diff --git a/Playground/babylon.d.txt b/Playground/babylon.d.txt index e0ae8f7f9da..cac2a7fcc73 100644 --- a/Playground/babylon.d.txt +++ b/Playground/babylon.d.txt @@ -158,7 +158,7 @@ declare module BABYLON { * Removes all the assets in the container from the scene */ removeAllFromScene(): void; - private _moveAssets(sourceAssets, targetAssets, keepAssets); + private _moveAssets; /** * Removes all the assets contained in the scene and adds them to the container. * @param keepAssets Set of assets to keep in the scene. (default: empty) @@ -696,10 +696,10 @@ declare module BABYLON { * this is easier to reference from here than from all the materials. */ /** - * Texture used in all pbr material as the reflection texture. - * As in the majority of the scene they are the same (exception for multi room and so on), - * this is easier to set here than in all the materials. - */ + * Texture used in all pbr material as the reflection texture. + * As in the majority of the scene they are the same (exception for multi room and so on), + * this is easier to set here than in all the materials. + */ environmentTexture: BaseTexture; /** @hidden */ protected _imageProcessingConfiguration: ImageProcessingConfiguration; @@ -1312,8 +1312,8 @@ protected readonly _isAlternateRenderingEnabled: boolean; * Gets the current geometry buffer associated to the scene. */ /** - * Sets the current geometry buffer for the scene. - */ + * Sets the current geometry buffer for the scene. + */ geometryBufferRenderer: Nullable; private _pickedDownMesh; private _pickedUpMesh; @@ -1335,7 +1335,7 @@ protected readonly _isAlternateRenderingEnabled: boolean; /** * Registers the transient components if needed. */ - private _registerTransientComponents(); + private _registerTransientComponents; /** * Add a component to the scene. * Note that the ccomponent could be registered on th next frame if this is called after @@ -1400,9 +1400,9 @@ protected readonly _isAlternateRenderingEnabled: boolean; */ readonly debugLayer: DebugLayer; /** - * Gets a boolean indicating if collisions are processed on a web worker - * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21 - */ + * Gets a boolean indicating if collisions are processed on a web worker + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21 + */ workerCollisions: boolean; /** * Gets the octree used to boost mesh selection (picking) @@ -1537,11 +1537,11 @@ protected readonly _isAlternateRenderingEnabled: boolean; getRenderId(): number; /** Call this function if you want to manually increment the render Id*/ incrementRenderId(): void; - private _updatePointerPosition(evt); - private _createUbo(); - private _createAlternateUbo(); - private _pickSpriteButKeepRay(originalPointerInfo, x, y, predicate?, fastCheck?, camera?); - private _setRayOnPointerInfo(pointerInfo); + private _updatePointerPosition; + private _createUbo; + private _createAlternateUbo; + private _pickSpriteButKeepRay; + private _setRayOnPointerInfo; /** * Use this method to simulate a pointer move on a mesh * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay @@ -1550,8 +1550,8 @@ protected readonly _isAlternateRenderingEnabled: boolean; * @returns the current scene */ simulatePointerMove(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene; - private _processPointerMove(pickResult, evt); - private _checkPrePointerObservable(pickResult, evt, type); + private _processPointerMove; + private _checkPrePointerObservable; /** * Use this method to simulate a pointer down on a mesh * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay @@ -1560,7 +1560,7 @@ protected readonly _isAlternateRenderingEnabled: boolean; * @returns the current scene */ simulatePointerDown(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene; - private _processPointerDown(pickResult, evt); + private _processPointerDown; /** * Use this method to simulate a pointer up on a mesh * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay @@ -1569,7 +1569,7 @@ protected readonly _isAlternateRenderingEnabled: boolean; * @returns the current scene */ simulatePointerUp(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene; - private _processPointerUp(pickResult, evt, clickInfo); + private _processPointerUp; /** * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down) * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default) @@ -1613,7 +1613,7 @@ protected readonly _isAlternateRenderingEnabled: boolean; * @param func defines the function to unregister */ unregisterAfterRender(func: () => void): void; - private _executeOnceBeforeRender(func); + private _executeOnceBeforeRender; /** * The provided function will run before render once and will be disposed afterwards. * A timeout delay can be provided so that the function will be executed in N ms. @@ -1727,12 +1727,12 @@ protected readonly _isAlternateRenderingEnabled: boolean; * Stops and removes all animations that have been applied to the scene */ stopAllAnimations(): void; - private _animate(); + private _animate; /** @hidden */ - private _processLateAnimationBindingsForMatrices(holder); - private _processLateAnimationBindingsForQuaternions(holder); - private _processLateAnimationBindings(); + private _processLateAnimationBindingsForMatrices; + private _processLateAnimationBindingsForQuaternions; + private _processLateAnimationBindings; /** @hidden */ /** @@ -2170,7 +2170,7 @@ protected readonly _isAlternateRenderingEnabled: boolean; * @return true if the data was successfully removed, false if it doesn't exist */ removeExternalData(key: string): boolean; - private _evaluateSubMesh(subMesh, mesh); + private _evaluateSubMesh; /** * Clear the processed materials smart array preventing retention point in material dispose. */ @@ -2207,8 +2207,8 @@ protected readonly _isAlternateRenderingEnabled: boolean; * @returns the current scene */ unfreezeActiveMeshes(): Scene; - private _evaluateActiveMeshes(); - private _activeMesh(sourceMesh, mesh); + private _evaluateActiveMeshes; + private _activeMesh; /** * Update the transform matrix to update from the current active camera * @param force defines a boolean used to force the update even if cache is up to date @@ -2221,29 +2221,29 @@ protected readonly _isAlternateRenderingEnabled: boolean; updateAlternateTransformMatrix(alternateCamera: Camera): void; /** @hidden */ - private _renderForCamera(camera, rigParent?); - private _processSubCameras(camera); - private _checkIntersections(); + private _renderForCamera; + private _processSubCameras; + private _checkIntersections; /** * Render the scene * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default) */ render(updateCameras?: boolean): void; - private _updateAudioParameters(); + private _updateAudioParameters; /** * Gets or sets if audio support is enabled * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music */ audioEnabled: boolean; - private _disableAudio(); - private _enableAudio(); + private _disableAudio; + private _enableAudio; /** * Gets or sets if audio will be output to headphones * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music */ headphone: boolean; - private _switchAudioModeForHeadphones(); - private _switchAudioModeForNormalSpeakers(); + private _switchAudioModeForHeadphones; + private _switchAudioModeForNormalSpeakers; /** * Creates a depth renderer a given camera which contains a depth map which can be used for post processing. * @param camera The camera to create the depth renderer on (default: scene's active camera) @@ -2353,9 +2353,9 @@ protected readonly _isAlternateRenderingEnabled: boolean; * @returns the current scene */ createPickingRayInCameraSpaceToRef(x: number, y: number, result: Ray, camera?: Camera): Scene; - private _internalPick(rayFunction, predicate?, fastCheck?); - private _internalMultiPick(rayFunction, predicate?); - private _internalPickSprites(ray, predicate?, fastCheck?, camera?); + private _internalPick; + private _internalMultiPick; + private _internalPickSprites; private _tempPickingRay; /** Launch a ray to try to pick a mesh in the scene * @param x position on screen @@ -2496,7 +2496,7 @@ protected readonly _isAlternateRenderingEnabled: boolean; * @returns a new VREXperienceHelper */ createDefaultVRExperience(webVROptions?: VRExperienceHelperOptions): VRExperienceHelper; - private _getByTags(list, tagsQuery, forEach?); + private _getByTags; /** * Get a list of meshes by tags * @param tagsQuery defines the tags query to use @@ -2743,8 +2743,8 @@ declare module BABYLON { * @param condition an optional determinant of action */ constructor( - /** the trigger, with or without parameters, for the action */ - triggerOptions: any, condition?: Condition); + /** the trigger, with or without parameters, for the action */ + triggerOptions: any, condition?: Condition); /** * Internal only * @hidden @@ -2828,9 +2828,9 @@ declare module BABYLON { /** The mesh that is currently pointed at (can be null) */ meshUnderPointer: Nullable; /** the original (browser) event that triggered the ActionEvent */ - sourceEvent: any; + sourceEvent?: any; /** additional data for the event */ - additionalData: any; + additionalData?: any; /** * Creates a new ActionEvent * @param source The mesh or sprite that triggered the action @@ -2841,18 +2841,18 @@ declare module BABYLON { * @param additionalData additional data for the event */ constructor( - /** The mesh or sprite that triggered the action */ - source: any, - /** The X mouse cursor position at the time of the event */ - pointerX: number, - /** The Y mouse cursor position at the time of the event */ - pointerY: number, - /** The mesh that is currently pointed at (can be null) */ - meshUnderPointer: Nullable, - /** the original (browser) event that triggered the ActionEvent */ - sourceEvent?: any, - /** additional data for the event */ - additionalData?: any); + /** The mesh or sprite that triggered the action */ + source: any, + /** The X mouse cursor position at the time of the event */ + pointerX: number, + /** The Y mouse cursor position at the time of the event */ + pointerY: number, + /** The mesh that is currently pointed at (can be null) */ + meshUnderPointer: Nullable, + /** the original (browser) event that triggered the ActionEvent */ + sourceEvent?: any, + /** additional data for the event */ + additionalData?: any); /** * Helper function to auto-create an ActionEvent from a source mesh. * @param source The source mesh that triggered the event @@ -3224,12 +3224,12 @@ declare module BABYLON { * @param operator the conditional operator, default ValueCondition.IsEqual */ constructor(actionManager: ActionManager, target: any, - /** path to specify the property of the target the conditional operator uses */ - propertyPath: string, - /** the value compared by the conditional operator against the current value of the property */ - value: any, - /** the conditional operator, default ValueCondition.IsEqual */ - operator?: number); + /** path to specify the property of the target the conditional operator uses */ + propertyPath: string, + /** the value compared by the conditional operator against the current value of the property */ + value: any, + /** the conditional operator, default ValueCondition.IsEqual */ + operator?: number); /** * Compares the given value with the property value for the specified conditional operator * @returns the result of the comparison @@ -3264,8 +3264,8 @@ declare module BABYLON { * @param predicate defines the predicate function used to validate the condition */ constructor(actionManager: ActionManager, - /** defines the predicate function used to validate the condition */ - predicate: () => boolean); + /** defines the predicate function used to validate the condition */ + predicate: () => boolean); /** * @returns the validity of the predicate condition */ @@ -3348,7 +3348,7 @@ declare module BABYLON { class PlayAnimationAction extends Action { from: number; to: number; - loop: boolean | undefined; + loop?: boolean | undefined; private _target; constructor(triggerOptions: any, target: any, from: number, to: number, loop?: boolean | undefined, condition?: Condition); @@ -3408,8 +3408,8 @@ declare module BABYLON { propertyPath: string; value: any; duration: number; - stopOtherAnimations: boolean | undefined; - onInterpolationDone: (() => void) | undefined; + stopOtherAnimations?: boolean | undefined; + onInterpolationDone?: (() => void) | undefined; private _target; private _effectiveTarget; private _property; @@ -3435,7 +3435,7 @@ declare module BABYLON { /** defines if the animation must loop (default is false) */ loopAnimation: boolean; /** defines a callback to call when animation ends if it is not looping */ - onAnimationEnd: (() => void) | null | undefined; + onAnimationEnd?: (() => void) | null | undefined; private _localDelayOffset; private _pausedDelay; private _runtimeAnimations; @@ -3486,16 +3486,16 @@ declare module BABYLON { * @param animations defines a group of animation to add to the new Animatable */ constructor(scene: Scene, - /** defines the target object */ - target: any, - /** defines the starting frame number (default is 0) */ - fromFrame?: number, - /** defines the ending frame number (default is 100) */ - toFrame?: number, - /** defines if the animation must loop (default is false) */ - loopAnimation?: boolean, speedRatio?: number, - /** defines a callback to call when animation ends if it is not looping */ - onAnimationEnd?: (() => void) | null | undefined, animations?: Animation[]); + /** defines the target object */ + target: any, + /** defines the starting frame number (default is 0) */ + fromFrame?: number, + /** defines the ending frame number (default is 100) */ + toFrame?: number, + /** defines if the animation must loop (default is false) */ + loopAnimation?: boolean, speedRatio?: number, + /** defines a callback to call when animation ends if it is not looping */ + onAnimationEnd?: (() => void) | null | undefined, animations?: Animation[]); /** * Synchronize and normalize current Animatable with a source Animatable * This is useful when using animation weights and when animations are not of the same length @@ -3554,7 +3554,7 @@ declare module BABYLON { * Restart the animation */ restart(): void; - private _raiseOnAnimationEnd(); + private _raiseOnAnimationEnd; /** * Stop and delete the current animation * @param animationName defines a string used to only stop some of the runtime animations instead of all @@ -3589,12 +3589,12 @@ declare module BABYLON { * @param to The ending frame of the animation */ constructor( - /**The name of the animation range**/ - name: string, - /**The starting frame of the animation */ - from: number, - /**The ending frame of the animation*/ - to: number); + /**The name of the animation range**/ + name: string, + /**The starting frame of the animation */ + from: number, + /**The ending frame of the animation*/ + to: number); /** * Makes a copy of the animation range * @returns A copy of the animation range @@ -3610,7 +3610,7 @@ declare module BABYLON { /** The event to perform when triggered **/ action: () => void; /** Specifies if the event should be triggered only once**/ - onlyOnce: boolean | undefined; + onlyOnce?: boolean | undefined; /** * Specifies if the animation event is done */ @@ -3622,12 +3622,12 @@ declare module BABYLON { * @param onlyOnce Specifies if the event should be triggered only once */ constructor( - /** The frame for which the event is triggered **/ - frame: number, - /** The event to perform when triggered **/ - action: () => void, - /** Specifies if the event should be triggered only once**/ - onlyOnce?: boolean | undefined); + /** The frame for which the event is triggered **/ + frame: number, + /** The event to perform when triggered **/ + action: () => void, + /** Specifies if the event should be triggered only once**/ + onlyOnce?: boolean | undefined); /** @hidden */ } @@ -3681,12 +3681,12 @@ declare module BABYLON { * Ensures that the value is limited between zero and one * @returns This path cursor */ - private ensureLimits(); + private ensureLimits; /** * Runs onchange callbacks on change (used by the animation engine) * @returns This path cursor */ - private raiseOnChange(); + private raiseOnChange; /** * Executes a function on change * @param f A path cursor onchange callback @@ -3726,7 +3726,7 @@ declare module BABYLON { /** * Do not interpolate between keys and use the start key value only. Tangents are ignored */ - STEP = 1, + STEP = 1 } /** * Class used to store any kind of animation @@ -3741,9 +3741,9 @@ declare module BABYLON { /**The data type of the animation */ dataType: number; /**The loop mode of the animation */ - loopMode: number | undefined; + loopMode?: number | undefined; /**Specifies if blending should be enabled */ - enableBlending: boolean | undefined; + enableBlending?: boolean | undefined; /** * Use matrix interpolation instead of using direct key value when animating matrices */ @@ -3871,18 +3871,18 @@ private static _PrepareAnimation(name: string, targetProperty: string, framePerS * @param enableBlendings Specifies if blending should be enabled */ constructor( - /**Name of the animation */ - name: string, - /**Property to animate */ - targetProperty: string, - /**The frames per second of the animation */ - framePerSecond: number, - /**The data type of the animation */ - dataType: number, - /**The loop mode of the animation */ - loopMode?: number | undefined, - /**Specifies if blending should be enabled */ - enableBlending?: boolean | undefined); + /**Name of the animation */ + name: string, + /**Property to animate */ + targetProperty: string, + /**The frames per second of the animation */ + framePerSecond: number, + /**The data type of the animation */ + dataType: number, + /**The loop mode of the animation */ + loopMode?: number | undefined, + /**Specifies if blending should be enabled */ + enableBlending?: boolean | undefined); /** * Converts the animation to a string * @param fullDetails support for multiple levels of logging within scene loading @@ -4201,8 +4201,8 @@ declare module BABYLON { * Gets or sets the speed ratio to use for all animations */ /** - * Gets or sets the speed ratio to use for all animations - */ + * Gets or sets the speed ratio to use for all animations + */ speedRatio: number; /** * Gets the targeted animations for this animation group @@ -4282,7 +4282,7 @@ declare module BABYLON { * Dispose all associated resources */ dispose(): void; - private _checkAnimationGroupEnded(animatable); + private _checkAnimationGroupEnded; } } @@ -4513,19 +4513,19 @@ declare module BABYLON { * @param highLimitValue The high limit value * @returns The interpolated value */ - private _interpolate(currentFrame, repeatCount, loopMode?, offsetValue?, highLimitValue?); + private _interpolate; /** * Apply the interpolated value to the target * @param currentValue defines the value computed by the animation * @param weight defines the weight to apply to this value (Defaults to 1.0) */ setValue(currentValue: any, weight?: number): void; - private _setValue(target, currentValue, weight, targetIndex?); + private _setValue; /** * Gets the loop pmode of the runtime animation * @returns Loop Mode */ - private _getCorrectLoopMode(); + private _getCorrectLoopMode; /** * Move the current animation to a given frame * @param frame defines the frame to move to @@ -4659,8 +4659,8 @@ declare module BABYLON { isOGGsupported: boolean; readonly audioContext: Nullable; constructor(); - private _unlockiOSaudio(); - private _initializeAudioContext(); + private _unlockiOSaudio; + private _initializeAudioContext; dispose(): void; getGlobalVolume(): number; setGlobalVolume(newVolume: number): void; @@ -4721,14 +4721,14 @@ declare module BABYLON { constructor(name: string, urlOrArrayBuffer: any, scene: Scene, readyToPlayCallback?: Nullable<() => void>, options?: any); dispose(): void; isReady(): boolean; - private _soundLoaded(audioData); + private _soundLoaded; setAudioBuffer(audioBuffer: AudioBuffer): void; updateOptions(options: any): void; - private _createSpatialParameters(); - private _updateSpatialParameters(); + private _createSpatialParameters; + private _updateSpatialParameters; switchPanningModelToHRTF(): void; switchPanningModelToEqualPower(): void; - private _switchPanningModel(); + private _switchPanningModel; connectToSoundTrackAudioNode(soundTrackAudioNode: AudioNode): void; /** * Transform this sound into a directional source @@ -4739,7 +4739,7 @@ declare module BABYLON { setDirectionalCone(coneInnerAngle: number, coneOuterAngle: number, coneOuterGain: number): void; setPosition(newPosition: Vector3): void; setLocalDirectionToMesh(newLocalDirection: Vector3): void; - private _updateDirection(); + private _updateDirection; updateDistanceFromListener(): void; setAttenuationFunction(callback: (currentVolume: number, currentDistance: number, maxDistance: number, refDistance: number, rolloffFactor: number) => number): void; /** @@ -4748,7 +4748,7 @@ declare module BABYLON { * @param offset (optional) Start the sound setting it at a specific time */ play(time?: number, offset?: number): void; - private _onended(); + private _onended; /** * Stop the sound * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default. @@ -4760,7 +4760,7 @@ declare module BABYLON { getVolume(): number; attachToMesh(meshToConnectTo: AbstractMesh): void; detachFromMesh(): void; - private _onRegisterAfterWorldMatrixUpdate(node); + private _onRegisterAfterWorldMatrixUpdate; clone(): Nullable; getAudioBuffer(): AudioBuffer | null; serialize(): any; @@ -4779,7 +4779,7 @@ declare module BABYLON { private _options; private _isInitialized; constructor(scene: Scene, options?: any); - private _initializeSoundTrackAudioGraph(); + private _initializeSoundTrackAudioGraph; dispose(): void; AddSound(sound: Sound): void; RemoveSound(sound: Sound): void; @@ -4893,10 +4893,10 @@ declare module BABYLON { * @param index defines index of the bone in the hiearchy */ constructor( - /** - * defines the bone name - */ - name: string, skeleton: Skeleton, parentBone?: Nullable, localMatrix?: Nullable, restPose?: Nullable, baseMatrix?: Nullable, index?: Nullable); + /** + * defines the bone name + */ + name: string, skeleton: Skeleton, parentBone?: Nullable, localMatrix?: Nullable, restPose?: Nullable, baseMatrix?: Nullable, index?: Nullable); /** * Gets the parent skeleton * @returns a skeleton @@ -4959,8 +4959,8 @@ declare module BABYLON { * Gets the animation properties override */ readonly animationPropertiesOverride: Nullable; - private _decompose(); - private _compose(); + private _decompose; + private _compose; /** * Update the base and local matrices * @param matrix defines the new base or local matrix @@ -4974,8 +4974,8 @@ declare module BABYLON { * Flag the bone as dirty (Forcing it to update everything) */ markAsDirty(): void; - private _markAsDirtyAndCompose(); - private _markAsDirtyAndDecompose(); + private _markAsDirtyAndCompose; + private _markAsDirtyAndDecompose; /** * Copy an animation range from another bone * @param source defines the source bone @@ -5075,8 +5075,8 @@ declare module BABYLON { * @param mesh The mesh that this bone is attached to. This is only used in world space */ setRotationMatrix(rotMat: Matrix, space?: Space, mesh?: AbstractMesh): void; - private _rotateWithMatrix(rmat, space?, mesh?); - private _getNegativeRotationToRef(rotMatInv, mesh?); + private _rotateWithMatrix; + private _getNegativeRotationToRef; /** * Get the position of the bone in local or world space * @param space The space that the returned position is in @@ -5270,7 +5270,7 @@ declare module BABYLON { maxAngle?: number; slerpAmount?: number; }); - private _setMaxAngle(ang); + private _setMaxAngle; /** * Force the controller to update the bones */ @@ -5394,9 +5394,9 @@ declare module BABYLON { * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()) */ update(): void; - private _getAngleDiff(ang1, ang2); - private _getAngleBetween(ang1, ang2); - private _isAngleBetween(ang, ang1, ang2); + private _getAngleDiff; + private _getAngleBetween; + private _isAngleBetween; } } @@ -5455,10 +5455,10 @@ declare module BABYLON { * @param scene defines the hosting scene */ constructor( - /** defines the skeleton name */ - name: string, - /** defines the skeleton Id */ - id: string, scene: Scene); + /** defines the skeleton name */ + name: string, + /** defines the skeleton Id */ + id: string, scene: Scene); /** * Gets the list of transform matrices to send to shaders (one matrix per bone) * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true) @@ -5519,7 +5519,7 @@ declare module BABYLON { * Forces the skeleton to go to rest pose */ returnToRest(): void; - private _getHighestAnimationFrame(); + private _getHighestAnimationFrame; /** * Begin a specific animation range * @param name defines the name of the range to start @@ -5589,7 +5589,323 @@ declare module BABYLON { * Sorts bones per internal index */ sortBones(): void; - private _sortBones(index, bones, visited); + private _sortBones; + } +} + +declare module BABYLON { + class Collider { + /** Define if a collision was found */ + collisionFound: boolean; + /** + * Define last intersection point in local space + */ + intersectionPoint: Vector3; + /** + * Define last collided mesh + */ + collidedMesh: Nullable; + private _collisionPoint; + private _planeIntersectionPoint; + private _tempVector; + private _tempVector2; + private _tempVector3; + private _tempVector4; + private _edge; + private _baseToVertex; + private _destinationPoint; + private _slidePlaneNormal; + private _displacementVector; + + + private _velocity; + private _basePoint; + private _epsilon; + + + private _velocityWorld; + private _normalizedVelocity; + + + private _nearestDistance; + private _collisionMask; + collisionMask: number; + /** + * Gets the plane normal used to compute the sliding response (in local space) + */ + readonly slidePlaneNormal: Vector3; + + + + + + + } +} + +declare module BABYLON { + var CollisionWorker: string; + interface ICollisionCoordinator { + getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: Nullable, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable) => void, collisionIndex: number): void; + init(scene: Scene): void; + destroy(): void; + onMeshAdded(mesh: AbstractMesh): void; + onMeshUpdated(mesh: AbstractMesh): void; + onMeshRemoved(mesh: AbstractMesh): void; + onGeometryAdded(geometry: Geometry): void; + onGeometryUpdated(geometry: Geometry): void; + onGeometryDeleted(geometry: Geometry): void; + } + interface SerializedMesh { + id: string; + name: string; + uniqueId: number; + geometryId: Nullable; + sphereCenter: Array; + sphereRadius: number; + boxMinimum: Array; + boxMaximum: Array; + worldMatrixFromCache: any; + subMeshes: Array; + checkCollisions: boolean; + } + interface SerializedSubMesh { + position: number; + verticesStart: number; + verticesCount: number; + indexStart: number; + indexCount: number; + hasMaterial: boolean; + sphereCenter: Array; + sphereRadius: number; + boxMinimum: Array; + boxMaximum: Array; + } + /** + * Interface describing the value associated with a geometry + */ + interface SerializedGeometry { + /** + * Defines the unique ID of the geometry + */ + id: string; + /** + * Defines the array containing the positions + */ + positions: Float32Array; + /** + * Defines the array containing the indices + */ + indices: Uint32Array; + /** + * Defines the array containing the normals + */ + normals: Float32Array; + } + interface BabylonMessage { + taskType: WorkerTaskType; + payload: InitPayload | CollidePayload | UpdatePayload; + } + interface SerializedColliderToWorker { + position: Array; + velocity: Array; + radius: Array; + } + /** Defines supported task for worker process */ + enum WorkerTaskType { + /** Initialization */ + INIT = 0, + /** Update of geometry */ + UPDATE = 1, + /** Evaluate collision */ + COLLIDE = 2 + } + interface WorkerReply { + error: WorkerReplyType; + taskType: WorkerTaskType; + payload?: any; + } + interface CollisionReplyPayload { + newPosition: Array; + collisionId: number; + collidedMeshUniqueId: number; + } + interface InitPayload { + } + interface CollidePayload { + collisionId: number; + collider: SerializedColliderToWorker; + maximumRetry: number; + excludedMeshUniqueId: Nullable; + } + interface UpdatePayload { + updatedMeshes: { + [n: number]: SerializedMesh; + }; + updatedGeometries: { + [s: string]: SerializedGeometry; + }; + removedMeshes: Array; + removedGeometries: Array; + } + /** Defines kind of replies returned by worker */ + enum WorkerReplyType { + /** Success */ + SUCCESS = 0, + /** Unkown error */ + UNKNOWN_ERROR = 1 + } + class CollisionCoordinatorWorker implements ICollisionCoordinator { + private _scene; + private _scaledPosition; + private _scaledVelocity; + private _collisionsCallbackArray; + private _init; + private _runningUpdated; + private _worker; + private _addUpdateMeshesList; + private _addUpdateGeometriesList; + private _toRemoveMeshesArray; + private _toRemoveGeometryArray; + constructor(); + static SerializeMesh: (mesh: AbstractMesh) => SerializedMesh; + static SerializeGeometry: (geometry: Geometry) => SerializedGeometry; + getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable) => void, collisionIndex: number): void; + init(scene: Scene): void; + destroy(): void; + onMeshAdded(mesh: AbstractMesh): void; + onMeshUpdated: (transformNode: TransformNode) => void; + onMeshRemoved(mesh: AbstractMesh): void; + onGeometryAdded(geometry: Geometry): void; + onGeometryUpdated: (geometry: Geometry) => void; + onGeometryDeleted(geometry: Geometry): void; + private _afterRender; + private _onMessageFromWorker; + } + class CollisionCoordinatorLegacy implements ICollisionCoordinator { + private _scene; + private _scaledPosition; + private _scaledVelocity; + private _finalPosition; + getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable) => void, collisionIndex: number): void; + init(scene: Scene): void; + destroy(): void; + onMeshAdded(mesh: AbstractMesh): void; + onMeshUpdated(mesh: AbstractMesh): void; + onMeshRemoved(mesh: AbstractMesh): void; + onGeometryAdded(geometry: Geometry): void; + onGeometryUpdated(geometry: Geometry): void; + onGeometryDeleted(geometry: Geometry): void; + private _collideWithWorld; + } +} + +declare function importScripts(...urls: string[]): void; +declare const safePostMessage: any; +declare module BABYLON { + var WorkerIncluded: boolean; + class CollisionCache { + private _meshes; + private _geometries; + getMeshes(): { + [n: number]: SerializedMesh; + }; + getGeometries(): { + [s: number]: SerializedGeometry; + }; + getMesh(id: any): SerializedMesh; + addMesh(mesh: SerializedMesh): void; + removeMesh(uniqueId: number): void; + getGeometry(id: string): SerializedGeometry; + addGeometry(geometry: SerializedGeometry): void; + removeGeometry(id: string): void; + } + class CollideWorker { + collider: Collider; + private _collisionCache; + private finalPosition; + private collisionsScalingMatrix; + private collisionTranformationMatrix; + constructor(collider: Collider, _collisionCache: CollisionCache, finalPosition: Vector3); + collideWithWorld(position: Vector3, velocity: Vector3, maximumRetry: number, excludedMeshUniqueId: Nullable): void; + private checkCollision; + private processCollisionsForSubMeshes; + private collideForSubMesh; + private checkSubmeshCollision; + } + interface ICollisionDetector { + onInit(payload: InitPayload): void; + onUpdate(payload: UpdatePayload): void; + onCollision(payload: CollidePayload): void; + } + class CollisionDetectorTransferable implements ICollisionDetector { + private _collisionCache; + onInit(payload: InitPayload): void; + onUpdate(payload: UpdatePayload): void; + onCollision(payload: CollidePayload): void; + } +} + +declare module BABYLON { + class IntersectionInfo { + bu: Nullable; + bv: Nullable; + distance: number; + faceId: number; + subMeshId: number; + constructor(bu: Nullable, bv: Nullable, distance: number); + } + /** + * Information about the result of picking within a scene + * See https://doc.babylonjs.com/babylon101/picking_collisions + */ + class PickingInfo { + /** + * If the pick collided with an object + */ + hit: boolean; + /** + * Distance away where the pick collided + */ + distance: number; + /** + * The location of pick collision + */ + pickedPoint: Nullable; + /** + * The mesh corrisponding the the pick collision + */ + pickedMesh: Nullable; + /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/ + bu: number; + /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/ + bv: number; + /** The id of the face on the mesh that was picked */ + faceId: number; + /** Id of the the submesh that was picked */ + subMeshId: number; + /** If a sprite was picked, this will be the sprite the pick collided with */ + pickedSprite: Nullable; + /** + * If a mesh was used to do the picking (eg. 6dof controller) this will be populated. + */ + originMesh: Nullable; + /** + * The ray that was used to perform the picking. + */ + ray: Nullable; + /** + * Gets the normal corrispodning to the face the pick collided with + * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false) + * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map + * @returns The normal corrispodning to the face the pick collided with + */ + getNormal(useWorldCoordinates?: boolean, useVerticesNormals?: boolean): Nullable; + /** + * Gets the texture coordinates of where the pick occured + * @returns the vector containing the coordnates of the texture + */ + getTextureCoordinates(): Nullable; } } @@ -5731,7 +6047,7 @@ declare module BABYLON { intersectsPlane(plane: Plane): Nullable; intersectsMesh(mesh: AbstractMesh, fastCheck?: boolean): PickingInfo; intersectsMeshes(meshes: Array, fastCheck?: boolean, results?: Array): Array; - private _comparePickingInfo(pickingInfoA, pickingInfoB); + private _comparePickingInfo; private static smallnum; private static rayl; /** @@ -5758,6 +6074,331 @@ declare module BABYLON { } } +/** + * Module Debug contains the (visual) components to debug a scene correctly + */ +declare module BABYLON.Debug { + /** + * The Axes viewer will show 3 axes in a specific point in space + */ + class AxesViewer { + private _xline; + private _yline; + private _zline; + private _xmesh; + private _ymesh; + private _zmesh; + /** + * Gets the hosting scene + */ + scene: Nullable; + /** + * Gets or sets a number used to scale line length + */ + scaleLines: number; + /** + * Creates a new AxesViewer + * @param scene defines the hosting scene + * @param scaleLines defines a number used to scale line length (1 by default) + */ + constructor(scene: Scene, scaleLines?: number); + /** + * Force the viewer to update + * @param position defines the position of the viewer + * @param xaxis defines the x axis of the viewer + * @param yaxis defines the y axis of the viewer + * @param zaxis defines the z axis of the viewer + */ + update(position: Vector3, xaxis: Vector3, yaxis: Vector3, zaxis: Vector3): void; + /** Releases resources */ + dispose(): void; + } +} + +declare module BABYLON.Debug { + /** + * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh + * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8 + */ + class BoneAxesViewer extends AxesViewer { + /** + * Gets or sets the target mesh where to display the axes viewer + */ + mesh: Nullable; + /** + * Gets or sets the target bone where to display the axes viewer + */ + bone: Nullable; + /** Gets current position */ + pos: Vector3; + /** Gets direction of X axis */ + xaxis: Vector3; + /** Gets direction of Y axis */ + yaxis: Vector3; + /** Gets direction of Z axis */ + zaxis: Vector3; + /** + * Creates a new BoneAxesViewer + * @param scene defines the hosting scene + * @param bone defines the target bone + * @param mesh defines the target mesh + * @param scaleLines defines a scaling factor for line length (1 by default) + */ + constructor(scene: Scene, bone: Bone, mesh: Mesh, scaleLines?: number); + /** + * Force the viewer to update + */ + update(): void; + /** Releases resources */ + dispose(): void; + } +} + +declare module BABYLON { + class DebugLayer { + private _scene; + static InspectorURL: string; + private _inspector; + private BJSINSPECTOR; + onPropertyChangedObservable: Observable<{ + object: any; + property: string; + value: any; + initialValue: any; + }>; + constructor(scene: Scene); + /** Creates the inspector window. */ + private _createInspector; + isVisible(): boolean; + hide(): void; + /** + * + * Launch the debugLayer. + * + * initialTab: + * | Value | Tab Name | + * | --- | --- | + * | 0 | Scene | + * | 1 | Console | + * | 2 | Stats | + * | 3 | Textures | + * | 4 | Mesh | + * | 5 | Light | + * | 6 | Material | + * | 7 | GLTF | + * | 8 | GUI | + * | 9 | Physics | + * | 10 | Camera | + * | 11 | Audio | + * + */ + show(config?: { + popup?: boolean; + initialTab?: number; + parentElement?: HTMLElement; + newColors?: { + backgroundColor?: string; + backgroundColorLighter?: string; + backgroundColorLighter2?: string; + backgroundColorLighter3?: string; + color?: string; + colorTop?: string; + colorBot?: string; + }; + }): void; + /** + * Gets the active tab + * @return the index of the active tab or -1 if the inspector is hidden + */ + getActiveTab(): number; + } +} + +declare module BABYLON.Debug { + /** + * Used to show the physics impostor around the specific mesh + */ + class PhysicsViewer { + /** @hidden */ + protected _impostors: Array>; + /** @hidden */ + protected _meshes: Array>; + /** @hidden */ + protected _scene: Nullable; + /** @hidden */ + protected _numMeshes: number; + /** @hidden */ + protected _physicsEnginePlugin: Nullable; + private _renderFunction; + private _debugBoxMesh; + private _debugSphereMesh; + private _debugMaterial; + /** + * Creates a new PhysicsViewer + * @param scene defines the hosting scene + */ + constructor(scene: Scene); + /** @hidden */ + protected _updateDebugMeshes(): void; + /** + * Renders a specified physic impostor + * @param impostor defines the impostor to render + */ + showImpostor(impostor: PhysicsImpostor): void; + /** + * Hides a specified physic impostor + * @param impostor defines the impostor to hide + */ + hideImpostor(impostor: Nullable): void; + private _getDebugMaterial; + private _getDebugBoxMesh; + private _getDebugSphereMesh; + private _getDebugMesh; + /** Releases all resources */ + dispose(): void; + } +} + +declare module BABYLON { + class RayHelper { + ray: Nullable; + private _renderPoints; + private _renderLine; + private _renderFunction; + private _scene; + private _updateToMeshFunction; + private _attachedToMesh; + private _meshSpaceDirection; + private _meshSpaceOrigin; + static CreateAndShow(ray: Ray, scene: Scene, color: Color3): RayHelper; + constructor(ray: Ray); + show(scene: Scene, color?: Color3): void; + hide(): void; + private _render; + attachToMesh(mesh: AbstractMesh, meshSpaceDirection?: Vector3, meshSpaceOrigin?: Vector3, length?: number): void; + detachFromMesh(): void; + private _updateToMesh; + dispose(): void; + } +} + +declare module BABYLON.Debug { + /** + * Class used to render a debug view of a given skeleton + * @see http://www.babylonjs-playground.com/#1BZJVJ#8 + */ + class SkeletonViewer { + /** defines the skeleton to render */ + skeleton: Skeleton; + /** defines the mesh attached to the skeleton */ + mesh: AbstractMesh; + /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */ + autoUpdateBonesMatrices: boolean; + /** defines the rendering group id to use with the viewer */ + renderingGroupId: number; + /** Gets or sets the color used to render the skeleton */ + color: Color3; + private _scene; + private _debugLines; + private _debugMesh; + private _isEnabled; + private _renderFunction; + /** + * Creates a new SkeletonViewer + * @param skeleton defines the skeleton to render + * @param mesh defines the mesh attached to the skeleton + * @param scene defines the hosting scene + * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) + * @param renderingGroupId defines the rendering group id to use with the viewer + */ + constructor( + /** defines the skeleton to render */ + skeleton: Skeleton, + /** defines the mesh attached to the skeleton */ + mesh: AbstractMesh, scene: Scene, + /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */ + autoUpdateBonesMatrices?: boolean, + /** defines the rendering group id to use with the viewer */ + renderingGroupId?: number); + /** Gets or sets a boolean indicating if the viewer is enabled */ + isEnabled: boolean; + private _getBonePosition; + private _getLinesForBonesWithLength; + private _getLinesForBonesNoLength; + /** Update the viewer to sync with current skeleton state */ + update(): void; + /** Release associated resources */ + dispose(): void; + } +} + +declare module BABYLON { + class KeyboardEventTypes { +private static _KEYDOWN: number; +private static _KEYUP: number; + static readonly KEYDOWN: number; + static readonly KEYUP: number; + } + class KeyboardInfo { + type: number; + event: KeyboardEvent; + constructor(type: number, event: KeyboardEvent); + } + /** + * This class is used to store keyboard related info for the onPreKeyboardObservable event. + * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable + */ + class KeyboardInfoPre extends KeyboardInfo { + constructor(type: number, event: KeyboardEvent); + skipOnPointerObservable: boolean; + } +} + +declare module BABYLON { + class PointerEventTypes { +private static _POINTERDOWN: number; +private static _POINTERUP: number; +private static _POINTERMOVE: number; +private static _POINTERWHEEL: number; +private static _POINTERPICK: number; +private static _POINTERTAP: number; +private static _POINTERDOUBLETAP: number; + static readonly POINTERDOWN: number; + static readonly POINTERUP: number; + static readonly POINTERMOVE: number; + static readonly POINTERWHEEL: number; + static readonly POINTERPICK: number; + static readonly POINTERTAP: number; + static readonly POINTERDOUBLETAP: number; + } + class PointerInfoBase { + type: number; + event: PointerEvent | MouseWheelEvent; + constructor(type: number, event: PointerEvent | MouseWheelEvent); + } + /** + * This class is used to store pointer related info for the onPrePointerObservable event. + * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable + */ + class PointerInfoPre extends PointerInfoBase { + /** + * Ray from a pointer if availible (eg. 6dof controller) + */ + ray: Nullable; + constructor(type: number, event: PointerEvent | MouseWheelEvent, localX: number, localY: number); + localPosition: Vector2; + skipOnPointerObservable: boolean; + } + /** + * This type contains all the data related to a pointer event in Babylon.js. + * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class. + */ + class PointerInfo extends PointerInfoBase { + pickInfo: Nullable; + constructor(type: number, event: PointerEvent | MouseWheelEvent, pickInfo: Nullable); + } +} + declare module BABYLON { /** * Interface for attribute information associated with buffer instanciation @@ -6434,10 +7075,10 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false) */ constructor(canvasOrContext: Nullable, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio?: boolean); - private _rebuildInternalTextures(); - private _rebuildEffects(); - private _rebuildBuffers(); - private _initGLContext(); + private _rebuildInternalTextures; + private _rebuildEffects; + private _rebuildBuffers; + private _initGLContext; /** * Gets version of the current webGL context */ @@ -6446,7 +7087,7 @@ private static _TextureLoaders: IInternalTextureLoader[]; * Returns true if the stencil buffer has been enabled through the creation option of the context. */ readonly isStencilEnable: boolean; - private _prepareWorkingCanvas(); + private _prepareWorkingCanvas; /** * Reset the texture cache to empty state */ @@ -6757,7 +7398,7 @@ private static _TextureLoaders: IInternalTextureLoader[]; */ disableVR(): void; private _onVRFullScreenTriggered; - private _getVRDisplaysAsync(); + private _getVRDisplaysAsync; /** * Binds the frame buffer to the specified texture. * @param texture The texture to render to or null for the default canvas @@ -6769,7 +7410,7 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @param lodLevel defines le lod level to bind to the frame buffer */ bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, depthStencilTexture?: InternalTexture, lodLevel?: number): void; - private bindUnboundFramebuffer(framebuffer); + private bindUnboundFramebuffer; /** * Unbind the current render target texture from the webGL context * @param texture defines the render target texture to unbind @@ -6821,7 +7462,7 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @param count defines the size of the data to update */ updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: FloatArray, offset?: number, count?: number): void; - private _resetVertexBufferBinding(); + private _resetVertexBufferBinding; /** * Creates a vertex buffer * @param data the data for the vertex buffer @@ -6849,7 +7490,7 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @param byteLength the byte length of the data */ updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void; - private _resetIndexBufferBinding(); + private _resetIndexBufferBinding; /** * Creates a new index buffer * @param indices defines the content of the index buffer @@ -6880,16 +7521,16 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @param index defines the index where to bind the block */ bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void; - private bindIndexBuffer(buffer); - private bindBuffer(buffer, target); + private bindIndexBuffer; + private bindBuffer; /** * update the bound buffer with the given data * @param data defines the data to update */ updateArrayBuffer(data: Float32Array): void; - private _vertexAttribPointer(buffer, indx, size, type, normalized, stride, offset); - private _bindIndexBufferWithCache(indexBuffer); - private _bindVertexBuffersAttributes(vertexBuffers, effect); + private _vertexAttribPointer; + private _bindIndexBufferWithCache; + private _bindVertexBuffersAttributes; /** * Records a vertex array object * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects @@ -6917,7 +7558,7 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @param effect defines the effect associated with the vertex buffer */ bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void; - private _unbindVertexArrayObject(); + private _unbindVertexArrayObject; /** * Bind a list of vertex buffers to the webGL context * @param vertexBuffers defines the list of vertex buffers to bind @@ -6999,7 +7640,7 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @param instancesCount defines the number of instances to draw (if instanciation is enabled) */ drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void; - private _drawMode(fillMode); + private _drawMode; /** @hidden */ /** @hidden */ @@ -7018,8 +7659,8 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @returns the new Effect */ createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect; - private _compileShader(source, type, defines, shaderVersion); - private _compileRawShader(source, type); + private _compileShader; + private _compileRawShader; /** * Directly creates a webGL program * @param vertexCode defines the vertex shader code to use @@ -7039,7 +7680,7 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @returns the new webGL program */ createShaderProgram(vertexCode: string, fragmentCode: string, defines: Nullable, context?: WebGLRenderingContext, transformFeedbackVaryings?: Nullable): WebGLProgram; - private _createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings?); + private _createShaderProgram; /** * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names * @param shaderProgram defines the webGL program to use @@ -7312,9 +7953,9 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @returns The extension selected. */ setTextureFormatToUse(formatsAvailable: Array): Nullable; - private _getSamplingParameters(samplingMode, generateMipMaps); - private _partialLoadImg(url, index, loadedImages, scene, onfinish, onErrorCallBack?); - private _cascadeLoadImgs(rootUrl, scene, onfinish, files, onError?); + private _getSamplingParameters; + private _partialLoadImg; + private _cascadeLoadImgs; /** @hidden */ /** @@ -7337,7 +7978,7 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @returns a InternalTexture for assignment back into BABYLON.Texture */ createTexture(urlArg: Nullable, noMipmap: boolean, invertY: boolean, scene: Nullable, samplingMode?: number, onLoad?: Nullable<() => void>, onError?: Nullable<(message: string, exception: any) => void>, buffer?: Nullable, fallback?: Nullable, format?: Nullable, forcedExtension?: Nullable): InternalTexture; - private _rescaleTexture(source, destination, scene, internalFormat, onComplete); + private _rescaleTexture; /** * Update a raw texture * @param texture defines the texture to update @@ -7406,7 +8047,7 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @param comparisonFunction The comparison function to set, 0 if no comparison required */ updateTextureComparisonFunction(texture: InternalTexture, comparisonFunction: number): void; - private _setupDepthStencilTexture(internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction); + private _setupDepthStencilTexture; /** * Creates a depth stencil texture. * This is only available in WebGL 2 or with the depth texture extension available. @@ -7425,7 +8066,7 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @param options The options defining the texture. * @returns The texture */ - private _createDepthStencilTexture(size, options); + private _createDepthStencilTexture; /** * Creates a depth stencil cube texture. * This is only available in WebGL 2. @@ -7433,7 +8074,7 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @param options The options defining the cube texture. * @returns The cube texture */ - private _createDepthStencilCubeTexture(size, options); + private _createDepthStencilCubeTexture; /** * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture. * @param renderTarget The render target to set the frame buffer for @@ -7457,7 +8098,7 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @returns the cube texture as an InternalTexture */ createMultipleRenderTarget(size: any, options: IMultiRenderTargetOptions): InternalTexture[]; - private _setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height, samples?); + private _setupFramebufferDepthAttachments; /** * Updates the sample count of a render target texture * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets @@ -7590,25 +8231,25 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @returns a new raw 3D texture (stored in an InternalTexture) */ createRawTexture3D(data: Nullable, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression?: Nullable, textureType?: number): InternalTexture; - private _prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode); - private _prepareWebGLTexture(texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode?); - private _convertRGBtoRGBATextureData(rgbData, width, height, textureType); + private _prepareWebGLTextureContinuation; + private _prepareWebGLTexture; + private _convertRGBtoRGBATextureData; /** @hidden */ /** @hidden */ - private setProgram(program); + private setProgram; private _boundUniforms; /** * Binds an effect to the webGL context * @param effect defines the effect to bind */ bindSamplers(effect: Effect): void; - private _moveBoundTextureOnTop(internalTexture); - private _getCorrectTextureChannel(channel, internalTexture); - private _linkTrackers(previous, next); - private _removeDesignatedSlot(internalTexture); - private _activateCurrentTexture(); + private _moveBoundTextureOnTop; + private _getCorrectTextureChannel; + private _linkTrackers; + private _removeDesignatedSlot; + private _activateCurrentTexture; /** @hidden */ protected _bindTextureDirectly(target: number, texture: Nullable, forTextureDataUpdate?: boolean, force?: boolean): boolean; /** @hidden */ @@ -7643,9 +8284,9 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @param texture The render target texture containing the depth stencil texture to apply */ setDepthStencilTexture(channel: number, uniform: Nullable, texture: Nullable): void; - private _bindSamplerUniformToChannel(sourceSlot, destination); - private _getTextureWrapMode(mode); - private _setTexture(channel, texture, isPartOfTextureArray?, depthStencilTexture?); + private _bindSamplerUniformToChannel; + private _getTextureWrapMode; + private _setTexture; /** * Sets an array of texture to the webGL context * @param channel defines the channel where the texture array must be set @@ -7655,8 +8296,8 @@ private static _TextureLoaders: IInternalTextureLoader[]; setTextureArray(channel: number, uniform: Nullable, textures: BaseTexture[]): void; /** @hidden */ - private _setTextureParameterFloat(target, parameter, value, texture); - private _setTextureParameterInteger(target, parameter, value, texture?); + private _setTextureParameterFloat; + private _setTextureParameterInteger; /** * Reads pixels from the current frame buffer. Please note that this function can be slow * @param x defines the x coordinate of the rectangle where pixels must be read @@ -7721,9 +8362,9 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen */ /** - * Sets the current loading screen object - * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen - */ + * Sets the current loading screen object + * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen + */ loadingScreen: ILoadingScreen; /** * Sets the current loading screen text @@ -7773,15 +8414,15 @@ private static _TextureLoaders: IInternalTextureLoader[]; * @returns a number representing the delta time in ms */ getDeltaTime(): number; - private _measureFps(); + private _measureFps; /** @hidden */ - private _canRenderToFloatFramebuffer(); - private _canRenderToHalfFloatFramebuffer(); - private _canRenderToFramebuffer(type); + private _canRenderToFloatFramebuffer; + private _canRenderToHalfFloatFramebuffer; + private _canRenderToFramebuffer; /** @hidden */ - private _getInternalFormat(format); + private _getInternalFormat; /** @hidden */ /** @hidden */ @@ -7790,8 +8431,8 @@ private static _TextureLoaders: IInternalTextureLoader[]; /** @hidden */ - private _partialLoadFile(url, index, loadedFiles, scene, onfinish, onErrorCallBack?); - private _cascadeLoadFiles(scene, onfinish, files, onError?); + private _partialLoadFile; + private _cascadeLoadFiles; /** * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found) * @returns true if the engine can be created @@ -7967,322 +8608,6 @@ declare var WebGLVertexArrayObject: { new (): WebGLVertexArrayObject; }; -declare module BABYLON { - class Collider { - /** Define if a collision was found */ - collisionFound: boolean; - /** - * Define last intersection point in local space - */ - intersectionPoint: Vector3; - /** - * Define last collided mesh - */ - collidedMesh: Nullable; - private _collisionPoint; - private _planeIntersectionPoint; - private _tempVector; - private _tempVector2; - private _tempVector3; - private _tempVector4; - private _edge; - private _baseToVertex; - private _destinationPoint; - private _slidePlaneNormal; - private _displacementVector; - - - private _velocity; - private _basePoint; - private _epsilon; - - - private _velocityWorld; - private _normalizedVelocity; - - - private _nearestDistance; - private _collisionMask; - collisionMask: number; - /** - * Gets the plane normal used to compute the sliding response (in local space) - */ - readonly slidePlaneNormal: Vector3; - - - - - - - } -} - -declare module BABYLON { - var CollisionWorker: string; - interface ICollisionCoordinator { - getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: Nullable, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable) => void, collisionIndex: number): void; - init(scene: Scene): void; - destroy(): void; - onMeshAdded(mesh: AbstractMesh): void; - onMeshUpdated(mesh: AbstractMesh): void; - onMeshRemoved(mesh: AbstractMesh): void; - onGeometryAdded(geometry: Geometry): void; - onGeometryUpdated(geometry: Geometry): void; - onGeometryDeleted(geometry: Geometry): void; - } - interface SerializedMesh { - id: string; - name: string; - uniqueId: number; - geometryId: Nullable; - sphereCenter: Array; - sphereRadius: number; - boxMinimum: Array; - boxMaximum: Array; - worldMatrixFromCache: any; - subMeshes: Array; - checkCollisions: boolean; - } - interface SerializedSubMesh { - position: number; - verticesStart: number; - verticesCount: number; - indexStart: number; - indexCount: number; - hasMaterial: boolean; - sphereCenter: Array; - sphereRadius: number; - boxMinimum: Array; - boxMaximum: Array; - } - /** - * Interface describing the value associated with a geometry - */ - interface SerializedGeometry { - /** - * Defines the unique ID of the geometry - */ - id: string; - /** - * Defines the array containing the positions - */ - positions: Float32Array; - /** - * Defines the array containing the indices - */ - indices: Uint32Array; - /** - * Defines the array containing the normals - */ - normals: Float32Array; - } - interface BabylonMessage { - taskType: WorkerTaskType; - payload: InitPayload | CollidePayload | UpdatePayload; - } - interface SerializedColliderToWorker { - position: Array; - velocity: Array; - radius: Array; - } - /** Defines supported task for worker process */ - enum WorkerTaskType { - /** Initialization */ - INIT = 0, - /** Update of geometry */ - UPDATE = 1, - /** Evaluate collision */ - COLLIDE = 2, - } - interface WorkerReply { - error: WorkerReplyType; - taskType: WorkerTaskType; - payload?: any; - } - interface CollisionReplyPayload { - newPosition: Array; - collisionId: number; - collidedMeshUniqueId: number; - } - interface InitPayload { - } - interface CollidePayload { - collisionId: number; - collider: SerializedColliderToWorker; - maximumRetry: number; - excludedMeshUniqueId: Nullable; - } - interface UpdatePayload { - updatedMeshes: { - [n: number]: SerializedMesh; - }; - updatedGeometries: { - [s: string]: SerializedGeometry; - }; - removedMeshes: Array; - removedGeometries: Array; - } - /** Defines kind of replies returned by worker */ - enum WorkerReplyType { - /** Success */ - SUCCESS = 0, - /** Unkown error */ - UNKNOWN_ERROR = 1, - } - class CollisionCoordinatorWorker implements ICollisionCoordinator { - private _scene; - private _scaledPosition; - private _scaledVelocity; - private _collisionsCallbackArray; - private _init; - private _runningUpdated; - private _worker; - private _addUpdateMeshesList; - private _addUpdateGeometriesList; - private _toRemoveMeshesArray; - private _toRemoveGeometryArray; - constructor(); - static SerializeMesh: (mesh: AbstractMesh) => SerializedMesh; - static SerializeGeometry: (geometry: Geometry) => SerializedGeometry; - getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable) => void, collisionIndex: number): void; - init(scene: Scene): void; - destroy(): void; - onMeshAdded(mesh: AbstractMesh): void; - onMeshUpdated: (transformNode: TransformNode) => void; - onMeshRemoved(mesh: AbstractMesh): void; - onGeometryAdded(geometry: Geometry): void; - onGeometryUpdated: (geometry: Geometry) => void; - onGeometryDeleted(geometry: Geometry): void; - private _afterRender; - private _onMessageFromWorker; - } - class CollisionCoordinatorLegacy implements ICollisionCoordinator { - private _scene; - private _scaledPosition; - private _scaledVelocity; - private _finalPosition; - getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable) => void, collisionIndex: number): void; - init(scene: Scene): void; - destroy(): void; - onMeshAdded(mesh: AbstractMesh): void; - onMeshUpdated(mesh: AbstractMesh): void; - onMeshRemoved(mesh: AbstractMesh): void; - onGeometryAdded(geometry: Geometry): void; - onGeometryUpdated(geometry: Geometry): void; - onGeometryDeleted(geometry: Geometry): void; - private _collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh?); - } -} - -declare function importScripts(...urls: string[]): void; -declare const safePostMessage: any; -declare module BABYLON { - var WorkerIncluded: boolean; - class CollisionCache { - private _meshes; - private _geometries; - getMeshes(): { - [n: number]: SerializedMesh; - }; - getGeometries(): { - [s: number]: SerializedGeometry; - }; - getMesh(id: any): SerializedMesh; - addMesh(mesh: SerializedMesh): void; - removeMesh(uniqueId: number): void; - getGeometry(id: string): SerializedGeometry; - addGeometry(geometry: SerializedGeometry): void; - removeGeometry(id: string): void; - } - class CollideWorker { - collider: Collider; - private _collisionCache; - private finalPosition; - private collisionsScalingMatrix; - private collisionTranformationMatrix; - constructor(collider: Collider, _collisionCache: CollisionCache, finalPosition: Vector3); - collideWithWorld(position: Vector3, velocity: Vector3, maximumRetry: number, excludedMeshUniqueId: Nullable): void; - private checkCollision(mesh); - private processCollisionsForSubMeshes(transformMatrix, mesh); - private collideForSubMesh(subMesh, transformMatrix, meshGeometry); - private checkSubmeshCollision(subMesh); - } - interface ICollisionDetector { - onInit(payload: InitPayload): void; - onUpdate(payload: UpdatePayload): void; - onCollision(payload: CollidePayload): void; - } - class CollisionDetectorTransferable implements ICollisionDetector { - private _collisionCache; - onInit(payload: InitPayload): void; - onUpdate(payload: UpdatePayload): void; - onCollision(payload: CollidePayload): void; - } -} - -declare module BABYLON { - class IntersectionInfo { - bu: Nullable; - bv: Nullable; - distance: number; - faceId: number; - subMeshId: number; - constructor(bu: Nullable, bv: Nullable, distance: number); - } - /** - * Information about the result of picking within a scene - * See https://doc.babylonjs.com/babylon101/picking_collisions - */ - class PickingInfo { - /** - * If the pick collided with an object - */ - hit: boolean; - /** - * Distance away where the pick collided - */ - distance: number; - /** - * The location of pick collision - */ - pickedPoint: Nullable; - /** - * The mesh corrisponding the the pick collision - */ - pickedMesh: Nullable; - /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/ - bu: number; - /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/ - bv: number; - /** The id of the face on the mesh that was picked */ - faceId: number; - /** Id of the the submesh that was picked */ - subMeshId: number; - /** If a sprite was picked, this will be the sprite the pick collided with */ - pickedSprite: Nullable; - /** - * If a mesh was used to do the picking (eg. 6dof controller) this will be populated. - */ - originMesh: Nullable; - /** - * The ray that was used to perform the picking. - */ - ray: Nullable; - /** - * Gets the normal corrispodning to the face the pick collided with - * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false) - * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map - * @returns The normal corrispodning to the face the pick collided with - */ - getNormal(useWorldCoordinates?: boolean, useVerticesNormals?: boolean): Nullable; - /** - * Gets the texture coordinates of where the pick occured - * @returns the vector containing the coordnates of the texture - */ - getTextureCoordinates(): Nullable; - } -} - declare module BABYLON { class ArcRotateCamera extends TargetCamera { alpha: number; @@ -8542,7 +8867,7 @@ declare module BABYLON { * @returns the first post process to be run on this camera. */ - private _cascadePostProcessesToRigCams(); + private _cascadePostProcessesToRigCams; attachPostProcess(postProcess: PostProcess, insertAt?: Nullable): number; detachPostProcess(postProcess: PostProcess): void; getWorldMatrix(): Matrix; @@ -8556,7 +8881,7 @@ declare module BABYLON { * @returns a Matrix */ getTransformationMatrix(): Matrix; - private updateFrustumPlanes(); + private updateFrustumPlanes; isInFrustum(target: ICullable): boolean; isCompletelyInFrustum(target: ICullable): boolean; getForwardRay(length?: number, transform?: Matrix, origin?: Vector3): Ray; @@ -8571,7 +8896,7 @@ declare module BABYLON { getLeftTarget(): Nullable; getRightTarget(): Nullable; setCameraRigMode(mode: number, rigParams: any): void; - private _getVRProjectionMatrix(); + private _getVRProjectionMatrix; protected _updateCameraRotationMatrix(): void; protected _updateWebVRCameraRotationMatrix(): void; /** @@ -8638,7 +8963,7 @@ declare module BABYLON { */ remove(inputToRemove: ICameraInput): void; removeByType(inputType: string): void; - private _addCheckInputs(fn); + private _addCheckInputs; attachInput(input: ICameraInput): void; attachElement(element: HTMLElement, noPreventDefault?: boolean): void; detachElement(element: HTMLElement, disconnect?: boolean): void; @@ -8694,8 +9019,8 @@ declare module BABYLON { maxCameraSpeed: number; lockedTarget: Nullable; constructor(name: string, position: Vector3, scene: Scene, lockedTarget?: Nullable); - private getRadians(degrees); - private follow(cameraTarget); + private getRadians; + private follow; getClassName(): string; } @@ -8706,7 +9031,7 @@ declare module BABYLON { target: Nullable; private _cartesianCoordinates; constructor(name: string, alpha: number, beta: number, radius: number, target: Nullable, scene: Scene); - private follow(); + private follow; getClassName(): string; } @@ -8724,9 +9049,9 @@ declare module BABYLON { * Higher values reduce sensitivity. */ /** - * Sets the input sensibility for a mouse input. (default is 2000.0) - * Higher values reduce sensitivity. - */ + * Sets the input sensibility for a mouse input. (default is 2000.0) + * Higher values reduce sensitivity. + */ angularSensibility: number; keysUp: number[]; keysDown: number[]; @@ -8835,7 +9160,7 @@ declare module BABYLON { * Override Camera._updateRigCameras */ - private _getRigCamPosition(halfSpace, result); + private _getRigCamPosition; getClassName(): string; } } @@ -9030,331 +9355,291 @@ interface Gamepad { readonly displayId: number; } -/** - * Module Debug contains the (visual) components to debug a scene correctly - */ -declare module BABYLON.Debug { +declare module BABYLON { + class StickValues { + x: number; + y: number; + constructor(x: number, y: number); + } + interface GamepadButtonChanges { + changed: boolean; + pressChanged: boolean; + touchChanged: boolean; + valueChanged: boolean; + } + class Gamepad { + id: string; + index: number; + browserGamepad: any; + type: number; + private _leftStick; + private _rightStick; + + private _leftStickAxisX; + private _leftStickAxisY; + private _rightStickAxisX; + private _rightStickAxisY; + private _onleftstickchanged; + private _onrightstickchanged; + static GAMEPAD: number; + static GENERIC: number; + static XBOX: number; + static POSE_ENABLED: number; + protected _invertLeftStickY: boolean; + readonly isConnected: boolean; + constructor(id: string, index: number, browserGamepad: any, leftStickX?: number, leftStickY?: number, rightStickX?: number, rightStickY?: number); + onleftstickchanged(callback: (values: StickValues) => void): void; + onrightstickchanged(callback: (values: StickValues) => void): void; + leftStick: StickValues; + rightStick: StickValues; + update(): void; + dispose(): void; + } + class GenericPad extends Gamepad { + private _buttons; + private _onbuttondown; + private _onbuttonup; + onButtonDownObservable: Observable; + onButtonUpObservable: Observable; + onbuttondown(callback: (buttonPressed: number) => void): void; + onbuttonup(callback: (buttonReleased: number) => void): void; + constructor(id: string, index: number, browserGamepad: any); + private _setButtonValue; + update(): void; + dispose(): void; + } +} + +declare module BABYLON { + class GamepadManager { + private _scene?; + private _babylonGamepads; + private _oneGamepadConnected; + + private _gamepadEventSupported; + private _gamepadSupport; + onGamepadConnectedObservable: Observable; + onGamepadDisconnectedObservable: Observable; + private _onGamepadConnectedEvent; + private _onGamepadDisconnectedEvent; + constructor(_scene?: Scene | undefined); + readonly gamepads: Gamepad[]; + getGamepadByType(type?: number): Nullable; + dispose(): void; + private _addNewGamepad; + private _startMonitoringGamepads; + private _stopMonitoringGamepads; + + private _updateGamepadObjects; + } +} + +declare module BABYLON { + interface Scene { + /** @hidden */ + + /** + * Gets the gamepad manager associated with the scene + * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads + */ + gamepadManager: GamepadManager; + } + interface FreeCameraInputsManager { + addGamepad(): FreeCameraInputsManager; + } + interface ArcRotateCameraInputsManager { + addGamepad(): ArcRotateCameraInputsManager; + } /** - * The Axes viewer will show 3 axes in a specific point in space - */ - class AxesViewer { - private _xline; - private _yline; - private _zline; - private _xmesh; - private _ymesh; - private _zmesh; + * Defines the gamepad scene component responsible to manage gamepads in a given scene + */ + class GamepadSystemSceneComponent implements ISceneComponent { /** - * Gets the hosting scene + * The component name helpfull to identify the component in the list of scene components. */ - scene: Nullable; + readonly name: string; /** - * Gets or sets a number used to scale line length + * The scene the component belongs to. */ - scaleLines: number; + scene: Scene; /** - * Creates a new AxesViewer - * @param scene defines the hosting scene - * @param scaleLines defines a number used to scale line length (1 by default) + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in */ - constructor(scene: Scene, scaleLines?: number); + constructor(scene: Scene); /** - * Force the viewer to update - * @param position defines the position of the viewer - * @param xaxis defines the x axis of the viewer - * @param yaxis defines the y axis of the viewer - * @param zaxis defines the z axis of the viewer + * Registers the component in a given scene + */ + register(): void; + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild(): void; + /** + * Disposes the component and the associated ressources */ - update(position: Vector3, xaxis: Vector3, yaxis: Vector3, zaxis: Vector3): void; - /** Releases resources */ dispose(): void; + private _beforeCameraUpdate; } } -declare module BABYLON.Debug { +declare module BABYLON { /** - * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh - * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8 + * Defines supported buttons for XBox360 compatible gamepads */ - class BoneAxesViewer extends AxesViewer { + enum Xbox360Button { + /** A */ + A = 0, + /** B */ + B = 1, + /** X */ + X = 2, + /** Y */ + Y = 3, + /** Start */ + Start = 4, + /** Back */ + Back = 5, + /** Left button */ + LB = 6, + /** Right button */ + RB = 7, + /** Left stick */ + LeftStick = 8, + /** Right stick */ + RightStick = 9 + } + /** Defines values for XBox360 DPad */ + enum Xbox360Dpad { + /** Up */ + Up = 0, + /** Down */ + Down = 1, + /** Left */ + Left = 2, + /** Right */ + Right = 3 + } + /** + * Defines a XBox360 gamepad + */ + class Xbox360Pad extends Gamepad { + private _leftTrigger; + private _rightTrigger; + private _onlefttriggerchanged; + private _onrighttriggerchanged; + private _onbuttondown; + private _onbuttonup; + private _ondpaddown; + private _ondpadup; + /** Observable raised when a button is pressed */ + onButtonDownObservable: Observable; + /** Observable raised when a button is released */ + onButtonUpObservable: Observable; + /** Observable raised when a pad is pressed */ + onPadDownObservable: Observable; + /** Observable raised when a pad is released */ + onPadUpObservable: Observable; + private _buttonA; + private _buttonB; + private _buttonX; + private _buttonY; + private _buttonBack; + private _buttonStart; + private _buttonLB; + private _buttonRB; + private _buttonLeftStick; + private _buttonRightStick; + private _dPadUp; + private _dPadDown; + private _dPadLeft; + private _dPadRight; + private _isXboxOnePad; /** - * Gets or sets the target mesh where to display the axes viewer + * Creates a new XBox360 gamepad object + * @param id defines the id of this gamepad + * @param index defines its index + * @param gamepad defines the internal HTML gamepad object + * @param xboxOne defines if it is a XBox One gamepad */ - mesh: Nullable; + constructor(id: string, index: number, gamepad: any, xboxOne?: boolean); /** - * Gets or sets the target bone where to display the axes viewer + * Defines the callback to call when left trigger is pressed + * @param callback defines the callback to use */ - bone: Nullable; - /** Gets current position */ - pos: Vector3; - /** Gets direction of X axis */ - xaxis: Vector3; - /** Gets direction of Y axis */ - yaxis: Vector3; - /** Gets direction of Z axis */ - zaxis: Vector3; + onlefttriggerchanged(callback: (value: number) => void): void; /** - * Creates a new BoneAxesViewer - * @param scene defines the hosting scene - * @param bone defines the target bone - * @param mesh defines the target mesh - * @param scaleLines defines a scaling factor for line length (1 by default) + * Defines the callback to call when right trigger is pressed + * @param callback defines the callback to use */ - constructor(scene: Scene, bone: Bone, mesh: Mesh, scaleLines?: number); + onrighttriggerchanged(callback: (value: number) => void): void; /** - * Force the viewer to update + * Gets or sets left trigger value */ - update(): void; - /** Releases resources */ - dispose(): void; - } -} - -declare module BABYLON { - class DebugLayer { - private _scene; - static InspectorURL: string; - private _inspector; - private BJSINSPECTOR; - onPropertyChangedObservable: Observable<{ - object: any; - property: string; - value: any; - initialValue: any; - }>; - constructor(scene: Scene); - /** Creates the inspector window. */ - private _createInspector(config?); - isVisible(): boolean; - hide(): void; + leftTrigger: number; /** - * - * Launch the debugLayer. - * - * initialTab: - * | Value | Tab Name | - * | --- | --- | - * | 0 | Scene | - * | 1 | Console | - * | 2 | Stats | - * | 3 | Textures | - * | 4 | Mesh | - * | 5 | Light | - * | 6 | Material | - * | 7 | GLTF | - * | 8 | GUI | - * | 9 | Physics | - * | 10 | Camera | - * | 11 | Audio | - * - */ - show(config?: { - popup?: boolean; - initialTab?: number; - parentElement?: HTMLElement; - newColors?: { - backgroundColor?: string; - backgroundColorLighter?: string; - backgroundColorLighter2?: string; - backgroundColorLighter3?: string; - color?: string; - colorTop?: string; - colorBot?: string; - }; - }): void; + * Gets or sets right trigger value + */ + rightTrigger: number; /** - * Gets the active tab - * @return the index of the active tab or -1 if the inspector is hidden + * Defines the callback to call when a button is pressed + * @param callback defines the callback to use */ - getActiveTab(): number; - } -} - -declare module BABYLON.Debug { - /** - * Used to show the physics impostor around the specific mesh - */ - class PhysicsViewer { - /** @hidden */ - protected _impostors: Array>; - /** @hidden */ - protected _meshes: Array>; - /** @hidden */ - protected _scene: Nullable; - /** @hidden */ - protected _numMeshes: number; - /** @hidden */ - protected _physicsEnginePlugin: Nullable; - private _renderFunction; - private _debugBoxMesh; - private _debugSphereMesh; - private _debugMaterial; + onbuttondown(callback: (buttonPressed: Xbox360Button) => void): void; /** - * Creates a new PhysicsViewer - * @param scene defines the hosting scene + * Defines the callback to call when a button is released + * @param callback defines the callback to use */ - constructor(scene: Scene); - /** @hidden */ - protected _updateDebugMeshes(): void; + onbuttonup(callback: (buttonReleased: Xbox360Button) => void): void; /** - * Renders a specified physic impostor - * @param impostor defines the impostor to render + * Defines the callback to call when a pad is pressed + * @param callback defines the callback to use */ - showImpostor(impostor: PhysicsImpostor): void; + ondpaddown(callback: (dPadPressed: Xbox360Dpad) => void): void; /** - * Hides a specified physic impostor - * @param impostor defines the impostor to hide + * Defines the callback to call when a pad is released + * @param callback defines the callback to use */ - hideImpostor(impostor: Nullable): void; - private _getDebugMaterial(scene); - private _getDebugBoxMesh(scene); - private _getDebugSphereMesh(scene); - private _getDebugMesh(impostor, scene); - /** Releases all resources */ - dispose(): void; - } -} - -declare module BABYLON { - class RayHelper { - ray: Nullable; - private _renderPoints; - private _renderLine; - private _renderFunction; - private _scene; - private _updateToMeshFunction; - private _attachedToMesh; - private _meshSpaceDirection; - private _meshSpaceOrigin; - static CreateAndShow(ray: Ray, scene: Scene, color: Color3): RayHelper; - constructor(ray: Ray); - show(scene: Scene, color?: Color3): void; - hide(): void; - private _render(); - attachToMesh(mesh: AbstractMesh, meshSpaceDirection?: Vector3, meshSpaceOrigin?: Vector3, length?: number): void; - detachFromMesh(): void; - private _updateToMesh(); - dispose(): void; - } -} - -declare module BABYLON.Debug { - /** - * Class used to render a debug view of a given skeleton - * @see http://www.babylonjs-playground.com/#1BZJVJ#8 - */ - class SkeletonViewer { - /** defines the skeleton to render */ - skeleton: Skeleton; - /** defines the mesh attached to the skeleton */ - mesh: AbstractMesh; - /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */ - autoUpdateBonesMatrices: boolean; - /** defines the rendering group id to use with the viewer */ - renderingGroupId: number; - /** Gets or sets the color used to render the skeleton */ - color: Color3; - private _scene; - private _debugLines; - private _debugMesh; - private _isEnabled; - private _renderFunction; + ondpadup(callback: (dPadReleased: Xbox360Dpad) => void): void; + private _setButtonValue; + private _setDPadValue; + /** Gets or sets value of A button */ + buttonA: number; + /** Gets or sets value of B button */ + buttonB: number; + /** Gets or sets value of X button */ + buttonX: number; + /** Gets or sets value of Y button */ + buttonY: number; + /** Gets or sets value of Start button */ + buttonStart: number; + /** Gets or sets value of Back button */ + buttonBack: number; + /** Gets or sets value of Left button */ + buttonLB: number; + /** Gets or sets value of Right button */ + buttonRB: number; + /** Gets or sets value of left stick */ + buttonLeftStick: number; + /** Gets or sets value of right stick */ + buttonRightStick: number; + /** Gets or sets value of DPad up */ + dPadUp: number; + /** Gets or sets value of DPad down */ + dPadDown: number; + /** Gets or sets value of DPad left */ + dPadLeft: number; + /** Gets or sets value of DPad right */ + dPadRight: number; /** - * Creates a new SkeletonViewer - * @param skeleton defines the skeleton to render - * @param mesh defines the mesh attached to the skeleton - * @param scene defines the hosting scene - * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) - * @param renderingGroupId defines the rendering group id to use with the viewer + * Force the gamepad to synchronize with device values */ - constructor( - /** defines the skeleton to render */ - skeleton: Skeleton, - /** defines the mesh attached to the skeleton */ - mesh: AbstractMesh, scene: Scene, - /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */ - autoUpdateBonesMatrices?: boolean, - /** defines the rendering group id to use with the viewer */ - renderingGroupId?: number); - /** Gets or sets a boolean indicating if the viewer is enabled */ - isEnabled: boolean; - private _getBonePosition(position, bone, meshMat, x?, y?, z?); - private _getLinesForBonesWithLength(bones, meshMat); - private _getLinesForBonesNoLength(bones, meshMat); - /** Update the viewer to sync with current skeleton state */ update(): void; - /** Release associated resources */ dispose(): void; } } -declare module BABYLON { - class KeyboardEventTypes { -private static _KEYDOWN: number; -private static _KEYUP: number; - static readonly KEYDOWN: number; - static readonly KEYUP: number; - } - class KeyboardInfo { - type: number; - event: KeyboardEvent; - constructor(type: number, event: KeyboardEvent); - } - /** - * This class is used to store keyboard related info for the onPreKeyboardObservable event. - * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable - */ - class KeyboardInfoPre extends KeyboardInfo { - constructor(type: number, event: KeyboardEvent); - skipOnPointerObservable: boolean; - } -} - -declare module BABYLON { - class PointerEventTypes { -private static _POINTERDOWN: number; -private static _POINTERUP: number; -private static _POINTERMOVE: number; -private static _POINTERWHEEL: number; -private static _POINTERPICK: number; -private static _POINTERTAP: number; -private static _POINTERDOUBLETAP: number; - static readonly POINTERDOWN: number; - static readonly POINTERUP: number; - static readonly POINTERMOVE: number; - static readonly POINTERWHEEL: number; - static readonly POINTERPICK: number; - static readonly POINTERTAP: number; - static readonly POINTERDOUBLETAP: number; - } - class PointerInfoBase { - type: number; - event: PointerEvent | MouseWheelEvent; - constructor(type: number, event: PointerEvent | MouseWheelEvent); - } - /** - * This class is used to store pointer related info for the onPrePointerObservable event. - * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable - */ - class PointerInfoPre extends PointerInfoBase { - /** - * Ray from a pointer if availible (eg. 6dof controller) - */ - ray: Nullable; - constructor(type: number, event: PointerEvent | MouseWheelEvent, localX: number, localY: number); - localPosition: Vector2; - skipOnPointerObservable: boolean; - } - /** - * This type contains all the data related to a pointer event in Babylon.js. - * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class. - */ - class PointerInfo extends PointerInfoBase { - pickInfo: Nullable; - constructor(type: number, event: PointerEvent | MouseWheelEvent, pickInfo: Nullable); - } -} - declare module BABYLON { /** * Represents the different options available during the creation of @@ -9528,7 +9813,7 @@ declare module BABYLON { /** * Creates the default options for the helper. */ - private static _getDefaultOptions(); + private static _getDefaultOptions; private _rootMesh; /** * Gets the root mesh created by the helper. @@ -9606,51 +9891,51 @@ declare module BABYLON { /** * Setup the image processing according to the specified options. */ - private _setupImageProcessing(); + private _setupImageProcessing; /** * Setup the environment texture according to the specified options. */ - private _setupEnvironmentTexture(); + private _setupEnvironmentTexture; /** * Setup the background according to the specified options. */ - private _setupBackground(); + private _setupBackground; /** * Get the scene sizes according to the setup. */ - private _getSceneSize(); + private _getSceneSize; /** * Setup the ground according to the specified options. */ - private _setupGround(sceneSize); + private _setupGround; /** * Setup the ground material according to the specified options. */ - private _setupGroundMaterial(); + private _setupGroundMaterial; /** * Setup the ground diffuse texture according to the specified options. */ - private _setupGroundDiffuseTexture(); + private _setupGroundDiffuseTexture; /** * Setup the ground mirror texture according to the specified options. */ - private _setupGroundMirrorTexture(sceneSize); + private _setupGroundMirrorTexture; /** * Setup the ground to receive the mirror texture. */ - private _setupMirrorInGroundMaterial(); + private _setupMirrorInGroundMaterial; /** * Setup the skybox according to the specified options. */ - private _setupSkybox(sceneSize); + private _setupSkybox; /** * Setup the skybox material according to the specified options. */ - private _setupSkyboxMaterial(); + private _setupSkyboxMaterial; /** * Setup the skybox reflection texture according to the specified options. */ - private _setupSkyboxReflectionTexture(); + private _setupSkyboxReflectionTexture; private _errorHandler; /** * Dispose all the elements created by the Helper. @@ -9886,8 +10171,8 @@ declare module BABYLON { */ constructor(color?: Color3, gizmoLayer?: UtilityLayerRenderer); protected _attachedMeshChanged(value: Nullable): void; - private _selectNode(selectedMesh); - private _recurseComputeWorld(mesh); + private _selectNode; + private _recurseComputeWorld; /** * Updates the bounding box information for the Gizmo */ @@ -9920,7 +10205,7 @@ declare module BABYLON { * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc. */ class Gizmo implements IDisposable { - /** The utility layer the gizmo will be added to */ gizmoLayer: UtilityLayerRenderer; + gizmoLayer: UtilityLayerRenderer; /** * The root mesh of the gizmo */ @@ -10199,8 +10484,8 @@ declare module BABYLON { * Gets the GPU frame time capture status */ /** - * Enable or disable the GPU frame time capture - */ + * Enable or disable the GPU frame time capture + */ captureGPUFrameTime: boolean; /** * Gets the perf counter used for shader compilation time @@ -10210,8 +10495,8 @@ declare module BABYLON { * Gets the shader compilation time capture status */ /** - * Enable or disable the shader compilation time capture - */ + * Enable or disable the shader compilation time capture + */ captureShaderCompilationTime: boolean; constructor(engine: Engine); dispose(): void; @@ -10269,8 +10554,8 @@ declare module BABYLON { * Gets the active meshes evaluation time capture status */ /** - * Enable or disable the active meshes evaluation time capture - */ + * Enable or disable the active meshes evaluation time capture + */ captureActiveMeshesEvaluationTime: boolean; /** * Gets the perf counter used for render targets render time @@ -10280,8 +10565,8 @@ declare module BABYLON { * Gets the render targets render time capture status */ /** - * Enable or disable the render targets render time capture - */ + * Enable or disable the render targets render time capture + */ captureRenderTargetsRenderTime: boolean; /** * Gets the perf counter used for particles render time @@ -10291,8 +10576,8 @@ declare module BABYLON { * Gets the particles render time capture status */ /** - * Enable or disable the particles render time capture - */ + * Enable or disable the particles render time capture + */ captureParticlesRenderTime: boolean; /** * Gets the perf counter used for sprites render time @@ -10302,8 +10587,8 @@ declare module BABYLON { * Gets the sprites render time capture status */ /** - * Enable or disable the sprites render time capture - */ + * Enable or disable the sprites render time capture + */ captureSpritesRenderTime: boolean; /** * Gets the perf counter used for physics time @@ -10313,8 +10598,8 @@ declare module BABYLON { * Gets the physics time capture status */ /** - * Enable or disable the physics time capture - */ + * Enable or disable the physics time capture + */ capturePhysicsTime: boolean; /** * Gets the perf counter used for animations time @@ -10324,8 +10609,8 @@ declare module BABYLON { * Gets the animations time capture status */ /** - * Enable or disable the animations time capture - */ + * Enable or disable the animations time capture + */ captureAnimationsTime: boolean; /** * Gets the perf counter used for frame time capture @@ -10335,8 +10620,8 @@ declare module BABYLON { * Gets the frame time capture status */ /** - * Enable or disable the frame time capture - */ + * Enable or disable the frame time capture + */ captureFrameTime: boolean; /** * Gets the perf counter used for inter-frames time capture @@ -10346,8 +10631,8 @@ declare module BABYLON { * Gets the inter-frames time capture status */ /** - * Enable or disable the inter-frames time capture - */ + * Enable or disable the inter-frames time capture + */ captureInterFrameTime: boolean; /** * Gets the perf counter used for render time capture @@ -10357,8 +10642,8 @@ declare module BABYLON { * Gets the render time capture status */ /** - * Enable or disable the render time capture - */ + * Enable or disable the render time capture + */ captureRenderTime: boolean; /** * Gets the perf counter used for camera render time capture @@ -10368,8 +10653,8 @@ declare module BABYLON { * Gets the camera render time capture status */ /** - * Enable or disable the camera render time capture - */ + * Enable or disable the camera render time capture + */ captureCameraRenderTime: boolean; /** * Gets the perf counter used for draw calls @@ -10497,8 +10782,8 @@ declare module BABYLON { * @param scene The scene to use the layer in */ constructor( - /** The Friendly of the effect in the scene */ - name: string, scene: Scene); + /** The Friendly of the effect in the scene */ + name: string, scene: Scene); /** * Get the effect name of the layer. * @return The effect name @@ -10554,16 +10839,16 @@ disposeMesh(mesh: Mesh): void; /** * Generates the index buffer of the full screen quad blending to the main canvas. */ - private _generateIndexBuffer(); + private _generateIndexBuffer; /** * Generates the vertex buffer of the full screen quad blending to the main canvas. */ - private _genrateVertexBuffer(); + private _genrateVertexBuffer; /** * Sets the main texture desired size which is the closest power of two * of the engine canvas size. */ - private _setMainTextureSize(); + private _setMainTextureSize; /** * Creates the main texture for the effect layer. */ @@ -10615,7 +10900,7 @@ disposeMesh(mesh: Mesh): void; /** * Dispose only the render target textures and post process. */ - private _disposeTextureAndPostProcesses(); + private _disposeTextureAndPostProcesses; /** * Dispose the highlight layer and free resources. */ @@ -10706,13 +10991,13 @@ declare module BABYLON { * Disposes the component and the associated ressources. */ dispose(): void; - private _isReadyForMesh(mesh, hardwareInstancedRendering); - private _renderMainTexture(camera); - private _setStencil(camera); - private _setStencilBack(camera); - private _draw(renderingGroupId); - private _drawCamera(camera); - private _drawRenderingGroup(index); + private _isReadyForMesh; + private _renderMainTexture; + private _setStencil; + private _setStencilBack; + private _draw; + private _drawCamera; + private _drawRenderingGroup; } } @@ -10777,19 +11062,19 @@ declare module BABYLON { * The default texture size ratio used for the glow. */ static DefaultTextureRatio: number; - /** - * Gets the kernel size of the blur. - */ /** * Sets the kernel size of the blur. */ - blurKernelSize: number; /** - * Gets the glow intensity. - */ + * Gets the kernel size of the blur. + */ + blurKernelSize: number; /** * Sets the glow intensity. */ + /** + * Gets the glow intensity. + */ intensity: number; private _options; private _intensity; @@ -11000,19 +11285,19 @@ declare module BABYLON { * Specifies whether or not the outer glow is ACTIVE in the layer. */ outerGlow: boolean; - /** - * Gets the horizontal size of the blur. - */ /** * Specifies the horizontal size of the blur. */ - blurHorizontalSize: number; /** - * Gets the vertical size of the blur. - */ + * Gets the horizontal size of the blur. + */ + blurHorizontalSize: number; /** * Specifies the vertical size of the blur. */ + /** + * Gets the vertical size of the blur. + */ blurVerticalSize: number; /** * An event triggered when the highlight layer is being blurred. @@ -11113,7 +11398,7 @@ declare module BABYLON { /** * Force the stencil to the normal expected value for none glowing parts */ - private _defaultStencilReference(mesh); + private _defaultStencilReference; /** * Free any resources and references associated to a mesh. * Internal use @@ -11180,7 +11465,7 @@ declare module BABYLON { private _onAfterRenderObserver; onAfterRender: () => void; constructor(name: string, imgUrl: Nullable, scene: Nullable, isBackground?: boolean, color?: Color4); - private _createIndexBuffer(); + private _createIndexBuffer; render(): void; dispose(): void; @@ -11226,9 +11511,9 @@ declare module BABYLON { * Disposes the component and the associated ressources. */ dispose(): void; - private _draw(camera, isBackground); - private _drawBackground(camera); - private _drawForeground(camera); + private _draw; + private _drawBackground; + private _drawForeground; } } @@ -11355,7 +11640,7 @@ declare module BABYLON { * Disposes the component and the associated ressources. */ dispose(): void; - private _draw(camera); + private _draw; } } @@ -11372,8 +11657,8 @@ declare module BABYLON { * Fix frustum size for the shadow generation. This is disabled if the value is 0. */ /** - * Specifies a fix frustum size for the shadow generation. - */ + * Specifies a fix frustum size for the shadow generation. + */ shadowFrustumSize: number; private _shadowOrthoScale; /** @@ -11382,10 +11667,10 @@ declare module BABYLON { * This does not impact in fixed frustum size (shadowFrustumSize being set) */ /** - * Sets the shadow projection scale against the optimal computed one. - * 0.1 by default which means that the projection window is increase by 10% from the optimal size. - * This does not impact in fixed frustum size (shadowFrustumSize being set) - */ + * Sets the shadow projection scale against the optimal computed one. + * 0.1 by default which means that the projection window is increase by 10% from the optimal size. + * This does not impact in fixed frustum size (shadowFrustumSize being set) + */ shadowOrthoScale: number; /** * Automatically compute the projection matrix to best fit (including all the casters) @@ -11630,17 +11915,17 @@ declare module BABYLON { * This is only relevant with PBR Materials where the light intensity can be defined in a physical way. */ /** - * Sets the photometric scale used to interpret the intensity. - * This is only relevant with PBR Materials where the light intensity can be defined in a physical way. - */ + * Sets the photometric scale used to interpret the intensity. + * This is only relevant with PBR Materials where the light intensity can be defined in a physical way. + */ intensityMode: number; private _radius; /** * Gets the light radius used by PBR Materials to simulate soft area lights. */ /** - * sets the light radius used by PBR Materials to simulate soft area lights. - */ + * sets the light radius used by PBR Materials to simulate soft area lights. + */ radius: number; private _renderPriority; /** @@ -11654,25 +11939,25 @@ declare module BABYLON { * the current shadow generator. */ /** - * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching - * the current shadow generator. - */ + * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching + * the current shadow generator. + */ shadowEnabled: boolean; private _includedOnlyMeshes; /** * Gets the only meshes impacted by this light. */ /** - * Sets the only meshes impacted by this light. - */ + * Sets the only meshes impacted by this light. + */ includedOnlyMeshes: AbstractMesh[]; private _excludedMeshes; /** * Gets the meshes not impacted by this light. */ /** - * Sets the meshes not impacted by this light. - */ + * Sets the meshes not impacted by this light. + */ excludedMeshes: AbstractMesh[]; private _excludeWithLayerMask; /** @@ -11680,9 +11965,9 @@ declare module BABYLON { * Inactive if 0 */ /** - * Sets the layer id use to find what meshes are not impacted by the light. - * Inactive if 0 - */ + * Sets the layer id use to find what meshes are not impacted by the light. + * Inactive if 0 + */ excludeWithLayerMask: number; private _includeOnlyWithLayerMask; /** @@ -11690,17 +11975,17 @@ declare module BABYLON { * Inactive if 0 */ /** - * Sets the layer id use to find what meshes are impacted by the light. - * Inactive if 0 - */ + * Sets the layer id use to find what meshes are impacted by the light. + * Inactive if 0 + */ includeOnlyWithLayerMask: number; private _lightmapMode; /** * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) */ /** - * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) - */ + * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) + */ lightmapMode: number; private _parentedWorldMatrix; /** @@ -11827,9 +12112,9 @@ getWorldMatrix(): Matrix; * @returns the created light after parsing */ static Parse(parsedLight: any, scene: Scene): Nullable; - private _hookArrayForExcluded(array); - private _hookArrayForIncludedOnly(array); - private _resyncMeshes(); + private _hookArrayForExcluded; + private _hookArrayForIncludedOnly; + private _resyncMeshes; /** * Forces the meshes to update their light related information in their rendering used effects * @hidden Internal Use Only @@ -11838,11 +12123,11 @@ getWorldMatrix(): Matrix; /** * Recomputes the cached photometric scale if needed. */ - private _computePhotometricScale(); + private _computePhotometricScale; /** * Returns the Photometric Scale according to the light type and intensity mode. */ - private _getPhotometricScale(); + private _getPhotometricScale; /** * Reorder the light in the scene according to their defined priority. * @hidden Internal Use Only @@ -11873,19 +12158,19 @@ declare module BABYLON { * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. */ /** - * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback - * This specifies what angle the shadow will use to be created. - * - * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. - */ + * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + * This specifies what angle the shadow will use to be created. + * + * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. + */ shadowAngle: number; /** * Gets the direction if it has been set. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback */ /** - * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback - */ + * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + */ direction: Vector3; /** * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene. @@ -12060,9 +12345,9 @@ declare module BABYLON { * point and spot lights. */ /** - * Sets the position the shadow will be casted from. Also use as the light position for both - * point and spot lights. - */ + * Sets the position the shadow will be casted from. Also use as the light position for both + * point and spot lights. + */ position: Vector3; protected _direction: Vector3; protected _setDirection(value: Vector3): void; @@ -12071,25 +12356,25 @@ declare module BABYLON { * Also use as the light direction on spot and directional lights. */ /** - * In 2d mode (needCube being false), sets the direction used to cast the shadow. - * Also use as the light direction on spot and directional lights. - */ + * In 2d mode (needCube being false), sets the direction used to cast the shadow. + * Also use as the light direction on spot and directional lights. + */ direction: Vector3; private _shadowMinZ; /** * Gets the shadow projection clipping minimum z value. */ /** - * Sets the shadow projection clipping minimum z value. - */ + * Sets the shadow projection clipping minimum z value. + */ shadowMinZ: number; private _shadowMaxZ; /** * Sets the shadow projection clipping maximum z value. */ /** - * Gets the shadow projection clipping maximum z value. - */ + * Gets the shadow projection clipping maximum z value. + */ shadowMaxZ: number; /** * Callback defining a custom Projection Matrix Builder. @@ -12194,16 +12479,16 @@ declare module BABYLON { * Gets the cone angle of the spot light in Radians. */ /** - * Sets the cone angle of the spot light in Radians. - */ + * Sets the cone angle of the spot light in Radians. + */ angle: number; private _shadowAngleScale; /** * Allows scaling the angle of the light for shadow generation only. */ /** - * Allows scaling the angle of the light for shadow generation only. - */ + * Allows scaling the angle of the light for shadow generation only. + */ shadowAngleScale: number; /** * The light decay speed with the distance from the emission spot. @@ -12219,24 +12504,24 @@ declare module BABYLON { * Gets the near clip of the Spotlight for texture projection. */ /** - * Sets the near clip of the Spotlight for texture projection. - */ + * Sets the near clip of the Spotlight for texture projection. + */ projectionTextureLightNear: number; protected _projectionTextureLightFar: number; /** * Gets the far clip of the Spotlight for texture projection. */ /** - * Sets the far clip of the Spotlight for texture projection. - */ + * Sets the far clip of the Spotlight for texture projection. + */ projectionTextureLightFar: number; protected _projectionTextureUpDirection: Vector3; /** * Gets the Up vector of the Spotlight for texture projection. */ /** - * Sets the Up vector of the Spotlight for texture projection. - */ + * Sets the Up vector of the Spotlight for texture projection. + */ projectionTextureUpDirection: Vector3; private _projectionTexture; /** @@ -12315,291 +12600,6 @@ declare module BABYLON { } } -declare module BABYLON { - class StickValues { - x: number; - y: number; - constructor(x: number, y: number); - } - interface GamepadButtonChanges { - changed: boolean; - pressChanged: boolean; - touchChanged: boolean; - valueChanged: boolean; - } - class Gamepad { - id: string; - index: number; - browserGamepad: any; - type: number; - private _leftStick; - private _rightStick; - - private _leftStickAxisX; - private _leftStickAxisY; - private _rightStickAxisX; - private _rightStickAxisY; - private _onleftstickchanged; - private _onrightstickchanged; - static GAMEPAD: number; - static GENERIC: number; - static XBOX: number; - static POSE_ENABLED: number; - protected _invertLeftStickY: boolean; - readonly isConnected: boolean; - constructor(id: string, index: number, browserGamepad: any, leftStickX?: number, leftStickY?: number, rightStickX?: number, rightStickY?: number); - onleftstickchanged(callback: (values: StickValues) => void): void; - onrightstickchanged(callback: (values: StickValues) => void): void; - leftStick: StickValues; - rightStick: StickValues; - update(): void; - dispose(): void; - } - class GenericPad extends Gamepad { - private _buttons; - private _onbuttondown; - private _onbuttonup; - onButtonDownObservable: Observable; - onButtonUpObservable: Observable; - onbuttondown(callback: (buttonPressed: number) => void): void; - onbuttonup(callback: (buttonReleased: number) => void): void; - constructor(id: string, index: number, browserGamepad: any); - private _setButtonValue(newValue, currentValue, buttonIndex); - update(): void; - dispose(): void; - } -} - -declare module BABYLON { - class GamepadManager { - private _scene; - private _babylonGamepads; - private _oneGamepadConnected; - - private _gamepadEventSupported; - private _gamepadSupport; - onGamepadConnectedObservable: Observable; - onGamepadDisconnectedObservable: Observable; - private _onGamepadConnectedEvent; - private _onGamepadDisconnectedEvent; - constructor(_scene?: Scene | undefined); - readonly gamepads: Gamepad[]; - getGamepadByType(type?: number): Nullable; - dispose(): void; - private _addNewGamepad(gamepad); - private _startMonitoringGamepads(); - private _stopMonitoringGamepads(); - - private _updateGamepadObjects(); - } -} - -declare module BABYLON { - interface Scene { - /** @hidden */ - - /** - * Gets the gamepad manager associated with the scene - * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads - */ - gamepadManager: GamepadManager; - } - interface FreeCameraInputsManager { - addGamepad(): FreeCameraInputsManager; - } - interface ArcRotateCameraInputsManager { - addGamepad(): ArcRotateCameraInputsManager; - } - /** - * Defines the gamepad scene component responsible to manage gamepads in a given scene - */ - class GamepadSystemSceneComponent implements ISceneComponent { - /** - * The component name helpfull to identify the component in the list of scene components. - */ - readonly name: string; - /** - * The scene the component belongs to. - */ - scene: Scene; - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene: Scene); - /** - * Registers the component in a given scene - */ - register(): void; - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild(): void; - /** - * Disposes the component and the associated ressources - */ - dispose(): void; - private _beforeCameraUpdate(); - } -} - -declare module BABYLON { - /** - * Defines supported buttons for XBox360 compatible gamepads - */ - enum Xbox360Button { - /** A */ - A = 0, - /** B */ - B = 1, - /** X */ - X = 2, - /** Y */ - Y = 3, - /** Start */ - Start = 4, - /** Back */ - Back = 5, - /** Left button */ - LB = 6, - /** Right button */ - RB = 7, - /** Left stick */ - LeftStick = 8, - /** Right stick */ - RightStick = 9, - } - /** Defines values for XBox360 DPad */ - enum Xbox360Dpad { - /** Up */ - Up = 0, - /** Down */ - Down = 1, - /** Left */ - Left = 2, - /** Right */ - Right = 3, - } - /** - * Defines a XBox360 gamepad - */ - class Xbox360Pad extends Gamepad { - private _leftTrigger; - private _rightTrigger; - private _onlefttriggerchanged; - private _onrighttriggerchanged; - private _onbuttondown; - private _onbuttonup; - private _ondpaddown; - private _ondpadup; - /** Observable raised when a button is pressed */ - onButtonDownObservable: Observable; - /** Observable raised when a button is released */ - onButtonUpObservable: Observable; - /** Observable raised when a pad is pressed */ - onPadDownObservable: Observable; - /** Observable raised when a pad is released */ - onPadUpObservable: Observable; - private _buttonA; - private _buttonB; - private _buttonX; - private _buttonY; - private _buttonBack; - private _buttonStart; - private _buttonLB; - private _buttonRB; - private _buttonLeftStick; - private _buttonRightStick; - private _dPadUp; - private _dPadDown; - private _dPadLeft; - private _dPadRight; - private _isXboxOnePad; - /** - * Creates a new XBox360 gamepad object - * @param id defines the id of this gamepad - * @param index defines its index - * @param gamepad defines the internal HTML gamepad object - * @param xboxOne defines if it is a XBox One gamepad - */ - constructor(id: string, index: number, gamepad: any, xboxOne?: boolean); - /** - * Defines the callback to call when left trigger is pressed - * @param callback defines the callback to use - */ - onlefttriggerchanged(callback: (value: number) => void): void; - /** - * Defines the callback to call when right trigger is pressed - * @param callback defines the callback to use - */ - onrighttriggerchanged(callback: (value: number) => void): void; - /** - * Gets or sets left trigger value - */ - leftTrigger: number; - /** - * Gets or sets right trigger value - */ - rightTrigger: number; - /** - * Defines the callback to call when a button is pressed - * @param callback defines the callback to use - */ - onbuttondown(callback: (buttonPressed: Xbox360Button) => void): void; - /** - * Defines the callback to call when a button is released - * @param callback defines the callback to use - */ - onbuttonup(callback: (buttonReleased: Xbox360Button) => void): void; - /** - * Defines the callback to call when a pad is pressed - * @param callback defines the callback to use - */ - ondpaddown(callback: (dPadPressed: Xbox360Dpad) => void): void; - /** - * Defines the callback to call when a pad is released - * @param callback defines the callback to use - */ - ondpadup(callback: (dPadReleased: Xbox360Dpad) => void): void; - private _setButtonValue(newValue, currentValue, buttonType); - private _setDPadValue(newValue, currentValue, buttonType); - /** Gets or sets value of A button */ - buttonA: number; - /** Gets or sets value of B button */ - buttonB: number; - /** Gets or sets value of X button */ - buttonX: number; - /** Gets or sets value of Y button */ - buttonY: number; - /** Gets or sets value of Start button */ - buttonStart: number; - /** Gets or sets value of Back button */ - buttonBack: number; - /** Gets or sets value of Left button */ - buttonLB: number; - /** Gets or sets value of Right button */ - buttonRB: number; - /** Gets or sets value of left stick */ - buttonLeftStick: number; - /** Gets or sets value of right stick */ - buttonRightStick: number; - /** Gets or sets value of DPad up */ - dPadUp: number; - /** Gets or sets value of DPad down */ - dPadDown: number; - /** Gets or sets value of DPad left */ - dPadLeft: number; - /** Gets or sets value of DPad right */ - dPadRight: number; - /** - * Force the gamepad to synchronize with device values - */ - update(): void; - dispose(): void; - } -} - declare module BABYLON { interface ILoadingScreen { displayLoadingUI: () => void; @@ -12755,12 +12755,12 @@ declare module BABYLON { static CleanBoneMatrixWeights: boolean; static OnPluginActivatedObservable: Observable; private static _registeredPlugins; - private static _getDefaultPlugin(); - private static _getPluginForExtension(extension); - private static _getPluginForDirectLoad(data); - private static _getPluginForFilename(sceneFilename); - private static _getDirectLoad(sceneFilename); - private static _loadData(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension); + private static _getDefaultPlugin; + private static _getPluginForExtension; + private static _getPluginForDirectLoad; + private static _getPluginForFilename; + private static _getDirectLoad; + private static _loadData; static GetPluginForExtension(extension: string): ISceneLoaderPlugin | ISceneLoaderPluginAsync | ISceneLoaderPluginFactory; static IsPluginForExtensionAvailable(extension: string): boolean; static RegisterPlugin(plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync): void; @@ -13009,18 +13009,18 @@ declare module BABYLON { * @param b defines the blue component (between 0 and 1, default is 0) */ constructor( - /** - * Defines the red component (between 0 and 1, default is 0) - */ - r?: number, - /** - * Defines the green component (between 0 and 1, default is 0) - */ - g?: number, - /** - * Defines the blue component (between 0 and 1, default is 0) - */ - b?: number); + /** + * Defines the red component (between 0 and 1, default is 0) + */ + r?: number, + /** + * Defines the green component (between 0 and 1, default is 0) + */ + g?: number, + /** + * Defines the blue component (between 0 and 1, default is 0) + */ + b?: number); /** * Creates a string with the Color3 current values * @returns the string representation of the Color3 object @@ -13307,22 +13307,22 @@ declare module BABYLON { * @param a defines the alpha component (between 0 and 1, default is 1) */ constructor( - /** - * Defines the red component (between 0 and 1, default is 0) - */ - r?: number, - /** - * Defines the green component (between 0 and 1, default is 0) - */ - g?: number, - /** - * Defines the blue component (between 0 and 1, default is 0) - */ - b?: number, - /** - * Defines the alpha component (between 0 and 1, default is 1) - */ - a?: number); + /** + * Defines the red component (between 0 and 1, default is 0) + */ + r?: number, + /** + * Defines the green component (between 0 and 1, default is 0) + */ + g?: number, + /** + * Defines the blue component (between 0 and 1, default is 0) + */ + b?: number, + /** + * Defines the alpha component (between 0 and 1, default is 1) + */ + a?: number); /** * Adds in place the given Color4 values to the current Color4 object * @param right defines the second operand @@ -13533,10 +13533,10 @@ declare module BABYLON { * @param y defines the second coordinate */ constructor( - /** defines the first coordinate */ - x?: number, - /** defines the second coordinate */ - y?: number); + /** defines the first coordinate */ + x?: number, + /** defines the second coordinate */ + y?: number); /** * Gets a string with the Vector2 coordinates * @returns a string with the Vector2 coordinates @@ -13915,18 +13915,18 @@ declare module BABYLON { * @param z defines the third coordinates (on Z axis) */ constructor( - /** - * Defines the first coordinates (on X axis) - */ - x?: number, - /** - * Defines the second coordinates (on Y axis) - */ - y?: number, - /** - * Defines the third coordinates (on Z axis) - */ - z?: number); + /** + * Defines the first coordinates (on X axis) + */ + x?: number, + /** + * Defines the second coordinates (on Y axis) + */ + y?: number, + /** + * Defines the third coordinates (on Z axis) + */ + z?: number); /** * Creates a string representation of the Vector3 * @returns a string with the Vector3 coordinates. @@ -14871,14 +14871,14 @@ declare module BABYLON { * @param w defines the fourth component (1.0 by default) */ constructor( - /** defines the first component (0 by default) */ - x?: number, - /** defines the second component (0 by default) */ - y?: number, - /** defines the third component (0 by default) */ - z?: number, - /** defines the fourth component (1.0 by default) */ - w?: number); + /** defines the first component (0 by default) */ + x?: number, + /** defines the second component (0 by default) */ + y?: number, + /** defines the third component (0 by default) */ + z?: number, + /** defines the fourth component (1.0 by default) */ + w?: number); /** * Gets a string representation for the current quaternion * @returns a string with the Quaternion coordinates @@ -16007,7 +16007,7 @@ declare module BABYLON { /** World space */ WORLD = 1, /** Bone space */ - BONE = 2, + BONE = 2 } /** Defines the 3 main axes */ class Axis { @@ -16033,7 +16033,7 @@ declare module BABYLON { */ CW = 0, /** Counter clockwise */ - CCW = 1, + CCW = 1 } /** * Defines angle representation @@ -16170,10 +16170,10 @@ declare module BABYLON { * Returns the same object updated. */ update(path: Vector3[], firstNormal?: Nullable): Path3D; - private _compute(firstNormal); - private _getFirstNonNullVector(index); - private _getLastNonNullVector(index); - private _normalVector(v0, vt, va); + private _compute; + private _getFirstNonNullVector; + private _getLastNonNullVector; + private _normalVector; } class Curve3 { private _points; @@ -16231,7 +16231,7 @@ declare module BABYLON { * curveA and curveB keep unchanged. */ continue(curve: Curve3): Curve3; - private _computeLength(path); + private _computeLength; } class PositionNormalVertex { position: Vector3; @@ -16435,9 +16435,9 @@ declare module BABYLON { * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ /** - * Sets the global Hue value. - * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). - */ + * Sets the global Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ globalHue: number; /** * Gets the global Density value. @@ -16445,28 +16445,28 @@ declare module BABYLON { * Values less than zero provide a filter of opposite hue. */ /** - * Sets the global Density value. - * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. - * Values less than zero provide a filter of opposite hue. - */ + * Sets the global Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ globalDensity: number; /** * Gets the global Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ /** - * Sets the global Saturation value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. - */ + * Sets the global Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ globalSaturation: number; /** * Gets the global Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ /** - * Sets the global Exposure value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. - */ + * Sets the global Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ globalExposure: number; private _highlightsHue; private _highlightsDensity; @@ -16477,9 +16477,9 @@ declare module BABYLON { * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ /** - * Sets the highlights Hue value. - * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). - */ + * Sets the highlights Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ highlightsHue: number; /** * Gets the highlights Density value. @@ -16487,28 +16487,28 @@ declare module BABYLON { * Values less than zero provide a filter of opposite hue. */ /** - * Sets the highlights Density value. - * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. - * Values less than zero provide a filter of opposite hue. - */ + * Sets the highlights Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ highlightsDensity: number; /** * Gets the highlights Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ /** - * Sets the highlights Saturation value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. - */ + * Sets the highlights Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ highlightsSaturation: number; /** * Gets the highlights Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ /** - * Sets the highlights Exposure value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. - */ + * Sets the highlights Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ highlightsExposure: number; private _midtonesHue; private _midtonesDensity; @@ -16519,9 +16519,9 @@ declare module BABYLON { * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ /** - * Sets the midtones Hue value. - * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). - */ + * Sets the midtones Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ midtonesHue: number; /** * Gets the midtones Density value. @@ -16529,28 +16529,28 @@ declare module BABYLON { * Values less than zero provide a filter of opposite hue. */ /** - * Sets the midtones Density value. - * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. - * Values less than zero provide a filter of opposite hue. - */ + * Sets the midtones Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ midtonesDensity: number; /** * Gets the midtones Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ /** - * Sets the midtones Saturation value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. - */ + * Sets the midtones Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ midtonesSaturation: number; /** * Gets the midtones Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ /** - * Sets the midtones Exposure value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. - */ + * Sets the midtones Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ midtonesExposure: number; private _shadowsHue; private _shadowsDensity; @@ -16561,9 +16561,9 @@ declare module BABYLON { * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ /** - * Sets the shadows Hue value. - * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). - */ + * Sets the shadows Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ shadowsHue: number; /** * Gets the shadows Density value. @@ -16571,28 +16571,28 @@ declare module BABYLON { * Values less than zero provide a filter of opposite hue. */ /** - * Sets the shadows Density value. - * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. - * Values less than zero provide a filter of opposite hue. - */ + * Sets the shadows Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ shadowsDensity: number; /** * Gets the shadows Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ /** - * Sets the shadows Saturation value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. - */ + * Sets the shadows Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ shadowsSaturation: number; /** * Gets the shadows Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ /** - * Sets the shadows Exposure value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. - */ + * Sets the shadows Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ shadowsExposure: number; getClassName(): string; /** @@ -16614,13 +16614,13 @@ declare module BABYLON { * @param exposure The exposure. * @param result The result data container. */ - private getColorGradingDataToRef(hue, density, saturation, exposure, result); + private getColorGradingDataToRef; /** * Takes an input slider value and returns an adjusted value that provides extra control near the centre. * @param value The input slider value in range [-100,100]. * @returns Adjusted value. */ - private static applyColorGradingSliderNonlinear(value); + private static applyColorGradingSliderNonlinear; /** * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV). * @param hue The hue (H) input. @@ -16628,7 +16628,7 @@ declare module BABYLON { * @param brightness The brightness (B) input. * @result An RGBA color represented as Vector4. */ - private static fromHSBToRef(hue, saturation, brightness, result); + private static fromHSBToRef; /** * Returns a value clamped between min and max * @param value The value to clamp @@ -16636,7 +16636,7 @@ declare module BABYLON { * @param max The maximum of value * @returns The clamped value. */ - private static clamp(value, min, max); + private static clamp; /** * Clones the current color curve instance. * @return The cloned curves @@ -16779,10 +16779,12 @@ declare module BABYLON { * Observable that will be called if an error occurs during shader compilation. */ onErrorObservable: Observable; + /** @hidden */ + /** * Observable that will be called when effect is bound. */ - onBindObservable: Observable; + readonly onBindObservable: Observable; /** @hidden */ private static _uniqueIdSeed; @@ -16901,9 +16903,9 @@ declare module BABYLON { /** @hidden */ - private _processShaderConversion(sourceCode, isFragment, callback); - private _processIncludes(sourceCode, callback); - private _processPrecision(source); + private _processShaderConversion; + private _processIncludes; + private _processPrecision; /** * Recompiles the webGL program * @param vertexSourceCode The source code for the vertex shader. @@ -17262,8 +17264,8 @@ declare module BABYLON { * Gets wether the color curves effect is enabled. */ /** - * Sets wether the color curves effect is enabled. - */ + * Sets wether the color curves effect is enabled. + */ colorCurvesEnabled: boolean; /** * Color grading LUT texture used in the effect if colorGradingEnabled is set to true @@ -17274,48 +17276,48 @@ declare module BABYLON { * Gets wether the color grading effect is enabled. */ /** - * Sets wether the color grading effect is enabled. - */ + * Sets wether the color grading effect is enabled. + */ colorGradingEnabled: boolean; private _colorGradingWithGreenDepth; /** * Gets wether the color grading effect is using a green depth for the 3d Texture. */ /** - * Sets wether the color grading effect is using a green depth for the 3d Texture. - */ + * Sets wether the color grading effect is using a green depth for the 3d Texture. + */ colorGradingWithGreenDepth: boolean; private _colorGradingBGR; /** * Gets wether the color grading texture contains BGR values. */ /** - * Sets wether the color grading texture contains BGR values. - */ + * Sets wether the color grading texture contains BGR values. + */ colorGradingBGR: boolean; /** * Gets the Exposure used in the effect. */ /** - * Sets the Exposure used in the effect. - */ + * Sets the Exposure used in the effect. + */ exposure: number; private _toneMappingEnabled; /** * Gets wether the tone mapping effect is enabled. */ /** - * Sets wether the tone mapping effect is enabled. - */ + * Sets wether the tone mapping effect is enabled. + */ toneMappingEnabled: boolean; protected _contrast: number; /** * Gets the contrast used in the effect. */ /** - * Sets the contrast used in the effect. - */ + * Sets the contrast used in the effect. + */ contrast: number; /** * Vignette stretch size. @@ -17347,32 +17349,32 @@ declare module BABYLON { * Gets the vignette blend mode allowing different kind of effect. */ /** - * Sets the vignette blend mode allowing different kind of effect. - */ + * Sets the vignette blend mode allowing different kind of effect. + */ vignetteBlendMode: number; private _vignetteEnabled; /** * Gets wether the vignette effect is enabled. */ /** - * Sets wether the vignette effect is enabled. - */ + * Sets wether the vignette effect is enabled. + */ vignetteEnabled: boolean; private _applyByPostProcess; /** * Gets wether the image processing is applied through a post process or not. */ /** - * Sets wether the image processing is applied through a post process or not. - */ + * Sets wether the image processing is applied through a post process or not. + */ applyByPostProcess: boolean; private _isEnabled; /** * Gets wether the image processing is enabled or not. */ /** - * Sets wether the image processing is enabled or not. - */ + * Sets wether the image processing is enabled or not. + */ isEnabled: boolean; /** * An event triggered when the configuration changes and requires Shader to Update some parameters. @@ -17665,23 +17667,23 @@ declare module BABYLON { * The alpha value of the material */ protected _alpha: number; - /** - * Gets the alpha value of the material - */ /** * Sets the alpha value of the material */ + /** + * Gets the alpha value of the material + */ alpha: number; /** * Specifies if back face culling is enabled */ protected _backFaceCulling: boolean; - /** - * Gets the back-face culling state - */ /** * Sets the back-face culling state */ + /** + * Gets the back-face culling state + */ backFaceCulling: boolean; /** * Stores the value for side orientation @@ -17719,14 +17721,16 @@ declare module BABYLON { * An observer which watches for dispose events */ private _onDisposeObserver; + private _onUnBindObservable; /** * Called during a dispose event */ onDispose: () => void; + private _onBindObservable; /** * An event triggered when the material is bound */ - onBindObservable: Observable; + readonly onBindObservable: Observable; /** * An observer which watches for bind events */ @@ -17738,14 +17742,11 @@ declare module BABYLON { /** * An event triggered when the material is unbound */ - onUnBindObservable: Observable; + readonly onUnBindObservable: Observable; /** * Stores the value of the alpha mode */ private _alphaMode; - /** - * Gets the value of the alpha mode - */ /** * Sets the value of the alpha mode. * @@ -17764,17 +17765,20 @@ declare module BABYLON { * | 10 | ALPHA_SCREENMODE | | * */ + /** + * Gets the value of the alpha mode + */ alphaMode: number; /** * Stores the state of the need depth pre-pass value */ private _needDepthPrePass; - /** - * Gets the depth pre-pass value - */ /** * Sets the need depth pre-pass value */ + /** + * Gets the depth pre-pass value + */ needDepthPrePass: boolean; /** * Specifies if depth writing should be disabled @@ -17792,12 +17796,12 @@ declare module BABYLON { * Stores the state specifing if fog should be enabled */ private _fogEnabled; - /** - * Gets the value of the fog enabled state - */ /** * Sets the state for enabling fog */ + /** + * Gets the value of the fog enabled state + */ fogEnabled: boolean; /** * Stores the size of points @@ -17811,22 +17815,22 @@ declare module BABYLON { * Gets a value specifying if wireframe mode is enabled */ /** - * Sets the state of wireframe mode - */ + * Sets the state of wireframe mode + */ wireframe: boolean; /** * Gets the value specifying if point clouds are enabled */ /** - * Sets the state of point cloud mode - */ + * Sets the state of point cloud mode + */ pointsCloud: boolean; /** * Gets the material fill mode */ /** - * Sets the material fill mode - */ + * Sets the material fill mode + */ fillMode: number; /** * Stores the effects for the material @@ -18275,7 +18279,7 @@ declare module BABYLON { private _subMaterials; subMaterials: Nullable[]; constructor(name: string, scene: Scene); - private _hookArray(array); + private _hookArray; getSubMaterial(index: number): Nullable; getActiveTextures(): BaseTexture[]; getClassName(): string; @@ -18337,7 +18341,7 @@ declare module BABYLON { getClassName(): string; needAlphaBlending(): boolean; needAlphaTesting(): boolean; - private _checkUniform(uniformName); + private _checkUniform; setTexture(name: string, texture: Texture): ShaderMaterial; setTextureArray(name: string, textures: Texture[]): ShaderMaterial; setFloat(name: string, value: number): ShaderMaterial; @@ -18354,7 +18358,7 @@ declare module BABYLON { setMatrix2x2(name: string, value: Float32Array): ShaderMaterial; setArray2(name: string, value: number[]): ShaderMaterial; setArray3(name: string, value: number[]): ShaderMaterial; - private _checkCache(scene, mesh?, useInstances?); + private _checkCache; isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean; bindOnlyWorldMatrix(world: Matrix): void; bind(world: Matrix, mesh?: Mesh): void; @@ -18564,10 +18568,10 @@ declare module BABYLON { * Gets the image processing configuration used either in this material. */ /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ imageProcessingConfiguration: ImageProcessingConfiguration; /** * Keep track of the image processing observer to allow dispose and replace. @@ -18582,22 +18586,22 @@ declare module BABYLON { * Gets wether the color curves effect is enabled. */ /** - * Sets wether the color curves effect is enabled. - */ + * Sets wether the color curves effect is enabled. + */ cameraColorCurvesEnabled: boolean; /** * Gets wether the color grading effect is enabled. */ /** - * Gets wether the color grading effect is enabled. - */ + * Gets wether the color grading effect is enabled. + */ cameraColorGradingEnabled: boolean; /** * Gets wether tonemapping is enabled or not. */ /** - * Sets wether tonemapping is enabled or not - */ + * Sets wether tonemapping is enabled or not + */ cameraToneMappingEnabled: boolean; /** * The camera exposure used on this material. @@ -18605,24 +18609,24 @@ declare module BABYLON { * This corresponds to a photographic exposure. */ /** - * The camera exposure used on this material. - * This property is here and not in the camera to allow controlling exposure without full screen post process. - * This corresponds to a photographic exposure. - */ + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ cameraExposure: number; /** * Gets The camera contrast used on this material. */ /** - * Sets The camera contrast used on this material. - */ + * Sets The camera contrast used on this material. + */ cameraContrast: number; /** * Gets the Color Grading 2D Lookup Texture. */ /** - * Sets the Color Grading 2D Lookup Texture. - */ + * Sets the Color Grading 2D Lookup Texture. + */ cameraColorGradingTexture: Nullable; /** * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). @@ -18631,11 +18635,11 @@ declare module BABYLON { * corresponding to low luminance, medium luminance, and high luminance areas respectively. */ /** - * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). - * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. - * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; - * corresponding to low luminance, medium luminance, and high luminance areas respectively. - */ + * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ cameraColorCurves: Nullable; customShaderNameResolve: (shaderName: string, uniforms: string[], uniformBuffers: string[], samplers: string[], defines: StandardMaterialDefines) => string; protected _renderTargets: SmartArray; @@ -18822,7 +18826,7 @@ declare module BABYLON { * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159 * for specs. */ - private _fillAlignment(size); + private _fillAlignment; /** * Adds an uniform in the buffer. * Warning : the subsequents calls of this function must be in the same order as declared in the shader @@ -18899,28 +18903,28 @@ declare module BABYLON { * @param {number} size Size of the data. */ updateUniform(uniformName: string, data: FloatArray, size: number): void; - private _updateMatrix3x3ForUniform(name, matrix); - private _updateMatrix3x3ForEffect(name, matrix); - private _updateMatrix2x2ForEffect(name, matrix); - private _updateMatrix2x2ForUniform(name, matrix); - private _updateFloatForEffect(name, x); - private _updateFloatForUniform(name, x); - private _updateFloat2ForEffect(name, x, y, suffix?); - private _updateFloat2ForUniform(name, x, y, suffix?); - private _updateFloat3ForEffect(name, x, y, z, suffix?); - private _updateFloat3ForUniform(name, x, y, z, suffix?); - private _updateFloat4ForEffect(name, x, y, z, w, suffix?); - private _updateFloat4ForUniform(name, x, y, z, w, suffix?); - private _updateMatrixForEffect(name, mat); - private _updateMatrixForUniform(name, mat); - private _updateVector3ForEffect(name, vector); - private _updateVector3ForUniform(name, vector); - private _updateVector4ForEffect(name, vector); - private _updateVector4ForUniform(name, vector); - private _updateColor3ForEffect(name, color, suffix?); - private _updateColor3ForUniform(name, color, suffix?); - private _updateColor4ForEffect(name, color, alpha, suffix?); - private _updateColor4ForUniform(name, color, alpha, suffix?); + private _updateMatrix3x3ForUniform; + private _updateMatrix3x3ForEffect; + private _updateMatrix2x2ForEffect; + private _updateMatrix2x2ForUniform; + private _updateFloatForEffect; + private _updateFloatForUniform; + private _updateFloat2ForEffect; + private _updateFloat2ForUniform; + private _updateFloat3ForEffect; + private _updateFloat3ForUniform; + private _updateFloat4ForEffect; + private _updateFloat4ForUniform; + private _updateMatrixForEffect; + private _updateMatrixForUniform; + private _updateVector3ForEffect; + private _updateVector3ForUniform; + private _updateVector4ForEffect; + private _updateVector4ForUniform; + private _updateColor3ForEffect; + private _updateColor3ForUniform; + private _updateColor4ForEffect; + private _updateColor4ForUniform; /** * Sets a sampler uniform on the effect. * @param {string} name Name of the sampler. @@ -18982,8 +18986,8 @@ declare module BABYLON { * @param influence defines the influence to use */ constructor( - /** defines the name of the target */ - name: string, influence?: number, scene?: Nullable); + /** defines the name of the target */ + name: string, influence?: number, scene?: Nullable); /** * Gets a boolean defining if the target contains position data */ @@ -19124,7 +19128,7 @@ declare module BABYLON { * @returns the serialized object */ serialize(): any; - private _syncActiveTargets(needUpdate); + private _syncActiveTargets; /** * Syncrhonize the targets with all the meshes using this morph target manager */ @@ -19141,7668 +19145,8318 @@ declare module BABYLON { declare module BABYLON { /** - * This represents a GPU particle system in Babylon - * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data - * @see https://www.babylonjs-playground.com/#PU4WYI#4 + * Class used to store all common mesh properties */ - class GPUParticleSystem implements IDisposable, IParticleSystem, IAnimatable { + class AbstractMesh extends TransformNode implements IDisposable, ICullable, IGetSetVerticesData { + /** No occlusion */ + static OCCLUSION_TYPE_NONE: number; + /** Occlusion set to optimisitic */ + static OCCLUSION_TYPE_OPTIMISTIC: number; + /** Occlusion set to strict */ + static OCCLUSION_TYPE_STRICT: number; + /** Use an accurante occlusion algorithm */ + static OCCLUSION_ALGORITHM_TYPE_ACCURATE: number; + /** Use a conservative occlusion algorithm */ + static OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE: number; /** - * The id of the Particle system. + * No billboard */ - id: string; + static readonly BILLBOARDMODE_NONE: number; + /** Billboard on X axis */ + static readonly BILLBOARDMODE_X: number; + /** Billboard on Y axis */ + static readonly BILLBOARDMODE_Y: number; + /** Billboard on Z axis */ + static readonly BILLBOARDMODE_Z: number; + /** Billboard on all axes */ + static readonly BILLBOARDMODE_ALL: number; + private _facetPositions; + private _facetNormals; + private _facetPartitioning; + private _facetNb; + private _partitioningSubdivisions; + private _partitioningBBoxRatio; + private _facetDataEnabled; + private _facetParameters; + private _bbSize; + private _subDiv; + private _facetDepthSort; + private _facetDepthSortEnabled; + private _depthSortedIndices; + private _depthSortedFacets; + private _facetDepthSortFunction; + private _facetDepthSortFrom; + private _facetDepthSortOrigin; + private _invertedMatrix; /** - * The friendly name of the Particle system. + * Gets the number of facets in the mesh + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet */ - name: string; + readonly facetNb: number; /** - * The emitter represents the Mesh or position we are attaching the particle system to. + * Gets or set the number (integer) of subdivisions per axis in the partioning space + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning */ - emitter: Nullable; + partitioningSubdivisions: number; /** - * The rendering group used by the Particle system to chose when to render. + * The ratio (float) to apply to the bouding box size to set to the partioning space. + * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning */ - renderingGroupId: number; + partitioningBBoxRatio: number; /** - * The layer mask we are rendering the particles through. + * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`. + * Works only for updatable meshes. + * Doesn't work with multi-materials + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort */ - layerMask: number; - private _capacity; - private _activeCount; - private _currentActiveCount; - private _accumulatedCount; - private _renderEffect; - private _updateEffect; - private _buffer0; - private _buffer1; - private _spriteBuffer; - private _updateVAO; - private _renderVAO; - private _targetIndex; - private _sourceBuffer; - private _targetBuffer; - private _scene; - private _engine; - private _currentRenderId; - private _started; - private _stopped; - private _timeDelta; - private _randomTexture; - private _randomTexture2; - private _attributesStrideSize; - private _updateEffectOptions; - private _randomTextureSize; - private _actualFrame; - private readonly _rawTextureWidth; + mustDepthSortFacets: boolean; /** - * List of animations used by the particle system. + * The location (Vector3) where the facet depth sort must be computed from. + * By default, the active camera position. + * Used only when facet depth sort is enabled + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort */ - animations: Animation[]; + facetDepthSortFrom: Vector3; /** - * Gets a boolean indicating if the GPU particles can be rendered on current browser + * gets a boolean indicating if facetData is enabled + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet */ - static readonly IsSupported: boolean; + readonly isFacetDataEnabled: boolean; + /** @hidden */ + /** - * An event triggered when the system is disposed. + * An event triggered when this mesh collides with another one */ - onDisposeObservable: Observable; + onCollideObservable: Observable; + private _onCollideObserver; + /** Set a function to call when this mesh collides with another one */ + onCollide: () => void; /** - * The overall motion speed (0.01 is default update speed, faster updates = faster animation) - */ - updateSpeed: number; + * An event triggered when the collision's position changes + */ + onCollisionPositionChangeObservable: Observable; + private _onCollisionPositionChangeObserver; + /** Set a function to call when the collision's position changes */ + onCollisionPositionChange: () => void; /** - * The amount of time the particle system is running (depends of the overall update speed). - */ - targetStopDuration: number; + * An event triggered when material is changed + */ + onMaterialChangedObservable: Observable; /** - * The texture used to render each particle. (this can be a spritesheet) + * Gets or sets the orientation for POV movement & rotation */ - particleTexture: Nullable; + definedFacingForward: boolean; /** - * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD. - */ - blendMode: number; + * This property determines the type of occlusion query algorithm to run in WebGl, you can use: + * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED. + * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate. + * @see http://doc.babylonjs.com/features/occlusionquery + */ + occlusionQueryAlgorithmType: number; /** - * Minimum life time of emitting particles. + * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values: + * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh. + * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh. + * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show. + * @see http://doc.babylonjs.com/features/occlusionquery */ - minLifeTime: number; + occlusionType: number; /** - * Maximum life time of emitting particles. - */ - maxLifeTime: number; + * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object. + * The default value is -1 which means don't break the query and wait till the result + * @see http://doc.babylonjs.com/features/occlusionquery + */ + occlusionRetryCount: number; + /** @hidden */ + + /** @hidden */ + /** - * Minimum Size of emitting particles. - */ - minSize: number; + * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not + * @see http://doc.babylonjs.com/features/occlusionquery + */ + isOccluded: boolean; + /** @hidden */ + /** - * Maximum Size of emitting particles. + * Flag to check the progress status of the query + * @see http://doc.babylonjs.com/features/occlusionquery */ - maxSize: number; + readonly isOcclusionQueryInProgress: boolean; + /** @hidden */ + + private _visibility; /** - * Minimum scale of emitting particles on X axis. + * Gets or sets mesh visibility between 0 and 1 (default is 1) */ - minScaleX: number; /** - * Maximum scale of emitting particles on X axis. + * Gets or sets mesh visibility between 0 and 1 (default is 1) + */ + visibility: number; + /** Gets or sets the alpha index used to sort transparent meshes + * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index */ - maxScaleX: number; + alphaIndex: number; /** - * Minimum scale of emitting particles on Y axis. + * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true */ - minScaleY: number; + isVisible: boolean; /** - * Maximum scale of emitting particles on Y axis. + * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true */ - maxScaleY: number; - /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors. + isPickable: boolean; + /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */ + showSubMeshesBoundingBox: boolean; + /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default) + * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares */ - color1: Color4; + isBlocker: boolean; /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors. + * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default) */ - color2: Color4; + enablePointerMoveEvents: boolean; /** - * Color the particle will have at the end of its lifetime. + * Specifies the rendering group id for this mesh (0 by default) + * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups */ - colorDead: Color4; + renderingGroupId: number; + private _material; + /** Gets or sets current material */ + material: Nullable; + private _receiveShadows; /** - * The maximum number of particles to emit per frame until we reach the activeParticleCount value + * Gets or sets a boolean indicating that this mesh can receive realtime shadows + * @see http://doc.babylonjs.com/babylon101/shadows */ - emitRate: number; + receiveShadows: boolean; /** - * You can use gravity if you want to give an orientation to your particles. + * Gets or sets a boolean indicating if the outline must be rendered as well + * @see https://www.babylonjs-playground.com/#10WJ5S#3 */ - gravity: Vector3; + renderOutline: boolean; + /** Defines color to use when rendering outline */ + outlineColor: Color3; + /** Define width to use when rendering outline */ + outlineWidth: number; /** - * Minimum power of emitting particles. + * Gets or sets a boolean indicating if the overlay must be rendered as well + * @see https://www.babylonjs-playground.com/#10WJ5S#2 */ - minEmitPower: number; + renderOverlay: boolean; + /** Defines color to use when rendering overlay */ + overlayColor: Color3; + /** Defines alpha to use when rendering overlay */ + overlayAlpha: number; + private _hasVertexAlpha; + /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */ + hasVertexAlpha: boolean; + private _useVertexColors; + /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */ + useVertexColors: boolean; + private _computeBonesUsingShaders; /** - * Maximum power of emitting particles. + * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default) */ - maxEmitPower: number; + computeBonesUsingShaders: boolean; + private _numBoneInfluencers; + /** Gets or sets the number of allowed bone influences per vertex (4 by default) */ + numBoneInfluencers: number; + private _applyFog; + /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */ + applyFog: boolean; + /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */ + useOctreeForRenderingSelection: boolean; + /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */ + useOctreeForPicking: boolean; + /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */ + useOctreeForCollisions: boolean; + private _layerMask; /** - * Minimum angular speed of emitting particles (Z-axis rotation for each particle). + * Gets or sets the current layer mask (default is 0x0FFFFFFF) + * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures */ - minAngularSpeed: number; + layerMask: number; /** - * Maximum angular speed of emitting particles (Z-axis rotation for each particle). + * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase) */ - maxAngularSpeed: number; + alwaysSelectAsActiveMesh: boolean; /** - * The particle emitter type defines the emitter used by the particle system. - * It can be for example box, sphere, or cone... + * Gets or sets the current action manager + * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ - particleEmitterType: Nullable; + actionManager: Nullable; /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Gets or sets impostor used for physic simulation + * @see http://doc.babylonjs.com/features/physics_engine */ - direction1: Vector3; + physicsImpostor: Nullable; + private _checkCollisions; + private _collisionMask; + private _collisionGroup; /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5)) + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ - direction2: Vector3; + ellipsoid: Vector3; /** - * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0)) + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ - minEmitBox: Vector3; + ellipsoidOffset: Vector3; + private _collider; + private _oldPositionForCollisions; + private _diffPositionForCollisions; /** - * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Gets or sets a collision mask used to mask collisions (default is -1). + * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 */ - maxEmitBox: Vector3; + collisionMask: number; /** - * Gets the maximum number of particles active at the same time. - * @returns The max number of active particles. + * Gets or sets the current collision group mask (-1 by default). + * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 */ - getCapacity(): number; + collisionGroup: number; /** - * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls - * to override the particles. + * Defines edge width used when edgesRenderer is enabled + * @see https://www.babylonjs-playground.com/#10OJSG#13 */ - forceDepthWrite: boolean; + edgesWidth: number; /** - * Gets or set the number of active particles - */ - activeParticleCount: number; - private _preWarmDone; - /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */ - preWarmCycles: number; - /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */ - preWarmStepOffset: number; - /** - * Gets or sets the minimal initial rotation in radians. - */ - minInitialRotation: number; - /** - * Gets or sets the maximal initial rotation in radians. - */ - maxInitialRotation: number; - /** - * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime) + * Defines edge color used when edgesRenderer is enabled + * @see https://www.babylonjs-playground.com/#10OJSG#13 */ - spriteCellChangeSpeed: number; + edgesColor: Color4; + /** @hidden */ + + private _collisionsTransformMatrix; + private _collisionsScalingMatrix; + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + /** - * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display + * Gets or sets the list of subMeshes + * @see http://doc.babylonjs.com/how_to/multi_materials */ - startSpriteCellID: number; + subMeshes: SubMesh[]; + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ +protected readonly _positions: Nullable; + /** @hidden */ + + /** @hidden */ + + private _skeleton; + /** @hidden */ + /** - * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display + * Gets or sets a skeleton to apply skining transformations + * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons */ - endSpriteCellID: number; + skeleton: Nullable; /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use + * Creates a new AbstractMesh + * @param name defines the name of the mesh + * @param scene defines the hosting scene */ - spriteCellWidth: number; + constructor(name: string, scene?: Nullable); /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use + * Returns the string "AbstractMesh" + * @returns "AbstractMesh" */ - spriteCellHeight: number; - /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ - translationPivot: Vector2; + getClassName(): string; /** - * Gets or sets a texture used to add random noise to particle positions + * Gets a string representation of the current mesh + * @param fullDetails defines a boolean indicating if full details must be included + * @returns a string representation of the current mesh */ - noiseTexture: Nullable; - /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ - noiseStrength: Vector3; + toString(fullDetails?: boolean): string; + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + private _markSubMeshesAsDirty; + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + /** - * Gets or sets the billboard mode to use when isBillboardBased = true. - * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far - */ - billboardMode: number; - private _isAnimationSheetEnabled; + * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0) + */ + scaling: Vector3; /** - * Gets whether an animation sprite sheet is enabled or not on the particle system + * Disables the mesh edge rendering mode + * @returns the currentAbstractMesh */ - readonly isAnimationSheetEnabled: boolean; + disableEdgesRendering(): AbstractMesh; /** - * Is this system ready to be used/rendered - * @return true if the system is ready + * Enables the edge rendering mode on the mesh. + * This mode makes the mesh edges visible + * @param epsilon defines the maximal distance between two angles to detect a face + * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces + * @returns the currentAbstractMesh + * @see https://www.babylonjs-playground.com/#19O9TU#0 */ - isReady(): boolean; + enableEdgesRendering(epsilon?: number, checkVerticesInsteadOfIndices?: boolean): AbstractMesh; /** - * Gets Wether the system has been started. - * @returns True if it has been started, otherwise false. + * Gets the edgesRenderer associated with the mesh */ - isStarted(): boolean; + readonly edgesRenderer: Nullable; /** - * Starts the particle system and begins to emit - * @param delay defines the delay in milliseconds before starting the system (0 by default) + * Returns true if the mesh is blocked. Implemented by child classes */ - start(delay?: number): void; + readonly isBlocked: boolean; /** - * Stops the particle system. + * Returns the mesh itself by default. Implemented by child classes + * @param camera defines the camera to use to pick the right LOD level + * @returns the currentAbstractMesh */ - stop(): void; + getLOD(camera: Camera): Nullable; /** - * Remove all active particles + * Returns 0 by default. Implemented by child classes + * @returns an integer */ - reset(): void; + getTotalVertices(): number; /** - * Returns the string "GPUParticleSystem" - * @returns a string containing the class name + * Returns null by default. Implemented by child classes + * @returns null */ - getClassName(): string; - private _isBillboardBased; + getIndices(): Nullable; /** - * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction + * Returns the array of the requested vertex data kind. Implemented by child classes + * @param kind defines the vertex data kind to use + * @returns null */ - isBillboardBased: boolean; - private _colorGradients; - private _colorGradientsTexture; + getVerticesData(kind: string): Nullable; /** - * Gets the current list of color gradients. - * You must use addColorGradient and removeColorGradient to udpate this list - * @returns the list of color gradients + * Sets the vertex data of the mesh geometry for the requested `kind`. + * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. + * Note that a new underlying VertexBuffer object is created each call. + * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. + * @param kind defines vertex data kind: + * * BABYLON.VertexBuffer.PositionKind + * * BABYLON.VertexBuffer.UVKind + * * BABYLON.VertexBuffer.UV2Kind + * * BABYLON.VertexBuffer.UV3Kind + * * BABYLON.VertexBuffer.UV4Kind + * * BABYLON.VertexBuffer.UV5Kind + * * BABYLON.VertexBuffer.UV6Kind + * * BABYLON.VertexBuffer.ColorKind + * * BABYLON.VertexBuffer.MatricesIndicesKind + * * BABYLON.VertexBuffer.MatricesIndicesExtraKind + * * BABYLON.VertexBuffer.MatricesWeightsKind + * * BABYLON.VertexBuffer.MatricesWeightsExtraKind + * @param data defines the data source + * @param updatable defines if the data must be flagged as updatable (or static) + * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind + * @returns the current mesh */ - getColorGradients(): Nullable>; + setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): AbstractMesh; /** - * Gets the current list of size gradients. - * You must use addSizeGradient and removeSizeGradient to udpate this list - * @returns the list of size gradients + * Updates the existing vertex data of the mesh geometry for the requested `kind`. + * If the mesh has no geometry, it is simply returned as it is. + * @param kind defines vertex data kind: + * * BABYLON.VertexBuffer.PositionKind + * * BABYLON.VertexBuffer.UVKind + * * BABYLON.VertexBuffer.UV2Kind + * * BABYLON.VertexBuffer.UV3Kind + * * BABYLON.VertexBuffer.UV4Kind + * * BABYLON.VertexBuffer.UV5Kind + * * BABYLON.VertexBuffer.UV6Kind + * * BABYLON.VertexBuffer.ColorKind + * * BABYLON.VertexBuffer.MatricesIndicesKind + * * BABYLON.VertexBuffer.MatricesIndicesExtraKind + * * BABYLON.VertexBuffer.MatricesWeightsKind + * * BABYLON.VertexBuffer.MatricesWeightsExtraKind + * @param data defines the data source + * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed + * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh + * @returns the current mesh */ - getSizeGradients(): Nullable>; + updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): AbstractMesh; /** - * Gets the current list of angular speed gradients. - * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list - * @returns the list of angular speed gradients + * Sets the mesh indices, + * If the mesh has no geometry, a new Geometry object is created and set to the mesh. + * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array) + * @param totalVertices Defines the total number of vertices + * @returns the current mesh */ - getAngularSpeedGradients(): Nullable>; + setIndices(indices: IndicesArray, totalVertices: Nullable): AbstractMesh; /** - * Gets the current list of velocity gradients. - * You must use addVelocityGradient and removeVelocityGradient to udpate this list - * @returns the list of angular speed gradients + * Gets a boolean indicating if specific vertex data is present + * @param kind defines the vertex data kind to use + * @returns true is data kind is present */ - getVelocityGradients(): Nullable>; - private _removeGradient(gradient, gradients, texture); + isVerticesDataPresent(kind: string): boolean; /** - * Adds a new color gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param color defines the color to affect to the specified gradient - * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from - * @returns the current particle system + * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined + * @returns a BoundingInfo */ - addColorGradient(gradient: number, color1: Color4, color2?: Color4): GPUParticleSystem; + getBoundingInfo(): BoundingInfo; /** - * Remove a specific color gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units) + * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box + * @returns the current mesh */ - removeColorGradient(gradient: number): GPUParticleSystem; - private _angularSpeedGradients; - private _angularSpeedGradientsTexture; - private _sizeGradients; - private _sizeGradientsTexture; - private _velocityGradients; - private _velocityGradientsTexture; - private _addFactorGradient(factorGradients, gradient, factor); + normalizeToUnitCube(includeDescendants?: boolean): AbstractMesh; /** - * Adds a new size gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @returns the current particle system + * Overwrite the current bounding info + * @param boundingInfo defines the new bounding info + * @returns the current mesh */ - addSizeGradient(gradient: number, factor: number): GPUParticleSystem; + setBoundingInfo(boundingInfo: BoundingInfo): AbstractMesh; + /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */ + readonly useBones: boolean; + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + /** - * Remove a specific size gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Gets the current world matrix + * @returns a Matrix */ - removeSizeGradient(gradient: number): GPUParticleSystem; + getWorldMatrix(): Matrix; + /** @hidden */ + /** - * Adds a new angular speed gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @returns the current particle system + * Perform relative position change from the point of view of behind the front of the mesh. + * This is performed taking into account the meshes current rotation, so you do not have to care. + * Supports definition of mesh facing forward or backward + * @param amountRight defines the distance on the right axis + * @param amountUp defines the distance on the up axis + * @param amountForward defines the distance on the forward axis + * @returns the current mesh */ - addAngularSpeedGradient(gradient: number, factor: number): GPUParticleSystem; + movePOV(amountRight: number, amountUp: number, amountForward: number): AbstractMesh; /** - * Remove a specific angular speed gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Calculate relative position change from the point of view of behind the front of the mesh. + * This is performed taking into account the meshes current rotation, so you do not have to care. + * Supports definition of mesh facing forward or backward + * @param amountRight defines the distance on the right axis + * @param amountUp defines the distance on the up axis + * @param amountForward defines the distance on the forward axis + * @returns the new displacement vector */ - removeAngularSpeedGradient(gradient: number): GPUParticleSystem; + calcMovePOV(amountRight: number, amountUp: number, amountForward: number): Vector3; /** - * Adds a new velocity gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @returns the current particle system + * Perform relative rotation change from the point of view of behind the front of the mesh. + * Supports definition of mesh facing forward or backward + * @param flipBack defines the flip + * @param twirlClockwise defines the twirl + * @param tiltRight defines the tilt + * @returns the current mesh */ - addVelocityGradient(gradient: number, factor: number): GPUParticleSystem; + rotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): AbstractMesh; /** - * Remove a specific velocity gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Calculate relative rotation change from the point of view of behind the front of the mesh. + * Supports definition of mesh facing forward or backward. + * @param flipBack defines the flip + * @param twirlClockwise defines the twirl + * @param tiltRight defines the tilt + * @returns the new rotation vector */ - removeVelocityGradient(gradient: number): GPUParticleSystem; + calcRotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): Vector3; /** - * Instantiates a GPU particle system. - * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. - * @param name The name of the particle system - * @param options The options used to create the system - * @param scene The scene the particle system belongs to - * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture + * Return the minimum and maximum world vectors of the entire hierarchy under current mesh + * @param includeDescendants Include bounding info from descendants as well (true by default) + * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors + * @returns the new bounding vectors */ - constructor(name: string, options: Partial<{ - capacity: number; - randomTextureSize: number; - }>, scene: Scene, isAnimationSheetEnabled?: boolean); - private _createUpdateVAO(source); - private _createRenderVAO(source, spriteSource); - private _initialize(force?); + getHierarchyBoundingVectors(includeDescendants?: boolean, predicate?: Nullable<(abstractMesh: AbstractMesh) => boolean>): { + min: Vector3; + max: Vector3; + }; /** @hidden */ /** @hidden */ + /** @hidden */ + protected _afterComputeWorldMatrix(): void; /** - * Animates the particle system for the current frame by emitting new particles and or animating the living ones. - * @param preWarm defines if we are in the pre-warmimg phase - */ - animate(preWarm?: boolean): void; - private _createFactorGradientTexture(factorGradients, textureName); - private _createSizeGradientTexture(); - private _createAngularSpeedGradientTexture(); - private _createVelocityGradientTexture(); - private _createColorGradientTexture(); - /** - * Renders the particle system in its current state - * @param preWarm defines if the system should only update the particles but not render them - * @returns the current number of particles - */ - render(preWarm?: boolean): number; - /** - * Rebuilds the particle system + * Returns `true` if the mesh is within the frustum defined by the passed array of planes. + * A mesh is in the frustum if its bounding box intersects the frustum + * @param frustumPlanes defines the frustum to test + * @returns true if the mesh is in the frustum planes */ - rebuild(): void; - private _releaseBuffers(); - private _releaseVAOs(); + isInFrustum(frustumPlanes: Plane[]): boolean; /** - * Disposes the particle system and free the associated resources - * @param disposeTexture defines if the particule texture must be disposed as well (true by default) + * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes. + * A mesh is completely in the frustum if its bounding box it completely inside the frustum. + * @param frustumPlanes defines the frustum to test + * @returns true if the mesh is completely in the frustum planes */ - dispose(disposeTexture?: boolean): void; + isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; /** - * Clones the particle system. - * @param name The name of the cloned object - * @param newEmitter The new emitter to use - * @returns the cloned particle system + * True if the mesh intersects another mesh or a SolidParticle object + * @param mesh defines a target mesh or SolidParticle to test + * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes) + * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes + * @returns true if there is an intersection */ - clone(name: string, newEmitter: any): Nullable; + intersectsMesh(mesh: AbstractMesh | SolidParticle, precise?: boolean, includeDescendants?: boolean): boolean; /** - * Serializes the particle system to a JSON object. - * @returns the JSON object + * Returns true if the passed point (Vector3) is inside the mesh bounding box + * @param point defines the point to test + * @returns true if there is an intersection */ - serialize(): any; + intersectsPoint(point: Vector3): boolean; /** - * Parses a JSON object to create a GPU particle system. - * @param parsedParticleSystem The JSON object to parse - * @param scene The scene to create the particle system in - * @param rootUrl The root url to use to load external dependencies like texture - * @returns the parsed GPU particle system + * Gets the current physics impostor + * @see http://doc.babylonjs.com/features/physics_engine + * @returns a physics impostor or null */ - static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): GPUParticleSystem; - } -} - -declare module BABYLON { - /** - * Interface representing a particle system in Babylon.js. - * This groups the common functionalities that needs to be implemented in order to create a particle system. - * A particle system represents a way to manage particles from their emission to their animation and rendering. - */ - interface IParticleSystem { + getPhysicsImpostor(): Nullable; /** - * List of animations used by the particle system. + * Gets the position of the current mesh in camera space + * @param camera defines the camera to use + * @returns a position */ - animations: Animation[]; + getPositionInCameraSpace(camera?: Nullable): Vector3; /** - * The id of the Particle system. + * Returns the distance from the mesh to the active camera + * @param camera defines the camera to use + * @returns the distance */ - id: string; + getDistanceToCamera(camera?: Nullable): number; /** - * The name of the Particle system. + * Apply a physic impulse to the mesh + * @param force defines the force to apply + * @param contactPoint defines where to apply the force + * @returns the current mesh + * @see http://doc.babylonjs.com/how_to/using_the_physics_engine */ - name: string; + applyImpulse(force: Vector3, contactPoint: Vector3): AbstractMesh; /** - * The emitter represents the Mesh or position we are attaching the particle system to. + * Creates a physic joint between two meshes + * @param otherMesh defines the other mesh to use + * @param pivot1 defines the pivot to use on this mesh + * @param pivot2 defines the pivot to use on the other mesh + * @param options defines additional options (can be plugin dependent) + * @returns the current mesh + * @see https://www.babylonjs-playground.com/#0BS5U0#0 */ - emitter: Nullable; + setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3, options?: any): AbstractMesh; /** - * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction + * Gets or sets a boolean indicating that this mesh can be used in the collision engine + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ - isBillboardBased: boolean; + checkCollisions: boolean; /** - * The rendering group used by the Particle system to chose when to render. + * Gets Collider object used to compute collisions (not physics) + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ - renderingGroupId: number; + readonly collider: Collider; /** - * The layer mask we are rendering the particles through. + * Move the mesh using collision engine + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity + * @param displacement defines the requested displacement vector + * @returns the current mesh */ - layerMask: number; + moveWithCollisions(displacement: Vector3): AbstractMesh; + private _onCollisionPositionChange; /** - * The overall motion speed (0.01 is default update speed, faster updates = faster animation) + * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations. + * Please note that you must have a decent number of submeshes to get performance improvements when using an octree + * @param maxCapacity defines the maximum size of each block (64 by default) + * @param maxDepth defines the maximum depth to use (no more than 2 levels by default) + * @returns the new octree + * @see https://www.babylonjs-playground.com/#NA4OQ#12 + * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees */ - updateSpeed: number; - /** - * The amount of time the particle system is running (depends of the overall update speed). - */ - targetStopDuration: number; + createOrUpdateSubmeshesOctree(maxCapacity?: number, maxDepth?: number): Octree; + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + /** - * The texture used to render each particle. (this can be a spritesheet) + * Checks if the passed Ray intersects with the mesh + * @param ray defines the ray to use + * @param fastCheck defines if fast mode (but less precise) must be used (false by default) + * @returns the picking info + * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh */ - particleTexture: Nullable; + intersects(ray: Ray, fastCheck?: boolean): PickingInfo; /** - * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE, ParticleSystem.BLENDMODE_STANDARD or ParticleSystem.BLENDMODE_ADD. + * Clones the current mesh + * @param name defines the mesh name + * @param newParent defines the new mesh parent + * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default) + * @returns the new mesh */ - blendMode: number; + clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable; /** - * Minimum life time of emitting particles. + * Disposes all the submeshes of the current meshnp + * @returns the current mesh */ - minLifeTime: number; + releaseSubMeshes(): AbstractMesh; /** - * Maximum life time of emitting particles. + * Releases resources associated with this abstract mesh. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) */ - maxLifeTime: number; + dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; /** - * Minimum Size of emitting particles. + * Adds the passed mesh as a child to the current mesh + * @param mesh defines the child mesh + * @returns the current mesh */ - minSize: number; + addChild(mesh: AbstractMesh): AbstractMesh; /** - * Maximum Size of emitting particles. + * Removes the passed mesh from the current mesh children list + * @param mesh defines the child mesh + * @returns the current mesh */ - maxSize: number; + removeChild(mesh: AbstractMesh): AbstractMesh; + /** @hidden */ + private _initFacetData; /** - * Minimum scale of emitting particles on X axis. + * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated. + * This method can be called within the render loop. + * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation + * @returns the current mesh + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - minScaleX: number; + updateFacetData(): AbstractMesh; /** - * Maximum scale of emitting particles on X axis. + * Returns the facetLocalNormals array. + * The normals are expressed in the mesh local spac + * @returns an array of Vector3 + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - maxScaleX: number; + getFacetLocalNormals(): Vector3[]; /** - * Minimum scale of emitting particles on Y axis. + * Returns the facetLocalPositions array. + * The facet positions are expressed in the mesh local space + * @returns an array of Vector3 + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - minScaleY: number; + getFacetLocalPositions(): Vector3[]; /** - * Maximum scale of emitting particles on Y axis. + * Returns the facetLocalPartioning array + * @returns an array of array of numbers + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - maxScaleY: number; + getFacetLocalPartitioning(): number[][]; /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors. + * Returns the i-th facet position in the world system. + * This method allocates a new Vector3 per call + * @param i defines the facet index + * @returns a new Vector3 + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - color1: Color4; + getFacetPosition(i: number): Vector3; /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors. + * Sets the reference Vector3 with the i-th facet position in the world system + * @param i defines the facet index + * @param ref defines the target vector + * @returns the current mesh + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - color2: Color4; + getFacetPositionToRef(i: number, ref: Vector3): AbstractMesh; /** - * Color the particle will have at the end of its lifetime. + * Returns the i-th facet normal in the world system. + * This method allocates a new Vector3 per call + * @param i defines the facet index + * @returns a new Vector3 + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - colorDead: Color4; + getFacetNormal(i: number): Vector3; /** - * The maximum number of particles to emit per frame until we reach the activeParticleCount value + * Sets the reference Vector3 with the i-th facet normal in the world system + * @param i defines the facet index + * @param ref defines the target vector + * @returns the current mesh + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - emitRate: number; + getFacetNormalToRef(i: number, ref: Vector3): this; /** - * You can use gravity if you want to give an orientation to your particles. + * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system) + * @param x defines x coordinate + * @param y defines y coordinate + * @param z defines z coordinate + * @returns the array of facet indexes + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - gravity: Vector3; + getFacetsAtLocalCoordinates(x: number, y: number, z: number): Nullable; /** - * Minimum power of emitting particles. + * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found + * @param projected sets as the (x,y,z) world projection on the facet + * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned + * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position + * @param x defines x coordinate + * @param y defines y coordinate + * @param z defines z coordinate + * @returns the face index if found (or null instead) + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - minEmitPower: number; + getClosestFacetAtCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace?: boolean, facing?: boolean): Nullable; /** - * Maximum power of emitting particles. + * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found + * @param projected sets as the (x,y,z) local projection on the facet + * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned + * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position + * @param x defines x coordinate + * @param y defines y coordinate + * @param z defines z coordinate + * @returns the face index if found (or null instead) + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - maxEmitPower: number; + getClosestFacetAtLocalCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace?: boolean, facing?: boolean): Nullable; /** - * Minimum angular speed of emitting particles (Z-axis rotation for each particle). + * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals() + * @returns the parameters + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - minAngularSpeed: number; + getFacetDataParameters(): any; /** - * Maximum angular speed of emitting particles (Z-axis rotation for each particle). + * Disables the feature FacetData and frees the related memory + * @returns the current mesh + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - maxAngularSpeed: number; + disableFacetData(): AbstractMesh; /** - * Gets or sets the minimal initial rotation in radians. + * Updates the AbstractMesh indices array + * @param indices defines the data source + * @returns the current mesh */ - minInitialRotation: number; + updateIndices(indices: IndicesArray): AbstractMesh; /** - * Gets or sets the maximal initial rotation in radians. + * Creates new normals data for the mesh + * @param updatable defines if the normal vertex buffer must be flagged as updatable + * @returns the current mesh */ - maxInitialRotation: number; + createNormals(updatable: boolean): AbstractMesh; /** - * The particle emitter type defines the emitter used by the particle system. - * It can be for example box, sphere, or cone... + * Align the mesh with a normal + * @param normal defines the normal to use + * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default) + * @returns the current mesh */ - particleEmitterType: Nullable; + alignWithNormal(normal: Vector3, upDirection?: Vector3): AbstractMesh; + /** @hidden */ + + } +} + +declare module BABYLON { + class Buffer { + private _engine; + private _buffer; + /** @hidden */ + + private _updatable; + private _instanced; /** - * Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 + * Gets the byte stride. */ - preWarmCycles: number; + readonly byteStride: number; /** - * Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) + * Constructor + * @param engine the engine + * @param data the data to use for this buffer + * @param updatable whether the data is updatable + * @param stride the stride (optional) + * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional) + * @param instanced whether the buffer is instanced (optional) + * @param useBytes set to true if the stride in in bytes (optional) */ - preWarmStepOffset: number; + constructor(engine: any, data: DataArray, updatable: boolean, stride?: number, postponeInternalCreation?: boolean, instanced?: boolean, useBytes?: boolean); /** - * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime) + * Create a new {BABYLON.VertexBuffer} based on the current buffer + * @param kind defines the vertex buffer kind (position, normal, etc.) + * @param offset defines offset in the buffer (0 by default) + * @param size defines the size in floats of attributes (position is 3 for instance) + * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved) + * @param instanced defines if the vertex buffer contains indexed data + * @param useBytes defines if the offset and stride are in bytes + * @returns the new vertex buffer */ - spriteCellChangeSpeed: number; + createVertexBuffer(kind: string, offset: number, size: number, stride?: number, instanced?: boolean, useBytes?: boolean): VertexBuffer; + isUpdatable(): boolean; + getData(): Nullable; + getBuffer(): Nullable; /** - * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display + * Gets the stride in float32 units (i.e. byte stride / 4). + * May not be an integer if the byte stride is not divisible by 4. + * DEPRECATED. Use byteStride instead. + * @returns the stride in float32 units */ - startSpriteCellID: number; + getStrideSize(): number; + create(data?: Nullable): void; + + update(data: DataArray): void; /** - * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display + * Updates the data directly. + * @param data the new data + * @param offset the new offset + * @param vertexCount the vertex count (optional) + * @param useBytes set to true if the offset is in bytes */ - endSpriteCellID: number; + updateDirectly(data: DataArray, offset: number, vertexCount?: number, useBytes?: boolean): void; + dispose(): void; + } +} + +declare module BABYLON { + class CSG { + private polygons; + matrix: Matrix; + position: Vector3; + rotation: Vector3; + rotationQuaternion: Nullable; + scaling: Vector3; + static FromMesh(mesh: Mesh): CSG; + private static FromPolygons; + clone(): CSG; + union(csg: CSG): CSG; + unionInPlace(csg: CSG): void; + subtract(csg: CSG): CSG; + subtractInPlace(csg: CSG): void; + intersect(csg: CSG): CSG; + intersectInPlace(csg: CSG): void; + inverse(): CSG; + inverseInPlace(): void; + copyTransformAttributes(csg: CSG): CSG; + buildMeshGeometry(name: string, scene: Scene, keepSubMeshes: boolean): Mesh; + toMesh(name: string, material: Nullable, scene: Scene, keepSubMeshes: boolean): Mesh; + } +} + +declare module BABYLON { + /** + * Class used to store geometry data (vertex buffers + index buffer) + */ + class Geometry implements IGetSetVerticesData { /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use + * Gets or sets the unique ID of the geometry */ - spriteCellWidth: number; + id: string; /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use + * Gets the delay loading state of the geometry (none by default which means not delayed) */ - spriteCellHeight: number; - /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ - translationPivot: Vector2; + delayLoadState: number; /** - * Gets or sets a texture used to add random noise to particle positions + * Gets the file containing the data to load when running in delay load state */ - noiseTexture: Nullable; - /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ - noiseStrength: Vector3; + delayLoadingFile: Nullable; /** - * Gets or sets the billboard mode to use when isBillboardBased = true. - * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far + * Callback called when the geometry is updated */ - billboardMode: number; + onGeometryUpdated: (geometry: Geometry, kind?: string) => void; + private _scene; + private _engine; + private _meshes; + private _totalVertices; + /** @hidden */ + + /** @hidden */ +; + private _isDisposed; + private _extend; + private _boundingBias; + /** @hidden */ + + private _indexBuffer; + private _indexBufferIsUpdatable; + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + private _vertexArrayObjects; + private _updatable; + /** @hidden */ + /** - * Gets the maximum number of particles active at the same time. - * @returns The max number of active particles. + * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y */ - getCapacity(): number; /** - * Gets Wether the system has been started. - * @returns True if it has been started, otherwise false. - */ - isStarted(): boolean; + * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y + */ + boundingBias: Vector2; /** - * Gets if the particle system has been started. - * @return true if the system has been started, otherwise false. + * Static function used to attach a new empty geometry to a mesh + * @param mesh defines the mesh to attach the geometry to + * @returns the new {BABYLON.Geometry} */ - isStarted(): boolean; + static CreateGeometryForMesh(mesh: Mesh): Geometry; /** - * Animates the particle system for this frame. + * Creates a new geometry + * @param id defines the unique ID + * @param scene defines the hosting scene + * @param vertexData defines the {BABYLON.VertexData} used to get geometry data + * @param updatable defines if geometry must be updatable (false by default) + * @param mesh defines the mesh that will be associated with the geometry */ - animate(): void; + constructor(id: string, scene: Scene, vertexData?: VertexData, updatable?: boolean, mesh?: Nullable); /** - * Renders the particle system in its current state. - * @returns the current number of particles + * Gets the current extend of the geometry */ - render(): number; + readonly extend: { + minimum: Vector3; + maximum: Vector3; + }; /** - * Dispose the particle system and frees its associated resources. - * @param disposeTexture defines if the particule texture must be disposed as well (true by default) + * Gets the hosting scene + * @returns the hosting {BABYLON.Scene} */ - dispose(disposeTexture?: boolean): void; + getScene(): Scene; /** - * Clones the particle system. - * @param name The name of the cloned object - * @param newEmitter The new emitter to use - * @returns the cloned particle system + * Gets the hosting engine + * @returns the hosting {BABYLON.Engine} */ - clone(name: string, newEmitter: any): Nullable; + getEngine(): Engine; /** - * Serializes the particle system to a JSON object. - * @returns the JSON object + * Defines if the geometry is ready to use + * @returns true if the geometry is ready to be used */ - serialize(): any; + isReady(): boolean; /** - * Rebuild the particle system + * Gets a value indicating that the geometry should not be serialized */ - rebuild(): void; + readonly doNotSerialize: boolean; + /** @hidden */ + /** - * Starts the particle system and begins to emit - * @param delay defines the delay in milliseconds before starting the system (0 by default) + * Affects all geometry data in one call + * @param vertexData defines the geometry data + * @param updatable defines if the geometry must be flagged as updatable (false as default) */ - start(delay?: number): void; + setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; /** - * Stops the particle system. + * Set specific vertex data + * @param kind defines the data kind (Position, normal, etc...) + * @param data defines the vertex data to use + * @param updatable defines if the vertex must be flagged as updatable (false as default) + * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified */ - stop(): void; + setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): void; /** - * Remove all active particles + * Removes a specific vertex data + * @param kind defines the data kind (Position, normal, etc...) */ - reset(): void; + removeVerticesData(kind: string): void; /** - * Is this system ready to be used/rendered - * @return true if the system is ready + * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data + * @param buffer defines the vertex buffer to use + * @param totalVertices defines the total number of vertices for position kind (could be null) */ - isReady(): boolean; + setVerticesBuffer(buffer: VertexBuffer, totalVertices?: Nullable): void; /** - * Adds a new color gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param color defines the color to affect to the specified gradient - * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from - * @returns the current particle system + * Update a specific vertex buffer + * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array + * It will do nothing if the buffer is not updatable + * @param kind defines the data kind (Position, normal, etc...) + * @param data defines the data to use + * @param offset defines the offset in the target buffer where to store the data + * @param useBytes set to true if the offset is in bytes */ - addColorGradient(gradient: number, color1: Color4, color2?: Color4): IParticleSystem; + updateVerticesDataDirectly(kind: string, data: DataArray, offset: number, useBytes?: boolean): void; /** - * Remove a specific color gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Update a specific vertex buffer + * This function will create a new buffer if the current one is not updatable + * @param kind defines the data kind (Position, normal, etc...) + * @param data defines the data to use + * @param updateExtends defines if the geometry extends must be recomputed (false by default) */ - removeColorGradient(gradient: number): IParticleSystem; + updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean): void; + private _updateBoundingInfo; + /** @hidden */ + /** - * Adds a new size gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * Gets total number of vertices + * @returns the total number of vertices */ - addSizeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem; + getTotalVertices(): number; /** - * Remove a specific size gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly. + * @param kind defines the data kind (Position, normal, etc...) + * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes + * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it + * @returns a float array containing vertex data */ - removeSizeGradient(gradient: number): IParticleSystem; + getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable; /** - * Gets the current list of color gradients. - * You must use addColorGradient and removeColorGradient to udpate this list - * @returns the list of color gradients + * Returns a boolean defining if the vertex data for the requested `kind` is updatable + * @param kind defines the data kind (Position, normal, etc...) + * @returns true if the vertex buffer with the specified kind is updatable */ - getColorGradients(): Nullable>; + isVertexBufferUpdatable(kind: string): boolean; /** - * Gets the current list of size gradients. - * You must use addSizeGradient and removeSizeGradient to udpate this list - * @returns the list of size gradients + * Gets a specific vertex buffer + * @param kind defines the data kind (Position, normal, etc...) + * @returns a {BABYLON.VertexBuffer} */ - getSizeGradients(): Nullable>; + getVertexBuffer(kind: string): Nullable; /** - * Gets the current list of angular speed gradients. - * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list - * @returns the list of angular speed gradients + * Returns all vertex buffers + * @return an object holding all vertex buffers indexed by kind */ - getAngularSpeedGradients(): Nullable>; + getVertexBuffers(): Nullable<{ + [key: string]: VertexBuffer; + }>; /** - * Adds a new angular speed gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * Gets a boolean indicating if specific vertex buffer is present + * @param kind defines the data kind (Position, normal, etc...) + * @returns true if data is present */ - addAngularSpeedGradient(gradient: number, factor: number, factor2?: number): IParticleSystem; + isVerticesDataPresent(kind: string): boolean; /** - * Remove a specific angular speed gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Gets a list of all attached data kinds (Position, normal, etc...) + * @returns a list of string containing all kinds */ - removeAngularSpeedGradient(gradient: number): IParticleSystem; + getVerticesDataKinds(): string[]; /** - * Gets the current list of velocity gradients. - * You must use addVelocityGradient and removeVelocityGradient to udpate this list - * @returns the list of velocity gradients + * Update index buffer + * @param indices defines the indices to store in the index buffer + * @param offset defines the offset in the target buffer where to store the data */ - getVelocityGradients(): Nullable>; + updateIndices(indices: IndicesArray, offset?: number): void; /** - * Adds a new velocity gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * Creates a new index buffer + * @param indices defines the indices to store in the index buffer + * @param totalVertices defines the total number of vertices (could be null) + * @param updatable defines if the index buffer must be flagged as updatable (false by default) */ - addVelocityGradient(gradient: number, factor: number, factor2?: number): IParticleSystem; + setIndices(indices: IndicesArray, totalVertices?: Nullable, updatable?: boolean): void; /** - * Remove a specific velocity gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Return the total number of indices + * @returns the total number of indices */ - removeVelocityGradient(gradient: number): IParticleSystem; - } -} - -declare module BABYLON { - /** - * A particle represents one of the element emitted by a particle system. - * This is mainly define by its coordinates, direction, velocity and age. - */ - class Particle { + getTotalIndices(): number; /** - * particleSystem the particle system the particle belongs to. + * Gets the index buffer array + * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes + * @returns the index buffer array */ - particleSystem: ParticleSystem; + getIndices(copyWhenShared?: boolean): Nullable; /** - * The world position of the particle in the scene. + * Gets the index buffer + * @return the index buffer */ - position: Vector3; + getIndexBuffer(): Nullable; + /** @hidden */ + /** - * The world direction of the particle in the scene. + * Release the associated resources for a specific mesh + * @param mesh defines the source mesh + * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it */ - direction: Vector3; + releaseForMesh(mesh: Mesh, shouldDispose?: boolean): void; /** - * The color of the particle. + * Apply current geometry to a given mesh + * @param mesh defines the mesh to apply geometry to */ - color: Color4; + applyToMesh(mesh: Mesh): void; + private _updateExtend; + private _applyToMesh; + private notifyUpdate; /** - * The color change of the particle per step. + * Load the geometry if it was flagged as delay loaded + * @param scene defines the hosting scene + * @param onLoaded defines a callback called when the geometry is loaded */ - colorStep: Color4; + load(scene: Scene, onLoaded?: () => void): void; + private _queueLoad; /** - * Defines how long will the life of the particle be. + * Invert the geometry to move from a right handed system to a left handed one. */ - lifeTime: number; + toLeftHanded(): void; + /** @hidden */ + + /** @hidden */ + /** - * The current age of the particle. - */ - age: number; - /** - * The current size of the particle. + * Gets a value indicating if the geometry is disposed + * @returns true if the geometry was disposed */ - size: number; + isDisposed(): boolean; + private _disposeVertexArrayObjects; /** - * The current scale of the particle. + * Free all associated resources */ - scale: Vector2; + dispose(): void; /** - * The current angle of the particle. + * Clone the current geometry into a new geometry + * @param id defines the unique ID of the new geometry + * @returns a new geometry object */ - angle: number; + copy(id: string): Geometry; /** - * Defines how fast is the angle changing. + * Serialize the current geometry info (and not the vertices data) into a JSON object + * @return a JSON representation of the current geometry data (without the vertices data) */ - angularSpeed: number; + serialize(): any; + private toNumberArray; /** - * Defines the cell index used by the particle to be rendered from a sprite. + * Serialize all vertices data into a JSON oject + * @returns a JSON representation of the current geometry data */ - cellIndex: number; - /** @hidden */ - - /** @hidden */ - - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - + serializeVerticeData(): any; /** - * Creates a new instance Particle - * @param particleSystem the particle system the particle belongs to + * Extracts a clone of a mesh geometry + * @param mesh defines the source mesh + * @param id defines the unique ID of the new geometry object + * @returns the new geometry object */ - constructor( - /** - * particleSystem the particle system the particle belongs to. - */ - particleSystem: ParticleSystem); - private updateCellInfoFromSystem(); + static ExtractFromMesh(mesh: Mesh, id: string): Nullable; /** - * Defines how the sprite cell index is updated for the particle + * You should now use Tools.RandomId(), this method is still here for legacy reasons. + * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 + * Be aware Math.random() could cause collisions, but: + * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide" + * @returns a string containing a new GUID */ - updateCellIndex(): void; + static RandomId(): string; + /** @hidden */ +private static _ImportGeometry(parsedGeometry: any, mesh: Mesh): void; + private static _CleanMatricesWeights; /** - * Copy the properties of particle to another one. - * @param other the particle to copy the information to. + * Create a new geometry from persisted data (Using .babylon file format) + * @param parsedVertexData defines the persisted data + * @param scene defines the hosting scene + * @param rootUrl defines the root url to use to load assets (like delayed data) + * @returns the new geometry object */ - copyTo(other: Particle): void; + static Parse(parsedVertexData: any, scene: Scene, rootUrl: string): Nullable; } -} - -declare module BABYLON { /** - * This class is made for on one-liner static method to help creating particle system set. + * Abstract class used to provide common services for all typed geometries + * @hidden */ - class ParticleHelper { + class _PrimitiveGeometry extends Geometry { + private _canBeRegenerated; + private _beingRegenerated; /** - * Gets or sets base Assets URL + * Creates a new typed geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) */ - static BaseAssetsUrl: string; + constructor(id: string, scene: Scene, _canBeRegenerated?: boolean, mesh?: Nullable); /** - * Create a default particle system that you can tweak - * @param emitter defines the emitter to use - * @param capacity defines the system capacity (default is 500 particles) - * @param scene defines the hosting scene - * @returns the new Particle system + * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default) + * @returns true if the geometry can be regenerated */ - static CreateDefault(emitter: Nullable, capacity?: number, scene?: Scene): ParticleSystem; + canBeRegenerated(): boolean; /** - * This is the main static method (one-liner) of this helper to create different particle systems - * @param type This string represents the type to the particle system to create - * @param scene The scene where the particle system should live - * @param gpu If the system will use gpu - * @returns the ParticleSystemSet created + * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values */ - static CreateAsync(type: string, scene: Nullable, gpu?: boolean): Promise; + regenerate(): void; /** - * Static function used to export a particle system to a ParticleSystemSet variable. - * Please note that the emitter shape is not exported - * @param system defines the particle systems to export + * Clone the geometry + * @param id defines the unique ID of the new geometry + * @returns the new geometry */ - static ExportSet(systems: IParticleSystem[]): ParticleSystemSet; - } -} + asNewGeometry(id: string): Geometry; + setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; + setVerticesData(kind: string, data: FloatArray, updatable?: boolean): void; + /** @hidden */ -declare module BABYLON { + copy(id: string): Geometry; + serialize(): any; + } /** - * This represents a particle system in Babylon. - * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. - * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function. - * @example https://doc.babylonjs.com/babylon101/particles + * Creates a ribbon geometry + * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons */ - class ParticleSystem implements IDisposable, IAnimatable, IParticleSystem { - /** - * Source color is added to the destination color without alpha affecting the result. - */ - static BLENDMODE_ONEONE: number; + class RibbonGeometry extends _PrimitiveGeometry { /** - * Blend current color and particle color using particle’s alpha. + * Defines the array of paths to use */ - static BLENDMODE_STANDARD: number; + pathArray: Vector3[][]; /** - * Add current color and particle color multiplied by particle’s alpha. + * Defines if the last and first points of each path in your pathArray must be joined */ - static BLENDMODE_ADD: number; + closeArray: boolean; /** - * List of animations used by the particle system. + * Defines if the last and first points of each path in your pathArray must be joined */ - animations: Animation[]; + closePath: boolean; /** - * The id of the Particle system. + * Defines the offset between points */ - id: string; + offset: number; /** - * The friendly name of the Particle system. + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - name: string; + side: number; /** - * The rendering group used by the Particle system to chose when to render. + * Creates a ribbon geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param pathArray defines the array of paths to use + * @param closeArray defines if the last path and the first path must be joined + * @param closePath defines if the last and first points of each path in your pathArray must be joined + * @param offset defines the offset between points + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - renderingGroupId: number; + constructor(id: string, scene: Scene, /** - * The emitter represents the Mesh or position we are attaching the particle system to. + * Defines the array of paths to use */ - emitter: Nullable; + pathArray: Vector3[][], /** - * The maximum number of particles to emit per frame + * Defines if the last and first points of each path in your pathArray must be joined */ - emitRate: number; + closeArray: boolean, /** - * If you want to launch only a few particles at once, that can be done, as well. + * Defines if the last and first points of each path in your pathArray must be joined */ - manualEmitCount: number; + closePath: boolean, /** - * The overall motion speed (0.01 is default update speed, faster updates = faster animation) + * Defines the offset between points */ - updateSpeed: number; + offset: number, canBeRegenerated?: boolean, mesh?: Mesh, /** - * The amount of time the particle system is running (depends of the overall update speed). + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - targetStopDuration: number; + side?: number); + /** @hidden */ + + copy(id: string): Geometry; + } + /** + * Creates a box geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#box + */ + class BoxGeometry extends _PrimitiveGeometry { /** - * Specifies whether the particle system will be disposed once it reaches the end of the animation. + * Defines the zise of the box (width, height and depth are the same) */ - disposeOnStop: boolean; + size: number; /** - * Minimum power of emitting particles. + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - minEmitPower: number; + side: number; /** - * Maximum power of emitting particles. + * Creates a box geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param size defines the zise of the box (width, height and depth are the same) + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - maxEmitPower: number; + constructor(id: string, scene: Scene, /** - * Minimum life time of emitting particles. + * Defines the zise of the box (width, height and depth are the same) */ - minLifeTime: number; + size: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * Maximum life time of emitting particles. + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - maxLifeTime: number; + side?: number); + + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedBox: any, scene: Scene): Nullable; + } + /** + * Creates a sphere geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere + */ + class SphereGeometry extends _PrimitiveGeometry { /** - * Minimum Size of emitting particles. + * Defines the number of segments to use to create the sphere */ - minSize: number; + segments: number; /** - * Maximum Size of emitting particles. + * Defines the diameter of the sphere */ - maxSize: number; + diameter: number; /** - * Minimum scale of emitting particles on X axis. + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - minScaleX: number; + side: number; /** - * Maximum scale of emitting particles on X axis. + * Create a new sphere geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param segments defines the number of segments to use to create the sphere + * @param diameter defines the diameter of the sphere + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - maxScaleX: number; + constructor(id: string, scene: Scene, /** - * Minimum scale of emitting particles on Y axis. + * Defines the number of segments to use to create the sphere */ - minScaleY: number; + segments: number, /** - * Maximum scale of emitting particles on Y axis. + * Defines the diameter of the sphere */ - maxScaleY: number; + diameter: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * Gets or sets the minimal initial rotation in radians. + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - minInitialRotation: number; + side?: number); + + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedSphere: any, scene: Scene): Nullable; + } + /** + * Creates a disc geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon + */ + class DiscGeometry extends _PrimitiveGeometry { /** - * Gets or sets the maximal initial rotation in radians. + * Defines the radius of the disc */ - maxInitialRotation: number; + radius: number; /** - * Minimum angular speed of emitting particles (Z-axis rotation for each particle). + * Defines the tesselation factor to apply to the disc */ - minAngularSpeed: number; + tessellation: number; /** - * Maximum angular speed of emitting particles (Z-axis rotation for each particle). + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - maxAngularSpeed: number; + side: number; /** - * The texture used to render each particle. (this can be a spritesheet) + * Creates a new disc geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param radius defines the radius of the disc + * @param tessellation defines the tesselation factor to apply to the disc + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - particleTexture: Nullable; + constructor(id: string, scene: Scene, /** - * The layer mask we are rendering the particles through. + * Defines the radius of the disc */ - layerMask: number; + radius: number, /** - * This can help using your own shader to render the particle system. - * The according effect will be created + * Defines the tesselation factor to apply to the disc */ - customShader: any; + tessellation: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * By default particle system starts as soon as they are created. This prevents the - * automatic start to happen and let you decide when to start emitting particles. + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - preventAutoStart: boolean; + side?: number); + + copy(id: string): Geometry; + } + /** + * Creates a new cylinder geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone + */ + class CylinderGeometry extends _PrimitiveGeometry { /** - * Gets or sets a texture used to add random noise to particle positions + * Defines the height of the cylinder */ - noiseTexture: Nullable; - /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ - noiseStrength: Vector3; + height: number; /** - * This function can be defined to provide custom update for active particles. - * This function will be called instead of regular update (age, position, color, etc.). - * Do not forget that this function will be called on every frame so try to keep it simple and fast :) + * Defines the diameter of the cylinder's top cap */ - updateFunction: (particles: Particle[]) => void; + diameterTop: number; /** - * Callback triggered when the particle animation is ending. + * Defines the diameter of the cylinder's bottom cap */ - onAnimationEnd: Nullable<() => void>; + diameterBottom: number; /** - * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD. + * Defines the tessellation factor to apply to the cylinder */ - blendMode: number; + tessellation: number; /** - * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls - * to override the particles. + * Defines the number of subdivisions to apply to the cylinder (1 by default) */ - forceDepthWrite: boolean; + subdivisions: number; /** - * You can use gravity if you want to give an orientation to your particles. + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - gravity: Vector3; - private _emitterWorldMatrix; - private _colorGradients; - private _sizeGradients; - private _lifeTimeGradients; - private _angularSpeedGradients; - private _velocityGradients; + side: number; /** - * Gets the current list of color gradients. - * You must use addColorGradient and removeColorGradient to udpate this list - * @returns the list of color gradients + * Creates a new cylinder geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param height defines the height of the cylinder + * @param diameterTop defines the diameter of the cylinder's top cap + * @param diameterBottom defines the diameter of the cylinder's bottom cap + * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides) + * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default) + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - getColorGradients(): Nullable>; + constructor(id: string, scene: Scene, /** - * Gets the current list of size gradients. - * You must use addSizeGradient and removeSizeGradient to udpate this list - * @returns the list of size gradients + * Defines the height of the cylinder */ - getSizeGradients(): Nullable>; + height: number, /** - * Gets the current list of life time gradients. - * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list - * @returns the list of life time gradients + * Defines the diameter of the cylinder's top cap */ - getLifeTimeGradients(): Nullable>; + diameterTop: number, /** - * Gets the current list of angular speed gradients. - * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list - * @returns the list of angular speed gradients + * Defines the diameter of the cylinder's bottom cap */ - getAngularSpeedGradients(): Nullable>; + diameterBottom: number, /** - * Gets the current list of velocity gradients. - * You must use addVelocityGradient and removeVelocityGradient to udpate this list - * @returns the list of velocity gradients + * Defines the tessellation factor to apply to the cylinder */ - getVelocityGradients(): Nullable>; + tessellation: number, /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Defines the number of subdivisions to apply to the cylinder (1 by default) */ - direction1: Vector3; + subdivisions?: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - direction2: Vector3; + side?: number); + + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedCylinder: any, scene: Scene): Nullable; + } + /** + * Creates a new torus geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#torus + */ + class TorusGeometry extends _PrimitiveGeometry { /** - * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Defines the diameter of the torus */ - minEmitBox: Vector3; + diameter: number; /** - * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Defines the thickness of the torus (ie. internal diameter) */ - maxEmitBox: Vector3; + thickness: number; /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors + * Defines the tesselation factor to apply to the torus */ - color1: Color4; + tessellation: number; /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - color2: Color4; + side: number; /** - * Color the particle will have at the end of its lifetime + * Creates a new torus geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param diameter defines the diameter of the torus + * @param thickness defines the thickness of the torus (ie. internal diameter) + * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle) + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - colorDead: Color4; + constructor(id: string, scene: Scene, /** - * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel + * Defines the diameter of the torus */ - textureMask: Color4; + diameter: number, /** - * The particle emitter type defines the emitter used by the particle system. - * It can be for example box, sphere, or cone... + * Defines the thickness of the torus (ie. internal diameter) */ - particleEmitterType: IParticleEmitterType; + thickness: number, /** - * This function can be defined to specify initial direction for every new particle. - * It by default use the emitterType defined function + * Defines the tesselation factor to apply to the torus */ - startDirectionFunction: (worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle) => void; + tessellation: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * This function can be defined to specify initial position for every new particle. - * It by default use the emitterType defined function + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle) => void; + side?: number); + + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedTorus: any, scene: Scene): Nullable; + } + /** + * Creates a new ground geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#ground + */ + class GroundGeometry extends _PrimitiveGeometry { /** - * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime) + * Defines the width of the ground */ - spriteCellChangeSpeed: number; + width: number; /** - * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display + * Defines the height of the ground */ - startSpriteCellID: number; + height: number; /** - * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display + * Defines the subdivisions to apply to the ground */ - endSpriteCellID: number; + subdivisions: number; /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use + * Creates a new ground geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param width defines the width of the ground + * @param height defines the height of the ground + * @param subdivisions defines the subdivisions to apply to the ground + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) */ - spriteCellWidth: number; + constructor(id: string, scene: Scene, /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use + * Defines the width of the ground */ - spriteCellHeight: number; - /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */ - preWarmCycles: number; - /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */ - preWarmStepOffset: number; - /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ - translationPivot: Vector2; - /** - * An event triggered when the system is disposed - */ - onDisposeObservable: Observable; - private _onDisposeObserver; + width: number, /** - * Sets a callback that will be triggered when the system is disposed + * Defines the height of the ground */ - onDispose: () => void; + height: number, /** - * Gets or sets whether an animation sprite sheet is enabled or not on the particle system + * Defines the subdivisions to apply to the ground */ - isAnimationSheetEnabled: boolean; - /** - * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction - */ - isBillboardBased: boolean; - /** - * Get hosting scene - * @returns the scene - */ - getScene(): Scene; - /** - * Gets or sets the billboard mode to use when isBillboardBased = true. - * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far - */ - billboardMode: number; - private _particles; - private _epsilon; - private _capacity; - private _scene; - private _stockParticles; - private _newPartsExcess; - private _vertexData; - private _vertexBuffer; - private _vertexBuffers; - private _spriteBuffer; - private _indexBuffer; - private _effect; - private _customEffect; - private _cachedDefines; - private _scaledColorStep; - private _colorDiff; - private _scaledDirection; - private _scaledGravity; - private _currentRenderId; - private _alive; - private _useInstancing; - private _started; - private _stopped; - private _actualFrame; - private _scaledUpdateSpeed; - private _vertexBufferSize; - private _isAnimationSheetEnabled; - private _isBillboardBased; - /** - * this is the Sub-emitters templates that will be used to generate particle system when the particle dies, this property is used by the root particle system only. - */ - subEmitters: ParticleSystem[]; - /** - * The current active Sub-systems, this property is used by the root particle system only. - */ - activeSubSystems: Array; - private _rootParticleSystem; - /** - * Gets the current list of active particles - */ - readonly particles: Particle[]; - /** - * Returns the string "ParticleSystem" - * @returns a string containing the class name - */ - getClassName(): string; + subdivisions: number, canBeRegenerated?: boolean, mesh?: Nullable); + + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedGround: any, scene: Scene): Nullable; + } + /** + * Creates a tiled ground geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground + */ + class TiledGroundGeometry extends _PrimitiveGeometry { /** - * Instantiates a particle system. - * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. - * @param name The name of the particle system - * @param capacity The max number of particles alive at the same time - * @param scene The scene the particle system belongs to - * @param customEffect a custom effect used to change the way particles are rendered by default - * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture - * @param epsilon Offset used to render the particles + * Defines the minimum value on X axis */ - constructor(name: string, capacity: number, scene: Scene, customEffect?: Nullable, isAnimationSheetEnabled?: boolean, epsilon?: number); - private _fetchR(u, v, width, height, pixels); - private _addFactorGradient(factorGradients, gradient, factor, factor2?); - private _removeFactorGradient(factorGradients, gradient); + xmin: number; /** - * Adds a new life time gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the life time factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * Defines the minimum value on Z axis */ - addLifeTimeGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; + zmin: number; /** - * Remove a specific life time gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Defines the maximum value on X axis */ - removeLifeTimeGradient(gradient: number): ParticleSystem; + xmax: number; /** - * Adds a new size gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * Defines the maximum value on Z axis */ - addSizeGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; + zmax: number; /** - * Remove a specific size gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Defines the subdivisions to apply to the ground */ - removeSizeGradient(gradient: number): ParticleSystem; + subdivisions: { + w: number; + h: number; + }; /** - * Adds a new angular speed gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * Defines the precision to use when computing the tiles */ - addAngularSpeedGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; + precision: { + w: number; + h: number; + }; /** - * Remove a specific angular speed gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Creates a tiled ground geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param xmin defines the minimum value on X axis + * @param zmin defines the minimum value on Z axis + * @param xmax defines the maximum value on X axis + * @param zmax defines the maximum value on Z axis + * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map) + * @param precision defines the precision to use when computing the tiles + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) */ - removeAngularSpeedGradient(gradient: number): ParticleSystem; + constructor(id: string, scene: Scene, /** - * Adds a new velocity gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * Defines the minimum value on X axis */ - addVelocityGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; + xmin: number, /** - * Remove a specific velocity gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Defines the minimum value on Z axis */ - removeVelocityGradient(gradient: number): ParticleSystem; + zmin: number, /** - * Adds a new color gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param color defines the color to affect to the specified gradient - * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from + * Defines the maximum value on X axis */ - addColorGradient(gradient: number, color: Color4, color2?: Color4): ParticleSystem; + xmax: number, /** - * Remove a specific color gradient - * @param gradient defines the gradient to remove + * Defines the maximum value on Z axis */ - removeColorGradient(gradient: number): ParticleSystem; - private _resetEffect(); - private _createVertexBuffers(); - private _createIndexBuffer(); + zmax: number, /** - * Gets the maximum number of particles active at the same time. - * @returns The max number of active particles. + * Defines the subdivisions to apply to the ground */ - getCapacity(): number; + subdivisions: { + w: number; + h: number; + }, /** - * Gets Wether there are still active particles in the system. - * @returns True if it is alive, otherwise false. + * Defines the precision to use when computing the tiles */ - isAlive(): boolean; + precision: { + w: number; + h: number; + }, canBeRegenerated?: boolean, mesh?: Nullable); + + copy(id: string): Geometry; + } + /** + * Creates a plane geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#plane + */ + class PlaneGeometry extends _PrimitiveGeometry { /** - * Gets Wether the system has been started. - * @returns True if it has been started, otherwise false. + * Defines the size of the plane (width === height) */ - isStarted(): boolean; + size: number; /** - * Starts the particle system and begins to emit - * @param delay defines the delay in milliseconds before starting the system (0 by default) + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - start(delay?: number): void; + side: number; /** - * Stops the particle system. - * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true. + * Creates a plane geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param size defines the size of the plane (width === height) + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - stop(stopSubEmitters?: boolean): void; + constructor(id: string, scene: Scene, /** - * Remove all active particles + * Defines the size of the plane (width === height) */ - reset(): void; + size: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * @hidden (for internal use only) + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ + side?: number); + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedPlane: any, scene: Scene): Nullable; + } + /** + * Creates a torus knot geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot + */ + class TorusKnotGeometry extends _PrimitiveGeometry { /** - * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list. - * Its lifetime will start back at 0. + * Defines the radius of the torus knot */ - recycleParticle: (particle: Particle) => void; - private _stopSubEmitters(); - private _createParticle; - private _removeFromRoot(); - private _emitFromParticle; - private _update(newParticles); - /** @hidden */ -private static _GetAttributeNamesOrOptions(isAnimationSheetEnabled?: boolean, isBillboardBased?: boolean): string[]; -private static _GetEffectCreationOptions(isAnimationSheetEnabled?: boolean): string[]; - private _getEffect(); + radius: number; /** - * Animates the particle system for the current frame by emitting new particles and or animating the living ones. - * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false) + * Defines the thickness of the torus knot tube */ - animate(preWarmOnly?: boolean): void; - private _appendParticleVertices(offset, particle); + tube: number; /** - * Rebuilds the particle system. + * Defines the number of radial segments */ - rebuild(): void; + radialSegments: number; /** - * Is this system ready to be used/rendered - * @return true if the system is ready + * Defines the number of tubular segments */ - isReady(): boolean; + tubularSegments: number; /** - * Renders the particle system in its current state. - * @returns the current number of particles + * Defines the first number of windings */ - render(): number; + p: number; /** - * Disposes the particle system and free the associated resources - * @param disposeTexture defines if the particule texture must be disposed as well (true by default) + * Defines the second number of windings */ - dispose(disposeTexture?: boolean): void; + q: number; /** - * Creates a Point Emitter for the particle system (emits directly from the emitter position) - * @param direction1 Particles are emitted between the direction1 and direction2 from within the box - * @param direction2 Particles are emitted between the direction1 and direction2 from within the box - * @returns the emitter + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - createPointEmitter(direction1: Vector3, direction2: Vector3): PointParticleEmitter; + side: number; /** - * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius) - * @param radius The radius of the hemisphere to emit from - * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius - * @returns the emitter + * Creates a torus knot geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param radius defines the radius of the torus knot + * @param tube defines the thickness of the torus knot tube + * @param radialSegments defines the number of radial segments + * @param tubularSegments defines the number of tubular segments + * @param p defines the first number of windings + * @param q defines the second number of windings + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - createHemisphericEmitter(radius?: number, radiusRange?: number): HemisphericParticleEmitter; + constructor(id: string, scene: Scene, /** - * Creates a Sphere Emitter for the particle system (emits along the sphere radius) - * @param radius The radius of the sphere to emit from - * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius - * @returns the emitter + * Defines the radius of the torus knot */ - createSphereEmitter(radius?: number, radiusRange?: number): SphereParticleEmitter; + radius: number, /** - * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2) - * @param radius The radius of the sphere to emit from - * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere - * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere - * @returns the emitter + * Defines the thickness of the torus knot tube */ - createDirectedSphereEmitter(radius?: number, direction1?: Vector3, direction2?: Vector3): SphereDirectedParticleEmitter; + tube: number, /** - * Creates a Cone Emitter for the particle system (emits from the cone to the particle position) - * @param radius The radius of the cone to emit from - * @param angle The base angle of the cone - * @returns the emitter + * Defines the number of radial segments */ - createConeEmitter(radius?: number, angle?: number): ConeParticleEmitter; + radialSegments: number, /** - * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox) - * @param direction1 Particles are emitted between the direction1 and direction2 from within the box - * @param direction2 Particles are emitted between the direction1 and direction2 from within the box - * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox - * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox - * @returns the emitter + * Defines the number of tubular segments */ - createBoxEmitter(direction1: Vector3, direction2: Vector3, minEmitBox: Vector3, maxEmitBox: Vector3): BoxParticleEmitter; + tubularSegments: number, /** - * Clones the particle system. - * @param name The name of the cloned object - * @param newEmitter The new emitter to use - * @returns the cloned particle system + * Defines the first number of windings */ - clone(name: string, newEmitter: any): ParticleSystem; + p: number, /** - * Serializes the particle system to a JSON object. - * @returns the JSON object + * Defines the second number of windings */ - serialize(): any; - /** @hidden */ -private static _Serialize(serializationObject: any, particleSystem: IParticleSystem): void; - /** @hidden */ -private static _Parse(parsedParticleSystem: any, particleSystem: IParticleSystem, scene: Scene, rootUrl: string): void; + q: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * Parses a JSON object to create a particle system. - * @param parsedParticleSystem The JSON object to parse - * @param scene The scene to create the particle system in - * @param rootUrl The root url to use to load external dependencies like texture - * @returns the Parsed particle system + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): ParticleSystem; + side?: number); + + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedTorusKnot: any, scene: Scene): Nullable; } } declare module BABYLON { - interface Engine { + class GroundMesh extends Mesh { + generateOctree: boolean; + private _heightQuads; + + + + + + + + + constructor(name: string, scene: Scene); + getClassName(): string; + readonly subdivisions: number; + readonly subdivisionsX: number; + readonly subdivisionsY: number; + optimize(chunksCount: number, octreeBlocksSize?: number): void; /** - * Create an effect to use with particle systems. - * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration - * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx) - * @param uniformsNames defines a list of attribute names - * @param samplers defines an array of string used to represent textures - * @param defines defines the string containing the defines to use to compile the shaders - * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails - * @param onCompiled defines a function to call when the effect creation is successful - * @param onError defines a function to call when the effect creation has failed - * @returns the new Effect + * Returns a height (y) value in the Worl system : + * the ground altitude at the coordinates (x, z) expressed in the World system. + * Returns the ground y position if (x, z) are outside the ground surface. */ - createEffectForParticles(fragmentName: string, uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect; + getHeightAtCoordinates(x: number, z: number): number; + /** + * Returns a normalized vector (Vector3) orthogonal to the ground + * at the ground coordinates (x, z) expressed in the World system. + * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface. + */ + getNormalAtCoordinates(x: number, z: number): Vector3; + /** + * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground + * at the ground coordinates (x, z) expressed in the World system. + * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface. + * Returns the GroundMesh. + */ + getNormalAtCoordinatesToRef(x: number, z: number, ref: Vector3): GroundMesh; + /** + * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates() + * if the ground has been updated. + * This can be used in the render loop. + * Returns the GroundMesh. + */ + updateCoordinateHeights(): GroundMesh; + private _getFacetAt; + private _initHeightQuads; + private _computeHeightQuads; + serialize(serializationObject: any): void; + static Parse(parsedMesh: any, scene: Scene): GroundMesh; } } declare module BABYLON { /** - * Represents a set of particle systems working together to create a specific effect + * Creates an instance based on a source mesh. */ - class ParticleSystemSet implements IDisposable { - private _emitterCreationOptions; - private _emitterNode; + class InstancedMesh extends AbstractMesh { + private _sourceMesh; + private _currentLOD; + constructor(name: string, source: Mesh); /** - * Gets the particle system list + * Returns the string "InstancedMesh". */ - systems: IParticleSystem[]; + getClassName(): string; + readonly receiveShadows: boolean; + readonly material: Nullable; + readonly visibility: number; + readonly skeleton: Nullable; + renderingGroupId: number; /** - * Gets the emitter node used with this set + * Returns the total number of vertices (integer). */ - readonly emitterNode: Nullable; + getTotalVertices(): number; + readonly sourceMesh: Mesh; /** - * Creates a new emitter mesh as a sphere - * @param options defines the options used to create the sphere - * @param renderingGroupId defines the renderingGroupId to use for the sphere - * @param scene defines the hosting scene + * Is this node ready to be used/rendered + * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) + * @return {boolean} is it ready */ - setEmitterAsSphere(options: { - diameter: number; - segments: number; - color: Color3; - }, renderingGroupId: number, scene: Scene): void; + isReady(completeCheck?: boolean): boolean; /** - * Starts all particle systems of the set - * @param emitter defines an optional mesh to use as emitter for the particle systems + * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc. */ - start(emitter?: AbstractMesh): void; + getVerticesData(kind: string, copyWhenShared?: boolean): Nullable; /** - * Release all associated resources + * Sets the vertex data of the mesh geometry for the requested `kind`. + * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. + * The `data` are either a numeric array either a Float32Array. + * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater. + * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc). + * Note that a new underlying VertexBuffer object is created each call. + * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. + * + * Possible `kind` values : + * - BABYLON.VertexBuffer.PositionKind + * - BABYLON.VertexBuffer.UVKind + * - BABYLON.VertexBuffer.UV2Kind + * - BABYLON.VertexBuffer.UV3Kind + * - BABYLON.VertexBuffer.UV4Kind + * - BABYLON.VertexBuffer.UV5Kind + * - BABYLON.VertexBuffer.UV6Kind + * - BABYLON.VertexBuffer.ColorKind + * - BABYLON.VertexBuffer.MatricesIndicesKind + * - BABYLON.VertexBuffer.MatricesIndicesExtraKind + * - BABYLON.VertexBuffer.MatricesWeightsKind + * - BABYLON.VertexBuffer.MatricesWeightsExtraKind + * + * Returns the Mesh. */ - dispose(): void; + setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): Mesh; /** - * Serialize the set into a JSON compatible object - * @returns a JSON compatible representation of the set + * Updates the existing vertex data of the mesh geometry for the requested `kind`. + * If the mesh has no geometry, it is simply returned as it is. + * The `data` are either a numeric array either a Float32Array. + * No new underlying VertexBuffer object is created. + * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. + * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh. + * + * Possible `kind` values : + * - BABYLON.VertexBuffer.PositionKind + * - BABYLON.VertexBuffer.UVKind + * - BABYLON.VertexBuffer.UV2Kind + * - BABYLON.VertexBuffer.UV3Kind + * - BABYLON.VertexBuffer.UV4Kind + * - BABYLON.VertexBuffer.UV5Kind + * - BABYLON.VertexBuffer.UV6Kind + * - BABYLON.VertexBuffer.ColorKind + * - BABYLON.VertexBuffer.MatricesIndicesKind + * - BABYLON.VertexBuffer.MatricesIndicesExtraKind + * - BABYLON.VertexBuffer.MatricesWeightsKind + * - BABYLON.VertexBuffer.MatricesWeightsExtraKind + * + * Returns the Mesh. */ - serialize(): any; + updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): Mesh; /** - * Parse a new ParticleSystemSet from a serialized source - * @param data defines a JSON compatible representation of the set - * @param scene defines the hosting scene - * @param gpu defines if we want GPU particles or CPU particles - * @returns a new ParticleSystemSet + * Sets the mesh indices. + * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array). + * If the mesh has no geometry, a new Geometry object is created and set to the mesh. + * This method creates a new index buffer each call. + * Returns the Mesh. */ - static Parse(data: any, scene: Scene, gpu?: boolean): ParticleSystemSet; - } -} - -declare module BABYLON { - /** - * Represents one particle of a solid particle system. - */ - class SolidParticle { + setIndices(indices: IndicesArray, totalVertices?: Nullable): Mesh; /** - * particle global index + * Boolean : True if the mesh owns the requested kind of data. */ - idx: number; + isVerticesDataPresent(kind: string): boolean; /** - * The color of the particle + * Returns an array of indices (IndicesArray). */ - color: Nullable; + getIndices(): Nullable; +protected readonly _positions: Nullable; /** - * The world space position of the particle. + * Sets a new updated BoundingInfo to the mesh. + * Returns the mesh. */ - position: Vector3; + refreshBoundingInfo(): InstancedMesh; + + /** - * The world space rotation of the particle. (Not use if rotationQuaternion is set) + * Returns the current associated LOD AbstractMesh. */ - rotation: Vector3; + getLOD(camera: Camera): AbstractMesh; + + /** - * The world space rotation quaternion of the particle. + * Creates a new InstancedMesh from the current mesh. + * - name (string) : the cloned mesh name + * - newParent (optional Node) : the optional Node to parent the clone to. + * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned. + * + * Returns the clone. */ - rotationQuaternion: Nullable; + clone(name: string, newParent: Node, doNotCloneChildren?: boolean): InstancedMesh; /** - * The scaling of the particle. + * Disposes the InstancedMesh. + * Returns nothing. */ - scaling: Vector3; + dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; + } +} + +declare module BABYLON { + class LinesMesh extends Mesh { + useVertexColor?: boolean | undefined; + useVertexAlpha?: boolean | undefined; + color: Color3; + alpha: number; /** - * The uvs of the particle. + * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray. + * This margin is expressed in world space coordinates, so its value may vary. + * Default value is 0.1 + * @returns the intersection Threshold value. */ - uvs: Vector4; /** - * The current speed of the particle. + * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray. + * This margin is expressed in world space coordinates, so its value may vary. + * @param value the new threshold to apply + */ + intersectionThreshold: number; + private _intersectionThreshold; + private _colorShader; + constructor(name: string, scene?: Nullable, parent?: Nullable, source?: LinesMesh, doNotCloneChildren?: boolean, useVertexColor?: boolean | undefined, useVertexAlpha?: boolean | undefined); + /** + * Returns the string "LineMesh" */ - velocity: Vector3; + getClassName(): string; /** - * The pivot point in the particle local space. + * @hidden */ - pivot: Vector3; /** - * Must the particle be translated from its pivot point in its local space ? - * In this case, the pivot point is set at the origin of the particle local space and the particle is translated. - * Default : false + * @hidden + */ + material: Material; + /** + * @hidden */ - translateFromPivot: boolean; + readonly checkCollisions: boolean; + createInstance(name: string): InstancedMesh; + + + dispose(doNotRecurse?: boolean): void; /** - * Is the particle active or not ? + * Returns a new LineMesh object cloned from the current one. */ - alive: boolean; + clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): LinesMesh; + } +} + +declare module BABYLON { + /** + * @hidden + **/ + class _InstancesBatch { + mustReturn: boolean; + visibleInstances: Nullable[]; + renderSelf: boolean[]; + } + class Mesh extends AbstractMesh implements IGetSetVerticesData { +private static _FRONTSIDE: number; +private static _BACKSIDE: number; +private static _DOUBLESIDE: number; +private static _DEFAULTSIDE: number; +private static _NO_CAP: number; +private static _CAP_START: number; +private static _CAP_END: number; +private static _CAP_ALL: number; /** - * Is the particle visible or not ? + * Mesh side orientation : usually the external or front surface */ - isVisible: boolean; + static readonly FRONTSIDE: number; /** - * Index of this particle in the global "positions" array (Internal use) + * Mesh side orientation : usually the internal or back surface */ - + static readonly BACKSIDE: number; /** - * Index of this particle in the global "indices" array (Internal use) + * Mesh side orientation : both internal and external or front and back surfaces */ - + static readonly DOUBLESIDE: number; /** - * ModelShape of this particle (Internal use) + * Mesh side orientation : by default, `FRONTSIDE` */ - + static readonly DEFAULTSIDE: number; /** - * ModelShape id of this particle + * Mesh cap setting : no cap */ - shapeId: number; + static readonly NO_CAP: number; /** - * Index of the particle in its shape id (Internal use) + * Mesh cap setting : one cap at the beginning of the mesh */ - idxInShape: number; + static readonly CAP_START: number; /** - * Reference to the shape model BoundingInfo object (Internal use) + * Mesh cap setting : one cap at the end of the mesh */ - + static readonly CAP_END: number; /** - * Particle BoundingInfo object (Internal use) + * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh */ - + static readonly CAP_ALL: number; + private _onBeforeRenderObservable; + private _onAfterRenderObservable; + private _onBeforeDrawObservable; /** - * Reference to the SPS what the particle belongs to (Internal use) + * An event triggered before rendering the mesh */ + readonly onBeforeRenderObservable: Observable; + /** + * An event triggered after rendering the mesh + */ + readonly onAfterRenderObservable: Observable; + /** + * An event triggered before drawing the mesh + */ + readonly onBeforeDrawObservable: Observable; + private _onBeforeDrawObserver; + onBeforeDraw: () => void; + delayLoadState: number; + instances: InstancedMesh[]; + delayLoadingFile: string; + + private _LODLevels; + onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Nullable) => void; + private _morphTargetManager; + morphTargetManager: Nullable; + + + + + private _renderIdForInstances; + private _batchCache; + private _instancesBufferSize; + private _instancesBuffer; + private _instancesData; + private _overridenInstanceCount; + private _effectiveMaterial; + private _preActivateId; + + overrideMaterialSideOrientation: Nullable; + private _areNormalsFrozen; + private _sourcePositions; + private _sourceNormals; + private _source; + readonly source: Nullable; + isUnIndexed: boolean; /** - * Still set as invisible in order to skip useless computations (Internal use) + * @constructor + * @param {string} name The value used by scene.getMeshByName() to do a lookup. + * @param {Scene} scene The scene to add this mesh to. + * @param {Node} parent The parent of this mesh, if it has one + * @param {Mesh} source An optional Mesh from which geometry is shared, cloned. + * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False. + * When false, achieved by calling a clone(), also passing False. + * This will make creation of children, recursive. + * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True. */ - + constructor(name: string, scene?: Nullable, parent?: Nullable, source?: Nullable, doNotCloneChildren?: boolean, clonePhysicsImpostor?: boolean); /** - * Last computed particle rotation matrix + * Returns the string "Mesh". + */ + getClassName(): string; + /** + * Returns a string. + * @param {boolean} fullDetails - support for multiple levels of logging within scene loading */ + toString(fullDetails?: boolean): string; /** - * Parent particle Id, if any. - * Default null. + * True if the mesh has some Levels Of Details (LOD). + * Returns a boolean. */ - parentId: Nullable; + readonly hasLODLevels: boolean; /** - * Internal global position in the SPS. + * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh + * @returns an array of {BABYLON.MeshLODLevel} */ - + getLODLevels(): MeshLODLevel[]; + private _sortLODLevels; /** - * Creates a Solid Particle object. - * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle() - * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier. - * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array. - * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array. - * @param model (ModelShape) is a reference to the model shape on what the particle is designed. - * @param shapeId (integer) is the model shape identifier in the SPS. - * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30)) - * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations. + * Add a mesh as LOD level triggered at the given distance. + * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD + * @param distance The distance from the center of the object to show this level + * @param mesh The mesh to be added as LOD level (can be null) + * @return This mesh (for chaining) */ - constructor(particleIndex: number, positionIndex: number, indiceIndex: number, model: Nullable, shapeId: number, idxInShape: number, sps: SolidParticleSystem, modelBoundingInfo?: Nullable); + addLODLevel(distance: number, mesh: Nullable): Mesh; /** - * Legacy support, changed scale to scaling + * Returns the LOD level mesh at the passed distance or null if not found. + * It is related to the method `addLODLevel(distance, mesh)`. + * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD + * Returns an object Mesh or `null`. */ + getLODLevelAtDistance(distance: number): Nullable; /** - * Legacy support, changed scale to scaling + * Remove a mesh from the LOD array + * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD + * @param {Mesh} mesh The mesh to be removed. + * @return {Mesh} This mesh (for chaining) */ - scale: Vector3; + removeLODLevel(mesh: Mesh): Mesh; /** - * Legacy support, changed quaternion to rotationQuaternion + * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh. + * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod */ + getLOD(camera: Camera, boundingSphere?: BoundingSphere): Nullable; /** - * Legacy support, changed quaternion to rotationQuaternion + * Returns the mesh internal Geometry object. */ - quaternion: Nullable; + readonly geometry: Nullable; /** - * Returns a boolean. True if the particle intersects another particle or another mesh, else false. - * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB) - * @param target is the object (solid particle or mesh) what the intersection is computed against. - * @returns true if it intersects + * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry. */ - intersectsMesh(target: Mesh | SolidParticle): boolean; - } - /** - * Represents the shape of the model used by one particle of a solid particle system. - * SPS internal tool, don't use it manually. - */ - class ModelShape { + getTotalVertices(): number; /** - * The shape id. + * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc). + * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one. + * You can force the copy with forceCopy === true + * Returns null if the mesh has no geometry or no vertex buffer. + * Possible `kind` values : + * - BABYLON.VertexBuffer.PositionKind + * - BABYLON.VertexBuffer.UVKind + * - BABYLON.VertexBuffer.UV2Kind + * - BABYLON.VertexBuffer.UV3Kind + * - BABYLON.VertexBuffer.UV4Kind + * - BABYLON.VertexBuffer.UV5Kind + * - BABYLON.VertexBuffer.UV6Kind + * - BABYLON.VertexBuffer.ColorKind + * - BABYLON.VertexBuffer.MatricesIndicesKind + * - BABYLON.VertexBuffer.MatricesIndicesExtraKind + * - BABYLON.VertexBuffer.MatricesWeightsKind + * - BABYLON.VertexBuffer.MatricesWeightsExtraKind */ - shapeID: number; + getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable; /** - * flat array of model positions (internal use) + * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc. + * Returns `null` if the mesh has no geometry. + * Possible `kind` values : + * - BABYLON.VertexBuffer.PositionKind + * - BABYLON.VertexBuffer.UVKind + * - BABYLON.VertexBuffer.UV2Kind + * - BABYLON.VertexBuffer.UV3Kind + * - BABYLON.VertexBuffer.UV4Kind + * - BABYLON.VertexBuffer.UV5Kind + * - BABYLON.VertexBuffer.UV6Kind + * - BABYLON.VertexBuffer.ColorKind + * - BABYLON.VertexBuffer.MatricesIndicesKind + * - BABYLON.VertexBuffer.MatricesIndicesExtraKind + * - BABYLON.VertexBuffer.MatricesWeightsKind + * - BABYLON.VertexBuffer.MatricesWeightsExtraKind */ - + getVertexBuffer(kind: string): Nullable; + isVerticesDataPresent(kind: string): boolean; /** - * flat array of model UVs (internal use) + * Returns a boolean defining if the vertex data for the requested `kind` is updatable. + * Possible `kind` values : + * - BABYLON.VertexBuffer.PositionKind + * - BABYLON.VertexBuffer.UVKind + * - BABYLON.VertexBuffer.UV2Kind + * - BABYLON.VertexBuffer.UV3Kind + * - BABYLON.VertexBuffer.UV4Kind + * - BABYLON.VertexBuffer.UV5Kind + * - BABYLON.VertexBuffer.UV6Kind + * - BABYLON.VertexBuffer.ColorKind + * - BABYLON.VertexBuffer.MatricesIndicesKind + * - BABYLON.VertexBuffer.MatricesIndicesExtraKind + * - BABYLON.VertexBuffer.MatricesWeightsKind + * - BABYLON.VertexBuffer.MatricesWeightsExtraKind */ - + isVertexBufferUpdatable(kind: string): boolean; /** - * length of the shape in the model indices array (internal use) + * Returns a string : the list of existing `kinds` of Vertex Data for this mesh. + * Possible `kind` values : + * - BABYLON.VertexBuffer.PositionKind + * - BABYLON.VertexBuffer.UVKind + * - BABYLON.VertexBuffer.UV2Kind + * - BABYLON.VertexBuffer.UV3Kind + * - BABYLON.VertexBuffer.UV4Kind + * - BABYLON.VertexBuffer.UV5Kind + * - BABYLON.VertexBuffer.UV6Kind + * - BABYLON.VertexBuffer.ColorKind + * - BABYLON.VertexBuffer.MatricesIndicesKind + * - BABYLON.VertexBuffer.MatricesIndicesExtraKind + * - BABYLON.VertexBuffer.MatricesWeightsKind + * - BABYLON.VertexBuffer.MatricesWeightsExtraKind */ - + getVerticesDataKinds(): string[]; /** - * Custom position function (internal use) + * Returns a positive integer : the total number of indices in this mesh geometry. + * Returns zero if the mesh has no geometry. + */ + getTotalIndices(): number; + /** + * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices. + * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one. + * Returns an empty array if the mesh has no geometry. */ + getIndices(copyWhenShared?: boolean): Nullable; + readonly isBlocked: boolean; + /** + * Determine if the current mesh is ready to be rendered + * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) + * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default) + * @returns true if all associated assets are ready (material, textures, shaders) + */ + isReady(completeCheck?: boolean, forceInstanceSupport?: boolean): boolean; + /** + * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update. + * This property is pertinent only for updatable parametric shapes. + */ + readonly areNormalsFrozen: boolean; + /** + * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. + * It has no effect at all on other shapes. + * It prevents the mesh normals from being recomputed on next `positions` array update. + * Returns the Mesh. + */ + freezeNormals(): Mesh; + /** + * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. + * It has no effect at all on other shapes. + * It reactivates the mesh normals computation if it was previously frozen. + * Returns the Mesh. + */ + unfreezeNormals(): Mesh; + /** + * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs + */ + overridenInstanceCount: number; + + /** - * Custom vertex function (internal use) + * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked. + * This means the mesh underlying bounding box and sphere are recomputed. + * Returns the Mesh. */ + refreshBoundingInfo(): Mesh; + + private _getPositionData; + subdivide(count: number): void; + setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): Mesh; + markVerticesDataAsUpdatable(kind: string, updatable?: boolean): void; /** - * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS. - * SPS internal tool, don't use it manually. - * @hidden + * Sets the mesh VertexBuffer. + * Returns the Mesh. */ - constructor(id: number, shape: Vector3[], indicesLength: number, shapeUV: number[], posFunction: Nullable<(particle: SolidParticle, i: number, s: number) => void>, vtxFunction: Nullable<(particle: SolidParticle, vertex: Vector3, i: number) => void>); - } - /** - * Represents a Depth Sorted Particle in the solid particle system. - */ - class DepthSortedParticle { + setVerticesBuffer(buffer: VertexBuffer): Mesh; + updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): Mesh; /** - * Index of the particle in the "indices" array + * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values. + * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions + * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything. + * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update. + * Returns the Mesh. */ - ind: number; + updateMeshPositions(positionFunction: (data: FloatArray) => void, computeNormals?: boolean): Mesh; /** - * Length of the particle shape in the "indices" array + * Creates a un-shared specific occurence of the geometry for the mesh. + * Returns the Mesh. */ - indicesLength: number; + makeGeometryUnique(): Mesh; + setIndices(indices: IndicesArray, totalVertices?: Nullable, updatable?: boolean): Mesh; /** - * Squared distance from the particle to the camera + * Update the current index buffer + * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array) + * Returns the Mesh. */ - sqDistance: number; - } -} + updateIndices(indices: IndicesArray, offset?: number): Mesh; + /** + * Invert the geometry to move from a right handed system to a left handed one. + * Returns the Mesh. + */ + toLeftHanded(): Mesh; -declare module BABYLON { - /** - * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh. - *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc. - * The SPS is also a particle system. It provides some methods to manage the particles. - * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior. - * - * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System - */ - class SolidParticleSystem implements IDisposable { /** - * The SPS array of Solid Particle objects. Just access each particle as with any classic array. - * Example : var p = SPS.particles[i]; + * Registers for this mesh a javascript function called just before the rendering process. + * This function is passed the current mesh. + * Return the Mesh. */ - particles: SolidParticle[]; + registerBeforeRender(func: (mesh: AbstractMesh) => void): Mesh; /** - * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value. + * Disposes a previously registered javascript function called before the rendering. + * This function is passed the current mesh. + * Returns the Mesh. */ - nbParticles: number; + unregisterBeforeRender(func: (mesh: AbstractMesh) => void): Mesh; /** - * If the particles must ever face the camera (default false). Useful for planar particles. + * Registers for this mesh a javascript function called just after the rendering is complete. + * This function is passed the current mesh. + * Returns the Mesh. */ - billboard: boolean; + registerAfterRender(func: (mesh: AbstractMesh) => void): Mesh; /** - * Recompute normals when adding a shape + * Disposes a previously registered javascript function called after the rendering. + * This function is passed the current mesh. + * Return the Mesh. */ - recomputeNormals: boolean; + unregisterAfterRender(func: (mesh: AbstractMesh) => void): Mesh; + + + /** - * This a counter ofr your own usage. It's not set by any SPS functions. + * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager + * @param subMesh defines the subMesh to render + * @param enableAlphaMode defines if alpha mode can be changed + * @returns the current mesh */ - counter: number; + render(subMesh: SubMesh, enableAlphaMode: boolean): Mesh; + private _onBeforeDraw; /** - * The SPS name. This name is also given to the underlying mesh. + * Returns an array populated with IParticleSystem objects whose the mesh is the emitter. */ - name: string; + getEmittedParticleSystems(): IParticleSystem[]; /** - * The SPS mesh. It's a standard BJS Mesh, so all the methods from the Mesh class are avalaible. + * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter. */ - mesh: Mesh; + getHierarchyEmittedParticleSystems(): IParticleSystem[]; /** - * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity. - * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns + * Normalize matrix weights so that all vertices have a total weight set to 1 */ - vars: any; + cleanMatrixWeights(): void; + + private _queueLoad; /** - * This array is populated when the SPS is set as 'pickable'. - * Each key of this array is a `faceId` value that you can get from a pickResult object. - * Each element of this array is an object `{idx: int, faceId: int}`. - * `idx` is the picked particle index in the `SPS.particles` array - * `faceId` is the picked face index counted within this particle. - * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#pickable-particles + * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter. */ - pickedParticles: { - idx: number; - faceId: number; - }[]; + isInFrustum(frustumPlanes: Plane[]): boolean; /** - * This array is populated when `enableDepthSort` is set to true. - * Each element of this array is an instance of the class DepthSortedParticle. + * Sets the mesh material by the material or multiMaterial `id` property. + * The material `id` is a string identifying the material or the multiMaterial. + * This method returns the Mesh. */ - depthSortedParticles: DepthSortedParticle[]; + setMaterialByID(id: string): Mesh; /** - * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only) + * Returns as a new array populated with the mesh material and/or skeleton, if any. */ - + getAnimatables(): IAnimatable[]; /** - * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only) + * Modifies the mesh geometry according to the passed transformation matrix. + * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable. + * The mesh normals are modified accordingly the same transformation. + * tuto : http://doc.babylonjs.com/resources/baking_transformations + * Note that, under the hood, this method sets a new VertexBuffer each call. + * Returns the Mesh. + */ + bakeTransformIntoVertices(transform: Matrix): Mesh; + /** + * Modifies the mesh geometry according to its own current World Matrix. + * The mesh World Matrix is then reset. + * This method returns nothing but really modifies the mesh even if it's originally not set as updatable. + * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations + * Note that, under the hood, this method sets a new VertexBuffer each call. + * Returns the Mesh. */ + bakeCurrentTransformIntoVertices(): Mesh; +protected readonly _positions: Nullable; + - private _scene; - private _positions; - private _indices; - private _normals; - private _colors; - private _uvs; - private _indices32; - private _positions32; - private _normals32; - private _fixedNormal32; - private _colors32; - private _uvs32; - private _index; - private _updatable; - private _pickable; - private _isVisibilityBoxLocked; - private _alwaysVisible; - private _depthSort; - private _shapeCounter; - private _copy; - private _shape; - private _shapeUV; - private _color; - private _computeParticleColor; - private _computeParticleTexture; - private _computeParticleRotation; - private _computeParticleVertex; - private _computeBoundingBox; - private _depthSortParticles; - private _cam_axisZ; - private _cam_axisY; - private _cam_axisX; - private _axisZ; - private _camera; - private _particle; - private _camDir; - private _camInvertedPosition; - private _rotMatrix; - private _invertMatrix; - private _rotated; - private _quaternion; - private _vertex; - private _normal; - private _yaw; - private _pitch; - private _roll; - private _halfroll; - private _halfpitch; - private _halfyaw; - private _sinRoll; - private _cosRoll; - private _sinPitch; - private _cosPitch; - private _sinYaw; - private _cosYaw; - private _mustUnrotateFixedNormals; - private _minimum; - private _maximum; - private _minBbox; - private _maxBbox; - private _particlesIntersect; - private _depthSortFunction; - private _needs32Bits; - private _pivotBackTranslation; - private _scaledPivot; - private _particleHasParent; - private _parent; /** - * Creates a SPS (Solid Particle System) object. - * @param name (String) is the SPS name, this will be the underlying mesh name. - * @param scene (Scene) is the scene in which the SPS is added. - * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable. - * @param isPickable (optional boolean, default false) : if the solid particles must be pickable. - * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera. - * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed. - * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). - * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance. - * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh. + * Returns a new Mesh object generated from the current mesh properties. + * This method must not get confused with createInstance(). + * The parameter `name` is a string, the name given to the new mesh. + * The optional parameter `newParent` can be any Node object (default `null`). + * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any. + * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any. */ - constructor(name: string, scene: Scene, options?: { - updatable?: boolean; - isPickable?: boolean; - enableDepthSort?: boolean; - particleIntersection?: boolean; - boundingSphereOnly?: boolean; - bSphereRadiusFactor?: number; - }); + clone(name: string, newParent?: Node, doNotCloneChildren?: boolean, clonePhysicsImpostor?: boolean): Mesh; /** - * Builds the SPS underlying mesh. Returns a standard Mesh. - * If no model shape was added to the SPS, the returned mesh is just a single triangular plane. - * @returns the created mesh + * Releases resources associated with this mesh. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) */ - buildMesh(): Mesh; + dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; /** - * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS. - * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places. - * Thus the particles generated from `digest()` have their property `position` set yet. - * @param mesh ( Mesh ) is the mesh to be digested - * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any - * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets - * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets - * @returns the current SPS + * Modifies the mesh geometry according to a displacement map. + * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. + * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. + * This method returns nothing. + * The parameter `url` is a string, the URL from the image file is to be downloaded. + * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement. + * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing. + * The parameter `uvOffset` is an optional vector2 used to offset UV. + * The parameter `uvScale` is an optional vector2 used to scale UV. + * + * Returns the Mesh. */ - digest(mesh: Mesh, options?: { - facetNb?: number; - number?: number; - delta?: number; - }): SolidParticleSystem; - private _unrotateFixedNormals(); - private _resetCopy(); - private _meshBuilder(p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options); - private _posToShape(positions); - private _uvsToShapeUV(uvs); - private _addParticle(idx, idxpos, idxind, model, shapeId, idxInShape, bInfo?); + applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void, uvOffset?: Vector2, uvScale?: Vector2): Mesh; /** - * Adds some particles to the SPS from the model shape. Returns the shape id. - * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps - * @param mesh is any Mesh object that will be used as a model for the solid particles. - * @param nb (positive integer) the number of particles to be created from this model - * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation. - * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation - * @returns the number of shapes in the system + * Modifies the mesh geometry according to a displacementMap buffer. + * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. + * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. + * This method returns nothing. + * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel. + * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image. + * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement. + * The parameter `uvOffset` is an optional vector2 used to offset UV. + * The parameter `uvScale` is an optional vector2 used to scale UV. + * + * Returns the Mesh. */ - addShape(mesh: Mesh, nb: number, options?: { - positionFunction?: any; - vertexFunction?: any; - }): number; - private _rebuildParticle(particle); + applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number, uvOffset?: Vector2, uvScale?: Vector2): Mesh; /** - * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed. - * @returns the SPS. + * Modify the mesh to get a flat shading rendering. + * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result. + * This method returns the Mesh. + * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated. */ - rebuildMesh(): SolidParticleSystem; + convertToFlatShadedMesh(): Mesh; /** - * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc. - * This method calls `updateParticle()` for each particle of the SPS. - * For an animated SPS, it is usually called within the render loop. - * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_ - * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_ - * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_ - * @returns the SPS. + * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers. + * In other words, more vertices, no more indices and a single bigger VBO. + * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated. + * Returns the Mesh. */ - setParticles(start?: number, end?: number, update?: boolean): SolidParticleSystem; - private _quaternionRotationYPR(); - private _quaternionToRotationMatrix(); - /** - * Disposes the SPS. - */ - dispose(): void; + convertToUnIndexedMesh(): Mesh; /** - * Visibilty helper : Recomputes the visible size according to the mesh bounding box - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility - * @returns the SPS. + * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true. + * This method returns the Mesh. + * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. */ - refreshVisibleSize(): SolidParticleSystem; + flipFaces(flipNormals?: boolean): Mesh; /** - * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box. - * @param size the size (float) of the visibility box - * note : this doesn't lock the SPS mesh bounding box. - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + * Creates a new InstancedMesh object from the mesh model. + * An instance shares the same properties and the same material than its model. + * Only these properties of each instance can then be set individually : + * - position + * - rotation + * - rotationQuaternion + * - setPivotMatrix + * - scaling + * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances + * Warning : this method is not supported for Line mesh and LineSystem */ - setVisibilityBox(size: number): void; + createInstance(name: string): InstancedMesh; /** - * Gets whether the SPS as always visible or not - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any. + * After this call, all the mesh instances have the same submeshes than the current mesh. + * This method returns the Mesh. */ + synchronizeInstances(): Mesh; /** - * Sets the SPS as always visible or not - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + * Simplify the mesh according to the given array of settings. + * Function will return immediately and will simplify async. It returns the Mesh. + * @param settings a collection of simplification settings. + * @param parallelProcessing should all levels calculate parallel or one after the other. + * @param type the type of simplification to run. + * @param successCallback optional success callback to be called after the simplification finished processing all settings. */ - isAlwaysVisible: boolean; + simplify(settings: Array, parallelProcessing?: boolean, simplificationType?: SimplificationType, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void): Mesh; /** - * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates. - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + * Optimization of the mesh's indices, in case a mesh has duplicated vertices. + * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes. + * This should be used together with the simplification to avoid disappearing triangles. + * Returns the Mesh. + * @param successCallback an optional success callback to be called after the optimization finished. */ + optimizeIndices(successCallback?: (mesh?: Mesh) => void): Mesh; + serialize(serializationObject: any): void; + /** - * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates. - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + * Returns a new Mesh object parsed from the source provided. + * The parameter `parsedMesh` is the source. + * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with */ - isVisibilityBoxLocked: boolean; + static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh; /** - * Gets if `setParticles()` computes the particle rotations or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate. + * Creates a ribbon mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. + * + * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial + * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry. + * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array. + * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array. + * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path. + * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11. + * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ + static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean | undefined, closePath: boolean, offset: number, scene?: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; /** - * Tells to `setParticles()` to compute the particle rotations or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate. + * Creates a plane polygonal mesh. By default, this is a disc. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `radius` sets the radius size (float) of the polygon (default 0.5). + * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc. + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - computeParticleRotation: boolean; + static CreateDisc(name: string, radius: number, tessellation: number, scene?: Nullable, updatable?: boolean, sideOrientation?: number): Mesh; /** - * Gets if `setParticles()` computes the particle colors or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set. + * Creates a box mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `size` sets the size (float) of each box side (default 1). + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ + static CreateBox(name: string, size: number, scene?: Nullable, updatable?: boolean, sideOrientation?: number): Mesh; /** - * Tells to `setParticles()` to compute the particle colors or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set. + * Creates a sphere mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `diameter` sets the diameter size (float) of the sphere (default 1). + * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32). + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - computeParticleColor: boolean; + static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; /** - * Gets if `setParticles()` computes the particle textures or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set. + * Creates a cylinder or a cone mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2). + * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1). + * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero. + * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance. + * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1). + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - computeParticleTexture: boolean; + static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene?: Scene, updatable?: any, sideOrientation?: number): Mesh; /** - * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not. - * Default value : false. The SPS is faster when it's set to false. - * Note : the particle custom vertex positions aren't stored values. + * Creates a torus mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `diameter` sets the diameter size (float) of the torus (default 1). + * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5). + * The parameter `tessellation` sets the number of torus sides (postive integer, default 16). + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ + static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; /** - * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not. - * Default value : false. The SPS is faster when it's set to false. - * Note : the particle custom vertex positions aren't stored values. + * Creates a torus knot mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `radius` sets the global radius size (float) of the torus knot (default 2). + * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32). + * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32). + * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3). + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - computeParticleVertex: boolean; + static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; /** - * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions. + * Creates a line mesh. + * Please consider using the same method from the MeshBuilder class instead. + * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter. + * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function. + * The parameter `points` is an array successive Vector3. + * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines + * When updating an instance, remember that only point positions can change, not the number of points. + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ + static CreateLines(name: string, points: Vector3[], scene?: Nullable, updatable?: boolean, instance?: Nullable): LinesMesh; /** - * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions. + * Creates a dashed line mesh. + * Please consider using the same method from the MeshBuilder class instead. + * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter. + * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function. + * The parameter `points` is an array successive Vector3. + * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200). + * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3). + * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1). + * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines + * When updating an instance, remember that only point positions can change, not the number of points. + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - computeBoundingBox: boolean; + static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene?: Nullable, updatable?: boolean, instance?: LinesMesh): LinesMesh; /** - * Gets if `setParticles()` sorts or not the distance between each particle and the camera. - * Skipped when `enableDepthSort` is set to `false` (default) at construction time. - * Default : `true` + * Creates a polygon mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh. + * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors. + * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Remember you can only change the shape positions, not their number when updating a polygon. */ + static CreatePolygon(name: string, shape: Vector3[], scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number): Mesh; /** - * Tells to `setParticles()` to sort or not the distance between each particle and the camera. - * Skipped when `enableDepthSort` is set to `false` (default) at construction time. - * Default : `true` + * Creates an extruded polygon mesh, with depth in the Y direction. + * Please consider using the same method from the MeshBuilder class instead. */ - depthSortParticles: boolean; + static ExtrudePolygon(name: string, shape: Vector3[], depth: number, scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number): Mesh; /** - * This function does nothing. It may be overwritten to set all the particle first values. - * The SPS doesn't call this function, you may have to call it by your own. - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management + * Creates an extruded shape mesh. + * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. + * Please consider using the same method from the MeshBuilder class instead. + * + * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes + * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be + * extruded along the Z axis. + * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. + * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve. + * The parameter `scale` (float, default 1) is the value to scale the shape. + * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape + * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - initParticles(): void; + static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene?: Nullable, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; /** - * This function does nothing. It may be overwritten to recycle a particle. - * The SPS doesn't call this function, you may have to call it by your own. - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management - * @param particle The particle to recycle - * @returns the recycled particle + * Creates an custom extruded shape mesh. + * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. + * Please consider using the same method from the MeshBuilder class instead. + * + * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes + * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be + * extruded along the Z axis. + * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. + * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path + * and the distance of this point from the begining of the path : + * ```javascript + * var rotationFunction = function(i, distance) { + * // do things + * return rotationValue; } + * ``` + * It must returns a float value that will be the rotation in radians applied to the shape on each path point. + * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path + * and the distance of this point from the begining of the path : + * ```javascript + * var scaleFunction = function(i, distance) { + * // do things + * return scaleValue;} + * ``` + * It must returns a float value that will be the scale value applied to the shape on each path point. + * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`. + * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`. + * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape + * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - recycleParticle(particle: SolidParticle): SolidParticle; + static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction: Function, rotationFunction: Function, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; /** - * Updates a particle : this function should be overwritten by the user. - * It is called on each particle by `setParticles()`. This is the place to code each particle behavior. - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management - * @example : just set a particle position or velocity and recycle conditions - * @param particle The particle to update - * @returns the updated particle + * Creates lathe mesh. + * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be + * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero. + * The parameter `radius` (positive float, default 1) is the radius value of the lathe. + * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe. + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - updateParticle(particle: SolidParticle): SolidParticle; + static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; /** - * Updates a vertex of a particle : it can be overwritten by the user. - * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only. - * @param particle the current particle - * @param vertex the current index of the current particle - * @param pt the index of the current vertex in the particle shape - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape - * @example : just set a vertex particle position - * @returns the updated vertex + * Creates a plane mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `size` sets the size (float) of both sides of the plane at once (default 1). + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - updateParticleVertex(particle: SolidParticle, vertex: Vector3, pt: number): Vector3; + static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; /** - * This will be called before any other treatment by `setParticles()` and will be passed three parameters. - * This does nothing and may be overwritten by the user. - * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param update the boolean update value actually passed to setParticles() + * Creates a ground mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground. + * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side. + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void; + static CreateGround(name: string, width: number, height: number, subdivisions: number, scene?: Scene, updatable?: boolean): Mesh; /** - * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update. - * This will be passed three parameters. - * This does nothing and may be overwritten by the user. - * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param update the boolean update value actually passed to setParticles() + * Creates a tiled ground mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates. + * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates. + * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the + * numbers of subdivisions on the ground width and height. Each subdivision is called a tile. + * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the + * numbers of subdivisions on the ground width and height of each tile. + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - afterUpdateParticles(start?: number, stop?: number, update?: boolean): void; - } -} - -declare module BABYLON { - interface PhysicsImpostorJoint { - mainImpostor: PhysicsImpostor; - connectedImpostor: PhysicsImpostor; - joint: PhysicsJoint; - } - class PhysicsEngine { - private _physicsPlugin; - gravity: Vector3; - constructor(gravity: Nullable, _physicsPlugin?: IPhysicsEnginePlugin); - setGravity(gravity: Vector3): void; + static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { + w: number; + h: number; + }, precision: { + w: number; + h: number; + }, scene: Scene, updatable?: boolean): Mesh; /** - * Set the time step of the physics engine. - * default is 1/60. - * To slow it down, enter 1/600 for example. - * To speed it up, 1/30 - * @param {number} newTimeStep the new timestep to apply to this world. + * Creates a ground mesh from a height map. + * tuto : http://doc.babylonjs.com/babylon101/height_map + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `url` sets the URL of the height map image resource. + * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes. + * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side. + * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground. + * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground. + * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time). + * This function is passed the newly built mesh : + * ```javascript + * function(mesh) { // do things + * return; } + * ``` + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - setTimeStep(newTimeStep?: number): void; + static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void): GroundMesh; /** - * Get the time step of the physics engine. + * Creates a tube mesh. + * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube. + * The parameter `radius` (positive float, default 1) sets the tube radius size. + * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface. + * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`. + * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. + * It must return a radius value (positive float) : + * ```javascript + * var radiusFunction = function(i, distance) { + * // do things + * return radius; } + * ``` + * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - getTimeStep(): number; - dispose(): void; - getPhysicsPluginName(): string; - static Epsilon: number; - private _impostors; - private _joints; + static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { + (i: number, distance: number): number; + }, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; /** - * Adding a new impostor for the impostor tracking. - * This will be done by the impostor itself. - * @param {PhysicsImpostor} impostor the impostor to add + * Creates a polyhedron mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial + * to choose the wanted type. + * The parameter `size` (positive float, default 1) sets the polygon size. + * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value). + * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`. + * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron + * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`). + * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors + * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored. + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - addImpostor(impostor: PhysicsImpostor): void; + static CreatePolyhedron(name: string, options: { + type?: number; + size?: number; + sizeX?: number; + sizeY?: number; + sizeZ?: number; + custom?: any; + faceUV?: Vector4[]; + faceColors?: Color4[]; + updatable?: boolean; + sideOrientation?: number; + }, scene: Scene): Mesh; /** - * Remove an impostor from the engine. - * This impostor and its mesh will not longer be updated by the physics engine. - * @param {PhysicsImpostor} impostor the impostor to remove + * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `radius` sets the radius size (float) of the icosphere (default 1). + * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`). + * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size. + * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface. + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - removeImpostor(impostor: PhysicsImpostor): void; + static CreateIcoSphere(name: string, options: { + radius?: number; + flat?: boolean; + subdivisions?: number; + sideOrientation?: number; + updatable?: boolean; + }, scene: Scene): Mesh; /** - * Add a joint to the physics engine - * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added. - * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint - * @param {PhysicsJoint} the joint that will connect both impostors. + * Creates a decal mesh. + * Please consider using the same method from the MeshBuilder class instead. + * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal. + * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates. + * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates. + * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling. + * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal. */ - addJoint(mainImpostor: PhysicsImpostor, connectedImpostor: PhysicsImpostor, joint: PhysicsJoint): void; - removeJoint(mainImpostor: PhysicsImpostor, connectedImpostor: PhysicsImpostor, joint: PhysicsJoint): void; + static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh; /** - * Called by the scene. no need to call it. + * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. */ - - getPhysicsPlugin(): IPhysicsEnginePlugin; - getImpostors(): Array; - getImpostorForPhysicsObject(object: IPhysicsEnabledObject): Nullable; - getImpostorWithPhysicsBody(body: any): Nullable; - } - interface IPhysicsEnginePlugin { - world: any; - name: string; - setGravity(gravity: Vector3): void; - setTimeStep(timeStep: number): void; - getTimeStep(): number; - executeStep(delta: number, impostors: Array): void; - applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3): void; - applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3): void; - generatePhysicsBody(impostor: PhysicsImpostor): void; - removePhysicsBody(impostor: PhysicsImpostor): void; - generateJoint(joint: PhysicsImpostorJoint): void; - removeJoint(joint: PhysicsImpostorJoint): void; - isSupported(): boolean; - setTransformationFromPhysicsBody(impostor: PhysicsImpostor): void; - setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion): void; - setLinearVelocity(impostor: PhysicsImpostor, velocity: Nullable): void; - setAngularVelocity(impostor: PhysicsImpostor, velocity: Nullable): void; - getLinearVelocity(impostor: PhysicsImpostor): Nullable; - getAngularVelocity(impostor: PhysicsImpostor): Nullable; - setBodyMass(impostor: PhysicsImpostor, mass: number): void; - getBodyMass(impostor: PhysicsImpostor): number; - getBodyFriction(impostor: PhysicsImpostor): number; - setBodyFriction(impostor: PhysicsImpostor, friction: number): void; - getBodyRestitution(impostor: PhysicsImpostor): number; - setBodyRestitution(impostor: PhysicsImpostor, restitution: number): void; - sleepBody(impostor: PhysicsImpostor): void; - wakeUpBody(impostor: PhysicsImpostor): void; - updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number): void; - setMotor(joint: IMotorEnabledJoint, speed: number, maxForce?: number, motorIndex?: number): void; - setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number, motorIndex?: number): void; - getRadius(impostor: PhysicsImpostor): number; - getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void; - syncMeshWithImpostor(mesh: AbstractMesh, impostor: PhysicsImpostor): void; - dispose(): void; - } -} - -declare module BABYLON { - class PhysicsHelper { - private _scene; - private _physicsEngine; - constructor(scene: Scene); + setPositionsForCPUSkinning(): Float32Array; /** - * @param {Vector3} origin the origin of the explosion - * @param {number} radius the explosion radius - * @param {number} strength the explosion strength - * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant + * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. */ - applyRadialExplosionImpulse(origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff): Nullable; + setNormalsForCPUSkinning(): Float32Array; /** - * @param {Vector3} origin the origin of the explosion - * @param {number} radius the explosion radius - * @param {number} strength the explosion strength - * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant + * Updates the vertex buffer by applying transformation from the bones. + * Returns the Mesh. + * + * @param {skeleton} skeleton to apply */ - applyRadialExplosionForce(origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff): Nullable; + applySkeleton(skeleton: Skeleton): Mesh; /** - * @param {Vector3} origin the origin of the explosion - * @param {number} radius the explosion radius - * @param {number} strength the explosion strength - * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant + * Returns an object `{min:` Vector3`, max:` Vector3`}` + * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system */ - gravitationalField(origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff): Nullable; + static MinMax(meshes: AbstractMesh[]): { + min: Vector3; + max: Vector3; + }; /** - * @param {Vector3} origin the origin of the updraft - * @param {number} radius the radius of the updraft - * @param {number} strength the strength of the updraft - * @param {number} height the height of the updraft - * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center + * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array. */ - updraft(origin: Vector3, radius: number, strength: number, height: number, updraftMode?: PhysicsUpdraftMode): Nullable; + static Center(meshesOrMinMaxVector: { + min: Vector3; + max: Vector3; + } | AbstractMesh[]): Vector3; /** - * @param {Vector3} origin the of the vortex - * @param {number} radius the radius of the vortex - * @param {number} strength the strength of the vortex - * @param {number} height the height of the vortex + * Merge the array of meshes into a single mesh for performance reasons. + * @param {Array} meshes - The vertices source. They should all be of the same material. Entries can empty + * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes + * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true. + * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class. + * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source. */ - vortex(origin: Vector3, radius: number, strength: number, height: number): Nullable; + static MergeMeshes(meshes: Array, disposeSource?: boolean, allow32BitsIndices?: boolean, meshSubclass?: Mesh, subdivideWithSubMeshes?: boolean): Nullable; } - /***** Radial explosion *****/ - class PhysicsRadialExplosionEvent { - private _scene; - private _sphere; - private _sphereOptions; - private _rays; - private _dataFetched; - constructor(scene: Scene); - /** - * Returns the data related to the radial explosion event (sphere & rays). - * @returns {PhysicsRadialExplosionEventData} - */ - getData(): PhysicsRadialExplosionEventData; +} + +declare module BABYLON { + /** + * Define an interface for all classes that will get and set the data on vertices + */ + interface IGetSetVerticesData { + isVerticesDataPresent(kind: string): boolean; + getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable; + getIndices(copyWhenShared?: boolean): Nullable; + setVerticesData(kind: string, data: FloatArray, updatable: boolean): void; + updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): void; + setIndices(indices: IndicesArray, totalVertices: Nullable, updatable?: boolean): void; + } + /** + * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance + */ + class VertexData { /** - * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse. - * @param impostor - * @param {Vector3} origin the origin of the explosion - * @param {number} radius the explosion radius - * @param {number} strength the explosion strength - * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear - * @returns {Nullable} + * An array of the x, y, z position of each vertex [...., x, y, z, .....] */ - getImpostorForceAndContactPoint(impostor: PhysicsImpostor, origin: Vector3, radius: number, strength: number, falloff: PhysicsRadialImpulseFalloff): Nullable; + positions: Nullable; /** - * Disposes the sphere. - * @param {bolean} force + * An array of the x, y, z normal vector of each vertex [...., x, y, z, .....] */ - dispose(force?: boolean): void; - /*** Helpers ***/ - private _prepareSphere(); - private _intersectsWithSphere(impostor, origin, radius); - } - /***** Gravitational Field *****/ - class PhysicsGravitationalFieldEvent { - private _physicsHelper; - private _scene; - private _origin; - private _radius; - private _strength; - private _falloff; - private _tickCallback; - private _sphere; - private _dataFetched; - constructor(physicsHelper: PhysicsHelper, scene: Scene, origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff); + normals: Nullable; /** - * Returns the data related to the gravitational field event (sphere). - * @returns {PhysicsGravitationalFieldEventData} + * An array of the x, y, z tangent vector of each vertex [...., x, y, z, .....] */ - getData(): PhysicsGravitationalFieldEventData; + tangents: Nullable; /** - * Enables the gravitational field. + * An array of u,v which maps a texture image onto each vertex [...., u, v, .....] */ - enable(): void; + uvs: Nullable; /** - * Disables the gravitational field. + * A second array of u,v which maps a texture image onto each vertex [...., u, v, .....] */ - disable(): void; + uvs2: Nullable; /** - * Disposes the sphere. - * @param {bolean} force + * A third array of u,v which maps a texture image onto each vertex [...., u, v, .....] */ - dispose(force?: boolean): void; - private _tick(); - } - /***** Updraft *****/ - class PhysicsUpdraftEvent { - private _scene; - private _origin; - private _radius; - private _strength; - private _height; - private _updraftMode; - private _physicsEngine; - private _originTop; - private _originDirection; - private _tickCallback; - private _cylinder; - private _cylinderPosition; - private _dataFetched; - constructor(_scene: Scene, _origin: Vector3, _radius: number, _strength: number, _height: number, _updraftMode: PhysicsUpdraftMode); + uvs3: Nullable; /** - * Returns the data related to the updraft event (cylinder). - * @returns {PhysicsUpdraftEventData} + * A fourth array of u,v which maps a texture image onto each vertex [...., u, v, .....] */ - getData(): PhysicsUpdraftEventData; + uvs4: Nullable; /** - * Enables the updraft. + * A fifth array of u,v which maps a texture image onto each vertex [...., u, v, .....] */ - enable(): void; + uvs5: Nullable; /** - * Disables the cortex. + * A sixth array of u,v which maps a texture image onto each vertex [...., u, v, .....] */ - disable(): void; + uvs6: Nullable; /** - * Disposes the sphere. - * @param {bolean} force + * An array of the r, g, b, a, color of each vertex [...., r, g, b, a, .....] */ - dispose(force?: boolean): void; - private getImpostorForceAndContactPoint(impostor); - private _tick(); - /*** Helpers ***/ - private _prepareCylinder(); - private _intersectsWithCylinder(impostor); - } - /***** Vortex *****/ - class PhysicsVortexEvent { - private _scene; - private _origin; - private _radius; - private _strength; - private _height; - private _physicsEngine; - private _originTop; - private _centripetalForceThreshold; - private _updraftMultiplier; - private _tickCallback; - private _cylinder; - private _cylinderPosition; - private _dataFetched; - constructor(_scene: Scene, _origin: Vector3, _radius: number, _strength: number, _height: number); + colors: Nullable; /** - * Returns the data related to the vortex event (cylinder). - * @returns {PhysicsVortexEventData} + * An array containing the list of indices to the array of matrices produced by bones, each vertex have up to 4 indices (8 if the matricesIndicesExtra is set). */ - getData(): PhysicsVortexEventData; + matricesIndices: Nullable; /** - * Enables the vortex. + * An array containing the list of weights defining the weight of each indexed matrix in the final computation */ - enable(): void; + matricesWeights: Nullable; /** - * Disables the cortex. + * An array extending the number of possible indices */ - disable(): void; + matricesIndicesExtra: Nullable; /** - * Disposes the sphere. - * @param {bolean} force + * An array extending the number of possible weights when the number of indices is extended */ - dispose(force?: boolean): void; - private getImpostorForceAndContactPoint(impostor); - private _tick(); - /*** Helpers ***/ - private _prepareCylinder(); - private _intersectsWithCylinder(impostor); - } - /***** Enums *****/ - /** - * The strenght of the force in correspondence to the distance of the affected object - */ - enum PhysicsRadialImpulseFalloff { - /** Defines that impulse is constant in strength across it's whole radius */ - Constant = 0, - /** DEfines that impulse gets weaker if it's further from the origin */ - Linear = 1, - } - /** - * The strenght of the force in correspondence to the distance of the affected object - */ - enum PhysicsUpdraftMode { - /** Defines that the upstream forces will pull towards the top center of the cylinder */ - Center = 0, - /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */ - Perpendicular = 1, - } - /***** Data interfaces *****/ - interface PhysicsForceAndContactPoint { - force: Vector3; - contactPoint: Vector3; - } - interface PhysicsRadialExplosionEventData { - sphere: Mesh; - rays: Array; - } - interface PhysicsGravitationalFieldEventData { - sphere: Mesh; - } - interface PhysicsUpdraftEventData { - cylinder: Mesh; - } - interface PhysicsVortexEventData { - cylinder: Mesh; - } -} - -declare module BABYLON { - interface PhysicsImpostorParameters { - mass: number; - friction?: number; - restitution?: number; - nativeOptions?: any; - ignoreParent?: boolean; - disableBidirectionalTransformation?: boolean; - } - interface IPhysicsEnabledObject { - position: Vector3; - rotationQuaternion: Nullable; - scaling: Vector3; - rotation?: Vector3; - parent?: any; - getBoundingInfo(): BoundingInfo; - computeWorldMatrix(force: boolean): Matrix; - getWorldMatrix?(): Matrix; - getChildMeshes?(directDescendantsOnly?: boolean): Array; - getVerticesData(kind: string): Nullable | Float32Array>; - getIndices?(): Nullable; - getScene?(): Scene; - getAbsolutePosition(): Vector3; - getAbsolutePivotPoint(): Vector3; - rotate(axis: Vector3, amount: number, space?: Space): TransformNode; - translate(axis: Vector3, distance: number, space?: Space): TransformNode; - setAbsolutePosition(absolutePosition: Vector3): TransformNode; - getClassName(): string; - } - class PhysicsImpostor { - object: IPhysicsEnabledObject; - type: number; - private _options; - private _scene; - static DEFAULT_OBJECT_SIZE: Vector3; - static IDENTITY_QUATERNION: Quaternion; - private _physicsEngine; - private _physicsBody; - private _bodyUpdateRequired; - private _onBeforePhysicsStepCallbacks; - private _onAfterPhysicsStepCallbacks; - private _onPhysicsCollideCallbacks; - private _deltaPosition; - private _deltaRotation; - private _deltaRotationConjugated; - private _parent; - private _isDisposed; - private static _tmpVecs; - private static _tmpQuat; - readonly isDisposed: boolean; - mass: number; - friction: number; - restitution: number; - uniqueId: number; - private _joints; - constructor(object: IPhysicsEnabledObject, type: number, _options?: PhysicsImpostorParameters, _scene?: Scene | undefined); + matricesWeightsExtra: Nullable; /** - * This function will completly initialize this impostor. - * It will create a new body - but only if this mesh has no parent. - * If it has, this impostor will not be used other than to define the impostor - * of the child mesh. + * An array of i, j, k the three vertex indices required for each triangular facet [...., i, j, k .....] */ - - private _getPhysicsParent(); + indices: Nullable; /** - * Should a new body be generated. + * Uses the passed data array to set the set the values for the specified kind of data + * @param data a linear array of floating numbers + * @param kind the type of data that is being set, eg positions, colors etc */ - isBodyInitRequired(): boolean; - setScalingUpdated(updated: boolean): void; + set(data: FloatArray, kind: string): void; /** - * Force a regeneration of this or the parent's impostor's body. - * Use under cautious - This will remove all joints already implemented. + * Associates the vertexData to the passed Mesh. + * Sets it as updatable or not (default `false`) + * @param mesh the mesh the vertexData is applied to + * @param updatable when used and having the value true allows new data to update the vertexData + * @returns the VertexData */ - forceUpdate(): void; + applyToMesh(mesh: Mesh, updatable?: boolean): VertexData; /** - * Gets the body that holds this impostor. Either its own, or its parent. + * Associates the vertexData to the passed Geometry. + * Sets it as updatable or not (default `false`) + * @param geometry the geometry the vertexData is applied to + * @param updatable when used and having the value true allows new data to update the vertexData + * @returns VertexData */ + applyToGeometry(geometry: Geometry, updatable?: boolean): VertexData; /** - * Set the physics body. Used mainly by the physics engine/plugin + * Updates the associated mesh + * @param mesh the mesh to be updated + * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false + * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false + * @returns VertexData */ - physicsBody: any; - parent: Nullable; - resetUpdateFlags(): void; - getObjectExtendSize(): Vector3; - getObjectCenter(): Vector3; + updateMesh(mesh: Mesh, updateExtends?: boolean, makeItUnique?: boolean): VertexData; /** - * Get a specific parametes from the options parameter. + * Updates the associated geometry + * @param geometry the geometry to be updated + * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false + * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false + * @returns VertexData. */ - getParam(paramName: string): any; + updateGeometry(geometry: Geometry, updateExtends?: boolean, makeItUnique?: boolean): VertexData; + private _applyTo; + private _update; /** - * Sets a specific parameter in the options given to the physics plugin + * Transforms each position and each normal of the vertexData according to the passed Matrix + * @param matrix the transforming matrix + * @returns the VertexData */ - setParam(paramName: string, value: number): void; + transform(matrix: Matrix): VertexData; /** - * Specifically change the body's mass option. Won't recreate the physics body object + * Merges the passed VertexData into the current one + * @param other the VertexData to be merged into the current one + * @returns the modified VertexData */ - setMass(mass: number): void; - getLinearVelocity(): Nullable; - setLinearVelocity(velocity: Nullable): void; - getAngularVelocity(): Nullable; - setAngularVelocity(velocity: Nullable): void; + merge(other: VertexData): VertexData; + private _mergeElement; + private _validate; /** - * Execute a function with the physics plugin native code. - * Provide a function the will have two variables - the world object and the physics body object. + * Serializes the VertexData + * @returns a serialized object */ - executeNativeFunction(func: (world: any, physicsBody: any) => void): void; + serialize(): any; /** - * Register a function that will be executed before the physics world is stepping forward. + * Extracts the vertexData from a mesh + * @param mesh the mesh from which to extract the VertexData + * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false + * @param forceCopy indicating that the VertexData must be cloned, optional, default false + * @returns the object VertexData associated to the passed mesh */ - registerBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void; - unregisterBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void; + static ExtractFromMesh(mesh: Mesh, copyWhenShared?: boolean, forceCopy?: boolean): VertexData; /** - * Register a function that will be executed after the physics step + * Extracts the vertexData from the geometry + * @param geometry the geometry from which to extract the VertexData + * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false + * @param forceCopy indicating that the VertexData must be cloned, optional, default false + * @returns the object VertexData associated to the passed mesh */ - registerAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void; - unregisterAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void; + static ExtractFromGeometry(geometry: Geometry, copyWhenShared?: boolean, forceCopy?: boolean): VertexData; + private static _ExtractFrom; /** - * register a function that will be executed when this impostor collides against a different body. + * Creates the VertexData for a Ribbon + * @param options an object used to set the following optional parameters for the ribbon, required but can be empty + * * pathArray array of paths, each of which an array of successive Vector3 + * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false + * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false + * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false + * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional + * * colors a linear array, of length 4 * number of vertices, of custom color values, optional + * @returns the VertexData of the ribbon */ - registerOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor) => void): void; - unregisterOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor | Array) => void): void; - private _tmpQuat; - private _tmpQuat2; - getParentsRotation(): Quaternion; + static CreateRibbon(options: { + pathArray: Vector3[][]; + closeArray?: boolean; + closePath?: boolean; + offset?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + invertUV?: boolean; + uvs?: Vector2[]; + colors?: Color4[]; + }): VertexData; /** - * this function is executed by the physics engine. + * Creates the VertexData for a box + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * size sets the width, height and depth of the box to the value of size, optional default 1 + * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size + * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size + * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size + * * faceUV an array of 6 Vector4 elements used to set different images to each box side + * * faceColors an array of 6 Color3 elements used to set different colors to each box side + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the box */ - beforeStep: () => void; + static CreateBox(options: { + size?: number; + width?: number; + height?: number; + depth?: number; + faceUV?: Vector4[]; + faceColors?: Color4[]; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * this function is executed by the physics engine. + * Creates the VertexData for an ellipsoid, defaults to a sphere + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * segments sets the number of horizontal strips optional, default 32 + * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1 + * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter + * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter + * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter + * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1 + * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1 + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the ellipsoid */ - afterStep: () => void; + static CreateSphere(options: { + segments?: number; + diameter?: number; + diameterX?: number; + diameterY?: number; + diameterZ?: number; + arc?: number; + slice?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * Legacy collision detection event support + * Creates the VertexData for a cylinder, cone or prism + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * height sets the height (y direction) of the cylinder, optional, default 2 + * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter + * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter + * * diameter sets the diameter of the top and bottom of the cone, optional default 1 + * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 + * * subdivisions` the number of rings along the cylinder height, optional, default 1 + * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1 + * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively + * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively + * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false + * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the cylinder, cone or prism */ - onCollideEvent: Nullable<(collider: PhysicsImpostor, collidedWith: PhysicsImpostor) => void>; - onCollide: (e: { - body: any; - }) => void; + static CreateCylinder(options: { + height?: number; + diameterTop?: number; + diameterBottom?: number; + diameter?: number; + tessellation?: number; + subdivisions?: number; + arc?: number; + faceColors?: Color4[]; + faceUV?: Vector4[]; + hasRings?: boolean; + enclose?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * Apply a force + * Creates the VertexData for a torus + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * diameter the diameter of the torus, optional default 1 + * * thickness the diameter of the tube forming the torus, optional default 0.5 + * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the torus */ - applyForce(force: Vector3, contactPoint: Vector3): PhysicsImpostor; + static CreateTorus(options: { + diameter?: number; + thickness?: number; + tessellation?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * Apply an impulse + * Creates the VertexData of the LineSystem + * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty + * - lines an array of lines, each line being an array of successive Vector3 + * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point + * @returns the VertexData of the LineSystem */ - applyImpulse(force: Vector3, contactPoint: Vector3): PhysicsImpostor; + static CreateLineSystem(options: { + lines: Vector3[][]; + colors?: Nullable; + }): VertexData; /** - * A help function to create a joint. + * Create the VertexData for a DashedLines + * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty + * - points an array successive Vector3 + * - dashSize the size of the dashes relative to the dash number, optional, default 3 + * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1 + * - dashNb the intended total number of dashes, optional, default 200 + * @returns the VertexData for the DashedLines */ - createJoint(otherImpostor: PhysicsImpostor, jointType: number, jointData: PhysicsJointData): PhysicsImpostor; + static CreateDashedLines(options: { + points: Vector3[]; + dashSize?: number; + gapSize?: number; + dashNb?: number; + }): VertexData; /** - * Add a joint to this impostor with a different impostor. + * Creates the VertexData for a Ground + * @param options an object used to set the following optional parameters for the Ground, required but can be empty + * - width the width (x direction) of the ground, optional, default 1 + * - height the height (z direction) of the ground, optional, default 1 + * - subdivisions the number of subdivisions per side, optional, default 1 + * @returns the VertexData of the Ground */ - addJoint(otherImpostor: PhysicsImpostor, joint: PhysicsJoint): PhysicsImpostor; + static CreateGround(options: { + width?: number; + height?: number; + subdivisions?: number; + subdivisionsX?: number; + subdivisionsY?: number; + }): VertexData; /** - * Will keep this body still, in a sleep mode. + * Creates the VertexData for a TiledGround by subdividing the ground into tiles + * @param options an object used to set the following optional parameters for the Ground, required but can be empty + * * xmin the ground minimum X coordinate, optional, default -1 + * * zmin the ground minimum Z coordinate, optional, default -1 + * * xmax the ground maximum X coordinate, optional, default 1 + * * zmax the ground maximum Z coordinate, optional, default 1 + * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6} + * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2} + * @returns the VertexData of the TiledGround */ - sleep(): PhysicsImpostor; + static CreateTiledGround(options: { + xmin: number; + zmin: number; + xmax: number; + zmax: number; + subdivisions?: { + w: number; + h: number; + }; + precision?: { + w: number; + h: number; + }; + }): VertexData; /** - * Wake the body up. + * Creates the VertexData of the Ground designed from a heightmap + * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap + * * width the width (x direction) of the ground + * * height the height (z direction) of the ground + * * subdivisions the number of subdivisions per side + * * minHeight the minimum altitude on the ground, optional, default 0 + * * maxHeight the maximum altitude on the ground, optional default 1 + * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11) + * * buffer the array holding the image color data + * * bufferWidth the width of image + * * bufferHeight the height of image + * @returns the VertexData of the Ground designed from a heightmap */ - wakeUp(): PhysicsImpostor; - clone(newObject: IPhysicsEnabledObject): Nullable; - dispose(): void; - setDeltaPosition(position: Vector3): void; - setDeltaRotation(rotation: Quaternion): void; - getBoxSizeToRef(result: Vector3): PhysicsImpostor; - getRadius(): number; + static CreateGroundFromHeightMap(options: { + width: number; + height: number; + subdivisions: number; + minHeight: number; + maxHeight: number; + colorFilter: Color3; + buffer: Uint8Array; + bufferWidth: number; + bufferHeight: number; + }): VertexData; /** - * Sync a bone with this impostor - * @param bone The bone to sync to the impostor. - * @param boneMesh The mesh that the bone is influencing. - * @param jointPivot The pivot of the joint / bone in local space. - * @param distToJoint Optional distance from the impostor to the joint. - * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. + * Creates the VertexData for a Plane + * @param options an object used to set the following optional parameters for the plane, required but can be empty + * * size sets the width and height of the plane to the value of size, optional default 1 + * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size + * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the box */ - syncBoneWithImpostor(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion): void; + static CreatePlane(options: { + size?: number; + width?: number; + height?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * Sync impostor to a bone - * @param bone The bone that the impostor will be synced to. - * @param boneMesh The mesh that the bone is influencing. - * @param jointPivot The pivot of the joint / bone in local space. - * @param distToJoint Optional distance from the impostor to the joint. - * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. - * @param boneAxis Optional vector3 axis the bone is aligned with + * Creates the VertexData of the Disc or regular Polygon + * @param options an object used to set the following optional parameters for the disc, required but can be empty + * * radius the radius of the disc, optional default 0.5 + * * tessellation the number of polygon sides, optional, default 64 + * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1 + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the box */ - syncImpostorWithBone(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion, boneAxis?: Vector3): void; - static NoImpostor: number; - static SphereImpostor: number; - static BoxImpostor: number; - static PlaneImpostor: number; - static MeshImpostor: number; - static CylinderImpostor: number; - static ParticleImpostor: number; - static HeightmapImpostor: number; - } -} - -declare module BABYLON { - interface PhysicsJointData { - mainPivot?: Vector3; - connectedPivot?: Vector3; - mainAxis?: Vector3; - connectedAxis?: Vector3; - collision?: boolean; - nativeParams?: any; - } - /** - * This is a holder class for the physics joint created by the physics plugin. - * It holds a set of functions to control the underlying joint. - */ - class PhysicsJoint { - type: number; - jointData: PhysicsJointData; - private _physicsJoint; - protected _physicsPlugin: IPhysicsEnginePlugin; - constructor(type: number, jointData: PhysicsJointData); - physicsJoint: any; - physicsPlugin: IPhysicsEnginePlugin; + static CreateDisc(options: { + radius?: number; + tessellation?: number; + arc?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * Execute a function that is physics-plugin specific. - * @param {Function} func the function that will be executed. - * It accepts two parameters: the physics world and the physics joint. + * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build() + * All parameters are provided by MeshBuilder.CreatePolygon as needed + * @param polygon a mesh built from polygonTriangulation.build() + * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively + * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively + * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the Polygon */ - executeNativeFunction(func: (world: any, physicsJoint: any) => void): void; - static DistanceJoint: number; - static HingeJoint: number; - static BallAndSocketJoint: number; - static WheelJoint: number; - static SliderJoint: number; - static PrismaticJoint: number; - static UniversalJoint: number; - static Hinge2Joint: number; - static PointToPointJoint: number; - static SpringJoint: number; - static LockJoint: number; - } - /** - * A class representing a physics distance joint. - */ - class DistanceJoint extends PhysicsJoint { - constructor(jointData: DistanceJointData); + static CreatePolygon(polygon: Mesh, sideOrientation: number, fUV?: Vector4[], fColors?: Color4[], frontUVs?: Vector4, backUVs?: Vector4): VertexData; /** - * Update the predefined distance. + * Creates the VertexData of the IcoSphere + * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty + * * radius the radius of the IcoSphere, optional default 1 + * * radiusX allows stretching in the x direction, optional, default radius + * * radiusY allows stretching in the y direction, optional, default radius + * * radiusZ allows stretching in the z direction, optional, default radius + * * flat when true creates a flat shaded mesh, optional, default true + * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the IcoSphere */ - updateDistance(maxDistance: number, minDistance?: number): void; - } - class MotorEnabledJoint extends PhysicsJoint implements IMotorEnabledJoint { - constructor(type: number, jointData: PhysicsJointData); + static CreateIcoSphere(options: { + radius?: number; + radiusX?: number; + radiusY?: number; + radiusZ?: number; + flat?: boolean; + subdivisions?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * Set the motor values. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param {number} force the force to apply - * @param {number} maxForce max force for this motor. + * Creates the VertexData for a Polyhedron + * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty + * * type provided types are: + * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1) + * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20) + * * size the size of the IcoSphere, optional default 1 + * * sizeX allows stretching in the x direction, optional, default size + * * sizeY allows stretching in the y direction, optional, default size + * * sizeZ allows stretching in the z direction, optional, default size + * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor + * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively + * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively + * * flat when true creates a flat shaded mesh, optional, default true + * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the Polyhedron */ - setMotor(force?: number, maxForce?: number): void; + static CreatePolyhedron(options: { + type?: number; + size?: number; + sizeX?: number; + sizeY?: number; + sizeZ?: number; + custom?: any; + faceUV?: Vector4[]; + faceColors?: Color4[]; + flat?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * Set the motor's limits. - * Attention, this function is plugin specific. Engines won't react 100% the same. + * Creates the VertexData for a TorusKnot + * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty + * * radius the radius of the torus knot, optional, default 2 + * * tube the thickness of the tube, optional, default 0.5 + * * radialSegments the number of sides on each tube segments, optional, default 32 + * * tubularSegments the number of tubes to decompose the knot into, optional, default 32 + * * p the number of windings around the z axis, optional, default 2 + * * q the number of windings around the x axis, optional, default 3 + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the Torus Knot */ - setLimit(upperLimit: number, lowerLimit?: number): void; - } - /** - * This class represents a single hinge physics joint - */ - class HingeJoint extends MotorEnabledJoint { - constructor(jointData: PhysicsJointData); + static CreateTorusKnot(options: { + radius?: number; + tube?: number; + radialSegments?: number; + tubularSegments?: number; + p?: number; + q?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * Set the motor values. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param {number} force the force to apply - * @param {number} maxForce max force for this motor. + * Compute normals for given positions and indices + * @param positions an array of vertex positions, [...., x, y, z, ......] + * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......] + * @param normals an array of vertex normals, [...., x, y, z, ......] + * @param options an object used to set the following optional parameters for the TorusKnot, optional + * * facetNormals : optional array of facet normals (vector3) + * * facetPositions : optional array of facet positions (vector3) + * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation + * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation + * * bInfo : optional bounding info, required for facetPartitioning computation + * * bbSize : optional bounding box size data, required for facetPartitioning computation + * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation + * * useRightHandedSystem: optional boolean to for right handed system computation + * * depthSort : optional boolean to enable the facet depth sort computation + * * distanceTo : optional Vector3 to compute the facet depth from this location + * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location */ - setMotor(force?: number, maxForce?: number): void; + static ComputeNormals(positions: any, indices: any, normals: any, options?: { + facetNormals?: any; + facetPositions?: any; + facetPartitioning?: any; + ratio?: number; + bInfo?: any; + bbSize?: Vector3; + subDiv?: any; + useRightHandedSystem?: boolean; + depthSort?: boolean; + distanceTo?: Vector3; + depthSortedFacets?: any; + }): void; + private static _ComputeSides; /** - * Set the motor's limits. - * Attention, this function is plugin specific. Engines won't react 100% the same. + * Applies VertexData created from the imported parameters to the geometry + * @param parsedVertexData the parsed data from an imported file + * @param geometry the geometry to apply the VertexData to */ - setLimit(upperLimit: number, lowerLimit?: number): void; + static ImportVertexData(parsedVertexData: any, geometry: Geometry): void; } +} + +declare module BABYLON { /** - * This class represents a dual hinge physics joint (same as wheel joint) + * Class containing static functions to help procedurally build meshes */ - class Hinge2Joint extends MotorEnabledJoint { - constructor(jointData: PhysicsJointData); + class MeshBuilder { + private static updateSideOrientation; + /** + * Creates a box mesh + * * The parameter `size` sets the size (float) of each box side (default 1) + * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`) + * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements) + * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the box mesh + */ + static CreateBox(name: string, options: { + size?: number; + width?: number; + height?: number; + depth?: number; + faceUV?: Vector4[]; + faceColors?: Color4[]; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + updatable?: boolean; + }, scene?: Nullable): Mesh; + /** + * Creates a sphere mesh + * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1) + * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`) + * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32) + * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio + * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude) + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the sphere mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere + */ + static CreateSphere(name: string, options: { + segments?: number; + diameter?: number; + diameterX?: number; + diameterY?: number; + diameterZ?: number; + arc?: number; + slice?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + updatable?: boolean; + }, scene: any): Mesh; + /** + * Creates a plane polygonal mesh. By default, this is a disc + * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5) + * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc + * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the plane polygonal mesh + * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon + */ + static CreateDisc(name: string, options: { + radius?: number; + tessellation?: number; + arc?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene?: Nullable): Mesh; + /** + * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided + * * The parameter `radius` sets the radius size (float) of the icosphere (default 1) + * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`) + * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size + * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the icosahedron mesh + * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere + */ + static CreateIcoSphere(name: string, options: { + radius?: number; + radiusX?: number; + radiusY?: number; + radiusZ?: number; + flat?: boolean; + subdivisions?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + updatable?: boolean; + }, scene: Scene): Mesh; + /** + * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters + * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry + * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array + * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array + * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path + * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11 + * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture + * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones + * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values + * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry + * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the ribbon mesh + * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial + * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes + */ + static CreateRibbon(name: string, options: { + pathArray: Vector3[][]; + closeArray?: boolean; + closePath?: boolean; + offset?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + instance?: Mesh; + invertUV?: boolean; + uvs?: Vector2[]; + colors?: Color4[]; + }, scene?: Nullable): Mesh; + /** + * Creates a cylinder or a cone mesh + * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2). + * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1). + * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero. + * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance. + * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1). + * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces. + * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis. + * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder. + * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements). + * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3 + * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7 + * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17 + * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface. + * * If `enclose` is false, a ring surface is one element. + * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces. + * * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379 + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the cylinder mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone + */ + static CreateCylinder(name: string, options: { + height?: number; + diameterTop?: number; + diameterBottom?: number; + diameter?: number; + tessellation?: number; + subdivisions?: number; + arc?: number; + faceColors?: Color4[]; + faceUV?: Vector4[]; + updatable?: boolean; + hasRings?: boolean; + enclose?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene: any): Mesh; + /** + * Creates a torus mesh + * * The parameter `diameter` sets the diameter size (float) of the torus (default 1) + * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5) + * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16) + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the torus mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus + */ + static CreateTorus(name: string, options: { + diameter?: number; + thickness?: number; + tessellation?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene: any): Mesh; + /** + * Creates a torus knot mesh + * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2) + * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32) + * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32) + * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3) + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the torus knot mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot + */ + static CreateTorusKnot(name: string, options: { + radius?: number; + tube?: number; + radialSegments?: number; + tubularSegments?: number; + p?: number; + q?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene: any): Mesh; + /** + * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh + * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter + * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function + * * The parameter `lines` is an array of lines, each line being an array of successive Vector3 + * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter + * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point + * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster) + * * Updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines + * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system + * @param name defines the name of the new line system + * @param options defines the options used to create the line system + * @param scene defines the hosting scene + * @returns a new line system mesh + */ + static CreateLineSystem(name: string, options: { + lines: Vector3[][]; + updatable?: boolean; + instance?: Nullable; + colors?: Nullable; + useVertexAlpha?: boolean; + }, scene: Nullable): LinesMesh; + /** + * Creates a line mesh + * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter + * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function + * * The parameter `points` is an array successive Vector3 + * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines + * * The optional parameter `colors` is an array of successive Color4, one per line point + * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster) + * * When updating an instance, remember that only point positions can change, not the number of points + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines + * @param name defines the name of the new line system + * @param options defines the options used to create the line system + * @param scene defines the hosting scene + * @returns a new line mesh + */ + static CreateLines(name: string, options: { + points: Vector3[]; + updatable?: boolean; + instance?: Nullable; + colors?: Color4[]; + useVertexAlpha?: boolean; + }, scene?: Nullable): LinesMesh; + /** + * Creates a dashed line mesh + * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter + * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function + * * The parameter `points` is an array successive Vector3 + * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200) + * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3) + * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1) + * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines + * * When updating an instance, remember that only point positions can change, not the number of points + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the dashed line mesh + * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines + */ + static CreateDashedLines(name: string, options: { + points: Vector3[]; + dashSize?: number; + gapSize?: number; + dashNb?: number; + updatable?: boolean; + instance?: LinesMesh; + }, scene?: Nullable): LinesMesh; + /** + * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. + * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis. + * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. + * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve. + * * The parameter `scale` (float, default 1) is the value to scale the shape. + * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape + * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture. + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the extruded shape mesh + * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes + * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes + * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes + */ + static ExtrudeShape(name: string, options: { + shape: Vector3[]; + path: Vector3[]; + scale?: number; + rotation?: number; + cap?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + instance?: Mesh; + invertUV?: boolean; + }, scene?: Nullable): Mesh; + /** + * Creates an custom extruded shape mesh. + * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. + * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis. + * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. + * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path + * * It must returns a float value that will be the rotation in radians applied to the shape on each path point. + * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path + * * It must returns a float value that will be the scale value applied to the shape on each path point + * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray` + * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray` + * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape + * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the custom extruded shape mesh + * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes + * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes + * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes + */ + static ExtrudeShapeCustom(name: string, options: { + shape: Vector3[]; + path: Vector3[]; + scaleFunction?: any; + rotationFunction?: any; + ribbonCloseArray?: boolean; + ribbonClosePath?: boolean; + cap?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + instance?: Mesh; + invertUV?: boolean; + }, scene: Scene): Mesh; + /** + * Creates lathe mesh. + * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe + * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero + * * The parameter `radius` (positive float, default 1) is the radius value of the lathe + * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe + * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides + * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape + * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc" + * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the lathe mesh + * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe + */ + static CreateLathe(name: string, options: { + shape: Vector3[]; + radius?: number; + tessellation?: number; + clip?: number; + arc?: number; + closed?: boolean; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + cap?: number; + invertUV?: boolean; + }, scene: Scene): Mesh; + /** + * Creates a plane mesh + * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1) + * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`) + * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the plane mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane + */ + static CreatePlane(name: string, options: { + size?: number; + width?: number; + height?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + updatable?: boolean; + sourcePlane?: Plane; + }, scene: Scene): Mesh; + /** + * Creates a ground mesh + * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground + * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the ground mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane + */ + static CreateGround(name: string, options: { + width?: number; + height?: number; + subdivisions?: number; + subdivisionsX?: number; + subdivisionsY?: number; + updatable?: boolean; + }, scene: any): Mesh; + /** + * Creates a tiled ground mesh + * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates + * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates + * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile + * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the tiled ground mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground + */ + static CreateTiledGround(name: string, options: { + xmin: number; + zmin: number; + xmax: number; + zmax: number; + subdivisions?: { + w: number; + h: number; + }; + precision?: { + w: number; + h: number; + }; + updatable?: boolean; + }, scene: Scene): Mesh; + /** + * Creates a ground mesh from a height map + * * The parameter `url` sets the URL of the height map image resource. + * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes. + * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side. + * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground. + * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground. + * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height. + * * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time). + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param url defines the url to the height map + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the ground mesh + * @see http://doc.babylonjs.com/babylon101/height_map + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map + */ + static CreateGroundFromHeightMap(name: string, url: string, options: { + width?: number; + height?: number; + subdivisions?: number; + minHeight?: number; + maxHeight?: number; + colorFilter?: Color3; + updatable?: boolean; + onReady?: (mesh: GroundMesh) => void; + }, scene: Scene): GroundMesh; + /** + * Creates a polygon mesh + * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh + * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors + * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4) + * * Remember you can only change the shape positions, not their number when updating a polygon + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the polygon mesh + */ + static CreatePolygon(name: string, options: { + shape: Vector3[]; + holes?: Vector3[][]; + depth?: number; + faceUV?: Vector4[]; + faceColors?: Color4[]; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene: Scene): Mesh; + /** + * Creates an extruded polygon mesh, with depth in the Y direction. + * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements) + * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the polygon mesh + */ + static ExtrudePolygon(name: string, options: { + shape: Vector3[]; + holes?: Vector3[][]; + depth?: number; + faceUV?: Vector4[]; + faceColors?: Color4[]; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene: Scene): Mesh; + /** + * Creates a tube mesh. + * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters + * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube + * * The parameter `radius` (positive float, default 1) sets the tube radius size + * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface + * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius` + * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float) + * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc + * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the tube mesh + * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube + */ + static CreateTube(name: string, options: { + path: Vector3[]; + radius?: number; + tessellation?: number; + radiusFunction?: { + (i: number, distance: number): number; + }; + cap?: number; + arc?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + instance?: Mesh; + invertUV?: boolean; + }, scene: Scene): Mesh; + /** + * Creates a polyhedron mesh + * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type + * * The parameter `size` (positive float, default 1) sets the polygon size + * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value) + * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type` + * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron + * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`) + * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors + * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the polyhedron mesh + * @see http://doc.babylonjs.com/how_to/polyhedra_shapes + */ + static CreatePolyhedron(name: string, options: { + type?: number; + size?: number; + sizeX?: number; + sizeY?: number; + sizeZ?: number; + custom?: any; + faceUV?: Vector4[]; + faceColors?: Color4[]; + flat?: boolean; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene: Scene): Mesh; + /** + * Creates a decal mesh. + * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal + * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates + * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates + * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling + * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal + * @param name defines the name of the mesh + * @param sourceMesh defines the mesh where the decal must be applied + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the decal mesh + * @see http://doc.babylonjs.com/how_to/decals + */ + static CreateDecal(name: string, sourceMesh: AbstractMesh, options: { + position?: Vector3; + normal?: Vector3; + size?: Vector3; + angle?: number; + }): Mesh; + private static _ExtrudeShapeGeneric; + } +} + +declare module BABYLON { + class MeshLODLevel { + distance: number; + mesh: Nullable; + constructor(distance: number, mesh: Nullable); + } +} + +declare module BABYLON { + /** + * A simplifier interface for future simplification implementations. + */ + interface ISimplifier { + /** + * Simplification of a given mesh according to the given settings. + * Since this requires computation, it is assumed that the function runs async. + * @param settings The settings of the simplification, including quality and distance + * @param successCallback A callback that will be called after the mesh was simplified. + * @param errorCallback in case of an error, this callback will be called. optional. + */ + simplify(settings: ISimplificationSettings, successCallback: (simplifiedMeshes: Mesh) => void, errorCallback?: () => void): void; + } + /** + * Expected simplification settings. + * Quality should be between 0 and 1 (1 being 100%, 0 being 0%); + */ + interface ISimplificationSettings { + quality: number; + distance: number; + optimizeMesh?: boolean; + } + class SimplificationSettings implements ISimplificationSettings { + quality: number; + distance: number; + optimizeMesh?: boolean | undefined; + constructor(quality: number, distance: number, optimizeMesh?: boolean | undefined); + } + interface ISimplificationTask { + settings: Array; + simplificationType: SimplificationType; + mesh: Mesh; + successCallback?: () => void; + parallelProcessing: boolean; + } + class SimplificationQueue { + private _simplificationArray; + running: boolean; + constructor(); + addTask(task: ISimplificationTask): void; + executeNext(): void; + runSimplification(task: ISimplificationTask): void; + private getSimplifier; + } + /** + * The implemented types of simplification + * At the moment only Quadratic Error Decimation is implemented + */ + enum SimplificationType { + /** Quadratic error decimation */ + QUADRATIC = 0 + } + class DecimationTriangle { + vertices: Array; + normal: Vector3; + error: Array; + deleted: boolean; + isDirty: boolean; + borderFactor: number; + deletePending: boolean; + originalOffset: number; + constructor(vertices: Array); + } + class DecimationVertex { + position: Vector3; + id: number; + q: QuadraticMatrix; + isBorder: boolean; + triangleStart: number; + triangleCount: number; + originalOffsets: Array; + constructor(position: Vector3, id: number); + updatePosition(newPosition: Vector3): void; + } + class QuadraticMatrix { + data: Array; + constructor(data?: Array); + det(a11: number, a12: number, a13: number, a21: number, a22: number, a23: number, a31: number, a32: number, a33: number): number; + addInPlace(matrix: QuadraticMatrix): void; + addArrayInPlace(data: Array): void; + add(matrix: QuadraticMatrix): QuadraticMatrix; + static FromData(a: number, b: number, c: number, d: number): QuadraticMatrix; + static DataFromNumbers(a: number, b: number, c: number, d: number): number[]; + } + class Reference { + vertexId: number; + triangleId: number; + constructor(vertexId: number, triangleId: number); + } + /** + * An implementation of the Quadratic Error simplification algorithm. + * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf + * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS + * @author RaananW + */ + class QuadraticErrorSimplification implements ISimplifier { + private _mesh; + private triangles; + private vertices; + private references; + private _reconstructedMesh; + syncIterations: number; + aggressiveness: number; + decimationIterations: number; + boundingBoxEpsilon: number; + constructor(_mesh: Mesh); + simplify(settings: ISimplificationSettings, successCallback: (simplifiedMesh: Mesh) => void): void; + private runDecimation; + private initWithMesh; + private init; + private reconstructMesh; + private initDecimatedMesh; + private isFlipped; + private updateTriangles; + private identifyBorder; + private updateMesh; + private vertexError; + private calculateError; + } +} + +declare module BABYLON { + class Polygon { + static Rectangle(xmin: number, ymin: number, xmax: number, ymax: number): Vector2[]; + static Circle(radius: number, cx?: number, cy?: number, numberOfSides?: number): Vector2[]; + static Parse(input: string): Vector2[]; + static StartingAt(x: number, y: number): Path2; + } + class PolygonMeshBuilder { + private _points; + private _outlinepoints; + private _holes; + private _name; + private _scene; + private _epoints; + private _eholes; + private _addToepoint; + constructor(name: string, contours: Path2, scene: Scene); + constructor(name: string, contours: Vector2[], scene: Scene); + addHole(hole: Vector2[]): PolygonMeshBuilder; + build(updatable?: boolean, depth?: number): Mesh; + private addSide; + } +} + +declare module BABYLON { + class BaseSubMesh { + + + readonly effect: Nullable; + setEffect(effect: Nullable, defines?: Nullable): void; + } + class SubMesh extends BaseSubMesh implements ICullable { + materialIndex: number; + verticesStart: number; + verticesCount: number; + indexStart: number; + indexCount: number; + linesIndexCount: number; + private _mesh; + private _renderingMesh; + private _boundingInfo; + private _linesIndexBuffer; + + + + + + + + private _currentMaterial; + static AddToMesh(materialIndex: number, verticesStart: number, verticesCount: number, indexStart: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox?: boolean): SubMesh; + constructor(materialIndex: number, verticesStart: number, verticesCount: number, indexStart: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox?: boolean); + readonly IsGlobal: boolean; + /** + * Returns the submesh BoudingInfo object. + */ + getBoundingInfo(): BoundingInfo; + /** + * Sets the submesh BoundingInfo. + * Return the SubMesh. + */ + setBoundingInfo(boundingInfo: BoundingInfo): SubMesh; + /** + * Returns the mesh of the current submesh. + */ + getMesh(): AbstractMesh; + /** + * Returns the rendering mesh of the submesh. + */ + getRenderingMesh(): Mesh; + /** + * Returns the submesh material. + */ + getMaterial(): Nullable; + /** + * Sets a new updated BoundingInfo object to the submesh. + * Returns the SubMesh. + */ + refreshBoundingInfo(): SubMesh; + + /** + * Updates the submesh BoundingInfo. + * Returns the Submesh. + */ + updateBoundingInfo(world: Matrix): SubMesh; + /** + * True is the submesh bounding box intersects the frustum defined by the passed array of planes. + * Boolean returned. + */ + isInFrustum(frustumPlanes: Plane[]): boolean; + /** + * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes. + * Boolean returned. + */ + isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; + /** + * Renders the submesh. + * Returns it. + */ + render(enableAlphaMode: boolean): SubMesh; + /** + * Returns a new Index Buffer. + * Type returned : WebGLBuffer. + */ + getLinesIndexBuffer(indices: IndicesArray, engine: Engine): WebGLBuffer; + /** + * True is the passed Ray intersects the submesh bounding box. + * Boolean returned. + */ + canIntersects(ray: Ray): boolean; + /** + * Returns an object IntersectionInfo. + */ + intersects(ray: Ray, positions: Vector3[], indices: IndicesArray, fastCheck?: boolean): Nullable; + + /** + * Creates a new Submesh from the passed Mesh. + */ + clone(newMesh: AbstractMesh, newRenderingMesh?: Mesh): SubMesh; + /** + * Disposes the Submesh. + * Returns nothing. + */ + dispose(): void; + /** + * Creates a new Submesh from the passed parameters : + * - materialIndex (integer) : the index of the main mesh material. + * - startIndex (integer) : the index where to start the copy in the mesh indices array. + * - indexCount (integer) : the number of indices to copy then from the startIndex. + * - mesh (Mesh) : the main mesh to create the submesh from. + * - renderingMesh (optional Mesh) : rendering mesh. + */ + static CreateFromIndices(materialIndex: number, startIndex: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh): SubMesh; + } +} + +declare module BABYLON { + class TransformNode extends Node { + static BILLBOARDMODE_NONE: number; + static BILLBOARDMODE_X: number; + static BILLBOARDMODE_Y: number; + static BILLBOARDMODE_Z: number; + static BILLBOARDMODE_ALL: number; + private _forward; + private _forwardInverted; + private _up; + private _right; + private _rightInverted; + private _rotation; + private _rotationQuaternion; + protected _scaling: Vector3; + protected _isDirty: boolean; + private _transformToBoneReferal; + /** + * Set the billboard mode. Default is 0. + * + * | Value | Type | Description | + * | --- | --- | --- | + * | 0 | BILLBOARDMODE_NONE | | + * | 1 | BILLBOARDMODE_X | | + * | 2 | BILLBOARDMODE_Y | | + * | 4 | BILLBOARDMODE_Z | | + * | 7 | BILLBOARDMODE_ALL | | + * + */ + billboardMode: number; + scalingDeterminant: number; + infiniteDistance: boolean; + /** + * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored. + * By default the system will update normals to compensate + */ + ignoreNonUniformScaling: boolean; + position: Vector3; + + private _localWorld; + + + private _absolutePosition; + private _pivotMatrix; + private _pivotMatrixInverse; + private _postMultiplyPivotMatrix; + protected _isWorldMatrixFrozen: boolean; + /** + * An event triggered after the world matrix is updated + */ + onAfterWorldMatrixUpdateObservable: Observable; + constructor(name: string, scene?: Nullable, isPure?: boolean); + /** + * Gets a string idenfifying the name of the class + * @returns "TransformNode" string + */ + getClassName(): string; /** - * Set the motor values. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param {number} force the force to apply - * @param {number} maxForce max force for this motor. - * @param {motorIndex} the motor's index, 0 or 1. + * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z. + * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector! + * Default : (0.0, 0.0, 0.0) + */ + rotation: Vector3; + /** + * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z. + * Default : (1.0, 1.0, 1.0) */ - setMotor(force?: number, maxForce?: number, motorIndex?: number): void; /** - * Set the motor limits. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param {number} upperLimit the upper limit - * @param {number} lowerLimit lower limit - * @param {motorIndex} the motor's index, 0 or 1. + * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z. + * Default : (1.0, 1.0, 1.0) + */ + scaling: Vector3; + /** + * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion. + * It's null by default. + * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0) */ - setLimit(upperLimit: number, lowerLimit?: number, motorIndex?: number): void; - } - interface IMotorEnabledJoint { - physicsJoint: any; - setMotor(force?: number, maxForce?: number, motorIndex?: number): void; - setLimit(upperLimit: number, lowerLimit?: number, motorIndex?: number): void; - } - interface DistanceJointData extends PhysicsJointData { - maxDistance: number; - } - interface SpringJointData extends PhysicsJointData { - length: number; - stiffness: number; - damping: number; - } -} - -declare module BABYLON { - /** - * Class used to store all common mesh properties - */ - class AbstractMesh extends TransformNode implements IDisposable, ICullable, IGetSetVerticesData { - /** No occlusion */ - static OCCLUSION_TYPE_NONE: number; - /** Occlusion set to optimisitic */ - static OCCLUSION_TYPE_OPTIMISTIC: number; - /** Occlusion set to strict */ - static OCCLUSION_TYPE_STRICT: number; - /** Use an accurante occlusion algorithm */ - static OCCLUSION_ALGORITHM_TYPE_ACCURATE: number; - /** Use a conservative occlusion algorithm */ - static OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE: number; + rotationQuaternion: Nullable; /** - * No billboard + * The forward direction of that transform in world space. */ - static readonly BILLBOARDMODE_NONE: number; - /** Billboard on X axis */ - static readonly BILLBOARDMODE_X: number; - /** Billboard on Y axis */ - static readonly BILLBOARDMODE_Y: number; - /** Billboard on Z axis */ - static readonly BILLBOARDMODE_Z: number; - /** Billboard on all axes */ - static readonly BILLBOARDMODE_ALL: number; - private _facetPositions; - private _facetNormals; - private _facetPartitioning; - private _facetNb; - private _partitioningSubdivisions; - private _partitioningBBoxRatio; - private _facetDataEnabled; - private _facetParameters; - private _bbSize; - private _subDiv; - private _facetDepthSort; - private _facetDepthSortEnabled; - private _depthSortedIndices; - private _depthSortedFacets; - private _facetDepthSortFunction; - private _facetDepthSortFrom; - private _facetDepthSortOrigin; - private _invertedMatrix; + readonly forward: Vector3; /** - * Gets the number of facets in the mesh - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet + * The up direction of that transform in world space. */ - readonly facetNb: number; + readonly up: Vector3; /** - * Gets or set the number (integer) of subdivisions per axis in the partioning space - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning + * The right direction of that transform in world space. */ - partitioningSubdivisions: number; + readonly right: Vector3; /** - * The ratio (float) to apply to the bouding box size to set to the partioning space. - * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning + * Returns the latest update of the World matrix + * Returns a Matrix. */ - partitioningBBoxRatio: number; + getWorldMatrix(): Matrix; + /** @hidden */ + /** - * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`. - * Works only for updatable meshes. - * Doesn't work with multi-materials - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort + * Returns directly the latest state of the mesh World matrix. + * A Matrix is returned. */ - mustDepthSortFacets: boolean; + readonly worldMatrixFromCache: Matrix; /** - * The location (Vector3) where the facet depth sort must be computed from. - * By default, the active camera position. - * Used only when facet depth sort is enabled - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort + * Copies the paramater passed Matrix into the mesh Pose matrix. + * Returns the TransformNode. */ - facetDepthSortFrom: Vector3; + updatePoseMatrix(matrix: Matrix): TransformNode; /** - * gets a boolean indicating if facetData is enabled - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet + * Returns the mesh Pose matrix. + * Returned object : Matrix */ - readonly isFacetDataEnabled: boolean; - /** @hidden */ + getPoseMatrix(): Matrix; + + markAsDirty(property: string): TransformNode; /** - * An event triggered when this mesh collides with another one - */ - onCollideObservable: Observable; - private _onCollideObserver; - /** Set a function to call when this mesh collides with another one */ - onCollide: () => void; + * Returns the current mesh absolute position. + * Retuns a Vector3. + */ + readonly absolutePosition: Vector3; /** - * An event triggered when the collision's position changes - */ - onCollisionPositionChangeObservable: Observable; - private _onCollisionPositionChangeObserver; - /** Set a function to call when the collision's position changes */ - onCollisionPositionChange: () => void; + * Sets a new matrix to apply before all other transformation + * @param matrix defines the transform matrix + * @returns the current TransformNode + */ + setPreTransformMatrix(matrix: Matrix): TransformNode; /** - * An event triggered when material is changed + * Sets a new pivot matrix to the current node + * @param matrix defines the new pivot matrix to use + * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect + * @returns the current TransformNode */ - onMaterialChangedObservable: Observable; + setPivotMatrix(matrix: Matrix, postMultiplyPivotMatrix?: boolean): TransformNode; /** - * Gets or sets the orientation for POV movement & rotation + * Returns the mesh pivot matrix. + * Default : Identity. + * A Matrix is returned. */ - definedFacingForward: boolean; + getPivotMatrix(): Matrix; /** - * This property determines the type of occlusion query algorithm to run in WebGl, you can use: - * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED. - * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate. - * @see http://doc.babylonjs.com/features/occlusionquery - */ - occlusionQueryAlgorithmType: number; + * Prevents the World matrix to be computed any longer. + * Returns the TransformNode. + */ + freezeWorldMatrix(): TransformNode; /** - * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values: - * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh. - * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh. - * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show. - * @see http://doc.babylonjs.com/features/occlusionquery + * Allows back the World matrix computation. + * Returns the TransformNode. */ - occlusionType: number; + unfreezeWorldMatrix(): this; /** - * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object. - * The default value is -1 which means don't break the query and wait till the result - * @see http://doc.babylonjs.com/features/occlusionquery + * True if the World matrix has been frozen. + * Returns a boolean. + */ + readonly isWorldMatrixFrozen: boolean; + /** + * Retuns the mesh absolute position in the World. + * Returns a Vector3. + */ + getAbsolutePosition(): Vector3; + /** + * Sets the mesh absolute position in the World from a Vector3 or an Array(3). + * Returns the TransformNode. + */ + setAbsolutePosition(absolutePosition: Vector3): TransformNode; + /** + * Sets the mesh position in its local space. + * Returns the TransformNode. + */ + setPositionWithLocalVector(vector3: Vector3): TransformNode; + /** + * Returns the mesh position in the local space from the current World matrix values. + * Returns a new Vector3. + */ + getPositionExpressedInLocalSpace(): Vector3; + /** + * Translates the mesh along the passed Vector3 in its local space. + * Returns the TransformNode. + */ + locallyTranslate(vector3: Vector3): TransformNode; + private static _lookAtVectorCache; + /** + * Orients a mesh towards a target point. Mesh must be drawn facing user. + * @param targetPoint the position (must be in same space as current mesh) to look at + * @param yawCor optional yaw (y-axis) correction in radians + * @param pitchCor optional pitch (x-axis) correction in radians + * @param rollCor optional roll (z-axis) correction in radians + * @param space the choosen space of the target + * @returns the TransformNode. + */ + lookAt(targetPoint: Vector3, yawCor?: number, pitchCor?: number, rollCor?: number, space?: Space): TransformNode; + /** + * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh. + * This Vector3 is expressed in the World space. + */ + getDirection(localAxis: Vector3): Vector3; + /** + * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh. + * localAxis is expressed in the mesh local space. + * result is computed in the Wordl space from the mesh World matrix. + * Returns the TransformNode. + */ + getDirectionToRef(localAxis: Vector3, result: Vector3): TransformNode; + /** + * Sets a new pivot point to the current node + * @param point defines the new pivot point to use + * @param space defines if the point is in world or local space (local by default) + * @returns the current TransformNode */ - occlusionRetryCount: number; - /** @hidden */ - - /** @hidden */ + setPivotPoint(point: Vector3, space?: Space): TransformNode; + /** + * Returns a new Vector3 set with the mesh pivot point coordinates in the local space. + */ + getPivotPoint(): Vector3; + /** + * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space. + * Returns the TransformNode. + */ + getPivotPointToRef(result: Vector3): TransformNode; + /** + * Returns a new Vector3 set with the mesh pivot point World coordinates. + */ + getAbsolutePivotPoint(): Vector3; + /** + * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates. + * Returns the TransformNode. + */ + getAbsolutePivotPointToRef(result: Vector3): TransformNode; + /** + * Defines the passed node as the parent of the current node. + * The node will remain exactly where it is and its position / rotation will be updated accordingly + * Returns the TransformNode. + */ + setParent(node: Nullable): TransformNode; + private _nonUniformScaling; + readonly nonUniformScaling: boolean; /** - * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not - * @see http://doc.babylonjs.com/features/occlusionquery + * Attach the current TransformNode to another TransformNode associated with a bone + * @param bone Bone affecting the TransformNode + * @param affectedTransformNode TransformNode associated with the bone + */ + attachToBone(bone: Bone, affectedTransformNode: TransformNode): TransformNode; + detachFromBone(): TransformNode; + private static _rotationAxisCache; + /** + * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space. + * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD. + * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. + * The passed axis is also normalized. + * Returns the TransformNode. + */ + rotate(axis: Vector3, amount: number, space?: Space): TransformNode; + /** + * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space. + * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. + * The passed axis is also normalized. + * Returns the TransformNode. + * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm + */ + rotateAround(point: Vector3, axis: Vector3, amount: number): TransformNode; + /** + * Translates the mesh along the axis vector for the passed distance in the given space. + * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD. + * Returns the TransformNode. + */ + translate(axis: Vector3, distance: number, space?: Space): TransformNode; + /** + * Adds a rotation step to the mesh current rotation. + * x, y, z are Euler angles expressed in radians. + * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set. + * This means this rotation is made in the mesh local space only. + * It's useful to set a custom rotation order different from the BJS standard one YXZ. + * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis. + * ```javascript + * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3); + * ``` + * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values. + * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles. + * Returns the TransformNode. + */ + addRotation(x: number, y: number, z: number): TransformNode; + /** + * Computes the mesh World matrix and returns it. + * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values. + * If the parameter `force` is let to `false` (default), the current cached World matrix is returned. + * If the parameter `force`is set to `true`, the actual computation is done. + * Returns the mesh World Matrix. + */ + computeWorldMatrix(force?: boolean): Matrix; + protected _afterComputeWorldMatrix(): void; + /** + * If you'd like to be called back after the mesh position, rotation or scaling has been updated. + * @param func: callback function to add + * + * Returns the TransformNode. */ - isOccluded: boolean; - /** @hidden */ - + registerAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode; /** - * Flag to check the progress status of the query - * @see http://doc.babylonjs.com/features/occlusionquery + * Removes a registered callback function. + * Returns the TransformNode. */ - readonly isOcclusionQueryInProgress: boolean; + unregisterAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode; + /** + * Clone the current transform node + * Returns the new transform node + * @param name Name of the new clone + * @param newParent New parent for the clone + * @param doNotCloneChildren Do not clone children hierarchy + */ + clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable; + serialize(currentSerializationObject?: any): any; + /** + * Returns a new TransformNode object parsed from the source provided. + * The parameter `parsedMesh` is the source. + * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with + */ + static Parse(parsedTransformNode: any, scene: Scene, rootUrl: string): TransformNode; + /** + * Releases resources associated with this transform node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; + } +} + +declare module BABYLON { + class VertexBuffer { /** @hidden */ - private _visibility; + private _kind; + private _size; + private _ownsBuffer; + private _instanced; + private _instanceDivisor; /** - * Gets or sets mesh visibility between 0 and 1 (default is 1) + * The byte type. */ + static readonly BYTE: number; /** - * Gets or sets mesh visibility between 0 and 1 (default is 1) + * The unsigned byte type. */ - visibility: number; - /** Gets or sets the alpha index used to sort transparent meshes - * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index + static readonly UNSIGNED_BYTE: number; + /** + * The short type. */ - alphaIndex: number; + static readonly SHORT: number; /** - * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true + * The unsigned short type. */ - isVisible: boolean; + static readonly UNSIGNED_SHORT: number; /** - * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true + * The integer type. */ - isPickable: boolean; - /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */ - showSubMeshesBoundingBox: boolean; - /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default) - * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares + static readonly INT: number; + /** + * The unsigned integer type. */ - isBlocker: boolean; + static readonly UNSIGNED_INT: number; /** - * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default) + * The float type. */ - enablePointerMoveEvents: boolean; + static readonly FLOAT: number; /** - * Specifies the rendering group id for this mesh (0 by default) - * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups + * Gets or sets the instance divisor when in instanced mode */ - renderingGroupId: number; - private _material; - /** Gets or sets current material */ - material: Nullable; - private _receiveShadows; + instanceDivisor: number; /** - * Gets or sets a boolean indicating that this mesh can receive realtime shadows - * @see http://doc.babylonjs.com/babylon101/shadows + * Gets the byte stride. */ - receiveShadows: boolean; + readonly byteStride: number; /** - * Gets or sets a boolean indicating if the outline must be rendered as well - * @see https://www.babylonjs-playground.com/#10WJ5S#3 + * Gets the byte offset. */ - renderOutline: boolean; - /** Defines color to use when rendering outline */ - outlineColor: Color3; - /** Define width to use when rendering outline */ - outlineWidth: number; + readonly byteOffset: number; /** - * Gets or sets a boolean indicating if the overlay must be rendered as well - * @see https://www.babylonjs-playground.com/#10WJ5S#2 + * Gets whether integer data values should be normalized into a certain range when being casted to a float. */ - renderOverlay: boolean; - /** Defines color to use when rendering overlay */ - overlayColor: Color3; - /** Defines alpha to use when rendering overlay */ - overlayAlpha: number; - private _hasVertexAlpha; - /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */ - hasVertexAlpha: boolean; - private _useVertexColors; - /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */ - useVertexColors: boolean; - private _computeBonesUsingShaders; + readonly normalized: boolean; /** - * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default) + * Gets the data type of each component in the array. */ - computeBonesUsingShaders: boolean; - private _numBoneInfluencers; - /** Gets or sets the number of allowed bone influences per vertex (4 by default) */ - numBoneInfluencers: number; - private _applyFog; - /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */ - applyFog: boolean; - /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */ - useOctreeForRenderingSelection: boolean; - /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */ - useOctreeForPicking: boolean; - /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */ - useOctreeForCollisions: boolean; - private _layerMask; + readonly type: number; + /** + * Constructor + * @param engine the engine + * @param data the data to use for this vertex buffer + * @param kind the vertex buffer kind + * @param updatable whether the data is updatable + * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional) + * @param stride the stride (optional) + * @param instanced whether the buffer is instanced (optional) + * @param offset the offset of the data (optional) + * @param size the number of components (optional) + * @param type the type of the component (optional) + * @param normalized whether the data contains normalized data (optional) + * @param useBytes set to true if stride and offset are in bytes (optional) + */ + constructor(engine: any, data: DataArray | Buffer, kind: string, updatable: boolean, postponeInternalCreation?: boolean, stride?: number, instanced?: boolean, offset?: number, size?: number, type?: number, normalized?: boolean, useBytes?: boolean); + + /** + * Returns the kind of the VertexBuffer (string). + */ + getKind(): string; + /** + * Boolean : is the VertexBuffer updatable ? + */ + isUpdatable(): boolean; + /** + * Returns an array of numbers or a typed array containing the VertexBuffer data. + */ + getData(): Nullable; + /** + * Returns the WebGLBuffer associated to the VertexBuffer. + */ + getBuffer(): Nullable; + /** + * Returns the stride as a multiple of the type byte length. + * DEPRECATED. Use byteStride instead. + */ + getStrideSize(): number; + /** + * Returns the offset as a multiple of the type byte length. + * DEPRECATED. Use byteOffset instead. + */ + getOffset(): number; /** - * Gets or sets the current layer mask (default is 0x0FFFFFFF) - * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures + * Returns the number of components per vertex attribute (integer). */ - layerMask: number; + getSize(): number; /** - * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase) + * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ? */ - alwaysSelectAsActiveMesh: boolean; + getIsInstanced(): boolean; /** - * Gets or sets the current action manager - * @see http://doc.babylonjs.com/how_to/how_to_use_actions + * Returns the instancing divisor, zero for non-instanced (integer). */ - actionManager: Nullable; + getInstanceDivisor(): number; /** - * Gets or sets impostor used for physic simulation - * @see http://doc.babylonjs.com/features/physics_engine + * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array. + * Returns the created WebGLBuffer. */ - physicsImpostor: Nullable; - private _checkCollisions; - private _collisionMask; - private _collisionGroup; + create(data?: DataArray): void; /** - * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5)) - * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity + * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array. + * This function will create a new buffer if the current one is not updatable + * Returns the updated WebGLBuffer. */ - ellipsoid: Vector3; + update(data: DataArray): void; /** - * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0)) - * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity + * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array. + * Returns the directly updated WebGLBuffer. + * @param data the new data + * @param offset the new offset + * @param useBytes set to true if the offset is in bytes */ - ellipsoidOffset: Vector3; - private _collider; - private _oldPositionForCollisions; - private _diffPositionForCollisions; + updateDirectly(data: DataArray, offset: number, useBytes?: boolean): void; /** - * Gets or sets a collision mask used to mask collisions (default is -1). - * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 + * Disposes the VertexBuffer and the underlying WebGLBuffer. */ - collisionMask: number; + dispose(): void; /** - * Gets or sets the current collision group mask (-1 by default). - * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 + * Enumerates each value of this vertex buffer as numbers. + * @param count the number of values to enumerate + * @param callback the callback function called for each value */ - collisionGroup: number; + forEach(count: number, callback: (value: number, index: number) => void): void; + private static _PositionKind; + private static _NormalKind; + private static _TangentKind; + private static _UVKind; + private static _UV2Kind; + private static _UV3Kind; + private static _UV4Kind; + private static _UV5Kind; + private static _UV6Kind; + private static _ColorKind; + private static _MatricesIndicesKind; + private static _MatricesWeightsKind; + private static _MatricesIndicesExtraKind; + private static _MatricesWeightsExtraKind; + static readonly PositionKind: string; + static readonly NormalKind: string; + static readonly TangentKind: string; + static readonly UVKind: string; + static readonly UV2Kind: string; + static readonly UV3Kind: string; + static readonly UV4Kind: string; + static readonly UV5Kind: string; + static readonly UV6Kind: string; + static readonly ColorKind: string; + static readonly MatricesIndicesKind: string; + static readonly MatricesWeightsKind: string; + static readonly MatricesIndicesExtraKind: string; + static readonly MatricesWeightsExtraKind: string; /** - * Defines edge width used when edgesRenderer is enabled - * @see https://www.babylonjs-playground.com/#10OJSG#13 + * Deduces the stride given a kind. + * @param kind The kind string to deduce + * @returns The deduced stride */ - edgesWidth: number; + static DeduceStride(kind: string): number; /** - * Defines edge color used when edgesRenderer is enabled - * @see https://www.babylonjs-playground.com/#10OJSG#13 + * Gets the byte length of the given type. + * @param type the type + * @returns the number of bytes */ - edgesColor: Color4; - /** @hidden */ - - private _collisionsTransformMatrix; - private _collisionsScalingMatrix; - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - + static GetTypeByteLength(type: number): number; /** - * Gets or sets the list of subMeshes - * @see http://doc.babylonjs.com/how_to/multi_materials + * Enumerates each value of the given parameters as numbers. + * @param data the data to enumerate + * @param byteOffset the byte offset of the data + * @param byteStride the byte stride of the data + * @param componentCount the number of components per element + * @param componentType the type of the component + * @param count the total number of components + * @param normalized whether the data is normalized + * @param callback the callback function called for each value */ - subMeshes: SubMesh[]; - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ -protected readonly _positions: Nullable; - /** @hidden */ - - /** @hidden */ - - private _skeleton; - /** @hidden */ + static ForEach(data: DataArray, byteOffset: number, byteStride: number, componentCount: number, componentType: number, count: number, normalized: boolean, callback: (value: number, index: number) => void): void; + private static _GetFloatValue; + } +} +declare module BABYLON { + /** + * This represents a GPU particle system in Babylon + * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data + * @see https://www.babylonjs-playground.com/#PU4WYI#4 + */ + class GPUParticleSystem implements IDisposable, IParticleSystem, IAnimatable { /** - * Gets or sets a skeleton to apply skining transformations - * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons + * The id of the Particle system. */ - skeleton: Nullable; + id: string; /** - * Creates a new AbstractMesh - * @param name defines the name of the mesh - * @param scene defines the hosting scene + * The friendly name of the Particle system. */ - constructor(name: string, scene?: Nullable); + name: string; /** - * Returns the string "AbstractMesh" - * @returns "AbstractMesh" + * The emitter represents the Mesh or position we are attaching the particle system to. */ - getClassName(): string; + emitter: Nullable; /** - * Gets a string representation of the current mesh - * @param fullDetails defines a boolean indicating if full details must be included - * @returns a string representation of the current mesh + * The rendering group used by the Particle system to chose when to render. */ - toString(fullDetails?: boolean): string; - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - private _markSubMeshesAsDirty(func); - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - + renderingGroupId: number; /** - * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0) + * The layer mask we are rendering the particles through. + */ + layerMask: number; + private _capacity; + private _activeCount; + private _currentActiveCount; + private _accumulatedCount; + private _renderEffect; + private _updateEffect; + private _buffer0; + private _buffer1; + private _spriteBuffer; + private _updateVAO; + private _renderVAO; + private _targetIndex; + private _sourceBuffer; + private _targetBuffer; + private _scene; + private _engine; + private _currentRenderId; + private _started; + private _stopped; + private _timeDelta; + private _randomTexture; + private _randomTexture2; + private _attributesStrideSize; + private _updateEffectOptions; + private _randomTextureSize; + private _actualFrame; + private readonly _rawTextureWidth; + /** + * List of animations used by the particle system. + */ + animations: Animation[]; + /** + * Gets a boolean indicating if the GPU particles can be rendered on current browser + */ + static readonly IsSupported: boolean; + /** + * An event triggered when the system is disposed. */ - scaling: Vector3; + onDisposeObservable: Observable; /** - * Disables the mesh edge rendering mode - * @returns the currentAbstractMesh + * The overall motion speed (0.01 is default update speed, faster updates = faster animation) */ - disableEdgesRendering(): AbstractMesh; + updateSpeed: number; /** - * Enables the edge rendering mode on the mesh. - * This mode makes the mesh edges visible - * @param epsilon defines the maximal distance between two angles to detect a face - * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces - * @returns the currentAbstractMesh - * @see https://www.babylonjs-playground.com/#19O9TU#0 + * The amount of time the particle system is running (depends of the overall update speed). */ - enableEdgesRendering(epsilon?: number, checkVerticesInsteadOfIndices?: boolean): AbstractMesh; + targetStopDuration: number; /** - * Gets the edgesRenderer associated with the mesh + * The texture used to render each particle. (this can be a spritesheet) */ - readonly edgesRenderer: Nullable; + particleTexture: Nullable; /** - * Returns true if the mesh is blocked. Implemented by child classes + * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD. */ - readonly isBlocked: boolean; + blendMode: number; /** - * Returns the mesh itself by default. Implemented by child classes - * @param camera defines the camera to use to pick the right LOD level - * @returns the currentAbstractMesh + * Minimum life time of emitting particles. */ - getLOD(camera: Camera): Nullable; + minLifeTime: number; /** - * Returns 0 by default. Implemented by child classes - * @returns an integer + * Maximum life time of emitting particles. */ - getTotalVertices(): number; + maxLifeTime: number; /** - * Returns null by default. Implemented by child classes - * @returns null + * Minimum Size of emitting particles. */ - getIndices(): Nullable; + minSize: number; /** - * Returns the array of the requested vertex data kind. Implemented by child classes - * @param kind defines the vertex data kind to use - * @returns null + * Maximum Size of emitting particles. */ - getVerticesData(kind: string): Nullable; + maxSize: number; /** - * Sets the vertex data of the mesh geometry for the requested `kind`. - * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. - * Note that a new underlying VertexBuffer object is created each call. - * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. - * @param kind defines vertex data kind: - * * BABYLON.VertexBuffer.PositionKind - * * BABYLON.VertexBuffer.UVKind - * * BABYLON.VertexBuffer.UV2Kind - * * BABYLON.VertexBuffer.UV3Kind - * * BABYLON.VertexBuffer.UV4Kind - * * BABYLON.VertexBuffer.UV5Kind - * * BABYLON.VertexBuffer.UV6Kind - * * BABYLON.VertexBuffer.ColorKind - * * BABYLON.VertexBuffer.MatricesIndicesKind - * * BABYLON.VertexBuffer.MatricesIndicesExtraKind - * * BABYLON.VertexBuffer.MatricesWeightsKind - * * BABYLON.VertexBuffer.MatricesWeightsExtraKind - * @param data defines the data source - * @param updatable defines if the data must be flagged as updatable (or static) - * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind - * @returns the current mesh + * Minimum scale of emitting particles on X axis. */ - setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): AbstractMesh; + minScaleX: number; /** - * Updates the existing vertex data of the mesh geometry for the requested `kind`. - * If the mesh has no geometry, it is simply returned as it is. - * @param kind defines vertex data kind: - * * BABYLON.VertexBuffer.PositionKind - * * BABYLON.VertexBuffer.UVKind - * * BABYLON.VertexBuffer.UV2Kind - * * BABYLON.VertexBuffer.UV3Kind - * * BABYLON.VertexBuffer.UV4Kind - * * BABYLON.VertexBuffer.UV5Kind - * * BABYLON.VertexBuffer.UV6Kind - * * BABYLON.VertexBuffer.ColorKind - * * BABYLON.VertexBuffer.MatricesIndicesKind - * * BABYLON.VertexBuffer.MatricesIndicesExtraKind - * * BABYLON.VertexBuffer.MatricesWeightsKind - * * BABYLON.VertexBuffer.MatricesWeightsExtraKind - * @param data defines the data source - * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed - * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh - * @returns the current mesh + * Maximum scale of emitting particles on X axis. */ - updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): AbstractMesh; + maxScaleX: number; /** - * Sets the mesh indices, - * If the mesh has no geometry, a new Geometry object is created and set to the mesh. - * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array) - * @param totalVertices Defines the total number of vertices - * @returns the current mesh + * Minimum scale of emitting particles on Y axis. */ - setIndices(indices: IndicesArray, totalVertices: Nullable): AbstractMesh; + minScaleY: number; /** - * Gets a boolean indicating if specific vertex data is present - * @param kind defines the vertex data kind to use - * @returns true is data kind is present + * Maximum scale of emitting particles on Y axis. */ - isVerticesDataPresent(kind: string): boolean; + maxScaleY: number; /** - * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined - * @returns a BoundingInfo + * Random color of each particle after it has been emitted, between color1 and color2 vectors. */ - getBoundingInfo(): BoundingInfo; + color1: Color4; /** - * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units) - * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box - * @returns the current mesh + * Random color of each particle after it has been emitted, between color1 and color2 vectors. */ - normalizeToUnitCube(includeDescendants?: boolean): AbstractMesh; + color2: Color4; /** - * Overwrite the current bounding info - * @param boundingInfo defines the new bounding info - * @returns the current mesh + * Color the particle will have at the end of its lifetime. */ - setBoundingInfo(boundingInfo: BoundingInfo): AbstractMesh; - /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */ - readonly useBones: boolean; - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - + colorDead: Color4; /** - * Gets the current world matrix - * @returns a Matrix + * The maximum number of particles to emit per frame until we reach the activeParticleCount value */ - getWorldMatrix(): Matrix; - /** @hidden */ - + emitRate: number; /** - * Perform relative position change from the point of view of behind the front of the mesh. - * This is performed taking into account the meshes current rotation, so you do not have to care. - * Supports definition of mesh facing forward or backward - * @param amountRight defines the distance on the right axis - * @param amountUp defines the distance on the up axis - * @param amountForward defines the distance on the forward axis - * @returns the current mesh + * You can use gravity if you want to give an orientation to your particles. */ - movePOV(amountRight: number, amountUp: number, amountForward: number): AbstractMesh; + gravity: Vector3; /** - * Calculate relative position change from the point of view of behind the front of the mesh. - * This is performed taking into account the meshes current rotation, so you do not have to care. - * Supports definition of mesh facing forward or backward - * @param amountRight defines the distance on the right axis - * @param amountUp defines the distance on the up axis - * @param amountForward defines the distance on the forward axis - * @returns the new displacement vector + * Minimum power of emitting particles. */ - calcMovePOV(amountRight: number, amountUp: number, amountForward: number): Vector3; + minEmitPower: number; /** - * Perform relative rotation change from the point of view of behind the front of the mesh. - * Supports definition of mesh facing forward or backward - * @param flipBack defines the flip - * @param twirlClockwise defines the twirl - * @param tiltRight defines the tilt - * @returns the current mesh + * Maximum power of emitting particles. */ - rotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): AbstractMesh; + maxEmitPower: number; /** - * Calculate relative rotation change from the point of view of behind the front of the mesh. - * Supports definition of mesh facing forward or backward. - * @param flipBack defines the flip - * @param twirlClockwise defines the twirl - * @param tiltRight defines the tilt - * @returns the new rotation vector + * Minimum angular speed of emitting particles (Z-axis rotation for each particle). */ - calcRotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): Vector3; + minAngularSpeed: number; /** - * Return the minimum and maximum world vectors of the entire hierarchy under current mesh - * @param includeDescendants Include bounding info from descendants as well (true by default) - * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors - * @returns the new bounding vectors + * Maximum angular speed of emitting particles (Z-axis rotation for each particle). */ - getHierarchyBoundingVectors(includeDescendants?: boolean, predicate?: Nullable<(abstractMesh: AbstractMesh) => boolean>): { - min: Vector3; - max: Vector3; - }; - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - protected _afterComputeWorldMatrix(): void; + maxAngularSpeed: number; /** - * Returns `true` if the mesh is within the frustum defined by the passed array of planes. - * A mesh is in the frustum if its bounding box intersects the frustum - * @param frustumPlanes defines the frustum to test - * @returns true if the mesh is in the frustum planes + * The particle emitter type defines the emitter used by the particle system. + * It can be for example box, sphere, or cone... */ - isInFrustum(frustumPlanes: Plane[]): boolean; + particleEmitterType: Nullable; /** - * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes. - * A mesh is completely in the frustum if its bounding box it completely inside the frustum. - * @param frustumPlanes defines the frustum to test - * @returns true if the mesh is completely in the frustum planes + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + * This only works when particleEmitterTyps is a BoxParticleEmitter */ - isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; + direction1: Vector3; /** - * True if the mesh intersects another mesh or a SolidParticle object - * @param mesh defines a target mesh or SolidParticle to test - * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes) - * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes - * @returns true if there is an intersection + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + * This only works when particleEmitterTyps is a BoxParticleEmitter */ - intersectsMesh(mesh: AbstractMesh | SolidParticle, precise?: boolean, includeDescendants?: boolean): boolean; + direction2: Vector3; /** - * Returns true if the passed point (Vector3) is inside the mesh bounding box - * @param point defines the point to test - * @returns true if there is an intersection + * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. + * This only works when particleEmitterTyps is a BoxParticleEmitter */ - intersectsPoint(point: Vector3): boolean; + minEmitBox: Vector3; /** - * Gets the current physics impostor - * @see http://doc.babylonjs.com/features/physics_engine - * @returns a physics impostor or null + * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. + * This only works when particleEmitterTyps is a BoxParticleEmitter */ - getPhysicsImpostor(): Nullable; + maxEmitBox: Vector3; /** - * Gets the position of the current mesh in camera space - * @param camera defines the camera to use - * @returns a position + * Gets the maximum number of particles active at the same time. + * @returns The max number of active particles. */ - getPositionInCameraSpace(camera?: Nullable): Vector3; + getCapacity(): number; /** - * Returns the distance from the mesh to the active camera - * @param camera defines the camera to use - * @returns the distance + * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls + * to override the particles. */ - getDistanceToCamera(camera?: Nullable): number; + forceDepthWrite: boolean; /** - * Apply a physic impulse to the mesh - * @param force defines the force to apply - * @param contactPoint defines where to apply the force - * @returns the current mesh - * @see http://doc.babylonjs.com/how_to/using_the_physics_engine + * Gets or set the number of active particles */ - applyImpulse(force: Vector3, contactPoint: Vector3): AbstractMesh; + activeParticleCount: number; + private _preWarmDone; + /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */ + preWarmCycles: number; + /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */ + preWarmStepOffset: number; /** - * Creates a physic joint between two meshes - * @param otherMesh defines the other mesh to use - * @param pivot1 defines the pivot to use on this mesh - * @param pivot2 defines the pivot to use on the other mesh - * @param options defines additional options (can be plugin dependent) - * @returns the current mesh - * @see https://www.babylonjs-playground.com/#0BS5U0#0 + * Gets or sets the minimal initial rotation in radians. */ - setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3, options?: any): AbstractMesh; + minInitialRotation: number; /** - * Gets or sets a boolean indicating that this mesh can be used in the collision engine - * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity + * Gets or sets the maximal initial rotation in radians. */ - checkCollisions: boolean; + maxInitialRotation: number; /** - * Gets Collider object used to compute collisions (not physics) - * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity + * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime) + */ + spriteCellChangeSpeed: number; + /** + * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display + */ + startSpriteCellID: number; + /** + * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display + */ + endSpriteCellID: number; + /** + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use */ - readonly collider: Collider; + spriteCellWidth: number; /** - * Move the mesh using collision engine - * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity - * @param displacement defines the requested displacement vector - * @returns the current mesh + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use */ - moveWithCollisions(displacement: Vector3): AbstractMesh; - private _onCollisionPositionChange; + spriteCellHeight: number; + /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ + translationPivot: Vector2; /** - * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations. - * Please note that you must have a decent number of submeshes to get performance improvements when using an octree - * @param maxCapacity defines the maximum size of each block (64 by default) - * @param maxDepth defines the maximum depth to use (no more than 2 levels by default) - * @returns the new octree - * @see https://www.babylonjs-playground.com/#NA4OQ#12 - * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees - */ - createOrUpdateSubmeshesOctree(maxCapacity?: number, maxDepth?: number): Octree; - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - + * Gets or sets a texture used to add random noise to particle positions + */ + noiseTexture: Nullable; + /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ + noiseStrength: Vector3; /** - * Checks if the passed Ray intersects with the mesh - * @param ray defines the ray to use - * @param fastCheck defines if fast mode (but less precise) must be used (false by default) - * @returns the picking info - * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh + * Gets or sets the billboard mode to use when isBillboardBased = true. + * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far */ - intersects(ray: Ray, fastCheck?: boolean): PickingInfo; + billboardMode: number; + private _isAnimationSheetEnabled; /** - * Clones the current mesh - * @param name defines the mesh name - * @param newParent defines the new mesh parent - * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default) - * @returns the new mesh + * Gets whether an animation sprite sheet is enabled or not on the particle system */ - clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable; + readonly isAnimationSheetEnabled: boolean; /** - * Disposes all the submeshes of the current meshnp - * @returns the current mesh + * Is this system ready to be used/rendered + * @return true if the system is ready */ - releaseSubMeshes(): AbstractMesh; + isReady(): boolean; /** - * Releases resources associated with this abstract mesh. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + * Gets Wether the system has been started. + * @returns True if it has been started, otherwise false. */ - dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; + isStarted(): boolean; /** - * Adds the passed mesh as a child to the current mesh - * @param mesh defines the child mesh - * @returns the current mesh + * Starts the particle system and begins to emit + * @param delay defines the delay in milliseconds before starting the system (0 by default) */ - addChild(mesh: AbstractMesh): AbstractMesh; + start(delay?: number): void; /** - * Removes the passed mesh from the current mesh children list - * @param mesh defines the child mesh - * @returns the current mesh + * Stops the particle system. */ - removeChild(mesh: AbstractMesh): AbstractMesh; - /** @hidden */ - private _initFacetData(); + stop(): void; /** - * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated. - * This method can be called within the render loop. - * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation - * @returns the current mesh - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Remove all active particles */ - updateFacetData(): AbstractMesh; + reset(): void; /** - * Returns the facetLocalNormals array. - * The normals are expressed in the mesh local spac - * @returns an array of Vector3 - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Returns the string "GPUParticleSystem" + * @returns a string containing the class name */ - getFacetLocalNormals(): Vector3[]; + getClassName(): string; + private _isBillboardBased; /** - * Returns the facetLocalPositions array. - * The facet positions are expressed in the mesh local space - * @returns an array of Vector3 - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction */ - getFacetLocalPositions(): Vector3[]; + isBillboardBased: boolean; + private _colorGradients; + private _colorGradientsTexture; /** - * Returns the facetLocalPartioning array - * @returns an array of array of numbers - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Gets the current list of color gradients. + * You must use addColorGradient and removeColorGradient to udpate this list + * @returns the list of color gradients */ - getFacetLocalPartitioning(): number[][]; + getColorGradients(): Nullable>; /** - * Returns the i-th facet position in the world system. - * This method allocates a new Vector3 per call - * @param i defines the facet index - * @returns a new Vector3 - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Gets the current list of size gradients. + * You must use addSizeGradient and removeSizeGradient to udpate this list + * @returns the list of size gradients */ - getFacetPosition(i: number): Vector3; + getSizeGradients(): Nullable>; /** - * Sets the reference Vector3 with the i-th facet position in the world system - * @param i defines the facet index - * @param ref defines the target vector - * @returns the current mesh - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Gets the current list of angular speed gradients. + * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list + * @returns the list of angular speed gradients */ - getFacetPositionToRef(i: number, ref: Vector3): AbstractMesh; + getAngularSpeedGradients(): Nullable>; /** - * Returns the i-th facet normal in the world system. - * This method allocates a new Vector3 per call - * @param i defines the facet index - * @returns a new Vector3 - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Gets the current list of velocity gradients. + * You must use addVelocityGradient and removeVelocityGradient to udpate this list + * @returns the list of angular speed gradients */ - getFacetNormal(i: number): Vector3; + getVelocityGradients(): Nullable>; + private _removeGradient; /** - * Sets the reference Vector3 with the i-th facet normal in the world system - * @param i defines the facet index - * @param ref defines the target vector - * @returns the current mesh - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Adds a new color gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param color defines the color to affect to the specified gradient + * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from + * @returns the current particle system */ - getFacetNormalToRef(i: number, ref: Vector3): this; + addColorGradient(gradient: number, color1: Color4, color2?: Color4): GPUParticleSystem; /** - * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system) - * @param x defines x coordinate - * @param y defines y coordinate - * @param z defines z coordinate - * @returns the array of facet indexes - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Remove a specific color gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - getFacetsAtLocalCoordinates(x: number, y: number, z: number): Nullable; + removeColorGradient(gradient: number): GPUParticleSystem; + private _angularSpeedGradients; + private _angularSpeedGradientsTexture; + private _sizeGradients; + private _sizeGradientsTexture; + private _velocityGradients; + private _velocityGradientsTexture; + private _addFactorGradient; /** - * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found - * @param projected sets as the (x,y,z) world projection on the facet - * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned - * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position - * @param x defines x coordinate - * @param y defines y coordinate - * @param z defines z coordinate - * @returns the face index if found (or null instead) - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Adds a new size gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @returns the current particle system */ - getClosestFacetAtCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace?: boolean, facing?: boolean): Nullable; + addSizeGradient(gradient: number, factor: number): GPUParticleSystem; /** - * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found - * @param projected sets as the (x,y,z) local projection on the facet - * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned - * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position - * @param x defines x coordinate - * @param y defines y coordinate - * @param z defines z coordinate - * @returns the face index if found (or null instead) - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Remove a specific size gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - getClosestFacetAtLocalCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace?: boolean, facing?: boolean): Nullable; + removeSizeGradient(gradient: number): GPUParticleSystem; /** - * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals() - * @returns the parameters - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Adds a new angular speed gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @returns the current particle system */ - getFacetDataParameters(): any; + addAngularSpeedGradient(gradient: number, factor: number): GPUParticleSystem; /** - * Disables the feature FacetData and frees the related memory - * @returns the current mesh - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Remove a specific angular speed gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - disableFacetData(): AbstractMesh; + removeAngularSpeedGradient(gradient: number): GPUParticleSystem; /** - * Updates the AbstractMesh indices array - * @param indices defines the data source - * @returns the current mesh + * Adds a new velocity gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @returns the current particle system */ - updateIndices(indices: IndicesArray): AbstractMesh; + addVelocityGradient(gradient: number, factor: number): GPUParticleSystem; /** - * Creates new normals data for the mesh - * @param updatable defines if the normal vertex buffer must be flagged as updatable - * @returns the current mesh + * Remove a specific velocity gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - createNormals(updatable: boolean): AbstractMesh; + removeVelocityGradient(gradient: number): GPUParticleSystem; /** - * Align the mesh with a normal - * @param normal defines the normal to use - * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default) - * @returns the current mesh + * Instantiates a GPU particle system. + * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. + * @param name The name of the particle system + * @param options The options used to create the system + * @param scene The scene the particle system belongs to + * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture */ - alignWithNormal(normal: Vector3, upDirection?: Vector3): AbstractMesh; + constructor(name: string, options: Partial<{ + capacity: number; + randomTextureSize: number; + }>, scene: Scene, isAnimationSheetEnabled?: boolean); + private _createUpdateVAO; + private _createRenderVAO; + private _initialize; /** @hidden */ - } -} - -declare module BABYLON { - class Buffer { - private _engine; - private _buffer; /** @hidden */ - private _updatable; - private _instanced; /** - * Gets the byte stride. + * Animates the particle system for the current frame by emitting new particles and or animating the living ones. + * @param preWarm defines if we are in the pre-warmimg phase */ - readonly byteStride: number; + animate(preWarm?: boolean): void; + private _createFactorGradientTexture; + private _createSizeGradientTexture; + private _createAngularSpeedGradientTexture; + private _createVelocityGradientTexture; + private _createColorGradientTexture; /** - * Constructor - * @param engine the engine - * @param data the data to use for this buffer - * @param updatable whether the data is updatable - * @param stride the stride (optional) - * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional) - * @param instanced whether the buffer is instanced (optional) - * @param useBytes set to true if the stride in in bytes (optional) + * Renders the particle system in its current state + * @param preWarm defines if the system should only update the particles but not render them + * @returns the current number of particles */ - constructor(engine: any, data: DataArray, updatable: boolean, stride?: number, postponeInternalCreation?: boolean, instanced?: boolean, useBytes?: boolean); + render(preWarm?: boolean): number; /** - * Create a new {BABYLON.VertexBuffer} based on the current buffer - * @param kind defines the vertex buffer kind (position, normal, etc.) - * @param offset defines offset in the buffer (0 by default) - * @param size defines the size in floats of attributes (position is 3 for instance) - * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved) - * @param instanced defines if the vertex buffer contains indexed data - * @param useBytes defines if the offset and stride are in bytes - * @returns the new vertex buffer + * Rebuilds the particle system */ - createVertexBuffer(kind: string, offset: number, size: number, stride?: number, instanced?: boolean, useBytes?: boolean): VertexBuffer; - isUpdatable(): boolean; - getData(): Nullable; - getBuffer(): Nullable; + rebuild(): void; + private _releaseBuffers; + private _releaseVAOs; /** - * Gets the stride in float32 units (i.e. byte stride / 4). - * May not be an integer if the byte stride is not divisible by 4. - * DEPRECATED. Use byteStride instead. - * @returns the stride in float32 units + * Disposes the particle system and free the associated resources + * @param disposeTexture defines if the particule texture must be disposed as well (true by default) */ - getStrideSize(): number; - create(data?: Nullable): void; - - update(data: DataArray): void; + dispose(disposeTexture?: boolean): void; /** - * Updates the data directly. - * @param data the new data - * @param offset the new offset - * @param vertexCount the vertex count (optional) - * @param useBytes set to true if the offset is in bytes + * Clones the particle system. + * @param name The name of the cloned object + * @param newEmitter The new emitter to use + * @returns the cloned particle system */ - updateDirectly(data: DataArray, offset: number, vertexCount?: number, useBytes?: boolean): void; - dispose(): void; - } -} - -declare module BABYLON { - class CSG { - private polygons; - matrix: Matrix; - position: Vector3; - rotation: Vector3; - rotationQuaternion: Nullable; - scaling: Vector3; - static FromMesh(mesh: Mesh): CSG; - private static FromPolygons(polygons); - clone(): CSG; - union(csg: CSG): CSG; - unionInPlace(csg: CSG): void; - subtract(csg: CSG): CSG; - subtractInPlace(csg: CSG): void; - intersect(csg: CSG): CSG; - intersectInPlace(csg: CSG): void; - inverse(): CSG; - inverseInPlace(): void; - copyTransformAttributes(csg: CSG): CSG; - buildMeshGeometry(name: string, scene: Scene, keepSubMeshes: boolean): Mesh; - toMesh(name: string, material: Nullable, scene: Scene, keepSubMeshes: boolean): Mesh; + clone(name: string, newEmitter: any): Nullable; + /** + * Serializes the particle system to a JSON object. + * @returns the JSON object + */ + serialize(): any; + /** + * Parses a JSON object to create a GPU particle system. + * @param parsedParticleSystem The JSON object to parse + * @param scene The scene to create the particle system in + * @param rootUrl The root url to use to load external dependencies like texture + * @returns the parsed GPU particle system + */ + static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): GPUParticleSystem; } } declare module BABYLON { /** - * Class used to store geometry data (vertex buffers + index buffer) + * Interface representing a particle system in Babylon.js. + * This groups the common functionalities that needs to be implemented in order to create a particle system. + * A particle system represents a way to manage particles from their emission to their animation and rendering. */ - class Geometry implements IGetSetVerticesData { + interface IParticleSystem { /** - * Gets or sets the unique ID of the geometry + * List of animations used by the particle system. + */ + animations: Animation[]; + /** + * The id of the Particle system. */ id: string; /** - * Gets the delay loading state of the geometry (none by default which means not delayed) + * The name of the Particle system. */ - delayLoadState: number; + name: string; /** - * Gets the file containing the data to load when running in delay load state + * The emitter represents the Mesh or position we are attaching the particle system to. */ - delayLoadingFile: Nullable; + emitter: Nullable; /** - * Callback called when the geometry is updated + * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction */ - onGeometryUpdated: (geometry: Geometry, kind?: string) => void; - private _scene; - private _engine; - private _meshes; - private _totalVertices; - /** @hidden */ - - /** @hidden */ -; - private _isDisposed; - private _extend; - private _boundingBias; - /** @hidden */ - - private _indexBuffer; - private _indexBufferIsUpdatable; - /** @hidden */ - - /** @hidden */ - - /** @hidden */ - - private _vertexArrayObjects; - private _updatable; - /** @hidden */ - + isBillboardBased: boolean; /** - * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y + * The rendering group used by the Particle system to chose when to render. */ + renderingGroupId: number; /** - * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y + * The layer mask we are rendering the particles through. */ - boundingBias: Vector2; + layerMask: number; /** - * Static function used to attach a new empty geometry to a mesh - * @param mesh defines the mesh to attach the geometry to - * @returns the new {BABYLON.Geometry} + * The overall motion speed (0.01 is default update speed, faster updates = faster animation) + */ + updateSpeed: number; + /** + * The amount of time the particle system is running (depends of the overall update speed). */ - static CreateGeometryForMesh(mesh: Mesh): Geometry; + targetStopDuration: number; /** - * Creates a new geometry - * @param id defines the unique ID - * @param scene defines the hosting scene - * @param vertexData defines the {BABYLON.VertexData} used to get geometry data - * @param updatable defines if geometry must be updatable (false by default) - * @param mesh defines the mesh that will be associated with the geometry + * The texture used to render each particle. (this can be a spritesheet) */ - constructor(id: string, scene: Scene, vertexData?: VertexData, updatable?: boolean, mesh?: Nullable); + particleTexture: Nullable; /** - * Gets the current extend of the geometry + * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE, ParticleSystem.BLENDMODE_STANDARD or ParticleSystem.BLENDMODE_ADD. */ - readonly extend: { - minimum: Vector3; - maximum: Vector3; - }; + blendMode: number; /** - * Gets the hosting scene - * @returns the hosting {BABYLON.Scene} + * Minimum life time of emitting particles. */ - getScene(): Scene; + minLifeTime: number; /** - * Gets the hosting engine - * @returns the hosting {BABYLON.Engine} + * Maximum life time of emitting particles. */ - getEngine(): Engine; + maxLifeTime: number; /** - * Defines if the geometry is ready to use - * @returns true if the geometry is ready to be used + * Minimum Size of emitting particles. */ - isReady(): boolean; + minSize: number; /** - * Gets a value indicating that the geometry should not be serialized + * Maximum Size of emitting particles. */ - readonly doNotSerialize: boolean; - /** @hidden */ - + maxSize: number; /** - * Affects all geometry data in one call - * @param vertexData defines the geometry data - * @param updatable defines if the geometry must be flagged as updatable (false as default) + * Minimum scale of emitting particles on X axis. */ - setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; + minScaleX: number; /** - * Set specific vertex data - * @param kind defines the data kind (Position, normal, etc...) - * @param data defines the vertex data to use - * @param updatable defines if the vertex must be flagged as updatable (false as default) - * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified + * Maximum scale of emitting particles on X axis. */ - setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): void; + maxScaleX: number; /** - * Removes a specific vertex data - * @param kind defines the data kind (Position, normal, etc...) + * Minimum scale of emitting particles on Y axis. */ - removeVerticesData(kind: string): void; + minScaleY: number; /** - * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data - * @param buffer defines the vertex buffer to use - * @param totalVertices defines the total number of vertices for position kind (could be null) + * Maximum scale of emitting particles on Y axis. */ - setVerticesBuffer(buffer: VertexBuffer, totalVertices?: Nullable): void; + maxScaleY: number; /** - * Update a specific vertex buffer - * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array - * It will do nothing if the buffer is not updatable - * @param kind defines the data kind (Position, normal, etc...) - * @param data defines the data to use - * @param offset defines the offset in the target buffer where to store the data - * @param useBytes set to true if the offset is in bytes + * Random color of each particle after it has been emitted, between color1 and color2 vectors. + */ + color1: Color4; + /** + * Random color of each particle after it has been emitted, between color1 and color2 vectors. + */ + color2: Color4; + /** + * Color the particle will have at the end of its lifetime. + */ + colorDead: Color4; + /** + * The maximum number of particles to emit per frame until we reach the activeParticleCount value + */ + emitRate: number; + /** + * You can use gravity if you want to give an orientation to your particles. + */ + gravity: Vector3; + /** + * Minimum power of emitting particles. + */ + minEmitPower: number; + /** + * Maximum power of emitting particles. */ - updateVerticesDataDirectly(kind: string, data: DataArray, offset: number, useBytes?: boolean): void; + maxEmitPower: number; /** - * Update a specific vertex buffer - * This function will create a new buffer if the current one is not updatable - * @param kind defines the data kind (Position, normal, etc...) - * @param data defines the data to use - * @param updateExtends defines if the geometry extends must be recomputed (false by default) + * Minimum angular speed of emitting particles (Z-axis rotation for each particle). */ - updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean): void; - private _updateBoundingInfo(updateExtends, data); - /** @hidden */ - + minAngularSpeed: number; /** - * Gets total number of vertices - * @returns the total number of vertices + * Maximum angular speed of emitting particles (Z-axis rotation for each particle). */ - getTotalVertices(): number; + maxAngularSpeed: number; /** - * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly. - * @param kind defines the data kind (Position, normal, etc...) - * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes - * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it - * @returns a float array containing vertex data + * Gets or sets the minimal initial rotation in radians. */ - getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable; + minInitialRotation: number; /** - * Returns a boolean defining if the vertex data for the requested `kind` is updatable - * @param kind defines the data kind (Position, normal, etc...) - * @returns true if the vertex buffer with the specified kind is updatable + * Gets or sets the maximal initial rotation in radians. */ - isVertexBufferUpdatable(kind: string): boolean; + maxInitialRotation: number; /** - * Gets a specific vertex buffer - * @param kind defines the data kind (Position, normal, etc...) - * @returns a {BABYLON.VertexBuffer} + * The particle emitter type defines the emitter used by the particle system. + * It can be for example box, sphere, or cone... */ - getVertexBuffer(kind: string): Nullable; + particleEmitterType: Nullable; /** - * Returns all vertex buffers - * @return an object holding all vertex buffers indexed by kind + * Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */ - getVertexBuffers(): Nullable<{ - [key: string]: VertexBuffer; - }>; + preWarmCycles: number; /** - * Gets a boolean indicating if specific vertex buffer is present - * @param kind defines the data kind (Position, normal, etc...) - * @returns true if data is present + * Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */ - isVerticesDataPresent(kind: string): boolean; + preWarmStepOffset: number; /** - * Gets a list of all attached data kinds (Position, normal, etc...) - * @returns a list of string containing all kinds + * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime) */ - getVerticesDataKinds(): string[]; + spriteCellChangeSpeed: number; /** - * Update index buffer - * @param indices defines the indices to store in the index buffer - * @param offset defines the offset in the target buffer where to store the data + * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display */ - updateIndices(indices: IndicesArray, offset?: number): void; + startSpriteCellID: number; /** - * Creates a new index buffer - * @param indices defines the indices to store in the index buffer - * @param totalVertices defines the total number of vertices (could be null) - * @param updatable defines if the index buffer must be flagged as updatable (false by default) + * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display */ - setIndices(indices: IndicesArray, totalVertices?: Nullable, updatable?: boolean): void; + endSpriteCellID: number; /** - * Return the total number of indices - * @returns the total number of indices + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use */ - getTotalIndices(): number; + spriteCellWidth: number; /** - * Gets the index buffer array - * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes - * @returns the index buffer array + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use */ - getIndices(copyWhenShared?: boolean): Nullable; + spriteCellHeight: number; + /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ + translationPivot: Vector2; /** - * Gets the index buffer - * @return the index buffer + * Gets or sets a texture used to add random noise to particle positions */ - getIndexBuffer(): Nullable; - /** @hidden */ - + noiseTexture: Nullable; + /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ + noiseStrength: Vector3; /** - * Release the associated resources for a specific mesh - * @param mesh defines the source mesh - * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it + * Gets or sets the billboard mode to use when isBillboardBased = true. + * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far */ - releaseForMesh(mesh: Mesh, shouldDispose?: boolean): void; + billboardMode: number; /** - * Apply current geometry to a given mesh - * @param mesh defines the mesh to apply geometry to + * Gets the maximum number of particles active at the same time. + * @returns The max number of active particles. */ - applyToMesh(mesh: Mesh): void; - private _updateExtend(data?); - private _applyToMesh(mesh); - private notifyUpdate(kind?); + getCapacity(): number; /** - * Load the geometry if it was flagged as delay loaded - * @param scene defines the hosting scene - * @param onLoaded defines a callback called when the geometry is loaded + * Gets Wether the system has been started. + * @returns True if it has been started, otherwise false. */ - load(scene: Scene, onLoaded?: () => void): void; - private _queueLoad(scene, onLoaded?); + isStarted(): boolean; /** - * Invert the geometry to move from a right handed system to a left handed one. + * Gets if the particle system has been started. + * @return true if the system has been started, otherwise false. */ - toLeftHanded(): void; - /** @hidden */ - - /** @hidden */ - + isStarted(): boolean; /** - * Gets a value indicating if the geometry is disposed - * @returns true if the geometry was disposed + * Animates the particle system for this frame. */ - isDisposed(): boolean; - private _disposeVertexArrayObjects(); + animate(): void; /** - * Free all associated resources + * Renders the particle system in its current state. + * @returns the current number of particles */ - dispose(): void; + render(): number; /** - * Clone the current geometry into a new geometry - * @param id defines the unique ID of the new geometry - * @returns a new geometry object + * Dispose the particle system and frees its associated resources. + * @param disposeTexture defines if the particule texture must be disposed as well (true by default) */ - copy(id: string): Geometry; + dispose(disposeTexture?: boolean): void; /** - * Serialize the current geometry info (and not the vertices data) into a JSON object - * @return a JSON representation of the current geometry data (without the vertices data) + * Clones the particle system. + * @param name The name of the cloned object + * @param newEmitter The new emitter to use + * @returns the cloned particle system + */ + clone(name: string, newEmitter: any): Nullable; + /** + * Serializes the particle system to a JSON object. + * @returns the JSON object */ serialize(): any; - private toNumberArray(origin); /** - * Serialize all vertices data into a JSON oject - * @returns a JSON representation of the current geometry data + * Rebuild the particle system */ - serializeVerticeData(): any; + rebuild(): void; /** - * Extracts a clone of a mesh geometry - * @param mesh defines the source mesh - * @param id defines the unique ID of the new geometry object - * @returns the new geometry object + * Starts the particle system and begins to emit + * @param delay defines the delay in milliseconds before starting the system (0 by default) */ - static ExtractFromMesh(mesh: Mesh, id: string): Nullable; + start(delay?: number): void; /** - * You should now use Tools.RandomId(), this method is still here for legacy reasons. - * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 - * Be aware Math.random() could cause collisions, but: - * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide" - * @returns a string containing a new GUID + * Stops the particle system. */ - static RandomId(): string; - /** @hidden */ -private static _ImportGeometry(parsedGeometry: any, mesh: Mesh): void; - private static _CleanMatricesWeights(parsedGeometry, mesh); + stop(): void; /** - * Create a new geometry from persisted data (Using .babylon file format) - * @param parsedVertexData defines the persisted data - * @param scene defines the hosting scene - * @param rootUrl defines the root url to use to load assets (like delayed data) - * @returns the new geometry object + * Remove all active particles */ - static Parse(parsedVertexData: any, scene: Scene, rootUrl: string): Nullable; - } - /** - * Abstract class used to provide common services for all typed geometries - * @hidden - */ - class _PrimitiveGeometry extends Geometry { - private _canBeRegenerated; - private _beingRegenerated; + reset(): void; /** - * Creates a new typed geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) + * Is this system ready to be used/rendered + * @return true if the system is ready */ - constructor(id: string, scene: Scene, _canBeRegenerated?: boolean, mesh?: Nullable); + isReady(): boolean; /** - * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default) - * @returns true if the geometry can be regenerated + * Adds a new color gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param color defines the color to affect to the specified gradient + * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from + * @returns the current particle system */ - canBeRegenerated(): boolean; + addColorGradient(gradient: number, color1: Color4, color2?: Color4): IParticleSystem; /** - * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values + * Remove a specific color gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - regenerate(): void; + removeColorGradient(gradient: number): IParticleSystem; /** - * Clone the geometry - * @param id defines the unique ID of the new geometry - * @returns the new geometry + * Adds a new size gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system */ - asNewGeometry(id: string): Geometry; - setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; - setVerticesData(kind: string, data: FloatArray, updatable?: boolean): void; - /** @hidden */ - - copy(id: string): Geometry; - serialize(): any; - } - /** - * Creates a ribbon geometry - * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons - */ - class RibbonGeometry extends _PrimitiveGeometry { + addSizeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem; /** - * Defines the array of paths to use + * Remove a specific size gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - pathArray: Vector3[][]; + removeSizeGradient(gradient: number): IParticleSystem; /** - * Defines if the last and first points of each path in your pathArray must be joined + * Gets the current list of color gradients. + * You must use addColorGradient and removeColorGradient to udpate this list + * @returns the list of color gradients */ - closeArray: boolean; + getColorGradients(): Nullable>; /** - * Defines if the last and first points of each path in your pathArray must be joined + * Gets the current list of size gradients. + * You must use addSizeGradient and removeSizeGradient to udpate this list + * @returns the list of size gradients */ - closePath: boolean; + getSizeGradients(): Nullable>; /** - * Defines the offset between points + * Gets the current list of angular speed gradients. + * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list + * @returns the list of angular speed gradients */ - offset: number; + getAngularSpeedGradients(): Nullable>; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Adds a new angular speed gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system */ - side: number; + addAngularSpeedGradient(gradient: number, factor: number, factor2?: number): IParticleSystem; /** - * Creates a ribbon geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param pathArray defines the array of paths to use - * @param closeArray defines if the last path and the first path must be joined - * @param closePath defines if the last and first points of each path in your pathArray must be joined - * @param offset defines the offset between points - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Remove a specific angular speed gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - constructor(id: string, scene: Scene, - /** - * Defines the array of paths to use - */ - pathArray: Vector3[][], - /** - * Defines if the last and first points of each path in your pathArray must be joined - */ - closeArray: boolean, - /** - * Defines if the last and first points of each path in your pathArray must be joined - */ - closePath: boolean, - /** - * Defines the offset between points - */ - offset: number, canBeRegenerated?: boolean, mesh?: Mesh, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - /** @hidden */ - - copy(id: string): Geometry; - } - /** - * Creates a box geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#box - */ - class BoxGeometry extends _PrimitiveGeometry { + removeAngularSpeedGradient(gradient: number): IParticleSystem; /** - * Defines the zise of the box (width, height and depth are the same) + * Gets the current list of velocity gradients. + * You must use addVelocityGradient and removeVelocityGradient to udpate this list + * @returns the list of velocity gradients */ - size: number; + getVelocityGradients(): Nullable>; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Adds a new velocity gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system */ - side: number; + addVelocityGradient(gradient: number, factor: number, factor2?: number): IParticleSystem; /** - * Creates a box geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param size defines the zise of the box (width, height and depth are the same) - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Remove a specific velocity gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - constructor(id: string, scene: Scene, - /** - * Defines the zise of the box (width, height and depth are the same) - */ - size: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedBox: any, scene: Scene): Nullable; + removeVelocityGradient(gradient: number): IParticleSystem; } +} + +declare module BABYLON { /** - * Creates a sphere geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere + * A particle represents one of the element emitted by a particle system. + * This is mainly define by its coordinates, direction, velocity and age. */ - class SphereGeometry extends _PrimitiveGeometry { + class Particle { /** - * Defines the number of segments to use to create the sphere + * particleSystem the particle system the particle belongs to. */ - segments: number; + particleSystem: ParticleSystem; /** - * Defines the diameter of the sphere + * The world position of the particle in the scene. */ - diameter: number; + position: Vector3; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * The world direction of the particle in the scene. */ - side: number; + direction: Vector3; /** - * Create a new sphere geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param segments defines the number of segments to use to create the sphere - * @param diameter defines the diameter of the sphere - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * The color of the particle. */ - constructor(id: string, scene: Scene, - /** - * Defines the number of segments to use to create the sphere - */ - segments: number, - /** - * Defines the diameter of the sphere - */ - diameter: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedSphere: any, scene: Scene): Nullable; - } - /** - * Creates a disc geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon - */ - class DiscGeometry extends _PrimitiveGeometry { + color: Color4; /** - * Defines the radius of the disc + * The color change of the particle per step. */ - radius: number; + colorStep: Color4; /** - * Defines the tesselation factor to apply to the disc + * Defines how long will the life of the particle be. */ - tessellation: number; + lifeTime: number; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * The current age of the particle. */ - side: number; + age: number; /** - * Creates a new disc geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param radius defines the radius of the disc - * @param tessellation defines the tesselation factor to apply to the disc - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * The current size of the particle. */ - constructor(id: string, scene: Scene, - /** - * Defines the radius of the disc - */ - radius: number, - /** - * Defines the tesselation factor to apply to the disc - */ - tessellation: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - - copy(id: string): Geometry; - } - /** - * Creates a new cylinder geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone - */ - class CylinderGeometry extends _PrimitiveGeometry { + size: number; /** - * Defines the height of the cylinder + * The current scale of the particle. */ - height: number; + scale: Vector2; /** - * Defines the diameter of the cylinder's top cap + * The current angle of the particle. */ - diameterTop: number; + angle: number; /** - * Defines the diameter of the cylinder's bottom cap + * Defines how fast is the angle changing. */ - diameterBottom: number; + angularSpeed: number; /** - * Defines the tessellation factor to apply to the cylinder + * Defines the cell index used by the particle to be rendered from a sprite. */ - tessellation: number; + cellIndex: number; + /** @hidden */ + + /** @hidden */ + + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + + /** @hidden */ + /** - * Defines the number of subdivisions to apply to the cylinder (1 by default) + * Creates a new instance Particle + * @param particleSystem the particle system the particle belongs to */ - subdivisions: number; + constructor( /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * particleSystem the particle system the particle belongs to. */ - side: number; + particleSystem: ParticleSystem); + private updateCellInfoFromSystem; /** - * Creates a new cylinder geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param height defines the height of the cylinder - * @param diameterTop defines the diameter of the cylinder's top cap - * @param diameterBottom defines the diameter of the cylinder's bottom cap - * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides) - * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default) - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Defines how the sprite cell index is updated for the particle */ - constructor(id: string, scene: Scene, - /** - * Defines the height of the cylinder - */ - height: number, - /** - * Defines the diameter of the cylinder's top cap - */ - diameterTop: number, - /** - * Defines the diameter of the cylinder's bottom cap - */ - diameterBottom: number, - /** - * Defines the tessellation factor to apply to the cylinder - */ - tessellation: number, - /** - * Defines the number of subdivisions to apply to the cylinder (1 by default) - */ - subdivisions?: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedCylinder: any, scene: Scene): Nullable; + updateCellIndex(): void; + /** + * Copy the properties of particle to another one. + * @param other the particle to copy the information to. + */ + copyTo(other: Particle): void; } +} + +declare module BABYLON { /** - * Creates a new torus geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#torus + * This class is made for on one-liner static method to help creating particle system set. */ - class TorusGeometry extends _PrimitiveGeometry { - /** - * Defines the diameter of the torus - */ - diameter: number; + class ParticleHelper { /** - * Defines the thickness of the torus (ie. internal diameter) + * Gets or sets base Assets URL */ - thickness: number; + static BaseAssetsUrl: string; /** - * Defines the tesselation factor to apply to the torus + * Create a default particle system that you can tweak + * @param emitter defines the emitter to use + * @param capacity defines the system capacity (default is 500 particles) + * @param scene defines the hosting scene + * @returns the new Particle system */ - tessellation: number; + static CreateDefault(emitter: Nullable, capacity?: number, scene?: Scene): ParticleSystem; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * This is the main static method (one-liner) of this helper to create different particle systems + * @param type This string represents the type to the particle system to create + * @param scene The scene where the particle system should live + * @param gpu If the system will use gpu + * @returns the ParticleSystemSet created */ - side: number; + static CreateAsync(type: string, scene: Nullable, gpu?: boolean): Promise; /** - * Creates a new torus geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param diameter defines the diameter of the torus - * @param thickness defines the thickness of the torus (ie. internal diameter) - * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle) - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Static function used to export a particle system to a ParticleSystemSet variable. + * Please note that the emitter shape is not exported + * @param system defines the particle systems to export */ - constructor(id: string, scene: Scene, - /** - * Defines the diameter of the torus - */ - diameter: number, - /** - * Defines the thickness of the torus (ie. internal diameter) - */ - thickness: number, - /** - * Defines the tesselation factor to apply to the torus - */ - tessellation: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedTorus: any, scene: Scene): Nullable; + static ExportSet(systems: IParticleSystem[]): ParticleSystemSet; } +} + +declare module BABYLON { /** - * Creates a new ground geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#ground + * This represents a particle system in Babylon. + * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. + * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function. + * @example https://doc.babylonjs.com/babylon101/particles */ - class GroundGeometry extends _PrimitiveGeometry { + class ParticleSystem implements IDisposable, IAnimatable, IParticleSystem { /** - * Defines the width of the ground + * Source color is added to the destination color without alpha affecting the result. */ - width: number; + static BLENDMODE_ONEONE: number; /** - * Defines the height of the ground + * Blend current color and particle color using particle’s alpha. */ - height: number; + static BLENDMODE_STANDARD: number; /** - * Defines the subdivisions to apply to the ground + * Add current color and particle color multiplied by particle’s alpha. */ - subdivisions: number; + static BLENDMODE_ADD: number; /** - * Creates a new ground geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param width defines the width of the ground - * @param height defines the height of the ground - * @param subdivisions defines the subdivisions to apply to the ground - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) + * List of animations used by the particle system. */ - constructor(id: string, scene: Scene, - /** - * Defines the width of the ground - */ - width: number, - /** - * Defines the height of the ground - */ - height: number, - /** - * Defines the subdivisions to apply to the ground - */ - subdivisions: number, canBeRegenerated?: boolean, mesh?: Nullable); - - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedGround: any, scene: Scene): Nullable; - } - /** - * Creates a tiled ground geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground - */ - class TiledGroundGeometry extends _PrimitiveGeometry { + animations: Animation[]; /** - * Defines the minimum value on X axis + * The id of the Particle system. */ - xmin: number; + id: string; /** - * Defines the minimum value on Z axis + * The friendly name of the Particle system. */ - zmin: number; + name: string; /** - * Defines the maximum value on X axis + * The rendering group used by the Particle system to chose when to render. */ - xmax: number; + renderingGroupId: number; /** - * Defines the maximum value on Z axis + * The emitter represents the Mesh or position we are attaching the particle system to. */ - zmax: number; + emitter: Nullable; /** - * Defines the subdivisions to apply to the ground + * The maximum number of particles to emit per frame */ - subdivisions: { - w: number; - h: number; - }; + emitRate: number; /** - * Defines the precision to use when computing the tiles + * If you want to launch only a few particles at once, that can be done, as well. */ - precision: { - w: number; - h: number; - }; + manualEmitCount: number; /** - * Creates a tiled ground geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param xmin defines the minimum value on X axis - * @param zmin defines the minimum value on Z axis - * @param xmax defines the maximum value on X axis - * @param zmax defines the maximum value on Z axis - * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map) - * @param precision defines the precision to use when computing the tiles - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) + * The overall motion speed (0.01 is default update speed, faster updates = faster animation) */ - constructor(id: string, scene: Scene, - /** - * Defines the minimum value on X axis - */ - xmin: number, - /** - * Defines the minimum value on Z axis - */ - zmin: number, - /** - * Defines the maximum value on X axis - */ - xmax: number, - /** - * Defines the maximum value on Z axis - */ - zmax: number, - /** - * Defines the subdivisions to apply to the ground - */ - subdivisions: { - w: number; - h: number; - }, - /** - * Defines the precision to use when computing the tiles - */ - precision: { - w: number; - h: number; - }, canBeRegenerated?: boolean, mesh?: Nullable); - - copy(id: string): Geometry; - } - /** - * Creates a plane geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#plane - */ - class PlaneGeometry extends _PrimitiveGeometry { + updateSpeed: number; /** - * Defines the size of the plane (width === height) + * The amount of time the particle system is running (depends of the overall update speed). */ - size: number; + targetStopDuration: number; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Specifies whether the particle system will be disposed once it reaches the end of the animation. */ - side: number; + disposeOnStop: boolean; /** - * Creates a plane geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param size defines the size of the plane (width === height) - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Minimum power of emitting particles. */ - constructor(id: string, scene: Scene, - /** - * Defines the size of the plane (width === height) - */ - size: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedPlane: any, scene: Scene): Nullable; - } - /** - * Creates a torus knot geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot - */ - class TorusKnotGeometry extends _PrimitiveGeometry { + minEmitPower: number; /** - * Defines the radius of the torus knot + * Maximum power of emitting particles. */ - radius: number; + maxEmitPower: number; /** - * Defines the thickness of the torus knot tube + * Minimum life time of emitting particles. */ - tube: number; + minLifeTime: number; /** - * Defines the number of radial segments + * Maximum life time of emitting particles. */ - radialSegments: number; + maxLifeTime: number; /** - * Defines the number of tubular segments + * Minimum Size of emitting particles. */ - tubularSegments: number; + minSize: number; /** - * Defines the first number of windings + * Maximum Size of emitting particles. */ - p: number; + maxSize: number; /** - * Defines the second number of windings + * Minimum scale of emitting particles on X axis. */ - q: number; + minScaleX: number; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Maximum scale of emitting particles on X axis. */ - side: number; + maxScaleX: number; /** - * Creates a torus knot geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param radius defines the radius of the torus knot - * @param tube defines the thickness of the torus knot tube - * @param radialSegments defines the number of radial segments - * @param tubularSegments defines the number of tubular segments - * @param p defines the first number of windings - * @param q defines the second number of windings - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Minimum scale of emitting particles on Y axis. */ - constructor(id: string, scene: Scene, - /** - * Defines the radius of the torus knot - */ - radius: number, - /** - * Defines the thickness of the torus knot tube - */ - tube: number, - /** - * Defines the number of radial segments - */ - radialSegments: number, - /** - * Defines the number of tubular segments - */ - tubularSegments: number, - /** - * Defines the first number of windings - */ - p: number, - /** - * Defines the second number of windings - */ - q: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedTorusKnot: any, scene: Scene): Nullable; - } -} - -declare module BABYLON { - class GroundMesh extends Mesh { - generateOctree: boolean; - private _heightQuads; - - - - - - - - - constructor(name: string, scene: Scene); - getClassName(): string; - readonly subdivisions: number; - readonly subdivisionsX: number; - readonly subdivisionsY: number; - optimize(chunksCount: number, octreeBlocksSize?: number): void; + minScaleY: number; /** - * Returns a height (y) value in the Worl system : - * the ground altitude at the coordinates (x, z) expressed in the World system. - * Returns the ground y position if (x, z) are outside the ground surface. + * Maximum scale of emitting particles on Y axis. */ - getHeightAtCoordinates(x: number, z: number): number; + maxScaleY: number; /** - * Returns a normalized vector (Vector3) orthogonal to the ground - * at the ground coordinates (x, z) expressed in the World system. - * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface. + * Gets or sets the minimal initial rotation in radians. */ - getNormalAtCoordinates(x: number, z: number): Vector3; + minInitialRotation: number; /** - * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground - * at the ground coordinates (x, z) expressed in the World system. - * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface. - * Returns the GroundMesh. + * Gets or sets the maximal initial rotation in radians. */ - getNormalAtCoordinatesToRef(x: number, z: number, ref: Vector3): GroundMesh; + maxInitialRotation: number; /** - * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates() - * if the ground has been updated. - * This can be used in the render loop. - * Returns the GroundMesh. - */ - updateCoordinateHeights(): GroundMesh; - private _getFacetAt(x, z); - private _initHeightQuads(); - private _computeHeightQuads(); - serialize(serializationObject: any): void; - static Parse(parsedMesh: any, scene: Scene): GroundMesh; - } -} - -declare module BABYLON { - /** - * Creates an instance based on a source mesh. - */ - class InstancedMesh extends AbstractMesh { - private _sourceMesh; - private _currentLOD; - constructor(name: string, source: Mesh); + * Minimum angular speed of emitting particles (Z-axis rotation for each particle). + */ + minAngularSpeed: number; /** - * Returns the string "InstancedMesh". + * Maximum angular speed of emitting particles (Z-axis rotation for each particle). */ - getClassName(): string; - readonly receiveShadows: boolean; - readonly material: Nullable; - readonly visibility: number; - readonly skeleton: Nullable; - renderingGroupId: number; + maxAngularSpeed: number; /** - * Returns the total number of vertices (integer). + * The texture used to render each particle. (this can be a spritesheet) */ - getTotalVertices(): number; - readonly sourceMesh: Mesh; + particleTexture: Nullable; /** - * Is this node ready to be used/rendered - * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) - * @return {boolean} is it ready + * The layer mask we are rendering the particles through. */ - isReady(completeCheck?: boolean): boolean; + layerMask: number; /** - * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc. + * This can help using your own shader to render the particle system. + * The according effect will be created */ - getVerticesData(kind: string, copyWhenShared?: boolean): Nullable; + customShader: any; /** - * Sets the vertex data of the mesh geometry for the requested `kind`. - * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. - * The `data` are either a numeric array either a Float32Array. - * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater. - * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc). - * Note that a new underlying VertexBuffer object is created each call. - * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. - * - * Possible `kind` values : - * - BABYLON.VertexBuffer.PositionKind - * - BABYLON.VertexBuffer.UVKind - * - BABYLON.VertexBuffer.UV2Kind - * - BABYLON.VertexBuffer.UV3Kind - * - BABYLON.VertexBuffer.UV4Kind - * - BABYLON.VertexBuffer.UV5Kind - * - BABYLON.VertexBuffer.UV6Kind - * - BABYLON.VertexBuffer.ColorKind - * - BABYLON.VertexBuffer.MatricesIndicesKind - * - BABYLON.VertexBuffer.MatricesIndicesExtraKind - * - BABYLON.VertexBuffer.MatricesWeightsKind - * - BABYLON.VertexBuffer.MatricesWeightsExtraKind - * - * Returns the Mesh. + * By default particle system starts as soon as they are created. This prevents the + * automatic start to happen and let you decide when to start emitting particles. */ - setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): Mesh; + preventAutoStart: boolean; /** - * Updates the existing vertex data of the mesh geometry for the requested `kind`. - * If the mesh has no geometry, it is simply returned as it is. - * The `data` are either a numeric array either a Float32Array. - * No new underlying VertexBuffer object is created. - * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. - * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh. - * - * Possible `kind` values : - * - BABYLON.VertexBuffer.PositionKind - * - BABYLON.VertexBuffer.UVKind - * - BABYLON.VertexBuffer.UV2Kind - * - BABYLON.VertexBuffer.UV3Kind - * - BABYLON.VertexBuffer.UV4Kind - * - BABYLON.VertexBuffer.UV5Kind - * - BABYLON.VertexBuffer.UV6Kind - * - BABYLON.VertexBuffer.ColorKind - * - BABYLON.VertexBuffer.MatricesIndicesKind - * - BABYLON.VertexBuffer.MatricesIndicesExtraKind - * - BABYLON.VertexBuffer.MatricesWeightsKind - * - BABYLON.VertexBuffer.MatricesWeightsExtraKind - * - * Returns the Mesh. + * Gets or sets a texture used to add random noise to particle positions */ - updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): Mesh; + noiseTexture: Nullable; + /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ + noiseStrength: Vector3; /** - * Sets the mesh indices. - * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array). - * If the mesh has no geometry, a new Geometry object is created and set to the mesh. - * This method creates a new index buffer each call. - * Returns the Mesh. + * This function can be defined to provide custom update for active particles. + * This function will be called instead of regular update (age, position, color, etc.). + * Do not forget that this function will be called on every frame so try to keep it simple and fast :) */ - setIndices(indices: IndicesArray, totalVertices?: Nullable): Mesh; + updateFunction: (particles: Particle[]) => void; /** - * Boolean : True if the mesh owns the requested kind of data. + * Callback triggered when the particle animation is ending. */ - isVerticesDataPresent(kind: string): boolean; + onAnimationEnd: Nullable<() => void>; /** - * Returns an array of indices (IndicesArray). + * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD. */ - getIndices(): Nullable; -protected readonly _positions: Nullable; + blendMode: number; /** - * Sets a new updated BoundingInfo to the mesh. - * Returns the mesh. + * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls + * to override the particles. */ - refreshBoundingInfo(): InstancedMesh; - - + forceDepthWrite: boolean; /** - * Returns the current associated LOD AbstractMesh. + * You can use gravity if you want to give an orientation to your particles. */ - getLOD(camera: Camera): AbstractMesh; - - + gravity: Vector3; + private _emitterWorldMatrix; + private _colorGradients; + private _sizeGradients; + private _lifeTimeGradients; + private _angularSpeedGradients; + private _velocityGradients; /** - * Creates a new InstancedMesh from the current mesh. - * - name (string) : the cloned mesh name - * - newParent (optional Node) : the optional Node to parent the clone to. - * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned. - * - * Returns the clone. + * Gets the current list of color gradients. + * You must use addColorGradient and removeColorGradient to udpate this list + * @returns the list of color gradients */ - clone(name: string, newParent: Node, doNotCloneChildren?: boolean): InstancedMesh; + getColorGradients(): Nullable>; /** - * Disposes the InstancedMesh. - * Returns nothing. + * Gets the current list of size gradients. + * You must use addSizeGradient and removeSizeGradient to udpate this list + * @returns the list of size gradients */ - dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; - } -} - -declare module BABYLON { - class LinesMesh extends Mesh { - useVertexColor: boolean | undefined; - useVertexAlpha: boolean | undefined; - color: Color3; - alpha: number; + getSizeGradients(): Nullable>; /** - * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray. - * This margin is expressed in world space coordinates, so its value may vary. - * Default value is 0.1 - * @returns the intersection Threshold value. + * Gets the current list of life time gradients. + * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list + * @returns the list of life time gradients */ + getLifeTimeGradients(): Nullable>; /** - * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray. - * This margin is expressed in world space coordinates, so its value may vary. - * @param value the new threshold to apply + * Gets the current list of angular speed gradients. + * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list + * @returns the list of angular speed gradients */ - intersectionThreshold: number; - private _intersectionThreshold; - private _colorShader; - constructor(name: string, scene?: Nullable, parent?: Nullable, source?: LinesMesh, doNotCloneChildren?: boolean, useVertexColor?: boolean | undefined, useVertexAlpha?: boolean | undefined); + getAngularSpeedGradients(): Nullable>; /** - * Returns the string "LineMesh" + * Gets the current list of velocity gradients. + * You must use addVelocityGradient and removeVelocityGradient to udpate this list + * @returns the list of velocity gradients */ - getClassName(): string; + getVelocityGradients(): Nullable>; /** - * @hidden + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + * This only works when particleEmitterTyps is a BoxParticleEmitter */ + direction1: Vector3; /** - * @hidden + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + * This only works when particleEmitterTyps is a BoxParticleEmitter + */ + direction2: Vector3; + /** + * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. + * This only works when particleEmitterTyps is a BoxParticleEmitter + */ + minEmitBox: Vector3; + /** + * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. + * This only works when particleEmitterTyps is a BoxParticleEmitter */ - material: Material; + maxEmitBox: Vector3; /** - * @hidden + * Random color of each particle after it has been emitted, between color1 and color2 vectors */ - readonly checkCollisions: boolean; - createInstance(name: string): InstancedMesh; - - - dispose(doNotRecurse?: boolean): void; + color1: Color4; /** - * Returns a new LineMesh object cloned from the current one. + * Random color of each particle after it has been emitted, between color1 and color2 vectors */ - clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): LinesMesh; - } -} - -declare module BABYLON { - /** - * @hidden - **/ - class _InstancesBatch { - mustReturn: boolean; - visibleInstances: Nullable[]; - renderSelf: boolean[]; - } - class Mesh extends AbstractMesh implements IGetSetVerticesData { -private static _FRONTSIDE: number; -private static _BACKSIDE: number; -private static _DOUBLESIDE: number; -private static _DEFAULTSIDE: number; -private static _NO_CAP: number; -private static _CAP_START: number; -private static _CAP_END: number; -private static _CAP_ALL: number; + color2: Color4; /** - * Mesh side orientation : usually the external or front surface + * Color the particle will have at the end of its lifetime */ - static readonly FRONTSIDE: number; + colorDead: Color4; /** - * Mesh side orientation : usually the internal or back surface + * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel */ - static readonly BACKSIDE: number; + textureMask: Color4; /** - * Mesh side orientation : both internal and external or front and back surfaces + * The particle emitter type defines the emitter used by the particle system. + * It can be for example box, sphere, or cone... */ - static readonly DOUBLESIDE: number; + particleEmitterType: IParticleEmitterType; /** - * Mesh side orientation : by default, `FRONTSIDE` + * This function can be defined to specify initial direction for every new particle. + * It by default use the emitterType defined function */ - static readonly DEFAULTSIDE: number; + startDirectionFunction: (worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle) => void; /** - * Mesh cap setting : no cap + * This function can be defined to specify initial position for every new particle. + * It by default use the emitterType defined function */ - static readonly NO_CAP: number; + startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle) => void; /** - * Mesh cap setting : one cap at the beginning of the mesh + * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime) */ - static readonly CAP_START: number; + spriteCellChangeSpeed: number; /** - * Mesh cap setting : one cap at the end of the mesh + * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display */ - static readonly CAP_END: number; + startSpriteCellID: number; /** - * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh + * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display */ - static readonly CAP_ALL: number; + endSpriteCellID: number; /** - * An event triggered before rendering the mesh + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use */ - onBeforeRenderObservable: Observable; + spriteCellWidth: number; /** - * An event triggered after rendering the mesh - */ - onAfterRenderObservable: Observable; + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use + */ + spriteCellHeight: number; + /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */ + preWarmCycles: number; + /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */ + preWarmStepOffset: number; + /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ + translationPivot: Vector2; /** - * An event triggered before drawing the mesh + * An event triggered when the system is disposed */ - onBeforeDrawObservable: Observable; - private _onBeforeDrawObserver; - onBeforeDraw: () => void; - delayLoadState: number; - instances: InstancedMesh[]; - delayLoadingFile: string; - - private _LODLevels; - onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Nullable) => void; - private _morphTargetManager; - morphTargetManager: Nullable; - - - - - private _renderIdForInstances; - private _batchCache; - private _instancesBufferSize; - private _instancesBuffer; - private _instancesData; - private _overridenInstanceCount; - private _effectiveMaterial; - - private _preActivateId; - - overrideMaterialSideOrientation: Nullable; - private _areNormalsFrozen; - private _sourcePositions; - private _sourceNormals; - private _source; - readonly source: Nullable; - isUnIndexed: boolean; - /** - * @constructor - * @param {string} name The value used by scene.getMeshByName() to do a lookup. - * @param {Scene} scene The scene to add this mesh to. - * @param {Node} parent The parent of this mesh, if it has one - * @param {Mesh} source An optional Mesh from which geometry is shared, cloned. - * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False. - * When false, achieved by calling a clone(), also passing False. - * This will make creation of children, recursive. - * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True. - */ - constructor(name: string, scene?: Nullable, parent?: Nullable, source?: Nullable, doNotCloneChildren?: boolean, clonePhysicsImpostor?: boolean); + onDisposeObservable: Observable; + private _onDisposeObserver; /** - * Returns the string "Mesh". + * Sets a callback that will be triggered when the system is disposed */ - getClassName(): string; + onDispose: () => void; /** - * Returns a string. - * @param {boolean} fullDetails - support for multiple levels of logging within scene loading + * Gets or sets whether an animation sprite sheet is enabled or not on the particle system */ - toString(fullDetails?: boolean): string; - + isAnimationSheetEnabled: boolean; /** - * True if the mesh has some Levels Of Details (LOD). - * Returns a boolean. + * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction */ - readonly hasLODLevels: boolean; + isBillboardBased: boolean; /** - * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh - * @returns an array of {BABYLON.MeshLODLevel} + * Get hosting scene + * @returns the scene */ - getLODLevels(): MeshLODLevel[]; - private _sortLODLevels(); + getScene(): Scene; /** - * Add a mesh as LOD level triggered at the given distance. - * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD - * @param distance The distance from the center of the object to show this level - * @param mesh The mesh to be added as LOD level (can be null) - * @return This mesh (for chaining) + * Gets or sets the billboard mode to use when isBillboardBased = true. + * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far */ - addLODLevel(distance: number, mesh: Nullable): Mesh; + billboardMode: number; + private _particles; + private _epsilon; + private _capacity; + private _scene; + private _stockParticles; + private _newPartsExcess; + private _vertexData; + private _vertexBuffer; + private _vertexBuffers; + private _spriteBuffer; + private _indexBuffer; + private _effect; + private _customEffect; + private _cachedDefines; + private _scaledColorStep; + private _colorDiff; + private _scaledDirection; + private _scaledGravity; + private _currentRenderId; + private _alive; + private _useInstancing; + private _started; + private _stopped; + private _actualFrame; + private _scaledUpdateSpeed; + private _vertexBufferSize; + private _isAnimationSheetEnabled; + private _isBillboardBased; /** - * Returns the LOD level mesh at the passed distance or null if not found. - * It is related to the method `addLODLevel(distance, mesh)`. - * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD - * Returns an object Mesh or `null`. + * this is the Sub-emitters templates that will be used to generate particle system when the particle dies, this property is used by the root particle system only. */ - getLODLevelAtDistance(distance: number): Nullable; + subEmitters: ParticleSystem[]; /** - * Remove a mesh from the LOD array - * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD - * @param {Mesh} mesh The mesh to be removed. - * @return {Mesh} This mesh (for chaining) - */ - removeLODLevel(mesh: Mesh): Mesh; + * The current active Sub-systems, this property is used by the root particle system only. + */ + activeSubSystems: Array; + private _rootParticleSystem; /** - * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh. - * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod + * Gets the current list of active particles */ - getLOD(camera: Camera, boundingSphere?: BoundingSphere): Nullable; + readonly particles: Particle[]; /** - * Returns the mesh internal Geometry object. + * Returns the string "ParticleSystem" + * @returns a string containing the class name */ - readonly geometry: Nullable; + getClassName(): string; /** - * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry. + * Instantiates a particle system. + * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. + * @param name The name of the particle system + * @param capacity The max number of particles alive at the same time + * @param scene The scene the particle system belongs to + * @param customEffect a custom effect used to change the way particles are rendered by default + * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture + * @param epsilon Offset used to render the particles */ - getTotalVertices(): number; + constructor(name: string, capacity: number, scene: Scene, customEffect?: Nullable, isAnimationSheetEnabled?: boolean, epsilon?: number); + private _fetchR; + private _addFactorGradient; + private _removeFactorGradient; /** - * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc). - * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one. - * You can force the copy with forceCopy === true - * Returns null if the mesh has no geometry or no vertex buffer. - * Possible `kind` values : - * - BABYLON.VertexBuffer.PositionKind - * - BABYLON.VertexBuffer.UVKind - * - BABYLON.VertexBuffer.UV2Kind - * - BABYLON.VertexBuffer.UV3Kind - * - BABYLON.VertexBuffer.UV4Kind - * - BABYLON.VertexBuffer.UV5Kind - * - BABYLON.VertexBuffer.UV6Kind - * - BABYLON.VertexBuffer.ColorKind - * - BABYLON.VertexBuffer.MatricesIndicesKind - * - BABYLON.VertexBuffer.MatricesIndicesExtraKind - * - BABYLON.VertexBuffer.MatricesWeightsKind - * - BABYLON.VertexBuffer.MatricesWeightsExtraKind + * Adds a new life time gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the life time factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system */ - getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable; + addLifeTimeGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; /** - * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc. - * Returns `null` if the mesh has no geometry. - * Possible `kind` values : - * - BABYLON.VertexBuffer.PositionKind - * - BABYLON.VertexBuffer.UVKind - * - BABYLON.VertexBuffer.UV2Kind - * - BABYLON.VertexBuffer.UV3Kind - * - BABYLON.VertexBuffer.UV4Kind - * - BABYLON.VertexBuffer.UV5Kind - * - BABYLON.VertexBuffer.UV6Kind - * - BABYLON.VertexBuffer.ColorKind - * - BABYLON.VertexBuffer.MatricesIndicesKind - * - BABYLON.VertexBuffer.MatricesIndicesExtraKind - * - BABYLON.VertexBuffer.MatricesWeightsKind - * - BABYLON.VertexBuffer.MatricesWeightsExtraKind + * Remove a specific life time gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - getVertexBuffer(kind: string): Nullable; - isVerticesDataPresent(kind: string): boolean; + removeLifeTimeGradient(gradient: number): ParticleSystem; /** - * Returns a boolean defining if the vertex data for the requested `kind` is updatable. - * Possible `kind` values : - * - BABYLON.VertexBuffer.PositionKind - * - BABYLON.VertexBuffer.UVKind - * - BABYLON.VertexBuffer.UV2Kind - * - BABYLON.VertexBuffer.UV3Kind - * - BABYLON.VertexBuffer.UV4Kind - * - BABYLON.VertexBuffer.UV5Kind - * - BABYLON.VertexBuffer.UV6Kind - * - BABYLON.VertexBuffer.ColorKind - * - BABYLON.VertexBuffer.MatricesIndicesKind - * - BABYLON.VertexBuffer.MatricesIndicesExtraKind - * - BABYLON.VertexBuffer.MatricesWeightsKind - * - BABYLON.VertexBuffer.MatricesWeightsExtraKind + * Adds a new size gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system */ - isVertexBufferUpdatable(kind: string): boolean; + addSizeGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; /** - * Returns a string : the list of existing `kinds` of Vertex Data for this mesh. - * Possible `kind` values : - * - BABYLON.VertexBuffer.PositionKind - * - BABYLON.VertexBuffer.UVKind - * - BABYLON.VertexBuffer.UV2Kind - * - BABYLON.VertexBuffer.UV3Kind - * - BABYLON.VertexBuffer.UV4Kind - * - BABYLON.VertexBuffer.UV5Kind - * - BABYLON.VertexBuffer.UV6Kind - * - BABYLON.VertexBuffer.ColorKind - * - BABYLON.VertexBuffer.MatricesIndicesKind - * - BABYLON.VertexBuffer.MatricesIndicesExtraKind - * - BABYLON.VertexBuffer.MatricesWeightsKind - * - BABYLON.VertexBuffer.MatricesWeightsExtraKind + * Remove a specific size gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - getVerticesDataKinds(): string[]; + removeSizeGradient(gradient: number): ParticleSystem; /** - * Returns a positive integer : the total number of indices in this mesh geometry. - * Returns zero if the mesh has no geometry. + * Adds a new angular speed gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system */ - getTotalIndices(): number; + addAngularSpeedGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; /** - * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices. - * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one. - * Returns an empty array if the mesh has no geometry. + * Remove a specific angular speed gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - getIndices(copyWhenShared?: boolean): Nullable; - readonly isBlocked: boolean; + removeAngularSpeedGradient(gradient: number): ParticleSystem; /** - * Determine if the current mesh is ready to be rendered - * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) - * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default) - * @returns true if all associated assets are ready (material, textures, shaders) + * Adds a new velocity gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system */ - isReady(completeCheck?: boolean, forceInstanceSupport?: boolean): boolean; + addVelocityGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; /** - * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update. - * This property is pertinent only for updatable parametric shapes. + * Remove a specific velocity gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - readonly areNormalsFrozen: boolean; + removeVelocityGradient(gradient: number): ParticleSystem; /** - * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. - * It has no effect at all on other shapes. - * It prevents the mesh normals from being recomputed on next `positions` array update. - * Returns the Mesh. + * Adds a new color gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param color defines the color to affect to the specified gradient + * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from */ - freezeNormals(): Mesh; + addColorGradient(gradient: number, color: Color4, color2?: Color4): ParticleSystem; /** - * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. - * It has no effect at all on other shapes. - * It reactivates the mesh normals computation if it was previously frozen. - * Returns the Mesh. + * Remove a specific color gradient + * @param gradient defines the gradient to remove */ - unfreezeNormals(): Mesh; + removeColorGradient(gradient: number): ParticleSystem; + private _resetEffect; + private _createVertexBuffers; + private _createIndexBuffer; /** - * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs + * Gets the maximum number of particles active at the same time. + * @returns The max number of active particles. */ - overridenInstanceCount: number; - - - + getCapacity(): number; /** - * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked. - * This means the mesh underlying bounding box and sphere are recomputed. - * Returns the Mesh. + * Gets Wether there are still active particles in the system. + * @returns True if it is alive, otherwise false. */ - refreshBoundingInfo(): Mesh; - - private _getPositionData(applySkeleton); - - subdivide(count: number): void; - setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): Mesh; - markVerticesDataAsUpdatable(kind: string, updatable?: boolean): void; + isAlive(): boolean; /** - * Sets the mesh VertexBuffer. - * Returns the Mesh. + * Gets Wether the system has been started. + * @returns True if it has been started, otherwise false. */ - setVerticesBuffer(buffer: VertexBuffer): Mesh; - updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): Mesh; + isStarted(): boolean; /** - * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values. - * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions - * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything. - * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update. - * Returns the Mesh. + * Starts the particle system and begins to emit + * @param delay defines the delay in milliseconds before starting the system (0 by default) */ - updateMeshPositions(positionFunction: (data: FloatArray) => void, computeNormals?: boolean): Mesh; + start(delay?: number): void; /** - * Creates a un-shared specific occurence of the geometry for the mesh. - * Returns the Mesh. + * Stops the particle system. + * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true. */ - makeGeometryUnique(): Mesh; - setIndices(indices: IndicesArray, totalVertices?: Nullable, updatable?: boolean): Mesh; + stop(stopSubEmitters?: boolean): void; /** - * Update the current index buffer - * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array) - * Returns the Mesh. + * Remove all active particles */ - updateIndices(indices: IndicesArray, offset?: number): Mesh; + reset(): void; /** - * Invert the geometry to move from a right handed system to a left handed one. - * Returns the Mesh. + * @hidden (for internal use only) */ - toLeftHanded(): Mesh; - /** - * Registers for this mesh a javascript function called just before the rendering process. - * This function is passed the current mesh. - * Return the Mesh. - */ - registerBeforeRender(func: (mesh: AbstractMesh) => void): Mesh; - /** - * Disposes a previously registered javascript function called before the rendering. - * This function is passed the current mesh. - * Returns the Mesh. + * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list. + * Its lifetime will start back at 0. */ - unregisterBeforeRender(func: (mesh: AbstractMesh) => void): Mesh; + recycleParticle: (particle: Particle) => void; + private _stopSubEmitters; + private _createParticle; + private _removeFromRoot; + private _emitFromParticle; + private _update; + /** @hidden */ +private static _GetAttributeNamesOrOptions(isAnimationSheetEnabled?: boolean, isBillboardBased?: boolean): string[]; +private static _GetEffectCreationOptions(isAnimationSheetEnabled?: boolean): string[]; + private _getEffect; /** - * Registers for this mesh a javascript function called just after the rendering is complete. - * This function is passed the current mesh. - * Returns the Mesh. + * Animates the particle system for the current frame by emitting new particles and or animating the living ones. + * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false) */ - registerAfterRender(func: (mesh: AbstractMesh) => void): Mesh; + animate(preWarmOnly?: boolean): void; + private _appendParticleVertices; /** - * Disposes a previously registered javascript function called after the rendering. - * This function is passed the current mesh. - * Return the Mesh. + * Rebuilds the particle system. */ - unregisterAfterRender(func: (mesh: AbstractMesh) => void): Mesh; - - - + rebuild(): void; /** - * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager - * @param subMesh defines the subMesh to render - * @param enableAlphaMode defines if alpha mode can be changed - * @returns the current mesh + * Is this system ready to be used/rendered + * @return true if the system is ready */ - render(subMesh: SubMesh, enableAlphaMode: boolean): Mesh; - private _onBeforeDraw(isInstance, world, effectiveMaterial?); + isReady(): boolean; /** - * Returns an array populated with IParticleSystem objects whose the mesh is the emitter. + * Renders the particle system in its current state. + * @returns the current number of particles */ - getEmittedParticleSystems(): IParticleSystem[]; + render(): number; /** - * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter. + * Disposes the particle system and free the associated resources + * @param disposeTexture defines if the particule texture must be disposed as well (true by default) */ - getHierarchyEmittedParticleSystems(): IParticleSystem[]; + dispose(disposeTexture?: boolean): void; /** - * Normalize matrix weights so that all vertices have a total weight set to 1 + * Creates a Point Emitter for the particle system (emits directly from the emitter position) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the box + * @param direction2 Particles are emitted between the direction1 and direction2 from within the box + * @returns the emitter */ - cleanMatrixWeights(): void; - - private _queueLoad(scene); + createPointEmitter(direction1: Vector3, direction2: Vector3): PointParticleEmitter; /** - * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter. + * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius) + * @param radius The radius of the hemisphere to emit from + * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius + * @returns the emitter */ - isInFrustum(frustumPlanes: Plane[]): boolean; + createHemisphericEmitter(radius?: number, radiusRange?: number): HemisphericParticleEmitter; /** - * Sets the mesh material by the material or multiMaterial `id` property. - * The material `id` is a string identifying the material or the multiMaterial. - * This method returns the Mesh. + * Creates a Sphere Emitter for the particle system (emits along the sphere radius) + * @param radius The radius of the sphere to emit from + * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius + * @returns the emitter */ - setMaterialByID(id: string): Mesh; + createSphereEmitter(radius?: number, radiusRange?: number): SphereParticleEmitter; /** - * Returns as a new array populated with the mesh material and/or skeleton, if any. + * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2) + * @param radius The radius of the sphere to emit from + * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere + * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere + * @returns the emitter */ - getAnimatables(): IAnimatable[]; + createDirectedSphereEmitter(radius?: number, direction1?: Vector3, direction2?: Vector3): SphereDirectedParticleEmitter; /** - * Modifies the mesh geometry according to the passed transformation matrix. - * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable. - * The mesh normals are modified accordingly the same transformation. - * tuto : http://doc.babylonjs.com/resources/baking_transformations - * Note that, under the hood, this method sets a new VertexBuffer each call. - * Returns the Mesh. + * Creates a Cone Emitter for the particle system (emits from the cone to the particle position) + * @param radius The radius of the cone to emit from + * @param angle The base angle of the cone + * @returns the emitter */ - bakeTransformIntoVertices(transform: Matrix): Mesh; + createConeEmitter(radius?: number, angle?: number): ConeParticleEmitter; /** - * Modifies the mesh geometry according to its own current World Matrix. - * The mesh World Matrix is then reset. - * This method returns nothing but really modifies the mesh even if it's originally not set as updatable. - * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations - * Note that, under the hood, this method sets a new VertexBuffer each call. - * Returns the Mesh. + * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the box + * @param direction2 Particles are emitted between the direction1 and direction2 from within the box + * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox + * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox + * @returns the emitter */ - bakeCurrentTransformIntoVertices(): Mesh; -protected readonly _positions: Nullable; - - + createBoxEmitter(direction1: Vector3, direction2: Vector3, minEmitBox: Vector3, maxEmitBox: Vector3): BoxParticleEmitter; /** - * Returns a new Mesh object generated from the current mesh properties. - * This method must not get confused with createInstance(). - * The parameter `name` is a string, the name given to the new mesh. - * The optional parameter `newParent` can be any Node object (default `null`). - * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any. - * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any. + * Clones the particle system. + * @param name The name of the cloned object + * @param newEmitter The new emitter to use + * @returns the cloned particle system */ - clone(name: string, newParent?: Node, doNotCloneChildren?: boolean, clonePhysicsImpostor?: boolean): Mesh; + clone(name: string, newEmitter: any): ParticleSystem; /** - * Releases resources associated with this mesh. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + * Serializes the particle system to a JSON object. + * @returns the JSON object */ - dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; + serialize(): any; + /** @hidden */ +private static _Serialize(serializationObject: any, particleSystem: IParticleSystem): void; + /** @hidden */ +private static _Parse(parsedParticleSystem: any, particleSystem: IParticleSystem, scene: Scene, rootUrl: string): void; /** - * Modifies the mesh geometry according to a displacement map. - * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. - * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. - * This method returns nothing. - * The parameter `url` is a string, the URL from the image file is to be downloaded. - * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement. - * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing. - * The parameter `uvOffset` is an optional vector2 used to offset UV. - * The parameter `uvScale` is an optional vector2 used to scale UV. - * - * Returns the Mesh. + * Parses a JSON object to create a particle system. + * @param parsedParticleSystem The JSON object to parse + * @param scene The scene to create the particle system in + * @param rootUrl The root url to use to load external dependencies like texture + * @returns the Parsed particle system */ - applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void, uvOffset?: Vector2, uvScale?: Vector2): Mesh; + static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): ParticleSystem; + } +} + +declare module BABYLON { + interface Engine { /** - * Modifies the mesh geometry according to a displacementMap buffer. - * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. - * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. - * This method returns nothing. - * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel. - * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image. - * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement. - * The parameter `uvOffset` is an optional vector2 used to offset UV. - * The parameter `uvScale` is an optional vector2 used to scale UV. - * - * Returns the Mesh. + * Create an effect to use with particle systems. + * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration + * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx) + * @param uniformsNames defines a list of attribute names + * @param samplers defines an array of string used to represent textures + * @param defines defines the string containing the defines to use to compile the shaders + * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails + * @param onCompiled defines a function to call when the effect creation is successful + * @param onError defines a function to call when the effect creation has failed + * @returns the new Effect */ - applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number, uvOffset?: Vector2, uvScale?: Vector2): Mesh; + createEffectForParticles(fragmentName: string, uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect; + } +} + +declare module BABYLON { + /** + * Represents a set of particle systems working together to create a specific effect + */ + class ParticleSystemSet implements IDisposable { + private _emitterCreationOptions; + private _emitterNode; /** - * Modify the mesh to get a flat shading rendering. - * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result. - * This method returns the Mesh. - * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated. + * Gets the particle system list */ - convertToFlatShadedMesh(): Mesh; + systems: IParticleSystem[]; /** - * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers. - * In other words, more vertices, no more indices and a single bigger VBO. - * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated. - * Returns the Mesh. + * Gets the emitter node used with this set */ - convertToUnIndexedMesh(): Mesh; + readonly emitterNode: Nullable; /** - * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true. - * This method returns the Mesh. - * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. + * Creates a new emitter mesh as a sphere + * @param options defines the options used to create the sphere + * @param renderingGroupId defines the renderingGroupId to use for the sphere + * @param scene defines the hosting scene */ - flipFaces(flipNormals?: boolean): Mesh; + setEmitterAsSphere(options: { + diameter: number; + segments: number; + color: Color3; + }, renderingGroupId: number, scene: Scene): void; /** - * Creates a new InstancedMesh object from the mesh model. - * An instance shares the same properties and the same material than its model. - * Only these properties of each instance can then be set individually : - * - position - * - rotation - * - rotationQuaternion - * - setPivotMatrix - * - scaling - * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances - * Warning : this method is not supported for Line mesh and LineSystem + * Starts all particle systems of the set + * @param emitter defines an optional mesh to use as emitter for the particle systems */ - createInstance(name: string): InstancedMesh; + start(emitter?: AbstractMesh): void; /** - * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any. - * After this call, all the mesh instances have the same submeshes than the current mesh. - * This method returns the Mesh. + * Release all associated resources */ - synchronizeInstances(): Mesh; + dispose(): void; /** - * Simplify the mesh according to the given array of settings. - * Function will return immediately and will simplify async. It returns the Mesh. - * @param settings a collection of simplification settings. - * @param parallelProcessing should all levels calculate parallel or one after the other. - * @param type the type of simplification to run. - * @param successCallback optional success callback to be called after the simplification finished processing all settings. + * Serialize the set into a JSON compatible object + * @returns a JSON compatible representation of the set */ - simplify(settings: Array, parallelProcessing?: boolean, simplificationType?: SimplificationType, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void): Mesh; + serialize(): any; /** - * Optimization of the mesh's indices, in case a mesh has duplicated vertices. - * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes. - * This should be used together with the simplification to avoid disappearing triangles. - * Returns the Mesh. - * @param successCallback an optional success callback to be called after the optimization finished. + * Parse a new ParticleSystemSet from a serialized source + * @param data defines a JSON compatible representation of the set + * @param scene defines the hosting scene + * @param gpu defines if we want GPU particles or CPU particles + * @returns a new ParticleSystemSet */ - optimizeIndices(successCallback?: (mesh?: Mesh) => void): Mesh; - serialize(serializationObject: any): void; + static Parse(data: any, scene: Scene, gpu?: boolean): ParticleSystemSet; + } +} +declare module BABYLON { + /** + * Represents one particle of a solid particle system. + */ + class SolidParticle { /** - * Returns a new Mesh object parsed from the source provided. - * The parameter `parsedMesh` is the source. - * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with - */ - static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh; - /** - * Creates a ribbon mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. - * - * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial - * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry. - * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array. - * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array. - * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path. - * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11. - * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * particle global index */ - static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean | undefined, closePath: boolean, offset: number, scene?: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; + idx: number; /** - * Creates a plane polygonal mesh. By default, this is a disc. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `radius` sets the radius size (float) of the polygon (default 0.5). - * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc. - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * The color of the particle */ - static CreateDisc(name: string, radius: number, tessellation: number, scene?: Nullable, updatable?: boolean, sideOrientation?: number): Mesh; + color: Nullable; /** - * Creates a box mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `size` sets the size (float) of each box side (default 1). - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * The world space position of the particle. */ - static CreateBox(name: string, size: number, scene?: Nullable, updatable?: boolean, sideOrientation?: number): Mesh; + position: Vector3; /** - * Creates a sphere mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `diameter` sets the diameter size (float) of the sphere (default 1). - * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32). - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * The world space rotation of the particle. (Not use if rotationQuaternion is set) */ - static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + rotation: Vector3; /** - * Creates a cylinder or a cone mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2). - * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1). - * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero. - * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance. - * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1). - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * The world space rotation quaternion of the particle. */ - static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene?: Scene, updatable?: any, sideOrientation?: number): Mesh; + rotationQuaternion: Nullable; /** - * Creates a torus mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `diameter` sets the diameter size (float) of the torus (default 1). - * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5). - * The parameter `tessellation` sets the number of torus sides (postive integer, default 16). - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * The scaling of the particle. */ - static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + scaling: Vector3; /** - * Creates a torus knot mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `radius` sets the global radius size (float) of the torus knot (default 2). - * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32). - * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32). - * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3). - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * The uvs of the particle. */ - static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + uvs: Vector4; /** - * Creates a line mesh. - * Please consider using the same method from the MeshBuilder class instead. - * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter. - * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function. - * The parameter `points` is an array successive Vector3. - * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines - * When updating an instance, remember that only point positions can change, not the number of points. - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * The current speed of the particle. */ - static CreateLines(name: string, points: Vector3[], scene?: Nullable, updatable?: boolean, instance?: Nullable): LinesMesh; + velocity: Vector3; /** - * Creates a dashed line mesh. - * Please consider using the same method from the MeshBuilder class instead. - * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter. - * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function. - * The parameter `points` is an array successive Vector3. - * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200). - * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3). - * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1). - * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines - * When updating an instance, remember that only point positions can change, not the number of points. - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * The pivot point in the particle local space. */ - static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene?: Nullable, updatable?: boolean, instance?: LinesMesh): LinesMesh; + pivot: Vector3; /** - * Creates a polygon mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh. - * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors. - * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * Remember you can only change the shape positions, not their number when updating a polygon. + * Must the particle be translated from its pivot point in its local space ? + * In this case, the pivot point is set at the origin of the particle local space and the particle is translated. + * Default : false */ - static CreatePolygon(name: string, shape: Vector3[], scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number): Mesh; + translateFromPivot: boolean; /** - * Creates an extruded polygon mesh, with depth in the Y direction. - * Please consider using the same method from the MeshBuilder class instead. + * Is the particle active or not ? */ - static ExtrudePolygon(name: string, shape: Vector3[], depth: number, scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number): Mesh; + alive: boolean; /** - * Creates an extruded shape mesh. - * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. - * Please consider using the same method from the MeshBuilder class instead. - * - * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes - * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be - * extruded along the Z axis. - * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. - * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve. - * The parameter `scale` (float, default 1) is the value to scale the shape. - * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape - * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Is the particle visible or not ? */ - static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene?: Nullable, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; + isVisible: boolean; /** - * Creates an custom extruded shape mesh. - * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. - * Please consider using the same method from the MeshBuilder class instead. - * - * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes - * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be - * extruded along the Z axis. - * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. - * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path - * and the distance of this point from the begining of the path : - * ```javascript - * var rotationFunction = function(i, distance) { - * // do things - * return rotationValue; } - * ``` - * It must returns a float value that will be the rotation in radians applied to the shape on each path point. - * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path - * and the distance of this point from the begining of the path : - * ```javascript - * var scaleFunction = function(i, distance) { - * // do things - * return scaleValue;} - * ``` - * It must returns a float value that will be the scale value applied to the shape on each path point. - * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`. - * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`. - * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape - * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Index of this particle in the global "positions" array (Internal use) */ - static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction: Function, rotationFunction: Function, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; + /** - * Creates lathe mesh. - * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be - * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero. - * The parameter `radius` (positive float, default 1) is the radius value of the lathe. - * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe. - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Index of this particle in the global "indices" array (Internal use) */ - static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + /** - * Creates a plane mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `size` sets the size (float) of both sides of the plane at once (default 1). - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * ModelShape of this particle (Internal use) */ - static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + /** - * Creates a ground mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground. - * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side. - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * ModelShape id of this particle */ - static CreateGround(name: string, width: number, height: number, subdivisions: number, scene?: Scene, updatable?: boolean): Mesh; + shapeId: number; /** - * Creates a tiled ground mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates. - * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates. - * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the - * numbers of subdivisions on the ground width and height. Each subdivision is called a tile. - * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the - * numbers of subdivisions on the ground width and height of each tile. - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Index of the particle in its shape id (Internal use) */ - static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { - w: number; - h: number; - }, precision: { - w: number; - h: number; - }, scene: Scene, updatable?: boolean): Mesh; + idxInShape: number; /** - * Creates a ground mesh from a height map. - * tuto : http://doc.babylonjs.com/babylon101/height_map - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `url` sets the URL of the height map image resource. - * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes. - * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side. - * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground. - * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground. - * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time). - * This function is passed the newly built mesh : - * ```javascript - * function(mesh) { // do things - * return; } - * ``` - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Reference to the shape model BoundingInfo object (Internal use) */ - static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void): GroundMesh; + /** - * Creates a tube mesh. - * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube. - * The parameter `radius` (positive float, default 1) sets the tube radius size. - * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface. - * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`. - * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. - * It must return a radius value (positive float) : - * ```javascript - * var radiusFunction = function(i, distance) { - * // do things - * return radius; } - * ``` - * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Particle BoundingInfo object (Internal use) */ - static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { - (i: number, distance: number): number; - }, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; + /** - * Creates a polyhedron mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial - * to choose the wanted type. - * The parameter `size` (positive float, default 1) sets the polygon size. - * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value). - * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`. - * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron - * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`). - * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors - * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored. - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Reference to the SPS what the particle belongs to (Internal use) */ - static CreatePolyhedron(name: string, options: { - type?: number; - size?: number; - sizeX?: number; - sizeY?: number; - sizeZ?: number; - custom?: any; - faceUV?: Vector4[]; - faceColors?: Color4[]; - updatable?: boolean; - sideOrientation?: number; - }, scene: Scene): Mesh; + /** - * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `radius` sets the radius size (float) of the icosphere (default 1). - * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`). - * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size. - * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface. - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Still set as invisible in order to skip useless computations (Internal use) */ - static CreateIcoSphere(name: string, options: { - radius?: number; - flat?: boolean; - subdivisions?: number; - sideOrientation?: number; - updatable?: boolean; - }, scene: Scene): Mesh; + /** - * Creates a decal mesh. - * Please consider using the same method from the MeshBuilder class instead. - * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal. - * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates. - * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates. - * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling. - * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal. + * Last computed particle rotation matrix */ - static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh; + /** - * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. + * Parent particle Id, if any. + * Default null. */ - setPositionsForCPUSkinning(): Float32Array; + parentId: Nullable; /** - * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. + * Internal global position in the SPS. */ - setNormalsForCPUSkinning(): Float32Array; + /** - * Updates the vertex buffer by applying transformation from the bones. - * Returns the Mesh. - * - * @param {skeleton} skeleton to apply + * Creates a Solid Particle object. + * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle() + * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier. + * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array. + * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array. + * @param model (ModelShape) is a reference to the model shape on what the particle is designed. + * @param shapeId (integer) is the model shape identifier in the SPS. + * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30)) + * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations. */ - applySkeleton(skeleton: Skeleton): Mesh; + constructor(particleIndex: number, positionIndex: number, indiceIndex: number, model: Nullable, shapeId: number, idxInShape: number, sps: SolidParticleSystem, modelBoundingInfo?: Nullable); /** - * Returns an object `{min:` Vector3`, max:` Vector3`}` - * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system + * Legacy support, changed scale to scaling */ - static MinMax(meshes: AbstractMesh[]): { - min: Vector3; - max: Vector3; - }; /** - * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array. + * Legacy support, changed scale to scaling + */ + scale: Vector3; + /** + * Legacy support, changed quaternion to rotationQuaternion */ - static Center(meshesOrMinMaxVector: { - min: Vector3; - max: Vector3; - } | AbstractMesh[]): Vector3; /** - * Merge the array of meshes into a single mesh for performance reasons. - * @param {Array} meshes - The vertices source. They should all be of the same material. Entries can empty - * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes - * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true. - * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class. - * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source. + * Legacy support, changed quaternion to rotationQuaternion + */ + quaternion: Nullable; + /** + * Returns a boolean. True if the particle intersects another particle or another mesh, else false. + * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB) + * @param target is the object (solid particle or mesh) what the intersection is computed against. + * @returns true if it intersects */ - static MergeMeshes(meshes: Array, disposeSource?: boolean, allow32BitsIndices?: boolean, meshSubclass?: Mesh, subdivideWithSubMeshes?: boolean): Nullable; - } -} - -declare module BABYLON { - /** - * Define an interface for all classes that will get and set the data on vertices - */ - interface IGetSetVerticesData { - isVerticesDataPresent(kind: string): boolean; - getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable; - getIndices(copyWhenShared?: boolean): Nullable; - setVerticesData(kind: string, data: FloatArray, updatable: boolean): void; - updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): void; - setIndices(indices: IndicesArray, totalVertices: Nullable, updatable?: boolean): void; + intersectsMesh(target: Mesh | SolidParticle): boolean; } /** - * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance + * Represents the shape of the model used by one particle of a solid particle system. + * SPS internal tool, don't use it manually. */ - class VertexData { + class ModelShape { /** - * An array of the x, y, z position of each vertex [...., x, y, z, .....] + * The shape id. */ - positions: Nullable; + shapeID: number; /** - * An array of the x, y, z normal vector of each vertex [...., x, y, z, .....] + * flat array of model positions (internal use) */ - normals: Nullable; + /** - * An array of the x, y, z tangent vector of each vertex [...., x, y, z, .....] + * flat array of model UVs (internal use) */ - tangents: Nullable; + /** - * An array of u,v which maps a texture image onto each vertex [...., u, v, .....] + * length of the shape in the model indices array (internal use) */ - uvs: Nullable; + /** - * A second array of u,v which maps a texture image onto each vertex [...., u, v, .....] + * Custom position function (internal use) */ - uvs2: Nullable; + /** - * A third array of u,v which maps a texture image onto each vertex [...., u, v, .....] + * Custom vertex function (internal use) */ - uvs3: Nullable; + /** - * A fourth array of u,v which maps a texture image onto each vertex [...., u, v, .....] + * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS. + * SPS internal tool, don't use it manually. + * @hidden */ - uvs4: Nullable; + constructor(id: number, shape: Vector3[], indicesLength: number, shapeUV: number[], posFunction: Nullable<(particle: SolidParticle, i: number, s: number) => void>, vtxFunction: Nullable<(particle: SolidParticle, vertex: Vector3, i: number) => void>); + } + /** + * Represents a Depth Sorted Particle in the solid particle system. + */ + class DepthSortedParticle { /** - * A fifth array of u,v which maps a texture image onto each vertex [...., u, v, .....] + * Index of the particle in the "indices" array */ - uvs5: Nullable; + ind: number; /** - * A sixth array of u,v which maps a texture image onto each vertex [...., u, v, .....] + * Length of the particle shape in the "indices" array */ - uvs6: Nullable; + indicesLength: number; /** - * An array of the r, g, b, a, color of each vertex [...., r, g, b, a, .....] + * Squared distance from the particle to the camera */ - colors: Nullable; + sqDistance: number; + } +} + +declare module BABYLON { + /** + * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh. + *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc. + + * The SPS is also a particle system. It provides some methods to manage the particles. + * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior. + * + * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System + */ + class SolidParticleSystem implements IDisposable { /** - * An array containing the list of indices to the array of matrices produced by bones, each vertex have up to 4 indices (8 if the matricesIndicesExtra is set). + * The SPS array of Solid Particle objects. Just access each particle as with any classic array. + * Example : var p = SPS.particles[i]; */ - matricesIndices: Nullable; + particles: SolidParticle[]; /** - * An array containing the list of weights defining the weight of each indexed matrix in the final computation + * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value. */ - matricesWeights: Nullable; + nbParticles: number; /** - * An array extending the number of possible indices + * If the particles must ever face the camera (default false). Useful for planar particles. */ - matricesIndicesExtra: Nullable; + billboard: boolean; /** - * An array extending the number of possible weights when the number of indices is extended + * Recompute normals when adding a shape */ - matricesWeightsExtra: Nullable; + recomputeNormals: boolean; /** - * An array of i, j, k the three vertex indices required for each triangular facet [...., i, j, k .....] + * This a counter ofr your own usage. It's not set by any SPS functions. */ - indices: Nullable; + counter: number; /** - * Uses the passed data array to set the set the values for the specified kind of data - * @param data a linear array of floating numbers - * @param kind the type of data that is being set, eg positions, colors etc + * The SPS name. This name is also given to the underlying mesh. */ - set(data: FloatArray, kind: string): void; + name: string; /** - * Associates the vertexData to the passed Mesh. - * Sets it as updatable or not (default `false`) - * @param mesh the mesh the vertexData is applied to - * @param updatable when used and having the value true allows new data to update the vertexData - * @returns the VertexData + * The SPS mesh. It's a standard BJS Mesh, so all the methods from the Mesh class are avalaible. */ - applyToMesh(mesh: Mesh, updatable?: boolean): VertexData; + mesh: Mesh; /** - * Associates the vertexData to the passed Geometry. - * Sets it as updatable or not (default `false`) - * @param geometry the geometry the vertexData is applied to - * @param updatable when used and having the value true allows new data to update the vertexData - * @returns VertexData + * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity. + * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns */ - applyToGeometry(geometry: Geometry, updatable?: boolean): VertexData; + vars: any; /** - * Updates the associated mesh - * @param mesh the mesh to be updated - * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false - * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false - * @returns VertexData + * This array is populated when the SPS is set as 'pickable'. + * Each key of this array is a `faceId` value that you can get from a pickResult object. + * Each element of this array is an object `{idx: int, faceId: int}`. + * `idx` is the picked particle index in the `SPS.particles` array + * `faceId` is the picked face index counted within this particle. + * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#pickable-particles */ - updateMesh(mesh: Mesh, updateExtends?: boolean, makeItUnique?: boolean): VertexData; + pickedParticles: { + idx: number; + faceId: number; + }[]; /** - * Updates the associated geometry - * @param geometry the geometry to be updated - * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false - * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false - * @returns VertexData. + * This array is populated when `enableDepthSort` is set to true. + * Each element of this array is an instance of the class DepthSortedParticle. */ - updateGeometry(geometry: Geometry, updateExtends?: boolean, makeItUnique?: boolean): VertexData; - private _applyTo(meshOrGeometry, updatable?); - private _update(meshOrGeometry, updateExtends?, makeItUnique?); + depthSortedParticles: DepthSortedParticle[]; /** - * Transforms each position and each normal of the vertexData according to the passed Matrix - * @param matrix the transforming matrix - * @returns the VertexData + * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only) */ - transform(matrix: Matrix): VertexData; + /** - * Merges the passed VertexData into the current one - * @param other the VertexData to be merged into the current one - * @returns the modified VertexData + * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only) */ - merge(other: VertexData): VertexData; - private _mergeElement(source, other); - private _validate(); + + private _scene; + private _positions; + private _indices; + private _normals; + private _colors; + private _uvs; + private _indices32; + private _positions32; + private _normals32; + private _fixedNormal32; + private _colors32; + private _uvs32; + private _index; + private _updatable; + private _pickable; + private _isVisibilityBoxLocked; + private _alwaysVisible; + private _depthSort; + private _shapeCounter; + private _copy; + private _shape; + private _shapeUV; + private _color; + private _computeParticleColor; + private _computeParticleTexture; + private _computeParticleRotation; + private _computeParticleVertex; + private _computeBoundingBox; + private _depthSortParticles; + private _cam_axisZ; + private _cam_axisY; + private _cam_axisX; + private _axisZ; + private _camera; + private _particle; + private _camDir; + private _camInvertedPosition; + private _rotMatrix; + private _invertMatrix; + private _rotated; + private _quaternion; + private _vertex; + private _normal; + private _yaw; + private _pitch; + private _roll; + private _halfroll; + private _halfpitch; + private _halfyaw; + private _sinRoll; + private _cosRoll; + private _sinPitch; + private _cosPitch; + private _sinYaw; + private _cosYaw; + private _mustUnrotateFixedNormals; + private _minimum; + private _maximum; + private _minBbox; + private _maxBbox; + private _particlesIntersect; + private _depthSortFunction; + private _needs32Bits; + private _pivotBackTranslation; + private _scaledPivot; + private _particleHasParent; + private _parent; /** - * Serializes the VertexData - * @returns a serialized object + * Creates a SPS (Solid Particle System) object. + * @param name (String) is the SPS name, this will be the underlying mesh name. + * @param scene (Scene) is the scene in which the SPS is added. + * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable. + * @param isPickable (optional boolean, default false) : if the solid particles must be pickable. + * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera. + * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed. + * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). + * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance. + * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh. */ - serialize(): any; + constructor(name: string, scene: Scene, options?: { + updatable?: boolean; + isPickable?: boolean; + enableDepthSort?: boolean; + particleIntersection?: boolean; + boundingSphereOnly?: boolean; + bSphereRadiusFactor?: number; + }); /** - * Extracts the vertexData from a mesh - * @param mesh the mesh from which to extract the VertexData - * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false - * @param forceCopy indicating that the VertexData must be cloned, optional, default false - * @returns the object VertexData associated to the passed mesh + * Builds the SPS underlying mesh. Returns a standard Mesh. + * If no model shape was added to the SPS, the returned mesh is just a single triangular plane. + * @returns the created mesh */ - static ExtractFromMesh(mesh: Mesh, copyWhenShared?: boolean, forceCopy?: boolean): VertexData; + buildMesh(): Mesh; /** - * Extracts the vertexData from the geometry - * @param geometry the geometry from which to extract the VertexData - * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false - * @param forceCopy indicating that the VertexData must be cloned, optional, default false - * @returns the object VertexData associated to the passed mesh + * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS. + * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places. + * Thus the particles generated from `digest()` have their property `position` set yet. + * @param mesh ( Mesh ) is the mesh to be digested + * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any + * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets + * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets + * @returns the current SPS */ - static ExtractFromGeometry(geometry: Geometry, copyWhenShared?: boolean, forceCopy?: boolean): VertexData; - private static _ExtractFrom(meshOrGeometry, copyWhenShared?, forceCopy?); + digest(mesh: Mesh, options?: { + facetNb?: number; + number?: number; + delta?: number; + }): SolidParticleSystem; + private _unrotateFixedNormals; + private _resetCopy; + private _meshBuilder; + private _posToShape; + private _uvsToShapeUV; + private _addParticle; /** - * Creates the VertexData for a Ribbon - * @param options an object used to set the following optional parameters for the ribbon, required but can be empty - * * pathArray array of paths, each of which an array of successive Vector3 - * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false - * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false - * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false - * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional - * * colors a linear array, of length 4 * number of vertices, of custom color values, optional - * @returns the VertexData of the ribbon + * Adds some particles to the SPS from the model shape. Returns the shape id. + * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps + * @param mesh is any Mesh object that will be used as a model for the solid particles. + * @param nb (positive integer) the number of particles to be created from this model + * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation. + * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation + * @returns the number of shapes in the system */ - static CreateRibbon(options: { - pathArray: Vector3[][]; - closeArray?: boolean; - closePath?: boolean; - offset?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - invertUV?: boolean; - uvs?: Vector2[]; - colors?: Color4[]; - }): VertexData; + addShape(mesh: Mesh, nb: number, options?: { + positionFunction?: any; + vertexFunction?: any; + }): number; + private _rebuildParticle; /** - * Creates the VertexData for a box - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * size sets the width, height and depth of the box to the value of size, optional default 1 - * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size - * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size - * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size - * * faceUV an array of 6 Vector4 elements used to set different images to each box side - * * faceColors an array of 6 Color3 elements used to set different colors to each box side - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the box + * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed. + * @returns the SPS. */ - static CreateBox(options: { - size?: number; - width?: number; - height?: number; - depth?: number; - faceUV?: Vector4[]; - faceColors?: Color4[]; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + rebuildMesh(): SolidParticleSystem; /** - * Creates the VertexData for an ellipsoid, defaults to a sphere - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * segments sets the number of horizontal strips optional, default 32 - * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1 - * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter - * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter - * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter - * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1 - * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1 - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the ellipsoid + * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc. + * This method calls `updateParticle()` for each particle of the SPS. + * For an animated SPS, it is usually called within the render loop. + * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_ + * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_ + * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_ + * @returns the SPS. */ - static CreateSphere(options: { - segments?: number; - diameter?: number; - diameterX?: number; - diameterY?: number; - diameterZ?: number; - arc?: number; - slice?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + setParticles(start?: number, end?: number, update?: boolean): SolidParticleSystem; + private _quaternionRotationYPR; + private _quaternionToRotationMatrix; /** - * Creates the VertexData for a cylinder, cone or prism - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * height sets the height (y direction) of the cylinder, optional, default 2 - * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter - * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter - * * diameter sets the diameter of the top and bottom of the cone, optional default 1 - * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 - * * subdivisions` the number of rings along the cylinder height, optional, default 1 - * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1 - * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively - * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively - * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false - * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the cylinder, cone or prism - */ - static CreateCylinder(options: { - height?: number; - diameterTop?: number; - diameterBottom?: number; - diameter?: number; - tessellation?: number; - subdivisions?: number; - arc?: number; - faceColors?: Color4[]; - faceUV?: Vector4[]; - hasRings?: boolean; - enclose?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + * Disposes the SPS. + */ + dispose(): void; /** - * Creates the VertexData for a torus - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * diameter the diameter of the torus, optional default 1 - * * thickness the diameter of the tube forming the torus, optional default 0.5 - * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the torus + * Visibilty helper : Recomputes the visible size according to the mesh bounding box + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + * @returns the SPS. */ - static CreateTorus(options: { - diameter?: number; - thickness?: number; - tessellation?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + refreshVisibleSize(): SolidParticleSystem; /** - * Creates the VertexData of the LineSystem - * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty - * - lines an array of lines, each line being an array of successive Vector3 - * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point - * @returns the VertexData of the LineSystem + * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box. + * @param size the size (float) of the visibility box + * note : this doesn't lock the SPS mesh bounding box. + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility */ - static CreateLineSystem(options: { - lines: Vector3[][]; - colors?: Nullable; - }): VertexData; + setVisibilityBox(size: number): void; /** - * Create the VertexData for a DashedLines - * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty - * - points an array successive Vector3 - * - dashSize the size of the dashes relative to the dash number, optional, default 3 - * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1 - * - dashNb the intended total number of dashes, optional, default 200 - * @returns the VertexData for the DashedLines + * Gets whether the SPS as always visible or not + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility */ - static CreateDashedLines(options: { - points: Vector3[]; - dashSize?: number; - gapSize?: number; - dashNb?: number; - }): VertexData; /** - * Creates the VertexData for a Ground - * @param options an object used to set the following optional parameters for the Ground, required but can be empty - * - width the width (x direction) of the ground, optional, default 1 - * - height the height (z direction) of the ground, optional, default 1 - * - subdivisions the number of subdivisions per side, optional, default 1 - * @returns the VertexData of the Ground + * Sets the SPS as always visible or not + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + */ + isAlwaysVisible: boolean; + /** + * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates. + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility */ - static CreateGround(options: { - width?: number; - height?: number; - subdivisions?: number; - subdivisionsX?: number; - subdivisionsY?: number; - }): VertexData; /** - * Creates the VertexData for a TiledGround by subdividing the ground into tiles - * @param options an object used to set the following optional parameters for the Ground, required but can be empty - * * xmin the ground minimum X coordinate, optional, default -1 - * * zmin the ground minimum Z coordinate, optional, default -1 - * * xmax the ground maximum X coordinate, optional, default 1 - * * zmax the ground maximum Z coordinate, optional, default 1 - * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6} - * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2} - * @returns the VertexData of the TiledGround + * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates. + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + */ + isVisibilityBoxLocked: boolean; + /** + * Tells to `setParticles()` to compute the particle rotations or not. + * Default value : true. The SPS is faster when it's set to false. + * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate. */ - static CreateTiledGround(options: { - xmin: number; - zmin: number; - xmax: number; - zmax: number; - subdivisions?: { - w: number; - h: number; - }; - precision?: { - w: number; - h: number; - }; - }): VertexData; /** - * Creates the VertexData of the Ground designed from a heightmap - * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap - * * width the width (x direction) of the ground - * * height the height (z direction) of the ground - * * subdivisions the number of subdivisions per side - * * minHeight the minimum altitude on the ground, optional, default 0 - * * maxHeight the maximum altitude on the ground, optional default 1 - * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11) - * * buffer the array holding the image color data - * * bufferWidth the width of image - * * bufferHeight the height of image - * @returns the VertexData of the Ground designed from a heightmap + * Gets if `setParticles()` computes the particle rotations or not. + * Default value : true. The SPS is faster when it's set to false. + * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate. + */ + computeParticleRotation: boolean; + /** + * Tells to `setParticles()` to compute the particle colors or not. + * Default value : true. The SPS is faster when it's set to false. + * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set. */ - static CreateGroundFromHeightMap(options: { - width: number; - height: number; - subdivisions: number; - minHeight: number; - maxHeight: number; - colorFilter: Color3; - buffer: Uint8Array; - bufferWidth: number; - bufferHeight: number; - }): VertexData; /** - * Creates the VertexData for a Plane - * @param options an object used to set the following optional parameters for the plane, required but can be empty - * * size sets the width and height of the plane to the value of size, optional default 1 - * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size - * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the box + * Gets if `setParticles()` computes the particle colors or not. + * Default value : true. The SPS is faster when it's set to false. + * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set. + */ + computeParticleColor: boolean; + /** + * Gets if `setParticles()` computes the particle textures or not. + * Default value : true. The SPS is faster when it's set to false. + * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set. + */ + computeParticleTexture: boolean; + /** + * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not. + * Default value : false. The SPS is faster when it's set to false. + * Note : the particle custom vertex positions aren't stored values. */ - static CreatePlane(options: { - size?: number; - width?: number; - height?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; /** - * Creates the VertexData of the Disc or regular Polygon - * @param options an object used to set the following optional parameters for the disc, required but can be empty - * * radius the radius of the disc, optional default 0.5 - * * tessellation the number of polygon sides, optional, default 64 - * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1 - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the box + * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not. + * Default value : false. The SPS is faster when it's set to false. + * Note : the particle custom vertex positions aren't stored values. + */ + computeParticleVertex: boolean; + /** + * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions. */ - static CreateDisc(options: { - radius?: number; - tessellation?: number; - arc?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; /** - * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build() - * All parameters are provided by MeshBuilder.CreatePolygon as needed - * @param polygon a mesh built from polygonTriangulation.build() - * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively - * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively - * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the Polygon + * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions. + */ + computeBoundingBox: boolean; + /** + * Tells to `setParticles()` to sort or not the distance between each particle and the camera. + * Skipped when `enableDepthSort` is set to `false` (default) at construction time. + * Default : `true` */ - static CreatePolygon(polygon: Mesh, sideOrientation: number, fUV?: Vector4[], fColors?: Color4[], frontUVs?: Vector4, backUVs?: Vector4): VertexData; /** - * Creates the VertexData of the IcoSphere - * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty - * * radius the radius of the IcoSphere, optional default 1 - * * radiusX allows stretching in the x direction, optional, default radius - * * radiusY allows stretching in the y direction, optional, default radius - * * radiusZ allows stretching in the z direction, optional, default radius - * * flat when true creates a flat shaded mesh, optional, default true - * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the IcoSphere + * Gets if `setParticles()` sorts or not the distance between each particle and the camera. + * Skipped when `enableDepthSort` is set to `false` (default) at construction time. + * Default : `true` + */ + depthSortParticles: boolean; + /** + * This function does nothing. It may be overwritten to set all the particle first values. + * The SPS doesn't call this function, you may have to call it by your own. + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management */ - static CreateIcoSphere(options: { - radius?: number; - radiusX?: number; - radiusY?: number; - radiusZ?: number; - flat?: boolean; - subdivisions?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + initParticles(): void; /** - * Creates the VertexData for a Polyhedron - * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty - * * type provided types are: - * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1) - * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20) - * * size the size of the IcoSphere, optional default 1 - * * sizeX allows stretching in the x direction, optional, default size - * * sizeY allows stretching in the y direction, optional, default size - * * sizeZ allows stretching in the z direction, optional, default size - * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor - * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively - * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively - * * flat when true creates a flat shaded mesh, optional, default true - * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the Polyhedron + * This function does nothing. It may be overwritten to recycle a particle. + * The SPS doesn't call this function, you may have to call it by your own. + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management + * @param particle The particle to recycle + * @returns the recycled particle */ - static CreatePolyhedron(options: { - type?: number; - size?: number; - sizeX?: number; - sizeY?: number; - sizeZ?: number; - custom?: any; - faceUV?: Vector4[]; - faceColors?: Color4[]; - flat?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + recycleParticle(particle: SolidParticle): SolidParticle; /** - * Creates the VertexData for a TorusKnot - * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty - * * radius the radius of the torus knot, optional, default 2 - * * tube the thickness of the tube, optional, default 0.5 - * * radialSegments the number of sides on each tube segments, optional, default 32 - * * tubularSegments the number of tubes to decompose the knot into, optional, default 32 - * * p the number of windings around the z axis, optional, default 2 - * * q the number of windings around the x axis, optional, default 3 - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the Torus Knot + * Updates a particle : this function should be overwritten by the user. + * It is called on each particle by `setParticles()`. This is the place to code each particle behavior. + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management + * @example : just set a particle position or velocity and recycle conditions + * @param particle The particle to update + * @returns the updated particle */ - static CreateTorusKnot(options: { - radius?: number; - tube?: number; - radialSegments?: number; - tubularSegments?: number; - p?: number; - q?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + updateParticle(particle: SolidParticle): SolidParticle; /** - * Compute normals for given positions and indices - * @param positions an array of vertex positions, [...., x, y, z, ......] - * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......] - * @param normals an array of vertex normals, [...., x, y, z, ......] - * @param options an object used to set the following optional parameters for the TorusKnot, optional - * * facetNormals : optional array of facet normals (vector3) - * * facetPositions : optional array of facet positions (vector3) - * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation - * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation - * * bInfo : optional bounding info, required for facetPartitioning computation - * * bbSize : optional bounding box size data, required for facetPartitioning computation - * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation - * * useRightHandedSystem: optional boolean to for right handed system computation - * * depthSort : optional boolean to enable the facet depth sort computation - * * distanceTo : optional Vector3 to compute the facet depth from this location - * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location + * Updates a vertex of a particle : it can be overwritten by the user. + * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only. + * @param particle the current particle + * @param vertex the current index of the current particle + * @param pt the index of the current vertex in the particle shape + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape + * @example : just set a vertex particle position + * @returns the updated vertex */ - static ComputeNormals(positions: any, indices: any, normals: any, options?: { - facetNormals?: any; - facetPositions?: any; - facetPartitioning?: any; - ratio?: number; - bInfo?: any; - bbSize?: Vector3; - subDiv?: any; - useRightHandedSystem?: boolean; - depthSort?: boolean; - distanceTo?: Vector3; - depthSortedFacets?: any; - }): void; - private static _ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs?, backUVs?); + updateParticleVertex(particle: SolidParticle, vertex: Vector3, pt: number): Vector3; /** - * Applies VertexData created from the imported parameters to the geometry - * @param parsedVertexData the parsed data from an imported file - * @param geometry the geometry to apply the VertexData to + * This will be called before any other treatment by `setParticles()` and will be passed three parameters. + * This does nothing and may be overwritten by the user. + * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() + * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() + * @param update the boolean update value actually passed to setParticles() */ - static ImportVertexData(parsedVertexData: any, geometry: Geometry): void; + beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void; + /** + * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update. + * This will be passed three parameters. + * This does nothing and may be overwritten by the user. + * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() + * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() + * @param update the boolean update value actually passed to setParticles() + */ + afterUpdateParticles(start?: number, stop?: number, update?: boolean): void; } } declare module BABYLON { - /** - * Class containing static functions to help procedurally build meshes - */ - class MeshBuilder { - private static updateSideOrientation(orientation?); + interface PhysicsImpostorJoint { + mainImpostor: PhysicsImpostor; + connectedImpostor: PhysicsImpostor; + joint: PhysicsJoint; + } + class PhysicsEngine { + private _physicsPlugin; + gravity: Vector3; + constructor(gravity: Nullable, _physicsPlugin?: IPhysicsEnginePlugin); + setGravity(gravity: Vector3): void; /** - * Creates a box mesh - * * The parameter `size` sets the size (float) of each box side (default 1) - * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`) - * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements) - * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the box mesh + * Set the time step of the physics engine. + * default is 1/60. + * To slow it down, enter 1/600 for example. + * To speed it up, 1/30 + * @param {number} newTimeStep the new timestep to apply to this world. */ - static CreateBox(name: string, options: { - size?: number; - width?: number; - height?: number; - depth?: number; - faceUV?: Vector4[]; - faceColors?: Color4[]; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - updatable?: boolean; - }, scene?: Nullable): Mesh; + setTimeStep(newTimeStep?: number): void; /** - * Creates a sphere mesh - * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1) - * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`) - * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32) - * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio - * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude) - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the sphere mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere + * Get the time step of the physics engine. */ - static CreateSphere(name: string, options: { - segments?: number; - diameter?: number; - diameterX?: number; - diameterY?: number; - diameterZ?: number; - arc?: number; - slice?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - updatable?: boolean; - }, scene: any): Mesh; + getTimeStep(): number; + dispose(): void; + getPhysicsPluginName(): string; + static Epsilon: number; + private _impostors; + private _joints; /** - * Creates a plane polygonal mesh. By default, this is a disc - * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5) - * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc - * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the plane polygonal mesh - * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon + * Adding a new impostor for the impostor tracking. + * This will be done by the impostor itself. + * @param {PhysicsImpostor} impostor the impostor to add */ - static CreateDisc(name: string, options: { - radius?: number; - tessellation?: number; - arc?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene?: Nullable): Mesh; + addImpostor(impostor: PhysicsImpostor): void; /** - * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided - * * The parameter `radius` sets the radius size (float) of the icosphere (default 1) - * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`) - * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size - * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the icosahedron mesh - * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere + * Remove an impostor from the engine. + * This impostor and its mesh will not longer be updated by the physics engine. + * @param {PhysicsImpostor} impostor the impostor to remove */ - static CreateIcoSphere(name: string, options: { - radius?: number; - radiusX?: number; - radiusY?: number; - radiusZ?: number; - flat?: boolean; - subdivisions?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - updatable?: boolean; - }, scene: Scene): Mesh; + removeImpostor(impostor: PhysicsImpostor): void; /** - * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters - * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry - * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array - * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array - * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path - * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11 - * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture - * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones - * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values - * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry - * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the ribbon mesh - * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial - * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes + * Add a joint to the physics engine + * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added. + * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint + * @param {PhysicsJoint} the joint that will connect both impostors. */ - static CreateRibbon(name: string, options: { - pathArray: Vector3[][]; - closeArray?: boolean; - closePath?: boolean; - offset?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - instance?: Mesh; - invertUV?: boolean; - uvs?: Vector2[]; - colors?: Color4[]; - }, scene?: Nullable): Mesh; + addJoint(mainImpostor: PhysicsImpostor, connectedImpostor: PhysicsImpostor, joint: PhysicsJoint): void; + removeJoint(mainImpostor: PhysicsImpostor, connectedImpostor: PhysicsImpostor, joint: PhysicsJoint): void; + /** + * Called by the scene. no need to call it. + */ + + getPhysicsPlugin(): IPhysicsEnginePlugin; + getImpostors(): Array; + getImpostorForPhysicsObject(object: IPhysicsEnabledObject): Nullable; + getImpostorWithPhysicsBody(body: any): Nullable; + } + interface IPhysicsEnginePlugin { + world: any; + name: string; + setGravity(gravity: Vector3): void; + setTimeStep(timeStep: number): void; + getTimeStep(): number; + executeStep(delta: number, impostors: Array): void; + applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3): void; + applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3): void; + generatePhysicsBody(impostor: PhysicsImpostor): void; + removePhysicsBody(impostor: PhysicsImpostor): void; + generateJoint(joint: PhysicsImpostorJoint): void; + removeJoint(joint: PhysicsImpostorJoint): void; + isSupported(): boolean; + setTransformationFromPhysicsBody(impostor: PhysicsImpostor): void; + setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion): void; + setLinearVelocity(impostor: PhysicsImpostor, velocity: Nullable): void; + setAngularVelocity(impostor: PhysicsImpostor, velocity: Nullable): void; + getLinearVelocity(impostor: PhysicsImpostor): Nullable; + getAngularVelocity(impostor: PhysicsImpostor): Nullable; + setBodyMass(impostor: PhysicsImpostor, mass: number): void; + getBodyMass(impostor: PhysicsImpostor): number; + getBodyFriction(impostor: PhysicsImpostor): number; + setBodyFriction(impostor: PhysicsImpostor, friction: number): void; + getBodyRestitution(impostor: PhysicsImpostor): number; + setBodyRestitution(impostor: PhysicsImpostor, restitution: number): void; + sleepBody(impostor: PhysicsImpostor): void; + wakeUpBody(impostor: PhysicsImpostor): void; + updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number): void; + setMotor(joint: IMotorEnabledJoint, speed: number, maxForce?: number, motorIndex?: number): void; + setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number, motorIndex?: number): void; + getRadius(impostor: PhysicsImpostor): number; + getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void; + syncMeshWithImpostor(mesh: AbstractMesh, impostor: PhysicsImpostor): void; + dispose(): void; + } +} + +declare module BABYLON { + class PhysicsHelper { + private _scene; + private _physicsEngine; + constructor(scene: Scene); /** - * Creates a cylinder or a cone mesh - * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2). - * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1). - * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero. - * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance. - * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1). - * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces. - * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis. - * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder. - * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements). - * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3 - * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7 - * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17 - * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface. - * * If `enclose` is false, a ring surface is one element. - * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces. - * * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379 - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the cylinder mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone + * @param {Vector3} origin the origin of the explosion + * @param {number} radius the explosion radius + * @param {number} strength the explosion strength + * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant */ - static CreateCylinder(name: string, options: { - height?: number; - diameterTop?: number; - diameterBottom?: number; - diameter?: number; - tessellation?: number; - subdivisions?: number; - arc?: number; - faceColors?: Color4[]; - faceUV?: Vector4[]; - updatable?: boolean; - hasRings?: boolean; - enclose?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene: any): Mesh; + applyRadialExplosionImpulse(origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff): Nullable; /** - * Creates a torus mesh - * * The parameter `diameter` sets the diameter size (float) of the torus (default 1) - * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5) - * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16) - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the torus mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus + * @param {Vector3} origin the origin of the explosion + * @param {number} radius the explosion radius + * @param {number} strength the explosion strength + * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant */ - static CreateTorus(name: string, options: { - diameter?: number; - thickness?: number; - tessellation?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene: any): Mesh; + applyRadialExplosionForce(origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff): Nullable; /** - * Creates a torus knot mesh - * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2) - * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32) - * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32) - * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3) - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the torus knot mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot + * @param {Vector3} origin the origin of the explosion + * @param {number} radius the explosion radius + * @param {number} strength the explosion strength + * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant */ - static CreateTorusKnot(name: string, options: { - radius?: number; - tube?: number; - radialSegments?: number; - tubularSegments?: number; - p?: number; - q?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene: any): Mesh; + gravitationalField(origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff): Nullable; /** - * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh - * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter - * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function - * * The parameter `lines` is an array of lines, each line being an array of successive Vector3 - * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter - * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point - * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster) - * * Updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines - * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system - * @param name defines the name of the new line system - * @param options defines the options used to create the line system - * @param scene defines the hosting scene - * @returns a new line system mesh + * @param {Vector3} origin the origin of the updraft + * @param {number} radius the radius of the updraft + * @param {number} strength the strength of the updraft + * @param {number} height the height of the updraft + * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center */ - static CreateLineSystem(name: string, options: { - lines: Vector3[][]; - updatable?: boolean; - instance?: Nullable; - colors?: Nullable; - useVertexAlpha?: boolean; - }, scene: Nullable): LinesMesh; + updraft(origin: Vector3, radius: number, strength: number, height: number, updraftMode?: PhysicsUpdraftMode): Nullable; /** - * Creates a line mesh - * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter - * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function - * * The parameter `points` is an array successive Vector3 - * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines - * * The optional parameter `colors` is an array of successive Color4, one per line point - * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster) - * * When updating an instance, remember that only point positions can change, not the number of points - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines - * @param name defines the name of the new line system - * @param options defines the options used to create the line system - * @param scene defines the hosting scene - * @returns a new line mesh + * @param {Vector3} origin the of the vortex + * @param {number} radius the radius of the vortex + * @param {number} strength the strength of the vortex + * @param {number} height the height of the vortex */ - static CreateLines(name: string, options: { - points: Vector3[]; - updatable?: boolean; - instance?: Nullable; - colors?: Color4[]; - useVertexAlpha?: boolean; - }, scene?: Nullable): LinesMesh; + vortex(origin: Vector3, radius: number, strength: number, height: number): Nullable; + } + /***** Radial explosion *****/ + class PhysicsRadialExplosionEvent { + private _scene; + private _sphere; + private _sphereOptions; + private _rays; + private _dataFetched; + constructor(scene: Scene); /** - * Creates a dashed line mesh - * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter - * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function - * * The parameter `points` is an array successive Vector3 - * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200) - * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3) - * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1) - * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines - * * When updating an instance, remember that only point positions can change, not the number of points - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the dashed line mesh - * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines + * Returns the data related to the radial explosion event (sphere & rays). + * @returns {PhysicsRadialExplosionEventData} */ - static CreateDashedLines(name: string, options: { - points: Vector3[]; - dashSize?: number; - gapSize?: number; - dashNb?: number; - updatable?: boolean; - instance?: LinesMesh; - }, scene?: Nullable): LinesMesh; + getData(): PhysicsRadialExplosionEventData; /** - * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. - * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis. - * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. - * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve. - * * The parameter `scale` (float, default 1) is the value to scale the shape. - * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape - * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture. - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the extruded shape mesh - * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes - * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes - * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes + * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse. + * @param impostor + * @param {Vector3} origin the origin of the explosion + * @param {number} radius the explosion radius + * @param {number} strength the explosion strength + * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear + * @returns {Nullable} */ - static ExtrudeShape(name: string, options: { - shape: Vector3[]; - path: Vector3[]; - scale?: number; - rotation?: number; - cap?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - instance?: Mesh; - invertUV?: boolean; - }, scene?: Nullable): Mesh; + getImpostorForceAndContactPoint(impostor: PhysicsImpostor, origin: Vector3, radius: number, strength: number, falloff: PhysicsRadialImpulseFalloff): Nullable; /** - * Creates an custom extruded shape mesh. - * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. - * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis. - * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. - * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path - * * It must returns a float value that will be the rotation in radians applied to the shape on each path point. - * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path - * * It must returns a float value that will be the scale value applied to the shape on each path point - * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray` - * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray` - * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape - * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the custom extruded shape mesh - * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes - * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes - * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes + * Disposes the sphere. + * @param {bolean} force */ - static ExtrudeShapeCustom(name: string, options: { - shape: Vector3[]; - path: Vector3[]; - scaleFunction?: any; - rotationFunction?: any; - ribbonCloseArray?: boolean; - ribbonClosePath?: boolean; - cap?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - instance?: Mesh; - invertUV?: boolean; - }, scene: Scene): Mesh; + dispose(force?: boolean): void; + /*** Helpers ***/ + private _prepareSphere; + private _intersectsWithSphere; + } + /***** Gravitational Field *****/ + class PhysicsGravitationalFieldEvent { + private _physicsHelper; + private _scene; + private _origin; + private _radius; + private _strength; + private _falloff; + private _tickCallback; + private _sphere; + private _dataFetched; + constructor(physicsHelper: PhysicsHelper, scene: Scene, origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff); /** - * Creates lathe mesh. - * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe - * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero - * * The parameter `radius` (positive float, default 1) is the radius value of the lathe - * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe - * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides - * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape - * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc" - * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the lathe mesh - * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe + * Returns the data related to the gravitational field event (sphere). + * @returns {PhysicsGravitationalFieldEventData} */ - static CreateLathe(name: string, options: { - shape: Vector3[]; - radius?: number; - tessellation?: number; - clip?: number; - arc?: number; - closed?: boolean; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - cap?: number; - invertUV?: boolean; - }, scene: Scene): Mesh; + getData(): PhysicsGravitationalFieldEventData; /** - * Creates a plane mesh - * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1) - * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`) - * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the plane mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane + * Enables the gravitational field. */ - static CreatePlane(name: string, options: { - size?: number; - width?: number; - height?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - updatable?: boolean; - sourcePlane?: Plane; - }, scene: Scene): Mesh; + enable(): void; /** - * Creates a ground mesh - * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground - * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the ground mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane + * Disables the gravitational field. */ - static CreateGround(name: string, options: { - width?: number; - height?: number; - subdivisions?: number; - subdivisionsX?: number; - subdivisionsY?: number; - updatable?: boolean; - }, scene: any): Mesh; + disable(): void; /** - * Creates a tiled ground mesh - * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates - * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates - * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile - * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the tiled ground mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground + * Disposes the sphere. + * @param {bolean} force */ - static CreateTiledGround(name: string, options: { - xmin: number; - zmin: number; - xmax: number; - zmax: number; - subdivisions?: { - w: number; - h: number; - }; - precision?: { - w: number; - h: number; - }; - updatable?: boolean; - }, scene: Scene): Mesh; + dispose(force?: boolean): void; + private _tick; + } + /***** Updraft *****/ + class PhysicsUpdraftEvent { + private _scene; + private _origin; + private _radius; + private _strength; + private _height; + private _updraftMode; + private _physicsEngine; + private _originTop; + private _originDirection; + private _tickCallback; + private _cylinder; + private _cylinderPosition; + private _dataFetched; + constructor(_scene: Scene, _origin: Vector3, _radius: number, _strength: number, _height: number, _updraftMode: PhysicsUpdraftMode); /** - * Creates a ground mesh from a height map - * * The parameter `url` sets the URL of the height map image resource. - * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes. - * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side. - * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground. - * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground. - * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height. - * * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time). - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param url defines the url to the height map - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the ground mesh - * @see http://doc.babylonjs.com/babylon101/height_map - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map + * Returns the data related to the updraft event (cylinder). + * @returns {PhysicsUpdraftEventData} */ - static CreateGroundFromHeightMap(name: string, url: string, options: { - width?: number; - height?: number; - subdivisions?: number; - minHeight?: number; - maxHeight?: number; - colorFilter?: Color3; - updatable?: boolean; - onReady?: (mesh: GroundMesh) => void; - }, scene: Scene): GroundMesh; + getData(): PhysicsUpdraftEventData; /** - * Creates a polygon mesh - * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh - * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors - * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4) - * * Remember you can only change the shape positions, not their number when updating a polygon - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the polygon mesh + * Enables the updraft. */ - static CreatePolygon(name: string, options: { - shape: Vector3[]; - holes?: Vector3[][]; - depth?: number; - faceUV?: Vector4[]; - faceColors?: Color4[]; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene: Scene): Mesh; + enable(): void; /** - * Creates an extruded polygon mesh, with depth in the Y direction. - * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements) - * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the polygon mesh + * Disables the cortex. */ - static ExtrudePolygon(name: string, options: { - shape: Vector3[]; - holes?: Vector3[][]; - depth?: number; - faceUV?: Vector4[]; - faceColors?: Color4[]; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene: Scene): Mesh; + disable(): void; + /** + * Disposes the sphere. + * @param {bolean} force + */ + dispose(force?: boolean): void; + private getImpostorForceAndContactPoint; + private _tick; + /*** Helpers ***/ + private _prepareCylinder; + private _intersectsWithCylinder; + } + /***** Vortex *****/ + class PhysicsVortexEvent { + private _scene; + private _origin; + private _radius; + private _strength; + private _height; + private _physicsEngine; + private _originTop; + private _centripetalForceThreshold; + private _updraftMultiplier; + private _tickCallback; + private _cylinder; + private _cylinderPosition; + private _dataFetched; + constructor(_scene: Scene, _origin: Vector3, _radius: number, _strength: number, _height: number); /** - * Creates a tube mesh. - * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters - * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube - * * The parameter `radius` (positive float, default 1) sets the tube radius size - * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface - * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius` - * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float) - * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc - * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the tube mesh - * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube + * Returns the data related to the vortex event (cylinder). + * @returns {PhysicsVortexEventData} */ - static CreateTube(name: string, options: { - path: Vector3[]; - radius?: number; - tessellation?: number; - radiusFunction?: { - (i: number, distance: number): number; - }; - cap?: number; - arc?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - instance?: Mesh; - invertUV?: boolean; - }, scene: Scene): Mesh; + getData(): PhysicsVortexEventData; /** - * Creates a polyhedron mesh - * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type - * * The parameter `size` (positive float, default 1) sets the polygon size - * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value) - * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type` - * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron - * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`) - * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors - * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the polyhedron mesh - * @see http://doc.babylonjs.com/how_to/polyhedra_shapes + * Enables the vortex. */ - static CreatePolyhedron(name: string, options: { - type?: number; - size?: number; - sizeX?: number; - sizeY?: number; - sizeZ?: number; - custom?: any; - faceUV?: Vector4[]; - faceColors?: Color4[]; - flat?: boolean; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene: Scene): Mesh; + enable(): void; /** - * Creates a decal mesh. - * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal - * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates - * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates - * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling - * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal - * @param name defines the name of the mesh - * @param sourceMesh defines the mesh where the decal must be applied - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the decal mesh - * @see http://doc.babylonjs.com/how_to/decals + * Disables the cortex. */ - static CreateDecal(name: string, sourceMesh: AbstractMesh, options: { - position?: Vector3; - normal?: Vector3; - size?: Vector3; - angle?: number; - }): Mesh; - private static _ExtrudeShapeGeneric(name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs); - } -} - -declare module BABYLON { - class MeshLODLevel { - distance: number; - mesh: Nullable; - constructor(distance: number, mesh: Nullable); - } -} - -declare module BABYLON { - /** - * A simplifier interface for future simplification implementations. - */ - interface ISimplifier { + disable(): void; /** - * Simplification of a given mesh according to the given settings. - * Since this requires computation, it is assumed that the function runs async. - * @param settings The settings of the simplification, including quality and distance - * @param successCallback A callback that will be called after the mesh was simplified. - * @param errorCallback in case of an error, this callback will be called. optional. + * Disposes the sphere. + * @param {bolean} force */ - simplify(settings: ISimplificationSettings, successCallback: (simplifiedMeshes: Mesh) => void, errorCallback?: () => void): void; + dispose(force?: boolean): void; + private getImpostorForceAndContactPoint; + private _tick; + /*** Helpers ***/ + private _prepareCylinder; + private _intersectsWithCylinder; } + /***** Enums *****/ /** - * Expected simplification settings. - * Quality should be between 0 and 1 (1 being 100%, 0 being 0%); - */ - interface ISimplificationSettings { - quality: number; - distance: number; - optimizeMesh?: boolean; - } - class SimplificationSettings implements ISimplificationSettings { - quality: number; - distance: number; - optimizeMesh: boolean | undefined; - constructor(quality: number, distance: number, optimizeMesh?: boolean | undefined); - } - interface ISimplificationTask { - settings: Array; - simplificationType: SimplificationType; - mesh: Mesh; - successCallback?: () => void; - parallelProcessing: boolean; - } - class SimplificationQueue { - private _simplificationArray; - running: boolean; - constructor(); - addTask(task: ISimplificationTask): void; - executeNext(): void; - runSimplification(task: ISimplificationTask): void; - private getSimplifier(task); + * The strenght of the force in correspondence to the distance of the affected object + */ + enum PhysicsRadialImpulseFalloff { + /** Defines that impulse is constant in strength across it's whole radius */ + Constant = 0, + /** DEfines that impulse gets weaker if it's further from the origin */ + Linear = 1 } /** - * The implemented types of simplification - * At the moment only Quadratic Error Decimation is implemented + * The strenght of the force in correspondence to the distance of the affected object */ - enum SimplificationType { - /** Quadratic error decimation */ - QUADRATIC = 0, + enum PhysicsUpdraftMode { + /** Defines that the upstream forces will pull towards the top center of the cylinder */ + Center = 0, + /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */ + Perpendicular = 1 } - class DecimationTriangle { - vertices: Array; - normal: Vector3; - error: Array; - deleted: boolean; - isDirty: boolean; - borderFactor: number; - deletePending: boolean; - originalOffset: number; - constructor(vertices: Array); + /***** Data interfaces *****/ + interface PhysicsForceAndContactPoint { + force: Vector3; + contactPoint: Vector3; } - class DecimationVertex { - position: Vector3; - id: number; - q: QuadraticMatrix; - isBorder: boolean; - triangleStart: number; - triangleCount: number; - originalOffsets: Array; - constructor(position: Vector3, id: number); - updatePosition(newPosition: Vector3): void; + interface PhysicsRadialExplosionEventData { + sphere: Mesh; + rays: Array; } - class QuadraticMatrix { - data: Array; - constructor(data?: Array); - det(a11: number, a12: number, a13: number, a21: number, a22: number, a23: number, a31: number, a32: number, a33: number): number; - addInPlace(matrix: QuadraticMatrix): void; - addArrayInPlace(data: Array): void; - add(matrix: QuadraticMatrix): QuadraticMatrix; - static FromData(a: number, b: number, c: number, d: number): QuadraticMatrix; - static DataFromNumbers(a: number, b: number, c: number, d: number): number[]; + interface PhysicsGravitationalFieldEventData { + sphere: Mesh; } - class Reference { - vertexId: number; - triangleId: number; - constructor(vertexId: number, triangleId: number); + interface PhysicsUpdraftEventData { + cylinder: Mesh; } - /** - * An implementation of the Quadratic Error simplification algorithm. - * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf - * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS - * @author RaananW - */ - class QuadraticErrorSimplification implements ISimplifier { - private _mesh; - private triangles; - private vertices; - private references; - private _reconstructedMesh; - syncIterations: number; - aggressiveness: number; - decimationIterations: number; - boundingBoxEpsilon: number; - constructor(_mesh: Mesh); - simplify(settings: ISimplificationSettings, successCallback: (simplifiedMesh: Mesh) => void): void; - private runDecimation(settings, submeshIndex, successCallback); - private initWithMesh(submeshIndex, callback, optimizeMesh?); - private init(callback); - private reconstructMesh(submeshIndex); - private initDecimatedMesh(); - private isFlipped(vertex1, vertex2, point, deletedArray, borderFactor, delTr); - private updateTriangles(origVertex, vertex, deletedArray, deletedTriangles); - private identifyBorder(); - private updateMesh(identifyBorders?); - private vertexError(q, point); - private calculateError(vertex1, vertex2, pointResult?, normalResult?, uvResult?, colorResult?); + interface PhysicsVortexEventData { + cylinder: Mesh; } } declare module BABYLON { - class Polygon { - static Rectangle(xmin: number, ymin: number, xmax: number, ymax: number): Vector2[]; - static Circle(radius: number, cx?: number, cy?: number, numberOfSides?: number): Vector2[]; - static Parse(input: string): Vector2[]; - static StartingAt(x: number, y: number): Path2; - } - class PolygonMeshBuilder { - private _points; - private _outlinepoints; - private _holes; - private _name; - private _scene; - private _epoints; - private _eholes; - private _addToepoint(points); - constructor(name: string, contours: Path2, scene: Scene); - constructor(name: string, contours: Vector2[], scene: Scene); - addHole(hole: Vector2[]): PolygonMeshBuilder; - build(updatable?: boolean, depth?: number): Mesh; - private addSide(positions, normals, uvs, indices, bounds, points, depth, flip); + interface PhysicsImpostorParameters { + mass: number; + friction?: number; + restitution?: number; + nativeOptions?: any; + ignoreParent?: boolean; + disableBidirectionalTransformation?: boolean; } -} - -declare module BABYLON { - class BaseSubMesh { - - - readonly effect: Nullable; - setEffect(effect: Nullable, defines?: Nullable): void; + interface IPhysicsEnabledObject { + position: Vector3; + rotationQuaternion: Nullable; + scaling: Vector3; + rotation?: Vector3; + parent?: any; + getBoundingInfo(): BoundingInfo; + computeWorldMatrix(force: boolean): Matrix; + getWorldMatrix?(): Matrix; + getChildMeshes?(directDescendantsOnly?: boolean): Array; + getVerticesData(kind: string): Nullable | Float32Array>; + getIndices?(): Nullable; + getScene?(): Scene; + getAbsolutePosition(): Vector3; + getAbsolutePivotPoint(): Vector3; + rotate(axis: Vector3, amount: number, space?: Space): TransformNode; + translate(axis: Vector3, distance: number, space?: Space): TransformNode; + setAbsolutePosition(absolutePosition: Vector3): TransformNode; + getClassName(): string; } - class SubMesh extends BaseSubMesh implements ICullable { - materialIndex: number; - verticesStart: number; - verticesCount: number; - indexStart: number; - indexCount: number; - linesIndexCount: number; - private _mesh; - private _renderingMesh; - private _boundingInfo; - private _linesIndexBuffer; - - - - - - + class PhysicsImpostor { + object: IPhysicsEnabledObject; + type: number; + private _options; + private _scene?; + static DEFAULT_OBJECT_SIZE: Vector3; + static IDENTITY_QUATERNION: Quaternion; + private _physicsEngine; + private _physicsBody; + private _bodyUpdateRequired; + private _onBeforePhysicsStepCallbacks; + private _onAfterPhysicsStepCallbacks; + private _onPhysicsCollideCallbacks; + private _deltaPosition; + private _deltaRotation; + private _deltaRotationConjugated; + private _parent; + private _isDisposed; + private static _tmpVecs; + private static _tmpQuat; + readonly isDisposed: boolean; + mass: number; + friction: number; + restitution: number; + uniqueId: number; + private _joints; + constructor(object: IPhysicsEnabledObject, type: number, _options?: PhysicsImpostorParameters, _scene?: Scene | undefined); + /** + * This function will completly initialize this impostor. + * It will create a new body - but only if this mesh has no parent. + * If it has, this impostor will not be used other than to define the impostor + * of the child mesh. + */ - private _currentMaterial; - static AddToMesh(materialIndex: number, verticesStart: number, verticesCount: number, indexStart: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox?: boolean): SubMesh; - constructor(materialIndex: number, verticesStart: number, verticesCount: number, indexStart: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox?: boolean); - readonly IsGlobal: boolean; + private _getPhysicsParent; /** - * Returns the submesh BoudingInfo object. + * Should a new body be generated. */ - getBoundingInfo(): BoundingInfo; + isBodyInitRequired(): boolean; + setScalingUpdated(updated: boolean): void; /** - * Sets the submesh BoundingInfo. - * Return the SubMesh. + * Force a regeneration of this or the parent's impostor's body. + * Use under cautious - This will remove all joints already implemented. */ - setBoundingInfo(boundingInfo: BoundingInfo): SubMesh; + forceUpdate(): void; /** - * Returns the mesh of the current submesh. + * Gets the body that holds this impostor. Either its own, or its parent. */ - getMesh(): AbstractMesh; /** - * Returns the rendering mesh of the submesh. + * Set the physics body. Used mainly by the physics engine/plugin + */ + physicsBody: any; + parent: Nullable; + resetUpdateFlags(): void; + getObjectExtendSize(): Vector3; + getObjectCenter(): Vector3; + /** + * Get a specific parametes from the options parameter. */ - getRenderingMesh(): Mesh; + getParam(paramName: string): any; /** - * Returns the submesh material. + * Sets a specific parameter in the options given to the physics plugin */ - getMaterial(): Nullable; + setParam(paramName: string, value: number): void; /** - * Sets a new updated BoundingInfo object to the submesh. - * Returns the SubMesh. + * Specifically change the body's mass option. Won't recreate the physics body object */ - refreshBoundingInfo(): SubMesh; - + setMass(mass: number): void; + getLinearVelocity(): Nullable; + setLinearVelocity(velocity: Nullable): void; + getAngularVelocity(): Nullable; + setAngularVelocity(velocity: Nullable): void; /** - * Updates the submesh BoundingInfo. - * Returns the Submesh. + * Execute a function with the physics plugin native code. + * Provide a function the will have two variables - the world object and the physics body object. */ - updateBoundingInfo(world: Matrix): SubMesh; + executeNativeFunction(func: (world: any, physicsBody: any) => void): void; /** - * True is the submesh bounding box intersects the frustum defined by the passed array of planes. - * Boolean returned. + * Register a function that will be executed before the physics world is stepping forward. */ - isInFrustum(frustumPlanes: Plane[]): boolean; + registerBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void; + unregisterBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void; /** - * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes. - * Boolean returned. + * Register a function that will be executed after the physics step */ - isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; + registerAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void; + unregisterAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void; + /** + * register a function that will be executed when this impostor collides against a different body. + */ + registerOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor) => void): void; + unregisterOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor | Array) => void): void; + private _tmpQuat; + private _tmpQuat2; + getParentsRotation(): Quaternion; + /** + * this function is executed by the physics engine. + */ + beforeStep: () => void; + /** + * this function is executed by the physics engine. + */ + afterStep: () => void; + /** + * Legacy collision detection event support + */ + onCollideEvent: Nullable<(collider: PhysicsImpostor, collidedWith: PhysicsImpostor) => void>; + onCollide: (e: { + body: any; + }) => void; + /** + * Apply a force + */ + applyForce(force: Vector3, contactPoint: Vector3): PhysicsImpostor; + /** + * Apply an impulse + */ + applyImpulse(force: Vector3, contactPoint: Vector3): PhysicsImpostor; + /** + * A help function to create a joint. + */ + createJoint(otherImpostor: PhysicsImpostor, jointType: number, jointData: PhysicsJointData): PhysicsImpostor; + /** + * Add a joint to this impostor with a different impostor. + */ + addJoint(otherImpostor: PhysicsImpostor, joint: PhysicsJoint): PhysicsImpostor; + /** + * Will keep this body still, in a sleep mode. + */ + sleep(): PhysicsImpostor; + /** + * Wake the body up. + */ + wakeUp(): PhysicsImpostor; + clone(newObject: IPhysicsEnabledObject): Nullable; + dispose(): void; + setDeltaPosition(position: Vector3): void; + setDeltaRotation(rotation: Quaternion): void; + getBoxSizeToRef(result: Vector3): PhysicsImpostor; + getRadius(): number; + /** + * Sync a bone with this impostor + * @param bone The bone to sync to the impostor. + * @param boneMesh The mesh that the bone is influencing. + * @param jointPivot The pivot of the joint / bone in local space. + * @param distToJoint Optional distance from the impostor to the joint. + * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. + */ + syncBoneWithImpostor(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion): void; + /** + * Sync impostor to a bone + * @param bone The bone that the impostor will be synced to. + * @param boneMesh The mesh that the bone is influencing. + * @param jointPivot The pivot of the joint / bone in local space. + * @param distToJoint Optional distance from the impostor to the joint. + * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. + * @param boneAxis Optional vector3 axis the bone is aligned with + */ + syncImpostorWithBone(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion, boneAxis?: Vector3): void; + static NoImpostor: number; + static SphereImpostor: number; + static BoxImpostor: number; + static PlaneImpostor: number; + static MeshImpostor: number; + static CylinderImpostor: number; + static ParticleImpostor: number; + static HeightmapImpostor: number; + } +} + +declare module BABYLON { + interface PhysicsJointData { + mainPivot?: Vector3; + connectedPivot?: Vector3; + mainAxis?: Vector3; + connectedAxis?: Vector3; + collision?: boolean; + nativeParams?: any; + } + /** + * This is a holder class for the physics joint created by the physics plugin. + * It holds a set of functions to control the underlying joint. + */ + class PhysicsJoint { + type: number; + jointData: PhysicsJointData; + private _physicsJoint; + protected _physicsPlugin: IPhysicsEnginePlugin; + constructor(type: number, jointData: PhysicsJointData); + physicsJoint: any; + physicsPlugin: IPhysicsEnginePlugin; + /** + * Execute a function that is physics-plugin specific. + * @param {Function} func the function that will be executed. + * It accepts two parameters: the physics world and the physics joint. + */ + executeNativeFunction(func: (world: any, physicsJoint: any) => void): void; + static DistanceJoint: number; + static HingeJoint: number; + static BallAndSocketJoint: number; + static WheelJoint: number; + static SliderJoint: number; + static PrismaticJoint: number; + static UniversalJoint: number; + static Hinge2Joint: number; + static PointToPointJoint: number; + static SpringJoint: number; + static LockJoint: number; + } + /** + * A class representing a physics distance joint. + */ + class DistanceJoint extends PhysicsJoint { + constructor(jointData: DistanceJointData); /** - * Renders the submesh. - * Returns it. + * Update the predefined distance. */ - render(enableAlphaMode: boolean): SubMesh; + updateDistance(maxDistance: number, minDistance?: number): void; + } + class MotorEnabledJoint extends PhysicsJoint implements IMotorEnabledJoint { + constructor(type: number, jointData: PhysicsJointData); /** - * Returns a new Index Buffer. - * Type returned : WebGLBuffer. + * Set the motor values. + * Attention, this function is plugin specific. Engines won't react 100% the same. + * @param {number} force the force to apply + * @param {number} maxForce max force for this motor. */ - getLinesIndexBuffer(indices: IndicesArray, engine: Engine): WebGLBuffer; + setMotor(force?: number, maxForce?: number): void; /** - * True is the passed Ray intersects the submesh bounding box. - * Boolean returned. + * Set the motor's limits. + * Attention, this function is plugin specific. Engines won't react 100% the same. */ - canIntersects(ray: Ray): boolean; + setLimit(upperLimit: number, lowerLimit?: number): void; + } + /** + * This class represents a single hinge physics joint + */ + class HingeJoint extends MotorEnabledJoint { + constructor(jointData: PhysicsJointData); /** - * Returns an object IntersectionInfo. + * Set the motor values. + * Attention, this function is plugin specific. Engines won't react 100% the same. + * @param {number} force the force to apply + * @param {number} maxForce max force for this motor. */ - intersects(ray: Ray, positions: Vector3[], indices: IndicesArray, fastCheck?: boolean): Nullable; - + setMotor(force?: number, maxForce?: number): void; /** - * Creates a new Submesh from the passed Mesh. + * Set the motor's limits. + * Attention, this function is plugin specific. Engines won't react 100% the same. */ - clone(newMesh: AbstractMesh, newRenderingMesh?: Mesh): SubMesh; + setLimit(upperLimit: number, lowerLimit?: number): void; + } + /** + * This class represents a dual hinge physics joint (same as wheel joint) + */ + class Hinge2Joint extends MotorEnabledJoint { + constructor(jointData: PhysicsJointData); /** - * Disposes the Submesh. - * Returns nothing. + * Set the motor values. + * Attention, this function is plugin specific. Engines won't react 100% the same. + * @param {number} force the force to apply + * @param {number} maxForce max force for this motor. + * @param {motorIndex} the motor's index, 0 or 1. */ - dispose(): void; + setMotor(force?: number, maxForce?: number, motorIndex?: number): void; /** - * Creates a new Submesh from the passed parameters : - * - materialIndex (integer) : the index of the main mesh material. - * - startIndex (integer) : the index where to start the copy in the mesh indices array. - * - indexCount (integer) : the number of indices to copy then from the startIndex. - * - mesh (Mesh) : the main mesh to create the submesh from. - * - renderingMesh (optional Mesh) : rendering mesh. + * Set the motor limits. + * Attention, this function is plugin specific. Engines won't react 100% the same. + * @param {number} upperLimit the upper limit + * @param {number} lowerLimit lower limit + * @param {motorIndex} the motor's index, 0 or 1. */ - static CreateFromIndices(materialIndex: number, startIndex: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh): SubMesh; + setLimit(upperLimit: number, lowerLimit?: number, motorIndex?: number): void; + } + interface IMotorEnabledJoint { + physicsJoint: any; + setMotor(force?: number, maxForce?: number, motorIndex?: number): void; + setLimit(upperLimit: number, lowerLimit?: number, motorIndex?: number): void; + } + interface DistanceJointData extends PhysicsJointData { + maxDistance: number; + } + interface SpringJointData extends PhysicsJointData { + length: number; + stiffness: number; + damping: number; } } declare module BABYLON { - class TransformNode extends Node { - static BILLBOARDMODE_NONE: number; - static BILLBOARDMODE_X: number; - static BILLBOARDMODE_Y: number; - static BILLBOARDMODE_Z: number; - static BILLBOARDMODE_ALL: number; - private _forward; - private _forwardInverted; - private _up; - private _right; - private _rightInverted; - private _rotation; - private _rotationQuaternion; - protected _scaling: Vector3; - protected _isDirty: boolean; - private _transformToBoneReferal; - /** - * Set the billboard mode. Default is 0. - * - * | Value | Type | Description | - * | --- | --- | --- | - * | 0 | BILLBOARDMODE_NONE | | - * | 1 | BILLBOARDMODE_X | | - * | 2 | BILLBOARDMODE_Y | | - * | 4 | BILLBOARDMODE_Z | | - * | 7 | BILLBOARDMODE_ALL | | - * - */ - billboardMode: number; - scalingDeterminant: number; - infiniteDistance: boolean; + class ReflectionProbe { + name: string; + private _scene; + private _renderTargetTexture; + private _projectionMatrix; + private _viewMatrix; + private _target; + private _add; + private _attachedMesh; + private _invertYAxis; + position: Vector3; + constructor(name: string, size: number, scene: Scene, generateMipMaps?: boolean); + samples: number; + refreshRate: number; + getScene(): Scene; + readonly cubeTexture: RenderTargetTexture; + readonly renderList: Nullable; + attachToMesh(mesh: AbstractMesh): void; /** - * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored. - * By default the system will update normals to compensate + * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. + * + * @param renderingGroupId The rendering group id corresponding to its index + * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. */ - ignoreNonUniformScaling: boolean; - position: Vector3; + setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean): void; + dispose(): void; + } +} - private _localWorld; +declare module BABYLON { + interface Scene { + /** @hidden (Backing field) */ + /** @hidden (Backing field) */ - private _absolutePosition; - private _pivotMatrix; - private _pivotMatrixInverse; - private _postMultiplyPivotMatrix; - protected _isWorldMatrixFrozen: boolean; - /** - * An event triggered after the world matrix is updated - */ - onAfterWorldMatrixUpdateObservable: Observable; - constructor(name: string, scene?: Nullable, isPure?: boolean); /** - * Gets a string idenfifying the name of the class - * @returns "TransformNode" string + * Gets or sets a boolean indicating if all bounding boxes must be rendered */ - getClassName(): string; - /** - * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z. - * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector! - * Default : (0.0, 0.0, 0.0) - */ - rotation: Vector3; + forceShowBoundingBoxes: boolean; /** - * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z. - * Default : (1.0, 1.0, 1.0) + * Gets the bounding box renderer associated with the scene + * @returns a BoundingBoxRenderer */ + getBoundingBoxRenderer(): BoundingBoxRenderer; + } + interface AbstractMesh { + /** @hidden (Backing field) */ + /** - * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z. - * Default : (1.0, 1.0, 1.0) - */ - scaling: Vector3; - /** - * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion. - * It's null by default. - * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0) + * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default) */ - rotationQuaternion: Nullable; + showBoundingBox: boolean; + } + class BoundingBoxRenderer implements ISceneComponent { /** - * The forward direction of that transform in world space. + * The component name helpfull to identify the component in the list of scene components. */ - readonly forward: Vector3; + readonly name: string; /** - * The up direction of that transform in world space. + * The scene the component belongs to. */ - readonly up: Vector3; + scene: Scene; + frontColor: Color3; + backColor: Color3; + showBackLines: boolean; + renderList: SmartArray; + private _colorShader; + private _vertexBuffers; + private _indexBuffer; + constructor(scene: Scene); /** - * The right direction of that transform in world space. + * Registers the component in a given scene */ - readonly right: Vector3; + register(): void; + private _evaluateSubMesh; + private _activeMesh; + private _prepareRessources; + private _createIndexBuffer; /** - * Returns the latest update of the World matrix - * Returns a Matrix. + * Rebuilds the elements related to this component in case of + * context lost for instance. */ - getWorldMatrix(): Matrix; - /** @hidden */ + rebuild(): void; + reset(): void; + render(): void; + renderOcclusionBoundingBox(mesh: AbstractMesh): void; + dispose(): void; + } +} +declare module BABYLON { + /** + * This represents a depth renderer in Babylon. + * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing + */ + class DepthRenderer { + private _scene; + private _depthMap; + private _effect; + private _cachedDefines; + private _camera; /** - * Returns directly the latest state of the mesh World matrix. - * A Matrix is returned. + * Instantiates a depth renderer + * @param scene The scene the renderer belongs to + * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT) + * @param camera The camera to be used to render the depth map (default: scene's active camera) */ - readonly worldMatrixFromCache: Matrix; + constructor(scene: Scene, type?: number, camera?: Nullable); /** - * Copies the paramater passed Matrix into the mesh Pose matrix. - * Returns the TransformNode. + * Creates the depth rendering effect and checks if the effect is ready. + * @param subMesh The submesh to be used to render the depth map of + * @param useInstances If multiple world instances should be used + * @returns if the depth renderer is ready to render the depth map */ - updatePoseMatrix(matrix: Matrix): TransformNode; + isReady(subMesh: SubMesh, useInstances: boolean): boolean; /** - * Returns the mesh Pose matrix. - * Returned object : Matrix + * Gets the texture which the depth map will be written to. + * @returns The depth map texture */ - getPoseMatrix(): Matrix; - - - markAsDirty(property: string): TransformNode; + getDepthMap(): RenderTargetTexture; /** - * Returns the current mesh absolute position. - * Retuns a Vector3. + * Disposes of the depth renderer. */ - readonly absolutePosition: Vector3; + dispose(): void; + } +} + +declare module BABYLON { + class EdgesRenderer { + edgesWidthScalerForOrthographic: number; + edgesWidthScalerForPerspective: number; + private _source; + private _linesPositions; + private _linesNormals; + private _linesIndices; + private _epsilon; + private _indicesCount; + private _lineShader; + private _ib; + private _buffers; + private _checkVerticesInsteadOfIndices; + /** Gets or sets a boolean indicating if the edgesRenderer is active */ + isEnabled: boolean; + constructor(source: AbstractMesh, epsilon?: number, checkVerticesInsteadOfIndices?: boolean); + private _prepareRessources; + + dispose(): void; + private _processEdgeForAdjacencies; + private _processEdgeForAdjacenciesWithVertices; + private _checkEdge; + + render(): void; + } +} + +declare module BABYLON { + /** + * This renderer is helpfull to fill one of the render target with a geometry buffer. + */ + class GeometryBufferRenderer { + private _scene; + private _multiRenderTarget; + private _ratio; + private _enablePosition; + protected _effect: Effect; + protected _cachedDefines: string; /** - * Sets a new matrix to apply before all other transformation - * @param matrix defines the transform matrix - * @returns the current TransformNode + * Set the render list (meshes to be rendered) used in the G buffer. */ - setPreTransformMatrix(matrix: Matrix): TransformNode; - /** - * Sets a new pivot matrix to the current node - * @param matrix defines the new pivot matrix to use - * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect - * @returns the current TransformNode - */ - setPivotMatrix(matrix: Matrix, postMultiplyPivotMatrix?: boolean): TransformNode; + renderList: Mesh[]; /** - * Returns the mesh pivot matrix. - * Default : Identity. - * A Matrix is returned. + * Gets wether or not G buffer are supported by the running hardware. + * This requires draw buffer supports */ - getPivotMatrix(): Matrix; + readonly isSupported: boolean; /** - * Prevents the World matrix to be computed any longer. - * Returns the TransformNode. + * Gets wether or not position are enabled for the G buffer. */ - freezeWorldMatrix(): TransformNode; /** - * Allows back the World matrix computation. - * Returns the TransformNode. - */ - unfreezeWorldMatrix(): this; + * Sets wether or not position are enabled for the G buffer. + */ + enablePosition: boolean; /** - * True if the World matrix has been frozen. - * Returns a boolean. + * Gets the scene associated with the buffer. */ - readonly isWorldMatrixFrozen: boolean; - /** - * Retuns the mesh absolute position in the World. - * Returns a Vector3. - */ - getAbsolutePosition(): Vector3; + readonly scene: Scene; /** - * Sets the mesh absolute position in the World from a Vector3 or an Array(3). - * Returns the TransformNode. + * Gets the ratio used by the buffer during its creation. + * How big is the buffer related to the main canvas. */ - setAbsolutePosition(absolutePosition: Vector3): TransformNode; - /** - * Sets the mesh position in its local space. - * Returns the TransformNode. - */ - setPositionWithLocalVector(vector3: Vector3): TransformNode; + readonly ratio: number; /** - * Returns the mesh position in the local space from the current World matrix values. - * Returns a new Vector3. + * Creates a new G Buffer for the scene + * @param scene The scene the buffer belongs to + * @param ratio How big is the buffer related to the main canvas. */ - getPositionExpressedInLocalSpace(): Vector3; + constructor(scene: Scene, ratio?: number); /** - * Translates the mesh along the passed Vector3 in its local space. - * Returns the TransformNode. + * Checks wether everything is ready to render a submesh to the G buffer. + * @param subMesh the submesh to check readiness for + * @param useInstances is the mesh drawn using instance or not + * @returns true if ready otherwise false */ - locallyTranslate(vector3: Vector3): TransformNode; - private static _lookAtVectorCache; + isReady(subMesh: SubMesh, useInstances: boolean): boolean; /** - * Orients a mesh towards a target point. Mesh must be drawn facing user. - * @param targetPoint the position (must be in same space as current mesh) to look at - * @param yawCor optional yaw (y-axis) correction in radians - * @param pitchCor optional pitch (x-axis) correction in radians - * @param rollCor optional roll (z-axis) correction in radians - * @param space the choosen space of the target - * @returns the TransformNode. + * Gets the current underlying G Buffer. + * @returns the buffer */ - lookAt(targetPoint: Vector3, yawCor?: number, pitchCor?: number, rollCor?: number, space?: Space): TransformNode; - /** - * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh. - * This Vector3 is expressed in the World space. - */ - getDirection(localAxis: Vector3): Vector3; + getGBuffer(): MultiRenderTarget; /** - * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh. - * localAxis is expressed in the mesh local space. - * result is computed in the Wordl space from the mesh World matrix. - * Returns the TransformNode. + * Gets the number of samples used to render the buffer (anti aliasing). */ - getDirectionToRef(localAxis: Vector3, result: Vector3): TransformNode; /** - * Sets a new pivot point to the current node - * @param point defines the new pivot point to use - * @param space defines if the point is in world or local space (local by default) - * @returns the current TransformNode + * Sets the number of samples used to render the buffer (anti aliasing). */ - setPivotPoint(point: Vector3, space?: Space): TransformNode; - /** - * Returns a new Vector3 set with the mesh pivot point coordinates in the local space. - */ - getPivotPoint(): Vector3; - /** - * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space. - * Returns the TransformNode. - */ - getPivotPointToRef(result: Vector3): TransformNode; - /** - * Returns a new Vector3 set with the mesh pivot point World coordinates. - */ - getAbsolutePivotPoint(): Vector3; - /** - * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates. - * Returns the TransformNode. - */ - getAbsolutePivotPointToRef(result: Vector3): TransformNode; + samples: number; /** - * Defines the passed node as the parent of the current node. - * The node will remain exactly where it is and its position / rotation will be updated accordingly - * Returns the TransformNode. + * Disposes the renderer and frees up associated resources. */ - setParent(node: Nullable): TransformNode; - private _nonUniformScaling; - readonly nonUniformScaling: boolean; + dispose(): void; + protected _createRenderTargets(): void; + } +} +declare module BABYLON { + class OutlineRenderer { + private _scene; + private _effect; + private _cachedDefines; + zOffset: number; + constructor(scene: Scene); + render(subMesh: SubMesh, batch: _InstancesBatch, useOverlay?: boolean): void; + isReady(subMesh: SubMesh, useInstances: boolean): boolean; + } +} + +declare module BABYLON { + class RenderingGroup { + index: number; + private _scene; + private _opaqueSubMeshes; + private _transparentSubMeshes; + private _alphaTestSubMeshes; + private _depthOnlySubMeshes; + private _particleSystems; + private _spriteManagers; + private _opaqueSortCompareFn; + private _alphaTestSortCompareFn; + private _transparentSortCompareFn; + private _renderOpaque; + private _renderAlphaTest; + private _renderTransparent; + private _edgesRenderers; + onBeforeTransparentRendering: () => void; /** - * Attach the current TransformNode to another TransformNode associated with a bone - * @param bone Bone affecting the TransformNode - * @param affectedTransformNode TransformNode associated with the bone - */ - attachToBone(bone: Bone, affectedTransformNode: TransformNode): TransformNode; - detachFromBone(): TransformNode; - private static _rotationAxisCache; - /** - * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space. - * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD. - * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. - * The passed axis is also normalized. - * Returns the TransformNode. - */ - rotate(axis: Vector3, amount: number, space?: Space): TransformNode; - /** - * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space. - * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. - * The passed axis is also normalized. - * Returns the TransformNode. - * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm - */ - rotateAround(point: Vector3, axis: Vector3, amount: number): TransformNode; - /** - * Translates the mesh along the axis vector for the passed distance in the given space. - * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD. - * Returns the TransformNode. - */ - translate(axis: Vector3, distance: number, space?: Space): TransformNode; - /** - * Adds a rotation step to the mesh current rotation. - * x, y, z are Euler angles expressed in radians. - * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set. - * This means this rotation is made in the mesh local space only. - * It's useful to set a custom rotation order different from the BJS standard one YXZ. - * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis. - * ```javascript - * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3); - * ``` - * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values. - * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles. - * Returns the TransformNode. - */ - addRotation(x: number, y: number, z: number): TransformNode; - /** - * Computes the mesh World matrix and returns it. - * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values. - * If the parameter `force` is let to `false` (default), the current cached World matrix is returned. - * If the parameter `force`is set to `true`, the actual computation is done. - * Returns the mesh World Matrix. + * Set the opaque sort comparison function. + * If null the sub meshes will be render in the order they were created */ - computeWorldMatrix(force?: boolean): Matrix; - protected _afterComputeWorldMatrix(): void; + opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number>; /** - * If you'd like to be called back after the mesh position, rotation or scaling has been updated. - * @param func: callback function to add - * - * Returns the TransformNode. - */ - registerAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode; + * Set the alpha test sort comparison function. + * If null the sub meshes will be render in the order they were created + */ + alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number>; /** - * Removes a registered callback function. - * Returns the TransformNode. + * Set the transparent sort comparison function. + * If null the sub meshes will be render in the order they were created */ - unregisterAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode; + transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number>; /** - * Clone the current transform node - * Returns the new transform node - * @param name Name of the new clone - * @param newParent New parent for the clone - * @param doNotCloneChildren Do not clone children hierarchy + * Creates a new rendering group. + * @param index The rendering group index + * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied + * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied + * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied */ - clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable; - serialize(currentSerializationObject?: any): any; + constructor(index: number, scene: Scene, opaqueSortCompareFn?: Nullable<(a: SubMesh, b: SubMesh) => number>, alphaTestSortCompareFn?: Nullable<(a: SubMesh, b: SubMesh) => number>, transparentSortCompareFn?: Nullable<(a: SubMesh, b: SubMesh) => number>); /** - * Returns a new TransformNode object parsed from the source provided. - * The parameter `parsedMesh` is the source. - * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with + * Render all the sub meshes contained in the group. + * @param customRenderFunction Used to override the default render behaviour of the group. + * @returns true if rendered some submeshes. */ - static Parse(parsedTransformNode: any, scene: Scene, rootUrl: string): TransformNode; + render(customRenderFunction: Nullable<(opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, depthOnlySubMeshes: SmartArray) => void>, renderSprites: boolean, renderParticles: boolean, activeMeshes: Nullable): void; /** - * Releases resources associated with this transform node. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + * Renders the opaque submeshes in the order from the opaqueSortCompareFn. + * @param subMeshes The submeshes to render */ - dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; - } -} - -declare module BABYLON { - class VertexBuffer { - /** @hidden */ - - private _kind; - private _size; - private _ownsBuffer; - private _instanced; - private _instanceDivisor; + private renderOpaqueSorted; /** - * The byte type. + * Renders the opaque submeshes in the order from the alphatestSortCompareFn. + * @param subMeshes The submeshes to render */ - static readonly BYTE: number; + private renderAlphaTestSorted; /** - * The unsigned byte type. + * Renders the opaque submeshes in the order from the transparentSortCompareFn. + * @param subMeshes The submeshes to render */ - static readonly UNSIGNED_BYTE: number; + private renderTransparentSorted; /** - * The short type. + * Renders the submeshes in a specified order. + * @param subMeshes The submeshes to sort before render + * @param sortCompareFn The comparison function use to sort + * @param cameraPosition The camera position use to preprocess the submeshes to help sorting + * @param transparent Specifies to activate blending if true */ - static readonly SHORT: number; + private static renderSorted; /** - * The unsigned short type. + * Renders the submeshes in the order they were dispatched (no sort applied). + * @param subMeshes The submeshes to render */ - static readonly UNSIGNED_SHORT: number; + private static renderUnsorted; /** - * The integer type. + * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) + * are rendered back to front if in the same alpha index. + * + * @param a The first submesh + * @param b The second submesh + * @returns The result of the comparison */ - static readonly INT: number; + static defaultTransparentSortCompare(a: SubMesh, b: SubMesh): number; /** - * The unsigned integer type. + * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) + * are rendered back to front. + * + * @param a The first submesh + * @param b The second submesh + * @returns The result of the comparison */ - static readonly UNSIGNED_INT: number; + static backToFrontSortCompare(a: SubMesh, b: SubMesh): number; /** - * The float type. + * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) + * are rendered front to back (prevent overdraw). + * + * @param a The first submesh + * @param b The second submesh + * @returns The result of the comparison */ - static readonly FLOAT: number; + static frontToBackSortCompare(a: SubMesh, b: SubMesh): number; /** - * Gets or sets the instance divisor when in instanced mode + * Resets the different lists of submeshes to prepare a new frame. */ - instanceDivisor: number; + prepare(): void; + dispose(): void; /** - * Gets the byte stride. + * Inserts the submesh in its correct queue depending on its material. + * @param subMesh The submesh to dispatch + * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance. + * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance. */ - readonly byteStride: number; + dispatch(subMesh: SubMesh, mesh?: AbstractMesh, material?: Nullable): void; + dispatchSprites(spriteManager: SpriteManager): void; + dispatchParticles(particleSystem: IParticleSystem): void; + private _renderParticles; + private _renderSprites; + } +} + +declare module BABYLON { + /** + * Interface describing the different options available in the rendering manager + * regarding Auto Clear between groups. + */ + interface IRenderingManagerAutoClearSetup { /** - * Gets the byte offset. + * Defines whether or not autoclear is enable. */ - readonly byteOffset: number; + autoClear: boolean; /** - * Gets whether integer data values should be normalized into a certain range when being casted to a float. + * Defines whether or not to autoclear the depth buffer. */ - readonly normalized: boolean; + depth: boolean; /** - * Gets the data type of each component in the array. + * Defines whether or not to autoclear the stencil buffer. */ - readonly type: number; + stencil: boolean; + } + class RenderingManager { /** - * Constructor - * @param engine the engine - * @param data the data to use for this vertex buffer - * @param kind the vertex buffer kind - * @param updatable whether the data is updatable - * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional) - * @param stride the stride (optional) - * @param instanced whether the buffer is instanced (optional) - * @param offset the offset of the data (optional) - * @param size the number of components (optional) - * @param type the type of the component (optional) - * @param normalized whether the data contains normalized data (optional) - * @param useBytes set to true if stride and offset are in bytes (optional) + * The max id used for rendering groups (not included) */ - constructor(engine: any, data: DataArray | Buffer, kind: string, updatable: boolean, postponeInternalCreation?: boolean, stride?: number, instanced?: boolean, offset?: number, size?: number, type?: number, normalized?: boolean, useBytes?: boolean); - + static MAX_RENDERINGGROUPS: number; /** - * Returns the kind of the VertexBuffer (string). + * The min id used for rendering groups (included) */ - getKind(): string; + static MIN_RENDERINGGROUPS: number; /** - * Boolean : is the VertexBuffer updatable ? + * Used to globally prevent autoclearing scenes. */ - isUpdatable(): boolean; + static AUTOCLEAR: boolean; /** - * Returns an array of numbers or a typed array containing the VertexBuffer data. + * Hidden */ - getData(): Nullable; + + private _scene; + private _renderingGroups; + private _depthStencilBufferAlreadyCleaned; + private _autoClearDepthStencil; + private _customOpaqueSortCompareFn; + private _customAlphaTestSortCompareFn; + private _customTransparentSortCompareFn; + private _renderingGroupInfo; + constructor(scene: Scene); + private _clearDepthStencilBuffer; + render(customRenderFunction: Nullable<(opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, depthOnlySubMeshes: SmartArray) => void>, activeMeshes: Nullable, renderParticles: boolean, renderSprites: boolean): void; + reset(): void; + dispose(): void; /** - * Returns the WebGLBuffer associated to the VertexBuffer. + * Clear the info related to rendering groups preventing retention points during dispose. */ - getBuffer(): Nullable; + freeRenderingGroups(): void; + private _prepareRenderingGroup; + dispatchSprites(spriteManager: SpriteManager): void; + dispatchParticles(particleSystem: IParticleSystem): void; /** - * Returns the stride as a multiple of the type byte length. - * DEPRECATED. Use byteStride instead. + * @param subMesh The submesh to dispatch + * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance. + * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance. */ - getStrideSize(): number; + dispatch(subMesh: SubMesh, mesh?: AbstractMesh, material?: Nullable): void; /** - * Returns the offset as a multiple of the type byte length. - * DEPRECATED. Use byteOffset instead. + * Overrides the default sort function applied in the renderging group to prepare the meshes. + * This allowed control for front to back rendering or reversly depending of the special needs. + * + * @param renderingGroupId The rendering group id corresponding to its index + * @param opaqueSortCompareFn The opaque queue comparison function use to sort. + * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. + * @param transparentSortCompareFn The transparent queue comparison function use to sort. */ - getOffset(): number; + setRenderingOrder(renderingGroupId: number, opaqueSortCompareFn?: Nullable<(a: SubMesh, b: SubMesh) => number>, alphaTestSortCompareFn?: Nullable<(a: SubMesh, b: SubMesh) => number>, transparentSortCompareFn?: Nullable<(a: SubMesh, b: SubMesh) => number>): void; /** - * Returns the number of components per vertex attribute (integer). + * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. + * + * @param renderingGroupId The rendering group id corresponding to its index + * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. + * @param depth Automatically clears depth between groups if true and autoClear is true. + * @param stencil Automatically clears stencil between groups if true and autoClear is true. */ - getSize(): number; + setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean, depth?: boolean, stencil?: boolean): void; /** - * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ? + * Gets the current auto clear configuration for one rendering group of the rendering + * manager. + * @param index the rendering group index to get the information for + * @returns The auto clear setup for the requested rendering group */ - getIsInstanced(): boolean; + getAutoClearDepthStencilSetup(index: number): IRenderingManagerAutoClearSetup; + } +} + +declare module BABYLON { + /** + * Renders a layer on top of an existing scene + */ + class UtilityLayerRenderer implements IDisposable { + originalScene: Scene; + private _pointerCaptures; + private _lastPointerEvents; + private static _DefaultUtilityLayer; + private static _DefaultKeepDepthUtilityLayer; /** - * Returns the instancing divisor, zero for non-instanced (integer). + * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it) */ - getInstanceDivisor(): number; + static readonly DefaultUtilityLayer: UtilityLayerRenderer; /** - * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array. - * Returns the created WebGLBuffer. + * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it) */ - create(data?: DataArray): void; + static readonly DefaultKeepDepthUtilityLayer: UtilityLayerRenderer; /** - * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array. - * This function will create a new buffer if the current one is not updatable - * Returns the updated WebGLBuffer. + * The scene that is rendered on top of the original scene */ - update(data: DataArray): void; + utilityLayerScene: Scene; /** - * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array. - * Returns the directly updated WebGLBuffer. - * @param data the new data - * @param offset the new offset - * @param useBytes set to true if the offset is in bytes + * If the utility layer should automatically be rendered on top of existing scene + */ + shouldRender: boolean; + /** + * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene */ - updateDirectly(data: DataArray, offset: number, useBytes?: boolean): void; + onlyCheckPointerDownEvents: boolean; /** - * Disposes the VertexBuffer and the underlying WebGLBuffer. + * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default) */ - dispose(): void; + processAllEvents: boolean; /** - * Enumerates each value of this vertex buffer as numbers. - * @param count the number of values to enumerate - * @param callback the callback function called for each value + * Observable raised when the pointer move from the utility layer scene to the main scene */ - forEach(count: number, callback: (value: number, index: number) => void): void; - private static _PositionKind; - private static _NormalKind; - private static _TangentKind; - private static _UVKind; - private static _UV2Kind; - private static _UV3Kind; - private static _UV4Kind; - private static _UV5Kind; - private static _UV6Kind; - private static _ColorKind; - private static _MatricesIndicesKind; - private static _MatricesWeightsKind; - private static _MatricesIndicesExtraKind; - private static _MatricesWeightsExtraKind; - static readonly PositionKind: string; - static readonly NormalKind: string; - static readonly TangentKind: string; - static readonly UVKind: string; - static readonly UV2Kind: string; - static readonly UV3Kind: string; - static readonly UV4Kind: string; - static readonly UV5Kind: string; - static readonly UV6Kind: string; - static readonly ColorKind: string; - static readonly MatricesIndicesKind: string; - static readonly MatricesWeightsKind: string; - static readonly MatricesIndicesExtraKind: string; - static readonly MatricesWeightsExtraKind: string; + onPointerOutObservable: Observable; + /** Gets or sets a predicate that will be used to indicate utility meshes present in the main scene */ + mainSceneTrackerPredicate: (mesh: Nullable) => boolean; + private _afterRenderObserver; + private _sceneDisposeObserver; + private _originalPointerObserver; /** - * Deduces the stride given a kind. - * @param kind The kind string to deduce - * @returns The deduced stride + * Instantiates a UtilityLayerRenderer + * @param originalScene the original scene that will be rendered on top of */ - static DeduceStride(kind: string): number; + constructor(/** the original scene that will be rendered on top of */ originalScene: Scene); + private _notifyObservers; /** - * Gets the byte length of the given type. - * @param type the type - * @returns the number of bytes + * Renders the utility layers scene on top of the original scene */ - static GetTypeByteLength(type: number): number; + render(): void; /** - * Enumerates each value of the given parameters as numbers. - * @param data the data to enumerate - * @param byteOffset the byte offset of the data - * @param byteStride the byte stride of the data - * @param componentCount the number of components per element - * @param componentType the type of the component - * @param count the total number of components - * @param normalized whether the data is normalized - * @param callback the callback function called for each value + * Disposes of the renderer */ - static ForEach(data: DataArray, byteOffset: number, byteStride: number, componentCount: number, componentType: number, count: number, normalized: boolean, callback: (value: number, index: number) => void): void; - private static _GetFloatValue(dataView, type, byteOffset, normalized); + dispose(): void; + private _updateCamera; } } declare module BABYLON { - class ReflectionProbe { + class Sprite { name: string; - private _scene; - private _renderTargetTexture; - private _projectionMatrix; - private _viewMatrix; - private _target; - private _add; - private _attachedMesh; - private _invertYAxis; position: Vector3; - constructor(name: string, size: number, scene: Scene, generateMipMaps?: boolean); - samples: number; - refreshRate: number; - getScene(): Scene; - readonly cubeTexture: RenderTargetTexture; - readonly renderList: Nullable; - attachToMesh(mesh: AbstractMesh): void; + color: Color4; + width: number; + height: number; + angle: number; + cellIndex: number; + invertU: number; + invertV: number; + disposeWhenFinishedAnimating: boolean; + animations: Animation[]; + isPickable: boolean; + actionManager: ActionManager; + private _animationStarted; + private _loopAnimation; + private _fromIndex; + private _toIndex; + private _delay; + private _direction; + private _manager; + private _time; + private _onAnimationEnd; /** - * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. - * - * @param renderingGroupId The rendering group id corresponding to its index - * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. + * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true */ - setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean): void; + isVisible: boolean; + size: number; + constructor(name: string, manager: SpriteManager); + playAnimation(from: number, to: number, loop: boolean, delay: number, onAnimationEnd: () => void): void; + stopAnimation(): void; + + dispose(): void; + } +} + +declare module BABYLON { + class SpriteManager { + name: string; + sprites: Sprite[]; + renderingGroupId: number; + layerMask: number; + fogEnabled: boolean; + isPickable: boolean; + cellWidth: number; + cellHeight: number; + /** + * An event triggered when the manager is disposed. + */ + onDisposeObservable: Observable; + private _onDisposeObserver; + onDispose: () => void; + private _capacity; + private _spriteTexture; + private _epsilon; + private _scene; + private _vertexData; + private _buffer; + private _vertexBuffers; + private _indexBuffer; + private _effectBase; + private _effectFog; + texture: Texture; + constructor(name: string, imgUrl: string, capacity: number, cellSize: any, scene: Scene, epsilon?: number, samplingMode?: number); + private _appendSpriteVertex; + intersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean): Nullable; + render(): void; dispose(): void; } } +declare module BABYLON { + /** + * @hidden + **/ + class _AlphaState { + private _isAlphaBlendDirty; + private _isBlendFunctionParametersDirty; + private _isBlendEquationParametersDirty; + private _isBlendConstantsDirty; + private _alphaBlend; + private _blendFunctionParameters; + private _blendEquationParameters; + private _blendConstants; + /** + * Initializes the state. + */ + constructor(); + readonly isDirty: boolean; + alphaBlend: boolean; + setAlphaBlendConstants(r: number, g: number, b: number, a: number): void; + setAlphaBlendFunctionParameters(value0: number, value1: number, value2: number, value3: number): void; + setAlphaEquationParameters(rgb: number, alpha: number): void; + reset(): void; + apply(gl: WebGLRenderingContext): void; + } +} + +declare module BABYLON { + /** + * @hidden + **/ + class _DepthCullingState { + private _isDepthTestDirty; + private _isDepthMaskDirty; + private _isDepthFuncDirty; + private _isCullFaceDirty; + private _isCullDirty; + private _isZOffsetDirty; + private _isFrontFaceDirty; + private _depthTest; + private _depthMask; + private _depthFunc; + private _cull; + private _cullFace; + private _zOffset; + private _frontFace; + /** + * Initializes the state. + */ + constructor(); + readonly isDirty: boolean; + zOffset: number; + cullFace: Nullable; + cull: Nullable; + depthFunc: Nullable; + depthMask: boolean; + depthTest: boolean; + frontFace: Nullable; + reset(): void; + apply(gl: WebGLRenderingContext): void; + } +} + +declare module BABYLON { + /** + * @hidden + **/ + class _StencilState { + private _isStencilTestDirty; + private _isStencilMaskDirty; + private _isStencilFuncDirty; + private _isStencilOpDirty; + private _stencilTest; + private _stencilMask; + private _stencilFunc; + private _stencilFuncRef; + private _stencilFuncMask; + private _stencilOpStencilFail; + private _stencilOpDepthFail; + private _stencilOpStencilDepthPass; + readonly isDirty: boolean; + stencilFunc: number; + stencilFuncRef: number; + stencilFuncMask: number; + stencilOpStencilFail: number; + stencilOpDepthFail: number; + stencilOpStencilDepthPass: number; + stencilMask: number; + stencilTest: boolean; + constructor(); + reset(): void; + apply(gl: WebGLRenderingContext): void; + } +} + declare module BABYLON { /** * Postprocess used to generate anaglyphic rendering @@ -26890,7 +27544,7 @@ declare module BABYLON { * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion. */ class BloomMergePostProcess extends PostProcess { - /** Weight of the bloom to be added to the original input. */ weight: number; + weight: number; /** * Creates a new instance of @see BloomMergePostProcess * @param name The name of the effect. @@ -26915,25 +27569,25 @@ declare module BABYLON { * Can be used twice in x and y directions to perform a guassian blur in two passes. */ class BlurPostProcess extends PostProcess { - /** The direction in which to blur the image. */ direction: Vector2; + direction: Vector2; private blockCompilation; protected _kernel: number; protected _idealKernel: number; protected _packedFloat: boolean; private _staticDefines; - /** - * Gets the length in pixels of the blur sample region - */ /** * Sets the length in pixels of the blur sample region */ - kernel: number; /** - * Gets wether or not the blur is unpacking/repacking floats - */ + * Gets the length in pixels of the blur sample region + */ + kernel: number; /** * Sets wether or not the blur needs to unpack/repack floats */ + /** + * Gets wether or not the blur is unpacking/repacking floats + */ packedFloat: boolean; /** * Creates a new instance BlurPostProcess @@ -27080,7 +27734,7 @@ declare module BABYLON { * See http://en.wikipedia.org/wiki/Kernel_(image_processing) */ class ConvolutionPostProcess extends PostProcess { - /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel: number[]; + kernel: number[]; /** * Creates a new instance ConvolutionPostProcess * @param name The name of the effect. @@ -27165,7 +27819,7 @@ declare module BABYLON { /** * Large blur */ - High = 2, + High = 2 } /** * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing. @@ -27323,7 +27977,7 @@ declare module BABYLON { texelWidth: number; texelHeight: number; constructor(name: string, options: number | PostProcessOptions, camera?: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number); - private _getDefines(); + private _getDefines; } } @@ -27371,10 +28025,10 @@ declare module BABYLON { * Gets the image processing configuration used either in this material. */ /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ imageProcessingConfiguration: ImageProcessingConfiguration; /** * Keep track of the image processing observer to allow dispose and replace. @@ -27386,1289 +28040,642 @@ declare module BABYLON { */ protected _attachImageProcessingConfiguration(configuration: Nullable, doNotBuild?: boolean): void; /** - * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true . - */ - /** - * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true . - */ - colorCurves: Nullable; - /** - * Gets wether the color curves effect is enabled. - */ - /** - * Sets wether the color curves effect is enabled. - */ - colorCurvesEnabled: boolean; - /** - * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. - */ - /** - * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. - */ - colorGradingTexture: Nullable; - /** - * Gets wether the color grading effect is enabled. - */ - /** - * Gets wether the color grading effect is enabled. - */ - colorGradingEnabled: boolean; - /** - * Gets exposure used in the effect. - */ - /** - * Sets exposure used in the effect. - */ - exposure: number; - /** - * Gets wether tonemapping is enabled or not. - */ - /** - * Sets wether tonemapping is enabled or not - */ - toneMappingEnabled: boolean; - /** - * Gets contrast used in the effect. - */ - /** - * Sets contrast used in the effect. - */ - contrast: number; - /** - * Gets Vignette stretch size. - */ - /** - * Sets Vignette stretch size. - */ - vignetteStretch: number; - /** - * Gets Vignette centre X Offset. - */ - /** - * Sets Vignette centre X Offset. - */ - vignetteCentreX: number; - /** - * Gets Vignette centre Y Offset. - */ - /** - * Sets Vignette centre Y Offset. - */ - vignetteCentreY: number; - /** - * Gets Vignette weight or intensity of the vignette effect. - */ - /** - * Sets Vignette weight or intensity of the vignette effect. - */ - vignetteWeight: number; - /** - * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) - * if vignetteEnabled is set to true. - */ - /** - * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) - * if vignetteEnabled is set to true. - */ - vignetteColor: Color4; - /** - * Gets Camera field of view used by the Vignette effect. - */ - /** - * Sets Camera field of view used by the Vignette effect. - */ - vignetteCameraFov: number; - /** - * Gets the vignette blend mode allowing different kind of effect. - */ - /** - * Sets the vignette blend mode allowing different kind of effect. - */ - vignetteBlendMode: number; - /** - * Gets wether the vignette effect is enabled. - */ - /** - * Sets wether the vignette effect is enabled. - */ - vignetteEnabled: boolean; - private _fromLinearSpace; - /** - * Gets wether the input of the processing is in Gamma or Linear Space. - */ - /** - * Sets wether the input of the processing is in Gamma or Linear Space. - */ - fromLinearSpace: boolean; - /** - * Defines cache preventing GC. - */ - private _defines; - constructor(name: string, options: number | PostProcessOptions, camera?: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number, imageProcessingConfiguration?: ImageProcessingConfiguration); - getClassName(): string; - protected _updateParameters(): void; - dispose(camera?: Camera): void; - } -} - -declare module BABYLON { - class PassPostProcess extends PostProcess { - constructor(name: string, options: number | PostProcessOptions, camera?: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number, blockCompilation?: boolean); - } -} - -declare module BABYLON { - type PostProcessOptions = { - width: number; - height: number; - }; - /** - * PostProcess can be used to apply a shader to a texture after it has been rendered - * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses - */ - class PostProcess { - /** Name of the PostProcess. */ name: string; - /** - * Width of the texture to apply the post process on - */ - width: number; - /** - * Height of the texture to apply the post process on - */ - height: number; - /** - * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain) - */ - - /** - * Sampling mode used by the shader - * See https://doc.babylonjs.com/classes/3.1/texture - */ - renderTargetSamplingMode: number; - /** - * Clear color to use when screen clearing - */ - clearColor: Color4; - /** - * If the buffer needs to be cleared before applying the post process. (default: true) - * Should be set to false if shader will overwrite all previous pixels. - */ - autoClear: boolean; - /** - * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE) - */ - alphaMode: number; - /** - * Sets the setAlphaBlendConstants of the babylon engine - */ - alphaConstants: Color4; - /** - * Animations to be used for the post processing - */ - animations: Animation[]; - /** - * Enable Pixel Perfect mode where texture is not scaled to be power of 2. - * Can only be used on a single postprocess or on the last one of a chain. (default: false) - */ - enablePixelPerfectMode: boolean; - /** - * Force the postprocess to be applied without taking in account viewport - */ - forceFullscreenViewport: boolean; - /** - * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR) - * - * | Value | Type | Description | - * | ----- | ----------------------------------- | ----------- | - * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) | - * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) | - * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) | - * - */ - scaleMode: number; - /** - * Force textures to be a power of two (default: false) - */ - alwaysForcePOT: boolean; - /** - * Number of sample textures (default: 1) - */ - samples: number; - /** - * Modify the scale of the post process to be the same as the viewport (default: false) - */ - adaptScaleToCurrentViewport: boolean; - private _camera; - private _scene; - private _engine; - private _options; - private _reusable; - private _textureType; - /** - * Smart array of input and output textures for the post process. - */ - - /** - * The index in _textures that corresponds to the output texture. - */ - - private _effect; - private _samplers; - private _fragmentUrl; - private _vertexUrl; - private _parameters; - private _scaleRatio; - protected _indexParameters: any; - private _shareOutputWithPostProcess; - private _texelSize; - private _forcedOutputTexture; - /** - * An event triggered when the postprocess is activated. - */ - onActivateObservable: Observable; - private _onActivateObserver; - /** - * A function that is added to the onActivateObservable - */ - onActivate: Nullable<(camera: Camera) => void>; - /** - * An event triggered when the postprocess changes its size. - */ - onSizeChangedObservable: Observable; - private _onSizeChangedObserver; - /** - * A function that is added to the onSizeChangedObservable - */ - onSizeChanged: (postProcess: PostProcess) => void; - /** - * An event triggered when the postprocess applies its effect. - */ - onApplyObservable: Observable; - private _onApplyObserver; - /** - * A function that is added to the onApplyObservable - */ - onApply: (effect: Effect) => void; - /** - * An event triggered before rendering the postprocess - */ - onBeforeRenderObservable: Observable; - private _onBeforeRenderObserver; - /** - * A function that is added to the onBeforeRenderObservable - */ - onBeforeRender: (effect: Effect) => void; - /** - * An event triggered after rendering the postprocess - */ - onAfterRenderObservable: Observable; - private _onAfterRenderObserver; - /** - * A function that is added to the onAfterRenderObservable - */ - onAfterRender: (efect: Effect) => void; - /** - * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will - * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process. - */ - inputTexture: InternalTexture; - /** - * Gets the camera which post process is applied to. - * @returns The camera the post process is applied to. - */ - getCamera(): Camera; - /** - * Gets the texel size of the postprocess. - * See https://en.wikipedia.org/wiki/Texel_(graphics) - */ - readonly texelSize: Vector2; - /** - * Creates a new instance PostProcess - * @param name The name of the PostProcess. - * @param fragmentUrl The url of the fragment shader to be used. - * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader. - * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader. - * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size) - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param defines String of defines that will be set when running the fragment shader. (default: null) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess") - * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx - * @param blockCompilation If the shader should not be compiled imediatly. (default: false) - */ - constructor(/** Name of the PostProcess. */ name: string, fragmentUrl: string, parameters: Nullable, samplers: Nullable, options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, defines?: Nullable, textureType?: number, vertexUrl?: string, indexParameters?: any, blockCompilation?: boolean); - /** - * Gets the engine which this post process belongs to. - * @returns The engine the post process was enabled with. - */ - getEngine(): Engine; - /** - * The effect that is created when initializing the post process. - * @returns The created effect corrisponding the the postprocess. - */ - getEffect(): Effect; - /** - * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another. - * @param postProcess The post process to share the output with. - * @returns This post process. - */ - shareOutputWith(postProcess: PostProcess): PostProcess; - /** - * Reverses the effect of calling shareOutputWith and returns the post process back to its original state. - * This should be called if the post process that shares output with this post process is disabled/disposed. - */ - useOwnOutput(): void; - /** - * Updates the effect with the current post process compile time values and recompiles the shader. - * @param defines Define statements that should be added at the beginning of the shader. (default: null) - * @param uniforms Set of uniform variables that will be passed to the shader. (default: null) - * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null) - * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx - * @param onCompiled Called when the shader has been compiled. - * @param onError Called if there is an error when compiling a shader. - */ - updateEffect(defines?: Nullable, uniforms?: Nullable, samplers?: Nullable, indexParameters?: any, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): void; - /** - * The post process is reusable if it can be used multiple times within one frame. - * @returns If the post process is reusable - */ - isReusable(): boolean; - /** invalidate frameBuffer to hint the postprocess to create a depth buffer */ - markTextureDirty(): void; - /** - * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable. - * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous. - * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable. - * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null) - * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false) - * @returns The target texture that was bound to be written to. - */ - activate(camera: Nullable, sourceTexture?: Nullable, forceDepthStencil?: boolean): InternalTexture; - /** - * If the post process is supported. - */ - readonly isSupported: boolean; - /** - * The aspect ratio of the output texture. - */ - readonly aspectRatio: number; - /** - * Get a value indicating if the post-process is ready to be used - * @returns true if the post-process is ready (shader is compiled) - */ - isReady(): boolean; - /** - * Binds all textures and uniforms to the shader, this will be run on every pass. - * @returns the effect corrisponding to this post process. Null if not compiled or not ready. - */ - apply(): Nullable; - private _disposeTextures(); - /** - * Disposes the post process. - * @param camera The camera to dispose the post process on. - */ - dispose(camera?: Camera): void; - } -} - -declare module BABYLON { - /** - * PostProcessManager is used to manage one or more post processes or post process pipelines - * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses - */ - class PostProcessManager { - private _scene; - private _indexBuffer; - private _vertexBuffers; - /** - * Creates a new instance PostProcess - * @param scene The scene that the post process is associated with. - */ - constructor(scene: Scene); - private _prepareBuffers(); - private _buildIndexBuffer(); - /** - * Rebuilds the vertex buffers of the manager. - */ - - /** - * Prepares a frame to be run through a post process. - * @param sourceTexture The input texture to the post procesess. (default: null) - * @param postProcesses An array of post processes to be run. (default: null) - * @returns True if the post processes were able to be run. - */ - - /** - * Manually render a set of post processes to a texture. - * @param postProcesses An array of post processes to be run. - * @param targetTexture The target texture to render to. - * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight - * @param faceIndex defines the face to render to if a cubemap is defined as the target - * @param lodLevel defines which lod of the texture to render to - */ - directRender(postProcesses: PostProcess[], targetTexture?: Nullable, forceFullscreenViewport?: boolean, faceIndex?: number, lodLevel?: number): void; - /** - * Finalize the result of the output of the postprocesses. - * @param doNotPresent If true the result will not be displayed to the screen. - * @param targetTexture The target texture to render to. - * @param faceIndex The index of the face to bind the target texture to. - * @param postProcesses The array of post processes to render. - * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false) - */ - - /** - * Disposes of the post process manager. - */ - dispose(): void; - } -} - -declare module BABYLON { - class RefractionPostProcess extends PostProcess { - color: Color3; - depth: number; - colorLevel: number; - private _refTexture; - private _ownRefractionTexture; - /** - * Gets or sets the refraction texture - * Please note that you are responsible for disposing the texture if you set it manually - */ - refractionTexture: Texture; - constructor(name: string, refractionTextureUrl: string, color: Color3, depth: number, colorLevel: number, options: number | PostProcessOptions, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); - dispose(camera: Camera): void; - } -} - -declare module BABYLON { - /** - * The SharpenPostProcess applies a sharpen kernel to every pixel - * See http://en.wikipedia.org/wiki/Kernel_(image_processing) - */ - class SharpenPostProcess extends PostProcess { - /** - * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1) - */ - colorAmount: number; - /** - * How much sharpness should be applied (default: 0.3) - */ - edgeAmount: number; - /** - * Creates a new instance ConvolutionPostProcess - * @param name The name of the effect. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) - */ - constructor(name: string, options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number, blockCompilation?: boolean); - } -} - -declare module BABYLON { - class StereoscopicInterlacePostProcess extends PostProcess { - private _stepSize; - private _passedProcess; - constructor(name: string, rigCameras: Camera[], isStereoscopicHoriz: boolean, samplingMode?: number, engine?: Engine, reusable?: boolean); - } -} - -declare module BABYLON { - /** Defines operator used for tonemapping */ - enum TonemappingOperator { - /** Hable */ - Hable = 0, - /** Reinhard */ - Reinhard = 1, - /** HejiDawson */ - HejiDawson = 2, - /** Photographic */ - Photographic = 3, - } - /** - * Defines a post process to apply tone mapping - */ - class TonemapPostProcess extends PostProcess { - private _operator; - /** Defines the required exposure adjustement */ - exposureAdjustment: number; - /** - * Creates a new TonemapPostProcess - * @param name defines the name of the postprocess - * @param _operator defines the operator to use - * @param exposureAdjustment defines the required exposure adjustement - * @param camera defines the camera to use (can be null) - * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default) - * @param engine defines the hosting engine (can be ignore if camera is set) - * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default) + * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true . */ - constructor(name: string, _operator: TonemappingOperator, - /** Defines the required exposure adjustement */ - exposureAdjustment: number, camera: Camera, samplingMode?: number, engine?: Engine, textureFormat?: number); - } -} - -declare module BABYLON { - class VolumetricLightScatteringPostProcess extends PostProcess { - private _volumetricLightScatteringPass; - private _volumetricLightScatteringRTT; - private _viewPort; - private _screenCoordinates; - private _cachedDefines; /** - * If not undefined, the mesh position is computed from the attached node position + * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true . */ - attachedNode: { - position: Vector3; - }; + colorCurves: Nullable; /** - * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true" - */ - customMeshPosition: Vector3; + * Gets wether the color curves effect is enabled. + */ /** - * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false) + * Sets wether the color curves effect is enabled. */ - useCustomMeshPosition: boolean; + colorCurvesEnabled: boolean; /** - * If the post-process should inverse the light scattering direction - */ - invert: boolean; + * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. + */ /** - * The internal mesh used by the post-process + * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. */ - mesh: Mesh; - useDiffuseColor: boolean; + colorGradingTexture: Nullable; /** - * Array containing the excluded meshes not rendered in the internal pass + * Gets wether the color grading effect is enabled. + */ + /** + * Gets wether the color grading effect is enabled. */ - excludedMeshes: AbstractMesh[]; + colorGradingEnabled: boolean; /** - * Controls the overall intensity of the post-process + * Gets exposure used in the effect. + */ + /** + * Sets exposure used in the effect. */ exposure: number; /** - * Dissipates each sample's contribution in range [0, 1] - */ - decay: number; + * Gets wether tonemapping is enabled or not. + */ /** - * Controls the overall intensity of each sample + * Sets wether tonemapping is enabled or not */ - weight: number; + toneMappingEnabled: boolean; /** - * Controls the density of each sample + * Gets contrast used in the effect. + */ + /** + * Sets contrast used in the effect. */ - density: number; + contrast: number; /** - * @constructor - * @param {string} name - The post-process name - * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) - * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to - * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering - * @param {number} samples - The post-process quality, default 100 - * @param {number} samplingMode - The post-process filtering mode - * @param {BABYLON.Engine} engine - The babylon engine - * @param {boolean} reusable - If the post-process is reusable - * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided + * Gets Vignette stretch size. */ - constructor(name: string, ratio: any, camera: Camera, mesh?: Mesh, samples?: number, samplingMode?: number, engine?: Engine, reusable?: boolean, scene?: Scene); - getClassName(): string; - private _isReady(subMesh, useInstances); /** - * Sets the new light position for light scattering effect - * @param {BABYLON.Vector3} The new custom light position - */ - setCustomMeshPosition(position: Vector3): void; + * Sets Vignette stretch size. + */ + vignetteStretch: number; /** - * Returns the light position for light scattering effect - * @return {BABYLON.Vector3} The custom light position + * Gets Vignette centre X Offset. */ - getCustomMeshPosition(): Vector3; /** - * Disposes the internal assets and detaches the post-process from the camera - */ - dispose(camera: Camera): void; + * Sets Vignette centre X Offset. + */ + vignetteCentreX: number; /** - * Returns the render target texture used by the post-process - * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process + * Gets Vignette centre Y Offset. */ - getPass(): RenderTargetTexture; - private _meshExcluded(mesh); - private _createPass(scene, ratio); - private _updateMeshScreenCoordinates(scene); /** - * Creates a default mesh for the Volumeric Light Scattering post-process - * @param {string} The mesh name - * @param {BABYLON.Scene} The scene where to create the mesh - * @return {BABYLON.Mesh} the default mesh + * Sets Vignette centre Y Offset. */ - static CreateDefaultMesh(name: string, scene: Scene): Mesh; - } -} - -declare module BABYLON { - class VRDistortionCorrectionPostProcess extends PostProcess { - private _isRightEye; - private _distortionFactors; - private _postProcessScaleFactor; - private _lensCenterOffset; - private _scaleIn; - private _scaleFactor; - private _lensCenter; - constructor(name: string, camera: Camera, isRightEye: boolean, vrMetrics: VRCameraMetrics); - } -} - -declare module BABYLON { - interface Scene { - /** @hidden (Backing field) */ - - /** @hidden (Backing field) */ - + vignetteCentreY: number; /** - * Gets or sets a boolean indicating if all bounding boxes must be rendered + * Gets Vignette weight or intensity of the vignette effect. */ - forceShowBoundingBoxes: boolean; /** - * Gets the bounding box renderer associated with the scene - * @returns a BoundingBoxRenderer - */ - getBoundingBoxRenderer(): BoundingBoxRenderer; - } - interface AbstractMesh { - /** @hidden (Backing field) */ - + * Sets Vignette weight or intensity of the vignette effect. + */ + vignetteWeight: number; /** - * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default) + * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) + * if vignetteEnabled is set to true. */ - showBoundingBox: boolean; - } - class BoundingBoxRenderer implements ISceneComponent { /** - * The component name helpfull to identify the component in the list of scene components. - */ - readonly name: string; + * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) + * if vignetteEnabled is set to true. + */ + vignetteColor: Color4; /** - * The scene the component belongs to. + * Gets Camera field of view used by the Vignette effect. */ - scene: Scene; - frontColor: Color3; - backColor: Color3; - showBackLines: boolean; - renderList: SmartArray; - private _colorShader; - private _vertexBuffers; - private _indexBuffer; - constructor(scene: Scene); /** - * Registers the component in a given scene - */ - register(): void; - private _evaluateSubMesh(mesh, subMesh); - private _activeMesh(sourceMesh, mesh); - private _prepareRessources(); - private _createIndexBuffer(); + * Sets Camera field of view used by the Vignette effect. + */ + vignetteCameraFov: number; /** - * Rebuilds the elements related to this component in case of - * context lost for instance. + * Gets the vignette blend mode allowing different kind of effect. */ - rebuild(): void; - reset(): void; - render(): void; - renderOcclusionBoundingBox(mesh: AbstractMesh): void; - dispose(): void; - } -} - -declare module BABYLON { - /** - * This represents a depth renderer in Babylon. - * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing - */ - class DepthRenderer { - private _scene; - private _depthMap; - private _effect; - private _cachedDefines; - private _camera; /** - * Instantiates a depth renderer - * @param scene The scene the renderer belongs to - * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT) - * @param camera The camera to be used to render the depth map (default: scene's active camera) - */ - constructor(scene: Scene, type?: number, camera?: Nullable); + * Sets the vignette blend mode allowing different kind of effect. + */ + vignetteBlendMode: number; /** - * Creates the depth rendering effect and checks if the effect is ready. - * @param subMesh The submesh to be used to render the depth map of - * @param useInstances If multiple world instances should be used - * @returns if the depth renderer is ready to render the depth map + * Gets wether the vignette effect is enabled. */ - isReady(subMesh: SubMesh, useInstances: boolean): boolean; /** - * Gets the texture which the depth map will be written to. - * @returns The depth map texture + * Sets wether the vignette effect is enabled. + */ + vignetteEnabled: boolean; + private _fromLinearSpace; + /** + * Gets wether the input of the processing is in Gamma or Linear Space. */ - getDepthMap(): RenderTargetTexture; /** - * Disposes of the depth renderer. + * Sets wether the input of the processing is in Gamma or Linear Space. + */ + fromLinearSpace: boolean; + /** + * Defines cache preventing GC. */ - dispose(): void; + private _defines; + constructor(name: string, options: number | PostProcessOptions, camera?: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number, imageProcessingConfiguration?: ImageProcessingConfiguration); + getClassName(): string; + protected _updateParameters(): void; + dispose(camera?: Camera): void; } } declare module BABYLON { - class EdgesRenderer { - edgesWidthScalerForOrthographic: number; - edgesWidthScalerForPerspective: number; - private _source; - private _linesPositions; - private _linesNormals; - private _linesIndices; - private _epsilon; - private _indicesCount; - private _lineShader; - private _ib; - private _buffers; - private _checkVerticesInsteadOfIndices; - /** Gets or sets a boolean indicating if the edgesRenderer is active */ - isEnabled: boolean; - constructor(source: AbstractMesh, epsilon?: number, checkVerticesInsteadOfIndices?: boolean); - private _prepareRessources(); - - dispose(): void; - private _processEdgeForAdjacencies(pa, pb, p0, p1, p2); - private _processEdgeForAdjacenciesWithVertices(pa, pb, p0, p1, p2); - private _checkEdge(faceIndex, edge, faceNormals, p0, p1); - - render(): void; + class PassPostProcess extends PostProcess { + constructor(name: string, options: number | PostProcessOptions, camera?: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number, blockCompilation?: boolean); } } declare module BABYLON { + type PostProcessOptions = { + width: number; + height: number; + }; /** - * This renderer is helpfull to fill one of the render target with a geometry buffer. + * PostProcess can be used to apply a shader to a texture after it has been rendered + * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses */ - class GeometryBufferRenderer { - private _scene; - private _multiRenderTarget; - private _ratio; - private _enablePosition; - protected _effect: Effect; - protected _cachedDefines: string; + class PostProcess { + name: string; /** - * Set the render list (meshes to be rendered) used in the G buffer. - */ - renderList: Mesh[]; + * Width of the texture to apply the post process on + */ + width: number; /** - * Gets wether or not G buffer are supported by the running hardware. - * This requires draw buffer supports - */ - readonly isSupported: boolean; + * Height of the texture to apply the post process on + */ + height: number; /** - * Gets wether or not position are enabled for the G buffer. - */ + * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain) + */ + /** - * Sets wether or not position are enabled for the G buffer. - */ - enablePosition: boolean; + * Sampling mode used by the shader + * See https://doc.babylonjs.com/classes/3.1/texture + */ + renderTargetSamplingMode: number; /** - * Gets the scene associated with the buffer. - */ - readonly scene: Scene; + * Clear color to use when screen clearing + */ + clearColor: Color4; /** - * Gets the ratio used by the buffer during its creation. - * How big is the buffer related to the main canvas. - */ - readonly ratio: number; + * If the buffer needs to be cleared before applying the post process. (default: true) + * Should be set to false if shader will overwrite all previous pixels. + */ + autoClear: boolean; /** - * Creates a new G Buffer for the scene - * @param scene The scene the buffer belongs to - * @param ratio How big is the buffer related to the main canvas. - */ - constructor(scene: Scene, ratio?: number); + * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE) + */ + alphaMode: number; /** - * Checks wether everything is ready to render a submesh to the G buffer. - * @param subMesh the submesh to check readiness for - * @param useInstances is the mesh drawn using instance or not - * @returns true if ready otherwise false - */ - isReady(subMesh: SubMesh, useInstances: boolean): boolean; + * Sets the setAlphaBlendConstants of the babylon engine + */ + alphaConstants: Color4; /** - * Gets the current underlying G Buffer. - * @returns the buffer - */ - getGBuffer(): MultiRenderTarget; + * Animations to be used for the post processing + */ + animations: Animation[]; /** - * Gets the number of samples used to render the buffer (anti aliasing). + * Enable Pixel Perfect mode where texture is not scaled to be power of 2. + * Can only be used on a single postprocess or on the last one of a chain. (default: false) */ + enablePixelPerfectMode: boolean; /** - * Sets the number of samples used to render the buffer (anti aliasing). + * Force the postprocess to be applied without taking in account viewport */ + forceFullscreenViewport: boolean; + /** + * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR) + * + * | Value | Type | Description | + * | ----- | ----------------------------------- | ----------- | + * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) | + * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) | + * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) | + * + */ + scaleMode: number; + /** + * Force textures to be a power of two (default: false) + */ + alwaysForcePOT: boolean; + /** + * Number of sample textures (default: 1) + */ samples: number; /** - * Disposes the renderer and frees up associated resources. - */ - dispose(): void; - protected _createRenderTargets(): void; - } -} - -declare module BABYLON { - class OutlineRenderer { + * Modify the scale of the post process to be the same as the viewport (default: false) + */ + adaptScaleToCurrentViewport: boolean; + private _camera; private _scene; - private _effect; - private _cachedDefines; - zOffset: number; - constructor(scene: Scene); - render(subMesh: SubMesh, batch: _InstancesBatch, useOverlay?: boolean): void; - isReady(subMesh: SubMesh, useInstances: boolean): boolean; - } -} + private _engine; + private _options; + private _reusable; + private _textureType; + /** + * Smart array of input and output textures for the post process. + */ -declare module BABYLON { - class RenderingGroup { - index: number; - private _scene; - private _opaqueSubMeshes; - private _transparentSubMeshes; - private _alphaTestSubMeshes; - private _depthOnlySubMeshes; - private _particleSystems; - private _spriteManagers; - private _opaqueSortCompareFn; - private _alphaTestSortCompareFn; - private _transparentSortCompareFn; - private _renderOpaque; - private _renderAlphaTest; - private _renderTransparent; - private _edgesRenderers; - onBeforeTransparentRendering: () => void; /** - * Set the opaque sort comparison function. - * If null the sub meshes will be render in the order they were created - */ - opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number>; + * The index in _textures that corresponds to the output texture. + */ + + private _effect; + private _samplers; + private _fragmentUrl; + private _vertexUrl; + private _parameters; + private _scaleRatio; + protected _indexParameters: any; + private _shareOutputWithPostProcess; + private _texelSize; + private _forcedOutputTexture; /** - * Set the alpha test sort comparison function. - * If null the sub meshes will be render in the order they were created - */ - alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number>; + * An event triggered when the postprocess is activated. + */ + onActivateObservable: Observable; + private _onActivateObserver; /** - * Set the transparent sort comparison function. - * If null the sub meshes will be render in the order they were created - */ - transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number>; + * A function that is added to the onActivateObservable + */ + onActivate: Nullable<(camera: Camera) => void>; /** - * Creates a new rendering group. - * @param index The rendering group index - * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied - * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied - * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied - */ - constructor(index: number, scene: Scene, opaqueSortCompareFn?: Nullable<(a: SubMesh, b: SubMesh) => number>, alphaTestSortCompareFn?: Nullable<(a: SubMesh, b: SubMesh) => number>, transparentSortCompareFn?: Nullable<(a: SubMesh, b: SubMesh) => number>); + * An event triggered when the postprocess changes its size. + */ + onSizeChangedObservable: Observable; + private _onSizeChangedObserver; /** - * Render all the sub meshes contained in the group. - * @param customRenderFunction Used to override the default render behaviour of the group. - * @returns true if rendered some submeshes. - */ - render(customRenderFunction: Nullable<(opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, depthOnlySubMeshes: SmartArray) => void>, renderSprites: boolean, renderParticles: boolean, activeMeshes: Nullable): void; + * A function that is added to the onSizeChangedObservable + */ + onSizeChanged: (postProcess: PostProcess) => void; /** - * Renders the opaque submeshes in the order from the opaqueSortCompareFn. - * @param subMeshes The submeshes to render - */ - private renderOpaqueSorted(subMeshes); + * An event triggered when the postprocess applies its effect. + */ + onApplyObservable: Observable; + private _onApplyObserver; /** - * Renders the opaque submeshes in the order from the alphatestSortCompareFn. - * @param subMeshes The submeshes to render - */ - private renderAlphaTestSorted(subMeshes); + * A function that is added to the onApplyObservable + */ + onApply: (effect: Effect) => void; /** - * Renders the opaque submeshes in the order from the transparentSortCompareFn. - * @param subMeshes The submeshes to render - */ - private renderTransparentSorted(subMeshes); + * An event triggered before rendering the postprocess + */ + onBeforeRenderObservable: Observable; + private _onBeforeRenderObserver; /** - * Renders the submeshes in a specified order. - * @param subMeshes The submeshes to sort before render - * @param sortCompareFn The comparison function use to sort - * @param cameraPosition The camera position use to preprocess the submeshes to help sorting - * @param transparent Specifies to activate blending if true - */ - private static renderSorted(subMeshes, sortCompareFn, camera, transparent); + * A function that is added to the onBeforeRenderObservable + */ + onBeforeRender: (effect: Effect) => void; /** - * Renders the submeshes in the order they were dispatched (no sort applied). - * @param subMeshes The submeshes to render - */ - private static renderUnsorted(subMeshes); + * An event triggered after rendering the postprocess + */ + onAfterRenderObservable: Observable; + private _onAfterRenderObserver; /** - * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) - * are rendered back to front if in the same alpha index. - * - * @param a The first submesh - * @param b The second submesh - * @returns The result of the comparison - */ - static defaultTransparentSortCompare(a: SubMesh, b: SubMesh): number; + * A function that is added to the onAfterRenderObservable + */ + onAfterRender: (efect: Effect) => void; /** - * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) - * are rendered back to front. - * - * @param a The first submesh - * @param b The second submesh - * @returns The result of the comparison - */ - static backToFrontSortCompare(a: SubMesh, b: SubMesh): number; + * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will + * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process. + */ + inputTexture: InternalTexture; /** - * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) - * are rendered front to back (prevent overdraw). - * - * @param a The first submesh - * @param b The second submesh - * @returns The result of the comparison - */ - static frontToBackSortCompare(a: SubMesh, b: SubMesh): number; + * Gets the camera which post process is applied to. + * @returns The camera the post process is applied to. + */ + getCamera(): Camera; /** - * Resets the different lists of submeshes to prepare a new frame. - */ - prepare(): void; - dispose(): void; + * Gets the texel size of the postprocess. + * See https://en.wikipedia.org/wiki/Texel_(graphics) + */ + readonly texelSize: Vector2; /** - * Inserts the submesh in its correct queue depending on its material. - * @param subMesh The submesh to dispatch - * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance. - * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance. + * Creates a new instance PostProcess + * @param name The name of the PostProcess. + * @param fragmentUrl The url of the fragment shader to be used. + * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader. + * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader. + * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size) + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param defines String of defines that will be set when running the fragment shader. (default: null) + * @param textureType Type of textures used when performing the post process. (default: 0) + * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess") + * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx + * @param blockCompilation If the shader should not be compiled imediatly. (default: false) */ - dispatch(subMesh: SubMesh, mesh?: AbstractMesh, material?: Nullable): void; - dispatchSprites(spriteManager: SpriteManager): void; - dispatchParticles(particleSystem: IParticleSystem): void; - private _renderParticles(activeMeshes); - private _renderSprites(); - } -} - -declare module BABYLON { - /** - * Interface describing the different options available in the rendering manager - * regarding Auto Clear between groups. - */ - interface IRenderingManagerAutoClearSetup { + constructor(/** Name of the PostProcess. */ name: string, fragmentUrl: string, parameters: Nullable, samplers: Nullable, options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, defines?: Nullable, textureType?: number, vertexUrl?: string, indexParameters?: any, blockCompilation?: boolean); /** - * Defines whether or not autoclear is enable. + * Gets the engine which this post process belongs to. + * @returns The engine the post process was enabled with. */ - autoClear: boolean; + getEngine(): Engine; /** - * Defines whether or not to autoclear the depth buffer. + * The effect that is created when initializing the post process. + * @returns The created effect corrisponding the the postprocess. */ - depth: boolean; + getEffect(): Effect; /** - * Defines whether or not to autoclear the stencil buffer. + * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another. + * @param postProcess The post process to share the output with. + * @returns This post process. */ - stencil: boolean; - } - class RenderingManager { + shareOutputWith(postProcess: PostProcess): PostProcess; /** - * The max id used for rendering groups (not included) + * Reverses the effect of calling shareOutputWith and returns the post process back to its original state. + * This should be called if the post process that shares output with this post process is disabled/disposed. */ - static MAX_RENDERINGGROUPS: number; + useOwnOutput(): void; /** - * The min id used for rendering groups (included) + * Updates the effect with the current post process compile time values and recompiles the shader. + * @param defines Define statements that should be added at the beginning of the shader. (default: null) + * @param uniforms Set of uniform variables that will be passed to the shader. (default: null) + * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null) + * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx + * @param onCompiled Called when the shader has been compiled. + * @param onError Called if there is an error when compiling a shader. */ - static MIN_RENDERINGGROUPS: number; + updateEffect(defines?: Nullable, uniforms?: Nullable, samplers?: Nullable, indexParameters?: any, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): void; /** - * Used to globally prevent autoclearing scenes. + * The post process is reusable if it can be used multiple times within one frame. + * @returns If the post process is reusable */ - static AUTOCLEAR: boolean; + isReusable(): boolean; + /** invalidate frameBuffer to hint the postprocess to create a depth buffer */ + markTextureDirty(): void; /** - * Hidden + * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable. + * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous. + * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable. + * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null) + * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false) + * @returns The target texture that was bound to be written to. */ - - private _scene; - private _renderingGroups; - private _depthStencilBufferAlreadyCleaned; - private _autoClearDepthStencil; - private _customOpaqueSortCompareFn; - private _customAlphaTestSortCompareFn; - private _customTransparentSortCompareFn; - private _renderingGroupInfo; - constructor(scene: Scene); - private _clearDepthStencilBuffer(depth?, stencil?); - render(customRenderFunction: Nullable<(opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, depthOnlySubMeshes: SmartArray) => void>, activeMeshes: Nullable, renderParticles: boolean, renderSprites: boolean): void; - reset(): void; - dispose(): void; + activate(camera: Nullable, sourceTexture?: Nullable, forceDepthStencil?: boolean): InternalTexture; /** - * Clear the info related to rendering groups preventing retention points during dispose. + * If the post process is supported. */ - freeRenderingGroups(): void; - private _prepareRenderingGroup(renderingGroupId); - dispatchSprites(spriteManager: SpriteManager): void; - dispatchParticles(particleSystem: IParticleSystem): void; + readonly isSupported: boolean; /** - * @param subMesh The submesh to dispatch - * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance. - * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance. + * The aspect ratio of the output texture. */ - dispatch(subMesh: SubMesh, mesh?: AbstractMesh, material?: Nullable): void; + readonly aspectRatio: number; /** - * Overrides the default sort function applied in the renderging group to prepare the meshes. - * This allowed control for front to back rendering or reversly depending of the special needs. - * - * @param renderingGroupId The rendering group id corresponding to its index - * @param opaqueSortCompareFn The opaque queue comparison function use to sort. - * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. - * @param transparentSortCompareFn The transparent queue comparison function use to sort. + * Get a value indicating if the post-process is ready to be used + * @returns true if the post-process is ready (shader is compiled) */ - setRenderingOrder(renderingGroupId: number, opaqueSortCompareFn?: Nullable<(a: SubMesh, b: SubMesh) => number>, alphaTestSortCompareFn?: Nullable<(a: SubMesh, b: SubMesh) => number>, transparentSortCompareFn?: Nullable<(a: SubMesh, b: SubMesh) => number>): void; + isReady(): boolean; /** - * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. - * - * @param renderingGroupId The rendering group id corresponding to its index - * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. - * @param depth Automatically clears depth between groups if true and autoClear is true. - * @param stencil Automatically clears stencil between groups if true and autoClear is true. + * Binds all textures and uniforms to the shader, this will be run on every pass. + * @returns the effect corrisponding to this post process. Null if not compiled or not ready. */ - setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean, depth?: boolean, stencil?: boolean): void; + apply(): Nullable; + private _disposeTextures; /** - * Gets the current auto clear configuration for one rendering group of the rendering - * manager. - * @param index the rendering group index to get the information for - * @returns The auto clear setup for the requested rendering group + * Disposes the post process. + * @param camera The camera to dispose the post process on. */ - getAutoClearDepthStencilSetup(index: number): IRenderingManagerAutoClearSetup; + dispose(camera?: Camera): void; } } declare module BABYLON { /** - * Renders a layer on top of an existing scene + * PostProcessManager is used to manage one or more post processes or post process pipelines + * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses */ - class UtilityLayerRenderer implements IDisposable { - /** the original scene that will be rendered on top of */ originalScene: Scene; - private _pointerCaptures; - private _lastPointerEvents; - private static _DefaultUtilityLayer; - private static _DefaultKeepDepthUtilityLayer; - /** - * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it) - */ - static readonly DefaultUtilityLayer: UtilityLayerRenderer; - /** - * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it) - */ - static readonly DefaultKeepDepthUtilityLayer: UtilityLayerRenderer; - /** - * The scene that is rendered on top of the original scene - */ - utilityLayerScene: Scene; - /** - * If the utility layer should automatically be rendered on top of existing scene - */ - shouldRender: boolean; + class PostProcessManager { + private _scene; + private _indexBuffer; + private _vertexBuffers; /** - * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene + * Creates a new instance PostProcess + * @param scene The scene that the post process is associated with. */ - onlyCheckPointerDownEvents: boolean; + constructor(scene: Scene); + private _prepareBuffers; + private _buildIndexBuffer; /** - * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default) + * Rebuilds the vertex buffers of the manager. */ - processAllEvents: boolean; + /** - * Observable raised when the pointer move from the utility layer scene to the main scene + * Prepares a frame to be run through a post process. + * @param sourceTexture The input texture to the post procesess. (default: null) + * @param postProcesses An array of post processes to be run. (default: null) + * @returns True if the post processes were able to be run. */ - onPointerOutObservable: Observable; - /** Gets or sets a predicate that will be used to indicate utility meshes present in the main scene */ - mainSceneTrackerPredicate: (mesh: Nullable) => boolean; - private _afterRenderObserver; - private _sceneDisposeObserver; - private _originalPointerObserver; + /** - * Instantiates a UtilityLayerRenderer - * @param originalScene the original scene that will be rendered on top of + * Manually render a set of post processes to a texture. + * @param postProcesses An array of post processes to be run. + * @param targetTexture The target texture to render to. + * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight + * @param faceIndex defines the face to render to if a cubemap is defined as the target + * @param lodLevel defines which lod of the texture to render to */ - constructor(/** the original scene that will be rendered on top of */ originalScene: Scene); - private _notifyObservers(prePointerInfo, pickInfo, pointerEvent); + directRender(postProcesses: PostProcess[], targetTexture?: Nullable, forceFullscreenViewport?: boolean, faceIndex?: number, lodLevel?: number): void; /** - * Renders the utility layers scene on top of the original scene + * Finalize the result of the output of the postprocesses. + * @param doNotPresent If true the result will not be displayed to the screen. + * @param targetTexture The target texture to render to. + * @param faceIndex The index of the face to bind the target texture to. + * @param postProcesses The array of post processes to render. + * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false) */ - render(): void; + /** - * Disposes of the renderer + * Disposes of the post process manager. */ dispose(): void; - private _updateCamera(); } } declare module BABYLON { - class Sprite { - name: string; - position: Vector3; - color: Color4; - width: number; - height: number; - angle: number; - cellIndex: number; - invertU: number; - invertV: number; - disposeWhenFinishedAnimating: boolean; - animations: Animation[]; - isPickable: boolean; - actionManager: ActionManager; - private _animationStarted; - private _loopAnimation; - private _fromIndex; - private _toIndex; - private _delay; - private _direction; - private _manager; - private _time; - private _onAnimationEnd; + class RefractionPostProcess extends PostProcess { + color: Color3; + depth: number; + colorLevel: number; + private _refTexture; + private _ownRefractionTexture; /** - * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true + * Gets or sets the refraction texture + * Please note that you are responsible for disposing the texture if you set it manually */ - isVisible: boolean; - size: number; - constructor(name: string, manager: SpriteManager); - playAnimation(from: number, to: number, loop: boolean, delay: number, onAnimationEnd: () => void): void; - stopAnimation(): void; - - dispose(): void; + refractionTexture: Texture; + constructor(name: string, refractionTextureUrl: string, color: Color3, depth: number, colorLevel: number, options: number | PostProcessOptions, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + dispose(camera: Camera): void; } } declare module BABYLON { - class SpriteManager { - name: string; - sprites: Sprite[]; - renderingGroupId: number; - layerMask: number; - fogEnabled: boolean; - isPickable: boolean; - cellWidth: number; - cellHeight: number; + /** + * The SharpenPostProcess applies a sharpen kernel to every pixel + * See http://en.wikipedia.org/wiki/Kernel_(image_processing) + */ + class SharpenPostProcess extends PostProcess { /** - * An event triggered when the manager is disposed. - */ - onDisposeObservable: Observable; - private _onDisposeObserver; - onDispose: () => void; - private _capacity; - private _spriteTexture; - private _epsilon; - private _scene; - private _vertexData; - private _buffer; - private _vertexBuffers; - private _indexBuffer; - private _effectBase; - private _effectFog; - texture: Texture; - constructor(name: string, imgUrl: string, capacity: number, cellSize: any, scene: Scene, epsilon?: number, samplingMode?: number); - private _appendSpriteVertex(index, sprite, offsetX, offsetY, rowSize); - intersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean): Nullable; - render(): void; - dispose(): void; + * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1) + */ + colorAmount: number; + /** + * How much sharpness should be applied (default: 0.3) + */ + edgeAmount: number; + /** + * Creates a new instance ConvolutionPostProcess + * @param name The name of the effect. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType Type of textures used when performing the post process. (default: 0) + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + */ + constructor(name: string, options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number, blockCompilation?: boolean); + } +} + +declare module BABYLON { + class StereoscopicInterlacePostProcess extends PostProcess { + private _stepSize; + private _passedProcess; + constructor(name: string, rigCameras: Camera[], isStereoscopicHoriz: boolean, samplingMode?: number, engine?: Engine, reusable?: boolean); } } declare module BABYLON { + /** Defines operator used for tonemapping */ + enum TonemappingOperator { + /** Hable */ + Hable = 0, + /** Reinhard */ + Reinhard = 1, + /** HejiDawson */ + HejiDawson = 2, + /** Photographic */ + Photographic = 3 + } /** - * @hidden - **/ - class _AlphaState { - private _isAlphaBlendDirty; - private _isBlendFunctionParametersDirty; - private _isBlendEquationParametersDirty; - private _isBlendConstantsDirty; - private _alphaBlend; - private _blendFunctionParameters; - private _blendEquationParameters; - private _blendConstants; + * Defines a post process to apply tone mapping + */ + class TonemapPostProcess extends PostProcess { + private _operator; + /** Defines the required exposure adjustement */ + exposureAdjustment: number; /** - * Initializes the state. + * Creates a new TonemapPostProcess + * @param name defines the name of the postprocess + * @param _operator defines the operator to use + * @param exposureAdjustment defines the required exposure adjustement + * @param camera defines the camera to use (can be null) + * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default) + * @param engine defines the hosting engine (can be ignore if camera is set) + * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default) */ - constructor(); - readonly isDirty: boolean; - alphaBlend: boolean; - setAlphaBlendConstants(r: number, g: number, b: number, a: number): void; - setAlphaBlendFunctionParameters(value0: number, value1: number, value2: number, value3: number): void; - setAlphaEquationParameters(rgb: number, alpha: number): void; - reset(): void; - apply(gl: WebGLRenderingContext): void; + constructor(name: string, _operator: TonemappingOperator, + /** Defines the required exposure adjustement */ + exposureAdjustment: number, camera: Camera, samplingMode?: number, engine?: Engine, textureFormat?: number); } } declare module BABYLON { - /** - * @hidden - **/ - class _DepthCullingState { - private _isDepthTestDirty; - private _isDepthMaskDirty; - private _isDepthFuncDirty; - private _isCullFaceDirty; - private _isCullDirty; - private _isZOffsetDirty; - private _isFrontFaceDirty; - private _depthTest; - private _depthMask; - private _depthFunc; - private _cull; - private _cullFace; - private _zOffset; - private _frontFace; + class VolumetricLightScatteringPostProcess extends PostProcess { + private _volumetricLightScatteringPass; + private _volumetricLightScatteringRTT; + private _viewPort; + private _screenCoordinates; + private _cachedDefines; /** - * Initializes the state. + * If not undefined, the mesh position is computed from the attached node position + */ + attachedNode: { + position: Vector3; + }; + /** + * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true" + */ + customMeshPosition: Vector3; + /** + * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false) + */ + useCustomMeshPosition: boolean; + /** + * If the post-process should inverse the light scattering direction + */ + invert: boolean; + /** + * The internal mesh used by the post-process + */ + mesh: Mesh; + useDiffuseColor: boolean; + /** + * Array containing the excluded meshes not rendered in the internal pass + */ + excludedMeshes: AbstractMesh[]; + /** + * Controls the overall intensity of the post-process + */ + exposure: number; + /** + * Dissipates each sample's contribution in range [0, 1] + */ + decay: number; + /** + * Controls the overall intensity of each sample + */ + weight: number; + /** + * Controls the density of each sample + */ + density: number; + /** + * @constructor + * @param {string} name - The post-process name + * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) + * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to + * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering + * @param {number} samples - The post-process quality, default 100 + * @param {number} samplingMode - The post-process filtering mode + * @param {BABYLON.Engine} engine - The babylon engine + * @param {boolean} reusable - If the post-process is reusable + * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided */ - constructor(); - readonly isDirty: boolean; - zOffset: number; - cullFace: Nullable; - cull: Nullable; - depthFunc: Nullable; - depthMask: boolean; - depthTest: boolean; - frontFace: Nullable; - reset(): void; - apply(gl: WebGLRenderingContext): void; + constructor(name: string, ratio: any, camera: Camera, mesh?: Mesh, samples?: number, samplingMode?: number, engine?: Engine, reusable?: boolean, scene?: Scene); + getClassName(): string; + private _isReady; + /** + * Sets the new light position for light scattering effect + * @param {BABYLON.Vector3} The new custom light position + */ + setCustomMeshPosition(position: Vector3): void; + /** + * Returns the light position for light scattering effect + * @return {BABYLON.Vector3} The custom light position + */ + getCustomMeshPosition(): Vector3; + /** + * Disposes the internal assets and detaches the post-process from the camera + */ + dispose(camera: Camera): void; + /** + * Returns the render target texture used by the post-process + * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process + */ + getPass(): RenderTargetTexture; + private _meshExcluded; + private _createPass; + private _updateMeshScreenCoordinates; + /** + * Creates a default mesh for the Volumeric Light Scattering post-process + * @param {string} The mesh name + * @param {BABYLON.Scene} The scene where to create the mesh + * @return {BABYLON.Mesh} the default mesh + */ + static CreateDefaultMesh(name: string, scene: Scene): Mesh; } } declare module BABYLON { - /** - * @hidden - **/ - class _StencilState { - private _isStencilTestDirty; - private _isStencilMaskDirty; - private _isStencilFuncDirty; - private _isStencilOpDirty; - private _stencilTest; - private _stencilMask; - private _stencilFunc; - private _stencilFuncRef; - private _stencilFuncMask; - private _stencilOpStencilFail; - private _stencilOpDepthFail; - private _stencilOpStencilDepthPass; - readonly isDirty: boolean; - stencilFunc: number; - stencilFuncRef: number; - stencilFuncMask: number; - stencilOpStencilFail: number; - stencilOpDepthFail: number; - stencilOpStencilDepthPass: number; - stencilMask: number; - stencilTest: boolean; - constructor(); - reset(): void; - apply(gl: WebGLRenderingContext): void; + class VRDistortionCorrectionPostProcess extends PostProcess { + private _isRightEye; + private _distortionFactors; + private _postProcessScaleFactor; + private _lensCenterOffset; + private _scaleIn; + private _scaleFactor; + private _lensCenter; + constructor(name: string, camera: Camera, isRightEye: boolean, vrMetrics: VRCameraMetrics); } } @@ -28684,8 +28691,8 @@ declare module BABYLON { * @returns true if the query matches */ static Eval(query: string, evaluateCallback: (val: any) => boolean): boolean; - private static _HandleParenthesisContent(parenthesisContent, evaluateCallback); - private static _SimplifyNegation(booleanString); + private static _HandleParenthesisContent; + private static _SimplifyNegation; } } @@ -28709,7 +28716,7 @@ declare module BABYLON { /** * Error */ - ERROR = 3, + ERROR = 3 } /** * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene @@ -28731,9 +28738,9 @@ declare module BABYLON { * @param name defines the name of the task */ constructor( - /** - * Task name - */ name: string); + /** + * Task name + */ name: string); private _isCompleted; private _taskState; private _errorObject; @@ -28776,8 +28783,8 @@ declare module BABYLON { * This can be used with failed tasks that have the reason for failure fixed. */ reset(): void; - private onErrorCallback(onError, message?, exception?); - private onDoneCallback(onSuccess, onError); + private onErrorCallback; + private onDoneCallback; } /** * Define the interface used by progress events raised during assets loading @@ -28868,22 +28875,22 @@ declare module BABYLON { * @param sceneFilename defines the filename of the scene to load from */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the list of mesh's names you want to load - */ - meshesNames: any, - /** - * Defines the root url to use as a base to load your meshes and associated resources - */ - rootUrl: string, - /** - * Defines the filename of the scene to load from - */ - sceneFilename: string); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the list of mesh's names you want to load + */ + meshesNames: any, + /** + * Defines the root url to use as a base to load your meshes and associated resources + */ + rootUrl: string, + /** + * Defines the filename of the scene to load from + */ + sceneFilename: string); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -28922,14 +28929,14 @@ declare module BABYLON { * @param url defines the location of the file to load */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the location of the file to load - */ - url: string); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the location of the file to load + */ + url: string); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -28968,14 +28975,14 @@ declare module BABYLON { * @param url defines the location of the file to load */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the location of the file to load - */ - url: string); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the location of the file to load + */ + url: string); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -29014,14 +29021,14 @@ declare module BABYLON { * @param url defines the location of the image to load */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the location of the image to load - */ - url: string); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the location of the image to load + */ + url: string); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -29054,11 +29061,11 @@ declare module BABYLON { /** * Defines if mipmap should not be generated (default is false) */ - noMipmap: boolean | undefined; + noMipmap?: boolean | undefined; /** * Defines if texture must be inverted on Y axis (default is false) */ - invertY: boolean | undefined; + invertY?: boolean | undefined; /** * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE) */ @@ -29084,26 +29091,26 @@ declare module BABYLON { * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE) */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the location of the file to load - */ - url: string, - /** - * Defines if mipmap should not be generated (default is false) - */ - noMipmap?: boolean | undefined, - /** - * Defines if texture must be inverted on Y axis (default is false) - */ - invertY?: boolean | undefined, - /** - * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE) - */ - samplingMode?: number); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the location of the file to load + */ + url: string, + /** + * Defines if mipmap should not be generated (default is false) + */ + noMipmap?: boolean | undefined, + /** + * Defines if texture must be inverted on Y axis (default is false) + */ + invertY?: boolean | undefined, + /** + * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE) + */ + samplingMode?: number); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -29127,15 +29134,15 @@ declare module BABYLON { /** * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default) */ - extensions: string[] | undefined; + extensions?: string[] | undefined; /** * Defines if mipmaps should not be generated (default is false) */ - noMipmap: boolean | undefined; + noMipmap?: boolean | undefined; /** * Defines the explicit list of files (undefined by default) */ - files: string[] | undefined; + files?: string[] | undefined; /** * Gets the loaded texture */ @@ -29157,26 +29164,26 @@ declare module BABYLON { * @param files defines the explicit list of files (undefined by default) */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension) - */ - url: string, - /** - * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default) - */ - extensions?: string[] | undefined, - /** - * Defines if mipmaps should not be generated (default is false) - */ - noMipmap?: boolean | undefined, - /** - * Defines the explicit list of files (undefined by default) - */ - files?: string[] | undefined); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension) + */ + url: string, + /** + * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default) + */ + extensions?: string[] | undefined, + /** + * Defines if mipmaps should not be generated (default is false) + */ + noMipmap?: boolean | undefined, + /** + * Defines the explicit list of files (undefined by default) + */ + files?: string[] | undefined); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -29240,34 +29247,34 @@ declare module BABYLON { * @param reserved Internal use only */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the location of the file to load - */ - url: string, - /** - * Defines the desired size (the more it increases the longer the generation will be) - */ - size: number, - /** - * Defines if mipmaps should not be generated (default is false) - */ - noMipmap?: boolean, - /** - * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true) - */ - generateHarmonics?: boolean, - /** - * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false) - */ - gammaSpace?: boolean, - /** - * Internal Use Only - */ - reserved?: boolean); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the location of the file to load + */ + url: string, + /** + * Defines the desired size (the more it increases the longer the generation will be) + */ + size: number, + /** + * Defines if mipmaps should not be generated (default is false) + */ + noMipmap?: boolean, + /** + * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true) + */ + generateHarmonics?: boolean, + /** + * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false) + */ + gammaSpace?: boolean, + /** + * Internal Use Only + */ + reserved?: boolean); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -29396,8 +29403,8 @@ declare module BABYLON { * @param task the task to remove */ removeTask(task: AbstractAssetTask): void; - private _decreaseWaitingTasksCount(task); - private _runTask(task); + private _decreaseWaitingTasksCount; + private _runTask; /** * Reset the {BABYLON.AssetsManager} and remove all tasks * @return the current instance of the {BABYLON.AssetsManager} @@ -29448,7 +29455,7 @@ declare module BABYLON { constructor(urlToScene: string, callbackManifestChecked: (checked: boolean) => any, disableManifestCheck?: boolean); private static _ParseURL; private static _ReturnFullUrlLocation; - private _checkManifestFile(); + private _checkManifestFile; /** * Open the database and make it available * @param successCallback defines the callback to call on success @@ -29461,11 +29468,11 @@ declare module BABYLON { * @param image defines the target DOM image */ loadImageFromDB(url: string, image: HTMLImageElement): void; - private _loadImageFromDBAsync(url, image, notInDBCallback); - private _saveImageIntoDBAsync(url, image); - private _checkVersionFromDB(url, versionLoaded); - private _loadVersionFromDBAsync(url, callback, updateInDBCallback); - private _saveVersionIntoDBAsync(url, callback); + private _loadImageFromDBAsync; + private _saveImageIntoDBAsync; + private _checkVersionFromDB; + private _loadVersionFromDBAsync; + private _saveVersionIntoDBAsync; /** * Loads a file from database * @param url defines the URL to load from @@ -29475,8 +29482,8 @@ declare module BABYLON { * @param useArrayBuffer defines a boolean to use array buffer instead of text string */ loadFileFromDB(url: string, sceneLoaded: (data: any) => void, progressCallBack?: (data: any) => void, errorCallback?: () => void, useArrayBuffer?: boolean): void; - private _loadFileFromDBAsync(url, callback, notInDBCallback, useArrayBuffer?); - private _saveFileIntoDBAsync(url, callback, progressCallback?, useArrayBuffer?, errorCallback?); + private _loadFileFromDBAsync; + private _saveFileIntoDBAsync; } } @@ -29500,17 +29507,17 @@ declare module BABYLON { static GetDDSInfo(arrayBuffer: any): DDSInfo; private static _FloatView; private static _Int32View; - private static _ToHalfFloat(value); - private static _FromHalfFloat(value); - private static _GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod); - private static _GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod); - private static _GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod); - private static _GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod); - private static _GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod); - private static _GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset); - private static _ExtractLongWordOrder(value); - private static _GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset); - private static _GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); + private static _ToHalfFloat; + private static _FromHalfFloat; + private static _GetHalfFloatAsFloatRGBAArrayBuffer; + private static _GetHalfFloatRGBAArrayBuffer; + private static _GetFloatRGBAArrayBuffer; + private static _GetFloatAsUIntRGBAArrayBuffer; + private static _GetHalfFloatAsUIntRGBAArrayBuffer; + private static _GetRGBAArrayBuffer; + private static _ExtractLongWordOrder; + private static _GetRGBArrayBuffer; + private static _GetLuminanceArrayBuffer; /** * Uploads DDS Levels to a Babylon Texture * @hidden @@ -29620,7 +29627,7 @@ declare module BABYLON { * @param texture defines the texture containing the polynomials * @return the JSON representation of the spherical info */ - private static _CreateEnvTextureIrradiance(texture); + private static _CreateEnvTextureIrradiance; /** * Uploads the texture info contained in the env file to the GPU. * @param texture defines the internal texture to upload to @@ -29669,13 +29676,13 @@ declare module BABYLON { private _dropHandler; monitorElementForDragNDrop(elementToMonitor: HTMLElement): void; dispose(): void; - private renderFunction(); - private drag(e); - private drop(eventDrop); - private _traverseFolder(folder, files, remaining, callback); - private _processFiles(files); + private renderFunction; + private drag; + private drop; + private _traverseFolder; + private _processFiles; loadFiles(event: any): void; - private _processReload(); + private _processReload; reload(): void; } } @@ -29719,7 +29726,7 @@ declare module BABYLON { * @hidden */ uploadLevels(texture: InternalTexture, loadMipmaps: boolean): void; - private _upload2DCompressedLevels(texture, loadMipmaps); + private _upload2DCompressedLevels; } } @@ -29796,18 +29803,18 @@ declare module BABYLON { * @param scope defines the current scope used to restore the JS context */ constructor( - /** - * Defines the callback to call when the observer is notified - */ - callback: (eventData: T, eventState: EventState) => void, - /** - * Defines the mask of the observer (used to filter notifications) - */ - mask: number, - /** - * Defines the current scope used to restore the JS context - */ - scope?: any); + /** + * Defines the callback to call when the observer is notified + */ + callback: (eventData: T, eventState: EventState) => void, + /** + * Defines the mask of the observer (used to filter notifications) + */ + mask: number, + /** + * Defines the current scope used to restore the JS context + */ + scope?: any); } /** * Represent a list of observers registered to multiple Observables object. @@ -29875,8 +29882,8 @@ declare module BABYLON { * @returns false if it doesn't belong to this Observable */ removeCallback(callback: (eventData: T, eventState: EventState) => void, scope?: any): boolean; - private _deferUnregister(observer); - private _remove(observer); + private _deferUnregister; + private _remove; /** * Notify all Observers by calling their respective callback with the given data * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute @@ -30092,10 +30099,10 @@ declare module BABYLON { * @param desc defines the description associated with the optimization */ constructor( - /** - * Defines the priority of this optimization (0 by default which means first in the list) - */ - priority?: number); + /** + * Defines the priority of this optimization (0 by default which means first in the list) + */ + priority?: number); } /** * Defines an optimization used to reduce the size of render target textures @@ -30126,18 +30133,18 @@ declare module BABYLON { * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed. */ constructor( - /** - * Defines the priority of this optimization (0 by default which means first in the list) - */ - priority?: number, - /** - * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter - */ - maximumSize?: number, - /** - * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed. - */ - step?: number); + /** + * Defines the priority of this optimization (0 by default which means first in the list) + */ + priority?: number, + /** + * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter + */ + maximumSize?: number, + /** + * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed. + */ + step?: number); /** * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization * @param scene defines the current scene where to apply this optimization @@ -30177,18 +30184,18 @@ declare module BABYLON { * @param step defines the step to use between two passes (0.5 by default) */ constructor( - /** - * Defines the priority of this optimization (0 by default which means first in the list) - */ - priority?: number, - /** - * Defines the maximum scale to use (2 by default) - */ - maximumScale?: number, - /** - * Defines the step to use between two passes (0.5 by default) - */ - step?: number); + /** + * Defines the priority of this optimization (0 by default which means first in the list) + */ + priority?: number, + /** + * Defines the maximum scale to use (2 by default) + */ + maximumScale?: number, + /** + * Defines the step to use between two passes (0.5 by default) + */ + step?: number); /** * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization * @param scene defines the current scene where to apply this optimization @@ -30323,8 +30330,8 @@ declare module BABYLON { * Gets or sets a boolean which defines if optimization octree has to be updated */ /** - * Gets or sets a boolean which defines if optimization octree has to be updated - */ + * Gets or sets a boolean which defines if optimization octree has to be updated + */ static UpdateSelectionTree: boolean; /** * Gets a string describing the action executed by the current optimization @@ -30364,14 +30371,14 @@ declare module BABYLON { * @param trackerDuration defines the interval between two checkes (2000ms by default) */ constructor( - /** - * Defines the target frame rate to reach (60 by default) - */ - targetFrameRate?: number, - /** - * Defines the interval between two checkes (2000ms by default) - */ - trackerDuration?: number); + /** + * Defines the target frame rate to reach (60 by default) + */ + targetFrameRate?: number, + /** + * Defines the interval between two checkes (2000ms by default) + */ + trackerDuration?: number); /** * Add a new optimization * @param optimization defines the SceneOptimization to add to the list of active optimizations @@ -30447,15 +30454,15 @@ declare module BABYLON { * Gets or sets the current target frame rate (60 by default) */ /** - * Gets or sets the current target frame rate (60 by default) - */ + * Gets or sets the current target frame rate (60 by default) + */ targetFrameRate: number; /** * Gets or sets the current interval between two checks (every 2000ms by default) */ /** - * Gets or sets the current interval between two checks (every 2000ms by default) - */ + * Gets or sets the current interval between two checks (every 2000ms by default) + */ trackerDuration: number; /** * Gets the list of active optimizations @@ -30482,7 +30489,7 @@ declare module BABYLON { * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate */ start(): void; - private _checkCurrentState(); + private _checkCurrentState; /** * Release all resources */ @@ -30729,7 +30736,7 @@ declare module BABYLON { getFactor(): number; } class LoadFileError extends Error { - request: XMLHttpRequest | undefined; + request?: XMLHttpRequest | undefined; private static _setPrototypeOf; constructor(message: string, request?: XMLHttpRequest | undefined); } @@ -30964,14 +30971,14 @@ declare module BABYLON { static readonly WarningLogLevel: number; static readonly ErrorLogLevel: number; static readonly AllLogLevel: number; - private static _AddLogEntry(entry); - private static _FormatMessage(message); - private static _LogDisabled(message); - private static _LogEnabled(message); - private static _WarnDisabled(message); - private static _WarnEnabled(message); - private static _ErrorDisabled(message); - private static _ErrorEnabled(message); + private static _AddLogEntry; + private static _FormatMessage; + private static _LogDisabled; + private static _LogEnabled; + private static _WarnDisabled; + private static _WarnEnabled; + private static _ErrorDisabled; + private static _ErrorEnabled; static Log: (message: string) => void; static Warn: (message: string) => void; static Error: (message: string) => void; @@ -31090,7 +31097,7 @@ private static _EndPerformanceConsole(counterName: string, condition?: boolean): * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter */ endMonitoring(newFrame?: boolean): void; - private _fetchResult(); + private _fetchResult; private _startMonitoringTime; private _min; private _max; @@ -31164,7 +31171,7 @@ declare module BABYLON { /** Y axis */ Y = 1, /** Z axis */ - Z = 2, + Z = 2 } /** * Class used to define virtual joystick (used in touch mode) @@ -31219,9 +31226,9 @@ declare module BABYLON { * @param newJoystickSensibility defines the new sensibility */ setJoystickSensibility(newJoystickSensibility: number): void; - private _onPointerDown(e); - private _onPointerMove(e); - private _onPointerUp(e); + private _onPointerDown; + private _onPointerMove; + private _onPointerUp; /** * Change the color of the virtual joystick * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000") @@ -31242,7 +31249,7 @@ declare module BABYLON { * @param axis defines the axis to use */ setAxisForUpDown(axis: JoystickAxis): void; - private _drawVirtualJoystick(); + private _drawVirtualJoystick; /** * Release internal HTML canvas */ @@ -31272,7 +31279,7 @@ declare module BABYLON { * @param action The action to perform. Call onComplete when the action is complete. */ push(action: (worker: Worker, onComplete: () => void) => void): void; - private _execute(workerInfo, action); + private _execute; } } @@ -31284,31 +31291,31 @@ declare module BABYLON { private _idleRotationWaitTime; private _idleRotationSpinupTime; /** - * Gets the flag that indicates if user zooming should stop animation. + * Sets the flag that indicates if user zooming should stop animation. */ /** - * Sets the flag that indicates if user zooming should stop animation. + * Gets the flag that indicates if user zooming should stop animation. */ zoomStopsAnimation: boolean; /** - * Gets the default speed at which the camera rotates around the model. + * Sets the default speed at which the camera rotates around the model. */ /** - * Sets the default speed at which the camera rotates around the model. + * Gets the default speed at which the camera rotates around the model. */ idleRotationSpeed: number; /** - * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating. + * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating. */ /** - * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating. + * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating. */ idleRotationWaitTime: number; /** - * Gets the time (milliseconds) to take to spin up to the full idle rotation speed. + * Sets the time (milliseconds) to take to spin up to the full idle rotation speed. */ /** - * Sets the time (milliseconds) to take to spin up to the full idle rotation speed. + * Gets the time (milliseconds) to take to spin up to the full idle rotation speed. */ idleRotationSpinupTime: number; /** @@ -31329,14 +31336,14 @@ declare module BABYLON { * Returns true if user is scrolling. * @return true if user is scrolling. */ - private _userIsZooming(); + private _userIsZooming; private _lastFrameRadius; - private _shouldAnimationStopForInteraction(); + private _shouldAnimationStopForInteraction; /** * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. */ - private _applyUserInteraction(); - private _userIsMoving(); + private _applyUserInteraction; + private _userIsMoving; } } @@ -31371,9 +31378,9 @@ declare module BABYLON { * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically */ /** - * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically - * Transition ranges will be set to 5% of the bounding box diagonal in world space - */ + * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically + * Transition ranges will be set to 5% of the bounding box diagonal in world space + */ autoTransitionRange: boolean; private _attachedCamera; private _onAfterCheckInputsObserver; @@ -31390,12 +31397,12 @@ declare module BABYLON { * @param radiusLimit The limit to check against. * @return Bool to indicate if at limit. */ - private _isRadiusAtLimit(radiusLimit); + private _isRadiusAtLimit; /** * Applies an animation to the radius of the camera, extending by the radiusDelta. * @param radiusDelta The delta by which to animate to. Can be negative. */ - private _applyBoundRadiusAnimation(radiusDelta); + private _applyBoundRadiusAnimation; /** * Removes all animation locks. Allows new animations to be added to any of the camera properties. */ @@ -31426,65 +31433,65 @@ declare module BABYLON { * The easing mode used by animations */ static EasingMode: number; - /** - * Gets current mode used by the behavior. - */ /** * Sets the current mode used by the behavior */ - mode: number; /** - * Gets the scale applied to the radius - */ + * Gets current mode used by the behavior. + */ + mode: number; /** * Sets the scale applied to the radius (1 by default) */ - radiusScale: number; /** - * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. - */ + * Gets the scale applied to the radius + */ + radiusScale: number; /** * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. */ + /** + * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. + */ positionScale: number; /** - * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle + * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle * behaviour is triggered, in radians. */ /** - * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle + * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle * behaviour is triggered, in radians. */ defaultElevation: number; - /** - * Gets the time (in milliseconds) taken to return to the default beta position. - * Negative value indicates camera should not return to default. - */ /** * Sets the time (in milliseconds) taken to return to the default beta position. * Negative value indicates camera should not return to default. */ - elevationReturnTime: number; /** - * Gets the delay (in milliseconds) taken before the camera returns to the default beta position. - */ + * Gets the time (in milliseconds) taken to return to the default beta position. + * Negative value indicates camera should not return to default. + */ + elevationReturnTime: number; /** * Sets the delay (in milliseconds) taken before the camera returns to the default beta position. */ - elevationReturnWaitTime: number; /** - * Gets the flag that indicates if user zooming should stop animation. + * Gets the delay (in milliseconds) taken before the camera returns to the default beta position. */ + elevationReturnWaitTime: number; /** * Sets the flag that indicates if user zooming should stop animation. */ - zoomStopsAnimation: boolean; /** - * Gets the transition time when framing the mesh, in milliseconds + * Gets the flag that indicates if user zooming should stop animation. */ + zoomStopsAnimation: boolean; /** * Sets the transition time when framing the mesh, in milliseconds */ + /** + * Gets the transition time when framing the mesh, in milliseconds + */ framingTime: number; private _onPrePointerObservableObserver; private _onAfterCheckInputsObserver; @@ -31548,20 +31555,20 @@ declare module BABYLON { * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera * is automatically returned to its default position (expected to be above ground plane). */ - private _maintainCameraAboveGround(); + private _maintainCameraAboveGround; /** * Returns the frustum slope based on the canvas ratio and camera FOV * @returns The frustum slope represented as a Vector2 with X and Y slopes */ - private _getFrustumSlope(); + private _getFrustumSlope; /** * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties. */ - private _clearAnimationLocks(); + private _clearAnimationLocks; /** * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. */ - private _applyUserInteraction(); + private _applyUserInteraction; /** * Stops and removes all animations that have been applied to the camera */ @@ -31614,10 +31621,10 @@ declare module BABYLON { * Initializes the behavior */ init(): void; - private _closestFace(targetDirection); + private _closestFace; private _zeroVector; private _lookAtTmpMatrix; - private _lookAtToRef(pos, up, ref); + private _lookAtToRef; /** * Attaches the AttachToBoxBehavior to the passed in mesh * @param target The mesh that the specified node will be attached to @@ -31651,7 +31658,7 @@ declare module BABYLON { * Initializes the behavior */ init(): void; - private _getCurrentDistance(); + private _getCurrentDistance; /** * Attaches the scale behavior the passed in mesh * @param ownerNode The mesh that will be scaled around once attached @@ -31775,7 +31782,7 @@ declare module BABYLON { */ attach(ownerNode: Mesh): void; releaseDrag(): void; - private _pickWithRayOnDragPlane(ray); + private _pickWithRayOnDragPlane; private _pointA; private _pointB; private _pointC; @@ -31783,7 +31790,7 @@ declare module BABYLON { private _lineB; private _localAxis; private _lookAt; - private _updateDragPlanePosition(ray, dragPlanePosition); + private _updateDragPlanePosition; /** * Detaches the behavior from the mesh */ @@ -32496,7 +32503,7 @@ declare module BABYLON { * See http://doc.babylonjs.com/how_to/webvr_helper */ class VRExperienceHelper { - /** Options to modify the vr experience helper's behavior. */ webVROptions: VRExperienceHelperOptions; + webVROptions: VRExperienceHelperOptions; private _scene; private _position; private _btnVR; @@ -32604,8 +32611,8 @@ declare module BABYLON { * The mesh used to display where the user is going to teleport. */ /** - * Sets the mesh to be used to display where the user is going to teleport. - */ + * Sets the mesh to be used to display where the user is going to teleport. + */ teleportationTarget: Mesh; /** * The mesh used to display where the user is selecting, @@ -32617,15 +32624,15 @@ declare module BABYLON { * If the ray of the gaze should be displayed. */ /** - * Sets if the ray of the gaze should be displayed. - */ + * Sets if the ray of the gaze should be displayed. + */ displayGaze: boolean; /** * If the ray of the LaserPointer should be displayed. */ /** - * Sets if the ray of the LaserPointer should be displayed. - */ + * Sets if the ray of the LaserPointer should be displayed. + */ displayLaserPointer: boolean; /** * The deviceOrientationCamera used as the camera when not in VR. @@ -32651,18 +32658,18 @@ declare module BABYLON { * @param webVROptions Options to modify the vr experience helper's behavior. */ constructor(scene: Scene, /** Options to modify the vr experience helper's behavior. */ webVROptions?: VRExperienceHelperOptions); - private _onDefaultMeshLoaded(webVRController); + private _onDefaultMeshLoaded; private _onResize; private _onFullscreenChange; /** * Gets a value indicating if we are currently in VR mode. */ readonly isInVRMode: boolean; - private onVrDisplayPresentChange(); - private onVRDisplayChanged(eventArgs); - private moveButtonToBottomRight(); - private displayVRButton(); - private updateButtonVisibility(); + private onVrDisplayPresentChange; + private onVRDisplayChanged; + private moveButtonToBottomRight; + private displayVRButton; + private updateButtonVisibility; /** * Attempt to enter VR. If a headset is connected and ready, will request present on that. * Otherwise, will use the fullscreen API. @@ -32676,8 +32683,8 @@ declare module BABYLON { * The position of the vr experience helper. */ /** - * Sets the position of the vr experience helper. - */ + * Sets the position of the vr experience helper. + */ position: Vector3; /** * Enables controllers and user interactions such as selecting and object or clicking on an object. @@ -32685,7 +32692,7 @@ declare module BABYLON { enableInteractions(): void; private readonly _noControllerIsActive; private beforeRender; - private _isTeleportationFloor(mesh); + private _isTeleportationFloor; /** * Adds a floor mesh to be used for teleportation. * @param floorMesh the mesh to be used for teleportation. @@ -32704,23 +32711,23 @@ declare module BABYLON { private _onNewGamepadConnected; private _tryEnableInteractionOnController; private _onNewGamepadDisconnected; - private _enableInteractionOnController(controller); - private _checkTeleportWithRay(stateObject, gazer); - private _checkRotate(stateObject, gazer); - private _checkTeleportBackwards(stateObject, gazer); - private _enableTeleportationOnController(controller); - private _createTeleportationCircles(); - private _displayTeleportationTarget(); - private _hideTeleportationTarget(); - private _rotateCamera(right); - private _moveTeleportationSelectorTo(hit, gazer, ray); + private _enableInteractionOnController; + private _checkTeleportWithRay; + private _checkRotate; + private _checkTeleportBackwards; + private _enableTeleportationOnController; + private _createTeleportationCircles; + private _displayTeleportationTarget; + private _hideTeleportationTarget; + private _rotateCamera; + private _moveTeleportationSelectorTo; private _workingVector; private _workingQuaternion; private _workingMatrix; - private _teleportCamera(location); - private _convertNormalToDirectionOfRay(normal, ray); - private _castRayAndSelectObject(gazer); - private _notifySelectedMeshUnselected(mesh); + private _teleportCamera; + private _convertNormalToDirectionOfRay; + private _castRayAndSelectObject; + private _notifySelectedMeshUnselected; /** * Sets the color of the laser ray from the vr controllers. * @param color new color for the ray. @@ -32979,550 +32986,58 @@ declare module BABYLON { *
 scene.onPointerDown = function() { camera.attachControl(canvas); }
* * @param element html element to attach the vrDevice to - * @param noPreventDefault prevent the default html element operation when attaching the vrDevice - */ - attachControl(element: HTMLElement, noPreventDefault?: boolean): void; - /** - * Detaches the camera from the html element and disables VR - * - * @param element html element to detach from - */ - detachControl(element: HTMLElement): void; - /** - * @returns the name of this class - */ - getClassName(): string; - /** - * Calls resetPose on the vrDisplay - * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose - */ - resetToCurrentRotation(): void; - /** - * Updates the rig cameras (left and right eye) - */ - - private _workingVector; - private _oneVector; - private _workingMatrix; - private updateCacheCalled; - /** - * Updates the cached values of the camera - * @param ignoreParentClass ignores updating the parent class's cache (default: false) - */ - - /** - * Updates the current device position and rotation in the babylon world - */ - update(): void; - /** - * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix) - * @returns an identity matrix - */ - - /** - * This function is called by the two RIG cameras. - * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance) - */ - protected _getWebVRViewMatrix(): Matrix; - protected _getWebVRProjectionMatrix(): Matrix; - private _onGamepadConnectedObserver; - private _onGamepadDisconnectedObserver; - /** - * Initializes the controllers and their meshes - */ - initControllers(): void; - } -} - -declare module BABYLON { - /** - * Interface to implement to create a shadow generator compatible with BJS. - */ - interface IShadowGenerator { - /** - * Gets the main RTT containing the shadow map (usually storing depth from the light point of view). - * @returns The render target texture if present otherwise, null - */ - getShadowMap(): Nullable; - /** - * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself). - * @returns The render target texture if the shadow map is present otherwise, null - */ - getShadowMapForRendering(): Nullable; - /** - * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready). - * @param subMesh The submesh we want to render in the shadow map - * @param useInstances Defines wether will draw in the map using instances - * @returns true if ready otherwise, false - */ - isReady(subMesh: SubMesh, useInstances: boolean): boolean; - /** - * Prepare all the defines in a material relying on a shadow map at the specified light index. - * @param defines Defines of the material we want to update - * @param lightIndex Index of the light in the enabled light list of the material - */ - prepareDefines(defines: MaterialDefines, lightIndex: number): void; - /** - * Binds the shadow related information inside of an effect (information like near, far, darkness... - * defined in the generator but impacting the effect). - * It implies the unifroms available on the materials are the standard BJS ones. - * @param lightIndex Index of the light in the enabled light list of the material owning the effect - * @param effect The effect we are binfing the information for - */ - bindShadowLight(lightIndex: string, effect: Effect): void; - /** - * Gets the transformation matrix used to project the meshes into the map from the light point of view. - * (eq to shadow prjection matrix * light transform matrix) - * @returns The transform matrix used to create the shadow map - */ - getTransformMatrix(): Matrix; - /** - * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between - * Cube and 2D textures for instance. - */ - recreateShadowMap(): void; - /** - * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects. - * @param onCompiled Callback triggered at the and of the effects compilation - * @param options Sets of optional options forcing the compilation with different modes - */ - forceCompilation(onCompiled?: (generator: ShadowGenerator) => void, options?: Partial<{ - useInstances: boolean; - }>): void; - /** - * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects. - * @param options Sets of optional options forcing the compilation with different modes - * @returns A promise that resolves when the compilation completes - */ - forceCompilationAsync(options?: Partial<{ - useInstances: boolean; - }>): Promise; - /** - * Serializes the shadow generator setup to a json object. - * @returns The serialized JSON object - */ - serialize(): any; - /** - * Disposes the Shadow map and related Textures and effects. - */ - dispose(): void; - } - /** - * Default implementation IShadowGenerator. - * This is the main object responsible of generating shadows in the framework. - * Documentation: https://doc.babylonjs.com/babylon101/shadows - */ - class ShadowGenerator implements IShadowGenerator { - /** - * Shadow generator mode None: no filtering applied. - */ - static readonly FILTER_NONE: number; - /** - * Shadow generator mode ESM: Exponential Shadow Mapping. - * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) - */ - static readonly FILTER_EXPONENTIALSHADOWMAP: number; - /** - * Shadow generator mode Poisson Sampling: Percentage Closer Filtering. - * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength) - */ - static readonly FILTER_POISSONSAMPLING: number; - /** - * Shadow generator mode ESM: Blurred Exponential Shadow Mapping. - * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) - */ - static readonly FILTER_BLUREXPONENTIALSHADOWMAP: number; - /** - * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing - * edge artifacts on steep falloff. - * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) - */ - static readonly FILTER_CLOSEEXPONENTIALSHADOWMAP: number; - /** - * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing - * edge artifacts on steep falloff. - * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) - */ - static readonly FILTER_BLURCLOSEEXPONENTIALSHADOWMAP: number; - /** - * Shadow generator mode PCF: Percentage Closer Filtering - * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1 - * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html) - */ - static readonly FILTER_PCF: number; - /** - * Shadow generator mode PCSS: Percentage Closering Soft Shadow. - * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1 - * Contact Hardening - */ - static readonly FILTER_PCSS: number; - /** - * Reserved for PCF and PCSS - * Highest Quality. - * - * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts. - * - * Execute PCSS with 32 taps blocker search and 64 taps PCF. - */ - static readonly QUALITY_HIGH: number; - /** - * Reserved for PCF and PCSS - * Good tradeoff for quality/perf cross devices - * - * Execute PCF on a 3*3 kernel. - * - * Execute PCSS with 16 taps blocker search and 32 taps PCF. - */ - static readonly QUALITY_MEDIUM: number; - /** - * Reserved for PCF and PCSS - * The lowest quality but the fastest. - * - * Execute PCF on a 1*1 kernel. - * - * Execute PCSS with 16 taps blocker search and 16 taps PCF. - */ - static readonly QUALITY_LOW: number; - private _bias; - /** - * Gets the bias: offset applied on the depth preventing acnea (in light direction). - */ - /** - * Sets the bias: offset applied on the depth preventing acnea (in light direction). - */ - bias: number; - private _normalBias; - /** - * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle). - */ - /** - * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle). - */ - normalBias: number; - private _blurBoxOffset; - /** - * Gets the blur box offset: offset applied during the blur pass. - * Only usefull if useKernelBlur = false - */ - /** - * Sets the blur box offset: offset applied during the blur pass. - * Only usefull if useKernelBlur = false - */ - blurBoxOffset: number; - private _blurScale; - /** - * Gets the blur scale: scale of the blurred texture compared to the main shadow map. - * 2 means half of the size. - */ - /** - * Sets the blur scale: scale of the blurred texture compared to the main shadow map. - * 2 means half of the size. - */ - blurScale: number; - private _blurKernel; - /** - * Gets the blur kernel: kernel size of the blur pass. - * Only usefull if useKernelBlur = true - */ - /** - * Sets the blur kernel: kernel size of the blur pass. - * Only usefull if useKernelBlur = true - */ - blurKernel: number; - private _useKernelBlur; - /** - * Gets whether the blur pass is a kernel blur (if true) or box blur. - * Only usefull in filtered mode (useBlurExponentialShadowMap...) - */ - /** - * Sets whether the blur pass is a kernel blur (if true) or box blur. - * Only usefull in filtered mode (useBlurExponentialShadowMap...) - */ - useKernelBlur: boolean; - private _depthScale; - /** - * Gets the depth scale used in ESM mode. - */ - /** - * Sets the depth scale used in ESM mode. - * This can override the scale stored on the light. - */ - depthScale: number; - private _filter; - /** - * Gets the current mode of the shadow generator (normal, PCF, ESM...). - * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE - */ - /** - * Sets the current mode of the shadow generator (normal, PCF, ESM...). - * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE - */ - filter: number; - /** - * Gets if the current filter is set to Poisson Sampling. - */ - /** - * Sets the current filter to Poisson Sampling. - */ - usePoissonSampling: boolean; - /** - * Gets if the current filter is set to VSM. - * DEPRECATED. Should use useExponentialShadowMap instead. - */ - /** - * Sets the current filter is to VSM. - * DEPRECATED. Should use useExponentialShadowMap instead. - */ - useVarianceShadowMap: boolean; - /** - * Gets if the current filter is set to blurred VSM. - * DEPRECATED. Should use useBlurExponentialShadowMap instead. - */ - /** - * Sets the current filter is to blurred VSM. - * DEPRECATED. Should use useBlurExponentialShadowMap instead. - */ - useBlurVarianceShadowMap: boolean; - /** - * Gets if the current filter is set to ESM. - */ - /** - * Sets the current filter is to ESM. - */ - useExponentialShadowMap: boolean; - /** - * Gets if the current filter is set to filtered ESM. - */ - /** - * Gets if the current filter is set to filtered ESM. - */ - useBlurExponentialShadowMap: boolean; - /** - * Gets if the current filter is set to "close ESM" (using the inverse of the - * exponential to prevent steep falloff artifacts). - */ - /** - * Sets the current filter to "close ESM" (using the inverse of the - * exponential to prevent steep falloff artifacts). - */ - useCloseExponentialShadowMap: boolean; - /** - * Gets if the current filter is set to filtered "close ESM" (using the inverse of the - * exponential to prevent steep falloff artifacts). - */ - /** - * Sets the current filter to filtered "close ESM" (using the inverse of the - * exponential to prevent steep falloff artifacts). - */ - useBlurCloseExponentialShadowMap: boolean; - /** - * Gets if the current filter is set to "PCF" (percentage closer filtering). - */ - /** - * Sets the current filter to "PCF" (percentage closer filtering). - */ - usePercentageCloserFiltering: boolean; - private _filteringQuality; - /** - * Gets the PCF or PCSS Quality. - * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. - */ - /** - * Sets the PCF or PCSS Quality. - * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. - */ - filteringQuality: number; - /** - * Gets if the current filter is set to "PCSS" (contact hardening). - */ - /** - * Sets the current filter to "PCSS" (contact hardening). - */ - useContactHardeningShadow: boolean; - private _contactHardeningLightSizeUVRatio; - /** - * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. - * Using a ratio helps keeping shape stability independently of the map size. - * - * It does not account for the light projection as it was having too much - * instability during the light setup or during light position changes. - * - * Only valid if useContactHardeningShadow is true. - */ - /** - * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. - * Using a ratio helps keeping shape stability independently of the map size. - * - * It does not account for the light projection as it was having too much - * instability during the light setup or during light position changes. - * - * Only valid if useContactHardeningShadow is true. - */ - contactHardeningLightSizeUVRatio: number; - private _darkness; - /** - * Returns the darkness value (float). This can only decrease the actual darkness of a shadow. - * 0 means strongest and 1 would means no shadow. - * @returns the darkness. - */ - getDarkness(): number; - /** - * Sets the darkness value (float). This can only decrease the actual darkness of a shadow. - * @param darkness The darkness value 0 means strongest and 1 would means no shadow. - * @returns the shadow generator allowing fluent coding. - */ - setDarkness(darkness: number): ShadowGenerator; - private _transparencyShadow; - /** - * Sets the ability to have transparent shadow (boolean). - * @param transparent True if transparent else False - * @returns the shadow generator allowing fluent coding - */ - setTransparencyShadow(transparent: boolean): ShadowGenerator; - private _shadowMap; - private _shadowMap2; - /** - * Gets the main RTT containing the shadow map (usually storing depth from the light point of view). - * @returns The render target texture if present otherwise, null - */ - getShadowMap(): Nullable; - /** - * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself). - * @returns The render target texture if the shadow map is present otherwise, null - */ - getShadowMapForRendering(): Nullable; - /** - * Helper function to add a mesh and its descendants to the list of shadow casters. - * @param mesh Mesh to add - * @param includeDescendants boolean indicating if the descendants should be added. Default to true - * @returns the Shadow Generator itself - */ - addShadowCaster(mesh: AbstractMesh, includeDescendants?: boolean): ShadowGenerator; - /** - * Helper function to remove a mesh and its descendants from the list of shadow casters - * @param mesh Mesh to remove - * @param includeDescendants boolean indicating if the descendants should be removed. Default to true - * @returns the Shadow Generator itself - */ - removeShadowCaster(mesh: AbstractMesh, includeDescendants?: boolean): ShadowGenerator; - /** - * Controls the extent to which the shadows fade out at the edge of the frustum - * Used only by directionals and spots - */ - frustumEdgeFalloff: number; - private _light; - /** - * Returns the associated light object. - * @returns the light generating the shadow - */ - getLight(): IShadowLight; - /** - * If true the shadow map is generated by rendering the back face of the mesh instead of the front face. - * This can help with self-shadowing as the geometry making up the back of objects is slightly offset. - * It might on the other hand introduce peter panning. - */ - forceBackFacesOnly: boolean; - private _scene; - private _lightDirection; - private _effect; - private _viewMatrix; - private _projectionMatrix; - private _transformMatrix; - private _cachedPosition; - private _cachedDirection; - private _cachedDefines; - private _currentRenderID; - private _boxBlurPostprocess; - private _kernelBlurXPostprocess; - private _kernelBlurYPostprocess; - private _blurPostProcesses; - private _mapSize; - private _currentFaceIndex; - private _currentFaceIndexCache; - private _textureType; - private _defaultTextureMatrix; - /** - * Creates a ShadowGenerator object. - * A ShadowGenerator is the required tool to use the shadows. - * Each light casting shadows needs to use its own ShadowGenerator. - * Documentation : http://doc.babylonjs.com/tutorials/shadows - * @param mapSize The size of the texture what stores the shadows. Example : 1024. - * @param light The light object generating the shadows. - * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture. - */ - constructor(mapSize: number, light: IShadowLight, useFullFloatFirst?: boolean); - private _initializeGenerator(); - private _initializeShadowMap(); - private _initializeBlurRTTAndPostProcesses(); - private _renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes); - private _renderSubMeshForShadowMap(subMesh); - private _applyFilterValues(); - /** - * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects. - * @param onCompiled Callback triggered at the and of the effects compilation - * @param options Sets of optional options forcing the compilation with different modes + * @param noPreventDefault prevent the default html element operation when attaching the vrDevice */ - forceCompilation(onCompiled?: (generator: ShadowGenerator) => void, options?: Partial<{ - useInstances: boolean; - }>): void; + attachControl(element: HTMLElement, noPreventDefault?: boolean): void; /** - * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects. - * @param options Sets of optional options forcing the compilation with different modes - * @returns A promise that resolves when the compilation completes + * Detaches the camera from the html element and disables VR + * + * @param element html element to detach from */ - forceCompilationAsync(options?: Partial<{ - useInstances: boolean; - }>): Promise; + detachControl(element: HTMLElement): void; /** - * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready). - * @param subMesh The submesh we want to render in the shadow map - * @param useInstances Defines wether will draw in the map using instances - * @returns true if ready otherwise, false + * @returns the name of this class */ - isReady(subMesh: SubMesh, useInstances: boolean): boolean; + getClassName(): string; /** - * Prepare all the defines in a material relying on a shadow map at the specified light index. - * @param defines Defines of the material we want to update - * @param lightIndex Index of the light in the enabled light list of the material + * Calls resetPose on the vrDisplay + * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose */ - prepareDefines(defines: any, lightIndex: number): void; + resetToCurrentRotation(): void; /** - * Binds the shadow related information inside of an effect (information like near, far, darkness... - * defined in the generator but impacting the effect). - * @param lightIndex Index of the light in the enabled light list of the material owning the effect - * @param effect The effect we are binfing the information for + * Updates the rig cameras (left and right eye) */ - bindShadowLight(lightIndex: string, effect: Effect): void; + + private _workingVector; + private _oneVector; + private _workingMatrix; + private updateCacheCalled; /** - * Gets the transformation matrix used to project the meshes into the map from the light point of view. - * (eq to shadow prjection matrix * light transform matrix) - * @returns The transform matrix used to create the shadow map + * Updates the cached values of the camera + * @param ignoreParentClass ignores updating the parent class's cache (default: false) */ - getTransformMatrix(): Matrix; + /** - * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between - * Cube and 2D textures for instance. + * Updates the current device position and rotation in the babylon world */ - recreateShadowMap(): void; - private _disposeBlurPostProcesses(); - private _disposeRTTandPostProcesses(); + update(): void; /** - * Disposes the ShadowGenerator. - * Returns nothing. + * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix) + * @returns an identity matrix */ - dispose(): void; + /** - * Serializes the shadow generator setup to a json object. - * @returns The serialized JSON object + * This function is called by the two RIG cameras. + * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance) */ - serialize(): any; + protected _getWebVRViewMatrix(): Matrix; + protected _getWebVRProjectionMatrix(): Matrix; + private _onGamepadConnectedObserver; + private _onGamepadDisconnectedObserver; /** - * Parses a serialized ShadowGenerator and returns a new ShadowGenerator. - * @param parsedShadowGenerator The JSON object to parse - * @param scene The scene to create the shadow map for - * @returns The parsed shadow generator + * Initializes the controllers and their meshes */ - static Parse(parsedShadowGenerator: any, scene: Scene): ShadowGenerator; + initControllers(): void; } } @@ -33741,7 +33256,7 @@ declare module BABYLON { /** * Generic */ - GENERIC = 5, + GENERIC = 5 } /** * Defines the MutableGamepadButton interface for the state of a gamepad button @@ -33824,325 +33339,817 @@ declare module BABYLON { /** * The raw pose from the device */ - rawPose: DevicePose; + rawPose: DevicePose; + /** + * Internal, the mesh attached to the controller + */ + + private _poseControlledCamera; + private _leftHandSystemQuaternion; + /** + * Internal, matrix used to convert room space to babylon space + */ + + /** + * Node to be used when casting a ray from the controller + */ + + /** + * Name of the child mesh that can be used to cast a ray from the controller + */ + static readonly POINTING_POSE: string; + /** + * Creates a new PoseEnabledController from a gamepad + * @param browserGamepad the gamepad that the PoseEnabledController should be created from + */ + constructor(browserGamepad: any); + private _workingMatrix; + /** + * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller + */ + update(): void; + /** + * Updates only the pose device and mesh without doing any button event checking + */ + protected _updatePoseAndMesh(): void; + /** + * Updates the state of the pose enbaled controller based on the raw pose data from the device + * @param poseData raw pose fromthe device + */ + updateFromDevice(poseData: DevicePose): void; + /** + * @hidden + */ + + /** + * Attaches a mesh to the controller + * @param mesh the mesh to be attached + */ + attachToMesh(mesh: AbstractMesh): void; + /** + * Attaches the controllers mesh to a camera + * @param camera the camera the mesh should be attached to + */ + attachToPoseControlledCamera(camera: TargetCamera): void; + /** + * Disposes of the controller + */ + dispose(): void; + /** + * The mesh that is attached to the controller + */ + readonly mesh: Nullable; + /** + * Gets the ray of the controller in the direction the controller is pointing + * @param length the length the resulting ray should be + * @returns a ray in the direction the controller is pointing + */ + getForwardRay(length?: number): Ray; + } +} + +declare module BABYLON { + /** + * Vive Controller + */ + class ViveController extends WebVRController { + /** + * Base Url for the controller model. + */ + static MODEL_BASE_URL: string; + /** + * File name for the controller model. + */ + static MODEL_FILENAME: string; + /** + * Creates a new ViveController from a gamepad + * @param vrGamepad the gamepad that the controller should be created from + */ + constructor(vrGamepad: any); + /** + * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. + * @param scene scene in which to add meshes + * @param meshLoaded optional callback function that will be called if the mesh loads successfully. + */ + initControllerMesh(scene: Scene, meshLoaded?: (mesh: AbstractMesh) => void): void; + /** + * Fired when the left button on this controller is modified + */ + readonly onLeftButtonStateChangedObservable: Observable; + /** + * Fired when the right button on this controller is modified + */ + readonly onRightButtonStateChangedObservable: Observable; + /** + * Fired when the menu button on this controller is modified + */ + readonly onMenuButtonStateChangedObservable: Observable; + /** + * Called once for each button that changed state since the last frame + * Vive mapping: + * 0: touchpad + * 1: trigger + * 2: left AND right buttons + * 3: menu button + * @param buttonIdx Which button index changed + * @param state New state of the button + * @param changes Which properties on the state changed since last frame + */ + protected _handleButtonChange(buttonIdx: number, state: ExtendedGamepadButton, changes: GamepadButtonChanges): void; + } +} + +declare module BABYLON { + /** + * Defines the WebVRController object that represents controllers tracked in 3D space + */ + abstract class WebVRController extends PoseEnabledController { + /** + * Internal, the default controller model for the controller + */ + protected _defaultModel: AbstractMesh; + /** + * Fired when the trigger state has changed + */ + onTriggerStateChangedObservable: Observable; + /** + * Fired when the main button state has changed + */ + onMainButtonStateChangedObservable: Observable; + /** + * Fired when the secondary button state has changed + */ + onSecondaryButtonStateChangedObservable: Observable; + /** + * Fired when the pad state has changed + */ + onPadStateChangedObservable: Observable; + /** + * Fired when controllers stick values have changed + */ + onPadValuesChangedObservable: Observable; + /** + * Array of button availible on the controller + */ + protected _buttons: Array; + private _onButtonStateChange; + /** + * Fired when a controller button's state has changed + * @param callback the callback containing the button that was modified + */ + onButtonStateChange(callback: (controlledIndex: number, buttonIndex: number, state: ExtendedGamepadButton) => void): void; + /** + * X and Y axis corrisponding to the controllers joystick + */ + pad: StickValues; + /** + * 'left' or 'right', see https://w3c.github.io/gamepad/extensions.html#gamepadhand-enum + */ + hand: string; + /** + * The default controller model for the controller + */ + readonly defaultModel: AbstractMesh; + /** + * Creates a new WebVRController from a gamepad + * @param vrGamepad the gamepad that the WebVRController should be created from + */ + constructor(vrGamepad: any); + /** + * Updates the state of the controller and mesh based on the current position and rotation of the controller + */ + update(): void; + /** + * Function to be called when a button is modified + */ + protected abstract _handleButtonChange(buttonIdx: number, value: ExtendedGamepadButton, changes: GamepadButtonChanges): void; + /** + * Loads a mesh and attaches it to the controller + * @param scene the scene the mesh should be added to + * @param meshLoaded callback for when the mesh has been loaded + */ + abstract initControllerMesh(scene: Scene, meshLoaded?: (mesh: AbstractMesh) => void): void; + private _setButtonValue; + private _changes; + private _checkChanges; + /** + * Disposes of th webVRCOntroller + */ + dispose(): void; + } +} + +declare module BABYLON { + /** + * Defines the WindowsMotionController object that the state of the windows motion controller + */ + class WindowsMotionController extends WebVRController { + /** + * The base url used to load the left and right controller models + */ + static MODEL_BASE_URL: string; + /** + * The name of the left controller model file + */ + static MODEL_LEFT_FILENAME: string; + /** + * The name of the right controller model file + */ + static MODEL_RIGHT_FILENAME: string; + /** + * The controller name prefix for this controller type + */ + static readonly GAMEPAD_ID_PREFIX: string; + /** + * The controller id pattern for this controller type + */ + private static readonly GAMEPAD_ID_PATTERN; + private _loadedMeshInfo; + private readonly _mapping; + /** + * Fired when the trackpad on this controller is clicked + */ + onTrackpadChangedObservable: Observable; + /** + * Fired when the trackpad on this controller is modified + */ + onTrackpadValuesChangedObservable: Observable; + /** + * The current x and y values of this controller's trackpad + */ + trackpad: StickValues; + /** + * Creates a new WindowsMotionController from a gamepad + * @param vrGamepad the gamepad that the controller should be created from + */ + constructor(vrGamepad: any); + /** + * Fired when the trigger on this controller is modified + */ + readonly onTriggerButtonStateChangedObservable: Observable; + /** + * Fired when the menu button on this controller is modified + */ + readonly onMenuButtonStateChangedObservable: Observable; + /** + * Fired when the grip button on this controller is modified + */ + readonly onGripButtonStateChangedObservable: Observable; + /** + * Fired when the thumbstick button on this controller is modified + */ + readonly onThumbstickButtonStateChangedObservable: Observable; + /** + * Fired when the touchpad button on this controller is modified + */ + readonly onTouchpadButtonStateChangedObservable: Observable; + /** + * Fired when the touchpad values on this controller are modified + */ + readonly onTouchpadValuesChangedObservable: Observable; + private _updateTrackpad; + /** + * Called once per frame by the engine. + */ + update(): void; + /** + * Called once for each button that changed state since the last frame + * @param buttonIdx Which button index changed + * @param state New state of the button + * @param changes Which properties on the state changed since last frame + */ + protected _handleButtonChange(buttonIdx: number, state: ExtendedGamepadButton, changes: GamepadButtonChanges): void; + /** + * Moves the buttons on the controller mesh based on their current state + * @param buttonName the name of the button to move + * @param buttonValue the value of the button which determines the buttons new position + */ + protected _lerpButtonTransform(buttonName: string, buttonValue: number): void; + /** + * Moves the axis on the controller mesh based on its current state + * @param axis the index of the axis + * @param axisValue the value of the axis which determines the meshes new position + * @hidden + */ + protected _lerpAxisTransform(axis: number, axisValue: number): void; + /** + * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. + * @param scene scene in which to add meshes + * @param meshLoaded optional callback function that will be called if the mesh loads successfully. + */ + initControllerMesh(scene: Scene, meshLoaded?: (mesh: AbstractMesh) => void, forceDefault?: boolean): void; + /** + * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that + * can be transformed by button presses and axes values, based on this._mapping. + * + * @param scene scene in which the meshes exist + * @param meshes list of meshes that make up the controller model to process + * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed. + */ + private processModel; + private createMeshInfo; + /** + * Gets the ray of the controller in the direction the controller is pointing + * @param length the length the resulting ray should be + * @returns a ray in the direction the controller is pointing + */ + getForwardRay(length?: number): Ray; + /** + * Disposes of the controller + */ + dispose(): void; + } +} + +declare module BABYLON { + /** + * Interface to implement to create a shadow generator compatible with BJS. + */ + interface IShadowGenerator { + /** + * Gets the main RTT containing the shadow map (usually storing depth from the light point of view). + * @returns The render target texture if present otherwise, null + */ + getShadowMap(): Nullable; + /** + * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself). + * @returns The render target texture if the shadow map is present otherwise, null + */ + getShadowMapForRendering(): Nullable; + /** + * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready). + * @param subMesh The submesh we want to render in the shadow map + * @param useInstances Defines wether will draw in the map using instances + * @returns true if ready otherwise, false + */ + isReady(subMesh: SubMesh, useInstances: boolean): boolean; + /** + * Prepare all the defines in a material relying on a shadow map at the specified light index. + * @param defines Defines of the material we want to update + * @param lightIndex Index of the light in the enabled light list of the material + */ + prepareDefines(defines: MaterialDefines, lightIndex: number): void; + /** + * Binds the shadow related information inside of an effect (information like near, far, darkness... + * defined in the generator but impacting the effect). + * It implies the unifroms available on the materials are the standard BJS ones. + * @param lightIndex Index of the light in the enabled light list of the material owning the effect + * @param effect The effect we are binfing the information for + */ + bindShadowLight(lightIndex: string, effect: Effect): void; + /** + * Gets the transformation matrix used to project the meshes into the map from the light point of view. + * (eq to shadow prjection matrix * light transform matrix) + * @returns The transform matrix used to create the shadow map + */ + getTransformMatrix(): Matrix; + /** + * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between + * Cube and 2D textures for instance. + */ + recreateShadowMap(): void; + /** + * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects. + * @param onCompiled Callback triggered at the and of the effects compilation + * @param options Sets of optional options forcing the compilation with different modes + */ + forceCompilation(onCompiled?: (generator: ShadowGenerator) => void, options?: Partial<{ + useInstances: boolean; + }>): void; + /** + * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects. + * @param options Sets of optional options forcing the compilation with different modes + * @returns A promise that resolves when the compilation completes + */ + forceCompilationAsync(options?: Partial<{ + useInstances: boolean; + }>): Promise; + /** + * Serializes the shadow generator setup to a json object. + * @returns The serialized JSON object + */ + serialize(): any; + /** + * Disposes the Shadow map and related Textures and effects. + */ + dispose(): void; + } + /** + * Default implementation IShadowGenerator. + * This is the main object responsible of generating shadows in the framework. + * Documentation: https://doc.babylonjs.com/babylon101/shadows + */ + class ShadowGenerator implements IShadowGenerator { + /** + * Shadow generator mode None: no filtering applied. + */ + static readonly FILTER_NONE: number; + /** + * Shadow generator mode ESM: Exponential Shadow Mapping. + * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) + */ + static readonly FILTER_EXPONENTIALSHADOWMAP: number; + /** + * Shadow generator mode Poisson Sampling: Percentage Closer Filtering. + * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength) + */ + static readonly FILTER_POISSONSAMPLING: number; + /** + * Shadow generator mode ESM: Blurred Exponential Shadow Mapping. + * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) + */ + static readonly FILTER_BLUREXPONENTIALSHADOWMAP: number; + /** + * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing + * edge artifacts on steep falloff. + * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) + */ + static readonly FILTER_CLOSEEXPONENTIALSHADOWMAP: number; + /** + * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing + * edge artifacts on steep falloff. + * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) + */ + static readonly FILTER_BLURCLOSEEXPONENTIALSHADOWMAP: number; + /** + * Shadow generator mode PCF: Percentage Closer Filtering + * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1 + * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html) + */ + static readonly FILTER_PCF: number; + /** + * Shadow generator mode PCSS: Percentage Closering Soft Shadow. + * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1 + * Contact Hardening + */ + static readonly FILTER_PCSS: number; /** - * Internal, the mesh attached to the controller + * Reserved for PCF and PCSS + * Highest Quality. + * + * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts. + * + * Execute PCSS with 32 taps blocker search and 64 taps PCF. */ - - private _poseControlledCamera; - private _leftHandSystemQuaternion; + static readonly QUALITY_HIGH: number; /** - * Internal, matrix used to convert room space to babylon space + * Reserved for PCF and PCSS + * Good tradeoff for quality/perf cross devices + * + * Execute PCF on a 3*3 kernel. + * + * Execute PCSS with 16 taps blocker search and 32 taps PCF. */ - + static readonly QUALITY_MEDIUM: number; /** - * Node to be used when casting a ray from the controller + * Reserved for PCF and PCSS + * The lowest quality but the fastest. + * + * Execute PCF on a 1*1 kernel. + * + * Execute PCSS with 16 taps blocker search and 16 taps PCF. */ - + static readonly QUALITY_LOW: number; + private _bias; /** - * Name of the child mesh that can be used to cast a ray from the controller + * Gets the bias: offset applied on the depth preventing acnea (in light direction). */ - static readonly POINTING_POSE: string; /** - * Creates a new PoseEnabledController from a gamepad - * @param browserGamepad the gamepad that the PoseEnabledController should be created from - */ - constructor(browserGamepad: any); - private _workingMatrix; + * Sets the bias: offset applied on the depth preventing acnea (in light direction). + */ + bias: number; + private _normalBias; /** - * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller + * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle). */ - update(): void; /** - * Updates only the pose device and mesh without doing any button event checking - */ - protected _updatePoseAndMesh(): void; + * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle). + */ + normalBias: number; + private _blurBoxOffset; /** - * Updates the state of the pose enbaled controller based on the raw pose data from the device - * @param poseData raw pose fromthe device + * Gets the blur box offset: offset applied during the blur pass. + * Only usefull if useKernelBlur = false */ - updateFromDevice(poseData: DevicePose): void; /** - * @hidden - */ - + * Sets the blur box offset: offset applied during the blur pass. + * Only usefull if useKernelBlur = false + */ + blurBoxOffset: number; + private _blurScale; /** - * Attaches a mesh to the controller - * @param mesh the mesh to be attached + * Gets the blur scale: scale of the blurred texture compared to the main shadow map. + * 2 means half of the size. */ - attachToMesh(mesh: AbstractMesh): void; /** - * Attaches the controllers mesh to a camera - * @param camera the camera the mesh should be attached to - */ - attachToPoseControlledCamera(camera: TargetCamera): void; + * Sets the blur scale: scale of the blurred texture compared to the main shadow map. + * 2 means half of the size. + */ + blurScale: number; + private _blurKernel; /** - * Disposes of the controller + * Gets the blur kernel: kernel size of the blur pass. + * Only usefull if useKernelBlur = true */ - dispose(): void; /** - * The mesh that is attached to the controller - */ - readonly mesh: Nullable; + * Sets the blur kernel: kernel size of the blur pass. + * Only usefull if useKernelBlur = true + */ + blurKernel: number; + private _useKernelBlur; /** - * Gets the ray of the controller in the direction the controller is pointing - * @param length the length the resulting ray should be - * @returns a ray in the direction the controller is pointing + * Gets whether the blur pass is a kernel blur (if true) or box blur. + * Only usefull in filtered mode (useBlurExponentialShadowMap...) */ - getForwardRay(length?: number): Ray; - } -} - -declare module BABYLON { - /** - * Vive Controller - */ - class ViveController extends WebVRController { /** - * Base Url for the controller model. - */ - static MODEL_BASE_URL: string; + * Sets whether the blur pass is a kernel blur (if true) or box blur. + * Only usefull in filtered mode (useBlurExponentialShadowMap...) + */ + useKernelBlur: boolean; + private _depthScale; /** - * File name for the controller model. + * Gets the depth scale used in ESM mode. */ - static MODEL_FILENAME: string; /** - * Creates a new ViveController from a gamepad - * @param vrGamepad the gamepad that the controller should be created from - */ - constructor(vrGamepad: any); + * Sets the depth scale used in ESM mode. + * This can override the scale stored on the light. + */ + depthScale: number; + private _filter; /** - * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. - * @param scene scene in which to add meshes - * @param meshLoaded optional callback function that will be called if the mesh loads successfully. + * Gets the current mode of the shadow generator (normal, PCF, ESM...). + * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE */ - initControllerMesh(scene: Scene, meshLoaded?: (mesh: AbstractMesh) => void): void; /** - * Fired when the left button on this controller is modified - */ - readonly onLeftButtonStateChangedObservable: Observable; + * Sets the current mode of the shadow generator (normal, PCF, ESM...). + * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE + */ + filter: number; /** - * Fired when the right button on this controller is modified + * Gets if the current filter is set to Poisson Sampling. */ - readonly onRightButtonStateChangedObservable: Observable; /** - * Fired when the menu button on this controller is modified - */ - readonly onMenuButtonStateChangedObservable: Observable; + * Sets the current filter to Poisson Sampling. + */ + usePoissonSampling: boolean; /** - * Called once for each button that changed state since the last frame - * Vive mapping: - * 0: touchpad - * 1: trigger - * 2: left AND right buttons - * 3: menu button - * @param buttonIdx Which button index changed - * @param state New state of the button - * @param changes Which properties on the state changed since last frame + * Gets if the current filter is set to VSM. + * DEPRECATED. Should use useExponentialShadowMap instead. */ - protected _handleButtonChange(buttonIdx: number, state: ExtendedGamepadButton, changes: GamepadButtonChanges): void; - } -} - -declare module BABYLON { - /** - * Defines the WebVRController object that represents controllers tracked in 3D space - */ - abstract class WebVRController extends PoseEnabledController { /** - * Internal, the default controller model for the controller - */ - protected _defaultModel: AbstractMesh; + * Sets the current filter is to VSM. + * DEPRECATED. Should use useExponentialShadowMap instead. + */ + useVarianceShadowMap: boolean; /** - * Fired when the trigger state has changed + * Gets if the current filter is set to blurred VSM. + * DEPRECATED. Should use useBlurExponentialShadowMap instead. */ - onTriggerStateChangedObservable: Observable; /** - * Fired when the main button state has changed - */ - onMainButtonStateChangedObservable: Observable; + * Sets the current filter is to blurred VSM. + * DEPRECATED. Should use useBlurExponentialShadowMap instead. + */ + useBlurVarianceShadowMap: boolean; /** - * Fired when the secondary button state has changed + * Gets if the current filter is set to ESM. */ - onSecondaryButtonStateChangedObservable: Observable; /** - * Fired when the pad state has changed - */ - onPadStateChangedObservable: Observable; + * Sets the current filter is to ESM. + */ + useExponentialShadowMap: boolean; /** - * Fired when controllers stick values have changed + * Gets if the current filter is set to filtered ESM. */ - onPadValuesChangedObservable: Observable; /** - * Array of button availible on the controller - */ - protected _buttons: Array; - private _onButtonStateChange; + * Gets if the current filter is set to filtered ESM. + */ + useBlurExponentialShadowMap: boolean; /** - * Fired when a controller button's state has changed - * @param callback the callback containing the button that was modified + * Gets if the current filter is set to "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). */ - onButtonStateChange(callback: (controlledIndex: number, buttonIndex: number, state: ExtendedGamepadButton) => void): void; /** - * X and Y axis corrisponding to the controllers joystick - */ - pad: StickValues; + * Sets the current filter to "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). + */ + useCloseExponentialShadowMap: boolean; /** - * 'left' or 'right', see https://w3c.github.io/gamepad/extensions.html#gamepadhand-enum + * Gets if the current filter is set to filtered "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). */ - hand: string; /** - * The default controller model for the controller - */ - readonly defaultModel: AbstractMesh; + * Sets the current filter to filtered "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). + */ + useBlurCloseExponentialShadowMap: boolean; /** - * Creates a new WebVRController from a gamepad - * @param vrGamepad the gamepad that the WebVRController should be created from + * Gets if the current filter is set to "PCF" (percentage closer filtering). */ - constructor(vrGamepad: any); /** - * Updates the state of the controller and mesh based on the current position and rotation of the controller - */ - update(): void; + * Sets the current filter to "PCF" (percentage closer filtering). + */ + usePercentageCloserFiltering: boolean; + private _filteringQuality; /** - * Function to be called when a button is modified + * Gets the PCF or PCSS Quality. + * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. */ - protected abstract _handleButtonChange(buttonIdx: number, value: ExtendedGamepadButton, changes: GamepadButtonChanges): void; /** - * Loads a mesh and attaches it to the controller - * @param scene the scene the mesh should be added to - * @param meshLoaded callback for when the mesh has been loaded - */ - abstract initControllerMesh(scene: Scene, meshLoaded?: (mesh: AbstractMesh) => void): void; - private _setButtonValue(newState, currentState, buttonIndex); - private _changes; - private _checkChanges(newState, currentState); + * Sets the PCF or PCSS Quality. + * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. + */ + filteringQuality: number; /** - * Disposes of th webVRCOntroller + * Gets if the current filter is set to "PCSS" (contact hardening). */ - dispose(): void; - } -} - -declare module BABYLON { - /** - * Defines the WindowsMotionController object that the state of the windows motion controller - */ - class WindowsMotionController extends WebVRController { /** - * The base url used to load the left and right controller models - */ - static MODEL_BASE_URL: string; + * Sets the current filter to "PCSS" (contact hardening). + */ + useContactHardeningShadow: boolean; + private _contactHardeningLightSizeUVRatio; /** - * The name of the left controller model file + * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. + * Using a ratio helps keeping shape stability independently of the map size. + * + * It does not account for the light projection as it was having too much + * instability during the light setup or during light position changes. + * + * Only valid if useContactHardeningShadow is true. */ - static MODEL_LEFT_FILENAME: string; /** - * The name of the right controller model file + * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. + * Using a ratio helps keeping shape stability independently of the map size. + * + * It does not account for the light projection as it was having too much + * instability during the light setup or during light position changes. + * + * Only valid if useContactHardeningShadow is true. + */ + contactHardeningLightSizeUVRatio: number; + private _darkness; + /** + * Returns the darkness value (float). This can only decrease the actual darkness of a shadow. + * 0 means strongest and 1 would means no shadow. + * @returns the darkness. */ - static MODEL_RIGHT_FILENAME: string; + getDarkness(): number; /** - * The controller name prefix for this controller type + * Sets the darkness value (float). This can only decrease the actual darkness of a shadow. + * @param darkness The darkness value 0 means strongest and 1 would means no shadow. + * @returns the shadow generator allowing fluent coding. */ - static readonly GAMEPAD_ID_PREFIX: string; + setDarkness(darkness: number): ShadowGenerator; + private _transparencyShadow; /** - * The controller id pattern for this controller type + * Sets the ability to have transparent shadow (boolean). + * @param transparent True if transparent else False + * @returns the shadow generator allowing fluent coding */ - private static readonly GAMEPAD_ID_PATTERN; - private _loadedMeshInfo; - private readonly _mapping; + setTransparencyShadow(transparent: boolean): ShadowGenerator; + private _shadowMap; + private _shadowMap2; /** - * Fired when the trackpad on this controller is clicked + * Gets the main RTT containing the shadow map (usually storing depth from the light point of view). + * @returns The render target texture if present otherwise, null */ - onTrackpadChangedObservable: Observable; + getShadowMap(): Nullable; /** - * Fired when the trackpad on this controller is modified + * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself). + * @returns The render target texture if the shadow map is present otherwise, null */ - onTrackpadValuesChangedObservable: Observable; + getShadowMapForRendering(): Nullable; /** - * The current x and y values of this controller's trackpad + * Helper function to add a mesh and its descendants to the list of shadow casters. + * @param mesh Mesh to add + * @param includeDescendants boolean indicating if the descendants should be added. Default to true + * @returns the Shadow Generator itself */ - trackpad: StickValues; + addShadowCaster(mesh: AbstractMesh, includeDescendants?: boolean): ShadowGenerator; /** - * Creates a new WindowsMotionController from a gamepad - * @param vrGamepad the gamepad that the controller should be created from + * Helper function to remove a mesh and its descendants from the list of shadow casters + * @param mesh Mesh to remove + * @param includeDescendants boolean indicating if the descendants should be removed. Default to true + * @returns the Shadow Generator itself */ - constructor(vrGamepad: any); + removeShadowCaster(mesh: AbstractMesh, includeDescendants?: boolean): ShadowGenerator; /** - * Fired when the trigger on this controller is modified + * Controls the extent to which the shadows fade out at the edge of the frustum + * Used only by directionals and spots */ - readonly onTriggerButtonStateChangedObservable: Observable; + frustumEdgeFalloff: number; + private _light; /** - * Fired when the menu button on this controller is modified + * Returns the associated light object. + * @returns the light generating the shadow */ - readonly onMenuButtonStateChangedObservable: Observable; + getLight(): IShadowLight; /** - * Fired when the grip button on this controller is modified + * If true the shadow map is generated by rendering the back face of the mesh instead of the front face. + * This can help with self-shadowing as the geometry making up the back of objects is slightly offset. + * It might on the other hand introduce peter panning. */ - readonly onGripButtonStateChangedObservable: Observable; + forceBackFacesOnly: boolean; + private _scene; + private _lightDirection; + private _effect; + private _viewMatrix; + private _projectionMatrix; + private _transformMatrix; + private _cachedPosition; + private _cachedDirection; + private _cachedDefines; + private _currentRenderID; + private _boxBlurPostprocess; + private _kernelBlurXPostprocess; + private _kernelBlurYPostprocess; + private _blurPostProcesses; + private _mapSize; + private _currentFaceIndex; + private _currentFaceIndexCache; + private _textureType; + private _defaultTextureMatrix; /** - * Fired when the thumbstick button on this controller is modified + * Creates a ShadowGenerator object. + * A ShadowGenerator is the required tool to use the shadows. + * Each light casting shadows needs to use its own ShadowGenerator. + * Documentation : http://doc.babylonjs.com/tutorials/shadows + * @param mapSize The size of the texture what stores the shadows. Example : 1024. + * @param light The light object generating the shadows. + * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture. */ - readonly onThumbstickButtonStateChangedObservable: Observable; + constructor(mapSize: number, light: IShadowLight, useFullFloatFirst?: boolean); + private _initializeGenerator; + private _initializeShadowMap; + private _initializeBlurRTTAndPostProcesses; + private _renderForShadowMap; + private _renderSubMeshForShadowMap; + private _applyFilterValues; /** - * Fired when the touchpad button on this controller is modified + * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects. + * @param onCompiled Callback triggered at the and of the effects compilation + * @param options Sets of optional options forcing the compilation with different modes */ - readonly onTouchpadButtonStateChangedObservable: Observable; + forceCompilation(onCompiled?: (generator: ShadowGenerator) => void, options?: Partial<{ + useInstances: boolean; + }>): void; /** - * Fired when the touchpad values on this controller are modified + * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects. + * @param options Sets of optional options forcing the compilation with different modes + * @returns A promise that resolves when the compilation completes */ - readonly onTouchpadValuesChangedObservable: Observable; - private _updateTrackpad(); + forceCompilationAsync(options?: Partial<{ + useInstances: boolean; + }>): Promise; /** - * Called once per frame by the engine. + * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready). + * @param subMesh The submesh we want to render in the shadow map + * @param useInstances Defines wether will draw in the map using instances + * @returns true if ready otherwise, false */ - update(): void; + isReady(subMesh: SubMesh, useInstances: boolean): boolean; /** - * Called once for each button that changed state since the last frame - * @param buttonIdx Which button index changed - * @param state New state of the button - * @param changes Which properties on the state changed since last frame + * Prepare all the defines in a material relying on a shadow map at the specified light index. + * @param defines Defines of the material we want to update + * @param lightIndex Index of the light in the enabled light list of the material */ - protected _handleButtonChange(buttonIdx: number, state: ExtendedGamepadButton, changes: GamepadButtonChanges): void; + prepareDefines(defines: any, lightIndex: number): void; /** - * Moves the buttons on the controller mesh based on their current state - * @param buttonName the name of the button to move - * @param buttonValue the value of the button which determines the buttons new position + * Binds the shadow related information inside of an effect (information like near, far, darkness... + * defined in the generator but impacting the effect). + * @param lightIndex Index of the light in the enabled light list of the material owning the effect + * @param effect The effect we are binfing the information for */ - protected _lerpButtonTransform(buttonName: string, buttonValue: number): void; + bindShadowLight(lightIndex: string, effect: Effect): void; /** - * Moves the axis on the controller mesh based on its current state - * @param axis the index of the axis - * @param axisValue the value of the axis which determines the meshes new position - * @hidden + * Gets the transformation matrix used to project the meshes into the map from the light point of view. + * (eq to shadow prjection matrix * light transform matrix) + * @returns The transform matrix used to create the shadow map */ - protected _lerpAxisTransform(axis: number, axisValue: number): void; + getTransformMatrix(): Matrix; /** - * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. - * @param scene scene in which to add meshes - * @param meshLoaded optional callback function that will be called if the mesh loads successfully. + * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between + * Cube and 2D textures for instance. */ - initControllerMesh(scene: Scene, meshLoaded?: (mesh: AbstractMesh) => void, forceDefault?: boolean): void; + recreateShadowMap(): void; + private _disposeBlurPostProcesses; + private _disposeRTTandPostProcesses; /** - * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that - * can be transformed by button presses and axes values, based on this._mapping. - * - * @param scene scene in which the meshes exist - * @param meshes list of meshes that make up the controller model to process - * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed. + * Disposes the ShadowGenerator. + * Returns nothing. */ - private processModel(scene, meshes); - private createMeshInfo(rootNode); + dispose(): void; /** - * Gets the ray of the controller in the direction the controller is pointing - * @param length the length the resulting ray should be - * @returns a ray in the direction the controller is pointing + * Serializes the shadow generator setup to a json object. + * @returns The serialized JSON object */ - getForwardRay(length?: number): Ray; + serialize(): any; /** - * Disposes of the controller - */ - dispose(): void; + * Parses a serialized ShadowGenerator and returns a new ShadowGenerator. + * @param parsedShadowGenerator The JSON object to parse + * @param scene The scene to create the shadow map for + * @returns The parsed shadow generator + */ + static Parse(parsedShadowGenerator: any, scene: Scene): ShadowGenerator; } } @@ -34310,31 +34317,31 @@ declare module BABYLON { * Gets the image processing configuration used either in this material. */ /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ imageProcessingConfiguration: Nullable; /** * Gets wether the color curves effect is enabled. */ /** - * Sets wether the color curves effect is enabled. - */ + * Sets wether the color curves effect is enabled. + */ cameraColorCurvesEnabled: boolean; /** * Gets wether the color grading effect is enabled. */ /** - * Gets wether the color grading effect is enabled. - */ + * Gets wether the color grading effect is enabled. + */ cameraColorGradingEnabled: boolean; /** * Gets wether tonemapping is enabled or not. */ /** - * Sets wether tonemapping is enabled or not - */ + * Sets wether tonemapping is enabled or not + */ cameraToneMappingEnabled: boolean; /** * The camera exposure used on this material. @@ -34342,24 +34349,24 @@ declare module BABYLON { * This corresponds to a photographic exposure. */ /** - * The camera exposure used on this material. - * This property is here and not in the camera to allow controlling exposure without full screen post process. - * This corresponds to a photographic exposure. - */ + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ cameraExposure: float; /** * Gets The camera contrast used on this material. */ /** - * Sets The camera contrast used on this material. - */ + * Sets The camera contrast used on this material. + */ cameraContrast: float; /** * Gets the Color Grading 2D Lookup Texture. */ /** - * Sets the Color Grading 2D Lookup Texture. - */ + * Sets the Color Grading 2D Lookup Texture. + */ cameraColorGradingTexture: Nullable; /** * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). @@ -34368,11 +34375,11 @@ declare module BABYLON { * corresponding to low luminance, medium luminance, and high luminance areas respectively. */ /** - * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). - * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. - * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; - * corresponding to low luminance, medium luminance, and high luminance areas respectively. - */ + * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ cameraColorCurves: Nullable; /** * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB. @@ -34411,11 +34418,11 @@ declare module BABYLON { /** * Compute the primary color according to the chosen perceptual color. */ - private _computePrimaryColorFromPerceptualColor(); + private _computePrimaryColorFromPerceptualColor; /** * Compute the highlights and shadow colors according to their chosen levels. */ - private _computePrimaryColors(); + private _computePrimaryColors; /** * Build the uniform buffer used in the material. */ @@ -34786,23 +34793,23 @@ declare module BABYLON { * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers. */ /** - * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers. - */ + * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers. + */ useLogarithmicDepth: boolean; /** * Gets the current transparency mode. */ /** - * Sets the transparency mode of the material. - * - * | Value | Type | Description | - * | ----- | ----------------------------------- | ----------- | - * | 0 | OPAQUE | | - * | 1 | ALPHATEST | | - * | 2 | ALPHABLEND | | - * | 3 | ALPHATESTANDBLEND | | - * - */ + * Sets the transparency mode of the material. + * + * | Value | Type | Description | + * | ----- | ----------------------------------- | ----------- | + * | 0 | OPAQUE | | + * | 1 | ALPHATEST | | + * | 2 | ALPHABLEND | | + * | 3 | ALPHATESTANDBLEND | | + * + */ transparencyMode: Nullable; /** * Returns true if alpha blending should be disabled. @@ -34846,8 +34853,8 @@ declare module BABYLON { * @returns boolean specifiying if the material uses metallic roughness workflow. */ isMetallicWorkflow(): boolean; - private _prepareEffect(mesh, defines, onCompiled?, onError?, useInstances?, useClipPlane?); - private _prepareDefines(mesh, defines, useInstances?, useClipPlane?); + private _prepareEffect; + private _prepareDefines; /** * Force shader compilation */ @@ -34878,13 +34885,13 @@ declare module BABYLON { * Returns the texture used for reflections. * @returns - Reflection texture if present. Otherwise, returns the environment texture. */ - private _getReflectionTexture(); + private _getReflectionTexture; /** * Returns the texture used for refraction or null if none is used. * @returns - Refection texture if present. If no refraction texture and refraction * is linked with transparency, returns environment texture. Otherwise, returns null. */ - private _getRefractionTexture(); + private _getRefractionTexture; /** * Disposes the resources of the material. * @param forceDisposeEffect - Forces the disposal of effects. @@ -34950,8 +34957,8 @@ declare module BABYLON { * Gets the current double sided mode. */ /** - * If sets to true and backfaceCulling is false, normals will be flipped on the backside. - */ + * If sets to true and backfaceCulling is false, normals will be flipped on the backside. + */ doubleSided: boolean; lightmapTexture: BaseTexture; useLightmapAsShadowmap: boolean; @@ -35272,31 +35279,31 @@ declare module BABYLON { * Gets the image processing configuration used either in this material. */ /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ imageProcessingConfiguration: ImageProcessingConfiguration; /** * Gets wether the color curves effect is enabled. */ /** - * Sets wether the color curves effect is enabled. - */ + * Sets wether the color curves effect is enabled. + */ cameraColorCurvesEnabled: boolean; /** * Gets wether the color grading effect is enabled. */ /** - * Gets wether the color grading effect is enabled. - */ + * Gets wether the color grading effect is enabled. + */ cameraColorGradingEnabled: boolean; /** * Gets wether tonemapping is enabled or not. */ /** - * Sets wether tonemapping is enabled or not - */ + * Sets wether tonemapping is enabled or not + */ cameraToneMappingEnabled: boolean; /** * The camera exposure used on this material. @@ -35304,24 +35311,24 @@ declare module BABYLON { * This corresponds to a photographic exposure. */ /** - * The camera exposure used on this material. - * This property is here and not in the camera to allow controlling exposure without full screen post process. - * This corresponds to a photographic exposure. - */ + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ cameraExposure: number; /** * Gets The camera contrast used on this material. */ /** - * Sets The camera contrast used on this material. - */ + * Sets The camera contrast used on this material. + */ cameraContrast: number; /** * Gets the Color Grading 2D Lookup Texture. */ /** - * Sets the Color Grading 2D Lookup Texture. - */ + * Sets the Color Grading 2D Lookup Texture. + */ cameraColorGradingTexture: Nullable; /** * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). @@ -35330,11 +35337,11 @@ declare module BABYLON { * corresponding to low luminance, medium luminance, and high luminance areas respectively. */ /** - * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). - * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. - * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; - * corresponding to low luminance, medium luminance, and high luminance areas respectively. - */ + * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ cameraColorCurves: Nullable; /** * Instantiates a new PBRMaterial instance. @@ -35672,11 +35679,11 @@ declare module BABYLON { /** * Occurs when the file being loaded is a .3dl LUT file. */ - private load3dlTexture(); + private load3dlTexture; /** * Starts the loading process of the texture. */ - private loadTexture(); + private loadTexture; /** * Clones the color gradind texture. */ @@ -35717,12 +35724,12 @@ declare module BABYLON { */ boundingBoxSize: Vector3; protected _rotationY: number; - /** - * Gets texture matrix rotation angle around Y axis radians. - */ /** * Sets texture matrix rotation angle around Y axis in radians. */ + /** + * Gets texture matrix rotation angle around Y axis radians. + */ rotationY: number; private _noMipmap; private _files; @@ -35793,7 +35800,7 @@ declare module BABYLON { * Gets the current state of canRescale */ readonly canRescale: boolean; - private _recreate(textureSize); + private _recreate; /** * Scales the texture * @param ratio the scale factor to apply to both width and height @@ -35871,20 +35878,20 @@ declare module BABYLON { */ coordinatesMode: number; protected _isBlocking: boolean; - /** - * Gets wether or not the texture is blocking during loading. - */ /** * Sets wether or not the texture is blocking during loading. */ + /** + * Gets wether or not the texture is blocking during loading. + */ isBlocking: boolean; protected _rotationY: number; - /** - * Gets texture matrix rotation angle around Y axis radians. - */ /** * Sets texture matrix rotation angle around Y axis in radians. */ + /** + * Gets texture matrix rotation angle around Y axis radians. + */ rotationY: number; /** * Gets or sets the center of the bounding box associated with the cube texture @@ -35914,7 +35921,7 @@ declare module BABYLON { /** * Occurs when the file is raw .hdr file. */ - private loadTexture(); + private loadTexture; clone(): HDRCubeTexture; delayLoad(): void; getReflectionTextureMatrix(): Matrix; @@ -36266,9 +36273,9 @@ declare module BABYLON { blurKernel: number; blurKernelX: number; blurKernelY: number; - private _autoComputeBlurKernel(); + private _autoComputeBlurKernel; protected _onRatioRescale(): void; - private _updateGammaSpace(); + private _updateGammaSpace; private _imageProcessingConfigChangeObserver; constructor(name: string, size: number | { width: number; @@ -36276,7 +36283,7 @@ declare module BABYLON { } | { ratio: number; }, scene: Scene, generateMipMaps?: boolean, type?: number, samplingMode?: number, generateDepthBuffer?: boolean); - private _preparePostProcesses(); + private _preparePostProcesses; clone(): MirrorTexture; serialize(): any; dispose(): void; @@ -36306,8 +36313,8 @@ declare module BABYLON { wrapV: number; constructor(name: string, size: any, count: number, scene: Scene, options?: IMultiRenderTargetOptions); - private _createInternalTextures(); - private _createTextures(); + private _createInternalTextures; + private _createTextures; samples: number; resize(size: any): void; protected unbindFrameBuffer(engine: Engine, faceIndex: number): void; @@ -36400,8 +36407,8 @@ declare module BABYLON { * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...) */ constructor(data: ArrayBufferView, width: number, height: number, depth: number, - /** Gets or sets the texture format to use */ - format: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number, textureType?: number); + /** Gets or sets the texture format to use */ + format: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number, textureType?: number); /** * Update the texture with new data * @param data defines the data to store in the texture @@ -36445,7 +36452,7 @@ private static _REFRESHRATE_RENDER_ONEVERYTWOFRAMES: number; * Use this list to define the list of mesh you want to render. */ renderList: Nullable>; - private _hookArray(array); + private _hookArray; renderParticles: boolean; renderSprites: boolean; coordinatesMode: number; @@ -36557,7 +36564,7 @@ private static _REFRESHRATE_RENDER_ONEVERYTWOFRAMES: number; * @param generateStencil Specifies whether or not a stencil should be allocated in the texture */ createDepthStencilTexture(comparisonFunction?: number, bilinearFiltering?: boolean, generateStencil?: boolean): void; - private _processSizeParameter(size); + private _processSizeParameter; samples: number; resetRefreshCounter(): void; refreshRate: number; @@ -36578,9 +36585,9 @@ private static _REFRESHRATE_RENDER_ONEVERYTWOFRAMES: number; ratio: number; }): void; render(useCameraPostProcess?: boolean, dumpForDebug?: boolean): void; - private _bestReflectionRenderTargetDimension(renderDimension, scale); + private _bestReflectionRenderTargetDimension; protected unbindFrameBuffer(engine: Engine, faceIndex: number): void; - private renderToTarget(faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug); + private renderToTarget; /** * Overrides the default sort function applied in the renderging group to prepare the meshes. * This allowed control for front to back rendering or reversly depending of the special needs. @@ -36702,7 +36709,7 @@ declare module BABYLON { updateURL(url: string, buffer?: Nullable): void; delayLoad(): void; updateSamplingMode(samplingMode: number): void; - private _prepareRowForTextureGeneration(x, y, z, t); + private _prepareRowForTextureGeneration; getTextureMatrix(): Matrix; getReflectionTextureMatrix(): Matrix; clone(): Texture; @@ -36765,8 +36772,8 @@ declare module BABYLON { * @param {VideoTextureSettings} [settings] allows finer control over video usage */ constructor(name: Nullable, src: string | string[] | HTMLVideoElement, scene: Nullable, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number, settings?: VideoTextureSettings); - private _getName(src); - private _getVideo(src); + private _getName; + private _getVideo; private _createInternalTexture; private reset; /** @@ -36799,6 +36806,105 @@ declare module BABYLON { } } +declare var DracoDecoderModule: any; +declare var WebAssembly: any; +declare module BABYLON { + /** + * Configuration for Draco compression + */ + interface IDracoCompressionConfiguration { + /** + * Configuration for the decoder. + */ + decoder?: { + /** + * The url to the WebAssembly module. + */ + wasmUrl?: string; + /** + * The url to the WebAssembly binary. + */ + wasmBinaryUrl?: string; + /** + * The url to the fallback JavaScript module. + */ + fallbackUrl?: string; + }; + } + /** + * Draco compression (https://google.github.io/draco/) + * + * This class wraps the Draco module. + * + * **Encoder** + * + * The encoder is not currently implemented. + * + * **Decoder** + * + * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com. + * + * To update the configuration, use the following code: + * ```javascript + * BABYLON.DracoCompression.Configuration = { + * decoder: { + * wasmUrl: "", + * wasmBinaryUrl: "", + * fallbackUrl: "", + * } + * }; + * ``` + * + * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version. + * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser. + * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session. + * + * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync: + * ```javascript + * var dracoCompression = new BABYLON.DracoCompression(); + * var vertexData = await dracoCompression.decodeMeshAsync(data, { + * [BABYLON.VertexBuffer.PositionKind]: 0 + * }); + * ``` + * + * @see https://www.babylonjs-playground.com/#N3EK4B#0 + */ + class DracoCompression implements IDisposable { + private static _DecoderModulePromise; + /** + * The configuration. Defaults to the following urls: + * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js" + * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm" + * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js" + */ + static Configuration: IDracoCompressionConfiguration; + /** + * Returns true if the decoder is available. + */ + static readonly DecoderAvailable: boolean; + /** + * Constructor + */ + constructor(); + /** + * Stop all async operations and release resources. + */ + dispose(): void; + /** + * Decode Draco compressed mesh data to vertex data. + * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data + * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids + * @returns A promise that resolves with the decoded vertex data + */ + decodeMeshAsync(data: ArrayBuffer | ArrayBufferView, attributes: { + [kind: string]: number; + }): Promise; + private static _GetDecoderModule; + private static _LoadScriptAsync; + private static _LoadFileAsync; + } +} + declare module BABYLON { /** * Particle emitter emitting particles from the inside of a box. @@ -36904,7 +37010,7 @@ declare module BABYLON { * Gets or sets the angle of the emission cone */ angle: number; - private _buildHeight(); + private _buildHeight; /** * Creates a new instance ConeParticleEmitter * @param radius the radius of the emission cone (1 by default) @@ -36912,8 +37018,8 @@ declare module BABYLON { * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0) */ constructor(radius?: number, angle?: number, - /** defines how much to randomize the particle direction [0-1] (default is 0) */ - directionRandomizer?: number); + /** defines how much to randomize the particle direction [0-1] (default is 0) */ + directionRandomizer?: number); /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system @@ -36986,18 +37092,18 @@ declare module BABYLON { * @param directionRandomizer defines how much to randomize the particle direction [0-1] */ constructor( - /** - * The radius of the emission hemisphere. - */ - radius?: number, - /** - * The range of emission [0-1] 0 Surface only, 1 Entire Radius. - */ - radiusRange?: number, - /** - * How much to randomize the particle direction [0-1]. - */ - directionRandomizer?: number); + /** + * The radius of the emission hemisphere. + */ + radius?: number, + /** + * The range of emission [0-1] 0 Surface only, 1 Entire Radius. + */ + radiusRange?: number, + /** + * How much to randomize the particle direction [0-1]. + */ + directionRandomizer?: number); /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system @@ -37188,18 +37294,18 @@ declare module BABYLON { * @param directionRandomizer defines how much to randomize the particle direction [0-1] */ constructor( - /** - * The radius of the emission sphere. - */ - radius?: number, - /** - * The range of emission [0-1] 0 Surface only, 1 Entire Radius. - */ - radiusRange?: number, - /** - * How much to randomize the particle direction [0-1]. - */ - directionRandomizer?: number); + /** + * The radius of the emission sphere. + */ + radius?: number, + /** + * The range of emission [0-1] 0 Surface only, 1 Entire Radius. + */ + radiusRange?: number, + /** + * How much to randomize the particle direction [0-1]. + */ + directionRandomizer?: number); /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system @@ -37265,14 +37371,14 @@ declare module BABYLON { * @param direction2 the max limit of the emission direction (up vector by default) */ constructor(radius?: number, - /** - * The min limit of the emission direction. - */ - direction1?: Vector3, - /** - * The max limit of the emission direction. - */ - direction2?: Vector3); + /** + * The min limit of the emission direction. + */ + direction1?: Vector3, + /** + * The max limit of the emission direction. + */ + direction2?: Vector3); /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system @@ -37329,20 +37435,20 @@ declare module BABYLON { applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3): void; applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3): void; generatePhysicsBody(impostor: PhysicsImpostor): void; - private _processChildMeshes(mainImpostor); + private _processChildMeshes; removePhysicsBody(impostor: PhysicsImpostor): void; generateJoint(impostorJoint: PhysicsImpostorJoint): void; removeJoint(impostorJoint: PhysicsImpostorJoint): void; - private _addMaterial(name, friction, restitution); - private _checkWithEpsilon(value); - private _createShape(impostor); - private _createHeightmap(object, pointDepth?); + private _addMaterial; + private _checkWithEpsilon; + private _createShape; + private _createHeightmap; private _minus90X; private _plus90X; private _tmpPosition; private _tmpDeltaPosition; private _tmpUnityRotation; - private _updatePhysicsBodyTransformation(impostor); + private _updatePhysicsBodyTransformation; setTransformationFromPhysicsBody(impostor: PhysicsImpostor): void; setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion): void; isSupported(): boolean; @@ -37365,7 +37471,7 @@ declare module BABYLON { getRadius(impostor: PhysicsImpostor): number; getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void; dispose(): void; - private _extendNamespace(); + private _extendNamespace; } } @@ -37412,105 +37518,6 @@ declare module BABYLON { } } -declare var DracoDecoderModule: any; -declare var WebAssembly: any; -declare module BABYLON { - /** - * Configuration for Draco compression - */ - interface IDracoCompressionConfiguration { - /** - * Configuration for the decoder. - */ - decoder?: { - /** - * The url to the WebAssembly module. - */ - wasmUrl?: string; - /** - * The url to the WebAssembly binary. - */ - wasmBinaryUrl?: string; - /** - * The url to the fallback JavaScript module. - */ - fallbackUrl?: string; - }; - } - /** - * Draco compression (https://google.github.io/draco/) - * - * This class wraps the Draco module. - * - * **Encoder** - * - * The encoder is not currently implemented. - * - * **Decoder** - * - * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com. - * - * To update the configuration, use the following code: - * ```javascript - * BABYLON.DracoCompression.Configuration = { - * decoder: { - * wasmUrl: "", - * wasmBinaryUrl: "", - * fallbackUrl: "", - * } - * }; - * ``` - * - * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version. - * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser. - * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session. - * - * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync: - * ```javascript - * var dracoCompression = new BABYLON.DracoCompression(); - * var vertexData = await dracoCompression.decodeMeshAsync(data, { - * [BABYLON.VertexBuffer.PositionKind]: 0 - * }); - * ``` - * - * @see https://www.babylonjs-playground.com/#N3EK4B#0 - */ - class DracoCompression implements IDisposable { - private static _DecoderModulePromise; - /** - * The configuration. Defaults to the following urls: - * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js" - * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm" - * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js" - */ - static Configuration: IDracoCompressionConfiguration; - /** - * Returns true if the decoder is available. - */ - static readonly DecoderAvailable: boolean; - /** - * Constructor - */ - constructor(); - /** - * Stop all async operations and release resources. - */ - dispose(): void; - /** - * Decode Draco compressed mesh data to vertex data. - * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data - * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids - * @returns A promise that resolves with the decoded vertex data - */ - decodeMeshAsync(data: ArrayBuffer | ArrayBufferView, attributes: { - [kind: string]: number; - }): Promise; - private static _GetDecoderModule(); - private static _LoadScriptAsync(url); - private static _LoadFileAsync(url); - } -} - declare module BABYLON { /** * This represents a set of one or more post processes in Babylon. @@ -37687,9 +37694,9 @@ declare module BABYLON { * This groups tools to convert HDR texture to native colors array. */ class HDRTools { - private static Ldexp(mantissa, exponent); - private static Rgbe2float(float32array, red, green, blue, exponent, index); - private static readStringLine(uint8array, startIndex); + private static Ldexp; + private static Rgbe2float; + private static readStringLine; /** * Reads header information from an RGBE texture stored in a native array. * More information on this format are available here: @@ -37723,7 +37730,7 @@ declare module BABYLON { * @return The pixels data in RGB right to left up to down order. */ static RGBE_ReadPixels(uint8array: Uint8Array, hdrInfo: HDRInfo): Float32Array; - private static RGBE_ReadPixels_RLE(uint8array, hdrInfo); + private static RGBE_ReadPixels_RLE; } } @@ -37805,8 +37812,8 @@ declare module BABYLON { * @return The cubemap data */ static ConvertPanoramaToCubemap(float32Array: Float32Array, inputWidth: number, inputHeight: number, size: number): CubeMapInfo; - private static CreateCubemapTexture(texSize, faceData, float32Array, inputWidth, inputHeight); - private static CalcProjectionSpherical(vDir, float32Array, inputWidth, inputHeight); + private static CreateCubemapTexture; + private static CalcProjectionSpherical; } } @@ -37829,7 +37836,7 @@ declare module BABYLON { private _config; private _texturePath; constructor(name: string, texturePath: any, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); - private loadJson(jsonUrl); + private loadJson; isReady(): boolean; render(useCameraPostProcess?: boolean): void; updateTextures(): void; @@ -37861,7 +37868,7 @@ declare module BABYLON { * @param generateMipMaps defines if mipmaps must be generated (true by default) */ constructor(name: string, size?: number, scene?: Nullable, fallbackTexture?: Texture, generateMipMaps?: boolean); - private _updateShaderUniforms(); + private _updateShaderUniforms; /** Generate the current state of the procedural texture */ render(useCameraPostProcess?: boolean): void; /** @@ -37908,7 +37915,7 @@ declare module BABYLON { private _fallbackTextureUsed; private _engine; constructor(name: string, size: any, fragment: any, scene: Nullable, fallbackTexture?: Nullable, generateMipMaps?: boolean, isCube?: boolean); - private _createIndexBuffer(); + private _createIndexBuffer; reset(): void; isReady(): boolean; @@ -37918,7 +37925,7 @@ declare module BABYLON { getRenderSize(): number; resize(size: number, generateMipMaps: boolean): void; - private _checkUniform(uniformName); + private _checkUniform; setTexture(name: string, texture: Texture): ProceduralTexture; setFloat(name: string, value: number): ProceduralTexture; /** @@ -38052,7 +38059,7 @@ declare module BABYLON { * Enable or disable the bloom from the pipeline */ bloomEnabled: boolean; - private _rebuildBloom(); + private _rebuildBloom; /** * If the depth of field is enabled. */ @@ -38102,9 +38109,9 @@ declare module BABYLON { private _hasCleared; private _prevPostProcess; private _prevPrevPostProcess; - private _setAutoClearAndTextureSharing(postProcess, skipTextureSharing?); - private _buildPipeline(); - private _disposePostProcesses(disposeNonRecreated?); + private _setAutoClearAndTextureSharing; + private _buildPipeline; + private _disposePostProcesses; /** * Adds a camera to the pipeline * @param camera the camera to be added @@ -38216,10 +38223,10 @@ declare module BABYLON { * Removes the internal pipeline assets and detaches the pipeline from the scene cameras */ dispose(disableDepthRender?: boolean): void; - private _createChromaticAberrationPostProcess(ratio); - private _createHighlightsPostProcess(ratio); - private _createDepthOfFieldPostProcess(ratio); - private _createGrainTexture(); + private _createChromaticAberrationPostProcess; + private _createHighlightsPostProcess; + private _createDepthOfFieldPostProcess; + private _createGrainTexture; } } @@ -38314,12 +38321,12 @@ declare module BABYLON { * Removes the internal pipeline assets and detatches the pipeline from the scene cameras */ dispose(disableGeometryBufferRenderer?: boolean): void; - private _createBlurPostProcess(ssaoRatio, blurRatio); + private _createBlurPostProcess; - private _generateHemisphere(); - private _createSSAOPostProcess(ratio); - private _createSSAOCombinePostProcess(ratio); - private _createRandomTexture(); + private _generateHemisphere; + private _createSSAOPostProcess; + private _createSSAOCombinePostProcess; + private _createRandomTexture; /** * Serialize the rendering pipeline (Used when exporting) * @returns the serialized object @@ -38404,11 +38411,11 @@ declare module BABYLON { * Removes the internal pipeline assets and detatches the pipeline from the scene cameras */ dispose(disableDepthRender?: boolean): void; - private _createBlurPostProcess(ratio); + private _createBlurPostProcess; - private _createSSAOPostProcess(ratio); - private _createSSAOCombinePostProcess(ratio); - private _createRandomTexture(); + private _createSSAOPostProcess; + private _createSSAOCombinePostProcess; + private _createRandomTexture; } } @@ -38495,19 +38502,19 @@ declare module BABYLON { * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to */ constructor(name: string, scene: Scene, ratio: number, originalPostProcess?: Nullable, cameras?: Camera[]); - private _buildPipeline(); - private _createDownSampleX4PostProcess(scene, ratio); - private _createBrightPassPostProcess(scene, ratio); - private _createBlurPostProcesses(scene, ratio, indice, blurWidthKey?); - private _createTextureAdderPostProcess(scene, ratio); - private _createVolumetricLightPostProcess(scene, ratio); - private _createLuminancePostProcesses(scene, textureType); - private _createHdrPostProcess(scene, ratio); - private _createLensFlarePostProcess(scene, ratio); - private _createDepthOfFieldPostProcess(scene, ratio); - private _createMotionBlurPostProcess(scene, ratio); - private _getDepthTexture(); - private _disposePostProcesses(); + private _buildPipeline; + private _createDownSampleX4PostProcess; + private _createBrightPassPostProcess; + private _createBlurPostProcesses; + private _createTextureAdderPostProcess; + private _createVolumetricLightPostProcess; + private _createLuminancePostProcesses; + private _createHdrPostProcess; + private _createLensFlarePostProcess; + private _createDepthOfFieldPostProcess; + private _createMotionBlurPostProcess; + private _getDepthTexture; + private _disposePostProcesses; /** * Dispose of the pipeline and stop all post processes */ @@ -40767,7 +40774,7 @@ declare module BABYLON { /** * Sets the useRightHandedSystem flag on the scene. */ - FORCE_RIGHT_HANDED = 1, + FORCE_RIGHT_HANDED = 1 } /** * Mode that determines what animations will start. @@ -40784,7 +40791,7 @@ declare module BABYLON { /** * All animations will start. */ - ALL = 2, + ALL = 2 } /** * Interface that contains the data for the glTF asset. @@ -40827,7 +40834,7 @@ declare module BABYLON { /** * The asset is completely loaded. */ - COMPLETE = 2, + COMPLETE = 2 } /** @hidden */ interface IGLTFLoader extends IDisposable { @@ -40947,8 +40954,19 @@ private static _CreateGLTFLoaderV2: (parent: GLTFFileLoader) => IGLTFLoader; private _onCompleteObserver; /** * Callback raised when the asset is completely loaded, immediately before the loader is disposed. + * For assets with LODs, raised when all of the LODs are complete. + * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise. */ onComplete: () => void; + /** + * Observable raised when an error occurs. + */ + readonly onErrorObservable: Observable; + private _onErrorObserver; + /** + * Callback raised when an error occurs. + */ + onError: (reason: any) => void; /** * Observable raised after the loader is disposed. */ @@ -41048,14 +41066,14 @@ private static _CreateGLTFLoaderV2: (parent: GLTFFileLoader) => IGLTFLoader; * @returns the created plugin */ createPlugin(): ISceneLoaderPlugin | ISceneLoaderPluginAsync; - private _parse(data); - private _getLoader(loaderData); - private _parseBinary(data); - private _parseV1(binaryReader); - private _parseV2(binaryReader); - private static _parseVersion(version); - private static _compareVersion(a, b); - private static _decodeBufferToText(buffer); + private _parse; + private _getLoader; + private _parseBinary; + private _parseV1; + private _parseV2; + private static _parseVersion; + private static _compareVersion; + private static _decodeBufferToText; private static readonly _logSpaces; private _logIndentLevel; private _loggingEnabled; @@ -41065,17 +41083,17 @@ private static _CreateGLTFLoaderV2: (parent: GLTFFileLoader) => IGLTFLoader; /** @hidden */ - private _logEnabled(message); - private _logDisabled(message); + private _logEnabled; + private _logDisabled; private _capturePerformanceCounters; /** @hidden */ /** @hidden */ - private _startPerformanceCounterEnabled(counterName); - private _startPerformanceCounterDisabled(counterName); - private _endPerformanceCounterEnabled(counterName); - private _endPerformanceCounterDisabled(counterName); + private _startPerformanceCounterEnabled; + private _startPerformanceCounterDisabled; + private _endPerformanceCounterEnabled; + private _endPerformanceCounterDisabled; } } @@ -41201,7 +41219,6 @@ declare module BABYLON.GLTF2 { - private _disposed; private _state; private _extensions; @@ -41214,9 +41231,6 @@ declare module BABYLON.GLTF2 { private static _ExtensionNames; private static _ExtensionFactories; private static _Register(name: string, factory: (loader: GLTFLoader) => GLTFLoaderExtension): void; - /** - * Loader state or null if the loader is not active. - */ readonly state: Nullable; constructor(parent: GLTFFileLoader); dispose(): void; @@ -41227,45 +41241,46 @@ private static _Register(name: string, factory: (loader: GLTFLoader) => GLTFLoad animationGroups: AnimationGroup[]; }>; loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise; - private _loadAsync(nodes); - private _loadData(data); - private _setupData(); - private _loadExtensions(); - private _checkExtensions(); - private _createRootNode(); + private _loadAsync; + private _loadData; + private _setupData; + private _loadExtensions; + private _checkExtensions; + private _setState; + private _createRootNode; - private _forEachPrimitive(node, callback); - private _getMeshes(); - private _getSkeletons(); - private _getAnimationGroups(); - private _startAnimations(); + private _forEachPrimitive; + private _getMeshes; + private _getSkeletons; + private _getAnimationGroups; + private _startAnimations; - private _loadMeshAsync(context, node, mesh, babylonMesh); - private _loadPrimitiveAsync(context, node, mesh, primitive, babylonMesh); - private _loadVertexDataAsync(context, primitive, babylonMesh); - private _createMorphTargets(context, node, mesh, primitive, babylonMesh); - private _loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry); - private _loadMorphTargetVertexDataAsync(context, babylonGeometry, attributes, babylonMorphTarget); - private static _LoadTransform(node, babylonNode); - private _loadSkinAsync(context, node, mesh, skin); - private _loadBones(context, skin); - private _loadBone(node, skin, babylonBones); - private _loadSkinInverseBindMatricesDataAsync(context, skin); - private _updateBoneMatrices(babylonSkeleton, inverseBindMatricesData); - private _getNodeMatrix(node); - private _loadCamera(context, camera, babylonMesh); - private _loadAnimationsAsync(); - private _loadAnimationAsync(context, animation); - private _loadAnimationChannelAsync(context, animationContext, animation, channel, babylonAnimationGroup); - private _loadAnimationSamplerAsync(context, sampler); - private _loadBufferAsync(context, buffer); + private _loadMeshAsync; + private _loadPrimitiveAsync; + private _loadVertexDataAsync; + private _createMorphTargets; + private _loadMorphTargetsAsync; + private _loadMorphTargetVertexDataAsync; + private static _LoadTransform; + private _loadSkinAsync; + private _loadBones; + private _loadBone; + private _loadSkinInverseBindMatricesDataAsync; + private _updateBoneMatrices; + private _getNodeMatrix; + private _loadCamera; + private _loadAnimationsAsync; + private _loadAnimationAsync; + private _loadAnimationChannelAsync; + private _loadAnimationSamplerAsync; + private _loadBufferAsync; - private _loadIndicesAccessorAsync(context, accessor); - private _loadFloatAccessorAsync(context, accessor); + private _loadIndicesAccessorAsync; + private _loadFloatAccessorAsync; - private _loadVertexAccessorAsync(context, accessor, kind); - private _getDefaultMaterial(drawMode); - private _loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial); + private _loadVertexAccessorAsync; + private _getDefaultMaterial; + private _loadMaterialMetallicRoughnessPropertiesAsync; @@ -41273,19 +41288,20 @@ private static _Register(name: string, factory: (loader: GLTFLoader) => GLTFLoad - private _loadSampler(context, sampler); + private _loadSampler; - private _onProgress(); + private _onProgress; private static _GetProperty(context: string, array: ArrayLike | undefined, index: number | undefined): T; - private static _GetTextureWrapMode(context, mode); - private static _GetTextureSamplingMode(context, magFilter?, minFilter?); - private static _GetTypedArray(context, componentType, bufferView, byteOffset, length); - private static _GetNumComponents(context, type); - private static _ValidateUri(uri); - private static _GetDrawMode(context, mode); - private _compileMaterialsAsync(); - private _compileShadowGeneratorsAsync(); + private static _GetTextureWrapMode; + private static _GetTextureSamplingMode; + private static _GetTypedArray; + private static _GetNumComponents; + private static _ValidateUri; + private static _GetDrawMode; + private _compileMaterialsAsync; + private _compileShadowGeneratorsAsync; + } } @@ -41303,7 +41319,7 @@ declare module BABYLON.GLTF2 { /** * Gets or sets extension name */ - readonly abstract name: string; + abstract readonly name: string; protected _loader: GLTFLoader; /** * Creates new GLTFLoaderExtension @@ -41314,6 +41330,14 @@ declare module BABYLON.GLTF2 { * Release all resources */ dispose(): void; + /** + * Override this method to do work after the state changes to LOADING. + */ + protected _onLoading(): void; + /** + * Override this method to do work after the state changes to READY. + */ + protected _onReady(): void; /** * Override this method to modify the default behavior for loading scenes. * @hidden @@ -41364,6 +41388,16 @@ declare module BABYLON.GLTF2 { * @hidden */ protected _loadExtrasValueAsync(context: string, property: IProperty, actionAsync: (extensionContext: string, value: TProperty) => Nullable>): Nullable>; + /** + * Helper method called by the loader after the state changes to LOADING. + * @hidden + */ +private static _OnLoading(loader: GLTFLoader): void; + /** + * Helper method called by the loader after the state changes to READY. + * @hidden + */ +private static _OnReady(loader: GLTFLoader): void; /** * Helper method called by the loader to allow extensions to override loading scenes. * @hidden @@ -41441,16 +41475,16 @@ declare module BABYLON.GLTF2.Extensions { private _materialIndexLOD; private _materialSignalLODs; private _materialPromiseLODs; - constructor(loader: GLTFLoader); dispose(): void; + protected _onReady(): void; protected _loadNodeAsync(context: string, node: _ILoaderNode): Nullable>; protected _loadMaterialAsync(context: string, material: _ILoaderMaterial, mesh: _ILoaderMesh, babylonMesh: Mesh, babylonDrawMode: number, assign: (babylonMaterial: Material) => void): Nullable>; protected _loadUriAsync(context: string, uri: string): Nullable>; /** * Gets an array of LOD properties from lowest to highest. */ - private _getLODs(context, property, array, ids); - private _disposeUnusedMaterials(); + private _getLODs; + private _disposeUnusedMaterials; } } @@ -41468,7 +41502,8 @@ declare module BABYLON.GLTF2.Extensions { /** @hidden */ class MSFT_sRGBFactors extends GLTFLoaderExtension { readonly name: string; - protected _loadMaterialAsync(context: string, material: _ILoaderMaterial, mesh: _ILoaderMesh, babylonMesh: Mesh, babylonDrawMode: number, assign: (babylonMaterial: Material) => void): Nullable>; + protected _loadMaterialPropertiesAsync(context: string, material: _ILoaderMaterial, babylonMaterial: Material): Nullable>; + private _convertColorsToLinear; } } @@ -41494,7 +41529,7 @@ declare module BABYLON.GLTF2.Extensions { class KHR_materials_pbrSpecularGlossiness extends GLTFLoaderExtension { readonly name: string; protected _loadMaterialPropertiesAsync(context: string, material: _ILoaderMaterial, babylonMaterial: Material): Nullable>; - private _loadSpecularGlossinessPropertiesAsync(context, material, properties, babylonMaterial); + private _loadSpecularGlossinessPropertiesAsync; } } @@ -41506,7 +41541,7 @@ declare module BABYLON.GLTF2.Extensions { class KHR_materials_unlit extends GLTFLoaderExtension { readonly name: string; protected _loadMaterialPropertiesAsync(context: string, material: _ILoaderMaterial, babylonMaterial: Material): Nullable>; - private _loadUnlitPropertiesAsync(context, material, babylonMaterial); + private _loadUnlitPropertiesAsync; } } @@ -41517,9 +41552,10 @@ declare module BABYLON.GLTF2.Extensions { */ class KHR_lights extends GLTFLoaderExtension { readonly name: string; + private _lights?; + protected _onLoading(): void; protected _loadSceneAsync(context: string, scene: _ILoaderScene): Nullable>; protected _loadNodeAsync(context: string, node: _ILoaderNode): Nullable>; - private readonly _lights; } } @@ -41541,9 +41577,10 @@ declare module BABYLON.GLTF2.Extensions { */ class EXT_lights_imageBased extends GLTFLoaderExtension { readonly name: string; + private _lights?; + protected _onLoading(): void; protected _loadSceneAsync(context: string, scene: _ILoaderScene): Nullable>; - private _loadLightAsync(context, light); - private readonly _lights; + private _loadLightAsync; } } @@ -41684,7 +41721,7 @@ declare module BABYLON.GLTF2 { * Lazy load a local engine with premultiplied alpha set to false */ - private reorderIndicesBasedOnPrimitiveMode(submesh, primitiveMode, babylonIndices, byteOffset, binaryWriter); + private reorderIndicesBasedOnPrimitiveMode; /** * Reorders the vertex attribute data based on the primitive mode. This is necessary when indices are not available and the winding order is * clock-wise during export to glTF @@ -41696,7 +41733,7 @@ declare module BABYLON.GLTF2 { * @param byteOffset The offset to the binary data * @param binaryWriter The binary data for the glTF file */ - private reorderVertexAttributeDataBasedOnPrimitiveMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter); + private reorderVertexAttributeDataBasedOnPrimitiveMode; /** * Reorders the vertex attributes in the correct triangle mode order . This is necessary when indices are not available and the winding order is * clock-wise during export to glTF @@ -41708,7 +41745,7 @@ declare module BABYLON.GLTF2 { * @param byteOffset The offset to the binary data * @param binaryWriter The binary data for the glTF file */ - private reorderTriangleFillMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter); + private reorderTriangleFillMode; /** * Reorders the vertex attributes in the correct triangle strip order. This is necessary when indices are not available and the winding order is * clock-wise during export to glTF @@ -41720,7 +41757,7 @@ declare module BABYLON.GLTF2 { * @param byteOffset The offset to the binary data * @param binaryWriter The binary data for the glTF file */ - private reorderTriangleStripDrawMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter); + private reorderTriangleStripDrawMode; /** * Reorders the vertex attributes in the correct triangle fan order. This is necessary when indices are not available and the winding order is * clock-wise during export to glTF @@ -41732,7 +41769,7 @@ declare module BABYLON.GLTF2 { * @param byteOffset The offset to the binary data * @param binaryWriter The binary data for the glTF file */ - private reorderTriangleFanMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter); + private reorderTriangleFanMode; /** * Writes the vertex attribute data to binary * @param vertices The vertices to write to the binary writer @@ -41741,7 +41778,7 @@ declare module BABYLON.GLTF2 { * @param meshAttributeArray The vertex attribute data * @param binaryWriter The writer containing the binary data */ - private writeVertexAttributeData(vertices, byteOffset, vertexAttributeKind, meshAttributeArray, binaryWriter); + private writeVertexAttributeData; /** * Writes mesh attribute data to a data buffer * Returns the bytelength of the data @@ -41750,7 +41787,7 @@ declare module BABYLON.GLTF2 { * @param binaryWriter The buffer to write the binary data to * @param indices Used to specify the order of the vertex data */ - private writeAttributeData(vertexBufferKind, meshAttributeArray, byteStride, binaryWriter); + private writeAttributeData; /** * Generates glTF json data * @param shouldUseGlb Indicates whether the json should be written for a glb file @@ -41758,7 +41795,7 @@ declare module BABYLON.GLTF2 { * @param prettyPrint Indicates whether the json file should be pretty printed (true) or not (false) * @returns json data as string */ - private generateJSON(shouldUseGlb, glTFPrefix?, prettyPrint?); + private generateJSON; /** * Generates data for .gltf and .bin files based on the glTF prefix string * @param glTFPrefix Text to use when prefixing a glTF file @@ -41769,13 +41806,13 @@ declare module BABYLON.GLTF2 { * Creates a binary buffer for glTF * @returns array buffer for binary data */ - private _generateBinaryAsync(); + private _generateBinaryAsync; /** * Pads the number to a multiple of 4 * @param num number to pad * @returns padded number */ - private _getPadding(num); + private _getPadding; /** * Generates a glb file from the json and binary data * Returns an object with the glb file name as the key and data as the value @@ -41788,47 +41825,47 @@ declare module BABYLON.GLTF2 { * @param node glTF Node for storing the transformation data * @param babylonTransformNode Babylon mesh used as the source for the transformation data */ - private setNodeTransformation(node, babylonTransformNode); - private getVertexBufferFromMesh(attributeKind, bufferMesh); + private setNodeTransformation; + private getVertexBufferFromMesh; /** * Creates a bufferview based on the vertices type for the Babylon mesh * @param kind Indicates the type of vertices data * @param babylonTransformNode The Babylon mesh to get the vertices data from * @param binaryWriter The buffer to write the bufferview data to */ - private createBufferViewKind(kind, babylonTransformNode, binaryWriter, byteStride); + private createBufferViewKind; /** * The primitive mode of the Babylon mesh * @param babylonMesh The BabylonJS mesh */ - private getMeshPrimitiveMode(babylonMesh); + private getMeshPrimitiveMode; /** * Sets the primitive mode of the glTF mesh primitive * @param meshPrimitive glTF mesh primitive * @param primitiveMode The primitive mode */ - private setPrimitiveMode(meshPrimitive, primitiveMode); + private setPrimitiveMode; /** * Sets the vertex attribute accessor based of the glTF mesh primitive * @param meshPrimitive glTF mesh primitive * @param attributeKind vertex attribute * @returns boolean specifying if uv coordinates are present */ - private setAttributeKind(meshPrimitive, attributeKind); + private setAttributeKind; /** * Sets data for the primitive attributes of each submesh * @param mesh glTF Mesh object to store the primitive attribute information * @param babylonTransformNode Babylon mesh to get the primitive attribute data from * @param binaryWriter Buffer to write the attribute data to */ - private setPrimitiveAttributes(mesh, babylonTransformNode, binaryWriter); + private setPrimitiveAttributes; /** * Creates a glTF scene based on the array of meshes * Returns the the total byte offset * @param babylonScene Babylon scene to get the mesh data from * @param binaryWriter Buffer to write binary data to */ - private createSceneAsync(babylonScene, binaryWriter); + private createSceneAsync; /** * Creates a mapping of Node unique id to node index and handles animations * @param babylonScene Babylon Scene @@ -41837,14 +41874,14 @@ declare module BABYLON.GLTF2 { * @param binaryWriter Buffer to write binary data to * @returns Node mapping of unique id to index */ - private createNodeMapAndAnimations(babylonScene, nodes, shouldExportTransformNode, binaryWriter); + private createNodeMapAndAnimations; /** * Creates a glTF node from a Babylon mesh * @param babylonMesh Source Babylon mesh * @param binaryWriter Buffer for storing geometry data * @returns glTF node */ - private createNode(babylonTransformNode, binaryWriter); + private createNode; } /** * @hidden @@ -41873,7 +41910,7 @@ declare module BABYLON.GLTF2 { * Resize the array buffer to the specified byte length * @param byteLength */ - private resizeBuffer(byteLength); + private resizeBuffer; /** * Get an array buffer with the length of the byte offset * @returns ArrayBuffer resized to the byte offset @@ -41971,7 +42008,7 @@ declare module BABYLON.GLTF2 { * @param color2 second color to compare to * @param epsilon threshold value */ - private static FuzzyEquals(color1, color2, epsilon); + private static FuzzyEquals; /** * Gets the materials from a Babylon scene and converts them to glTF materials * @param scene babylonjs scene @@ -42045,7 +42082,7 @@ private static _SolveMetallic(diffuse: number, specular: number, oneMinusSpecula * @param mimeType mimetype of the image * @returns base64 image string */ - private _createBase64FromCanvasAsync(buffer, width, height, mimeType); + private _createBase64FromCanvasAsync; /** * Generates a white texture based on the specified width and height * @param width width of the texture in pixels @@ -42053,7 +42090,7 @@ private static _SolveMetallic(diffuse: number, specular: number, oneMinusSpecula * @param scene babylonjs scene * @returns white texture */ - private _createWhiteTexture(width, height, scene); + private _createWhiteTexture; /** * Resizes the two source textures to the same dimensions. If a texture is null, a default white texture is generated. If both textures are null, returns null * @param texture1 first texture to resize @@ -42061,14 +42098,14 @@ private static _SolveMetallic(diffuse: number, specular: number, oneMinusSpecula * @param scene babylonjs scene * @returns resized textures or null */ - private _resizeTexturesToSameDimensions(texture1, texture2, scene); + private _resizeTexturesToSameDimensions; /** * Converts an array of pixels to a Float32Array * Throws an error if the pixel format is not supported * @param pixels - array buffer containing pixel values * @returns Float32 of pixels */ - private _convertPixelArrayToFloat32(pixels); + private _convertPixelArrayToFloat32; /** * Convert Specular Glossiness Textures to Metallic Roughness * See link below for info on the material conversions from PBR Metallic/Roughness and Specular/Glossiness @@ -42079,25 +42116,25 @@ private static _SolveMetallic(diffuse: number, specular: number, oneMinusSpecula * @param mimeType the mime type to use for the texture * @returns pbr metallic roughness interface or null */ - private _convertSpecularGlossinessTexturesToMetallicRoughnessAsync(diffuseTexture, specularGlossinessTexture, factors, mimeType); + private _convertSpecularGlossinessTexturesToMetallicRoughnessAsync; /** * Converts specular glossiness material properties to metallic roughness * @param specularGlossiness interface with specular glossiness material properties * @returns interface with metallic roughness material properties */ - private _convertSpecularGlossinessToMetallicRoughness(specularGlossiness); + private _convertSpecularGlossinessToMetallicRoughness; /** * Calculates the surface reflectance, independent of lighting conditions * @param color Color source to calculate brightness from * @returns number representing the perceived brightness, or zero if color is undefined */ - private _getPerceivedBrightness(color); + private _getPerceivedBrightness; /** * Returns the maximum color component value * @param color * @returns maximum color component value, or zero if color is null or undefined */ - private _getMaxComponent(color); + private _getMaxComponent; /** * Convert a PBRMaterial (Metallic/Roughness) to Metallic Roughness factors * @param babylonPBRMaterial BJS PBR Metallic Roughness Material @@ -42109,10 +42146,10 @@ private static _SolveMetallic(diffuse: number, specular: number, oneMinusSpecula * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied * @returns glTF PBR Metallic Roughness factors */ - private _convertMetalRoughFactorsToMetallicRoughnessAsync(babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords); - private _getGLTFTextureSampler(texture); - private _getGLTFTextureWrapMode(wrapMode); - private _getGLTFTextureWrapModesSampler(texture); + private _convertMetalRoughFactorsToMetallicRoughnessAsync; + private _getGLTFTextureSampler; + private _getGLTFTextureWrapMode; + private _getGLTFTextureWrapModesSampler; /** * Convert a PBRMaterial (Specular/Glossiness) to Metallic Roughness factors * @param babylonPBRMaterial BJS PBR Metallic Roughness Material @@ -42124,7 +42161,7 @@ private static _SolveMetallic(diffuse: number, specular: number, oneMinusSpecula * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied * @returns glTF PBR Metallic Roughness factors */ - private _convertSpecGlossFactorsToMetallicRoughnessAsync(babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords); + private _convertSpecGlossFactorsToMetallicRoughnessAsync; /** * Converts a Babylon PBR Metallic Roughness Material to a glTF Material * @param babylonPBRMaterial BJS PBR Metallic Roughness Material @@ -42136,8 +42173,8 @@ private static _SolveMetallic(diffuse: number, specular: number, oneMinusSpecula * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied */ - private setMetallicRoughnessPbrMaterial(metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, hasTextureCoords); - private getPixelsFromTexture(babylonTexture); + private setMetallicRoughnessPbrMaterial; + private getPixelsFromTexture; /** * Extracts a texture from a Babylon texture into file data and glTF data * @param babylonTexture Babylon texture to extract @@ -42147,7 +42184,7 @@ private static _SolveMetallic(diffuse: number, specular: number, oneMinusSpecula * @param imageData map of image file name and data * @return glTF texture info, or null if the texture format is not supported */ - private _exportTextureAsync(babylonTexture, mimeType); + private _exportTextureAsync; /** * Builds a texture from base64 string * @param base64Texture base64 texture string @@ -42158,7 +42195,7 @@ private static _SolveMetallic(diffuse: number, specular: number, oneMinusSpecula * @param imageData map of image data * @returns glTF texture info, or null if the texture format is not supported */ - private _getTextureInfoFromBase64(base64Texture, baseTextureName, mimeType, texCoordIndex, samplerIndex); + private _getTextureInfoFromBase64; } } @@ -42224,7 +42261,7 @@ declare module BABYLON.GLTF2 { * @returns nullable IAnimationData */ private static _CreateNodeAnimation(babylonTransformNode: TransformNode, animation: Animation, animationChannelTargetPath: AnimationChannelTargetPath, convertToRightHandedSystem: boolean, useQuaternion: boolean, animationSampleRate: number): Nullable<_IAnimationData>; - private static _DeduceAnimationInfo(animation); + private static _DeduceAnimationInfo; /** * @ignore * Create node animations from the transform node animations @@ -42256,7 +42293,7 @@ private static _CreateNodeAnimationFromTransformNodeAnimations(babylonTransformN private static _CreateNodeAnimationFromAnimationGroups(babylonScene: Scene, glTFAnimations: IAnimation[], nodeMap: { [key: number]: number; }, nodes: INode[], binaryWriter: _BinaryWriter, bufferViews: IBufferView[], accessors: IAccessor[], convertToRightHandedSystem: boolean, animationSampleRate: number): void; - private static AddAnimation(name, glTFAnimation, babylonTransformNode, animation, dataAccessorType, animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, useQuaternion, animationSampleRate); + private static AddAnimation; /** * Create a baked animation * @param babylonTransformNode BabylonJS mesh @@ -42270,9 +42307,9 @@ private static _CreateNodeAnimationFromAnimationGroups(babylonScene: Scene, glTF * @param convertToRightHandedSystem converts the values to right-handed * @param useQuaternion specifies if quaternions should be used */ - private static _CreateBakedAnimation(babylonTransformNode, animation, animationChannelTargetPath, minFrame, maxFrame, fps, sampleRate, inputs, outputs, minMaxFrames, convertToRightHandedSystem, useQuaternion); - private static _ConvertFactorToVector3OrQuaternion(factor, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion); - private static _SetInterpolatedValue(babylonTransformNode, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion); + private static _CreateBakedAnimation; + private static _ConvertFactorToVector3OrQuaternion; + private static _SetInterpolatedValue; /** * Creates linear animation from the animation key frames * @param babylonTransformNode BabylonJS mesh @@ -42284,7 +42321,7 @@ private static _CreateNodeAnimationFromAnimationGroups(babylonScene: Scene, glTF * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed * @param useQuaternion Specifies if quaternions are used in the animation */ - private static _CreateLinearOrStepAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion); + private static _CreateLinearOrStepAnimation; /** * Creates cubic spline animation from the animation key frames * @param babylonTransformNode BabylonJS mesh @@ -42296,8 +42333,8 @@ private static _CreateNodeAnimationFromAnimationGroups(babylonScene: Scene, glTF * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed * @param useQuaternion Specifies if quaternions are used in the animation */ - private static _CreateCubicSplineAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion); - private static _GetBasePositionRotationOrScale(babylonTransformNode, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion); + private static _CreateCubicSplineAnimation; + private static _GetBasePositionRotationOrScale; /** * Adds a key frame value * @param keyFrame @@ -42308,14 +42345,14 @@ private static _CreateNodeAnimationFromAnimationGroups(babylonScene: Scene, glTF * @param convertToRightHandedSystem * @param useQuaternion */ - private static _AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion); + private static _AddKeyframeValue; /** * Determine the interpolation based on the key frames * @param keyFrames * @param animationChannelTargetPath * @param useQuaternion */ - private static _DeduceInterpolation(keyFrames, animationChannelTargetPath, useQuaternion); + private static _DeduceInterpolation; /** * Adds an input tangent or output tangent to the output data * If an input tangent or output tangent is missing, it uses the zero vector or zero quaternion @@ -42328,13 +42365,13 @@ private static _CreateNodeAnimationFromAnimationGroups(babylonScene: Scene, glTF * @param useQuaternion Specifies if quaternions are used * @param convertToRightHandedSystem Specifies if the values should be converted to right-handed */ - private static AddSplineTangent(babylonTransformNode, tangentType, outputs, animationChannelTargetPath, interpolation, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem); + private static AddSplineTangent; /** * Get the minimum and maximum key frames' frame values * @param keyFrames animation key frames * @returns the minimum and maximum key frame value */ - private static calculateMinMaxKeyFrames(keyFrames); + private static calculateMinMaxKeyFrames; } } diff --git a/dist/preview release/babylon.d.ts b/dist/preview release/babylon.d.ts index 43d5bffc019..5d17ac5084a 100644 --- a/dist/preview release/babylon.d.ts +++ b/dist/preview release/babylon.d.ts @@ -158,7 +158,7 @@ declare module BABYLON { * Removes all the assets in the container from the scene */ removeAllFromScene(): void; - private _moveAssets(sourceAssets, targetAssets, keepAssets); + private _moveAssets; /** * Removes all the assets contained in the scene and adds them to the container. * @param keepAssets Set of assets to keep in the scene. (default: empty) @@ -696,10 +696,10 @@ declare module BABYLON { * this is easier to reference from here than from all the materials. */ /** - * Texture used in all pbr material as the reflection texture. - * As in the majority of the scene they are the same (exception for multi room and so on), - * this is easier to set here than in all the materials. - */ + * Texture used in all pbr material as the reflection texture. + * As in the majority of the scene they are the same (exception for multi room and so on), + * this is easier to set here than in all the materials. + */ environmentTexture: BaseTexture; /** @hidden */ protected _imageProcessingConfiguration: ImageProcessingConfiguration; @@ -1312,8 +1312,8 @@ declare module BABYLON { * Gets the current geometry buffer associated to the scene. */ /** - * Sets the current geometry buffer for the scene. - */ + * Sets the current geometry buffer for the scene. + */ geometryBufferRenderer: Nullable; private _pickedDownMesh; private _pickedUpMesh; @@ -1335,7 +1335,7 @@ declare module BABYLON { /** * Registers the transient components if needed. */ - private _registerTransientComponents(); + private _registerTransientComponents; /** * Add a component to the scene. * Note that the ccomponent could be registered on th next frame if this is called after @@ -1400,9 +1400,9 @@ declare module BABYLON { */ readonly debugLayer: DebugLayer; /** - * Gets a boolean indicating if collisions are processed on a web worker - * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21 - */ + * Gets a boolean indicating if collisions are processed on a web worker + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21 + */ workerCollisions: boolean; /** * Gets the octree used to boost mesh selection (picking) @@ -1537,11 +1537,11 @@ declare module BABYLON { getRenderId(): number; /** Call this function if you want to manually increment the render Id*/ incrementRenderId(): void; - private _updatePointerPosition(evt); - private _createUbo(); - private _createAlternateUbo(); - private _pickSpriteButKeepRay(originalPointerInfo, x, y, predicate?, fastCheck?, camera?); - private _setRayOnPointerInfo(pointerInfo); + private _updatePointerPosition; + private _createUbo; + private _createAlternateUbo; + private _pickSpriteButKeepRay; + private _setRayOnPointerInfo; /** * Use this method to simulate a pointer move on a mesh * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay @@ -1550,8 +1550,8 @@ declare module BABYLON { * @returns the current scene */ simulatePointerMove(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene; - private _processPointerMove(pickResult, evt); - private _checkPrePointerObservable(pickResult, evt, type); + private _processPointerMove; + private _checkPrePointerObservable; /** * Use this method to simulate a pointer down on a mesh * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay @@ -1560,7 +1560,7 @@ declare module BABYLON { * @returns the current scene */ simulatePointerDown(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene; - private _processPointerDown(pickResult, evt); + private _processPointerDown; /** * Use this method to simulate a pointer up on a mesh * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay @@ -1569,7 +1569,7 @@ declare module BABYLON { * @returns the current scene */ simulatePointerUp(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene; - private _processPointerUp(pickResult, evt, clickInfo); + private _processPointerUp; /** * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down) * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default) @@ -1613,7 +1613,7 @@ declare module BABYLON { * @param func defines the function to unregister */ unregisterAfterRender(func: () => void): void; - private _executeOnceBeforeRender(func); + private _executeOnceBeforeRender; /** * The provided function will run before render once and will be disposed afterwards. * A timeout delay can be provided so that the function will be executed in N ms. @@ -1727,12 +1727,12 @@ declare module BABYLON { * Stops and removes all animations that have been applied to the scene */ stopAllAnimations(): void; - private _animate(); + private _animate; /** @hidden */ _registerTargetForLateAnimationBinding(runtimeAnimation: RuntimeAnimation, originalValue: any): void; - private _processLateAnimationBindingsForMatrices(holder); - private _processLateAnimationBindingsForQuaternions(holder); - private _processLateAnimationBindings(); + private _processLateAnimationBindingsForMatrices; + private _processLateAnimationBindingsForQuaternions; + private _processLateAnimationBindings; /** @hidden */ _switchToAlternateCameraConfiguration(active: boolean): void; /** @@ -2170,7 +2170,7 @@ declare module BABYLON { * @return true if the data was successfully removed, false if it doesn't exist */ removeExternalData(key: string): boolean; - private _evaluateSubMesh(subMesh, mesh); + private _evaluateSubMesh; /** * Clear the processed materials smart array preventing retention point in material dispose. */ @@ -2207,8 +2207,8 @@ declare module BABYLON { * @returns the current scene */ unfreezeActiveMeshes(): Scene; - private _evaluateActiveMeshes(); - private _activeMesh(sourceMesh, mesh); + private _evaluateActiveMeshes; + private _activeMesh; /** * Update the transform matrix to update from the current active camera * @param force defines a boolean used to force the update even if cache is up to date @@ -2221,29 +2221,29 @@ declare module BABYLON { updateAlternateTransformMatrix(alternateCamera: Camera): void; /** @hidden */ _allowPostProcessClear: boolean; - private _renderForCamera(camera, rigParent?); - private _processSubCameras(camera); - private _checkIntersections(); + private _renderForCamera; + private _processSubCameras; + private _checkIntersections; /** * Render the scene * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default) */ render(updateCameras?: boolean): void; - private _updateAudioParameters(); + private _updateAudioParameters; /** * Gets or sets if audio support is enabled * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music */ audioEnabled: boolean; - private _disableAudio(); - private _enableAudio(); + private _disableAudio; + private _enableAudio; /** * Gets or sets if audio will be output to headphones * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music */ headphone: boolean; - private _switchAudioModeForHeadphones(); - private _switchAudioModeForNormalSpeakers(); + private _switchAudioModeForHeadphones; + private _switchAudioModeForNormalSpeakers; /** * Creates a depth renderer a given camera which contains a depth map which can be used for post processing. * @param camera The camera to create the depth renderer on (default: scene's active camera) @@ -2353,9 +2353,9 @@ declare module BABYLON { * @returns the current scene */ createPickingRayInCameraSpaceToRef(x: number, y: number, result: Ray, camera?: Camera): Scene; - private _internalPick(rayFunction, predicate?, fastCheck?); - private _internalMultiPick(rayFunction, predicate?); - private _internalPickSprites(ray, predicate?, fastCheck?, camera?); + private _internalPick; + private _internalMultiPick; + private _internalPickSprites; private _tempPickingRay; /** Launch a ray to try to pick a mesh in the scene * @param x position on screen @@ -2496,7 +2496,7 @@ declare module BABYLON { * @returns a new VREXperienceHelper */ createDefaultVRExperience(webVROptions?: VRExperienceHelperOptions): VRExperienceHelper; - private _getByTags(list, tagsQuery, forEach?); + private _getByTags; /** * Get a list of meshes by tags * @param tagsQuery defines the tags query to use @@ -2743,8 +2743,8 @@ declare module BABYLON { * @param condition an optional determinant of action */ constructor( - /** the trigger, with or without parameters, for the action */ - triggerOptions: any, condition?: Condition); + /** the trigger, with or without parameters, for the action */ + triggerOptions: any, condition?: Condition); /** * Internal only * @hidden @@ -2828,9 +2828,9 @@ declare module BABYLON { /** The mesh that is currently pointed at (can be null) */ meshUnderPointer: Nullable; /** the original (browser) event that triggered the ActionEvent */ - sourceEvent: any; + sourceEvent?: any; /** additional data for the event */ - additionalData: any; + additionalData?: any; /** * Creates a new ActionEvent * @param source The mesh or sprite that triggered the action @@ -2841,18 +2841,18 @@ declare module BABYLON { * @param additionalData additional data for the event */ constructor( - /** The mesh or sprite that triggered the action */ - source: any, - /** The X mouse cursor position at the time of the event */ - pointerX: number, - /** The Y mouse cursor position at the time of the event */ - pointerY: number, - /** The mesh that is currently pointed at (can be null) */ - meshUnderPointer: Nullable, - /** the original (browser) event that triggered the ActionEvent */ - sourceEvent?: any, - /** additional data for the event */ - additionalData?: any); + /** The mesh or sprite that triggered the action */ + source: any, + /** The X mouse cursor position at the time of the event */ + pointerX: number, + /** The Y mouse cursor position at the time of the event */ + pointerY: number, + /** The mesh that is currently pointed at (can be null) */ + meshUnderPointer: Nullable, + /** the original (browser) event that triggered the ActionEvent */ + sourceEvent?: any, + /** additional data for the event */ + additionalData?: any); /** * Helper function to auto-create an ActionEvent from a source mesh. * @param source The source mesh that triggered the event @@ -3224,12 +3224,12 @@ declare module BABYLON { * @param operator the conditional operator, default ValueCondition.IsEqual */ constructor(actionManager: ActionManager, target: any, - /** path to specify the property of the target the conditional operator uses */ - propertyPath: string, - /** the value compared by the conditional operator against the current value of the property */ - value: any, - /** the conditional operator, default ValueCondition.IsEqual */ - operator?: number); + /** path to specify the property of the target the conditional operator uses */ + propertyPath: string, + /** the value compared by the conditional operator against the current value of the property */ + value: any, + /** the conditional operator, default ValueCondition.IsEqual */ + operator?: number); /** * Compares the given value with the property value for the specified conditional operator * @returns the result of the comparison @@ -3264,8 +3264,8 @@ declare module BABYLON { * @param predicate defines the predicate function used to validate the condition */ constructor(actionManager: ActionManager, - /** defines the predicate function used to validate the condition */ - predicate: () => boolean); + /** defines the predicate function used to validate the condition */ + predicate: () => boolean); /** * @returns the validity of the predicate condition */ @@ -3348,7 +3348,7 @@ declare module BABYLON { class PlayAnimationAction extends Action { from: number; to: number; - loop: boolean | undefined; + loop?: boolean | undefined; private _target; constructor(triggerOptions: any, target: any, from: number, to: number, loop?: boolean | undefined, condition?: Condition); _prepare(): void; @@ -3408,8 +3408,8 @@ declare module BABYLON { propertyPath: string; value: any; duration: number; - stopOtherAnimations: boolean | undefined; - onInterpolationDone: (() => void) | undefined; + stopOtherAnimations?: boolean | undefined; + onInterpolationDone?: (() => void) | undefined; private _target; private _effectiveTarget; private _property; @@ -3435,7 +3435,7 @@ declare module BABYLON { /** defines if the animation must loop (default is false) */ loopAnimation: boolean; /** defines a callback to call when animation ends if it is not looping */ - onAnimationEnd: (() => void) | null | undefined; + onAnimationEnd?: (() => void) | null | undefined; private _localDelayOffset; private _pausedDelay; private _runtimeAnimations; @@ -3486,16 +3486,16 @@ declare module BABYLON { * @param animations defines a group of animation to add to the new Animatable */ constructor(scene: Scene, - /** defines the target object */ - target: any, - /** defines the starting frame number (default is 0) */ - fromFrame?: number, - /** defines the ending frame number (default is 100) */ - toFrame?: number, - /** defines if the animation must loop (default is false) */ - loopAnimation?: boolean, speedRatio?: number, - /** defines a callback to call when animation ends if it is not looping */ - onAnimationEnd?: (() => void) | null | undefined, animations?: Animation[]); + /** defines the target object */ + target: any, + /** defines the starting frame number (default is 0) */ + fromFrame?: number, + /** defines the ending frame number (default is 100) */ + toFrame?: number, + /** defines if the animation must loop (default is false) */ + loopAnimation?: boolean, speedRatio?: number, + /** defines a callback to call when animation ends if it is not looping */ + onAnimationEnd?: (() => void) | null | undefined, animations?: Animation[]); /** * Synchronize and normalize current Animatable with a source Animatable * This is useful when using animation weights and when animations are not of the same length @@ -3554,7 +3554,7 @@ declare module BABYLON { * Restart the animation */ restart(): void; - private _raiseOnAnimationEnd(); + private _raiseOnAnimationEnd; /** * Stop and delete the current animation * @param animationName defines a string used to only stop some of the runtime animations instead of all @@ -3589,12 +3589,12 @@ declare module BABYLON { * @param to The ending frame of the animation */ constructor( - /**The name of the animation range**/ - name: string, - /**The starting frame of the animation */ - from: number, - /**The ending frame of the animation*/ - to: number); + /**The name of the animation range**/ + name: string, + /**The starting frame of the animation */ + from: number, + /**The ending frame of the animation*/ + to: number); /** * Makes a copy of the animation range * @returns A copy of the animation range @@ -3610,7 +3610,7 @@ declare module BABYLON { /** The event to perform when triggered **/ action: () => void; /** Specifies if the event should be triggered only once**/ - onlyOnce: boolean | undefined; + onlyOnce?: boolean | undefined; /** * Specifies if the animation event is done */ @@ -3622,12 +3622,12 @@ declare module BABYLON { * @param onlyOnce Specifies if the event should be triggered only once */ constructor( - /** The frame for which the event is triggered **/ - frame: number, - /** The event to perform when triggered **/ - action: () => void, - /** Specifies if the event should be triggered only once**/ - onlyOnce?: boolean | undefined); + /** The frame for which the event is triggered **/ + frame: number, + /** The event to perform when triggered **/ + action: () => void, + /** Specifies if the event should be triggered only once**/ + onlyOnce?: boolean | undefined); /** @hidden */ _clone(): AnimationEvent; } @@ -3681,12 +3681,12 @@ declare module BABYLON { * Ensures that the value is limited between zero and one * @returns This path cursor */ - private ensureLimits(); + private ensureLimits; /** * Runs onchange callbacks on change (used by the animation engine) * @returns This path cursor */ - private raiseOnChange(); + private raiseOnChange; /** * Executes a function on change * @param f A path cursor onchange callback @@ -3726,7 +3726,7 @@ declare module BABYLON { /** * Do not interpolate between keys and use the start key value only. Tangents are ignored */ - STEP = 1, + STEP = 1 } /** * Class used to store any kind of animation @@ -3741,9 +3741,9 @@ declare module BABYLON { /**The data type of the animation */ dataType: number; /**The loop mode of the animation */ - loopMode: number | undefined; + loopMode?: number | undefined; /**Specifies if blending should be enabled */ - enableBlending: boolean | undefined; + enableBlending?: boolean | undefined; /** * Use matrix interpolation instead of using direct key value when animating matrices */ @@ -3871,18 +3871,18 @@ declare module BABYLON { * @param enableBlendings Specifies if blending should be enabled */ constructor( - /**Name of the animation */ - name: string, - /**Property to animate */ - targetProperty: string, - /**The frames per second of the animation */ - framePerSecond: number, - /**The data type of the animation */ - dataType: number, - /**The loop mode of the animation */ - loopMode?: number | undefined, - /**Specifies if blending should be enabled */ - enableBlending?: boolean | undefined); + /**Name of the animation */ + name: string, + /**Property to animate */ + targetProperty: string, + /**The frames per second of the animation */ + framePerSecond: number, + /**The data type of the animation */ + dataType: number, + /**The loop mode of the animation */ + loopMode?: number | undefined, + /**Specifies if blending should be enabled */ + enableBlending?: boolean | undefined); /** * Converts the animation to a string * @param fullDetails support for multiple levels of logging within scene loading @@ -4201,8 +4201,8 @@ declare module BABYLON { * Gets or sets the speed ratio to use for all animations */ /** - * Gets or sets the speed ratio to use for all animations - */ + * Gets or sets the speed ratio to use for all animations + */ speedRatio: number; /** * Gets the targeted animations for this animation group @@ -4282,7 +4282,7 @@ declare module BABYLON { * Dispose all associated resources */ dispose(): void; - private _checkAnimationGroupEnded(animatable); + private _checkAnimationGroupEnded; } } @@ -4513,19 +4513,19 @@ declare module BABYLON { * @param highLimitValue The high limit value * @returns The interpolated value */ - private _interpolate(currentFrame, repeatCount, loopMode?, offsetValue?, highLimitValue?); + private _interpolate; /** * Apply the interpolated value to the target * @param currentValue defines the value computed by the animation * @param weight defines the weight to apply to this value (Defaults to 1.0) */ setValue(currentValue: any, weight?: number): void; - private _setValue(target, currentValue, weight, targetIndex?); + private _setValue; /** * Gets the loop pmode of the runtime animation * @returns Loop Mode */ - private _getCorrectLoopMode(); + private _getCorrectLoopMode; /** * Move the current animation to a given frame * @param frame defines the frame to move to @@ -4659,8 +4659,8 @@ declare module BABYLON { isOGGsupported: boolean; readonly audioContext: Nullable; constructor(); - private _unlockiOSaudio(); - private _initializeAudioContext(); + private _unlockiOSaudio; + private _initializeAudioContext; dispose(): void; getGlobalVolume(): number; setGlobalVolume(newVolume: number): void; @@ -4721,14 +4721,14 @@ declare module BABYLON { constructor(name: string, urlOrArrayBuffer: any, scene: Scene, readyToPlayCallback?: Nullable<() => void>, options?: any); dispose(): void; isReady(): boolean; - private _soundLoaded(audioData); + private _soundLoaded; setAudioBuffer(audioBuffer: AudioBuffer): void; updateOptions(options: any): void; - private _createSpatialParameters(); - private _updateSpatialParameters(); + private _createSpatialParameters; + private _updateSpatialParameters; switchPanningModelToHRTF(): void; switchPanningModelToEqualPower(): void; - private _switchPanningModel(); + private _switchPanningModel; connectToSoundTrackAudioNode(soundTrackAudioNode: AudioNode): void; /** * Transform this sound into a directional source @@ -4739,7 +4739,7 @@ declare module BABYLON { setDirectionalCone(coneInnerAngle: number, coneOuterAngle: number, coneOuterGain: number): void; setPosition(newPosition: Vector3): void; setLocalDirectionToMesh(newLocalDirection: Vector3): void; - private _updateDirection(); + private _updateDirection; updateDistanceFromListener(): void; setAttenuationFunction(callback: (currentVolume: number, currentDistance: number, maxDistance: number, refDistance: number, rolloffFactor: number) => number): void; /** @@ -4748,7 +4748,7 @@ declare module BABYLON { * @param offset (optional) Start the sound setting it at a specific time */ play(time?: number, offset?: number): void; - private _onended(); + private _onended; /** * Stop the sound * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default. @@ -4760,7 +4760,7 @@ declare module BABYLON { getVolume(): number; attachToMesh(meshToConnectTo: AbstractMesh): void; detachFromMesh(): void; - private _onRegisterAfterWorldMatrixUpdate(node); + private _onRegisterAfterWorldMatrixUpdate; clone(): Nullable; getAudioBuffer(): AudioBuffer | null; serialize(): any; @@ -4779,7 +4779,7 @@ declare module BABYLON { private _options; private _isInitialized; constructor(scene: Scene, options?: any); - private _initializeSoundTrackAudioGraph(); + private _initializeSoundTrackAudioGraph; dispose(): void; AddSound(sound: Sound): void; RemoveSound(sound: Sound): void; @@ -4790,52 +4790,6 @@ declare module BABYLON { } } -declare module BABYLON { - /** - * Interface used to define a behavior - */ - interface Behavior { - /** gets or sets behavior's name */ - name: string; - /** - * Function called when the behavior needs to be initialized (after attaching it to a target) - */ - init(): void; - /** - * Called when the behavior is attached to a target - * @param target defines the target where the behavior is attached to - */ - attach(target: T): void; - /** - * Called when the behavior is detached from its target - */ - detach(): void; - } - /** - * Interface implemented by classes supporting behaviors - */ - interface IBehaviorAware { - /** - * Attach a behavior - * @param behavior defines the behavior to attach - * @returns the current host - */ - addBehavior(behavior: Behavior): T; - /** - * Remove a behavior from the current object - * @param behavior defines the behavior to detach - * @returns the current host - */ - removeBehavior(behavior: Behavior): T; - /** - * Gets a behavior using its name to search - * @param name defines the name to search - * @returns the behavior or null if not found - */ - getBehaviorByName(name: string): Nullable>; - } -} - declare module BABYLON { /** * Class used to store bone information @@ -4893,10 +4847,10 @@ declare module BABYLON { * @param index defines index of the bone in the hiearchy */ constructor( - /** - * defines the bone name - */ - name: string, skeleton: Skeleton, parentBone?: Nullable, localMatrix?: Nullable, restPose?: Nullable, baseMatrix?: Nullable, index?: Nullable); + /** + * defines the bone name + */ + name: string, skeleton: Skeleton, parentBone?: Nullable, localMatrix?: Nullable, restPose?: Nullable, baseMatrix?: Nullable, index?: Nullable); /** * Gets the parent skeleton * @returns a skeleton @@ -4959,8 +4913,8 @@ declare module BABYLON { * Gets the animation properties override */ readonly animationPropertiesOverride: Nullable; - private _decompose(); - private _compose(); + private _decompose; + private _compose; /** * Update the base and local matrices * @param matrix defines the new base or local matrix @@ -4974,8 +4928,8 @@ declare module BABYLON { * Flag the bone as dirty (Forcing it to update everything) */ markAsDirty(): void; - private _markAsDirtyAndCompose(); - private _markAsDirtyAndDecompose(); + private _markAsDirtyAndCompose; + private _markAsDirtyAndDecompose; /** * Copy an animation range from another bone * @param source defines the source bone @@ -5075,8 +5029,8 @@ declare module BABYLON { * @param mesh The mesh that this bone is attached to. This is only used in world space */ setRotationMatrix(rotMat: Matrix, space?: Space, mesh?: AbstractMesh): void; - private _rotateWithMatrix(rmat, space?, mesh?); - private _getNegativeRotationToRef(rotMatInv, mesh?); + private _rotateWithMatrix; + private _getNegativeRotationToRef; /** * Get the position of the bone in local or world space * @param space The space that the returned position is in @@ -5270,7 +5224,7 @@ declare module BABYLON { maxAngle?: number; slerpAmount?: number; }); - private _setMaxAngle(ang); + private _setMaxAngle; /** * Force the controller to update the bones */ @@ -5394,9 +5348,9 @@ declare module BABYLON { * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()) */ update(): void; - private _getAngleDiff(ang1, ang2); - private _getAngleBetween(ang1, ang2); - private _isAngleBetween(ang, ang1, ang2); + private _getAngleDiff; + private _getAngleBetween; + private _isAngleBetween; } } @@ -5455,10 +5409,10 @@ declare module BABYLON { * @param scene defines the hosting scene */ constructor( - /** defines the skeleton name */ - name: string, - /** defines the skeleton Id */ - id: string, scene: Scene); + /** defines the skeleton name */ + name: string, + /** defines the skeleton Id */ + id: string, scene: Scene); /** * Gets the list of transform matrices to send to shaders (one matrix per bone) * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true) @@ -5519,7 +5473,7 @@ declare module BABYLON { * Forces the skeleton to go to rest pose */ returnToRest(): void; - private _getHighestAnimationFrame(); + private _getHighestAnimationFrame; /** * Begin a specific animation range * @param name defines the name of the range to start @@ -5589,7 +5543,7 @@ declare module BABYLON { * Sorts bones per internal index */ sortBones(): void; - private _sortBones(index, bones, visited); + private _sortBones; } } @@ -5731,7 +5685,7 @@ declare module BABYLON { intersectsPlane(plane: Plane): Nullable; intersectsMesh(mesh: AbstractMesh, fastCheck?: boolean): PickingInfo; intersectsMeshes(meshes: Array, fastCheck?: boolean, results?: Array): Array; - private _comparePickingInfo(pickingInfoA, pickingInfoB); + private _comparePickingInfo; private static smallnum; private static rayl; /** @@ -5759,1065 +5713,689 @@ declare module BABYLON { } declare module BABYLON { - class ArcRotateCamera extends TargetCamera { - alpha: number; - beta: number; - radius: number; - protected _target: Vector3; - protected _targetHost: Nullable; - target: Vector3; - inertialAlphaOffset: number; - inertialBetaOffset: number; - inertialRadiusOffset: number; - lowerAlphaLimit: Nullable; - upperAlphaLimit: Nullable; - lowerBetaLimit: number; - upperBetaLimit: number; - lowerRadiusLimit: Nullable; - upperRadiusLimit: Nullable; - inertialPanningX: number; - inertialPanningY: number; - pinchToPanMaxDistance: number; - panningDistanceLimit: Nullable; - panningOriginTarget: Vector3; - panningInertia: number; - angularSensibilityX: number; - angularSensibilityY: number; - pinchPrecision: number; - pinchDeltaPercentage: number; - panningSensibility: number; - keysUp: number[]; - keysDown: number[]; - keysLeft: number[]; - keysRight: number[]; - wheelPrecision: number; - wheelDeltaPercentage: number; - zoomOnFactor: number; - targetScreenOffset: Vector2; - allowUpsideDown: boolean; - _viewMatrix: Matrix; - _useCtrlForPanning: boolean; - _panningMouseButton: number; - inputs: ArcRotateCameraInputsManager; - _reset: () => void; - panningAxis: Vector3; - protected _localDirection: Vector3; - protected _transformedDirection: Vector3; - private _bouncingBehavior; - readonly bouncingBehavior: Nullable; - useBouncingBehavior: boolean; - private _framingBehavior; - readonly framingBehavior: Nullable; - useFramingBehavior: boolean; - private _autoRotationBehavior; - readonly autoRotationBehavior: Nullable; - useAutoRotationBehavior: boolean; - onMeshTargetChangedObservable: Observable>; - onCollide: (collidedMesh: AbstractMesh) => void; - checkCollisions: boolean; - collisionRadius: Vector3; - protected _collider: Collider; - protected _previousPosition: Vector3; - protected _collisionVelocity: Vector3; - protected _newPosition: Vector3; - protected _previousAlpha: number; - protected _previousBeta: number; - protected _previousRadius: number; - protected _collisionTriggered: boolean; - protected _targetBoundingCenter: Nullable; - private _computationVector; - constructor(name: string, alpha: number, beta: number, radius: number, target: Vector3, scene: Scene, setActiveOnSceneIfNoneActive?: boolean); - _initCache(): void; - _updateCache(ignoreParentClass?: boolean): void; - protected _getTargetPosition(): Vector3; - /** - * Store current camera state (fov, position, etc..) - */ - private _storedAlpha; - private _storedBeta; - private _storedRadius; - private _storedTarget; - storeState(): Camera; + /** + * Interface used to define a behavior + */ + interface Behavior { + /** gets or sets behavior's name */ + name: string; /** - * Restored camera state. You must call storeState() first + * Function called when the behavior needs to be initialized (after attaching it to a target) */ - _restoreStateValues(): boolean; - _isSynchronizedViewMatrix(): boolean; - attachControl(element: HTMLElement, noPreventDefault?: boolean, useCtrlForPanning?: boolean, panningMouseButton?: number): void; - detachControl(element: HTMLElement): void; - _checkInputs(): void; - protected _checkLimits(): void; - rebuildAnglesAndRadius(): void; - setPosition(position: Vector3): void; - setTarget(target: AbstractMesh | Vector3, toBoundingCenter?: boolean, allowSamePosition?: boolean): void; - _getViewMatrix(): Matrix; - protected _onCollisionPositionChange: (collisionId: number, newPosition: Vector3, collidedMesh?: Nullable) => void; - zoomOn(meshes?: AbstractMesh[], doNotUpdateMaxZ?: boolean): void; - focusOn(meshesOrMinMaxVectorAndDistance: AbstractMesh[] | { - min: Vector3; - max: Vector3; - distance: number; - }, doNotUpdateMaxZ?: boolean): void; + init(): void; /** - * @override - * Override Camera.createRigCamera + * Called when the behavior is attached to a target + * @param target defines the target where the behavior is attached to */ - createRigCamera(name: string, cameraIndex: number): Camera; + attach(target: T): void; /** - * @override - * Override Camera._updateRigCameras + * Called when the behavior is detached from its target */ - _updateRigCameras(): void; - dispose(): void; - getClassName(): string; - } -} - -declare module BABYLON { - class ArcRotateCameraInputsManager extends CameraInputsManager { - constructor(camera: ArcRotateCamera); - addMouseWheel(): ArcRotateCameraInputsManager; - addPointers(): ArcRotateCameraInputsManager; - addKeyboard(): ArcRotateCameraInputsManager; - addVRDeviceOrientation(): ArcRotateCameraInputsManager; + detach(): void; } -} - -declare module BABYLON { - class Camera extends Node { - inputs: CameraInputsManager; - private static _PERSPECTIVE_CAMERA; - private static _ORTHOGRAPHIC_CAMERA; - private static _FOVMODE_VERTICAL_FIXED; - private static _FOVMODE_HORIZONTAL_FIXED; - private static _RIG_MODE_NONE; - private static _RIG_MODE_STEREOSCOPIC_ANAGLYPH; - private static _RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL; - private static _RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; - private static _RIG_MODE_STEREOSCOPIC_OVERUNDER; - private static _RIG_MODE_VR; - private static _RIG_MODE_WEBVR; - static readonly PERSPECTIVE_CAMERA: number; - static readonly ORTHOGRAPHIC_CAMERA: number; - /** - * This is the default FOV mode for perspective cameras. - * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum. - * - */ - static readonly FOVMODE_VERTICAL_FIXED: number; - /** - * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum. - * - */ - static readonly FOVMODE_HORIZONTAL_FIXED: number; - static readonly RIG_MODE_NONE: number; - static readonly RIG_MODE_STEREOSCOPIC_ANAGLYPH: number; - static readonly RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: number; - static readonly RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: number; - static readonly RIG_MODE_STEREOSCOPIC_OVERUNDER: number; - static readonly RIG_MODE_VR: number; - static readonly RIG_MODE_WEBVR: number; - static ForceAttachControlToAlwaysPreventDefault: boolean; - static UseAlternateWebVRRendering: boolean; - position: Vector3; - /** - * The vector the camera should consider as up. - * (default is Vector3(0, 1, 0) aka Vector3.Up()) - */ - upVector: Vector3; - orthoLeft: Nullable; - orthoRight: Nullable; - orthoBottom: Nullable; - orthoTop: Nullable; - /** - * FOV is set in Radians. (default is 0.8) - */ - fov: number; - minZ: number; - maxZ: number; - inertia: number; - mode: number; - isIntermediate: boolean; - viewport: Viewport; - /** - * Restricts the camera to viewing objects with the same layerMask. - * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0 - */ - layerMask: number; - /** - * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED) - */ - fovMode: number; - cameraRigMode: number; - interaxialDistance: number; - isStereoscopicSideBySide: boolean; - _cameraRigParams: any; - _rigCameras: Camera[]; - _rigPostProcess: Nullable; - protected _webvrViewMatrix: Matrix; - _skipRendering: boolean; - _alternateCamera: Camera; - customRenderTargets: RenderTargetTexture[]; - onViewMatrixChangedObservable: Observable; - onProjectionMatrixChangedObservable: Observable; - onAfterCheckInputsObservable: Observable; - onRestoreStateObservable: Observable; - private _computedViewMatrix; - _projectionMatrix: Matrix; - private _doNotComputeProjectionMatrix; - private _worldMatrix; - _postProcesses: Nullable[]; - private _transformMatrix; - _activeMeshes: SmartArray; - protected _globalPosition: Vector3; - private _frustumPlanes; - private _refreshFrustumPlanes; - constructor(name: string, position: Vector3, scene: Scene, setActiveOnSceneIfNoneActive?: boolean); - private _storedFov; - private _stateStored; - /** - * Store current camera state (fov, position, etc..) - */ - storeState(): Camera; - /** - * Restores the camera state values if it has been stored. You must call storeState() first - */ - protected _restoreStateValues(): boolean; + /** + * Interface implemented by classes supporting behaviors + */ + interface IBehaviorAware { /** - * Restored camera state. You must call storeState() first + * Attach a behavior + * @param behavior defines the behavior to attach + * @returns the current host */ - restoreState(): boolean; - getClassName(): string; + addBehavior(behavior: Behavior): T; /** - * @param {boolean} fullDetails - support for multiple levels of logging within scene loading + * Remove a behavior from the current object + * @param behavior defines the behavior to detach + * @returns the current host */ - toString(fullDetails?: boolean): string; - readonly globalPosition: Vector3; - getActiveMeshes(): SmartArray; - isActiveMesh(mesh: Mesh): boolean; + removeBehavior(behavior: Behavior): T; /** - * Is this camera ready to be used/rendered - * @param completeCheck defines if a complete check (including post processes) has to be done (false by default) - * @return true if the camera is ready + * Gets a behavior using its name to search + * @param name defines the name to search + * @returns the behavior or null if not found */ - isReady(completeCheck?: boolean): boolean; - _initCache(): void; - _updateCache(ignoreParentClass?: boolean): void; - _isSynchronized(): boolean; - _isSynchronizedViewMatrix(): boolean; - _isSynchronizedProjectionMatrix(): boolean; - attachControl(element: HTMLElement, noPreventDefault?: boolean): void; - detachControl(element: HTMLElement): void; - update(): void; - _checkInputs(): void; - readonly rigCameras: Camera[]; - readonly rigPostProcess: Nullable; + getBehaviorByName(name: string): Nullable>; + } +} + +declare module BABYLON { + class Collider { + /** Define if a collision was found */ + collisionFound: boolean; /** - * Internal, gets the first post proces. - * @returns the first post process to be run on this camera. + * Define last intersection point in local space */ - _getFirstPostProcess(): Nullable; - private _cascadePostProcessesToRigCams(); - attachPostProcess(postProcess: PostProcess, insertAt?: Nullable): number; - detachPostProcess(postProcess: PostProcess): void; - getWorldMatrix(): Matrix; - _getViewMatrix(): Matrix; - getViewMatrix(force?: boolean): Matrix; - freezeProjectionMatrix(projection?: Matrix): void; - unfreezeProjectionMatrix(): void; - getProjectionMatrix(force?: boolean): Matrix; + intersectionPoint: Vector3; /** - * Gets the transformation matrix (ie. the multiplication of view by projection matrices) - * @returns a Matrix + * Define last collided mesh */ - getTransformationMatrix(): Matrix; - private updateFrustumPlanes(); - isInFrustum(target: ICullable): boolean; - isCompletelyInFrustum(target: ICullable): boolean; - getForwardRay(length?: number, transform?: Matrix, origin?: Vector3): Ray; + collidedMesh: Nullable; + private _collisionPoint; + private _planeIntersectionPoint; + private _tempVector; + private _tempVector2; + private _tempVector3; + private _tempVector4; + private _edge; + private _baseToVertex; + private _destinationPoint; + private _slidePlaneNormal; + private _displacementVector; + _radius: Vector3; + _retry: number; + private _velocity; + private _basePoint; + private _epsilon; + _velocityWorldLength: number; + _basePointWorld: Vector3; + private _velocityWorld; + private _normalizedVelocity; + _initialVelocity: Vector3; + _initialPosition: Vector3; + private _nearestDistance; + private _collisionMask; + collisionMask: number; /** - * Releases resources associated with this node. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + * Gets the plane normal used to compute the sliding response (in local space) */ - dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; - readonly leftCamera: Nullable; - readonly rightCamera: Nullable; - getLeftTarget(): Nullable; - getRightTarget(): Nullable; - setCameraRigMode(mode: number, rigParams: any): void; - private _getVRProjectionMatrix(); - protected _updateCameraRotationMatrix(): void; - protected _updateWebVRCameraRotationMatrix(): void; + readonly slidePlaneNormal: Vector3; + _initialize(source: Vector3, dir: Vector3, e: number): void; + _checkPointInTriangle(point: Vector3, pa: Vector3, pb: Vector3, pc: Vector3, n: Vector3): boolean; + _canDoCollision(sphereCenter: Vector3, sphereRadius: number, vecMin: Vector3, vecMax: Vector3): boolean; + _testTriangle(faceIndex: number, trianglePlaneArray: Array, p1: Vector3, p2: Vector3, p3: Vector3, hasMaterial: boolean): void; + _collide(trianglePlaneArray: Array, pts: Vector3[], indices: IndicesArray, indexStart: number, indexEnd: number, decal: number, hasMaterial: boolean): void; + _getResponse(pos: Vector3, vel: Vector3): void; + } +} + +declare module BABYLON { + var CollisionWorker: string; + interface ICollisionCoordinator { + getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: Nullable, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable) => void, collisionIndex: number): void; + init(scene: Scene): void; + destroy(): void; + onMeshAdded(mesh: AbstractMesh): void; + onMeshUpdated(mesh: AbstractMesh): void; + onMeshRemoved(mesh: AbstractMesh): void; + onGeometryAdded(geometry: Geometry): void; + onGeometryUpdated(geometry: Geometry): void; + onGeometryDeleted(geometry: Geometry): void; + } + interface SerializedMesh { + id: string; + name: string; + uniqueId: number; + geometryId: Nullable; + sphereCenter: Array; + sphereRadius: number; + boxMinimum: Array; + boxMaximum: Array; + worldMatrixFromCache: any; + subMeshes: Array; + checkCollisions: boolean; + } + interface SerializedSubMesh { + position: number; + verticesStart: number; + verticesCount: number; + indexStart: number; + indexCount: number; + hasMaterial: boolean; + sphereCenter: Array; + sphereRadius: number; + boxMinimum: Array; + boxMaximum: Array; + } + /** + * Interface describing the value associated with a geometry + */ + interface SerializedGeometry { /** - * This function MUST be overwritten by the different WebVR cameras available. - * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right. + * Defines the unique ID of the geometry */ - protected _getWebVRProjectionMatrix(): Matrix; + id: string; /** - * This function MUST be overwritten by the different WebVR cameras available. - * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right. + * Defines the array containing the positions */ - protected _getWebVRViewMatrix(): Matrix; - setCameraRigParameter(name: string, value: any): void; + positions: Float32Array; /** - * needs to be overridden by children so sub has required properties to be copied + * Defines the array containing the indices */ - createRigCamera(name: string, cameraIndex: number): Nullable; + indices: Uint32Array; /** - * May need to be overridden by children + * Defines the array containing the normals */ - _updateRigCameras(): void; - _setupInputs(): void; - serialize(): any; - clone(name: string): Camera; - getDirection(localAxis: Vector3): Vector3; - getDirectionToRef(localAxis: Vector3, result: Vector3): void; - static GetConstructorFromName(type: string, name: string, scene: Scene, interaxial_distance?: number, isStereoscopicSideBySide?: boolean): () => Camera; - computeWorldMatrix(): Matrix; - static Parse(parsedCamera: any, scene: Scene): Camera; + normals: Float32Array; } -} - -declare module BABYLON { - var CameraInputTypes: {}; - interface ICameraInput { - camera: Nullable; - getClassName(): string; - getSimpleName(): string; - attachControl: (element: HTMLElement, noPreventDefault?: boolean) => void; - detachControl: (element: Nullable) => void; - checkInputs?: () => void; + interface BabylonMessage { + taskType: WorkerTaskType; + payload: InitPayload | CollidePayload | UpdatePayload; } - interface CameraInputsMap { - [name: string]: ICameraInput; - [idx: number]: ICameraInput; + interface SerializedColliderToWorker { + position: Array; + velocity: Array; + radius: Array; } - class CameraInputsManager { - attached: CameraInputsMap; - attachedElement: Nullable; - noPreventDefault: boolean; - camera: TCamera; - checkInputs: () => void; - constructor(camera: TCamera); - /** - * Add an input method to a camera - * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs - * @param input camera input method - */ - add(input: ICameraInput): void; - /** - * Remove a specific input method from a camera - * example: camera.inputs.remove(camera.inputs.attached.mouse); - * @param inputToRemove camera input method - */ - remove(inputToRemove: ICameraInput): void; - removeByType(inputType: string): void; - private _addCheckInputs(fn); - attachInput(input: ICameraInput): void; - attachElement(element: HTMLElement, noPreventDefault?: boolean): void; - detachElement(element: HTMLElement, disconnect?: boolean): void; - rebuildInputCheck(): void; - /** - * Remove all attached input methods from a camera - */ - clear(): void; - serialize(serializedCamera: any): void; - parse(parsedCamera: any): void; + /** Defines supported task for worker process */ + enum WorkerTaskType { + /** Initialization */ + INIT = 0, + /** Update of geometry */ + UPDATE = 1, + /** Evaluate collision */ + COLLIDE = 2 + } + interface WorkerReply { + error: WorkerReplyType; + taskType: WorkerTaskType; + payload?: any; + } + interface CollisionReplyPayload { + newPosition: Array; + collisionId: number; + collidedMeshUniqueId: number; + } + interface InitPayload { + } + interface CollidePayload { + collisionId: number; + collider: SerializedColliderToWorker; + maximumRetry: number; + excludedMeshUniqueId: Nullable; + } + interface UpdatePayload { + updatedMeshes: { + [n: number]: SerializedMesh; + }; + updatedGeometries: { + [s: string]: SerializedGeometry; + }; + removedMeshes: Array; + removedGeometries: Array; + } + /** Defines kind of replies returned by worker */ + enum WorkerReplyType { + /** Success */ + SUCCESS = 0, + /** Unkown error */ + UNKNOWN_ERROR = 1 + } + class CollisionCoordinatorWorker implements ICollisionCoordinator { + private _scene; + private _scaledPosition; + private _scaledVelocity; + private _collisionsCallbackArray; + private _init; + private _runningUpdated; + private _worker; + private _addUpdateMeshesList; + private _addUpdateGeometriesList; + private _toRemoveMeshesArray; + private _toRemoveGeometryArray; + constructor(); + static SerializeMesh: (mesh: AbstractMesh) => SerializedMesh; + static SerializeGeometry: (geometry: Geometry) => SerializedGeometry; + getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable) => void, collisionIndex: number): void; + init(scene: Scene): void; + destroy(): void; + onMeshAdded(mesh: AbstractMesh): void; + onMeshUpdated: (transformNode: TransformNode) => void; + onMeshRemoved(mesh: AbstractMesh): void; + onGeometryAdded(geometry: Geometry): void; + onGeometryUpdated: (geometry: Geometry) => void; + onGeometryDeleted(geometry: Geometry): void; + private _afterRender; + private _onMessageFromWorker; + } + class CollisionCoordinatorLegacy implements ICollisionCoordinator { + private _scene; + private _scaledPosition; + private _scaledVelocity; + private _finalPosition; + getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable) => void, collisionIndex: number): void; + init(scene: Scene): void; + destroy(): void; + onMeshAdded(mesh: AbstractMesh): void; + onMeshUpdated(mesh: AbstractMesh): void; + onMeshRemoved(mesh: AbstractMesh): void; + onGeometryAdded(geometry: Geometry): void; + onGeometryUpdated(geometry: Geometry): void; + onGeometryDeleted(geometry: Geometry): void; + private _collideWithWorld; + } +} + +declare function importScripts(...urls: string[]): void; +declare const safePostMessage: any; +declare module BABYLON { + var WorkerIncluded: boolean; + class CollisionCache { + private _meshes; + private _geometries; + getMeshes(): { + [n: number]: SerializedMesh; + }; + getGeometries(): { + [s: number]: SerializedGeometry; + }; + getMesh(id: any): SerializedMesh; + addMesh(mesh: SerializedMesh): void; + removeMesh(uniqueId: number): void; + getGeometry(id: string): SerializedGeometry; + addGeometry(geometry: SerializedGeometry): void; + removeGeometry(id: string): void; + } + class CollideWorker { + collider: Collider; + private _collisionCache; + private finalPosition; + private collisionsScalingMatrix; + private collisionTranformationMatrix; + constructor(collider: Collider, _collisionCache: CollisionCache, finalPosition: Vector3); + collideWithWorld(position: Vector3, velocity: Vector3, maximumRetry: number, excludedMeshUniqueId: Nullable): void; + private checkCollision; + private processCollisionsForSubMeshes; + private collideForSubMesh; + private checkSubmeshCollision; + } + interface ICollisionDetector { + onInit(payload: InitPayload): void; + onUpdate(payload: UpdatePayload): void; + onCollision(payload: CollidePayload): void; + } + class CollisionDetectorTransferable implements ICollisionDetector { + private _collisionCache; + onInit(payload: InitPayload): void; + onUpdate(payload: UpdatePayload): void; + onCollision(payload: CollidePayload): void; } } declare module BABYLON { + class IntersectionInfo { + bu: Nullable; + bv: Nullable; + distance: number; + faceId: number; + subMeshId: number; + constructor(bu: Nullable, bv: Nullable, distance: number); + } /** - * This is a camera specifically designed to react to device orientation events such as a modern mobile device - * being tilted forward or back and left or right. + * Information about the result of picking within a scene + * See https://doc.babylonjs.com/babylon101/picking_collisions */ - class DeviceOrientationCamera extends FreeCamera { - private _initialQuaternion; - private _quaternionCache; + class PickingInfo { /** - * Creates a new device orientation camera - * @param name The name of the camera - * @param position The start position camera - * @param scene The scene the camera belongs to + * If the pick collided with an object */ - constructor(name: string, position: Vector3, scene: Scene); + hit: boolean; /** - * Gets the current instance class name ("DeviceOrientationCamera"). - * This helps avoiding instanceof at run time. - * @returns the class name + * Distance away where the pick collided */ - getClassName(): string; + distance: number; /** - * Checks and applies the current values of the inputs to the camera. (Internal use only) + * The location of pick collision */ - _checkInputs(): void; + pickedPoint: Nullable; /** - * Reset the camera to its default orientation on the specified axis only. - * @param axis The axis to reset + * The mesh corrisponding the the pick collision */ - resetToCurrentRotation(axis?: Axis): void; - } -} - -declare module BABYLON { - class FollowCamera extends TargetCamera { - radius: number; - rotationOffset: number; - heightOffset: number; - cameraAcceleration: number; - maxCameraSpeed: number; - lockedTarget: Nullable; - constructor(name: string, position: Vector3, scene: Scene, lockedTarget?: Nullable); - private getRadians(degrees); - private follow(cameraTarget); - _checkInputs(): void; - getClassName(): string; - } - class ArcFollowCamera extends TargetCamera { - alpha: number; - beta: number; - radius: number; - target: Nullable; - private _cartesianCoordinates; - constructor(name: string, alpha: number, beta: number, radius: number, target: Nullable, scene: Scene); - private follow(); - _checkInputs(): void; - getClassName(): string; + pickedMesh: Nullable; + /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/ + bu: number; + /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/ + bv: number; + /** The id of the face on the mesh that was picked */ + faceId: number; + /** Id of the the submesh that was picked */ + subMeshId: number; + /** If a sprite was picked, this will be the sprite the pick collided with */ + pickedSprite: Nullable; + /** + * If a mesh was used to do the picking (eg. 6dof controller) this will be populated. + */ + originMesh: Nullable; + /** + * The ray that was used to perform the picking. + */ + ray: Nullable; + /** + * Gets the normal corrispodning to the face the pick collided with + * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false) + * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map + * @returns The normal corrispodning to the face the pick collided with + */ + getNormal(useWorldCoordinates?: boolean, useVerticesNormals?: boolean): Nullable; + /** + * Gets the texture coordinates of where the pick occured + * @returns the vector containing the coordnates of the texture + */ + getTextureCoordinates(): Nullable; } } -declare module BABYLON { - class FreeCamera extends TargetCamera { - ellipsoid: Vector3; - ellipsoidOffset: Vector3; - checkCollisions: boolean; - applyGravity: boolean; - inputs: FreeCameraInputsManager; +/** + * Module Debug contains the (visual) components to debug a scene correctly + */ +declare module BABYLON.Debug { + /** + * The Axes viewer will show 3 axes in a specific point in space + */ + class AxesViewer { + private _xline; + private _yline; + private _zline; + private _xmesh; + private _ymesh; + private _zmesh; /** - * Gets the input sensibility for a mouse input. (default is 2000.0) - * Higher values reduce sensitivity. + * Gets the hosting scene */ + scene: Nullable; /** - * Sets the input sensibility for a mouse input. (default is 2000.0) - * Higher values reduce sensitivity. + * Gets or sets a number used to scale line length */ - angularSensibility: number; - keysUp: number[]; - keysDown: number[]; - keysLeft: number[]; - keysRight: number[]; - onCollide: (collidedMesh: AbstractMesh) => void; - private _collider; - private _needMoveForGravity; - private _oldPosition; - private _diffPosition; - private _newPosition; - _localDirection: Vector3; - _transformedDirection: Vector3; - constructor(name: string, position: Vector3, scene: Scene, setActiveOnSceneIfNoneActive?: boolean); - attachControl(element: HTMLElement, noPreventDefault?: boolean): void; - detachControl(element: HTMLElement): void; - private _collisionMask; - collisionMask: number; - _collideWithWorld(displacement: Vector3): void; - private _onCollisionPositionChange; - _checkInputs(): void; - _decideIfNeedsToMove(): boolean; - _updatePosition(): void; + scaleLines: number; + /** + * Creates a new AxesViewer + * @param scene defines the hosting scene + * @param scaleLines defines a number used to scale line length (1 by default) + */ + constructor(scene: Scene, scaleLines?: number); + /** + * Force the viewer to update + * @param position defines the position of the viewer + * @param xaxis defines the x axis of the viewer + * @param yaxis defines the y axis of the viewer + * @param zaxis defines the z axis of the viewer + */ + update(position: Vector3, xaxis: Vector3, yaxis: Vector3, zaxis: Vector3): void; + /** Releases resources */ dispose(): void; - getClassName(): string; - } -} - -declare module BABYLON { - class FreeCameraInputsManager extends CameraInputsManager { - constructor(camera: FreeCamera); - addKeyboard(): FreeCameraInputsManager; - addMouse(touchEnabled?: boolean): FreeCameraInputsManager; - addDeviceOrientation(): FreeCameraInputsManager; - addTouch(): FreeCameraInputsManager; - addVirtualJoystick(): FreeCameraInputsManager; - } -} - -declare module BABYLON { - class GamepadCamera extends UniversalCamera { - gamepadAngularSensibility: number; - gamepadMoveSensibility: number; - constructor(name: string, position: Vector3, scene: Scene); - getClassName(): string; } } -declare module BABYLON { - class TargetCamera extends Camera { - cameraDirection: Vector3; - cameraRotation: Vector2; - rotation: Vector3; - rotationQuaternion: Quaternion; - speed: number; - noRotationConstraint: boolean; - lockedTarget: any; - _currentTarget: Vector3; - _viewMatrix: Matrix; - _camMatrix: Matrix; - _cameraTransformMatrix: Matrix; - _cameraRotationMatrix: Matrix; - private _rigCamTransformMatrix; - _referencePoint: Vector3; - private _currentUpVector; - _transformedReferencePoint: Vector3; - protected _globalCurrentTarget: Vector3; - protected _globalCurrentUpVector: Vector3; - _reset: () => void; - constructor(name: string, position: Vector3, scene: Scene, setActiveOnSceneIfNoneActive?: boolean); - getFrontPosition(distance: number): Vector3; - _getLockedTargetPosition(): Nullable; - /** - * Store current camera state (fov, position, etc..) - */ - private _storedPosition; - private _storedRotation; - private _storedRotationQuaternion; - storeState(): Camera; +declare module BABYLON.Debug { + /** + * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh + * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8 + */ + class BoneAxesViewer extends AxesViewer { /** - * Restored camera state. You must call storeState() first + * Gets or sets the target mesh where to display the axes viewer */ - _restoreStateValues(): boolean; - _initCache(): void; - _updateCache(ignoreParentClass?: boolean): void; - _isSynchronizedViewMatrix(): boolean; - _computeLocalCameraSpeed(): number; - setTarget(target: Vector3): void; + mesh: Nullable; /** - * Return the current target position of the camera. This value is expressed in local space. + * Gets or sets the target bone where to display the axes viewer */ - getTarget(): Vector3; - _decideIfNeedsToMove(): boolean; - _updatePosition(): void; - _checkInputs(): void; - protected _updateCameraRotationMatrix(): void; - _getViewMatrix(): Matrix; - protected _computeViewMatrix(position: Vector3, target: Vector3, up: Vector3): void; + bone: Nullable; + /** Gets current position */ + pos: Vector3; + /** Gets direction of X axis */ + xaxis: Vector3; + /** Gets direction of Y axis */ + yaxis: Vector3; + /** Gets direction of Z axis */ + zaxis: Vector3; /** - * @override - * Override Camera.createRigCamera + * Creates a new BoneAxesViewer + * @param scene defines the hosting scene + * @param bone defines the target bone + * @param mesh defines the target mesh + * @param scaleLines defines a scaling factor for line length (1 by default) */ - createRigCamera(name: string, cameraIndex: number): Nullable; + constructor(scene: Scene, bone: Bone, mesh: Mesh, scaleLines?: number); /** - * @override - * Override Camera._updateRigCameras + * Force the viewer to update */ - _updateRigCameras(): void; - private _getRigCamPosition(halfSpace, result); - getClassName(): string; - } -} - -declare module BABYLON { - class TouchCamera extends FreeCamera { - touchAngularSensibility: number; - touchMoveSensibility: number; - constructor(name: string, position: Vector3, scene: Scene); - getClassName(): string; - _setupInputs(): void; - } -} - -declare module BABYLON { - class UniversalCamera extends TouchCamera { - gamepadAngularSensibility: number; - gamepadMoveSensibility: number; - constructor(name: string, position: Vector3, scene: Scene); - getClassName(): string; + update(): void; + /** Releases resources */ + dispose(): void; } } declare module BABYLON { - class VirtualJoysticksCamera extends FreeCamera { - constructor(name: string, position: Vector3, scene: Scene); - getClassName(): string; + class DebugLayer { + private _scene; + static InspectorURL: string; + private _inspector; + private BJSINSPECTOR; + onPropertyChangedObservable: Observable<{ + object: any; + property: string; + value: any; + initialValue: any; + }>; + constructor(scene: Scene); + /** Creates the inspector window. */ + private _createInspector; + isVisible(): boolean; + hide(): void; + /** + * + * Launch the debugLayer. + * + * initialTab: + * | Value | Tab Name | + * | --- | --- | + * | 0 | Scene | + * | 1 | Console | + * | 2 | Stats | + * | 3 | Textures | + * | 4 | Mesh | + * | 5 | Light | + * | 6 | Material | + * | 7 | GLTF | + * | 8 | GUI | + * | 9 | Physics | + * | 10 | Camera | + * | 11 | Audio | + * + */ + show(config?: { + popup?: boolean; + initialTab?: number; + parentElement?: HTMLElement; + newColors?: { + backgroundColor?: string; + backgroundColorLighter?: string; + backgroundColorLighter2?: string; + backgroundColorLighter3?: string; + color?: string; + colorTop?: string; + colorBot?: string; + }; + }): void; + /** + * Gets the active tab + * @return the index of the active tab or -1 if the inspector is hidden + */ + getActiveTab(): number; } } -interface VRDisplay extends EventTarget { +declare module BABYLON.Debug { /** - * Dictionary of capabilities describing the VRDisplay. + * Used to show the physics impostor around the specific mesh */ - readonly capabilities: VRDisplayCapabilities; - /** - * z-depth defining the far plane of the eye view frustum - * enables mapping of values in the render target depth - * attachment to scene coordinates. Initially set to 10000.0. - */ - depthFar: number; - /** - * z-depth defining the near plane of the eye view frustum - * enables mapping of values in the render target depth - * attachment to scene coordinates. Initially set to 0.01. - */ - depthNear: number; - /** - * An identifier for this distinct VRDisplay. Used as an - * association point in the Gamepad API. - */ - readonly displayId: number; - /** - * A display name, a user-readable name identifying it. - */ - readonly displayName: string; - readonly isConnected: boolean; - readonly isPresenting: boolean; - /** - * If this VRDisplay supports room-scale experiences, the optional - * stage attribute contains details on the room-scale parameters. - */ - readonly stageParameters: VRStageParameters | null; - /** - * Passing the value returned by `requestAnimationFrame` to - * `cancelAnimationFrame` will unregister the callback. - */ - cancelAnimationFrame(handle: number): void; - /** - * Stops presenting to the VRDisplay. - */ - exitPresent(): Promise; - getEyeParameters(whichEye: string): VREyeParameters; - /** - * Populates the passed VRFrameData with the information required to render - * the current frame. - */ - getFrameData(frameData: VRFrameData): boolean; - /** - * Get the layers currently being presented. - */ - getLayers(): VRLayer[]; - /** - * Return a VRPose containing the future predicted pose of the VRDisplay - * when the current frame will be presented. The value returned will not - * change until JavaScript has returned control to the browser. - * - * The VRPose will contain the position, orientation, velocity, - * and acceleration of each of these properties. - */ - getPose(): VRPose; - /** - * Return the current instantaneous pose of the VRDisplay, with no - * prediction applied. - */ - getImmediatePose(): VRPose; - /** - * The callback passed to `requestAnimationFrame` will be called - * any time a new frame should be rendered. When the VRDisplay is - * presenting the callback will be called at the native refresh - * rate of the HMD. When not presenting this function acts - * identically to how window.requestAnimationFrame acts. Content should - * make no assumptions of frame rate or vsync behavior as the HMD runs - * asynchronously from other displays and at differing refresh rates. - */ - requestAnimationFrame(callback: FrameRequestCallback): number; - /** - * Begin presenting to the VRDisplay. Must be called in response to a user gesture. - * Repeat calls while already presenting will update the VRLayers being displayed. - */ - requestPresent(layers: VRLayer[]): Promise; - /** - * Reset the pose for this display, treating its current position and - * orientation as the "origin/zero" values. VRPose.position, - * VRPose.orientation, and VRStageParameters.sittingToStandingTransform may be - * updated when calling resetPose(). This should be called in only - * sitting-space experiences. - */ - resetPose(): void; - /** - * The VRLayer provided to the VRDisplay will be captured and presented - * in the HMD. Calling this function has the same effect on the source - * canvas as any other operation that uses its source image, and canvases - * created without preserveDrawingBuffer set to true will be cleared. - */ - submitFrame(pose?: VRPose): void; -} -declare var VRDisplay: { - prototype: VRDisplay; - new (): VRDisplay; -}; -interface VRLayer { - leftBounds?: number[] | null; - rightBounds?: number[] | null; - source?: HTMLCanvasElement | null; -} -interface VRDisplayCapabilities { - readonly canPresent: boolean; - readonly hasExternalDisplay: boolean; - readonly hasOrientation: boolean; - readonly hasPosition: boolean; - readonly maxLayers: number; -} -interface VREyeParameters { - /** @deprecated */ - readonly fieldOfView: VRFieldOfView; - readonly offset: Float32Array; - readonly renderHeight: number; - readonly renderWidth: number; -} -interface VRFieldOfView { - readonly downDegrees: number; - readonly leftDegrees: number; - readonly rightDegrees: number; - readonly upDegrees: number; -} -interface VRFrameData { - readonly leftProjectionMatrix: Float32Array; - readonly leftViewMatrix: Float32Array; - readonly pose: VRPose; - readonly rightProjectionMatrix: Float32Array; - readonly rightViewMatrix: Float32Array; - readonly timestamp: number; -} -interface VRPose { - readonly angularAcceleration: Float32Array | null; - readonly angularVelocity: Float32Array | null; - readonly linearAcceleration: Float32Array | null; - readonly linearVelocity: Float32Array | null; - readonly orientation: Float32Array | null; - readonly position: Float32Array | null; - readonly timestamp: number; -} -interface VRStageParameters { - sittingToStandingTransform?: Float32Array; - sizeX?: number; - sizeY?: number; -} -interface Navigator { - getVRDisplays(): Promise; - readonly activeVRDisplays: ReadonlyArray; -} -interface Window { - onvrdisplayconnected: ((this: Window, ev: Event) => any) | null; - onvrdisplaydisconnected: ((this: Window, ev: Event) => any) | null; - onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; - addEventListener(type: "vrdisplayconnected", listener: (ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "vrdisplaydisconnected", listener: (ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "vrdisplaypresentchange", listener: (ev: Event) => any, useCapture?: boolean): void; -} -interface Gamepad { - readonly displayId: number; -} - -declare module BABYLON { - class Collider { - /** Define if a collision was found */ - collisionFound: boolean; + class PhysicsViewer { + /** @hidden */ + protected _impostors: Array>; + /** @hidden */ + protected _meshes: Array>; + /** @hidden */ + protected _scene: Nullable; + /** @hidden */ + protected _numMeshes: number; + /** @hidden */ + protected _physicsEnginePlugin: Nullable; + private _renderFunction; + private _debugBoxMesh; + private _debugSphereMesh; + private _debugMaterial; /** - * Define last intersection point in local space + * Creates a new PhysicsViewer + * @param scene defines the hosting scene */ - intersectionPoint: Vector3; + constructor(scene: Scene); + /** @hidden */ + protected _updateDebugMeshes(): void; /** - * Define last collided mesh + * Renders a specified physic impostor + * @param impostor defines the impostor to render */ - collidedMesh: Nullable; - private _collisionPoint; - private _planeIntersectionPoint; - private _tempVector; - private _tempVector2; - private _tempVector3; - private _tempVector4; - private _edge; - private _baseToVertex; - private _destinationPoint; - private _slidePlaneNormal; - private _displacementVector; - _radius: Vector3; - _retry: number; - private _velocity; - private _basePoint; - private _epsilon; - _velocityWorldLength: number; - _basePointWorld: Vector3; - private _velocityWorld; - private _normalizedVelocity; - _initialVelocity: Vector3; - _initialPosition: Vector3; - private _nearestDistance; - private _collisionMask; - collisionMask: number; + showImpostor(impostor: PhysicsImpostor): void; /** - * Gets the plane normal used to compute the sliding response (in local space) + * Hides a specified physic impostor + * @param impostor defines the impostor to hide */ - readonly slidePlaneNormal: Vector3; - _initialize(source: Vector3, dir: Vector3, e: number): void; - _checkPointInTriangle(point: Vector3, pa: Vector3, pb: Vector3, pc: Vector3, n: Vector3): boolean; - _canDoCollision(sphereCenter: Vector3, sphereRadius: number, vecMin: Vector3, vecMax: Vector3): boolean; - _testTriangle(faceIndex: number, trianglePlaneArray: Array, p1: Vector3, p2: Vector3, p3: Vector3, hasMaterial: boolean): void; - _collide(trianglePlaneArray: Array, pts: Vector3[], indices: IndicesArray, indexStart: number, indexEnd: number, decal: number, hasMaterial: boolean): void; - _getResponse(pos: Vector3, vel: Vector3): void; + hideImpostor(impostor: Nullable): void; + private _getDebugMaterial; + private _getDebugBoxMesh; + private _getDebugSphereMesh; + private _getDebugMesh; + /** Releases all resources */ + dispose(): void; } } declare module BABYLON { - var CollisionWorker: string; - interface ICollisionCoordinator { - getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: Nullable, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable) => void, collisionIndex: number): void; - init(scene: Scene): void; - destroy(): void; - onMeshAdded(mesh: AbstractMesh): void; - onMeshUpdated(mesh: AbstractMesh): void; - onMeshRemoved(mesh: AbstractMesh): void; - onGeometryAdded(geometry: Geometry): void; - onGeometryUpdated(geometry: Geometry): void; - onGeometryDeleted(geometry: Geometry): void; - } - interface SerializedMesh { - id: string; - name: string; - uniqueId: number; - geometryId: Nullable; - sphereCenter: Array; - sphereRadius: number; - boxMinimum: Array; - boxMaximum: Array; - worldMatrixFromCache: any; - subMeshes: Array; - checkCollisions: boolean; - } - interface SerializedSubMesh { - position: number; - verticesStart: number; - verticesCount: number; - indexStart: number; - indexCount: number; - hasMaterial: boolean; - sphereCenter: Array; - sphereRadius: number; - boxMinimum: Array; - boxMaximum: Array; + class RayHelper { + ray: Nullable; + private _renderPoints; + private _renderLine; + private _renderFunction; + private _scene; + private _updateToMeshFunction; + private _attachedToMesh; + private _meshSpaceDirection; + private _meshSpaceOrigin; + static CreateAndShow(ray: Ray, scene: Scene, color: Color3): RayHelper; + constructor(ray: Ray); + show(scene: Scene, color?: Color3): void; + hide(): void; + private _render; + attachToMesh(mesh: AbstractMesh, meshSpaceDirection?: Vector3, meshSpaceOrigin?: Vector3, length?: number): void; + detachFromMesh(): void; + private _updateToMesh; + dispose(): void; } +} + +declare module BABYLON.Debug { /** - * Interface describing the value associated with a geometry + * Class used to render a debug view of a given skeleton + * @see http://www.babylonjs-playground.com/#1BZJVJ#8 */ - interface SerializedGeometry { - /** - * Defines the unique ID of the geometry - */ - id: string; - /** - * Defines the array containing the positions - */ - positions: Float32Array; - /** - * Defines the array containing the indices - */ - indices: Uint32Array; + class SkeletonViewer { + /** defines the skeleton to render */ + skeleton: Skeleton; + /** defines the mesh attached to the skeleton */ + mesh: AbstractMesh; + /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */ + autoUpdateBonesMatrices: boolean; + /** defines the rendering group id to use with the viewer */ + renderingGroupId: number; + /** Gets or sets the color used to render the skeleton */ + color: Color3; + private _scene; + private _debugLines; + private _debugMesh; + private _isEnabled; + private _renderFunction; /** - * Defines the array containing the normals + * Creates a new SkeletonViewer + * @param skeleton defines the skeleton to render + * @param mesh defines the mesh attached to the skeleton + * @param scene defines the hosting scene + * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) + * @param renderingGroupId defines the rendering group id to use with the viewer */ - normals: Float32Array; - } - interface BabylonMessage { - taskType: WorkerTaskType; - payload: InitPayload | CollidePayload | UpdatePayload; - } - interface SerializedColliderToWorker { - position: Array; - velocity: Array; - radius: Array; - } - /** Defines supported task for worker process */ - enum WorkerTaskType { - /** Initialization */ - INIT = 0, - /** Update of geometry */ - UPDATE = 1, - /** Evaluate collision */ - COLLIDE = 2, - } - interface WorkerReply { - error: WorkerReplyType; - taskType: WorkerTaskType; - payload?: any; - } - interface CollisionReplyPayload { - newPosition: Array; - collisionId: number; - collidedMeshUniqueId: number; - } - interface InitPayload { - } - interface CollidePayload { - collisionId: number; - collider: SerializedColliderToWorker; - maximumRetry: number; - excludedMeshUniqueId: Nullable; - } - interface UpdatePayload { - updatedMeshes: { - [n: number]: SerializedMesh; - }; - updatedGeometries: { - [s: string]: SerializedGeometry; - }; - removedMeshes: Array; - removedGeometries: Array; - } - /** Defines kind of replies returned by worker */ - enum WorkerReplyType { - /** Success */ - SUCCESS = 0, - /** Unkown error */ - UNKNOWN_ERROR = 1, - } - class CollisionCoordinatorWorker implements ICollisionCoordinator { - private _scene; - private _scaledPosition; - private _scaledVelocity; - private _collisionsCallbackArray; - private _init; - private _runningUpdated; - private _worker; - private _addUpdateMeshesList; - private _addUpdateGeometriesList; - private _toRemoveMeshesArray; - private _toRemoveGeometryArray; - constructor(); - static SerializeMesh: (mesh: AbstractMesh) => SerializedMesh; - static SerializeGeometry: (geometry: Geometry) => SerializedGeometry; - getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable) => void, collisionIndex: number): void; - init(scene: Scene): void; - destroy(): void; - onMeshAdded(mesh: AbstractMesh): void; - onMeshUpdated: (transformNode: TransformNode) => void; - onMeshRemoved(mesh: AbstractMesh): void; - onGeometryAdded(geometry: Geometry): void; - onGeometryUpdated: (geometry: Geometry) => void; - onGeometryDeleted(geometry: Geometry): void; - private _afterRender; - private _onMessageFromWorker; - } - class CollisionCoordinatorLegacy implements ICollisionCoordinator { - private _scene; - private _scaledPosition; - private _scaledVelocity; - private _finalPosition; - getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable) => void, collisionIndex: number): void; - init(scene: Scene): void; - destroy(): void; - onMeshAdded(mesh: AbstractMesh): void; - onMeshUpdated(mesh: AbstractMesh): void; - onMeshRemoved(mesh: AbstractMesh): void; - onGeometryAdded(geometry: Geometry): void; - onGeometryUpdated(geometry: Geometry): void; - onGeometryDeleted(geometry: Geometry): void; - private _collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh?); + constructor( + /** defines the skeleton to render */ + skeleton: Skeleton, + /** defines the mesh attached to the skeleton */ + mesh: AbstractMesh, scene: Scene, + /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */ + autoUpdateBonesMatrices?: boolean, + /** defines the rendering group id to use with the viewer */ + renderingGroupId?: number); + /** Gets or sets a boolean indicating if the viewer is enabled */ + isEnabled: boolean; + private _getBonePosition; + private _getLinesForBonesWithLength; + private _getLinesForBonesNoLength; + /** Update the viewer to sync with current skeleton state */ + update(): void; + /** Release associated resources */ + dispose(): void; } } -declare function importScripts(...urls: string[]): void; -declare const safePostMessage: any; declare module BABYLON { - var WorkerIncluded: boolean; - class CollisionCache { - private _meshes; - private _geometries; - getMeshes(): { - [n: number]: SerializedMesh; - }; - getGeometries(): { - [s: number]: SerializedGeometry; - }; - getMesh(id: any): SerializedMesh; - addMesh(mesh: SerializedMesh): void; - removeMesh(uniqueId: number): void; - getGeometry(id: string): SerializedGeometry; - addGeometry(geometry: SerializedGeometry): void; - removeGeometry(id: string): void; - } - class CollideWorker { - collider: Collider; - private _collisionCache; - private finalPosition; - private collisionsScalingMatrix; - private collisionTranformationMatrix; - constructor(collider: Collider, _collisionCache: CollisionCache, finalPosition: Vector3); - collideWithWorld(position: Vector3, velocity: Vector3, maximumRetry: number, excludedMeshUniqueId: Nullable): void; - private checkCollision(mesh); - private processCollisionsForSubMeshes(transformMatrix, mesh); - private collideForSubMesh(subMesh, transformMatrix, meshGeometry); - private checkSubmeshCollision(subMesh); + class KeyboardEventTypes { + static _KEYDOWN: number; + static _KEYUP: number; + static readonly KEYDOWN: number; + static readonly KEYUP: number; } - interface ICollisionDetector { - onInit(payload: InitPayload): void; - onUpdate(payload: UpdatePayload): void; - onCollision(payload: CollidePayload): void; + class KeyboardInfo { + type: number; + event: KeyboardEvent; + constructor(type: number, event: KeyboardEvent); } - class CollisionDetectorTransferable implements ICollisionDetector { - private _collisionCache; - onInit(payload: InitPayload): void; - onUpdate(payload: UpdatePayload): void; - onCollision(payload: CollidePayload): void; + /** + * This class is used to store keyboard related info for the onPreKeyboardObservable event. + * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable + */ + class KeyboardInfoPre extends KeyboardInfo { + constructor(type: number, event: KeyboardEvent); + skipOnPointerObservable: boolean; } } declare module BABYLON { - class IntersectionInfo { - bu: Nullable; - bv: Nullable; - distance: number; - faceId: number; - subMeshId: number; - constructor(bu: Nullable, bv: Nullable, distance: number); + class PointerEventTypes { + static _POINTERDOWN: number; + static _POINTERUP: number; + static _POINTERMOVE: number; + static _POINTERWHEEL: number; + static _POINTERPICK: number; + static _POINTERTAP: number; + static _POINTERDOUBLETAP: number; + static readonly POINTERDOWN: number; + static readonly POINTERUP: number; + static readonly POINTERMOVE: number; + static readonly POINTERWHEEL: number; + static readonly POINTERPICK: number; + static readonly POINTERTAP: number; + static readonly POINTERDOUBLETAP: number; + } + class PointerInfoBase { + type: number; + event: PointerEvent | MouseWheelEvent; + constructor(type: number, event: PointerEvent | MouseWheelEvent); } /** - * Information about the result of picking within a scene - * See https://doc.babylonjs.com/babylon101/picking_collisions + * This class is used to store pointer related info for the onPrePointerObservable event. + * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable */ - class PickingInfo { - /** - * If the pick collided with an object - */ - hit: boolean; - /** - * Distance away where the pick collided - */ - distance: number; - /** - * The location of pick collision - */ - pickedPoint: Nullable; - /** - * The mesh corrisponding the the pick collision - */ - pickedMesh: Nullable; - /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/ - bu: number; - /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/ - bv: number; - /** The id of the face on the mesh that was picked */ - faceId: number; - /** Id of the the submesh that was picked */ - subMeshId: number; - /** If a sprite was picked, this will be the sprite the pick collided with */ - pickedSprite: Nullable; - /** - * If a mesh was used to do the picking (eg. 6dof controller) this will be populated. - */ - originMesh: Nullable; + class PointerInfoPre extends PointerInfoBase { /** - * The ray that was used to perform the picking. + * Ray from a pointer if availible (eg. 6dof controller) */ ray: Nullable; - /** - * Gets the normal corrispodning to the face the pick collided with - * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false) - * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map - * @returns The normal corrispodning to the face the pick collided with - */ - getNormal(useWorldCoordinates?: boolean, useVerticesNormals?: boolean): Nullable; - /** - * Gets the texture coordinates of where the pick occured - * @returns the vector containing the coordnates of the texture - */ - getTextureCoordinates(): Nullable; + constructor(type: number, event: PointerEvent | MouseWheelEvent, localX: number, localY: number); + localPosition: Vector2; + skipOnPointerObservable: boolean; + } + /** + * This type contains all the data related to a pointer event in Babylon.js. + * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class. + */ + class PointerInfo extends PointerInfoBase { + pickInfo: Nullable; + constructor(type: number, event: PointerEvent | MouseWheelEvent, pickInfo: Nullable); } } @@ -7497,10 +7075,10 @@ declare module BABYLON { * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false) */ constructor(canvasOrContext: Nullable, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio?: boolean); - private _rebuildInternalTextures(); - private _rebuildEffects(); - private _rebuildBuffers(); - private _initGLContext(); + private _rebuildInternalTextures; + private _rebuildEffects; + private _rebuildBuffers; + private _initGLContext; /** * Gets version of the current webGL context */ @@ -7509,7 +7087,7 @@ declare module BABYLON { * Returns true if the stencil buffer has been enabled through the creation option of the context. */ readonly isStencilEnable: boolean; - private _prepareWorkingCanvas(); + private _prepareWorkingCanvas; /** * Reset the texture cache to empty state */ @@ -7820,7 +7398,7 @@ declare module BABYLON { */ disableVR(): void; private _onVRFullScreenTriggered; - private _getVRDisplaysAsync(); + private _getVRDisplaysAsync; /** * Binds the frame buffer to the specified texture. * @param texture The texture to render to or null for the default canvas @@ -7832,7 +7410,7 @@ declare module BABYLON { * @param lodLevel defines le lod level to bind to the frame buffer */ bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, depthStencilTexture?: InternalTexture, lodLevel?: number): void; - private bindUnboundFramebuffer(framebuffer); + private bindUnboundFramebuffer; /** * Unbind the current render target texture from the webGL context * @param texture defines the render target texture to unbind @@ -7884,7 +7462,7 @@ declare module BABYLON { * @param count defines the size of the data to update */ updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: FloatArray, offset?: number, count?: number): void; - private _resetVertexBufferBinding(); + private _resetVertexBufferBinding; /** * Creates a vertex buffer * @param data the data for the vertex buffer @@ -7912,7 +7490,7 @@ declare module BABYLON { * @param byteLength the byte length of the data */ updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void; - private _resetIndexBufferBinding(); + private _resetIndexBufferBinding; /** * Creates a new index buffer * @param indices defines the content of the index buffer @@ -7943,16 +7521,16 @@ declare module BABYLON { * @param index defines the index where to bind the block */ bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void; - private bindIndexBuffer(buffer); - private bindBuffer(buffer, target); + private bindIndexBuffer; + private bindBuffer; /** * update the bound buffer with the given data * @param data defines the data to update */ updateArrayBuffer(data: Float32Array): void; - private _vertexAttribPointer(buffer, indx, size, type, normalized, stride, offset); - private _bindIndexBufferWithCache(indexBuffer); - private _bindVertexBuffersAttributes(vertexBuffers, effect); + private _vertexAttribPointer; + private _bindIndexBufferWithCache; + private _bindVertexBuffersAttributes; /** * Records a vertex array object * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects @@ -7980,7 +7558,7 @@ declare module BABYLON { * @param effect defines the effect associated with the vertex buffer */ bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void; - private _unbindVertexArrayObject(); + private _unbindVertexArrayObject; /** * Bind a list of vertex buffers to the webGL context * @param vertexBuffers defines the list of vertex buffers to bind @@ -8062,7 +7640,7 @@ declare module BABYLON { * @param instancesCount defines the number of instances to draw (if instanciation is enabled) */ drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void; - private _drawMode(fillMode); + private _drawMode; /** @hidden */ _releaseEffect(effect: Effect): void; /** @hidden */ @@ -8081,8 +7659,8 @@ declare module BABYLON { * @returns the new Effect */ createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect; - private _compileShader(source, type, defines, shaderVersion); - private _compileRawShader(source, type); + private _compileShader; + private _compileRawShader; /** * Directly creates a webGL program * @param vertexCode defines the vertex shader code to use @@ -8102,7 +7680,7 @@ declare module BABYLON { * @returns the new webGL program */ createShaderProgram(vertexCode: string, fragmentCode: string, defines: Nullable, context?: WebGLRenderingContext, transformFeedbackVaryings?: Nullable): WebGLProgram; - private _createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings?); + private _createShaderProgram; /** * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names * @param shaderProgram defines the webGL program to use @@ -8375,9 +7953,9 @@ declare module BABYLON { * @returns The extension selected. */ setTextureFormatToUse(formatsAvailable: Array): Nullable; - private _getSamplingParameters(samplingMode, generateMipMaps); - private _partialLoadImg(url, index, loadedImages, scene, onfinish, onErrorCallBack?); - private _cascadeLoadImgs(rootUrl, scene, onfinish, files, onError?); + private _getSamplingParameters; + private _partialLoadImg; + private _cascadeLoadImgs; /** @hidden */ _createTexture(): WebGLTexture; /** @@ -8400,7 +7978,7 @@ declare module BABYLON { * @returns a InternalTexture for assignment back into BABYLON.Texture */ createTexture(urlArg: Nullable, noMipmap: boolean, invertY: boolean, scene: Nullable, samplingMode?: number, onLoad?: Nullable<() => void>, onError?: Nullable<(message: string, exception: any) => void>, buffer?: Nullable, fallback?: Nullable, format?: Nullable, forcedExtension?: Nullable): InternalTexture; - private _rescaleTexture(source, destination, scene, internalFormat, onComplete); + private _rescaleTexture; /** * Update a raw texture * @param texture defines the texture to update @@ -8469,7 +8047,7 @@ declare module BABYLON { * @param comparisonFunction The comparison function to set, 0 if no comparison required */ updateTextureComparisonFunction(texture: InternalTexture, comparisonFunction: number): void; - private _setupDepthStencilTexture(internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction); + private _setupDepthStencilTexture; /** * Creates a depth stencil texture. * This is only available in WebGL 2 or with the depth texture extension available. @@ -8488,7 +8066,7 @@ declare module BABYLON { * @param options The options defining the texture. * @returns The texture */ - private _createDepthStencilTexture(size, options); + private _createDepthStencilTexture; /** * Creates a depth stencil cube texture. * This is only available in WebGL 2. @@ -8496,7 +8074,7 @@ declare module BABYLON { * @param options The options defining the cube texture. * @returns The cube texture */ - private _createDepthStencilCubeTexture(size, options); + private _createDepthStencilCubeTexture; /** * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture. * @param renderTarget The render target to set the frame buffer for @@ -8520,7 +8098,7 @@ declare module BABYLON { * @returns the cube texture as an InternalTexture */ createMultipleRenderTarget(size: any, options: IMultiRenderTargetOptions): InternalTexture[]; - private _setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height, samples?); + private _setupFramebufferDepthAttachments; /** * Updates the sample count of a render target texture * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets @@ -8653,25 +8231,25 @@ declare module BABYLON { * @returns a new raw 3D texture (stored in an InternalTexture) */ createRawTexture3D(data: Nullable, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression?: Nullable, textureType?: number): InternalTexture; - private _prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode); - private _prepareWebGLTexture(texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode?); - private _convertRGBtoRGBATextureData(rgbData, width, height, textureType); + private _prepareWebGLTextureContinuation; + private _prepareWebGLTexture; + private _convertRGBtoRGBATextureData; /** @hidden */ _releaseFramebufferObjects(texture: InternalTexture): void; /** @hidden */ _releaseTexture(texture: InternalTexture): void; - private setProgram(program); + private setProgram; private _boundUniforms; /** * Binds an effect to the webGL context * @param effect defines the effect to bind */ bindSamplers(effect: Effect): void; - private _moveBoundTextureOnTop(internalTexture); - private _getCorrectTextureChannel(channel, internalTexture); - private _linkTrackers(previous, next); - private _removeDesignatedSlot(internalTexture); - private _activateCurrentTexture(); + private _moveBoundTextureOnTop; + private _getCorrectTextureChannel; + private _linkTrackers; + private _removeDesignatedSlot; + private _activateCurrentTexture; /** @hidden */ protected _bindTextureDirectly(target: number, texture: Nullable, forTextureDataUpdate?: boolean, force?: boolean): boolean; /** @hidden */ @@ -8706,9 +8284,9 @@ declare module BABYLON { * @param texture The render target texture containing the depth stencil texture to apply */ setDepthStencilTexture(channel: number, uniform: Nullable, texture: Nullable): void; - private _bindSamplerUniformToChannel(sourceSlot, destination); - private _getTextureWrapMode(mode); - private _setTexture(channel, texture, isPartOfTextureArray?, depthStencilTexture?); + private _bindSamplerUniformToChannel; + private _getTextureWrapMode; + private _setTexture; /** * Sets an array of texture to the webGL context * @param channel defines the channel where the texture array must be set @@ -8718,8 +8296,8 @@ declare module BABYLON { setTextureArray(channel: number, uniform: Nullable, textures: BaseTexture[]): void; /** @hidden */ _setAnisotropicLevel(target: number, texture: BaseTexture): void; - private _setTextureParameterFloat(target, parameter, value, texture); - private _setTextureParameterInteger(target, parameter, value, texture?); + private _setTextureParameterFloat; + private _setTextureParameterInteger; /** * Reads pixels from the current frame buffer. Please note that this function can be slow * @param x defines the x coordinate of the rectangle where pixels must be read @@ -8784,9 +8362,9 @@ declare module BABYLON { * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen */ /** - * Sets the current loading screen object - * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen - */ + * Sets the current loading screen object + * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen + */ loadingScreen: ILoadingScreen; /** * Sets the current loading screen text @@ -8836,15 +8414,15 @@ declare module BABYLON { * @returns a number representing the delta time in ms */ getDeltaTime(): number; - private _measureFps(); + private _measureFps; /** @hidden */ _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex?: number, level?: number): ArrayBufferView; - private _canRenderToFloatFramebuffer(); - private _canRenderToHalfFloatFramebuffer(); - private _canRenderToFramebuffer(type); + private _canRenderToFloatFramebuffer; + private _canRenderToHalfFloatFramebuffer; + private _canRenderToFramebuffer; /** @hidden */ _getWebGLTextureType(type: number): number; - private _getInternalFormat(format); + private _getInternalFormat; /** @hidden */ _getRGBABufferInternalSizedFormat(type: number, format?: number): number; /** @hidden */ @@ -8853,8 +8431,8 @@ declare module BABYLON { _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, database?: Database, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest; /** @hidden */ _loadFileAsync(url: string, database?: Database, useArrayBuffer?: boolean): Promise; - private _partialLoadFile(url, index, loadedFiles, scene, onfinish, onErrorCallBack?); - private _cascadeLoadFiles(scene, onfinish, files, onError?); + private _partialLoadFile; + private _cascadeLoadFiles; /** * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found) * @returns true if the engine can be created @@ -9030,329 +8608,751 @@ declare var WebGLVertexArrayObject: { new (): WebGLVertexArrayObject; }; -/** - * Module Debug contains the (visual) components to debug a scene correctly - */ -declare module BABYLON.Debug { - /** - * The Axes viewer will show 3 axes in a specific point in space - */ - class AxesViewer { - private _xline; - private _yline; - private _zline; - private _xmesh; - private _ymesh; - private _zmesh; +declare module BABYLON { + class ArcRotateCamera extends TargetCamera { + alpha: number; + beta: number; + radius: number; + protected _target: Vector3; + protected _targetHost: Nullable; + target: Vector3; + inertialAlphaOffset: number; + inertialBetaOffset: number; + inertialRadiusOffset: number; + lowerAlphaLimit: Nullable; + upperAlphaLimit: Nullable; + lowerBetaLimit: number; + upperBetaLimit: number; + lowerRadiusLimit: Nullable; + upperRadiusLimit: Nullable; + inertialPanningX: number; + inertialPanningY: number; + pinchToPanMaxDistance: number; + panningDistanceLimit: Nullable; + panningOriginTarget: Vector3; + panningInertia: number; + angularSensibilityX: number; + angularSensibilityY: number; + pinchPrecision: number; + pinchDeltaPercentage: number; + panningSensibility: number; + keysUp: number[]; + keysDown: number[]; + keysLeft: number[]; + keysRight: number[]; + wheelPrecision: number; + wheelDeltaPercentage: number; + zoomOnFactor: number; + targetScreenOffset: Vector2; + allowUpsideDown: boolean; + _viewMatrix: Matrix; + _useCtrlForPanning: boolean; + _panningMouseButton: number; + inputs: ArcRotateCameraInputsManager; + _reset: () => void; + panningAxis: Vector3; + protected _localDirection: Vector3; + protected _transformedDirection: Vector3; + private _bouncingBehavior; + readonly bouncingBehavior: Nullable; + useBouncingBehavior: boolean; + private _framingBehavior; + readonly framingBehavior: Nullable; + useFramingBehavior: boolean; + private _autoRotationBehavior; + readonly autoRotationBehavior: Nullable; + useAutoRotationBehavior: boolean; + onMeshTargetChangedObservable: Observable>; + onCollide: (collidedMesh: AbstractMesh) => void; + checkCollisions: boolean; + collisionRadius: Vector3; + protected _collider: Collider; + protected _previousPosition: Vector3; + protected _collisionVelocity: Vector3; + protected _newPosition: Vector3; + protected _previousAlpha: number; + protected _previousBeta: number; + protected _previousRadius: number; + protected _collisionTriggered: boolean; + protected _targetBoundingCenter: Nullable; + private _computationVector; + constructor(name: string, alpha: number, beta: number, radius: number, target: Vector3, scene: Scene, setActiveOnSceneIfNoneActive?: boolean); + _initCache(): void; + _updateCache(ignoreParentClass?: boolean): void; + protected _getTargetPosition(): Vector3; /** - * Gets the hosting scene + * Store current camera state (fov, position, etc..) */ - scene: Nullable; + private _storedAlpha; + private _storedBeta; + private _storedRadius; + private _storedTarget; + storeState(): Camera; /** - * Gets or sets a number used to scale line length + * Restored camera state. You must call storeState() first */ - scaleLines: number; + _restoreStateValues(): boolean; + _isSynchronizedViewMatrix(): boolean; + attachControl(element: HTMLElement, noPreventDefault?: boolean, useCtrlForPanning?: boolean, panningMouseButton?: number): void; + detachControl(element: HTMLElement): void; + _checkInputs(): void; + protected _checkLimits(): void; + rebuildAnglesAndRadius(): void; + setPosition(position: Vector3): void; + setTarget(target: AbstractMesh | Vector3, toBoundingCenter?: boolean, allowSamePosition?: boolean): void; + _getViewMatrix(): Matrix; + protected _onCollisionPositionChange: (collisionId: number, newPosition: Vector3, collidedMesh?: Nullable) => void; + zoomOn(meshes?: AbstractMesh[], doNotUpdateMaxZ?: boolean): void; + focusOn(meshesOrMinMaxVectorAndDistance: AbstractMesh[] | { + min: Vector3; + max: Vector3; + distance: number; + }, doNotUpdateMaxZ?: boolean): void; /** - * Creates a new AxesViewer - * @param scene defines the hosting scene - * @param scaleLines defines a number used to scale line length (1 by default) + * @override + * Override Camera.createRigCamera */ - constructor(scene: Scene, scaleLines?: number); + createRigCamera(name: string, cameraIndex: number): Camera; /** - * Force the viewer to update - * @param position defines the position of the viewer - * @param xaxis defines the x axis of the viewer - * @param yaxis defines the y axis of the viewer - * @param zaxis defines the z axis of the viewer + * @override + * Override Camera._updateRigCameras */ - update(position: Vector3, xaxis: Vector3, yaxis: Vector3, zaxis: Vector3): void; - /** Releases resources */ + _updateRigCameras(): void; dispose(): void; + getClassName(): string; } } -declare module BABYLON.Debug { - /** - * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh - * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8 - */ - class BoneAxesViewer extends AxesViewer { +declare module BABYLON { + class ArcRotateCameraInputsManager extends CameraInputsManager { + constructor(camera: ArcRotateCamera); + addMouseWheel(): ArcRotateCameraInputsManager; + addPointers(): ArcRotateCameraInputsManager; + addKeyboard(): ArcRotateCameraInputsManager; + addVRDeviceOrientation(): ArcRotateCameraInputsManager; + } +} + +declare module BABYLON { + class Camera extends Node { + inputs: CameraInputsManager; + private static _PERSPECTIVE_CAMERA; + private static _ORTHOGRAPHIC_CAMERA; + private static _FOVMODE_VERTICAL_FIXED; + private static _FOVMODE_HORIZONTAL_FIXED; + private static _RIG_MODE_NONE; + private static _RIG_MODE_STEREOSCOPIC_ANAGLYPH; + private static _RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL; + private static _RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; + private static _RIG_MODE_STEREOSCOPIC_OVERUNDER; + private static _RIG_MODE_VR; + private static _RIG_MODE_WEBVR; + static readonly PERSPECTIVE_CAMERA: number; + static readonly ORTHOGRAPHIC_CAMERA: number; /** - * Gets or sets the target mesh where to display the axes viewer + * This is the default FOV mode for perspective cameras. + * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum. + * */ - mesh: Nullable; + static readonly FOVMODE_VERTICAL_FIXED: number; /** - * Gets or sets the target bone where to display the axes viewer + * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum. + * */ - bone: Nullable; - /** Gets current position */ - pos: Vector3; - /** Gets direction of X axis */ - xaxis: Vector3; - /** Gets direction of Y axis */ - yaxis: Vector3; - /** Gets direction of Z axis */ - zaxis: Vector3; + static readonly FOVMODE_HORIZONTAL_FIXED: number; + static readonly RIG_MODE_NONE: number; + static readonly RIG_MODE_STEREOSCOPIC_ANAGLYPH: number; + static readonly RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: number; + static readonly RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: number; + static readonly RIG_MODE_STEREOSCOPIC_OVERUNDER: number; + static readonly RIG_MODE_VR: number; + static readonly RIG_MODE_WEBVR: number; + static ForceAttachControlToAlwaysPreventDefault: boolean; + static UseAlternateWebVRRendering: boolean; + position: Vector3; /** - * Creates a new BoneAxesViewer - * @param scene defines the hosting scene - * @param bone defines the target bone - * @param mesh defines the target mesh - * @param scaleLines defines a scaling factor for line length (1 by default) + * The vector the camera should consider as up. + * (default is Vector3(0, 1, 0) aka Vector3.Up()) */ - constructor(scene: Scene, bone: Bone, mesh: Mesh, scaleLines?: number); + upVector: Vector3; + orthoLeft: Nullable; + orthoRight: Nullable; + orthoBottom: Nullable; + orthoTop: Nullable; /** - * Force the viewer to update + * FOV is set in Radians. (default is 0.8) + */ + fov: number; + minZ: number; + maxZ: number; + inertia: number; + mode: number; + isIntermediate: boolean; + viewport: Viewport; + /** + * Restricts the camera to viewing objects with the same layerMask. + * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0 + */ + layerMask: number; + /** + * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED) + */ + fovMode: number; + cameraRigMode: number; + interaxialDistance: number; + isStereoscopicSideBySide: boolean; + _cameraRigParams: any; + _rigCameras: Camera[]; + _rigPostProcess: Nullable; + protected _webvrViewMatrix: Matrix; + _skipRendering: boolean; + _alternateCamera: Camera; + customRenderTargets: RenderTargetTexture[]; + onViewMatrixChangedObservable: Observable; + onProjectionMatrixChangedObservable: Observable; + onAfterCheckInputsObservable: Observable; + onRestoreStateObservable: Observable; + private _computedViewMatrix; + _projectionMatrix: Matrix; + private _doNotComputeProjectionMatrix; + private _worldMatrix; + _postProcesses: Nullable[]; + private _transformMatrix; + _activeMeshes: SmartArray; + protected _globalPosition: Vector3; + private _frustumPlanes; + private _refreshFrustumPlanes; + constructor(name: string, position: Vector3, scene: Scene, setActiveOnSceneIfNoneActive?: boolean); + private _storedFov; + private _stateStored; + /** + * Store current camera state (fov, position, etc..) + */ + storeState(): Camera; + /** + * Restores the camera state values if it has been stored. You must call storeState() first + */ + protected _restoreStateValues(): boolean; + /** + * Restored camera state. You must call storeState() first + */ + restoreState(): boolean; + getClassName(): string; + /** + * @param {boolean} fullDetails - support for multiple levels of logging within scene loading + */ + toString(fullDetails?: boolean): string; + readonly globalPosition: Vector3; + getActiveMeshes(): SmartArray; + isActiveMesh(mesh: Mesh): boolean; + /** + * Is this camera ready to be used/rendered + * @param completeCheck defines if a complete check (including post processes) has to be done (false by default) + * @return true if the camera is ready */ + isReady(completeCheck?: boolean): boolean; + _initCache(): void; + _updateCache(ignoreParentClass?: boolean): void; + _isSynchronized(): boolean; + _isSynchronizedViewMatrix(): boolean; + _isSynchronizedProjectionMatrix(): boolean; + attachControl(element: HTMLElement, noPreventDefault?: boolean): void; + detachControl(element: HTMLElement): void; update(): void; - /** Releases resources */ - dispose(): void; - } -} - -declare module BABYLON { - class DebugLayer { - private _scene; - static InspectorURL: string; - private _inspector; - private BJSINSPECTOR; - onPropertyChangedObservable: Observable<{ - object: any; - property: string; - value: any; - initialValue: any; - }>; - constructor(scene: Scene); - /** Creates the inspector window. */ - private _createInspector(config?); - isVisible(): boolean; - hide(): void; + _checkInputs(): void; + readonly rigCameras: Camera[]; + readonly rigPostProcess: Nullable; /** - * - * Launch the debugLayer. - * - * initialTab: - * | Value | Tab Name | - * | --- | --- | - * | 0 | Scene | - * | 1 | Console | - * | 2 | Stats | - * | 3 | Textures | - * | 4 | Mesh | - * | 5 | Light | - * | 6 | Material | - * | 7 | GLTF | - * | 8 | GUI | - * | 9 | Physics | - * | 10 | Camera | - * | 11 | Audio | - * - */ - show(config?: { - popup?: boolean; - initialTab?: number; - parentElement?: HTMLElement; - newColors?: { - backgroundColor?: string; - backgroundColorLighter?: string; - backgroundColorLighter2?: string; - backgroundColorLighter3?: string; - color?: string; - colorTop?: string; - colorBot?: string; - }; - }): void; + * Internal, gets the first post proces. + * @returns the first post process to be run on this camera. + */ + _getFirstPostProcess(): Nullable; + private _cascadePostProcessesToRigCams; + attachPostProcess(postProcess: PostProcess, insertAt?: Nullable): number; + detachPostProcess(postProcess: PostProcess): void; + getWorldMatrix(): Matrix; + _getViewMatrix(): Matrix; + getViewMatrix(force?: boolean): Matrix; + freezeProjectionMatrix(projection?: Matrix): void; + unfreezeProjectionMatrix(): void; + getProjectionMatrix(force?: boolean): Matrix; /** - * Gets the active tab - * @return the index of the active tab or -1 if the inspector is hidden + * Gets the transformation matrix (ie. the multiplication of view by projection matrices) + * @returns a Matrix */ - getActiveTab(): number; - } -} - -declare module BABYLON.Debug { - /** - * Used to show the physics impostor around the specific mesh - */ - class PhysicsViewer { - /** @hidden */ - protected _impostors: Array>; - /** @hidden */ - protected _meshes: Array>; - /** @hidden */ - protected _scene: Nullable; - /** @hidden */ - protected _numMeshes: number; - /** @hidden */ - protected _physicsEnginePlugin: Nullable; - private _renderFunction; - private _debugBoxMesh; - private _debugSphereMesh; - private _debugMaterial; + getTransformationMatrix(): Matrix; + private updateFrustumPlanes; + isInFrustum(target: ICullable): boolean; + isCompletelyInFrustum(target: ICullable): boolean; + getForwardRay(length?: number, transform?: Matrix, origin?: Vector3): Ray; /** - * Creates a new PhysicsViewer - * @param scene defines the hosting scene + * Releases resources associated with this node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) */ - constructor(scene: Scene); - /** @hidden */ - protected _updateDebugMeshes(): void; + dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; + readonly leftCamera: Nullable; + readonly rightCamera: Nullable; + getLeftTarget(): Nullable; + getRightTarget(): Nullable; + setCameraRigMode(mode: number, rigParams: any): void; + private _getVRProjectionMatrix; + protected _updateCameraRotationMatrix(): void; + protected _updateWebVRCameraRotationMatrix(): void; /** - * Renders a specified physic impostor - * @param impostor defines the impostor to render + * This function MUST be overwritten by the different WebVR cameras available. + * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right. */ - showImpostor(impostor: PhysicsImpostor): void; + protected _getWebVRProjectionMatrix(): Matrix; /** - * Hides a specified physic impostor - * @param impostor defines the impostor to hide + * This function MUST be overwritten by the different WebVR cameras available. + * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right. */ - hideImpostor(impostor: Nullable): void; - private _getDebugMaterial(scene); - private _getDebugBoxMesh(scene); - private _getDebugSphereMesh(scene); - private _getDebugMesh(impostor, scene); - /** Releases all resources */ - dispose(): void; + protected _getWebVRViewMatrix(): Matrix; + setCameraRigParameter(name: string, value: any): void; + /** + * needs to be overridden by children so sub has required properties to be copied + */ + createRigCamera(name: string, cameraIndex: number): Nullable; + /** + * May need to be overridden by children + */ + _updateRigCameras(): void; + _setupInputs(): void; + serialize(): any; + clone(name: string): Camera; + getDirection(localAxis: Vector3): Vector3; + getDirectionToRef(localAxis: Vector3, result: Vector3): void; + static GetConstructorFromName(type: string, name: string, scene: Scene, interaxial_distance?: number, isStereoscopicSideBySide?: boolean): () => Camera; + computeWorldMatrix(): Matrix; + static Parse(parsedCamera: any, scene: Scene): Camera; + } +} + +declare module BABYLON { + var CameraInputTypes: {}; + interface ICameraInput { + camera: Nullable; + getClassName(): string; + getSimpleName(): string; + attachControl: (element: HTMLElement, noPreventDefault?: boolean) => void; + detachControl: (element: Nullable) => void; + checkInputs?: () => void; + } + interface CameraInputsMap { + [name: string]: ICameraInput; + [idx: number]: ICameraInput; + } + class CameraInputsManager { + attached: CameraInputsMap; + attachedElement: Nullable; + noPreventDefault: boolean; + camera: TCamera; + checkInputs: () => void; + constructor(camera: TCamera); + /** + * Add an input method to a camera + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + * @param input camera input method + */ + add(input: ICameraInput): void; + /** + * Remove a specific input method from a camera + * example: camera.inputs.remove(camera.inputs.attached.mouse); + * @param inputToRemove camera input method + */ + remove(inputToRemove: ICameraInput): void; + removeByType(inputType: string): void; + private _addCheckInputs; + attachInput(input: ICameraInput): void; + attachElement(element: HTMLElement, noPreventDefault?: boolean): void; + detachElement(element: HTMLElement, disconnect?: boolean): void; + rebuildInputCheck(): void; + /** + * Remove all attached input methods from a camera + */ + clear(): void; + serialize(serializedCamera: any): void; + parse(parsedCamera: any): void; } } declare module BABYLON { - class RayHelper { - ray: Nullable; - private _renderPoints; - private _renderLine; - private _renderFunction; - private _scene; - private _updateToMeshFunction; - private _attachedToMesh; - private _meshSpaceDirection; - private _meshSpaceOrigin; - static CreateAndShow(ray: Ray, scene: Scene, color: Color3): RayHelper; - constructor(ray: Ray); - show(scene: Scene, color?: Color3): void; - hide(): void; - private _render(); - attachToMesh(mesh: AbstractMesh, meshSpaceDirection?: Vector3, meshSpaceOrigin?: Vector3, length?: number): void; - detachFromMesh(): void; - private _updateToMesh(); - dispose(): void; - } -} - -declare module BABYLON.Debug { /** - * Class used to render a debug view of a given skeleton - * @see http://www.babylonjs-playground.com/#1BZJVJ#8 + * This is a camera specifically designed to react to device orientation events such as a modern mobile device + * being tilted forward or back and left or right. */ - class SkeletonViewer { - /** defines the skeleton to render */ - skeleton: Skeleton; - /** defines the mesh attached to the skeleton */ - mesh: AbstractMesh; - /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */ - autoUpdateBonesMatrices: boolean; - /** defines the rendering group id to use with the viewer */ - renderingGroupId: number; - /** Gets or sets the color used to render the skeleton */ - color: Color3; - private _scene; - private _debugLines; - private _debugMesh; - private _isEnabled; - private _renderFunction; + class DeviceOrientationCamera extends FreeCamera { + private _initialQuaternion; + private _quaternionCache; /** - * Creates a new SkeletonViewer - * @param skeleton defines the skeleton to render - * @param mesh defines the mesh attached to the skeleton - * @param scene defines the hosting scene - * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) - * @param renderingGroupId defines the rendering group id to use with the viewer + * Creates a new device orientation camera + * @param name The name of the camera + * @param position The start position camera + * @param scene The scene the camera belongs to */ - constructor( - /** defines the skeleton to render */ - skeleton: Skeleton, - /** defines the mesh attached to the skeleton */ - mesh: AbstractMesh, scene: Scene, - /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */ - autoUpdateBonesMatrices?: boolean, - /** defines the rendering group id to use with the viewer */ - renderingGroupId?: number); - /** Gets or sets a boolean indicating if the viewer is enabled */ - isEnabled: boolean; - private _getBonePosition(position, bone, meshMat, x?, y?, z?); - private _getLinesForBonesWithLength(bones, meshMat); - private _getLinesForBonesNoLength(bones, meshMat); - /** Update the viewer to sync with current skeleton state */ - update(): void; - /** Release associated resources */ - dispose(): void; + constructor(name: string, position: Vector3, scene: Scene); + /** + * Gets the current instance class name ("DeviceOrientationCamera"). + * This helps avoiding instanceof at run time. + * @returns the class name + */ + getClassName(): string; + /** + * Checks and applies the current values of the inputs to the camera. (Internal use only) + */ + _checkInputs(): void; + /** + * Reset the camera to its default orientation on the specified axis only. + * @param axis The axis to reset + */ + resetToCurrentRotation(axis?: Axis): void; } } declare module BABYLON { - class KeyboardEventTypes { - static _KEYDOWN: number; - static _KEYUP: number; - static readonly KEYDOWN: number; - static readonly KEYUP: number; + class FollowCamera extends TargetCamera { + radius: number; + rotationOffset: number; + heightOffset: number; + cameraAcceleration: number; + maxCameraSpeed: number; + lockedTarget: Nullable; + constructor(name: string, position: Vector3, scene: Scene, lockedTarget?: Nullable); + private getRadians; + private follow; + _checkInputs(): void; + getClassName(): string; } - class KeyboardInfo { - type: number; - event: KeyboardEvent; - constructor(type: number, event: KeyboardEvent); + class ArcFollowCamera extends TargetCamera { + alpha: number; + beta: number; + radius: number; + target: Nullable; + private _cartesianCoordinates; + constructor(name: string, alpha: number, beta: number, radius: number, target: Nullable, scene: Scene); + private follow; + _checkInputs(): void; + getClassName(): string; } - /** - * This class is used to store keyboard related info for the onPreKeyboardObservable event. - * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable - */ - class KeyboardInfoPre extends KeyboardInfo { - constructor(type: number, event: KeyboardEvent); - skipOnPointerObservable: boolean; +} + +declare module BABYLON { + class FreeCamera extends TargetCamera { + ellipsoid: Vector3; + ellipsoidOffset: Vector3; + checkCollisions: boolean; + applyGravity: boolean; + inputs: FreeCameraInputsManager; + /** + * Gets the input sensibility for a mouse input. (default is 2000.0) + * Higher values reduce sensitivity. + */ + /** + * Sets the input sensibility for a mouse input. (default is 2000.0) + * Higher values reduce sensitivity. + */ + angularSensibility: number; + keysUp: number[]; + keysDown: number[]; + keysLeft: number[]; + keysRight: number[]; + onCollide: (collidedMesh: AbstractMesh) => void; + private _collider; + private _needMoveForGravity; + private _oldPosition; + private _diffPosition; + private _newPosition; + _localDirection: Vector3; + _transformedDirection: Vector3; + constructor(name: string, position: Vector3, scene: Scene, setActiveOnSceneIfNoneActive?: boolean); + attachControl(element: HTMLElement, noPreventDefault?: boolean): void; + detachControl(element: HTMLElement): void; + private _collisionMask; + collisionMask: number; + _collideWithWorld(displacement: Vector3): void; + private _onCollisionPositionChange; + _checkInputs(): void; + _decideIfNeedsToMove(): boolean; + _updatePosition(): void; + dispose(): void; + getClassName(): string; } } declare module BABYLON { - class PointerEventTypes { - static _POINTERDOWN: number; - static _POINTERUP: number; - static _POINTERMOVE: number; - static _POINTERWHEEL: number; - static _POINTERPICK: number; - static _POINTERTAP: number; - static _POINTERDOUBLETAP: number; - static readonly POINTERDOWN: number; - static readonly POINTERUP: number; - static readonly POINTERMOVE: number; - static readonly POINTERWHEEL: number; - static readonly POINTERPICK: number; - static readonly POINTERTAP: number; - static readonly POINTERDOUBLETAP: number; + class FreeCameraInputsManager extends CameraInputsManager { + constructor(camera: FreeCamera); + addKeyboard(): FreeCameraInputsManager; + addMouse(touchEnabled?: boolean): FreeCameraInputsManager; + addDeviceOrientation(): FreeCameraInputsManager; + addTouch(): FreeCameraInputsManager; + addVirtualJoystick(): FreeCameraInputsManager; } - class PointerInfoBase { - type: number; - event: PointerEvent | MouseWheelEvent; - constructor(type: number, event: PointerEvent | MouseWheelEvent); +} + +declare module BABYLON { + class GamepadCamera extends UniversalCamera { + gamepadAngularSensibility: number; + gamepadMoveSensibility: number; + constructor(name: string, position: Vector3, scene: Scene); + getClassName(): string; } - /** - * This class is used to store pointer related info for the onPrePointerObservable event. - * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable - */ - class PointerInfoPre extends PointerInfoBase { +} + +declare module BABYLON { + class TargetCamera extends Camera { + cameraDirection: Vector3; + cameraRotation: Vector2; + rotation: Vector3; + rotationQuaternion: Quaternion; + speed: number; + noRotationConstraint: boolean; + lockedTarget: any; + _currentTarget: Vector3; + _viewMatrix: Matrix; + _camMatrix: Matrix; + _cameraTransformMatrix: Matrix; + _cameraRotationMatrix: Matrix; + private _rigCamTransformMatrix; + _referencePoint: Vector3; + private _currentUpVector; + _transformedReferencePoint: Vector3; + protected _globalCurrentTarget: Vector3; + protected _globalCurrentUpVector: Vector3; + _reset: () => void; + constructor(name: string, position: Vector3, scene: Scene, setActiveOnSceneIfNoneActive?: boolean); + getFrontPosition(distance: number): Vector3; + _getLockedTargetPosition(): Nullable; /** - * Ray from a pointer if availible (eg. 6dof controller) + * Store current camera state (fov, position, etc..) */ - ray: Nullable; - constructor(type: number, event: PointerEvent | MouseWheelEvent, localX: number, localY: number); - localPosition: Vector2; - skipOnPointerObservable: boolean; + private _storedPosition; + private _storedRotation; + private _storedRotationQuaternion; + storeState(): Camera; + /** + * Restored camera state. You must call storeState() first + */ + _restoreStateValues(): boolean; + _initCache(): void; + _updateCache(ignoreParentClass?: boolean): void; + _isSynchronizedViewMatrix(): boolean; + _computeLocalCameraSpeed(): number; + setTarget(target: Vector3): void; + /** + * Return the current target position of the camera. This value is expressed in local space. + */ + getTarget(): Vector3; + _decideIfNeedsToMove(): boolean; + _updatePosition(): void; + _checkInputs(): void; + protected _updateCameraRotationMatrix(): void; + _getViewMatrix(): Matrix; + protected _computeViewMatrix(position: Vector3, target: Vector3, up: Vector3): void; + /** + * @override + * Override Camera.createRigCamera + */ + createRigCamera(name: string, cameraIndex: number): Nullable; + /** + * @override + * Override Camera._updateRigCameras + */ + _updateRigCameras(): void; + private _getRigCamPosition; + getClassName(): string; + } +} + +declare module BABYLON { + class TouchCamera extends FreeCamera { + touchAngularSensibility: number; + touchMoveSensibility: number; + constructor(name: string, position: Vector3, scene: Scene); + getClassName(): string; + _setupInputs(): void; + } +} + +declare module BABYLON { + class UniversalCamera extends TouchCamera { + gamepadAngularSensibility: number; + gamepadMoveSensibility: number; + constructor(name: string, position: Vector3, scene: Scene); + getClassName(): string; + } +} + +declare module BABYLON { + class VirtualJoysticksCamera extends FreeCamera { + constructor(name: string, position: Vector3, scene: Scene); + getClassName(): string; } +} + +interface VRDisplay extends EventTarget { /** - * This type contains all the data related to a pointer event in Babylon.js. - * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class. + * Dictionary of capabilities describing the VRDisplay. */ - class PointerInfo extends PointerInfoBase { - pickInfo: Nullable; - constructor(type: number, event: PointerEvent | MouseWheelEvent, pickInfo: Nullable); - } + readonly capabilities: VRDisplayCapabilities; + /** + * z-depth defining the far plane of the eye view frustum + * enables mapping of values in the render target depth + * attachment to scene coordinates. Initially set to 10000.0. + */ + depthFar: number; + /** + * z-depth defining the near plane of the eye view frustum + * enables mapping of values in the render target depth + * attachment to scene coordinates. Initially set to 0.01. + */ + depthNear: number; + /** + * An identifier for this distinct VRDisplay. Used as an + * association point in the Gamepad API. + */ + readonly displayId: number; + /** + * A display name, a user-readable name identifying it. + */ + readonly displayName: string; + readonly isConnected: boolean; + readonly isPresenting: boolean; + /** + * If this VRDisplay supports room-scale experiences, the optional + * stage attribute contains details on the room-scale parameters. + */ + readonly stageParameters: VRStageParameters | null; + /** + * Passing the value returned by `requestAnimationFrame` to + * `cancelAnimationFrame` will unregister the callback. + */ + cancelAnimationFrame(handle: number): void; + /** + * Stops presenting to the VRDisplay. + */ + exitPresent(): Promise; + getEyeParameters(whichEye: string): VREyeParameters; + /** + * Populates the passed VRFrameData with the information required to render + * the current frame. + */ + getFrameData(frameData: VRFrameData): boolean; + /** + * Get the layers currently being presented. + */ + getLayers(): VRLayer[]; + /** + * Return a VRPose containing the future predicted pose of the VRDisplay + * when the current frame will be presented. The value returned will not + * change until JavaScript has returned control to the browser. + * + * The VRPose will contain the position, orientation, velocity, + * and acceleration of each of these properties. + */ + getPose(): VRPose; + /** + * Return the current instantaneous pose of the VRDisplay, with no + * prediction applied. + */ + getImmediatePose(): VRPose; + /** + * The callback passed to `requestAnimationFrame` will be called + * any time a new frame should be rendered. When the VRDisplay is + * presenting the callback will be called at the native refresh + * rate of the HMD. When not presenting this function acts + * identically to how window.requestAnimationFrame acts. Content should + * make no assumptions of frame rate or vsync behavior as the HMD runs + * asynchronously from other displays and at differing refresh rates. + */ + requestAnimationFrame(callback: FrameRequestCallback): number; + /** + * Begin presenting to the VRDisplay. Must be called in response to a user gesture. + * Repeat calls while already presenting will update the VRLayers being displayed. + */ + requestPresent(layers: VRLayer[]): Promise; + /** + * Reset the pose for this display, treating its current position and + * orientation as the "origin/zero" values. VRPose.position, + * VRPose.orientation, and VRStageParameters.sittingToStandingTransform may be + * updated when calling resetPose(). This should be called in only + * sitting-space experiences. + */ + resetPose(): void; + /** + * The VRLayer provided to the VRDisplay will be captured and presented + * in the HMD. Calling this function has the same effect on the source + * canvas as any other operation that uses its source image, and canvases + * created without preserveDrawingBuffer set to true will be cleared. + */ + submitFrame(pose?: VRPose): void; +} +declare var VRDisplay: { + prototype: VRDisplay; + new (): VRDisplay; +}; +interface VRLayer { + leftBounds?: number[] | null; + rightBounds?: number[] | null; + source?: HTMLCanvasElement | null; +} +interface VRDisplayCapabilities { + readonly canPresent: boolean; + readonly hasExternalDisplay: boolean; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly maxLayers: number; +} +interface VREyeParameters { + /** @deprecated */ + readonly fieldOfView: VRFieldOfView; + readonly offset: Float32Array; + readonly renderHeight: number; + readonly renderWidth: number; +} +interface VRFieldOfView { + readonly downDegrees: number; + readonly leftDegrees: number; + readonly rightDegrees: number; + readonly upDegrees: number; +} +interface VRFrameData { + readonly leftProjectionMatrix: Float32Array; + readonly leftViewMatrix: Float32Array; + readonly pose: VRPose; + readonly rightProjectionMatrix: Float32Array; + readonly rightViewMatrix: Float32Array; + readonly timestamp: number; +} +interface VRPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; + readonly timestamp: number; +} +interface VRStageParameters { + sittingToStandingTransform?: Float32Array; + sizeX?: number; + sizeY?: number; +} +interface Navigator { + getVRDisplays(): Promise; + readonly activeVRDisplays: ReadonlyArray; +} +interface Window { + onvrdisplayconnected: ((this: Window, ev: Event) => any) | null; + onvrdisplaydisconnected: ((this: Window, ev: Event) => any) | null; + onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; + addEventListener(type: "vrdisplayconnected", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "vrdisplaydisconnected", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "vrdisplaypresentchange", listener: (ev: Event) => any, useCapture?: boolean): void; +} +interface Gamepad { + readonly displayId: number; } declare module BABYLON { @@ -9404,7 +9404,7 @@ declare module BABYLON { onbuttondown(callback: (buttonPressed: number) => void): void; onbuttonup(callback: (buttonReleased: number) => void): void; constructor(id: string, index: number, browserGamepad: any); - private _setButtonValue(newValue, currentValue, buttonIndex); + private _setButtonValue; update(): void; dispose(): void; } @@ -9412,7 +9412,7 @@ declare module BABYLON { declare module BABYLON { class GamepadManager { - private _scene; + private _scene?; private _babylonGamepads; private _oneGamepadConnected; _isMonitoring: boolean; @@ -9426,11 +9426,11 @@ declare module BABYLON { readonly gamepads: Gamepad[]; getGamepadByType(type?: number): Nullable; dispose(): void; - private _addNewGamepad(gamepad); - private _startMonitoringGamepads(); - private _stopMonitoringGamepads(); + private _addNewGamepad; + private _startMonitoringGamepads; + private _stopMonitoringGamepads; _checkGamepadsStatus(): void; - private _updateGamepadObjects(); + private _updateGamepadObjects; } } @@ -9480,7 +9480,7 @@ declare module BABYLON { * Disposes the component and the associated ressources */ dispose(): void; - private _beforeCameraUpdate(); + private _beforeCameraUpdate; } } @@ -9508,7 +9508,7 @@ declare module BABYLON { /** Left stick */ LeftStick = 8, /** Right stick */ - RightStick = 9, + RightStick = 9 } /** Defines values for XBox360 DPad */ enum Xbox360Dpad { @@ -9519,7 +9519,7 @@ declare module BABYLON { /** Left */ Left = 2, /** Right */ - Right = 3, + Right = 3 } /** * Defines a XBox360 gamepad @@ -9602,8 +9602,8 @@ declare module BABYLON { * @param callback defines the callback to use */ ondpadup(callback: (dPadReleased: Xbox360Dpad) => void): void; - private _setButtonValue(newValue, currentValue, buttonType); - private _setDPadValue(newValue, currentValue, buttonType); + private _setButtonValue; + private _setDPadValue; /** Gets or sets value of A button */ buttonA: number; /** Gets or sets value of B button */ @@ -9642,221 +9642,409 @@ declare module BABYLON { declare module BABYLON { /** - * This class can be used to get instrumentation data from a Babylon engine + * Represents the different options available during the creation of + * a Environment helper. + * + * This can control the default ground, skybox and image processing setup of your scene. */ - class EngineInstrumentation implements IDisposable { - engine: Engine; - private _captureGPUFrameTime; - private _gpuFrameTimeToken; - private _gpuFrameTime; - private _captureShaderCompilationTime; - private _shaderCompilationTime; - private _onBeginFrameObserver; - private _onEndFrameObserver; - private _onBeforeShaderCompilationObserver; - private _onAfterShaderCompilationObserver; + interface IEnvironmentHelperOptions { /** - * Gets the perf counter used for GPU frame time + * Specifies wether or not to create a ground. + * True by default. */ - readonly gpuFrameTimeCounter: PerfCounter; + createGround: boolean; /** - * Gets the GPU frame time capture status + * Specifies the ground size. + * 15 by default. */ + groundSize: number; /** - * Enable or disable the GPU frame time capture + * The texture used on the ground for the main color. + * Comes from the BabylonJS CDN by default. + * + * Remarks: Can be either a texture or a url. */ - captureGPUFrameTime: boolean; + groundTexture: string | BaseTexture; /** - * Gets the perf counter used for shader compilation time - */ - readonly shaderCompilationTimeCounter: PerfCounter; + * The color mixed in the ground texture by default. + * BabylonJS clearColor by default. + */ + groundColor: Color3; /** - * Gets the shader compilation time capture status + * Specifies the ground opacity. + * 1 by default. */ + groundOpacity: number; /** - * Enable or disable the shader compilation time capture + * Enables the ground to receive shadows. + * True by default. */ - captureShaderCompilationTime: boolean; - constructor(engine: Engine); - dispose(): void; + enableGroundShadow: boolean; + /** + * Helps preventing the shadow to be fully black on the ground. + * 0.5 by default. + */ + groundShadowLevel: number; + /** + * Creates a mirror texture attach to the ground. + * false by default. + */ + enableGroundMirror: boolean; + /** + * Specifies the ground mirror size ratio. + * 0.3 by default as the default kernel is 64. + */ + groundMirrorSizeRatio: number; + /** + * Specifies the ground mirror blur kernel size. + * 64 by default. + */ + groundMirrorBlurKernel: number; + /** + * Specifies the ground mirror visibility amount. + * 1 by default + */ + groundMirrorAmount: number; + /** + * Specifies the ground mirror reflectance weight. + * This uses the standard weight of the background material to setup the fresnel effect + * of the mirror. + * 1 by default. + */ + groundMirrorFresnelWeight: number; + /** + * Specifies the ground mirror Falloff distance. + * This can helps reducing the size of the reflection. + * 0 by Default. + */ + groundMirrorFallOffDistance: number; + /** + * Specifies the ground mirror texture type. + * Unsigned Int by Default. + */ + groundMirrorTextureType: number; + /** + * Specifies a bias applied to the ground vertical position to prevent z-fighting with + * the shown objects. + */ + groundYBias: number; + /** + * Specifies wether or not to create a skybox. + * True by default. + */ + createSkybox: boolean; + /** + * Specifies the skybox size. + * 20 by default. + */ + skyboxSize: number; + /** + * The texture used on the skybox for the main color. + * Comes from the BabylonJS CDN by default. + * + * Remarks: Can be either a texture or a url. + */ + skyboxTexture: string | BaseTexture; + /** + * The color mixed in the skybox texture by default. + * BabylonJS clearColor by default. + */ + skyboxColor: Color3; + /** + * The background rotation around the Y axis of the scene. + * This helps aligning the key lights of your scene with the background. + * 0 by default. + */ + backgroundYRotation: number; + /** + * Compute automatically the size of the elements to best fit with the scene. + */ + sizeAuto: boolean; + /** + * Default position of the rootMesh if autoSize is not true. + */ + rootPosition: Vector3; + /** + * Sets up the image processing in the scene. + * true by default. + */ + setupImageProcessing: boolean; + /** + * The texture used as your environment texture in the scene. + * Comes from the BabylonJS CDN by default and in use if setupImageProcessing is true. + * + * Remarks: Can be either a texture or a url. + */ + environmentTexture: string | BaseTexture; + /** + * The value of the exposure to apply to the scene. + * 0.6 by default if setupImageProcessing is true. + */ + cameraExposure: number; + /** + * The value of the contrast to apply to the scene. + * 1.6 by default if setupImageProcessing is true. + */ + cameraContrast: number; + /** + * Specifies wether or not tonemapping should be enabled in the scene. + * true by default if setupImageProcessing is true. + */ + toneMappingEnabled: boolean; } -} - -declare module BABYLON { /** - * This class can be used to get instrumentation data from a Babylon engine + * The Environment helper class can be used to add a fully featuread none expensive background to your scene. + * It includes by default a skybox and a ground relying on the BackgroundMaterial. + * It also helps with the default setup of your imageProcessing configuration. */ - class SceneInstrumentation implements IDisposable { - scene: Scene; - private _captureActiveMeshesEvaluationTime; - private _activeMeshesEvaluationTime; - private _captureRenderTargetsRenderTime; - private _renderTargetsRenderTime; - private _captureFrameTime; - private _frameTime; - private _captureRenderTime; - private _renderTime; - private _captureInterFrameTime; - private _interFrameTime; - private _captureParticlesRenderTime; - private _particlesRenderTime; - private _captureSpritesRenderTime; - private _spritesRenderTime; - private _capturePhysicsTime; - private _physicsTime; - private _captureAnimationsTime; - private _animationsTime; - private _captureCameraRenderTime; - private _cameraRenderTime; - private _onBeforeActiveMeshesEvaluationObserver; - private _onAfterActiveMeshesEvaluationObserver; - private _onBeforeRenderTargetsRenderObserver; - private _onAfterRenderTargetsRenderObserver; - private _onAfterRenderObserver; - private _onBeforeDrawPhaseObserver; - private _onAfterDrawPhaseObserver; - private _onBeforeAnimationsObserver; - private _onBeforeParticlesRenderingObserver; - private _onAfterParticlesRenderingObserver; - private _onBeforeSpritesRenderingObserver; - private _onAfterSpritesRenderingObserver; - private _onBeforePhysicsObserver; - private _onAfterPhysicsObserver; - private _onAfterAnimationsObserver; - private _onBeforeCameraRenderObserver; - private _onAfterCameraRenderObserver; + class EnvironmentHelper { /** - * Gets the perf counter used for active meshes evaluation time + * Default ground texture URL. */ - readonly activeMeshesEvaluationTimeCounter: PerfCounter; + private static _groundTextureCDNUrl; /** - * Gets the active meshes evaluation time capture status + * Default skybox texture URL. */ + private static _skyboxTextureCDNUrl; /** - * Enable or disable the active meshes evaluation time capture + * Default environment texture URL. */ - captureActiveMeshesEvaluationTime: boolean; + private static _environmentTextureCDNUrl; /** - * Gets the perf counter used for render targets render time + * Creates the default options for the helper. */ - readonly renderTargetsRenderTimeCounter: PerfCounter; + private static _getDefaultOptions; + private _rootMesh; /** - * Gets the render targets render time capture status + * Gets the root mesh created by the helper. */ + readonly rootMesh: Mesh; + private _skybox; /** - * Enable or disable the render targets render time capture + * Gets the skybox created by the helper. */ - captureRenderTargetsRenderTime: boolean; + readonly skybox: Nullable; + private _skyboxTexture; /** - * Gets the perf counter used for particles render time + * Gets the skybox texture created by the helper. */ - readonly particlesRenderTimeCounter: PerfCounter; + readonly skyboxTexture: Nullable; + private _skyboxMaterial; /** - * Gets the particles render time capture status + * Gets the skybox material created by the helper. */ + readonly skyboxMaterial: Nullable; + private _ground; /** - * Enable or disable the particles render time capture + * Gets the ground mesh created by the helper. */ - captureParticlesRenderTime: boolean; + readonly ground: Nullable; + private _groundTexture; /** - * Gets the perf counter used for sprites render time + * Gets the ground texture created by the helper. */ - readonly spritesRenderTimeCounter: PerfCounter; + readonly groundTexture: Nullable; + private _groundMirror; /** - * Gets the sprites render time capture status + * Gets the ground mirror created by the helper. */ + readonly groundMirror: Nullable; /** - * Enable or disable the sprites render time capture + * Gets the ground mirror render list to helps pushing the meshes + * you wish in the ground reflection. */ - captureSpritesRenderTime: boolean; + readonly groundMirrorRenderList: Nullable; + private _groundMaterial; /** - * Gets the perf counter used for physics time + * Gets the ground material created by the helper. */ - readonly physicsTimeCounter: PerfCounter; + readonly groundMaterial: Nullable; /** - * Gets the physics time capture status + * Stores the creation options. */ + private readonly _scene; + private _options; /** - * Enable or disable the physics time capture + * This observable will be notified with any error during the creation of the environment, + * mainly texture creation errors. */ - capturePhysicsTime: boolean; + onErrorObservable: Observable<{ + message?: string; + exception?: any; + }>; /** - * Gets the perf counter used for animations time + * constructor + * @param options + * @param scene The scene to add the material to */ - readonly animationsTimeCounter: PerfCounter; + constructor(options: Partial, scene: Scene); /** - * Gets the animations time capture status + * Updates the background according to the new options + * @param options */ + updateOptions(options: Partial): void; /** - * Enable or disable the animations time capture + * Sets the primary color of all the available elements. + * @param color the main color to affect to the ground and the background */ - captureAnimationsTime: boolean; + setMainColor(color: Color3): void; /** - * Gets the perf counter used for frame time capture + * Setup the image processing according to the specified options. */ - readonly frameTimeCounter: PerfCounter; + private _setupImageProcessing; /** - * Gets the frame time capture status + * Setup the environment texture according to the specified options. + */ + private _setupEnvironmentTexture; + /** + * Setup the background according to the specified options. */ + private _setupBackground; /** - * Enable or disable the frame time capture + * Get the scene sizes according to the setup. */ - captureFrameTime: boolean; + private _getSceneSize; /** - * Gets the perf counter used for inter-frames time capture + * Setup the ground according to the specified options. */ - readonly interFrameTimeCounter: PerfCounter; + private _setupGround; /** - * Gets the inter-frames time capture status + * Setup the ground material according to the specified options. */ + private _setupGroundMaterial; /** - * Enable or disable the inter-frames time capture + * Setup the ground diffuse texture according to the specified options. */ - captureInterFrameTime: boolean; + private _setupGroundDiffuseTexture; /** - * Gets the perf counter used for render time capture + * Setup the ground mirror texture according to the specified options. */ - readonly renderTimeCounter: PerfCounter; + private _setupGroundMirrorTexture; /** - * Gets the render time capture status + * Setup the ground to receive the mirror texture. */ + private _setupMirrorInGroundMaterial; /** - * Enable or disable the render time capture + * Setup the skybox according to the specified options. */ - captureRenderTime: boolean; + private _setupSkybox; /** - * Gets the perf counter used for camera render time capture + * Setup the skybox material according to the specified options. */ - readonly cameraRenderTimeCounter: PerfCounter; + private _setupSkyboxMaterial; /** - * Gets the camera render time capture status + * Setup the skybox reflection texture according to the specified options. */ + private _setupSkyboxReflectionTexture; + private _errorHandler; /** - * Enable or disable the camera render time capture + * Dispose all the elements created by the Helper. */ - captureCameraRenderTime: boolean; + dispose(): void; + } +} + +declare module BABYLON { + /** + * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes. + * As a subclass of Node, this allow parenting to the camera with different locations in the scene. + * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere. + * Potential additions to this helper include zoom and and non-infinite distance rendering effects. + */ + class PhotoDome extends Node { + private _useDirectMapping; /** - * Gets the perf counter used for draw calls + * The texture being displayed on the sphere */ - readonly drawCallsCounter: PerfCounter; + protected _photoTexture: Texture; /** - * Gets the perf counter used for texture collisions + * Gets or sets the texture being displayed on the sphere */ - readonly textureCollisionsCounter: PerfCounter; - constructor(scene: Scene); - dispose(): void; + photoTexture: Texture; + /** + * The skybox material + */ + protected _material: BackgroundMaterial; + /** + * The surface used for the skybox + */ + protected _mesh: Mesh; + /** + * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". + * Also see the options.resolution property. + */ + fovMultiplier: number; + /** + * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh. + * @param name Element's name, child elements will append suffixes for their own names. + * @param urlsOfPhoto define the url of the photo to display + * @param options An object containing optional or exposed sub element properties + */ + constructor(name: string, urlOfPhoto: string, options: { + resolution?: number; + size?: number; + useDirectMapping?: boolean; + }, scene: Scene); + /** + * Releases resources associated with this node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; } } declare module BABYLON { /** - * @hidden - **/ - class _TimeToken { - _startTimeQuery: Nullable; - _endTimeQuery: Nullable; - _timeElapsedQuery: Nullable; - _timeElapsedQueryEnded: boolean; + * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes. + * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene. + * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere. + * Potential additions to this helper include zoom and and non-infinite distance rendering effects. + */ + class VideoDome extends Node { + private _useDirectMapping; + /** + * The video texture being displayed on the sphere + */ + protected _videoTexture: VideoTexture; + /** + * Gets the video texture being displayed on the sphere + */ + readonly videoTexture: VideoTexture; + /** + * The skybox material + */ + protected _material: BackgroundMaterial; + /** + * The surface used for the skybox + */ + protected _mesh: Mesh; + /** + * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". + * Also see the options.resolution property. + */ + fovMultiplier: number; + /** + * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh. + * @param name Element's name, child elements will append suffixes for their own names. + * @param urlsOrVideo defines the url(s) or the video element to use + * @param options An object containing optional or exposed sub element properties + */ + constructor(name: string, urlsOrVideo: string | string[] | HTMLVideoElement, options: { + resolution?: number; + clickToPlay?: boolean; + autoPlay?: boolean; + loop?: boolean; + size?: number; + poster?: string; + useDirectMapping?: boolean; + }, scene: Scene); + /** + * Releases resources associated with this node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; } } @@ -9983,8 +10171,8 @@ declare module BABYLON { */ constructor(color?: Color3, gizmoLayer?: UtilityLayerRenderer); protected _attachedMeshChanged(value: Nullable): void; - private _selectNode(selectedMesh); - private _recurseComputeWorld(mesh); + private _selectNode; + private _recurseComputeWorld; /** * Updates the bounding box information for the Gizmo */ @@ -10017,7 +10205,8 @@ declare module BABYLON { * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc. */ class Gizmo implements IDisposable { - /** The utility layer the gizmo will be added to */ gizmoLayer: UtilityLayerRenderer; + /** The utility layer the gizmo will be added to */ + gizmoLayer: UtilityLayerRenderer; /** * The root mesh of the gizmo */ @@ -10058,7 +10247,9 @@ declare module BABYLON { * Creates a gizmo * @param gizmoLayer The utility layer the gizmo will be added to */ - constructor(/** The utility layer the gizmo will be added to */ gizmoLayer?: UtilityLayerRenderer); + constructor( + /** The utility layer the gizmo will be added to */ + gizmoLayer?: UtilityLayerRenderer); private _tempVector; /** * @hidden @@ -10275,494 +10466,489 @@ declare module BABYLON { declare module BABYLON { /** - * Represents the different options available during the creation of - * a Environment helper. - * - * This can control the default ground, skybox and image processing setup of your scene. + * This class can be used to get instrumentation data from a Babylon engine */ - interface IEnvironmentHelperOptions { + class EngineInstrumentation implements IDisposable { + engine: Engine; + private _captureGPUFrameTime; + private _gpuFrameTimeToken; + private _gpuFrameTime; + private _captureShaderCompilationTime; + private _shaderCompilationTime; + private _onBeginFrameObserver; + private _onEndFrameObserver; + private _onBeforeShaderCompilationObserver; + private _onAfterShaderCompilationObserver; /** - * Specifies wether or not to create a ground. - * True by default. + * Gets the perf counter used for GPU frame time */ - createGround: boolean; + readonly gpuFrameTimeCounter: PerfCounter; /** - * Specifies the ground size. - * 15 by default. + * Gets the GPU frame time capture status */ - groundSize: number; /** - * The texture used on the ground for the main color. - * Comes from the BabylonJS CDN by default. - * - * Remarks: Can be either a texture or a url. - */ - groundTexture: string | BaseTexture; + * Enable or disable the GPU frame time capture + */ + captureGPUFrameTime: boolean; /** - * The color mixed in the ground texture by default. - * BabylonJS clearColor by default. + * Gets the perf counter used for shader compilation time */ - groundColor: Color3; + readonly shaderCompilationTimeCounter: PerfCounter; /** - * Specifies the ground opacity. - * 1 by default. + * Gets the shader compilation time capture status */ - groundOpacity: number; /** - * Enables the ground to receive shadows. - * True by default. - */ - enableGroundShadow: boolean; + * Enable or disable the shader compilation time capture + */ + captureShaderCompilationTime: boolean; + constructor(engine: Engine); + dispose(): void; + } +} + +declare module BABYLON { + /** + * This class can be used to get instrumentation data from a Babylon engine + */ + class SceneInstrumentation implements IDisposable { + scene: Scene; + private _captureActiveMeshesEvaluationTime; + private _activeMeshesEvaluationTime; + private _captureRenderTargetsRenderTime; + private _renderTargetsRenderTime; + private _captureFrameTime; + private _frameTime; + private _captureRenderTime; + private _renderTime; + private _captureInterFrameTime; + private _interFrameTime; + private _captureParticlesRenderTime; + private _particlesRenderTime; + private _captureSpritesRenderTime; + private _spritesRenderTime; + private _capturePhysicsTime; + private _physicsTime; + private _captureAnimationsTime; + private _animationsTime; + private _captureCameraRenderTime; + private _cameraRenderTime; + private _onBeforeActiveMeshesEvaluationObserver; + private _onAfterActiveMeshesEvaluationObserver; + private _onBeforeRenderTargetsRenderObserver; + private _onAfterRenderTargetsRenderObserver; + private _onAfterRenderObserver; + private _onBeforeDrawPhaseObserver; + private _onAfterDrawPhaseObserver; + private _onBeforeAnimationsObserver; + private _onBeforeParticlesRenderingObserver; + private _onAfterParticlesRenderingObserver; + private _onBeforeSpritesRenderingObserver; + private _onAfterSpritesRenderingObserver; + private _onBeforePhysicsObserver; + private _onAfterPhysicsObserver; + private _onAfterAnimationsObserver; + private _onBeforeCameraRenderObserver; + private _onAfterCameraRenderObserver; /** - * Helps preventing the shadow to be fully black on the ground. - * 0.5 by default. + * Gets the perf counter used for active meshes evaluation time */ - groundShadowLevel: number; + readonly activeMeshesEvaluationTimeCounter: PerfCounter; /** - * Creates a mirror texture attach to the ground. - * false by default. + * Gets the active meshes evaluation time capture status */ - enableGroundMirror: boolean; /** - * Specifies the ground mirror size ratio. - * 0.3 by default as the default kernel is 64. - */ - groundMirrorSizeRatio: number; + * Enable or disable the active meshes evaluation time capture + */ + captureActiveMeshesEvaluationTime: boolean; /** - * Specifies the ground mirror blur kernel size. - * 64 by default. + * Gets the perf counter used for render targets render time */ - groundMirrorBlurKernel: number; + readonly renderTargetsRenderTimeCounter: PerfCounter; /** - * Specifies the ground mirror visibility amount. - * 1 by default + * Gets the render targets render time capture status */ - groundMirrorAmount: number; /** - * Specifies the ground mirror reflectance weight. - * This uses the standard weight of the background material to setup the fresnel effect - * of the mirror. - * 1 by default. - */ - groundMirrorFresnelWeight: number; + * Enable or disable the render targets render time capture + */ + captureRenderTargetsRenderTime: boolean; /** - * Specifies the ground mirror Falloff distance. - * This can helps reducing the size of the reflection. - * 0 by Default. + * Gets the perf counter used for particles render time */ - groundMirrorFallOffDistance: number; + readonly particlesRenderTimeCounter: PerfCounter; /** - * Specifies the ground mirror texture type. - * Unsigned Int by Default. + * Gets the particles render time capture status */ - groundMirrorTextureType: number; /** - * Specifies a bias applied to the ground vertical position to prevent z-fighting with - * the shown objects. - */ - groundYBias: number; + * Enable or disable the particles render time capture + */ + captureParticlesRenderTime: boolean; /** - * Specifies wether or not to create a skybox. - * True by default. + * Gets the perf counter used for sprites render time */ - createSkybox: boolean; + readonly spritesRenderTimeCounter: PerfCounter; /** - * Specifies the skybox size. - * 20 by default. + * Gets the sprites render time capture status */ - skyboxSize: number; /** - * The texture used on the skybox for the main color. - * Comes from the BabylonJS CDN by default. - * - * Remarks: Can be either a texture or a url. - */ - skyboxTexture: string | BaseTexture; + * Enable or disable the sprites render time capture + */ + captureSpritesRenderTime: boolean; /** - * The color mixed in the skybox texture by default. - * BabylonJS clearColor by default. + * Gets the perf counter used for physics time */ - skyboxColor: Color3; + readonly physicsTimeCounter: PerfCounter; /** - * The background rotation around the Y axis of the scene. - * This helps aligning the key lights of your scene with the background. - * 0 by default. + * Gets the physics time capture status */ - backgroundYRotation: number; /** - * Compute automatically the size of the elements to best fit with the scene. + * Enable or disable the physics time capture + */ + capturePhysicsTime: boolean; + /** + * Gets the perf counter used for animations time */ - sizeAuto: boolean; + readonly animationsTimeCounter: PerfCounter; /** - * Default position of the rootMesh if autoSize is not true. + * Gets the animations time capture status */ - rootPosition: Vector3; /** - * Sets up the image processing in the scene. - * true by default. + * Enable or disable the animations time capture + */ + captureAnimationsTime: boolean; + /** + * Gets the perf counter used for frame time capture */ - setupImageProcessing: boolean; + readonly frameTimeCounter: PerfCounter; /** - * The texture used as your environment texture in the scene. - * Comes from the BabylonJS CDN by default and in use if setupImageProcessing is true. - * - * Remarks: Can be either a texture or a url. + * Gets the frame time capture status */ - environmentTexture: string | BaseTexture; /** - * The value of the exposure to apply to the scene. - * 0.6 by default if setupImageProcessing is true. + * Enable or disable the frame time capture + */ + captureFrameTime: boolean; + /** + * Gets the perf counter used for inter-frames time capture */ - cameraExposure: number; + readonly interFrameTimeCounter: PerfCounter; /** - * The value of the contrast to apply to the scene. - * 1.6 by default if setupImageProcessing is true. + * Gets the inter-frames time capture status */ - cameraContrast: number; /** - * Specifies wether or not tonemapping should be enabled in the scene. - * true by default if setupImageProcessing is true. + * Enable or disable the inter-frames time capture + */ + captureInterFrameTime: boolean; + /** + * Gets the perf counter used for render time capture */ - toneMappingEnabled: boolean; - } - /** - * The Environment helper class can be used to add a fully featuread none expensive background to your scene. - * It includes by default a skybox and a ground relying on the BackgroundMaterial. - * It also helps with the default setup of your imageProcessing configuration. - */ - class EnvironmentHelper { + readonly renderTimeCounter: PerfCounter; /** - * Default ground texture URL. + * Gets the render time capture status */ - private static _groundTextureCDNUrl; /** - * Default skybox texture URL. + * Enable or disable the render time capture + */ + captureRenderTime: boolean; + /** + * Gets the perf counter used for camera render time capture */ - private static _skyboxTextureCDNUrl; + readonly cameraRenderTimeCounter: PerfCounter; /** - * Default environment texture URL. + * Gets the camera render time capture status */ - private static _environmentTextureCDNUrl; /** - * Creates the default options for the helper. + * Enable or disable the camera render time capture + */ + captureCameraRenderTime: boolean; + /** + * Gets the perf counter used for draw calls */ - private static _getDefaultOptions(); - private _rootMesh; + readonly drawCallsCounter: PerfCounter; /** - * Gets the root mesh created by the helper. + * Gets the perf counter used for texture collisions */ - readonly rootMesh: Mesh; - private _skybox; + readonly textureCollisionsCounter: PerfCounter; + constructor(scene: Scene); + dispose(): void; + } +} + +declare module BABYLON { + /** + * @hidden + **/ + class _TimeToken { + _startTimeQuery: Nullable; + _endTimeQuery: Nullable; + _timeElapsedQuery: Nullable; + _timeElapsedQueryEnded: boolean; + } +} + +declare module BABYLON { + /** + * Effect layer options. This helps customizing the behaviour + * of the effect layer. + */ + interface IEffectLayerOptions { /** - * Gets the skybox created by the helper. + * Multiplication factor apply to the canvas size to compute the render target size + * used to generated the objects (the smaller the faster). */ - readonly skybox: Nullable; - private _skyboxTexture; + mainTextureRatio: number; /** - * Gets the skybox texture created by the helper. + * Enforces a fixed size texture to ensure effect stability across devices. */ - readonly skyboxTexture: Nullable; - private _skyboxMaterial; + mainTextureFixedSize?: number; /** - * Gets the skybox material created by the helper. + * Alpha blending mode used to apply the blur. Default depends of the implementation. */ - readonly skyboxMaterial: Nullable; - private _ground; + alphaBlendingMode: number; /** - * Gets the ground mesh created by the helper. + * The camera attached to the layer. */ - readonly ground: Nullable; - private _groundTexture; + camera: Nullable; /** - * Gets the ground texture created by the helper. + * The rendering group to draw the layer in. */ - readonly groundTexture: Nullable; - private _groundMirror; + renderingGroupId: number; + } + /** + * The effect layer Helps adding post process effect blended with the main pass. + * + * This can be for instance use to generate glow or higlight effects on the scene. + * + * The effect layer class can not be used directly and is intented to inherited from to be + * customized per effects. + */ + abstract class EffectLayer { + private _vertexBuffers; + private _indexBuffer; + private _cachedDefines; + private _effectLayerMapGenerationEffect; + private _effectLayerOptions; + private _mergeEffect; + protected _scene: Scene; + protected _engine: Engine; + protected _maxSize: number; + protected _mainTextureDesiredSize: ISize; + protected _mainTexture: RenderTargetTexture; + protected _shouldRender: boolean; + protected _postProcesses: PostProcess[]; + protected _textures: BaseTexture[]; + protected _emissiveTextureAndColor: { + texture: Nullable; + color: Color4; + }; /** - * Gets the ground mirror created by the helper. + * The name of the layer */ - readonly groundMirror: Nullable; + name: string; /** - * Gets the ground mirror render list to helps pushing the meshes - * you wish in the ground reflection. + * The clear color of the texture used to generate the glow map. */ - readonly groundMirrorRenderList: Nullable; - private _groundMaterial; + neutralColor: Color4; /** - * Gets the ground material created by the helper. + * Specifies wether the highlight layer is enabled or not. */ - readonly groundMaterial: Nullable; + isEnabled: boolean; /** - * Stores the creation options. + * Gets the camera attached to the layer. */ - private readonly _scene; - private _options; + readonly camera: Nullable; /** - * This observable will be notified with any error during the creation of the environment, - * mainly texture creation errors. + * Gets the rendering group id the layer should render in. */ - onErrorObservable: Observable<{ - message?: string; - exception?: any; - }>; + readonly renderingGroupId: number; /** - * constructor - * @param options - * @param scene The scene to add the material to + * An event triggered when the effect layer has been disposed. */ - constructor(options: Partial, scene: Scene); + onDisposeObservable: Observable; /** - * Updates the background according to the new options - * @param options + * An event triggered when the effect layer is about rendering the main texture with the glowy parts. */ - updateOptions(options: Partial): void; + onBeforeRenderMainTextureObservable: Observable; /** - * Sets the primary color of all the available elements. - * @param color the main color to affect to the ground and the background + * An event triggered when the generated texture is being merged in the scene. */ - setMainColor(color: Color3): void; + onBeforeComposeObservable: Observable; /** - * Setup the image processing according to the specified options. + * An event triggered when the generated texture has been merged in the scene. */ - private _setupImageProcessing(); + onAfterComposeObservable: Observable; /** - * Setup the environment texture according to the specified options. + * An event triggered when the efffect layer changes its size. */ - private _setupEnvironmentTexture(); + onSizeChangedObservable: Observable; /** - * Setup the background according to the specified options. + * Instantiates a new effect Layer and references it in the scene. + * @param name The name of the layer + * @param scene The scene to use the layer in */ - private _setupBackground(); + constructor( + /** The Friendly of the effect in the scene */ + name: string, scene: Scene); /** - * Get the scene sizes according to the setup. + * Get the effect name of the layer. + * @return The effect name */ - private _getSceneSize(); + abstract getEffectName(): string; /** - * Setup the ground according to the specified options. + * Checks for the readiness of the element composing the layer. + * @param subMesh the mesh to check for + * @param useInstances specify wether or not to use instances to render the mesh + * @return true if ready otherwise, false */ - private _setupGround(sceneSize); + abstract isReady(subMesh: SubMesh, useInstances: boolean): boolean; /** - * Setup the ground material according to the specified options. + * Returns wether or nood the layer needs stencil enabled during the mesh rendering. + * @returns true if the effect requires stencil during the main canvas render pass. */ - private _setupGroundMaterial(); + abstract needStencil(): boolean; /** - * Setup the ground diffuse texture according to the specified options. + * Create the merge effect. This is the shader use to blit the information back + * to the main canvas at the end of the scene rendering. + * @returns The effect containing the shader used to merge the effect on the main canvas */ - private _setupGroundDiffuseTexture(); + protected abstract _createMergeEffect(): Effect; /** - * Setup the ground mirror texture according to the specified options. + * Creates the render target textures and post processes used in the effect layer. */ - private _setupGroundMirrorTexture(sceneSize); + protected abstract _createTextureAndPostProcesses(): void; /** - * Setup the ground to receive the mirror texture. + * Implementation specific of rendering the generating effect on the main canvas. + * @param effect The effect used to render through */ - private _setupMirrorInGroundMaterial(); + protected abstract _internalRender(effect: Effect): void; /** - * Setup the skybox according to the specified options. + * Sets the required values for both the emissive texture and and the main color. */ - private _setupSkybox(sceneSize); + protected abstract _setEmissiveTextureAndColor(mesh: Mesh, subMesh: SubMesh, material: Material): void; /** - * Setup the skybox material according to the specified options. + * Free any resources and references associated to a mesh. + * Internal use + * @param mesh The mesh to free. */ - private _setupSkyboxMaterial(); + abstract _disposeMesh(mesh: Mesh): void; /** - * Setup the skybox reflection texture according to the specified options. + * Serializes this layer (Glow or Highlight for example) + * @returns a serialized layer object */ - private _setupSkyboxReflectionTexture(); - private _errorHandler; + abstract serialize?(): any; /** - * Dispose all the elements created by the Helper. + * Initializes the effect layer with the required options. + * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information) */ - dispose(): void; - } -} - -declare module BABYLON { - /** - * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes. - * As a subclass of Node, this allow parenting to the camera with different locations in the scene. - * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere. - * Potential additions to this helper include zoom and and non-infinite distance rendering effects. - */ - class PhotoDome extends Node { - private _useDirectMapping; + protected _init(options: Partial): void; /** - * The texture being displayed on the sphere + * Generates the index buffer of the full screen quad blending to the main canvas. */ - protected _photoTexture: Texture; + private _generateIndexBuffer; /** - * Gets or sets the texture being displayed on the sphere + * Generates the vertex buffer of the full screen quad blending to the main canvas. */ - photoTexture: Texture; + private _genrateVertexBuffer; /** - * The skybox material + * Sets the main texture desired size which is the closest power of two + * of the engine canvas size. */ - protected _material: BackgroundMaterial; + private _setMainTextureSize; /** - * The surface used for the skybox + * Creates the main texture for the effect layer. */ - protected _mesh: Mesh; + protected _createMainTexture(): void; /** - * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". - * Also see the options.resolution property. + * Checks for the readiness of the element composing the layer. + * @param subMesh the mesh to check for + * @param useInstances specify wether or not to use instances to render the mesh + * @param emissiveTexture the associated emissive texture used to generate the glow + * @return true if ready otherwise, false */ - fovMultiplier: number; + protected _isReady(subMesh: SubMesh, useInstances: boolean, emissiveTexture: Nullable): boolean; /** - * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh. - * @param name Element's name, child elements will append suffixes for their own names. - * @param urlsOfPhoto define the url of the photo to display - * @param options An object containing optional or exposed sub element properties + * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene. */ - constructor(name: string, urlOfPhoto: string, options: { - resolution?: number; - size?: number; - useDirectMapping?: boolean; - }, scene: Scene); + render(): void; /** - * Releases resources associated with this node. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + * Determine if a given mesh will be used in the current effect. + * @param mesh mesh to test + * @returns true if the mesh will be used */ - dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; - } -} - -declare module BABYLON { - /** - * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes. - * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene. - * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere. - * Potential additions to this helper include zoom and and non-infinite distance rendering effects. - */ - class VideoDome extends Node { - private _useDirectMapping; + hasMesh(mesh: AbstractMesh): boolean; /** - * The video texture being displayed on the sphere + * Returns true if the layer contains information to display, otherwise false. + * @returns true if the glow layer should be rendered */ - protected _videoTexture: VideoTexture; + shouldRender(): boolean; /** - * Gets the video texture being displayed on the sphere + * Returns true if the mesh should render, otherwise false. + * @param mesh The mesh to render + * @returns true if it should render otherwise false */ - readonly videoTexture: VideoTexture; + protected _shouldRenderMesh(mesh: Mesh): boolean; /** - * The skybox material + * Returns true if the mesh should render, otherwise false. + * @param mesh The mesh to render + * @returns true if it should render otherwise false */ - protected _material: BackgroundMaterial; + protected _shouldRenderEmissiveTextureForMesh(mesh: Mesh): boolean; /** - * The surface used for the skybox + * Renders the submesh passed in parameter to the generation map. */ - protected _mesh: Mesh; + protected _renderSubMesh(subMesh: SubMesh): void; /** - * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". - * Also see the options.resolution property. + * Rebuild the required buffers. + * @hidden Internal use only. */ - fovMultiplier: number; + _rebuild(): void; /** - * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh. - * @param name Element's name, child elements will append suffixes for their own names. - * @param urlsOrVideo defines the url(s) or the video element to use - * @param options An object containing optional or exposed sub element properties + * Dispose only the render target textures and post process. */ - constructor(name: string, urlsOrVideo: string | string[] | HTMLVideoElement, options: { - resolution?: number; - clickToPlay?: boolean; - autoPlay?: boolean; - loop?: boolean; - size?: number; - poster?: string; - useDirectMapping?: boolean; - }, scene: Scene); + private _disposeTextureAndPostProcesses; /** - * Releases resources associated with this node. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + * Dispose the highlight layer and free resources. */ - dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; - } -} - -declare module BABYLON { - class LensFlare { - size: number; - position: number; - color: Color3; - texture: Nullable; - alphaMode: number; - private _system; - static AddFlare(size: number, position: number, color: Color3, imgUrl: string, system: LensFlareSystem): LensFlare; - constructor(size: number, position: number, color: Color3, imgUrl: string, system: LensFlareSystem); - dispose(): void; - } -} - -declare module BABYLON { - class LensFlareSystem { - name: string; - lensFlares: LensFlare[]; - borderLimit: number; - viewportBorder: number; - meshesSelectionPredicate: (mesh: AbstractMesh) => boolean; - layerMask: number; - id: string; - private _scene; - private _emitter; - private _vertexBuffers; - private _indexBuffer; - private _effect; - private _positionX; - private _positionY; - private _isEnabled; - constructor(name: string, emitter: any, scene: Scene); - isEnabled: boolean; - getScene(): Scene; - getEmitter(): any; - setEmitter(newEmitter: any): void; - getEmitterPosition(): Vector3; - computeEffectivePosition(globalViewport: Viewport): boolean; - _isVisible(): boolean; - render(): boolean; dispose(): void; - static Parse(parsedLensFlareSystem: any, scene: Scene, rootUrl: string): LensFlareSystem; - serialize(): any; + /** + * Gets the class name of the effect layer + * @returns the string with the class name of the effect layer + */ + getClassName(): string; + /** + * Creates an effect layer from parsed effect layer data + * @param parsedEffectLayer defines effect layer data + * @param scene defines the current scene + * @param rootUrl defines the root URL containing the effect layer information + * @returns a parsed effect Layer + */ + static Parse(parsedEffectLayer: any, scene: Scene, rootUrl: string): EffectLayer; } } declare module BABYLON { interface AbstractScene { /** - * The list of lens flare system added to the scene - * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares - */ - lensFlareSystems: Array; - /** - * Removes the given lens flare system from this scene. - * @param toRemove The lens flare system to remove - * @returns The index of the removed lens flare system - */ - removeLensFlareSystem(toRemove: LensFlareSystem): number; - /** - * Adds the given lens flare system to this scene - * @param newLensFlareSystem The lens flare system to add + * The list of effect layers (highlights/glow) added to the scene + * @see http://doc.babylonjs.com/how_to/highlight_layer + * @see http://doc.babylonjs.com/how_to/glow_layer */ - addLensFlareSystem(newLensFlareSystem: LensFlareSystem): void; + effectLayers: Array; /** - * Gets a lens flare system using its name - * @param name defines the name to look for - * @returns the lens flare system or null if not found + * Removes the given effect layer from this scene. + * @param toRemove defines the effect layer to remove + * @returns the index of the removed effect layer */ - getLensFlareSystemByName(name: string): Nullable; + removeEffectLayer(toRemove: EffectLayer): number; /** - * Gets a lens flare system using its id - * @param id defines the id to look for - * @returns the lens flare system or null if not found + * Adds the given effect layer to this scene + * @param newEffectLayer defines the effect layer to add */ - getLensFlareSystemByID(id: string): Nullable; + addEffectLayer(newEffectLayer: EffectLayer): void; } /** - * Defines the lens flare scene component responsible to manage any lens flares + * Defines the layer scene component responsible to manage any effect layers * in a given scene. */ - class LensFlareSystemSceneComponent implements ISceneSerializableComponent { + class EffectLayerSceneComponent implements ISceneSerializableComponent { /** * The component name helpfull to identify the component in the list of scene components. */ @@ -10771,8 +10957,12 @@ declare module BABYLON { * The scene the component belongs to. */ scene: Scene; - /** - * Creates a new instance of the component for the given scene + private _engine; + private _renderEffects; + private _needStencil; + private _previousStencilState; + /** + * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ constructor(scene: Scene); @@ -10785,6 +10975,11 @@ declare module BABYLON { * context lost for instance. */ rebuild(): void; + /** + * Serializes the component data to the specified json object + * @param serializationObject The object to serialize to + */ + serialize(serializationObject: any): void; /** * Adds all the element from the container to the scene * @param container the container holding the elements @@ -10795,966 +10990,1092 @@ declare module BABYLON { * @param container contains the elements to remove */ removeFromContainer(container: AbstractScene): void; - /** - * Serializes the component data to the specified json object - * @param serializationObject The object to serialize to - */ - serialize(serializationObject: any): void; /** * Disposes the component and the associated ressources. */ dispose(): void; - private _draw(camera); + private _isReadyForMesh; + private _renderMainTexture; + private _setStencil; + private _setStencilBack; + private _draw; + private _drawCamera; + private _drawRenderingGroup; } } declare module BABYLON { + interface AbstractScene { + /** + * Return a the first highlight layer of the scene with a given name. + * @param name The name of the highlight layer to look for. + * @return The highlight layer if found otherwise null. + */ + getGlowLayerByName(name: string): Nullable; + } /** - * A directional light is defined by a direction (what a surprise!). - * The light is emitted from everywhere in the specified direction, and has an infinite range. - * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object. - * Documentation: https://doc.babylonjs.com/babylon101/lights + * Glow layer options. This helps customizing the behaviour + * of the glow layer. */ - class DirectionalLight extends ShadowLight { - private _shadowFrustumSize; + interface IGlowLayerOptions { /** - * Fix frustum size for the shadow generation. This is disabled if the value is 0. + * Multiplication factor apply to the canvas size to compute the render target size + * used to generated the glowing objects (the smaller the faster). */ + mainTextureRatio: number; /** - * Specifies a fix frustum size for the shadow generation. + * Enforces a fixed size texture to ensure resize independant blur. */ - shadowFrustumSize: number; - private _shadowOrthoScale; + mainTextureFixedSize?: number; /** - * Gets the shadow projection scale against the optimal computed one. - * 0.1 by default which means that the projection window is increase by 10% from the optimal size. - * This does not impact in fixed frustum size (shadowFrustumSize being set) + * How big is the kernel of the blur texture. */ + blurKernelSize: number; /** - * Sets the shadow projection scale against the optimal computed one. - * 0.1 by default which means that the projection window is increase by 10% from the optimal size. - * This does not impact in fixed frustum size (shadowFrustumSize being set) + * The camera attached to the layer. */ - shadowOrthoScale: number; + camera: Nullable; /** - * Automatically compute the projection matrix to best fit (including all the casters) - * on each frame. + * Enable MSAA by chosing the number of samples. */ - autoUpdateExtends: boolean; - private _orthoLeft; - private _orthoRight; - private _orthoTop; - private _orthoBottom; + mainTextureSamples?: number; /** - * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3). - * The directional light is emitted from everywhere in the given direction. - * It can cast shawdows. - * Documentation : http://doc.babylonjs.com/tutorials/lights - * @param name The friendly name of the light - * @param direction The direction of the light - * @param scene The scene the light belongs to + * The rendering group to draw the layer in. */ - constructor(name: string, direction: Vector3, scene: Scene); + renderingGroupId: number; + } + /** + * The glow layer Helps adding a glow effect around the emissive parts of a mesh. + * + * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove + * glowy meshes to your scene. + * + * Documentation: https://doc.babylonjs.com/how_to/glow_layer + */ + class GlowLayer extends EffectLayer { /** - * Returns the string "DirectionalLight". - * @return The class name + * Effect Name of the layer. */ - getClassName(): string; + static readonly EffectName: string; /** - * Returns the integer 1. - * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x + * The default blur kernel size used for the glow. */ - getTypeID(): number; + static DefaultBlurKernelSize: number; /** - * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix. - * Returns the DirectionalLight Shadow projection matrix. + * The default texture size ratio used for the glow. */ - protected _setDefaultShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; + static DefaultTextureRatio: number; /** - * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix. - * Returns the DirectionalLight Shadow projection matrix. + * Sets the kernel size of the blur. */ - protected _setDefaultFixedFrustumShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix): void; /** - * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix. - * Returns the DirectionalLight Shadow projection matrix. + * Gets the kernel size of the blur. + */ + blurKernelSize: number; + /** + * Sets the glow intensity. */ - protected _setDefaultAutoExtendShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; - protected _buildUniformLayout(): void; /** - * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name. - * @param effect The effect to update - * @param lightIndex The index of the light in the effect to update - * @returns The directional light + * Gets the glow intensity. + */ + intensity: number; + private _options; + private _intensity; + private _horizontalBlurPostprocess1; + private _verticalBlurPostprocess1; + private _horizontalBlurPostprocess2; + private _verticalBlurPostprocess2; + private _blurTexture1; + private _blurTexture2; + private _postProcesses1; + private _postProcesses2; + private _includedOnlyMeshes; + private _excludedMeshes; + /** + * Callback used to let the user override the color selection on a per mesh basis */ - transferToEffect(effect: Effect, lightIndex: string): DirectionalLight; + customEmissiveColorSelector: (mesh: Mesh, subMesh: SubMesh, material: Material, result: Color4) => void; /** - * Gets the minZ used for shadow according to both the scene and the light. - * - * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being - * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5. - * @param activeCamera The camera we are returning the min for - * @returns the depth min z + * Callback used to let the user override the texture selection on a per mesh basis */ - getDepthMinZ(activeCamera: Camera): number; + customEmissiveTextureSelector: (mesh: Mesh, subMesh: SubMesh, material: Material) => Texture; /** - * Gets the maxZ used for shadow according to both the scene and the light. - * - * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being - * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5. - * @param activeCamera The camera we are returning the max for - * @returns the depth max z + * Instantiates a new glow Layer and references it to the scene. + * @param name The name of the layer + * @param scene The scene to use the layer in + * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information) */ - getDepthMaxZ(activeCamera: Camera): number; + constructor(name: string, scene: Scene, options?: Partial); /** - * Prepares the list of defines specific to the light type. - * @param defines the list of defines - * @param lightIndex defines the index of the light for the effect + * Get the effect name of the layer. + * @return The effect name */ - prepareLightSpecificDefines(defines: any, lightIndex: number): void; - } -} - -declare module BABYLON { - /** - * The HemisphericLight simulates the ambient environment light, - * so the passed direction is the light reflection direction, not the incoming direction. - */ - class HemisphericLight extends Light { + getEffectName(): string; /** - * The groundColor is the light in the opposite direction to the one specified during creation. - * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction. + * Create the merge effect. This is the shader use to blit the information back + * to the main canvas at the end of the scene rendering. */ - groundColor: Color3; + protected _createMergeEffect(): Effect; /** - * The light reflection direction, not the incoming direction. + * Creates the render target textures and post processes used in the glow layer. */ - direction: Vector3; - private _worldMatrix; + protected _createTextureAndPostProcesses(): void; /** - * Creates a HemisphericLight object in the scene according to the passed direction (Vector3). - * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction. - * The HemisphericLight can't cast shadows. - * Documentation : http://doc.babylonjs.com/tutorials/lights - * @param name The friendly name of the light - * @param direction The direction of the light reflection - * @param scene The scene the light belongs to + * Checks for the readiness of the element composing the layer. + * @param subMesh the mesh to check for + * @param useInstances specify wether or not to use instances to render the mesh + * @param emissiveTexture the associated emissive texture used to generate the glow + * @return true if ready otherwise, false */ - constructor(name: string, direction: Vector3, scene: Scene); - protected _buildUniformLayout(): void; + isReady(subMesh: SubMesh, useInstances: boolean): boolean; /** - * Returns the string "HemisphericLight". - * @return The class name + * Returns wether or nood the layer needs stencil enabled during the mesh rendering. */ - getClassName(): string; + needStencil(): boolean; /** - * Sets the HemisphericLight direction towards the passed target (Vector3). - * Returns the updated direction. - * @param target The target the direction should point to - * @return The computed direction + * Implementation specific of rendering the generating effect on the main canvas. + * @param effect The effect used to render through */ - setDirectionToTarget(target: Vector3): Vector3; + protected _internalRender(effect: Effect): void; /** - * Returns the shadow generator associated to the light. - * @returns Always null for hemispheric lights because it does not support shadows. + * Sets the required values for both the emissive texture and and the main color. */ - getShadowGenerator(): Nullable; + protected _setEmissiveTextureAndColor(mesh: Mesh, subMesh: SubMesh, material: Material): void; /** - * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string). - * @param effect The effect to update - * @param lightIndex The index of the light in the effect to update - * @returns The hemispheric light + * Returns true if the mesh should render, otherwise false. + * @param mesh The mesh to render + * @returns true if it should render otherwise false */ - transferToEffect(effect: Effect, lightIndex: string): HemisphericLight; + protected _shouldRenderMesh(mesh: Mesh): boolean; /** - * @hidden internal use only. + * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer. + * @param mesh The mesh to exclude from the glow layer */ - _getWorldMatrix(): Matrix; + addExcludedMesh(mesh: Mesh): void; /** - * Returns the integer 3. - * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x + * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer. + * @param mesh The mesh to remove + */ + removeExcludedMesh(mesh: Mesh): void; + /** + * Add a mesh in the inclusion list to impact or being impacted by the glow layer. + * @param mesh The mesh to include in the glow layer */ - getTypeID(): number; + addIncludedOnlyMesh(mesh: Mesh): void; /** - * Prepares the list of defines specific to the light type. - * @param defines the list of defines - * @param lightIndex defines the index of the light for the effect + * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer. + * @param mesh The mesh to remove + */ + removeIncludedOnlyMesh(mesh: Mesh): void; + /** + * Determine if a given mesh will be used in the glow layer + * @param mesh The mesh to test + * @returns true if the mesh will be highlighted by the current glow layer */ - prepareLightSpecificDefines(defines: any, lightIndex: number): void; + hasMesh(mesh: AbstractMesh): boolean; + /** + * Free any resources and references associated to a mesh. + * Internal use + * @param mesh The mesh to free. + */ + _disposeMesh(mesh: Mesh): void; + /** + * Gets the class name of the effect layer + * @returns the string with the class name of the effect layer + */ + getClassName(): string; + /** + * Serializes this glow layer + * @returns a serialized glow layer object + */ + serialize(): any; + /** + * Creates a Glow Layer from parsed glow layer data + * @param parsedGlowLayer defines glow layer data + * @param scene defines the current scene + * @param rootUrl defines the root URL containing the glow layer information + * @returns a parsed Glow Layer + */ + static Parse(parsedGlowLayer: any, scene: Scene, rootUrl: string): GlowLayer; } } declare module BABYLON { + interface AbstractScene { + /** + * Return a the first highlight layer of the scene with a given name. + * @param name The name of the highlight layer to look for. + * @return The highlight layer if found otherwise null. + */ + getHighlightLayerByName(name: string): Nullable; + } /** - * Base class of all the lights in Babylon. It groups all the generic information about lights. - * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour. - * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased. + * Highlight layer options. This helps customizing the behaviour + * of the highlight layer. */ - abstract class Light extends Node { + interface IHighlightLayerOptions { /** - * If every light affecting the material is in this lightmapMode, - * material.lightmapTexture adds or multiplies - * (depends on material.useLightmapAsShadowmap) - * after every other light calculations. + * Multiplication factor apply to the canvas size to compute the render target size + * used to generated the glowing objects (the smaller the faster). */ - static readonly LIGHTMAP_DEFAULT: number; + mainTextureRatio: number; /** - * material.lightmapTexture as only diffuse lighting from this light - * adds only specular lighting from this light - * adds dynamic shadows + * Enforces a fixed size texture to ensure resize independant blur. */ - static readonly LIGHTMAP_SPECULAR: number; + mainTextureFixedSize?: number; /** - * material.lightmapTexture as only lighting - * no light calculation from this light - * only adds dynamic shadows from this light + * Multiplication factor apply to the main texture size in the first step of the blur to reduce the size + * of the picture to blur (the smaller the faster). */ - static readonly LIGHTMAP_SHADOWSONLY: number; + blurTextureSizeRatio: number; /** - * Each light type uses the default quantity according to its type: - * point/spot lights use luminous intensity - * directional lights use illuminance + * How big in texel of the blur texture is the vertical blur. */ - static readonly INTENSITYMODE_AUTOMATIC: number; + blurVerticalSize: number; /** - * lumen (lm) + * How big in texel of the blur texture is the horizontal blur. */ - static readonly INTENSITYMODE_LUMINOUSPOWER: number; + blurHorizontalSize: number; /** - * candela (lm/sr) + * Alpha blending mode used to apply the blur. Default is combine. */ - static readonly INTENSITYMODE_LUMINOUSINTENSITY: number; + alphaBlendingMode: number; /** - * lux (lm/m^2) + * The camera attached to the layer. */ - static readonly INTENSITYMODE_ILLUMINANCE: number; + camera: Nullable; /** - * nit (cd/m^2) + * Should we display highlight as a solid stroke? */ - static readonly INTENSITYMODE_LUMINANCE: number; + isStroke?: boolean; /** - * Light type const id of the point light. + * The rendering group to draw the layer in. */ - static readonly LIGHTTYPEID_POINTLIGHT: number; + renderingGroupId: number; + } + /** + * The highlight layer Helps adding a glow effect around a mesh. + * + * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove + * glowy meshes to your scene. + * + * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!! + */ + class HighlightLayer extends EffectLayer { + name: string; /** - * Light type const id of the directional light. + * Effect Name of the highlight layer. */ - static readonly LIGHTTYPEID_DIRECTIONALLIGHT: number; + static readonly EffectName: string; /** - * Light type const id of the spot light. + * The neutral color used during the preparation of the glow effect. + * This is black by default as the blend operation is a blend operation. */ - static readonly LIGHTTYPEID_SPOTLIGHT: number; + static NeutralColor: Color4; /** - * Light type const id of the hemispheric light. + * Stencil value used for glowing meshes. */ - static readonly LIGHTTYPEID_HEMISPHERICLIGHT: number; + static GlowingMeshStencilReference: number; /** - * Diffuse gives the basic color to an object. + * Stencil value used for the other meshes in the scene. */ - diffuse: Color3; + static NormalMeshStencilReference: number; /** - * Specular produces a highlight color on an object. - * Note: This is note affecting PBR materials. + * Specifies whether or not the inner glow is ACTIVE in the layer. */ - specular: Color3; + innerGlow: boolean; /** - * Strength of the light. - * Note: By default it is define in the framework own unit. - * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in. + * Specifies whether or not the outer glow is ACTIVE in the layer. */ - intensity: number; + outerGlow: boolean; /** - * Defines how far from the source the light is impacting in scene units. - * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff. + * Specifies the horizontal size of the blur. */ - range: number; /** - * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type - * of light. - */ - private _photometricScale; - private _intensityMode; + * Gets the horizontal size of the blur. + */ + blurHorizontalSize: number; /** - * Gets the photometric scale used to interpret the intensity. - * This is only relevant with PBR Materials where the light intensity can be defined in a physical way. + * Specifies the vertical size of the blur. */ /** - * Sets the photometric scale used to interpret the intensity. - * This is only relevant with PBR Materials where the light intensity can be defined in a physical way. - */ - intensityMode: number; - private _radius; + * Gets the vertical size of the blur. + */ + blurVerticalSize: number; /** - * Gets the light radius used by PBR Materials to simulate soft area lights. + * An event triggered when the highlight layer is being blurred. */ + onBeforeBlurObservable: Observable; /** - * sets the light radius used by PBR Materials to simulate soft area lights. + * An event triggered when the highlight layer has been blurred. */ - radius: number; - private _renderPriority; + onAfterBlurObservable: Observable; + private _instanceGlowingMeshStencilReference; + private _options; + private _downSamplePostprocess; + private _horizontalBlurPostprocess; + private _verticalBlurPostprocess; + private _blurTexture; + private _meshes; + private _excludedMeshes; /** - * Defines the rendering priority of the lights. It can help in case of fallback or number of lights - * exceeding the number allowed of the materials. + * Instantiates a new highlight Layer and references it to the scene.. + * @param name The name of the layer + * @param scene The scene to use the layer in + * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information) */ - renderPriority: number; - private _shadowEnabled; + constructor(name: string, scene: Scene, options?: Partial); /** - * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching - * the current shadow generator. + * Get the effect name of the layer. + * @return The effect name */ + getEffectName(): string; /** - * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching - * the current shadow generator. + * Create the merge effect. This is the shader use to blit the information back + * to the main canvas at the end of the scene rendering. */ - shadowEnabled: boolean; - private _includedOnlyMeshes; + protected _createMergeEffect(): Effect; /** - * Gets the only meshes impacted by this light. + * Creates the render target textures and post processes used in the highlight layer. */ + protected _createTextureAndPostProcesses(): void; /** - * Sets the only meshes impacted by this light. + * Returns wether or nood the layer needs stencil enabled during the mesh rendering. */ - includedOnlyMeshes: AbstractMesh[]; - private _excludedMeshes; + needStencil(): boolean; /** - * Gets the meshes not impacted by this light. + * Checks for the readiness of the element composing the layer. + * @param subMesh the mesh to check for + * @param useInstances specify wether or not to use instances to render the mesh + * @param emissiveTexture the associated emissive texture used to generate the glow + * @return true if ready otherwise, false */ + isReady(subMesh: SubMesh, useInstances: boolean): boolean; /** - * Sets the meshes not impacted by this light. + * Implementation specific of rendering the generating effect on the main canvas. + * @param effect The effect used to render through */ - excludedMeshes: AbstractMesh[]; - private _excludeWithLayerMask; + protected _internalRender(effect: Effect): void; /** - * Gets the layer id use to find what meshes are not impacted by the light. - * Inactive if 0 + * Returns true if the layer contains information to display, otherwise false. */ + shouldRender(): boolean; /** - * Sets the layer id use to find what meshes are not impacted by the light. - * Inactive if 0 + * Returns true if the mesh should render, otherwise false. + * @param mesh The mesh to render + * @returns true if it should render otherwise false */ - excludeWithLayerMask: number; - private _includeOnlyWithLayerMask; + protected _shouldRenderMesh(mesh: Mesh): boolean; /** - * Gets the layer id use to find what meshes are impacted by the light. - * Inactive if 0 + * Sets the required values for both the emissive texture and and the main color. */ + protected _setEmissiveTextureAndColor(mesh: Mesh, subMesh: SubMesh, material: Material): void; /** - * Sets the layer id use to find what meshes are impacted by the light. - * Inactive if 0 + * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer. + * @param mesh The mesh to exclude from the highlight layer */ - includeOnlyWithLayerMask: number; - private _lightmapMode; + addExcludedMesh(mesh: Mesh): void; /** - * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) - */ + * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer. + * @param mesh The mesh to highlight + */ + removeExcludedMesh(mesh: Mesh): void; /** - * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) + * Determine if a given mesh will be highlighted by the current HighlightLayer + * @param mesh mesh to test + * @returns true if the mesh will be highlighted by the current HighlightLayer */ - lightmapMode: number; - private _parentedWorldMatrix; + hasMesh(mesh: AbstractMesh): boolean; /** - * Shadow generator associted to the light. - * Internal use only. + * Add a mesh in the highlight layer in order to make it glow with the chosen color. + * @param mesh The mesh to highlight + * @param color The color of the highlight + * @param glowEmissiveOnly Extract the glow from the emissive texture */ - _shadowGenerator: Nullable; + addMesh(mesh: Mesh, color: Color3, glowEmissiveOnly?: boolean): void; /** - * @hidden Internal use only. + * Remove a mesh from the highlight layer in order to make it stop glowing. + * @param mesh The mesh to highlight */ - _excludedMeshesIds: string[]; + removeMesh(mesh: Mesh): void; /** - * @hidden Internal use only. + * Force the stencil to the normal expected value for none glowing parts */ - _includedOnlyMeshesIds: string[]; + private _defaultStencilReference; /** - * The current light unifom buffer. - * @hidden Internal use only. + * Free any resources and references associated to a mesh. + * Internal use + * @param mesh The mesh to free. */ - _uniformBuffer: UniformBuffer; + _disposeMesh(mesh: Mesh): void; /** - * Creates a Light object in the scene. - * Documentation : http://doc.babylonjs.com/tutorials/lights - * @param name The firendly name of the light - * @param scene The scene the light belongs too + * Dispose the highlight layer and free resources. */ - constructor(name: string, scene: Scene); - protected abstract _buildUniformLayout(): void; + dispose(): void; /** - * Sets the passed Effect "effect" with the Light information. - * @param effect The effect to update - * @param lightIndex The index of the light in the effect to update - * @returns The light - */ - abstract transferToEffect(effect: Effect, lightIndex: string): Light; - /** - * @hidden internal use only. - */ - abstract _getWorldMatrix(): Matrix; - /** - * Returns the string "Light". - * @returns the class name - */ + * Gets the class name of the effect layer + * @returns the string with the class name of the effect layer + */ getClassName(): string; /** - * Converts the light information to a readable string for debug purpose. - * @param fullDetails Supports for multiple levels of logging within scene loading - * @returns the human readable light info + * Serializes this Highlight layer + * @returns a serialized Highlight layer object */ - toString(fullDetails?: boolean): string; + serialize(): any; /** - * Set the enabled state of this node. - * @param value - the new enabled state + * Creates a Highlight layer from parsed Highlight layer data + * @param parsedHightlightLayer defines the Highlight layer data + * @param scene defines the current scene + * @param rootUrl defines the root URL containing the Highlight layer information + * @returns a parsed Highlight layer */ - setEnabled(value: boolean): void; + static Parse(parsedHightlightLayer: any, scene: Scene, rootUrl: string): HighlightLayer; + } +} + +declare module BABYLON { + class Layer { + name: string; + texture: Nullable; + isBackground: boolean; + color: Color4; + scale: Vector2; + offset: Vector2; + alphaBlendingMode: number; + alphaTest: boolean; + layerMask: number; + private _scene; + private _vertexBuffers; + private _indexBuffer; + private _effect; + private _alphaTestEffect; /** - * Returns the Light associated shadow generator if any. - * @return the associated shadow generator. - */ - getShadowGenerator(): Nullable; + * An event triggered when the layer is disposed. + */ + onDisposeObservable: Observable; + private _onDisposeObserver; + onDispose: () => void; /** - * Returns a Vector3, the absolute light position in the World. - * @returns the world space position of the light - */ - getAbsolutePosition(): Vector3; + * An event triggered before rendering the scene + */ + onBeforeRenderObservable: Observable; + private _onBeforeRenderObserver; + onBeforeRender: () => void; /** - * Specifies if the light will affect the passed mesh. - * @param mesh The mesh to test against the light - * @return true the mesh is affected otherwise, false. - */ - canAffectMesh(mesh: AbstractMesh): boolean; + * An event triggered after rendering the scene + */ + onAfterRenderObservable: Observable; + private _onAfterRenderObserver; + onAfterRender: () => void; + constructor(name: string, imgUrl: Nullable, scene: Nullable, isBackground?: boolean, color?: Color4); + private _createIndexBuffer; + _rebuild(): void; + render(): void; + dispose(): void; + } +} + +declare module BABYLON { + interface AbstractScene { /** - * Computes and Returns the light World matrix. - * @returns the world matrix + * The list of layers (background and foreground) of the scene */ - getWorldMatrix(): Matrix; + layers: Array; + } + /** + * Defines the layer scene component responsible to manage any layers + * in a given scene. + */ + class LayerSceneComponent implements ISceneComponent { /** - * Sort function to order lights for rendering. - * @param a First Light object to compare to second. - * @param b Second Light object to compare first. - * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b. + * The component name helpfull to identify the component in the list of scene components. */ - static CompareLightsPriority(a: Light, b: Light): number; + readonly name: string; /** - * Releases resources associated with this node. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + * The scene the component belongs to. */ - dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; + scene: Scene; + private _engine; /** - * Returns the light type ID (integer). - * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in */ - getTypeID(): number; + constructor(scene: Scene); /** - * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode. - * @returns the scaled intensity in intensity mode unit + * Registers the component in a given scene */ - getScaledIntensity(): number; + register(): void; /** - * Returns a new Light object, named "name", from the current one. - * @param name The name of the cloned light - * @returns the new created light + * Rebuilds the elements related to this component in case of + * context lost for instance. */ - clone(name: string): Nullable; + rebuild(): void; /** - * Serializes the current light into a Serialization object. - * @returns the serialized object. + * Disposes the component and the associated ressources. */ + dispose(): void; + private _draw; + private _drawBackground; + private _drawForeground; + } +} + +declare module BABYLON { + class LensFlare { + size: number; + position: number; + color: Color3; + texture: Nullable; + alphaMode: number; + private _system; + static AddFlare(size: number, position: number, color: Color3, imgUrl: string, system: LensFlareSystem): LensFlare; + constructor(size: number, position: number, color: Color3, imgUrl: string, system: LensFlareSystem); + dispose(): void; + } +} + +declare module BABYLON { + class LensFlareSystem { + name: string; + lensFlares: LensFlare[]; + borderLimit: number; + viewportBorder: number; + meshesSelectionPredicate: (mesh: AbstractMesh) => boolean; + layerMask: number; + id: string; + private _scene; + private _emitter; + private _vertexBuffers; + private _indexBuffer; + private _effect; + private _positionX; + private _positionY; + private _isEnabled; + constructor(name: string, emitter: any, scene: Scene); + isEnabled: boolean; + getScene(): Scene; + getEmitter(): any; + setEmitter(newEmitter: any): void; + getEmitterPosition(): Vector3; + computeEffectivePosition(globalViewport: Viewport): boolean; + _isVisible(): boolean; + render(): boolean; + dispose(): void; + static Parse(parsedLensFlareSystem: any, scene: Scene, rootUrl: string): LensFlareSystem; serialize(): any; + } +} + +declare module BABYLON { + interface AbstractScene { /** - * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3. - * This new light is named "name" and added to the passed scene. - * @param type Type according to the types available in Light.LIGHTTYPEID_x - * @param name The friendly name of the light - * @param scene The scene the new light will belong to - * @returns the constructor function - */ - static GetConstructorFromName(type: number, name: string, scene: Scene): Nullable<() => Light>; - /** - * Parses the passed "parsedLight" and returns a new instanced Light from this parsing. - * @param parsedLight The JSON representation of the light - * @param scene The scene to create the parsed light in - * @returns the created light after parsing - */ - static Parse(parsedLight: any, scene: Scene): Nullable; - private _hookArrayForExcluded(array); - private _hookArrayForIncludedOnly(array); - private _resyncMeshes(); - /** - * Forces the meshes to update their light related information in their rendering used effects - * @hidden Internal Use Only + * The list of lens flare system added to the scene + * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares */ - _markMeshesAsLightDirty(): void; + lensFlareSystems: Array; /** - * Recomputes the cached photometric scale if needed. + * Removes the given lens flare system from this scene. + * @param toRemove The lens flare system to remove + * @returns The index of the removed lens flare system */ - private _computePhotometricScale(); + removeLensFlareSystem(toRemove: LensFlareSystem): number; /** - * Returns the Photometric Scale according to the light type and intensity mode. + * Adds the given lens flare system to this scene + * @param newLensFlareSystem The lens flare system to add */ - private _getPhotometricScale(); + addLensFlareSystem(newLensFlareSystem: LensFlareSystem): void; /** - * Reorder the light in the scene according to their defined priority. - * @hidden Internal Use Only + * Gets a lens flare system using its name + * @param name defines the name to look for + * @returns the lens flare system or null if not found */ - _reorderLightsInScene(): void; + getLensFlareSystemByName(name: string): Nullable; /** - * Prepares the list of defines specific to the light type. - * @param defines the list of defines - * @param lightIndex defines the index of the light for the effect + * Gets a lens flare system using its id + * @param id defines the id to look for + * @returns the lens flare system or null if not found */ - abstract prepareLightSpecificDefines(defines: any, lightIndex: number): void; + getLensFlareSystemByID(id: string): Nullable; } -} - -declare module BABYLON { /** - * A point light is a light defined by an unique point in world space. - * The light is emitted in every direction from this point. - * A good example of a point light is a standard light bulb. - * Documentation: https://doc.babylonjs.com/babylon101/lights + * Defines the lens flare scene component responsible to manage any lens flares + * in a given scene. */ - class PointLight extends ShadowLight { - private _shadowAngle; - /** - * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback - * This specifies what angle the shadow will use to be created. - * - * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. - */ - /** - * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback - * This specifies what angle the shadow will use to be created. - * - * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. - */ - shadowAngle: number; - /** - * Gets the direction if it has been set. - * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback - */ + class LensFlareSystemSceneComponent implements ISceneSerializableComponent { /** - * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + * The component name helpfull to identify the component in the list of scene components. */ - direction: Vector3; + readonly name: string; /** - * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene. - * A PointLight emits the light in every direction. - * It can cast shadows. - * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it : - * ```javascript - * var pointLight = new BABYLON.PointLight("pl", camera.position, scene); - * ``` - * Documentation : http://doc.babylonjs.com/tutorials/lights - * @param name The light friendly name - * @param position The position of the point light in the scene - * @param scene The scene the lights belongs to + * The scene the component belongs to. */ - constructor(name: string, position: Vector3, scene: Scene); + scene: Scene; /** - * Returns the string "PointLight" - * @returns the class name + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in */ - getClassName(): string; + constructor(scene: Scene); /** - * Returns the integer 0. - * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x + * Registers the component in a given scene */ - getTypeID(): number; + register(): void; /** - * Specifies wether or not the shadowmap should be a cube texture. - * @returns true if the shadowmap needs to be a cube texture. + * Rebuilds the elements related to this component in case of + * context lost for instance. */ - needCube(): boolean; + rebuild(): void; /** - * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer). - * @param faceIndex The index of the face we are computed the direction to generate shadow - * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true + * Adds all the element from the container to the scene + * @param container the container holding the elements */ - getShadowDirection(faceIndex?: number): Vector3; + addFromContainer(container: AbstractScene): void; /** - * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings : - * - fov = PI / 2 - * - aspect ratio : 1.0 - * - z-near and far equal to the active camera minZ and maxZ. - * Returns the PointLight. + * Removes all the elements in the container from the scene + * @param container contains the elements to remove */ - protected _setDefaultShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; - protected _buildUniformLayout(): void; + removeFromContainer(container: AbstractScene): void; /** - * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string). - * @param effect The effect to update - * @param lightIndex The index of the light in the effect to update - * @returns The point light + * Serializes the component data to the specified json object + * @param serializationObject The object to serialize to */ - transferToEffect(effect: Effect, lightIndex: string): PointLight; + serialize(serializationObject: any): void; /** - * Prepares the list of defines specific to the light type. - * @param defines the list of defines - * @param lightIndex defines the index of the light for the effect + * Disposes the component and the associated ressources. */ - prepareLightSpecificDefines(defines: any, lightIndex: number): void; + dispose(): void; + private _draw; } } declare module BABYLON { - /** - * Interface describing all the common properties and methods a shadow light needs to implement. - * This helps both the shadow generator and materials to genrate the corresponding shadow maps - * as well as binding the different shadow properties to the effects. - */ - interface IShadowLight extends Light { + interface ILoadingScreen { + displayLoadingUI: () => void; + hideLoadingUI: () => void; + loadingUIBackgroundColor: string; + loadingUIText: string; + } + class DefaultLoadingScreen implements ILoadingScreen { + private _renderingCanvas; + private _loadingText; + private _loadingDivBackgroundColor; + private _loadingDiv; + private _loadingTextDiv; + constructor(_renderingCanvas: HTMLCanvasElement, _loadingText?: string, _loadingDivBackgroundColor?: string); + displayLoadingUI(): void; + hideLoadingUI(): void; + loadingUIText: string; + loadingUIBackgroundColor: string; + private _resizeLoadingUI; + } +} + +declare module BABYLON { + class SceneLoaderProgressEvent { + readonly lengthComputable: boolean; + readonly loaded: number; + readonly total: number; + constructor(lengthComputable: boolean, loaded: number, total: number); + static FromProgressEvent(event: ProgressEvent): SceneLoaderProgressEvent; + } + interface ISceneLoaderPluginExtensions { + [extension: string]: { + isBinary: boolean; + }; + } + interface ISceneLoaderPluginFactory { + name: string; + createPlugin(): ISceneLoaderPlugin | ISceneLoaderPluginAsync; + canDirectLoad?: (data: string) => boolean; + } + interface ISceneLoaderPlugin { /** - * The light id in the scene (used in scene.findLighById for instance) + * The friendly name of this plugin. */ - id: string; + name: string; /** - * The position the shdow will be casted from. + * The file extensions supported by this plugin. */ - position: Vector3; + extensions: string | ISceneLoaderPluginExtensions; /** - * In 2d mode (needCube being false), the direction used to cast the shadow. + * Import meshes into a scene. + * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported + * @param scene The scene to import into + * @param data The data to import + * @param rootUrl The root url for scene and resources + * @param meshes The meshes array to import into + * @param particleSystems The particle systems array to import into + * @param skeletons The skeletons array to import into + * @param onError The callback when import fails + * @returns True if successful or false otherwise */ - direction: Vector3; + importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], onError?: (message: string, exception?: any) => void): boolean; /** - * The transformed position. Position of the light in world space taking parenting in account. + * Load into a scene. + * @param scene The scene to load into + * @param data The data to import + * @param rootUrl The root url for scene and resources + * @param onError The callback when import fails + * @returns true if successful or false otherwise */ - transformedPosition: Vector3; + load(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): boolean; /** - * The transformed direction. Direction of the light in world space taking parenting in account. + * The callback that returns true if the data can be directly loaded. */ - transformedDirection: Vector3; + canDirectLoad?: (data: string) => boolean; /** - * The friendly name of the light in the scene. + * The callback that allows custom handling of the root url based on the response url. */ - name: string; + rewriteRootURL?: (rootUrl: string, responseURL?: string) => string; /** - * Defines the shadow projection clipping minimum z value. + * Load into an asset container. + * @param scene The scene to load into + * @param data The data to import + * @param rootUrl The root url for scene and resources + * @param onError The callback when import fails + * @returns The loaded asset container */ - shadowMinZ: number; + loadAssetContainer(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer; + } + interface ISceneLoaderPluginAsync { /** - * Defines the shadow projection clipping maximum z value. + * The friendly name of this plugin. */ - shadowMaxZ: number; + name: string; /** - * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light - * @returns true if the information has been computed, false if it does not need to (no parenting) + * The file extensions supported by this plugin. */ - computeTransformedInformation(): boolean; + extensions: string | ISceneLoaderPluginExtensions; /** - * Gets the scene the light belongs to. - * @returns The scene + * Import meshes into a scene. + * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported + * @param scene The scene to import into + * @param data The data to import + * @param rootUrl The root url for scene and resources + * @param onProgress The callback when the load progresses + * @returns The loaded meshes, particle systems, skeletons, and animation groups */ - getScene(): Scene; + importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{ + meshes: AbstractMesh[]; + particleSystems: IParticleSystem[]; + skeletons: Skeleton[]; + animationGroups: AnimationGroup[]; + }>; /** - * Callback defining a custom Projection Matrix Builder. - * This can be used to override the default projection matrix computation. + * Load into a scene. + * @param scene The scene to load into + * @param data The data to import + * @param rootUrl The root url for scene and resources + * @param onProgress The callback when the load progresses + * @returns Nothing */ - customProjectionMatrixBuilder: (viewMatrix: Matrix, renderList: Array, result: Matrix) => void; + loadAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise; /** - * Sets the shadow projection matrix in parameter to the generated projection matrix. - * @param matrix The materix to updated with the projection information - * @param viewMatrix The transform matrix of the light - * @param renderList The list of mesh to render in the map - * @returns The current light + * The callback that returns true if the data can be directly loaded. */ - setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): IShadowLight; + canDirectLoad?: (data: string) => boolean; /** - * Gets the current depth scale used in ESM. - * @returns The scale + * The callback that allows custom handling of the root url based on the response url. */ - getDepthScale(): number; + rewriteRootURL?: (rootUrl: string, responseURL?: string) => string; /** - * Returns whether or not the shadow generation require a cube texture or a 2d texture. - * @returns true if a cube texture needs to be use + * Load into an asset container. + * @param scene The scene to load into + * @param data The data to import + * @param rootUrl The root url for scene and resources + * @param onProgress The callback when the load progresses + * @returns The loaded asset container */ - needCube(): boolean; + loadAssetContainerAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise; + } + class SceneLoader { + private static _ForceFullSceneLoadingForIncremental; + private static _ShowLoadingScreen; + private static _CleanBoneMatrixWeights; + static readonly NO_LOGGING: number; + static readonly MINIMAL_LOGGING: number; + static readonly SUMMARY_LOGGING: number; + static readonly DETAILED_LOGGING: number; + private static _loggingLevel; + static ForceFullSceneLoadingForIncremental: boolean; + static ShowLoadingScreen: boolean; + static loggingLevel: number; + static CleanBoneMatrixWeights: boolean; + static OnPluginActivatedObservable: Observable; + private static _registeredPlugins; + private static _getDefaultPlugin; + private static _getPluginForExtension; + private static _getPluginForDirectLoad; + private static _getPluginForFilename; + private static _getDirectLoad; + private static _loadData; + static GetPluginForExtension(extension: string): ISceneLoaderPlugin | ISceneLoaderPluginAsync | ISceneLoaderPluginFactory; + static IsPluginForExtensionAvailable(extension: string): boolean; + static RegisterPlugin(plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync): void; /** - * Detects if the projection matrix requires to be recomputed this frame. - * @returns true if it requires to be recomputed otherwise, false. + * Import meshes into a scene + * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported + * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) + * @param scene the instance of BABYLON.Scene to append to + * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded plugin */ - needProjectionMatrixCompute(): boolean; + static ImportMesh(meshNames: any, rootUrl: string, sceneFilename?: any, scene?: Nullable, onSuccess?: Nullable<(meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[]) => void>, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, onError?: Nullable<(scene: Scene, message: string, exception?: any) => void>, pluginExtension?: Nullable): Nullable; /** - * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed. - */ - forceProjectionMatrixCompute(): void; - /** - * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed. - * @param faceIndex The index of the face we are computed the direction to generate shadow - * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true - */ - getShadowDirection(faceIndex?: number): Vector3; - /** - * Gets the minZ used for shadow according to both the scene and the light. - * @param activeCamera The camera we are returning the min for - * @returns the depth min z - */ - getDepthMinZ(activeCamera: Camera): number; - /** - * Gets the maxZ used for shadow according to both the scene and the light. - * @param activeCamera The camera we are returning the max for - * @returns the depth max z - */ - getDepthMaxZ(activeCamera: Camera): number; - } - /** - * Base implementation IShadowLight - * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern. - */ - abstract class ShadowLight extends Light implements IShadowLight { - protected abstract _setDefaultShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; - protected _position: Vector3; - protected _setPosition(value: Vector3): void; - /** - * Sets the position the shadow will be casted from. Also use as the light position for both - * point and spot lights. - */ - /** - * Sets the position the shadow will be casted from. Also use as the light position for both - * point and spot lights. - */ - position: Vector3; - protected _direction: Vector3; - protected _setDirection(value: Vector3): void; - /** - * In 2d mode (needCube being false), gets the direction used to cast the shadow. - * Also use as the light direction on spot and directional lights. - */ + * Import meshes into a scene + * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported + * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) + * @param scene the instance of BABYLON.Scene to append to + * @param onProgress a callback with a progress event for each file being loaded + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups + */ + static ImportMeshAsync(meshNames: any, rootUrl: string, sceneFilename?: any, scene?: Nullable, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, pluginExtension?: Nullable): Promise<{ + meshes: AbstractMesh[]; + particleSystems: IParticleSystem[]; + skeletons: Skeleton[]; + animationGroups: AnimationGroup[]; + }>; /** - * In 2d mode (needCube being false), sets the direction used to cast the shadow. - * Also use as the light direction on spot and directional lights. - */ - direction: Vector3; - private _shadowMinZ; + * Load a scene + * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) + * @param engine is the instance of BABYLON.Engine to use to create the scene + * @param onSuccess a callback with the scene when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded plugin + */ + static Load(rootUrl: string, sceneFilename: any, engine: Engine, onSuccess?: Nullable<(scene: Scene) => void>, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, onError?: Nullable<(scene: Scene, message: string, exception?: any) => void>, pluginExtension?: Nullable): Nullable; /** - * Gets the shadow projection clipping minimum z value. - */ + * Load a scene + * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) + * @param engine is the instance of BABYLON.Engine to use to create the scene + * @param onProgress a callback with a progress event for each file being loaded + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded scene + */ + static LoadAsync(rootUrl: string, sceneFilename: any, engine: Engine, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, pluginExtension?: Nullable): Promise; /** - * Sets the shadow projection clipping minimum z value. - */ - shadowMinZ: number; - private _shadowMaxZ; + * Append a scene + * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) + * @param scene is the instance of BABYLON.Scene to append to + * @param onSuccess a callback with the scene when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded plugin + */ + static Append(rootUrl: string, sceneFilename?: any, scene?: Nullable, onSuccess?: Nullable<(scene: Scene) => void>, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, onError?: Nullable<(scene: Scene, message: string, exception?: any) => void>, pluginExtension?: Nullable): Nullable; /** - * Sets the shadow projection clipping maximum z value. - */ + * Append a scene + * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) + * @param scene is the instance of BABYLON.Scene to append to + * @param onProgress a callback with a progress event for each file being loaded + * @param pluginExtension the extension used to determine the plugin + * @returns The given scene + */ + static AppendAsync(rootUrl: string, sceneFilename?: any, scene?: Nullable, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, pluginExtension?: Nullable): Promise; /** - * Gets the shadow projection clipping maximum z value. - */ - shadowMaxZ: number; + * Load a scene into an asset container + * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) + * @param scene is the instance of BABYLON.Scene to append to (default: last created scene) + * @param onSuccess a callback with the scene when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded plugin + */ + static LoadAssetContainer(rootUrl: string, sceneFilename?: any, scene?: Nullable, onSuccess?: Nullable<(assets: AssetContainer) => void>, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, onError?: Nullable<(scene: Scene, message: string, exception?: any) => void>, pluginExtension?: Nullable): Nullable; /** - * Callback defining a custom Projection Matrix Builder. - * This can be used to override the default projection matrix computation. - */ - customProjectionMatrixBuilder: (viewMatrix: Matrix, renderList: Array, result: Matrix) => void; + * Load a scene into an asset container + * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) + * @param scene is the instance of BABYLON.Scene to append to + * @param onProgress a callback with a progress event for each file being loaded + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded asset container + */ + static LoadAssetContainerAsync(rootUrl: string, sceneFilename?: any, scene?: Nullable, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, pluginExtension?: Nullable): Promise; + } +} + +declare module BABYLON { + /** + * A directional light is defined by a direction (what a surprise!). + * The light is emitted from everywhere in the specified direction, and has an infinite range. + * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object. + * Documentation: https://doc.babylonjs.com/babylon101/lights + */ + class DirectionalLight extends ShadowLight { + private _shadowFrustumSize; /** - * The transformed position. Position of the light in world space taking parenting in account. + * Fix frustum size for the shadow generation. This is disabled if the value is 0. */ - transformedPosition: Vector3; /** - * The transformed direction. Direction of the light in world space taking parenting in account. - */ - transformedDirection: Vector3; - private _worldMatrix; - private _needProjectionMatrixCompute; + * Specifies a fix frustum size for the shadow generation. + */ + shadowFrustumSize: number; + private _shadowOrthoScale; /** - * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light - * @returns true if the information has been computed, false if it does not need to (no parenting) + * Gets the shadow projection scale against the optimal computed one. + * 0.1 by default which means that the projection window is increase by 10% from the optimal size. + * This does not impact in fixed frustum size (shadowFrustumSize being set) */ - computeTransformedInformation(): boolean; /** - * Return the depth scale used for the shadow map. - * @returns the depth scale. - */ - getDepthScale(): number; + * Sets the shadow projection scale against the optimal computed one. + * 0.1 by default which means that the projection window is increase by 10% from the optimal size. + * This does not impact in fixed frustum size (shadowFrustumSize being set) + */ + shadowOrthoScale: number; /** - * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed. - * @param faceIndex The index of the face we are computed the direction to generate shadow - * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true + * Automatically compute the projection matrix to best fit (including all the casters) + * on each frame. */ - getShadowDirection(faceIndex?: number): Vector3; + autoUpdateExtends: boolean; + private _orthoLeft; + private _orthoRight; + private _orthoTop; + private _orthoBottom; /** - * Returns the ShadowLight absolute position in the World. - * @returns the position vector in world space + * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3). + * The directional light is emitted from everywhere in the given direction. + * It can cast shawdows. + * Documentation : http://doc.babylonjs.com/tutorials/lights + * @param name The friendly name of the light + * @param direction The direction of the light + * @param scene The scene the light belongs to */ - getAbsolutePosition(): Vector3; + constructor(name: string, direction: Vector3, scene: Scene); /** - * Sets the ShadowLight direction toward the passed target. - * @param target The point tot target in local space - * @returns the updated ShadowLight direction + * Returns the string "DirectionalLight". + * @return The class name */ - setDirectionToTarget(target: Vector3): Vector3; + getClassName(): string; /** - * Returns the light rotation in euler definition. - * @returns the x y z rotation in local space. + * Returns the integer 1. + * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x */ - getRotation(): Vector3; + getTypeID(): number; /** - * Returns whether or not the shadow generation require a cube texture or a 2d texture. - * @returns true if a cube texture needs to be use + * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix. + * Returns the DirectionalLight Shadow projection matrix. */ - needCube(): boolean; + protected _setDefaultShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; /** - * Detects if the projection matrix requires to be recomputed this frame. - * @returns true if it requires to be recomputed otherwise, false. + * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix. + * Returns the DirectionalLight Shadow projection matrix. */ - needProjectionMatrixCompute(): boolean; + protected _setDefaultFixedFrustumShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix): void; /** - * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed. + * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix. + * Returns the DirectionalLight Shadow projection matrix. */ - forceProjectionMatrixCompute(): void; + protected _setDefaultAutoExtendShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; + protected _buildUniformLayout(): void; /** - * Get the world matrix of the sahdow lights. - * @hidden Internal Use Only + * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name. + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The directional light */ - _getWorldMatrix(): Matrix; + transferToEffect(effect: Effect, lightIndex: string): DirectionalLight; /** * Gets the minZ used for shadow according to both the scene and the light. + * + * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being + * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5. * @param activeCamera The camera we are returning the min for * @returns the depth min z */ getDepthMinZ(activeCamera: Camera): number; /** * Gets the maxZ used for shadow according to both the scene and the light. + * + * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being + * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5. * @param activeCamera The camera we are returning the max for * @returns the depth max z */ getDepthMaxZ(activeCamera: Camera): number; /** - * Sets the shadow projection matrix in parameter to the generated projection matrix. - * @param matrix The materix to updated with the projection information - * @param viewMatrix The transform matrix of the light - * @param renderList The list of mesh to render in the map - * @returns The current light + * Prepares the list of defines specific to the light type. + * @param defines the list of defines + * @param lightIndex defines the index of the light for the effect */ - setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): IShadowLight; + prepareLightSpecificDefines(defines: any, lightIndex: number): void; } } declare module BABYLON { /** - * A spot light is defined by a position, a direction, an angle, and an exponent. - * These values define a cone of light starting from the position, emitting toward the direction. - * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam, - * and the exponent defines the speed of the decay of the light with distance (reach). - * Documentation: https://doc.babylonjs.com/babylon101/lights + * The HemisphericLight simulates the ambient environment light, + * so the passed direction is the light reflection direction, not the incoming direction. */ - class SpotLight extends ShadowLight { - private _angle; - /** - * Gets the cone angle of the spot light in Radians. - */ - /** - * Sets the cone angle of the spot light in Radians. - */ - angle: number; - private _shadowAngleScale; - /** - * Allows scaling the angle of the light for shadow generation only. - */ - /** - * Allows scaling the angle of the light for shadow generation only. - */ - shadowAngleScale: number; - /** - * The light decay speed with the distance from the emission spot. - */ - exponent: number; - private _projectionTextureMatrix; - /** - * Allows reading the projecton texture - */ - readonly projectionTextureMatrix: Matrix; - protected _projectionTextureLightNear: number; - /** - * Gets the near clip of the Spotlight for texture projection. - */ - /** - * Sets the near clip of the Spotlight for texture projection. - */ - projectionTextureLightNear: number; - protected _projectionTextureLightFar: number; - /** - * Gets the far clip of the Spotlight for texture projection. - */ - /** - * Sets the far clip of the Spotlight for texture projection. - */ - projectionTextureLightFar: number; - protected _projectionTextureUpDirection: Vector3; + class HemisphericLight extends Light { /** - * Gets the Up vector of the Spotlight for texture projection. + * The groundColor is the light in the opposite direction to the one specified during creation. + * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction. */ + groundColor: Color3; /** - * Sets the Up vector of the Spotlight for texture projection. + * The light reflection direction, not the incoming direction. */ - projectionTextureUpDirection: Vector3; - private _projectionTexture; - /** - * Gets the projection texture of the light. - */ - /** - * Sets the projection texture of the light. - */ - projectionTexture: Nullable; - private _projectionTextureViewLightDirty; - private _projectionTextureProjectionLightDirty; - private _projectionTextureDirty; - private _projectionTextureViewTargetVector; - private _projectionTextureViewLightMatrix; - private _projectionTextureProjectionLightMatrix; - private _projectionTextureScalingMatrix; + direction: Vector3; + private _worldMatrix; /** - * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone. - * It can cast shadows. + * Creates a HemisphericLight object in the scene according to the passed direction (Vector3). + * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction. + * The HemisphericLight can't cast shadows. * Documentation : http://doc.babylonjs.com/tutorials/lights - * @param name The light friendly name - * @param position The position of the spot light in the scene - * @param direction The direction of the light in the scene - * @param angle The cone angle of the light in Radians - * @param exponent The light decay speed with the distance from the emission spot - * @param scene The scene the lights belongs to + * @param name The friendly name of the light + * @param direction The direction of the light reflection + * @param scene The scene the light belongs to */ - constructor(name: string, position: Vector3, direction: Vector3, angle: number, exponent: number, scene: Scene); + constructor(name: string, direction: Vector3, scene: Scene); + protected _buildUniformLayout(): void; /** - * Returns the string "SpotLight". - * @returns the class name + * Returns the string "HemisphericLight". + * @return The class name */ getClassName(): string; /** - * Returns the integer 2. - * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x - */ - getTypeID(): number; - /** - * Overrides the direction setter to recompute the projection texture view light Matrix. - */ - protected _setDirection(value: Vector3): void; - /** - * Overrides the position setter to recompute the projection texture view light Matrix. - */ - protected _setPosition(value: Vector3): void; - /** - * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0. - * Returns the SpotLight. + * Sets the HemisphericLight direction towards the passed target (Vector3). + * Returns the updated direction. + * @param target The target the direction should point to + * @return The computed direction */ - protected _setDefaultShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; - protected _computeProjectionTextureViewLightMatrix(): void; - protected _computeProjectionTextureProjectionLightMatrix(): void; + setDirectionToTarget(target: Vector3): Vector3; /** - * Main function for light texture projection matrix computing. + * Returns the shadow generator associated to the light. + * @returns Always null for hemispheric lights because it does not support shadows. */ - protected _computeProjectionTextureMatrix(): void; - protected _buildUniformLayout(): void; + getShadowGenerator(): Nullable; /** - * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction. + * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string). * @param effect The effect to update * @param lightIndex The index of the light in the effect to update - * @returns The spot light + * @returns The hemispheric light */ - transferToEffect(effect: Effect, lightIndex: string): SpotLight; + transferToEffect(effect: Effect, lightIndex: string): HemisphericLight; /** - * Disposes the light and the associated resources. + * @hidden internal use only. */ - dispose(): void; + _getWorldMatrix(): Matrix; + /** + * Returns the integer 3. + * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x + */ + getTypeID(): number; /** * Prepares the list of defines specific to the light type. * @param defines the list of defines @@ -11766,1261 +12087,943 @@ declare module BABYLON { declare module BABYLON { /** - * Effect layer options. This helps customizing the behaviour - * of the effect layer. + * Base class of all the lights in Babylon. It groups all the generic information about lights. + * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour. + * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased. */ - interface IEffectLayerOptions { + abstract class Light extends Node { /** - * Multiplication factor apply to the canvas size to compute the render target size - * used to generated the objects (the smaller the faster). + * If every light affecting the material is in this lightmapMode, + * material.lightmapTexture adds or multiplies + * (depends on material.useLightmapAsShadowmap) + * after every other light calculations. */ - mainTextureRatio: number; + static readonly LIGHTMAP_DEFAULT: number; /** - * Enforces a fixed size texture to ensure effect stability across devices. + * material.lightmapTexture as only diffuse lighting from this light + * adds only specular lighting from this light + * adds dynamic shadows */ - mainTextureFixedSize?: number; + static readonly LIGHTMAP_SPECULAR: number; /** - * Alpha blending mode used to apply the blur. Default depends of the implementation. + * material.lightmapTexture as only lighting + * no light calculation from this light + * only adds dynamic shadows from this light */ - alphaBlendingMode: number; + static readonly LIGHTMAP_SHADOWSONLY: number; /** - * The camera attached to the layer. + * Each light type uses the default quantity according to its type: + * point/spot lights use luminous intensity + * directional lights use illuminance */ - camera: Nullable; + static readonly INTENSITYMODE_AUTOMATIC: number; /** - * The rendering group to draw the layer in. + * lumen (lm) */ - renderingGroupId: number; - } - /** - * The effect layer Helps adding post process effect blended with the main pass. - * - * This can be for instance use to generate glow or higlight effects on the scene. - * - * The effect layer class can not be used directly and is intented to inherited from to be - * customized per effects. - */ - abstract class EffectLayer { - private _vertexBuffers; - private _indexBuffer; - private _cachedDefines; - private _effectLayerMapGenerationEffect; - private _effectLayerOptions; - private _mergeEffect; - protected _scene: Scene; - protected _engine: Engine; - protected _maxSize: number; - protected _mainTextureDesiredSize: ISize; - protected _mainTexture: RenderTargetTexture; - protected _shouldRender: boolean; - protected _postProcesses: PostProcess[]; - protected _textures: BaseTexture[]; - protected _emissiveTextureAndColor: { - texture: Nullable; - color: Color4; - }; + static readonly INTENSITYMODE_LUMINOUSPOWER: number; /** - * The name of the layer + * candela (lm/sr) */ - name: string; + static readonly INTENSITYMODE_LUMINOUSINTENSITY: number; /** - * The clear color of the texture used to generate the glow map. + * lux (lm/m^2) */ - neutralColor: Color4; + static readonly INTENSITYMODE_ILLUMINANCE: number; /** - * Specifies wether the highlight layer is enabled or not. + * nit (cd/m^2) */ - isEnabled: boolean; + static readonly INTENSITYMODE_LUMINANCE: number; /** - * Gets the camera attached to the layer. + * Light type const id of the point light. */ - readonly camera: Nullable; + static readonly LIGHTTYPEID_POINTLIGHT: number; /** - * Gets the rendering group id the layer should render in. + * Light type const id of the directional light. */ - readonly renderingGroupId: number; + static readonly LIGHTTYPEID_DIRECTIONALLIGHT: number; /** - * An event triggered when the effect layer has been disposed. + * Light type const id of the spot light. */ - onDisposeObservable: Observable; + static readonly LIGHTTYPEID_SPOTLIGHT: number; /** - * An event triggered when the effect layer is about rendering the main texture with the glowy parts. + * Light type const id of the hemispheric light. */ - onBeforeRenderMainTextureObservable: Observable; + static readonly LIGHTTYPEID_HEMISPHERICLIGHT: number; /** - * An event triggered when the generated texture is being merged in the scene. + * Diffuse gives the basic color to an object. */ - onBeforeComposeObservable: Observable; + diffuse: Color3; /** - * An event triggered when the generated texture has been merged in the scene. + * Specular produces a highlight color on an object. + * Note: This is note affecting PBR materials. */ - onAfterComposeObservable: Observable; + specular: Color3; /** - * An event triggered when the efffect layer changes its size. + * Strength of the light. + * Note: By default it is define in the framework own unit. + * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in. */ - onSizeChangedObservable: Observable; + intensity: number; /** - * Instantiates a new effect Layer and references it in the scene. - * @param name The name of the layer - * @param scene The scene to use the layer in + * Defines how far from the source the light is impacting in scene units. + * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff. */ - constructor( - /** The Friendly of the effect in the scene */ - name: string, scene: Scene); + range: number; /** - * Get the effect name of the layer. - * @return The effect name + * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type + * of light. */ - abstract getEffectName(): string; + private _photometricScale; + private _intensityMode; /** - * Checks for the readiness of the element composing the layer. - * @param subMesh the mesh to check for - * @param useInstances specify wether or not to use instances to render the mesh - * @return true if ready otherwise, false + * Gets the photometric scale used to interpret the intensity. + * This is only relevant with PBR Materials where the light intensity can be defined in a physical way. */ - abstract isReady(subMesh: SubMesh, useInstances: boolean): boolean; /** - * Returns wether or nood the layer needs stencil enabled during the mesh rendering. - * @returns true if the effect requires stencil during the main canvas render pass. - */ - abstract needStencil(): boolean; + * Sets the photometric scale used to interpret the intensity. + * This is only relevant with PBR Materials where the light intensity can be defined in a physical way. + */ + intensityMode: number; + private _radius; /** - * Create the merge effect. This is the shader use to blit the information back - * to the main canvas at the end of the scene rendering. - * @returns The effect containing the shader used to merge the effect on the main canvas + * Gets the light radius used by PBR Materials to simulate soft area lights. */ - protected abstract _createMergeEffect(): Effect; /** - * Creates the render target textures and post processes used in the effect layer. + * sets the light radius used by PBR Materials to simulate soft area lights. + */ + radius: number; + private _renderPriority; + /** + * Defines the rendering priority of the lights. It can help in case of fallback or number of lights + * exceeding the number allowed of the materials. */ - protected abstract _createTextureAndPostProcesses(): void; + renderPriority: number; + private _shadowEnabled; /** - * Implementation specific of rendering the generating effect on the main canvas. - * @param effect The effect used to render through + * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching + * the current shadow generator. */ - protected abstract _internalRender(effect: Effect): void; /** - * Sets the required values for both the emissive texture and and the main color. + * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching + * the current shadow generator. + */ + shadowEnabled: boolean; + private _includedOnlyMeshes; + /** + * Gets the only meshes impacted by this light. */ - protected abstract _setEmissiveTextureAndColor(mesh: Mesh, subMesh: SubMesh, material: Material): void; /** - * Free any resources and references associated to a mesh. - * Internal use - * @param mesh The mesh to free. + * Sets the only meshes impacted by this light. + */ + includedOnlyMeshes: AbstractMesh[]; + private _excludedMeshes; + /** + * Gets the meshes not impacted by this light. */ - abstract _disposeMesh(mesh: Mesh): void; /** - * Serializes this layer (Glow or Highlight for example) - * @returns a serialized layer object + * Sets the meshes not impacted by this light. + */ + excludedMeshes: AbstractMesh[]; + private _excludeWithLayerMask; + /** + * Gets the layer id use to find what meshes are not impacted by the light. + * Inactive if 0 */ - abstract serialize?(): any; /** - * Initializes the effect layer with the required options. - * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information) + * Sets the layer id use to find what meshes are not impacted by the light. + * Inactive if 0 + */ + excludeWithLayerMask: number; + private _includeOnlyWithLayerMask; + /** + * Gets the layer id use to find what meshes are impacted by the light. + * Inactive if 0 */ - protected _init(options: Partial): void; /** - * Generates the index buffer of the full screen quad blending to the main canvas. + * Sets the layer id use to find what meshes are impacted by the light. + * Inactive if 0 + */ + includeOnlyWithLayerMask: number; + private _lightmapMode; + /** + * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) */ - private _generateIndexBuffer(); /** - * Generates the vertex buffer of the full screen quad blending to the main canvas. + * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) + */ + lightmapMode: number; + private _parentedWorldMatrix; + /** + * Shadow generator associted to the light. + * Internal use only. */ - private _genrateVertexBuffer(); + _shadowGenerator: Nullable; /** - * Sets the main texture desired size which is the closest power of two - * of the engine canvas size. + * @hidden Internal use only. */ - private _setMainTextureSize(); + _excludedMeshesIds: string[]; /** - * Creates the main texture for the effect layer. + * @hidden Internal use only. */ - protected _createMainTexture(): void; + _includedOnlyMeshesIds: string[]; /** - * Checks for the readiness of the element composing the layer. - * @param subMesh the mesh to check for - * @param useInstances specify wether or not to use instances to render the mesh - * @param emissiveTexture the associated emissive texture used to generate the glow - * @return true if ready otherwise, false + * The current light unifom buffer. + * @hidden Internal use only. */ - protected _isReady(subMesh: SubMesh, useInstances: boolean, emissiveTexture: Nullable): boolean; + _uniformBuffer: UniformBuffer; /** - * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene. + * Creates a Light object in the scene. + * Documentation : http://doc.babylonjs.com/tutorials/lights + * @param name The firendly name of the light + * @param scene The scene the light belongs too */ - render(): void; + constructor(name: string, scene: Scene); + protected abstract _buildUniformLayout(): void; /** - * Determine if a given mesh will be used in the current effect. - * @param mesh mesh to test - * @returns true if the mesh will be used + * Sets the passed Effect "effect" with the Light information. + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The light */ - hasMesh(mesh: AbstractMesh): boolean; + abstract transferToEffect(effect: Effect, lightIndex: string): Light; /** - * Returns true if the layer contains information to display, otherwise false. - * @returns true if the glow layer should be rendered + * @hidden internal use only. */ - shouldRender(): boolean; + abstract _getWorldMatrix(): Matrix; /** - * Returns true if the mesh should render, otherwise false. - * @param mesh The mesh to render - * @returns true if it should render otherwise false + * Returns the string "Light". + * @returns the class name */ - protected _shouldRenderMesh(mesh: Mesh): boolean; + getClassName(): string; /** - * Returns true if the mesh should render, otherwise false. - * @param mesh The mesh to render - * @returns true if it should render otherwise false + * Converts the light information to a readable string for debug purpose. + * @param fullDetails Supports for multiple levels of logging within scene loading + * @returns the human readable light info */ - protected _shouldRenderEmissiveTextureForMesh(mesh: Mesh): boolean; + toString(fullDetails?: boolean): string; /** - * Renders the submesh passed in parameter to the generation map. + * Set the enabled state of this node. + * @param value - the new enabled state */ - protected _renderSubMesh(subMesh: SubMesh): void; + setEnabled(value: boolean): void; /** - * Rebuild the required buffers. - * @hidden Internal use only. + * Returns the Light associated shadow generator if any. + * @return the associated shadow generator. */ - _rebuild(): void; + getShadowGenerator(): Nullable; /** - * Dispose only the render target textures and post process. + * Returns a Vector3, the absolute light position in the World. + * @returns the world space position of the light */ - private _disposeTextureAndPostProcesses(); + getAbsolutePosition(): Vector3; /** - * Dispose the highlight layer and free resources. + * Specifies if the light will affect the passed mesh. + * @param mesh The mesh to test against the light + * @return true the mesh is affected otherwise, false. */ - dispose(): void; + canAffectMesh(mesh: AbstractMesh): boolean; /** - * Gets the class name of the effect layer - * @returns the string with the class name of the effect layer - */ - getClassName(): string; + * Computes and Returns the light World matrix. + * @returns the world matrix + */ + getWorldMatrix(): Matrix; /** - * Creates an effect layer from parsed effect layer data - * @param parsedEffectLayer defines effect layer data - * @param scene defines the current scene - * @param rootUrl defines the root URL containing the effect layer information - * @returns a parsed effect Layer + * Sort function to order lights for rendering. + * @param a First Light object to compare to second. + * @param b Second Light object to compare first. + * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b. */ - static Parse(parsedEffectLayer: any, scene: Scene, rootUrl: string): EffectLayer; - } -} - -declare module BABYLON { - interface AbstractScene { + static CompareLightsPriority(a: Light, b: Light): number; /** - * The list of effect layers (highlights/glow) added to the scene - * @see http://doc.babylonjs.com/how_to/highlight_layer - * @see http://doc.babylonjs.com/how_to/glow_layer + * Releases resources associated with this node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) */ - effectLayers: Array; + dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; /** - * Removes the given effect layer from this scene. - * @param toRemove defines the effect layer to remove - * @returns the index of the removed effect layer + * Returns the light type ID (integer). + * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x */ - removeEffectLayer(toRemove: EffectLayer): number; + getTypeID(): number; /** - * Adds the given effect layer to this scene - * @param newEffectLayer defines the effect layer to add + * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode. + * @returns the scaled intensity in intensity mode unit */ - addEffectLayer(newEffectLayer: EffectLayer): void; - } - /** - * Defines the layer scene component responsible to manage any effect layers - * in a given scene. - */ - class EffectLayerSceneComponent implements ISceneSerializableComponent { + getScaledIntensity(): number; /** - * The component name helpfull to identify the component in the list of scene components. + * Returns a new Light object, named "name", from the current one. + * @param name The name of the cloned light + * @returns the new created light */ - readonly name: string; + clone(name: string): Nullable; /** - * The scene the component belongs to. + * Serializes the current light into a Serialization object. + * @returns the serialized object. */ - scene: Scene; - private _engine; - private _renderEffects; - private _needStencil; - private _previousStencilState; + serialize(): any; /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in + * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3. + * This new light is named "name" and added to the passed scene. + * @param type Type according to the types available in Light.LIGHTTYPEID_x + * @param name The friendly name of the light + * @param scene The scene the new light will belong to + * @returns the constructor function */ - constructor(scene: Scene); + static GetConstructorFromName(type: number, name: string, scene: Scene): Nullable<() => Light>; /** - * Registers the component in a given scene + * Parses the passed "parsedLight" and returns a new instanced Light from this parsing. + * @param parsedLight The JSON representation of the light + * @param scene The scene to create the parsed light in + * @returns the created light after parsing */ - register(): void; + static Parse(parsedLight: any, scene: Scene): Nullable; + private _hookArrayForExcluded; + private _hookArrayForIncludedOnly; + private _resyncMeshes; /** - * Rebuilds the elements related to this component in case of - * context lost for instance. + * Forces the meshes to update their light related information in their rendering used effects + * @hidden Internal Use Only */ - rebuild(): void; + _markMeshesAsLightDirty(): void; /** - * Serializes the component data to the specified json object - * @param serializationObject The object to serialize to + * Recomputes the cached photometric scale if needed. */ - serialize(serializationObject: any): void; + private _computePhotometricScale; /** - * Adds all the element from the container to the scene - * @param container the container holding the elements + * Returns the Photometric Scale according to the light type and intensity mode. */ - addFromContainer(container: AbstractScene): void; + private _getPhotometricScale; /** - * Removes all the elements in the container from the scene - * @param container contains the elements to remove + * Reorder the light in the scene according to their defined priority. + * @hidden Internal Use Only */ - removeFromContainer(container: AbstractScene): void; + _reorderLightsInScene(): void; /** - * Disposes the component and the associated ressources. + * Prepares the list of defines specific to the light type. + * @param defines the list of defines + * @param lightIndex defines the index of the light for the effect */ - dispose(): void; - private _isReadyForMesh(mesh, hardwareInstancedRendering); - private _renderMainTexture(camera); - private _setStencil(camera); - private _setStencilBack(camera); - private _draw(renderingGroupId); - private _drawCamera(camera); - private _drawRenderingGroup(index); + abstract prepareLightSpecificDefines(defines: any, lightIndex: number): void; } } declare module BABYLON { - interface AbstractScene { - /** - * Return a the first highlight layer of the scene with a given name. - * @param name The name of the highlight layer to look for. - * @return The highlight layer if found otherwise null. - */ - getGlowLayerByName(name: string): Nullable; - } /** - * Glow layer options. This helps customizing the behaviour - * of the glow layer. + * A point light is a light defined by an unique point in world space. + * The light is emitted in every direction from this point. + * A good example of a point light is a standard light bulb. + * Documentation: https://doc.babylonjs.com/babylon101/lights */ - interface IGlowLayerOptions { + class PointLight extends ShadowLight { + private _shadowAngle; /** - * Multiplication factor apply to the canvas size to compute the render target size - * used to generated the glowing objects (the smaller the faster). + * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + * This specifies what angle the shadow will use to be created. + * + * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. */ - mainTextureRatio: number; /** - * Enforces a fixed size texture to ensure resize independant blur. - */ - mainTextureFixedSize?: number; + * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + * This specifies what angle the shadow will use to be created. + * + * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. + */ + shadowAngle: number; /** - * How big is the kernel of the blur texture. + * Gets the direction if it has been set. + * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback */ - blurKernelSize: number; /** - * The camera attached to the layer. - */ - camera: Nullable; + * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + */ + direction: Vector3; /** - * Enable MSAA by chosing the number of samples. + * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene. + * A PointLight emits the light in every direction. + * It can cast shadows. + * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it : + * ```javascript + * var pointLight = new BABYLON.PointLight("pl", camera.position, scene); + * ``` + * Documentation : http://doc.babylonjs.com/tutorials/lights + * @param name The light friendly name + * @param position The position of the point light in the scene + * @param scene The scene the lights belongs to */ - mainTextureSamples?: number; + constructor(name: string, position: Vector3, scene: Scene); /** - * The rendering group to draw the layer in. + * Returns the string "PointLight" + * @returns the class name */ - renderingGroupId: number; - } - /** - * The glow layer Helps adding a glow effect around the emissive parts of a mesh. - * - * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove - * glowy meshes to your scene. - * - * Documentation: https://doc.babylonjs.com/how_to/glow_layer - */ - class GlowLayer extends EffectLayer { + getClassName(): string; /** - * Effect Name of the layer. + * Returns the integer 0. + * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x */ - static readonly EffectName: string; + getTypeID(): number; /** - * The default blur kernel size used for the glow. + * Specifies wether or not the shadowmap should be a cube texture. + * @returns true if the shadowmap needs to be a cube texture. */ - static DefaultBlurKernelSize: number; + needCube(): boolean; /** - * The default texture size ratio used for the glow. + * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer). + * @param faceIndex The index of the face we are computed the direction to generate shadow + * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true */ - static DefaultTextureRatio: number; + getShadowDirection(faceIndex?: number): Vector3; /** - * Gets the kernel size of the blur. + * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings : + * - fov = PI / 2 + * - aspect ratio : 1.0 + * - z-near and far equal to the active camera minZ and maxZ. + * Returns the PointLight. */ + protected _setDefaultShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; + protected _buildUniformLayout(): void; /** - * Sets the kernel size of the blur. + * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string). + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The point light */ - blurKernelSize: number; + transferToEffect(effect: Effect, lightIndex: string): PointLight; /** - * Gets the glow intensity. + * Prepares the list of defines specific to the light type. + * @param defines the list of defines + * @param lightIndex defines the index of the light for the effect */ + prepareLightSpecificDefines(defines: any, lightIndex: number): void; + } +} + +declare module BABYLON { + /** + * Interface describing all the common properties and methods a shadow light needs to implement. + * This helps both the shadow generator and materials to genrate the corresponding shadow maps + * as well as binding the different shadow properties to the effects. + */ + interface IShadowLight extends Light { /** - * Sets the glow intensity. + * The light id in the scene (used in scene.findLighById for instance) */ - intensity: number; - private _options; - private _intensity; - private _horizontalBlurPostprocess1; - private _verticalBlurPostprocess1; - private _horizontalBlurPostprocess2; - private _verticalBlurPostprocess2; - private _blurTexture1; - private _blurTexture2; - private _postProcesses1; - private _postProcesses2; - private _includedOnlyMeshes; - private _excludedMeshes; + id: string; /** - * Callback used to let the user override the color selection on a per mesh basis + * The position the shdow will be casted from. */ - customEmissiveColorSelector: (mesh: Mesh, subMesh: SubMesh, material: Material, result: Color4) => void; + position: Vector3; /** - * Callback used to let the user override the texture selection on a per mesh basis + * In 2d mode (needCube being false), the direction used to cast the shadow. */ - customEmissiveTextureSelector: (mesh: Mesh, subMesh: SubMesh, material: Material) => Texture; + direction: Vector3; /** - * Instantiates a new glow Layer and references it to the scene. - * @param name The name of the layer - * @param scene The scene to use the layer in - * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information) + * The transformed position. Position of the light in world space taking parenting in account. */ - constructor(name: string, scene: Scene, options?: Partial); + transformedPosition: Vector3; /** - * Get the effect name of the layer. - * @return The effect name + * The transformed direction. Direction of the light in world space taking parenting in account. */ - getEffectName(): string; + transformedDirection: Vector3; /** - * Create the merge effect. This is the shader use to blit the information back - * to the main canvas at the end of the scene rendering. + * The friendly name of the light in the scene. */ - protected _createMergeEffect(): Effect; + name: string; /** - * Creates the render target textures and post processes used in the glow layer. + * Defines the shadow projection clipping minimum z value. */ - protected _createTextureAndPostProcesses(): void; + shadowMinZ: number; /** - * Checks for the readiness of the element composing the layer. - * @param subMesh the mesh to check for - * @param useInstances specify wether or not to use instances to render the mesh - * @param emissiveTexture the associated emissive texture used to generate the glow - * @return true if ready otherwise, false + * Defines the shadow projection clipping maximum z value. */ - isReady(subMesh: SubMesh, useInstances: boolean): boolean; + shadowMaxZ: number; /** - * Returns wether or nood the layer needs stencil enabled during the mesh rendering. + * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light + * @returns true if the information has been computed, false if it does not need to (no parenting) */ - needStencil(): boolean; + computeTransformedInformation(): boolean; /** - * Implementation specific of rendering the generating effect on the main canvas. - * @param effect The effect used to render through + * Gets the scene the light belongs to. + * @returns The scene */ - protected _internalRender(effect: Effect): void; + getScene(): Scene; /** - * Sets the required values for both the emissive texture and and the main color. + * Callback defining a custom Projection Matrix Builder. + * This can be used to override the default projection matrix computation. */ - protected _setEmissiveTextureAndColor(mesh: Mesh, subMesh: SubMesh, material: Material): void; + customProjectionMatrixBuilder: (viewMatrix: Matrix, renderList: Array, result: Matrix) => void; /** - * Returns true if the mesh should render, otherwise false. - * @param mesh The mesh to render - * @returns true if it should render otherwise false + * Sets the shadow projection matrix in parameter to the generated projection matrix. + * @param matrix The materix to updated with the projection information + * @param viewMatrix The transform matrix of the light + * @param renderList The list of mesh to render in the map + * @returns The current light */ - protected _shouldRenderMesh(mesh: Mesh): boolean; + setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): IShadowLight; /** - * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer. - * @param mesh The mesh to exclude from the glow layer + * Gets the current depth scale used in ESM. + * @returns The scale */ - addExcludedMesh(mesh: Mesh): void; - /** - * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer. - * @param mesh The mesh to remove - */ - removeExcludedMesh(mesh: Mesh): void; + getDepthScale(): number; /** - * Add a mesh in the inclusion list to impact or being impacted by the glow layer. - * @param mesh The mesh to include in the glow layer + * Returns whether or not the shadow generation require a cube texture or a 2d texture. + * @returns true if a cube texture needs to be use */ - addIncludedOnlyMesh(mesh: Mesh): void; - /** - * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer. - * @param mesh The mesh to remove - */ - removeIncludedOnlyMesh(mesh: Mesh): void; + needCube(): boolean; /** - * Determine if a given mesh will be used in the glow layer - * @param mesh The mesh to test - * @returns true if the mesh will be highlighted by the current glow layer + * Detects if the projection matrix requires to be recomputed this frame. + * @returns true if it requires to be recomputed otherwise, false. */ - hasMesh(mesh: AbstractMesh): boolean; + needProjectionMatrixCompute(): boolean; /** - * Free any resources and references associated to a mesh. - * Internal use - * @param mesh The mesh to free. + * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed. */ - _disposeMesh(mesh: Mesh): void; + forceProjectionMatrixCompute(): void; /** - * Gets the class name of the effect layer - * @returns the string with the class name of the effect layer - */ - getClassName(): string; + * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed. + * @param faceIndex The index of the face we are computed the direction to generate shadow + * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true + */ + getShadowDirection(faceIndex?: number): Vector3; /** - * Serializes this glow layer - * @returns a serialized glow layer object + * Gets the minZ used for shadow according to both the scene and the light. + * @param activeCamera The camera we are returning the min for + * @returns the depth min z */ - serialize(): any; + getDepthMinZ(activeCamera: Camera): number; /** - * Creates a Glow Layer from parsed glow layer data - * @param parsedGlowLayer defines glow layer data - * @param scene defines the current scene - * @param rootUrl defines the root URL containing the glow layer information - * @returns a parsed Glow Layer + * Gets the maxZ used for shadow according to both the scene and the light. + * @param activeCamera The camera we are returning the max for + * @returns the depth max z */ - static Parse(parsedGlowLayer: any, scene: Scene, rootUrl: string): GlowLayer; - } -} - -declare module BABYLON { - interface AbstractScene { - /** - * Return a the first highlight layer of the scene with a given name. - * @param name The name of the highlight layer to look for. - * @return The highlight layer if found otherwise null. - */ - getHighlightLayerByName(name: string): Nullable; + getDepthMaxZ(activeCamera: Camera): number; } /** - * Highlight layer options. This helps customizing the behaviour - * of the highlight layer. + * Base implementation IShadowLight + * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern. */ - interface IHighlightLayerOptions { + abstract class ShadowLight extends Light implements IShadowLight { + protected abstract _setDefaultShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; + protected _position: Vector3; + protected _setPosition(value: Vector3): void; /** - * Multiplication factor apply to the canvas size to compute the render target size - * used to generated the glowing objects (the smaller the faster). + * Sets the position the shadow will be casted from. Also use as the light position for both + * point and spot lights. */ - mainTextureRatio: number; /** - * Enforces a fixed size texture to ensure resize independant blur. + * Sets the position the shadow will be casted from. Also use as the light position for both + * point and spot lights. + */ + position: Vector3; + protected _direction: Vector3; + protected _setDirection(value: Vector3): void; + /** + * In 2d mode (needCube being false), gets the direction used to cast the shadow. + * Also use as the light direction on spot and directional lights. */ - mainTextureFixedSize?: number; /** - * Multiplication factor apply to the main texture size in the first step of the blur to reduce the size - * of the picture to blur (the smaller the faster). + * In 2d mode (needCube being false), sets the direction used to cast the shadow. + * Also use as the light direction on spot and directional lights. + */ + direction: Vector3; + private _shadowMinZ; + /** + * Gets the shadow projection clipping minimum z value. */ - blurTextureSizeRatio: number; /** - * How big in texel of the blur texture is the vertical blur. + * Sets the shadow projection clipping minimum z value. + */ + shadowMinZ: number; + private _shadowMaxZ; + /** + * Sets the shadow projection clipping maximum z value. */ - blurVerticalSize: number; /** - * How big in texel of the blur texture is the horizontal blur. + * Gets the shadow projection clipping maximum z value. + */ + shadowMaxZ: number; + /** + * Callback defining a custom Projection Matrix Builder. + * This can be used to override the default projection matrix computation. */ - blurHorizontalSize: number; + customProjectionMatrixBuilder: (viewMatrix: Matrix, renderList: Array, result: Matrix) => void; /** - * Alpha blending mode used to apply the blur. Default is combine. + * The transformed position. Position of the light in world space taking parenting in account. */ - alphaBlendingMode: number; + transformedPosition: Vector3; /** - * The camera attached to the layer. + * The transformed direction. Direction of the light in world space taking parenting in account. */ - camera: Nullable; + transformedDirection: Vector3; + private _worldMatrix; + private _needProjectionMatrixCompute; /** - * Should we display highlight as a solid stroke? + * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light + * @returns true if the information has been computed, false if it does not need to (no parenting) */ - isStroke?: boolean; + computeTransformedInformation(): boolean; /** - * The rendering group to draw the layer in. + * Return the depth scale used for the shadow map. + * @returns the depth scale. */ - renderingGroupId: number; - } - /** - * The highlight layer Helps adding a glow effect around a mesh. - * - * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove - * glowy meshes to your scene. - * - * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!! - */ - class HighlightLayer extends EffectLayer { - name: string; + getDepthScale(): number; /** - * Effect Name of the highlight layer. + * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed. + * @param faceIndex The index of the face we are computed the direction to generate shadow + * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true */ - static readonly EffectName: string; + getShadowDirection(faceIndex?: number): Vector3; /** - * The neutral color used during the preparation of the glow effect. - * This is black by default as the blend operation is a blend operation. + * Returns the ShadowLight absolute position in the World. + * @returns the position vector in world space */ - static NeutralColor: Color4; + getAbsolutePosition(): Vector3; /** - * Stencil value used for glowing meshes. + * Sets the ShadowLight direction toward the passed target. + * @param target The point tot target in local space + * @returns the updated ShadowLight direction */ - static GlowingMeshStencilReference: number; + setDirectionToTarget(target: Vector3): Vector3; /** - * Stencil value used for the other meshes in the scene. + * Returns the light rotation in euler definition. + * @returns the x y z rotation in local space. */ - static NormalMeshStencilReference: number; + getRotation(): Vector3; /** - * Specifies whether or not the inner glow is ACTIVE in the layer. + * Returns whether or not the shadow generation require a cube texture or a 2d texture. + * @returns true if a cube texture needs to be use */ - innerGlow: boolean; + needCube(): boolean; /** - * Specifies whether or not the outer glow is ACTIVE in the layer. + * Detects if the projection matrix requires to be recomputed this frame. + * @returns true if it requires to be recomputed otherwise, false. */ - outerGlow: boolean; + needProjectionMatrixCompute(): boolean; /** - * Gets the horizontal size of the blur. + * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed. */ + forceProjectionMatrixCompute(): void; /** - * Specifies the horizontal size of the blur. + * Get the world matrix of the sahdow lights. + * @hidden Internal Use Only */ - blurHorizontalSize: number; + _getWorldMatrix(): Matrix; /** - * Gets the vertical size of the blur. + * Gets the minZ used for shadow according to both the scene and the light. + * @param activeCamera The camera we are returning the min for + * @returns the depth min z */ + getDepthMinZ(activeCamera: Camera): number; /** - * Specifies the vertical size of the blur. + * Gets the maxZ used for shadow according to both the scene and the light. + * @param activeCamera The camera we are returning the max for + * @returns the depth max z */ - blurVerticalSize: number; + getDepthMaxZ(activeCamera: Camera): number; /** - * An event triggered when the highlight layer is being blurred. + * Sets the shadow projection matrix in parameter to the generated projection matrix. + * @param matrix The materix to updated with the projection information + * @param viewMatrix The transform matrix of the light + * @param renderList The list of mesh to render in the map + * @returns The current light */ - onBeforeBlurObservable: Observable; + setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): IShadowLight; + } +} + +declare module BABYLON { + /** + * A spot light is defined by a position, a direction, an angle, and an exponent. + * These values define a cone of light starting from the position, emitting toward the direction. + * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam, + * and the exponent defines the speed of the decay of the light with distance (reach). + * Documentation: https://doc.babylonjs.com/babylon101/lights + */ + class SpotLight extends ShadowLight { + private _angle; /** - * An event triggered when the highlight layer has been blurred. + * Gets the cone angle of the spot light in Radians. */ - onAfterBlurObservable: Observable; - private _instanceGlowingMeshStencilReference; - private _options; - private _downSamplePostprocess; - private _horizontalBlurPostprocess; - private _verticalBlurPostprocess; - private _blurTexture; - private _meshes; - private _excludedMeshes; /** - * Instantiates a new highlight Layer and references it to the scene.. - * @param name The name of the layer - * @param scene The scene to use the layer in - * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information) + * Sets the cone angle of the spot light in Radians. + */ + angle: number; + private _shadowAngleScale; + /** + * Allows scaling the angle of the light for shadow generation only. */ - constructor(name: string, scene: Scene, options?: Partial); /** - * Get the effect name of the layer. - * @return The effect name + * Allows scaling the angle of the light for shadow generation only. + */ + shadowAngleScale: number; + /** + * The light decay speed with the distance from the emission spot. */ - getEffectName(): string; + exponent: number; + private _projectionTextureMatrix; /** - * Create the merge effect. This is the shader use to blit the information back - * to the main canvas at the end of the scene rendering. + * Allows reading the projecton texture + */ + readonly projectionTextureMatrix: Matrix; + protected _projectionTextureLightNear: number; + /** + * Gets the near clip of the Spotlight for texture projection. */ - protected _createMergeEffect(): Effect; /** - * Creates the render target textures and post processes used in the highlight layer. + * Sets the near clip of the Spotlight for texture projection. + */ + projectionTextureLightNear: number; + protected _projectionTextureLightFar: number; + /** + * Gets the far clip of the Spotlight for texture projection. */ - protected _createTextureAndPostProcesses(): void; /** - * Returns wether or nood the layer needs stencil enabled during the mesh rendering. + * Sets the far clip of the Spotlight for texture projection. + */ + projectionTextureLightFar: number; + protected _projectionTextureUpDirection: Vector3; + /** + * Gets the Up vector of the Spotlight for texture projection. */ - needStencil(): boolean; /** - * Checks for the readiness of the element composing the layer. - * @param subMesh the mesh to check for - * @param useInstances specify wether or not to use instances to render the mesh - * @param emissiveTexture the associated emissive texture used to generate the glow - * @return true if ready otherwise, false + * Sets the Up vector of the Spotlight for texture projection. + */ + projectionTextureUpDirection: Vector3; + private _projectionTexture; + /** + * Gets the projection texture of the light. + */ + /** + * Sets the projection texture of the light. + */ + projectionTexture: Nullable; + private _projectionTextureViewLightDirty; + private _projectionTextureProjectionLightDirty; + private _projectionTextureDirty; + private _projectionTextureViewTargetVector; + private _projectionTextureViewLightMatrix; + private _projectionTextureProjectionLightMatrix; + private _projectionTextureScalingMatrix; + /** + * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone. + * It can cast shadows. + * Documentation : http://doc.babylonjs.com/tutorials/lights + * @param name The light friendly name + * @param position The position of the spot light in the scene + * @param direction The direction of the light in the scene + * @param angle The cone angle of the light in Radians + * @param exponent The light decay speed with the distance from the emission spot + * @param scene The scene the lights belongs to */ - isReady(subMesh: SubMesh, useInstances: boolean): boolean; + constructor(name: string, position: Vector3, direction: Vector3, angle: number, exponent: number, scene: Scene); /** - * Implementation specific of rendering the generating effect on the main canvas. - * @param effect The effect used to render through + * Returns the string "SpotLight". + * @returns the class name */ - protected _internalRender(effect: Effect): void; + getClassName(): string; /** - * Returns true if the layer contains information to display, otherwise false. + * Returns the integer 2. + * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x */ - shouldRender(): boolean; + getTypeID(): number; /** - * Returns true if the mesh should render, otherwise false. - * @param mesh The mesh to render - * @returns true if it should render otherwise false + * Overrides the direction setter to recompute the projection texture view light Matrix. */ - protected _shouldRenderMesh(mesh: Mesh): boolean; + protected _setDirection(value: Vector3): void; /** - * Sets the required values for both the emissive texture and and the main color. + * Overrides the position setter to recompute the projection texture view light Matrix. */ - protected _setEmissiveTextureAndColor(mesh: Mesh, subMesh: SubMesh, material: Material): void; + protected _setPosition(value: Vector3): void; /** - * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer. - * @param mesh The mesh to exclude from the highlight layer + * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0. + * Returns the SpotLight. */ - addExcludedMesh(mesh: Mesh): void; + protected _setDefaultShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; + protected _computeProjectionTextureViewLightMatrix(): void; + protected _computeProjectionTextureProjectionLightMatrix(): void; /** - * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer. - * @param mesh The mesh to highlight - */ - removeExcludedMesh(mesh: Mesh): void; + * Main function for light texture projection matrix computing. + */ + protected _computeProjectionTextureMatrix(): void; + protected _buildUniformLayout(): void; /** - * Determine if a given mesh will be highlighted by the current HighlightLayer - * @param mesh mesh to test - * @returns true if the mesh will be highlighted by the current HighlightLayer + * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction. + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The spot light */ - hasMesh(mesh: AbstractMesh): boolean; + transferToEffect(effect: Effect, lightIndex: string): SpotLight; /** - * Add a mesh in the highlight layer in order to make it glow with the chosen color. - * @param mesh The mesh to highlight - * @param color The color of the highlight - * @param glowEmissiveOnly Extract the glow from the emissive texture + * Disposes the light and the associated resources. */ - addMesh(mesh: Mesh, color: Color3, glowEmissiveOnly?: boolean): void; + dispose(): void; /** - * Remove a mesh from the highlight layer in order to make it stop glowing. - * @param mesh The mesh to highlight + * Prepares the list of defines specific to the light type. + * @param defines the list of defines + * @param lightIndex defines the index of the light for the effect */ - removeMesh(mesh: Mesh): void; + prepareLightSpecificDefines(defines: any, lightIndex: number): void; + } +} + +declare module BABYLON { + class Scalar { /** - * Force the stencil to the normal expected value for none glowing parts + * Two pi constants convenient for computation. */ - private _defaultStencilReference(mesh); + static TwoPi: number; /** - * Free any resources and references associated to a mesh. - * Internal use - * @param mesh The mesh to free. + * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45) */ - _disposeMesh(mesh: Mesh): void; + static WithinEpsilon(a: number, b: number, epsilon?: number): boolean; /** - * Dispose the highlight layer and free resources. + * Returns a string : the upper case translation of the number i to hexadecimal. */ - dispose(): void; + static ToHex(i: number): string; /** - * Gets the class name of the effect layer - * @returns the string with the class name of the effect layer - */ - getClassName(): string; + * Returns -1 if value is negative and +1 is value is positive. + * Returns the value itself if it's equal to zero. + */ + static Sign(value: number): number; /** - * Serializes this Highlight layer - * @returns a serialized Highlight layer object + * Returns the value itself if it's between min and max. + * Returns min if the value is lower than min. + * Returns max if the value is greater than max. */ - serialize(): any; + static Clamp(value: number, min?: number, max?: number): number; /** - * Creates a Highlight layer from parsed Highlight layer data - * @param parsedHightlightLayer defines the Highlight layer data - * @param scene defines the current scene - * @param rootUrl defines the root URL containing the Highlight layer information - * @returns a parsed Highlight layer + * Returns the log2 of value. */ - static Parse(parsedHightlightLayer: any, scene: Scene, rootUrl: string): HighlightLayer; - } -} - -declare module BABYLON { - class Layer { - name: string; - texture: Nullable; - isBackground: boolean; - color: Color4; - scale: Vector2; - offset: Vector2; - alphaBlendingMode: number; - alphaTest: boolean; - layerMask: number; - private _scene; - private _vertexBuffers; - private _indexBuffer; - private _effect; - private _alphaTestEffect; + static Log2(value: number): number; /** - * An event triggered when the layer is disposed. + * Loops the value, so that it is never larger than length and never smaller than 0. + * + * This is similar to the modulo operator but it works with floating point numbers. + * For example, using 3.0 for t and 2.5 for length, the result would be 0.5. + * With t = 5 and length = 2.5, the result would be 0.0. + * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator */ - onDisposeObservable: Observable; - private _onDisposeObserver; - onDispose: () => void; + static Repeat(value: number, length: number): number; /** - * An event triggered before rendering the scene + * Normalize the value between 0.0 and 1.0 using min and max values */ - onBeforeRenderObservable: Observable; - private _onBeforeRenderObserver; - onBeforeRender: () => void; + static Normalize(value: number, min: number, max: number): number; /** - * An event triggered after rendering the scene + * Denormalize the value from 0.0 and 1.0 using min and max values */ - onAfterRenderObservable: Observable; - private _onAfterRenderObserver; - onAfterRender: () => void; - constructor(name: string, imgUrl: Nullable, scene: Nullable, isBackground?: boolean, color?: Color4); - private _createIndexBuffer(); - _rebuild(): void; - render(): void; - dispose(): void; + static Denormalize(normalized: number, min: number, max: number): number; + /** + * Calculates the shortest difference between two given angles given in degrees. + */ + static DeltaAngle(current: number, target: number): number; + /** + * PingPongs the value t, so that it is never larger than length and never smaller than 0. + * + * The returned value will move back and forth between 0 and length + */ + static PingPong(tx: number, length: number): number; + /** + * Interpolates between min and max with smoothing at the limits. + * + * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up + * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions. + */ + static SmoothStep(from: number, to: number, tx: number): number; + /** + * Moves a value current towards target. + * + * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta. + * Negative values of maxDelta pushes the value away from target. + */ + static MoveTowards(current: number, target: number, maxDelta: number): number; + /** + * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees. + * + * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta + * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead. + */ + static MoveTowardsAngle(current: number, target: number, maxDelta: number): number; + /** + * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar. + */ + static Lerp(start: number, end: number, amount: number): number; + /** + * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees. + * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees. + */ + static LerpAngle(start: number, end: number, amount: number): number; + /** + * Calculates the linear parameter t that produces the interpolant value within the range [a, b]. + */ + static InverseLerp(a: number, b: number, value: number): number; + /** + * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2". + */ + static Hermite(value1: number, tangent1: number, value2: number, tangent2: number, amount: number): number; + /** + * Returns a random float number between and min and max values + */ + static RandomRange(min: number, max: number): number; + /** + * This function returns percentage of a number in a given range. + * + * RangeToPercent(40,20,60) will return 0.5 (50%) + * RangeToPercent(34,0,100) will return 0.34 (34%) + */ + static RangeToPercent(number: number, min: number, max: number): number; + /** + * This function returns number that corresponds to the percentage in a given range. + * + * PercentToRange(0.34,0,100) will return 34. + */ + static PercentToRange(percent: number, min: number, max: number): number; + /** + * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians. + * @param angle The angle to normalize in radian. + * @return The converted angle. + */ + static NormalizeRadians(angle: number): number; } } declare module BABYLON { - interface AbstractScene { - /** - * The list of layers (background and foreground) of the scene - */ - layers: Array; - } + const ToGammaSpace: number; + const ToLinearSpace = 2.2; + const Epsilon = 0.001; /** - * Defines the layer scene component responsible to manage any layers - * in a given scene. + * Class used to hold a RBG color */ - class LayerSceneComponent implements ISceneComponent { + class Color3 { /** - * The component name helpfull to identify the component in the list of scene components. + * Defines the red component (between 0 and 1, default is 0) */ - readonly name: string; + r: number; /** - * The scene the component belongs to. + * Defines the green component (between 0 and 1, default is 0) */ - scene: Scene; - private _engine; + g: number; /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in + * Defines the blue component (between 0 and 1, default is 0) */ - constructor(scene: Scene); + b: number; /** - * Registers the component in a given scene + * Creates a new Color3 object from red, green, blue values, all between 0 and 1 + * @param r defines the red component (between 0 and 1, default is 0) + * @param g defines the green component (between 0 and 1, default is 0) + * @param b defines the blue component (between 0 and 1, default is 0) */ - register(): void; + constructor( /** - * Rebuilds the elements related to this component in case of - * context lost for instance. + * Defines the red component (between 0 and 1, default is 0) */ - rebuild(): void; + r?: number, /** - * Disposes the component and the associated ressources. + * Defines the green component (between 0 and 1, default is 0) */ - dispose(): void; - private _draw(camera, isBackground); - private _drawBackground(camera); - private _drawForeground(camera); - } -} - -declare module BABYLON { - interface ILoadingScreen { - displayLoadingUI: () => void; - hideLoadingUI: () => void; - loadingUIBackgroundColor: string; - loadingUIText: string; - } - class DefaultLoadingScreen implements ILoadingScreen { - private _renderingCanvas; - private _loadingText; - private _loadingDivBackgroundColor; - private _loadingDiv; - private _loadingTextDiv; - constructor(_renderingCanvas: HTMLCanvasElement, _loadingText?: string, _loadingDivBackgroundColor?: string); - displayLoadingUI(): void; - hideLoadingUI(): void; - loadingUIText: string; - loadingUIBackgroundColor: string; - private _resizeLoadingUI; - } -} - -declare module BABYLON { - class SceneLoaderProgressEvent { - readonly lengthComputable: boolean; - readonly loaded: number; - readonly total: number; - constructor(lengthComputable: boolean, loaded: number, total: number); - static FromProgressEvent(event: ProgressEvent): SceneLoaderProgressEvent; - } - interface ISceneLoaderPluginExtensions { - [extension: string]: { - isBinary: boolean; - }; - } - interface ISceneLoaderPluginFactory { - name: string; - createPlugin(): ISceneLoaderPlugin | ISceneLoaderPluginAsync; - canDirectLoad?: (data: string) => boolean; - } - interface ISceneLoaderPlugin { - /** - * The friendly name of this plugin. - */ - name: string; - /** - * The file extensions supported by this plugin. - */ - extensions: string | ISceneLoaderPluginExtensions; - /** - * Import meshes into a scene. - * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported - * @param scene The scene to import into - * @param data The data to import - * @param rootUrl The root url for scene and resources - * @param meshes The meshes array to import into - * @param particleSystems The particle systems array to import into - * @param skeletons The skeletons array to import into - * @param onError The callback when import fails - * @returns True if successful or false otherwise - */ - importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], onError?: (message: string, exception?: any) => void): boolean; - /** - * Load into a scene. - * @param scene The scene to load into - * @param data The data to import - * @param rootUrl The root url for scene and resources - * @param onError The callback when import fails - * @returns true if successful or false otherwise - */ - load(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): boolean; - /** - * The callback that returns true if the data can be directly loaded. - */ - canDirectLoad?: (data: string) => boolean; - /** - * The callback that allows custom handling of the root url based on the response url. - */ - rewriteRootURL?: (rootUrl: string, responseURL?: string) => string; - /** - * Load into an asset container. - * @param scene The scene to load into - * @param data The data to import - * @param rootUrl The root url for scene and resources - * @param onError The callback when import fails - * @returns The loaded asset container - */ - loadAssetContainer(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer; - } - interface ISceneLoaderPluginAsync { - /** - * The friendly name of this plugin. - */ - name: string; - /** - * The file extensions supported by this plugin. - */ - extensions: string | ISceneLoaderPluginExtensions; - /** - * Import meshes into a scene. - * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported - * @param scene The scene to import into - * @param data The data to import - * @param rootUrl The root url for scene and resources - * @param onProgress The callback when the load progresses - * @returns The loaded meshes, particle systems, skeletons, and animation groups - */ - importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{ - meshes: AbstractMesh[]; - particleSystems: IParticleSystem[]; - skeletons: Skeleton[]; - animationGroups: AnimationGroup[]; - }>; - /** - * Load into a scene. - * @param scene The scene to load into - * @param data The data to import - * @param rootUrl The root url for scene and resources - * @param onProgress The callback when the load progresses - * @returns Nothing - */ - loadAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise; - /** - * The callback that returns true if the data can be directly loaded. - */ - canDirectLoad?: (data: string) => boolean; - /** - * The callback that allows custom handling of the root url based on the response url. - */ - rewriteRootURL?: (rootUrl: string, responseURL?: string) => string; - /** - * Load into an asset container. - * @param scene The scene to load into - * @param data The data to import - * @param rootUrl The root url for scene and resources - * @param onProgress The callback when the load progresses - * @returns The loaded asset container - */ - loadAssetContainerAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise; - } - class SceneLoader { - private static _ForceFullSceneLoadingForIncremental; - private static _ShowLoadingScreen; - private static _CleanBoneMatrixWeights; - static readonly NO_LOGGING: number; - static readonly MINIMAL_LOGGING: number; - static readonly SUMMARY_LOGGING: number; - static readonly DETAILED_LOGGING: number; - private static _loggingLevel; - static ForceFullSceneLoadingForIncremental: boolean; - static ShowLoadingScreen: boolean; - static loggingLevel: number; - static CleanBoneMatrixWeights: boolean; - static OnPluginActivatedObservable: Observable; - private static _registeredPlugins; - private static _getDefaultPlugin(); - private static _getPluginForExtension(extension); - private static _getPluginForDirectLoad(data); - private static _getPluginForFilename(sceneFilename); - private static _getDirectLoad(sceneFilename); - private static _loadData(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension); - static GetPluginForExtension(extension: string): ISceneLoaderPlugin | ISceneLoaderPluginAsync | ISceneLoaderPluginFactory; - static IsPluginForExtensionAvailable(extension: string): boolean; - static RegisterPlugin(plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync): void; - /** - * Import meshes into a scene - * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported - * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) - * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) - * @param scene the instance of BABYLON.Scene to append to - * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds - * @param onProgress a callback with a progress event for each file being loaded - * @param onError a callback with the scene, a message, and possibly an exception when import fails - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded plugin - */ - static ImportMesh(meshNames: any, rootUrl: string, sceneFilename?: any, scene?: Nullable, onSuccess?: Nullable<(meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[]) => void>, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, onError?: Nullable<(scene: Scene, message: string, exception?: any) => void>, pluginExtension?: Nullable): Nullable; - /** - * Import meshes into a scene - * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported - * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) - * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) - * @param scene the instance of BABYLON.Scene to append to - * @param onProgress a callback with a progress event for each file being loaded - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups - */ - static ImportMeshAsync(meshNames: any, rootUrl: string, sceneFilename?: any, scene?: Nullable, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, pluginExtension?: Nullable): Promise<{ - meshes: AbstractMesh[]; - particleSystems: IParticleSystem[]; - skeletons: Skeleton[]; - animationGroups: AnimationGroup[]; - }>; - /** - * Load a scene - * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) - * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) - * @param engine is the instance of BABYLON.Engine to use to create the scene - * @param onSuccess a callback with the scene when import succeeds - * @param onProgress a callback with a progress event for each file being loaded - * @param onError a callback with the scene, a message, and possibly an exception when import fails - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded plugin - */ - static Load(rootUrl: string, sceneFilename: any, engine: Engine, onSuccess?: Nullable<(scene: Scene) => void>, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, onError?: Nullable<(scene: Scene, message: string, exception?: any) => void>, pluginExtension?: Nullable): Nullable; - /** - * Load a scene - * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) - * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) - * @param engine is the instance of BABYLON.Engine to use to create the scene - * @param onProgress a callback with a progress event for each file being loaded - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded scene - */ - static LoadAsync(rootUrl: string, sceneFilename: any, engine: Engine, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, pluginExtension?: Nullable): Promise; - /** - * Append a scene - * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) - * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) - * @param scene is the instance of BABYLON.Scene to append to - * @param onSuccess a callback with the scene when import succeeds - * @param onProgress a callback with a progress event for each file being loaded - * @param onError a callback with the scene, a message, and possibly an exception when import fails - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded plugin - */ - static Append(rootUrl: string, sceneFilename?: any, scene?: Nullable, onSuccess?: Nullable<(scene: Scene) => void>, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, onError?: Nullable<(scene: Scene, message: string, exception?: any) => void>, pluginExtension?: Nullable): Nullable; - /** - * Append a scene - * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) - * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) - * @param scene is the instance of BABYLON.Scene to append to - * @param onProgress a callback with a progress event for each file being loaded - * @param pluginExtension the extension used to determine the plugin - * @returns The given scene - */ - static AppendAsync(rootUrl: string, sceneFilename?: any, scene?: Nullable, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, pluginExtension?: Nullable): Promise; - /** - * Load a scene into an asset container - * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) - * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) - * @param scene is the instance of BABYLON.Scene to append to (default: last created scene) - * @param onSuccess a callback with the scene when import succeeds - * @param onProgress a callback with a progress event for each file being loaded - * @param onError a callback with the scene, a message, and possibly an exception when import fails - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded plugin - */ - static LoadAssetContainer(rootUrl: string, sceneFilename?: any, scene?: Nullable, onSuccess?: Nullable<(assets: AssetContainer) => void>, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, onError?: Nullable<(scene: Scene, message: string, exception?: any) => void>, pluginExtension?: Nullable): Nullable; - /** - * Load a scene into an asset container - * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb) - * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string) - * @param scene is the instance of BABYLON.Scene to append to - * @param onProgress a callback with a progress event for each file being loaded - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded asset container - */ - static LoadAssetContainerAsync(rootUrl: string, sceneFilename?: any, scene?: Nullable, onProgress?: Nullable<(event: SceneLoaderProgressEvent) => void>, pluginExtension?: Nullable): Promise; - } -} - -declare module BABYLON { - class Scalar { - /** - * Two pi constants convenient for computation. - */ - static TwoPi: number; - /** - * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45) - */ - static WithinEpsilon(a: number, b: number, epsilon?: number): boolean; - /** - * Returns a string : the upper case translation of the number i to hexadecimal. - */ - static ToHex(i: number): string; - /** - * Returns -1 if value is negative and +1 is value is positive. - * Returns the value itself if it's equal to zero. - */ - static Sign(value: number): number; - /** - * Returns the value itself if it's between min and max. - * Returns min if the value is lower than min. - * Returns max if the value is greater than max. - */ - static Clamp(value: number, min?: number, max?: number): number; - /** - * Returns the log2 of value. - */ - static Log2(value: number): number; - /** - * Loops the value, so that it is never larger than length and never smaller than 0. - * - * This is similar to the modulo operator but it works with floating point numbers. - * For example, using 3.0 for t and 2.5 for length, the result would be 0.5. - * With t = 5 and length = 2.5, the result would be 0.0. - * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator - */ - static Repeat(value: number, length: number): number; - /** - * Normalize the value between 0.0 and 1.0 using min and max values - */ - static Normalize(value: number, min: number, max: number): number; - /** - * Denormalize the value from 0.0 and 1.0 using min and max values - */ - static Denormalize(normalized: number, min: number, max: number): number; - /** - * Calculates the shortest difference between two given angles given in degrees. - */ - static DeltaAngle(current: number, target: number): number; - /** - * PingPongs the value t, so that it is never larger than length and never smaller than 0. - * - * The returned value will move back and forth between 0 and length - */ - static PingPong(tx: number, length: number): number; - /** - * Interpolates between min and max with smoothing at the limits. - * - * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up - * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions. - */ - static SmoothStep(from: number, to: number, tx: number): number; - /** - * Moves a value current towards target. - * - * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta. - * Negative values of maxDelta pushes the value away from target. - */ - static MoveTowards(current: number, target: number, maxDelta: number): number; - /** - * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees. - * - * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta - * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead. - */ - static MoveTowardsAngle(current: number, target: number, maxDelta: number): number; - /** - * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar. - */ - static Lerp(start: number, end: number, amount: number): number; - /** - * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees. - * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees. - */ - static LerpAngle(start: number, end: number, amount: number): number; - /** - * Calculates the linear parameter t that produces the interpolant value within the range [a, b]. - */ - static InverseLerp(a: number, b: number, value: number): number; - /** - * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2". - */ - static Hermite(value1: number, tangent1: number, value2: number, tangent2: number, amount: number): number; - /** - * Returns a random float number between and min and max values - */ - static RandomRange(min: number, max: number): number; - /** - * This function returns percentage of a number in a given range. - * - * RangeToPercent(40,20,60) will return 0.5 (50%) - * RangeToPercent(34,0,100) will return 0.34 (34%) - */ - static RangeToPercent(number: number, min: number, max: number): number; - /** - * This function returns number that corresponds to the percentage in a given range. - * - * PercentToRange(0.34,0,100) will return 34. - */ - static PercentToRange(percent: number, min: number, max: number): number; - /** - * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians. - * @param angle The angle to normalize in radian. - * @return The converted angle. - */ - static NormalizeRadians(angle: number): number; - } -} - -declare module BABYLON { - const ToGammaSpace: number; - const ToLinearSpace = 2.2; - const Epsilon = 0.001; - /** - * Class used to hold a RBG color - */ - class Color3 { - /** - * Defines the red component (between 0 and 1, default is 0) - */ - r: number; - /** - * Defines the green component (between 0 and 1, default is 0) - */ - g: number; + g?: number, /** * Defines the blue component (between 0 and 1, default is 0) */ - b: number; - /** - * Creates a new Color3 object from red, green, blue values, all between 0 and 1 - * @param r defines the red component (between 0 and 1, default is 0) - * @param g defines the green component (between 0 and 1, default is 0) - * @param b defines the blue component (between 0 and 1, default is 0) - */ - constructor( - /** - * Defines the red component (between 0 and 1, default is 0) - */ - r?: number, - /** - * Defines the green component (between 0 and 1, default is 0) - */ - g?: number, - /** - * Defines the blue component (between 0 and 1, default is 0) - */ - b?: number); + b?: number); /** * Creates a string with the Color3 current values * @returns the string representation of the Color3 object @@ -13307,22 +13310,22 @@ declare module BABYLON { * @param a defines the alpha component (between 0 and 1, default is 1) */ constructor( - /** - * Defines the red component (between 0 and 1, default is 0) - */ - r?: number, - /** - * Defines the green component (between 0 and 1, default is 0) - */ - g?: number, - /** - * Defines the blue component (between 0 and 1, default is 0) - */ - b?: number, - /** - * Defines the alpha component (between 0 and 1, default is 1) - */ - a?: number); + /** + * Defines the red component (between 0 and 1, default is 0) + */ + r?: number, + /** + * Defines the green component (between 0 and 1, default is 0) + */ + g?: number, + /** + * Defines the blue component (between 0 and 1, default is 0) + */ + b?: number, + /** + * Defines the alpha component (between 0 and 1, default is 1) + */ + a?: number); /** * Adds in place the given Color4 values to the current Color4 object * @param right defines the second operand @@ -13533,10 +13536,10 @@ declare module BABYLON { * @param y defines the second coordinate */ constructor( - /** defines the first coordinate */ - x?: number, - /** defines the second coordinate */ - y?: number); + /** defines the first coordinate */ + x?: number, + /** defines the second coordinate */ + y?: number); /** * Gets a string with the Vector2 coordinates * @returns a string with the Vector2 coordinates @@ -13915,18 +13918,18 @@ declare module BABYLON { * @param z defines the third coordinates (on Z axis) */ constructor( - /** - * Defines the first coordinates (on X axis) - */ - x?: number, - /** - * Defines the second coordinates (on Y axis) - */ - y?: number, - /** - * Defines the third coordinates (on Z axis) - */ - z?: number); + /** + * Defines the first coordinates (on X axis) + */ + x?: number, + /** + * Defines the second coordinates (on Y axis) + */ + y?: number, + /** + * Defines the third coordinates (on Z axis) + */ + z?: number); /** * Creates a string representation of the Vector3 * @returns a string with the Vector3 coordinates. @@ -14871,14 +14874,14 @@ declare module BABYLON { * @param w defines the fourth component (1.0 by default) */ constructor( - /** defines the first component (0 by default) */ - x?: number, - /** defines the second component (0 by default) */ - y?: number, - /** defines the third component (0 by default) */ - z?: number, - /** defines the fourth component (1.0 by default) */ - w?: number); + /** defines the first component (0 by default) */ + x?: number, + /** defines the second component (0 by default) */ + y?: number, + /** defines the third component (0 by default) */ + z?: number, + /** defines the fourth component (1.0 by default) */ + w?: number); /** * Gets a string representation for the current quaternion * @returns a string with the Quaternion coordinates @@ -16007,7 +16010,7 @@ declare module BABYLON { /** World space */ WORLD = 1, /** Bone space */ - BONE = 2, + BONE = 2 } /** Defines the 3 main axes */ class Axis { @@ -16033,7 +16036,7 @@ declare module BABYLON { */ CW = 0, /** Counter clockwise */ - CCW = 1, + CCW = 1 } /** * Defines angle representation @@ -16170,10 +16173,10 @@ declare module BABYLON { * Returns the same object updated. */ update(path: Vector3[], firstNormal?: Nullable): Path3D; - private _compute(firstNormal); - private _getFirstNonNullVector(index); - private _getLastNonNullVector(index); - private _normalVector(v0, vt, va); + private _compute; + private _getFirstNonNullVector; + private _getLastNonNullVector; + private _normalVector; } class Curve3 { private _points; @@ -16231,7 +16234,7 @@ declare module BABYLON { * curveA and curveB keep unchanged. */ continue(curve: Curve3): Curve3; - private _computeLength(path); + private _computeLength; } class PositionNormalVertex { position: Vector3; @@ -16435,9 +16438,9 @@ declare module BABYLON { * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ /** - * Sets the global Hue value. - * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). - */ + * Sets the global Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ globalHue: number; /** * Gets the global Density value. @@ -16445,28 +16448,28 @@ declare module BABYLON { * Values less than zero provide a filter of opposite hue. */ /** - * Sets the global Density value. - * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. - * Values less than zero provide a filter of opposite hue. - */ + * Sets the global Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ globalDensity: number; /** * Gets the global Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ /** - * Sets the global Saturation value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. - */ + * Sets the global Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ globalSaturation: number; /** * Gets the global Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ /** - * Sets the global Exposure value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. - */ + * Sets the global Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ globalExposure: number; private _highlightsHue; private _highlightsDensity; @@ -16477,9 +16480,9 @@ declare module BABYLON { * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ /** - * Sets the highlights Hue value. - * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). - */ + * Sets the highlights Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ highlightsHue: number; /** * Gets the highlights Density value. @@ -16487,28 +16490,28 @@ declare module BABYLON { * Values less than zero provide a filter of opposite hue. */ /** - * Sets the highlights Density value. - * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. - * Values less than zero provide a filter of opposite hue. - */ + * Sets the highlights Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ highlightsDensity: number; /** * Gets the highlights Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ /** - * Sets the highlights Saturation value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. - */ + * Sets the highlights Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ highlightsSaturation: number; /** * Gets the highlights Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ /** - * Sets the highlights Exposure value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. - */ + * Sets the highlights Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ highlightsExposure: number; private _midtonesHue; private _midtonesDensity; @@ -16519,9 +16522,9 @@ declare module BABYLON { * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ /** - * Sets the midtones Hue value. - * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). - */ + * Sets the midtones Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ midtonesHue: number; /** * Gets the midtones Density value. @@ -16529,28 +16532,28 @@ declare module BABYLON { * Values less than zero provide a filter of opposite hue. */ /** - * Sets the midtones Density value. - * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. - * Values less than zero provide a filter of opposite hue. - */ + * Sets the midtones Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ midtonesDensity: number; /** * Gets the midtones Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ /** - * Sets the midtones Saturation value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. - */ + * Sets the midtones Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ midtonesSaturation: number; /** * Gets the midtones Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ /** - * Sets the midtones Exposure value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. - */ + * Sets the midtones Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ midtonesExposure: number; private _shadowsHue; private _shadowsDensity; @@ -16561,9 +16564,9 @@ declare module BABYLON { * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ /** - * Sets the shadows Hue value. - * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). - */ + * Sets the shadows Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ shadowsHue: number; /** * Gets the shadows Density value. @@ -16571,28 +16574,28 @@ declare module BABYLON { * Values less than zero provide a filter of opposite hue. */ /** - * Sets the shadows Density value. - * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. - * Values less than zero provide a filter of opposite hue. - */ + * Sets the shadows Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ shadowsDensity: number; /** * Gets the shadows Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ /** - * Sets the shadows Saturation value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. - */ + * Sets the shadows Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ shadowsSaturation: number; /** * Gets the shadows Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ /** - * Sets the shadows Exposure value. - * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. - */ + * Sets the shadows Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ shadowsExposure: number; getClassName(): string; /** @@ -16614,13 +16617,13 @@ declare module BABYLON { * @param exposure The exposure. * @param result The result data container. */ - private getColorGradingDataToRef(hue, density, saturation, exposure, result); + private getColorGradingDataToRef; /** * Takes an input slider value and returns an adjusted value that provides extra control near the centre. * @param value The input slider value in range [-100,100]. * @returns Adjusted value. */ - private static applyColorGradingSliderNonlinear(value); + private static applyColorGradingSliderNonlinear; /** * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV). * @param hue The hue (H) input. @@ -16628,7 +16631,7 @@ declare module BABYLON { * @param brightness The brightness (B) input. * @result An RGBA color represented as Vector4. */ - private static fromHSBToRef(hue, saturation, brightness, result); + private static fromHSBToRef; /** * Returns a value clamped between min and max * @param value The value to clamp @@ -16636,7 +16639,7 @@ declare module BABYLON { * @param max The maximum of value * @returns The clamped value. */ - private static clamp(value, min, max); + private static clamp; /** * Clones the current color curve instance. * @return The cloned curves @@ -16779,10 +16782,12 @@ declare module BABYLON { * Observable that will be called if an error occurs during shader compilation. */ onErrorObservable: Observable; + /** @hidden */ + _onBindObservable: Nullable>; /** * Observable that will be called when effect is bound. */ - onBindObservable: Observable; + readonly onBindObservable: Observable; /** @hidden */ _bonesComputationForcedToCPU: boolean; private static _uniqueIdSeed; @@ -16901,9 +16906,9 @@ declare module BABYLON { _loadFragmentShader(fragment: any, callback: (data: any) => void): void; /** @hidden */ _dumpShadersSource(vertexCode: string, fragmentCode: string, defines: string): void; - private _processShaderConversion(sourceCode, isFragment, callback); - private _processIncludes(sourceCode, callback); - private _processPrecision(source); + private _processShaderConversion; + private _processIncludes; + private _processPrecision; /** * Recompiles the webGL program * @param vertexSourceCode The source code for the vertex shader. @@ -17262,8 +17267,8 @@ declare module BABYLON { * Gets wether the color curves effect is enabled. */ /** - * Sets wether the color curves effect is enabled. - */ + * Sets wether the color curves effect is enabled. + */ colorCurvesEnabled: boolean; /** * Color grading LUT texture used in the effect if colorGradingEnabled is set to true @@ -17274,48 +17279,48 @@ declare module BABYLON { * Gets wether the color grading effect is enabled. */ /** - * Sets wether the color grading effect is enabled. - */ + * Sets wether the color grading effect is enabled. + */ colorGradingEnabled: boolean; private _colorGradingWithGreenDepth; /** * Gets wether the color grading effect is using a green depth for the 3d Texture. */ /** - * Sets wether the color grading effect is using a green depth for the 3d Texture. - */ + * Sets wether the color grading effect is using a green depth for the 3d Texture. + */ colorGradingWithGreenDepth: boolean; private _colorGradingBGR; /** * Gets wether the color grading texture contains BGR values. */ /** - * Sets wether the color grading texture contains BGR values. - */ + * Sets wether the color grading texture contains BGR values. + */ colorGradingBGR: boolean; _exposure: number; /** * Gets the Exposure used in the effect. */ /** - * Sets the Exposure used in the effect. - */ + * Sets the Exposure used in the effect. + */ exposure: number; private _toneMappingEnabled; /** * Gets wether the tone mapping effect is enabled. */ /** - * Sets wether the tone mapping effect is enabled. - */ + * Sets wether the tone mapping effect is enabled. + */ toneMappingEnabled: boolean; protected _contrast: number; /** * Gets the contrast used in the effect. */ /** - * Sets the contrast used in the effect. - */ + * Sets the contrast used in the effect. + */ contrast: number; /** * Vignette stretch size. @@ -17347,32 +17352,32 @@ declare module BABYLON { * Gets the vignette blend mode allowing different kind of effect. */ /** - * Sets the vignette blend mode allowing different kind of effect. - */ + * Sets the vignette blend mode allowing different kind of effect. + */ vignetteBlendMode: number; private _vignetteEnabled; /** * Gets wether the vignette effect is enabled. */ /** - * Sets wether the vignette effect is enabled. - */ + * Sets wether the vignette effect is enabled. + */ vignetteEnabled: boolean; private _applyByPostProcess; /** * Gets wether the image processing is applied through a post process or not. */ /** - * Sets wether the image processing is applied through a post process or not. - */ + * Sets wether the image processing is applied through a post process or not. + */ applyByPostProcess: boolean; private _isEnabled; /** * Gets wether the image processing is enabled or not. */ /** - * Sets wether the image processing is enabled or not. - */ + * Sets wether the image processing is enabled or not. + */ isEnabled: boolean; /** * An event triggered when the configuration changes and requires Shader to Update some parameters. @@ -17665,23 +17670,23 @@ declare module BABYLON { * The alpha value of the material */ protected _alpha: number; - /** - * Gets the alpha value of the material - */ /** * Sets the alpha value of the material */ + /** + * Gets the alpha value of the material + */ alpha: number; /** * Specifies if back face culling is enabled */ protected _backFaceCulling: boolean; - /** - * Gets the back-face culling state - */ /** * Sets the back-face culling state */ + /** + * Gets the back-face culling state + */ backFaceCulling: boolean; /** * Stores the value for side orientation @@ -17719,14 +17724,16 @@ declare module BABYLON { * An observer which watches for dispose events */ private _onDisposeObserver; + private _onUnBindObservable; /** * Called during a dispose event */ onDispose: () => void; + private _onBindObservable; /** * An event triggered when the material is bound */ - onBindObservable: Observable; + readonly onBindObservable: Observable; /** * An observer which watches for bind events */ @@ -17738,14 +17745,11 @@ declare module BABYLON { /** * An event triggered when the material is unbound */ - onUnBindObservable: Observable; + readonly onUnBindObservable: Observable; /** * Stores the value of the alpha mode */ private _alphaMode; - /** - * Gets the value of the alpha mode - */ /** * Sets the value of the alpha mode. * @@ -17764,17 +17768,20 @@ declare module BABYLON { * | 10 | ALPHA_SCREENMODE | | * */ + /** + * Gets the value of the alpha mode + */ alphaMode: number; /** * Stores the state of the need depth pre-pass value */ private _needDepthPrePass; - /** - * Gets the depth pre-pass value - */ /** * Sets the need depth pre-pass value */ + /** + * Gets the depth pre-pass value + */ needDepthPrePass: boolean; /** * Specifies if depth writing should be disabled @@ -17792,12 +17799,12 @@ declare module BABYLON { * Stores the state specifing if fog should be enabled */ private _fogEnabled; - /** - * Gets the value of the fog enabled state - */ /** * Sets the state for enabling fog */ + /** + * Gets the value of the fog enabled state + */ fogEnabled: boolean; /** * Stores the size of points @@ -17811,22 +17818,22 @@ declare module BABYLON { * Gets a value specifying if wireframe mode is enabled */ /** - * Sets the state of wireframe mode - */ + * Sets the state of wireframe mode + */ wireframe: boolean; /** * Gets the value specifying if point clouds are enabled */ /** - * Sets the state of point cloud mode - */ + * Sets the state of point cloud mode + */ pointsCloud: boolean; /** * Gets the material fill mode */ /** - * Sets the material fill mode - */ + * Sets the material fill mode + */ fillMode: number; /** * Stores the effects for the material @@ -18275,7 +18282,7 @@ declare module BABYLON { private _subMaterials; subMaterials: Nullable[]; constructor(name: string, scene: Scene); - private _hookArray(array); + private _hookArray; getSubMaterial(index: number): Nullable; getActiveTextures(): BaseTexture[]; getClassName(): string; @@ -18337,7 +18344,7 @@ declare module BABYLON { getClassName(): string; needAlphaBlending(): boolean; needAlphaTesting(): boolean; - private _checkUniform(uniformName); + private _checkUniform; setTexture(name: string, texture: Texture): ShaderMaterial; setTextureArray(name: string, textures: Texture[]): ShaderMaterial; setFloat(name: string, value: number): ShaderMaterial; @@ -18354,7 +18361,7 @@ declare module BABYLON { setMatrix2x2(name: string, value: Float32Array): ShaderMaterial; setArray2(name: string, value: number[]): ShaderMaterial; setArray3(name: string, value: number[]): ShaderMaterial; - private _checkCache(scene, mesh?, useInstances?); + private _checkCache; isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean; bindOnlyWorldMatrix(world: Matrix): void; bind(world: Matrix, mesh?: Mesh): void; @@ -18564,10 +18571,10 @@ declare module BABYLON { * Gets the image processing configuration used either in this material. */ /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ imageProcessingConfiguration: ImageProcessingConfiguration; /** * Keep track of the image processing observer to allow dispose and replace. @@ -18582,22 +18589,22 @@ declare module BABYLON { * Gets wether the color curves effect is enabled. */ /** - * Sets wether the color curves effect is enabled. - */ + * Sets wether the color curves effect is enabled. + */ cameraColorCurvesEnabled: boolean; /** * Gets wether the color grading effect is enabled. */ /** - * Gets wether the color grading effect is enabled. - */ + * Gets wether the color grading effect is enabled. + */ cameraColorGradingEnabled: boolean; /** * Gets wether tonemapping is enabled or not. */ /** - * Sets wether tonemapping is enabled or not - */ + * Sets wether tonemapping is enabled or not + */ cameraToneMappingEnabled: boolean; /** * The camera exposure used on this material. @@ -18605,24 +18612,24 @@ declare module BABYLON { * This corresponds to a photographic exposure. */ /** - * The camera exposure used on this material. - * This property is here and not in the camera to allow controlling exposure without full screen post process. - * This corresponds to a photographic exposure. - */ + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ cameraExposure: number; /** * Gets The camera contrast used on this material. */ /** - * Sets The camera contrast used on this material. - */ + * Sets The camera contrast used on this material. + */ cameraContrast: number; /** * Gets the Color Grading 2D Lookup Texture. */ /** - * Sets the Color Grading 2D Lookup Texture. - */ + * Sets the Color Grading 2D Lookup Texture. + */ cameraColorGradingTexture: Nullable; /** * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). @@ -18631,11 +18638,11 @@ declare module BABYLON { * corresponding to low luminance, medium luminance, and high luminance areas respectively. */ /** - * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). - * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. - * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; - * corresponding to low luminance, medium luminance, and high luminance areas respectively. - */ + * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ cameraColorCurves: Nullable; customShaderNameResolve: (shaderName: string, uniforms: string[], uniformBuffers: string[], samplers: string[], defines: StandardMaterialDefines) => string; protected _renderTargets: SmartArray; @@ -18822,7 +18829,7 @@ declare module BABYLON { * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159 * for specs. */ - private _fillAlignment(size); + private _fillAlignment; /** * Adds an uniform in the buffer. * Warning : the subsequents calls of this function must be in the same order as declared in the shader @@ -18899,28 +18906,28 @@ declare module BABYLON { * @param {number} size Size of the data. */ updateUniform(uniformName: string, data: FloatArray, size: number): void; - private _updateMatrix3x3ForUniform(name, matrix); - private _updateMatrix3x3ForEffect(name, matrix); - private _updateMatrix2x2ForEffect(name, matrix); - private _updateMatrix2x2ForUniform(name, matrix); - private _updateFloatForEffect(name, x); - private _updateFloatForUniform(name, x); - private _updateFloat2ForEffect(name, x, y, suffix?); - private _updateFloat2ForUniform(name, x, y, suffix?); - private _updateFloat3ForEffect(name, x, y, z, suffix?); - private _updateFloat3ForUniform(name, x, y, z, suffix?); - private _updateFloat4ForEffect(name, x, y, z, w, suffix?); - private _updateFloat4ForUniform(name, x, y, z, w, suffix?); - private _updateMatrixForEffect(name, mat); - private _updateMatrixForUniform(name, mat); - private _updateVector3ForEffect(name, vector); - private _updateVector3ForUniform(name, vector); - private _updateVector4ForEffect(name, vector); - private _updateVector4ForUniform(name, vector); - private _updateColor3ForEffect(name, color, suffix?); - private _updateColor3ForUniform(name, color, suffix?); - private _updateColor4ForEffect(name, color, alpha, suffix?); - private _updateColor4ForUniform(name, color, alpha, suffix?); + private _updateMatrix3x3ForUniform; + private _updateMatrix3x3ForEffect; + private _updateMatrix2x2ForEffect; + private _updateMatrix2x2ForUniform; + private _updateFloatForEffect; + private _updateFloatForUniform; + private _updateFloat2ForEffect; + private _updateFloat2ForUniform; + private _updateFloat3ForEffect; + private _updateFloat3ForUniform; + private _updateFloat4ForEffect; + private _updateFloat4ForUniform; + private _updateMatrixForEffect; + private _updateMatrixForUniform; + private _updateVector3ForEffect; + private _updateVector3ForUniform; + private _updateVector4ForEffect; + private _updateVector4ForUniform; + private _updateColor3ForEffect; + private _updateColor3ForUniform; + private _updateColor4ForEffect; + private _updateColor4ForUniform; /** * Sets a sampler uniform on the effect. * @param {string} name Name of the sampler. @@ -18982,8 +18989,8 @@ declare module BABYLON { * @param influence defines the influence to use */ constructor( - /** defines the name of the target */ - name: string, influence?: number, scene?: Nullable); + /** defines the name of the target */ + name: string, influence?: number, scene?: Nullable); /** * Gets a boolean defining if the target contains position data */ @@ -19124,7 +19131,7 @@ declare module BABYLON { * @returns the serialized object */ serialize(): any; - private _syncActiveTargets(needUpdate); + private _syncActiveTargets; /** * Syncrhonize the targets with all the meshes using this morph target manager */ @@ -19140,7638 +19147,7641 @@ declare module BABYLON { } declare module BABYLON { - interface PhysicsImpostorJoint { - mainImpostor: PhysicsImpostor; - connectedImpostor: PhysicsImpostor; - joint: PhysicsJoint; - } - class PhysicsEngine { - private _physicsPlugin; - gravity: Vector3; - constructor(gravity: Nullable, _physicsPlugin?: IPhysicsEnginePlugin); - setGravity(gravity: Vector3): void; + /** + * Class used to store all common mesh properties + */ + class AbstractMesh extends TransformNode implements IDisposable, ICullable, IGetSetVerticesData { + /** No occlusion */ + static OCCLUSION_TYPE_NONE: number; + /** Occlusion set to optimisitic */ + static OCCLUSION_TYPE_OPTIMISTIC: number; + /** Occlusion set to strict */ + static OCCLUSION_TYPE_STRICT: number; + /** Use an accurante occlusion algorithm */ + static OCCLUSION_ALGORITHM_TYPE_ACCURATE: number; + /** Use a conservative occlusion algorithm */ + static OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE: number; /** - * Set the time step of the physics engine. - * default is 1/60. - * To slow it down, enter 1/600 for example. - * To speed it up, 1/30 - * @param {number} newTimeStep the new timestep to apply to this world. + * No billboard */ - setTimeStep(newTimeStep?: number): void; + static readonly BILLBOARDMODE_NONE: number; + /** Billboard on X axis */ + static readonly BILLBOARDMODE_X: number; + /** Billboard on Y axis */ + static readonly BILLBOARDMODE_Y: number; + /** Billboard on Z axis */ + static readonly BILLBOARDMODE_Z: number; + /** Billboard on all axes */ + static readonly BILLBOARDMODE_ALL: number; + private _facetPositions; + private _facetNormals; + private _facetPartitioning; + private _facetNb; + private _partitioningSubdivisions; + private _partitioningBBoxRatio; + private _facetDataEnabled; + private _facetParameters; + private _bbSize; + private _subDiv; + private _facetDepthSort; + private _facetDepthSortEnabled; + private _depthSortedIndices; + private _depthSortedFacets; + private _facetDepthSortFunction; + private _facetDepthSortFrom; + private _facetDepthSortOrigin; + private _invertedMatrix; /** - * Get the time step of the physics engine. + * Gets the number of facets in the mesh + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet */ - getTimeStep(): number; - dispose(): void; - getPhysicsPluginName(): string; - static Epsilon: number; - private _impostors; - private _joints; + readonly facetNb: number; /** - * Adding a new impostor for the impostor tracking. - * This will be done by the impostor itself. - * @param {PhysicsImpostor} impostor the impostor to add + * Gets or set the number (integer) of subdivisions per axis in the partioning space + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning */ - addImpostor(impostor: PhysicsImpostor): void; + partitioningSubdivisions: number; /** - * Remove an impostor from the engine. - * This impostor and its mesh will not longer be updated by the physics engine. - * @param {PhysicsImpostor} impostor the impostor to remove + * The ratio (float) to apply to the bouding box size to set to the partioning space. + * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning */ - removeImpostor(impostor: PhysicsImpostor): void; + partitioningBBoxRatio: number; /** - * Add a joint to the physics engine - * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added. - * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint - * @param {PhysicsJoint} the joint that will connect both impostors. + * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`. + * Works only for updatable meshes. + * Doesn't work with multi-materials + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort */ - addJoint(mainImpostor: PhysicsImpostor, connectedImpostor: PhysicsImpostor, joint: PhysicsJoint): void; - removeJoint(mainImpostor: PhysicsImpostor, connectedImpostor: PhysicsImpostor, joint: PhysicsJoint): void; + mustDepthSortFacets: boolean; /** - * Called by the scene. no need to call it. + * The location (Vector3) where the facet depth sort must be computed from. + * By default, the active camera position. + * Used only when facet depth sort is enabled + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort */ - _step(delta: number): void; - getPhysicsPlugin(): IPhysicsEnginePlugin; - getImpostors(): Array; - getImpostorForPhysicsObject(object: IPhysicsEnabledObject): Nullable; - getImpostorWithPhysicsBody(body: any): Nullable; - } - interface IPhysicsEnginePlugin { - world: any; - name: string; - setGravity(gravity: Vector3): void; - setTimeStep(timeStep: number): void; - getTimeStep(): number; - executeStep(delta: number, impostors: Array): void; - applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3): void; - applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3): void; - generatePhysicsBody(impostor: PhysicsImpostor): void; - removePhysicsBody(impostor: PhysicsImpostor): void; - generateJoint(joint: PhysicsImpostorJoint): void; - removeJoint(joint: PhysicsImpostorJoint): void; - isSupported(): boolean; - setTransformationFromPhysicsBody(impostor: PhysicsImpostor): void; - setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion): void; - setLinearVelocity(impostor: PhysicsImpostor, velocity: Nullable): void; - setAngularVelocity(impostor: PhysicsImpostor, velocity: Nullable): void; - getLinearVelocity(impostor: PhysicsImpostor): Nullable; - getAngularVelocity(impostor: PhysicsImpostor): Nullable; - setBodyMass(impostor: PhysicsImpostor, mass: number): void; - getBodyMass(impostor: PhysicsImpostor): number; - getBodyFriction(impostor: PhysicsImpostor): number; - setBodyFriction(impostor: PhysicsImpostor, friction: number): void; - getBodyRestitution(impostor: PhysicsImpostor): number; - setBodyRestitution(impostor: PhysicsImpostor, restitution: number): void; - sleepBody(impostor: PhysicsImpostor): void; - wakeUpBody(impostor: PhysicsImpostor): void; - updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number): void; - setMotor(joint: IMotorEnabledJoint, speed: number, maxForce?: number, motorIndex?: number): void; - setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number, motorIndex?: number): void; - getRadius(impostor: PhysicsImpostor): number; - getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void; - syncMeshWithImpostor(mesh: AbstractMesh, impostor: PhysicsImpostor): void; - dispose(): void; - } -} - -declare module BABYLON { - class PhysicsHelper { - private _scene; - private _physicsEngine; - constructor(scene: Scene); + facetDepthSortFrom: Vector3; /** - * @param {Vector3} origin the origin of the explosion - * @param {number} radius the explosion radius - * @param {number} strength the explosion strength - * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant + * gets a boolean indicating if facetData is enabled + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet */ - applyRadialExplosionImpulse(origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff): Nullable; + readonly isFacetDataEnabled: boolean; + /** @hidden */ + _updateNonUniformScalingState(value: boolean): boolean; /** - * @param {Vector3} origin the origin of the explosion - * @param {number} radius the explosion radius - * @param {number} strength the explosion strength - * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant - */ - applyRadialExplosionForce(origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff): Nullable; + * An event triggered when this mesh collides with another one + */ + onCollideObservable: Observable; + private _onCollideObserver; + /** Set a function to call when this mesh collides with another one */ + onCollide: () => void; /** - * @param {Vector3} origin the origin of the explosion - * @param {number} radius the explosion radius - * @param {number} strength the explosion strength - * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant - */ - gravitationalField(origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff): Nullable; + * An event triggered when the collision's position changes + */ + onCollisionPositionChangeObservable: Observable; + private _onCollisionPositionChangeObserver; + /** Set a function to call when the collision's position changes */ + onCollisionPositionChange: () => void; /** - * @param {Vector3} origin the origin of the updraft - * @param {number} radius the radius of the updraft - * @param {number} strength the strength of the updraft - * @param {number} height the height of the updraft - * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center - */ - updraft(origin: Vector3, radius: number, strength: number, height: number, updraftMode?: PhysicsUpdraftMode): Nullable; + * An event triggered when material is changed + */ + onMaterialChangedObservable: Observable; /** - * @param {Vector3} origin the of the vortex - * @param {number} radius the radius of the vortex - * @param {number} strength the strength of the vortex - * @param {number} height the height of the vortex + * Gets or sets the orientation for POV movement & rotation */ - vortex(origin: Vector3, radius: number, strength: number, height: number): Nullable; - } - /***** Radial explosion *****/ - class PhysicsRadialExplosionEvent { - private _scene; - private _sphere; - private _sphereOptions; - private _rays; - private _dataFetched; - constructor(scene: Scene); + definedFacingForward: boolean; /** - * Returns the data related to the radial explosion event (sphere & rays). - * @returns {PhysicsRadialExplosionEventData} - */ - getData(): PhysicsRadialExplosionEventData; + * This property determines the type of occlusion query algorithm to run in WebGl, you can use: + * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED. + * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate. + * @see http://doc.babylonjs.com/features/occlusionquery + */ + occlusionQueryAlgorithmType: number; /** - * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse. - * @param impostor - * @param {Vector3} origin the origin of the explosion - * @param {number} radius the explosion radius - * @param {number} strength the explosion strength - * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear - * @returns {Nullable} + * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values: + * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh. + * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh. + * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show. + * @see http://doc.babylonjs.com/features/occlusionquery */ - getImpostorForceAndContactPoint(impostor: PhysicsImpostor, origin: Vector3, radius: number, strength: number, falloff: PhysicsRadialImpulseFalloff): Nullable; + occlusionType: number; /** - * Disposes the sphere. - * @param {bolean} force - */ - dispose(force?: boolean): void; - /*** Helpers ***/ - private _prepareSphere(); - private _intersectsWithSphere(impostor, origin, radius); - } - /***** Gravitational Field *****/ - class PhysicsGravitationalFieldEvent { - private _physicsHelper; - private _scene; - private _origin; - private _radius; - private _strength; - private _falloff; - private _tickCallback; - private _sphere; - private _dataFetched; - constructor(physicsHelper: PhysicsHelper, scene: Scene, origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff); + * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object. + * The default value is -1 which means don't break the query and wait till the result + * @see http://doc.babylonjs.com/features/occlusionquery + */ + occlusionRetryCount: number; + /** @hidden */ + _occlusionInternalRetryCounter: number; + /** @hidden */ + _isOccluded: boolean; /** - * Returns the data related to the gravitational field event (sphere). - * @returns {PhysicsGravitationalFieldEventData} - */ - getData(): PhysicsGravitationalFieldEventData; + * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not + * @see http://doc.babylonjs.com/features/occlusionquery + */ + isOccluded: boolean; + /** @hidden */ + _isOcclusionQueryInProgress: boolean; /** - * Enables the gravitational field. + * Flag to check the progress status of the query + * @see http://doc.babylonjs.com/features/occlusionquery */ - enable(): void; + readonly isOcclusionQueryInProgress: boolean; + /** @hidden */ + _occlusionQuery: Nullable; + private _visibility; /** - * Disables the gravitational field. + * Gets or sets mesh visibility between 0 and 1 (default is 1) */ - disable(): void; /** - * Disposes the sphere. - * @param {bolean} force + * Gets or sets mesh visibility between 0 and 1 (default is 1) + */ + visibility: number; + /** Gets or sets the alpha index used to sort transparent meshes + * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index */ - dispose(force?: boolean): void; - private _tick(); - } - /***** Updraft *****/ - class PhysicsUpdraftEvent { - private _scene; - private _origin; - private _radius; - private _strength; - private _height; - private _updraftMode; - private _physicsEngine; - private _originTop; - private _originDirection; - private _tickCallback; - private _cylinder; - private _cylinderPosition; - private _dataFetched; - constructor(_scene: Scene, _origin: Vector3, _radius: number, _strength: number, _height: number, _updraftMode: PhysicsUpdraftMode); + alphaIndex: number; /** - * Returns the data related to the updraft event (cylinder). - * @returns {PhysicsUpdraftEventData} + * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true */ - getData(): PhysicsUpdraftEventData; + isVisible: boolean; /** - * Enables the updraft. + * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true */ - enable(): void; - /** - * Disables the cortex. + isPickable: boolean; + /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */ + showSubMeshesBoundingBox: boolean; + /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default) + * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares */ - disable(): void; + isBlocker: boolean; /** - * Disposes the sphere. - * @param {bolean} force + * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default) */ - dispose(force?: boolean): void; - private getImpostorForceAndContactPoint(impostor); - private _tick(); - /*** Helpers ***/ - private _prepareCylinder(); - private _intersectsWithCylinder(impostor); - } - /***** Vortex *****/ - class PhysicsVortexEvent { - private _scene; - private _origin; - private _radius; - private _strength; - private _height; - private _physicsEngine; - private _originTop; - private _centripetalForceThreshold; - private _updraftMultiplier; - private _tickCallback; - private _cylinder; - private _cylinderPosition; - private _dataFetched; - constructor(_scene: Scene, _origin: Vector3, _radius: number, _strength: number, _height: number); + enablePointerMoveEvents: boolean; /** - * Returns the data related to the vortex event (cylinder). - * @returns {PhysicsVortexEventData} + * Specifies the rendering group id for this mesh (0 by default) + * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups */ - getData(): PhysicsVortexEventData; + renderingGroupId: number; + private _material; + /** Gets or sets current material */ + material: Nullable; + private _receiveShadows; /** - * Enables the vortex. + * Gets or sets a boolean indicating that this mesh can receive realtime shadows + * @see http://doc.babylonjs.com/babylon101/shadows */ - enable(): void; + receiveShadows: boolean; /** - * Disables the cortex. + * Gets or sets a boolean indicating if the outline must be rendered as well + * @see https://www.babylonjs-playground.com/#10WJ5S#3 */ - disable(): void; + renderOutline: boolean; + /** Defines color to use when rendering outline */ + outlineColor: Color3; + /** Define width to use when rendering outline */ + outlineWidth: number; /** - * Disposes the sphere. - * @param {bolean} force + * Gets or sets a boolean indicating if the overlay must be rendered as well + * @see https://www.babylonjs-playground.com/#10WJ5S#2 */ - dispose(force?: boolean): void; - private getImpostorForceAndContactPoint(impostor); - private _tick(); - /*** Helpers ***/ - private _prepareCylinder(); - private _intersectsWithCylinder(impostor); - } - /***** Enums *****/ - /** - * The strenght of the force in correspondence to the distance of the affected object - */ - enum PhysicsRadialImpulseFalloff { - /** Defines that impulse is constant in strength across it's whole radius */ - Constant = 0, - /** DEfines that impulse gets weaker if it's further from the origin */ - Linear = 1, - } - /** - * The strenght of the force in correspondence to the distance of the affected object - */ - enum PhysicsUpdraftMode { - /** Defines that the upstream forces will pull towards the top center of the cylinder */ - Center = 0, - /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */ - Perpendicular = 1, - } - /***** Data interfaces *****/ - interface PhysicsForceAndContactPoint { - force: Vector3; - contactPoint: Vector3; - } - interface PhysicsRadialExplosionEventData { - sphere: Mesh; - rays: Array; - } - interface PhysicsGravitationalFieldEventData { - sphere: Mesh; - } - interface PhysicsUpdraftEventData { - cylinder: Mesh; - } - interface PhysicsVortexEventData { - cylinder: Mesh; - } -} - -declare module BABYLON { - interface PhysicsImpostorParameters { - mass: number; - friction?: number; - restitution?: number; - nativeOptions?: any; - ignoreParent?: boolean; - disableBidirectionalTransformation?: boolean; - } - interface IPhysicsEnabledObject { - position: Vector3; - rotationQuaternion: Nullable; - scaling: Vector3; - rotation?: Vector3; - parent?: any; - getBoundingInfo(): BoundingInfo; - computeWorldMatrix(force: boolean): Matrix; - getWorldMatrix?(): Matrix; - getChildMeshes?(directDescendantsOnly?: boolean): Array; - getVerticesData(kind: string): Nullable | Float32Array>; - getIndices?(): Nullable; - getScene?(): Scene; - getAbsolutePosition(): Vector3; - getAbsolutePivotPoint(): Vector3; - rotate(axis: Vector3, amount: number, space?: Space): TransformNode; - translate(axis: Vector3, distance: number, space?: Space): TransformNode; - setAbsolutePosition(absolutePosition: Vector3): TransformNode; - getClassName(): string; - } - class PhysicsImpostor { - object: IPhysicsEnabledObject; - type: number; - private _options; - private _scene; - static DEFAULT_OBJECT_SIZE: Vector3; - static IDENTITY_QUATERNION: Quaternion; - private _physicsEngine; - private _physicsBody; - private _bodyUpdateRequired; - private _onBeforePhysicsStepCallbacks; - private _onAfterPhysicsStepCallbacks; - private _onPhysicsCollideCallbacks; - private _deltaPosition; - private _deltaRotation; - private _deltaRotationConjugated; - private _parent; - private _isDisposed; - private static _tmpVecs; - private static _tmpQuat; - readonly isDisposed: boolean; - mass: number; - friction: number; - restitution: number; - uniqueId: number; - private _joints; - constructor(object: IPhysicsEnabledObject, type: number, _options?: PhysicsImpostorParameters, _scene?: Scene | undefined); + renderOverlay: boolean; + /** Defines color to use when rendering overlay */ + overlayColor: Color3; + /** Defines alpha to use when rendering overlay */ + overlayAlpha: number; + private _hasVertexAlpha; + /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */ + hasVertexAlpha: boolean; + private _useVertexColors; + /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */ + useVertexColors: boolean; + private _computeBonesUsingShaders; /** - * This function will completly initialize this impostor. - * It will create a new body - but only if this mesh has no parent. - * If it has, this impostor will not be used other than to define the impostor - * of the child mesh. + * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default) */ - _init(): void; - private _getPhysicsParent(); + computeBonesUsingShaders: boolean; + private _numBoneInfluencers; + /** Gets or sets the number of allowed bone influences per vertex (4 by default) */ + numBoneInfluencers: number; + private _applyFog; + /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */ + applyFog: boolean; + /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */ + useOctreeForRenderingSelection: boolean; + /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */ + useOctreeForPicking: boolean; + /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */ + useOctreeForCollisions: boolean; + private _layerMask; /** - * Should a new body be generated. + * Gets or sets the current layer mask (default is 0x0FFFFFFF) + * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures */ - isBodyInitRequired(): boolean; - setScalingUpdated(updated: boolean): void; + layerMask: number; /** - * Force a regeneration of this or the parent's impostor's body. - * Use under cautious - This will remove all joints already implemented. + * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase) */ - forceUpdate(): void; + alwaysSelectAsActiveMesh: boolean; /** - * Gets the body that holds this impostor. Either its own, or its parent. + * Gets or sets the current action manager + * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ + actionManager: Nullable; /** - * Set the physics body. Used mainly by the physics engine/plugin + * Gets or sets impostor used for physic simulation + * @see http://doc.babylonjs.com/features/physics_engine */ - physicsBody: any; - parent: Nullable; - resetUpdateFlags(): void; - getObjectExtendSize(): Vector3; - getObjectCenter(): Vector3; + physicsImpostor: Nullable; + private _checkCollisions; + private _collisionMask; + private _collisionGroup; /** - * Get a specific parametes from the options parameter. + * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5)) + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ - getParam(paramName: string): any; + ellipsoid: Vector3; /** - * Sets a specific parameter in the options given to the physics plugin + * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0)) + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ - setParam(paramName: string, value: number): void; + ellipsoidOffset: Vector3; + private _collider; + private _oldPositionForCollisions; + private _diffPositionForCollisions; /** - * Specifically change the body's mass option. Won't recreate the physics body object + * Gets or sets a collision mask used to mask collisions (default is -1). + * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 */ - setMass(mass: number): void; - getLinearVelocity(): Nullable; - setLinearVelocity(velocity: Nullable): void; - getAngularVelocity(): Nullable; - setAngularVelocity(velocity: Nullable): void; + collisionMask: number; /** - * Execute a function with the physics plugin native code. - * Provide a function the will have two variables - the world object and the physics body object. + * Gets or sets the current collision group mask (-1 by default). + * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 */ - executeNativeFunction(func: (world: any, physicsBody: any) => void): void; + collisionGroup: number; /** - * Register a function that will be executed before the physics world is stepping forward. + * Defines edge width used when edgesRenderer is enabled + * @see https://www.babylonjs-playground.com/#10OJSG#13 */ - registerBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void; - unregisterBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void; + edgesWidth: number; /** - * Register a function that will be executed after the physics step + * Defines edge color used when edgesRenderer is enabled + * @see https://www.babylonjs-playground.com/#10OJSG#13 */ - registerAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void; - unregisterAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void; + edgesColor: Color4; + /** @hidden */ + _edgesRenderer: Nullable; + private _collisionsTransformMatrix; + private _collisionsScalingMatrix; + /** @hidden */ + _masterMesh: Nullable; + /** @hidden */ + _boundingInfo: Nullable; + /** @hidden */ + _renderId: number; /** - * register a function that will be executed when this impostor collides against a different body. + * Gets or sets the list of subMeshes + * @see http://doc.babylonjs.com/how_to/multi_materials */ - registerOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor) => void): void; - unregisterOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor | Array) => void): void; - private _tmpQuat; - private _tmpQuat2; - getParentsRotation(): Quaternion; + subMeshes: SubMesh[]; + /** @hidden */ + _submeshesOctree: Octree; + /** @hidden */ + _intersectionsInProgress: AbstractMesh[]; + /** @hidden */ + _unIndexed: boolean; + /** @hidden */ + _lightSources: Light[]; + /** @hidden */ + readonly _positions: Nullable; + /** @hidden */ + _waitingActions: any; + /** @hidden */ + _waitingFreezeWorldMatrix: Nullable; + private _skeleton; + /** @hidden */ + _bonesTransformMatrices: Nullable; /** - * this function is executed by the physics engine. + * Gets or sets a skeleton to apply skining transformations + * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons */ - beforeStep: () => void; + skeleton: Nullable; /** - * this function is executed by the physics engine. + * Creates a new AbstractMesh + * @param name defines the name of the mesh + * @param scene defines the hosting scene */ - afterStep: () => void; + constructor(name: string, scene?: Nullable); /** - * Legacy collision detection event support + * Returns the string "AbstractMesh" + * @returns "AbstractMesh" */ - onCollideEvent: Nullable<(collider: PhysicsImpostor, collidedWith: PhysicsImpostor) => void>; - onCollide: (e: { - body: any; - }) => void; + getClassName(): string; /** - * Apply a force + * Gets a string representation of the current mesh + * @param fullDetails defines a boolean indicating if full details must be included + * @returns a string representation of the current mesh */ - applyForce(force: Vector3, contactPoint: Vector3): PhysicsImpostor; + toString(fullDetails?: boolean): string; + /** @hidden */ + _rebuild(): void; + /** @hidden */ + _resyncLightSources(): void; + /** @hidden */ + _resyncLighSource(light: Light): void; + /** @hidden */ + _unBindEffect(): void; + /** @hidden */ + _removeLightSource(light: Light): void; + private _markSubMeshesAsDirty; + /** @hidden */ + _markSubMeshesAsLightDirty(): void; + /** @hidden */ + _markSubMeshesAsAttributesDirty(): void; + /** @hidden */ + _markSubMeshesAsMiscDirty(): void; /** - * Apply an impulse + * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0) + */ + scaling: Vector3; + /** + * Disables the mesh edge rendering mode + * @returns the currentAbstractMesh */ - applyImpulse(force: Vector3, contactPoint: Vector3): PhysicsImpostor; + disableEdgesRendering(): AbstractMesh; /** - * A help function to create a joint. + * Enables the edge rendering mode on the mesh. + * This mode makes the mesh edges visible + * @param epsilon defines the maximal distance between two angles to detect a face + * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces + * @returns the currentAbstractMesh + * @see https://www.babylonjs-playground.com/#19O9TU#0 */ - createJoint(otherImpostor: PhysicsImpostor, jointType: number, jointData: PhysicsJointData): PhysicsImpostor; + enableEdgesRendering(epsilon?: number, checkVerticesInsteadOfIndices?: boolean): AbstractMesh; /** - * Add a joint to this impostor with a different impostor. + * Gets the edgesRenderer associated with the mesh */ - addJoint(otherImpostor: PhysicsImpostor, joint: PhysicsJoint): PhysicsImpostor; + readonly edgesRenderer: Nullable; /** - * Will keep this body still, in a sleep mode. + * Returns true if the mesh is blocked. Implemented by child classes */ - sleep(): PhysicsImpostor; + readonly isBlocked: boolean; /** - * Wake the body up. + * Returns the mesh itself by default. Implemented by child classes + * @param camera defines the camera to use to pick the right LOD level + * @returns the currentAbstractMesh */ - wakeUp(): PhysicsImpostor; - clone(newObject: IPhysicsEnabledObject): Nullable; - dispose(): void; - setDeltaPosition(position: Vector3): void; - setDeltaRotation(rotation: Quaternion): void; - getBoxSizeToRef(result: Vector3): PhysicsImpostor; - getRadius(): number; + getLOD(camera: Camera): Nullable; /** - * Sync a bone with this impostor - * @param bone The bone to sync to the impostor. - * @param boneMesh The mesh that the bone is influencing. - * @param jointPivot The pivot of the joint / bone in local space. - * @param distToJoint Optional distance from the impostor to the joint. - * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. + * Returns 0 by default. Implemented by child classes + * @returns an integer */ - syncBoneWithImpostor(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion): void; + getTotalVertices(): number; /** - * Sync impostor to a bone - * @param bone The bone that the impostor will be synced to. - * @param boneMesh The mesh that the bone is influencing. - * @param jointPivot The pivot of the joint / bone in local space. - * @param distToJoint Optional distance from the impostor to the joint. - * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. - * @param boneAxis Optional vector3 axis the bone is aligned with + * Returns null by default. Implemented by child classes + * @returns null */ - syncImpostorWithBone(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion, boneAxis?: Vector3): void; - static NoImpostor: number; - static SphereImpostor: number; - static BoxImpostor: number; - static PlaneImpostor: number; - static MeshImpostor: number; - static CylinderImpostor: number; - static ParticleImpostor: number; - static HeightmapImpostor: number; - } -} - -declare module BABYLON { - interface PhysicsJointData { - mainPivot?: Vector3; - connectedPivot?: Vector3; - mainAxis?: Vector3; - connectedAxis?: Vector3; - collision?: boolean; - nativeParams?: any; - } - /** - * This is a holder class for the physics joint created by the physics plugin. - * It holds a set of functions to control the underlying joint. - */ - class PhysicsJoint { - type: number; - jointData: PhysicsJointData; - private _physicsJoint; - protected _physicsPlugin: IPhysicsEnginePlugin; - constructor(type: number, jointData: PhysicsJointData); - physicsJoint: any; - physicsPlugin: IPhysicsEnginePlugin; + getIndices(): Nullable; /** - * Execute a function that is physics-plugin specific. - * @param {Function} func the function that will be executed. - * It accepts two parameters: the physics world and the physics joint. + * Returns the array of the requested vertex data kind. Implemented by child classes + * @param kind defines the vertex data kind to use + * @returns null */ - executeNativeFunction(func: (world: any, physicsJoint: any) => void): void; - static DistanceJoint: number; - static HingeJoint: number; - static BallAndSocketJoint: number; - static WheelJoint: number; - static SliderJoint: number; - static PrismaticJoint: number; - static UniversalJoint: number; - static Hinge2Joint: number; - static PointToPointJoint: number; - static SpringJoint: number; - static LockJoint: number; - } - /** - * A class representing a physics distance joint. - */ - class DistanceJoint extends PhysicsJoint { - constructor(jointData: DistanceJointData); + getVerticesData(kind: string): Nullable; /** - * Update the predefined distance. + * Sets the vertex data of the mesh geometry for the requested `kind`. + * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. + * Note that a new underlying VertexBuffer object is created each call. + * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. + * @param kind defines vertex data kind: + * * BABYLON.VertexBuffer.PositionKind + * * BABYLON.VertexBuffer.UVKind + * * BABYLON.VertexBuffer.UV2Kind + * * BABYLON.VertexBuffer.UV3Kind + * * BABYLON.VertexBuffer.UV4Kind + * * BABYLON.VertexBuffer.UV5Kind + * * BABYLON.VertexBuffer.UV6Kind + * * BABYLON.VertexBuffer.ColorKind + * * BABYLON.VertexBuffer.MatricesIndicesKind + * * BABYLON.VertexBuffer.MatricesIndicesExtraKind + * * BABYLON.VertexBuffer.MatricesWeightsKind + * * BABYLON.VertexBuffer.MatricesWeightsExtraKind + * @param data defines the data source + * @param updatable defines if the data must be flagged as updatable (or static) + * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind + * @returns the current mesh */ - updateDistance(maxDistance: number, minDistance?: number): void; - } - class MotorEnabledJoint extends PhysicsJoint implements IMotorEnabledJoint { - constructor(type: number, jointData: PhysicsJointData); + setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): AbstractMesh; /** - * Set the motor values. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param {number} force the force to apply - * @param {number} maxForce max force for this motor. + * Updates the existing vertex data of the mesh geometry for the requested `kind`. + * If the mesh has no geometry, it is simply returned as it is. + * @param kind defines vertex data kind: + * * BABYLON.VertexBuffer.PositionKind + * * BABYLON.VertexBuffer.UVKind + * * BABYLON.VertexBuffer.UV2Kind + * * BABYLON.VertexBuffer.UV3Kind + * * BABYLON.VertexBuffer.UV4Kind + * * BABYLON.VertexBuffer.UV5Kind + * * BABYLON.VertexBuffer.UV6Kind + * * BABYLON.VertexBuffer.ColorKind + * * BABYLON.VertexBuffer.MatricesIndicesKind + * * BABYLON.VertexBuffer.MatricesIndicesExtraKind + * * BABYLON.VertexBuffer.MatricesWeightsKind + * * BABYLON.VertexBuffer.MatricesWeightsExtraKind + * @param data defines the data source + * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed + * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh + * @returns the current mesh */ - setMotor(force?: number, maxForce?: number): void; + updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): AbstractMesh; /** - * Set the motor's limits. - * Attention, this function is plugin specific. Engines won't react 100% the same. + * Sets the mesh indices, + * If the mesh has no geometry, a new Geometry object is created and set to the mesh. + * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array) + * @param totalVertices Defines the total number of vertices + * @returns the current mesh */ - setLimit(upperLimit: number, lowerLimit?: number): void; - } - /** - * This class represents a single hinge physics joint - */ - class HingeJoint extends MotorEnabledJoint { - constructor(jointData: PhysicsJointData); + setIndices(indices: IndicesArray, totalVertices: Nullable): AbstractMesh; /** - * Set the motor values. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param {number} force the force to apply - * @param {number} maxForce max force for this motor. + * Gets a boolean indicating if specific vertex data is present + * @param kind defines the vertex data kind to use + * @returns true is data kind is present */ - setMotor(force?: number, maxForce?: number): void; + isVerticesDataPresent(kind: string): boolean; /** - * Set the motor's limits. - * Attention, this function is plugin specific. Engines won't react 100% the same. + * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined + * @returns a BoundingInfo */ - setLimit(upperLimit: number, lowerLimit?: number): void; - } - /** - * This class represents a dual hinge physics joint (same as wheel joint) - */ - class Hinge2Joint extends MotorEnabledJoint { - constructor(jointData: PhysicsJointData); + getBoundingInfo(): BoundingInfo; /** - * Set the motor values. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param {number} force the force to apply - * @param {number} maxForce max force for this motor. - * @param {motorIndex} the motor's index, 0 or 1. + * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units) + * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box + * @returns the current mesh */ - setMotor(force?: number, maxForce?: number, motorIndex?: number): void; + normalizeToUnitCube(includeDescendants?: boolean): AbstractMesh; /** - * Set the motor limits. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param {number} upperLimit the upper limit - * @param {number} lowerLimit lower limit - * @param {motorIndex} the motor's index, 0 or 1. + * Overwrite the current bounding info + * @param boundingInfo defines the new bounding info + * @returns the current mesh */ - setLimit(upperLimit: number, lowerLimit?: number, motorIndex?: number): void; - } - interface IMotorEnabledJoint { - physicsJoint: any; - setMotor(force?: number, maxForce?: number, motorIndex?: number): void; - setLimit(upperLimit: number, lowerLimit?: number, motorIndex?: number): void; - } - interface DistanceJointData extends PhysicsJointData { - maxDistance: number; - } - interface SpringJointData extends PhysicsJointData { - length: number; - stiffness: number; - damping: number; - } -} - -declare module BABYLON { - /** - * This represents a GPU particle system in Babylon - * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data - * @see https://www.babylonjs-playground.com/#PU4WYI#4 - */ - class GPUParticleSystem implements IDisposable, IParticleSystem, IAnimatable { + setBoundingInfo(boundingInfo: BoundingInfo): AbstractMesh; + /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */ + readonly useBones: boolean; + /** @hidden */ + _preActivate(): void; + /** @hidden */ + _preActivateForIntermediateRendering(renderId: number): void; + /** @hidden */ + _activate(renderId: number): void; /** - * The id of the Particle system. + * Gets the current world matrix + * @returns a Matrix */ - id: string; + getWorldMatrix(): Matrix; + /** @hidden */ + _getWorldMatrixDeterminant(): number; /** - * The friendly name of the Particle system. + * Perform relative position change from the point of view of behind the front of the mesh. + * This is performed taking into account the meshes current rotation, so you do not have to care. + * Supports definition of mesh facing forward or backward + * @param amountRight defines the distance on the right axis + * @param amountUp defines the distance on the up axis + * @param amountForward defines the distance on the forward axis + * @returns the current mesh */ - name: string; + movePOV(amountRight: number, amountUp: number, amountForward: number): AbstractMesh; /** - * The emitter represents the Mesh or position we are attaching the particle system to. + * Calculate relative position change from the point of view of behind the front of the mesh. + * This is performed taking into account the meshes current rotation, so you do not have to care. + * Supports definition of mesh facing forward or backward + * @param amountRight defines the distance on the right axis + * @param amountUp defines the distance on the up axis + * @param amountForward defines the distance on the forward axis + * @returns the new displacement vector */ - emitter: Nullable; + calcMovePOV(amountRight: number, amountUp: number, amountForward: number): Vector3; /** - * The rendering group used by the Particle system to chose when to render. + * Perform relative rotation change from the point of view of behind the front of the mesh. + * Supports definition of mesh facing forward or backward + * @param flipBack defines the flip + * @param twirlClockwise defines the twirl + * @param tiltRight defines the tilt + * @returns the current mesh */ - renderingGroupId: number; + rotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): AbstractMesh; /** - * The layer mask we are rendering the particles through. + * Calculate relative rotation change from the point of view of behind the front of the mesh. + * Supports definition of mesh facing forward or backward. + * @param flipBack defines the flip + * @param twirlClockwise defines the twirl + * @param tiltRight defines the tilt + * @returns the new rotation vector */ - layerMask: number; - private _capacity; - private _activeCount; - private _currentActiveCount; - private _accumulatedCount; - private _renderEffect; - private _updateEffect; - private _buffer0; - private _buffer1; - private _spriteBuffer; - private _updateVAO; - private _renderVAO; - private _targetIndex; - private _sourceBuffer; - private _targetBuffer; - private _scene; - private _engine; - private _currentRenderId; - private _started; - private _stopped; - private _timeDelta; - private _randomTexture; - private _randomTexture2; - private _attributesStrideSize; - private _updateEffectOptions; - private _randomTextureSize; - private _actualFrame; - private readonly _rawTextureWidth; + calcRotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): Vector3; /** - * List of animations used by the particle system. + * Return the minimum and maximum world vectors of the entire hierarchy under current mesh + * @param includeDescendants Include bounding info from descendants as well (true by default) + * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors + * @returns the new bounding vectors */ - animations: Animation[]; + getHierarchyBoundingVectors(includeDescendants?: boolean, predicate?: Nullable<(abstractMesh: AbstractMesh) => boolean>): { + min: Vector3; + max: Vector3; + }; + /** @hidden */ + _updateBoundingInfo(): AbstractMesh; + /** @hidden */ + _updateSubMeshesBoundingInfo(matrix: Matrix): AbstractMesh; + /** @hidden */ + protected _afterComputeWorldMatrix(): void; /** - * Gets a boolean indicating if the GPU particles can be rendered on current browser + * Returns `true` if the mesh is within the frustum defined by the passed array of planes. + * A mesh is in the frustum if its bounding box intersects the frustum + * @param frustumPlanes defines the frustum to test + * @returns true if the mesh is in the frustum planes */ - static readonly IsSupported: boolean; - /** - * An event triggered when the system is disposed. - */ - onDisposeObservable: Observable; + isInFrustum(frustumPlanes: Plane[]): boolean; /** - * The overall motion speed (0.01 is default update speed, faster updates = faster animation) + * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes. + * A mesh is completely in the frustum if its bounding box it completely inside the frustum. + * @param frustumPlanes defines the frustum to test + * @returns true if the mesh is completely in the frustum planes */ - updateSpeed: number; + isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; /** - * The amount of time the particle system is running (depends of the overall update speed). + * True if the mesh intersects another mesh or a SolidParticle object + * @param mesh defines a target mesh or SolidParticle to test + * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes) + * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes + * @returns true if there is an intersection */ - targetStopDuration: number; + intersectsMesh(mesh: AbstractMesh | SolidParticle, precise?: boolean, includeDescendants?: boolean): boolean; /** - * The texture used to render each particle. (this can be a spritesheet) + * Returns true if the passed point (Vector3) is inside the mesh bounding box + * @param point defines the point to test + * @returns true if there is an intersection */ - particleTexture: Nullable; + intersectsPoint(point: Vector3): boolean; /** - * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD. + * Gets the current physics impostor + * @see http://doc.babylonjs.com/features/physics_engine + * @returns a physics impostor or null */ - blendMode: number; + getPhysicsImpostor(): Nullable; /** - * Minimum life time of emitting particles. + * Gets the position of the current mesh in camera space + * @param camera defines the camera to use + * @returns a position */ - minLifeTime: number; + getPositionInCameraSpace(camera?: Nullable): Vector3; /** - * Maximum life time of emitting particles. + * Returns the distance from the mesh to the active camera + * @param camera defines the camera to use + * @returns the distance */ - maxLifeTime: number; + getDistanceToCamera(camera?: Nullable): number; /** - * Minimum Size of emitting particles. + * Apply a physic impulse to the mesh + * @param force defines the force to apply + * @param contactPoint defines where to apply the force + * @returns the current mesh + * @see http://doc.babylonjs.com/how_to/using_the_physics_engine */ - minSize: number; + applyImpulse(force: Vector3, contactPoint: Vector3): AbstractMesh; /** - * Maximum Size of emitting particles. + * Creates a physic joint between two meshes + * @param otherMesh defines the other mesh to use + * @param pivot1 defines the pivot to use on this mesh + * @param pivot2 defines the pivot to use on the other mesh + * @param options defines additional options (can be plugin dependent) + * @returns the current mesh + * @see https://www.babylonjs-playground.com/#0BS5U0#0 */ - maxSize: number; + setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3, options?: any): AbstractMesh; /** - * Minimum scale of emitting particles on X axis. + * Gets or sets a boolean indicating that this mesh can be used in the collision engine + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ - minScaleX: number; + checkCollisions: boolean; /** - * Maximum scale of emitting particles on X axis. + * Gets Collider object used to compute collisions (not physics) + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ - maxScaleX: number; + readonly collider: Collider; /** - * Minimum scale of emitting particles on Y axis. + * Move the mesh using collision engine + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity + * @param displacement defines the requested displacement vector + * @returns the current mesh */ - minScaleY: number; + moveWithCollisions(displacement: Vector3): AbstractMesh; + private _onCollisionPositionChange; /** - * Maximum scale of emitting particles on Y axis. - */ - maxScaleY: number; + * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations. + * Please note that you must have a decent number of submeshes to get performance improvements when using an octree + * @param maxCapacity defines the maximum size of each block (64 by default) + * @param maxDepth defines the maximum depth to use (no more than 2 levels by default) + * @returns the new octree + * @see https://www.babylonjs-playground.com/#NA4OQ#12 + * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees + */ + createOrUpdateSubmeshesOctree(maxCapacity?: number, maxDepth?: number): Octree; + /** @hidden */ + _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): AbstractMesh; + /** @hidden */ + _processCollisionsForSubMeshes(collider: Collider, transformMatrix: Matrix): AbstractMesh; + /** @hidden */ + _checkCollision(collider: Collider): AbstractMesh; + /** @hidden */ + _generatePointsArray(): boolean; /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors. + * Checks if the passed Ray intersects with the mesh + * @param ray defines the ray to use + * @param fastCheck defines if fast mode (but less precise) must be used (false by default) + * @returns the picking info + * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh */ - color1: Color4; + intersects(ray: Ray, fastCheck?: boolean): PickingInfo; /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors. + * Clones the current mesh + * @param name defines the mesh name + * @param newParent defines the new mesh parent + * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default) + * @returns the new mesh */ - color2: Color4; + clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable; /** - * Color the particle will have at the end of its lifetime. + * Disposes all the submeshes of the current meshnp + * @returns the current mesh */ - colorDead: Color4; + releaseSubMeshes(): AbstractMesh; /** - * The maximum number of particles to emit per frame until we reach the activeParticleCount value + * Releases resources associated with this abstract mesh. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) */ - emitRate: number; + dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; /** - * You can use gravity if you want to give an orientation to your particles. + * Adds the passed mesh as a child to the current mesh + * @param mesh defines the child mesh + * @returns the current mesh */ - gravity: Vector3; + addChild(mesh: AbstractMesh): AbstractMesh; /** - * Minimum power of emitting particles. + * Removes the passed mesh from the current mesh children list + * @param mesh defines the child mesh + * @returns the current mesh */ - minEmitPower: number; + removeChild(mesh: AbstractMesh): AbstractMesh; + /** @hidden */ + private _initFacetData; /** - * Maximum power of emitting particles. + * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated. + * This method can be called within the render loop. + * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation + * @returns the current mesh + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - maxEmitPower: number; + updateFacetData(): AbstractMesh; /** - * Minimum angular speed of emitting particles (Z-axis rotation for each particle). + * Returns the facetLocalNormals array. + * The normals are expressed in the mesh local spac + * @returns an array of Vector3 + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - minAngularSpeed: number; + getFacetLocalNormals(): Vector3[]; /** - * Maximum angular speed of emitting particles (Z-axis rotation for each particle). + * Returns the facetLocalPositions array. + * The facet positions are expressed in the mesh local space + * @returns an array of Vector3 + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - maxAngularSpeed: number; + getFacetLocalPositions(): Vector3[]; /** - * The particle emitter type defines the emitter used by the particle system. - * It can be for example box, sphere, or cone... + * Returns the facetLocalPartioning array + * @returns an array of array of numbers + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - particleEmitterType: Nullable; + getFacetLocalPartitioning(): number[][]; /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Returns the i-th facet position in the world system. + * This method allocates a new Vector3 per call + * @param i defines the facet index + * @returns a new Vector3 + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - direction1: Vector3; + getFacetPosition(i: number): Vector3; /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Sets the reference Vector3 with the i-th facet position in the world system + * @param i defines the facet index + * @param ref defines the target vector + * @returns the current mesh + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - direction2: Vector3; + getFacetPositionToRef(i: number, ref: Vector3): AbstractMesh; /** - * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Returns the i-th facet normal in the world system. + * This method allocates a new Vector3 per call + * @param i defines the facet index + * @returns a new Vector3 + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - minEmitBox: Vector3; + getFacetNormal(i: number): Vector3; /** - * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Sets the reference Vector3 with the i-th facet normal in the world system + * @param i defines the facet index + * @param ref defines the target vector + * @returns the current mesh + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - maxEmitBox: Vector3; + getFacetNormalToRef(i: number, ref: Vector3): this; /** - * Gets the maximum number of particles active at the same time. - * @returns The max number of active particles. + * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system) + * @param x defines x coordinate + * @param y defines y coordinate + * @param z defines z coordinate + * @returns the array of facet indexes + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - getCapacity(): number; + getFacetsAtLocalCoordinates(x: number, y: number, z: number): Nullable; /** - * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls - * to override the particles. + * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found + * @param projected sets as the (x,y,z) world projection on the facet + * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned + * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position + * @param x defines x coordinate + * @param y defines y coordinate + * @param z defines z coordinate + * @returns the face index if found (or null instead) + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - forceDepthWrite: boolean; + getClosestFacetAtCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace?: boolean, facing?: boolean): Nullable; /** - * Gets or set the number of active particles + * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found + * @param projected sets as the (x,y,z) local projection on the facet + * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned + * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position + * @param x defines x coordinate + * @param y defines y coordinate + * @param z defines z coordinate + * @returns the face index if found (or null instead) + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - activeParticleCount: number; - private _preWarmDone; - /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */ - preWarmCycles: number; - /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */ - preWarmStepOffset: number; + getClosestFacetAtLocalCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace?: boolean, facing?: boolean): Nullable; /** - * Gets or sets the minimal initial rotation in radians. + * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals() + * @returns the parameters + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - minInitialRotation: number; + getFacetDataParameters(): any; /** - * Gets or sets the maximal initial rotation in radians. + * Disables the feature FacetData and frees the related memory + * @returns the current mesh + * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ - maxInitialRotation: number; + disableFacetData(): AbstractMesh; /** - * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime) + * Updates the AbstractMesh indices array + * @param indices defines the data source + * @returns the current mesh */ - spriteCellChangeSpeed: number; + updateIndices(indices: IndicesArray): AbstractMesh; /** - * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display + * Creates new normals data for the mesh + * @param updatable defines if the normal vertex buffer must be flagged as updatable + * @returns the current mesh */ - startSpriteCellID: number; + createNormals(updatable: boolean): AbstractMesh; /** - * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display + * Align the mesh with a normal + * @param normal defines the normal to use + * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default) + * @returns the current mesh */ - endSpriteCellID: number; + alignWithNormal(normal: Vector3, upDirection?: Vector3): AbstractMesh; + /** @hidden */ + _checkOcclusionQuery(): void; + } +} + +declare module BABYLON { + class Buffer { + private _engine; + private _buffer; + /** @hidden */ + _data: Nullable; + private _updatable; + private _instanced; /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use + * Gets the byte stride. */ - spriteCellWidth: number; + readonly byteStride: number; /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use + * Constructor + * @param engine the engine + * @param data the data to use for this buffer + * @param updatable whether the data is updatable + * @param stride the stride (optional) + * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional) + * @param instanced whether the buffer is instanced (optional) + * @param useBytes set to true if the stride in in bytes (optional) */ - spriteCellHeight: number; - /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ - translationPivot: Vector2; + constructor(engine: any, data: DataArray, updatable: boolean, stride?: number, postponeInternalCreation?: boolean, instanced?: boolean, useBytes?: boolean); /** - * Gets or sets a texture used to add random noise to particle positions + * Create a new {BABYLON.VertexBuffer} based on the current buffer + * @param kind defines the vertex buffer kind (position, normal, etc.) + * @param offset defines offset in the buffer (0 by default) + * @param size defines the size in floats of attributes (position is 3 for instance) + * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved) + * @param instanced defines if the vertex buffer contains indexed data + * @param useBytes defines if the offset and stride are in bytes + * @returns the new vertex buffer */ - noiseTexture: Nullable; - /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ - noiseStrength: Vector3; + createVertexBuffer(kind: string, offset: number, size: number, stride?: number, instanced?: boolean, useBytes?: boolean): VertexBuffer; + isUpdatable(): boolean; + getData(): Nullable; + getBuffer(): Nullable; /** - * Gets or sets the billboard mode to use when isBillboardBased = true. - * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far + * Gets the stride in float32 units (i.e. byte stride / 4). + * May not be an integer if the byte stride is not divisible by 4. + * DEPRECATED. Use byteStride instead. + * @returns the stride in float32 units */ - billboardMode: number; - private _isAnimationSheetEnabled; + getStrideSize(): number; + create(data?: Nullable): void; + _rebuild(): void; + update(data: DataArray): void; /** - * Gets whether an animation sprite sheet is enabled or not on the particle system + * Updates the data directly. + * @param data the new data + * @param offset the new offset + * @param vertexCount the vertex count (optional) + * @param useBytes set to true if the offset is in bytes */ - readonly isAnimationSheetEnabled: boolean; + updateDirectly(data: DataArray, offset: number, vertexCount?: number, useBytes?: boolean): void; + dispose(): void; + } +} + +declare module BABYLON { + class CSG { + private polygons; + matrix: Matrix; + position: Vector3; + rotation: Vector3; + rotationQuaternion: Nullable; + scaling: Vector3; + static FromMesh(mesh: Mesh): CSG; + private static FromPolygons; + clone(): CSG; + union(csg: CSG): CSG; + unionInPlace(csg: CSG): void; + subtract(csg: CSG): CSG; + subtractInPlace(csg: CSG): void; + intersect(csg: CSG): CSG; + intersectInPlace(csg: CSG): void; + inverse(): CSG; + inverseInPlace(): void; + copyTransformAttributes(csg: CSG): CSG; + buildMeshGeometry(name: string, scene: Scene, keepSubMeshes: boolean): Mesh; + toMesh(name: string, material: Nullable, scene: Scene, keepSubMeshes: boolean): Mesh; + } +} + +declare module BABYLON { + /** + * Class used to store geometry data (vertex buffers + index buffer) + */ + class Geometry implements IGetSetVerticesData { /** - * Is this system ready to be used/rendered - * @return true if the system is ready + * Gets or sets the unique ID of the geometry */ - isReady(): boolean; + id: string; /** - * Gets Wether the system has been started. - * @returns True if it has been started, otherwise false. + * Gets the delay loading state of the geometry (none by default which means not delayed) */ - isStarted(): boolean; + delayLoadState: number; /** - * Starts the particle system and begins to emit - * @param delay defines the delay in milliseconds before starting the system (0 by default) + * Gets the file containing the data to load when running in delay load state */ - start(delay?: number): void; + delayLoadingFile: Nullable; /** - * Stops the particle system. + * Callback called when the geometry is updated */ - stop(): void; - /** - * Remove all active particles - */ - reset(): void; + onGeometryUpdated: (geometry: Geometry, kind?: string) => void; + private _scene; + private _engine; + private _meshes; + private _totalVertices; + /** @hidden */ + _indices: IndicesArray; + /** @hidden */ + _vertexBuffers: { + [key: string]: VertexBuffer; + }; + private _isDisposed; + private _extend; + private _boundingBias; + /** @hidden */ + _delayInfo: Array; + private _indexBuffer; + private _indexBufferIsUpdatable; + /** @hidden */ + _boundingInfo: Nullable; + /** @hidden */ + _delayLoadingFunction: Nullable<(any: any, geometry: Geometry) => void>; + /** @hidden */ + _softwareSkinningRenderId: number; + private _vertexArrayObjects; + private _updatable; + /** @hidden */ + _positions: Nullable; /** - * Returns the string "GPUParticleSystem" - * @returns a string containing the class name + * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y */ - getClassName(): string; - private _isBillboardBased; /** - * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction - */ - isBillboardBased: boolean; - private _colorGradients; - private _colorGradientsTexture; + * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y + */ + boundingBias: Vector2; /** - * Gets the current list of color gradients. - * You must use addColorGradient and removeColorGradient to udpate this list - * @returns the list of color gradients + * Static function used to attach a new empty geometry to a mesh + * @param mesh defines the mesh to attach the geometry to + * @returns the new {BABYLON.Geometry} */ - getColorGradients(): Nullable>; + static CreateGeometryForMesh(mesh: Mesh): Geometry; /** - * Gets the current list of size gradients. - * You must use addSizeGradient and removeSizeGradient to udpate this list - * @returns the list of size gradients + * Creates a new geometry + * @param id defines the unique ID + * @param scene defines the hosting scene + * @param vertexData defines the {BABYLON.VertexData} used to get geometry data + * @param updatable defines if geometry must be updatable (false by default) + * @param mesh defines the mesh that will be associated with the geometry */ - getSizeGradients(): Nullable>; + constructor(id: string, scene: Scene, vertexData?: VertexData, updatable?: boolean, mesh?: Nullable); /** - * Gets the current list of angular speed gradients. - * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list - * @returns the list of angular speed gradients + * Gets the current extend of the geometry */ - getAngularSpeedGradients(): Nullable>; + readonly extend: { + minimum: Vector3; + maximum: Vector3; + }; /** - * Gets the current list of velocity gradients. - * You must use addVelocityGradient and removeVelocityGradient to udpate this list - * @returns the list of angular speed gradients + * Gets the hosting scene + * @returns the hosting {BABYLON.Scene} */ - getVelocityGradients(): Nullable>; - private _removeGradient(gradient, gradients, texture); + getScene(): Scene; /** - * Adds a new color gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param color defines the color to affect to the specified gradient - * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from - * @returns the current particle system + * Gets the hosting engine + * @returns the hosting {BABYLON.Engine} */ - addColorGradient(gradient: number, color1: Color4, color2?: Color4): GPUParticleSystem; + getEngine(): Engine; /** - * Remove a specific color gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Defines if the geometry is ready to use + * @returns true if the geometry is ready to be used */ - removeColorGradient(gradient: number): GPUParticleSystem; - private _angularSpeedGradients; - private _angularSpeedGradientsTexture; - private _sizeGradients; - private _sizeGradientsTexture; - private _velocityGradients; - private _velocityGradientsTexture; - private _addFactorGradient(factorGradients, gradient, factor); + isReady(): boolean; /** - * Adds a new size gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @returns the current particle system + * Gets a value indicating that the geometry should not be serialized */ - addSizeGradient(gradient: number, factor: number): GPUParticleSystem; + readonly doNotSerialize: boolean; + /** @hidden */ + _rebuild(): void; /** - * Remove a specific size gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Affects all geometry data in one call + * @param vertexData defines the geometry data + * @param updatable defines if the geometry must be flagged as updatable (false as default) */ - removeSizeGradient(gradient: number): GPUParticleSystem; + setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; /** - * Adds a new angular speed gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @returns the current particle system + * Set specific vertex data + * @param kind defines the data kind (Position, normal, etc...) + * @param data defines the vertex data to use + * @param updatable defines if the vertex must be flagged as updatable (false as default) + * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified */ - addAngularSpeedGradient(gradient: number, factor: number): GPUParticleSystem; + setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): void; /** - * Remove a specific angular speed gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Removes a specific vertex data + * @param kind defines the data kind (Position, normal, etc...) */ - removeAngularSpeedGradient(gradient: number): GPUParticleSystem; + removeVerticesData(kind: string): void; /** - * Adds a new velocity gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @returns the current particle system + * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data + * @param buffer defines the vertex buffer to use + * @param totalVertices defines the total number of vertices for position kind (could be null) */ - addVelocityGradient(gradient: number, factor: number): GPUParticleSystem; + setVerticesBuffer(buffer: VertexBuffer, totalVertices?: Nullable): void; /** - * Remove a specific velocity gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Update a specific vertex buffer + * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array + * It will do nothing if the buffer is not updatable + * @param kind defines the data kind (Position, normal, etc...) + * @param data defines the data to use + * @param offset defines the offset in the target buffer where to store the data + * @param useBytes set to true if the offset is in bytes */ - removeVelocityGradient(gradient: number): GPUParticleSystem; + updateVerticesDataDirectly(kind: string, data: DataArray, offset: number, useBytes?: boolean): void; /** - * Instantiates a GPU particle system. - * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. - * @param name The name of the particle system - * @param options The options used to create the system - * @param scene The scene the particle system belongs to - * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture + * Update a specific vertex buffer + * This function will create a new buffer if the current one is not updatable + * @param kind defines the data kind (Position, normal, etc...) + * @param data defines the data to use + * @param updateExtends defines if the geometry extends must be recomputed (false by default) */ - constructor(name: string, options: Partial<{ - capacity: number; - randomTextureSize: number; - }>, scene: Scene, isAnimationSheetEnabled?: boolean); - private _createUpdateVAO(source); - private _createRenderVAO(source, spriteSource); - private _initialize(force?); - /** @hidden */ - _recreateUpdateEffect(): void; + updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean): void; + private _updateBoundingInfo; /** @hidden */ - _recreateRenderEffect(): void; + _bind(effect: Nullable, indexToBind?: Nullable): void; /** - * Animates the particle system for the current frame by emitting new particles and or animating the living ones. - * @param preWarm defines if we are in the pre-warmimg phase + * Gets total number of vertices + * @returns the total number of vertices */ - animate(preWarm?: boolean): void; - private _createFactorGradientTexture(factorGradients, textureName); - private _createSizeGradientTexture(); - private _createAngularSpeedGradientTexture(); - private _createVelocityGradientTexture(); - private _createColorGradientTexture(); + getTotalVertices(): number; /** - * Renders the particle system in its current state - * @param preWarm defines if the system should only update the particles but not render them - * @returns the current number of particles + * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly. + * @param kind defines the data kind (Position, normal, etc...) + * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes + * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it + * @returns a float array containing vertex data */ - render(preWarm?: boolean): number; + getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable; /** - * Rebuilds the particle system + * Returns a boolean defining if the vertex data for the requested `kind` is updatable + * @param kind defines the data kind (Position, normal, etc...) + * @returns true if the vertex buffer with the specified kind is updatable */ - rebuild(): void; - private _releaseBuffers(); - private _releaseVAOs(); + isVertexBufferUpdatable(kind: string): boolean; /** - * Disposes the particle system and free the associated resources - * @param disposeTexture defines if the particule texture must be disposed as well (true by default) + * Gets a specific vertex buffer + * @param kind defines the data kind (Position, normal, etc...) + * @returns a {BABYLON.VertexBuffer} */ - dispose(disposeTexture?: boolean): void; + getVertexBuffer(kind: string): Nullable; /** - * Clones the particle system. - * @param name The name of the cloned object - * @param newEmitter The new emitter to use - * @returns the cloned particle system + * Returns all vertex buffers + * @return an object holding all vertex buffers indexed by kind */ - clone(name: string, newEmitter: any): Nullable; + getVertexBuffers(): Nullable<{ + [key: string]: VertexBuffer; + }>; /** - * Serializes the particle system to a JSON object. - * @returns the JSON object + * Gets a boolean indicating if specific vertex buffer is present + * @param kind defines the data kind (Position, normal, etc...) + * @returns true if data is present */ - serialize(): any; + isVerticesDataPresent(kind: string): boolean; /** - * Parses a JSON object to create a GPU particle system. - * @param parsedParticleSystem The JSON object to parse - * @param scene The scene to create the particle system in - * @param rootUrl The root url to use to load external dependencies like texture - * @returns the parsed GPU particle system + * Gets a list of all attached data kinds (Position, normal, etc...) + * @returns a list of string containing all kinds */ - static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): GPUParticleSystem; - } -} - -declare module BABYLON { - /** - * Interface representing a particle system in Babylon.js. - * This groups the common functionalities that needs to be implemented in order to create a particle system. - * A particle system represents a way to manage particles from their emission to their animation and rendering. - */ - interface IParticleSystem { + getVerticesDataKinds(): string[]; /** - * List of animations used by the particle system. + * Update index buffer + * @param indices defines the indices to store in the index buffer + * @param offset defines the offset in the target buffer where to store the data */ - animations: Animation[]; + updateIndices(indices: IndicesArray, offset?: number): void; /** - * The id of the Particle system. + * Creates a new index buffer + * @param indices defines the indices to store in the index buffer + * @param totalVertices defines the total number of vertices (could be null) + * @param updatable defines if the index buffer must be flagged as updatable (false by default) */ - id: string; + setIndices(indices: IndicesArray, totalVertices?: Nullable, updatable?: boolean): void; /** - * The name of the Particle system. + * Return the total number of indices + * @returns the total number of indices */ - name: string; + getTotalIndices(): number; /** - * The emitter represents the Mesh or position we are attaching the particle system to. + * Gets the index buffer array + * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes + * @returns the index buffer array */ - emitter: Nullable; + getIndices(copyWhenShared?: boolean): Nullable; /** - * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction + * Gets the index buffer + * @return the index buffer */ - isBillboardBased: boolean; + getIndexBuffer(): Nullable; + /** @hidden */ + _releaseVertexArrayObject(effect?: Nullable): void; /** - * The rendering group used by the Particle system to chose when to render. + * Release the associated resources for a specific mesh + * @param mesh defines the source mesh + * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it */ - renderingGroupId: number; + releaseForMesh(mesh: Mesh, shouldDispose?: boolean): void; /** - * The layer mask we are rendering the particles through. + * Apply current geometry to a given mesh + * @param mesh defines the mesh to apply geometry to */ - layerMask: number; + applyToMesh(mesh: Mesh): void; + private _updateExtend; + private _applyToMesh; + private notifyUpdate; /** - * The overall motion speed (0.01 is default update speed, faster updates = faster animation) - */ - updateSpeed: number; + * Load the geometry if it was flagged as delay loaded + * @param scene defines the hosting scene + * @param onLoaded defines a callback called when the geometry is loaded + */ + load(scene: Scene, onLoaded?: () => void): void; + private _queueLoad; /** - * The amount of time the particle system is running (depends of the overall update speed). + * Invert the geometry to move from a right handed system to a left handed one. */ - targetStopDuration: number; + toLeftHanded(): void; + /** @hidden */ + _resetPointsArrayCache(): void; + /** @hidden */ + _generatePointsArray(): boolean; /** - * The texture used to render each particle. (this can be a spritesheet) + * Gets a value indicating if the geometry is disposed + * @returns true if the geometry was disposed */ - particleTexture: Nullable; + isDisposed(): boolean; + private _disposeVertexArrayObjects; /** - * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE, ParticleSystem.BLENDMODE_STANDARD or ParticleSystem.BLENDMODE_ADD. + * Free all associated resources */ - blendMode: number; + dispose(): void; /** - * Minimum life time of emitting particles. + * Clone the current geometry into a new geometry + * @param id defines the unique ID of the new geometry + * @returns a new geometry object */ - minLifeTime: number; + copy(id: string): Geometry; /** - * Maximum life time of emitting particles. + * Serialize the current geometry info (and not the vertices data) into a JSON object + * @return a JSON representation of the current geometry data (without the vertices data) */ - maxLifeTime: number; + serialize(): any; + private toNumberArray; /** - * Minimum Size of emitting particles. + * Serialize all vertices data into a JSON oject + * @returns a JSON representation of the current geometry data */ - minSize: number; + serializeVerticeData(): any; /** - * Maximum Size of emitting particles. + * Extracts a clone of a mesh geometry + * @param mesh defines the source mesh + * @param id defines the unique ID of the new geometry object + * @returns the new geometry object */ - maxSize: number; + static ExtractFromMesh(mesh: Mesh, id: string): Nullable; /** - * Minimum scale of emitting particles on X axis. + * You should now use Tools.RandomId(), this method is still here for legacy reasons. + * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 + * Be aware Math.random() could cause collisions, but: + * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide" + * @returns a string containing a new GUID */ - minScaleX: number; + static RandomId(): string; + /** @hidden */ + static _ImportGeometry(parsedGeometry: any, mesh: Mesh): void; + private static _CleanMatricesWeights; /** - * Maximum scale of emitting particles on X axis. + * Create a new geometry from persisted data (Using .babylon file format) + * @param parsedVertexData defines the persisted data + * @param scene defines the hosting scene + * @param rootUrl defines the root url to use to load assets (like delayed data) + * @returns the new geometry object */ - maxScaleX: number; + static Parse(parsedVertexData: any, scene: Scene, rootUrl: string): Nullable; + } + /** + * Abstract class used to provide common services for all typed geometries + * @hidden + */ + class _PrimitiveGeometry extends Geometry { + private _canBeRegenerated; + private _beingRegenerated; /** - * Minimum scale of emitting particles on Y axis. + * Creates a new typed geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) */ - minScaleY: number; + constructor(id: string, scene: Scene, _canBeRegenerated?: boolean, mesh?: Nullable); /** - * Maximum scale of emitting particles on Y axis. + * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default) + * @returns true if the geometry can be regenerated */ - maxScaleY: number; + canBeRegenerated(): boolean; /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors. + * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values */ - color1: Color4; + regenerate(): void; /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors. + * Clone the geometry + * @param id defines the unique ID of the new geometry + * @returns the new geometry */ - color2: Color4; + asNewGeometry(id: string): Geometry; + setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; + setVerticesData(kind: string, data: FloatArray, updatable?: boolean): void; + /** @hidden */ + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + } + /** + * Creates a ribbon geometry + * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons + */ + class RibbonGeometry extends _PrimitiveGeometry { /** - * Color the particle will have at the end of its lifetime. + * Defines the array of paths to use */ - colorDead: Color4; + pathArray: Vector3[][]; /** - * The maximum number of particles to emit per frame until we reach the activeParticleCount value + * Defines if the last and first points of each path in your pathArray must be joined */ - emitRate: number; + closeArray: boolean; /** - * You can use gravity if you want to give an orientation to your particles. + * Defines if the last and first points of each path in your pathArray must be joined */ - gravity: Vector3; + closePath: boolean; /** - * Minimum power of emitting particles. + * Defines the offset between points */ - minEmitPower: number; + offset: number; /** - * Maximum power of emitting particles. + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - maxEmitPower: number; + side: number; /** - * Minimum angular speed of emitting particles (Z-axis rotation for each particle). + * Creates a ribbon geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param pathArray defines the array of paths to use + * @param closeArray defines if the last path and the first path must be joined + * @param closePath defines if the last and first points of each path in your pathArray must be joined + * @param offset defines the offset between points + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - minAngularSpeed: number; + constructor(id: string, scene: Scene, /** - * Maximum angular speed of emitting particles (Z-axis rotation for each particle). + * Defines the array of paths to use */ - maxAngularSpeed: number; + pathArray: Vector3[][], /** - * Gets or sets the minimal initial rotation in radians. + * Defines if the last and first points of each path in your pathArray must be joined */ - minInitialRotation: number; + closeArray: boolean, /** - * Gets or sets the maximal initial rotation in radians. + * Defines if the last and first points of each path in your pathArray must be joined */ - maxInitialRotation: number; + closePath: boolean, /** - * The particle emitter type defines the emitter used by the particle system. - * It can be for example box, sphere, or cone... + * Defines the offset between points */ - particleEmitterType: Nullable; + offset: number, canBeRegenerated?: boolean, mesh?: Mesh, /** - * Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - preWarmCycles: number; + side?: number); + /** @hidden */ + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + /** + * Creates a box geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#box + */ + class BoxGeometry extends _PrimitiveGeometry { /** - * Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) + * Defines the zise of the box (width, height and depth are the same) */ - preWarmStepOffset: number; + size: number; /** - * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime) + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - spriteCellChangeSpeed: number; + side: number; /** - * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display + * Creates a box geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param size defines the zise of the box (width, height and depth are the same) + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - startSpriteCellID: number; + constructor(id: string, scene: Scene, /** - * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display + * Defines the zise of the box (width, height and depth are the same) */ - endSpriteCellID: number; + size: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - spriteCellWidth: number; + side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedBox: any, scene: Scene): Nullable; + } + /** + * Creates a sphere geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere + */ + class SphereGeometry extends _PrimitiveGeometry { /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use + * Defines the number of segments to use to create the sphere */ - spriteCellHeight: number; - /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ - translationPivot: Vector2; + segments: number; /** - * Gets or sets a texture used to add random noise to particle positions + * Defines the diameter of the sphere */ - noiseTexture: Nullable; - /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ - noiseStrength: Vector3; + diameter: number; /** - * Gets or sets the billboard mode to use when isBillboardBased = true. - * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - billboardMode: number; + side: number; /** - * Gets the maximum number of particles active at the same time. - * @returns The max number of active particles. + * Create a new sphere geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param segments defines the number of segments to use to create the sphere + * @param diameter defines the diameter of the sphere + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - getCapacity(): number; + constructor(id: string, scene: Scene, /** - * Gets Wether the system has been started. - * @returns True if it has been started, otherwise false. - */ - isStarted(): boolean; - /** - * Gets if the particle system has been started. - * @return true if the system has been started, otherwise false. + * Defines the number of segments to use to create the sphere */ - isStarted(): boolean; + segments: number, /** - * Animates the particle system for this frame. + * Defines the diameter of the sphere */ - animate(): void; + diameter: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * Renders the particle system in its current state. - * @returns the current number of particles + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - render(): number; + side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedSphere: any, scene: Scene): Nullable; + } + /** + * Creates a disc geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon + */ + class DiscGeometry extends _PrimitiveGeometry { /** - * Dispose the particle system and frees its associated resources. - * @param disposeTexture defines if the particule texture must be disposed as well (true by default) + * Defines the radius of the disc */ - dispose(disposeTexture?: boolean): void; + radius: number; /** - * Clones the particle system. - * @param name The name of the cloned object - * @param newEmitter The new emitter to use - * @returns the cloned particle system + * Defines the tesselation factor to apply to the disc */ - clone(name: string, newEmitter: any): Nullable; + tessellation: number; /** - * Serializes the particle system to a JSON object. - * @returns the JSON object + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - serialize(): any; + side: number; /** - * Rebuild the particle system + * Creates a new disc geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param radius defines the radius of the disc + * @param tessellation defines the tesselation factor to apply to the disc + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - rebuild(): void; + constructor(id: string, scene: Scene, /** - * Starts the particle system and begins to emit - * @param delay defines the delay in milliseconds before starting the system (0 by default) + * Defines the radius of the disc */ - start(delay?: number): void; + radius: number, /** - * Stops the particle system. + * Defines the tesselation factor to apply to the disc */ - stop(): void; + tessellation: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * Remove all active particles + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - reset(): void; + side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + /** + * Creates a new cylinder geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone + */ + class CylinderGeometry extends _PrimitiveGeometry { /** - * Is this system ready to be used/rendered - * @return true if the system is ready + * Defines the height of the cylinder */ - isReady(): boolean; + height: number; /** - * Adds a new color gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param color defines the color to affect to the specified gradient - * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from - * @returns the current particle system + * Defines the diameter of the cylinder's top cap */ - addColorGradient(gradient: number, color1: Color4, color2?: Color4): IParticleSystem; + diameterTop: number; /** - * Remove a specific color gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Defines the diameter of the cylinder's bottom cap */ - removeColorGradient(gradient: number): IParticleSystem; + diameterBottom: number; /** - * Adds a new size gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * Defines the tessellation factor to apply to the cylinder */ - addSizeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem; + tessellation: number; /** - * Remove a specific size gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Defines the number of subdivisions to apply to the cylinder (1 by default) */ - removeSizeGradient(gradient: number): IParticleSystem; + subdivisions: number; /** - * Gets the current list of color gradients. - * You must use addColorGradient and removeColorGradient to udpate this list - * @returns the list of color gradients + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - getColorGradients(): Nullable>; + side: number; /** - * Gets the current list of size gradients. - * You must use addSizeGradient and removeSizeGradient to udpate this list - * @returns the list of size gradients + * Creates a new cylinder geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param height defines the height of the cylinder + * @param diameterTop defines the diameter of the cylinder's top cap + * @param diameterBottom defines the diameter of the cylinder's bottom cap + * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides) + * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default) + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - getSizeGradients(): Nullable>; + constructor(id: string, scene: Scene, /** - * Gets the current list of angular speed gradients. - * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list - * @returns the list of angular speed gradients + * Defines the height of the cylinder */ - getAngularSpeedGradients(): Nullable>; + height: number, /** - * Adds a new angular speed gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * Defines the diameter of the cylinder's top cap */ - addAngularSpeedGradient(gradient: number, factor: number, factor2?: number): IParticleSystem; + diameterTop: number, /** - * Remove a specific angular speed gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Defines the diameter of the cylinder's bottom cap */ - removeAngularSpeedGradient(gradient: number): IParticleSystem; + diameterBottom: number, /** - * Gets the current list of velocity gradients. - * You must use addVelocityGradient and removeVelocityGradient to udpate this list - * @returns the list of velocity gradients + * Defines the tessellation factor to apply to the cylinder */ - getVelocityGradients(): Nullable>; + tessellation: number, /** - * Adds a new velocity gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * Defines the number of subdivisions to apply to the cylinder (1 by default) */ - addVelocityGradient(gradient: number, factor: number, factor2?: number): IParticleSystem; + subdivisions?: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * Remove a specific velocity gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - removeVelocityGradient(gradient: number): IParticleSystem; + side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedCylinder: any, scene: Scene): Nullable; } -} - -declare module BABYLON { /** - * A particle represents one of the element emitted by a particle system. - * This is mainly define by its coordinates, direction, velocity and age. + * Creates a new torus geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#torus */ - class Particle { - /** - * particleSystem the particle system the particle belongs to. - */ - particleSystem: ParticleSystem; - /** - * The world position of the particle in the scene. - */ - position: Vector3; - /** - * The world direction of the particle in the scene. - */ - direction: Vector3; + class TorusGeometry extends _PrimitiveGeometry { /** - * The color of the particle. + * Defines the diameter of the torus */ - color: Color4; + diameter: number; /** - * The color change of the particle per step. + * Defines the thickness of the torus (ie. internal diameter) */ - colorStep: Color4; + thickness: number; /** - * Defines how long will the life of the particle be. + * Defines the tesselation factor to apply to the torus */ - lifeTime: number; + tessellation: number; /** - * The current age of the particle. + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - age: number; + side: number; /** - * The current size of the particle. + * Creates a new torus geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param diameter defines the diameter of the torus + * @param thickness defines the thickness of the torus (ie. internal diameter) + * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle) + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - size: number; + constructor(id: string, scene: Scene, /** - * The current scale of the particle. + * Defines the diameter of the torus */ - scale: Vector2; + diameter: number, /** - * The current angle of the particle. + * Defines the thickness of the torus (ie. internal diameter) */ - angle: number; + thickness: number, /** - * Defines how fast is the angle changing. + * Defines the tesselation factor to apply to the torus */ - angularSpeed: number; + tessellation: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * Defines the cell index used by the particle to be rendered from a sprite. + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - cellIndex: number; - /** @hidden */ - _initialDirection: Nullable; - /** @hidden */ - _initialStartSpriteCellID: number; - _initialEndSpriteCellID: number; - /** @hidden */ - _currentColorGradient: Nullable; - /** @hidden */ - _currentColor1: Color4; - /** @hidden */ - _currentColor2: Color4; - /** @hidden */ - _currentSizeGradient: Nullable; - /** @hidden */ - _currentSize1: number; - /** @hidden */ - _currentSize2: number; - /** @hidden */ - _currentAngularSpeedGradient: Nullable; - /** @hidden */ - _currentAngularSpeed1: number; - /** @hidden */ - _currentAngularSpeed2: number; - /** @hidden */ - _currentVelocityGradient: Nullable; - /** @hidden */ - _currentVelocity1: number; - /** @hidden */ - _currentVelocity2: number; + side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedTorus: any, scene: Scene): Nullable; + } + /** + * Creates a new ground geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#ground + */ + class GroundGeometry extends _PrimitiveGeometry { /** - * Creates a new instance Particle - * @param particleSystem the particle system the particle belongs to + * Defines the width of the ground */ - constructor( - /** - * particleSystem the particle system the particle belongs to. - */ - particleSystem: ParticleSystem); - private updateCellInfoFromSystem(); + width: number; /** - * Defines how the sprite cell index is updated for the particle + * Defines the height of the ground */ - updateCellIndex(): void; + height: number; /** - * Copy the properties of particle to another one. - * @param other the particle to copy the information to. + * Defines the subdivisions to apply to the ground */ - copyTo(other: Particle): void; - } -} - -declare module BABYLON { - /** - * This class is made for on one-liner static method to help creating particle system set. - */ - class ParticleHelper { + subdivisions: number; /** - * Gets or sets base Assets URL + * Creates a new ground geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param width defines the width of the ground + * @param height defines the height of the ground + * @param subdivisions defines the subdivisions to apply to the ground + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) */ - static BaseAssetsUrl: string; + constructor(id: string, scene: Scene, /** - * Create a default particle system that you can tweak - * @param emitter defines the emitter to use - * @param capacity defines the system capacity (default is 500 particles) - * @param scene defines the hosting scene - * @returns the new Particle system + * Defines the width of the ground */ - static CreateDefault(emitter: Nullable, capacity?: number, scene?: Scene): ParticleSystem; + width: number, /** - * This is the main static method (one-liner) of this helper to create different particle systems - * @param type This string represents the type to the particle system to create - * @param scene The scene where the particle system should live - * @param gpu If the system will use gpu - * @returns the ParticleSystemSet created + * Defines the height of the ground */ - static CreateAsync(type: string, scene: Nullable, gpu?: boolean): Promise; + height: number, /** - * Static function used to export a particle system to a ParticleSystemSet variable. - * Please note that the emitter shape is not exported - * @param system defines the particle systems to export + * Defines the subdivisions to apply to the ground */ - static ExportSet(systems: IParticleSystem[]): ParticleSystemSet; + subdivisions: number, canBeRegenerated?: boolean, mesh?: Nullable); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedGround: any, scene: Scene): Nullable; } -} - -declare module BABYLON { /** - * This represents a particle system in Babylon. - * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. - * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function. - * @example https://doc.babylonjs.com/babylon101/particles + * Creates a tiled ground geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground */ - class ParticleSystem implements IDisposable, IAnimatable, IParticleSystem { + class TiledGroundGeometry extends _PrimitiveGeometry { /** - * Source color is added to the destination color without alpha affecting the result. + * Defines the minimum value on X axis */ - static BLENDMODE_ONEONE: number; + xmin: number; /** - * Blend current color and particle color using particle’s alpha. + * Defines the minimum value on Z axis */ - static BLENDMODE_STANDARD: number; + zmin: number; /** - * Add current color and particle color multiplied by particle’s alpha. + * Defines the maximum value on X axis */ - static BLENDMODE_ADD: number; + xmax: number; /** - * List of animations used by the particle system. + * Defines the maximum value on Z axis */ - animations: Animation[]; + zmax: number; /** - * The id of the Particle system. + * Defines the subdivisions to apply to the ground */ - id: string; + subdivisions: { + w: number; + h: number; + }; /** - * The friendly name of the Particle system. + * Defines the precision to use when computing the tiles */ - name: string; + precision: { + w: number; + h: number; + }; /** - * The rendering group used by the Particle system to chose when to render. + * Creates a tiled ground geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param xmin defines the minimum value on X axis + * @param zmin defines the minimum value on Z axis + * @param xmax defines the maximum value on X axis + * @param zmax defines the maximum value on Z axis + * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map) + * @param precision defines the precision to use when computing the tiles + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) */ - renderingGroupId: number; + constructor(id: string, scene: Scene, /** - * The emitter represents the Mesh or position we are attaching the particle system to. + * Defines the minimum value on X axis */ - emitter: Nullable; + xmin: number, /** - * The maximum number of particles to emit per frame + * Defines the minimum value on Z axis */ - emitRate: number; + zmin: number, /** - * If you want to launch only a few particles at once, that can be done, as well. + * Defines the maximum value on X axis */ - manualEmitCount: number; + xmax: number, /** - * The overall motion speed (0.01 is default update speed, faster updates = faster animation) + * Defines the maximum value on Z axis */ - updateSpeed: number; + zmax: number, /** - * The amount of time the particle system is running (depends of the overall update speed). + * Defines the subdivisions to apply to the ground */ - targetStopDuration: number; + subdivisions: { + w: number; + h: number; + }, /** - * Specifies whether the particle system will be disposed once it reaches the end of the animation. + * Defines the precision to use when computing the tiles */ - disposeOnStop: boolean; + precision: { + w: number; + h: number; + }, canBeRegenerated?: boolean, mesh?: Nullable); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + /** + * Creates a plane geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#plane + */ + class PlaneGeometry extends _PrimitiveGeometry { /** - * Minimum power of emitting particles. + * Defines the size of the plane (width === height) */ - minEmitPower: number; + size: number; /** - * Maximum power of emitting particles. + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - maxEmitPower: number; + side: number; /** - * Minimum life time of emitting particles. + * Creates a plane geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param size defines the size of the plane (width === height) + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - minLifeTime: number; + constructor(id: string, scene: Scene, /** - * Maximum life time of emitting particles. + * Defines the size of the plane (width === height) */ - maxLifeTime: number; + size: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * Minimum Size of emitting particles. + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - minSize: number; + side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedPlane: any, scene: Scene): Nullable; + } + /** + * Creates a torus knot geometry + * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot + */ + class TorusKnotGeometry extends _PrimitiveGeometry { /** - * Maximum Size of emitting particles. + * Defines the radius of the torus knot */ - maxSize: number; + radius: number; /** - * Minimum scale of emitting particles on X axis. + * Defines the thickness of the torus knot tube */ - minScaleX: number; + tube: number; /** - * Maximum scale of emitting particles on X axis. + * Defines the number of radial segments */ - maxScaleX: number; + radialSegments: number; /** - * Minimum scale of emitting particles on Y axis. + * Defines the number of tubular segments */ - minScaleY: number; + tubularSegments: number; /** - * Maximum scale of emitting particles on Y axis. + * Defines the first number of windings */ - maxScaleY: number; + p: number; /** - * Gets or sets the minimal initial rotation in radians. + * Defines the second number of windings */ - minInitialRotation: number; + q: number; /** - * Gets or sets the maximal initial rotation in radians. + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - maxInitialRotation: number; + side: number; /** - * Minimum angular speed of emitting particles (Z-axis rotation for each particle). + * Creates a torus knot geometry + * @param id defines the unique ID of the geometry + * @param scene defines the hosting scene + * @param radius defines the radius of the torus knot + * @param tube defines the thickness of the torus knot tube + * @param radialSegments defines the number of radial segments + * @param tubularSegments defines the number of tubular segments + * @param p defines the first number of windings + * @param q defines the second number of windings + * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) + * @param mesh defines the hosting mesh (can be null) + * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - minAngularSpeed: number; + constructor(id: string, scene: Scene, /** - * Maximum angular speed of emitting particles (Z-axis rotation for each particle). + * Defines the radius of the torus knot */ - maxAngularSpeed: number; + radius: number, /** - * The texture used to render each particle. (this can be a spritesheet) + * Defines the thickness of the torus knot tube */ - particleTexture: Nullable; + tube: number, /** - * The layer mask we are rendering the particles through. + * Defines the number of radial segments */ - layerMask: number; + radialSegments: number, /** - * This can help using your own shader to render the particle system. - * The according effect will be created + * Defines the number of tubular segments */ - customShader: any; + tubularSegments: number, /** - * By default particle system starts as soon as they are created. This prevents the - * automatic start to happen and let you decide when to start emitting particles. + * Defines the first number of windings */ - preventAutoStart: boolean; + p: number, /** - * Gets or sets a texture used to add random noise to particle positions + * Defines the second number of windings */ - noiseTexture: Nullable; - /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ - noiseStrength: Vector3; + q: number, canBeRegenerated?: boolean, mesh?: Nullable, /** - * This function can be defined to provide custom update for active particles. - * This function will be called instead of regular update (age, position, color, etc.). - * Do not forget that this function will be called on every frame so try to keep it simple and fast :) + * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ - updateFunction: (particles: Particle[]) => void; + side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedTorusKnot: any, scene: Scene): Nullable; + } +} + +declare module BABYLON { + class GroundMesh extends Mesh { + generateOctree: boolean; + private _heightQuads; + _subdivisionsX: number; + _subdivisionsY: number; + _width: number; + _height: number; + _minX: number; + _maxX: number; + _minZ: number; + _maxZ: number; + constructor(name: string, scene: Scene); + getClassName(): string; + readonly subdivisions: number; + readonly subdivisionsX: number; + readonly subdivisionsY: number; + optimize(chunksCount: number, octreeBlocksSize?: number): void; /** - * Callback triggered when the particle animation is ending. + * Returns a height (y) value in the Worl system : + * the ground altitude at the coordinates (x, z) expressed in the World system. + * Returns the ground y position if (x, z) are outside the ground surface. */ - onAnimationEnd: Nullable<() => void>; + getHeightAtCoordinates(x: number, z: number): number; /** - * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD. + * Returns a normalized vector (Vector3) orthogonal to the ground + * at the ground coordinates (x, z) expressed in the World system. + * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface. */ - blendMode: number; + getNormalAtCoordinates(x: number, z: number): Vector3; /** - * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls - * to override the particles. + * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground + * at the ground coordinates (x, z) expressed in the World system. + * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface. + * Returns the GroundMesh. */ - forceDepthWrite: boolean; + getNormalAtCoordinatesToRef(x: number, z: number, ref: Vector3): GroundMesh; /** - * You can use gravity if you want to give an orientation to your particles. - */ - gravity: Vector3; - private _emitterWorldMatrix; - private _colorGradients; - private _sizeGradients; - private _lifeTimeGradients; - private _angularSpeedGradients; - private _velocityGradients; + * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates() + * if the ground has been updated. + * This can be used in the render loop. + * Returns the GroundMesh. + */ + updateCoordinateHeights(): GroundMesh; + private _getFacetAt; + private _initHeightQuads; + private _computeHeightQuads; + serialize(serializationObject: any): void; + static Parse(parsedMesh: any, scene: Scene): GroundMesh; + } +} + +declare module BABYLON { + /** + * Creates an instance based on a source mesh. + */ + class InstancedMesh extends AbstractMesh { + private _sourceMesh; + private _currentLOD; + constructor(name: string, source: Mesh); /** - * Gets the current list of color gradients. - * You must use addColorGradient and removeColorGradient to udpate this list - * @returns the list of color gradients + * Returns the string "InstancedMesh". */ - getColorGradients(): Nullable>; + getClassName(): string; + readonly receiveShadows: boolean; + readonly material: Nullable; + readonly visibility: number; + readonly skeleton: Nullable; + renderingGroupId: number; /** - * Gets the current list of size gradients. - * You must use addSizeGradient and removeSizeGradient to udpate this list - * @returns the list of size gradients + * Returns the total number of vertices (integer). */ - getSizeGradients(): Nullable>; + getTotalVertices(): number; + readonly sourceMesh: Mesh; /** - * Gets the current list of life time gradients. - * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list - * @returns the list of life time gradients + * Is this node ready to be used/rendered + * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) + * @return {boolean} is it ready */ - getLifeTimeGradients(): Nullable>; + isReady(completeCheck?: boolean): boolean; /** - * Gets the current list of angular speed gradients. - * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list - * @returns the list of angular speed gradients + * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc. */ - getAngularSpeedGradients(): Nullable>; + getVerticesData(kind: string, copyWhenShared?: boolean): Nullable; /** - * Gets the current list of velocity gradients. - * You must use addVelocityGradient and removeVelocityGradient to udpate this list - * @returns the list of velocity gradients + * Sets the vertex data of the mesh geometry for the requested `kind`. + * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. + * The `data` are either a numeric array either a Float32Array. + * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater. + * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc). + * Note that a new underlying VertexBuffer object is created each call. + * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. + * + * Possible `kind` values : + * - BABYLON.VertexBuffer.PositionKind + * - BABYLON.VertexBuffer.UVKind + * - BABYLON.VertexBuffer.UV2Kind + * - BABYLON.VertexBuffer.UV3Kind + * - BABYLON.VertexBuffer.UV4Kind + * - BABYLON.VertexBuffer.UV5Kind + * - BABYLON.VertexBuffer.UV6Kind + * - BABYLON.VertexBuffer.ColorKind + * - BABYLON.VertexBuffer.MatricesIndicesKind + * - BABYLON.VertexBuffer.MatricesIndicesExtraKind + * - BABYLON.VertexBuffer.MatricesWeightsKind + * - BABYLON.VertexBuffer.MatricesWeightsExtraKind + * + * Returns the Mesh. */ - getVelocityGradients(): Nullable>; + setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): Mesh; /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Updates the existing vertex data of the mesh geometry for the requested `kind`. + * If the mesh has no geometry, it is simply returned as it is. + * The `data` are either a numeric array either a Float32Array. + * No new underlying VertexBuffer object is created. + * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. + * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh. + * + * Possible `kind` values : + * - BABYLON.VertexBuffer.PositionKind + * - BABYLON.VertexBuffer.UVKind + * - BABYLON.VertexBuffer.UV2Kind + * - BABYLON.VertexBuffer.UV3Kind + * - BABYLON.VertexBuffer.UV4Kind + * - BABYLON.VertexBuffer.UV5Kind + * - BABYLON.VertexBuffer.UV6Kind + * - BABYLON.VertexBuffer.ColorKind + * - BABYLON.VertexBuffer.MatricesIndicesKind + * - BABYLON.VertexBuffer.MatricesIndicesExtraKind + * - BABYLON.VertexBuffer.MatricesWeightsKind + * - BABYLON.VertexBuffer.MatricesWeightsExtraKind + * + * Returns the Mesh. */ - direction1: Vector3; + updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): Mesh; /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Sets the mesh indices. + * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array). + * If the mesh has no geometry, a new Geometry object is created and set to the mesh. + * This method creates a new index buffer each call. + * Returns the Mesh. */ - direction2: Vector3; + setIndices(indices: IndicesArray, totalVertices?: Nullable): Mesh; /** - * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Boolean : True if the mesh owns the requested kind of data. */ - minEmitBox: Vector3; + isVerticesDataPresent(kind: string): boolean; /** - * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. - * This only works when particleEmitterTyps is a BoxParticleEmitter + * Returns an array of indices (IndicesArray). */ - maxEmitBox: Vector3; + getIndices(): Nullable; + readonly _positions: Nullable; /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors + * Sets a new updated BoundingInfo to the mesh. + * Returns the mesh. */ - color1: Color4; + refreshBoundingInfo(): InstancedMesh; + _preActivate(): InstancedMesh; + _activate(renderId: number): InstancedMesh; /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors + * Returns the current associated LOD AbstractMesh. */ - color2: Color4; + getLOD(camera: Camera): AbstractMesh; + _syncSubMeshes(): InstancedMesh; + _generatePointsArray(): boolean; /** - * Color the particle will have at the end of its lifetime + * Creates a new InstancedMesh from the current mesh. + * - name (string) : the cloned mesh name + * - newParent (optional Node) : the optional Node to parent the clone to. + * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned. + * + * Returns the clone. */ - colorDead: Color4; + clone(name: string, newParent: Node, doNotCloneChildren?: boolean): InstancedMesh; /** - * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel + * Disposes the InstancedMesh. + * Returns nothing. */ - textureMask: Color4; + dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; + } +} + +declare module BABYLON { + class LinesMesh extends Mesh { + useVertexColor?: boolean | undefined; + useVertexAlpha?: boolean | undefined; + color: Color3; + alpha: number; /** - * The particle emitter type defines the emitter used by the particle system. - * It can be for example box, sphere, or cone... + * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray. + * This margin is expressed in world space coordinates, so its value may vary. + * Default value is 0.1 + * @returns the intersection Threshold value. */ - particleEmitterType: IParticleEmitterType; /** - * This function can be defined to specify initial direction for every new particle. - * It by default use the emitterType defined function - */ - startDirectionFunction: (worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle) => void; + * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray. + * This margin is expressed in world space coordinates, so its value may vary. + * @param value the new threshold to apply + */ + intersectionThreshold: number; + private _intersectionThreshold; + private _colorShader; + constructor(name: string, scene?: Nullable, parent?: Nullable, source?: LinesMesh, doNotCloneChildren?: boolean, useVertexColor?: boolean | undefined, useVertexAlpha?: boolean | undefined); /** - * This function can be defined to specify initial position for every new particle. - * It by default use the emitterType defined function + * Returns the string "LineMesh" */ - startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle) => void; + getClassName(): string; /** - * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime) + * @hidden */ - spriteCellChangeSpeed: number; /** - * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display + * @hidden + */ + material: Material; + /** + * @hidden */ - startSpriteCellID: number; + readonly checkCollisions: boolean; + createInstance(name: string): InstancedMesh; + _bind(subMesh: SubMesh, effect: Effect, fillMode: number): LinesMesh; + _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): LinesMesh; + dispose(doNotRecurse?: boolean): void; /** - * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display + * Returns a new LineMesh object cloned from the current one. */ - endSpriteCellID: number; + clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): LinesMesh; + } +} + +declare module BABYLON { + /** + * @hidden + **/ + class _InstancesBatch { + mustReturn: boolean; + visibleInstances: Nullable[]; + renderSelf: boolean[]; + } + class Mesh extends AbstractMesh implements IGetSetVerticesData { + static _FRONTSIDE: number; + static _BACKSIDE: number; + static _DOUBLESIDE: number; + static _DEFAULTSIDE: number; + static _NO_CAP: number; + static _CAP_START: number; + static _CAP_END: number; + static _CAP_ALL: number; /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use + * Mesh side orientation : usually the external or front surface */ - spriteCellWidth: number; + static readonly FRONTSIDE: number; /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use + * Mesh side orientation : usually the internal or back surface */ - spriteCellHeight: number; - /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */ - preWarmCycles: number; - /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */ - preWarmStepOffset: number; - /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ - translationPivot: Vector2; + static readonly BACKSIDE: number; /** - * An event triggered when the system is disposed - */ - onDisposeObservable: Observable; - private _onDisposeObserver; + * Mesh side orientation : both internal and external or front and back surfaces + */ + static readonly DOUBLESIDE: number; /** - * Sets a callback that will be triggered when the system is disposed + * Mesh side orientation : by default, `FRONTSIDE` */ - onDispose: () => void; + static readonly DEFAULTSIDE: number; /** - * Gets or sets whether an animation sprite sheet is enabled or not on the particle system + * Mesh cap setting : no cap */ - isAnimationSheetEnabled: boolean; + static readonly NO_CAP: number; /** - * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction + * Mesh cap setting : one cap at the beginning of the mesh */ - isBillboardBased: boolean; + static readonly CAP_START: number; /** - * Get hosting scene - * @returns the scene + * Mesh cap setting : one cap at the end of the mesh */ - getScene(): Scene; + static readonly CAP_END: number; /** - * Gets or sets the billboard mode to use when isBillboardBased = true. - * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far + * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh */ - billboardMode: number; - private _particles; - private _epsilon; - private _capacity; - private _scene; - private _stockParticles; - private _newPartsExcess; - private _vertexData; - private _vertexBuffer; - private _vertexBuffers; - private _spriteBuffer; - private _indexBuffer; - private _effect; - private _customEffect; - private _cachedDefines; - private _scaledColorStep; - private _colorDiff; - private _scaledDirection; - private _scaledGravity; - private _currentRenderId; - private _alive; - private _useInstancing; - private _started; - private _stopped; - private _actualFrame; - private _scaledUpdateSpeed; - private _vertexBufferSize; - private _isAnimationSheetEnabled; - private _isBillboardBased; + static readonly CAP_ALL: number; + private _onBeforeRenderObservable; + private _onAfterRenderObservable; + private _onBeforeDrawObservable; /** - * this is the Sub-emitters templates that will be used to generate particle system when the particle dies, this property is used by the root particle system only. + * An event triggered before rendering the mesh */ - subEmitters: ParticleSystem[]; + readonly onBeforeRenderObservable: Observable; /** - * The current active Sub-systems, this property is used by the root particle system only. + * An event triggered after rendering the mesh */ - activeSubSystems: Array; - private _rootParticleSystem; + readonly onAfterRenderObservable: Observable; /** - * Gets the current list of active particles + * An event triggered before drawing the mesh + */ + readonly onBeforeDrawObservable: Observable; + private _onBeforeDrawObserver; + onBeforeDraw: () => void; + delayLoadState: number; + instances: InstancedMesh[]; + delayLoadingFile: string; + _binaryInfo: any; + private _LODLevels; + onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Nullable) => void; + private _morphTargetManager; + morphTargetManager: Nullable; + _geometry: Nullable; + _delayInfo: Array; + _delayLoadingFunction: (any: any, mesh: Mesh) => void; + _visibleInstances: any; + private _renderIdForInstances; + private _batchCache; + private _instancesBufferSize; + private _instancesBuffer; + private _instancesData; + private _overridenInstanceCount; + private _effectiveMaterial; + _shouldGenerateFlatShading: boolean; + private _preActivateId; + _originalBuilderSideOrientation: number; + overrideMaterialSideOrientation: Nullable; + private _areNormalsFrozen; + private _sourcePositions; + private _sourceNormals; + private _source; + readonly source: Nullable; + isUnIndexed: boolean; + /** + * @constructor + * @param {string} name The value used by scene.getMeshByName() to do a lookup. + * @param {Scene} scene The scene to add this mesh to. + * @param {Node} parent The parent of this mesh, if it has one + * @param {Mesh} source An optional Mesh from which geometry is shared, cloned. + * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False. + * When false, achieved by calling a clone(), also passing False. + * This will make creation of children, recursive. + * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True. */ - readonly particles: Particle[]; + constructor(name: string, scene?: Nullable, parent?: Nullable, source?: Nullable, doNotCloneChildren?: boolean, clonePhysicsImpostor?: boolean); /** - * Returns the string "ParticleSystem" - * @returns a string containing the class name + * Returns the string "Mesh". */ getClassName(): string; /** - * Instantiates a particle system. - * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. - * @param name The name of the particle system - * @param capacity The max number of particles alive at the same time - * @param scene The scene the particle system belongs to - * @param customEffect a custom effect used to change the way particles are rendered by default - * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture - * @param epsilon Offset used to render the particles + * Returns a string. + * @param {boolean} fullDetails - support for multiple levels of logging within scene loading */ - constructor(name: string, capacity: number, scene: Scene, customEffect?: Nullable, isAnimationSheetEnabled?: boolean, epsilon?: number); - private _fetchR(u, v, width, height, pixels); - private _addFactorGradient(factorGradients, gradient, factor, factor2?); - private _removeFactorGradient(factorGradients, gradient); + toString(fullDetails?: boolean): string; + _unBindEffect(): void; /** - * Adds a new life time gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the life time factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * True if the mesh has some Levels Of Details (LOD). + * Returns a boolean. */ - addLifeTimeGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; + readonly hasLODLevels: boolean; /** - * Remove a specific life time gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh + * @returns an array of {BABYLON.MeshLODLevel} */ - removeLifeTimeGradient(gradient: number): ParticleSystem; + getLODLevels(): MeshLODLevel[]; + private _sortLODLevels; /** - * Adds a new size gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * Add a mesh as LOD level triggered at the given distance. + * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD + * @param distance The distance from the center of the object to show this level + * @param mesh The mesh to be added as LOD level (can be null) + * @return This mesh (for chaining) */ - addSizeGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; + addLODLevel(distance: number, mesh: Nullable): Mesh; /** - * Remove a specific size gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Returns the LOD level mesh at the passed distance or null if not found. + * It is related to the method `addLODLevel(distance, mesh)`. + * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD + * Returns an object Mesh or `null`. */ - removeSizeGradient(gradient: number): ParticleSystem; + getLODLevelAtDistance(distance: number): Nullable; /** - * Adds a new angular speed gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * Remove a mesh from the LOD array + * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD + * @param {Mesh} mesh The mesh to be removed. + * @return {Mesh} This mesh (for chaining) */ - addAngularSpeedGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; + removeLODLevel(mesh: Mesh): Mesh; /** - * Remove a specific angular speed gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh. + * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod */ - removeAngularSpeedGradient(gradient: number): ParticleSystem; + getLOD(camera: Camera, boundingSphere?: BoundingSphere): Nullable; /** - * Adds a new velocity gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system + * Returns the mesh internal Geometry object. */ - addVelocityGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; + readonly geometry: Nullable; /** - * Remove a specific velocity gradient - * @param gradient defines the gradient to remove - * @returns the current particle system + * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry. */ - removeVelocityGradient(gradient: number): ParticleSystem; + getTotalVertices(): number; /** - * Adds a new color gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param color defines the color to affect to the specified gradient - * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from + * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc). + * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one. + * You can force the copy with forceCopy === true + * Returns null if the mesh has no geometry or no vertex buffer. + * Possible `kind` values : + * - BABYLON.VertexBuffer.PositionKind + * - BABYLON.VertexBuffer.UVKind + * - BABYLON.VertexBuffer.UV2Kind + * - BABYLON.VertexBuffer.UV3Kind + * - BABYLON.VertexBuffer.UV4Kind + * - BABYLON.VertexBuffer.UV5Kind + * - BABYLON.VertexBuffer.UV6Kind + * - BABYLON.VertexBuffer.ColorKind + * - BABYLON.VertexBuffer.MatricesIndicesKind + * - BABYLON.VertexBuffer.MatricesIndicesExtraKind + * - BABYLON.VertexBuffer.MatricesWeightsKind + * - BABYLON.VertexBuffer.MatricesWeightsExtraKind */ - addColorGradient(gradient: number, color: Color4, color2?: Color4): ParticleSystem; + getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable; /** - * Remove a specific color gradient - * @param gradient defines the gradient to remove - */ - removeColorGradient(gradient: number): ParticleSystem; - private _resetEffect(); - private _createVertexBuffers(); - private _createIndexBuffer(); - /** - * Gets the maximum number of particles active at the same time. - * @returns The max number of active particles. + * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc. + * Returns `null` if the mesh has no geometry. + * Possible `kind` values : + * - BABYLON.VertexBuffer.PositionKind + * - BABYLON.VertexBuffer.UVKind + * - BABYLON.VertexBuffer.UV2Kind + * - BABYLON.VertexBuffer.UV3Kind + * - BABYLON.VertexBuffer.UV4Kind + * - BABYLON.VertexBuffer.UV5Kind + * - BABYLON.VertexBuffer.UV6Kind + * - BABYLON.VertexBuffer.ColorKind + * - BABYLON.VertexBuffer.MatricesIndicesKind + * - BABYLON.VertexBuffer.MatricesIndicesExtraKind + * - BABYLON.VertexBuffer.MatricesWeightsKind + * - BABYLON.VertexBuffer.MatricesWeightsExtraKind */ - getCapacity(): number; + getVertexBuffer(kind: string): Nullable; + isVerticesDataPresent(kind: string): boolean; /** - * Gets Wether there are still active particles in the system. - * @returns True if it is alive, otherwise false. + * Returns a boolean defining if the vertex data for the requested `kind` is updatable. + * Possible `kind` values : + * - BABYLON.VertexBuffer.PositionKind + * - BABYLON.VertexBuffer.UVKind + * - BABYLON.VertexBuffer.UV2Kind + * - BABYLON.VertexBuffer.UV3Kind + * - BABYLON.VertexBuffer.UV4Kind + * - BABYLON.VertexBuffer.UV5Kind + * - BABYLON.VertexBuffer.UV6Kind + * - BABYLON.VertexBuffer.ColorKind + * - BABYLON.VertexBuffer.MatricesIndicesKind + * - BABYLON.VertexBuffer.MatricesIndicesExtraKind + * - BABYLON.VertexBuffer.MatricesWeightsKind + * - BABYLON.VertexBuffer.MatricesWeightsExtraKind */ - isAlive(): boolean; + isVertexBufferUpdatable(kind: string): boolean; /** - * Gets Wether the system has been started. - * @returns True if it has been started, otherwise false. + * Returns a string : the list of existing `kinds` of Vertex Data for this mesh. + * Possible `kind` values : + * - BABYLON.VertexBuffer.PositionKind + * - BABYLON.VertexBuffer.UVKind + * - BABYLON.VertexBuffer.UV2Kind + * - BABYLON.VertexBuffer.UV3Kind + * - BABYLON.VertexBuffer.UV4Kind + * - BABYLON.VertexBuffer.UV5Kind + * - BABYLON.VertexBuffer.UV6Kind + * - BABYLON.VertexBuffer.ColorKind + * - BABYLON.VertexBuffer.MatricesIndicesKind + * - BABYLON.VertexBuffer.MatricesIndicesExtraKind + * - BABYLON.VertexBuffer.MatricesWeightsKind + * - BABYLON.VertexBuffer.MatricesWeightsExtraKind */ - isStarted(): boolean; + getVerticesDataKinds(): string[]; /** - * Starts the particle system and begins to emit - * @param delay defines the delay in milliseconds before starting the system (0 by default) + * Returns a positive integer : the total number of indices in this mesh geometry. + * Returns zero if the mesh has no geometry. */ - start(delay?: number): void; + getTotalIndices(): number; /** - * Stops the particle system. - * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true. + * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices. + * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one. + * Returns an empty array if the mesh has no geometry. */ - stop(stopSubEmitters?: boolean): void; + getIndices(copyWhenShared?: boolean): Nullable; + readonly isBlocked: boolean; /** - * Remove all active particles + * Determine if the current mesh is ready to be rendered + * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) + * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default) + * @returns true if all associated assets are ready (material, textures, shaders) */ - reset(): void; + isReady(completeCheck?: boolean, forceInstanceSupport?: boolean): boolean; /** - * @hidden (for internal use only) + * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update. + * This property is pertinent only for updatable parametric shapes. */ - _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void; + readonly areNormalsFrozen: boolean; /** - * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list. - * Its lifetime will start back at 0. + * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. + * It has no effect at all on other shapes. + * It prevents the mesh normals from being recomputed on next `positions` array update. + * Returns the Mesh. */ - recycleParticle: (particle: Particle) => void; - private _stopSubEmitters(); - private _createParticle; - private _removeFromRoot(); - private _emitFromParticle; - private _update(newParticles); - /** @hidden */ - static _GetAttributeNamesOrOptions(isAnimationSheetEnabled?: boolean, isBillboardBased?: boolean): string[]; - static _GetEffectCreationOptions(isAnimationSheetEnabled?: boolean): string[]; - private _getEffect(); + freezeNormals(): Mesh; /** - * Animates the particle system for the current frame by emitting new particles and or animating the living ones. - * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false) + * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. + * It has no effect at all on other shapes. + * It reactivates the mesh normals computation if it was previously frozen. + * Returns the Mesh. */ - animate(preWarmOnly?: boolean): void; - private _appendParticleVertices(offset, particle); + unfreezeNormals(): Mesh; /** - * Rebuilds the particle system. + * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs */ - rebuild(): void; + overridenInstanceCount: number; + _preActivate(): Mesh; + _preActivateForIntermediateRendering(renderId: number): Mesh; + _registerInstanceForRenderId(instance: InstancedMesh, renderId: number): Mesh; /** - * Is this system ready to be used/rendered - * @return true if the system is ready + * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked. + * This means the mesh underlying bounding box and sphere are recomputed. + * Returns the Mesh. */ - isReady(): boolean; + refreshBoundingInfo(): Mesh; + _refreshBoundingInfo(applySkeleton: boolean): Mesh; + private _getPositionData; + _createGlobalSubMesh(force: boolean): Nullable; + subdivide(count: number): void; + setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): Mesh; + markVerticesDataAsUpdatable(kind: string, updatable?: boolean): void; /** - * Renders the particle system in its current state. - * @returns the current number of particles + * Sets the mesh VertexBuffer. + * Returns the Mesh. */ - render(): number; + setVerticesBuffer(buffer: VertexBuffer): Mesh; + updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): Mesh; /** - * Disposes the particle system and free the associated resources - * @param disposeTexture defines if the particule texture must be disposed as well (true by default) + * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values. + * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions + * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything. + * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update. + * Returns the Mesh. */ - dispose(disposeTexture?: boolean): void; + updateMeshPositions(positionFunction: (data: FloatArray) => void, computeNormals?: boolean): Mesh; /** - * Creates a Point Emitter for the particle system (emits directly from the emitter position) - * @param direction1 Particles are emitted between the direction1 and direction2 from within the box - * @param direction2 Particles are emitted between the direction1 and direction2 from within the box - * @returns the emitter + * Creates a un-shared specific occurence of the geometry for the mesh. + * Returns the Mesh. */ - createPointEmitter(direction1: Vector3, direction2: Vector3): PointParticleEmitter; + makeGeometryUnique(): Mesh; + setIndices(indices: IndicesArray, totalVertices?: Nullable, updatable?: boolean): Mesh; /** - * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius) - * @param radius The radius of the hemisphere to emit from - * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius - * @returns the emitter + * Update the current index buffer + * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array) + * Returns the Mesh. */ - createHemisphericEmitter(radius?: number, radiusRange?: number): HemisphericParticleEmitter; + updateIndices(indices: IndicesArray, offset?: number): Mesh; /** - * Creates a Sphere Emitter for the particle system (emits along the sphere radius) - * @param radius The radius of the sphere to emit from - * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius - * @returns the emitter + * Invert the geometry to move from a right handed system to a left handed one. + * Returns the Mesh. */ - createSphereEmitter(radius?: number, radiusRange?: number): SphereParticleEmitter; + toLeftHanded(): Mesh; + _bind(subMesh: SubMesh, effect: Effect, fillMode: number): Mesh; + _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number, alternate?: boolean): Mesh; /** - * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2) - * @param radius The radius of the sphere to emit from - * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere - * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere - * @returns the emitter + * Registers for this mesh a javascript function called just before the rendering process. + * This function is passed the current mesh. + * Return the Mesh. */ - createDirectedSphereEmitter(radius?: number, direction1?: Vector3, direction2?: Vector3): SphereDirectedParticleEmitter; + registerBeforeRender(func: (mesh: AbstractMesh) => void): Mesh; /** - * Creates a Cone Emitter for the particle system (emits from the cone to the particle position) - * @param radius The radius of the cone to emit from - * @param angle The base angle of the cone - * @returns the emitter + * Disposes a previously registered javascript function called before the rendering. + * This function is passed the current mesh. + * Returns the Mesh. */ - createConeEmitter(radius?: number, angle?: number): ConeParticleEmitter; + unregisterBeforeRender(func: (mesh: AbstractMesh) => void): Mesh; /** - * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox) - * @param direction1 Particles are emitted between the direction1 and direction2 from within the box - * @param direction2 Particles are emitted between the direction1 and direction2 from within the box - * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox - * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox - * @returns the emitter + * Registers for this mesh a javascript function called just after the rendering is complete. + * This function is passed the current mesh. + * Returns the Mesh. */ - createBoxEmitter(direction1: Vector3, direction2: Vector3, minEmitBox: Vector3, maxEmitBox: Vector3): BoxParticleEmitter; + registerAfterRender(func: (mesh: AbstractMesh) => void): Mesh; /** - * Clones the particle system. - * @param name The name of the cloned object - * @param newEmitter The new emitter to use - * @returns the cloned particle system + * Disposes a previously registered javascript function called after the rendering. + * This function is passed the current mesh. + * Return the Mesh. */ - clone(name: string, newEmitter: any): ParticleSystem; + unregisterAfterRender(func: (mesh: AbstractMesh) => void): Mesh; + _getInstancesRenderList(subMeshId: number): _InstancesBatch; + _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): Mesh; + _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean, onBeforeDraw: (isInstance: boolean, world: Matrix, effectiveMaterial?: Material) => void, effectiveMaterial?: Material): Mesh; /** - * Serializes the particle system to a JSON object. - * @returns the JSON object + * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager + * @param subMesh defines the subMesh to render + * @param enableAlphaMode defines if alpha mode can be changed + * @returns the current mesh */ - serialize(): any; - /** @hidden */ - static _Serialize(serializationObject: any, particleSystem: IParticleSystem): void; - /** @hidden */ - static _Parse(parsedParticleSystem: any, particleSystem: IParticleSystem, scene: Scene, rootUrl: string): void; + render(subMesh: SubMesh, enableAlphaMode: boolean): Mesh; + private _onBeforeDraw; /** - * Parses a JSON object to create a particle system. - * @param parsedParticleSystem The JSON object to parse - * @param scene The scene to create the particle system in - * @param rootUrl The root url to use to load external dependencies like texture - * @returns the Parsed particle system + * Returns an array populated with IParticleSystem objects whose the mesh is the emitter. */ - static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): ParticleSystem; - } -} - -declare module BABYLON { - interface Engine { + getEmittedParticleSystems(): IParticleSystem[]; /** - * Create an effect to use with particle systems. - * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration - * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx) - * @param uniformsNames defines a list of attribute names - * @param samplers defines an array of string used to represent textures - * @param defines defines the string containing the defines to use to compile the shaders - * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails - * @param onCompiled defines a function to call when the effect creation is successful - * @param onError defines a function to call when the effect creation has failed - * @returns the new Effect + * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter. */ - createEffectForParticles(fragmentName: string, uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect; - } -} - -declare module BABYLON { - /** - * Represents a set of particle systems working together to create a specific effect - */ - class ParticleSystemSet implements IDisposable { - private _emitterCreationOptions; - private _emitterNode; + getHierarchyEmittedParticleSystems(): IParticleSystem[]; /** - * Gets the particle system list + * Normalize matrix weights so that all vertices have a total weight set to 1 */ - systems: IParticleSystem[]; + cleanMatrixWeights(): void; + _checkDelayState(): Mesh; + private _queueLoad; /** - * Gets the emitter node used with this set + * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter. */ - readonly emitterNode: Nullable; + isInFrustum(frustumPlanes: Plane[]): boolean; /** - * Creates a new emitter mesh as a sphere - * @param options defines the options used to create the sphere - * @param renderingGroupId defines the renderingGroupId to use for the sphere - * @param scene defines the hosting scene + * Sets the mesh material by the material or multiMaterial `id` property. + * The material `id` is a string identifying the material or the multiMaterial. + * This method returns the Mesh. */ - setEmitterAsSphere(options: { - diameter: number; - segments: number; - color: Color3; - }, renderingGroupId: number, scene: Scene): void; + setMaterialByID(id: string): Mesh; /** - * Starts all particle systems of the set - * @param emitter defines an optional mesh to use as emitter for the particle systems + * Returns as a new array populated with the mesh material and/or skeleton, if any. */ - start(emitter?: AbstractMesh): void; + getAnimatables(): IAnimatable[]; /** - * Release all associated resources + * Modifies the mesh geometry according to the passed transformation matrix. + * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable. + * The mesh normals are modified accordingly the same transformation. + * tuto : http://doc.babylonjs.com/resources/baking_transformations + * Note that, under the hood, this method sets a new VertexBuffer each call. + * Returns the Mesh. */ - dispose(): void; + bakeTransformIntoVertices(transform: Matrix): Mesh; /** - * Serialize the set into a JSON compatible object - * @returns a JSON compatible representation of the set + * Modifies the mesh geometry according to its own current World Matrix. + * The mesh World Matrix is then reset. + * This method returns nothing but really modifies the mesh even if it's originally not set as updatable. + * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations + * Note that, under the hood, this method sets a new VertexBuffer each call. + * Returns the Mesh. */ - serialize(): any; + bakeCurrentTransformIntoVertices(): Mesh; + readonly _positions: Nullable; + _resetPointsArrayCache(): Mesh; + _generatePointsArray(): boolean; /** - * Parse a new ParticleSystemSet from a serialized source - * @param data defines a JSON compatible representation of the set - * @param scene defines the hosting scene - * @param gpu defines if we want GPU particles or CPU particles - * @returns a new ParticleSystemSet + * Returns a new Mesh object generated from the current mesh properties. + * This method must not get confused with createInstance(). + * The parameter `name` is a string, the name given to the new mesh. + * The optional parameter `newParent` can be any Node object (default `null`). + * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any. + * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any. */ - static Parse(data: any, scene: Scene, gpu?: boolean): ParticleSystemSet; - } -} - -declare module BABYLON { - /** - * Represents one particle of a solid particle system. - */ - class SolidParticle { + clone(name: string, newParent?: Node, doNotCloneChildren?: boolean, clonePhysicsImpostor?: boolean): Mesh; /** - * particle global index + * Releases resources associated with this mesh. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) */ - idx: number; + dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; /** - * The color of the particle + * Modifies the mesh geometry according to a displacement map. + * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. + * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. + * This method returns nothing. + * The parameter `url` is a string, the URL from the image file is to be downloaded. + * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement. + * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing. + * The parameter `uvOffset` is an optional vector2 used to offset UV. + * The parameter `uvScale` is an optional vector2 used to scale UV. + * + * Returns the Mesh. */ - color: Nullable; + applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void, uvOffset?: Vector2, uvScale?: Vector2): Mesh; /** - * The world space position of the particle. + * Modifies the mesh geometry according to a displacementMap buffer. + * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. + * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. + * This method returns nothing. + * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel. + * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image. + * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement. + * The parameter `uvOffset` is an optional vector2 used to offset UV. + * The parameter `uvScale` is an optional vector2 used to scale UV. + * + * Returns the Mesh. */ - position: Vector3; + applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number, uvOffset?: Vector2, uvScale?: Vector2): Mesh; /** - * The world space rotation of the particle. (Not use if rotationQuaternion is set) + * Modify the mesh to get a flat shading rendering. + * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result. + * This method returns the Mesh. + * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated. */ - rotation: Vector3; + convertToFlatShadedMesh(): Mesh; /** - * The world space rotation quaternion of the particle. + * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers. + * In other words, more vertices, no more indices and a single bigger VBO. + * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated. + * Returns the Mesh. */ - rotationQuaternion: Nullable; + convertToUnIndexedMesh(): Mesh; /** - * The scaling of the particle. + * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true. + * This method returns the Mesh. + * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. */ - scaling: Vector3; + flipFaces(flipNormals?: boolean): Mesh; /** - * The uvs of the particle. + * Creates a new InstancedMesh object from the mesh model. + * An instance shares the same properties and the same material than its model. + * Only these properties of each instance can then be set individually : + * - position + * - rotation + * - rotationQuaternion + * - setPivotMatrix + * - scaling + * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances + * Warning : this method is not supported for Line mesh and LineSystem */ - uvs: Vector4; + createInstance(name: string): InstancedMesh; /** - * The current speed of the particle. + * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any. + * After this call, all the mesh instances have the same submeshes than the current mesh. + * This method returns the Mesh. */ - velocity: Vector3; + synchronizeInstances(): Mesh; /** - * The pivot point in the particle local space. + * Simplify the mesh according to the given array of settings. + * Function will return immediately and will simplify async. It returns the Mesh. + * @param settings a collection of simplification settings. + * @param parallelProcessing should all levels calculate parallel or one after the other. + * @param type the type of simplification to run. + * @param successCallback optional success callback to be called after the simplification finished processing all settings. */ - pivot: Vector3; + simplify(settings: Array, parallelProcessing?: boolean, simplificationType?: SimplificationType, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void): Mesh; /** - * Must the particle be translated from its pivot point in its local space ? - * In this case, the pivot point is set at the origin of the particle local space and the particle is translated. - * Default : false + * Optimization of the mesh's indices, in case a mesh has duplicated vertices. + * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes. + * This should be used together with the simplification to avoid disappearing triangles. + * Returns the Mesh. + * @param successCallback an optional success callback to be called after the optimization finished. */ - translateFromPivot: boolean; + optimizeIndices(successCallback?: (mesh?: Mesh) => void): Mesh; + serialize(serializationObject: any): void; + _syncGeometryWithMorphTargetManager(): void; /** - * Is the particle active or not ? + * Returns a new Mesh object parsed from the source provided. + * The parameter `parsedMesh` is the source. + * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with */ - alive: boolean; + static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh; /** - * Is the particle visible or not ? + * Creates a ribbon mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. + * + * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial + * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry. + * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array. + * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array. + * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path. + * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11. + * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - isVisible: boolean; + static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean | undefined, closePath: boolean, offset: number, scene?: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; /** - * Index of this particle in the global "positions" array (Internal use) + * Creates a plane polygonal mesh. By default, this is a disc. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `radius` sets the radius size (float) of the polygon (default 0.5). + * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc. + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - _pos: number; + static CreateDisc(name: string, radius: number, tessellation: number, scene?: Nullable, updatable?: boolean, sideOrientation?: number): Mesh; /** - * Index of this particle in the global "indices" array (Internal use) + * Creates a box mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `size` sets the size (float) of each box side (default 1). + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - _ind: number; + static CreateBox(name: string, size: number, scene?: Nullable, updatable?: boolean, sideOrientation?: number): Mesh; /** - * ModelShape of this particle (Internal use) + * Creates a sphere mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `diameter` sets the diameter size (float) of the sphere (default 1). + * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32). + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - _model: ModelShape; + static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; /** - * ModelShape id of this particle + * Creates a cylinder or a cone mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2). + * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1). + * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero. + * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance. + * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1). + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - shapeId: number; + static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene?: Scene, updatable?: any, sideOrientation?: number): Mesh; /** - * Index of the particle in its shape id (Internal use) + * Creates a torus mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `diameter` sets the diameter size (float) of the torus (default 1). + * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5). + * The parameter `tessellation` sets the number of torus sides (postive integer, default 16). + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - idxInShape: number; + static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; /** - * Reference to the shape model BoundingInfo object (Internal use) + * Creates a torus knot mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `radius` sets the global radius size (float) of the torus knot (default 2). + * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32). + * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32). + * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3). + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - _modelBoundingInfo: BoundingInfo; + static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; /** - * Particle BoundingInfo object (Internal use) - */ - _boundingInfo: BoundingInfo; - /** - * Reference to the SPS what the particle belongs to (Internal use) + * Creates a line mesh. + * Please consider using the same method from the MeshBuilder class instead. + * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter. + * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function. + * The parameter `points` is an array successive Vector3. + * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines + * When updating an instance, remember that only point positions can change, not the number of points. + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - _sps: SolidParticleSystem; + static CreateLines(name: string, points: Vector3[], scene?: Nullable, updatable?: boolean, instance?: Nullable): LinesMesh; /** - * Still set as invisible in order to skip useless computations (Internal use) + * Creates a dashed line mesh. + * Please consider using the same method from the MeshBuilder class instead. + * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter. + * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function. + * The parameter `points` is an array successive Vector3. + * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200). + * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3). + * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1). + * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines + * When updating an instance, remember that only point positions can change, not the number of points. + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - _stillInvisible: boolean; + static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene?: Nullable, updatable?: boolean, instance?: LinesMesh): LinesMesh; /** - * Last computed particle rotation matrix + * Creates a polygon mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh. + * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors. + * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Remember you can only change the shape positions, not their number when updating a polygon. */ - _rotationMatrix: number[]; + static CreatePolygon(name: string, shape: Vector3[], scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number): Mesh; /** - * Parent particle Id, if any. - * Default null. + * Creates an extruded polygon mesh, with depth in the Y direction. + * Please consider using the same method from the MeshBuilder class instead. */ - parentId: Nullable; + static ExtrudePolygon(name: string, shape: Vector3[], depth: number, scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number): Mesh; /** - * Internal global position in the SPS. + * Creates an extruded shape mesh. + * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. + * Please consider using the same method from the MeshBuilder class instead. + * + * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes + * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be + * extruded along the Z axis. + * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. + * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve. + * The parameter `scale` (float, default 1) is the value to scale the shape. + * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape + * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - _globalPosition: Vector3; + static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene?: Nullable, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; /** - * Creates a Solid Particle object. - * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle() - * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier. - * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array. - * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array. - * @param model (ModelShape) is a reference to the model shape on what the particle is designed. - * @param shapeId (integer) is the model shape identifier in the SPS. - * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30)) - * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations. + * Creates an custom extruded shape mesh. + * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. + * Please consider using the same method from the MeshBuilder class instead. + * + * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes + * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be + * extruded along the Z axis. + * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. + * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path + * and the distance of this point from the begining of the path : + * ```javascript + * var rotationFunction = function(i, distance) { + * // do things + * return rotationValue; } + * ``` + * It must returns a float value that will be the rotation in radians applied to the shape on each path point. + * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path + * and the distance of this point from the begining of the path : + * ```javascript + * var scaleFunction = function(i, distance) { + * // do things + * return scaleValue;} + * ``` + * It must returns a float value that will be the scale value applied to the shape on each path point. + * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`. + * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`. + * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape + * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - constructor(particleIndex: number, positionIndex: number, indiceIndex: number, model: Nullable, shapeId: number, idxInShape: number, sps: SolidParticleSystem, modelBoundingInfo?: Nullable); + static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction: Function, rotationFunction: Function, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; /** - * Legacy support, changed scale to scaling + * Creates lathe mesh. + * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be + * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero. + * The parameter `radius` (positive float, default 1) is the radius value of the lathe. + * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe. + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ + static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; /** - * Legacy support, changed scale to scaling + * Creates a plane mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `size` sets the size (float) of both sides of the plane at once (default 1). + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - scale: Vector3; + static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; /** - * Legacy support, changed quaternion to rotationQuaternion + * Creates a ground mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground. + * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side. + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ + static CreateGround(name: string, width: number, height: number, subdivisions: number, scene?: Scene, updatable?: boolean): Mesh; /** - * Legacy support, changed quaternion to rotationQuaternion + * Creates a tiled ground mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates. + * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates. + * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the + * numbers of subdivisions on the ground width and height. Each subdivision is called a tile. + * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the + * numbers of subdivisions on the ground width and height of each tile. + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - quaternion: Nullable; + static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { + w: number; + h: number; + }, precision: { + w: number; + h: number; + }, scene: Scene, updatable?: boolean): Mesh; /** - * Returns a boolean. True if the particle intersects another particle or another mesh, else false. - * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB) - * @param target is the object (solid particle or mesh) what the intersection is computed against. - * @returns true if it intersects + * Creates a ground mesh from a height map. + * tuto : http://doc.babylonjs.com/babylon101/height_map + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `url` sets the URL of the height map image resource. + * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes. + * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side. + * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground. + * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground. + * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time). + * This function is passed the newly built mesh : + * ```javascript + * function(mesh) { // do things + * return; } + * ``` + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - intersectsMesh(target: Mesh | SolidParticle): boolean; - } - /** - * Represents the shape of the model used by one particle of a solid particle system. - * SPS internal tool, don't use it manually. - */ - class ModelShape { + static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void): GroundMesh; /** - * The shape id. + * Creates a tube mesh. + * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube. + * The parameter `radius` (positive float, default 1) sets the tube radius size. + * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface. + * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`. + * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. + * It must return a radius value (positive float) : + * ```javascript + * var radiusFunction = function(i, distance) { + * // do things + * return radius; } + * ``` + * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - shapeID: number; + static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { + (i: number, distance: number): number; + }, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; /** - * flat array of model positions (internal use) + * Creates a polyhedron mesh. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial + * to choose the wanted type. + * The parameter `size` (positive float, default 1) sets the polygon size. + * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value). + * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`. + * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron + * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`). + * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors + * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored. + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - _shape: Vector3[]; + static CreatePolyhedron(name: string, options: { + type?: number; + size?: number; + sizeX?: number; + sizeY?: number; + sizeZ?: number; + custom?: any; + faceUV?: Vector4[]; + faceColors?: Color4[]; + updatable?: boolean; + sideOrientation?: number; + }, scene: Scene): Mesh; /** - * flat array of model UVs (internal use) + * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided. + * Please consider using the same method from the MeshBuilder class instead. + * The parameter `radius` sets the radius size (float) of the icosphere (default 1). + * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`). + * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size. + * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface. + * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ - _shapeUV: number[]; + static CreateIcoSphere(name: string, options: { + radius?: number; + flat?: boolean; + subdivisions?: number; + sideOrientation?: number; + updatable?: boolean; + }, scene: Scene): Mesh; /** - * length of the shape in the model indices array (internal use) + * Creates a decal mesh. + * Please consider using the same method from the MeshBuilder class instead. + * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal. + * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates. + * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates. + * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling. + * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal. */ - _indicesLength: number; + static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh; /** - * Custom position function (internal use) + * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. */ - _positionFunction: Nullable<(particle: SolidParticle, i: number, s: number) => void>; + setPositionsForCPUSkinning(): Float32Array; /** - * Custom vertex function (internal use) + * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. */ - _vertexFunction: Nullable<(particle: SolidParticle, vertex: Vector3, i: number) => void>; + setNormalsForCPUSkinning(): Float32Array; /** - * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS. - * SPS internal tool, don't use it manually. - * @hidden + * Updates the vertex buffer by applying transformation from the bones. + * Returns the Mesh. + * + * @param {skeleton} skeleton to apply */ - constructor(id: number, shape: Vector3[], indicesLength: number, shapeUV: number[], posFunction: Nullable<(particle: SolidParticle, i: number, s: number) => void>, vtxFunction: Nullable<(particle: SolidParticle, vertex: Vector3, i: number) => void>); - } - /** - * Represents a Depth Sorted Particle in the solid particle system. - */ - class DepthSortedParticle { + applySkeleton(skeleton: Skeleton): Mesh; /** - * Index of the particle in the "indices" array + * Returns an object `{min:` Vector3`, max:` Vector3`}` + * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system */ - ind: number; + static MinMax(meshes: AbstractMesh[]): { + min: Vector3; + max: Vector3; + }; /** - * Length of the particle shape in the "indices" array + * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array. */ - indicesLength: number; + static Center(meshesOrMinMaxVector: { + min: Vector3; + max: Vector3; + } | AbstractMesh[]): Vector3; /** - * Squared distance from the particle to the camera + * Merge the array of meshes into a single mesh for performance reasons. + * @param {Array} meshes - The vertices source. They should all be of the same material. Entries can empty + * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes + * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true. + * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class. + * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source. */ - sqDistance: number; + static MergeMeshes(meshes: Array, disposeSource?: boolean, allow32BitsIndices?: boolean, meshSubclass?: Mesh, subdivideWithSubMeshes?: boolean): Nullable; } } declare module BABYLON { /** - * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh. - *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc. - - * The SPS is also a particle system. It provides some methods to manage the particles. - * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior. - * - * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System + * Define an interface for all classes that will get and set the data on vertices */ - class SolidParticleSystem implements IDisposable { - /** - * The SPS array of Solid Particle objects. Just access each particle as with any classic array. - * Example : var p = SPS.particles[i]; - */ - particles: SolidParticle[]; + interface IGetSetVerticesData { + isVerticesDataPresent(kind: string): boolean; + getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable; + getIndices(copyWhenShared?: boolean): Nullable; + setVerticesData(kind: string, data: FloatArray, updatable: boolean): void; + updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): void; + setIndices(indices: IndicesArray, totalVertices: Nullable, updatable?: boolean): void; + } + /** + * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance + */ + class VertexData { /** - * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value. + * An array of the x, y, z position of each vertex [...., x, y, z, .....] */ - nbParticles: number; + positions: Nullable; /** - * If the particles must ever face the camera (default false). Useful for planar particles. + * An array of the x, y, z normal vector of each vertex [...., x, y, z, .....] */ - billboard: boolean; + normals: Nullable; /** - * Recompute normals when adding a shape + * An array of the x, y, z tangent vector of each vertex [...., x, y, z, .....] */ - recomputeNormals: boolean; + tangents: Nullable; /** - * This a counter ofr your own usage. It's not set by any SPS functions. + * An array of u,v which maps a texture image onto each vertex [...., u, v, .....] */ - counter: number; + uvs: Nullable; /** - * The SPS name. This name is also given to the underlying mesh. + * A second array of u,v which maps a texture image onto each vertex [...., u, v, .....] */ - name: string; + uvs2: Nullable; /** - * The SPS mesh. It's a standard BJS Mesh, so all the methods from the Mesh class are avalaible. + * A third array of u,v which maps a texture image onto each vertex [...., u, v, .....] */ - mesh: Mesh; + uvs3: Nullable; /** - * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity. - * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns + * A fourth array of u,v which maps a texture image onto each vertex [...., u, v, .....] */ - vars: any; + uvs4: Nullable; /** - * This array is populated when the SPS is set as 'pickable'. - * Each key of this array is a `faceId` value that you can get from a pickResult object. - * Each element of this array is an object `{idx: int, faceId: int}`. - * `idx` is the picked particle index in the `SPS.particles` array - * `faceId` is the picked face index counted within this particle. - * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#pickable-particles + * A fifth array of u,v which maps a texture image onto each vertex [...., u, v, .....] */ - pickedParticles: { - idx: number; - faceId: number; - }[]; + uvs5: Nullable; /** - * This array is populated when `enableDepthSort` is set to true. - * Each element of this array is an instance of the class DepthSortedParticle. + * A sixth array of u,v which maps a texture image onto each vertex [...., u, v, .....] */ - depthSortedParticles: DepthSortedParticle[]; + uvs6: Nullable; /** - * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only) + * An array of the r, g, b, a, color of each vertex [...., r, g, b, a, .....] */ - _bSphereOnly: boolean; + colors: Nullable; /** - * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only) + * An array containing the list of indices to the array of matrices produced by bones, each vertex have up to 4 indices (8 if the matricesIndicesExtra is set). */ - _bSphereRadiusFactor: number; - private _scene; - private _positions; - private _indices; - private _normals; - private _colors; - private _uvs; - private _indices32; - private _positions32; - private _normals32; - private _fixedNormal32; - private _colors32; - private _uvs32; - private _index; - private _updatable; - private _pickable; - private _isVisibilityBoxLocked; - private _alwaysVisible; - private _depthSort; - private _shapeCounter; - private _copy; - private _shape; - private _shapeUV; - private _color; - private _computeParticleColor; - private _computeParticleTexture; - private _computeParticleRotation; - private _computeParticleVertex; - private _computeBoundingBox; - private _depthSortParticles; - private _cam_axisZ; - private _cam_axisY; - private _cam_axisX; - private _axisZ; - private _camera; - private _particle; - private _camDir; - private _camInvertedPosition; - private _rotMatrix; - private _invertMatrix; - private _rotated; - private _quaternion; - private _vertex; - private _normal; - private _yaw; - private _pitch; - private _roll; - private _halfroll; - private _halfpitch; - private _halfyaw; - private _sinRoll; - private _cosRoll; - private _sinPitch; - private _cosPitch; - private _sinYaw; - private _cosYaw; - private _mustUnrotateFixedNormals; - private _minimum; - private _maximum; - private _minBbox; - private _maxBbox; - private _particlesIntersect; - private _depthSortFunction; - private _needs32Bits; - private _pivotBackTranslation; - private _scaledPivot; - private _particleHasParent; - private _parent; + matricesIndices: Nullable; /** - * Creates a SPS (Solid Particle System) object. - * @param name (String) is the SPS name, this will be the underlying mesh name. - * @param scene (Scene) is the scene in which the SPS is added. - * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable. - * @param isPickable (optional boolean, default false) : if the solid particles must be pickable. - * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera. - * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed. - * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). - * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance. - * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh. + * An array containing the list of weights defining the weight of each indexed matrix in the final computation */ - constructor(name: string, scene: Scene, options?: { - updatable?: boolean; - isPickable?: boolean; - enableDepthSort?: boolean; - particleIntersection?: boolean; - boundingSphereOnly?: boolean; - bSphereRadiusFactor?: number; - }); + matricesWeights: Nullable; /** - * Builds the SPS underlying mesh. Returns a standard Mesh. - * If no model shape was added to the SPS, the returned mesh is just a single triangular plane. - * @returns the created mesh + * An array extending the number of possible indices */ - buildMesh(): Mesh; + matricesIndicesExtra: Nullable; /** - * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS. - * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places. - * Thus the particles generated from `digest()` have their property `position` set yet. - * @param mesh ( Mesh ) is the mesh to be digested - * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any - * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets - * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets - * @returns the current SPS + * An array extending the number of possible weights when the number of indices is extended */ - digest(mesh: Mesh, options?: { - facetNb?: number; - number?: number; - delta?: number; - }): SolidParticleSystem; - private _unrotateFixedNormals(); - private _resetCopy(); - private _meshBuilder(p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options); - private _posToShape(positions); - private _uvsToShapeUV(uvs); - private _addParticle(idx, idxpos, idxind, model, shapeId, idxInShape, bInfo?); + matricesWeightsExtra: Nullable; /** - * Adds some particles to the SPS from the model shape. Returns the shape id. - * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps - * @param mesh is any Mesh object that will be used as a model for the solid particles. - * @param nb (positive integer) the number of particles to be created from this model - * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation. - * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation - * @returns the number of shapes in the system + * An array of i, j, k the three vertex indices required for each triangular facet [...., i, j, k .....] */ - addShape(mesh: Mesh, nb: number, options?: { - positionFunction?: any; - vertexFunction?: any; - }): number; - private _rebuildParticle(particle); + indices: Nullable; /** - * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed. - * @returns the SPS. + * Uses the passed data array to set the set the values for the specified kind of data + * @param data a linear array of floating numbers + * @param kind the type of data that is being set, eg positions, colors etc */ - rebuildMesh(): SolidParticleSystem; + set(data: FloatArray, kind: string): void; /** - * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc. - * This method calls `updateParticle()` for each particle of the SPS. - * For an animated SPS, it is usually called within the render loop. - * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_ - * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_ - * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_ - * @returns the SPS. + * Associates the vertexData to the passed Mesh. + * Sets it as updatable or not (default `false`) + * @param mesh the mesh the vertexData is applied to + * @param updatable when used and having the value true allows new data to update the vertexData + * @returns the VertexData */ - setParticles(start?: number, end?: number, update?: boolean): SolidParticleSystem; - private _quaternionRotationYPR(); - private _quaternionToRotationMatrix(); + applyToMesh(mesh: Mesh, updatable?: boolean): VertexData; /** - * Disposes the SPS. - */ - dispose(): void; + * Associates the vertexData to the passed Geometry. + * Sets it as updatable or not (default `false`) + * @param geometry the geometry the vertexData is applied to + * @param updatable when used and having the value true allows new data to update the vertexData + * @returns VertexData + */ + applyToGeometry(geometry: Geometry, updatable?: boolean): VertexData; /** - * Visibilty helper : Recomputes the visible size according to the mesh bounding box - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility - * @returns the SPS. + * Updates the associated mesh + * @param mesh the mesh to be updated + * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false + * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false + * @returns VertexData */ - refreshVisibleSize(): SolidParticleSystem; + updateMesh(mesh: Mesh, updateExtends?: boolean, makeItUnique?: boolean): VertexData; /** - * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box. - * @param size the size (float) of the visibility box - * note : this doesn't lock the SPS mesh bounding box. - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + * Updates the associated geometry + * @param geometry the geometry to be updated + * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false + * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false + * @returns VertexData. */ - setVisibilityBox(size: number): void; + updateGeometry(geometry: Geometry, updateExtends?: boolean, makeItUnique?: boolean): VertexData; + private _applyTo; + private _update; /** - * Gets whether the SPS as always visible or not - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + * Transforms each position and each normal of the vertexData according to the passed Matrix + * @param matrix the transforming matrix + * @returns the VertexData */ + transform(matrix: Matrix): VertexData; /** - * Sets the SPS as always visible or not - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + * Merges the passed VertexData into the current one + * @param other the VertexData to be merged into the current one + * @returns the modified VertexData */ - isAlwaysVisible: boolean; + merge(other: VertexData): VertexData; + private _mergeElement; + private _validate; /** - * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates. - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + * Serializes the VertexData + * @returns a serialized object */ + serialize(): any; /** - * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates. - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + * Extracts the vertexData from a mesh + * @param mesh the mesh from which to extract the VertexData + * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false + * @param forceCopy indicating that the VertexData must be cloned, optional, default false + * @returns the object VertexData associated to the passed mesh */ - isVisibilityBoxLocked: boolean; + static ExtractFromMesh(mesh: Mesh, copyWhenShared?: boolean, forceCopy?: boolean): VertexData; /** - * Gets if `setParticles()` computes the particle rotations or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate. + * Extracts the vertexData from the geometry + * @param geometry the geometry from which to extract the VertexData + * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false + * @param forceCopy indicating that the VertexData must be cloned, optional, default false + * @returns the object VertexData associated to the passed mesh */ + static ExtractFromGeometry(geometry: Geometry, copyWhenShared?: boolean, forceCopy?: boolean): VertexData; + private static _ExtractFrom; /** - * Tells to `setParticles()` to compute the particle rotations or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate. + * Creates the VertexData for a Ribbon + * @param options an object used to set the following optional parameters for the ribbon, required but can be empty + * * pathArray array of paths, each of which an array of successive Vector3 + * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false + * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false + * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false + * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional + * * colors a linear array, of length 4 * number of vertices, of custom color values, optional + * @returns the VertexData of the ribbon */ - computeParticleRotation: boolean; + static CreateRibbon(options: { + pathArray: Vector3[][]; + closeArray?: boolean; + closePath?: boolean; + offset?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + invertUV?: boolean; + uvs?: Vector2[]; + colors?: Color4[]; + }): VertexData; /** - * Gets if `setParticles()` computes the particle colors or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set. + * Creates the VertexData for a box + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * size sets the width, height and depth of the box to the value of size, optional default 1 + * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size + * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size + * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size + * * faceUV an array of 6 Vector4 elements used to set different images to each box side + * * faceColors an array of 6 Color3 elements used to set different colors to each box side + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the box */ + static CreateBox(options: { + size?: number; + width?: number; + height?: number; + depth?: number; + faceUV?: Vector4[]; + faceColors?: Color4[]; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * Tells to `setParticles()` to compute the particle colors or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set. + * Creates the VertexData for an ellipsoid, defaults to a sphere + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * segments sets the number of horizontal strips optional, default 32 + * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1 + * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter + * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter + * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter + * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1 + * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1 + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the ellipsoid */ - computeParticleColor: boolean; + static CreateSphere(options: { + segments?: number; + diameter?: number; + diameterX?: number; + diameterY?: number; + diameterZ?: number; + arc?: number; + slice?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * Gets if `setParticles()` computes the particle textures or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set. + * Creates the VertexData for a cylinder, cone or prism + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * height sets the height (y direction) of the cylinder, optional, default 2 + * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter + * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter + * * diameter sets the diameter of the top and bottom of the cone, optional default 1 + * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 + * * subdivisions` the number of rings along the cylinder height, optional, default 1 + * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1 + * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively + * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively + * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false + * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the cylinder, cone or prism */ - computeParticleTexture: boolean; + static CreateCylinder(options: { + height?: number; + diameterTop?: number; + diameterBottom?: number; + diameter?: number; + tessellation?: number; + subdivisions?: number; + arc?: number; + faceColors?: Color4[]; + faceUV?: Vector4[]; + hasRings?: boolean; + enclose?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not. - * Default value : false. The SPS is faster when it's set to false. - * Note : the particle custom vertex positions aren't stored values. + * Creates the VertexData for a torus + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * diameter the diameter of the torus, optional default 1 + * * thickness the diameter of the tube forming the torus, optional default 0.5 + * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the torus */ + static CreateTorus(options: { + diameter?: number; + thickness?: number; + tessellation?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not. - * Default value : false. The SPS is faster when it's set to false. - * Note : the particle custom vertex positions aren't stored values. + * Creates the VertexData of the LineSystem + * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty + * - lines an array of lines, each line being an array of successive Vector3 + * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point + * @returns the VertexData of the LineSystem */ - computeParticleVertex: boolean; + static CreateLineSystem(options: { + lines: Vector3[][]; + colors?: Nullable; + }): VertexData; /** - * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions. + * Create the VertexData for a DashedLines + * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty + * - points an array successive Vector3 + * - dashSize the size of the dashes relative to the dash number, optional, default 3 + * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1 + * - dashNb the intended total number of dashes, optional, default 200 + * @returns the VertexData for the DashedLines */ + static CreateDashedLines(options: { + points: Vector3[]; + dashSize?: number; + gapSize?: number; + dashNb?: number; + }): VertexData; /** - * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions. + * Creates the VertexData for a Ground + * @param options an object used to set the following optional parameters for the Ground, required but can be empty + * - width the width (x direction) of the ground, optional, default 1 + * - height the height (z direction) of the ground, optional, default 1 + * - subdivisions the number of subdivisions per side, optional, default 1 + * @returns the VertexData of the Ground */ - computeBoundingBox: boolean; + static CreateGround(options: { + width?: number; + height?: number; + subdivisions?: number; + subdivisionsX?: number; + subdivisionsY?: number; + }): VertexData; /** - * Gets if `setParticles()` sorts or not the distance between each particle and the camera. - * Skipped when `enableDepthSort` is set to `false` (default) at construction time. - * Default : `true` + * Creates the VertexData for a TiledGround by subdividing the ground into tiles + * @param options an object used to set the following optional parameters for the Ground, required but can be empty + * * xmin the ground minimum X coordinate, optional, default -1 + * * zmin the ground minimum Z coordinate, optional, default -1 + * * xmax the ground maximum X coordinate, optional, default 1 + * * zmax the ground maximum Z coordinate, optional, default 1 + * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6} + * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2} + * @returns the VertexData of the TiledGround */ + static CreateTiledGround(options: { + xmin: number; + zmin: number; + xmax: number; + zmax: number; + subdivisions?: { + w: number; + h: number; + }; + precision?: { + w: number; + h: number; + }; + }): VertexData; /** - * Tells to `setParticles()` to sort or not the distance between each particle and the camera. - * Skipped when `enableDepthSort` is set to `false` (default) at construction time. - * Default : `true` + * Creates the VertexData of the Ground designed from a heightmap + * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap + * * width the width (x direction) of the ground + * * height the height (z direction) of the ground + * * subdivisions the number of subdivisions per side + * * minHeight the minimum altitude on the ground, optional, default 0 + * * maxHeight the maximum altitude on the ground, optional default 1 + * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11) + * * buffer the array holding the image color data + * * bufferWidth the width of image + * * bufferHeight the height of image + * @returns the VertexData of the Ground designed from a heightmap */ - depthSortParticles: boolean; + static CreateGroundFromHeightMap(options: { + width: number; + height: number; + subdivisions: number; + minHeight: number; + maxHeight: number; + colorFilter: Color3; + buffer: Uint8Array; + bufferWidth: number; + bufferHeight: number; + }): VertexData; /** - * This function does nothing. It may be overwritten to set all the particle first values. - * The SPS doesn't call this function, you may have to call it by your own. - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management + * Creates the VertexData for a Plane + * @param options an object used to set the following optional parameters for the plane, required but can be empty + * * size sets the width and height of the plane to the value of size, optional default 1 + * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size + * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the box */ - initParticles(): void; + static CreatePlane(options: { + size?: number; + width?: number; + height?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * This function does nothing. It may be overwritten to recycle a particle. - * The SPS doesn't call this function, you may have to call it by your own. - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management - * @param particle The particle to recycle - * @returns the recycled particle + * Creates the VertexData of the Disc or regular Polygon + * @param options an object used to set the following optional parameters for the disc, required but can be empty + * * radius the radius of the disc, optional default 0.5 + * * tessellation the number of polygon sides, optional, default 64 + * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1 + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the box */ - recycleParticle(particle: SolidParticle): SolidParticle; + static CreateDisc(options: { + radius?: number; + tessellation?: number; + arc?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * Updates a particle : this function should be overwritten by the user. - * It is called on each particle by `setParticles()`. This is the place to code each particle behavior. - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management - * @example : just set a particle position or velocity and recycle conditions - * @param particle The particle to update - * @returns the updated particle + * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build() + * All parameters are provided by MeshBuilder.CreatePolygon as needed + * @param polygon a mesh built from polygonTriangulation.build() + * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively + * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively + * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the Polygon */ - updateParticle(particle: SolidParticle): SolidParticle; + static CreatePolygon(polygon: Mesh, sideOrientation: number, fUV?: Vector4[], fColors?: Color4[], frontUVs?: Vector4, backUVs?: Vector4): VertexData; /** - * Updates a vertex of a particle : it can be overwritten by the user. - * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only. - * @param particle the current particle - * @param vertex the current index of the current particle - * @param pt the index of the current vertex in the particle shape - * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape - * @example : just set a vertex particle position - * @returns the updated vertex + * Creates the VertexData of the IcoSphere + * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty + * * radius the radius of the IcoSphere, optional default 1 + * * radiusX allows stretching in the x direction, optional, default radius + * * radiusY allows stretching in the y direction, optional, default radius + * * radiusZ allows stretching in the z direction, optional, default radius + * * flat when true creates a flat shaded mesh, optional, default true + * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the IcoSphere */ - updateParticleVertex(particle: SolidParticle, vertex: Vector3, pt: number): Vector3; + static CreateIcoSphere(options: { + radius?: number; + radiusX?: number; + radiusY?: number; + radiusZ?: number; + flat?: boolean; + subdivisions?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * This will be called before any other treatment by `setParticles()` and will be passed three parameters. - * This does nothing and may be overwritten by the user. - * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param update the boolean update value actually passed to setParticles() + * Creates the VertexData for a Polyhedron + * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty + * * type provided types are: + * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1) + * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20) + * * size the size of the IcoSphere, optional default 1 + * * sizeX allows stretching in the x direction, optional, default size + * * sizeY allows stretching in the y direction, optional, default size + * * sizeZ allows stretching in the z direction, optional, default size + * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor + * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively + * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively + * * flat when true creates a flat shaded mesh, optional, default true + * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the Polyhedron */ - beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void; + static CreatePolyhedron(options: { + type?: number; + size?: number; + sizeX?: number; + sizeY?: number; + sizeZ?: number; + custom?: any; + faceUV?: Vector4[]; + faceColors?: Color4[]; + flat?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; /** - * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update. - * This will be passed three parameters. - * This does nothing and may be overwritten by the user. - * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param update the boolean update value actually passed to setParticles() + * Creates the VertexData for a TorusKnot + * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty + * * radius the radius of the torus knot, optional, default 2 + * * tube the thickness of the tube, optional, default 0.5 + * * radialSegments the number of sides on each tube segments, optional, default 32 + * * tubularSegments the number of tubes to decompose the knot into, optional, default 32 + * * p the number of windings around the z axis, optional, default 2 + * * q the number of windings around the x axis, optional, default 3 + * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the Torus Knot */ - afterUpdateParticles(start?: number, stop?: number, update?: boolean): void; + static CreateTorusKnot(options: { + radius?: number; + tube?: number; + radialSegments?: number; + tubularSegments?: number; + p?: number; + q?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }): VertexData; + /** + * Compute normals for given positions and indices + * @param positions an array of vertex positions, [...., x, y, z, ......] + * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......] + * @param normals an array of vertex normals, [...., x, y, z, ......] + * @param options an object used to set the following optional parameters for the TorusKnot, optional + * * facetNormals : optional array of facet normals (vector3) + * * facetPositions : optional array of facet positions (vector3) + * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation + * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation + * * bInfo : optional bounding info, required for facetPartitioning computation + * * bbSize : optional bounding box size data, required for facetPartitioning computation + * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation + * * useRightHandedSystem: optional boolean to for right handed system computation + * * depthSort : optional boolean to enable the facet depth sort computation + * * distanceTo : optional Vector3 to compute the facet depth from this location + * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location + */ + static ComputeNormals(positions: any, indices: any, normals: any, options?: { + facetNormals?: any; + facetPositions?: any; + facetPartitioning?: any; + ratio?: number; + bInfo?: any; + bbSize?: Vector3; + subDiv?: any; + useRightHandedSystem?: boolean; + depthSort?: boolean; + distanceTo?: Vector3; + depthSortedFacets?: any; + }): void; + private static _ComputeSides; + /** + * Applies VertexData created from the imported parameters to the geometry + * @param parsedVertexData the parsed data from an imported file + * @param geometry the geometry to apply the VertexData to + */ + static ImportVertexData(parsedVertexData: any, geometry: Geometry): void; } } declare module BABYLON { /** - * Class used to store all common mesh properties + * Class containing static functions to help procedurally build meshes */ - class AbstractMesh extends TransformNode implements IDisposable, ICullable, IGetSetVerticesData { - /** No occlusion */ - static OCCLUSION_TYPE_NONE: number; - /** Occlusion set to optimisitic */ - static OCCLUSION_TYPE_OPTIMISTIC: number; - /** Occlusion set to strict */ - static OCCLUSION_TYPE_STRICT: number; - /** Use an accurante occlusion algorithm */ - static OCCLUSION_ALGORITHM_TYPE_ACCURATE: number; - /** Use a conservative occlusion algorithm */ - static OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE: number; + class MeshBuilder { + private static updateSideOrientation; /** - * No billboard + * Creates a box mesh + * * The parameter `size` sets the size (float) of each box side (default 1) + * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`) + * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements) + * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the box mesh */ - static readonly BILLBOARDMODE_NONE: number; - /** Billboard on X axis */ - static readonly BILLBOARDMODE_X: number; - /** Billboard on Y axis */ - static readonly BILLBOARDMODE_Y: number; - /** Billboard on Z axis */ - static readonly BILLBOARDMODE_Z: number; - /** Billboard on all axes */ - static readonly BILLBOARDMODE_ALL: number; - private _facetPositions; - private _facetNormals; - private _facetPartitioning; - private _facetNb; - private _partitioningSubdivisions; - private _partitioningBBoxRatio; - private _facetDataEnabled; - private _facetParameters; - private _bbSize; - private _subDiv; - private _facetDepthSort; - private _facetDepthSortEnabled; - private _depthSortedIndices; - private _depthSortedFacets; - private _facetDepthSortFunction; - private _facetDepthSortFrom; - private _facetDepthSortOrigin; - private _invertedMatrix; + static CreateBox(name: string, options: { + size?: number; + width?: number; + height?: number; + depth?: number; + faceUV?: Vector4[]; + faceColors?: Color4[]; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + updatable?: boolean; + }, scene?: Nullable): Mesh; /** - * Gets the number of facets in the mesh - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet + * Creates a sphere mesh + * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1) + * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`) + * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32) + * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio + * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude) + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the sphere mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere */ - readonly facetNb: number; + static CreateSphere(name: string, options: { + segments?: number; + diameter?: number; + diameterX?: number; + diameterY?: number; + diameterZ?: number; + arc?: number; + slice?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + updatable?: boolean; + }, scene: any): Mesh; /** - * Gets or set the number (integer) of subdivisions per axis in the partioning space - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning + * Creates a plane polygonal mesh. By default, this is a disc + * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5) + * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc + * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the plane polygonal mesh + * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon */ - partitioningSubdivisions: number; + static CreateDisc(name: string, options: { + radius?: number; + tessellation?: number; + arc?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene?: Nullable): Mesh; /** - * The ratio (float) to apply to the bouding box size to set to the partioning space. - * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning + * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided + * * The parameter `radius` sets the radius size (float) of the icosphere (default 1) + * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`) + * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size + * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the icosahedron mesh + * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere */ - partitioningBBoxRatio: number; + static CreateIcoSphere(name: string, options: { + radius?: number; + radiusX?: number; + radiusY?: number; + radiusZ?: number; + flat?: boolean; + subdivisions?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + updatable?: boolean; + }, scene: Scene): Mesh; /** - * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`. - * Works only for updatable meshes. - * Doesn't work with multi-materials - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort + * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters + * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry + * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array + * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array + * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path + * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11 + * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture + * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones + * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values + * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry + * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the ribbon mesh + * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial + * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes */ - mustDepthSortFacets: boolean; + static CreateRibbon(name: string, options: { + pathArray: Vector3[][]; + closeArray?: boolean; + closePath?: boolean; + offset?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + instance?: Mesh; + invertUV?: boolean; + uvs?: Vector2[]; + colors?: Color4[]; + }, scene?: Nullable): Mesh; /** - * The location (Vector3) where the facet depth sort must be computed from. - * By default, the active camera position. - * Used only when facet depth sort is enabled - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort + * Creates a cylinder or a cone mesh + * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2). + * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1). + * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero. + * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance. + * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1). + * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces. + * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis. + * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder. + * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements). + * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3 + * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7 + * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17 + * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface. + * * If `enclose` is false, a ring surface is one element. + * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces. + * * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379 + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the cylinder mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone */ - facetDepthSortFrom: Vector3; + static CreateCylinder(name: string, options: { + height?: number; + diameterTop?: number; + diameterBottom?: number; + diameter?: number; + tessellation?: number; + subdivisions?: number; + arc?: number; + faceColors?: Color4[]; + faceUV?: Vector4[]; + updatable?: boolean; + hasRings?: boolean; + enclose?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene: any): Mesh; /** - * gets a boolean indicating if facetData is enabled - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet + * Creates a torus mesh + * * The parameter `diameter` sets the diameter size (float) of the torus (default 1) + * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5) + * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16) + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the torus mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus */ - readonly isFacetDataEnabled: boolean; - /** @hidden */ - _updateNonUniformScalingState(value: boolean): boolean; - /** - * An event triggered when this mesh collides with another one - */ - onCollideObservable: Observable; - private _onCollideObserver; - /** Set a function to call when this mesh collides with another one */ - onCollide: () => void; - /** - * An event triggered when the collision's position changes - */ - onCollisionPositionChangeObservable: Observable; - private _onCollisionPositionChangeObserver; - /** Set a function to call when the collision's position changes */ - onCollisionPositionChange: () => void; - /** - * An event triggered when material is changed - */ - onMaterialChangedObservable: Observable; + static CreateTorus(name: string, options: { + diameter?: number; + thickness?: number; + tessellation?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene: any): Mesh; /** - * Gets or sets the orientation for POV movement & rotation + * Creates a torus knot mesh + * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2) + * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32) + * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32) + * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3) + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the torus knot mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot */ - definedFacingForward: boolean; - /** - * This property determines the type of occlusion query algorithm to run in WebGl, you can use: - * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED. - * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate. - * @see http://doc.babylonjs.com/features/occlusionquery - */ - occlusionQueryAlgorithmType: number; + static CreateTorusKnot(name: string, options: { + radius?: number; + tube?: number; + radialSegments?: number; + tubularSegments?: number; + p?: number; + q?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene: any): Mesh; /** - * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values: - * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh. - * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh. - * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show. - * @see http://doc.babylonjs.com/features/occlusionquery + * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh + * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter + * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function + * * The parameter `lines` is an array of lines, each line being an array of successive Vector3 + * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter + * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point + * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster) + * * Updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines + * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system + * @param name defines the name of the new line system + * @param options defines the options used to create the line system + * @param scene defines the hosting scene + * @returns a new line system mesh */ - occlusionType: number; - /** - * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object. - * The default value is -1 which means don't break the query and wait till the result - * @see http://doc.babylonjs.com/features/occlusionquery - */ - occlusionRetryCount: number; - /** @hidden */ - _occlusionInternalRetryCounter: number; - /** @hidden */ - _isOccluded: boolean; - /** - * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not - * @see http://doc.babylonjs.com/features/occlusionquery - */ - isOccluded: boolean; - /** @hidden */ - _isOcclusionQueryInProgress: boolean; + static CreateLineSystem(name: string, options: { + lines: Vector3[][]; + updatable?: boolean; + instance?: Nullable; + colors?: Nullable; + useVertexAlpha?: boolean; + }, scene: Nullable): LinesMesh; /** - * Flag to check the progress status of the query - * @see http://doc.babylonjs.com/features/occlusionquery + * Creates a line mesh + * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter + * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function + * * The parameter `points` is an array successive Vector3 + * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines + * * The optional parameter `colors` is an array of successive Color4, one per line point + * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster) + * * When updating an instance, remember that only point positions can change, not the number of points + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines + * @param name defines the name of the new line system + * @param options defines the options used to create the line system + * @param scene defines the hosting scene + * @returns a new line mesh */ - readonly isOcclusionQueryInProgress: boolean; - /** @hidden */ - _occlusionQuery: Nullable; - private _visibility; + static CreateLines(name: string, options: { + points: Vector3[]; + updatable?: boolean; + instance?: Nullable; + colors?: Color4[]; + useVertexAlpha?: boolean; + }, scene?: Nullable): LinesMesh; /** - * Gets or sets mesh visibility between 0 and 1 (default is 1) + * Creates a dashed line mesh + * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter + * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function + * * The parameter `points` is an array successive Vector3 + * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200) + * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3) + * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1) + * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines + * * When updating an instance, remember that only point positions can change, not the number of points + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the dashed line mesh + * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines */ + static CreateDashedLines(name: string, options: { + points: Vector3[]; + dashSize?: number; + gapSize?: number; + dashNb?: number; + updatable?: boolean; + instance?: LinesMesh; + }, scene?: Nullable): LinesMesh; /** - * Gets or sets mesh visibility between 0 and 1 (default is 1) - */ - visibility: number; - /** Gets or sets the alpha index used to sort transparent meshes - * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index + * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. + * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis. + * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. + * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve. + * * The parameter `scale` (float, default 1) is the value to scale the shape. + * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape + * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture. + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the extruded shape mesh + * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes + * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes + * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes */ - alphaIndex: number; + static ExtrudeShape(name: string, options: { + shape: Vector3[]; + path: Vector3[]; + scale?: number; + rotation?: number; + cap?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + instance?: Mesh; + invertUV?: boolean; + }, scene?: Nullable): Mesh; /** - * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true + * Creates an custom extruded shape mesh. + * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. + * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis. + * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. + * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path + * * It must returns a float value that will be the rotation in radians applied to the shape on each path point. + * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path + * * It must returns a float value that will be the scale value applied to the shape on each path point + * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray` + * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray` + * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape + * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the custom extruded shape mesh + * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes + * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes + * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes */ - isVisible: boolean; + static ExtrudeShapeCustom(name: string, options: { + shape: Vector3[]; + path: Vector3[]; + scaleFunction?: any; + rotationFunction?: any; + ribbonCloseArray?: boolean; + ribbonClosePath?: boolean; + cap?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + instance?: Mesh; + invertUV?: boolean; + }, scene: Scene): Mesh; /** - * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true - */ - isPickable: boolean; - /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */ - showSubMeshesBoundingBox: boolean; - /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default) - * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares + * Creates lathe mesh. + * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe + * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero + * * The parameter `radius` (positive float, default 1) is the radius value of the lathe + * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe + * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides + * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape + * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc" + * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the lathe mesh + * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe */ - isBlocker: boolean; - /** - * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default) + static CreateLathe(name: string, options: { + shape: Vector3[]; + radius?: number; + tessellation?: number; + clip?: number; + arc?: number; + closed?: boolean; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + cap?: number; + invertUV?: boolean; + }, scene: Scene): Mesh; + /** + * Creates a plane mesh + * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1) + * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`) + * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the plane mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane */ - enablePointerMoveEvents: boolean; + static CreatePlane(name: string, options: { + size?: number; + width?: number; + height?: number; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + updatable?: boolean; + sourcePlane?: Plane; + }, scene: Scene): Mesh; /** - * Specifies the rendering group id for this mesh (0 by default) - * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups + * Creates a ground mesh + * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground + * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the ground mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane */ - renderingGroupId: number; - private _material; - /** Gets or sets current material */ - material: Nullable; - private _receiveShadows; + static CreateGround(name: string, options: { + width?: number; + height?: number; + subdivisions?: number; + subdivisionsX?: number; + subdivisionsY?: number; + updatable?: boolean; + }, scene: any): Mesh; /** - * Gets or sets a boolean indicating that this mesh can receive realtime shadows - * @see http://doc.babylonjs.com/babylon101/shadows + * Creates a tiled ground mesh + * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates + * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates + * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile + * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the tiled ground mesh + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground */ - receiveShadows: boolean; + static CreateTiledGround(name: string, options: { + xmin: number; + zmin: number; + xmax: number; + zmax: number; + subdivisions?: { + w: number; + h: number; + }; + precision?: { + w: number; + h: number; + }; + updatable?: boolean; + }, scene: Scene): Mesh; /** - * Gets or sets a boolean indicating if the outline must be rendered as well - * @see https://www.babylonjs-playground.com/#10WJ5S#3 + * Creates a ground mesh from a height map + * * The parameter `url` sets the URL of the height map image resource. + * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes. + * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side. + * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground. + * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground. + * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height. + * * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time). + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param url defines the url to the height map + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the ground mesh + * @see http://doc.babylonjs.com/babylon101/height_map + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map */ - renderOutline: boolean; - /** Defines color to use when rendering outline */ - outlineColor: Color3; - /** Define width to use when rendering outline */ - outlineWidth: number; + static CreateGroundFromHeightMap(name: string, url: string, options: { + width?: number; + height?: number; + subdivisions?: number; + minHeight?: number; + maxHeight?: number; + colorFilter?: Color3; + updatable?: boolean; + onReady?: (mesh: GroundMesh) => void; + }, scene: Scene): GroundMesh; /** - * Gets or sets a boolean indicating if the overlay must be rendered as well - * @see https://www.babylonjs-playground.com/#10WJ5S#2 + * Creates a polygon mesh + * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh + * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors + * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4) + * * Remember you can only change the shape positions, not their number when updating a polygon + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the polygon mesh */ - renderOverlay: boolean; - /** Defines color to use when rendering overlay */ - overlayColor: Color3; - /** Defines alpha to use when rendering overlay */ - overlayAlpha: number; - private _hasVertexAlpha; - /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */ - hasVertexAlpha: boolean; - private _useVertexColors; - /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */ - useVertexColors: boolean; - private _computeBonesUsingShaders; + static CreatePolygon(name: string, options: { + shape: Vector3[]; + holes?: Vector3[][]; + depth?: number; + faceUV?: Vector4[]; + faceColors?: Color4[]; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene: Scene): Mesh; /** - * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default) + * Creates an extruded polygon mesh, with depth in the Y direction. + * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements) + * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the polygon mesh */ - computeBonesUsingShaders: boolean; - private _numBoneInfluencers; - /** Gets or sets the number of allowed bone influences per vertex (4 by default) */ - numBoneInfluencers: number; - private _applyFog; - /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */ - applyFog: boolean; - /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */ - useOctreeForRenderingSelection: boolean; - /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */ - useOctreeForPicking: boolean; - /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */ - useOctreeForCollisions: boolean; - private _layerMask; + static ExtrudePolygon(name: string, options: { + shape: Vector3[]; + holes?: Vector3[][]; + depth?: number; + faceUV?: Vector4[]; + faceColors?: Color4[]; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene: Scene): Mesh; /** - * Gets or sets the current layer mask (default is 0x0FFFFFFF) - * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures + * Creates a tube mesh. + * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters + * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube + * * The parameter `radius` (positive float, default 1) sets the tube radius size + * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface + * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius` + * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float) + * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc + * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the tube mesh + * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes + * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube */ - layerMask: number; + static CreateTube(name: string, options: { + path: Vector3[]; + radius?: number; + tessellation?: number; + radiusFunction?: { + (i: number, distance: number): number; + }; + cap?: number; + arc?: number; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + instance?: Mesh; + invertUV?: boolean; + }, scene: Scene): Mesh; /** - * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase) + * Creates a polyhedron mesh + * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type + * * The parameter `size` (positive float, default 1) sets the polygon size + * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value) + * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type` + * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron + * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`) + * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors + * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the polyhedron mesh + * @see http://doc.babylonjs.com/how_to/polyhedra_shapes */ - alwaysSelectAsActiveMesh: boolean; + static CreatePolyhedron(name: string, options: { + type?: number; + size?: number; + sizeX?: number; + sizeY?: number; + sizeZ?: number; + custom?: any; + faceUV?: Vector4[]; + faceColors?: Color4[]; + flat?: boolean; + updatable?: boolean; + sideOrientation?: number; + frontUVs?: Vector4; + backUVs?: Vector4; + }, scene: Scene): Mesh; /** - * Gets or sets the current action manager - * @see http://doc.babylonjs.com/how_to/how_to_use_actions + * Creates a decal mesh. + * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal + * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates + * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates + * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling + * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal + * @param name defines the name of the mesh + * @param sourceMesh defines the mesh where the decal must be applied + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the decal mesh + * @see http://doc.babylonjs.com/how_to/decals */ - actionManager: Nullable; + static CreateDecal(name: string, sourceMesh: AbstractMesh, options: { + position?: Vector3; + normal?: Vector3; + size?: Vector3; + angle?: number; + }): Mesh; + private static _ExtrudeShapeGeneric; + } +} + +declare module BABYLON { + class MeshLODLevel { + distance: number; + mesh: Nullable; + constructor(distance: number, mesh: Nullable); + } +} + +declare module BABYLON { + /** + * A simplifier interface for future simplification implementations. + */ + interface ISimplifier { /** - * Gets or sets impostor used for physic simulation - * @see http://doc.babylonjs.com/features/physics_engine + * Simplification of a given mesh according to the given settings. + * Since this requires computation, it is assumed that the function runs async. + * @param settings The settings of the simplification, including quality and distance + * @param successCallback A callback that will be called after the mesh was simplified. + * @param errorCallback in case of an error, this callback will be called. optional. */ - physicsImpostor: Nullable; - private _checkCollisions; - private _collisionMask; - private _collisionGroup; + simplify(settings: ISimplificationSettings, successCallback: (simplifiedMeshes: Mesh) => void, errorCallback?: () => void): void; + } + /** + * Expected simplification settings. + * Quality should be between 0 and 1 (1 being 100%, 0 being 0%); + */ + interface ISimplificationSettings { + quality: number; + distance: number; + optimizeMesh?: boolean; + } + class SimplificationSettings implements ISimplificationSettings { + quality: number; + distance: number; + optimizeMesh?: boolean | undefined; + constructor(quality: number, distance: number, optimizeMesh?: boolean | undefined); + } + interface ISimplificationTask { + settings: Array; + simplificationType: SimplificationType; + mesh: Mesh; + successCallback?: () => void; + parallelProcessing: boolean; + } + class SimplificationQueue { + private _simplificationArray; + running: boolean; + constructor(); + addTask(task: ISimplificationTask): void; + executeNext(): void; + runSimplification(task: ISimplificationTask): void; + private getSimplifier; + } + /** + * The implemented types of simplification + * At the moment only Quadratic Error Decimation is implemented + */ + enum SimplificationType { + /** Quadratic error decimation */ + QUADRATIC = 0 + } + class DecimationTriangle { + vertices: Array; + normal: Vector3; + error: Array; + deleted: boolean; + isDirty: boolean; + borderFactor: number; + deletePending: boolean; + originalOffset: number; + constructor(vertices: Array); + } + class DecimationVertex { + position: Vector3; + id: number; + q: QuadraticMatrix; + isBorder: boolean; + triangleStart: number; + triangleCount: number; + originalOffsets: Array; + constructor(position: Vector3, id: number); + updatePosition(newPosition: Vector3): void; + } + class QuadraticMatrix { + data: Array; + constructor(data?: Array); + det(a11: number, a12: number, a13: number, a21: number, a22: number, a23: number, a31: number, a32: number, a33: number): number; + addInPlace(matrix: QuadraticMatrix): void; + addArrayInPlace(data: Array): void; + add(matrix: QuadraticMatrix): QuadraticMatrix; + static FromData(a: number, b: number, c: number, d: number): QuadraticMatrix; + static DataFromNumbers(a: number, b: number, c: number, d: number): number[]; + } + class Reference { + vertexId: number; + triangleId: number; + constructor(vertexId: number, triangleId: number); + } + /** + * An implementation of the Quadratic Error simplification algorithm. + * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf + * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS + * @author RaananW + */ + class QuadraticErrorSimplification implements ISimplifier { + private _mesh; + private triangles; + private vertices; + private references; + private _reconstructedMesh; + syncIterations: number; + aggressiveness: number; + decimationIterations: number; + boundingBoxEpsilon: number; + constructor(_mesh: Mesh); + simplify(settings: ISimplificationSettings, successCallback: (simplifiedMesh: Mesh) => void): void; + private runDecimation; + private initWithMesh; + private init; + private reconstructMesh; + private initDecimatedMesh; + private isFlipped; + private updateTriangles; + private identifyBorder; + private updateMesh; + private vertexError; + private calculateError; + } +} + +declare module BABYLON { + class Polygon { + static Rectangle(xmin: number, ymin: number, xmax: number, ymax: number): Vector2[]; + static Circle(radius: number, cx?: number, cy?: number, numberOfSides?: number): Vector2[]; + static Parse(input: string): Vector2[]; + static StartingAt(x: number, y: number): Path2; + } + class PolygonMeshBuilder { + private _points; + private _outlinepoints; + private _holes; + private _name; + private _scene; + private _epoints; + private _eholes; + private _addToepoint; + constructor(name: string, contours: Path2, scene: Scene); + constructor(name: string, contours: Vector2[], scene: Scene); + addHole(hole: Vector2[]): PolygonMeshBuilder; + build(updatable?: boolean, depth?: number): Mesh; + private addSide; + } +} + +declare module BABYLON { + class BaseSubMesh { + _materialDefines: Nullable; + _materialEffect: Nullable; + readonly effect: Nullable; + setEffect(effect: Nullable, defines?: Nullable): void; + } + class SubMesh extends BaseSubMesh implements ICullable { + materialIndex: number; + verticesStart: number; + verticesCount: number; + indexStart: number; + indexCount: number; + linesIndexCount: number; + private _mesh; + private _renderingMesh; + private _boundingInfo; + private _linesIndexBuffer; + _lastColliderWorldVertices: Nullable; + _trianglePlanes: Plane[]; + _lastColliderTransformMatrix: Matrix; + _renderId: number; + _alphaIndex: number; + _distanceToCamera: number; + _id: number; + private _currentMaterial; + static AddToMesh(materialIndex: number, verticesStart: number, verticesCount: number, indexStart: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox?: boolean): SubMesh; + constructor(materialIndex: number, verticesStart: number, verticesCount: number, indexStart: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox?: boolean); + readonly IsGlobal: boolean; /** - * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5)) - * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity + * Returns the submesh BoudingInfo object. */ - ellipsoid: Vector3; + getBoundingInfo(): BoundingInfo; /** - * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0)) - * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity + * Sets the submesh BoundingInfo. + * Return the SubMesh. */ - ellipsoidOffset: Vector3; - private _collider; - private _oldPositionForCollisions; - private _diffPositionForCollisions; + setBoundingInfo(boundingInfo: BoundingInfo): SubMesh; /** - * Gets or sets a collision mask used to mask collisions (default is -1). - * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 + * Returns the mesh of the current submesh. */ - collisionMask: number; + getMesh(): AbstractMesh; /** - * Gets or sets the current collision group mask (-1 by default). - * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 + * Returns the rendering mesh of the submesh. */ - collisionGroup: number; + getRenderingMesh(): Mesh; /** - * Defines edge width used when edgesRenderer is enabled - * @see https://www.babylonjs-playground.com/#10OJSG#13 + * Returns the submesh material. */ - edgesWidth: number; + getMaterial(): Nullable; /** - * Defines edge color used when edgesRenderer is enabled - * @see https://www.babylonjs-playground.com/#10OJSG#13 + * Sets a new updated BoundingInfo object to the submesh. + * Returns the SubMesh. */ - edgesColor: Color4; - /** @hidden */ - _edgesRenderer: Nullable; - private _collisionsTransformMatrix; - private _collisionsScalingMatrix; - /** @hidden */ - _masterMesh: Nullable; - /** @hidden */ - _boundingInfo: Nullable; - /** @hidden */ - _renderId: number; + refreshBoundingInfo(): SubMesh; + _checkCollision(collider: Collider): boolean; /** - * Gets or sets the list of subMeshes - * @see http://doc.babylonjs.com/how_to/multi_materials + * Updates the submesh BoundingInfo. + * Returns the Submesh. */ - subMeshes: SubMesh[]; - /** @hidden */ - _submeshesOctree: Octree; - /** @hidden */ - _intersectionsInProgress: AbstractMesh[]; - /** @hidden */ - _unIndexed: boolean; - /** @hidden */ - _lightSources: Light[]; - /** @hidden */ - readonly _positions: Nullable; - /** @hidden */ - _waitingActions: any; - /** @hidden */ - _waitingFreezeWorldMatrix: Nullable; - private _skeleton; - /** @hidden */ - _bonesTransformMatrices: Nullable; + updateBoundingInfo(world: Matrix): SubMesh; /** - * Gets or sets a skeleton to apply skining transformations - * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons + * True is the submesh bounding box intersects the frustum defined by the passed array of planes. + * Boolean returned. */ - skeleton: Nullable; + isInFrustum(frustumPlanes: Plane[]): boolean; /** - * Creates a new AbstractMesh - * @param name defines the name of the mesh - * @param scene defines the hosting scene + * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes. + * Boolean returned. */ - constructor(name: string, scene?: Nullable); + isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; /** - * Returns the string "AbstractMesh" - * @returns "AbstractMesh" + * Renders the submesh. + * Returns it. */ - getClassName(): string; + render(enableAlphaMode: boolean): SubMesh; /** - * Gets a string representation of the current mesh - * @param fullDetails defines a boolean indicating if full details must be included - * @returns a string representation of the current mesh + * Returns a new Index Buffer. + * Type returned : WebGLBuffer. */ - toString(fullDetails?: boolean): string; - /** @hidden */ - _rebuild(): void; - /** @hidden */ - _resyncLightSources(): void; - /** @hidden */ - _resyncLighSource(light: Light): void; - /** @hidden */ - _unBindEffect(): void; - /** @hidden */ - _removeLightSource(light: Light): void; - private _markSubMeshesAsDirty(func); - /** @hidden */ - _markSubMeshesAsLightDirty(): void; - /** @hidden */ - _markSubMeshesAsAttributesDirty(): void; - /** @hidden */ - _markSubMeshesAsMiscDirty(): void; - /** - * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0) - */ - scaling: Vector3; + getLinesIndexBuffer(indices: IndicesArray, engine: Engine): WebGLBuffer; /** - * Disables the mesh edge rendering mode - * @returns the currentAbstractMesh + * True is the passed Ray intersects the submesh bounding box. + * Boolean returned. */ - disableEdgesRendering(): AbstractMesh; + canIntersects(ray: Ray): boolean; /** - * Enables the edge rendering mode on the mesh. - * This mode makes the mesh edges visible - * @param epsilon defines the maximal distance between two angles to detect a face - * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces - * @returns the currentAbstractMesh - * @see https://www.babylonjs-playground.com/#19O9TU#0 + * Returns an object IntersectionInfo. */ - enableEdgesRendering(epsilon?: number, checkVerticesInsteadOfIndices?: boolean): AbstractMesh; + intersects(ray: Ray, positions: Vector3[], indices: IndicesArray, fastCheck?: boolean): Nullable; + _rebuild(): void; /** - * Gets the edgesRenderer associated with the mesh + * Creates a new Submesh from the passed Mesh. */ - readonly edgesRenderer: Nullable; + clone(newMesh: AbstractMesh, newRenderingMesh?: Mesh): SubMesh; /** - * Returns true if the mesh is blocked. Implemented by child classes + * Disposes the Submesh. + * Returns nothing. */ - readonly isBlocked: boolean; + dispose(): void; /** - * Returns the mesh itself by default. Implemented by child classes - * @param camera defines the camera to use to pick the right LOD level - * @returns the currentAbstractMesh + * Creates a new Submesh from the passed parameters : + * - materialIndex (integer) : the index of the main mesh material. + * - startIndex (integer) : the index where to start the copy in the mesh indices array. + * - indexCount (integer) : the number of indices to copy then from the startIndex. + * - mesh (Mesh) : the main mesh to create the submesh from. + * - renderingMesh (optional Mesh) : rendering mesh. */ - getLOD(camera: Camera): Nullable; + static CreateFromIndices(materialIndex: number, startIndex: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh): SubMesh; + } +} + +declare module BABYLON { + class TransformNode extends Node { + static BILLBOARDMODE_NONE: number; + static BILLBOARDMODE_X: number; + static BILLBOARDMODE_Y: number; + static BILLBOARDMODE_Z: number; + static BILLBOARDMODE_ALL: number; + private _forward; + private _forwardInverted; + private _up; + private _right; + private _rightInverted; + private _rotation; + private _rotationQuaternion; + protected _scaling: Vector3; + protected _isDirty: boolean; + private _transformToBoneReferal; /** - * Returns 0 by default. Implemented by child classes - * @returns an integer - */ - getTotalVertices(): number; + * Set the billboard mode. Default is 0. + * + * | Value | Type | Description | + * | --- | --- | --- | + * | 0 | BILLBOARDMODE_NONE | | + * | 1 | BILLBOARDMODE_X | | + * | 2 | BILLBOARDMODE_Y | | + * | 4 | BILLBOARDMODE_Z | | + * | 7 | BILLBOARDMODE_ALL | | + * + */ + billboardMode: number; + scalingDeterminant: number; + infiniteDistance: boolean; /** - * Returns null by default. Implemented by child classes - * @returns null + * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored. + * By default the system will update normals to compensate */ - getIndices(): Nullable; + ignoreNonUniformScaling: boolean; + position: Vector3; + _poseMatrix: Matrix; + private _localWorld; + _worldMatrix: Matrix; + _worldMatrixDeterminant: number; + private _absolutePosition; + private _pivotMatrix; + private _pivotMatrixInverse; + private _postMultiplyPivotMatrix; + protected _isWorldMatrixFrozen: boolean; /** - * Returns the array of the requested vertex data kind. Implemented by child classes - * @param kind defines the vertex data kind to use - * @returns null - */ - getVerticesData(kind: string): Nullable; + * An event triggered after the world matrix is updated + */ + onAfterWorldMatrixUpdateObservable: Observable; + constructor(name: string, scene?: Nullable, isPure?: boolean); /** - * Sets the vertex data of the mesh geometry for the requested `kind`. - * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. - * Note that a new underlying VertexBuffer object is created each call. - * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. - * @param kind defines vertex data kind: - * * BABYLON.VertexBuffer.PositionKind - * * BABYLON.VertexBuffer.UVKind - * * BABYLON.VertexBuffer.UV2Kind - * * BABYLON.VertexBuffer.UV3Kind - * * BABYLON.VertexBuffer.UV4Kind - * * BABYLON.VertexBuffer.UV5Kind - * * BABYLON.VertexBuffer.UV6Kind - * * BABYLON.VertexBuffer.ColorKind - * * BABYLON.VertexBuffer.MatricesIndicesKind - * * BABYLON.VertexBuffer.MatricesIndicesExtraKind - * * BABYLON.VertexBuffer.MatricesWeightsKind - * * BABYLON.VertexBuffer.MatricesWeightsExtraKind - * @param data defines the data source - * @param updatable defines if the data must be flagged as updatable (or static) - * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind - * @returns the current mesh + * Gets a string idenfifying the name of the class + * @returns "TransformNode" string */ - setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): AbstractMesh; + getClassName(): string; /** - * Updates the existing vertex data of the mesh geometry for the requested `kind`. - * If the mesh has no geometry, it is simply returned as it is. - * @param kind defines vertex data kind: - * * BABYLON.VertexBuffer.PositionKind - * * BABYLON.VertexBuffer.UVKind - * * BABYLON.VertexBuffer.UV2Kind - * * BABYLON.VertexBuffer.UV3Kind - * * BABYLON.VertexBuffer.UV4Kind - * * BABYLON.VertexBuffer.UV5Kind - * * BABYLON.VertexBuffer.UV6Kind - * * BABYLON.VertexBuffer.ColorKind - * * BABYLON.VertexBuffer.MatricesIndicesKind - * * BABYLON.VertexBuffer.MatricesIndicesExtraKind - * * BABYLON.VertexBuffer.MatricesWeightsKind - * * BABYLON.VertexBuffer.MatricesWeightsExtraKind - * @param data defines the data source - * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed - * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh - * @returns the current mesh - */ - updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): AbstractMesh; + * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z. + * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector! + * Default : (0.0, 0.0, 0.0) + */ + rotation: Vector3; /** - * Sets the mesh indices, - * If the mesh has no geometry, a new Geometry object is created and set to the mesh. - * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array) - * @param totalVertices Defines the total number of vertices - * @returns the current mesh + * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z. + * Default : (1.0, 1.0, 1.0) */ - setIndices(indices: IndicesArray, totalVertices: Nullable): AbstractMesh; /** - * Gets a boolean indicating if specific vertex data is present - * @param kind defines the vertex data kind to use - * @returns true is data kind is present + * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z. + * Default : (1.0, 1.0, 1.0) + */ + scaling: Vector3; + /** + * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion. + * It's null by default. + * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0) */ - isVerticesDataPresent(kind: string): boolean; + rotationQuaternion: Nullable; /** - * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined - * @returns a BoundingInfo + * The forward direction of that transform in world space. */ - getBoundingInfo(): BoundingInfo; + readonly forward: Vector3; /** - * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units) - * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box - * @returns the current mesh + * The up direction of that transform in world space. */ - normalizeToUnitCube(includeDescendants?: boolean): AbstractMesh; + readonly up: Vector3; /** - * Overwrite the current bounding info - * @param boundingInfo defines the new bounding info - * @returns the current mesh + * The right direction of that transform in world space. */ - setBoundingInfo(boundingInfo: BoundingInfo): AbstractMesh; - /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */ - readonly useBones: boolean; - /** @hidden */ - _preActivate(): void; - /** @hidden */ - _preActivateForIntermediateRendering(renderId: number): void; - /** @hidden */ - _activate(renderId: number): void; + readonly right: Vector3; /** - * Gets the current world matrix - * @returns a Matrix + * Returns the latest update of the World matrix + * Returns a Matrix. */ getWorldMatrix(): Matrix; /** @hidden */ _getWorldMatrixDeterminant(): number; /** - * Perform relative position change from the point of view of behind the front of the mesh. - * This is performed taking into account the meshes current rotation, so you do not have to care. - * Supports definition of mesh facing forward or backward - * @param amountRight defines the distance on the right axis - * @param amountUp defines the distance on the up axis - * @param amountForward defines the distance on the forward axis - * @returns the current mesh + * Returns directly the latest state of the mesh World matrix. + * A Matrix is returned. */ - movePOV(amountRight: number, amountUp: number, amountForward: number): AbstractMesh; + readonly worldMatrixFromCache: Matrix; /** - * Calculate relative position change from the point of view of behind the front of the mesh. - * This is performed taking into account the meshes current rotation, so you do not have to care. - * Supports definition of mesh facing forward or backward - * @param amountRight defines the distance on the right axis - * @param amountUp defines the distance on the up axis - * @param amountForward defines the distance on the forward axis - * @returns the new displacement vector + * Copies the paramater passed Matrix into the mesh Pose matrix. + * Returns the TransformNode. */ - calcMovePOV(amountRight: number, amountUp: number, amountForward: number): Vector3; + updatePoseMatrix(matrix: Matrix): TransformNode; /** - * Perform relative rotation change from the point of view of behind the front of the mesh. - * Supports definition of mesh facing forward or backward - * @param flipBack defines the flip - * @param twirlClockwise defines the twirl - * @param tiltRight defines the tilt - * @returns the current mesh + * Returns the mesh Pose matrix. + * Returned object : Matrix */ - rotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): AbstractMesh; + getPoseMatrix(): Matrix; + _isSynchronized(): boolean; + _initCache(): void; + markAsDirty(property: string): TransformNode; /** - * Calculate relative rotation change from the point of view of behind the front of the mesh. - * Supports definition of mesh facing forward or backward. - * @param flipBack defines the flip - * @param twirlClockwise defines the twirl - * @param tiltRight defines the tilt - * @returns the new rotation vector + * Returns the current mesh absolute position. + * Retuns a Vector3. */ - calcRotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): Vector3; + readonly absolutePosition: Vector3; /** - * Return the minimum and maximum world vectors of the entire hierarchy under current mesh - * @param includeDescendants Include bounding info from descendants as well (true by default) - * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors - * @returns the new bounding vectors + * Sets a new matrix to apply before all other transformation + * @param matrix defines the transform matrix + * @returns the current TransformNode */ - getHierarchyBoundingVectors(includeDescendants?: boolean, predicate?: Nullable<(abstractMesh: AbstractMesh) => boolean>): { - min: Vector3; - max: Vector3; - }; - /** @hidden */ - _updateBoundingInfo(): AbstractMesh; - /** @hidden */ - _updateSubMeshesBoundingInfo(matrix: Matrix): AbstractMesh; - /** @hidden */ - protected _afterComputeWorldMatrix(): void; + setPreTransformMatrix(matrix: Matrix): TransformNode; /** - * Returns `true` if the mesh is within the frustum defined by the passed array of planes. - * A mesh is in the frustum if its bounding box intersects the frustum - * @param frustumPlanes defines the frustum to test - * @returns true if the mesh is in the frustum planes - */ - isInFrustum(frustumPlanes: Plane[]): boolean; + * Sets a new pivot matrix to the current node + * @param matrix defines the new pivot matrix to use + * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect + * @returns the current TransformNode + */ + setPivotMatrix(matrix: Matrix, postMultiplyPivotMatrix?: boolean): TransformNode; /** - * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes. - * A mesh is completely in the frustum if its bounding box it completely inside the frustum. - * @param frustumPlanes defines the frustum to test - * @returns true if the mesh is completely in the frustum planes + * Returns the mesh pivot matrix. + * Default : Identity. + * A Matrix is returned. */ - isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; + getPivotMatrix(): Matrix; /** - * True if the mesh intersects another mesh or a SolidParticle object - * @param mesh defines a target mesh or SolidParticle to test - * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes) - * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes - * @returns true if there is an intersection + * Prevents the World matrix to be computed any longer. + * Returns the TransformNode. */ - intersectsMesh(mesh: AbstractMesh | SolidParticle, precise?: boolean, includeDescendants?: boolean): boolean; + freezeWorldMatrix(): TransformNode; /** - * Returns true if the passed point (Vector3) is inside the mesh bounding box - * @param point defines the point to test - * @returns true if there is an intersection + * Allows back the World matrix computation. + * Returns the TransformNode. */ - intersectsPoint(point: Vector3): boolean; + unfreezeWorldMatrix(): this; /** - * Gets the current physics impostor - * @see http://doc.babylonjs.com/features/physics_engine - * @returns a physics impostor or null + * True if the World matrix has been frozen. + * Returns a boolean. */ - getPhysicsImpostor(): Nullable; + readonly isWorldMatrixFrozen: boolean; /** - * Gets the position of the current mesh in camera space - * @param camera defines the camera to use - * @returns a position - */ - getPositionInCameraSpace(camera?: Nullable): Vector3; + * Retuns the mesh absolute position in the World. + * Returns a Vector3. + */ + getAbsolutePosition(): Vector3; /** - * Returns the distance from the mesh to the active camera - * @param camera defines the camera to use - * @returns the distance + * Sets the mesh absolute position in the World from a Vector3 or an Array(3). + * Returns the TransformNode. */ - getDistanceToCamera(camera?: Nullable): number; + setAbsolutePosition(absolutePosition: Vector3): TransformNode; /** - * Apply a physic impulse to the mesh - * @param force defines the force to apply - * @param contactPoint defines where to apply the force - * @returns the current mesh - * @see http://doc.babylonjs.com/how_to/using_the_physics_engine - */ - applyImpulse(force: Vector3, contactPoint: Vector3): AbstractMesh; + * Sets the mesh position in its local space. + * Returns the TransformNode. + */ + setPositionWithLocalVector(vector3: Vector3): TransformNode; /** - * Creates a physic joint between two meshes - * @param otherMesh defines the other mesh to use - * @param pivot1 defines the pivot to use on this mesh - * @param pivot2 defines the pivot to use on the other mesh - * @param options defines additional options (can be plugin dependent) - * @returns the current mesh - * @see https://www.babylonjs-playground.com/#0BS5U0#0 + * Returns the mesh position in the local space from the current World matrix values. + * Returns a new Vector3. */ - setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3, options?: any): AbstractMesh; + getPositionExpressedInLocalSpace(): Vector3; /** - * Gets or sets a boolean indicating that this mesh can be used in the collision engine - * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity + * Translates the mesh along the passed Vector3 in its local space. + * Returns the TransformNode. */ - checkCollisions: boolean; + locallyTranslate(vector3: Vector3): TransformNode; + private static _lookAtVectorCache; /** - * Gets Collider object used to compute collisions (not physics) - * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity + * Orients a mesh towards a target point. Mesh must be drawn facing user. + * @param targetPoint the position (must be in same space as current mesh) to look at + * @param yawCor optional yaw (y-axis) correction in radians + * @param pitchCor optional pitch (x-axis) correction in radians + * @param rollCor optional roll (z-axis) correction in radians + * @param space the choosen space of the target + * @returns the TransformNode. */ - readonly collider: Collider; + lookAt(targetPoint: Vector3, yawCor?: number, pitchCor?: number, rollCor?: number, space?: Space): TransformNode; /** - * Move the mesh using collision engine - * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity - * @param displacement defines the requested displacement vector - * @returns the current mesh + * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh. + * This Vector3 is expressed in the World space. + */ + getDirection(localAxis: Vector3): Vector3; + /** + * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh. + * localAxis is expressed in the mesh local space. + * result is computed in the Wordl space from the mesh World matrix. + * Returns the TransformNode. */ - moveWithCollisions(displacement: Vector3): AbstractMesh; - private _onCollisionPositionChange; + getDirectionToRef(localAxis: Vector3, result: Vector3): TransformNode; /** - * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations. - * Please note that you must have a decent number of submeshes to get performance improvements when using an octree - * @param maxCapacity defines the maximum size of each block (64 by default) - * @param maxDepth defines the maximum depth to use (no more than 2 levels by default) - * @returns the new octree - * @see https://www.babylonjs-playground.com/#NA4OQ#12 - * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees + * Sets a new pivot point to the current node + * @param point defines the new pivot point to use + * @param space defines if the point is in world or local space (local by default) + * @returns the current TransformNode */ - createOrUpdateSubmeshesOctree(maxCapacity?: number, maxDepth?: number): Octree; - /** @hidden */ - _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): AbstractMesh; - /** @hidden */ - _processCollisionsForSubMeshes(collider: Collider, transformMatrix: Matrix): AbstractMesh; - /** @hidden */ - _checkCollision(collider: Collider): AbstractMesh; - /** @hidden */ - _generatePointsArray(): boolean; + setPivotPoint(point: Vector3, space?: Space): TransformNode; /** - * Checks if the passed Ray intersects with the mesh - * @param ray defines the ray to use - * @param fastCheck defines if fast mode (but less precise) must be used (false by default) - * @returns the picking info - * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh + * Returns a new Vector3 set with the mesh pivot point coordinates in the local space. */ - intersects(ray: Ray, fastCheck?: boolean): PickingInfo; + getPivotPoint(): Vector3; /** - * Clones the current mesh - * @param name defines the mesh name - * @param newParent defines the new mesh parent - * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default) - * @returns the new mesh + * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space. + * Returns the TransformNode. */ - clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable; + getPivotPointToRef(result: Vector3): TransformNode; /** - * Disposes all the submeshes of the current meshnp - * @returns the current mesh + * Returns a new Vector3 set with the mesh pivot point World coordinates. */ - releaseSubMeshes(): AbstractMesh; + getAbsolutePivotPoint(): Vector3; /** - * Releases resources associated with this abstract mesh. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates. + * Returns the TransformNode. */ - dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; + getAbsolutePivotPointToRef(result: Vector3): TransformNode; /** - * Adds the passed mesh as a child to the current mesh - * @param mesh defines the child mesh - * @returns the current mesh + * Defines the passed node as the parent of the current node. + * The node will remain exactly where it is and its position / rotation will be updated accordingly + * Returns the TransformNode. */ - addChild(mesh: AbstractMesh): AbstractMesh; + setParent(node: Nullable): TransformNode; + private _nonUniformScaling; + readonly nonUniformScaling: boolean; + _updateNonUniformScalingState(value: boolean): boolean; /** - * Removes the passed mesh from the current mesh children list - * @param mesh defines the child mesh - * @returns the current mesh + * Attach the current TransformNode to another TransformNode associated with a bone + * @param bone Bone affecting the TransformNode + * @param affectedTransformNode TransformNode associated with the bone */ - removeChild(mesh: AbstractMesh): AbstractMesh; - /** @hidden */ - private _initFacetData(); + attachToBone(bone: Bone, affectedTransformNode: TransformNode): TransformNode; + detachFromBone(): TransformNode; + private static _rotationAxisCache; /** - * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated. - * This method can be called within the render loop. - * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation - * @returns the current mesh - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space. + * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD. + * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. + * The passed axis is also normalized. + * Returns the TransformNode. */ - updateFacetData(): AbstractMesh; + rotate(axis: Vector3, amount: number, space?: Space): TransformNode; /** - * Returns the facetLocalNormals array. - * The normals are expressed in the mesh local spac - * @returns an array of Vector3 - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space. + * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. + * The passed axis is also normalized. + * Returns the TransformNode. + * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm */ - getFacetLocalNormals(): Vector3[]; + rotateAround(point: Vector3, axis: Vector3, amount: number): TransformNode; /** - * Returns the facetLocalPositions array. - * The facet positions are expressed in the mesh local space - * @returns an array of Vector3 - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Translates the mesh along the axis vector for the passed distance in the given space. + * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD. + * Returns the TransformNode. */ - getFacetLocalPositions(): Vector3[]; + translate(axis: Vector3, distance: number, space?: Space): TransformNode; /** - * Returns the facetLocalPartioning array - * @returns an array of array of numbers - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Adds a rotation step to the mesh current rotation. + * x, y, z are Euler angles expressed in radians. + * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set. + * This means this rotation is made in the mesh local space only. + * It's useful to set a custom rotation order different from the BJS standard one YXZ. + * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis. + * ```javascript + * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3); + * ``` + * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values. + * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles. + * Returns the TransformNode. */ - getFacetLocalPartitioning(): number[][]; + addRotation(x: number, y: number, z: number): TransformNode; /** - * Returns the i-th facet position in the world system. - * This method allocates a new Vector3 per call - * @param i defines the facet index - * @returns a new Vector3 - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Computes the mesh World matrix and returns it. + * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values. + * If the parameter `force` is let to `false` (default), the current cached World matrix is returned. + * If the parameter `force`is set to `true`, the actual computation is done. + * Returns the mesh World Matrix. */ - getFacetPosition(i: number): Vector3; + computeWorldMatrix(force?: boolean): Matrix; + protected _afterComputeWorldMatrix(): void; /** - * Sets the reference Vector3 with the i-th facet position in the world system - * @param i defines the facet index - * @param ref defines the target vector - * @returns the current mesh - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * If you'd like to be called back after the mesh position, rotation or scaling has been updated. + * @param func: callback function to add + * + * Returns the TransformNode. + */ + registerAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode; + /** + * Removes a registered callback function. + * Returns the TransformNode. */ - getFacetPositionToRef(i: number, ref: Vector3): AbstractMesh; + unregisterAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode; /** - * Returns the i-th facet normal in the world system. - * This method allocates a new Vector3 per call - * @param i defines the facet index - * @returns a new Vector3 - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Clone the current transform node + * Returns the new transform node + * @param name Name of the new clone + * @param newParent New parent for the clone + * @param doNotCloneChildren Do not clone children hierarchy */ - getFacetNormal(i: number): Vector3; + clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable; + serialize(currentSerializationObject?: any): any; /** - * Sets the reference Vector3 with the i-th facet normal in the world system - * @param i defines the facet index - * @param ref defines the target vector - * @returns the current mesh - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Returns a new TransformNode object parsed from the source provided. + * The parameter `parsedMesh` is the source. + * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with */ - getFacetNormalToRef(i: number, ref: Vector3): this; + static Parse(parsedTransformNode: any, scene: Scene, rootUrl: string): TransformNode; /** - * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system) - * @param x defines x coordinate - * @param y defines y coordinate - * @param z defines z coordinate - * @returns the array of facet indexes - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * Releases resources associated with this transform node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) */ - getFacetsAtLocalCoordinates(x: number, y: number, z: number): Nullable; + dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; + } +} + +declare module BABYLON { + class VertexBuffer { + /** @hidden */ + _buffer: Buffer; + private _kind; + private _size; + private _ownsBuffer; + private _instanced; + private _instanceDivisor; /** - * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found - * @param projected sets as the (x,y,z) world projection on the facet - * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned - * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position - * @param x defines x coordinate - * @param y defines y coordinate - * @param z defines z coordinate - * @returns the face index if found (or null instead) - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * The byte type. */ - getClosestFacetAtCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace?: boolean, facing?: boolean): Nullable; + static readonly BYTE: number; /** - * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found - * @param projected sets as the (x,y,z) local projection on the facet - * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned - * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position - * @param x defines x coordinate - * @param y defines y coordinate - * @param z defines z coordinate - * @returns the face index if found (or null instead) - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * The unsigned byte type. */ - getClosestFacetAtLocalCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace?: boolean, facing?: boolean): Nullable; + static readonly UNSIGNED_BYTE: number; /** - * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals() - * @returns the parameters - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * The short type. */ - getFacetDataParameters(): any; + static readonly SHORT: number; /** - * Disables the feature FacetData and frees the related memory - * @returns the current mesh - * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata + * The unsigned short type. */ - disableFacetData(): AbstractMesh; + static readonly UNSIGNED_SHORT: number; /** - * Updates the AbstractMesh indices array - * @param indices defines the data source - * @returns the current mesh + * The integer type. */ - updateIndices(indices: IndicesArray): AbstractMesh; + static readonly INT: number; /** - * Creates new normals data for the mesh - * @param updatable defines if the normal vertex buffer must be flagged as updatable - * @returns the current mesh + * The unsigned integer type. */ - createNormals(updatable: boolean): AbstractMesh; + static readonly UNSIGNED_INT: number; /** - * Align the mesh with a normal - * @param normal defines the normal to use - * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default) - * @returns the current mesh + * The float type. */ - alignWithNormal(normal: Vector3, upDirection?: Vector3): AbstractMesh; - /** @hidden */ - _checkOcclusionQuery(): void; - } -} - -declare module BABYLON { - class Buffer { - private _engine; - private _buffer; - /** @hidden */ - _data: Nullable; - private _updatable; - private _instanced; + static readonly FLOAT: number; + /** + * Gets or sets the instance divisor when in instanced mode + */ + instanceDivisor: number; /** * Gets the byte stride. */ readonly byteStride: number; + /** + * Gets the byte offset. + */ + readonly byteOffset: number; + /** + * Gets whether integer data values should be normalized into a certain range when being casted to a float. + */ + readonly normalized: boolean; + /** + * Gets the data type of each component in the array. + */ + readonly type: number; /** * Constructor * @param engine the engine - * @param data the data to use for this buffer + * @param data the data to use for this vertex buffer + * @param kind the vertex buffer kind * @param updatable whether the data is updatable - * @param stride the stride (optional) * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional) + * @param stride the stride (optional) * @param instanced whether the buffer is instanced (optional) - * @param useBytes set to true if the stride in in bytes (optional) + * @param offset the offset of the data (optional) + * @param size the number of components (optional) + * @param type the type of the component (optional) + * @param normalized whether the data contains normalized data (optional) + * @param useBytes set to true if stride and offset are in bytes (optional) */ - constructor(engine: any, data: DataArray, updatable: boolean, stride?: number, postponeInternalCreation?: boolean, instanced?: boolean, useBytes?: boolean); + constructor(engine: any, data: DataArray | Buffer, kind: string, updatable: boolean, postponeInternalCreation?: boolean, stride?: number, instanced?: boolean, offset?: number, size?: number, type?: number, normalized?: boolean, useBytes?: boolean); + _rebuild(): void; /** - * Create a new {BABYLON.VertexBuffer} based on the current buffer - * @param kind defines the vertex buffer kind (position, normal, etc.) - * @param offset defines offset in the buffer (0 by default) - * @param size defines the size in floats of attributes (position is 3 for instance) - * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved) - * @param instanced defines if the vertex buffer contains indexed data - * @param useBytes defines if the offset and stride are in bytes - * @returns the new vertex buffer + * Returns the kind of the VertexBuffer (string). */ - createVertexBuffer(kind: string, offset: number, size: number, stride?: number, instanced?: boolean, useBytes?: boolean): VertexBuffer; - isUpdatable(): boolean; - getData(): Nullable; - getBuffer(): Nullable; + getKind(): string; /** - * Gets the stride in float32 units (i.e. byte stride / 4). - * May not be an integer if the byte stride is not divisible by 4. - * DEPRECATED. Use byteStride instead. - * @returns the stride in float32 units + * Boolean : is the VertexBuffer updatable ? */ - getStrideSize(): number; - create(data?: Nullable): void; - _rebuild(): void; - update(data: DataArray): void; + isUpdatable(): boolean; /** - * Updates the data directly. - * @param data the new data - * @param offset the new offset - * @param vertexCount the vertex count (optional) - * @param useBytes set to true if the offset is in bytes + * Returns an array of numbers or a typed array containing the VertexBuffer data. */ - updateDirectly(data: DataArray, offset: number, vertexCount?: number, useBytes?: boolean): void; - dispose(): void; - } -} - -declare module BABYLON { - class CSG { - private polygons; - matrix: Matrix; - position: Vector3; - rotation: Vector3; - rotationQuaternion: Nullable; - scaling: Vector3; - static FromMesh(mesh: Mesh): CSG; - private static FromPolygons(polygons); - clone(): CSG; - union(csg: CSG): CSG; - unionInPlace(csg: CSG): void; - subtract(csg: CSG): CSG; - subtractInPlace(csg: CSG): void; - intersect(csg: CSG): CSG; - intersectInPlace(csg: CSG): void; - inverse(): CSG; - inverseInPlace(): void; - copyTransformAttributes(csg: CSG): CSG; - buildMeshGeometry(name: string, scene: Scene, keepSubMeshes: boolean): Mesh; - toMesh(name: string, material: Nullable, scene: Scene, keepSubMeshes: boolean): Mesh; - } -} - -declare module BABYLON { - /** - * Class used to store geometry data (vertex buffers + index buffer) - */ - class Geometry implements IGetSetVerticesData { + getData(): Nullable; /** - * Gets or sets the unique ID of the geometry + * Returns the WebGLBuffer associated to the VertexBuffer. */ - id: string; + getBuffer(): Nullable; /** - * Gets the delay loading state of the geometry (none by default which means not delayed) + * Returns the stride as a multiple of the type byte length. + * DEPRECATED. Use byteStride instead. */ - delayLoadState: number; + getStrideSize(): number; /** - * Gets the file containing the data to load when running in delay load state + * Returns the offset as a multiple of the type byte length. + * DEPRECATED. Use byteOffset instead. */ - delayLoadingFile: Nullable; + getOffset(): number; /** - * Callback called when the geometry is updated + * Returns the number of components per vertex attribute (integer). */ - onGeometryUpdated: (geometry: Geometry, kind?: string) => void; - private _scene; - private _engine; - private _meshes; - private _totalVertices; - /** @hidden */ - _indices: IndicesArray; - /** @hidden */ - _vertexBuffers: { - [key: string]: VertexBuffer; - }; - private _isDisposed; - private _extend; - private _boundingBias; - /** @hidden */ - _delayInfo: Array; - private _indexBuffer; - private _indexBufferIsUpdatable; - /** @hidden */ - _boundingInfo: Nullable; - /** @hidden */ - _delayLoadingFunction: Nullable<(any: any, geometry: Geometry) => void>; - /** @hidden */ - _softwareSkinningRenderId: number; - private _vertexArrayObjects; - private _updatable; - /** @hidden */ - _positions: Nullable; + getSize(): number; /** - * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y + * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ? */ + getIsInstanced(): boolean; /** - * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y + * Returns the instancing divisor, zero for non-instanced (integer). */ - boundingBias: Vector2; + getInstanceDivisor(): number; /** - * Static function used to attach a new empty geometry to a mesh - * @param mesh defines the mesh to attach the geometry to - * @returns the new {BABYLON.Geometry} + * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array. + * Returns the created WebGLBuffer. */ - static CreateGeometryForMesh(mesh: Mesh): Geometry; + create(data?: DataArray): void; /** - * Creates a new geometry - * @param id defines the unique ID - * @param scene defines the hosting scene - * @param vertexData defines the {BABYLON.VertexData} used to get geometry data - * @param updatable defines if geometry must be updatable (false by default) - * @param mesh defines the mesh that will be associated with the geometry + * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array. + * This function will create a new buffer if the current one is not updatable + * Returns the updated WebGLBuffer. */ - constructor(id: string, scene: Scene, vertexData?: VertexData, updatable?: boolean, mesh?: Nullable); + update(data: DataArray): void; /** - * Gets the current extend of the geometry + * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array. + * Returns the directly updated WebGLBuffer. + * @param data the new data + * @param offset the new offset + * @param useBytes set to true if the offset is in bytes */ - readonly extend: { - minimum: Vector3; - maximum: Vector3; - }; + updateDirectly(data: DataArray, offset: number, useBytes?: boolean): void; /** - * Gets the hosting scene - * @returns the hosting {BABYLON.Scene} + * Disposes the VertexBuffer and the underlying WebGLBuffer. */ - getScene(): Scene; + dispose(): void; /** - * Gets the hosting engine - * @returns the hosting {BABYLON.Engine} + * Enumerates each value of this vertex buffer as numbers. + * @param count the number of values to enumerate + * @param callback the callback function called for each value */ - getEngine(): Engine; + forEach(count: number, callback: (value: number, index: number) => void): void; + private static _PositionKind; + private static _NormalKind; + private static _TangentKind; + private static _UVKind; + private static _UV2Kind; + private static _UV3Kind; + private static _UV4Kind; + private static _UV5Kind; + private static _UV6Kind; + private static _ColorKind; + private static _MatricesIndicesKind; + private static _MatricesWeightsKind; + private static _MatricesIndicesExtraKind; + private static _MatricesWeightsExtraKind; + static readonly PositionKind: string; + static readonly NormalKind: string; + static readonly TangentKind: string; + static readonly UVKind: string; + static readonly UV2Kind: string; + static readonly UV3Kind: string; + static readonly UV4Kind: string; + static readonly UV5Kind: string; + static readonly UV6Kind: string; + static readonly ColorKind: string; + static readonly MatricesIndicesKind: string; + static readonly MatricesWeightsKind: string; + static readonly MatricesIndicesExtraKind: string; + static readonly MatricesWeightsExtraKind: string; /** - * Defines if the geometry is ready to use - * @returns true if the geometry is ready to be used + * Deduces the stride given a kind. + * @param kind The kind string to deduce + * @returns The deduced stride */ - isReady(): boolean; + static DeduceStride(kind: string): number; /** - * Gets a value indicating that the geometry should not be serialized + * Gets the byte length of the given type. + * @param type the type + * @returns the number of bytes */ - readonly doNotSerialize: boolean; - /** @hidden */ - _rebuild(): void; + static GetTypeByteLength(type: number): number; /** - * Affects all geometry data in one call - * @param vertexData defines the geometry data - * @param updatable defines if the geometry must be flagged as updatable (false as default) + * Enumerates each value of the given parameters as numbers. + * @param data the data to enumerate + * @param byteOffset the byte offset of the data + * @param byteStride the byte stride of the data + * @param componentCount the number of components per element + * @param componentType the type of the component + * @param count the total number of components + * @param normalized whether the data is normalized + * @param callback the callback function called for each value */ - setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; + static ForEach(data: DataArray, byteOffset: number, byteStride: number, componentCount: number, componentType: number, count: number, normalized: boolean, callback: (value: number, index: number) => void): void; + private static _GetFloatValue; + } +} + +declare module BABYLON { + interface PhysicsImpostorJoint { + mainImpostor: PhysicsImpostor; + connectedImpostor: PhysicsImpostor; + joint: PhysicsJoint; + } + class PhysicsEngine { + private _physicsPlugin; + gravity: Vector3; + constructor(gravity: Nullable, _physicsPlugin?: IPhysicsEnginePlugin); + setGravity(gravity: Vector3): void; /** - * Set specific vertex data - * @param kind defines the data kind (Position, normal, etc...) - * @param data defines the vertex data to use - * @param updatable defines if the vertex must be flagged as updatable (false as default) - * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified + * Set the time step of the physics engine. + * default is 1/60. + * To slow it down, enter 1/600 for example. + * To speed it up, 1/30 + * @param {number} newTimeStep the new timestep to apply to this world. */ - setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): void; + setTimeStep(newTimeStep?: number): void; /** - * Removes a specific vertex data - * @param kind defines the data kind (Position, normal, etc...) + * Get the time step of the physics engine. */ - removeVerticesData(kind: string): void; + getTimeStep(): number; + dispose(): void; + getPhysicsPluginName(): string; + static Epsilon: number; + private _impostors; + private _joints; /** - * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data - * @param buffer defines the vertex buffer to use - * @param totalVertices defines the total number of vertices for position kind (could be null) + * Adding a new impostor for the impostor tracking. + * This will be done by the impostor itself. + * @param {PhysicsImpostor} impostor the impostor to add */ - setVerticesBuffer(buffer: VertexBuffer, totalVertices?: Nullable): void; + addImpostor(impostor: PhysicsImpostor): void; /** - * Update a specific vertex buffer - * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array - * It will do nothing if the buffer is not updatable - * @param kind defines the data kind (Position, normal, etc...) - * @param data defines the data to use - * @param offset defines the offset in the target buffer where to store the data - * @param useBytes set to true if the offset is in bytes + * Remove an impostor from the engine. + * This impostor and its mesh will not longer be updated by the physics engine. + * @param {PhysicsImpostor} impostor the impostor to remove */ - updateVerticesDataDirectly(kind: string, data: DataArray, offset: number, useBytes?: boolean): void; + removeImpostor(impostor: PhysicsImpostor): void; /** - * Update a specific vertex buffer - * This function will create a new buffer if the current one is not updatable - * @param kind defines the data kind (Position, normal, etc...) - * @param data defines the data to use - * @param updateExtends defines if the geometry extends must be recomputed (false by default) + * Add a joint to the physics engine + * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added. + * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint + * @param {PhysicsJoint} the joint that will connect both impostors. */ - updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean): void; - private _updateBoundingInfo(updateExtends, data); - /** @hidden */ - _bind(effect: Nullable, indexToBind?: Nullable): void; + addJoint(mainImpostor: PhysicsImpostor, connectedImpostor: PhysicsImpostor, joint: PhysicsJoint): void; + removeJoint(mainImpostor: PhysicsImpostor, connectedImpostor: PhysicsImpostor, joint: PhysicsJoint): void; /** - * Gets total number of vertices - * @returns the total number of vertices + * Called by the scene. no need to call it. */ - getTotalVertices(): number; + _step(delta: number): void; + getPhysicsPlugin(): IPhysicsEnginePlugin; + getImpostors(): Array; + getImpostorForPhysicsObject(object: IPhysicsEnabledObject): Nullable; + getImpostorWithPhysicsBody(body: any): Nullable; + } + interface IPhysicsEnginePlugin { + world: any; + name: string; + setGravity(gravity: Vector3): void; + setTimeStep(timeStep: number): void; + getTimeStep(): number; + executeStep(delta: number, impostors: Array): void; + applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3): void; + applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3): void; + generatePhysicsBody(impostor: PhysicsImpostor): void; + removePhysicsBody(impostor: PhysicsImpostor): void; + generateJoint(joint: PhysicsImpostorJoint): void; + removeJoint(joint: PhysicsImpostorJoint): void; + isSupported(): boolean; + setTransformationFromPhysicsBody(impostor: PhysicsImpostor): void; + setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion): void; + setLinearVelocity(impostor: PhysicsImpostor, velocity: Nullable): void; + setAngularVelocity(impostor: PhysicsImpostor, velocity: Nullable): void; + getLinearVelocity(impostor: PhysicsImpostor): Nullable; + getAngularVelocity(impostor: PhysicsImpostor): Nullable; + setBodyMass(impostor: PhysicsImpostor, mass: number): void; + getBodyMass(impostor: PhysicsImpostor): number; + getBodyFriction(impostor: PhysicsImpostor): number; + setBodyFriction(impostor: PhysicsImpostor, friction: number): void; + getBodyRestitution(impostor: PhysicsImpostor): number; + setBodyRestitution(impostor: PhysicsImpostor, restitution: number): void; + sleepBody(impostor: PhysicsImpostor): void; + wakeUpBody(impostor: PhysicsImpostor): void; + updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number): void; + setMotor(joint: IMotorEnabledJoint, speed: number, maxForce?: number, motorIndex?: number): void; + setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number, motorIndex?: number): void; + getRadius(impostor: PhysicsImpostor): number; + getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void; + syncMeshWithImpostor(mesh: AbstractMesh, impostor: PhysicsImpostor): void; + dispose(): void; + } +} + +declare module BABYLON { + class PhysicsHelper { + private _scene; + private _physicsEngine; + constructor(scene: Scene); /** - * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly. - * @param kind defines the data kind (Position, normal, etc...) - * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes - * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it - * @returns a float array containing vertex data + * @param {Vector3} origin the origin of the explosion + * @param {number} radius the explosion radius + * @param {number} strength the explosion strength + * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant */ - getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable; + applyRadialExplosionImpulse(origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff): Nullable; /** - * Returns a boolean defining if the vertex data for the requested `kind` is updatable - * @param kind defines the data kind (Position, normal, etc...) - * @returns true if the vertex buffer with the specified kind is updatable + * @param {Vector3} origin the origin of the explosion + * @param {number} radius the explosion radius + * @param {number} strength the explosion strength + * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant */ - isVertexBufferUpdatable(kind: string): boolean; + applyRadialExplosionForce(origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff): Nullable; /** - * Gets a specific vertex buffer - * @param kind defines the data kind (Position, normal, etc...) - * @returns a {BABYLON.VertexBuffer} + * @param {Vector3} origin the origin of the explosion + * @param {number} radius the explosion radius + * @param {number} strength the explosion strength + * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant */ - getVertexBuffer(kind: string): Nullable; + gravitationalField(origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff): Nullable; /** - * Returns all vertex buffers - * @return an object holding all vertex buffers indexed by kind + * @param {Vector3} origin the origin of the updraft + * @param {number} radius the radius of the updraft + * @param {number} strength the strength of the updraft + * @param {number} height the height of the updraft + * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center */ - getVertexBuffers(): Nullable<{ - [key: string]: VertexBuffer; - }>; + updraft(origin: Vector3, radius: number, strength: number, height: number, updraftMode?: PhysicsUpdraftMode): Nullable; /** - * Gets a boolean indicating if specific vertex buffer is present - * @param kind defines the data kind (Position, normal, etc...) - * @returns true if data is present + * @param {Vector3} origin the of the vortex + * @param {number} radius the radius of the vortex + * @param {number} strength the strength of the vortex + * @param {number} height the height of the vortex */ - isVerticesDataPresent(kind: string): boolean; + vortex(origin: Vector3, radius: number, strength: number, height: number): Nullable; + } + /***** Radial explosion *****/ + class PhysicsRadialExplosionEvent { + private _scene; + private _sphere; + private _sphereOptions; + private _rays; + private _dataFetched; + constructor(scene: Scene); /** - * Gets a list of all attached data kinds (Position, normal, etc...) - * @returns a list of string containing all kinds + * Returns the data related to the radial explosion event (sphere & rays). + * @returns {PhysicsRadialExplosionEventData} */ - getVerticesDataKinds(): string[]; + getData(): PhysicsRadialExplosionEventData; /** - * Update index buffer - * @param indices defines the indices to store in the index buffer - * @param offset defines the offset in the target buffer where to store the data + * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse. + * @param impostor + * @param {Vector3} origin the origin of the explosion + * @param {number} radius the explosion radius + * @param {number} strength the explosion strength + * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear + * @returns {Nullable} */ - updateIndices(indices: IndicesArray, offset?: number): void; + getImpostorForceAndContactPoint(impostor: PhysicsImpostor, origin: Vector3, radius: number, strength: number, falloff: PhysicsRadialImpulseFalloff): Nullable; /** - * Creates a new index buffer - * @param indices defines the indices to store in the index buffer - * @param totalVertices defines the total number of vertices (could be null) - * @param updatable defines if the index buffer must be flagged as updatable (false by default) + * Disposes the sphere. + * @param {bolean} force */ - setIndices(indices: IndicesArray, totalVertices?: Nullable, updatable?: boolean): void; + dispose(force?: boolean): void; + /*** Helpers ***/ + private _prepareSphere; + private _intersectsWithSphere; + } + /***** Gravitational Field *****/ + class PhysicsGravitationalFieldEvent { + private _physicsHelper; + private _scene; + private _origin; + private _radius; + private _strength; + private _falloff; + private _tickCallback; + private _sphere; + private _dataFetched; + constructor(physicsHelper: PhysicsHelper, scene: Scene, origin: Vector3, radius: number, strength: number, falloff?: PhysicsRadialImpulseFalloff); /** - * Return the total number of indices - * @returns the total number of indices + * Returns the data related to the gravitational field event (sphere). + * @returns {PhysicsGravitationalFieldEventData} */ - getTotalIndices(): number; + getData(): PhysicsGravitationalFieldEventData; /** - * Gets the index buffer array - * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes - * @returns the index buffer array + * Enables the gravitational field. */ - getIndices(copyWhenShared?: boolean): Nullable; + enable(): void; /** - * Gets the index buffer - * @return the index buffer + * Disables the gravitational field. */ - getIndexBuffer(): Nullable; - /** @hidden */ - _releaseVertexArrayObject(effect?: Nullable): void; + disable(): void; /** - * Release the associated resources for a specific mesh - * @param mesh defines the source mesh - * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it + * Disposes the sphere. + * @param {bolean} force */ - releaseForMesh(mesh: Mesh, shouldDispose?: boolean): void; + dispose(force?: boolean): void; + private _tick; + } + /***** Updraft *****/ + class PhysicsUpdraftEvent { + private _scene; + private _origin; + private _radius; + private _strength; + private _height; + private _updraftMode; + private _physicsEngine; + private _originTop; + private _originDirection; + private _tickCallback; + private _cylinder; + private _cylinderPosition; + private _dataFetched; + constructor(_scene: Scene, _origin: Vector3, _radius: number, _strength: number, _height: number, _updraftMode: PhysicsUpdraftMode); /** - * Apply current geometry to a given mesh - * @param mesh defines the mesh to apply geometry to + * Returns the data related to the updraft event (cylinder). + * @returns {PhysicsUpdraftEventData} */ - applyToMesh(mesh: Mesh): void; - private _updateExtend(data?); - private _applyToMesh(mesh); - private notifyUpdate(kind?); + getData(): PhysicsUpdraftEventData; /** - * Load the geometry if it was flagged as delay loaded - * @param scene defines the hosting scene - * @param onLoaded defines a callback called when the geometry is loaded + * Enables the updraft. */ - load(scene: Scene, onLoaded?: () => void): void; - private _queueLoad(scene, onLoaded?); + enable(): void; /** - * Invert the geometry to move from a right handed system to a left handed one. + * Disables the cortex. */ - toLeftHanded(): void; - /** @hidden */ - _resetPointsArrayCache(): void; - /** @hidden */ - _generatePointsArray(): boolean; + disable(): void; /** - * Gets a value indicating if the geometry is disposed - * @returns true if the geometry was disposed + * Disposes the sphere. + * @param {bolean} force */ - isDisposed(): boolean; - private _disposeVertexArrayObjects(); + dispose(force?: boolean): void; + private getImpostorForceAndContactPoint; + private _tick; + /*** Helpers ***/ + private _prepareCylinder; + private _intersectsWithCylinder; + } + /***** Vortex *****/ + class PhysicsVortexEvent { + private _scene; + private _origin; + private _radius; + private _strength; + private _height; + private _physicsEngine; + private _originTop; + private _centripetalForceThreshold; + private _updraftMultiplier; + private _tickCallback; + private _cylinder; + private _cylinderPosition; + private _dataFetched; + constructor(_scene: Scene, _origin: Vector3, _radius: number, _strength: number, _height: number); /** - * Free all associated resources + * Returns the data related to the vortex event (cylinder). + * @returns {PhysicsVortexEventData} */ - dispose(): void; + getData(): PhysicsVortexEventData; /** - * Clone the current geometry into a new geometry - * @param id defines the unique ID of the new geometry - * @returns a new geometry object + * Enables the vortex. */ - copy(id: string): Geometry; + enable(): void; /** - * Serialize the current geometry info (and not the vertices data) into a JSON object - * @return a JSON representation of the current geometry data (without the vertices data) + * Disables the cortex. */ - serialize(): any; - private toNumberArray(origin); + disable(): void; /** - * Serialize all vertices data into a JSON oject - * @returns a JSON representation of the current geometry data + * Disposes the sphere. + * @param {bolean} force */ - serializeVerticeData(): any; + dispose(force?: boolean): void; + private getImpostorForceAndContactPoint; + private _tick; + /*** Helpers ***/ + private _prepareCylinder; + private _intersectsWithCylinder; + } + /***** Enums *****/ + /** + * The strenght of the force in correspondence to the distance of the affected object + */ + enum PhysicsRadialImpulseFalloff { + /** Defines that impulse is constant in strength across it's whole radius */ + Constant = 0, + /** DEfines that impulse gets weaker if it's further from the origin */ + Linear = 1 + } + /** + * The strenght of the force in correspondence to the distance of the affected object + */ + enum PhysicsUpdraftMode { + /** Defines that the upstream forces will pull towards the top center of the cylinder */ + Center = 0, + /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */ + Perpendicular = 1 + } + /***** Data interfaces *****/ + interface PhysicsForceAndContactPoint { + force: Vector3; + contactPoint: Vector3; + } + interface PhysicsRadialExplosionEventData { + sphere: Mesh; + rays: Array; + } + interface PhysicsGravitationalFieldEventData { + sphere: Mesh; + } + interface PhysicsUpdraftEventData { + cylinder: Mesh; + } + interface PhysicsVortexEventData { + cylinder: Mesh; + } +} + +declare module BABYLON { + interface PhysicsImpostorParameters { + mass: number; + friction?: number; + restitution?: number; + nativeOptions?: any; + ignoreParent?: boolean; + disableBidirectionalTransformation?: boolean; + } + interface IPhysicsEnabledObject { + position: Vector3; + rotationQuaternion: Nullable; + scaling: Vector3; + rotation?: Vector3; + parent?: any; + getBoundingInfo(): BoundingInfo; + computeWorldMatrix(force: boolean): Matrix; + getWorldMatrix?(): Matrix; + getChildMeshes?(directDescendantsOnly?: boolean): Array; + getVerticesData(kind: string): Nullable | Float32Array>; + getIndices?(): Nullable; + getScene?(): Scene; + getAbsolutePosition(): Vector3; + getAbsolutePivotPoint(): Vector3; + rotate(axis: Vector3, amount: number, space?: Space): TransformNode; + translate(axis: Vector3, distance: number, space?: Space): TransformNode; + setAbsolutePosition(absolutePosition: Vector3): TransformNode; + getClassName(): string; + } + class PhysicsImpostor { + object: IPhysicsEnabledObject; + type: number; + private _options; + private _scene?; + static DEFAULT_OBJECT_SIZE: Vector3; + static IDENTITY_QUATERNION: Quaternion; + private _physicsEngine; + private _physicsBody; + private _bodyUpdateRequired; + private _onBeforePhysicsStepCallbacks; + private _onAfterPhysicsStepCallbacks; + private _onPhysicsCollideCallbacks; + private _deltaPosition; + private _deltaRotation; + private _deltaRotationConjugated; + private _parent; + private _isDisposed; + private static _tmpVecs; + private static _tmpQuat; + readonly isDisposed: boolean; + mass: number; + friction: number; + restitution: number; + uniqueId: number; + private _joints; + constructor(object: IPhysicsEnabledObject, type: number, _options?: PhysicsImpostorParameters, _scene?: Scene | undefined); /** - * Extracts a clone of a mesh geometry - * @param mesh defines the source mesh - * @param id defines the unique ID of the new geometry object - * @returns the new geometry object + * This function will completly initialize this impostor. + * It will create a new body - but only if this mesh has no parent. + * If it has, this impostor will not be used other than to define the impostor + * of the child mesh. */ - static ExtractFromMesh(mesh: Mesh, id: string): Nullable; + _init(): void; + private _getPhysicsParent; /** - * You should now use Tools.RandomId(), this method is still here for legacy reasons. - * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 - * Be aware Math.random() could cause collisions, but: - * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide" - * @returns a string containing a new GUID + * Should a new body be generated. */ - static RandomId(): string; - /** @hidden */ - static _ImportGeometry(parsedGeometry: any, mesh: Mesh): void; - private static _CleanMatricesWeights(parsedGeometry, mesh); + isBodyInitRequired(): boolean; + setScalingUpdated(updated: boolean): void; /** - * Create a new geometry from persisted data (Using .babylon file format) - * @param parsedVertexData defines the persisted data - * @param scene defines the hosting scene - * @param rootUrl defines the root url to use to load assets (like delayed data) - * @returns the new geometry object + * Force a regeneration of this or the parent's impostor's body. + * Use under cautious - This will remove all joints already implemented. */ - static Parse(parsedVertexData: any, scene: Scene, rootUrl: string): Nullable; - } - /** - * Abstract class used to provide common services for all typed geometries - * @hidden - */ - class _PrimitiveGeometry extends Geometry { - private _canBeRegenerated; - private _beingRegenerated; + forceUpdate(): void; /** - * Creates a new typed geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) + * Gets the body that holds this impostor. Either its own, or its parent. */ - constructor(id: string, scene: Scene, _canBeRegenerated?: boolean, mesh?: Nullable); /** - * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default) - * @returns true if the geometry can be regenerated - */ - canBeRegenerated(): boolean; + * Set the physics body. Used mainly by the physics engine/plugin + */ + physicsBody: any; + parent: Nullable; + resetUpdateFlags(): void; + getObjectExtendSize(): Vector3; + getObjectCenter(): Vector3; /** - * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values + * Get a specific parametes from the options parameter. */ - regenerate(): void; + getParam(paramName: string): any; /** - * Clone the geometry - * @param id defines the unique ID of the new geometry - * @returns the new geometry + * Sets a specific parameter in the options given to the physics plugin */ - asNewGeometry(id: string): Geometry; - setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; - setVerticesData(kind: string, data: FloatArray, updatable?: boolean): void; - /** @hidden */ - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - } - /** - * Creates a ribbon geometry - * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons - */ - class RibbonGeometry extends _PrimitiveGeometry { + setParam(paramName: string, value: number): void; /** - * Defines the array of paths to use + * Specifically change the body's mass option. Won't recreate the physics body object */ - pathArray: Vector3[][]; + setMass(mass: number): void; + getLinearVelocity(): Nullable; + setLinearVelocity(velocity: Nullable): void; + getAngularVelocity(): Nullable; + setAngularVelocity(velocity: Nullable): void; /** - * Defines if the last and first points of each path in your pathArray must be joined + * Execute a function with the physics plugin native code. + * Provide a function the will have two variables - the world object and the physics body object. */ - closeArray: boolean; + executeNativeFunction(func: (world: any, physicsBody: any) => void): void; /** - * Defines if the last and first points of each path in your pathArray must be joined + * Register a function that will be executed before the physics world is stepping forward. */ - closePath: boolean; + registerBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void; + unregisterBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void; /** - * Defines the offset between points + * Register a function that will be executed after the physics step */ - offset: number; + registerAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void; + unregisterAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * register a function that will be executed when this impostor collides against a different body. */ - side: number; + registerOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor) => void): void; + unregisterOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor | Array) => void): void; + private _tmpQuat; + private _tmpQuat2; + getParentsRotation(): Quaternion; /** - * Creates a ribbon geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param pathArray defines the array of paths to use - * @param closeArray defines if the last path and the first path must be joined - * @param closePath defines if the last and first points of each path in your pathArray must be joined - * @param offset defines the offset between points - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * this function is executed by the physics engine. */ - constructor(id: string, scene: Scene, - /** - * Defines the array of paths to use - */ - pathArray: Vector3[][], - /** - * Defines if the last and first points of each path in your pathArray must be joined - */ - closeArray: boolean, - /** - * Defines if the last and first points of each path in your pathArray must be joined - */ - closePath: boolean, - /** - * Defines the offset between points - */ - offset: number, canBeRegenerated?: boolean, mesh?: Mesh, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - /** @hidden */ - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - } - /** - * Creates a box geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#box - */ - class BoxGeometry extends _PrimitiveGeometry { + beforeStep: () => void; /** - * Defines the zise of the box (width, height and depth are the same) + * this function is executed by the physics engine. */ - size: number; + afterStep: () => void; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Legacy collision detection event support */ - side: number; + onCollideEvent: Nullable<(collider: PhysicsImpostor, collidedWith: PhysicsImpostor) => void>; + onCollide: (e: { + body: any; + }) => void; /** - * Creates a box geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param size defines the zise of the box (width, height and depth are the same) - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Apply a force */ - constructor(id: string, scene: Scene, - /** - * Defines the zise of the box (width, height and depth are the same) - */ - size: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedBox: any, scene: Scene): Nullable; - } - /** - * Creates a sphere geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere - */ - class SphereGeometry extends _PrimitiveGeometry { + applyForce(force: Vector3, contactPoint: Vector3): PhysicsImpostor; /** - * Defines the number of segments to use to create the sphere + * Apply an impulse */ - segments: number; + applyImpulse(force: Vector3, contactPoint: Vector3): PhysicsImpostor; /** - * Defines the diameter of the sphere + * A help function to create a joint. */ - diameter: number; + createJoint(otherImpostor: PhysicsImpostor, jointType: number, jointData: PhysicsJointData): PhysicsImpostor; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Add a joint to this impostor with a different impostor. */ - side: number; + addJoint(otherImpostor: PhysicsImpostor, joint: PhysicsJoint): PhysicsImpostor; /** - * Create a new sphere geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param segments defines the number of segments to use to create the sphere - * @param diameter defines the diameter of the sphere - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Will keep this body still, in a sleep mode. */ - constructor(id: string, scene: Scene, - /** - * Defines the number of segments to use to create the sphere - */ - segments: number, - /** - * Defines the diameter of the sphere - */ - diameter: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedSphere: any, scene: Scene): Nullable; - } - /** - * Creates a disc geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon - */ - class DiscGeometry extends _PrimitiveGeometry { + sleep(): PhysicsImpostor; /** - * Defines the radius of the disc + * Wake the body up. */ - radius: number; + wakeUp(): PhysicsImpostor; + clone(newObject: IPhysicsEnabledObject): Nullable; + dispose(): void; + setDeltaPosition(position: Vector3): void; + setDeltaRotation(rotation: Quaternion): void; + getBoxSizeToRef(result: Vector3): PhysicsImpostor; + getRadius(): number; /** - * Defines the tesselation factor to apply to the disc + * Sync a bone with this impostor + * @param bone The bone to sync to the impostor. + * @param boneMesh The mesh that the bone is influencing. + * @param jointPivot The pivot of the joint / bone in local space. + * @param distToJoint Optional distance from the impostor to the joint. + * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. */ - tessellation: number; + syncBoneWithImpostor(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion): void; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Sync impostor to a bone + * @param bone The bone that the impostor will be synced to. + * @param boneMesh The mesh that the bone is influencing. + * @param jointPivot The pivot of the joint / bone in local space. + * @param distToJoint Optional distance from the impostor to the joint. + * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. + * @param boneAxis Optional vector3 axis the bone is aligned with */ - side: number; + syncImpostorWithBone(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion, boneAxis?: Vector3): void; + static NoImpostor: number; + static SphereImpostor: number; + static BoxImpostor: number; + static PlaneImpostor: number; + static MeshImpostor: number; + static CylinderImpostor: number; + static ParticleImpostor: number; + static HeightmapImpostor: number; + } +} + +declare module BABYLON { + interface PhysicsJointData { + mainPivot?: Vector3; + connectedPivot?: Vector3; + mainAxis?: Vector3; + connectedAxis?: Vector3; + collision?: boolean; + nativeParams?: any; + } + /** + * This is a holder class for the physics joint created by the physics plugin. + * It holds a set of functions to control the underlying joint. + */ + class PhysicsJoint { + type: number; + jointData: PhysicsJointData; + private _physicsJoint; + protected _physicsPlugin: IPhysicsEnginePlugin; + constructor(type: number, jointData: PhysicsJointData); + physicsJoint: any; + physicsPlugin: IPhysicsEnginePlugin; /** - * Creates a new disc geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param radius defines the radius of the disc - * @param tessellation defines the tesselation factor to apply to the disc - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Execute a function that is physics-plugin specific. + * @param {Function} func the function that will be executed. + * It accepts two parameters: the physics world and the physics joint. */ - constructor(id: string, scene: Scene, - /** - * Defines the radius of the disc - */ - radius: number, - /** - * Defines the tesselation factor to apply to the disc - */ - tessellation: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; + executeNativeFunction(func: (world: any, physicsJoint: any) => void): void; + static DistanceJoint: number; + static HingeJoint: number; + static BallAndSocketJoint: number; + static WheelJoint: number; + static SliderJoint: number; + static PrismaticJoint: number; + static UniversalJoint: number; + static Hinge2Joint: number; + static PointToPointJoint: number; + static SpringJoint: number; + static LockJoint: number; } /** - * Creates a new cylinder geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone + * A class representing a physics distance joint. */ - class CylinderGeometry extends _PrimitiveGeometry { + class DistanceJoint extends PhysicsJoint { + constructor(jointData: DistanceJointData); /** - * Defines the height of the cylinder + * Update the predefined distance. */ - height: number; + updateDistance(maxDistance: number, minDistance?: number): void; + } + class MotorEnabledJoint extends PhysicsJoint implements IMotorEnabledJoint { + constructor(type: number, jointData: PhysicsJointData); /** - * Defines the diameter of the cylinder's top cap + * Set the motor values. + * Attention, this function is plugin specific. Engines won't react 100% the same. + * @param {number} force the force to apply + * @param {number} maxForce max force for this motor. */ - diameterTop: number; + setMotor(force?: number, maxForce?: number): void; /** - * Defines the diameter of the cylinder's bottom cap + * Set the motor's limits. + * Attention, this function is plugin specific. Engines won't react 100% the same. */ - diameterBottom: number; + setLimit(upperLimit: number, lowerLimit?: number): void; + } + /** + * This class represents a single hinge physics joint + */ + class HingeJoint extends MotorEnabledJoint { + constructor(jointData: PhysicsJointData); /** - * Defines the tessellation factor to apply to the cylinder + * Set the motor values. + * Attention, this function is plugin specific. Engines won't react 100% the same. + * @param {number} force the force to apply + * @param {number} maxForce max force for this motor. */ - tessellation: number; + setMotor(force?: number, maxForce?: number): void; /** - * Defines the number of subdivisions to apply to the cylinder (1 by default) + * Set the motor's limits. + * Attention, this function is plugin specific. Engines won't react 100% the same. */ - subdivisions: number; + setLimit(upperLimit: number, lowerLimit?: number): void; + } + /** + * This class represents a dual hinge physics joint (same as wheel joint) + */ + class Hinge2Joint extends MotorEnabledJoint { + constructor(jointData: PhysicsJointData); /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Set the motor values. + * Attention, this function is plugin specific. Engines won't react 100% the same. + * @param {number} force the force to apply + * @param {number} maxForce max force for this motor. + * @param {motorIndex} the motor's index, 0 or 1. */ - side: number; + setMotor(force?: number, maxForce?: number, motorIndex?: number): void; /** - * Creates a new cylinder geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param height defines the height of the cylinder - * @param diameterTop defines the diameter of the cylinder's top cap - * @param diameterBottom defines the diameter of the cylinder's bottom cap - * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides) - * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default) - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Set the motor limits. + * Attention, this function is plugin specific. Engines won't react 100% the same. + * @param {number} upperLimit the upper limit + * @param {number} lowerLimit lower limit + * @param {motorIndex} the motor's index, 0 or 1. */ - constructor(id: string, scene: Scene, - /** - * Defines the height of the cylinder - */ - height: number, - /** - * Defines the diameter of the cylinder's top cap - */ - diameterTop: number, - /** - * Defines the diameter of the cylinder's bottom cap - */ - diameterBottom: number, - /** - * Defines the tessellation factor to apply to the cylinder - */ - tessellation: number, - /** - * Defines the number of subdivisions to apply to the cylinder (1 by default) - */ - subdivisions?: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedCylinder: any, scene: Scene): Nullable; + setLimit(upperLimit: number, lowerLimit?: number, motorIndex?: number): void; + } + interface IMotorEnabledJoint { + physicsJoint: any; + setMotor(force?: number, maxForce?: number, motorIndex?: number): void; + setLimit(upperLimit: number, lowerLimit?: number, motorIndex?: number): void; + } + interface DistanceJointData extends PhysicsJointData { + maxDistance: number; + } + interface SpringJointData extends PhysicsJointData { + length: number; + stiffness: number; + damping: number; } +} + +declare module BABYLON { /** - * Creates a new torus geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#torus + * This represents a GPU particle system in Babylon + * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data + * @see https://www.babylonjs-playground.com/#PU4WYI#4 */ - class TorusGeometry extends _PrimitiveGeometry { + class GPUParticleSystem implements IDisposable, IParticleSystem, IAnimatable { /** - * Defines the diameter of the torus + * The id of the Particle system. */ - diameter: number; + id: string; /** - * Defines the thickness of the torus (ie. internal diameter) + * The friendly name of the Particle system. */ - thickness: number; + name: string; /** - * Defines the tesselation factor to apply to the torus + * The emitter represents the Mesh or position we are attaching the particle system to. */ - tessellation: number; + emitter: Nullable; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * The rendering group used by the Particle system to chose when to render. */ - side: number; + renderingGroupId: number; /** - * Creates a new torus geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param diameter defines the diameter of the torus - * @param thickness defines the thickness of the torus (ie. internal diameter) - * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle) - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * The layer mask we are rendering the particles through. */ - constructor(id: string, scene: Scene, - /** - * Defines the diameter of the torus - */ - diameter: number, - /** - * Defines the thickness of the torus (ie. internal diameter) - */ - thickness: number, - /** - * Defines the tesselation factor to apply to the torus - */ - tessellation: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedTorus: any, scene: Scene): Nullable; - } - /** - * Creates a new ground geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#ground - */ - class GroundGeometry extends _PrimitiveGeometry { + layerMask: number; + private _capacity; + private _activeCount; + private _currentActiveCount; + private _accumulatedCount; + private _renderEffect; + private _updateEffect; + private _buffer0; + private _buffer1; + private _spriteBuffer; + private _updateVAO; + private _renderVAO; + private _targetIndex; + private _sourceBuffer; + private _targetBuffer; + private _scene; + private _engine; + private _currentRenderId; + private _started; + private _stopped; + private _timeDelta; + private _randomTexture; + private _randomTexture2; + private _attributesStrideSize; + private _updateEffectOptions; + private _randomTextureSize; + private _actualFrame; + private readonly _rawTextureWidth; /** - * Defines the width of the ground + * List of animations used by the particle system. */ - width: number; + animations: Animation[]; /** - * Defines the height of the ground + * Gets a boolean indicating if the GPU particles can be rendered on current browser */ - height: number; + static readonly IsSupported: boolean; /** - * Defines the subdivisions to apply to the ground + * An event triggered when the system is disposed. + */ + onDisposeObservable: Observable; + /** + * The overall motion speed (0.01 is default update speed, faster updates = faster animation) */ - subdivisions: number; + updateSpeed: number; /** - * Creates a new ground geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param width defines the width of the ground - * @param height defines the height of the ground - * @param subdivisions defines the subdivisions to apply to the ground - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) + * The amount of time the particle system is running (depends of the overall update speed). */ - constructor(id: string, scene: Scene, - /** - * Defines the width of the ground - */ - width: number, - /** - * Defines the height of the ground - */ - height: number, - /** - * Defines the subdivisions to apply to the ground - */ - subdivisions: number, canBeRegenerated?: boolean, mesh?: Nullable); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedGround: any, scene: Scene): Nullable; - } - /** - * Creates a tiled ground geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground - */ - class TiledGroundGeometry extends _PrimitiveGeometry { + targetStopDuration: number; /** - * Defines the minimum value on X axis + * The texture used to render each particle. (this can be a spritesheet) */ - xmin: number; + particleTexture: Nullable; /** - * Defines the minimum value on Z axis + * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD. */ - zmin: number; + blendMode: number; /** - * Defines the maximum value on X axis + * Minimum life time of emitting particles. */ - xmax: number; + minLifeTime: number; /** - * Defines the maximum value on Z axis + * Maximum life time of emitting particles. */ - zmax: number; + maxLifeTime: number; /** - * Defines the subdivisions to apply to the ground + * Minimum Size of emitting particles. */ - subdivisions: { - w: number; - h: number; - }; + minSize: number; /** - * Defines the precision to use when computing the tiles + * Maximum Size of emitting particles. */ - precision: { - w: number; - h: number; - }; + maxSize: number; /** - * Creates a tiled ground geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param xmin defines the minimum value on X axis - * @param zmin defines the minimum value on Z axis - * @param xmax defines the maximum value on X axis - * @param zmax defines the maximum value on Z axis - * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map) - * @param precision defines the precision to use when computing the tiles - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) + * Minimum scale of emitting particles on X axis. */ - constructor(id: string, scene: Scene, - /** - * Defines the minimum value on X axis - */ - xmin: number, - /** - * Defines the minimum value on Z axis - */ - zmin: number, - /** - * Defines the maximum value on X axis - */ - xmax: number, - /** - * Defines the maximum value on Z axis - */ - zmax: number, - /** - * Defines the subdivisions to apply to the ground - */ - subdivisions: { - w: number; - h: number; - }, - /** - * Defines the precision to use when computing the tiles - */ - precision: { - w: number; - h: number; - }, canBeRegenerated?: boolean, mesh?: Nullable); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - } - /** - * Creates a plane geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#plane - */ - class PlaneGeometry extends _PrimitiveGeometry { + minScaleX: number; /** - * Defines the size of the plane (width === height) + * Maximum scale of emitting particles on X axis. */ - size: number; + maxScaleX: number; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Minimum scale of emitting particles on Y axis. */ - side: number; + minScaleY: number; /** - * Creates a plane geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param size defines the size of the plane (width === height) - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Maximum scale of emitting particles on Y axis. */ - constructor(id: string, scene: Scene, - /** - * Defines the size of the plane (width === height) - */ - size: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedPlane: any, scene: Scene): Nullable; - } - /** - * Creates a torus knot geometry - * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot - */ - class TorusKnotGeometry extends _PrimitiveGeometry { + maxScaleY: number; /** - * Defines the radius of the torus knot + * Random color of each particle after it has been emitted, between color1 and color2 vectors. */ - radius: number; + color1: Color4; /** - * Defines the thickness of the torus knot tube + * Random color of each particle after it has been emitted, between color1 and color2 vectors. */ - tube: number; + color2: Color4; /** - * Defines the number of radial segments + * Color the particle will have at the end of its lifetime. */ - radialSegments: number; + colorDead: Color4; /** - * Defines the number of tubular segments + * The maximum number of particles to emit per frame until we reach the activeParticleCount value */ - tubularSegments: number; + emitRate: number; /** - * Defines the first number of windings + * You can use gravity if you want to give an orientation to your particles. */ - p: number; + gravity: Vector3; /** - * Defines the second number of windings + * Minimum power of emitting particles. */ - q: number; + minEmitPower: number; /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Maximum power of emitting particles. */ - side: number; + maxEmitPower: number; /** - * Creates a torus knot geometry - * @param id defines the unique ID of the geometry - * @param scene defines the hosting scene - * @param radius defines the radius of the torus knot - * @param tube defines the thickness of the torus knot tube - * @param radialSegments defines the number of radial segments - * @param tubularSegments defines the number of tubular segments - * @param p defines the first number of windings - * @param q defines the second number of windings - * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) - * @param mesh defines the hosting mesh (can be null) - * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) + * Minimum angular speed of emitting particles (Z-axis rotation for each particle). */ - constructor(id: string, scene: Scene, - /** - * Defines the radius of the torus knot - */ - radius: number, - /** - * Defines the thickness of the torus knot tube - */ - tube: number, - /** - * Defines the number of radial segments - */ - radialSegments: number, - /** - * Defines the number of tubular segments - */ - tubularSegments: number, - /** - * Defines the first number of windings - */ - p: number, - /** - * Defines the second number of windings - */ - q: number, canBeRegenerated?: boolean, mesh?: Nullable, - /** - * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) - */ - side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedTorusKnot: any, scene: Scene): Nullable; - } -} - -declare module BABYLON { - class GroundMesh extends Mesh { - generateOctree: boolean; - private _heightQuads; - _subdivisionsX: number; - _subdivisionsY: number; - _width: number; - _height: number; - _minX: number; - _maxX: number; - _minZ: number; - _maxZ: number; - constructor(name: string, scene: Scene); - getClassName(): string; - readonly subdivisions: number; - readonly subdivisionsX: number; - readonly subdivisionsY: number; - optimize(chunksCount: number, octreeBlocksSize?: number): void; + minAngularSpeed: number; /** - * Returns a height (y) value in the Worl system : - * the ground altitude at the coordinates (x, z) expressed in the World system. - * Returns the ground y position if (x, z) are outside the ground surface. + * Maximum angular speed of emitting particles (Z-axis rotation for each particle). */ - getHeightAtCoordinates(x: number, z: number): number; + maxAngularSpeed: number; /** - * Returns a normalized vector (Vector3) orthogonal to the ground - * at the ground coordinates (x, z) expressed in the World system. - * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface. + * The particle emitter type defines the emitter used by the particle system. + * It can be for example box, sphere, or cone... */ - getNormalAtCoordinates(x: number, z: number): Vector3; + particleEmitterType: Nullable; /** - * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground - * at the ground coordinates (x, z) expressed in the World system. - * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface. - * Returns the GroundMesh. + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + * This only works when particleEmitterTyps is a BoxParticleEmitter */ - getNormalAtCoordinatesToRef(x: number, z: number, ref: Vector3): GroundMesh; + direction1: Vector3; /** - * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates() - * if the ground has been updated. - * This can be used in the render loop. - * Returns the GroundMesh. - */ - updateCoordinateHeights(): GroundMesh; - private _getFacetAt(x, z); - private _initHeightQuads(); - private _computeHeightQuads(); - serialize(serializationObject: any): void; - static Parse(parsedMesh: any, scene: Scene): GroundMesh; - } -} - -declare module BABYLON { - /** - * Creates an instance based on a source mesh. - */ - class InstancedMesh extends AbstractMesh { - private _sourceMesh; - private _currentLOD; - constructor(name: string, source: Mesh); + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + * This only works when particleEmitterTyps is a BoxParticleEmitter + */ + direction2: Vector3; /** - * Returns the string "InstancedMesh". + * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. + * This only works when particleEmitterTyps is a BoxParticleEmitter */ - getClassName(): string; - readonly receiveShadows: boolean; - readonly material: Nullable; - readonly visibility: number; - readonly skeleton: Nullable; - renderingGroupId: number; + minEmitBox: Vector3; /** - * Returns the total number of vertices (integer). + * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. + * This only works when particleEmitterTyps is a BoxParticleEmitter */ - getTotalVertices(): number; - readonly sourceMesh: Mesh; + maxEmitBox: Vector3; /** - * Is this node ready to be used/rendered - * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) - * @return {boolean} is it ready + * Gets the maximum number of particles active at the same time. + * @returns The max number of active particles. */ - isReady(completeCheck?: boolean): boolean; + getCapacity(): number; /** - * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc. + * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls + * to override the particles. */ - getVerticesData(kind: string, copyWhenShared?: boolean): Nullable; + forceDepthWrite: boolean; /** - * Sets the vertex data of the mesh geometry for the requested `kind`. - * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. - * The `data` are either a numeric array either a Float32Array. - * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater. - * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc). - * Note that a new underlying VertexBuffer object is created each call. - * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. - * - * Possible `kind` values : - * - BABYLON.VertexBuffer.PositionKind - * - BABYLON.VertexBuffer.UVKind - * - BABYLON.VertexBuffer.UV2Kind - * - BABYLON.VertexBuffer.UV3Kind - * - BABYLON.VertexBuffer.UV4Kind - * - BABYLON.VertexBuffer.UV5Kind - * - BABYLON.VertexBuffer.UV6Kind - * - BABYLON.VertexBuffer.ColorKind - * - BABYLON.VertexBuffer.MatricesIndicesKind - * - BABYLON.VertexBuffer.MatricesIndicesExtraKind - * - BABYLON.VertexBuffer.MatricesWeightsKind - * - BABYLON.VertexBuffer.MatricesWeightsExtraKind - * - * Returns the Mesh. + * Gets or set the number of active particles */ - setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): Mesh; + activeParticleCount: number; + private _preWarmDone; + /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */ + preWarmCycles: number; + /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */ + preWarmStepOffset: number; /** - * Updates the existing vertex data of the mesh geometry for the requested `kind`. - * If the mesh has no geometry, it is simply returned as it is. - * The `data` are either a numeric array either a Float32Array. - * No new underlying VertexBuffer object is created. - * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. - * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh. - * - * Possible `kind` values : - * - BABYLON.VertexBuffer.PositionKind - * - BABYLON.VertexBuffer.UVKind - * - BABYLON.VertexBuffer.UV2Kind - * - BABYLON.VertexBuffer.UV3Kind - * - BABYLON.VertexBuffer.UV4Kind - * - BABYLON.VertexBuffer.UV5Kind - * - BABYLON.VertexBuffer.UV6Kind - * - BABYLON.VertexBuffer.ColorKind - * - BABYLON.VertexBuffer.MatricesIndicesKind - * - BABYLON.VertexBuffer.MatricesIndicesExtraKind - * - BABYLON.VertexBuffer.MatricesWeightsKind - * - BABYLON.VertexBuffer.MatricesWeightsExtraKind - * - * Returns the Mesh. + * Gets or sets the minimal initial rotation in radians. */ - updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): Mesh; + minInitialRotation: number; /** - * Sets the mesh indices. - * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array). - * If the mesh has no geometry, a new Geometry object is created and set to the mesh. - * This method creates a new index buffer each call. - * Returns the Mesh. + * Gets or sets the maximal initial rotation in radians. */ - setIndices(indices: IndicesArray, totalVertices?: Nullable): Mesh; + maxInitialRotation: number; /** - * Boolean : True if the mesh owns the requested kind of data. + * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime) */ - isVerticesDataPresent(kind: string): boolean; + spriteCellChangeSpeed: number; /** - * Returns an array of indices (IndicesArray). + * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display */ - getIndices(): Nullable; - readonly _positions: Nullable; + startSpriteCellID: number; /** - * Sets a new updated BoundingInfo to the mesh. - * Returns the mesh. + * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display */ - refreshBoundingInfo(): InstancedMesh; - _preActivate(): InstancedMesh; - _activate(renderId: number): InstancedMesh; + endSpriteCellID: number; /** - * Returns the current associated LOD AbstractMesh. + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use */ - getLOD(camera: Camera): AbstractMesh; - _syncSubMeshes(): InstancedMesh; - _generatePointsArray(): boolean; + spriteCellWidth: number; /** - * Creates a new InstancedMesh from the current mesh. - * - name (string) : the cloned mesh name - * - newParent (optional Node) : the optional Node to parent the clone to. - * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned. - * - * Returns the clone. + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use */ - clone(name: string, newParent: Node, doNotCloneChildren?: boolean): InstancedMesh; + spriteCellHeight: number; + /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ + translationPivot: Vector2; /** - * Disposes the InstancedMesh. - * Returns nothing. + * Gets or sets a texture used to add random noise to particle positions */ - dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; - } -} - -declare module BABYLON { - class LinesMesh extends Mesh { - useVertexColor: boolean | undefined; - useVertexAlpha: boolean | undefined; - color: Color3; - alpha: number; + noiseTexture: Nullable; + /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ + noiseStrength: Vector3; /** - * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray. - * This margin is expressed in world space coordinates, so its value may vary. - * Default value is 0.1 - * @returns the intersection Threshold value. + * Gets or sets the billboard mode to use when isBillboardBased = true. + * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far */ + billboardMode: number; + private _isAnimationSheetEnabled; /** - * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray. - * This margin is expressed in world space coordinates, so its value may vary. - * @param value the new threshold to apply + * Gets whether an animation sprite sheet is enabled or not on the particle system */ - intersectionThreshold: number; - private _intersectionThreshold; - private _colorShader; - constructor(name: string, scene?: Nullable, parent?: Nullable, source?: LinesMesh, doNotCloneChildren?: boolean, useVertexColor?: boolean | undefined, useVertexAlpha?: boolean | undefined); + readonly isAnimationSheetEnabled: boolean; /** - * Returns the string "LineMesh" + * Is this system ready to be used/rendered + * @return true if the system is ready */ - getClassName(): string; + isReady(): boolean; /** - * @hidden + * Gets Wether the system has been started. + * @returns True if it has been started, otherwise false. */ + isStarted(): boolean; /** - * @hidden + * Starts the particle system and begins to emit + * @param delay defines the delay in milliseconds before starting the system (0 by default) */ - material: Material; + start(delay?: number): void; /** - * @hidden + * Stops the particle system. */ - readonly checkCollisions: boolean; - createInstance(name: string): InstancedMesh; - _bind(subMesh: SubMesh, effect: Effect, fillMode: number): LinesMesh; - _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): LinesMesh; - dispose(doNotRecurse?: boolean): void; + stop(): void; /** - * Returns a new LineMesh object cloned from the current one. + * Remove all active particles */ - clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): LinesMesh; - } -} - -declare module BABYLON { - /** - * @hidden - **/ - class _InstancesBatch { - mustReturn: boolean; - visibleInstances: Nullable[]; - renderSelf: boolean[]; - } - class Mesh extends AbstractMesh implements IGetSetVerticesData { - static _FRONTSIDE: number; - static _BACKSIDE: number; - static _DOUBLESIDE: number; - static _DEFAULTSIDE: number; - static _NO_CAP: number; - static _CAP_START: number; - static _CAP_END: number; - static _CAP_ALL: number; + reset(): void; /** - * Mesh side orientation : usually the external or front surface + * Returns the string "GPUParticleSystem" + * @returns a string containing the class name */ - static readonly FRONTSIDE: number; + getClassName(): string; + private _isBillboardBased; /** - * Mesh side orientation : usually the internal or back surface + * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction */ - static readonly BACKSIDE: number; + isBillboardBased: boolean; + private _colorGradients; + private _colorGradientsTexture; /** - * Mesh side orientation : both internal and external or front and back surfaces + * Gets the current list of color gradients. + * You must use addColorGradient and removeColorGradient to udpate this list + * @returns the list of color gradients */ - static readonly DOUBLESIDE: number; + getColorGradients(): Nullable>; /** - * Mesh side orientation : by default, `FRONTSIDE` + * Gets the current list of size gradients. + * You must use addSizeGradient and removeSizeGradient to udpate this list + * @returns the list of size gradients */ - static readonly DEFAULTSIDE: number; + getSizeGradients(): Nullable>; /** - * Mesh cap setting : no cap + * Gets the current list of angular speed gradients. + * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list + * @returns the list of angular speed gradients */ - static readonly NO_CAP: number; + getAngularSpeedGradients(): Nullable>; /** - * Mesh cap setting : one cap at the beginning of the mesh + * Gets the current list of velocity gradients. + * You must use addVelocityGradient and removeVelocityGradient to udpate this list + * @returns the list of angular speed gradients */ - static readonly CAP_START: number; + getVelocityGradients(): Nullable>; + private _removeGradient; /** - * Mesh cap setting : one cap at the end of the mesh + * Adds a new color gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param color defines the color to affect to the specified gradient + * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from + * @returns the current particle system */ - static readonly CAP_END: number; + addColorGradient(gradient: number, color1: Color4, color2?: Color4): GPUParticleSystem; /** - * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh + * Remove a specific color gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - static readonly CAP_ALL: number; + removeColorGradient(gradient: number): GPUParticleSystem; + private _angularSpeedGradients; + private _angularSpeedGradientsTexture; + private _sizeGradients; + private _sizeGradientsTexture; + private _velocityGradients; + private _velocityGradientsTexture; + private _addFactorGradient; /** - * An event triggered before rendering the mesh + * Adds a new size gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @returns the current particle system */ - onBeforeRenderObservable: Observable; + addSizeGradient(gradient: number, factor: number): GPUParticleSystem; /** - * An event triggered after rendering the mesh - */ - onAfterRenderObservable: Observable; + * Remove a specific size gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeSizeGradient(gradient: number): GPUParticleSystem; /** - * An event triggered before drawing the mesh - */ - onBeforeDrawObservable: Observable; - private _onBeforeDrawObserver; - onBeforeDraw: () => void; - delayLoadState: number; - instances: InstancedMesh[]; - delayLoadingFile: string; - _binaryInfo: any; - private _LODLevels; - onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Nullable) => void; - private _morphTargetManager; - morphTargetManager: Nullable; - _geometry: Nullable; - _delayInfo: Array; - _delayLoadingFunction: (any: any, mesh: Mesh) => void; - _visibleInstances: any; - private _renderIdForInstances; - private _batchCache; - private _instancesBufferSize; - private _instancesBuffer; - private _instancesData; - private _overridenInstanceCount; - private _effectiveMaterial; - _shouldGenerateFlatShading: boolean; - private _preActivateId; - _originalBuilderSideOrientation: number; - overrideMaterialSideOrientation: Nullable; - private _areNormalsFrozen; - private _sourcePositions; - private _sourceNormals; - private _source; - readonly source: Nullable; - isUnIndexed: boolean; + * Adds a new angular speed gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @returns the current particle system + */ + addAngularSpeedGradient(gradient: number, factor: number): GPUParticleSystem; /** - * @constructor - * @param {string} name The value used by scene.getMeshByName() to do a lookup. - * @param {Scene} scene The scene to add this mesh to. - * @param {Node} parent The parent of this mesh, if it has one - * @param {Mesh} source An optional Mesh from which geometry is shared, cloned. - * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False. - * When false, achieved by calling a clone(), also passing False. - * This will make creation of children, recursive. - * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True. + * Remove a specific angular speed gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - constructor(name: string, scene?: Nullable, parent?: Nullable, source?: Nullable, doNotCloneChildren?: boolean, clonePhysicsImpostor?: boolean); + removeAngularSpeedGradient(gradient: number): GPUParticleSystem; /** - * Returns the string "Mesh". + * Adds a new velocity gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @returns the current particle system */ - getClassName(): string; + addVelocityGradient(gradient: number, factor: number): GPUParticleSystem; /** - * Returns a string. - * @param {boolean} fullDetails - support for multiple levels of logging within scene loading + * Remove a specific velocity gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - toString(fullDetails?: boolean): string; - _unBindEffect(): void; + removeVelocityGradient(gradient: number): GPUParticleSystem; /** - * True if the mesh has some Levels Of Details (LOD). - * Returns a boolean. + * Instantiates a GPU particle system. + * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. + * @param name The name of the particle system + * @param options The options used to create the system + * @param scene The scene the particle system belongs to + * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture */ - readonly hasLODLevels: boolean; + constructor(name: string, options: Partial<{ + capacity: number; + randomTextureSize: number; + }>, scene: Scene, isAnimationSheetEnabled?: boolean); + private _createUpdateVAO; + private _createRenderVAO; + private _initialize; + /** @hidden */ + _recreateUpdateEffect(): void; + /** @hidden */ + _recreateRenderEffect(): void; /** - * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh - * @returns an array of {BABYLON.MeshLODLevel} + * Animates the particle system for the current frame by emitting new particles and or animating the living ones. + * @param preWarm defines if we are in the pre-warmimg phase */ - getLODLevels(): MeshLODLevel[]; - private _sortLODLevels(); + animate(preWarm?: boolean): void; + private _createFactorGradientTexture; + private _createSizeGradientTexture; + private _createAngularSpeedGradientTexture; + private _createVelocityGradientTexture; + private _createColorGradientTexture; /** - * Add a mesh as LOD level triggered at the given distance. - * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD - * @param distance The distance from the center of the object to show this level - * @param mesh The mesh to be added as LOD level (can be null) - * @return This mesh (for chaining) + * Renders the particle system in its current state + * @param preWarm defines if the system should only update the particles but not render them + * @returns the current number of particles */ - addLODLevel(distance: number, mesh: Nullable): Mesh; + render(preWarm?: boolean): number; /** - * Returns the LOD level mesh at the passed distance or null if not found. - * It is related to the method `addLODLevel(distance, mesh)`. - * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD - * Returns an object Mesh or `null`. + * Rebuilds the particle system */ - getLODLevelAtDistance(distance: number): Nullable; + rebuild(): void; + private _releaseBuffers; + private _releaseVAOs; /** - * Remove a mesh from the LOD array - * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD - * @param {Mesh} mesh The mesh to be removed. - * @return {Mesh} This mesh (for chaining) + * Disposes the particle system and free the associated resources + * @param disposeTexture defines if the particule texture must be disposed as well (true by default) */ - removeLODLevel(mesh: Mesh): Mesh; + dispose(disposeTexture?: boolean): void; /** - * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh. - * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod + * Clones the particle system. + * @param name The name of the cloned object + * @param newEmitter The new emitter to use + * @returns the cloned particle system */ - getLOD(camera: Camera, boundingSphere?: BoundingSphere): Nullable; + clone(name: string, newEmitter: any): Nullable; /** - * Returns the mesh internal Geometry object. + * Serializes the particle system to a JSON object. + * @returns the JSON object */ - readonly geometry: Nullable; + serialize(): any; /** - * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry. + * Parses a JSON object to create a GPU particle system. + * @param parsedParticleSystem The JSON object to parse + * @param scene The scene to create the particle system in + * @param rootUrl The root url to use to load external dependencies like texture + * @returns the parsed GPU particle system */ - getTotalVertices(): number; + static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): GPUParticleSystem; + } +} + +declare module BABYLON { + /** + * Interface representing a particle system in Babylon.js. + * This groups the common functionalities that needs to be implemented in order to create a particle system. + * A particle system represents a way to manage particles from their emission to their animation and rendering. + */ + interface IParticleSystem { /** - * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc). - * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one. - * You can force the copy with forceCopy === true - * Returns null if the mesh has no geometry or no vertex buffer. - * Possible `kind` values : - * - BABYLON.VertexBuffer.PositionKind - * - BABYLON.VertexBuffer.UVKind - * - BABYLON.VertexBuffer.UV2Kind - * - BABYLON.VertexBuffer.UV3Kind - * - BABYLON.VertexBuffer.UV4Kind - * - BABYLON.VertexBuffer.UV5Kind - * - BABYLON.VertexBuffer.UV6Kind - * - BABYLON.VertexBuffer.ColorKind - * - BABYLON.VertexBuffer.MatricesIndicesKind - * - BABYLON.VertexBuffer.MatricesIndicesExtraKind - * - BABYLON.VertexBuffer.MatricesWeightsKind - * - BABYLON.VertexBuffer.MatricesWeightsExtraKind + * List of animations used by the particle system. */ - getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable; + animations: Animation[]; /** - * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc. - * Returns `null` if the mesh has no geometry. - * Possible `kind` values : - * - BABYLON.VertexBuffer.PositionKind - * - BABYLON.VertexBuffer.UVKind - * - BABYLON.VertexBuffer.UV2Kind - * - BABYLON.VertexBuffer.UV3Kind - * - BABYLON.VertexBuffer.UV4Kind - * - BABYLON.VertexBuffer.UV5Kind - * - BABYLON.VertexBuffer.UV6Kind - * - BABYLON.VertexBuffer.ColorKind - * - BABYLON.VertexBuffer.MatricesIndicesKind - * - BABYLON.VertexBuffer.MatricesIndicesExtraKind - * - BABYLON.VertexBuffer.MatricesWeightsKind - * - BABYLON.VertexBuffer.MatricesWeightsExtraKind + * The id of the Particle system. */ - getVertexBuffer(kind: string): Nullable; - isVerticesDataPresent(kind: string): boolean; + id: string; /** - * Returns a boolean defining if the vertex data for the requested `kind` is updatable. - * Possible `kind` values : - * - BABYLON.VertexBuffer.PositionKind - * - BABYLON.VertexBuffer.UVKind - * - BABYLON.VertexBuffer.UV2Kind - * - BABYLON.VertexBuffer.UV3Kind - * - BABYLON.VertexBuffer.UV4Kind - * - BABYLON.VertexBuffer.UV5Kind - * - BABYLON.VertexBuffer.UV6Kind - * - BABYLON.VertexBuffer.ColorKind - * - BABYLON.VertexBuffer.MatricesIndicesKind - * - BABYLON.VertexBuffer.MatricesIndicesExtraKind - * - BABYLON.VertexBuffer.MatricesWeightsKind - * - BABYLON.VertexBuffer.MatricesWeightsExtraKind + * The name of the Particle system. */ - isVertexBufferUpdatable(kind: string): boolean; + name: string; /** - * Returns a string : the list of existing `kinds` of Vertex Data for this mesh. - * Possible `kind` values : - * - BABYLON.VertexBuffer.PositionKind - * - BABYLON.VertexBuffer.UVKind - * - BABYLON.VertexBuffer.UV2Kind - * - BABYLON.VertexBuffer.UV3Kind - * - BABYLON.VertexBuffer.UV4Kind - * - BABYLON.VertexBuffer.UV5Kind - * - BABYLON.VertexBuffer.UV6Kind - * - BABYLON.VertexBuffer.ColorKind - * - BABYLON.VertexBuffer.MatricesIndicesKind - * - BABYLON.VertexBuffer.MatricesIndicesExtraKind - * - BABYLON.VertexBuffer.MatricesWeightsKind - * - BABYLON.VertexBuffer.MatricesWeightsExtraKind + * The emitter represents the Mesh or position we are attaching the particle system to. */ - getVerticesDataKinds(): string[]; + emitter: Nullable; /** - * Returns a positive integer : the total number of indices in this mesh geometry. - * Returns zero if the mesh has no geometry. + * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction */ - getTotalIndices(): number; + isBillboardBased: boolean; /** - * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices. - * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one. - * Returns an empty array if the mesh has no geometry. + * The rendering group used by the Particle system to chose when to render. */ - getIndices(copyWhenShared?: boolean): Nullable; - readonly isBlocked: boolean; + renderingGroupId: number; /** - * Determine if the current mesh is ready to be rendered - * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) - * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default) - * @returns true if all associated assets are ready (material, textures, shaders) + * The layer mask we are rendering the particles through. */ - isReady(completeCheck?: boolean, forceInstanceSupport?: boolean): boolean; + layerMask: number; /** - * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update. - * This property is pertinent only for updatable parametric shapes. - */ - readonly areNormalsFrozen: boolean; + * The overall motion speed (0.01 is default update speed, faster updates = faster animation) + */ + updateSpeed: number; /** - * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. - * It has no effect at all on other shapes. - * It prevents the mesh normals from being recomputed on next `positions` array update. - * Returns the Mesh. + * The amount of time the particle system is running (depends of the overall update speed). */ - freezeNormals(): Mesh; + targetStopDuration: number; /** - * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. - * It has no effect at all on other shapes. - * It reactivates the mesh normals computation if it was previously frozen. - * Returns the Mesh. + * The texture used to render each particle. (this can be a spritesheet) */ - unfreezeNormals(): Mesh; + particleTexture: Nullable; /** - * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs + * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE, ParticleSystem.BLENDMODE_STANDARD or ParticleSystem.BLENDMODE_ADD. */ - overridenInstanceCount: number; - _preActivate(): Mesh; - _preActivateForIntermediateRendering(renderId: number): Mesh; - _registerInstanceForRenderId(instance: InstancedMesh, renderId: number): Mesh; + blendMode: number; /** - * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked. - * This means the mesh underlying bounding box and sphere are recomputed. - * Returns the Mesh. + * Minimum life time of emitting particles. */ - refreshBoundingInfo(): Mesh; - _refreshBoundingInfo(applySkeleton: boolean): Mesh; - private _getPositionData(applySkeleton); - _createGlobalSubMesh(force: boolean): Nullable; - subdivide(count: number): void; - setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): Mesh; - markVerticesDataAsUpdatable(kind: string, updatable?: boolean): void; + minLifeTime: number; /** - * Sets the mesh VertexBuffer. - * Returns the Mesh. + * Maximum life time of emitting particles. */ - setVerticesBuffer(buffer: VertexBuffer): Mesh; - updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): Mesh; + maxLifeTime: number; /** - * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values. - * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions - * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything. - * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update. - * Returns the Mesh. + * Minimum Size of emitting particles. */ - updateMeshPositions(positionFunction: (data: FloatArray) => void, computeNormals?: boolean): Mesh; + minSize: number; /** - * Creates a un-shared specific occurence of the geometry for the mesh. - * Returns the Mesh. + * Maximum Size of emitting particles. */ - makeGeometryUnique(): Mesh; - setIndices(indices: IndicesArray, totalVertices?: Nullable, updatable?: boolean): Mesh; + maxSize: number; /** - * Update the current index buffer - * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array) - * Returns the Mesh. + * Minimum scale of emitting particles on X axis. */ - updateIndices(indices: IndicesArray, offset?: number): Mesh; + minScaleX: number; /** - * Invert the geometry to move from a right handed system to a left handed one. - * Returns the Mesh. + * Maximum scale of emitting particles on X axis. */ - toLeftHanded(): Mesh; - _bind(subMesh: SubMesh, effect: Effect, fillMode: number): Mesh; - _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number, alternate?: boolean): Mesh; + maxScaleX: number; /** - * Registers for this mesh a javascript function called just before the rendering process. - * This function is passed the current mesh. - * Return the Mesh. + * Minimum scale of emitting particles on Y axis. */ - registerBeforeRender(func: (mesh: AbstractMesh) => void): Mesh; + minScaleY: number; /** - * Disposes a previously registered javascript function called before the rendering. - * This function is passed the current mesh. - * Returns the Mesh. + * Maximum scale of emitting particles on Y axis. */ - unregisterBeforeRender(func: (mesh: AbstractMesh) => void): Mesh; + maxScaleY: number; /** - * Registers for this mesh a javascript function called just after the rendering is complete. - * This function is passed the current mesh. - * Returns the Mesh. + * Random color of each particle after it has been emitted, between color1 and color2 vectors. */ - registerAfterRender(func: (mesh: AbstractMesh) => void): Mesh; + color1: Color4; /** - * Disposes a previously registered javascript function called after the rendering. - * This function is passed the current mesh. - * Return the Mesh. + * Random color of each particle after it has been emitted, between color1 and color2 vectors. */ - unregisterAfterRender(func: (mesh: AbstractMesh) => void): Mesh; - _getInstancesRenderList(subMeshId: number): _InstancesBatch; - _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): Mesh; - _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean, onBeforeDraw: (isInstance: boolean, world: Matrix, effectiveMaterial?: Material) => void, effectiveMaterial?: Material): Mesh; + color2: Color4; /** - * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager - * @param subMesh defines the subMesh to render - * @param enableAlphaMode defines if alpha mode can be changed - * @returns the current mesh + * Color the particle will have at the end of its lifetime. */ - render(subMesh: SubMesh, enableAlphaMode: boolean): Mesh; - private _onBeforeDraw(isInstance, world, effectiveMaterial?); + colorDead: Color4; /** - * Returns an array populated with IParticleSystem objects whose the mesh is the emitter. + * The maximum number of particles to emit per frame until we reach the activeParticleCount value */ - getEmittedParticleSystems(): IParticleSystem[]; + emitRate: number; /** - * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter. + * You can use gravity if you want to give an orientation to your particles. */ - getHierarchyEmittedParticleSystems(): IParticleSystem[]; + gravity: Vector3; /** - * Normalize matrix weights so that all vertices have a total weight set to 1 + * Minimum power of emitting particles. */ - cleanMatrixWeights(): void; - _checkDelayState(): Mesh; - private _queueLoad(scene); + minEmitPower: number; /** - * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter. + * Maximum power of emitting particles. */ - isInFrustum(frustumPlanes: Plane[]): boolean; + maxEmitPower: number; /** - * Sets the mesh material by the material or multiMaterial `id` property. - * The material `id` is a string identifying the material or the multiMaterial. - * This method returns the Mesh. + * Minimum angular speed of emitting particles (Z-axis rotation for each particle). */ - setMaterialByID(id: string): Mesh; + minAngularSpeed: number; /** - * Returns as a new array populated with the mesh material and/or skeleton, if any. + * Maximum angular speed of emitting particles (Z-axis rotation for each particle). */ - getAnimatables(): IAnimatable[]; + maxAngularSpeed: number; /** - * Modifies the mesh geometry according to the passed transformation matrix. - * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable. - * The mesh normals are modified accordingly the same transformation. - * tuto : http://doc.babylonjs.com/resources/baking_transformations - * Note that, under the hood, this method sets a new VertexBuffer each call. - * Returns the Mesh. + * Gets or sets the minimal initial rotation in radians. */ - bakeTransformIntoVertices(transform: Matrix): Mesh; + minInitialRotation: number; /** - * Modifies the mesh geometry according to its own current World Matrix. - * The mesh World Matrix is then reset. - * This method returns nothing but really modifies the mesh even if it's originally not set as updatable. - * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations - * Note that, under the hood, this method sets a new VertexBuffer each call. - * Returns the Mesh. + * Gets or sets the maximal initial rotation in radians. */ - bakeCurrentTransformIntoVertices(): Mesh; - readonly _positions: Nullable; - _resetPointsArrayCache(): Mesh; - _generatePointsArray(): boolean; + maxInitialRotation: number; /** - * Returns a new Mesh object generated from the current mesh properties. - * This method must not get confused with createInstance(). - * The parameter `name` is a string, the name given to the new mesh. - * The optional parameter `newParent` can be any Node object (default `null`). - * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any. - * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any. + * The particle emitter type defines the emitter used by the particle system. + * It can be for example box, sphere, or cone... */ - clone(name: string, newParent?: Node, doNotCloneChildren?: boolean, clonePhysicsImpostor?: boolean): Mesh; + particleEmitterType: Nullable; /** - * Releases resources associated with this mesh. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + * Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */ - dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; + preWarmCycles: number; /** - * Modifies the mesh geometry according to a displacement map. - * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. - * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. - * This method returns nothing. - * The parameter `url` is a string, the URL from the image file is to be downloaded. - * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement. - * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing. - * The parameter `uvOffset` is an optional vector2 used to offset UV. - * The parameter `uvScale` is an optional vector2 used to scale UV. - * - * Returns the Mesh. + * Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */ - applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void, uvOffset?: Vector2, uvScale?: Vector2): Mesh; + preWarmStepOffset: number; /** - * Modifies the mesh geometry according to a displacementMap buffer. - * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. - * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. - * This method returns nothing. - * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel. - * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image. - * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement. - * The parameter `uvOffset` is an optional vector2 used to offset UV. - * The parameter `uvScale` is an optional vector2 used to scale UV. - * - * Returns the Mesh. + * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime) */ - applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number, uvOffset?: Vector2, uvScale?: Vector2): Mesh; + spriteCellChangeSpeed: number; /** - * Modify the mesh to get a flat shading rendering. - * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result. - * This method returns the Mesh. - * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated. + * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display */ - convertToFlatShadedMesh(): Mesh; + startSpriteCellID: number; /** - * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers. - * In other words, more vertices, no more indices and a single bigger VBO. - * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated. - * Returns the Mesh. + * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display */ - convertToUnIndexedMesh(): Mesh; + endSpriteCellID: number; /** - * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true. - * This method returns the Mesh. - * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use */ - flipFaces(flipNormals?: boolean): Mesh; + spriteCellWidth: number; /** - * Creates a new InstancedMesh object from the mesh model. - * An instance shares the same properties and the same material than its model. - * Only these properties of each instance can then be set individually : - * - position - * - rotation - * - rotationQuaternion - * - setPivotMatrix - * - scaling - * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances - * Warning : this method is not supported for Line mesh and LineSystem + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use */ - createInstance(name: string): InstancedMesh; + spriteCellHeight: number; + /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ + translationPivot: Vector2; /** - * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any. - * After this call, all the mesh instances have the same submeshes than the current mesh. - * This method returns the Mesh. + * Gets or sets a texture used to add random noise to particle positions */ - synchronizeInstances(): Mesh; + noiseTexture: Nullable; + /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ + noiseStrength: Vector3; /** - * Simplify the mesh according to the given array of settings. - * Function will return immediately and will simplify async. It returns the Mesh. - * @param settings a collection of simplification settings. - * @param parallelProcessing should all levels calculate parallel or one after the other. - * @param type the type of simplification to run. - * @param successCallback optional success callback to be called after the simplification finished processing all settings. + * Gets or sets the billboard mode to use when isBillboardBased = true. + * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far */ - simplify(settings: Array, parallelProcessing?: boolean, simplificationType?: SimplificationType, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void): Mesh; + billboardMode: number; /** - * Optimization of the mesh's indices, in case a mesh has duplicated vertices. - * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes. - * This should be used together with the simplification to avoid disappearing triangles. - * Returns the Mesh. - * @param successCallback an optional success callback to be called after the optimization finished. + * Gets the maximum number of particles active at the same time. + * @returns The max number of active particles. */ - optimizeIndices(successCallback?: (mesh?: Mesh) => void): Mesh; - serialize(serializationObject: any): void; - _syncGeometryWithMorphTargetManager(): void; + getCapacity(): number; /** - * Returns a new Mesh object parsed from the source provided. - * The parameter `parsedMesh` is the source. - * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with + * Gets Wether the system has been started. + * @returns True if it has been started, otherwise false. */ - static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh; + isStarted(): boolean; /** - * Creates a ribbon mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. - * - * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial - * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry. - * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array. - * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array. - * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path. - * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11. - * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Gets if the particle system has been started. + * @return true if the system has been started, otherwise false. */ - static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean | undefined, closePath: boolean, offset: number, scene?: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; + isStarted(): boolean; /** - * Creates a plane polygonal mesh. By default, this is a disc. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `radius` sets the radius size (float) of the polygon (default 0.5). - * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc. - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Animates the particle system for this frame. */ - static CreateDisc(name: string, radius: number, tessellation: number, scene?: Nullable, updatable?: boolean, sideOrientation?: number): Mesh; + animate(): void; /** - * Creates a box mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `size` sets the size (float) of each box side (default 1). - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Renders the particle system in its current state. + * @returns the current number of particles */ - static CreateBox(name: string, size: number, scene?: Nullable, updatable?: boolean, sideOrientation?: number): Mesh; + render(): number; /** - * Creates a sphere mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `diameter` sets the diameter size (float) of the sphere (default 1). - * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32). - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Dispose the particle system and frees its associated resources. + * @param disposeTexture defines if the particule texture must be disposed as well (true by default) */ - static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + dispose(disposeTexture?: boolean): void; /** - * Creates a cylinder or a cone mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2). - * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1). - * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero. - * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance. - * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1). - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Clones the particle system. + * @param name The name of the cloned object + * @param newEmitter The new emitter to use + * @returns the cloned particle system */ - static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene?: Scene, updatable?: any, sideOrientation?: number): Mesh; + clone(name: string, newEmitter: any): Nullable; /** - * Creates a torus mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `diameter` sets the diameter size (float) of the torus (default 1). - * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5). - * The parameter `tessellation` sets the number of torus sides (postive integer, default 16). - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Serializes the particle system to a JSON object. + * @returns the JSON object */ - static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + serialize(): any; /** - * Creates a torus knot mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `radius` sets the global radius size (float) of the torus knot (default 2). - * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32). - * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32). - * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3). - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Rebuild the particle system */ - static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + rebuild(): void; /** - * Creates a line mesh. - * Please consider using the same method from the MeshBuilder class instead. - * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter. - * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function. - * The parameter `points` is an array successive Vector3. - * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines - * When updating an instance, remember that only point positions can change, not the number of points. - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Starts the particle system and begins to emit + * @param delay defines the delay in milliseconds before starting the system (0 by default) */ - static CreateLines(name: string, points: Vector3[], scene?: Nullable, updatable?: boolean, instance?: Nullable): LinesMesh; + start(delay?: number): void; /** - * Creates a dashed line mesh. - * Please consider using the same method from the MeshBuilder class instead. - * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter. - * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function. - * The parameter `points` is an array successive Vector3. - * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200). - * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3). - * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1). - * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines - * When updating an instance, remember that only point positions can change, not the number of points. - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Stops the particle system. */ - static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene?: Nullable, updatable?: boolean, instance?: LinesMesh): LinesMesh; + stop(): void; /** - * Creates a polygon mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh. - * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors. - * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * Remember you can only change the shape positions, not their number when updating a polygon. + * Remove all active particles */ - static CreatePolygon(name: string, shape: Vector3[], scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number): Mesh; + reset(): void; /** - * Creates an extruded polygon mesh, with depth in the Y direction. - * Please consider using the same method from the MeshBuilder class instead. + * Is this system ready to be used/rendered + * @return true if the system is ready */ - static ExtrudePolygon(name: string, shape: Vector3[], depth: number, scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number): Mesh; + isReady(): boolean; /** - * Creates an extruded shape mesh. - * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. - * Please consider using the same method from the MeshBuilder class instead. - * - * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes - * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be - * extruded along the Z axis. - * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. - * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve. - * The parameter `scale` (float, default 1) is the value to scale the shape. - * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape - * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Adds a new color gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param color defines the color to affect to the specified gradient + * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from + * @returns the current particle system */ - static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene?: Nullable, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; + addColorGradient(gradient: number, color1: Color4, color2?: Color4): IParticleSystem; /** - * Creates an custom extruded shape mesh. - * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. - * Please consider using the same method from the MeshBuilder class instead. - * - * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes - * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be - * extruded along the Z axis. - * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. - * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path - * and the distance of this point from the begining of the path : - * ```javascript - * var rotationFunction = function(i, distance) { - * // do things - * return rotationValue; } - * ``` - * It must returns a float value that will be the rotation in radians applied to the shape on each path point. - * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path - * and the distance of this point from the begining of the path : - * ```javascript - * var scaleFunction = function(i, distance) { - * // do things - * return scaleValue;} - * ``` - * It must returns a float value that will be the scale value applied to the shape on each path point. - * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`. - * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`. - * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape - * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Remove a specific color gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction: Function, rotationFunction: Function, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; + removeColorGradient(gradient: number): IParticleSystem; /** - * Creates lathe mesh. - * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be - * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero. - * The parameter `radius` (positive float, default 1) is the radius value of the lathe. - * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe. - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Adds a new size gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system */ - static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + addSizeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem; /** - * Creates a plane mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `size` sets the size (float) of both sides of the plane at once (default 1). - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Remove a specific size gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + removeSizeGradient(gradient: number): IParticleSystem; /** - * Creates a ground mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground. - * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side. - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Gets the current list of color gradients. + * You must use addColorGradient and removeColorGradient to udpate this list + * @returns the list of color gradients */ - static CreateGround(name: string, width: number, height: number, subdivisions: number, scene?: Scene, updatable?: boolean): Mesh; + getColorGradients(): Nullable>; /** - * Creates a tiled ground mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates. - * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates. - * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the - * numbers of subdivisions on the ground width and height. Each subdivision is called a tile. - * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the - * numbers of subdivisions on the ground width and height of each tile. - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Gets the current list of size gradients. + * You must use addSizeGradient and removeSizeGradient to udpate this list + * @returns the list of size gradients */ - static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { - w: number; - h: number; - }, precision: { - w: number; - h: number; - }, scene: Scene, updatable?: boolean): Mesh; + getSizeGradients(): Nullable>; /** - * Creates a ground mesh from a height map. - * tuto : http://doc.babylonjs.com/babylon101/height_map - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `url` sets the URL of the height map image resource. - * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes. - * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side. - * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground. - * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground. - * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time). - * This function is passed the newly built mesh : - * ```javascript - * function(mesh) { // do things - * return; } - * ``` - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Gets the current list of angular speed gradients. + * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list + * @returns the list of angular speed gradients */ - static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void): GroundMesh; + getAngularSpeedGradients(): Nullable>; /** - * Creates a tube mesh. - * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube. - * The parameter `radius` (positive float, default 1) sets the tube radius size. - * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface. - * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`. - * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. - * It must return a radius value (positive float) : - * ```javascript - * var radiusFunction = function(i, distance) { - * // do things - * return radius; } - * ``` - * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Adds a new angular speed gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system */ - static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { - (i: number, distance: number): number; - }, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; + addAngularSpeedGradient(gradient: number, factor: number, factor2?: number): IParticleSystem; /** - * Creates a polyhedron mesh. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial - * to choose the wanted type. - * The parameter `size` (positive float, default 1) sets the polygon size. - * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value). - * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`. - * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron - * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`). - * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors - * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored. - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Remove a specific angular speed gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - static CreatePolyhedron(name: string, options: { - type?: number; - size?: number; - sizeX?: number; - sizeY?: number; - sizeZ?: number; - custom?: any; - faceUV?: Vector4[]; - faceColors?: Color4[]; - updatable?: boolean; - sideOrientation?: number; - }, scene: Scene): Mesh; + removeAngularSpeedGradient(gradient: number): IParticleSystem; /** - * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided. - * Please consider using the same method from the MeshBuilder class instead. - * The parameter `radius` sets the radius size (float) of the icosphere (default 1). - * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`). - * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size. - * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface. - * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Gets the current list of velocity gradients. + * You must use addVelocityGradient and removeVelocityGradient to udpate this list + * @returns the list of velocity gradients */ - static CreateIcoSphere(name: string, options: { - radius?: number; - flat?: boolean; - subdivisions?: number; - sideOrientation?: number; - updatable?: boolean; - }, scene: Scene): Mesh; + getVelocityGradients(): Nullable>; /** - * Creates a decal mesh. - * Please consider using the same method from the MeshBuilder class instead. - * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal. - * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates. - * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates. - * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling. - * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal. + * Adds a new velocity gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system */ - static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh; + addVelocityGradient(gradient: number, factor: number, factor2?: number): IParticleSystem; /** - * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. + * Remove a specific velocity gradient + * @param gradient defines the gradient to remove + * @returns the current particle system */ - setPositionsForCPUSkinning(): Float32Array; + removeVelocityGradient(gradient: number): IParticleSystem; + } +} + +declare module BABYLON { + /** + * A particle represents one of the element emitted by a particle system. + * This is mainly define by its coordinates, direction, velocity and age. + */ + class Particle { /** - * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. + * particleSystem the particle system the particle belongs to. */ - setNormalsForCPUSkinning(): Float32Array; + particleSystem: ParticleSystem; /** - * Updates the vertex buffer by applying transformation from the bones. - * Returns the Mesh. - * - * @param {skeleton} skeleton to apply + * The world position of the particle in the scene. */ - applySkeleton(skeleton: Skeleton): Mesh; + position: Vector3; /** - * Returns an object `{min:` Vector3`, max:` Vector3`}` - * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system + * The world direction of the particle in the scene. */ - static MinMax(meshes: AbstractMesh[]): { - min: Vector3; - max: Vector3; - }; + direction: Vector3; /** - * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array. + * The color of the particle. */ - static Center(meshesOrMinMaxVector: { - min: Vector3; - max: Vector3; - } | AbstractMesh[]): Vector3; + color: Color4; /** - * Merge the array of meshes into a single mesh for performance reasons. - * @param {Array} meshes - The vertices source. They should all be of the same material. Entries can empty - * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes - * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true. - * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class. - * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source. + * The color change of the particle per step. */ - static MergeMeshes(meshes: Array, disposeSource?: boolean, allow32BitsIndices?: boolean, meshSubclass?: Mesh, subdivideWithSubMeshes?: boolean): Nullable; + colorStep: Color4; + /** + * Defines how long will the life of the particle be. + */ + lifeTime: number; + /** + * The current age of the particle. + */ + age: number; + /** + * The current size of the particle. + */ + size: number; + /** + * The current scale of the particle. + */ + scale: Vector2; + /** + * The current angle of the particle. + */ + angle: number; + /** + * Defines how fast is the angle changing. + */ + angularSpeed: number; + /** + * Defines the cell index used by the particle to be rendered from a sprite. + */ + cellIndex: number; + /** @hidden */ + _initialDirection: Nullable; + /** @hidden */ + _initialStartSpriteCellID: number; + _initialEndSpriteCellID: number; + /** @hidden */ + _currentColorGradient: Nullable; + /** @hidden */ + _currentColor1: Color4; + /** @hidden */ + _currentColor2: Color4; + /** @hidden */ + _currentSizeGradient: Nullable; + /** @hidden */ + _currentSize1: number; + /** @hidden */ + _currentSize2: number; + /** @hidden */ + _currentAngularSpeedGradient: Nullable; + /** @hidden */ + _currentAngularSpeed1: number; + /** @hidden */ + _currentAngularSpeed2: number; + /** @hidden */ + _currentVelocityGradient: Nullable; + /** @hidden */ + _currentVelocity1: number; + /** @hidden */ + _currentVelocity2: number; + /** + * Creates a new instance Particle + * @param particleSystem the particle system the particle belongs to + */ + constructor( + /** + * particleSystem the particle system the particle belongs to. + */ + particleSystem: ParticleSystem); + private updateCellInfoFromSystem; + /** + * Defines how the sprite cell index is updated for the particle + */ + updateCellIndex(): void; + /** + * Copy the properties of particle to another one. + * @param other the particle to copy the information to. + */ + copyTo(other: Particle): void; } } declare module BABYLON { /** - * Define an interface for all classes that will get and set the data on vertices + * This class is made for on one-liner static method to help creating particle system set. */ - interface IGetSetVerticesData { - isVerticesDataPresent(kind: string): boolean; - getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable; - getIndices(copyWhenShared?: boolean): Nullable; - setVerticesData(kind: string, data: FloatArray, updatable: boolean): void; - updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): void; - setIndices(indices: IndicesArray, totalVertices: Nullable, updatable?: boolean): void; + class ParticleHelper { + /** + * Gets or sets base Assets URL + */ + static BaseAssetsUrl: string; + /** + * Create a default particle system that you can tweak + * @param emitter defines the emitter to use + * @param capacity defines the system capacity (default is 500 particles) + * @param scene defines the hosting scene + * @returns the new Particle system + */ + static CreateDefault(emitter: Nullable, capacity?: number, scene?: Scene): ParticleSystem; + /** + * This is the main static method (one-liner) of this helper to create different particle systems + * @param type This string represents the type to the particle system to create + * @param scene The scene where the particle system should live + * @param gpu If the system will use gpu + * @returns the ParticleSystemSet created + */ + static CreateAsync(type: string, scene: Nullable, gpu?: boolean): Promise; + /** + * Static function used to export a particle system to a ParticleSystemSet variable. + * Please note that the emitter shape is not exported + * @param system defines the particle systems to export + */ + static ExportSet(systems: IParticleSystem[]): ParticleSystemSet; } +} + +declare module BABYLON { /** - * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance + * This represents a particle system in Babylon. + * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. + * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function. + * @example https://doc.babylonjs.com/babylon101/particles */ - class VertexData { + class ParticleSystem implements IDisposable, IAnimatable, IParticleSystem { /** - * An array of the x, y, z position of each vertex [...., x, y, z, .....] + * Source color is added to the destination color without alpha affecting the result. */ - positions: Nullable; + static BLENDMODE_ONEONE: number; /** - * An array of the x, y, z normal vector of each vertex [...., x, y, z, .....] + * Blend current color and particle color using particle’s alpha. */ - normals: Nullable; + static BLENDMODE_STANDARD: number; /** - * An array of the x, y, z tangent vector of each vertex [...., x, y, z, .....] + * Add current color and particle color multiplied by particle’s alpha. */ - tangents: Nullable; + static BLENDMODE_ADD: number; /** - * An array of u,v which maps a texture image onto each vertex [...., u, v, .....] + * List of animations used by the particle system. */ - uvs: Nullable; + animations: Animation[]; /** - * A second array of u,v which maps a texture image onto each vertex [...., u, v, .....] + * The id of the Particle system. */ - uvs2: Nullable; + id: string; /** - * A third array of u,v which maps a texture image onto each vertex [...., u, v, .....] + * The friendly name of the Particle system. */ - uvs3: Nullable; + name: string; /** - * A fourth array of u,v which maps a texture image onto each vertex [...., u, v, .....] + * The rendering group used by the Particle system to chose when to render. */ - uvs4: Nullable; + renderingGroupId: number; /** - * A fifth array of u,v which maps a texture image onto each vertex [...., u, v, .....] + * The emitter represents the Mesh or position we are attaching the particle system to. */ - uvs5: Nullable; + emitter: Nullable; /** - * A sixth array of u,v which maps a texture image onto each vertex [...., u, v, .....] + * The maximum number of particles to emit per frame */ - uvs6: Nullable; + emitRate: number; /** - * An array of the r, g, b, a, color of each vertex [...., r, g, b, a, .....] + * If you want to launch only a few particles at once, that can be done, as well. */ - colors: Nullable; + manualEmitCount: number; /** - * An array containing the list of indices to the array of matrices produced by bones, each vertex have up to 4 indices (8 if the matricesIndicesExtra is set). + * The overall motion speed (0.01 is default update speed, faster updates = faster animation) */ - matricesIndices: Nullable; + updateSpeed: number; /** - * An array containing the list of weights defining the weight of each indexed matrix in the final computation + * The amount of time the particle system is running (depends of the overall update speed). */ - matricesWeights: Nullable; + targetStopDuration: number; /** - * An array extending the number of possible indices + * Specifies whether the particle system will be disposed once it reaches the end of the animation. */ - matricesIndicesExtra: Nullable; + disposeOnStop: boolean; /** - * An array extending the number of possible weights when the number of indices is extended + * Minimum power of emitting particles. */ - matricesWeightsExtra: Nullable; + minEmitPower: number; /** - * An array of i, j, k the three vertex indices required for each triangular facet [...., i, j, k .....] + * Maximum power of emitting particles. */ - indices: Nullable; + maxEmitPower: number; /** - * Uses the passed data array to set the set the values for the specified kind of data - * @param data a linear array of floating numbers - * @param kind the type of data that is being set, eg positions, colors etc + * Minimum life time of emitting particles. */ - set(data: FloatArray, kind: string): void; + minLifeTime: number; /** - * Associates the vertexData to the passed Mesh. - * Sets it as updatable or not (default `false`) - * @param mesh the mesh the vertexData is applied to - * @param updatable when used and having the value true allows new data to update the vertexData - * @returns the VertexData + * Maximum life time of emitting particles. */ - applyToMesh(mesh: Mesh, updatable?: boolean): VertexData; + maxLifeTime: number; /** - * Associates the vertexData to the passed Geometry. - * Sets it as updatable or not (default `false`) - * @param geometry the geometry the vertexData is applied to - * @param updatable when used and having the value true allows new data to update the vertexData - * @returns VertexData + * Minimum Size of emitting particles. */ - applyToGeometry(geometry: Geometry, updatable?: boolean): VertexData; + minSize: number; /** - * Updates the associated mesh - * @param mesh the mesh to be updated - * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false - * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false - * @returns VertexData + * Maximum Size of emitting particles. */ - updateMesh(mesh: Mesh, updateExtends?: boolean, makeItUnique?: boolean): VertexData; + maxSize: number; /** - * Updates the associated geometry - * @param geometry the geometry to be updated - * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false - * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false - * @returns VertexData. + * Minimum scale of emitting particles on X axis. */ - updateGeometry(geometry: Geometry, updateExtends?: boolean, makeItUnique?: boolean): VertexData; - private _applyTo(meshOrGeometry, updatable?); - private _update(meshOrGeometry, updateExtends?, makeItUnique?); + minScaleX: number; /** - * Transforms each position and each normal of the vertexData according to the passed Matrix - * @param matrix the transforming matrix - * @returns the VertexData + * Maximum scale of emitting particles on X axis. */ - transform(matrix: Matrix): VertexData; + maxScaleX: number; /** - * Merges the passed VertexData into the current one - * @param other the VertexData to be merged into the current one - * @returns the modified VertexData + * Minimum scale of emitting particles on Y axis. */ - merge(other: VertexData): VertexData; - private _mergeElement(source, other); - private _validate(); + minScaleY: number; /** - * Serializes the VertexData - * @returns a serialized object + * Maximum scale of emitting particles on Y axis. */ - serialize(): any; + maxScaleY: number; /** - * Extracts the vertexData from a mesh - * @param mesh the mesh from which to extract the VertexData - * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false - * @param forceCopy indicating that the VertexData must be cloned, optional, default false - * @returns the object VertexData associated to the passed mesh + * Gets or sets the minimal initial rotation in radians. */ - static ExtractFromMesh(mesh: Mesh, copyWhenShared?: boolean, forceCopy?: boolean): VertexData; + minInitialRotation: number; /** - * Extracts the vertexData from the geometry - * @param geometry the geometry from which to extract the VertexData - * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false - * @param forceCopy indicating that the VertexData must be cloned, optional, default false - * @returns the object VertexData associated to the passed mesh + * Gets or sets the maximal initial rotation in radians. */ - static ExtractFromGeometry(geometry: Geometry, copyWhenShared?: boolean, forceCopy?: boolean): VertexData; - private static _ExtractFrom(meshOrGeometry, copyWhenShared?, forceCopy?); + maxInitialRotation: number; /** - * Creates the VertexData for a Ribbon - * @param options an object used to set the following optional parameters for the ribbon, required but can be empty - * * pathArray array of paths, each of which an array of successive Vector3 - * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false - * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false - * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false - * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional - * * colors a linear array, of length 4 * number of vertices, of custom color values, optional - * @returns the VertexData of the ribbon + * Minimum angular speed of emitting particles (Z-axis rotation for each particle). */ - static CreateRibbon(options: { - pathArray: Vector3[][]; - closeArray?: boolean; - closePath?: boolean; - offset?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - invertUV?: boolean; - uvs?: Vector2[]; - colors?: Color4[]; - }): VertexData; + minAngularSpeed: number; /** - * Creates the VertexData for a box - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * size sets the width, height and depth of the box to the value of size, optional default 1 - * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size - * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size - * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size - * * faceUV an array of 6 Vector4 elements used to set different images to each box side - * * faceColors an array of 6 Color3 elements used to set different colors to each box side - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the box + * Maximum angular speed of emitting particles (Z-axis rotation for each particle). */ - static CreateBox(options: { - size?: number; - width?: number; - height?: number; - depth?: number; - faceUV?: Vector4[]; - faceColors?: Color4[]; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + maxAngularSpeed: number; /** - * Creates the VertexData for an ellipsoid, defaults to a sphere - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * segments sets the number of horizontal strips optional, default 32 - * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1 - * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter - * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter - * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter - * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1 - * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1 - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the ellipsoid + * The texture used to render each particle. (this can be a spritesheet) */ - static CreateSphere(options: { - segments?: number; - diameter?: number; - diameterX?: number; - diameterY?: number; - diameterZ?: number; - arc?: number; - slice?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + particleTexture: Nullable; /** - * Creates the VertexData for a cylinder, cone or prism - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * height sets the height (y direction) of the cylinder, optional, default 2 - * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter - * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter - * * diameter sets the diameter of the top and bottom of the cone, optional default 1 - * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 - * * subdivisions` the number of rings along the cylinder height, optional, default 1 - * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1 - * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively - * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively - * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false - * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the cylinder, cone or prism + * The layer mask we are rendering the particles through. */ - static CreateCylinder(options: { - height?: number; - diameterTop?: number; - diameterBottom?: number; - diameter?: number; - tessellation?: number; - subdivisions?: number; - arc?: number; - faceColors?: Color4[]; - faceUV?: Vector4[]; - hasRings?: boolean; - enclose?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + layerMask: number; /** - * Creates the VertexData for a torus - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * diameter the diameter of the torus, optional default 1 - * * thickness the diameter of the tube forming the torus, optional default 0.5 - * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the torus + * This can help using your own shader to render the particle system. + * The according effect will be created */ - static CreateTorus(options: { - diameter?: number; - thickness?: number; - tessellation?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + customShader: any; /** - * Creates the VertexData of the LineSystem - * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty - * - lines an array of lines, each line being an array of successive Vector3 - * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point - * @returns the VertexData of the LineSystem + * By default particle system starts as soon as they are created. This prevents the + * automatic start to happen and let you decide when to start emitting particles. */ - static CreateLineSystem(options: { - lines: Vector3[][]; - colors?: Nullable; - }): VertexData; + preventAutoStart: boolean; /** - * Create the VertexData for a DashedLines - * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty - * - points an array successive Vector3 - * - dashSize the size of the dashes relative to the dash number, optional, default 3 - * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1 - * - dashNb the intended total number of dashes, optional, default 200 - * @returns the VertexData for the DashedLines + * Gets or sets a texture used to add random noise to particle positions */ - static CreateDashedLines(options: { - points: Vector3[]; - dashSize?: number; - gapSize?: number; - dashNb?: number; - }): VertexData; + noiseTexture: Nullable; + /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ + noiseStrength: Vector3; /** - * Creates the VertexData for a Ground - * @param options an object used to set the following optional parameters for the Ground, required but can be empty - * - width the width (x direction) of the ground, optional, default 1 - * - height the height (z direction) of the ground, optional, default 1 - * - subdivisions the number of subdivisions per side, optional, default 1 - * @returns the VertexData of the Ground + * This function can be defined to provide custom update for active particles. + * This function will be called instead of regular update (age, position, color, etc.). + * Do not forget that this function will be called on every frame so try to keep it simple and fast :) */ - static CreateGround(options: { - width?: number; - height?: number; - subdivisions?: number; - subdivisionsX?: number; - subdivisionsY?: number; - }): VertexData; + updateFunction: (particles: Particle[]) => void; /** - * Creates the VertexData for a TiledGround by subdividing the ground into tiles - * @param options an object used to set the following optional parameters for the Ground, required but can be empty - * * xmin the ground minimum X coordinate, optional, default -1 - * * zmin the ground minimum Z coordinate, optional, default -1 - * * xmax the ground maximum X coordinate, optional, default 1 - * * zmax the ground maximum Z coordinate, optional, default 1 - * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6} - * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2} - * @returns the VertexData of the TiledGround + * Callback triggered when the particle animation is ending. */ - static CreateTiledGround(options: { - xmin: number; - zmin: number; - xmax: number; - zmax: number; - subdivisions?: { - w: number; - h: number; - }; - precision?: { - w: number; - h: number; - }; - }): VertexData; + onAnimationEnd: Nullable<() => void>; /** - * Creates the VertexData of the Ground designed from a heightmap - * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap - * * width the width (x direction) of the ground - * * height the height (z direction) of the ground - * * subdivisions the number of subdivisions per side - * * minHeight the minimum altitude on the ground, optional, default 0 - * * maxHeight the maximum altitude on the ground, optional default 1 - * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11) - * * buffer the array holding the image color data - * * bufferWidth the width of image - * * bufferHeight the height of image - * @returns the VertexData of the Ground designed from a heightmap + * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD. */ - static CreateGroundFromHeightMap(options: { - width: number; - height: number; - subdivisions: number; - minHeight: number; - maxHeight: number; - colorFilter: Color3; - buffer: Uint8Array; - bufferWidth: number; - bufferHeight: number; - }): VertexData; + blendMode: number; /** - * Creates the VertexData for a Plane - * @param options an object used to set the following optional parameters for the plane, required but can be empty - * * size sets the width and height of the plane to the value of size, optional default 1 - * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size - * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the box + * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls + * to override the particles. */ - static CreatePlane(options: { - size?: number; - width?: number; - height?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + forceDepthWrite: boolean; /** - * Creates the VertexData of the Disc or regular Polygon - * @param options an object used to set the following optional parameters for the disc, required but can be empty - * * radius the radius of the disc, optional default 0.5 - * * tessellation the number of polygon sides, optional, default 64 - * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1 - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the box + * You can use gravity if you want to give an orientation to your particles. */ - static CreateDisc(options: { - radius?: number; - tessellation?: number; - arc?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + gravity: Vector3; + private _emitterWorldMatrix; + private _colorGradients; + private _sizeGradients; + private _lifeTimeGradients; + private _angularSpeedGradients; + private _velocityGradients; /** - * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build() - * All parameters are provided by MeshBuilder.CreatePolygon as needed - * @param polygon a mesh built from polygonTriangulation.build() - * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively - * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively - * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the Polygon + * Gets the current list of color gradients. + * You must use addColorGradient and removeColorGradient to udpate this list + * @returns the list of color gradients */ - static CreatePolygon(polygon: Mesh, sideOrientation: number, fUV?: Vector4[], fColors?: Color4[], frontUVs?: Vector4, backUVs?: Vector4): VertexData; + getColorGradients(): Nullable>; /** - * Creates the VertexData of the IcoSphere - * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty - * * radius the radius of the IcoSphere, optional default 1 - * * radiusX allows stretching in the x direction, optional, default radius - * * radiusY allows stretching in the y direction, optional, default radius - * * radiusZ allows stretching in the z direction, optional, default radius - * * flat when true creates a flat shaded mesh, optional, default true - * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the IcoSphere + * Gets the current list of size gradients. + * You must use addSizeGradient and removeSizeGradient to udpate this list + * @returns the list of size gradients */ - static CreateIcoSphere(options: { - radius?: number; - radiusX?: number; - radiusY?: number; - radiusZ?: number; - flat?: boolean; - subdivisions?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + getSizeGradients(): Nullable>; /** - * Creates the VertexData for a Polyhedron - * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty - * * type provided types are: - * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1) - * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20) - * * size the size of the IcoSphere, optional default 1 - * * sizeX allows stretching in the x direction, optional, default size - * * sizeY allows stretching in the y direction, optional, default size - * * sizeZ allows stretching in the z direction, optional, default size - * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor - * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively - * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively - * * flat when true creates a flat shaded mesh, optional, default true - * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the Polyhedron + * Gets the current list of life time gradients. + * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list + * @returns the list of life time gradients */ - static CreatePolyhedron(options: { - type?: number; - size?: number; - sizeX?: number; - sizeY?: number; - sizeZ?: number; - custom?: any; - faceUV?: Vector4[]; - faceColors?: Color4[]; - flat?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + getLifeTimeGradients(): Nullable>; /** - * Creates the VertexData for a TorusKnot - * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty - * * radius the radius of the torus knot, optional, default 2 - * * tube the thickness of the tube, optional, default 0.5 - * * radialSegments the number of sides on each tube segments, optional, default 32 - * * tubularSegments the number of tubes to decompose the knot into, optional, default 32 - * * p the number of windings around the z axis, optional, default 2 - * * q the number of windings around the x axis, optional, default 3 - * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) - * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) - * @returns the VertexData of the Torus Knot + * Gets the current list of angular speed gradients. + * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list + * @returns the list of angular speed gradients */ - static CreateTorusKnot(options: { - radius?: number; - tube?: number; - radialSegments?: number; - tubularSegments?: number; - p?: number; - q?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }): VertexData; + getAngularSpeedGradients(): Nullable>; /** - * Compute normals for given positions and indices - * @param positions an array of vertex positions, [...., x, y, z, ......] - * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......] - * @param normals an array of vertex normals, [...., x, y, z, ......] - * @param options an object used to set the following optional parameters for the TorusKnot, optional - * * facetNormals : optional array of facet normals (vector3) - * * facetPositions : optional array of facet positions (vector3) - * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation - * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation - * * bInfo : optional bounding info, required for facetPartitioning computation - * * bbSize : optional bounding box size data, required for facetPartitioning computation - * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation - * * useRightHandedSystem: optional boolean to for right handed system computation - * * depthSort : optional boolean to enable the facet depth sort computation - * * distanceTo : optional Vector3 to compute the facet depth from this location - * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location + * Gets the current list of velocity gradients. + * You must use addVelocityGradient and removeVelocityGradient to udpate this list + * @returns the list of velocity gradients */ - static ComputeNormals(positions: any, indices: any, normals: any, options?: { - facetNormals?: any; - facetPositions?: any; - facetPartitioning?: any; - ratio?: number; - bInfo?: any; - bbSize?: Vector3; - subDiv?: any; - useRightHandedSystem?: boolean; - depthSort?: boolean; - distanceTo?: Vector3; - depthSortedFacets?: any; - }): void; - private static _ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs?, backUVs?); + getVelocityGradients(): Nullable>; /** - * Applies VertexData created from the imported parameters to the geometry - * @param parsedVertexData the parsed data from an imported file - * @param geometry the geometry to apply the VertexData to + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + * This only works when particleEmitterTyps is a BoxParticleEmitter */ - static ImportVertexData(parsedVertexData: any, geometry: Geometry): void; - } -} - -declare module BABYLON { - /** - * Class containing static functions to help procedurally build meshes - */ - class MeshBuilder { - private static updateSideOrientation(orientation?); + direction1: Vector3; /** - * Creates a box mesh - * * The parameter `size` sets the size (float) of each box side (default 1) - * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`) - * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements) - * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the box mesh + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + * This only works when particleEmitterTyps is a BoxParticleEmitter */ - static CreateBox(name: string, options: { - size?: number; - width?: number; - height?: number; - depth?: number; - faceUV?: Vector4[]; - faceColors?: Color4[]; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - updatable?: boolean; - }, scene?: Nullable): Mesh; + direction2: Vector3; /** - * Creates a sphere mesh - * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1) - * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`) - * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32) - * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio - * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude) - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the sphere mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere + * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. + * This only works when particleEmitterTyps is a BoxParticleEmitter */ - static CreateSphere(name: string, options: { - segments?: number; - diameter?: number; - diameterX?: number; - diameterY?: number; - diameterZ?: number; - arc?: number; - slice?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - updatable?: boolean; - }, scene: any): Mesh; + minEmitBox: Vector3; /** - * Creates a plane polygonal mesh. By default, this is a disc - * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5) - * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc - * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the plane polygonal mesh - * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon + * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. + * This only works when particleEmitterTyps is a BoxParticleEmitter */ - static CreateDisc(name: string, options: { - radius?: number; - tessellation?: number; - arc?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene?: Nullable): Mesh; + maxEmitBox: Vector3; /** - * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided - * * The parameter `radius` sets the radius size (float) of the icosphere (default 1) - * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`) - * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size - * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the icosahedron mesh - * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere + * Random color of each particle after it has been emitted, between color1 and color2 vectors */ - static CreateIcoSphere(name: string, options: { - radius?: number; - radiusX?: number; - radiusY?: number; - radiusZ?: number; - flat?: boolean; - subdivisions?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - updatable?: boolean; - }, scene: Scene): Mesh; + color1: Color4; /** - * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters - * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry - * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array - * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array - * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path - * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11 - * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture - * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones - * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values - * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry - * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the ribbon mesh - * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial - * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes + * Random color of each particle after it has been emitted, between color1 and color2 vectors */ - static CreateRibbon(name: string, options: { - pathArray: Vector3[][]; - closeArray?: boolean; - closePath?: boolean; - offset?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - instance?: Mesh; - invertUV?: boolean; - uvs?: Vector2[]; - colors?: Color4[]; - }, scene?: Nullable): Mesh; + color2: Color4; /** - * Creates a cylinder or a cone mesh - * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2). - * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1). - * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero. - * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance. - * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1). - * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces. - * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis. - * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder. - * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements). - * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3 - * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7 - * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17 - * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface. - * * If `enclose` is false, a ring surface is one element. - * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces. - * * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379 - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the cylinder mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone + * Color the particle will have at the end of its lifetime */ - static CreateCylinder(name: string, options: { - height?: number; - diameterTop?: number; - diameterBottom?: number; - diameter?: number; - tessellation?: number; - subdivisions?: number; - arc?: number; - faceColors?: Color4[]; - faceUV?: Vector4[]; - updatable?: boolean; - hasRings?: boolean; - enclose?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene: any): Mesh; + colorDead: Color4; /** - * Creates a torus mesh - * * The parameter `diameter` sets the diameter size (float) of the torus (default 1) - * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5) - * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16) - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the torus mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus + * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel */ - static CreateTorus(name: string, options: { - diameter?: number; - thickness?: number; - tessellation?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene: any): Mesh; + textureMask: Color4; /** - * Creates a torus knot mesh - * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2) - * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32) - * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32) - * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3) - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the torus knot mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot + * The particle emitter type defines the emitter used by the particle system. + * It can be for example box, sphere, or cone... */ - static CreateTorusKnot(name: string, options: { - radius?: number; - tube?: number; - radialSegments?: number; - tubularSegments?: number; - p?: number; - q?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene: any): Mesh; + particleEmitterType: IParticleEmitterType; /** - * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh - * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter - * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function - * * The parameter `lines` is an array of lines, each line being an array of successive Vector3 - * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter - * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point - * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster) - * * Updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines - * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system - * @param name defines the name of the new line system - * @param options defines the options used to create the line system - * @param scene defines the hosting scene - * @returns a new line system mesh + * This function can be defined to specify initial direction for every new particle. + * It by default use the emitterType defined function */ - static CreateLineSystem(name: string, options: { - lines: Vector3[][]; - updatable?: boolean; - instance?: Nullable; - colors?: Nullable; - useVertexAlpha?: boolean; - }, scene: Nullable): LinesMesh; + startDirectionFunction: (worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle) => void; /** - * Creates a line mesh - * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter - * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function - * * The parameter `points` is an array successive Vector3 - * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines - * * The optional parameter `colors` is an array of successive Color4, one per line point - * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster) - * * When updating an instance, remember that only point positions can change, not the number of points - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines - * @param name defines the name of the new line system - * @param options defines the options used to create the line system - * @param scene defines the hosting scene - * @returns a new line mesh + * This function can be defined to specify initial position for every new particle. + * It by default use the emitterType defined function */ - static CreateLines(name: string, options: { - points: Vector3[]; - updatable?: boolean; - instance?: Nullable; - colors?: Color4[]; - useVertexAlpha?: boolean; - }, scene?: Nullable): LinesMesh; + startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle) => void; /** - * Creates a dashed line mesh - * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter - * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function - * * The parameter `points` is an array successive Vector3 - * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200) - * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3) - * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1) - * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines - * * When updating an instance, remember that only point positions can change, not the number of points - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the dashed line mesh - * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines + * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime) */ - static CreateDashedLines(name: string, options: { - points: Vector3[]; - dashSize?: number; - gapSize?: number; - dashNb?: number; - updatable?: boolean; - instance?: LinesMesh; - }, scene?: Nullable): LinesMesh; + spriteCellChangeSpeed: number; /** - * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. - * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis. - * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. - * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve. - * * The parameter `scale` (float, default 1) is the value to scale the shape. - * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape - * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture. - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the extruded shape mesh - * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes - * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes - * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes + * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display */ - static ExtrudeShape(name: string, options: { - shape: Vector3[]; - path: Vector3[]; - scale?: number; - rotation?: number; - cap?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - instance?: Mesh; - invertUV?: boolean; - }, scene?: Nullable): Mesh; + startSpriteCellID: number; /** - * Creates an custom extruded shape mesh. - * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. - * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis. - * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. - * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path - * * It must returns a float value that will be the rotation in radians applied to the shape on each path point. - * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path - * * It must returns a float value that will be the scale value applied to the shape on each path point - * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray` - * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray` - * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape - * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the custom extruded shape mesh - * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes - * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes - * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes + * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display */ - static ExtrudeShapeCustom(name: string, options: { - shape: Vector3[]; - path: Vector3[]; - scaleFunction?: any; - rotationFunction?: any; - ribbonCloseArray?: boolean; - ribbonClosePath?: boolean; - cap?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - instance?: Mesh; - invertUV?: boolean; - }, scene: Scene): Mesh; + endSpriteCellID: number; /** - * Creates lathe mesh. - * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe - * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero - * * The parameter `radius` (positive float, default 1) is the radius value of the lathe - * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe - * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides - * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape - * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc" - * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the lathe mesh - * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use */ - static CreateLathe(name: string, options: { - shape: Vector3[]; - radius?: number; - tessellation?: number; - clip?: number; - arc?: number; - closed?: boolean; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - cap?: number; - invertUV?: boolean; - }, scene: Scene): Mesh; + spriteCellWidth: number; /** - * Creates a plane mesh - * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1) - * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`) - * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the plane mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use */ - static CreatePlane(name: string, options: { - size?: number; - width?: number; - height?: number; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - updatable?: boolean; - sourcePlane?: Plane; - }, scene: Scene): Mesh; + spriteCellHeight: number; + /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */ + preWarmCycles: number; + /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */ + preWarmStepOffset: number; + /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ + translationPivot: Vector2; /** - * Creates a ground mesh - * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground - * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the ground mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane + * An event triggered when the system is disposed + */ + onDisposeObservable: Observable; + private _onDisposeObserver; + /** + * Sets a callback that will be triggered when the system is disposed */ - static CreateGround(name: string, options: { - width?: number; - height?: number; - subdivisions?: number; - subdivisionsX?: number; - subdivisionsY?: number; - updatable?: boolean; - }, scene: any): Mesh; + onDispose: () => void; /** - * Creates a tiled ground mesh - * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates - * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates - * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile - * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the tiled ground mesh - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground + * Gets or sets whether an animation sprite sheet is enabled or not on the particle system */ - static CreateTiledGround(name: string, options: { - xmin: number; - zmin: number; - xmax: number; - zmax: number; - subdivisions?: { - w: number; - h: number; - }; - precision?: { - w: number; - h: number; - }; - updatable?: boolean; - }, scene: Scene): Mesh; + isAnimationSheetEnabled: boolean; /** - * Creates a ground mesh from a height map - * * The parameter `url` sets the URL of the height map image resource. - * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes. - * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side. - * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground. - * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground. - * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height. - * * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time). - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param url defines the url to the height map - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the ground mesh - * @see http://doc.babylonjs.com/babylon101/height_map - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map + * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction */ - static CreateGroundFromHeightMap(name: string, url: string, options: { - width?: number; - height?: number; - subdivisions?: number; - minHeight?: number; - maxHeight?: number; - colorFilter?: Color3; - updatable?: boolean; - onReady?: (mesh: GroundMesh) => void; - }, scene: Scene): GroundMesh; + isBillboardBased: boolean; /** - * Creates a polygon mesh - * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh - * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors - * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4) - * * Remember you can only change the shape positions, not their number when updating a polygon - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the polygon mesh + * Get hosting scene + * @returns the scene */ - static CreatePolygon(name: string, options: { - shape: Vector3[]; - holes?: Vector3[][]; - depth?: number; - faceUV?: Vector4[]; - faceColors?: Color4[]; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene: Scene): Mesh; + getScene(): Scene; /** - * Creates an extruded polygon mesh, with depth in the Y direction. - * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements) - * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the polygon mesh + * Gets or sets the billboard mode to use when isBillboardBased = true. + * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far */ - static ExtrudePolygon(name: string, options: { - shape: Vector3[]; - holes?: Vector3[][]; - depth?: number; - faceUV?: Vector4[]; - faceColors?: Color4[]; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene: Scene): Mesh; + billboardMode: number; + private _particles; + private _epsilon; + private _capacity; + private _scene; + private _stockParticles; + private _newPartsExcess; + private _vertexData; + private _vertexBuffer; + private _vertexBuffers; + private _spriteBuffer; + private _indexBuffer; + private _effect; + private _customEffect; + private _cachedDefines; + private _scaledColorStep; + private _colorDiff; + private _scaledDirection; + private _scaledGravity; + private _currentRenderId; + private _alive; + private _useInstancing; + private _started; + private _stopped; + private _actualFrame; + private _scaledUpdateSpeed; + private _vertexBufferSize; + private _isAnimationSheetEnabled; + private _isBillboardBased; /** - * Creates a tube mesh. - * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters - * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube - * * The parameter `radius` (positive float, default 1) sets the tube radius size - * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface - * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius` - * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float) - * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc - * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL - * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the tube mesh - * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes - * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube + * this is the Sub-emitters templates that will be used to generate particle system when the particle dies, this property is used by the root particle system only. */ - static CreateTube(name: string, options: { - path: Vector3[]; - radius?: number; - tessellation?: number; - radiusFunction?: { - (i: number, distance: number): number; - }; - cap?: number; - arc?: number; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - instance?: Mesh; - invertUV?: boolean; - }, scene: Scene): Mesh; + subEmitters: ParticleSystem[]; /** - * Creates a polyhedron mesh - * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type - * * The parameter `size` (positive float, default 1) sets the polygon size - * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value) - * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type` - * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron - * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`) - * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors - * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the polyhedron mesh - * @see http://doc.babylonjs.com/how_to/polyhedra_shapes + * The current active Sub-systems, this property is used by the root particle system only. + */ + activeSubSystems: Array; + private _rootParticleSystem; + /** + * Gets the current list of active particles */ - static CreatePolyhedron(name: string, options: { - type?: number; - size?: number; - sizeX?: number; - sizeY?: number; - sizeZ?: number; - custom?: any; - faceUV?: Vector4[]; - faceColors?: Color4[]; - flat?: boolean; - updatable?: boolean; - sideOrientation?: number; - frontUVs?: Vector4; - backUVs?: Vector4; - }, scene: Scene): Mesh; + readonly particles: Particle[]; /** - * Creates a decal mesh. - * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal - * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates - * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates - * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling - * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal - * @param name defines the name of the mesh - * @param sourceMesh defines the mesh where the decal must be applied - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns the decal mesh - * @see http://doc.babylonjs.com/how_to/decals + * Returns the string "ParticleSystem" + * @returns a string containing the class name */ - static CreateDecal(name: string, sourceMesh: AbstractMesh, options: { - position?: Vector3; - normal?: Vector3; - size?: Vector3; - angle?: number; - }): Mesh; - private static _ExtrudeShapeGeneric(name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs); - } -} - -declare module BABYLON { - class MeshLODLevel { - distance: number; - mesh: Nullable; - constructor(distance: number, mesh: Nullable); - } -} - -declare module BABYLON { - /** - * A simplifier interface for future simplification implementations. - */ - interface ISimplifier { + getClassName(): string; /** - * Simplification of a given mesh according to the given settings. - * Since this requires computation, it is assumed that the function runs async. - * @param settings The settings of the simplification, including quality and distance - * @param successCallback A callback that will be called after the mesh was simplified. - * @param errorCallback in case of an error, this callback will be called. optional. + * Instantiates a particle system. + * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. + * @param name The name of the particle system + * @param capacity The max number of particles alive at the same time + * @param scene The scene the particle system belongs to + * @param customEffect a custom effect used to change the way particles are rendered by default + * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture + * @param epsilon Offset used to render the particles */ - simplify(settings: ISimplificationSettings, successCallback: (simplifiedMeshes: Mesh) => void, errorCallback?: () => void): void; - } - /** - * Expected simplification settings. - * Quality should be between 0 and 1 (1 being 100%, 0 being 0%); - */ - interface ISimplificationSettings { - quality: number; - distance: number; - optimizeMesh?: boolean; - } - class SimplificationSettings implements ISimplificationSettings { - quality: number; - distance: number; - optimizeMesh: boolean | undefined; - constructor(quality: number, distance: number, optimizeMesh?: boolean | undefined); - } - interface ISimplificationTask { - settings: Array; - simplificationType: SimplificationType; - mesh: Mesh; - successCallback?: () => void; - parallelProcessing: boolean; - } - class SimplificationQueue { - private _simplificationArray; - running: boolean; - constructor(); - addTask(task: ISimplificationTask): void; - executeNext(): void; - runSimplification(task: ISimplificationTask): void; - private getSimplifier(task); - } - /** - * The implemented types of simplification - * At the moment only Quadratic Error Decimation is implemented - */ - enum SimplificationType { - /** Quadratic error decimation */ - QUADRATIC = 0, - } - class DecimationTriangle { - vertices: Array; - normal: Vector3; - error: Array; - deleted: boolean; - isDirty: boolean; - borderFactor: number; - deletePending: boolean; - originalOffset: number; - constructor(vertices: Array); - } - class DecimationVertex { - position: Vector3; - id: number; - q: QuadraticMatrix; - isBorder: boolean; - triangleStart: number; - triangleCount: number; - originalOffsets: Array; - constructor(position: Vector3, id: number); - updatePosition(newPosition: Vector3): void; - } - class QuadraticMatrix { - data: Array; - constructor(data?: Array); - det(a11: number, a12: number, a13: number, a21: number, a22: number, a23: number, a31: number, a32: number, a33: number): number; - addInPlace(matrix: QuadraticMatrix): void; - addArrayInPlace(data: Array): void; - add(matrix: QuadraticMatrix): QuadraticMatrix; - static FromData(a: number, b: number, c: number, d: number): QuadraticMatrix; - static DataFromNumbers(a: number, b: number, c: number, d: number): number[]; - } - class Reference { - vertexId: number; - triangleId: number; - constructor(vertexId: number, triangleId: number); - } - /** - * An implementation of the Quadratic Error simplification algorithm. - * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf - * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS - * @author RaananW - */ - class QuadraticErrorSimplification implements ISimplifier { - private _mesh; - private triangles; - private vertices; - private references; - private _reconstructedMesh; - syncIterations: number; - aggressiveness: number; - decimationIterations: number; - boundingBoxEpsilon: number; - constructor(_mesh: Mesh); - simplify(settings: ISimplificationSettings, successCallback: (simplifiedMesh: Mesh) => void): void; - private runDecimation(settings, submeshIndex, successCallback); - private initWithMesh(submeshIndex, callback, optimizeMesh?); - private init(callback); - private reconstructMesh(submeshIndex); - private initDecimatedMesh(); - private isFlipped(vertex1, vertex2, point, deletedArray, borderFactor, delTr); - private updateTriangles(origVertex, vertex, deletedArray, deletedTriangles); - private identifyBorder(); - private updateMesh(identifyBorders?); - private vertexError(q, point); - private calculateError(vertex1, vertex2, pointResult?, normalResult?, uvResult?, colorResult?); - } -} - -declare module BABYLON { - class Polygon { - static Rectangle(xmin: number, ymin: number, xmax: number, ymax: number): Vector2[]; - static Circle(radius: number, cx?: number, cy?: number, numberOfSides?: number): Vector2[]; - static Parse(input: string): Vector2[]; - static StartingAt(x: number, y: number): Path2; - } - class PolygonMeshBuilder { - private _points; - private _outlinepoints; - private _holes; - private _name; - private _scene; - private _epoints; - private _eholes; - private _addToepoint(points); - constructor(name: string, contours: Path2, scene: Scene); - constructor(name: string, contours: Vector2[], scene: Scene); - addHole(hole: Vector2[]): PolygonMeshBuilder; - build(updatable?: boolean, depth?: number): Mesh; - private addSide(positions, normals, uvs, indices, bounds, points, depth, flip); - } -} - -declare module BABYLON { - class BaseSubMesh { - _materialDefines: Nullable; - _materialEffect: Nullable; - readonly effect: Nullable; - setEffect(effect: Nullable, defines?: Nullable): void; - } - class SubMesh extends BaseSubMesh implements ICullable { - materialIndex: number; - verticesStart: number; - verticesCount: number; - indexStart: number; - indexCount: number; - linesIndexCount: number; - private _mesh; - private _renderingMesh; - private _boundingInfo; - private _linesIndexBuffer; - _lastColliderWorldVertices: Nullable; - _trianglePlanes: Plane[]; - _lastColliderTransformMatrix: Matrix; - _renderId: number; - _alphaIndex: number; - _distanceToCamera: number; - _id: number; - private _currentMaterial; - static AddToMesh(materialIndex: number, verticesStart: number, verticesCount: number, indexStart: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox?: boolean): SubMesh; - constructor(materialIndex: number, verticesStart: number, verticesCount: number, indexStart: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox?: boolean); - readonly IsGlobal: boolean; + constructor(name: string, capacity: number, scene: Scene, customEffect?: Nullable, isAnimationSheetEnabled?: boolean, epsilon?: number); + private _fetchR; + private _addFactorGradient; + private _removeFactorGradient; /** - * Returns the submesh BoudingInfo object. + * Adds a new life time gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the life time factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system */ - getBoundingInfo(): BoundingInfo; + addLifeTimeGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; + /** + * Remove a specific life time gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeLifeTimeGradient(gradient: number): ParticleSystem; + /** + * Adds a new size gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system + */ + addSizeGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; + /** + * Remove a specific size gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeSizeGradient(gradient: number): ParticleSystem; + /** + * Adds a new angular speed gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system + */ + addAngularSpeedGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; + /** + * Remove a specific angular speed gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeAngularSpeedGradient(gradient: number): ParticleSystem; + /** + * Adds a new velocity gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system + */ + addVelocityGradient(gradient: number, factor: number, factor2?: number): ParticleSystem; + /** + * Remove a specific velocity gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeVelocityGradient(gradient: number): ParticleSystem; + /** + * Adds a new color gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param color defines the color to affect to the specified gradient + * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from + */ + addColorGradient(gradient: number, color: Color4, color2?: Color4): ParticleSystem; + /** + * Remove a specific color gradient + * @param gradient defines the gradient to remove + */ + removeColorGradient(gradient: number): ParticleSystem; + private _resetEffect; + private _createVertexBuffers; + private _createIndexBuffer; + /** + * Gets the maximum number of particles active at the same time. + * @returns The max number of active particles. + */ + getCapacity(): number; + /** + * Gets Wether there are still active particles in the system. + * @returns True if it is alive, otherwise false. + */ + isAlive(): boolean; + /** + * Gets Wether the system has been started. + * @returns True if it has been started, otherwise false. + */ + isStarted(): boolean; + /** + * Starts the particle system and begins to emit + * @param delay defines the delay in milliseconds before starting the system (0 by default) + */ + start(delay?: number): void; + /** + * Stops the particle system. + * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true. + */ + stop(stopSubEmitters?: boolean): void; + /** + * Remove all active particles + */ + reset(): void; + /** + * @hidden (for internal use only) + */ + _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void; + /** + * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list. + * Its lifetime will start back at 0. + */ + recycleParticle: (particle: Particle) => void; + private _stopSubEmitters; + private _createParticle; + private _removeFromRoot; + private _emitFromParticle; + private _update; + /** @hidden */ + static _GetAttributeNamesOrOptions(isAnimationSheetEnabled?: boolean, isBillboardBased?: boolean): string[]; + static _GetEffectCreationOptions(isAnimationSheetEnabled?: boolean): string[]; + private _getEffect; /** - * Sets the submesh BoundingInfo. - * Return the SubMesh. + * Animates the particle system for the current frame by emitting new particles and or animating the living ones. + * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false) */ - setBoundingInfo(boundingInfo: BoundingInfo): SubMesh; + animate(preWarmOnly?: boolean): void; + private _appendParticleVertices; /** - * Returns the mesh of the current submesh. + * Rebuilds the particle system. */ - getMesh(): AbstractMesh; + rebuild(): void; /** - * Returns the rendering mesh of the submesh. + * Is this system ready to be used/rendered + * @return true if the system is ready */ - getRenderingMesh(): Mesh; + isReady(): boolean; /** - * Returns the submesh material. + * Renders the particle system in its current state. + * @returns the current number of particles */ - getMaterial(): Nullable; + render(): number; /** - * Sets a new updated BoundingInfo object to the submesh. - * Returns the SubMesh. + * Disposes the particle system and free the associated resources + * @param disposeTexture defines if the particule texture must be disposed as well (true by default) */ - refreshBoundingInfo(): SubMesh; - _checkCollision(collider: Collider): boolean; + dispose(disposeTexture?: boolean): void; /** - * Updates the submesh BoundingInfo. - * Returns the Submesh. + * Creates a Point Emitter for the particle system (emits directly from the emitter position) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the box + * @param direction2 Particles are emitted between the direction1 and direction2 from within the box + * @returns the emitter */ - updateBoundingInfo(world: Matrix): SubMesh; + createPointEmitter(direction1: Vector3, direction2: Vector3): PointParticleEmitter; /** - * True is the submesh bounding box intersects the frustum defined by the passed array of planes. - * Boolean returned. + * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius) + * @param radius The radius of the hemisphere to emit from + * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius + * @returns the emitter */ - isInFrustum(frustumPlanes: Plane[]): boolean; + createHemisphericEmitter(radius?: number, radiusRange?: number): HemisphericParticleEmitter; /** - * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes. - * Boolean returned. + * Creates a Sphere Emitter for the particle system (emits along the sphere radius) + * @param radius The radius of the sphere to emit from + * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius + * @returns the emitter */ - isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; + createSphereEmitter(radius?: number, radiusRange?: number): SphereParticleEmitter; /** - * Renders the submesh. - * Returns it. + * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2) + * @param radius The radius of the sphere to emit from + * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere + * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere + * @returns the emitter */ - render(enableAlphaMode: boolean): SubMesh; + createDirectedSphereEmitter(radius?: number, direction1?: Vector3, direction2?: Vector3): SphereDirectedParticleEmitter; /** - * Returns a new Index Buffer. - * Type returned : WebGLBuffer. + * Creates a Cone Emitter for the particle system (emits from the cone to the particle position) + * @param radius The radius of the cone to emit from + * @param angle The base angle of the cone + * @returns the emitter */ - getLinesIndexBuffer(indices: IndicesArray, engine: Engine): WebGLBuffer; + createConeEmitter(radius?: number, angle?: number): ConeParticleEmitter; /** - * True is the passed Ray intersects the submesh bounding box. - * Boolean returned. + * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the box + * @param direction2 Particles are emitted between the direction1 and direction2 from within the box + * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox + * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox + * @returns the emitter */ - canIntersects(ray: Ray): boolean; + createBoxEmitter(direction1: Vector3, direction2: Vector3, minEmitBox: Vector3, maxEmitBox: Vector3): BoxParticleEmitter; /** - * Returns an object IntersectionInfo. + * Clones the particle system. + * @param name The name of the cloned object + * @param newEmitter The new emitter to use + * @returns the cloned particle system */ - intersects(ray: Ray, positions: Vector3[], indices: IndicesArray, fastCheck?: boolean): Nullable; - _rebuild(): void; + clone(name: string, newEmitter: any): ParticleSystem; /** - * Creates a new Submesh from the passed Mesh. + * Serializes the particle system to a JSON object. + * @returns the JSON object */ - clone(newMesh: AbstractMesh, newRenderingMesh?: Mesh): SubMesh; + serialize(): any; + /** @hidden */ + static _Serialize(serializationObject: any, particleSystem: IParticleSystem): void; + /** @hidden */ + static _Parse(parsedParticleSystem: any, particleSystem: IParticleSystem, scene: Scene, rootUrl: string): void; /** - * Disposes the Submesh. - * Returns nothing. + * Parses a JSON object to create a particle system. + * @param parsedParticleSystem The JSON object to parse + * @param scene The scene to create the particle system in + * @param rootUrl The root url to use to load external dependencies like texture + * @returns the Parsed particle system */ - dispose(): void; + static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): ParticleSystem; + } +} + +declare module BABYLON { + interface Engine { /** - * Creates a new Submesh from the passed parameters : - * - materialIndex (integer) : the index of the main mesh material. - * - startIndex (integer) : the index where to start the copy in the mesh indices array. - * - indexCount (integer) : the number of indices to copy then from the startIndex. - * - mesh (Mesh) : the main mesh to create the submesh from. - * - renderingMesh (optional Mesh) : rendering mesh. + * Create an effect to use with particle systems. + * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration + * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx) + * @param uniformsNames defines a list of attribute names + * @param samplers defines an array of string used to represent textures + * @param defines defines the string containing the defines to use to compile the shaders + * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails + * @param onCompiled defines a function to call when the effect creation is successful + * @param onError defines a function to call when the effect creation has failed + * @returns the new Effect */ - static CreateFromIndices(materialIndex: number, startIndex: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh): SubMesh; + createEffectForParticles(fragmentName: string, uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect; } } declare module BABYLON { - class TransformNode extends Node { - static BILLBOARDMODE_NONE: number; - static BILLBOARDMODE_X: number; - static BILLBOARDMODE_Y: number; - static BILLBOARDMODE_Z: number; - static BILLBOARDMODE_ALL: number; - private _forward; - private _forwardInverted; - private _up; - private _right; - private _rightInverted; - private _rotation; - private _rotationQuaternion; - protected _scaling: Vector3; - protected _isDirty: boolean; - private _transformToBoneReferal; - /** - * Set the billboard mode. Default is 0. - * - * | Value | Type | Description | - * | --- | --- | --- | - * | 0 | BILLBOARDMODE_NONE | | - * | 1 | BILLBOARDMODE_X | | - * | 2 | BILLBOARDMODE_Y | | - * | 4 | BILLBOARDMODE_Z | | - * | 7 | BILLBOARDMODE_ALL | | - * - */ - billboardMode: number; - scalingDeterminant: number; - infiniteDistance: boolean; + /** + * Represents a set of particle systems working together to create a specific effect + */ + class ParticleSystemSet implements IDisposable { + private _emitterCreationOptions; + private _emitterNode; /** - * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored. - * By default the system will update normals to compensate + * Gets the particle system list */ - ignoreNonUniformScaling: boolean; - position: Vector3; - _poseMatrix: Matrix; - private _localWorld; - _worldMatrix: Matrix; - _worldMatrixDeterminant: number; - private _absolutePosition; - private _pivotMatrix; - private _pivotMatrixInverse; - private _postMultiplyPivotMatrix; - protected _isWorldMatrixFrozen: boolean; - /** - * An event triggered after the world matrix is updated - */ - onAfterWorldMatrixUpdateObservable: Observable; - constructor(name: string, scene?: Nullable, isPure?: boolean); + systems: IParticleSystem[]; /** - * Gets a string idenfifying the name of the class - * @returns "TransformNode" string + * Gets the emitter node used with this set */ - getClassName(): string; + readonly emitterNode: Nullable; /** - * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z. - * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector! - * Default : (0.0, 0.0, 0.0) - */ - rotation: Vector3; + * Creates a new emitter mesh as a sphere + * @param options defines the options used to create the sphere + * @param renderingGroupId defines the renderingGroupId to use for the sphere + * @param scene defines the hosting scene + */ + setEmitterAsSphere(options: { + diameter: number; + segments: number; + color: Color3; + }, renderingGroupId: number, scene: Scene): void; /** - * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z. - * Default : (1.0, 1.0, 1.0) + * Starts all particle systems of the set + * @param emitter defines an optional mesh to use as emitter for the particle systems */ + start(emitter?: AbstractMesh): void; /** - * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z. - * Default : (1.0, 1.0, 1.0) - */ - scaling: Vector3; + * Release all associated resources + */ + dispose(): void; /** - * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion. - * It's null by default. - * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0) + * Serialize the set into a JSON compatible object + * @returns a JSON compatible representation of the set */ - rotationQuaternion: Nullable; + serialize(): any; /** - * The forward direction of that transform in world space. + * Parse a new ParticleSystemSet from a serialized source + * @param data defines a JSON compatible representation of the set + * @param scene defines the hosting scene + * @param gpu defines if we want GPU particles or CPU particles + * @returns a new ParticleSystemSet */ - readonly forward: Vector3; + static Parse(data: any, scene: Scene, gpu?: boolean): ParticleSystemSet; + } +} + +declare module BABYLON { + /** + * Represents one particle of a solid particle system. + */ + class SolidParticle { /** - * The up direction of that transform in world space. + * particle global index */ - readonly up: Vector3; + idx: number; /** - * The right direction of that transform in world space. + * The color of the particle */ - readonly right: Vector3; + color: Nullable; /** - * Returns the latest update of the World matrix - * Returns a Matrix. + * The world space position of the particle. */ - getWorldMatrix(): Matrix; - /** @hidden */ - _getWorldMatrixDeterminant(): number; + position: Vector3; /** - * Returns directly the latest state of the mesh World matrix. - * A Matrix is returned. + * The world space rotation of the particle. (Not use if rotationQuaternion is set) */ - readonly worldMatrixFromCache: Matrix; + rotation: Vector3; /** - * Copies the paramater passed Matrix into the mesh Pose matrix. - * Returns the TransformNode. + * The world space rotation quaternion of the particle. */ - updatePoseMatrix(matrix: Matrix): TransformNode; + rotationQuaternion: Nullable; /** - * Returns the mesh Pose matrix. - * Returned object : Matrix + * The scaling of the particle. */ - getPoseMatrix(): Matrix; - _isSynchronized(): boolean; - _initCache(): void; - markAsDirty(property: string): TransformNode; + scaling: Vector3; /** - * Returns the current mesh absolute position. - * Retuns a Vector3. + * The uvs of the particle. */ - readonly absolutePosition: Vector3; + uvs: Vector4; /** - * Sets a new matrix to apply before all other transformation - * @param matrix defines the transform matrix - * @returns the current TransformNode + * The current speed of the particle. */ - setPreTransformMatrix(matrix: Matrix): TransformNode; + velocity: Vector3; /** - * Sets a new pivot matrix to the current node - * @param matrix defines the new pivot matrix to use - * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect - * @returns the current TransformNode - */ - setPivotMatrix(matrix: Matrix, postMultiplyPivotMatrix?: boolean): TransformNode; + * The pivot point in the particle local space. + */ + pivot: Vector3; /** - * Returns the mesh pivot matrix. - * Default : Identity. - * A Matrix is returned. + * Must the particle be translated from its pivot point in its local space ? + * In this case, the pivot point is set at the origin of the particle local space and the particle is translated. + * Default : false */ - getPivotMatrix(): Matrix; + translateFromPivot: boolean; /** - * Prevents the World matrix to be computed any longer. - * Returns the TransformNode. + * Is the particle active or not ? */ - freezeWorldMatrix(): TransformNode; + alive: boolean; /** - * Allows back the World matrix computation. - * Returns the TransformNode. + * Is the particle visible or not ? */ - unfreezeWorldMatrix(): this; + isVisible: boolean; /** - * True if the World matrix has been frozen. - * Returns a boolean. + * Index of this particle in the global "positions" array (Internal use) */ - readonly isWorldMatrixFrozen: boolean; + _pos: number; /** - * Retuns the mesh absolute position in the World. - * Returns a Vector3. - */ - getAbsolutePosition(): Vector3; + * Index of this particle in the global "indices" array (Internal use) + */ + _ind: number; /** - * Sets the mesh absolute position in the World from a Vector3 or an Array(3). - * Returns the TransformNode. + * ModelShape of this particle (Internal use) */ - setAbsolutePosition(absolutePosition: Vector3): TransformNode; + _model: ModelShape; /** - * Sets the mesh position in its local space. - * Returns the TransformNode. - */ - setPositionWithLocalVector(vector3: Vector3): TransformNode; + * ModelShape id of this particle + */ + shapeId: number; /** - * Returns the mesh position in the local space from the current World matrix values. - * Returns a new Vector3. + * Index of the particle in its shape id (Internal use) */ - getPositionExpressedInLocalSpace(): Vector3; + idxInShape: number; /** - * Translates the mesh along the passed Vector3 in its local space. - * Returns the TransformNode. + * Reference to the shape model BoundingInfo object (Internal use) */ - locallyTranslate(vector3: Vector3): TransformNode; - private static _lookAtVectorCache; + _modelBoundingInfo: BoundingInfo; /** - * Orients a mesh towards a target point. Mesh must be drawn facing user. - * @param targetPoint the position (must be in same space as current mesh) to look at - * @param yawCor optional yaw (y-axis) correction in radians - * @param pitchCor optional pitch (x-axis) correction in radians - * @param rollCor optional roll (z-axis) correction in radians - * @param space the choosen space of the target - * @returns the TransformNode. + * Particle BoundingInfo object (Internal use) */ - lookAt(targetPoint: Vector3, yawCor?: number, pitchCor?: number, rollCor?: number, space?: Space): TransformNode; + _boundingInfo: BoundingInfo; /** - * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh. - * This Vector3 is expressed in the World space. - */ - getDirection(localAxis: Vector3): Vector3; + * Reference to the SPS what the particle belongs to (Internal use) + */ + _sps: SolidParticleSystem; /** - * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh. - * localAxis is expressed in the mesh local space. - * result is computed in the Wordl space from the mesh World matrix. - * Returns the TransformNode. + * Still set as invisible in order to skip useless computations (Internal use) */ - getDirectionToRef(localAxis: Vector3, result: Vector3): TransformNode; + _stillInvisible: boolean; /** - * Sets a new pivot point to the current node - * @param point defines the new pivot point to use - * @param space defines if the point is in world or local space (local by default) - * @returns the current TransformNode - */ - setPivotPoint(point: Vector3, space?: Space): TransformNode; + * Last computed particle rotation matrix + */ + _rotationMatrix: number[]; /** - * Returns a new Vector3 set with the mesh pivot point coordinates in the local space. + * Parent particle Id, if any. + * Default null. */ - getPivotPoint(): Vector3; + parentId: Nullable; /** - * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space. - * Returns the TransformNode. + * Internal global position in the SPS. */ - getPivotPointToRef(result: Vector3): TransformNode; + _globalPosition: Vector3; /** - * Returns a new Vector3 set with the mesh pivot point World coordinates. + * Creates a Solid Particle object. + * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle() + * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier. + * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array. + * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array. + * @param model (ModelShape) is a reference to the model shape on what the particle is designed. + * @param shapeId (integer) is the model shape identifier in the SPS. + * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30)) + * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations. */ - getAbsolutePivotPoint(): Vector3; + constructor(particleIndex: number, positionIndex: number, indiceIndex: number, model: Nullable, shapeId: number, idxInShape: number, sps: SolidParticleSystem, modelBoundingInfo?: Nullable); /** - * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates. - * Returns the TransformNode. + * Legacy support, changed scale to scaling */ - getAbsolutePivotPointToRef(result: Vector3): TransformNode; /** - * Defines the passed node as the parent of the current node. - * The node will remain exactly where it is and its position / rotation will be updated accordingly - * Returns the TransformNode. + * Legacy support, changed scale to scaling + */ + scale: Vector3; + /** + * Legacy support, changed quaternion to rotationQuaternion */ - setParent(node: Nullable): TransformNode; - private _nonUniformScaling; - readonly nonUniformScaling: boolean; - _updateNonUniformScalingState(value: boolean): boolean; /** - * Attach the current TransformNode to another TransformNode associated with a bone - * @param bone Bone affecting the TransformNode - * @param affectedTransformNode TransformNode associated with the bone + * Legacy support, changed quaternion to rotationQuaternion + */ + quaternion: Nullable; + /** + * Returns a boolean. True if the particle intersects another particle or another mesh, else false. + * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB) + * @param target is the object (solid particle or mesh) what the intersection is computed against. + * @returns true if it intersects */ - attachToBone(bone: Bone, affectedTransformNode: TransformNode): TransformNode; - detachFromBone(): TransformNode; - private static _rotationAxisCache; + intersectsMesh(target: Mesh | SolidParticle): boolean; + } + /** + * Represents the shape of the model used by one particle of a solid particle system. + * SPS internal tool, don't use it manually. + */ + class ModelShape { /** - * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space. - * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD. - * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. - * The passed axis is also normalized. - * Returns the TransformNode. + * The shape id. */ - rotate(axis: Vector3, amount: number, space?: Space): TransformNode; + shapeID: number; /** - * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space. - * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. - * The passed axis is also normalized. - * Returns the TransformNode. - * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm + * flat array of model positions (internal use) */ - rotateAround(point: Vector3, axis: Vector3, amount: number): TransformNode; + _shape: Vector3[]; /** - * Translates the mesh along the axis vector for the passed distance in the given space. - * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD. - * Returns the TransformNode. + * flat array of model UVs (internal use) */ - translate(axis: Vector3, distance: number, space?: Space): TransformNode; + _shapeUV: number[]; /** - * Adds a rotation step to the mesh current rotation. - * x, y, z are Euler angles expressed in radians. - * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set. - * This means this rotation is made in the mesh local space only. - * It's useful to set a custom rotation order different from the BJS standard one YXZ. - * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis. - * ```javascript - * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3); - * ``` - * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values. - * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles. - * Returns the TransformNode. + * length of the shape in the model indices array (internal use) */ - addRotation(x: number, y: number, z: number): TransformNode; + _indicesLength: number; /** - * Computes the mesh World matrix and returns it. - * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values. - * If the parameter `force` is let to `false` (default), the current cached World matrix is returned. - * If the parameter `force`is set to `true`, the actual computation is done. - * Returns the mesh World Matrix. + * Custom position function (internal use) */ - computeWorldMatrix(force?: boolean): Matrix; - protected _afterComputeWorldMatrix(): void; + _positionFunction: Nullable<(particle: SolidParticle, i: number, s: number) => void>; /** - * If you'd like to be called back after the mesh position, rotation or scaling has been updated. - * @param func: callback function to add - * - * Returns the TransformNode. - */ - registerAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode; + * Custom vertex function (internal use) + */ + _vertexFunction: Nullable<(particle: SolidParticle, vertex: Vector3, i: number) => void>; /** - * Removes a registered callback function. - * Returns the TransformNode. + * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS. + * SPS internal tool, don't use it manually. + * @hidden */ - unregisterAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode; + constructor(id: number, shape: Vector3[], indicesLength: number, shapeUV: number[], posFunction: Nullable<(particle: SolidParticle, i: number, s: number) => void>, vtxFunction: Nullable<(particle: SolidParticle, vertex: Vector3, i: number) => void>); + } + /** + * Represents a Depth Sorted Particle in the solid particle system. + */ + class DepthSortedParticle { /** - * Clone the current transform node - * Returns the new transform node - * @param name Name of the new clone - * @param newParent New parent for the clone - * @param doNotCloneChildren Do not clone children hierarchy + * Index of the particle in the "indices" array */ - clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable; - serialize(currentSerializationObject?: any): any; + ind: number; /** - * Returns a new TransformNode object parsed from the source provided. - * The parameter `parsedMesh` is the source. - * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with + * Length of the particle shape in the "indices" array */ - static Parse(parsedTransformNode: any, scene: Scene, rootUrl: string): TransformNode; + indicesLength: number; /** - * Releases resources associated with this transform node. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + * Squared distance from the particle to the camera */ - dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void; + sqDistance: number; } } declare module BABYLON { - class VertexBuffer { - /** @hidden */ - _buffer: Buffer; - private _kind; - private _size; - private _ownsBuffer; - private _instanced; - private _instanceDivisor; + /** + * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh. + *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc. + + * The SPS is also a particle system. It provides some methods to manage the particles. + * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior. + * + * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System + */ + class SolidParticleSystem implements IDisposable { /** - * The byte type. + * The SPS array of Solid Particle objects. Just access each particle as with any classic array. + * Example : var p = SPS.particles[i]; */ - static readonly BYTE: number; + particles: SolidParticle[]; /** - * The unsigned byte type. + * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value. */ - static readonly UNSIGNED_BYTE: number; + nbParticles: number; /** - * The short type. + * If the particles must ever face the camera (default false). Useful for planar particles. */ - static readonly SHORT: number; + billboard: boolean; /** - * The unsigned short type. + * Recompute normals when adding a shape */ - static readonly UNSIGNED_SHORT: number; + recomputeNormals: boolean; /** - * The integer type. + * This a counter ofr your own usage. It's not set by any SPS functions. */ - static readonly INT: number; + counter: number; /** - * The unsigned integer type. + * The SPS name. This name is also given to the underlying mesh. */ - static readonly UNSIGNED_INT: number; + name: string; /** - * The float type. + * The SPS mesh. It's a standard BJS Mesh, so all the methods from the Mesh class are avalaible. */ - static readonly FLOAT: number; + mesh: Mesh; /** - * Gets or sets the instance divisor when in instanced mode + * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity. + * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns */ - instanceDivisor: number; + vars: any; /** - * Gets the byte stride. + * This array is populated when the SPS is set as 'pickable'. + * Each key of this array is a `faceId` value that you can get from a pickResult object. + * Each element of this array is an object `{idx: int, faceId: int}`. + * `idx` is the picked particle index in the `SPS.particles` array + * `faceId` is the picked face index counted within this particle. + * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#pickable-particles */ - readonly byteStride: number; + pickedParticles: { + idx: number; + faceId: number; + }[]; /** - * Gets the byte offset. + * This array is populated when `enableDepthSort` is set to true. + * Each element of this array is an instance of the class DepthSortedParticle. */ - readonly byteOffset: number; + depthSortedParticles: DepthSortedParticle[]; /** - * Gets whether integer data values should be normalized into a certain range when being casted to a float. + * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only) */ - readonly normalized: boolean; + _bSphereOnly: boolean; /** - * Gets the data type of each component in the array. + * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only) */ - readonly type: number; + _bSphereRadiusFactor: number; + private _scene; + private _positions; + private _indices; + private _normals; + private _colors; + private _uvs; + private _indices32; + private _positions32; + private _normals32; + private _fixedNormal32; + private _colors32; + private _uvs32; + private _index; + private _updatable; + private _pickable; + private _isVisibilityBoxLocked; + private _alwaysVisible; + private _depthSort; + private _shapeCounter; + private _copy; + private _shape; + private _shapeUV; + private _color; + private _computeParticleColor; + private _computeParticleTexture; + private _computeParticleRotation; + private _computeParticleVertex; + private _computeBoundingBox; + private _depthSortParticles; + private _cam_axisZ; + private _cam_axisY; + private _cam_axisX; + private _axisZ; + private _camera; + private _particle; + private _camDir; + private _camInvertedPosition; + private _rotMatrix; + private _invertMatrix; + private _rotated; + private _quaternion; + private _vertex; + private _normal; + private _yaw; + private _pitch; + private _roll; + private _halfroll; + private _halfpitch; + private _halfyaw; + private _sinRoll; + private _cosRoll; + private _sinPitch; + private _cosPitch; + private _sinYaw; + private _cosYaw; + private _mustUnrotateFixedNormals; + private _minimum; + private _maximum; + private _minBbox; + private _maxBbox; + private _particlesIntersect; + private _depthSortFunction; + private _needs32Bits; + private _pivotBackTranslation; + private _scaledPivot; + private _particleHasParent; + private _parent; /** - * Constructor - * @param engine the engine - * @param data the data to use for this vertex buffer - * @param kind the vertex buffer kind - * @param updatable whether the data is updatable - * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional) - * @param stride the stride (optional) - * @param instanced whether the buffer is instanced (optional) - * @param offset the offset of the data (optional) - * @param size the number of components (optional) - * @param type the type of the component (optional) - * @param normalized whether the data contains normalized data (optional) - * @param useBytes set to true if stride and offset are in bytes (optional) + * Creates a SPS (Solid Particle System) object. + * @param name (String) is the SPS name, this will be the underlying mesh name. + * @param scene (Scene) is the scene in which the SPS is added. + * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable. + * @param isPickable (optional boolean, default false) : if the solid particles must be pickable. + * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera. + * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed. + * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). + * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance. + * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh. */ - constructor(engine: any, data: DataArray | Buffer, kind: string, updatable: boolean, postponeInternalCreation?: boolean, stride?: number, instanced?: boolean, offset?: number, size?: number, type?: number, normalized?: boolean, useBytes?: boolean); - _rebuild(): void; + constructor(name: string, scene: Scene, options?: { + updatable?: boolean; + isPickable?: boolean; + enableDepthSort?: boolean; + particleIntersection?: boolean; + boundingSphereOnly?: boolean; + bSphereRadiusFactor?: number; + }); /** - * Returns the kind of the VertexBuffer (string). + * Builds the SPS underlying mesh. Returns a standard Mesh. + * If no model shape was added to the SPS, the returned mesh is just a single triangular plane. + * @returns the created mesh */ - getKind(): string; + buildMesh(): Mesh; /** - * Boolean : is the VertexBuffer updatable ? + * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS. + * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places. + * Thus the particles generated from `digest()` have their property `position` set yet. + * @param mesh ( Mesh ) is the mesh to be digested + * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any + * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets + * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets + * @returns the current SPS */ - isUpdatable(): boolean; + digest(mesh: Mesh, options?: { + facetNb?: number; + number?: number; + delta?: number; + }): SolidParticleSystem; + private _unrotateFixedNormals; + private _resetCopy; + private _meshBuilder; + private _posToShape; + private _uvsToShapeUV; + private _addParticle; /** - * Returns an array of numbers or a typed array containing the VertexBuffer data. + * Adds some particles to the SPS from the model shape. Returns the shape id. + * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps + * @param mesh is any Mesh object that will be used as a model for the solid particles. + * @param nb (positive integer) the number of particles to be created from this model + * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation. + * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation + * @returns the number of shapes in the system */ - getData(): Nullable; + addShape(mesh: Mesh, nb: number, options?: { + positionFunction?: any; + vertexFunction?: any; + }): number; + private _rebuildParticle; /** - * Returns the WebGLBuffer associated to the VertexBuffer. + * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed. + * @returns the SPS. */ - getBuffer(): Nullable; + rebuildMesh(): SolidParticleSystem; /** - * Returns the stride as a multiple of the type byte length. - * DEPRECATED. Use byteStride instead. + * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc. + * This method calls `updateParticle()` for each particle of the SPS. + * For an animated SPS, it is usually called within the render loop. + * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_ + * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_ + * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_ + * @returns the SPS. */ - getStrideSize(): number; + setParticles(start?: number, end?: number, update?: boolean): SolidParticleSystem; + private _quaternionRotationYPR; + private _quaternionToRotationMatrix; /** - * Returns the offset as a multiple of the type byte length. - * DEPRECATED. Use byteOffset instead. + * Disposes the SPS. + */ + dispose(): void; + /** + * Visibilty helper : Recomputes the visible size according to the mesh bounding box + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + * @returns the SPS. */ - getOffset(): number; + refreshVisibleSize(): SolidParticleSystem; /** - * Returns the number of components per vertex attribute (integer). + * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box. + * @param size the size (float) of the visibility box + * note : this doesn't lock the SPS mesh bounding box. + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility */ - getSize(): number; + setVisibilityBox(size: number): void; /** - * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ? + * Gets whether the SPS as always visible or not + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility */ - getIsInstanced(): boolean; /** - * Returns the instancing divisor, zero for non-instanced (integer). + * Sets the SPS as always visible or not + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + */ + isAlwaysVisible: boolean; + /** + * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates. + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility */ - getInstanceDivisor(): number; /** - * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array. - * Returns the created WebGLBuffer. + * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates. + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility + */ + isVisibilityBoxLocked: boolean; + /** + * Tells to `setParticles()` to compute the particle rotations or not. + * Default value : true. The SPS is faster when it's set to false. + * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate. */ - create(data?: DataArray): void; /** - * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array. - * This function will create a new buffer if the current one is not updatable - * Returns the updated WebGLBuffer. + * Gets if `setParticles()` computes the particle rotations or not. + * Default value : true. The SPS is faster when it's set to false. + * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate. + */ + computeParticleRotation: boolean; + /** + * Tells to `setParticles()` to compute the particle colors or not. + * Default value : true. The SPS is faster when it's set to false. + * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set. */ - update(data: DataArray): void; /** - * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array. - * Returns the directly updated WebGLBuffer. - * @param data the new data - * @param offset the new offset - * @param useBytes set to true if the offset is in bytes + * Gets if `setParticles()` computes the particle colors or not. + * Default value : true. The SPS is faster when it's set to false. + * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set. + */ + computeParticleColor: boolean; + /** + * Gets if `setParticles()` computes the particle textures or not. + * Default value : true. The SPS is faster when it's set to false. + * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set. + */ + computeParticleTexture: boolean; + /** + * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not. + * Default value : false. The SPS is faster when it's set to false. + * Note : the particle custom vertex positions aren't stored values. */ - updateDirectly(data: DataArray, offset: number, useBytes?: boolean): void; /** - * Disposes the VertexBuffer and the underlying WebGLBuffer. + * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not. + * Default value : false. The SPS is faster when it's set to false. + * Note : the particle custom vertex positions aren't stored values. + */ + computeParticleVertex: boolean; + /** + * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions. */ - dispose(): void; /** - * Enumerates each value of this vertex buffer as numbers. - * @param count the number of values to enumerate - * @param callback the callback function called for each value + * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions. + */ + computeBoundingBox: boolean; + /** + * Tells to `setParticles()` to sort or not the distance between each particle and the camera. + * Skipped when `enableDepthSort` is set to `false` (default) at construction time. + * Default : `true` */ - forEach(count: number, callback: (value: number, index: number) => void): void; - private static _PositionKind; - private static _NormalKind; - private static _TangentKind; - private static _UVKind; - private static _UV2Kind; - private static _UV3Kind; - private static _UV4Kind; - private static _UV5Kind; - private static _UV6Kind; - private static _ColorKind; - private static _MatricesIndicesKind; - private static _MatricesWeightsKind; - private static _MatricesIndicesExtraKind; - private static _MatricesWeightsExtraKind; - static readonly PositionKind: string; - static readonly NormalKind: string; - static readonly TangentKind: string; - static readonly UVKind: string; - static readonly UV2Kind: string; - static readonly UV3Kind: string; - static readonly UV4Kind: string; - static readonly UV5Kind: string; - static readonly UV6Kind: string; - static readonly ColorKind: string; - static readonly MatricesIndicesKind: string; - static readonly MatricesWeightsKind: string; - static readonly MatricesIndicesExtraKind: string; - static readonly MatricesWeightsExtraKind: string; /** - * Deduces the stride given a kind. - * @param kind The kind string to deduce - * @returns The deduced stride + * Gets if `setParticles()` sorts or not the distance between each particle and the camera. + * Skipped when `enableDepthSort` is set to `false` (default) at construction time. + * Default : `true` + */ + depthSortParticles: boolean; + /** + * This function does nothing. It may be overwritten to set all the particle first values. + * The SPS doesn't call this function, you may have to call it by your own. + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management */ - static DeduceStride(kind: string): number; + initParticles(): void; /** - * Gets the byte length of the given type. - * @param type the type - * @returns the number of bytes + * This function does nothing. It may be overwritten to recycle a particle. + * The SPS doesn't call this function, you may have to call it by your own. + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management + * @param particle The particle to recycle + * @returns the recycled particle */ - static GetTypeByteLength(type: number): number; + recycleParticle(particle: SolidParticle): SolidParticle; /** - * Enumerates each value of the given parameters as numbers. - * @param data the data to enumerate - * @param byteOffset the byte offset of the data - * @param byteStride the byte stride of the data - * @param componentCount the number of components per element - * @param componentType the type of the component - * @param count the total number of components - * @param normalized whether the data is normalized - * @param callback the callback function called for each value + * Updates a particle : this function should be overwritten by the user. + * It is called on each particle by `setParticles()`. This is the place to code each particle behavior. + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management + * @example : just set a particle position or velocity and recycle conditions + * @param particle The particle to update + * @returns the updated particle */ - static ForEach(data: DataArray, byteOffset: number, byteStride: number, componentCount: number, componentType: number, count: number, normalized: boolean, callback: (value: number, index: number) => void): void; - private static _GetFloatValue(dataView, type, byteOffset, normalized); + updateParticle(particle: SolidParticle): SolidParticle; + /** + * Updates a vertex of a particle : it can be overwritten by the user. + * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only. + * @param particle the current particle + * @param vertex the current index of the current particle + * @param pt the index of the current vertex in the particle shape + * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape + * @example : just set a vertex particle position + * @returns the updated vertex + */ + updateParticleVertex(particle: SolidParticle, vertex: Vector3, pt: number): Vector3; + /** + * This will be called before any other treatment by `setParticles()` and will be passed three parameters. + * This does nothing and may be overwritten by the user. + * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() + * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() + * @param update the boolean update value actually passed to setParticles() + */ + beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void; + /** + * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update. + * This will be passed three parameters. + * This does nothing and may be overwritten by the user. + * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() + * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() + * @param update the boolean update value actually passed to setParticles() + */ + afterUpdateParticles(start?: number, stop?: number, update?: boolean): void; } } @@ -26850,10 +26860,10 @@ declare module BABYLON { * Registers the component in a given scene */ register(): void; - private _evaluateSubMesh(mesh, subMesh); - private _activeMesh(sourceMesh, mesh); - private _prepareRessources(); - private _createIndexBuffer(); + private _evaluateSubMesh; + private _activeMesh; + private _prepareRessources; + private _createIndexBuffer; /** * Rebuilds the elements related to this component in case of * context lost for instance. @@ -26920,12 +26930,12 @@ declare module BABYLON { /** Gets or sets a boolean indicating if the edgesRenderer is active */ isEnabled: boolean; constructor(source: AbstractMesh, epsilon?: number, checkVerticesInsteadOfIndices?: boolean); - private _prepareRessources(); + private _prepareRessources; _rebuild(): void; dispose(): void; - private _processEdgeForAdjacencies(pa, pb, p0, p1, p2); - private _processEdgeForAdjacenciesWithVertices(pa, pb, p0, p1, p2); - private _checkEdge(faceIndex, edge, faceNormals, p0, p1); + private _processEdgeForAdjacencies; + private _processEdgeForAdjacenciesWithVertices; + private _checkEdge; _generateEdgesLines(): void; render(): void; } @@ -26955,8 +26965,8 @@ declare module BABYLON { * Gets wether or not position are enabled for the G buffer. */ /** - * Sets wether or not position are enabled for the G buffer. - */ + * Sets wether or not position are enabled for the G buffer. + */ enablePosition: boolean; /** * Gets the scene associated with the buffer. @@ -26989,8 +26999,8 @@ declare module BABYLON { * Gets the number of samples used to render the buffer (anti aliasing). */ /** - * Sets the number of samples used to render the buffer (anti aliasing). - */ + * Sets the number of samples used to render the buffer (anti aliasing). + */ samples: number; /** * Disposes the renderer and frees up associated resources. @@ -27063,17 +27073,17 @@ declare module BABYLON { * Renders the opaque submeshes in the order from the opaqueSortCompareFn. * @param subMeshes The submeshes to render */ - private renderOpaqueSorted(subMeshes); + private renderOpaqueSorted; /** * Renders the opaque submeshes in the order from the alphatestSortCompareFn. * @param subMeshes The submeshes to render */ - private renderAlphaTestSorted(subMeshes); + private renderAlphaTestSorted; /** * Renders the opaque submeshes in the order from the transparentSortCompareFn. * @param subMeshes The submeshes to render */ - private renderTransparentSorted(subMeshes); + private renderTransparentSorted; /** * Renders the submeshes in a specified order. * @param subMeshes The submeshes to sort before render @@ -27081,12 +27091,12 @@ declare module BABYLON { * @param cameraPosition The camera position use to preprocess the submeshes to help sorting * @param transparent Specifies to activate blending if true */ - private static renderSorted(subMeshes, sortCompareFn, camera, transparent); + private static renderSorted; /** * Renders the submeshes in the order they were dispatched (no sort applied). * @param subMeshes The submeshes to render */ - private static renderUnsorted(subMeshes); + private static renderUnsorted; /** * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) * are rendered back to front if in the same alpha index. @@ -27128,8 +27138,8 @@ declare module BABYLON { dispatch(subMesh: SubMesh, mesh?: AbstractMesh, material?: Nullable): void; dispatchSprites(spriteManager: SpriteManager): void; dispatchParticles(particleSystem: IParticleSystem): void; - private _renderParticles(activeMeshes); - private _renderSprites(); + private _renderParticles; + private _renderSprites; } } @@ -27178,7 +27188,7 @@ declare module BABYLON { private _customTransparentSortCompareFn; private _renderingGroupInfo; constructor(scene: Scene); - private _clearDepthStencilBuffer(depth?, stencil?); + private _clearDepthStencilBuffer; render(customRenderFunction: Nullable<(opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, depthOnlySubMeshes: SmartArray) => void>, activeMeshes: Nullable, renderParticles: boolean, renderSprites: boolean): void; reset(): void; dispose(): void; @@ -27186,7 +27196,7 @@ declare module BABYLON { * Clear the info related to rendering groups preventing retention points during dispose. */ freeRenderingGroups(): void; - private _prepareRenderingGroup(renderingGroupId); + private _prepareRenderingGroup; dispatchSprites(spriteManager: SpriteManager): void; dispatchParticles(particleSystem: IParticleSystem): void; /** @@ -27229,7 +27239,8 @@ declare module BABYLON { * Renders a layer on top of an existing scene */ class UtilityLayerRenderer implements IDisposable { - /** the original scene that will be rendered on top of */ originalScene: Scene; + /** the original scene that will be rendered on top of */ + originalScene: Scene; private _pointerCaptures; private _lastPointerEvents; private static _DefaultUtilityLayer; @@ -27271,8 +27282,10 @@ declare module BABYLON { * Instantiates a UtilityLayerRenderer * @param originalScene the original scene that will be rendered on top of */ - constructor(/** the original scene that will be rendered on top of */ originalScene: Scene); - private _notifyObservers(prePointerInfo, pickInfo, pointerEvent); + constructor( + /** the original scene that will be rendered on top of */ + originalScene: Scene); + private _notifyObservers; /** * Renders the utility layers scene on top of the original scene */ @@ -27281,7 +27294,7 @@ declare module BABYLON { * Disposes of the renderer */ dispose(): void; - private _updateCamera(); + private _updateCamera; } } @@ -27350,7 +27363,7 @@ declare module BABYLON { private _effectFog; texture: Texture; constructor(name: string, imgUrl: string, capacity: number, cellSize: any, scene: Scene, epsilon?: number, samplingMode?: number); - private _appendSpriteVertex(index, sprite, offsetX, offsetY, rowSize); + private _appendSpriteVertex; intersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean): Nullable; render(): void; dispose(): void; @@ -27539,7 +27552,8 @@ declare module BABYLON { * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion. */ class BloomMergePostProcess extends PostProcess { - /** Weight of the bloom to be added to the original input. */ weight: number; + /** Weight of the bloom to be added to the original input. */ + weight: number; /** * Creates a new instance of @see BloomMergePostProcess * @param name The name of the effect. @@ -27554,7 +27568,9 @@ declare module BABYLON { * @param textureType Type of textures used when performing the post process. (default: 0) * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ - constructor(name: string, originalFromInput: PostProcess, blurred: PostProcess, /** Weight of the bloom to be added to the original input. */ weight: number, options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number, blockCompilation?: boolean); + constructor(name: string, originalFromInput: PostProcess, blurred: PostProcess, + /** Weight of the bloom to be added to the original input. */ + weight: number, options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number, blockCompilation?: boolean); } } @@ -27564,25 +27580,26 @@ declare module BABYLON { * Can be used twice in x and y directions to perform a guassian blur in two passes. */ class BlurPostProcess extends PostProcess { - /** The direction in which to blur the image. */ direction: Vector2; + /** The direction in which to blur the image. */ + direction: Vector2; private blockCompilation; protected _kernel: number; protected _idealKernel: number; protected _packedFloat: boolean; private _staticDefines; - /** - * Gets the length in pixels of the blur sample region - */ /** * Sets the length in pixels of the blur sample region */ - kernel: number; /** - * Gets wether or not the blur is unpacking/repacking floats - */ + * Gets the length in pixels of the blur sample region + */ + kernel: number; /** * Sets wether or not the blur needs to unpack/repack floats */ + /** + * Gets wether or not the blur is unpacking/repacking floats + */ packedFloat: boolean; /** * Creates a new instance BlurPostProcess @@ -27597,7 +27614,9 @@ declare module BABYLON { * @param textureType Type of textures used when performing the post process. (default: 0) * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ - constructor(name: string, /** The direction in which to blur the image. */ direction: Vector2, kernel: number, options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number, defines?: string, blockCompilation?: boolean); + constructor(name: string, + /** The direction in which to blur the image. */ + direction: Vector2, kernel: number, options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number, defines?: string, blockCompilation?: boolean); /** * Updates the effect with the current post process compile time values and recompiles the shader. * @param defines Define statements that should be added at the beginning of the shader. (default: null) @@ -27729,7 +27748,8 @@ declare module BABYLON { * See http://en.wikipedia.org/wiki/Kernel_(image_processing) */ class ConvolutionPostProcess extends PostProcess { - /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel: number[]; + /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ + kernel: number[]; /** * Creates a new instance ConvolutionPostProcess * @param name The name of the effect. @@ -27741,7 +27761,9 @@ declare module BABYLON { * @param reusable If the post process can be reused on the same frame. (default: false) * @param textureType Type of textures used when performing the post process. (default: 0) */ - constructor(name: string, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel: number[], options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number); + constructor(name: string, + /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ + kernel: number[], options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number); /** * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing) */ @@ -27814,7 +27836,7 @@ declare module BABYLON { /** * Large blur */ - High = 2, + High = 2 } /** * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing. @@ -27972,7 +27994,7 @@ declare module BABYLON { texelWidth: number; texelHeight: number; constructor(name: string, options: number | PostProcessOptions, camera?: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType?: number); - private _getDefines(); + private _getDefines; } } @@ -28020,10 +28042,10 @@ declare module BABYLON { * Gets the image processing configuration used either in this material. */ /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ imageProcessingConfiguration: ImageProcessingConfiguration; /** * Keep track of the image processing observer to allow dispose and replace. @@ -28038,116 +28060,116 @@ declare module BABYLON { * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true . */ /** - * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true . - */ + * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true . + */ colorCurves: Nullable; /** * Gets wether the color curves effect is enabled. */ /** - * Sets wether the color curves effect is enabled. - */ + * Sets wether the color curves effect is enabled. + */ colorCurvesEnabled: boolean; /** * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. */ /** - * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. - */ + * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. + */ colorGradingTexture: Nullable; /** * Gets wether the color grading effect is enabled. */ /** - * Gets wether the color grading effect is enabled. - */ + * Gets wether the color grading effect is enabled. + */ colorGradingEnabled: boolean; /** * Gets exposure used in the effect. */ /** - * Sets exposure used in the effect. - */ + * Sets exposure used in the effect. + */ exposure: number; /** * Gets wether tonemapping is enabled or not. */ /** - * Sets wether tonemapping is enabled or not - */ + * Sets wether tonemapping is enabled or not + */ toneMappingEnabled: boolean; /** * Gets contrast used in the effect. */ /** - * Sets contrast used in the effect. - */ + * Sets contrast used in the effect. + */ contrast: number; /** * Gets Vignette stretch size. */ /** - * Sets Vignette stretch size. - */ + * Sets Vignette stretch size. + */ vignetteStretch: number; /** * Gets Vignette centre X Offset. */ /** - * Sets Vignette centre X Offset. - */ + * Sets Vignette centre X Offset. + */ vignetteCentreX: number; /** * Gets Vignette centre Y Offset. */ /** - * Sets Vignette centre Y Offset. - */ + * Sets Vignette centre Y Offset. + */ vignetteCentreY: number; /** * Gets Vignette weight or intensity of the vignette effect. */ /** - * Sets Vignette weight or intensity of the vignette effect. - */ + * Sets Vignette weight or intensity of the vignette effect. + */ vignetteWeight: number; /** * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) * if vignetteEnabled is set to true. */ /** - * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) - * if vignetteEnabled is set to true. - */ + * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) + * if vignetteEnabled is set to true. + */ vignetteColor: Color4; /** * Gets Camera field of view used by the Vignette effect. */ /** - * Sets Camera field of view used by the Vignette effect. - */ + * Sets Camera field of view used by the Vignette effect. + */ vignetteCameraFov: number; /** * Gets the vignette blend mode allowing different kind of effect. */ /** - * Sets the vignette blend mode allowing different kind of effect. - */ + * Sets the vignette blend mode allowing different kind of effect. + */ vignetteBlendMode: number; /** * Gets wether the vignette effect is enabled. */ /** - * Sets wether the vignette effect is enabled. - */ + * Sets wether the vignette effect is enabled. + */ vignetteEnabled: boolean; private _fromLinearSpace; /** * Gets wether the input of the processing is in Gamma or Linear Space. */ /** - * Sets wether the input of the processing is in Gamma or Linear Space. - */ + * Sets wether the input of the processing is in Gamma or Linear Space. + */ fromLinearSpace: boolean; /** * Defines cache preventing GC. @@ -28176,7 +28198,8 @@ declare module BABYLON { * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses */ class PostProcess { - /** Name of the PostProcess. */ name: string; + /** Name of the PostProcess. */ + name: string; /** * Width of the texture to apply the post process on */ @@ -28348,7 +28371,9 @@ declare module BABYLON { * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx * @param blockCompilation If the shader should not be compiled imediatly. (default: false) */ - constructor(/** Name of the PostProcess. */ name: string, fragmentUrl: string, parameters: Nullable, samplers: Nullable, options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, defines?: Nullable, textureType?: number, vertexUrl?: string, indexParameters?: any, blockCompilation?: boolean); + constructor( + /** Name of the PostProcess. */ + name: string, fragmentUrl: string, parameters: Nullable, samplers: Nullable, options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, defines?: Nullable, textureType?: number, vertexUrl?: string, indexParameters?: any, blockCompilation?: boolean); /** * Gets the engine which this post process belongs to. * @returns The engine the post process was enabled with. @@ -28414,7 +28439,7 @@ declare module BABYLON { * @returns the effect corrisponding to this post process. Null if not compiled or not ready. */ apply(): Nullable; - private _disposeTextures(); + private _disposeTextures; /** * Disposes the post process. * @param camera The camera to dispose the post process on. @@ -28437,8 +28462,8 @@ declare module BABYLON { * @param scene The scene that the post process is associated with. */ constructor(scene: Scene); - private _prepareBuffers(); - private _buildIndexBuffer(); + private _prepareBuffers; + private _buildIndexBuffer; /** * Rebuilds the vertex buffers of the manager. */ @@ -28539,7 +28564,7 @@ declare module BABYLON { /** HejiDawson */ HejiDawson = 2, /** Photographic */ - Photographic = 3, + Photographic = 3 } /** * Defines a post process to apply tone mapping @@ -28559,8 +28584,8 @@ declare module BABYLON { * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default) */ constructor(name: string, _operator: TonemappingOperator, - /** Defines the required exposure adjustement */ - exposureAdjustment: number, camera: Camera, samplingMode?: number, engine?: Engine, textureFormat?: number); + /** Defines the required exposure adjustement */ + exposureAdjustment: number, camera: Camera, samplingMode?: number, engine?: Engine, textureFormat?: number); } } @@ -28628,7 +28653,7 @@ declare module BABYLON { */ constructor(name: string, ratio: any, camera: Camera, mesh?: Mesh, samples?: number, samplingMode?: number, engine?: Engine, reusable?: boolean, scene?: Scene); getClassName(): string; - private _isReady(subMesh, useInstances); + private _isReady; /** * Sets the new light position for light scattering effect * @param {BABYLON.Vector3} The new custom light position @@ -28648,9 +28673,9 @@ declare module BABYLON { * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process */ getPass(): RenderTargetTexture; - private _meshExcluded(mesh); - private _createPass(scene, ratio); - private _updateMeshScreenCoordinates(scene); + private _meshExcluded; + private _createPass; + private _updateMeshScreenCoordinates; /** * Creates a default mesh for the Volumeric Light Scattering post-process * @param {string} The mesh name @@ -28686,8 +28711,8 @@ declare module BABYLON { * @returns true if the query matches */ static Eval(query: string, evaluateCallback: (val: any) => boolean): boolean; - private static _HandleParenthesisContent(parenthesisContent, evaluateCallback); - private static _SimplifyNegation(booleanString); + private static _HandleParenthesisContent; + private static _SimplifyNegation; } } @@ -28711,7 +28736,7 @@ declare module BABYLON { /** * Error */ - ERROR = 3, + ERROR = 3 } /** * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene @@ -28733,9 +28758,9 @@ declare module BABYLON { * @param name defines the name of the task */ constructor( - /** - * Task name - */ name: string); + /** + * Task name + */ name: string); private _isCompleted; private _taskState; private _errorObject; @@ -28778,8 +28803,8 @@ declare module BABYLON { * This can be used with failed tasks that have the reason for failure fixed. */ reset(): void; - private onErrorCallback(onError, message?, exception?); - private onDoneCallback(onSuccess, onError); + private onErrorCallback; + private onDoneCallback; } /** * Define the interface used by progress events raised during assets loading @@ -28870,22 +28895,22 @@ declare module BABYLON { * @param sceneFilename defines the filename of the scene to load from */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the list of mesh's names you want to load - */ - meshesNames: any, - /** - * Defines the root url to use as a base to load your meshes and associated resources - */ - rootUrl: string, - /** - * Defines the filename of the scene to load from - */ - sceneFilename: string); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the list of mesh's names you want to load + */ + meshesNames: any, + /** + * Defines the root url to use as a base to load your meshes and associated resources + */ + rootUrl: string, + /** + * Defines the filename of the scene to load from + */ + sceneFilename: string); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -28924,14 +28949,14 @@ declare module BABYLON { * @param url defines the location of the file to load */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the location of the file to load - */ - url: string); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the location of the file to load + */ + url: string); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -28970,14 +28995,14 @@ declare module BABYLON { * @param url defines the location of the file to load */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the location of the file to load - */ - url: string); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the location of the file to load + */ + url: string); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -29016,14 +29041,14 @@ declare module BABYLON { * @param url defines the location of the image to load */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the location of the image to load - */ - url: string); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the location of the image to load + */ + url: string); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -29056,11 +29081,11 @@ declare module BABYLON { /** * Defines if mipmap should not be generated (default is false) */ - noMipmap: boolean | undefined; + noMipmap?: boolean | undefined; /** * Defines if texture must be inverted on Y axis (default is false) */ - invertY: boolean | undefined; + invertY?: boolean | undefined; /** * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE) */ @@ -29086,26 +29111,26 @@ declare module BABYLON { * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE) */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the location of the file to load - */ - url: string, - /** - * Defines if mipmap should not be generated (default is false) - */ - noMipmap?: boolean | undefined, - /** - * Defines if texture must be inverted on Y axis (default is false) - */ - invertY?: boolean | undefined, - /** - * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE) - */ - samplingMode?: number); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the location of the file to load + */ + url: string, + /** + * Defines if mipmap should not be generated (default is false) + */ + noMipmap?: boolean | undefined, + /** + * Defines if texture must be inverted on Y axis (default is false) + */ + invertY?: boolean | undefined, + /** + * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE) + */ + samplingMode?: number); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -29129,15 +29154,15 @@ declare module BABYLON { /** * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default) */ - extensions: string[] | undefined; + extensions?: string[] | undefined; /** * Defines if mipmaps should not be generated (default is false) */ - noMipmap: boolean | undefined; + noMipmap?: boolean | undefined; /** * Defines the explicit list of files (undefined by default) */ - files: string[] | undefined; + files?: string[] | undefined; /** * Gets the loaded texture */ @@ -29159,26 +29184,26 @@ declare module BABYLON { * @param files defines the explicit list of files (undefined by default) */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension) - */ - url: string, - /** - * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default) - */ - extensions?: string[] | undefined, - /** - * Defines if mipmaps should not be generated (default is false) - */ - noMipmap?: boolean | undefined, - /** - * Defines the explicit list of files (undefined by default) - */ - files?: string[] | undefined); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension) + */ + url: string, + /** + * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default) + */ + extensions?: string[] | undefined, + /** + * Defines if mipmaps should not be generated (default is false) + */ + noMipmap?: boolean | undefined, + /** + * Defines the explicit list of files (undefined by default) + */ + files?: string[] | undefined); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -29242,34 +29267,34 @@ declare module BABYLON { * @param reserved Internal use only */ constructor( - /** - * Defines the name of the task - */ - name: string, - /** - * Defines the location of the file to load - */ - url: string, - /** - * Defines the desired size (the more it increases the longer the generation will be) - */ - size: number, - /** - * Defines if mipmaps should not be generated (default is false) - */ - noMipmap?: boolean, - /** - * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true) - */ - generateHarmonics?: boolean, - /** - * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false) - */ - gammaSpace?: boolean, - /** - * Internal Use Only - */ - reserved?: boolean); + /** + * Defines the name of the task + */ + name: string, + /** + * Defines the location of the file to load + */ + url: string, + /** + * Defines the desired size (the more it increases the longer the generation will be) + */ + size: number, + /** + * Defines if mipmaps should not be generated (default is false) + */ + noMipmap?: boolean, + /** + * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true) + */ + generateHarmonics?: boolean, + /** + * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false) + */ + gammaSpace?: boolean, + /** + * Internal Use Only + */ + reserved?: boolean); /** * Execute the current task * @param scene defines the scene where you want your assets to be loaded @@ -29398,8 +29423,8 @@ declare module BABYLON { * @param task the task to remove */ removeTask(task: AbstractAssetTask): void; - private _decreaseWaitingTasksCount(task); - private _runTask(task); + private _decreaseWaitingTasksCount; + private _runTask; /** * Reset the {BABYLON.AssetsManager} and remove all tasks * @return the current instance of the {BABYLON.AssetsManager} @@ -29450,7 +29475,7 @@ declare module BABYLON { constructor(urlToScene: string, callbackManifestChecked: (checked: boolean) => any, disableManifestCheck?: boolean); private static _ParseURL; private static _ReturnFullUrlLocation; - private _checkManifestFile(); + private _checkManifestFile; /** * Open the database and make it available * @param successCallback defines the callback to call on success @@ -29463,11 +29488,11 @@ declare module BABYLON { * @param image defines the target DOM image */ loadImageFromDB(url: string, image: HTMLImageElement): void; - private _loadImageFromDBAsync(url, image, notInDBCallback); - private _saveImageIntoDBAsync(url, image); - private _checkVersionFromDB(url, versionLoaded); - private _loadVersionFromDBAsync(url, callback, updateInDBCallback); - private _saveVersionIntoDBAsync(url, callback); + private _loadImageFromDBAsync; + private _saveImageIntoDBAsync; + private _checkVersionFromDB; + private _loadVersionFromDBAsync; + private _saveVersionIntoDBAsync; /** * Loads a file from database * @param url defines the URL to load from @@ -29477,8 +29502,8 @@ declare module BABYLON { * @param useArrayBuffer defines a boolean to use array buffer instead of text string */ loadFileFromDB(url: string, sceneLoaded: (data: any) => void, progressCallBack?: (data: any) => void, errorCallback?: () => void, useArrayBuffer?: boolean): void; - private _loadFileFromDBAsync(url, callback, notInDBCallback, useArrayBuffer?); - private _saveFileIntoDBAsync(url, callback, progressCallback?, useArrayBuffer?, errorCallback?); + private _loadFileFromDBAsync; + private _saveFileIntoDBAsync; } } @@ -29502,17 +29527,17 @@ declare module BABYLON { static GetDDSInfo(arrayBuffer: any): DDSInfo; private static _FloatView; private static _Int32View; - private static _ToHalfFloat(value); - private static _FromHalfFloat(value); - private static _GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod); - private static _GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod); - private static _GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod); - private static _GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod); - private static _GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod); - private static _GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset); - private static _ExtractLongWordOrder(value); - private static _GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset); - private static _GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); + private static _ToHalfFloat; + private static _FromHalfFloat; + private static _GetHalfFloatAsFloatRGBAArrayBuffer; + private static _GetHalfFloatRGBAArrayBuffer; + private static _GetFloatRGBAArrayBuffer; + private static _GetFloatAsUIntRGBAArrayBuffer; + private static _GetHalfFloatAsUIntRGBAArrayBuffer; + private static _GetRGBAArrayBuffer; + private static _ExtractLongWordOrder; + private static _GetRGBArrayBuffer; + private static _GetLuminanceArrayBuffer; /** * Uploads DDS Levels to a Babylon Texture * @hidden @@ -29622,7 +29647,7 @@ declare module BABYLON { * @param texture defines the texture containing the polynomials * @return the JSON representation of the spherical info */ - private static _CreateEnvTextureIrradiance(texture); + private static _CreateEnvTextureIrradiance; /** * Uploads the texture info contained in the env file to the GPU. * @param texture defines the internal texture to upload to @@ -29671,13 +29696,13 @@ declare module BABYLON { private _dropHandler; monitorElementForDragNDrop(elementToMonitor: HTMLElement): void; dispose(): void; - private renderFunction(); - private drag(e); - private drop(eventDrop); - private _traverseFolder(folder, files, remaining, callback); - private _processFiles(files); + private renderFunction; + private drag; + private drop; + private _traverseFolder; + private _processFiles; loadFiles(event: any): void; - private _processReload(); + private _processReload; reload(): void; } } @@ -29721,7 +29746,7 @@ declare module BABYLON { * @hidden */ uploadLevels(texture: InternalTexture, loadMipmaps: boolean): void; - private _upload2DCompressedLevels(texture, loadMipmaps); + private _upload2DCompressedLevels; } } @@ -29798,18 +29823,18 @@ declare module BABYLON { * @param scope defines the current scope used to restore the JS context */ constructor( - /** - * Defines the callback to call when the observer is notified - */ - callback: (eventData: T, eventState: EventState) => void, - /** - * Defines the mask of the observer (used to filter notifications) - */ - mask: number, - /** - * Defines the current scope used to restore the JS context - */ - scope?: any); + /** + * Defines the callback to call when the observer is notified + */ + callback: (eventData: T, eventState: EventState) => void, + /** + * Defines the mask of the observer (used to filter notifications) + */ + mask: number, + /** + * Defines the current scope used to restore the JS context + */ + scope?: any); } /** * Represent a list of observers registered to multiple Observables object. @@ -29877,8 +29902,8 @@ declare module BABYLON { * @returns false if it doesn't belong to this Observable */ removeCallback(callback: (eventData: T, eventState: EventState) => void, scope?: any): boolean; - private _deferUnregister(observer); - private _remove(observer); + private _deferUnregister; + private _remove; /** * Notify all Observers by calling their respective callback with the given data * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute @@ -30094,10 +30119,10 @@ declare module BABYLON { * @param desc defines the description associated with the optimization */ constructor( - /** - * Defines the priority of this optimization (0 by default which means first in the list) - */ - priority?: number); + /** + * Defines the priority of this optimization (0 by default which means first in the list) + */ + priority?: number); } /** * Defines an optimization used to reduce the size of render target textures @@ -30128,18 +30153,18 @@ declare module BABYLON { * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed. */ constructor( - /** - * Defines the priority of this optimization (0 by default which means first in the list) - */ - priority?: number, - /** - * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter - */ - maximumSize?: number, - /** - * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed. - */ - step?: number); + /** + * Defines the priority of this optimization (0 by default which means first in the list) + */ + priority?: number, + /** + * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter + */ + maximumSize?: number, + /** + * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed. + */ + step?: number); /** * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization * @param scene defines the current scene where to apply this optimization @@ -30179,18 +30204,18 @@ declare module BABYLON { * @param step defines the step to use between two passes (0.5 by default) */ constructor( - /** - * Defines the priority of this optimization (0 by default which means first in the list) - */ - priority?: number, - /** - * Defines the maximum scale to use (2 by default) - */ - maximumScale?: number, - /** - * Defines the step to use between two passes (0.5 by default) - */ - step?: number); + /** + * Defines the priority of this optimization (0 by default which means first in the list) + */ + priority?: number, + /** + * Defines the maximum scale to use (2 by default) + */ + maximumScale?: number, + /** + * Defines the step to use between two passes (0.5 by default) + */ + step?: number); /** * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization * @param scene defines the current scene where to apply this optimization @@ -30325,8 +30350,8 @@ declare module BABYLON { * Gets or sets a boolean which defines if optimization octree has to be updated */ /** - * Gets or sets a boolean which defines if optimization octree has to be updated - */ + * Gets or sets a boolean which defines if optimization octree has to be updated + */ static UpdateSelectionTree: boolean; /** * Gets a string describing the action executed by the current optimization @@ -30366,14 +30391,14 @@ declare module BABYLON { * @param trackerDuration defines the interval between two checkes (2000ms by default) */ constructor( - /** - * Defines the target frame rate to reach (60 by default) - */ - targetFrameRate?: number, - /** - * Defines the interval between two checkes (2000ms by default) - */ - trackerDuration?: number); + /** + * Defines the target frame rate to reach (60 by default) + */ + targetFrameRate?: number, + /** + * Defines the interval between two checkes (2000ms by default) + */ + trackerDuration?: number); /** * Add a new optimization * @param optimization defines the SceneOptimization to add to the list of active optimizations @@ -30449,15 +30474,15 @@ declare module BABYLON { * Gets or sets the current target frame rate (60 by default) */ /** - * Gets or sets the current target frame rate (60 by default) - */ + * Gets or sets the current target frame rate (60 by default) + */ targetFrameRate: number; /** * Gets or sets the current interval between two checks (every 2000ms by default) */ /** - * Gets or sets the current interval between two checks (every 2000ms by default) - */ + * Gets or sets the current interval between two checks (every 2000ms by default) + */ trackerDuration: number; /** * Gets the list of active optimizations @@ -30484,7 +30509,7 @@ declare module BABYLON { * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate */ start(): void; - private _checkCurrentState(); + private _checkCurrentState; /** * Release all resources */ @@ -30731,7 +30756,7 @@ declare module BABYLON { getFactor(): number; } class LoadFileError extends Error { - request: XMLHttpRequest | undefined; + request?: XMLHttpRequest | undefined; private static _setPrototypeOf; constructor(message: string, request?: XMLHttpRequest | undefined); } @@ -30966,14 +30991,14 @@ declare module BABYLON { static readonly WarningLogLevel: number; static readonly ErrorLogLevel: number; static readonly AllLogLevel: number; - private static _AddLogEntry(entry); - private static _FormatMessage(message); - private static _LogDisabled(message); - private static _LogEnabled(message); - private static _WarnDisabled(message); - private static _WarnEnabled(message); - private static _ErrorDisabled(message); - private static _ErrorEnabled(message); + private static _AddLogEntry; + private static _FormatMessage; + private static _LogDisabled; + private static _LogEnabled; + private static _WarnDisabled; + private static _WarnEnabled; + private static _ErrorDisabled; + private static _ErrorEnabled; static Log: (message: string) => void; static Warn: (message: string) => void; static Error: (message: string) => void; @@ -31092,7 +31117,7 @@ declare module BABYLON { * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter */ endMonitoring(newFrame?: boolean): void; - private _fetchResult(); + private _fetchResult; private _startMonitoringTime; private _min; private _max; @@ -31166,7 +31191,7 @@ declare module BABYLON { /** Y axis */ Y = 1, /** Z axis */ - Z = 2, + Z = 2 } /** * Class used to define virtual joystick (used in touch mode) @@ -31221,9 +31246,9 @@ declare module BABYLON { * @param newJoystickSensibility defines the new sensibility */ setJoystickSensibility(newJoystickSensibility: number): void; - private _onPointerDown(e); - private _onPointerMove(e); - private _onPointerUp(e); + private _onPointerDown; + private _onPointerMove; + private _onPointerUp; /** * Change the color of the virtual joystick * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000") @@ -31244,7 +31269,7 @@ declare module BABYLON { * @param axis defines the axis to use */ setAxisForUpDown(axis: JoystickAxis): void; - private _drawVirtualJoystick(); + private _drawVirtualJoystick; /** * Release internal HTML canvas */ @@ -31274,7 +31299,54 @@ declare module BABYLON { * @param action The action to perform. Call onComplete when the action is complete. */ push(action: (worker: Worker, onComplete: () => void) => void): void; - private _execute(workerInfo, action); + private _execute; + } +} + +declare module BABYLON { + interface IOctreeContainer { + blocks: Array>; + } + class Octree { + maxDepth: number; + blocks: Array>; + dynamicContent: T[]; + private _maxBlockCapacity; + private _selectionContent; + private _creationFunc; + constructor(creationFunc: (entry: T, block: OctreeBlock) => void, maxBlockCapacity?: number, maxDepth?: number); + update(worldMin: Vector3, worldMax: Vector3, entries: T[]): void; + addMesh(entry: T): void; + select(frustumPlanes: Plane[], allowDuplicate?: boolean): SmartArray; + intersects(sphereCenter: Vector3, sphereRadius: number, allowDuplicate?: boolean): SmartArray; + intersectsRay(ray: Ray): SmartArray; + static _CreateBlocks(worldMin: Vector3, worldMax: Vector3, entries: T[], maxBlockCapacity: number, currentDepth: number, maxDepth: number, target: IOctreeContainer, creationFunc: (entry: T, block: OctreeBlock) => void): void; + static CreationFuncForMeshes: (entry: AbstractMesh, block: OctreeBlock) => void; + static CreationFuncForSubMeshes: (entry: SubMesh, block: OctreeBlock) => void; + } +} + +declare module BABYLON { + class OctreeBlock { + entries: T[]; + blocks: Array>; + private _depth; + private _maxDepth; + private _capacity; + private _minPoint; + private _maxPoint; + private _boundingVectors; + private _creationFunc; + constructor(minPoint: Vector3, maxPoint: Vector3, capacity: number, depth: number, maxDepth: number, creationFunc: (entry: T, block: OctreeBlock) => void); + readonly capacity: number; + readonly minPoint: Vector3; + readonly maxPoint: Vector3; + addEntry(entry: T): void; + addEntries(entries: T[]): void; + select(frustumPlanes: Plane[], selection: SmartArrayNoDuplicate, allowDuplicate?: boolean): void; + intersects(sphereCenter: Vector3, sphereRadius: number, selection: SmartArrayNoDuplicate, allowDuplicate?: boolean): void; + intersectsRay(ray: Ray, selection: SmartArrayNoDuplicate): void; + createInnerBlocks(): void; } } @@ -31286,31 +31358,31 @@ declare module BABYLON { private _idleRotationWaitTime; private _idleRotationSpinupTime; /** - * Gets the flag that indicates if user zooming should stop animation. + * Sets the flag that indicates if user zooming should stop animation. */ /** - * Sets the flag that indicates if user zooming should stop animation. + * Gets the flag that indicates if user zooming should stop animation. */ zoomStopsAnimation: boolean; /** - * Gets the default speed at which the camera rotates around the model. + * Sets the default speed at which the camera rotates around the model. */ /** - * Sets the default speed at which the camera rotates around the model. + * Gets the default speed at which the camera rotates around the model. */ idleRotationSpeed: number; /** - * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating. + * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating. */ /** - * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating. + * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating. */ idleRotationWaitTime: number; /** - * Gets the time (milliseconds) to take to spin up to the full idle rotation speed. + * Sets the time (milliseconds) to take to spin up to the full idle rotation speed. */ /** - * Sets the time (milliseconds) to take to spin up to the full idle rotation speed. + * Gets the time (milliseconds) to take to spin up to the full idle rotation speed. */ idleRotationSpinupTime: number; /** @@ -31331,14 +31403,14 @@ declare module BABYLON { * Returns true if user is scrolling. * @return true if user is scrolling. */ - private _userIsZooming(); + private _userIsZooming; private _lastFrameRadius; - private _shouldAnimationStopForInteraction(); + private _shouldAnimationStopForInteraction; /** * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. */ - private _applyUserInteraction(); - private _userIsMoving(); + private _applyUserInteraction; + private _userIsMoving; } } @@ -31373,9 +31445,9 @@ declare module BABYLON { * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically */ /** - * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically - * Transition ranges will be set to 5% of the bounding box diagonal in world space - */ + * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically + * Transition ranges will be set to 5% of the bounding box diagonal in world space + */ autoTransitionRange: boolean; private _attachedCamera; private _onAfterCheckInputsObserver; @@ -31392,12 +31464,12 @@ declare module BABYLON { * @param radiusLimit The limit to check against. * @return Bool to indicate if at limit. */ - private _isRadiusAtLimit(radiusLimit); + private _isRadiusAtLimit; /** * Applies an animation to the radius of the camera, extending by the radiusDelta. * @param radiusDelta The delta by which to animate to. Can be negative. */ - private _applyBoundRadiusAnimation(radiusDelta); + private _applyBoundRadiusAnimation; /** * Removes all animation locks. Allows new animations to be added to any of the camera properties. */ @@ -31428,65 +31500,65 @@ declare module BABYLON { * The easing mode used by animations */ static EasingMode: number; - /** - * Gets current mode used by the behavior. - */ /** * Sets the current mode used by the behavior */ - mode: number; /** - * Gets the scale applied to the radius - */ + * Gets current mode used by the behavior. + */ + mode: number; /** * Sets the scale applied to the radius (1 by default) */ - radiusScale: number; /** - * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. - */ + * Gets the scale applied to the radius + */ + radiusScale: number; /** * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. */ + /** + * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. + */ positionScale: number; /** - * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle + * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle * behaviour is triggered, in radians. */ /** - * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle + * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle * behaviour is triggered, in radians. */ defaultElevation: number; - /** - * Gets the time (in milliseconds) taken to return to the default beta position. - * Negative value indicates camera should not return to default. - */ /** * Sets the time (in milliseconds) taken to return to the default beta position. * Negative value indicates camera should not return to default. */ - elevationReturnTime: number; /** - * Gets the delay (in milliseconds) taken before the camera returns to the default beta position. - */ + * Gets the time (in milliseconds) taken to return to the default beta position. + * Negative value indicates camera should not return to default. + */ + elevationReturnTime: number; /** * Sets the delay (in milliseconds) taken before the camera returns to the default beta position. */ - elevationReturnWaitTime: number; /** - * Gets the flag that indicates if user zooming should stop animation. + * Gets the delay (in milliseconds) taken before the camera returns to the default beta position. */ + elevationReturnWaitTime: number; /** * Sets the flag that indicates if user zooming should stop animation. */ - zoomStopsAnimation: boolean; /** - * Gets the transition time when framing the mesh, in milliseconds + * Gets the flag that indicates if user zooming should stop animation. */ + zoomStopsAnimation: boolean; /** * Sets the transition time when framing the mesh, in milliseconds */ + /** + * Gets the transition time when framing the mesh, in milliseconds + */ framingTime: number; private _onPrePointerObservableObserver; private _onAfterCheckInputsObserver; @@ -31550,20 +31622,20 @@ declare module BABYLON { * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera * is automatically returned to its default position (expected to be above ground plane). */ - private _maintainCameraAboveGround(); + private _maintainCameraAboveGround; /** * Returns the frustum slope based on the canvas ratio and camera FOV * @returns The frustum slope represented as a Vector2 with X and Y slopes */ - private _getFrustumSlope(); + private _getFrustumSlope; /** * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties. */ - private _clearAnimationLocks(); + private _clearAnimationLocks; /** * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. */ - private _applyUserInteraction(); + private _applyUserInteraction; /** * Stops and removes all animations that have been applied to the camera */ @@ -31616,10 +31688,10 @@ declare module BABYLON { * Initializes the behavior */ init(): void; - private _closestFace(targetDirection); + private _closestFace; private _zeroVector; private _lookAtTmpMatrix; - private _lookAtToRef(pos, up, ref); + private _lookAtToRef; /** * Attaches the AttachToBoxBehavior to the passed in mesh * @param target The mesh that the specified node will be attached to @@ -31653,7 +31725,7 @@ declare module BABYLON { * Initializes the behavior */ init(): void; - private _getCurrentDistance(); + private _getCurrentDistance; /** * Attaches the scale behavior the passed in mesh * @param ownerNode The mesh that will be scaled around once attached @@ -31777,7 +31849,7 @@ declare module BABYLON { */ attach(ownerNode: Mesh): void; releaseDrag(): void; - private _pickWithRayOnDragPlane(ray); + private _pickWithRayOnDragPlane; private _pointA; private _pointB; private _pointC; @@ -31785,7 +31857,7 @@ declare module BABYLON { private _lineB; private _localAxis; private _lookAt; - private _updateDragPlanePosition(ray, dragPlanePosition); + private _updateDragPlanePosition; /** * Detaches the behavior from the mesh */ @@ -31850,49 +31922,110 @@ declare module BABYLON { } declare module BABYLON { - interface IOctreeContainer { - blocks: Array>; - } - class Octree { - maxDepth: number; - blocks: Array>; - dynamicContent: T[]; - private _maxBlockCapacity; - private _selectionContent; - private _creationFunc; - constructor(creationFunc: (entry: T, block: OctreeBlock) => void, maxBlockCapacity?: number, maxDepth?: number); - update(worldMin: Vector3, worldMax: Vector3, entries: T[]): void; - addMesh(entry: T): void; - select(frustumPlanes: Plane[], allowDuplicate?: boolean): SmartArray; - intersects(sphereCenter: Vector3, sphereRadius: number, allowDuplicate?: boolean): SmartArray; - intersectsRay(ray: Ray): SmartArray; - static _CreateBlocks(worldMin: Vector3, worldMax: Vector3, entries: T[], maxBlockCapacity: number, currentDepth: number, maxDepth: number, target: IOctreeContainer, creationFunc: (entry: T, block: OctreeBlock) => void): void; - static CreationFuncForMeshes: (entry: AbstractMesh, block: OctreeBlock) => void; - static CreationFuncForSubMeshes: (entry: SubMesh, block: OctreeBlock) => void; + interface Engine { + /** + * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function) + * @return the new query + */ + createQuery(): WebGLQuery; + /** + * Delete and release a webGL query + * @param query defines the query to delete + * @return the current engine + */ + deleteQuery(query: WebGLQuery): Engine; + /** + * Check if a given query has resolved and got its value + * @param query defines the query to check + * @returns true if the query got its value + */ + isQueryResultAvailable(query: WebGLQuery): boolean; + /** + * Gets the value of a given query + * @param query defines the query to check + * @returns the value of the query + */ + getQueryResult(query: WebGLQuery): number; + /** + * Initiates an occlusion query + * @param algorithmType defines the algorithm to use + * @param query defines the query to use + * @returns the current engine + * @see http://doc.babylonjs.com/features/occlusionquery + */ + beginOcclusionQuery(algorithmType: number, query: WebGLQuery): Engine; + /** + * Ends an occlusion query + * @see http://doc.babylonjs.com/features/occlusionquery + * @param algorithmType defines the algorithm to use + * @returns the current engine + */ + endOcclusionQuery(algorithmType: number): Engine; + /** + * Starts a time query (used to measure time spent by the GPU on a specific frame) + * Please note that only one query can be issued at a time + * @returns a time token used to track the time span + */ + startTimeQuery(): Nullable<_TimeToken>; + /** + * Ends a time query + * @param token defines the token used to measure the time span + * @returns the time spent (in ns) + */ + endTimeQuery(token: _TimeToken): int; + /** @hidden */ + _currentNonTimestampToken: Nullable<_TimeToken>; + /** @hidden */ + _createTimeQuery(): WebGLQuery; + /** @hidden */ + _deleteTimeQuery(query: WebGLQuery): void; + /** @hidden */ + _getGlAlgorithmType(algorithmType: number): number; + /** @hidden */ + _getTimeQueryResult(query: WebGLQuery): any; + /** @hidden */ + _getTimeQueryAvailability(query: WebGLQuery): any; } } declare module BABYLON { - class OctreeBlock { - entries: T[]; - blocks: Array>; - private _depth; - private _maxDepth; - private _capacity; - private _minPoint; - private _maxPoint; - private _boundingVectors; - private _creationFunc; - constructor(minPoint: Vector3, maxPoint: Vector3, capacity: number, depth: number, maxDepth: number, creationFunc: (entry: T, block: OctreeBlock) => void); - readonly capacity: number; - readonly minPoint: Vector3; - readonly maxPoint: Vector3; - addEntry(entry: T): void; - addEntries(entries: T[]): void; - select(frustumPlanes: Plane[], selection: SmartArrayNoDuplicate, allowDuplicate?: boolean): void; - intersects(sphereCenter: Vector3, sphereRadius: number, selection: SmartArrayNoDuplicate, allowDuplicate?: boolean): void; - intersectsRay(ray: Ray, selection: SmartArrayNoDuplicate): void; - createInnerBlocks(): void; + interface Engine { + /** + * Creates a webGL transform feedback object + * Please makes sure to check webGLVersion property to check if you are running webGL 2+ + * @returns the webGL transform feedback object + */ + createTransformFeedback(): WebGLTransformFeedback; + /** + * Delete a webGL transform feedback object + * @param value defines the webGL transform feedback object to delete + */ + deleteTransformFeedback(value: WebGLTransformFeedback): void; + /** + * Bind a webGL transform feedback object to the webgl context + * @param value defines the webGL transform feedback object to bind + */ + bindTransformFeedback(value: Nullable): void; + /** + * Begins a transform feedback operation + * @param usePoints defines if points or triangles must be used + */ + beginTransformFeedback(usePoints: boolean): void; + /** + * Ends a transform feedback operation + */ + endTransformFeedback(): void; + /** + * Specify the varyings to use with transform feedback + * @param program defines the associated webGL program + * @param value defines the list of strings representing the varying names + */ + setTranformFeedbackVaryings(program: WebGLProgram, value: string[]): void; + /** + * Bind a webGL buffer for a transform feedback operation + * @param value defines the webGL buffer to bind + */ + bindTransformFeedbackBuffer(value: Nullable): void; } } @@ -32390,7 +32523,8 @@ declare module BABYLON { * See http://doc.babylonjs.com/how_to/webvr_helper */ class VRExperienceHelper { - /** Options to modify the vr experience helper's behavior. */ webVROptions: VRExperienceHelperOptions; + /** Options to modify the vr experience helper's behavior. */ + webVROptions: VRExperienceHelperOptions; private _scene; private _position; private _btnVR; @@ -32498,8 +32632,8 @@ declare module BABYLON { * The mesh used to display where the user is going to teleport. */ /** - * Sets the mesh to be used to display where the user is going to teleport. - */ + * Sets the mesh to be used to display where the user is going to teleport. + */ teleportationTarget: Mesh; /** * The mesh used to display where the user is selecting, @@ -32511,15 +32645,15 @@ declare module BABYLON { * If the ray of the gaze should be displayed. */ /** - * Sets if the ray of the gaze should be displayed. - */ + * Sets if the ray of the gaze should be displayed. + */ displayGaze: boolean; /** * If the ray of the LaserPointer should be displayed. */ /** - * Sets if the ray of the LaserPointer should be displayed. - */ + * Sets if the ray of the LaserPointer should be displayed. + */ displayLaserPointer: boolean; /** * The deviceOrientationCamera used as the camera when not in VR. @@ -32544,19 +32678,21 @@ declare module BABYLON { * @param scene The scene the VRExperienceHelper belongs to. * @param webVROptions Options to modify the vr experience helper's behavior. */ - constructor(scene: Scene, /** Options to modify the vr experience helper's behavior. */ webVROptions?: VRExperienceHelperOptions); - private _onDefaultMeshLoaded(webVRController); + constructor(scene: Scene, + /** Options to modify the vr experience helper's behavior. */ + webVROptions?: VRExperienceHelperOptions); + private _onDefaultMeshLoaded; private _onResize; private _onFullscreenChange; /** * Gets a value indicating if we are currently in VR mode. */ readonly isInVRMode: boolean; - private onVrDisplayPresentChange(); - private onVRDisplayChanged(eventArgs); - private moveButtonToBottomRight(); - private displayVRButton(); - private updateButtonVisibility(); + private onVrDisplayPresentChange; + private onVRDisplayChanged; + private moveButtonToBottomRight; + private displayVRButton; + private updateButtonVisibility; /** * Attempt to enter VR. If a headset is connected and ready, will request present on that. * Otherwise, will use the fullscreen API. @@ -32570,8 +32706,8 @@ declare module BABYLON { * The position of the vr experience helper. */ /** - * Sets the position of the vr experience helper. - */ + * Sets the position of the vr experience helper. + */ position: Vector3; /** * Enables controllers and user interactions such as selecting and object or clicking on an object. @@ -32579,7 +32715,7 @@ declare module BABYLON { enableInteractions(): void; private readonly _noControllerIsActive; private beforeRender; - private _isTeleportationFloor(mesh); + private _isTeleportationFloor; /** * Adds a floor mesh to be used for teleportation. * @param floorMesh the mesh to be used for teleportation. @@ -32598,23 +32734,23 @@ declare module BABYLON { private _onNewGamepadConnected; private _tryEnableInteractionOnController; private _onNewGamepadDisconnected; - private _enableInteractionOnController(controller); - private _checkTeleportWithRay(stateObject, gazer); - private _checkRotate(stateObject, gazer); - private _checkTeleportBackwards(stateObject, gazer); - private _enableTeleportationOnController(controller); - private _createTeleportationCircles(); - private _displayTeleportationTarget(); - private _hideTeleportationTarget(); - private _rotateCamera(right); - private _moveTeleportationSelectorTo(hit, gazer, ray); + private _enableInteractionOnController; + private _checkTeleportWithRay; + private _checkRotate; + private _checkTeleportBackwards; + private _enableTeleportationOnController; + private _createTeleportationCircles; + private _displayTeleportationTarget; + private _hideTeleportationTarget; + private _rotateCamera; + private _moveTeleportationSelectorTo; private _workingVector; private _workingQuaternion; private _workingMatrix; - private _teleportCamera(location); - private _convertNormalToDirectionOfRay(normal, ray); - private _castRayAndSelectObject(gazer); - private _notifySelectedMeshUnselected(mesh); + private _teleportCamera; + private _convertNormalToDirectionOfRay; + private _castRayAndSelectObject; + private _notifySelectedMeshUnselected; /** * Sets the color of the laser ray from the vr controllers. * @param color new color for the ray. @@ -32928,114 +33064,6 @@ declare module BABYLON { } } -declare module BABYLON { - interface Engine { - /** - * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function) - * @return the new query - */ - createQuery(): WebGLQuery; - /** - * Delete and release a webGL query - * @param query defines the query to delete - * @return the current engine - */ - deleteQuery(query: WebGLQuery): Engine; - /** - * Check if a given query has resolved and got its value - * @param query defines the query to check - * @returns true if the query got its value - */ - isQueryResultAvailable(query: WebGLQuery): boolean; - /** - * Gets the value of a given query - * @param query defines the query to check - * @returns the value of the query - */ - getQueryResult(query: WebGLQuery): number; - /** - * Initiates an occlusion query - * @param algorithmType defines the algorithm to use - * @param query defines the query to use - * @returns the current engine - * @see http://doc.babylonjs.com/features/occlusionquery - */ - beginOcclusionQuery(algorithmType: number, query: WebGLQuery): Engine; - /** - * Ends an occlusion query - * @see http://doc.babylonjs.com/features/occlusionquery - * @param algorithmType defines the algorithm to use - * @returns the current engine - */ - endOcclusionQuery(algorithmType: number): Engine; - /** - * Starts a time query (used to measure time spent by the GPU on a specific frame) - * Please note that only one query can be issued at a time - * @returns a time token used to track the time span - */ - startTimeQuery(): Nullable<_TimeToken>; - /** - * Ends a time query - * @param token defines the token used to measure the time span - * @returns the time spent (in ns) - */ - endTimeQuery(token: _TimeToken): int; - /** @hidden */ - _currentNonTimestampToken: Nullable<_TimeToken>; - /** @hidden */ - _createTimeQuery(): WebGLQuery; - /** @hidden */ - _deleteTimeQuery(query: WebGLQuery): void; - /** @hidden */ - _getGlAlgorithmType(algorithmType: number): number; - /** @hidden */ - _getTimeQueryResult(query: WebGLQuery): any; - /** @hidden */ - _getTimeQueryAvailability(query: WebGLQuery): any; - } -} - -declare module BABYLON { - interface Engine { - /** - * Creates a webGL transform feedback object - * Please makes sure to check webGLVersion property to check if you are running webGL 2+ - * @returns the webGL transform feedback object - */ - createTransformFeedback(): WebGLTransformFeedback; - /** - * Delete a webGL transform feedback object - * @param value defines the webGL transform feedback object to delete - */ - deleteTransformFeedback(value: WebGLTransformFeedback): void; - /** - * Bind a webGL transform feedback object to the webgl context - * @param value defines the webGL transform feedback object to bind - */ - bindTransformFeedback(value: Nullable): void; - /** - * Begins a transform feedback operation - * @param usePoints defines if points or triangles must be used - */ - beginTransformFeedback(usePoints: boolean): void; - /** - * Ends a transform feedback operation - */ - endTransformFeedback(): void; - /** - * Specify the varyings to use with transform feedback - * @param program defines the associated webGL program - * @param value defines the list of strings representing the varying names - */ - setTranformFeedbackVaryings(program: WebGLProgram, value: string[]): void; - /** - * Bind a webGL buffer for a transform feedback operation - * @param value defines the webGL buffer to bind - */ - bindTransformFeedbackBuffer(value: Nullable): void; - } -} - declare module BABYLON { /** * Google Daydream controller @@ -33251,7 +33279,7 @@ declare module BABYLON { /** * Generic */ - GENERIC = 5, + GENERIC = 5 } /** * Defines the MutableGamepadButton interface for the state of a gamepad button @@ -33524,9 +33552,9 @@ declare module BABYLON { * @param meshLoaded callback for when the mesh has been loaded */ abstract initControllerMesh(scene: Scene, meshLoaded?: (mesh: AbstractMesh) => void): void; - private _setButtonValue(newState, currentState, buttonIndex); + private _setButtonValue; private _changes; - private _checkChanges(newState, currentState); + private _checkChanges; /** * Disposes of th webVRCOntroller */ @@ -33602,7 +33630,7 @@ declare module BABYLON { * Fired when the touchpad values on this controller are modified */ readonly onTouchpadValuesChangedObservable: Observable; - private _updateTrackpad(); + private _updateTrackpad; /** * Called once per frame by the engine. */ @@ -33641,8 +33669,8 @@ declare module BABYLON { * @param meshes list of meshes that make up the controller model to process * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed. */ - private processModel(scene, meshes); - private createMeshInfo(rootNode); + private processModel; + private createMeshInfo; /** * Gets the ray of the controller in the direction the controller is pointing * @param length the length the resulting ray should be @@ -33656,6 +33684,9 @@ declare module BABYLON { } } +declare module BABYLON { +} + declare module BABYLON { /** * Interface to implement to create a shadow generator compatible with BJS. @@ -33810,16 +33841,16 @@ declare module BABYLON { * Gets the bias: offset applied on the depth preventing acnea (in light direction). */ /** - * Sets the bias: offset applied on the depth preventing acnea (in light direction). - */ + * Sets the bias: offset applied on the depth preventing acnea (in light direction). + */ bias: number; private _normalBias; /** * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle). */ /** - * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle). - */ + * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle). + */ normalBias: number; private _blurBoxOffset; /** @@ -33827,9 +33858,9 @@ declare module BABYLON { * Only usefull if useKernelBlur = false */ /** - * Sets the blur box offset: offset applied during the blur pass. - * Only usefull if useKernelBlur = false - */ + * Sets the blur box offset: offset applied during the blur pass. + * Only usefull if useKernelBlur = false + */ blurBoxOffset: number; private _blurScale; /** @@ -33837,9 +33868,9 @@ declare module BABYLON { * 2 means half of the size. */ /** - * Sets the blur scale: scale of the blurred texture compared to the main shadow map. - * 2 means half of the size. - */ + * Sets the blur scale: scale of the blurred texture compared to the main shadow map. + * 2 means half of the size. + */ blurScale: number; private _blurKernel; /** @@ -33847,9 +33878,9 @@ declare module BABYLON { * Only usefull if useKernelBlur = true */ /** - * Sets the blur kernel: kernel size of the blur pass. - * Only usefull if useKernelBlur = true - */ + * Sets the blur kernel: kernel size of the blur pass. + * Only usefull if useKernelBlur = true + */ blurKernel: number; private _useKernelBlur; /** @@ -33857,18 +33888,18 @@ declare module BABYLON { * Only usefull in filtered mode (useBlurExponentialShadowMap...) */ /** - * Sets whether the blur pass is a kernel blur (if true) or box blur. - * Only usefull in filtered mode (useBlurExponentialShadowMap...) - */ + * Sets whether the blur pass is a kernel blur (if true) or box blur. + * Only usefull in filtered mode (useBlurExponentialShadowMap...) + */ useKernelBlur: boolean; private _depthScale; /** * Gets the depth scale used in ESM mode. */ /** - * Sets the depth scale used in ESM mode. - * This can override the scale stored on the light. - */ + * Sets the depth scale used in ESM mode. + * This can override the scale stored on the light. + */ depthScale: number; private _filter; /** @@ -33876,73 +33907,73 @@ declare module BABYLON { * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE */ /** - * Sets the current mode of the shadow generator (normal, PCF, ESM...). - * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE - */ + * Sets the current mode of the shadow generator (normal, PCF, ESM...). + * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE + */ filter: number; /** * Gets if the current filter is set to Poisson Sampling. */ /** - * Sets the current filter to Poisson Sampling. - */ + * Sets the current filter to Poisson Sampling. + */ usePoissonSampling: boolean; /** * Gets if the current filter is set to VSM. * DEPRECATED. Should use useExponentialShadowMap instead. */ /** - * Sets the current filter is to VSM. - * DEPRECATED. Should use useExponentialShadowMap instead. - */ + * Sets the current filter is to VSM. + * DEPRECATED. Should use useExponentialShadowMap instead. + */ useVarianceShadowMap: boolean; /** * Gets if the current filter is set to blurred VSM. * DEPRECATED. Should use useBlurExponentialShadowMap instead. */ /** - * Sets the current filter is to blurred VSM. - * DEPRECATED. Should use useBlurExponentialShadowMap instead. - */ + * Sets the current filter is to blurred VSM. + * DEPRECATED. Should use useBlurExponentialShadowMap instead. + */ useBlurVarianceShadowMap: boolean; /** * Gets if the current filter is set to ESM. */ /** - * Sets the current filter is to ESM. - */ + * Sets the current filter is to ESM. + */ useExponentialShadowMap: boolean; /** * Gets if the current filter is set to filtered ESM. */ /** - * Gets if the current filter is set to filtered ESM. - */ + * Gets if the current filter is set to filtered ESM. + */ useBlurExponentialShadowMap: boolean; /** * Gets if the current filter is set to "close ESM" (using the inverse of the * exponential to prevent steep falloff artifacts). */ /** - * Sets the current filter to "close ESM" (using the inverse of the - * exponential to prevent steep falloff artifacts). - */ + * Sets the current filter to "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). + */ useCloseExponentialShadowMap: boolean; /** * Gets if the current filter is set to filtered "close ESM" (using the inverse of the * exponential to prevent steep falloff artifacts). */ /** - * Sets the current filter to filtered "close ESM" (using the inverse of the - * exponential to prevent steep falloff artifacts). - */ + * Sets the current filter to filtered "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). + */ useBlurCloseExponentialShadowMap: boolean; /** * Gets if the current filter is set to "PCF" (percentage closer filtering). */ /** - * Sets the current filter to "PCF" (percentage closer filtering). - */ + * Sets the current filter to "PCF" (percentage closer filtering). + */ usePercentageCloserFiltering: boolean; private _filteringQuality; /** @@ -33950,16 +33981,16 @@ declare module BABYLON { * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. */ /** - * Sets the PCF or PCSS Quality. - * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. - */ + * Sets the PCF or PCSS Quality. + * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. + */ filteringQuality: number; /** * Gets if the current filter is set to "PCSS" (contact hardening). */ /** - * Sets the current filter to "PCSS" (contact hardening). - */ + * Sets the current filter to "PCSS" (contact hardening). + */ useContactHardeningShadow: boolean; private _contactHardeningLightSizeUVRatio; /** @@ -33972,14 +34003,14 @@ declare module BABYLON { * Only valid if useContactHardeningShadow is true. */ /** - * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. - * Using a ratio helps keeping shape stability independently of the map size. - * - * It does not account for the light projection as it was having too much - * instability during the light setup or during light position changes. - * - * Only valid if useContactHardeningShadow is true. - */ + * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. + * Using a ratio helps keeping shape stability independently of the map size. + * + * It does not account for the light projection as it was having too much + * instability during the light setup or during light position changes. + * + * Only valid if useContactHardeningShadow is true. + */ contactHardeningLightSizeUVRatio: number; private _darkness; /** @@ -34073,12 +34104,12 @@ declare module BABYLON { * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture. */ constructor(mapSize: number, light: IShadowLight, useFullFloatFirst?: boolean); - private _initializeGenerator(); - private _initializeShadowMap(); - private _initializeBlurRTTAndPostProcesses(); - private _renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes); - private _renderSubMeshForShadowMap(subMesh); - private _applyFilterValues(); + private _initializeGenerator; + private _initializeShadowMap; + private _initializeBlurRTTAndPostProcesses; + private _renderForShadowMap; + private _renderSubMeshForShadowMap; + private _applyFilterValues; /** * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects. * @param onCompiled Callback triggered at the and of the effects compilation @@ -34126,8 +34157,8 @@ declare module BABYLON { * Cube and 2D textures for instance. */ recreateShadowMap(): void; - private _disposeBlurPostProcesses(); - private _disposeRTTandPostProcesses(); + private _disposeBlurPostProcesses; + private _disposeRTTandPostProcesses; /** * Disposes the ShadowGenerator. * Returns nothing. @@ -34148,9 +34179,6 @@ declare module BABYLON { } } -declare module BABYLON { -} - declare module BABYLON { /** * Background material used to create an efficient environement around your scene. @@ -34312,31 +34340,31 @@ declare module BABYLON { * Gets the image processing configuration used either in this material. */ /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ imageProcessingConfiguration: Nullable; /** * Gets wether the color curves effect is enabled. */ /** - * Sets wether the color curves effect is enabled. - */ + * Sets wether the color curves effect is enabled. + */ cameraColorCurvesEnabled: boolean; /** * Gets wether the color grading effect is enabled. */ /** - * Gets wether the color grading effect is enabled. - */ + * Gets wether the color grading effect is enabled. + */ cameraColorGradingEnabled: boolean; /** * Gets wether tonemapping is enabled or not. */ /** - * Sets wether tonemapping is enabled or not - */ + * Sets wether tonemapping is enabled or not + */ cameraToneMappingEnabled: boolean; /** * The camera exposure used on this material. @@ -34344,24 +34372,24 @@ declare module BABYLON { * This corresponds to a photographic exposure. */ /** - * The camera exposure used on this material. - * This property is here and not in the camera to allow controlling exposure without full screen post process. - * This corresponds to a photographic exposure. - */ + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ cameraExposure: float; /** * Gets The camera contrast used on this material. */ /** - * Sets The camera contrast used on this material. - */ + * Sets The camera contrast used on this material. + */ cameraContrast: float; /** * Gets the Color Grading 2D Lookup Texture. */ /** - * Sets the Color Grading 2D Lookup Texture. - */ + * Sets the Color Grading 2D Lookup Texture. + */ cameraColorGradingTexture: Nullable; /** * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). @@ -34370,11 +34398,11 @@ declare module BABYLON { * corresponding to low luminance, medium luminance, and high luminance areas respectively. */ /** - * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). - * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. - * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; - * corresponding to low luminance, medium luminance, and high luminance areas respectively. - */ + * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ cameraColorCurves: Nullable; /** * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB. @@ -34413,11 +34441,11 @@ declare module BABYLON { /** * Compute the primary color according to the chosen perceptual color. */ - private _computePrimaryColorFromPerceptualColor(); + private _computePrimaryColorFromPerceptualColor; /** * Compute the highlights and shadow colors according to their chosen levels. */ - private _computePrimaryColors(); + private _computePrimaryColors; /** * Build the uniform buffer used in the material. */ @@ -34788,23 +34816,23 @@ declare module BABYLON { * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers. */ /** - * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers. - */ + * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers. + */ useLogarithmicDepth: boolean; /** * Gets the current transparency mode. */ /** - * Sets the transparency mode of the material. - * - * | Value | Type | Description | - * | ----- | ----------------------------------- | ----------- | - * | 0 | OPAQUE | | - * | 1 | ALPHATEST | | - * | 2 | ALPHABLEND | | - * | 3 | ALPHATESTANDBLEND | | - * - */ + * Sets the transparency mode of the material. + * + * | Value | Type | Description | + * | ----- | ----------------------------------- | ----------- | + * | 0 | OPAQUE | | + * | 1 | ALPHATEST | | + * | 2 | ALPHABLEND | | + * | 3 | ALPHATESTANDBLEND | | + * + */ transparencyMode: Nullable; /** * Returns true if alpha blending should be disabled. @@ -34848,8 +34876,8 @@ declare module BABYLON { * @returns boolean specifiying if the material uses metallic roughness workflow. */ isMetallicWorkflow(): boolean; - private _prepareEffect(mesh, defines, onCompiled?, onError?, useInstances?, useClipPlane?); - private _prepareDefines(mesh, defines, useInstances?, useClipPlane?); + private _prepareEffect; + private _prepareDefines; /** * Force shader compilation */ @@ -34880,13 +34908,13 @@ declare module BABYLON { * Returns the texture used for reflections. * @returns - Reflection texture if present. Otherwise, returns the environment texture. */ - private _getReflectionTexture(); + private _getReflectionTexture; /** * Returns the texture used for refraction or null if none is used. * @returns - Refection texture if present. If no refraction texture and refraction * is linked with transparency, returns environment texture. Otherwise, returns null. */ - private _getRefractionTexture(); + private _getRefractionTexture; /** * Disposes the resources of the material. * @param forceDisposeEffect - Forces the disposal of effects. @@ -34952,8 +34980,8 @@ declare module BABYLON { * Gets the current double sided mode. */ /** - * If sets to true and backfaceCulling is false, normals will be flipped on the backside. - */ + * If sets to true and backfaceCulling is false, normals will be flipped on the backside. + */ doubleSided: boolean; lightmapTexture: BaseTexture; useLightmapAsShadowmap: boolean; @@ -35274,31 +35302,31 @@ declare module BABYLON { * Gets the image processing configuration used either in this material. */ /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ imageProcessingConfiguration: ImageProcessingConfiguration; /** * Gets wether the color curves effect is enabled. */ /** - * Sets wether the color curves effect is enabled. - */ + * Sets wether the color curves effect is enabled. + */ cameraColorCurvesEnabled: boolean; /** * Gets wether the color grading effect is enabled. */ /** - * Gets wether the color grading effect is enabled. - */ + * Gets wether the color grading effect is enabled. + */ cameraColorGradingEnabled: boolean; /** * Gets wether tonemapping is enabled or not. */ /** - * Sets wether tonemapping is enabled or not - */ + * Sets wether tonemapping is enabled or not + */ cameraToneMappingEnabled: boolean; /** * The camera exposure used on this material. @@ -35306,24 +35334,24 @@ declare module BABYLON { * This corresponds to a photographic exposure. */ /** - * The camera exposure used on this material. - * This property is here and not in the camera to allow controlling exposure without full screen post process. - * This corresponds to a photographic exposure. - */ + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ cameraExposure: number; /** * Gets The camera contrast used on this material. */ /** - * Sets The camera contrast used on this material. - */ + * Sets The camera contrast used on this material. + */ cameraContrast: number; /** * Gets the Color Grading 2D Lookup Texture. */ /** - * Sets the Color Grading 2D Lookup Texture. - */ + * Sets the Color Grading 2D Lookup Texture. + */ cameraColorGradingTexture: Nullable; /** * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). @@ -35332,11 +35360,11 @@ declare module BABYLON { * corresponding to low luminance, medium luminance, and high luminance areas respectively. */ /** - * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). - * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. - * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; - * corresponding to low luminance, medium luminance, and high luminance areas respectively. - */ + * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ cameraColorCurves: Nullable; /** * Instantiates a new PBRMaterial instance. @@ -35674,11 +35702,11 @@ declare module BABYLON { /** * Occurs when the file being loaded is a .3dl LUT file. */ - private load3dlTexture(); + private load3dlTexture; /** * Starts the loading process of the texture. */ - private loadTexture(); + private loadTexture; /** * Clones the color gradind texture. */ @@ -35719,12 +35747,12 @@ declare module BABYLON { */ boundingBoxSize: Vector3; protected _rotationY: number; - /** - * Gets texture matrix rotation angle around Y axis radians. - */ /** * Sets texture matrix rotation angle around Y axis in radians. */ + /** + * Gets texture matrix rotation angle around Y axis radians. + */ rotationY: number; private _noMipmap; private _files; @@ -35795,7 +35823,7 @@ declare module BABYLON { * Gets the current state of canRescale */ readonly canRescale: boolean; - private _recreate(textureSize); + private _recreate; /** * Scales the texture * @param ratio the scale factor to apply to both width and height @@ -35873,20 +35901,20 @@ declare module BABYLON { */ coordinatesMode: number; protected _isBlocking: boolean; - /** - * Gets wether or not the texture is blocking during loading. - */ /** * Sets wether or not the texture is blocking during loading. */ + /** + * Gets wether or not the texture is blocking during loading. + */ isBlocking: boolean; protected _rotationY: number; - /** - * Gets texture matrix rotation angle around Y axis radians. - */ /** * Sets texture matrix rotation angle around Y axis in radians. */ + /** + * Gets texture matrix rotation angle around Y axis radians. + */ rotationY: number; /** * Gets or sets the center of the bounding box associated with the cube texture @@ -35916,7 +35944,7 @@ declare module BABYLON { /** * Occurs when the file is raw .hdr file. */ - private loadTexture(); + private loadTexture; clone(): HDRCubeTexture; delayLoad(): void; getReflectionTextureMatrix(): Matrix; @@ -36268,9 +36296,9 @@ declare module BABYLON { blurKernel: number; blurKernelX: number; blurKernelY: number; - private _autoComputeBlurKernel(); + private _autoComputeBlurKernel; protected _onRatioRescale(): void; - private _updateGammaSpace(); + private _updateGammaSpace; private _imageProcessingConfigChangeObserver; constructor(name: string, size: number | { width: number; @@ -36278,7 +36306,7 @@ declare module BABYLON { } | { ratio: number; }, scene: Scene, generateMipMaps?: boolean, type?: number, samplingMode?: number, generateDepthBuffer?: boolean); - private _preparePostProcesses(); + private _preparePostProcesses; clone(): MirrorTexture; serialize(): any; dispose(): void; @@ -36308,8 +36336,8 @@ declare module BABYLON { wrapV: number; constructor(name: string, size: any, count: number, scene: Scene, options?: IMultiRenderTargetOptions); _rebuild(): void; - private _createInternalTextures(); - private _createTextures(); + private _createInternalTextures; + private _createTextures; samples: number; resize(size: any): void; protected unbindFrameBuffer(engine: Engine, faceIndex: number): void; @@ -36402,8 +36430,8 @@ declare module BABYLON { * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...) */ constructor(data: ArrayBufferView, width: number, height: number, depth: number, - /** Gets or sets the texture format to use */ - format: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number, textureType?: number); + /** Gets or sets the texture format to use */ + format: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number, textureType?: number); /** * Update the texture with new data * @param data defines the data to store in the texture @@ -36447,7 +36475,7 @@ declare module BABYLON { * Use this list to define the list of mesh you want to render. */ renderList: Nullable>; - private _hookArray(array); + private _hookArray; renderParticles: boolean; renderSprites: boolean; coordinatesMode: number; @@ -36559,7 +36587,7 @@ declare module BABYLON { * @param generateStencil Specifies whether or not a stencil should be allocated in the texture */ createDepthStencilTexture(comparisonFunction?: number, bilinearFiltering?: boolean, generateStencil?: boolean): void; - private _processSizeParameter(size); + private _processSizeParameter; samples: number; resetRefreshCounter(): void; refreshRate: number; @@ -36580,9 +36608,9 @@ declare module BABYLON { ratio: number; }): void; render(useCameraPostProcess?: boolean, dumpForDebug?: boolean): void; - private _bestReflectionRenderTargetDimension(renderDimension, scale); + private _bestReflectionRenderTargetDimension; protected unbindFrameBuffer(engine: Engine, faceIndex: number): void; - private renderToTarget(faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug); + private renderToTarget; /** * Overrides the default sort function applied in the renderging group to prepare the meshes. * This allowed control for front to back rendering or reversly depending of the special needs. @@ -36704,7 +36732,7 @@ declare module BABYLON { updateURL(url: string, buffer?: Nullable): void; delayLoad(): void; updateSamplingMode(samplingMode: number): void; - private _prepareRowForTextureGeneration(x, y, z, t); + private _prepareRowForTextureGeneration; getTextureMatrix(): Matrix; getReflectionTextureMatrix(): Matrix; clone(): Texture; @@ -36767,8 +36795,8 @@ declare module BABYLON { * @param {VideoTextureSettings} [settings] allows finer control over video usage */ constructor(name: Nullable, src: string | string[] | HTMLVideoElement, scene: Nullable, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number, settings?: VideoTextureSettings); - private _getName(src); - private _getVideo(src); + private _getName; + private _getVideo; private _createInternalTexture; private reset; /** @@ -36801,6 +36829,105 @@ declare module BABYLON { } } +declare var DracoDecoderModule: any; +declare var WebAssembly: any; +declare module BABYLON { + /** + * Configuration for Draco compression + */ + interface IDracoCompressionConfiguration { + /** + * Configuration for the decoder. + */ + decoder?: { + /** + * The url to the WebAssembly module. + */ + wasmUrl?: string; + /** + * The url to the WebAssembly binary. + */ + wasmBinaryUrl?: string; + /** + * The url to the fallback JavaScript module. + */ + fallbackUrl?: string; + }; + } + /** + * Draco compression (https://google.github.io/draco/) + * + * This class wraps the Draco module. + * + * **Encoder** + * + * The encoder is not currently implemented. + * + * **Decoder** + * + * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com. + * + * To update the configuration, use the following code: + * ```javascript + * BABYLON.DracoCompression.Configuration = { + * decoder: { + * wasmUrl: "", + * wasmBinaryUrl: "", + * fallbackUrl: "", + * } + * }; + * ``` + * + * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version. + * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser. + * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session. + * + * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync: + * ```javascript + * var dracoCompression = new BABYLON.DracoCompression(); + * var vertexData = await dracoCompression.decodeMeshAsync(data, { + * [BABYLON.VertexBuffer.PositionKind]: 0 + * }); + * ``` + * + * @see https://www.babylonjs-playground.com/#N3EK4B#0 + */ + class DracoCompression implements IDisposable { + private static _DecoderModulePromise; + /** + * The configuration. Defaults to the following urls: + * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js" + * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm" + * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js" + */ + static Configuration: IDracoCompressionConfiguration; + /** + * Returns true if the decoder is available. + */ + static readonly DecoderAvailable: boolean; + /** + * Constructor + */ + constructor(); + /** + * Stop all async operations and release resources. + */ + dispose(): void; + /** + * Decode Draco compressed mesh data to vertex data. + * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data + * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids + * @returns A promise that resolves with the decoded vertex data + */ + decodeMeshAsync(data: ArrayBuffer | ArrayBufferView, attributes: { + [kind: string]: number; + }): Promise; + private static _GetDecoderModule; + private static _LoadScriptAsync; + private static _LoadFileAsync; + } +} + declare module BABYLON { class CannonJSPlugin implements IPhysicsEnginePlugin { private _useDeltaForWorldStep; @@ -36817,20 +36944,20 @@ declare module BABYLON { applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3): void; applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3): void; generatePhysicsBody(impostor: PhysicsImpostor): void; - private _processChildMeshes(mainImpostor); + private _processChildMeshes; removePhysicsBody(impostor: PhysicsImpostor): void; generateJoint(impostorJoint: PhysicsImpostorJoint): void; removeJoint(impostorJoint: PhysicsImpostorJoint): void; - private _addMaterial(name, friction, restitution); - private _checkWithEpsilon(value); - private _createShape(impostor); - private _createHeightmap(object, pointDepth?); + private _addMaterial; + private _checkWithEpsilon; + private _createShape; + private _createHeightmap; private _minus90X; private _plus90X; private _tmpPosition; private _tmpDeltaPosition; private _tmpUnityRotation; - private _updatePhysicsBodyTransformation(impostor); + private _updatePhysicsBodyTransformation; setTransformationFromPhysicsBody(impostor: PhysicsImpostor): void; setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion): void; isSupported(): boolean; @@ -36853,7 +36980,7 @@ declare module BABYLON { getRadius(impostor: PhysicsImpostor): number; getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void; dispose(): void; - private _extendNamespace(); + private _extendNamespace; } } @@ -37005,7 +37132,7 @@ declare module BABYLON { * Gets or sets the angle of the emission cone */ angle: number; - private _buildHeight(); + private _buildHeight; /** * Creates a new instance ConeParticleEmitter * @param radius the radius of the emission cone (1 by default) @@ -37013,8 +37140,8 @@ declare module BABYLON { * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0) */ constructor(radius?: number, angle?: number, - /** defines how much to randomize the particle direction [0-1] (default is 0) */ - directionRandomizer?: number); + /** defines how much to randomize the particle direction [0-1] (default is 0) */ + directionRandomizer?: number); /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system @@ -37087,18 +37214,18 @@ declare module BABYLON { * @param directionRandomizer defines how much to randomize the particle direction [0-1] */ constructor( - /** - * The radius of the emission hemisphere. - */ - radius?: number, - /** - * The range of emission [0-1] 0 Surface only, 1 Entire Radius. - */ - radiusRange?: number, - /** - * How much to randomize the particle direction [0-1]. - */ - directionRandomizer?: number); + /** + * The radius of the emission hemisphere. + */ + radius?: number, + /** + * The range of emission [0-1] 0 Surface only, 1 Entire Radius. + */ + radiusRange?: number, + /** + * How much to randomize the particle direction [0-1]. + */ + directionRandomizer?: number); /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system @@ -37289,18 +37416,18 @@ declare module BABYLON { * @param directionRandomizer defines how much to randomize the particle direction [0-1] */ constructor( - /** - * The radius of the emission sphere. - */ - radius?: number, - /** - * The range of emission [0-1] 0 Surface only, 1 Entire Radius. - */ - radiusRange?: number, - /** - * How much to randomize the particle direction [0-1]. - */ - directionRandomizer?: number); + /** + * The radius of the emission sphere. + */ + radius?: number, + /** + * The range of emission [0-1] 0 Surface only, 1 Entire Radius. + */ + radiusRange?: number, + /** + * How much to randomize the particle direction [0-1]. + */ + directionRandomizer?: number); /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system @@ -37366,14 +37493,14 @@ declare module BABYLON { * @param direction2 the max limit of the emission direction (up vector by default) */ constructor(radius?: number, - /** - * The min limit of the emission direction. - */ - direction1?: Vector3, - /** - * The max limit of the emission direction. - */ - direction2?: Vector3); + /** + * The min limit of the emission direction. + */ + direction1?: Vector3, + /** + * The max limit of the emission direction. + */ + direction2?: Vector3); /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system @@ -37414,105 +37541,6 @@ declare module BABYLON { } } -declare var DracoDecoderModule: any; -declare var WebAssembly: any; -declare module BABYLON { - /** - * Configuration for Draco compression - */ - interface IDracoCompressionConfiguration { - /** - * Configuration for the decoder. - */ - decoder?: { - /** - * The url to the WebAssembly module. - */ - wasmUrl?: string; - /** - * The url to the WebAssembly binary. - */ - wasmBinaryUrl?: string; - /** - * The url to the fallback JavaScript module. - */ - fallbackUrl?: string; - }; - } - /** - * Draco compression (https://google.github.io/draco/) - * - * This class wraps the Draco module. - * - * **Encoder** - * - * The encoder is not currently implemented. - * - * **Decoder** - * - * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com. - * - * To update the configuration, use the following code: - * ```javascript - * BABYLON.DracoCompression.Configuration = { - * decoder: { - * wasmUrl: "", - * wasmBinaryUrl: "", - * fallbackUrl: "", - * } - * }; - * ``` - * - * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version. - * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser. - * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session. - * - * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync: - * ```javascript - * var dracoCompression = new BABYLON.DracoCompression(); - * var vertexData = await dracoCompression.decodeMeshAsync(data, { - * [BABYLON.VertexBuffer.PositionKind]: 0 - * }); - * ``` - * - * @see https://www.babylonjs-playground.com/#N3EK4B#0 - */ - class DracoCompression implements IDisposable { - private static _DecoderModulePromise; - /** - * The configuration. Defaults to the following urls: - * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js" - * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm" - * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js" - */ - static Configuration: IDracoCompressionConfiguration; - /** - * Returns true if the decoder is available. - */ - static readonly DecoderAvailable: boolean; - /** - * Constructor - */ - constructor(); - /** - * Stop all async operations and release resources. - */ - dispose(): void; - /** - * Decode Draco compressed mesh data to vertex data. - * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data - * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids - * @returns A promise that resolves with the decoded vertex data - */ - decodeMeshAsync(data: ArrayBuffer | ArrayBufferView, attributes: { - [kind: string]: number; - }): Promise; - private static _GetDecoderModule(); - private static _LoadScriptAsync(url); - private static _LoadFileAsync(url); - } -} - declare module BABYLON { /** * This represents a set of one or more post processes in Babylon. @@ -37689,9 +37717,9 @@ declare module BABYLON { * This groups tools to convert HDR texture to native colors array. */ class HDRTools { - private static Ldexp(mantissa, exponent); - private static Rgbe2float(float32array, red, green, blue, exponent, index); - private static readStringLine(uint8array, startIndex); + private static Ldexp; + private static Rgbe2float; + private static readStringLine; /** * Reads header information from an RGBE texture stored in a native array. * More information on this format are available here: @@ -37725,7 +37753,7 @@ declare module BABYLON { * @return The pixels data in RGB right to left up to down order. */ static RGBE_ReadPixels(uint8array: Uint8Array, hdrInfo: HDRInfo): Float32Array; - private static RGBE_ReadPixels_RLE(uint8array, hdrInfo); + private static RGBE_ReadPixels_RLE; } } @@ -37807,8 +37835,8 @@ declare module BABYLON { * @return The cubemap data */ static ConvertPanoramaToCubemap(float32Array: Float32Array, inputWidth: number, inputHeight: number, size: number): CubeMapInfo; - private static CreateCubemapTexture(texSize, faceData, float32Array, inputWidth, inputHeight); - private static CalcProjectionSpherical(vDir, float32Array, inputWidth, inputHeight); + private static CreateCubemapTexture; + private static CalcProjectionSpherical; } } @@ -37831,7 +37859,7 @@ declare module BABYLON { private _config; private _texturePath; constructor(name: string, texturePath: any, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); - private loadJson(jsonUrl); + private loadJson; isReady(): boolean; render(useCameraPostProcess?: boolean): void; updateTextures(): void; @@ -37863,7 +37891,7 @@ declare module BABYLON { * @param generateMipMaps defines if mipmaps must be generated (true by default) */ constructor(name: string, size?: number, scene?: Nullable, fallbackTexture?: Texture, generateMipMaps?: boolean); - private _updateShaderUniforms(); + private _updateShaderUniforms; /** Generate the current state of the procedural texture */ render(useCameraPostProcess?: boolean): void; /** @@ -37912,7 +37940,7 @@ declare module BABYLON { private _fallbackTextureUsed; private _engine; constructor(name: string, size: any, fragment: any, scene: Nullable, fallbackTexture?: Nullable, generateMipMaps?: boolean, isCube?: boolean); - private _createIndexBuffer(); + private _createIndexBuffer; _rebuild(): void; reset(): void; isReady(): boolean; @@ -37922,7 +37950,7 @@ declare module BABYLON { _shouldRender(): boolean; getRenderSize(): number; resize(size: number, generateMipMaps: boolean): void; - private _checkUniform(uniformName); + private _checkUniform; setTexture(name: string, texture: Texture): ProceduralTexture; setFloat(name: string, value: number): ProceduralTexture; /** @@ -38056,7 +38084,7 @@ declare module BABYLON { * Enable or disable the bloom from the pipeline */ bloomEnabled: boolean; - private _rebuildBloom(); + private _rebuildBloom; /** * If the depth of field is enabled. */ @@ -38106,9 +38134,9 @@ declare module BABYLON { private _hasCleared; private _prevPostProcess; private _prevPrevPostProcess; - private _setAutoClearAndTextureSharing(postProcess, skipTextureSharing?); - private _buildPipeline(); - private _disposePostProcesses(disposeNonRecreated?); + private _setAutoClearAndTextureSharing; + private _buildPipeline; + private _disposePostProcesses; /** * Adds a camera to the pipeline * @param camera the camera to be added @@ -38220,10 +38248,10 @@ declare module BABYLON { * Removes the internal pipeline assets and detaches the pipeline from the scene cameras */ dispose(disableDepthRender?: boolean): void; - private _createChromaticAberrationPostProcess(ratio); - private _createHighlightsPostProcess(ratio); - private _createDepthOfFieldPostProcess(ratio); - private _createGrainTexture(); + private _createChromaticAberrationPostProcess; + private _createHighlightsPostProcess; + private _createDepthOfFieldPostProcess; + private _createGrainTexture; } } @@ -38318,12 +38346,12 @@ declare module BABYLON { * Removes the internal pipeline assets and detatches the pipeline from the scene cameras */ dispose(disableGeometryBufferRenderer?: boolean): void; - private _createBlurPostProcess(ssaoRatio, blurRatio); + private _createBlurPostProcess; _rebuild(): void; - private _generateHemisphere(); - private _createSSAOPostProcess(ratio); - private _createSSAOCombinePostProcess(ratio); - private _createRandomTexture(); + private _generateHemisphere; + private _createSSAOPostProcess; + private _createSSAOCombinePostProcess; + private _createRandomTexture; /** * Serialize the rendering pipeline (Used when exporting) * @returns the serialized object @@ -38408,11 +38436,11 @@ declare module BABYLON { * Removes the internal pipeline assets and detatches the pipeline from the scene cameras */ dispose(disableDepthRender?: boolean): void; - private _createBlurPostProcess(ratio); + private _createBlurPostProcess; _rebuild(): void; - private _createSSAOPostProcess(ratio); - private _createSSAOCombinePostProcess(ratio); - private _createRandomTexture(); + private _createSSAOPostProcess; + private _createSSAOCombinePostProcess; + private _createRandomTexture; } } @@ -38499,19 +38527,19 @@ declare module BABYLON { * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to */ constructor(name: string, scene: Scene, ratio: number, originalPostProcess?: Nullable, cameras?: Camera[]); - private _buildPipeline(); - private _createDownSampleX4PostProcess(scene, ratio); - private _createBrightPassPostProcess(scene, ratio); - private _createBlurPostProcesses(scene, ratio, indice, blurWidthKey?); - private _createTextureAdderPostProcess(scene, ratio); - private _createVolumetricLightPostProcess(scene, ratio); - private _createLuminancePostProcesses(scene, textureType); - private _createHdrPostProcess(scene, ratio); - private _createLensFlarePostProcess(scene, ratio); - private _createDepthOfFieldPostProcess(scene, ratio); - private _createMotionBlurPostProcess(scene, ratio); - private _getDepthTexture(); - private _disposePostProcesses(); + private _buildPipeline; + private _createDownSampleX4PostProcess; + private _createBrightPassPostProcess; + private _createBlurPostProcesses; + private _createTextureAdderPostProcess; + private _createVolumetricLightPostProcess; + private _createLuminancePostProcesses; + private _createHdrPostProcess; + private _createLensFlarePostProcess; + private _createDepthOfFieldPostProcess; + private _createMotionBlurPostProcess; + private _getDepthTexture; + private _disposePostProcesses; /** * Dispose of the pipeline and stop all post processes */ diff --git a/dist/preview release/babylon.js b/dist/preview release/babylon.js index ebf68be6d40..03fa60b92de 100644 --- a/dist/preview release/babylon.js +++ b/dist/preview release/babylon.js @@ -1,63 +1,64 @@ -!(function(e,t){var i=[],r=e.CANNON||this.CANNON,n=e.OIMO||this.OIMO,o=e.earcut||this.earcut;if("object"==typeof exports&&"object"==typeof module){try{r=r||require("cannon")}catch(e){}try{n=n||require("oimo")}catch(e){}try{o=o||require("earcut")}catch(e){}module.exports=t(r,n,o)}else if("function"==typeof define&&define.amd)require.specified&&require.specified("cannon")&&i.push("cannon"),require.specified&&require.specified("oimo")&&i.push("oimo"),require.specified&&require.specified("earcut")&&i.push("earcut"),define("babylonjs",i,t);else if("object"==typeof exports){try{r=r||require("cannon")}catch(e){}try{n=n||require("oimo")}catch(e){}try{o=o||require("earcut")}catch(e){}exports.babylonjs=t(r,n,o)}else e.BABYLON=t(r,n,o)})(this,(function(e,t,i){e=e||this.CANNON,t=t||this.OIMO,i=i||this.earcut;var r,n=this&&this.__decorate||function(e,t,i,r){var n,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,i,s):n(t,i))||s);return o>3&&s&&Object.defineProperty(t,i,s),s},o=this&&this.__extends||(function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])};return function(t,i){function r(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}})();!(function(e){var t=(function(){function e(){this._defines={},this._currentRank=32,this._maxRank=-1}return e.prototype.unBindMesh=function(){this._mesh=null},e.prototype.addFallback=function(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)},e.prototype.addCPUSkinningFallback=function(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)},Object.defineProperty(e.prototype,"isMoreFallbacks",{get:function(){return this._currentRank<=this._maxRank},enumerable:!0,configurable:!0}),e.prototype.reduce=function(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0&&this._mesh.material){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;for(var i=this._mesh.getScene(),r=0;r-1?i:e.Engine.ShadersRepository+i,this._engine._loadFile(n+".vertex.fx",r)},t.prototype._loadFragmentShader=function(i,r){if(e.Tools.IsWindowObjectExist()&&i instanceof HTMLElement){return void r(e.Tools.GetDOMTextContent(i))}if("base64:"===i.substr(0,7)){return void r(window.atob(i.substr(7)))}if(t.ShadersStore[i+"PixelShader"])return void r(t.ShadersStore[i+"PixelShader"]);if(t.ShadersStore[i+"FragmentShader"])return void r(t.ShadersStore[i+"FragmentShader"]);var n;n="."===i[0]||"/"===i[0]||i.indexOf("http")>-1?i:e.Engine.ShadersRepository+i,this._engine._loadFile(n+".fragment.fx",r)},t.prototype._dumpShadersSource=function(t,i,r){var n=this._engine.webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"",o=n+(r?r+"\n":"");t=o+t,i=o+i;var s=2,a=/\n/gm,l="\n1\t"+t.replace(a,(function(){return"\n"+s+++"\t"}));s=2;var c="\n1\t"+i.replace(a,(function(){return"\n"+s+++"\t"}));this.name.vertexElement?(e.Tools.Error("Vertex shader: "+this.name.vertexElement+l),e.Tools.Error("Fragment shader: "+this.name.fragmentElement+c)):this.name.vertex?(e.Tools.Error("Vertex shader: "+this.name.vertex+l),e.Tools.Error("Fragment shader: "+this.name.fragment+c)):(e.Tools.Error("Vertex shader: "+this.name+l),e.Tools.Error("Fragment shader: "+this.name+c))},t.prototype._processShaderConversion=function(e,t,i){var r=this._processPrecision(e);if(1==this._engine.webGLVersion)return void i(r);if(-1!==r.indexOf("#version 3"))return void i(r.replace("#version 300 es",""));var n=-1!==r.search(/#extension.+GL_EXT_draw_buffers.+require/),o=/#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,s=r.replace(o,"");s=s.replace(/varying(?![\n\r])\s/g,t?"in ":"out "),s=s.replace(/attribute[ \t]/g,"in "),s=s.replace(/[ \t]attribute/g," in"),t&&(s=s.replace(/texture2DLodEXT\s*\(/g,"textureLod("),s=s.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),s=s.replace(/texture2D\s*\(/g,"texture("),s=s.replace(/textureCube\s*\(/g,"texture("),s=s.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),s=s.replace(/gl_FragColor/g,"glFragColor"),s=s.replace(/gl_FragData/g,"glFragData"),s=s.replace(/void\s+?main\s*\(/g,(n?"":"out vec4 glFragColor;\n")+"void main(")),i(s)},t.prototype._processIncludes=function(i,r){for(var n=this,o=/#include<(.+)>(\((.*)\))*(\[(.*)\])*/g,s=o.exec(i),a=new String(i);null!=s;){var l=s[1];if(-1!==l.indexOf("__decl__")&&(l=l.replace(/__decl__/,""),this._engine.supportsUniformBuffers&&(l=l.replace(/Vertex/,"Ubo"),l=l.replace(/Fragment/,"Ubo")),l+="Declaration"),!t.IncludesShadersStore[l]){var c=e.Engine.ShadersRepository+"ShadersInclude/"+l+".fx";return void this._engine._loadFile(c,(function(e){t.IncludesShadersStore[l]=e,n._processIncludes(a,r)}))}var h=t.IncludesShadersStore[l];if(s[2])for(var u=s[3].split(","),d=0;dr.x?r.x:n,n=nr.y?r.y:o,o=oi.x?e.x:i.x,e.y>i.y?e.y:i.y)},t.Transform=function(e,i){var r=t.Zero();return t.TransformToRef(e,i,r),r},t.TransformToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+t.m[13];i.x=r,i.y=n},t.PointInTriangle=function(e,t,i,r){var n=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),o=n<0?-1:1,s=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*o,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*o;return s>0&&a>0&&s+a<2*n*o},t.Distance=function(e,i){return Math.sqrt(t.DistanceSquared(e,i))},t.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y;return i*i+r*r},t.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},t.DistanceOfPointFromSegment=function(e,i,r){ -var n=t.DistanceSquared(i,r);if(0===n)return t.Distance(e,i);var o=r.subtract(i),s=Math.max(0,Math.min(1,t.Dot(e.subtract(i),o)/n)),a=i.add(o.multiplyByFloats(s,s));return t.Distance(e,a)},t})();e.Vector2=r;var n=(function(){function t(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this.x=e,this.y=t,this.z=i}return t.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+"}"},t.prototype.getClassName=function(){return"Vector3"},t.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0)},t.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},t.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,this},t.prototype.toQuaternion=function(){return e.Quaternion.RotationYawPitchRoll(this.x,this.y,this.z)},t.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this},t.prototype.add=function(e){return new t(this.x+e.x,this.y+e.y,this.z+e.z)},t.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,this},t.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this},t.prototype.subtract=function(e){return new t(this.x-e.x,this.y-e.y,this.z-e.z)},t.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,this},t.prototype.subtractFromFloats=function(e,i,r){return new t(this.x-e,this.y-i,this.z-r)},t.prototype.subtractFromFloatsToRef=function(e,t,i,r){return r.x=this.x-e,r.y=this.y-t,r.z=this.z-i,this},t.prototype.negate=function(){return new t(-this.x,-this.y,-this.z)},t.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this},t.prototype.scale=function(e){return new t(this.x*e,this.y*e,this.z*e)},t.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,this},t.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,this},t.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z},t.prototype.equalsWithEpsilon=function(t,i){return void 0===i&&(i=e.Epsilon),t&&e.Scalar.WithinEpsilon(this.x,t.x,i)&&e.Scalar.WithinEpsilon(this.y,t.y,i)&&e.Scalar.WithinEpsilon(this.z,t.z,i)},t.prototype.equalsToFloats=function(e,t,i){return this.x===e&&this.y===t&&this.z===i},t.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this},t.prototype.multiply=function(e){return new t(this.x*e.x,this.y*e.y,this.z*e.z)},t.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,this},t.prototype.multiplyByFloats=function(e,i,r){return new t(this.x*e,this.y*i,this.z*r)},t.prototype.divide=function(e){return new t(this.x/e.x,this.y/e.y,this.z/e.z)},t.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,this},t.prototype.divideInPlace=function(e){return this.divideToRef(e,this)},t.prototype.minimizeInPlace=function(e){return e.xthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),this},Object.defineProperty(t.prototype,"isNonUniform",{get:function(){var e=Math.abs(this.x),t=Math.abs(this.y);if(e!==t)return!0;var i=Math.abs(this.z);return e!==i||t!==i},enumerable:!0,configurable:!0}),t.prototype.floor=function(){return new t(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))},t.prototype.fract=function(){return new t(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z))},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},t.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},t.prototype.normalize=function(){var e=this.length();if(0===e||1===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this},t.prototype.normalizeToNew=function(){var e=new t(0,0,0);return this.normalizeToRef(e),e},t.prototype.normalizeToRef=function(e){var t=this.length();if(0===t||1===t)return e.set(this.x,this.y,this.z),e;var i=1/t;return this.scaleToRef(i,e),e},t.prototype.clone=function(){return new t(this.x,this.y,this.z)},t.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this},t.prototype.copyFromFloats=function(e,t,i){return this.x=e,this.y=t,this.z=i,this},t.prototype.set=function(e,t,i){return this.copyFromFloats(e,t,i)},t.GetClipFactor=function(e,i,r,n){var o=t.Dot(e,r)-n;return o/(o-(t.Dot(i,r)-n))},t.GetAngleBetweenVectors=function(e,i,r){var n=e.clone().normalize(),o=i.clone().normalize(),s=t.Dot(n,o),a=t.Cross(n,o);return t.Dot(a,r)>0?Math.acos(s):-Math.acos(s)},t.FromArray=function(e,i){return i||(i=0),new t(e[i],e[i+1],e[i+2])},t.FromFloatArray=function(e,i){return t.FromArray(e,i)},t.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2]},t.FromFloatArrayToRef=function(e,i,r){return t.FromArrayToRef(e,i,r)},t.FromFloatsToRef=function(e,t,i,r){r.x=e,r.y=t,r.z=i},t.Zero=function(){return new t(0,0,0)},t.One=function(){return new t(1,1,1)},t.Up=function(){return new t(0,1,0)},t.Down=function(){return new t(0,-1,0)},t.Forward=function(){return new t(0,0,1)},t.Right=function(){return new t(1,0,0)},t.Left=function(){return new t(-1,0,0)},t.TransformCoordinates=function(e,i){var r=t.Zero();return t.TransformCoordinatesToRef(e,i,r),r},t.TransformCoordinatesToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9]+t.m[13],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10]+t.m[14],s=e.x*t.m[3]+e.y*t.m[7]+e.z*t.m[11]+t.m[15];i.x=r/s,i.y=n/s,i.z=o/s},t.TransformCoordinatesFromFloatsToRef=function(e,t,i,r,n){var o=e*r.m[0]+t*r.m[4]+i*r.m[8]+r.m[12],s=e*r.m[1]+t*r.m[5]+i*r.m[9]+r.m[13],a=e*r.m[2]+t*r.m[6]+i*r.m[10]+r.m[14],l=e*r.m[3]+t*r.m[7]+i*r.m[11]+r.m[15];n.x=o/l,n.y=s/l,n.z=a/l},t.TransformNormal=function(e,i){var r=t.Zero();return t.TransformNormalToRef(e,i,r),r},t.TransformNormalToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10];i.x=r,i.y=n,i.z=o},t.TransformNormalFromFloatsToRef=function(e,t,i,r,n){n.x=e*r.m[0]+t*r.m[4]+i*r.m[8],n.y=e*r.m[1]+t*r.m[5]+i*r.m[9],n.z=e*r.m[2]+t*r.m[6]+i*r.m[10]},t.CatmullRom=function(e,i,r,n,o){var s=o*o,a=o*s;return new t(.5*(2*i.x+(-e.x+r.x)*o+(2*e.x-5*i.x+4*r.x-n.x)*s+(-e.x+3*i.x-3*r.x+n.x)*a),.5*(2*i.y+(-e.y+r.y)*o+(2*e.y-5*i.y+4*r.y-n.y)*s+(-e.y+3*i.y-3*r.y+n.y)*a),.5*(2*i.z+(-e.z+r.z)*o+(2*e.z-5*i.z+4*r.z-n.z)*s+(-e.z+3*i.z-3*r.z+n.z)*a))},t.Clamp=function(e,i,r){var n=e.x;n=n>r.x?r.x:n,n=nr.y?r.y:o,o=or.z?r.z:s,s=sthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this},t.prototype.floor=function(){return new t(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))},t.prototype.fract=function(){return new t(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},t.prototype.normalize=function(){var e=this.length();if(0===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toVector3=function(){return new n(this.x,this.y,this.z)},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},t.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},t.prototype.set=function(e,t,i,r){return this.copyFromFloats(e,t,i,r)},t.FromArray=function(e,i){return i||(i=0),new t(e[i],e[i+1],e[i+2],e[i+3])},t.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3]},t.FromFloatArrayToRef=function(e,i,r){t.FromArrayToRef(e,i,r)},t.FromFloatsToRef=function(e,t,i,r,n){n.x=e,n.y=t,n.z=i,n.w=r},t.Zero=function(){return new t(0,0,0,0)},t.One=function(){return new t(1,1,1,1)},t.Normalize=function(e){var i=t.Zero();return t.NormalizeToRef(e,i),i},t.NormalizeToRef=function(e,t){t.copyFrom(e),t.normalize()},t.Minimize=function(e,t){var i=e.clone();return i.minimizeInPlace(t),i},t.Maximize=function(e,t){var i=e.clone();return i.maximizeInPlace(t),i},t.Distance=function(e,i){return Math.sqrt(t.DistanceSquared(e,i))},t.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y,n=e.z-t.z,o=e.w-t.w;return i*i+r*r+n*n+o*o},t.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},t.TransformNormal=function(e,i){var r=t.Zero();return t.TransformNormalToRef(e,i,r),r},t.TransformNormalToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10];i.x=r,i.y=n,i.z=o,i.w=e.w},t.TransformNormalFromFloatsToRef=function(e,t,i,r,n,o){o.x=e*n.m[0]+t*n.m[4]+i*n.m[8],o.y=e*n.m[1]+t*n.m[5]+i*n.m[9],o.z=e*n.m[2]+t*n.m[6]+i*n.m[10],o.w=r},t})();e.Vector4=o;var s=(function(){function e(e,t){this.width=e,this.height=t}return e.prototype.toString=function(){return"{W: "+this.width+", H: "+this.height+"}"},e.prototype.getClassName=function(){return"Size"},e.prototype.getHashCode=function(){var e=this.width||0;return e=397*e^(this.height||0)},e.prototype.copyFrom=function(e){this.width=e.width,this.height=e.height},e.prototype.copyFromFloats=function(e,t){return this.width=e,this.height=t,this},e.prototype.set=function(e,t){return this.copyFromFloats(e,t)},e.prototype.multiplyByFloats=function(t,i){return new e(this.width*t,this.height*i)},e.prototype.clone=function(){return new e(this.width,this.height)},e.prototype.equals=function(e){return!!e&&(this.width===e.width&&this.height===e.height)},Object.defineProperty(e.prototype,"surface",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),e.Zero=function(){return new e(0,0)},e.prototype.add=function(t){return new e(this.width+t.width,this.height+t.height)},e.prototype.subtract=function(t){return new e(this.width-t.width,this.height-t.height)},e.Lerp=function(t,i,r){return new e(t.width+(i.width-t.width)*r,t.height+(i.height-t.height)*r)},e})();e.Size=s;var a=(function(){function e(e,t,i,r){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=1),this.x=e,this.y=t,this.z=i,this.w=r}return e.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},e.prototype.getClassName=function(){return"Quaternion"},e.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0),e=397*e^(this.w||0)},e.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},e.prototype.clone=function(){return new e(this.x,this.y,this.z,this.w)},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},e.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},e.prototype.set=function(e,t,i,r){return this.copyFromFloats(e,t,i,r)},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},e.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},e.prototype.scale=function(t){return new e(this.x*t,this.y*t,this.z*t,this.w*t)},e.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e,this},e.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,t.w+=this.w*e,this},e.prototype.multiply=function(t){var i=new e(0,0,0,1);return this.multiplyToRef(t,i),i},e.prototype.multiplyToRef=function(e,t){var i=this.x*e.w+this.y*e.z-this.z*e.y+this.w*e.x,r=-this.x*e.z+this.y*e.w+this.z*e.x+this.w*e.y,n=this.x*e.y-this.y*e.x+this.z*e.w+this.w*e.z,o=-this.x*e.x-this.y*e.y-this.z*e.z+this.w*e.w;return t.copyFromFloats(i,r,n,o),this},e.prototype.multiplyInPlace=function(e){return this.multiplyToRef(e,this),this},e.prototype.conjugateToRef=function(e){return e.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},e.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},e.prototype.conjugate=function(){return new e(-this.x,-this.y,-this.z,this.w)},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.prototype.normalize=function(){var e=1/this.length();return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.toEulerAngles=function(e){void 0===e&&(e="YZX");var t=n.Zero();return this.toEulerAnglesToRef(t,e),t},e.prototype.toEulerAnglesToRef=function(e,t){void 0===t&&(t="YZX");var i=this.z,r=this.x,n=this.y,o=this.w,s=o*o,a=i*i,l=r*r,c=n*n,h=n*i-r*o;return h<-.4999999?(e.y=2*Math.atan2(n,o),e.x=Math.PI/2,e.z=0):h>.4999999?(e.y=2*Math.atan2(n,o),e.x=-Math.PI/2,e.z=0):(e.z=Math.atan2(2*(r*n+i*o),-a-l+c+s),e.x=Math.asin(-2*(i*n-r*o)),e.y=Math.atan2(2*(i*r+n*o),a-l-c+s)),this},e.prototype.toRotationMatrix=function(e){var t=this.x*this.x,i=this.y*this.y,r=this.z*this.z,n=this.x*this.y,o=this.z*this.w,s=this.z*this.x,a=this.y*this.w,l=this.y*this.z,c=this.x*this.w;return e.m[0]=1-2*(i+r),e.m[1]=2*(n+o),e.m[2]=2*(s-a),e.m[3]=0,e.m[4]=2*(n-o),e.m[5]=1-2*(r+t),e.m[6]=2*(l+c),e.m[7]=0,e.m[8]=2*(s+a),e.m[9]=2*(l-c),e.m[10]=1-2*(i+t),e.m[11]=0,e.m[12]=0,e.m[13]=0,e.m[14]=0,e.m[15]=1,e._markAsUpdated(),this},e.prototype.fromRotationMatrix=function(t){return e.FromRotationMatrixToRef(t,this),this},e.FromRotationMatrix=function(t){var i=new e;return e.FromRotationMatrixToRef(t,i),i},e.FromRotationMatrixToRef=function(e,t){var i,r=e.m,n=r[0],o=r[4],s=r[8],a=r[1],l=r[5],c=r[9],h=r[2],u=r[6],d=r[10],f=n+l+d;f>0?(i=.5/Math.sqrt(f+1),t.w=.25/i,t.x=(u-c)*i,t.y=(s-h)*i,t.z=(a-o)*i):n>l&&n>d?(i=2*Math.sqrt(1+n-l-d),t.w=(u-c)/i,t.x=.25*i,t.y=(o+a)/i,t.z=(s+h)/i):l>d?(i=2*Math.sqrt(1+l-n-d),t.w=(s-h)/i,t.x=(o+a)/i,t.y=.25*i,t.z=(c+u)/i):(i=2*Math.sqrt(1+d-n-l),t.w=(a-o)/i,t.x=(s+h)/i,t.y=(c+u)/i,t.z=.25*i)},e.Dot=function(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w},e.AreClose=function(t,i){return e.Dot(t,i)>=0},e.Zero=function(){return new e(0,0,0,0)},e.Inverse=function(t){return new e(-t.x,-t.y,-t.z,t.w)},e.Identity=function(){return new e(0,0,0,1)},e.IsIdentity=function(e){return e&&0===e.x&&0===e.y&&0===e.z&&1===e.w},e.RotationAxis=function(t,i){return e.RotationAxisToRef(t,i,new e)},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(t/2);return e.normalize(),i.w=Math.cos(t/2),i.x=e.x*r,i.y=e.y*r,i.z=e.z*r,i},e.FromArray=function(t,i){return i||(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){var n=.5*i,o=.5*t,s=.5*e,a=Math.sin(n),l=Math.cos(n),c=Math.sin(o),h=Math.cos(o),u=Math.sin(s),d=Math.cos(s);r.x=d*c*l+u*h*a,r.y=u*h*l-d*c*a,r.z=d*h*a-u*c*l,r.w=d*h*l+u*c*a},e.RotationAlphaBetaGamma=function(t,i,r){var n=new e;return e.RotationAlphaBetaGammaToRef(t,i,r,n),n},e.RotationAlphaBetaGammaToRef=function(e,t,i,r){var n=.5*(i+e),o=.5*(i-e),s=.5*t;r.x=Math.cos(o)*Math.sin(s),r.y=Math.sin(o)*Math.sin(s),r.z=Math.sin(n)*Math.cos(s),r.w=Math.cos(n)*Math.cos(s)},e.RotationQuaternionFromAxis=function(t,i,r){var n=new e(0,0,0,0);return e.RotationQuaternionFromAxisToRef(t,i,r,n),n},e.RotationQuaternionFromAxisToRef=function(t,i,r,n){var o=E.Matrix[0];l.FromXYZAxesToRef(t.normalize(),i.normalize(),r.normalize(),o),e.FromRotationMatrixToRef(o,n)},e.Slerp=function(t,i,r){var n=e.Identity();return e.SlerpToRef(t,i,r,n),n},e.SlerpToRef=function(e,t,i,r){var n,o,s=e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w,a=!1;if(s<0&&(a=!0,s=-s),s>.999999)o=1-i,n=a?-i:i;else{var l=Math.acos(s),c=1/Math.sin(l);o=Math.sin((1-i)*l)*c,n=a?-Math.sin(i*l)*c:Math.sin(i*l)*c}r.x=o*e.x+n*t.x,r.y=o*e.y+n*t.y,r.z=o*e.z+n*t.z,r.w=o*e.w+n*t.w},e.Hermite=function(t,i,r,n,o){var s=o*o,a=o*s,l=2*a-3*s+1,c=-2*a+3*s,h=a-2*s+o,u=a-s;return new e(t.x*l+r.x*c+i.x*h+n.x*u,t.y*l+r.y*c+i.y*h+n.y*u,t.z*l+r.z*c+i.z*h+n.z*u,t.w*l+r.w*c+i.w*h+n.w*u)},e})();e.Quaternion=a;var l=(function(){function e(){this._isIdentity=!1,this._isIdentityDirty=!0,this.m=new Float32Array(16),this._markAsUpdated()}return e.prototype._markAsUpdated=function(){this.updateFlag=e._updateFlagSeed++,this._isIdentityDirty=!0},e.prototype.isIdentity=function(e){return void 0===e&&(e=!1),this._isIdentityDirty&&(this._isIdentityDirty=!1,1!==this.m[0]||1!==this.m[5]||1!==this.m[15]?this._isIdentity=!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?this._isIdentity=!1:this._isIdentity=!0,e||1===this.m[10]||(this._isIdentity=!1)),this._isIdentity},e.prototype.determinant=function(){var e=this.m[10]*this.m[15]-this.m[11]*this.m[14],t=this.m[9]*this.m[15]-this.m[11]*this.m[13],i=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],n=this.m[8]*this.m[14]-this.m[10]*this.m[12],o=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*e-this.m[6]*t+this.m[7]*i)-this.m[1]*(this.m[4]*e-this.m[6]*r+this.m[7]*n)+this.m[2]*(this.m[4]*t-this.m[5]*r+this.m[7]*o)-this.m[3]*(this.m[4]*i-this.m[5]*n+this.m[6]*o)},e.prototype.toArray=function(){return this.m},e.prototype.asArray=function(){return this.toArray()},e.prototype.invert=function(){return this.invertToRef(this),this},e.prototype.reset=function(){for(var e=0;e<16;e++)this.m[e]=0;return this._markAsUpdated(),this},e.prototype.add=function(t){var i=new e;return this.addToRef(t,i),i},e.prototype.addToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]=this.m[i]+e.m[i];return t._markAsUpdated(),this},e.prototype.addToSelf=function(e){for(var t=0;t<16;t++)this.m[t]+=e.m[t];return this._markAsUpdated(),this},e.prototype.invertToRef=function(e){var t=this.m[0],i=this.m[1],r=this.m[2],n=this.m[3],o=this.m[4],s=this.m[5],a=this.m[6],l=this.m[7],c=this.m[8],h=this.m[9],u=this.m[10],d=this.m[11],f=this.m[12],p=this.m[13],_=this.m[14],m=this.m[15],g=u*m-d*_,v=h*m-d*p,y=h*_-u*p,b=c*m-d*f,x=c*_-u*f,T=c*p-h*f,E=s*g-a*v+l*y,P=-(o*g-a*b+l*x),A=o*v-s*b+l*T,M=-(o*y-s*x+a*T),S=1/(t*E+i*P+r*A+n*M),C=a*m-l*_,R=s*m-l*p,O=s*_-a*p,D=o*m-l*f,I=o*_-a*f,w=o*p-s*f,L=a*d-l*u,F=s*d-l*h,B=s*u-a*h,V=o*d-l*c,N=o*u-a*c,U=o*h-s*c;return e.m[0]=E*S,e.m[4]=P*S,e.m[8]=A*S,e.m[12]=M*S,e.m[1]=-(i*g-r*v+n*y)*S,e.m[5]=(t*g-r*b+n*x)*S,e.m[9]=-(t*v-i*b+n*T)*S,e.m[13]=(t*y-i*x+r*T)*S,e.m[2]=(i*C-r*R+n*O)*S,e.m[6]=-(t*C-r*D+n*I)*S,e.m[10]=(t*R-i*D+n*w)*S,e.m[14]=-(t*O-i*I+r*w)*S,e.m[3]=-(i*L-r*F+n*B)*S,e.m[7]=(t*L-r*V+n*N)*S,e.m[11]=-(t*F-i*V+n*U)*S,e.m[15]=(t*B-i*N+r*U)*S,e._markAsUpdated(),this},e.prototype.setTranslationFromFloats=function(e,t,i){return this.m[12]=e,this.m[13]=t,this.m[14]=i,this._markAsUpdated(),this},e.prototype.setTranslation=function(e){return this.m[12]=e.x,this.m[13]=e.y,this.m[14]=e.z,this._markAsUpdated(),this},e.prototype.getTranslation=function(){return new n(this.m[12],this.m[13],this.m[14])},e.prototype.getTranslationToRef=function(e){return e.x=this.m[12],e.y=this.m[13],e.z=this.m[14],this},e.prototype.removeRotationAndScaling=function(){return this.setRowFromFloats(0,1,0,0,0),this.setRowFromFloats(1,0,1,0,0),this.setRowFromFloats(2,0,0,1,0),this},e.prototype.multiply=function(t){var i=new e;return this.multiplyToRef(t,i),i},e.prototype.copyFrom=function(e){for(var t=0;t<16;t++)this.m[t]=e.m[t];return this._markAsUpdated(),this},e.prototype.copyToArray=function(e,t){void 0===t&&(t=0);for(var i=0;i<16;i++)e[t+i]=this.m[i];return this},e.prototype.multiplyToRef=function(e,t){return this.multiplyToArray(e,t.m,0),t._markAsUpdated(),this},e.prototype.multiplyToArray=function(e,t,i){var r=this.m[0],n=this.m[1],o=this.m[2],s=this.m[3],a=this.m[4],l=this.m[5],c=this.m[6],h=this.m[7],u=this.m[8],d=this.m[9],f=this.m[10],p=this.m[11],_=this.m[12],m=this.m[13],g=this.m[14],v=this.m[15],y=e.m[0],b=e.m[1],x=e.m[2],T=e.m[3],E=e.m[4],P=e.m[5],A=e.m[6],M=e.m[7],S=e.m[8],C=e.m[9],R=e.m[10],O=e.m[11],D=e.m[12],I=e.m[13],w=e.m[14],L=e.m[15];return t[i]=r*y+n*E+o*S+s*D,t[i+1]=r*b+n*P+o*C+s*I,t[i+2]=r*x+n*A+o*R+s*w,t[i+3]=r*T+n*M+o*O+s*L,t[i+4]=a*y+l*E+c*S+h*D,t[i+5]=a*b+l*P+c*C+h*I,t[i+6]=a*x+l*A+c*R+h*w,t[i+7]=a*T+l*M+c*O+h*L,t[i+8]=u*y+d*E+f*S+p*D,t[i+9]=u*b+d*P+f*C+p*I,t[i+10]=u*x+d*A+f*R+p*w,t[i+11]=u*T+d*M+f*O+p*L,t[i+12]=_*y+m*E+g*S+v*D,t[i+13]=_*b+m*P+g*C+v*I,t[i+14]=_*x+m*A+g*R+v*w,t[i+15]=_*T+m*M+g*O+v*L,this},e.prototype.equals=function(e){return e&&this.m[0]===e.m[0]&&this.m[1]===e.m[1]&&this.m[2]===e.m[2]&&this.m[3]===e.m[3]&&this.m[4]===e.m[4]&&this.m[5]===e.m[5]&&this.m[6]===e.m[6]&&this.m[7]===e.m[7]&&this.m[8]===e.m[8]&&this.m[9]===e.m[9]&&this.m[10]===e.m[10]&&this.m[11]===e.m[11]&&this.m[12]===e.m[12]&&this.m[13]===e.m[13]&&this.m[14]===e.m[14]&&this.m[15]===e.m[15]},e.prototype.clone=function(){return e.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},e.prototype.getClassName=function(){return"Matrix"},e.prototype.getHashCode=function(){for(var e=this.m[0]||0,t=1;t<16;t++)e=397*e^(this.m[t]||0);return e},e.prototype.decompose=function(t,i,r){return r&&(r.x=this.m[12],r.y=this.m[13],r.z=this.m[14]),t=t||E.Vector3[0],t.x=Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),this.determinant()<=0&&(t.y*=-1),0===t.x||0===t.y||0===t.z?(i&&(i.x=0,i.y=0,i.z=0,i.w=1),!1):(i&&(e.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,E.Matrix[0]),a.FromRotationMatrixToRef(E.Matrix[0],i)),!0)},e.prototype.getRow=function(e){if(e<0||e>3)return null;var t=4*e;return new o(this.m[t+0],this.m[t+1],this.m[t+2],this.m[t+3])},e.prototype.setRow=function(e,t){if(e<0||e>3)return this;var i=4*e;return this.m[i+0]=t.x,this.m[i+1]=t.y,this.m[i+2]=t.z,this.m[i+3]=t.w,this._markAsUpdated(),this},e.prototype.transpose=function(){return e.Transpose(this)},e.prototype.transposeToRef=function(t){return e.TransposeToRef(this,t),this},e.prototype.setRowFromFloats=function(e,t,i,r,n){if(e<0||e>3)return this;var o=4*e;return this.m[o+0]=t,this.m[o+1]=i,this.m[o+2]=r,this.m[o+3]=n,this._markAsUpdated(),this},e.prototype.scale=function(t){var i=new e;return this.scaleToRef(t,i),i},e.prototype.scaleToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]=this.m[i]*e;return t._markAsUpdated(),this},e.prototype.scaleAndAddToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]+=this.m[i]*e;return t._markAsUpdated(),this},e.prototype.toNormalMatrix=function(t){this.invertToRef(t),t.transpose();var i=t.m;e.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,t)},e.prototype.getRotationMatrix=function(){var t=e.Identity();return this.getRotationMatrixToRef(t),t},e.prototype.getRotationMatrixToRef=function(t){var i=this.m,r=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),n=Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),o=Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);return this.determinant()<=0&&(n*=-1),0===r||0===n||0===o?e.IdentityToRef(t):e.FromValuesToRef(i[0]/r,i[1]/r,i[2]/r,0,i[4]/n,i[5]/n,i[6]/n,0,i[8]/o,i[9]/o,i[10]/o,0,0,0,0,1,t),this},e.FromArray=function(t,i){var r=new e;return i||(i=0),e.FromArrayToRef(t,i,r),r},e.FromArrayToRef=function(e,t,i){for(var r=0;r<16;r++)i.m[r]=e[r+t];i._markAsUpdated()},e.FromFloat32ArrayToRefScaled=function(e,t,i,r){for(var n=0;n<16;n++)r.m[n]=e[n+t]*i;r._markAsUpdated()},e.FromValuesToRef=function(e,t,i,r,n,o,s,a,l,c,h,u,d,f,p,_,m){m.m[0]=e,m.m[1]=t,m.m[2]=i,m.m[3]=r,m.m[4]=n,m.m[5]=o,m.m[6]=s,m.m[7]=a,m.m[8]=l,m.m[9]=c,m.m[10]=h,m.m[11]=u,m.m[12]=d,m.m[13]=f,m.m[14]=p,m.m[15]=_,m._markAsUpdated()},Object.defineProperty(e,"IdentityReadOnly",{get:function(){return e._identityReadOnly},enumerable:!0,configurable:!0}),e.FromValues=function(t,i,r,n,o,s,a,l,c,h,u,d,f,p,_,m){var g=new e;return g.m[0]=t,g.m[1]=i,g.m[2]=r,g.m[3]=n,g.m[4]=o,g.m[5]=s,g.m[6]=a,g.m[7]=l,g.m[8]=c,g.m[9]=h,g.m[10]=u,g.m[11]=d,g.m[12]=f,g.m[13]=p,g.m[14]=_,g.m[15]=m,g},e.Compose=function(t,i,r){var n=e.Identity();return e.ComposeToRef(t,i,r,n),n},e.ComposeToRef=function(t,i,r,n){e.FromValuesToRef(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1,E.Matrix[1]),i.toRotationMatrix(E.Matrix[0]),E.Matrix[1].multiplyToRef(E.Matrix[0],n),n.setTranslation(r)},e.Identity=function(){return e.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},e.IdentityToRef=function(t){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},e.Zero=function(){return e.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},e.RotationX=function(t){var i=new e;return e.RotationXToRef(t,i),i},e.Invert=function(t){var i=new e;return t.invertToRef(i),i},e.RotationXToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[0]=1,t.m[15]=1,t.m[5]=r,t.m[10]=r,t.m[9]=-i,t.m[6]=i,t.m[1]=0,t.m[2]=0,t.m[3]=0,t.m[4]=0,t.m[7]=0,t.m[8]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t._markAsUpdated()},e.RotationY=function(t){var i=new e;return e.RotationYToRef(t,i),i},e.RotationYToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[5]=1,t.m[15]=1,t.m[0]=r,t.m[2]=-i,t.m[8]=i,t.m[10]=r,t.m[1]=0,t.m[3]=0,t.m[4]=0,t.m[6]=0,t.m[7]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t._markAsUpdated()},e.RotationZ=function(t){var i=new e;return e.RotationZToRef(t,i),i},e.RotationZToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[10]=1,t.m[15]=1,t.m[0]=r,t.m[1]=i,t.m[4]=-i,t.m[5]=r,t.m[2]=0,t.m[3]=0,t.m[6]=0,t.m[7]=0,t.m[8]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t._markAsUpdated()},e.RotationAxis=function(t,i){var r=e.Zero();return e.RotationAxisToRef(t,i,r),r},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(-t),n=Math.cos(-t),o=1-n;e.normalize(),i.m[0]=e.x*e.x*o+n,i.m[1]=e.x*e.y*o-e.z*r,i.m[2]=e.x*e.z*o+e.y*r,i.m[3]=0,i.m[4]=e.y*e.x*o+e.z*r,i.m[5]=e.y*e.y*o+n,i.m[6]=e.y*e.z*o-e.x*r,i.m[7]=0,i.m[8]=e.z*e.x*o-e.y*r,i.m[9]=e.z*e.y*o+e.x*r,i.m[10]=e.z*e.z*o+n,i.m[11]=0,i.m[15]=1, -i._markAsUpdated()},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){a.RotationYawPitchRollToRef(e,t,i,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},e.Scaling=function(t,i,r){var n=e.Zero();return e.ScalingToRef(t,i,r,n),n},e.ScalingToRef=function(e,t,i,r){r.m[0]=e,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=t,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=i,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1,r._markAsUpdated()},e.Translation=function(t,i,r){var n=e.Identity();return e.TranslationToRef(t,i,r,n),n},e.TranslationToRef=function(t,i,r,n){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,r,1,n)},e.Lerp=function(t,i,r){var n=e.Zero();return e.LerpToRef(t,i,r,n),n},e.LerpToRef=function(e,t,i,r){for(var n=0;n<16;n++)r.m[n]=e.m[n]*(1-i)+t.m[n]*i;r._markAsUpdated()},e.DecomposeLerp=function(t,i,r){var n=e.Zero();return e.DecomposeLerpToRef(t,i,r,n),n},e.DecomposeLerpToRef=function(t,i,r,o){var s=E.Vector3[0],l=E.Quaternion[0],c=E.Vector3[1];t.decompose(s,l,c);var h=E.Vector3[2],u=E.Quaternion[1],d=E.Vector3[3];i.decompose(h,u,d);var f=E.Vector3[4];n.LerpToRef(s,h,r,f);var p=E.Quaternion[2];a.SlerpToRef(l,u,r,p);var _=E.Vector3[5];n.LerpToRef(c,d,r,_),e.ComposeToRef(f,p,_,o)},e.LookAtLH=function(t,i,r){var n=e.Zero();return e.LookAtLHToRef(t,i,r,n),n},e.LookAtLHToRef=function(t,i,r,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),n.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),n.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-n.Dot(this._xAxis,t),a=-n.Dot(this._yAxis,t),l=-n.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,l,1,o)},e.LookAtRH=function(t,i,r){var n=e.Zero();return e.LookAtRHToRef(t,i,r,n),n},e.LookAtRHToRef=function(t,i,r,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),n.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),n.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-n.Dot(this._xAxis,t),a=-n.Dot(this._yAxis,t),l=-n.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,l,1,o)},e.OrthoLH=function(t,i,r,n){var o=e.Zero();return e.OrthoLHToRef(t,i,r,n,o),o},e.OrthoLHToRef=function(t,i,r,n,o){var s=r,a=n,l=2/t,c=2/i,h=2/(a-s),u=-(a+s)/(a-s);e.FromValuesToRef(l,0,0,0,0,c,0,0,0,0,h,0,0,0,u,1,o)},e.OrthoOffCenterLH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterLHToRef=function(t,i,r,n,o,s,a){var l=o,c=s,h=2/(i-t),u=2/(n-r),d=2/(c-l),f=-(c+l)/(c-l),p=(t+i)/(t-i),_=(n+r)/(r-n);e.FromValuesToRef(h,0,0,0,0,u,0,0,0,0,d,0,p,_,f,1,a)},e.OrthoOffCenterRH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterRHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterRHToRef=function(t,i,r,n,o,s,a){e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a.m[10]*=-1},e.PerspectiveLH=function(t,i,r,n){var o=e.Zero(),s=r,a=n,l=2*s/t,c=2*s/i,h=(a+s)/(a-s),u=-2*a*s/(a-s);return e.FromValuesToRef(l,0,0,0,0,c,0,0,0,0,h,1,0,0,u,0,o),o},e.PerspectiveFovLH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovLHToRef(t,i,r,n,o),o},e.PerspectiveFovLHToRef=function(t,i,r,n,o,s){void 0===s&&(s=!0);var a=r,l=n,c=1/Math.tan(.5*t),h=s?c/i:c,u=s?c:c*i,d=(l+a)/(l-a),f=-2*l*a/(l-a);e.FromValuesToRef(h,0,0,0,0,u,0,0,0,0,d,1,0,0,f,0,o)},e.PerspectiveFovRH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovRHToRef(t,i,r,n,o),o},e.PerspectiveFovRHToRef=function(t,i,r,n,o,s){void 0===s&&(s=!0);var a=r,l=n,c=1/Math.tan(.5*t),h=s?c/i:c,u=s?c:c*i,d=-(l+a)/(l-a),f=-2*l*a/(l-a);e.FromValuesToRef(h,0,0,0,0,u,0,0,0,0,d,-1,0,0,f,0,o)},e.PerspectiveFovWebVRToRef=function(e,t,i,r,n){void 0===n&&(n=!1);var o=n?-1:1,s=Math.tan(e.upDegrees*Math.PI/180),a=Math.tan(e.downDegrees*Math.PI/180),l=Math.tan(e.leftDegrees*Math.PI/180),c=Math.tan(e.rightDegrees*Math.PI/180),h=2/(l+c),u=2/(s+a);r.m[0]=h,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=u,r.m[6]=r.m[7]=0,r.m[8]=(l-c)*h*.5,r.m[9]=-(s-a)*u*.5,r.m[10]=-i/(t-i),r.m[11]=1*o,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=-2*i*t/(i-t),r._markAsUpdated()},e.GetFinalMatrix=function(t,i,r,n,o,s){var a=t.width,l=t.height,c=t.x,h=t.y,u=e.FromValues(a/2,0,0,0,0,-l/2,0,0,0,0,s-o,0,c+a/2,l/2+h,o,1);return i.multiply(r).multiply(n).multiply(u)},e.GetAsMatrix2x2=function(e){return new Float32Array([e.m[0],e.m[1],e.m[4],e.m[5]])},e.GetAsMatrix3x3=function(e){return new Float32Array([e.m[0],e.m[1],e.m[2],e.m[4],e.m[5],e.m[6],e.m[8],e.m[9],e.m[10]])},e.Transpose=function(t){var i=new e;return e.TransposeToRef(t,i),i},e.TransposeToRef=function(e,t){t.m[0]=e.m[0],t.m[1]=e.m[4],t.m[2]=e.m[8],t.m[3]=e.m[12],t.m[4]=e.m[1],t.m[5]=e.m[5],t.m[6]=e.m[9],t.m[7]=e.m[13],t.m[8]=e.m[2],t.m[9]=e.m[6],t.m[10]=e.m[10],t.m[11]=e.m[14],t.m[12]=e.m[3],t.m[13]=e.m[7],t.m[14]=e.m[11],t.m[15]=e.m[15]},e.Reflection=function(t){var i=new e;return e.ReflectionToRef(t,i),i},e.ReflectionToRef=function(e,t){e.normalize();var i=e.normal.x,r=e.normal.y,n=e.normal.z,o=-2*i,s=-2*r,a=-2*n;t.m[0]=o*i+1,t.m[1]=s*i,t.m[2]=a*i,t.m[3]=0,t.m[4]=o*r,t.m[5]=s*r+1,t.m[6]=a*r,t.m[7]=0,t.m[8]=o*n,t.m[9]=s*n,t.m[10]=a*n+1,t.m[11]=0,t.m[12]=o*e.d,t.m[13]=s*e.d,t.m[14]=a*e.d,t.m[15]=1,t._markAsUpdated()},e.FromXYZAxesToRef=function(e,t,i,r){r.m[0]=e.x,r.m[1]=e.y,r.m[2]=e.z,r.m[3]=0,r.m[4]=t.x,r.m[5]=t.y,r.m[6]=t.z,r.m[7]=0,r.m[8]=i.x,r.m[9]=i.y,r.m[10]=i.z,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1,r._markAsUpdated()},e.FromQuaternionToRef=function(e,t){var i=e.x*e.x,r=e.y*e.y,n=e.z*e.z,o=e.x*e.y,s=e.z*e.w,a=e.z*e.x,l=e.y*e.w,c=e.y*e.z,h=e.x*e.w;t.m[0]=1-2*(r+n),t.m[1]=2*(o+s),t.m[2]=2*(a-l),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(n+i),t.m[6]=2*(c+h),t.m[7]=0,t.m[8]=2*(a+l),t.m[9]=2*(c-h),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,t._markAsUpdated()},e._tempQuaternion=new a,e._xAxis=n.Zero(),e._yAxis=n.Zero(),e._zAxis=n.Zero(),e._updateFlagSeed=0,e._identityReadOnly=e.Identity(),e})();e.Matrix=l;var c=(function(){function e(e,t,i,r){this.normal=new n(e,t,i),this.d=r}return e.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},e.prototype.clone=function(){return new e(this.normal.x,this.normal.y,this.normal.z,this.d)},e.prototype.getClassName=function(){return"Plane"},e.prototype.getHashCode=function(){var e=this.normal.getHashCode();return e=397*e^(this.d||0)},e.prototype.normalize=function(){var e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this},e.prototype.transform=function(t){var i=l.Transpose(t),r=this.normal.x,n=this.normal.y,o=this.normal.z,s=this.d;return new e(r*i.m[0]+n*i.m[1]+o*i.m[2]+s*i.m[3],r*i.m[4]+n*i.m[5]+o*i.m[6]+s*i.m[7],r*i.m[8]+n*i.m[9]+o*i.m[10]+s*i.m[11],r*i.m[12]+n*i.m[13]+o*i.m[14]+s*i.m[15])},e.prototype.dotCoordinate=function(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d},e.prototype.copyFromPoints=function(e,t,i){var r,n=t.x-e.x,o=t.y-e.y,s=t.z-e.z,a=i.x-e.x,l=i.y-e.y,c=i.z-e.z,h=o*c-s*l,u=s*a-n*c,d=n*l-o*a,f=Math.sqrt(h*h+u*u+d*d);return r=0!==f?1/f:0,this.normal.x=h*r,this.normal.y=u*r,this.normal.z=d*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this},e.prototype.isFrontFacingTo=function(e,t){return n.Dot(this.normal,e)<=t},e.prototype.signedDistanceTo=function(e){return n.Dot(e,this.normal)+this.d},e.FromArray=function(t){return new e(t[0],t[1],t[2],t[3])},e.FromPoints=function(t,i,r){var n=new e(0,0,0,0);return n.copyFromPoints(t,i,r),n},e.FromPositionAndNormal=function(t,i){var r=new e(0,0,0,0);return i.normalize(),r.normal=i,r.d=-(i.x*t.x+i.y*t.y+i.z*t.z),r},e.SignedDistanceToPlaneFromPositionAndNormal=function(e,t,i){var r=-(t.x*e.x+t.y*e.y+t.z*e.z);return n.Dot(i,t)+r},e})();e.Plane=c;var h=(function(){function e(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}return e.prototype.toGlobal=function(t,i){if(t.getRenderWidth){var r=t;return this.toGlobal(r.getRenderWidth(),r.getRenderHeight())}var n=t;return new e(this.x*n,this.y*i,this.width*n,this.height*i)},e.prototype.clone=function(){return new e(this.x,this.y,this.width,this.height)},e})();e.Viewport=h;var u=(function(){function e(){}return e.GetPlanes=function(t){for(var i=[],r=0;r<6;r++)i.push(new c(0,0,0,0));return e.GetPlanesToRef(t,i),i},e.GetNearPlaneToRef=function(e,t){t.normal.x=e.m[3]+e.m[2],t.normal.y=e.m[7]+e.m[6],t.normal.z=e.m[11]+e.m[10],t.d=e.m[15]+e.m[14],t.normalize()},e.GetFarPlaneToRef=function(e,t){t.normal.x=e.m[3]-e.m[2],t.normal.y=e.m[7]-e.m[6],t.normal.z=e.m[11]-e.m[10],t.d=e.m[15]-e.m[14],t.normalize()},e.GetLeftPlaneToRef=function(e,t){t.normal.x=e.m[3]+e.m[0],t.normal.y=e.m[7]+e.m[4],t.normal.z=e.m[11]+e.m[8],t.d=e.m[15]+e.m[12],t.normalize()},e.GetRightPlaneToRef=function(e,t){t.normal.x=e.m[3]-e.m[0],t.normal.y=e.m[7]-e.m[4],t.normal.z=e.m[11]-e.m[8],t.d=e.m[15]-e.m[12],t.normalize()},e.GetTopPlaneToRef=function(e,t){t.normal.x=e.m[3]-e.m[1],t.normal.y=e.m[7]-e.m[5],t.normal.z=e.m[11]-e.m[9],t.d=e.m[15]-e.m[13],t.normalize()},e.GetBottomPlaneToRef=function(e,t){t.normal.x=e.m[3]+e.m[1],t.normal.y=e.m[7]+e.m[5],t.normal.z=e.m[11]+e.m[9],t.d=e.m[15]+e.m[13],t.normalize()},e.GetPlanesToRef=function(t,i){e.GetNearPlaneToRef(t,i[0]),e.GetFarPlaneToRef(t,i[1]),e.GetLeftPlaneToRef(t,i[2]),e.GetRightPlaneToRef(t,i[3]),e.GetTopPlaneToRef(t,i[4]),e.GetBottomPlaneToRef(t,i[5])},e})();e.Frustum=u;!(function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"})(e.Space||(e.Space={}));var d=(function(){function e(){}return e.X=new n(1,0,0),e.Y=new n(0,1,0),e.Z=new n(0,0,1),e})();e.Axis=d;var f=(function(){function e(){}return e.interpolate=function(e,t,i,r,n){for(var o=1-3*r+3*t,s=3*r-6*t,a=3*t,l=e,c=0;c<5;c++){var h=l*l;l-=(o*(h*l)+s*h+a*l-e)*(1/(3*o*h+2*s*l+a)),l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*n+Math.pow(l,3)},e})();e.BezierCurve=f;var p;!(function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"})(p=e.Orientation||(e.Orientation={}));var _=(function(){function e(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}return e.prototype.degrees=function(){return 180*this._radians/Math.PI},e.prototype.radians=function(){return this._radians},e.BetweenTwoPoints=function(t,i){var r=i.subtract(t);return new e(Math.atan2(r.y,r.x))},e.FromRadians=function(t){return new e(t)},e.FromDegrees=function(t){return new e(t*Math.PI/180)},e})();e.Angle=_;var m=(function(){function e(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;var n=Math.pow(t.x,2)+Math.pow(t.y,2),o=(Math.pow(e.x,2)+Math.pow(e.y,2)-n)/2,s=(n-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new r((o*(t.y-i.y)-s*(e.y-t.y))/a,((e.x-t.x)*s-(t.x-i.x)*o)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=_.BetweenTwoPoints(this.centerPoint,this.startPoint);var l=this.startAngle.degrees(),c=_.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=_.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();c-l>180&&(c-=360),c-l<-180&&(c+=360),h-c>180&&(h-=360),h-c<-180&&(h+=360),this.orientation=c-l<0?p.CW:p.CCW,this.angle=_.FromDegrees(this.orientation===p.CW?l-h:h-l)}return e})();e.Arc2=m;var g=(function(){function e(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(e,t))}return e.prototype.addLineTo=function(e,t){if(this.closed)return this;var i=new r(e,t),n=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(n).length(),this},e.prototype.addArcTo=function(e,t,i,n,o){if(void 0===o&&(o=36),this.closed)return this;var s=this._points[this._points.length-1],a=new r(e,t),l=new r(i,n),c=new m(s,a,l),h=c.angle.radians()/o;c.orientation===p.CW&&(h*=-1);for(var u=c.startAngle.radians()+h,d=0;d1)return r.Zero();for(var t=e*this.length(),i=0,n=0;n=i&&t<=c){var h=l.normalize(),u=t-i;return new r(s.x+h.x*u,s.y+h.y*u)}i=c}return r.Zero()},e.StartingAt=function(t,i){return new e(t,i)},e})();e.Path2=g;var v=(function(){function t(e,t,i){void 0===t&&(t=null),this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;rt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i},t.prototype._normalVector=function(t,i,r){var o,s=i.length();if(0===s&&(s=1),void 0===r||null===r){var a;a=e.Scalar.WithinEpsilon(Math.abs(i.y)/s,1,e.Epsilon)?e.Scalar.WithinEpsilon(Math.abs(i.x)/s,1,e.Epsilon)?e.Scalar.WithinEpsilon(Math.abs(i.z)/s,1,e.Epsilon)?n.Zero():new n(0,0,1):new n(1,0,0):new n(0,-1,0),o=n.Cross(i,a)}else o=n.Cross(i,r),n.CrossToRef(o,i,o);return o.normalize(),o},t})();e.Path3D=v;var y=(function(){function e(e){this._length=0,this._points=e,this._length=this._computeLength(e)}return e.CreateQuadraticBezier=function(t,i,r,o){o=o>2?o:3;for(var s=new Array,a=function(e,t,i,r){return(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r},l=0;l<=o;l++)s.push(new n(a(l/o,t.x,i.x,r.x),a(l/o,t.y,i.y,r.y),a(l/o,t.z,i.z,r.z)));return new e(s)},e.CreateCubicBezier=function(t,i,r,o,s){s=s>3?s:4;for(var a=new Array,l=function(e,t,i,r,n){return(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*n},c=0;c<=s;c++)a.push(new n(l(c/s,t.x,i.x,r.x,o.x),l(c/s,t.y,i.y,r.y,o.y),l(c/s,t.z,i.z,r.z,o.z)));return new e(a)},e.CreateHermiteSpline=function(t,i,r,o,s){for(var a=new Array,l=1/s,c=0;c<=s;c++)a.push(n.Hermite(t,i,r,o,c*l));return new e(a)},e.CreateCatmullRomSpline=function(t,i,r){var o=new Array,s=1/i,a=0;if(r){for(var l=t.length,c=0;c0?1:-1},e.Clamp=function(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1),Math.min(i,Math.max(t,e))},e.Log2=function(e){return Math.log(e)*Math.LOG2E},e.Repeat=function(e,t){return e-Math.floor(e/t)*t},e.Normalize=function(e,t,i){return(e-t)/(i-t)},e.Denormalize=function(e,t,i){return e*(i-t)+t},e.DeltaAngle=function(t,i){var r=e.Repeat(i-t,360);return r>180&&(r-=360),r},e.PingPong=function(t,i){var r=e.Repeat(t,2*i);return i-Math.abs(r-i)},e.SmoothStep=function(t,i,r){var n=e.Clamp(r);return n=-2*n*n*n+3*n*n,i*n+t*(1-n)},e.MoveTowards=function(t,i,r){return Math.abs(i-t)<=r?i:t+e.Sign(i-t)*r},e.MoveTowardsAngle=function(t,i,r){var n=e.DeltaAngle(t,i),o=0;return-r180&&(n-=360),t+n*e.Clamp(r)},e.InverseLerp=function(t,i,r){return t!=i?e.Clamp((r-t)/(i-t)):0},e.Hermite=function(e,t,i,r,n){var o=n*n,s=n*o;return e*(2*s-3*o+1)+i*(-2*s+3*o)+t*(s-2*o+n)+r*(s-o)},e.RandomRange=function(e,t){return e===t?e:Math.random()*(t-e)+e},e.RangeToPercent=function(e,t,i){return(e-t)/(i-t)},e.PercentToRange=function(e,t,i){return(i-t)*e+t},e.NormalizeRadians=function(t){return t-=e.TwoPi*Math.floor((t+Math.PI)/e.TwoPi)},e.TwoPi=2*Math.PI,e})();e.Scalar=t})(r||(r={}));var r;!(function(e){function t(e){var t=e.getClassName();return v[t]||(v[t]={}),v[t]}function i(e){var t=e.getClassName();if(y[t])return y[t];y[t]={};for(var i=y[t],r=e,n=t;n;){var o=v[n];for(var s in o)i[s]=o[s];var a=void 0,l=!1;do{if(a=Object.getPrototypeOf(r),!a.getClassName){l=!0;break}if(a.getClassName()!==n)break;r=a}while(a);if(l)break;n=a.getClassName(),r=a}return i}function r(e,i){return function(r,n){var o=t(r);o[n]||(o[n]={type:e,sourceName:i})}}function n(e,t){return void 0===t&&(t=null),function(i,r){var n=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[n]},set:function(t){this[n]!==t&&(this[n]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}function o(e,t){return void 0===t&&(t=null),n(e,t)}function s(e){return r(0,e)}function a(e){return r(1,e)}function l(e){return r(2,e)}function c(e){return r(3,e)}function h(e){return r(4,e)}function u(e){return r(5,e)}function d(e){return r(6,e)}function f(e){return r(7,e)}function p(e){return r(8,e)}function _(e){return r(9,e)}function m(e){return r(10,e)}function g(e){return r(11,e)}var v={},y={},b=function(t,r,n){var o=t();e.Tags&&e.Tags.AddTagsTo(o,r.tags);var s=i(o);for(var a in s){var l=s[a],c=r[a],h=l.type;if(void 0!==c&&null!==c)switch(h){case 0:case 6:case 11:o[a]=c;break;case 1:o[a]=n||c.isRenderTarget?c:c.clone();break;case 2:case 3:case 4:case 5:case 7:case 10:o[a]=n?c:c.clone()}}return o};e.expandToProperty=o,e.serialize=s,e.serializeAsTexture=a,e.serializeAsColor3=l,e.serializeAsFresnelParameters=c,e.serializeAsVector2=h,e.serializeAsVector3=u,e.serializeAsMeshReference=d,e.serializeAsColorCurves=f,e.serializeAsColor4=p,e.serializeAsImageProcessingConfiguration=_,e.serializeAsQuaternion=m,e.serializeAsCameraReference=g;var x=(function(){function t(){}return t.Serialize=function(t,r){r||(r={}),e.Tags&&(r.tags=e.Tags.GetTags(t));var n=i(t);for(var o in n){var s=n[o],a=s.sourceName||o,l=s.type,c=t[o];if(void 0!==c&&null!==c)switch(l){case 0:r[a]=c;break;case 1:r[a]=c.serialize();break;case 2:r[a]=c.asArray();break;case 3:r[a]=c.serialize();break;case 4:case 5:r[a]=c.asArray();break;case 6:r[a]=c.id;break;case 7:r[a]=c.serialize();break;case 8:r[a]=c.asArray();break;case 9:r[a]=c.serialize();break;case 10:r[a]=c.asArray();break;case 11:r[a]=c.id}}return r},t.Parse=function(t,r,n,o){void 0===o&&(o=null);var s=t();o||(o=""),e.Tags&&e.Tags.AddTagsTo(s,r.tags);var a=i(s);for(var l in a){var c=a[l],h=r[c.sourceName||l],u=c.type;if(void 0!==h&&null!==h){var d=s;switch(u){case 0:d[l]=h;break;case 1:n&&(d[l]=e.Texture.Parse(h,n,o));break;case 2:d[l]=e.Color3.FromArray(h);break;case 3:d[l]=e.FresnelParameters.Parse(h);break;case 4:d[l]=e.Vector2.FromArray(h);break;case 5:d[l]=e.Vector3.FromArray(h);break;case 6:n&&(d[l]=n.getLastMeshByID(h));break;case 7:d[l]=e.ColorCurves.Parse(h);break;case 8:d[l]=e.Color4.FromArray(h);break;case 9:d[l]=e.ImageProcessingConfiguration.Parse(h);break;case 10:d[l]=e.Quaternion.FromArray(h);break;case 11:n&&(d[l]=n.getCameraByID(h))}}}return s},t.Clone=function(e,t){return b(e,t,!1)},t.Instanciate=function(e,t){return b(e,t,!0)},t})();e.SerializationHelper=x})(r||(r={}));var r;!(function(e){var t=(function(){function e(){var e=this;this.promise=new Promise(function(t,i){e._resolve=t,e._reject=i})}return Object.defineProperty(e.prototype,"resolve",{get:function(){return this._resolve},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"reject",{get:function(){return this._reject},enumerable:!0,configurable:!0}),e})();e.Deferred=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i,r){void 0===t&&(t=!1),this.initalize(e,t,i,r)}return e.prototype.initalize=function(e,t,i,r){return void 0===t&&(t=!1),this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this},e})();e.EventState=t;var i=(function(){function e(e,t,i){void 0===i&&(i=null),this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1}return e})();e.Observer=i;var r=(function(){function e(){}return e.prototype.dispose=function(){if(this._observers&&this._observables)for(var e=0;e0},r.prototype.clear=function(){this._observers=new Array,this._onObserverAdded=null},r.prototype.clone=function(){var e=new r;return e._observers=this._observers.slice(0),e},r.prototype.hasSpecificMask=function(e){void 0===e&&(e=-1);for(var t=0,i=this._observers;tthis.data.length&&(this.data.length*=2)},e.prototype.forEach=function(e){for(var t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t=this.length?-1:t},e.prototype.contains=function(e){return-1!==this.data.indexOf(e)},e._GlobalId=0,e})();e.SmartArray=t;var i=(function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._duplicateId=0,t}return o(t,e),t.prototype.push=function(t){e.prototype.push.call(this,t),t.__smartArrayFlags||(t.__smartArrayFlags={}),t.__smartArrayFlags[this._id]=this._duplicateId},t.prototype.pushNoDuplicate=function(e){return(!e.__smartArrayFlags||e.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(e),!0)},t.prototype.reset=function(){e.prototype.reset.call(this),this._duplicateId++},t.prototype.concatWithNoDuplicate=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t=e||-1!==i.indexOf("file:")?-1:Math.pow(2,n)*t}},e})();e.RetryStrategy=s;var a,l=function(t,i){return t?t instanceof e.Mesh?null:t instanceof e.SubMesh?t.clone(i):t.clone?t.clone():null:null},c=(function(){function t(){}return t.FetchToRef=function(e,t,i,r,n,o){var s=Math.abs(e)*i%i|0,a=Math.abs(t)*r%r|0,l=4*(s+a*i);o.r=n[l]/255,o.g=n[l+1]/255,o.b=n[l+2]/255,o.a=n[l+3]/255},t.Mix=function(e,t,i){return e*(1-i)+t*i},t.Instantiate=function(e){if(t.RegisteredExternalClasses&&t.RegisteredExternalClasses[e])return t.RegisteredExternalClasses[e];for(var i=e.split("."),r=window||this,n=0,o=i.length;n>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e},t.FloorPOT=function(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)},t.NearestPOT=function(e){var i=t.CeilingPOT(e),r=t.FloorPOT(e);return i-e>e-r?r:i},t.GetExponentOfTwo=function(i,r,n){void 0===n&&(n=e.Engine.SCALEMODE_NEAREST);var o;switch(n){case e.Engine.SCALEMODE_FLOOR:o=t.FloorPOT(i);break;case e.Engine.SCALEMODE_NEAREST:o=t.NearestPOT(i);break;case e.Engine.SCALEMODE_CEILING:default:o=t.CeilingPOT(i)}return Math.min(o,r)},t.GetFilename=function(e){var t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)},t.GetFolderPath=function(e,t){void 0===t&&(t=!1);var i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)},t.GetDOMTextContent=function(e){for(var t="",i=e.firstChild;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t},t.ToDegrees=function(e){return 180*e/Math.PI},t.ToRadians=function(e){return e*Math.PI/180},t.EncodeArrayBufferTobase64=function(e){for(var t,i,r,n,o,s,a,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c="",h=0,u=new Uint8Array(e);h>2,o=(3&t)<<4|i>>4,s=(15&i)<<2|r>>6,a=63&r,isNaN(i)?s=a=64:isNaN(r)&&(a=64),c+=l.charAt(n)+l.charAt(o)+l.charAt(s)+l.charAt(a);return"data:image/png;base64,"+c},t.ExtractMinAndMaxIndexed=function(t,i,r,n,o){void 0===o&&(o=null) -;for(var s=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new e.Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),l=r;l=(r?t.length/2:t.length))return null;if(r){var n=t;return new e.Vector2(n[2*i+0],n[2*i+1])}return t[i]}},t.ExtractMinAndMaxVector2=function(t,i){void 0===i&&(i=null);for(var r=new e.Vector2(Number.MAX_VALUE,Number.MAX_VALUE),n=new e.Vector2(-Number.MAX_VALUE,-Number.MAX_VALUE),o=0,s=t(o++);s;)r=e.Vector2.Minimize(s,r),n=e.Vector2.Maximize(s,n),s=t(o++);return i&&(r.x-=r.x*i.x+i.y,r.y-=r.y*i.x+i.y,n.x+=n.x*i.x+i.y,n.y+=n.y*i.x+i.y),{minimum:r,maximum:n}},t.MakeArray=function(e,t){return!0===t||void 0!==e&&null!=e?Array.isArray(e)?e:[e]:null},t.GetPointerPrefix=function(){var e="pointer";return!t.IsWindowObjectExist()||window.PointerEvent||navigator.pointerEnabled||(e="mouse"),e},t.QueueNewFrame=function(e,i){return t.IsWindowObjectExist()?(i||(i=window),i.requestAnimationFrame?i.requestAnimationFrame(e):i.msRequestAnimationFrame?i.msRequestAnimationFrame(e):i.webkitRequestAnimationFrame?i.webkitRequestAnimationFrame(e):i.mozRequestAnimationFrame?i.mozRequestAnimationFrame(e):i.oRequestAnimationFrame?i.oRequestAnimationFrame(e):window.setTimeout(e,16)):setTimeout(e,16)},t.RequestFullscreen=function(e){var t=e.requestFullscreen||e.msRequestFullscreen||e.webkitRequestFullscreen||e.mozRequestFullScreen;t&&t.call(e)},t.ExitFullscreen=function(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitCancelFullScreen?document.webkitCancelFullScreen():document.msCancelFullScreen&&document.msCancelFullScreen()},t.SetCorsBehavior=function(e,i){if((!e||0!==e.indexOf("data:"))&&t.CorsBehavior)if("string"==typeof t.CorsBehavior||t.CorsBehavior instanceof String)i.crossOrigin=t.CorsBehavior;else{var r=t.CorsBehavior(e);r&&(i.crossOrigin=r)}},t.CleanUrl=function(e){return e=e.replace(/#/gm,"%23")},t.LoadImage=function(i,r,n,o){var s,a=!1;i instanceof ArrayBuffer?(s=URL.createObjectURL(new Blob([i])),a=!0):i instanceof Blob?(s=URL.createObjectURL(i),a=!0):(s=t.CleanUrl(i),s=t.PreprocessUrl(i));var l=new Image;t.SetCorsBehavior(s,l);var c=function(){a&&l.src&&URL.revokeObjectURL(l.src),l.removeEventListener("load",c),l.removeEventListener("error",h),r(l)},h=function(e){a&&l.src&&URL.revokeObjectURL(l.src),l.removeEventListener("load",c),l.removeEventListener("error",h),t.Error("Error while trying to load image: "+i),n&&n("Error while trying to load image: "+i,e)};l.addEventListener("load",c),l.addEventListener("error",h);var u=function(){l.src=s},d=function(){o&&o.loadImageFromDB(s,l)};if("data:"!==s.substr(0,5)&&o&&o.enableTexturesOffline&&e.Database.IsUASupportingBlobStorage)o.openAsync(d,u);else{if(-1!==s.indexOf("file:")){var f=decodeURIComponent(s.substring(5).toLowerCase());if(e.FilesInput.FilesToLoad[f]){try{var p;try{p=URL.createObjectURL(e.FilesInput.FilesToLoad[f],{oneTimeOnly:!0})}catch(t){p=URL.createObjectURL(e.FilesInput.FilesToLoad[f])}l.src=p,a=!0}catch(e){l.src=""}return l}}u()}return l},t.LoadFile=function(i,r,o,s,a,l){if(i=t.CleanUrl(i),i=t.PreprocessUrl(i),-1!==i.indexOf("file:")){var c=decodeURIComponent(i.substring(5).toLowerCase());if(e.FilesInput.FilesToLoad[c])return t.ReadFile(e.FilesInput.FilesToLoad[c],r,o,a)}var h=t.BaseUrl+i,u=!1,d={onCompleteObservable:new e.Observable,abort:function(){return u=!0}},f=function(){var e=new XMLHttpRequest,i=null;d.abort=function(){u=!0,e.readyState!==(XMLHttpRequest.DONE||4)&&e.abort(),null!==i&&(clearTimeout(i),i=null)};var s=function(c){e.open("GET",h,!0),a&&(e.responseType="arraybuffer"),o&&e.addEventListener("progress",o);var f=function(){e.removeEventListener("loadend",f),d.onCompleteObservable.notifyObservers(d),d.onCompleteObservable.clear()};e.addEventListener("loadend",f);var p=function(){if(!u&&e.readyState===(XMLHttpRequest.DONE||4)){if(e.removeEventListener("readystatechange",p),e.status>=200&&e.status<300||!t.IsWindowObjectExist()&&0===e.status)return void r(a?e.response:e.responseText,e.responseURL);var o=t.DefaultRetryStrategy;if(o){var d=o(h,e,c);if(-1!==d)return e.removeEventListener("loadend",f),e=new XMLHttpRequest,void(i=setTimeout((function(){return s(c+1)}),d))}var _=new n("Error status: "+e.status+" "+e.statusText+" - Unable to load "+h,e);if(!l)throw _;l(e,_)}};e.addEventListener("readystatechange",p),e.send()};s(0)};if(s&&s.enableSceneOffline){var p=function(e){e&&e.status>400?l&&l(e):u||f()},_=function(){u||s&&s.loadFileFromDB(i,(function(e){u||r(e),d.onCompleteObservable.notifyObservers(d)}),o?function(e){u||o(e)}:void 0,p,a)};s.openAsync(_,p)}else f();return d},t.LoadScript=function(e,t,i){var r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.type="text/javascript",n.src=e,n.onload=function(){t&&t()},n.onerror=function(t){i&&i("Unable to load script '"+e+"'",t)},r.appendChild(n)},t.ReadFileAsDataURL=function(t,i,r){var n=new FileReader,o={onCompleteObservable:new e.Observable,abort:function(){return n.abort()}};return n.onloadend=function(e){o.onCompleteObservable.notifyObservers(o)},n.onload=function(e){i(e.target.result)},n.onprogress=r,n.readAsDataURL(t),o},t.ReadFile=function(i,r,n,o){var s=new FileReader,a={onCompleteObservable:new e.Observable,abort:function(){return s.abort()}};return s.onloadend=function(e){return a.onCompleteObservable.notifyObservers(a)},s.onerror=function(e){t.Log("Error while reading file: "+i.name),r(JSON.stringify({autoClear:!0,clearColor:[1,0,0],ambientColor:[0,0,0],gravity:[0,-9.807,0],meshes:[],cameras:[],lights:[]}))},s.onload=function(e){r(e.target.result)},n&&(s.onprogress=n),o?s.readAsArrayBuffer(i):s.readAsText(i),a},t.FileAsURL=function(e){var t=new Blob([e]);return(window.URL||window.webkitURL).createObjectURL(t)},t.Format=function(e,t){return void 0===t&&(t=2),e.toFixed(t)},t.CheckExtends=function(e,t,i){e.xi.x&&(i.x=e.x),e.y>i.y&&(i.y=e.y),e.z>i.z&&(i.z=e.z)},t.DeepCopy=function(e,t,i,r){for(var n in e)if(("_"!==n[0]||r&&-1!==r.indexOf(n))&&(!i||-1===i.indexOf(n))){var o=e[n],s=typeof o;if("function"!==s)try{if("object"===s)if(o instanceof Array){if(t[n]=[],o.length>0)if("object"==typeof o[0])for(var a=0;al&&(d=l,u=d*h);var f=Math.max(0,s-u)/2,p=Math.max(0,l-d)/2,_=e.getRenderingCanvas();c&&_&&c.drawImage(_,f,p,u,d),t.EncodeScreenshotCanvasData(n,o)},t.CreateScreenshotUsingRenderTarget=function(i,r,n,o,s,a,l,c){void 0===s&&(s="image/png"),void 0===a&&(a=1),void 0===l&&(l=!1);var h,u;if(n.precision)h=Math.round(i.getRenderWidth()*n.precision),u=Math.round(h/i.getAspectRatio(r)),n={width:h,height:u};else if(n.width&&n.height)h=n.width,u=n.height;else if(n.width&&!n.height)h=n.width,u=Math.round(h/i.getAspectRatio(r)),n={width:h,height:u};else if(n.height&&!n.width)u=n.height,h=Math.round(u*i.getAspectRatio(r)),n={width:h,height:u};else{if(isNaN(n))return void t.Error("Invalid 'size' parameter !");u=n,h=n}var d=r.getScene(),f=null;d.activeCamera!==r&&(f=d.activeCamera,d.activeCamera=r);var p=new e.RenderTargetTexture("screenShot",n,d,!1,!1,e.Engine.TEXTURETYPE_UNSIGNED_INT,!1,e.Texture.NEAREST_SAMPLINGMODE);p.renderList=null,p.samples=a,l&&p.addPostProcess(new e.FxaaPostProcess("antialiasing",1,d.activeCamera)),p.onAfterRenderObservable.add((function(){t.DumpFramebuffer(h,u,i,o,s,c)})),d.incrementRenderId(),d.resetCachedMaterial(),p.render(!0),p.dispose(),f&&(d.activeCamera=f),r.getProjectionMatrix(!0)},t.ValidateXHRData=function(t,i){void 0===i&&(i=7);try{if(1&i){if(t.responseText&&t.responseText.length>0)return!0;if(1===i)return!1}if(2&i){var r=e.TGATools.GetTGAHeader(t.response);if(r.width&&r.height&&r.width>0&&r.height>0)return!0;if(2===i)return!1}if(4&i){var n=new Uint8Array(t.response,0,3);return 68===n[0]&&68===n[1]&&83===n[2]}}catch(e){}return!1},t.RandomId=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))},t.IsBase64=function(e){return!(e.length<5)&&"data:"===e.substr(0,5)},t.DecodeBase64=function(e){for(var t=atob(e.split(",")[1]),i=t.length,r=new Uint8Array(new ArrayBuffer(i)),n=0;n
";t._AddLogEntry(r)},t._WarnDisabled=function(e){},t._WarnEnabled=function(e){var i=t._FormatMessage(e);console.warn("BJS - "+i);var r="
"+i+"

";t._AddLogEntry(r)},t._ErrorDisabled=function(e){},t._ErrorEnabled=function(e){t.errorsCount++;var i=t._FormatMessage(e);console.error("BJS - "+i);var r="
"+i+"

";t._AddLogEntry(r)},Object.defineProperty(t,"LogCache",{get:function(){return t._LogCache},enumerable:!0,configurable:!0}),t.ClearLogCache=function(){t._LogCache="",t.errorsCount=0},Object.defineProperty(t,"LogLevels",{set:function(e){(e&t.MessageLogLevel)===t.MessageLogLevel?t.Log=t._LogEnabled:t.Log=t._LogDisabled,(e&t.WarningLogLevel)===t.WarningLogLevel?t.Warn=t._WarnEnabled:t.Warn=t._WarnDisabled,(e&t.ErrorLogLevel)===t.ErrorLogLevel?t.Error=t._ErrorEnabled:t.Error=t._ErrorDisabled},enumerable:!0,configurable:!0}),t.IsWindowObjectExist=function(){return"undefined"!=typeof window},Object.defineProperty(t,"PerformanceNoneLogLevel",{get:function(){return t._PerformanceNoneLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceUserMarkLogLevel",{get:function(){return t._PerformanceUserMarkLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceConsoleLogLevel",{get:function(){return t._PerformanceConsoleLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceLogLevel",{set:function(e){return(e&t.PerformanceUserMarkLogLevel)===t.PerformanceUserMarkLogLevel?(t.StartPerformanceCounter=t._StartUserMark,void(t.EndPerformanceCounter=t._EndUserMark)):(e&t.PerformanceConsoleLogLevel)===t.PerformanceConsoleLogLevel?(t.StartPerformanceCounter=t._StartPerformanceConsole,void(t.EndPerformanceCounter=t._EndPerformanceConsole)):(t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,void(t.EndPerformanceCounter=t._EndPerformanceCounterDisabled))},enumerable:!0,configurable:!0}),t._StartPerformanceCounterDisabled=function(e,t){},t._EndPerformanceCounterDisabled=function(e,t){},t._StartUserMark=function(e,i){if(void 0===i&&(i=!0),!t._performance){if(!t.IsWindowObjectExist())return;t._performance=window.performance}i&&t._performance.mark&&t._performance.mark(e+"-Begin")},t._EndUserMark=function(e,i){void 0===i&&(i=!0),i&&t._performance.mark&&(t._performance.mark(e+"-End"),t._performance.measure(e,e+"-Begin",e+"-End"))},t._StartPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._StartUserMark(e,i),console.time&&console.time(e))},t._EndPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._EndUserMark(e,i),console.time&&console.timeEnd(e))},Object.defineProperty(t,"Now",{get:function(){return t.IsWindowObjectExist()&&window.performance&&window.performance.now?window.performance.now():Date.now()},enumerable:!0,configurable:!0}),t.GetClassName=function(e,t){void 0===t&&(t=!1);var i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__}i||(i=typeof e)}return i},t.First=function(e,t){for(var i=0,r=e;i=e.length)return null;var r=e.charCodeAt?e.charCodeAt(i):e[i];return r&&r.getHashCode&&(r=r.getHashCode()),"string"==typeof r?t.hashCodeFromStream(t.arrayOrStringFeeder(r)):r}},t.hashCodeFromStream=function(e){for(var t=0,i=0,r=e(i++);null!=r;)t=(t<<5)-t+r,t|=0,r=e(i++);return t},t.DelayAsync=function(e){return new Promise(function(t){setTimeout((function(){t()}),e)})},t.GetCurrentGradient=function(e,t,i){for(var r=0;r=n.gradient&&e<=o.gradient){i(n,o,(e-n.gradient)/(o.gradient-n.gradient))}}},t.BaseUrl="",t.DefaultRetryStrategy=s.ExponentialBackoff(),t.CorsBehavior="anonymous",t.UseFallbackTexture=!0,t.RegisteredExternalClasses={},t.fallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z",t._tmpFloatArray=new Float32Array(1),t.PreprocessUrl=function(e){return e},t._NoneLogLevel=0,t._MessageLogLevel=1,t._WarningLogLevel=2,t._ErrorLogLevel=4,t._LogCache="",t.errorsCount=0,t.Log=t._LogEnabled,t.Warn=t._WarnEnabled,t.Error=t._ErrorEnabled,t._PerformanceNoneLogLevel=0,t._PerformanceUserMarkLogLevel=1,t._PerformanceConsoleLogLevel=2,t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,t.EndPerformanceCounter=t._EndPerformanceCounterDisabled,t})();e.Tools=c;var h=(function(){function e(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}return Object.defineProperty(e.prototype,"min",{get:function(){return this._min},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"max",{get:function(){return this._max},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"average",{get:function(){return this._average},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lastSecAverage",{get:function(){return this._lastSecAverage},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"current",{get:function(){return this._current},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"total",{get:function(){return this._totalAccumulated},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"count",{get:function(){return this._totalValueCount},enumerable:!0,configurable:!0}),e.prototype.fetchNewFrame=function(){this._totalValueCount++,this._current=0,this._lastSecValueCount++},e.prototype.addCount=function(t,i){e.Enabled&&(this._current+=t,i&&this._fetchResult())},e.prototype.beginMonitoring=function(){e.Enabled&&(this._startMonitoringTime=c.Now)},e.prototype.endMonitoring=function(t){if(void 0===t&&(t=!0),e.Enabled){t&&this.fetchNewFrame();var i=c.Now;this._current=i-this._startMonitoringTime,t&&this._fetchResult()}},e.prototype._fetchResult=function(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;var e=c.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)},e.Enabled=!0,e})();e.PerfCounter=h,e.className=t;var u=(function(){function e(e,t,i,r){void 0===r&&(r=0),this.iterations=e,this._fn=t,this._successCallback=i,this.index=r-1,this._done=!1}return e.prototype.executeNext=function(){this._done||(this.index+1=t)break;if(r(s),o&&o()){e.breakLoop();break}}e.executeNext()}),s)}),n)},e})();e.AsyncLoop=u})(r||(r={}));var r;!(function(e){var t;!(function(e){e[e.Pending=0]="Pending",e[e.Fulfilled=1]="Fulfilled",e[e.Rejected=2]="Rejected"})(t||(t={}));var i=(function(){function e(){this.count=0,this.target=0,this.results=[]}return e})(),r=(function(){function r(e){var i=this;if(this._state=t.Pending,this._children=new Array,this._rejectWasConsumed=!1,e)try{e((function(e){i._resolve(e)}),(function(e){i._reject(e)}))}catch(e){this._reject(e)}}return Object.defineProperty(r.prototype,"_result",{get:function(){return this._resultValue},set:function(e){this._resultValue=e,this._parent&&void 0===this._parent._result&&(this._parent._result=e)},enumerable:!0,configurable:!0}),r.prototype.catch=function(e){return this.then(void 0,e)},r.prototype.then=function(i,n){var o=this,s=new r;return s._onFulfilled=i,s._onRejected=n,this._children.push(s),s._parent=this,this._state!==t.Pending&&e.Tools.SetImmediate((function(){if(o._state===t.Fulfilled||o._rejectWasConsumed){var e=s._resolve(o._result);if(void 0!==e&&null!==e)if(void 0!==e._state){var i=e;s._children.push(i),i._parent=s,s=i}else s._result=e}else s._reject(o._reason)})),s},r.prototype._moveChildren=function(e){var i=this;if((l=this._children).push.apply(l,e.splice(0,e.length)),this._children.forEach((function(e){e._parent=i})),this._state===t.Fulfilled)for(var r=0,n=this._children;r-1){if(d.capture&&d.captureConstraint){var _=d.capture,m=d.captureConstraint,g=new RegExp(_),v=g.exec(c);if(v&&v.length>0){var y=parseInt(v[v.length-1]);if(y>=m)continue}}for(var b=0,x=p;b1&&!this.disableUniformBuffers},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"needPOTTextures",{get:function(){return this._webGLVersion<2||this.forcePOTTextures},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"doNotHandleContextLost",{get:function(){return this._doNotHandleContextLost},set:function(e){this._doNotHandleContextLost=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"performanceMonitor",{get:function(){return this._performanceMonitor},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"texturesSupported",{get:function(){return this._texturesSupported},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"currentViewport",{get:function(){return this._cachedViewport},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"emptyTexture",{get:function(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,i.TEXTUREFORMAT_RGBA,!1,!1,i.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"emptyTexture3D",{get:function(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,i.TEXTUREFORMAT_RGBA,!1,!1,i.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture3D},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"emptyCubeTexture",{get:function(){if(!this._emptyCubeTexture){var e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,i.TEXTUREFORMAT_RGBA,i.TEXTURETYPE_UNSIGNED_INT,!1,!1,i.TEXTURE_NEAREST_SAMPLINGMODE)}return this._emptyCubeTexture},enumerable:!0,configurable:!0}),i.prototype._rebuildInternalTextures=function(){for(var e=this._internalTexturesCache.slice(),t=0,i=e;t1||null!==this._gl.getExtension("OES_standard_derivatives"),this._caps.astc=this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),this._caps.s3tc=this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),this._caps.pvrtc=this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),this._caps.etc1=this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),this._caps.etc2=this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),this._caps.textureAnisotropicFilterExtension=this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.uintIndices=this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),this._caps.fragmentDepthSupported=this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),this._caps.highPrecisionShaderSupported=!0,this._caps.timerQuery=this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)>0),this._caps.colorBufferFloat=this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float"),this._caps.textureFloat=!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloat=!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._webGLVersion>1&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._caps.textureLOD=!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),this._webGLVersion>1)this._caps.drawBuffersExtension=!0;else{var t=this._gl.getExtension("WEBGL_draw_buffers");if(null!==t){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=t.drawBuffersWEBGL.bind(t),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(var i=0;i<16;i++)this._gl["COLOR_ATTACHMENT"+i+"_WEBGL"]=t["COLOR_ATTACHMENT"+i+"_WEBGL"]}else this._caps.drawBuffersExtension=!1}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{var r=this._gl.getExtension("WEBGL_depth_texture");null!=r&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=r.UNSIGNED_INT_24_8_WEBGL)}if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{var n=this._gl.getExtension("OES_vertex_array_object");null!=n?(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=n.createVertexArrayOES.bind(n),this._gl.bindVertexArray=n.bindVertexArrayOES.bind(n),this._gl.deleteVertexArray=n.deleteVertexArrayOES.bind(n)):this._caps.vertexArrayObject=!1}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{var s=this._gl.getExtension("ANGLE_instanced_arrays");null!=s?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=s.drawArraysInstancedANGLE.bind(s),this._gl.drawElementsInstanced=s.drawElementsInstancedANGLE.bind(s),this._gl.vertexAttribDivisor=s.vertexAttribDivisorANGLE.bind(s)):this._caps.instancedArrays=!1}if(this._caps.astc&&this.texturesSupported.push("-astc.ktx"),this._caps.s3tc&&this.texturesSupported.push("-dxt.ktx"),this._caps.pvrtc&&this.texturesSupported.push("-pvrtc.ktx"),this._caps.etc2&&this.texturesSupported.push("-etc2.ktx"),this._caps.etc1&&this.texturesSupported.push("-etc1.ktx"),this._gl.getShaderPrecisionFormat){var a=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);a&&(this._caps.highPrecisionShaderSupported=0!==a.precision)}this.setDepthBuffer(!0),this.setDepthFunctionToLessOrEqual(),this.setDepthWrite(!0),this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(var l=0;l=0&&this._activeRenderLoops.splice(t,1)},i.prototype._renderLoop=function(){if(!this._contextWasLost){var t=!0;if(!this.renderEvenInBackground&&this._windowIsBackground&&(t=!1),t){this.beginFrame();for(var i=0;i0){var r=null;this._vrDisplay&&this._vrDisplay.isPresenting&&(r=this._vrDisplay),this._frameHandler=e.Tools.QueueNewFrame(this._bindedRenderFunction,r)}else this._renderingQueueLaunched=!1},i.prototype.runRenderLoop=function(t){-1===this._activeRenderLoops.indexOf(t)&&(this._activeRenderLoops.push(t),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._bindedRenderFunction=this._renderLoop.bind(this),this._frameHandler=e.Tools.QueueNewFrame(this._bindedRenderFunction)))},i.prototype.switchFullscreen=function(t){this.isFullscreen?e.Tools.ExitFullscreen():(this._pointerLockRequested=t,this._renderingCanvas&&e.Tools.RequestFullscreen(this._renderingCanvas))},i.prototype.clear=function(e,t,i,r){void 0===r&&(r=!1),this.applyStates();var n=0;t&&e&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),n|=this._gl.COLOR_BUFFER_BIT),i&&(this._gl.clearDepth(1),n|=this._gl.DEPTH_BUFFER_BIT),r&&(this._gl.clearStencil(0),n|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(n)},i.prototype.scissorClear=function(e,t,i,r,n){var o=this._gl,s=o.getParameter(o.SCISSOR_TEST),a=o.getParameter(o.SCISSOR_BOX);o.enable(o.SCISSOR_TEST),o.scissor(e,t,i,r),this.clear(n,!0,!0,!0),o.scissor(a[0],a[1],a[2],a[3]),!0===s?o.enable(o.SCISSOR_TEST):o.disable(o.SCISSOR_TEST)},i.prototype._viewport=function(e,t,i,r){e===this._viewportCached.x&&t===this._viewportCached.y&&i===this._viewportCached.z&&r===this._viewportCached.w||(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r,this._gl.viewport(e,t,i,r))},i.prototype.setViewport=function(e,t,i){var r=t||this.getRenderWidth(),n=i||this.getRenderHeight(),o=e.x||0,s=e.y||0;this._cachedViewport=e,this._viewport(o*r,s*n,r*e.width,n*e.height)},i.prototype.setDirectViewport=function(e,t,i,r){var n=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),n},i.prototype.beginFrame=function(){this.onBeginFrameObservable.notifyObservers(this),this._measureFps()},i.prototype.endFrame=function(){this._badOS&&this.flushFramebuffer(),this._vrDisplay&&this._vrDisplay.isPresenting&&this._vrDisplay.submitFrame(),this.onEndFrameObservable.notifyObservers(this)},i.prototype.resize=function(){if(!this._vrDisplay||!this._vrDisplay.isPresenting){var e=this._renderingCanvas?this._renderingCanvas.clientWidth:window.innerWidth,t=this._renderingCanvas?this._renderingCanvas.clientHeight:window.innerHeight;this.setSize(e/this._hardwareScalingLevel,t/this._hardwareScalingLevel)}},i.prototype.setSize=function(e,t){if(this._renderingCanvas&&(this._renderingCanvas.width!==e||this._renderingCanvas.height!==t)){this._renderingCanvas.width=e,this._renderingCanvas.height=t;for(var i=0;i1?"COLOR_ATTACHMENT"+o:"COLOR_ATTACHMENT"+o+"_WEBGL"],r.readBuffer(n[o]),r.drawBuffers(n),r.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(var o=0;o1?"COLOR_ATTACHMENT"+o:"COLOR_ATTACHMENT"+o+"_WEBGL"];r.drawBuffers(n)}for(var o=0;o65535){n=!0;break}r=n?new Uint32Array(e):new Uint16Array(e)}else r=new Uint16Array(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),i.references=1,i.is32Bits=n,i},i.prototype.bindArrayBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(e,this._gl.ARRAY_BUFFER)},i.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e)},i.prototype.bindUniformBufferBase=function(e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e)},i.prototype.bindUniformBlock=function(e,t,i){var r=this._gl.getUniformBlockIndex(e,t);this._gl.uniformBlockBinding(e,r,i)},i.prototype.bindIndexBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)},i.prototype.bindBuffer=function(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e),this._currentBoundBuffer[t]=e)},i.prototype.updateArrayBuffer=function(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)},i.prototype._vertexAttribPointer=function(e,t,i,r,n,o,s){var a=this._currentBufferPointers[t],l=!1;a.active?(a.buffer!==e&&(a.buffer=e,l=!0),a.size!==i&&(a.size=i,l=!0),a.type!==r&&(a.type=r,l=!0),a.normalized!==n&&(a.normalized=n,l=!0),a.stride!==o&&(a.stride=o,l=!0),a.offset!==s&&(a.offset=s,l=!0)):(l=!0,a.active=!0,a.index=t,a.size=i,a.type=r,a.normalized=n,a.stride=o,a.offset=s,a.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),this._gl.vertexAttribPointer(t,i,r,n,o,s))},i.prototype._bindIndexBufferWithCache=function(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)},i.prototype._bindVertexBuffersAttributes=function(e,t){var i=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var r=0;r=0){var o=e[i[r]];if(!o)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);var s=o.getBuffer();s&&(this._vertexAttribPointer(s,n,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(s))))}}},i.prototype.recordVertexArrayObject=function(e,t,i){var r=this._gl.createVertexArray();return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r},i.prototype.bindVertexArrayObject=function(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)},i.prototype.bindBuffersDirectly=function(e,t,i,r,n){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==n){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=n;var o=n.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var s=0,a=0;a=0&&(this._gl.enableVertexAttribArray(l),this._vertexAttribArraysEnabled[l]=!0,this._vertexAttribPointer(e,l,i[a],this._gl.FLOAT,!1,r,s)),s+=4*i[a]}}this._bindIndexBufferWithCache(t)},i.prototype._unbindVertexArrayObject=function(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))},i.prototype.bindBuffers=function(e,t,i){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i)),this._bindIndexBufferWithCache(t)},i.prototype.unbindInstanceAttributes=function(){for(var e,t=0,i=this._currentInstanceLocations.length;t1?"#version 300 es\n#define WEBGL2 \n":"",s=this._compileShader(e,"vertex",i,o),a=this._compileShader(t,"fragment",i,o),l=this._createShaderProgram(s,a,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),l},i.prototype._createShaderProgram=function(e,t,i,r){void 0===r&&(r=null);var n=i.createProgram();if(!n)throw new Error("Unable to create program");if(i.attachShader(n,e),i.attachShader(n,t),this.webGLVersion>1&&r){var o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(n,r),n.transformFeedback=o}if(i.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),!i.getProgramParameter(n,i.LINK_STATUS)){var s=i.getProgramInfoLog(n);if(s)throw new Error(s)}if(this.validateShaderPrograms){i.validateProgram(n);if(!i.getProgramParameter(n,i.VALIDATE_STATUS)){var s=i.getProgramInfoLog(n);if(s)throw new Error(s)}}return i.deleteShader(e),i.deleteShader(t),n},i.prototype.getUniforms=function(e,t){for(var i=new Array,r=0;r-1?p.substring(y).toLowerCase():""),x=null,T=0,E=i._TextureLoaders;Tc||t.height>c)return f._prepareWorkingCanvas(),!(!f._workingCanvas||!f._workingContext)&&(f._workingCanvas.width=i,f._workingCanvas.height=r,f._workingContext.drawImage(t,0,0,t.width,t.height,0,0,i,r),s.texImage2D(s.TEXTURE_2D,0,l,l,s.UNSIGNED_BYTE,f._workingCanvas),v.width=i,v.height=r,!1);var h=new e.InternalTexture(f,e.InternalTexture.DATASOURCE_TEMP);return f._bindTextureDirectly(s.TEXTURE_2D,h,!0),s.texImage2D(s.TEXTURE_2D,0,l,l,s.UNSIGNED_BYTE,t),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),f._rescaleTexture(h,v,o,l,(function(){f._releaseTexture(h),f._bindTextureDirectly(s.TEXTURE_2D,v,!0),n()})),!0}),s)};!_||g?c instanceof HTMLImageElement?C(c):e.Tools.LoadImage(p,C,M,o?o.database:null):"string"==typeof c||c instanceof ArrayBuffer||c instanceof Blob?e.Tools.LoadImage(c,C,M,o?o.database:null):C(c)}return v},i.prototype._rescaleTexture=function(t,r,n,o,s){var a=this,l=this.createRenderTargetTexture({width:r.width,height:r.height},{generateMipMaps:!1,type:i.TEXTURETYPE_UNSIGNED_INT,samplingMode:i.TEXTURE_BILINEAR_SAMPLINGMODE,generateDepthBuffer:!1,generateStencilBuffer:!1});this._rescalePostProcess||(this._rescalePostProcess=new e.PassPostProcess("rescale",1,null,i.TEXTURE_BILINEAR_SAMPLINGMODE,this,!1,i.TEXTURETYPE_UNSIGNED_INT)),this._rescalePostProcess.getEffect().executeWhenCompiled((function(){a._rescalePostProcess.onApply=function(e){e._bindTexture("textureSampler",t)};var e=n;e||(e=a.scenes[a.scenes.length-1]),e.postProcessManager.directRender([a._rescalePostProcess],l,!0),a._bindTextureDirectly(a._gl.TEXTURE_2D,r,!0),a._gl.copyTexImage2D(a._gl.TEXTURE_2D,0,o,0,0,r.width,r.height,0),a.unBindFramebuffer(l),a._releaseTexture(l),s&&s()}))},i.prototype.updateRawTexture=function(e,t,r,n,o,s){if(void 0===o&&(o=null),void 0===s&&(s=i.TEXTURETYPE_UNSIGNED_INT),e){var a=this._getRGBABufferInternalSizedFormat(s,r),l=this._getInternalFormat(r),c=this._getWebGLTextureType(s);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(e._bufferView=t,e.format=r,e.type=s,e.invertY=n,e._compression=o),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),o&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[o],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,e.width,e.height,0,l,c,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}},i.prototype.createRawTexture=function(t,r,n,o,s,a,l,c,h){void 0===c&&(c=null),void 0===h&&(h=i.TEXTURETYPE_UNSIGNED_INT);var u=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RAW);u.baseWidth=r,u.baseHeight=n,u.width=r,u.height=n,u.format=o,u.generateMipMaps=s,u.samplingMode=l,u.invertY=a,u._compression=c,u.type=h,this._doNotHandleContextLost||(u._bufferView=t),this.updateRawTexture(u,t,o,a,c,h),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);var d=this._getSamplingParameters(l,s);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},i.prototype._unpackFlipY=function(e){this._unpackFlipYCached!==e&&(this._unpackFlipYCached=e,this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0))},i.prototype._getUnpackAlignement=function(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}, -i.prototype.createDynamicTexture=function(t,i,r,n){var o=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_DYNAMIC);return o.baseWidth=t,o.baseHeight=i,r&&(t=this.needPOTTextures?e.Tools.GetExponentOfTwo(t,this._caps.maxTextureSize):t,i=this.needPOTTextures?e.Tools.GetExponentOfTwo(i,this._caps.maxTextureSize):i),o.width=t,o.height=i,o.isReady=!1,o.generateMipMaps=r,o.samplingMode=n,this.updateTextureSamplingMode(n,o),this._internalTexturesCache.push(o),o},i.prototype.updateTextureSamplingMode=function(e,t){var i=this._getSamplingParameters(e,t.generateMipMaps);t.isCube?(this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):t.is3D?(this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_3D,null)):(this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),t.samplingMode=e},i.prototype.updateDynamicTexture=function(e,t,i,r,n){if(void 0===r&&(r=!1),e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(i),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);var o=n?this._getInternalFormat(n):this._gl.RGBA;this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,o,this._gl.UNSIGNED_BYTE,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0}},i.prototype.updateVideoTexture=function(e,t,i){if(e&&!e._isDisabled){var r=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=document.createElement("canvas");var n=e._workingCanvas.getContext("2d");if(!n)throw new Error("Unable to get 2d context");e._workingContext=n,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),r||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}}},i.prototype.updateTextureComparisonFunction=function(t,r){if(1===this.webGLVersion)return void e.Tools.Error("WebGL 1 does not support texture comparison.");var n=this._gl;t.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,t,!0),0===r?(n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_FUNC,i.LEQUAL),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_MODE,n.NONE)):(n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_FUNC,r),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),0===r?(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_FUNC,i.LEQUAL),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_MODE,n.NONE)):(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_FUNC,r),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),t._comparisonFunction=r},i.prototype._setupDepthStencilTexture=function(e,t,r,n,o){var s=t.width||t,a=t.height||t;e.baseWidth=s,e.baseHeight=a,e.width=s,e.height=a,e.isReady=!0,e.samples=1,e.generateMipMaps=!1,e._generateDepthBuffer=!0,e._generateStencilBuffer=r,e.samplingMode=n?i.TEXTURE_BILINEAR_SAMPLINGMODE:i.TEXTURE_NEAREST_SAMPLINGMODE,e.type=i.TEXTURETYPE_UNSIGNED_INT,e._comparisonFunction=o;var l=this._gl,c=e.isCube?l.TEXTURE_CUBE_MAP:l.TEXTURE_2D,h=this._getSamplingParameters(e.samplingMode,!1);l.texParameteri(c,l.TEXTURE_MAG_FILTER,h.mag),l.texParameteri(c,l.TEXTURE_MIN_FILTER,h.min),l.texParameteri(c,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(c,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),0===o?(l.texParameteri(c,l.TEXTURE_COMPARE_FUNC,i.LEQUAL),l.texParameteri(c,l.TEXTURE_COMPARE_MODE,l.NONE)):(l.texParameteri(c,l.TEXTURE_COMPARE_FUNC,o),l.texParameteri(c,l.TEXTURE_COMPARE_MODE,l.COMPARE_REF_TO_TEXTURE))},i.prototype.createDepthStencilTexture=function(e,t){if(t.isCube){var i=e.width||e;return this._createDepthStencilCubeTexture(i,t)}return this._createDepthStencilTexture(e,t)},i.prototype._createDepthStencilTexture=function(t,i){var r=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_DEPTHTEXTURE);if(!this._caps.depthTextureExtension)return e.Tools.Error("Depth texture is not supported by your browser or hardware."),r;var n=s({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},i),o=this._gl;return this._bindTextureDirectly(o.TEXTURE_2D,r,!0),this._setupDepthStencilTexture(r,t,n.generateStencil,n.bilinearFiltering,n.comparisonFunction),this.webGLVersion>1?n.generateStencil?o.texImage2D(o.TEXTURE_2D,0,o.DEPTH24_STENCIL8,r.width,r.height,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_COMPONENT24,r.width,r.height,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null):n.generateStencil?o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_STENCIL,r.width,r.height,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_COMPONENT,r.width,r.height,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null),this._bindTextureDirectly(o.TEXTURE_2D,null),r},i.prototype._createDepthStencilCubeTexture=function(t,i){var r=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_UNKNOWN);if(r.isCube=!0,1===this.webGLVersion)return e.Tools.Error("Depth cube texture is not supported by WebGL 1."),r;var n=s({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},i),o=this._gl;this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,r,!0),this._setupDepthStencilTexture(r,t,n.generateStencil,n.bilinearFiltering,n.comparisonFunction);for(var a=0;a<6;a++)n.generateStencil?o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,o.DEPTH24_STENCIL8,t,t,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,o.DEPTH_COMPONENT24,t,t,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null);return this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null),r},i.prototype.setFrameBufferDepthStencilTexture=function(e){var t=e.getInternalTexture();if(t&&t._framebuffer&&e.depthStencilTexture){var i=this._gl,r=e.depthStencilTexture;this.bindUnboundFramebuffer(t._framebuffer),r.isCube?r._generateStencilBuffer?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_CUBE_MAP_POSITIVE_X,r._webGLTexture,0):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_CUBE_MAP_POSITIVE_X,r._webGLTexture,0):r._generateStencilBuffer?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_2D,r._webGLTexture,0):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,r._webGLTexture,0),this.bindUnboundFramebuffer(null)}},i.prototype.createRenderTargetTexture=function(t,n){var o=new r;void 0!==n&&"object"==typeof n?(o.generateMipMaps=n.generateMipMaps,o.generateDepthBuffer=void 0===n.generateDepthBuffer||n.generateDepthBuffer,o.generateStencilBuffer=o.generateDepthBuffer&&n.generateStencilBuffer,o.type=void 0===n.type?i.TEXTURETYPE_UNSIGNED_INT:n.type,o.samplingMode=void 0===n.samplingMode?i.TEXTURE_TRILINEAR_SAMPLINGMODE:n.samplingMode,o.format=void 0===n.format?i.TEXTUREFORMAT_RGBA:n.format):(o.generateMipMaps=n,o.generateDepthBuffer=!0,o.generateStencilBuffer=!1,o.type=i.TEXTURETYPE_UNSIGNED_INT,o.samplingMode=i.TEXTURE_TRILINEAR_SAMPLINGMODE,o.format=i.TEXTUREFORMAT_RGBA),o.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering?o.type!==i.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering||(o.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE):o.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE;var s=this._gl,a=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RENDERTARGET);this._bindTextureDirectly(s.TEXTURE_2D,a,!0);var l=t.width||t,c=t.height||t,h=this._getSamplingParameters(o.samplingMode,!!o.generateMipMaps);o.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloat||(o.type=i.TEXTURETYPE_UNSIGNED_INT,e.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,h.mag),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,h.min),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(o.type,o.format),l,c,0,this._getInternalFormat(o.format),this._getWebGLTextureType(o.type),null);var u=this._currentFramebuffer,d=s.createFramebuffer();return this.bindUnboundFramebuffer(d),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,a._webGLTexture,0),a._depthStencilBuffer=this._setupFramebufferDepthAttachments(!!o.generateStencilBuffer,o.generateDepthBuffer,l,c),o.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),this.bindUnboundFramebuffer(u),a._framebuffer=d,a.baseWidth=l,a.baseHeight=c,a.width=l,a.height=c,a.isReady=!0,a.samples=1,a.generateMipMaps=!!o.generateMipMaps,a.samplingMode=o.samplingMode,a.type=o.type,a._generateDepthBuffer=o.generateDepthBuffer,a._generateStencilBuffer=!!o.generateStencilBuffer,this._internalTexturesCache.push(a),a},i.prototype.createMultipleRenderTarget=function(t,r){var n=!1,o=!0,s=!1,a=!1,l=1,c=i.TEXTURETYPE_UNSIGNED_INT,h=i.TEXTURE_TRILINEAR_SAMPLINGMODE,u=new Array,d=new Array;void 0!==r&&(n=void 0!==r.generateMipMaps&&r.generateMipMaps,o=void 0===r.generateDepthBuffer||r.generateDepthBuffer,s=void 0!==r.generateStencilBuffer&&r.generateStencilBuffer,a=void 0!==r.generateDepthTexture&&r.generateDepthTexture,l=r.textureCount||1,r.types&&(u=r.types),r.samplingModes&&(d=r.samplingModes));var f=this._gl,p=f.createFramebuffer();this.bindUnboundFramebuffer(p);for(var _=t.width||t,m=t.height||t,g=[],v=[],y=this._setupFramebufferDepthAttachments(s,o,_,m),b=0;b1?"COLOR_ATTACHMENT"+b:"COLOR_ATTACHMENT"+b+"_WEBGL"];g.push(P),v.push(A),f.activeTexture(f["TEXTURE"+b]),f.bindTexture(f.TEXTURE_2D,P._webGLTexture),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MAG_FILTER,E.mag),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MIN_FILTER,E.min),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),f.texImage2D(f.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(T),_,m,0,f.RGBA,this._getWebGLTextureType(T),null),f.framebufferTexture2D(f.DRAW_FRAMEBUFFER,A,f.TEXTURE_2D,P._webGLTexture,0),n&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(f.TEXTURE_2D,null),P._framebuffer=p,P._depthStencilBuffer=y,P.baseWidth=_,P.baseHeight=m,P.width=_,P.height=m,P.isReady=!0,P.samples=1,P.generateMipMaps=n,P.samplingMode=x,P.type=T,P._generateDepthBuffer=o,P._generateStencilBuffer=s,P._attachments=v,this._internalTexturesCache.push(P)}if(a&&this._caps.depthTextureExtension){var M=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_MULTIRENDERTARGET);f.activeTexture(f.TEXTURE0),f.bindTexture(f.TEXTURE_2D,M._webGLTexture),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MAG_FILTER,f.NEAREST),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MIN_FILTER,f.NEAREST),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),f.texImage2D(f.TEXTURE_2D,0,this.webGLVersion<2?f.DEPTH_COMPONENT:f.DEPTH_COMPONENT16,_,m,0,f.DEPTH_COMPONENT,f.UNSIGNED_SHORT,null),f.framebufferTexture2D(f.FRAMEBUFFER,f.DEPTH_ATTACHMENT,f.TEXTURE_2D,M._webGLTexture,0),M._framebuffer=p,M.baseWidth=_,M.baseHeight=m,M.width=_,M.height=m,M.isReady=!0,M.samples=1,M.generateMipMaps=n,M.samplingMode=f.NEAREST,M._generateDepthBuffer=o,M._generateStencilBuffer=s,g.push(M),this._internalTexturesCache.push(M)}return f.drawBuffers(v),f.bindRenderbuffer(f.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),this.resetTextureCache(),g},i.prototype._setupFramebufferDepthAttachments=function(e,t,i,r,n){void 0===n&&(n=1);var o=null,s=this._gl;return e?(o=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,o),n>1?s.renderbufferStorageMultisample(s.RENDERBUFFER,n,s.DEPTH24_STENCIL8,i,r):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,i,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,o)):t&&(o=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,o),n>1?s.renderbufferStorageMultisample(s.RENDERBUFFER,n,s.DEPTH_COMPONENT16,i,r):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT16,i,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,o)),o},i.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e)return 1;if(e.samples===t)return t;var i=this._gl;if(t=Math.min(t,i.getParameter(i.MAX_SAMPLES)),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),e._MSAARenderBuffer&&(i.deleteRenderbuffer(e._MSAARenderBuffer),e._MSAARenderBuffer=null),t>1){var r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this.bindUnboundFramebuffer(e._MSAAFramebuffer);var n=i.createRenderbuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorageMultisample(i.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(e.type),e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,n),e._MSAARenderBuffer=n}else this.bindUnboundFramebuffer(e._framebuffer);return e.samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.width,e.height,t),i.bindRenderbuffer(i.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),t},i.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||0==e.length)return 1;if(e[0].samples===t)return t;var i=this._gl;t=Math.min(t,i.getParameter(i.MAX_SAMPLES)),e[0]._depthStencilBuffer&&(i.deleteRenderbuffer(e[0]._depthStencilBuffer),e[0]._depthStencilBuffer=null),e[0]._MSAAFramebuffer&&(i.deleteFramebuffer(e[0]._MSAAFramebuffer),e[0]._MSAAFramebuffer=null);for(var r=0;r1){var n=i.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");this.bindUnboundFramebuffer(n);for(var o=this._setupFramebufferDepthAttachments(e[0]._generateStencilBuffer,e[0]._generateDepthBuffer,e[0].width,e[0].height,t),s=[],r=0;r1?"COLOR_ATTACHMENT"+r:"COLOR_ATTACHMENT"+r+"_WEBGL"],c=i.createRenderbuffer();if(!c)throw new Error("Unable to create multi sampled framebuffer");i.bindRenderbuffer(i.RENDERBUFFER,c),i.renderbufferStorageMultisample(i.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(a.type),a.width,a.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,l,i.RENDERBUFFER,c),a._MSAAFramebuffer=n,a._MSAARenderBuffer=c,a.samples=t,a._depthStencilBuffer=o,i.bindRenderbuffer(i.RENDERBUFFER,null),s.push(l)}i.drawBuffers(s)}else this.bindUnboundFramebuffer(e[0]._framebuffer);return this.bindUnboundFramebuffer(null),t},i.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,r,n,o,s){void 0===o&&(o=0),void 0===s&&(s=0);var a=this._gl,l=a.TEXTURE_2D;e.isCube&&(l=a.TEXTURE_CUBE_MAP_POSITIVE_X+o),this._gl.compressedTexImage2D(l,s,t,i,r,0,n)},i.prototype._uploadDataToTextureDirectly=function(t,i,r,n){void 0===r&&(r=0),void 0===n&&(n=0);var o=this._gl,s=this._getWebGLTextureType(t.type),a=this._getInternalFormat(t.format),l=this._getRGBABufferInternalSizedFormat(t.type,a);this._unpackFlipY(t.invertY);var c=o.TEXTURE_2D;t.isCube&&(c=o.TEXTURE_CUBE_MAP_POSITIVE_X+r);var h=Math.round(e.Scalar.Log2(t.width)),u=Math.round(e.Scalar.Log2(t.height)),d=Math.pow(2,Math.max(h-n,0)),f=Math.pow(2,Math.max(u-n,0));o.texImage2D(c,n,l,d,f,0,a,s,i)},i.prototype._uploadArrayBufferViewToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0);var n=this._gl,o=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(o,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(o,null,!0)},i.prototype._uploadImageToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0);var n=this._gl,o=this._getWebGLTextureType(e.type),s=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,s),l=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);var c=n.TEXTURE_2D;e.isCube&&(c=n.TEXTURE_CUBE_MAP_POSITIVE_X+i),n.texImage2D(c,r,a,s,o,t),this._bindTextureDirectly(l,null,!0)},i.prototype.createRenderTargetCubeTexture=function(t,r){var n=s({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:i.TEXTURETYPE_UNSIGNED_INT,samplingMode:i.TEXTURE_TRILINEAR_SAMPLINGMODE,format:i.TEXTUREFORMAT_RGBA},r);n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,n.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering?n.type!==i.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering||(n.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE):n.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE;var o=this._gl,a=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RENDERTARGET);this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,a,!0);var l=this._getSamplingParameters(n.samplingMode,n.generateMipMaps);n.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloat||(n.type=i.TEXTURETYPE_UNSIGNED_INT,e.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,l.mag),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,l.min),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE);for(var c=0;c<6;c++)o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+c,0,this._getRGBABufferInternalSizedFormat(n.type,n.format),t,t,0,this._getInternalFormat(n.format),this._getWebGLTextureType(n.type),null);var h=o.createFramebuffer();return this.bindUnboundFramebuffer(h),a._depthStencilBuffer=this._setupFramebufferDepthAttachments(n.generateStencilBuffer,n.generateDepthBuffer,t,t),n.generateMipMaps&&o.generateMipmap(o.TEXTURE_CUBE_MAP),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null),o.bindRenderbuffer(o.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),a._framebuffer=h,a.width=t,a.height=t,a.isReady=!0,a.isCube=!0,a.samples=1,a.generateMipMaps=n.generateMipMaps,a.samplingMode=n.samplingMode,a.type=n.type,a._generateDepthBuffer=n.generateDepthBuffer,a._generateStencilBuffer=n.generateStencilBuffer,this._internalTexturesCache.push(a),a},i.prototype.createPrefilteredCubeTexture=function(t,i,r,n,o,s,a,l,c){var h=this;void 0===o&&(o=null),void 0===s&&(s=null),void 0===l&&(l=null),void 0===c&&(c=!0);var u=function(t){if(!t)return void(o&&o(null));var s=t.texture;if(c?t.info.sphericalPolynomial&&(s._sphericalPolynomial=t.info.sphericalPolynomial):s._sphericalPolynomial=new e.SphericalPolynomial,s._dataSource=e.InternalTexture.DATASOURCE_CUBEPREFILTERED,h._caps.textureLOD)return void(o&&o(s));var a=h._gl,l=t.width;if(l){for(var u=[],d=0;d<3;d++){var f=d/2,p=1-f,_=n,m=e.Scalar.Log2(l)*r+n,g=_+(m-_)*p,v=Math.round(Math.min(Math.max(g,0),m)),y=new e.InternalTexture(h,e.InternalTexture.DATASOURCE_TEMP);if(y.type=s.type,y.format=s.format,y.width=Math.pow(2,Math.max(e.Scalar.Log2(l)-v,0)),y.height=y.width,y.isCube=!0,h._bindTextureDirectly(a.TEXTURE_CUBE_MAP,y,!0),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),t.isDDS){var b=t.info,x=t.data;h._unpackFlipY(b.isCompressed),e.DDSTools.UploadDDSLevels(h,y,x,b,!0,6,v)}else e.Tools.Warn("DDS is the only prefiltered cube map supported so far.");h._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);var T=new e.BaseTexture(i);T.isCube=!0,T._texture=y,y.isReady=!0,u.push(T)}s._lodTextureHigh=u[2],s._lodTextureMid=u[1],s._lodTextureLow=u[0],o&&o(s)}};return this.createCubeTexture(t,i,null,!1,u,s,a,l,c,r,n)},i.prototype.createCubeTexture=function(t,r,n,o,s,a,l,c,h,u,d,f){var p=this;void 0===s&&(s=null),void 0===a&&(a=null),void 0===c&&(c=null),void 0===h&&(h=!1),void 0===u&&(u=0),void 0===d&&(d=0),void 0===f&&(f=null);var _=this._gl,m=f||new e.InternalTexture(this,e.InternalTexture.DATASOURCE_CUBE);m.isCube=!0,m.url=t,m.generateMipMaps=!o,m._lodGenerationScale=u,m._lodGenerationOffset=d,this._doNotHandleContextLost||(m._extension=c,m._files=n);for(var g=t.lastIndexOf("."),v=c||(g>-1?t.substring(g).toLowerCase():""),y=null,b=0,x=i._TextureLoaders;b>v,b=0;b<6;b++){var x=g[v][b];m&&(x=f._convertRGBtoRGBATextureData(x,y,y,o)),p.texImage2D(b,v,u,y,y,0,h,s,x)}f._bindTextureDirectly(p.TEXTURE_CUBE_MAP,null)}else f.updateRawCubeTexture(_,r,n,o,d);_.isReady=!0,t._removePendingData(_),c&&c()}};return this._loadFile(e,(function(e){g(e)}),void 0,t.database,!0,m),_},i.prototype.updateRawTexture3D=function(e,t,r,n,o,s){void 0===o&&(o=null),void 0===s&&(s=i.TEXTURETYPE_UNSIGNED_INT);var a=this._getWebGLTextureType(s),l=this._getInternalFormat(r),c=this._getRGBABufferInternalSizedFormat(s,r);this._bindTextureDirectly(this._gl.TEXTURE_3D,e,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(e._bufferView=t,e.format=r,e.invertY=n,e._compression=o),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),o&&t?this._gl.compressedTexImage3D(this._gl.TEXTURE_3D,0,this.getCaps().s3tc[o],e.width,e.height,e.depth,0,t):this._gl.texImage3D(this._gl.TEXTURE_3D,0,c,e.width,e.height,e.depth,0,l,a,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_3D),this._bindTextureDirectly(this._gl.TEXTURE_3D,null),e.isReady=!0},i.prototype.createRawTexture3D=function(t,r,n,o,s,a,l,c,h,u){void 0===h&&(h=null),void 0===u&&(u=i.TEXTURETYPE_UNSIGNED_INT);var d=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RAW3D);d.baseWidth=r,d.baseHeight=n,d.baseDepth=o,d.width=r,d.height=n,d.depth=o,d.format=s,d.type=u,d.generateMipMaps=a,d.samplingMode=c,d.is3D=!0,this._doNotHandleContextLost||(d._bufferView=t),this.updateRawTexture3D(d,t,s,l,h,u),this._bindTextureDirectly(this._gl.TEXTURE_3D,d,!0);var f=this._getSamplingParameters(c,a);return this._gl.texParameteri(this._gl.TEXTURE_3D,this._gl.TEXTURE_MAG_FILTER,f.mag),this._gl.texParameteri(this._gl.TEXTURE_3D,this._gl.TEXTURE_MIN_FILTER,f.min),a&&this._gl.generateMipmap(this._gl.TEXTURE_3D),this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._internalTexturesCache.push(d),d},i.prototype._prepareWebGLTextureContinuation=function(e,t,i,r,n){var o=this._gl;if(o){var s=this._getSamplingParameters(n,!i);o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,s.mag),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,s.min),i||r||o.generateMipmap(o.TEXTURE_2D),this._bindTextureDirectly(o.TEXTURE_2D,null),t&&t._removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}},i.prototype._prepareWebGLTexture=function(t,r,n,o,s,a,l,c,h){var u=this;void 0===h&&(h=i.TEXTURE_TRILINEAR_SAMPLINGMODE);var d=this.getCaps().maxTextureSize,f=Math.min(d,this.needPOTTextures?e.Tools.GetExponentOfTwo(n,d):n),p=Math.min(d,this.needPOTTextures?e.Tools.GetExponentOfTwo(o,d):o),_=this._gl;if(_){if(!t._webGLTexture)return void(r&&r._removePendingData(t));this._bindTextureDirectly(_.TEXTURE_2D,t,!0),this._unpackFlipY(void 0===s||!!s),t.baseWidth=n,t.baseHeight=o,t.width=f,t.height=p,t.isReady=!0,c(f,p,(function(){u._prepareWebGLTextureContinuation(t,r,a,l,h)}))||this._prepareWebGLTextureContinuation(t,r,a,l,h)}},i.prototype._convertRGBtoRGBATextureData=function(e,t,r,n){var o;o=n===i.TEXTURETYPE_FLOAT?new Float32Array(t*r*4):new Uint32Array(t*r*4);for(var s=0;s-1?t._designatedSlot:this._nextFreeTextureSlots.length?this._nextFreeTextureSlots[0]:(this._textureCollisions.addCount(1,!1),this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next));return e},i.prototype._linkTrackers=function(e,t){e.next=t,t.previous=e},i.prototype._removeDesignatedSlot=function(e){var t=e._designatedSlot;return-1===t?-1:(e._designatedSlot=-1,this.disableTextureBindingOptimization?-1:(this._linkTrackers(e.previous,e.next),this._boundTexturesCache[t]=null,this._nextFreeTextureSlots.push(t),t))},i.prototype._activateCurrentTexture=function(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)},i.prototype._bindTextureDirectly=function(e,t,i,r){void 0===i&&(i=!1),void 0===r&&(r=!1);var n=!1;i&&t&&t._designatedSlot>-1&&(this._activeChannel=t._designatedSlot);var o=this._boundTexturesCache[this._activeChannel],s=t&&t._initialSlot>-1;if(o!==t||r){if(o&&this._removeDesignatedSlot(o),this._activateCurrentTexture(),this._gl.bindTexture(e,t?t._webGLTexture:null),this._boundTexturesCache[this._activeChannel]=t,t){if(!this.disableTextureBindingOptimization){var a=this._nextFreeTextureSlots.indexOf(this._activeChannel);a>-1&&this._nextFreeTextureSlots.splice(a,1),this._linkTrackers(this._lastBoundInternalTextureTracker.previous,t),this._linkTrackers(t,this._lastBoundInternalTextureTracker)}t._designatedSlot=this._activeChannel}}else i&&(n=!0,this._activateCurrentTexture());return s&&!i&&this._bindSamplerUniformToChannel(t._initialSlot,this._activeChannel),n},i.prototype._bindTexture=function(e,t){e<0||(t&&(e=this._getCorrectTextureChannel(e,t)),this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,t))},i.prototype.setTextureFromPostProcess=function(e,t){this._bindTexture(e,t?t._textures.data[t._currentRenderTextureInd]:null)},i.prototype.setTextureFromPostProcessOutput=function(e,t){this._bindTexture(e,t?t._outputTexture:null)},i.prototype.unbindAllTextures=function(){for(var e=0;e1&&this._bindTextureDirectly(this._gl.TEXTURE_3D,null)},i.prototype.setTexture=function(e,t,i){e<0||(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))},i.prototype.setDepthStencilTexture=function(e,t,i){e<0||(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0):this._setTexture(e,null))},i.prototype._bindSamplerUniformToChannel=function(e,t){var i=this._boundUniforms[e];i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)},i.prototype._getTextureWrapMode=function(e){switch(e){case i.TEXTURE_WRAP_ADDRESSMODE:return this._gl.REPEAT;case i.TEXTURE_CLAMP_ADDRESSMODE:return this._gl.CLAMP_TO_EDGE;case i.TEXTURE_MIRROR_ADDRESSMODE:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT},i.prototype._setTexture=function(e,t,r,n){if(void 0===r&&(r=!1),void 0===n&&(n=!1),!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&this._bindTextureDirectly(this._gl.TEXTURE_3D,null)),!1;if(t.video)this._activeChannel=e,t.update();else if(t.delayLoadState===i.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;var o;o=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:this.emptyTexture,r||(e=this._getCorrectTextureChannel(e,o));var s=!0;if(this._boundTexturesCache[e]===o&&(this._moveBoundTextureOnTop(o),r||this._bindSamplerUniformToChannel(o._initialSlot,e),s=!1),this._activeChannel=e,o&&o.is3D)s&&this._bindTextureDirectly(this._gl.TEXTURE_3D,o,r),o&&o._cachedWrapU!==t.wrapU&&(o._cachedWrapU=t.wrapU,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),o)),o&&o._cachedWrapV!==t.wrapV&&(o._cachedWrapV=t.wrapV,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),o)),o&&o._cachedWrapR!==t.wrapR&&(o._cachedWrapR=t.wrapR,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),o)),this._setAnisotropicLevel(this._gl.TEXTURE_3D,t);else if(o&&o.isCube){if(s&&this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,o,r),o._cachedCoordinatesMode!==t.coordinatesMode){o._cachedCoordinatesMode=t.coordinatesMode;var a=t.coordinatesMode!==i.TEXTURE_CUBIC_MODE&&t.coordinatesMode!==i.TEXTURE_SKYBOX_MODE?this._gl.REPEAT:this._gl.CLAMP_TO_EDGE;this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_S,a,o),this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_T,a)}this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP,t)}else s&&this._bindTextureDirectly(this._gl.TEXTURE_2D,o,r),o&&o._cachedWrapU!==t.wrapU&&(o._cachedWrapU=t.wrapU,this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),o)),o&&o._cachedWrapV!==t.wrapV&&(o._cachedWrapV=t.wrapV,this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),o)),this._setAnisotropicLevel(this._gl.TEXTURE_2D,t);return!0},i.prototype.setTextureArray=function(e,t,i){if(!(e<0)&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(var r=0;r=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||(this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1)},i.prototype.releaseEffects=function(){for(var e in this._compiledEffects)this._deleteProgram(this._compiledEffects[e]._program);this._compiledEffects={}},i.prototype.dispose=function(){for(this.hideLoadingUI(),this.stopRenderLoop();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();i.audioEngine&&i.audioEngine.dispose(),this.releaseEffects(),this.unbindAllAttributes(),this._boundUniforms=[],this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.disableVR(),e.Tools.IsWindowObjectExist()&&(window.removeEventListener("blur",this._onBlur),window.removeEventListener("focus",this._onFocus),window.removeEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted),window.removeEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange),this._onVrDisplayConnect&&(window.removeEventListener("vrdisplayconnect",this._onVrDisplayConnect),this._onVrDisplayDisconnect&&window.removeEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),this._onVrDisplayPresentChange&&window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),this._onVrDisplayConnect=null,this._onVrDisplayDisconnect=null));var t=i.Instances.indexOf(this);t>=0&&i.Instances.splice(t,1),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers=[],this._renderingCanvas=null,this._currentProgram=null,this._bindedRenderFunction=null,this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear(),e.Effect.ResetCache();for(var r=0,n=this._activeRequests;r-1?o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_CUBE_MAP_POSITIVE_X+r,e._webGLTexture,n):o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,e._webGLTexture,n);var a,l=void 0!==e.type?this._getWebGLTextureType(e.type):o.UNSIGNED_BYTE;switch(l){case o.UNSIGNED_BYTE:a=new Uint8Array(4*t*i),l=o.UNSIGNED_BYTE;break;default:a=new Float32Array(4*t*i),l=o.FLOAT}return o.readPixels(0,0,t,i,o.RGBA,l,a),o.bindFramebuffer(o.FRAMEBUFFER,this._currentFramebuffer),a},i.prototype._canRenderToFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(i.TEXTURETYPE_FLOAT)},i.prototype._canRenderToHalfFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(i.TEXTURETYPE_HALF_FLOAT)},i.prototype._canRenderToFramebuffer=function(e){for(var t=this._gl;t.getError()!==t.NO_ERROR;);var i=!0,r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);var n=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&o===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);var s=t.RGBA,a=t.UNSIGNED_BYTE,l=new Uint8Array(4);t.readPixels(0,0,1,1,s,a,l),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(n),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i},i.prototype._getWebGLTextureType=function(e){return e===i.TEXTURETYPE_FLOAT?this._gl.FLOAT:e===i.TEXTURETYPE_HALF_FLOAT?this._gl.HALF_FLOAT_OES:this._gl.UNSIGNED_BYTE},i.prototype._getInternalFormat=function(e){var t=this._gl.RGBA;switch(e){case i.TEXTUREFORMAT_ALPHA:t=this._gl.ALPHA;break;case i.TEXTUREFORMAT_LUMINANCE:t=this._gl.LUMINANCE;break;case i.TEXTUREFORMAT_LUMINANCE_ALPHA:t=this._gl.LUMINANCE_ALPHA;break;case i.TEXTUREFORMAT_RGB:t=this._gl.RGB;break;case i.TEXTUREFORMAT_RGBA:t=this._gl.RGBA;break;case i.TEXTUREFORMAT_R:t=this._gl.RED;break;case i.TEXTUREFORMAT_RG:t=this._gl.RG}return t},i.prototype._getRGBABufferInternalSizedFormat=function(e,t){if(1===this._webGLVersion){if(void 0!==t)switch(t){case i.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case i.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA}return this._gl.RGBA}if(e===i.TEXTURETYPE_FLOAT){if(void 0!==t)switch(t){case i.TEXTUREFORMAT_R:return this._gl.R32F;case i.TEXTUREFORMAT_RG:return this._gl.RG32F;case i.TEXTUREFORMAT_RGB:return this._gl.RGB32F}return this._gl.RGBA32F}if(e===i.TEXTURETYPE_HALF_FLOAT){if(t)switch(t){case i.TEXTUREFORMAT_R:return this._gl.R16F;case i.TEXTUREFORMAT_RG:return this._gl.RG16F;case i.TEXTUREFORMAT_RGB:return this._gl.RGB16F}return this._gl.RGBA16F}if(void 0!==t)switch(t){case i.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case i.TEXTUREFORMAT_RGB:return this._gl.RGB;case i.TEXTUREFORMAT_R:return this._gl.R8;case i.TEXTUREFORMAT_RG:return this._gl.RG8;case i.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA}return this._gl.RGBA},i.prototype._getRGBAMultiSampleBufferFormat=function(e){return e===i.TEXTURETYPE_FLOAT?this._gl.RGBA32F:e===i.TEXTURETYPE_HALF_FLOAT?this._gl.RGBA16F:this._gl.RGBA8},i.prototype._loadFile=function(t,i,r,n,o,s){var a=this,l=e.Tools.LoadFile(t,i,r,n,o,s);return this._activeRequests.push(l),l.onCompleteObservable.add((function(e){a._activeRequests.splice(a._activeRequests.indexOf(e),1)})),l},i.prototype._loadFileAsync=function(e,t,i){var r=this;return new Promise(function(n,o){r._loadFile(e,(function(e){n(e)}),void 0,t,i,(function(e,t){o(t)}))})},i.prototype._partialLoadFile=function(e,t,i,r,n,o){void 0===o&&(o=null);var s=function(e){i[t]=e,6===++i._internalCount&&n(i)},a=function(e,t){o&&e&&o(e.status+" "+e.statusText,t)};this._loadFile(e,s,void 0,void 0,!0,a)},i.prototype._cascadeLoadFiles=function(e,t,i,r){void 0===r&&(r=null);var n=[];n._internalCount=0;for(var o=0;o<6;o++)this._partialLoadFile(i[o],o,n,e,t,r)},i.isSupported=function(){try{var e=document.createElement("canvas");return null!=(e.getContext("webgl")||e.getContext("experimental-webgl"))&&!!window.WebGLRenderingContext}catch(e){return!1}},i.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Macintosh",capture:null,captureConstraint:null,targets:["textureBindingOptimization"]},{key:"iPhone",capture:null,captureConstraint:null,targets:["textureBindingOptimization"]},{key:"iPad",capture:null,captureConstraint:null,targets:["textureBindingOptimization"]}],i.Instances=new Array,i._TextureLoaders=[],i.ALPHA_DISABLE=0,i.ALPHA_ADD=1,i.ALPHA_COMBINE=2,i.ALPHA_SUBTRACT=3,i.ALPHA_MULTIPLY=4,i.ALPHA_MAXIMIZED=5,i.ALPHA_ONEONE=6,i.ALPHA_PREMULTIPLIED=7,i.ALPHA_PREMULTIPLIED_PORTERDUFF=8,i.ALPHA_INTERPOLATE=9,i.ALPHA_SCREENMODE=10,i.DELAYLOADSTATE_NONE=0,i.DELAYLOADSTATE_LOADED=1,i.DELAYLOADSTATE_LOADING=2,i.DELAYLOADSTATE_NOTLOADED=4,i.NEVER=512,i.ALWAYS=519,i.LESS=513,i.EQUAL=514,i.LEQUAL=515,i.GREATER=516,i.GEQUAL=518,i.NOTEQUAL=517,i.KEEP=7680,i.REPLACE=7681,i.INCR=7682,i.DECR=7683,i.INVERT=5386,i.INCR_WRAP=34055,i.DECR_WRAP=34056,i.TEXTURE_CLAMP_ADDRESSMODE=0,i.TEXTURE_WRAP_ADDRESSMODE=1,i.TEXTURE_MIRROR_ADDRESSMODE=2,i.TEXTUREFORMAT_ALPHA=0,i.TEXTUREFORMAT_LUMINANCE=1,i.TEXTUREFORMAT_LUMINANCE_ALPHA=2,i.TEXTUREFORMAT_RGB=4,i.TEXTUREFORMAT_RGBA=5,i.TEXTUREFORMAT_R=6,i.TEXTUREFORMAT_RG=7,i.TEXTURETYPE_UNSIGNED_INT=0,i.TEXTURETYPE_FLOAT=1,i.TEXTURETYPE_HALF_FLOAT=2,i.TEXTURE_NEAREST_SAMPLINGMODE=1,i.TEXTURE_BILINEAR_SAMPLINGMODE=2,i.TEXTURE_TRILINEAR_SAMPLINGMODE=3,i.TEXTURE_NEAREST_NEAREST_MIPLINEAR=1,i.TEXTURE_LINEAR_LINEAR_MIPNEAREST=2,i.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,i.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,i.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,i.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,i.TEXTURE_NEAREST_LINEAR=7,i.TEXTURE_NEAREST_NEAREST=8,i.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,i.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,i.TEXTURE_LINEAR_LINEAR=11,i.TEXTURE_LINEAR_NEAREST=12,i.TEXTURE_EXPLICIT_MODE=0,i.TEXTURE_SPHERICAL_MODE=1,i.TEXTURE_PLANAR_MODE=2,i.TEXTURE_CUBIC_MODE=3,i.TEXTURE_PROJECTION_MODE=4,i.TEXTURE_SKYBOX_MODE=5,i.TEXTURE_INVCUBIC_MODE=6,i.TEXTURE_EQUIRECTANGULAR_MODE=7,i.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,i.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,i.SCALEMODE_FLOOR=1,i.SCALEMODE_NEAREST=2,i.SCALEMODE_CEILING=3,i.CollisionsEpsilon=.001,i.CodeRepository="src/",i.ShadersRepository="src/Shaders/",i})();e.Engine=a})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i){void 0===i&&(i=null),this.state="",this.metadata=null,this.doNotSerialize=!1,this._isDisposed=!1,this.animations=new Array,this._ranges={},this._isEnabled=!0,this._isReady=!0,this._currentRenderId=-1,this._parentRenderId=-1,this._childRenderId=-1,this._animationPropertiesOverride=null,this.onDisposeObservable=new e.Observable,this._behaviors=new Array,this.name=t,this.id=t,this._scene=i||e.Engine.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}return t.AddNodeConstructor=function(e,t){this._NodeConstructors[e]=t},t.Construct=function(e,t,i,r){var n=this._NodeConstructors[e];return n?n(t,i,r):null},t.prototype.isDisposed=function(){return this._isDisposed},Object.defineProperty(t.prototype,"parent",{get:function(){return this._parentNode},set:function(e){if(this._parentNode!==e){if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){var t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1)}this._parentNode=e,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this))}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"Node"},Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEngine=function(){return this._scene.getEngine()},t.prototype.addBehavior=function(e){var t=this;return-1!==this._behaviors.indexOf(e)?this:(e.init(),this._scene.isLoading?this._scene.onDataLoadedObservable.addOnce((function(){e.attach(t)})):e.attach(this),this._behaviors.push(e),this)},t.prototype.removeBehavior=function(e){var t=this._behaviors.indexOf(e);return-1===t?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)},Object.defineProperty(t.prototype,"behaviors",{get:function(){return this._behaviors},enumerable:!0,configurable:!0}),t.prototype.getBehaviorByName=function(e){for(var t=0,i=this._behaviors;tthis.maximumWorld.x&&(this.maximumWorld.x=r.x),r.y>this.maximumWorld.y&&(this.maximumWorld.y=r.y),r.z>this.maximumWorld.z&&(this.maximumWorld.z=r.z)}this.maximumWorld.subtractToRef(this.minimumWorld,this.extendSizeWorld),this.extendSizeWorld.scaleInPlace(.5),this.maximumWorld.addToRef(this.minimumWorld,this.centerWorld),this.centerWorld.scaleInPlace(.5),e.Vector3.FromFloatArrayToRef(t.m,0,this.directions[0]),e.Vector3.FromFloatArrayToRef(t.m,4,this.directions[1]),e.Vector3.FromFloatArrayToRef(t.m,8,this.directions[2]),this._worldMatrix=t},t.prototype.isInFrustum=function(e){return t.IsInFrustum(this.vectorsWorld,e)},t.prototype.isCompletelyInFrustum=function(e){return t.IsCompletelyInFrustum(this.vectorsWorld,e)},t.prototype.intersectsPoint=function(t){var i=-e.Epsilon;return!(this.maximumWorld.x-t.xt.x-this.minimumWorld.x)&&(!(this.maximumWorld.y-t.yt.y-this.minimumWorld.y)&&!(this.maximumWorld.z-t.zt.z-this.minimumWorld.z))},t.prototype.intersectsSphere=function(e){return t.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}, -t.prototype.intersectsMinMax=function(e,t){return!(this.maximumWorld.xt.x)&&(!(this.maximumWorld.yt.y)&&!(this.maximumWorld.zt.z))},t.Intersects=function(e,t){return!(e.maximumWorld.xt.maximumWorld.x)&&(!(e.maximumWorld.yt.maximumWorld.y)&&!(e.maximumWorld.zt.maximumWorld.z))},t.IntersectsSphere=function(t,i,r,n){var o=e.Vector3.Clamp(r,t,i);return e.Vector3.DistanceSquared(r,o)<=n*n},t.IsCompletelyInFrustum=function(e,t){for(var i=0;i<6;i++)for(var r=0;r<8;r++)if(t[i].dotCoordinate(e[r])<0)return!1;return!0},t.IsInFrustum=function(e,t){for(var i=0;i<6;i++){for(var r=8,n=0;n<8&&t[i].dotCoordinate(e[n])<0;n++)--r;if(0===r)return!1}return!0},t})();e.BoundingBox=t})(r||(r={}));var r;!(function(e){var t=function(t,i){var r=e.Vector3.Dot(i.centerWorld,t),n=Math.abs(e.Vector3.Dot(i.directions[0],t))*i.extendSize.x,o=Math.abs(e.Vector3.Dot(i.directions[1],t))*i.extendSize.y,s=Math.abs(e.Vector3.Dot(i.directions[2],t))*i.extendSize.z,a=n+o+s;return{min:r-a,max:r+a}},i=function(e,t,i,r){return!(e>r||i>t)},r=function(e,r,n){var o=t(e,r),s=t(e,n);return i(o.min,o.max,s.min,s.max)},n=(function(){function t(t,i){this.minimum=t,this.maximum=i,this._isLocked=!1,this.boundingBox=new e.BoundingBox(t,i),this.boundingSphere=new e.BoundingSphere(t,i)}return Object.defineProperty(t.prototype,"isLocked",{get:function(){return this._isLocked},set:function(e){this._isLocked=e},enumerable:!0,configurable:!0}),t.prototype.update=function(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))},t.prototype.centerOn=function(t,i){return this.minimum=t.subtract(i),this.maximum=t.add(i),this.boundingBox=new e.BoundingBox(this.minimum,this.maximum),this.boundingSphere=new e.BoundingSphere(this.minimum,this.maximum),this},t.prototype.scale=function(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this},t.prototype.isInFrustum=function(e){return!!this.boundingSphere.isInFrustum(e)&&this.boundingBox.isInFrustum(e)},Object.defineProperty(t.prototype,"diagonalLength",{get:function(){var e=this.boundingBox;return e.maximumWorld.subtract(e.minimumWorld).length()},enumerable:!0,configurable:!0}),t.prototype.isCompletelyInFrustum=function(e){return this.boundingBox.isCompletelyInFrustum(e)},t.prototype._checkCollision=function(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)},t.prototype.intersectsPoint=function(e){return!!this.boundingSphere.centerWorld&&(!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e))},t.prototype.intersects=function(t,i){if(!this.boundingSphere.centerWorld||!t.boundingSphere.centerWorld)return!1;if(!e.BoundingSphere.Intersects(this.boundingSphere,t.boundingSphere))return!1;if(!e.BoundingBox.Intersects(this.boundingBox,t.boundingBox))return!1;if(!i)return!0;var n=this.boundingBox,o=t.boundingBox;return!!r(n.directions[0],n,o)&&(!!r(n.directions[1],n,o)&&(!!r(n.directions[2],n,o)&&(!!r(o.directions[0],n,o)&&(!!r(o.directions[1],n,o)&&(!!r(o.directions[2],n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[1]),n,o)&&!!r(e.Vector3.Cross(n.directions[2],o.directions[2]),n,o))))))))))))))},t})();e.BoundingInfo=n})(r||(r={}));var r;!(function(e){var t=(function(t){function i(r,n,o){void 0===n&&(n=null),void 0===o&&(o=!0);var s=t.call(this,r,n)||this;return s._forward=new e.Vector3(0,0,1),s._forwardInverted=new e.Vector3(0,0,-1),s._up=new e.Vector3(0,1,0),s._right=new e.Vector3(1,0,0),s._rightInverted=new e.Vector3(-1,0,0),s._rotation=e.Vector3.Zero(),s._scaling=e.Vector3.One(),s._isDirty=!1,s.billboardMode=i.BILLBOARDMODE_NONE,s.scalingDeterminant=1,s.infiniteDistance=!1,s.ignoreNonUniformScaling=!1,s.position=e.Vector3.Zero(),s._localWorld=e.Matrix.Zero(),s._worldMatrix=e.Matrix.Zero(),s._worldMatrixDeterminant=0,s._absolutePosition=e.Vector3.Zero(),s._pivotMatrix=e.Matrix.Identity(),s._postMultiplyPivotMatrix=!1,s._isWorldMatrixFrozen=!1,s.onAfterWorldMatrixUpdateObservable=new e.Observable,s._nonUniformScaling=!1,o&&s.getScene().addTransformNode(s),s}return o(i,t),i.prototype.getClassName=function(){return"TransformNode"},Object.defineProperty(i.prototype,"rotation",{get:function(){return this._rotation},set:function(e){this._rotation=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"scaling",{get:function(){return this._scaling},set:function(e){this._scaling=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"rotationQuaternion",{get:function(){return this._rotationQuaternion},set:function(e){this._rotationQuaternion=e,e&&this.rotation.length()&&this.rotation.copyFromFloats(0,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"forward",{get:function(){return e.Vector3.Normalize(e.Vector3.TransformNormal(this.getScene().useRightHandedSystem?this._forwardInverted:this._forward,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"up",{get:function(){return e.Vector3.Normalize(e.Vector3.TransformNormal(this._up,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return e.Vector3.Normalize(e.Vector3.TransformNormal(this.getScene().useRightHandedSystem?this._rightInverted:this._right,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),i.prototype.getWorldMatrix=function(){return this._currentRenderId!==this.getScene().getRenderId()&&this.computeWorldMatrix(),this._worldMatrix},i.prototype._getWorldMatrixDeterminant=function(){return this._worldMatrixDeterminant},Object.defineProperty(i.prototype,"worldMatrixFromCache",{get:function(){return this._worldMatrix},enumerable:!0,configurable:!0}),i.prototype.updatePoseMatrix=function(e){return this._poseMatrix.copyFrom(e),this},i.prototype.getPoseMatrix=function(){return this._poseMatrix},i.prototype._isSynchronized=function(){return!this._isDirty&&(this.billboardMode===this._cache.billboardMode&&this.billboardMode===i.BILLBOARDMODE_NONE&&(!this._cache.pivotMatrixUpdated&&(!this.infiniteDistance&&(!!this._cache.position.equals(this.position)&&(!(this.rotationQuaternion&&!this._cache.rotationQuaternion.equals(this.rotationQuaternion))&&(!!this._cache.rotation.equals(this.rotation)&&!!this._cache.scaling.equals(this.scaling)))))))},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.localMatrixUpdated=!1,this._cache.position=e.Vector3.Zero(),this._cache.scaling=e.Vector3.Zero(),this._cache.rotation=e.Vector3.Zero(),this._cache.rotationQuaternion=new e.Quaternion(0,0,0,0),this._cache.billboardMode=-1},i.prototype.markAsDirty=function(e){return"rotation"===e&&(this.rotationQuaternion=null),this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this},Object.defineProperty(i.prototype,"absolutePosition",{get:function(){return this._absolutePosition},enumerable:!0,configurable:!0}),i.prototype.setPreTransformMatrix=function(e){return this.setPivotMatrix(e,!1)},i.prototype.setPivotMatrix=function(t,i){return void 0===i&&(i=!0),this._pivotMatrix=t.clone(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=i,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=e.Matrix.Invert(this._pivotMatrix)),this},i.prototype.getPivotMatrix=function(){return this._pivotMatrix},i.prototype.freezeWorldMatrix=function(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this._isWorldMatrixFrozen=!0,this},i.prototype.unfreezeWorldMatrix=function(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this},Object.defineProperty(i.prototype,"isWorldMatrixFrozen",{get:function(){return this._isWorldMatrixFrozen},enumerable:!0,configurable:!0}),i.prototype.getAbsolutePosition=function(){return this.computeWorldMatrix(),this._absolutePosition},i.prototype.setAbsolutePosition=function(t){if(!t)return this;var i,r,n;if(void 0===t.x){if(arguments.length<3)return this;i=arguments[0],r=arguments[1],n=arguments[2]}else i=t.x,r=t.y,n=t.z;if(this.parent){var o=this.parent.getWorldMatrix().clone();o.invert();var s=new e.Vector3(i,r,n);this.position=e.Vector3.TransformCoordinates(s,o)}else this.position.x=i,this.position.y=r,this.position.z=n;return this},i.prototype.setPositionWithLocalVector=function(t){return this.computeWorldMatrix(),this.position=e.Vector3.TransformNormal(t,this._localWorld),this},i.prototype.getPositionExpressedInLocalSpace=function(){this.computeWorldMatrix();var t=this._localWorld.clone();return t.invert(),e.Vector3.TransformNormal(this.position,t)},i.prototype.locallyTranslate=function(t){return this.computeWorldMatrix(!0),this.position=e.Vector3.TransformCoordinates(t,this._localWorld),this},i.prototype.lookAt=function(t,r,n,o,s){void 0===r&&(r=0),void 0===n&&(n=0),void 0===o&&(o=0),void 0===s&&(s=e.Space.LOCAL);var a=i._lookAtVectorCache,l=s===e.Space.LOCAL?this.position:this.getAbsolutePosition();t.subtractToRef(l,a);var c=-Math.atan2(a.z,a.x)-Math.PI/2,h=Math.sqrt(a.x*a.x+a.z*a.z),u=Math.atan2(a.y,h);return this.rotationQuaternion?e.Quaternion.RotationYawPitchRollToRef(c+r,u+n,o,this.rotationQuaternion):(this.rotation.x=u+n,this.rotation.y=c+r,this.rotation.z=o),this},i.prototype.getDirection=function(t){var i=e.Vector3.Zero();return this.getDirectionToRef(t,i),i},i.prototype.getDirectionToRef=function(t,i){return e.Vector3.TransformNormalToRef(t,this.getWorldMatrix(),i),this},i.prototype.setPivotPoint=function(t,i){void 0===i&&(i=e.Space.LOCAL),0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);var r=this.getWorldMatrix();if(i==e.Space.WORLD){var n=e.Tmp.Matrix[0];r.invertToRef(n),t=e.Vector3.TransformCoordinates(t,n)}return this.setPivotMatrix(e.Matrix.Translation(-t.x,-t.y,-t.z),!0)},i.prototype.getPivotPoint=function(){var t=e.Vector3.Zero();return this.getPivotPointToRef(t),t},i.prototype.getPivotPointToRef=function(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this},i.prototype.getAbsolutePivotPoint=function(){var t=e.Vector3.Zero();return this.getAbsolutePivotPointToRef(t),t},i.prototype.getAbsolutePivotPointToRef=function(t){return t.x=this._pivotMatrix.m[12],t.y=this._pivotMatrix.m[13],t.z=this._pivotMatrix.m[14],this.getPivotPointToRef(t),e.Vector3.TransformCoordinatesToRef(t,this.getWorldMatrix(),t),this},i.prototype.setParent=function(t){if(!t&&!this.parent)return this;if(t){var i=e.Tmp.Quaternion[0],r=e.Tmp.Vector3[0],n=e.Tmp.Vector3[1],o=e.Tmp.Matrix[0],s=e.Tmp.Matrix[1];this.computeWorldMatrix(!0),t.computeWorldMatrix(!0),t.getWorldMatrix().invertToRef(s),this.getWorldMatrix().multiplyToRef(s,o),o.decompose(n,i,r),this.rotationQuaternion?this.rotationQuaternion.copyFrom(i):i.toEulerAnglesToRef(this.rotation),this.position.x=r.x,this.position.y=r.y,this.position.z=r.z,this.scaling.x=n.x,this.scaling.y=n.y,this.scaling.z=n.z}else{var i=e.Tmp.Quaternion[0],r=e.Tmp.Vector3[0],n=e.Tmp.Vector3[1];this.parent&&this.parent.computeWorldMatrix&&this.parent.computeWorldMatrix(!0),this.computeWorldMatrix(!0),this.getWorldMatrix().decompose(n,i,r),this.rotationQuaternion?this.rotationQuaternion.copyFrom(i):i.toEulerAnglesToRef(this.rotation),this.scaling.x=n.x,this.scaling.y=n.y,this.scaling.z=n.z,this.position.x=r.x,this.position.y=r.y,this.position.z=r.z}return this.parent=t,this},Object.defineProperty(i.prototype,"nonUniformScaling",{get:function(){return this._nonUniformScaling},enumerable:!0,configurable:!0}),i.prototype._updateNonUniformScalingState=function(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)},i.prototype.attachToBone=function(e,t){return this._transformToBoneReferal=t,this.parent=e,e.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this},i.prototype.detachFromBone=function(){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=null,this):this},i.prototype.rotate=function(t,r,n){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation=e.Vector3.Zero());var o;if(n&&n!==e.Space.LOCAL){if(this.parent){var s=this.parent.getWorldMatrix().clone();s.invert(),t=e.Vector3.TransformNormal(t,s)}o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),this.rotationQuaternion.multiplyToRef(o,this.rotationQuaternion);return this},i.prototype.rotateAround=function(t,i,r){return i.normalize(),this.rotationQuaternion||(this.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.copyFromFloats(0,0,0)),t.subtractToRef(this.position,e.Tmp.Vector3[0]),e.Matrix.TranslationToRef(e.Tmp.Vector3[0].x,e.Tmp.Vector3[0].y,e.Tmp.Vector3[0].z,e.Tmp.Matrix[0]),e.Tmp.Matrix[0].invertToRef(e.Tmp.Matrix[2]),e.Matrix.RotationAxisToRef(i,r,e.Tmp.Matrix[1]),e.Tmp.Matrix[2].multiplyToRef(e.Tmp.Matrix[1],e.Tmp.Matrix[2]),e.Tmp.Matrix[2].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[2]),e.Tmp.Matrix[2].decompose(e.Tmp.Vector3[0],e.Tmp.Quaternion[0],e.Tmp.Vector3[1]),this.position.addInPlace(e.Tmp.Vector3[1]),e.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this},i.prototype.translate=function(t,i,r){var n=t.scale(i);if(r&&r!==e.Space.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(n));else{var o=this.getPositionExpressedInLocalSpace().add(n);this.setPositionWithLocalVector(o)}return this},i.prototype.addRotation=function(t,i,r){var n;this.rotationQuaternion?n=this.rotationQuaternion:(n=e.Tmp.Quaternion[1],e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,n));var o=e.Tmp.Quaternion[0];return e.Quaternion.RotationYawPitchRollToRef(i,t,r,o),n.multiplyInPlace(o),this.rotationQuaternion||n.toEulerAnglesToRef(this.rotation),this},i.prototype.computeWorldMatrix=function(t){if(this._isWorldMatrixFrozen)return this._worldMatrix;if(!t&&this.isSynchronized(!0))return this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix;if(this._cache.position.copyFrom(this.position),this._cache.scaling.copyFrom(this.scaling),this._cache.pivotMatrixUpdated=!1,this._cache.billboardMode=this.billboardMode,this._currentRenderId=this.getScene().getRenderId(),this._childRenderId=this.getScene().getRenderId(),this._isDirty=!1,e.Matrix.ScalingToRef(this.scaling.x*this.scalingDeterminant,this.scaling.y*this.scalingDeterminant,this.scaling.z*this.scalingDeterminant,e.Tmp.Matrix[1]),this.rotationQuaternion){this.rotation.length()&&(this.rotationQuaternion.multiplyInPlace(e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)),this.rotation.copyFromFloats(0,0,0))}this.rotationQuaternion?(this.rotationQuaternion.toRotationMatrix(e.Tmp.Matrix[0]),this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,e.Tmp.Matrix[0]),this._cache.rotation.copyFrom(this.rotation));var r=this.getScene().activeCamera;if(this.infiniteDistance&&!this.parent&&r){var n=r.getWorldMatrix(),o=new e.Vector3(n.m[12],n.m[13],n.m[14]);e.Matrix.TranslationToRef(this.position.x+o.x,this.position.y+o.y,this.position.z+o.z,e.Tmp.Matrix[2])}else e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,e.Tmp.Matrix[2]);if(this._pivotMatrix.multiplyToRef(e.Tmp.Matrix[1],e.Tmp.Matrix[4]),e.Tmp.Matrix[4].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[5]),this.billboardMode!==i.BILLBOARDMODE_NONE&&r){if((this.billboardMode&i.BILLBOARDMODE_ALL)!==i.BILLBOARDMODE_ALL){var s=e.Tmp.Vector3[3];this.parent&&this.parent.getWorldMatrix?this._transformToBoneReferal?(this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),e.Tmp.Matrix[6]),e.Vector3.TransformCoordinatesToRef(this.position,e.Tmp.Matrix[6],s)):e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),s):s.copyFrom(this.position),s.subtractInPlace(r.globalPosition);var a=e.Tmp.Vector3[4].copyFromFloats(0,0,0);(this.billboardMode&i.BILLBOARDMODE_X)===i.BILLBOARDMODE_X&&(a.x=Math.atan2(-s.y,s.z)),(this.billboardMode&i.BILLBOARDMODE_Y)===i.BILLBOARDMODE_Y&&(a.y=Math.atan2(s.x,s.z)),(this.billboardMode&i.BILLBOARDMODE_Z)===i.BILLBOARDMODE_Z&&(a.z=Math.atan2(s.y,s.x)),e.Matrix.RotationYawPitchRollToRef(a.y,a.x,a.z,e.Tmp.Matrix[0])}else e.Tmp.Matrix[1].copyFrom(r.getViewMatrix()),e.Tmp.Matrix[1].setTranslationFromFloats(0,0,0),e.Tmp.Matrix[1].invertToRef(e.Tmp.Matrix[0]);e.Tmp.Matrix[1].copyFrom(e.Tmp.Matrix[5]),e.Tmp.Matrix[1].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[5])}return this._postMultiplyPivotMatrix&&e.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse,e.Tmp.Matrix[5]),e.Tmp.Matrix[5].multiplyToRef(e.Tmp.Matrix[2],this._localWorld),this.parent&&this.parent.getWorldMatrix?(this.billboardMode!==i.BILLBOARDMODE_NONE?(this._transformToBoneReferal?(this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),e.Tmp.Matrix[6]),e.Tmp.Matrix[5].copyFrom(e.Tmp.Matrix[6])):e.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix()),this._localWorld.getTranslationToRef(e.Tmp.Vector3[5]),e.Vector3.TransformCoordinatesToRef(e.Tmp.Vector3[5],e.Tmp.Matrix[5],e.Tmp.Vector3[5]),this._worldMatrix.copyFrom(this._localWorld),this._worldMatrix.setTranslation(e.Tmp.Vector3[5])):this._transformToBoneReferal?(this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),e.Tmp.Matrix[6]),e.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()):this._worldMatrix.copyFrom(this._localWorld),this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this.scaling.isNonUniform?this._updateNonUniformScalingState(!0):this.parent&&this.parent._nonUniformScaling?this._updateNonUniformScalingState(this.parent._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=e.Matrix.Invert(this._worldMatrix)),this._worldMatrixDeterminant=this._worldMatrix.determinant(),this._worldMatrix},i.prototype._afterComputeWorldMatrix=function(){},i.prototype.registerAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this},i.prototype.unregisterAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this},i.prototype.clone=function(t,r,n){var o=this,s=e.SerializationHelper.Clone((function(){return new i(t,o.getScene())}),this);if(s.name=t,s.id=t,r&&(s.parent=r),!n)for(var a=this.getDescendants(!0),l=0;le.Engine.CollisionsEpsilon&&o.position.addInPlace(o._diffPositionForCollisions),r&&o.onCollideObservable.notifyObservers(r),o.onCollisionPositionChangeObservable.notifyObservers(o.position)},o.getScene().addMesh(o),o._resyncLightSources(),o}return o(i,t),Object.defineProperty(i,"BILLBOARDMODE_NONE",{get:function(){return e.TransformNode.BILLBOARDMODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_X",{get:function(){return e.TransformNode.BILLBOARDMODE_X},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Y",{get:function(){return e.TransformNode.BILLBOARDMODE_Y},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Z",{get:function(){return e.TransformNode.BILLBOARDMODE_Z},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_ALL",{get:function(){return e.TransformNode.BILLBOARDMODE_ALL},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"facetNb",{get:function(){return this._facetNb},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"partitioningSubdivisions",{get:function(){return this._partitioningSubdivisions},set:function(e){this._partitioningSubdivisions=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"partitioningBBoxRatio",{get:function(){return this._partitioningBBoxRatio},set:function(e){this._partitioningBBoxRatio=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"mustDepthSortFacets",{get:function(){return this._facetDepthSort},set:function(e){this._facetDepthSort=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"facetDepthSortFrom",{get:function(){return this._facetDepthSortFrom},set:function(e){this._facetDepthSortFrom=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"isFacetDataEnabled",{get:function(){return this._facetDataEnabled},enumerable:!0,configurable:!0}),i.prototype._updateNonUniformScalingState=function(e){return!!t.prototype._updateNonUniformScalingState.call(this,e)&&(this._markSubMeshesAsMiscDirty(),!0)},Object.defineProperty(i.prototype,"onCollide",{set:function(e){this._onCollideObserver&&this.onCollideObservable.remove(this._onCollideObserver),this._onCollideObserver=this.onCollideObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onCollisionPositionChange",{set:function(e){this._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver),this._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"isOccluded",{get:function(){return this._isOccluded},set:function(e){this._isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"isOcclusionQueryInProgress",{get:function(){return this._isOcclusionQueryInProgress},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"visibility",{get:function(){return this._visibility},set:function(e){this._visibility!==e&&(this._visibility=e,this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"material",{get:function(){return this._material},set:function(e){this._material!==e&&(this._material=e,this.onMaterialChangedObservable.hasObservers&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&this._unBindEffect())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"receiveShadows",{get:function(){return this._receiveShadows},set:function(e){this._receiveShadows!==e&&(this._receiveShadows=e,this._markSubMeshesAsLightDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"hasVertexAlpha",{get:function(){return this._hasVertexAlpha},set:function(e){this._hasVertexAlpha!==e&&(this._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useVertexColors",{get:function(){return this._useVertexColors},set:function(e){this._useVertexColors!==e&&(this._useVertexColors=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"computeBonesUsingShaders",{get:function(){return this._computeBonesUsingShaders},set:function(e){this._computeBonesUsingShaders!==e&&(this._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"numBoneInfluencers",{get:function(){return this._numBoneInfluencers},set:function(e){this._numBoneInfluencers!==e&&(this._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"applyFog",{get:function(){return this._applyFog},set:function(e){this._applyFog!==e&&(this._applyFog=e,this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"layerMask",{get:function(){return this._layerMask},set:function(e){e!==this._layerMask&&(this._layerMask=e,this._resyncLightSources())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"collisionGroup",{get:function(){return this._collisionGroup},set:function(e){this._collisionGroup=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"_positions",{get:function(){return null},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"skeleton",{get:function(){return this._skeleton},set:function(e){this._skeleton&&this._skeleton.needInitialSkinMatrix&&this._skeleton._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._skeleton=e,this._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"AbstractMesh"},i.prototype.toString=function(t){var i="Name: "+this.name+", isInstance: "+(this instanceof e.InstancedMesh?"YES":"NO");return i+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0),this._skeleton&&(i+=", skeleton: "+this._skeleton.name),t&&(i+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],i+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingFreezeWorldMatrix?"YES":"NO")),i},i.prototype._rebuild=function(){if(this._occlusionQuery&&(this._occlusionQuery=null),this._edgesRenderer&&this._edgesRenderer._rebuild(),this.subMeshes)for(var e=0,t=this.subMeshes;e1&&!a._checkCollision(e)||this._collideForSubMesh(a,t,e)}return this},i.prototype._checkCollision=function(t){return this._boundingInfo&&this._boundingInfo._checkCollision(t)?(e.Matrix.ScalingToRef(1/t._radius.x,1/t._radius.y,1/t._radius.z,this._collisionsScalingMatrix),this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix,this._collisionsTransformMatrix),this._processCollisionsForSubMeshes(t,this._collisionsTransformMatrix),this):this},i.prototype._generatePointsArray=function(){return!1},i.prototype.intersects=function(t,i){var r=new e.PickingInfo;if(!(this.subMeshes&&this._boundingInfo&&t.intersectsSphere(this._boundingInfo.boundingSphere)&&t.intersectsBox(this._boundingInfo.boundingBox)))return r;if(!this._generatePointsArray())return r;var n,o,s=null;if(this._submeshesOctree&&this.useOctreeForPicking){var a=e.Ray.Transform(t,this.getWorldMatrix()),l=this._submeshesOctree.intersectsRay(a);o=l.length,n=l.data}else n=this.subMeshes,o=n.length;for(var c=0;c1)||h.canIntersects(t)){var u=h.intersects(t,this._positions,this.getIndices(),i);if(u&&(i||!s||u.distance65535){o=!0;break}this._depthSortedIndices=o?new Uint32Array(i):new Uint16Array(i)}if(this._facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!this._facetDepthSortFrom){var a=this.getScene().activeCamera;this._facetDepthSortFrom=a?a.position:e.Vector3.Zero()}this._depthSortedFacets=[];for(var l=0;le.Epsilon?n.maximum.x-n.minimum.x:e.Epsilon,this._bbSize.y=n.maximum.y-n.minimum.y>e.Epsilon?n.maximum.y-n.minimum.y:e.Epsilon,this._bbSize.z=n.maximum.z-n.minimum.z>e.Epsilon?n.maximum.z-n.minimum.z:e.Epsilon;var h=this._bbSize.x>this._bbSize.y?this._bbSize.x:this._bbSize.y;if(h=h>this._bbSize.z?h:this._bbSize.z,this._subDiv.max=this._partitioningSubdivisions,this._subDiv.X=Math.floor(this._subDiv.max*this._bbSize.x/h),this._subDiv.Y=Math.floor(this._subDiv.max*this._bbSize.y/h),this._subDiv.Z=Math.floor(this._subDiv.max*this._bbSize.z/h),this._subDiv.X=this._subDiv.X<1?1:this._subDiv.X,this._subDiv.Y=this._subDiv.Y<1?1:this._subDiv.Y,this._subDiv.Z=this._subDiv.Z<1?1:this._subDiv.Z,this._facetParameters.facetNormals=this.getFacetLocalNormals(),this._facetParameters.facetPositions=this.getFacetLocalPositions(),this._facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),this._facetParameters.bInfo=n,this._facetParameters.bbSize=this._bbSize,this._facetParameters.subDiv=this._subDiv,this._facetParameters.ratio=this.partitioningBBoxRatio,this._facetParameters.depthSort=this._facetDepthSort,this._facetDepthSort&&this._facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(this._invertedMatrix),e.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom,this._invertedMatrix,this._facetDepthSortOrigin),this._facetParameters.distanceTo=this._facetDepthSortOrigin),this._facetParameters.depthSortedFacets=this._depthSortedFacets,e.VertexData.ComputeNormals(t,i,r,this._facetParameters),this._facetDepthSort&&this._facetDepthSortEnabled){this._depthSortedFacets.sort(this._facetDepthSortFunction);for(var u=this._depthSortedIndices.length/3|0,l=0;lthis._subDiv.max||o<0||o>this._subDiv.max||s<0||s>this._subDiv.max?null:this._facetPartitioning[n+this._subDiv.max*o+this._subDiv.max*this._subDiv.max*s]},i.prototype.getClosestFacetAtCoordinates=function(t,i,r,n,o,s){void 0===o&&(o=!1),void 0===s&&(s=!0);var a=this.getWorldMatrix(),l=e.Tmp.Matrix[5];a.invertToRef(l);var c=e.Tmp.Vector3[8];e.Vector3.TransformCoordinatesFromFloatsToRef(t,i,r,l,c);var h=this.getClosestFacetAtLocalCoordinates(c.x,c.y,c.z,n,o,s);return n&&e.Vector3.TransformCoordinatesFromFloatsToRef(n.x,n.y,n.z,a,n),h},i.prototype.getClosestFacetAtLocalCoordinates=function(e,t,i,r,n,o){void 0===n&&(n=!1),void 0===o&&(o=!0);var s=null,a=0,l=0,c=0,h=0,u=0,d=0,f=0,p=0,_=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;for(var v,y,b,x=Number.MAX_VALUE,T=x,E=0;E=0||n&&!o&&h<=0)&&(h=y.x*b.x+y.y*b.y+y.z*b.z,u=-(y.x*e+y.y*t+y.z*i-h)/(y.x*y.x+y.y*y.y+y.z*y.z),d=e+y.x*u,f=t+y.y*u,p=i+y.z*u,a=d-e,l=f-t,c=p-i,(T=a*a+l*l+c*c)0&&-1===this.includedOnlyMeshes.indexOf(e))&&(!(this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e))&&((0===this.includeOnlyWithLayerMask||0!=(this.includeOnlyWithLayerMask&e.layerMask))&&!(0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask)))},i.prototype.getWorldMatrix=function(){this._currentRenderId=this.getScene().getRenderId(),this._childRenderId=this._currentRenderId;var t=this._getWorldMatrix();return this.parent&&this.parent.getWorldMatrix?(this._parentedWorldMatrix||(this._parentedWorldMatrix=e.Matrix.Identity()),t.multiplyToRef(this.parent.getWorldMatrix(),this._parentedWorldMatrix),this._markSyncedWithParent(),this._parentedWorldMatrix):t},i.CompareLightsPriority=function(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority},i.prototype.dispose=function(e,i){void 0===i&&(i=!1),this._shadowGenerator&&(this._shadowGenerator.dispose(),this._shadowGenerator=null),this.getScene().stopAnimation(this);for(var r=0,n=this.getScene().meshes;r0&&(t.excludedMeshesIds=[],this.excludedMeshes.forEach((function(e){t.excludedMeshesIds.push(e.id)}))),this.includedOnlyMeshes.length>0&&(t.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((function(e){t.includedOnlyMeshesIds.push(e.id)}))),e.Animation.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t},i.GetConstructorFromName=function(t,i,r){var n=e.Node.Construct("Light_Type_"+t,i,r);return n||null},i.Parse=function(t,r){var n=i.GetConstructorFromName(t.type,t.name,r);if(!n)return null;var o=e.SerializationHelper.Parse(n,t,r);if(t.excludedMeshesIds&&(o._excludedMeshesIds=t.excludedMeshesIds),t.includedOnlyMeshesIds&&(o._includedOnlyMeshesIds=t.includedOnlyMeshesIds),t.parentId&&(o._waitingParentId=t.parentId),t.animations){for(var s=0;s-1?(e.Tools.Error("You're trying to reuse a post process not defined as reusable."),0):(null==i||i<0?this._postProcesses.push(t):null===this._postProcesses[i]?this._postProcesses[i]=t:this._postProcesses.splice(i,0,t),this._cascadePostProcessesToRigCams(),this._postProcesses.indexOf(t))},i.prototype.detachPostProcess=function(e){var t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._cascadePostProcessesToRigCams()},i.prototype.getWorldMatrix=function(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)},i.prototype._getViewMatrix=function(){return e.Matrix.Identity()},i.prototype.getViewMatrix=function(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childRenderId=this._currentRenderId,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._computedViewMatrix)},i.prototype.freezeProjectionMatrix=function(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)},i.prototype.unfreezeProjectionMatrix=function(){this._doNotComputeProjectionMatrix=!1},i.prototype.getProjectionMatrix=function(t){if(this._doNotComputeProjectionMatrix||!t&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;var r=this.getEngine(),n=this.getScene();if(this.mode===i.PERSPECTIVE_CAMERA)this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=r.getAspectRatio(this),this.minZ<=0&&(this.minZ=.1),n.useRightHandedSystem?e.Matrix.PerspectiveFovRHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED):e.Matrix.PerspectiveFovLHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED);else{var o=r.getRenderWidth()/2,s=r.getRenderHeight()/2;n.useRightHandedSystem?e.Matrix.OrthoOffCenterRHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix):e.Matrix.OrthoOffCenterLHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=r.getRenderWidth(),this._cache.renderHeight=r.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix},i.prototype.getTransformationMatrix=function(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix},i.prototype.updateFrustumPlanes=function(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?e.Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=e.Frustum.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)},i.prototype.isInFrustum=function(e){return this.updateFrustumPlanes(),e.isInFrustum(this._frustumPlanes)},i.prototype.isCompletelyInFrustum=function(e){return this.updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)},i.prototype.getForwardRay=function(t,i,r){void 0===t&&(t=100),i||(i=this.getWorldMatrix()),r||(r=this.position);var n=new e.Vector3(0,0,1),o=e.Vector3.TransformNormal(n,i),s=e.Vector3.Normalize(o);return new e.Ray(r,s,t)},i.prototype.dispose=function(e,r){for(void 0===r&&(r=!1),this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){var n=this._rigCameras.pop();n&&n.dispose()}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses=[];else if(this.cameraRigMode!==i.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses=[];else for(var o=this._postProcesses.length;--o>=0;){var s=this._postProcesses[o];s&&s.dispose(this)}for(var o=this.customRenderTargets.length;--o>=0;)this.customRenderTargets[o].dispose();this.customRenderTargets=[],this._activeMeshes.dispose(),t.prototype.dispose.call(this,e,r)},Object.defineProperty(i.prototype,"leftCamera",{get:function(){return this._rigCameras.length<1?null:this._rigCameras[0]},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"rightCamera",{get:function(){return this._rigCameras.length<2?null:this._rigCameras[1]},enumerable:!0,configurable:!0}),i.prototype.getLeftTarget=function(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()},i.prototype.getRightTarget=function(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()},i.prototype.setCameraRigMode=function(t,r){if(this.cameraRigMode!==t){for(;this._rigCameras.length>0;){var n=this._rigCameras.pop();n&&n.dispose()}if(this.cameraRigMode=t,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=r.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==i.RIG_MODE_NONE){var o=this.createRigCamera(this.name+"_L",0),s=this.createRigCamera(this.name+"_R",1);o&&s&&(this._rigCameras.push(o),this._rigCameras.push(s))}switch(this.cameraRigMode){case i.RIG_MODE_STEREOSCOPIC_ANAGLYPH:this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.AnaglyphPostProcess(this.name+"_anaglyph",1,this._rigCameras);break;case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case i.RIG_MODE_STEREOSCOPIC_OVERUNDER:var a=this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.StereoscopicInterlacePostProcess(this.name+"_stereoInterlace",this._rigCameras,a);break;case i.RIG_MODE_VR:var l=r.vrCameraMetrics||e.VRCameraMetrics.GetDefault();this._rigCameras[0]._cameraRigParams.vrMetrics=l,this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0]._cameraRigParams.vrHMatrix=l.leftHMatrix,this._rigCameras[0]._cameraRigParams.vrPreViewMatrix=l.leftPreViewMatrix,this._rigCameras[0].getProjectionMatrix=this._rigCameras[0]._getVRProjectionMatrix,this._rigCameras[1]._cameraRigParams.vrMetrics=l,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1]._cameraRigParams.vrHMatrix=l.rightHMatrix,this._rigCameras[1]._cameraRigParams.vrPreViewMatrix=l.rightPreViewMatrix,this._rigCameras[1].getProjectionMatrix=this._rigCameras[1]._getVRProjectionMatrix,l.compensateDistortion&&(this._rigCameras[0]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",this._rigCameras[0],!1,l),this._rigCameras[1]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",this._rigCameras[1],!0,l));break;case i.RIG_MODE_WEBVR:if(r.vrDisplay){var c=r.vrDisplay.getEyeParameters("left"),h=r.vrDisplay.getEyeParameters("right");this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0].setCameraRigParameter("left",!0),this._rigCameras[0].setCameraRigParameter("specs",r.specs),this._rigCameras[0].setCameraRigParameter("eyeParameters",c),this._rigCameras[0].setCameraRigParameter("frameData",r.frameData),this._rigCameras[0].setCameraRigParameter("parentCamera",r.parentCamera),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0].getProjectionMatrix=this._getWebVRProjectionMatrix,this._rigCameras[0].parent=this,this._rigCameras[0]._getViewMatrix=this._getWebVRViewMatrix,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1].setCameraRigParameter("eyeParameters",h),this._rigCameras[1].setCameraRigParameter("specs",r.specs),this._rigCameras[1].setCameraRigParameter("frameData",r.frameData),this._rigCameras[1].setCameraRigParameter("parentCamera",r.parentCamera),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1].getProjectionMatrix=this._getWebVRProjectionMatrix,this._rigCameras[1].parent=this,this._rigCameras[1]._getViewMatrix=this._getWebVRViewMatrix,i.UseAlternateWebVRRendering&&(this._rigCameras[1]._skipRendering=!0,this._rigCameras[0]._alternateCamera=this._rigCameras[1])}}this._cascadePostProcessesToRigCams(),this.update()}},i.prototype._getVRProjectionMatrix=function(){return e.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix},i.prototype._updateCameraRotationMatrix=function(){},i.prototype._updateWebVRCameraRotationMatrix=function(){},i.prototype._getWebVRProjectionMatrix=function(){return e.Matrix.Identity()},i.prototype._getWebVRViewMatrix=function(){return e.Matrix.Identity()},i.prototype.setCameraRigParameter=function(t,i){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[t]=i,"interaxialDistance"===t&&(this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(i/.0637))},i.prototype.createRigCamera=function(e,t){return null},i.prototype._updateRigCameras=function(){for(var e=0;ei._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0},t.frontToBackSortCompare=function(e,t){return e._distanceToCamerat._distanceToCamera?1:0},t.prototype.prepare=function(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this._spriteManagers.reset(),this._edgesRenderers.reset()},t.prototype.dispose=function(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()},t.prototype.dispatch=function(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!==i&&void 0!==i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),null!==t._edgesRenderer&&void 0!==t._edgesRenderer&&t._edgesRenderer.isEnabled&&this._edgesRenderers.push(t._edgesRenderer))},t.prototype.dispatchSprites=function(e){this._spriteManagers.push(e)},t.prototype.dispatchParticles=function(e){this._particleSystems.push(e)},t.prototype._renderParticles=function(e){if(0!==this._particleSystems.length){var t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(var i=0;i0){for(var e=0,t=this._transientComponents;er.LongPressDelay&&Math.abs(n._startingPointerPosition.x-n._pointerX)r.DoubleClickDelay&&!s._doubleClickOccured||e!==s._previousButtonPressed)&&(s._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,i(t,s._currentPickResult))},this._initClickEvent=function(i,n,o,a){var l=new t;s._currentPickResult=null;var c=null,h=i.hasSpecificMask(e.PointerEventTypes.POINTERPICK)||n.hasSpecificMask(e.PointerEventTypes.POINTERPICK)||i.hasSpecificMask(e.PointerEventTypes.POINTERTAP)||n.hasSpecificMask(e.PointerEventTypes.POINTERTAP)||i.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)||n.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP);if(!h&&e.ActionManager&&e.ActionManager.HasPickTriggers&&(c=s._initActionManager(c,l))&&(h=c.hasPickTriggers),h){var u=o.button;if(l.hasSwiped=Math.abs(s._startingPointerPosition.x-s._pointerX)>r.DragMovementThreshold||Math.abs(s._startingPointerPosition.y-s._pointerY)>r.DragMovementThreshold,!l.hasSwiped){var d=!r.ExclusiveDoubleClickMode;d||(d=!i.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)&&!n.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP))&&!e.ActionManager.HasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)&&(c=s._initActionManager(c,l))&&(d=!c.hasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)),d?(Date.now()-s._previousStartingPointerTime>r.DoubleClickDelay||u!==s._previousButtonPressed)&&(l.singleClick=!0,a(l,s._currentPickResult)):(s._previousDelayedSimpleClickTimeout=s._delayedSimpleClickTimeout,s._delayedSimpleClickTimeout=window.setTimeout(s._delayedSimpleClick.bind(s,u,l,a),r.DoubleClickDelay));var f=i.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)||n.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP);!f&&e.ActionManager.HasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)&&(c=s._initActionManager(c,l))&&(f=c.hasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)),f&&(u===s._previousButtonPressed&&Date.now()-s._previousStartingPointerTime0&&(i=s.pickSprite(s._unTranslatedPointerX,s._unTranslatedPointerY,s._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,t.button){case 0:i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnLeftPickTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t));break;case 1:i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnCenterPickTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t));break;case 2:i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnRightPickTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickDownTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t))}}},this._onPointerUp=function(t){0!==s._totalPointersPressed&&(s._totalPointersPressed--,s._pickedUpMesh=null,s._meshPickProceed=!1,s._updatePointerPosition(t),s._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,t,(function(i,n){if(s.onPrePointerObservable.hasObservers())if(i.ignore){if(s._checkPrePointerObservable(null,t,e.PointerEventTypes.POINTERUP))return}else if(!i.hasSwiped){if(i.singleClick&&s.onPrePointerObservable.hasSpecificMask(e.PointerEventTypes.POINTERTAP)&&s._checkPrePointerObservable(null,t,e.PointerEventTypes.POINTERTAP))return;if(i.doubleClick&&s.onPrePointerObservable.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)&&s._checkPrePointerObservable(null,t,e.PointerEventTypes.POINTERDOUBLETAP))return}if(s.cameraToUseForPointers||s.activeCamera){if(s._pointerCaptures[t.pointerId]=!1,s.pointerUpPredicate||(s.pointerUpPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()}),!s._meshPickProceed&&(e.ActionManager&&e.ActionManager.HasTriggers||s.onPointerObservable.hasObservers())&&s._initActionManager(null,i),n||(n=s._currentPickResult),s._processPointerUp(n,t,i),!i.ignore&&s.spriteManagers.length>0){var o=s.pickSprite(s._unTranslatedPointerX,s._unTranslatedPointerY,s._spritePredicate,!1,s.cameraToUseForPointers||void 0);o&&(o.hit&&o.pickedSprite&&o.pickedSprite.actionManager&&(o.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickUpTrigger,e.ActionEvent.CreateNewFromSprite(o.pickedSprite,s,t)),o.pickedSprite.actionManager&&Math.abs(s._startingPointerPosition.x-s._pointerX)0)return!1;var t,i=this.getEngine();for(t=0;t0,o=0,s=this._isReadyForMeshStage;o0)for(var a=0,l=this.activeCameras;a0},enumerable:!0,configurable:!0}),r.prototype.executeWhenReady=function(e){var t=this;this.onReadyObservable.add(e),-1===this._executeWhenReadyTimeoutId&&(this._executeWhenReadyTimeoutId=setTimeout((function(){t._checkIsReady()}),150))},r.prototype.whenReadyAsync=function(){var e=this;return new Promise(function(t){e.executeWhenReady((function(){t()}))})},r.prototype._checkIsReady=function(){var e=this;if(this._registerTransientComponents(),this.isReady())return this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=-1);this._executeWhenReadyTimeoutId=setTimeout((function(){e._checkIsReady()}),150)},r.prototype.beginWeightedAnimation=function(e,t,i,r,n,o,s,a,l){void 0===r&&(r=1),void 0===o&&(o=1);var c=this.beginAnimation(e,t,i,n,o,s,a,!1,l);return c.weight=r,c},r.prototype.beginAnimation=function(t,i,r,n,o,s,a,l,c){void 0===o&&(o=1),void 0===l&&(l=!0),i>r&&o>0&&(o*=-1),l&&this.stopAnimation(t,void 0,c),a||(a=new e.Animatable(this,t,i,r,n,o,s));var h=!c||c(t);if(t.animations&&h&&a.appendAnimations(t,t.animations),t.getAnimatables)for(var u=t.getAnimatables(),d=0;d0)return;this._animationTimeLast=t}var i=this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale;this._animationTime+=i,this._animationTimeLast=t;for(var r=0;r0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t},r.prototype.removeParticleSystem=function(e){var t=this.particleSystems.indexOf(e);return-1!==t&&this.particleSystems.splice(t,1),t},r.prototype.removeAnimation=function(e){var t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t},r.prototype.removeAnimationGroup=function(e){var t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t},r.prototype.removeMultiMaterial=function(e){var t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),t},r.prototype.removeMaterial=function(e){var t=this.materials.indexOf(e);return-1!==t&&this.materials.splice(t,1),t},r.prototype.removeActionManager=function(e){var t=this.actionManagers.indexOf(e);return-1!==t&&this.actionManagers.splice(t,1),t},r.prototype.removeTexture=function(e){var t=this.textures.indexOf(e);return-1!==t&&this.textures.splice(t,1),t},r.prototype.addLight=function(e){this.lights.push(e),this.sortLightsByPriority();for(var t=0,i=this.meshes;t-1&&(this.geometries.splice(t,1),this.collisionCoordinator&&this.collisionCoordinator.onGeometryDeleted(e),this.onGeometryRemovedObservable.notifyObservers(e),!0)},r.prototype.getGeometries=function(){return this.geometries},r.prototype.getMeshByID=function(e){for(var t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null},r.prototype.getLastEntryByID=function(e){var t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null},r.prototype.getNodeByID=function(e){var t=this.getMeshByID(e);if(t)return t;var i=this.getLightByID(e);if(i)return i;var r=this.getCameraByID(e);return r||this.getBoneByID(e)},r.prototype.getNodeByName=function(e){var t=this.getMeshByName(e);if(t)return t;var i=this.getLightByName(e);if(i)return i;var r=this.getCameraByName(e);return r||this.getBoneByName(e)},r.prototype.getMeshByName=function(e){for(var t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null},r.prototype.getSkeletonById=function(e){for(var t=0;t0&&(a.alwaysSelectAsActiveMesh||0!=(a.layerMask&this.activeCamera.layerMask)&&a.isInFrustum(this._frustumPlanes))&&(this._activeMeshes.push(a),this.activeCamera._activeMeshes.push(a),a._activate(this._renderId),l!==a&&l._activate(this._renderId),this._activeMesh(a,l)))));if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(var h=0;h0){var n,o;if(t.useOctreeForRenderingSelection&&void 0!==t._submeshesOctree&&null!==t._submeshesOctree){var s=t._submeshesOctree.select(this._frustumPlanes);n=s.length,o=s.data}else o=t.subMeshes,n=o.length;for(var a,l=0;l0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),i&&i.customRenderTargets&&i.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(i.customRenderTargets),this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){e.Tools.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(var s=0;s0),this._renderId++}for(var c=0,h=this._cameraDrawRenderTargetStage;c-1&&(n.trigger===e.ActionManager.OnIntersectionExitTrigger&&n._executeCurrent(e.ActionEvent.CreateNew(i,void 0,s)),i.actionManager.hasSpecificTrigger(e.ActionManager.OnIntersectionExitTrigger,(function(t){var i=t instanceof e.AbstractMesh?t:t.mesh;return s===i}))&&n.trigger!==e.ActionManager.OnIntersectionExitTrigger||i._intersectionsInProgress.splice(l,1))}}}},r.prototype.render=function(t){if(void 0===t&&(t=!0),!this.isDisposed){if(this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(e.ActionManager.OnEveryFrameTrigger),this.simplificationQueue&&!this.simplificationQueue.running&&this.simplificationQueue.executeNext(),this._engine.isDeterministicLockStep()){var i=Math.max(r.MinDeltaTime,Math.min(this._engine.getDeltaTime(),r.MaxDeltaTime))+this._timeAccumulator,n=1e3/60;this._physicsEngine&&(n=1e3*this._physicsEngine.getTimeStep());var o=0,s=this._engine.getLockstepMaxSteps(),a=Math.floor(i/60);a=Math.min(a,s);do{this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=.06*n,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this._physicsEngine&&(this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(n/1e3),this.onAfterPhysicsObservable.notifyObservers(this)),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,o++,i-=n}while(i>0&&o0)for(var h=0;h0),this._intermediateRendering=!0;for(var _=0;_0),this._intermediateRendering=!1,this._renderId++}if(this.customRenderTargets.length>0&&f.restoreDefaultFramebuffer(),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.activeCamera=p,this.proceduralTexturesEnabled){e.Tools.StartPerformanceCounter("Procedural textures",this.proceduralTextures.length>0);for(var g=0;g0)}if((this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil),this.shadowsEnabled)for(var y=0;y0)for(var h=0;h0&&this._engine.clear(null,!1,!0,!0),this._processSubCameras(this.activeCameras[h]);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera)}this._checkIntersections(),e.AudioEngine&&this._updateAudioParameters(),this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this);for(var d=0;d0?this.activeCameras[0]:this.activeCamera)&&i.canUseWebAudio&&i.audioContext){i.audioContext.listener.setPosition(t.position.x,t.position.y,t.position.z),t.rigCameras&&t.rigCameras.length>0&&(t=t.rigCameras[0]);var r=e.Matrix.Invert(t.getViewMatrix()),n=e.Vector3.TransformNormal(new e.Vector3(0,0,-1),r);n.normalize(),isNaN(n.x)||isNaN(n.y)||isNaN(n.z)||i.audioContext.listener.setOrientation(n.x,n.y,n.z,0,1,0);var o;for(o=0;o-1&&this._engine.scenes.splice(a,1),this._engine.wipeCaches(!0),this._isDisposed=!0},Object.defineProperty(r.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!0,configurable:!0}),r.prototype.disposeSounds=function(){if(this._mainSoundTrack){this.mainSoundTrack.dispose();for(var e=0;e=n.distance))&&(n=c,r)))break}return n||new e.PickingInfo},r.prototype._internalMultiPick=function(t,i){if(!e.PickingInfo)return null;for(var r=new Array,n=0;n0)for(var s=0;s=o.distance))&&(o=l,r))break}}return o||new e.PickingInfo},r.prototype.pick=function(t,i,r,n,o){var s=this;if(!e.PickingInfo)return null;var a=this._internalPick((function(e){return s.createPickingRayToRef(t,i,e,s._tempPickingRay,o||null),s._tempPickingRay}),r,n);return a&&(a.ray=this.createPickingRay(t,i,e.Matrix.Identity(),o||null)),a},r.prototype.pickSprite=function(e,t,i,r,n){return this.createPickingRayInCameraSpaceToRef(e,t,this._tempPickingRay,n),this._internalPickSprites(this._tempPickingRay,i,r,n)},r.prototype.pickWithRay=function(t,i,r){var n=this,o=this._internalPick((function(i){return n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(n._pickWithRayInverseMatrix),n._cachedRayForTransform||(n._cachedRayForTransform=e.Ray.Zero()),e.Ray.TransformToRef(t,n._pickWithRayInverseMatrix,n._cachedRayForTransform),n._cachedRayForTransform}),i,r);return o&&(o.ray=t),o},r.prototype.multiPick=function(e,t,i,r){var n=this;return this._internalMultiPick((function(i){return n.createPickingRay(e,t,i,r||null)}),i)},r.prototype.multiPickWithRay=function(t,i){var r=this;return this._internalMultiPick((function(i){return r._pickWithRayInverseMatrix||(r._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(r._pickWithRayInverseMatrix),r._cachedRayForTransform||(r._cachedRayForTransform=e.Ray.Zero()),e.Ray.TransformToRef(t,r._pickWithRayInverseMatrix,r._cachedRayForTransform),r._cachedRayForTransform}),i)},r.prototype.setPointerOverMesh=function(t){this._pointerOverMesh!==t&&(this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)),this._pointerOverMesh=t,this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)))},r.prototype.getPointerOverMesh=function(){return this._pointerOverMesh},r.prototype.setPointerOverSprite=function(t){this._pointerOverSprite!==t&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=t,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)))},r.prototype.getPointerOverSprite=function(){return this._pointerOverSprite},r.prototype.getPhysicsEngine=function(){return this._physicsEngine},r.prototype.enablePhysics=function(t,i){if(void 0===t&&(t=null),this._physicsEngine)return!0;try{return this._physicsEngine=new e.PhysicsEngine(t,i),!0}catch(t){return e.Tools.Error(t.message),!1}},r.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},r.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},r.prototype.deleteCompoundImpostor=function(e){var t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},r.prototype._rebuildGeometries=function(){for(var e=0,t=this.geometries;e=0&&this._scene.textures.splice(e,1),void 0!==this._texture&&(this.releaseInternalTexture(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear())}},t.prototype.serialize=function(){if(!this.name)return null;var t=e.SerializationHelper.Serialize(this);return e.Animation.AppendSerializedAnimations(this,t),t},t.WhenAllReady=function(e,t){var i=e.length;if(0===i)return void t();for(var r,n,o=0;o0},enumerable:!0,configurable:!0}),r.prototype.getLODLevels=function(){return this._LODLevels},r.prototype._sortLODLevels=function(){this._LODLevels.sort((function(e,t){return e.distancet.distance?-1:0}))},r.prototype.addLODLevel=function(t,i){if(i&&i._masterMesh)return e.Tools.Warn("You cannot use a mesh as LOD level twice"),this;var r=new e.MeshLODLevel(t,i);return this._LODLevels.push(r),i&&(i._masterMesh=this),this._sortLODLevels(),this},r.prototype.getLODLevelAtDistance=function(e){for(var t=0;tr)return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,this._LODLevels[this._LODLevels.length-1].mesh),this;for(var n=0;n0;this.computeWorldMatrix();var a=this.material||o.defaultMaterial;if(a)if(a.storeEffectOnSubMeshes)for(var l=0,c=this.subMeshes;l4,s=o?this.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind):null,a=o?this.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind):null,l=this.skeleton.getTransformMatrices(this),c=e.Tmp.Vector3[0],h=e.Tmp.Matrix[0],u=e.Tmp.Matrix[1],d=0,f=0;f0&&(e.Matrix.FromFloat32ArrayToRefScaled(l,Math.floor(16*r[d+p]),_,u),h.addToSelf(u));if(o)for(p=0;p<4;p++)(_=a[d+p])>0&&(e.Matrix.FromFloat32ArrayToRefScaled(l,Math.floor(16*s[d+p]),_,u),h.addToSelf(u));e.Vector3.TransformCoordinatesFromFloatsToRef(i[f],i[f+1],i[f+2],h,c),c.toArray(i,f)}}return i},r.prototype._createGlobalSubMesh=function(t){var i=this.getTotalVertices();if(!i||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){var r=this.getIndices();if(!r)return null;var n=r.length,o=!1;if(t)o=!0;else for(var s=0,a=this.subMeshes;s=n){o=!0;break}if(l.verticesStart+l.verticesCount>=i){o=!0;break}}if(!o)return this.subMeshes[0]}return this.releaseSubMeshes(),new e.SubMesh(0,0,i,0,this.getTotalIndices(),this)},r.prototype.subdivide=function(t){if(!(t<1)){for(var i=this.getTotalIndices(),r=i/t|0,n=0;r%3!=0;)r++;this.releaseSubMeshes();for(var o=0;o=i);o++)e.SubMesh.CreateFromIndices(0,n,Math.min(r,i-n),this),n+=r;this.synchronizeInstances()}},r.prototype.setVerticesData=function(t,i,r,n){if(void 0===r&&(r=!1),this._geometry)this._geometry.setVerticesData(t,i,r,n);else{var o=new e.VertexData;o.set(i,t);var s=this.getScene();new e.Geometry(e.Geometry.RandomId(),s,o,r,this)}return this},r.prototype.markVerticesDataAsUpdatable=function(e,t){void 0===t&&(t=!0);var i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)},r.prototype.setVerticesBuffer=function(t){return this._geometry||(this._geometry=e.Geometry.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(t),this},r.prototype.updateVerticesData=function(e,t,i,r){return this._geometry?(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this},r.prototype.updateMeshPositions=function(t,i){void 0===i&&(i=!0);var r=this.getVerticesData(e.VertexBuffer.PositionKind);if(!r)return this;if(t(r),this.updateVerticesData(e.VertexBuffer.PositionKind,r,!1,!1),i){var n=this.getIndices(),o=this.getVerticesData(e.VertexBuffer.NormalKind);if(!o)return this;e.VertexData.ComputeNormals(r,n,o),this.updateVerticesData(e.VertexBuffer.NormalKind,o,!1,!1)}return this},r.prototype.makeGeometryUnique=function(){if(!this._geometry)return this;var t=this._geometry,i=this._geometry.copy(e.Geometry.RandomId());return t.releaseForMesh(this,!0),i.applyToMesh(this),this},r.prototype.setIndices=function(t,i,r){if(void 0===i&&(i=null),void 0===r&&(r=!1),this._geometry)this._geometry.setIndices(t,i,r);else{var n=new e.VertexData;n.indices=t;var o=this.getScene();new e.Geometry(e.Geometry.RandomId(),o,n,r,this)}return this},r.prototype.updateIndices=function(e,t){return this._geometry?(this._geometry.updateIndices(e,t),this):this},r.prototype.toLeftHanded=function(){return this._geometry?(this._geometry.toLeftHanded(),this):this},r.prototype._bind=function(t,i,r){if(!this._geometry)return this;var n,o=this.getScene().getEngine();if(this._unIndexed)n=null;else switch(r){case e.Material.PointFillMode:n=null;break;case e.Material.WireFrameFillMode:n=t.getLinesIndexBuffer(this.getIndices(),o);break;default:case e.Material.TriangleFillMode:n=this._unIndexed?null:this._geometry.getIndexBuffer()}return this._geometry._bind(i,n),this},r.prototype._draw=function(t,i,r,n){if(void 0===n&&(n=!1),!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this.onBeforeDrawObservable.notifyObservers(this);var o=this.getScene(),s=o.getEngine();if(this._unIndexed||i==e.Material.PointFillMode?s.drawArraysType(i,t.verticesStart,t.verticesCount,r):i==e.Material.WireFrameFillMode?s.drawElementsType(i,0,t.linesIndexCount,r):s.drawElementsType(i,t.indexStart,t.indexCount,r),o._isAlternateRenderingEnabled&&!n){var a=t.effect||this._effectiveMaterial.getEffect();if(!a||!o.activeCamera)return this;o._switchToAlternateCameraConfiguration(!0),this._effectiveMaterial.bindView(a),this._effectiveMaterial.bindViewProjection(a),s.setViewport(o.activeCamera._alternateCamera.viewport),this._draw(t,i,r,!0),s.setViewport(o.activeCamera.viewport),o._switchToAlternateCameraConfiguration(!1),this._effectiveMaterial.bindView(a),this._effectiveMaterial.bindViewProjection(a)}return this},r.prototype.registerBeforeRender=function(e){return this.onBeforeRenderObservable.add(e),this},r.prototype.unregisterBeforeRender=function(e){return this.onBeforeRenderObservable.removeCallback(e),this},r.prototype.registerAfterRender=function(e){return this.onAfterRenderObservable.add(e),this},r.prototype.unregisterAfterRender=function(e){return this.onAfterRenderObservable.removeCallback(e),this},r.prototype._getInstancesRenderList=function(e){var t=this.getScene();if(this._batchCache.mustReturn=!1,this._batchCache.renderSelf[e]=this.isEnabled()&&this.isVisible,this._batchCache.visibleInstances[e]=null,this._visibleInstances){var i=t.getRenderId(),r=t._isInIntermediateRendering()?this._visibleInstances.intermediateDefaultRenderId:this._visibleInstances.defaultRenderId;this._batchCache.visibleInstances[e]=this._visibleInstances[i];var n=this._renderId;!this._batchCache.visibleInstances[e]&&r&&(this._batchCache.visibleInstances[e]=this._visibleInstances[r],i=Math.max(r,i),n=Math.max(this._visibleInstances.selfDefaultRenderId,i));var o=this._batchCache.visibleInstances[e];if(o&&o.length){if(this._renderIdForInstances[e]===i)return this._batchCache.mustReturn=!0,this._batchCache;i!==n&&(this._batchCache.renderSelf[e]=!1)}this._renderIdForInstances[e]=i}return this._batchCache},r.prototype._renderWithInstances=function(t,i,r,n,o){var s=r.visibleInstances[t._id];if(!s)return this;for(var a=s.length+1,l=16*a*4,c=this._instancesBufferSize,h=this._instancesBuffer;this._instancesBufferSizes-1)&&(h=s-1),c>.001){for(var f=1/c,u=0;u<4;u++)n[l+u]*=f;if(o)for(var u=0;u<4;u++)o[l+u]*=f}else h>=4?(o[l+h-4]=1-c,r[l+h-4]=t):(n[l+h]=1-c,i[l+h]=t)}this.setVerticesData(e.VertexBuffer.MatricesIndicesKind,i),r&&this.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,r),this.setVerticesData(e.VertexBuffer.MatricesWeightsKind,n),o&&this.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,o)}},r.prototype._checkDelayState=function(){var t=this.getScene();return this._geometry?this._geometry.load(t):this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADING,this._queueLoad(t)),this},r.prototype._queueLoad=function(t){var i=this;t._addPendingData(this);var r=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return e.Tools.LoadFile(this.delayLoadingFile,(function(r){r instanceof ArrayBuffer?i._delayLoadingFunction(r,i):i._delayLoadingFunction(JSON.parse(r),i),i.instances.forEach((function(e){e._syncSubMeshes()})),i.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,t._removePendingData(i)}),(function(){}),t.database,r),this},r.prototype.isInFrustum=function(t){return this.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADING&&(!!i.prototype.isInFrustum.call(this,t)&&(this._checkDelayState(),!0))},r.prototype.setMaterialByID=function(e){var t,i=this.getScene().materials;for(t=i.length-1;t>-1;t--)if(i[t].id===e)return this.material=i[t],this;var r=this.getScene().multiMaterials;for(t=r.length-1;t>-1;t--)if(r[t].id===e)return this.material=r[t],this;return this},r.prototype.getAnimatables=function(){var e=new Array;return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e},r.prototype.bakeTransformIntoVertices=function(t){if(!this.isVerticesDataPresent(e.VertexBuffer.PositionKind))return this;var i=this.subMeshes.splice(0);this._resetPointsArrayCache();var r,n=this.getVerticesData(e.VertexBuffer.PositionKind),o=new Array;for(r=0;r-1&&(o.morphTargetManager=i.getMorphTargetManagerById(t.morphTargetManagerId)),t.skeletonId>-1&&(o.skeleton=i.getLastSkeletonByID(t.skeletonId),t.numBoneInfluencers&&(o.numBoneInfluencers=t.numBoneInfluencers)),t.animations){for(var s=0;s4,c=l?this.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind):null,h=l?this.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind):null,u=t.getTransformMatrices(this),d=e.Vector3.Zero(),f=new e.Matrix,p=new e.Matrix,_=0,m=0;m0&&(e.Matrix.FromFloat32ArrayToRefScaled(u,Math.floor(16*o[_+a]),g,p),f.addToSelf(p));if(l)for(a=0;a<4;a++)(g=h[_+a])>0&&(e.Matrix.FromFloat32ArrayToRefScaled(u,Math.floor(16*c[_+a]),g,p),f.addToSelf(p));e.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[m],this._sourcePositions[m+1],this._sourcePositions[m+2],f,d),d.toArray(r,m),e.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[m],this._sourceNormals[m+1],this._sourceNormals[m+2],f,d),d.toArray(n,m),f.reset()}return this.updateVerticesData(e.VertexBuffer.PositionKind,r),this.updateVerticesData(e.VertexBuffer.NormalKind,n),this},r.MinMax=function(t){var i=null,r=null;return t.forEach((function(e,t,n){var o=e.getBoundingInfo(),s=o.boundingBox;i&&r?(i.minimizeInPlace(s.minimumWorld),r.maximizeInPlace(s.maximumWorld)):(i=s.minimumWorld,r=s.maximumWorld)})),i&&r?{min:i,max:r}:{min:e.Vector3.Zero(),max:e.Vector3.Zero()}},r.Center=function(t){var i=t instanceof Array?r.MinMax(t):t;return e.Vector3.Center(i.min,i.max)},r.MergeMeshes=function(t,i,n,o,s){void 0===i&&(i=!0);var a;if(!n){var l=0;for(a=0;a65536)return e.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}var c,h=null,u=new Array,d=null;for(a=0;aa&&(a=h)}return new i(e,s,a-s+1,t,r,n,o)},i})(t);e.SubMesh=i})(r||(r={}));var r,s=this&&this.__assign||Object.assign||function(e){for(var t,i=1,r=arguments.length;i=0&&this._scene.materials.splice(i,1),i=0;ia?a:Math.floor(l);var c,h,u,d,f=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,p=i.uvs,_=i.colors,m=[],g=[],v=[],y=[],b=[],x=[],T=[],E=[],P=[],A=[];if(r.length<2){var M=[],S=[];for(u=0;u0&&(I=C[d].subtract(C[d-1]).length(),w=I+T[h],b[h].push(w),T[h]=w),d++;o&&(d--,m.push(C[0].x,C[0].y,C[0].z),I=C[d].subtract(C[0]).length(),w=I+T[h],b[h].push(w),T[h]=w),P[h]=R+D,A[h]=O,O+=R+D}var L,F,B=null,V=null;for(u=0;u1)?1:i.arc||1,l=i.slice&&i.slice<=0?1:i.slice||1,c=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,h=new e.Vector3(n/2,o/2,s/2),u=2+r,d=2*u,f=[],p=[],_=[],m=[],g=0;g<=u;g++){for(var v=g/u,y=v*Math.PI*l,b=0;b<=d;b++){var x=b/d,T=x*Math.PI*2*a,E=e.Matrix.RotationZ(-y),P=e.Matrix.RotationY(T),A=e.Vector3.TransformCoordinates(e.Vector3.Up(),E),M=e.Vector3.TransformCoordinates(A,P),S=M.multiply(h),C=M.divide(h).normalize();p.push(S.x,S.y,S.z),_.push(C.x,C.y,C.z),m.push(x,v)}if(g>0)for(var R=p.length/3,O=R-2*(d+1);O+d+21)?1:i.arc||1,d=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,f=i.faceUV||new Array(3),p=i.faceColors,_=1!==u&&h?2:0,m=c?l:1,g=2+(1+_)*m;for(r=0;r0&&(i.push(a-1),i.push(a)),a++}var d=new t;return d.indices=i,d.positions=r,o&&(d.colors=s),d},t.CreateDashedLines=function(i){var r=i.dashSize||3,n=i.gapSize||1,o=i.dashNb||200,s=i.points,a=new Array,l=new Array,c=e.Vector3.Zero(),h=0,u=0,d=0,f=0,p=0,_=0,m=0;for(m=0;m1)?1:i.arc||1,h=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE;r.push(0,0,0),s.push(.5,.5);for(var u=2*Math.PI*c,d=u/l,f=0;f=r.length)?0:i.type||0,u=i.size,d=i.sizeX||u||1,f=i.sizeY||u||1,p=i.sizeZ||u||1,_=i.custom||r[h],m=_.face.length,g=i.faceUV||new Array(m),v=i.faceColors,y=void 0===i.flat||i.flat,b=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,x=new Array,T=new Array,E=new Array,P=new Array,A=new Array,M=0,S=0,C=new Array,R=0,O=0;if(y)for(O=0;On.bbSize.y?n.bbSize.x:n.bbSize.y;$=$>n.bbSize.z?$:n.bbSize.z,w=n.subDiv.X*O/n.bbSize.x,L=n.subDiv.Y*O/n.bbSize.y,F=n.subDiv.Z*O/n.bbSize.z,B=n.subDiv.max*n.subDiv.max,n.facetPartitioning.length=0}for(o=0;o0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),this._indexBuffer&&(this._indexBuffer.references=i)},t.prototype.notifyUpdate=function(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e);for(var t=0,i=this._meshes;t0){for(var i=0;i0){for(var i=0;i0){for(var i=0;i0){var l=new Float32Array(i,a.positionsAttrDesc.offset,a.positionsAttrDesc.count);r.setVerticesData(e.VertexBuffer.PositionKind,l,!1)}if(a.normalsAttrDesc&&a.normalsAttrDesc.count>0){var c=new Float32Array(i,a.normalsAttrDesc.offset,a.normalsAttrDesc.count);r.setVerticesData(e.VertexBuffer.NormalKind,c,!1)}if(a.tangetsAttrDesc&&a.tangetsAttrDesc.count>0){var h=new Float32Array(i,a.tangetsAttrDesc.offset,a.tangetsAttrDesc.count);r.setVerticesData(e.VertexBuffer.TangentKind,h,!1)}if(a.uvsAttrDesc&&a.uvsAttrDesc.count>0){var u=new Float32Array(i,a.uvsAttrDesc.offset,a.uvsAttrDesc.count);r.setVerticesData(e.VertexBuffer.UVKind,u,!1)}if(a.uvs2AttrDesc&&a.uvs2AttrDesc.count>0){var d=new Float32Array(i,a.uvs2AttrDesc.offset,a.uvs2AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV2Kind,d,!1)}if(a.uvs3AttrDesc&&a.uvs3AttrDesc.count>0){var f=new Float32Array(i,a.uvs3AttrDesc.offset,a.uvs3AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV3Kind,f,!1)}if(a.uvs4AttrDesc&&a.uvs4AttrDesc.count>0){var p=new Float32Array(i,a.uvs4AttrDesc.offset,a.uvs4AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV4Kind,p,!1)}if(a.uvs5AttrDesc&&a.uvs5AttrDesc.count>0){var _=new Float32Array(i,a.uvs5AttrDesc.offset,a.uvs5AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV5Kind,_,!1)}if(a.uvs6AttrDesc&&a.uvs6AttrDesc.count>0){var m=new Float32Array(i,a.uvs6AttrDesc.offset,a.uvs6AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV6Kind,m,!1)}if(a.colorsAttrDesc&&a.colorsAttrDesc.count>0){var g=new Float32Array(i,a.colorsAttrDesc.offset,a.colorsAttrDesc.count);r.setVerticesData(e.VertexBuffer.ColorKind,g,!1,a.colorsAttrDesc.stride)}if(a.matricesIndicesAttrDesc&&a.matricesIndicesAttrDesc.count>0){for(var v=new Int32Array(i,a.matricesIndicesAttrDesc.offset,a.matricesIndicesAttrDesc.count),y=[],b=0;b>8),y.push((16711680&x)>>16),y.push(x>>24)}r.setVerticesData(e.VertexBuffer.MatricesIndicesKind,y,!1)}if(a.matricesWeightsAttrDesc&&a.matricesWeightsAttrDesc.count>0){var T=new Float32Array(i,a.matricesWeightsAttrDesc.offset,a.matricesWeightsAttrDesc.count);r.setVerticesData(e.VertexBuffer.MatricesWeightsKind,T,!1)}if(a.indicesAttrDesc&&a.indicesAttrDesc.count>0){var E=new Int32Array(i,a.indicesAttrDesc.offset,a.indicesAttrDesc.count);r.setIndices(E,null)}if(a.subMeshesAttrDesc&&a.subMeshesAttrDesc.count>0){var P=new Int32Array(i,a.subMeshesAttrDesc.offset,5*a.subMeshesAttrDesc.count);r.subMeshes=[];for(var b=0;b>8),y.push((16711680&O)>>16),y.push(O>>24)}r.setVerticesData(e.VertexBuffer.MatricesIndicesKind,y,i.matricesIndices._updatable)}if(i.matricesIndicesExtra)if(i.matricesIndicesExtra._isExpanded)delete i.matricesIndices._isExpanded,r.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,i.matricesIndicesExtra,i.matricesIndicesExtra._updatable);else{for(var y=[],b=0;b>8),y.push((16711680&O)>>16),y.push(O>>24)}r.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,y,i.matricesIndicesExtra._updatable)}i.matricesWeights&&(t._CleanMatricesWeights(i,r),r.setVerticesData(e.VertexBuffer.MatricesWeightsKind,i.matricesWeights,i.matricesWeights._updatable)),i.matricesWeightsExtra&&r.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,i.matricesWeightsExtra,i.matricesWeights._updatable),r.setIndices(i.indices,null)}if(i.subMeshes){r.subMeshes=[];for(var D=0;D-1){var n=i.getScene().getLastSkeletonByID(t.skeletonId);if(n){r=n.bones.length;for(var o=i.getVerticesData(e.VertexBuffer.MatricesIndicesKind),s=i.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind),a=t.matricesWeights,l=t.matricesWeightsExtra,c=t.numBoneInfluencer,h=a.length,u=0;uc-1)&&(f=c-1),d>.001){for(var m=1/d,p=0;p<4;p++)a[u+p]*=m;if(l)for(var p=0;p<4;p++)l[u+p]*=m}else f>=4?(l[u+f-4]=1-d,s[u+f-4]=r):(a[u+f]=1-d,o[u+f]=r)}i.setVerticesData(e.VertexBuffer.MatricesIndicesKind,o),t.matricesWeightsExtra&&i.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,s)}}}},t.Parse=function(i,r,n){if(r.getGeometryByID(i.id))return null;var o=new t(i.id,r,void 0,i.updatable);return e.Tags&&e.Tags.AddTagsTo(o,i.tags),i.delayLoadingFile?(o.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED,o.delayLoadingFile=n+i.delayLoadingFile,o._boundingInfo=new e.BoundingInfo(e.Vector3.FromArray(i.boundingBoxMinimum),e.Vector3.FromArray(i.boundingBoxMaximum)),o._delayInfo=[],i.hasUVs&&o._delayInfo.push(e.VertexBuffer.UVKind),i.hasUVs2&&o._delayInfo.push(e.VertexBuffer.UV2Kind),i.hasUVs3&&o._delayInfo.push(e.VertexBuffer.UV3Kind),i.hasUVs4&&o._delayInfo.push(e.VertexBuffer.UV4Kind),i.hasUVs5&&o._delayInfo.push(e.VertexBuffer.UV5Kind),i.hasUVs6&&o._delayInfo.push(e.VertexBuffer.UV6Kind),i.hasColors&&o._delayInfo.push(e.VertexBuffer.ColorKind),i.hasMatricesIndices&&o._delayInfo.push(e.VertexBuffer.MatricesIndicesKind),i.hasMatricesWeights&&o._delayInfo.push(e.VertexBuffer.MatricesWeightsKind),o._delayLoadingFunction=e.VertexData.ImportVertexData):e.VertexData.ImportVertexData(i,o),r.pushGeometry(o,!0),o},t})();e.Geometry=t;var i=(function(e){function t(t,i,r,n){void 0===r&&(r=!1),void 0===n&&(n=null);var o=e.call(this,t,i,void 0,!1,n)||this;return o._canBeRegenerated=r,o._beingRegenerated=!0,o.regenerate(),o._beingRegenerated=!1,o}return o(t,e),t.prototype.canBeRegenerated=function(){return this._canBeRegenerated},t.prototype.regenerate=function(){this._canBeRegenerated&&(this._beingRegenerated=!0,this.setAllVerticesData(this._regenerateVertexData(),!1),this._beingRegenerated=!1)},t.prototype.asNewGeometry=function(t){return e.prototype.copy.call(this,t)},t.prototype.setAllVerticesData=function(t,i){this._beingRegenerated&&e.prototype.setAllVerticesData.call(this,t,!1)},t.prototype.setVerticesData=function(t,i,r){this._beingRegenerated&&e.prototype.setVerticesData.call(this,t,i,!1)},t.prototype._regenerateVertexData=function(){throw new Error("Abstract method")},t.prototype.copy=function(e){throw new Error("Must be overriden in sub-classes.")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.canBeRegenerated=this.canBeRegenerated(),t},t})(t);e._PrimitiveGeometry=i;var r=(function(t){function i(i,r,n,o,s,a,l,c,h){void 0===h&&(h=e.Mesh.DEFAULTSIDE);var u=t.call(this,i,r,l,c)||this;return u.pathArray=n,u.closeArray=o,u.closePath=s,u.offset=a,u.side=h,u}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateRibbon({pathArray:this.pathArray,closeArray:this.closeArray,closePath:this.closePath,offset:this.offset,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.pathArray,this.closeArray,this.closePath,this.offset,this.canBeRegenerated(),void 0,this.side)},i})(i);e.RibbonGeometry=r;var n=(function(t){function i(i,r,n,o,s,a){void 0===s&&(s=null),void 0===a&&(a=e.Mesh.DEFAULTSIDE);var l=t.call(this,i,r,o,s)||this;return l.size=n,l.side=a,l}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateBox({size:this.size,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.size,this.canBeRegenerated(),void 0,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.size=this.size,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.size,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.BoxGeometry=n;var s=(function(t){function i(i,r,n,o,s,a,l){void 0===a&&(a=null),void 0===l&&(l=e.Mesh.DEFAULTSIDE);var c=t.call(this,i,r,s,a)||this;return c.segments=n,c.diameter=o,c.side=l,c}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateSphere({segments:this.segments,diameter:this.diameter,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.segments,this.diameter,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.segments=this.segments,e.diameter=this.diameter,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.segments,t.diameter,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.SphereGeometry=s;var a=(function(t){function i(i,r,n,o,s,a,l){void 0===a&&(a=null),void 0===l&&(l=e.Mesh.DEFAULTSIDE);var c=t.call(this,i,r,s,a)||this;return c.radius=n,c.tessellation=o,c.side=l,c}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateDisc({radius:this.radius,tessellation:this.tessellation,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.radius,this.tessellation,this.canBeRegenerated(),null,this.side)},i})(i);e.DiscGeometry=a;var l=(function(t){function i(i,r,n,o,s,a,l,c,h,u){void 0===l&&(l=1),void 0===h&&(h=null),void 0===u&&(u=e.Mesh.DEFAULTSIDE);var d=t.call(this,i,r,c,h)||this;return d.height=n,d.diameterTop=o,d.diameterBottom=s,d.tessellation=a,d.subdivisions=l,d.side=u,d}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateCylinder({height:this.height,diameterTop:this.diameterTop,diameterBottom:this.diameterBottom,tessellation:this.tessellation,subdivisions:this.subdivisions,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.height,this.diameterTop,this.diameterBottom,this.tessellation,this.subdivisions,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.height=this.height,e.diameterTop=this.diameterTop,e.diameterBottom=this.diameterBottom,e.tessellation=this.tessellation,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.height,t.diameterTop,t.diameterBottom,t.tessellation,t.subdivisions,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.CylinderGeometry=l -;var c=(function(t){function i(i,r,n,o,s,a,l,c){void 0===l&&(l=null),void 0===c&&(c=e.Mesh.DEFAULTSIDE);var h=t.call(this,i,r,a,l)||this;return h.diameter=n,h.thickness=o,h.tessellation=s,h.side=c,h}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorus({diameter:this.diameter,thickness:this.thickness,tessellation:this.tessellation,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.diameter,this.thickness,this.tessellation,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.diameter=this.diameter,e.thickness=this.thickness,e.tessellation=this.tessellation,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.diameter,t.thickness,t.tessellation,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.TorusGeometry=c;var h=(function(t){function i(e,i,r,n,o,s,a){void 0===a&&(a=null);var l=t.call(this,e,i,s,a)||this;return l.width=r,l.height=n,l.subdivisions=o,l}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateGround({width:this.width,height:this.height,subdivisions:this.subdivisions})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.width,this.height,this.subdivisions,this.canBeRegenerated(),null)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.width=this.width,e.height=this.height,e.subdivisions=this.subdivisions,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.width,t.height,t.subdivisions,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.GroundGeometry=h;var u=(function(t){function i(e,i,r,n,o,s,a,l,c,h){void 0===h&&(h=null);var u=t.call(this,e,i,c,h)||this;return u.xmin=r,u.zmin=n,u.xmax=o,u.zmax=s,u.subdivisions=a,u.precision=l,u}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTiledGround({xmin:this.xmin,zmin:this.zmin,xmax:this.xmax,zmax:this.zmax,subdivisions:this.subdivisions,precision:this.precision})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.xmin,this.zmin,this.xmax,this.zmax,this.subdivisions,this.precision,this.canBeRegenerated(),null)},i})(i);e.TiledGroundGeometry=u;var d=(function(t){function i(i,r,n,o,s,a){void 0===s&&(s=null),void 0===a&&(a=e.Mesh.DEFAULTSIDE);var l=t.call(this,i,r,o,s)||this;return l.size=n,l.side=a,l}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreatePlane({size:this.size,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.size,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.size=this.size,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.size,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.PlaneGeometry=d;var f=(function(t){function i(i,r,n,o,s,a,l,c,h,u,d){void 0===u&&(u=null),void 0===d&&(d=e.Mesh.DEFAULTSIDE);var f=t.call(this,i,r,h,u)||this;return f.radius=n,f.tube=o,f.radialSegments=s,f.tubularSegments=a,f.p=l,f.q=c,f.side=d,f}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorusKnot({radius:this.radius,tube:this.tube,radialSegments:this.radialSegments,tubularSegments:this.tubularSegments,p:this.p,q:this.q,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.radius,this.tube,this.radialSegments,this.tubularSegments,this.p,this.q,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.radius=this.radius,e.tube=this.tube,e.radialSegments=this.radialSegments,e.tubularSegments=this.tubularSegments,e.p=this.p,e.q=this.q,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.radius,t.tube,t.radialSegments,t.tubularSegments,t.p,t.q,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.TorusKnotGeometry=f})(r||(r={}));var r;!(function(e){var t=(function(){function t(e){void 0===e&&(e=30),this._enabled=!0,this._rollingFrameTime=new i(e)}return t.prototype.sampleFrame=function(t){if(void 0===t&&(t=e.Tools.Now),this._enabled){if(null!=this._lastFrameTimeMs){var i=t-this._lastFrameTimeMs;this._rollingFrameTime.add(i)}this._lastFrameTimeMs=t}},Object.defineProperty(t.prototype,"averageFrameTime",{get:function(){return this._rollingFrameTime.average},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"averageFrameTimeVariance",{get:function(){return this._rollingFrameTime.variance},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"instantaneousFrameTime",{get:function(){return this._rollingFrameTime.history(0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"averageFPS",{get:function(){return 1e3/this._rollingFrameTime.average},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"instantaneousFPS",{get:function(){var e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isSaturated",{get:function(){return this._rollingFrameTime.isSaturated()},enumerable:!0,configurable:!0}),t.prototype.enable=function(){this._enabled=!0},t.prototype.disable=function(){this._enabled=!1,this._lastFrameTimeMs=null},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._enabled},enumerable:!0,configurable:!0}),t.prototype.reset=function(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()},t})();e.PerformanceMonitor=t;var i=(function(){function e(e){this._samples=new Array(e),this.reset()}return e.prototype.add=function(e){var t;if(this.isSaturated()){var i=this._samples[this._pos];t=i-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(i-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length},e.prototype.history=function(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;var t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]},e.prototype.isSaturated=function(){return this._sampleCount>=this._samples.length},e.prototype.reset=function(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0},e.prototype._wrapPosition=function(e){var t=this._samples.length;return(e%t+t)%t},e})();e.RollingAverage=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.BindEyePosition=function(e,t){if(t._forcedViewPosition)return void e.setVector3("vEyePosition",t._forcedViewPosition);e.setVector3("vEyePosition",t._mirroredCameraPosition?t._mirroredCameraPosition:t.activeCamera.globalPosition)},t.PrepareDefinesForMergedUV=function(e,t,i){t._needUVs=!0,t[i]=!0,e.getTextureMatrix().isIdentity(!0)?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,0===e.coordinatesIndex?t.MAINUV1=!0:t.MAINUV2=!0):t[i+"DIRECTUV"]=0},t.BindTextureMatrix=function(e,t,i){var r=e.getTextureMatrix();r.isIdentity(!0)||t.updateMatrix(i+"Matrix",r)},t.PrepareDefinesForMisc=function(t,i,r,n,o,s,a){a._areMiscDirty&&(a.LOGARITHMICDEPTH=r,a.POINTSIZE=n,a.FOG=i.fogEnabled&&t.applyFog&&i.fogMode!==e.Scene.FOGMODE_NONE&&o,a.NONUNIFORMSCALING=t.nonUniformScaling,a.ALPHATEST=s)},t.PrepareDefinesForFrameBoundValues=function(e,t,i,r,n){void 0===n&&(n=null);var o=!1;null==n&&(n=void 0!==e.clipPlane&&null!==e.clipPlane),i.CLIPPLANE!==n&&(i.CLIPPLANE=n,o=!0),i.DEPTHPREPASS!==!t.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==r&&(i.INSTANCES=r,o=!0),o&&i.markAsUnprocessed()},t.PrepareDefinesForAttributes=function(t,i,r,n,o,s){if(void 0===o&&(o=!1),void 0===s&&(s=!0),!i._areAttributesDirty&&i._needNormals===i._normals&&i._needUVs===i._uvs)return!1;if(i._normals=i._needNormals,i._uvs=i._needUVs,i.NORMAL=i._needNormals&&t.isVerticesDataPresent(e.VertexBuffer.NormalKind),i._needNormals&&t.isVerticesDataPresent(e.VertexBuffer.TangentKind)&&(i.TANGENT=!0),i._needUVs?(i.UV1=t.isVerticesDataPresent(e.VertexBuffer.UVKind),i.UV2=t.isVerticesDataPresent(e.VertexBuffer.UV2Kind)):(i.UV1=!1,i.UV2=!1),r){var a=t.useVertexColors&&t.isVerticesDataPresent(e.VertexBuffer.ColorKind);i.VERTEXCOLOR=a,i.VERTEXALPHA=t.hasVertexAlpha&&a&&s}if(n&&(t.useBones&&t.computeBonesUsingShaders&&t.skeleton?(i.NUM_BONE_INFLUENCERS=t.numBoneInfluencers,i.BonesPerMesh=t.skeleton.bones.length+1):(i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0)),o){var l=t.morphTargetManager;l?(i.MORPHTARGETS_TANGENT=l.supportsTangents&&i.TANGENT,i.MORPHTARGETS_NORMAL=l.supportsNormals&&i.NORMAL,i.MORPHTARGETS=l.numInfluencers>0,i.NUM_MORPH_INFLUENCERS=l.numInfluencers):(i.MORPHTARGETS_TANGENT=!1,i.MORPHTARGETS_NORMAL=!1,i.MORPHTARGETS=!1,i.NUM_MORPH_INFLUENCERS=0)}return!0},t.PrepareDefinesForLights=function(t,i,r,n,o,s){if(void 0===o&&(o=4),void 0===s&&(s=!1),!r._areLightsDirty)return r._needNormals;var a=0,l=!1,c=!1,h=!1,u=!1,d=!1;if(t.lightsEnabled&&!s)for(var f=0,p=i._lightSources;f0&&(u=!0,m.prepareDefines(r,a))}}if(_.lightmapMode!=e.Light.LIGHTMAP_DEFAULT?(h=!0,r["LIGHTMAPEXCLUDED"+a]=!0,r["LIGHTMAPNOSPECULAR"+a]=_.lightmapMode==e.Light.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+a]=!1,r["LIGHTMAPNOSPECULAR"+a]=!1),++a===o)break}r.SPECULARTERM=d,r.SHADOWS=u;for(var v=a;v0&&(n=r+o,t.addFallback(n,"LIGHT"+o)),e.SHADOWS||(e["SHADOW"+o]&&t.addFallback(r,"SHADOW"+o),e["SHADOWPCF"+o]&&t.addFallback(r,"SHADOWPCF"+o),e["SHADOWPCSS"+o]&&t.addFallback(r,"SHADOWPCSS"+o),e["SHADOWPOISSON"+o]&&t.addFallback(r,"SHADOWPOISSON"+o),e["SHADOWESM"+o]&&t.addFallback(r,"SHADOWESM"+o));return n++},t.PrepareAttributesForMorphTargets=function(t,i,r){var n=r.NUM_MORPH_INFLUENCERS;if(n>0&&e.Engine.LastCreatedEngine)for(var o=e.Engine.LastCreatedEngine.getCaps().maxVertexAttribs,s=i.morphTargetManager,a=s&&s.supportsNormals&&r.NORMAL,l=s&&s.supportsTangents&&r.TANGENT,c=0;co&&e.Tools.Error("Cannot add more vertex attributes for mesh "+i.name)},t.PrepareAttributesForBones=function(t,i,r,n){r.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,i),t.push(e.VertexBuffer.MatricesIndicesKind),t.push(e.VertexBuffer.MatricesWeightsKind),r.NUM_BONE_INFLUENCERS>4&&(t.push(e.VertexBuffer.MatricesIndicesExtraKind),t.push(e.VertexBuffer.MatricesWeightsExtraKind)))},t.PrepareAttributesForInstances=function(e,t){t.INSTANCES&&(e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"))},t.BindLightShadow=function(e,t,i,r,n){if(e.shadowEnabled&&i.receiveShadows){var o=e.getShadowGenerator();o&&o.bindShadowLight(r,n)}},t.BindLightProperties=function(e,t,i){e.transferToEffect(t,i+"")},t.BindLights=function(i,r,n,o,s,a){void 0===s&&(s=4),void 0===a&&(a=!1);for(var l=Math.min(r._lightSources.length,s),c=0;c0,a.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,a.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===e.Texture.INVCUBIC_MODE,a.REFLECTIONMAP_3D=this._reflectionTexture.isCube,this._reflectionTexture.coordinatesMode){case e.Texture.EXPLICIT_MODE:a.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case e.Texture.PLANAR_MODE:a.setReflectionMode("REFLECTIONMAP_PLANAR");break;case e.Texture.PROJECTION_MODE:a.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case e.Texture.SKYBOX_MODE:a.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case e.Texture.SPHERICAL_MODE:a.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case e.Texture.EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:default:a.setReflectionMode("REFLECTIONMAP_CUBIC")}a.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else a.REFLECTION=!1;if(this._emissiveTexture&&r.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,a,"EMISSIVE")}else a.EMISSIVE=!1;if(this._lightmapTexture&&r.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,a,"LIGHTMAP"),a.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap}else a.LIGHTMAP=!1;if(this._specularTexture&&r.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture,a,"SPECULAR"),a.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else a.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&r.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,a,"BUMP"),a.PARALLAX=this._useParallax,a.PARALLAXOCCLUSION=this._useParallaxOcclusion,a.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else a.BUMP=!1;if(this._refractionTexture&&r.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;a._needUVs=!0,a.REFRACTION=!0,a.REFRACTIONMAP_3D=this._refractionTexture.isCube}else a.REFRACTION=!1;a.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else a.DIFFUSE=!1,a.AMBIENT=!1,a.OPACITY=!1,a.REFLECTION=!1,a.EMISSIVE=!1,a.LIGHTMAP=!1,a.BUMP=!1,a.REFRACTION=!1;a.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),a.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,a.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,a.SPECULAROVERALPHA=this._useSpecularOverAlpha,a.PREMULTIPLYALPHA=this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED||this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF}if(a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a),a.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,a.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if(a._areFresnelDirty&&(r.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(a.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,a.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,a.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,a.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,a.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,a.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,a._needNormals=!0,a.FRESNEL=!0):a.FRESNEL=!1),e.MaterialHelper.PrepareDefinesForMisc(i,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(i),a),e.MaterialHelper.PrepareDefinesForAttributes(i,a,!0,!0,!0),e.MaterialHelper.PrepareDefinesForFrameBoundValues(s,l,a,o),a.isDirty){a.markAsProcessed(),s.resetCachedMaterial();var c=new e.EffectFallbacks;a.REFLECTION&&c.addFallback(0,"REFLECTION"),a.SPECULAR&&c.addFallback(0,"SPECULAR"),a.BUMP&&c.addFallback(0,"BUMP"),a.PARALLAX&&c.addFallback(1,"PARALLAX"),a.PARALLAXOCCLUSION&&c.addFallback(0,"PARALLAXOCCLUSION"),a.SPECULAROVERALPHA&&c.addFallback(0,"SPECULAROVERALPHA"),a.FOG&&c.addFallback(1,"FOG"),a.POINTSIZE&&c.addFallback(0,"POINTSIZE"),a.LOGARITHMICDEPTH&&c.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(a,c,this._maxSimultaneousLights),a.SPECULARTERM&&c.addFallback(0,"SPECULARTERM"),a.DIFFUSEFRESNEL&&c.addFallback(1,"DIFFUSEFRESNEL"),a.OPACITYFRESNEL&&c.addFallback(2,"OPACITYFRESNEL"),a.REFLECTIONFRESNEL&&c.addFallback(3,"REFLECTIONFRESNEL"),a.EMISSIVEFRESNEL&&c.addFallback(4,"EMISSIVEFRESNEL"),a.FRESNEL&&c.addFallback(4,"FRESNEL");var h=[e.VertexBuffer.PositionKind];a.NORMAL&&h.push(e.VertexBuffer.NormalKind),a.UV1&&h.push(e.VertexBuffer.UVKind),a.UV2&&h.push(e.VertexBuffer.UV2Kind),a.VERTEXCOLOR&&h.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(h,i,a,c),e.MaterialHelper.PrepareAttributesForInstances(h,a),e.MaterialHelper.PrepareAttributesForMorphTargets(h,i,a);var u="default",d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff"],f=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler"],p=["Material","Scene"];e.ImageProcessingConfiguration&&(e.ImageProcessingConfiguration.PrepareUniforms(d,a),e.ImageProcessingConfiguration.PrepareSamplers(f,a)),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:a,maxSimultaneousLights:this._maxSimultaneousLights}),this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,d,p,f,a));var _=a.toString();n.setEffect(s.getEngine().createEffect(u,{attributes:h,uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:_,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:a.NUM_MORPH_INFLUENCERS}},l),a),this.buildUniformLayout()}return!(!n.effect||!n.effect.isReady())&&(a._renderId=s.getRenderId(),this._wasPreviouslyReady=!0,!0)},r.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("diffuseLeftColor",4),this._uniformBuffer.addUniform("diffuseRightColor",4),this._uniformBuffer.addUniform("opacityParts",4),this._uniformBuffer.addUniform("reflectionLeftColor",4),this._uniformBuffer.addUniform("reflectionRightColor",4),this._uniformBuffer.addUniform("refractionLeftColor",4),this._uniformBuffer.addUniform("refractionRightColor",4),this._uniformBuffer.addUniform("emissiveLeftColor",4),this._uniformBuffer.addUniform("emissiveRightColor",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vAmbientInfos",2),this._uniformBuffer.addUniform("vOpacityInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("vReflectionPosition",3),this._uniformBuffer.addUniform("vReflectionSize",3),this._uniformBuffer.addUniform("vEmissiveInfos",2),this._uniformBuffer.addUniform("vLightmapInfos",2),this._uniformBuffer.addUniform("vSpecularInfos",2),this._uniformBuffer.addUniform("vBumpInfos",3), -this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("ambientMatrix",16),this._uniformBuffer.addUniform("opacityMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("emissiveMatrix",16),this._uniformBuffer.addUniform("lightmapMatrix",16),this._uniformBuffer.addUniform("specularMatrix",16),this._uniformBuffer.addUniform("bumpMatrix",16),this._uniformBuffer.addUniform("vTangentSpaceParams",2),this._uniformBuffer.addUniform("refractionMatrix",16),this._uniformBuffer.addUniform("vRefractionInfos",4),this._uniformBuffer.addUniform("vSpecularColor",4),this._uniformBuffer.addUniform("vEmissiveColor",3),this._uniformBuffer.addUniform("vDiffuseColor",4),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.create()},r.prototype.unbind=function(){if(this._activeEffect){var e=!1;this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&(this._activeEffect.setTexture("reflection2DSampler",null),e=!0),this._refractionTexture&&this._refractionTexture.isRenderTarget&&(this._activeEffect.setTexture("refraction2DSampler",null),e=!0),e&&this._markAllSubMeshesAsTexturesDirty()}i.prototype.unbind.call(this)},r.prototype.bindForSubMesh=function(t,i,n){var o=this.getScene(),s=n._materialDefines;if(s){var a=n.effect;if(a){this._activeEffect=a,this.bindOnlyWorldMatrix(t),s.OBJECTSPACE_NORMALMAP&&(t.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var l=this._mustRebind(o,a,i.visibility);if(e.MaterialHelper.BindBonesParameters(i,a),l){if(this._uniformBuffer.bindToEffect(a,"Material"),this.bindViewProjection(a),!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync){if(r.FresnelEnabled&&s.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),this._uniformBuffer.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&this._uniformBuffer.updateColor4("opacityParts",new e.Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),this._uniformBuffer.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),this._uniformBuffer.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),this._uniformBuffer.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),o.texturesEnabled){if(this._diffuseTexture&&r.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),e.MaterialHelper.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse"),this._diffuseTexture.hasAlpha&&a.setFloat("alphaCutOff",this.alphaCutOff)),this._ambientTexture&&r.AmbientTextureEnabled&&(this._uniformBuffer.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),e.MaterialHelper.BindTextureMatrix(this._ambientTexture,this._uniformBuffer,"ambient")),this._opacityTexture&&r.OpacityTextureEnabled&&(this._uniformBuffer.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),e.MaterialHelper.BindTextureMatrix(this._opacityTexture,this._uniformBuffer,"opacity")),this._reflectionTexture&&r.ReflectionTextureEnabled&&(this._uniformBuffer.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),this._uniformBuffer.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){var c=this._reflectionTexture;this._uniformBuffer.updateVector3("vReflectionPosition",c.boundingBoxPosition),this._uniformBuffer.updateVector3("vReflectionSize",c.boundingBoxSize)}if(this._emissiveTexture&&r.EmissiveTextureEnabled&&(this._uniformBuffer.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),e.MaterialHelper.BindTextureMatrix(this._emissiveTexture,this._uniformBuffer,"emissive")),this._lightmapTexture&&r.LightmapTextureEnabled&&(this._uniformBuffer.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),e.MaterialHelper.BindTextureMatrix(this._lightmapTexture,this._uniformBuffer,"lightmap")),this._specularTexture&&r.SpecularTextureEnabled&&(this._uniformBuffer.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),e.MaterialHelper.BindTextureMatrix(this._specularTexture,this._uniformBuffer,"specular")),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&r.BumpTextureEnabled&&(this._uniformBuffer.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),e.MaterialHelper.BindTextureMatrix(this._bumpTexture,this._uniformBuffer,"bump"),o._mirroredCameraPosition?this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&r.RefractionTextureEnabled){var h=1;this._refractionTexture.isCube||(this._uniformBuffer.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(h=this._refractionTexture.depth)),this._uniformBuffer.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,h,this.invertRefractionY?-1:1)}}this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.SPECULARTERM&&this._uniformBuffer.updateColor4("vSpecularColor",this.specularColor,this.specularPower),this._uniformBuffer.updateColor3("vEmissiveColor",this.emissiveColor),this._uniformBuffer.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha*i.visibility)}if(o.texturesEnabled&&(this._diffuseTexture&&r.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&r.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&r.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&r.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&r.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&r.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&r.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&r.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&r.RefractionTextureEnabled)){var h=1;this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture)}e.MaterialHelper.BindClipPlane(a,o),o.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),e.MaterialHelper.BindEyePosition(a,o),a.setColor3("vAmbientColor",this._globalAmbientColor)}!l&&this.isFrozen||(o.lightsEnabled&&!this._disableLighting&&e.MaterialHelper.BindLights(o,i,a,s,this._maxSimultaneousLights),(o.fogEnabled&&i.applyFog&&o.fogMode!==e.Scene.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture)&&this.bindView(a),e.MaterialHelper.BindFogParameters(o,i,a),s.NUM_MORPH_INFLUENCERS&&e.MaterialHelper.BindMorphTargetParameters(i,a),e.MaterialHelper.BindLogDepth(s,a,o),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(i,this._activeEffect)}}},r.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e},r.prototype.getActiveTextures=function(){var e=i.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e},r.prototype.hasTexture=function(e){return!!i.prototype.hasTexture.call(this,e)||(this._diffuseTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._emissiveTexture===e||(this._specularTexture===e||(this._bumpTexture===e||(this._lightmapTexture===e||this._refractionTexture===e))))))))},r.prototype.dispose=function(e,t){t&&(this._diffuseTexture&&this._diffuseTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._specularTexture&&this._specularTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),i.prototype.dispose.call(this,e,t)},r.prototype.clone=function(t){var i=this,n=e.SerializationHelper.Clone((function(){return new r(t,i.getScene())}),this);return n.name=t,n.id=t,n},r.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},r.Parse=function(t,i,n){return e.SerializationHelper.Parse((function(){return new r(t.name,i)}),t,i,n)},Object.defineProperty(r,"DiffuseTextureEnabled",{get:function(){return r._DiffuseTextureEnabled},set:function(t){r._DiffuseTextureEnabled!==t&&(r._DiffuseTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"AmbientTextureEnabled",{get:function(){return r._AmbientTextureEnabled},set:function(t){r._AmbientTextureEnabled!==t&&(r._AmbientTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"OpacityTextureEnabled",{get:function(){return r._OpacityTextureEnabled},set:function(t){r._OpacityTextureEnabled!==t&&(r._OpacityTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"ReflectionTextureEnabled",{get:function(){return r._ReflectionTextureEnabled},set:function(t){r._ReflectionTextureEnabled!==t&&(r._ReflectionTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"EmissiveTextureEnabled",{get:function(){return r._EmissiveTextureEnabled},set:function(t){r._EmissiveTextureEnabled!==t&&(r._EmissiveTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"SpecularTextureEnabled",{get:function(){return r._SpecularTextureEnabled},set:function(t){r._SpecularTextureEnabled!==t&&(r._SpecularTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"BumpTextureEnabled",{get:function(){return r._BumpTextureEnabled},set:function(t){r._BumpTextureEnabled!==t&&(r._BumpTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"LightmapTextureEnabled",{get:function(){return r._LightmapTextureEnabled},set:function(t){r._LightmapTextureEnabled!==t&&(r._LightmapTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"RefractionTextureEnabled",{get:function(){return r._RefractionTextureEnabled},set:function(t){r._RefractionTextureEnabled!==t&&(r._RefractionTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"ColorGradingTextureEnabled",{get:function(){return r._ColorGradingTextureEnabled},set:function(t){r._ColorGradingTextureEnabled!==t&&(r._ColorGradingTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"FresnelEnabled",{get:function(){return r._FresnelEnabled},set:function(t){r._FresnelEnabled!==t&&(r._FresnelEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.FresnelDirtyFlag))},enumerable:!0,configurable:!0}),r._DiffuseTextureEnabled=!0,r._AmbientTextureEnabled=!0,r._OpacityTextureEnabled=!0,r._ReflectionTextureEnabled=!0,r._EmissiveTextureEnabled=!0,r._SpecularTextureEnabled=!0,r._BumpTextureEnabled=!0,r._LightmapTextureEnabled=!0,r._RefractionTextureEnabled=!0,r._ColorGradingTextureEnabled=!0,r._FresnelEnabled=!0,n([e.serializeAsTexture("diffuseTexture")],r.prototype,"_diffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],r.prototype,"diffuseTexture",void 0),n([e.serializeAsTexture("ambientTexture")],r.prototype,"_ambientTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"ambientTexture",void 0),n([e.serializeAsTexture("opacityTexture")],r.prototype,"_opacityTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],r.prototype,"opacityTexture",void 0),n([e.serializeAsTexture("reflectionTexture")],r.prototype,"_reflectionTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionTexture",void 0),n([e.serializeAsTexture("emissiveTexture")],r.prototype,"_emissiveTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"emissiveTexture",void 0),n([e.serializeAsTexture("specularTexture")],r.prototype,"_specularTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"specularTexture",void 0),n([e.serializeAsTexture("bumpTexture")],r.prototype,"_bumpTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"bumpTexture",void 0),n([e.serializeAsTexture("lightmapTexture")],r.prototype,"_lightmapTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"lightmapTexture",void 0),n([e.serializeAsTexture("refractionTexture")],r.prototype,"_refractionTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"refractionTexture",void 0),n([e.serializeAsColor3("ambient")],r.prototype,"ambientColor",void 0),n([e.serializeAsColor3("diffuse")],r.prototype,"diffuseColor",void 0),n([e.serializeAsColor3("specular")],r.prototype,"specularColor",void 0),n([e.serializeAsColor3("emissive")],r.prototype,"emissiveColor",void 0),n([e.serialize()],r.prototype,"specularPower",void 0),n([e.serialize("useAlphaFromDiffuseTexture")],r.prototype,"_useAlphaFromDiffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useAlphaFromDiffuseTexture",void 0),n([e.serialize("useEmissiveAsIllumination")],r.prototype,"_useEmissiveAsIllumination",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useEmissiveAsIllumination",void 0),n([e.serialize("linkEmissiveWithDiffuse")],r.prototype,"_linkEmissiveWithDiffuse",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"linkEmissiveWithDiffuse",void 0),n([e.serialize("useSpecularOverAlpha")],r.prototype,"_useSpecularOverAlpha",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useSpecularOverAlpha",void 0),n([e.serialize("useReflectionOverAlpha")],r.prototype,"_useReflectionOverAlpha",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useReflectionOverAlpha",void 0),n([e.serialize("disableLighting")],r.prototype,"_disableLighting",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"disableLighting",void 0),n([e.serialize("useObjectSpaceNormalMap")],r.prototype,"_useObjectSpaceNormalMap",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useObjectSpaceNormalMap",void 0),n([e.serialize("useParallax")],r.prototype,"_useParallax",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useParallax",void 0),n([e.serialize("useParallaxOcclusion")],r.prototype,"_useParallaxOcclusion",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useParallaxOcclusion",void 0),n([e.serialize()],r.prototype,"parallaxScaleBias",void 0),n([e.serialize("roughness")],r.prototype,"_roughness",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"roughness",void 0),n([e.serialize()],r.prototype,"indexOfRefraction",void 0),n([e.serialize()],r.prototype,"invertRefractionY",void 0),n([e.serialize()],r.prototype,"alphaCutOff",void 0),n([e.serialize("useLightmapAsShadowmap")],r.prototype,"_useLightmapAsShadowmap",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useLightmapAsShadowmap",void 0),n([e.serializeAsFresnelParameters("diffuseFresnelParameters")],r.prototype,"_diffuseFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"diffuseFresnelParameters",void 0),n([e.serializeAsFresnelParameters("opacityFresnelParameters")],r.prototype,"_opacityFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")],r.prototype,"opacityFresnelParameters",void 0),n([e.serializeAsFresnelParameters("reflectionFresnelParameters")],r.prototype,"_reflectionFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"reflectionFresnelParameters",void 0),n([e.serializeAsFresnelParameters("refractionFresnelParameters")],r.prototype,"_refractionFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"refractionFresnelParameters",void 0),n([e.serializeAsFresnelParameters("emissiveFresnelParameters")],r.prototype,"_emissiveFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"emissiveFresnelParameters",void 0),n([e.serialize("useReflectionFresnelFromSpecular")],r.prototype,"_useReflectionFresnelFromSpecular",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"useReflectionFresnelFromSpecular",void 0),n([e.serialize("useGlossinessFromSpecularMapAlpha")],r.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useGlossinessFromSpecularMapAlpha",void 0),n([e.serialize("maxSimultaneousLights")],r.prototype,"_maxSimultaneousLights",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"maxSimultaneousLights",void 0),n([e.serialize("invertNormalMapX")],r.prototype,"_invertNormalMapX",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"invertNormalMapX",void 0),n([e.serialize("invertNormalMapY")],r.prototype,"_invertNormalMapY",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"invertNormalMapY",void 0),n([e.serialize("twoSidedLighting")],r.prototype,"_twoSidedLighting",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"twoSidedLighting",void 0),n([e.serialize()],r.prototype,"useLogarithmicDepth",null),r})(e.PushMaterial);e.StandardMaterial=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.x=e.Vector3.Zero(),this.y=e.Vector3.Zero(),this.z=e.Vector3.Zero(),this.xx=e.Vector3.Zero(),this.yy=e.Vector3.Zero(),this.zz=e.Vector3.Zero(),this.xy=e.Vector3.Zero(),this.yz=e.Vector3.Zero(),this.zx=e.Vector3.Zero()}return t.prototype.addAmbient=function(t){var i=new e.Vector3(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.prototype.scale=function(e){this.x=this.x.scale(e),this.y=this.y.scale(e),this.z=this.z.scale(e),this.xx=this.xx.scale(e),this.yy=this.yy.scale(e),this.zz=this.zz.scale(e),this.yz=this.yz.scale(e),this.zx=this.zx.scale(e),this.xy=this.xy.scale(e)},t.FromHarmonics=function(e){var i=new t;return i.x=e.l11.scale(1.02333),i.y=e.l1_1.scale(1.02333),i.z=e.l10.scale(1.02333),i.xx=e.l00.scale(.886277).subtract(e.l20.scale(.247708)).add(e.lL22.scale(.429043)),i.yy=e.l00.scale(.886277).subtract(e.l20.scale(.247708)).subtract(e.lL22.scale(.429043)),i.zz=e.l00.scale(.886277).add(e.l20.scale(.495417)),i.yz=e.l2_1.scale(.858086),i.zx=e.l21.scale(.858086),i.xy=e.l2_2.scale(.858086),i.scale(1/Math.PI),i},t.FromArray=function(i){var r=new t;return e.Vector3.FromArrayToRef(i[0],0,r.x),e.Vector3.FromArrayToRef(i[1],0,r.y),e.Vector3.FromArrayToRef(i[2],0,r.z),e.Vector3.FromArrayToRef(i[3],0,r.xx),e.Vector3.FromArrayToRef(i[4],0,r.yy),e.Vector3.FromArrayToRef(i[5],0,r.zz),e.Vector3.FromArrayToRef(i[6],0,r.yz),e.Vector3.FromArrayToRef(i[7],0,r.zx),e.Vector3.FromArrayToRef(i[8],0,r.xy),r},t})();e.SphericalPolynomial=t;var i=(function(){function t(){this.l00=e.Vector3.Zero(),this.l1_1=e.Vector3.Zero(),this.l10=e.Vector3.Zero(),this.l11=e.Vector3.Zero(),this.l2_2=e.Vector3.Zero(),this.l2_1=e.Vector3.Zero(),this.l20=e.Vector3.Zero(),this.l21=e.Vector3.Zero(),this.lL22=e.Vector3.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e.Vector3(i.r,i.g,i.b),o=n.scale(r);this.l00=this.l00.add(o.scale(.282095)),this.l1_1=this.l1_1.add(o.scale(.488603*t.y)),this.l10=this.l10.add(o.scale(.488603*t.z)),this.l11=this.l11.add(o.scale(.488603*t.x)),this.l2_2=this.l2_2.add(o.scale(1.092548*t.x*t.y)),this.l2_1=this.l2_1.add(o.scale(1.092548*t.y*t.z)),this.l21=this.l21.add(o.scale(1.092548*t.x*t.z)),this.l20=this.l20.add(o.scale(.315392*(3*t.z*t.z-1))),this.lL22=this.lL22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(e){this.l00=this.l00.scale(e),this.l1_1=this.l1_1.scale(e),this.l10=this.l10.scale(e),this.l11=this.l11.scale(e),this.l2_2=this.l2_2.scale(e),this.l2_1=this.l2_1.scale(e),this.l20=this.l20.scale(e),this.l21=this.l21.scale(e),this.lL22=this.lL22.scale(e)},t.prototype.convertIncidentRadianceToIrradiance=function(){this.l00=this.l00.scale(3.141593),this.l1_1=this.l1_1.scale(2.094395),this.l10=this.l10.scale(2.094395),this.l11=this.l11.scale(2.094395),this.l2_2=this.l2_2.scale(.785398),this.l2_1=this.l2_1.scale(.785398),this.l20=this.l20.scale(.785398),this.l21=this.l21.scale(.785398),this.lL22=this.lL22.scale(.785398)},t.prototype.convertIrradianceToLambertianRadiance=function(){this.scale(1/Math.PI)},t.FromPolynomial=function(e){var i=new t;return i.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),i.l1_1=e.y.scale(.977204),i.l10=e.z.scale(.977204),i.l11=e.x.scale(.977204),i.l2_2=e.xy.scale(1.16538),i.l2_1=e.yz.scale(1.16538),i.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),i.l21=e.zx.scale(1.16538),i.lL22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),i.scale(Math.PI),i},t.FromArray=function(i){var r=new t;return e.Vector3.FromArrayToRef(i[0],0,r.l00),e.Vector3.FromArrayToRef(i[1],0,r.l1_1),e.Vector3.FromArrayToRef(i[2],0,r.l10),e.Vector3.FromArrayToRef(i[3],0,r.l11),e.Vector3.FromArrayToRef(i[4],0,r.l2_2),e.Vector3.FromArrayToRef(i[5],0,r.l2_1),e.Vector3.FromArrayToRef(i[6],0,r.l20),e.Vector3.FromArrayToRef(i[7],0,r.l21),e.Vector3.FromArrayToRef(i[8],0,r.lL22),r},t})();e.SphericalHarmonics=i})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}return e})(),i=(function(){function i(){}return i.ConvertCubeMapTextureToSphericalPolynomial=function(t){if(!t.isCube)return null;var i,r,n=t.getSize().width,o=t.readPixels(0),s=t.readPixels(1);t.isRenderTarget?(i=t.readPixels(3),r=t.readPixels(2)):(i=t.readPixels(2),r=t.readPixels(3));var a=t.readPixels(4),l=t.readPixels(5),c=t.gammaSpace,h=e.Engine.TEXTUREFORMAT_RGBA,u=e.Engine.TEXTURETYPE_UNSIGNED_INT;t.textureType&&t.textureType!==e.Engine.TEXTURETYPE_UNSIGNED_INT&&(u=e.Engine.TEXTURETYPE_FLOAT);var d={size:n,right:o,left:s,up:i,down:r,front:a,back:l,format:h,type:u,gammaSpace:c};return this.ConvertCubeMapToSphericalPolynomial(d)},i.ConvertCubeMapToSphericalPolynomial=function(t){for(var i=new e.SphericalHarmonics,r=0,n=2/t.size,o=n,s=.5*n-1,a=0;a<6;a++)for(var l=this.FileFaces[a],c=t[l.name],h=s,u=t.format===e.Engine.TEXTUREFORMAT_RGBA?4:3,d=0;d0&&c.addCPUSkinningFallback(h++,t),i.MORPHTARGETS&&c.addFallback(h++,"MORPHTARGETS");var u=[e.VertexBuffer.PositionKind];i.NORMAL&&u.push(e.VertexBuffer.NormalKind),i.TANGENT&&u.push(e.VertexBuffer.TangentKind),i.UV1&&u.push(e.VertexBuffer.UVKind),i.UV2&&u.push(e.VertexBuffer.UV2Kind),i.VERTEXCOLOR&&u.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(u,t,i,c),e.MaterialHelper.PrepareAttributesForInstances(u,i),e.MaterialHelper.PrepareAttributesForMorphTargets(u,t,i);var d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vEmissiveColor","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","refractionMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX","vSphericalYY","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vReflectionMicrosurfaceInfos","vRefractionMicrosurfaceInfos","vTangentSpaceParams"],f=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","microSurfaceSampler","environmentBrdfSampler"],p=["Material","Scene"];e.ImageProcessingConfiguration&&(e.ImageProcessingConfiguration.PrepareUniforms(d,i),e.ImageProcessingConfiguration.PrepareSamplers(f,i)),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:i,maxSimultaneousLights:this._maxSimultaneousLights});var _=i.toString();return l.createEffect("pbr",{attributes:u,uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:_,fallbacks:c,onCompiled:r,onError:n,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:i.NUM_MORPH_INFLUENCERS}},l)},r.prototype._prepareDefines=function(t,i,r,n){void 0===r&&(r=null),void 0===n&&(n=null);var o=this.getScene(),s=o.getEngine();if(e.MaterialHelper.PrepareDefinesForLights(o,t,i,!0,this._maxSimultaneousLights,this._disableLighting),i._needNormals=!0,i.METALLICWORKFLOW=this.isMetallicWorkflow(),i._areTexturesDirty){if(i._needUVs=!1,o.texturesEnabled){o.getEngine().getCaps().textureLOD&&(i.LODBASEDMICROSFURACE=!0),this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled?e.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture,i,"ALBEDO"):i.ALBEDO=!1,this._ambientTexture&&e.StandardMaterial.AmbientTextureEnabled?(e.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture,i,"AMBIENT"),i.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):i.AMBIENT=!1,this._opacityTexture&&e.StandardMaterial.OpacityTextureEnabled?(e.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture,i,"OPACITY"),i.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):i.OPACITY=!1;var a=this._getReflectionTexture();if(a&&e.StandardMaterial.ReflectionTextureEnabled){switch(i.REFLECTION=!0,i.GAMMAREFLECTION=a.gammaSpace,i.RGBDREFLECTION=a.isRGBD,i.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!a.invertZ:a.invertZ,i.LODINREFLECTIONALPHA=a.lodLevelInAlpha,a.coordinatesMode===e.Texture.INVCUBIC_MODE&&(i.INVERTCUBICMAP=!0),i.REFLECTIONMAP_3D=a.isCube,a.coordinatesMode){case e.Texture.EXPLICIT_MODE:i.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:i.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:i.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:i.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:i.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:default:i.REFLECTIONMAP_CUBIC=!0,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!!a.boundingBoxSize}a.coordinatesMode!==e.Texture.SKYBOX_MODE&&a.sphericalPolynomial&&(i.USESPHERICALFROMREFLECTIONMAP=!0,this._forceIrradianceInFragment||o.getEngine().getCaps().maxVaryingVectors<=8?i.USESPHERICALINVERTEX=!1:i.USESPHERICALINVERTEX=!0)}else i.REFLECTION=!1,i.REFLECTIONMAP_3D=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_CUBIC=!1,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.INVERTCUBICMAP=!1,i.USESPHERICALFROMREFLECTIONMAP=!1,i.USESPHERICALINVERTEX=!1,i.REFLECTIONMAP_OPPOSITEZ=!1,i.LODINREFLECTIONALPHA=!1,i.GAMMAREFLECTION=!1,i.RGBDREFLECTION=!1;this._lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled?(e.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,i,"LIGHTMAP"),i.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,i.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace):i.LIGHTMAP=!1,this._emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled?e.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,i,"EMISSIVE"):i.EMISSIVE=!1,e.StandardMaterial.SpecularTextureEnabled?(this._metallicTexture?(e.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture,i,"REFLECTIVITY"),i.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,i.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,i.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,i.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed):this._reflectivityTexture?(e.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture,i,"REFLECTIVITY"),i.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,i.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap):i.REFLECTIVITY=!1,this._microSurfaceTexture?e.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture,i,"MICROSURFACEMAP"):i.MICROSURFACEMAP=!1):(i.REFLECTIVITY=!1,i.MICROSURFACEMAP=!1),o.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&e.StandardMaterial.BumpTextureEnabled&&!this._disableBumpMap?(e.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,i,"BUMP"),this._useParallax&&this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled?(i.PARALLAX=!0,i.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):i.PARALLAX=!1,i.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):i.BUMP=!1;var l=this._getRefractionTexture();l&&e.StandardMaterial.RefractionTextureEnabled?(i.REFRACTION=!0,i.REFRACTIONMAP_3D=l.isCube,i.GAMMAREFRACTION=l.gammaSpace,i.RGBDREFRACTION=l.isRGBD,i.REFRACTIONMAP_OPPOSITEZ=l.invertZ,i.LODINREFRACTIONALPHA=l.lodLevelInAlpha,this._linkRefractionWithTransparency&&(i.LINKREFRACTIONTOTRANSPARENCY=!0)):i.REFRACTION=!1,this._environmentBRDFTexture&&e.StandardMaterial.ReflectionTextureEnabled?i.ENVIRONMENTBRDF=!0:i.ENVIRONMENTBRDF=!1,this._shouldUseAlphaFromAlbedoTexture()?i.ALPHAFROMALBEDO=!0:i.ALPHAFROMALBEDO=!1}i.SPECULAROVERALPHA=this._useSpecularOverAlpha,i.USEPHYSICALLIGHTFALLOFF=this._usePhysicalLightFalloff,i.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?i.TWOSIDEDLIGHTING=!0:i.TWOSIDEDLIGHTING=!1,i.ALPHATESTVALUE=this._alphaCutOff+(this._alphaCutOff%1==0?".":""),i.PREMULTIPLYALPHA=this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED||this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF,i.ALPHABLEND=this.needAlphaBlendingForMesh(t),i.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,i.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel,i.SPECULARAA=o.getEngine().getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}i._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(i),i.FORCENORMALFORWARD=this._forceNormalForward,i.RADIANCEOCCLUSION=this._useRadianceOcclusion,i.HORIZONOCCLUSION=this._useHorizonOcclusion,i._areMiscDirty&&(e.MaterialHelper.PrepareDefinesForMisc(t,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(t)||this._forceAlphaTest,i),i.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!t.isVerticesDataPresent(e.VertexBuffer.NormalKind)),e.MaterialHelper.PrepareDefinesForFrameBoundValues(o,s,i,!!r,n),e.MaterialHelper.PrepareDefinesForAttributes(t,i,!0,!0,!0,this._transparencyMode!==e.PBRMaterial.PBRMATERIAL_OPAQUE)},r.prototype.forceCompilation=function(e,i,r){var n=this,o=s({clipPlane:!1},r),a=new t,l=this._prepareEffect(e,a,void 0,void 0,void 0,o.clipPlane);l.isReady()?i&&i(this):l.onCompileObservable.add((function(){i&&i(n)}))},r.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("vAlbedoInfos",2),this._uniformBuffer.addUniform("vAmbientInfos",3),this._uniformBuffer.addUniform("vOpacityInfos",2),this._uniformBuffer.addUniform("vEmissiveInfos",2),this._uniformBuffer.addUniform("vLightmapInfos",2),this._uniformBuffer.addUniform("vReflectivityInfos",3),this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos",2),this._uniformBuffer.addUniform("vRefractionInfos",4),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("vReflectionPosition",3),this._uniformBuffer.addUniform("vReflectionSize",3),this._uniformBuffer.addUniform("vBumpInfos",3),this._uniformBuffer.addUniform("albedoMatrix",16),this._uniformBuffer.addUniform("ambientMatrix",16),this._uniformBuffer.addUniform("opacityMatrix",16),this._uniformBuffer.addUniform("emissiveMatrix",16),this._uniformBuffer.addUniform("lightmapMatrix",16),this._uniformBuffer.addUniform("reflectivityMatrix",16),this._uniformBuffer.addUniform("microSurfaceSamplerMatrix",16),this._uniformBuffer.addUniform("bumpMatrix",16),this._uniformBuffer.addUniform("vTangentSpaceParams",2),this._uniformBuffer.addUniform("refractionMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionColor",3),this._uniformBuffer.addUniform("vAlbedoColor",4),this._uniformBuffer.addUniform("vLightingIntensity",4),this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("vReflectivityColor",4),this._uniformBuffer.addUniform("vEmissiveColor",3),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.create()},r.prototype.unbind=function(){this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._uniformBuffer.setTexture("refractionSampler",null),i.prototype.unbind.call(this)},r.prototype.bindForSubMesh=function(t,i,r){var n=this.getScene(),o=r._materialDefines;if(o){var s=r.effect;if(s){this._activeEffect=s,this.bindOnlyWorldMatrix(t),o.OBJECTSPACE_NORMALMAP&&(t.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var a=this._mustRebind(n,s,i.visibility);e.MaterialHelper.BindBonesParameters(i,this._activeEffect);var l=null;if(a){this._uniformBuffer.bindToEffect(s,"Material"),this.bindViewProjection(s),l=this._getReflectionTexture();var c=this._getRefractionTexture();if(!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync){if(n.texturesEnabled){if(this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),e.MaterialHelper.BindTextureMatrix(this._albedoTexture,this._uniformBuffer,"albedo")),this._ambientTexture&&e.StandardMaterial.AmbientTextureEnabled&&(this._uniformBuffer.updateFloat3("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength),e.MaterialHelper.BindTextureMatrix(this._ambientTexture,this._uniformBuffer,"ambient")),this._opacityTexture&&e.StandardMaterial.OpacityTextureEnabled&&(this._uniformBuffer.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),e.MaterialHelper.BindTextureMatrix(this._opacityTexture,this._uniformBuffer,"opacity")),l&&e.StandardMaterial.ReflectionTextureEnabled){if(this._uniformBuffer.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){var h=l;this._uniformBuffer.updateVector3("vReflectionPosition",h.boundingBoxPosition),this._uniformBuffer.updateVector3("vReflectionSize",h.boundingBoxSize)}var u=l.sphericalPolynomial;o.USESPHERICALFROMREFLECTIONMAP&&u&&(this._activeEffect.setFloat3("vSphericalX",u.x.x,u.x.y,u.x.z),this._activeEffect.setFloat3("vSphericalY",u.y.x,u.y.y,u.y.z),this._activeEffect.setFloat3("vSphericalZ",u.z.x,u.z.y,u.z.z),this._activeEffect.setFloat3("vSphericalXX_ZZ",u.xx.x-u.zz.x,u.xx.y-u.zz.y,u.xx.z-u.zz.z),this._activeEffect.setFloat3("vSphericalYY_ZZ",u.yy.x-u.zz.x,u.yy.y-u.zz.y,u.yy.z-u.zz.z),this._activeEffect.setFloat3("vSphericalZZ",u.zz.x,u.zz.y,u.zz.z),this._activeEffect.setFloat3("vSphericalXY",u.xy.x,u.xy.y,u.xy.z),this._activeEffect.setFloat3("vSphericalYZ",u.yz.x,u.yz.y,u.yz.z),this._activeEffect.setFloat3("vSphericalZX",u.zx.x,u.zx.y,u.zx.z)),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}if(this._emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled&&(this._uniformBuffer.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),e.MaterialHelper.BindTextureMatrix(this._emissiveTexture,this._uniformBuffer,"emissive")),this._lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled&&(this._uniformBuffer.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),e.MaterialHelper.BindTextureMatrix(this._lightmapTexture,this._uniformBuffer,"lightmap")),e.StandardMaterial.SpecularTextureEnabled&&(this._metallicTexture?(this._uniformBuffer.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),e.MaterialHelper.BindTextureMatrix(this._metallicTexture,this._uniformBuffer,"reflectivity")):this._reflectivityTexture&&(this._uniformBuffer.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),e.MaterialHelper.BindTextureMatrix(this._reflectivityTexture,this._uniformBuffer,"reflectivity")),this._microSurfaceTexture&&(this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),e.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture,this._uniformBuffer,"microSurfaceSampler"))),this._bumpTexture&&n.getEngine().getCaps().standardDerivatives&&e.StandardMaterial.BumpTextureEnabled&&!this._disableBumpMap&&(this._uniformBuffer.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),e.MaterialHelper.BindTextureMatrix(this._bumpTexture,this._uniformBuffer,"bump"),n._mirroredCameraPosition?this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),c&&e.StandardMaterial.RefractionTextureEnabled){this._uniformBuffer.updateMatrix("refractionMatrix",c.getReflectionTextureMatrix());var d=1;c.isCube||c.depth&&(d=c.depth),this._uniformBuffer.updateFloat4("vRefractionInfos",c.level,this._indexOfRefraction,d,this._invertRefractionY?-1:1),this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos",c.getSize().width,c.lodGenerationScale,c.lodGenerationOffset)}}this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),o.METALLICWORKFLOW?(e.PBRMaterial._scaledReflectivity.r=void 0===this._metallic||null===this._metallic?1:this._metallic,e.PBRMaterial._scaledReflectivity.g=void 0===this._roughness||null===this._roughness?1:this._roughness,this._uniformBuffer.updateColor4("vReflectivityColor",e.PBRMaterial._scaledReflectivity,0)):this._uniformBuffer.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface),this._uniformBuffer.updateColor3("vEmissiveColor",this._emissiveColor),this._uniformBuffer.updateColor3("vReflectionColor",this._reflectionColor),this._uniformBuffer.updateColor4("vAlbedoColor",this._albedoColor,this.alpha*i.visibility),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity,this._lightingInfos.w=this._specularIntensity,this._uniformBuffer.updateVector4("vLightingIntensity",this._lightingInfos)}n.texturesEnabled&&(this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&e.StandardMaterial.AmbientTextureEnabled&&this._uniformBuffer.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&e.StandardMaterial.OpacityTextureEnabled&&this._uniformBuffer.setTexture("opacitySampler",this._opacityTexture),l&&e.StandardMaterial.ReflectionTextureEnabled&&(o.LODBASEDMICROSFURACE?this._uniformBuffer.setTexture("reflectionSampler",l):(this._uniformBuffer.setTexture("reflectionSampler",l._lodTextureMid||l),this._uniformBuffer.setTexture("reflectionSamplerLow",l._lodTextureLow||l),this._uniformBuffer.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l))),o.ENVIRONMENTBRDF&&this._uniformBuffer.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),c&&e.StandardMaterial.RefractionTextureEnabled&&(o.LODBASEDMICROSFURACE?this._uniformBuffer.setTexture("refractionSampler",c):(this._uniformBuffer.setTexture("refractionSampler",c._lodTextureMid||c),this._uniformBuffer.setTexture("refractionSamplerLow",c._lodTextureLow||c),this._uniformBuffer.setTexture("refractionSamplerHigh",c._lodTextureHigh||c))),this._emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled&&this._uniformBuffer.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled&&this._uniformBuffer.setTexture("lightmapSampler",this._lightmapTexture),e.StandardMaterial.SpecularTextureEnabled&&(this._metallicTexture?this._uniformBuffer.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&this._uniformBuffer.setTexture("reflectivitySampler",this._reflectivityTexture),this._microSurfaceTexture&&this._uniformBuffer.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&n.getEngine().getCaps().standardDerivatives&&e.StandardMaterial.BumpTextureEnabled&&!this._disableBumpMap&&this._uniformBuffer.setTexture("bumpSampler",this._bumpTexture)),e.MaterialHelper.BindClipPlane(this._activeEffect,n),n.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor);var f=n._forcedViewPosition?n._forcedViewPosition:n._mirroredCameraPosition?n._mirroredCameraPosition:n.activeCamera.globalPosition,p=n.useRightHandedSystem===(null!=n._mirroredCameraPosition);s.setFloat4("vEyePosition",f.x,f.y,f.z,p?-1:1),s.setColor3("vAmbientColor",this._globalAmbientColor)}!a&&this.isFrozen||(n.lightsEnabled&&!this._disableLighting&&e.MaterialHelper.BindLights(n,i,this._activeEffect,o,this._maxSimultaneousLights,this._usePhysicalLightFalloff),(n.fogEnabled&&i.applyFog&&n.fogMode!==e.Scene.FOGMODE_NONE||l)&&this.bindView(s),e.MaterialHelper.BindFogParameters(n,i,this._activeEffect),o.NUM_MORPH_INFLUENCERS&&e.MaterialHelper.BindMorphTargetParameters(i,this._activeEffect),this._imageProcessingConfiguration.bind(this._activeEffect),e.MaterialHelper.BindLogDepth(o,this._activeEffect,n)),this._uniformBuffer.update(),this._afterBind(i,this._activeEffect)}}},r.prototype.getAnimatables=function(){var e=[];return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e},r.prototype._getReflectionTexture=function(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture},r.prototype._getRefractionTexture=function(){return this._refractionTexture?this._refractionTexture:this._linkRefractionWithTransparency?this.getScene().environmentTexture:null},r.prototype.dispose=function(e,t){t&&(this._albedoTexture&&this._albedoTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._environmentBRDFTexture&&this.getScene()._environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._metallicTexture&&this._metallicTexture.dispose(),this._reflectivityTexture&&this._reflectivityTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),i.prototype.dispose.call(this,e,t)},r._scaledReflectivity=new e.Color3,n([e.serializeAsImageProcessingConfiguration()],r.prototype,"_imageProcessingConfiguration",void 0),n([e.serialize()],r.prototype,"useLogarithmicDepth",null),n([e.serialize()],r.prototype,"transparencyMode",null),r})(e.PushMaterial);e.PBRBaseMaterial=i})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r){var n=t.call(this,i,r)||this;return n.maxSimultaneousLights=4,n.disableLighting=!1,n.invertNormalMapX=!1,n.invertNormalMapY=!1,n.emissiveColor=new e.Color3(0,0,0),n.occlusionStrength=1,n.useLightmapAsShadowmap=!1,n._useAlphaFromAlbedoTexture=!0,n._useAmbientInGrayScale=!0,n}return o(i,t),Object.defineProperty(i.prototype,"doubleSided",{get:function(){return this._twoSidedLighting},set:function(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())},enumerable:!0,configurable:!0}),i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this.environmentTexture&&e.push(this.environmentTexture),this.normalTexture&&e.push(this.normalTexture),this.emissiveTexture&&e.push(this.emissiveTexture),this.occlusionTexture&&e.push(this.occlusionTexture),this.lightmapTexture&&e.push(this.lightmapTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this.lightmapTexture===e},i.prototype.getClassName=function(){return"PBRBaseSimpleMaterial"},n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"maxSimultaneousLights",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"disableLighting",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],i.prototype,"environmentTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapX",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapY",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],i.prototype,"normalTexture",void 0), -n([e.serializeAsColor3("emissive"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveColor",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],i.prototype,"occlusionStrength",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],i.prototype,"occlusionTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],i.prototype,"alphaCutOff",void 0),n([e.serialize()],i.prototype,"doubleSided",null),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty",null)],i.prototype,"lightmapTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLightmapAsShadowmap",void 0),i})(e.PBRBaseMaterial);e.PBRBaseSimpleMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r){var n=t.call(this,i,r)||this;return n.directIntensity=1,n.emissiveIntensity=1,n.environmentIntensity=1,n.specularIntensity=1,n.disableBumpMap=!1,n.ambientTextureStrength=1,n.ambientColor=new e.Color3(0,0,0),n.albedoColor=new e.Color3(1,1,1),n.reflectivityColor=new e.Color3(1,1,1),n.reflectionColor=new e.Color3(1,1,1),n.emissiveColor=new e.Color3(0,0,0),n.microSurface=1,n.indexOfRefraction=.66,n.invertRefractionY=!1,n.linkRefractionWithTransparency=!1,n.useLightmapAsShadowmap=!1,n.useAlphaFromAlbedoTexture=!1,n.forceAlphaTest=!1,n.alphaCutOff=.4,n.useSpecularOverAlpha=!0,n.useMicroSurfaceFromReflectivityMapAlpha=!1,n.useRoughnessFromMetallicTextureAlpha=!0,n.useRoughnessFromMetallicTextureGreen=!1,n.useMetallnessFromMetallicTextureBlue=!1,n.useAmbientOcclusionFromMetallicTextureRed=!1,n.useAmbientInGrayScale=!1,n.useAutoMicroSurfaceFromReflectivityMap=!1,n.usePhysicalLightFalloff=!0,n.useRadianceOverAlpha=!0,n.useObjectSpaceNormalMap=!1,n.useParallax=!1,n.useParallaxOcclusion=!1,n.parallaxScaleBias=.05,n.disableLighting=!1,n.forceIrradianceInFragment=!1,n.maxSimultaneousLights=4,n.invertNormalMapX=!1,n.invertNormalMapY=!1,n.twoSidedLighting=!1,n.useAlphaFresnel=!1,n.useLinearAlphaFresnel=!1,n.environmentBRDFTexture=null,n.forceNormalForward=!1,n.enableSpecularAntiAliasing=!1,n.useHorizonOcclusion=!0,n.useRadianceOcclusion=!0,n.unlit=!1,n._environmentBRDFTexture=e.TextureTools.GetEnvironmentBRDFTexture(r),n}return o(i,t),Object.defineProperty(i,"PBRMATERIAL_OPAQUE",{get:function(){return this._PBRMATERIAL_OPAQUE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"PBRMATERIAL_ALPHATEST",{get:function(){return this._PBRMATERIAL_ALPHATEST},enumerable:!0,configurable:!0}),Object.defineProperty(i,"PBRMATERIAL_ALPHABLEND",{get:function(){return this._PBRMATERIAL_ALPHABLEND},enumerable:!0,configurable:!0}),Object.defineProperty(i,"PBRMATERIAL_ALPHATESTANDBLEND",{get:function(){return this._PBRMATERIAL_ALPHATESTANDBLEND},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurves",{get:function(){return this._imageProcessingConfiguration.colorCurves},set:function(e){this._imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"PBRMaterial"},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this._albedoTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._reflectivityTexture===e||(this._metallicTexture===e||(this._microSurfaceTexture===e||(this._bumpTexture===e||(this._lightmapTexture===e||this._refractionTexture===e)))))))))},i.prototype.clone=function(t){var r=this,n=e.SerializationHelper.Clone((function(){return new i(t,r.getScene())}),this);return n.id=t,n.name=t,n},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRMaterial",t},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,r)}),t,r,n)},i._PBRMATERIAL_OPAQUE=0,i._PBRMATERIAL_ALPHATEST=1,i._PBRMATERIAL_ALPHABLEND=2,i._PBRMATERIAL_ALPHATESTANDBLEND=3,n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"directIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"environmentIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"specularIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"disableBumpMap",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"albedoTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientTextureStrength",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"opacityTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectivityTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallicTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallic",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"roughness",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"microSurfaceTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"bumpTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty",null)],i.prototype,"lightmapTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"refractionTexture",void 0),n([e.serializeAsColor3("ambient"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientColor",void 0),n([e.serializeAsColor3("albedo"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"albedoColor",void 0),n([e.serializeAsColor3("reflectivity"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectivityColor",void 0),n([e.serializeAsColor3("reflection"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionColor",void 0),n([e.serializeAsColor3("emissive"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveColor",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"microSurface",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"indexOfRefraction",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertRefractionY",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"linkRefractionWithTransparency",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLightmapAsShadowmap",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"useAlphaFromAlbedoTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"forceAlphaTest",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"alphaCutOff",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useSpecularOverAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRoughnessFromMetallicTextureGreen",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useMetallnessFromMetallicTextureBlue",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAmbientInGrayScale",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"usePhysicalLightFalloff",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRadianceOverAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useObjectSpaceNormalMap",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useParallax",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useParallaxOcclusion",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"parallaxScaleBias",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"disableLighting",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"forceIrradianceInFragment",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"maxSimultaneousLights",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapX",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapY",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"twoSidedLighting",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAlphaFresnel",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLinearAlphaFresnel",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"environmentBRDFTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"forceNormalForward",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"enableSpecularAntiAliasing",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useHorizonOcclusion",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRadianceOcclusion",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsMiscDirty")],i.prototype,"unlit",void 0),i})(e.PBRBaseMaterial);e.PBRMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i){var r=t.call(this,e,i)||this;return r._useRoughnessFromMetallicTextureAlpha=!1,r._useRoughnessFromMetallicTextureGreen=!0,r._useMetallnessFromMetallicTextureBlue=!0,r.metallic=1,r.roughness=1,r}return o(i,t),i.prototype.getClassName=function(){return"PBRMetallicRoughnessMaterial"},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this.baseTexture&&e.push(this.baseTexture),this.metallicRoughnessTexture&&e.push(this.metallicRoughnessTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this.baseTexture===e||this.metallicRoughnessTexture===e)},i.prototype.clone=function(t){var r=this,n=e.SerializationHelper.Clone((function(){return new i(t,r.getScene())}),this);return n.id=t,n.name=t,n},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRMetallicRoughnessMaterial",t},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,r)}),t,r,n)},n([e.serializeAsColor3(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoColor")],i.prototype,"baseColor",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],i.prototype,"baseTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallic",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"roughness",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],i.prototype,"metallicRoughnessTexture",void 0),i})(e.PBRBaseSimpleMaterial);e.PBRMetallicRoughnessMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i){var r=t.call(this,e,i)||this;return r._useMicroSurfaceFromReflectivityMapAlpha=!0,r}return o(i,t),i.prototype.getClassName=function(){return"PBRSpecularGlossinessMaterial"},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this.diffuseTexture&&e.push(this.diffuseTexture),this.specularGlossinessTexture&&e.push(this.specularGlossinessTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this.diffuseTexture===e||this.specularGlossinessTexture===e)},i.prototype.clone=function(t){var r=this,n=e.SerializationHelper.Clone((function(){return new i(t,r.getScene())}),this);return n.id=t,n.name=t,n},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRSpecularGlossinessMaterial",t},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,r)}),t,r,n)},n([e.serializeAsColor3("diffuse"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoColor")],i.prototype,"diffuseColor",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],i.prototype,"diffuseTexture",void 0),n([e.serializeAsColor3("specular"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],i.prototype,"specularColor",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_microSurface")],i.prototype,"glossiness",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],i.prototype,"specularGlossinessTexture",void 0),i})(e.PBRBaseSimpleMaterial);e.PBRSpecularGlossinessMaterial=t})(r||(r={}));var r;!(function(e){e.CameraInputTypes={};var t=(function(){function t(e){this.attached={},this.camera=e,this.checkInputs=function(){}}return t.prototype.add=function(t){var i=t.getSimpleName();if(this.attached[i])return void e.Tools.Warn("camera input of type "+i+" already exists on camera");this.attached[i]=t,t.camera=this.camera,t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t))),this.attachedElement&&t.attachControl(this.attachedElement)},t.prototype.remove=function(e){for(var t in this.attached){var i=this.attached[t];i===e&&(i.detachControl(this.attachedElement),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}},t.prototype.removeByType=function(e){for(var t in this.attached){var i=this.attached[t];i.getClassName()===e&&(i.detachControl(this.attachedElement),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}},t.prototype._addCheckInputs=function(e){var t=this.checkInputs;return function(){t(),e()}},t.prototype.attachInput=function(e){this.attachedElement&&e.attachControl(this.attachedElement,this.noPreventDefault)},t.prototype.attachElement=function(t,i){if(void 0===i&&(i=!1),!this.attachedElement){i=!e.Camera.ForceAttachControlToAlwaysPreventDefault&&i,this.attachedElement=t,this.noPreventDefault=i;for(var r in this.attached)this.attached[r].attachControl(t,i)}},t.prototype.detachElement=function(e,t){if(void 0===t&&(t=!1),this.attachedElement===e){for(var i in this.attached)this.attached[i].detachControl(e),t&&(this.attached[i].camera=null);this.attachedElement=null}},t.prototype.rebuildInputCheck=function(){this.checkInputs=function(){};for(var e in this.attached){var t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}},t.prototype.clear=function(){this.attachedElement&&this.detachElement(this.attachedElement,!0),this.attached={},this.attachedElement=null,this.checkInputs=function(){}},t.prototype.serialize=function(t){var i={};for(var r in this.attached){var n=this.attached[r],o=e.SerializationHelper.Serialize(n);i[n.getClassName()]=o}t.inputsmgr=i},t.prototype.parse=function(t){var i=t.inputsmgr;if(i){this.clear();for(var r in i){var n=e.CameraInputTypes[r];if(n){var o=i[r],s=e.SerializationHelper.Parse((function(){return new n}),o,null);this.add(s)}}}else for(var r in this.attached){var n=e.CameraInputTypes[this.attached[r].getClassName()];if(n){var s=e.SerializationHelper.Parse((function(){return new n}),t,null);this.remove(this.attached[r]),this.add(s)}}},t})();e.CameraInputsManager=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o){void 0===o&&(o=!0);var s=t.call(this,i,r,n,o)||this;return s.cameraDirection=new e.Vector3(0,0,0),s.cameraRotation=new e.Vector2(0,0),s.rotation=new e.Vector3(0,0,0),s.speed=2,s.noRotationConstraint=!1,s.lockedTarget=null,s._currentTarget=e.Vector3.Zero(),s._viewMatrix=e.Matrix.Zero(),s._camMatrix=e.Matrix.Zero(),s._cameraTransformMatrix=e.Matrix.Zero(),s._cameraRotationMatrix=e.Matrix.Zero(),s._referencePoint=new e.Vector3(0,0,1),s._currentUpVector=new e.Vector3(0,1,0),s._transformedReferencePoint=e.Vector3.Zero(),s._globalCurrentTarget=e.Vector3.Zero(),s._globalCurrentUpVector=e.Vector3.Zero(),s}return o(i,t),i.prototype.getFrontPosition=function(e){this.getWorldMatrix();var t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)},i.prototype._getLockedTargetPosition=function(){return this.lockedTarget?(this.lockedTarget.absolutePosition&&this.lockedTarget.computeWorldMatrix(),this.lockedTarget.absolutePosition||this.lockedTarget):null},i.prototype.storeState=function(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),t.prototype.storeState.call(this)},i.prototype._restoreStateValues=function(){return!!t.prototype._restoreStateValues.call(this)&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.lockedTarget=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new e.Quaternion(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this);var i=this._getLockedTargetPosition();i?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(i):this._cache.lockedTarget=i.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)},i.prototype._isSynchronizedViewMatrix=function(){if(!t.prototype._isSynchronizedViewMatrix.call(this))return!1;var e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))},i.prototype._computeLocalCameraSpeed=function(){var e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))},i.prototype.setTarget=function(t){this.upVector.normalize(),e.Matrix.LookAtLHToRef(this.position,t,this.upVector,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);var i=t.subtract(this.position);i.x>=0?this.rotation.y=-Math.atan(i.z/i.x)+Math.PI/2:this.rotation.y=-Math.atan(i.z/i.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)},i.prototype.getTarget=function(){return this._currentTarget},i.prototype._decideIfNeedsToMove=function(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(e.Tmp.Matrix[0]),e.Vector3.TransformNormalToRef(this.cameraDirection,e.Tmp.Matrix[0],e.Tmp.Vector3[0]),void this.position.addInPlace(e.Tmp.Vector3[0]);this.position.addInPlace(this.cameraDirection)},i.prototype._checkInputs=function(){var i=this._decideIfNeedsToMove(),r=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(i&&this._updatePosition(),r){if(this.rotation.x+=this.cameraRotation.x,this.rotation.y+=this.cameraRotation.y,this.rotationQuaternion){this.rotation.lengthSquared()&&e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}if(!this.noRotationConstraint){var n=Math.PI/2*.95;this.rotation.x>n&&(this.rotation.x=n),this.rotation.x<-n&&(this.rotation.x=-n)}}i&&(Math.abs(this.cameraDirection.x)=0&&r._keys.splice(o,1),i||n.preventDefault()}})))},t.prototype.detachControl=function(e){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys=[]},t.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var t=this.camera,i=0;ie.Engine.CollisionsEpsilon&&(s.position.addInPlace(s._diffPosition),s.onCollide&&r&&s.onCollide(r))})(i)},s.inputs=new e.FreeCameraInputsManager(s),s.inputs.addKeyboard().addMouse(),s}return o(i,t),Object.defineProperty(i.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;return e?e.angularSensibility:0},set:function(e){var t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),i.prototype.attachControl=function(e,t){this.inputs.attachElement(e,t)},i.prototype.detachControl=function(t){this.inputs.detachElement(t),this.cameraDirection=new e.Vector3(0,0,0),this.cameraRotation=new e.Vector2(0,0)},Object.defineProperty(i.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),i.prototype._collideWithWorld=function(t){var i;i=this.parent?e.Vector3.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,i.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset),this._collider||(this._collider=new e.Collider),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;var r=t;this.applyGravity&&(r=t.add(this.getScene().gravity)),this.getScene().collisionCoordinator.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},i.prototype._checkInputs=function(){this._localDirection||(this._localDirection=e.Vector3.Zero(),this._transformedDirection=e.Vector3.Zero()),this.inputs.checkInputs(),t.prototype._checkInputs.call(this)},i.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):t.prototype._updatePosition.call(this)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getClassName=function(){return"FreeCamera"},n([e.serializeAsVector3()],i.prototype,"ellipsoid",void 0),n([e.serializeAsVector3()],i.prototype,"ellipsoidOffset",void 0),n([e.serialize()],i.prototype,"checkCollisions",void 0),n([e.serialize()],i.prototype,"applyGravity",void 0),i})(e.TargetCamera);e.FreeCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._keys=new Array,this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0}return t.prototype.attachControl=function(t,i){var r=this;this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((function(){r._keys=[]})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((function(t){var n=t.event;if(t.type===e.KeyboardEventTypes.KEYDOWN){if(r._ctrlPressed=n.ctrlKey,r._altPressed=n.altKey,-1!==r.keysUp.indexOf(n.keyCode)||-1!==r.keysDown.indexOf(n.keyCode)||-1!==r.keysLeft.indexOf(n.keyCode)||-1!==r.keysRight.indexOf(n.keyCode)||-1!==r.keysReset.indexOf(n.keyCode)){var o=r._keys.indexOf(n.keyCode);-1===o&&r._keys.push(n.keyCode),n.preventDefault&&(i||n.preventDefault())}}else if(-1!==r.keysUp.indexOf(n.keyCode)||-1!==r.keysDown.indexOf(n.keyCode)||-1!==r.keysLeft.indexOf(n.keyCode)||-1!==r.keysRight.indexOf(n.keyCode)||-1!==r.keysReset.indexOf(n.keyCode)){var o=r._keys.indexOf(n.keyCode);o>=0&&r._keys.splice(o,1),n.preventDefault&&(i||n.preventDefault())}})))},t.prototype.detachControl=function(e){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys=[]},t.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var e=this.camera,t=0;t0?a/(1+r.wheelDeltaPercentage):a*(1+r.wheelDeltaPercentage)}else s=o.wheelDelta/(40*r.wheelPrecision);else o.detail&&(s=-o.detail/r.wheelPrecision);s&&(r.camera.inertialRadiusOffset+=s),o.preventDefault&&(i||o.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,e.PointerEventTypes.POINTERWHEEL)},t.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},t.prototype.getClassName=function(){return"ArcRotateCameraMouseWheelInput"},t.prototype.getSimpleName=function(){return"mousewheel"},n([e.serialize()],t.prototype,"wheelPrecision",void 0),n([e.serialize()],t.prototype,"wheelDeltaPercentage",void 0),t})();e.ArcRotateCameraMouseWheelInput=t,e.CameraInputTypes.ArcRotateCameraMouseWheelInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this._isPanClick=!1,this.pinchInwards=!0}return t.prototype.attachControl=function(t,i){var r,n=this,o=this.camera.getEngine(),s=null,a=null,l=0,c=0,h=0,u={x:0,y:0,isPaning:!1,isPinching:!1};this._pointerInput=function(d,f){var p=d.event,_="touch"===d.event.pointerType;if(!o.isInVRExclusivePointerMode&&(d.type===e.PointerEventTypes.POINTERMOVE||-1!==n.buttons.indexOf(p.button))){var m=p.srcElement||p.target;if(d.type===e.PointerEventTypes.POINTERDOWN&&m){try{m.setPointerCapture(p.pointerId)}catch(e){}n._isPanClick=p.button===n.camera._panningMouseButton,r={x:p.clientX,y:p.clientY,pointerId:p.pointerId,type:p.pointerType},null===s?s=r:null===a&&(a=r),i||(p.preventDefault(),t.focus())}else if(d.type===e.PointerEventTypes.POINTERDOUBLETAP)n.camera.restoreState();else if(d.type===e.PointerEventTypes.POINTERUP&&m){try{m.releasePointerCapture(p.pointerId)}catch(e){}r=null,l=0,u.isPaning=!1,u.isPinching=!1,h=0,c=0,_||(a=null),o._badOS?s=a=null:a&&s&&s.pointerId==p.pointerId?(s=a,a=null,r={x:s.x,y:s.y,pointerId:s.pointerId,type:p.pointerType}):s&&a&&a.pointerId==p.pointerId?(a=null,r={x:s.x,y:s.y,pointerId:s.pointerId,type:p.pointerType}):s=a=null,i||p.preventDefault()}else if(d.type===e.PointerEventTypes.POINTERMOVE)if(i||p.preventDefault(),s&&null===a&&r){if(0!==n.panningSensibility&&(p.ctrlKey&&n.camera._useCtrlForPanning||n._isPanClick))n.camera.inertialPanningX+=-(p.clientX-r.x)/n.panningSensibility,n.camera.inertialPanningY+=(p.clientY-r.y)/n.panningSensibility;else{var g=p.clientX-r.x,v=p.clientY-r.y;n.camera.inertialAlphaOffset-=g/n.angularSensibilityX,n.camera.inertialBetaOffset-=v/n.angularSensibilityY}r.x=p.clientX,r.y=p.clientY}else if(s&&a){var y=s.pointerId===p.pointerId?s:a;y.x=p.clientX,y.y=p.clientY;var b=n.pinchInwards?1:-1,x=s.x-a.x,T=s.y-a.y,E=x*x+T*T,P=Math.sqrt(E);if(0===l)return c=P,l=E,u.x=(s.x+a.x)/2,void(u.y=(s.y+a.y)/2);if(n.multiTouchPanAndZoom){if(n.pinchDeltaPercentage?n.camera.inertialRadiusOffset+=.001*(E-l)*n.camera.radius*n.pinchDeltaPercentage:n.camera.inertialRadiusOffset+=(E-l)/(n.pinchPrecision*((n.angularSensibilityX+n.angularSensibilityY)/2)*b),0!==n.panningSensibility){var A=(s.x+a.x)/2,M=(s.y+a.y)/2,S=A-u.x,C=M-u.y;u.x=A,u.y=M,n.camera.inertialPanningX+=-S/n.panningSensibility,n.camera.inertialPanningY+=C/n.panningSensibility}}else{if(h++,u.isPinching||h<20&&Math.abs(P-c)>n.camera.pinchToPanMaxDistance)n.pinchDeltaPercentage?n.camera.inertialRadiusOffset+=.001*(E-l)*n.camera.radius*n.pinchDeltaPercentage:n.camera.inertialRadiusOffset+=(E-l)/(n.pinchPrecision*((n.angularSensibilityX+n.angularSensibilityY)/2)*b),u.isPaning=!1,u.isPinching=!0;else if(r&&r.pointerId===y.pointerId&&0!==n.panningSensibility&&n.multiTouchPanning){if(!u.isPaning)return u.isPaning=!0,u.isPinching=!1,u.x=y.x,void(u.y=y.y);n.camera.inertialPanningX+=-(y.x-u.x)/n.panningSensibility,n.camera.inertialPanningY+=(y.y-u.y)/n.panningSensibility}r&&r.pointerId===p.pointerId&&(u.x=y.x,u.y=y.y)}l=E}}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE|e.PointerEventTypes._POINTERDOUBLETAP),this._onContextMenu=function(e){e.preventDefault()},this.camera._useCtrlForPanning||t.addEventListener("contextmenu",this._onContextMenu,!1),this._onLostFocus=function(){s=a=null,l=0,u.isPaning=!1,u.isPinching=!1,h=0,r=null,c=0},this._onMouseMove=function(e){if(o.isPointerLock){var t=e.movementX||e.mozMovementX||e.webkitMovementX||e.msMovementX||0,r=e.movementY||e.mozMovementY||e.webkitMovementY||e.msMovementY||0;n.camera.inertialAlphaOffset-=t/n.angularSensibilityX,n.camera.inertialBetaOffset-=r/n.angularSensibilityY,i||e.preventDefault()}},this._onGestureStart=function(e){void 0!==window.MSGesture&&(n._MSGestureHandler||(n._MSGestureHandler=new MSGesture,n._MSGestureHandler.target=t),n._MSGestureHandler.addPointer(e.pointerId))},this._onGesture=function(e){n.camera.radius*=e.scale,e.preventDefault&&(i||(e.stopPropagation(),e.preventDefault()))},t.addEventListener("mousemove",this._onMouseMove,!1),t.addEventListener("MSPointerDown",this._onGestureStart,!1),t.addEventListener("MSGestureChange",this._onGesture,!1),e.Tools.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},t.prototype.detachControl=function(t){this._onLostFocus&&e.Tools.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]),t&&this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._onContextMenu&&t.removeEventListener("contextmenu",this._onContextMenu),this._onMouseMove&&t.removeEventListener("mousemove",this._onMouseMove),this._onGestureStart&&t.removeEventListener("MSPointerDown",this._onGestureStart),this._onGesture&&t.removeEventListener("MSGestureChange",this._onGesture),this._isPanClick=!1,this.pinchInwards=!0,this._onMouseMove=null,this._onGestureStart=null,this._onGesture=null,this._MSGestureHandler=null,this._onLostFocus=null,this._onContextMenu=null)},t.prototype.getClassName=function(){return"ArcRotateCameraPointersInput"},t.prototype.getSimpleName=function(){return"pointers"},n([e.serialize()],t.prototype,"buttons",void 0),n([e.serialize()],t.prototype,"angularSensibilityX",void 0),n([e.serialize()],t.prototype,"angularSensibilityY",void 0),n([e.serialize()],t.prototype,"pinchPrecision",void 0),n([e.serialize()],t.prototype,"pinchDeltaPercentage",void 0),n([e.serialize()],t.prototype,"panningSensibility",void 0),n([e.serialize()],t.prototype,"multiTouchPanning",void 0),n([e.serialize()],t.prototype,"multiTouchPanAndZoom",void 0),t})();e.ArcRotateCameraPointersInput=t,e.CameraInputTypes.ArcRotateCameraPointersInput=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e){return t.call(this,e)||this}return o(i,t),i.prototype.addMouseWheel=function(){return this.add(new e.ArcRotateCameraMouseWheelInput),this},i.prototype.addPointers=function(){return this.add(new e.ArcRotateCameraPointersInput),this},i.prototype.addKeyboard=function(){return this.add(new e.ArcRotateCameraKeyboardMoveInput),this},i.prototype.addVRDeviceOrientation=function(){return this.add(new e.ArcRotateCameraVRDeviceOrientationInput),this},i})(e.CameraInputsManager);e.ArcRotateCameraInputsManager=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("ArcRotateCamera",(function(i,r){return function(){return new t(i,0,0,1,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s,a,l){void 0===l&&(l=!0);var c=t.call(this,i,e.Vector3.Zero(),a,l)||this;return c.inertialAlphaOffset=0,c.inertialBetaOffset=0,c.inertialRadiusOffset=0,c.lowerAlphaLimit=null,c.upperAlphaLimit=null,c.lowerBetaLimit=.01,c.upperBetaLimit=Math.PI,c.lowerRadiusLimit=null,c.upperRadiusLimit=null,c.inertialPanningX=0,c.inertialPanningY=0,c.pinchToPanMaxDistance=20,c.panningDistanceLimit=null,c.panningOriginTarget=e.Vector3.Zero(),c.panningInertia=.9,c.zoomOnFactor=1,c.targetScreenOffset=e.Vector2.Zero(),c.allowUpsideDown=!0,c._viewMatrix=new e.Matrix,c.panningAxis=new e.Vector3(1,1,0),c.onMeshTargetChangedObservable=new e.Observable,c.checkCollisions=!1,c.collisionRadius=new e.Vector3(.5,.5,.5),c._previousPosition=e.Vector3.Zero(),c._collisionVelocity=e.Vector3.Zero(),c._newPosition=e.Vector3.Zero(),c._computationVector=e.Vector3.Zero(),c._onCollisionPositionChange=function(e,t,i){void 0===i&&(i=null),c.getScene().workerCollisions&&c.checkCollisions&&t.multiplyInPlace(c._collider._radius),i?(c.setPosition(t),c.onCollide&&c.onCollide(i)):c._previousPosition.copyFrom(c.position);var r=Math.cos(c.alpha),n=Math.sin(c.alpha),o=Math.cos(c.beta),s=Math.sin(c.beta);0===s&&(s=1e-4);var a=c._getTargetPosition();c._computationVector.copyFromFloats(c.radius*r*s,c.radius*o,c.radius*n*s),a.addToRef(c._computationVector,c._newPosition),c.position.copyFrom(c._newPosition);var l=c.upVector;c.allowUpsideDown&&c.beta<0&&(l=l.clone(),l=l.negate()),c._computeViewMatrix(c.position,a,l),c._viewMatrix.m[12]+=c.targetScreenOffset.x,c._viewMatrix.m[13]+=c.targetScreenOffset.y,c._collisionTriggered=!1},c._target=e.Vector3.Zero(),s&&c.setTarget(s),c.alpha=r,c.beta=n,c.radius=o,c.getViewMatrix(),c.inputs=new e.ArcRotateCameraInputsManager(c),c.inputs.addKeyboard().addMouseWheel().addPointers(),c}return o(i,t),Object.defineProperty(i.prototype,"target",{get:function(){return this._target},set:function(e){this.setTarget(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"angularSensibilityX",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"angularSensibilityY",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pinchPrecision",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchPrecision:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pinchDeltaPercentage",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"panningSensibility",{get:function(){var e=this.inputs.attached.pointers;return e?e.panningSensibility:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wheelPrecision",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wheelDeltaPercentage",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"bouncingBehavior",{get:function(){return this._bouncingBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useBouncingBehavior",{get:function(){return null!=this._bouncingBehavior},set:function(t){t!==this.useBouncingBehavior&&(t?(this._bouncingBehavior=new e.BouncingBehavior,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"framingBehavior",{get:function(){return this._framingBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useFramingBehavior",{get:function(){return null!=this._framingBehavior},set:function(t){t!==this.useFramingBehavior&&(t?(this._framingBehavior=new e.FramingBehavior,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"autoRotationBehavior",{get:function(){return this._autoRotationBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useAutoRotationBehavior",{get:function(){return null!=this._autoRotationBehavior},set:function(t){t!==this.useAutoRotationBehavior&&(t?(this._autoRotationBehavior=new e.AutoRotationBehavior,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))},enumerable:!0,configurable:!0}),i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache._target=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=e.Vector2.Zero()},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)},i.prototype._getTargetPosition=function(){if(this._targetHost&&this._targetHost.getAbsolutePosition){var e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}var t=this._getLockedTargetPosition();return t||this._target},i.prototype.storeState=function(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),t.prototype.storeState.call(this)},i.prototype._restoreStateValues=function(){return!!t.prototype._restoreStateValues.call(this)&&(this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.setTarget(this._storedTarget.clone()),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)},i.prototype._isSynchronizedViewMatrix=function(){return!!t.prototype._isSynchronizedViewMatrix.call(this)&&(this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset))},i.prototype.attachControl=function(e,t,i,r){var n=this;void 0===i&&(i=!0),void 0===r&&(r=2),this._useCtrlForPanning=i,this._panningMouseButton=r,this.inputs.attachElement(e,t),this._reset=function(){n.inertialAlphaOffset=0,n.inertialBetaOffset=0,n.inertialRadiusOffset=0,n.inertialPanningX=0,n.inertialPanningY=0}},i.prototype.detachControl=function(e){this.inputs.detachElement(e),this._reset&&this._reset()},i.prototype._checkInputs=function(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){var i=this.inertialAlphaOffset;this.beta<=0&&(i*=-1),this.getScene().useRightHandedSystem&&(i*=-1),this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(i*=-1),this.alpha+=i,this.beta+=this.inertialBetaOffset,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit)},i.prototype.rebuildAnglesAndRadius=function(){this.position.subtractToRef(this._getTargetPosition(),this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4),this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha),this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()},i.prototype.setPosition=function(e){this.position.equals(e)||(this.position.copyFrom(e),this.rebuildAnglesAndRadius())},i.prototype.setTarget=function(e,t,i){if(void 0===t&&(t=!1),void 0===i&&(i=!1),e.getBoundingInfo)this._targetBoundingCenter=t?e.getBoundingInfo().boundingBox.centerWorld.clone():null,this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{var r=e,n=this._getTargetPosition();if(n&&!i&&n.equals(r))return;this._targetHost=null,this._target=r,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}this.rebuildAnglesAndRadius()},i.prototype._getViewMatrix=function(){var t=Math.cos(this.alpha),i=Math.sin(this.alpha),r=Math.cos(this.beta),n=Math.sin(this.beta);0===n&&(n=1e-4);var o=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*t*n,this.radius*r,this.radius*i*n),o.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions)this._collider||(this._collider=new e.Collider),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this.position,this._collisionVelocity),this._collisionTriggered=!0,this.getScene().collisionCoordinator.getNewPosition(this.position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId);else{this.position.copyFrom(this._newPosition);var s=this.upVector;this.allowUpsideDown&&n<0&&(s=s.clone(),s=s.negate()),this._computeViewMatrix(this.position,o,s),this._viewMatrix.m[12]+=this.targetScreenOffset.x,this._viewMatrix.m[13]+=this.targetScreenOffset.y}return this._currentTarget=o,this._viewMatrix},i.prototype.zoomOn=function(t,i){void 0===i&&(i=!1),t=t||this.getScene().meshes;var r=e.Mesh.MinMax(t),n=e.Vector3.Distance(r.min,r.max);this.radius=n*this.zoomOnFactor,this.focusOn({min:r.min,max:r.max,distance:n},i)},i.prototype.focusOn=function(t,i){void 0===i&&(i=!1);var r,n;if(void 0===t.min){var o=t||this.getScene().meshes;r=e.Mesh.MinMax(o),n=e.Vector3.Distance(r.min,r.max)}else{var s=t;r=s,n=s.distance}this._target=e.Mesh.Center(r),i||(this.maxZ=2*n)},i.prototype.createRigCamera=function(t,r){var n=0;switch(this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:n=this._cameraRigParams.stereoHalfAngle*(0===r?1:-1);break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:n=this._cameraRigParams.stereoHalfAngle*(0===r?-1:1)}var o=new i(t,this.alpha+n,this.beta,this.radius,this._target,this.getScene());return o._cameraRigParams={},o},i.prototype._updateRigCameras=function(){ -var i=this._rigCameras[0],r=this._rigCameras[1];switch(i.beta=r.beta=this.beta,i.radius=r.radius=this.radius,this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:i.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}t.prototype._updateRigCameras.call(this)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getClassName=function(){return"ArcRotateCamera"},n([e.serialize()],i.prototype,"alpha",void 0),n([e.serialize()],i.prototype,"beta",void 0),n([e.serialize()],i.prototype,"radius",void 0),n([e.serializeAsVector3("target")],i.prototype,"_target",void 0),n([e.serialize()],i.prototype,"inertialAlphaOffset",void 0),n([e.serialize()],i.prototype,"inertialBetaOffset",void 0),n([e.serialize()],i.prototype,"inertialRadiusOffset",void 0),n([e.serialize()],i.prototype,"lowerAlphaLimit",void 0),n([e.serialize()],i.prototype,"upperAlphaLimit",void 0),n([e.serialize()],i.prototype,"lowerBetaLimit",void 0),n([e.serialize()],i.prototype,"upperBetaLimit",void 0),n([e.serialize()],i.prototype,"lowerRadiusLimit",void 0),n([e.serialize()],i.prototype,"upperRadiusLimit",void 0),n([e.serialize()],i.prototype,"inertialPanningX",void 0),n([e.serialize()],i.prototype,"inertialPanningY",void 0),n([e.serialize()],i.prototype,"pinchToPanMaxDistance",void 0),n([e.serialize()],i.prototype,"panningDistanceLimit",void 0),n([e.serializeAsVector3()],i.prototype,"panningOriginTarget",void 0),n([e.serialize()],i.prototype,"panningInertia",void 0),n([e.serialize()],i.prototype,"zoomOnFactor",void 0),n([e.serialize()],i.prototype,"allowUpsideDown",void 0),i})(e.TargetCamera);e.ArcRotateCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_3",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n){var o=t.call(this,i,n)||this;return o.groundColor=new e.Color3(0,0,0),o.direction=r||e.Vector3.Up(),o}return o(i,t),i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.getClassName=function(){return"HemisphericLight"},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(e.Vector3.Zero())),this.direction},i.prototype.getShadowGenerator=function(){return null},i.prototype.transferToEffect=function(t,i){var r=e.Vector3.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",r.x,r.y,r.z,0,i),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),i),this},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),this._worldMatrix},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_HEMISPHERICLIGHT},i.prototype.prepareLightSpecificDefines=function(e,t){e["HEMILIGHT"+t]=!0},n([e.serializeAsColor3()],i.prototype,"groundColor",void 0),n([e.serializeAsVector3()],i.prototype,"direction",void 0),i})(e.Light);e.HemisphericLight=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(){var e=null!==t&&t.apply(this,arguments)||this;return e._needProjectionMatrixCompute=!0,e}return o(i,t),i.prototype._setPosition=function(e){this._position=e},Object.defineProperty(i.prototype,"position",{get:function(){return this._position},set:function(e){this._setPosition(e)},enumerable:!0,configurable:!0}),i.prototype._setDirection=function(e){this._direction=e},Object.defineProperty(i.prototype,"direction",{get:function(){return this._direction},set:function(e){this._setDirection(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowMinZ",{get:function(){return this._shadowMinZ},set:function(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowMaxZ",{get:function(){return this._shadowMaxZ},set:function(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),i.prototype.computeTransformedInformation=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=e.Vector3.Zero()),e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=e.Vector3.Zero()),e.Vector3.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0)},i.prototype.getDepthScale=function(){return 50},i.prototype.getShadowDirection=function(e){return this.transformedDirection?this.transformedDirection:this.direction},i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(this.position)),this.direction},i.prototype.getRotation=function(){this.direction.normalize();var t=e.Vector3.Cross(this.direction,e.Axis.Y),i=e.Vector3.Cross(t,this.direction);return e.Vector3.RotationFromAxis(t,i,this.direction)},i.prototype.needCube=function(){return!1},i.prototype.needProjectionMatrixCompute=function(){return this._needProjectionMatrixCompute},i.prototype.forceProjectionMatrixCompute=function(){this._needProjectionMatrixCompute=!0},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this._worldMatrix},i.prototype.getDepthMinZ=function(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ},i.prototype.getDepthMaxZ=function(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ},i.prototype.setShadowProjectionMatrix=function(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this},n([e.serializeAsVector3()],i.prototype,"position",null),n([e.serializeAsVector3()],i.prototype,"direction",null),n([e.serialize()],i.prototype,"shadowMinZ",null),n([e.serialize()],i.prototype,"shadowMaxZ",null),i})(e.Light);e.ShadowLight=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_0",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(e,i,r){var n=t.call(this,e,r)||this;return n._shadowAngle=Math.PI/2,n.position=i,n}return o(i,t),Object.defineProperty(i.prototype,"shadowAngle",{get:function(){return this._shadowAngle},set:function(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"direction",{get:function(){return this._direction},set:function(e){var t=this.needCube();this._direction=e,this.needCube()!==t&&this._shadowGenerator&&this._shadowGenerator.recreateShadowMap()},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"PointLight"},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_POINTLIGHT},i.prototype.needCube=function(){return!this.direction},i.prototype.getShadowDirection=function(i){if(this.direction)return t.prototype.getShadowDirection.call(this,i);switch(i){case 0:return new e.Vector3(1,0,0);case 1:return new e.Vector3(-1,0,0);case 2:return new e.Vector3(0,-1,0);case 3:return new e.Vector3(0,1,0);case 4:return new e.Vector3(0,0,1);case 5:return new e.Vector3(0,0,-1)}return e.Vector3.Zero()},i.prototype._setDefaultShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;n&&e.Matrix.PerspectiveFovLHToRef(this.shadowAngle,1,this.getDepthMinZ(n),this.getDepthMaxZ(n),t)},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this)},i.prototype.prepareLightSpecificDefines=function(e,t){e["POINTLIGHT"+t]=!0},n([e.serialize()],i.prototype,"shadowAngle",null),i})(e.ShadowLight);e.PointLight=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_1",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(e,i,r){var n=t.call(this,e,r)||this;return n._shadowFrustumSize=0,n._shadowOrthoScale=.1,n.autoUpdateExtends=!0,n._orthoLeft=Number.MAX_VALUE,n._orthoRight=Number.MIN_VALUE,n._orthoTop=Number.MIN_VALUE,n._orthoBottom=Number.MAX_VALUE,n.position=i.scale(-1),n.direction=i,n}return o(i,t),Object.defineProperty(i.prototype,"shadowFrustumSize",{get:function(){return this._shadowFrustumSize},set:function(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowOrthoScale",{get:function(){return this._shadowOrthoScale},set:function(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"DirectionalLight"},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_DIRECTIONALLIGHT},i.prototype._setDefaultShadowProjectionMatrix=function(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e,t):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)},i.prototype._setDefaultFixedFrustumShadowProjectionMatrix=function(t,i){var r=this.getScene().activeCamera;r&&e.Matrix.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,t)},i.prototype._setDefaultAutoExtendShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;if(n){if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){var o=e.Vector3.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;for(var s=0;sthis._orthoRight&&(this._orthoRight=o.x),o.y>this._orthoTop&&(this._orthoTop=o.y)}}var u=this._orthoRight-this._orthoLeft,d=this._orthoTop-this._orthoBottom;e.Matrix.OrthoOffCenterLHToRef(this._orthoLeft-u*this.shadowOrthoScale,this._orthoRight+u*this.shadowOrthoScale,this._orthoBottom-d*this.shadowOrthoScale,this._orthoTop+d*this.shadowOrthoScale,void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,t)}},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)},i.prototype.getDepthMinZ=function(e){return 1},i.prototype.getDepthMaxZ=function(e){return 1},i.prototype.prepareLightSpecificDefines=function(e,t){e["DIRLIGHT"+t]=!0},n([e.serialize()],i.prototype,"shadowFrustumSize",null),n([e.serialize()],i.prototype,"shadowOrthoScale",null),n([e.serialize()],i.prototype,"autoUpdateExtends",void 0),i})(e.ShadowLight);e.DirectionalLight=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_2",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),e.Vector3.Zero(),0,0,r)}}));var t=(function(t){function i(i,r,n,o,s,a){var l=t.call(this,i,a)||this;return l._projectionTextureMatrix=e.Matrix.Zero(),l._projectionTextureLightNear=1e-6,l._projectionTextureLightFar=1e3,l._projectionTextureUpDirection=e.Vector3.Up(),l._projectionTextureViewLightDirty=!0,l._projectionTextureProjectionLightDirty=!0,l._projectionTextureDirty=!0,l._projectionTextureViewTargetVector=e.Vector3.Zero(),l._projectionTextureViewLightMatrix=e.Matrix.Zero(),l._projectionTextureProjectionLightMatrix=e.Matrix.Zero(),l._projectionTextureScalingMatrix=e.Matrix.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),l.position=r,l.direction=n,l.angle=o,l.exponent=s,l}return o(i,t),Object.defineProperty(i.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowAngleScale",{get:function(){return this._shadowAngleScale},set:function(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureMatrix",{get:function(){return this._projectionTextureMatrix},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureLightNear",{get:function(){return this._projectionTextureLightNear},set:function(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureLightFar",{get:function(){return this._projectionTextureLightFar},set:function(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureUpDirection",{get:function(){return this._projectionTextureUpDirection},set:function(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTexture",{get:function(){return this._projectionTexture},set:function(e){this._projectionTexture=e,this._projectionTextureDirty=!0},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"SpotLight"},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_SPOTLIGHT},i.prototype._setDirection=function(e){t.prototype._setDirection.call(this,e),this._projectionTextureViewLightDirty=!0},i.prototype._setPosition=function(e){t.prototype._setPosition.call(this,e),this._projectionTextureViewLightDirty=!0},i.prototype._setDefaultShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;if(n){this._shadowAngleScale=this._shadowAngleScale||1;var o=this._shadowAngleScale*this._angle;e.Matrix.PerspectiveFovLHToRef(o,1,this.getDepthMinZ(n),this.getDepthMaxZ(n),t)}},i.prototype._computeProjectionTextureViewLightMatrix=function(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.position.addToRef(this.direction,this._projectionTextureViewTargetVector),e.Matrix.LookAtLHToRef(this.position,this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)},i.prototype._computeProjectionTextureProjectionLightMatrix=function(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;var t=this.projectionTextureLightFar,i=this.projectionTextureLightNear,r=t/(t-i),n=-r*i,o=1/Math.tan(this._angle/2);e.Matrix.FromValuesToRef(o/1,0,0,0,0,o,0,0,0,0,r,1,0,0,n,0,this._projectionTextureProjectionLightMatrix)},i.prototype._computeProjectionTextureMatrix=function(){this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(t,i){var r;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,i),r=e.Vector3.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,i),r=e.Vector3.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",r.x,r.y,r.z,Math.cos(.5*this.angle),i),this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),t.setMatrix("textureProjectionMatrix"+i,this._projectionTextureMatrix),t.setTexture("projectionLightSampler"+i,this.projectionTexture)),this},i.prototype.dispose=function(){t.prototype.dispose.call(this),this._projectionTexture&&this._projectionTexture.dispose()},i.prototype.prepareLightSpecificDefines=function(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!this.projectionTexture},n([e.serialize()],i.prototype,"angle",null),n([e.serialize()],i.prototype,"shadowAngleScale",null),n([e.serialize()],i.prototype,"exponent",void 0),n([e.serialize()],i.prototype,"projectionTextureLightNear",null),n([e.serialize()],i.prototype,"projectionTextureLightFar",null),n([e.serialize()],i.prototype,"projectionTextureUpDirection",null),n([e.serializeAsTexture("projectedLightTexture")],i.prototype,"_projectionTexture",void 0),i})(e.ShadowLight);e.SpotLight=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=e.Animation.ANIMATIONLOOPMODE_CYCLE}return t})();e.AnimationPropertiesOverride=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i){this.name=e,this.from=t,this.to=i}return e.prototype.clone=function(){return new e(this.name,this.from,this.to)},e})();e.AnimationRange=t;var i=(function(){function e(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}return e.prototype._clone=function(){return new e(this.frame,this.action,this.onlyOnce)},e})();e.AnimationEvent=i;var r=(function(){function t(e){this.path=e,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e.Vector3(t.x,0,t.y)},t.prototype.moveAhead=function(e){return void 0===e&&(e=.002),this.move(e),this},t.prototype.moveBack=function(e){return void 0===e&&(e=.002),this.move(-e),this},t.prototype.move=function(e){if(Math.abs(e)>1)throw"step size should be less than 1.";return this.value+=e,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.raiseOnChange=function(){var e=this;return this._onchange.forEach((function(t){return t(e)})),this},t.prototype.onchange=function(e){return this._onchange.push(e),this},t})();e.PathCursor=r;var n;!(function(e){e[e.STEP=1]="STEP"})(n=e.AnimationKeyInterpolation||(e.AnimationKeyInterpolation={}));var o=(function(){function i(e,t,r,n,o,s){this.name=e,this.targetProperty=t,this.framePerSecond=r,this.dataType=n,this.loopMode=o,this.enableBlending=s,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=n,this.loopMode=void 0===o?i.ANIMATIONLOOPMODE_CYCLE:o}return i._PrepareAnimation=function(t,r,n,o,s,a,l,c){var h=void 0;if(!isNaN(parseFloat(s))&&isFinite(s)?h=i.ANIMATIONTYPE_FLOAT:s instanceof e.Quaternion?h=i.ANIMATIONTYPE_QUATERNION:s instanceof e.Vector3?h=i.ANIMATIONTYPE_VECTOR3:s instanceof e.Vector2?h=i.ANIMATIONTYPE_VECTOR2:s instanceof e.Color3?h=i.ANIMATIONTYPE_COLOR3:s instanceof e.Size&&(h=i.ANIMATIONTYPE_SIZE),void 0==h)return null;var u=new i(t,r,n,h,l),d=[{frame:0,value:s},{frame:o,value:a}];return u.setKeys(d),void 0!==c&&u.setEasingFunction(c),u},i.CreateAnimation=function(e,t,r,n){var o=new i(e+"Animation",e,r,t,i.ANIMATIONLOOPMODE_CONSTANT);return o.setEasingFunction(n),o},i.CreateAndStartAnimation=function(e,t,r,n,o,s,a,l,c,h){var u=i._PrepareAnimation(e,r,n,o,s,a,l,c);return u?t.getScene().beginDirectAnimation(t,[u],0,o,1===u.loopMode,1,h):null},i.CreateAndStartHierarchyAnimation=function(e,t,r,n,o,s,a,l,c,h,u){var d=i._PrepareAnimation(e,n,o,s,a,l,c,h);return d?t.getScene().beginDirectHierarchyAnimation(t,r,[d],0,s,1===d.loopMode,1,u):null},i.CreateMergeAndStartAnimation=function(e,t,r,n,o,s,a,l,c,h){var u=i._PrepareAnimation(e,r,n,o,s,a,l,c);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,o,1===u.loopMode,1,h)):null},i.TransitionTo=function(e,t,i,r,n,o,s,a){if(void 0===a&&(a=null),s<=0)return i[e]=t,a&&a(),null;var l=n*(s/1e3);o.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(o);var c=r.beginAnimation(i,0,l,!1);return c.onAnimationEnd=a,c},Object.defineProperty(i.prototype,"runtimeAnimations",{get:function(){return this._runtimeAnimations},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"hasRunningRuntimeAnimations",{get:function(){for(var e=0,t=this._runtimeAnimations;e=0;o--)this._keys[o].frame>=r&&this._keys[o].frame<=n&&this._keys.splice(o,1);this._ranges[e]=null}},i.prototype.getRange=function(e){return this._ranges[e]},i.prototype.getKeys=function(){return this._keys},i.prototype.getHighestFrame=function(){for(var e=0,t=0,i=this._keys.length;t0)return a.clone?a.clone():a;var l=this.getKeys(),c=Math.max(0,Math.min(l.length-1,Math.floor(l.length*(e-l[0].frame)/(l[l.length-1].frame-l[0].frame))-1));if(l[c].frame>=e)for(;c-1>=0&&l[c].frame>=e;)c--;for(var h=c;h=e){var d=l[h],f=this._getKeyValue(d.value);if(d.interpolation===n.STEP)return f;var p=this._getKeyValue(u.value),_=void 0!==d.outTangent&&void 0!==u.inTangent,m=u.frame-d.frame,g=(e-d.frame)/m,v=this.getEasingFunction();switch(null!=v&&(g=v.ease(g)),this.dataType){case i.ANIMATIONTYPE_FLOAT:var y=_?this.floatInterpolateFunctionWithTangents(f,d.outTangent*m,p,u.inTangent*m,g):this.floatInterpolateFunction(f,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return y;case i.ANIMATIONLOOPMODE_RELATIVE:return s*t+y}break;case i.ANIMATIONTYPE_QUATERNION:var b=_?this.quaternionInterpolateFunctionWithTangents(f,d.outTangent.scale(m),p,u.inTangent.scale(m),g):this.quaternionInterpolateFunction(f,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return b;case i.ANIMATIONLOOPMODE_RELATIVE:return b.addInPlace(s.scale(t))}return b;case i.ANIMATIONTYPE_VECTOR3:var x=_?this.vector3InterpolateFunctionWithTangents(f,d.outTangent.scale(m),p,u.inTangent.scale(m),g):this.vector3InterpolateFunction(f,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return x;case i.ANIMATIONLOOPMODE_RELATIVE:return x.add(s.scale(t))}case i.ANIMATIONTYPE_VECTOR2:var T=_?this.vector2InterpolateFunctionWithTangents(f,d.outTangent.scale(m),p,u.inTangent.scale(m),g):this.vector2InterpolateFunction(f,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return T;case i.ANIMATIONLOOPMODE_RELATIVE:return T.add(s.scale(t))}case i.ANIMATIONTYPE_SIZE:switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(f,p,g);case i.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(f,p,g).add(s.scale(t))}case i.ANIMATIONTYPE_COLOR3:switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.color3InterpolateFunction(f,p,g);case i.ANIMATIONLOOPMODE_RELATIVE:return this.color3InterpolateFunction(f,p,g).add(s.scale(t))}case i.ANIMATIONTYPE_MATRIX:switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:if(i.AllowMatricesInterpolation)return this.matrixInterpolateFunction(f,p,g,r);case i.ANIMATIONLOOPMODE_RELATIVE:return f}}break}}return this._getKeyValue(l[l.length-1].value)},i.prototype.matrixInterpolateFunction=function(t,r,n,o){return i.AllowMatrixDecomposeForInterpolation?o?(e.Matrix.DecomposeLerpToRef(t,r,n,o),o):e.Matrix.DecomposeLerp(t,r,n):o?(e.Matrix.LerpToRef(t,r,n,o),o):e.Matrix.Lerp(t,r,n)},i.prototype.clone=function(){var e=new i(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(var t in this._ranges){var r=this._ranges[t];r&&(e._ranges[t]=r.clone())}}return e},i.prototype.setKeys=function(e){this._keys=e.slice(0)},i.prototype.serialize=function(){var e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;var t=this.dataType;e.keys=[];for(var r=this.getKeys(),n=0;n=1&&(l=h.values[1]),h.values.length>=2&&(c=h.values[2]);break;case i.ANIMATIONTYPE_QUATERNION:if(r=e.Quaternion.FromArray(h.values),h.values.length>=8){var u=e.Quaternion.FromArray(h.values.slice(4,8));u.equals(e.Quaternion.Zero())||(l=u)}if(h.values.length>=12){var d=e.Quaternion.FromArray(h.values.slice(8,12));d.equals(e.Quaternion.Zero())||(c=d)}break;case i.ANIMATIONTYPE_MATRIX:r=e.Matrix.FromArray(h.values);break;case i.ANIMATIONTYPE_COLOR3:r=e.Color3.FromArray(h.values);break;case i.ANIMATIONTYPE_VECTOR3:default:r=e.Vector3.FromArray(h.values)}var f={};f.frame=h.frame,f.value=r,void 0!=l&&(f.inTangent=l),void 0!=c&&(f.outTangent=c),a.push(f)}if(o.setKeys(a),t.ranges)for(n=0;nr[0].frame&&(this._from=r[0].frame),this._toe){var a={frame:e,value:o.value,inTangent:o.inTangent,outTangent:o.outTangent,interpolation:o.interpolation};n.splice(0,0,a)}if(s.frame-1&&this._scene.animationGroups.splice(e,1)},t.prototype._checkAnimationGroupEnded=function(e){var t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))},t})();e.AnimationGroup=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i,r){var n=this;this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._targetPath="",this._weight=1,this._ratioOffset=0,this._previousDelay=0,this._previousRatio=0,this._animation=t,this._target=e,this._scene=i,this._host=r,t._runtimeAnimations.push(this);var o=t.getEvents();o&&o.length>0&&o.forEach((function(e){n._events.push(e._clone())}))}return Object.defineProperty(t.prototype,"currentFrame",{get:function(){return this._currentFrame},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weight",{get:function(){return this._weight},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentValue",{get:function(){return this._currentValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"targetPath",{get:function(){return this._targetPath},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){return this._activeTarget},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animation",{get:function(){return this._animation},enumerable:!0,configurable:!0}),t.prototype.reset=function(e){if(void 0===e&&(e=!1),e)if(this._target instanceof Array)for(var t=0,i=0,r=this._target;i-1&&this._animation.runtimeAnimations.splice(e,1)},t.prototype._interpolate=function(t,i,r,n,o){return this._currentFrame=t,this._animation.dataType!==e.Animation.ANIMATIONTYPE_MATRIX||this._workValue||(this._workValue=e.Matrix.Zero()),this._animation._interpolate(t,i,this._workValue,r,n,o)},t.prototype.setValue=function(e,t){if(void 0===t&&(t=1),this._target instanceof Array)for(var i=0,r=0,n=this._target;r1){for(var l=t[a[0]],c=1;ct[t.length-1].frame&&(e=t[t.length-1].frame);var i=this._interpolate(e,0,this._getCorrectLoopMode());this.setValue(i,-1)},t.prototype._prepareForSpeedRatioChange=function(e){var t=this._previousDelay*(this._animation.framePerSecond*e)/1e3;this._ratioOffset=this._previousRatio-t},t.prototype.animate=function(t,i,r,n,o,s){void 0===s&&(s=-1);var a=this._animation.targetPropertyPath;if(!a||a.length<1)return this._stopped=!0,!1;var l=!0,c=this._animation.getKeys();if(0!==c[0].frame){var h={frame:0,value:c[0].value};c.splice(0,0,h)}else if(1===c.length){var h={frame:.001,value:c[0].value};c.push(h)}(ic[c.length-1].frame)&&(i=c[0].frame),(rc[c.length-1].frame)&&(r=c[c.length-1].frame),i===r&&(i>c[0].frame?i--:ri&&f>=d||i>r&&f<=d)&&!n)l=!1,p=this._animation._getKeyValue(c[c.length-1].value);else if(this._getCorrectLoopMode()!==e.Animation.ANIMATIONLOOPMODE_CYCLE){var _=r.toString()+i.toString();if(!this._offsetsCache[_]){var m=this._interpolate(i,0,e.Animation.ANIMATIONLOOPMODE_CYCLE),g=this._interpolate(r,0,e.Animation.ANIMATIONLOOPMODE_CYCLE);switch(this._animation.dataType){case e.Animation.ANIMATIONTYPE_FLOAT:this._offsetsCache[_]=g-m;break;case e.Animation.ANIMATIONTYPE_QUATERNION:this._offsetsCache[_]=g.subtract(m);break;case e.Animation.ANIMATIONTYPE_VECTOR3:this._offsetsCache[_]=g.subtract(m);case e.Animation.ANIMATIONTYPE_VECTOR2:this._offsetsCache[_]=g.subtract(m);case e.Animation.ANIMATIONTYPE_SIZE:this._offsetsCache[_]=g.subtract(m);case e.Animation.ANIMATIONTYPE_COLOR3:this._offsetsCache[_]=g.subtract(m)}this._highLimitsCache[_]=g}p=this._highLimitsCache[_],u=this._offsetsCache[_]}if(void 0===u)switch(this._animation.dataType){case e.Animation.ANIMATIONTYPE_FLOAT:u=0;break;case e.Animation.ANIMATIONTYPE_QUATERNION:u=new e.Quaternion(0,0,0,0);break;case e.Animation.ANIMATIONTYPE_VECTOR3:u=e.Vector3.Zero();break;case e.Animation.ANIMATIONTYPE_VECTOR2:u=e.Vector2.Zero();break;case e.Animation.ANIMATIONTYPE_SIZE:u=e.Size.Zero();break;case e.Animation.ANIMATIONTYPE_COLOR3:u=e.Color3.Black()}var v=f/d>>0,y=l?i+f%d:r;if(this._host&&this._host.syncRoot){var b=this._host.syncRoot;y=i+(r-i)*((b.masterFrame-b.fromFrame)/(b.toFrame-b.fromFrame))}var x=this._events;if(d>0&&this.currentFrame>y||d<0&&this.currentFrame0&&y>=x[T].frame&&x[T].frame>=i||d<0&&y<=x[T].frame&&x[T].frame<=i){var P=x[T];P.isDone||(P.onlyOnce&&(x.splice(T,1),T--),P.isDone=!0,P.action())}return l||(this._stopped=!0),l},t})();e.RuntimeAnimation=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a,l){void 0===r&&(r=0),void 0===n&&(n=100),void 0===o&&(o=!1),void 0===s&&(s=1),this.target=i,this.fromFrame=r,this.toFrame=n,this.loopAnimation=o,this.onAnimationEnd=a,this._localDelayOffset=null,this._pausedDelay=null,this._runtimeAnimations=new Array,this._paused=!1,this._speedRatio=1,this._weight=-1,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new e.Observable,this._scene=t,l&&this.appendAnimations(i,l),this._speedRatio=s,t._activeAnimatables.push(this)}return Object.defineProperty(t.prototype,"syncRoot",{get:function(){return this._syncRoot},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"masterFrame",{get:function(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weight",{get:function(){return this._weight},set:function(e){if(-1===e)return void(this._weight=-1);this._weight=Math.min(Math.max(e,0),1)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"speedRatio",{get:function(){return this._speedRatio},set:function(e){for(var t=0;t-1&&(this._scene._activeAnimatables.splice(t,1),this._scene._activeAnimatables.push(this))}return this},t.prototype.getAnimations=function(){return this._runtimeAnimations},t.prototype.appendAnimations=function(t,i){for(var r=0;r-1){for(var r=this._runtimeAnimations,n=r.length-1;n>=0;n--){var o=r[n];e&&o.animation.name!=e||(t&&!t(o.target)||(o.dispose(),r.splice(n,1)))}0==r.length&&(this._scene._activeAnimatables.splice(i,1),this._raiseOnAnimationEnd())}}else{var n=this._scene._activeAnimatables.indexOf(this);if(n>-1){this._scene._activeAnimatables.splice(n,1);for(var r=this._runtimeAnimations,n=0;n=.5?.5*(1-this.easeInCore(2*(1-t)))+.5:.5*this.easeInCore(2*t)},e._EASINGMODE_EASEIN=0,e._EASINGMODE_EASEOUT=1,e._EASINGMODE_EASEINOUT=2,e})();e.EasingFunction=t;var i=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)},t})(t);e.CircleEase=i;var r=(function(e){function t(t){void 0===t&&(t=1);var i=e.call(this)||this;return i.amplitude=t,i}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)},t})(t);e.BackEase=r;var n=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=2);var r=e.call(this)||this;return r.bounces=t,r.bounciness=i,r}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.bounces),i=this.bounciness;i<=1&&(i=1.001);var r=Math.pow(i,t),n=1-i,o=(1-r)/n+.5*r,s=e*o,a=Math.log(-s*(1-i)+1)/Math.log(i),l=Math.floor(a),c=l+1,h=(1-Math.pow(i,l))/(n*o),u=(1-Math.pow(i,c))/(n*o),d=.5*(h+u),f=e-d,p=d-h;return-Math.pow(1/i,t-l)/(p*p)*(f-p)*(f+p)},t})(t);e.BounceEase=n;var s=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e*e},t})(t);e.CubicEase=s;var a=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=3);var r=e.call(this)||this;return r.oscillations=t,r.springiness=i,r}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.oscillations),i=Math.max(0,this.springiness);return(0==i?e:(Math.exp(i*e)-1)/(Math.exp(i)-1))*Math.sin((6.283185307179586*t+1.5707963267948966)*e)},t})(t);e.ElasticEase=a;var l=(function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.exponent=t,i}return o(t,e),t.prototype.easeInCore=function(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)},t})(t);e.ExponentialEase=l;var c=(function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.power=t,i}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.power);return Math.pow(e,t)},t})(t);e.PowerEase=c;var h=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e},t})(t);e.QuadraticEase=h;var u=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e*e*e},t})(t);e.QuarticEase=u;var d=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e*e*e*e},t})(t);e.QuinticEase=d;var f=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return 1-Math.sin(1.5707963267948966*(1-e))},t})(t);e.SineEase=f;var p=(function(t){function i(e,i,r,n){void 0===e&&(e=0),void 0===i&&(i=0),void 0===r&&(r=1),void 0===n&&(n=1);var o=t.call(this)||this;return o.x1=e,o.y1=i,o.x2=r,o.y2=n,o}return o(i,t),i.prototype.easeInCore=function(t){return e.BezierCurve.interpolate(t,this.x1,this.y1,this.x2,this.y2)},i})(t);e.BezierCurveEase=p})(r||(r={}));var r;!(function(e){var t=(function(){function e(e){this._actionManager=e}return e.prototype.isValid=function(){return!0},e.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},e.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},e.prototype.serialize=function(){},e.prototype._serialize=function(e){return{type:2,children:[],name:e.name,properties:e.properties}},e})();e.Condition=t;var i=(function(t){function i(e,r,n,o,s){void 0===s&&(s=i.IsEqual);var a=t.call(this,e)||this;return a.propertyPath=n,a.value=o,a.operator=s,a._target=r,a._effectiveTarget=a._getEffectiveTarget(r,a.propertyPath),a._property=a._getProperty(a.propertyPath),a}return o(i,t),Object.defineProperty(i,"IsEqual",{get:function(){return i._IsEqual},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsDifferent",{get:function(){return i._IsDifferent},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsGreater",{get:function(){return i._IsGreater},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsLesser",{get:function(){return i._IsLesser},enumerable:!0,configurable:!0}),i.prototype.isValid=function(){switch(this.operator){case i.IsGreater:return this._effectiveTarget[this._property]>this.value;case i.IsLesser:return this._effectiveTarget[this._property]-1&&this._scene.actionManagers.splice(e,1)},t.prototype.getScene=function(){return this._scene},t.prototype.hasSpecificTriggers=function(e){for(var t=0;t-1)return!0}return!1},t.prototype.hasSpecificTrigger=function(e,t){for(var i=0;i=t._OnPickTrigger&&i.trigger<=t._OnPointerOutTrigger)return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPickTriggers",{get:function(){for(var e=0;e=t._OnPickTrigger&&i.trigger<=t._OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"HasTriggers",{get:function(){for(var e in t.Triggers)if(t.Triggers.hasOwnProperty(e))return!0;return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"HasPickTriggers",{get:function(){for(var e in t.Triggers)if(t.Triggers.hasOwnProperty(e)){var i=parseInt(e);if(i>=t._OnPickTrigger&&i<=t._OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),t.HasSpecificTrigger=function(e){for(var i in t.Triggers)if(t.Triggers.hasOwnProperty(i)){var r=parseInt(i);if(r===e)return!0}return!1},t.prototype.registerAction=function(i){return i.trigger===t.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(e.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(i),t.Triggers[i.trigger]?t.Triggers[i.trigger]++:t.Triggers[i.trigger]=1,i._actionManager=this,i._prepare(),i)},t.prototype.unregisterAction=function(e){var i=this.actions.indexOf(e);return-1!==i&&(this.actions.splice(i,1),t.Triggers[e.trigger]-=1,0===t.Triggers[e.trigger]&&delete t.Triggers[e.trigger],delete e._actionManager,!0)},t.prototype.processTrigger=function(e,i){for(var r=0;r0;if(2===i.type?d.push(o):d.push(r),_){for(var m=new Array,g=0;g0){var d=u.properties[0].value,f=null===u.properties[0].targetType?d:n.getMeshByName(d);f._meshId&&(f.mesh=n.getMeshByID(f._meshId)),h={trigger:t[u.name],parameter:f}}else h=t[u.name];for(var p=0;p>0;this._vertexData[o+10]=t.cellIndex-s*n,this._vertexData[o+11]=s,this._vertexData[o+12]=t.color.r,this._vertexData[o+13]=t.color.g,this._vertexData[o+14]=t.color.b,this._vertexData[o+15]=t.color.a},t.prototype.intersects=function(t,i,r,n){for(var o=Math.min(this._capacity,this.sprites.length),s=e.Vector3.Zero(),a=e.Vector3.Zero(),l=Number.MAX_VALUE,c=null,h=e.Vector3.Zero(),u=i.getViewMatrix(),d=0;dp&&(l=p,c=f,n))break}}}if(c){var _=new e.PickingInfo;return _.hit=!0,_.pickedSprite=c,_.distance=l,_}return null},t.prototype.render=function(){if(this._effectBase.isReady()&&this._effectFog.isReady()&&this._spriteTexture&&this._spriteTexture.isReady()){for(var t=this._scene.getEngine(),i=this._spriteTexture.getBaseSize(),r=t.getDeltaTime(),n=Math.min(this._capacity,this.sprites.length),o=i.width/this.cellWidth,s=0,a=0;athis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,this.cellIndex>this._toIndex&&(this._loopAnimation?this.cellIndex=this._fromIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()))))},t.prototype.dispose=function(){for(var e=0;et.x)return!1}else if(i=1/this.direction.x,r=(e.x-this.origin.x)*i,n=(t.x-this.origin.x)*i,n===-1/0&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yt.y)return!1}else if(i=1/this.direction.y,r=(e.y-this.origin.y)*i,n=(t.y-this.origin.y)*i,n===-1/0&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zt.z)return!1}else if(i=1/this.direction.z,r=(e.z-this.origin.z)*i,n=(t.z-this.origin.z)*i,n===-1/0&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;return!0},t.prototype.intersectsBox=function(e){return this.intersectsBoxMinMax(e.minimum,e.maximum)},t.prototype.intersectsSphere=function(e){var t=e.center.x-this.origin.x,i=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=t*t+i*i+r*r,o=e.radius*e.radius;if(n<=o)return!0;var s=t*this.direction.x+i*this.direction.y+r*this.direction.z;return!(s<0)&&n-s*s<=o},t.prototype.intersectsTriangle=function(t,i,r){this._edge1||(this._edge1=e.Vector3.Zero(),this._edge2=e.Vector3.Zero(),this._pvec=e.Vector3.Zero(),this._tvec=e.Vector3.Zero(),this._qvec=e.Vector3.Zero()),i.subtractToRef(t,this._edge1),r.subtractToRef(t,this._edge2),e.Vector3.CrossToRef(this.direction,this._edge2,this._pvec);var n=e.Vector3.Dot(this._edge1,this._pvec);if(0===n)return null;var o=1/n;this.origin.subtractToRef(t,this._tvec);var s=e.Vector3.Dot(this._tvec,this._pvec)*o;if(s<0||s>1)return null;e.Vector3.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Vector3.Dot(this.direction,this._qvec)*o;if(a<0||s+a>1)return null;var l=e.Vector3.Dot(this._edge2,this._qvec)*o;return l>this.length?null:new e.IntersectionInfo(s,a,l)},t.prototype.intersectsPlane=function(t){var i,r=e.Vector3.Dot(t.normal,this.direction);if(Math.abs(r)<9.99999997475243e-7)return null;var n=e.Vector3.Dot(t.normal,this.origin);return i=(-t.d-n)/r,i<0?i<-9.99999997475243e-7?null:0:i},t.prototype.intersectsMesh=function(i,r){var n=e.Tmp.Matrix[0];return i.getWorldMatrix().invertToRef(n),this._tmpRay?t.TransformToRef(this,n,this._tmpRay):this._tmpRay=t.Transform(this,n),i.intersects(this._tmpRay,r)},t.prototype.intersectsMeshes=function(e,t,i){i?i.length=0:i=[];for(var r=0;rt.distance?1:0},t.prototype.intersectionSegment=function(i,r,n){var o,s,a,l,c=this.origin.add(this.direction.multiplyByFloats(t.rayl,t.rayl,t.rayl)),h=r.subtract(i),u=c.subtract(this.origin),d=i.subtract(this.origin),f=e.Vector3.Dot(h,h),p=e.Vector3.Dot(h,u),_=e.Vector3.Dot(u,u),m=e.Vector3.Dot(h,d),g=e.Vector3.Dot(u,d),v=f*_-p*p,y=v,b=v;vy&&(s=y,l=g+p,b=_)),l<0?(l=0,-m<0?s=0:-m>f?s=y:(s=-m,y=f)):l>b&&(l=b,-m+p<0?s=0:-m+p>f?s=y:(s=-m+p,y=f)),o=Math.abs(s)0&&a<=this.length&&T.lengthSquared()i.x+r)&&(!(i.x-r>t.x)&&(!(e.y>i.y+r)&&(!(i.y-r>t.y)&&(!(e.z>i.z+r)&&!(i.z-r>t.z)))))},i=(function(){var e={root:0,found:!1};return function(t,i,r,n){e.root=0,e.found=!1;var o=i*i-4*t*r;if(o<0)return e;var s=Math.sqrt(o),a=(-i-s)/(2*t),l=(-i+s)/(2*t);if(a>l){var c=l;l=a,a=c}return a>0&&a0&&l=0))},r.prototype._canDoCollision=function(i,r,n,o){var s=e.Vector3.Distance(this._basePointWorld,i),a=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+a+r)&&!!t(n,o,this._basePointWorld,this._velocityWorldLength+a)},r.prototype._testTriangle=function(t,r,n,o,s,a){var l,c=!1;r||(r=[]),r[t]||(r[t]=new e.Plane(0,0,0,0),r[t].copyFromPoints(n,o,s));var h=r[t];if(a||h.isFrontFacingTo(this._normalizedVelocity,0)){var u=h.signedDistanceTo(this._basePoint),d=e.Vector3.Dot(h.normal,this._velocity);if(0==d){if(Math.abs(u)>=1)return;c=!0,l=0}else{l=(-1-u)/d;var f=(1-u)/d;if(l>f){var p=f;f=l,l=p}if(l>1||f<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);var _=!1,m=1;if(c||(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(l,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,n,o,s,h.normal)&&(_=!0,m=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!_){var g=this._velocity.lengthSquared(),v=g;this._basePoint.subtractToRef(n,this._tempVector);var y=2*e.Vector3.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,x=i(v,y,b,m);x.found&&(m=x.root,_=!0,this._collisionPoint.copyFrom(n)),this._basePoint.subtractToRef(o,this._tempVector),y=2*e.Vector3.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,x=i(v,y,b,m),x.found&&(m=x.root,_=!0,this._collisionPoint.copyFrom(o)),this._basePoint.subtractToRef(s,this._tempVector),y=2*e.Vector3.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,x=i(v,y,b,m),x.found&&(m=x.root,_=!0,this._collisionPoint.copyFrom(s)),o.subtractToRef(n,this._edge),n.subtractToRef(this._basePoint,this._baseToVertex);var T=this._edge.lengthSquared(),E=e.Vector3.Dot(this._edge,this._velocity),P=e.Vector3.Dot(this._edge,this._baseToVertex);if(v=T*-g+E*E,y=T*(2*e.Vector3.Dot(this._velocity,this._baseToVertex))-2*E*P,b=T*(1-this._baseToVertex.lengthSquared())+P*P,x=i(v,y,b,m),x.found){var A=(E*x.root-P)/T;A>=0&&A<=1&&(m=x.root,_=!0,this._edge.scaleInPlace(A),n.addToRef(this._edge,this._collisionPoint))}s.subtractToRef(o,this._edge),o.subtractToRef(this._basePoint,this._baseToVertex),T=this._edge.lengthSquared(),E=e.Vector3.Dot(this._edge,this._velocity),P=e.Vector3.Dot(this._edge,this._baseToVertex),v=T*-g+E*E,y=T*(2*e.Vector3.Dot(this._velocity,this._baseToVertex))-2*E*P,b=T*(1-this._baseToVertex.lengthSquared())+P*P,x=i(v,y,b,m),x.found&&(A=(E*x.root-P)/T)>=0&&A<=1&&(m=x.root,_=!0,this._edge.scaleInPlace(A),o.addToRef(this._edge,this._collisionPoint)),n.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),T=this._edge.lengthSquared(),E=e.Vector3.Dot(this._edge,this._velocity),P=e.Vector3.Dot(this._edge,this._baseToVertex),v=T*-g+E*E,y=T*(2*e.Vector3.Dot(this._velocity,this._baseToVertex))-2*E*P,b=T*(1-this._baseToVertex.lengthSquared())+P*P,x=i(v,y,b,m),x.found&&(A=(E*x.root-P)/T)>=0&&A<=1&&(m=x.root,_=!0,this._edge.scaleInPlace(A),s.addToRef(this._edge,this._collisionPoint))}if(_){var M=m*this._velocity.length();(!this.collisionFound||M4)){++n._runningUpdated;var e={updatedMeshes:n._addUpdateMeshesList,updatedGeometries:n._addUpdateGeometriesList, -removedGeometries:n._toRemoveGeometryArray,removedMeshes:n._toRemoveMeshesArray},i={payload:e,taskType:t.UPDATE},r=[];for(var o in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(o)&&(r.push(i.payload.updatedGeometries[o].indices.buffer),r.push(i.payload.updatedGeometries[o].normals.buffer),r.push(i.payload.updatedGeometries[o].positions.buffer));n._worker.postMessage(i,r),n._addUpdateMeshesList={},n._addUpdateGeometriesList={},n._toRemoveGeometryArray=[],n._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(r){var o=r.data;if(o.error!=i.SUCCESS)return void e.Tools.Warn("error returned from worker!");switch(o.taskType){case t.INIT:n._init=!0,n._scene.meshes.forEach((function(e){n.onMeshAdded(e)})),n._scene.getGeometries().forEach((function(e){n.onGeometryAdded(e)}));break;case t.UPDATE:n._runningUpdated--;break;case t.COLLIDE:var s=o.payload;if(!n._collisionsCallbackArray[s.collisionId])return;var a=n._collisionsCallbackArray[s.collisionId];if(a){var l=n._scene.getMeshByUniqueID(s.collidedMeshUniqueId);l&&a(s.collisionId,e.Vector3.FromArray(s.newPosition),l)}n._collisionsCallbackArray[s.collisionId]=null}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return r.prototype.getNewPosition=function(e,i,r,n,o,s,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(r._radius,this._scaledPosition),i.divideToRef(r._radius,this._scaledVelocity),this._collisionsCallbackArray[a]=s;var l={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:r._radius.asArray()},collisionId:a,excludedMeshUniqueId:o?o.uniqueId:null,maximumRetry:n},c={payload:l,taskType:t.COLLIDE};this._worker.postMessage(c)}},r.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var r=e.WorkerIncluded?e.Engine.CodeRepository+"Collisions/babylon.collisionWorker.js":URL.createObjectURL(new Blob([e.CollisionWorker],{type:"application/javascript"}));this._worker=new Worker(r),this._worker.onmessage=this._onMessageFromWorker;var n={payload:{},taskType:t.INIT};this._worker.postMessage(n)},r.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},r.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},r.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},r.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},r.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},r.SerializeMesh=function(t){var i=[];t.subMeshes&&(i=t.subMeshes.map((function(e,t){var i=e.getBoundingInfo();return{position:t,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:i.boundingSphere.centerWorld.asArray(),sphereRadius:i.boundingSphere.radiusWorld,boxMinimum:i.boundingBox.minimumWorld.asArray(),boxMaximum:i.boundingBox.maximumWorld.asArray()}})));var r=null;if(t instanceof e.Mesh){var n=t.geometry;r=n?n.id:null}else if(t instanceof e.InstancedMesh){var n=t.sourceMesh&&t.sourceMesh.geometry;r=n?n.id:null}var o=t.getBoundingInfo();return{uniqueId:t.uniqueId,id:t.id,name:t.name,geometryId:r,sphereCenter:o.boundingSphere.centerWorld.asArray(),sphereRadius:o.boundingSphere.radiusWorld,boxMinimum:o.boundingBox.minimumWorld.asArray(),boxMaximum:o.boundingBox.maximumWorld.asArray(),worldMatrixFromCache:t.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:t.checkCollisions}},r.SerializeGeometry=function(t){return{id:t.id,positions:new Float32Array(t.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(t.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Uint32Array(t.getIndices()||[])}},r})();e.CollisionCoordinatorWorker=r;var n=(function(){function t(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return t.prototype.getNewPosition=function(e,t,i,r,n,o,s){e.divideToRef(i._radius,this._scaledPosition),t.divideToRef(i._radius,this._scaledVelocity),i.collidedMesh=null,i._retry=0,i._initialVelocity=this._scaledVelocity,i._initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,r,this._finalPosition,n),this._finalPosition.multiplyInPlace(i._radius),o(s,this._finalPosition,i.collidedMesh)},t.prototype.init=function(e){this._scene=e},t.prototype.destroy=function(){},t.prototype.onMeshAdded=function(e){},t.prototype.onMeshUpdated=function(e){},t.prototype.onMeshRemoved=function(e){},t.prototype.onGeometryAdded=function(e){},t.prototype.onGeometryUpdated=function(e){},t.prototype.onGeometryDeleted=function(e){},t.prototype._collideWithWorld=function(t,i,r,n,o,s){void 0===s&&(s=null);var a=10*e.Engine.CollisionsEpsilon;if(r._retry>=n)return void o.copyFrom(t);var l=s?s.collisionMask:r.collisionMask;r._initialize(t,i,a);for(var c=0;c=n.lifeTime)return l._emitFromParticle(n),l.recycleParticle(n),o--,"continue";var s=n.age/n.lifeTime;l._colorGradients&&l._colorGradients.length>0?e.Tools.GetCurrentGradient(s,l._colorGradients,(function(t,i,r){t!==n._currentColorGradient&&(n._currentColor1.copyFrom(n._currentColor2),i.getColorToRef(n._currentColor2),n._currentColorGradient=t),e.Color4.LerpToRef(n._currentColor1,n._currentColor2,r,n.color)})):(n.colorStep.scaleToRef(l._scaledUpdateSpeed,l._scaledColorStep),n.color.addInPlace(l._scaledColorStep),n.color.a<0&&(n.color.a=0)),l._angularSpeedGradients&&l._angularSpeedGradients.length>0&&e.Tools.GetCurrentGradient(s,l._angularSpeedGradients,(function(t,i,r){t!==n._currentAngularSpeedGradient&&(n._currentAngularSpeed1=n._currentAngularSpeed2,n._currentAngularSpeed2=i.getFactor(),n._currentAngularSpeedGradient=t),n.angularSpeed=e.Scalar.Lerp(n._currentAngularSpeed1,n._currentAngularSpeed2,r)})),n.angle+=n.angularSpeed*l._scaledUpdateSpeed;var a=l._scaledUpdateSpeed;if(l._velocityGradients&&l._velocityGradients.length>0&&e.Tools.GetCurrentGradient(s,l._velocityGradients,(function(t,i,r){t!==n._currentVelocityGradient&&(n._currentVelocity1=n._currentVelocity2,n._currentVelocity2=i.getFactor(),n._currentVelocityGradient=t),a*=e.Scalar.Lerp(n._currentVelocity1,n._currentVelocity2,r)})),n.direction.scaleToRef(a,l._scaledDirection),n.position.addInPlace(l._scaledDirection),i&&r){var c=e.Tmp.Vector3[0],h=e.Tmp.Vector3[1];l._emitterWorldMatrix.getTranslationToRef(h),n.position.subtractToRef(h,c);var u=l._fetchR(c.y,c.z,r.width,r.height,i),d=l._fetchR(c.x+.33,c.z+.33,r.width,r.height,i),f=l._fetchR(c.x-.33,c.y-.33,r.width,r.height,i),p=e.Tmp.Vector3[0],_=e.Tmp.Vector3[1];p.copyFromFloats((2*u-1)*l.noiseStrength.x,(2*d-1)*l.noiseStrength.y,(2*f-1)*l.noiseStrength.z),p.scaleToRef(l._scaledUpdateSpeed,_),n.direction.addInPlace(_)}l.gravity.scaleToRef(l._scaledUpdateSpeed,l._scaledGravity),n.direction.addInPlace(l._scaledGravity),l._sizeGradients&&l._sizeGradients.length>0&&e.Tools.GetCurrentGradient(s,l._sizeGradients,(function(t,i,r){t!==n._currentSizeGradient&&(n._currentSize1=n._currentSize2,n._currentSize2=i.getFactor(),n._currentSizeGradient=t),n.size=e.Scalar.Lerp(n._currentSize1,n._currentSize2,r)})),l._isAnimationSheetEnabled&&n.updateCellIndex()})()}}return t.prototype.getColorGradients=function(){return this._colorGradients},t.prototype.getSizeGradients=function(){return this._sizeGradients},t.prototype.getLifeTimeGradients=function(){return this._lifeTimeGradients},t.prototype.getAngularSpeedGradients=function(){return this._angularSpeedGradients},t.prototype.getVelocityGradients=function(){return this._velocityGradients},Object.defineProperty(t.prototype,"direction1",{get:function(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction2",{get:function(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minEmitBox",{get:function(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxEmitBox",{get:function(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isAnimationSheetEnabled",{get:function(){return this._isAnimationSheetEnabled},set:function(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._resetEffect())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isBillboardBased",{get:function(){return this._isBillboardBased},set:function(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._resetEffect())},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},Object.defineProperty(t.prototype,"particles",{get:function(){return this._particles},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"ParticleSystem"},t.prototype._fetchR=function(e,t,i,r,n){return e=.5*Math.abs(e)+.5,t=.5*Math.abs(t)+.5,n[4*((e*i%i|0)+(t*r%r|0)*i)]/255},t.prototype._addFactorGradient=function(t,i,r,n){var o=new e.FactorGradient;o.gradient=i,o.factor1=r,o.factor2=n,t.push(o),t.sort((function(e,t){return e.gradientt.gradient?1:0}))},t.prototype._removeFactorGradient=function(e,t){if(e)for(var i=0,r=0,n=e;rt.gradient?1:0})),this},t.prototype.removeColorGradient=function(e){if(!this._colorGradients)return this;for(var t=0,i=0,r=this._colorGradients;i0,this.emitter.position){var i=this.emitter;this._emitterWorldMatrix=i.getWorldMatrix()}else{var r=this.emitter;this._emitterWorldMatrix=e.Matrix.Translation(r.x,r.y,r.z)}this.updateFunction(this._particles);for(var n,o,s=this,a=0;a0){var i=e.Scalar.Clamp(s._actualFrame/s.targetStopDuration);e.Tools.GetCurrentGradient(i,s._lifeTimeGradients,(function(t,r,o){var s=t,a=r,l=s.getFactor(),c=a.getFactor(),h=(i-s.gradient)/(a.gradient-s.gradient);n.lifeTime=e.Scalar.Lerp(l,c,h)}))}else n.lifeTime=e.Scalar.RandomRange(s.minLifeTime,s.maxLifeTime);s._sizeGradients&&0!==s._sizeGradients.length?(n._currentSizeGradient=s._sizeGradients[0],n._currentSize1=n._currentSizeGradient.getFactor(),n.size=n._currentSize1,s._sizeGradients.length>1?n._currentSize2=s._sizeGradients[1].getFactor():n._currentSize2=n._currentSize1):n.size=e.Scalar.RandomRange(s.minSize,s.maxSize),n.scale.copyFromFloats(e.Scalar.RandomRange(s.minScaleX,s.maxScaleX),e.Scalar.RandomRange(s.minScaleY,s.maxScaleY)),s._angularSpeedGradients&&0!==s._angularSpeedGradients.length?(n._currentAngularSpeedGradient=s._angularSpeedGradients[0],n.angularSpeed=n._currentAngularSpeedGradient.getFactor(),n._currentAngularSpeed1=n.angularSpeed,s._angularSpeedGradients.length>1?n._currentAngularSpeed2=s._angularSpeedGradients[1].getFactor():n._currentAngularSpeed2=n._currentAngularSpeed1):n.angularSpeed=e.Scalar.RandomRange(s.minAngularSpeed,s.maxAngularSpeed),n.angle=e.Scalar.RandomRange(s.minInitialRotation,s.maxInitialRotation),s._velocityGradients&&s._velocityGradients.length>0&&(n._currentVelocityGradient=s._velocityGradients[0],n._currentVelocity1=n._currentVelocityGradient.getFactor(),s._velocityGradients.length>1?n._currentVelocity2=s._velocityGradients[1].getFactor():n._currentVelocity2=n._currentVelocity1),s._colorGradients&&0!==s._colorGradients.length?(n._currentColorGradient=s._colorGradients[0],n._currentColorGradient.getColorToRef(n.color),n._currentColor1.copyFrom(n.color),s._colorGradients.length>1?s._colorGradients[1].getColorToRef(n._currentColor2):n._currentColor2.copyFrom(n.color)):(o=e.Scalar.RandomRange(0,1),e.Color4.LerpToRef(s.color1,s.color2,o,n.color),s.colorDead.subtractToRef(n.color,s._colorDiff),s._colorDiff.scaleToRef(1/n.lifeTime,n.colorStep)),s._isAnimationSheetEnabled&&(n._initialStartSpriteCellID=s.startSpriteCellID,n._initialEndSpriteCellID=s.endSpriteCellID)})())break}},t._GetAttributeNamesOrOptions=function(t,i){void 0===t&&(t=!1),void 0===i&&(i=!1);var r=[e.VertexBuffer.PositionKind,e.VertexBuffer.ColorKind,"angle","offset","size"];return t&&r.push("cellIndex"),i||r.push("direction"),r},t._GetEffectCreationOptions=function(e){void 0===e&&(e=!1);var t=["invView","view","projection","vClipPlane","textureMask","translationPivot","eyePosition"];return e&&t.push("particlesInfos"),t},t.prototype._getEffect=function(){if(this._customEffect)return this._customEffect;var i=[];if(this._scene.clipPlane&&i.push("#define CLIPPLANE"),this._isAnimationSheetEnabled&&i.push("#define ANIMATESHEET"),this._isBillboardBased)switch(i.push("#define BILLBOARD"),this.billboardMode){case e.AbstractMesh.BILLBOARDMODE_Y:i.push("#define BILLBOARDY");break;case e.AbstractMesh.BILLBOARDMODE_ALL:}var r=i.join("\n");if(this._cachedDefines!==r){this._cachedDefines=r;var n=t._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased),o=t._GetEffectCreationOptions(this._isAnimationSheetEnabled);this._effect=this._scene.getEngine().createEffect("particles",n,o,["diffuseSampler"],r)}return this._effect},t.prototype.animate=function(e){if(void 0===e&&(e=!1),this._started){if(!e){var t=this._getEffect();if(!(this.emitter&&t.isReady()&&this.particleTexture&&this.particleTexture.isReady()))return;if(this._currentRenderId===this._scene.getRenderId())return;this._currentRenderId=this._scene.getRenderId()}this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:this._scene.getAnimationRatio());var i;if(this.manualEmitCount>-1?(i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0):(i=this.emitRate*this._scaledUpdateSpeed>>0,this._newPartsExcess+=this.emitRate*this._scaledUpdateSpeed-i),this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene._toBeDisposed.push(this))),!e){for(var r=0,n=0;n-1&&this._scene.particleSystems.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.prototype.createPointEmitter=function(t,i){var r=new e.PointParticleEmitter;return r.direction1=t,r.direction2=i,this.particleEmitterType=r,r},t.prototype.createHemisphericEmitter=function(t,i){void 0===t&&(t=1),void 0===i&&(i=1);var r=new e.HemisphericParticleEmitter(t,i);return this.particleEmitterType=r,r},t.prototype.createSphereEmitter=function(t,i){void 0===t&&(t=1),void 0===i&&(i=1);var r=new e.SphereParticleEmitter(t,i);return this.particleEmitterType=r,r},t.prototype.createDirectedSphereEmitter=function(t,i,r){void 0===t&&(t=1),void 0===i&&(i=new e.Vector3(0,1,0)),void 0===r&&(r=new e.Vector3(0,1,0));var n=new e.SphereDirectedParticleEmitter(t,i,r);return this.particleEmitterType=n,n},t.prototype.createConeEmitter=function(t,i){void 0===t&&(t=1),void 0===i&&(i=Math.PI/4);var r=new e.ConeParticleEmitter(t,i);return this.particleEmitterType=r,r},t.prototype.createBoxEmitter=function(t,i,r,n){var o=new e.BoxParticleEmitter;return this.particleEmitterType=o,this.direction1=t,this.direction2=i,this.minEmitBox=r,this.maxEmitBox=n,o},t.prototype.clone=function(i,r){var n=null,o=null;if(null!=this.customShader){o=this.customShader;var s=o.shaderOptions.defines.length>0?o.shaderOptions.defines.join("\n"):"";n=this._scene.getEngine().createEffectForParticles(o.shaderPath.fragmentElement,o.shaderOptions.uniforms,o.shaderOptions.samplers,s)}else this._customEffect&&(n=this._customEffect);var a=new t(i,this._capacity,this._scene,n);return a.customShader=o,e.Tools.DeepCopy(this,a,["particles","customShader"]),void 0===r&&(r=this.emitter),a.emitter=r,this.particleTexture&&(a.particleTexture=new e.Texture(this.particleTexture.url,this._scene)),this.preventAutoStart||a.start(),a},t.prototype.serialize=function(){var e={} -;return t._Serialize(e,this),e.textureMask=this.textureMask.asArray(),e.customShader=this.customShader,e.preventAutoStart=this.preventAutoStart,e.isAnimationSheetEnabled=this._isAnimationSheetEnabled,e},t._Serialize=function(t,i){if(t.name=i.name,t.id=i.id,t.capacity=i.getCapacity(),i.emitter.position){var r=i.emitter;t.emitterId=r.id}else{var n=i.emitter;t.emitter=n.asArray()}i.particleEmitterType&&(t.particleEmitterType=i.particleEmitterType.serialize()),i.particleTexture&&(t.textureName=i.particleTexture.name),e.Animation.AppendSerializedAnimations(i,t),t.renderingGroupId=i.renderingGroupId,t.isBillboardBased=i.isBillboardBased,t.minAngularSpeed=i.minAngularSpeed,t.maxAngularSpeed=i.maxAngularSpeed,t.minSize=i.minSize,t.maxSize=i.maxSize,t.minScaleX=i.minScaleX,t.maxScaleX=i.maxScaleX,t.minScaleY=i.minScaleY,t.maxScaleY=i.maxScaleY,t.minEmitPower=i.minEmitPower,t.maxEmitPower=i.maxEmitPower,t.minLifeTime=i.minLifeTime,t.maxLifeTime=i.maxLifeTime,t.emitRate=i.emitRate,t.gravity=i.gravity.asArray(),t.noiseStrength=i.noiseStrength.asArray(),t.color1=i.color1.asArray(),t.color2=i.color2.asArray(),t.colorDead=i.colorDead.asArray(),t.updateSpeed=i.updateSpeed,t.targetStopDuration=i.targetStopDuration,t.blendMode=i.blendMode,t.preWarmCycles=i.preWarmCycles,t.preWarmStepOffset=i.preWarmStepOffset,t.minInitialRotation=i.minInitialRotation,t.maxInitialRotation=i.maxInitialRotation,t.startSpriteCellID=i.startSpriteCellID,t.endSpriteCellID=i.endSpriteCellID,t.spriteCellChangeSpeed=i.spriteCellChangeSpeed,t.spriteCellWidth=i.spriteCellWidth,t.spriteCellHeight=i.spriteCellHeight;var o=i.getColorGradients();if(o){t.colorGradients=[];for(var s=0,a=o;s0?a.shaderOptions.defines.join("\n"):"";s=r.getEngine().createEffectForParticles(a.shaderPath.fragmentElement,a.shaderOptions.uniforms,a.shaderOptions.samplers,l)}var c=new t(o,i.capacity,r,s,i.isAnimationSheetEnabled);return c.customShader=a,i.id&&(c.id=i.id),i.preventAutoStart&&(c.preventAutoStart=i.preventAutoStart),t._Parse(i,c,r,n),c.textureMask=e.Color4.FromArray(i.textureMask),c.preventAutoStart||c.start(),c},t.BLENDMODE_ONEONE=0,t.BLENDMODE_STANDARD=1,t.BLENDMODE_ADD=2,t})();e.ParticleSystem=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.direction1=new e.Vector3(0,1,0),this.direction2=new e.Vector3(0,1,0),this.minEmitBox=new e.Vector3(-.5,-.5,-.5),this.maxEmitBox=new e.Vector3(.5,.5,.5)}return t.prototype.startDirectionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.direction1.x,this.direction2.x),o=e.Scalar.RandomRange(this.direction1.y,this.direction2.y),s=e.Scalar.RandomRange(this.direction1.z,this.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(n,o,s,t,i)},t.prototype.startPositionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),o=e.Scalar.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),s=e.Scalar.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);e.Vector3.TransformCoordinatesFromFloatsToRef(n,o,s,t,i)},t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)},t.prototype.getEffectDefines=function(){return"#define BOXEMITTER"},t.prototype.getClassName=function(){return"BoxParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e},t.prototype.parse=function(t){e.Vector3.FromArrayToRef(t.direction1,0,this.direction1),e.Vector3.FromArrayToRef(t.direction2,0,this.direction2),e.Vector3.FromArrayToRef(t.minEmitBox,0,this.minEmitBox),e.Vector3.FromArrayToRef(t.maxEmitBox,0,this.maxEmitBox)},t})();e.BoxParticleEmitter=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i){void 0===e&&(e=1),void 0===t&&(t=Math.PI),void 0===i&&(i=0),this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}return Object.defineProperty(t.prototype,"radius",{get:function(){return this._radius},set:function(e){this._radius=e,this._buildHeight()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._buildHeight()},enumerable:!0,configurable:!0}),t.prototype._buildHeight=function(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1},t.prototype.startDirectionFunction=function(t,i,r){if(1===Math.abs(Math.cos(this._angle)))e.Vector3.TransformNormalFromFloatsToRef(0,1,0,t,i);else{var n=r.position.subtract(t.getTranslation()).normalize(),o=e.Scalar.RandomRange(0,this.directionRandomizer),s=e.Scalar.RandomRange(0,this.directionRandomizer),a=e.Scalar.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=s,n.z+=a,n.normalize(),e.Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,t,i)}},t.prototype.startPositionFunction=function(t,i,r){var n,o=e.Scalar.RandomRange(0,2*Math.PI);this.emitFromSpawnPointOnly?n=1e-4:(n=e.Scalar.RandomRange(0,this.heightRange),n=1-n*n);var s=this._radius-e.Scalar.RandomRange(0,this._radius*this.radiusRange);s*=n;var a=s*Math.sin(o),l=s*Math.cos(o),c=n*this._height;e.Vector3.TransformCoordinatesFromFloatsToRef(a,c,l,t,i)},t.prototype.clone=function(){var i=new t(this._radius,this._angle,this.directionRandomizer);return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)},t.prototype.getEffectDefines=function(){var e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e},t.prototype.getClassName=function(){return"ConeParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e},t.prototype.parse=function(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer},t})();e.ConeParticleEmitter=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return t.prototype.startDirectionFunction=function(t,i,r){var n=r.position.subtract(t.getTranslation()).normalize(),o=e.Scalar.RandomRange(0,this.directionRandomizer),s=e.Scalar.RandomRange(0,this.directionRandomizer),a=e.Scalar.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=s,n.z+=a,n.normalize(),e.Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,t,i)},t.prototype.startPositionFunction=function(t,i,r){var n=this.radius-e.Scalar.RandomRange(0,this.radius*this.radiusRange),o=e.Scalar.RandomRange(0,1),s=e.Scalar.RandomRange(0,2*Math.PI),a=Math.acos(2*o-1),l=n*Math.cos(s)*Math.sin(a),c=n*Math.cos(a),h=n*Math.sin(s)*Math.sin(a);e.Vector3.TransformCoordinatesFromFloatsToRef(l,c,h,t,i)},t.prototype.clone=function(){var i=new t(this.radius,this.directionRandomizer);return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},t.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER"},t.prototype.getClassName=function(){return"SphereParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},t.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},t})();e.SphereParticleEmitter=t;var i=(function(t){function i(i,r,n){void 0===i&&(i=1),void 0===r&&(r=new e.Vector3(0,1,0)),void 0===n&&(n=new e.Vector3(0,1,0));var o=t.call(this,i)||this;return o.direction1=r,o.direction2=n,o}return o(i,t),i.prototype.startDirectionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.direction1.x,this.direction2.x),o=e.Scalar.RandomRange(this.direction1.y,this.direction2.y),s=e.Scalar.RandomRange(this.direction1.z,this.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(n,o,s,t,i)},i.prototype.clone=function(){var t=new i(this.radius,this.direction1,this.direction2);return e.Tools.DeepCopy(this,t),t},i.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},i.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"},i.prototype.getClassName=function(){return"SphereDirectedParticleEmitter"},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e},i.prototype.parse=function(e){t.prototype.parse.call(this,e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)},i})(t);e.SphereDirectedParticleEmitter=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return t.prototype.startDirectionFunction=function(t,i,r){var n=r.position.subtract(t.getTranslation()).normalize(),o=e.Scalar.RandomRange(0,this.directionRandomizer),s=e.Scalar.RandomRange(0,this.directionRandomizer),a=e.Scalar.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=s,n.z+=a,n.normalize(),e.Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,t,i)},t.prototype.startPositionFunction=function(t,i,r){var n=this.radius-e.Scalar.RandomRange(0,this.radius*this.radiusRange),o=e.Scalar.RandomRange(0,1),s=e.Scalar.RandomRange(0,2*Math.PI),a=Math.acos(2*o-1),l=n*Math.cos(s)*Math.sin(a),c=n*Math.cos(a),h=n*Math.sin(s)*Math.sin(a);e.Vector3.TransformCoordinatesFromFloatsToRef(l,Math.abs(c),h,t,i)},t.prototype.clone=function(){var i=new t(this.radius,this.directionRandomizer);return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},t.prototype.getEffectDefines=function(){return"#define HEMISPHERICEMITTER"},t.prototype.getClassName=function(){return"HemisphericParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},t.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},t})();e.HemisphericParticleEmitter=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.direction1=new e.Vector3(0,1,0),this.direction2=new e.Vector3(0,1,0)}return t.prototype.startDirectionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.direction1.x,this.direction2.x),o=e.Scalar.RandomRange(this.direction1.y,this.direction2.y),s=e.Scalar.RandomRange(this.direction1.z,this.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(n,o,s,t,i)},t.prototype.startPositionFunction=function(t,i,r){e.Vector3.TransformCoordinatesFromFloatsToRef(0,0,0,t,i)},t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},t.prototype.getEffectDefines=function(){return"#define POINTEMITTER"},t.prototype.getClassName=function(){return"PointParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e},t.prototype.parse=function(t){e.Vector3.FromArrayToRef(t.direction1,0,this.direction1),e.Vector3.FromArrayToRef(t.direction2,0,this.direction2)},t})();e.PointParticleEmitter=t})(r||(r={}));var r;!(function(e){e.AbstractScene.AddParser(e.SceneComponentConstants.NAME_PARTICLESYSTEM,(function(t,i,r,n){var o=e.AbstractScene.GetIndividualParser(e.SceneComponentConstants.NAME_PARTICLESYSTEM);if(o&&void 0!==t.particleSystems&&null!==t.particleSystems)for(var s=0,a=t.particleSystems.length;s4&&(s.push(e.VertexBuffer.MatricesIndicesExtraKind),s.push(e.VertexBuffer.MatricesWeightsExtraKind)),o.push("#define NUM_BONE_INFLUENCERS "+t.numBoneInfluencers),o.push("#define BonesPerMesh "+(t.skeleton.bones.length+1)),a.addCPUSkinningFallback(0,t),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones")):o.push("#define NUM_BONE_INFLUENCERS 0");for(var c in this._textures)if(!this._textures[c].isReady())return!1;t&&this._shouldTurnAlphaTestOn(t)&&o.push("#define ALPHATEST");var h=this._effect,u=o.join("\n");return this._effect=n.createEffect(this._shaderPath,{attributes:s,uniformsNames:this._options.uniforms,uniformBuffersNames:this._options.uniformBuffers,samplers:this._options.samplers,defines:u,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError},n),!!this._effect.isReady()&&(h!==this._effect&&r.resetCachedMaterial(),this._renderId=r.getRenderId(),!0)},i.prototype.bindOnlyWorldMatrix=function(e){var t=this.getScene();this._effect&&(-1!==this._options.uniforms.indexOf("world")&&this._effect.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),this._effect.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&this._effect.setMatrix("worldViewProjection",e.multiply(t.getTransformMatrix())))},i.prototype.bind=function(t,i){if(this.bindOnlyWorldMatrix(t),this._effect&&this.getScene().getCachedMaterial()!==this){-1!==this._options.uniforms.indexOf("view")&&this._effect.setMatrix("view",this.getScene().getViewMatrix()),-1!==this._options.uniforms.indexOf("projection")&&this._effect.setMatrix("projection",this.getScene().getProjectionMatrix()),-1!==this._options.uniforms.indexOf("viewProjection")&&this._effect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.MaterialHelper.BindBonesParameters(i,this._effect);var r;for(r in this._textures)this._effect.setTexture(r,this._textures[r]);for(r in this._textureArrays)this._effect.setTextureArray(r,this._textureArrays[r]);for(r in this._ints)this._effect.setInt(r,this._ints[r]);for(r in this._floats)this._effect.setFloat(r,this._floats[r]);for(r in this._floatsArrays)this._effect.setArray(r,this._floatsArrays[r]);for(r in this._colors3)this._effect.setColor3(r,this._colors3[r]);for(r in this._colors3Arrays)this._effect.setArray3(r,this._colors3Arrays[r]);for(r in this._colors4){var n=this._colors4[r];this._effect.setFloat4(r,n.r,n.g,n.b,n.a)}for(r in this._vectors2)this._effect.setVector2(r,this._vectors2[r]);for(r in this._vectors3)this._effect.setVector3(r,this._vectors3[r]);for(r in this._vectors4)this._effect.setVector4(r,this._vectors4[r]);for(r in this._matrices)this._effect.setMatrix(r,this._matrices[r]);for(r in this._matrices3x3)this._effect.setMatrix3x3(r,this._matrices3x3[r]);for(r in this._matrices2x2)this._effect.setMatrix2x2(r,this._matrices2x2[r]);for(r in this._vectors2Arrays)this._effect.setArray2(r,this._vectors2Arrays[r]);for(r in this._vectors3Arrays)this._effect.setArray3(r,this._vectors3Arrays[r])}this._afterBind(i)},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);for(var i in this._textures)e.push(this._textures[i]);for(var i in this._textureArrays)for(var r=this._textureArrays[i],n=0;nthis._maxX||ithis._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var s=this._getFacetAt(t,i),a=-(s.x*t+s.z*i+s.w)/s.y;return e.Vector3.TransformCoordinatesFromFloatsToRef(0,a,0,r,o),o.y},i.prototype.getNormalAtCoordinates=function(t,i){var r=new e.Vector3(0,1,0);return this.getNormalAtCoordinatesToRef(t,i,r),r},i.prototype.getNormalAtCoordinatesToRef=function(t,i,r){var n=this.getWorldMatrix(),o=e.Tmp.Matrix[5];n.invertToRef(o);var s=e.Tmp.Vector3[8];if(e.Vector3.TransformCoordinatesFromFloatsToRef(t,0,i,o,s),t=s.x,i=s.z,tthis._maxX||ithis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var a=this._getFacetAt(t,i);return e.Vector3.TransformNormalFromFloatsToRef(a.x,a.y,a.z,n,r),this},i.prototype.updateCoordinateHeights=function(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this},i.prototype._getFacetAt=function(e,t){var i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),n=this._heightQuads[r*this._subdivisionsX+i];return t=0;s--){var a=t[s],l=a.getParent();if(l){var c=this._debugLines[n];c||(c=[e.Vector3.Zero(),e.Vector3.Zero()],this._debugLines[n]=c),a.getAbsolutePositionToRef(this.mesh,c[0]),l.getAbsolutePositionToRef(this.mesh,c[1]),c[0].subtractInPlace(o),c[1].subtractInPlace(o),n++}}},t.prototype.update=function(){this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteTransforms(),void 0===this.skeleton.bones[0].length?this._getLinesForBonesNoLength(this.skeleton.bones,this.mesh.getWorldMatrix()):this._getLinesForBonesWithLength(this.skeleton.bones,this.mesh.getWorldMatrix()),this._debugMesh?e.MeshBuilder.CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:this._debugMesh},this._scene):(this._debugMesh=e.MeshBuilder.CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:null},this._scene),this._debugMesh.renderingGroupId=this.renderingGroupId),this._debugMesh.position.copyFrom(this.mesh.position),this._debugMesh.color=this.color},t.prototype.dispose=function(){this._debugMesh&&(this.isEnabled=!1,this._debugMesh.dispose(),this._debugMesh=null)},t})();t.SkeletonViewer=i})(e.Debug||(e.Debug={}))})(r||(r={}));var r;!(function(e){!(function(t){var i=(function(){function t(t,i){void 0===i&&(i=1),this._xline=[e.Vector3.Zero(),e.Vector3.Zero()],this._yline=[e.Vector3.Zero(),e.Vector3.Zero()],this._zline=[e.Vector3.Zero(),e.Vector3.Zero()],this.scaleLines=1,this.scaleLines=i,this._xmesh=e.Mesh.CreateLines("xline",this._xline,t,!0),this._ymesh=e.Mesh.CreateLines("yline",this._yline,t,!0),this._zmesh=e.Mesh.CreateLines("zline",this._zline,t,!0),this._xmesh.renderingGroupId=2,this._ymesh.renderingGroupId=2,this._zmesh.renderingGroupId=2,this._xmesh.material.checkReadyOnlyOnce=!0,this._xmesh.color=new e.Color3(1,0,0),this._ymesh.material.checkReadyOnlyOnce=!0,this._ymesh.color=new e.Color3(0,1,0),this._zmesh.material.checkReadyOnlyOnce=!0,this._zmesh.color=new e.Color3(0,0,1),this.scene=t}return t.prototype.update=function(t,i,r,n){var o=this.scaleLines;this._xmesh&&this._xmesh.position.copyFrom(t),this._ymesh&&this._ymesh.position.copyFrom(t),this._zmesh&&this._zmesh.position.copyFrom(t);var s=this._xline[1];s.x=i.x*o,s.y=i.y*o,s.z=i.z*o,e.Mesh.CreateLines("",this._xline,null,!1,this._xmesh),s=this._yline[1],s.x=r.x*o,s.y=r.y*o,s.z=r.z*o,e.Mesh.CreateLines("",this._yline,null,!1,this._ymesh),s=this._zline[1],s.x=n.x*o,s.y=n.y*o,s.z=n.z*o,e.Mesh.CreateLines("",this._zline,null,!1,this._zmesh)},t.prototype.dispose=function(){this._xmesh&&this._xmesh.dispose(),this._ymesh&&this._ymesh.dispose(),this._zmesh&&this._zmesh.dispose(),this._xmesh=null,this._ymesh=null,this._zmesh=null,this.scene=null},t})();t.AxesViewer=i})(e.Debug||(e.Debug={}))})(r||(r={}));var r;!(function(e){!(function(t){var i=(function(t){function i(i,r,n,o){void 0===o&&(o=1);var s=t.call(this,i,o)||this;return s.pos=e.Vector3.Zero(),s.xaxis=e.Vector3.Zero(),s.yaxis=e.Vector3.Zero(),s.zaxis=e.Vector3.Zero(),s.mesh=n,s.bone=r,s}return o(i,t),i.prototype.update=function(){if(this.mesh&&this.bone){var i=this.bone;i.getAbsolutePositionToRef(this.mesh,this.pos),i.getDirectionToRef(e.Axis.X,this.mesh,this.xaxis),i.getDirectionToRef(e.Axis.Y,this.mesh,this.yaxis),i.getDirectionToRef(e.Axis.Z,this.mesh,this.zaxis),t.prototype.update.call(this,this.pos,this.xaxis,this.yaxis,this.zaxis)}},i.prototype.dispose=function(){this.mesh&&(this.mesh=null,this.bone=null,t.prototype.dispose.call(this))},i})(t.AxesViewer);t.BoneAxesViewer=i})(e.Debug||(e.Debug={}))})(r||(r={}));var r;!(function(e){var t=(function(){function t(e){this.ray=e}return t.CreateAndShow=function(e,i,r){var n=new t(e);return n.show(i,r),n},t.prototype.show=function(t,i){if(!this._renderFunction&&this.ray){var r=this.ray;this._renderFunction=this._render.bind(this),this._scene=t,this._renderPoints=[r.origin,r.origin.add(r.direction.scale(r.length))],this._renderLine=e.Mesh.CreateLines("ray",this._renderPoints,t,!0),this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}i&&this._renderLine&&this._renderLine.color.copyFrom(i)},t.prototype.hide=function(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])},t.prototype._render=function(){var t=this.ray;if(t){var i=this._renderPoints[1],r=Math.min(t.length,1e6);i.copyFrom(t.direction),i.scaleInPlace(r),i.addInPlace(t.origin),e.Mesh.CreateLines("ray",this._renderPoints,this._scene,!0,this._renderLine)}},t.prototype.attachToMesh=function(t,i,r,n){this._attachedToMesh=t;var o=this.ray;o&&(o.direction||(o.direction=e.Vector3.Zero()),o.origin||(o.origin=e.Vector3.Zero()),n&&(o.length=n),r||(r=e.Vector3.Zero()),i||(i=new e.Vector3(0,0,-1)),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(i),this._meshSpaceOrigin.copyFrom(r)):(this._meshSpaceDirection=i.clone(),this._meshSpaceOrigin=r.clone()),this._updateToMeshFunction||(this._updateToMeshFunction=this._updateToMesh.bind(this),this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction)),this._updateToMesh())},t.prototype.detachFromMesh=function(){this._attachedToMesh&&(this._updateToMeshFunction&&this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction),this._attachedToMesh=null,this._updateToMeshFunction=null)},t.prototype._updateToMesh=function(){var t=this.ray;if(this._attachedToMesh&&t){if(this._attachedToMesh._isDisposed)return void this.detachFromMesh();this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,t.direction),e.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),t.origin)}},t.prototype.dispose=function(){this.hide(),this.detachFromMesh(),this.ray=null},t})();e.RayHelper=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){this.BJSINSPECTOR="undefined"!=typeof INSPECTOR?INSPECTOR:void 0,this.onPropertyChangedObservable=new e.Observable,this._scene=t}return t.prototype._createInspector=function(e){void 0===e&&(e={});var t=e.popup||!1,i=e.initialTab||0,r=e.parentElement||null;this._inspector||(this.BJSINSPECTOR=this.BJSINSPECTOR||"undefined"!=typeof INSPECTOR?INSPECTOR:void 0,this._inspector=new this.BJSINSPECTOR.Inspector(this._scene,t,i,r,e.newColors))},t.prototype.isVisible=function(){return!!this._inspector},t.prototype.hide=function(){if(this._inspector){try{this._inspector.dispose()}catch(e){}this.onPropertyChangedObservable.clear(),this._inspector=null}},t.prototype.show=function(i){void 0===i&&(i={}),void 0===this.BJSINSPECTOR?e.Tools.LoadScript(t.InspectorURL,this._createInspector.bind(this,i)):this._createInspector(i)},t.prototype.getActiveTab=function(){return this._inspector?this._inspector.getActiveTabIndex():-1},t.InspectorURL="https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js",t})();e.DebugLayer=t})(r||(r={}));var r;!(function(e){!(function(t){var i=(function(){function t(t){this._impostors=[],this._meshes=[],this._numMeshes=0,this._scene=t||e.Engine.LastCreatedScene;var i=this._scene.getPhysicsEngine();i&&(this._physicsEnginePlugin=i.getPhysicsPlugin())}return t.prototype._updateDebugMeshes=function(){for(var e=this._physicsEnginePlugin,t=0;t0?(this._meshes[i]=this._meshes[this._numMeshes],this._impostors[i]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}},t.prototype._getDebugMaterial=function(t){return this._debugMaterial||(this._debugMaterial=new e.StandardMaterial("",t),this._debugMaterial.wireframe=!0),this._debugMaterial},t.prototype._getDebugBoxMesh=function(t){return this._debugBoxMesh||(this._debugBoxMesh=e.MeshBuilder.CreateBox("physicsBodyBoxViewMesh",{size:1},t),this._debugBoxMesh.renderingGroupId=1,this._debugBoxMesh.rotationQuaternion=e.Quaternion.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(t),t.removeMesh(this._debugBoxMesh)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")},t.prototype._getDebugSphereMesh=function(t){return this._debugSphereMesh||(this._debugSphereMesh=e.MeshBuilder.CreateSphere("physicsBodySphereViewMesh",{diameter:1},t),this._debugSphereMesh.renderingGroupId=1,this._debugSphereMesh.rotationQuaternion=e.Quaternion.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(t),t.removeMesh(this._debugSphereMesh)),this._debugSphereMesh.createInstance("physicsBodyBoxViewInstance")},t.prototype._getDebugMesh=function(t,i){var r=null;if(t.type==e.PhysicsImpostor.BoxImpostor)r=this._getDebugBoxMesh(i),t.getBoxSizeToRef(r.scaling);else if(t.type==e.PhysicsImpostor.SphereImpostor){r=this._getDebugSphereMesh(i);var n=t.getRadius();r.scaling.x=2*n,r.scaling.y=2*n,r.scaling.z=2*n}return r},t.prototype.dispose=function(){for(var e=0;e1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction1",{get:function(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction2",{get:function(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minEmitBox",{get:function(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxEmitBox",{get:function(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)},enumerable:!0,configurable:!0}),t.prototype.getCapacity=function(){return this._capacity},Object.defineProperty(t.prototype,"activeParticleCount",{get:function(){return this._activeCount},set:function(e){this._activeCount=Math.min(e,this._capacity)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isAnimationSheetEnabled",{get:function(){return this._isAnimationSheetEnabled},enumerable:!0,configurable:!0}),t.prototype.isReady=function(){return this._updateEffect?!!(this.emitter&&this._updateEffect.isReady()&&this._renderEffect.isReady()&&this.particleTexture&&this.particleTexture.isReady()):(this._recreateUpdateEffect(),this._recreateRenderEffect(),!1)},t.prototype.isStarted=function(){return this._started},t.prototype.start=function(e){var t=this;if(void 0===e&&(e=0),e)return void setTimeout((function(){t.start(0)}),e);this._started=!0,this._stopped=!1,this._preWarmDone=!1},t.prototype.stop=function(){this._stopped=!0},t.prototype.reset=function(){this._releaseBuffers(),this._releaseVAOs(),this._currentActiveCount=0,this._targetIndex=0},t.prototype.getClassName=function(){return"GPUParticleSystem"},Object.defineProperty(t.prototype,"isBillboardBased",{get:function(){return this._isBillboardBased},set:function(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._releaseBuffers())},enumerable:!0,configurable:!0}),t.prototype.getColorGradients=function(){return this._colorGradients},t.prototype.getSizeGradients=function(){return this._sizeGradients},t.prototype.getAngularSpeedGradients=function(){return this._angularSpeedGradients},t.prototype.getVelocityGradients=function(){return this._velocityGradients},t.prototype._removeGradient=function(e,t,i){if(!t)return this;for(var r=0,n=0,o=t;nt.gradient?1:0})),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeColorGradient=function(e){return this._removeGradient(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this},t.prototype._addFactorGradient=function(t,i,r){var n=new e.FactorGradient;n.gradient=i,n.factor1=r,t.push(n),t.sort((function(e,t){return e.gradientt.gradient?1:0})),this._releaseBuffers()},t.prototype.addSizeGradient=function(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeSizeGradient=function(e){return this._removeGradient(e,this._sizeGradients,this._sizeGradientsTexture), -this._sizeGradientsTexture=null,this},t.prototype.addAngularSpeedGradient=function(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeAngularSpeedGradient=function(e){return this._removeGradient(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this},t.prototype.addVelocityGradient=function(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeVelocityGradient=function(e){return this._removeGradient(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this},t.prototype._createUpdateVAO=function(e){var t={};t.position=e.createVertexBuffer("position",0,3),t.age=e.createVertexBuffer("age",3,1),t.life=e.createVertexBuffer("life",4,1),t.seed=e.createVertexBuffer("seed",5,4),t.size=e.createVertexBuffer("size",9,3);var i=12;this._colorGradientsTexture||(t.color=e.createVertexBuffer("color",i,4),i+=4),t.direction=e.createVertexBuffer("direction",i,3),i+=3,this._isBillboardBased||(t.initialDirection=e.createVertexBuffer("initialDirection",i,3),i+=3),this._angularSpeedGradientsTexture?(t.angle=e.createVertexBuffer("angle",i,1),i+=1):(t.angle=e.createVertexBuffer("angle",i,2),i+=2),this._isAnimationSheetEnabled&&(t.cellIndex=e.createVertexBuffer("cellIndex",i,1),i+=1);var r=this._engine.recordVertexArrayObject(t,null,this._updateEffect);return this._engine.bindArrayBuffer(null),r},t.prototype._createRenderVAO=function(e,t){var i={};i.position=e.createVertexBuffer("position",0,3,this._attributesStrideSize,!0),i.age=e.createVertexBuffer("age",3,1,this._attributesStrideSize,!0),i.life=e.createVertexBuffer("life",4,1,this._attributesStrideSize,!0),i.size=e.createVertexBuffer("size",9,3,this._attributesStrideSize,!0);var r=12;this._colorGradientsTexture||(i.color=e.createVertexBuffer("color",r,4,this._attributesStrideSize,!0),r+=4),r+=3,this._isBillboardBased||(i.initialDirection=e.createVertexBuffer("initialDirection",r,3,this._attributesStrideSize,!0),r+=3),i.angle=e.createVertexBuffer("angle",r,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?r++:r+=2,this._isAnimationSheetEnabled&&(i.cellIndex=e.createVertexBuffer("cellIndex",r,1,this._attributesStrideSize,!0),r+=1),i.offset=t.createVertexBuffer("offset",0,2),i.uv=t.createVertexBuffer("uv",2,2);var n=this._engine.recordVertexArrayObject(i,null,this._renderEffect);return this._engine.bindArrayBuffer(null),n},t.prototype._initialize=function(t){if(void 0===t&&(t=!1),!this._buffer0||t){var i=this._scene.getEngine(),r=new Array;this.isBillboardBased||(this._attributesStrideSize+=3),this._colorGradientsTexture&&(this._attributesStrideSize-=4),this._angularSpeedGradientsTexture&&(this._attributesStrideSize-=1),this._isAnimationSheetEnabled&&(this._attributesStrideSize+=1);for(var n=0;n=this.targetStopDuration&&this.stop()},t.prototype._createFactorGradientTexture=function(t,i){var r=this[i];if(t&&t.length&&!r){for(var n=new Float32Array(this._rawTextureWidth),o=0;o1){var r=0|this._accumulatedCount;this._accumulatedCount-=r,this._currentActiveCount=Math.min(this._activeCount,this._currentActiveCount+r)}if(!this._currentActiveCount)return 0;this._engine.enableEffect(this._updateEffect),this._engine.setState(!1),this._updateEffect.setFloat("currentCount",this._currentActiveCount),this._updateEffect.setFloat("timeDelta",this._timeDelta),this._updateEffect.setFloat("stopFactor",this._stopped?0:1),this._updateEffect.setTexture("randomSampler",this._randomTexture),this._updateEffect.setTexture("randomSampler2",this._randomTexture2),this._updateEffect.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateEffect.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateEffect.setDirectColor4("color1",this.color1),this._updateEffect.setDirectColor4("color2",this.color2)),this._updateEffect.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateEffect.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateEffect.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateEffect.setVector3("gravity",this.gravity),this._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._sizeGradientsTexture),this._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._angularSpeedGradientsTexture),this._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._velocityGradientsTexture),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateEffect),this._isAnimationSheetEnabled&&this._updateEffect.setFloat3("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed),this.noiseTexture&&(this._updateEffect.setTexture("noiseSampler",this.noiseTexture),this._updateEffect.setVector3("noiseStrength",this.noiseStrength));var n;if(this.emitter.position){n=this.emitter.getWorldMatrix()}else{var o=this.emitter;n=e.Matrix.Translation(o.x,o.y,o.z)}if(this._updateEffect.setMatrix("emitterWM",n),this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex],null),this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer()),this._engine.setRasterizerState(!1),this._engine.beginTransformFeedback(!0),this._engine.drawArraysType(e.Material.PointListDrawMode,0,this._currentActiveCount),this._engine.endTransformFeedback(),this._engine.setRasterizerState(!0),this._engine.bindTransformFeedbackBuffer(null),!t){this._engine.enableEffect(this._renderEffect);var s=this._scene.getViewMatrix();if(this._renderEffect.setMatrix("view",s),this._renderEffect.setMatrix("projection",this._scene.getProjectionMatrix()),this._renderEffect.setTexture("textureSampler",this.particleTexture),this._renderEffect.setVector2("translationPivot",this.translationPivot),this._colorGradientsTexture?this._renderEffect.setTexture("colorGradientSampler",this._colorGradientsTexture):this._renderEffect.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){var a=this.particleTexture.getBaseSize();this._renderEffect.setFloat3("sheetInfos",this.spriteCellWidth/a.width,this.spriteCellHeight/a.height,a.width/this.spriteCellWidth)}if(this._isBillboardBased){var l=this._scene.activeCamera;this._renderEffect.setVector3("eyePosition",l.globalPosition)}if(this._scene.clipPlane){var c=this._scene.clipPlane,h=s.clone();h.invert(),this._renderEffect.setMatrix("invView",h),this._renderEffect.setFloat4("vClipPlane",c.normal.x,c.normal.y,c.normal.z,c.d)}switch(this.blendMode){case e.ParticleSystem.BLENDMODE_ADD:this._engine.setAlphaMode(e.Engine.ALPHA_ADD);break;case e.ParticleSystem.BLENDMODE_ONEONE:this._engine.setAlphaMode(e.Engine.ALPHA_ONEONE);break;case e.ParticleSystem.BLENDMODE_STANDARD:this._engine.setAlphaMode(e.Engine.ALPHA_COMBINE)}this.forceDepthWrite&&this._engine.setDepthWrite(!0),this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex],null),this._engine.drawArraysType(e.Material.TriangleFanDrawMode,0,4,this._currentActiveCount),this._engine.setAlphaMode(e.Engine.ALPHA_DISABLE)}2===++this._targetIndex&&(this._targetIndex=0);var u=this._sourceBuffer;return this._sourceBuffer=this._targetBuffer,this._targetBuffer=u,this._currentActiveCount},t.prototype.rebuild=function(){this._initialize(!0)},t.prototype._releaseBuffers=function(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null)},t.prototype._releaseVAOs=function(){if(this._updateVAO){for(var e=0;e-1&&this._scene.particleSystems.splice(t,1),this._releaseBuffers(),this._releaseVAOs(),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._randomTexture&&(this._randomTexture.dispose(),this._randomTexture=null),this._randomTexture2&&(this._randomTexture2.dispose(),this._randomTexture2=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.prototype.clone=function(i,r){var n=new t(i,{capacity:this._capacity,randomTextureSize:this._randomTextureSize},this._scene);return e.Tools.DeepCopy(this,n),void 0===r&&(r=this.emitter),n.emitter=r,this.particleTexture&&(n.particleTexture=new e.Texture(this.particleTexture.url,this._scene)),n},t.prototype.serialize=function(){var t={};return e.ParticleSystem._Serialize(t,this),t.activeParticleCount=this.activeParticleCount,t},t.Parse=function(i,r,n){var o=i.name,s=new t(o,{capacity:i.capacity,randomTextureSize:i.randomTextureSize},r);return i.activeParticleCount&&(s.activeParticleCount=i.activeParticleCount),e.ParticleSystem._Parse(i,s,r,n),s},t})();e.GPUParticleSystem=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a,l){void 0===l&&(l=null),this.idx=0,this.color=new e.Color4(1,1,1,1),this.position=e.Vector3.Zero(),this.rotation=e.Vector3.Zero(),this.scaling=e.Vector3.One(),this.uvs=new e.Vector4(0,0,1,1),this.velocity=e.Vector3.Zero(),this.pivot=e.Vector3.Zero(),this.translateFromPivot=!1,this.alive=!0,this.isVisible=!0,this._pos=0,this._ind=0,this.shapeId=0,this.idxInShape=0,this._stillInvisible=!1,this._rotationMatrix=[1,0,0,0,1,0,0,0,1],this.parentId=null,this._globalPosition=e.Vector3.Zero(),this.idx=t,this._pos=i,this._ind=r,this._model=n,this.shapeId=o,this.idxInShape=s,this._sps=a,l&&(this._modelBoundingInfo=l,this._boundingInfo=new e.BoundingInfo(l.minimum,l.maximum))}return Object.defineProperty(t.prototype,"scale",{get:function(){return this.scaling},set:function(e){this.scaling=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"quaternion",{get:function(){return this.rotationQuaternion},set:function(e){this.rotationQuaternion=e},enumerable:!0,configurable:!0}),t.prototype.intersectsMesh=function(t){return!(!this._boundingInfo||!t._boundingInfo)&&(this._sps._bSphereOnly?e.BoundingSphere.Intersects(this._boundingInfo.boundingSphere,t._boundingInfo.boundingSphere):this._boundingInfo.intersects(t._boundingInfo,!1))},t})();e.SolidParticle=t;var i=(function(){function e(e,t,i,r,n,o){this._indicesLength=0,this.shapeID=e,this._shape=t,this._indicesLength=i,this._shapeUV=r,this._positionFunction=n,this._vertexFunction=o}return e})();e.ModelShape=i;var r=(function(){function e(){this.ind=0,this.indicesLength=0,this.sqDistance=0}return e})();e.DepthSortedParticle=r})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){this.particles=new Array,this.nbParticles=0,this.billboard=!1,this.recomputeNormals=!0,this.counter=0,this.vars={},this._bSphereOnly=!1,this._bSphereRadiusFactor=1,this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._index=0,this._updatable=!0,this._pickable=!1,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._depthSort=!1,this._shapeCounter=0,this._copy=new e.SolidParticle(0,0,0,null,0,0,this),this._color=new e.Color4(0,0,0,0),this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeParticleVertex=!1,this._computeBoundingBox=!1,this._depthSortParticles=!0,this._cam_axisZ=e.Vector3.Zero(),this._cam_axisY=e.Vector3.Zero(),this._cam_axisX=e.Vector3.Zero(),this._axisZ=e.Axis.Z,this._camDir=e.Vector3.Zero(),this._camInvertedPosition=e.Vector3.Zero(),this._rotMatrix=new e.Matrix,this._invertMatrix=new e.Matrix,this._rotated=e.Vector3.Zero(),this._quaternion=new e.Quaternion,this._vertex=e.Vector3.Zero(),this._normal=e.Vector3.Zero(),this._yaw=0,this._pitch=0,this._roll=0,this._halfroll=0,this._halfpitch=0,this._halfyaw=0,this._sinRoll=0,this._cosRoll=0,this._sinPitch=0,this._cosPitch=0,this._sinYaw=0,this._cosYaw=0,this._mustUnrotateFixedNormals=!1,this._minimum=e.Vector3.Zero(),this._maximum=e.Vector3.Zero(),this._minBbox=e.Vector3.Zero(),this._maxBbox=e.Vector3.Zero(),this._particlesIntersect=!1,this._depthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},this._needs32Bits=!1,this._pivotBackTranslation=e.Vector3.Zero(),this._scaledPivot=e.Vector3.Zero(),this._particleHasParent=!1,this.name=t,this._scene=i||e.Engine.LastCreatedScene,this._camera=i.activeCamera,this._pickable=!!r&&r.isPickable,this._depthSort=!!r&&r.enableDepthSort,this._particlesIntersect=!!r&&r.particleIntersection,this._bSphereOnly=!!r&&r.boundingSphereOnly,this._bSphereRadiusFactor=r&&r.bSphereRadiusFactor?r.bSphereRadiusFactor:1,r&&void 0!==r.updatable?this._updatable=r.updatable:this._updatable=!0,this._pickable&&(this.pickedParticles=[]),this._depthSort&&(this.depthSortedParticles=[])}return t.prototype.buildMesh=function(){if(0===this.nbParticles){var t=e.MeshBuilder.CreateDisc("",{radius:1,tessellation:3},this._scene);this.addShape(t,1),t.dispose()}this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),this.recomputeNormals&&e.VertexData.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();var i=new e.VertexData;i.indices=this._depthSort?this._indices:this._indices32,i.set(this._positions32,e.VertexBuffer.PositionKind),i.set(this._normals32,e.VertexBuffer.NormalKind),this._uvs32.length>0&&i.set(this._uvs32,e.VertexBuffer.UVKind),this._colors32.length>0&&i.set(this._colors32,e.VertexBuffer.ColorKind);var r=new e.Mesh(this.name,this._scene);return i.applyToMesh(r,this._updatable),this.mesh=r,this.mesh.isPickable=this._pickable,this._depthSort||(this._indices=null),this._positions=null,this._normals=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0),r},t.prototype.digest=function(t,i){var r=i&&i.facetNb||1,n=i&&i.number||0,o=i&&i.delta||0,s=t.getVerticesData(e.VertexBuffer.PositionKind),a=t.getIndices(),l=t.getVerticesData(e.VertexBuffer.UVKind),c=t.getVerticesData(e.VertexBuffer.ColorKind),h=t.getVerticesData(e.VertexBuffer.NormalKind),u=0,d=a.length/3;n?(n=n>d?d:n,r=Math.round(d/n),o=0):r=r>d?d:r;for(var f=[],p=[],_=[],m=[],g=e.Vector3.Zero(),v=r;ud-r&&(r=d-u),f.length=0,p.length=0,_.length=0,m.length=0;for(var y=0,b=3*u;b<3*(u+r);b++){p.push(y);var x=a[b];f.push(s[3*x],s[3*x+1],s[3*x+2]),l&&_.push(l[2*x],l[2*x+1]),c&&m.push(c[4*x],c[4*x+1],c[4*x+2],c[4*x+3]),y++}var T,E=this.nbParticles,P=this._posToShape(f),A=this._uvsToShapeUV(_);for(T=0;T65535&&(this._needs32Bits=!0)}if(this._pickable){var b=n.length/3;for(_=0;_=this.nbParticles?this.nbParticles-1:i,this._computeBoundingBox&&(0==t&&i==this.nbParticles-1?(e.Vector3.FromFloatsToRef(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,this._minimum),e.Vector3.FromFloatsToRef(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE,this._maximum)):this.mesh._boundingInfo&&(this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum),this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum))),s=this.particles[t]._pos;var d=s/3|0;l=4*d,h=2*d;for(var f=t;f<=i;f++){if(this._particle=this.particles[f],this._shape=this._particle._model._shape,this._shapeUV=this._particle._model._shapeUV,this.updateParticle(this._particle),this._depthSort&&this._depthSortParticles){var p=this.depthSortedParticles[f];p.ind=this._particle._ind,p.indicesLength=this._particle._model._indicesLength,p.sqDistance=e.Vector3.DistanceSquared(this._particle.position,this._camInvertedPosition)}if(!this._particle.alive||this._particle._stillInvisible&&!this._particle.isVisible)u=this._shape.length,s+=3*u,l+=4*u,h+=2*u;else{if(this._particle.isVisible)for(this._particle._stillInvisible=!1,this._particleHasParent=null!==this._particle.parentId,this._scaledPivot.x=this._particle.pivot.x*this._particle.scaling.x,this._scaledPivot.y=this._particle.pivot.y*this._particle.scaling.y,this._scaledPivot.z=this._particle.pivot.z*this._particle.scaling.z,this.billboard&&(this._particle.rotation.x=0,this._particle.rotation.y=0),(this._computeParticleRotation||this.billboard)&&(this._particle.rotationQuaternion?this._quaternion.copyFrom(this._particle.rotationQuaternion):(this._yaw=this._particle.rotation.y,this._pitch=this._particle.rotation.x,this._roll=this._particle.rotation.z,this._quaternionRotationYPR()),this._quaternionToRotationMatrix()),this._particleHasParent?(this._parent=this.particles[this._particle.parentId], -this._rotated.x=this._particle.position.x*this._parent._rotationMatrix[0]+this._particle.position.y*this._parent._rotationMatrix[3]+this._particle.position.z*this._parent._rotationMatrix[6],this._rotated.y=this._particle.position.x*this._parent._rotationMatrix[1]+this._particle.position.y*this._parent._rotationMatrix[4]+this._particle.position.z*this._parent._rotationMatrix[7],this._rotated.z=this._particle.position.x*this._parent._rotationMatrix[2]+this._particle.position.y*this._parent._rotationMatrix[5]+this._particle.position.z*this._parent._rotationMatrix[8],this._particle._globalPosition.x=this._parent._globalPosition.x+this._rotated.x,this._particle._globalPosition.y=this._parent._globalPosition.y+this._rotated.y,this._particle._globalPosition.z=this._parent._globalPosition.z+this._rotated.z,(this._computeParticleRotation||this.billboard)&&(this._particle._rotationMatrix[0]=this._rotMatrix.m[0]*this._parent._rotationMatrix[0]+this._rotMatrix.m[1]*this._parent._rotationMatrix[3]+this._rotMatrix.m[2]*this._parent._rotationMatrix[6],this._particle._rotationMatrix[1]=this._rotMatrix.m[0]*this._parent._rotationMatrix[1]+this._rotMatrix.m[1]*this._parent._rotationMatrix[4]+this._rotMatrix.m[2]*this._parent._rotationMatrix[7],this._particle._rotationMatrix[2]=this._rotMatrix.m[0]*this._parent._rotationMatrix[2]+this._rotMatrix.m[1]*this._parent._rotationMatrix[5]+this._rotMatrix.m[2]*this._parent._rotationMatrix[8],this._particle._rotationMatrix[3]=this._rotMatrix.m[4]*this._parent._rotationMatrix[0]+this._rotMatrix.m[5]*this._parent._rotationMatrix[3]+this._rotMatrix.m[6]*this._parent._rotationMatrix[6],this._particle._rotationMatrix[4]=this._rotMatrix.m[4]*this._parent._rotationMatrix[1]+this._rotMatrix.m[5]*this._parent._rotationMatrix[4]+this._rotMatrix.m[6]*this._parent._rotationMatrix[7],this._particle._rotationMatrix[5]=this._rotMatrix.m[4]*this._parent._rotationMatrix[2]+this._rotMatrix.m[5]*this._parent._rotationMatrix[5]+this._rotMatrix.m[6]*this._parent._rotationMatrix[8],this._particle._rotationMatrix[6]=this._rotMatrix.m[8]*this._parent._rotationMatrix[0]+this._rotMatrix.m[9]*this._parent._rotationMatrix[3]+this._rotMatrix.m[10]*this._parent._rotationMatrix[6],this._particle._rotationMatrix[7]=this._rotMatrix.m[8]*this._parent._rotationMatrix[1]+this._rotMatrix.m[9]*this._parent._rotationMatrix[4]+this._rotMatrix.m[10]*this._parent._rotationMatrix[7],this._particle._rotationMatrix[8]=this._rotMatrix.m[8]*this._parent._rotationMatrix[2]+this._rotMatrix.m[9]*this._parent._rotationMatrix[5]+this._rotMatrix.m[10]*this._parent._rotationMatrix[8])):(this._particle._globalPosition.x=this._particle.position.x,this._particle._globalPosition.y=this._particle.position.y,this._particle._globalPosition.z=this._particle.position.z,(this._computeParticleRotation||this.billboard)&&(this._particle._rotationMatrix[0]=this._rotMatrix.m[0],this._particle._rotationMatrix[1]=this._rotMatrix.m[1],this._particle._rotationMatrix[2]=this._rotMatrix.m[2],this._particle._rotationMatrix[3]=this._rotMatrix.m[4],this._particle._rotationMatrix[4]=this._rotMatrix.m[5],this._particle._rotationMatrix[5]=this._rotMatrix.m[6],this._particle._rotationMatrix[6]=this._rotMatrix.m[8],this._particle._rotationMatrix[7]=this._rotMatrix.m[9],this._particle._rotationMatrix[8]=this._rotMatrix.m[10])),this._particle.translateFromPivot?(this._pivotBackTranslation.x=0,this._pivotBackTranslation.y=0,this._pivotBackTranslation.z=0):(this._pivotBackTranslation.x=this._scaledPivot.x,this._pivotBackTranslation.y=this._scaledPivot.y,this._pivotBackTranslation.z=this._scaledPivot.z),u=0;uthis._maximum.x&&(this._maximum.x=this._positions32[o]),this._positions32[o+1]this._maximum.y&&(this._maximum.y=this._positions32[o+1]),this._positions32[o+2]this._maximum.z&&(this._maximum.z=this._positions32[o+2])),this._computeParticleVertex||(this._normal.x=this._fixedNormal32[o],this._normal.y=this._fixedNormal32[o+1],this._normal.z=this._fixedNormal32[o+2],this._rotated.x=this._normal.x*this._particle._rotationMatrix[0]+this._normal.y*this._particle._rotationMatrix[3]+this._normal.z*this._particle._rotationMatrix[6],this._rotated.y=this._normal.x*this._particle._rotationMatrix[1]+this._normal.y*this._particle._rotationMatrix[4]+this._normal.z*this._particle._rotationMatrix[7],this._rotated.z=this._normal.x*this._particle._rotationMatrix[2]+this._normal.y*this._particle._rotationMatrix[5]+this._normal.z*this._particle._rotationMatrix[8],this._normals32[o]=this._cam_axisX.x*this._rotated.x+this._cam_axisY.x*this._rotated.y+this._cam_axisZ.x*this._rotated.z,this._normals32[o+1]=this._cam_axisX.y*this._rotated.x+this._cam_axisY.y*this._rotated.y+this._cam_axisZ.y*this._rotated.z,this._normals32[o+2]=this._cam_axisX.z*this._rotated.x+this._cam_axisY.z*this._rotated.y+this._cam_axisZ.z*this._rotated.z),this._computeParticleColor&&this._particle.color&&(this._colors32[a]=this._particle.color.r,this._colors32[a+1]=this._particle.color.g,this._colors32[a+2]=this._particle.color.b,this._colors32[a+3]=this._particle.color.a),this._computeParticleTexture&&(this._uvs32[c]=this._shapeUV[2*u]*(this._particle.uvs.z-this._particle.uvs.x)+this._particle.uvs.x,this._uvs32[c+1]=this._shapeUV[2*u+1]*(this._particle.uvs.w-this._particle.uvs.y)+this._particle.uvs.y);else for(this._particle._stillInvisible=!0,u=0;ue.Tmp.Vector3[1].x&&(e.Tmp.Vector3[1].x=l[u].x),l[u].ye.Tmp.Vector3[1].y&&(e.Tmp.Vector3[1].y=l[u].y),l[u].ze.Tmp.Vector3[1].z&&(e.Tmp.Vector3[1].z=l[u].z),u++,r+=3;c._closePath&&(t[r]=l[0].x,t[r+1]=l[0].y,t[r+2]=l[0].z,r+=3)}}(u),c._boundingInfo=new e.BoundingInfo(e.Tmp.Vector3[0],e.Tmp.Vector3[1]),c._boundingInfo.update(c._worldMatrix),c.updateVerticesData(e.VertexBuffer.PositionKind,u,!1,!1),r.colors){for(var d=c.getVerticesData(e.VertexBuffer.ColorKind),f=0;f1?1:r.arc:1,a=void 0===r.closed||r.closed,l=r.shape,c=r.radius||1,h=r.tessellation||64,u=r.clip||0,d=r.updatable,f=t.updateSideOrientation(r.sideOrientation),p=r.cap||e.Mesh.NO_CAP,_=2*Math.PI,m=new Array,g=r.invertUV||!1,v=0,y=0,b=_/h*s,x=new Array;for(v=0;v<=h-u;v++){var x=[];for(p!=e.Mesh.CAP_START&&p!=e.Mesh.CAP_ALL||(x.push(new e.Vector3(0,l[0].y,0)),x.push(new e.Vector3(Math.cos(v*b)*l[0].x*c,l[0].y,Math.sin(v*b)*l[0].x*c))),y=0;y1)?1:r.arc||1;var p,_,m=function(t,i,r,n,o,s,a,l){for(var c,h,u,d,f=i.getTangents(),p=i.getNormals(),_=i.getDistances(),m=2*Math.PI,g=m/o*l,v=function(){return n},y=s||v,b=e.Tmp.Matrix[0],x=a===e.Mesh._NO_CAP||a===e.Mesh.CAP_END?0:2,T=0;T3?0:h,_=m(o,p,v,a,l,c,h,r.arc);var y=t.CreateRibbon(i,{pathArray:_,closePath:!0,closeArray:!1,updatable:d,sideOrientation:f,invertUV:u,frontUVs:r.frontUVs,backUVs:r.backUVs},n);return y.pathArray=_,y.path3D=p,y.tessellation=l,y.cap=h,y.arc=r.arc,y.radius=a,y},t.CreatePolyhedron=function(i,r,n){var o=new e.Mesh(i,n);return r.sideOrientation=t.updateSideOrientation(r.sideOrientation),o._originalBuilderSideOrientation=r.sideOrientation,e.VertexData.CreatePolyhedron(r).applyToMesh(o,r.updatable),o},t.CreateDecal=function(t,i,r){var n=i.getIndices(),o=i.getVerticesData(e.VertexBuffer.PositionKind),s=i.getVerticesData(e.VertexBuffer.NormalKind),a=r.position||e.Vector3.Zero(),l=r.normal||e.Vector3.Up(),c=r.size||e.Vector3.One(),h=r.angle||0;if(!l){var u=new e.Vector3(0,0,1),d=i.getScene().activeCamera,f=e.Vector3.TransformCoordinates(u,d.getWorldMatrix());l=d.globalPosition.subtract(f)}var p=-Math.atan2(l.z,l.x)-Math.PI/2,_=Math.sqrt(l.x*l.x+l.z*l.z),m=Math.atan2(l.y,_),g=e.Matrix.RotationYawPitchRoll(p,m,h).multiply(e.Matrix.Translation(a.x,a.y,a.z)),v=e.Matrix.Invert(g),y=i.getWorldMatrix(),b=y.multiply(v),x=new e.VertexData;x.indices=[],x.positions=[],x.normals=[],x.uvs=[];for(var T=0,E=function(t){var i=new e.PositionNormalVertex;if(!n||!o||!s)return i;var r=n[t];return i.position=new e.Vector3(o[3*r],o[3*r+1],o[3*r+2]),i.position=e.Vector3.TransformCoordinates(i.position,b),i.normal=new e.Vector3(s[3*r],s[3*r+1],s[3*r+2]),i.normal=e.Vector3.TransformNormal(i.normal,b),i},P=function(t,i){if(0===t.length)return t;for(var r=.5*Math.abs(e.Vector3.Dot(c,i)),n=function(t,n){var o=e.Vector3.GetClipFactor(t.position,n.position,i,r);return new e.PositionNormalVertex(e.Vector3.Lerp(t.position,n.position,o),e.Vector3.Lerp(t.normal,n.normal,o))},o=new Array,s=0;s0,l=m>0,h=g>0,(a?1:0)+(l?1:0)+(h?1:0)){case 0:o.push(t[s]),o.push(t[s+1]),o.push(t[s+2]);break;case 1:if(a&&(u=t[s+1],d=t[s+2],f=n(t[s],u),p=n(t[s],d)),l){u=t[s],d=t[s+2],f=n(t[s+1],u),p=n(t[s+1],d),o.push(f),o.push(d.clone()),o.push(u.clone()),o.push(d.clone()),o.push(f.clone()),o.push(p);break}h&&(u=t[s],d=t[s+1],f=n(t[s+2],u),p=n(t[s+2],d)),u&&d&&f&&p&&(o.push(u.clone()),o.push(d.clone()),o.push(f),o.push(p),o.push(f.clone()),o.push(d.clone()));break;case 2:a||(u=t[s].clone(),d=n(u,t[s+1]),f=n(u,t[s+2]),o.push(u),o.push(d),o.push(f)),l||(u=t[s+1].clone(),d=n(u,t[s+2]),f=n(u,t[s]),o.push(u),o.push(d),o.push(f)),h||(u=t[s+2].clone(),d=n(u,t[s]),f=n(u,t[s+1]),o.push(u),o.push(d),o.push(f))}}return o},A=0;A3?0:u,x=T(r,n,b,E,o,s,a,l,u,d);var P=t.CreateRibbon(i,{pathArray:x,closeArray:c,closePath:h,updatable:p,sideOrientation:_,invertUV:g,frontUVs:v||void 0,backUVs:y||void 0 -},f);return P.pathArray=x,P.path3D=b,P.cap=u,P},t})();e.MeshBuilder=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return Object.defineProperty(t,"DecoderAvailable",{get:function(){if("undefined"!=typeof DracoDecoderModule)return!0;var e=t.Configuration.decoder;if(e){if(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly)return!0;if(e.fallbackUrl)return!0}return!1},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){},t.prototype.decodeMeshAsync=function(i,r){var n=i instanceof ArrayBuffer?new Uint8Array(i):i;return t._GetDecoderModule().then((function(t){var i=t.module,o=new e.VertexData,s=new i.DecoderBuffer;s.Init(n,n.byteLength);var a,l,c=new i.Decoder;try{var h=c.GetEncodedGeometryType(s);switch(h){case i.TRIANGULAR_MESH:a=new i.Mesh,l=c.DecodeBufferToMesh(s,a);break;case i.POINT_CLOUD:a=new i.PointCloud,l=c.DecodeBufferToPointCloud(s,a);break;default:throw new Error("Invalid geometry type "+h)}if(!l.ok()||!a.ptr)throw new Error(l.error_msg());var u=a.num_points();if(h===i.TRIANGULAR_MESH){var d=a.num_faces(),f=new i.DracoInt32Array;try{for(var p=new Uint32Array(3*d),_=0;_0&&(c=!0,this._soundLoaded(i));break;case"String":l.push(i);case"Array":0===l.length&&(l=i);for(var h=0;h0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect();else if(e.Engine.audioEngine.audioContext&&this._soundSource){var i=t?e.Engine.audioEngine.audioContext.currentTime+t:e.Engine.audioEngine.audioContext.currentTime;this._soundSource.stop(i),this._soundSource.onended=function(){},this.isPaused||(this._startOffset=0)}this.isPlaying=!1}},t.prototype.pause=function(){this.isPlaying&&(this.isPaused=!0,this._streaming?this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect():e.Engine.audioEngine.audioContext&&(this.stop(0),this._startOffset+=e.Engine.audioEngine.audioContext.currentTime-this._startTime))},t.prototype.setVolume=function(t,i){e.Engine.audioEngine.canUseWebAudio&&this._soundGain&&(i&&e.Engine.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(t,e.Engine.audioEngine.audioContext.currentTime+i)):this._soundGain.gain.value=t),this._volume=t},t.prototype.setPlaybackRate=function(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))},t.prototype.getVolume=function(){return this._volume},t.prototype.attachToMesh=function(e){var t=this;this._connectedMesh&&this._registerFunc&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedMesh=e,this.spatialSound||(this.spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play())),this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh),this._registerFunc=function(e){return t._onRegisterAfterWorldMatrixUpdate(e)},e.registerAfterWorldMatrixUpdate(this._registerFunc)},t.prototype.detachFromMesh=function(){this._connectedMesh&&this._registerFunc&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedMesh=null)},t.prototype._onRegisterAfterWorldMatrixUpdate=function(t){if(t.getBoundingInfo){var i=t,r=i.getBoundingInfo();this.setPosition(r.boundingSphere.centerWorld),e.Engine.audioEngine.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}},t.prototype.clone=function(){var e=this;if(this._streaming)return null;var i=function(){e._isReadyToPlay?(n._audioBuffer=e.getAudioBuffer(),n._isReadyToPlay=!0,n.autoplay&&n.play()):window.setTimeout(i,300)},r={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},n=new t(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,r);return this.useCustomAttenuation&&n.setAttenuationFunction(this._customAttenuationFunction),n.setPosition(this._position),n.setPlaybackRate(this._playbackRate),i(),n},t.prototype.getAudioBuffer=function(){return this._audioBuffer},t.prototype.serialize=function(){var e={name:this.name,url:this.name,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId};return this.spatialSound&&(this._connectedMesh&&(e.connectedMeshId=this._connectedMesh.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e},t.Parse=function(i,r,n,o){var s,a=i.name;s=i.url?n+i.url:n+a;var l,c={autoplay:i.autoplay,loop:i.loop,volume:i.volume,spatialSound:i.spatialSound,maxDistance:i.maxDistance,rolloffFactor:i.rolloffFactor,refDistance:i.refDistance,distanceModel:i.distanceModel,playbackRate:i.playbackRate};if(o){var h=function(){o._isReadyToPlay?(l._audioBuffer=o.getAudioBuffer(),l._isReadyToPlay=!0,l.autoplay&&l.play()):window.setTimeout(h,300)};l=new t(a,new ArrayBuffer(0),r,null,c),h()}else l=new t(a,s,r,function(){r._removePendingData(l)},c),r._addPendingData(l);if(i.position){var u=e.Vector3.FromArray(i.position);l.setPosition(u)}if(i.isDirectional&&(l.setDirectionalCone(i.coneInnerAngle||360,i.coneOuterAngle||360,i.coneOuterGain||0),i.localDirectionToMesh)){var d=e.Vector3.FromArray(i.localDirectionToMesh);l.setLocalDirectionToMesh(d)}if(i.connectedMeshId){var f=r.getMeshByID(i.connectedMeshId);f&&l.attachToMesh(f)}return l},t})();e.Sound=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t){this.id=-1,this._isMainTrack=!1,this._isInitialized=!1,this._scene=e,this.soundCollection=new Array,this._options=t,this._isMainTrack||(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}return t.prototype._initializeSoundTrackAudioGraph=function(){e.Engine.audioEngine.canUseWebAudio&&e.Engine.audioEngine.audioContext&&(this._outputAudioNode=e.Engine.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(e.Engine.audioEngine.masterGain),this._options&&(this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._options.mainTrack&&(this._isMainTrack=this._options.mainTrack)),this._isInitialized=!0)},t.prototype.dispose=function(){if(e.Engine.audioEngine&&e.Engine.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}},t.prototype.AddSound=function(t){this._isInitialized||this._initializeSoundTrackAudioGraph(),e.Engine.audioEngine.canUseWebAudio&&this._outputAudioNode&&t.connectToSoundTrackAudioNode(this._outputAudioNode),t.soundTrackId&&(-1===t.soundTrackId?this._scene.mainSoundTrack.RemoveSound(t):this._scene.soundTracks[t.soundTrackId].RemoveSound(t)),this.soundCollection.push(t),t.soundTrackId=this.id},t.prototype.RemoveSound=function(e){var t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)},t.prototype.setVolume=function(t){e.Engine.audioEngine.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=t)},t.prototype.switchPanningModelToHRTF=function(){if(e.Engine.audioEngine.canUseWebAudio)for(var t=0;t-1?i.substring(m).toLowerCase():""),v=".dds"===g,y=".env"===g;if(y?(_.gammaSpace=!1,_._prefiltered=!1):(_._prefiltered=h,h&&(_.gammaSpace=!1)),_._texture=_._getFromCache(i,o),!s&&(y||v||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),s=[],n))for(var b=0;b0&&(this._postProcesses[0].autoClear=!1))}},i.prototype._shouldRender=function(){return-1===this._currentRefreshId?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)},i.prototype.getRenderSize=function(){return this._size.width?this._size.width:this._size},i.prototype.getRenderWidth=function(){return this._size.width?this._size.width:this._size},i.prototype.getRenderHeight=function(){return this._size.width?this._size.height:this._size},Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype.scale=function(e){var t=this.getRenderSize()*e;this.resize(t)},i.prototype.getReflectionTextureMatrix=function(){return this.isCube?this._textureMatrix:t.prototype.getReflectionTextureMatrix.call(this)},i.prototype.resize=function(e){this.releaseInternalTexture();var t=this.getScene();t&&(this._processSizeParameter(e),this.isCube?this._texture=t.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._texture=t.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions))},i.prototype.render=function(e,t){void 0===e&&(e=!1),void 0===t&&(t=!1);var i=this.getScene();if(i){var r=i.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(var n=0;n=0&&this._renderingManager.dispatchParticles(v))}if(this.isCube)for(var b=0;b<6;b++)this.renderToTarget(b,h,u,e,t),i.incrementRenderId(),i.resetCachedMaterial();else this.renderToTarget(0,h,u,e,t);this.onAfterUnbindObservable.notifyObservers(this),i.activeCamera&&(this.activeCamera&&this.activeCamera!==i.activeCamera&&i.setTransformMatrix(i.activeCamera.getViewMatrix(),i.activeCamera.getProjectionMatrix(!0)),r.setViewport(i.activeCamera.viewport)),i.resetCachedMaterial()}},i.prototype._bestReflectionRenderTargetDimension=function(t,i){var r=t*i,n=e.Tools.NearestPOT(r+16384/(128+r));return Math.min(e.Tools.FloorPOT(t),n)},i.prototype.unbindFrameBuffer=function(e,t){var i=this;this._texture&&e.unBindFramebuffer(this._texture,this.isCube,(function(){i.onAfterRenderObservable.notifyObservers(t)}))},i.prototype.renderToTarget=function(t,i,r,n,o){var s=this.getScene();if(s){var a=s.getEngine();this._texture&&(this._postProcessManager?this._postProcessManager._prepareFrame(this._texture,this._postProcesses):n&&s.postProcessManager._prepareFrame(this._texture)||this._texture&&a.bindFramebuffer(this._texture,this.isCube?t:void 0,void 0,void 0,this.ignoreCameraViewport,this.depthStencilTexture?this.depthStencilTexture:void 0),this.onBeforeRenderObservable.notifyObservers(t),this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):a.clear(this.clearColor||s.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),this._renderingManager.render(this.customRenderFunction,i,this.renderParticles,this.renderSprites),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._texture,t,this._postProcesses,this.ignoreCameraViewport):n&&s.postProcessManager._finalizeFrame(!1,this._texture,t),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),o&&e.Tools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),a),this.isCube&&5!==t?this.onAfterRenderObservable.notifyObservers(t):(this.isCube&&5===t&&a.generateMipMapsForCubemap(this._texture),this.unbindFrameBuffer(a,t)))}},i.prototype.setRenderingOrder=function(e,t,i,r){void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._renderingManager.setRenderingOrder(e,t,i,r)},i.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(var i=0;i=0&&e.customRenderTargets.splice(i,1);for(var r=0,n=e.cameras;r=0&&o.customRenderTargets.splice(i,1)}t.prototype.dispose.call(this)}},i.prototype._rebuild=function(){this.refreshRate===i.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=i.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()},i.prototype.freeRenderingGroups=function(){this._renderingManager&&this._renderingManager.freeRenderingGroups()},i._REFRESHRATE_RENDER_ONCE=0,i._REFRESHRATE_RENDER_ONEVERYFRAME=1,i._REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,i})(e.Texture);e.RenderTargetTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s){var a=this,l=!(!s||!s.generateMipMaps)&&s.generateMipMaps,c=!(!s||!s.generateDepthTexture)&&s.generateDepthTexture,h=!s||void 0===s.doNotChangeAspectRatio||s.doNotChangeAspectRatio;if(a=t.call(this,i,r,o,l,h)||this,a._engine=o.getEngine(),!a.isSupported)return void a.dispose();for(var u=[],d=[],f=0;f1||this._engine.getCaps().drawBuffersExtension},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"textures",{get:function(){return this._textures},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"depthTexture",{get:function(){return this._textures[this._textures.length-1]},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wrapU",{set:function(e){if(this._textures)for(var t=0;t=0;e--)void 0!==this._internalTextures[e]&&(this._internalTextures[e].dispose(),this._internalTextures.splice(e,1))},i})(e.RenderTargetTexture);e.MultiRenderTarget=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l){void 0===s&&(s=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),void 0===l&&(l=!0);var c=t.call(this,i,r,n,o,!0,s,!1,a,l)||this;return c.scene=n,c.mirrorPlane=new e.Plane(0,1,0,1),c._transformMatrix=e.Matrix.Zero(),c._mirrorMatrix=e.Matrix.Zero(),c._adaptiveBlurKernel=0,c._blurKernelX=0,c._blurKernelY=0,c._blurRatio=1,c.ignoreCameraViewport=!0,c._updateGammaSpace(),c._imageProcessingConfigChangeObserver=n.imageProcessingConfiguration.onUpdateParameters.add((function(){c._updateGammaSpace})),c.onBeforeRenderObservable.add((function(){e.Matrix.ReflectionToRef(c.mirrorPlane,c._mirrorMatrix),c._savedViewMatrix=n.getViewMatrix(),c._mirrorMatrix.multiplyToRef(c._savedViewMatrix,c._transformMatrix),n.setTransformMatrix(c._transformMatrix,n.getProjectionMatrix()),n.clipPlane=c.mirrorPlane,n.getEngine().cullBackFaces=!1,n._mirroredCameraPosition=e.Vector3.TransformCoordinates(n.activeCamera.globalPosition,c._mirrorMatrix)})),c.onAfterRenderObservable.add((function(){n.setTransformMatrix(c._savedViewMatrix,n.getProjectionMatrix()),n.getEngine().cullBackFaces=!0,n._mirroredCameraPosition=null,delete n.clipPlane})),c}return o(i,t),Object.defineProperty(i.prototype,"blurRatio",{get:function(){return this._blurRatio},set:function(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"adaptiveBlurKernel",{set:function(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurKernel",{set:function(e){this.blurKernelX=e,this.blurKernelY=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurKernelX",{get:function(){return this._blurKernelX},set:function(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurKernelY",{get:function(){return this._blurKernelY},set:function(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),i.prototype._autoComputeBlurKernel=function(){var e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i},i.prototype._onRatioRescale=function(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()},i.prototype._updateGammaSpace=function(){this.gammaSpace=!this.scene.imageProcessingConfiguration.isEnabled||!this.scene.imageProcessingConfiguration.applyByPostProcess},i.prototype._preparePostProcesses=function(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){var t=this.getScene().getEngine(),i=t.getCaps().textureFloatRender?e.Engine.TEXTURETYPE_FLOAT:e.Engine.TEXTURETYPE_HALF_FLOAT;this._blurX=new e.BlurPostProcess("horizontal blur",new e.Vector2(1,0),this._blurKernelX,this._blurRatio,null,e.Texture.BILINEAR_SAMPLINGMODE,t,!1,i),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._texture:this._blurX.alwaysForcePOT=!0,this._blurY=new e.BlurPostProcess("vertical blur",new e.Vector2(0,1),this._blurKernelY,this._blurRatio,null,e.Texture.BILINEAR_SAMPLINGMODE,t,!1,i),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=this.getSize(),r=new i(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(r.renderList=this.renderList.slice(0)),r},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.mirrorPlane.asArray(),e},i.prototype.dispose=function(){t.prototype.dispose.call(this),this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver)},i})(e.RenderTargetTexture);e.MirrorTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o){var s=t.call(this,i,r,n,o,!0)||this;return s.refractionPlane=new e.Plane(0,1,0,1),s.depth=2,s.onBeforeRenderObservable.add((function(){n.clipPlane=s.refractionPlane})),s.onAfterRenderObservable.add((function(){delete n.clipPlane})),s}return o(i,t),i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=this.getSize(),r=new i(this.name,t.width,e,this._generateMipMaps);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.refractionPlane=this.refractionPlane.clone(),this.renderList&&(r.renderList=this.renderList.slice(0)),r.depth=this.depth,r},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e},i})(e.RenderTargetTexture);e.RefractionTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a){void 0===n&&(n=null),void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===a&&(a=e.Engine.TEXTUREFORMAT_RGBA);var l=t.call(this,null,n,!o,void 0,s,void 0,void 0,void 0,void 0,a)||this;l.name=i,l._engine=l.getScene().getEngine(),l.wrapU=e.Texture.CLAMP_ADDRESSMODE,l.wrapV=e.Texture.CLAMP_ADDRESSMODE,l._generateMipMaps=o,r.getContext?(l._canvas=r,l._texture=l._engine.createDynamicTexture(r.width,r.height,o,s)):(l._canvas=document.createElement("canvas"),r.width||0===r.width?l._texture=l._engine.createDynamicTexture(r.width,r.height,o,s):l._texture=l._engine.createDynamicTexture(r,r,o,s));var c=l.getSize();return l._canvas.width=c.width,l._canvas.height=c.height,l._context=l._canvas.getContext("2d"),l}return o(i,t),Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype._recreate=function(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._engine.createDynamicTexture(e.width,e.height,this._generateMipMaps,this._samplingMode)},i.prototype.scale=function(e){var t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)},i.prototype.scaleTo=function(e,t){var i=this.getSize();i.width=e,i.height=t,this._recreate(i)},i.prototype.getContext=function(){return this._context},i.prototype.clear=function(){var e=this.getSize();this._context.fillRect(0,0,e.width,e.height)},i.prototype.update=function(e,t){void 0===t&&(t=!1),this._engine.updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0)},i.prototype.drawText=function(e,t,i,r,n,o,s,a){void 0===a&&(a=!0);var l=this.getSize();if(o&&(this._context.fillStyle=o,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null===t||void 0===t){var c=this._context.measureText(e);t=(l.width-c.width)/2}if(null===i||void 0===i){var h=parseInt(r.replace(/\D/g,""));i=l.height/2+h/3.65}this._context.fillStyle=n,this._context.fillText(e,t,i),a&&this.update(s)},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=this.getSize(),r=new i(this.name,t,e,this._generateMipMaps);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.wrapU=this.wrapU,r.wrapV=this.wrapV,r},i.prototype.serialize=function(){var i=this.getScene();i&&!i.isReady()&&e.Tools.Warn("The scene must be ready before serializing the dynamic texture");var r=t.prototype.serialize.call(this);return r.base64String=this._canvas.toDataURL(),r.invertY=this._invertY,r.samplingMode=this.samplingMode,r},i.prototype._rebuild=function(){this.update()},i})(e.Texture);e.DynamicTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l){void 0===o&&(o=!1),void 0===s&&(s=!1),void 0===a&&(a=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===l&&(l={autoPlay:!0,loop:!0,autoUpdateTexture:!0});var c=t.call(this,null,n,!o,s)||this;return c._onUserActionRequestedObservable=null,c._stillImageCaptured=!1,c._poster=!1,c._createInternalTexture=function(){if(null!=c._texture){if(!c._poster)return;c._texture.dispose(),c._poster=!1}if(!c._engine.needPOTTextures||e.Tools.IsExponentOfTwo(c.video.videoWidth)&&e.Tools.IsExponentOfTwo(c.video.videoHeight)?(c.wrapU=e.Texture.WRAP_ADDRESSMODE,c.wrapV=e.Texture.WRAP_ADDRESSMODE):(c.wrapU=e.Texture.CLAMP_ADDRESSMODE,c.wrapV=e.Texture.CLAMP_ADDRESSMODE,c._generateMipMaps=!1),c._texture=c._engine.createDynamicTexture(c.video.videoWidth,c.video.videoHeight,c._generateMipMaps,c._samplingMode),c.video.autoplay)c._texture.isReady=!0,c._updateInternalTexture(),c._onLoadObservable&&c._onLoadObservable.hasObservers()&&c.onLoadObservable.notifyObservers(c);else{var t=c.video.onplaying,i=!1;c.video.onplaying=function(){c.video.onplaying=t,c._texture.isReady=!0,c._updateInternalTexture(),i||c.video.pause(),c._onLoadObservable&&c._onLoadObservable.hasObservers()&&c.onLoadObservable.notifyObservers(c)};var r=c.video.play();r?r.then((function(){})).catch((function(){i=!0,c._onUserActionRequestedObservable&&c._onUserActionRequestedObservable.hasObservers()&&c._onUserActionRequestedObservable.notifyObservers(c)})):(c.video.onplaying=t,c._texture.isReady=!0,c._updateInternalTexture(),c._onLoadObservable&&c._onLoadObservable.hasObservers()&&c.onLoadObservable.notifyObservers(c))}},c.reset=function(){null!=c._texture&&(c._poster||(c._texture.dispose(),c._texture=null))},c._updateInternalTexture=function(e){null!=c._texture&&c._texture.isReady&&(c.video.readyState=c.video.HAVE_CURRENT_DATA&&c._createInternalTexture(),l.poster&&(c._texture=c._engine.createTexture(l.poster,!1,!0,n),c._poster=!0),c}return o(i,t),Object.defineProperty(i.prototype,"onUserActionRequestedObservable",{get:function(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new e.Observable),this._onUserActionRequestedObservable},enumerable:!0,configurable:!0}),i.prototype._getName=function(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e},i.prototype._getVideo=function(t){if(t instanceof HTMLVideoElement)return e.Tools.SetCorsBehavior(t.currentSrc,t),t;var i=document.createElement("video");return"string"==typeof t?(e.Tools.SetCorsBehavior(t,i),i.src=t):(e.Tools.SetCorsBehavior(t[0],i),t.forEach((function(e){var t=document.createElement("source");t.src=e,i.appendChild(t)}))),i},i.prototype._rebuild=function(){this.update()},i.prototype.update=function(){this.autoUpdateTexture&&this.updateTexture(!0)},i.prototype.updateTexture=function(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))},i.prototype.updateURL=function(e){this.video.src=e},i.prototype.dispose=function(){t.prototype.dispose.call(this),this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener("canplay",this._createInternalTexture),this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this.reset),this.video.pause()},i.CreateFromWebCam=function(t,r,n){var o=document.createElement("video");o.setAttribute("autoplay",""),o.setAttribute("muted",""),o.setAttribute("playsinline","");var s;n&&n.deviceId&&(s={exact:n.deviceId}),window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,navigator.mediaDevices?navigator.mediaDevices.getUserMedia({video:n}).then((function(e){void 0!==o.mozSrcObject?o.mozSrcObject=e:o.srcObject=e;var n=function(){r&&r(new i("video",o,t,!0,!0)),o.removeEventListener("playing",n)};o.addEventListener("playing",n),o.play()})).catch((function(t){e.Tools.Error(t.name)})):(navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,navigator.getUserMedia&&navigator.getUserMedia({video:{deviceId:s,width:{min:n&&n.minWidth||256,max:n&&n.maxWidth||640},height:{min:n&&n.minHeight||256,max:n&&n.maxHeight||480}}},(function(e){void 0!==o.mozSrcObject?o.mozSrcObject=e:o.src=window.URL&&window.URL.createObjectURL(e)||e,o.play(),r&&r(new i("video",o,t,!0,!0))}),(function(t){e.Tools.Error(t.name)})))},i})(e.Texture);e.VideoTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c,h){void 0===a&&(a=!0),void 0===l&&(l=!1),void 0===c&&(c=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT);var u=t.call(this,null,s,!a,l)||this;return u.format=o,u._engine=s.getEngine(),u._texture=s.getEngine().createRawTexture(i,r,n,o,a,l,c,null,h),u.wrapU=e.Texture.CLAMP_ADDRESSMODE,u.wrapV=e.Texture.CLAMP_ADDRESSMODE,u}return o(i,t),i.prototype.update=function(e){this._engine.updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,void 0,this._texture.type)},i.CreateLuminanceTexture=function(t,r,n,o,s,a,l){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_LUMINANCE,o,s,a,l)},i.CreateLuminanceAlphaTexture=function(t,r,n,o,s,a,l){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA,o,s,a,l)},i.CreateAlphaTexture=function(t,r,n,o,s,a,l){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_ALPHA,o,s,a,l)},i.CreateRGBTexture=function(t,r,n,o,s,a,l,c){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT),new i(t,r,n,e.Engine.TEXTUREFORMAT_RGB,o,s,a,l,c)},i.CreateRGBATexture=function(t,r,n,o,s,a,l,c){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT),new i(t,r,n,e.Engine.TEXTUREFORMAT_RGBA,o,s,a,l,c)},i.CreateRTexture=function(t,r,n,o,s,a,l,c){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===c&&(c=e.Engine.TEXTURETYPE_FLOAT),new i(t,r,n,e.Engine.TEXTUREFORMAT_R,o,s,a,l,c)},i})(e.Texture);e.RawTexture=t})(r||(r={}));var r;!(function(e){ -var t=(function(t){function i(i,r,n,o,s,a,l,c,h,u){void 0===l&&(l=!0),void 0===c&&(c=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===u&&(u=e.Engine.TEXTURETYPE_UNSIGNED_INT);var d=t.call(this,null,a,!l,c)||this;return d.format=s,d._engine=a.getEngine(),d._texture=a.getEngine().createRawTexture3D(i,r,n,o,s,l,c,h,void 0,u),d.is3D=!0,d}return o(i,t),i.prototype.update=function(e){this._texture&&this._engine.updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,void 0,this._texture.type)},i})(e.Texture);e.RawTexture3D=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e){this._vertexBuffers={},this._scene=e}return t.prototype._prepareBuffers=function(){if(!this._vertexBuffers[e.VertexBuffer.PositionKind]){var t=[];t.push(1,1),t.push(-1,1),t.push(-1,-1),t.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(this._scene.getEngine(),t,e.VertexBuffer.PositionKind,!1,!1,2),this._buildIndexBuffer()}},t.prototype._buildIndexBuffer=function(){var e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)},t.prototype._rebuild=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t._rebuild(),this._buildIndexBuffer())},t.prototype._prepareFrame=function(e,t){void 0===e&&(e=null),void 0===t&&(t=null);var i=this._scene.activeCamera;if(!i)return!1;var t=t||i._postProcesses.filter((function(e){return null!=e}));return!(!t||0===t.length||!this._scene.postProcessesEnabled)&&(t[0].activate(i,e,null!==t&&void 0!==t),!0)},t.prototype.directRender=function(t,i,r,n,o){void 0===i&&(i=null),void 0===r&&(r=!1),void 0===n&&(n=0),void 0===o&&(o=0);for(var s=this._scene.getEngine(),a=0;a0){for(var p=0;p0)for(var e=0;e0){var r=this._camera._getFirstPostProcess();r&&r.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}},t})();e.PostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c){return void 0===n&&(n=null),void 0===l&&(l=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1),t.call(this,i,"pass",null,null,r,n,o,s,a,void 0,l,void 0,null,c)||this}return o(i,t),i})(e.PostProcess);e.PassPostProcess=t})(r||(r={}));var r,s=this&&this.__assign||Object.assign||function(e){for(var t,i=1,r=arguments.length;i=1?1:e<=0?0:e,this},t.prototype.setTransparencyShadow=function(e){return this._transparencyShadow=e,this},t.prototype.getShadowMap=function(){return this._shadowMap},t.prototype.getShadowMapForRendering=function(){return this._shadowMap2?this._shadowMap2:this._shadowMap},t.prototype.addShadowCaster=function(e,t){return void 0===t&&(t=!0),this._shadowMap?(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.push(e),t&&(i=this._shadowMap.renderList).push.apply(i,e.getChildMeshes()),this):this;var i},t.prototype.removeShadowCaster=function(e,t){if(void 0===t&&(t=!0),!this._shadowMap||!this._shadowMap.renderList)return this;var i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(var r=0,n=e.getChildren();r1?(this._shadowMap=new e.RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1),this._shadowMap.createDepthStencilTexture(e.Engine.LESS,!0)):this._shadowMap=new e.RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._shadowMap.onBeforeRenderObservable.add((function(e){i._currentFaceIndex=e,i._filter===t.FILTER_PCF&&r.setColorWrite(!1)})),this._shadowMap.customRenderFunction=this._renderForShadowMap.bind(this),this._shadowMap.onAfterUnbindObservable.add((function(){if(i._filter===t.FILTER_PCF&&r.setColorWrite(!0),i.useBlurExponentialShadowMap||i.useBlurCloseExponentialShadowMap){var e=i.getShadowMapForRendering();e&&i._scene.postProcessManager.directRender(i._blurPostProcesses,e.getInternalTexture(),!0)}}));var n=new e.Color4(0,0,0,0),o=new e.Color4(1,1,1,1);this._shadowMap.onClearObservable.add((function(e){i._filter===t.FILTER_PCF?e.clear(o,!1,!0,!1):i.useExponentialShadowMap||i.useBlurExponentialShadowMap?e.clear(n,!0,!0,!1):e.clear(o,!0,!0,!1)}))},t.prototype._initializeBlurRTTAndPostProcesses=function(){var t=this,i=this._scene.getEngine(),r=this._mapSize/this.blurScale;this.useKernelBlur&&1===this.blurScale||(this._shadowMap2=new e.RenderTargetTexture(this._light.name+"_shadowMap2",r,this._scene,!1,!0,this._textureType),this._shadowMap2.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new e.BlurPostProcess(this._light.name+"KernelBlurX",new e.Vector2(1,0),this.blurKernel,1,null,e.Texture.BILINEAR_SAMPLINGMODE,i,!1,this._textureType),this._kernelBlurXPostprocess.width=r,this._kernelBlurXPostprocess.height=r,this._kernelBlurXPostprocess.onApplyObservable.add((function(e){e.setTexture("textureSampler",t._shadowMap)})),this._kernelBlurYPostprocess=new e.BlurPostProcess(this._light.name+"KernelBlurY",new e.Vector2(0,1),this.blurKernel,1,null,e.Texture.BILINEAR_SAMPLINGMODE,i,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===e.Engine.TEXTURETYPE_UNSIGNED_INT&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new e.PostProcess(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,e.Texture.BILINEAR_SAMPLINGMODE,i,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",r,r),e.setTexture("textureSampler",t._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])},t.prototype._renderForShadowMap=function(e,t,i,r){var n,o=this._scene.getEngine();if(r.length){for(o.setColorWrite(!1),n=0;n=a.length)return void(e&&e(i));setTimeout(d,16)}};d()},t.prototype.forceCompilationAsync=function(e){var t=this;return new Promise(function(i){t.forceCompilation((function(){i()}),e)})},t.prototype.isReady=function(t,i){var r=[];this._textureType!==e.Engine.TEXTURETYPE_UNSIGNED_INT&&r.push("#define FLOAT"),this.useExponentialShadowMap||this.useBlurExponentialShadowMap?r.push("#define ESM"):(this.usePercentageCloserFiltering||this.useContactHardeningShadow)&&r.push("#define DEPTHTEXTURE");var n=[e.VertexBuffer.PositionKind],o=t.getMesh(),s=t.getMaterial();if(this.normalBias&&o.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(n.push(e.VertexBuffer.NormalKind),r.push("#define NORMAL"),o.nonUniformScaling&&r.push("#define NONUNIFORMSCALING"),this.getLight().getTypeID()===e.Light.LIGHTTYPEID_DIRECTIONALLIGHT&&r.push("#define DIRECTIONINLIGHTDATA")),s&&s.needAlphaTesting()){var a=s.getAlphaTestTexture();a&&(r.push("#define ALPHATEST"),o.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push(e.VertexBuffer.UVKind),r.push("#define UV1")),o.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&1===a.coordinatesIndex&&(n.push(e.VertexBuffer.UV2Kind),r.push("#define UV2")))}o.useBones&&o.computeBonesUsingShaders?(n.push(e.VertexBuffer.MatricesIndicesKind),n.push(e.VertexBuffer.MatricesWeightsKind),o.numBoneInfluencers>4&&(n.push(e.VertexBuffer.MatricesIndicesExtraKind),n.push(e.VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton.bones.length+1))):r.push("#define NUM_BONE_INFLUENCERS 0");var l=o.morphTargetManager,c=0;l&&l.numInfluencers>0&&(r.push("#define MORPHTARGETS"),c=l.numInfluencers,r.push("#define NUM_MORPH_INFLUENCERS "+c),e.MaterialHelper.PrepareAttributesForMorphTargets(n,o,{NUM_MORPH_INFLUENCERS:c})),i&&(r.push("#define INSTANCES"),n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"));var h=r.join("\n");return this._cachedDefines!==h&&(this._cachedDefines=h,this._effect=this._scene.getEngine().createEffect("shadowMap",n,["world","mBones","viewProjection","diffuseMatrix","lightData","depthValues","biasAndScale","morphTargetInfluences"],["diffuseSampler"],h,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c})),!!this._effect.isReady()&&((this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady())&&(!(this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady())&&!(this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())))},t.prototype.prepareDefines=function(e,i){var r=this._scene,n=this._light;r.shadowsEnabled&&n.shadowEnabled&&(e["SHADOW"+i]=!0,this.useContactHardeningShadow&&(e["SHADOWPCSS"+i]=!0,this._filteringQuality===t.QUALITY_LOW?e["SHADOWLOWQUALITY"+i]=!0:this._filteringQuality===t.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+i]=!0)),this.usePercentageCloserFiltering?(e["SHADOWPCF"+i]=!0,this._filteringQuality===t.QUALITY_LOW?e["SHADOWLOWQUALITY"+i]=!0:this._filteringQuality===t.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+i]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+i]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+i]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+i]=!0),n.needCube()&&(e["SHADOWCUBE"+i]=!0))},t.prototype.bindShadowLight=function(e,i){var r=this._light,n=this._scene;if(n.shadowsEnabled&&r.shadowEnabled){var o=n.activeCamera;if(o){var s=this.getShadowMap();s&&(r.needCube()||i.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===t.FILTER_PCF?(i.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),s.getSize().width,1/s.getSize().width,this.frustumEdgeFalloff,e)):this._filter===t.FILTER_PCSS?(i.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i.setTexture("depthSampler"+e,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/s.getSize().width,this._contactHardeningLightSizeUVRatio*s.getSize().width,this.frustumEdgeFalloff,e)):(i.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/s.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),r._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(o),this.getLight().getDepthMinZ(o)+this.getLight().getDepthMaxZ(o),e))}}},t.prototype.getTransformMatrix=function(){var t=this._scene;if(this._currentRenderID===t.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderID=t.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;var i=this._light.position;if(this._light.computeTransformedInformation()&&(i=this._light.transformedPosition),e.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(e.Vector3.Dot(this._lightDirection,e.Vector3.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!i.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(i),this._cachedDirection.copyFrom(this._lightDirection),e.Matrix.LookAtLHToRef(i,i.add(this._lightDirection),e.Vector3.Up(),this._viewMatrix);var r=this.getShadowMap();if(r){var n=r.renderList;n&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,n)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)} -return this._transformMatrix},t.prototype.recreateShadowMap=function(){var e=this._shadowMap;if(e){var t=e.renderList;this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this.filter,this._applyFilterValues(),this._shadowMap.renderList=t}},t.prototype._disposeBlurPostProcesses=function(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]},t.prototype._disposeRTTandPostProcesses=function(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()},t.prototype.dispose=function(){this._disposeRTTandPostProcesses(),this._light&&(this._light._shadowGenerator=null,this._light._markMeshesAsLightDirty())},t.prototype.serialize=function(){var e={},t=this.getShadowMap();if(!t)return e;if(e.lightId=this._light.id,e.mapSize=t.getRenderSize(),e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.forceBackFacesOnly=this.forceBackFacesOnly,e.depthScale=this.depthScale,e.darkness=this.getDarkness(),e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.filteringQuality=this.filteringQuality,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.renderList=[],t.renderList)for(var i=0;i0){for(var ne=0;ne0){for(var se=0;se-1&&void 0!==f.skeletons&&null!==f.skeletons){if(!1===v.indexOf(b.skeletonId)>-1)for(var D=0,I=f.skeletons.length;D0&&this._textureLoadingCallback(e)}this._currentScene.render()}},t.prototype.drag=function(e){e.stopPropagation(),e.preventDefault()},t.prototype.drop=function(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)},t.prototype._traverseFolder=function(e,t,i,r){var n=this,o=e.createReader(),s=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");o.readEntries((function(e){i.count+=e.length;for(var o=0,a=e;o0){for(var i=new Array,r=[],n=e.dataTransfer?e.dataTransfer.items:null,o=0;o0&&e.Tools.ClearLogCache(),this._engine.stopRenderLoop()),e.SceneLoader.LoadAsync("file:",this._sceneFileToLoad,this._engine,(function(e){t._progressCallback&&t._progressCallback(e)})).then((function(e){t._currentScene&&t._currentScene.dispose(),t._currentScene=e,t._sceneLoadedCallback&&t._sceneLoadedCallback(t._sceneFileToLoad,t._currentScene),t._currentScene.executeWhenReady((function(){t._engine.runRenderLoop((function(){t.renderFunction()}))}))})).catch((function(e){t._errorCallback&&t._errorCallback(t._sceneFileToLoad,t._currentScene,e.message)}))):e.Tools.Error("Please provide a valid .babylon file.")},t.FilesToLoad={},t})();e.FilesInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.EnableFor=function(e){e._tags=e._tags||{},e.hasTags=function(){return t.HasTags(e)},e.addTags=function(i){return t.AddTagsTo(e,i)},e.removeTags=function(i){return t.RemoveTagsFrom(e,i)},e.matchesTagsQuery=function(i){return t.MatchesQuery(e,i)}},t.DisableFor=function(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery},t.HasTags=function(t){return!!t._tags&&!e.Tools.IsEmpty(t._tags)},t.GetTags=function(e,t){if(void 0===t&&(t=!0),!e._tags)return null;if(t){var i=[];for(var r in e._tags)e._tags.hasOwnProperty(r)&&!0===e._tags[r]&&i.push(r);return i.join(" ")}return e._tags},t.AddTagsTo=function(e,i){if(i&&"string"==typeof i){i.split(" ").forEach((function(i,r,n){t._AddTagTo(e,i)}))}},t._AddTagTo=function(e,i){""!==(i=i.trim())&&"true"!==i&&"false"!==i&&(i.match(/[\s]/)||i.match(/^([!]|([|]|[&]){2})/)||(t.EnableFor(e),e._tags[i]=!0))},t.RemoveTagsFrom=function(e,i){if(t.HasTags(e)){var r=i.split(" ");for(var n in r)t._RemoveTagFrom(e,r[n])}},t._RemoveTagFrom=function(e,t){delete e._tags[t]},t.MatchesQuery=function(i,r){return void 0===r||(""===r?t.HasTags(i):e.AndOrNotEvaluator.Eval(r,(function(e){return t.HasTags(i)&&i._tags[e]})))},t})();e.Tags=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){}return e.Eval=function(t,i){return"true"===(t=t.match(/\([^\(\)]*\)/g)?t.replace(/\([^\(\)]*\)/g,(function(t){return t=t.slice(1,t.length-1),e._HandleParenthesisContent(t,i)})):e._HandleParenthesisContent(t,i))||"false"!==t&&e.Eval(t,i)},e._HandleParenthesisContent=function(t,i){i=i||function(e){return"true"===e};var r,n=t.split("||");for(var o in n)if(n.hasOwnProperty(o)){var s=e._SimplifyNegation(n[o].trim()),a=s.split("&&");if(a.length>1)for(var l=0;l=400&&o?o(c):i()}),!1),c.addEventListener("error",(function(t){e.Tools.Error("error on XHR request."),i()}),!1),c.send()}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i()},t.IsUASupportingBlobStorage=!0,t.IDBStorageEnabled=!0,t._ParseURL=function(e){document.createElement("a").href=e;var t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},t._ReturnFullUrlLocation=function(e){return-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")?t._ParseURL(window.location.href)+e:e},t})();e.Database=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._isEnabled=!0,this.leftColor=e.Color3.White(),this.rightColor=e.Color3.Black(),this.bias=0,this.power=1}return Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(t){this._isEnabled!==t&&(this._isEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.FresnelDirtyFlag|e.Material.MiscDirtyFlag))},enumerable:!0,configurable:!0}),t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.serialize=function(){var e={};return e.isEnabled=this.isEnabled,e.leftColor=this.leftColor.asArray(),e.rightColor=this.rightColor.asArray(),e.bias=this.bias,e.power=this.power,e},t.Parse=function(i){var r=new t;return r.isEnabled=i.isEnabled,r.leftColor=e.Color3.FromArray(i.leftColor),r.rightColor=e.Color3.FromArray(i.rightColor),r.bias=i.bias,r.power=i.power||1,r},t})();e.FresnelParameters=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i){var r=t.call(this,e,i,!0)||this;return i.multiMaterials.push(r),r.subMaterials=new Array,r.storeEffectOnSubMeshes=!0,r}return o(i,t),Object.defineProperty(i.prototype,"subMaterials",{get:function(){return this._subMaterials},set:function(e){this._subMaterials=e,this._hookArray(e)},enumerable:!0,configurable:!0}),i.prototype._hookArray=function(e){var t=this,i=e.push;e.push=function(){for(var r=[],n=0;n=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]},i.prototype.getActiveTextures=function(){return(e=t.prototype.getActiveTextures.call(this)).concat.apply(e,this.subMaterials.map((function(e){return e?e.getActiveTextures():[]})));var e},i.prototype.getClassName=function(){return"MultiMaterial"},i.prototype.isReadyForSubMesh=function(e,t,i){for(var r=0;r=0&&r.multiMaterials.splice(n,1),t.prototype.dispose.call(this,e,i)}},i})(e.Material);e.MultiMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250}return t.prototype.attachControl=function(t,i){var r=this,n=null;void 0===this._pointerInput&&(this._onLostFocus=function(e){r._offsetX=null,r._offsetY=null},this._pointerInput=function(t,o){var s=t.event;if("mouse"!==s.pointerType)if(t.type===e.PointerEventTypes.POINTERDOWN){if(i||s.preventDefault(),r._pointerPressed.push(s.pointerId),1!==r._pointerPressed.length)return;n={x:s.clientX,y:s.clientY}}else if(t.type===e.PointerEventTypes.POINTERUP){i||s.preventDefault();var a=r._pointerPressed.indexOf(s.pointerId);if(-1===a)return;if(r._pointerPressed.splice(a,1),0!=a)return;n=null,r._offsetX=null,r._offsetY=null}else if(t.type===e.PointerEventTypes.POINTERMOVE){if(i||s.preventDefault(),!n)return;var a=r._pointerPressed.indexOf(s.pointerId);if(0!=a)return;r._offsetX=s.clientX-n.x,r._offsetY=-(s.clientY-n.y)}}),this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE),this._onLostFocus&&t.addEventListener("blur",this._onLostFocus)},t.prototype.detachControl=function(e){this._pointerInput&&e&&(this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null),this._onLostFocus&&(e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null),this._pointerPressed=[],this._offsetX=null,this._offsetY=null)},t.prototype.checkInputs=function(){if(this._offsetX&&this._offsetY){var t=this.camera;if(t.cameraRotation.y+=this._offsetX/this.touchAngularSensibility,this._pointerPressed.length>1)t.cameraRotation.x+=-this._offsetY/this.touchAngularSensibility;else{var i=t._computeLocalCameraSpeed(),r=new e.Vector3(0,0,i*this._offsetY/this.touchMoveSensibility);e.Matrix.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,0,t._cameraRotationMatrix),t.cameraDirection.addInPlace(e.Vector3.TransformCoordinates(r,t._cameraRotationMatrix))}}},t.prototype.getClassName=function(){return"FreeCameraTouchInput"},t.prototype.getSimpleName=function(){return"touch"},n([e.serialize()],t.prototype,"touchAngularSensibility",void 0),n([e.serialize()],t.prototype,"touchMoveSensibility",void 0),t})();e.FreeCameraTouchInput=t,e.CameraInputTypes.FreeCameraTouchInput=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("TouchCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addTouch(),n._setupInputs(),n}return o(t,e),Object.defineProperty(t.prototype,"touchAngularSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"touchMoveSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"TouchCamera"},t.prototype._setupInputs=function(){var e=this.inputs.attached.mouse;e&&(e.touchEnabled=!1)},t})(e.FreeCamera);e.TouchCamera=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l){void 0===s&&(s=null),void 0===a&&(a=!0),void 0===l&&(l=!1);var c=t.call(this,null,o,!a)||this;c.isCube=l,c.isEnabled=!0,c._currentRefreshId=-1,c._refreshRate=1,c._vertexBuffers={},c._uniforms=new Array,c._samplers=new Array,c._textures={},c._floats={},c._ints={},c._floatsArrays={},c._colors3={},c._colors4={},c._vectors2={},c._vectors3={},c._matrices={},c._fallbackTextureUsed=!1,o=c.getScene(),o.proceduralTextures.push(c),c._engine=o.getEngine(),c.name=i,c.isRenderTarget=!0,c._size=r,c._generateMipMaps=a,c.setFragment(n),c._fallbackTexture=s,l?(c._texture=c._engine.createRenderTargetCubeTexture(r,{generateMipMaps:a}),c.setFloat("face",0)):c._texture=c._engine.createRenderTargetTexture(r,a);var h=[];return h.push(1,1),h.push(-1,1),h.push(-1,-1),h.push(1,-1),c._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(c._engine,h,e.VertexBuffer.PositionKind,!1,!1,2),c._createIndexBuffer(),c}return o(i,t),i.prototype._createIndexBuffer=function(){var e=this._engine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)},i.prototype._rebuild=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&t._rebuild(),this._createIndexBuffer(),this.refreshRate===e.RenderTargetTexture.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=e.RenderTargetTexture.REFRESHRATE_RENDER_ONCE)},i.prototype.reset=function(){if(void 0!==this._effect){this._engine._releaseEffect(this._effect)}},i.prototype.isReady=function(){var t,i=this,r=this._engine;return!!this._fragment&&(!!this._fallbackTextureUsed||(t=void 0!==this._fragment.fragmentElement?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._effect=r.createEffect(t,[e.VertexBuffer.PositionKind],this._uniforms,this._samplers,"",void 0,void 0,(function(){i.releaseInternalTexture(),i._fallbackTexture&&(i._texture=i._fallbackTexture._texture,i._texture&&i._texture.incrementReferences()),i._fallbackTextureUsed=!0})),this._effect.isReady()))},i.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},i.prototype.setFragment=function(e){this._fragment=e},Object.defineProperty(i.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!0,configurable:!0}),i.prototype._shouldRender=function(){return!!(this.isEnabled&&this.isReady()&&this._texture)&&(!this._fallbackTextureUsed&&(-1===this._currentRefreshId?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)))},i.prototype.getRenderSize=function(){return this._size},i.prototype.resize=function(e,t){this._fallbackTextureUsed||(this.releaseInternalTexture(),this._texture=this._engine.createRenderTargetTexture(e,t),this._size=e,this._generateMipMaps=t)},i.prototype._checkUniform=function(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)},i.prototype.setTexture=function(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this},i.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},i.prototype.setInt=function(e,t){return this._checkUniform(e),this._ints[e]=t,this},i.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},i.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},i.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},i.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},i.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},i.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},i.prototype.render=function(t){var i=this.getScene();if(i){var r=this._engine;r.enableEffect(this._effect),r.setState(!1);for(var n in this._textures)this._effect.setTexture(n,this._textures[n]);for(n in this._ints)this._effect.setInt(n,this._ints[n]);for(n in this._floats)this._effect.setFloat(n,this._floats[n]);for(n in this._floatsArrays)this._effect.setArray(n,this._floatsArrays[n]);for(n in this._colors3)this._effect.setColor3(n,this._colors3[n]);for(n in this._colors4){var o=this._colors4[n];this._effect.setFloat4(n,o.r,o.g,o.b,o.a)}for(n in this._vectors2)this._effect.setVector2(n,this._vectors2[n]);for(n in this._vectors3)this._effect.setVector3(n,this._vectors3[n]);for(n in this._matrices)this._effect.setMatrix(n,this._matrices[n]);if(this._texture){if(this.isCube)for(var s=0;s<6;s++)r.bindFramebuffer(this._texture,s,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),this._effect.setFloat("face",s),r.clear(i.clearColor,!0,!0,!0),r.drawElementsType(e.Material.TriangleFillMode,0,6),5===s&&r.generateMipMapsForCubemap(this._texture);else r.bindFramebuffer(this._texture,0,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),r.clear(i.clearColor,!0,!0,!0),r.drawElementsType(e.Material.TriangleFillMode,0,6);r.unBindFramebuffer(this._texture,this.isCube),this.onGenerated&&this.onGenerated()}}},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t},i.prototype.dispose=function(){var i=this.getScene();if(i){var r=i.proceduralTextures.indexOf(this);r>=0&&i.proceduralTextures.splice(r,1);var n=this._vertexBuffers[e.VertexBuffer.PositionKind];n&&(n.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),t.prototype.dispose.call(this)}},n([e.serialize()],i.prototype,"_size",void 0),n([e.serialize()],i.prototype,"_generateMipMaps",void 0),n([e.serialize()],i.prototype,"isEnabled",void 0),n([e.serialize()],i.prototype,"refreshRate",null),i})(e.Texture);e.ProceduralTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i,r,n,o,s){var a=t.call(this,e,r,null,n,o,s)||this;return a._animate=!0,a._time=0,a._texturePath=i,a.loadJson(i),a.refreshRate=1,a}return o(i,t),i.prototype.loadJson=function(t){ -var i=this,r=function(){e.Tools.Log("No config file found in "+t+" trying to use ShadersStore or DOM element");try{i.setFragment(i._texturePath)}catch(t){e.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},n=t+"/config.json",o=new XMLHttpRequest;o.open("GET",n,!0),o.addEventListener("load",(function(){if(200===o.status||e.Tools.ValidateXHRData(o,1))try{i._config=JSON.parse(o.response),i.updateShaderUniforms(),i.updateTextures(),i.setFragment(i._texturePath+"/custom"),i._animate=i._config.animate,i.refreshRate=i._config.refreshrate}catch(e){r()}else r()}),!1),o.addEventListener("error",(function(){r()}),!1);try{o.send()}catch(t){e.Tools.Error("CustomProceduralTexture: Error on XHR send request.")}},i.prototype.isReady=function(){if(!t.prototype.isReady.call(this))return!1;for(var e in this._textures){if(!this._textures[e].isReady())return!1}return!0},i.prototype.render=function(e){var i=this.getScene();this._animate&&i&&(this._time+=.03*i.getAnimationRatio(),this.updateShaderUniforms()),t.prototype.render.call(this,e)},i.prototype.updateTextures=function(){for(var t=0;t.005?0+r:0,i.y=Math.abs(n)>.005?0+n:0;var o=this.gamepad.rightStick;if(o){var s=o.x/this.gamepadAngularSensibility,a=o.y/this.gamepadAngularSensibility;o.x=Math.abs(s)>.001?0+s:0,o.y=Math.abs(a)>.001?0+a:0}else o={x:0,y:0};t.rotationQuaternion?t.rotationQuaternion.toRotationMatrix(this._cameraTransform):e.Matrix.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,0,this._cameraTransform);var l=50*t._computeLocalCameraSpeed();this._vector3.copyFromFloats(i.x*l,0,-i.y*l),e.Vector3.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),t.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(o.y,o.x),t.cameraRotation.addInPlace(this._vector2)}},t.prototype.getClassName=function(){return"FreeCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},n([e.serialize()],t.prototype,"gamepadAngularSensibility",void 0),n([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.FreeCameraGamepadInput=t,e.CameraInputTypes.FreeCameraGamepadInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40}return t.prototype.attachControl=function(t,i){var r=this,n=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=n.onGamepadConnectedObservable.add((function(t){t.type!==e.Gamepad.POSE_ENABLED&&(r.gamepad&&t.type!==e.Gamepad.XBOX||(r.gamepad=t))})),this._onGamepadDisconnectedObserver=n.onGamepadDisconnectedObservable.add((function(e){r.gamepad===e&&(r.gamepad=null)})),this.gamepad=n.getGamepadByType(e.Gamepad.XBOX)},t.prototype.detachControl=function(e){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null},t.prototype.checkInputs=function(){if(this.gamepad){var e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){var i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){var r=t.y/this.gamepadRotationSensibility;0!=r&&Math.abs(r)>.005&&(e.inertialBetaOffset+=r)}}var n=this.gamepad.leftStick;if(n&&0!=n.y){var o=n.y/this.gamepadMoveSensibility;0!=o&&Math.abs(o)>.005&&(this.camera.inertialRadiusOffset-=o)}}},t.prototype.getClassName=function(){return"ArcRotateCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},n([e.serialize()],t.prototype,"gamepadRotationSensibility",void 0),n([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.ArcRotateCameraGamepadInput=t,e.CameraInputTypes.ArcRotateCameraGamepadInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){var i=this;this._scene=t,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new e.Observable,e.Tools.IsWindowObjectExist()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator.getGamepads||navigator.webkitGetGamepads||navigator.msGetGamepads||navigator.webkitGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new e.Observable(function(e){for(var t in i._babylonGamepads){var r=i._babylonGamepads[t];r&&r._isConnected&&i.onGamepadConnectedObservable.notifyObserver(e,r)}}),this._onGamepadConnectedEvent=function(e){var t=e.gamepad;if(!(t.index in i._babylonGamepads&&i._babylonGamepads[t.index].isConnected)){var r;i._babylonGamepads[t.index]?(r=i._babylonGamepads[t.index],r.browserGamepad=t,r._isConnected=!0):r=i._addNewGamepad(t),i.onGamepadConnectedObservable.notifyObservers(r),i._startMonitoringGamepads()}},this._onGamepadDisconnectedEvent=function(e){var t=e.gamepad;for(var r in i._babylonGamepads)if(i._babylonGamepads[r].index===t.index){var n=i._babylonGamepads[r];n._isConnected=!1,i.onGamepadDisconnectedObservable.notifyObservers(n);break}},this._gamepadSupport&&(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported?(window.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1)):this._startMonitoringGamepads())}return Object.defineProperty(t.prototype,"gamepads",{get:function(){return this._babylonGamepads},enumerable:!0,configurable:!0}),t.prototype.getGamepadByType=function(t){void 0===t&&(t=e.Gamepad.XBOX);for(var i=0,r=this._babylonGamepads;i=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}return Object.defineProperty(e.prototype,"isConnected",{get:function(){return this._isConnected},enumerable:!0,configurable:!0}),e.prototype.onleftstickchanged=function(e){this._onleftstickchanged=e},e.prototype.onrightstickchanged=function(e){this._onrightstickchanged=e},Object.defineProperty(e.prototype,"leftStick",{get:function(){return this._leftStick},set:function(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightStick",{get:function(){return this._rightStick},set:function(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e},enumerable:!0,configurable:!0}),e.prototype.update=function(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})},e.prototype.dispose=function(){},e.GAMEPAD=0,e.GENERIC=1,e.XBOX=2,e.POSE_ENABLED=3,e})();e.Gamepad=i;var r=(function(t){function r(r,n,o){var s=t.call(this,r,n,o)||this;return s.onButtonDownObservable=new e.Observable,s.onButtonUpObservable=new e.Observable,s.type=i.GENERIC,s._buttons=new Array(o.buttons.length),s}return o(r,t),r.prototype.onbuttondown=function(e){this._onbuttondown=e},r.prototype.onbuttonup=function(e){this._onbuttonup=e},r.prototype._setButtonValue=function(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},r.prototype.update=function(){t.prototype.update.call(this);for(var e=0;ethis._maxRotationDistFromHeadset){var n=r-(r<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=n;var o=Math.sin(-n),s=Math.cos(-n);this._calculatedPosition.x=this._calculatedPosition.x*s-this._calculatedPosition.z*o,this._calculatedPosition.z=this._calculatedPosition.x*o+this._calculatedPosition.z*s}}},i.prototype.initControllerMesh=function(t,r){var n=this;e.SceneLoader.ImportMesh("",i.MODEL_BASE_URL,i.MODEL_FILENAME,t,(function(i){var o=new e.Mesh("",t);i[1].parent=o,i[1].position.z=-.15,n._defaultModel=o,n.attachToMesh(n._defaultModel),r&&r(n._defaultModel)}))},i.prototype._handleButtonChange=function(e,t,i){if(ethis.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),(f>this.maxCameraSpeed||f<-this.maxCameraSpeed)&&(f=f<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new e.Vector3(this.position.x+u,this.position.y+d,this.position.z+f),this.setTarget(o)}},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.lockedTarget&&this.follow(this.lockedTarget)},i.prototype.getClassName=function(){return"FollowCamera"},n([e.serialize()],i.prototype,"radius",void 0),n([e.serialize()],i.prototype,"rotationOffset",void 0),n([e.serialize()],i.prototype,"heightOffset",void 0),n([e.serialize()],i.prototype,"cameraAcceleration",void 0),n([e.serialize()],i.prototype,"maxCameraSpeed",void 0),n([e.serializeAsMeshReference("lockedTargetId")],i.prototype,"lockedTarget",void 0),i})(e.TargetCamera);e.FollowCamera=t;var i=(function(t){function i(i,r,n,o,s,a){var l=t.call(this,i,e.Vector3.Zero(),a)||this;return l.alpha=r,l.beta=n,l.radius=o,l.target=s,l._cartesianCoordinates=e.Vector3.Zero(),l.follow(),l}return o(i,t),i.prototype.follow=function(){if(this.target){this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);var e=this.target.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.follow()},i.prototype.getClassName=function(){return"ArcFollowCamera"},i})(e.TargetCamera);e.ArcFollowCamera=i})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addGamepad(),n}return o(t,e),Object.defineProperty(t.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"UniversalCamera"},t})(e.TouchCamera);e.UniversalCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("GamepadCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(e){function t(t,i,r){return e.call(this,t,i,r)||this}return o(t,e),Object.defineProperty(t.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"GamepadCamera"},t})(e.UniversalCamera);e.GamepadCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this._renderPipelines={}}return e.prototype.addPipeline=function(e){this._renderPipelines[e._name]=e},e.prototype.attachCamerasToRenderPipeline=function(e,t,i){void 0===i&&(i=!1);var r=this._renderPipelines[e];r&&r._attachCameras(t,i)},e.prototype.detachCamerasFromRenderPipeline=function(e,t){var i=this._renderPipelines[e];i&&i._detachCameras(t)},e.prototype.enableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._enableEffect(t,i)},e.prototype.disableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._disableEffect(t,i)},e.prototype.update=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}},e.prototype._rebuild=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t._rebuild()}},e.prototype.dispose=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t.dispose()}},e})();e.PostProcessRenderPipelineManager=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}return Object.defineProperty(t.prototype,"isSupported",{get:function(){for(var e in this._postProcesses)if(this._postProcesses.hasOwnProperty(e))for(var t=this._postProcesses[e],i=0;i=2&&t.length>0){var i=this._renderEffects[t[0]].getPostProcesses();if(i)return i[0].samples=e,!0}return!1},t.prototype.dispose=function(){},n([e.serialize()],t.prototype,"_name",void 0),t})();e.PostProcessRenderPipeline=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){void 0===i&&(i=e.Engine.TEXTURETYPE_FLOAT),void 0===r&&(r=null);var n=this;this._scene=t,this._camera=r;var o=t.getEngine();this._depthMap=new e.RenderTargetTexture("depthMap",{width:o.getRenderWidth(),height:o.getRenderHeight()},this._scene,!1,!0,i),this._depthMap.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._depthMap.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((function(t){t.clear(new e.Color4(1,1,1,1),!0,!0,!0)}));var s=function(t){var i=t.getRenderingMesh(),r=n._scene,o=r.getEngine(),s=t.getMaterial();if(s){o.setState(s.backFaceCulling,0,!1,r.useRightHandedSystem);var a=i._getInstancesRenderList(t._id);if(!a.mustReturn){var l=o.getCaps().instancedArrays&&null!==a.visibleInstances[t._id],c=n._camera||r.activeCamera;if(n.isReady(t,l)&&c){if(o.enableEffect(n._effect),i._bind(t,n._effect,e.Material.TriangleFillMode),n._effect.setMatrix("viewProjection",r.getTransformMatrix()),n._effect.setFloat2("depthValues",c.minZ,c.minZ+c.maxZ),s&&s.needAlphaTesting()){var h=s.getAlphaTestTexture();h&&(n._effect.setTexture("diffuseSampler",h),n._effect.setMatrix("diffuseMatrix",h.getTextureMatrix()))}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&n._effect.setMatrices("mBones",i.skeleton.getTransformMatrices(i)),i._processRendering(t,n._effect,e.Material.TriangleFillMode,a,l,(function(e,t){return n._effect.setMatrix("world",t)}))}}}};this._depthMap.customRenderFunction=function(e,t,i,r){var n;if(r.length){for(o.setColorWrite(!1),n=0;n4&&(o.push(e.VertexBuffer.MatricesIndicesExtraKind),o.push(e.VertexBuffer.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("depth",o,["world","mBones","viewProjection","diffuseMatrix","depthValues"],["diffuseSampler"],a)),this._effect.isReady()},t.prototype.getDepthMap=function(){return this._depthMap},t.prototype.dispose=function(){this._depthMap.dispose()},t})();e.DepthRenderer=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o){var s=t.call(this,r.getEngine(),i)||this;s.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",s.SSAORenderEffect="SSAORenderEffect",s.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",s.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",s.SSAOCombineRenderEffect="SSAOCombineRenderEffect",s.totalStrength=1,s.radius=1e-4,s.area=.0075,s.fallOff=1e-6,s.base=.5,s._firstUpdate=!0,s._scene=r,s._createRandomTexture(),s._depthTexture=r.enableDepthRenderer().getDepthMap();var a=n.ssaoRatio||n,l=n.combineRatio||n;return s._originalColorPostProcess=new e.PassPostProcess("SSAOOriginalSceneColor",l,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),!1),s._createSSAOPostProcess(a),s._createBlurPostProcess(a),s._createSSAOCombinePostProcess(l),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOOriginalSceneColorEffect,function(){return s._originalColorPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAORenderEffect,function(){return s._ssaoPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOBlurHRenderEffect,function(){return s._blurHPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOBlurVRenderEffect,function(){return s._blurVPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOCombineRenderEffect,function(){return s._ssaoCombinePostProcess},!0)),r.postProcessRenderPipelineManager.addPipeline(s),o&&r.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(i,o),s}return o(i,t),i.prototype.dispose=function(e){void 0===e&&(e=!1);for(var i=0;i0?r._ssaoCombinePostProcess.width:r._originalColorPostProcess.width),e.setFloat("near",r._scene.activeCamera.minZ),e.setFloat("far",r._scene.activeCamera.maxZ),e.setFloat("radius",r.radius),e.setTexture("depthSampler",r._depthTexture),r._firstUpdate&&e.setArray("samplerOffsets",r._samplerOffsets))},this._blurVPostProcess=new e.PostProcess("BlurV","ssao2",["outSize","samplerOffsets","near","far","radius"],["depthSampler"],i,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE "+(n?"1":"0")+"\n"),this._blurVPostProcess.onApply=function(e){r._scene.activeCamera&&(e.setFloat("outSize",r._ssaoCombinePostProcess.height>0?r._ssaoCombinePostProcess.height:r._originalColorPostProcess.height),e.setFloat("near",r._scene.activeCamera.minZ),e.setFloat("far",r._scene.activeCamera.maxZ),e.setFloat("radius",r.radius),e.setTexture("depthSampler",r._depthTexture),r._firstUpdate&&(e.setArray("samplerOffsets",r._samplerOffsets),r._firstUpdate=!1))}},i.prototype._rebuild=function(){this._firstUpdate=!0,t.prototype._rebuild.call(this)},i.prototype._generateHemisphere=function(){for(var t,i,r=this.samples,n=[],o=function(e,t){return Math.random()*(t-e)+e},s=0;s=0;a--){var o=Math.pow(3,a),l="#define LUMINANCE_DOWN_SAMPLE\n";0===a&&(l+="#define FINAL_DOWN_SAMPLER");var c=new e.PostProcess("HDRLuminanceDownSample"+a,"standard",["dsOffsets","halfDestPixelSize"],[],{width:o,height:o},null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,l,r);this.luminanceDownSamplePostProcesses.push(c)}var h=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((function(i,r){var o=new Array(18);i.onApply=function(e){if(h){for(var t=0,s=-1;s<2;s++)for(var a=-1;a<2;a++)o[t]=s/h.width,o[t+1]=a/h.height,t+=2;e.setArray2("dsOffsets",o),e.setFloat("halfDestPixelSize",.5/h.width),h=r===n.luminanceDownSamplePostProcesses.length-1?n.luminancePostProcess:i}},r===n.luminanceDownSamplePostProcesses.length-1&&(i.onAfterRender=function(i){var r=t.getEngine().readPixels(0,0,1,1),o=new e.Vector4(1/16581375,1/65025,1/255,1);n._hdrCurrentLuminance=(r[0]*o.x+r[1]*o.y+r[2]*o.z+r[3]*o.w)/100}),n.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLuminanceDownSample"+r,function(){return i},!0))}))},i.prototype._createHdrPostProcess=function(t,i){var r=this;this.hdrPostProcess=new e.PostProcess("HDR","standard",["averageLuminance"],["textureAdderSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define HDR",e.Engine.TEXTURETYPE_UNSIGNED_INT);var n=1,o=0,s=0;this.hdrPostProcess.onApply=function(i){if(i.setTextureFromPostProcess("textureAdderSampler",r._currentDepthOfFieldSource),o+=t.getEngine().getDeltaTime(),n<0)n=r._hdrCurrentLuminance;else{var a=(s-o)/1e3;r._hdrCurrentLuminancen-r.hdrIncreaseRate*a?n-=r.hdrIncreaseRate*a:n=r._hdrCurrentLuminance}n=e.Scalar.Clamp(n,r.hdrMinimumLuminance,1e20),i.setFloat("averageLuminance",n),s=o,r._currentDepthOfFieldSource=r.hdrFinalPostProcess},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDR",function(){return r.hdrPostProcess},!0))},i.prototype._createLensFlarePostProcess=function(t,i){var r=this;this.lensFlarePostProcess=new e.PostProcess("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],i/2,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define LENS_FLARE",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLensFlare",function(){return r.lensFlarePostProcess},!0)),this._createBlurPostProcesses(t,i/4,2),this.lensFlareComposePostProcess=new e.PostProcess("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define LENS_FLARE_COMPOSE",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLensFlareCompose",function(){return r.lensFlareComposePostProcess},!0));var n=new e.Vector2(0,0);this.lensFlarePostProcess.onApply=function(e){e.setTextureFromPostProcess("textureSampler",r._bloomEnabled?r.blurHPostProcesses[0]:r.originalPostProcess),e.setTexture("lensColorSampler",r.lensColorTexture),e.setFloat("strength",r.lensFlareStrength),e.setFloat("ghostDispersal",r.lensFlareGhostDispersal),e.setFloat("haloWidth",r.lensFlareHaloWidth),n.x=r.lensFlarePostProcess.width,n.y=r.lensFlarePostProcess.height,e.setVector2("resolution",n),e.setFloat("distortionStrength",r.lensFlareDistortionStrength)};var o=e.Matrix.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=e.Matrix.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=function(t){if(r._scene.activeCamera){t.setTextureFromPostProcess("otherSampler",r._currentDepthOfFieldSource),t.setTexture("lensDirtSampler",r.lensFlareDirtTexture),t.setTexture("lensStarSampler",r.lensStarTexture);var i=r._scene.activeCamera.getViewMatrix().getRow(0),n=r._scene.activeCamera.getViewMatrix().getRow(2),a=e.Vector3.Dot(i.toVector3(),new e.Vector3(1,0,0))+e.Vector3.Dot(n.toVector3(),new e.Vector3(0,0,1));a*=4;var l=e.Matrix.FromValues(.5*Math.cos(a),-Math.sin(a),0,0,Math.sin(a),.5*Math.cos(a),0,0,0,0,1,0,0,0,0,1),c=s.multiply(l).multiply(o);t.setMatrix("lensStarMatrix",c),r._currentDepthOfFieldSource=r.lensFlareFinalPostProcess}}},i.prototype._createDepthOfFieldPostProcess=function(t,i){var r=this;this.depthOfFieldPostProcess=new e.PostProcess("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define DEPTH_OF_FIELD",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.depthOfFieldPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",r._currentDepthOfFieldSource),e.setTexture("depthSampler",r._getDepthTexture()),e.setFloat("distance",r.depthOfFieldDistance)},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRDepthOfField",function(){return r.depthOfFieldPostProcess},!0))},i.prototype._createMotionBlurPostProcess=function(t,i){var r=this;this.motionBlurPostProcess=new e.PostProcess("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),e.Engine.TEXTURETYPE_UNSIGNED_INT);var n=0,o=e.Matrix.Identity(),s=e.Matrix.Identity(),a=e.Matrix.Identity(),l=e.Vector2.Zero();this.motionBlurPostProcess.onApply=function(e){a=t.getProjectionMatrix().multiply(t.getViewMatrix()),a.invertToRef(s),e.setMatrix("inverseViewProjection",s),e.setMatrix("prevViewProjection",o),o=a,l.x=r.motionBlurPostProcess.width,l.y=r.motionBlurPostProcess.height,e.setVector2("screenSize",l),n=t.getEngine().getFps()/60,e.setFloat("motionScale",n),e.setFloat("motionStrength",r.motionStrength),e.setTexture("depthSampler",r._getDepthTexture())},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRMotionBlur",function(){return r.motionBlurPostProcess},!0))},i.prototype._getDepthTexture=function(){if(this._scene.getEngine().getCaps().drawBuffersExtension){return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]}return this._scene.enableDepthRenderer().getDepthMap()},i.prototype._disposePostProcesses=function(){for(var e=0;e-1?"#define MALI 1\n":null},i})(e.PostProcess);e.FxaaPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c,h,u){void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===u&&(u=!1);var d=t.call(this,i,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],o,s,a,l,c,null,h,void 0,null,u)||this;return d.aberrationAmount=30,d.radialIntensity=0,d.direction=new e.Vector2(.707,.707),d.centerPosition=new e.Vector2(.5,.5),d.onApplyObservable.add((function(e){e.setFloat("chromatic_aberration",d.aberrationAmount),e.setFloat("screen_width",r),e.setFloat("screen_height",n),e.setFloat("radialIntensity",d.radialIntensity),e.setFloat2("direction",d.direction.x,d.direction.y),e.setFloat2("centerPosition",d.centerPosition.x,d.centerPosition.y)})),d}return o(i,t),i})(e.PostProcess);e.ChromaticAberrationPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c){void 0===l&&(l=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var h=t.call(this,i,"grain",["intensity","animatedSeed"],[],r,n,o,s,a,null,l,void 0,null,c)||this;return h.intensity=30,h.animated=!1,h.onApplyObservable.add((function(e){e.setFloat("intensity",h.intensity),e.setFloat("animatedSeed",h.animated?Math.random()+1:1)})),h}return o(i,t),i})(e.PostProcess);e.GrainPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c){void 0===l&&(l=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var h=t.call(this,i,"sharpen",["sharpnessAmounts","screenSize"],null,r,n,o,s,a,null,l,void 0,null,c)||this;return h.colorAmount=1,h.edgeAmount=.3,h.onApply=function(e){e.setFloat2("screenSize",h.width,h.height),e.setFloat2("sharpnessAmounts",h.edgeAmount,h.colorAmount)},h}return o(i,t),i})(e.PostProcess);e.SharpenPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c,h,u,d){void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===u&&(u=""),void 0===d&&(d=!1);var f=t.call(this,i,"kernelBlur",["delta","direction","cameraMinMaxZ"],["circleOfConfusionSampler"],o,s,a,l,c,null,h,"kernelBlur",{varyingCount:0,depCount:0},!0)||this;return f.direction=r,f.blockCompilation=d,f._packedFloat=!1,f._staticDefines="",f._staticDefines=u,f.onApplyObservable.add((function(e){f._outputTexture?e.setFloat2("delta",1/f._outputTexture.width*f.direction.x,1/f._outputTexture.height*f.direction.y):e.setFloat2("delta",1/f.width*f.direction.x,1/f.height*f.direction.y)})),f.kernel=n,f}return o(i,t),Object.defineProperty(i.prototype,"kernel",{get:function(){return this._idealKernel},set:function(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.blockCompilation||this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"packedFloat",{get:function(){return this._packedFloat},set:function(e){this._packedFloat!==e&&(this._packedFloat=e,this.blockCompilation||this._updateParameters())},enumerable:!0,configurable:!0}),i.prototype.updateEffect=function(e,t,i,r,n,o){void 0===e&&(e=null),void 0===t&&(t=null),void 0===i&&(i=null),this._updateParameters(n,o)},i.prototype._updateParameters=function(e,i){for(var r=this._kernel,n=(r-1)/2,o=[],s=[],a=0,l=0;l0)return Math.max(n,3)}return Math.max(t,3)},i.prototype._gaussianWeight=function(e){var t=Math.sqrt(2*Math.PI)*(1/3),i=-e*e/(1/3*2*(1/3));return 1/t*Math.exp(i)},i.prototype._glslFloat=function(e,t){return void 0===t&&(t=8),e.toFixed(t).replace(/0+$/,"")},i})(e.PostProcess);e.BlurPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c,h,u,d,f,p){void 0===c&&(c=null),void 0===h&&(h=e.Texture.BILINEAR_SAMPLINGMODE),void 0===f&&(f=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===p&&(p=!1);var _=t.call(this,i,n,o,s,a,h=e.Texture.BILINEAR_SAMPLINGMODE,u,d,f=e.Engine.TEXTURETYPE_UNSIGNED_INT,"#define DOF 1\r\n",p)||this;return _.direction=n,_.onApplyObservable.add((function(e){null!=c&&e.setTextureFromPostProcess("textureSampler",c),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",l),r.activeCamera&&e.setFloat2("cameraMinMaxZ",r.activeCamera.minZ,r.activeCamera.maxZ)})),_}return o(i,t),i})(e.BlurPostProcess);e.DepthOfFieldBlurPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){}return e})();e.DepthOfFieldMergePostProcessOptions=t;var i=(function(t){function i(i,r,n,o,s,a,l,c,h,u,d){void 0===u&&(u=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===d&&(d=!1);var f=t.call(this,i,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,a,l,c,h,null,u,void 0,null,!0)||this;return f.blurSteps=o,f.onApplyObservable.add((function(e){e.setTextureFromPostProcess("textureSampler",r),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",n),o.forEach((function(t,i){e.setTextureFromPostProcessOutput("blurStep"+(o.length-i-1),t)}))})),d||f.updateEffect(),f}return o(i,t),i.prototype.updateEffect=function(e,i,r,n,o,s){void 0===e&&(e=null),void 0===i&&(i=null),void 0===r&&(r=null),e||(e="",e+="#define BLUR_LEVEL "+(this.blurSteps.length-1)+"\n"),t.prototype.updateEffect.call(this,e,i,r,n,o,s)},i})(e.PostProcess);e.DepthOfFieldMergePostProcess=i})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c,h){void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1);var u=t.call(this,i,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],n,o,s,a,l,null,c,void 0,null,h)||this;return u.lensSize=50,u.fStop=1.4,u.focusDistance=2e3,u.focalLength=50,u._depthTexture=null,u._depthTexture=r,u.onApplyObservable.add((function(t){if(!u._depthTexture)return void e.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");t.setTexture("depthSampler",u._depthTexture);var i=u.lensSize/u.fStop,r=i*u.focalLength/(u.focusDistance-u.focalLength);t.setFloat("focusDistance",u.focusDistance),t.setFloat("cocPrecalculation",r),t.setFloat2("cameraMinMaxZ",u._depthTexture.activeCamera.minZ,u._depthTexture.activeCamera.maxZ)})),u}return o(i,t),Object.defineProperty(i.prototype,"depthTexture",{set:function(e){this._depthTexture=e},enumerable:!0,configurable:!0}),i})(e.PostProcess);e.CircleOfConfusionPostProcess=t})(r||(r={}));var r;!(function(e){var t;!(function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"})(t=e.DepthOfFieldEffectBlurLevel||(e.DepthOfFieldEffectBlurLevel={}));var i=(function(i){function r(r,n,o,s,a){void 0===o&&(o=t.Low),void 0===s&&(s=0),void 0===a&&(a=!1);var l=i.call(this,r.getEngine(),"depth of field",(function(){return l._effects}),!0)||this;l._effects=[],l._circleOfConfusion=new e.CircleOfConfusionPostProcess("circleOfConfusion",n,1,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),!1,s,a),l._depthOfFieldBlurY=[],l._depthOfFieldBlurX=[];var c=1,h=15;switch(o){case t.High:c=3,h=51;break;case t.Medium:c=2,h=31;break;default:h=15,c=1}for(var u=h/Math.pow(2,c-1),d=1,f=0;f1&&e.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}},i.prototype._disposePostProcesses=function(e){void 0===e&&(e=!1);for(var t=0;t4&&(o.push(e.VertexBuffer.MatricesIndicesExtraKind),o.push(e.VertexBuffer.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("geometry",o,["world","mBones","viewProjection","diffuseMatrix","view"],["diffuseSampler"],a,void 0,void 0,void 0,{buffersCount:this._enablePosition?3:2})),this._effect.isReady()},t.prototype.getGBuffer=function(){return this._multiRenderTarget},Object.defineProperty(t.prototype,"samples",{get:function(){return this._multiRenderTarget.samples},set:function(e){this._multiRenderTarget.samples=e},enumerable:!0, -configurable:!0}),t.prototype.dispose=function(){this.getGBuffer().dispose()},t.prototype._createRenderTargets=function(){var t=this,i=this._scene.getEngine(),r=this._enablePosition?3:2;if(this._multiRenderTarget=new e.MultiRenderTarget("gBuffer",{width:i.getRenderWidth()*this._ratio,height:i.getRenderHeight()*this._ratio},r,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:e.Engine.TEXTURETYPE_FLOAT}),this.isSupported){this._multiRenderTarget.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null,this._multiRenderTarget.onClearObservable.add((function(t){t.clear(new e.Color4(0,0,0,1),!0,!0,!0)}));var n=function(i){var r=i.getRenderingMesh(),n=t._scene,o=n.getEngine(),s=i.getMaterial();if(s){o.setState(s.backFaceCulling,0,!1,n.useRightHandedSystem);var a=r._getInstancesRenderList(i._id);if(!a.mustReturn){var l=o.getCaps().instancedArrays&&null!==a.visibleInstances[i._id];if(t.isReady(i,l)){if(o.enableEffect(t._effect),r._bind(i,t._effect,e.Material.TriangleFillMode),t._effect.setMatrix("viewProjection",n.getTransformMatrix()),t._effect.setMatrix("view",n.getViewMatrix()),s&&s.needAlphaTesting()){var c=s.getAlphaTestTexture();c&&(t._effect.setTexture("diffuseSampler",c),t._effect.setMatrix("diffuseMatrix",c.getTextureMatrix()))}r.useBones&&r.computeBonesUsingShaders&&r.skeleton&&t._effect.setMatrices("mBones",r.skeleton.getTransformMatrices(r)),r._processRendering(i,t._effect,e.Material.TriangleFillMode,a,l,(function(e,i){return t._effect.setMatrix("world",i)}))}}}};this._multiRenderTarget.customRenderFunction=function(e,t,r,o){var s;if(o.length){for(i.setColorWrite(!1),s=0;s1,n.wrapU=e.Texture.CLAMP_ADDRESSMODE,n.wrapV=e.Texture.CLAMP_ADDRESSMODE,n.wrapR=e.Texture.CLAMP_ADDRESSMODE,n.anisotropicFilteringLevel=1,n._texture=n._getFromCache(i,!0),n._texture||(r.useDelayedTextureLoading?n.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED:n.loadTexture()),n):n}return o(i,t),i.prototype.getTextureMatrix=function(){return this._textureMatrix},i.prototype.load3dlTexture=function(){var t,r=this._engine;t=1===r.webGLVersion?r.createRawTexture(null,1,1,e.Engine.TEXTUREFORMAT_RGBA,!1,!1,e.Texture.BILINEAR_SAMPLINGMODE):r.createRawTexture3D(null,1,1,1,e.Engine.TEXTUREFORMAT_RGBA,!1,!1,e.Texture.BILINEAR_SAMPLINGMODE),this._texture=t;var n=function(n){if("string"==typeof n){for(var o,s=null,a=null,l=n.split("\n"),c=0,h=0,u=0,d=0,f=0,p=0;p0&&(p+1)%4==0)s[p]=255;else{var b=a[p];s[p]=b/f*255}t.is3D?(t.updateSize(c,c,c),r.updateRawTexture3D(t,s,e.Engine.TEXTUREFORMAT_RGBA,!1)):(t.updateSize(c*c,c),r.updateRawTexture(t,s,e.Engine.TEXTUREFORMAT_RGBA,!1))}},o=this.getScene();return o?o._loadFile(this.url,n):this._engine._loadFile(this.url,n),this._texture},i.prototype.loadTexture=function(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this.load3dlTexture()},i.prototype.clone=function(){var e=new i(this.url,this.getScene());return e.level=this.level,e},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,!0),this._texture||this.loadTexture())},i.Parse=function(e,t,r){var n=null;return e.name&&!e.isRenderTarget&&(n=new i(e.name,t),n.name=e.name,n.level=e.level),n},i.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e},i._noneEmptyLineRegex=/\S+/,i})(e.BaseTexture);e.ColorGradingTexture=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._dirty=!0,this._tempColor=new e.Color4(0,0,0,0),this._globalCurve=new e.Color4(0,0,0,0),this._highlightsCurve=new e.Color4(0,0,0,0),this._midtonesCurve=new e.Color4(0,0,0,0),this._shadowsCurve=new e.Color4(0,0,0,0),this._positiveCurve=new e.Color4(0,0,0,0),this._negativeCurve=new e.Color4(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}return Object.defineProperty(t.prototype,"globalHue",{get:function(){return this._globalHue},set:function(e){this._globalHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalDensity",{get:function(){return this._globalDensity},set:function(e){this._globalDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalSaturation",{get:function(){return this._globalSaturation},set:function(e){this._globalSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalExposure",{get:function(){return this._globalExposure},set:function(e){this._globalExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsHue",{get:function(){return this._highlightsHue},set:function(e){this._highlightsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsDensity",{get:function(){return this._highlightsDensity},set:function(e){this._highlightsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsSaturation",{get:function(){return this._highlightsSaturation},set:function(e){this._highlightsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsExposure",{get:function(){return this._highlightsExposure},set:function(e){this._highlightsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesHue",{get:function(){return this._midtonesHue},set:function(e){this._midtonesHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesDensity",{get:function(){return this._midtonesDensity},set:function(e){this._midtonesDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesSaturation",{get:function(){return this._midtonesSaturation},set:function(e){this._midtonesSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesExposure",{get:function(){return this._midtonesExposure},set:function(e){this._midtonesExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsHue",{get:function(){return this._shadowsHue},set:function(e){this._shadowsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsDensity",{get:function(){return this._shadowsDensity},set:function(e){this._shadowsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsSaturation",{get:function(){return this._shadowsSaturation},set:function(e){this._shadowsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsExposure",{get:function(){return this._shadowsExposure},set:function(e){this._shadowsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"ColorCurves"},t.Bind=function(e,t,i,r,n){void 0===i&&(i="vCameraColorCurvePositive"),void 0===r&&(r="vCameraColorCurveNeutral"),void 0===n&&(n="vCameraColorCurveNegative"),e._dirty&&(e._dirty=!1,e.getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e.getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e.getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e.getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(n,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))},t.PrepareUniforms=function(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")},t.prototype.getColorGradingDataToRef=function(e,i,r,n,o){null!=e&&(e=t.clamp(e,0,360),i=t.clamp(i,-100,100),r=t.clamp(r,-100,100),n=t.clamp(n,-100,100),i=t.applyColorGradingSliderNonlinear(i),i*=.5,n=t.applyColorGradingSliderNonlinear(n),i<0&&(i*=-1,e=(e+180)%360),t.fromHSBToRef(e,i,50+.25*n,o),o.scaleToRef(2,o),o.a=1+.01*r)},t.applyColorGradingSliderNonlinear=function(e){e/=100;var t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100},t.fromHSBToRef=function(e,i,r,n){var o=t.clamp(e,0,360),s=t.clamp(i/100,0,1),a=t.clamp(r/100,0,1);if(0===s)n.r=a,n.g=a,n.b=a;else{o/=60;var l=Math.floor(o),c=o-l,h=a*(1-s),u=a*(1-s*c),d=a*(1-s*(1-c));switch(l){case 0:n.r=a,n.g=d,n.b=h;break;case 1:n.r=u,n.g=a,n.b=h;break;case 2:n.r=h,n.g=a,n.b=d;break;case 3:n.r=h,n.g=u,n.b=a;break;case 4:n.r=d,n.g=h,n.b=a;break;default:n.r=a,n.g=h,n.b=u}}n.a=1},t.clamp=function(e,t,i){return Math.min(Math.max(e,t),i)},t.prototype.clone=function(){return e.SerializationHelper.Clone((function(){return new t}),this)},t.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},t.Parse=function(i){return e.SerializationHelper.Parse((function(){return new t}),i,null,null)},n([e.serialize()],t.prototype,"_globalHue",void 0),n([e.serialize()],t.prototype,"_globalDensity",void 0),n([e.serialize()],t.prototype,"_globalSaturation",void 0),n([e.serialize()],t.prototype,"_globalExposure",void 0),n([e.serialize()],t.prototype,"_highlightsHue",void 0),n([e.serialize()],t.prototype,"_highlightsDensity",void 0),n([e.serialize()],t.prototype,"_highlightsSaturation",void 0),n([e.serialize()],t.prototype,"_highlightsExposure",void 0),n([e.serialize()],t.prototype,"_midtonesHue",void 0),n([e.serialize()],t.prototype,"_midtonesDensity",void 0),n([e.serialize()],t.prototype,"_midtonesSaturation",void 0),n([e.serialize()],t.prototype,"_midtonesExposure",void 0),t})();e.ColorCurves=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c,h,u){var d=t.call(this,i,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],a,l,c,h,u)||this;return d.color=n,d.depth=o,d.colorLevel=s,d._ownRefractionTexture=!0,d.onActivateObservable.add((function(t){d._refTexture=d._refTexture||new e.Texture(r,t.getScene())})),d.onApplyObservable.add((function(e){e.setColor3("baseColor",d.color),e.setFloat("depth",d.depth),e.setFloat("colorLevel",d.colorLevel),e.setTexture("refractionSampler",d._refTexture)})),d}return o(i,t),Object.defineProperty(i.prototype,"refractionTexture",{get:function(){return this._refTexture},set:function(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1},enumerable:!0,configurable:!0}),i.prototype.dispose=function(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),t.prototype.dispose.call(this,e)},i})(e.PostProcess);e.RefractionPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){var a=e.call(this,t,"blackAndWhite",["degree"],null,i,r,n,o,s)||this;return a.degree=1,a.onApplyObservable.add((function(e){e.setFloat("degree",a.degree)})),a}return o(t,e),t})(e.PostProcess);e.BlackAndWhitePostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c){void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT);var h=t.call(this,i,"convolution",["kernel","screenSize"],null,n,o,s,a,l,null,c)||this;return h.kernel=r,h.onApply=function(e){e.setFloat2("screenSize",h.width,h.height),e.setArray("kernel",h.kernel)},h}return o(i,t),i.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],i.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],i.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],i.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],i.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],i.GaussianKernel=[0,1,0,1,1,1,0,1,0],i})(e.PostProcess);e.ConvolutionPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i,r,n,o,s,a){var l=e.call(this,t,"filter",["kernelMatrix"],null,r,n,o,s,a)||this;return l.kernelMatrix=i,l.onApply=function(e){e.setMatrix("kernelMatrix",l.kernelMatrix)},l}return o(t,e),t})(e.PostProcess);e.FilterPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(r,n,o,s,a,l,c,h,u){void 0===a&&(a=100),void 0===l&&(l=e.Texture.BILINEAR_SAMPLINGMODE);var d=t.call(this,r,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],n.postProcessRatio||n,o,l,c,h,"#define NUM_SAMPLES "+a)||this;return d._screenCoordinates=e.Vector2.Zero(),d.customMeshPosition=e.Vector3.Zero(),d.useCustomMeshPosition=!1,d.invert=!0,d.excludedMeshes=new Array,d.exposure=.3,d.decay=.96815,d.weight=.58767,d.density=.926,u=null===o?u:o.getScene(),c=u.getEngine(),d._viewPort=new e.Viewport(0,0,1,1).toGlobal(c.getRenderWidth(),c.getRenderHeight()),d.mesh=null!==s?s:i.CreateDefaultMesh("VolumetricLightScatteringMesh",u),d._createPass(u,n.passRatio||n),d.onActivate=function(e){d.isSupported||d.dispose(e),d.onActivate=null},d.onApplyObservable.add((function(e){d._updateMeshScreenCoordinates(u),e.setTexture("lightScatteringSampler",d._volumetricLightScatteringRTT),e.setFloat("exposure",d.exposure),e.setFloat("decay",d.decay),e.setFloat("weight",d.weight),e.setFloat("density",d.density),e.setVector2("meshPositionOnScreen",d._screenCoordinates)})),d}return o(i,t),Object.defineProperty(i.prototype,"useDiffuseColor",{get:function(){return e.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1},set:function(t){e.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"VolumetricLightScatteringPostProcess"},i.prototype._isReady=function(t,i){var r=t.getMesh();if(r===this.mesh&&r.material)return r.material.isReady(r);var n=[],o=[e.VertexBuffer.PositionKind],s=t.getMaterial();s&&(s.needAlphaTesting()&&n.push("#define ALPHATEST"),r.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(o.push(e.VertexBuffer.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(o.push(e.VertexBuffer.UV2Kind),n.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(o.push(e.VertexBuffer.MatricesIndicesKind),o.push(e.VertexBuffer.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._volumetricLightScatteringPass=r.getScene().getEngine().createEffect({vertexElement:"depth",fragmentElement:"volumetricLightScatteringPass"},o,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],a)),this._volumetricLightScatteringPass.isReady()},i.prototype.setCustomMeshPosition=function(e){this.customMeshPosition=e},i.prototype.getCustomMeshPosition=function(){return this.customMeshPosition},i.prototype.dispose=function(e){var i=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==i&&e.getScene().customRenderTargets.splice(i,1),this._volumetricLightScatteringRTT.dispose(),t.prototype.dispose.call(this,e)},i.prototype.getPass=function(){return this._volumetricLightScatteringRTT},i.prototype._meshExcluded=function(e){return this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)},i.prototype._createPass=function(t,i){var r=this,n=t.getEngine();this._volumetricLightScatteringRTT=new e.RenderTargetTexture("volumetricLightScatteringMap",{width:n.getRenderWidth()*i,height:n.getRenderHeight()*i},t,!1,!0,e.Engine.TEXTURETYPE_UNSIGNED_INT),this._volumetricLightScatteringRTT.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;var o=this.getCamera();o?o.customRenderTargets.push(this._volumetricLightScatteringRTT):t.customRenderTargets.push(this._volumetricLightScatteringRTT);var s,a=function(t){var i=t.getRenderingMesh();if(!r._meshExcluded(i)){var n=t.getMaterial();if(n){var o=i.getScene(),s=o.getEngine();s.setState(n.backFaceCulling);var a=i._getInstancesRenderList(t._id);if(!a.mustReturn){var l=s.getCaps().instancedArrays&&null!==a.visibleInstances[t._id];if(r._isReady(t,l)){var c=r._volumetricLightScatteringPass;if(i===r.mesh&&(c=t.effect?t.effect:n.getEffect()),s.enableEffect(c),i._bind(t,c,e.Material.TriangleFillMode),i===r.mesh)n.bind(i.getWorldMatrix(),i);else{if(r._volumetricLightScatteringPass.setMatrix("viewProjection",o.getTransformMatrix()),n&&n.needAlphaTesting()){var h=n.getAlphaTestTexture();r._volumetricLightScatteringPass.setTexture("diffuseSampler",h),h&&r._volumetricLightScatteringPass.setMatrix("diffuseMatrix",h.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&r._volumetricLightScatteringPass.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}i._processRendering(t,r._volumetricLightScatteringPass,e.Material.TriangleFillMode,a,l,(function(e,t){return c.setMatrix("world",t)}))}}}}},l=new e.Color4(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((function(){s=t.clearColor,t.clearColor=l})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((function(){t.clearColor=s})),this._volumetricLightScatteringRTT.customRenderFunction=function(i,r,n,o){var s,l=t.getEngine();if(o.length){for(l.setColorWrite(!1),s=0;st._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0})),l.setAlphaMode(e.Engine.ALPHA_COMBINE),s=0;s=h&&a.frame<=u&&(n?(c=a.value.clone(),m?(l=c.getTranslation(),c.setTranslation(l.scaleInPlace(g))):v&&o?(l=c.getTranslation(),c.setTranslation(l.multiplyInPlace(o))):c=a.value):c=a.value,y.push({frame:a.frame+r,value:c}));return this.animations[0].createRange(i,h+r,u+r),!0},i.prototype.translate=function(t,r,n){void 0===r&&(r=e.Space.LOCAL);var o=this.getLocalMatrix();if(r==e.Space.LOCAL)o.m[12]+=t.x,o.m[13]+=t.y,o.m[14]+=t.z;else{var s=null;n&&(s=n.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var a=i._tmpMats[0],l=i._tmpVecs[0];this._parent&&(n&&s?(a.copyFrom(this._parent.getAbsoluteTransform()),a.multiplyToRef(s,a)):a.copyFrom(this._parent.getAbsoluteTransform())),a.m[12]=0,a.m[13]=0,a.m[14]=0,a.invert(),e.Vector3.TransformCoordinatesToRef(t,a,l),o.m[12]+=l.x,o.m[13]+=l.y,o.m[14]+=l.z}this._markAsDirtyAndDecompose()},i.prototype.setPosition=function(t,r,n){void 0===r&&(r=e.Space.LOCAL);var o=this.getLocalMatrix();if(r==e.Space.LOCAL)o.m[12]=t.x,o.m[13]=t.y,o.m[14]=t.z;else{var s=null;n&&(s=n.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var a=i._tmpMats[0],l=i._tmpVecs[0];this._parent&&(n&&s?(a.copyFrom(this._parent.getAbsoluteTransform()),a.multiplyToRef(s,a)):a.copyFrom(this._parent.getAbsoluteTransform())),a.invert(),e.Vector3.TransformCoordinatesToRef(t,a,l),o.m[12]=l.x,o.m[13]=l.y,o.m[14]=l.z}this._markAsDirtyAndDecompose()},i.prototype.setAbsolutePosition=function(t,i){this.setPosition(t,e.Space.WORLD,i)},i.prototype.scale=function(t,r,n,o){void 0===o&&(o=!1);var s=this.getLocalMatrix(),a=i._tmpMats[0];e.Matrix.ScalingToRef(t,r,n,a),a.multiplyToRef(s,s),a.invert();for(var l=0,c=this.children;l0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,n.x>n.y&&n.x>n.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length){var o=this._bone1.getScale(),s=this._bone2.getScale();this._bone1Length=this._bone1.length*o.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*s.y*this.mesh.scaling.y}else if(this._bone1.children[0]){t.computeWorldMatrix(!0);var a=this._bone2.children[0].getAbsolutePosition(t),l=this._bone2.getAbsolutePosition(t),c=this._bone1.getAbsolutePosition(t);this._bone1Length=e.Vector3.Distance(a,l),this._bone2Length=e.Vector3.Distance(l,c)}this._bone1.getRotationMatrixToRef(e.Space.WORLD,t,this._bone1Mat),this.maxAngle=Math.PI,r&&(r.targetMesh&&(this.targetMesh=r.targetMesh,this.targetMesh.computeWorldMatrix(!0)),r.poleTargetMesh?(this.poleTargetMesh=r.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):r.poleTargetBone?this.poleTargetBone=r.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),r.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(r.poleTargetLocalOffset),r.poleAngle&&(this.poleAngle=r.poleAngle),r.bendAxis&&this._bendAxis.copyFrom(r.bendAxis),r.maxAngle&&(this.maxAngle=r.maxAngle),r.slerpAmount&&(this.slerpAmount=r.slerpAmount))}}return Object.defineProperty(t.prototype,"maxAngle",{get:function(){return this._maxAngle},set:function(e){this._setMaxAngle(e)},enumerable:!0,configurable:!0}),t.prototype._setMaxAngle=function(e){e<0&&(e=0),(e>Math.PI||void 0==e)&&(e=Math.PI),this._maxAngle=e;var t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))},t.prototype.update=function(){var i=this._bone1;if(i){var r=this.targetPosition,n=this.poleTargetPosition,o=t._tmpMats[0],s=t._tmpMats[1];this.targetMesh&&r.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,n):this.poleTargetMesh&&e.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),n);var a=t._tmpVecs[0],l=t._tmpVecs[1],c=t._tmpVecs[2],h=t._tmpVecs[3],u=t._tmpVecs[4],d=t._tmpQuat;i.getAbsolutePositionToRef(this.mesh,a),n.subtractToRef(a,u),0==u.x&&0==u.y&&0==u.z?u.y=1:u.normalize(),r.subtractToRef(a,h),h.normalize(),e.Vector3.CrossToRef(h,u,l),l.normalize(),e.Vector3.CrossToRef(h,l,c),c.normalize(),e.Matrix.FromXYZAxesToRef(c,h,l,o);var f=this._bone1Length,p=this._bone2Length,_=e.Vector3.Distance(a,r);this._maxReach>0&&(_=Math.min(this._maxReach,_));var m=(p*p+_*_-f*f)/(2*p*_),g=(_*_+f*f-p*p)/(2*_*f);m>1&&(m=1),g>1&&(g=1),m<-1&&(m=-1),g<-1&&(g=-1);var v=Math.acos(m),y=Math.acos(g),b=-v-y;if(this._rightHandedSystem)e.Matrix.RotationYawPitchRollToRef(0,0,this._adjustRoll,s),s.multiplyToRef(o,o),e.Matrix.RotationAxisToRef(this._bendAxis,y,s),s.multiplyToRef(o,o);else{var x=t._tmpVecs[5];x.copyFrom(this._bendAxis),x.x*=-1,e.Matrix.RotationAxisToRef(x,-y,s),s.multiplyToRef(o,o)}this.poleAngle&&(e.Matrix.RotationAxisToRef(h,this.poleAngle,s),o.multiplyToRef(s,o)),this._bone1&&(this.slerpAmount<1?(this._slerping||e.Quaternion.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),e.Quaternion.FromRotationMatrixToRef(o,d),e.Quaternion.SlerpToRef(this._bone1Quat,d,this.slerpAmount,this._bone1Quat),b=this._bone2Ang*(1-this.slerpAmount)+b*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,e.Space.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(o,e.Space.WORLD,this.mesh),this._bone1Mat.copyFrom(o),this._slerping=!1)),this._bone2.setAxisAngle(this._bendAxis,b,e.Space.LOCAL),this._bone2Ang=b}},t._tmpVecs=[e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero()],t._tmpQuat=e.Quaternion.Identity(),t._tmpMats=[e.Matrix.Identity(),e.Matrix.Identity()],t})();e.BoneIKController=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n){if(this.upAxis=e.Vector3.Up(),this.upAxisSpace=e.Space.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=e.Quaternion.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=e.Vector3.Forward(),this.mesh=t,this.bone=i,this.target=r,n&&(n.adjustYaw&&(this.adjustYaw=n.adjustYaw),n.adjustPitch&&(this.adjustPitch=n.adjustPitch),n.adjustRoll&&(this.adjustRoll=n.adjustRoll),null!=n.maxYaw?this.maxYaw=n.maxYaw:this.maxYaw=Math.PI,null!=n.minYaw?this.minYaw=n.minYaw:this.minYaw=-Math.PI,null!=n.maxPitch?this.maxPitch=n.maxPitch:this.maxPitch=Math.PI,null!=n.minPitch?this.minPitch=n.minPitch:this.minPitch=-Math.PI,null!=n.slerpAmount&&(this.slerpAmount=n.slerpAmount),null!=n.upAxis&&(this.upAxis=n.upAxis),null!=n.upAxisSpace&&(this.upAxisSpace=n.upAxisSpace),null!=n.yawAxis||null!=n.pitchAxis)){var o=e.Axis.Y,s=e.Axis.X;null!=n.yawAxis&&(o=n.yawAxis.clone(),o.normalize()),null!=n.pitchAxis&&(s=n.pitchAxis.clone(),s.normalize());var a=e.Vector3.Cross(s,o);this._transformYawPitch=e.Matrix.Identity(),e.Matrix.FromXYZAxesToRef(s,o,a,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}i.getParent()||this.upAxisSpace!=e.Space.BONE||(this.upAxisSpace=e.Space.LOCAL)}return Object.defineProperty(t.prototype,"minYaw",{get:function(){return this._minYaw},set:function(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxYaw",{get:function(){return this._maxYaw},set:function(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minPitch",{get:function(){return this._minPitch},set:function(e){this._minPitch=e,this._minPitchTan=Math.tan(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxPitch",{get:function(){return this._maxPitch},set:function(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)},enumerable:!0,configurable:!0}),t.prototype.update=function(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);var i=this.bone,r=t._tmpVecs[0];i.getAbsolutePositionToRef(this.mesh,r);var n=this.target,o=t._tmpMats[0],s=t._tmpMats[1],a=this.mesh,l=i.getParent(),c=t._tmpVecs[1];c.copyFrom(this.upAxis),this.upAxisSpace==e.Space.BONE&&l?(this._transformYawPitch&&e.Vector3.TransformCoordinatesToRef(c,this._transformYawPitchInv,c),l.getDirectionToRef(c,this.mesh,c)):this.upAxisSpace==e.Space.LOCAL&&(a.getDirectionToRef(c,c),1==a.scaling.x&&1==a.scaling.y&&1==a.scaling.z||c.normalize());var h=!1,u=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(h=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(u=!0),h||u){var d=t._tmpMats[2],f=t._tmpMats[3];if(this.upAxisSpace==e.Space.BONE&&1==c.y&&l)l.getRotationMatrixToRef(e.Space.WORLD,this.mesh,d);else if(this.upAxisSpace!=e.Space.LOCAL||1!=c.y||l){var p=t._tmpVecs[2];p.copyFrom(this._fowardAxis),this._transformYawPitch&&e.Vector3.TransformCoordinatesToRef(p,this._transformYawPitchInv,p),l?l.getDirectionToRef(p,this.mesh,p):a.getDirectionToRef(p,p);var _=e.Vector3.Cross(c,p);_.normalize();var p=e.Vector3.Cross(_,c);e.Matrix.FromXYZAxesToRef(_,c,p,d)}else d.copyFrom(a.getWorldMatrix());d.invertToRef(f);var m=null;if(u){var g=t._tmpVecs[3];n.subtractToRef(r,g),e.Vector3.TransformCoordinatesToRef(g,f,g),m=Math.sqrt(g.x*g.x+g.z*g.z);var v=Math.atan2(g.y,m),y=v;v>this._maxPitch?(g.y=this._maxPitchTan*m,y=this._maxPitch):vthis._maxYaw||bMath.PI?this._isAngleBetween(b,this._maxYaw,this._midYawConstraint)?(g.z=this._maxYawCos*m,g.x=this._maxYawSin*m,x=this._maxYaw):this._isAngleBetween(b,this._midYawConstraint,this._minYaw)&&(g.z=this._minYawCos*m,g.x=this._minYawSin*m,x=this._minYaw):b>this._maxYaw?(g.z=this._maxYawCos*m,g.x=this._maxYawSin*m,x=this._maxYaw):bMath.PI){var T=t._tmpVecs[8];T.copyFrom(e.Axis.Z),this._transformYawPitch&&e.Vector3.TransformCoordinatesToRef(T,this._transformYawPitchInv,T);var E=t._tmpMats[4];this._boneQuat.toRotationMatrix(E),this.mesh.getWorldMatrix().multiplyToRef(E,E),e.Vector3.TransformCoordinatesToRef(T,E,T),e.Vector3.TransformCoordinatesToRef(T,f,T);var P=Math.atan2(T.x,T.z);if(this._getAngleBetween(P,b)>this._getAngleBetween(P,this._midYawConstraint)){null==m&&(m=Math.sqrt(g.x*g.x+g.z*g.z));var A=this._getAngleBetween(P,this._maxYaw);this._getAngleBetween(P,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i},t.prototype._getAngleBetween=function(e,t){e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t;var i=0;return i=eMath.PI&&(i=2*Math.PI-i),i},t.prototype._isAngleBetween=function(e,t,i){if(e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t,i%=2*Math.PI,i=i<0?i+2*Math.PI:i,tt&&ei&&e-1&&this._meshesWithPoseMatrix.splice(t,1)},t.prototype._computeTransformMatrices=function(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(var i=0;i0&&(n.animation=i.animations[0].serialize()),e.ranges=[];for(var o in this._ranges){var s=this._ranges[o];if(s){var a={};a.name=o,a.from=s.from,a.to=s.to,e.ranges.push(a)}}}return e},t.Parse=function(i,r){var n=new t(i.name,i.id,r);i.dimensionsAtRest&&(n.dimensionsAtRest=e.Vector3.FromArray(i.dimensionsAtRest)),n.needInitialSkinMatrix=i.needInitialSkinMatrix;var o;for(o=0;o-1&&(a=n.bones[s.parentBoneIndex]);var l=s.rest?e.Matrix.FromArray(s.rest):null,c=new e.Bone(s.name,n,a,e.Matrix.FromArray(s.matrix),l);s.length&&(c.length=s.length),s.metadata&&(c.metadata=s.metadata),s.animation&&c.animations.push(e.Animation.Parse(s.animation))}if(i.ranges)for(o=0;o0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e},t.prototype.sortBones=function(){for(var e=new Array,t=new Array(this.bones.length),i=0;i1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)},t.Rgbe2float=function(e,t,i,r,n,o){n>0?(n=this.Ldexp(1,n-136),e[o+0]=t*n,e[o+1]=i*n,e[o+2]=r*n):(e[o+0]=0,e[o+1]=0,e[o+2]=0)},t.readStringLine=function(e,t){for(var i="",r="",n=t;n32767)throw"HDR Bad header format, unsupported size";return s+=r.length+1,{height:t,width:i,dataPosition:s}},t.GetCubeMapTextureData=function(t,i){var r=new Uint8Array(t),n=this.RGBE_ReadHeader(r),o=this.RGBE_ReadPixels_RLE(r,n);return e.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(o,n.width,n.height,i)},t.RGBE_ReadPixels=function(e,t){return this.RGBE_ReadPixels_RLE(e,t)},t.RGBE_ReadPixels_RLE=function(e,t){for(var i,r,n,o,s,a=t.height,l=t.width,c=t.dataPosition,h=0,u=0,d=0,f=new ArrayBuffer(4*l),p=new Uint8Array(f),_=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(_);a>0;){if(i=e[c++],r=e[c++],n=e[c++],o=e[c++],2!=i||2!=r||128&n)throw"HDR Bad header format, not RLE";if((n<<8|o)!=l)throw"HDR Bad header format, wrong scan line width";for(h=0,d=0;d<4;d++)for(u=(d+1)*l;h128){if(0==(s=i-128)||s>u-h)throw"HDR Bad Format, bad scanline data (run)";for(;s-- >0;)p[h++]=r}else{if(0==(s=i)||s>u-h)throw"HDR Bad Format, bad scanline data (non-run)";if(p[h++]=r,--s>0)for(var g=0;g255){var g=255/m;f*=g,p*=g,_*=g}l[3*d+0]=f,l[3*d+1]=p,l[3*d+2]=_}l?a.push(l):a.push(u)}return a},n=this.getScene();n&&(this._texture=n.getEngine().createRawCubeTextureFromUrl(this.url,n,this._size,e.Engine.TEXTUREFORMAT_RGB,n.getEngine().getCaps().textureFloat?e.Engine.TEXTURETYPE_FLOAT:e.Engine.TEXTURETYPE_UNSIGNED_INT,this._noMipmap,r,null,this._onLoad,this._onError))},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=new i(this.url,e,this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t.coordinatesIndex=this.coordinatesIndex,t.coordinatesMode=this.coordinatesMode,t},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this.loadTexture())},i.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},i.prototype.setReflectionTextureMatrix=function(e){this._textureMatrix=e},i.Parse=function(t,r,n){var o=null;return t.name&&!t.isRenderTarget&&(o=new i(n+t.name,r,t.size,t.noMipmap,t.generateHarmonics,t.useInGammaSpace),o.name=t.name,o.hasAlpha=t.hasAlpha,o.level=t.level,o.coordinatesMode=t.coordinatesMode,o.isBlocking=t.isBlocking),o&&(t.boundingBoxPosition&&(o.boundingBoxPosition=e.Vector3.FromArray(t.boundingBoxPosition)),t.boundingBoxSize&&(o.boundingBoxSize=e.Vector3.FromArray(t.boundingBoxSize)),t.rotationY&&(o.rotationY=t.rotationY)),o},i.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e},i._facesMapping=["right","left","up","down","front","back"],i})(e.BaseTexture);e.HDRCubeTexture=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.ConvertPanoramaToCubemap=function(t,i,r,n){if(!t)throw"ConvertPanoramaToCubemap: input cannot be null";if(t.length!=i*r*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(n,this.FACE_FRONT,t,i,r),back:this.CreateCubemapTexture(n,this.FACE_BACK,t,i,r),left:this.CreateCubemapTexture(n,this.FACE_LEFT,t,i,r),right:this.CreateCubemapTexture(n,this.FACE_RIGHT,t,i,r),up:this.CreateCubemapTexture(n,this.FACE_UP,t,i,r),down:this.CreateCubemapTexture(n,this.FACE_DOWN,t,i,r),size:n,type:e.Engine.TEXTURETYPE_FLOAT,format:e.Engine.TEXTUREFORMAT_RGB,gammaSpace:!1}},t.CreateCubemapTexture=function(e,t,i,r,n){for(var o=new ArrayBuffer(e*e*4*3),s=new Float32Array(o),a=t[1].subtract(t[0]).scale(1/e),l=t[3].subtract(t[2]).scale(1/e),c=1/e,h=0,u=0;uMath.PI;)n-=2*Math.PI;var s=n/Math.PI,a=o/Math.PI;s=.5*s+.5;var l=Math.round(s*i);l<0?l=0:l>=i&&(l=i-1);var c=Math.round(a*r);c<0?c=0:c>=r&&(c=r-1);var h=r-c-1;return{r:t[h*i*3+3*l+0],g:t[h*i*3+3*l+1],b:t[h*i*3+3*l+2]}},t.FACE_FRONT=[new e.Vector3(-1,-1,-1),new e.Vector3(1,-1,-1),new e.Vector3(-1,1,-1),new e.Vector3(1,1,-1)],t.FACE_BACK=[new e.Vector3(1,-1,1),new e.Vector3(-1,-1,1),new e.Vector3(1,1,1),new e.Vector3(-1,1,1)],t.FACE_RIGHT=[new e.Vector3(1,-1,-1),new e.Vector3(1,-1,1),new e.Vector3(1,1,-1),new e.Vector3(1,1,1)],t.FACE_LEFT=[new e.Vector3(-1,-1,1),new e.Vector3(-1,-1,-1),new e.Vector3(-1,1,1),new e.Vector3(-1,1,-1)],t.FACE_DOWN=[new e.Vector3(-1,1,-1),new e.Vector3(1,1,-1),new e.Vector3(-1,1,1),new e.Vector3(1,1,1)],t.FACE_UP=[new e.Vector3(-1,-1,1),new e.Vector3(1,-1,1),new e.Vector3(-1,-1,-1),new e.Vector3(1,-1,-1)],t})();e.PanoramaToCubeMapTools=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i){var r=e.call(this,t.x,t.y)||this;return r.index=i,r}return o(t,e),t})(e.Vector2),r=(function(){function i(){this.elements=new Array}return i.prototype.add=function(e){var i=this,r=new Array;return e.forEach((function(e){if(0===r.length||!e.equalsWithEpsilon(r[0])){var n=new t(e,i.elements.length);r.push(n),i.elements.push(n)}})),r},i.prototype.computeBounds=function(){var t=new e.Vector2(this.elements[0].x,this.elements[0].y),i=new e.Vector2(this.elements[0].x,this.elements[0].y);return this.elements.forEach((function(e){e.xi.x&&(i.x=e.x),e.yi.y&&(i.y=e.y)})),{min:t,max:i,width:i.x-t.x,height:i.y-t.y}},i})(),n=(function(){function t(){}return t.Rectangle=function(t,i,r,n){return[new e.Vector2(t,i),new e.Vector2(r,i),new e.Vector2(r,n),new e.Vector2(t,n)]},t.Circle=function(t,i,r,n){void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=32);for(var o=new Array,s=0,a=2*Math.PI/n,l=0;l0){var f=a.length/3;this._points.elements.forEach((function(e){s.push(0,-1,0),a.push(e.x,-r,e.y),l.push(1-(e.x-c.min.x)/c.width,1-(e.y-c.min.y)/c.height)}));for(var p=h.length,d=0;ds.elements.length-1?s.elements[0]:s.elements[u+1],t.push(f.x,0,f.y),t.push(f.x,-a,f.y),t.push(d.x,0,d.y),t.push(d.x,-a,d.y);var p=new e.Vector3(f.x,0,f.y),_=new e.Vector3(d.x,0,d.y),m=_.subtract(p),g=new e.Vector3(0,1,0),v=e.Vector3.Cross(m,g);v=v.normalize(),r.push(h/o.width,0),r.push(h/o.width,1),h+=m.length(),r.push(h/o.width,0),r.push(h/o.width,1),l?(i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),n.push(c),n.push(c+2),n.push(c+1),n.push(c+1),n.push(c+2),n.push(c+3)):(i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),n.push(c),n.push(c+1),n.push(c+2),n.push(c+1),n.push(c+3),n.push(c+2)),c+=4}},t})();e.PolygonMeshBuilder=s})(r||(r={}));var r;!(function(e){var t=0,i=(function(){function t(e,t,i){this.pos=e,this.normal=t,this.uv=i}return t.prototype.clone=function(){return new t(this.pos.clone(),this.normal.clone(),this.uv.clone())},t.prototype.flip=function(){this.normal=this.normal.scale(-1)},t.prototype.interpolate=function(i,r){return new t(e.Vector3.Lerp(this.pos,i.pos,r),e.Vector3.Lerp(this.normal,i.normal,r),e.Vector2.Lerp(this.uv,i.uv,r))},t})(),r=(function(){function t(e,t){this.normal=e,this.w=t}return t.FromPoints=function(i,r,n){var o=n.subtract(i),s=r.subtract(i);if(0===o.lengthSquared()||0===s.lengthSquared())return null;var a=e.Vector3.Normalize(e.Vector3.Cross(o,s));return new t(a,e.Vector3.Dot(a,i))},t.prototype.clone=function(){return new t(this.normal.clone(),this.w)},t.prototype.flip=function(){this.normal.scaleInPlace(-1),this.w=-this.w},t.prototype.splitPolygon=function(i,r,o,s,a){var l,c,h=0,u=[];for(l=0;lt.EPSILON?1:0;h|=d,u.push(d)}switch(h){case 0:(e.Vector3.Dot(this.normal,i.plane.normal)>0?r:o).push(i);break;case 1:s.push(i);break;case 2:a.push(i);break;case 3:var f=[],p=[];for(l=0;l=3&&(x=new n(f,i.shared),x.plane&&s.push(x)),p.length>=3&&(x=new n(p,i.shared),x.plane&&a.push(x))}},t.EPSILON=1e-5,t})(),n=(function(){function e(e,t){this.vertices=e,this.shared=t,this.plane=r.FromPoints(e[0].pos,e[1].pos,e[2].pos)}return e.prototype.clone=function(){return new e(this.vertices.map((function(e){return e.clone()})),this.shared)},e.prototype.flip=function(){this.vertices.reverse().map((function(e){e.flip()})),this.plane.flip()},e})(),o=(function(){function e(e){this.plane=null,this.front=null,this.back=null,this.polygons=new Array,e&&this.build(e)}return e.prototype.clone=function(){var t=new e;return t.plane=this.plane&&this.plane.clone(),t.front=this.front&&this.front.clone(),t.back=this.back&&this.back.clone(),t.polygons=this.polygons.map((function(e){return e.clone()})),t},e.prototype.invert=function(){for(var e=0;e0);for(var r=0,n=i;r0)}},t})();e.LensFlareSystemSceneComponent=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){this.name=t,this.lensFlares=new Array,this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=r||e.Engine.LastCreatedScene;var n=this._scene._getComponent(e.SceneComponentConstants.NAME_LENSFLARESYSTEM);n||(n=new e.LensFlareSystemSceneComponent(this._scene),r._addComponent(n)),this._emitter=i,this.id=t,r.lensFlareSystems.push(this),this.meshesSelectionPredicate=function(e){return r.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&0!=(e.layerMask&r.activeCamera.layerMask)};var o=r.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(o,s,e.VertexBuffer.PositionKind,!1,!1,2);var a=[];a.push(0),a.push(1),a.push(2),a.push(0),a.push(2),a.push(3),this._indexBuffer=o.createIndexBuffer(a),this._effect=o.createEffect("lensFlare",[e.VertexBuffer.PositionKind],["color","viewportMatrix"],["textureSampler"],"")}return Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEmitter=function(){return this._emitter},t.prototype.setEmitter=function(e){this._emitter=e},t.prototype.getEmitterPosition=function(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position},t.prototype.computeEffectivePosition=function(t){var i=this.getEmitterPosition();return i=e.Vector3.Project(i,e.Matrix.Identity(),this._scene.getTransformMatrix(),t),this._positionX=i.x,this._positionY=i.y,i=e.Vector3.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(t.x-=this.viewportBorder,t.y-=this.viewportBorder, -t.width+=2*this.viewportBorder,t.height+=2*this.viewportBorder,i.x+=this.viewportBorder,i.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder),i.z>0&&(this._positionX>t.x&&this._positionXt.y&&(this._positionY,t.y,t.height),!0)},t.prototype._isVisible=function(){if(!this._isEnabled||!this._scene.activeCamera)return!1;var t=this.getEmitterPosition(),i=t.subtract(this._scene.activeCamera.globalPosition),r=i.length();i.normalize();var n=new e.Ray(this._scene.activeCamera.globalPosition,i),o=this._scene.pickWithRay(n,this.meshesSelectionPredicate,!0);return!o||!o.hit||o.distance>r},t.prototype.render=function(){if(!this._effect.isReady()||!this._scene.activeCamera)return!1;var t=this._scene.getEngine(),i=this._scene.activeCamera.viewport,r=i.toGlobal(t.getRenderWidth(!0),t.getRenderHeight(!0));if(!this.computeEffectivePosition(r))return!1;if(!this._isVisible())return!1;var n,o;n=this._positionXr.x+r.width-this.borderLimit?this._positionX-r.x-r.width+this.borderLimit:0,o=this._positionYr.y+r.height-this.borderLimit?this._positionY-r.y-r.height+this.borderLimit:0;var s=n>o?n:o;(s-=this.viewportBorder)>this.borderLimit&&(s=this.borderLimit);var a=1-s/this.borderLimit;if(a<0)return!1;a>1&&(a=1),this.viewportBorder>0&&(r.x+=this.viewportBorder,r.y+=this.viewportBorder,r.width-=2*this.viewportBorder,r.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);var l=r.x+r.width/2,c=r.y+r.height/2,h=l-this._positionX,u=c-this._positionY;t.enableEffect(this._effect),t.setState(!1),t.setDepthBuffer(!1),t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect);for(var d=0;d-1?this._onBeforePhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerAfterPhysicsStep=function(e){this._onAfterPhysicsStepCallbacks.push(e)},t.prototype.unregisterAfterPhysicsStep=function(t){var i=this._onAfterPhysicsStepCallbacks.indexOf(t);i>-1?this._onAfterPhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerOnPhysicsCollide=function(e,t){var i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})},t.prototype.unregisterOnPhysicsCollide=function(t,i){var r=t instanceof Array?t:[t],n=-1;this._onPhysicsCollideCallbacks.some((function(e,t){if(e.callback===i&&e.otherImpostors.length===r.length){var o=e.otherImpostors.every((function(e){return r.indexOf(e)>-1}));return o&&(n=t),o}return!1}))?this._onPhysicsCollideCallbacks.splice(n,1):e.Tools.Warn("Function to remove was not found")},t.prototype.getParentsRotation=function(){var t=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);t;)t.rotationQuaternion?this._tmpQuat2.copyFrom(t.rotationQuaternion):e.Quaternion.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,t.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),t=t.parent;return this._tmpQuat},t.prototype.applyForce=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this},t.prototype.applyImpulse=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this},t.prototype.createJoint=function(t,i,r){var n=new e.PhysicsJoint(i,r);return this.addJoint(t,n),this},t.prototype.addJoint=function(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this},t.prototype.sleep=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this},t.prototype.wakeUp=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this},t.prototype.clone=function(e){return e?new t(e,this.type,this._options,this._scene):null},t.prototype.dispose=function(){var e=this;this._physicsEngine&&(this._joints.forEach((function(t){e._physicsEngine&&e._physicsEngine.removeJoint(e,t.otherImpostor,t.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)},t.prototype.setDeltaPosition=function(e){this._deltaPosition.copyFrom(e)},t.prototype.setDeltaRotation=function(t){this._deltaRotation||(this._deltaRotation=new e.Quaternion),this._deltaRotation.copyFrom(t),this._deltaRotationConjugated=this._deltaRotation.conjugate()},t.prototype.getBoxSizeToRef=function(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this},t.prototype.getRadius=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0},t.prototype.syncBoneWithImpostor=function(i,r,n,o,s){var a=t._tmpVecs[0],l=this.object;if(l.rotationQuaternion)if(s){var c=t._tmpQuat;l.rotationQuaternion.multiplyToRef(s,c),i.setRotationQuaternion(c,e.Space.WORLD,r)}else i.setRotationQuaternion(l.rotationQuaternion,e.Space.WORLD,r);a.x=0,a.y=0,a.z=0,n&&(a.x=n.x,a.y=n.y,a.z=n.z,i.getDirectionToRef(a,r,a),void 0!==o&&null!==o||(o=n.length()),a.x*=o,a.y*=o,a.z*=o),i.getParent()?(a.addInPlace(l.getAbsolutePosition()),i.setAbsolutePosition(a,r)):(r.setAbsolutePosition(l.getAbsolutePosition()),r.position.x-=a.x,r.position.y-=a.y,r.position.z-=a.z)},t.prototype.syncImpostorWithBone=function(i,r,n,o,s,a){var l=this.object;if(l.rotationQuaternion)if(s){var c=t._tmpQuat;i.getRotationQuaternionToRef(e.Space.WORLD,r,c),c.multiplyToRef(s,l.rotationQuaternion)}else i.getRotationQuaternionToRef(e.Space.WORLD,r,l.rotationQuaternion);var h=t._tmpVecs[0],u=t._tmpVecs[1];a||(a=t._tmpVecs[2],a.x=0,a.y=1,a.z=0),i.getDirectionToRef(a,r,u),i.getAbsolutePositionToRef(r,h),void 0!==o&&null!==o||!n||(o=n.length()),void 0!==o&&null!==o&&(h.x+=u.x*o,h.y+=u.y*o,h.z+=u.z*o),l.setAbsolutePosition(h)},t.DEFAULT_OBJECT_SIZE=new e.Vector3(1,1,1),t.IDENTITY_QUATERNION=e.Quaternion.Identity(),t._tmpVecs=[e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero()],t._tmpQuat=e.Quaternion.Identity(),t.NoImpostor=0,t.SphereImpostor=1,t.BoxImpostor=2,t.PlaneImpostor=3,t.MeshImpostor=4,t.CylinderImpostor=7,t.ParticleImpostor=8,t.HeightmapImpostor=9,t})();e.PhysicsImpostor=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i){if(void 0===i&&(i=new e.CannonJSPlugin),this._physicsPlugin=i,this._impostors=[],this._joints=[],!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");t=t||new e.Vector3(0,-9.807,0),this.setGravity(t),this.setTimeStep()}return t.prototype.setGravity=function(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)},t.prototype.setTimeStep=function(e){void 0===e&&(e=1/60),this._physicsPlugin.setTimeStep(e)},t.prototype.getTimeStep=function(){return this._physicsPlugin.getTimeStep()},t.prototype.dispose=function(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()},t.prototype.getPhysicsPluginName=function(){return this._physicsPlugin.name},t.prototype.addImpostor=function(e){e.uniqueId=this._impostors.push(e),e.parent||this._physicsPlugin.generatePhysicsBody(e)},t.prototype.removeImpostor=function(e){var t=this._impostors.indexOf(e);if(t>-1){var i=this._impostors.splice(t,1);i.length&&(i[0].physicsBody=null)}},t.prototype.addJoint=function(e,t,i){var r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)},t.prototype.removeJoint=function(e,t,i){var r=this._joints.filter((function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e}));r.length&&this._physicsPlugin.removeJoint(r[0])},t.prototype._step=function(e){var t=this;this._impostors.forEach((function(e){e.isBodyInitRequired()&&t._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)},t.prototype.getPhysicsPlugin=function(){return this._physicsPlugin},t.prototype.getImpostors=function(){return this._impostors},t.prototype.getImpostorForPhysicsObject=function(e){for(var t=0;tr)return null;var f=o===s.Constant?n:n*(1-d/r);return{force:l.multiplyByFloats(f,f,f),contactPoint:u}},t.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._sphere.dispose():setTimeout((function(){t._dataFetched||t._sphere.dispose()}),0)},t.prototype._prepareSphere=function(){this._sphere||(this._sphere=e.MeshBuilder.CreateSphere("radialExplosionEventSphere",this._sphereOptions,this._scene),this._sphere.isVisible=!1)},t.prototype._intersectsWithSphere=function(t,i,r){var n=t.object;return this._prepareSphere(),this._sphere.position=i,this._sphere.scaling=new e.Vector3(2*r,2*r,2*r),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(n,!0)},t})();e.PhysicsRadialExplosionEvent=i;var r=(function(){function e(e,t,i,r,n,o){void 0===o&&(o=s.Constant),this._dataFetched=!1,this._physicsHelper=e,this._scene=t,this._origin=i,this._radius=r,this._strength=n,this._falloff=o,this._tickCallback=this._tick.bind(this)}return e.prototype.getData=function(){return this._dataFetched=!0,{sphere:this._sphere}},e.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},e.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._sphere.dispose():setTimeout((function(){t._dataFetched||t._sphere.dispose()}),0)},e.prototype._tick=function(){if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._radius,-1*this._strength,this._falloff);else{var e=this._physicsHelper.applyRadialExplosionForce(this._origin,this._radius,-1*this._strength,this._falloff);e&&(this._sphere=e.getData().sphere.clone("radialExplosionEventSphereClone"))}},e})();e.PhysicsGravitationalFieldEvent=r;var n=(function(){function t(t,i,r,n,o,s){this._scene=t,this._origin=i,this._radius=r,this._strength=n,this._height=o,this._updraftMode=s,this._originTop=e.Vector3.Zero(),this._originDirection=e.Vector3.Zero(),this._cylinderPosition=e.Vector3.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._origin.addToRef(new e.Vector3(0,this._height/2,0),this._cylinderPosition),this._origin.addToRef(new e.Vector3(0,this._height,0),this._originTop),this._updraftMode===a.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=this._tick.bind(this)}return t.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},t.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},t.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},t.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._cylinder.dispose():setTimeout((function(){t._dataFetched||t._cylinder.dispose()}),0)},t.prototype.getImpostorForceAndContactPoint=function(e){if(0===e.mass)return null;if(!this._intersectsWithCylinder(e))return null;var t=e.getObjectCenter();if(this._updraftMode===a.Perpendicular)var i=this._originDirection;else var i=t.subtract(this._originTop);var r=-1*this._strength;return{force:i.multiplyByFloats(r,r,r),contactPoint:t}},t.prototype._tick=function(){var e=this;this._physicsEngine.getImpostors().forEach((function(t){var i=e.getImpostorForceAndContactPoint(t);i&&t.applyForce(i.force,i.contactPoint)}))},t.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=e.MeshBuilder.CreateCylinder("updraftEventCylinder",{height:this._height,diameter:2*this._radius},this._scene),this._cylinder.isVisible=!1)},t.prototype._intersectsWithCylinder=function(e){var t=e.object;return this._prepareCylinder(),this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(t,!0)},t})();e.PhysicsUpdraftEvent=n;var o=(function(){function t(t,i,r,n,o){this._scene=t,this._origin=i,this._radius=r,this._strength=n,this._height=o,this._originTop=e.Vector3.Zero(),this._centripetalForceThreshold=.7,this._updraftMultiplier=.02,this._cylinderPosition=e.Vector3.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._origin.addToRef(new e.Vector3(0,this._height/2,0),this._cylinderPosition),this._origin.addToRef(new e.Vector3(0,this._height,0),this._originTop),this._tickCallback=this._tick.bind(this)}return t.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},t.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},t.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},t.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._cylinder.dispose():setTimeout((function(){t._dataFetched||t._cylinder.dispose()}),0)},t.prototype.getImpostorForceAndContactPoint=function(t){if(0===t.mass)return null;if(!this._intersectsWithCylinder(t))return null;if("Mesh"!==t.object.getClassName()&&"InstancedMesh"!==t.object.getClassName())return null;var i=t.getObjectCenter(),r=new e.Vector3(this._origin.x,i.y,this._origin.z),n=i.subtract(r),o=new e.Ray(r,n,this._radius),s=o.intersectsMesh(t.object),a=s.pickedPoint;if(!a)return null;var l=s.distance/this._radius,c=e.Vector3.Cross(r,i).normalize(),h=a.normalize();if(l>this._centripetalForceThreshold&&(h=h.negate()),l>this._centripetalForceThreshold)var u=h.x*this._strength/8,d=h.y*this._updraftMultiplier,f=h.z*this._strength/8;else var u=(c.x+h.x)/2,d=this._originTop.y*this._updraftMultiplier,f=(c.z+h.z)/2;var p=new e.Vector3(u,d,f);return p=p.multiplyByFloats(this._strength,this._strength,this._strength),{force:p,contactPoint:i}},t.prototype._tick=function(){var e=this;this._physicsEngine.getImpostors().forEach((function(t){var i=e.getImpostorForceAndContactPoint(t);i&&t.applyForce(i.force,i.contactPoint)}))},t.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=e.MeshBuilder.CreateCylinder("vortexEventCylinder",{height:this._height,diameter:2*this._radius},this._scene),this._cylinder.isVisible=!1)},t.prototype._intersectsWithCylinder=function(e){var t=e.object;return this._prepareCylinder(),this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(t,!0)},t})();e.PhysicsVortexEvent=o;var s;!(function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"})(s=e.PhysicsRadialImpulseFalloff||(e.PhysicsRadialImpulseFalloff={}));var a;!(function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"})(a=e.PhysicsUpdraftMode||(e.PhysicsUpdraftMode={}))})(r||(r={}));var r;!(function(t){var i=(function(){function i(i,r){if(void 0===i&&(i=!0),void 0===r&&(r=10),this._useDeltaForWorldStep=i,this.name="CannonJSPlugin",this._physicsMaterials=new Array,this._fixedTimeStep=1/60,this.BJSCANNON=e,this._minus90X=new t.Quaternion(-.7071067811865475,0,0,.7071067811865475),this._plus90X=new t.Quaternion(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=t.Vector3.Zero(),this._tmpDeltaPosition=t.Vector3.Zero(),this._tmpUnityRotation=new t.Quaternion,!this.isSupported())return void t.Tools.Error("CannonJS is not available. Please make sure you included the js file.");this._extendNamespace(),this.world=new this.BJSCANNON.World,this.world.broadphase=new this.BJSCANNON.NaiveBroadphase,this.world.solver.iterations=r}return i.prototype.setGravity=function(e){this.world.gravity.copy(e)},i.prototype.setTimeStep=function(e){this._fixedTimeStep=e},i.prototype.getTimeStep=function(){return this._fixedTimeStep},i.prototype.executeStep=function(e,t){this.world.step(this._fixedTimeStep,this._useDeltaForWorldStep?e:0,3)},i.prototype.applyImpulse=function(e,t,i){var r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),n=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(n,r)},i.prototype.applyForce=function(e,t,i){var r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),n=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(n,r)},i.prototype.generatePhysicsBody=function(e){if(e.parent)return void(e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate()));if(e.isBodyInitRequired()){var t=this._createShape(e),i=e.physicsBody;i&&this.removePhysicsBody(e);var r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),n={mass:e.getParam("mass"),material:r},o=e.getParam("nativeOptions");for(var s in o)o.hasOwnProperty(s)&&(n[s]=o[s]);e.physicsBody=new this.BJSCANNON.Body(n),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){e.physicsBody[t].copy(i[t])})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)},i.prototype._processChildMeshes=function(e){var i=this,r=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],n=e.object.rotationQuaternion;if(r.length){var o=function(r,s){if(n&&s.rotationQuaternion){var a=s.getPhysicsImpostor();if(a){if(a.parent!==e){var l=s.getAbsolutePosition().subtract(e.object.getAbsolutePosition()),c=s.rotationQuaternion.multiply(t.Quaternion.Inverse(n));a.physicsBody&&(i.removePhysicsBody(a),a.physicsBody=null),a.parent=e,a.resetUpdateFlags(),e.physicsBody.addShape(i._createShape(a),new i.BJSCANNON.Vec3(l.x,l.y,l.z),new i.BJSCANNON.Quaternion(c.x,c.y,c.z,c.w)),e.physicsBody.mass+=a.getParam("mass")}}n.multiplyInPlace(s.rotationQuaternion),s.getChildMeshes(!0).filter((function(e){return!!e.physicsImpostor})).forEach(o.bind(i,s.getAbsolutePosition()))}};r.filter((function(e){return!!e.physicsImpostor})).forEach(o.bind(this,e.object.getAbsolutePosition()))}},i.prototype.removePhysicsBody=function(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),this.world.remove(e.physicsBody)},i.prototype.generateJoint=function(e){var i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(i&&r){var n,o=e.joint.jointData,s={pivotA:o.mainPivot?(new this.BJSCANNON.Vec3).copy(o.mainPivot):null, -pivotB:o.connectedPivot?(new this.BJSCANNON.Vec3).copy(o.connectedPivot):null,axisA:o.mainAxis?(new this.BJSCANNON.Vec3).copy(o.mainAxis):null,axisB:o.connectedAxis?(new this.BJSCANNON.Vec3).copy(o.connectedAxis):null,maxForce:o.nativeParams.maxForce,collideConnected:!!o.collision};switch(e.joint.type){case t.PhysicsJoint.HingeJoint:case t.PhysicsJoint.Hinge2Joint:n=new this.BJSCANNON.HingeConstraint(i,r,s);break;case t.PhysicsJoint.DistanceJoint:n=new this.BJSCANNON.DistanceConstraint(i,r,o.maxDistance||2);break;case t.PhysicsJoint.SpringJoint:var a=o;n=new this.BJSCANNON.Spring(i,r,{restLength:a.length,stiffness:a.stiffness,damping:a.damping,localAnchorA:s.pivotA,localAnchorB:s.pivotB});break;case t.PhysicsJoint.LockJoint:n=new this.BJSCANNON.LockConstraint(i,r,s);break;case t.PhysicsJoint.PointToPointJoint:case t.PhysicsJoint.BallAndSocketJoint:default:n=new this.BJSCANNON.PointToPointConstraint(i,s.pivotA,r,s.pivotA,s.maxForce)}n.collideConnected=!!o.collision,e.joint.physicsJoint=n,e.joint.type!==t.PhysicsJoint.SpringJoint?this.world.addConstraint(n):e.mainImpostor.registerAfterPhysicsStep((function(){n.applyForce()}))}},i.prototype.removeJoint=function(e){this.world.removeConstraint(e.joint.physicsJoint)},i.prototype._addMaterial=function(e,t,i){var r,n;for(r=0;r1e3*i));a++);this.time+=r;for(var l=this.time%i,c=l/i,h=e,u=this.bodies,d=0;d!==u.length;d++){var f=u[d];f.type!==t.Body.STATIC&&f.sleepState!==t.Body.SLEEPING?(f.position.vsub(f.previousPosition,h),h.scale(c,h),f.position.vadd(h,f.interpolatedPosition)):(f.interpolatedPosition.copy(f.position),f.interpolatedQuaternion.copy(f.quaternion))}}}},i})();t.CannonJSPlugin=i})(r||(r={}));var r;!(function(e){var i=(function(){function i(i){this.name="OimoJSPlugin",this._tmpImpostorsArray=[],this._tmpPositionVector=e.Vector3.Zero(),this.BJSOIMO=t,this.world=new this.BJSOIMO.World({iterations:i}),this.world.clear()}return i.prototype.setGravity=function(e){this.world.gravity.copy(e)},i.prototype.setTimeStep=function(e){this.world.timeStep=e},i.prototype.getTimeStep=function(){return this.world.timeStep},i.prototype.executeStep=function(e,t){var i=this;t.forEach((function(e){e.beforeStep()})),this.world.step(),t.forEach((function(e){e.afterStep(),i._tmpImpostorsArray[e.uniqueId]=e}));for(var r=this.world.contacts;null!==r;)if(!r.touching||r.body1.sleeping||r.body2.sleeping){var n=this._tmpImpostorsArray[+r.body1.name],o=this._tmpImpostorsArray[+r.body2.name];n&&o?(n.onCollide({body:o.physicsBody}),o.onCollide({body:n.physicsBody}),r=r.next):r=r.next}else r=r.next},i.prototype.applyImpulse=function(e,t,i){var r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))},i.prototype.applyForce=function(t,i,r){e.Tools.Warn("Oimo doesn't support applying force. Using impule instead."),this.applyImpulse(t,i,r)},i.prototype.generatePhysicsBody=function(t){var i=this;if(t.parent)return void(t.physicsBody&&(this.removePhysicsBody(t),t.forceUpdate()));if(t.isBodyInitRequired()){var r={name:t.uniqueId,config:[t.getParam("mass")||1,t.getParam("friction"),t.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==t.getParam("mass"),density:t.getParam("mass"),friction:t.getParam("friction"),restitution:t.getParam("restitution"),world:this.world},n=[t];!(function(e){e.getChildMeshes&&e.getChildMeshes().forEach((function(e){e.physicsImpostor&&n.push(e.physicsImpostor)}))})(t.object);var o=function(t){return Math.max(t,e.PhysicsEngine.Epsilon)},s=new e.Quaternion;n.forEach((function(n){if(n.object.rotationQuaternion){var a=n.object.rotationQuaternion;s=a.clone();var l=a.toEulerAngles(),c=n.getObjectExtendSize();if(n===t){var h=t.getObjectCenter();t.object.getAbsolutePivotPoint().subtractToRef(h,i._tmpPositionVector),i._tmpPositionVector.divideInPlace(t.object.scaling),r.pos.push(h.x),r.pos.push(h.y),r.pos.push(h.z),r.posShape.push(0,0,0),r.rot.push(0),r.rot.push(0),r.rot.push(0),r.rotShape.push(0,0,0)}else{var u=n.object.getAbsolutePosition().subtract(t.object.getAbsolutePosition());r.posShape.push(u.x),r.posShape.push(u.y),r.posShape.push(u.z),r.pos.push(0,0,0),r.rot.push(0),r.rot.push(0),r.rot.push(0),r.rotShape.push(57.29577951308232*l.x),r.rotShape.push(57.29577951308232*l.y),r.rotShape.push(57.29577951308232*l.z)}switch(n.type){case e.PhysicsImpostor.ParticleImpostor:e.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case e.PhysicsImpostor.SphereImpostor:var d=c.x,f=c.y,p=c.z,_=Math.max(o(d),o(f),o(p))/2;r.type.push("sphere"),r.size.push(_),r.size.push(_),r.size.push(_);break;case e.PhysicsImpostor.CylinderImpostor:var m=o(c.x)/2,g=o(c.y);r.type.push("cylinder"),r.size.push(m),r.size.push(g),r.size.push(g);break;case e.PhysicsImpostor.PlaneImpostor:case e.PhysicsImpostor.BoxImpostor:default:var m=o(c.x),g=o(c.y),v=o(c.z);r.type.push("box"),r.size.push(m),r.size.push(g),r.size.push(v)}n.object.rotationQuaternion=a}})),t.physicsBody=this.world.add(r),t.physicsBody.resetQuaternion(s),t.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);t.setDeltaPosition(this._tmpPositionVector)},i.prototype.removePhysicsBody=function(e){this.world.removeRigidBody(e.physicsBody)},i.prototype.generateJoint=function(t){var i=t.mainImpostor.physicsBody,r=t.connectedImpostor.physicsBody;if(i&&r){var n,o=t.joint.jointData,s=o.nativeParams||{},a={body1:i,body2:r,axe1:s.axe1||(o.mainAxis?o.mainAxis.asArray():null),axe2:s.axe2||(o.connectedAxis?o.connectedAxis.asArray():null),pos1:s.pos1||(o.mainPivot?o.mainPivot.asArray():null),pos2:s.pos2||(o.connectedPivot?o.connectedPivot.asArray():null),min:s.min,max:s.max,collision:s.collision||o.collision,spring:s.spring,world:this.world};switch(t.joint.type){case e.PhysicsJoint.BallAndSocketJoint:n="jointBall";break;case e.PhysicsJoint.SpringJoint:e.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");var l=o;a.min=l.length||a.min,a.max=Math.max(a.min,a.max);case e.PhysicsJoint.DistanceJoint:n="jointDistance",a.max=o.maxDistance;break;case e.PhysicsJoint.PrismaticJoint:n="jointPrisme";break;case e.PhysicsJoint.SliderJoint:n="jointSlide";break;case e.PhysicsJoint.WheelJoint:n="jointWheel";break;case e.PhysicsJoint.HingeJoint:default:n="jointHinge"}a.type=n,t.joint.physicsJoint=this.world.add(a)}},i.prototype.removeJoint=function(t){try{this.world.removeJoint(t.joint.physicsJoint)}catch(t){e.Tools.Warn(t)}},i.prototype.isSupported=function(){return void 0!==this.BJSOIMO},i.prototype.setTransformationFromPhysicsBody=function(e){e.physicsBody.sleeping||(e.object.position.copyFrom(e.physicsBody.getPosition()),e.object.rotationQuaternion&&e.object.rotationQuaternion.copyFrom(e.physicsBody.getQuaternion()))},i.prototype.setPhysicsBodyTransformation=function(e,t,i){var r=e.physicsBody;r.position.copy(t),r.orientation.copy(i),r.syncShapes(),r.awake()},i.prototype.setLinearVelocity=function(e,t){e.physicsBody.linearVelocity.copy(t)},i.prototype.setAngularVelocity=function(e,t){e.physicsBody.angularVelocity.copy(t)},i.prototype.getLinearVelocity=function(t){var i=t.physicsBody.linearVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},i.prototype.getAngularVelocity=function(t){var i=t.physicsBody.angularVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},i.prototype.setBodyMass=function(e,t){var i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)},i.prototype.getBodyMass=function(e){return e.physicsBody.shapes.density},i.prototype.getBodyFriction=function(e){return e.physicsBody.shapes.friction},i.prototype.setBodyFriction=function(e,t){e.physicsBody.shapes.friction=t},i.prototype.getBodyRestitution=function(e){return e.physicsBody.shapes.restitution},i.prototype.setBodyRestitution=function(e,t){e.physicsBody.shapes.restitution=t},i.prototype.sleepBody=function(e){e.physicsBody.sleep()},i.prototype.wakeUpBody=function(e){e.physicsBody.awake()},i.prototype.updateDistanceJoint=function(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)},i.prototype.setMotor=function(e,t,i,r){var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setMotor(t,i)},i.prototype.setLimit=function(e,t,i,r){var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setLimit(t,void 0===i?-t:i)},i.prototype.syncMeshWithImpostor=function(e,t){var i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.s)},i.prototype.getRadius=function(e){return e.physicsBody.shapes.radius},i.prototype.getBoxSizeToRef=function(e,t){var i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth},i.prototype.dispose=function(){this.world.clear()},i})();e.OimoJSPlugin=i})(r||(r={}));var r;!(function(e){function t(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}function i(e){return String.fromCharCode(255&e,e>>8&255,e>>16&255,e>>24&255)}var r=t("DXT1"),n=t("DXT3"),o=t("DXT5"),s=t("DX10"),a=(function(){function t(){}return t.GetDDSInfo=function(t){var i=new Int32Array(t,0,31),a=new Int32Array(t,0,35),l=1;131072&i[2]&&(l=Math.max(1,i[7]));var c=i[21],h=c===s?a[32]:0,u=e.Engine.TEXTURETYPE_UNSIGNED_INT;switch(c){case 113:u=e.Engine.TEXTURETYPE_HALF_FLOAT;break;case 116:u=e.Engine.TEXTURETYPE_FLOAT;break;case s:if(10===h){u=e.Engine.TEXTURETYPE_HALF_FLOAT;break}}return{width:i[4],height:i[3],mipmapCount:l,isFourCC:4==(4&i[20]),isRGB:64==(64&i[20]),isLuminance:131072==(131072&i[20]),isCube:512==(512&i[28]),isCompressed:c===r||c===n||c===o,dxgiFormat:h,textureType:u}},t._ToHalfFloat=function(e){t._FloatView||(t._FloatView=new Float32Array(1),t._Int32View=new Int32Array(t._FloatView.buffer)),t._FloatView[0]=e;var i=t._Int32View[0],r=i>>16&32768,n=i>>12&2047,o=i>>23&255;return o<103?r:o>142?(r|=31744,r|=(255==o?0:1)&&8388607&i):o<113?(n|=2048,r|=(n>>114-o)+(n>>113-o&1)):(r|=o-112<<10|n>>1,r+=1&n)},t._FromHalfFloat=function(e){var t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(r/Math.pow(2,10)):31==i?r?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+r/Math.pow(2,10))},t._GetHalfFloatAsFloatRGBAArrayBuffer=function(e,i,r,n,o,s){for(var a=new Float32Array(n),l=new Uint16Array(o,r),c=0,h=0;h>8)},t._GetRGBArrayBuffer=function(e,t,i,r,n,o,s,a){for(var l=new Uint8Array(r),c=new Uint8Array(n,i),h=0,u=0;u0?h.sphericalPolynomial=e.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({size:P[4],right:_[0],left:_[1],up:_[2],down:_[3],front:_[4],back:_[5],format:e.Engine.TEXTUREFORMAT_RGBA,type:e.Engine.TEXTURETYPE_FLOAT,gammaSpace:!1}):h.sphericalPolynomial=void 0},t.StoreLODInAlphaChannel=!1,t})();e.DDSTools=a})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.supportCascades=!0}return t.prototype.canLoad=function(e,t,i,r,n){return 0===e.indexOf(".dds")},t.prototype.transformUrl=function(e,t){return e},t.prototype.getFallbackTextureUrl=function(e,t){return null},t.prototype.loadCubeData=function(t,i,r,n,o){var s,a=i.getEngine(),l=!1;if(Array.isArray(t))for(var c=0;c1)&&i.generateMipMaps,a._unpackFlipY(s.isCompressed),e.DDSTools.UploadDDSLevels(a,i,h,s,l,6,-1,c),s.isFourCC||1!==s.mipmapCount||a.generateMipMapsForCubemap(i)}else{var u=t;s=e.DDSTools.GetDDSInfo(u),i.width=s.width,i.height=s.height,r&&(s.sphericalPolynomial=new e.SphericalPolynomial),l=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&i.generateMipMaps,a._unpackFlipY(s.isCompressed),e.DDSTools.UploadDDSLevels(a,i,u,s,l,6),s.isFourCC||1!==s.mipmapCount||a.generateMipMapsForCubemap(i)}a._setCubeMapTextureParams(l),i.isReady=!0,n&&n({isDDS:!0,width:i.width,info:s,data:t,texture:i})},t.prototype.loadData=function(t,i,r){var n=e.DDSTools.GetDDSInfo(t),o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&i.generateMipMaps&&n.width>>n.mipmapCount-1==1;r(n.width,n.height,!o,n.isFourCC,(function(){e.DDSTools.UploadDDSLevels(i.getEngine(),i,t,n,o,1)}))},t})();e.Engine._TextureLoaders.push(new t)})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.GetTGAHeader=function(e){var t=0;return{id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]}},t.UploadContent=function(i,r){if(r.length<19)return void e.Tools.Error("Unable to load TGA file - Not enough data to contain header");var n=18,o=t.GetTGAHeader(r);if(o.id_length+n>r.length)return void e.Tools.Error("Unable to load TGA file - Not enough data");n+=o.id_length;var s=!1,a=!1,l=!1;switch(o.image_type){case t._TYPE_RLE_INDEXED:s=!0;case t._TYPE_INDEXED:a=!0;break;case t._TYPE_RLE_RGB:s=!0;case t._TYPE_RGB:break;case t._TYPE_RLE_GREY:s=!0;case t._TYPE_GREY:l=!0}var c,h,u=o.pixel_size>>3,d=o.width*o.height*u;if(a&&(h=r.subarray(n,n+=o.colormap_length*(o.colormap_size>>3))),s){c=new Uint8Array(d);for(var f,p,_,m=0,g=new Uint8Array(u);n>t._ORIGIN_SHIFT){default:case t._ORIGIN_UL:v=0,b=1,E=o.width,y=0,x=1,T=o.height;break;case t._ORIGIN_BL:v=0,b=1,E=o.width,y=o.height-1,x=-1,T=-1;break;case t._ORIGIN_UR:v=o.width-1,b=-1,E=-1,y=0,x=1,T=o.height;break;case t._ORIGIN_BR:v=o.width-1,b=-1,E=-1,y=o.height-1,x=-1,T=-1}var P="_getImageData"+(l?"Grey":"")+o.pixel_size+"bits",A=t[P](o,h,c,y,x,T,v,b,E);i.getEngine()._uploadDataToTextureDirectly(i,A)},t._getImageData8bits=function(e,t,i,r,n,o,s,a,l){var c,h,u,d=i,f=t,p=e.width,_=e.height,m=0,g=new Uint8Array(p*_*4);for(u=r;u!==o;u+=n)for(h=s;h!==l;h+=a,m++)c=d[m],g[4*(h+p*u)+3]=255,g[4*(h+p*u)+2]=f[3*c+0],g[4*(h+p*u)+1]=f[3*c+1],g[4*(h+p*u)+0]=f[3*c+2];return g},t._getImageData16bits=function(e,t,i,r,n,o,s,a,l){var c,h,u,d=i,f=e.width,p=e.height,_=0,m=new Uint8Array(f*p*4);for(u=r;u!==o;u+=n)for(h=s;h!==l;h+=a,_+=2){c=d[_+0]+(d[_+1]<<8);var g=255*((31744&c)>>10)/31|0,v=255*((992&c)>>5)/31|0,y=255*(31&c)/31|0;m[4*(h+f*u)+0]=g,m[4*(h+f*u)+1]=v,m[4*(h+f*u)+2]=y,m[4*(h+f*u)+3]=32768&c?0:255}return m},t._getImageData24bits=function(e,t,i,r,n,o,s,a,l){var c,h,u=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(h=r;h!==o;h+=n)for(c=s;c!==l;c+=a,p+=3)_[4*(c+d*h)+3]=255,_[4*(c+d*h)+2]=u[p+0],_[4*(c+d*h)+1]=u[p+1],_[4*(c+d*h)+0]=u[p+2];return _},t._getImageData32bits=function(e,t,i,r,n,o,s,a,l){var c,h,u=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(h=r;h!==o;h+=n)for(c=s;c!==l;c+=a,p+=4)_[4*(c+d*h)+2]=u[p+0],_[4*(c+d*h)+1]=u[p+1],_[4*(c+d*h)+0]=u[p+2],_[4*(c+d*h)+3]=u[p+3];return _},t._getImageDataGrey8bits=function(e,t,i,r,n,o,s,a,l){var c,h,u,d=i,f=e.width,p=e.height,_=0,m=new Uint8Array(f*p*4);for(u=r;u!==o;u+=n)for(h=s;h!==l;h+=a,_++)c=d[_],m[4*(h+f*u)+0]=c,m[4*(h+f*u)+1]=c,m[4*(h+f*u)+2]=c,m[4*(h+f*u)+3]=255;return m},t._getImageDataGrey16bits=function(e,t,i,r,n,o,s,a,l){var c,h,u=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(h=r;h!==o;h+=n)for(c=s;c!==l;c+=a,p+=2)_[4*(c+d*h)+0]=u[p+0],_[4*(c+d*h)+1]=u[p+0],_[4*(c+d*h)+2]=u[p+0],_[4*(c+d*h)+3]=u[p+1];return _},t._TYPE_INDEXED=1,t._TYPE_RGB=2,t._TYPE_GREY=3,t._TYPE_RLE_INDEXED=9,t._TYPE_RLE_RGB=10,t._TYPE_RLE_GREY=11,t._ORIGIN_MASK=48,t._ORIGIN_SHIFT=4,t._ORIGIN_BL=0,t._ORIGIN_BR=1,t._ORIGIN_UL=2,t._ORIGIN_UR=3,t})();e.TGATools=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.supportCascades=!1}return t.prototype.canLoad=function(e,t,i,r,n){return 0===e.indexOf(".tga")},t.prototype.transformUrl=function(e,t){return e},t.prototype.getFallbackTextureUrl=function(e,t){return null},t.prototype.loadCubeData=function(e,t,i,r,n){throw".env not supported in Cube."},t.prototype.loadData=function(t,i,r){var n=new Uint8Array(t),o=e.TGATools.GetTGAHeader(n);r(o.width,o.height,i.generateMipMaps,!1,(function(){e.TGATools.UploadContent(i,n)}))},t})();e.Engine._TextureLoaders.push(new t)})(r||(r={}));var r;!(function(e){var t=(function(){function t(i,r,n,o){this.arrayBuffer=i;var s=new Uint8Array(this.arrayBuffer,0,12);if(171!==s[0]||75!==s[1]||84!==s[2]||88!==s[3]||32!==s[4]||49!==s[5]||49!==s[6]||187!==s[7]||13!==s[8]||10!==s[9]||26!==s[10]||10!==s[11])return void e.Tools.Error("texture missing KTX identifier");var a=new Int32Array(this.arrayBuffer,12,13),l=16909060===a[0];return this.glType=l?this.switchEndainness(a[1]):a[1],this.glTypeSize=l?this.switchEndainness(a[2]):a[2],this.glFormat=l?this.switchEndainness(a[3]):a[3],this.glInternalFormat=l?this.switchEndainness(a[4]):a[4],this.glBaseInternalFormat=l?this.switchEndainness(a[5]):a[5],this.pixelWidth=l?this.switchEndainness(a[6]):a[6],this.pixelHeight=l?this.switchEndainness(a[7]):a[7],this.pixelDepth=l?this.switchEndainness(a[8]):a[8],this.numberOfArrayElements=l?this.switchEndainness(a[9]):a[9],this.numberOfFaces=l?this.switchEndainness(a[10]):a[10],this.numberOfMipmapLevels=l?this.switchEndainness(a[11]):a[11],this.bytesOfKeyValueData=l?this.switchEndainness(a[12]):a[12],0!==this.glType?void e.Tools.Error("only compressed formats currently supported"):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?void e.Tools.Error("only 2D textures currently supported"):0!==this.numberOfArrayElements?void e.Tools.Error("texture arrays not currently supported"):this.numberOfFaces!==r?void e.Tools.Error("number of faces expected"+r+", but found "+this.numberOfFaces):void(this.loadType=t.COMPRESSED_2D))}return t.prototype.switchEndainness=function(e){return(255&e)<<24|(65280&e)<<8|e>>8&65280|e>>24&255},t.prototype.uploadLevels=function(e,i){switch(this.loadType){case t.COMPRESSED_2D:this._upload2DCompressedLevels(e,i);break;case t.TEX_2D:case t.COMPRESSED_3D:case t.TEX_3D:}},t.prototype._upload2DCompressedLevels=function(e,i){for(var r=t.HEADER_LEN+this.bytesOfKeyValueData,n=this.pixelWidth,o=this.pixelHeight,s=i?this.numberOfMipmapLevels:1,a=0;a-1?e.substring(0,i):e)+t}, -t.prototype.getFallbackTextureUrl=function(e,t){var i=new RegExp(t+"$");return e.replace(i,"")},t.prototype.loadCubeData=function(t,i,r,n,o){if(!Array.isArray(t)){var s=i.getEngine(),a=new e.KhronosTextureContainer(t,6),l=a.numberOfMipmapLevels>1&&i.generateMipMaps;s._unpackFlipY(!0),a.uploadLevels(i,i.generateMipMaps),i.width=a.pixelWidth,i.height=a.pixelHeight,s._setCubeMapTextureParams(l),i.isReady=!0}},t.prototype.loadData=function(t,i,r){var n=new e.KhronosTextureContainer(t,1);r(n.pixelWidth,n.pixelHeight,!1,!0,(function(){n.uploadLevels(i,i.generateMipMaps)}))},t})();e.Engine._TextureLoaders.unshift(new t)})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.GetEnvInfo=function(i){for(var r=new DataView(i),n=0,o=0;o0)):!i._pointerCaptures[l.pointerId]&&s.distance>a.distance&&(i.mainSceneTrackerPredicate&&i.mainSceneTrackerPredicate(a.pickedMesh)?(i._notifyObservers(r,a,l),r.skipOnPointerObservable=!0):i._lastPointerEvents[l.pointerId]&&(i.onPointerOutObservable.notifyObservers(l.pointerId),delete i._lastPointerEvents[l.pointerId])),r.type===e.PointerEventTypes.POINTERUP&&i._pointerCaptures[l.pointerId]&&(i._pointerCaptures[l.pointerId]=!1))}}})),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderObservable.add((function(){i.shouldRender&&i.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((function(){i.dispose()})),this._updateCamera()}return Object.defineProperty(t,"DefaultUtilityLayer",{get:function(){return null==t._DefaultUtilityLayer&&(t._DefaultUtilityLayer=new t(e.Engine.LastCreatedScene),t._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((function(){t._DefaultUtilityLayer=null}))),t._DefaultUtilityLayer},enumerable:!0,configurable:!0}),Object.defineProperty(t,"DefaultKeepDepthUtilityLayer",{get:function(){return null==t._DefaultKeepDepthUtilityLayer&&(t._DefaultKeepDepthUtilityLayer=new t(e.Engine.LastCreatedScene),t._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,t._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((function(){t._DefaultKeepDepthUtilityLayer=null}))),t._DefaultKeepDepthUtilityLayer},enumerable:!0,configurable:!0}),t.prototype._notifyObservers=function(t,i,r){t.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new e.PointerInfo(t.type,t.event,i)),this._lastPointerEvents[r.pointerId]=r.pointerType)},t.prototype.render=function(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){var e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}},t.prototype.dispose=function(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()},t.prototype._updateCamera=function(){this.utilityLayerScene.activeCamera=this.originalScene.activeCamera},t._DefaultUtilityLayer=null,t._DefaultKeepDepthUtilityLayer=null,t})();e.UtilityLayerRenderer=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){this.maxDragAngle=0,this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerID=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new e.Observable,this.onDragStartObservable=new e.Observable,this.onDragEndObservable=new e.Observable,this.moveAttached=!0,this.enabled=!0,this.detachCameraControls=!0,this.useObjectOrienationForDragging=!0,this._tmpVector=new e.Vector3(0,0,0),this._alternatePickedPoint=new e.Vector3(0,0,0),this._worldDragAxis=new e.Vector3(0,0,0),this._pointA=new e.Vector3(0,0,0),this._pointB=new e.Vector3(0,0,0),this._pointC=new e.Vector3(0,0,0),this._lineA=new e.Vector3(0,0,0),this._lineB=new e.Vector3(0,0,0),this._localAxis=new e.Vector3(0,0,0),this._lookAt=new e.Vector3(0,0,0),this._options=t||{};var i=0;if(this._options.dragAxis&&i++,this._options.dragPlaneNormal&&i++,i>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}return Object.defineProperty(t.prototype,"name",{get:function(){return"PointerDrag"},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(i){var r=this;this._scene=i.getScene(),this._attachedNode=i,t._planeScene||(this._debugMode?t._planeScene=this._scene:(t._planeScene=new e.Scene(this._scene.getEngine()),t._planeScene.detachControl(),this._scene.getEngine().scenes.pop(),this._scene.onDisposeObservable.addOnce((function(){t._planeScene.dispose(),t._planeScene=null})))),this._dragPlane=e.Mesh.CreatePlane("pointerDragPlane",this._debugMode?1:1e4,t._planeScene,!1,e.Mesh.DOUBLESIDE),this.lastDragPosition=new e.Vector3(0,0,0);var n=new e.Vector3(0,0,0),o=0,s=new e.Vector3(0,0,0),a=function(e){return r._attachedNode==e||e.isDescendantOf(r._attachedNode)},l=null;this._pointerObserver=this._scene.onPointerObservable.add((function(t,i){if(r.enabled)if(t.type==e.PointerEventTypes.POINTERDOWN){if(!r.dragging&&t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh&&t.pickInfo.pickedPoint&&t.pickInfo.ray&&a(t.pickInfo.pickedMesh)){r._updateDragPlanePosition(t.pickInfo.ray,t.pickInfo.pickedPoint);var c=r._pickWithRayOnDragPlane(t.pickInfo.ray);c&&(r.dragging=!0,r.currentDraggingPointerID=t.event.pointerId,r.lastDragPosition.copyFrom(c),r.onDragStartObservable.notifyObservers({dragPlanePoint:c,pointerId:r.currentDraggingPointerID}),s.copyFrom(r._attachedNode.absolutePosition),r.detachCameraControls&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&(r._scene.activeCamera.inputs.attachedElement?(l=r._scene.activeCamera.inputs.attachedElement,r._scene.activeCamera.detachControl(r._scene.activeCamera.inputs.attachedElement)):l=null))}}else if(t.type==e.PointerEventTypes.POINTERUP)r.currentDraggingPointerID==t.event.pointerId&&(r.releaseDrag(),r.detachCameraControls&&l&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&r._scene.activeCamera.attachControl(l,!0));else if(t.type==e.PointerEventTypes.POINTERMOVE&&r.currentDraggingPointerID==t.event.pointerId&&r.dragging&&t.pickInfo&&t.pickInfo.ray){r._moving=!0;var c=r._pickWithRayOnDragPlane(t.pickInfo.ray);c&&(r.updateDragPlane&&r._updateDragPlanePosition(t.pickInfo.ray,c),r._options.dragAxis?(e.Vector3.TransformCoordinatesToRef(r._options.dragAxis,r._attachedNode.getWorldMatrix().getRotationMatrix(),r._worldDragAxis),c.subtractToRef(r.lastDragPosition,r._tmpVector),o=e.Vector3.Dot(r._tmpVector,r._worldDragAxis),r._worldDragAxis.scaleToRef(o,n)):(o=n.length(),c.subtractToRef(r.lastDragPosition,n)),s.addInPlace(n),r.onDragObservable.notifyObservers({dragDistance:o,delta:n,dragPlanePoint:c,dragPlaneNormal:r._dragPlane.forward,pointerId:r.currentDraggingPointerID}),r.lastDragPosition.copyFrom(c))}})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((function(){r._moving&&r.moveAttached&&(s.subtractToRef(r._attachedNode.absolutePosition,r._tmpVector),r._tmpVector.scaleInPlace(.2),r._attachedNode.getAbsolutePosition().addToRef(r._tmpVector,r._tmpVector),r._attachedNode.setAbsolutePosition(r._tmpVector))}))},t.prototype.releaseDrag=function(){this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerID}),this.currentDraggingPointerID=-1,this._moving=!1},t.prototype._pickWithRayOnDragPlane=function(i){var r=this;if(!i)return null;var n=Math.acos(e.Vector3.Dot(this._dragPlane.forward,i.direction));if(n>Math.PI/2&&(n=Math.PI-n),this.maxDragAngle>0&&n>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(i.direction),this._attachedNode.absolutePosition.subtractToRef(i.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(-2*e.Vector3.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);var o=e.Vector3.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-o,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition),this._alternatePickedPoint}return null}var s=t._planeScene.pickWithRay(i,(function(e){return e==r._dragPlane}));return s&&s.hit&&s.pickedMesh&&s.pickedPoint?s.pickedPoint:null},t.prototype._updateDragPlanePosition=function(t,i){this._pointA.copyFrom(i),this._options.dragAxis?(this.useObjectOrienationForDragging?e.Vector3.TransformCoordinatesToRef(this._options.dragAxis,this._attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),this._pointA.addToRef(this._localAxis,this._pointB),t.origin.subtractToRef(this._pointA,this._pointC),this._pointA.addToRef(this._pointC.normalize(),this._pointC),this._pointB.subtractToRef(this._pointA,this._lineA),this._pointC.subtractToRef(this._pointA,this._lineB),e.Vector3.CrossToRef(this._lineA,this._lineB,this._lookAt),e.Vector3.CrossToRef(this._lineA,this._lookAt,this._lookAt),this._lookAt.normalize(),this._dragPlane.position.copyFrom(this._pointA),this._pointA.subtractToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrienationForDragging?e.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal,this._attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.subtractToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(t.origin)),this._dragPlane.computeWorldMatrix(!0)},t.prototype.detach=function(){this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver)},t})();e.PointerDragBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._startDistance=0,this._initialScale=new e.Vector3(0,0,0),this._targetScale=new e.Vector3(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new e.PointerDragBehavior({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new e.PointerDragBehavior({}),this._dragBehaviorB.moveAttached=!1}return Object.defineProperty(t.prototype,"name",{get:function(){return"MultiPointerScale"},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype._getCurrentDistance=function(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()},t.prototype.attach=function(e){var t=this;this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add((function(i){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerID==t._dragBehaviorB.currentDraggingPointerID?t._dragBehaviorA.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))})),this._dragBehaviorB.onDragStartObservable.add((function(i){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerID==t._dragBehaviorB.currentDraggingPointerID?t._dragBehaviorB.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))})),[this._dragBehaviorA,this._dragBehaviorB].forEach((function(e){e.onDragObservable.add((function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var e=t._getCurrentDistance()/t._startDistance;t._initialScale.scaleToRef(e,t._targetScale)}}))})),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var i=t._targetScale.subtract(e.scaling).scaleInPlace(.1);i.length()>.01&&e.scaling.addInPlace(i)}}))},t.prototype.detach=function(){var e=this;this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach((function(t){t.onDragStartObservable.clear(),t.onDragObservable.clear(),e._ownerNode.removeBehavior(t)}))},t})();e.MultiPointerScaleBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._sceneRenderObserver=null,this._targetPosition=new e.Vector3(0,0,0),this._moving=!1,this._startingOrientation=new e.Quaternion,this.zDragFactor=3,this.dragging=!1,this.dragDeltaRatio=.2,this.currentDraggingPointerID=-1,this.detachCameraControls=!0}return Object.defineProperty(t.prototype,"name",{get:function(){return"SixDofDrag"},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(i){var r=this;this._ownerNode=i,this._scene=this._ownerNode.getScene(),t._virtualScene||(t._virtualScene=new e.Scene(this._scene.getEngine()),this._scene.getEngine().scenes.pop());var n=null,o=new e.Vector3(0,0,0);this._virtualOriginMesh=new e.AbstractMesh("",t._virtualScene),this._virtualOriginMesh.rotationQuaternion=new e.Quaternion,this._virtualDragMesh=new e.AbstractMesh("",t._virtualScene),this._virtualDragMesh.rotationQuaternion=new e.Quaternion;var s=function(e){return r._ownerNode==e||e.isDescendantOf(r._ownerNode)},a=null;this._pointerObserver=this._scene.onPointerObservable.add((function(t,i){if(t.type==e.PointerEventTypes.POINTERDOWN){if(!r.dragging&&t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh&&t.pickInfo.ray&&s(t.pickInfo.pickedMesh)){r._scene.activeCamera&&r._scene.activeCamera.cameraRigMode==e.Camera.RIG_MODE_NONE&&t.pickInfo.ray.origin.copyFrom(r._scene.activeCamera.position),n=r._ownerNode,o.copyFrom(t.pickInfo.ray.origin),r._virtualOriginMesh.position.copyFrom(t.pickInfo.ray.origin),r._virtualOriginMesh.lookAt(t.pickInfo.ray.origin.subtract(t.pickInfo.ray.direction)),r._virtualOriginMesh.removeChild(r._virtualDragMesh),r._virtualDragMesh.position.copyFrom(n.absolutePosition),n.rotationQuaternion||(n.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(n.rotation.y,n.rotation.x,n.rotation.z));var l=n.parent;n.setParent(null),r._virtualDragMesh.rotationQuaternion.copyFrom(n.rotationQuaternion),n.setParent(l),r._virtualOriginMesh.addChild(r._virtualDragMesh),r._targetPosition.copyFrom(r._virtualDragMesh.absolutePosition),r.dragging=!0,r.currentDraggingPointerID=t.event.pointerId,r.detachCameraControls&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&(r._scene.activeCamera.inputs.attachedElement?(a=r._scene.activeCamera.inputs.attachedElement,r._scene.activeCamera.detachControl(r._scene.activeCamera.inputs.attachedElement)):a=null)}}else if(t.type==e.PointerEventTypes.POINTERUP)r.currentDraggingPointerID==t.event.pointerId&&(r.dragging=!1,r._moving=!1,r.currentDraggingPointerID=-1,n=null,r._virtualOriginMesh.removeChild(r._virtualDragMesh),r.detachCameraControls&&a&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&r._scene.activeCamera.attachControl(a,!0));else if(t.type==e.PointerEventTypes.POINTERMOVE&&r.currentDraggingPointerID==t.event.pointerId&&r.dragging&&t.pickInfo&&t.pickInfo.ray&&n){var c=r.zDragFactor;r._scene.activeCamera&&r._scene.activeCamera.cameraRigMode==e.Camera.RIG_MODE_NONE&&(t.pickInfo.ray.origin.copyFrom(r._scene.activeCamera.position),c=0);var h=t.pickInfo.ray.origin.subtract(o);o.copyFrom(t.pickInfo.ray.origin);var u=-e.Vector3.Dot(h,t.pickInfo.ray.direction);r._virtualOriginMesh.addChild(r._virtualDragMesh),r._virtualDragMesh.position.z-=r._virtualDragMesh.position.z<1?u*r.zDragFactor:u*c*r._virtualDragMesh.position.z,r._virtualDragMesh.position.z<0&&(r._virtualDragMesh.position.z=0),r._virtualOriginMesh.position.copyFrom(t.pickInfo.ray.origin),r._virtualOriginMesh.lookAt(t.pickInfo.ray.origin.subtract(t.pickInfo.ray.direction)),r._virtualOriginMesh.removeChild(r._virtualDragMesh),r._targetPosition.copyFrom(r._virtualDragMesh.absolutePosition),n.parent&&e.Vector3.TransformCoordinatesToRef(r._targetPosition,e.Matrix.Invert(n.parent.getWorldMatrix()),r._targetPosition),r._moving||r._startingOrientation.copyFrom(r._virtualDragMesh.rotationQuaternion),r._moving=!0}}));var l=new e.Quaternion;this._sceneRenderObserver=i.getScene().onBeforeRenderObservable.add((function(){if(r.dragging&&r._moving&&n){n.position.addInPlace(r._targetPosition.subtract(n.position).scale(r.dragDeltaRatio)),l.copyFrom(r._startingOrientation),l.x=-l.x,l.y=-l.y,l.z=-l.z,r._virtualDragMesh.rotationQuaternion.multiplyToRef(l,l),e.Quaternion.RotationYawPitchRollToRef(l.toEulerAngles("xyz").y,0,0,l),l.multiplyToRef(r._startingOrientation,l);var t=n.parent;n.setParent(null),e.Quaternion.SlerpToRef(n.rotationQuaternion,l,r.dragDeltaRatio,n.rotationQuaternion),n.setParent(t)}}))},t.prototype.detach=function(){this._scene&&this._scene.onPointerObservable.remove(this._pointerObserver),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualOriginMesh&&this._virtualOriginMesh.dispose(),this._virtualDragMesh&&this._virtualDragMesh.dispose()},t})();e.SixDofDragBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n){void 0===i&&(i=new e.Vector3),void 0===r&&(r=0),void 0===n&&(n=!1),this.direction=t,this.rotatedDirection=i,this.diff=r,this.ignore=n}return t})(),i=(function(){function i(i){this.ui=i,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new t(e.Vector3.Up()),new t(e.Vector3.Down()),new t(e.Vector3.Left()),new t(e.Vector3.Right()),new t(e.Vector3.Forward()),new t(e.Vector3.Forward().scaleInPlace(-1))],this._tmpMatrix=new e.Matrix,this._tmpVector=new e.Vector3,this._zeroVector=e.Vector3.Zero(),this._lookAtTmpMatrix=new e.Matrix}return i.prototype.init=function(){},i.prototype._closestFace=function(t){var i=this;return this._faceVectors.forEach((function(r){i._target.rotationQuaternion||(i._target.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(i._target.rotation.y,i._target.rotation.x,i._target.rotation.z)),i._target.rotationQuaternion.toRotationMatrix(i._tmpMatrix),e.Vector3.TransformCoordinatesToRef(r.direction,i._tmpMatrix,r.rotatedDirection),r.diff=e.Vector3.GetAngleBetweenVectors(r.rotatedDirection,t,e.Vector3.Cross(r.rotatedDirection,t))})),this._faceVectors.reduce((function(e,t){return e.ignore?t:t.ignore?e:e.diffo.snapDistance){var t=Math.floor(Math.abs(u)/o.snapDistance);u%=o.snapDistance,e.delta.normalizeToRef(d),d.scaleInPlace(o.snapDistance*t),o.attachedMesh.position.addInPlace(d),f.snapDistance=o.snapDistance*t,o.onSnapObservable.notifyObservers(f)}})),o._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e,t){if(!o._customMeshSet){var i=e.pickInfo&&-1!=o._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh),r=i?a:s;o._rootMesh.getChildMeshes().forEach((function(e){e.material=r,e.color&&(e.color=r.emissiveColor)}))}})),o}return o(i,t),i.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),t.prototype.dispose.call(this)},i})(e.Gizmo);e.AxisDragGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n){void 0===r&&(r=e.Color3.Gray()),void 0===n&&(n=e.UtilityLayerRenderer.DefaultUtilityLayer);var o=t.call(this,n)||this;o._pointerObserver=null,o.snapDistance=0,o.onSnapObservable=new e.Observable;var s=new e.StandardMaterial("",n.utilityLayerScene);s.disableLighting=!0,s.emissiveColor=r;var a=new e.StandardMaterial("",n.utilityLayerScene);a.disableLighting=!0,a.emissiveColor=r.add(new e.Color3(.2,.2,.2));var l=new e.AbstractMesh("",n.utilityLayerScene),c=e.MeshBuilder.CreateBox("yPosMesh",{size:.4},n.utilityLayerScene),h=e.MeshBuilder.CreateLines("yPosMesh",{points:[new e.Vector3(0,0,0),new e.Vector3(0,1.5,0)]},n.utilityLayerScene);h.color=s.emissiveColor,l.addChild(c),l.addChild(h),c.scaling.scaleInPlace(.1),c.material=s,c.rotation.x=Math.PI/2,c.position.z+=.3,h.scaling.scaleInPlace(.2),h.rotation.x=Math.PI/2,h.material=s,l.lookAt(o._rootMesh.position.subtract(i)),o._rootMesh.addChild(l),o.dragBehavior=new e.PointerDragBehavior({dragAxis:i}),o.dragBehavior.moveAttached=!1,o._rootMesh.addBehavior(o.dragBehavior);var u=0,d=new e.Vector3,f={snapDistance:0};return o.dragBehavior.onDragObservable.add((function(e){if(o.attachedMesh){var t=!1,r=0;0==o.snapDistance?i.scaleToRef(e.dragDistance,d):(u+=e.dragDistance,Math.abs(u)>o.snapDistance?(r=Math.floor(u/o.snapDistance),u%=o.snapDistance,i.scaleToRef(o.snapDistance*r,d),t=!0):d.scaleInPlace(0)),o.attachedMesh.scaling.addInPlace(d),t&&(f.snapDistance=o.snapDistance*r,o.onSnapObservable.notifyObservers(f))}})),o._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e,t){if(!o._customMeshSet){var i=e.pickInfo&&-1!=o._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh),r=i?a:s;o._rootMesh.getChildMeshes().forEach((function(e){e.material=r,e.color&&(e.color=r.emissiveColor)}))}})),o}return o(i,t),i.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),t.prototype.dispose.call(this)},i})(e.Gizmo);e.AxisScaleGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n){void 0===r&&(r=e.Color3.Gray()),void 0===n&&(n=e.UtilityLayerRenderer.DefaultUtilityLayer);var o=t.call(this,n)||this;o._pointerObserver=null,o.snapDistance=0,o.onSnapObservable=new e.Observable;var s=new e.StandardMaterial("",n.utilityLayerScene);s.disableLighting=!0,s.emissiveColor=r;var a=new e.StandardMaterial("",n.utilityLayerScene);a.disableLighting=!0,a.emissiveColor=r.add(new e.Color3(.2,.2,.2));for(var l=new e.AbstractMesh("",n.utilityLayerScene),c=new Array,h=0;h<20;h++){var u=2*Math.PI*(h/19);c.push(new e.Vector3(2*Math.sin(u),0,2*Math.cos(u)))}var d=e.Mesh.CreateLines("",c,n.utilityLayerScene);d.color=s.emissiveColor,d.scaling.scaleInPlace(.1),d.material=s,d.rotation.x=Math.PI/2,l.addChild(d),l.lookAt(o._rootMesh.position.subtract(i)),o._rootMesh.addChild(l),o.dragBehavior=new e.PointerDragBehavior({dragPlaneNormal:i}),o.dragBehavior.moveAttached=!1,o.dragBehavior.maxDragAngle=9*Math.PI/20,o.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,o._rootMesh.addBehavior(o.dragBehavior);var f=new e.Vector3;o.dragBehavior.onDragStartObservable.add((function(e){o.attachedMesh&&f.copyFrom(e.dragPlanePoint)}));var p=new e.Matrix,_=new e.Vector3,m=new e.Vector3,g={snapDistance:0},v=0;return o.dragBehavior.onDragObservable.add((function(t){if(o.attachedMesh){o.attachedMesh.rotationQuaternion||(o.attachedMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(o.attachedMesh.rotation.y,o.attachedMesh.rotation.x,o.attachedMesh.rotation.z));var r=t.dragPlanePoint.subtract(o.attachedMesh.position).normalize(),s=f.subtract(o.attachedMesh.position).normalize(),a=e.Vector3.Cross(r,s),l=e.Vector3.Dot(r,s),c=Math.atan2(a.length(),l);if(_.copyFrom(i),m.copyFrom(i),o.updateGizmoRotationToMatchAttachedMesh&&(o.attachedMesh.rotationQuaternion.toRotationMatrix(p),m=e.Vector3.TransformCoordinates(_,p)),n.utilityLayerScene.activeCamera){var h=n.utilityLayerScene.activeCamera.position.subtract(o.attachedMesh.position);e.Vector3.Dot(h,m)>0&&(_.scaleInPlace(-1),m.scaleInPlace(-1))}e.Vector3.Dot(m,a)>0&&(c=-c);var u=!1;if(0!=o.snapDistance)if(v+=c,Math.abs(v)>o.snapDistance){var d=Math.floor(v/o.snapDistance);v%=o.snapDistance,c=o.snapDistance*d,u=!0}else c=0;var y=Math.sin(c/2),b=new e.Quaternion(_.x*y,_.y*y,_.z*y,Math.cos(c/2));o.updateGizmoRotationToMatchAttachedMesh?o.attachedMesh.rotationQuaternion.multiplyToRef(b,o.attachedMesh.rotationQuaternion):b.multiplyToRef(o.attachedMesh.rotationQuaternion,o.attachedMesh.rotationQuaternion),f.copyFrom(t.dragPlanePoint),u&&(g.snapDistance=c,o.onSnapObservable.notifyObservers(g))}})),o._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e,t){if(!o._customMeshSet){var i=e.pickInfo&&-1!=o._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh),r=i?a:s;o._rootMesh.getChildMeshes().forEach((function(e){e.material=r,e.color&&(e.color=r.emissiveColor)}))}})),o}return o(i,t),i.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),t.prototype.dispose.call(this)},i})(e.Gizmo);e.PlaneRotationGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i){void 0===i&&(i=e.UtilityLayerRenderer.DefaultUtilityLayer);var r=t.call(this,i)||this;return r.xGizmo=new e.AxisDragGizmo(new e.Vector3(1,0,0),e.Color3.Green().scale(.5),i),r.yGizmo=new e.AxisDragGizmo(new e.Vector3(0,1,0),e.Color3.Red().scale(.5),i),r.zGizmo=new e.AxisDragGizmo(new e.Vector3(0,0,1),e.Color3.Blue().scale(.5),i),r.attachedMesh=null,r}return o(i,t),Object.defineProperty(i.prototype,"attachedMesh",{set:function(e){this.xGizmo&&(this.xGizmo.attachedMesh=e,this.yGizmo.attachedMesh=e,this.zGizmo.attachedMesh=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!0,configurable:!0}),i.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose()},i.prototype.setCustomMesh=function(t){e.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")},i})(e.Gizmo);e.PositionGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i){void 0===i&&(i=e.UtilityLayerRenderer.DefaultUtilityLayer);var r=t.call(this,i)||this;return r.xGizmo=new e.PlaneRotationGizmo(new e.Vector3(1,0,0),e.Color3.Green().scale(.5),i),r.yGizmo=new e.PlaneRotationGizmo(new e.Vector3(0,1,0),e.Color3.Red().scale(.5),i),r.zGizmo=new e.PlaneRotationGizmo(new e.Vector3(0,0,1),e.Color3.Blue().scale(.5),i),r.attachedMesh=null,r}return o(i,t),Object.defineProperty(i.prototype,"attachedMesh",{set:function(e){this.xGizmo&&(this.xGizmo.attachedMesh=e,this.yGizmo.attachedMesh=e,this.zGizmo.attachedMesh=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!0,configurable:!0}),i.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose()},i.prototype.setCustomMesh=function(t){e.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")},i})(e.Gizmo);e.RotationGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i){void 0===i&&(i=e.UtilityLayerRenderer.DefaultUtilityLayer);var r=t.call(this,i)||this;return r.xGizmo=new e.AxisScaleGizmo(new e.Vector3(1,0,0),e.Color3.Green().scale(.5),i),r.yGizmo=new e.AxisScaleGizmo(new e.Vector3(0,1,0),e.Color3.Red().scale(.5),i),r.zGizmo=new e.AxisScaleGizmo(new e.Vector3(0,0,1),e.Color3.Blue().scale(.5),i),r.attachedMesh=null,r}return o(i,t),Object.defineProperty(i.prototype,"attachedMesh",{set:function(e){this.xGizmo&&(this.xGizmo.attachedMesh=e,this.yGizmo.attachedMesh=e,this.zGizmo.attachedMesh=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!0,configurable:!0}),i.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose()},i})(e.Gizmo);e.ScaleGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r){void 0===i&&(i=e.Color3.Gray()),void 0===r&&(r=e.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer);var n=t.call(this,r)||this;n._boundingDimensions=new e.Vector3(1,1,1),n._renderObserver=null,n._pointerObserver=null,n._scaleDragSpeed=.2,n._tmpQuaternion=new e.Quaternion,n._tmpVector=new e.Vector3(0,0,0),n.rotationSphereSize=.1,n.scaleBoxSize=.1,n.fixedDragMeshScreenSize=!1,n.fixedDragMeshScreenSizeDistanceFactor=10,n.onDragStartObservable=new e.Observable,n.onDragObservable=new e.Observable,n.onDragEndObservable=new e.Observable,n._existingMeshScale=new e.Vector3,n._updateScale=!1,n._anchorMesh=new e.AbstractMesh("anchor",r.utilityLayerScene);var o=new e.StandardMaterial("",r.utilityLayerScene);o.disableLighting=!0,o.emissiveColor=i;var s=new e.StandardMaterial("",r.utilityLayerScene);s.disableLighting=!0,s.emissiveColor=i.clone().add(new e.Color3(.2,.2,.2)),n._lineBoundingBox=new e.AbstractMesh("",r.utilityLayerScene),n._lineBoundingBox.rotationQuaternion=new e.Quaternion;var a=[];a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,0),new e.Vector3(n._boundingDimensions.x,0,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,0),new e.Vector3(0,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,0),new e.Vector3(0,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,0,0),new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,0,0),new e.Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,n._boundingDimensions.y,0),new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,n._boundingDimensions.y,0),new e.Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,n._boundingDimensions.z),new e.Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,n._boundingDimensions.z),new e.Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new e.Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new e.Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.forEach((function(t){t.color=i,t.position.addInPlace(new e.Vector3(-n._boundingDimensions.x/2,-n._boundingDimensions.y/2,-n._boundingDimensions.z/2)),t.isPickable=!1,n._lineBoundingBox.addChild(t)})),n._rootMesh.addChild(n._lineBoundingBox),n._rotateSpheresParent=new e.AbstractMesh("",r.utilityLayerScene),n._rotateSpheresParent.rotationQuaternion=new e.Quaternion;for(var l,c=this,h=0;h<12;h++)!(function(t){var i=e.MeshBuilder.CreateSphere("",{diameter:1},r.utilityLayerScene);i.rotationQuaternion=new e.Quaternion,i.material=o,l=new e.PointerDragBehavior({}),l.moveAttached=!1,l.updateDragPlane=!1,i.addBehavior(l);var s=new e.Vector3(1,0,0),a=0;l.onDragStartObservable.add((function(e){s.copyFrom(i.forward),a=0})),l.onDragObservable.add((function(i){if(n.onDragObservable.notifyObservers({}),n.attachedMesh){var r=s,o=i.dragPlaneNormal.scale(e.Vector3.Dot(i.dragPlaneNormal,r)),l=r.subtract(o).normalizeToNew(),c=-e.Vector3.Dot(l,i.delta);c=c/n._boundingDimensions.length()*n._anchorMesh.scaling.length(),n.attachedMesh.rotationQuaternion||(n.attachedMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(n.attachedMesh.rotation.y,n.attachedMesh.rotation.x,n.attachedMesh.rotation.z)),n._anchorMesh.rotationQuaternion||(n._anchorMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(n._anchorMesh.rotation.y,n._anchorMesh.rotation.x,n._anchorMesh.rotation.z)),a+=c,Math.abs(a)<=2*Math.PI&&(t>=8?e.Quaternion.RotationYawPitchRollToRef(0,0,c,n._tmpQuaternion):t>=4?e.Quaternion.RotationYawPitchRollToRef(c,0,0,n._tmpQuaternion):e.Quaternion.RotationYawPitchRollToRef(0,c,0,n._tmpQuaternion),n._anchorMesh.addChild(n.attachedMesh),n._anchorMesh.rotationQuaternion.multiplyToRef(n._tmpQuaternion,n._anchorMesh.rotationQuaternion),n._anchorMesh.removeChild(n.attachedMesh)),n.updateBoundingBox()}})),l.onDragStartObservable.add((function(){n.onDragStartObservable.notifyObservers({}),n._selectNode(i)})),l.onDragEndObservable.add((function(){n.onDragEndObservable.notifyObservers({}),n._selectNode(null)})),c._rotateSpheresParent.addChild(i)})(h);n._rootMesh.addChild(n._rotateSpheresParent),n._scaleBoxesParent=new e.AbstractMesh("",r.utilityLayerScene),n._scaleBoxesParent.rotationQuaternion=new e.Quaternion;for(var u=0;u<2;u++)for(var d=0;d<2;d++)for(var l,f=this,p=0;p<2;p++)!(function(){var t=e.MeshBuilder.CreateBox("",{size:1},r.utilityLayerScene);t.material=o;var i=new e.Vector3(0==u?-1:1,0==d?-1:1,0==p?-1:1);l=new e.PointerDragBehavior({dragAxis:i}),l.moveAttached=!1,t.addBehavior(l),l.onDragObservable.add((function(i){if(n.onDragObservable.notifyObservers({}),n.attachedMesh){var r=i.dragDistance/n._boundingDimensions.length()*n._anchorMesh.scaling.length(),o=new e.Vector3(r,r,r);o.scaleInPlace(n._scaleDragSpeed),n.updateBoundingBox(),t.absolutePosition.subtractToRef(n._anchorMesh.position,n._tmpVector),n._anchorMesh.position.subtractInPlace(n._tmpVector),n._anchorMesh.addChild(n.attachedMesh),n._anchorMesh.scaling.addInPlace(o),(n._anchorMesh.scaling.x<0||n._anchorMesh.scaling.y<0||n._anchorMesh.scaling.z<0)&&n._anchorMesh.scaling.subtractInPlace(o),n._anchorMesh.removeChild(n.attachedMesh)}})),l.onDragStartObservable.add((function(){n.onDragStartObservable.notifyObservers({}),n._selectNode(t)})),l.onDragEndObservable.add((function(){n.onDragEndObservable.notifyObservers({}),n._selectNode(null)})),f._scaleBoxesParent.addChild(t)})();n._rootMesh.addChild(n._scaleBoxesParent);var _=new Array;return n._pointerObserver=r.utilityLayerScene.onPointerObservable.add((function(e,t){_[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=_[e.event.pointerId]&&(_[e.event.pointerId].material=o,delete _[e.event.pointerId]):n._rotateSpheresParent.getChildMeshes().concat(n._scaleBoxesParent.getChildMeshes()).forEach((function(t){e.pickInfo&&e.pickInfo.pickedMesh==t&&(_[e.event.pointerId]=t,t.material=s)}))})),n._renderObserver=n.gizmoLayer.originalScene.onBeforeRenderObservable.add((function(){n.attachedMesh&&!n._existingMeshScale.equals(n.attachedMesh.scaling)&&n.updateBoundingBox()})),n.updateBoundingBox(),n}return o(i,t),i.prototype._attachedMeshChanged=function(e){e&&(this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),this.updateBoundingBox())},i.prototype._selectNode=function(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((function(t,i){t.isVisible=!e||t==e}))},i.prototype._recurseComputeWorld=function(e){var t=this;e.computeWorldMatrix(!0),e.getChildMeshes().forEach((function(e){t._recurseComputeWorld(e)}))},i.prototype.updateBoundingBox=function(){if(this._update(),this.attachedMesh){this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);var t=this.attachedMesh.getHierarchyBoundingVectors();t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this._recurseComputeWorld(this.attachedMesh)}for(var i=this._rotateSpheresParent.getChildMeshes(),r=0;r<3;r++)for(var n=0;n<2;n++)for(var o=0;o<2;o++){var s=4*r+2*n+o;if(0==r&&(i[s].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*n,this._boundingDimensions.z*o),i[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),i[s].lookAt(e.Vector3.Cross(e.Vector3.Right(),i[s].position.normalizeToNew()).normalizeToNew().add(i[s].position))),1==r&&(i[s].position.set(this._boundingDimensions.x*n,this._boundingDimensions.y/2,this._boundingDimensions.z*o),i[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),i[s].lookAt(e.Vector3.Cross(e.Vector3.Up(),i[s].position.normalizeToNew()).normalizeToNew().add(i[s].position))),2==r&&(i[s].position.set(this._boundingDimensions.x*n,this._boundingDimensions.y*o,this._boundingDimensions.z/2),i[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),i[s].lookAt(e.Vector3.Cross(e.Vector3.Forward(),i[s].position.normalizeToNew()).normalizeToNew().add(i[s].position))),this.fixedDragMeshScreenSize){this._rootMesh.computeWorldMatrix(),this._rotateSpheresParent.computeWorldMatrix(),i[s].computeWorldMatrix(),i[s].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var a=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;i[s].scaling.set(a,a,a)}else i[s].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}for(var l=this._scaleBoxesParent.getChildMeshes(),r=0;r<2;r++)for(var n=0;n<2;n++)for(var o=0;o<2;o++){var s=4*r+2*n+o;if(l[s])if(l[s].position.set(this._boundingDimensions.x*r,this._boundingDimensions.y*n,this._boundingDimensions.z*o),l[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize){this._rootMesh.computeWorldMatrix(),this._scaleBoxesParent.computeWorldMatrix(),l[s].computeWorldMatrix(),l[s].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var a=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;l[s].scaling.set(a,a,a)}else l[s].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize)}this.attachedMesh&&this._existingMeshScale.copyFrom(this.attachedMesh.scaling)},i.prototype.setEnabledRotationAxis=function(e){this._rotateSpheresParent.getChildMeshes().forEach((function(t,i){i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))}))},i.prototype.dispose=function(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),t.prototype.dispose.call(this)},i.MakeNotPickableAndWrapInBoundingBox=function(t){var i=function(e){e.isPickable=!1,e.getChildMeshes().forEach((function(e){i(e)}))};i(t),t.rotationQuaternion||(t.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(t.rotation.y,t.rotation.x,t.rotation.z));var r=t.position.clone(),n=t.rotationQuaternion.clone();t.rotationQuaternion.set(0,0,0,1),t.position.set(0,0,0);var o=e.MeshBuilder.CreateBox("box",{size:1},t.getScene()),s=t.getHierarchyBoundingVectors();return s.max.subtractToRef(s.min,o.scaling),o.position.set((s.max.x+s.min.x)/2,(s.max.y+s.min.y)/2,(s.max.z+s.min.z)/2),t.addChild(o),t.rotationQuaternion.copyFrom(n),t.position.copyFrom(r),t.removeChild(o),o.addChild(t),o.visibility=0,o},i.prototype.setCustomMesh=function(t){e.Tools.Error("Custom meshes are not supported on this gizmo")},i})(e.Gizmo);e.BoundingBoxGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){var i=this;this.scene=t,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObserver=null,this._attachedMesh=null,this._boundingBoxColor=e.Color3.FromHexString("#0984e3"),this._dragBehavior=new e.SixDofDragBehavior,this.attachableMeshes=null,this.usePointerToAttachGizmos=!0,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null},this._pointerObserver=t.onPointerObservable.add((function(t,r){if(i.usePointerToAttachGizmos&&t.type==e.PointerEventTypes.POINTERDOWN)if(t.pickInfo&&t.pickInfo.pickedMesh){var n=t.pickInfo.pickedMesh;if(null==i.attachableMeshes)for(;n&&null!=n.parent;)n=n.parent;else{var o=!1;i.attachableMeshes.forEach((function(e){n&&(n==e||n.isDescendantOf(e))&&(n=e,o=!0)})),o||(n=null)}n instanceof e.AbstractMesh&&i.attachToMesh(n)}else i.attachToMesh(null)}))}return t.prototype.attachToMesh=function(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this._dragBehavior),this._attachedMesh=e;for(var t in this.gizmos){var i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this._dragBehavior)},Object.defineProperty(t.prototype,"positionGizmoEnabled",{get:function(){return this._gizmosEnabled.positionGizmo},set:function(t){t?(this.gizmos.positionGizmo=this.gizmos.positionGizmo||new e.PositionGizmo,this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh=!1,this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedMesh=null),this._gizmosEnabled.positionGizmo=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationGizmoEnabled",{get:function(){return this._gizmosEnabled.rotationGizmo},set:function(t){t?(this.gizmos.rotationGizmo=this.gizmos.rotationGizmo||new e.RotationGizmo,this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh=!1,this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedMesh=null),this._gizmosEnabled.rotationGizmo=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleGizmoEnabled",{get:function(){return this._gizmosEnabled.scaleGizmo},set:function(t){t?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new e.ScaleGizmo,this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedMesh=null),this._gizmosEnabled.scaleGizmo=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"boundingBoxGizmoEnabled",{get:function(){return this._gizmosEnabled.boundingBoxGizmo},set:function(t){t?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new e.BoundingBoxGizmo(this._boundingBoxColor),this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh,this._attachedMesh&&(this._attachedMesh.removeBehavior(this._dragBehavior),this._attachedMesh.addBehavior(this._dragBehavior))):this.gizmos.boundingBoxGizmo&&(this.gizmos.boundingBoxGizmo.attachedMesh=null),this._gizmosEnabled.boundingBoxGizmo=t},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.scene.onPointerObservable.remove(this._pointerObserver);for(var e in this.gizmos){var t=this.gizmos[e];t&&t.dispose()}this._dragBehavior.detach(),this._gizmoLayer.dispose()},t})();e.GizmoManager=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){void 0===i&&(i=0),void 0===r&&(r=null),this.name=t,this.animations=new Array,this._positions=null,this._normals=null,this._tangents=null,this.onInfluenceChanged=new e.Observable,this._animationPropertiesOverride=null,this._scene=r||e.Engine.LastCreatedScene,this.influence=i}return Object.defineProperty(t.prototype,"influence",{get:function(){return this._influence},set:function(e){if(this._influence!==e){var t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPositions",{get:function(){return!!this._positions},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasNormals",{get:function(){return!!this._normals},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasTangents",{get:function(){return!!this._tangents},enumerable:!0,configurable:!0}),t.prototype.setPositions=function(e){this._positions=e},t.prototype.getPositions=function(){return this._positions},t.prototype.setNormals=function(e){this._normals=e},t.prototype.getNormals=function(){return this._normals},t.prototype.setTangents=function(e){this._tangents=e},t.prototype.getTangents=function(){return this._tangents},t.prototype.serialize=function(){var t={};return t.name=this.name,t.influence=this.influence,t.positions=Array.prototype.slice.call(this.getPositions()),this.hasNormals&&(t.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(t.tangents=Array.prototype.slice.call(this.getTangents())), -e.Animation.AppendSerializedAnimations(this,t),t},t.Parse=function(i){var r=new t(i.name,i.influence);if(r.setPositions(i.positions),i.normals&&r.setNormals(i.normals),i.tangents&&r.setTangents(i.tangents),i.animations)for(var n=0;n=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetObservable.splice(t,1)[0]),this._syncActiveTargets(!0))},t.prototype.serialize=function(){var e={};e.id=this.uniqueId,e.targets=[];for(var t=0,i=this._targets;tthis.capacity&&this._depth=2&&t.onControllersAttachedObservable.notifyObservers(t.controllers)}}}))},i})(e.FreeCamera);e.WebVRFreeCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("DeviceOrientationCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n){var o=t.call(this,i,r,n)||this;return o._quaternionCache=new e.Quaternion,o.inputs.addDeviceOrientation(),o}return o(i,t),i.prototype.getClassName=function(){return"DeviceOrientationCamera"},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)},i.prototype.resetToCurrentRotation=function(t){var i=this;void 0===t&&(t=e.Axis.Y),this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new e.Quaternion),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((function(e){t[e]?i._initialQuaternion[e]*=-1:i._initialQuaternion[e]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))},i})(e.FreeCamera);e.DeviceOrientationCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s){void 0===o&&(o=!0), -void 0===s&&(s=e.VRCameraMetrics.GetDefault());var a=t.call(this,i,r,n)||this;return s.compensateDistortion=o,a.setCameraRigMode(e.Camera.RIG_MODE_VR,{vrCameraMetrics:s}),a}return o(i,t),i.prototype.getClassName=function(){return"VRDeviceOrientationFreeCamera"},i})(e.DeviceOrientationCamera);e.VRDeviceOrientationFreeCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera",(function(i,r){return function(){return new t(i,0,0,1,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s,a,l,c){void 0===l&&(l=!0),void 0===c&&(c=e.VRCameraMetrics.GetDefault());var h=t.call(this,i,r,n,o,s,a)||this;return c.compensateDistortion=l,h.setCameraRigMode(e.Camera.RIG_MODE_VR,{vrCameraMetrics:c}),h.inputs.addVRDeviceOrientation(),h}return o(i,t),i.prototype.getClassName=function(){return"VRDeviceOrientationArcRotateCamera"},i})(e.ArcRotateCamera);e.VRDeviceOrientationArcRotateCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s){void 0===o&&(o=!0),void 0===s&&(s=e.VRCameraMetrics.GetDefault());var a=t.call(this,i,r,n,o,s)||this;return a.inputs.addGamepad(),a}return o(i,t),i.prototype.getClassName=function(){return"VRDeviceOrientationGamepadCamera"},i})(e.VRDeviceOrientationFreeCamera);e.VRDeviceOrientationGamepadCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(i,r){if(void 0===r&&(r=null),this.scene=i,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=t._idCounter++,r)this._gazeTracker=r.clone("gazeTracker");else{this._gazeTracker=e.Mesh.CreateTorus("gazeTracker",.0035,.0025,20,i,!1),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;var n=new e.StandardMaterial("targetMat",i);n.specularColor=e.Color3.Black(),n.emissiveColor=new e.Color3(.7,.7,.7),n.backFaceCulling=!1,this._gazeTracker.material=n}}return t.prototype._getForwardRay=function(t){return new e.Ray(e.Vector3.Zero(),new e.Vector3(0,0,t))},t.prototype._selectionPointerDown=function(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})},t.prototype._selectionPointerUp=function(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1},t.prototype._activatePointer=function(){this._activePointer=!0},t.prototype._deactivatePointer=function(){this._activePointer=!1},t.prototype._updatePointerDistance=function(e){void 0===e&&(e=100)},t.prototype.dispose=function(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()},t._idCounter=0,t})(),i=(function(t){function i(i,r,n){var o=t.call(this,r,n)||this;o.webVRController=i,o._laserPointer=e.Mesh.CreateCylinder("laserPointer",1,.004,2e-4,20,1,r,!1);var s=new e.StandardMaterial("laserPointerMat",r);if(s.emissiveColor=new e.Color3(.7,.7,.7),s.alpha=.6,o._laserPointer.material=s,o._laserPointer.rotation.x=Math.PI/2,o._laserPointer.position.z=-.5,o._laserPointer.isVisible=!1,o._laserPointer.isPickable=!1,!i.mesh){var a=new e.Mesh("preloadControllerMesh",r),l=new e.Mesh(e.PoseEnabledController.POINTING_POSE,r);l.rotation.x=-.7,a.addChild(l),i.attachToMesh(a)}return o._setLaserPointerParent(i.mesh),o._meshAttachedObserver=i._meshAttachedObservable.add((function(e){o._setLaserPointerParent(e)})),o}return o(i,t),i.prototype._getForwardRay=function(e){return this.webVRController.getForwardRay(e)},i.prototype._activatePointer=function(){t.prototype._activatePointer.call(this),this._laserPointer.isVisible=!0},i.prototype._deactivatePointer=function(){t.prototype._deactivatePointer.call(this),this._laserPointer.isVisible=!1},i.prototype._setLaserPointerColor=function(e){this._laserPointer.material.emissiveColor=e},i.prototype._setLaserPointerParent=function(t){var i=function(e){e.isPickable=!1,e.getChildMeshes().forEach((function(e){i(e)}))};i(t);var r=t.getChildMeshes();this.webVRController._pointingPoseNode=null;for(var n=0;n=0){t=r[n],this.webVRController._pointingPoseNode=t;break}this._laserPointer.parent=t},i.prototype._updatePointerDistance=function(e){void 0===e&&(e=100),this._laserPointer.scaling.y=e,this._laserPointer.position.z=-e/2},i.prototype.dispose=function(){t.prototype.dispose.call(this),this._laserPointer.dispose(),this._meshAttachedObserver&&this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)},i})(t),r=(function(t){function i(e,i){var r=t.call(this,i)||this;return r.getCamera=e,r}return o(i,t),i.prototype._getForwardRay=function(t){var i=this.getCamera();return i?i.getForwardRay(t):new e.Ray(e.Vector3.Zero(),e.Vector3.Forward())},i})(t),n=(function(){function t(t,n){void 0===n&&(n={});var o=this;if(this.webVROptions=n,this._webVRsupported=!1,this._webVRready=!1,this._webVRrequesting=!1,this._webVRpresenting=!1,this._fullscreenVRpresenting=!1,this.onEnteringVRObservable=new e.Observable,this.onExitingVRObservable=new e.Observable,this.onControllerMeshLoadedObservable=new e.Observable,this._useCustomVRButton=!1,this._teleportationRequested=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._rotationAllowed=!0,this._teleportBackwardsVector=new e.Vector3(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new e.Vector3(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this.leftController=null,this.rightController=null,this.onNewMeshSelected=new e.Observable,this.onNewMeshPicked=new e.Observable,this.onBeforeCameraTeleport=new e.Observable,this.onAfterCameraTeleport=new e.Observable,this.onSelectedMeshUnselected=new e.Observable,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._interactionsRequested=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this._onResize=function(){o.moveButtonToBottomRight(),o._fullscreenVRpresenting&&o._webVRready&&o.exitVR()},this._onFullscreenChange=function(){void 0!==document.fullscreen?o._fullscreenVRpresenting=document.fullscreen:void 0!==document.mozFullScreen?o._fullscreenVRpresenting=document.mozFullScreen:void 0!==document.webkitIsFullScreen?o._fullscreenVRpresenting=document.webkitIsFullScreen:void 0!==document.msIsFullScreen?o._fullscreenVRpresenting=document.msIsFullScreen:void 0!==document.msFullscreenElement&&(o._fullscreenVRpresenting=document.msFullscreenElement),!o._fullscreenVRpresenting&&o._canvas&&(o.exitVR(),o._useCustomVRButton||(o._btnVR.style.top=o._canvas.offsetTop+o._canvas.offsetHeight-70+"px",o._btnVR.style.left=o._canvas.offsetLeft+o._canvas.offsetWidth-100+"px"))},this.beforeRender=function(){o.leftController&&o.leftController._activePointer&&o._castRayAndSelectObject(o.leftController),o.rightController&&o.rightController._activePointer&&o._castRayAndSelectObject(o.rightController),o._noControllerIsActive?o._castRayAndSelectObject(o._cameraGazer):o._cameraGazer._gazeTracker.isVisible=!1},this._onNewGamepadConnected=function(t){if(t.type!==e.Gamepad.POSE_ENABLED)t.leftStick&&t.onleftstickchanged((function(e){o._teleportationInitialized&&o.teleportationEnabled&&(!o.leftController&&!o.rightController||o.leftController&&!o.leftController._activePointer&&o.rightController&&!o.rightController._activePointer)&&(o._checkTeleportWithRay(e,o._cameraGazer),o._checkTeleportBackwards(e,o._cameraGazer))})),t.rightStick&&t.onrightstickchanged((function(e){o._teleportationInitialized&&o._checkRotate(e,o._cameraGazer)})),t.type===e.Gamepad.XBOX&&(t.onbuttondown((function(t){o._interactionsEnabled&&t===e.Xbox360Button.A&&o._cameraGazer._selectionPointerDown()})),t.onbuttonup((function(t){o._interactionsEnabled&&t===e.Xbox360Button.A&&o._cameraGazer._selectionPointerUp()})));else{var r=t,n=new i(r,o._scene,o._cameraGazer._gazeTracker);"right"===r.hand||o.leftController&&o.leftController.webVRController!=r?o.rightController=n:o.leftController=n,o._tryEnableInteractionOnController(n)}},this._tryEnableInteractionOnController=function(e){o._interactionsRequested&&!e._interactionsEnabled&&o._enableInteractionOnController(e),o._teleportationRequested&&!e._teleportationEnabled&&o._enableTeleportationOnController(e)},this._onNewGamepadDisconnected=function(t){t instanceof e.WebVRController&&("left"===t.hand&&null!=o.leftController&&(o.leftController.dispose(),o.leftController=null),"right"===t.hand&&null!=o.rightController&&(o.rightController.dispose(),o.rightController=null))},this._workingVector=e.Vector3.Zero(),this._workingQuaternion=e.Quaternion.Identity(),this._workingMatrix=e.Matrix.Identity(),this._scene=t,this._canvas=t.getEngine().getRenderingCanvas(),void 0===n.createFallbackVRDeviceOrientationFreeCamera&&(n.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===n.createDeviceOrientationCamera&&(n.createDeviceOrientationCamera=!0),void 0===n.laserToggle&&(n.laserToggle=!0),void 0===n.defaultHeight&&(n.defaultHeight=1.7),n.useCustomVRButton&&(this._useCustomVRButton=!0,n.customVRButton&&(this._btnVR=n.customVRButton)),n.rayLength&&(this._rayLength=n.rayLength),this._defaultHeight=n.defaultHeight,n.positionScale&&(this._rayLength*=n.positionScale,this._defaultHeight*=n.positionScale),this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new e.Vector3(0,this._defaultHeight,0),n.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new e.DeviceOrientationCamera("deviceOrientationVRHelper",this._position.clone(),t),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof e.TargetCamera&&this._scene.activeCamera.rotation)){var s=this._scene.activeCamera;s.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(s.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.Quaternion.RotationYawPitchRoll(s.rotation.y,s.rotation.x,s.rotation.z)),this._deviceOrientationCamera.rotation=s.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._canvas&&this._scene.activeCamera.attachControl(this._canvas)}else this._existingCamera=this._scene.activeCamera;if(n.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new e.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper",this._position,this._scene)),this._webVRCamera=new e.WebVRFreeCamera("WebVRHelper",this._position,this._scene,n),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new r(function(){return o.currentVRCamera},t),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";var a=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";a+=".babylonVRicon.vrdisplaypresenting { display: none; }";var l=document.createElement("style");l.appendChild(document.createTextNode(a)),document.getElementsByTagName("head")[0].appendChild(l),this.moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(function(){o.isInVRMode?o.exitVR():o.enterVR()})),window.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("mozfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("msfullscreenchange",this._onFullscreenChange,!1),document.onmsfullscreenchange=this._onFullscreenChange,n.createFallbackVRDeviceOrientationFreeCamera?this.displayVRButton():this._scene.getEngine().onVRDisplayChangedObservable.add((function(e){e.vrDisplay&&o.displayVRButton()})),this._onKeyDown=function(e){27===e.keyCode&&o.isInVRMode&&o.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((function(e,t){o.isInVRMode&&(o.exitVR(),o._fullscreenVRpresenting&&o._scene.getEngine().switchFullscreen(!0))}),e.PointerEventTypes.POINTERDOUBLETAP,!1),this._onVRDisplayChanged=function(e){return o.onVRDisplayChanged(e)},this._onVrDisplayPresentChange=function(){return o.onVrDisplayPresentChange()},this._onVRRequestPresentStart=function(){o._webVRrequesting=!0,o.updateButtonVisibility()},this._onVRRequestPresentComplete=function(e){o._webVRrequesting=!1,o.updateButtonVisibility()},t.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged),t.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),t.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),window.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),t.onDisposeObservable.add((function(){o.dispose()})),this._webVRCamera.onControllerMeshLoadedObservable.add((function(e){return o._onDefaultMeshLoaded(e)})),this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),this.updateButtonVisibility(),this._circleEase=new e.CircleEase,this._circleEase.setEasingMode(e.EasingFunction.EASINGMODE_EASEINOUT),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes})}return Object.defineProperty(t.prototype,"onEnteringVR",{get:function(){return this.onEnteringVRObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onExitingVR",{get:function(){return this.onExitingVRObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onControllerMeshLoaded",{get:function(){return this.onControllerMeshLoadedObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"teleportationTarget",{get:function(){return this._teleportationTarget},set:function(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gazeTrackerMesh",{get:function(){return this._cameraGazer._gazeTracker},set:function(e){e&&(this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker",this.leftController&&(this.leftController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")),this.rightController&&(this.rightController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayGaze",{get:function(){return this._displayGaze},set:function(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1,this.leftController&&(this.leftController._gazeTracker.isVisible=!1),this.rightController&&(this.rightController._gazeTracker.isVisible=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayLaserPointer",{get:function(){return this._displayLaserPointer},set:function(e){this._displayLaserPointer=e,e?(this.rightController&&this.rightController._activatePointer(),this.leftController&&this.leftController._activatePointer()):(this.rightController&&(this.rightController._deactivatePointer(),this.rightController._gazeTracker.isVisible=!1),this.leftController&&(this.leftController._deactivatePointer(),this.leftController._gazeTracker.isVisible=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"deviceOrientationCamera",{get:function(){return this._deviceOrientationCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentVRCamera",{get:function(){return this._webVRready?this._webVRCamera:this._scene.activeCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"webVRCamera",{get:function(){return this._webVRCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vrDeviceOrientationCamera",{get:function(){return this._vrDeviceOrientationCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_teleportationRequestInitiated",{get:function(){return this._cameraGazer._teleportationRequestInitiated||null!==this.leftController&&this.leftController._teleportationRequestInitiated||null!==this.rightController&&this.rightController._teleportationRequestInitiated},enumerable:!0,configurable:!0}),t.prototype._onDefaultMeshLoaded=function(t){this.leftController&&this.leftController.webVRController==t&&t.mesh&&this.leftController._setLaserPointerParent(t.mesh),this.rightController&&this.rightController.webVRController==t&&t.mesh&&this.rightController._setLaserPointerParent(t.mesh);try{this.onControllerMeshLoadedObservable.notifyObservers(t)}catch(t){e.Tools.Warn("Error in your custom logic onControllerMeshLoaded: "+t)}},Object.defineProperty(t.prototype,"isInVRMode",{get:function(){return this._webVRpresenting||this._fullscreenVRpresenting},enumerable:!0,configurable:!0}),t.prototype.onVrDisplayPresentChange=function(){var t=this._scene.getEngine().getVRDevice();if(t){var i=this._webVRpresenting;this._webVRpresenting=t.isPresenting,i&&!this._webVRpresenting&&this.exitVR()}else e.Tools.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");this.updateButtonVisibility()},t.prototype.onVRDisplayChanged=function(e){this._webVRsupported=e.vrSupported,this._webVRready=!!e.vrDisplay,this._webVRpresenting=e.vrDisplay&&e.vrDisplay.isPresenting,this.updateButtonVisibility()},t.prototype.moveButtonToBottomRight=function(){this._canvas&&!this._useCustomVRButton&&(this._btnVR.style.top=this._canvas.offsetTop+this._canvas.offsetHeight-70+"px",this._btnVR.style.left=this._canvas.offsetLeft+this._canvas.offsetWidth-100+"px")},t.prototype.displayVRButton=function(){this._useCustomVRButton||this._btnVRDisplayed||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)},t.prototype.updateButtonVisibility=function(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode?this._btnVR.className+=" vrdisplaypresenting":(this._webVRready&&(this._btnVR.className+=" vrdisplayready"),this._webVRsupported&&(this._btnVR.className+=" vrdisplaysupported"),this._webVRrequesting&&(this._btnVR.className+=" vrdisplayrequesting")))},t.prototype.enterVR=function(){if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(t){e.Tools.Warn("Error in your custom logic onEnteringVR: "+t)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this._existingCamera=this._scene.activeCamera),this._webVRrequesting||(this._webVRready?this._webVRpresenting||(this._webVRCamera.position=this._position,this._scene.activeCamera=this._webVRCamera):this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().switchFullscreen(!0),this.updateButtonVisibility()),this._scene.activeCamera&&this._canvas&&this._scene.activeCamera.attachControl(this._canvas),this._interactionsEnabled&&this._scene.registerBeforeRender(this.beforeRender))},t.prototype.exitVR=function(){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(t){e.Tools.Warn("Error in your custom logic onExitingVR: "+t)}this._webVRpresenting&&this._scene.getEngine().disableVR(),this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._canvas&&this._scene.activeCamera.attachControl(this._canvas)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera),this.updateButtonVisibility(),this._interactionsEnabled&&this._scene.unregisterBeforeRender(this.beforeRender),this._scene.getEngine().resize()},Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)},enumerable:!0,configurable:!0}),t.prototype.enableInteractions=function(){var e=this;this._interactionsEnabled||(this._interactionsRequested=!0,this.leftController&&this._enableInteractionOnController(this.leftController),this.rightController&&this._enableInteractionOnController(this.rightController),this.raySelectionPredicate=function(e){return e.isVisible&&e.isPickable},this.meshSelectionPredicate=function(e){return!0},this._raySelectionPredicate=function(t){return!!(e._isTeleportationFloor(t)||-1===t.name.indexOf("gazeTracker")&&-1===t.name.indexOf("teleportationTarget")&&-1===t.name.indexOf("torusTeleportation"))&&e.raySelectionPredicate(t)},this._interactionsEnabled=!0)},Object.defineProperty(t.prototype,"_noControllerIsActive",{get:function(){return!(this.leftController&&this.leftController._activePointer||this.rightController&&this.rightController._activePointer)},enumerable:!0,configurable:!0}),t.prototype._isTeleportationFloor=function(e){for(var t=0;t-1||this._floorMeshesCollection.push(e))},t.prototype.removeFloorMesh=function(e){if(this._floorMeshesCollection){var t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}},t.prototype.enableTeleportation=function(t){if(void 0===t&&(t={}),!this._teleportationInitialized){this._teleportationRequested=!0,this.enableInteractions(),t.floorMeshName&&(this._floorMeshName=t.floorMeshName),t.floorMeshes&&(this._floorMeshesCollection=t.floorMeshes),null!=this.leftController&&this._enableTeleportationOnController(this.leftController),null!=this.rightController&&this._enableTeleportationOnController(this.rightController);var i=new e.ImageProcessingConfiguration;i.vignetteColor=new e.Color4(0,0,0,0),i.vignetteEnabled=!0,this._postProcessMove=new e.ImageProcessingPostProcess("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,i),this._webVRCamera.detachPostProcess(this._postProcessMove),this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&(this._createTeleportationCircles(),this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))}},t.prototype._enableInteractionOnController=function(e){var t=this;e.webVRController.mesh&&(e._interactionsEnabled=!0,e._activatePointer(),this.webVROptions.laserToggle&&e.webVRController.onMainButtonStateChangedObservable.add((function(i){t._displayLaserPointer&&1===i.value&&(e._activePointer?e._deactivatePointer():e._activatePointer(),t.displayGaze&&(e._gazeTracker.isVisible=e._activePointer))})),e.webVRController.onTriggerStateChangedObservable.add((function(i){var r=e;t._noControllerIsActive&&(r=t._cameraGazer),r._pointerDownOnMeshAsked?i.valuet._padSensibilityUp&&r._selectionPointerDown()})))},t.prototype._checkTeleportWithRay=function(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))},t.prototype._checkTeleportBackwards=function(t,i){if(!i._teleportationRequestInitiated)if(t.y>this._padSensibilityUp&&i._dpadPressed){if(!i._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;var r=e.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),n=this.currentVRCamera.position;this.currentVRCamera.devicePosition&&this.currentVRCamera.deviceRotationQuaternion&&(r=this.currentVRCamera.deviceRotationQuaternion,n=this.currentVRCamera.devicePosition),r.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,e.Quaternion.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),e.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);var o=new e.Ray(n,this._workingVector),s=this._scene.pickWithRay(o,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this._teleportCamera(s.pickedPoint),i._teleportationBackRequestInitiated=!0}}else i._teleportationBackRequestInitiated=!1},t.prototype._enableTeleportationOnController=function(t){var i=this;t.webVRController.mesh&&(t._interactionsEnabled||this._enableInteractionOnController(t),t._interactionsEnabled=!0,t._teleportationEnabled=!0,t.webVRController.controllerType===e.PoseEnabledControllerType.VIVE&&(t._dpadPressed=!1,t.webVRController.onPadStateChangedObservable.add((function(e){t._dpadPressed=e.pressed,t._dpadPressed||(t._rotationLeftAsked=!1,t._rotationRightAsked=!1,t._teleportationBackRequestInitiated=!1)}))),t.webVRController.onPadValuesChangedObservable.add((function(e){i.teleportationEnabled&&(i._checkTeleportBackwards(e,t),i._checkTeleportWithRay(e,t)),i._checkRotate(e,t)})))},t.prototype._createTeleportationCircles=function(){this._teleportationTarget=e.Mesh.CreateGround("teleportationTarget",2,2,2,this._scene),this._teleportationTarget.isPickable=!1;var t=new e.DynamicTexture("DynamicTexture",512,this._scene,!0);t.hasAlpha=!0;var i=t.getContext();i.beginPath(),i.arc(256,256,200,0,2*Math.PI,!1),i.fillStyle=this._teleportationFillColor,i.fill(),i.lineWidth=10,i.strokeStyle=this._teleportationBorderColor,i.stroke(),i.closePath(),t.update();var r=new e.StandardMaterial("TextPlaneMaterial",this._scene);r.diffuseTexture=t,this._teleportationTarget.material=r;var n=e.Mesh.CreateTorus("torusTeleportation",.75,.1,25,this._scene,!1);n.isPickable=!1,n.parent=this._teleportationTarget;var o=new e.Animation("animationInnerCircle","position.y",30,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CYCLE),s=[];s.push({frame:0,value:0}),s.push({frame:30,value:.4}),s.push({frame:60,value:0}),o.setKeys(s);var a=new e.SineEase;a.setEasingMode(e.EasingFunction.EASINGMODE_EASEINOUT),o.setEasingFunction(a),n.animations=[],n.animations.push(o),this._scene.beginAnimation(n,0,60,!0),this._hideTeleportationTarget()},t.prototype._displayTeleportationTarget=function(){this._teleportActive=!0,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!0,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!0))},t.prototype._hideTeleportationTarget=function(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))},t.prototype._rotateCamera=function(t){var i=this;if(this.currentVRCamera instanceof e.FreeCamera){t?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];var r=e.Quaternion.FromRotationMatrix(e.Matrix.RotationY(Math.PI/4*this._rotationAngle)),n=new e.Animation("animationRotation","rotationQuaternion",90,e.Animation.ANIMATIONTYPE_QUATERNION,e.Animation.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),o.push({frame:6,value:r}),n.setKeys(o),n.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(n),this._postProcessMove.animations=[];var s=new e.Animation("animationPP","vignetteWeight",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:4}),a.push({frame:6,value:0}),s.setKeys(a),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);var l=new e.Animation("animationPP2","vignetteStretch",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),c=[];c.push({frame:0,value:0}),c.push({frame:3,value:10}),c.push({frame:6,value:0}),l.setKeys(c),l.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,6,!1,1,(function(){i._webVRCamera.detachPostProcess(i._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}},t.prototype._moveTeleportationSelectorTo=function(t,i,r){if(t.pickedPoint){i._teleportationRequestInitiated&&(this._displayTeleportationTarget(),this._haloCenter.copyFrom(t.pickedPoint),this._teleportationTarget.position.copyFrom(t.pickedPoint)) -;var n=this._convertNormalToDirectionOfRay(t.getNormal(!0,!1),r);if(n){var o=e.Vector3.Cross(e.Axis.Y,n),s=e.Vector3.Cross(n,o);e.Vector3.RotationFromAxisToRef(s,n,o,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}},t.prototype._teleportCamera=function(t){var i=this;if(this.currentVRCamera instanceof e.FreeCamera){this.webVRCamera.leftCamera?(this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),this._workingVector.subtractInPlace(this.webVRCamera.position),t.subtractToRef(this._workingVector,this._workingVector)):this._workingVector.copyFrom(t),this.isInVRMode?this._workingVector.y+=this.webVRCamera.deviceDistanceToRoomGround()*this._webVRCamera.deviceScaleFactor:this._workingVector.y+=this._defaultHeight,this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this.currentVRCamera.animations=[];var r=new e.Animation("animationCameraTeleportation","position",90,e.Animation.ANIMATIONTYPE_VECTOR3,e.Animation.ANIMATIONLOOPMODE_CONSTANT),n=[{frame:0,value:this.currentVRCamera.position},{frame:11,value:this._workingVector}];r.setKeys(n),r.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];var o=new e.Animation("animationPP","vignetteWeight",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:0}),s.push({frame:5,value:8}),s.push({frame:11,value:0}),o.setKeys(s),this._postProcessMove.animations.push(o);var a=new e.Animation("animationPP2","vignetteStretch",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:5,value:10}),l.push({frame:11,value:0}),a.setKeys(l),this._postProcessMove.animations.push(a),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,11,!1,1,(function(){i._webVRCamera.detachPostProcess(i._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,11,!1,1,(function(){i.onAfterCameraTeleport.notifyObservers(i._workingVector)})),this._hideTeleportationTarget()}},t.prototype._convertNormalToDirectionOfRay=function(t,i){if(t){Math.acos(e.Vector3.Dot(t,i.direction))i.halfWidth,t&&this._joystickPointerID<0?(this._joystickPointerID=e.pointerId,this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone(),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):i._globalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))},i.prototype._onPointerMove=function(e){if(this._joystickPointerID==e.pointerId){this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY,this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos);var i=this.reverseLeftRight?-1:1,r=i*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,r));break;case t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,r));break;case t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,r))}var n=this.reverseUpDown?1:-1,o=n*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,o));break;case t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,o));break;case t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,o))}}else{var s=this._touches.get(e.pointerId.toString());s&&(s.x=e.clientX,s.y=e.clientY)}},i.prototype._onPointerUp=function(e){if(this._joystickPointerID==e.pointerId)i.vjCanvasContext.clearRect(this._joystickPointerStartPos.x-64,this._joystickPointerStartPos.y-64,128,128),i.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x-42,this._joystickPreviousPointerPos.y-42,84,84),this._joystickPointerID=-1,this.pressed=!1;else{var t=this._touches.get(e.pointerId.toString());t&&i.vjCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(e.pointerId.toString())},i.prototype.setJoystickColor=function(e){this._joystickColor=e},i.prototype.setActionOnTouch=function(e){this._action=e},i.prototype.setAxisForLeftRight=function(e){switch(e){case t.X:case t.Y:case t.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=t.X}},i.prototype.setAxisForUpDown=function(e){switch(e){case t.X:case t.Y:case t.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=t.Y}},i.prototype._drawVirtualJoystick=function(){var e=this;this.pressed&&this._touches.forEach((function(t,r){r.pointerId===e._joystickPointerID?(i.vjCanvasContext.clearRect(e._joystickPointerStartPos.x-64,e._joystickPointerStartPos.y-64,128,128),i.vjCanvasContext.clearRect(e._joystickPreviousPointerPos.x-42,e._joystickPreviousPointerPos.y-42,84,84),i.vjCanvasContext.beginPath(),i.vjCanvasContext.lineWidth=6,i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.arc(e._joystickPointerStartPos.x,e._joystickPointerStartPos.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.lineWidth=2,i.vjCanvasContext.arc(e._joystickPointerStartPos.x,e._joystickPointerStartPos.y,60,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.arc(e._joystickPointerPos.x,e._joystickPointerPos.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),e._joystickPreviousPointerPos=e._joystickPointerPos.clone()):(i.vjCanvasContext.clearRect(r.prevX-44,r.prevY-44,88,88),i.vjCanvasContext.beginPath(),i.vjCanvasContext.fillStyle="white",i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle="red",i.vjCanvasContext.lineWidth=6,i.vjCanvasContext.arc(r.x,r.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),r.prevX=r.x,r.prevY=r.y)})),requestAnimationFrame((function(){e._drawVirtualJoystick()}))},i.prototype.releaseCanvas=function(){i.vjCanvas&&(i.vjCanvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),i.vjCanvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),i.vjCanvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),i.vjCanvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(i.vjCanvas),i.vjCanvas=null)},i._globalJoystickIndex=0,i})();e.VirtualJoystick=i})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VirtualJoysticksCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addVirtualJoystick(),n}return o(t,e),t.prototype.getClassName=function(){return"VirtualJoysticksCamera"},t})(e.FreeCamera);e.VirtualJoysticksCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.prototype.getLeftJoystick=function(){return this._leftjoystick},t.prototype.getRightJoystick=function(){return this._rightjoystick},t.prototype.checkInputs=function(){if(this._leftjoystick){var t=this.camera,i=50*t._computeLocalCameraSpeed(),r=e.Matrix.RotationYawPitchRoll(t.rotation.y,t.rotation.x,0),n=e.Vector3.TransformCoordinates(new e.Vector3(this._leftjoystick.deltaPosition.x*i,this._leftjoystick.deltaPosition.y*i,this._leftjoystick.deltaPosition.z*i),r);t.cameraDirection=t.cameraDirection.add(n),t.cameraRotation=t.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}},t.prototype.attachControl=function(t,i){this._leftjoystick=new e.VirtualJoystick(!0),this._leftjoystick.setAxisForUpDown(e.JoystickAxis.Z),this._leftjoystick.setAxisForLeftRight(e.JoystickAxis.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new e.VirtualJoystick(!1),this._rightjoystick.setAxisForUpDown(e.JoystickAxis.X),this._rightjoystick.setAxisForLeftRight(e.JoystickAxis.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")},t.prototype.detachControl=function(e){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()},t.prototype.getClassName=function(){return"FreeCameraVirtualJoystickInput"},t.prototype.getSimpleName=function(){return"virtualJoystick"},t})();e.FreeCameraVirtualJoystickInput=t,e.CameraInputTypes.FreeCameraVirtualJoystickInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i){this.quality=e,this.distance=t,this.optimizeMesh=i}return e})();e.SimplificationSettings=t;var i=(function(){function t(){this.running=!1,this._simplificationArray=[]}return t.prototype.addTask=function(e){this._simplificationArray.push(e)},t.prototype.executeNext=function(){var e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1},t.prototype.runSimplification=function(t){var i=this;if(t.parallelProcessing)t.settings.forEach((function(e){i.getSimplifier(t).simplify(e,(function(r){t.mesh.addLODLevel(e.distance,r),r.isVisible=!0,e.quality===t.settings[t.settings.length-1].quality&&t.successCallback&&t.successCallback(),i.executeNext()}))}));else{var r=this.getSimplifier(t),n=function(e,i){r.simplify(e,(function(r){t.mesh.addLODLevel(e.distance,r),r.isVisible=!0,i()}))};e.AsyncLoop.Run(t.settings.length,(function(e){n(t.settings[e.index],(function(){e.executeNext()}))}),(function(){t.successCallback&&t.successCallback(),i.executeNext()}))}},t.prototype.getSimplifier=function(e){switch(e.simplificationType){case r.QUADRATIC:default:return new l(e.mesh)}},t})();e.SimplificationQueue=i;var r;!(function(e){e[e.QUADRATIC=0]="QUADRATIC"})(r=e.SimplificationType||(e.SimplificationType={}));var n=(function(){function e(e){this.vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}return e})();e.DecimationTriangle=n;var o=(function(){function e(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new s,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}return e.prototype.updatePosition=function(e){this.position.copyFrom(e)},e})();e.DecimationVertex=o;var s=(function(){function e(e){this.data=new Array(10);for(var t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}return e.prototype.det=function(e,t,i,r,n,o,s,a,l){return this.data[e]*this.data[n]*this.data[l]+this.data[i]*this.data[r]*this.data[a]+this.data[t]*this.data[o]*this.data[s]-this.data[i]*this.data[n]*this.data[s]-this.data[e]*this.data[o]*this.data[a]-this.data[t]*this.data[r]*this.data[l]},e.prototype.addInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e.data[t]},e.prototype.addArrayInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e[t]},e.prototype.add=function(t){for(var i=new e,r=0;r<10;++r)i.data[r]=this.data[r]+t.data[r];return i},e.FromData=function(t,i,r,n){return new e(e.DataFromNumbers(t,i,r,n))},e.DataFromNumbers=function(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]},e})();e.QuadraticMatrix=s;var a=(function(){function e(e,t){this.vertexId=e,this.triangleId=t}return e})();e.Reference=a;var l=(function(){function t(t){this._mesh=t,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=e.Epsilon}return t.prototype.simplify=function(t,i){var r=this;this.initDecimatedMesh(),e.AsyncLoop.Run(this._mesh.subMeshes.length,(function(e){r.initWithMesh(e.index,(function(){r.runDecimation(t,e.index,(function(){e.executeNext()}))}),t.optimizeMesh)}),(function(){setTimeout((function(){i(r._reconstructedMesh)}),0)}))},t.prototype.runDecimation=function(t,i,r){var n=this,o=~~(this.triangles.length*t.quality),s=0,a=this.triangles.length,l=function(t,i){setTimeout((function(){t%5==0&&n.updateMesh(0===t);for(var r=0;rl||r.deleted||r.isDirty))for(var o=0;o<3;++o)if(r.error[o]>0,d,(function(){var t=function(e){if(l){var t=c.indexStart/3+e,i=3*t,r=l[i+0],o=l[i+1],a=l[i+2],h=s.vertices[u[r-c.verticesStart]],d=s.vertices[u[o-c.verticesStart]],f=s.vertices[u[a-c.verticesStart]],p=new n([h,d,f]);p.originalOffset=i,s.triangles.push(p)}};e.AsyncLoop.SyncAsyncForLoop(c.indexCount/3,s.syncIterations,t,(function(){s.init(i)}))}))},t.prototype.init=function(t){var i=this,r=function(t){var r=i.triangles[t];r.normal=e.Vector3.Cross(r.vertices[1].position.subtract(r.vertices[0].position),r.vertices[2].position.subtract(r.vertices[0].position)).normalize();for(var n=0;n<3;n++)r.vertices[n].q.addArrayInPlace(s.DataFromNumbers(r.normal.x,r.normal.y,r.normal.z,-e.Vector3.Dot(r.normal,r.vertices[0].position)))};e.AsyncLoop.SyncAsyncForLoop(this.triangles.length,this.syncIterations,r,(function(){var r=function(e){for(var t=i.triangles[e],r=0;r<3;++r)t.error[r]=i.calculateError(t.vertices[r],t.vertices[(r+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])};e.AsyncLoop.SyncAsyncForLoop(i.triangles.length,i.syncIterations,r,(function(){t()}))}))},t.prototype.reconstructMesh=function(t){var i,r=[];for(i=0;i0&&this._reconstructedMesh.setVerticesData(e.VertexBuffer.UVKind,l),c.length>0&&this._reconstructedMesh.setVerticesData(e.VertexBuffer.ColorKind,c);var b=this._mesh.subMeshes[t];t>0&&(this._reconstructedMesh.subMeshes=[],g.forEach((function(t){e.SubMesh.AddToMesh(t.materialIndex,t.verticesStart,t.verticesCount,t.indexStart,t.indexCount,t.getMesh())})),e.SubMesh.AddToMesh(b.materialIndex,m,f,_,3*r.length,this._reconstructedMesh))},t.prototype.initDecimatedMesh=function(){this._reconstructedMesh=new e.Mesh(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId},t.prototype.isFlipped=function(t,i,r,n,o,s){for(var a=0;a.999)return!0;var p=e.Vector3.Cross(d,f).normalize();if(n[a]=!1,e.Vector3.Dot(p,l.normal)<.2)return!0}else n[a]=!0,s.push(l)}}return!1},t.prototype.updateTriangles=function(e,t,i,r){for(var n=r,o=0;othis.maximumSize&&(n.scale(this.step),i=!1)}}return i},t})(t);e.TextureOptimization=i;var r=(function(e){function t(t,i,r){void 0===t&&(t=0),void 0===i&&(i=2),void 0===r&&(r=.25);var n=e.call(this,t)||this;return n.priority=t,n.maximumScale=i,n.step=r,n._currentScale=-1,n._directionOffset=1,n}return o(t,e),t.prototype.getDescription=function(){return"Setting hardware scaling level to "+this._currentScale},t.prototype.apply=function(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale},t})(t);e.HardwareScalingOptimization=r;var n=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning shadows on/off"},t.prototype.apply=function(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0},t})(t);e.ShadowsOptimization=n;var s=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning post-processes on/off"},t.prototype.apply=function(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0},t})(t);e.PostProcessesOptimization=s;var a=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning lens flares on/off"},t.prototype.apply=function(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0},t})(t);e.LensFlaresOptimization=a;var l=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"},t.prototype.apply=function(e,t){return!this.onApply||this.onApply(e,t)},t})(t);e.CustomOptimization=l;var c=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning particles on/off"},t.prototype.apply=function(e,t){return e.particlesEnabled=t.isInImprovementMode,!0},t})(t);e.ParticlesOptimization=c;var h=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){ -return"Turning render targets off"},t.prototype.apply=function(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0},t})(t);e.RenderTargetsOptimization=h;var u=(function(t){function i(){var i=null!==t&&t.apply(this,arguments)||this;return i._canBeMerged=function(t){if(!(t instanceof e.Mesh))return!1;var i=t;return!i.isDisposed()&&(!(!i.isVisible||!i.isEnabled())&&(!(i.instances.length>0)&&(!i.skeleton&&!i.hasLODLevels)))},i}return o(i,t),Object.defineProperty(i,"UpdateSelectionTree",{get:function(){return i._UpdateSelectionTree},set:function(e){i._UpdateSelectionTree=e},enumerable:!0,configurable:!0}),i.prototype.getDescription=function(){return"Merging similar meshes together"},i.prototype.apply=function(t,r,n){for(var o=t.meshes.slice(0),s=o.length,a=0;a=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);for(var r=!0,n=!0,o=0;o4&&(n.push(e.VertexBuffer.MatricesIndicesExtraKind),n.push(e.VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton?o.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),i&&(r.push("#define INSTANCES"),n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"));var a=r.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("outline",n,["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant"],["diffuseSampler"],a)),this._effect.isReady()},t})();e.OutlineRenderer=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this.edges=new Array,this.edgesConnectedCount=0}return e})(),i=(function(){function i(e,t,i){void 0===t&&(t=.95),void 0===i&&(i=!1),this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this._source=e,this._checkVerticesInsteadOfIndices=i,this._epsilon=t,this._prepareRessources(),this._generateEdgesLines()}return i.prototype._prepareRessources=function(){this._lineShader||(this._lineShader=new e.ShaderMaterial("lineShader",this._source.getScene(),"line",{attributes:["position","normal"],uniforms:["worldViewProjection","color","width","aspectRatio"]}),this._lineShader.disableDepthWrite=!0,this._lineShader.backFaceCulling=!1)},i.prototype._rebuild=function(){var t=this._buffers[e.VertexBuffer.PositionKind];t&&t._rebuild(),(t=this._buffers[e.VertexBuffer.NormalKind])&&t._rebuild();var i=this._source.getScene(),r=i.getEngine();this._ib=r.createIndexBuffer(this._linesIndices)},i.prototype.dispose=function(){var t=this._buffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._buffers[e.VertexBuffer.PositionKind]=null),t=this._buffers[e.VertexBuffer.NormalKind],t&&(t.dispose(),this._buffers[e.VertexBuffer.NormalKind]=null),this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose()},i.prototype._processEdgeForAdjacencies=function(e,t,i,r,n){return e===i&&t===r||e===r&&t===i?0:e===r&&t===n||e===n&&t===r?1:e===n&&t===i||e===i&&t===n?2:-1},i.prototype._processEdgeForAdjacenciesWithVertices=function(e,t,i,r,n){return e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(r)||e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(i)?0:e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(n)||e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(r)?1:e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(i)||e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(n)?2:-1},i.prototype._checkEdge=function(t,i,r,n,o){var s;if(void 0===i)s=!0;else{s=e.Vector3.Dot(r[t],r[i])0){this._previousStencilState=this._engine.getStencilBuffer();for(var r=0,n=i;r-1)){this._renderEffects=!0,this._needStencil=this._needStencil||o.needStencil();var s=o._mainTexture;s._shouldRender()&&(this.scene.incrementRenderId(),s.render(!1,!1))}}this.scene.incrementRenderId()}},t.prototype._setStencil=function(e){this._needStencil&&this._engine.setStencilBuffer(!0)},t.prototype._setStencilBack=function(e){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)},t.prototype._draw=function(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);for(var t=this.scene.effectLayers,i=0;i4&&(s.push(e.VertexBuffer.MatricesIndicesExtraKind),s.push(e.VertexBuffer.MatricesWeightsExtraKind)),o.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),o.push("#define BonesPerMesh "+(a.skeleton?a.skeleton.bones.length+1:0))):o.push("#define NUM_BONE_INFLUENCERS 0");var u=a.morphTargetManager,d=0;u&&u.numInfluencers>0&&(o.push("#define MORPHTARGETS"),d=u.numInfluencers,o.push("#define NUM_MORPH_INFLUENCERS "+d),e.MaterialHelper.PrepareAttributesForMorphTargets(s,a,{NUM_MORPH_INFLUENCERS:d})),i&&(o.push("#define INSTANCES"),s.push("world0"),s.push("world1"),s.push("world2"),s.push("world3"));var f=o.join("\n");return this._cachedDefines!==f&&(this._cachedDefines=f,this._effectLayerMapGenerationEffect=this._scene.getEngine().createEffect("glowMapGeneration",s,["world","mBones","viewProjection","diffuseMatrix","color","emissiveMatrix","morphTargetInfluences"],["diffuseSampler","emissiveSampler"],f,void 0,void 0,void 0,{maxSimultaneousMorphTargets:d})),this._effectLayerMapGenerationEffect.isReady()},t.prototype.render=function(){var e=this._mergeEffect;if(e.isReady()){for(var t=0;t-1&&this._scene.effectLayers.splice(i,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()},t.prototype.getClassName=function(){return"EffectLayer"},t.Parse=function(t,i,r){return e.Tools.Instantiate(t.customType).Parse(t,i,r)},n([e.serialize()],t.prototype,"name",void 0),n([e.serializeAsColor4()],t.prototype,"neutralColor",void 0),n([e.serialize()],t.prototype,"isEnabled",void 0),n([e.serializeAsCameraReference()],t.prototype,"camera",null),n([e.serialize()],t.prototype,"renderingGroupId",null),t})();e.EffectLayer=t})(r||(r={}));var r;!(function(e){e.AbstractScene.prototype.getHighlightLayerByName=function(e){for(var t=0;t-1&&this._tasks.splice(t,1)},i.prototype._decreaseWaitingTasksCount=function(i){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,i),this.onProgressObservable.notifyObservers(new r(this._waitingTasksCount,this._totalTasksCount,i))}catch(t){e.Tools.Error("Error running progress callbacks."),console.log(t)}if(0===this._waitingTasksCount){try{this.onFinish&&this.onFinish(this._tasks);for(var n=this._tasks.slice(),o=0,s=n;o-1&&this._tasks.splice(a,1)}}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(t){e.Tools.Error("Error running tasks-done callbacks."),console.log(t)}this._isLoading=!1,this._scene.getEngine().hideLoadingUI()}},i.prototype._runTask=function(e){var t=this,i=function(){try{t.onTaskSuccess&&t.onTaskSuccess(e),t.onTaskSuccessObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)}catch(e){r("Error executing task success callbacks",e)}},r=function(i,r){e._setErrorObject(i,r),t.onTaskError&&t.onTaskError(e),t.onTaskErrorObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)};e.run(this._scene,i,r)},i.prototype.reset=function(){return this._isLoading=!1,this._tasks=new Array,this},i.prototype.load=function(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(var e=0;e=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,i,s):n(t,i))||s);return o>3&&s&&Object.defineProperty(t,i,s),s},o=this&&this.__extends||(function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])};return function(t,i){function r(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}})();!(function(e){var t=(function(){function e(){this._defines={},this._currentRank=32,this._maxRank=-1}return e.prototype.unBindMesh=function(){this._mesh=null},e.prototype.addFallback=function(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)},e.prototype.addCPUSkinningFallback=function(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)},Object.defineProperty(e.prototype,"isMoreFallbacks",{get:function(){return this._currentRank<=this._maxRank},enumerable:!0,configurable:!0}),e.prototype.reduce=function(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0&&this._mesh.material){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;for(var i=this._mesh.getScene(),r=0;r-1?i:e.Engine.ShadersRepository+i,this._engine._loadFile(n+".vertex.fx",r)},t.prototype._loadFragmentShader=function(i,r){if(e.Tools.IsWindowObjectExist()&&i instanceof HTMLElement){return void r(e.Tools.GetDOMTextContent(i))}if("base64:"===i.substr(0,7)){return void r(window.atob(i.substr(7)))}if(t.ShadersStore[i+"PixelShader"])return void r(t.ShadersStore[i+"PixelShader"]);if(t.ShadersStore[i+"FragmentShader"])return void r(t.ShadersStore[i+"FragmentShader"]);var n;n="."===i[0]||"/"===i[0]||i.indexOf("http")>-1?i:e.Engine.ShadersRepository+i,this._engine._loadFile(n+".fragment.fx",r)},t.prototype._dumpShadersSource=function(t,i,r){var n=this._engine.webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"",o=n+(r?r+"\n":"");t=o+t,i=o+i;var s=2,a=/\n/gm,l="\n1\t"+t.replace(a,(function(){return"\n"+s+++"\t"}));s=2;var c="\n1\t"+i.replace(a,(function(){return"\n"+s+++"\t"}));this.name.vertexElement?(e.Tools.Error("Vertex shader: "+this.name.vertexElement+l),e.Tools.Error("Fragment shader: "+this.name.fragmentElement+c)):this.name.vertex?(e.Tools.Error("Vertex shader: "+this.name.vertex+l),e.Tools.Error("Fragment shader: "+this.name.fragment+c)):(e.Tools.Error("Vertex shader: "+this.name+l),e.Tools.Error("Fragment shader: "+this.name+c))},t.prototype._processShaderConversion=function(e,t,i){var r=this._processPrecision(e);if(1==this._engine.webGLVersion)return void i(r);if(-1!==r.indexOf("#version 3"))return void i(r.replace("#version 300 es",""));var n=-1!==r.search(/#extension.+GL_EXT_draw_buffers.+require/),o=/#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,s=r.replace(o,"");s=s.replace(/varying(?![\n\r])\s/g,t?"in ":"out "),s=s.replace(/attribute[ \t]/g,"in "),s=s.replace(/[ \t]attribute/g," in"),t&&(s=s.replace(/texture2DLodEXT\s*\(/g,"textureLod("),s=s.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),s=s.replace(/texture2D\s*\(/g,"texture("),s=s.replace(/textureCube\s*\(/g,"texture("),s=s.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),s=s.replace(/gl_FragColor/g,"glFragColor"),s=s.replace(/gl_FragData/g,"glFragData"),s=s.replace(/void\s+?main\s*\(/g,(n?"":"out vec4 glFragColor;\n")+"void main(")),i(s)},t.prototype._processIncludes=function(i,r){for(var n=this,o=/#include<(.+)>(\((.*)\))*(\[(.*)\])*/g,s=o.exec(i),a=new String(i);null!=s;){var l=s[1];if(-1!==l.indexOf("__decl__")&&(l=l.replace(/__decl__/,""),this._engine.supportsUniformBuffers&&(l=l.replace(/Vertex/,"Ubo"),l=l.replace(/Fragment/,"Ubo")),l+="Declaration"),!t.IncludesShadersStore[l]){var c=e.Engine.ShadersRepository+"ShadersInclude/"+l+".fx";return void this._engine._loadFile(c,(function(e){t.IncludesShadersStore[l]=e,n._processIncludes(a,r)}))}var h=t.IncludesShadersStore[l];if(s[2])for(var u=s[3].split(","),d=0;dr.x?r.x:n,n=nr.y?r.y:o,o=oi.x?e.x:i.x,e.y>i.y?e.y:i.y)},t.Transform=function(e,i){var r=t.Zero();return t.TransformToRef(e,i,r),r},t.TransformToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+t.m[13];i.x=r,i.y=n},t.PointInTriangle=function(e,t,i,r){var n=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),o=n<0?-1:1,s=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*o,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*o;return s>0&&a>0&&s+a<2*n*o},t.Distance=function(e,i){return Math.sqrt(t.DistanceSquared(e,i))},t.DistanceSquared=function(e,t){ +var i=e.x-t.x,r=e.y-t.y;return i*i+r*r},t.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},t.DistanceOfPointFromSegment=function(e,i,r){var n=t.DistanceSquared(i,r);if(0===n)return t.Distance(e,i);var o=r.subtract(i),s=Math.max(0,Math.min(1,t.Dot(e.subtract(i),o)/n)),a=i.add(o.multiplyByFloats(s,s));return t.Distance(e,a)},t})();e.Vector2=r;var n=(function(){function t(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this.x=e,this.y=t,this.z=i}return t.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+"}"},t.prototype.getClassName=function(){return"Vector3"},t.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0)},t.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},t.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,this},t.prototype.toQuaternion=function(){return e.Quaternion.RotationYawPitchRoll(this.x,this.y,this.z)},t.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this},t.prototype.add=function(e){return new t(this.x+e.x,this.y+e.y,this.z+e.z)},t.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,this},t.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this},t.prototype.subtract=function(e){return new t(this.x-e.x,this.y-e.y,this.z-e.z)},t.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,this},t.prototype.subtractFromFloats=function(e,i,r){return new t(this.x-e,this.y-i,this.z-r)},t.prototype.subtractFromFloatsToRef=function(e,t,i,r){return r.x=this.x-e,r.y=this.y-t,r.z=this.z-i,this},t.prototype.negate=function(){return new t(-this.x,-this.y,-this.z)},t.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this},t.prototype.scale=function(e){return new t(this.x*e,this.y*e,this.z*e)},t.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,this},t.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,this},t.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z},t.prototype.equalsWithEpsilon=function(t,i){return void 0===i&&(i=e.Epsilon),t&&e.Scalar.WithinEpsilon(this.x,t.x,i)&&e.Scalar.WithinEpsilon(this.y,t.y,i)&&e.Scalar.WithinEpsilon(this.z,t.z,i)},t.prototype.equalsToFloats=function(e,t,i){return this.x===e&&this.y===t&&this.z===i},t.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this},t.prototype.multiply=function(e){return new t(this.x*e.x,this.y*e.y,this.z*e.z)},t.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,this},t.prototype.multiplyByFloats=function(e,i,r){return new t(this.x*e,this.y*i,this.z*r)},t.prototype.divide=function(e){return new t(this.x/e.x,this.y/e.y,this.z/e.z)},t.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,this},t.prototype.divideInPlace=function(e){return this.divideToRef(e,this)},t.prototype.minimizeInPlace=function(e){return e.xthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),this},Object.defineProperty(t.prototype,"isNonUniform",{get:function(){var e=Math.abs(this.x),t=Math.abs(this.y);if(e!==t)return!0;var i=Math.abs(this.z);return e!==i||t!==i},enumerable:!0,configurable:!0}),t.prototype.floor=function(){return new t(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))},t.prototype.fract=function(){return new t(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z))},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},t.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},t.prototype.normalize=function(){var e=this.length();if(0===e||1===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this},t.prototype.normalizeToNew=function(){var e=new t(0,0,0);return this.normalizeToRef(e),e},t.prototype.normalizeToRef=function(e){var t=this.length();if(0===t||1===t)return e.set(this.x,this.y,this.z),e;var i=1/t;return this.scaleToRef(i,e),e},t.prototype.clone=function(){return new t(this.x,this.y,this.z)},t.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this},t.prototype.copyFromFloats=function(e,t,i){return this.x=e,this.y=t,this.z=i,this},t.prototype.set=function(e,t,i){return this.copyFromFloats(e,t,i)},t.GetClipFactor=function(e,i,r,n){var o=t.Dot(e,r)-n;return o/(o-(t.Dot(i,r)-n))},t.GetAngleBetweenVectors=function(e,i,r){var n=e.clone().normalize(),o=i.clone().normalize(),s=t.Dot(n,o),a=t.Cross(n,o);return t.Dot(a,r)>0?Math.acos(s):-Math.acos(s)},t.FromArray=function(e,i){return i||(i=0),new t(e[i],e[i+1],e[i+2])},t.FromFloatArray=function(e,i){return t.FromArray(e,i)},t.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2]},t.FromFloatArrayToRef=function(e,i,r){return t.FromArrayToRef(e,i,r)},t.FromFloatsToRef=function(e,t,i,r){r.x=e,r.y=t,r.z=i},t.Zero=function(){return new t(0,0,0)},t.One=function(){return new t(1,1,1)},t.Up=function(){return new t(0,1,0)},t.Down=function(){return new t(0,-1,0)},t.Forward=function(){return new t(0,0,1)},t.Right=function(){return new t(1,0,0)},t.Left=function(){return new t(-1,0,0)},t.TransformCoordinates=function(e,i){var r=t.Zero();return t.TransformCoordinatesToRef(e,i,r),r},t.TransformCoordinatesToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9]+t.m[13],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10]+t.m[14],s=e.x*t.m[3]+e.y*t.m[7]+e.z*t.m[11]+t.m[15];i.x=r/s,i.y=n/s,i.z=o/s},t.TransformCoordinatesFromFloatsToRef=function(e,t,i,r,n){var o=e*r.m[0]+t*r.m[4]+i*r.m[8]+r.m[12],s=e*r.m[1]+t*r.m[5]+i*r.m[9]+r.m[13],a=e*r.m[2]+t*r.m[6]+i*r.m[10]+r.m[14],l=e*r.m[3]+t*r.m[7]+i*r.m[11]+r.m[15];n.x=o/l,n.y=s/l,n.z=a/l},t.TransformNormal=function(e,i){var r=t.Zero();return t.TransformNormalToRef(e,i,r),r},t.TransformNormalToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10];i.x=r,i.y=n,i.z=o},t.TransformNormalFromFloatsToRef=function(e,t,i,r,n){n.x=e*r.m[0]+t*r.m[4]+i*r.m[8],n.y=e*r.m[1]+t*r.m[5]+i*r.m[9],n.z=e*r.m[2]+t*r.m[6]+i*r.m[10]},t.CatmullRom=function(e,i,r,n,o){var s=o*o,a=o*s;return new t(.5*(2*i.x+(-e.x+r.x)*o+(2*e.x-5*i.x+4*r.x-n.x)*s+(-e.x+3*i.x-3*r.x+n.x)*a),.5*(2*i.y+(-e.y+r.y)*o+(2*e.y-5*i.y+4*r.y-n.y)*s+(-e.y+3*i.y-3*r.y+n.y)*a),.5*(2*i.z+(-e.z+r.z)*o+(2*e.z-5*i.z+4*r.z-n.z)*s+(-e.z+3*i.z-3*r.z+n.z)*a))},t.Clamp=function(e,i,r){var n=e.x;n=n>r.x?r.x:n,n=nr.y?r.y:o,o=or.z?r.z:s,s=sthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this},t.prototype.floor=function(){return new t(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))},t.prototype.fract=function(){return new t(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},t.prototype.normalize=function(){var e=this.length();if(0===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toVector3=function(){return new n(this.x,this.y,this.z)},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},t.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},t.prototype.set=function(e,t,i,r){return this.copyFromFloats(e,t,i,r)},t.FromArray=function(e,i){return i||(i=0),new t(e[i],e[i+1],e[i+2],e[i+3])},t.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3]},t.FromFloatArrayToRef=function(e,i,r){t.FromArrayToRef(e,i,r)},t.FromFloatsToRef=function(e,t,i,r,n){n.x=e,n.y=t,n.z=i,n.w=r},t.Zero=function(){return new t(0,0,0,0)},t.One=function(){return new t(1,1,1,1)},t.Normalize=function(e){var i=t.Zero();return t.NormalizeToRef(e,i),i},t.NormalizeToRef=function(e,t){t.copyFrom(e),t.normalize()},t.Minimize=function(e,t){var i=e.clone();return i.minimizeInPlace(t),i},t.Maximize=function(e,t){var i=e.clone();return i.maximizeInPlace(t),i},t.Distance=function(e,i){return Math.sqrt(t.DistanceSquared(e,i))},t.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y,n=e.z-t.z,o=e.w-t.w;return i*i+r*r+n*n+o*o},t.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},t.TransformNormal=function(e,i){var r=t.Zero();return t.TransformNormalToRef(e,i,r),r},t.TransformNormalToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10];i.x=r,i.y=n,i.z=o,i.w=e.w},t.TransformNormalFromFloatsToRef=function(e,t,i,r,n,o){o.x=e*n.m[0]+t*n.m[4]+i*n.m[8],o.y=e*n.m[1]+t*n.m[5]+i*n.m[9],o.z=e*n.m[2]+t*n.m[6]+i*n.m[10],o.w=r},t})();e.Vector4=o;var s=(function(){function e(e,t){this.width=e,this.height=t}return e.prototype.toString=function(){return"{W: "+this.width+", H: "+this.height+"}"},e.prototype.getClassName=function(){return"Size"},e.prototype.getHashCode=function(){var e=this.width||0;return e=397*e^(this.height||0)},e.prototype.copyFrom=function(e){this.width=e.width,this.height=e.height},e.prototype.copyFromFloats=function(e,t){return this.width=e,this.height=t,this},e.prototype.set=function(e,t){return this.copyFromFloats(e,t)},e.prototype.multiplyByFloats=function(t,i){return new e(this.width*t,this.height*i)},e.prototype.clone=function(){return new e(this.width,this.height)},e.prototype.equals=function(e){return!!e&&(this.width===e.width&&this.height===e.height)},Object.defineProperty(e.prototype,"surface",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),e.Zero=function(){return new e(0,0)},e.prototype.add=function(t){return new e(this.width+t.width,this.height+t.height)},e.prototype.subtract=function(t){return new e(this.width-t.width,this.height-t.height)},e.Lerp=function(t,i,r){return new e(t.width+(i.width-t.width)*r,t.height+(i.height-t.height)*r)},e})();e.Size=s;var a=(function(){function e(e,t,i,r){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=1),this.x=e,this.y=t,this.z=i,this.w=r}return e.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},e.prototype.getClassName=function(){return"Quaternion"},e.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0),e=397*e^(this.w||0)},e.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},e.prototype.clone=function(){return new e(this.x,this.y,this.z,this.w)},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},e.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},e.prototype.set=function(e,t,i,r){return this.copyFromFloats(e,t,i,r)},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},e.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},e.prototype.scale=function(t){return new e(this.x*t,this.y*t,this.z*t,this.w*t)},e.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e,this},e.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,t.w+=this.w*e,this},e.prototype.multiply=function(t){var i=new e(0,0,0,1);return this.multiplyToRef(t,i),i},e.prototype.multiplyToRef=function(e,t){var i=this.x*e.w+this.y*e.z-this.z*e.y+this.w*e.x,r=-this.x*e.z+this.y*e.w+this.z*e.x+this.w*e.y,n=this.x*e.y-this.y*e.x+this.z*e.w+this.w*e.z,o=-this.x*e.x-this.y*e.y-this.z*e.z+this.w*e.w;return t.copyFromFloats(i,r,n,o),this},e.prototype.multiplyInPlace=function(e){return this.multiplyToRef(e,this),this},e.prototype.conjugateToRef=function(e){return e.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},e.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},e.prototype.conjugate=function(){return new e(-this.x,-this.y,-this.z,this.w)},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.prototype.normalize=function(){var e=1/this.length();return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.toEulerAngles=function(e){void 0===e&&(e="YZX");var t=n.Zero();return this.toEulerAnglesToRef(t,e),t},e.prototype.toEulerAnglesToRef=function(e,t){void 0===t&&(t="YZX");var i=this.z,r=this.x,n=this.y,o=this.w,s=o*o,a=i*i,l=r*r,c=n*n,h=n*i-r*o;return h<-.4999999?(e.y=2*Math.atan2(n,o),e.x=Math.PI/2,e.z=0):h>.4999999?(e.y=2*Math.atan2(n,o),e.x=-Math.PI/2,e.z=0):(e.z=Math.atan2(2*(r*n+i*o),-a-l+c+s),e.x=Math.asin(-2*(i*n-r*o)),e.y=Math.atan2(2*(i*r+n*o),a-l-c+s)),this},e.prototype.toRotationMatrix=function(e){var t=this.x*this.x,i=this.y*this.y,r=this.z*this.z,n=this.x*this.y,o=this.z*this.w,s=this.z*this.x,a=this.y*this.w,l=this.y*this.z,c=this.x*this.w;return e.m[0]=1-2*(i+r),e.m[1]=2*(n+o),e.m[2]=2*(s-a),e.m[3]=0,e.m[4]=2*(n-o),e.m[5]=1-2*(r+t),e.m[6]=2*(l+c),e.m[7]=0,e.m[8]=2*(s+a),e.m[9]=2*(l-c),e.m[10]=1-2*(i+t),e.m[11]=0,e.m[12]=0,e.m[13]=0,e.m[14]=0,e.m[15]=1,e._markAsUpdated(),this},e.prototype.fromRotationMatrix=function(t){return e.FromRotationMatrixToRef(t,this),this},e.FromRotationMatrix=function(t){var i=new e;return e.FromRotationMatrixToRef(t,i),i},e.FromRotationMatrixToRef=function(e,t){var i,r=e.m,n=r[0],o=r[4],s=r[8],a=r[1],l=r[5],c=r[9],h=r[2],u=r[6],d=r[10],f=n+l+d;f>0?(i=.5/Math.sqrt(f+1),t.w=.25/i,t.x=(u-c)*i,t.y=(s-h)*i,t.z=(a-o)*i):n>l&&n>d?(i=2*Math.sqrt(1+n-l-d),t.w=(u-c)/i,t.x=.25*i,t.y=(o+a)/i,t.z=(s+h)/i):l>d?(i=2*Math.sqrt(1+l-n-d),t.w=(s-h)/i,t.x=(o+a)/i,t.y=.25*i,t.z=(c+u)/i):(i=2*Math.sqrt(1+d-n-l),t.w=(a-o)/i,t.x=(s+h)/i,t.y=(c+u)/i,t.z=.25*i)},e.Dot=function(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w},e.AreClose=function(t,i){return e.Dot(t,i)>=0},e.Zero=function(){return new e(0,0,0,0)},e.Inverse=function(t){return new e(-t.x,-t.y,-t.z,t.w)},e.Identity=function(){return new e(0,0,0,1)},e.IsIdentity=function(e){return e&&0===e.x&&0===e.y&&0===e.z&&1===e.w},e.RotationAxis=function(t,i){return e.RotationAxisToRef(t,i,new e)},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(t/2);return e.normalize(),i.w=Math.cos(t/2),i.x=e.x*r,i.y=e.y*r,i.z=e.z*r,i},e.FromArray=function(t,i){return i||(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){var n=.5*i,o=.5*t,s=.5*e,a=Math.sin(n),l=Math.cos(n),c=Math.sin(o),h=Math.cos(o),u=Math.sin(s),d=Math.cos(s);r.x=d*c*l+u*h*a,r.y=u*h*l-d*c*a,r.z=d*h*a-u*c*l,r.w=d*h*l+u*c*a},e.RotationAlphaBetaGamma=function(t,i,r){var n=new e;return e.RotationAlphaBetaGammaToRef(t,i,r,n),n},e.RotationAlphaBetaGammaToRef=function(e,t,i,r){var n=.5*(i+e),o=.5*(i-e),s=.5*t;r.x=Math.cos(o)*Math.sin(s),r.y=Math.sin(o)*Math.sin(s),r.z=Math.sin(n)*Math.cos(s),r.w=Math.cos(n)*Math.cos(s)},e.RotationQuaternionFromAxis=function(t,i,r){var n=new e(0,0,0,0);return e.RotationQuaternionFromAxisToRef(t,i,r,n),n},e.RotationQuaternionFromAxisToRef=function(t,i,r,n){var o=E.Matrix[0];l.FromXYZAxesToRef(t.normalize(),i.normalize(),r.normalize(),o),e.FromRotationMatrixToRef(o,n)},e.Slerp=function(t,i,r){var n=e.Identity();return e.SlerpToRef(t,i,r,n),n},e.SlerpToRef=function(e,t,i,r){var n,o,s=e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w,a=!1;if(s<0&&(a=!0,s=-s),s>.999999)o=1-i,n=a?-i:i;else{var l=Math.acos(s),c=1/Math.sin(l);o=Math.sin((1-i)*l)*c,n=a?-Math.sin(i*l)*c:Math.sin(i*l)*c}r.x=o*e.x+n*t.x,r.y=o*e.y+n*t.y,r.z=o*e.z+n*t.z,r.w=o*e.w+n*t.w},e.Hermite=function(t,i,r,n,o){var s=o*o,a=o*s,l=2*a-3*s+1,c=-2*a+3*s,h=a-2*s+o,u=a-s;return new e(t.x*l+r.x*c+i.x*h+n.x*u,t.y*l+r.y*c+i.y*h+n.y*u,t.z*l+r.z*c+i.z*h+n.z*u,t.w*l+r.w*c+i.w*h+n.w*u)},e})();e.Quaternion=a;var l=(function(){function e(){this._isIdentity=!1,this._isIdentityDirty=!0,this.m=new Float32Array(16),this._markAsUpdated()}return e.prototype._markAsUpdated=function(){this.updateFlag=e._updateFlagSeed++,this._isIdentityDirty=!0},e.prototype.isIdentity=function(e){return void 0===e&&(e=!1),this._isIdentityDirty&&(this._isIdentityDirty=!1,1!==this.m[0]||1!==this.m[5]||1!==this.m[15]?this._isIdentity=!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?this._isIdentity=!1:this._isIdentity=!0,e||1===this.m[10]||(this._isIdentity=!1)),this._isIdentity},e.prototype.determinant=function(){var e=this.m[10]*this.m[15]-this.m[11]*this.m[14],t=this.m[9]*this.m[15]-this.m[11]*this.m[13],i=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],n=this.m[8]*this.m[14]-this.m[10]*this.m[12],o=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*e-this.m[6]*t+this.m[7]*i)-this.m[1]*(this.m[4]*e-this.m[6]*r+this.m[7]*n)+this.m[2]*(this.m[4]*t-this.m[5]*r+this.m[7]*o)-this.m[3]*(this.m[4]*i-this.m[5]*n+this.m[6]*o)},e.prototype.toArray=function(){return this.m},e.prototype.asArray=function(){return this.toArray()},e.prototype.invert=function(){return this.invertToRef(this),this},e.prototype.reset=function(){for(var e=0;e<16;e++)this.m[e]=0;return this._markAsUpdated(),this},e.prototype.add=function(t){var i=new e;return this.addToRef(t,i),i},e.prototype.addToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]=this.m[i]+e.m[i];return t._markAsUpdated(),this},e.prototype.addToSelf=function(e){for(var t=0;t<16;t++)this.m[t]+=e.m[t];return this._markAsUpdated(),this},e.prototype.invertToRef=function(e){var t=this.m[0],i=this.m[1],r=this.m[2],n=this.m[3],o=this.m[4],s=this.m[5],a=this.m[6],l=this.m[7],c=this.m[8],h=this.m[9],u=this.m[10],d=this.m[11],f=this.m[12],p=this.m[13],_=this.m[14],m=this.m[15],g=u*m-d*_,v=h*m-d*p,y=h*_-u*p,b=c*m-d*f,x=c*_-u*f,T=c*p-h*f,E=s*g-a*v+l*y,P=-(o*g-a*b+l*x),A=o*v-s*b+l*T,M=-(o*y-s*x+a*T),S=1/(t*E+i*P+r*A+n*M),C=a*m-l*_,R=s*m-l*p,O=s*_-a*p,D=o*m-l*f,I=o*_-a*f,w=o*p-s*f,L=a*d-l*u,F=s*d-l*h,B=s*u-a*h,V=o*d-l*c,N=o*u-a*c,U=o*h-s*c;return e.m[0]=E*S,e.m[4]=P*S,e.m[8]=A*S,e.m[12]=M*S,e.m[1]=-(i*g-r*v+n*y)*S,e.m[5]=(t*g-r*b+n*x)*S,e.m[9]=-(t*v-i*b+n*T)*S,e.m[13]=(t*y-i*x+r*T)*S,e.m[2]=(i*C-r*R+n*O)*S,e.m[6]=-(t*C-r*D+n*I)*S,e.m[10]=(t*R-i*D+n*w)*S,e.m[14]=-(t*O-i*I+r*w)*S,e.m[3]=-(i*L-r*F+n*B)*S,e.m[7]=(t*L-r*V+n*N)*S,e.m[11]=-(t*F-i*V+n*U)*S,e.m[15]=(t*B-i*N+r*U)*S,e._markAsUpdated(),this},e.prototype.setTranslationFromFloats=function(e,t,i){return this.m[12]=e,this.m[13]=t,this.m[14]=i,this._markAsUpdated(),this},e.prototype.setTranslation=function(e){return this.m[12]=e.x,this.m[13]=e.y,this.m[14]=e.z,this._markAsUpdated(),this},e.prototype.getTranslation=function(){return new n(this.m[12],this.m[13],this.m[14])},e.prototype.getTranslationToRef=function(e){return e.x=this.m[12],e.y=this.m[13],e.z=this.m[14],this},e.prototype.removeRotationAndScaling=function(){return this.setRowFromFloats(0,1,0,0,0),this.setRowFromFloats(1,0,1,0,0),this.setRowFromFloats(2,0,0,1,0),this},e.prototype.multiply=function(t){var i=new e;return this.multiplyToRef(t,i),i},e.prototype.copyFrom=function(e){for(var t=0;t<16;t++)this.m[t]=e.m[t];return this._markAsUpdated(),this},e.prototype.copyToArray=function(e,t){void 0===t&&(t=0);for(var i=0;i<16;i++)e[t+i]=this.m[i];return this},e.prototype.multiplyToRef=function(e,t){return this.multiplyToArray(e,t.m,0),t._markAsUpdated(),this},e.prototype.multiplyToArray=function(e,t,i){var r=this.m[0],n=this.m[1],o=this.m[2],s=this.m[3],a=this.m[4],l=this.m[5],c=this.m[6],h=this.m[7],u=this.m[8],d=this.m[9],f=this.m[10],p=this.m[11],_=this.m[12],m=this.m[13],g=this.m[14],v=this.m[15],y=e.m[0],b=e.m[1],x=e.m[2],T=e.m[3],E=e.m[4],P=e.m[5],A=e.m[6],M=e.m[7],S=e.m[8],C=e.m[9],R=e.m[10],O=e.m[11],D=e.m[12],I=e.m[13],w=e.m[14],L=e.m[15];return t[i]=r*y+n*E+o*S+s*D,t[i+1]=r*b+n*P+o*C+s*I,t[i+2]=r*x+n*A+o*R+s*w,t[i+3]=r*T+n*M+o*O+s*L,t[i+4]=a*y+l*E+c*S+h*D,t[i+5]=a*b+l*P+c*C+h*I,t[i+6]=a*x+l*A+c*R+h*w,t[i+7]=a*T+l*M+c*O+h*L,t[i+8]=u*y+d*E+f*S+p*D,t[i+9]=u*b+d*P+f*C+p*I,t[i+10]=u*x+d*A+f*R+p*w,t[i+11]=u*T+d*M+f*O+p*L,t[i+12]=_*y+m*E+g*S+v*D,t[i+13]=_*b+m*P+g*C+v*I,t[i+14]=_*x+m*A+g*R+v*w,t[i+15]=_*T+m*M+g*O+v*L,this},e.prototype.equals=function(e){return e&&this.m[0]===e.m[0]&&this.m[1]===e.m[1]&&this.m[2]===e.m[2]&&this.m[3]===e.m[3]&&this.m[4]===e.m[4]&&this.m[5]===e.m[5]&&this.m[6]===e.m[6]&&this.m[7]===e.m[7]&&this.m[8]===e.m[8]&&this.m[9]===e.m[9]&&this.m[10]===e.m[10]&&this.m[11]===e.m[11]&&this.m[12]===e.m[12]&&this.m[13]===e.m[13]&&this.m[14]===e.m[14]&&this.m[15]===e.m[15]},e.prototype.clone=function(){return e.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},e.prototype.getClassName=function(){return"Matrix"},e.prototype.getHashCode=function(){for(var e=this.m[0]||0,t=1;t<16;t++)e=397*e^(this.m[t]||0);return e},e.prototype.decompose=function(t,i,r){return r&&(r.x=this.m[12],r.y=this.m[13],r.z=this.m[14]),t=t||E.Vector3[0],t.x=Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),this.determinant()<=0&&(t.y*=-1),0===t.x||0===t.y||0===t.z?(i&&(i.x=0,i.y=0,i.z=0,i.w=1),!1):(i&&(e.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,E.Matrix[0]),a.FromRotationMatrixToRef(E.Matrix[0],i)),!0)},e.prototype.getRow=function(e){if(e<0||e>3)return null;var t=4*e;return new o(this.m[t+0],this.m[t+1],this.m[t+2],this.m[t+3])},e.prototype.setRow=function(e,t){if(e<0||e>3)return this;var i=4*e;return this.m[i+0]=t.x,this.m[i+1]=t.y,this.m[i+2]=t.z,this.m[i+3]=t.w,this._markAsUpdated(),this},e.prototype.transpose=function(){return e.Transpose(this)},e.prototype.transposeToRef=function(t){return e.TransposeToRef(this,t),this},e.prototype.setRowFromFloats=function(e,t,i,r,n){if(e<0||e>3)return this;var o=4*e;return this.m[o+0]=t,this.m[o+1]=i,this.m[o+2]=r,this.m[o+3]=n,this._markAsUpdated(),this},e.prototype.scale=function(t){var i=new e;return this.scaleToRef(t,i),i},e.prototype.scaleToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]=this.m[i]*e;return t._markAsUpdated(),this},e.prototype.scaleAndAddToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]+=this.m[i]*e;return t._markAsUpdated(),this},e.prototype.toNormalMatrix=function(t){this.invertToRef(t),t.transpose();var i=t.m;e.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,t)},e.prototype.getRotationMatrix=function(){var t=e.Identity();return this.getRotationMatrixToRef(t),t},e.prototype.getRotationMatrixToRef=function(t){var i=this.m,r=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),n=Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),o=Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);return this.determinant()<=0&&(n*=-1),0===r||0===n||0===o?e.IdentityToRef(t):e.FromValuesToRef(i[0]/r,i[1]/r,i[2]/r,0,i[4]/n,i[5]/n,i[6]/n,0,i[8]/o,i[9]/o,i[10]/o,0,0,0,0,1,t),this},e.FromArray=function(t,i){var r=new e;return i||(i=0),e.FromArrayToRef(t,i,r),r},e.FromArrayToRef=function(e,t,i){for(var r=0;r<16;r++)i.m[r]=e[r+t];i._markAsUpdated()},e.FromFloat32ArrayToRefScaled=function(e,t,i,r){for(var n=0;n<16;n++)r.m[n]=e[n+t]*i;r._markAsUpdated()},e.FromValuesToRef=function(e,t,i,r,n,o,s,a,l,c,h,u,d,f,p,_,m){m.m[0]=e,m.m[1]=t,m.m[2]=i,m.m[3]=r,m.m[4]=n,m.m[5]=o,m.m[6]=s,m.m[7]=a,m.m[8]=l,m.m[9]=c,m.m[10]=h,m.m[11]=u,m.m[12]=d,m.m[13]=f,m.m[14]=p,m.m[15]=_,m._markAsUpdated()},Object.defineProperty(e,"IdentityReadOnly",{get:function(){return e._identityReadOnly},enumerable:!0,configurable:!0}),e.FromValues=function(t,i,r,n,o,s,a,l,c,h,u,d,f,p,_,m){var g=new e;return g.m[0]=t,g.m[1]=i,g.m[2]=r,g.m[3]=n,g.m[4]=o,g.m[5]=s,g.m[6]=a,g.m[7]=l,g.m[8]=c,g.m[9]=h,g.m[10]=u,g.m[11]=d,g.m[12]=f,g.m[13]=p,g.m[14]=_,g.m[15]=m,g},e.Compose=function(t,i,r){var n=e.Identity();return e.ComposeToRef(t,i,r,n),n},e.ComposeToRef=function(t,i,r,n){e.FromValuesToRef(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1,E.Matrix[1]),i.toRotationMatrix(E.Matrix[0]),E.Matrix[1].multiplyToRef(E.Matrix[0],n),n.setTranslation(r)},e.Identity=function(){return e.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},e.IdentityToRef=function(t){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},e.Zero=function(){return e.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},e.RotationX=function(t){var i=new e;return e.RotationXToRef(t,i),i},e.Invert=function(t){var i=new e;return t.invertToRef(i),i},e.RotationXToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[0]=1,t.m[15]=1,t.m[5]=r,t.m[10]=r,t.m[9]=-i,t.m[6]=i,t.m[1]=0,t.m[2]=0,t.m[3]=0,t.m[4]=0,t.m[7]=0,t.m[8]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t._markAsUpdated()},e.RotationY=function(t){var i=new e;return e.RotationYToRef(t,i),i},e.RotationYToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[5]=1,t.m[15]=1,t.m[0]=r,t.m[2]=-i,t.m[8]=i,t.m[10]=r,t.m[1]=0,t.m[3]=0,t.m[4]=0,t.m[6]=0,t.m[7]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t._markAsUpdated()},e.RotationZ=function(t){var i=new e;return e.RotationZToRef(t,i),i},e.RotationZToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[10]=1,t.m[15]=1,t.m[0]=r,t.m[1]=i,t.m[4]=-i,t.m[5]=r,t.m[2]=0,t.m[3]=0,t.m[6]=0,t.m[7]=0,t.m[8]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t._markAsUpdated()},e.RotationAxis=function(t,i){var r=e.Zero();return e.RotationAxisToRef(t,i,r),r},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(-t),n=Math.cos(-t),o=1-n;e.normalize(),i.m[0]=e.x*e.x*o+n,i.m[1]=e.x*e.y*o-e.z*r,i.m[2]=e.x*e.z*o+e.y*r,i.m[3]=0, +i.m[4]=e.y*e.x*o+e.z*r,i.m[5]=e.y*e.y*o+n,i.m[6]=e.y*e.z*o-e.x*r,i.m[7]=0,i.m[8]=e.z*e.x*o-e.y*r,i.m[9]=e.z*e.y*o+e.x*r,i.m[10]=e.z*e.z*o+n,i.m[11]=0,i.m[15]=1,i._markAsUpdated()},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){a.RotationYawPitchRollToRef(e,t,i,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},e.Scaling=function(t,i,r){var n=e.Zero();return e.ScalingToRef(t,i,r,n),n},e.ScalingToRef=function(e,t,i,r){r.m[0]=e,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=t,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=i,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1,r._markAsUpdated()},e.Translation=function(t,i,r){var n=e.Identity();return e.TranslationToRef(t,i,r,n),n},e.TranslationToRef=function(t,i,r,n){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,r,1,n)},e.Lerp=function(t,i,r){var n=e.Zero();return e.LerpToRef(t,i,r,n),n},e.LerpToRef=function(e,t,i,r){for(var n=0;n<16;n++)r.m[n]=e.m[n]*(1-i)+t.m[n]*i;r._markAsUpdated()},e.DecomposeLerp=function(t,i,r){var n=e.Zero();return e.DecomposeLerpToRef(t,i,r,n),n},e.DecomposeLerpToRef=function(t,i,r,o){var s=E.Vector3[0],l=E.Quaternion[0],c=E.Vector3[1];t.decompose(s,l,c);var h=E.Vector3[2],u=E.Quaternion[1],d=E.Vector3[3];i.decompose(h,u,d);var f=E.Vector3[4];n.LerpToRef(s,h,r,f);var p=E.Quaternion[2];a.SlerpToRef(l,u,r,p);var _=E.Vector3[5];n.LerpToRef(c,d,r,_),e.ComposeToRef(f,p,_,o)},e.LookAtLH=function(t,i,r){var n=e.Zero();return e.LookAtLHToRef(t,i,r,n),n},e.LookAtLHToRef=function(t,i,r,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),n.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),n.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-n.Dot(this._xAxis,t),a=-n.Dot(this._yAxis,t),l=-n.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,l,1,o)},e.LookAtRH=function(t,i,r){var n=e.Zero();return e.LookAtRHToRef(t,i,r,n),n},e.LookAtRHToRef=function(t,i,r,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),n.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),n.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-n.Dot(this._xAxis,t),a=-n.Dot(this._yAxis,t),l=-n.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,l,1,o)},e.OrthoLH=function(t,i,r,n){var o=e.Zero();return e.OrthoLHToRef(t,i,r,n,o),o},e.OrthoLHToRef=function(t,i,r,n,o){var s=r,a=n,l=2/t,c=2/i,h=2/(a-s),u=-(a+s)/(a-s);e.FromValuesToRef(l,0,0,0,0,c,0,0,0,0,h,0,0,0,u,1,o)},e.OrthoOffCenterLH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterLHToRef=function(t,i,r,n,o,s,a){var l=o,c=s,h=2/(i-t),u=2/(n-r),d=2/(c-l),f=-(c+l)/(c-l),p=(t+i)/(t-i),_=(n+r)/(r-n);e.FromValuesToRef(h,0,0,0,0,u,0,0,0,0,d,0,p,_,f,1,a)},e.OrthoOffCenterRH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterRHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterRHToRef=function(t,i,r,n,o,s,a){e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a.m[10]*=-1},e.PerspectiveLH=function(t,i,r,n){var o=e.Zero(),s=r,a=n,l=2*s/t,c=2*s/i,h=(a+s)/(a-s),u=-2*a*s/(a-s);return e.FromValuesToRef(l,0,0,0,0,c,0,0,0,0,h,1,0,0,u,0,o),o},e.PerspectiveFovLH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovLHToRef(t,i,r,n,o),o},e.PerspectiveFovLHToRef=function(t,i,r,n,o,s){void 0===s&&(s=!0);var a=r,l=n,c=1/Math.tan(.5*t),h=s?c/i:c,u=s?c:c*i,d=(l+a)/(l-a),f=-2*l*a/(l-a);e.FromValuesToRef(h,0,0,0,0,u,0,0,0,0,d,1,0,0,f,0,o)},e.PerspectiveFovRH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovRHToRef(t,i,r,n,o),o},e.PerspectiveFovRHToRef=function(t,i,r,n,o,s){void 0===s&&(s=!0);var a=r,l=n,c=1/Math.tan(.5*t),h=s?c/i:c,u=s?c:c*i,d=-(l+a)/(l-a),f=-2*l*a/(l-a);e.FromValuesToRef(h,0,0,0,0,u,0,0,0,0,d,-1,0,0,f,0,o)},e.PerspectiveFovWebVRToRef=function(e,t,i,r,n){void 0===n&&(n=!1);var o=n?-1:1,s=Math.tan(e.upDegrees*Math.PI/180),a=Math.tan(e.downDegrees*Math.PI/180),l=Math.tan(e.leftDegrees*Math.PI/180),c=Math.tan(e.rightDegrees*Math.PI/180),h=2/(l+c),u=2/(s+a);r.m[0]=h,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=u,r.m[6]=r.m[7]=0,r.m[8]=(l-c)*h*.5,r.m[9]=-(s-a)*u*.5,r.m[10]=-i/(t-i),r.m[11]=1*o,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=-2*i*t/(i-t),r._markAsUpdated()},e.GetFinalMatrix=function(t,i,r,n,o,s){var a=t.width,l=t.height,c=t.x,h=t.y,u=e.FromValues(a/2,0,0,0,0,-l/2,0,0,0,0,s-o,0,c+a/2,l/2+h,o,1);return i.multiply(r).multiply(n).multiply(u)},e.GetAsMatrix2x2=function(e){return new Float32Array([e.m[0],e.m[1],e.m[4],e.m[5]])},e.GetAsMatrix3x3=function(e){return new Float32Array([e.m[0],e.m[1],e.m[2],e.m[4],e.m[5],e.m[6],e.m[8],e.m[9],e.m[10]])},e.Transpose=function(t){var i=new e;return e.TransposeToRef(t,i),i},e.TransposeToRef=function(e,t){t.m[0]=e.m[0],t.m[1]=e.m[4],t.m[2]=e.m[8],t.m[3]=e.m[12],t.m[4]=e.m[1],t.m[5]=e.m[5],t.m[6]=e.m[9],t.m[7]=e.m[13],t.m[8]=e.m[2],t.m[9]=e.m[6],t.m[10]=e.m[10],t.m[11]=e.m[14],t.m[12]=e.m[3],t.m[13]=e.m[7],t.m[14]=e.m[11],t.m[15]=e.m[15]},e.Reflection=function(t){var i=new e;return e.ReflectionToRef(t,i),i},e.ReflectionToRef=function(e,t){e.normalize();var i=e.normal.x,r=e.normal.y,n=e.normal.z,o=-2*i,s=-2*r,a=-2*n;t.m[0]=o*i+1,t.m[1]=s*i,t.m[2]=a*i,t.m[3]=0,t.m[4]=o*r,t.m[5]=s*r+1,t.m[6]=a*r,t.m[7]=0,t.m[8]=o*n,t.m[9]=s*n,t.m[10]=a*n+1,t.m[11]=0,t.m[12]=o*e.d,t.m[13]=s*e.d,t.m[14]=a*e.d,t.m[15]=1,t._markAsUpdated()},e.FromXYZAxesToRef=function(e,t,i,r){r.m[0]=e.x,r.m[1]=e.y,r.m[2]=e.z,r.m[3]=0,r.m[4]=t.x,r.m[5]=t.y,r.m[6]=t.z,r.m[7]=0,r.m[8]=i.x,r.m[9]=i.y,r.m[10]=i.z,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1,r._markAsUpdated()},e.FromQuaternionToRef=function(e,t){var i=e.x*e.x,r=e.y*e.y,n=e.z*e.z,o=e.x*e.y,s=e.z*e.w,a=e.z*e.x,l=e.y*e.w,c=e.y*e.z,h=e.x*e.w;t.m[0]=1-2*(r+n),t.m[1]=2*(o+s),t.m[2]=2*(a-l),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(n+i),t.m[6]=2*(c+h),t.m[7]=0,t.m[8]=2*(a+l),t.m[9]=2*(c-h),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,t._markAsUpdated()},e._tempQuaternion=new a,e._xAxis=n.Zero(),e._yAxis=n.Zero(),e._zAxis=n.Zero(),e._updateFlagSeed=0,e._identityReadOnly=e.Identity(),e})();e.Matrix=l;var c=(function(){function e(e,t,i,r){this.normal=new n(e,t,i),this.d=r}return e.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},e.prototype.clone=function(){return new e(this.normal.x,this.normal.y,this.normal.z,this.d)},e.prototype.getClassName=function(){return"Plane"},e.prototype.getHashCode=function(){var e=this.normal.getHashCode();return e=397*e^(this.d||0)},e.prototype.normalize=function(){var e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this},e.prototype.transform=function(t){var i=l.Transpose(t),r=this.normal.x,n=this.normal.y,o=this.normal.z,s=this.d;return new e(r*i.m[0]+n*i.m[1]+o*i.m[2]+s*i.m[3],r*i.m[4]+n*i.m[5]+o*i.m[6]+s*i.m[7],r*i.m[8]+n*i.m[9]+o*i.m[10]+s*i.m[11],r*i.m[12]+n*i.m[13]+o*i.m[14]+s*i.m[15])},e.prototype.dotCoordinate=function(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d},e.prototype.copyFromPoints=function(e,t,i){var r,n=t.x-e.x,o=t.y-e.y,s=t.z-e.z,a=i.x-e.x,l=i.y-e.y,c=i.z-e.z,h=o*c-s*l,u=s*a-n*c,d=n*l-o*a,f=Math.sqrt(h*h+u*u+d*d);return r=0!==f?1/f:0,this.normal.x=h*r,this.normal.y=u*r,this.normal.z=d*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this},e.prototype.isFrontFacingTo=function(e,t){return n.Dot(this.normal,e)<=t},e.prototype.signedDistanceTo=function(e){return n.Dot(e,this.normal)+this.d},e.FromArray=function(t){return new e(t[0],t[1],t[2],t[3])},e.FromPoints=function(t,i,r){var n=new e(0,0,0,0);return n.copyFromPoints(t,i,r),n},e.FromPositionAndNormal=function(t,i){var r=new e(0,0,0,0);return i.normalize(),r.normal=i,r.d=-(i.x*t.x+i.y*t.y+i.z*t.z),r},e.SignedDistanceToPlaneFromPositionAndNormal=function(e,t,i){var r=-(t.x*e.x+t.y*e.y+t.z*e.z);return n.Dot(i,t)+r},e})();e.Plane=c;var h=(function(){function e(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}return e.prototype.toGlobal=function(t,i){if(t.getRenderWidth){var r=t;return this.toGlobal(r.getRenderWidth(),r.getRenderHeight())}var n=t;return new e(this.x*n,this.y*i,this.width*n,this.height*i)},e.prototype.clone=function(){return new e(this.x,this.y,this.width,this.height)},e})();e.Viewport=h;var u=(function(){function e(){}return e.GetPlanes=function(t){for(var i=[],r=0;r<6;r++)i.push(new c(0,0,0,0));return e.GetPlanesToRef(t,i),i},e.GetNearPlaneToRef=function(e,t){t.normal.x=e.m[3]+e.m[2],t.normal.y=e.m[7]+e.m[6],t.normal.z=e.m[11]+e.m[10],t.d=e.m[15]+e.m[14],t.normalize()},e.GetFarPlaneToRef=function(e,t){t.normal.x=e.m[3]-e.m[2],t.normal.y=e.m[7]-e.m[6],t.normal.z=e.m[11]-e.m[10],t.d=e.m[15]-e.m[14],t.normalize()},e.GetLeftPlaneToRef=function(e,t){t.normal.x=e.m[3]+e.m[0],t.normal.y=e.m[7]+e.m[4],t.normal.z=e.m[11]+e.m[8],t.d=e.m[15]+e.m[12],t.normalize()},e.GetRightPlaneToRef=function(e,t){t.normal.x=e.m[3]-e.m[0],t.normal.y=e.m[7]-e.m[4],t.normal.z=e.m[11]-e.m[8],t.d=e.m[15]-e.m[12],t.normalize()},e.GetTopPlaneToRef=function(e,t){t.normal.x=e.m[3]-e.m[1],t.normal.y=e.m[7]-e.m[5],t.normal.z=e.m[11]-e.m[9],t.d=e.m[15]-e.m[13],t.normalize()},e.GetBottomPlaneToRef=function(e,t){t.normal.x=e.m[3]+e.m[1],t.normal.y=e.m[7]+e.m[5],t.normal.z=e.m[11]+e.m[9],t.d=e.m[15]+e.m[13],t.normalize()},e.GetPlanesToRef=function(t,i){e.GetNearPlaneToRef(t,i[0]),e.GetFarPlaneToRef(t,i[1]),e.GetLeftPlaneToRef(t,i[2]),e.GetRightPlaneToRef(t,i[3]),e.GetTopPlaneToRef(t,i[4]),e.GetBottomPlaneToRef(t,i[5])},e})();e.Frustum=u;!(function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"})(e.Space||(e.Space={}));var d=(function(){function e(){}return e.X=new n(1,0,0),e.Y=new n(0,1,0),e.Z=new n(0,0,1),e})();e.Axis=d;var f=(function(){function e(){}return e.interpolate=function(e,t,i,r,n){for(var o=1-3*r+3*t,s=3*r-6*t,a=3*t,l=e,c=0;c<5;c++){var h=l*l;l-=(o*(h*l)+s*h+a*l-e)*(1/(3*o*h+2*s*l+a)),l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*n+Math.pow(l,3)},e})();e.BezierCurve=f;var p;!(function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"})(p=e.Orientation||(e.Orientation={}));var _=(function(){function e(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}return e.prototype.degrees=function(){return 180*this._radians/Math.PI},e.prototype.radians=function(){return this._radians},e.BetweenTwoPoints=function(t,i){var r=i.subtract(t);return new e(Math.atan2(r.y,r.x))},e.FromRadians=function(t){return new e(t)},e.FromDegrees=function(t){return new e(t*Math.PI/180)},e})();e.Angle=_;var m=(function(){function e(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;var n=Math.pow(t.x,2)+Math.pow(t.y,2),o=(Math.pow(e.x,2)+Math.pow(e.y,2)-n)/2,s=(n-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new r((o*(t.y-i.y)-s*(e.y-t.y))/a,((e.x-t.x)*s-(t.x-i.x)*o)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=_.BetweenTwoPoints(this.centerPoint,this.startPoint);var l=this.startAngle.degrees(),c=_.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=_.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();c-l>180&&(c-=360),c-l<-180&&(c+=360),h-c>180&&(h-=360),h-c<-180&&(h+=360),this.orientation=c-l<0?p.CW:p.CCW,this.angle=_.FromDegrees(this.orientation===p.CW?l-h:h-l)}return e})();e.Arc2=m;var g=(function(){function e(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(e,t))}return e.prototype.addLineTo=function(e,t){if(this.closed)return this;var i=new r(e,t),n=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(n).length(),this},e.prototype.addArcTo=function(e,t,i,n,o){if(void 0===o&&(o=36),this.closed)return this;var s=this._points[this._points.length-1],a=new r(e,t),l=new r(i,n),c=new m(s,a,l),h=c.angle.radians()/o;c.orientation===p.CW&&(h*=-1);for(var u=c.startAngle.radians()+h,d=0;d1)return r.Zero();for(var t=e*this.length(),i=0,n=0;n=i&&t<=c){var h=l.normalize(),u=t-i;return new r(s.x+h.x*u,s.y+h.y*u)}i=c}return r.Zero()},e.StartingAt=function(t,i){return new e(t,i)},e})();e.Path2=g;var v=(function(){function t(e,t,i){void 0===t&&(t=null),this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;rt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i},t.prototype._normalVector=function(t,i,r){var o,s=i.length();if(0===s&&(s=1),void 0===r||null===r){var a;a=e.Scalar.WithinEpsilon(Math.abs(i.y)/s,1,e.Epsilon)?e.Scalar.WithinEpsilon(Math.abs(i.x)/s,1,e.Epsilon)?e.Scalar.WithinEpsilon(Math.abs(i.z)/s,1,e.Epsilon)?n.Zero():new n(0,0,1):new n(1,0,0):new n(0,-1,0),o=n.Cross(i,a)}else o=n.Cross(i,r),n.CrossToRef(o,i,o);return o.normalize(),o},t})();e.Path3D=v;var y=(function(){function e(e){this._length=0,this._points=e,this._length=this._computeLength(e)}return e.CreateQuadraticBezier=function(t,i,r,o){o=o>2?o:3;for(var s=new Array,a=function(e,t,i,r){return(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r},l=0;l<=o;l++)s.push(new n(a(l/o,t.x,i.x,r.x),a(l/o,t.y,i.y,r.y),a(l/o,t.z,i.z,r.z)));return new e(s)},e.CreateCubicBezier=function(t,i,r,o,s){s=s>3?s:4;for(var a=new Array,l=function(e,t,i,r,n){return(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*n},c=0;c<=s;c++)a.push(new n(l(c/s,t.x,i.x,r.x,o.x),l(c/s,t.y,i.y,r.y,o.y),l(c/s,t.z,i.z,r.z,o.z)));return new e(a)},e.CreateHermiteSpline=function(t,i,r,o,s){for(var a=new Array,l=1/s,c=0;c<=s;c++)a.push(n.Hermite(t,i,r,o,c*l));return new e(a)},e.CreateCatmullRomSpline=function(t,i,r){var o=new Array,s=1/i,a=0;if(r){for(var l=t.length,c=0;c0?1:-1},e.Clamp=function(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1),Math.min(i,Math.max(t,e))},e.Log2=function(e){return Math.log(e)*Math.LOG2E},e.Repeat=function(e,t){return e-Math.floor(e/t)*t},e.Normalize=function(e,t,i){return(e-t)/(i-t)},e.Denormalize=function(e,t,i){return e*(i-t)+t},e.DeltaAngle=function(t,i){var r=e.Repeat(i-t,360);return r>180&&(r-=360),r},e.PingPong=function(t,i){var r=e.Repeat(t,2*i);return i-Math.abs(r-i)},e.SmoothStep=function(t,i,r){var n=e.Clamp(r);return n=-2*n*n*n+3*n*n,i*n+t*(1-n)},e.MoveTowards=function(t,i,r){return Math.abs(i-t)<=r?i:t+e.Sign(i-t)*r},e.MoveTowardsAngle=function(t,i,r){var n=e.DeltaAngle(t,i),o=0;return-r180&&(n-=360),t+n*e.Clamp(r)},e.InverseLerp=function(t,i,r){return t!=i?e.Clamp((r-t)/(i-t)):0},e.Hermite=function(e,t,i,r,n){var o=n*n,s=n*o;return e*(2*s-3*o+1)+i*(-2*s+3*o)+t*(s-2*o+n)+r*(s-o)},e.RandomRange=function(e,t){return e===t?e:Math.random()*(t-e)+e},e.RangeToPercent=function(e,t,i){return(e-t)/(i-t)},e.PercentToRange=function(e,t,i){return(i-t)*e+t},e.NormalizeRadians=function(t){return t-=e.TwoPi*Math.floor((t+Math.PI)/e.TwoPi)},e.TwoPi=2*Math.PI,e})();e.Scalar=t})(r||(r={}));var r;!(function(e){function t(e){var t=e.getClassName();return v[t]||(v[t]={}),v[t]}function i(e){var t=e.getClassName();if(y[t])return y[t];y[t]={};for(var i=y[t],r=e,n=t;n;){var o=v[n];for(var s in o)i[s]=o[s];var a=void 0,l=!1;do{if(a=Object.getPrototypeOf(r),!a.getClassName){l=!0;break}if(a.getClassName()!==n)break;r=a}while(a);if(l)break;n=a.getClassName(),r=a}return i}function r(e,i){return function(r,n){var o=t(r);o[n]||(o[n]={type:e,sourceName:i})}}function n(e,t){return void 0===t&&(t=null),function(i,r){var n=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[n]},set:function(t){this[n]!==t&&(this[n]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}function o(e,t){return void 0===t&&(t=null),n(e,t)}function s(e){return r(0,e)}function a(e){return r(1,e)}function l(e){return r(2,e)}function c(e){return r(3,e)}function h(e){return r(4,e)}function u(e){return r(5,e)}function d(e){return r(6,e)}function f(e){return r(7,e)}function p(e){return r(8,e)}function _(e){return r(9,e)}function m(e){return r(10,e)}function g(e){return r(11,e)}var v={},y={},b=function(t,r,n){var o=t();e.Tags&&e.Tags.AddTagsTo(o,r.tags);var s=i(o);for(var a in s){var l=s[a],c=r[a],h=l.type;if(void 0!==c&&null!==c)switch(h){case 0:case 6:case 11:o[a]=c;break;case 1:o[a]=n||c.isRenderTarget?c:c.clone();break;case 2:case 3:case 4:case 5:case 7:case 10:o[a]=n?c:c.clone()}}return o};e.expandToProperty=o,e.serialize=s,e.serializeAsTexture=a,e.serializeAsColor3=l,e.serializeAsFresnelParameters=c,e.serializeAsVector2=h,e.serializeAsVector3=u,e.serializeAsMeshReference=d,e.serializeAsColorCurves=f,e.serializeAsColor4=p,e.serializeAsImageProcessingConfiguration=_,e.serializeAsQuaternion=m,e.serializeAsCameraReference=g;var x=(function(){function t(){}return t.Serialize=function(t,r){r||(r={}),e.Tags&&(r.tags=e.Tags.GetTags(t));var n=i(t);for(var o in n){var s=n[o],a=s.sourceName||o,l=s.type,c=t[o];if(void 0!==c&&null!==c)switch(l){case 0:r[a]=c;break;case 1:r[a]=c.serialize();break;case 2:r[a]=c.asArray();break;case 3:r[a]=c.serialize();break;case 4:case 5:r[a]=c.asArray();break;case 6:r[a]=c.id;break;case 7:r[a]=c.serialize();break;case 8:r[a]=c.asArray();break;case 9:r[a]=c.serialize();break;case 10:r[a]=c.asArray();break;case 11:r[a]=c.id}}return r},t.Parse=function(t,r,n,o){void 0===o&&(o=null);var s=t();o||(o=""),e.Tags&&e.Tags.AddTagsTo(s,r.tags);var a=i(s);for(var l in a){var c=a[l],h=r[c.sourceName||l],u=c.type;if(void 0!==h&&null!==h){var d=s;switch(u){case 0:d[l]=h;break;case 1:n&&(d[l]=e.Texture.Parse(h,n,o));break;case 2:d[l]=e.Color3.FromArray(h);break;case 3:d[l]=e.FresnelParameters.Parse(h);break;case 4:d[l]=e.Vector2.FromArray(h);break;case 5:d[l]=e.Vector3.FromArray(h);break;case 6:n&&(d[l]=n.getLastMeshByID(h));break;case 7:d[l]=e.ColorCurves.Parse(h);break;case 8:d[l]=e.Color4.FromArray(h);break;case 9:d[l]=e.ImageProcessingConfiguration.Parse(h);break;case 10:d[l]=e.Quaternion.FromArray(h);break;case 11:n&&(d[l]=n.getCameraByID(h))}}}return s},t.Clone=function(e,t){return b(e,t,!1)},t.Instanciate=function(e,t){return b(e,t,!0)},t})();e.SerializationHelper=x})(r||(r={}));var r;!(function(e){var t=(function(){function e(){var e=this;this.promise=new Promise(function(t,i){e._resolve=t,e._reject=i})}return Object.defineProperty(e.prototype,"resolve",{get:function(){return this._resolve},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"reject",{get:function(){return this._reject},enumerable:!0,configurable:!0}),e})();e.Deferred=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i,r){void 0===t&&(t=!1),this.initalize(e,t,i,r)}return e.prototype.initalize=function(e,t,i,r){return void 0===t&&(t=!1),this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this},e})();e.EventState=t;var i=(function(){function e(e,t,i){void 0===i&&(i=null),this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1}return e})();e.Observer=i;var r=(function(){function e(){}return e.prototype.dispose=function(){if(this._observers&&this._observables)for(var e=0;e0},r.prototype.clear=function(){this._observers=new Array,this._onObserverAdded=null},r.prototype.clone=function(){var e=new r;return e._observers=this._observers.slice(0),e},r.prototype.hasSpecificMask=function(e){void 0===e&&(e=-1);for(var t=0,i=this._observers;tthis.data.length&&(this.data.length*=2)},e.prototype.forEach=function(e){for(var t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t=this.length?-1:t},e.prototype.contains=function(e){return-1!==this.data.indexOf(e)},e._GlobalId=0,e})();e.SmartArray=t;var i=(function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._duplicateId=0,t}return o(t,e),t.prototype.push=function(t){e.prototype.push.call(this,t),t.__smartArrayFlags||(t.__smartArrayFlags={}),t.__smartArrayFlags[this._id]=this._duplicateId},t.prototype.pushNoDuplicate=function(e){return(!e.__smartArrayFlags||e.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(e),!0)},t.prototype.reset=function(){e.prototype.reset.call(this),this._duplicateId++},t.prototype.concatWithNoDuplicate=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t=e||-1!==i.indexOf("file:")?-1:Math.pow(2,n)*t}},e})();e.RetryStrategy=s;var a,l=function(t,i){return t?t instanceof e.Mesh?null:t instanceof e.SubMesh?t.clone(i):t.clone?t.clone():null:null},c=(function(){function t(){}return t.FetchToRef=function(e,t,i,r,n,o){var s=Math.abs(e)*i%i|0,a=Math.abs(t)*r%r|0,l=4*(s+a*i);o.r=n[l]/255,o.g=n[l+1]/255,o.b=n[l+2]/255,o.a=n[l+3]/255},t.Mix=function(e,t,i){return e*(1-i)+t*i},t.Instantiate=function(e){if(t.RegisteredExternalClasses&&t.RegisteredExternalClasses[e])return t.RegisteredExternalClasses[e];for(var i=e.split("."),r=window||this,n=0,o=i.length;n>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e},t.FloorPOT=function(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)},t.NearestPOT=function(e){var i=t.CeilingPOT(e),r=t.FloorPOT(e);return i-e>e-r?r:i},t.GetExponentOfTwo=function(i,r,n){void 0===n&&(n=e.Engine.SCALEMODE_NEAREST);var o;switch(n){case e.Engine.SCALEMODE_FLOOR:o=t.FloorPOT(i);break;case e.Engine.SCALEMODE_NEAREST:o=t.NearestPOT(i);break;case e.Engine.SCALEMODE_CEILING:default:o=t.CeilingPOT(i)}return Math.min(o,r)},t.GetFilename=function(e){var t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)},t.GetFolderPath=function(e,t){void 0===t&&(t=!1);var i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)},t.GetDOMTextContent=function(e){for(var t="",i=e.firstChild;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t},t.ToDegrees=function(e){return 180*e/Math.PI},t.ToRadians=function(e){return e*Math.PI/180},t.EncodeArrayBufferTobase64=function(e){for(var t,i,r,n,o,s,a,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c="",h=0,u=new Uint8Array(e);h>2,o=(3&t)<<4|i>>4,s=(15&i)<<2|r>>6,a=63&r,isNaN(i)?s=a=64:isNaN(r)&&(a=64),c+=l.charAt(n)+l.charAt(o)+l.charAt(s)+l.charAt(a);return"data:image/png;base64,"+c}, +t.ExtractMinAndMaxIndexed=function(t,i,r,n,o){void 0===o&&(o=null);for(var s=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new e.Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),l=r;l=(r?t.length/2:t.length))return null;if(r){var n=t;return new e.Vector2(n[2*i+0],n[2*i+1])}return t[i]}},t.ExtractMinAndMaxVector2=function(t,i){void 0===i&&(i=null);for(var r=new e.Vector2(Number.MAX_VALUE,Number.MAX_VALUE),n=new e.Vector2(-Number.MAX_VALUE,-Number.MAX_VALUE),o=0,s=t(o++);s;)r=e.Vector2.Minimize(s,r),n=e.Vector2.Maximize(s,n),s=t(o++);return i&&(r.x-=r.x*i.x+i.y,r.y-=r.y*i.x+i.y,n.x+=n.x*i.x+i.y,n.y+=n.y*i.x+i.y),{minimum:r,maximum:n}},t.MakeArray=function(e,t){return!0===t||void 0!==e&&null!=e?Array.isArray(e)?e:[e]:null},t.GetPointerPrefix=function(){var e="pointer";return!t.IsWindowObjectExist()||window.PointerEvent||navigator.pointerEnabled||(e="mouse"),e},t.QueueNewFrame=function(e,i){return t.IsWindowObjectExist()?(i||(i=window),i.requestAnimationFrame?i.requestAnimationFrame(e):i.msRequestAnimationFrame?i.msRequestAnimationFrame(e):i.webkitRequestAnimationFrame?i.webkitRequestAnimationFrame(e):i.mozRequestAnimationFrame?i.mozRequestAnimationFrame(e):i.oRequestAnimationFrame?i.oRequestAnimationFrame(e):window.setTimeout(e,16)):setTimeout(e,16)},t.RequestFullscreen=function(e){var t=e.requestFullscreen||e.msRequestFullscreen||e.webkitRequestFullscreen||e.mozRequestFullScreen;t&&t.call(e)},t.ExitFullscreen=function(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitCancelFullScreen?document.webkitCancelFullScreen():document.msCancelFullScreen&&document.msCancelFullScreen()},t.SetCorsBehavior=function(e,i){if((!e||0!==e.indexOf("data:"))&&t.CorsBehavior)if("string"==typeof t.CorsBehavior||t.CorsBehavior instanceof String)i.crossOrigin=t.CorsBehavior;else{var r=t.CorsBehavior(e);r&&(i.crossOrigin=r)}},t.CleanUrl=function(e){return e=e.replace(/#/gm,"%23")},t.LoadImage=function(i,r,n,o){var s,a=!1;i instanceof ArrayBuffer?(s=URL.createObjectURL(new Blob([i])),a=!0):i instanceof Blob?(s=URL.createObjectURL(i),a=!0):(s=t.CleanUrl(i),s=t.PreprocessUrl(i));var l=new Image;t.SetCorsBehavior(s,l);var c=function(){a&&l.src&&URL.revokeObjectURL(l.src),l.removeEventListener("load",c),l.removeEventListener("error",h),r(l)},h=function(e){a&&l.src&&URL.revokeObjectURL(l.src),l.removeEventListener("load",c),l.removeEventListener("error",h),t.Error("Error while trying to load image: "+i),n&&n("Error while trying to load image: "+i,e)};l.addEventListener("load",c),l.addEventListener("error",h);var u=function(){l.src=s},d=function(){o&&o.loadImageFromDB(s,l)};if("data:"!==s.substr(0,5)&&o&&o.enableTexturesOffline&&e.Database.IsUASupportingBlobStorage)o.openAsync(d,u);else{if(-1!==s.indexOf("file:")){var f=decodeURIComponent(s.substring(5).toLowerCase());if(e.FilesInput.FilesToLoad[f]){try{var p;try{p=URL.createObjectURL(e.FilesInput.FilesToLoad[f],{oneTimeOnly:!0})}catch(t){p=URL.createObjectURL(e.FilesInput.FilesToLoad[f])}l.src=p,a=!0}catch(e){l.src=""}return l}}u()}return l},t.LoadFile=function(i,r,o,s,a,l){if(i=t.CleanUrl(i),i=t.PreprocessUrl(i),-1!==i.indexOf("file:")){var c=decodeURIComponent(i.substring(5).toLowerCase());if(e.FilesInput.FilesToLoad[c])return t.ReadFile(e.FilesInput.FilesToLoad[c],r,o,a)}var h=t.BaseUrl+i,u=!1,d={onCompleteObservable:new e.Observable,abort:function(){return u=!0}},f=function(){var e=new XMLHttpRequest,i=null;d.abort=function(){u=!0,e.readyState!==(XMLHttpRequest.DONE||4)&&e.abort(),null!==i&&(clearTimeout(i),i=null)};var s=function(c){e.open("GET",h,!0),a&&(e.responseType="arraybuffer"),o&&e.addEventListener("progress",o);var f=function(){e.removeEventListener("loadend",f),d.onCompleteObservable.notifyObservers(d),d.onCompleteObservable.clear()};e.addEventListener("loadend",f);var p=function(){if(!u&&e.readyState===(XMLHttpRequest.DONE||4)){if(e.removeEventListener("readystatechange",p),e.status>=200&&e.status<300||!t.IsWindowObjectExist()&&0===e.status)return void r(a?e.response:e.responseText,e.responseURL);var o=t.DefaultRetryStrategy;if(o){var d=o(h,e,c);if(-1!==d)return e.removeEventListener("loadend",f),e=new XMLHttpRequest,void(i=setTimeout((function(){return s(c+1)}),d))}var _=new n("Error status: "+e.status+" "+e.statusText+" - Unable to load "+h,e);if(!l)throw _;l(e,_)}};e.addEventListener("readystatechange",p),e.send()};s(0)};if(s&&s.enableSceneOffline){var p=function(e){e&&e.status>400?l&&l(e):u||f()},_=function(){u||s&&s.loadFileFromDB(i,(function(e){u||r(e),d.onCompleteObservable.notifyObservers(d)}),o?function(e){u||o(e)}:void 0,p,a)};s.openAsync(_,p)}else f();return d},t.LoadScript=function(e,t,i){var r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.type="text/javascript",n.src=e,n.onload=function(){t&&t()},n.onerror=function(t){i&&i("Unable to load script '"+e+"'",t)},r.appendChild(n)},t.ReadFileAsDataURL=function(t,i,r){var n=new FileReader,o={onCompleteObservable:new e.Observable,abort:function(){return n.abort()}};return n.onloadend=function(e){o.onCompleteObservable.notifyObservers(o)},n.onload=function(e){i(e.target.result)},n.onprogress=r,n.readAsDataURL(t),o},t.ReadFile=function(i,r,n,o){var s=new FileReader,a={onCompleteObservable:new e.Observable,abort:function(){return s.abort()}};return s.onloadend=function(e){return a.onCompleteObservable.notifyObservers(a)},s.onerror=function(e){t.Log("Error while reading file: "+i.name),r(JSON.stringify({autoClear:!0,clearColor:[1,0,0],ambientColor:[0,0,0],gravity:[0,-9.807,0],meshes:[],cameras:[],lights:[]}))},s.onload=function(e){r(e.target.result)},n&&(s.onprogress=n),o?s.readAsArrayBuffer(i):s.readAsText(i),a},t.FileAsURL=function(e){var t=new Blob([e]);return(window.URL||window.webkitURL).createObjectURL(t)},t.Format=function(e,t){return void 0===t&&(t=2),e.toFixed(t)},t.CheckExtends=function(e,t,i){e.xi.x&&(i.x=e.x),e.y>i.y&&(i.y=e.y),e.z>i.z&&(i.z=e.z)},t.DeepCopy=function(e,t,i,r){for(var n in e)if(("_"!==n[0]||r&&-1!==r.indexOf(n))&&(!i||-1===i.indexOf(n))){var o=e[n],s=typeof o;if("function"!==s)try{if("object"===s)if(o instanceof Array){if(t[n]=[],o.length>0)if("object"==typeof o[0])for(var a=0;al&&(d=l,u=d*h);var f=Math.max(0,s-u)/2,p=Math.max(0,l-d)/2,_=e.getRenderingCanvas();c&&_&&c.drawImage(_,f,p,u,d),t.EncodeScreenshotCanvasData(n,o)},t.CreateScreenshotUsingRenderTarget=function(i,r,n,o,s,a,l,c){void 0===s&&(s="image/png"),void 0===a&&(a=1),void 0===l&&(l=!1);var h,u;if(n.precision)h=Math.round(i.getRenderWidth()*n.precision),u=Math.round(h/i.getAspectRatio(r)),n={width:h,height:u};else if(n.width&&n.height)h=n.width,u=n.height;else if(n.width&&!n.height)h=n.width,u=Math.round(h/i.getAspectRatio(r)),n={width:h,height:u};else if(n.height&&!n.width)u=n.height,h=Math.round(u*i.getAspectRatio(r)),n={width:h,height:u};else{if(isNaN(n))return void t.Error("Invalid 'size' parameter !");u=n,h=n}var d=r.getScene(),f=null;d.activeCamera!==r&&(f=d.activeCamera,d.activeCamera=r);var p=new e.RenderTargetTexture("screenShot",n,d,!1,!1,e.Engine.TEXTURETYPE_UNSIGNED_INT,!1,e.Texture.NEAREST_SAMPLINGMODE);p.renderList=null,p.samples=a,l&&p.addPostProcess(new e.FxaaPostProcess("antialiasing",1,d.activeCamera)),p.onAfterRenderObservable.add((function(){t.DumpFramebuffer(h,u,i,o,s,c)})),d.incrementRenderId(),d.resetCachedMaterial(),p.render(!0),p.dispose(),f&&(d.activeCamera=f),r.getProjectionMatrix(!0)},t.ValidateXHRData=function(t,i){void 0===i&&(i=7);try{if(1&i){if(t.responseText&&t.responseText.length>0)return!0;if(1===i)return!1}if(2&i){var r=e.TGATools.GetTGAHeader(t.response);if(r.width&&r.height&&r.width>0&&r.height>0)return!0;if(2===i)return!1}if(4&i){var n=new Uint8Array(t.response,0,3);return 68===n[0]&&68===n[1]&&83===n[2]}}catch(e){}return!1},t.RandomId=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))},t.IsBase64=function(e){return!(e.length<5)&&"data:"===e.substr(0,5)},t.DecodeBase64=function(e){for(var t=atob(e.split(",")[1]),i=t.length,r=new Uint8Array(new ArrayBuffer(i)),n=0;n
";t._AddLogEntry(r)},t._WarnDisabled=function(e){},t._WarnEnabled=function(e){var i=t._FormatMessage(e);console.warn("BJS - "+i);var r="
"+i+"

";t._AddLogEntry(r)},t._ErrorDisabled=function(e){},t._ErrorEnabled=function(e){t.errorsCount++;var i=t._FormatMessage(e);console.error("BJS - "+i);var r="
"+i+"

";t._AddLogEntry(r)},Object.defineProperty(t,"LogCache",{get:function(){return t._LogCache},enumerable:!0,configurable:!0}),t.ClearLogCache=function(){t._LogCache="",t.errorsCount=0},Object.defineProperty(t,"LogLevels",{set:function(e){(e&t.MessageLogLevel)===t.MessageLogLevel?t.Log=t._LogEnabled:t.Log=t._LogDisabled,(e&t.WarningLogLevel)===t.WarningLogLevel?t.Warn=t._WarnEnabled:t.Warn=t._WarnDisabled,(e&t.ErrorLogLevel)===t.ErrorLogLevel?t.Error=t._ErrorEnabled:t.Error=t._ErrorDisabled},enumerable:!0,configurable:!0}),t.IsWindowObjectExist=function(){return"undefined"!=typeof window},Object.defineProperty(t,"PerformanceNoneLogLevel",{get:function(){return t._PerformanceNoneLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceUserMarkLogLevel",{get:function(){return t._PerformanceUserMarkLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceConsoleLogLevel",{get:function(){return t._PerformanceConsoleLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceLogLevel",{set:function(e){return(e&t.PerformanceUserMarkLogLevel)===t.PerformanceUserMarkLogLevel?(t.StartPerformanceCounter=t._StartUserMark,void(t.EndPerformanceCounter=t._EndUserMark)):(e&t.PerformanceConsoleLogLevel)===t.PerformanceConsoleLogLevel?(t.StartPerformanceCounter=t._StartPerformanceConsole,void(t.EndPerformanceCounter=t._EndPerformanceConsole)):(t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,void(t.EndPerformanceCounter=t._EndPerformanceCounterDisabled))},enumerable:!0,configurable:!0}),t._StartPerformanceCounterDisabled=function(e,t){},t._EndPerformanceCounterDisabled=function(e,t){},t._StartUserMark=function(e,i){if(void 0===i&&(i=!0),!t._performance){if(!t.IsWindowObjectExist())return;t._performance=window.performance}i&&t._performance.mark&&t._performance.mark(e+"-Begin")},t._EndUserMark=function(e,i){void 0===i&&(i=!0),i&&t._performance.mark&&(t._performance.mark(e+"-End"),t._performance.measure(e,e+"-Begin",e+"-End"))},t._StartPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._StartUserMark(e,i),console.time&&console.time(e))},t._EndPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._EndUserMark(e,i),console.time&&console.timeEnd(e))},Object.defineProperty(t,"Now",{get:function(){return t.IsWindowObjectExist()&&window.performance&&window.performance.now?window.performance.now():Date.now()},enumerable:!0,configurable:!0}),t.GetClassName=function(e,t){void 0===t&&(t=!1);var i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__}i||(i=typeof e)}return i},t.First=function(e,t){for(var i=0,r=e;i=e.length)return null;var r=e.charCodeAt?e.charCodeAt(i):e[i];return r&&r.getHashCode&&(r=r.getHashCode()),"string"==typeof r?t.hashCodeFromStream(t.arrayOrStringFeeder(r)):r}},t.hashCodeFromStream=function(e){for(var t=0,i=0,r=e(i++);null!=r;)t=(t<<5)-t+r,t|=0,r=e(i++);return t},t.DelayAsync=function(e){return new Promise(function(t){setTimeout((function(){t()}),e)})},t.GetCurrentGradient=function(e,t,i){for(var r=0;r=n.gradient&&e<=o.gradient){i(n,o,(e-n.gradient)/(o.gradient-n.gradient))}}},t.BaseUrl="",t.DefaultRetryStrategy=s.ExponentialBackoff(),t.CorsBehavior="anonymous",t.UseFallbackTexture=!0,t.RegisteredExternalClasses={},t.fallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z",t._tmpFloatArray=new Float32Array(1),t.PreprocessUrl=function(e){return e},t._NoneLogLevel=0,t._MessageLogLevel=1,t._WarningLogLevel=2,t._ErrorLogLevel=4,t._LogCache="",t.errorsCount=0,t.Log=t._LogEnabled,t.Warn=t._WarnEnabled,t.Error=t._ErrorEnabled,t._PerformanceNoneLogLevel=0,t._PerformanceUserMarkLogLevel=1,t._PerformanceConsoleLogLevel=2,t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,t.EndPerformanceCounter=t._EndPerformanceCounterDisabled,t})();e.Tools=c;var h=(function(){function e(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}return Object.defineProperty(e.prototype,"min",{get:function(){return this._min},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"max",{get:function(){return this._max},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"average",{get:function(){return this._average},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lastSecAverage",{get:function(){return this._lastSecAverage},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"current",{get:function(){return this._current},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"total",{get:function(){return this._totalAccumulated},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"count",{get:function(){return this._totalValueCount},enumerable:!0,configurable:!0}),e.prototype.fetchNewFrame=function(){this._totalValueCount++,this._current=0,this._lastSecValueCount++},e.prototype.addCount=function(t,i){e.Enabled&&(this._current+=t,i&&this._fetchResult())},e.prototype.beginMonitoring=function(){e.Enabled&&(this._startMonitoringTime=c.Now)},e.prototype.endMonitoring=function(t){if(void 0===t&&(t=!0),e.Enabled){t&&this.fetchNewFrame();var i=c.Now;this._current=i-this._startMonitoringTime,t&&this._fetchResult()}},e.prototype._fetchResult=function(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;var e=c.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)},e.Enabled=!0,e})();e.PerfCounter=h,e.className=t;var u=(function(){function e(e,t,i,r){void 0===r&&(r=0),this.iterations=e,this._fn=t,this._successCallback=i,this.index=r-1,this._done=!1}return e.prototype.executeNext=function(){this._done||(this.index+1=t)break;if(r(s),o&&o()){e.breakLoop();break}}e.executeNext()}),s)}),n)},e})();e.AsyncLoop=u})(r||(r={}));var r;!(function(e){var t;!(function(e){e[e.Pending=0]="Pending",e[e.Fulfilled=1]="Fulfilled",e[e.Rejected=2]="Rejected"})(t||(t={}));var i=(function(){function e(){this.count=0,this.target=0,this.results=[]}return e})(),r=(function(){function r(e){var i=this;if(this._state=t.Pending,this._children=new Array,this._rejectWasConsumed=!1,e)try{e((function(e){i._resolve(e)}),(function(e){i._reject(e)}))}catch(e){this._reject(e)}}return Object.defineProperty(r.prototype,"_result",{get:function(){return this._resultValue},set:function(e){this._resultValue=e,this._parent&&void 0===this._parent._result&&(this._parent._result=e)},enumerable:!0,configurable:!0}),r.prototype.catch=function(e){return this.then(void 0,e)},r.prototype.then=function(i,n){var o=this,s=new r;return s._onFulfilled=i,s._onRejected=n,this._children.push(s),s._parent=this,this._state!==t.Pending&&e.Tools.SetImmediate((function(){if(o._state===t.Fulfilled||o._rejectWasConsumed){var e=s._resolve(o._result);if(void 0!==e&&null!==e)if(void 0!==e._state){var i=e;s._children.push(i),i._parent=s,s=i}else s._result=e}else s._reject(o._reason)})),s},r.prototype._moveChildren=function(e){var i,r=this;if((i=this._children).push.apply(i,e.splice(0,e.length)),this._children.forEach((function(e){e._parent=r})),this._state===t.Fulfilled)for(var n=0,o=this._children;n-1){if(d.capture&&d.captureConstraint){var _=d.capture,m=d.captureConstraint,g=new RegExp(_),v=g.exec(c);if(v&&v.length>0){var y=parseInt(v[v.length-1]);if(y>=m)continue}}for(var b=0,x=p;b1&&!this.disableUniformBuffers},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"needPOTTextures",{get:function(){return this._webGLVersion<2||this.forcePOTTextures},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"doNotHandleContextLost",{get:function(){return this._doNotHandleContextLost},set:function(e){this._doNotHandleContextLost=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"performanceMonitor",{get:function(){return this._performanceMonitor},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"texturesSupported",{get:function(){return this._texturesSupported},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"currentViewport",{get:function(){return this._cachedViewport},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"emptyTexture",{get:function(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,i.TEXTUREFORMAT_RGBA,!1,!1,i.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"emptyTexture3D",{get:function(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,i.TEXTUREFORMAT_RGBA,!1,!1,i.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture3D},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"emptyCubeTexture",{get:function(){if(!this._emptyCubeTexture){var e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,i.TEXTUREFORMAT_RGBA,i.TEXTURETYPE_UNSIGNED_INT,!1,!1,i.TEXTURE_NEAREST_SAMPLINGMODE)}return this._emptyCubeTexture},enumerable:!0,configurable:!0}),i.prototype._rebuildInternalTextures=function(){for(var e=this._internalTexturesCache.slice(),t=0,i=e;t1||null!==this._gl.getExtension("OES_standard_derivatives"),this._caps.astc=this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),this._caps.s3tc=this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),this._caps.pvrtc=this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),this._caps.etc1=this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),this._caps.etc2=this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),this._caps.textureAnisotropicFilterExtension=this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.uintIndices=this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),this._caps.fragmentDepthSupported=this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),this._caps.highPrecisionShaderSupported=!0,this._caps.timerQuery=this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)>0),this._caps.colorBufferFloat=this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float"),this._caps.textureFloat=!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloat=!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._webGLVersion>1&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._caps.textureLOD=!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),this._webGLVersion>1)this._caps.drawBuffersExtension=!0;else{var t=this._gl.getExtension("WEBGL_draw_buffers");if(null!==t){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=t.drawBuffersWEBGL.bind(t),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(var i=0;i<16;i++)this._gl["COLOR_ATTACHMENT"+i+"_WEBGL"]=t["COLOR_ATTACHMENT"+i+"_WEBGL"]}else this._caps.drawBuffersExtension=!1}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{var r=this._gl.getExtension("WEBGL_depth_texture");null!=r&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=r.UNSIGNED_INT_24_8_WEBGL)}if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{var n=this._gl.getExtension("OES_vertex_array_object");null!=n?(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=n.createVertexArrayOES.bind(n),this._gl.bindVertexArray=n.bindVertexArrayOES.bind(n),this._gl.deleteVertexArray=n.deleteVertexArrayOES.bind(n)):this._caps.vertexArrayObject=!1}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{var s=this._gl.getExtension("ANGLE_instanced_arrays");null!=s?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=s.drawArraysInstancedANGLE.bind(s),this._gl.drawElementsInstanced=s.drawElementsInstancedANGLE.bind(s),this._gl.vertexAttribDivisor=s.vertexAttribDivisorANGLE.bind(s)):this._caps.instancedArrays=!1}if(this._caps.astc&&this.texturesSupported.push("-astc.ktx"),this._caps.s3tc&&this.texturesSupported.push("-dxt.ktx"),this._caps.pvrtc&&this.texturesSupported.push("-pvrtc.ktx"),this._caps.etc2&&this.texturesSupported.push("-etc2.ktx"),this._caps.etc1&&this.texturesSupported.push("-etc1.ktx"),this._gl.getShaderPrecisionFormat){var a=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);a&&(this._caps.highPrecisionShaderSupported=0!==a.precision)}this.setDepthBuffer(!0),this.setDepthFunctionToLessOrEqual(),this.setDepthWrite(!0),this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(var l=0;l=0&&this._activeRenderLoops.splice(t,1)},i.prototype._renderLoop=function(){if(!this._contextWasLost){var t=!0;if(!this.renderEvenInBackground&&this._windowIsBackground&&(t=!1),t){this.beginFrame();for(var i=0;i0){var r=null;this._vrDisplay&&this._vrDisplay.isPresenting&&(r=this._vrDisplay),this._frameHandler=e.Tools.QueueNewFrame(this._bindedRenderFunction,r)}else this._renderingQueueLaunched=!1},i.prototype.runRenderLoop=function(t){-1===this._activeRenderLoops.indexOf(t)&&(this._activeRenderLoops.push(t),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._bindedRenderFunction=this._renderLoop.bind(this),this._frameHandler=e.Tools.QueueNewFrame(this._bindedRenderFunction)))},i.prototype.switchFullscreen=function(t){this.isFullscreen?e.Tools.ExitFullscreen():(this._pointerLockRequested=t,this._renderingCanvas&&e.Tools.RequestFullscreen(this._renderingCanvas))},i.prototype.clear=function(e,t,i,r){void 0===r&&(r=!1),this.applyStates();var n=0;t&&e&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),n|=this._gl.COLOR_BUFFER_BIT),i&&(this._gl.clearDepth(1),n|=this._gl.DEPTH_BUFFER_BIT),r&&(this._gl.clearStencil(0),n|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(n)},i.prototype.scissorClear=function(e,t,i,r,n){var o=this._gl,s=o.getParameter(o.SCISSOR_TEST),a=o.getParameter(o.SCISSOR_BOX);o.enable(o.SCISSOR_TEST),o.scissor(e,t,i,r),this.clear(n,!0,!0,!0),o.scissor(a[0],a[1],a[2],a[3]),!0===s?o.enable(o.SCISSOR_TEST):o.disable(o.SCISSOR_TEST)},i.prototype._viewport=function(e,t,i,r){e===this._viewportCached.x&&t===this._viewportCached.y&&i===this._viewportCached.z&&r===this._viewportCached.w||(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r,this._gl.viewport(e,t,i,r))},i.prototype.setViewport=function(e,t,i){var r=t||this.getRenderWidth(),n=i||this.getRenderHeight(),o=e.x||0,s=e.y||0;this._cachedViewport=e,this._viewport(o*r,s*n,r*e.width,n*e.height)},i.prototype.setDirectViewport=function(e,t,i,r){var n=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),n},i.prototype.beginFrame=function(){this.onBeginFrameObservable.notifyObservers(this),this._measureFps()},i.prototype.endFrame=function(){this._badOS&&this.flushFramebuffer(),this._vrDisplay&&this._vrDisplay.isPresenting&&this._vrDisplay.submitFrame(),this.onEndFrameObservable.notifyObservers(this)},i.prototype.resize=function(){if(!this._vrDisplay||!this._vrDisplay.isPresenting){var e=this._renderingCanvas?this._renderingCanvas.clientWidth:window.innerWidth,t=this._renderingCanvas?this._renderingCanvas.clientHeight:window.innerHeight;this.setSize(e/this._hardwareScalingLevel,t/this._hardwareScalingLevel)}},i.prototype.setSize=function(e,t){if(this._renderingCanvas&&(this._renderingCanvas.width!==e||this._renderingCanvas.height!==t)){this._renderingCanvas.width=e,this._renderingCanvas.height=t;for(var i=0;i1?"COLOR_ATTACHMENT"+o:"COLOR_ATTACHMENT"+o+"_WEBGL"],r.readBuffer(n[o]),r.drawBuffers(n),r.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(var o=0;o1?"COLOR_ATTACHMENT"+o:"COLOR_ATTACHMENT"+o+"_WEBGL"];r.drawBuffers(n)}for(var o=0;o65535){n=!0;break}r=n?new Uint32Array(e):new Uint16Array(e)}else r=new Uint16Array(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),i.references=1,i.is32Bits=n,i},i.prototype.bindArrayBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(e,this._gl.ARRAY_BUFFER)},i.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e)},i.prototype.bindUniformBufferBase=function(e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e)},i.prototype.bindUniformBlock=function(e,t,i){var r=this._gl.getUniformBlockIndex(e,t);this._gl.uniformBlockBinding(e,r,i)},i.prototype.bindIndexBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)},i.prototype.bindBuffer=function(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e),this._currentBoundBuffer[t]=e)},i.prototype.updateArrayBuffer=function(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)},i.prototype._vertexAttribPointer=function(e,t,i,r,n,o,s){var a=this._currentBufferPointers[t],l=!1;a.active?(a.buffer!==e&&(a.buffer=e,l=!0),a.size!==i&&(a.size=i,l=!0),a.type!==r&&(a.type=r,l=!0),a.normalized!==n&&(a.normalized=n,l=!0),a.stride!==o&&(a.stride=o,l=!0),a.offset!==s&&(a.offset=s,l=!0)):(l=!0,a.active=!0,a.index=t,a.size=i,a.type=r,a.normalized=n,a.stride=o,a.offset=s,a.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),this._gl.vertexAttribPointer(t,i,r,n,o,s))},i.prototype._bindIndexBufferWithCache=function(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)},i.prototype._bindVertexBuffersAttributes=function(e,t){var i=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var r=0;r=0){var o=e[i[r]];if(!o)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);var s=o.getBuffer();s&&(this._vertexAttribPointer(s,n,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(s))))}}},i.prototype.recordVertexArrayObject=function(e,t,i){var r=this._gl.createVertexArray();return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r},i.prototype.bindVertexArrayObject=function(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)},i.prototype.bindBuffersDirectly=function(e,t,i,r,n){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==n){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=n;var o=n.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var s=0,a=0;a=0&&(this._gl.enableVertexAttribArray(l),this._vertexAttribArraysEnabled[l]=!0,this._vertexAttribPointer(e,l,i[a],this._gl.FLOAT,!1,r,s)),s+=4*i[a]}}this._bindIndexBufferWithCache(t)},i.prototype._unbindVertexArrayObject=function(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))},i.prototype.bindBuffers=function(e,t,i){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i)),this._bindIndexBufferWithCache(t)},i.prototype.unbindInstanceAttributes=function(){for(var e,t=0,i=this._currentInstanceLocations.length;t1?"#version 300 es\n#define WEBGL2 \n":"",s=this._compileShader(e,"vertex",i,o),a=this._compileShader(t,"fragment",i,o),l=this._createShaderProgram(s,a,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),l},i.prototype._createShaderProgram=function(e,t,i,r){void 0===r&&(r=null);var n=i.createProgram();if(!n)throw new Error("Unable to create program");if(i.attachShader(n,e),i.attachShader(n,t),this.webGLVersion>1&&r){var o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(n,r),n.transformFeedback=o}if(i.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),!i.getProgramParameter(n,i.LINK_STATUS)){var s=i.getProgramInfoLog(n);if(s)throw new Error(s)}if(this.validateShaderPrograms){i.validateProgram(n);if(!i.getProgramParameter(n,i.VALIDATE_STATUS)){var s=i.getProgramInfoLog(n);if(s)throw new Error(s)}}return i.deleteShader(e),i.deleteShader(t),n},i.prototype.getUniforms=function(e,t){for(var i=new Array,r=0;r-1?p.substring(y).toLowerCase():""),x=null,T=0,E=i._TextureLoaders;Tc||t.height>c)return f._prepareWorkingCanvas(),!(!f._workingCanvas||!f._workingContext)&&(f._workingCanvas.width=i,f._workingCanvas.height=r,f._workingContext.drawImage(t,0,0,t.width,t.height,0,0,i,r),s.texImage2D(s.TEXTURE_2D,0,l,l,s.UNSIGNED_BYTE,f._workingCanvas),v.width=i,v.height=r,!1);var h=new e.InternalTexture(f,e.InternalTexture.DATASOURCE_TEMP);return f._bindTextureDirectly(s.TEXTURE_2D,h,!0),s.texImage2D(s.TEXTURE_2D,0,l,l,s.UNSIGNED_BYTE,t),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),f._rescaleTexture(h,v,o,l,(function(){f._releaseTexture(h),f._bindTextureDirectly(s.TEXTURE_2D,v,!0),n()})),!0}),s)};!_||g?c instanceof HTMLImageElement?C(c):e.Tools.LoadImage(p,C,M,o?o.database:null):"string"==typeof c||c instanceof ArrayBuffer||c instanceof Blob?e.Tools.LoadImage(c,C,M,o?o.database:null):C(c)}return v},i.prototype._rescaleTexture=function(t,r,n,o,s){var a=this,l=this.createRenderTargetTexture({width:r.width,height:r.height},{generateMipMaps:!1,type:i.TEXTURETYPE_UNSIGNED_INT,samplingMode:i.TEXTURE_BILINEAR_SAMPLINGMODE,generateDepthBuffer:!1,generateStencilBuffer:!1});this._rescalePostProcess||(this._rescalePostProcess=new e.PassPostProcess("rescale",1,null,i.TEXTURE_BILINEAR_SAMPLINGMODE,this,!1,i.TEXTURETYPE_UNSIGNED_INT)),this._rescalePostProcess.getEffect().executeWhenCompiled((function(){a._rescalePostProcess.onApply=function(e){e._bindTexture("textureSampler",t)};var e=n;e||(e=a.scenes[a.scenes.length-1]),e.postProcessManager.directRender([a._rescalePostProcess],l,!0),a._bindTextureDirectly(a._gl.TEXTURE_2D,r,!0),a._gl.copyTexImage2D(a._gl.TEXTURE_2D,0,o,0,0,r.width,r.height,0),a.unBindFramebuffer(l),a._releaseTexture(l),s&&s()}))},i.prototype.updateRawTexture=function(e,t,r,n,o,s){if(void 0===o&&(o=null),void 0===s&&(s=i.TEXTURETYPE_UNSIGNED_INT),e){var a=this._getRGBABufferInternalSizedFormat(s,r),l=this._getInternalFormat(r),c=this._getWebGLTextureType(s);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(e._bufferView=t,e.format=r,e.type=s,e.invertY=n,e._compression=o),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),o&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[o],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,e.width,e.height,0,l,c,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}},i.prototype.createRawTexture=function(t,r,n,o,s,a,l,c,h){void 0===c&&(c=null),void 0===h&&(h=i.TEXTURETYPE_UNSIGNED_INT);var u=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RAW);u.baseWidth=r,u.baseHeight=n,u.width=r,u.height=n,u.format=o,u.generateMipMaps=s,u.samplingMode=l,u.invertY=a,u._compression=c,u.type=h,this._doNotHandleContextLost||(u._bufferView=t),this.updateRawTexture(u,t,o,a,c,h),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);var d=this._getSamplingParameters(l,s);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},i.prototype._unpackFlipY=function(e){this._unpackFlipYCached!==e&&(this._unpackFlipYCached=e,this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0))}, +i.prototype._getUnpackAlignement=function(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)},i.prototype.createDynamicTexture=function(t,i,r,n){var o=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_DYNAMIC);return o.baseWidth=t,o.baseHeight=i,r&&(t=this.needPOTTextures?e.Tools.GetExponentOfTwo(t,this._caps.maxTextureSize):t,i=this.needPOTTextures?e.Tools.GetExponentOfTwo(i,this._caps.maxTextureSize):i),o.width=t,o.height=i,o.isReady=!1,o.generateMipMaps=r,o.samplingMode=n,this.updateTextureSamplingMode(n,o),this._internalTexturesCache.push(o),o},i.prototype.updateTextureSamplingMode=function(e,t){var i=this._getSamplingParameters(e,t.generateMipMaps);t.isCube?(this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):t.is3D?(this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_3D,null)):(this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),t.samplingMode=e},i.prototype.updateDynamicTexture=function(e,t,i,r,n){if(void 0===r&&(r=!1),e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(i),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);var o=n?this._getInternalFormat(n):this._gl.RGBA;this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,o,this._gl.UNSIGNED_BYTE,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0}},i.prototype.updateVideoTexture=function(e,t,i){if(e&&!e._isDisabled){var r=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=document.createElement("canvas");var n=e._workingCanvas.getContext("2d");if(!n)throw new Error("Unable to get 2d context");e._workingContext=n,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),r||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}}},i.prototype.updateTextureComparisonFunction=function(t,r){if(1===this.webGLVersion)return void e.Tools.Error("WebGL 1 does not support texture comparison.");var n=this._gl;t.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,t,!0),0===r?(n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_FUNC,i.LEQUAL),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_MODE,n.NONE)):(n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_FUNC,r),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),0===r?(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_FUNC,i.LEQUAL),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_MODE,n.NONE)):(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_FUNC,r),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),t._comparisonFunction=r},i.prototype._setupDepthStencilTexture=function(e,t,r,n,o){var s=t.width||t,a=t.height||t;e.baseWidth=s,e.baseHeight=a,e.width=s,e.height=a,e.isReady=!0,e.samples=1,e.generateMipMaps=!1,e._generateDepthBuffer=!0,e._generateStencilBuffer=r,e.samplingMode=n?i.TEXTURE_BILINEAR_SAMPLINGMODE:i.TEXTURE_NEAREST_SAMPLINGMODE,e.type=i.TEXTURETYPE_UNSIGNED_INT,e._comparisonFunction=o;var l=this._gl,c=e.isCube?l.TEXTURE_CUBE_MAP:l.TEXTURE_2D,h=this._getSamplingParameters(e.samplingMode,!1);l.texParameteri(c,l.TEXTURE_MAG_FILTER,h.mag),l.texParameteri(c,l.TEXTURE_MIN_FILTER,h.min),l.texParameteri(c,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(c,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),0===o?(l.texParameteri(c,l.TEXTURE_COMPARE_FUNC,i.LEQUAL),l.texParameteri(c,l.TEXTURE_COMPARE_MODE,l.NONE)):(l.texParameteri(c,l.TEXTURE_COMPARE_FUNC,o),l.texParameteri(c,l.TEXTURE_COMPARE_MODE,l.COMPARE_REF_TO_TEXTURE))},i.prototype.createDepthStencilTexture=function(e,t){if(t.isCube){var i=e.width||e;return this._createDepthStencilCubeTexture(i,t)}return this._createDepthStencilTexture(e,t)},i.prototype._createDepthStencilTexture=function(t,i){var r=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_DEPTHTEXTURE);if(!this._caps.depthTextureExtension)return e.Tools.Error("Depth texture is not supported by your browser or hardware."),r;var n=s({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},i),o=this._gl;return this._bindTextureDirectly(o.TEXTURE_2D,r,!0),this._setupDepthStencilTexture(r,t,n.generateStencil,n.bilinearFiltering,n.comparisonFunction),this.webGLVersion>1?n.generateStencil?o.texImage2D(o.TEXTURE_2D,0,o.DEPTH24_STENCIL8,r.width,r.height,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_COMPONENT24,r.width,r.height,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null):n.generateStencil?o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_STENCIL,r.width,r.height,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_COMPONENT,r.width,r.height,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null),this._bindTextureDirectly(o.TEXTURE_2D,null),r},i.prototype._createDepthStencilCubeTexture=function(t,i){var r=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_UNKNOWN);if(r.isCube=!0,1===this.webGLVersion)return e.Tools.Error("Depth cube texture is not supported by WebGL 1."),r;var n=s({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},i),o=this._gl;this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,r,!0),this._setupDepthStencilTexture(r,t,n.generateStencil,n.bilinearFiltering,n.comparisonFunction);for(var a=0;a<6;a++)n.generateStencil?o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,o.DEPTH24_STENCIL8,t,t,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,o.DEPTH_COMPONENT24,t,t,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null);return this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null),r},i.prototype.setFrameBufferDepthStencilTexture=function(e){var t=e.getInternalTexture();if(t&&t._framebuffer&&e.depthStencilTexture){var i=this._gl,r=e.depthStencilTexture;this.bindUnboundFramebuffer(t._framebuffer),r.isCube?r._generateStencilBuffer?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_CUBE_MAP_POSITIVE_X,r._webGLTexture,0):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_CUBE_MAP_POSITIVE_X,r._webGLTexture,0):r._generateStencilBuffer?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_2D,r._webGLTexture,0):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,r._webGLTexture,0),this.bindUnboundFramebuffer(null)}},i.prototype.createRenderTargetTexture=function(t,n){var o=new r;void 0!==n&&"object"==typeof n?(o.generateMipMaps=n.generateMipMaps,o.generateDepthBuffer=void 0===n.generateDepthBuffer||n.generateDepthBuffer,o.generateStencilBuffer=o.generateDepthBuffer&&n.generateStencilBuffer,o.type=void 0===n.type?i.TEXTURETYPE_UNSIGNED_INT:n.type,o.samplingMode=void 0===n.samplingMode?i.TEXTURE_TRILINEAR_SAMPLINGMODE:n.samplingMode,o.format=void 0===n.format?i.TEXTUREFORMAT_RGBA:n.format):(o.generateMipMaps=n,o.generateDepthBuffer=!0,o.generateStencilBuffer=!1,o.type=i.TEXTURETYPE_UNSIGNED_INT,o.samplingMode=i.TEXTURE_TRILINEAR_SAMPLINGMODE,o.format=i.TEXTUREFORMAT_RGBA),o.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering?o.type!==i.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering||(o.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE):o.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE;var s=this._gl,a=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RENDERTARGET);this._bindTextureDirectly(s.TEXTURE_2D,a,!0);var l=t.width||t,c=t.height||t,h=this._getSamplingParameters(o.samplingMode,!!o.generateMipMaps);o.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloat||(o.type=i.TEXTURETYPE_UNSIGNED_INT,e.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,h.mag),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,h.min),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(o.type,o.format),l,c,0,this._getInternalFormat(o.format),this._getWebGLTextureType(o.type),null);var u=this._currentFramebuffer,d=s.createFramebuffer();return this.bindUnboundFramebuffer(d),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,a._webGLTexture,0),a._depthStencilBuffer=this._setupFramebufferDepthAttachments(!!o.generateStencilBuffer,o.generateDepthBuffer,l,c),o.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),this.bindUnboundFramebuffer(u),a._framebuffer=d,a.baseWidth=l,a.baseHeight=c,a.width=l,a.height=c,a.isReady=!0,a.samples=1,a.generateMipMaps=!!o.generateMipMaps,a.samplingMode=o.samplingMode,a.type=o.type,a._generateDepthBuffer=o.generateDepthBuffer,a._generateStencilBuffer=!!o.generateStencilBuffer,this._internalTexturesCache.push(a),a},i.prototype.createMultipleRenderTarget=function(t,r){var n=!1,o=!0,s=!1,a=!1,l=1,c=i.TEXTURETYPE_UNSIGNED_INT,h=i.TEXTURE_TRILINEAR_SAMPLINGMODE,u=new Array,d=new Array;void 0!==r&&(n=void 0!==r.generateMipMaps&&r.generateMipMaps,o=void 0===r.generateDepthBuffer||r.generateDepthBuffer,s=void 0!==r.generateStencilBuffer&&r.generateStencilBuffer,a=void 0!==r.generateDepthTexture&&r.generateDepthTexture,l=r.textureCount||1,r.types&&(u=r.types),r.samplingModes&&(d=r.samplingModes));var f=this._gl,p=f.createFramebuffer();this.bindUnboundFramebuffer(p);for(var _=t.width||t,m=t.height||t,g=[],v=[],y=this._setupFramebufferDepthAttachments(s,o,_,m),b=0;b1?"COLOR_ATTACHMENT"+b:"COLOR_ATTACHMENT"+b+"_WEBGL"];g.push(P),v.push(A),f.activeTexture(f["TEXTURE"+b]),f.bindTexture(f.TEXTURE_2D,P._webGLTexture),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MAG_FILTER,E.mag),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MIN_FILTER,E.min),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),f.texImage2D(f.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(T),_,m,0,f.RGBA,this._getWebGLTextureType(T),null),f.framebufferTexture2D(f.DRAW_FRAMEBUFFER,A,f.TEXTURE_2D,P._webGLTexture,0),n&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(f.TEXTURE_2D,null),P._framebuffer=p,P._depthStencilBuffer=y,P.baseWidth=_,P.baseHeight=m,P.width=_,P.height=m,P.isReady=!0,P.samples=1,P.generateMipMaps=n,P.samplingMode=x,P.type=T,P._generateDepthBuffer=o,P._generateStencilBuffer=s,P._attachments=v,this._internalTexturesCache.push(P)}if(a&&this._caps.depthTextureExtension){var M=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_MULTIRENDERTARGET);f.activeTexture(f.TEXTURE0),f.bindTexture(f.TEXTURE_2D,M._webGLTexture),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MAG_FILTER,f.NEAREST),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MIN_FILTER,f.NEAREST),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),f.texImage2D(f.TEXTURE_2D,0,this.webGLVersion<2?f.DEPTH_COMPONENT:f.DEPTH_COMPONENT16,_,m,0,f.DEPTH_COMPONENT,f.UNSIGNED_SHORT,null),f.framebufferTexture2D(f.FRAMEBUFFER,f.DEPTH_ATTACHMENT,f.TEXTURE_2D,M._webGLTexture,0),M._framebuffer=p,M.baseWidth=_,M.baseHeight=m,M.width=_,M.height=m,M.isReady=!0,M.samples=1,M.generateMipMaps=n,M.samplingMode=f.NEAREST,M._generateDepthBuffer=o,M._generateStencilBuffer=s,g.push(M),this._internalTexturesCache.push(M)}return f.drawBuffers(v),f.bindRenderbuffer(f.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),this.resetTextureCache(),g},i.prototype._setupFramebufferDepthAttachments=function(e,t,i,r,n){void 0===n&&(n=1);var o=null,s=this._gl;return e?(o=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,o),n>1?s.renderbufferStorageMultisample(s.RENDERBUFFER,n,s.DEPTH24_STENCIL8,i,r):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,i,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,o)):t&&(o=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,o),n>1?s.renderbufferStorageMultisample(s.RENDERBUFFER,n,s.DEPTH_COMPONENT16,i,r):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT16,i,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,o)),o},i.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e)return 1;if(e.samples===t)return t;var i=this._gl;if(t=Math.min(t,i.getParameter(i.MAX_SAMPLES)),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),e._MSAARenderBuffer&&(i.deleteRenderbuffer(e._MSAARenderBuffer),e._MSAARenderBuffer=null),t>1){var r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this.bindUnboundFramebuffer(e._MSAAFramebuffer);var n=i.createRenderbuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorageMultisample(i.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(e.type),e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,n),e._MSAARenderBuffer=n}else this.bindUnboundFramebuffer(e._framebuffer);return e.samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.width,e.height,t),i.bindRenderbuffer(i.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),t},i.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||0==e.length)return 1;if(e[0].samples===t)return t;var i=this._gl;t=Math.min(t,i.getParameter(i.MAX_SAMPLES)),e[0]._depthStencilBuffer&&(i.deleteRenderbuffer(e[0]._depthStencilBuffer),e[0]._depthStencilBuffer=null),e[0]._MSAAFramebuffer&&(i.deleteFramebuffer(e[0]._MSAAFramebuffer),e[0]._MSAAFramebuffer=null);for(var r=0;r1){var n=i.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");this.bindUnboundFramebuffer(n);for(var o=this._setupFramebufferDepthAttachments(e[0]._generateStencilBuffer,e[0]._generateDepthBuffer,e[0].width,e[0].height,t),s=[],r=0;r1?"COLOR_ATTACHMENT"+r:"COLOR_ATTACHMENT"+r+"_WEBGL"],c=i.createRenderbuffer();if(!c)throw new Error("Unable to create multi sampled framebuffer");i.bindRenderbuffer(i.RENDERBUFFER,c),i.renderbufferStorageMultisample(i.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(a.type),a.width,a.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,l,i.RENDERBUFFER,c),a._MSAAFramebuffer=n,a._MSAARenderBuffer=c,a.samples=t,a._depthStencilBuffer=o,i.bindRenderbuffer(i.RENDERBUFFER,null),s.push(l)}i.drawBuffers(s)}else this.bindUnboundFramebuffer(e[0]._framebuffer);return this.bindUnboundFramebuffer(null),t},i.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,r,n,o,s){void 0===o&&(o=0),void 0===s&&(s=0);var a=this._gl,l=a.TEXTURE_2D;e.isCube&&(l=a.TEXTURE_CUBE_MAP_POSITIVE_X+o),this._gl.compressedTexImage2D(l,s,t,i,r,0,n)},i.prototype._uploadDataToTextureDirectly=function(t,i,r,n){void 0===r&&(r=0),void 0===n&&(n=0);var o=this._gl,s=this._getWebGLTextureType(t.type),a=this._getInternalFormat(t.format),l=this._getRGBABufferInternalSizedFormat(t.type,a);this._unpackFlipY(t.invertY);var c=o.TEXTURE_2D;t.isCube&&(c=o.TEXTURE_CUBE_MAP_POSITIVE_X+r);var h=Math.round(e.Scalar.Log2(t.width)),u=Math.round(e.Scalar.Log2(t.height)),d=Math.pow(2,Math.max(h-n,0)),f=Math.pow(2,Math.max(u-n,0));o.texImage2D(c,n,l,d,f,0,a,s,i)},i.prototype._uploadArrayBufferViewToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0);var n=this._gl,o=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(o,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(o,null,!0)},i.prototype._uploadImageToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0);var n=this._gl,o=this._getWebGLTextureType(e.type),s=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,s),l=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);var c=n.TEXTURE_2D;e.isCube&&(c=n.TEXTURE_CUBE_MAP_POSITIVE_X+i),n.texImage2D(c,r,a,s,o,t),this._bindTextureDirectly(l,null,!0)},i.prototype.createRenderTargetCubeTexture=function(t,r){var n=s({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:i.TEXTURETYPE_UNSIGNED_INT,samplingMode:i.TEXTURE_TRILINEAR_SAMPLINGMODE,format:i.TEXTUREFORMAT_RGBA},r);n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,n.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering?n.type!==i.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering||(n.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE):n.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE;var o=this._gl,a=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RENDERTARGET);this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,a,!0);var l=this._getSamplingParameters(n.samplingMode,n.generateMipMaps);n.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloat||(n.type=i.TEXTURETYPE_UNSIGNED_INT,e.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,l.mag),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,l.min),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE);for(var c=0;c<6;c++)o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+c,0,this._getRGBABufferInternalSizedFormat(n.type,n.format),t,t,0,this._getInternalFormat(n.format),this._getWebGLTextureType(n.type),null);var h=o.createFramebuffer();return this.bindUnboundFramebuffer(h),a._depthStencilBuffer=this._setupFramebufferDepthAttachments(n.generateStencilBuffer,n.generateDepthBuffer,t,t),n.generateMipMaps&&o.generateMipmap(o.TEXTURE_CUBE_MAP),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null),o.bindRenderbuffer(o.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),a._framebuffer=h,a.width=t,a.height=t,a.isReady=!0,a.isCube=!0,a.samples=1,a.generateMipMaps=n.generateMipMaps,a.samplingMode=n.samplingMode,a.type=n.type,a._generateDepthBuffer=n.generateDepthBuffer,a._generateStencilBuffer=n.generateStencilBuffer,this._internalTexturesCache.push(a),a},i.prototype.createPrefilteredCubeTexture=function(t,i,r,n,o,s,a,l,c){var h=this;void 0===o&&(o=null),void 0===s&&(s=null),void 0===l&&(l=null),void 0===c&&(c=!0);var u=function(t){if(!t)return void(o&&o(null));var s=t.texture;if(c?t.info.sphericalPolynomial&&(s._sphericalPolynomial=t.info.sphericalPolynomial):s._sphericalPolynomial=new e.SphericalPolynomial,s._dataSource=e.InternalTexture.DATASOURCE_CUBEPREFILTERED,h._caps.textureLOD)return void(o&&o(s));var a=h._gl,l=t.width;if(l){for(var u=[],d=0;d<3;d++){var f=d/2,p=1-f,_=n,m=e.Scalar.Log2(l)*r+n,g=_+(m-_)*p,v=Math.round(Math.min(Math.max(g,0),m)),y=new e.InternalTexture(h,e.InternalTexture.DATASOURCE_TEMP);if(y.type=s.type,y.format=s.format,y.width=Math.pow(2,Math.max(e.Scalar.Log2(l)-v,0)),y.height=y.width,y.isCube=!0,h._bindTextureDirectly(a.TEXTURE_CUBE_MAP,y,!0),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),t.isDDS){var b=t.info,x=t.data;h._unpackFlipY(b.isCompressed),e.DDSTools.UploadDDSLevels(h,y,x,b,!0,6,v)}else e.Tools.Warn("DDS is the only prefiltered cube map supported so far.");h._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);var T=new e.BaseTexture(i);T.isCube=!0,T._texture=y,y.isReady=!0,u.push(T)}s._lodTextureHigh=u[2],s._lodTextureMid=u[1],s._lodTextureLow=u[0],o&&o(s)}};return this.createCubeTexture(t,i,null,!1,u,s,a,l,c,r,n)},i.prototype.createCubeTexture=function(t,r,n,o,s,a,l,c,h,u,d,f){var p=this;void 0===s&&(s=null),void 0===a&&(a=null),void 0===c&&(c=null),void 0===h&&(h=!1),void 0===u&&(u=0),void 0===d&&(d=0),void 0===f&&(f=null);var _=this._gl,m=f||new e.InternalTexture(this,e.InternalTexture.DATASOURCE_CUBE);m.isCube=!0,m.url=t,m.generateMipMaps=!o,m._lodGenerationScale=u,m._lodGenerationOffset=d,this._doNotHandleContextLost||(m._extension=c,m._files=n);for(var g=t.lastIndexOf("."),v=c||(g>-1?t.substring(g).toLowerCase():""),y=null,b=0,x=i._TextureLoaders;b>v,b=0;b<6;b++){var x=g[v][b];m&&(x=f._convertRGBtoRGBATextureData(x,y,y,o)),p.texImage2D(b,v,u,y,y,0,h,s,x)}f._bindTextureDirectly(p.TEXTURE_CUBE_MAP,null)}else f.updateRawCubeTexture(_,r,n,o,d);_.isReady=!0,t._removePendingData(_),c&&c()}};return this._loadFile(e,(function(e){g(e)}),void 0,t.database,!0,m),_},i.prototype.updateRawTexture3D=function(e,t,r,n,o,s){void 0===o&&(o=null),void 0===s&&(s=i.TEXTURETYPE_UNSIGNED_INT);var a=this._getWebGLTextureType(s),l=this._getInternalFormat(r),c=this._getRGBABufferInternalSizedFormat(s,r);this._bindTextureDirectly(this._gl.TEXTURE_3D,e,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(e._bufferView=t,e.format=r,e.invertY=n,e._compression=o),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),o&&t?this._gl.compressedTexImage3D(this._gl.TEXTURE_3D,0,this.getCaps().s3tc[o],e.width,e.height,e.depth,0,t):this._gl.texImage3D(this._gl.TEXTURE_3D,0,c,e.width,e.height,e.depth,0,l,a,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_3D),this._bindTextureDirectly(this._gl.TEXTURE_3D,null),e.isReady=!0},i.prototype.createRawTexture3D=function(t,r,n,o,s,a,l,c,h,u){void 0===h&&(h=null),void 0===u&&(u=i.TEXTURETYPE_UNSIGNED_INT);var d=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RAW3D);d.baseWidth=r,d.baseHeight=n,d.baseDepth=o,d.width=r,d.height=n,d.depth=o,d.format=s,d.type=u,d.generateMipMaps=a,d.samplingMode=c,d.is3D=!0,this._doNotHandleContextLost||(d._bufferView=t),this.updateRawTexture3D(d,t,s,l,h,u),this._bindTextureDirectly(this._gl.TEXTURE_3D,d,!0);var f=this._getSamplingParameters(c,a);return this._gl.texParameteri(this._gl.TEXTURE_3D,this._gl.TEXTURE_MAG_FILTER,f.mag),this._gl.texParameteri(this._gl.TEXTURE_3D,this._gl.TEXTURE_MIN_FILTER,f.min),a&&this._gl.generateMipmap(this._gl.TEXTURE_3D),this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._internalTexturesCache.push(d),d},i.prototype._prepareWebGLTextureContinuation=function(e,t,i,r,n){var o=this._gl;if(o){var s=this._getSamplingParameters(n,!i);o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,s.mag),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,s.min),i||r||o.generateMipmap(o.TEXTURE_2D),this._bindTextureDirectly(o.TEXTURE_2D,null),t&&t._removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}},i.prototype._prepareWebGLTexture=function(t,r,n,o,s,a,l,c,h){var u=this;void 0===h&&(h=i.TEXTURE_TRILINEAR_SAMPLINGMODE);var d=this.getCaps().maxTextureSize,f=Math.min(d,this.needPOTTextures?e.Tools.GetExponentOfTwo(n,d):n),p=Math.min(d,this.needPOTTextures?e.Tools.GetExponentOfTwo(o,d):o),_=this._gl;if(_){if(!t._webGLTexture)return void(r&&r._removePendingData(t));this._bindTextureDirectly(_.TEXTURE_2D,t,!0),this._unpackFlipY(void 0===s||!!s),t.baseWidth=n,t.baseHeight=o,t.width=f,t.height=p,t.isReady=!0,c(f,p,(function(){u._prepareWebGLTextureContinuation(t,r,a,l,h)}))||this._prepareWebGLTextureContinuation(t,r,a,l,h)}},i.prototype._convertRGBtoRGBATextureData=function(e,t,r,n){var o;o=n===i.TEXTURETYPE_FLOAT?new Float32Array(t*r*4):new Uint32Array(t*r*4);for(var s=0;s-1?t._designatedSlot:this._nextFreeTextureSlots.length?this._nextFreeTextureSlots[0]:(this._textureCollisions.addCount(1,!1),this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next));return e},i.prototype._linkTrackers=function(e,t){e.next=t,t.previous=e},i.prototype._removeDesignatedSlot=function(e){var t=e._designatedSlot;return-1===t?-1:(e._designatedSlot=-1,this.disableTextureBindingOptimization?-1:(this._linkTrackers(e.previous,e.next),this._boundTexturesCache[t]=null,this._nextFreeTextureSlots.push(t),t))},i.prototype._activateCurrentTexture=function(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)},i.prototype._bindTextureDirectly=function(e,t,i,r){void 0===i&&(i=!1),void 0===r&&(r=!1);var n=!1;i&&t&&t._designatedSlot>-1&&(this._activeChannel=t._designatedSlot);var o=this._boundTexturesCache[this._activeChannel],s=t&&t._initialSlot>-1;if(o!==t||r){if(o&&this._removeDesignatedSlot(o),this._activateCurrentTexture(),this._gl.bindTexture(e,t?t._webGLTexture:null),this._boundTexturesCache[this._activeChannel]=t,t){if(!this.disableTextureBindingOptimization){var a=this._nextFreeTextureSlots.indexOf(this._activeChannel);a>-1&&this._nextFreeTextureSlots.splice(a,1),this._linkTrackers(this._lastBoundInternalTextureTracker.previous,t),this._linkTrackers(t,this._lastBoundInternalTextureTracker)}t._designatedSlot=this._activeChannel}}else i&&(n=!0,this._activateCurrentTexture());return s&&!i&&this._bindSamplerUniformToChannel(t._initialSlot,this._activeChannel),n},i.prototype._bindTexture=function(e,t){e<0||(t&&(e=this._getCorrectTextureChannel(e,t)),this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,t))},i.prototype.setTextureFromPostProcess=function(e,t){this._bindTexture(e,t?t._textures.data[t._currentRenderTextureInd]:null)},i.prototype.setTextureFromPostProcessOutput=function(e,t){this._bindTexture(e,t?t._outputTexture:null)},i.prototype.unbindAllTextures=function(){for(var e=0;e1&&this._bindTextureDirectly(this._gl.TEXTURE_3D,null)},i.prototype.setTexture=function(e,t,i){e<0||(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))},i.prototype.setDepthStencilTexture=function(e,t,i){e<0||(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0):this._setTexture(e,null))},i.prototype._bindSamplerUniformToChannel=function(e,t){var i=this._boundUniforms[e];i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)},i.prototype._getTextureWrapMode=function(e){switch(e){case i.TEXTURE_WRAP_ADDRESSMODE:return this._gl.REPEAT;case i.TEXTURE_CLAMP_ADDRESSMODE:return this._gl.CLAMP_TO_EDGE;case i.TEXTURE_MIRROR_ADDRESSMODE:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT},i.prototype._setTexture=function(e,t,r,n){if(void 0===r&&(r=!1),void 0===n&&(n=!1),!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&this._bindTextureDirectly(this._gl.TEXTURE_3D,null)),!1;if(t.video)this._activeChannel=e,t.update();else if(t.delayLoadState===i.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;var o;o=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:this.emptyTexture,r||(e=this._getCorrectTextureChannel(e,o));var s=!0;if(this._boundTexturesCache[e]===o&&(this._moveBoundTextureOnTop(o),r||this._bindSamplerUniformToChannel(o._initialSlot,e),s=!1),this._activeChannel=e,o&&o.is3D)s&&this._bindTextureDirectly(this._gl.TEXTURE_3D,o,r),o&&o._cachedWrapU!==t.wrapU&&(o._cachedWrapU=t.wrapU,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),o)),o&&o._cachedWrapV!==t.wrapV&&(o._cachedWrapV=t.wrapV,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),o)),o&&o._cachedWrapR!==t.wrapR&&(o._cachedWrapR=t.wrapR,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),o)),this._setAnisotropicLevel(this._gl.TEXTURE_3D,t);else if(o&&o.isCube){if(s&&this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,o,r),o._cachedCoordinatesMode!==t.coordinatesMode){o._cachedCoordinatesMode=t.coordinatesMode;var a=t.coordinatesMode!==i.TEXTURE_CUBIC_MODE&&t.coordinatesMode!==i.TEXTURE_SKYBOX_MODE?this._gl.REPEAT:this._gl.CLAMP_TO_EDGE;this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_S,a,o),this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_T,a)}this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP,t)}else s&&this._bindTextureDirectly(this._gl.TEXTURE_2D,o,r),o&&o._cachedWrapU!==t.wrapU&&(o._cachedWrapU=t.wrapU,this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),o)),o&&o._cachedWrapV!==t.wrapV&&(o._cachedWrapV=t.wrapV,this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),o)),this._setAnisotropicLevel(this._gl.TEXTURE_2D,t);return!0},i.prototype.setTextureArray=function(e,t,i){if(!(e<0)&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(var r=0;r=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||(this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1)},i.prototype.releaseEffects=function(){for(var e in this._compiledEffects)this._deleteProgram(this._compiledEffects[e]._program);this._compiledEffects={}},i.prototype.dispose=function(){for(this.hideLoadingUI(),this.stopRenderLoop();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();i.audioEngine&&i.audioEngine.dispose(),this.releaseEffects(),this.unbindAllAttributes(),this._boundUniforms=[],this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.disableVR(),e.Tools.IsWindowObjectExist()&&(window.removeEventListener("blur",this._onBlur),window.removeEventListener("focus",this._onFocus),window.removeEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted),window.removeEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange),this._onVrDisplayConnect&&(window.removeEventListener("vrdisplayconnect",this._onVrDisplayConnect),this._onVrDisplayDisconnect&&window.removeEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),this._onVrDisplayPresentChange&&window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),this._onVrDisplayConnect=null,this._onVrDisplayDisconnect=null));var t=i.Instances.indexOf(this);t>=0&&i.Instances.splice(t,1),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers=[],this._renderingCanvas=null,this._currentProgram=null,this._bindedRenderFunction=null,this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear(),e.Effect.ResetCache();for(var r=0,n=this._activeRequests;r-1?o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_CUBE_MAP_POSITIVE_X+r,e._webGLTexture,n):o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,e._webGLTexture,n);var a,l=void 0!==e.type?this._getWebGLTextureType(e.type):o.UNSIGNED_BYTE;switch(l){case o.UNSIGNED_BYTE:a=new Uint8Array(4*t*i),l=o.UNSIGNED_BYTE;break;default:a=new Float32Array(4*t*i),l=o.FLOAT}return o.readPixels(0,0,t,i,o.RGBA,l,a),o.bindFramebuffer(o.FRAMEBUFFER,this._currentFramebuffer),a},i.prototype._canRenderToFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(i.TEXTURETYPE_FLOAT)},i.prototype._canRenderToHalfFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(i.TEXTURETYPE_HALF_FLOAT)},i.prototype._canRenderToFramebuffer=function(e){for(var t=this._gl;t.getError()!==t.NO_ERROR;);var i=!0,r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);var n=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&o===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);var s=t.RGBA,a=t.UNSIGNED_BYTE,l=new Uint8Array(4);t.readPixels(0,0,1,1,s,a,l),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(n),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i},i.prototype._getWebGLTextureType=function(e){return e===i.TEXTURETYPE_FLOAT?this._gl.FLOAT:e===i.TEXTURETYPE_HALF_FLOAT?this._gl.HALF_FLOAT_OES:this._gl.UNSIGNED_BYTE},i.prototype._getInternalFormat=function(e){var t=this._gl.RGBA;switch(e){case i.TEXTUREFORMAT_ALPHA:t=this._gl.ALPHA;break;case i.TEXTUREFORMAT_LUMINANCE:t=this._gl.LUMINANCE;break;case i.TEXTUREFORMAT_LUMINANCE_ALPHA:t=this._gl.LUMINANCE_ALPHA;break;case i.TEXTUREFORMAT_RGB:t=this._gl.RGB;break;case i.TEXTUREFORMAT_RGBA:t=this._gl.RGBA;break;case i.TEXTUREFORMAT_R:t=this._gl.RED;break;case i.TEXTUREFORMAT_RG:t=this._gl.RG}return t},i.prototype._getRGBABufferInternalSizedFormat=function(e,t){if(1===this._webGLVersion){if(void 0!==t)switch(t){case i.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case i.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA}return this._gl.RGBA}if(e===i.TEXTURETYPE_FLOAT){if(void 0!==t)switch(t){case i.TEXTUREFORMAT_R:return this._gl.R32F;case i.TEXTUREFORMAT_RG:return this._gl.RG32F;case i.TEXTUREFORMAT_RGB:return this._gl.RGB32F}return this._gl.RGBA32F}if(e===i.TEXTURETYPE_HALF_FLOAT){if(t)switch(t){case i.TEXTUREFORMAT_R:return this._gl.R16F;case i.TEXTUREFORMAT_RG:return this._gl.RG16F;case i.TEXTUREFORMAT_RGB:return this._gl.RGB16F}return this._gl.RGBA16F}if(void 0!==t)switch(t){case i.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case i.TEXTUREFORMAT_RGB:return this._gl.RGB;case i.TEXTUREFORMAT_R:return this._gl.R8;case i.TEXTUREFORMAT_RG:return this._gl.RG8;case i.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA}return this._gl.RGBA},i.prototype._getRGBAMultiSampleBufferFormat=function(e){return e===i.TEXTURETYPE_FLOAT?this._gl.RGBA32F:e===i.TEXTURETYPE_HALF_FLOAT?this._gl.RGBA16F:this._gl.RGBA8},i.prototype._loadFile=function(t,i,r,n,o,s){var a=this,l=e.Tools.LoadFile(t,i,r,n,o,s);return this._activeRequests.push(l),l.onCompleteObservable.add((function(e){a._activeRequests.splice(a._activeRequests.indexOf(e),1)})),l},i.prototype._loadFileAsync=function(e,t,i){var r=this;return new Promise(function(n,o){r._loadFile(e,(function(e){n(e)}),void 0,t,i,(function(e,t){o(t)}))})},i.prototype._partialLoadFile=function(e,t,i,r,n,o){void 0===o&&(o=null);var s=function(e){i[t]=e,6===++i._internalCount&&n(i)},a=function(e,t){o&&e&&o(e.status+" "+e.statusText,t)};this._loadFile(e,s,void 0,void 0,!0,a)},i.prototype._cascadeLoadFiles=function(e,t,i,r){void 0===r&&(r=null);var n=[];n._internalCount=0;for(var o=0;o<6;o++)this._partialLoadFile(i[o],o,n,e,t,r)},i.isSupported=function(){try{var e=document.createElement("canvas");return null!=(e.getContext("webgl")||e.getContext("experimental-webgl"))&&!!window.WebGLRenderingContext}catch(e){return!1}},i.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Macintosh",capture:null,captureConstraint:null,targets:["textureBindingOptimization"]},{key:"iPhone",capture:null,captureConstraint:null,targets:["textureBindingOptimization"]},{key:"iPad",capture:null,captureConstraint:null,targets:["textureBindingOptimization"]}],i.Instances=new Array,i._TextureLoaders=[],i.ALPHA_DISABLE=0,i.ALPHA_ADD=1,i.ALPHA_COMBINE=2,i.ALPHA_SUBTRACT=3,i.ALPHA_MULTIPLY=4,i.ALPHA_MAXIMIZED=5,i.ALPHA_ONEONE=6,i.ALPHA_PREMULTIPLIED=7,i.ALPHA_PREMULTIPLIED_PORTERDUFF=8,i.ALPHA_INTERPOLATE=9,i.ALPHA_SCREENMODE=10,i.DELAYLOADSTATE_NONE=0,i.DELAYLOADSTATE_LOADED=1,i.DELAYLOADSTATE_LOADING=2,i.DELAYLOADSTATE_NOTLOADED=4,i.NEVER=512,i.ALWAYS=519,i.LESS=513,i.EQUAL=514,i.LEQUAL=515,i.GREATER=516,i.GEQUAL=518,i.NOTEQUAL=517,i.KEEP=7680,i.REPLACE=7681,i.INCR=7682,i.DECR=7683,i.INVERT=5386,i.INCR_WRAP=34055,i.DECR_WRAP=34056,i.TEXTURE_CLAMP_ADDRESSMODE=0,i.TEXTURE_WRAP_ADDRESSMODE=1,i.TEXTURE_MIRROR_ADDRESSMODE=2,i.TEXTUREFORMAT_ALPHA=0,i.TEXTUREFORMAT_LUMINANCE=1,i.TEXTUREFORMAT_LUMINANCE_ALPHA=2,i.TEXTUREFORMAT_RGB=4,i.TEXTUREFORMAT_RGBA=5,i.TEXTUREFORMAT_R=6,i.TEXTUREFORMAT_RG=7,i.TEXTURETYPE_UNSIGNED_INT=0,i.TEXTURETYPE_FLOAT=1,i.TEXTURETYPE_HALF_FLOAT=2,i.TEXTURE_NEAREST_SAMPLINGMODE=1,i.TEXTURE_BILINEAR_SAMPLINGMODE=2,i.TEXTURE_TRILINEAR_SAMPLINGMODE=3,i.TEXTURE_NEAREST_NEAREST_MIPLINEAR=1,i.TEXTURE_LINEAR_LINEAR_MIPNEAREST=2,i.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,i.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,i.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,i.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,i.TEXTURE_NEAREST_LINEAR=7,i.TEXTURE_NEAREST_NEAREST=8,i.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,i.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,i.TEXTURE_LINEAR_LINEAR=11,i.TEXTURE_LINEAR_NEAREST=12,i.TEXTURE_EXPLICIT_MODE=0,i.TEXTURE_SPHERICAL_MODE=1,i.TEXTURE_PLANAR_MODE=2,i.TEXTURE_CUBIC_MODE=3,i.TEXTURE_PROJECTION_MODE=4,i.TEXTURE_SKYBOX_MODE=5,i.TEXTURE_INVCUBIC_MODE=6,i.TEXTURE_EQUIRECTANGULAR_MODE=7,i.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,i.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,i.SCALEMODE_FLOOR=1,i.SCALEMODE_NEAREST=2,i.SCALEMODE_CEILING=3,i.CollisionsEpsilon=.001,i.CodeRepository="src/",i.ShadersRepository="src/Shaders/",i})();e.Engine=a})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i){void 0===i&&(i=null),this.state="",this.metadata=null,this.doNotSerialize=!1,this._isDisposed=!1,this.animations=new Array,this._ranges={},this._isEnabled=!0,this._isReady=!0,this._currentRenderId=-1,this._parentRenderId=-1,this._childRenderId=-1,this._animationPropertiesOverride=null,this.onDisposeObservable=new e.Observable,this._behaviors=new Array,this.name=t,this.id=t,this._scene=i||e.Engine.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}return t.AddNodeConstructor=function(e,t){this._NodeConstructors[e]=t},t.Construct=function(e,t,i,r){var n=this._NodeConstructors[e];return n?n(t,i,r):null},t.prototype.isDisposed=function(){return this._isDisposed},Object.defineProperty(t.prototype,"parent",{get:function(){return this._parentNode},set:function(e){if(this._parentNode!==e){if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){var t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1)}this._parentNode=e,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this))}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"Node"},Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEngine=function(){return this._scene.getEngine()},t.prototype.addBehavior=function(e){var t=this;return-1!==this._behaviors.indexOf(e)?this:(e.init(),this._scene.isLoading?this._scene.onDataLoadedObservable.addOnce((function(){e.attach(t)})):e.attach(this),this._behaviors.push(e),this)},t.prototype.removeBehavior=function(e){var t=this._behaviors.indexOf(e);return-1===t?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)},Object.defineProperty(t.prototype,"behaviors",{get:function(){return this._behaviors},enumerable:!0,configurable:!0}),t.prototype.getBehaviorByName=function(e){for(var t=0,i=this._behaviors;tthis.maximumWorld.x&&(this.maximumWorld.x=r.x),r.y>this.maximumWorld.y&&(this.maximumWorld.y=r.y),r.z>this.maximumWorld.z&&(this.maximumWorld.z=r.z)}this.maximumWorld.subtractToRef(this.minimumWorld,this.extendSizeWorld),this.extendSizeWorld.scaleInPlace(.5),this.maximumWorld.addToRef(this.minimumWorld,this.centerWorld),this.centerWorld.scaleInPlace(.5),e.Vector3.FromFloatArrayToRef(t.m,0,this.directions[0]),e.Vector3.FromFloatArrayToRef(t.m,4,this.directions[1]),e.Vector3.FromFloatArrayToRef(t.m,8,this.directions[2]),this._worldMatrix=t},t.prototype.isInFrustum=function(e){return t.IsInFrustum(this.vectorsWorld,e)},t.prototype.isCompletelyInFrustum=function(e){return t.IsCompletelyInFrustum(this.vectorsWorld,e)},t.prototype.intersectsPoint=function(t){var i=-e.Epsilon;return!(this.maximumWorld.x-t.xt.x-this.minimumWorld.x)&&(!(this.maximumWorld.y-t.yt.y-this.minimumWorld.y)&&!(this.maximumWorld.z-t.zt.z-this.minimumWorld.z))},t.prototype.intersectsSphere=function(e){ +return t.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)},t.prototype.intersectsMinMax=function(e,t){return!(this.maximumWorld.xt.x)&&(!(this.maximumWorld.yt.y)&&!(this.maximumWorld.zt.z))},t.Intersects=function(e,t){return!(e.maximumWorld.xt.maximumWorld.x)&&(!(e.maximumWorld.yt.maximumWorld.y)&&!(e.maximumWorld.zt.maximumWorld.z))},t.IntersectsSphere=function(t,i,r,n){var o=e.Vector3.Clamp(r,t,i);return e.Vector3.DistanceSquared(r,o)<=n*n},t.IsCompletelyInFrustum=function(e,t){for(var i=0;i<6;i++)for(var r=0;r<8;r++)if(t[i].dotCoordinate(e[r])<0)return!1;return!0},t.IsInFrustum=function(e,t){for(var i=0;i<6;i++){for(var r=8,n=0;n<8&&t[i].dotCoordinate(e[n])<0;n++)--r;if(0===r)return!1}return!0},t})();e.BoundingBox=t})(r||(r={}));var r;!(function(e){var t=function(t,i){var r=e.Vector3.Dot(i.centerWorld,t),n=Math.abs(e.Vector3.Dot(i.directions[0],t))*i.extendSize.x,o=Math.abs(e.Vector3.Dot(i.directions[1],t))*i.extendSize.y,s=Math.abs(e.Vector3.Dot(i.directions[2],t))*i.extendSize.z,a=n+o+s;return{min:r-a,max:r+a}},i=function(e,t,i,r){return!(e>r||i>t)},r=function(e,r,n){var o=t(e,r),s=t(e,n);return i(o.min,o.max,s.min,s.max)},n=(function(){function t(t,i){this.minimum=t,this.maximum=i,this._isLocked=!1,this.boundingBox=new e.BoundingBox(t,i),this.boundingSphere=new e.BoundingSphere(t,i)}return Object.defineProperty(t.prototype,"isLocked",{get:function(){return this._isLocked},set:function(e){this._isLocked=e},enumerable:!0,configurable:!0}),t.prototype.update=function(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))},t.prototype.centerOn=function(t,i){return this.minimum=t.subtract(i),this.maximum=t.add(i),this.boundingBox=new e.BoundingBox(this.minimum,this.maximum),this.boundingSphere=new e.BoundingSphere(this.minimum,this.maximum),this},t.prototype.scale=function(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this},t.prototype.isInFrustum=function(e){return!!this.boundingSphere.isInFrustum(e)&&this.boundingBox.isInFrustum(e)},Object.defineProperty(t.prototype,"diagonalLength",{get:function(){var e=this.boundingBox;return e.maximumWorld.subtract(e.minimumWorld).length()},enumerable:!0,configurable:!0}),t.prototype.isCompletelyInFrustum=function(e){return this.boundingBox.isCompletelyInFrustum(e)},t.prototype._checkCollision=function(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)},t.prototype.intersectsPoint=function(e){return!!this.boundingSphere.centerWorld&&(!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e))},t.prototype.intersects=function(t,i){if(!this.boundingSphere.centerWorld||!t.boundingSphere.centerWorld)return!1;if(!e.BoundingSphere.Intersects(this.boundingSphere,t.boundingSphere))return!1;if(!e.BoundingBox.Intersects(this.boundingBox,t.boundingBox))return!1;if(!i)return!0;var n=this.boundingBox,o=t.boundingBox;return!!r(n.directions[0],n,o)&&(!!r(n.directions[1],n,o)&&(!!r(n.directions[2],n,o)&&(!!r(o.directions[0],n,o)&&(!!r(o.directions[1],n,o)&&(!!r(o.directions[2],n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[1]),n,o)&&!!r(e.Vector3.Cross(n.directions[2],o.directions[2]),n,o))))))))))))))},t})();e.BoundingInfo=n})(r||(r={}));var r;!(function(e){var t=(function(t){function i(r,n,o){void 0===n&&(n=null),void 0===o&&(o=!0);var s=t.call(this,r,n)||this;return s._forward=new e.Vector3(0,0,1),s._forwardInverted=new e.Vector3(0,0,-1),s._up=new e.Vector3(0,1,0),s._right=new e.Vector3(1,0,0),s._rightInverted=new e.Vector3(-1,0,0),s._rotation=e.Vector3.Zero(),s._scaling=e.Vector3.One(),s._isDirty=!1,s.billboardMode=i.BILLBOARDMODE_NONE,s.scalingDeterminant=1,s.infiniteDistance=!1,s.ignoreNonUniformScaling=!1,s.position=e.Vector3.Zero(),s._localWorld=e.Matrix.Zero(),s._worldMatrix=e.Matrix.Zero(),s._worldMatrixDeterminant=0,s._absolutePosition=e.Vector3.Zero(),s._pivotMatrix=e.Matrix.Identity(),s._postMultiplyPivotMatrix=!1,s._isWorldMatrixFrozen=!1,s.onAfterWorldMatrixUpdateObservable=new e.Observable,s._nonUniformScaling=!1,o&&s.getScene().addTransformNode(s),s}return o(i,t),i.prototype.getClassName=function(){return"TransformNode"},Object.defineProperty(i.prototype,"rotation",{get:function(){return this._rotation},set:function(e){this._rotation=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"scaling",{get:function(){return this._scaling},set:function(e){this._scaling=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"rotationQuaternion",{get:function(){return this._rotationQuaternion},set:function(e){this._rotationQuaternion=e,e&&this.rotation.length()&&this.rotation.copyFromFloats(0,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"forward",{get:function(){return e.Vector3.Normalize(e.Vector3.TransformNormal(this.getScene().useRightHandedSystem?this._forwardInverted:this._forward,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"up",{get:function(){return e.Vector3.Normalize(e.Vector3.TransformNormal(this._up,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return e.Vector3.Normalize(e.Vector3.TransformNormal(this.getScene().useRightHandedSystem?this._rightInverted:this._right,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),i.prototype.getWorldMatrix=function(){return this._currentRenderId!==this.getScene().getRenderId()&&this.computeWorldMatrix(),this._worldMatrix},i.prototype._getWorldMatrixDeterminant=function(){return this._worldMatrixDeterminant},Object.defineProperty(i.prototype,"worldMatrixFromCache",{get:function(){return this._worldMatrix},enumerable:!0,configurable:!0}),i.prototype.updatePoseMatrix=function(e){return this._poseMatrix.copyFrom(e),this},i.prototype.getPoseMatrix=function(){return this._poseMatrix},i.prototype._isSynchronized=function(){return!this._isDirty&&(this.billboardMode===this._cache.billboardMode&&this.billboardMode===i.BILLBOARDMODE_NONE&&(!this._cache.pivotMatrixUpdated&&(!this.infiniteDistance&&(!!this._cache.position.equals(this.position)&&(!(this.rotationQuaternion&&!this._cache.rotationQuaternion.equals(this.rotationQuaternion))&&(!!this._cache.rotation.equals(this.rotation)&&!!this._cache.scaling.equals(this.scaling)))))))},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.localMatrixUpdated=!1,this._cache.position=e.Vector3.Zero(),this._cache.scaling=e.Vector3.Zero(),this._cache.rotation=e.Vector3.Zero(),this._cache.rotationQuaternion=new e.Quaternion(0,0,0,0),this._cache.billboardMode=-1},i.prototype.markAsDirty=function(e){return"rotation"===e&&(this.rotationQuaternion=null),this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this},Object.defineProperty(i.prototype,"absolutePosition",{get:function(){return this._absolutePosition},enumerable:!0,configurable:!0}),i.prototype.setPreTransformMatrix=function(e){return this.setPivotMatrix(e,!1)},i.prototype.setPivotMatrix=function(t,i){return void 0===i&&(i=!0),this._pivotMatrix=t.clone(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=i,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=e.Matrix.Invert(this._pivotMatrix)),this},i.prototype.getPivotMatrix=function(){return this._pivotMatrix},i.prototype.freezeWorldMatrix=function(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this._isWorldMatrixFrozen=!0,this},i.prototype.unfreezeWorldMatrix=function(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this},Object.defineProperty(i.prototype,"isWorldMatrixFrozen",{get:function(){return this._isWorldMatrixFrozen},enumerable:!0,configurable:!0}),i.prototype.getAbsolutePosition=function(){return this.computeWorldMatrix(),this._absolutePosition},i.prototype.setAbsolutePosition=function(t){if(!t)return this;var i,r,n;if(void 0===t.x){if(arguments.length<3)return this;i=arguments[0],r=arguments[1],n=arguments[2]}else i=t.x,r=t.y,n=t.z;if(this.parent){var o=this.parent.getWorldMatrix().clone();o.invert();var s=new e.Vector3(i,r,n);this.position=e.Vector3.TransformCoordinates(s,o)}else this.position.x=i,this.position.y=r,this.position.z=n;return this},i.prototype.setPositionWithLocalVector=function(t){return this.computeWorldMatrix(),this.position=e.Vector3.TransformNormal(t,this._localWorld),this},i.prototype.getPositionExpressedInLocalSpace=function(){this.computeWorldMatrix();var t=this._localWorld.clone();return t.invert(),e.Vector3.TransformNormal(this.position,t)},i.prototype.locallyTranslate=function(t){return this.computeWorldMatrix(!0),this.position=e.Vector3.TransformCoordinates(t,this._localWorld),this},i.prototype.lookAt=function(t,r,n,o,s){void 0===r&&(r=0),void 0===n&&(n=0),void 0===o&&(o=0),void 0===s&&(s=e.Space.LOCAL);var a=i._lookAtVectorCache,l=s===e.Space.LOCAL?this.position:this.getAbsolutePosition();t.subtractToRef(l,a);var c=-Math.atan2(a.z,a.x)-Math.PI/2,h=Math.sqrt(a.x*a.x+a.z*a.z),u=Math.atan2(a.y,h);return this.rotationQuaternion?e.Quaternion.RotationYawPitchRollToRef(c+r,u+n,o,this.rotationQuaternion):(this.rotation.x=u+n,this.rotation.y=c+r,this.rotation.z=o),this},i.prototype.getDirection=function(t){var i=e.Vector3.Zero();return this.getDirectionToRef(t,i),i},i.prototype.getDirectionToRef=function(t,i){return e.Vector3.TransformNormalToRef(t,this.getWorldMatrix(),i),this},i.prototype.setPivotPoint=function(t,i){void 0===i&&(i=e.Space.LOCAL),0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);var r=this.getWorldMatrix();if(i==e.Space.WORLD){var n=e.Tmp.Matrix[0];r.invertToRef(n),t=e.Vector3.TransformCoordinates(t,n)}return this.setPivotMatrix(e.Matrix.Translation(-t.x,-t.y,-t.z),!0)},i.prototype.getPivotPoint=function(){var t=e.Vector3.Zero();return this.getPivotPointToRef(t),t},i.prototype.getPivotPointToRef=function(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this},i.prototype.getAbsolutePivotPoint=function(){var t=e.Vector3.Zero();return this.getAbsolutePivotPointToRef(t),t},i.prototype.getAbsolutePivotPointToRef=function(t){return t.x=this._pivotMatrix.m[12],t.y=this._pivotMatrix.m[13],t.z=this._pivotMatrix.m[14],this.getPivotPointToRef(t),e.Vector3.TransformCoordinatesToRef(t,this.getWorldMatrix(),t),this},i.prototype.setParent=function(t){if(!t&&!this.parent)return this;if(t){var i=e.Tmp.Quaternion[0],r=e.Tmp.Vector3[0],n=e.Tmp.Vector3[1],o=e.Tmp.Matrix[0],s=e.Tmp.Matrix[1];this.computeWorldMatrix(!0),t.computeWorldMatrix(!0),t.getWorldMatrix().invertToRef(s),this.getWorldMatrix().multiplyToRef(s,o),o.decompose(n,i,r),this.rotationQuaternion?this.rotationQuaternion.copyFrom(i):i.toEulerAnglesToRef(this.rotation),this.position.x=r.x,this.position.y=r.y,this.position.z=r.z,this.scaling.x=n.x,this.scaling.y=n.y,this.scaling.z=n.z}else{var i=e.Tmp.Quaternion[0],r=e.Tmp.Vector3[0],n=e.Tmp.Vector3[1];this.parent&&this.parent.computeWorldMatrix&&this.parent.computeWorldMatrix(!0),this.computeWorldMatrix(!0),this.getWorldMatrix().decompose(n,i,r),this.rotationQuaternion?this.rotationQuaternion.copyFrom(i):i.toEulerAnglesToRef(this.rotation),this.scaling.x=n.x,this.scaling.y=n.y,this.scaling.z=n.z,this.position.x=r.x,this.position.y=r.y,this.position.z=r.z}return this.parent=t,this},Object.defineProperty(i.prototype,"nonUniformScaling",{get:function(){return this._nonUniformScaling},enumerable:!0,configurable:!0}),i.prototype._updateNonUniformScalingState=function(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)},i.prototype.attachToBone=function(e,t){return this._transformToBoneReferal=t,this.parent=e,e.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this},i.prototype.detachFromBone=function(){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=null,this):this},i.prototype.rotate=function(t,r,n){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation=e.Vector3.Zero());var o;if(n&&n!==e.Space.LOCAL){if(this.parent){var s=this.parent.getWorldMatrix().clone();s.invert(),t=e.Vector3.TransformNormal(t,s)}o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),this.rotationQuaternion.multiplyToRef(o,this.rotationQuaternion);return this},i.prototype.rotateAround=function(t,i,r){return i.normalize(),this.rotationQuaternion||(this.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.copyFromFloats(0,0,0)),t.subtractToRef(this.position,e.Tmp.Vector3[0]),e.Matrix.TranslationToRef(e.Tmp.Vector3[0].x,e.Tmp.Vector3[0].y,e.Tmp.Vector3[0].z,e.Tmp.Matrix[0]),e.Tmp.Matrix[0].invertToRef(e.Tmp.Matrix[2]),e.Matrix.RotationAxisToRef(i,r,e.Tmp.Matrix[1]),e.Tmp.Matrix[2].multiplyToRef(e.Tmp.Matrix[1],e.Tmp.Matrix[2]),e.Tmp.Matrix[2].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[2]),e.Tmp.Matrix[2].decompose(e.Tmp.Vector3[0],e.Tmp.Quaternion[0],e.Tmp.Vector3[1]),this.position.addInPlace(e.Tmp.Vector3[1]),e.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this},i.prototype.translate=function(t,i,r){var n=t.scale(i);if(r&&r!==e.Space.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(n));else{var o=this.getPositionExpressedInLocalSpace().add(n);this.setPositionWithLocalVector(o)}return this},i.prototype.addRotation=function(t,i,r){var n;this.rotationQuaternion?n=this.rotationQuaternion:(n=e.Tmp.Quaternion[1],e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,n));var o=e.Tmp.Quaternion[0];return e.Quaternion.RotationYawPitchRollToRef(i,t,r,o),n.multiplyInPlace(o),this.rotationQuaternion||n.toEulerAnglesToRef(this.rotation),this},i.prototype.computeWorldMatrix=function(t){if(this._isWorldMatrixFrozen)return this._worldMatrix;if(!t&&this.isSynchronized(!0))return this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix;if(this._cache.position.copyFrom(this.position),this._cache.scaling.copyFrom(this.scaling),this._cache.pivotMatrixUpdated=!1,this._cache.billboardMode=this.billboardMode,this._currentRenderId=this.getScene().getRenderId(),this._childRenderId=this.getScene().getRenderId(),this._isDirty=!1,e.Matrix.ScalingToRef(this.scaling.x*this.scalingDeterminant,this.scaling.y*this.scalingDeterminant,this.scaling.z*this.scalingDeterminant,e.Tmp.Matrix[1]),this.rotationQuaternion){this.rotation.length()&&(this.rotationQuaternion.multiplyInPlace(e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)),this.rotation.copyFromFloats(0,0,0))}this.rotationQuaternion?(this.rotationQuaternion.toRotationMatrix(e.Tmp.Matrix[0]),this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,e.Tmp.Matrix[0]),this._cache.rotation.copyFrom(this.rotation));var r=this.getScene().activeCamera;if(this.infiniteDistance&&!this.parent&&r){var n=r.getWorldMatrix(),o=new e.Vector3(n.m[12],n.m[13],n.m[14]);e.Matrix.TranslationToRef(this.position.x+o.x,this.position.y+o.y,this.position.z+o.z,e.Tmp.Matrix[2])}else e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,e.Tmp.Matrix[2]);if(this._pivotMatrix.multiplyToRef(e.Tmp.Matrix[1],e.Tmp.Matrix[4]),e.Tmp.Matrix[4].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[5]),this.billboardMode!==i.BILLBOARDMODE_NONE&&r){if((this.billboardMode&i.BILLBOARDMODE_ALL)!==i.BILLBOARDMODE_ALL){var s=e.Tmp.Vector3[3];this.parent&&this.parent.getWorldMatrix?this._transformToBoneReferal?(this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),e.Tmp.Matrix[6]),e.Vector3.TransformCoordinatesToRef(this.position,e.Tmp.Matrix[6],s)):e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),s):s.copyFrom(this.position),s.subtractInPlace(r.globalPosition);var a=e.Tmp.Vector3[4].copyFromFloats(0,0,0);(this.billboardMode&i.BILLBOARDMODE_X)===i.BILLBOARDMODE_X&&(a.x=Math.atan2(-s.y,s.z)),(this.billboardMode&i.BILLBOARDMODE_Y)===i.BILLBOARDMODE_Y&&(a.y=Math.atan2(s.x,s.z)),(this.billboardMode&i.BILLBOARDMODE_Z)===i.BILLBOARDMODE_Z&&(a.z=Math.atan2(s.y,s.x)),e.Matrix.RotationYawPitchRollToRef(a.y,a.x,a.z,e.Tmp.Matrix[0])}else e.Tmp.Matrix[1].copyFrom(r.getViewMatrix()),e.Tmp.Matrix[1].setTranslationFromFloats(0,0,0),e.Tmp.Matrix[1].invertToRef(e.Tmp.Matrix[0]);e.Tmp.Matrix[1].copyFrom(e.Tmp.Matrix[5]),e.Tmp.Matrix[1].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[5])}return this._postMultiplyPivotMatrix&&e.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse,e.Tmp.Matrix[5]),e.Tmp.Matrix[5].multiplyToRef(e.Tmp.Matrix[2],this._localWorld),this.parent&&this.parent.getWorldMatrix?(this.billboardMode!==i.BILLBOARDMODE_NONE?(this._transformToBoneReferal?(this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),e.Tmp.Matrix[6]),e.Tmp.Matrix[5].copyFrom(e.Tmp.Matrix[6])):e.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix()),this._localWorld.getTranslationToRef(e.Tmp.Vector3[5]),e.Vector3.TransformCoordinatesToRef(e.Tmp.Vector3[5],e.Tmp.Matrix[5],e.Tmp.Vector3[5]),this._worldMatrix.copyFrom(this._localWorld),this._worldMatrix.setTranslation(e.Tmp.Vector3[5])):this._transformToBoneReferal?(this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),e.Tmp.Matrix[6]),e.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()):this._worldMatrix.copyFrom(this._localWorld),this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this.scaling.isNonUniform?this._updateNonUniformScalingState(!0):this.parent&&this.parent._nonUniformScaling?this._updateNonUniformScalingState(this.parent._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=e.Matrix.Invert(this._worldMatrix)),this._worldMatrixDeterminant=this._worldMatrix.determinant(),this._worldMatrix},i.prototype._afterComputeWorldMatrix=function(){},i.prototype.registerAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this},i.prototype.unregisterAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this},i.prototype.clone=function(t,r,n){var o=this,s=e.SerializationHelper.Clone((function(){return new i(t,o.getScene())}),this);if(s.name=t,s.id=t,r&&(s.parent=r),!n)for(var a=this.getDescendants(!0),l=0;le.Engine.CollisionsEpsilon&&o.position.addInPlace(o._diffPositionForCollisions),r&&o.onCollideObservable.notifyObservers(r),o.onCollisionPositionChangeObservable.notifyObservers(o.position)},o.getScene().addMesh(o),o._resyncLightSources(),o}return o(i,t),Object.defineProperty(i,"BILLBOARDMODE_NONE",{get:function(){return e.TransformNode.BILLBOARDMODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_X",{get:function(){return e.TransformNode.BILLBOARDMODE_X},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Y",{get:function(){return e.TransformNode.BILLBOARDMODE_Y},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Z",{get:function(){return e.TransformNode.BILLBOARDMODE_Z},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_ALL",{get:function(){return e.TransformNode.BILLBOARDMODE_ALL},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"facetNb",{get:function(){return this._facetNb},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"partitioningSubdivisions",{get:function(){return this._partitioningSubdivisions},set:function(e){this._partitioningSubdivisions=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"partitioningBBoxRatio",{get:function(){return this._partitioningBBoxRatio},set:function(e){this._partitioningBBoxRatio=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"mustDepthSortFacets",{get:function(){return this._facetDepthSort},set:function(e){this._facetDepthSort=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"facetDepthSortFrom",{get:function(){return this._facetDepthSortFrom},set:function(e){this._facetDepthSortFrom=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"isFacetDataEnabled",{get:function(){return this._facetDataEnabled},enumerable:!0,configurable:!0}),i.prototype._updateNonUniformScalingState=function(e){return!!t.prototype._updateNonUniformScalingState.call(this,e)&&(this._markSubMeshesAsMiscDirty(),!0)},Object.defineProperty(i.prototype,"onCollide",{set:function(e){this._onCollideObserver&&this.onCollideObservable.remove(this._onCollideObserver),this._onCollideObserver=this.onCollideObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onCollisionPositionChange",{set:function(e){this._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver),this._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"isOccluded",{get:function(){return this._isOccluded},set:function(e){this._isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"isOcclusionQueryInProgress",{get:function(){return this._isOcclusionQueryInProgress},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"visibility",{get:function(){return this._visibility},set:function(e){this._visibility!==e&&(this._visibility=e,this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"material",{get:function(){return this._material},set:function(e){this._material!==e&&(this._material=e,this.onMaterialChangedObservable.hasObservers&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&this._unBindEffect())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"receiveShadows",{get:function(){return this._receiveShadows},set:function(e){this._receiveShadows!==e&&(this._receiveShadows=e,this._markSubMeshesAsLightDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"hasVertexAlpha",{get:function(){return this._hasVertexAlpha},set:function(e){this._hasVertexAlpha!==e&&(this._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useVertexColors",{get:function(){return this._useVertexColors},set:function(e){this._useVertexColors!==e&&(this._useVertexColors=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"computeBonesUsingShaders",{get:function(){return this._computeBonesUsingShaders},set:function(e){this._computeBonesUsingShaders!==e&&(this._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"numBoneInfluencers",{get:function(){return this._numBoneInfluencers},set:function(e){this._numBoneInfluencers!==e&&(this._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"applyFog",{get:function(){return this._applyFog},set:function(e){this._applyFog!==e&&(this._applyFog=e,this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"layerMask",{get:function(){return this._layerMask},set:function(e){e!==this._layerMask&&(this._layerMask=e,this._resyncLightSources())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"collisionGroup",{get:function(){return this._collisionGroup},set:function(e){this._collisionGroup=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"_positions",{get:function(){return null},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"skeleton",{get:function(){return this._skeleton},set:function(e){this._skeleton&&this._skeleton.needInitialSkinMatrix&&this._skeleton._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._skeleton=e,this._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"AbstractMesh"},i.prototype.toString=function(t){var i="Name: "+this.name+", isInstance: "+(this instanceof e.InstancedMesh?"YES":"NO");return i+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0),this._skeleton&&(i+=", skeleton: "+this._skeleton.name),t&&(i+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],i+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingFreezeWorldMatrix?"YES":"NO")),i},i.prototype._rebuild=function(){if(this._occlusionQuery&&(this._occlusionQuery=null),this._edgesRenderer&&this._edgesRenderer._rebuild(),this.subMeshes)for(var e=0,t=this.subMeshes;e1&&!a._checkCollision(e)||this._collideForSubMesh(a,t,e)}return this},i.prototype._checkCollision=function(t){return this._boundingInfo&&this._boundingInfo._checkCollision(t)?(e.Matrix.ScalingToRef(1/t._radius.x,1/t._radius.y,1/t._radius.z,this._collisionsScalingMatrix),this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix,this._collisionsTransformMatrix),this._processCollisionsForSubMeshes(t,this._collisionsTransformMatrix),this):this},i.prototype._generatePointsArray=function(){return!1},i.prototype.intersects=function(t,i){var r=new e.PickingInfo;if(!(this.subMeshes&&this._boundingInfo&&t.intersectsSphere(this._boundingInfo.boundingSphere)&&t.intersectsBox(this._boundingInfo.boundingBox)))return r;if(!this._generatePointsArray())return r;var n,o,s=null;if(this._submeshesOctree&&this.useOctreeForPicking){var a=e.Ray.Transform(t,this.getWorldMatrix()),l=this._submeshesOctree.intersectsRay(a);o=l.length,n=l.data}else n=this.subMeshes,o=n.length;for(var c=0;c1)||h.canIntersects(t)){var u=h.intersects(t,this._positions,this.getIndices(),i);if(u&&(i||!s||u.distance65535){o=!0;break}this._depthSortedIndices=o?new Uint32Array(i):new Uint16Array(i)}if(this._facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!this._facetDepthSortFrom){var a=this.getScene().activeCamera;this._facetDepthSortFrom=a?a.position:e.Vector3.Zero()}this._depthSortedFacets=[];for(var l=0;le.Epsilon?n.maximum.x-n.minimum.x:e.Epsilon,this._bbSize.y=n.maximum.y-n.minimum.y>e.Epsilon?n.maximum.y-n.minimum.y:e.Epsilon,this._bbSize.z=n.maximum.z-n.minimum.z>e.Epsilon?n.maximum.z-n.minimum.z:e.Epsilon;var h=this._bbSize.x>this._bbSize.y?this._bbSize.x:this._bbSize.y;if(h=h>this._bbSize.z?h:this._bbSize.z,this._subDiv.max=this._partitioningSubdivisions,this._subDiv.X=Math.floor(this._subDiv.max*this._bbSize.x/h),this._subDiv.Y=Math.floor(this._subDiv.max*this._bbSize.y/h),this._subDiv.Z=Math.floor(this._subDiv.max*this._bbSize.z/h),this._subDiv.X=this._subDiv.X<1?1:this._subDiv.X,this._subDiv.Y=this._subDiv.Y<1?1:this._subDiv.Y,this._subDiv.Z=this._subDiv.Z<1?1:this._subDiv.Z,this._facetParameters.facetNormals=this.getFacetLocalNormals(),this._facetParameters.facetPositions=this.getFacetLocalPositions(),this._facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),this._facetParameters.bInfo=n,this._facetParameters.bbSize=this._bbSize,this._facetParameters.subDiv=this._subDiv,this._facetParameters.ratio=this.partitioningBBoxRatio,this._facetParameters.depthSort=this._facetDepthSort,this._facetDepthSort&&this._facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(this._invertedMatrix),e.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom,this._invertedMatrix,this._facetDepthSortOrigin),this._facetParameters.distanceTo=this._facetDepthSortOrigin),this._facetParameters.depthSortedFacets=this._depthSortedFacets,e.VertexData.ComputeNormals(t,i,r,this._facetParameters),this._facetDepthSort&&this._facetDepthSortEnabled){this._depthSortedFacets.sort(this._facetDepthSortFunction);for(var u=this._depthSortedIndices.length/3|0,l=0;lthis._subDiv.max||o<0||o>this._subDiv.max||s<0||s>this._subDiv.max?null:this._facetPartitioning[n+this._subDiv.max*o+this._subDiv.max*this._subDiv.max*s]},i.prototype.getClosestFacetAtCoordinates=function(t,i,r,n,o,s){void 0===o&&(o=!1),void 0===s&&(s=!0);var a=this.getWorldMatrix(),l=e.Tmp.Matrix[5];a.invertToRef(l);var c=e.Tmp.Vector3[8];e.Vector3.TransformCoordinatesFromFloatsToRef(t,i,r,l,c);var h=this.getClosestFacetAtLocalCoordinates(c.x,c.y,c.z,n,o,s);return n&&e.Vector3.TransformCoordinatesFromFloatsToRef(n.x,n.y,n.z,a,n),h},i.prototype.getClosestFacetAtLocalCoordinates=function(e,t,i,r,n,o){void 0===n&&(n=!1),void 0===o&&(o=!0);var s=null,a=0,l=0,c=0,h=0,u=0,d=0,f=0,p=0,_=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;for(var v,y,b,x=Number.MAX_VALUE,T=x,E=0;E=0||n&&!o&&h<=0)&&(h=y.x*b.x+y.y*b.y+y.z*b.z,u=-(y.x*e+y.y*t+y.z*i-h)/(y.x*y.x+y.y*y.y+y.z*y.z),d=e+y.x*u,f=t+y.y*u,p=i+y.z*u,a=d-e,l=f-t,c=p-i,(T=a*a+l*l+c*c)0&&-1===this.includedOnlyMeshes.indexOf(e))&&(!(this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e))&&((0===this.includeOnlyWithLayerMask||0!=(this.includeOnlyWithLayerMask&e.layerMask))&&!(0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask)))},i.prototype.getWorldMatrix=function(){this._currentRenderId=this.getScene().getRenderId(),this._childRenderId=this._currentRenderId;var t=this._getWorldMatrix();return this.parent&&this.parent.getWorldMatrix?(this._parentedWorldMatrix||(this._parentedWorldMatrix=e.Matrix.Identity()),t.multiplyToRef(this.parent.getWorldMatrix(),this._parentedWorldMatrix),this._markSyncedWithParent(),this._parentedWorldMatrix):t},i.CompareLightsPriority=function(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority},i.prototype.dispose=function(e,i){void 0===i&&(i=!1),this._shadowGenerator&&(this._shadowGenerator.dispose(),this._shadowGenerator=null),this.getScene().stopAnimation(this);for(var r=0,n=this.getScene().meshes;r0&&(t.excludedMeshesIds=[],this.excludedMeshes.forEach((function(e){t.excludedMeshesIds.push(e.id)}))),this.includedOnlyMeshes.length>0&&(t.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((function(e){t.includedOnlyMeshesIds.push(e.id)}))),e.Animation.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t},i.GetConstructorFromName=function(t,i,r){var n=e.Node.Construct("Light_Type_"+t,i,r);return n||null},i.Parse=function(t,r){var n=i.GetConstructorFromName(t.type,t.name,r);if(!n)return null;var o=e.SerializationHelper.Parse(n,t,r);if(t.excludedMeshesIds&&(o._excludedMeshesIds=t.excludedMeshesIds),t.includedOnlyMeshesIds&&(o._includedOnlyMeshesIds=t.includedOnlyMeshesIds),t.parentId&&(o._waitingParentId=t.parentId),t.animations){for(var s=0;s-1?(e.Tools.Error("You're trying to reuse a post process not defined as reusable."),0):(null==i||i<0?this._postProcesses.push(t):null===this._postProcesses[i]?this._postProcesses[i]=t:this._postProcesses.splice(i,0,t),this._cascadePostProcessesToRigCams(),this._postProcesses.indexOf(t))},i.prototype.detachPostProcess=function(e){var t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._cascadePostProcessesToRigCams()},i.prototype.getWorldMatrix=function(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)},i.prototype._getViewMatrix=function(){return e.Matrix.Identity()},i.prototype.getViewMatrix=function(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childRenderId=this._currentRenderId,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._computedViewMatrix)},i.prototype.freezeProjectionMatrix=function(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)},i.prototype.unfreezeProjectionMatrix=function(){this._doNotComputeProjectionMatrix=!1},i.prototype.getProjectionMatrix=function(t){if(this._doNotComputeProjectionMatrix||!t&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;var r=this.getEngine(),n=this.getScene();if(this.mode===i.PERSPECTIVE_CAMERA)this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=r.getAspectRatio(this),this.minZ<=0&&(this.minZ=.1),n.useRightHandedSystem?e.Matrix.PerspectiveFovRHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED):e.Matrix.PerspectiveFovLHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED);else{var o=r.getRenderWidth()/2,s=r.getRenderHeight()/2;n.useRightHandedSystem?e.Matrix.OrthoOffCenterRHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix):e.Matrix.OrthoOffCenterLHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=r.getRenderWidth(),this._cache.renderHeight=r.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix},i.prototype.getTransformationMatrix=function(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix},i.prototype.updateFrustumPlanes=function(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?e.Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=e.Frustum.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)},i.prototype.isInFrustum=function(e){return this.updateFrustumPlanes(),e.isInFrustum(this._frustumPlanes)},i.prototype.isCompletelyInFrustum=function(e){return this.updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)},i.prototype.getForwardRay=function(t,i,r){void 0===t&&(t=100),i||(i=this.getWorldMatrix()),r||(r=this.position);var n=new e.Vector3(0,0,1),o=e.Vector3.TransformNormal(n,i),s=e.Vector3.Normalize(o);return new e.Ray(r,s,t)},i.prototype.dispose=function(e,r){for(void 0===r&&(r=!1),this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){var n=this._rigCameras.pop();n&&n.dispose()}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses=[];else if(this.cameraRigMode!==i.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses=[];else for(var o=this._postProcesses.length;--o>=0;){var s=this._postProcesses[o];s&&s.dispose(this)}for(var o=this.customRenderTargets.length;--o>=0;)this.customRenderTargets[o].dispose();this.customRenderTargets=[],this._activeMeshes.dispose(),t.prototype.dispose.call(this,e,r)},Object.defineProperty(i.prototype,"leftCamera",{get:function(){return this._rigCameras.length<1?null:this._rigCameras[0]},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"rightCamera",{get:function(){return this._rigCameras.length<2?null:this._rigCameras[1]},enumerable:!0,configurable:!0}),i.prototype.getLeftTarget=function(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()},i.prototype.getRightTarget=function(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()},i.prototype.setCameraRigMode=function(t,r){if(this.cameraRigMode!==t){for(;this._rigCameras.length>0;){var n=this._rigCameras.pop();n&&n.dispose()}if(this.cameraRigMode=t,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=r.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==i.RIG_MODE_NONE){var o=this.createRigCamera(this.name+"_L",0),s=this.createRigCamera(this.name+"_R",1);o&&s&&(this._rigCameras.push(o),this._rigCameras.push(s))}switch(this.cameraRigMode){case i.RIG_MODE_STEREOSCOPIC_ANAGLYPH:this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.AnaglyphPostProcess(this.name+"_anaglyph",1,this._rigCameras);break;case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case i.RIG_MODE_STEREOSCOPIC_OVERUNDER:var a=this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.StereoscopicInterlacePostProcess(this.name+"_stereoInterlace",this._rigCameras,a);break;case i.RIG_MODE_VR:var l=r.vrCameraMetrics||e.VRCameraMetrics.GetDefault();this._rigCameras[0]._cameraRigParams.vrMetrics=l,this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0]._cameraRigParams.vrHMatrix=l.leftHMatrix,this._rigCameras[0]._cameraRigParams.vrPreViewMatrix=l.leftPreViewMatrix,this._rigCameras[0].getProjectionMatrix=this._rigCameras[0]._getVRProjectionMatrix,this._rigCameras[1]._cameraRigParams.vrMetrics=l,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1]._cameraRigParams.vrHMatrix=l.rightHMatrix,this._rigCameras[1]._cameraRigParams.vrPreViewMatrix=l.rightPreViewMatrix,this._rigCameras[1].getProjectionMatrix=this._rigCameras[1]._getVRProjectionMatrix,l.compensateDistortion&&(this._rigCameras[0]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",this._rigCameras[0],!1,l),this._rigCameras[1]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",this._rigCameras[1],!0,l));break;case i.RIG_MODE_WEBVR:if(r.vrDisplay){var c=r.vrDisplay.getEyeParameters("left"),h=r.vrDisplay.getEyeParameters("right");this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0].setCameraRigParameter("left",!0),this._rigCameras[0].setCameraRigParameter("specs",r.specs),this._rigCameras[0].setCameraRigParameter("eyeParameters",c),this._rigCameras[0].setCameraRigParameter("frameData",r.frameData),this._rigCameras[0].setCameraRigParameter("parentCamera",r.parentCamera),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0].getProjectionMatrix=this._getWebVRProjectionMatrix,this._rigCameras[0].parent=this,this._rigCameras[0]._getViewMatrix=this._getWebVRViewMatrix,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1].setCameraRigParameter("eyeParameters",h),this._rigCameras[1].setCameraRigParameter("specs",r.specs),this._rigCameras[1].setCameraRigParameter("frameData",r.frameData),this._rigCameras[1].setCameraRigParameter("parentCamera",r.parentCamera),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1].getProjectionMatrix=this._getWebVRProjectionMatrix,this._rigCameras[1].parent=this,this._rigCameras[1]._getViewMatrix=this._getWebVRViewMatrix,i.UseAlternateWebVRRendering&&(this._rigCameras[1]._skipRendering=!0,this._rigCameras[0]._alternateCamera=this._rigCameras[1])}}this._cascadePostProcessesToRigCams(),this.update()}},i.prototype._getVRProjectionMatrix=function(){return e.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix},i.prototype._updateCameraRotationMatrix=function(){},i.prototype._updateWebVRCameraRotationMatrix=function(){},i.prototype._getWebVRProjectionMatrix=function(){return e.Matrix.Identity()},i.prototype._getWebVRViewMatrix=function(){return e.Matrix.Identity()},i.prototype.setCameraRigParameter=function(t,i){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[t]=i,"interaxialDistance"===t&&(this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(i/.0637))},i.prototype.createRigCamera=function(e,t){return null},i.prototype._updateRigCameras=function(){for(var e=0;ei._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0},t.frontToBackSortCompare=function(e,t){return e._distanceToCamerat._distanceToCamera?1:0},t.prototype.prepare=function(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this._spriteManagers.reset(),this._edgesRenderers.reset()},t.prototype.dispose=function(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()},t.prototype.dispatch=function(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!==i&&void 0!==i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),null!==t._edgesRenderer&&void 0!==t._edgesRenderer&&t._edgesRenderer.isEnabled&&this._edgesRenderers.push(t._edgesRenderer))},t.prototype.dispatchSprites=function(e){this._spriteManagers.push(e)},t.prototype.dispatchParticles=function(e){this._particleSystems.push(e)},t.prototype._renderParticles=function(e){if(0!==this._particleSystems.length){var t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(var i=0;i0){for(var e=0,t=this._transientComponents;er.LongPressDelay&&Math.abs(n._startingPointerPosition.x-n._pointerX)r.DoubleClickDelay&&!s._doubleClickOccured||e!==s._previousButtonPressed)&&(s._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,i(t,s._currentPickResult))},this._initClickEvent=function(i,n,o,a){var l=new t;s._currentPickResult=null;var c=null,h=i.hasSpecificMask(e.PointerEventTypes.POINTERPICK)||n.hasSpecificMask(e.PointerEventTypes.POINTERPICK)||i.hasSpecificMask(e.PointerEventTypes.POINTERTAP)||n.hasSpecificMask(e.PointerEventTypes.POINTERTAP)||i.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)||n.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP);if(!h&&e.ActionManager&&e.ActionManager.HasPickTriggers&&(c=s._initActionManager(c,l))&&(h=c.hasPickTriggers),h){var u=o.button;if(l.hasSwiped=Math.abs(s._startingPointerPosition.x-s._pointerX)>r.DragMovementThreshold||Math.abs(s._startingPointerPosition.y-s._pointerY)>r.DragMovementThreshold,!l.hasSwiped){var d=!r.ExclusiveDoubleClickMode;d||(d=!i.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)&&!n.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP))&&!e.ActionManager.HasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)&&(c=s._initActionManager(c,l))&&(d=!c.hasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)),d?(Date.now()-s._previousStartingPointerTime>r.DoubleClickDelay||u!==s._previousButtonPressed)&&(l.singleClick=!0,a(l,s._currentPickResult)):(s._previousDelayedSimpleClickTimeout=s._delayedSimpleClickTimeout,s._delayedSimpleClickTimeout=window.setTimeout(s._delayedSimpleClick.bind(s,u,l,a),r.DoubleClickDelay));var f=i.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)||n.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP);!f&&e.ActionManager.HasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)&&(c=s._initActionManager(c,l))&&(f=c.hasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)),f&&(u===s._previousButtonPressed&&Date.now()-s._previousStartingPointerTime0&&(i=s.pickSprite(s._unTranslatedPointerX,s._unTranslatedPointerY,s._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,t.button){case 0:i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnLeftPickTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t));break;case 1:i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnCenterPickTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t));break;case 2:i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnRightPickTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickDownTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t))}}},this._onPointerUp=function(t){0!==s._totalPointersPressed&&(s._totalPointersPressed--,s._pickedUpMesh=null,s._meshPickProceed=!1,s._updatePointerPosition(t),s._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,t,(function(i,n){if(s.onPrePointerObservable.hasObservers())if(i.ignore){if(s._checkPrePointerObservable(null,t,e.PointerEventTypes.POINTERUP))return}else if(!i.hasSwiped){if(i.singleClick&&s.onPrePointerObservable.hasSpecificMask(e.PointerEventTypes.POINTERTAP)&&s._checkPrePointerObservable(null,t,e.PointerEventTypes.POINTERTAP))return;if(i.doubleClick&&s.onPrePointerObservable.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)&&s._checkPrePointerObservable(null,t,e.PointerEventTypes.POINTERDOUBLETAP))return}if(s.cameraToUseForPointers||s.activeCamera){if(s._pointerCaptures[t.pointerId]=!1,s.pointerUpPredicate||(s.pointerUpPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()}),!s._meshPickProceed&&(e.ActionManager&&e.ActionManager.HasTriggers||s.onPointerObservable.hasObservers())&&s._initActionManager(null,i),n||(n=s._currentPickResult),s._processPointerUp(n,t,i),!i.ignore&&s.spriteManagers.length>0){var o=s.pickSprite(s._unTranslatedPointerX,s._unTranslatedPointerY,s._spritePredicate,!1,s.cameraToUseForPointers||void 0);o&&(o.hit&&o.pickedSprite&&o.pickedSprite.actionManager&&(o.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickUpTrigger,e.ActionEvent.CreateNewFromSprite(o.pickedSprite,s,t)),o.pickedSprite.actionManager&&Math.abs(s._startingPointerPosition.x-s._pointerX)0)return!1;var t,i=this.getEngine();for(t=0;t0,o=0,s=this._isReadyForMeshStage;o0)for(var a=0,l=this.activeCameras;a0},enumerable:!0,configurable:!0}),r.prototype.executeWhenReady=function(e){var t=this;this.onReadyObservable.add(e),-1===this._executeWhenReadyTimeoutId&&(this._executeWhenReadyTimeoutId=setTimeout((function(){t._checkIsReady()}),150))},r.prototype.whenReadyAsync=function(){var e=this;return new Promise(function(t){e.executeWhenReady((function(){t()}))})},r.prototype._checkIsReady=function(){var e=this;if(this._registerTransientComponents(),this.isReady())return this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=-1);this._executeWhenReadyTimeoutId=setTimeout((function(){e._checkIsReady()}),150)},r.prototype.beginWeightedAnimation=function(e,t,i,r,n,o,s,a,l){void 0===r&&(r=1),void 0===o&&(o=1);var c=this.beginAnimation(e,t,i,n,o,s,a,!1,l);return c.weight=r,c},r.prototype.beginAnimation=function(t,i,r,n,o,s,a,l,c){void 0===o&&(o=1),void 0===l&&(l=!0),i>r&&o>0&&(o*=-1),l&&this.stopAnimation(t,void 0,c),a||(a=new e.Animatable(this,t,i,r,n,o,s));var h=!c||c(t);if(t.animations&&h&&a.appendAnimations(t,t.animations),t.getAnimatables)for(var u=t.getAnimatables(),d=0;d0)return;this._animationTimeLast=t}var i=this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale;this._animationTime+=i,this._animationTimeLast=t;for(var r=0;r0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t},r.prototype.removeParticleSystem=function(e){var t=this.particleSystems.indexOf(e);return-1!==t&&this.particleSystems.splice(t,1),t},r.prototype.removeAnimation=function(e){var t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t},r.prototype.removeAnimationGroup=function(e){var t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t},r.prototype.removeMultiMaterial=function(e){var t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),t},r.prototype.removeMaterial=function(e){var t=this.materials.indexOf(e);return-1!==t&&this.materials.splice(t,1),t},r.prototype.removeActionManager=function(e){var t=this.actionManagers.indexOf(e);return-1!==t&&this.actionManagers.splice(t,1),t},r.prototype.removeTexture=function(e){var t=this.textures.indexOf(e);return-1!==t&&this.textures.splice(t,1),t},r.prototype.addLight=function(e){this.lights.push(e),this.sortLightsByPriority();for(var t=0,i=this.meshes;t-1&&(this.geometries.splice(t,1),this.collisionCoordinator&&this.collisionCoordinator.onGeometryDeleted(e),this.onGeometryRemovedObservable.notifyObservers(e),!0)},r.prototype.getGeometries=function(){return this.geometries},r.prototype.getMeshByID=function(e){for(var t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null},r.prototype.getLastEntryByID=function(e){var t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null},r.prototype.getNodeByID=function(e){var t=this.getMeshByID(e);if(t)return t;var i=this.getLightByID(e);if(i)return i;var r=this.getCameraByID(e);return r||this.getBoneByID(e)},r.prototype.getNodeByName=function(e){var t=this.getMeshByName(e);if(t)return t;var i=this.getLightByName(e);if(i)return i;var r=this.getCameraByName(e);return r||this.getBoneByName(e)},r.prototype.getMeshByName=function(e){for(var t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null},r.prototype.getSkeletonById=function(e){for(var t=0;t0&&(a.alwaysSelectAsActiveMesh||0!=(a.layerMask&this.activeCamera.layerMask)&&a.isInFrustum(this._frustumPlanes))&&(this._activeMeshes.push(a),this.activeCamera._activeMeshes.push(a),a._activate(this._renderId),l!==a&&l._activate(this._renderId),this._activeMesh(a,l)))));if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(var h=0;h0){var n,o;if(t.useOctreeForRenderingSelection&&void 0!==t._submeshesOctree&&null!==t._submeshesOctree){var s=t._submeshesOctree.select(this._frustumPlanes);n=s.length,o=s.data}else o=t.subMeshes,n=o.length;for(var a,l=0;l0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),i&&i.customRenderTargets&&i.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(i.customRenderTargets),this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){e.Tools.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(var s=0;s0),this._renderId++}for(var c=0,h=this._cameraDrawRenderTargetStage;c-1&&(n.trigger===e.ActionManager.OnIntersectionExitTrigger&&n._executeCurrent(e.ActionEvent.CreateNew(i,void 0,s)),i.actionManager.hasSpecificTrigger(e.ActionManager.OnIntersectionExitTrigger,(function(t){var i=t instanceof e.AbstractMesh?t:t.mesh;return s===i}))&&n.trigger!==e.ActionManager.OnIntersectionExitTrigger||i._intersectionsInProgress.splice(l,1))}}}},r.prototype.render=function(t){if(void 0===t&&(t=!0),!this.isDisposed){if(this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(e.ActionManager.OnEveryFrameTrigger),this.simplificationQueue&&!this.simplificationQueue.running&&this.simplificationQueue.executeNext(),this._engine.isDeterministicLockStep()){var i=Math.max(r.MinDeltaTime,Math.min(this._engine.getDeltaTime(),r.MaxDeltaTime))+this._timeAccumulator,n=1e3/60;this._physicsEngine&&(n=1e3*this._physicsEngine.getTimeStep());var o=0,s=this._engine.getLockstepMaxSteps(),a=Math.floor(i/60);a=Math.min(a,s);do{this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=.06*n,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this._physicsEngine&&(this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(n/1e3),this.onAfterPhysicsObservable.notifyObservers(this)),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,o++,i-=n}while(i>0&&o0)for(var h=0;h0),this._intermediateRendering=!0;for(var _=0;_0),this._intermediateRendering=!1,this._renderId++}if(this.customRenderTargets.length>0&&f.restoreDefaultFramebuffer(),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.activeCamera=p,this.proceduralTexturesEnabled){e.Tools.StartPerformanceCounter("Procedural textures",this.proceduralTextures.length>0);for(var g=0;g0)}if((this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil),this.shadowsEnabled)for(var y=0;y0)for(var h=0;h0&&this._engine.clear(null,!1,!0,!0),this._processSubCameras(this.activeCameras[h]);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera)}this._checkIntersections(),e.AudioEngine&&this._updateAudioParameters(),this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this);for(var d=0;d0?this.activeCameras[0]:this.activeCamera)&&i.canUseWebAudio&&i.audioContext){i.audioContext.listener.setPosition(t.position.x,t.position.y,t.position.z),t.rigCameras&&t.rigCameras.length>0&&(t=t.rigCameras[0]);var r=e.Matrix.Invert(t.getViewMatrix()),n=e.Vector3.TransformNormal(new e.Vector3(0,0,-1),r);n.normalize(),isNaN(n.x)||isNaN(n.y)||isNaN(n.z)||i.audioContext.listener.setOrientation(n.x,n.y,n.z,0,1,0);var o;for(o=0;o-1&&this._engine.scenes.splice(a,1),this._engine.wipeCaches(!0),this._isDisposed=!0},Object.defineProperty(r.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!0,configurable:!0}),r.prototype.disposeSounds=function(){if(this._mainSoundTrack){this.mainSoundTrack.dispose();for(var e=0;e=n.distance))&&(n=c,r)))break}return n||new e.PickingInfo},r.prototype._internalMultiPick=function(t,i){if(!e.PickingInfo)return null;for(var r=new Array,n=0;n0)for(var s=0;s=o.distance))&&(o=l,r))break}}return o||new e.PickingInfo},r.prototype.pick=function(t,i,r,n,o){var s=this;if(!e.PickingInfo)return null;var a=this._internalPick((function(e){return s.createPickingRayToRef(t,i,e,s._tempPickingRay,o||null),s._tempPickingRay}),r,n);return a&&(a.ray=this.createPickingRay(t,i,e.Matrix.Identity(),o||null)),a},r.prototype.pickSprite=function(e,t,i,r,n){return this.createPickingRayInCameraSpaceToRef(e,t,this._tempPickingRay,n),this._internalPickSprites(this._tempPickingRay,i,r,n)},r.prototype.pickWithRay=function(t,i,r){var n=this,o=this._internalPick((function(i){return n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(n._pickWithRayInverseMatrix),n._cachedRayForTransform||(n._cachedRayForTransform=e.Ray.Zero()),e.Ray.TransformToRef(t,n._pickWithRayInverseMatrix,n._cachedRayForTransform),n._cachedRayForTransform}),i,r);return o&&(o.ray=t),o},r.prototype.multiPick=function(e,t,i,r){var n=this;return this._internalMultiPick((function(i){return n.createPickingRay(e,t,i,r||null)}),i)},r.prototype.multiPickWithRay=function(t,i){var r=this;return this._internalMultiPick((function(i){return r._pickWithRayInverseMatrix||(r._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(r._pickWithRayInverseMatrix),r._cachedRayForTransform||(r._cachedRayForTransform=e.Ray.Zero()),e.Ray.TransformToRef(t,r._pickWithRayInverseMatrix,r._cachedRayForTransform),r._cachedRayForTransform}),i)},r.prototype.setPointerOverMesh=function(t){this._pointerOverMesh!==t&&(this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)),this._pointerOverMesh=t,this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)))},r.prototype.getPointerOverMesh=function(){return this._pointerOverMesh},r.prototype.setPointerOverSprite=function(t){this._pointerOverSprite!==t&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=t,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)))},r.prototype.getPointerOverSprite=function(){return this._pointerOverSprite},r.prototype.getPhysicsEngine=function(){return this._physicsEngine},r.prototype.enablePhysics=function(t,i){if(void 0===t&&(t=null),this._physicsEngine)return!0;try{return this._physicsEngine=new e.PhysicsEngine(t,i),!0}catch(t){return e.Tools.Error(t.message),!1}},r.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},r.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},r.prototype.deleteCompoundImpostor=function(e){var t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},r.prototype._rebuildGeometries=function(){for(var e=0,t=this.geometries;e=0&&this._scene.textures.splice(e,1),void 0!==this._texture&&(this.releaseInternalTexture(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear())}},t.prototype.serialize=function(){if(!this.name)return null;var t=e.SerializationHelper.Serialize(this);return e.Animation.AppendSerializedAnimations(this,t),t},t.WhenAllReady=function(e,t){var i=e.length;if(0===i)return void t();for(var r,n,o=0;o0},enumerable:!0,configurable:!0}),r.prototype.getLODLevels=function(){return this._LODLevels},r.prototype._sortLODLevels=function(){this._LODLevels.sort((function(e,t){return e.distancet.distance?-1:0}))},r.prototype.addLODLevel=function(t,i){if(i&&i._masterMesh)return e.Tools.Warn("You cannot use a mesh as LOD level twice"),this;var r=new e.MeshLODLevel(t,i);return this._LODLevels.push(r),i&&(i._masterMesh=this),this._sortLODLevels(),this},r.prototype.getLODLevelAtDistance=function(e){for(var t=0;tr)return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,this._LODLevels[this._LODLevels.length-1].mesh),this;for(var n=0;n0;this.computeWorldMatrix();var a=this.material||o.defaultMaterial;if(a)if(a.storeEffectOnSubMeshes)for(var l=0,c=this.subMeshes;l4,s=o?this.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind):null,a=o?this.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind):null,l=this.skeleton.getTransformMatrices(this),c=e.Tmp.Vector3[0],h=e.Tmp.Matrix[0],u=e.Tmp.Matrix[1],d=0,f=0;f0&&(e.Matrix.FromFloat32ArrayToRefScaled(l,Math.floor(16*r[d+p]),_,u),h.addToSelf(u));if(o)for(p=0;p<4;p++)(_=a[d+p])>0&&(e.Matrix.FromFloat32ArrayToRefScaled(l,Math.floor(16*s[d+p]),_,u),h.addToSelf(u));e.Vector3.TransformCoordinatesFromFloatsToRef(i[f],i[f+1],i[f+2],h,c),c.toArray(i,f)}}return i},r.prototype._createGlobalSubMesh=function(t){var i=this.getTotalVertices();if(!i||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){var r=this.getIndices();if(!r)return null;var n=r.length,o=!1;if(t)o=!0;else for(var s=0,a=this.subMeshes;s=n){o=!0;break}if(l.verticesStart+l.verticesCount>=i){o=!0;break}}if(!o)return this.subMeshes[0]}return this.releaseSubMeshes(),new e.SubMesh(0,0,i,0,this.getTotalIndices(),this)},r.prototype.subdivide=function(t){if(!(t<1)){for(var i=this.getTotalIndices(),r=i/t|0,n=0;r%3!=0;)r++;this.releaseSubMeshes();for(var o=0;o=i);o++)e.SubMesh.CreateFromIndices(0,n,Math.min(r,i-n),this),n+=r;this.synchronizeInstances()}},r.prototype.setVerticesData=function(t,i,r,n){if(void 0===r&&(r=!1),this._geometry)this._geometry.setVerticesData(t,i,r,n);else{var o=new e.VertexData;o.set(i,t);var s=this.getScene();new e.Geometry(e.Geometry.RandomId(),s,o,r,this)}return this},r.prototype.markVerticesDataAsUpdatable=function(e,t){void 0===t&&(t=!0);var i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)},r.prototype.setVerticesBuffer=function(t){return this._geometry||(this._geometry=e.Geometry.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(t),this},r.prototype.updateVerticesData=function(e,t,i,r){return this._geometry?(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this},r.prototype.updateMeshPositions=function(t,i){void 0===i&&(i=!0);var r=this.getVerticesData(e.VertexBuffer.PositionKind);if(!r)return this;if(t(r),this.updateVerticesData(e.VertexBuffer.PositionKind,r,!1,!1),i){var n=this.getIndices(),o=this.getVerticesData(e.VertexBuffer.NormalKind);if(!o)return this;e.VertexData.ComputeNormals(r,n,o),this.updateVerticesData(e.VertexBuffer.NormalKind,o,!1,!1)}return this},r.prototype.makeGeometryUnique=function(){if(!this._geometry)return this;var t=this._geometry,i=this._geometry.copy(e.Geometry.RandomId());return t.releaseForMesh(this,!0),i.applyToMesh(this),this},r.prototype.setIndices=function(t,i,r){if(void 0===i&&(i=null),void 0===r&&(r=!1),this._geometry)this._geometry.setIndices(t,i,r);else{var n=new e.VertexData;n.indices=t;var o=this.getScene();new e.Geometry(e.Geometry.RandomId(),o,n,r,this)}return this},r.prototype.updateIndices=function(e,t){return this._geometry?(this._geometry.updateIndices(e,t),this):this},r.prototype.toLeftHanded=function(){return this._geometry?(this._geometry.toLeftHanded(),this):this},r.prototype._bind=function(t,i,r){if(!this._geometry)return this;var n,o=this.getScene().getEngine();if(this._unIndexed)n=null;else switch(r){case e.Material.PointFillMode:n=null;break;case e.Material.WireFrameFillMode:n=t.getLinesIndexBuffer(this.getIndices(),o);break;default:case e.Material.TriangleFillMode:n=this._unIndexed?null:this._geometry.getIndexBuffer()}return this._geometry._bind(i,n),this},r.prototype._draw=function(t,i,r,n){if(void 0===n&&(n=!1),!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._onBeforeDrawObservable&&this._onBeforeDrawObservable.notifyObservers(this);var o=this.getScene(),s=o.getEngine();if(this._unIndexed||i==e.Material.PointFillMode?s.drawArraysType(i,t.verticesStart,t.verticesCount,r):i==e.Material.WireFrameFillMode?s.drawElementsType(i,0,t.linesIndexCount,r):s.drawElementsType(i,t.indexStart,t.indexCount,r),o._isAlternateRenderingEnabled&&!n){var a=t.effect||this._effectiveMaterial.getEffect();if(!a||!o.activeCamera)return this;o._switchToAlternateCameraConfiguration(!0),this._effectiveMaterial.bindView(a),this._effectiveMaterial.bindViewProjection(a),s.setViewport(o.activeCamera._alternateCamera.viewport),this._draw(t,i,r,!0),s.setViewport(o.activeCamera.viewport),o._switchToAlternateCameraConfiguration(!1),this._effectiveMaterial.bindView(a),this._effectiveMaterial.bindViewProjection(a)}return this},r.prototype.registerBeforeRender=function(e){return this.onBeforeRenderObservable.add(e),this},r.prototype.unregisterBeforeRender=function(e){return this.onBeforeRenderObservable.removeCallback(e),this},r.prototype.registerAfterRender=function(e){return this.onAfterRenderObservable.add(e),this},r.prototype.unregisterAfterRender=function(e){return this.onAfterRenderObservable.removeCallback(e),this},r.prototype._getInstancesRenderList=function(e){var t=this.getScene();if(this._batchCache.mustReturn=!1,this._batchCache.renderSelf[e]=this.isEnabled()&&this.isVisible,this._batchCache.visibleInstances[e]=null,this._visibleInstances){var i=t.getRenderId(),r=t._isInIntermediateRendering()?this._visibleInstances.intermediateDefaultRenderId:this._visibleInstances.defaultRenderId;this._batchCache.visibleInstances[e]=this._visibleInstances[i];var n=this._renderId;!this._batchCache.visibleInstances[e]&&r&&(this._batchCache.visibleInstances[e]=this._visibleInstances[r],i=Math.max(r,i),n=Math.max(this._visibleInstances.selfDefaultRenderId,i));var o=this._batchCache.visibleInstances[e];if(o&&o.length){if(this._renderIdForInstances[e]===i)return this._batchCache.mustReturn=!0,this._batchCache;i!==n&&(this._batchCache.renderSelf[e]=!1)}this._renderIdForInstances[e]=i}return this._batchCache},r.prototype._renderWithInstances=function(t,i,r,n,o){var s=r.visibleInstances[t._id];if(!s)return this;for(var a=s.length+1,l=16*a*4,c=this._instancesBufferSize,h=this._instancesBuffer;this._instancesBufferSizes-1)&&(h=s-1),c>.001){for(var f=1/c,u=0;u<4;u++)n[l+u]*=f;if(o)for(var u=0;u<4;u++)o[l+u]*=f}else h>=4?(o[l+h-4]=1-c,r[l+h-4]=t):(n[l+h]=1-c,i[l+h]=t)}this.setVerticesData(e.VertexBuffer.MatricesIndicesKind,i),r&&this.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,r),this.setVerticesData(e.VertexBuffer.MatricesWeightsKind,n),o&&this.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,o)}},r.prototype._checkDelayState=function(){var t=this.getScene();return this._geometry?this._geometry.load(t):this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADING,this._queueLoad(t)),this},r.prototype._queueLoad=function(t){var i=this;t._addPendingData(this);var r=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return e.Tools.LoadFile(this.delayLoadingFile,(function(r){r instanceof ArrayBuffer?i._delayLoadingFunction(r,i):i._delayLoadingFunction(JSON.parse(r),i),i.instances.forEach((function(e){e._syncSubMeshes()})),i.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,t._removePendingData(i)}),(function(){}),t.database,r),this},r.prototype.isInFrustum=function(t){return this.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADING&&(!!i.prototype.isInFrustum.call(this,t)&&(this._checkDelayState(),!0))},r.prototype.setMaterialByID=function(e){var t,i=this.getScene().materials;for(t=i.length-1;t>-1;t--)if(i[t].id===e)return this.material=i[t],this;var r=this.getScene().multiMaterials;for(t=r.length-1;t>-1;t--)if(r[t].id===e)return this.material=r[t],this;return this},r.prototype.getAnimatables=function(){var e=new Array;return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e},r.prototype.bakeTransformIntoVertices=function(t){if(!this.isVerticesDataPresent(e.VertexBuffer.PositionKind))return this;var i=this.subMeshes.splice(0);this._resetPointsArrayCache();var r,n=this.getVerticesData(e.VertexBuffer.PositionKind),o=new Array;for(r=0;r-1&&(o.morphTargetManager=i.getMorphTargetManagerById(t.morphTargetManagerId)),t.skeletonId>-1&&(o.skeleton=i.getLastSkeletonByID(t.skeletonId),t.numBoneInfluencers&&(o.numBoneInfluencers=t.numBoneInfluencers)),t.animations){for(var s=0;s4,c=l?this.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind):null,h=l?this.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind):null,u=t.getTransformMatrices(this),d=e.Vector3.Zero(),f=new e.Matrix,p=new e.Matrix,_=0,m=0;m0&&(e.Matrix.FromFloat32ArrayToRefScaled(u,Math.floor(16*o[_+a]),g,p),f.addToSelf(p));if(l)for(a=0;a<4;a++)(g=h[_+a])>0&&(e.Matrix.FromFloat32ArrayToRefScaled(u,Math.floor(16*c[_+a]),g,p),f.addToSelf(p));e.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[m],this._sourcePositions[m+1],this._sourcePositions[m+2],f,d),d.toArray(r,m),e.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[m],this._sourceNormals[m+1],this._sourceNormals[m+2],f,d),d.toArray(n,m),f.reset()}return this.updateVerticesData(e.VertexBuffer.PositionKind,r),this.updateVerticesData(e.VertexBuffer.NormalKind,n),this},r.MinMax=function(t){var i=null,r=null;return t.forEach((function(e,t,n){var o=e.getBoundingInfo(),s=o.boundingBox;i&&r?(i.minimizeInPlace(s.minimumWorld),r.maximizeInPlace(s.maximumWorld)):(i=s.minimumWorld,r=s.maximumWorld)})),i&&r?{min:i,max:r}:{min:e.Vector3.Zero(),max:e.Vector3.Zero()}},r.Center=function(t){var i=t instanceof Array?r.MinMax(t):t;return e.Vector3.Center(i.min,i.max)},r.MergeMeshes=function(t,i,n,o,s){void 0===i&&(i=!0);var a;if(!n){var l=0;for(a=0;a65536)return e.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}var c,h=null,u=new Array,d=null;for(a=0;aa&&(a=h)}return new i(e,s,a-s+1,t,r,n,o)},i})(t);e.SubMesh=i})(r||(r={}));var r,s=this&&this.__assign||Object.assign||function(e){for(var t,i=1,r=arguments.length;i=0&&this._scene.materials.splice(i,1),i=0;ia?a:Math.floor(l);var c,h,u,d,f=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,p=i.uvs,_=i.colors,m=[],g=[],v=[],y=[],b=[],x=[],T=[],E=[],P=[],A=[];if(r.length<2){var M=[],S=[];for(u=0;u0&&(I=C[d].subtract(C[d-1]).length(),w=I+T[h],b[h].push(w),T[h]=w),d++;o&&(d--,m.push(C[0].x,C[0].y,C[0].z),I=C[d].subtract(C[0]).length(),w=I+T[h],b[h].push(w),T[h]=w),P[h]=R+D,A[h]=O,O+=R+D}var L,F,B=null,V=null;for(u=0;u1)?1:i.arc||1,l=i.slice&&i.slice<=0?1:i.slice||1,c=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,h=new e.Vector3(n/2,o/2,s/2),u=2+r,d=2*u,f=[],p=[],_=[],m=[],g=0;g<=u;g++){for(var v=g/u,y=v*Math.PI*l,b=0;b<=d;b++){var x=b/d,T=x*Math.PI*2*a,E=e.Matrix.RotationZ(-y),P=e.Matrix.RotationY(T),A=e.Vector3.TransformCoordinates(e.Vector3.Up(),E),M=e.Vector3.TransformCoordinates(A,P),S=M.multiply(h),C=M.divide(h).normalize();p.push(S.x,S.y,S.z),_.push(C.x,C.y,C.z),m.push(x,v)}if(g>0)for(var R=p.length/3,O=R-2*(d+1);O+d+21)?1:i.arc||1,d=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,f=i.faceUV||new Array(3),p=i.faceColors,_=1!==u&&h?2:0,m=c?l:1,g=2+(1+_)*m;for(r=0;r0&&(i.push(a-1),i.push(a)),a++}var d=new t;return d.indices=i,d.positions=r,o&&(d.colors=s),d},t.CreateDashedLines=function(i){var r=i.dashSize||3,n=i.gapSize||1,o=i.dashNb||200,s=i.points,a=new Array,l=new Array,c=e.Vector3.Zero(),h=0,u=0,d=0,f=0,p=0,_=0,m=0;for(m=0;m1)?1:i.arc||1,h=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE;r.push(0,0,0),s.push(.5,.5);for(var u=2*Math.PI*c,d=u/l,f=0;f=r.length)?0:i.type||0,u=i.size,d=i.sizeX||u||1,f=i.sizeY||u||1,p=i.sizeZ||u||1,_=i.custom||r[h],m=_.face.length,g=i.faceUV||new Array(m),v=i.faceColors,y=void 0===i.flat||i.flat,b=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,x=new Array,T=new Array,E=new Array,P=new Array,A=new Array,M=0,S=0,C=new Array,R=0,O=0;if(y)for(O=0;On.bbSize.y?n.bbSize.x:n.bbSize.y;$=$>n.bbSize.z?$:n.bbSize.z,w=n.subDiv.X*O/n.bbSize.x,L=n.subDiv.Y*O/n.bbSize.y,F=n.subDiv.Z*O/n.bbSize.z,B=n.subDiv.max*n.subDiv.max,n.facetPartitioning.length=0}for(o=0;o0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),this._indexBuffer&&(this._indexBuffer.references=i)},t.prototype.notifyUpdate=function(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e);for(var t=0,i=this._meshes;t0){for(var i=0;i0){for(var i=0;i0){for(var i=0;i0){var l=new Float32Array(i,a.positionsAttrDesc.offset,a.positionsAttrDesc.count);r.setVerticesData(e.VertexBuffer.PositionKind,l,!1)}if(a.normalsAttrDesc&&a.normalsAttrDesc.count>0){var c=new Float32Array(i,a.normalsAttrDesc.offset,a.normalsAttrDesc.count);r.setVerticesData(e.VertexBuffer.NormalKind,c,!1)}if(a.tangetsAttrDesc&&a.tangetsAttrDesc.count>0){var h=new Float32Array(i,a.tangetsAttrDesc.offset,a.tangetsAttrDesc.count);r.setVerticesData(e.VertexBuffer.TangentKind,h,!1)}if(a.uvsAttrDesc&&a.uvsAttrDesc.count>0){var u=new Float32Array(i,a.uvsAttrDesc.offset,a.uvsAttrDesc.count);r.setVerticesData(e.VertexBuffer.UVKind,u,!1)}if(a.uvs2AttrDesc&&a.uvs2AttrDesc.count>0){var d=new Float32Array(i,a.uvs2AttrDesc.offset,a.uvs2AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV2Kind,d,!1)}if(a.uvs3AttrDesc&&a.uvs3AttrDesc.count>0){var f=new Float32Array(i,a.uvs3AttrDesc.offset,a.uvs3AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV3Kind,f,!1)}if(a.uvs4AttrDesc&&a.uvs4AttrDesc.count>0){var p=new Float32Array(i,a.uvs4AttrDesc.offset,a.uvs4AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV4Kind,p,!1)}if(a.uvs5AttrDesc&&a.uvs5AttrDesc.count>0){var _=new Float32Array(i,a.uvs5AttrDesc.offset,a.uvs5AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV5Kind,_,!1)}if(a.uvs6AttrDesc&&a.uvs6AttrDesc.count>0){var m=new Float32Array(i,a.uvs6AttrDesc.offset,a.uvs6AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV6Kind,m,!1)}if(a.colorsAttrDesc&&a.colorsAttrDesc.count>0){var g=new Float32Array(i,a.colorsAttrDesc.offset,a.colorsAttrDesc.count);r.setVerticesData(e.VertexBuffer.ColorKind,g,!1,a.colorsAttrDesc.stride)}if(a.matricesIndicesAttrDesc&&a.matricesIndicesAttrDesc.count>0){for(var v=new Int32Array(i,a.matricesIndicesAttrDesc.offset,a.matricesIndicesAttrDesc.count),y=[],b=0;b>8),y.push((16711680&x)>>16),y.push(x>>24)}r.setVerticesData(e.VertexBuffer.MatricesIndicesKind,y,!1)}if(a.matricesWeightsAttrDesc&&a.matricesWeightsAttrDesc.count>0){var T=new Float32Array(i,a.matricesWeightsAttrDesc.offset,a.matricesWeightsAttrDesc.count);r.setVerticesData(e.VertexBuffer.MatricesWeightsKind,T,!1)}if(a.indicesAttrDesc&&a.indicesAttrDesc.count>0){var E=new Int32Array(i,a.indicesAttrDesc.offset,a.indicesAttrDesc.count);r.setIndices(E,null)}if(a.subMeshesAttrDesc&&a.subMeshesAttrDesc.count>0){var P=new Int32Array(i,a.subMeshesAttrDesc.offset,5*a.subMeshesAttrDesc.count);r.subMeshes=[];for(var b=0;b>8),y.push((16711680&O)>>16),y.push(O>>24)}r.setVerticesData(e.VertexBuffer.MatricesIndicesKind,y,i.matricesIndices._updatable)}if(i.matricesIndicesExtra)if(i.matricesIndicesExtra._isExpanded)delete i.matricesIndices._isExpanded,r.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,i.matricesIndicesExtra,i.matricesIndicesExtra._updatable);else{for(var y=[],b=0;b>8),y.push((16711680&O)>>16),y.push(O>>24)}r.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,y,i.matricesIndicesExtra._updatable)}i.matricesWeights&&(t._CleanMatricesWeights(i,r),r.setVerticesData(e.VertexBuffer.MatricesWeightsKind,i.matricesWeights,i.matricesWeights._updatable)),i.matricesWeightsExtra&&r.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,i.matricesWeightsExtra,i.matricesWeights._updatable),r.setIndices(i.indices,null)}if(i.subMeshes){r.subMeshes=[];for(var D=0;D-1){var n=i.getScene().getLastSkeletonByID(t.skeletonId);if(n){r=n.bones.length;for(var o=i.getVerticesData(e.VertexBuffer.MatricesIndicesKind),s=i.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind),a=t.matricesWeights,l=t.matricesWeightsExtra,c=t.numBoneInfluencer,h=a.length,u=0;uc-1)&&(f=c-1),d>.001){for(var m=1/d,p=0;p<4;p++)a[u+p]*=m;if(l)for(var p=0;p<4;p++)l[u+p]*=m}else f>=4?(l[u+f-4]=1-d,s[u+f-4]=r):(a[u+f]=1-d,o[u+f]=r)}i.setVerticesData(e.VertexBuffer.MatricesIndicesKind,o),t.matricesWeightsExtra&&i.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,s)}}}},t.Parse=function(i,r,n){if(r.getGeometryByID(i.id))return null;var o=new t(i.id,r,void 0,i.updatable);return e.Tags&&e.Tags.AddTagsTo(o,i.tags),i.delayLoadingFile?(o.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED,o.delayLoadingFile=n+i.delayLoadingFile,o._boundingInfo=new e.BoundingInfo(e.Vector3.FromArray(i.boundingBoxMinimum),e.Vector3.FromArray(i.boundingBoxMaximum)),o._delayInfo=[],i.hasUVs&&o._delayInfo.push(e.VertexBuffer.UVKind),i.hasUVs2&&o._delayInfo.push(e.VertexBuffer.UV2Kind),i.hasUVs3&&o._delayInfo.push(e.VertexBuffer.UV3Kind),i.hasUVs4&&o._delayInfo.push(e.VertexBuffer.UV4Kind),i.hasUVs5&&o._delayInfo.push(e.VertexBuffer.UV5Kind),i.hasUVs6&&o._delayInfo.push(e.VertexBuffer.UV6Kind),i.hasColors&&o._delayInfo.push(e.VertexBuffer.ColorKind),i.hasMatricesIndices&&o._delayInfo.push(e.VertexBuffer.MatricesIndicesKind),i.hasMatricesWeights&&o._delayInfo.push(e.VertexBuffer.MatricesWeightsKind),o._delayLoadingFunction=e.VertexData.ImportVertexData):e.VertexData.ImportVertexData(i,o),r.pushGeometry(o,!0),o},t})();e.Geometry=t;var i=(function(e){function t(t,i,r,n){void 0===r&&(r=!1),void 0===n&&(n=null);var o=e.call(this,t,i,void 0,!1,n)||this;return o._canBeRegenerated=r,o._beingRegenerated=!0,o.regenerate(),o._beingRegenerated=!1,o}return o(t,e),t.prototype.canBeRegenerated=function(){return this._canBeRegenerated},t.prototype.regenerate=function(){this._canBeRegenerated&&(this._beingRegenerated=!0,this.setAllVerticesData(this._regenerateVertexData(),!1),this._beingRegenerated=!1)},t.prototype.asNewGeometry=function(t){return e.prototype.copy.call(this,t)},t.prototype.setAllVerticesData=function(t,i){this._beingRegenerated&&e.prototype.setAllVerticesData.call(this,t,!1)},t.prototype.setVerticesData=function(t,i,r){this._beingRegenerated&&e.prototype.setVerticesData.call(this,t,i,!1)},t.prototype._regenerateVertexData=function(){throw new Error("Abstract method")},t.prototype.copy=function(e){throw new Error("Must be overriden in sub-classes.")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.canBeRegenerated=this.canBeRegenerated(),t},t})(t);e._PrimitiveGeometry=i;var r=(function(t){function i(i,r,n,o,s,a,l,c,h){void 0===h&&(h=e.Mesh.DEFAULTSIDE);var u=t.call(this,i,r,l,c)||this;return u.pathArray=n,u.closeArray=o,u.closePath=s,u.offset=a,u.side=h,u}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateRibbon({pathArray:this.pathArray,closeArray:this.closeArray,closePath:this.closePath,offset:this.offset,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.pathArray,this.closeArray,this.closePath,this.offset,this.canBeRegenerated(),void 0,this.side)},i})(i);e.RibbonGeometry=r;var n=(function(t){function i(i,r,n,o,s,a){void 0===s&&(s=null),void 0===a&&(a=e.Mesh.DEFAULTSIDE);var l=t.call(this,i,r,o,s)||this;return l.size=n,l.side=a,l}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateBox({size:this.size,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.size,this.canBeRegenerated(),void 0,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.size=this.size,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.size,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.BoxGeometry=n;var s=(function(t){function i(i,r,n,o,s,a,l){void 0===a&&(a=null),void 0===l&&(l=e.Mesh.DEFAULTSIDE);var c=t.call(this,i,r,s,a)||this;return c.segments=n,c.diameter=o,c.side=l,c}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateSphere({segments:this.segments,diameter:this.diameter,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.segments,this.diameter,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.segments=this.segments,e.diameter=this.diameter,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.segments,t.diameter,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.SphereGeometry=s;var a=(function(t){function i(i,r,n,o,s,a,l){void 0===a&&(a=null),void 0===l&&(l=e.Mesh.DEFAULTSIDE);var c=t.call(this,i,r,s,a)||this;return c.radius=n, +c.tessellation=o,c.side=l,c}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateDisc({radius:this.radius,tessellation:this.tessellation,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.radius,this.tessellation,this.canBeRegenerated(),null,this.side)},i})(i);e.DiscGeometry=a;var l=(function(t){function i(i,r,n,o,s,a,l,c,h,u){void 0===l&&(l=1),void 0===h&&(h=null),void 0===u&&(u=e.Mesh.DEFAULTSIDE);var d=t.call(this,i,r,c,h)||this;return d.height=n,d.diameterTop=o,d.diameterBottom=s,d.tessellation=a,d.subdivisions=l,d.side=u,d}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateCylinder({height:this.height,diameterTop:this.diameterTop,diameterBottom:this.diameterBottom,tessellation:this.tessellation,subdivisions:this.subdivisions,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.height,this.diameterTop,this.diameterBottom,this.tessellation,this.subdivisions,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.height=this.height,e.diameterTop=this.diameterTop,e.diameterBottom=this.diameterBottom,e.tessellation=this.tessellation,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.height,t.diameterTop,t.diameterBottom,t.tessellation,t.subdivisions,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.CylinderGeometry=l;var c=(function(t){function i(i,r,n,o,s,a,l,c){void 0===l&&(l=null),void 0===c&&(c=e.Mesh.DEFAULTSIDE);var h=t.call(this,i,r,a,l)||this;return h.diameter=n,h.thickness=o,h.tessellation=s,h.side=c,h}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorus({diameter:this.diameter,thickness:this.thickness,tessellation:this.tessellation,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.diameter,this.thickness,this.tessellation,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.diameter=this.diameter,e.thickness=this.thickness,e.tessellation=this.tessellation,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.diameter,t.thickness,t.tessellation,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.TorusGeometry=c;var h=(function(t){function i(e,i,r,n,o,s,a){void 0===a&&(a=null);var l=t.call(this,e,i,s,a)||this;return l.width=r,l.height=n,l.subdivisions=o,l}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateGround({width:this.width,height:this.height,subdivisions:this.subdivisions})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.width,this.height,this.subdivisions,this.canBeRegenerated(),null)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.width=this.width,e.height=this.height,e.subdivisions=this.subdivisions,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.width,t.height,t.subdivisions,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.GroundGeometry=h;var u=(function(t){function i(e,i,r,n,o,s,a,l,c,h){void 0===h&&(h=null);var u=t.call(this,e,i,c,h)||this;return u.xmin=r,u.zmin=n,u.xmax=o,u.zmax=s,u.subdivisions=a,u.precision=l,u}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTiledGround({xmin:this.xmin,zmin:this.zmin,xmax:this.xmax,zmax:this.zmax,subdivisions:this.subdivisions,precision:this.precision})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.xmin,this.zmin,this.xmax,this.zmax,this.subdivisions,this.precision,this.canBeRegenerated(),null)},i})(i);e.TiledGroundGeometry=u;var d=(function(t){function i(i,r,n,o,s,a){void 0===s&&(s=null),void 0===a&&(a=e.Mesh.DEFAULTSIDE);var l=t.call(this,i,r,o,s)||this;return l.size=n,l.side=a,l}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreatePlane({size:this.size,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.size,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.size=this.size,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.size,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.PlaneGeometry=d;var f=(function(t){function i(i,r,n,o,s,a,l,c,h,u,d){void 0===u&&(u=null),void 0===d&&(d=e.Mesh.DEFAULTSIDE);var f=t.call(this,i,r,h,u)||this;return f.radius=n,f.tube=o,f.radialSegments=s,f.tubularSegments=a,f.p=l,f.q=c,f.side=d,f}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorusKnot({radius:this.radius,tube:this.tube,radialSegments:this.radialSegments,tubularSegments:this.tubularSegments,p:this.p,q:this.q,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.radius,this.tube,this.radialSegments,this.tubularSegments,this.p,this.q,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.radius=this.radius,e.tube=this.tube,e.radialSegments=this.radialSegments,e.tubularSegments=this.tubularSegments,e.p=this.p,e.q=this.q,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.radius,t.tube,t.radialSegments,t.tubularSegments,t.p,t.q,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.TorusKnotGeometry=f})(r||(r={}));var r;!(function(e){var t=(function(){function t(e){void 0===e&&(e=30),this._enabled=!0,this._rollingFrameTime=new i(e)}return t.prototype.sampleFrame=function(t){if(void 0===t&&(t=e.Tools.Now),this._enabled){if(null!=this._lastFrameTimeMs){var i=t-this._lastFrameTimeMs;this._rollingFrameTime.add(i)}this._lastFrameTimeMs=t}},Object.defineProperty(t.prototype,"averageFrameTime",{get:function(){return this._rollingFrameTime.average},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"averageFrameTimeVariance",{get:function(){return this._rollingFrameTime.variance},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"instantaneousFrameTime",{get:function(){return this._rollingFrameTime.history(0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"averageFPS",{get:function(){return 1e3/this._rollingFrameTime.average},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"instantaneousFPS",{get:function(){var e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isSaturated",{get:function(){return this._rollingFrameTime.isSaturated()},enumerable:!0,configurable:!0}),t.prototype.enable=function(){this._enabled=!0},t.prototype.disable=function(){this._enabled=!1,this._lastFrameTimeMs=null},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._enabled},enumerable:!0,configurable:!0}),t.prototype.reset=function(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()},t})();e.PerformanceMonitor=t;var i=(function(){function e(e){this._samples=new Array(e),this.reset()}return e.prototype.add=function(e){var t;if(this.isSaturated()){var i=this._samples[this._pos];t=i-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(i-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length},e.prototype.history=function(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;var t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]},e.prototype.isSaturated=function(){return this._sampleCount>=this._samples.length},e.prototype.reset=function(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0},e.prototype._wrapPosition=function(e){var t=this._samples.length;return(e%t+t)%t},e})();e.RollingAverage=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.BindEyePosition=function(e,t){if(t._forcedViewPosition)return void e.setVector3("vEyePosition",t._forcedViewPosition);e.setVector3("vEyePosition",t._mirroredCameraPosition?t._mirroredCameraPosition:t.activeCamera.globalPosition)},t.PrepareDefinesForMergedUV=function(e,t,i){t._needUVs=!0,t[i]=!0,e.getTextureMatrix().isIdentity(!0)?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,0===e.coordinatesIndex?t.MAINUV1=!0:t.MAINUV2=!0):t[i+"DIRECTUV"]=0},t.BindTextureMatrix=function(e,t,i){var r=e.getTextureMatrix();r.isIdentity(!0)||t.updateMatrix(i+"Matrix",r)},t.PrepareDefinesForMisc=function(t,i,r,n,o,s,a){a._areMiscDirty&&(a.LOGARITHMICDEPTH=r,a.POINTSIZE=n,a.FOG=i.fogEnabled&&t.applyFog&&i.fogMode!==e.Scene.FOGMODE_NONE&&o,a.NONUNIFORMSCALING=t.nonUniformScaling,a.ALPHATEST=s)},t.PrepareDefinesForFrameBoundValues=function(e,t,i,r,n){void 0===n&&(n=null);var o=!1;null==n&&(n=void 0!==e.clipPlane&&null!==e.clipPlane),i.CLIPPLANE!==n&&(i.CLIPPLANE=n,o=!0),i.DEPTHPREPASS!==!t.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==r&&(i.INSTANCES=r,o=!0),o&&i.markAsUnprocessed()},t.PrepareDefinesForAttributes=function(t,i,r,n,o,s){if(void 0===o&&(o=!1),void 0===s&&(s=!0),!i._areAttributesDirty&&i._needNormals===i._normals&&i._needUVs===i._uvs)return!1;if(i._normals=i._needNormals,i._uvs=i._needUVs,i.NORMAL=i._needNormals&&t.isVerticesDataPresent(e.VertexBuffer.NormalKind),i._needNormals&&t.isVerticesDataPresent(e.VertexBuffer.TangentKind)&&(i.TANGENT=!0),i._needUVs?(i.UV1=t.isVerticesDataPresent(e.VertexBuffer.UVKind),i.UV2=t.isVerticesDataPresent(e.VertexBuffer.UV2Kind)):(i.UV1=!1,i.UV2=!1),r){var a=t.useVertexColors&&t.isVerticesDataPresent(e.VertexBuffer.ColorKind);i.VERTEXCOLOR=a,i.VERTEXALPHA=t.hasVertexAlpha&&a&&s}if(n&&(t.useBones&&t.computeBonesUsingShaders&&t.skeleton?(i.NUM_BONE_INFLUENCERS=t.numBoneInfluencers,i.BonesPerMesh=t.skeleton.bones.length+1):(i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0)),o){var l=t.morphTargetManager;l?(i.MORPHTARGETS_TANGENT=l.supportsTangents&&i.TANGENT,i.MORPHTARGETS_NORMAL=l.supportsNormals&&i.NORMAL,i.MORPHTARGETS=l.numInfluencers>0,i.NUM_MORPH_INFLUENCERS=l.numInfluencers):(i.MORPHTARGETS_TANGENT=!1,i.MORPHTARGETS_NORMAL=!1,i.MORPHTARGETS=!1,i.NUM_MORPH_INFLUENCERS=0)}return!0},t.PrepareDefinesForLights=function(t,i,r,n,o,s){if(void 0===o&&(o=4),void 0===s&&(s=!1),!r._areLightsDirty)return r._needNormals;var a=0,l=!1,c=!1,h=!1,u=!1,d=!1;if(t.lightsEnabled&&!s)for(var f=0,p=i._lightSources;f0&&(u=!0,m.prepareDefines(r,a))}}if(_.lightmapMode!=e.Light.LIGHTMAP_DEFAULT?(h=!0,r["LIGHTMAPEXCLUDED"+a]=!0,r["LIGHTMAPNOSPECULAR"+a]=_.lightmapMode==e.Light.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+a]=!1,r["LIGHTMAPNOSPECULAR"+a]=!1),++a===o)break}r.SPECULARTERM=d,r.SHADOWS=u;for(var v=a;v0&&(n=r+o,t.addFallback(n,"LIGHT"+o)),e.SHADOWS||(e["SHADOW"+o]&&t.addFallback(r,"SHADOW"+o),e["SHADOWPCF"+o]&&t.addFallback(r,"SHADOWPCF"+o),e["SHADOWPCSS"+o]&&t.addFallback(r,"SHADOWPCSS"+o),e["SHADOWPOISSON"+o]&&t.addFallback(r,"SHADOWPOISSON"+o),e["SHADOWESM"+o]&&t.addFallback(r,"SHADOWESM"+o));return n++},t.PrepareAttributesForMorphTargets=function(t,i,r){var n=r.NUM_MORPH_INFLUENCERS;if(n>0&&e.Engine.LastCreatedEngine)for(var o=e.Engine.LastCreatedEngine.getCaps().maxVertexAttribs,s=i.morphTargetManager,a=s&&s.supportsNormals&&r.NORMAL,l=s&&s.supportsTangents&&r.TANGENT,c=0;co&&e.Tools.Error("Cannot add more vertex attributes for mesh "+i.name)},t.PrepareAttributesForBones=function(t,i,r,n){r.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,i),t.push(e.VertexBuffer.MatricesIndicesKind),t.push(e.VertexBuffer.MatricesWeightsKind),r.NUM_BONE_INFLUENCERS>4&&(t.push(e.VertexBuffer.MatricesIndicesExtraKind),t.push(e.VertexBuffer.MatricesWeightsExtraKind)))},t.PrepareAttributesForInstances=function(e,t){t.INSTANCES&&(e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"))},t.BindLightShadow=function(e,t,i,r,n){if(e.shadowEnabled&&i.receiveShadows){var o=e.getShadowGenerator();o&&o.bindShadowLight(r,n)}},t.BindLightProperties=function(e,t,i){e.transferToEffect(t,i+"")},t.BindLights=function(i,r,n,o,s,a){void 0===s&&(s=4),void 0===a&&(a=!1);for(var l=Math.min(r._lightSources.length,s),c=0;c0,a.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,a.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===e.Texture.INVCUBIC_MODE,a.REFLECTIONMAP_3D=this._reflectionTexture.isCube,this._reflectionTexture.coordinatesMode){case e.Texture.EXPLICIT_MODE:a.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case e.Texture.PLANAR_MODE:a.setReflectionMode("REFLECTIONMAP_PLANAR");break;case e.Texture.PROJECTION_MODE:a.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case e.Texture.SKYBOX_MODE:a.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case e.Texture.SPHERICAL_MODE:a.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case e.Texture.EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:default:a.setReflectionMode("REFLECTIONMAP_CUBIC")}a.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else a.REFLECTION=!1;if(this._emissiveTexture&&r.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,a,"EMISSIVE")}else a.EMISSIVE=!1;if(this._lightmapTexture&&r.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,a,"LIGHTMAP"),a.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap}else a.LIGHTMAP=!1;if(this._specularTexture&&r.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture,a,"SPECULAR"),a.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else a.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&r.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,a,"BUMP"),a.PARALLAX=this._useParallax,a.PARALLAXOCCLUSION=this._useParallaxOcclusion,a.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else a.BUMP=!1;if(this._refractionTexture&&r.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;a._needUVs=!0,a.REFRACTION=!0,a.REFRACTIONMAP_3D=this._refractionTexture.isCube}else a.REFRACTION=!1;a.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else a.DIFFUSE=!1,a.AMBIENT=!1,a.OPACITY=!1,a.REFLECTION=!1,a.EMISSIVE=!1,a.LIGHTMAP=!1,a.BUMP=!1,a.REFRACTION=!1;a.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),a.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,a.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,a.SPECULAROVERALPHA=this._useSpecularOverAlpha,a.PREMULTIPLYALPHA=this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED||this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF}if(a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a),a.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,a.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if(a._areFresnelDirty&&(r.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(a.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,a.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,a.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,a.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,a.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,a.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,a._needNormals=!0,a.FRESNEL=!0):a.FRESNEL=!1),e.MaterialHelper.PrepareDefinesForMisc(i,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(i),a),e.MaterialHelper.PrepareDefinesForAttributes(i,a,!0,!0,!0),e.MaterialHelper.PrepareDefinesForFrameBoundValues(s,l,a,o),a.isDirty){a.markAsProcessed(),s.resetCachedMaterial();var c=new e.EffectFallbacks;a.REFLECTION&&c.addFallback(0,"REFLECTION"),a.SPECULAR&&c.addFallback(0,"SPECULAR"),a.BUMP&&c.addFallback(0,"BUMP"),a.PARALLAX&&c.addFallback(1,"PARALLAX"),a.PARALLAXOCCLUSION&&c.addFallback(0,"PARALLAXOCCLUSION"),a.SPECULAROVERALPHA&&c.addFallback(0,"SPECULAROVERALPHA"),a.FOG&&c.addFallback(1,"FOG"),a.POINTSIZE&&c.addFallback(0,"POINTSIZE"),a.LOGARITHMICDEPTH&&c.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(a,c,this._maxSimultaneousLights),a.SPECULARTERM&&c.addFallback(0,"SPECULARTERM"),a.DIFFUSEFRESNEL&&c.addFallback(1,"DIFFUSEFRESNEL"),a.OPACITYFRESNEL&&c.addFallback(2,"OPACITYFRESNEL"),a.REFLECTIONFRESNEL&&c.addFallback(3,"REFLECTIONFRESNEL"),a.EMISSIVEFRESNEL&&c.addFallback(4,"EMISSIVEFRESNEL"),a.FRESNEL&&c.addFallback(4,"FRESNEL");var h=[e.VertexBuffer.PositionKind];a.NORMAL&&h.push(e.VertexBuffer.NormalKind),a.UV1&&h.push(e.VertexBuffer.UVKind),a.UV2&&h.push(e.VertexBuffer.UV2Kind),a.VERTEXCOLOR&&h.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(h,i,a,c),e.MaterialHelper.PrepareAttributesForInstances(h,a),e.MaterialHelper.PrepareAttributesForMorphTargets(h,i,a);var u="default",d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff"],f=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler"],p=["Material","Scene"];e.ImageProcessingConfiguration&&(e.ImageProcessingConfiguration.PrepareUniforms(d,a),e.ImageProcessingConfiguration.PrepareSamplers(f,a)),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:a,maxSimultaneousLights:this._maxSimultaneousLights}),this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,d,p,f,a)) +;var _=a.toString();n.setEffect(s.getEngine().createEffect(u,{attributes:h,uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:_,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:a.NUM_MORPH_INFLUENCERS}},l),a),this.buildUniformLayout()}return!(!n.effect||!n.effect.isReady())&&(a._renderId=s.getRenderId(),this._wasPreviouslyReady=!0,!0)},r.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("diffuseLeftColor",4),this._uniformBuffer.addUniform("diffuseRightColor",4),this._uniformBuffer.addUniform("opacityParts",4),this._uniformBuffer.addUniform("reflectionLeftColor",4),this._uniformBuffer.addUniform("reflectionRightColor",4),this._uniformBuffer.addUniform("refractionLeftColor",4),this._uniformBuffer.addUniform("refractionRightColor",4),this._uniformBuffer.addUniform("emissiveLeftColor",4),this._uniformBuffer.addUniform("emissiveRightColor",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vAmbientInfos",2),this._uniformBuffer.addUniform("vOpacityInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("vReflectionPosition",3),this._uniformBuffer.addUniform("vReflectionSize",3),this._uniformBuffer.addUniform("vEmissiveInfos",2),this._uniformBuffer.addUniform("vLightmapInfos",2),this._uniformBuffer.addUniform("vSpecularInfos",2),this._uniformBuffer.addUniform("vBumpInfos",3),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("ambientMatrix",16),this._uniformBuffer.addUniform("opacityMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("emissiveMatrix",16),this._uniformBuffer.addUniform("lightmapMatrix",16),this._uniformBuffer.addUniform("specularMatrix",16),this._uniformBuffer.addUniform("bumpMatrix",16),this._uniformBuffer.addUniform("vTangentSpaceParams",2),this._uniformBuffer.addUniform("refractionMatrix",16),this._uniformBuffer.addUniform("vRefractionInfos",4),this._uniformBuffer.addUniform("vSpecularColor",4),this._uniformBuffer.addUniform("vEmissiveColor",3),this._uniformBuffer.addUniform("vDiffuseColor",4),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.create()},r.prototype.unbind=function(){if(this._activeEffect){var e=!1;this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&(this._activeEffect.setTexture("reflection2DSampler",null),e=!0),this._refractionTexture&&this._refractionTexture.isRenderTarget&&(this._activeEffect.setTexture("refraction2DSampler",null),e=!0),e&&this._markAllSubMeshesAsTexturesDirty()}i.prototype.unbind.call(this)},r.prototype.bindForSubMesh=function(t,i,n){var o=this.getScene(),s=n._materialDefines;if(s){var a=n.effect;if(a){this._activeEffect=a,this.bindOnlyWorldMatrix(t),s.OBJECTSPACE_NORMALMAP&&(t.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var l=this._mustRebind(o,a,i.visibility);if(e.MaterialHelper.BindBonesParameters(i,a),l){if(this._uniformBuffer.bindToEffect(a,"Material"),this.bindViewProjection(a),!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync){if(r.FresnelEnabled&&s.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),this._uniformBuffer.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&this._uniformBuffer.updateColor4("opacityParts",new e.Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),this._uniformBuffer.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),this._uniformBuffer.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),this._uniformBuffer.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),o.texturesEnabled){if(this._diffuseTexture&&r.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),e.MaterialHelper.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse"),this._diffuseTexture.hasAlpha&&a.setFloat("alphaCutOff",this.alphaCutOff)),this._ambientTexture&&r.AmbientTextureEnabled&&(this._uniformBuffer.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),e.MaterialHelper.BindTextureMatrix(this._ambientTexture,this._uniformBuffer,"ambient")),this._opacityTexture&&r.OpacityTextureEnabled&&(this._uniformBuffer.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),e.MaterialHelper.BindTextureMatrix(this._opacityTexture,this._uniformBuffer,"opacity")),this._reflectionTexture&&r.ReflectionTextureEnabled&&(this._uniformBuffer.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),this._uniformBuffer.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){var c=this._reflectionTexture;this._uniformBuffer.updateVector3("vReflectionPosition",c.boundingBoxPosition),this._uniformBuffer.updateVector3("vReflectionSize",c.boundingBoxSize)}if(this._emissiveTexture&&r.EmissiveTextureEnabled&&(this._uniformBuffer.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),e.MaterialHelper.BindTextureMatrix(this._emissiveTexture,this._uniformBuffer,"emissive")),this._lightmapTexture&&r.LightmapTextureEnabled&&(this._uniformBuffer.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),e.MaterialHelper.BindTextureMatrix(this._lightmapTexture,this._uniformBuffer,"lightmap")),this._specularTexture&&r.SpecularTextureEnabled&&(this._uniformBuffer.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),e.MaterialHelper.BindTextureMatrix(this._specularTexture,this._uniformBuffer,"specular")),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&r.BumpTextureEnabled&&(this._uniformBuffer.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),e.MaterialHelper.BindTextureMatrix(this._bumpTexture,this._uniformBuffer,"bump"),o._mirroredCameraPosition?this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&r.RefractionTextureEnabled){var h=1;this._refractionTexture.isCube||(this._uniformBuffer.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(h=this._refractionTexture.depth)),this._uniformBuffer.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,h,this.invertRefractionY?-1:1)}}this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.SPECULARTERM&&this._uniformBuffer.updateColor4("vSpecularColor",this.specularColor,this.specularPower),this._uniformBuffer.updateColor3("vEmissiveColor",this.emissiveColor),this._uniformBuffer.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha*i.visibility)}if(o.texturesEnabled&&(this._diffuseTexture&&r.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&r.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&r.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&r.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&r.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&r.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&r.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&r.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&r.RefractionTextureEnabled)){var h=1;this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture)}e.MaterialHelper.BindClipPlane(a,o),o.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),e.MaterialHelper.BindEyePosition(a,o),a.setColor3("vAmbientColor",this._globalAmbientColor)}!l&&this.isFrozen||(o.lightsEnabled&&!this._disableLighting&&e.MaterialHelper.BindLights(o,i,a,s,this._maxSimultaneousLights),(o.fogEnabled&&i.applyFog&&o.fogMode!==e.Scene.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture)&&this.bindView(a),e.MaterialHelper.BindFogParameters(o,i,a),s.NUM_MORPH_INFLUENCERS&&e.MaterialHelper.BindMorphTargetParameters(i,a),e.MaterialHelper.BindLogDepth(s,a,o),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(i,this._activeEffect)}}},r.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e},r.prototype.getActiveTextures=function(){var e=i.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e},r.prototype.hasTexture=function(e){return!!i.prototype.hasTexture.call(this,e)||(this._diffuseTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._emissiveTexture===e||(this._specularTexture===e||(this._bumpTexture===e||(this._lightmapTexture===e||this._refractionTexture===e))))))))},r.prototype.dispose=function(e,t){t&&(this._diffuseTexture&&this._diffuseTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._specularTexture&&this._specularTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),i.prototype.dispose.call(this,e,t)},r.prototype.clone=function(t){var i=this,n=e.SerializationHelper.Clone((function(){return new r(t,i.getScene())}),this);return n.name=t,n.id=t,n},r.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},r.Parse=function(t,i,n){return e.SerializationHelper.Parse((function(){return new r(t.name,i)}),t,i,n)},Object.defineProperty(r,"DiffuseTextureEnabled",{get:function(){return r._DiffuseTextureEnabled},set:function(t){r._DiffuseTextureEnabled!==t&&(r._DiffuseTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"AmbientTextureEnabled",{get:function(){return r._AmbientTextureEnabled},set:function(t){r._AmbientTextureEnabled!==t&&(r._AmbientTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"OpacityTextureEnabled",{get:function(){return r._OpacityTextureEnabled},set:function(t){r._OpacityTextureEnabled!==t&&(r._OpacityTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"ReflectionTextureEnabled",{get:function(){return r._ReflectionTextureEnabled},set:function(t){r._ReflectionTextureEnabled!==t&&(r._ReflectionTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"EmissiveTextureEnabled",{get:function(){return r._EmissiveTextureEnabled},set:function(t){r._EmissiveTextureEnabled!==t&&(r._EmissiveTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"SpecularTextureEnabled",{get:function(){return r._SpecularTextureEnabled},set:function(t){r._SpecularTextureEnabled!==t&&(r._SpecularTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"BumpTextureEnabled",{get:function(){return r._BumpTextureEnabled},set:function(t){r._BumpTextureEnabled!==t&&(r._BumpTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"LightmapTextureEnabled",{get:function(){return r._LightmapTextureEnabled},set:function(t){r._LightmapTextureEnabled!==t&&(r._LightmapTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"RefractionTextureEnabled",{get:function(){return r._RefractionTextureEnabled},set:function(t){r._RefractionTextureEnabled!==t&&(r._RefractionTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"ColorGradingTextureEnabled",{get:function(){return r._ColorGradingTextureEnabled},set:function(t){r._ColorGradingTextureEnabled!==t&&(r._ColorGradingTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"FresnelEnabled",{get:function(){return r._FresnelEnabled},set:function(t){r._FresnelEnabled!==t&&(r._FresnelEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.FresnelDirtyFlag))},enumerable:!0,configurable:!0}),r._DiffuseTextureEnabled=!0,r._AmbientTextureEnabled=!0,r._OpacityTextureEnabled=!0,r._ReflectionTextureEnabled=!0,r._EmissiveTextureEnabled=!0,r._SpecularTextureEnabled=!0,r._BumpTextureEnabled=!0,r._LightmapTextureEnabled=!0,r._RefractionTextureEnabled=!0,r._ColorGradingTextureEnabled=!0,r._FresnelEnabled=!0,n([e.serializeAsTexture("diffuseTexture")],r.prototype,"_diffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],r.prototype,"diffuseTexture",void 0),n([e.serializeAsTexture("ambientTexture")],r.prototype,"_ambientTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"ambientTexture",void 0),n([e.serializeAsTexture("opacityTexture")],r.prototype,"_opacityTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],r.prototype,"opacityTexture",void 0),n([e.serializeAsTexture("reflectionTexture")],r.prototype,"_reflectionTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionTexture",void 0),n([e.serializeAsTexture("emissiveTexture")],r.prototype,"_emissiveTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"emissiveTexture",void 0),n([e.serializeAsTexture("specularTexture")],r.prototype,"_specularTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"specularTexture",void 0),n([e.serializeAsTexture("bumpTexture")],r.prototype,"_bumpTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"bumpTexture",void 0),n([e.serializeAsTexture("lightmapTexture")],r.prototype,"_lightmapTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"lightmapTexture",void 0),n([e.serializeAsTexture("refractionTexture")],r.prototype,"_refractionTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"refractionTexture",void 0),n([e.serializeAsColor3("ambient")],r.prototype,"ambientColor",void 0),n([e.serializeAsColor3("diffuse")],r.prototype,"diffuseColor",void 0),n([e.serializeAsColor3("specular")],r.prototype,"specularColor",void 0),n([e.serializeAsColor3("emissive")],r.prototype,"emissiveColor",void 0),n([e.serialize()],r.prototype,"specularPower",void 0),n([e.serialize("useAlphaFromDiffuseTexture")],r.prototype,"_useAlphaFromDiffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useAlphaFromDiffuseTexture",void 0),n([e.serialize("useEmissiveAsIllumination")],r.prototype,"_useEmissiveAsIllumination",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useEmissiveAsIllumination",void 0),n([e.serialize("linkEmissiveWithDiffuse")],r.prototype,"_linkEmissiveWithDiffuse",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"linkEmissiveWithDiffuse",void 0),n([e.serialize("useSpecularOverAlpha")],r.prototype,"_useSpecularOverAlpha",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useSpecularOverAlpha",void 0),n([e.serialize("useReflectionOverAlpha")],r.prototype,"_useReflectionOverAlpha",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useReflectionOverAlpha",void 0),n([e.serialize("disableLighting")],r.prototype,"_disableLighting",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"disableLighting",void 0),n([e.serialize("useObjectSpaceNormalMap")],r.prototype,"_useObjectSpaceNormalMap",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useObjectSpaceNormalMap",void 0),n([e.serialize("useParallax")],r.prototype,"_useParallax",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useParallax",void 0),n([e.serialize("useParallaxOcclusion")],r.prototype,"_useParallaxOcclusion",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useParallaxOcclusion",void 0),n([e.serialize()],r.prototype,"parallaxScaleBias",void 0),n([e.serialize("roughness")],r.prototype,"_roughness",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"roughness",void 0),n([e.serialize()],r.prototype,"indexOfRefraction",void 0),n([e.serialize()],r.prototype,"invertRefractionY",void 0),n([e.serialize()],r.prototype,"alphaCutOff",void 0),n([e.serialize("useLightmapAsShadowmap")],r.prototype,"_useLightmapAsShadowmap",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useLightmapAsShadowmap",void 0),n([e.serializeAsFresnelParameters("diffuseFresnelParameters")],r.prototype,"_diffuseFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"diffuseFresnelParameters",void 0),n([e.serializeAsFresnelParameters("opacityFresnelParameters")],r.prototype,"_opacityFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")],r.prototype,"opacityFresnelParameters",void 0),n([e.serializeAsFresnelParameters("reflectionFresnelParameters")],r.prototype,"_reflectionFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"reflectionFresnelParameters",void 0),n([e.serializeAsFresnelParameters("refractionFresnelParameters")],r.prototype,"_refractionFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"refractionFresnelParameters",void 0),n([e.serializeAsFresnelParameters("emissiveFresnelParameters")],r.prototype,"_emissiveFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"emissiveFresnelParameters",void 0),n([e.serialize("useReflectionFresnelFromSpecular")],r.prototype,"_useReflectionFresnelFromSpecular",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"useReflectionFresnelFromSpecular",void 0),n([e.serialize("useGlossinessFromSpecularMapAlpha")],r.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useGlossinessFromSpecularMapAlpha",void 0),n([e.serialize("maxSimultaneousLights")],r.prototype,"_maxSimultaneousLights",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"maxSimultaneousLights",void 0),n([e.serialize("invertNormalMapX")],r.prototype,"_invertNormalMapX",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"invertNormalMapX",void 0),n([e.serialize("invertNormalMapY")],r.prototype,"_invertNormalMapY",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"invertNormalMapY",void 0),n([e.serialize("twoSidedLighting")],r.prototype,"_twoSidedLighting",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"twoSidedLighting",void 0),n([e.serialize()],r.prototype,"useLogarithmicDepth",null),r})(e.PushMaterial);e.StandardMaterial=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.x=e.Vector3.Zero(),this.y=e.Vector3.Zero(),this.z=e.Vector3.Zero(),this.xx=e.Vector3.Zero(),this.yy=e.Vector3.Zero(),this.zz=e.Vector3.Zero(),this.xy=e.Vector3.Zero(),this.yz=e.Vector3.Zero(),this.zx=e.Vector3.Zero()}return t.prototype.addAmbient=function(t){var i=new e.Vector3(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.prototype.scale=function(e){this.x=this.x.scale(e),this.y=this.y.scale(e),this.z=this.z.scale(e),this.xx=this.xx.scale(e),this.yy=this.yy.scale(e),this.zz=this.zz.scale(e),this.yz=this.yz.scale(e),this.zx=this.zx.scale(e),this.xy=this.xy.scale(e)},t.FromHarmonics=function(e){var i=new t;return i.x=e.l11.scale(1.02333),i.y=e.l1_1.scale(1.02333),i.z=e.l10.scale(1.02333),i.xx=e.l00.scale(.886277).subtract(e.l20.scale(.247708)).add(e.lL22.scale(.429043)),i.yy=e.l00.scale(.886277).subtract(e.l20.scale(.247708)).subtract(e.lL22.scale(.429043)),i.zz=e.l00.scale(.886277).add(e.l20.scale(.495417)),i.yz=e.l2_1.scale(.858086),i.zx=e.l21.scale(.858086),i.xy=e.l2_2.scale(.858086),i.scale(1/Math.PI),i},t.FromArray=function(i){var r=new t;return e.Vector3.FromArrayToRef(i[0],0,r.x),e.Vector3.FromArrayToRef(i[1],0,r.y),e.Vector3.FromArrayToRef(i[2],0,r.z),e.Vector3.FromArrayToRef(i[3],0,r.xx),e.Vector3.FromArrayToRef(i[4],0,r.yy),e.Vector3.FromArrayToRef(i[5],0,r.zz),e.Vector3.FromArrayToRef(i[6],0,r.yz),e.Vector3.FromArrayToRef(i[7],0,r.zx),e.Vector3.FromArrayToRef(i[8],0,r.xy),r},t})();e.SphericalPolynomial=t;var i=(function(){function t(){this.l00=e.Vector3.Zero(),this.l1_1=e.Vector3.Zero(),this.l10=e.Vector3.Zero(),this.l11=e.Vector3.Zero(),this.l2_2=e.Vector3.Zero(),this.l2_1=e.Vector3.Zero(),this.l20=e.Vector3.Zero(),this.l21=e.Vector3.Zero(),this.lL22=e.Vector3.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e.Vector3(i.r,i.g,i.b),o=n.scale(r);this.l00=this.l00.add(o.scale(.282095)),this.l1_1=this.l1_1.add(o.scale(.488603*t.y)),this.l10=this.l10.add(o.scale(.488603*t.z)),this.l11=this.l11.add(o.scale(.488603*t.x)),this.l2_2=this.l2_2.add(o.scale(1.092548*t.x*t.y)),this.l2_1=this.l2_1.add(o.scale(1.092548*t.y*t.z)),this.l21=this.l21.add(o.scale(1.092548*t.x*t.z)),this.l20=this.l20.add(o.scale(.315392*(3*t.z*t.z-1))),this.lL22=this.lL22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(e){this.l00=this.l00.scale(e),this.l1_1=this.l1_1.scale(e),this.l10=this.l10.scale(e),this.l11=this.l11.scale(e),this.l2_2=this.l2_2.scale(e),this.l2_1=this.l2_1.scale(e),this.l20=this.l20.scale(e),this.l21=this.l21.scale(e),this.lL22=this.lL22.scale(e)},t.prototype.convertIncidentRadianceToIrradiance=function(){this.l00=this.l00.scale(3.141593),this.l1_1=this.l1_1.scale(2.094395),this.l10=this.l10.scale(2.094395),this.l11=this.l11.scale(2.094395),this.l2_2=this.l2_2.scale(.785398),this.l2_1=this.l2_1.scale(.785398),this.l20=this.l20.scale(.785398),this.l21=this.l21.scale(.785398),this.lL22=this.lL22.scale(.785398)},t.prototype.convertIrradianceToLambertianRadiance=function(){this.scale(1/Math.PI)},t.FromPolynomial=function(e){var i=new t;return i.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),i.l1_1=e.y.scale(.977204),i.l10=e.z.scale(.977204),i.l11=e.x.scale(.977204),i.l2_2=e.xy.scale(1.16538),i.l2_1=e.yz.scale(1.16538),i.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),i.l21=e.zx.scale(1.16538),i.lL22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),i.scale(Math.PI),i},t.FromArray=function(i){var r=new t;return e.Vector3.FromArrayToRef(i[0],0,r.l00),e.Vector3.FromArrayToRef(i[1],0,r.l1_1),e.Vector3.FromArrayToRef(i[2],0,r.l10),e.Vector3.FromArrayToRef(i[3],0,r.l11),e.Vector3.FromArrayToRef(i[4],0,r.l2_2),e.Vector3.FromArrayToRef(i[5],0,r.l2_1),e.Vector3.FromArrayToRef(i[6],0,r.l20),e.Vector3.FromArrayToRef(i[7],0,r.l21),e.Vector3.FromArrayToRef(i[8],0,r.lL22),r},t})();e.SphericalHarmonics=i})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}return e})(),i=(function(){function i(){}return i.ConvertCubeMapTextureToSphericalPolynomial=function(t){if(!t.isCube)return null;var i,r,n=t.getSize().width,o=t.readPixels(0),s=t.readPixels(1);t.isRenderTarget?(i=t.readPixels(3),r=t.readPixels(2)):(i=t.readPixels(2),r=t.readPixels(3));var a=t.readPixels(4),l=t.readPixels(5),c=t.gammaSpace,h=e.Engine.TEXTUREFORMAT_RGBA,u=e.Engine.TEXTURETYPE_UNSIGNED_INT;t.textureType&&t.textureType!==e.Engine.TEXTURETYPE_UNSIGNED_INT&&(u=e.Engine.TEXTURETYPE_FLOAT);var d={size:n,right:o,left:s,up:i,down:r,front:a,back:l,format:h,type:u,gammaSpace:c};return this.ConvertCubeMapToSphericalPolynomial(d)},i.ConvertCubeMapToSphericalPolynomial=function(t){for(var i=new e.SphericalHarmonics,r=0,n=2/t.size,o=n,s=.5*n-1,a=0;a<6;a++)for(var l=this.FileFaces[a],c=t[l.name],h=s,u=t.format===e.Engine.TEXTUREFORMAT_RGBA?4:3,d=0;d0&&c.addCPUSkinningFallback(h++,t),i.MORPHTARGETS&&c.addFallback(h++,"MORPHTARGETS");var u=[e.VertexBuffer.PositionKind];i.NORMAL&&u.push(e.VertexBuffer.NormalKind),i.TANGENT&&u.push(e.VertexBuffer.TangentKind),i.UV1&&u.push(e.VertexBuffer.UVKind),i.UV2&&u.push(e.VertexBuffer.UV2Kind),i.VERTEXCOLOR&&u.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(u,t,i,c),e.MaterialHelper.PrepareAttributesForInstances(u,i),e.MaterialHelper.PrepareAttributesForMorphTargets(u,t,i);var d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vEmissiveColor","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","refractionMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX","vSphericalYY","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vReflectionMicrosurfaceInfos","vRefractionMicrosurfaceInfos","vTangentSpaceParams"],f=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","microSurfaceSampler","environmentBrdfSampler"],p=["Material","Scene"];e.ImageProcessingConfiguration&&(e.ImageProcessingConfiguration.PrepareUniforms(d,i),e.ImageProcessingConfiguration.PrepareSamplers(f,i)),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:i,maxSimultaneousLights:this._maxSimultaneousLights});var _=i.toString();return l.createEffect("pbr",{attributes:u,uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:_,fallbacks:c,onCompiled:r,onError:n,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:i.NUM_MORPH_INFLUENCERS}},l)},r.prototype._prepareDefines=function(t,i,r,n){void 0===r&&(r=null),void 0===n&&(n=null);var o=this.getScene(),s=o.getEngine();if(e.MaterialHelper.PrepareDefinesForLights(o,t,i,!0,this._maxSimultaneousLights,this._disableLighting),i._needNormals=!0,i.METALLICWORKFLOW=this.isMetallicWorkflow(),i._areTexturesDirty){if(i._needUVs=!1,o.texturesEnabled){o.getEngine().getCaps().textureLOD&&(i.LODBASEDMICROSFURACE=!0),this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled?e.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture,i,"ALBEDO"):i.ALBEDO=!1,this._ambientTexture&&e.StandardMaterial.AmbientTextureEnabled?(e.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture,i,"AMBIENT"),i.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):i.AMBIENT=!1,this._opacityTexture&&e.StandardMaterial.OpacityTextureEnabled?(e.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture,i,"OPACITY"),i.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):i.OPACITY=!1;var a=this._getReflectionTexture();if(a&&e.StandardMaterial.ReflectionTextureEnabled){switch(i.REFLECTION=!0,i.GAMMAREFLECTION=a.gammaSpace,i.RGBDREFLECTION=a.isRGBD,i.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!a.invertZ:a.invertZ,i.LODINREFLECTIONALPHA=a.lodLevelInAlpha,a.coordinatesMode===e.Texture.INVCUBIC_MODE&&(i.INVERTCUBICMAP=!0),i.REFLECTIONMAP_3D=a.isCube,a.coordinatesMode){case e.Texture.EXPLICIT_MODE:i.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:i.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:i.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:i.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:i.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:default:i.REFLECTIONMAP_CUBIC=!0,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!!a.boundingBoxSize}a.coordinatesMode!==e.Texture.SKYBOX_MODE&&a.sphericalPolynomial&&(i.USESPHERICALFROMREFLECTIONMAP=!0,this._forceIrradianceInFragment||o.getEngine().getCaps().maxVaryingVectors<=8?i.USESPHERICALINVERTEX=!1:i.USESPHERICALINVERTEX=!0)}else i.REFLECTION=!1,i.REFLECTIONMAP_3D=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_CUBIC=!1,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.INVERTCUBICMAP=!1,i.USESPHERICALFROMREFLECTIONMAP=!1,i.USESPHERICALINVERTEX=!1,i.REFLECTIONMAP_OPPOSITEZ=!1,i.LODINREFLECTIONALPHA=!1,i.GAMMAREFLECTION=!1,i.RGBDREFLECTION=!1;this._lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled?(e.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,i,"LIGHTMAP"),i.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,i.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace):i.LIGHTMAP=!1,this._emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled?e.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,i,"EMISSIVE"):i.EMISSIVE=!1,e.StandardMaterial.SpecularTextureEnabled?(this._metallicTexture?(e.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture,i,"REFLECTIVITY"),i.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,i.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,i.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,i.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed):this._reflectivityTexture?(e.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture,i,"REFLECTIVITY"),i.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,i.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap):i.REFLECTIVITY=!1,this._microSurfaceTexture?e.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture,i,"MICROSURFACEMAP"):i.MICROSURFACEMAP=!1):(i.REFLECTIVITY=!1,i.MICROSURFACEMAP=!1),o.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&e.StandardMaterial.BumpTextureEnabled&&!this._disableBumpMap?(e.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,i,"BUMP"),this._useParallax&&this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled?(i.PARALLAX=!0,i.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):i.PARALLAX=!1,i.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):i.BUMP=!1;var l=this._getRefractionTexture();l&&e.StandardMaterial.RefractionTextureEnabled?(i.REFRACTION=!0,i.REFRACTIONMAP_3D=l.isCube,i.GAMMAREFRACTION=l.gammaSpace,i.RGBDREFRACTION=l.isRGBD,i.REFRACTIONMAP_OPPOSITEZ=l.invertZ,i.LODINREFRACTIONALPHA=l.lodLevelInAlpha,this._linkRefractionWithTransparency&&(i.LINKREFRACTIONTOTRANSPARENCY=!0)):i.REFRACTION=!1,this._environmentBRDFTexture&&e.StandardMaterial.ReflectionTextureEnabled?i.ENVIRONMENTBRDF=!0:i.ENVIRONMENTBRDF=!1,this._shouldUseAlphaFromAlbedoTexture()?i.ALPHAFROMALBEDO=!0:i.ALPHAFROMALBEDO=!1}i.SPECULAROVERALPHA=this._useSpecularOverAlpha,i.USEPHYSICALLIGHTFALLOFF=this._usePhysicalLightFalloff,i.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?i.TWOSIDEDLIGHTING=!0:i.TWOSIDEDLIGHTING=!1,i.ALPHATESTVALUE=this._alphaCutOff+(this._alphaCutOff%1==0?".":""),i.PREMULTIPLYALPHA=this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED||this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF,i.ALPHABLEND=this.needAlphaBlendingForMesh(t),i.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,i.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel,i.SPECULARAA=o.getEngine().getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}i._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(i),i.FORCENORMALFORWARD=this._forceNormalForward,i.RADIANCEOCCLUSION=this._useRadianceOcclusion,i.HORIZONOCCLUSION=this._useHorizonOcclusion,i._areMiscDirty&&(e.MaterialHelper.PrepareDefinesForMisc(t,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(t)||this._forceAlphaTest,i),i.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!t.isVerticesDataPresent(e.VertexBuffer.NormalKind)),e.MaterialHelper.PrepareDefinesForFrameBoundValues(o,s,i,!!r,n),e.MaterialHelper.PrepareDefinesForAttributes(t,i,!0,!0,!0,this._transparencyMode!==e.PBRMaterial.PBRMATERIAL_OPAQUE)},r.prototype.forceCompilation=function(e,i,r){var n=this,o=s({clipPlane:!1},r),a=new t,l=this._prepareEffect(e,a,void 0,void 0,void 0,o.clipPlane);l.isReady()?i&&i(this):l.onCompileObservable.add((function(){i&&i(n)}))},r.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("vAlbedoInfos",2),this._uniformBuffer.addUniform("vAmbientInfos",3),this._uniformBuffer.addUniform("vOpacityInfos",2),this._uniformBuffer.addUniform("vEmissiveInfos",2),this._uniformBuffer.addUniform("vLightmapInfos",2),this._uniformBuffer.addUniform("vReflectivityInfos",3),this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos",2),this._uniformBuffer.addUniform("vRefractionInfos",4),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("vReflectionPosition",3),this._uniformBuffer.addUniform("vReflectionSize",3),this._uniformBuffer.addUniform("vBumpInfos",3),this._uniformBuffer.addUniform("albedoMatrix",16),this._uniformBuffer.addUniform("ambientMatrix",16),this._uniformBuffer.addUniform("opacityMatrix",16),this._uniformBuffer.addUniform("emissiveMatrix",16),this._uniformBuffer.addUniform("lightmapMatrix",16),this._uniformBuffer.addUniform("reflectivityMatrix",16),this._uniformBuffer.addUniform("microSurfaceSamplerMatrix",16),this._uniformBuffer.addUniform("bumpMatrix",16),this._uniformBuffer.addUniform("vTangentSpaceParams",2),this._uniformBuffer.addUniform("refractionMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionColor",3),this._uniformBuffer.addUniform("vAlbedoColor",4),this._uniformBuffer.addUniform("vLightingIntensity",4),this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("vReflectivityColor",4),this._uniformBuffer.addUniform("vEmissiveColor",3),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.create()},r.prototype.unbind=function(){this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._uniformBuffer.setTexture("refractionSampler",null),i.prototype.unbind.call(this)},r.prototype.bindForSubMesh=function(t,i,r){var n=this.getScene(),o=r._materialDefines;if(o){var s=r.effect;if(s){this._activeEffect=s,this.bindOnlyWorldMatrix(t),o.OBJECTSPACE_NORMALMAP&&(t.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var a=this._mustRebind(n,s,i.visibility);e.MaterialHelper.BindBonesParameters(i,this._activeEffect);var l=null;if(a){this._uniformBuffer.bindToEffect(s,"Material"),this.bindViewProjection(s),l=this._getReflectionTexture();var c=this._getRefractionTexture();if(!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync){if(n.texturesEnabled){if(this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),e.MaterialHelper.BindTextureMatrix(this._albedoTexture,this._uniformBuffer,"albedo")),this._ambientTexture&&e.StandardMaterial.AmbientTextureEnabled&&(this._uniformBuffer.updateFloat3("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength),e.MaterialHelper.BindTextureMatrix(this._ambientTexture,this._uniformBuffer,"ambient")),this._opacityTexture&&e.StandardMaterial.OpacityTextureEnabled&&(this._uniformBuffer.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),e.MaterialHelper.BindTextureMatrix(this._opacityTexture,this._uniformBuffer,"opacity")),l&&e.StandardMaterial.ReflectionTextureEnabled){if(this._uniformBuffer.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){var h=l;this._uniformBuffer.updateVector3("vReflectionPosition",h.boundingBoxPosition),this._uniformBuffer.updateVector3("vReflectionSize",h.boundingBoxSize)}var u=l.sphericalPolynomial;o.USESPHERICALFROMREFLECTIONMAP&&u&&(this._activeEffect.setFloat3("vSphericalX",u.x.x,u.x.y,u.x.z),this._activeEffect.setFloat3("vSphericalY",u.y.x,u.y.y,u.y.z),this._activeEffect.setFloat3("vSphericalZ",u.z.x,u.z.y,u.z.z),this._activeEffect.setFloat3("vSphericalXX_ZZ",u.xx.x-u.zz.x,u.xx.y-u.zz.y,u.xx.z-u.zz.z),this._activeEffect.setFloat3("vSphericalYY_ZZ",u.yy.x-u.zz.x,u.yy.y-u.zz.y,u.yy.z-u.zz.z),this._activeEffect.setFloat3("vSphericalZZ",u.zz.x,u.zz.y,u.zz.z),this._activeEffect.setFloat3("vSphericalXY",u.xy.x,u.xy.y,u.xy.z),this._activeEffect.setFloat3("vSphericalYZ",u.yz.x,u.yz.y,u.yz.z),this._activeEffect.setFloat3("vSphericalZX",u.zx.x,u.zx.y,u.zx.z)),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}if(this._emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled&&(this._uniformBuffer.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),e.MaterialHelper.BindTextureMatrix(this._emissiveTexture,this._uniformBuffer,"emissive")),this._lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled&&(this._uniformBuffer.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),e.MaterialHelper.BindTextureMatrix(this._lightmapTexture,this._uniformBuffer,"lightmap")),e.StandardMaterial.SpecularTextureEnabled&&(this._metallicTexture?(this._uniformBuffer.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),e.MaterialHelper.BindTextureMatrix(this._metallicTexture,this._uniformBuffer,"reflectivity")):this._reflectivityTexture&&(this._uniformBuffer.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),e.MaterialHelper.BindTextureMatrix(this._reflectivityTexture,this._uniformBuffer,"reflectivity")),this._microSurfaceTexture&&(this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),e.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture,this._uniformBuffer,"microSurfaceSampler"))),this._bumpTexture&&n.getEngine().getCaps().standardDerivatives&&e.StandardMaterial.BumpTextureEnabled&&!this._disableBumpMap&&(this._uniformBuffer.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),e.MaterialHelper.BindTextureMatrix(this._bumpTexture,this._uniformBuffer,"bump"),n._mirroredCameraPosition?this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),c&&e.StandardMaterial.RefractionTextureEnabled){this._uniformBuffer.updateMatrix("refractionMatrix",c.getReflectionTextureMatrix());var d=1;c.isCube||c.depth&&(d=c.depth),this._uniformBuffer.updateFloat4("vRefractionInfos",c.level,this._indexOfRefraction,d,this._invertRefractionY?-1:1),this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos",c.getSize().width,c.lodGenerationScale,c.lodGenerationOffset)}}this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),o.METALLICWORKFLOW?(e.PBRMaterial._scaledReflectivity.r=void 0===this._metallic||null===this._metallic?1:this._metallic,e.PBRMaterial._scaledReflectivity.g=void 0===this._roughness||null===this._roughness?1:this._roughness,this._uniformBuffer.updateColor4("vReflectivityColor",e.PBRMaterial._scaledReflectivity,0)):this._uniformBuffer.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface),this._uniformBuffer.updateColor3("vEmissiveColor",this._emissiveColor),this._uniformBuffer.updateColor3("vReflectionColor",this._reflectionColor),this._uniformBuffer.updateColor4("vAlbedoColor",this._albedoColor,this.alpha*i.visibility),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity,this._lightingInfos.w=this._specularIntensity,this._uniformBuffer.updateVector4("vLightingIntensity",this._lightingInfos)}n.texturesEnabled&&(this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&e.StandardMaterial.AmbientTextureEnabled&&this._uniformBuffer.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&e.StandardMaterial.OpacityTextureEnabled&&this._uniformBuffer.setTexture("opacitySampler",this._opacityTexture),l&&e.StandardMaterial.ReflectionTextureEnabled&&(o.LODBASEDMICROSFURACE?this._uniformBuffer.setTexture("reflectionSampler",l):(this._uniformBuffer.setTexture("reflectionSampler",l._lodTextureMid||l),this._uniformBuffer.setTexture("reflectionSamplerLow",l._lodTextureLow||l),this._uniformBuffer.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l))),o.ENVIRONMENTBRDF&&this._uniformBuffer.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),c&&e.StandardMaterial.RefractionTextureEnabled&&(o.LODBASEDMICROSFURACE?this._uniformBuffer.setTexture("refractionSampler",c):(this._uniformBuffer.setTexture("refractionSampler",c._lodTextureMid||c),this._uniformBuffer.setTexture("refractionSamplerLow",c._lodTextureLow||c),this._uniformBuffer.setTexture("refractionSamplerHigh",c._lodTextureHigh||c))),this._emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled&&this._uniformBuffer.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled&&this._uniformBuffer.setTexture("lightmapSampler",this._lightmapTexture),e.StandardMaterial.SpecularTextureEnabled&&(this._metallicTexture?this._uniformBuffer.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&this._uniformBuffer.setTexture("reflectivitySampler",this._reflectivityTexture),this._microSurfaceTexture&&this._uniformBuffer.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&n.getEngine().getCaps().standardDerivatives&&e.StandardMaterial.BumpTextureEnabled&&!this._disableBumpMap&&this._uniformBuffer.setTexture("bumpSampler",this._bumpTexture)),e.MaterialHelper.BindClipPlane(this._activeEffect,n),n.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor);var f=n._forcedViewPosition?n._forcedViewPosition:n._mirroredCameraPosition?n._mirroredCameraPosition:n.activeCamera.globalPosition,p=n.useRightHandedSystem===(null!=n._mirroredCameraPosition);s.setFloat4("vEyePosition",f.x,f.y,f.z,p?-1:1),s.setColor3("vAmbientColor",this._globalAmbientColor)}!a&&this.isFrozen||(n.lightsEnabled&&!this._disableLighting&&e.MaterialHelper.BindLights(n,i,this._activeEffect,o,this._maxSimultaneousLights,this._usePhysicalLightFalloff),(n.fogEnabled&&i.applyFog&&n.fogMode!==e.Scene.FOGMODE_NONE||l)&&this.bindView(s),e.MaterialHelper.BindFogParameters(n,i,this._activeEffect),o.NUM_MORPH_INFLUENCERS&&e.MaterialHelper.BindMorphTargetParameters(i,this._activeEffect),this._imageProcessingConfiguration.bind(this._activeEffect),e.MaterialHelper.BindLogDepth(o,this._activeEffect,n)),this._uniformBuffer.update(),this._afterBind(i,this._activeEffect)}}},r.prototype.getAnimatables=function(){var e=[];return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e},r.prototype._getReflectionTexture=function(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture},r.prototype._getRefractionTexture=function(){return this._refractionTexture?this._refractionTexture:this._linkRefractionWithTransparency?this.getScene().environmentTexture:null},r.prototype.dispose=function(e,t){t&&(this._albedoTexture&&this._albedoTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._environmentBRDFTexture&&this.getScene()._environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._metallicTexture&&this._metallicTexture.dispose(),this._reflectivityTexture&&this._reflectivityTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),i.prototype.dispose.call(this,e,t)},r._scaledReflectivity=new e.Color3,n([e.serializeAsImageProcessingConfiguration()],r.prototype,"_imageProcessingConfiguration",void 0),n([e.serialize()],r.prototype,"useLogarithmicDepth",null),n([e.serialize()],r.prototype,"transparencyMode",null),r})(e.PushMaterial);e.PBRBaseMaterial=i})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r){var n=t.call(this,i,r)||this;return n.maxSimultaneousLights=4,n.disableLighting=!1,n.invertNormalMapX=!1,n.invertNormalMapY=!1,n.emissiveColor=new e.Color3(0,0,0),n.occlusionStrength=1,n.useLightmapAsShadowmap=!1,n._useAlphaFromAlbedoTexture=!0,n._useAmbientInGrayScale=!0,n}return o(i,t),Object.defineProperty(i.prototype,"doubleSided",{get:function(){return this._twoSidedLighting}, +set:function(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())},enumerable:!0,configurable:!0}),i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this.environmentTexture&&e.push(this.environmentTexture),this.normalTexture&&e.push(this.normalTexture),this.emissiveTexture&&e.push(this.emissiveTexture),this.occlusionTexture&&e.push(this.occlusionTexture),this.lightmapTexture&&e.push(this.lightmapTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this.lightmapTexture===e},i.prototype.getClassName=function(){return"PBRBaseSimpleMaterial"},n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"maxSimultaneousLights",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"disableLighting",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],i.prototype,"environmentTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapX",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapY",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],i.prototype,"normalTexture",void 0),n([e.serializeAsColor3("emissive"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveColor",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],i.prototype,"occlusionStrength",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],i.prototype,"occlusionTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],i.prototype,"alphaCutOff",void 0),n([e.serialize()],i.prototype,"doubleSided",null),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty",null)],i.prototype,"lightmapTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLightmapAsShadowmap",void 0),i})(e.PBRBaseMaterial);e.PBRBaseSimpleMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r){var n=t.call(this,i,r)||this;return n.directIntensity=1,n.emissiveIntensity=1,n.environmentIntensity=1,n.specularIntensity=1,n.disableBumpMap=!1,n.ambientTextureStrength=1,n.ambientColor=new e.Color3(0,0,0),n.albedoColor=new e.Color3(1,1,1),n.reflectivityColor=new e.Color3(1,1,1),n.reflectionColor=new e.Color3(1,1,1),n.emissiveColor=new e.Color3(0,0,0),n.microSurface=1,n.indexOfRefraction=.66,n.invertRefractionY=!1,n.linkRefractionWithTransparency=!1,n.useLightmapAsShadowmap=!1,n.useAlphaFromAlbedoTexture=!1,n.forceAlphaTest=!1,n.alphaCutOff=.4,n.useSpecularOverAlpha=!0,n.useMicroSurfaceFromReflectivityMapAlpha=!1,n.useRoughnessFromMetallicTextureAlpha=!0,n.useRoughnessFromMetallicTextureGreen=!1,n.useMetallnessFromMetallicTextureBlue=!1,n.useAmbientOcclusionFromMetallicTextureRed=!1,n.useAmbientInGrayScale=!1,n.useAutoMicroSurfaceFromReflectivityMap=!1,n.usePhysicalLightFalloff=!0,n.useRadianceOverAlpha=!0,n.useObjectSpaceNormalMap=!1,n.useParallax=!1,n.useParallaxOcclusion=!1,n.parallaxScaleBias=.05,n.disableLighting=!1,n.forceIrradianceInFragment=!1,n.maxSimultaneousLights=4,n.invertNormalMapX=!1,n.invertNormalMapY=!1,n.twoSidedLighting=!1,n.useAlphaFresnel=!1,n.useLinearAlphaFresnel=!1,n.environmentBRDFTexture=null,n.forceNormalForward=!1,n.enableSpecularAntiAliasing=!1,n.useHorizonOcclusion=!0,n.useRadianceOcclusion=!0,n.unlit=!1,n._environmentBRDFTexture=e.TextureTools.GetEnvironmentBRDFTexture(r),n}return o(i,t),Object.defineProperty(i,"PBRMATERIAL_OPAQUE",{get:function(){return this._PBRMATERIAL_OPAQUE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"PBRMATERIAL_ALPHATEST",{get:function(){return this._PBRMATERIAL_ALPHATEST},enumerable:!0,configurable:!0}),Object.defineProperty(i,"PBRMATERIAL_ALPHABLEND",{get:function(){return this._PBRMATERIAL_ALPHABLEND},enumerable:!0,configurable:!0}),Object.defineProperty(i,"PBRMATERIAL_ALPHATESTANDBLEND",{get:function(){return this._PBRMATERIAL_ALPHATESTANDBLEND},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurves",{get:function(){return this._imageProcessingConfiguration.colorCurves},set:function(e){this._imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"PBRMaterial"},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this._albedoTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._reflectivityTexture===e||(this._metallicTexture===e||(this._microSurfaceTexture===e||(this._bumpTexture===e||(this._lightmapTexture===e||this._refractionTexture===e)))))))))},i.prototype.clone=function(t){var r=this,n=e.SerializationHelper.Clone((function(){return new i(t,r.getScene())}),this);return n.id=t,n.name=t,n},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRMaterial",t},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,r)}),t,r,n)},i._PBRMATERIAL_OPAQUE=0,i._PBRMATERIAL_ALPHATEST=1,i._PBRMATERIAL_ALPHABLEND=2,i._PBRMATERIAL_ALPHATESTANDBLEND=3,n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"directIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"environmentIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"specularIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"disableBumpMap",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"albedoTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientTextureStrength",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"opacityTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectivityTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallicTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallic",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"roughness",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"microSurfaceTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"bumpTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty",null)],i.prototype,"lightmapTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"refractionTexture",void 0),n([e.serializeAsColor3("ambient"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientColor",void 0),n([e.serializeAsColor3("albedo"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"albedoColor",void 0),n([e.serializeAsColor3("reflectivity"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectivityColor",void 0),n([e.serializeAsColor3("reflection"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionColor",void 0),n([e.serializeAsColor3("emissive"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveColor",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"microSurface",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"indexOfRefraction",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertRefractionY",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"linkRefractionWithTransparency",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLightmapAsShadowmap",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"useAlphaFromAlbedoTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"forceAlphaTest",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"alphaCutOff",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useSpecularOverAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRoughnessFromMetallicTextureGreen",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useMetallnessFromMetallicTextureBlue",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAmbientInGrayScale",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"usePhysicalLightFalloff",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRadianceOverAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useObjectSpaceNormalMap",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useParallax",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useParallaxOcclusion",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"parallaxScaleBias",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"disableLighting",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"forceIrradianceInFragment",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"maxSimultaneousLights",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapX",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapY",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"twoSidedLighting",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAlphaFresnel",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLinearAlphaFresnel",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"environmentBRDFTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"forceNormalForward",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"enableSpecularAntiAliasing",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useHorizonOcclusion",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRadianceOcclusion",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsMiscDirty")],i.prototype,"unlit",void 0),i})(e.PBRBaseMaterial);e.PBRMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i){var r=t.call(this,e,i)||this;return r._useRoughnessFromMetallicTextureAlpha=!1,r._useRoughnessFromMetallicTextureGreen=!0,r._useMetallnessFromMetallicTextureBlue=!0,r.metallic=1,r.roughness=1,r}return o(i,t),i.prototype.getClassName=function(){return"PBRMetallicRoughnessMaterial"},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this.baseTexture&&e.push(this.baseTexture),this.metallicRoughnessTexture&&e.push(this.metallicRoughnessTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this.baseTexture===e||this.metallicRoughnessTexture===e)},i.prototype.clone=function(t){var r=this,n=e.SerializationHelper.Clone((function(){return new i(t,r.getScene())}),this);return n.id=t,n.name=t,n},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRMetallicRoughnessMaterial",t},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,r)}),t,r,n)},n([e.serializeAsColor3(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoColor")],i.prototype,"baseColor",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],i.prototype,"baseTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallic",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"roughness",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],i.prototype,"metallicRoughnessTexture",void 0),i})(e.PBRBaseSimpleMaterial);e.PBRMetallicRoughnessMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i){var r=t.call(this,e,i)||this;return r._useMicroSurfaceFromReflectivityMapAlpha=!0,r}return o(i,t),i.prototype.getClassName=function(){return"PBRSpecularGlossinessMaterial"},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this.diffuseTexture&&e.push(this.diffuseTexture),this.specularGlossinessTexture&&e.push(this.specularGlossinessTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this.diffuseTexture===e||this.specularGlossinessTexture===e)},i.prototype.clone=function(t){var r=this,n=e.SerializationHelper.Clone((function(){return new i(t,r.getScene())}),this);return n.id=t,n.name=t,n},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRSpecularGlossinessMaterial",t},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,r)}),t,r,n)},n([e.serializeAsColor3("diffuse"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoColor")],i.prototype,"diffuseColor",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],i.prototype,"diffuseTexture",void 0),n([e.serializeAsColor3("specular"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],i.prototype,"specularColor",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_microSurface")],i.prototype,"glossiness",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],i.prototype,"specularGlossinessTexture",void 0),i})(e.PBRBaseSimpleMaterial);e.PBRSpecularGlossinessMaterial=t})(r||(r={}));var r;!(function(e){e.CameraInputTypes={};var t=(function(){function t(e){this.attached={},this.camera=e,this.checkInputs=function(){}}return t.prototype.add=function(t){var i=t.getSimpleName();if(this.attached[i])return void e.Tools.Warn("camera input of type "+i+" already exists on camera");this.attached[i]=t,t.camera=this.camera,t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t))),this.attachedElement&&t.attachControl(this.attachedElement)},t.prototype.remove=function(e){for(var t in this.attached){var i=this.attached[t];i===e&&(i.detachControl(this.attachedElement),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}},t.prototype.removeByType=function(e){for(var t in this.attached){var i=this.attached[t];i.getClassName()===e&&(i.detachControl(this.attachedElement),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}},t.prototype._addCheckInputs=function(e){var t=this.checkInputs;return function(){t(),e()}},t.prototype.attachInput=function(e){this.attachedElement&&e.attachControl(this.attachedElement,this.noPreventDefault)},t.prototype.attachElement=function(t,i){if(void 0===i&&(i=!1),!this.attachedElement){i=!e.Camera.ForceAttachControlToAlwaysPreventDefault&&i,this.attachedElement=t,this.noPreventDefault=i;for(var r in this.attached)this.attached[r].attachControl(t,i)}},t.prototype.detachElement=function(e,t){if(void 0===t&&(t=!1),this.attachedElement===e){for(var i in this.attached)this.attached[i].detachControl(e),t&&(this.attached[i].camera=null);this.attachedElement=null}},t.prototype.rebuildInputCheck=function(){this.checkInputs=function(){};for(var e in this.attached){var t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}},t.prototype.clear=function(){this.attachedElement&&this.detachElement(this.attachedElement,!0),this.attached={},this.attachedElement=null,this.checkInputs=function(){}},t.prototype.serialize=function(t){var i={};for(var r in this.attached){var n=this.attached[r],o=e.SerializationHelper.Serialize(n);i[n.getClassName()]=o}t.inputsmgr=i},t.prototype.parse=function(t){var i=t.inputsmgr;if(i){this.clear();for(var r in i){var n=e.CameraInputTypes[r];if(n){var o=i[r],s=e.SerializationHelper.Parse((function(){return new n}),o,null);this.add(s)}}}else for(var r in this.attached){var n=e.CameraInputTypes[this.attached[r].getClassName()];if(n){var s=e.SerializationHelper.Parse((function(){return new n}),t,null);this.remove(this.attached[r]),this.add(s)}}},t})();e.CameraInputsManager=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o){void 0===o&&(o=!0);var s=t.call(this,i,r,n,o)||this;return s.cameraDirection=new e.Vector3(0,0,0),s.cameraRotation=new e.Vector2(0,0),s.rotation=new e.Vector3(0,0,0),s.speed=2,s.noRotationConstraint=!1,s.lockedTarget=null,s._currentTarget=e.Vector3.Zero(),s._viewMatrix=e.Matrix.Zero(),s._camMatrix=e.Matrix.Zero(),s._cameraTransformMatrix=e.Matrix.Zero(),s._cameraRotationMatrix=e.Matrix.Zero(),s._referencePoint=new e.Vector3(0,0,1),s._currentUpVector=new e.Vector3(0,1,0),s._transformedReferencePoint=e.Vector3.Zero(),s._globalCurrentTarget=e.Vector3.Zero(),s._globalCurrentUpVector=e.Vector3.Zero(),s}return o(i,t),i.prototype.getFrontPosition=function(e){this.getWorldMatrix();var t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)},i.prototype._getLockedTargetPosition=function(){return this.lockedTarget?(this.lockedTarget.absolutePosition&&this.lockedTarget.computeWorldMatrix(),this.lockedTarget.absolutePosition||this.lockedTarget):null},i.prototype.storeState=function(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),t.prototype.storeState.call(this)},i.prototype._restoreStateValues=function(){return!!t.prototype._restoreStateValues.call(this)&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.lockedTarget=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new e.Quaternion(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this);var i=this._getLockedTargetPosition();i?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(i):this._cache.lockedTarget=i.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)},i.prototype._isSynchronizedViewMatrix=function(){if(!t.prototype._isSynchronizedViewMatrix.call(this))return!1;var e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))},i.prototype._computeLocalCameraSpeed=function(){var e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))},i.prototype.setTarget=function(t){this.upVector.normalize(),e.Matrix.LookAtLHToRef(this.position,t,this.upVector,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);var i=t.subtract(this.position);i.x>=0?this.rotation.y=-Math.atan(i.z/i.x)+Math.PI/2:this.rotation.y=-Math.atan(i.z/i.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)},i.prototype.getTarget=function(){return this._currentTarget},i.prototype._decideIfNeedsToMove=function(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(e.Tmp.Matrix[0]),e.Vector3.TransformNormalToRef(this.cameraDirection,e.Tmp.Matrix[0],e.Tmp.Vector3[0]),void this.position.addInPlace(e.Tmp.Vector3[0]);this.position.addInPlace(this.cameraDirection)},i.prototype._checkInputs=function(){var i=this._decideIfNeedsToMove(),r=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(i&&this._updatePosition(),r){if(this.rotation.x+=this.cameraRotation.x,this.rotation.y+=this.cameraRotation.y,this.rotationQuaternion){this.rotation.lengthSquared()&&e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}if(!this.noRotationConstraint){var n=Math.PI/2*.95;this.rotation.x>n&&(this.rotation.x=n),this.rotation.x<-n&&(this.rotation.x=-n)}}i&&(Math.abs(this.cameraDirection.x)=0&&r._keys.splice(o,1),i||n.preventDefault()}})))},t.prototype.detachControl=function(e){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys=[]},t.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var t=this.camera,i=0;ie.Engine.CollisionsEpsilon&&(s.position.addInPlace(s._diffPosition),s.onCollide&&r&&s.onCollide(r))})(i)},s.inputs=new e.FreeCameraInputsManager(s),s.inputs.addKeyboard().addMouse(),s}return o(i,t),Object.defineProperty(i.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;return e?e.angularSensibility:0},set:function(e){var t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),i.prototype.attachControl=function(e,t){this.inputs.attachElement(e,t)},i.prototype.detachControl=function(t){this.inputs.detachElement(t),this.cameraDirection=new e.Vector3(0,0,0),this.cameraRotation=new e.Vector2(0,0)},Object.defineProperty(i.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),i.prototype._collideWithWorld=function(t){var i;i=this.parent?e.Vector3.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,i.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset),this._collider||(this._collider=new e.Collider),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;var r=t;this.applyGravity&&(r=t.add(this.getScene().gravity)),this.getScene().collisionCoordinator.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},i.prototype._checkInputs=function(){this._localDirection||(this._localDirection=e.Vector3.Zero(),this._transformedDirection=e.Vector3.Zero()),this.inputs.checkInputs(),t.prototype._checkInputs.call(this)},i.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):t.prototype._updatePosition.call(this)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getClassName=function(){return"FreeCamera"},n([e.serializeAsVector3()],i.prototype,"ellipsoid",void 0),n([e.serializeAsVector3()],i.prototype,"ellipsoidOffset",void 0),n([e.serialize()],i.prototype,"checkCollisions",void 0),n([e.serialize()],i.prototype,"applyGravity",void 0),i})(e.TargetCamera);e.FreeCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._keys=new Array,this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0}return t.prototype.attachControl=function(t,i){var r=this;this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((function(){r._keys=[]})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((function(t){var n=t.event;if(t.type===e.KeyboardEventTypes.KEYDOWN){if(r._ctrlPressed=n.ctrlKey,r._altPressed=n.altKey,-1!==r.keysUp.indexOf(n.keyCode)||-1!==r.keysDown.indexOf(n.keyCode)||-1!==r.keysLeft.indexOf(n.keyCode)||-1!==r.keysRight.indexOf(n.keyCode)||-1!==r.keysReset.indexOf(n.keyCode)){var o=r._keys.indexOf(n.keyCode);-1===o&&r._keys.push(n.keyCode),n.preventDefault&&(i||n.preventDefault())}}else if(-1!==r.keysUp.indexOf(n.keyCode)||-1!==r.keysDown.indexOf(n.keyCode)||-1!==r.keysLeft.indexOf(n.keyCode)||-1!==r.keysRight.indexOf(n.keyCode)||-1!==r.keysReset.indexOf(n.keyCode)){var o=r._keys.indexOf(n.keyCode);o>=0&&r._keys.splice(o,1),n.preventDefault&&(i||n.preventDefault())}})))},t.prototype.detachControl=function(e){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys=[]},t.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var e=this.camera,t=0;t0?a/(1+r.wheelDeltaPercentage):a*(1+r.wheelDeltaPercentage)}else s=o.wheelDelta/(40*r.wheelPrecision);else o.detail&&(s=-o.detail/r.wheelPrecision);s&&(r.camera.inertialRadiusOffset+=s),o.preventDefault&&(i||o.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,e.PointerEventTypes.POINTERWHEEL)},t.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},t.prototype.getClassName=function(){return"ArcRotateCameraMouseWheelInput"},t.prototype.getSimpleName=function(){return"mousewheel"},n([e.serialize()],t.prototype,"wheelPrecision",void 0),n([e.serialize()],t.prototype,"wheelDeltaPercentage",void 0),t})();e.ArcRotateCameraMouseWheelInput=t,e.CameraInputTypes.ArcRotateCameraMouseWheelInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this._isPanClick=!1,this.pinchInwards=!0}return t.prototype.attachControl=function(t,i){var r,n=this,o=this.camera.getEngine(),s=null,a=null,l=0,c=0,h=0,u={x:0,y:0,isPaning:!1,isPinching:!1};this._pointerInput=function(d,f){var p=d.event,_="touch"===d.event.pointerType;if(!o.isInVRExclusivePointerMode&&(d.type===e.PointerEventTypes.POINTERMOVE||-1!==n.buttons.indexOf(p.button))){var m=p.srcElement||p.target;if(d.type===e.PointerEventTypes.POINTERDOWN&&m){try{m.setPointerCapture(p.pointerId)}catch(e){}n._isPanClick=p.button===n.camera._panningMouseButton,r={x:p.clientX,y:p.clientY,pointerId:p.pointerId,type:p.pointerType},null===s?s=r:null===a&&(a=r),i||(p.preventDefault(),t.focus())}else if(d.type===e.PointerEventTypes.POINTERDOUBLETAP)n.camera.restoreState();else if(d.type===e.PointerEventTypes.POINTERUP&&m){try{m.releasePointerCapture(p.pointerId)}catch(e){}r=null,l=0,u.isPaning=!1,u.isPinching=!1,h=0,c=0,_||(a=null),o._badOS?s=a=null:a&&s&&s.pointerId==p.pointerId?(s=a,a=null,r={x:s.x,y:s.y,pointerId:s.pointerId,type:p.pointerType}):s&&a&&a.pointerId==p.pointerId?(a=null,r={x:s.x,y:s.y,pointerId:s.pointerId,type:p.pointerType}):s=a=null,i||p.preventDefault()}else if(d.type===e.PointerEventTypes.POINTERMOVE)if(i||p.preventDefault(),s&&null===a&&r){if(0!==n.panningSensibility&&(p.ctrlKey&&n.camera._useCtrlForPanning||n._isPanClick))n.camera.inertialPanningX+=-(p.clientX-r.x)/n.panningSensibility,n.camera.inertialPanningY+=(p.clientY-r.y)/n.panningSensibility;else{var g=p.clientX-r.x,v=p.clientY-r.y;n.camera.inertialAlphaOffset-=g/n.angularSensibilityX,n.camera.inertialBetaOffset-=v/n.angularSensibilityY}r.x=p.clientX,r.y=p.clientY}else if(s&&a){var y=s.pointerId===p.pointerId?s:a;y.x=p.clientX,y.y=p.clientY;var b=n.pinchInwards?1:-1,x=s.x-a.x,T=s.y-a.y,E=x*x+T*T,P=Math.sqrt(E);if(0===l)return c=P,l=E,u.x=(s.x+a.x)/2,void(u.y=(s.y+a.y)/2);if(n.multiTouchPanAndZoom){if(n.pinchDeltaPercentage?n.camera.inertialRadiusOffset+=.001*(E-l)*n.camera.radius*n.pinchDeltaPercentage:n.camera.inertialRadiusOffset+=(E-l)/(n.pinchPrecision*((n.angularSensibilityX+n.angularSensibilityY)/2)*b),0!==n.panningSensibility){var A=(s.x+a.x)/2,M=(s.y+a.y)/2,S=A-u.x,C=M-u.y;u.x=A,u.y=M,n.camera.inertialPanningX+=-S/n.panningSensibility,n.camera.inertialPanningY+=C/n.panningSensibility}}else{if(h++,u.isPinching||h<20&&Math.abs(P-c)>n.camera.pinchToPanMaxDistance)n.pinchDeltaPercentage?n.camera.inertialRadiusOffset+=.001*(E-l)*n.camera.radius*n.pinchDeltaPercentage:n.camera.inertialRadiusOffset+=(E-l)/(n.pinchPrecision*((n.angularSensibilityX+n.angularSensibilityY)/2)*b),u.isPaning=!1,u.isPinching=!0;else if(r&&r.pointerId===y.pointerId&&0!==n.panningSensibility&&n.multiTouchPanning){if(!u.isPaning)return u.isPaning=!0,u.isPinching=!1,u.x=y.x,void(u.y=y.y);n.camera.inertialPanningX+=-(y.x-u.x)/n.panningSensibility,n.camera.inertialPanningY+=(y.y-u.y)/n.panningSensibility}r&&r.pointerId===p.pointerId&&(u.x=y.x,u.y=y.y)}l=E}}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE|e.PointerEventTypes._POINTERDOUBLETAP),this._onContextMenu=function(e){e.preventDefault()},this.camera._useCtrlForPanning||t.addEventListener("contextmenu",this._onContextMenu,!1),this._onLostFocus=function(){s=a=null,l=0,u.isPaning=!1,u.isPinching=!1,h=0,r=null,c=0},this._onMouseMove=function(e){if(o.isPointerLock){var t=e.movementX||e.mozMovementX||e.webkitMovementX||e.msMovementX||0,r=e.movementY||e.mozMovementY||e.webkitMovementY||e.msMovementY||0;n.camera.inertialAlphaOffset-=t/n.angularSensibilityX,n.camera.inertialBetaOffset-=r/n.angularSensibilityY,i||e.preventDefault()}},this._onGestureStart=function(e){void 0!==window.MSGesture&&(n._MSGestureHandler||(n._MSGestureHandler=new MSGesture,n._MSGestureHandler.target=t),n._MSGestureHandler.addPointer(e.pointerId))},this._onGesture=function(e){n.camera.radius*=e.scale,e.preventDefault&&(i||(e.stopPropagation(),e.preventDefault()))},t.addEventListener("mousemove",this._onMouseMove,!1),t.addEventListener("MSPointerDown",this._onGestureStart,!1),t.addEventListener("MSGestureChange",this._onGesture,!1),e.Tools.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},t.prototype.detachControl=function(t){this._onLostFocus&&e.Tools.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]),t&&this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._onContextMenu&&t.removeEventListener("contextmenu",this._onContextMenu),this._onMouseMove&&t.removeEventListener("mousemove",this._onMouseMove),this._onGestureStart&&t.removeEventListener("MSPointerDown",this._onGestureStart),this._onGesture&&t.removeEventListener("MSGestureChange",this._onGesture),this._isPanClick=!1,this.pinchInwards=!0,this._onMouseMove=null,this._onGestureStart=null,this._onGesture=null,this._MSGestureHandler=null,this._onLostFocus=null,this._onContextMenu=null)},t.prototype.getClassName=function(){return"ArcRotateCameraPointersInput"},t.prototype.getSimpleName=function(){return"pointers"},n([e.serialize()],t.prototype,"buttons",void 0),n([e.serialize()],t.prototype,"angularSensibilityX",void 0),n([e.serialize()],t.prototype,"angularSensibilityY",void 0),n([e.serialize()],t.prototype,"pinchPrecision",void 0),n([e.serialize()],t.prototype,"pinchDeltaPercentage",void 0),n([e.serialize()],t.prototype,"panningSensibility",void 0),n([e.serialize()],t.prototype,"multiTouchPanning",void 0),n([e.serialize()],t.prototype,"multiTouchPanAndZoom",void 0),t})();e.ArcRotateCameraPointersInput=t,e.CameraInputTypes.ArcRotateCameraPointersInput=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e){return t.call(this,e)||this}return o(i,t),i.prototype.addMouseWheel=function(){return this.add(new e.ArcRotateCameraMouseWheelInput),this},i.prototype.addPointers=function(){return this.add(new e.ArcRotateCameraPointersInput),this},i.prototype.addKeyboard=function(){return this.add(new e.ArcRotateCameraKeyboardMoveInput),this},i.prototype.addVRDeviceOrientation=function(){return this.add(new e.ArcRotateCameraVRDeviceOrientationInput),this},i})(e.CameraInputsManager);e.ArcRotateCameraInputsManager=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("ArcRotateCamera",(function(i,r){return function(){return new t(i,0,0,1,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s,a,l){void 0===l&&(l=!0);var c=t.call(this,i,e.Vector3.Zero(),a,l)||this;return c.inertialAlphaOffset=0,c.inertialBetaOffset=0,c.inertialRadiusOffset=0,c.lowerAlphaLimit=null,c.upperAlphaLimit=null,c.lowerBetaLimit=.01,c.upperBetaLimit=Math.PI,c.lowerRadiusLimit=null,c.upperRadiusLimit=null,c.inertialPanningX=0,c.inertialPanningY=0,c.pinchToPanMaxDistance=20,c.panningDistanceLimit=null,c.panningOriginTarget=e.Vector3.Zero(),c.panningInertia=.9,c.zoomOnFactor=1,c.targetScreenOffset=e.Vector2.Zero(),c.allowUpsideDown=!0,c._viewMatrix=new e.Matrix,c.panningAxis=new e.Vector3(1,1,0),c.onMeshTargetChangedObservable=new e.Observable,c.checkCollisions=!1,c.collisionRadius=new e.Vector3(.5,.5,.5),c._previousPosition=e.Vector3.Zero(),c._collisionVelocity=e.Vector3.Zero(),c._newPosition=e.Vector3.Zero(),c._computationVector=e.Vector3.Zero(),c._onCollisionPositionChange=function(e,t,i){void 0===i&&(i=null),c.getScene().workerCollisions&&c.checkCollisions&&t.multiplyInPlace(c._collider._radius),i?(c.setPosition(t),c.onCollide&&c.onCollide(i)):c._previousPosition.copyFrom(c.position);var r=Math.cos(c.alpha),n=Math.sin(c.alpha),o=Math.cos(c.beta),s=Math.sin(c.beta);0===s&&(s=1e-4);var a=c._getTargetPosition();c._computationVector.copyFromFloats(c.radius*r*s,c.radius*o,c.radius*n*s),a.addToRef(c._computationVector,c._newPosition),c.position.copyFrom(c._newPosition);var l=c.upVector;c.allowUpsideDown&&c.beta<0&&(l=l.clone(),l=l.negate()),c._computeViewMatrix(c.position,a,l),c._viewMatrix.m[12]+=c.targetScreenOffset.x,c._viewMatrix.m[13]+=c.targetScreenOffset.y,c._collisionTriggered=!1},c._target=e.Vector3.Zero(),s&&c.setTarget(s),c.alpha=r,c.beta=n,c.radius=o,c.getViewMatrix(),c.inputs=new e.ArcRotateCameraInputsManager(c),c.inputs.addKeyboard().addMouseWheel().addPointers(),c}return o(i,t),Object.defineProperty(i.prototype,"target",{get:function(){return this._target},set:function(e){this.setTarget(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"angularSensibilityX",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"angularSensibilityY",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pinchPrecision",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchPrecision:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pinchDeltaPercentage",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"panningSensibility",{get:function(){var e=this.inputs.attached.pointers;return e?e.panningSensibility:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wheelPrecision",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wheelDeltaPercentage",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"bouncingBehavior",{get:function(){return this._bouncingBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useBouncingBehavior",{get:function(){return null!=this._bouncingBehavior},set:function(t){t!==this.useBouncingBehavior&&(t?(this._bouncingBehavior=new e.BouncingBehavior,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"framingBehavior",{get:function(){return this._framingBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useFramingBehavior",{get:function(){return null!=this._framingBehavior},set:function(t){t!==this.useFramingBehavior&&(t?(this._framingBehavior=new e.FramingBehavior,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"autoRotationBehavior",{get:function(){return this._autoRotationBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useAutoRotationBehavior",{get:function(){return null!=this._autoRotationBehavior},set:function(t){t!==this.useAutoRotationBehavior&&(t?(this._autoRotationBehavior=new e.AutoRotationBehavior,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))},enumerable:!0,configurable:!0}),i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache._target=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=e.Vector2.Zero()},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)},i.prototype._getTargetPosition=function(){if(this._targetHost&&this._targetHost.getAbsolutePosition){var e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}var t=this._getLockedTargetPosition();return t||this._target},i.prototype.storeState=function(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),t.prototype.storeState.call(this)},i.prototype._restoreStateValues=function(){return!!t.prototype._restoreStateValues.call(this)&&(this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.setTarget(this._storedTarget.clone()),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)},i.prototype._isSynchronizedViewMatrix=function(){return!!t.prototype._isSynchronizedViewMatrix.call(this)&&(this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset))},i.prototype.attachControl=function(e,t,i,r){var n=this;void 0===i&&(i=!0),void 0===r&&(r=2),this._useCtrlForPanning=i,this._panningMouseButton=r,this.inputs.attachElement(e,t),this._reset=function(){n.inertialAlphaOffset=0,n.inertialBetaOffset=0,n.inertialRadiusOffset=0,n.inertialPanningX=0,n.inertialPanningY=0}},i.prototype.detachControl=function(e){this.inputs.detachElement(e),this._reset&&this._reset()},i.prototype._checkInputs=function(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){var i=this.inertialAlphaOffset;this.beta<=0&&(i*=-1),this.getScene().useRightHandedSystem&&(i*=-1),this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(i*=-1),this.alpha+=i,this.beta+=this.inertialBetaOffset,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit)},i.prototype.rebuildAnglesAndRadius=function(){this.position.subtractToRef(this._getTargetPosition(),this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4),this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha),this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()},i.prototype.setPosition=function(e){this.position.equals(e)||(this.position.copyFrom(e),this.rebuildAnglesAndRadius())},i.prototype.setTarget=function(e,t,i){if(void 0===t&&(t=!1),void 0===i&&(i=!1),e.getBoundingInfo)this._targetBoundingCenter=t?e.getBoundingInfo().boundingBox.centerWorld.clone():null,this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{var r=e,n=this._getTargetPosition();if(n&&!i&&n.equals(r))return;this._targetHost=null,this._target=r,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}this.rebuildAnglesAndRadius()},i.prototype._getViewMatrix=function(){var t=Math.cos(this.alpha),i=Math.sin(this.alpha),r=Math.cos(this.beta),n=Math.sin(this.beta);0===n&&(n=1e-4);var o=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*t*n,this.radius*r,this.radius*i*n),o.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions)this._collider||(this._collider=new e.Collider),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this.position,this._collisionVelocity),this._collisionTriggered=!0, +this.getScene().collisionCoordinator.getNewPosition(this.position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId);else{this.position.copyFrom(this._newPosition);var s=this.upVector;this.allowUpsideDown&&n<0&&(s=s.clone(),s=s.negate()),this._computeViewMatrix(this.position,o,s),this._viewMatrix.m[12]+=this.targetScreenOffset.x,this._viewMatrix.m[13]+=this.targetScreenOffset.y}return this._currentTarget=o,this._viewMatrix},i.prototype.zoomOn=function(t,i){void 0===i&&(i=!1),t=t||this.getScene().meshes;var r=e.Mesh.MinMax(t),n=e.Vector3.Distance(r.min,r.max);this.radius=n*this.zoomOnFactor,this.focusOn({min:r.min,max:r.max,distance:n},i)},i.prototype.focusOn=function(t,i){void 0===i&&(i=!1);var r,n;if(void 0===t.min){var o=t||this.getScene().meshes;r=e.Mesh.MinMax(o),n=e.Vector3.Distance(r.min,r.max)}else{var s=t;r=s,n=s.distance}this._target=e.Mesh.Center(r),i||(this.maxZ=2*n)},i.prototype.createRigCamera=function(t,r){var n=0;switch(this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:n=this._cameraRigParams.stereoHalfAngle*(0===r?1:-1);break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:n=this._cameraRigParams.stereoHalfAngle*(0===r?-1:1)}var o=new i(t,this.alpha+n,this.beta,this.radius,this._target,this.getScene());return o._cameraRigParams={},o},i.prototype._updateRigCameras=function(){var i=this._rigCameras[0],r=this._rigCameras[1];switch(i.beta=r.beta=this.beta,i.radius=r.radius=this.radius,this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:i.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}t.prototype._updateRigCameras.call(this)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getClassName=function(){return"ArcRotateCamera"},n([e.serialize()],i.prototype,"alpha",void 0),n([e.serialize()],i.prototype,"beta",void 0),n([e.serialize()],i.prototype,"radius",void 0),n([e.serializeAsVector3("target")],i.prototype,"_target",void 0),n([e.serialize()],i.prototype,"inertialAlphaOffset",void 0),n([e.serialize()],i.prototype,"inertialBetaOffset",void 0),n([e.serialize()],i.prototype,"inertialRadiusOffset",void 0),n([e.serialize()],i.prototype,"lowerAlphaLimit",void 0),n([e.serialize()],i.prototype,"upperAlphaLimit",void 0),n([e.serialize()],i.prototype,"lowerBetaLimit",void 0),n([e.serialize()],i.prototype,"upperBetaLimit",void 0),n([e.serialize()],i.prototype,"lowerRadiusLimit",void 0),n([e.serialize()],i.prototype,"upperRadiusLimit",void 0),n([e.serialize()],i.prototype,"inertialPanningX",void 0),n([e.serialize()],i.prototype,"inertialPanningY",void 0),n([e.serialize()],i.prototype,"pinchToPanMaxDistance",void 0),n([e.serialize()],i.prototype,"panningDistanceLimit",void 0),n([e.serializeAsVector3()],i.prototype,"panningOriginTarget",void 0),n([e.serialize()],i.prototype,"panningInertia",void 0),n([e.serialize()],i.prototype,"zoomOnFactor",void 0),n([e.serialize()],i.prototype,"allowUpsideDown",void 0),i})(e.TargetCamera);e.ArcRotateCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_3",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n){var o=t.call(this,i,n)||this;return o.groundColor=new e.Color3(0,0,0),o.direction=r||e.Vector3.Up(),o}return o(i,t),i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.getClassName=function(){return"HemisphericLight"},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(e.Vector3.Zero())),this.direction},i.prototype.getShadowGenerator=function(){return null},i.prototype.transferToEffect=function(t,i){var r=e.Vector3.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",r.x,r.y,r.z,0,i),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),i),this},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),this._worldMatrix},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_HEMISPHERICLIGHT},i.prototype.prepareLightSpecificDefines=function(e,t){e["HEMILIGHT"+t]=!0},n([e.serializeAsColor3()],i.prototype,"groundColor",void 0),n([e.serializeAsVector3()],i.prototype,"direction",void 0),i})(e.Light);e.HemisphericLight=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(){var e=null!==t&&t.apply(this,arguments)||this;return e._needProjectionMatrixCompute=!0,e}return o(i,t),i.prototype._setPosition=function(e){this._position=e},Object.defineProperty(i.prototype,"position",{get:function(){return this._position},set:function(e){this._setPosition(e)},enumerable:!0,configurable:!0}),i.prototype._setDirection=function(e){this._direction=e},Object.defineProperty(i.prototype,"direction",{get:function(){return this._direction},set:function(e){this._setDirection(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowMinZ",{get:function(){return this._shadowMinZ},set:function(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowMaxZ",{get:function(){return this._shadowMaxZ},set:function(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),i.prototype.computeTransformedInformation=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=e.Vector3.Zero()),e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=e.Vector3.Zero()),e.Vector3.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0)},i.prototype.getDepthScale=function(){return 50},i.prototype.getShadowDirection=function(e){return this.transformedDirection?this.transformedDirection:this.direction},i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(this.position)),this.direction},i.prototype.getRotation=function(){this.direction.normalize();var t=e.Vector3.Cross(this.direction,e.Axis.Y),i=e.Vector3.Cross(t,this.direction);return e.Vector3.RotationFromAxis(t,i,this.direction)},i.prototype.needCube=function(){return!1},i.prototype.needProjectionMatrixCompute=function(){return this._needProjectionMatrixCompute},i.prototype.forceProjectionMatrixCompute=function(){this._needProjectionMatrixCompute=!0},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this._worldMatrix},i.prototype.getDepthMinZ=function(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ},i.prototype.getDepthMaxZ=function(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ},i.prototype.setShadowProjectionMatrix=function(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this},n([e.serializeAsVector3()],i.prototype,"position",null),n([e.serializeAsVector3()],i.prototype,"direction",null),n([e.serialize()],i.prototype,"shadowMinZ",null),n([e.serialize()],i.prototype,"shadowMaxZ",null),i})(e.Light);e.ShadowLight=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_0",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(e,i,r){var n=t.call(this,e,r)||this;return n._shadowAngle=Math.PI/2,n.position=i,n}return o(i,t),Object.defineProperty(i.prototype,"shadowAngle",{get:function(){return this._shadowAngle},set:function(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"direction",{get:function(){return this._direction},set:function(e){var t=this.needCube();this._direction=e,this.needCube()!==t&&this._shadowGenerator&&this._shadowGenerator.recreateShadowMap()},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"PointLight"},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_POINTLIGHT},i.prototype.needCube=function(){return!this.direction},i.prototype.getShadowDirection=function(i){if(this.direction)return t.prototype.getShadowDirection.call(this,i);switch(i){case 0:return new e.Vector3(1,0,0);case 1:return new e.Vector3(-1,0,0);case 2:return new e.Vector3(0,-1,0);case 3:return new e.Vector3(0,1,0);case 4:return new e.Vector3(0,0,1);case 5:return new e.Vector3(0,0,-1)}return e.Vector3.Zero()},i.prototype._setDefaultShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;n&&e.Matrix.PerspectiveFovLHToRef(this.shadowAngle,1,this.getDepthMinZ(n),this.getDepthMaxZ(n),t)},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this)},i.prototype.prepareLightSpecificDefines=function(e,t){e["POINTLIGHT"+t]=!0},n([e.serialize()],i.prototype,"shadowAngle",null),i})(e.ShadowLight);e.PointLight=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_1",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(e,i,r){var n=t.call(this,e,r)||this;return n._shadowFrustumSize=0,n._shadowOrthoScale=.1,n.autoUpdateExtends=!0,n._orthoLeft=Number.MAX_VALUE,n._orthoRight=Number.MIN_VALUE,n._orthoTop=Number.MIN_VALUE,n._orthoBottom=Number.MAX_VALUE,n.position=i.scale(-1),n.direction=i,n}return o(i,t),Object.defineProperty(i.prototype,"shadowFrustumSize",{get:function(){return this._shadowFrustumSize},set:function(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowOrthoScale",{get:function(){return this._shadowOrthoScale},set:function(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"DirectionalLight"},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_DIRECTIONALLIGHT},i.prototype._setDefaultShadowProjectionMatrix=function(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e,t):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)},i.prototype._setDefaultFixedFrustumShadowProjectionMatrix=function(t,i){var r=this.getScene().activeCamera;r&&e.Matrix.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,t)},i.prototype._setDefaultAutoExtendShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;if(n){if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){var o=e.Vector3.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;for(var s=0;sthis._orthoRight&&(this._orthoRight=o.x),o.y>this._orthoTop&&(this._orthoTop=o.y)}}var u=this._orthoRight-this._orthoLeft,d=this._orthoTop-this._orthoBottom;e.Matrix.OrthoOffCenterLHToRef(this._orthoLeft-u*this.shadowOrthoScale,this._orthoRight+u*this.shadowOrthoScale,this._orthoBottom-d*this.shadowOrthoScale,this._orthoTop+d*this.shadowOrthoScale,void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,t)}},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)},i.prototype.getDepthMinZ=function(e){return 1},i.prototype.getDepthMaxZ=function(e){return 1},i.prototype.prepareLightSpecificDefines=function(e,t){e["DIRLIGHT"+t]=!0},n([e.serialize()],i.prototype,"shadowFrustumSize",null),n([e.serialize()],i.prototype,"shadowOrthoScale",null),n([e.serialize()],i.prototype,"autoUpdateExtends",void 0),i})(e.ShadowLight);e.DirectionalLight=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_2",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),e.Vector3.Zero(),0,0,r)}}));var t=(function(t){function i(i,r,n,o,s,a){var l=t.call(this,i,a)||this;return l._projectionTextureMatrix=e.Matrix.Zero(),l._projectionTextureLightNear=1e-6,l._projectionTextureLightFar=1e3,l._projectionTextureUpDirection=e.Vector3.Up(),l._projectionTextureViewLightDirty=!0,l._projectionTextureProjectionLightDirty=!0,l._projectionTextureDirty=!0,l._projectionTextureViewTargetVector=e.Vector3.Zero(),l._projectionTextureViewLightMatrix=e.Matrix.Zero(),l._projectionTextureProjectionLightMatrix=e.Matrix.Zero(),l._projectionTextureScalingMatrix=e.Matrix.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),l.position=r,l.direction=n,l.angle=o,l.exponent=s,l}return o(i,t),Object.defineProperty(i.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowAngleScale",{get:function(){return this._shadowAngleScale},set:function(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureMatrix",{get:function(){return this._projectionTextureMatrix},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureLightNear",{get:function(){return this._projectionTextureLightNear},set:function(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureLightFar",{get:function(){return this._projectionTextureLightFar},set:function(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureUpDirection",{get:function(){return this._projectionTextureUpDirection},set:function(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTexture",{get:function(){return this._projectionTexture},set:function(e){this._projectionTexture=e,this._projectionTextureDirty=!0},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"SpotLight"},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_SPOTLIGHT},i.prototype._setDirection=function(e){t.prototype._setDirection.call(this,e),this._projectionTextureViewLightDirty=!0},i.prototype._setPosition=function(e){t.prototype._setPosition.call(this,e),this._projectionTextureViewLightDirty=!0},i.prototype._setDefaultShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;if(n){this._shadowAngleScale=this._shadowAngleScale||1;var o=this._shadowAngleScale*this._angle;e.Matrix.PerspectiveFovLHToRef(o,1,this.getDepthMinZ(n),this.getDepthMaxZ(n),t)}},i.prototype._computeProjectionTextureViewLightMatrix=function(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.position.addToRef(this.direction,this._projectionTextureViewTargetVector),e.Matrix.LookAtLHToRef(this.position,this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)},i.prototype._computeProjectionTextureProjectionLightMatrix=function(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;var t=this.projectionTextureLightFar,i=this.projectionTextureLightNear,r=t/(t-i),n=-r*i,o=1/Math.tan(this._angle/2);e.Matrix.FromValuesToRef(o/1,0,0,0,0,o,0,0,0,0,r,1,0,0,n,0,this._projectionTextureProjectionLightMatrix)},i.prototype._computeProjectionTextureMatrix=function(){this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(t,i){var r;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,i),r=e.Vector3.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,i),r=e.Vector3.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",r.x,r.y,r.z,Math.cos(.5*this.angle),i),this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),t.setMatrix("textureProjectionMatrix"+i,this._projectionTextureMatrix),t.setTexture("projectionLightSampler"+i,this.projectionTexture)),this},i.prototype.dispose=function(){t.prototype.dispose.call(this),this._projectionTexture&&this._projectionTexture.dispose()},i.prototype.prepareLightSpecificDefines=function(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!this.projectionTexture},n([e.serialize()],i.prototype,"angle",null),n([e.serialize()],i.prototype,"shadowAngleScale",null),n([e.serialize()],i.prototype,"exponent",void 0),n([e.serialize()],i.prototype,"projectionTextureLightNear",null),n([e.serialize()],i.prototype,"projectionTextureLightFar",null),n([e.serialize()],i.prototype,"projectionTextureUpDirection",null),n([e.serializeAsTexture("projectedLightTexture")],i.prototype,"_projectionTexture",void 0),i})(e.ShadowLight);e.SpotLight=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=e.Animation.ANIMATIONLOOPMODE_CYCLE}return t})();e.AnimationPropertiesOverride=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i){this.name=e,this.from=t,this.to=i}return e.prototype.clone=function(){return new e(this.name,this.from,this.to)},e})();e.AnimationRange=t;var i=(function(){function e(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}return e.prototype._clone=function(){return new e(this.frame,this.action,this.onlyOnce)},e})();e.AnimationEvent=i;var r=(function(){function t(e){this.path=e,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e.Vector3(t.x,0,t.y)},t.prototype.moveAhead=function(e){return void 0===e&&(e=.002),this.move(e),this},t.prototype.moveBack=function(e){return void 0===e&&(e=.002),this.move(-e),this},t.prototype.move=function(e){if(Math.abs(e)>1)throw"step size should be less than 1.";return this.value+=e,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.raiseOnChange=function(){var e=this;return this._onchange.forEach((function(t){return t(e)})),this},t.prototype.onchange=function(e){return this._onchange.push(e),this},t})();e.PathCursor=r;var n;!(function(e){e[e.STEP=1]="STEP"})(n=e.AnimationKeyInterpolation||(e.AnimationKeyInterpolation={}));var o=(function(){function i(e,t,r,n,o,s){this.name=e,this.targetProperty=t,this.framePerSecond=r,this.dataType=n,this.loopMode=o,this.enableBlending=s,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=n,this.loopMode=void 0===o?i.ANIMATIONLOOPMODE_CYCLE:o}return i._PrepareAnimation=function(t,r,n,o,s,a,l,c){var h=void 0;if(!isNaN(parseFloat(s))&&isFinite(s)?h=i.ANIMATIONTYPE_FLOAT:s instanceof e.Quaternion?h=i.ANIMATIONTYPE_QUATERNION:s instanceof e.Vector3?h=i.ANIMATIONTYPE_VECTOR3:s instanceof e.Vector2?h=i.ANIMATIONTYPE_VECTOR2:s instanceof e.Color3?h=i.ANIMATIONTYPE_COLOR3:s instanceof e.Size&&(h=i.ANIMATIONTYPE_SIZE),void 0==h)return null;var u=new i(t,r,n,h,l),d=[{frame:0,value:s},{frame:o,value:a}];return u.setKeys(d),void 0!==c&&u.setEasingFunction(c),u},i.CreateAnimation=function(e,t,r,n){var o=new i(e+"Animation",e,r,t,i.ANIMATIONLOOPMODE_CONSTANT);return o.setEasingFunction(n),o},i.CreateAndStartAnimation=function(e,t,r,n,o,s,a,l,c,h){var u=i._PrepareAnimation(e,r,n,o,s,a,l,c);return u?t.getScene().beginDirectAnimation(t,[u],0,o,1===u.loopMode,1,h):null},i.CreateAndStartHierarchyAnimation=function(e,t,r,n,o,s,a,l,c,h,u){var d=i._PrepareAnimation(e,n,o,s,a,l,c,h);return d?t.getScene().beginDirectHierarchyAnimation(t,r,[d],0,s,1===d.loopMode,1,u):null},i.CreateMergeAndStartAnimation=function(e,t,r,n,o,s,a,l,c,h){var u=i._PrepareAnimation(e,r,n,o,s,a,l,c);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,o,1===u.loopMode,1,h)):null},i.TransitionTo=function(e,t,i,r,n,o,s,a){if(void 0===a&&(a=null),s<=0)return i[e]=t,a&&a(),null;var l=n*(s/1e3);o.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(o);var c=r.beginAnimation(i,0,l,!1);return c.onAnimationEnd=a,c},Object.defineProperty(i.prototype,"runtimeAnimations",{get:function(){return this._runtimeAnimations},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"hasRunningRuntimeAnimations",{get:function(){for(var e=0,t=this._runtimeAnimations;e=0;o--)this._keys[o].frame>=r&&this._keys[o].frame<=n&&this._keys.splice(o,1);this._ranges[e]=null}},i.prototype.getRange=function(e){return this._ranges[e]},i.prototype.getKeys=function(){return this._keys},i.prototype.getHighestFrame=function(){for(var e=0,t=0,i=this._keys.length;t0)return a.clone?a.clone():a;var l=this.getKeys(),c=Math.max(0,Math.min(l.length-1,Math.floor(l.length*(e-l[0].frame)/(l[l.length-1].frame-l[0].frame))-1));if(l[c].frame>=e)for(;c-1>=0&&l[c].frame>=e;)c--;for(var h=c;h=e){var d=l[h],f=this._getKeyValue(d.value);if(d.interpolation===n.STEP)return f;var p=this._getKeyValue(u.value),_=void 0!==d.outTangent&&void 0!==u.inTangent,m=u.frame-d.frame,g=(e-d.frame)/m,v=this.getEasingFunction();switch(null!=v&&(g=v.ease(g)),this.dataType){case i.ANIMATIONTYPE_FLOAT:var y=_?this.floatInterpolateFunctionWithTangents(f,d.outTangent*m,p,u.inTangent*m,g):this.floatInterpolateFunction(f,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return y;case i.ANIMATIONLOOPMODE_RELATIVE:return s*t+y}break;case i.ANIMATIONTYPE_QUATERNION:var b=_?this.quaternionInterpolateFunctionWithTangents(f,d.outTangent.scale(m),p,u.inTangent.scale(m),g):this.quaternionInterpolateFunction(f,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return b;case i.ANIMATIONLOOPMODE_RELATIVE:return b.addInPlace(s.scale(t))}return b;case i.ANIMATIONTYPE_VECTOR3:var x=_?this.vector3InterpolateFunctionWithTangents(f,d.outTangent.scale(m),p,u.inTangent.scale(m),g):this.vector3InterpolateFunction(f,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return x;case i.ANIMATIONLOOPMODE_RELATIVE:return x.add(s.scale(t))}case i.ANIMATIONTYPE_VECTOR2:var T=_?this.vector2InterpolateFunctionWithTangents(f,d.outTangent.scale(m),p,u.inTangent.scale(m),g):this.vector2InterpolateFunction(f,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return T;case i.ANIMATIONLOOPMODE_RELATIVE:return T.add(s.scale(t))}case i.ANIMATIONTYPE_SIZE:switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(f,p,g);case i.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(f,p,g).add(s.scale(t))}case i.ANIMATIONTYPE_COLOR3:switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.color3InterpolateFunction(f,p,g);case i.ANIMATIONLOOPMODE_RELATIVE:return this.color3InterpolateFunction(f,p,g).add(s.scale(t))}case i.ANIMATIONTYPE_MATRIX:switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:if(i.AllowMatricesInterpolation)return this.matrixInterpolateFunction(f,p,g,r);case i.ANIMATIONLOOPMODE_RELATIVE:return f}}break}}return this._getKeyValue(l[l.length-1].value)},i.prototype.matrixInterpolateFunction=function(t,r,n,o){return i.AllowMatrixDecomposeForInterpolation?o?(e.Matrix.DecomposeLerpToRef(t,r,n,o),o):e.Matrix.DecomposeLerp(t,r,n):o?(e.Matrix.LerpToRef(t,r,n,o),o):e.Matrix.Lerp(t,r,n)},i.prototype.clone=function(){var e=new i(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(var t in this._ranges){var r=this._ranges[t];r&&(e._ranges[t]=r.clone())}}return e},i.prototype.setKeys=function(e){this._keys=e.slice(0)},i.prototype.serialize=function(){var e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;var t=this.dataType;e.keys=[];for(var r=this.getKeys(),n=0;n=1&&(l=h.values[1]),h.values.length>=2&&(c=h.values[2]);break;case i.ANIMATIONTYPE_QUATERNION:if(r=e.Quaternion.FromArray(h.values),h.values.length>=8){var u=e.Quaternion.FromArray(h.values.slice(4,8));u.equals(e.Quaternion.Zero())||(l=u)}if(h.values.length>=12){var d=e.Quaternion.FromArray(h.values.slice(8,12));d.equals(e.Quaternion.Zero())||(c=d)}break;case i.ANIMATIONTYPE_MATRIX:r=e.Matrix.FromArray(h.values);break;case i.ANIMATIONTYPE_COLOR3:r=e.Color3.FromArray(h.values);break;case i.ANIMATIONTYPE_VECTOR3:default:r=e.Vector3.FromArray(h.values)}var f={};f.frame=h.frame,f.value=r,void 0!=l&&(f.inTangent=l),void 0!=c&&(f.outTangent=c),a.push(f)}if(o.setKeys(a),t.ranges)for(n=0;nr[0].frame&&(this._from=r[0].frame),this._toe){var a={frame:e,value:o.value,inTangent:o.inTangent,outTangent:o.outTangent,interpolation:o.interpolation};n.splice(0,0,a)}if(s.frame-1&&this._scene.animationGroups.splice(e,1)},t.prototype._checkAnimationGroupEnded=function(e){var t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))},t})();e.AnimationGroup=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i,r){var n=this;this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._targetPath="",this._weight=1,this._ratioOffset=0,this._previousDelay=0,this._previousRatio=0,this._animation=t,this._target=e,this._scene=i,this._host=r,t._runtimeAnimations.push(this);var o=t.getEvents();o&&o.length>0&&o.forEach((function(e){n._events.push(e._clone())}))}return Object.defineProperty(t.prototype,"currentFrame",{get:function(){return this._currentFrame},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weight",{get:function(){return this._weight},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentValue",{get:function(){return this._currentValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"targetPath",{get:function(){return this._targetPath},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){return this._activeTarget},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animation",{get:function(){return this._animation},enumerable:!0,configurable:!0}),t.prototype.reset=function(e){if(void 0===e&&(e=!1),e)if(this._target instanceof Array)for(var t=0,i=0,r=this._target;i-1&&this._animation.runtimeAnimations.splice(e,1)},t.prototype._interpolate=function(t,i,r,n,o){return this._currentFrame=t,this._animation.dataType!==e.Animation.ANIMATIONTYPE_MATRIX||this._workValue||(this._workValue=e.Matrix.Zero()),this._animation._interpolate(t,i,this._workValue,r,n,o)},t.prototype.setValue=function(e,t){if(void 0===t&&(t=1),this._target instanceof Array)for(var i=0,r=0,n=this._target;r1){for(var l=t[a[0]],c=1;ct[t.length-1].frame&&(e=t[t.length-1].frame);var i=this._interpolate(e,0,this._getCorrectLoopMode());this.setValue(i,-1)},t.prototype._prepareForSpeedRatioChange=function(e){var t=this._previousDelay*(this._animation.framePerSecond*e)/1e3;this._ratioOffset=this._previousRatio-t},t.prototype.animate=function(t,i,r,n,o,s){void 0===s&&(s=-1);var a=this._animation.targetPropertyPath;if(!a||a.length<1)return this._stopped=!0,!1;var l=!0,c=this._animation.getKeys();if(0!==c[0].frame){var h={frame:0,value:c[0].value};c.splice(0,0,h)}else if(1===c.length){var h={frame:.001,value:c[0].value};c.push(h)}(ic[c.length-1].frame)&&(i=c[0].frame),(rc[c.length-1].frame)&&(r=c[c.length-1].frame),i===r&&(i>c[0].frame?i--:ri&&f>=d||i>r&&f<=d)&&!n)l=!1,p=this._animation._getKeyValue(c[c.length-1].value);else if(this._getCorrectLoopMode()!==e.Animation.ANIMATIONLOOPMODE_CYCLE){var _=r.toString()+i.toString();if(!this._offsetsCache[_]){var m=this._interpolate(i,0,e.Animation.ANIMATIONLOOPMODE_CYCLE),g=this._interpolate(r,0,e.Animation.ANIMATIONLOOPMODE_CYCLE);switch(this._animation.dataType){case e.Animation.ANIMATIONTYPE_FLOAT:this._offsetsCache[_]=g-m;break;case e.Animation.ANIMATIONTYPE_QUATERNION:this._offsetsCache[_]=g.subtract(m);break;case e.Animation.ANIMATIONTYPE_VECTOR3:this._offsetsCache[_]=g.subtract(m);case e.Animation.ANIMATIONTYPE_VECTOR2:this._offsetsCache[_]=g.subtract(m);case e.Animation.ANIMATIONTYPE_SIZE:this._offsetsCache[_]=g.subtract(m);case e.Animation.ANIMATIONTYPE_COLOR3:this._offsetsCache[_]=g.subtract(m)}this._highLimitsCache[_]=g}p=this._highLimitsCache[_],u=this._offsetsCache[_]}if(void 0===u)switch(this._animation.dataType){case e.Animation.ANIMATIONTYPE_FLOAT:u=0;break;case e.Animation.ANIMATIONTYPE_QUATERNION:u=new e.Quaternion(0,0,0,0);break;case e.Animation.ANIMATIONTYPE_VECTOR3:u=e.Vector3.Zero();break;case e.Animation.ANIMATIONTYPE_VECTOR2:u=e.Vector2.Zero();break;case e.Animation.ANIMATIONTYPE_SIZE:u=e.Size.Zero();break;case e.Animation.ANIMATIONTYPE_COLOR3:u=e.Color3.Black()}var v=f/d>>0,y=l?i+f%d:r;if(this._host&&this._host.syncRoot){var b=this._host.syncRoot;y=i+(r-i)*((b.masterFrame-b.fromFrame)/(b.toFrame-b.fromFrame))}var x=this._events;if(d>0&&this.currentFrame>y||d<0&&this.currentFrame0&&y>=x[T].frame&&x[T].frame>=i||d<0&&y<=x[T].frame&&x[T].frame<=i){var P=x[T];P.isDone||(P.onlyOnce&&(x.splice(T,1),T--),P.isDone=!0,P.action())}return l||(this._stopped=!0),l},t})();e.RuntimeAnimation=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a,l){void 0===r&&(r=0),void 0===n&&(n=100),void 0===o&&(o=!1),void 0===s&&(s=1),this.target=i,this.fromFrame=r,this.toFrame=n,this.loopAnimation=o,this.onAnimationEnd=a,this._localDelayOffset=null,this._pausedDelay=null,this._runtimeAnimations=new Array,this._paused=!1,this._speedRatio=1,this._weight=-1,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new e.Observable,this._scene=t,l&&this.appendAnimations(i,l),this._speedRatio=s,t._activeAnimatables.push(this)}return Object.defineProperty(t.prototype,"syncRoot",{get:function(){return this._syncRoot},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"masterFrame",{get:function(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weight",{get:function(){return this._weight},set:function(e){if(-1===e)return void(this._weight=-1);this._weight=Math.min(Math.max(e,0),1)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"speedRatio",{get:function(){return this._speedRatio},set:function(e){for(var t=0;t-1&&(this._scene._activeAnimatables.splice(t,1),this._scene._activeAnimatables.push(this))}return this},t.prototype.getAnimations=function(){return this._runtimeAnimations},t.prototype.appendAnimations=function(t,i){for(var r=0;r-1){for(var r=this._runtimeAnimations,n=r.length-1;n>=0;n--){var o=r[n];e&&o.animation.name!=e||(t&&!t(o.target)||(o.dispose(),r.splice(n,1)))}0==r.length&&(this._scene._activeAnimatables.splice(i,1),this._raiseOnAnimationEnd())}}else{var n=this._scene._activeAnimatables.indexOf(this);if(n>-1){this._scene._activeAnimatables.splice(n,1);for(var r=this._runtimeAnimations,n=0;n=.5?.5*(1-this.easeInCore(2*(1-t)))+.5:.5*this.easeInCore(2*t)},e._EASINGMODE_EASEIN=0,e._EASINGMODE_EASEOUT=1,e._EASINGMODE_EASEINOUT=2,e})();e.EasingFunction=t;var i=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)},t})(t);e.CircleEase=i;var r=(function(e){function t(t){void 0===t&&(t=1);var i=e.call(this)||this;return i.amplitude=t,i}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)},t})(t);e.BackEase=r;var n=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=2);var r=e.call(this)||this;return r.bounces=t,r.bounciness=i,r}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.bounces),i=this.bounciness;i<=1&&(i=1.001);var r=Math.pow(i,t),n=1-i,o=(1-r)/n+.5*r,s=e*o,a=Math.log(-s*(1-i)+1)/Math.log(i),l=Math.floor(a),c=l+1,h=(1-Math.pow(i,l))/(n*o),u=(1-Math.pow(i,c))/(n*o),d=.5*(h+u),f=e-d,p=d-h;return-Math.pow(1/i,t-l)/(p*p)*(f-p)*(f+p)},t})(t);e.BounceEase=n;var s=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e*e},t})(t);e.CubicEase=s;var a=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=3);var r=e.call(this)||this;return r.oscillations=t,r.springiness=i,r}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.oscillations),i=Math.max(0,this.springiness);return(0==i?e:(Math.exp(i*e)-1)/(Math.exp(i)-1))*Math.sin((6.283185307179586*t+1.5707963267948966)*e)},t})(t);e.ElasticEase=a;var l=(function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.exponent=t,i}return o(t,e),t.prototype.easeInCore=function(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)},t})(t);e.ExponentialEase=l;var c=(function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.power=t,i}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.power);return Math.pow(e,t)},t})(t);e.PowerEase=c;var h=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e},t})(t);e.QuadraticEase=h;var u=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e*e*e},t})(t);e.QuarticEase=u;var d=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e*e*e*e},t})(t);e.QuinticEase=d;var f=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return 1-Math.sin(1.5707963267948966*(1-e))},t})(t);e.SineEase=f;var p=(function(t){function i(e,i,r,n){void 0===e&&(e=0),void 0===i&&(i=0),void 0===r&&(r=1),void 0===n&&(n=1);var o=t.call(this)||this;return o.x1=e,o.y1=i,o.x2=r,o.y2=n,o}return o(i,t),i.prototype.easeInCore=function(t){return e.BezierCurve.interpolate(t,this.x1,this.y1,this.x2,this.y2)},i})(t);e.BezierCurveEase=p})(r||(r={}));var r;!(function(e){var t=(function(){function e(e){this._actionManager=e}return e.prototype.isValid=function(){return!0},e.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},e.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},e.prototype.serialize=function(){},e.prototype._serialize=function(e){return{type:2,children:[],name:e.name,properties:e.properties}},e})();e.Condition=t;var i=(function(t){function i(e,r,n,o,s){void 0===s&&(s=i.IsEqual);var a=t.call(this,e)||this;return a.propertyPath=n,a.value=o,a.operator=s,a._target=r,a._effectiveTarget=a._getEffectiveTarget(r,a.propertyPath),a._property=a._getProperty(a.propertyPath),a}return o(i,t),Object.defineProperty(i,"IsEqual",{get:function(){return i._IsEqual},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsDifferent",{get:function(){return i._IsDifferent},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsGreater",{get:function(){return i._IsGreater},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsLesser",{get:function(){return i._IsLesser},enumerable:!0,configurable:!0}),i.prototype.isValid=function(){switch(this.operator){case i.IsGreater:return this._effectiveTarget[this._property]>this.value;case i.IsLesser:return this._effectiveTarget[this._property]-1&&this._scene.actionManagers.splice(e,1)},t.prototype.getScene=function(){return this._scene},t.prototype.hasSpecificTriggers=function(e){for(var t=0;t-1)return!0}return!1},t.prototype.hasSpecificTrigger=function(e,t){for(var i=0;i=t._OnPickTrigger&&i.trigger<=t._OnPointerOutTrigger)return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPickTriggers",{get:function(){for(var e=0;e=t._OnPickTrigger&&i.trigger<=t._OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"HasTriggers",{get:function(){for(var e in t.Triggers)if(t.Triggers.hasOwnProperty(e))return!0;return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"HasPickTriggers",{get:function(){for(var e in t.Triggers)if(t.Triggers.hasOwnProperty(e)){var i=parseInt(e);if(i>=t._OnPickTrigger&&i<=t._OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),t.HasSpecificTrigger=function(e){for(var i in t.Triggers)if(t.Triggers.hasOwnProperty(i)){var r=parseInt(i);if(r===e)return!0}return!1},t.prototype.registerAction=function(i){return i.trigger===t.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(e.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(i),t.Triggers[i.trigger]?t.Triggers[i.trigger]++:t.Triggers[i.trigger]=1,i._actionManager=this,i._prepare(),i)},t.prototype.unregisterAction=function(e){var i=this.actions.indexOf(e);return-1!==i&&(this.actions.splice(i,1),t.Triggers[e.trigger]-=1,0===t.Triggers[e.trigger]&&delete t.Triggers[e.trigger],delete e._actionManager,!0)},t.prototype.processTrigger=function(e,i){for(var r=0;r0;if(2===i.type?d.push(o):d.push(r),_){for(var m=new Array,g=0;g0){var d=u.properties[0].value,f=null===u.properties[0].targetType?d:n.getMeshByName(d);f._meshId&&(f.mesh=n.getMeshByID(f._meshId)),h={trigger:t[u.name],parameter:f}}else h=t[u.name];for(var p=0;p>0;this._vertexData[o+10]=t.cellIndex-s*n,this._vertexData[o+11]=s,this._vertexData[o+12]=t.color.r,this._vertexData[o+13]=t.color.g,this._vertexData[o+14]=t.color.b,this._vertexData[o+15]=t.color.a},t.prototype.intersects=function(t,i,r,n){for(var o=Math.min(this._capacity,this.sprites.length),s=e.Vector3.Zero(),a=e.Vector3.Zero(),l=Number.MAX_VALUE,c=null,h=e.Vector3.Zero(),u=i.getViewMatrix(),d=0;dp&&(l=p,c=f,n))break}}}if(c){var _=new e.PickingInfo;return _.hit=!0,_.pickedSprite=c,_.distance=l,_}return null},t.prototype.render=function(){if(this._effectBase.isReady()&&this._effectFog.isReady()&&this._spriteTexture&&this._spriteTexture.isReady()){for(var t=this._scene.getEngine(),i=this._spriteTexture.getBaseSize(),r=t.getDeltaTime(),n=Math.min(this._capacity,this.sprites.length),o=i.width/this.cellWidth,s=0,a=0;athis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,this.cellIndex>this._toIndex&&(this._loopAnimation?this.cellIndex=this._fromIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()))))},t.prototype.dispose=function(){for(var e=0;et.x)return!1}else if(i=1/this.direction.x,r=(e.x-this.origin.x)*i,n=(t.x-this.origin.x)*i,n===-1/0&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yt.y)return!1}else if(i=1/this.direction.y,r=(e.y-this.origin.y)*i,n=(t.y-this.origin.y)*i,n===-1/0&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zt.z)return!1}else if(i=1/this.direction.z,r=(e.z-this.origin.z)*i,n=(t.z-this.origin.z)*i,n===-1/0&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;return!0},t.prototype.intersectsBox=function(e){return this.intersectsBoxMinMax(e.minimum,e.maximum)},t.prototype.intersectsSphere=function(e){var t=e.center.x-this.origin.x,i=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=t*t+i*i+r*r,o=e.radius*e.radius;if(n<=o)return!0;var s=t*this.direction.x+i*this.direction.y+r*this.direction.z;return!(s<0)&&n-s*s<=o},t.prototype.intersectsTriangle=function(t,i,r){this._edge1||(this._edge1=e.Vector3.Zero(),this._edge2=e.Vector3.Zero(),this._pvec=e.Vector3.Zero(),this._tvec=e.Vector3.Zero(),this._qvec=e.Vector3.Zero()),i.subtractToRef(t,this._edge1),r.subtractToRef(t,this._edge2),e.Vector3.CrossToRef(this.direction,this._edge2,this._pvec);var n=e.Vector3.Dot(this._edge1,this._pvec);if(0===n)return null;var o=1/n;this.origin.subtractToRef(t,this._tvec);var s=e.Vector3.Dot(this._tvec,this._pvec)*o;if(s<0||s>1)return null;e.Vector3.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Vector3.Dot(this.direction,this._qvec)*o;if(a<0||s+a>1)return null;var l=e.Vector3.Dot(this._edge2,this._qvec)*o;return l>this.length?null:new e.IntersectionInfo(s,a,l)},t.prototype.intersectsPlane=function(t){var i,r=e.Vector3.Dot(t.normal,this.direction);if(Math.abs(r)<9.99999997475243e-7)return null;var n=e.Vector3.Dot(t.normal,this.origin);return i=(-t.d-n)/r,i<0?i<-9.99999997475243e-7?null:0:i},t.prototype.intersectsMesh=function(i,r){var n=e.Tmp.Matrix[0];return i.getWorldMatrix().invertToRef(n),this._tmpRay?t.TransformToRef(this,n,this._tmpRay):this._tmpRay=t.Transform(this,n),i.intersects(this._tmpRay,r)},t.prototype.intersectsMeshes=function(e,t,i){i?i.length=0:i=[];for(var r=0;rt.distance?1:0},t.prototype.intersectionSegment=function(i,r,n){var o,s,a,l,c=this.origin.add(this.direction.multiplyByFloats(t.rayl,t.rayl,t.rayl)),h=r.subtract(i),u=c.subtract(this.origin),d=i.subtract(this.origin),f=e.Vector3.Dot(h,h),p=e.Vector3.Dot(h,u),_=e.Vector3.Dot(u,u),m=e.Vector3.Dot(h,d),g=e.Vector3.Dot(u,d),v=f*_-p*p,y=v,b=v;vy&&(s=y,l=g+p,b=_)),l<0?(l=0,-m<0?s=0:-m>f?s=y:(s=-m,y=f)):l>b&&(l=b,-m+p<0?s=0:-m+p>f?s=y:(s=-m+p,y=f)),o=Math.abs(s)0&&a<=this.length&&T.lengthSquared()i.x+r)&&(!(i.x-r>t.x)&&(!(e.y>i.y+r)&&(!(i.y-r>t.y)&&(!(e.z>i.z+r)&&!(i.z-r>t.z)))))},i=(function(){var e={root:0,found:!1};return function(t,i,r,n){e.root=0,e.found=!1;var o=i*i-4*t*r;if(o<0)return e;var s=Math.sqrt(o),a=(-i-s)/(2*t),l=(-i+s)/(2*t);if(a>l){var c=l;l=a,a=c}return a>0&&a0&&l=0))},r.prototype._canDoCollision=function(i,r,n,o){var s=e.Vector3.Distance(this._basePointWorld,i),a=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+a+r)&&!!t(n,o,this._basePointWorld,this._velocityWorldLength+a)},r.prototype._testTriangle=function(t,r,n,o,s,a){var l,c=!1;r||(r=[]),r[t]||(r[t]=new e.Plane(0,0,0,0),r[t].copyFromPoints(n,o,s));var h=r[t];if(a||h.isFrontFacingTo(this._normalizedVelocity,0)){var u=h.signedDistanceTo(this._basePoint),d=e.Vector3.Dot(h.normal,this._velocity);if(0==d){if(Math.abs(u)>=1)return;c=!0,l=0}else{l=(-1-u)/d;var f=(1-u)/d;if(l>f){var p=f;f=l,l=p}if(l>1||f<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);var _=!1,m=1;if(c||(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(l,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,n,o,s,h.normal)&&(_=!0,m=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!_){var g=this._velocity.lengthSquared(),v=g;this._basePoint.subtractToRef(n,this._tempVector);var y=2*e.Vector3.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,x=i(v,y,b,m);x.found&&(m=x.root,_=!0,this._collisionPoint.copyFrom(n)),this._basePoint.subtractToRef(o,this._tempVector),y=2*e.Vector3.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,x=i(v,y,b,m),x.found&&(m=x.root,_=!0,this._collisionPoint.copyFrom(o)),this._basePoint.subtractToRef(s,this._tempVector),y=2*e.Vector3.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,x=i(v,y,b,m),x.found&&(m=x.root,_=!0,this._collisionPoint.copyFrom(s)),o.subtractToRef(n,this._edge),n.subtractToRef(this._basePoint,this._baseToVertex);var T=this._edge.lengthSquared(),E=e.Vector3.Dot(this._edge,this._velocity),P=e.Vector3.Dot(this._edge,this._baseToVertex);if(v=T*-g+E*E,y=T*(2*e.Vector3.Dot(this._velocity,this._baseToVertex))-2*E*P,b=T*(1-this._baseToVertex.lengthSquared())+P*P,x=i(v,y,b,m),x.found){var A=(E*x.root-P)/T;A>=0&&A<=1&&(m=x.root,_=!0,this._edge.scaleInPlace(A),n.addToRef(this._edge,this._collisionPoint))}s.subtractToRef(o,this._edge),o.subtractToRef(this._basePoint,this._baseToVertex),T=this._edge.lengthSquared(),E=e.Vector3.Dot(this._edge,this._velocity),P=e.Vector3.Dot(this._edge,this._baseToVertex),v=T*-g+E*E,y=T*(2*e.Vector3.Dot(this._velocity,this._baseToVertex))-2*E*P,b=T*(1-this._baseToVertex.lengthSquared())+P*P,x=i(v,y,b,m),x.found&&(A=(E*x.root-P)/T)>=0&&A<=1&&(m=x.root,_=!0,this._edge.scaleInPlace(A),o.addToRef(this._edge,this._collisionPoint)),n.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),T=this._edge.lengthSquared(),E=e.Vector3.Dot(this._edge,this._velocity),P=e.Vector3.Dot(this._edge,this._baseToVertex),v=T*-g+E*E,y=T*(2*e.Vector3.Dot(this._velocity,this._baseToVertex))-2*E*P,b=T*(1-this._baseToVertex.lengthSquared())+P*P,x=i(v,y,b,m),x.found&&(A=(E*x.root-P)/T)>=0&&A<=1&&(m=x.root,_=!0,this._edge.scaleInPlace(A),s.addToRef(this._edge,this._collisionPoint))}if(_){var M=m*this._velocity.length();(!this.collisionFound||M4)){++n._runningUpdated;var e={updatedMeshes:n._addUpdateMeshesList,updatedGeometries:n._addUpdateGeometriesList,removedGeometries:n._toRemoveGeometryArray,removedMeshes:n._toRemoveMeshesArray},i={payload:e,taskType:t.UPDATE},r=[];for(var o in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(o)&&(r.push(i.payload.updatedGeometries[o].indices.buffer),r.push(i.payload.updatedGeometries[o].normals.buffer),r.push(i.payload.updatedGeometries[o].positions.buffer));n._worker.postMessage(i,r),n._addUpdateMeshesList={},n._addUpdateGeometriesList={},n._toRemoveGeometryArray=[],n._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(r){var o=r.data;if(o.error!=i.SUCCESS)return void e.Tools.Warn("error returned from worker!");switch(o.taskType){case t.INIT:n._init=!0,n._scene.meshes.forEach((function(e){n.onMeshAdded(e)})),n._scene.getGeometries().forEach((function(e){n.onGeometryAdded(e)}));break;case t.UPDATE:n._runningUpdated--;break;case t.COLLIDE:var s=o.payload;if(!n._collisionsCallbackArray[s.collisionId])return;var a=n._collisionsCallbackArray[s.collisionId];if(a){var l=n._scene.getMeshByUniqueID(s.collidedMeshUniqueId);l&&a(s.collisionId,e.Vector3.FromArray(s.newPosition),l)}n._collisionsCallbackArray[s.collisionId]=null}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return r.prototype.getNewPosition=function(e,i,r,n,o,s,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(r._radius,this._scaledPosition),i.divideToRef(r._radius,this._scaledVelocity),this._collisionsCallbackArray[a]=s;var l={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:r._radius.asArray()},collisionId:a,excludedMeshUniqueId:o?o.uniqueId:null,maximumRetry:n},c={payload:l,taskType:t.COLLIDE};this._worker.postMessage(c)}},r.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var r=e.WorkerIncluded?e.Engine.CodeRepository+"Collisions/babylon.collisionWorker.js":URL.createObjectURL(new Blob([e.CollisionWorker],{type:"application/javascript"}));this._worker=new Worker(r),this._worker.onmessage=this._onMessageFromWorker;var n={payload:{},taskType:t.INIT};this._worker.postMessage(n)},r.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},r.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},r.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},r.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},r.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},r.SerializeMesh=function(t){var i=[];t.subMeshes&&(i=t.subMeshes.map((function(e,t){var i=e.getBoundingInfo();return{position:t,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:i.boundingSphere.centerWorld.asArray(),sphereRadius:i.boundingSphere.radiusWorld,boxMinimum:i.boundingBox.minimumWorld.asArray(),boxMaximum:i.boundingBox.maximumWorld.asArray()}})));var r=null;if(t instanceof e.Mesh){var n=t.geometry;r=n?n.id:null}else if(t instanceof e.InstancedMesh){var n=t.sourceMesh&&t.sourceMesh.geometry;r=n?n.id:null}var o=t.getBoundingInfo();return{uniqueId:t.uniqueId,id:t.id,name:t.name,geometryId:r,sphereCenter:o.boundingSphere.centerWorld.asArray(),sphereRadius:o.boundingSphere.radiusWorld,boxMinimum:o.boundingBox.minimumWorld.asArray(),boxMaximum:o.boundingBox.maximumWorld.asArray(),worldMatrixFromCache:t.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:t.checkCollisions}},r.SerializeGeometry=function(t){return{id:t.id,positions:new Float32Array(t.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(t.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Uint32Array(t.getIndices()||[])}},r})();e.CollisionCoordinatorWorker=r;var n=(function(){function t(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return t.prototype.getNewPosition=function(e,t,i,r,n,o,s){e.divideToRef(i._radius,this._scaledPosition),t.divideToRef(i._radius,this._scaledVelocity),i.collidedMesh=null,i._retry=0,i._initialVelocity=this._scaledVelocity,i._initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,r,this._finalPosition,n),this._finalPosition.multiplyInPlace(i._radius),o(s,this._finalPosition,i.collidedMesh)},t.prototype.init=function(e){this._scene=e},t.prototype.destroy=function(){},t.prototype.onMeshAdded=function(e){},t.prototype.onMeshUpdated=function(e){},t.prototype.onMeshRemoved=function(e){},t.prototype.onGeometryAdded=function(e){},t.prototype.onGeometryUpdated=function(e){},t.prototype.onGeometryDeleted=function(e){},t.prototype._collideWithWorld=function(t,i,r,n,o,s){void 0===s&&(s=null);var a=10*e.Engine.CollisionsEpsilon;if(r._retry>=n)return void o.copyFrom(t);var l=s?s.collisionMask:r.collisionMask;r._initialize(t,i,a);for(var c=0;c=n.lifeTime)return l._emitFromParticle(n),l.recycleParticle(n),o--,"continue";var s=n.age/n.lifeTime;l._colorGradients&&l._colorGradients.length>0?e.Tools.GetCurrentGradient(s,l._colorGradients,(function(t,i,r){t!==n._currentColorGradient&&(n._currentColor1.copyFrom(n._currentColor2),i.getColorToRef(n._currentColor2),n._currentColorGradient=t),e.Color4.LerpToRef(n._currentColor1,n._currentColor2,r,n.color)})):(n.colorStep.scaleToRef(l._scaledUpdateSpeed,l._scaledColorStep),n.color.addInPlace(l._scaledColorStep),n.color.a<0&&(n.color.a=0)),l._angularSpeedGradients&&l._angularSpeedGradients.length>0&&e.Tools.GetCurrentGradient(s,l._angularSpeedGradients,(function(t,i,r){t!==n._currentAngularSpeedGradient&&(n._currentAngularSpeed1=n._currentAngularSpeed2,n._currentAngularSpeed2=i.getFactor(),n._currentAngularSpeedGradient=t),n.angularSpeed=e.Scalar.Lerp(n._currentAngularSpeed1,n._currentAngularSpeed2,r)})),n.angle+=n.angularSpeed*l._scaledUpdateSpeed;var a=l._scaledUpdateSpeed;if(l._velocityGradients&&l._velocityGradients.length>0&&e.Tools.GetCurrentGradient(s,l._velocityGradients,(function(t,i,r){t!==n._currentVelocityGradient&&(n._currentVelocity1=n._currentVelocity2,n._currentVelocity2=i.getFactor(),n._currentVelocityGradient=t),a*=e.Scalar.Lerp(n._currentVelocity1,n._currentVelocity2,r)})),n.direction.scaleToRef(a,l._scaledDirection),n.position.addInPlace(l._scaledDirection),i&&r){var c=e.Tmp.Vector3[0],h=e.Tmp.Vector3[1];l._emitterWorldMatrix.getTranslationToRef(h),n.position.subtractToRef(h,c);var u=l._fetchR(c.y,c.z,r.width,r.height,i),d=l._fetchR(c.x+.33,c.z+.33,r.width,r.height,i),f=l._fetchR(c.x-.33,c.y-.33,r.width,r.height,i),p=e.Tmp.Vector3[0],_=e.Tmp.Vector3[1];p.copyFromFloats((2*u-1)*l.noiseStrength.x,(2*d-1)*l.noiseStrength.y,(2*f-1)*l.noiseStrength.z),p.scaleToRef(l._scaledUpdateSpeed,_),n.direction.addInPlace(_)}l.gravity.scaleToRef(l._scaledUpdateSpeed,l._scaledGravity),n.direction.addInPlace(l._scaledGravity),l._sizeGradients&&l._sizeGradients.length>0&&e.Tools.GetCurrentGradient(s,l._sizeGradients,(function(t,i,r){t!==n._currentSizeGradient&&(n._currentSize1=n._currentSize2,n._currentSize2=i.getFactor(),n._currentSizeGradient=t),n.size=e.Scalar.Lerp(n._currentSize1,n._currentSize2,r)})),l._isAnimationSheetEnabled&&n.updateCellIndex()})()}}return t.prototype.getColorGradients=function(){return this._colorGradients},t.prototype.getSizeGradients=function(){return this._sizeGradients},t.prototype.getLifeTimeGradients=function(){return this._lifeTimeGradients},t.prototype.getAngularSpeedGradients=function(){return this._angularSpeedGradients},t.prototype.getVelocityGradients=function(){return this._velocityGradients},Object.defineProperty(t.prototype,"direction1",{get:function(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction2",{get:function(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minEmitBox",{get:function(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxEmitBox",{get:function(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isAnimationSheetEnabled",{get:function(){return this._isAnimationSheetEnabled},set:function(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._resetEffect())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isBillboardBased",{get:function(){return this._isBillboardBased},set:function(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._resetEffect())},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},Object.defineProperty(t.prototype,"particles",{get:function(){return this._particles},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"ParticleSystem"},t.prototype._fetchR=function(e,t,i,r,n){return e=.5*Math.abs(e)+.5,t=.5*Math.abs(t)+.5,n[4*((e*i%i|0)+(t*r%r|0)*i)]/255},t.prototype._addFactorGradient=function(t,i,r,n){var o=new e.FactorGradient;o.gradient=i,o.factor1=r,o.factor2=n,t.push(o),t.sort((function(e,t){return e.gradientt.gradient?1:0}))},t.prototype._removeFactorGradient=function(e,t){if(e)for(var i=0,r=0,n=e;rt.gradient?1:0})),this},t.prototype.removeColorGradient=function(e){if(!this._colorGradients)return this;for(var t=0,i=0,r=this._colorGradients;i0,this.emitter.position){var i=this.emitter;this._emitterWorldMatrix=i.getWorldMatrix()}else{var r=this.emitter;this._emitterWorldMatrix=e.Matrix.Translation(r.x,r.y,r.z)}this.updateFunction(this._particles);for(var n,o,s=this,a=0;a0){var i=e.Scalar.Clamp(s._actualFrame/s.targetStopDuration);e.Tools.GetCurrentGradient(i,s._lifeTimeGradients,(function(t,r,o){var s=t,a=r,l=s.getFactor(),c=a.getFactor(),h=(i-s.gradient)/(a.gradient-s.gradient);n.lifeTime=e.Scalar.Lerp(l,c,h)}))}else n.lifeTime=e.Scalar.RandomRange(s.minLifeTime,s.maxLifeTime);s._sizeGradients&&0!==s._sizeGradients.length?(n._currentSizeGradient=s._sizeGradients[0],n._currentSize1=n._currentSizeGradient.getFactor(),n.size=n._currentSize1,s._sizeGradients.length>1?n._currentSize2=s._sizeGradients[1].getFactor():n._currentSize2=n._currentSize1):n.size=e.Scalar.RandomRange(s.minSize,s.maxSize),n.scale.copyFromFloats(e.Scalar.RandomRange(s.minScaleX,s.maxScaleX),e.Scalar.RandomRange(s.minScaleY,s.maxScaleY)),s._angularSpeedGradients&&0!==s._angularSpeedGradients.length?(n._currentAngularSpeedGradient=s._angularSpeedGradients[0],n.angularSpeed=n._currentAngularSpeedGradient.getFactor(),n._currentAngularSpeed1=n.angularSpeed,s._angularSpeedGradients.length>1?n._currentAngularSpeed2=s._angularSpeedGradients[1].getFactor():n._currentAngularSpeed2=n._currentAngularSpeed1):n.angularSpeed=e.Scalar.RandomRange(s.minAngularSpeed,s.maxAngularSpeed),n.angle=e.Scalar.RandomRange(s.minInitialRotation,s.maxInitialRotation),s._velocityGradients&&s._velocityGradients.length>0&&(n._currentVelocityGradient=s._velocityGradients[0],n._currentVelocity1=n._currentVelocityGradient.getFactor(),s._velocityGradients.length>1?n._currentVelocity2=s._velocityGradients[1].getFactor():n._currentVelocity2=n._currentVelocity1),s._colorGradients&&0!==s._colorGradients.length?(n._currentColorGradient=s._colorGradients[0],n._currentColorGradient.getColorToRef(n.color),n._currentColor1.copyFrom(n.color),s._colorGradients.length>1?s._colorGradients[1].getColorToRef(n._currentColor2):n._currentColor2.copyFrom(n.color)):(o=e.Scalar.RandomRange(0,1),e.Color4.LerpToRef(s.color1,s.color2,o,n.color),s.colorDead.subtractToRef(n.color,s._colorDiff),s._colorDiff.scaleToRef(1/n.lifeTime,n.colorStep)),s._isAnimationSheetEnabled&&(n._initialStartSpriteCellID=s.startSpriteCellID,n._initialEndSpriteCellID=s.endSpriteCellID)})())break}},t._GetAttributeNamesOrOptions=function(t,i){void 0===t&&(t=!1),void 0===i&&(i=!1);var r=[e.VertexBuffer.PositionKind,e.VertexBuffer.ColorKind,"angle","offset","size"];return t&&r.push("cellIndex"),i||r.push("direction"),r},t._GetEffectCreationOptions=function(e){void 0===e&&(e=!1);var t=["invView","view","projection","vClipPlane","textureMask","translationPivot","eyePosition"];return e&&t.push("particlesInfos"),t},t.prototype._getEffect=function(){if(this._customEffect)return this._customEffect;var i=[];if(this._scene.clipPlane&&i.push("#define CLIPPLANE"),this._isAnimationSheetEnabled&&i.push("#define ANIMATESHEET"),this._isBillboardBased)switch(i.push("#define BILLBOARD"),this.billboardMode){case e.AbstractMesh.BILLBOARDMODE_Y:i.push("#define BILLBOARDY");break;case e.AbstractMesh.BILLBOARDMODE_ALL:}var r=i.join("\n");if(this._cachedDefines!==r){this._cachedDefines=r;var n=t._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased),o=t._GetEffectCreationOptions(this._isAnimationSheetEnabled);this._effect=this._scene.getEngine().createEffect("particles",n,o,["diffuseSampler"],r)}return this._effect},t.prototype.animate=function(e){if(void 0===e&&(e=!1),this._started){if(!e){var t=this._getEffect();if(!(this.emitter&&t.isReady()&&this.particleTexture&&this.particleTexture.isReady()))return;if(this._currentRenderId===this._scene.getRenderId())return;this._currentRenderId=this._scene.getRenderId()}this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:this._scene.getAnimationRatio());var i;if(this.manualEmitCount>-1?(i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0):(i=this.emitRate*this._scaledUpdateSpeed>>0,this._newPartsExcess+=this.emitRate*this._scaledUpdateSpeed-i),this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene._toBeDisposed.push(this))),!e){for(var r=0,n=0;n-1&&this._scene.particleSystems.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.prototype.createPointEmitter=function(t,i){var r=new e.PointParticleEmitter;return r.direction1=t,r.direction2=i,this.particleEmitterType=r,r},t.prototype.createHemisphericEmitter=function(t,i){void 0===t&&(t=1),void 0===i&&(i=1) +;var r=new e.HemisphericParticleEmitter(t,i);return this.particleEmitterType=r,r},t.prototype.createSphereEmitter=function(t,i){void 0===t&&(t=1),void 0===i&&(i=1);var r=new e.SphereParticleEmitter(t,i);return this.particleEmitterType=r,r},t.prototype.createDirectedSphereEmitter=function(t,i,r){void 0===t&&(t=1),void 0===i&&(i=new e.Vector3(0,1,0)),void 0===r&&(r=new e.Vector3(0,1,0));var n=new e.SphereDirectedParticleEmitter(t,i,r);return this.particleEmitterType=n,n},t.prototype.createConeEmitter=function(t,i){void 0===t&&(t=1),void 0===i&&(i=Math.PI/4);var r=new e.ConeParticleEmitter(t,i);return this.particleEmitterType=r,r},t.prototype.createBoxEmitter=function(t,i,r,n){var o=new e.BoxParticleEmitter;return this.particleEmitterType=o,this.direction1=t,this.direction2=i,this.minEmitBox=r,this.maxEmitBox=n,o},t.prototype.clone=function(i,r){var n=null,o=null;if(null!=this.customShader){o=this.customShader;var s=o.shaderOptions.defines.length>0?o.shaderOptions.defines.join("\n"):"";n=this._scene.getEngine().createEffectForParticles(o.shaderPath.fragmentElement,o.shaderOptions.uniforms,o.shaderOptions.samplers,s)}else this._customEffect&&(n=this._customEffect);var a=new t(i,this._capacity,this._scene,n);return a.customShader=o,e.Tools.DeepCopy(this,a,["particles","customShader"]),void 0===r&&(r=this.emitter),a.emitter=r,this.particleTexture&&(a.particleTexture=new e.Texture(this.particleTexture.url,this._scene)),this.preventAutoStart||a.start(),a},t.prototype.serialize=function(){var e={};return t._Serialize(e,this),e.textureMask=this.textureMask.asArray(),e.customShader=this.customShader,e.preventAutoStart=this.preventAutoStart,e.isAnimationSheetEnabled=this._isAnimationSheetEnabled,e},t._Serialize=function(t,i){if(t.name=i.name,t.id=i.id,t.capacity=i.getCapacity(),i.emitter.position){var r=i.emitter;t.emitterId=r.id}else{var n=i.emitter;t.emitter=n.asArray()}i.particleEmitterType&&(t.particleEmitterType=i.particleEmitterType.serialize()),i.particleTexture&&(t.textureName=i.particleTexture.name),e.Animation.AppendSerializedAnimations(i,t),t.renderingGroupId=i.renderingGroupId,t.isBillboardBased=i.isBillboardBased,t.minAngularSpeed=i.minAngularSpeed,t.maxAngularSpeed=i.maxAngularSpeed,t.minSize=i.minSize,t.maxSize=i.maxSize,t.minScaleX=i.minScaleX,t.maxScaleX=i.maxScaleX,t.minScaleY=i.minScaleY,t.maxScaleY=i.maxScaleY,t.minEmitPower=i.minEmitPower,t.maxEmitPower=i.maxEmitPower,t.minLifeTime=i.minLifeTime,t.maxLifeTime=i.maxLifeTime,t.emitRate=i.emitRate,t.gravity=i.gravity.asArray(),t.noiseStrength=i.noiseStrength.asArray(),t.color1=i.color1.asArray(),t.color2=i.color2.asArray(),t.colorDead=i.colorDead.asArray(),t.updateSpeed=i.updateSpeed,t.targetStopDuration=i.targetStopDuration,t.blendMode=i.blendMode,t.preWarmCycles=i.preWarmCycles,t.preWarmStepOffset=i.preWarmStepOffset,t.minInitialRotation=i.minInitialRotation,t.maxInitialRotation=i.maxInitialRotation,t.startSpriteCellID=i.startSpriteCellID,t.endSpriteCellID=i.endSpriteCellID,t.spriteCellChangeSpeed=i.spriteCellChangeSpeed,t.spriteCellWidth=i.spriteCellWidth,t.spriteCellHeight=i.spriteCellHeight;var o=i.getColorGradients();if(o){t.colorGradients=[];for(var s=0,a=o;s0?a.shaderOptions.defines.join("\n"):"";s=r.getEngine().createEffectForParticles(a.shaderPath.fragmentElement,a.shaderOptions.uniforms,a.shaderOptions.samplers,l)}var c=new t(o,i.capacity,r,s,i.isAnimationSheetEnabled);return c.customShader=a,i.id&&(c.id=i.id),i.preventAutoStart&&(c.preventAutoStart=i.preventAutoStart),t._Parse(i,c,r,n),c.textureMask=e.Color4.FromArray(i.textureMask),c.preventAutoStart||c.start(),c},t.BLENDMODE_ONEONE=0,t.BLENDMODE_STANDARD=1,t.BLENDMODE_ADD=2,t})();e.ParticleSystem=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.direction1=new e.Vector3(0,1,0),this.direction2=new e.Vector3(0,1,0),this.minEmitBox=new e.Vector3(-.5,-.5,-.5),this.maxEmitBox=new e.Vector3(.5,.5,.5)}return t.prototype.startDirectionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.direction1.x,this.direction2.x),o=e.Scalar.RandomRange(this.direction1.y,this.direction2.y),s=e.Scalar.RandomRange(this.direction1.z,this.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(n,o,s,t,i)},t.prototype.startPositionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),o=e.Scalar.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),s=e.Scalar.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);e.Vector3.TransformCoordinatesFromFloatsToRef(n,o,s,t,i)},t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)},t.prototype.getEffectDefines=function(){return"#define BOXEMITTER"},t.prototype.getClassName=function(){return"BoxParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e},t.prototype.parse=function(t){e.Vector3.FromArrayToRef(t.direction1,0,this.direction1),e.Vector3.FromArrayToRef(t.direction2,0,this.direction2),e.Vector3.FromArrayToRef(t.minEmitBox,0,this.minEmitBox),e.Vector3.FromArrayToRef(t.maxEmitBox,0,this.maxEmitBox)},t})();e.BoxParticleEmitter=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i){void 0===e&&(e=1),void 0===t&&(t=Math.PI),void 0===i&&(i=0),this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}return Object.defineProperty(t.prototype,"radius",{get:function(){return this._radius},set:function(e){this._radius=e,this._buildHeight()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._buildHeight()},enumerable:!0,configurable:!0}),t.prototype._buildHeight=function(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1},t.prototype.startDirectionFunction=function(t,i,r){if(1===Math.abs(Math.cos(this._angle)))e.Vector3.TransformNormalFromFloatsToRef(0,1,0,t,i);else{var n=r.position.subtract(t.getTranslation()).normalize(),o=e.Scalar.RandomRange(0,this.directionRandomizer),s=e.Scalar.RandomRange(0,this.directionRandomizer),a=e.Scalar.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=s,n.z+=a,n.normalize(),e.Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,t,i)}},t.prototype.startPositionFunction=function(t,i,r){var n,o=e.Scalar.RandomRange(0,2*Math.PI);this.emitFromSpawnPointOnly?n=1e-4:(n=e.Scalar.RandomRange(0,this.heightRange),n=1-n*n);var s=this._radius-e.Scalar.RandomRange(0,this._radius*this.radiusRange);s*=n;var a=s*Math.sin(o),l=s*Math.cos(o),c=n*this._height;e.Vector3.TransformCoordinatesFromFloatsToRef(a,c,l,t,i)},t.prototype.clone=function(){var i=new t(this._radius,this._angle,this.directionRandomizer);return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)},t.prototype.getEffectDefines=function(){var e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e},t.prototype.getClassName=function(){return"ConeParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e},t.prototype.parse=function(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer},t})();e.ConeParticleEmitter=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return t.prototype.startDirectionFunction=function(t,i,r){var n=r.position.subtract(t.getTranslation()).normalize(),o=e.Scalar.RandomRange(0,this.directionRandomizer),s=e.Scalar.RandomRange(0,this.directionRandomizer),a=e.Scalar.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=s,n.z+=a,n.normalize(),e.Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,t,i)},t.prototype.startPositionFunction=function(t,i,r){var n=this.radius-e.Scalar.RandomRange(0,this.radius*this.radiusRange),o=e.Scalar.RandomRange(0,1),s=e.Scalar.RandomRange(0,2*Math.PI),a=Math.acos(2*o-1),l=n*Math.cos(s)*Math.sin(a),c=n*Math.cos(a),h=n*Math.sin(s)*Math.sin(a);e.Vector3.TransformCoordinatesFromFloatsToRef(l,c,h,t,i)},t.prototype.clone=function(){var i=new t(this.radius,this.directionRandomizer);return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},t.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER"},t.prototype.getClassName=function(){return"SphereParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},t.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},t})();e.SphereParticleEmitter=t;var i=(function(t){function i(i,r,n){void 0===i&&(i=1),void 0===r&&(r=new e.Vector3(0,1,0)),void 0===n&&(n=new e.Vector3(0,1,0));var o=t.call(this,i)||this;return o.direction1=r,o.direction2=n,o}return o(i,t),i.prototype.startDirectionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.direction1.x,this.direction2.x),o=e.Scalar.RandomRange(this.direction1.y,this.direction2.y),s=e.Scalar.RandomRange(this.direction1.z,this.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(n,o,s,t,i)},i.prototype.clone=function(){var t=new i(this.radius,this.direction1,this.direction2);return e.Tools.DeepCopy(this,t),t},i.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},i.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"},i.prototype.getClassName=function(){return"SphereDirectedParticleEmitter"},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e},i.prototype.parse=function(e){t.prototype.parse.call(this,e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)},i})(t);e.SphereDirectedParticleEmitter=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return t.prototype.startDirectionFunction=function(t,i,r){var n=r.position.subtract(t.getTranslation()).normalize(),o=e.Scalar.RandomRange(0,this.directionRandomizer),s=e.Scalar.RandomRange(0,this.directionRandomizer),a=e.Scalar.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=s,n.z+=a,n.normalize(),e.Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,t,i)},t.prototype.startPositionFunction=function(t,i,r){var n=this.radius-e.Scalar.RandomRange(0,this.radius*this.radiusRange),o=e.Scalar.RandomRange(0,1),s=e.Scalar.RandomRange(0,2*Math.PI),a=Math.acos(2*o-1),l=n*Math.cos(s)*Math.sin(a),c=n*Math.cos(a),h=n*Math.sin(s)*Math.sin(a);e.Vector3.TransformCoordinatesFromFloatsToRef(l,Math.abs(c),h,t,i)},t.prototype.clone=function(){var i=new t(this.radius,this.directionRandomizer);return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},t.prototype.getEffectDefines=function(){return"#define HEMISPHERICEMITTER"},t.prototype.getClassName=function(){return"HemisphericParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},t.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},t})();e.HemisphericParticleEmitter=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.direction1=new e.Vector3(0,1,0),this.direction2=new e.Vector3(0,1,0)}return t.prototype.startDirectionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.direction1.x,this.direction2.x),o=e.Scalar.RandomRange(this.direction1.y,this.direction2.y),s=e.Scalar.RandomRange(this.direction1.z,this.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(n,o,s,t,i)},t.prototype.startPositionFunction=function(t,i,r){e.Vector3.TransformCoordinatesFromFloatsToRef(0,0,0,t,i)},t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},t.prototype.getEffectDefines=function(){return"#define POINTEMITTER"},t.prototype.getClassName=function(){return"PointParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e},t.prototype.parse=function(t){e.Vector3.FromArrayToRef(t.direction1,0,this.direction1),e.Vector3.FromArrayToRef(t.direction2,0,this.direction2)},t})();e.PointParticleEmitter=t})(r||(r={}));var r;!(function(e){e.AbstractScene.AddParser(e.SceneComponentConstants.NAME_PARTICLESYSTEM,(function(t,i,r,n){var o=e.AbstractScene.GetIndividualParser(e.SceneComponentConstants.NAME_PARTICLESYSTEM);if(o&&void 0!==t.particleSystems&&null!==t.particleSystems)for(var s=0,a=t.particleSystems.length;s4&&(s.push(e.VertexBuffer.MatricesIndicesExtraKind),s.push(e.VertexBuffer.MatricesWeightsExtraKind)),o.push("#define NUM_BONE_INFLUENCERS "+t.numBoneInfluencers),o.push("#define BonesPerMesh "+(t.skeleton.bones.length+1)),a.addCPUSkinningFallback(0,t),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones")):o.push("#define NUM_BONE_INFLUENCERS 0");for(var c in this._textures)if(!this._textures[c].isReady())return!1;t&&this._shouldTurnAlphaTestOn(t)&&o.push("#define ALPHATEST");var h=this._effect,u=o.join("\n");return this._effect=n.createEffect(this._shaderPath,{attributes:s,uniformsNames:this._options.uniforms,uniformBuffersNames:this._options.uniformBuffers,samplers:this._options.samplers,defines:u,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError},n),!!this._effect.isReady()&&(h!==this._effect&&r.resetCachedMaterial(),this._renderId=r.getRenderId(),!0)},i.prototype.bindOnlyWorldMatrix=function(e){var t=this.getScene();this._effect&&(-1!==this._options.uniforms.indexOf("world")&&this._effect.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),this._effect.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&this._effect.setMatrix("worldViewProjection",e.multiply(t.getTransformMatrix())))},i.prototype.bind=function(t,i){if(this.bindOnlyWorldMatrix(t),this._effect&&this.getScene().getCachedMaterial()!==this){-1!==this._options.uniforms.indexOf("view")&&this._effect.setMatrix("view",this.getScene().getViewMatrix()),-1!==this._options.uniforms.indexOf("projection")&&this._effect.setMatrix("projection",this.getScene().getProjectionMatrix()),-1!==this._options.uniforms.indexOf("viewProjection")&&this._effect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.MaterialHelper.BindBonesParameters(i,this._effect);var r;for(r in this._textures)this._effect.setTexture(r,this._textures[r]);for(r in this._textureArrays)this._effect.setTextureArray(r,this._textureArrays[r]);for(r in this._ints)this._effect.setInt(r,this._ints[r]);for(r in this._floats)this._effect.setFloat(r,this._floats[r]);for(r in this._floatsArrays)this._effect.setArray(r,this._floatsArrays[r]);for(r in this._colors3)this._effect.setColor3(r,this._colors3[r]);for(r in this._colors3Arrays)this._effect.setArray3(r,this._colors3Arrays[r]);for(r in this._colors4){var n=this._colors4[r];this._effect.setFloat4(r,n.r,n.g,n.b,n.a)}for(r in this._vectors2)this._effect.setVector2(r,this._vectors2[r]);for(r in this._vectors3)this._effect.setVector3(r,this._vectors3[r]);for(r in this._vectors4)this._effect.setVector4(r,this._vectors4[r]);for(r in this._matrices)this._effect.setMatrix(r,this._matrices[r]);for(r in this._matrices3x3)this._effect.setMatrix3x3(r,this._matrices3x3[r]);for(r in this._matrices2x2)this._effect.setMatrix2x2(r,this._matrices2x2[r]);for(r in this._vectors2Arrays)this._effect.setArray2(r,this._vectors2Arrays[r]);for(r in this._vectors3Arrays)this._effect.setArray3(r,this._vectors3Arrays[r])}this._afterBind(i)},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);for(var i in this._textures)e.push(this._textures[i]);for(var i in this._textureArrays)for(var r=this._textureArrays[i],n=0;nthis._maxX||ithis._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var s=this._getFacetAt(t,i),a=-(s.x*t+s.z*i+s.w)/s.y;return e.Vector3.TransformCoordinatesFromFloatsToRef(0,a,0,r,o),o.y},i.prototype.getNormalAtCoordinates=function(t,i){var r=new e.Vector3(0,1,0);return this.getNormalAtCoordinatesToRef(t,i,r),r},i.prototype.getNormalAtCoordinatesToRef=function(t,i,r){var n=this.getWorldMatrix(),o=e.Tmp.Matrix[5];n.invertToRef(o);var s=e.Tmp.Vector3[8];if(e.Vector3.TransformCoordinatesFromFloatsToRef(t,0,i,o,s),t=s.x,i=s.z,tthis._maxX||ithis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var a=this._getFacetAt(t,i);return e.Vector3.TransformNormalFromFloatsToRef(a.x,a.y,a.z,n,r),this},i.prototype.updateCoordinateHeights=function(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this},i.prototype._getFacetAt=function(e,t){var i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),n=this._heightQuads[r*this._subdivisionsX+i];return t=0;s--){var a=t[s],l=a.getParent();if(l){var c=this._debugLines[n];c||(c=[e.Vector3.Zero(),e.Vector3.Zero()],this._debugLines[n]=c),a.getAbsolutePositionToRef(this.mesh,c[0]),l.getAbsolutePositionToRef(this.mesh,c[1]),c[0].subtractInPlace(o),c[1].subtractInPlace(o),n++}}},t.prototype.update=function(){this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteTransforms(),void 0===this.skeleton.bones[0].length?this._getLinesForBonesNoLength(this.skeleton.bones,this.mesh.getWorldMatrix()):this._getLinesForBonesWithLength(this.skeleton.bones,this.mesh.getWorldMatrix()),this._debugMesh?e.MeshBuilder.CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:this._debugMesh},this._scene):(this._debugMesh=e.MeshBuilder.CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:null},this._scene),this._debugMesh.renderingGroupId=this.renderingGroupId),this._debugMesh.position.copyFrom(this.mesh.position),this._debugMesh.color=this.color},t.prototype.dispose=function(){this._debugMesh&&(this.isEnabled=!1,this._debugMesh.dispose(),this._debugMesh=null)},t})();t.SkeletonViewer=i})(e.Debug||(e.Debug={}))})(r||(r={}));var r;!(function(e){!(function(t){var i=(function(){function t(t,i){void 0===i&&(i=1),this._xline=[e.Vector3.Zero(),e.Vector3.Zero()],this._yline=[e.Vector3.Zero(),e.Vector3.Zero()],this._zline=[e.Vector3.Zero(),e.Vector3.Zero()],this.scaleLines=1,this.scaleLines=i,this._xmesh=e.Mesh.CreateLines("xline",this._xline,t,!0),this._ymesh=e.Mesh.CreateLines("yline",this._yline,t,!0),this._zmesh=e.Mesh.CreateLines("zline",this._zline,t,!0),this._xmesh.renderingGroupId=2,this._ymesh.renderingGroupId=2,this._zmesh.renderingGroupId=2,this._xmesh.material.checkReadyOnlyOnce=!0,this._xmesh.color=new e.Color3(1,0,0),this._ymesh.material.checkReadyOnlyOnce=!0,this._ymesh.color=new e.Color3(0,1,0),this._zmesh.material.checkReadyOnlyOnce=!0,this._zmesh.color=new e.Color3(0,0,1),this.scene=t}return t.prototype.update=function(t,i,r,n){var o=this.scaleLines;this._xmesh&&this._xmesh.position.copyFrom(t),this._ymesh&&this._ymesh.position.copyFrom(t),this._zmesh&&this._zmesh.position.copyFrom(t);var s=this._xline[1];s.x=i.x*o,s.y=i.y*o,s.z=i.z*o,e.Mesh.CreateLines("",this._xline,null,!1,this._xmesh),s=this._yline[1],s.x=r.x*o,s.y=r.y*o,s.z=r.z*o,e.Mesh.CreateLines("",this._yline,null,!1,this._ymesh),s=this._zline[1],s.x=n.x*o,s.y=n.y*o,s.z=n.z*o,e.Mesh.CreateLines("",this._zline,null,!1,this._zmesh)},t.prototype.dispose=function(){this._xmesh&&this._xmesh.dispose(),this._ymesh&&this._ymesh.dispose(),this._zmesh&&this._zmesh.dispose(),this._xmesh=null,this._ymesh=null,this._zmesh=null,this.scene=null},t})();t.AxesViewer=i})(e.Debug||(e.Debug={}))})(r||(r={}));var r;!(function(e){!(function(t){var i=(function(t){function i(i,r,n,o){void 0===o&&(o=1);var s=t.call(this,i,o)||this;return s.pos=e.Vector3.Zero(),s.xaxis=e.Vector3.Zero(),s.yaxis=e.Vector3.Zero(),s.zaxis=e.Vector3.Zero(),s.mesh=n,s.bone=r,s}return o(i,t),i.prototype.update=function(){if(this.mesh&&this.bone){var i=this.bone;i.getAbsolutePositionToRef(this.mesh,this.pos),i.getDirectionToRef(e.Axis.X,this.mesh,this.xaxis),i.getDirectionToRef(e.Axis.Y,this.mesh,this.yaxis),i.getDirectionToRef(e.Axis.Z,this.mesh,this.zaxis),t.prototype.update.call(this,this.pos,this.xaxis,this.yaxis,this.zaxis)}},i.prototype.dispose=function(){this.mesh&&(this.mesh=null,this.bone=null,t.prototype.dispose.call(this))},i})(t.AxesViewer);t.BoneAxesViewer=i})(e.Debug||(e.Debug={}))})(r||(r={}));var r;!(function(e){var t=(function(){function t(e){this.ray=e}return t.CreateAndShow=function(e,i,r){var n=new t(e);return n.show(i,r),n},t.prototype.show=function(t,i){if(!this._renderFunction&&this.ray){var r=this.ray;this._renderFunction=this._render.bind(this),this._scene=t,this._renderPoints=[r.origin,r.origin.add(r.direction.scale(r.length))],this._renderLine=e.Mesh.CreateLines("ray",this._renderPoints,t,!0),this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}i&&this._renderLine&&this._renderLine.color.copyFrom(i)},t.prototype.hide=function(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])},t.prototype._render=function(){var t=this.ray;if(t){var i=this._renderPoints[1],r=Math.min(t.length,1e6);i.copyFrom(t.direction),i.scaleInPlace(r),i.addInPlace(t.origin),e.Mesh.CreateLines("ray",this._renderPoints,this._scene,!0,this._renderLine)}},t.prototype.attachToMesh=function(t,i,r,n){this._attachedToMesh=t;var o=this.ray;o&&(o.direction||(o.direction=e.Vector3.Zero()),o.origin||(o.origin=e.Vector3.Zero()),n&&(o.length=n),r||(r=e.Vector3.Zero()),i||(i=new e.Vector3(0,0,-1)),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(i),this._meshSpaceOrigin.copyFrom(r)):(this._meshSpaceDirection=i.clone(),this._meshSpaceOrigin=r.clone()),this._updateToMeshFunction||(this._updateToMeshFunction=this._updateToMesh.bind(this),this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction)),this._updateToMesh())},t.prototype.detachFromMesh=function(){this._attachedToMesh&&(this._updateToMeshFunction&&this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction),this._attachedToMesh=null,this._updateToMeshFunction=null)},t.prototype._updateToMesh=function(){var t=this.ray;if(this._attachedToMesh&&t){if(this._attachedToMesh._isDisposed)return void this.detachFromMesh();this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,t.direction),e.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),t.origin)}},t.prototype.dispose=function(){this.hide(),this.detachFromMesh(),this.ray=null},t})();e.RayHelper=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){this.BJSINSPECTOR="undefined"!=typeof INSPECTOR?INSPECTOR:void 0,this.onPropertyChangedObservable=new e.Observable,this._scene=t}return t.prototype._createInspector=function(e){void 0===e&&(e={});var t=e.popup||!1,i=e.initialTab||0,r=e.parentElement||null;this._inspector||(this.BJSINSPECTOR=this.BJSINSPECTOR||"undefined"!=typeof INSPECTOR?INSPECTOR:void 0,this._inspector=new this.BJSINSPECTOR.Inspector(this._scene,t,i,r,e.newColors))},t.prototype.isVisible=function(){return!!this._inspector},t.prototype.hide=function(){if(this._inspector){try{this._inspector.dispose()}catch(e){}this.onPropertyChangedObservable.clear(),this._inspector=null}},t.prototype.show=function(i){void 0===i&&(i={}),void 0===this.BJSINSPECTOR?e.Tools.LoadScript(t.InspectorURL,this._createInspector.bind(this,i)):this._createInspector(i)},t.prototype.getActiveTab=function(){return this._inspector?this._inspector.getActiveTabIndex():-1},t.InspectorURL="https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js",t})();e.DebugLayer=t})(r||(r={}));var r;!(function(e){!(function(t){var i=(function(){function t(t){this._impostors=[],this._meshes=[],this._numMeshes=0,this._scene=t||e.Engine.LastCreatedScene;var i=this._scene.getPhysicsEngine();i&&(this._physicsEnginePlugin=i.getPhysicsPlugin())}return t.prototype._updateDebugMeshes=function(){for(var e=this._physicsEnginePlugin,t=0;t0?(this._meshes[i]=this._meshes[this._numMeshes],this._impostors[i]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}},t.prototype._getDebugMaterial=function(t){return this._debugMaterial||(this._debugMaterial=new e.StandardMaterial("",t),this._debugMaterial.wireframe=!0),this._debugMaterial},t.prototype._getDebugBoxMesh=function(t){return this._debugBoxMesh||(this._debugBoxMesh=e.MeshBuilder.CreateBox("physicsBodyBoxViewMesh",{size:1},t),this._debugBoxMesh.renderingGroupId=1,this._debugBoxMesh.rotationQuaternion=e.Quaternion.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(t),t.removeMesh(this._debugBoxMesh)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")},t.prototype._getDebugSphereMesh=function(t){return this._debugSphereMesh||(this._debugSphereMesh=e.MeshBuilder.CreateSphere("physicsBodySphereViewMesh",{diameter:1},t),this._debugSphereMesh.renderingGroupId=1,this._debugSphereMesh.rotationQuaternion=e.Quaternion.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(t),t.removeMesh(this._debugSphereMesh)),this._debugSphereMesh.createInstance("physicsBodyBoxViewInstance")},t.prototype._getDebugMesh=function(t,i){var r=null;if(t.type==e.PhysicsImpostor.BoxImpostor)r=this._getDebugBoxMesh(i),t.getBoxSizeToRef(r.scaling);else if(t.type==e.PhysicsImpostor.SphereImpostor){r=this._getDebugSphereMesh(i);var n=t.getRadius();r.scaling.x=2*n,r.scaling.y=2*n,r.scaling.z=2*n}return r},t.prototype.dispose=function(){for(var e=0;e1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction1",{get:function(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction2",{get:function(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minEmitBox",{get:function(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxEmitBox",{get:function(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)},enumerable:!0,configurable:!0}),t.prototype.getCapacity=function(){return this._capacity},Object.defineProperty(t.prototype,"activeParticleCount",{get:function(){return this._activeCount},set:function(e){this._activeCount=Math.min(e,this._capacity)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isAnimationSheetEnabled",{get:function(){return this._isAnimationSheetEnabled},enumerable:!0,configurable:!0}),t.prototype.isReady=function(){return this._updateEffect?!!(this.emitter&&this._updateEffect.isReady()&&this._renderEffect.isReady()&&this.particleTexture&&this.particleTexture.isReady()):(this._recreateUpdateEffect(),this._recreateRenderEffect(),!1)},t.prototype.isStarted=function(){return this._started},t.prototype.start=function(e){var t=this;if(void 0===e&&(e=0),e)return void setTimeout((function(){t.start(0)}),e);this._started=!0,this._stopped=!1,this._preWarmDone=!1},t.prototype.stop=function(){this._stopped=!0},t.prototype.reset=function(){this._releaseBuffers(),this._releaseVAOs(),this._currentActiveCount=0,this._targetIndex=0},t.prototype.getClassName=function(){return"GPUParticleSystem"},Object.defineProperty(t.prototype,"isBillboardBased",{get:function(){return this._isBillboardBased},set:function(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._releaseBuffers())}, +enumerable:!0,configurable:!0}),t.prototype.getColorGradients=function(){return this._colorGradients},t.prototype.getSizeGradients=function(){return this._sizeGradients},t.prototype.getAngularSpeedGradients=function(){return this._angularSpeedGradients},t.prototype.getVelocityGradients=function(){return this._velocityGradients},t.prototype._removeGradient=function(e,t,i){if(!t)return this;for(var r=0,n=0,o=t;nt.gradient?1:0})),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeColorGradient=function(e){return this._removeGradient(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this},t.prototype._addFactorGradient=function(t,i,r){var n=new e.FactorGradient;n.gradient=i,n.factor1=r,t.push(n),t.sort((function(e,t){return e.gradientt.gradient?1:0})),this._releaseBuffers()},t.prototype.addSizeGradient=function(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeSizeGradient=function(e){return this._removeGradient(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this},t.prototype.addAngularSpeedGradient=function(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeAngularSpeedGradient=function(e){return this._removeGradient(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this},t.prototype.addVelocityGradient=function(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeVelocityGradient=function(e){return this._removeGradient(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this},t.prototype._createUpdateVAO=function(e){var t={};t.position=e.createVertexBuffer("position",0,3),t.age=e.createVertexBuffer("age",3,1),t.life=e.createVertexBuffer("life",4,1),t.seed=e.createVertexBuffer("seed",5,4),t.size=e.createVertexBuffer("size",9,3);var i=12;this._colorGradientsTexture||(t.color=e.createVertexBuffer("color",i,4),i+=4),t.direction=e.createVertexBuffer("direction",i,3),i+=3,this._isBillboardBased||(t.initialDirection=e.createVertexBuffer("initialDirection",i,3),i+=3),this._angularSpeedGradientsTexture?(t.angle=e.createVertexBuffer("angle",i,1),i+=1):(t.angle=e.createVertexBuffer("angle",i,2),i+=2),this._isAnimationSheetEnabled&&(t.cellIndex=e.createVertexBuffer("cellIndex",i,1),i+=1);var r=this._engine.recordVertexArrayObject(t,null,this._updateEffect);return this._engine.bindArrayBuffer(null),r},t.prototype._createRenderVAO=function(e,t){var i={};i.position=e.createVertexBuffer("position",0,3,this._attributesStrideSize,!0),i.age=e.createVertexBuffer("age",3,1,this._attributesStrideSize,!0),i.life=e.createVertexBuffer("life",4,1,this._attributesStrideSize,!0),i.size=e.createVertexBuffer("size",9,3,this._attributesStrideSize,!0);var r=12;this._colorGradientsTexture||(i.color=e.createVertexBuffer("color",r,4,this._attributesStrideSize,!0),r+=4),r+=3,this._isBillboardBased||(i.initialDirection=e.createVertexBuffer("initialDirection",r,3,this._attributesStrideSize,!0),r+=3),i.angle=e.createVertexBuffer("angle",r,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?r++:r+=2,this._isAnimationSheetEnabled&&(i.cellIndex=e.createVertexBuffer("cellIndex",r,1,this._attributesStrideSize,!0),r+=1),i.offset=t.createVertexBuffer("offset",0,2),i.uv=t.createVertexBuffer("uv",2,2);var n=this._engine.recordVertexArrayObject(i,null,this._renderEffect);return this._engine.bindArrayBuffer(null),n},t.prototype._initialize=function(t){if(void 0===t&&(t=!1),!this._buffer0||t){var i=this._scene.getEngine(),r=new Array;this.isBillboardBased||(this._attributesStrideSize+=3),this._colorGradientsTexture&&(this._attributesStrideSize-=4),this._angularSpeedGradientsTexture&&(this._attributesStrideSize-=1),this._isAnimationSheetEnabled&&(this._attributesStrideSize+=1);for(var n=0;n=this.targetStopDuration&&this.stop()},t.prototype._createFactorGradientTexture=function(t,i){var r=this[i];if(t&&t.length&&!r){for(var n=new Float32Array(this._rawTextureWidth),o=0;o1){var r=0|this._accumulatedCount;this._accumulatedCount-=r,this._currentActiveCount=Math.min(this._activeCount,this._currentActiveCount+r)}if(!this._currentActiveCount)return 0;this._engine.enableEffect(this._updateEffect),this._engine.setState(!1),this._updateEffect.setFloat("currentCount",this._currentActiveCount),this._updateEffect.setFloat("timeDelta",this._timeDelta),this._updateEffect.setFloat("stopFactor",this._stopped?0:1),this._updateEffect.setTexture("randomSampler",this._randomTexture),this._updateEffect.setTexture("randomSampler2",this._randomTexture2),this._updateEffect.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateEffect.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateEffect.setDirectColor4("color1",this.color1),this._updateEffect.setDirectColor4("color2",this.color2)),this._updateEffect.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateEffect.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateEffect.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateEffect.setVector3("gravity",this.gravity),this._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._sizeGradientsTexture),this._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._angularSpeedGradientsTexture),this._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._velocityGradientsTexture),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateEffect),this._isAnimationSheetEnabled&&this._updateEffect.setFloat3("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed),this.noiseTexture&&(this._updateEffect.setTexture("noiseSampler",this.noiseTexture),this._updateEffect.setVector3("noiseStrength",this.noiseStrength));var n;if(this.emitter.position){n=this.emitter.getWorldMatrix()}else{var o=this.emitter;n=e.Matrix.Translation(o.x,o.y,o.z)}if(this._updateEffect.setMatrix("emitterWM",n),this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex],null),this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer()),this._engine.setRasterizerState(!1),this._engine.beginTransformFeedback(!0),this._engine.drawArraysType(e.Material.PointListDrawMode,0,this._currentActiveCount),this._engine.endTransformFeedback(),this._engine.setRasterizerState(!0),this._engine.bindTransformFeedbackBuffer(null),!t){this._engine.enableEffect(this._renderEffect);var s=this._scene.getViewMatrix();if(this._renderEffect.setMatrix("view",s),this._renderEffect.setMatrix("projection",this._scene.getProjectionMatrix()),this._renderEffect.setTexture("textureSampler",this.particleTexture),this._renderEffect.setVector2("translationPivot",this.translationPivot),this._colorGradientsTexture?this._renderEffect.setTexture("colorGradientSampler",this._colorGradientsTexture):this._renderEffect.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){var a=this.particleTexture.getBaseSize();this._renderEffect.setFloat3("sheetInfos",this.spriteCellWidth/a.width,this.spriteCellHeight/a.height,a.width/this.spriteCellWidth)}if(this._isBillboardBased){var l=this._scene.activeCamera;this._renderEffect.setVector3("eyePosition",l.globalPosition)}if(this._scene.clipPlane){var c=this._scene.clipPlane,h=s.clone();h.invert(),this._renderEffect.setMatrix("invView",h),this._renderEffect.setFloat4("vClipPlane",c.normal.x,c.normal.y,c.normal.z,c.d)}switch(this.blendMode){case e.ParticleSystem.BLENDMODE_ADD:this._engine.setAlphaMode(e.Engine.ALPHA_ADD);break;case e.ParticleSystem.BLENDMODE_ONEONE:this._engine.setAlphaMode(e.Engine.ALPHA_ONEONE);break;case e.ParticleSystem.BLENDMODE_STANDARD:this._engine.setAlphaMode(e.Engine.ALPHA_COMBINE)}this.forceDepthWrite&&this._engine.setDepthWrite(!0),this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex],null),this._engine.drawArraysType(e.Material.TriangleFanDrawMode,0,4,this._currentActiveCount),this._engine.setAlphaMode(e.Engine.ALPHA_DISABLE)}2===++this._targetIndex&&(this._targetIndex=0);var u=this._sourceBuffer;return this._sourceBuffer=this._targetBuffer,this._targetBuffer=u,this._currentActiveCount},t.prototype.rebuild=function(){this._initialize(!0)},t.prototype._releaseBuffers=function(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null)},t.prototype._releaseVAOs=function(){if(this._updateVAO){for(var e=0;e-1&&this._scene.particleSystems.splice(t,1),this._releaseBuffers(),this._releaseVAOs(),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._randomTexture&&(this._randomTexture.dispose(),this._randomTexture=null),this._randomTexture2&&(this._randomTexture2.dispose(),this._randomTexture2=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.prototype.clone=function(i,r){var n=new t(i,{capacity:this._capacity,randomTextureSize:this._randomTextureSize},this._scene);return e.Tools.DeepCopy(this,n),void 0===r&&(r=this.emitter),n.emitter=r,this.particleTexture&&(n.particleTexture=new e.Texture(this.particleTexture.url,this._scene)),n},t.prototype.serialize=function(){var t={};return e.ParticleSystem._Serialize(t,this),t.activeParticleCount=this.activeParticleCount,t},t.Parse=function(i,r,n){var o=i.name,s=new t(o,{capacity:i.capacity,randomTextureSize:i.randomTextureSize},r);return i.activeParticleCount&&(s.activeParticleCount=i.activeParticleCount),e.ParticleSystem._Parse(i,s,r,n),s},t})();e.GPUParticleSystem=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a,l){void 0===l&&(l=null),this.idx=0,this.color=new e.Color4(1,1,1,1),this.position=e.Vector3.Zero(),this.rotation=e.Vector3.Zero(),this.scaling=e.Vector3.One(),this.uvs=new e.Vector4(0,0,1,1),this.velocity=e.Vector3.Zero(),this.pivot=e.Vector3.Zero(),this.translateFromPivot=!1,this.alive=!0,this.isVisible=!0,this._pos=0,this._ind=0,this.shapeId=0,this.idxInShape=0,this._stillInvisible=!1,this._rotationMatrix=[1,0,0,0,1,0,0,0,1],this.parentId=null,this._globalPosition=e.Vector3.Zero(),this.idx=t,this._pos=i,this._ind=r,this._model=n,this.shapeId=o,this.idxInShape=s,this._sps=a,l&&(this._modelBoundingInfo=l,this._boundingInfo=new e.BoundingInfo(l.minimum,l.maximum))}return Object.defineProperty(t.prototype,"scale",{get:function(){return this.scaling},set:function(e){this.scaling=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"quaternion",{get:function(){return this.rotationQuaternion},set:function(e){this.rotationQuaternion=e},enumerable:!0,configurable:!0}),t.prototype.intersectsMesh=function(t){return!(!this._boundingInfo||!t._boundingInfo)&&(this._sps._bSphereOnly?e.BoundingSphere.Intersects(this._boundingInfo.boundingSphere,t._boundingInfo.boundingSphere):this._boundingInfo.intersects(t._boundingInfo,!1))},t})();e.SolidParticle=t;var i=(function(){function e(e,t,i,r,n,o){this._indicesLength=0,this.shapeID=e,this._shape=t,this._indicesLength=i,this._shapeUV=r,this._positionFunction=n,this._vertexFunction=o}return e})();e.ModelShape=i;var r=(function(){function e(){this.ind=0,this.indicesLength=0,this.sqDistance=0}return e})();e.DepthSortedParticle=r})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){this.particles=new Array,this.nbParticles=0,this.billboard=!1,this.recomputeNormals=!0,this.counter=0,this.vars={},this._bSphereOnly=!1,this._bSphereRadiusFactor=1,this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._index=0,this._updatable=!0,this._pickable=!1,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._depthSort=!1,this._shapeCounter=0,this._copy=new e.SolidParticle(0,0,0,null,0,0,this),this._color=new e.Color4(0,0,0,0),this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeParticleVertex=!1,this._computeBoundingBox=!1,this._depthSortParticles=!0,this._cam_axisZ=e.Vector3.Zero(),this._cam_axisY=e.Vector3.Zero(),this._cam_axisX=e.Vector3.Zero(),this._axisZ=e.Axis.Z,this._camDir=e.Vector3.Zero(),this._camInvertedPosition=e.Vector3.Zero(),this._rotMatrix=new e.Matrix,this._invertMatrix=new e.Matrix,this._rotated=e.Vector3.Zero(),this._quaternion=new e.Quaternion,this._vertex=e.Vector3.Zero(),this._normal=e.Vector3.Zero(),this._yaw=0,this._pitch=0,this._roll=0,this._halfroll=0,this._halfpitch=0,this._halfyaw=0,this._sinRoll=0,this._cosRoll=0,this._sinPitch=0,this._cosPitch=0,this._sinYaw=0,this._cosYaw=0,this._mustUnrotateFixedNormals=!1,this._minimum=e.Vector3.Zero(),this._maximum=e.Vector3.Zero(),this._minBbox=e.Vector3.Zero(),this._maxBbox=e.Vector3.Zero(),this._particlesIntersect=!1,this._depthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},this._needs32Bits=!1,this._pivotBackTranslation=e.Vector3.Zero(),this._scaledPivot=e.Vector3.Zero(),this._particleHasParent=!1,this.name=t,this._scene=i||e.Engine.LastCreatedScene,this._camera=i.activeCamera,this._pickable=!!r&&r.isPickable,this._depthSort=!!r&&r.enableDepthSort,this._particlesIntersect=!!r&&r.particleIntersection,this._bSphereOnly=!!r&&r.boundingSphereOnly,this._bSphereRadiusFactor=r&&r.bSphereRadiusFactor?r.bSphereRadiusFactor:1,r&&void 0!==r.updatable?this._updatable=r.updatable:this._updatable=!0,this._pickable&&(this.pickedParticles=[]),this._depthSort&&(this.depthSortedParticles=[])}return t.prototype.buildMesh=function(){if(0===this.nbParticles){var t=e.MeshBuilder.CreateDisc("",{radius:1,tessellation:3},this._scene);this.addShape(t,1),t.dispose()}this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),this.recomputeNormals&&e.VertexData.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();var i=new e.VertexData;i.indices=this._depthSort?this._indices:this._indices32,i.set(this._positions32,e.VertexBuffer.PositionKind),i.set(this._normals32,e.VertexBuffer.NormalKind),this._uvs32.length>0&&i.set(this._uvs32,e.VertexBuffer.UVKind),this._colors32.length>0&&i.set(this._colors32,e.VertexBuffer.ColorKind);var r=new e.Mesh(this.name,this._scene);return i.applyToMesh(r,this._updatable),this.mesh=r,this.mesh.isPickable=this._pickable,this._depthSort||(this._indices=null),this._positions=null,this._normals=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0),r},t.prototype.digest=function(t,i){var r=i&&i.facetNb||1,n=i&&i.number||0,o=i&&i.delta||0,s=t.getVerticesData(e.VertexBuffer.PositionKind),a=t.getIndices(),l=t.getVerticesData(e.VertexBuffer.UVKind),c=t.getVerticesData(e.VertexBuffer.ColorKind),h=t.getVerticesData(e.VertexBuffer.NormalKind),u=0,d=a.length/3;n?(n=n>d?d:n,r=Math.round(d/n),o=0):r=r>d?d:r;for(var f=[],p=[],_=[],m=[],g=e.Vector3.Zero(),v=r;ud-r&&(r=d-u),f.length=0,p.length=0,_.length=0,m.length=0;for(var y=0,b=3*u;b<3*(u+r);b++){p.push(y);var x=a[b];f.push(s[3*x],s[3*x+1],s[3*x+2]),l&&_.push(l[2*x],l[2*x+1]),c&&m.push(c[4*x],c[4*x+1],c[4*x+2],c[4*x+3]),y++}var T,E=this.nbParticles,P=this._posToShape(f),A=this._uvsToShapeUV(_);for(T=0;T65535&&(this._needs32Bits=!0)}if(this._pickable){var b=n.length/3;for(_=0;_=this.nbParticles?this.nbParticles-1:i,this._computeBoundingBox&&(0==t&&i==this.nbParticles-1?(e.Vector3.FromFloatsToRef(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,this._minimum), +e.Vector3.FromFloatsToRef(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE,this._maximum)):this.mesh._boundingInfo&&(this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum),this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum))),s=this.particles[t]._pos;var d=s/3|0;l=4*d,h=2*d;for(var f=t;f<=i;f++){if(this._particle=this.particles[f],this._shape=this._particle._model._shape,this._shapeUV=this._particle._model._shapeUV,this.updateParticle(this._particle),this._depthSort&&this._depthSortParticles){var p=this.depthSortedParticles[f];p.ind=this._particle._ind,p.indicesLength=this._particle._model._indicesLength,p.sqDistance=e.Vector3.DistanceSquared(this._particle.position,this._camInvertedPosition)}if(!this._particle.alive||this._particle._stillInvisible&&!this._particle.isVisible)u=this._shape.length,s+=3*u,l+=4*u,h+=2*u;else{if(this._particle.isVisible)for(this._particle._stillInvisible=!1,this._particleHasParent=null!==this._particle.parentId,this._scaledPivot.x=this._particle.pivot.x*this._particle.scaling.x,this._scaledPivot.y=this._particle.pivot.y*this._particle.scaling.y,this._scaledPivot.z=this._particle.pivot.z*this._particle.scaling.z,this.billboard&&(this._particle.rotation.x=0,this._particle.rotation.y=0),(this._computeParticleRotation||this.billboard)&&(this._particle.rotationQuaternion?this._quaternion.copyFrom(this._particle.rotationQuaternion):(this._yaw=this._particle.rotation.y,this._pitch=this._particle.rotation.x,this._roll=this._particle.rotation.z,this._quaternionRotationYPR()),this._quaternionToRotationMatrix()),this._particleHasParent?(this._parent=this.particles[this._particle.parentId],this._rotated.x=this._particle.position.x*this._parent._rotationMatrix[0]+this._particle.position.y*this._parent._rotationMatrix[3]+this._particle.position.z*this._parent._rotationMatrix[6],this._rotated.y=this._particle.position.x*this._parent._rotationMatrix[1]+this._particle.position.y*this._parent._rotationMatrix[4]+this._particle.position.z*this._parent._rotationMatrix[7],this._rotated.z=this._particle.position.x*this._parent._rotationMatrix[2]+this._particle.position.y*this._parent._rotationMatrix[5]+this._particle.position.z*this._parent._rotationMatrix[8],this._particle._globalPosition.x=this._parent._globalPosition.x+this._rotated.x,this._particle._globalPosition.y=this._parent._globalPosition.y+this._rotated.y,this._particle._globalPosition.z=this._parent._globalPosition.z+this._rotated.z,(this._computeParticleRotation||this.billboard)&&(this._particle._rotationMatrix[0]=this._rotMatrix.m[0]*this._parent._rotationMatrix[0]+this._rotMatrix.m[1]*this._parent._rotationMatrix[3]+this._rotMatrix.m[2]*this._parent._rotationMatrix[6],this._particle._rotationMatrix[1]=this._rotMatrix.m[0]*this._parent._rotationMatrix[1]+this._rotMatrix.m[1]*this._parent._rotationMatrix[4]+this._rotMatrix.m[2]*this._parent._rotationMatrix[7],this._particle._rotationMatrix[2]=this._rotMatrix.m[0]*this._parent._rotationMatrix[2]+this._rotMatrix.m[1]*this._parent._rotationMatrix[5]+this._rotMatrix.m[2]*this._parent._rotationMatrix[8],this._particle._rotationMatrix[3]=this._rotMatrix.m[4]*this._parent._rotationMatrix[0]+this._rotMatrix.m[5]*this._parent._rotationMatrix[3]+this._rotMatrix.m[6]*this._parent._rotationMatrix[6],this._particle._rotationMatrix[4]=this._rotMatrix.m[4]*this._parent._rotationMatrix[1]+this._rotMatrix.m[5]*this._parent._rotationMatrix[4]+this._rotMatrix.m[6]*this._parent._rotationMatrix[7],this._particle._rotationMatrix[5]=this._rotMatrix.m[4]*this._parent._rotationMatrix[2]+this._rotMatrix.m[5]*this._parent._rotationMatrix[5]+this._rotMatrix.m[6]*this._parent._rotationMatrix[8],this._particle._rotationMatrix[6]=this._rotMatrix.m[8]*this._parent._rotationMatrix[0]+this._rotMatrix.m[9]*this._parent._rotationMatrix[3]+this._rotMatrix.m[10]*this._parent._rotationMatrix[6],this._particle._rotationMatrix[7]=this._rotMatrix.m[8]*this._parent._rotationMatrix[1]+this._rotMatrix.m[9]*this._parent._rotationMatrix[4]+this._rotMatrix.m[10]*this._parent._rotationMatrix[7],this._particle._rotationMatrix[8]=this._rotMatrix.m[8]*this._parent._rotationMatrix[2]+this._rotMatrix.m[9]*this._parent._rotationMatrix[5]+this._rotMatrix.m[10]*this._parent._rotationMatrix[8])):(this._particle._globalPosition.x=this._particle.position.x,this._particle._globalPosition.y=this._particle.position.y,this._particle._globalPosition.z=this._particle.position.z,(this._computeParticleRotation||this.billboard)&&(this._particle._rotationMatrix[0]=this._rotMatrix.m[0],this._particle._rotationMatrix[1]=this._rotMatrix.m[1],this._particle._rotationMatrix[2]=this._rotMatrix.m[2],this._particle._rotationMatrix[3]=this._rotMatrix.m[4],this._particle._rotationMatrix[4]=this._rotMatrix.m[5],this._particle._rotationMatrix[5]=this._rotMatrix.m[6],this._particle._rotationMatrix[6]=this._rotMatrix.m[8],this._particle._rotationMatrix[7]=this._rotMatrix.m[9],this._particle._rotationMatrix[8]=this._rotMatrix.m[10])),this._particle.translateFromPivot?(this._pivotBackTranslation.x=0,this._pivotBackTranslation.y=0,this._pivotBackTranslation.z=0):(this._pivotBackTranslation.x=this._scaledPivot.x,this._pivotBackTranslation.y=this._scaledPivot.y,this._pivotBackTranslation.z=this._scaledPivot.z),u=0;uthis._maximum.x&&(this._maximum.x=this._positions32[o]),this._positions32[o+1]this._maximum.y&&(this._maximum.y=this._positions32[o+1]),this._positions32[o+2]this._maximum.z&&(this._maximum.z=this._positions32[o+2])),this._computeParticleVertex||(this._normal.x=this._fixedNormal32[o],this._normal.y=this._fixedNormal32[o+1],this._normal.z=this._fixedNormal32[o+2],this._rotated.x=this._normal.x*this._particle._rotationMatrix[0]+this._normal.y*this._particle._rotationMatrix[3]+this._normal.z*this._particle._rotationMatrix[6],this._rotated.y=this._normal.x*this._particle._rotationMatrix[1]+this._normal.y*this._particle._rotationMatrix[4]+this._normal.z*this._particle._rotationMatrix[7],this._rotated.z=this._normal.x*this._particle._rotationMatrix[2]+this._normal.y*this._particle._rotationMatrix[5]+this._normal.z*this._particle._rotationMatrix[8],this._normals32[o]=this._cam_axisX.x*this._rotated.x+this._cam_axisY.x*this._rotated.y+this._cam_axisZ.x*this._rotated.z,this._normals32[o+1]=this._cam_axisX.y*this._rotated.x+this._cam_axisY.y*this._rotated.y+this._cam_axisZ.y*this._rotated.z,this._normals32[o+2]=this._cam_axisX.z*this._rotated.x+this._cam_axisY.z*this._rotated.y+this._cam_axisZ.z*this._rotated.z),this._computeParticleColor&&this._particle.color&&(this._colors32[a]=this._particle.color.r,this._colors32[a+1]=this._particle.color.g,this._colors32[a+2]=this._particle.color.b,this._colors32[a+3]=this._particle.color.a),this._computeParticleTexture&&(this._uvs32[c]=this._shapeUV[2*u]*(this._particle.uvs.z-this._particle.uvs.x)+this._particle.uvs.x,this._uvs32[c+1]=this._shapeUV[2*u+1]*(this._particle.uvs.w-this._particle.uvs.y)+this._particle.uvs.y);else for(this._particle._stillInvisible=!0,u=0;ue.Tmp.Vector3[1].x&&(e.Tmp.Vector3[1].x=l[u].x),l[u].ye.Tmp.Vector3[1].y&&(e.Tmp.Vector3[1].y=l[u].y),l[u].ze.Tmp.Vector3[1].z&&(e.Tmp.Vector3[1].z=l[u].z),u++,r+=3;c._closePath&&(t[r]=l[0].x,t[r+1]=l[0].y,t[r+2]=l[0].z,r+=3)}}(u),c._boundingInfo=new e.BoundingInfo(e.Tmp.Vector3[0],e.Tmp.Vector3[1]),c._boundingInfo.update(c._worldMatrix),c.updateVerticesData(e.VertexBuffer.PositionKind,u,!1,!1),r.colors){for(var d=c.getVerticesData(e.VertexBuffer.ColorKind),f=0;f1?1:r.arc:1,a=void 0===r.closed||r.closed,l=r.shape,c=r.radius||1,h=r.tessellation||64,u=r.clip||0,d=r.updatable,f=t.updateSideOrientation(r.sideOrientation),p=r.cap||e.Mesh.NO_CAP,_=2*Math.PI,m=new Array,g=r.invertUV||!1,v=0,y=0,b=_/h*s,x=new Array;for(v=0;v<=h-u;v++){var x=[];for(p!=e.Mesh.CAP_START&&p!=e.Mesh.CAP_ALL||(x.push(new e.Vector3(0,l[0].y,0)),x.push(new e.Vector3(Math.cos(v*b)*l[0].x*c,l[0].y,Math.sin(v*b)*l[0].x*c))),y=0;y1)?1:r.arc||1;var p,_,m=function(t,i,r,n,o,s,a,l){for(var c,h,u,d,f=i.getTangents(),p=i.getNormals(),_=i.getDistances(),m=2*Math.PI,g=m/o*l,v=function(){return n},y=s||v,b=e.Tmp.Matrix[0],x=a===e.Mesh._NO_CAP||a===e.Mesh.CAP_END?0:2,T=0;T3?0:h,_=m(o,p,v,a,l,c,h,r.arc);var y=t.CreateRibbon(i,{pathArray:_,closePath:!0,closeArray:!1,updatable:d,sideOrientation:f,invertUV:u,frontUVs:r.frontUVs,backUVs:r.backUVs},n);return y.pathArray=_,y.path3D=p,y.tessellation=l,y.cap=h,y.arc=r.arc,y.radius=a,y},t.CreatePolyhedron=function(i,r,n){var o=new e.Mesh(i,n);return r.sideOrientation=t.updateSideOrientation(r.sideOrientation),o._originalBuilderSideOrientation=r.sideOrientation,e.VertexData.CreatePolyhedron(r).applyToMesh(o,r.updatable),o},t.CreateDecal=function(t,i,r){var n=i.getIndices(),o=i.getVerticesData(e.VertexBuffer.PositionKind),s=i.getVerticesData(e.VertexBuffer.NormalKind),a=r.position||e.Vector3.Zero(),l=r.normal||e.Vector3.Up(),c=r.size||e.Vector3.One(),h=r.angle||0;if(!l){var u=new e.Vector3(0,0,1),d=i.getScene().activeCamera,f=e.Vector3.TransformCoordinates(u,d.getWorldMatrix());l=d.globalPosition.subtract(f)}var p=-Math.atan2(l.z,l.x)-Math.PI/2,_=Math.sqrt(l.x*l.x+l.z*l.z),m=Math.atan2(l.y,_),g=e.Matrix.RotationYawPitchRoll(p,m,h).multiply(e.Matrix.Translation(a.x,a.y,a.z)),v=e.Matrix.Invert(g),y=i.getWorldMatrix(),b=y.multiply(v),x=new e.VertexData;x.indices=[],x.positions=[],x.normals=[],x.uvs=[];for(var T=0,E=function(t){var i=new e.PositionNormalVertex;if(!n||!o||!s)return i;var r=n[t];return i.position=new e.Vector3(o[3*r],o[3*r+1],o[3*r+2]),i.position=e.Vector3.TransformCoordinates(i.position,b),i.normal=new e.Vector3(s[3*r],s[3*r+1],s[3*r+2]),i.normal=e.Vector3.TransformNormal(i.normal,b),i},P=function(t,i){if(0===t.length)return t;for(var r=.5*Math.abs(e.Vector3.Dot(c,i)),n=function(t,n){var o=e.Vector3.GetClipFactor(t.position,n.position,i,r);return new e.PositionNormalVertex(e.Vector3.Lerp(t.position,n.position,o),e.Vector3.Lerp(t.normal,n.normal,o))},o=new Array,s=0;s0,l=m>0,h=g>0,(a?1:0)+(l?1:0)+(h?1:0)){case 0:o.push(t[s]),o.push(t[s+1]),o.push(t[s+2]);break;case 1:if(a&&(u=t[s+1],d=t[s+2],f=n(t[s],u),p=n(t[s],d)),l){u=t[s],d=t[s+2],f=n(t[s+1],u),p=n(t[s+1],d),o.push(f),o.push(d.clone()),o.push(u.clone()),o.push(d.clone()),o.push(f.clone()),o.push(p);break}h&&(u=t[s],d=t[s+1],f=n(t[s+2],u),p=n(t[s+2],d)),u&&d&&f&&p&&(o.push(u.clone()),o.push(d.clone()),o.push(f),o.push(p),o.push(f.clone()),o.push(d.clone()));break;case 2:a||(u=t[s].clone(),d=n(u,t[s+1]),f=n(u,t[s+2]),o.push(u),o.push(d),o.push(f)),l||(u=t[s+1].clone(),d=n(u,t[s+2]),f=n(u,t[s]),o.push(u),o.push(d),o.push(f)),h||(u=t[s+2].clone(),d=n(u,t[s]),f=n(u,t[s+1]),o.push(u),o.push(d),o.push(f))}}return o},A=0;A3?0:u,x=T(r,n,b,E,o,s,a,l,u,d);var P=t.CreateRibbon(i,{pathArray:x,closeArray:c,closePath:h,updatable:p,sideOrientation:_,invertUV:g,frontUVs:v||void 0,backUVs:y||void 0},f);return P.pathArray=x,P.path3D=b,P.cap=u,P},t})();e.MeshBuilder=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return Object.defineProperty(t,"DecoderAvailable",{get:function(){if("undefined"!=typeof DracoDecoderModule)return!0;var e=t.Configuration.decoder;if(e){if(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly)return!0;if(e.fallbackUrl)return!0}return!1},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){},t.prototype.decodeMeshAsync=function(i,r){var n=i instanceof ArrayBuffer?new Uint8Array(i):i;return t._GetDecoderModule().then((function(t){var i=t.module,o=new e.VertexData,s=new i.DecoderBuffer;s.Init(n,n.byteLength);var a,l,c=new i.Decoder;try{var h=c.GetEncodedGeometryType(s);switch(h){case i.TRIANGULAR_MESH:a=new i.Mesh,l=c.DecodeBufferToMesh(s,a);break;case i.POINT_CLOUD:a=new i.PointCloud,l=c.DecodeBufferToPointCloud(s,a);break;default:throw new Error("Invalid geometry type "+h)}if(!l.ok()||!a.ptr)throw new Error(l.error_msg());var u=a.num_points();if(h===i.TRIANGULAR_MESH){var d=a.num_faces(),f=new i.DracoInt32Array;try{for(var p=new Uint32Array(3*d),_=0;_0&&(c=!0,this._soundLoaded(i));break;case"String":l.push(i);case"Array":0===l.length&&(l=i);for(var h=0;h0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect();else if(e.Engine.audioEngine.audioContext&&this._soundSource){var i=t?e.Engine.audioEngine.audioContext.currentTime+t:e.Engine.audioEngine.audioContext.currentTime;this._soundSource.stop(i),this._soundSource.onended=function(){},this.isPaused||(this._startOffset=0)}this.isPlaying=!1}},t.prototype.pause=function(){this.isPlaying&&(this.isPaused=!0,this._streaming?this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect():e.Engine.audioEngine.audioContext&&(this.stop(0),this._startOffset+=e.Engine.audioEngine.audioContext.currentTime-this._startTime))},t.prototype.setVolume=function(t,i){e.Engine.audioEngine.canUseWebAudio&&this._soundGain&&(i&&e.Engine.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(t,e.Engine.audioEngine.audioContext.currentTime+i)):this._soundGain.gain.value=t),this._volume=t},t.prototype.setPlaybackRate=function(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))},t.prototype.getVolume=function(){return this._volume},t.prototype.attachToMesh=function(e){var t=this;this._connectedMesh&&this._registerFunc&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedMesh=e,this.spatialSound||(this.spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play())),this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh),this._registerFunc=function(e){return t._onRegisterAfterWorldMatrixUpdate(e)},e.registerAfterWorldMatrixUpdate(this._registerFunc)},t.prototype.detachFromMesh=function(){this._connectedMesh&&this._registerFunc&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedMesh=null)},t.prototype._onRegisterAfterWorldMatrixUpdate=function(t){if(t.getBoundingInfo){var i=t,r=i.getBoundingInfo();this.setPosition(r.boundingSphere.centerWorld),e.Engine.audioEngine.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}},t.prototype.clone=function(){var e=this;if(this._streaming)return null;var i=function(){e._isReadyToPlay?(n._audioBuffer=e.getAudioBuffer(),n._isReadyToPlay=!0,n.autoplay&&n.play()):window.setTimeout(i,300)},r={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},n=new t(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,r);return this.useCustomAttenuation&&n.setAttenuationFunction(this._customAttenuationFunction),n.setPosition(this._position),n.setPlaybackRate(this._playbackRate),i(),n},t.prototype.getAudioBuffer=function(){return this._audioBuffer},t.prototype.serialize=function(){var e={name:this.name,url:this.name,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId};return this.spatialSound&&(this._connectedMesh&&(e.connectedMeshId=this._connectedMesh.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e},t.Parse=function(i,r,n,o){var s,a=i.name;s=i.url?n+i.url:n+a;var l,c={autoplay:i.autoplay,loop:i.loop,volume:i.volume,spatialSound:i.spatialSound,maxDistance:i.maxDistance,rolloffFactor:i.rolloffFactor,refDistance:i.refDistance,distanceModel:i.distanceModel,playbackRate:i.playbackRate};if(o){var h=function(){o._isReadyToPlay?(l._audioBuffer=o.getAudioBuffer(),l._isReadyToPlay=!0,l.autoplay&&l.play()):window.setTimeout(h,300)};l=new t(a,new ArrayBuffer(0),r,null,c),h()}else l=new t(a,s,r,function(){r._removePendingData(l)},c),r._addPendingData(l);if(i.position){var u=e.Vector3.FromArray(i.position);l.setPosition(u)}if(i.isDirectional&&(l.setDirectionalCone(i.coneInnerAngle||360,i.coneOuterAngle||360,i.coneOuterGain||0),i.localDirectionToMesh)){var d=e.Vector3.FromArray(i.localDirectionToMesh);l.setLocalDirectionToMesh(d)}if(i.connectedMeshId){var f=r.getMeshByID(i.connectedMeshId);f&&l.attachToMesh(f)}return l},t})();e.Sound=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t){this.id=-1,this._isMainTrack=!1,this._isInitialized=!1,this._scene=e,this.soundCollection=new Array,this._options=t,this._isMainTrack||(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}return t.prototype._initializeSoundTrackAudioGraph=function(){e.Engine.audioEngine.canUseWebAudio&&e.Engine.audioEngine.audioContext&&(this._outputAudioNode=e.Engine.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(e.Engine.audioEngine.masterGain),this._options&&(this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._options.mainTrack&&(this._isMainTrack=this._options.mainTrack)),this._isInitialized=!0)},t.prototype.dispose=function(){if(e.Engine.audioEngine&&e.Engine.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}},t.prototype.AddSound=function(t){this._isInitialized||this._initializeSoundTrackAudioGraph(),e.Engine.audioEngine.canUseWebAudio&&this._outputAudioNode&&t.connectToSoundTrackAudioNode(this._outputAudioNode),t.soundTrackId&&(-1===t.soundTrackId?this._scene.mainSoundTrack.RemoveSound(t):this._scene.soundTracks[t.soundTrackId].RemoveSound(t)),this.soundCollection.push(t),t.soundTrackId=this.id},t.prototype.RemoveSound=function(e){var t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)},t.prototype.setVolume=function(t){e.Engine.audioEngine.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=t)},t.prototype.switchPanningModelToHRTF=function(){if(e.Engine.audioEngine.canUseWebAudio)for(var t=0;t-1?i.substring(m).toLowerCase():""),v=".dds"===g,y=".env"===g;if(y?(_.gammaSpace=!1,_._prefiltered=!1):(_._prefiltered=h,h&&(_.gammaSpace=!1)),_._texture=_._getFromCache(i,o),!s&&(y||v||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),s=[],n))for(var b=0;b0&&(this._postProcesses[0].autoClear=!1))}},i.prototype._shouldRender=function(){return-1===this._currentRefreshId?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)},i.prototype.getRenderSize=function(){return this._size.width?this._size.width:this._size},i.prototype.getRenderWidth=function(){return this._size.width?this._size.width:this._size},i.prototype.getRenderHeight=function(){return this._size.width?this._size.height:this._size},Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype.scale=function(e){var t=this.getRenderSize()*e;this.resize(t)},i.prototype.getReflectionTextureMatrix=function(){return this.isCube?this._textureMatrix:t.prototype.getReflectionTextureMatrix.call(this)},i.prototype.resize=function(e){this.releaseInternalTexture();var t=this.getScene();t&&(this._processSizeParameter(e),this.isCube?this._texture=t.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._texture=t.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions))},i.prototype.render=function(e,t){void 0===e&&(e=!1),void 0===t&&(t=!1);var i=this.getScene();if(i){var r=i.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(var n=0;n=0&&this._renderingManager.dispatchParticles(v))}if(this.isCube)for(var b=0;b<6;b++)this.renderToTarget(b,h,u,e,t),i.incrementRenderId(),i.resetCachedMaterial();else this.renderToTarget(0,h,u,e,t);this.onAfterUnbindObservable.notifyObservers(this),i.activeCamera&&(this.activeCamera&&this.activeCamera!==i.activeCamera&&i.setTransformMatrix(i.activeCamera.getViewMatrix(),i.activeCamera.getProjectionMatrix(!0)),r.setViewport(i.activeCamera.viewport)),i.resetCachedMaterial()}},i.prototype._bestReflectionRenderTargetDimension=function(t,i){var r=t*i,n=e.Tools.NearestPOT(r+16384/(128+r));return Math.min(e.Tools.FloorPOT(t),n)},i.prototype.unbindFrameBuffer=function(e,t){var i=this;this._texture&&e.unBindFramebuffer(this._texture,this.isCube,(function(){i.onAfterRenderObservable.notifyObservers(t)}))},i.prototype.renderToTarget=function(t,i,r,n,o){var s=this.getScene();if(s){var a=s.getEngine();this._texture&&(this._postProcessManager?this._postProcessManager._prepareFrame(this._texture,this._postProcesses):n&&s.postProcessManager._prepareFrame(this._texture)||this._texture&&a.bindFramebuffer(this._texture,this.isCube?t:void 0,void 0,void 0,this.ignoreCameraViewport,this.depthStencilTexture?this.depthStencilTexture:void 0),this.onBeforeRenderObservable.notifyObservers(t),this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):a.clear(this.clearColor||s.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),this._renderingManager.render(this.customRenderFunction,i,this.renderParticles,this.renderSprites),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._texture,t,this._postProcesses,this.ignoreCameraViewport):n&&s.postProcessManager._finalizeFrame(!1,this._texture,t),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),o&&e.Tools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),a),this.isCube&&5!==t?this.onAfterRenderObservable.notifyObservers(t):(this.isCube&&5===t&&a.generateMipMapsForCubemap(this._texture),this.unbindFrameBuffer(a,t)))}},i.prototype.setRenderingOrder=function(e,t,i,r){void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._renderingManager.setRenderingOrder(e,t,i,r)},i.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(var i=0;i=0&&e.customRenderTargets.splice(i,1);for(var r=0,n=e.cameras;r=0&&o.customRenderTargets.splice(i,1)}t.prototype.dispose.call(this)}},i.prototype._rebuild=function(){this.refreshRate===i.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=i.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()},i.prototype.freeRenderingGroups=function(){this._renderingManager&&this._renderingManager.freeRenderingGroups()},i._REFRESHRATE_RENDER_ONCE=0,i._REFRESHRATE_RENDER_ONEVERYFRAME=1,i._REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,i})(e.Texture);e.RenderTargetTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s){var a=this,l=!(!s||!s.generateMipMaps)&&s.generateMipMaps,c=!(!s||!s.generateDepthTexture)&&s.generateDepthTexture,h=!s||void 0===s.doNotChangeAspectRatio||s.doNotChangeAspectRatio;if(a=t.call(this,i,r,o,l,h)||this,a._engine=o.getEngine(),!a.isSupported)return void a.dispose();for(var u=[],d=[],f=0;f1||this._engine.getCaps().drawBuffersExtension},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"textures",{get:function(){return this._textures},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"depthTexture",{get:function(){return this._textures[this._textures.length-1]},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wrapU",{set:function(e){if(this._textures)for(var t=0;t=0;e--)void 0!==this._internalTextures[e]&&(this._internalTextures[e].dispose(),this._internalTextures.splice(e,1))},i})(e.RenderTargetTexture);e.MultiRenderTarget=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l){void 0===s&&(s=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),void 0===l&&(l=!0);var c=t.call(this,i,r,n,o,!0,s,!1,a,l)||this;return c.scene=n,c.mirrorPlane=new e.Plane(0,1,0,1),c._transformMatrix=e.Matrix.Zero(),c._mirrorMatrix=e.Matrix.Zero(),c._adaptiveBlurKernel=0,c._blurKernelX=0,c._blurKernelY=0,c._blurRatio=1,c.ignoreCameraViewport=!0,c._updateGammaSpace(),c._imageProcessingConfigChangeObserver=n.imageProcessingConfiguration.onUpdateParameters.add((function(){c._updateGammaSpace})),c.onBeforeRenderObservable.add((function(){e.Matrix.ReflectionToRef(c.mirrorPlane,c._mirrorMatrix),c._savedViewMatrix=n.getViewMatrix(),c._mirrorMatrix.multiplyToRef(c._savedViewMatrix,c._transformMatrix),n.setTransformMatrix(c._transformMatrix,n.getProjectionMatrix()),n.clipPlane=c.mirrorPlane,n.getEngine().cullBackFaces=!1,n._mirroredCameraPosition=e.Vector3.TransformCoordinates(n.activeCamera.globalPosition,c._mirrorMatrix)})),c.onAfterRenderObservable.add((function(){n.setTransformMatrix(c._savedViewMatrix,n.getProjectionMatrix()),n.getEngine().cullBackFaces=!0,n._mirroredCameraPosition=null,delete n.clipPlane})),c}return o(i,t),Object.defineProperty(i.prototype,"blurRatio",{get:function(){return this._blurRatio},set:function(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"adaptiveBlurKernel",{set:function(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurKernel",{set:function(e){this.blurKernelX=e,this.blurKernelY=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurKernelX",{get:function(){return this._blurKernelX},set:function(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurKernelY",{get:function(){return this._blurKernelY},set:function(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),i.prototype._autoComputeBlurKernel=function(){var e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i},i.prototype._onRatioRescale=function(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()},i.prototype._updateGammaSpace=function(){this.gammaSpace=!this.scene.imageProcessingConfiguration.isEnabled||!this.scene.imageProcessingConfiguration.applyByPostProcess},i.prototype._preparePostProcesses=function(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){var t=this.getScene().getEngine(),i=t.getCaps().textureFloatRender?e.Engine.TEXTURETYPE_FLOAT:e.Engine.TEXTURETYPE_HALF_FLOAT;this._blurX=new e.BlurPostProcess("horizontal blur",new e.Vector2(1,0),this._blurKernelX,this._blurRatio,null,e.Texture.BILINEAR_SAMPLINGMODE,t,!1,i),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._texture:this._blurX.alwaysForcePOT=!0,this._blurY=new e.BlurPostProcess("vertical blur",new e.Vector2(0,1),this._blurKernelY,this._blurRatio,null,e.Texture.BILINEAR_SAMPLINGMODE,t,!1,i),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=this.getSize(),r=new i(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(r.renderList=this.renderList.slice(0)),r},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.mirrorPlane.asArray(),e},i.prototype.dispose=function(){t.prototype.dispose.call(this),this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver)},i})(e.RenderTargetTexture);e.MirrorTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o){var s=t.call(this,i,r,n,o,!0)||this;return s.refractionPlane=new e.Plane(0,1,0,1),s.depth=2,s.onBeforeRenderObservable.add((function(){n.clipPlane=s.refractionPlane})),s.onAfterRenderObservable.add((function(){delete n.clipPlane})),s}return o(i,t),i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=this.getSize(),r=new i(this.name,t.width,e,this._generateMipMaps);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.refractionPlane=this.refractionPlane.clone(),this.renderList&&(r.renderList=this.renderList.slice(0)),r.depth=this.depth,r},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e},i})(e.RenderTargetTexture);e.RefractionTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a){void 0===n&&(n=null),void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===a&&(a=e.Engine.TEXTUREFORMAT_RGBA);var l=t.call(this,null,n,!o,void 0,s,void 0,void 0,void 0,void 0,a)||this;l.name=i,l._engine=l.getScene().getEngine(),l.wrapU=e.Texture.CLAMP_ADDRESSMODE,l.wrapV=e.Texture.CLAMP_ADDRESSMODE,l._generateMipMaps=o,r.getContext?(l._canvas=r,l._texture=l._engine.createDynamicTexture(r.width,r.height,o,s)):(l._canvas=document.createElement("canvas"),r.width||0===r.width?l._texture=l._engine.createDynamicTexture(r.width,r.height,o,s):l._texture=l._engine.createDynamicTexture(r,r,o,s));var c=l.getSize();return l._canvas.width=c.width,l._canvas.height=c.height,l._context=l._canvas.getContext("2d"),l}return o(i,t),Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype._recreate=function(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._engine.createDynamicTexture(e.width,e.height,this._generateMipMaps,this._samplingMode)},i.prototype.scale=function(e){var t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)},i.prototype.scaleTo=function(e,t){var i=this.getSize();i.width=e,i.height=t,this._recreate(i)},i.prototype.getContext=function(){return this._context},i.prototype.clear=function(){var e=this.getSize();this._context.fillRect(0,0,e.width,e.height)},i.prototype.update=function(e,t){void 0===t&&(t=!1),this._engine.updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0)},i.prototype.drawText=function(e,t,i,r,n,o,s,a){void 0===a&&(a=!0);var l=this.getSize();if(o&&(this._context.fillStyle=o,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null===t||void 0===t){var c=this._context.measureText(e);t=(l.width-c.width)/2}if(null===i||void 0===i){var h=parseInt(r.replace(/\D/g,""));i=l.height/2+h/3.65}this._context.fillStyle=n,this._context.fillText(e,t,i),a&&this.update(s)},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=this.getSize(),r=new i(this.name,t,e,this._generateMipMaps);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.wrapU=this.wrapU,r.wrapV=this.wrapV,r},i.prototype.serialize=function(){var i=this.getScene();i&&!i.isReady()&&e.Tools.Warn("The scene must be ready before serializing the dynamic texture");var r=t.prototype.serialize.call(this);return r.base64String=this._canvas.toDataURL(),r.invertY=this._invertY,r.samplingMode=this.samplingMode,r},i.prototype._rebuild=function(){this.update()},i})(e.Texture);e.DynamicTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l){void 0===o&&(o=!1),void 0===s&&(s=!1),void 0===a&&(a=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===l&&(l={autoPlay:!0,loop:!0,autoUpdateTexture:!0});var c=t.call(this,null,n,!o,s)||this;return c._onUserActionRequestedObservable=null,c._stillImageCaptured=!1,c._poster=!1,c._createInternalTexture=function(){if(null!=c._texture){if(!c._poster)return;c._texture.dispose(),c._poster=!1}if(!c._engine.needPOTTextures||e.Tools.IsExponentOfTwo(c.video.videoWidth)&&e.Tools.IsExponentOfTwo(c.video.videoHeight)?(c.wrapU=e.Texture.WRAP_ADDRESSMODE,c.wrapV=e.Texture.WRAP_ADDRESSMODE):(c.wrapU=e.Texture.CLAMP_ADDRESSMODE,c.wrapV=e.Texture.CLAMP_ADDRESSMODE,c._generateMipMaps=!1),c._texture=c._engine.createDynamicTexture(c.video.videoWidth,c.video.videoHeight,c._generateMipMaps,c._samplingMode),c.video.autoplay)c._texture.isReady=!0,c._updateInternalTexture(),c._onLoadObservable&&c._onLoadObservable.hasObservers()&&c.onLoadObservable.notifyObservers(c);else{var t=c.video.onplaying,i=!1;c.video.onplaying=function(){c.video.onplaying=t,c._texture.isReady=!0,c._updateInternalTexture(),i||c.video.pause(),c._onLoadObservable&&c._onLoadObservable.hasObservers()&&c.onLoadObservable.notifyObservers(c)};var r=c.video.play();r?r.then((function(){})).catch((function(){i=!0,c._onUserActionRequestedObservable&&c._onUserActionRequestedObservable.hasObservers()&&c._onUserActionRequestedObservable.notifyObservers(c)})):(c.video.onplaying=t,c._texture.isReady=!0,c._updateInternalTexture(),c._onLoadObservable&&c._onLoadObservable.hasObservers()&&c.onLoadObservable.notifyObservers(c))}},c.reset=function(){null!=c._texture&&(c._poster||(c._texture.dispose(),c._texture=null))},c._updateInternalTexture=function(e){null!=c._texture&&c._texture.isReady&&(c.video.readyState=c.video.HAVE_CURRENT_DATA&&c._createInternalTexture(),l.poster&&(c._texture=c._engine.createTexture(l.poster,!1,!0,n),c._poster=!0),c}return o(i,t),Object.defineProperty(i.prototype,"onUserActionRequestedObservable",{get:function(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new e.Observable),this._onUserActionRequestedObservable},enumerable:!0,configurable:!0}),i.prototype._getName=function(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e},i.prototype._getVideo=function(t){if(t instanceof HTMLVideoElement)return e.Tools.SetCorsBehavior(t.currentSrc,t),t;var i=document.createElement("video");return"string"==typeof t?(e.Tools.SetCorsBehavior(t,i),i.src=t):(e.Tools.SetCorsBehavior(t[0],i),t.forEach((function(e){var t=document.createElement("source");t.src=e,i.appendChild(t)}))),i},i.prototype._rebuild=function(){this.update()},i.prototype.update=function(){this.autoUpdateTexture&&this.updateTexture(!0)},i.prototype.updateTexture=function(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))},i.prototype.updateURL=function(e){this.video.src=e},i.prototype.dispose=function(){t.prototype.dispose.call(this),this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener("canplay",this._createInternalTexture),this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this.reset),this.video.pause()},i.CreateFromWebCam=function(t,r,n){var o=document.createElement("video");o.setAttribute("autoplay",""),o.setAttribute("muted",""),o.setAttribute("playsinline","");var s;n&&n.deviceId&&(s={exact:n.deviceId}),window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,navigator.mediaDevices?navigator.mediaDevices.getUserMedia({video:n}).then((function(e){void 0!==o.mozSrcObject?o.mozSrcObject=e:o.srcObject=e;var n=function(){r&&r(new i("video",o,t,!0,!0)),o.removeEventListener("playing",n)};o.addEventListener("playing",n),o.play()})).catch((function(t){e.Tools.Error(t.name)})):(navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,navigator.getUserMedia&&navigator.getUserMedia({video:{deviceId:s,width:{min:n&&n.minWidth||256,max:n&&n.maxWidth||640},height:{min:n&&n.minHeight||256,max:n&&n.maxHeight||480}}},(function(e){void 0!==o.mozSrcObject?o.mozSrcObject=e:o.src=window.URL&&window.URL.createObjectURL(e)||e,o.play(),r&&r(new i("video",o,t,!0,!0))}),(function(t){e.Tools.Error(t.name)})))},i})(e.Texture);e.VideoTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c,h){void 0===a&&(a=!0),void 0===l&&(l=!1),void 0===c&&(c=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT);var u=t.call(this,null,s,!a,l)||this +;return u.format=o,u._engine=s.getEngine(),u._texture=s.getEngine().createRawTexture(i,r,n,o,a,l,c,null,h),u.wrapU=e.Texture.CLAMP_ADDRESSMODE,u.wrapV=e.Texture.CLAMP_ADDRESSMODE,u}return o(i,t),i.prototype.update=function(e){this._engine.updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,void 0,this._texture.type)},i.CreateLuminanceTexture=function(t,r,n,o,s,a,l){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_LUMINANCE,o,s,a,l)},i.CreateLuminanceAlphaTexture=function(t,r,n,o,s,a,l){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA,o,s,a,l)},i.CreateAlphaTexture=function(t,r,n,o,s,a,l){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_ALPHA,o,s,a,l)},i.CreateRGBTexture=function(t,r,n,o,s,a,l,c){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT),new i(t,r,n,e.Engine.TEXTUREFORMAT_RGB,o,s,a,l,c)},i.CreateRGBATexture=function(t,r,n,o,s,a,l,c){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT),new i(t,r,n,e.Engine.TEXTUREFORMAT_RGBA,o,s,a,l,c)},i.CreateRTexture=function(t,r,n,o,s,a,l,c){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===c&&(c=e.Engine.TEXTURETYPE_FLOAT),new i(t,r,n,e.Engine.TEXTUREFORMAT_R,o,s,a,l,c)},i})(e.Texture);e.RawTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c,h,u){void 0===l&&(l=!0),void 0===c&&(c=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===u&&(u=e.Engine.TEXTURETYPE_UNSIGNED_INT);var d=t.call(this,null,a,!l,c)||this;return d.format=s,d._engine=a.getEngine(),d._texture=a.getEngine().createRawTexture3D(i,r,n,o,s,l,c,h,void 0,u),d.is3D=!0,d}return o(i,t),i.prototype.update=function(e){this._texture&&this._engine.updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,void 0,this._texture.type)},i})(e.Texture);e.RawTexture3D=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e){this._vertexBuffers={},this._scene=e}return t.prototype._prepareBuffers=function(){if(!this._vertexBuffers[e.VertexBuffer.PositionKind]){var t=[];t.push(1,1),t.push(-1,1),t.push(-1,-1),t.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(this._scene.getEngine(),t,e.VertexBuffer.PositionKind,!1,!1,2),this._buildIndexBuffer()}},t.prototype._buildIndexBuffer=function(){var e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)},t.prototype._rebuild=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t._rebuild(),this._buildIndexBuffer())},t.prototype._prepareFrame=function(e,t){void 0===e&&(e=null),void 0===t&&(t=null);var i=this._scene.activeCamera;if(!i)return!1;var t=t||i._postProcesses.filter((function(e){return null!=e}));return!(!t||0===t.length||!this._scene.postProcessesEnabled)&&(t[0].activate(i,e,null!==t&&void 0!==t),!0)},t.prototype.directRender=function(t,i,r,n,o){void 0===i&&(i=null),void 0===r&&(r=!1),void 0===n&&(n=0),void 0===o&&(o=0);for(var s=this._scene.getEngine(),a=0;a0){for(var p=0;p0)for(var e=0;e0){var r=this._camera._getFirstPostProcess();r&&r.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}},t})();e.PostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c){return void 0===n&&(n=null),void 0===l&&(l=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1),t.call(this,i,"pass",null,null,r,n,o,s,a,void 0,l,void 0,null,c)||this}return o(i,t),i})(e.PostProcess);e.PassPostProcess=t})(r||(r={}));var r,s=this&&this.__assign||Object.assign||function(e){for(var t,i=1,r=arguments.length;i=1?1:e<=0?0:e,this},t.prototype.setTransparencyShadow=function(e){return this._transparencyShadow=e,this},t.prototype.getShadowMap=function(){return this._shadowMap},t.prototype.getShadowMapForRendering=function(){return this._shadowMap2?this._shadowMap2:this._shadowMap},t.prototype.addShadowCaster=function(e,t){void 0===t&&(t=!0);var i;return this._shadowMap?(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.push(e),t&&(i=this._shadowMap.renderList).push.apply(i,e.getChildMeshes()),this):this},t.prototype.removeShadowCaster=function(e,t){if(void 0===t&&(t=!0),!this._shadowMap||!this._shadowMap.renderList)return this;var i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(var r=0,n=e.getChildren();r1?(this._shadowMap=new e.RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1),this._shadowMap.createDepthStencilTexture(e.Engine.LESS,!0)):this._shadowMap=new e.RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._shadowMap.onBeforeRenderObservable.add((function(e){i._currentFaceIndex=e,i._filter===t.FILTER_PCF&&r.setColorWrite(!1)})),this._shadowMap.customRenderFunction=this._renderForShadowMap.bind(this),this._shadowMap.onAfterUnbindObservable.add((function(){if(i._filter===t.FILTER_PCF&&r.setColorWrite(!0),i.useBlurExponentialShadowMap||i.useBlurCloseExponentialShadowMap){var e=i.getShadowMapForRendering();e&&i._scene.postProcessManager.directRender(i._blurPostProcesses,e.getInternalTexture(),!0)}}));var n=new e.Color4(0,0,0,0),o=new e.Color4(1,1,1,1);this._shadowMap.onClearObservable.add((function(e){i._filter===t.FILTER_PCF?e.clear(o,!1,!0,!1):i.useExponentialShadowMap||i.useBlurExponentialShadowMap?e.clear(n,!0,!0,!1):e.clear(o,!0,!0,!1)}))},t.prototype._initializeBlurRTTAndPostProcesses=function(){var t=this,i=this._scene.getEngine(),r=this._mapSize/this.blurScale;this.useKernelBlur&&1===this.blurScale||(this._shadowMap2=new e.RenderTargetTexture(this._light.name+"_shadowMap2",r,this._scene,!1,!0,this._textureType),this._shadowMap2.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new e.BlurPostProcess(this._light.name+"KernelBlurX",new e.Vector2(1,0),this.blurKernel,1,null,e.Texture.BILINEAR_SAMPLINGMODE,i,!1,this._textureType),this._kernelBlurXPostprocess.width=r,this._kernelBlurXPostprocess.height=r,this._kernelBlurXPostprocess.onApplyObservable.add((function(e){e.setTexture("textureSampler",t._shadowMap)})),this._kernelBlurYPostprocess=new e.BlurPostProcess(this._light.name+"KernelBlurY",new e.Vector2(0,1),this.blurKernel,1,null,e.Texture.BILINEAR_SAMPLINGMODE,i,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===e.Engine.TEXTURETYPE_UNSIGNED_INT&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new e.PostProcess(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,e.Texture.BILINEAR_SAMPLINGMODE,i,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",r,r),e.setTexture("textureSampler",t._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])},t.prototype._renderForShadowMap=function(e,t,i,r){var n,o=this._scene.getEngine();if(r.length){for(o.setColorWrite(!1),n=0;n=a.length)return void(e&&e(i));setTimeout(d,16)}};d()},t.prototype.forceCompilationAsync=function(e){var t=this;return new Promise(function(i){t.forceCompilation((function(){i()}),e)})},t.prototype.isReady=function(t,i){var r=[];this._textureType!==e.Engine.TEXTURETYPE_UNSIGNED_INT&&r.push("#define FLOAT"),this.useExponentialShadowMap||this.useBlurExponentialShadowMap?r.push("#define ESM"):(this.usePercentageCloserFiltering||this.useContactHardeningShadow)&&r.push("#define DEPTHTEXTURE");var n=[e.VertexBuffer.PositionKind],o=t.getMesh(),s=t.getMaterial();if(this.normalBias&&o.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(n.push(e.VertexBuffer.NormalKind),r.push("#define NORMAL"),o.nonUniformScaling&&r.push("#define NONUNIFORMSCALING"),this.getLight().getTypeID()===e.Light.LIGHTTYPEID_DIRECTIONALLIGHT&&r.push("#define DIRECTIONINLIGHTDATA")),s&&s.needAlphaTesting()){var a=s.getAlphaTestTexture();a&&(r.push("#define ALPHATEST"),o.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push(e.VertexBuffer.UVKind),r.push("#define UV1")),o.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&1===a.coordinatesIndex&&(n.push(e.VertexBuffer.UV2Kind),r.push("#define UV2")))}o.useBones&&o.computeBonesUsingShaders?(n.push(e.VertexBuffer.MatricesIndicesKind),n.push(e.VertexBuffer.MatricesWeightsKind),o.numBoneInfluencers>4&&(n.push(e.VertexBuffer.MatricesIndicesExtraKind),n.push(e.VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton.bones.length+1))):r.push("#define NUM_BONE_INFLUENCERS 0");var l=o.morphTargetManager,c=0;l&&l.numInfluencers>0&&(r.push("#define MORPHTARGETS"),c=l.numInfluencers,r.push("#define NUM_MORPH_INFLUENCERS "+c),e.MaterialHelper.PrepareAttributesForMorphTargets(n,o,{NUM_MORPH_INFLUENCERS:c})),i&&(r.push("#define INSTANCES"),n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"));var h=r.join("\n");return this._cachedDefines!==h&&(this._cachedDefines=h,this._effect=this._scene.getEngine().createEffect("shadowMap",n,["world","mBones","viewProjection","diffuseMatrix","lightData","depthValues","biasAndScale","morphTargetInfluences"],["diffuseSampler"],h,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c})),!!this._effect.isReady()&&((this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady())&&(!(this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady())&&!(this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())))},t.prototype.prepareDefines=function(e,i){var r=this._scene,n=this._light;r.shadowsEnabled&&n.shadowEnabled&&(e["SHADOW"+i]=!0,this.useContactHardeningShadow&&(e["SHADOWPCSS"+i]=!0,this._filteringQuality===t.QUALITY_LOW?e["SHADOWLOWQUALITY"+i]=!0:this._filteringQuality===t.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+i]=!0)),this.usePercentageCloserFiltering?(e["SHADOWPCF"+i]=!0,this._filteringQuality===t.QUALITY_LOW?e["SHADOWLOWQUALITY"+i]=!0:this._filteringQuality===t.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+i]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+i]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+i]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+i]=!0),n.needCube()&&(e["SHADOWCUBE"+i]=!0))},t.prototype.bindShadowLight=function(e,i){var r=this._light,n=this._scene;if(n.shadowsEnabled&&r.shadowEnabled){var o=n.activeCamera;if(o){var s=this.getShadowMap();s&&(r.needCube()||i.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===t.FILTER_PCF?(i.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),s.getSize().width,1/s.getSize().width,this.frustumEdgeFalloff,e)):this._filter===t.FILTER_PCSS?(i.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()), +i.setTexture("depthSampler"+e,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/s.getSize().width,this._contactHardeningLightSizeUVRatio*s.getSize().width,this.frustumEdgeFalloff,e)):(i.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/s.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),r._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(o),this.getLight().getDepthMinZ(o)+this.getLight().getDepthMaxZ(o),e))}}},t.prototype.getTransformMatrix=function(){var t=this._scene;if(this._currentRenderID===t.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderID=t.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;var i=this._light.position;if(this._light.computeTransformedInformation()&&(i=this._light.transformedPosition),e.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(e.Vector3.Dot(this._lightDirection,e.Vector3.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!i.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(i),this._cachedDirection.copyFrom(this._lightDirection),e.Matrix.LookAtLHToRef(i,i.add(this._lightDirection),e.Vector3.Up(),this._viewMatrix);var r=this.getShadowMap();if(r){var n=r.renderList;n&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,n)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix},t.prototype.recreateShadowMap=function(){var e=this._shadowMap;if(e){var t=e.renderList;this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this.filter,this._applyFilterValues(),this._shadowMap.renderList=t}},t.prototype._disposeBlurPostProcesses=function(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]},t.prototype._disposeRTTandPostProcesses=function(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()},t.prototype.dispose=function(){this._disposeRTTandPostProcesses(),this._light&&(this._light._shadowGenerator=null,this._light._markMeshesAsLightDirty())},t.prototype.serialize=function(){var e={},t=this.getShadowMap();if(!t)return e;if(e.lightId=this._light.id,e.mapSize=t.getRenderSize(),e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.forceBackFacesOnly=this.forceBackFacesOnly,e.depthScale=this.depthScale,e.darkness=this.getDarkness(),e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.filteringQuality=this.filteringQuality,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.renderList=[],t.renderList)for(var i=0;i0){for(var ne=0;ne0){for(var se=0;se-1&&void 0!==f.skeletons&&null!==f.skeletons){if(!1===v.indexOf(b.skeletonId)>-1)for(var D=0,I=f.skeletons.length;D0&&this._textureLoadingCallback(e)}this._currentScene.render()}},t.prototype.drag=function(e){e.stopPropagation(),e.preventDefault()},t.prototype.drop=function(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)},t.prototype._traverseFolder=function(e,t,i,r){var n=this,o=e.createReader(),s=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");o.readEntries((function(e){i.count+=e.length;for(var o=0,a=e;o0){for(var i=new Array,r=[],n=e.dataTransfer?e.dataTransfer.items:null,o=0;o0&&e.Tools.ClearLogCache(),this._engine.stopRenderLoop()),e.SceneLoader.LoadAsync("file:",this._sceneFileToLoad,this._engine,(function(e){t._progressCallback&&t._progressCallback(e)})).then((function(e){t._currentScene&&t._currentScene.dispose(),t._currentScene=e,t._sceneLoadedCallback&&t._sceneLoadedCallback(t._sceneFileToLoad,t._currentScene),t._currentScene.executeWhenReady((function(){t._engine.runRenderLoop((function(){t.renderFunction()}))}))})).catch((function(e){t._errorCallback&&t._errorCallback(t._sceneFileToLoad,t._currentScene,e.message)}))):e.Tools.Error("Please provide a valid .babylon file.")},t.FilesToLoad={},t})();e.FilesInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.EnableFor=function(e){e._tags=e._tags||{},e.hasTags=function(){return t.HasTags(e)},e.addTags=function(i){return t.AddTagsTo(e,i)},e.removeTags=function(i){return t.RemoveTagsFrom(e,i)},e.matchesTagsQuery=function(i){return t.MatchesQuery(e,i)}},t.DisableFor=function(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery},t.HasTags=function(t){return!!t._tags&&!e.Tools.IsEmpty(t._tags)},t.GetTags=function(e,t){if(void 0===t&&(t=!0),!e._tags)return null;if(t){var i=[];for(var r in e._tags)e._tags.hasOwnProperty(r)&&!0===e._tags[r]&&i.push(r);return i.join(" ")}return e._tags},t.AddTagsTo=function(e,i){if(i&&"string"==typeof i){i.split(" ").forEach((function(i,r,n){t._AddTagTo(e,i)}))}},t._AddTagTo=function(e,i){""!==(i=i.trim())&&"true"!==i&&"false"!==i&&(i.match(/[\s]/)||i.match(/^([!]|([|]|[&]){2})/)||(t.EnableFor(e),e._tags[i]=!0))},t.RemoveTagsFrom=function(e,i){if(t.HasTags(e)){var r=i.split(" ");for(var n in r)t._RemoveTagFrom(e,r[n])}},t._RemoveTagFrom=function(e,t){delete e._tags[t]},t.MatchesQuery=function(i,r){return void 0===r||(""===r?t.HasTags(i):e.AndOrNotEvaluator.Eval(r,(function(e){return t.HasTags(i)&&i._tags[e]})))},t})();e.Tags=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){}return e.Eval=function(t,i){return"true"===(t=t.match(/\([^\(\)]*\)/g)?t.replace(/\([^\(\)]*\)/g,(function(t){return t=t.slice(1,t.length-1),e._HandleParenthesisContent(t,i)})):e._HandleParenthesisContent(t,i))||"false"!==t&&e.Eval(t,i)},e._HandleParenthesisContent=function(t,i){i=i||function(e){return"true"===e};var r,n=t.split("||");for(var o in n)if(n.hasOwnProperty(o)){var s=e._SimplifyNegation(n[o].trim()),a=s.split("&&");if(a.length>1)for(var l=0;l=400&&o?o(c):i()}),!1),c.addEventListener("error",(function(t){e.Tools.Error("error on XHR request."),i()}),!1),c.send()}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i()},t.IsUASupportingBlobStorage=!0,t.IDBStorageEnabled=!0,t._ParseURL=function(e){document.createElement("a").href=e;var t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},t._ReturnFullUrlLocation=function(e){return-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")?t._ParseURL(window.location.href)+e:e},t})();e.Database=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._isEnabled=!0,this.leftColor=e.Color3.White(),this.rightColor=e.Color3.Black(),this.bias=0,this.power=1}return Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(t){this._isEnabled!==t&&(this._isEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.FresnelDirtyFlag|e.Material.MiscDirtyFlag))},enumerable:!0,configurable:!0}),t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.serialize=function(){var e={};return e.isEnabled=this.isEnabled,e.leftColor=this.leftColor.asArray(),e.rightColor=this.rightColor.asArray(),e.bias=this.bias,e.power=this.power,e},t.Parse=function(i){var r=new t;return r.isEnabled=i.isEnabled,r.leftColor=e.Color3.FromArray(i.leftColor),r.rightColor=e.Color3.FromArray(i.rightColor),r.bias=i.bias,r.power=i.power||1,r},t})();e.FresnelParameters=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i){var r=t.call(this,e,i,!0)||this;return i.multiMaterials.push(r),r.subMaterials=new Array,r.storeEffectOnSubMeshes=!0,r}return o(i,t),Object.defineProperty(i.prototype,"subMaterials",{get:function(){return this._subMaterials},set:function(e){this._subMaterials=e,this._hookArray(e)},enumerable:!0,configurable:!0}),i.prototype._hookArray=function(e){var t=this,i=e.push;e.push=function(){for(var r=[],n=0;n=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]},i.prototype.getActiveTextures=function(){var e;return(e=t.prototype.getActiveTextures.call(this)).concat.apply(e,this.subMaterials.map((function(e){return e?e.getActiveTextures():[]})))},i.prototype.getClassName=function(){return"MultiMaterial"},i.prototype.isReadyForSubMesh=function(e,t,i){for(var r=0;r=0&&r.multiMaterials.splice(n,1),t.prototype.dispose.call(this,e,i)}},i})(e.Material);e.MultiMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250}return t.prototype.attachControl=function(t,i){var r=this,n=null;void 0===this._pointerInput&&(this._onLostFocus=function(e){r._offsetX=null,r._offsetY=null},this._pointerInput=function(t,o){var s=t.event;if("mouse"!==s.pointerType)if(t.type===e.PointerEventTypes.POINTERDOWN){if(i||s.preventDefault(),r._pointerPressed.push(s.pointerId),1!==r._pointerPressed.length)return;n={x:s.clientX,y:s.clientY}}else if(t.type===e.PointerEventTypes.POINTERUP){i||s.preventDefault();var a=r._pointerPressed.indexOf(s.pointerId);if(-1===a)return;if(r._pointerPressed.splice(a,1),0!=a)return;n=null,r._offsetX=null,r._offsetY=null}else if(t.type===e.PointerEventTypes.POINTERMOVE){if(i||s.preventDefault(),!n)return;var a=r._pointerPressed.indexOf(s.pointerId);if(0!=a)return;r._offsetX=s.clientX-n.x,r._offsetY=-(s.clientY-n.y)}}),this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE),this._onLostFocus&&t.addEventListener("blur",this._onLostFocus)},t.prototype.detachControl=function(e){this._pointerInput&&e&&(this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null),this._onLostFocus&&(e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null),this._pointerPressed=[],this._offsetX=null,this._offsetY=null)},t.prototype.checkInputs=function(){if(this._offsetX&&this._offsetY){var t=this.camera;if(t.cameraRotation.y+=this._offsetX/this.touchAngularSensibility,this._pointerPressed.length>1)t.cameraRotation.x+=-this._offsetY/this.touchAngularSensibility;else{var i=t._computeLocalCameraSpeed(),r=new e.Vector3(0,0,i*this._offsetY/this.touchMoveSensibility);e.Matrix.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,0,t._cameraRotationMatrix),t.cameraDirection.addInPlace(e.Vector3.TransformCoordinates(r,t._cameraRotationMatrix))}}},t.prototype.getClassName=function(){return"FreeCameraTouchInput"},t.prototype.getSimpleName=function(){return"touch"},n([e.serialize()],t.prototype,"touchAngularSensibility",void 0),n([e.serialize()],t.prototype,"touchMoveSensibility",void 0),t})();e.FreeCameraTouchInput=t,e.CameraInputTypes.FreeCameraTouchInput=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("TouchCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addTouch(),n._setupInputs(),n}return o(t,e),Object.defineProperty(t.prototype,"touchAngularSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"touchMoveSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"TouchCamera"},t.prototype._setupInputs=function(){var e=this.inputs.attached.mouse;e&&(e.touchEnabled=!1)},t})(e.FreeCamera);e.TouchCamera=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l){void 0===s&&(s=null),void 0===a&&(a=!0),void 0===l&&(l=!1);var c=t.call(this,null,o,!a)||this;c.isCube=l,c.isEnabled=!0,c._currentRefreshId=-1,c._refreshRate=1,c._vertexBuffers={},c._uniforms=new Array,c._samplers=new Array,c._textures={},c._floats={},c._ints={},c._floatsArrays={},c._colors3={},c._colors4={},c._vectors2={},c._vectors3={},c._matrices={},c._fallbackTextureUsed=!1,o=c.getScene(),o.proceduralTextures.push(c),c._engine=o.getEngine(),c.name=i,c.isRenderTarget=!0,c._size=r,c._generateMipMaps=a,c.setFragment(n),c._fallbackTexture=s,l?(c._texture=c._engine.createRenderTargetCubeTexture(r,{generateMipMaps:a}),c.setFloat("face",0)):c._texture=c._engine.createRenderTargetTexture(r,a);var h=[];return h.push(1,1),h.push(-1,1),h.push(-1,-1),h.push(1,-1),c._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(c._engine,h,e.VertexBuffer.PositionKind,!1,!1,2),c._createIndexBuffer(),c}return o(i,t),i.prototype._createIndexBuffer=function(){var e=this._engine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)},i.prototype._rebuild=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&t._rebuild(),this._createIndexBuffer(),this.refreshRate===e.RenderTargetTexture.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=e.RenderTargetTexture.REFRESHRATE_RENDER_ONCE)},i.prototype.reset=function(){if(void 0!==this._effect){this._engine._releaseEffect(this._effect)}},i.prototype.isReady=function(){var t,i=this,r=this._engine;return!!this._fragment&&(!!this._fallbackTextureUsed||(t=void 0!==this._fragment.fragmentElement?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._effect=r.createEffect(t,[e.VertexBuffer.PositionKind],this._uniforms,this._samplers,"",void 0,void 0,(function(){i.releaseInternalTexture(),i._fallbackTexture&&(i._texture=i._fallbackTexture._texture,i._texture&&i._texture.incrementReferences()),i._fallbackTextureUsed=!0})),this._effect.isReady()))},i.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},i.prototype.setFragment=function(e){this._fragment=e},Object.defineProperty(i.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!0,configurable:!0}),i.prototype._shouldRender=function(){return!!(this.isEnabled&&this.isReady()&&this._texture)&&(!this._fallbackTextureUsed&&(-1===this._currentRefreshId?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)))},i.prototype.getRenderSize=function(){return this._size},i.prototype.resize=function(e,t){this._fallbackTextureUsed||(this.releaseInternalTexture(),this._texture=this._engine.createRenderTargetTexture(e,t),this._size=e,this._generateMipMaps=t)},i.prototype._checkUniform=function(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)},i.prototype.setTexture=function(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this},i.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},i.prototype.setInt=function(e,t){return this._checkUniform(e),this._ints[e]=t,this},i.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},i.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},i.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},i.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},i.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},i.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},i.prototype.render=function(t){var i=this.getScene();if(i){var r=this._engine;r.enableEffect(this._effect),r.setState(!1);for(var n in this._textures)this._effect.setTexture(n,this._textures[n]);for(n in this._ints)this._effect.setInt(n,this._ints[n]);for(n in this._floats)this._effect.setFloat(n,this._floats[n]);for(n in this._floatsArrays)this._effect.setArray(n,this._floatsArrays[n]);for(n in this._colors3)this._effect.setColor3(n,this._colors3[n]);for(n in this._colors4){var o=this._colors4[n];this._effect.setFloat4(n,o.r,o.g,o.b,o.a)}for(n in this._vectors2)this._effect.setVector2(n,this._vectors2[n]);for(n in this._vectors3)this._effect.setVector3(n,this._vectors3[n]);for(n in this._matrices)this._effect.setMatrix(n,this._matrices[n]);if(this._texture){ +if(this.isCube)for(var s=0;s<6;s++)r.bindFramebuffer(this._texture,s,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),this._effect.setFloat("face",s),r.clear(i.clearColor,!0,!0,!0),r.drawElementsType(e.Material.TriangleFillMode,0,6),5===s&&r.generateMipMapsForCubemap(this._texture);else r.bindFramebuffer(this._texture,0,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),r.clear(i.clearColor,!0,!0,!0),r.drawElementsType(e.Material.TriangleFillMode,0,6);r.unBindFramebuffer(this._texture,this.isCube),this.onGenerated&&this.onGenerated()}}},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t},i.prototype.dispose=function(){var i=this.getScene();if(i){var r=i.proceduralTextures.indexOf(this);r>=0&&i.proceduralTextures.splice(r,1);var n=this._vertexBuffers[e.VertexBuffer.PositionKind];n&&(n.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),t.prototype.dispose.call(this)}},n([e.serialize()],i.prototype,"_size",void 0),n([e.serialize()],i.prototype,"_generateMipMaps",void 0),n([e.serialize()],i.prototype,"isEnabled",void 0),n([e.serialize()],i.prototype,"refreshRate",null),i})(e.Texture);e.ProceduralTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i,r,n,o,s){var a=t.call(this,e,r,null,n,o,s)||this;return a._animate=!0,a._time=0,a._texturePath=i,a.loadJson(i),a.refreshRate=1,a}return o(i,t),i.prototype.loadJson=function(t){var i=this,r=function(){e.Tools.Log("No config file found in "+t+" trying to use ShadersStore or DOM element");try{i.setFragment(i._texturePath)}catch(t){e.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},n=t+"/config.json",o=new XMLHttpRequest;o.open("GET",n,!0),o.addEventListener("load",(function(){if(200===o.status||e.Tools.ValidateXHRData(o,1))try{i._config=JSON.parse(o.response),i.updateShaderUniforms(),i.updateTextures(),i.setFragment(i._texturePath+"/custom"),i._animate=i._config.animate,i.refreshRate=i._config.refreshrate}catch(e){r()}else r()}),!1),o.addEventListener("error",(function(){r()}),!1);try{o.send()}catch(t){e.Tools.Error("CustomProceduralTexture: Error on XHR send request.")}},i.prototype.isReady=function(){if(!t.prototype.isReady.call(this))return!1;for(var e in this._textures){if(!this._textures[e].isReady())return!1}return!0},i.prototype.render=function(e){var i=this.getScene();this._animate&&i&&(this._time+=.03*i.getAnimationRatio(),this.updateShaderUniforms()),t.prototype.render.call(this,e)},i.prototype.updateTextures=function(){for(var t=0;t.005?0+r:0,i.y=Math.abs(n)>.005?0+n:0;var o=this.gamepad.rightStick;if(o){var s=o.x/this.gamepadAngularSensibility,a=o.y/this.gamepadAngularSensibility;o.x=Math.abs(s)>.001?0+s:0,o.y=Math.abs(a)>.001?0+a:0}else o={x:0,y:0};t.rotationQuaternion?t.rotationQuaternion.toRotationMatrix(this._cameraTransform):e.Matrix.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,0,this._cameraTransform);var l=50*t._computeLocalCameraSpeed();this._vector3.copyFromFloats(i.x*l,0,-i.y*l),e.Vector3.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),t.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(o.y,o.x),t.cameraRotation.addInPlace(this._vector2)}},t.prototype.getClassName=function(){return"FreeCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},n([e.serialize()],t.prototype,"gamepadAngularSensibility",void 0),n([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.FreeCameraGamepadInput=t,e.CameraInputTypes.FreeCameraGamepadInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40}return t.prototype.attachControl=function(t,i){var r=this,n=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=n.onGamepadConnectedObservable.add((function(t){t.type!==e.Gamepad.POSE_ENABLED&&(r.gamepad&&t.type!==e.Gamepad.XBOX||(r.gamepad=t))})),this._onGamepadDisconnectedObserver=n.onGamepadDisconnectedObservable.add((function(e){r.gamepad===e&&(r.gamepad=null)})),this.gamepad=n.getGamepadByType(e.Gamepad.XBOX)},t.prototype.detachControl=function(e){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null},t.prototype.checkInputs=function(){if(this.gamepad){var e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){var i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){var r=t.y/this.gamepadRotationSensibility;0!=r&&Math.abs(r)>.005&&(e.inertialBetaOffset+=r)}}var n=this.gamepad.leftStick;if(n&&0!=n.y){var o=n.y/this.gamepadMoveSensibility;0!=o&&Math.abs(o)>.005&&(this.camera.inertialRadiusOffset-=o)}}},t.prototype.getClassName=function(){return"ArcRotateCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},n([e.serialize()],t.prototype,"gamepadRotationSensibility",void 0),n([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.ArcRotateCameraGamepadInput=t,e.CameraInputTypes.ArcRotateCameraGamepadInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){var i=this;this._scene=t,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new e.Observable,e.Tools.IsWindowObjectExist()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator.getGamepads||navigator.webkitGetGamepads||navigator.msGetGamepads||navigator.webkitGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new e.Observable(function(e){for(var t in i._babylonGamepads){var r=i._babylonGamepads[t];r&&r._isConnected&&i.onGamepadConnectedObservable.notifyObserver(e,r)}}),this._onGamepadConnectedEvent=function(e){var t=e.gamepad;if(!(t.index in i._babylonGamepads&&i._babylonGamepads[t.index].isConnected)){var r;i._babylonGamepads[t.index]?(r=i._babylonGamepads[t.index],r.browserGamepad=t,r._isConnected=!0):r=i._addNewGamepad(t),i.onGamepadConnectedObservable.notifyObservers(r),i._startMonitoringGamepads()}},this._onGamepadDisconnectedEvent=function(e){var t=e.gamepad;for(var r in i._babylonGamepads)if(i._babylonGamepads[r].index===t.index){var n=i._babylonGamepads[r];n._isConnected=!1,i.onGamepadDisconnectedObservable.notifyObservers(n);break}},this._gamepadSupport&&(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported?(window.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1)):this._startMonitoringGamepads())}return Object.defineProperty(t.prototype,"gamepads",{get:function(){return this._babylonGamepads},enumerable:!0,configurable:!0}),t.prototype.getGamepadByType=function(t){void 0===t&&(t=e.Gamepad.XBOX);for(var i=0,r=this._babylonGamepads;i=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}return Object.defineProperty(e.prototype,"isConnected",{get:function(){return this._isConnected},enumerable:!0,configurable:!0}),e.prototype.onleftstickchanged=function(e){this._onleftstickchanged=e},e.prototype.onrightstickchanged=function(e){this._onrightstickchanged=e},Object.defineProperty(e.prototype,"leftStick",{get:function(){return this._leftStick},set:function(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightStick",{get:function(){return this._rightStick},set:function(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e},enumerable:!0,configurable:!0}),e.prototype.update=function(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})},e.prototype.dispose=function(){},e.GAMEPAD=0,e.GENERIC=1,e.XBOX=2,e.POSE_ENABLED=3,e})();e.Gamepad=i;var r=(function(t){function r(r,n,o){var s=t.call(this,r,n,o)||this;return s.onButtonDownObservable=new e.Observable,s.onButtonUpObservable=new e.Observable,s.type=i.GENERIC,s._buttons=new Array(o.buttons.length),s}return o(r,t),r.prototype.onbuttondown=function(e){this._onbuttondown=e},r.prototype.onbuttonup=function(e){this._onbuttonup=e},r.prototype._setButtonValue=function(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},r.prototype.update=function(){t.prototype.update.call(this);for(var e=0;ethis._maxRotationDistFromHeadset){var n=r-(r<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=n;var o=Math.sin(-n),s=Math.cos(-n);this._calculatedPosition.x=this._calculatedPosition.x*s-this._calculatedPosition.z*o,this._calculatedPosition.z=this._calculatedPosition.x*o+this._calculatedPosition.z*s}}},i.prototype.initControllerMesh=function(t,r){var n=this;e.SceneLoader.ImportMesh("",i.MODEL_BASE_URL,i.MODEL_FILENAME,t,(function(i){var o=new e.Mesh("",t);i[1].parent=o,i[1].position.z=-.15,n._defaultModel=o,n.attachToMesh(n._defaultModel),r&&r(n._defaultModel)}))},i.prototype._handleButtonChange=function(e,t,i){if(ethis.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),(f>this.maxCameraSpeed||f<-this.maxCameraSpeed)&&(f=f<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new e.Vector3(this.position.x+u,this.position.y+d,this.position.z+f),this.setTarget(o)}},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.lockedTarget&&this.follow(this.lockedTarget)},i.prototype.getClassName=function(){return"FollowCamera"},n([e.serialize()],i.prototype,"radius",void 0),n([e.serialize()],i.prototype,"rotationOffset",void 0),n([e.serialize()],i.prototype,"heightOffset",void 0),n([e.serialize()],i.prototype,"cameraAcceleration",void 0),n([e.serialize()],i.prototype,"maxCameraSpeed",void 0),n([e.serializeAsMeshReference("lockedTargetId")],i.prototype,"lockedTarget",void 0),i})(e.TargetCamera);e.FollowCamera=t;var i=(function(t){function i(i,r,n,o,s,a){var l=t.call(this,i,e.Vector3.Zero(),a)||this;return l.alpha=r,l.beta=n,l.radius=o,l.target=s,l._cartesianCoordinates=e.Vector3.Zero(),l.follow(),l}return o(i,t),i.prototype.follow=function(){if(this.target){this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);var e=this.target.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.follow()},i.prototype.getClassName=function(){return"ArcFollowCamera"},i})(e.TargetCamera);e.ArcFollowCamera=i})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addGamepad(),n}return o(t,e),Object.defineProperty(t.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"UniversalCamera"},t})(e.TouchCamera);e.UniversalCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("GamepadCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(e){function t(t,i,r){return e.call(this,t,i,r)||this}return o(t,e),Object.defineProperty(t.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"GamepadCamera"},t})(e.UniversalCamera);e.GamepadCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this._renderPipelines={}}return e.prototype.addPipeline=function(e){this._renderPipelines[e._name]=e},e.prototype.attachCamerasToRenderPipeline=function(e,t,i){void 0===i&&(i=!1);var r=this._renderPipelines[e];r&&r._attachCameras(t,i)},e.prototype.detachCamerasFromRenderPipeline=function(e,t){var i=this._renderPipelines[e];i&&i._detachCameras(t)},e.prototype.enableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._enableEffect(t,i)},e.prototype.disableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._disableEffect(t,i)},e.prototype.update=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}},e.prototype._rebuild=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t._rebuild()}},e.prototype.dispose=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t.dispose()}},e})();e.PostProcessRenderPipelineManager=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}return Object.defineProperty(t.prototype,"isSupported",{get:function(){for(var e in this._postProcesses)if(this._postProcesses.hasOwnProperty(e))for(var t=this._postProcesses[e],i=0;i=2&&t.length>0){var i=this._renderEffects[t[0]].getPostProcesses();if(i)return i[0].samples=e,!0}return!1},t.prototype.dispose=function(){},n([e.serialize()],t.prototype,"_name",void 0),t})();e.PostProcessRenderPipeline=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){void 0===i&&(i=e.Engine.TEXTURETYPE_FLOAT),void 0===r&&(r=null);var n=this;this._scene=t,this._camera=r;var o=t.getEngine();this._depthMap=new e.RenderTargetTexture("depthMap",{width:o.getRenderWidth(),height:o.getRenderHeight()},this._scene,!1,!0,i),this._depthMap.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._depthMap.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((function(t){t.clear(new e.Color4(1,1,1,1),!0,!0,!0)}));var s=function(t){var i=t.getRenderingMesh(),r=n._scene,o=r.getEngine(),s=t.getMaterial();if(s){o.setState(s.backFaceCulling,0,!1,r.useRightHandedSystem);var a=i._getInstancesRenderList(t._id);if(!a.mustReturn){var l=o.getCaps().instancedArrays&&null!==a.visibleInstances[t._id],c=n._camera||r.activeCamera;if(n.isReady(t,l)&&c){if(o.enableEffect(n._effect),i._bind(t,n._effect,e.Material.TriangleFillMode),n._effect.setMatrix("viewProjection",r.getTransformMatrix()),n._effect.setFloat2("depthValues",c.minZ,c.minZ+c.maxZ),s&&s.needAlphaTesting()){var h=s.getAlphaTestTexture();h&&(n._effect.setTexture("diffuseSampler",h),n._effect.setMatrix("diffuseMatrix",h.getTextureMatrix()))}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&n._effect.setMatrices("mBones",i.skeleton.getTransformMatrices(i)),i._processRendering(t,n._effect,e.Material.TriangleFillMode,a,l,(function(e,t){return n._effect.setMatrix("world",t)}))}}}};this._depthMap.customRenderFunction=function(e,t,i,r){var n;if(r.length){for(o.setColorWrite(!1),n=0;n4&&(o.push(e.VertexBuffer.MatricesIndicesExtraKind),o.push(e.VertexBuffer.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("depth",o,["world","mBones","viewProjection","diffuseMatrix","depthValues"],["diffuseSampler"],a)),this._effect.isReady()},t.prototype.getDepthMap=function(){return this._depthMap},t.prototype.dispose=function(){this._depthMap.dispose()},t})();e.DepthRenderer=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o){var s=t.call(this,r.getEngine(),i)||this;s.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",s.SSAORenderEffect="SSAORenderEffect",s.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",s.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",s.SSAOCombineRenderEffect="SSAOCombineRenderEffect",s.totalStrength=1,s.radius=1e-4,s.area=.0075,s.fallOff=1e-6,s.base=.5,s._firstUpdate=!0,s._scene=r,s._createRandomTexture(),s._depthTexture=r.enableDepthRenderer().getDepthMap();var a=n.ssaoRatio||n,l=n.combineRatio||n;return s._originalColorPostProcess=new e.PassPostProcess("SSAOOriginalSceneColor",l,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),!1),s._createSSAOPostProcess(a),s._createBlurPostProcess(a),s._createSSAOCombinePostProcess(l),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOOriginalSceneColorEffect,function(){return s._originalColorPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAORenderEffect,function(){return s._ssaoPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOBlurHRenderEffect,function(){return s._blurHPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOBlurVRenderEffect,function(){return s._blurVPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOCombineRenderEffect,function(){return s._ssaoCombinePostProcess},!0)),r.postProcessRenderPipelineManager.addPipeline(s),o&&r.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(i,o),s}return o(i,t),i.prototype.dispose=function(e){void 0===e&&(e=!1);for(var i=0;i0?r._ssaoCombinePostProcess.width:r._originalColorPostProcess.width),e.setFloat("near",r._scene.activeCamera.minZ),e.setFloat("far",r._scene.activeCamera.maxZ),e.setFloat("radius",r.radius),e.setTexture("depthSampler",r._depthTexture),r._firstUpdate&&e.setArray("samplerOffsets",r._samplerOffsets))},this._blurVPostProcess=new e.PostProcess("BlurV","ssao2",["outSize","samplerOffsets","near","far","radius"],["depthSampler"],i,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE "+(n?"1":"0")+"\n"),this._blurVPostProcess.onApply=function(e){r._scene.activeCamera&&(e.setFloat("outSize",r._ssaoCombinePostProcess.height>0?r._ssaoCombinePostProcess.height:r._originalColorPostProcess.height),e.setFloat("near",r._scene.activeCamera.minZ),e.setFloat("far",r._scene.activeCamera.maxZ),e.setFloat("radius",r.radius),e.setTexture("depthSampler",r._depthTexture),r._firstUpdate&&(e.setArray("samplerOffsets",r._samplerOffsets),r._firstUpdate=!1))}},i.prototype._rebuild=function(){this._firstUpdate=!0,t.prototype._rebuild.call(this)},i.prototype._generateHemisphere=function(){for(var t,i,r=this.samples,n=[],o=function(e,t){return Math.random()*(t-e)+e},s=0;s=0;a--){var o=Math.pow(3,a),l="#define LUMINANCE_DOWN_SAMPLE\n";0===a&&(l+="#define FINAL_DOWN_SAMPLER");var c=new e.PostProcess("HDRLuminanceDownSample"+a,"standard",["dsOffsets","halfDestPixelSize"],[],{width:o,height:o},null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,l,r);this.luminanceDownSamplePostProcesses.push(c)}var h=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((function(i,r){var o=new Array(18);i.onApply=function(e){if(h){for(var t=0,s=-1;s<2;s++)for(var a=-1;a<2;a++)o[t]=s/h.width,o[t+1]=a/h.height,t+=2;e.setArray2("dsOffsets",o),e.setFloat("halfDestPixelSize",.5/h.width),h=r===n.luminanceDownSamplePostProcesses.length-1?n.luminancePostProcess:i}},r===n.luminanceDownSamplePostProcesses.length-1&&(i.onAfterRender=function(i){var r=t.getEngine().readPixels(0,0,1,1),o=new e.Vector4(1/16581375,1/65025,1/255,1);n._hdrCurrentLuminance=(r[0]*o.x+r[1]*o.y+r[2]*o.z+r[3]*o.w)/100}),n.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLuminanceDownSample"+r,function(){return i},!0))}))},i.prototype._createHdrPostProcess=function(t,i){var r=this;this.hdrPostProcess=new e.PostProcess("HDR","standard",["averageLuminance"],["textureAdderSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define HDR",e.Engine.TEXTURETYPE_UNSIGNED_INT);var n=1,o=0,s=0;this.hdrPostProcess.onApply=function(i){if(i.setTextureFromPostProcess("textureAdderSampler",r._currentDepthOfFieldSource),o+=t.getEngine().getDeltaTime(),n<0)n=r._hdrCurrentLuminance;else{var a=(s-o)/1e3;r._hdrCurrentLuminancen-r.hdrIncreaseRate*a?n-=r.hdrIncreaseRate*a:n=r._hdrCurrentLuminance}n=e.Scalar.Clamp(n,r.hdrMinimumLuminance,1e20),i.setFloat("averageLuminance",n),s=o,r._currentDepthOfFieldSource=r.hdrFinalPostProcess},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDR",function(){return r.hdrPostProcess},!0))},i.prototype._createLensFlarePostProcess=function(t,i){var r=this;this.lensFlarePostProcess=new e.PostProcess("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],i/2,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define LENS_FLARE",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLensFlare",function(){return r.lensFlarePostProcess},!0)),this._createBlurPostProcesses(t,i/4,2),this.lensFlareComposePostProcess=new e.PostProcess("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define LENS_FLARE_COMPOSE",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLensFlareCompose",function(){return r.lensFlareComposePostProcess},!0));var n=new e.Vector2(0,0);this.lensFlarePostProcess.onApply=function(e){e.setTextureFromPostProcess("textureSampler",r._bloomEnabled?r.blurHPostProcesses[0]:r.originalPostProcess),e.setTexture("lensColorSampler",r.lensColorTexture),e.setFloat("strength",r.lensFlareStrength),e.setFloat("ghostDispersal",r.lensFlareGhostDispersal),e.setFloat("haloWidth",r.lensFlareHaloWidth),n.x=r.lensFlarePostProcess.width,n.y=r.lensFlarePostProcess.height,e.setVector2("resolution",n),e.setFloat("distortionStrength",r.lensFlareDistortionStrength)};var o=e.Matrix.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=e.Matrix.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=function(t){if(r._scene.activeCamera){t.setTextureFromPostProcess("otherSampler",r._currentDepthOfFieldSource),t.setTexture("lensDirtSampler",r.lensFlareDirtTexture),t.setTexture("lensStarSampler",r.lensStarTexture);var i=r._scene.activeCamera.getViewMatrix().getRow(0),n=r._scene.activeCamera.getViewMatrix().getRow(2),a=e.Vector3.Dot(i.toVector3(),new e.Vector3(1,0,0))+e.Vector3.Dot(n.toVector3(),new e.Vector3(0,0,1));a*=4;var l=e.Matrix.FromValues(.5*Math.cos(a),-Math.sin(a),0,0,Math.sin(a),.5*Math.cos(a),0,0,0,0,1,0,0,0,0,1),c=s.multiply(l).multiply(o);t.setMatrix("lensStarMatrix",c),r._currentDepthOfFieldSource=r.lensFlareFinalPostProcess}}},i.prototype._createDepthOfFieldPostProcess=function(t,i){var r=this;this.depthOfFieldPostProcess=new e.PostProcess("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define DEPTH_OF_FIELD",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.depthOfFieldPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",r._currentDepthOfFieldSource),e.setTexture("depthSampler",r._getDepthTexture()),e.setFloat("distance",r.depthOfFieldDistance)},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRDepthOfField",function(){return r.depthOfFieldPostProcess},!0))},i.prototype._createMotionBlurPostProcess=function(t,i){var r=this;this.motionBlurPostProcess=new e.PostProcess("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),e.Engine.TEXTURETYPE_UNSIGNED_INT);var n=0,o=e.Matrix.Identity(),s=e.Matrix.Identity(),a=e.Matrix.Identity(),l=e.Vector2.Zero();this.motionBlurPostProcess.onApply=function(e){a=t.getProjectionMatrix().multiply(t.getViewMatrix()),a.invertToRef(s),e.setMatrix("inverseViewProjection",s),e.setMatrix("prevViewProjection",o),o=a,l.x=r.motionBlurPostProcess.width,l.y=r.motionBlurPostProcess.height,e.setVector2("screenSize",l),n=t.getEngine().getFps()/60,e.setFloat("motionScale",n),e.setFloat("motionStrength",r.motionStrength),e.setTexture("depthSampler",r._getDepthTexture())},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRMotionBlur",function(){return r.motionBlurPostProcess},!0))},i.prototype._getDepthTexture=function(){if(this._scene.getEngine().getCaps().drawBuffersExtension){return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]}return this._scene.enableDepthRenderer().getDepthMap()},i.prototype._disposePostProcesses=function(){for(var e=0;e-1?"#define MALI 1\n":null},i})(e.PostProcess);e.FxaaPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c,h,u){void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===u&&(u=!1);var d=t.call(this,i,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],o,s,a,l,c,null,h,void 0,null,u)||this;return d.aberrationAmount=30,d.radialIntensity=0,d.direction=new e.Vector2(.707,.707),d.centerPosition=new e.Vector2(.5,.5),d.onApplyObservable.add((function(e){e.setFloat("chromatic_aberration",d.aberrationAmount),e.setFloat("screen_width",r),e.setFloat("screen_height",n),e.setFloat("radialIntensity",d.radialIntensity),e.setFloat2("direction",d.direction.x,d.direction.y),e.setFloat2("centerPosition",d.centerPosition.x,d.centerPosition.y)})),d}return o(i,t),i})(e.PostProcess);e.ChromaticAberrationPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c){void 0===l&&(l=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var h=t.call(this,i,"grain",["intensity","animatedSeed"],[],r,n,o,s,a,null,l,void 0,null,c)||this;return h.intensity=30,h.animated=!1,h.onApplyObservable.add((function(e){e.setFloat("intensity",h.intensity),e.setFloat("animatedSeed",h.animated?Math.random()+1:1)})),h}return o(i,t),i})(e.PostProcess);e.GrainPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c){void 0===l&&(l=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var h=t.call(this,i,"sharpen",["sharpnessAmounts","screenSize"],null,r,n,o,s,a,null,l,void 0,null,c)||this;return h.colorAmount=1,h.edgeAmount=.3,h.onApply=function(e){e.setFloat2("screenSize",h.width,h.height),e.setFloat2("sharpnessAmounts",h.edgeAmount,h.colorAmount)},h}return o(i,t),i})(e.PostProcess);e.SharpenPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c,h,u,d){void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===u&&(u=""),void 0===d&&(d=!1);var f=t.call(this,i,"kernelBlur",["delta","direction","cameraMinMaxZ"],["circleOfConfusionSampler"],o,s,a,l,c,null,h,"kernelBlur",{varyingCount:0,depCount:0},!0)||this;return f.direction=r,f.blockCompilation=d,f._packedFloat=!1,f._staticDefines="",f._staticDefines=u,f.onApplyObservable.add((function(e){f._outputTexture?e.setFloat2("delta",1/f._outputTexture.width*f.direction.x,1/f._outputTexture.height*f.direction.y):e.setFloat2("delta",1/f.width*f.direction.x,1/f.height*f.direction.y)})),f.kernel=n,f}return o(i,t),Object.defineProperty(i.prototype,"kernel",{get:function(){return this._idealKernel},set:function(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.blockCompilation||this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"packedFloat",{get:function(){return this._packedFloat},set:function(e){this._packedFloat!==e&&(this._packedFloat=e,this.blockCompilation||this._updateParameters())},enumerable:!0,configurable:!0}),i.prototype.updateEffect=function(e,t,i,r,n,o){void 0===e&&(e=null),void 0===t&&(t=null),void 0===i&&(i=null),this._updateParameters(n,o)},i.prototype._updateParameters=function(e,i){for(var r=this._kernel,n=(r-1)/2,o=[],s=[],a=0,l=0;l0)return Math.max(n,3)}return Math.max(t,3)},i.prototype._gaussianWeight=function(e){var t=Math.sqrt(2*Math.PI)*(1/3),i=-e*e/(1/3*2*(1/3));return 1/t*Math.exp(i)},i.prototype._glslFloat=function(e,t){return void 0===t&&(t=8),e.toFixed(t).replace(/0+$/,"")},i})(e.PostProcess);e.BlurPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c,h,u,d,f,p){void 0===c&&(c=null),void 0===h&&(h=e.Texture.BILINEAR_SAMPLINGMODE),void 0===f&&(f=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===p&&(p=!1);var _=t.call(this,i,n,o,s,a,h=e.Texture.BILINEAR_SAMPLINGMODE,u,d,f=e.Engine.TEXTURETYPE_UNSIGNED_INT,"#define DOF 1\r\n",p)||this;return _.direction=n,_.onApplyObservable.add((function(e){null!=c&&e.setTextureFromPostProcess("textureSampler",c),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",l),r.activeCamera&&e.setFloat2("cameraMinMaxZ",r.activeCamera.minZ,r.activeCamera.maxZ)})),_}return o(i,t),i})(e.BlurPostProcess);e.DepthOfFieldBlurPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){}return e})();e.DepthOfFieldMergePostProcessOptions=t;var i=(function(t){function i(i,r,n,o,s,a,l,c,h,u,d){void 0===u&&(u=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===d&&(d=!1);var f=t.call(this,i,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,a,l,c,h,null,u,void 0,null,!0)||this;return f.blurSteps=o,f.onApplyObservable.add((function(e){e.setTextureFromPostProcess("textureSampler",r),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",n),o.forEach((function(t,i){e.setTextureFromPostProcessOutput("blurStep"+(o.length-i-1),t)}))})),d||f.updateEffect(),f}return o(i,t),i.prototype.updateEffect=function(e,i,r,n,o,s){void 0===e&&(e=null),void 0===i&&(i=null),void 0===r&&(r=null),e||(e="",e+="#define BLUR_LEVEL "+(this.blurSteps.length-1)+"\n"),t.prototype.updateEffect.call(this,e,i,r,n,o,s)},i})(e.PostProcess);e.DepthOfFieldMergePostProcess=i})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c,h){void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1);var u=t.call(this,i,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],n,o,s,a,l,null,c,void 0,null,h)||this;return u.lensSize=50,u.fStop=1.4,u.focusDistance=2e3,u.focalLength=50,u._depthTexture=null,u._depthTexture=r,u.onApplyObservable.add((function(t){if(!u._depthTexture)return void e.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");t.setTexture("depthSampler",u._depthTexture);var i=u.lensSize/u.fStop,r=i*u.focalLength/(u.focusDistance-u.focalLength);t.setFloat("focusDistance",u.focusDistance),t.setFloat("cocPrecalculation",r),t.setFloat2("cameraMinMaxZ",u._depthTexture.activeCamera.minZ,u._depthTexture.activeCamera.maxZ)})),u}return o(i,t),Object.defineProperty(i.prototype,"depthTexture",{set:function(e){this._depthTexture=e},enumerable:!0,configurable:!0}),i})(e.PostProcess);e.CircleOfConfusionPostProcess=t})(r||(r={}));var r;!(function(e){var t;!(function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"})(t=e.DepthOfFieldEffectBlurLevel||(e.DepthOfFieldEffectBlurLevel={}));var i=(function(i){function r(r,n,o,s,a){void 0===o&&(o=t.Low),void 0===s&&(s=0),void 0===a&&(a=!1);var l=i.call(this,r.getEngine(),"depth of field",(function(){return l._effects}),!0)||this;l._effects=[],l._circleOfConfusion=new e.CircleOfConfusionPostProcess("circleOfConfusion",n,1,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),!1,s,a),l._depthOfFieldBlurY=[],l._depthOfFieldBlurX=[];var c=1,h=15;switch(o){case t.High:c=3,h=51;break;case t.Medium:c=2,h=31;break;default:h=15,c=1}for(var u=h/Math.pow(2,c-1),d=1,f=0;f1&&e.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}},i.prototype._disposePostProcesses=function(e){void 0===e&&(e=!1);for(var t=0;t4&&(o.push(e.VertexBuffer.MatricesIndicesExtraKind),o.push(e.VertexBuffer.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("geometry",o,["world","mBones","viewProjection","diffuseMatrix","view"],["diffuseSampler"],a,void 0,void 0,void 0,{buffersCount:this._enablePosition?3:2})),this._effect.isReady()},t.prototype.getGBuffer=function(){return this._multiRenderTarget},Object.defineProperty(t.prototype,"samples",{get:function(){return this._multiRenderTarget.samples},set:function(e){this._multiRenderTarget.samples=e},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.getGBuffer().dispose()},t.prototype._createRenderTargets=function(){var t=this,i=this._scene.getEngine(),r=this._enablePosition?3:2;if(this._multiRenderTarget=new e.MultiRenderTarget("gBuffer",{width:i.getRenderWidth()*this._ratio,height:i.getRenderHeight()*this._ratio},r,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:e.Engine.TEXTURETYPE_FLOAT}),this.isSupported){this._multiRenderTarget.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null,this._multiRenderTarget.onClearObservable.add((function(t){t.clear(new e.Color4(0,0,0,1),!0,!0,!0)}));var n=function(i){var r=i.getRenderingMesh(),n=t._scene,o=n.getEngine(),s=i.getMaterial();if(s){o.setState(s.backFaceCulling,0,!1,n.useRightHandedSystem);var a=r._getInstancesRenderList(i._id);if(!a.mustReturn){var l=o.getCaps().instancedArrays&&null!==a.visibleInstances[i._id];if(t.isReady(i,l)){if(o.enableEffect(t._effect),r._bind(i,t._effect,e.Material.TriangleFillMode),t._effect.setMatrix("viewProjection",n.getTransformMatrix()),t._effect.setMatrix("view",n.getViewMatrix()),s&&s.needAlphaTesting()){var c=s.getAlphaTestTexture();c&&(t._effect.setTexture("diffuseSampler",c),t._effect.setMatrix("diffuseMatrix",c.getTextureMatrix()))}r.useBones&&r.computeBonesUsingShaders&&r.skeleton&&t._effect.setMatrices("mBones",r.skeleton.getTransformMatrices(r)),r._processRendering(i,t._effect,e.Material.TriangleFillMode,a,l,(function(e,i){return t._effect.setMatrix("world",i)}))}}}};this._multiRenderTarget.customRenderFunction=function(e,t,r,o){var s;if(o.length){for(i.setColorWrite(!1),s=0;s1,n.wrapU=e.Texture.CLAMP_ADDRESSMODE,n.wrapV=e.Texture.CLAMP_ADDRESSMODE,n.wrapR=e.Texture.CLAMP_ADDRESSMODE,n.anisotropicFilteringLevel=1,n._texture=n._getFromCache(i,!0),n._texture||(r.useDelayedTextureLoading?n.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED:n.loadTexture()),n):n}return o(i,t),i.prototype.getTextureMatrix=function(){return this._textureMatrix},i.prototype.load3dlTexture=function(){var t,r=this._engine;t=1===r.webGLVersion?r.createRawTexture(null,1,1,e.Engine.TEXTUREFORMAT_RGBA,!1,!1,e.Texture.BILINEAR_SAMPLINGMODE):r.createRawTexture3D(null,1,1,1,e.Engine.TEXTUREFORMAT_RGBA,!1,!1,e.Texture.BILINEAR_SAMPLINGMODE),this._texture=t;var n=function(n){if("string"==typeof n){for(var o,s=null,a=null,l=n.split("\n"),c=0,h=0,u=0,d=0,f=0,p=0;p0&&(p+1)%4==0)s[p]=255;else{var b=a[p];s[p]=b/f*255}t.is3D?(t.updateSize(c,c,c),r.updateRawTexture3D(t,s,e.Engine.TEXTUREFORMAT_RGBA,!1)):(t.updateSize(c*c,c),r.updateRawTexture(t,s,e.Engine.TEXTUREFORMAT_RGBA,!1))}},o=this.getScene();return o?o._loadFile(this.url,n):this._engine._loadFile(this.url,n),this._texture},i.prototype.loadTexture=function(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this.load3dlTexture()},i.prototype.clone=function(){var e=new i(this.url,this.getScene());return e.level=this.level,e},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,!0),this._texture||this.loadTexture())},i.Parse=function(e,t,r){var n=null;return e.name&&!e.isRenderTarget&&(n=new i(e.name,t),n.name=e.name,n.level=e.level),n},i.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e},i._noneEmptyLineRegex=/\S+/,i})(e.BaseTexture);e.ColorGradingTexture=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._dirty=!0,this._tempColor=new e.Color4(0,0,0,0),this._globalCurve=new e.Color4(0,0,0,0),this._highlightsCurve=new e.Color4(0,0,0,0),this._midtonesCurve=new e.Color4(0,0,0,0),this._shadowsCurve=new e.Color4(0,0,0,0),this._positiveCurve=new e.Color4(0,0,0,0),this._negativeCurve=new e.Color4(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}return Object.defineProperty(t.prototype,"globalHue",{get:function(){return this._globalHue},set:function(e){this._globalHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalDensity",{get:function(){return this._globalDensity},set:function(e){this._globalDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalSaturation",{get:function(){return this._globalSaturation},set:function(e){this._globalSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalExposure",{get:function(){return this._globalExposure},set:function(e){this._globalExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsHue",{get:function(){return this._highlightsHue},set:function(e){this._highlightsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsDensity",{get:function(){return this._highlightsDensity},set:function(e){this._highlightsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsSaturation",{get:function(){return this._highlightsSaturation},set:function(e){this._highlightsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsExposure",{get:function(){return this._highlightsExposure},set:function(e){this._highlightsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesHue",{get:function(){return this._midtonesHue},set:function(e){this._midtonesHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesDensity",{get:function(){return this._midtonesDensity},set:function(e){this._midtonesDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesSaturation",{get:function(){return this._midtonesSaturation},set:function(e){this._midtonesSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesExposure",{get:function(){return this._midtonesExposure},set:function(e){this._midtonesExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsHue",{get:function(){return this._shadowsHue},set:function(e){this._shadowsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsDensity",{get:function(){return this._shadowsDensity},set:function(e){this._shadowsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsSaturation",{get:function(){return this._shadowsSaturation},set:function(e){this._shadowsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsExposure",{get:function(){return this._shadowsExposure},set:function(e){this._shadowsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"ColorCurves"},t.Bind=function(e,t,i,r,n){void 0===i&&(i="vCameraColorCurvePositive"),void 0===r&&(r="vCameraColorCurveNeutral"),void 0===n&&(n="vCameraColorCurveNegative"),e._dirty&&(e._dirty=!1,e.getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e.getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e.getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e.getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(n,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))},t.PrepareUniforms=function(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")},t.prototype.getColorGradingDataToRef=function(e,i,r,n,o){null!=e&&(e=t.clamp(e,0,360),i=t.clamp(i,-100,100),r=t.clamp(r,-100,100),n=t.clamp(n,-100,100),i=t.applyColorGradingSliderNonlinear(i),i*=.5,n=t.applyColorGradingSliderNonlinear(n),i<0&&(i*=-1,e=(e+180)%360),t.fromHSBToRef(e,i,50+.25*n,o),o.scaleToRef(2,o),o.a=1+.01*r)},t.applyColorGradingSliderNonlinear=function(e){e/=100;var t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100},t.fromHSBToRef=function(e,i,r,n){var o=t.clamp(e,0,360),s=t.clamp(i/100,0,1),a=t.clamp(r/100,0,1);if(0===s)n.r=a,n.g=a,n.b=a;else{o/=60;var l=Math.floor(o),c=o-l,h=a*(1-s),u=a*(1-s*c),d=a*(1-s*(1-c));switch(l){case 0:n.r=a,n.g=d,n.b=h;break;case 1:n.r=u,n.g=a,n.b=h;break;case 2:n.r=h,n.g=a,n.b=d;break;case 3:n.r=h,n.g=u,n.b=a;break;case 4:n.r=d,n.g=h,n.b=a;break;default:n.r=a,n.g=h,n.b=u}}n.a=1},t.clamp=function(e,t,i){return Math.min(Math.max(e,t),i)},t.prototype.clone=function(){return e.SerializationHelper.Clone((function(){return new t}),this)},t.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},t.Parse=function(i){return e.SerializationHelper.Parse((function(){return new t}),i,null,null)},n([e.serialize()],t.prototype,"_globalHue",void 0),n([e.serialize()],t.prototype,"_globalDensity",void 0),n([e.serialize()],t.prototype,"_globalSaturation",void 0),n([e.serialize()],t.prototype,"_globalExposure",void 0),n([e.serialize()],t.prototype,"_highlightsHue",void 0),n([e.serialize()],t.prototype,"_highlightsDensity",void 0),n([e.serialize()],t.prototype,"_highlightsSaturation",void 0),n([e.serialize()],t.prototype,"_highlightsExposure",void 0),n([e.serialize()],t.prototype,"_midtonesHue",void 0),n([e.serialize()],t.prototype,"_midtonesDensity",void 0),n([e.serialize()],t.prototype,"_midtonesSaturation",void 0),n([e.serialize()],t.prototype,"_midtonesExposure",void 0),t})();e.ColorCurves=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c,h,u){var d=t.call(this,i,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],a,l,c,h,u)||this;return d.color=n,d.depth=o,d.colorLevel=s,d._ownRefractionTexture=!0,d.onActivateObservable.add((function(t){d._refTexture=d._refTexture||new e.Texture(r,t.getScene())})),d.onApplyObservable.add((function(e){e.setColor3("baseColor",d.color),e.setFloat("depth",d.depth),e.setFloat("colorLevel",d.colorLevel),e.setTexture("refractionSampler",d._refTexture)})),d}return o(i,t),Object.defineProperty(i.prototype,"refractionTexture",{get:function(){return this._refTexture},set:function(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1},enumerable:!0,configurable:!0}),i.prototype.dispose=function(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),t.prototype.dispose.call(this,e)},i})(e.PostProcess);e.RefractionPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){var a=e.call(this,t,"blackAndWhite",["degree"],null,i,r,n,o,s)||this;return a.degree=1,a.onApplyObservable.add((function(e){e.setFloat("degree",a.degree)})),a}return o(t,e),t})(e.PostProcess);e.BlackAndWhitePostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,c){void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT);var h=t.call(this,i,"convolution",["kernel","screenSize"],null,n,o,s,a,l,null,c)||this;return h.kernel=r,h.onApply=function(e){e.setFloat2("screenSize",h.width,h.height),e.setArray("kernel",h.kernel)},h}return o(i,t),i.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],i.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],i.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],i.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],i.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],i.GaussianKernel=[0,1,0,1,1,1,0,1,0],i})(e.PostProcess);e.ConvolutionPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i,r,n,o,s,a){var l=e.call(this,t,"filter",["kernelMatrix"],null,r,n,o,s,a)||this;return l.kernelMatrix=i,l.onApply=function(e){e.setMatrix("kernelMatrix",l.kernelMatrix)},l}return o(t,e),t})(e.PostProcess);e.FilterPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(r,n,o,s,a,l,c,h,u){void 0===a&&(a=100),void 0===l&&(l=e.Texture.BILINEAR_SAMPLINGMODE);var d=t.call(this,r,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],n.postProcessRatio||n,o,l,c,h,"#define NUM_SAMPLES "+a)||this;return d._screenCoordinates=e.Vector2.Zero(),d.customMeshPosition=e.Vector3.Zero(),d.useCustomMeshPosition=!1,d.invert=!0,d.excludedMeshes=new Array,d.exposure=.3,d.decay=.96815,d.weight=.58767,d.density=.926,u=null===o?u:o.getScene(),c=u.getEngine(),d._viewPort=new e.Viewport(0,0,1,1).toGlobal(c.getRenderWidth(),c.getRenderHeight()),d.mesh=null!==s?s:i.CreateDefaultMesh("VolumetricLightScatteringMesh",u),d._createPass(u,n.passRatio||n),d.onActivate=function(e){d.isSupported||d.dispose(e),d.onActivate=null},d.onApplyObservable.add((function(e){d._updateMeshScreenCoordinates(u),e.setTexture("lightScatteringSampler",d._volumetricLightScatteringRTT),e.setFloat("exposure",d.exposure),e.setFloat("decay",d.decay),e.setFloat("weight",d.weight),e.setFloat("density",d.density),e.setVector2("meshPositionOnScreen",d._screenCoordinates)})),d}return o(i,t),Object.defineProperty(i.prototype,"useDiffuseColor",{get:function(){return e.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1},set:function(t){e.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"VolumetricLightScatteringPostProcess"},i.prototype._isReady=function(t,i){var r=t.getMesh();if(r===this.mesh&&r.material)return r.material.isReady(r);var n=[],o=[e.VertexBuffer.PositionKind],s=t.getMaterial();s&&(s.needAlphaTesting()&&n.push("#define ALPHATEST"),r.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(o.push(e.VertexBuffer.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(o.push(e.VertexBuffer.UV2Kind),n.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(o.push(e.VertexBuffer.MatricesIndicesKind),o.push(e.VertexBuffer.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._volumetricLightScatteringPass=r.getScene().getEngine().createEffect({vertexElement:"depth",fragmentElement:"volumetricLightScatteringPass"},o,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],a)),this._volumetricLightScatteringPass.isReady()},i.prototype.setCustomMeshPosition=function(e){this.customMeshPosition=e},i.prototype.getCustomMeshPosition=function(){return this.customMeshPosition},i.prototype.dispose=function(e){var i=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==i&&e.getScene().customRenderTargets.splice(i,1),this._volumetricLightScatteringRTT.dispose(),t.prototype.dispose.call(this,e)},i.prototype.getPass=function(){return this._volumetricLightScatteringRTT},i.prototype._meshExcluded=function(e){return this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)},i.prototype._createPass=function(t,i){var r=this,n=t.getEngine();this._volumetricLightScatteringRTT=new e.RenderTargetTexture("volumetricLightScatteringMap",{width:n.getRenderWidth()*i,height:n.getRenderHeight()*i},t,!1,!0,e.Engine.TEXTURETYPE_UNSIGNED_INT),this._volumetricLightScatteringRTT.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;var o=this.getCamera();o?o.customRenderTargets.push(this._volumetricLightScatteringRTT):t.customRenderTargets.push(this._volumetricLightScatteringRTT);var s,a=function(t){var i=t.getRenderingMesh();if(!r._meshExcluded(i)){var n=t.getMaterial();if(n){var o=i.getScene(),s=o.getEngine();s.setState(n.backFaceCulling);var a=i._getInstancesRenderList(t._id);if(!a.mustReturn){var l=s.getCaps().instancedArrays&&null!==a.visibleInstances[t._id];if(r._isReady(t,l)){var c=r._volumetricLightScatteringPass;if(i===r.mesh&&(c=t.effect?t.effect:n.getEffect()),s.enableEffect(c),i._bind(t,c,e.Material.TriangleFillMode),i===r.mesh)n.bind(i.getWorldMatrix(),i);else{if(r._volumetricLightScatteringPass.setMatrix("viewProjection",o.getTransformMatrix()),n&&n.needAlphaTesting()){var h=n.getAlphaTestTexture();r._volumetricLightScatteringPass.setTexture("diffuseSampler",h),h&&r._volumetricLightScatteringPass.setMatrix("diffuseMatrix",h.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&r._volumetricLightScatteringPass.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}i._processRendering(t,r._volumetricLightScatteringPass,e.Material.TriangleFillMode,a,l,(function(e,t){return c.setMatrix("world",t)}))}}}}},l=new e.Color4(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((function(){s=t.clearColor,t.clearColor=l})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((function(){t.clearColor=s})),this._volumetricLightScatteringRTT.customRenderFunction=function(i,r,n,o){var s,l=t.getEngine();if(o.length){for(l.setColorWrite(!1),s=0;st._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0})),l.setAlphaMode(e.Engine.ALPHA_COMBINE),s=0;s=h&&a.frame<=u&&(n?(c=a.value.clone(),m?(l=c.getTranslation(),c.setTranslation(l.scaleInPlace(g))):v&&o?(l=c.getTranslation(),c.setTranslation(l.multiplyInPlace(o))):c=a.value):c=a.value,y.push({frame:a.frame+r,value:c}));return this.animations[0].createRange(i,h+r,u+r),!0},i.prototype.translate=function(t,r,n){void 0===r&&(r=e.Space.LOCAL);var o=this.getLocalMatrix();if(r==e.Space.LOCAL)o.m[12]+=t.x,o.m[13]+=t.y,o.m[14]+=t.z;else{var s=null;n&&(s=n.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var a=i._tmpMats[0],l=i._tmpVecs[0];this._parent&&(n&&s?(a.copyFrom(this._parent.getAbsoluteTransform()),a.multiplyToRef(s,a)):a.copyFrom(this._parent.getAbsoluteTransform())),a.m[12]=0,a.m[13]=0,a.m[14]=0,a.invert(),e.Vector3.TransformCoordinatesToRef(t,a,l),o.m[12]+=l.x,o.m[13]+=l.y,o.m[14]+=l.z}this._markAsDirtyAndDecompose()},i.prototype.setPosition=function(t,r,n){void 0===r&&(r=e.Space.LOCAL);var o=this.getLocalMatrix();if(r==e.Space.LOCAL)o.m[12]=t.x,o.m[13]=t.y,o.m[14]=t.z;else{var s=null;n&&(s=n.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var a=i._tmpMats[0],l=i._tmpVecs[0];this._parent&&(n&&s?(a.copyFrom(this._parent.getAbsoluteTransform()),a.multiplyToRef(s,a)):a.copyFrom(this._parent.getAbsoluteTransform())),a.invert(),e.Vector3.TransformCoordinatesToRef(t,a,l),o.m[12]=l.x,o.m[13]=l.y,o.m[14]=l.z}this._markAsDirtyAndDecompose()},i.prototype.setAbsolutePosition=function(t,i){this.setPosition(t,e.Space.WORLD,i)},i.prototype.scale=function(t,r,n,o){void 0===o&&(o=!1);var s=this.getLocalMatrix(),a=i._tmpMats[0];e.Matrix.ScalingToRef(t,r,n,a),a.multiplyToRef(s,s),a.invert();for(var l=0,c=this.children;l0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,n.x>n.y&&n.x>n.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length){var o=this._bone1.getScale(),s=this._bone2.getScale();this._bone1Length=this._bone1.length*o.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*s.y*this.mesh.scaling.y}else if(this._bone1.children[0]){t.computeWorldMatrix(!0);var a=this._bone2.children[0].getAbsolutePosition(t),l=this._bone2.getAbsolutePosition(t),c=this._bone1.getAbsolutePosition(t);this._bone1Length=e.Vector3.Distance(a,l),this._bone2Length=e.Vector3.Distance(l,c)}this._bone1.getRotationMatrixToRef(e.Space.WORLD,t,this._bone1Mat),this.maxAngle=Math.PI,r&&(r.targetMesh&&(this.targetMesh=r.targetMesh,this.targetMesh.computeWorldMatrix(!0)),r.poleTargetMesh?(this.poleTargetMesh=r.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):r.poleTargetBone?this.poleTargetBone=r.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),r.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(r.poleTargetLocalOffset),r.poleAngle&&(this.poleAngle=r.poleAngle),r.bendAxis&&this._bendAxis.copyFrom(r.bendAxis),r.maxAngle&&(this.maxAngle=r.maxAngle),r.slerpAmount&&(this.slerpAmount=r.slerpAmount))}}return Object.defineProperty(t.prototype,"maxAngle",{get:function(){return this._maxAngle},set:function(e){this._setMaxAngle(e)},enumerable:!0,configurable:!0}),t.prototype._setMaxAngle=function(e){e<0&&(e=0),(e>Math.PI||void 0==e)&&(e=Math.PI),this._maxAngle=e;var t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))},t.prototype.update=function(){var i=this._bone1;if(i){var r=this.targetPosition,n=this.poleTargetPosition,o=t._tmpMats[0],s=t._tmpMats[1];this.targetMesh&&r.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,n):this.poleTargetMesh&&e.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),n);var a=t._tmpVecs[0],l=t._tmpVecs[1],c=t._tmpVecs[2],h=t._tmpVecs[3],u=t._tmpVecs[4],d=t._tmpQuat;i.getAbsolutePositionToRef(this.mesh,a),n.subtractToRef(a,u),0==u.x&&0==u.y&&0==u.z?u.y=1:u.normalize(),r.subtractToRef(a,h),h.normalize(),e.Vector3.CrossToRef(h,u,l),l.normalize(),e.Vector3.CrossToRef(h,l,c),c.normalize(),e.Matrix.FromXYZAxesToRef(c,h,l,o);var f=this._bone1Length,p=this._bone2Length,_=e.Vector3.Distance(a,r);this._maxReach>0&&(_=Math.min(this._maxReach,_));var m=(p*p+_*_-f*f)/(2*p*_),g=(_*_+f*f-p*p)/(2*_*f);m>1&&(m=1),g>1&&(g=1),m<-1&&(m=-1),g<-1&&(g=-1);var v=Math.acos(m),y=Math.acos(g),b=-v-y;if(this._rightHandedSystem)e.Matrix.RotationYawPitchRollToRef(0,0,this._adjustRoll,s),s.multiplyToRef(o,o),e.Matrix.RotationAxisToRef(this._bendAxis,y,s),s.multiplyToRef(o,o);else{var x=t._tmpVecs[5];x.copyFrom(this._bendAxis),x.x*=-1,e.Matrix.RotationAxisToRef(x,-y,s),s.multiplyToRef(o,o)}this.poleAngle&&(e.Matrix.RotationAxisToRef(h,this.poleAngle,s),o.multiplyToRef(s,o)),this._bone1&&(this.slerpAmount<1?(this._slerping||e.Quaternion.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),e.Quaternion.FromRotationMatrixToRef(o,d),e.Quaternion.SlerpToRef(this._bone1Quat,d,this.slerpAmount,this._bone1Quat),b=this._bone2Ang*(1-this.slerpAmount)+b*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,e.Space.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(o,e.Space.WORLD,this.mesh),this._bone1Mat.copyFrom(o),this._slerping=!1)),this._bone2.setAxisAngle(this._bendAxis,b,e.Space.LOCAL),this._bone2Ang=b}},t._tmpVecs=[e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero()],t._tmpQuat=e.Quaternion.Identity(),t._tmpMats=[e.Matrix.Identity(),e.Matrix.Identity()],t})();e.BoneIKController=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n){if(this.upAxis=e.Vector3.Up(),this.upAxisSpace=e.Space.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=e.Quaternion.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=e.Vector3.Forward(),this.mesh=t,this.bone=i,this.target=r,n&&(n.adjustYaw&&(this.adjustYaw=n.adjustYaw),n.adjustPitch&&(this.adjustPitch=n.adjustPitch),n.adjustRoll&&(this.adjustRoll=n.adjustRoll),null!=n.maxYaw?this.maxYaw=n.maxYaw:this.maxYaw=Math.PI,null!=n.minYaw?this.minYaw=n.minYaw:this.minYaw=-Math.PI,null!=n.maxPitch?this.maxPitch=n.maxPitch:this.maxPitch=Math.PI,null!=n.minPitch?this.minPitch=n.minPitch:this.minPitch=-Math.PI,null!=n.slerpAmount&&(this.slerpAmount=n.slerpAmount),null!=n.upAxis&&(this.upAxis=n.upAxis),null!=n.upAxisSpace&&(this.upAxisSpace=n.upAxisSpace),null!=n.yawAxis||null!=n.pitchAxis)){var o=e.Axis.Y,s=e.Axis.X;null!=n.yawAxis&&(o=n.yawAxis.clone(),o.normalize()),null!=n.pitchAxis&&(s=n.pitchAxis.clone(),s.normalize());var a=e.Vector3.Cross(s,o);this._transformYawPitch=e.Matrix.Identity(),e.Matrix.FromXYZAxesToRef(s,o,a,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}i.getParent()||this.upAxisSpace!=e.Space.BONE||(this.upAxisSpace=e.Space.LOCAL)}return Object.defineProperty(t.prototype,"minYaw",{get:function(){return this._minYaw},set:function(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxYaw",{get:function(){return this._maxYaw},set:function(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minPitch",{get:function(){return this._minPitch},set:function(e){this._minPitch=e,this._minPitchTan=Math.tan(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxPitch",{get:function(){return this._maxPitch},set:function(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)},enumerable:!0,configurable:!0}),t.prototype.update=function(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);var i=this.bone,r=t._tmpVecs[0];i.getAbsolutePositionToRef(this.mesh,r);var n=this.target,o=t._tmpMats[0],s=t._tmpMats[1],a=this.mesh,l=i.getParent(),c=t._tmpVecs[1];c.copyFrom(this.upAxis),this.upAxisSpace==e.Space.BONE&&l?(this._transformYawPitch&&e.Vector3.TransformCoordinatesToRef(c,this._transformYawPitchInv,c),l.getDirectionToRef(c,this.mesh,c)):this.upAxisSpace==e.Space.LOCAL&&(a.getDirectionToRef(c,c),1==a.scaling.x&&1==a.scaling.y&&1==a.scaling.z||c.normalize());var h=!1,u=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(h=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(u=!0),h||u){var d=t._tmpMats[2],f=t._tmpMats[3];if(this.upAxisSpace==e.Space.BONE&&1==c.y&&l)l.getRotationMatrixToRef(e.Space.WORLD,this.mesh,d);else if(this.upAxisSpace!=e.Space.LOCAL||1!=c.y||l){var p=t._tmpVecs[2];p.copyFrom(this._fowardAxis),this._transformYawPitch&&e.Vector3.TransformCoordinatesToRef(p,this._transformYawPitchInv,p),l?l.getDirectionToRef(p,this.mesh,p):a.getDirectionToRef(p,p);var _=e.Vector3.Cross(c,p);_.normalize();var p=e.Vector3.Cross(_,c);e.Matrix.FromXYZAxesToRef(_,c,p,d)}else d.copyFrom(a.getWorldMatrix());d.invertToRef(f);var m=null;if(u){var g=t._tmpVecs[3];n.subtractToRef(r,g),e.Vector3.TransformCoordinatesToRef(g,f,g),m=Math.sqrt(g.x*g.x+g.z*g.z);var v=Math.atan2(g.y,m),y=v;v>this._maxPitch?(g.y=this._maxPitchTan*m,y=this._maxPitch):vthis._maxYaw||bMath.PI?this._isAngleBetween(b,this._maxYaw,this._midYawConstraint)?(g.z=this._maxYawCos*m,g.x=this._maxYawSin*m,x=this._maxYaw):this._isAngleBetween(b,this._midYawConstraint,this._minYaw)&&(g.z=this._minYawCos*m,g.x=this._minYawSin*m,x=this._minYaw):b>this._maxYaw?(g.z=this._maxYawCos*m,g.x=this._maxYawSin*m,x=this._maxYaw):bMath.PI){var T=t._tmpVecs[8];T.copyFrom(e.Axis.Z),this._transformYawPitch&&e.Vector3.TransformCoordinatesToRef(T,this._transformYawPitchInv,T);var E=t._tmpMats[4];this._boneQuat.toRotationMatrix(E),this.mesh.getWorldMatrix().multiplyToRef(E,E),e.Vector3.TransformCoordinatesToRef(T,E,T),e.Vector3.TransformCoordinatesToRef(T,f,T);var P=Math.atan2(T.x,T.z);if(this._getAngleBetween(P,b)>this._getAngleBetween(P,this._midYawConstraint)){null==m&&(m=Math.sqrt(g.x*g.x+g.z*g.z));var A=this._getAngleBetween(P,this._maxYaw);this._getAngleBetween(P,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i},t.prototype._getAngleBetween=function(e,t){e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t;var i=0;return i=eMath.PI&&(i=2*Math.PI-i),i},t.prototype._isAngleBetween=function(e,t,i){if(e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t,i%=2*Math.PI,i=i<0?i+2*Math.PI:i,tt&&ei&&e-1&&this._meshesWithPoseMatrix.splice(t,1)},t.prototype._computeTransformMatrices=function(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(var i=0;i0&&(n.animation=i.animations[0].serialize()),e.ranges=[];for(var o in this._ranges){var s=this._ranges[o];if(s){var a={};a.name=o,a.from=s.from,a.to=s.to,e.ranges.push(a)}}}return e},t.Parse=function(i,r){var n=new t(i.name,i.id,r);i.dimensionsAtRest&&(n.dimensionsAtRest=e.Vector3.FromArray(i.dimensionsAtRest)),n.needInitialSkinMatrix=i.needInitialSkinMatrix;var o;for(o=0;o-1&&(a=n.bones[s.parentBoneIndex]);var l=s.rest?e.Matrix.FromArray(s.rest):null,c=new e.Bone(s.name,n,a,e.Matrix.FromArray(s.matrix),l);s.length&&(c.length=s.length),s.metadata&&(c.metadata=s.metadata),s.animation&&c.animations.push(e.Animation.Parse(s.animation))}if(i.ranges)for(o=0;o0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e},t.prototype.sortBones=function(){for(var e=new Array,t=new Array(this.bones.length),i=0;i1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)},t.Rgbe2float=function(e,t,i,r,n,o){n>0?(n=this.Ldexp(1,n-136),e[o+0]=t*n,e[o+1]=i*n,e[o+2]=r*n):(e[o+0]=0,e[o+1]=0,e[o+2]=0)},t.readStringLine=function(e,t){for(var i="",r="",n=t;n32767)throw"HDR Bad header format, unsupported size";return s+=r.length+1,{height:t,width:i,dataPosition:s}},t.GetCubeMapTextureData=function(t,i){var r=new Uint8Array(t),n=this.RGBE_ReadHeader(r),o=this.RGBE_ReadPixels_RLE(r,n);return e.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(o,n.width,n.height,i)},t.RGBE_ReadPixels=function(e,t){return this.RGBE_ReadPixels_RLE(e,t)},t.RGBE_ReadPixels_RLE=function(e,t){for(var i,r,n,o,s,a=t.height,l=t.width,c=t.dataPosition,h=0,u=0,d=0,f=new ArrayBuffer(4*l),p=new Uint8Array(f),_=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(_);a>0;){if(i=e[c++],r=e[c++],n=e[c++],o=e[c++],2!=i||2!=r||128&n)throw"HDR Bad header format, not RLE";if((n<<8|o)!=l)throw"HDR Bad header format, wrong scan line width";for(h=0,d=0;d<4;d++)for(u=(d+1)*l;h128){if(0==(s=i-128)||s>u-h)throw"HDR Bad Format, bad scanline data (run)";for(;s-- >0;)p[h++]=r}else{if(0==(s=i)||s>u-h)throw"HDR Bad Format, bad scanline data (non-run)";if(p[h++]=r,--s>0)for(var g=0;g255){var g=255/m;f*=g,p*=g,_*=g}l[3*d+0]=f,l[3*d+1]=p,l[3*d+2]=_}l?a.push(l):a.push(u)}return a},n=this.getScene();n&&(this._texture=n.getEngine().createRawCubeTextureFromUrl(this.url,n,this._size,e.Engine.TEXTUREFORMAT_RGB,n.getEngine().getCaps().textureFloat?e.Engine.TEXTURETYPE_FLOAT:e.Engine.TEXTURETYPE_UNSIGNED_INT,this._noMipmap,r,null,this._onLoad,this._onError))},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=new i(this.url,e,this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t.coordinatesIndex=this.coordinatesIndex,t.coordinatesMode=this.coordinatesMode,t},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this.loadTexture())},i.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},i.prototype.setReflectionTextureMatrix=function(e){this._textureMatrix=e},i.Parse=function(t,r,n){var o=null;return t.name&&!t.isRenderTarget&&(o=new i(n+t.name,r,t.size,t.noMipmap,t.generateHarmonics,t.useInGammaSpace),o.name=t.name,o.hasAlpha=t.hasAlpha,o.level=t.level,o.coordinatesMode=t.coordinatesMode,o.isBlocking=t.isBlocking),o&&(t.boundingBoxPosition&&(o.boundingBoxPosition=e.Vector3.FromArray(t.boundingBoxPosition)),t.boundingBoxSize&&(o.boundingBoxSize=e.Vector3.FromArray(t.boundingBoxSize)),t.rotationY&&(o.rotationY=t.rotationY)),o},i.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e},i._facesMapping=["right","left","up","down","front","back"],i})(e.BaseTexture);e.HDRCubeTexture=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.ConvertPanoramaToCubemap=function(t,i,r,n){if(!t)throw"ConvertPanoramaToCubemap: input cannot be null";if(t.length!=i*r*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(n,this.FACE_FRONT,t,i,r),back:this.CreateCubemapTexture(n,this.FACE_BACK,t,i,r),left:this.CreateCubemapTexture(n,this.FACE_LEFT,t,i,r),right:this.CreateCubemapTexture(n,this.FACE_RIGHT,t,i,r),up:this.CreateCubemapTexture(n,this.FACE_UP,t,i,r),down:this.CreateCubemapTexture(n,this.FACE_DOWN,t,i,r),size:n,type:e.Engine.TEXTURETYPE_FLOAT,format:e.Engine.TEXTUREFORMAT_RGB,gammaSpace:!1}},t.CreateCubemapTexture=function(e,t,i,r,n){for(var o=new ArrayBuffer(e*e*4*3),s=new Float32Array(o),a=t[1].subtract(t[0]).scale(1/e),l=t[3].subtract(t[2]).scale(1/e),c=1/e,h=0,u=0;uMath.PI;)n-=2*Math.PI;var s=n/Math.PI,a=o/Math.PI;s=.5*s+.5;var l=Math.round(s*i);l<0?l=0:l>=i&&(l=i-1);var c=Math.round(a*r);c<0?c=0:c>=r&&(c=r-1);var h=r-c-1;return{r:t[h*i*3+3*l+0],g:t[h*i*3+3*l+1],b:t[h*i*3+3*l+2]}},t.FACE_FRONT=[new e.Vector3(-1,-1,-1),new e.Vector3(1,-1,-1),new e.Vector3(-1,1,-1),new e.Vector3(1,1,-1)],t.FACE_BACK=[new e.Vector3(1,-1,1),new e.Vector3(-1,-1,1),new e.Vector3(1,1,1),new e.Vector3(-1,1,1)],t.FACE_RIGHT=[new e.Vector3(1,-1,-1),new e.Vector3(1,-1,1),new e.Vector3(1,1,-1),new e.Vector3(1,1,1)],t.FACE_LEFT=[new e.Vector3(-1,-1,1),new e.Vector3(-1,-1,-1),new e.Vector3(-1,1,1),new e.Vector3(-1,1,-1)],t.FACE_DOWN=[new e.Vector3(-1,1,-1),new e.Vector3(1,1,-1),new e.Vector3(-1,1,1),new e.Vector3(1,1,1)],t.FACE_UP=[new e.Vector3(-1,-1,1),new e.Vector3(1,-1,1),new e.Vector3(-1,-1,-1),new e.Vector3(1,-1,-1)],t})();e.PanoramaToCubeMapTools=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i){var r=e.call(this,t.x,t.y)||this;return r.index=i,r}return o(t,e),t})(e.Vector2),r=(function(){function i(){this.elements=new Array}return i.prototype.add=function(e){var i=this,r=new Array;return e.forEach((function(e){if(0===r.length||!e.equalsWithEpsilon(r[0])){var n=new t(e,i.elements.length);r.push(n),i.elements.push(n)}})),r},i.prototype.computeBounds=function(){var t=new e.Vector2(this.elements[0].x,this.elements[0].y),i=new e.Vector2(this.elements[0].x,this.elements[0].y);return this.elements.forEach((function(e){e.xi.x&&(i.x=e.x),e.yi.y&&(i.y=e.y)})),{min:t,max:i,width:i.x-t.x,height:i.y-t.y}},i})(),n=(function(){function t(){}return t.Rectangle=function(t,i,r,n){return[new e.Vector2(t,i),new e.Vector2(r,i),new e.Vector2(r,n),new e.Vector2(t,n)]},t.Circle=function(t,i,r,n){void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=32);for(var o=new Array,s=0,a=2*Math.PI/n,l=0;l0){var f=a.length/3;this._points.elements.forEach((function(e){s.push(0,-1,0),a.push(e.x,-r,e.y),l.push(1-(e.x-c.min.x)/c.width,1-(e.y-c.min.y)/c.height)}));for(var p=h.length,d=0;ds.elements.length-1?s.elements[0]:s.elements[u+1],t.push(f.x,0,f.y),t.push(f.x,-a,f.y),t.push(d.x,0,d.y),t.push(d.x,-a,d.y);var p=new e.Vector3(f.x,0,f.y),_=new e.Vector3(d.x,0,d.y),m=_.subtract(p),g=new e.Vector3(0,1,0),v=e.Vector3.Cross(m,g);v=v.normalize(),r.push(h/o.width,0),r.push(h/o.width,1),h+=m.length(),r.push(h/o.width,0),r.push(h/o.width,1),l?(i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),n.push(c),n.push(c+2),n.push(c+1),n.push(c+1),n.push(c+2),n.push(c+3)):(i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),n.push(c),n.push(c+1),n.push(c+2),n.push(c+1),n.push(c+3),n.push(c+2)),c+=4}},t})();e.PolygonMeshBuilder=s})(r||(r={}));var r;!(function(e){var t=0,i=(function(){function t(e,t,i){this.pos=e,this.normal=t,this.uv=i}return t.prototype.clone=function(){return new t(this.pos.clone(),this.normal.clone(),this.uv.clone())},t.prototype.flip=function(){this.normal=this.normal.scale(-1)},t.prototype.interpolate=function(i,r){return new t(e.Vector3.Lerp(this.pos,i.pos,r),e.Vector3.Lerp(this.normal,i.normal,r),e.Vector2.Lerp(this.uv,i.uv,r))},t})(),r=(function(){function t(e,t){this.normal=e,this.w=t}return t.FromPoints=function(i,r,n){var o=n.subtract(i),s=r.subtract(i);if(0===o.lengthSquared()||0===s.lengthSquared())return null;var a=e.Vector3.Normalize(e.Vector3.Cross(o,s));return new t(a,e.Vector3.Dot(a,i))},t.prototype.clone=function(){return new t(this.normal.clone(),this.w)},t.prototype.flip=function(){this.normal.scaleInPlace(-1),this.w=-this.w},t.prototype.splitPolygon=function(i,r,o,s,a){var l,c,h=0,u=[];for(l=0;lt.EPSILON?1:0;h|=d,u.push(d)}switch(h){case 0:(e.Vector3.Dot(this.normal,i.plane.normal)>0?r:o).push(i);break;case 1:s.push(i);break;case 2:a.push(i);break;case 3:var f=[],p=[];for(l=0;l=3&&(x=new n(f,i.shared),x.plane&&s.push(x)),p.length>=3&&(x=new n(p,i.shared),x.plane&&a.push(x))}},t.EPSILON=1e-5,t})(),n=(function(){function e(e,t){this.vertices=e,this.shared=t,this.plane=r.FromPoints(e[0].pos,e[1].pos,e[2].pos)}return e.prototype.clone=function(){return new e(this.vertices.map((function(e){return e.clone()})),this.shared)},e.prototype.flip=function(){this.vertices.reverse().map((function(e){e.flip()})),this.plane.flip()},e})(),o=(function(){function e(e){this.plane=null,this.front=null,this.back=null,this.polygons=new Array,e&&this.build(e)}return e.prototype.clone=function(){var t=new e;return t.plane=this.plane&&this.plane.clone(),t.front=this.front&&this.front.clone(),t.back=this.back&&this.back.clone(),t.polygons=this.polygons.map((function(e){return e.clone()})),t},e.prototype.invert=function(){for(var e=0;e0);for(var r=0,n=i;r0)}},t})();e.LensFlareSystemSceneComponent=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){this.name=t,this.lensFlares=new Array,this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455, +this._vertexBuffers={},this._isEnabled=!0,this._scene=r||e.Engine.LastCreatedScene;var n=this._scene._getComponent(e.SceneComponentConstants.NAME_LENSFLARESYSTEM);n||(n=new e.LensFlareSystemSceneComponent(this._scene),r._addComponent(n)),this._emitter=i,this.id=t,r.lensFlareSystems.push(this),this.meshesSelectionPredicate=function(e){return r.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&0!=(e.layerMask&r.activeCamera.layerMask)};var o=r.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(o,s,e.VertexBuffer.PositionKind,!1,!1,2);var a=[];a.push(0),a.push(1),a.push(2),a.push(0),a.push(2),a.push(3),this._indexBuffer=o.createIndexBuffer(a),this._effect=o.createEffect("lensFlare",[e.VertexBuffer.PositionKind],["color","viewportMatrix"],["textureSampler"],"")}return Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEmitter=function(){return this._emitter},t.prototype.setEmitter=function(e){this._emitter=e},t.prototype.getEmitterPosition=function(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position},t.prototype.computeEffectivePosition=function(t){var i=this.getEmitterPosition();return i=e.Vector3.Project(i,e.Matrix.Identity(),this._scene.getTransformMatrix(),t),this._positionX=i.x,this._positionY=i.y,i=e.Vector3.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(t.x-=this.viewportBorder,t.y-=this.viewportBorder,t.width+=2*this.viewportBorder,t.height+=2*this.viewportBorder,i.x+=this.viewportBorder,i.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder),i.z>0&&(this._positionX>t.x&&this._positionXt.y&&(this._positionY,t.y,t.height),!0)},t.prototype._isVisible=function(){if(!this._isEnabled||!this._scene.activeCamera)return!1;var t=this.getEmitterPosition(),i=t.subtract(this._scene.activeCamera.globalPosition),r=i.length();i.normalize();var n=new e.Ray(this._scene.activeCamera.globalPosition,i),o=this._scene.pickWithRay(n,this.meshesSelectionPredicate,!0);return!o||!o.hit||o.distance>r},t.prototype.render=function(){if(!this._effect.isReady()||!this._scene.activeCamera)return!1;var t=this._scene.getEngine(),i=this._scene.activeCamera.viewport,r=i.toGlobal(t.getRenderWidth(!0),t.getRenderHeight(!0));if(!this.computeEffectivePosition(r))return!1;if(!this._isVisible())return!1;var n,o;n=this._positionXr.x+r.width-this.borderLimit?this._positionX-r.x-r.width+this.borderLimit:0,o=this._positionYr.y+r.height-this.borderLimit?this._positionY-r.y-r.height+this.borderLimit:0;var s=n>o?n:o;(s-=this.viewportBorder)>this.borderLimit&&(s=this.borderLimit);var a=1-s/this.borderLimit;if(a<0)return!1;a>1&&(a=1),this.viewportBorder>0&&(r.x+=this.viewportBorder,r.y+=this.viewportBorder,r.width-=2*this.viewportBorder,r.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);var l=r.x+r.width/2,c=r.y+r.height/2,h=l-this._positionX,u=c-this._positionY;t.enableEffect(this._effect),t.setState(!1),t.setDepthBuffer(!1),t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect);for(var d=0;d-1?this._onBeforePhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerAfterPhysicsStep=function(e){this._onAfterPhysicsStepCallbacks.push(e)},t.prototype.unregisterAfterPhysicsStep=function(t){var i=this._onAfterPhysicsStepCallbacks.indexOf(t);i>-1?this._onAfterPhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerOnPhysicsCollide=function(e,t){var i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})},t.prototype.unregisterOnPhysicsCollide=function(t,i){var r=t instanceof Array?t:[t],n=-1;this._onPhysicsCollideCallbacks.some((function(e,t){if(e.callback===i&&e.otherImpostors.length===r.length){var o=e.otherImpostors.every((function(e){return r.indexOf(e)>-1}));return o&&(n=t),o}return!1}))?this._onPhysicsCollideCallbacks.splice(n,1):e.Tools.Warn("Function to remove was not found")},t.prototype.getParentsRotation=function(){var t=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);t;)t.rotationQuaternion?this._tmpQuat2.copyFrom(t.rotationQuaternion):e.Quaternion.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,t.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),t=t.parent;return this._tmpQuat},t.prototype.applyForce=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this},t.prototype.applyImpulse=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this},t.prototype.createJoint=function(t,i,r){var n=new e.PhysicsJoint(i,r);return this.addJoint(t,n),this},t.prototype.addJoint=function(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this},t.prototype.sleep=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this},t.prototype.wakeUp=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this},t.prototype.clone=function(e){return e?new t(e,this.type,this._options,this._scene):null},t.prototype.dispose=function(){var e=this;this._physicsEngine&&(this._joints.forEach((function(t){e._physicsEngine&&e._physicsEngine.removeJoint(e,t.otherImpostor,t.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)},t.prototype.setDeltaPosition=function(e){this._deltaPosition.copyFrom(e)},t.prototype.setDeltaRotation=function(t){this._deltaRotation||(this._deltaRotation=new e.Quaternion),this._deltaRotation.copyFrom(t),this._deltaRotationConjugated=this._deltaRotation.conjugate()},t.prototype.getBoxSizeToRef=function(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this},t.prototype.getRadius=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0},t.prototype.syncBoneWithImpostor=function(i,r,n,o,s){var a=t._tmpVecs[0],l=this.object;if(l.rotationQuaternion)if(s){var c=t._tmpQuat;l.rotationQuaternion.multiplyToRef(s,c),i.setRotationQuaternion(c,e.Space.WORLD,r)}else i.setRotationQuaternion(l.rotationQuaternion,e.Space.WORLD,r);a.x=0,a.y=0,a.z=0,n&&(a.x=n.x,a.y=n.y,a.z=n.z,i.getDirectionToRef(a,r,a),void 0!==o&&null!==o||(o=n.length()),a.x*=o,a.y*=o,a.z*=o),i.getParent()?(a.addInPlace(l.getAbsolutePosition()),i.setAbsolutePosition(a,r)):(r.setAbsolutePosition(l.getAbsolutePosition()),r.position.x-=a.x,r.position.y-=a.y,r.position.z-=a.z)},t.prototype.syncImpostorWithBone=function(i,r,n,o,s,a){var l=this.object;if(l.rotationQuaternion)if(s){var c=t._tmpQuat;i.getRotationQuaternionToRef(e.Space.WORLD,r,c),c.multiplyToRef(s,l.rotationQuaternion)}else i.getRotationQuaternionToRef(e.Space.WORLD,r,l.rotationQuaternion);var h=t._tmpVecs[0],u=t._tmpVecs[1];a||(a=t._tmpVecs[2],a.x=0,a.y=1,a.z=0),i.getDirectionToRef(a,r,u),i.getAbsolutePositionToRef(r,h),void 0!==o&&null!==o||!n||(o=n.length()),void 0!==o&&null!==o&&(h.x+=u.x*o,h.y+=u.y*o,h.z+=u.z*o),l.setAbsolutePosition(h)},t.DEFAULT_OBJECT_SIZE=new e.Vector3(1,1,1),t.IDENTITY_QUATERNION=e.Quaternion.Identity(),t._tmpVecs=[e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero()],t._tmpQuat=e.Quaternion.Identity(),t.NoImpostor=0,t.SphereImpostor=1,t.BoxImpostor=2,t.PlaneImpostor=3,t.MeshImpostor=4,t.CylinderImpostor=7,t.ParticleImpostor=8,t.HeightmapImpostor=9,t})();e.PhysicsImpostor=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i){if(void 0===i&&(i=new e.CannonJSPlugin),this._physicsPlugin=i,this._impostors=[],this._joints=[],!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");t=t||new e.Vector3(0,-9.807,0),this.setGravity(t),this.setTimeStep()}return t.prototype.setGravity=function(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)},t.prototype.setTimeStep=function(e){void 0===e&&(e=1/60),this._physicsPlugin.setTimeStep(e)},t.prototype.getTimeStep=function(){return this._physicsPlugin.getTimeStep()},t.prototype.dispose=function(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()},t.prototype.getPhysicsPluginName=function(){return this._physicsPlugin.name},t.prototype.addImpostor=function(e){e.uniqueId=this._impostors.push(e),e.parent||this._physicsPlugin.generatePhysicsBody(e)},t.prototype.removeImpostor=function(e){var t=this._impostors.indexOf(e);if(t>-1){var i=this._impostors.splice(t,1);i.length&&(i[0].physicsBody=null)}},t.prototype.addJoint=function(e,t,i){var r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)},t.prototype.removeJoint=function(e,t,i){var r=this._joints.filter((function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e}));r.length&&this._physicsPlugin.removeJoint(r[0])},t.prototype._step=function(e){var t=this;this._impostors.forEach((function(e){e.isBodyInitRequired()&&t._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)},t.prototype.getPhysicsPlugin=function(){return this._physicsPlugin},t.prototype.getImpostors=function(){return this._impostors},t.prototype.getImpostorForPhysicsObject=function(e){for(var t=0;tr)return null;var f=o===s.Constant?n:n*(1-d/r);return{force:l.multiplyByFloats(f,f,f),contactPoint:u}},t.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._sphere.dispose():setTimeout((function(){t._dataFetched||t._sphere.dispose()}),0)},t.prototype._prepareSphere=function(){this._sphere||(this._sphere=e.MeshBuilder.CreateSphere("radialExplosionEventSphere",this._sphereOptions,this._scene),this._sphere.isVisible=!1)},t.prototype._intersectsWithSphere=function(t,i,r){var n=t.object;return this._prepareSphere(),this._sphere.position=i,this._sphere.scaling=new e.Vector3(2*r,2*r,2*r),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(n,!0)},t})();e.PhysicsRadialExplosionEvent=i;var r=(function(){function e(e,t,i,r,n,o){void 0===o&&(o=s.Constant),this._dataFetched=!1,this._physicsHelper=e,this._scene=t,this._origin=i,this._radius=r,this._strength=n,this._falloff=o,this._tickCallback=this._tick.bind(this)}return e.prototype.getData=function(){return this._dataFetched=!0,{sphere:this._sphere}},e.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},e.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._sphere.dispose():setTimeout((function(){t._dataFetched||t._sphere.dispose()}),0)},e.prototype._tick=function(){if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._radius,-1*this._strength,this._falloff);else{var e=this._physicsHelper.applyRadialExplosionForce(this._origin,this._radius,-1*this._strength,this._falloff);e&&(this._sphere=e.getData().sphere.clone("radialExplosionEventSphereClone"))}},e})();e.PhysicsGravitationalFieldEvent=r;var n=(function(){function t(t,i,r,n,o,s){this._scene=t,this._origin=i,this._radius=r,this._strength=n,this._height=o,this._updraftMode=s,this._originTop=e.Vector3.Zero(),this._originDirection=e.Vector3.Zero(),this._cylinderPosition=e.Vector3.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._origin.addToRef(new e.Vector3(0,this._height/2,0),this._cylinderPosition),this._origin.addToRef(new e.Vector3(0,this._height,0),this._originTop),this._updraftMode===a.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=this._tick.bind(this)}return t.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},t.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},t.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},t.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._cylinder.dispose():setTimeout((function(){t._dataFetched||t._cylinder.dispose()}),0)},t.prototype.getImpostorForceAndContactPoint=function(e){if(0===e.mass)return null;if(!this._intersectsWithCylinder(e))return null;var t=e.getObjectCenter();if(this._updraftMode===a.Perpendicular)var i=this._originDirection;else var i=t.subtract(this._originTop);var r=-1*this._strength;return{force:i.multiplyByFloats(r,r,r),contactPoint:t}},t.prototype._tick=function(){var e=this;this._physicsEngine.getImpostors().forEach((function(t){var i=e.getImpostorForceAndContactPoint(t);i&&t.applyForce(i.force,i.contactPoint)}))},t.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=e.MeshBuilder.CreateCylinder("updraftEventCylinder",{height:this._height,diameter:2*this._radius},this._scene),this._cylinder.isVisible=!1)},t.prototype._intersectsWithCylinder=function(e){var t=e.object;return this._prepareCylinder(),this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(t,!0)},t})();e.PhysicsUpdraftEvent=n;var o=(function(){function t(t,i,r,n,o){this._scene=t,this._origin=i,this._radius=r,this._strength=n,this._height=o,this._originTop=e.Vector3.Zero(),this._centripetalForceThreshold=.7,this._updraftMultiplier=.02,this._cylinderPosition=e.Vector3.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._origin.addToRef(new e.Vector3(0,this._height/2,0),this._cylinderPosition),this._origin.addToRef(new e.Vector3(0,this._height,0),this._originTop),this._tickCallback=this._tick.bind(this)}return t.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},t.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},t.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},t.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._cylinder.dispose():setTimeout((function(){t._dataFetched||t._cylinder.dispose()}),0)},t.prototype.getImpostorForceAndContactPoint=function(t){if(0===t.mass)return null;if(!this._intersectsWithCylinder(t))return null;if("Mesh"!==t.object.getClassName()&&"InstancedMesh"!==t.object.getClassName())return null;var i=t.getObjectCenter(),r=new e.Vector3(this._origin.x,i.y,this._origin.z),n=i.subtract(r),o=new e.Ray(r,n,this._radius),s=o.intersectsMesh(t.object),a=s.pickedPoint;if(!a)return null;var l=s.distance/this._radius,c=e.Vector3.Cross(r,i).normalize(),h=a.normalize();if(l>this._centripetalForceThreshold&&(h=h.negate()),l>this._centripetalForceThreshold)var u=h.x*this._strength/8,d=h.y*this._updraftMultiplier,f=h.z*this._strength/8;else var u=(c.x+h.x)/2,d=this._originTop.y*this._updraftMultiplier,f=(c.z+h.z)/2;var p=new e.Vector3(u,d,f);return p=p.multiplyByFloats(this._strength,this._strength,this._strength),{force:p,contactPoint:i}},t.prototype._tick=function(){var e=this;this._physicsEngine.getImpostors().forEach((function(t){var i=e.getImpostorForceAndContactPoint(t);i&&t.applyForce(i.force,i.contactPoint)}))},t.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=e.MeshBuilder.CreateCylinder("vortexEventCylinder",{height:this._height,diameter:2*this._radius},this._scene),this._cylinder.isVisible=!1)},t.prototype._intersectsWithCylinder=function(e){var t=e.object;return this._prepareCylinder(),this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(t,!0)},t})();e.PhysicsVortexEvent=o;var s;!(function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"})(s=e.PhysicsRadialImpulseFalloff||(e.PhysicsRadialImpulseFalloff={}));var a;!(function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"})(a=e.PhysicsUpdraftMode||(e.PhysicsUpdraftMode={}))})(r||(r={}));var r;!(function(t){var i=(function(){function i(i,r){if(void 0===i&&(i=!0),void 0===r&&(r=10),this._useDeltaForWorldStep=i,this.name="CannonJSPlugin",this._physicsMaterials=new Array,this._fixedTimeStep=1/60,this.BJSCANNON=e,this._minus90X=new t.Quaternion(-.7071067811865475,0,0,.7071067811865475),this._plus90X=new t.Quaternion(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=t.Vector3.Zero(),this._tmpDeltaPosition=t.Vector3.Zero(),this._tmpUnityRotation=new t.Quaternion,!this.isSupported())return void t.Tools.Error("CannonJS is not available. Please make sure you included the js file.");this._extendNamespace(),this.world=new this.BJSCANNON.World,this.world.broadphase=new this.BJSCANNON.NaiveBroadphase,this.world.solver.iterations=r}return i.prototype.setGravity=function(e){this.world.gravity.copy(e)},i.prototype.setTimeStep=function(e){this._fixedTimeStep=e},i.prototype.getTimeStep=function(){return this._fixedTimeStep},i.prototype.executeStep=function(e,t){this.world.step(this._fixedTimeStep,this._useDeltaForWorldStep?e:0,3)},i.prototype.applyImpulse=function(e,t,i){var r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),n=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(n,r)},i.prototype.applyForce=function(e,t,i){var r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),n=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(n,r)},i.prototype.generatePhysicsBody=function(e){if(e.parent)return void(e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate()));if(e.isBodyInitRequired()){var t=this._createShape(e),i=e.physicsBody;i&&this.removePhysicsBody(e);var r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),n={mass:e.getParam("mass"),material:r},o=e.getParam("nativeOptions");for(var s in o)o.hasOwnProperty(s)&&(n[s]=o[s]);e.physicsBody=new this.BJSCANNON.Body(n), +e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){e.physicsBody[t].copy(i[t])})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)},i.prototype._processChildMeshes=function(e){var i=this,r=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],n=e.object.rotationQuaternion;if(r.length){var o=function(r,s){if(n&&s.rotationQuaternion){var a=s.getPhysicsImpostor();if(a){if(a.parent!==e){var l=s.getAbsolutePosition().subtract(e.object.getAbsolutePosition()),c=s.rotationQuaternion.multiply(t.Quaternion.Inverse(n));a.physicsBody&&(i.removePhysicsBody(a),a.physicsBody=null),a.parent=e,a.resetUpdateFlags(),e.physicsBody.addShape(i._createShape(a),new i.BJSCANNON.Vec3(l.x,l.y,l.z),new i.BJSCANNON.Quaternion(c.x,c.y,c.z,c.w)),e.physicsBody.mass+=a.getParam("mass")}}n.multiplyInPlace(s.rotationQuaternion),s.getChildMeshes(!0).filter((function(e){return!!e.physicsImpostor})).forEach(o.bind(i,s.getAbsolutePosition()))}};r.filter((function(e){return!!e.physicsImpostor})).forEach(o.bind(this,e.object.getAbsolutePosition()))}},i.prototype.removePhysicsBody=function(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),this.world.remove(e.physicsBody)},i.prototype.generateJoint=function(e){var i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(i&&r){var n,o=e.joint.jointData,s={pivotA:o.mainPivot?(new this.BJSCANNON.Vec3).copy(o.mainPivot):null,pivotB:o.connectedPivot?(new this.BJSCANNON.Vec3).copy(o.connectedPivot):null,axisA:o.mainAxis?(new this.BJSCANNON.Vec3).copy(o.mainAxis):null,axisB:o.connectedAxis?(new this.BJSCANNON.Vec3).copy(o.connectedAxis):null,maxForce:o.nativeParams.maxForce,collideConnected:!!o.collision};switch(e.joint.type){case t.PhysicsJoint.HingeJoint:case t.PhysicsJoint.Hinge2Joint:n=new this.BJSCANNON.HingeConstraint(i,r,s);break;case t.PhysicsJoint.DistanceJoint:n=new this.BJSCANNON.DistanceConstraint(i,r,o.maxDistance||2);break;case t.PhysicsJoint.SpringJoint:var a=o;n=new this.BJSCANNON.Spring(i,r,{restLength:a.length,stiffness:a.stiffness,damping:a.damping,localAnchorA:s.pivotA,localAnchorB:s.pivotB});break;case t.PhysicsJoint.LockJoint:n=new this.BJSCANNON.LockConstraint(i,r,s);break;case t.PhysicsJoint.PointToPointJoint:case t.PhysicsJoint.BallAndSocketJoint:default:n=new this.BJSCANNON.PointToPointConstraint(i,s.pivotA,r,s.pivotA,s.maxForce)}n.collideConnected=!!o.collision,e.joint.physicsJoint=n,e.joint.type!==t.PhysicsJoint.SpringJoint?this.world.addConstraint(n):e.mainImpostor.registerAfterPhysicsStep((function(){n.applyForce()}))}},i.prototype.removeJoint=function(e){this.world.removeConstraint(e.joint.physicsJoint)},i.prototype._addMaterial=function(e,t,i){var r,n;for(r=0;r1e3*i));a++);this.time+=r;for(var l=this.time%i,c=l/i,h=e,u=this.bodies,d=0;d!==u.length;d++){var f=u[d];f.type!==t.Body.STATIC&&f.sleepState!==t.Body.SLEEPING?(f.position.vsub(f.previousPosition,h),h.scale(c,h),f.position.vadd(h,f.interpolatedPosition)):(f.interpolatedPosition.copy(f.position),f.interpolatedQuaternion.copy(f.quaternion))}}}},i})();t.CannonJSPlugin=i})(r||(r={}));var r;!(function(e){var i=(function(){function i(i){this.name="OimoJSPlugin",this._tmpImpostorsArray=[],this._tmpPositionVector=e.Vector3.Zero(),this.BJSOIMO=t,this.world=new this.BJSOIMO.World({iterations:i}),this.world.clear()}return i.prototype.setGravity=function(e){this.world.gravity.copy(e)},i.prototype.setTimeStep=function(e){this.world.timeStep=e},i.prototype.getTimeStep=function(){return this.world.timeStep},i.prototype.executeStep=function(e,t){var i=this;t.forEach((function(e){e.beforeStep()})),this.world.step(),t.forEach((function(e){e.afterStep(),i._tmpImpostorsArray[e.uniqueId]=e}));for(var r=this.world.contacts;null!==r;)if(!r.touching||r.body1.sleeping||r.body2.sleeping){var n=this._tmpImpostorsArray[+r.body1.name],o=this._tmpImpostorsArray[+r.body2.name];n&&o?(n.onCollide({body:o.physicsBody}),o.onCollide({body:n.physicsBody}),r=r.next):r=r.next}else r=r.next},i.prototype.applyImpulse=function(e,t,i){var r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))},i.prototype.applyForce=function(t,i,r){e.Tools.Warn("Oimo doesn't support applying force. Using impule instead."),this.applyImpulse(t,i,r)},i.prototype.generatePhysicsBody=function(t){var i=this;if(t.parent)return void(t.physicsBody&&(this.removePhysicsBody(t),t.forceUpdate()));if(t.isBodyInitRequired()){var r={name:t.uniqueId,config:[t.getParam("mass")||1,t.getParam("friction"),t.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==t.getParam("mass"),density:t.getParam("mass"),friction:t.getParam("friction"),restitution:t.getParam("restitution"),world:this.world},n=[t];!(function(e){e.getChildMeshes&&e.getChildMeshes().forEach((function(e){e.physicsImpostor&&n.push(e.physicsImpostor)}))})(t.object);var o=function(t){return Math.max(t,e.PhysicsEngine.Epsilon)},s=new e.Quaternion;n.forEach((function(n){if(n.object.rotationQuaternion){var a=n.object.rotationQuaternion;s=a.clone();var l=a.toEulerAngles(),c=n.getObjectExtendSize();if(n===t){var h=t.getObjectCenter();t.object.getAbsolutePivotPoint().subtractToRef(h,i._tmpPositionVector),i._tmpPositionVector.divideInPlace(t.object.scaling),r.pos.push(h.x),r.pos.push(h.y),r.pos.push(h.z),r.posShape.push(0,0,0),r.rot.push(0),r.rot.push(0),r.rot.push(0),r.rotShape.push(0,0,0)}else{var u=n.object.getAbsolutePosition().subtract(t.object.getAbsolutePosition());r.posShape.push(u.x),r.posShape.push(u.y),r.posShape.push(u.z),r.pos.push(0,0,0),r.rot.push(0),r.rot.push(0),r.rot.push(0),r.rotShape.push(57.29577951308232*l.x),r.rotShape.push(57.29577951308232*l.y),r.rotShape.push(57.29577951308232*l.z)}switch(n.type){case e.PhysicsImpostor.ParticleImpostor:e.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case e.PhysicsImpostor.SphereImpostor:var d=c.x,f=c.y,p=c.z,_=Math.max(o(d),o(f),o(p))/2;r.type.push("sphere"),r.size.push(_),r.size.push(_),r.size.push(_);break;case e.PhysicsImpostor.CylinderImpostor:var m=o(c.x)/2,g=o(c.y);r.type.push("cylinder"),r.size.push(m),r.size.push(g),r.size.push(g);break;case e.PhysicsImpostor.PlaneImpostor:case e.PhysicsImpostor.BoxImpostor:default:var m=o(c.x),g=o(c.y),v=o(c.z);r.type.push("box"),r.size.push(m),r.size.push(g),r.size.push(v)}n.object.rotationQuaternion=a}})),t.physicsBody=this.world.add(r),t.physicsBody.resetQuaternion(s),t.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);t.setDeltaPosition(this._tmpPositionVector)},i.prototype.removePhysicsBody=function(e){this.world.removeRigidBody(e.physicsBody)},i.prototype.generateJoint=function(t){var i=t.mainImpostor.physicsBody,r=t.connectedImpostor.physicsBody;if(i&&r){var n,o=t.joint.jointData,s=o.nativeParams||{},a={body1:i,body2:r,axe1:s.axe1||(o.mainAxis?o.mainAxis.asArray():null),axe2:s.axe2||(o.connectedAxis?o.connectedAxis.asArray():null),pos1:s.pos1||(o.mainPivot?o.mainPivot.asArray():null),pos2:s.pos2||(o.connectedPivot?o.connectedPivot.asArray():null),min:s.min,max:s.max,collision:s.collision||o.collision,spring:s.spring,world:this.world};switch(t.joint.type){case e.PhysicsJoint.BallAndSocketJoint:n="jointBall";break;case e.PhysicsJoint.SpringJoint:e.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");var l=o;a.min=l.length||a.min,a.max=Math.max(a.min,a.max);case e.PhysicsJoint.DistanceJoint:n="jointDistance",a.max=o.maxDistance;break;case e.PhysicsJoint.PrismaticJoint:n="jointPrisme";break;case e.PhysicsJoint.SliderJoint:n="jointSlide";break;case e.PhysicsJoint.WheelJoint:n="jointWheel";break;case e.PhysicsJoint.HingeJoint:default:n="jointHinge"}a.type=n,t.joint.physicsJoint=this.world.add(a)}},i.prototype.removeJoint=function(t){try{this.world.removeJoint(t.joint.physicsJoint)}catch(t){e.Tools.Warn(t)}},i.prototype.isSupported=function(){return void 0!==this.BJSOIMO},i.prototype.setTransformationFromPhysicsBody=function(e){e.physicsBody.sleeping||(e.object.position.copyFrom(e.physicsBody.getPosition()),e.object.rotationQuaternion&&e.object.rotationQuaternion.copyFrom(e.physicsBody.getQuaternion()))},i.prototype.setPhysicsBodyTransformation=function(e,t,i){var r=e.physicsBody;r.position.copy(t),r.orientation.copy(i),r.syncShapes(),r.awake()},i.prototype.setLinearVelocity=function(e,t){e.physicsBody.linearVelocity.copy(t)},i.prototype.setAngularVelocity=function(e,t){e.physicsBody.angularVelocity.copy(t)},i.prototype.getLinearVelocity=function(t){var i=t.physicsBody.linearVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},i.prototype.getAngularVelocity=function(t){var i=t.physicsBody.angularVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},i.prototype.setBodyMass=function(e,t){var i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)},i.prototype.getBodyMass=function(e){return e.physicsBody.shapes.density},i.prototype.getBodyFriction=function(e){return e.physicsBody.shapes.friction},i.prototype.setBodyFriction=function(e,t){e.physicsBody.shapes.friction=t},i.prototype.getBodyRestitution=function(e){return e.physicsBody.shapes.restitution},i.prototype.setBodyRestitution=function(e,t){e.physicsBody.shapes.restitution=t},i.prototype.sleepBody=function(e){e.physicsBody.sleep()},i.prototype.wakeUpBody=function(e){e.physicsBody.awake()},i.prototype.updateDistanceJoint=function(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)},i.prototype.setMotor=function(e,t,i,r){var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setMotor(t,i)},i.prototype.setLimit=function(e,t,i,r){var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setLimit(t,void 0===i?-t:i)},i.prototype.syncMeshWithImpostor=function(e,t){var i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.s)},i.prototype.getRadius=function(e){return e.physicsBody.shapes.radius},i.prototype.getBoxSizeToRef=function(e,t){var i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth},i.prototype.dispose=function(){this.world.clear()},i})();e.OimoJSPlugin=i})(r||(r={}));var r;!(function(e){function t(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}function i(e){return String.fromCharCode(255&e,e>>8&255,e>>16&255,e>>24&255)}var r=t("DXT1"),n=t("DXT3"),o=t("DXT5"),s=t("DX10"),a=(function(){function t(){}return t.GetDDSInfo=function(t){var i=new Int32Array(t,0,31),a=new Int32Array(t,0,35),l=1;131072&i[2]&&(l=Math.max(1,i[7]));var c=i[21],h=c===s?a[32]:0,u=e.Engine.TEXTURETYPE_UNSIGNED_INT;switch(c){case 113:u=e.Engine.TEXTURETYPE_HALF_FLOAT;break;case 116:u=e.Engine.TEXTURETYPE_FLOAT;break;case s:if(10===h){u=e.Engine.TEXTURETYPE_HALF_FLOAT;break}}return{width:i[4],height:i[3],mipmapCount:l,isFourCC:4==(4&i[20]),isRGB:64==(64&i[20]),isLuminance:131072==(131072&i[20]),isCube:512==(512&i[28]),isCompressed:c===r||c===n||c===o,dxgiFormat:h,textureType:u}},t._ToHalfFloat=function(e){t._FloatView||(t._FloatView=new Float32Array(1),t._Int32View=new Int32Array(t._FloatView.buffer)),t._FloatView[0]=e;var i=t._Int32View[0],r=i>>16&32768,n=i>>12&2047,o=i>>23&255;return o<103?r:o>142?(r|=31744,r|=(255==o?0:1)&&8388607&i):o<113?(n|=2048,r|=(n>>114-o)+(n>>113-o&1)):(r|=o-112<<10|n>>1,r+=1&n)},t._FromHalfFloat=function(e){var t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(r/Math.pow(2,10)):31==i?r?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+r/Math.pow(2,10))},t._GetHalfFloatAsFloatRGBAArrayBuffer=function(e,i,r,n,o,s){for(var a=new Float32Array(n),l=new Uint16Array(o,r),c=0,h=0;h>8)},t._GetRGBArrayBuffer=function(e,t,i,r,n,o,s,a){for(var l=new Uint8Array(r),c=new Uint8Array(n,i),h=0,u=0;u0?h.sphericalPolynomial=e.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({size:P[4],right:_[0],left:_[1],up:_[2],down:_[3],front:_[4],back:_[5],format:e.Engine.TEXTUREFORMAT_RGBA,type:e.Engine.TEXTURETYPE_FLOAT,gammaSpace:!1}):h.sphericalPolynomial=void 0},t.StoreLODInAlphaChannel=!1,t})();e.DDSTools=a})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.supportCascades=!0}return t.prototype.canLoad=function(e,t,i,r,n){return 0===e.indexOf(".dds")},t.prototype.transformUrl=function(e,t){return e},t.prototype.getFallbackTextureUrl=function(e,t){return null},t.prototype.loadCubeData=function(t,i,r,n,o){var s,a=i.getEngine(),l=!1;if(Array.isArray(t))for(var c=0;c1)&&i.generateMipMaps,a._unpackFlipY(s.isCompressed),e.DDSTools.UploadDDSLevels(a,i,h,s,l,6,-1,c),s.isFourCC||1!==s.mipmapCount||a.generateMipMapsForCubemap(i)}else{var u=t;s=e.DDSTools.GetDDSInfo(u),i.width=s.width,i.height=s.height,r&&(s.sphericalPolynomial=new e.SphericalPolynomial),l=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&i.generateMipMaps,a._unpackFlipY(s.isCompressed),e.DDSTools.UploadDDSLevels(a,i,u,s,l,6),s.isFourCC||1!==s.mipmapCount||a.generateMipMapsForCubemap(i)}a._setCubeMapTextureParams(l),i.isReady=!0,n&&n({isDDS:!0,width:i.width,info:s,data:t,texture:i})},t.prototype.loadData=function(t,i,r){var n=e.DDSTools.GetDDSInfo(t),o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&i.generateMipMaps&&n.width>>n.mipmapCount-1==1;r(n.width,n.height,!o,n.isFourCC,(function(){e.DDSTools.UploadDDSLevels(i.getEngine(),i,t,n,o,1)}))},t})();e.Engine._TextureLoaders.push(new t)})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.GetTGAHeader=function(e){var t=0;return{id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]}},t.UploadContent=function(i,r){if(r.length<19)return void e.Tools.Error("Unable to load TGA file - Not enough data to contain header");var n=18,o=t.GetTGAHeader(r);if(o.id_length+n>r.length)return void e.Tools.Error("Unable to load TGA file - Not enough data");n+=o.id_length;var s=!1,a=!1,l=!1;switch(o.image_type){case t._TYPE_RLE_INDEXED:s=!0;case t._TYPE_INDEXED:a=!0;break;case t._TYPE_RLE_RGB:s=!0;case t._TYPE_RGB:break;case t._TYPE_RLE_GREY:s=!0;case t._TYPE_GREY:l=!0}var c,h,u=o.pixel_size>>3,d=o.width*o.height*u;if(a&&(h=r.subarray(n,n+=o.colormap_length*(o.colormap_size>>3))),s){c=new Uint8Array(d);for(var f,p,_,m=0,g=new Uint8Array(u);n>t._ORIGIN_SHIFT){default:case t._ORIGIN_UL:v=0,b=1,E=o.width,y=0,x=1,T=o.height;break;case t._ORIGIN_BL:v=0,b=1,E=o.width,y=o.height-1,x=-1,T=-1;break;case t._ORIGIN_UR:v=o.width-1,b=-1,E=-1,y=0,x=1,T=o.height;break;case t._ORIGIN_BR:v=o.width-1,b=-1,E=-1,y=o.height-1,x=-1,T=-1}var P="_getImageData"+(l?"Grey":"")+o.pixel_size+"bits",A=t[P](o,h,c,y,x,T,v,b,E);i.getEngine()._uploadDataToTextureDirectly(i,A)},t._getImageData8bits=function(e,t,i,r,n,o,s,a,l){var c,h,u,d=i,f=t,p=e.width,_=e.height,m=0,g=new Uint8Array(p*_*4);for(u=r;u!==o;u+=n)for(h=s;h!==l;h+=a,m++)c=d[m],g[4*(h+p*u)+3]=255,g[4*(h+p*u)+2]=f[3*c+0],g[4*(h+p*u)+1]=f[3*c+1],g[4*(h+p*u)+0]=f[3*c+2];return g},t._getImageData16bits=function(e,t,i,r,n,o,s,a,l){var c,h,u,d=i,f=e.width,p=e.height,_=0,m=new Uint8Array(f*p*4);for(u=r;u!==o;u+=n)for(h=s;h!==l;h+=a,_+=2){c=d[_+0]+(d[_+1]<<8);var g=255*((31744&c)>>10)/31|0,v=255*((992&c)>>5)/31|0,y=255*(31&c)/31|0;m[4*(h+f*u)+0]=g,m[4*(h+f*u)+1]=v,m[4*(h+f*u)+2]=y,m[4*(h+f*u)+3]=32768&c?0:255}return m},t._getImageData24bits=function(e,t,i,r,n,o,s,a,l){var c,h,u=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(h=r;h!==o;h+=n)for(c=s;c!==l;c+=a,p+=3)_[4*(c+d*h)+3]=255,_[4*(c+d*h)+2]=u[p+0],_[4*(c+d*h)+1]=u[p+1],_[4*(c+d*h)+0]=u[p+2];return _},t._getImageData32bits=function(e,t,i,r,n,o,s,a,l){var c,h,u=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(h=r;h!==o;h+=n)for(c=s;c!==l;c+=a,p+=4)_[4*(c+d*h)+2]=u[p+0],_[4*(c+d*h)+1]=u[p+1],_[4*(c+d*h)+0]=u[p+2],_[4*(c+d*h)+3]=u[p+3];return _},t._getImageDataGrey8bits=function(e,t,i,r,n,o,s,a,l){var c,h,u,d=i,f=e.width,p=e.height,_=0,m=new Uint8Array(f*p*4);for(u=r;u!==o;u+=n)for(h=s;h!==l;h+=a,_++)c=d[_],m[4*(h+f*u)+0]=c,m[4*(h+f*u)+1]=c,m[4*(h+f*u)+2]=c,m[4*(h+f*u)+3]=255;return m},t._getImageDataGrey16bits=function(e,t,i,r,n,o,s,a,l){var c,h,u=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(h=r;h!==o;h+=n)for(c=s;c!==l;c+=a,p+=2)_[4*(c+d*h)+0]=u[p+0],_[4*(c+d*h)+1]=u[p+0],_[4*(c+d*h)+2]=u[p+0],_[4*(c+d*h)+3]=u[p+1];return _},t._TYPE_INDEXED=1,t._TYPE_RGB=2,t._TYPE_GREY=3,t._TYPE_RLE_INDEXED=9,t._TYPE_RLE_RGB=10,t._TYPE_RLE_GREY=11,t._ORIGIN_MASK=48,t._ORIGIN_SHIFT=4,t._ORIGIN_BL=0,t._ORIGIN_BR=1,t._ORIGIN_UL=2,t._ORIGIN_UR=3,t})();e.TGATools=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.supportCascades=!1}return t.prototype.canLoad=function(e,t,i,r,n){return 0===e.indexOf(".tga")},t.prototype.transformUrl=function(e,t){return e},t.prototype.getFallbackTextureUrl=function(e,t){return null},t.prototype.loadCubeData=function(e,t,i,r,n){throw".env not supported in Cube."},t.prototype.loadData=function(t,i,r){var n=new Uint8Array(t),o=e.TGATools.GetTGAHeader(n);r(o.width,o.height,i.generateMipMaps,!1,(function(){e.TGATools.UploadContent(i,n)}))},t})();e.Engine._TextureLoaders.push(new t)})(r||(r={}));var r;!(function(e){var t=(function(){function t(i,r,n,o){this.arrayBuffer=i;var s=new Uint8Array(this.arrayBuffer,0,12);if(171!==s[0]||75!==s[1]||84!==s[2]||88!==s[3]||32!==s[4]||49!==s[5]||49!==s[6]||187!==s[7]||13!==s[8]||10!==s[9]||26!==s[10]||10!==s[11])return void e.Tools.Error("texture missing KTX identifier");var a=new Int32Array(this.arrayBuffer,12,13),l=16909060===a[0];return this.glType=l?this.switchEndainness(a[1]):a[1],this.glTypeSize=l?this.switchEndainness(a[2]):a[2],this.glFormat=l?this.switchEndainness(a[3]):a[3],this.glInternalFormat=l?this.switchEndainness(a[4]):a[4],this.glBaseInternalFormat=l?this.switchEndainness(a[5]):a[5],this.pixelWidth=l?this.switchEndainness(a[6]):a[6],this.pixelHeight=l?this.switchEndainness(a[7]):a[7],this.pixelDepth=l?this.switchEndainness(a[8]):a[8],this.numberOfArrayElements=l?this.switchEndainness(a[9]):a[9], +this.numberOfFaces=l?this.switchEndainness(a[10]):a[10],this.numberOfMipmapLevels=l?this.switchEndainness(a[11]):a[11],this.bytesOfKeyValueData=l?this.switchEndainness(a[12]):a[12],0!==this.glType?void e.Tools.Error("only compressed formats currently supported"):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?void e.Tools.Error("only 2D textures currently supported"):0!==this.numberOfArrayElements?void e.Tools.Error("texture arrays not currently supported"):this.numberOfFaces!==r?void e.Tools.Error("number of faces expected"+r+", but found "+this.numberOfFaces):void(this.loadType=t.COMPRESSED_2D))}return t.prototype.switchEndainness=function(e){return(255&e)<<24|(65280&e)<<8|e>>8&65280|e>>24&255},t.prototype.uploadLevels=function(e,i){switch(this.loadType){case t.COMPRESSED_2D:this._upload2DCompressedLevels(e,i);break;case t.TEX_2D:case t.COMPRESSED_3D:case t.TEX_3D:}},t.prototype._upload2DCompressedLevels=function(e,i){for(var r=t.HEADER_LEN+this.bytesOfKeyValueData,n=this.pixelWidth,o=this.pixelHeight,s=i?this.numberOfMipmapLevels:1,a=0;a-1?e.substring(0,i):e)+t},t.prototype.getFallbackTextureUrl=function(e,t){var i=new RegExp(t+"$");return e.replace(i,"")},t.prototype.loadCubeData=function(t,i,r,n,o){if(!Array.isArray(t)){var s=i.getEngine(),a=new e.KhronosTextureContainer(t,6),l=a.numberOfMipmapLevels>1&&i.generateMipMaps;s._unpackFlipY(!0),a.uploadLevels(i,i.generateMipMaps),i.width=a.pixelWidth,i.height=a.pixelHeight,s._setCubeMapTextureParams(l),i.isReady=!0}},t.prototype.loadData=function(t,i,r){var n=new e.KhronosTextureContainer(t,1);r(n.pixelWidth,n.pixelHeight,!1,!0,(function(){n.uploadLevels(i,i.generateMipMaps)}))},t})();e.Engine._TextureLoaders.unshift(new t)})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.GetEnvInfo=function(i){for(var r=new DataView(i),n=0,o=0;o0)):!i._pointerCaptures[l.pointerId]&&s.distance>a.distance&&(i.mainSceneTrackerPredicate&&i.mainSceneTrackerPredicate(a.pickedMesh)?(i._notifyObservers(r,a,l),r.skipOnPointerObservable=!0):i._lastPointerEvents[l.pointerId]&&(i.onPointerOutObservable.notifyObservers(l.pointerId),delete i._lastPointerEvents[l.pointerId])),r.type===e.PointerEventTypes.POINTERUP&&i._pointerCaptures[l.pointerId]&&(i._pointerCaptures[l.pointerId]=!1))}}})),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderObservable.add((function(){i.shouldRender&&i.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((function(){i.dispose()})),this._updateCamera()}return Object.defineProperty(t,"DefaultUtilityLayer",{get:function(){return null==t._DefaultUtilityLayer&&(t._DefaultUtilityLayer=new t(e.Engine.LastCreatedScene),t._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((function(){t._DefaultUtilityLayer=null}))),t._DefaultUtilityLayer},enumerable:!0,configurable:!0}),Object.defineProperty(t,"DefaultKeepDepthUtilityLayer",{get:function(){return null==t._DefaultKeepDepthUtilityLayer&&(t._DefaultKeepDepthUtilityLayer=new t(e.Engine.LastCreatedScene),t._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,t._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((function(){t._DefaultKeepDepthUtilityLayer=null}))),t._DefaultKeepDepthUtilityLayer},enumerable:!0,configurable:!0}),t.prototype._notifyObservers=function(t,i,r){t.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new e.PointerInfo(t.type,t.event,i)),this._lastPointerEvents[r.pointerId]=r.pointerType)},t.prototype.render=function(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){var e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}},t.prototype.dispose=function(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()},t.prototype._updateCamera=function(){this.utilityLayerScene.activeCamera=this.originalScene.activeCamera},t._DefaultUtilityLayer=null,t._DefaultKeepDepthUtilityLayer=null,t})();e.UtilityLayerRenderer=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){this.maxDragAngle=0,this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerID=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new e.Observable,this.onDragStartObservable=new e.Observable,this.onDragEndObservable=new e.Observable,this.moveAttached=!0,this.enabled=!0,this.detachCameraControls=!0,this.useObjectOrienationForDragging=!0,this._tmpVector=new e.Vector3(0,0,0),this._alternatePickedPoint=new e.Vector3(0,0,0),this._worldDragAxis=new e.Vector3(0,0,0),this._pointA=new e.Vector3(0,0,0),this._pointB=new e.Vector3(0,0,0),this._pointC=new e.Vector3(0,0,0),this._lineA=new e.Vector3(0,0,0),this._lineB=new e.Vector3(0,0,0),this._localAxis=new e.Vector3(0,0,0),this._lookAt=new e.Vector3(0,0,0),this._options=t||{};var i=0;if(this._options.dragAxis&&i++,this._options.dragPlaneNormal&&i++,i>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}return Object.defineProperty(t.prototype,"name",{get:function(){return"PointerDrag"},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(i){var r=this;this._scene=i.getScene(),this._attachedNode=i,t._planeScene||(this._debugMode?t._planeScene=this._scene:(t._planeScene=new e.Scene(this._scene.getEngine()),t._planeScene.detachControl(),this._scene.getEngine().scenes.pop(),this._scene.onDisposeObservable.addOnce((function(){t._planeScene.dispose(),t._planeScene=null})))),this._dragPlane=e.Mesh.CreatePlane("pointerDragPlane",this._debugMode?1:1e4,t._planeScene,!1,e.Mesh.DOUBLESIDE),this.lastDragPosition=new e.Vector3(0,0,0);var n=new e.Vector3(0,0,0),o=0,s=new e.Vector3(0,0,0),a=function(e){return r._attachedNode==e||e.isDescendantOf(r._attachedNode)},l=null;this._pointerObserver=this._scene.onPointerObservable.add((function(t,i){if(r.enabled)if(t.type==e.PointerEventTypes.POINTERDOWN){if(!r.dragging&&t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh&&t.pickInfo.pickedPoint&&t.pickInfo.ray&&a(t.pickInfo.pickedMesh)){r._updateDragPlanePosition(t.pickInfo.ray,t.pickInfo.pickedPoint);var c=r._pickWithRayOnDragPlane(t.pickInfo.ray);c&&(r.dragging=!0,r.currentDraggingPointerID=t.event.pointerId,r.lastDragPosition.copyFrom(c),r.onDragStartObservable.notifyObservers({dragPlanePoint:c,pointerId:r.currentDraggingPointerID}),s.copyFrom(r._attachedNode.absolutePosition),r.detachCameraControls&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&(r._scene.activeCamera.inputs.attachedElement?(l=r._scene.activeCamera.inputs.attachedElement,r._scene.activeCamera.detachControl(r._scene.activeCamera.inputs.attachedElement)):l=null))}}else if(t.type==e.PointerEventTypes.POINTERUP)r.currentDraggingPointerID==t.event.pointerId&&(r.releaseDrag(),r.detachCameraControls&&l&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&r._scene.activeCamera.attachControl(l,!0));else if(t.type==e.PointerEventTypes.POINTERMOVE&&r.currentDraggingPointerID==t.event.pointerId&&r.dragging&&t.pickInfo&&t.pickInfo.ray){r._moving=!0;var c=r._pickWithRayOnDragPlane(t.pickInfo.ray);c&&(r.updateDragPlane&&r._updateDragPlanePosition(t.pickInfo.ray,c),r._options.dragAxis?(e.Vector3.TransformCoordinatesToRef(r._options.dragAxis,r._attachedNode.getWorldMatrix().getRotationMatrix(),r._worldDragAxis),c.subtractToRef(r.lastDragPosition,r._tmpVector),o=e.Vector3.Dot(r._tmpVector,r._worldDragAxis),r._worldDragAxis.scaleToRef(o,n)):(o=n.length(),c.subtractToRef(r.lastDragPosition,n)),s.addInPlace(n),r.onDragObservable.notifyObservers({dragDistance:o,delta:n,dragPlanePoint:c,dragPlaneNormal:r._dragPlane.forward,pointerId:r.currentDraggingPointerID}),r.lastDragPosition.copyFrom(c))}})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((function(){r._moving&&r.moveAttached&&(s.subtractToRef(r._attachedNode.absolutePosition,r._tmpVector),r._tmpVector.scaleInPlace(.2),r._attachedNode.getAbsolutePosition().addToRef(r._tmpVector,r._tmpVector),r._attachedNode.setAbsolutePosition(r._tmpVector))}))},t.prototype.releaseDrag=function(){this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerID}),this.currentDraggingPointerID=-1,this._moving=!1},t.prototype._pickWithRayOnDragPlane=function(i){var r=this;if(!i)return null;var n=Math.acos(e.Vector3.Dot(this._dragPlane.forward,i.direction));if(n>Math.PI/2&&(n=Math.PI-n),this.maxDragAngle>0&&n>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(i.direction),this._attachedNode.absolutePosition.subtractToRef(i.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(-2*e.Vector3.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);var o=e.Vector3.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-o,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition),this._alternatePickedPoint}return null}var s=t._planeScene.pickWithRay(i,(function(e){return e==r._dragPlane}));return s&&s.hit&&s.pickedMesh&&s.pickedPoint?s.pickedPoint:null},t.prototype._updateDragPlanePosition=function(t,i){this._pointA.copyFrom(i),this._options.dragAxis?(this.useObjectOrienationForDragging?e.Vector3.TransformCoordinatesToRef(this._options.dragAxis,this._attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),this._pointA.addToRef(this._localAxis,this._pointB),t.origin.subtractToRef(this._pointA,this._pointC),this._pointA.addToRef(this._pointC.normalize(),this._pointC),this._pointB.subtractToRef(this._pointA,this._lineA),this._pointC.subtractToRef(this._pointA,this._lineB),e.Vector3.CrossToRef(this._lineA,this._lineB,this._lookAt),e.Vector3.CrossToRef(this._lineA,this._lookAt,this._lookAt),this._lookAt.normalize(),this._dragPlane.position.copyFrom(this._pointA),this._pointA.subtractToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrienationForDragging?e.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal,this._attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.subtractToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(t.origin)),this._dragPlane.computeWorldMatrix(!0)},t.prototype.detach=function(){this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver)},t})();e.PointerDragBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._startDistance=0,this._initialScale=new e.Vector3(0,0,0),this._targetScale=new e.Vector3(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new e.PointerDragBehavior({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new e.PointerDragBehavior({}),this._dragBehaviorB.moveAttached=!1}return Object.defineProperty(t.prototype,"name",{get:function(){return"MultiPointerScale"},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype._getCurrentDistance=function(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()},t.prototype.attach=function(e){var t=this;this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add((function(i){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerID==t._dragBehaviorB.currentDraggingPointerID?t._dragBehaviorA.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))})),this._dragBehaviorB.onDragStartObservable.add((function(i){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerID==t._dragBehaviorB.currentDraggingPointerID?t._dragBehaviorB.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))})),[this._dragBehaviorA,this._dragBehaviorB].forEach((function(e){e.onDragObservable.add((function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var e=t._getCurrentDistance()/t._startDistance;t._initialScale.scaleToRef(e,t._targetScale)}}))})),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var i=t._targetScale.subtract(e.scaling).scaleInPlace(.1);i.length()>.01&&e.scaling.addInPlace(i)}}))},t.prototype.detach=function(){var e=this;this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach((function(t){t.onDragStartObservable.clear(),t.onDragObservable.clear(),e._ownerNode.removeBehavior(t)}))},t})();e.MultiPointerScaleBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._sceneRenderObserver=null,this._targetPosition=new e.Vector3(0,0,0),this._moving=!1,this._startingOrientation=new e.Quaternion,this.zDragFactor=3,this.dragging=!1,this.dragDeltaRatio=.2,this.currentDraggingPointerID=-1,this.detachCameraControls=!0}return Object.defineProperty(t.prototype,"name",{get:function(){return"SixDofDrag"},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(i){var r=this;this._ownerNode=i,this._scene=this._ownerNode.getScene(),t._virtualScene||(t._virtualScene=new e.Scene(this._scene.getEngine()),this._scene.getEngine().scenes.pop());var n=null,o=new e.Vector3(0,0,0);this._virtualOriginMesh=new e.AbstractMesh("",t._virtualScene),this._virtualOriginMesh.rotationQuaternion=new e.Quaternion,this._virtualDragMesh=new e.AbstractMesh("",t._virtualScene),this._virtualDragMesh.rotationQuaternion=new e.Quaternion;var s=function(e){return r._ownerNode==e||e.isDescendantOf(r._ownerNode)},a=null;this._pointerObserver=this._scene.onPointerObservable.add((function(t,i){if(t.type==e.PointerEventTypes.POINTERDOWN){if(!r.dragging&&t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh&&t.pickInfo.ray&&s(t.pickInfo.pickedMesh)){r._scene.activeCamera&&r._scene.activeCamera.cameraRigMode==e.Camera.RIG_MODE_NONE&&t.pickInfo.ray.origin.copyFrom(r._scene.activeCamera.position),n=r._ownerNode,o.copyFrom(t.pickInfo.ray.origin),r._virtualOriginMesh.position.copyFrom(t.pickInfo.ray.origin),r._virtualOriginMesh.lookAt(t.pickInfo.ray.origin.subtract(t.pickInfo.ray.direction)),r._virtualOriginMesh.removeChild(r._virtualDragMesh),r._virtualDragMesh.position.copyFrom(n.absolutePosition),n.rotationQuaternion||(n.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(n.rotation.y,n.rotation.x,n.rotation.z));var l=n.parent;n.setParent(null),r._virtualDragMesh.rotationQuaternion.copyFrom(n.rotationQuaternion),n.setParent(l),r._virtualOriginMesh.addChild(r._virtualDragMesh),r._targetPosition.copyFrom(r._virtualDragMesh.absolutePosition),r.dragging=!0,r.currentDraggingPointerID=t.event.pointerId,r.detachCameraControls&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&(r._scene.activeCamera.inputs.attachedElement?(a=r._scene.activeCamera.inputs.attachedElement,r._scene.activeCamera.detachControl(r._scene.activeCamera.inputs.attachedElement)):a=null)}}else if(t.type==e.PointerEventTypes.POINTERUP)r.currentDraggingPointerID==t.event.pointerId&&(r.dragging=!1,r._moving=!1,r.currentDraggingPointerID=-1,n=null,r._virtualOriginMesh.removeChild(r._virtualDragMesh),r.detachCameraControls&&a&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&r._scene.activeCamera.attachControl(a,!0));else if(t.type==e.PointerEventTypes.POINTERMOVE&&r.currentDraggingPointerID==t.event.pointerId&&r.dragging&&t.pickInfo&&t.pickInfo.ray&&n){var c=r.zDragFactor;r._scene.activeCamera&&r._scene.activeCamera.cameraRigMode==e.Camera.RIG_MODE_NONE&&(t.pickInfo.ray.origin.copyFrom(r._scene.activeCamera.position),c=0);var h=t.pickInfo.ray.origin.subtract(o);o.copyFrom(t.pickInfo.ray.origin);var u=-e.Vector3.Dot(h,t.pickInfo.ray.direction);r._virtualOriginMesh.addChild(r._virtualDragMesh),r._virtualDragMesh.position.z-=r._virtualDragMesh.position.z<1?u*r.zDragFactor:u*c*r._virtualDragMesh.position.z,r._virtualDragMesh.position.z<0&&(r._virtualDragMesh.position.z=0),r._virtualOriginMesh.position.copyFrom(t.pickInfo.ray.origin),r._virtualOriginMesh.lookAt(t.pickInfo.ray.origin.subtract(t.pickInfo.ray.direction)),r._virtualOriginMesh.removeChild(r._virtualDragMesh),r._targetPosition.copyFrom(r._virtualDragMesh.absolutePosition),n.parent&&e.Vector3.TransformCoordinatesToRef(r._targetPosition,e.Matrix.Invert(n.parent.getWorldMatrix()),r._targetPosition),r._moving||r._startingOrientation.copyFrom(r._virtualDragMesh.rotationQuaternion),r._moving=!0}}));var l=new e.Quaternion;this._sceneRenderObserver=i.getScene().onBeforeRenderObservable.add((function(){if(r.dragging&&r._moving&&n){n.position.addInPlace(r._targetPosition.subtract(n.position).scale(r.dragDeltaRatio)),l.copyFrom(r._startingOrientation),l.x=-l.x,l.y=-l.y,l.z=-l.z,r._virtualDragMesh.rotationQuaternion.multiplyToRef(l,l),e.Quaternion.RotationYawPitchRollToRef(l.toEulerAngles("xyz").y,0,0,l),l.multiplyToRef(r._startingOrientation,l);var t=n.parent;n.setParent(null),e.Quaternion.SlerpToRef(n.rotationQuaternion,l,r.dragDeltaRatio,n.rotationQuaternion),n.setParent(t)}}))},t.prototype.detach=function(){this._scene&&this._scene.onPointerObservable.remove(this._pointerObserver),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualOriginMesh&&this._virtualOriginMesh.dispose(),this._virtualDragMesh&&this._virtualDragMesh.dispose()},t})();e.SixDofDragBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n){void 0===i&&(i=new e.Vector3),void 0===r&&(r=0),void 0===n&&(n=!1),this.direction=t,this.rotatedDirection=i,this.diff=r,this.ignore=n}return t})(),i=(function(){function i(i){this.ui=i,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new t(e.Vector3.Up()),new t(e.Vector3.Down()),new t(e.Vector3.Left()),new t(e.Vector3.Right()),new t(e.Vector3.Forward()),new t(e.Vector3.Forward().scaleInPlace(-1))],this._tmpMatrix=new e.Matrix,this._tmpVector=new e.Vector3,this._zeroVector=e.Vector3.Zero(),this._lookAtTmpMatrix=new e.Matrix}return i.prototype.init=function(){},i.prototype._closestFace=function(t){var i=this;return this._faceVectors.forEach((function(r){i._target.rotationQuaternion||(i._target.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(i._target.rotation.y,i._target.rotation.x,i._target.rotation.z)),i._target.rotationQuaternion.toRotationMatrix(i._tmpMatrix),e.Vector3.TransformCoordinatesToRef(r.direction,i._tmpMatrix,r.rotatedDirection),r.diff=e.Vector3.GetAngleBetweenVectors(r.rotatedDirection,t,e.Vector3.Cross(r.rotatedDirection,t))})),this._faceVectors.reduce((function(e,t){return e.ignore?t:t.ignore?e:e.diffo.snapDistance){var t=Math.floor(Math.abs(u)/o.snapDistance);u%=o.snapDistance,e.delta.normalizeToRef(d),d.scaleInPlace(o.snapDistance*t),o.attachedMesh.position.addInPlace(d),f.snapDistance=o.snapDistance*t,o.onSnapObservable.notifyObservers(f)}})),o._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e,t){if(!o._customMeshSet){var i=e.pickInfo&&-1!=o._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh),r=i?a:s;o._rootMesh.getChildMeshes().forEach((function(e){e.material=r,e.color&&(e.color=r.emissiveColor)}))}})),o}return o(i,t),i.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),t.prototype.dispose.call(this)},i})(e.Gizmo);e.AxisDragGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n){void 0===r&&(r=e.Color3.Gray()),void 0===n&&(n=e.UtilityLayerRenderer.DefaultUtilityLayer);var o=t.call(this,n)||this;o._pointerObserver=null,o.snapDistance=0,o.onSnapObservable=new e.Observable;var s=new e.StandardMaterial("",n.utilityLayerScene);s.disableLighting=!0,s.emissiveColor=r;var a=new e.StandardMaterial("",n.utilityLayerScene);a.disableLighting=!0,a.emissiveColor=r.add(new e.Color3(.2,.2,.2));var l=new e.AbstractMesh("",n.utilityLayerScene),c=e.MeshBuilder.CreateBox("yPosMesh",{size:.4},n.utilityLayerScene),h=e.MeshBuilder.CreateLines("yPosMesh",{points:[new e.Vector3(0,0,0),new e.Vector3(0,1.5,0)]},n.utilityLayerScene);h.color=s.emissiveColor,l.addChild(c),l.addChild(h),c.scaling.scaleInPlace(.1),c.material=s,c.rotation.x=Math.PI/2,c.position.z+=.3,h.scaling.scaleInPlace(.2),h.rotation.x=Math.PI/2,h.material=s,l.lookAt(o._rootMesh.position.subtract(i)),o._rootMesh.addChild(l),o.dragBehavior=new e.PointerDragBehavior({dragAxis:i}),o.dragBehavior.moveAttached=!1,o._rootMesh.addBehavior(o.dragBehavior);var u=0,d=new e.Vector3,f={snapDistance:0};return o.dragBehavior.onDragObservable.add((function(e){if(o.attachedMesh){var t=!1,r=0;0==o.snapDistance?i.scaleToRef(e.dragDistance,d):(u+=e.dragDistance,Math.abs(u)>o.snapDistance?(r=Math.floor(u/o.snapDistance),u%=o.snapDistance,i.scaleToRef(o.snapDistance*r,d),t=!0):d.scaleInPlace(0)),o.attachedMesh.scaling.addInPlace(d),t&&(f.snapDistance=o.snapDistance*r,o.onSnapObservable.notifyObservers(f))}})),o._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e,t){if(!o._customMeshSet){var i=e.pickInfo&&-1!=o._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh),r=i?a:s;o._rootMesh.getChildMeshes().forEach((function(e){e.material=r,e.color&&(e.color=r.emissiveColor)}))}})),o}return o(i,t),i.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),t.prototype.dispose.call(this)},i})(e.Gizmo);e.AxisScaleGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n){void 0===r&&(r=e.Color3.Gray()),void 0===n&&(n=e.UtilityLayerRenderer.DefaultUtilityLayer);var o=t.call(this,n)||this;o._pointerObserver=null,o.snapDistance=0,o.onSnapObservable=new e.Observable;var s=new e.StandardMaterial("",n.utilityLayerScene);s.disableLighting=!0,s.emissiveColor=r;var a=new e.StandardMaterial("",n.utilityLayerScene);a.disableLighting=!0,a.emissiveColor=r.add(new e.Color3(.2,.2,.2));for(var l=new e.AbstractMesh("",n.utilityLayerScene),c=new Array,h=0;h<20;h++){var u=2*Math.PI*(h/19);c.push(new e.Vector3(2*Math.sin(u),0,2*Math.cos(u)))}var d=e.Mesh.CreateLines("",c,n.utilityLayerScene);d.color=s.emissiveColor,d.scaling.scaleInPlace(.1),d.material=s,d.rotation.x=Math.PI/2,l.addChild(d),l.lookAt(o._rootMesh.position.subtract(i)),o._rootMesh.addChild(l),o.dragBehavior=new e.PointerDragBehavior({dragPlaneNormal:i}),o.dragBehavior.moveAttached=!1,o.dragBehavior.maxDragAngle=9*Math.PI/20,o.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,o._rootMesh.addBehavior(o.dragBehavior);var f=new e.Vector3;o.dragBehavior.onDragStartObservable.add((function(e){o.attachedMesh&&f.copyFrom(e.dragPlanePoint)}));var p=new e.Matrix,_=new e.Vector3,m=new e.Vector3,g={snapDistance:0},v=0;return o.dragBehavior.onDragObservable.add((function(t){if(o.attachedMesh){o.attachedMesh.rotationQuaternion||(o.attachedMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(o.attachedMesh.rotation.y,o.attachedMesh.rotation.x,o.attachedMesh.rotation.z));var r=t.dragPlanePoint.subtract(o.attachedMesh.position).normalize(),s=f.subtract(o.attachedMesh.position).normalize(),a=e.Vector3.Cross(r,s),l=e.Vector3.Dot(r,s),c=Math.atan2(a.length(),l);if(_.copyFrom(i),m.copyFrom(i),o.updateGizmoRotationToMatchAttachedMesh&&(o.attachedMesh.rotationQuaternion.toRotationMatrix(p),m=e.Vector3.TransformCoordinates(_,p)),n.utilityLayerScene.activeCamera){var h=n.utilityLayerScene.activeCamera.position.subtract(o.attachedMesh.position);e.Vector3.Dot(h,m)>0&&(_.scaleInPlace(-1),m.scaleInPlace(-1))}e.Vector3.Dot(m,a)>0&&(c=-c);var u=!1;if(0!=o.snapDistance)if(v+=c,Math.abs(v)>o.snapDistance){var d=Math.floor(v/o.snapDistance);v%=o.snapDistance,c=o.snapDistance*d,u=!0}else c=0;var y=Math.sin(c/2),b=new e.Quaternion(_.x*y,_.y*y,_.z*y,Math.cos(c/2));o.updateGizmoRotationToMatchAttachedMesh?o.attachedMesh.rotationQuaternion.multiplyToRef(b,o.attachedMesh.rotationQuaternion):b.multiplyToRef(o.attachedMesh.rotationQuaternion,o.attachedMesh.rotationQuaternion),f.copyFrom(t.dragPlanePoint),u&&(g.snapDistance=c,o.onSnapObservable.notifyObservers(g))}})),o._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e,t){if(!o._customMeshSet){var i=e.pickInfo&&-1!=o._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh),r=i?a:s;o._rootMesh.getChildMeshes().forEach((function(e){e.material=r,e.color&&(e.color=r.emissiveColor)}))}})),o}return o(i,t),i.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),t.prototype.dispose.call(this)},i})(e.Gizmo);e.PlaneRotationGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i){void 0===i&&(i=e.UtilityLayerRenderer.DefaultUtilityLayer);var r=t.call(this,i)||this;return r.xGizmo=new e.AxisDragGizmo(new e.Vector3(1,0,0),e.Color3.Green().scale(.5),i),r.yGizmo=new e.AxisDragGizmo(new e.Vector3(0,1,0),e.Color3.Red().scale(.5),i),r.zGizmo=new e.AxisDragGizmo(new e.Vector3(0,0,1),e.Color3.Blue().scale(.5),i),r.attachedMesh=null,r}return o(i,t),Object.defineProperty(i.prototype,"attachedMesh",{set:function(e){this.xGizmo&&(this.xGizmo.attachedMesh=e,this.yGizmo.attachedMesh=e,this.zGizmo.attachedMesh=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!0,configurable:!0}),i.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose()},i.prototype.setCustomMesh=function(t){e.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")},i})(e.Gizmo);e.PositionGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i){void 0===i&&(i=e.UtilityLayerRenderer.DefaultUtilityLayer);var r=t.call(this,i)||this;return r.xGizmo=new e.PlaneRotationGizmo(new e.Vector3(1,0,0),e.Color3.Green().scale(.5),i),r.yGizmo=new e.PlaneRotationGizmo(new e.Vector3(0,1,0),e.Color3.Red().scale(.5),i),r.zGizmo=new e.PlaneRotationGizmo(new e.Vector3(0,0,1),e.Color3.Blue().scale(.5),i),r.attachedMesh=null,r}return o(i,t),Object.defineProperty(i.prototype,"attachedMesh",{set:function(e){this.xGizmo&&(this.xGizmo.attachedMesh=e,this.yGizmo.attachedMesh=e,this.zGizmo.attachedMesh=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!0,configurable:!0}),i.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose()},i.prototype.setCustomMesh=function(t){e.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")},i})(e.Gizmo);e.RotationGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i){void 0===i&&(i=e.UtilityLayerRenderer.DefaultUtilityLayer);var r=t.call(this,i)||this;return r.xGizmo=new e.AxisScaleGizmo(new e.Vector3(1,0,0),e.Color3.Green().scale(.5),i),r.yGizmo=new e.AxisScaleGizmo(new e.Vector3(0,1,0),e.Color3.Red().scale(.5),i),r.zGizmo=new e.AxisScaleGizmo(new e.Vector3(0,0,1),e.Color3.Blue().scale(.5),i),r.attachedMesh=null,r}return o(i,t),Object.defineProperty(i.prototype,"attachedMesh",{set:function(e){this.xGizmo&&(this.xGizmo.attachedMesh=e,this.yGizmo.attachedMesh=e,this.zGizmo.attachedMesh=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!0,configurable:!0}),i.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose()},i})(e.Gizmo);e.ScaleGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r){void 0===i&&(i=e.Color3.Gray()),void 0===r&&(r=e.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer);var n=t.call(this,r)||this;n._boundingDimensions=new e.Vector3(1,1,1),n._renderObserver=null,n._pointerObserver=null,n._scaleDragSpeed=.2,n._tmpQuaternion=new e.Quaternion,n._tmpVector=new e.Vector3(0,0,0),n.rotationSphereSize=.1,n.scaleBoxSize=.1,n.fixedDragMeshScreenSize=!1,n.fixedDragMeshScreenSizeDistanceFactor=10,n.onDragStartObservable=new e.Observable,n.onDragObservable=new e.Observable,n.onDragEndObservable=new e.Observable,n._existingMeshScale=new e.Vector3,n._updateScale=!1,n._anchorMesh=new e.AbstractMesh("anchor",r.utilityLayerScene);var o=new e.StandardMaterial("",r.utilityLayerScene);o.disableLighting=!0,o.emissiveColor=i;var s=new e.StandardMaterial("",r.utilityLayerScene);s.disableLighting=!0,s.emissiveColor=i.clone().add(new e.Color3(.2,.2,.2)),n._lineBoundingBox=new e.AbstractMesh("",r.utilityLayerScene),n._lineBoundingBox.rotationQuaternion=new e.Quaternion;var a=[];a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,0),new e.Vector3(n._boundingDimensions.x,0,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,0),new e.Vector3(0,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,0),new e.Vector3(0,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,0,0),new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,0,0),new e.Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,n._boundingDimensions.y,0),new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,n._boundingDimensions.y,0),new e.Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,n._boundingDimensions.z),new e.Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,n._boundingDimensions.z),new e.Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new e.Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new e.Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.forEach((function(t){t.color=i,t.position.addInPlace(new e.Vector3(-n._boundingDimensions.x/2,-n._boundingDimensions.y/2,-n._boundingDimensions.z/2)),t.isPickable=!1,n._lineBoundingBox.addChild(t)})),n._rootMesh.addChild(n._lineBoundingBox),n._rotateSpheresParent=new e.AbstractMesh("",r.utilityLayerScene),n._rotateSpheresParent.rotationQuaternion=new e.Quaternion;for(var l,c=this,h=0;h<12;h++)!(function(t){var i=e.MeshBuilder.CreateSphere("",{diameter:1},r.utilityLayerScene);i.rotationQuaternion=new e.Quaternion,i.material=o,l=new e.PointerDragBehavior({}),l.moveAttached=!1,l.updateDragPlane=!1,i.addBehavior(l);var s=new e.Vector3(1,0,0),a=0;l.onDragStartObservable.add((function(e){s.copyFrom(i.forward),a=0})),l.onDragObservable.add((function(i){if(n.onDragObservable.notifyObservers({}),n.attachedMesh){var r=s,o=i.dragPlaneNormal.scale(e.Vector3.Dot(i.dragPlaneNormal,r)),l=r.subtract(o).normalizeToNew(),c=-e.Vector3.Dot(l,i.delta);c=c/n._boundingDimensions.length()*n._anchorMesh.scaling.length(),n.attachedMesh.rotationQuaternion||(n.attachedMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(n.attachedMesh.rotation.y,n.attachedMesh.rotation.x,n.attachedMesh.rotation.z)),n._anchorMesh.rotationQuaternion||(n._anchorMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(n._anchorMesh.rotation.y,n._anchorMesh.rotation.x,n._anchorMesh.rotation.z)),a+=c,Math.abs(a)<=2*Math.PI&&(t>=8?e.Quaternion.RotationYawPitchRollToRef(0,0,c,n._tmpQuaternion):t>=4?e.Quaternion.RotationYawPitchRollToRef(c,0,0,n._tmpQuaternion):e.Quaternion.RotationYawPitchRollToRef(0,c,0,n._tmpQuaternion),n._anchorMesh.addChild(n.attachedMesh),n._anchorMesh.rotationQuaternion.multiplyToRef(n._tmpQuaternion,n._anchorMesh.rotationQuaternion),n._anchorMesh.removeChild(n.attachedMesh)),n.updateBoundingBox()}})),l.onDragStartObservable.add((function(){n.onDragStartObservable.notifyObservers({}),n._selectNode(i)})),l.onDragEndObservable.add((function(){n.onDragEndObservable.notifyObservers({}),n._selectNode(null)})),c._rotateSpheresParent.addChild(i)})(h);n._rootMesh.addChild(n._rotateSpheresParent),n._scaleBoxesParent=new e.AbstractMesh("",r.utilityLayerScene),n._scaleBoxesParent.rotationQuaternion=new e.Quaternion;for(var u=0;u<2;u++)for(var d=0;d<2;d++)for(var l,f=this,p=0;p<2;p++)!(function(){var t=e.MeshBuilder.CreateBox("",{size:1},r.utilityLayerScene);t.material=o;var i=new e.Vector3(0==u?-1:1,0==d?-1:1,0==p?-1:1);l=new e.PointerDragBehavior({dragAxis:i}),l.moveAttached=!1,t.addBehavior(l),l.onDragObservable.add((function(i){if(n.onDragObservable.notifyObservers({}),n.attachedMesh){var r=i.dragDistance/n._boundingDimensions.length()*n._anchorMesh.scaling.length(),o=new e.Vector3(r,r,r);o.scaleInPlace(n._scaleDragSpeed),n.updateBoundingBox(),t.absolutePosition.subtractToRef(n._anchorMesh.position,n._tmpVector),n._anchorMesh.position.subtractInPlace(n._tmpVector),n._anchorMesh.addChild(n.attachedMesh),n._anchorMesh.scaling.addInPlace(o),(n._anchorMesh.scaling.x<0||n._anchorMesh.scaling.y<0||n._anchorMesh.scaling.z<0)&&n._anchorMesh.scaling.subtractInPlace(o),n._anchorMesh.removeChild(n.attachedMesh)}})),l.onDragStartObservable.add((function(){n.onDragStartObservable.notifyObservers({}),n._selectNode(t)})),l.onDragEndObservable.add((function(){n.onDragEndObservable.notifyObservers({}),n._selectNode(null)})),f._scaleBoxesParent.addChild(t)})();n._rootMesh.addChild(n._scaleBoxesParent);var _=new Array;return n._pointerObserver=r.utilityLayerScene.onPointerObservable.add((function(e,t){_[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=_[e.event.pointerId]&&(_[e.event.pointerId].material=o,delete _[e.event.pointerId]):n._rotateSpheresParent.getChildMeshes().concat(n._scaleBoxesParent.getChildMeshes()).forEach((function(t){e.pickInfo&&e.pickInfo.pickedMesh==t&&(_[e.event.pointerId]=t,t.material=s)}))})),n._renderObserver=n.gizmoLayer.originalScene.onBeforeRenderObservable.add((function(){n.attachedMesh&&!n._existingMeshScale.equals(n.attachedMesh.scaling)&&n.updateBoundingBox()})),n.updateBoundingBox(),n}return o(i,t),i.prototype._attachedMeshChanged=function(e){e&&(this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),this.updateBoundingBox())},i.prototype._selectNode=function(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((function(t,i){t.isVisible=!e||t==e}))},i.prototype._recurseComputeWorld=function(e){var t=this;e.computeWorldMatrix(!0),e.getChildMeshes().forEach((function(e){t._recurseComputeWorld(e)}))},i.prototype.updateBoundingBox=function(){if(this._update(),this.attachedMesh){this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);var t=this.attachedMesh.getHierarchyBoundingVectors();t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this._recurseComputeWorld(this.attachedMesh)}for(var i=this._rotateSpheresParent.getChildMeshes(),r=0;r<3;r++)for(var n=0;n<2;n++)for(var o=0;o<2;o++){var s=4*r+2*n+o;if(0==r&&(i[s].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*n,this._boundingDimensions.z*o),i[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),i[s].lookAt(e.Vector3.Cross(e.Vector3.Right(),i[s].position.normalizeToNew()).normalizeToNew().add(i[s].position))),1==r&&(i[s].position.set(this._boundingDimensions.x*n,this._boundingDimensions.y/2,this._boundingDimensions.z*o),i[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),i[s].lookAt(e.Vector3.Cross(e.Vector3.Up(),i[s].position.normalizeToNew()).normalizeToNew().add(i[s].position))),2==r&&(i[s].position.set(this._boundingDimensions.x*n,this._boundingDimensions.y*o,this._boundingDimensions.z/2),i[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),i[s].lookAt(e.Vector3.Cross(e.Vector3.Forward(),i[s].position.normalizeToNew()).normalizeToNew().add(i[s].position))),this.fixedDragMeshScreenSize){this._rootMesh.computeWorldMatrix(),this._rotateSpheresParent.computeWorldMatrix(),i[s].computeWorldMatrix(),i[s].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var a=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;i[s].scaling.set(a,a,a)}else i[s].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}for(var l=this._scaleBoxesParent.getChildMeshes(),r=0;r<2;r++)for(var n=0;n<2;n++)for(var o=0;o<2;o++){var s=4*r+2*n+o;if(l[s])if(l[s].position.set(this._boundingDimensions.x*r,this._boundingDimensions.y*n,this._boundingDimensions.z*o),l[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize){this._rootMesh.computeWorldMatrix(),this._scaleBoxesParent.computeWorldMatrix(),l[s].computeWorldMatrix(),l[s].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var a=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;l[s].scaling.set(a,a,a)}else l[s].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize)}this.attachedMesh&&this._existingMeshScale.copyFrom(this.attachedMesh.scaling)},i.prototype.setEnabledRotationAxis=function(e){this._rotateSpheresParent.getChildMeshes().forEach((function(t,i){i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))}))},i.prototype.dispose=function(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),t.prototype.dispose.call(this)},i.MakeNotPickableAndWrapInBoundingBox=function(t){var i=function(e){e.isPickable=!1,e.getChildMeshes().forEach((function(e){i(e)}))};i(t),t.rotationQuaternion||(t.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(t.rotation.y,t.rotation.x,t.rotation.z));var r=t.position.clone(),n=t.rotationQuaternion.clone();t.rotationQuaternion.set(0,0,0,1),t.position.set(0,0,0);var o=e.MeshBuilder.CreateBox("box",{size:1},t.getScene()),s=t.getHierarchyBoundingVectors();return s.max.subtractToRef(s.min,o.scaling),o.position.set((s.max.x+s.min.x)/2,(s.max.y+s.min.y)/2,(s.max.z+s.min.z)/2),t.addChild(o),t.rotationQuaternion.copyFrom(n),t.position.copyFrom(r),t.removeChild(o),o.addChild(t),o.visibility=0,o},i.prototype.setCustomMesh=function(t){e.Tools.Error("Custom meshes are not supported on this gizmo")},i})(e.Gizmo);e.BoundingBoxGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){var i=this;this.scene=t,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObserver=null,this._attachedMesh=null,this._boundingBoxColor=e.Color3.FromHexString("#0984e3"),this._dragBehavior=new e.SixDofDragBehavior,this.attachableMeshes=null,this.usePointerToAttachGizmos=!0,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null},this._pointerObserver=t.onPointerObservable.add((function(t,r){if(i.usePointerToAttachGizmos&&t.type==e.PointerEventTypes.POINTERDOWN)if(t.pickInfo&&t.pickInfo.pickedMesh){var n=t.pickInfo.pickedMesh;if(null==i.attachableMeshes)for(;n&&null!=n.parent;)n=n.parent;else{var o=!1;i.attachableMeshes.forEach((function(e){n&&(n==e||n.isDescendantOf(e))&&(n=e,o=!0)})),o||(n=null)}n instanceof e.AbstractMesh&&i.attachToMesh(n)}else i.attachToMesh(null)}))}return t.prototype.attachToMesh=function(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this._dragBehavior),this._attachedMesh=e;for(var t in this.gizmos){var i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this._dragBehavior)},Object.defineProperty(t.prototype,"positionGizmoEnabled",{get:function(){return this._gizmosEnabled.positionGizmo},set:function(t){t?(this.gizmos.positionGizmo=this.gizmos.positionGizmo||new e.PositionGizmo,this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh=!1,this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedMesh=null),this._gizmosEnabled.positionGizmo=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationGizmoEnabled",{get:function(){return this._gizmosEnabled.rotationGizmo},set:function(t){t?(this.gizmos.rotationGizmo=this.gizmos.rotationGizmo||new e.RotationGizmo,this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh=!1,this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedMesh=null),this._gizmosEnabled.rotationGizmo=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleGizmoEnabled",{get:function(){return this._gizmosEnabled.scaleGizmo},set:function(t){t?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new e.ScaleGizmo,this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedMesh=null),this._gizmosEnabled.scaleGizmo=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"boundingBoxGizmoEnabled",{get:function(){return this._gizmosEnabled.boundingBoxGizmo},set:function(t){t?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new e.BoundingBoxGizmo(this._boundingBoxColor),this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh,this._attachedMesh&&(this._attachedMesh.removeBehavior(this._dragBehavior),this._attachedMesh.addBehavior(this._dragBehavior))):this.gizmos.boundingBoxGizmo&&(this.gizmos.boundingBoxGizmo.attachedMesh=null),this._gizmosEnabled.boundingBoxGizmo=t},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.scene.onPointerObservable.remove(this._pointerObserver);for(var e in this.gizmos){var t=this.gizmos[e];t&&t.dispose()}this._dragBehavior.detach(),this._gizmoLayer.dispose()},t})();e.GizmoManager=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){void 0===i&&(i=0),void 0===r&&(r=null),this.name=t,this.animations=new Array,this._positions=null,this._normals=null, +this._tangents=null,this.onInfluenceChanged=new e.Observable,this._animationPropertiesOverride=null,this._scene=r||e.Engine.LastCreatedScene,this.influence=i}return Object.defineProperty(t.prototype,"influence",{get:function(){return this._influence},set:function(e){if(this._influence!==e){var t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPositions",{get:function(){return!!this._positions},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasNormals",{get:function(){return!!this._normals},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasTangents",{get:function(){return!!this._tangents},enumerable:!0,configurable:!0}),t.prototype.setPositions=function(e){this._positions=e},t.prototype.getPositions=function(){return this._positions},t.prototype.setNormals=function(e){this._normals=e},t.prototype.getNormals=function(){return this._normals},t.prototype.setTangents=function(e){this._tangents=e},t.prototype.getTangents=function(){return this._tangents},t.prototype.serialize=function(){var t={};return t.name=this.name,t.influence=this.influence,t.positions=Array.prototype.slice.call(this.getPositions()),this.hasNormals&&(t.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(t.tangents=Array.prototype.slice.call(this.getTangents())),e.Animation.AppendSerializedAnimations(this,t),t},t.Parse=function(i){var r=new t(i.name,i.influence);if(r.setPositions(i.positions),i.normals&&r.setNormals(i.normals),i.tangents&&r.setTangents(i.tangents),i.animations)for(var n=0;n=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetObservable.splice(t,1)[0]),this._syncActiveTargets(!0))},t.prototype.serialize=function(){var e={};e.id=this.uniqueId,e.targets=[];for(var t=0,i=this._targets;tthis.capacity&&this._depth=2&&t.onControllersAttachedObservable.notifyObservers(t.controllers)}}}))},i})(e.FreeCamera);e.WebVRFreeCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("DeviceOrientationCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n){var o=t.call(this,i,r,n)||this;return o._quaternionCache=new e.Quaternion,o.inputs.addDeviceOrientation(),o}return o(i,t),i.prototype.getClassName=function(){return"DeviceOrientationCamera"},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)},i.prototype.resetToCurrentRotation=function(t){var i=this;void 0===t&&(t=e.Axis.Y),this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new e.Quaternion),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((function(e){t[e]?i._initialQuaternion[e]*=-1:i._initialQuaternion[e]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))},i})(e.FreeCamera);e.DeviceOrientationCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s){void 0===o&&(o=!0),void 0===s&&(s=e.VRCameraMetrics.GetDefault());var a=t.call(this,i,r,n)||this;return s.compensateDistortion=o,a.setCameraRigMode(e.Camera.RIG_MODE_VR,{vrCameraMetrics:s}),a}return o(i,t),i.prototype.getClassName=function(){return"VRDeviceOrientationFreeCamera"},i})(e.DeviceOrientationCamera);e.VRDeviceOrientationFreeCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera",(function(i,r){return function(){return new t(i,0,0,1,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s,a,l,c){void 0===l&&(l=!0),void 0===c&&(c=e.VRCameraMetrics.GetDefault());var h=t.call(this,i,r,n,o,s,a)||this;return c.compensateDistortion=l,h.setCameraRigMode(e.Camera.RIG_MODE_VR,{vrCameraMetrics:c}),h.inputs.addVRDeviceOrientation(),h}return o(i,t),i.prototype.getClassName=function(){return"VRDeviceOrientationArcRotateCamera"},i})(e.ArcRotateCamera);e.VRDeviceOrientationArcRotateCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s){void 0===o&&(o=!0),void 0===s&&(s=e.VRCameraMetrics.GetDefault());var a=t.call(this,i,r,n,o,s)||this;return a.inputs.addGamepad(),a}return o(i,t),i.prototype.getClassName=function(){return"VRDeviceOrientationGamepadCamera"},i})(e.VRDeviceOrientationFreeCamera);e.VRDeviceOrientationGamepadCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(i,r){if(void 0===r&&(r=null),this.scene=i,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=t._idCounter++,r)this._gazeTracker=r.clone("gazeTracker");else{this._gazeTracker=e.Mesh.CreateTorus("gazeTracker",.0035,.0025,20,i,!1),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;var n=new e.StandardMaterial("targetMat",i);n.specularColor=e.Color3.Black(),n.emissiveColor=new e.Color3(.7,.7,.7),n.backFaceCulling=!1,this._gazeTracker.material=n}}return t.prototype._getForwardRay=function(t){return new e.Ray(e.Vector3.Zero(),new e.Vector3(0,0,t))},t.prototype._selectionPointerDown=function(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})},t.prototype._selectionPointerUp=function(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1},t.prototype._activatePointer=function(){this._activePointer=!0},t.prototype._deactivatePointer=function(){this._activePointer=!1},t.prototype._updatePointerDistance=function(e){void 0===e&&(e=100)},t.prototype.dispose=function(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()},t._idCounter=0,t})(),i=(function(t){function i(i,r,n){var o=t.call(this,r,n)||this;o.webVRController=i,o._laserPointer=e.Mesh.CreateCylinder("laserPointer",1,.004,2e-4,20,1,r,!1);var s=new e.StandardMaterial("laserPointerMat",r);if(s.emissiveColor=new e.Color3(.7,.7,.7),s.alpha=.6,o._laserPointer.material=s,o._laserPointer.rotation.x=Math.PI/2,o._laserPointer.position.z=-.5,o._laserPointer.isVisible=!1,o._laserPointer.isPickable=!1,!i.mesh){var a=new e.Mesh("preloadControllerMesh",r),l=new e.Mesh(e.PoseEnabledController.POINTING_POSE,r);l.rotation.x=-.7,a.addChild(l),i.attachToMesh(a)}return o._setLaserPointerParent(i.mesh),o._meshAttachedObserver=i._meshAttachedObservable.add((function(e){o._setLaserPointerParent(e)})),o}return o(i,t),i.prototype._getForwardRay=function(e){return this.webVRController.getForwardRay(e)},i.prototype._activatePointer=function(){t.prototype._activatePointer.call(this),this._laserPointer.isVisible=!0},i.prototype._deactivatePointer=function(){t.prototype._deactivatePointer.call(this),this._laserPointer.isVisible=!1},i.prototype._setLaserPointerColor=function(e){this._laserPointer.material.emissiveColor=e},i.prototype._setLaserPointerParent=function(t){var i=function(e){e.isPickable=!1,e.getChildMeshes().forEach((function(e){i(e)}))};i(t);var r=t.getChildMeshes();this.webVRController._pointingPoseNode=null;for(var n=0;n=0){t=r[n],this.webVRController._pointingPoseNode=t;break}this._laserPointer.parent=t},i.prototype._updatePointerDistance=function(e){void 0===e&&(e=100),this._laserPointer.scaling.y=e,this._laserPointer.position.z=-e/2},i.prototype.dispose=function(){t.prototype.dispose.call(this),this._laserPointer.dispose(),this._meshAttachedObserver&&this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)},i})(t),r=(function(t){function i(e,i){var r=t.call(this,i)||this;return r.getCamera=e,r}return o(i,t),i.prototype._getForwardRay=function(t){var i=this.getCamera();return i?i.getForwardRay(t):new e.Ray(e.Vector3.Zero(),e.Vector3.Forward())},i})(t),n=(function(){function t(t,n){void 0===n&&(n={});var o=this;if(this.webVROptions=n,this._webVRsupported=!1,this._webVRready=!1,this._webVRrequesting=!1,this._webVRpresenting=!1,this._fullscreenVRpresenting=!1,this.onEnteringVRObservable=new e.Observable,this.onExitingVRObservable=new e.Observable,this.onControllerMeshLoadedObservable=new e.Observable,this._useCustomVRButton=!1,this._teleportationRequested=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._rotationAllowed=!0,this._teleportBackwardsVector=new e.Vector3(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new e.Vector3(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this.leftController=null,this.rightController=null,this.onNewMeshSelected=new e.Observable,this.onNewMeshPicked=new e.Observable,this.onBeforeCameraTeleport=new e.Observable,this.onAfterCameraTeleport=new e.Observable,this.onSelectedMeshUnselected=new e.Observable,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._interactionsRequested=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this._onResize=function(){o.moveButtonToBottomRight(),o._fullscreenVRpresenting&&o._webVRready&&o.exitVR()},this._onFullscreenChange=function(){void 0!==document.fullscreen?o._fullscreenVRpresenting=document.fullscreen:void 0!==document.mozFullScreen?o._fullscreenVRpresenting=document.mozFullScreen:void 0!==document.webkitIsFullScreen?o._fullscreenVRpresenting=document.webkitIsFullScreen:void 0!==document.msIsFullScreen?o._fullscreenVRpresenting=document.msIsFullScreen:void 0!==document.msFullscreenElement&&(o._fullscreenVRpresenting=document.msFullscreenElement),!o._fullscreenVRpresenting&&o._canvas&&(o.exitVR(),o._useCustomVRButton||(o._btnVR.style.top=o._canvas.offsetTop+o._canvas.offsetHeight-70+"px",o._btnVR.style.left=o._canvas.offsetLeft+o._canvas.offsetWidth-100+"px"))},this.beforeRender=function(){o.leftController&&o.leftController._activePointer&&o._castRayAndSelectObject(o.leftController),o.rightController&&o.rightController._activePointer&&o._castRayAndSelectObject(o.rightController),o._noControllerIsActive?o._castRayAndSelectObject(o._cameraGazer):o._cameraGazer._gazeTracker.isVisible=!1},this._onNewGamepadConnected=function(t){if(t.type!==e.Gamepad.POSE_ENABLED)t.leftStick&&t.onleftstickchanged((function(e){o._teleportationInitialized&&o.teleportationEnabled&&(!o.leftController&&!o.rightController||o.leftController&&!o.leftController._activePointer&&o.rightController&&!o.rightController._activePointer)&&(o._checkTeleportWithRay(e,o._cameraGazer),o._checkTeleportBackwards(e,o._cameraGazer))})),t.rightStick&&t.onrightstickchanged((function(e){o._teleportationInitialized&&o._checkRotate(e,o._cameraGazer)})),t.type===e.Gamepad.XBOX&&(t.onbuttondown((function(t){o._interactionsEnabled&&t===e.Xbox360Button.A&&o._cameraGazer._selectionPointerDown()})),t.onbuttonup((function(t){o._interactionsEnabled&&t===e.Xbox360Button.A&&o._cameraGazer._selectionPointerUp()})));else{var r=t,n=new i(r,o._scene,o._cameraGazer._gazeTracker);"right"===r.hand||o.leftController&&o.leftController.webVRController!=r?o.rightController=n:o.leftController=n,o._tryEnableInteractionOnController(n)}},this._tryEnableInteractionOnController=function(e){o._interactionsRequested&&!e._interactionsEnabled&&o._enableInteractionOnController(e),o._teleportationRequested&&!e._teleportationEnabled&&o._enableTeleportationOnController(e)},this._onNewGamepadDisconnected=function(t){t instanceof e.WebVRController&&("left"===t.hand&&null!=o.leftController&&(o.leftController.dispose(),o.leftController=null),"right"===t.hand&&null!=o.rightController&&(o.rightController.dispose(),o.rightController=null))},this._workingVector=e.Vector3.Zero(),this._workingQuaternion=e.Quaternion.Identity(),this._workingMatrix=e.Matrix.Identity(),this._scene=t,this._canvas=t.getEngine().getRenderingCanvas(),void 0===n.createFallbackVRDeviceOrientationFreeCamera&&(n.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===n.createDeviceOrientationCamera&&(n.createDeviceOrientationCamera=!0),void 0===n.laserToggle&&(n.laserToggle=!0),void 0===n.defaultHeight&&(n.defaultHeight=1.7),n.useCustomVRButton&&(this._useCustomVRButton=!0,n.customVRButton&&(this._btnVR=n.customVRButton)),n.rayLength&&(this._rayLength=n.rayLength),this._defaultHeight=n.defaultHeight,n.positionScale&&(this._rayLength*=n.positionScale,this._defaultHeight*=n.positionScale),this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new e.Vector3(0,this._defaultHeight,0),n.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new e.DeviceOrientationCamera("deviceOrientationVRHelper",this._position.clone(),t),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof e.TargetCamera&&this._scene.activeCamera.rotation)){var s=this._scene.activeCamera;s.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(s.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.Quaternion.RotationYawPitchRoll(s.rotation.y,s.rotation.x,s.rotation.z)),this._deviceOrientationCamera.rotation=s.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._canvas&&this._scene.activeCamera.attachControl(this._canvas)}else this._existingCamera=this._scene.activeCamera;if(n.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new e.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper",this._position,this._scene)),this._webVRCamera=new e.WebVRFreeCamera("WebVRHelper",this._position,this._scene,n),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new r(function(){return o.currentVRCamera},t),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";var a=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";a+=".babylonVRicon.vrdisplaypresenting { display: none; }";var l=document.createElement("style");l.appendChild(document.createTextNode(a)),document.getElementsByTagName("head")[0].appendChild(l),this.moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(function(){o.isInVRMode?o.exitVR():o.enterVR()})),window.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("mozfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("msfullscreenchange",this._onFullscreenChange,!1),document.onmsfullscreenchange=this._onFullscreenChange,n.createFallbackVRDeviceOrientationFreeCamera?this.displayVRButton():this._scene.getEngine().onVRDisplayChangedObservable.add((function(e){e.vrDisplay&&o.displayVRButton()})),this._onKeyDown=function(e){27===e.keyCode&&o.isInVRMode&&o.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((function(e,t){o.isInVRMode&&(o.exitVR(),o._fullscreenVRpresenting&&o._scene.getEngine().switchFullscreen(!0))}),e.PointerEventTypes.POINTERDOUBLETAP,!1),this._onVRDisplayChanged=function(e){return o.onVRDisplayChanged(e)},this._onVrDisplayPresentChange=function(){return o.onVrDisplayPresentChange()},this._onVRRequestPresentStart=function(){o._webVRrequesting=!0,o.updateButtonVisibility()},this._onVRRequestPresentComplete=function(e){o._webVRrequesting=!1,o.updateButtonVisibility()},t.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged),t.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),t.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),window.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),t.onDisposeObservable.add((function(){o.dispose()})),this._webVRCamera.onControllerMeshLoadedObservable.add((function(e){return o._onDefaultMeshLoaded(e)})),this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),this.updateButtonVisibility(),this._circleEase=new e.CircleEase,this._circleEase.setEasingMode(e.EasingFunction.EASINGMODE_EASEINOUT),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes})}return Object.defineProperty(t.prototype,"onEnteringVR",{get:function(){return this.onEnteringVRObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onExitingVR",{get:function(){return this.onExitingVRObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onControllerMeshLoaded",{get:function(){return this.onControllerMeshLoadedObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"teleportationTarget",{get:function(){return this._teleportationTarget},set:function(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gazeTrackerMesh",{get:function(){return this._cameraGazer._gazeTracker},set:function(e){e&&(this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker",this.leftController&&(this.leftController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")),this.rightController&&(this.rightController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayGaze",{get:function(){return this._displayGaze},set:function(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1,this.leftController&&(this.leftController._gazeTracker.isVisible=!1),this.rightController&&(this.rightController._gazeTracker.isVisible=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayLaserPointer",{get:function(){return this._displayLaserPointer},set:function(e){this._displayLaserPointer=e,e?(this.rightController&&this.rightController._activatePointer(),this.leftController&&this.leftController._activatePointer()):(this.rightController&&(this.rightController._deactivatePointer(),this.rightController._gazeTracker.isVisible=!1),this.leftController&&(this.leftController._deactivatePointer(),this.leftController._gazeTracker.isVisible=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"deviceOrientationCamera",{get:function(){return this._deviceOrientationCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentVRCamera",{get:function(){return this._webVRready?this._webVRCamera:this._scene.activeCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"webVRCamera",{get:function(){return this._webVRCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vrDeviceOrientationCamera",{get:function(){return this._vrDeviceOrientationCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_teleportationRequestInitiated",{get:function(){return this._cameraGazer._teleportationRequestInitiated||null!==this.leftController&&this.leftController._teleportationRequestInitiated||null!==this.rightController&&this.rightController._teleportationRequestInitiated},enumerable:!0,configurable:!0}),t.prototype._onDefaultMeshLoaded=function(t){this.leftController&&this.leftController.webVRController==t&&t.mesh&&this.leftController._setLaserPointerParent(t.mesh),this.rightController&&this.rightController.webVRController==t&&t.mesh&&this.rightController._setLaserPointerParent(t.mesh);try{this.onControllerMeshLoadedObservable.notifyObservers(t)}catch(t){e.Tools.Warn("Error in your custom logic onControllerMeshLoaded: "+t)}},Object.defineProperty(t.prototype,"isInVRMode",{get:function(){return this._webVRpresenting||this._fullscreenVRpresenting},enumerable:!0,configurable:!0}),t.prototype.onVrDisplayPresentChange=function(){var t=this._scene.getEngine().getVRDevice();if(t){var i=this._webVRpresenting;this._webVRpresenting=t.isPresenting,i&&!this._webVRpresenting&&this.exitVR()}else e.Tools.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");this.updateButtonVisibility()},t.prototype.onVRDisplayChanged=function(e){this._webVRsupported=e.vrSupported,this._webVRready=!!e.vrDisplay,this._webVRpresenting=e.vrDisplay&&e.vrDisplay.isPresenting,this.updateButtonVisibility()},t.prototype.moveButtonToBottomRight=function(){this._canvas&&!this._useCustomVRButton&&(this._btnVR.style.top=this._canvas.offsetTop+this._canvas.offsetHeight-70+"px",this._btnVR.style.left=this._canvas.offsetLeft+this._canvas.offsetWidth-100+"px")},t.prototype.displayVRButton=function(){this._useCustomVRButton||this._btnVRDisplayed||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)},t.prototype.updateButtonVisibility=function(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode?this._btnVR.className+=" vrdisplaypresenting":(this._webVRready&&(this._btnVR.className+=" vrdisplayready"),this._webVRsupported&&(this._btnVR.className+=" vrdisplaysupported"),this._webVRrequesting&&(this._btnVR.className+=" vrdisplayrequesting")))},t.prototype.enterVR=function(){if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(t){e.Tools.Warn("Error in your custom logic onEnteringVR: "+t)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this._existingCamera=this._scene.activeCamera),this._webVRrequesting||(this._webVRready?this._webVRpresenting||(this._webVRCamera.position=this._position,this._scene.activeCamera=this._webVRCamera):this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().switchFullscreen(!0),this.updateButtonVisibility()),this._scene.activeCamera&&this._canvas&&this._scene.activeCamera.attachControl(this._canvas),this._interactionsEnabled&&this._scene.registerBeforeRender(this.beforeRender))},t.prototype.exitVR=function(){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(t){e.Tools.Warn("Error in your custom logic onExitingVR: "+t)}this._webVRpresenting&&this._scene.getEngine().disableVR(),this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._canvas&&this._scene.activeCamera.attachControl(this._canvas)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera),this.updateButtonVisibility(),this._interactionsEnabled&&this._scene.unregisterBeforeRender(this.beforeRender),this._scene.getEngine().resize()},Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)},enumerable:!0,configurable:!0}),t.prototype.enableInteractions=function(){var e=this;this._interactionsEnabled||(this._interactionsRequested=!0,this.leftController&&this._enableInteractionOnController(this.leftController),this.rightController&&this._enableInteractionOnController(this.rightController),this.raySelectionPredicate=function(e){return e.isVisible&&e.isPickable},this.meshSelectionPredicate=function(e){return!0},this._raySelectionPredicate=function(t){return!!(e._isTeleportationFloor(t)||-1===t.name.indexOf("gazeTracker")&&-1===t.name.indexOf("teleportationTarget")&&-1===t.name.indexOf("torusTeleportation"))&&e.raySelectionPredicate(t)},this._interactionsEnabled=!0)},Object.defineProperty(t.prototype,"_noControllerIsActive",{get:function(){return!(this.leftController&&this.leftController._activePointer||this.rightController&&this.rightController._activePointer)},enumerable:!0,configurable:!0}),t.prototype._isTeleportationFloor=function(e){for(var t=0;t-1||this._floorMeshesCollection.push(e))},t.prototype.removeFloorMesh=function(e){if(this._floorMeshesCollection){var t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}},t.prototype.enableTeleportation=function(t){if(void 0===t&&(t={}),!this._teleportationInitialized){this._teleportationRequested=!0,this.enableInteractions(),t.floorMeshName&&(this._floorMeshName=t.floorMeshName),t.floorMeshes&&(this._floorMeshesCollection=t.floorMeshes),null!=this.leftController&&this._enableTeleportationOnController(this.leftController),null!=this.rightController&&this._enableTeleportationOnController(this.rightController);var i=new e.ImageProcessingConfiguration;i.vignetteColor=new e.Color4(0,0,0,0),i.vignetteEnabled=!0,this._postProcessMove=new e.ImageProcessingPostProcess("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,i),this._webVRCamera.detachPostProcess(this._postProcessMove),this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&(this._createTeleportationCircles(),this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))}},t.prototype._enableInteractionOnController=function(e){var t=this;e.webVRController.mesh&&(e._interactionsEnabled=!0,e._activatePointer(),this.webVROptions.laserToggle&&e.webVRController.onMainButtonStateChangedObservable.add((function(i){t._displayLaserPointer&&1===i.value&&(e._activePointer?e._deactivatePointer():e._activatePointer(),t.displayGaze&&(e._gazeTracker.isVisible=e._activePointer))})),e.webVRController.onTriggerStateChangedObservable.add((function(i){var r=e;t._noControllerIsActive&&(r=t._cameraGazer),r._pointerDownOnMeshAsked?i.valuet._padSensibilityUp&&r._selectionPointerDown()})))},t.prototype._checkTeleportWithRay=function(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))},t.prototype._checkTeleportBackwards=function(t,i){if(!i._teleportationRequestInitiated)if(t.y>this._padSensibilityUp&&i._dpadPressed){if(!i._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;var r=e.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),n=this.currentVRCamera.position;this.currentVRCamera.devicePosition&&this.currentVRCamera.deviceRotationQuaternion&&(r=this.currentVRCamera.deviceRotationQuaternion,n=this.currentVRCamera.devicePosition),r.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,e.Quaternion.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),e.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);var o=new e.Ray(n,this._workingVector),s=this._scene.pickWithRay(o,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this._teleportCamera(s.pickedPoint),i._teleportationBackRequestInitiated=!0}}else i._teleportationBackRequestInitiated=!1},t.prototype._enableTeleportationOnController=function(t){var i=this;t.webVRController.mesh&&(t._interactionsEnabled||this._enableInteractionOnController(t),t._interactionsEnabled=!0,t._teleportationEnabled=!0,t.webVRController.controllerType===e.PoseEnabledControllerType.VIVE&&(t._dpadPressed=!1,t.webVRController.onPadStateChangedObservable.add((function(e){t._dpadPressed=e.pressed,t._dpadPressed||(t._rotationLeftAsked=!1,t._rotationRightAsked=!1,t._teleportationBackRequestInitiated=!1)}))),t.webVRController.onPadValuesChangedObservable.add((function(e){i.teleportationEnabled&&(i._checkTeleportBackwards(e,t),i._checkTeleportWithRay(e,t)),i._checkRotate(e,t)})))},t.prototype._createTeleportationCircles=function(){this._teleportationTarget=e.Mesh.CreateGround("teleportationTarget",2,2,2,this._scene),this._teleportationTarget.isPickable=!1;var t=new e.DynamicTexture("DynamicTexture",512,this._scene,!0);t.hasAlpha=!0;var i=t.getContext();i.beginPath(),i.arc(256,256,200,0,2*Math.PI,!1),i.fillStyle=this._teleportationFillColor,i.fill(),i.lineWidth=10,i.strokeStyle=this._teleportationBorderColor,i.stroke(),i.closePath(),t.update();var r=new e.StandardMaterial("TextPlaneMaterial",this._scene);r.diffuseTexture=t,this._teleportationTarget.material=r;var n=e.Mesh.CreateTorus("torusTeleportation",.75,.1,25,this._scene,!1);n.isPickable=!1,n.parent=this._teleportationTarget;var o=new e.Animation("animationInnerCircle","position.y",30,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CYCLE),s=[];s.push({frame:0,value:0}),s.push({frame:30,value:.4}),s.push({frame:60,value:0}),o.setKeys(s);var a=new e.SineEase;a.setEasingMode(e.EasingFunction.EASINGMODE_EASEINOUT),o.setEasingFunction(a),n.animations=[],n.animations.push(o),this._scene.beginAnimation(n,0,60,!0),this._hideTeleportationTarget()},t.prototype._displayTeleportationTarget=function(){this._teleportActive=!0,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!0,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!0))},t.prototype._hideTeleportationTarget=function(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))},t.prototype._rotateCamera=function(t){var i=this;if(this.currentVRCamera instanceof e.FreeCamera){t?this._rotationAngle++:this._rotationAngle--, +this.currentVRCamera.animations=[];var r=e.Quaternion.FromRotationMatrix(e.Matrix.RotationY(Math.PI/4*this._rotationAngle)),n=new e.Animation("animationRotation","rotationQuaternion",90,e.Animation.ANIMATIONTYPE_QUATERNION,e.Animation.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),o.push({frame:6,value:r}),n.setKeys(o),n.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(n),this._postProcessMove.animations=[];var s=new e.Animation("animationPP","vignetteWeight",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:4}),a.push({frame:6,value:0}),s.setKeys(a),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);var l=new e.Animation("animationPP2","vignetteStretch",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),c=[];c.push({frame:0,value:0}),c.push({frame:3,value:10}),c.push({frame:6,value:0}),l.setKeys(c),l.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,6,!1,1,(function(){i._webVRCamera.detachPostProcess(i._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}},t.prototype._moveTeleportationSelectorTo=function(t,i,r){if(t.pickedPoint){i._teleportationRequestInitiated&&(this._displayTeleportationTarget(),this._haloCenter.copyFrom(t.pickedPoint),this._teleportationTarget.position.copyFrom(t.pickedPoint));var n=this._convertNormalToDirectionOfRay(t.getNormal(!0,!1),r);if(n){var o=e.Vector3.Cross(e.Axis.Y,n),s=e.Vector3.Cross(n,o);e.Vector3.RotationFromAxisToRef(s,n,o,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}},t.prototype._teleportCamera=function(t){var i=this;if(this.currentVRCamera instanceof e.FreeCamera){this.webVRCamera.leftCamera?(this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),this._workingVector.subtractInPlace(this.webVRCamera.position),t.subtractToRef(this._workingVector,this._workingVector)):this._workingVector.copyFrom(t),this.isInVRMode?this._workingVector.y+=this.webVRCamera.deviceDistanceToRoomGround()*this._webVRCamera.deviceScaleFactor:this._workingVector.y+=this._defaultHeight,this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this.currentVRCamera.animations=[];var r=new e.Animation("animationCameraTeleportation","position",90,e.Animation.ANIMATIONTYPE_VECTOR3,e.Animation.ANIMATIONLOOPMODE_CONSTANT),n=[{frame:0,value:this.currentVRCamera.position},{frame:11,value:this._workingVector}];r.setKeys(n),r.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];var o=new e.Animation("animationPP","vignetteWeight",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:0}),s.push({frame:5,value:8}),s.push({frame:11,value:0}),o.setKeys(s),this._postProcessMove.animations.push(o);var a=new e.Animation("animationPP2","vignetteStretch",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:5,value:10}),l.push({frame:11,value:0}),a.setKeys(l),this._postProcessMove.animations.push(a),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,11,!1,1,(function(){i._webVRCamera.detachPostProcess(i._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,11,!1,1,(function(){i.onAfterCameraTeleport.notifyObservers(i._workingVector)})),this._hideTeleportationTarget()}},t.prototype._convertNormalToDirectionOfRay=function(t,i){if(t){Math.acos(e.Vector3.Dot(t,i.direction))i.halfWidth,t&&this._joystickPointerID<0?(this._joystickPointerID=e.pointerId,this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone(),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):i._globalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))},i.prototype._onPointerMove=function(e){if(this._joystickPointerID==e.pointerId){this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY,this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos);var i=this.reverseLeftRight?-1:1,r=i*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,r));break;case t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,r));break;case t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,r))}var n=this.reverseUpDown?1:-1,o=n*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,o));break;case t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,o));break;case t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,o))}}else{var s=this._touches.get(e.pointerId.toString());s&&(s.x=e.clientX,s.y=e.clientY)}},i.prototype._onPointerUp=function(e){if(this._joystickPointerID==e.pointerId)i.vjCanvasContext.clearRect(this._joystickPointerStartPos.x-64,this._joystickPointerStartPos.y-64,128,128),i.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x-42,this._joystickPreviousPointerPos.y-42,84,84),this._joystickPointerID=-1,this.pressed=!1;else{var t=this._touches.get(e.pointerId.toString());t&&i.vjCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(e.pointerId.toString())},i.prototype.setJoystickColor=function(e){this._joystickColor=e},i.prototype.setActionOnTouch=function(e){this._action=e},i.prototype.setAxisForLeftRight=function(e){switch(e){case t.X:case t.Y:case t.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=t.X}},i.prototype.setAxisForUpDown=function(e){switch(e){case t.X:case t.Y:case t.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=t.Y}},i.prototype._drawVirtualJoystick=function(){var e=this;this.pressed&&this._touches.forEach((function(t,r){r.pointerId===e._joystickPointerID?(i.vjCanvasContext.clearRect(e._joystickPointerStartPos.x-64,e._joystickPointerStartPos.y-64,128,128),i.vjCanvasContext.clearRect(e._joystickPreviousPointerPos.x-42,e._joystickPreviousPointerPos.y-42,84,84),i.vjCanvasContext.beginPath(),i.vjCanvasContext.lineWidth=6,i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.arc(e._joystickPointerStartPos.x,e._joystickPointerStartPos.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.lineWidth=2,i.vjCanvasContext.arc(e._joystickPointerStartPos.x,e._joystickPointerStartPos.y,60,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.arc(e._joystickPointerPos.x,e._joystickPointerPos.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),e._joystickPreviousPointerPos=e._joystickPointerPos.clone()):(i.vjCanvasContext.clearRect(r.prevX-44,r.prevY-44,88,88),i.vjCanvasContext.beginPath(),i.vjCanvasContext.fillStyle="white",i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle="red",i.vjCanvasContext.lineWidth=6,i.vjCanvasContext.arc(r.x,r.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),r.prevX=r.x,r.prevY=r.y)})),requestAnimationFrame((function(){e._drawVirtualJoystick()}))},i.prototype.releaseCanvas=function(){i.vjCanvas&&(i.vjCanvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),i.vjCanvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),i.vjCanvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),i.vjCanvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(i.vjCanvas),i.vjCanvas=null)},i._globalJoystickIndex=0,i})();e.VirtualJoystick=i})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VirtualJoysticksCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addVirtualJoystick(),n}return o(t,e),t.prototype.getClassName=function(){return"VirtualJoysticksCamera"},t})(e.FreeCamera);e.VirtualJoysticksCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.prototype.getLeftJoystick=function(){return this._leftjoystick},t.prototype.getRightJoystick=function(){return this._rightjoystick},t.prototype.checkInputs=function(){if(this._leftjoystick){var t=this.camera,i=50*t._computeLocalCameraSpeed(),r=e.Matrix.RotationYawPitchRoll(t.rotation.y,t.rotation.x,0),n=e.Vector3.TransformCoordinates(new e.Vector3(this._leftjoystick.deltaPosition.x*i,this._leftjoystick.deltaPosition.y*i,this._leftjoystick.deltaPosition.z*i),r);t.cameraDirection=t.cameraDirection.add(n),t.cameraRotation=t.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}},t.prototype.attachControl=function(t,i){this._leftjoystick=new e.VirtualJoystick(!0),this._leftjoystick.setAxisForUpDown(e.JoystickAxis.Z),this._leftjoystick.setAxisForLeftRight(e.JoystickAxis.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new e.VirtualJoystick(!1),this._rightjoystick.setAxisForUpDown(e.JoystickAxis.X),this._rightjoystick.setAxisForLeftRight(e.JoystickAxis.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")},t.prototype.detachControl=function(e){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()},t.prototype.getClassName=function(){return"FreeCameraVirtualJoystickInput"},t.prototype.getSimpleName=function(){return"virtualJoystick"},t})();e.FreeCameraVirtualJoystickInput=t,e.CameraInputTypes.FreeCameraVirtualJoystickInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i){this.quality=e,this.distance=t,this.optimizeMesh=i}return e})();e.SimplificationSettings=t;var i=(function(){function t(){this.running=!1,this._simplificationArray=[]}return t.prototype.addTask=function(e){this._simplificationArray.push(e)},t.prototype.executeNext=function(){var e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1},t.prototype.runSimplification=function(t){var i=this;if(t.parallelProcessing)t.settings.forEach((function(e){i.getSimplifier(t).simplify(e,(function(r){t.mesh.addLODLevel(e.distance,r),r.isVisible=!0,e.quality===t.settings[t.settings.length-1].quality&&t.successCallback&&t.successCallback(),i.executeNext()}))}));else{var r=this.getSimplifier(t),n=function(e,i){r.simplify(e,(function(r){t.mesh.addLODLevel(e.distance,r),r.isVisible=!0,i()}))};e.AsyncLoop.Run(t.settings.length,(function(e){n(t.settings[e.index],(function(){e.executeNext()}))}),(function(){t.successCallback&&t.successCallback(),i.executeNext()}))}},t.prototype.getSimplifier=function(e){switch(e.simplificationType){case r.QUADRATIC:default:return new l(e.mesh)}},t})();e.SimplificationQueue=i;var r;!(function(e){e[e.QUADRATIC=0]="QUADRATIC"})(r=e.SimplificationType||(e.SimplificationType={}));var n=(function(){function e(e){this.vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}return e})();e.DecimationTriangle=n;var o=(function(){function e(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new s,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}return e.prototype.updatePosition=function(e){this.position.copyFrom(e)},e})();e.DecimationVertex=o;var s=(function(){function e(e){this.data=new Array(10);for(var t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}return e.prototype.det=function(e,t,i,r,n,o,s,a,l){return this.data[e]*this.data[n]*this.data[l]+this.data[i]*this.data[r]*this.data[a]+this.data[t]*this.data[o]*this.data[s]-this.data[i]*this.data[n]*this.data[s]-this.data[e]*this.data[o]*this.data[a]-this.data[t]*this.data[r]*this.data[l]},e.prototype.addInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e.data[t]},e.prototype.addArrayInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e[t]},e.prototype.add=function(t){for(var i=new e,r=0;r<10;++r)i.data[r]=this.data[r]+t.data[r];return i},e.FromData=function(t,i,r,n){return new e(e.DataFromNumbers(t,i,r,n))},e.DataFromNumbers=function(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]},e})();e.QuadraticMatrix=s;var a=(function(){function e(e,t){this.vertexId=e,this.triangleId=t}return e})();e.Reference=a;var l=(function(){function t(t){this._mesh=t,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=e.Epsilon}return t.prototype.simplify=function(t,i){var r=this;this.initDecimatedMesh(),e.AsyncLoop.Run(this._mesh.subMeshes.length,(function(e){r.initWithMesh(e.index,(function(){r.runDecimation(t,e.index,(function(){e.executeNext()}))}),t.optimizeMesh)}),(function(){setTimeout((function(){i(r._reconstructedMesh)}),0)}))},t.prototype.runDecimation=function(t,i,r){var n=this,o=~~(this.triangles.length*t.quality),s=0,a=this.triangles.length,l=function(t,i){setTimeout((function(){t%5==0&&n.updateMesh(0===t);for(var r=0;rl||r.deleted||r.isDirty))for(var o=0;o<3;++o)if(r.error[o]>0,d,(function(){var t=function(e){if(l){var t=c.indexStart/3+e,i=3*t,r=l[i+0],o=l[i+1],a=l[i+2],h=s.vertices[u[r-c.verticesStart]],d=s.vertices[u[o-c.verticesStart]],f=s.vertices[u[a-c.verticesStart]],p=new n([h,d,f]);p.originalOffset=i,s.triangles.push(p)}};e.AsyncLoop.SyncAsyncForLoop(c.indexCount/3,s.syncIterations,t,(function(){s.init(i)}))}))},t.prototype.init=function(t){var i=this,r=function(t){var r=i.triangles[t];r.normal=e.Vector3.Cross(r.vertices[1].position.subtract(r.vertices[0].position),r.vertices[2].position.subtract(r.vertices[0].position)).normalize();for(var n=0;n<3;n++)r.vertices[n].q.addArrayInPlace(s.DataFromNumbers(r.normal.x,r.normal.y,r.normal.z,-e.Vector3.Dot(r.normal,r.vertices[0].position)))};e.AsyncLoop.SyncAsyncForLoop(this.triangles.length,this.syncIterations,r,(function(){var r=function(e){for(var t=i.triangles[e],r=0;r<3;++r)t.error[r]=i.calculateError(t.vertices[r],t.vertices[(r+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])};e.AsyncLoop.SyncAsyncForLoop(i.triangles.length,i.syncIterations,r,(function(){t()}))}))},t.prototype.reconstructMesh=function(t){var i,r=[];for(i=0;i0&&this._reconstructedMesh.setVerticesData(e.VertexBuffer.UVKind,l),c.length>0&&this._reconstructedMesh.setVerticesData(e.VertexBuffer.ColorKind,c);var b=this._mesh.subMeshes[t];t>0&&(this._reconstructedMesh.subMeshes=[],g.forEach((function(t){e.SubMesh.AddToMesh(t.materialIndex,t.verticesStart,t.verticesCount,t.indexStart,t.indexCount,t.getMesh())})),e.SubMesh.AddToMesh(b.materialIndex,m,f,_,3*r.length,this._reconstructedMesh))},t.prototype.initDecimatedMesh=function(){this._reconstructedMesh=new e.Mesh(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId},t.prototype.isFlipped=function(t,i,r,n,o,s){for(var a=0;a.999)return!0;var p=e.Vector3.Cross(d,f).normalize();if(n[a]=!1,e.Vector3.Dot(p,l.normal)<.2)return!0}else n[a]=!0,s.push(l)}}return!1},t.prototype.updateTriangles=function(e,t,i,r){for(var n=r,o=0;othis.maximumSize&&(n.scale(this.step),i=!1)}}return i},t})(t);e.TextureOptimization=i;var r=(function(e){function t(t,i,r){void 0===t&&(t=0),void 0===i&&(i=2),void 0===r&&(r=.25);var n=e.call(this,t)||this;return n.priority=t,n.maximumScale=i,n.step=r,n._currentScale=-1,n._directionOffset=1,n}return o(t,e),t.prototype.getDescription=function(){return"Setting hardware scaling level to "+this._currentScale},t.prototype.apply=function(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step, +e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale},t})(t);e.HardwareScalingOptimization=r;var n=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning shadows on/off"},t.prototype.apply=function(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0},t})(t);e.ShadowsOptimization=n;var s=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning post-processes on/off"},t.prototype.apply=function(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0},t})(t);e.PostProcessesOptimization=s;var a=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning lens flares on/off"},t.prototype.apply=function(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0},t})(t);e.LensFlaresOptimization=a;var l=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"},t.prototype.apply=function(e,t){return!this.onApply||this.onApply(e,t)},t})(t);e.CustomOptimization=l;var c=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning particles on/off"},t.prototype.apply=function(e,t){return e.particlesEnabled=t.isInImprovementMode,!0},t})(t);e.ParticlesOptimization=c;var h=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning render targets off"},t.prototype.apply=function(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0},t})(t);e.RenderTargetsOptimization=h;var u=(function(t){function i(){var i=null!==t&&t.apply(this,arguments)||this;return i._canBeMerged=function(t){if(!(t instanceof e.Mesh))return!1;var i=t;return!i.isDisposed()&&(!(!i.isVisible||!i.isEnabled())&&(!(i.instances.length>0)&&(!i.skeleton&&!i.hasLODLevels)))},i}return o(i,t),Object.defineProperty(i,"UpdateSelectionTree",{get:function(){return i._UpdateSelectionTree},set:function(e){i._UpdateSelectionTree=e},enumerable:!0,configurable:!0}),i.prototype.getDescription=function(){return"Merging similar meshes together"},i.prototype.apply=function(t,r,n){for(var o=t.meshes.slice(0),s=o.length,a=0;a=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);for(var r=!0,n=!0,o=0;o4&&(n.push(e.VertexBuffer.MatricesIndicesExtraKind),n.push(e.VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton?o.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),i&&(r.push("#define INSTANCES"),n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"));var a=r.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("outline",n,["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant"],["diffuseSampler"],a)),this._effect.isReady()},t})();e.OutlineRenderer=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this.edges=new Array,this.edgesConnectedCount=0}return e})(),i=(function(){function i(e,t,i){void 0===t&&(t=.95),void 0===i&&(i=!1),this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this._source=e,this._checkVerticesInsteadOfIndices=i,this._epsilon=t,this._prepareRessources(),this._generateEdgesLines()}return i.prototype._prepareRessources=function(){this._lineShader||(this._lineShader=new e.ShaderMaterial("lineShader",this._source.getScene(),"line",{attributes:["position","normal"],uniforms:["worldViewProjection","color","width","aspectRatio"]}),this._lineShader.disableDepthWrite=!0,this._lineShader.backFaceCulling=!1)},i.prototype._rebuild=function(){var t=this._buffers[e.VertexBuffer.PositionKind];t&&t._rebuild(),(t=this._buffers[e.VertexBuffer.NormalKind])&&t._rebuild();var i=this._source.getScene(),r=i.getEngine();this._ib=r.createIndexBuffer(this._linesIndices)},i.prototype.dispose=function(){var t=this._buffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._buffers[e.VertexBuffer.PositionKind]=null),t=this._buffers[e.VertexBuffer.NormalKind],t&&(t.dispose(),this._buffers[e.VertexBuffer.NormalKind]=null),this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose()},i.prototype._processEdgeForAdjacencies=function(e,t,i,r,n){return e===i&&t===r||e===r&&t===i?0:e===r&&t===n||e===n&&t===r?1:e===n&&t===i||e===i&&t===n?2:-1},i.prototype._processEdgeForAdjacenciesWithVertices=function(e,t,i,r,n){return e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(r)||e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(i)?0:e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(n)||e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(r)?1:e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(i)||e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(n)?2:-1},i.prototype._checkEdge=function(t,i,r,n,o){var s;if(void 0===i)s=!0;else{s=e.Vector3.Dot(r[t],r[i])0){this._previousStencilState=this._engine.getStencilBuffer();for(var r=0,n=i;r-1)){this._renderEffects=!0,this._needStencil=this._needStencil||o.needStencil();var s=o._mainTexture;s._shouldRender()&&(this.scene.incrementRenderId(),s.render(!1,!1))}}this.scene.incrementRenderId()}},t.prototype._setStencil=function(e){this._needStencil&&this._engine.setStencilBuffer(!0)},t.prototype._setStencilBack=function(e){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)},t.prototype._draw=function(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);for(var t=this.scene.effectLayers,i=0;i4&&(s.push(e.VertexBuffer.MatricesIndicesExtraKind),s.push(e.VertexBuffer.MatricesWeightsExtraKind)),o.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),o.push("#define BonesPerMesh "+(a.skeleton?a.skeleton.bones.length+1:0))):o.push("#define NUM_BONE_INFLUENCERS 0");var u=a.morphTargetManager,d=0;u&&u.numInfluencers>0&&(o.push("#define MORPHTARGETS"),d=u.numInfluencers,o.push("#define NUM_MORPH_INFLUENCERS "+d),e.MaterialHelper.PrepareAttributesForMorphTargets(s,a,{NUM_MORPH_INFLUENCERS:d})),i&&(o.push("#define INSTANCES"),s.push("world0"),s.push("world1"),s.push("world2"),s.push("world3"));var f=o.join("\n");return this._cachedDefines!==f&&(this._cachedDefines=f,this._effectLayerMapGenerationEffect=this._scene.getEngine().createEffect("glowMapGeneration",s,["world","mBones","viewProjection","diffuseMatrix","color","emissiveMatrix","morphTargetInfluences"],["diffuseSampler","emissiveSampler"],f,void 0,void 0,void 0,{maxSimultaneousMorphTargets:d})),this._effectLayerMapGenerationEffect.isReady()},t.prototype.render=function(){var e=this._mergeEffect;if(e.isReady()){for(var t=0;t-1&&this._scene.effectLayers.splice(i,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()},t.prototype.getClassName=function(){return"EffectLayer"},t.Parse=function(t,i,r){return e.Tools.Instantiate(t.customType).Parse(t,i,r)},n([e.serialize()],t.prototype,"name",void 0),n([e.serializeAsColor4()],t.prototype,"neutralColor",void 0),n([e.serialize()],t.prototype,"isEnabled",void 0),n([e.serializeAsCameraReference()],t.prototype,"camera",null),n([e.serialize()],t.prototype,"renderingGroupId",null),t})();e.EffectLayer=t})(r||(r={}));var r;!(function(e){e.AbstractScene.prototype.getHighlightLayerByName=function(e){for(var t=0;t-1&&this._tasks.splice(t,1)},i.prototype._decreaseWaitingTasksCount=function(i){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,i),this.onProgressObservable.notifyObservers(new r(this._waitingTasksCount,this._totalTasksCount,i))}catch(t){e.Tools.Error("Error running progress callbacks."),console.log(t)}if(0===this._waitingTasksCount){try{this.onFinish&&this.onFinish(this._tasks);for(var n=this._tasks.slice(),o=0,s=n;o-1&&this._tasks.splice(a,1)}}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(t){e.Tools.Error("Error running tasks-done callbacks."),console.log(t)}this._isLoading=!1,this._scene.getEngine().hideLoadingUI()}},i.prototype._runTask=function(e){var t=this,i=function(){try{t.onTaskSuccess&&t.onTaskSuccess(e),t.onTaskSuccessObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)}catch(e){r("Error executing task success callbacks",e)}},r=function(i,r){e._setErrorObject(i,r),t.onTaskError&&t.onTaskError(e),t.onTaskErrorObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)};e.run(this._scene,i,r)},i.prototype.reset=function(){return this._isLoading=!1,this._tasks=new Array,this},i.prototype.load=function(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(var e=0;eu.upperRadiusLimit?u.upperRadiusLimit:h),h):0},t.prototype._maintainCameraAboveGround=function(){var i=this;if(!(this._elevationReturnTime<0)){var r=e.Tools.Now-this._lastInteractionTime,n=.5*Math.PI-this._defaultElevation,o=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>o&&r>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=e.Animation.CreateAnimation("beta",e.Animation.ANIMATIONTYPE_FLOAT,60,t.EasingFunction));var s=e.Animation.TransitionTo("beta",n,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(function(){i._clearAnimationLocks(),i.stopAllAnimations()}));s&&this._animatables.push(s)}}},t.prototype._getFrustumSlope=function(){var t=this._attachedCamera;if(!t)return e.Vector2.Zero();var i=t.getScene().getEngine(),r=i.getAspectRatio(t),n=Math.tan(t.fov/2),o=n*r;return new e.Vector2(o,n)},t.prototype._clearAnimationLocks=function(){this._betaIsAnimating=!1},t.prototype._applyUserInteraction=function(){this.isUserIsMoving&&(this._lastInteractionTime=e.Tools.Now,this.stopAllAnimations(),this._clearAnimationLocks())},t.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()},Object.defineProperty(t.prototype,"isUserIsMoving",{get:function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},enumerable:!0,configurable:!0}),t.EasingFunction=new e.ExponentialEase,t.EasingMode=e.EasingFunction.EASINGMODE_EASEINOUT,t.IgnoreBoundsSizeMode=0,t.FitFrustumSidesMode=1,t})();e.FramingBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}return Object.defineProperty(t.prototype,"name",{get:function(){return"Bouncing"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"autoTransitionRange",{get:function(){return this._autoTransitionRange},set:function(e){var t=this;if(this._autoTransitionRange!==e){this._autoTransitionRange=e;var i=this._attachedCamera;i&&(e?this._onMeshTargetChangedObserver=i.onMeshTargetChangedObservable.add((function(e){if(e){e.computeWorldMatrix(!0);var i=e.getBoundingInfo().diagonalLength;t.lowerRadiusTransitionRange=.05*i,t.upperRadiusTransitionRange=.05*i}})):this._onMeshTargetChangedObserver&&i.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(e){var t=this;this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((function(){t._attachedCamera&&(t._isRadiusAtLimit(t._attachedCamera.lowerRadiusLimit)&&t._applyBoundRadiusAnimation(t.lowerRadiusTransitionRange),t._isRadiusAtLimit(t._attachedCamera.upperRadiusLimit)&&t._applyBoundRadiusAnimation(t.upperRadiusTransitionRange))}))},t.prototype.detach=function(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)},t.prototype._isRadiusAtLimit=function(e){return!!this._attachedCamera&&(this._attachedCamera.radius===e&&!this._radiusIsAnimating)},t.prototype._applyBoundRadiusAnimation=function(i){var r=this;if(this._attachedCamera){this._radiusBounceTransition||(t.EasingFunction.setEasingMode(t.EasingMode),this._radiusBounceTransition=e.Animation.CreateAnimation("radius",e.Animation.ANIMATIONTYPE_FLOAT,60,t.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;var n=e.Animation.TransitionTo("radius",this._attachedCamera.radius+i,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,(function(){return r._clearAnimationLocks()}));n&&this._animatables.push(n)}},t.prototype._clearAnimationLocks=function(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)},t.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()},t.EasingFunction=new e.BackEase(.3),t.EasingMode=e.EasingFunction.EASINGMODE_EASEOUT,t})();e.BouncingBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}return Object.defineProperty(t.prototype,"name",{get:function(){return"AutoRotation"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(e){this._zoomStopsAnimation=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"idleRotationSpeed",{get:function(){return this._idleRotationSpeed},set:function(e){this._idleRotationSpeed=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"idleRotationWaitTime",{get:function(){return this._idleRotationWaitTime},set:function(e){this._idleRotationWaitTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"idleRotationSpinupTime",{get:function(){return this._idleRotationSpinupTime},set:function(e){this._idleRotationSpinupTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationInProgress",{get:function(){return Math.abs(this._cameraRotationSpeed)>0},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(t){var i=this;this._attachedCamera=t;var r=this._attachedCamera.getScene();this._onPrePointerObservableObserver=r.onPrePointerObservable.add((function(t){if(t.type===e.PointerEventTypes.POINTERDOWN)return void(i._isPointerDown=!0);t.type===e.PointerEventTypes.POINTERUP&&(i._isPointerDown=!1)})),this._onAfterCheckInputsObserver=t.onAfterCheckInputsObservable.add((function(){var t=e.Tools.Now,r=0;null!=i._lastFrameTime&&(r=t-i._lastFrameTime),i._lastFrameTime=t,i._applyUserInteraction();var n=t-i._lastInteractionTime-i._idleRotationWaitTime,o=Math.max(Math.min(n/i._idleRotationSpinupTime,1),0);i._cameraRotationSpeed=i._idleRotationSpeed*o,i._attachedCamera&&(i._attachedCamera.alpha-=i._cameraRotationSpeed*(r/1e3))}))},t.prototype.detach=function(){if(this._attachedCamera){var e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}},t.prototype._userIsZooming=function(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset},t.prototype._shouldAnimationStopForInteraction=function(){if(!this._attachedCamera)return!1;var e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()},t.prototype._applyUserInteraction=function(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=e.Tools.Now)},t.prototype._userIsMoving=function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},t})();e.AutoRotationBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}return e})();e.NullEngineOptions=t;var i=(function(i){function r(r){void 0===r&&(r=new t);var n=i.call(this,null)||this;return void 0===r.deterministicLockstep&&(r.deterministicLockstep=!1),void 0===r.lockstepMaxSteps&&(r.lockstepMaxSteps=4),n._options=r,n._caps=new e.EngineCapabilities,n._caps.maxTexturesImageUnits=16,n._caps.maxVertexTextureImageUnits=16,n._caps.maxTextureSize=512,n._caps.maxCubemapTextureSize=512,n._caps.maxRenderTextureSize=512,n._caps.maxVertexAttribs=16,n._caps.maxVaryingVectors=16,n._caps.maxFragmentUniformVectors=16,n._caps.maxVertexUniformVectors=16,n._caps.standardDerivatives=!1,n._caps.astc=null,n._caps.s3tc=null,n._caps.pvrtc=null,n._caps.etc1=null,n._caps.etc2=null,n._caps.textureAnisotropicFilterExtension=null,n._caps.maxAnisotropy=0,n._caps.uintIndices=!1,n._caps.fragmentDepthSupported=!1,n._caps.highPrecisionShaderSupported=!0,n._caps.colorBufferFloat=!1,n._caps.textureFloat=!1,n._caps.textureFloatLinearFiltering=!1,n._caps.textureFloatRender=!1,n._caps.textureHalfFloat=!1,n._caps.textureHalfFloatLinearFiltering=!1,n._caps.textureHalfFloatRender=!1,n._caps.textureLOD=!1,n._caps.drawBuffersExtension=!1,n._caps.depthTextureExtension=!1,n._caps.vertexArrayObject=!1,n._caps.instancedArrays=!1,e.Tools.Log("Babylon.js null engine (v"+e.Engine.Version+") launched"),"undefined"==typeof URL&&(URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(Blob=function(){}),n}return o(r,i),r.prototype.isDeterministicLockStep=function(){return this._options.deterministicLockstep},r.prototype.getLockstepMaxSteps=function(){return this._options.lockstepMaxSteps},r.prototype.getHardwareScalingLevel=function(){return 1},r.prototype.createVertexBuffer=function(e){return{capacity:0,references:1,is32Bits:!1}},r.prototype.createIndexBuffer=function(e){return{capacity:0,references:1,is32Bits:!1}},r.prototype.clear=function(e,t,i,r){void 0===r&&(r=!1)},r.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth},r.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight},r.prototype.setViewport=function(e,t,i){this._cachedViewport=e},r.prototype.createShaderProgram=function(e,t,i,r){return{transformFeedback:null,__SPECTOR_rebuildProgram:null}},r.prototype.getUniforms=function(e,t){return[]},r.prototype.getAttributes=function(e,t){return[]},r.prototype.bindSamplers=function(e){this._currentEffect=null},r.prototype.enableEffect=function(e){this._currentEffect=e,e.onBind&&e.onBind(e),e.onBindObservable.notifyObservers(e)},r.prototype.setState=function(e,t,i,r){void 0===t&&(t=0),void 0===r&&(r=!1)},r.prototype.setIntArray=function(e,t){},r.prototype.setIntArray2=function(e,t){},r.prototype.setIntArray3=function(e,t){},r.prototype.setIntArray4=function(e,t){},r.prototype.setFloatArray=function(e,t){},r.prototype.setFloatArray2=function(e,t){},r.prototype.setFloatArray3=function(e,t){},r.prototype.setFloatArray4=function(e,t){},r.prototype.setArray=function(e,t){},r.prototype.setArray2=function(e,t){},r.prototype.setArray3=function(e,t){},r.prototype.setArray4=function(e,t){},r.prototype.setMatrices=function(e,t){},r.prototype.setMatrix=function(e,t){},r.prototype.setMatrix3x3=function(e,t){},r.prototype.setMatrix2x2=function(e,t){},r.prototype.setFloat=function(e,t){},r.prototype.setFloat2=function(e,t,i){},r.prototype.setFloat3=function(e,t,i,r){},r.prototype.setBool=function(e,t){},r.prototype.setFloat4=function(e,t,i,r,n){},r.prototype.setColor3=function(e,t){},r.prototype.setColor4=function(e,t,i){},r.prototype.setAlphaMode=function(t,i){void 0===i&&(i=!1),this._alphaMode!==t&&(this._alphaState.alphaBlend=t!==e.Engine.ALPHA_DISABLE,i||this.setDepthWrite(t===e.Engine.ALPHA_DISABLE),this._alphaMode=t)},r.prototype.bindBuffers=function(e,t,i){},r.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilState.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},r.prototype.draw=function(e,t,i,r){},r.prototype.drawElementsType=function(e,t,i,r){},r.prototype.drawArraysType=function(e,t,i,r){},r.prototype._createTexture=function(){return{}},r.prototype._releaseTexture=function(e){},r.prototype.createTexture=function(t,i,r,n,o,s,a,l,c,h){void 0===o&&(o=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===s&&(s=null),void 0===a&&(a=null),void 0===l&&(l=null);var u=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_URL),d=String(t);return u.url=d,u.generateMipMaps=!i,u.samplingMode=o,u.invertY=r,u.baseWidth=this._options.textureSize,u.baseHeight=this._options.textureSize,u.width=this._options.textureSize,u.height=this._options.textureSize,h&&(u.format=h),u.isReady=!0,s&&s(),this._internalTexturesCache.push(u),u},r.prototype.createRenderTargetTexture=function(t,i){var r=new e.RenderTargetCreationOptions;void 0!==i&&"object"==typeof i?(r.generateMipMaps=i.generateMipMaps,r.generateDepthBuffer=void 0===i.generateDepthBuffer||i.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&i.generateStencilBuffer,r.type=void 0===i.type?e.Engine.TEXTURETYPE_UNSIGNED_INT:i.type,r.samplingMode=void 0===i.samplingMode?e.Texture.TRILINEAR_SAMPLINGMODE:i.samplingMode):(r.generateMipMaps=i,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.type=e.Engine.TEXTURETYPE_UNSIGNED_INT,r.samplingMode=e.Texture.TRILINEAR_SAMPLINGMODE);var n=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RENDERTARGET),o=t.width||t,s=t.height||t;return n._depthStencilBuffer={},n._framebuffer={},n.baseWidth=o,n.baseHeight=s,n.width=o,n.height=s,n.isReady=!0,n.samples=1,n.generateMipMaps=!!r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,n._generateDepthBuffer=r.generateDepthBuffer,n._generateStencilBuffer=!!r.generateStencilBuffer,this._internalTexturesCache.push(n),n},r.prototype.updateTextureSamplingMode=function(e,t){t.samplingMode=e},r.prototype.bindFramebuffer=function(e,t,i,r,n){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer,this._cachedViewport&&!n&&this.setViewport(this._cachedViewport,i,r)},r.prototype.unBindFramebuffer=function(e,t,i){void 0===t&&(t=!1),this._currentRenderTarget=null,i&&(e._MSAAFramebuffer&&(this._currentFramebuffer=e._framebuffer),i()),this._currentFramebuffer=null},r.prototype.createDynamicVertexBuffer=function(e){return{capacity:1,references:1,is32Bits:!1}},r.prototype.updateDynamicTexture=function(e,t,i,r,n){void 0===r&&(r=!1)},r.prototype.getError=function(){return 0},r.prototype._getUnpackAlignement=function(){return 1},r.prototype._unpackFlipY=function(e){},r.prototype.updateDynamicIndexBuffer=function(e,t,i){void 0===i&&(i=0)},r.prototype.updateDynamicVertexBuffer=function(e,t,i,r){},r.prototype._bindTextureDirectly=function(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)},r.prototype._bindTexture=function(e,t){e<0||this._bindTextureDirectly(0,t)},r.prototype._releaseBuffer=function(e){return 0===--e.references},r.prototype.releaseEffects=function(){},r.prototype.displayLoadingUI=function(){},r.prototype.hideLoadingUI=function(){},r.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,r,n,o,s){void 0===o&&(o=0),void 0===s&&(s=0)},r.prototype._uploadDataToTextureDirectly=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},r.prototype._uploadArrayBufferViewToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},r.prototype._uploadImageToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},r})(e.Engine);e.NullEngine=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){this.engine=t,this._captureGPUFrameTime=!1,this._gpuFrameTime=new e.PerfCounter,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new e.PerfCounter,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}return Object.defineProperty(t.prototype,"gpuFrameTimeCounter",{get:function(){return this._gpuFrameTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureGPUFrameTime",{get:function(){return this._captureGPUFrameTime},set:function(e){var t=this;e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.engine.onBeginFrameObservable.add((function(){t._gpuFrameTimeToken||(t._gpuFrameTimeToken=t.engine.startTimeQuery())})),this._onEndFrameObserver=this.engine.onEndFrameObservable.add((function(){if(t._gpuFrameTimeToken){var e=t.engine.endTimeQuery(t._gpuFrameTimeToken);e>-1&&(t._gpuFrameTimeToken=null,t._gpuFrameTime.fetchNewFrame(),t._gpuFrameTime.addCount(e,!0))}}))):(this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shaderCompilationTimeCounter",{get:function(){return this._shaderCompilationTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureShaderCompilationTime",{get:function(){return this._captureShaderCompilationTime},set:function(e){var t=this;e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add((function(){t._shaderCompilationTime.fetchNewFrame(),t._shaderCompilationTime.beginMonitoring()})),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add((function(){t._shaderCompilationTime.endMonitoring()}))):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null},t})();e.EngineInstrumentation=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){var i=this;this.scene=t,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new e.PerfCounter,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new e.PerfCounter,this._captureFrameTime=!1,this._frameTime=new e.PerfCounter,this._captureRenderTime=!1,this._renderTime=new e.PerfCounter,this._captureInterFrameTime=!1,this._interFrameTime=new e.PerfCounter,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new e.PerfCounter,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new e.PerfCounter,this._capturePhysicsTime=!1,this._physicsTime=new e.PerfCounter,this._captureAnimationsTime=!1,this._animationsTime=new e.PerfCounter,this._captureCameraRenderTime=!1,this._cameraRenderTime=new e.PerfCounter,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=t.onBeforeAnimationsObservable.add((function(){i._captureActiveMeshesEvaluationTime&&i._activeMeshesEvaluationTime.fetchNewFrame(),i._captureRenderTargetsRenderTime&&i._renderTargetsRenderTime.fetchNewFrame(),i._captureFrameTime&&(e.Tools.StartPerformanceCounter("Scene rendering"),i._frameTime.beginMonitoring()),i._captureInterFrameTime&&i._interFrameTime.endMonitoring(),i._captureParticlesRenderTime&&i._particlesRenderTime.fetchNewFrame(),i._captureSpritesRenderTime&&i._spritesRenderTime.fetchNewFrame(),i._captureAnimationsTime&&i._animationsTime.beginMonitoring(),i.scene.getEngine()._drawCalls.fetchNewFrame(),i.scene.getEngine()._textureCollisions.fetchNewFrame()})),this._onAfterRenderObserver=t.onAfterRenderObservable.add((function(){i._captureFrameTime&&(e.Tools.EndPerformanceCounter("Scene rendering"),i._frameTime.endMonitoring()),i._captureRenderTime&&i._renderTime.endMonitoring(!1),i._captureInterFrameTime&&i._interFrameTime.beginMonitoring()}))}return Object.defineProperty(t.prototype,"activeMeshesEvaluationTimeCounter",{get:function(){return this._activeMeshesEvaluationTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureActiveMeshesEvaluationTime",{get:function(){return this._captureActiveMeshesEvaluationTime},set:function(t){var i=this;t!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=t,t?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add((function(){e.Tools.StartPerformanceCounter("Active meshes evaluation"),i._activeMeshesEvaluationTime.beginMonitoring()})),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add((function(){e.Tools.EndPerformanceCounter("Active meshes evaluation"),i._activeMeshesEvaluationTime.endMonitoring()}))):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderTargetsRenderTimeCounter",{get:function(){return this._renderTargetsRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureRenderTargetsRenderTime",{get:function(){return this._captureRenderTargetsRenderTime},set:function(t){var i=this;t!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=t,t?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add((function(){e.Tools.StartPerformanceCounter("Render targets rendering"),i._renderTargetsRenderTime.beginMonitoring()})),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add((function(){e.Tools.EndPerformanceCounter("Render targets rendering"),i._renderTargetsRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"particlesRenderTimeCounter",{get:function(){return this._particlesRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureParticlesRenderTime",{get:function(){return this._captureParticlesRenderTime},set:function(t){var i=this;t!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=t,t?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add((function(){e.Tools.StartPerformanceCounter("Particles"),i._particlesRenderTime.beginMonitoring()})),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add((function(){e.Tools.EndPerformanceCounter("Particles"),i._particlesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"spritesRenderTimeCounter",{get:function(){return this._spritesRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureSpritesRenderTime",{get:function(){return this._captureSpritesRenderTime},set:function(t){var i=this;t!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=t,t?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add((function(){e.Tools.StartPerformanceCounter("Sprites"),i._spritesRenderTime.beginMonitoring()})),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add((function(){e.Tools.EndPerformanceCounter("Sprites"),i._spritesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"physicsTimeCounter",{get:function(){return this._physicsTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"capturePhysicsTime",{get:function(){return this._capturePhysicsTime},set:function(t){var i=this;t!==this._capturePhysicsTime&&(this._capturePhysicsTime=t,t?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add((function(){e.Tools.StartPerformanceCounter("Physics"),i._physicsTime.beginMonitoring()})), -this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add((function(){e.Tools.EndPerformanceCounter("Physics"),i._physicsTime.endMonitoring()}))):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationsTimeCounter",{get:function(){return this._animationsTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureAnimationsTime",{get:function(){return this._captureAnimationsTime},set:function(e){var t=this;e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add((function(){t._animationsTime.endMonitoring()})):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"frameTimeCounter",{get:function(){return this._frameTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureFrameTime",{get:function(){return this._captureFrameTime},set:function(e){this._captureFrameTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"interFrameTimeCounter",{get:function(){return this._interFrameTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureInterFrameTime",{get:function(){return this._captureInterFrameTime},set:function(e){this._captureInterFrameTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderTimeCounter",{get:function(){return this._renderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureRenderTime",{get:function(){return this._captureRenderTime},set:function(t){var i=this;t!==this._captureRenderTime&&(this._captureRenderTime=t,t?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add((function(){i._renderTime.beginMonitoring(),e.Tools.StartPerformanceCounter("Main render")})),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add((function(){i._renderTime.endMonitoring(!1),e.Tools.EndPerformanceCounter("Main render")}))):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraRenderTimeCounter",{get:function(){return this._cameraRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureCameraRenderTime",{get:function(){return this._captureCameraRenderTime},set:function(t){var i=this;t!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=t,t?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add((function(t){i._cameraRenderTime.beginMonitoring(),e.Tools.StartPerformanceCounter("Rendering camera "+t.name)})),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add((function(t){i._cameraRenderTime.endMonitoring(!1),e.Tools.EndPerformanceCounter("Rendering camera "+t.name)}))):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"drawCallsCounter",{get:function(){return this.scene.getEngine()._drawCalls},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"textureCollisionsCounter",{get:function(){return this.scene.getEngine()._textureCollisions},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null,this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null,this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null},t})();e.SceneInstrumentation=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this._timeElapsedQueryEnded=!1}return e})();e._TimeToken=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.DIFFUSEDIRECTUV=0,t.GAMMADIFFUSE=!1,t.DIFFUSEHASALPHA=!1,t.OPACITYFRESNEL=!1,t.REFLECTIONBLUR=!1,t.REFLECTIONFRESNEL=!1,t.REFLECTIONFALLOFF=!1,t.TEXTURELODSUPPORT=!1,t.PREMULTIPLYALPHA=!1,t.USERGBCOLOR=!1,t.USEHIGHLIGHTANDSHADOWCOLORS=!1,t.NOISE=!1,t.REFLECTIONBGR=!1,t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=!1,t.CONTRAST=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.EXPOSURE=!1,t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.EQUIRECTANGULAR_RELFECTION_FOV=!1,t.MAINUV1=!1,t.MAINUV2=!1,t.UV1=!1,t.UV2=!1,t.CLIPPLANE=!1,t.POINTSIZE=!1,t.FOG=!1,t.NORMAL=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.SHADOWFLOAT=!1,t.rebuild(),t}return o(t,e),t})(e.MaterialDefines),i=(function(i){function r(t,r){var n=i.call(this,t,r)||this;return n.primaryColor=e.Color3.White(),n._primaryColorShadowLevel=0,n._primaryColorHighlightLevel=0,n.reflectionTexture=null,n.reflectionBlur=0,n.diffuseTexture=null,n._shadowLights=null,n.shadowLights=null,n.shadowLevel=0,n.sceneCenter=e.Vector3.Zero(),n.opacityFresnel=!0,n.reflectionFresnel=!1,n.reflectionFalloffDistance=0,n.reflectionAmount=1,n.reflectionReflectance0=.05,n.reflectionReflectance90=.5,n.useRGBColor=!0,n.enableNoise=!1,n._fovMultiplier=1,n.useEquirectangularFOV=!1,n._maxSimultaneousLights=4,n.maxSimultaneousLights=4,n._imageProcessingObserver=null,n.switchToBGR=!1,n._renderTargets=new e.SmartArray(16),n._reflectionControls=e.Vector4.Zero(),n._white=e.Color3.White(),n._primaryShadowColor=e.Color3.Black(),n._primaryHighlightColor=e.Color3.Black(),n._attachImageProcessingConfiguration(null),n.getRenderTargetTextures=function(){return n._renderTargets.reset(),n._diffuseTexture&&n._diffuseTexture.isRenderTarget&&n._renderTargets.push(n._diffuseTexture),n._reflectionTexture&&n._reflectionTexture.isRenderTarget&&n._renderTargets.push(n._reflectionTexture),n._renderTargets},n}return o(r,i),Object.defineProperty(r.prototype,"_perceptualColor",{get:function(){return this.__perceptualColor},set:function(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"primaryColorShadowLevel",{get:function(){return this._primaryColorShadowLevel},set:function(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"primaryColorHighlightLevel",{get:function(){return this._primaryColorHighlightLevel},set:function(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"reflectionStandardFresnelWeight",{set:function(e){var t=e;t<.5?(t*=2,this.reflectionReflectance0=r.StandardReflectance0*t,this.reflectionReflectance90=r.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=r.StandardReflectance0+(1-r.StandardReflectance0)*t,this.reflectionReflectance90=r.StandardReflectance90+(1-r.StandardReflectance90)*t)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"fovMultiplier",{get:function(){return this._fovMultiplier},set:function(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))},enumerable:!0,configurable:!0}),r.prototype._attachImageProcessingConfiguration=function(e){var t=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((function(e){t._computePrimaryColorFromPerceptualColor(),t._markAllSubMeshesAsImageProcessingDirty()}))))},Object.defineProperty(r.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this.imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorCurves",{get:function(){return this.imageProcessingConfiguration.colorCurves},set:function(e){this.imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),r.prototype.needAlphaTesting=function(){return!0},r.prototype.needAlphaBlending=function(){return this.alpha<0||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha},r.prototype.isReadyForSubMesh=function(i,r,n){var o=this;if(void 0===n&&(n=!1),r.effect&&this.isFrozen&&this._wasPreviouslyReady)return!0;r._materialDefines||(r._materialDefines=new t);var s=this.getScene(),a=r._materialDefines;if(!this.checkReadyOnEveryCall&&r.effect&&a._renderId===s.getRenderId())return!0;var l=s.getEngine();if(e.MaterialHelper.PrepareDefinesForLights(s,i,a,!1,this._maxSimultaneousLights),a._needNormals=!0,a._areTexturesDirty){if(a._needUVs=!1,s.texturesEnabled){if(s.getEngine().getCaps().textureLOD&&(a.TEXTURELODSUPPORT=!0),this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture,a,"DIFFUSE"),a.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,a.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,a.OPACITYFRESNEL=this._opacityFresnel}else a.DIFFUSE=!1,a.DIFFUSEHASALPHA=!1,a.GAMMADIFFUSE=!1,a.OPACITYFRESNEL=!1;var c=this._reflectionTexture;if(c&&e.StandardMaterial.ReflectionTextureEnabled){if(!c.isReadyOrNotBlocking())return!1;switch(a.REFLECTION=!0,a.GAMMAREFLECTION=c.gammaSpace,a.RGBDREFLECTION=c.isRGBD,a.REFLECTIONBLUR=this._reflectionBlur>0,a.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!c.invertZ:c.invertZ,a.LODINREFLECTIONALPHA=c.lodLevelInAlpha,a.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,a.REFLECTIONBGR=this.switchToBGR,c.coordinatesMode===e.Texture.INVCUBIC_MODE&&(a.INVERTCUBICMAP=!0),a.REFLECTIONMAP_3D=c.isCube,c.coordinatesMode){case e.Texture.EXPLICIT_MODE:a.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:a.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:a.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:a.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:a.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:default:a.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(a.REFLECTIONFRESNEL=!0,a.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(a.REFLECTIONFRESNEL=!1,a.REFLECTIONFALLOFF=!1)}else a.REFLECTION=!1,a.REFLECTIONFRESNEL=!1,a.REFLECTIONFALLOFF=!1,a.REFLECTIONBLUR=!1,a.REFLECTIONMAP_3D=!1,a.REFLECTIONMAP_SPHERICAL=!1,a.REFLECTIONMAP_PLANAR=!1,a.REFLECTIONMAP_CUBIC=!1,a.REFLECTIONMAP_PROJECTION=!1,a.REFLECTIONMAP_SKYBOX=!1,a.REFLECTIONMAP_EXPLICIT=!1,a.REFLECTIONMAP_EQUIRECTANGULAR=!1,a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,a.INVERTCUBICMAP=!1,a.REFLECTIONMAP_OPPOSITEZ=!1,a.LODINREFLECTIONALPHA=!1,a.GAMMAREFLECTION=!1,a.RGBDREFLECTION=!1}a.PREMULTIPLYALPHA=this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED||this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF,a.USERGBCOLOR=this._useRGBColor,a.NOISE=this._enableNoise}if(a._areLightsDirty&&(a.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel)),a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a)}if(e.MaterialHelper.PrepareDefinesForMisc(i,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(i),a),e.MaterialHelper.PrepareDefinesForFrameBoundValues(s,l,a,n),e.MaterialHelper.PrepareDefinesForAttributes(i,a,!1,!0,!1)&&i&&(s.getEngine().getCaps().standardDerivatives||i.isVerticesDataPresent(e.VertexBuffer.NormalKind)||(i.createNormals(!0),e.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: "+i.name))),a.isDirty){a.markAsProcessed(),s.resetCachedMaterial();var h=new e.EffectFallbacks;a.FOG&&h.addFallback(0,"FOG"),a.POINTSIZE&&h.addFallback(1,"POINTSIZE"),e.MaterialHelper.HandleFallbacksForShadows(a,h,this._maxSimultaneousLights),a.NUM_BONE_INFLUENCERS>0&&h.addCPUSkinningFallback(0,i);var u=[e.VertexBuffer.PositionKind];a.NORMAL&&u.push(e.VertexBuffer.NormalKind),a.UV1&&u.push(e.VertexBuffer.UVKind),a.UV2&&u.push(e.VertexBuffer.UV2Kind),e.MaterialHelper.PrepareAttributesForBones(u,i,a,h),e.MaterialHelper.PrepareAttributesForInstances(u,a);var d=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","vClipPlane","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"],f=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],p=["Material","Scene"];e.ImageProcessingConfiguration&&(e.ImageProcessingConfiguration.PrepareUniforms(d,a),e.ImageProcessingConfiguration.PrepareSamplers(f,a)),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:a,maxSimultaneousLights:this._maxSimultaneousLights});var _=function(e){o.onCompiled&&o.onCompiled(e),o.bindSceneUniformBuffer(e,s.getSceneUniformBuffer())},m=a.toString();r.setEffect(s.getEngine().createEffect("background",{attributes:u,uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:m,fallbacks:h,onCompiled:_,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},l),a),this.buildUniformLayout()}return!(!r.effect||!r.effect.isReady())&&(a._renderId=s.getRenderId(),this._wasPreviouslyReady=!0,!0)},r.prototype._computePrimaryColorFromPerceptualColor=function(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())},r.prototype._computePrimaryColors=function(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))},r.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.create()},r.prototype.unbind=function(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),i.prototype.unbind.call(this)},r.prototype.bindOnlyWorldMatrix=function(e){this._activeEffect.setMatrix("world",e)},r.prototype.bindForSubMesh=function(t,i,r){var n=this.getScene(),o=r._materialDefines;if(o){var s=r.effect;if(s){this._activeEffect=s,this.bindOnlyWorldMatrix(t),e.MaterialHelper.BindBonesParameters(i,this._activeEffect);var a=this._mustRebind(n,s,i.visibility);if(a){this._uniformBuffer.bindToEffect(s,"Material"),this.bindViewProjection(s);var l=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(n.texturesEnabled&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),e.MaterialHelper.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),l&&e.StandardMaterial.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",l.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),o.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),n.texturesEnabled&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),l&&e.StandardMaterial.ReflectionTextureEnabled&&(o.REFLECTIONBLUR&&o.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",l):o.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",l._lodTextureMid||l),this._uniformBuffer.setTexture("reflectionSamplerLow",l._lodTextureLow||l),this._uniformBuffer.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)):this._uniformBuffer.setTexture("reflectionSampler",l),o.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w)))),e.MaterialHelper.BindClipPlane(this._activeEffect,n),e.MaterialHelper.BindEyePosition(s,n)}!a&&this.isFrozen||(n.lightsEnabled&&e.MaterialHelper.BindLights(n,i,this._activeEffect,o,this._maxSimultaneousLights,!1),this.bindView(s),e.MaterialHelper.BindFogParameters(n,i,this._activeEffect),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(i,this._activeEffect)}}},r.prototype.dispose=function(e,t){void 0===e&&(e=!1),void 0===t&&(t=!1),t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),i.prototype.dispose.call(this,e)},r.prototype.clone=function(t){var i=this;return e.SerializationHelper.Clone((function(){return new r(t,i.getScene())}),this)},r.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.BackgroundMaterial",t},r.prototype.getClassName=function(){return"BackgroundMaterial"},r.Parse=function(t,i,n){return e.SerializationHelper.Parse((function(){return new r(t.name,i)}),t,i,n)},r.StandardReflectance0=.05,r.StandardReflectance90=.5,n([e.serializeAsColor3()],r.prototype,"_primaryColor",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"primaryColor",void 0),n([e.serializeAsColor3()],r.prototype,"__perceptualColor",void 0),n([e.serialize()],r.prototype,"_primaryColorShadowLevel",void 0),n([e.serialize()],r.prototype,"_primaryColorHighlightLevel",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"primaryColorHighlightLevel",null),n([e.serializeAsTexture()],r.prototype,"_reflectionTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionTexture",void 0),n([e.serialize()],r.prototype,"_reflectionBlur",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionBlur",void 0),n([e.serializeAsTexture()],r.prototype,"_diffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"diffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"shadowLights",void 0),n([e.serialize()],r.prototype,"_shadowLevel",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"shadowLevel",void 0),n([e.serializeAsVector3()],r.prototype,"_sceneCenter",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"sceneCenter",void 0),n([e.serialize()],r.prototype,"_opacityFresnel",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"opacityFresnel",void 0),n([e.serialize()],r.prototype,"_reflectionFresnel",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionFresnel",void 0),n([e.serialize()],r.prototype,"_reflectionFalloffDistance",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionFalloffDistance",void 0),n([e.serialize()],r.prototype,"_reflectionAmount",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionAmount",void 0),n([e.serialize()],r.prototype,"_reflectionReflectance0",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionReflectance0",void 0),n([e.serialize()],r.prototype,"_reflectionReflectance90",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionReflectance90",void 0),n([e.serialize()],r.prototype,"_useRGBColor",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useRGBColor",void 0),n([e.serialize()],r.prototype,"_enableNoise",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"enableNoise",void 0),n([e.serialize()],r.prototype,"_maxSimultaneousLights",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"maxSimultaneousLights",void 0),n([e.serializeAsImageProcessingConfiguration()],r.prototype,"_imageProcessingConfiguration",void 0),r})(e.PushMaterial);e.BackgroundMaterial=i})(r||(r={}));var r,s=this&&this.__assign||Object.assign||function(e){for(var t,i=1,r=arguments.length;ii&&(i=2*a,r=i),i*=1.1,r*=1.5,n=o.min.add(s.scale(.5)),n.y=o.min.y-this._options.groundYBias}return{groundSize:i,skyboxSize:r,rootPosition:n}},t.prototype._setupGround=function(t){var i=this;this._ground&&!this._ground.isDisposed()||(this._ground=e.Mesh.CreatePlane("BackgroundPlane",t.groundSize,this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((function(){i._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow},t.prototype._setupGroundMaterial=function(){this._groundMaterial||(this._groundMaterial=new e.BackgroundMaterial("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)},t.prototype._setupGroundDiffuseTexture=function(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof e.BaseTexture)return void(this._groundMaterial.diffuseTexture=this._options.groundTexture);var t=new e.Texture(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler);t.gammaSpace=!1,t.hasAlpha=!0,this._groundMaterial.diffuseTexture=t}},t.prototype._setupGroundMirrorTexture=function(t){var i=e.Texture.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new e.MirrorTexture("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,e.Texture.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new e.Plane(0,-1,0,t.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=i,this._groundMirror.wrapV=i,this._groundMirror.gammaSpace=!1,this._groundMirror.renderList))for(var r=0;rthis.occlusionRetryCount))return;this._isOcclusionQueryInProgress=!1,this._occlusionInternalRetryCounter=0,this._isOccluded=this.occlusionType!==e.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC&&this._isOccluded}}var r=this.getScene();if(r.getBoundingBoxRenderer){var n=r.getBoundingBoxRenderer();this._occlusionQuery||(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(this.occlusionQueryAlgorithmType,this._occlusionQuery),n.renderOcclusionBoundingBox(this),t.endOcclusionQuery(this.occlusionQueryAlgorithmType),this._isOcclusionQueryInProgress=!0}}})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===r&&(r=256),void 0===n&&(n=e.Engine.LastCreatedScene);var a=t.call(this,i,r,"noise",n,o,s)||this;return a._time=0,a.brightness=.2,a.octaves=3,a.persistence=.8,a.animationSpeedFactor=1,a._updateShaderUniforms(),a}return o(i,t),i.prototype._updateShaderUniforms=function(){var e=this.getScene();e&&(this._time+=e.getAnimationRatio()*this.animationSpeedFactor*.01,this.setFloat("brightness",this.brightness),this.setInt("octaves",this.octaves),this.setFloat("persistence",this.persistence),this.setFloat("timeScale",this._time))},i.prototype.render=function(e){this._updateShaderUniforms(),t.prototype.render.call(this,e)},i.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this,t.prototype.serialize.call(this));return i.customType="BABYLON.NoiseProceduralTexture",i},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,t._size,r,void 0,t._generateMipMaps)}),t,r,n)},i})(e.ProceduralTexture);e.NoiseProceduralTexture=t})(r||(r={})),r.Effect.ShadersStore={defaultVertexShader:"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n",defaultPixelShader:"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#include\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include\n#include\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n", -pbrVertexShader:"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include\n\n#include\n\n#include\n\n#include[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include\n}",pbrPixelShader:"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include\n#include\n#include\n\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n\n#include\nvoid main(void) {\n#include\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include\n#include(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}",rgbdEncodePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}",rgbdDecodePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}",spritesVertexShader:"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}",spritesPixelShader:"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include\ngl_FragColor=color;\n}",particlesVertexShader:"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}",particlesPixelShader:"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}",colorVertexShader:"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}",colorPixelShader:"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}", -gpuRenderParticlesVertexShader:"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}",gpuRenderParticlesPixelShader:"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n",gpuUpdateParticlesVertexShader:"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}",gpuUpdateParticlesPixelShader:"#version 300 es\nvoid main() {\ndiscard;\n}\n",postprocessVertexShader:"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}",passPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}",shadowMapVertexShader:"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n\n#include\n#include\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",shadowMapPixelShader:"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}",depthBoxBlurPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}",proceduralVertexShader:"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}",depthVertexShader:"\nattribute vec3 position;\n#include\n\n#include\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",depthPixelShader:"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}",ssaoPixelShader:"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; imaxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}", +Object.defineProperty(t.prototype,"radiusScale",{get:function(){return this._radiusScale},set:function(e){this._radiusScale=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"positionScale",{get:function(){return this._positionScale},set:function(e){this._positionScale=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"defaultElevation",{get:function(){return this._defaultElevation},set:function(e){this._defaultElevation=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"elevationReturnTime",{get:function(){return this._elevationReturnTime},set:function(e){this._elevationReturnTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"elevationReturnWaitTime",{get:function(){return this._elevationReturnWaitTime},set:function(e){this._elevationReturnWaitTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(e){this._zoomStopsAnimation=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"framingTime",{get:function(){return this._framingTime},set:function(e){this._framingTime=e},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(i){var r=this;this._attachedCamera=i;var n=this._attachedCamera.getScene();t.EasingFunction.setEasingMode(t.EasingMode),this._onPrePointerObservableObserver=n.onPrePointerObservable.add((function(t){if(t.type===e.PointerEventTypes.POINTERDOWN)return void(r._isPointerDown=!0);t.type===e.PointerEventTypes.POINTERUP&&(r._isPointerDown=!1)})),this._onMeshTargetChangedObserver=i.onMeshTargetChangedObservable.add((function(e){e&&r.zoomOnMesh(e)})),this._onAfterCheckInputsObserver=i.onAfterCheckInputsObservable.add((function(){r._applyUserInteraction(),r._maintainCameraAboveGround()}))},t.prototype.detach=function(){if(this._attachedCamera){var e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}},t.prototype.zoomOnMesh=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=null),e.computeWorldMatrix(!0);var r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)},t.prototype.zoomOnMeshHierarchy=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=null),e.computeWorldMatrix(!0);var r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)},t.prototype.zoomOnMeshesHierarchy=function(t,i,r){void 0===i&&(i=!1),void 0===r&&(r=null);for(var n=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new e.Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=0;su.upperRadiusLimit?u.upperRadiusLimit:h),h):0},t.prototype._maintainCameraAboveGround=function(){var i=this;if(!(this._elevationReturnTime<0)){var r=e.Tools.Now-this._lastInteractionTime,n=.5*Math.PI-this._defaultElevation,o=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>o&&r>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=e.Animation.CreateAnimation("beta",e.Animation.ANIMATIONTYPE_FLOAT,60,t.EasingFunction));var s=e.Animation.TransitionTo("beta",n,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(function(){i._clearAnimationLocks(),i.stopAllAnimations()}));s&&this._animatables.push(s)}}},t.prototype._getFrustumSlope=function(){var t=this._attachedCamera;if(!t)return e.Vector2.Zero();var i=t.getScene().getEngine(),r=i.getAspectRatio(t),n=Math.tan(t.fov/2),o=n*r;return new e.Vector2(o,n)},t.prototype._clearAnimationLocks=function(){this._betaIsAnimating=!1},t.prototype._applyUserInteraction=function(){this.isUserIsMoving&&(this._lastInteractionTime=e.Tools.Now,this.stopAllAnimations(),this._clearAnimationLocks())},t.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()},Object.defineProperty(t.prototype,"isUserIsMoving",{get:function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},enumerable:!0,configurable:!0}),t.EasingFunction=new e.ExponentialEase,t.EasingMode=e.EasingFunction.EASINGMODE_EASEINOUT,t.IgnoreBoundsSizeMode=0,t.FitFrustumSidesMode=1,t})();e.FramingBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}return Object.defineProperty(t.prototype,"name",{get:function(){return"Bouncing"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"autoTransitionRange",{get:function(){return this._autoTransitionRange},set:function(e){var t=this;if(this._autoTransitionRange!==e){this._autoTransitionRange=e;var i=this._attachedCamera;i&&(e?this._onMeshTargetChangedObserver=i.onMeshTargetChangedObservable.add((function(e){if(e){e.computeWorldMatrix(!0);var i=e.getBoundingInfo().diagonalLength;t.lowerRadiusTransitionRange=.05*i,t.upperRadiusTransitionRange=.05*i}})):this._onMeshTargetChangedObserver&&i.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(e){var t=this;this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((function(){t._attachedCamera&&(t._isRadiusAtLimit(t._attachedCamera.lowerRadiusLimit)&&t._applyBoundRadiusAnimation(t.lowerRadiusTransitionRange),t._isRadiusAtLimit(t._attachedCamera.upperRadiusLimit)&&t._applyBoundRadiusAnimation(t.upperRadiusTransitionRange))}))},t.prototype.detach=function(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)},t.prototype._isRadiusAtLimit=function(e){return!!this._attachedCamera&&(this._attachedCamera.radius===e&&!this._radiusIsAnimating)},t.prototype._applyBoundRadiusAnimation=function(i){var r=this;if(this._attachedCamera){this._radiusBounceTransition||(t.EasingFunction.setEasingMode(t.EasingMode),this._radiusBounceTransition=e.Animation.CreateAnimation("radius",e.Animation.ANIMATIONTYPE_FLOAT,60,t.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;var n=e.Animation.TransitionTo("radius",this._attachedCamera.radius+i,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,(function(){return r._clearAnimationLocks()}));n&&this._animatables.push(n)}},t.prototype._clearAnimationLocks=function(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)},t.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()},t.EasingFunction=new e.BackEase(.3),t.EasingMode=e.EasingFunction.EASINGMODE_EASEOUT,t})();e.BouncingBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}return Object.defineProperty(t.prototype,"name",{get:function(){return"AutoRotation"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(e){this._zoomStopsAnimation=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"idleRotationSpeed",{get:function(){return this._idleRotationSpeed},set:function(e){this._idleRotationSpeed=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"idleRotationWaitTime",{get:function(){return this._idleRotationWaitTime},set:function(e){this._idleRotationWaitTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"idleRotationSpinupTime",{get:function(){return this._idleRotationSpinupTime},set:function(e){this._idleRotationSpinupTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationInProgress",{get:function(){return Math.abs(this._cameraRotationSpeed)>0},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(t){var i=this;this._attachedCamera=t;var r=this._attachedCamera.getScene();this._onPrePointerObservableObserver=r.onPrePointerObservable.add((function(t){if(t.type===e.PointerEventTypes.POINTERDOWN)return void(i._isPointerDown=!0);t.type===e.PointerEventTypes.POINTERUP&&(i._isPointerDown=!1)})),this._onAfterCheckInputsObserver=t.onAfterCheckInputsObservable.add((function(){var t=e.Tools.Now,r=0;null!=i._lastFrameTime&&(r=t-i._lastFrameTime),i._lastFrameTime=t,i._applyUserInteraction();var n=t-i._lastInteractionTime-i._idleRotationWaitTime,o=Math.max(Math.min(n/i._idleRotationSpinupTime,1),0);i._cameraRotationSpeed=i._idleRotationSpeed*o,i._attachedCamera&&(i._attachedCamera.alpha-=i._cameraRotationSpeed*(r/1e3))}))},t.prototype.detach=function(){if(this._attachedCamera){var e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}},t.prototype._userIsZooming=function(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset},t.prototype._shouldAnimationStopForInteraction=function(){if(!this._attachedCamera)return!1;var e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()},t.prototype._applyUserInteraction=function(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=e.Tools.Now)},t.prototype._userIsMoving=function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},t})();e.AutoRotationBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}return e})();e.NullEngineOptions=t;var i=(function(i){function r(r){void 0===r&&(r=new t);var n=i.call(this,null)||this;return void 0===r.deterministicLockstep&&(r.deterministicLockstep=!1),void 0===r.lockstepMaxSteps&&(r.lockstepMaxSteps=4),n._options=r,n._caps=new e.EngineCapabilities,n._caps.maxTexturesImageUnits=16,n._caps.maxVertexTextureImageUnits=16,n._caps.maxTextureSize=512,n._caps.maxCubemapTextureSize=512,n._caps.maxRenderTextureSize=512,n._caps.maxVertexAttribs=16,n._caps.maxVaryingVectors=16,n._caps.maxFragmentUniformVectors=16,n._caps.maxVertexUniformVectors=16,n._caps.standardDerivatives=!1,n._caps.astc=null,n._caps.s3tc=null,n._caps.pvrtc=null,n._caps.etc1=null,n._caps.etc2=null,n._caps.textureAnisotropicFilterExtension=null,n._caps.maxAnisotropy=0,n._caps.uintIndices=!1,n._caps.fragmentDepthSupported=!1,n._caps.highPrecisionShaderSupported=!0,n._caps.colorBufferFloat=!1,n._caps.textureFloat=!1,n._caps.textureFloatLinearFiltering=!1,n._caps.textureFloatRender=!1,n._caps.textureHalfFloat=!1,n._caps.textureHalfFloatLinearFiltering=!1,n._caps.textureHalfFloatRender=!1,n._caps.textureLOD=!1,n._caps.drawBuffersExtension=!1,n._caps.depthTextureExtension=!1,n._caps.vertexArrayObject=!1,n._caps.instancedArrays=!1,e.Tools.Log("Babylon.js null engine (v"+e.Engine.Version+") launched"),"undefined"==typeof URL&&(URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(Blob=function(){}),n}return o(r,i),r.prototype.isDeterministicLockStep=function(){return this._options.deterministicLockstep},r.prototype.getLockstepMaxSteps=function(){return this._options.lockstepMaxSteps},r.prototype.getHardwareScalingLevel=function(){return 1},r.prototype.createVertexBuffer=function(e){return{capacity:0,references:1,is32Bits:!1}},r.prototype.createIndexBuffer=function(e){return{capacity:0,references:1,is32Bits:!1}},r.prototype.clear=function(e,t,i,r){void 0===r&&(r=!1)},r.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth},r.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight},r.prototype.setViewport=function(e,t,i){this._cachedViewport=e},r.prototype.createShaderProgram=function(e,t,i,r){return{transformFeedback:null,__SPECTOR_rebuildProgram:null}},r.prototype.getUniforms=function(e,t){return[]},r.prototype.getAttributes=function(e,t){return[]},r.prototype.bindSamplers=function(e){this._currentEffect=null},r.prototype.enableEffect=function(e){this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e)},r.prototype.setState=function(e,t,i,r){void 0===t&&(t=0),void 0===r&&(r=!1)},r.prototype.setIntArray=function(e,t){},r.prototype.setIntArray2=function(e,t){},r.prototype.setIntArray3=function(e,t){},r.prototype.setIntArray4=function(e,t){},r.prototype.setFloatArray=function(e,t){},r.prototype.setFloatArray2=function(e,t){},r.prototype.setFloatArray3=function(e,t){},r.prototype.setFloatArray4=function(e,t){},r.prototype.setArray=function(e,t){},r.prototype.setArray2=function(e,t){},r.prototype.setArray3=function(e,t){},r.prototype.setArray4=function(e,t){},r.prototype.setMatrices=function(e,t){},r.prototype.setMatrix=function(e,t){},r.prototype.setMatrix3x3=function(e,t){},r.prototype.setMatrix2x2=function(e,t){},r.prototype.setFloat=function(e,t){},r.prototype.setFloat2=function(e,t,i){},r.prototype.setFloat3=function(e,t,i,r){},r.prototype.setBool=function(e,t){},r.prototype.setFloat4=function(e,t,i,r,n){},r.prototype.setColor3=function(e,t){},r.prototype.setColor4=function(e,t,i){},r.prototype.setAlphaMode=function(t,i){void 0===i&&(i=!1),this._alphaMode!==t&&(this._alphaState.alphaBlend=t!==e.Engine.ALPHA_DISABLE,i||this.setDepthWrite(t===e.Engine.ALPHA_DISABLE),this._alphaMode=t)},r.prototype.bindBuffers=function(e,t,i){},r.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilState.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},r.prototype.draw=function(e,t,i,r){},r.prototype.drawElementsType=function(e,t,i,r){},r.prototype.drawArraysType=function(e,t,i,r){},r.prototype._createTexture=function(){return{}},r.prototype._releaseTexture=function(e){},r.prototype.createTexture=function(t,i,r,n,o,s,a,l,c,h){void 0===o&&(o=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===s&&(s=null),void 0===a&&(a=null),void 0===l&&(l=null);var u=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_URL),d=String(t);return u.url=d,u.generateMipMaps=!i,u.samplingMode=o,u.invertY=r,u.baseWidth=this._options.textureSize,u.baseHeight=this._options.textureSize,u.width=this._options.textureSize,u.height=this._options.textureSize,h&&(u.format=h),u.isReady=!0,s&&s(),this._internalTexturesCache.push(u),u},r.prototype.createRenderTargetTexture=function(t,i){var r=new e.RenderTargetCreationOptions;void 0!==i&&"object"==typeof i?(r.generateMipMaps=i.generateMipMaps,r.generateDepthBuffer=void 0===i.generateDepthBuffer||i.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&i.generateStencilBuffer,r.type=void 0===i.type?e.Engine.TEXTURETYPE_UNSIGNED_INT:i.type,r.samplingMode=void 0===i.samplingMode?e.Texture.TRILINEAR_SAMPLINGMODE:i.samplingMode):(r.generateMipMaps=i,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.type=e.Engine.TEXTURETYPE_UNSIGNED_INT,r.samplingMode=e.Texture.TRILINEAR_SAMPLINGMODE);var n=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RENDERTARGET),o=t.width||t,s=t.height||t;return n._depthStencilBuffer={},n._framebuffer={},n.baseWidth=o,n.baseHeight=s,n.width=o,n.height=s,n.isReady=!0,n.samples=1,n.generateMipMaps=!!r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,n._generateDepthBuffer=r.generateDepthBuffer,n._generateStencilBuffer=!!r.generateStencilBuffer,this._internalTexturesCache.push(n),n},r.prototype.updateTextureSamplingMode=function(e,t){t.samplingMode=e},r.prototype.bindFramebuffer=function(e,t,i,r,n){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer,this._cachedViewport&&!n&&this.setViewport(this._cachedViewport,i,r)},r.prototype.unBindFramebuffer=function(e,t,i){void 0===t&&(t=!1),this._currentRenderTarget=null,i&&(e._MSAAFramebuffer&&(this._currentFramebuffer=e._framebuffer),i()),this._currentFramebuffer=null},r.prototype.createDynamicVertexBuffer=function(e){return{capacity:1,references:1,is32Bits:!1}},r.prototype.updateDynamicTexture=function(e,t,i,r,n){void 0===r&&(r=!1)},r.prototype.getError=function(){return 0},r.prototype._getUnpackAlignement=function(){return 1},r.prototype._unpackFlipY=function(e){},r.prototype.updateDynamicIndexBuffer=function(e,t,i){void 0===i&&(i=0)},r.prototype.updateDynamicVertexBuffer=function(e,t,i,r){},r.prototype._bindTextureDirectly=function(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)},r.prototype._bindTexture=function(e,t){e<0||this._bindTextureDirectly(0,t)},r.prototype._releaseBuffer=function(e){return 0===--e.references},r.prototype.releaseEffects=function(){},r.prototype.displayLoadingUI=function(){},r.prototype.hideLoadingUI=function(){},r.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,r,n,o,s){void 0===o&&(o=0),void 0===s&&(s=0)},r.prototype._uploadDataToTextureDirectly=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},r.prototype._uploadArrayBufferViewToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},r.prototype._uploadImageToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},r})(e.Engine);e.NullEngine=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){this.engine=t,this._captureGPUFrameTime=!1,this._gpuFrameTime=new e.PerfCounter,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new e.PerfCounter,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}return Object.defineProperty(t.prototype,"gpuFrameTimeCounter",{get:function(){return this._gpuFrameTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureGPUFrameTime",{get:function(){return this._captureGPUFrameTime},set:function(e){var t=this;e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.engine.onBeginFrameObservable.add((function(){t._gpuFrameTimeToken||(t._gpuFrameTimeToken=t.engine.startTimeQuery())})),this._onEndFrameObserver=this.engine.onEndFrameObservable.add((function(){if(t._gpuFrameTimeToken){var e=t.engine.endTimeQuery(t._gpuFrameTimeToken);e>-1&&(t._gpuFrameTimeToken=null,t._gpuFrameTime.fetchNewFrame(),t._gpuFrameTime.addCount(e,!0))}}))):(this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shaderCompilationTimeCounter",{get:function(){return this._shaderCompilationTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureShaderCompilationTime",{get:function(){return this._captureShaderCompilationTime},set:function(e){var t=this;e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add((function(){t._shaderCompilationTime.fetchNewFrame(),t._shaderCompilationTime.beginMonitoring()})),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add((function(){t._shaderCompilationTime.endMonitoring()}))):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null},t})();e.EngineInstrumentation=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){var i=this;this.scene=t,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new e.PerfCounter,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new e.PerfCounter,this._captureFrameTime=!1,this._frameTime=new e.PerfCounter,this._captureRenderTime=!1,this._renderTime=new e.PerfCounter,this._captureInterFrameTime=!1,this._interFrameTime=new e.PerfCounter,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new e.PerfCounter,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new e.PerfCounter,this._capturePhysicsTime=!1,this._physicsTime=new e.PerfCounter,this._captureAnimationsTime=!1,this._animationsTime=new e.PerfCounter,this._captureCameraRenderTime=!1,this._cameraRenderTime=new e.PerfCounter,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=t.onBeforeAnimationsObservable.add((function(){i._captureActiveMeshesEvaluationTime&&i._activeMeshesEvaluationTime.fetchNewFrame(),i._captureRenderTargetsRenderTime&&i._renderTargetsRenderTime.fetchNewFrame(),i._captureFrameTime&&(e.Tools.StartPerformanceCounter("Scene rendering"),i._frameTime.beginMonitoring()),i._captureInterFrameTime&&i._interFrameTime.endMonitoring(),i._captureParticlesRenderTime&&i._particlesRenderTime.fetchNewFrame(),i._captureSpritesRenderTime&&i._spritesRenderTime.fetchNewFrame(),i._captureAnimationsTime&&i._animationsTime.beginMonitoring(),i.scene.getEngine()._drawCalls.fetchNewFrame(),i.scene.getEngine()._textureCollisions.fetchNewFrame()})),this._onAfterRenderObserver=t.onAfterRenderObservable.add((function(){i._captureFrameTime&&(e.Tools.EndPerformanceCounter("Scene rendering"),i._frameTime.endMonitoring()),i._captureRenderTime&&i._renderTime.endMonitoring(!1),i._captureInterFrameTime&&i._interFrameTime.beginMonitoring()}))}return Object.defineProperty(t.prototype,"activeMeshesEvaluationTimeCounter",{get:function(){return this._activeMeshesEvaluationTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureActiveMeshesEvaluationTime",{get:function(){return this._captureActiveMeshesEvaluationTime},set:function(t){var i=this;t!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=t,t?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add((function(){e.Tools.StartPerformanceCounter("Active meshes evaluation"),i._activeMeshesEvaluationTime.beginMonitoring()})),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add((function(){e.Tools.EndPerformanceCounter("Active meshes evaluation"),i._activeMeshesEvaluationTime.endMonitoring()}))):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderTargetsRenderTimeCounter",{get:function(){return this._renderTargetsRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureRenderTargetsRenderTime",{get:function(){return this._captureRenderTargetsRenderTime},set:function(t){var i=this;t!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=t,t?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add((function(){e.Tools.StartPerformanceCounter("Render targets rendering"),i._renderTargetsRenderTime.beginMonitoring()})),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add((function(){e.Tools.EndPerformanceCounter("Render targets rendering"),i._renderTargetsRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"particlesRenderTimeCounter",{get:function(){return this._particlesRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureParticlesRenderTime",{get:function(){return this._captureParticlesRenderTime},set:function(t){var i=this;t!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=t,t?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add((function(){e.Tools.StartPerformanceCounter("Particles"),i._particlesRenderTime.beginMonitoring()})),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add((function(){e.Tools.EndPerformanceCounter("Particles"),i._particlesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"spritesRenderTimeCounter",{get:function(){return this._spritesRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureSpritesRenderTime",{get:function(){return this._captureSpritesRenderTime},set:function(t){var i=this;t!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=t,t?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add((function(){e.Tools.StartPerformanceCounter("Sprites"),i._spritesRenderTime.beginMonitoring()})),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add((function(){e.Tools.EndPerformanceCounter("Sprites"),i._spritesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"physicsTimeCounter",{get:function(){return this._physicsTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"capturePhysicsTime",{get:function(){return this._capturePhysicsTime},set:function(t){var i=this;t!==this._capturePhysicsTime&&(this._capturePhysicsTime=t,t?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add((function(){e.Tools.StartPerformanceCounter("Physics"), +i._physicsTime.beginMonitoring()})),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add((function(){e.Tools.EndPerformanceCounter("Physics"),i._physicsTime.endMonitoring()}))):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationsTimeCounter",{get:function(){return this._animationsTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureAnimationsTime",{get:function(){return this._captureAnimationsTime},set:function(e){var t=this;e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add((function(){t._animationsTime.endMonitoring()})):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"frameTimeCounter",{get:function(){return this._frameTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureFrameTime",{get:function(){return this._captureFrameTime},set:function(e){this._captureFrameTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"interFrameTimeCounter",{get:function(){return this._interFrameTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureInterFrameTime",{get:function(){return this._captureInterFrameTime},set:function(e){this._captureInterFrameTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderTimeCounter",{get:function(){return this._renderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureRenderTime",{get:function(){return this._captureRenderTime},set:function(t){var i=this;t!==this._captureRenderTime&&(this._captureRenderTime=t,t?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add((function(){i._renderTime.beginMonitoring(),e.Tools.StartPerformanceCounter("Main render")})),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add((function(){i._renderTime.endMonitoring(!1),e.Tools.EndPerformanceCounter("Main render")}))):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraRenderTimeCounter",{get:function(){return this._cameraRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureCameraRenderTime",{get:function(){return this._captureCameraRenderTime},set:function(t){var i=this;t!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=t,t?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add((function(t){i._cameraRenderTime.beginMonitoring(),e.Tools.StartPerformanceCounter("Rendering camera "+t.name)})),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add((function(t){i._cameraRenderTime.endMonitoring(!1),e.Tools.EndPerformanceCounter("Rendering camera "+t.name)}))):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"drawCallsCounter",{get:function(){return this.scene.getEngine()._drawCalls},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"textureCollisionsCounter",{get:function(){return this.scene.getEngine()._textureCollisions},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null,this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null,this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null},t})();e.SceneInstrumentation=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this._timeElapsedQueryEnded=!1}return e})();e._TimeToken=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.DIFFUSEDIRECTUV=0,t.GAMMADIFFUSE=!1,t.DIFFUSEHASALPHA=!1,t.OPACITYFRESNEL=!1,t.REFLECTIONBLUR=!1,t.REFLECTIONFRESNEL=!1,t.REFLECTIONFALLOFF=!1,t.TEXTURELODSUPPORT=!1,t.PREMULTIPLYALPHA=!1,t.USERGBCOLOR=!1,t.USEHIGHLIGHTANDSHADOWCOLORS=!1,t.NOISE=!1,t.REFLECTIONBGR=!1,t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=!1,t.CONTRAST=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.EXPOSURE=!1,t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.EQUIRECTANGULAR_RELFECTION_FOV=!1,t.MAINUV1=!1,t.MAINUV2=!1,t.UV1=!1,t.UV2=!1,t.CLIPPLANE=!1,t.POINTSIZE=!1,t.FOG=!1,t.NORMAL=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.SHADOWFLOAT=!1,t.rebuild(),t}return o(t,e),t})(e.MaterialDefines),i=(function(i){function r(t,r){var n=i.call(this,t,r)||this;return n.primaryColor=e.Color3.White(),n._primaryColorShadowLevel=0,n._primaryColorHighlightLevel=0,n.reflectionTexture=null,n.reflectionBlur=0,n.diffuseTexture=null,n._shadowLights=null,n.shadowLights=null,n.shadowLevel=0,n.sceneCenter=e.Vector3.Zero(),n.opacityFresnel=!0,n.reflectionFresnel=!1,n.reflectionFalloffDistance=0,n.reflectionAmount=1,n.reflectionReflectance0=.05,n.reflectionReflectance90=.5,n.useRGBColor=!0,n.enableNoise=!1,n._fovMultiplier=1,n.useEquirectangularFOV=!1,n._maxSimultaneousLights=4,n.maxSimultaneousLights=4,n._imageProcessingObserver=null,n.switchToBGR=!1,n._renderTargets=new e.SmartArray(16),n._reflectionControls=e.Vector4.Zero(),n._white=e.Color3.White(),n._primaryShadowColor=e.Color3.Black(),n._primaryHighlightColor=e.Color3.Black(),n._attachImageProcessingConfiguration(null),n.getRenderTargetTextures=function(){return n._renderTargets.reset(),n._diffuseTexture&&n._diffuseTexture.isRenderTarget&&n._renderTargets.push(n._diffuseTexture),n._reflectionTexture&&n._reflectionTexture.isRenderTarget&&n._renderTargets.push(n._reflectionTexture),n._renderTargets},n}return o(r,i),Object.defineProperty(r.prototype,"_perceptualColor",{get:function(){return this.__perceptualColor},set:function(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"primaryColorShadowLevel",{get:function(){return this._primaryColorShadowLevel},set:function(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"primaryColorHighlightLevel",{get:function(){return this._primaryColorHighlightLevel},set:function(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"reflectionStandardFresnelWeight",{set:function(e){var t=e;t<.5?(t*=2,this.reflectionReflectance0=r.StandardReflectance0*t,this.reflectionReflectance90=r.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=r.StandardReflectance0+(1-r.StandardReflectance0)*t,this.reflectionReflectance90=r.StandardReflectance90+(1-r.StandardReflectance90)*t)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"fovMultiplier",{get:function(){return this._fovMultiplier},set:function(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))},enumerable:!0,configurable:!0}),r.prototype._attachImageProcessingConfiguration=function(e){var t=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((function(e){t._computePrimaryColorFromPerceptualColor(),t._markAllSubMeshesAsImageProcessingDirty()}))))},Object.defineProperty(r.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this.imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorCurves",{get:function(){return this.imageProcessingConfiguration.colorCurves},set:function(e){this.imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),r.prototype.needAlphaTesting=function(){return!0},r.prototype.needAlphaBlending=function(){return this.alpha<0||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha},r.prototype.isReadyForSubMesh=function(i,r,n){var o=this;if(void 0===n&&(n=!1),r.effect&&this.isFrozen&&this._wasPreviouslyReady)return!0;r._materialDefines||(r._materialDefines=new t);var s=this.getScene(),a=r._materialDefines;if(!this.checkReadyOnEveryCall&&r.effect&&a._renderId===s.getRenderId())return!0;var l=s.getEngine();if(e.MaterialHelper.PrepareDefinesForLights(s,i,a,!1,this._maxSimultaneousLights),a._needNormals=!0,a._areTexturesDirty){if(a._needUVs=!1,s.texturesEnabled){if(s.getEngine().getCaps().textureLOD&&(a.TEXTURELODSUPPORT=!0),this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture,a,"DIFFUSE"),a.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,a.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,a.OPACITYFRESNEL=this._opacityFresnel}else a.DIFFUSE=!1,a.DIFFUSEHASALPHA=!1,a.GAMMADIFFUSE=!1,a.OPACITYFRESNEL=!1;var c=this._reflectionTexture;if(c&&e.StandardMaterial.ReflectionTextureEnabled){if(!c.isReadyOrNotBlocking())return!1;switch(a.REFLECTION=!0,a.GAMMAREFLECTION=c.gammaSpace,a.RGBDREFLECTION=c.isRGBD,a.REFLECTIONBLUR=this._reflectionBlur>0,a.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!c.invertZ:c.invertZ,a.LODINREFLECTIONALPHA=c.lodLevelInAlpha,a.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,a.REFLECTIONBGR=this.switchToBGR,c.coordinatesMode===e.Texture.INVCUBIC_MODE&&(a.INVERTCUBICMAP=!0),a.REFLECTIONMAP_3D=c.isCube,c.coordinatesMode){case e.Texture.EXPLICIT_MODE:a.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:a.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:a.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:a.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:a.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:default:a.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(a.REFLECTIONFRESNEL=!0,a.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(a.REFLECTIONFRESNEL=!1,a.REFLECTIONFALLOFF=!1)}else a.REFLECTION=!1,a.REFLECTIONFRESNEL=!1,a.REFLECTIONFALLOFF=!1,a.REFLECTIONBLUR=!1,a.REFLECTIONMAP_3D=!1,a.REFLECTIONMAP_SPHERICAL=!1,a.REFLECTIONMAP_PLANAR=!1,a.REFLECTIONMAP_CUBIC=!1,a.REFLECTIONMAP_PROJECTION=!1,a.REFLECTIONMAP_SKYBOX=!1,a.REFLECTIONMAP_EXPLICIT=!1,a.REFLECTIONMAP_EQUIRECTANGULAR=!1,a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,a.INVERTCUBICMAP=!1,a.REFLECTIONMAP_OPPOSITEZ=!1,a.LODINREFLECTIONALPHA=!1,a.GAMMAREFLECTION=!1,a.RGBDREFLECTION=!1}a.PREMULTIPLYALPHA=this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED||this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF,a.USERGBCOLOR=this._useRGBColor,a.NOISE=this._enableNoise}if(a._areLightsDirty&&(a.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel)),a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a)}if(e.MaterialHelper.PrepareDefinesForMisc(i,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(i),a),e.MaterialHelper.PrepareDefinesForFrameBoundValues(s,l,a,n),e.MaterialHelper.PrepareDefinesForAttributes(i,a,!1,!0,!1)&&i&&(s.getEngine().getCaps().standardDerivatives||i.isVerticesDataPresent(e.VertexBuffer.NormalKind)||(i.createNormals(!0),e.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: "+i.name))),a.isDirty){a.markAsProcessed(),s.resetCachedMaterial();var h=new e.EffectFallbacks;a.FOG&&h.addFallback(0,"FOG"),a.POINTSIZE&&h.addFallback(1,"POINTSIZE"),e.MaterialHelper.HandleFallbacksForShadows(a,h,this._maxSimultaneousLights),a.NUM_BONE_INFLUENCERS>0&&h.addCPUSkinningFallback(0,i);var u=[e.VertexBuffer.PositionKind];a.NORMAL&&u.push(e.VertexBuffer.NormalKind),a.UV1&&u.push(e.VertexBuffer.UVKind),a.UV2&&u.push(e.VertexBuffer.UV2Kind),e.MaterialHelper.PrepareAttributesForBones(u,i,a,h),e.MaterialHelper.PrepareAttributesForInstances(u,a);var d=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","vClipPlane","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"],f=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],p=["Material","Scene"];e.ImageProcessingConfiguration&&(e.ImageProcessingConfiguration.PrepareUniforms(d,a),e.ImageProcessingConfiguration.PrepareSamplers(f,a)),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:a,maxSimultaneousLights:this._maxSimultaneousLights});var _=function(e){o.onCompiled&&o.onCompiled(e),o.bindSceneUniformBuffer(e,s.getSceneUniformBuffer())},m=a.toString();r.setEffect(s.getEngine().createEffect("background",{attributes:u,uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:m,fallbacks:h,onCompiled:_,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},l),a),this.buildUniformLayout()}return!(!r.effect||!r.effect.isReady())&&(a._renderId=s.getRenderId(),this._wasPreviouslyReady=!0,!0)},r.prototype._computePrimaryColorFromPerceptualColor=function(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())},r.prototype._computePrimaryColors=function(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))},r.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.create()},r.prototype.unbind=function(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),i.prototype.unbind.call(this)},r.prototype.bindOnlyWorldMatrix=function(e){this._activeEffect.setMatrix("world",e)},r.prototype.bindForSubMesh=function(t,i,r){var n=this.getScene(),o=r._materialDefines;if(o){var s=r.effect;if(s){this._activeEffect=s,this.bindOnlyWorldMatrix(t),e.MaterialHelper.BindBonesParameters(i,this._activeEffect);var a=this._mustRebind(n,s,i.visibility);if(a){this._uniformBuffer.bindToEffect(s,"Material"),this.bindViewProjection(s);var l=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(n.texturesEnabled&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),e.MaterialHelper.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),l&&e.StandardMaterial.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",l.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),o.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),n.texturesEnabled&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),l&&e.StandardMaterial.ReflectionTextureEnabled&&(o.REFLECTIONBLUR&&o.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",l):o.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",l._lodTextureMid||l),this._uniformBuffer.setTexture("reflectionSamplerLow",l._lodTextureLow||l),this._uniformBuffer.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)):this._uniformBuffer.setTexture("reflectionSampler",l),o.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w)))),e.MaterialHelper.BindClipPlane(this._activeEffect,n),e.MaterialHelper.BindEyePosition(s,n)}!a&&this.isFrozen||(n.lightsEnabled&&e.MaterialHelper.BindLights(n,i,this._activeEffect,o,this._maxSimultaneousLights,!1),this.bindView(s),e.MaterialHelper.BindFogParameters(n,i,this._activeEffect),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(i,this._activeEffect)}}},r.prototype.dispose=function(e,t){void 0===e&&(e=!1),void 0===t&&(t=!1),t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),i.prototype.dispose.call(this,e)},r.prototype.clone=function(t){var i=this;return e.SerializationHelper.Clone((function(){return new r(t,i.getScene())}),this)},r.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.BackgroundMaterial",t},r.prototype.getClassName=function(){return"BackgroundMaterial"},r.Parse=function(t,i,n){return e.SerializationHelper.Parse((function(){return new r(t.name,i)}),t,i,n)},r.StandardReflectance0=.05,r.StandardReflectance90=.5,n([e.serializeAsColor3()],r.prototype,"_primaryColor",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"primaryColor",void 0),n([e.serializeAsColor3()],r.prototype,"__perceptualColor",void 0),n([e.serialize()],r.prototype,"_primaryColorShadowLevel",void 0),n([e.serialize()],r.prototype,"_primaryColorHighlightLevel",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"primaryColorHighlightLevel",null),n([e.serializeAsTexture()],r.prototype,"_reflectionTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionTexture",void 0),n([e.serialize()],r.prototype,"_reflectionBlur",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionBlur",void 0),n([e.serializeAsTexture()],r.prototype,"_diffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"diffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"shadowLights",void 0),n([e.serialize()],r.prototype,"_shadowLevel",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"shadowLevel",void 0),n([e.serializeAsVector3()],r.prototype,"_sceneCenter",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"sceneCenter",void 0),n([e.serialize()],r.prototype,"_opacityFresnel",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"opacityFresnel",void 0),n([e.serialize()],r.prototype,"_reflectionFresnel",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionFresnel",void 0),n([e.serialize()],r.prototype,"_reflectionFalloffDistance",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionFalloffDistance",void 0),n([e.serialize()],r.prototype,"_reflectionAmount",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionAmount",void 0),n([e.serialize()],r.prototype,"_reflectionReflectance0",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionReflectance0",void 0),n([e.serialize()],r.prototype,"_reflectionReflectance90",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionReflectance90",void 0),n([e.serialize()],r.prototype,"_useRGBColor",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useRGBColor",void 0),n([e.serialize()],r.prototype,"_enableNoise",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"enableNoise",void 0),n([e.serialize()],r.prototype,"_maxSimultaneousLights",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"maxSimultaneousLights",void 0),n([e.serializeAsImageProcessingConfiguration()],r.prototype,"_imageProcessingConfiguration",void 0),r})(e.PushMaterial);e.BackgroundMaterial=i})(r||(r={}));var r,s=this&&this.__assign||Object.assign||function(e){for(var t,i=1,r=arguments.length;ii&&(i=2*a,r=i),i*=1.1,r*=1.5,n=o.min.add(s.scale(.5)),n.y=o.min.y-this._options.groundYBias}return{groundSize:i,skyboxSize:r,rootPosition:n}},t.prototype._setupGround=function(t){var i=this;this._ground&&!this._ground.isDisposed()||(this._ground=e.Mesh.CreatePlane("BackgroundPlane",t.groundSize,this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((function(){i._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow},t.prototype._setupGroundMaterial=function(){this._groundMaterial||(this._groundMaterial=new e.BackgroundMaterial("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)},t.prototype._setupGroundDiffuseTexture=function(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof e.BaseTexture)return void(this._groundMaterial.diffuseTexture=this._options.groundTexture);var t=new e.Texture(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler);t.gammaSpace=!1,t.hasAlpha=!0,this._groundMaterial.diffuseTexture=t}},t.prototype._setupGroundMirrorTexture=function(t){var i=e.Texture.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new e.MirrorTexture("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,e.Texture.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new e.Plane(0,-1,0,t.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=i,this._groundMirror.wrapV=i,this._groundMirror.gammaSpace=!1,this._groundMirror.renderList))for(var r=0;rthis.occlusionRetryCount))return;this._isOcclusionQueryInProgress=!1,this._occlusionInternalRetryCounter=0,this._isOccluded=this.occlusionType!==e.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC&&this._isOccluded}}var r=this.getScene();if(r.getBoundingBoxRenderer){var n=r.getBoundingBoxRenderer();this._occlusionQuery||(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(this.occlusionQueryAlgorithmType,this._occlusionQuery),n.renderOcclusionBoundingBox(this),t.endOcclusionQuery(this.occlusionQueryAlgorithmType),this._isOcclusionQueryInProgress=!0}}})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===r&&(r=256),void 0===n&&(n=e.Engine.LastCreatedScene);var a=t.call(this,i,r,"noise",n,o,s)||this;return a._time=0,a.brightness=.2,a.octaves=3,a.persistence=.8,a.animationSpeedFactor=1,a._updateShaderUniforms(),a}return o(i,t),i.prototype._updateShaderUniforms=function(){var e=this.getScene();e&&(this._time+=e.getAnimationRatio()*this.animationSpeedFactor*.01,this.setFloat("brightness",this.brightness),this.setInt("octaves",this.octaves),this.setFloat("persistence",this.persistence),this.setFloat("timeScale",this._time))},i.prototype.render=function(e){this._updateShaderUniforms(),t.prototype.render.call(this,e)},i.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this,t.prototype.serialize.call(this));return i.customType="BABYLON.NoiseProceduralTexture",i},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,t._size,r,void 0,t._generateMipMaps)}),t,r,n)},i})(e.ProceduralTexture);e.NoiseProceduralTexture=t})(r||(r={})),r.Effect.ShadersStore={defaultVertexShader:"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n", +defaultPixelShader:"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#include\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include\n#include\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n",pbrVertexShader:"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include\n\n#include\n\n#include\n\n#include[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include\n}", +pbrPixelShader:"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include\n#include\n#include\n\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n\n#include\nvoid main(void) {\n#include\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include\n#include(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}",rgbdEncodePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}",rgbdDecodePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}",spritesVertexShader:"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}",spritesPixelShader:"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include\ngl_FragColor=color;\n}",particlesVertexShader:"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}",particlesPixelShader:"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}",colorVertexShader:"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}",colorPixelShader:"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}",gpuRenderParticlesVertexShader:"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}",gpuRenderParticlesPixelShader:"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n", +gpuUpdateParticlesVertexShader:"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}",gpuUpdateParticlesPixelShader:"#version 300 es\nvoid main() {\ndiscard;\n}\n",postprocessVertexShader:"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}",passPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}",shadowMapVertexShader:"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n\n#include\n#include\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",shadowMapPixelShader:"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}",depthBoxBlurPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}",proceduralVertexShader:"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}",depthVertexShader:"\nattribute vec3 position;\n#include\n\n#include\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",depthPixelShader:"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}",ssaoPixelShader:"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; imaxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}", depthOfFieldPixelShader:"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n",standardPixelShader:"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminanceshadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n",fxaaVertexShader:"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}",fxaaPixelShader:"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}",sharpenPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}",kernelBlurVertexShader:"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}",kernelBlurPixelShader:"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}",depthOfFieldMergePixelShader:"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n",circleOfConfusionPixelShader:"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n",bloomMergePixelShader:"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n",extractHighlightsPixelShader:"#include\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}",geometryVertexShader:"precision highp float;\nprecision highp int;\n#include\n#include\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include\n#include\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",geometryPixelShader:"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include[3]\n#else\n#include[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}",refractionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}",blackAndWhitePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}", convolutionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}",filterPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}",volumetricLightScatteringPixelShader:"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i\n#include\n#include\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}",lensFlareVertexShader:"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}",lensFlarePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}",anaglyphPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}",stereoscopicInterlacePixelShader:"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}",vrDistortionCorrectionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}",glowBlurPostProcessPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}",glowMapGenerationPixelShader:"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}",glowMapGenerationVertexShader:"\nattribute vec3 position;\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n\n#include\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",glowMapMergePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}",glowMapMergeVertexShader:"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}",lineVertexShader:"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}",linePixelShader:"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}",outlineVertexShader:"\nattribute vec3 position;\nattribute vec3 normal;\n#include\n\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n",outlinePixelShader:"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n}",layerVertexShader:"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}",layerPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}",backgroundVertexShader:"precision highp float;\n#include<__decl__backgroundVertex>\n#include\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n\n#include\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include\n\n#include\n\n#include[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",backgroundPixelShader:"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#include\n#include\n\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n",noisePixelShader:"\n\nuniform float brightness;\nuniform int octaves;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif",instancesDeclaration:"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif",pointCloudVertexDeclaration:"#ifdef POINTSIZE\nuniform float pointSize;\n#endif",bumpVertexDeclaration:"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n",clipPlaneVertexDeclaration:"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif",fogVertexDeclaration:"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif",morphTargetsVertexGlobalDeclaration:"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif",morphTargetsVertexDeclaration:"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif",logDepthDeclaration:"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif",morphTargetsVertex:"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif",instancesVertex:"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif",bonesVertex:"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif",bumpVertex:"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif",clipPlaneVertex:"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif",fogVertex:"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif",shadowsVertex:"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif",pointCloudVertex:"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif",logDepthVertex:"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif",helperFunctions:"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}",lightFragmentDeclaration:"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif", lightsFragmentFunctions:"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}",lightUboDeclaration:"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif",defaultVertexDeclaration:"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n",defaultFragmentDeclaration:"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif",defaultUboDeclaration:"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};",shadowsFragmentFunctions:"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx * @param blockCompilation If the shader should not be compiled imediatly. (default: false) */ - function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) { + function PostProcess( + /** Name of the PostProcess. */ + name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) { if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; } if (defines === void 0) { defines = null; } if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } @@ -68696,6 +68776,7 @@ var BABYLON; */ ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) { if (includeDescendants === void 0) { includeDescendants = true; } + var _a; if (!this._shadowMap) { return this; } @@ -68707,7 +68788,6 @@ var BABYLON; (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes()); } return this; - var _a; }; /** * Helper function to remove a mesh and its descendants from the list of shadow casters @@ -72047,6 +72127,7 @@ var BABYLON; return this.subMaterials[index]; }; MultiMaterial.prototype.getActiveTextures = function () { + var _a; return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { if (subMaterial) { return subMaterial.getActiveTextures(); @@ -72055,7 +72136,6 @@ var BABYLON; return []; } })); - var _a; }; // Methods MultiMaterial.prototype.getClassName = function () { @@ -77718,7 +77798,9 @@ var BABYLON; * @param textureType Type of textures used when performing the post process. (default: 0) * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ - function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) { + function BlurPostProcess(name, + /** The direction in which to blur the image. */ + direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) { if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; } if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } if (defines === void 0) { defines = ""; } @@ -78350,7 +78432,9 @@ var BABYLON; * @param textureType Type of textures used when performing the post process. (default: 0) * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ - function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) { + function BloomMergePostProcess(name, originalFromInput, blurred, + /** Weight of the bloom to be added to the original input. */ + weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) { if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } if (blockCompilation === void 0) { blockCompilation = false; } var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this; @@ -80812,7 +80896,9 @@ var BABYLON; * @param reusable If the post process can be reused on the same frame. (default: false) * @param textureType Type of textures used when performing the post process. (default: 0) */ - function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) { + function ConvolutionPostProcess(name, + /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ + kernel, options, camera, samplingMode, engine, reusable, textureType) { if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this; _this.kernel = kernel; @@ -90055,7 +90141,9 @@ var BABYLON; * Instantiates a UtilityLayerRenderer * @param originalScene the original scene that will be rendered on top of */ - function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) { + function UtilityLayerRenderer( + /** the original scene that will be rendered on top of */ + originalScene) { var _this = this; this.originalScene = originalScene; this._pointerCaptures = {}; @@ -91067,7 +91155,9 @@ var BABYLON; * Creates a gizmo * @param gizmoLayer The utility layer the gizmo will be added to */ - function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) { + function Gizmo( + /** The utility layer the gizmo will be added to */ + gizmoLayer) { if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; } var _this = this; this.gizmoLayer = gizmoLayer; @@ -94572,7 +94662,9 @@ var BABYLON; * @param scene The scene the VRExperienceHelper belongs to. * @param webVROptions Options to modify the vr experience helper's behavior. */ - function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) { + function VRExperienceHelper(scene, + /** Options to modify the vr experience helper's behavior. */ + webVROptions) { if (webVROptions === void 0) { webVROptions = {}; } var _this = this; this.webVROptions = webVROptions; @@ -102546,7 +102638,9 @@ var BABYLON; if (effect.onBind) { effect.onBind(effect); } - effect.onBindObservable.notifyObservers(effect); + if (effect._onBindObservable) { + effect._onBindObservable.notifyObservers(effect); + } }; NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) { if (zOffset === void 0) { zOffset = 0; } diff --git a/dist/preview release/babylon.no-module.max.js b/dist/preview release/babylon.no-module.max.js index 6b1df1503d8..d16a168a7ca 100644 --- a/dist/preview release/babylon.no-module.max.js +++ b/dist/preview release/babylon.no-module.max.js @@ -155,10 +155,6 @@ var BABYLON; * Observable that will be called if an error occurs during shader compilation. */ this.onErrorObservable = new BABYLON.Observable(); - /** - * Observable that will be called when effect is bound. - */ - this.onBindObservable = new BABYLON.Observable(); /** @hidden */ this._bonesComputationForcedToCPU = false; this._uniformBuffersNames = {}; @@ -239,6 +235,19 @@ var BABYLON; }); }); } + Object.defineProperty(Effect.prototype, "onBindObservable", { + /** + * Observable that will be called when effect is bound. + */ + get: function () { + if (!this._onBindObservable) { + this._onBindObservable = new BABYLON.Observable(); + } + return this._onBindObservable; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Effect.prototype, "key", { /** * Unique key for this effect @@ -10449,6 +10458,7 @@ var BABYLON; }; InternalPromise.prototype._moveChildren = function (children) { var _this = this; + var _a; (_a = this._children).push.apply(_a, children.splice(0, children.length)); this._children.forEach(function (child) { child._parent = _this; @@ -10465,7 +10475,6 @@ var BABYLON; child._reject(this._reason); } } - var _a; }; InternalPromise.prototype._resolve = function (value) { try { @@ -13776,7 +13785,7 @@ var BABYLON; * @param effect defines the effect to activate */ Engine.prototype.enableEffect = function (effect) { - if (!effect) { + if (!effect || effect === this._currentEffect) { return; } // Use program @@ -13785,7 +13794,9 @@ var BABYLON; if (effect.onBind) { effect.onBind(effect); } - effect.onBindObservable.notifyObservers(effect); + if (effect._onBindObservable) { + effect._onBindObservable.notifyObservers(effect); + } }; /** * Set the value of an uniform to an array of int32 @@ -30993,19 +31004,6 @@ var BABYLON; if (source === void 0) { source = null; } if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; } var _this = _super.call(this, name, scene) || this; - // Events - /** - * An event triggered before rendering the mesh - */ - _this.onBeforeRenderObservable = new BABYLON.Observable(); - /** - * An event triggered after rendering the mesh - */ - _this.onAfterRenderObservable = new BABYLON.Observable(); - /** - * An event triggered before drawing the mesh - */ - _this.onBeforeDrawObservable = new BABYLON.Observable(); // Members _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE; _this.instances = new Array(); @@ -31028,7 +31026,9 @@ var BABYLON; } // Deep copy BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", - "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]); + "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen", + "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw" + ], ["_poseMatrix"]); // Source mesh _this._source = source; // Metadata @@ -31164,6 +31164,45 @@ var BABYLON; enumerable: true, configurable: true }); + Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", { + /** + * An event triggered before rendering the mesh + */ + get: function () { + if (!this._onBeforeRenderObservable) { + this._onBeforeRenderObservable = new BABYLON.Observable(); + } + return this._onBeforeRenderObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", { + /** + * An event triggered after rendering the mesh + */ + get: function () { + if (!this._onAfterRenderObservable) { + this._onAfterRenderObservable = new BABYLON.Observable(); + } + return this._onAfterRenderObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", { + /** + * An event triggered before drawing the mesh + */ + get: function () { + if (!this._onBeforeDrawObservable) { + this._onBeforeDrawObservable = new BABYLON.Observable(); + } + return this._onBeforeDrawObservable; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Mesh.prototype, "onBeforeDraw", { set: function (callback) { if (this._onBeforeDrawObserver) { @@ -31950,7 +31989,9 @@ var BABYLON; if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) { return this; } - this.onBeforeDrawObservable.notifyObservers(this); + if (this._onBeforeDrawObservable) { + this._onBeforeDrawObservable.notifyObservers(this); + } var scene = this.getScene(); var engine = scene.getEngine(); if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) { @@ -32133,10 +32174,10 @@ var BABYLON; * @returns the current mesh */ Mesh.prototype.render = function (subMesh, enableAlphaMode) { - this._checkOcclusionQuery(); - if (this._isOccluded) { - return this; - } + // this._checkOcclusionQuery(); + // if (this._isOccluded) { + // return this; + // } var scene = this.getScene(); // Managing instances var batch = this._getInstancesRenderList(subMesh._id); @@ -32147,7 +32188,9 @@ var BABYLON; if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) { return this; } - this.onBeforeRenderObservable.notifyObservers(this); + if (this._onBeforeRenderObservable) { + this._onBeforeRenderObservable.notifyObservers(this); + } var engine = scene.getEngine(); var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined); // Material @@ -32231,7 +32274,9 @@ var BABYLON; scene.getOutlineRenderer().render(subMesh, batch, true); engine.setAlphaMode(currentMode); } - this.onAfterRenderObservable.notifyObservers(this); + if (this._onAfterRenderObservable) { + this._onAfterRenderObservable.notifyObservers(this); + } return this; }; Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) { @@ -32527,6 +32572,15 @@ var BABYLON; if (this._geometry) { this._geometry.releaseForMesh(this, true); } + if (this._onBeforeDrawObservable) { + this._onBeforeDrawObservable.clear(); + } + if (this._onBeforeRenderObservable) { + this._onBeforeRenderObservable.clear(); + } + if (this._onAfterRenderObservable) { + this._onAfterRenderObservable.clear(); + } // Sources var meshes = this.getScene().meshes; meshes.forEach(function (abstractMesh) { @@ -34622,14 +34676,6 @@ var BABYLON; * An event triggered when the material is disposed */ this.onDisposeObservable = new BABYLON.Observable(); - /** - * An event triggered when the material is bound - */ - this.onBindObservable = new BABYLON.Observable(); - /** - * An event triggered when the material is unbound - */ - this.onUnBindObservable = new BABYLON.Observable(); /** * Stores the value of the alpha mode */ @@ -34899,6 +34945,19 @@ var BABYLON; enumerable: true, configurable: true }); + Object.defineProperty(Material.prototype, "onBindObservable", { + /** + * An event triggered when the material is bound + */ + get: function () { + if (!this._onBindObservable) { + this._onBindObservable = new BABYLON.Observable(); + } + return this._onBindObservable; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Material.prototype, "onBind", { /** * Called during a bind event @@ -34912,6 +34971,19 @@ var BABYLON; enumerable: true, configurable: true }); + Object.defineProperty(Material.prototype, "onUnBindObservable", { + /** + * An event triggered when the material is unbound + */ + get: function () { + if (!this._onUnBindObservable) { + this._onUnBindObservable = new BABYLON.Observable(); + } + return this._onUnBindObservable; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Material.prototype, "alphaMode", { /** * Gets the value of the alpha mode @@ -35243,8 +35315,8 @@ var BABYLON; else { this._scene._cachedVisibility = 1; } - if (mesh) { - this.onBindObservable.notifyObservers(mesh); + if (this._onBindObservable && mesh) { + this._onBindObservable.notifyObservers(mesh); } if (this.disableDepthWrite) { var engine = this._scene.getEngine(); @@ -35256,7 +35328,9 @@ var BABYLON; * Unbinds the material from the mesh */ Material.prototype.unbind = function () { - this.onUnBindObservable.notifyObservers(this); + if (this._onUnBindObservable) { + this._onUnBindObservable.notifyObservers(this); + } if (this.disableDepthWrite) { var engine = this._scene.getEngine(); engine.setDepthWrite(this._cachedDepthWriteState); @@ -35506,8 +35580,12 @@ var BABYLON; // Callback this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); - this.onBindObservable.clear(); - this.onUnBindObservable.clear(); + if (this._onBindObservable) { + this._onBindObservable.clear(); + } + if (this._onUnBindObservable) { + this._onUnBindObservable.clear(); + } }; /** * Serializes this material @@ -41767,7 +41845,7 @@ var BABYLON; StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { if (useInstances === void 0) { useInstances = false; } if (subMesh.effect && this.isFrozen) { - if (this._wasPreviouslyReady && subMesh.effect) { + if (this._wasPreviouslyReady) { return true; } } @@ -67584,7 +67662,9 @@ var BABYLON; * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx * @param blockCompilation If the shader should not be compiled imediatly. (default: false) */ - function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) { + function PostProcess( + /** Name of the PostProcess. */ + name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) { if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; } if (defines === void 0) { defines = null; } if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } @@ -68663,6 +68743,7 @@ var BABYLON; */ ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) { if (includeDescendants === void 0) { includeDescendants = true; } + var _a; if (!this._shadowMap) { return this; } @@ -68674,7 +68755,6 @@ var BABYLON; (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes()); } return this; - var _a; }; /** * Helper function to remove a mesh and its descendants from the list of shadow casters @@ -72014,6 +72094,7 @@ var BABYLON; return this.subMaterials[index]; }; MultiMaterial.prototype.getActiveTextures = function () { + var _a; return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { if (subMaterial) { return subMaterial.getActiveTextures(); @@ -72022,7 +72103,6 @@ var BABYLON; return []; } })); - var _a; }; // Methods MultiMaterial.prototype.getClassName = function () { @@ -77685,7 +77765,9 @@ var BABYLON; * @param textureType Type of textures used when performing the post process. (default: 0) * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ - function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) { + function BlurPostProcess(name, + /** The direction in which to blur the image. */ + direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) { if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; } if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } if (defines === void 0) { defines = ""; } @@ -78317,7 +78399,9 @@ var BABYLON; * @param textureType Type of textures used when performing the post process. (default: 0) * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ - function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) { + function BloomMergePostProcess(name, originalFromInput, blurred, + /** Weight of the bloom to be added to the original input. */ + weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) { if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } if (blockCompilation === void 0) { blockCompilation = false; } var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this; @@ -80779,7 +80863,9 @@ var BABYLON; * @param reusable If the post process can be reused on the same frame. (default: false) * @param textureType Type of textures used when performing the post process. (default: 0) */ - function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) { + function ConvolutionPostProcess(name, + /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ + kernel, options, camera, samplingMode, engine, reusable, textureType) { if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this; _this.kernel = kernel; @@ -90022,7 +90108,9 @@ var BABYLON; * Instantiates a UtilityLayerRenderer * @param originalScene the original scene that will be rendered on top of */ - function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) { + function UtilityLayerRenderer( + /** the original scene that will be rendered on top of */ + originalScene) { var _this = this; this.originalScene = originalScene; this._pointerCaptures = {}; @@ -91034,7 +91122,9 @@ var BABYLON; * Creates a gizmo * @param gizmoLayer The utility layer the gizmo will be added to */ - function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) { + function Gizmo( + /** The utility layer the gizmo will be added to */ + gizmoLayer) { if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; } var _this = this; this.gizmoLayer = gizmoLayer; @@ -94539,7 +94629,9 @@ var BABYLON; * @param scene The scene the VRExperienceHelper belongs to. * @param webVROptions Options to modify the vr experience helper's behavior. */ - function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) { + function VRExperienceHelper(scene, + /** Options to modify the vr experience helper's behavior. */ + webVROptions) { if (webVROptions === void 0) { webVROptions = {}; } var _this = this; this.webVROptions = webVROptions; @@ -102513,7 +102605,9 @@ var BABYLON; if (effect.onBind) { effect.onBind(effect); } - effect.onBindObservable.notifyObservers(effect); + if (effect._onBindObservable) { + effect._onBindObservable.notifyObservers(effect); + } }; NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) { if (zOffset === void 0) { zOffset = 0; } diff --git a/dist/preview release/babylon.worker.js b/dist/preview release/babylon.worker.js index 71a72e5347b..063a4f7b582 100644 --- a/dist/preview release/babylon.worker.js +++ b/dist/preview release/babylon.worker.js @@ -1,63 +1,64 @@ -!(function(e,t){var i=[],r=e.CANNON||this.CANNON,n=e.OIMO||this.OIMO,o=e.earcut||this.earcut;if("object"==typeof exports&&"object"==typeof module){try{r=r||require("cannon")}catch(e){}try{n=n||require("oimo")}catch(e){}try{o=o||require("earcut")}catch(e){}module.exports=t(r,n,o)}else if("function"==typeof define&&define.amd)require.specified&&require.specified("cannon")&&i.push("cannon"),require.specified&&require.specified("oimo")&&i.push("oimo"),require.specified&&require.specified("earcut")&&i.push("earcut"),define("babylonjs",i,t);else if("object"==typeof exports){try{r=r||require("cannon")}catch(e){}try{n=n||require("oimo")}catch(e){}try{o=o||require("earcut")}catch(e){}exports.babylonjs=t(r,n,o)}else e.BABYLON=t(r,n,o)})(this,(function(e,t,i){e=e||this.CANNON,t=t||this.OIMO,i=i||this.earcut;var r,n=this&&this.__decorate||function(e,t,i,r){var n,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,i,s):n(t,i))||s);return o>3&&s&&Object.defineProperty(t,i,s),s},o=this&&this.__extends||(function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])};return function(t,i){function r(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}})();!(function(e){var t=(function(){function e(){this._defines={},this._currentRank=32,this._maxRank=-1}return e.prototype.unBindMesh=function(){this._mesh=null},e.prototype.addFallback=function(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)},e.prototype.addCPUSkinningFallback=function(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)},Object.defineProperty(e.prototype,"isMoreFallbacks",{get:function(){return this._currentRank<=this._maxRank},enumerable:!0,configurable:!0}),e.prototype.reduce=function(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0&&this._mesh.material){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;for(var i=this._mesh.getScene(),r=0;r-1?i:e.Engine.ShadersRepository+i,this._engine._loadFile(n+".vertex.fx",r)},t.prototype._loadFragmentShader=function(i,r){if(e.Tools.IsWindowObjectExist()&&i instanceof HTMLElement){return void r(e.Tools.GetDOMTextContent(i))}if("base64:"===i.substr(0,7)){return void r(window.atob(i.substr(7)))}if(t.ShadersStore[i+"PixelShader"])return void r(t.ShadersStore[i+"PixelShader"]);if(t.ShadersStore[i+"FragmentShader"])return void r(t.ShadersStore[i+"FragmentShader"]);var n;n="."===i[0]||"/"===i[0]||i.indexOf("http")>-1?i:e.Engine.ShadersRepository+i,this._engine._loadFile(n+".fragment.fx",r)},t.prototype._dumpShadersSource=function(t,i,r){var n=this._engine.webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"",o=n+(r?r+"\n":"");t=o+t,i=o+i;var s=2,a=/\n/gm,l="\n1\t"+t.replace(a,(function(){return"\n"+s+++"\t"}));s=2;var h="\n1\t"+i.replace(a,(function(){return"\n"+s+++"\t"}));this.name.vertexElement?(e.Tools.Error("Vertex shader: "+this.name.vertexElement+l),e.Tools.Error("Fragment shader: "+this.name.fragmentElement+h)):this.name.vertex?(e.Tools.Error("Vertex shader: "+this.name.vertex+l),e.Tools.Error("Fragment shader: "+this.name.fragment+h)):(e.Tools.Error("Vertex shader: "+this.name+l),e.Tools.Error("Fragment shader: "+this.name+h))},t.prototype._processShaderConversion=function(e,t,i){var r=this._processPrecision(e);if(1==this._engine.webGLVersion)return void i(r);if(-1!==r.indexOf("#version 3"))return void i(r.replace("#version 300 es",""));var n=-1!==r.search(/#extension.+GL_EXT_draw_buffers.+require/),o=/#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,s=r.replace(o,"");s=s.replace(/varying(?![\n\r])\s/g,t?"in ":"out "),s=s.replace(/attribute[ \t]/g,"in "),s=s.replace(/[ \t]attribute/g," in"),t&&(s=s.replace(/texture2DLodEXT\s*\(/g,"textureLod("),s=s.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),s=s.replace(/texture2D\s*\(/g,"texture("),s=s.replace(/textureCube\s*\(/g,"texture("),s=s.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),s=s.replace(/gl_FragColor/g,"glFragColor"),s=s.replace(/gl_FragData/g,"glFragData"),s=s.replace(/void\s+?main\s*\(/g,(n?"":"out vec4 glFragColor;\n")+"void main(")),i(s)},t.prototype._processIncludes=function(i,r){for(var n=this,o=/#include<(.+)>(\((.*)\))*(\[(.*)\])*/g,s=o.exec(i),a=new String(i);null!=s;){var l=s[1];if(-1!==l.indexOf("__decl__")&&(l=l.replace(/__decl__/,""),this._engine.supportsUniformBuffers&&(l=l.replace(/Vertex/,"Ubo"),l=l.replace(/Fragment/,"Ubo")),l+="Declaration"),!t.IncludesShadersStore[l]){var h=e.Engine.ShadersRepository+"ShadersInclude/"+l+".fx";return void this._engine._loadFile(h,(function(e){t.IncludesShadersStore[l]=e,n._processIncludes(a,r)}))}var c=t.IncludesShadersStore[l];if(s[2])for(var u=s[3].split(","),f=0;fr.x?r.x:n,n=nr.y?r.y:o,o=oi.x?e.x:i.x,e.y>i.y?e.y:i.y)},t.Transform=function(e,i){var r=t.Zero();return t.TransformToRef(e,i,r),r},t.TransformToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+t.m[13];i.x=r,i.y=n},t.PointInTriangle=function(e,t,i,r){var n=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),o=n<0?-1:1,s=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*o,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*o;return s>0&&a>0&&s+a<2*n*o},t.Distance=function(e,i){return Math.sqrt(t.DistanceSquared(e,i))},t.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y;return i*i+r*r},t.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},t.DistanceOfPointFromSegment=function(e,i,r){ -var n=t.DistanceSquared(i,r);if(0===n)return t.Distance(e,i);var o=r.subtract(i),s=Math.max(0,Math.min(1,t.Dot(e.subtract(i),o)/n)),a=i.add(o.multiplyByFloats(s,s));return t.Distance(e,a)},t})();e.Vector2=r;var n=(function(){function t(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this.x=e,this.y=t,this.z=i}return t.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+"}"},t.prototype.getClassName=function(){return"Vector3"},t.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0)},t.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},t.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,this},t.prototype.toQuaternion=function(){return e.Quaternion.RotationYawPitchRoll(this.x,this.y,this.z)},t.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this},t.prototype.add=function(e){return new t(this.x+e.x,this.y+e.y,this.z+e.z)},t.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,this},t.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this},t.prototype.subtract=function(e){return new t(this.x-e.x,this.y-e.y,this.z-e.z)},t.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,this},t.prototype.subtractFromFloats=function(e,i,r){return new t(this.x-e,this.y-i,this.z-r)},t.prototype.subtractFromFloatsToRef=function(e,t,i,r){return r.x=this.x-e,r.y=this.y-t,r.z=this.z-i,this},t.prototype.negate=function(){return new t(-this.x,-this.y,-this.z)},t.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this},t.prototype.scale=function(e){return new t(this.x*e,this.y*e,this.z*e)},t.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,this},t.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,this},t.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z},t.prototype.equalsWithEpsilon=function(t,i){return void 0===i&&(i=e.Epsilon),t&&e.Scalar.WithinEpsilon(this.x,t.x,i)&&e.Scalar.WithinEpsilon(this.y,t.y,i)&&e.Scalar.WithinEpsilon(this.z,t.z,i)},t.prototype.equalsToFloats=function(e,t,i){return this.x===e&&this.y===t&&this.z===i},t.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this},t.prototype.multiply=function(e){return new t(this.x*e.x,this.y*e.y,this.z*e.z)},t.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,this},t.prototype.multiplyByFloats=function(e,i,r){return new t(this.x*e,this.y*i,this.z*r)},t.prototype.divide=function(e){return new t(this.x/e.x,this.y/e.y,this.z/e.z)},t.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,this},t.prototype.divideInPlace=function(e){return this.divideToRef(e,this)},t.prototype.minimizeInPlace=function(e){return e.xthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),this},Object.defineProperty(t.prototype,"isNonUniform",{get:function(){var e=Math.abs(this.x),t=Math.abs(this.y);if(e!==t)return!0;var i=Math.abs(this.z);return e!==i||t!==i},enumerable:!0,configurable:!0}),t.prototype.floor=function(){return new t(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))},t.prototype.fract=function(){return new t(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z))},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},t.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},t.prototype.normalize=function(){var e=this.length();if(0===e||1===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this},t.prototype.normalizeToNew=function(){var e=new t(0,0,0);return this.normalizeToRef(e),e},t.prototype.normalizeToRef=function(e){var t=this.length();if(0===t||1===t)return e.set(this.x,this.y,this.z),e;var i=1/t;return this.scaleToRef(i,e),e},t.prototype.clone=function(){return new t(this.x,this.y,this.z)},t.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this},t.prototype.copyFromFloats=function(e,t,i){return this.x=e,this.y=t,this.z=i,this},t.prototype.set=function(e,t,i){return this.copyFromFloats(e,t,i)},t.GetClipFactor=function(e,i,r,n){var o=t.Dot(e,r)-n;return o/(o-(t.Dot(i,r)-n))},t.GetAngleBetweenVectors=function(e,i,r){var n=e.clone().normalize(),o=i.clone().normalize(),s=t.Dot(n,o),a=t.Cross(n,o);return t.Dot(a,r)>0?Math.acos(s):-Math.acos(s)},t.FromArray=function(e,i){return i||(i=0),new t(e[i],e[i+1],e[i+2])},t.FromFloatArray=function(e,i){return t.FromArray(e,i)},t.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2]},t.FromFloatArrayToRef=function(e,i,r){return t.FromArrayToRef(e,i,r)},t.FromFloatsToRef=function(e,t,i,r){r.x=e,r.y=t,r.z=i},t.Zero=function(){return new t(0,0,0)},t.One=function(){return new t(1,1,1)},t.Up=function(){return new t(0,1,0)},t.Down=function(){return new t(0,-1,0)},t.Forward=function(){return new t(0,0,1)},t.Right=function(){return new t(1,0,0)},t.Left=function(){return new t(-1,0,0)},t.TransformCoordinates=function(e,i){var r=t.Zero();return t.TransformCoordinatesToRef(e,i,r),r},t.TransformCoordinatesToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9]+t.m[13],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10]+t.m[14],s=e.x*t.m[3]+e.y*t.m[7]+e.z*t.m[11]+t.m[15];i.x=r/s,i.y=n/s,i.z=o/s},t.TransformCoordinatesFromFloatsToRef=function(e,t,i,r,n){var o=e*r.m[0]+t*r.m[4]+i*r.m[8]+r.m[12],s=e*r.m[1]+t*r.m[5]+i*r.m[9]+r.m[13],a=e*r.m[2]+t*r.m[6]+i*r.m[10]+r.m[14],l=e*r.m[3]+t*r.m[7]+i*r.m[11]+r.m[15];n.x=o/l,n.y=s/l,n.z=a/l},t.TransformNormal=function(e,i){var r=t.Zero();return t.TransformNormalToRef(e,i,r),r},t.TransformNormalToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10];i.x=r,i.y=n,i.z=o},t.TransformNormalFromFloatsToRef=function(e,t,i,r,n){n.x=e*r.m[0]+t*r.m[4]+i*r.m[8],n.y=e*r.m[1]+t*r.m[5]+i*r.m[9],n.z=e*r.m[2]+t*r.m[6]+i*r.m[10]},t.CatmullRom=function(e,i,r,n,o){var s=o*o,a=o*s;return new t(.5*(2*i.x+(-e.x+r.x)*o+(2*e.x-5*i.x+4*r.x-n.x)*s+(-e.x+3*i.x-3*r.x+n.x)*a),.5*(2*i.y+(-e.y+r.y)*o+(2*e.y-5*i.y+4*r.y-n.y)*s+(-e.y+3*i.y-3*r.y+n.y)*a),.5*(2*i.z+(-e.z+r.z)*o+(2*e.z-5*i.z+4*r.z-n.z)*s+(-e.z+3*i.z-3*r.z+n.z)*a))},t.Clamp=function(e,i,r){var n=e.x;n=n>r.x?r.x:n,n=nr.y?r.y:o,o=or.z?r.z:s,s=sthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this},t.prototype.floor=function(){return new t(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))},t.prototype.fract=function(){return new t(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},t.prototype.normalize=function(){var e=this.length();if(0===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toVector3=function(){return new n(this.x,this.y,this.z)},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},t.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},t.prototype.set=function(e,t,i,r){return this.copyFromFloats(e,t,i,r)},t.FromArray=function(e,i){return i||(i=0),new t(e[i],e[i+1],e[i+2],e[i+3])},t.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3]},t.FromFloatArrayToRef=function(e,i,r){t.FromArrayToRef(e,i,r)},t.FromFloatsToRef=function(e,t,i,r,n){n.x=e,n.y=t,n.z=i,n.w=r},t.Zero=function(){return new t(0,0,0,0)},t.One=function(){return new t(1,1,1,1)},t.Normalize=function(e){var i=t.Zero();return t.NormalizeToRef(e,i),i},t.NormalizeToRef=function(e,t){t.copyFrom(e),t.normalize()},t.Minimize=function(e,t){var i=e.clone();return i.minimizeInPlace(t),i},t.Maximize=function(e,t){var i=e.clone();return i.maximizeInPlace(t),i},t.Distance=function(e,i){return Math.sqrt(t.DistanceSquared(e,i))},t.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y,n=e.z-t.z,o=e.w-t.w;return i*i+r*r+n*n+o*o},t.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},t.TransformNormal=function(e,i){var r=t.Zero();return t.TransformNormalToRef(e,i,r),r},t.TransformNormalToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10];i.x=r,i.y=n,i.z=o,i.w=e.w},t.TransformNormalFromFloatsToRef=function(e,t,i,r,n,o){o.x=e*n.m[0]+t*n.m[4]+i*n.m[8],o.y=e*n.m[1]+t*n.m[5]+i*n.m[9],o.z=e*n.m[2]+t*n.m[6]+i*n.m[10],o.w=r},t})();e.Vector4=o;var s=(function(){function e(e,t){this.width=e,this.height=t}return e.prototype.toString=function(){return"{W: "+this.width+", H: "+this.height+"}"},e.prototype.getClassName=function(){return"Size"},e.prototype.getHashCode=function(){var e=this.width||0;return e=397*e^(this.height||0)},e.prototype.copyFrom=function(e){this.width=e.width,this.height=e.height},e.prototype.copyFromFloats=function(e,t){return this.width=e,this.height=t,this},e.prototype.set=function(e,t){return this.copyFromFloats(e,t)},e.prototype.multiplyByFloats=function(t,i){return new e(this.width*t,this.height*i)},e.prototype.clone=function(){return new e(this.width,this.height)},e.prototype.equals=function(e){return!!e&&(this.width===e.width&&this.height===e.height)},Object.defineProperty(e.prototype,"surface",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),e.Zero=function(){return new e(0,0)},e.prototype.add=function(t){return new e(this.width+t.width,this.height+t.height)},e.prototype.subtract=function(t){return new e(this.width-t.width,this.height-t.height)},e.Lerp=function(t,i,r){return new e(t.width+(i.width-t.width)*r,t.height+(i.height-t.height)*r)},e})();e.Size=s;var a=(function(){function e(e,t,i,r){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=1),this.x=e,this.y=t,this.z=i,this.w=r}return e.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},e.prototype.getClassName=function(){return"Quaternion"},e.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0),e=397*e^(this.w||0)},e.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},e.prototype.clone=function(){return new e(this.x,this.y,this.z,this.w)},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},e.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},e.prototype.set=function(e,t,i,r){return this.copyFromFloats(e,t,i,r)},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},e.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},e.prototype.scale=function(t){return new e(this.x*t,this.y*t,this.z*t,this.w*t)},e.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e,this},e.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,t.w+=this.w*e,this},e.prototype.multiply=function(t){var i=new e(0,0,0,1);return this.multiplyToRef(t,i),i},e.prototype.multiplyToRef=function(e,t){var i=this.x*e.w+this.y*e.z-this.z*e.y+this.w*e.x,r=-this.x*e.z+this.y*e.w+this.z*e.x+this.w*e.y,n=this.x*e.y-this.y*e.x+this.z*e.w+this.w*e.z,o=-this.x*e.x-this.y*e.y-this.z*e.z+this.w*e.w;return t.copyFromFloats(i,r,n,o),this},e.prototype.multiplyInPlace=function(e){return this.multiplyToRef(e,this),this},e.prototype.conjugateToRef=function(e){return e.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},e.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},e.prototype.conjugate=function(){return new e(-this.x,-this.y,-this.z,this.w)},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.prototype.normalize=function(){var e=1/this.length();return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.toEulerAngles=function(e){void 0===e&&(e="YZX");var t=n.Zero();return this.toEulerAnglesToRef(t,e),t},e.prototype.toEulerAnglesToRef=function(e,t){void 0===t&&(t="YZX");var i=this.z,r=this.x,n=this.y,o=this.w,s=o*o,a=i*i,l=r*r,h=n*n,c=n*i-r*o;return c<-.4999999?(e.y=2*Math.atan2(n,o),e.x=Math.PI/2,e.z=0):c>.4999999?(e.y=2*Math.atan2(n,o),e.x=-Math.PI/2,e.z=0):(e.z=Math.atan2(2*(r*n+i*o),-a-l+h+s),e.x=Math.asin(-2*(i*n-r*o)),e.y=Math.atan2(2*(i*r+n*o),a-l-h+s)),this},e.prototype.toRotationMatrix=function(e){var t=this.x*this.x,i=this.y*this.y,r=this.z*this.z,n=this.x*this.y,o=this.z*this.w,s=this.z*this.x,a=this.y*this.w,l=this.y*this.z,h=this.x*this.w;return e.m[0]=1-2*(i+r),e.m[1]=2*(n+o),e.m[2]=2*(s-a),e.m[3]=0,e.m[4]=2*(n-o),e.m[5]=1-2*(r+t),e.m[6]=2*(l+h),e.m[7]=0,e.m[8]=2*(s+a),e.m[9]=2*(l-h),e.m[10]=1-2*(i+t),e.m[11]=0,e.m[12]=0,e.m[13]=0,e.m[14]=0,e.m[15]=1,e._markAsUpdated(),this},e.prototype.fromRotationMatrix=function(t){return e.FromRotationMatrixToRef(t,this),this},e.FromRotationMatrix=function(t){var i=new e;return e.FromRotationMatrixToRef(t,i),i},e.FromRotationMatrixToRef=function(e,t){var i,r=e.m,n=r[0],o=r[4],s=r[8],a=r[1],l=r[5],h=r[9],c=r[2],u=r[6],f=r[10],d=n+l+f;d>0?(i=.5/Math.sqrt(d+1),t.w=.25/i,t.x=(u-h)*i,t.y=(s-c)*i,t.z=(a-o)*i):n>l&&n>f?(i=2*Math.sqrt(1+n-l-f),t.w=(u-h)/i,t.x=.25*i,t.y=(o+a)/i,t.z=(s+c)/i):l>f?(i=2*Math.sqrt(1+l-n-f),t.w=(s-c)/i,t.x=(o+a)/i,t.y=.25*i,t.z=(h+u)/i):(i=2*Math.sqrt(1+f-n-l),t.w=(a-o)/i,t.x=(s+c)/i,t.y=(h+u)/i,t.z=.25*i)},e.Dot=function(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w},e.AreClose=function(t,i){return e.Dot(t,i)>=0},e.Zero=function(){return new e(0,0,0,0)},e.Inverse=function(t){return new e(-t.x,-t.y,-t.z,t.w)},e.Identity=function(){return new e(0,0,0,1)},e.IsIdentity=function(e){return e&&0===e.x&&0===e.y&&0===e.z&&1===e.w},e.RotationAxis=function(t,i){return e.RotationAxisToRef(t,i,new e)},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(t/2);return e.normalize(),i.w=Math.cos(t/2),i.x=e.x*r,i.y=e.y*r,i.z=e.z*r,i},e.FromArray=function(t,i){return i||(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){var n=.5*i,o=.5*t,s=.5*e,a=Math.sin(n),l=Math.cos(n),h=Math.sin(o),c=Math.cos(o),u=Math.sin(s),f=Math.cos(s);r.x=f*h*l+u*c*a,r.y=u*c*l-f*h*a,r.z=f*c*a-u*h*l,r.w=f*c*l+u*h*a},e.RotationAlphaBetaGamma=function(t,i,r){var n=new e;return e.RotationAlphaBetaGammaToRef(t,i,r,n),n},e.RotationAlphaBetaGammaToRef=function(e,t,i,r){var n=.5*(i+e),o=.5*(i-e),s=.5*t;r.x=Math.cos(o)*Math.sin(s),r.y=Math.sin(o)*Math.sin(s),r.z=Math.sin(n)*Math.cos(s),r.w=Math.cos(n)*Math.cos(s)},e.RotationQuaternionFromAxis=function(t,i,r){var n=new e(0,0,0,0);return e.RotationQuaternionFromAxisToRef(t,i,r,n),n},e.RotationQuaternionFromAxisToRef=function(t,i,r,n){var o=E.Matrix[0];l.FromXYZAxesToRef(t.normalize(),i.normalize(),r.normalize(),o),e.FromRotationMatrixToRef(o,n)},e.Slerp=function(t,i,r){var n=e.Identity();return e.SlerpToRef(t,i,r,n),n},e.SlerpToRef=function(e,t,i,r){var n,o,s=e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w,a=!1;if(s<0&&(a=!0,s=-s),s>.999999)o=1-i,n=a?-i:i;else{var l=Math.acos(s),h=1/Math.sin(l);o=Math.sin((1-i)*l)*h,n=a?-Math.sin(i*l)*h:Math.sin(i*l)*h}r.x=o*e.x+n*t.x,r.y=o*e.y+n*t.y,r.z=o*e.z+n*t.z,r.w=o*e.w+n*t.w},e.Hermite=function(t,i,r,n,o){var s=o*o,a=o*s,l=2*a-3*s+1,h=-2*a+3*s,c=a-2*s+o,u=a-s;return new e(t.x*l+r.x*h+i.x*c+n.x*u,t.y*l+r.y*h+i.y*c+n.y*u,t.z*l+r.z*h+i.z*c+n.z*u,t.w*l+r.w*h+i.w*c+n.w*u)},e})();e.Quaternion=a;var l=(function(){function e(){this._isIdentity=!1,this._isIdentityDirty=!0,this.m=new Float32Array(16),this._markAsUpdated()}return e.prototype._markAsUpdated=function(){this.updateFlag=e._updateFlagSeed++,this._isIdentityDirty=!0},e.prototype.isIdentity=function(e){return void 0===e&&(e=!1),this._isIdentityDirty&&(this._isIdentityDirty=!1,1!==this.m[0]||1!==this.m[5]||1!==this.m[15]?this._isIdentity=!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?this._isIdentity=!1:this._isIdentity=!0,e||1===this.m[10]||(this._isIdentity=!1)),this._isIdentity},e.prototype.determinant=function(){var e=this.m[10]*this.m[15]-this.m[11]*this.m[14],t=this.m[9]*this.m[15]-this.m[11]*this.m[13],i=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],n=this.m[8]*this.m[14]-this.m[10]*this.m[12],o=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*e-this.m[6]*t+this.m[7]*i)-this.m[1]*(this.m[4]*e-this.m[6]*r+this.m[7]*n)+this.m[2]*(this.m[4]*t-this.m[5]*r+this.m[7]*o)-this.m[3]*(this.m[4]*i-this.m[5]*n+this.m[6]*o)},e.prototype.toArray=function(){return this.m},e.prototype.asArray=function(){return this.toArray()},e.prototype.invert=function(){return this.invertToRef(this),this},e.prototype.reset=function(){for(var e=0;e<16;e++)this.m[e]=0;return this._markAsUpdated(),this},e.prototype.add=function(t){var i=new e;return this.addToRef(t,i),i},e.prototype.addToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]=this.m[i]+e.m[i];return t._markAsUpdated(),this},e.prototype.addToSelf=function(e){for(var t=0;t<16;t++)this.m[t]+=e.m[t];return this._markAsUpdated(),this},e.prototype.invertToRef=function(e){var t=this.m[0],i=this.m[1],r=this.m[2],n=this.m[3],o=this.m[4],s=this.m[5],a=this.m[6],l=this.m[7],h=this.m[8],c=this.m[9],u=this.m[10],f=this.m[11],d=this.m[12],p=this.m[13],m=this.m[14],_=this.m[15],g=u*_-f*m,v=c*_-f*p,y=c*m-u*p,b=h*_-f*d,x=h*m-u*d,T=h*p-c*d,E=s*g-a*v+l*y,P=-(o*g-a*b+l*x),A=o*v-s*b+l*T,M=-(o*y-s*x+a*T),S=1/(t*E+i*P+r*A+n*M),R=a*_-l*m,C=s*_-l*p,O=s*m-a*p,D=o*_-l*d,I=o*m-a*d,w=o*p-s*d,L=a*f-l*u,F=s*f-l*c,B=s*u-a*c,V=o*f-l*h,N=o*u-a*h,U=o*c-s*h;return e.m[0]=E*S,e.m[4]=P*S,e.m[8]=A*S,e.m[12]=M*S,e.m[1]=-(i*g-r*v+n*y)*S,e.m[5]=(t*g-r*b+n*x)*S,e.m[9]=-(t*v-i*b+n*T)*S,e.m[13]=(t*y-i*x+r*T)*S,e.m[2]=(i*R-r*C+n*O)*S,e.m[6]=-(t*R-r*D+n*I)*S,e.m[10]=(t*C-i*D+n*w)*S,e.m[14]=-(t*O-i*I+r*w)*S,e.m[3]=-(i*L-r*F+n*B)*S,e.m[7]=(t*L-r*V+n*N)*S,e.m[11]=-(t*F-i*V+n*U)*S,e.m[15]=(t*B-i*N+r*U)*S,e._markAsUpdated(),this},e.prototype.setTranslationFromFloats=function(e,t,i){return this.m[12]=e,this.m[13]=t,this.m[14]=i,this._markAsUpdated(),this},e.prototype.setTranslation=function(e){return this.m[12]=e.x,this.m[13]=e.y,this.m[14]=e.z,this._markAsUpdated(),this},e.prototype.getTranslation=function(){return new n(this.m[12],this.m[13],this.m[14])},e.prototype.getTranslationToRef=function(e){return e.x=this.m[12],e.y=this.m[13],e.z=this.m[14],this},e.prototype.removeRotationAndScaling=function(){return this.setRowFromFloats(0,1,0,0,0),this.setRowFromFloats(1,0,1,0,0),this.setRowFromFloats(2,0,0,1,0),this},e.prototype.multiply=function(t){var i=new e;return this.multiplyToRef(t,i),i},e.prototype.copyFrom=function(e){for(var t=0;t<16;t++)this.m[t]=e.m[t];return this._markAsUpdated(),this},e.prototype.copyToArray=function(e,t){void 0===t&&(t=0);for(var i=0;i<16;i++)e[t+i]=this.m[i];return this},e.prototype.multiplyToRef=function(e,t){return this.multiplyToArray(e,t.m,0),t._markAsUpdated(),this},e.prototype.multiplyToArray=function(e,t,i){var r=this.m[0],n=this.m[1],o=this.m[2],s=this.m[3],a=this.m[4],l=this.m[5],h=this.m[6],c=this.m[7],u=this.m[8],f=this.m[9],d=this.m[10],p=this.m[11],m=this.m[12],_=this.m[13],g=this.m[14],v=this.m[15],y=e.m[0],b=e.m[1],x=e.m[2],T=e.m[3],E=e.m[4],P=e.m[5],A=e.m[6],M=e.m[7],S=e.m[8],R=e.m[9],C=e.m[10],O=e.m[11],D=e.m[12],I=e.m[13],w=e.m[14],L=e.m[15];return t[i]=r*y+n*E+o*S+s*D,t[i+1]=r*b+n*P+o*R+s*I,t[i+2]=r*x+n*A+o*C+s*w,t[i+3]=r*T+n*M+o*O+s*L,t[i+4]=a*y+l*E+h*S+c*D,t[i+5]=a*b+l*P+h*R+c*I,t[i+6]=a*x+l*A+h*C+c*w,t[i+7]=a*T+l*M+h*O+c*L,t[i+8]=u*y+f*E+d*S+p*D,t[i+9]=u*b+f*P+d*R+p*I,t[i+10]=u*x+f*A+d*C+p*w,t[i+11]=u*T+f*M+d*O+p*L,t[i+12]=m*y+_*E+g*S+v*D,t[i+13]=m*b+_*P+g*R+v*I,t[i+14]=m*x+_*A+g*C+v*w,t[i+15]=m*T+_*M+g*O+v*L,this},e.prototype.equals=function(e){return e&&this.m[0]===e.m[0]&&this.m[1]===e.m[1]&&this.m[2]===e.m[2]&&this.m[3]===e.m[3]&&this.m[4]===e.m[4]&&this.m[5]===e.m[5]&&this.m[6]===e.m[6]&&this.m[7]===e.m[7]&&this.m[8]===e.m[8]&&this.m[9]===e.m[9]&&this.m[10]===e.m[10]&&this.m[11]===e.m[11]&&this.m[12]===e.m[12]&&this.m[13]===e.m[13]&&this.m[14]===e.m[14]&&this.m[15]===e.m[15]},e.prototype.clone=function(){return e.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},e.prototype.getClassName=function(){return"Matrix"},e.prototype.getHashCode=function(){for(var e=this.m[0]||0,t=1;t<16;t++)e=397*e^(this.m[t]||0);return e},e.prototype.decompose=function(t,i,r){return r&&(r.x=this.m[12],r.y=this.m[13],r.z=this.m[14]),t=t||E.Vector3[0],t.x=Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),this.determinant()<=0&&(t.y*=-1),0===t.x||0===t.y||0===t.z?(i&&(i.x=0,i.y=0,i.z=0,i.w=1),!1):(i&&(e.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,E.Matrix[0]),a.FromRotationMatrixToRef(E.Matrix[0],i)),!0)},e.prototype.getRow=function(e){if(e<0||e>3)return null;var t=4*e;return new o(this.m[t+0],this.m[t+1],this.m[t+2],this.m[t+3])},e.prototype.setRow=function(e,t){if(e<0||e>3)return this;var i=4*e;return this.m[i+0]=t.x,this.m[i+1]=t.y,this.m[i+2]=t.z,this.m[i+3]=t.w,this._markAsUpdated(),this},e.prototype.transpose=function(){return e.Transpose(this)},e.prototype.transposeToRef=function(t){return e.TransposeToRef(this,t),this},e.prototype.setRowFromFloats=function(e,t,i,r,n){if(e<0||e>3)return this;var o=4*e;return this.m[o+0]=t,this.m[o+1]=i,this.m[o+2]=r,this.m[o+3]=n,this._markAsUpdated(),this},e.prototype.scale=function(t){var i=new e;return this.scaleToRef(t,i),i},e.prototype.scaleToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]=this.m[i]*e;return t._markAsUpdated(),this},e.prototype.scaleAndAddToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]+=this.m[i]*e;return t._markAsUpdated(),this},e.prototype.toNormalMatrix=function(t){this.invertToRef(t),t.transpose();var i=t.m;e.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,t)},e.prototype.getRotationMatrix=function(){var t=e.Identity();return this.getRotationMatrixToRef(t),t},e.prototype.getRotationMatrixToRef=function(t){var i=this.m,r=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),n=Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),o=Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);return this.determinant()<=0&&(n*=-1),0===r||0===n||0===o?e.IdentityToRef(t):e.FromValuesToRef(i[0]/r,i[1]/r,i[2]/r,0,i[4]/n,i[5]/n,i[6]/n,0,i[8]/o,i[9]/o,i[10]/o,0,0,0,0,1,t),this},e.FromArray=function(t,i){var r=new e;return i||(i=0),e.FromArrayToRef(t,i,r),r},e.FromArrayToRef=function(e,t,i){for(var r=0;r<16;r++)i.m[r]=e[r+t];i._markAsUpdated()},e.FromFloat32ArrayToRefScaled=function(e,t,i,r){for(var n=0;n<16;n++)r.m[n]=e[n+t]*i;r._markAsUpdated()},e.FromValuesToRef=function(e,t,i,r,n,o,s,a,l,h,c,u,f,d,p,m,_){_.m[0]=e,_.m[1]=t,_.m[2]=i,_.m[3]=r,_.m[4]=n,_.m[5]=o,_.m[6]=s,_.m[7]=a,_.m[8]=l,_.m[9]=h,_.m[10]=c,_.m[11]=u,_.m[12]=f,_.m[13]=d,_.m[14]=p,_.m[15]=m,_._markAsUpdated()},Object.defineProperty(e,"IdentityReadOnly",{get:function(){return e._identityReadOnly},enumerable:!0,configurable:!0}),e.FromValues=function(t,i,r,n,o,s,a,l,h,c,u,f,d,p,m,_){var g=new e;return g.m[0]=t,g.m[1]=i,g.m[2]=r,g.m[3]=n,g.m[4]=o,g.m[5]=s,g.m[6]=a,g.m[7]=l,g.m[8]=h,g.m[9]=c,g.m[10]=u,g.m[11]=f,g.m[12]=d,g.m[13]=p,g.m[14]=m,g.m[15]=_,g},e.Compose=function(t,i,r){var n=e.Identity();return e.ComposeToRef(t,i,r,n),n},e.ComposeToRef=function(t,i,r,n){e.FromValuesToRef(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1,E.Matrix[1]),i.toRotationMatrix(E.Matrix[0]),E.Matrix[1].multiplyToRef(E.Matrix[0],n),n.setTranslation(r)},e.Identity=function(){return e.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},e.IdentityToRef=function(t){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},e.Zero=function(){return e.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},e.RotationX=function(t){var i=new e;return e.RotationXToRef(t,i),i},e.Invert=function(t){var i=new e;return t.invertToRef(i),i},e.RotationXToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[0]=1,t.m[15]=1,t.m[5]=r,t.m[10]=r,t.m[9]=-i,t.m[6]=i,t.m[1]=0,t.m[2]=0,t.m[3]=0,t.m[4]=0,t.m[7]=0,t.m[8]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t._markAsUpdated()},e.RotationY=function(t){var i=new e;return e.RotationYToRef(t,i),i},e.RotationYToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[5]=1,t.m[15]=1,t.m[0]=r,t.m[2]=-i,t.m[8]=i,t.m[10]=r,t.m[1]=0,t.m[3]=0,t.m[4]=0,t.m[6]=0,t.m[7]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t._markAsUpdated()},e.RotationZ=function(t){var i=new e;return e.RotationZToRef(t,i),i},e.RotationZToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[10]=1,t.m[15]=1,t.m[0]=r,t.m[1]=i,t.m[4]=-i,t.m[5]=r,t.m[2]=0,t.m[3]=0,t.m[6]=0,t.m[7]=0,t.m[8]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t._markAsUpdated()},e.RotationAxis=function(t,i){var r=e.Zero();return e.RotationAxisToRef(t,i,r),r},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(-t),n=Math.cos(-t),o=1-n;e.normalize(),i.m[0]=e.x*e.x*o+n,i.m[1]=e.x*e.y*o-e.z*r,i.m[2]=e.x*e.z*o+e.y*r,i.m[3]=0,i.m[4]=e.y*e.x*o+e.z*r,i.m[5]=e.y*e.y*o+n,i.m[6]=e.y*e.z*o-e.x*r,i.m[7]=0,i.m[8]=e.z*e.x*o-e.y*r,i.m[9]=e.z*e.y*o+e.x*r,i.m[10]=e.z*e.z*o+n,i.m[11]=0,i.m[15]=1, -i._markAsUpdated()},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){a.RotationYawPitchRollToRef(e,t,i,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},e.Scaling=function(t,i,r){var n=e.Zero();return e.ScalingToRef(t,i,r,n),n},e.ScalingToRef=function(e,t,i,r){r.m[0]=e,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=t,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=i,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1,r._markAsUpdated()},e.Translation=function(t,i,r){var n=e.Identity();return e.TranslationToRef(t,i,r,n),n},e.TranslationToRef=function(t,i,r,n){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,r,1,n)},e.Lerp=function(t,i,r){var n=e.Zero();return e.LerpToRef(t,i,r,n),n},e.LerpToRef=function(e,t,i,r){for(var n=0;n<16;n++)r.m[n]=e.m[n]*(1-i)+t.m[n]*i;r._markAsUpdated()},e.DecomposeLerp=function(t,i,r){var n=e.Zero();return e.DecomposeLerpToRef(t,i,r,n),n},e.DecomposeLerpToRef=function(t,i,r,o){var s=E.Vector3[0],l=E.Quaternion[0],h=E.Vector3[1];t.decompose(s,l,h);var c=E.Vector3[2],u=E.Quaternion[1],f=E.Vector3[3];i.decompose(c,u,f);var d=E.Vector3[4];n.LerpToRef(s,c,r,d);var p=E.Quaternion[2];a.SlerpToRef(l,u,r,p);var m=E.Vector3[5];n.LerpToRef(h,f,r,m),e.ComposeToRef(d,p,m,o)},e.LookAtLH=function(t,i,r){var n=e.Zero();return e.LookAtLHToRef(t,i,r,n),n},e.LookAtLHToRef=function(t,i,r,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),n.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),n.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-n.Dot(this._xAxis,t),a=-n.Dot(this._yAxis,t),l=-n.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,l,1,o)},e.LookAtRH=function(t,i,r){var n=e.Zero();return e.LookAtRHToRef(t,i,r,n),n},e.LookAtRHToRef=function(t,i,r,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),n.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),n.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-n.Dot(this._xAxis,t),a=-n.Dot(this._yAxis,t),l=-n.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,l,1,o)},e.OrthoLH=function(t,i,r,n){var o=e.Zero();return e.OrthoLHToRef(t,i,r,n,o),o},e.OrthoLHToRef=function(t,i,r,n,o){var s=r,a=n,l=2/t,h=2/i,c=2/(a-s),u=-(a+s)/(a-s);e.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,0,0,u,1,o)},e.OrthoOffCenterLH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterLHToRef=function(t,i,r,n,o,s,a){var l=o,h=s,c=2/(i-t),u=2/(n-r),f=2/(h-l),d=-(h+l)/(h-l),p=(t+i)/(t-i),m=(n+r)/(r-n);e.FromValuesToRef(c,0,0,0,0,u,0,0,0,0,f,0,p,m,d,1,a)},e.OrthoOffCenterRH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterRHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterRHToRef=function(t,i,r,n,o,s,a){e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a.m[10]*=-1},e.PerspectiveLH=function(t,i,r,n){var o=e.Zero(),s=r,a=n,l=2*s/t,h=2*s/i,c=(a+s)/(a-s),u=-2*a*s/(a-s);return e.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,1,0,0,u,0,o),o},e.PerspectiveFovLH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovLHToRef(t,i,r,n,o),o},e.PerspectiveFovLHToRef=function(t,i,r,n,o,s){void 0===s&&(s=!0);var a=r,l=n,h=1/Math.tan(.5*t),c=s?h/i:h,u=s?h:h*i,f=(l+a)/(l-a),d=-2*l*a/(l-a);e.FromValuesToRef(c,0,0,0,0,u,0,0,0,0,f,1,0,0,d,0,o)},e.PerspectiveFovRH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovRHToRef(t,i,r,n,o),o},e.PerspectiveFovRHToRef=function(t,i,r,n,o,s){void 0===s&&(s=!0);var a=r,l=n,h=1/Math.tan(.5*t),c=s?h/i:h,u=s?h:h*i,f=-(l+a)/(l-a),d=-2*l*a/(l-a);e.FromValuesToRef(c,0,0,0,0,u,0,0,0,0,f,-1,0,0,d,0,o)},e.PerspectiveFovWebVRToRef=function(e,t,i,r,n){void 0===n&&(n=!1);var o=n?-1:1,s=Math.tan(e.upDegrees*Math.PI/180),a=Math.tan(e.downDegrees*Math.PI/180),l=Math.tan(e.leftDegrees*Math.PI/180),h=Math.tan(e.rightDegrees*Math.PI/180),c=2/(l+h),u=2/(s+a);r.m[0]=c,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=u,r.m[6]=r.m[7]=0,r.m[8]=(l-h)*c*.5,r.m[9]=-(s-a)*u*.5,r.m[10]=-i/(t-i),r.m[11]=1*o,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=-2*i*t/(i-t),r._markAsUpdated()},e.GetFinalMatrix=function(t,i,r,n,o,s){var a=t.width,l=t.height,h=t.x,c=t.y,u=e.FromValues(a/2,0,0,0,0,-l/2,0,0,0,0,s-o,0,h+a/2,l/2+c,o,1);return i.multiply(r).multiply(n).multiply(u)},e.GetAsMatrix2x2=function(e){return new Float32Array([e.m[0],e.m[1],e.m[4],e.m[5]])},e.GetAsMatrix3x3=function(e){return new Float32Array([e.m[0],e.m[1],e.m[2],e.m[4],e.m[5],e.m[6],e.m[8],e.m[9],e.m[10]])},e.Transpose=function(t){var i=new e;return e.TransposeToRef(t,i),i},e.TransposeToRef=function(e,t){t.m[0]=e.m[0],t.m[1]=e.m[4],t.m[2]=e.m[8],t.m[3]=e.m[12],t.m[4]=e.m[1],t.m[5]=e.m[5],t.m[6]=e.m[9],t.m[7]=e.m[13],t.m[8]=e.m[2],t.m[9]=e.m[6],t.m[10]=e.m[10],t.m[11]=e.m[14],t.m[12]=e.m[3],t.m[13]=e.m[7],t.m[14]=e.m[11],t.m[15]=e.m[15]},e.Reflection=function(t){var i=new e;return e.ReflectionToRef(t,i),i},e.ReflectionToRef=function(e,t){e.normalize();var i=e.normal.x,r=e.normal.y,n=e.normal.z,o=-2*i,s=-2*r,a=-2*n;t.m[0]=o*i+1,t.m[1]=s*i,t.m[2]=a*i,t.m[3]=0,t.m[4]=o*r,t.m[5]=s*r+1,t.m[6]=a*r,t.m[7]=0,t.m[8]=o*n,t.m[9]=s*n,t.m[10]=a*n+1,t.m[11]=0,t.m[12]=o*e.d,t.m[13]=s*e.d,t.m[14]=a*e.d,t.m[15]=1,t._markAsUpdated()},e.FromXYZAxesToRef=function(e,t,i,r){r.m[0]=e.x,r.m[1]=e.y,r.m[2]=e.z,r.m[3]=0,r.m[4]=t.x,r.m[5]=t.y,r.m[6]=t.z,r.m[7]=0,r.m[8]=i.x,r.m[9]=i.y,r.m[10]=i.z,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1,r._markAsUpdated()},e.FromQuaternionToRef=function(e,t){var i=e.x*e.x,r=e.y*e.y,n=e.z*e.z,o=e.x*e.y,s=e.z*e.w,a=e.z*e.x,l=e.y*e.w,h=e.y*e.z,c=e.x*e.w;t.m[0]=1-2*(r+n),t.m[1]=2*(o+s),t.m[2]=2*(a-l),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+c),t.m[7]=0,t.m[8]=2*(a+l),t.m[9]=2*(h-c),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,t._markAsUpdated()},e._tempQuaternion=new a,e._xAxis=n.Zero(),e._yAxis=n.Zero(),e._zAxis=n.Zero(),e._updateFlagSeed=0,e._identityReadOnly=e.Identity(),e})();e.Matrix=l;var h=(function(){function e(e,t,i,r){this.normal=new n(e,t,i),this.d=r}return e.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},e.prototype.clone=function(){return new e(this.normal.x,this.normal.y,this.normal.z,this.d)},e.prototype.getClassName=function(){return"Plane"},e.prototype.getHashCode=function(){var e=this.normal.getHashCode();return e=397*e^(this.d||0)},e.prototype.normalize=function(){var e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this},e.prototype.transform=function(t){var i=l.Transpose(t),r=this.normal.x,n=this.normal.y,o=this.normal.z,s=this.d;return new e(r*i.m[0]+n*i.m[1]+o*i.m[2]+s*i.m[3],r*i.m[4]+n*i.m[5]+o*i.m[6]+s*i.m[7],r*i.m[8]+n*i.m[9]+o*i.m[10]+s*i.m[11],r*i.m[12]+n*i.m[13]+o*i.m[14]+s*i.m[15])},e.prototype.dotCoordinate=function(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d},e.prototype.copyFromPoints=function(e,t,i){var r,n=t.x-e.x,o=t.y-e.y,s=t.z-e.z,a=i.x-e.x,l=i.y-e.y,h=i.z-e.z,c=o*h-s*l,u=s*a-n*h,f=n*l-o*a,d=Math.sqrt(c*c+u*u+f*f);return r=0!==d?1/d:0,this.normal.x=c*r,this.normal.y=u*r,this.normal.z=f*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this},e.prototype.isFrontFacingTo=function(e,t){return n.Dot(this.normal,e)<=t},e.prototype.signedDistanceTo=function(e){return n.Dot(e,this.normal)+this.d},e.FromArray=function(t){return new e(t[0],t[1],t[2],t[3])},e.FromPoints=function(t,i,r){var n=new e(0,0,0,0);return n.copyFromPoints(t,i,r),n},e.FromPositionAndNormal=function(t,i){var r=new e(0,0,0,0);return i.normalize(),r.normal=i,r.d=-(i.x*t.x+i.y*t.y+i.z*t.z),r},e.SignedDistanceToPlaneFromPositionAndNormal=function(e,t,i){var r=-(t.x*e.x+t.y*e.y+t.z*e.z);return n.Dot(i,t)+r},e})();e.Plane=h;var c=(function(){function e(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}return e.prototype.toGlobal=function(t,i){if(t.getRenderWidth){var r=t;return this.toGlobal(r.getRenderWidth(),r.getRenderHeight())}var n=t;return new e(this.x*n,this.y*i,this.width*n,this.height*i)},e.prototype.clone=function(){return new e(this.x,this.y,this.width,this.height)},e})();e.Viewport=c;var u=(function(){function e(){}return e.GetPlanes=function(t){for(var i=[],r=0;r<6;r++)i.push(new h(0,0,0,0));return e.GetPlanesToRef(t,i),i},e.GetNearPlaneToRef=function(e,t){t.normal.x=e.m[3]+e.m[2],t.normal.y=e.m[7]+e.m[6],t.normal.z=e.m[11]+e.m[10],t.d=e.m[15]+e.m[14],t.normalize()},e.GetFarPlaneToRef=function(e,t){t.normal.x=e.m[3]-e.m[2],t.normal.y=e.m[7]-e.m[6],t.normal.z=e.m[11]-e.m[10],t.d=e.m[15]-e.m[14],t.normalize()},e.GetLeftPlaneToRef=function(e,t){t.normal.x=e.m[3]+e.m[0],t.normal.y=e.m[7]+e.m[4],t.normal.z=e.m[11]+e.m[8],t.d=e.m[15]+e.m[12],t.normalize()},e.GetRightPlaneToRef=function(e,t){t.normal.x=e.m[3]-e.m[0],t.normal.y=e.m[7]-e.m[4],t.normal.z=e.m[11]-e.m[8],t.d=e.m[15]-e.m[12],t.normalize()},e.GetTopPlaneToRef=function(e,t){t.normal.x=e.m[3]-e.m[1],t.normal.y=e.m[7]-e.m[5],t.normal.z=e.m[11]-e.m[9],t.d=e.m[15]-e.m[13],t.normalize()},e.GetBottomPlaneToRef=function(e,t){t.normal.x=e.m[3]+e.m[1],t.normal.y=e.m[7]+e.m[5],t.normal.z=e.m[11]+e.m[9],t.d=e.m[15]+e.m[13],t.normalize()},e.GetPlanesToRef=function(t,i){e.GetNearPlaneToRef(t,i[0]),e.GetFarPlaneToRef(t,i[1]),e.GetLeftPlaneToRef(t,i[2]),e.GetRightPlaneToRef(t,i[3]),e.GetTopPlaneToRef(t,i[4]),e.GetBottomPlaneToRef(t,i[5])},e})();e.Frustum=u;!(function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"})(e.Space||(e.Space={}));var f=(function(){function e(){}return e.X=new n(1,0,0),e.Y=new n(0,1,0),e.Z=new n(0,0,1),e})();e.Axis=f;var d=(function(){function e(){}return e.interpolate=function(e,t,i,r,n){for(var o=1-3*r+3*t,s=3*r-6*t,a=3*t,l=e,h=0;h<5;h++){var c=l*l;l-=(o*(c*l)+s*c+a*l-e)*(1/(3*o*c+2*s*l+a)),l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*n+Math.pow(l,3)},e})();e.BezierCurve=d;var p;!(function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"})(p=e.Orientation||(e.Orientation={}));var m=(function(){function e(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}return e.prototype.degrees=function(){return 180*this._radians/Math.PI},e.prototype.radians=function(){return this._radians},e.BetweenTwoPoints=function(t,i){var r=i.subtract(t);return new e(Math.atan2(r.y,r.x))},e.FromRadians=function(t){return new e(t)},e.FromDegrees=function(t){return new e(t*Math.PI/180)},e})();e.Angle=m;var _=(function(){function e(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;var n=Math.pow(t.x,2)+Math.pow(t.y,2),o=(Math.pow(e.x,2)+Math.pow(e.y,2)-n)/2,s=(n-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new r((o*(t.y-i.y)-s*(e.y-t.y))/a,((e.x-t.x)*s-(t.x-i.x)*o)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=m.BetweenTwoPoints(this.centerPoint,this.startPoint);var l=this.startAngle.degrees(),h=m.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),c=m.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();h-l>180&&(h-=360),h-l<-180&&(h+=360),c-h>180&&(c-=360),c-h<-180&&(c+=360),this.orientation=h-l<0?p.CW:p.CCW,this.angle=m.FromDegrees(this.orientation===p.CW?l-c:c-l)}return e})();e.Arc2=_;var g=(function(){function e(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(e,t))}return e.prototype.addLineTo=function(e,t){if(this.closed)return this;var i=new r(e,t),n=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(n).length(),this},e.prototype.addArcTo=function(e,t,i,n,o){if(void 0===o&&(o=36),this.closed)return this;var s=this._points[this._points.length-1],a=new r(e,t),l=new r(i,n),h=new _(s,a,l),c=h.angle.radians()/o;h.orientation===p.CW&&(c*=-1);for(var u=h.startAngle.radians()+c,f=0;f1)return r.Zero();for(var t=e*this.length(),i=0,n=0;n=i&&t<=h){var c=l.normalize(),u=t-i;return new r(s.x+c.x*u,s.y+c.y*u)}i=h}return r.Zero()},e.StartingAt=function(t,i){return new e(t,i)},e})();e.Path2=g;var v=(function(){function t(e,t,i){void 0===t&&(t=null),this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;rt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i},t.prototype._normalVector=function(t,i,r){var o,s=i.length();if(0===s&&(s=1),void 0===r||null===r){var a;a=e.Scalar.WithinEpsilon(Math.abs(i.y)/s,1,e.Epsilon)?e.Scalar.WithinEpsilon(Math.abs(i.x)/s,1,e.Epsilon)?e.Scalar.WithinEpsilon(Math.abs(i.z)/s,1,e.Epsilon)?n.Zero():new n(0,0,1):new n(1,0,0):new n(0,-1,0),o=n.Cross(i,a)}else o=n.Cross(i,r),n.CrossToRef(o,i,o);return o.normalize(),o},t})();e.Path3D=v;var y=(function(){function e(e){this._length=0,this._points=e,this._length=this._computeLength(e)}return e.CreateQuadraticBezier=function(t,i,r,o){o=o>2?o:3;for(var s=new Array,a=function(e,t,i,r){return(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r},l=0;l<=o;l++)s.push(new n(a(l/o,t.x,i.x,r.x),a(l/o,t.y,i.y,r.y),a(l/o,t.z,i.z,r.z)));return new e(s)},e.CreateCubicBezier=function(t,i,r,o,s){s=s>3?s:4;for(var a=new Array,l=function(e,t,i,r,n){return(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*n},h=0;h<=s;h++)a.push(new n(l(h/s,t.x,i.x,r.x,o.x),l(h/s,t.y,i.y,r.y,o.y),l(h/s,t.z,i.z,r.z,o.z)));return new e(a)},e.CreateHermiteSpline=function(t,i,r,o,s){for(var a=new Array,l=1/s,h=0;h<=s;h++)a.push(n.Hermite(t,i,r,o,h*l));return new e(a)},e.CreateCatmullRomSpline=function(t,i,r){var o=new Array,s=1/i,a=0;if(r){for(var l=t.length,h=0;h0?1:-1},e.Clamp=function(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1),Math.min(i,Math.max(t,e))},e.Log2=function(e){return Math.log(e)*Math.LOG2E},e.Repeat=function(e,t){return e-Math.floor(e/t)*t},e.Normalize=function(e,t,i){return(e-t)/(i-t)},e.Denormalize=function(e,t,i){return e*(i-t)+t},e.DeltaAngle=function(t,i){var r=e.Repeat(i-t,360);return r>180&&(r-=360),r},e.PingPong=function(t,i){var r=e.Repeat(t,2*i);return i-Math.abs(r-i)},e.SmoothStep=function(t,i,r){var n=e.Clamp(r);return n=-2*n*n*n+3*n*n,i*n+t*(1-n)},e.MoveTowards=function(t,i,r){return Math.abs(i-t)<=r?i:t+e.Sign(i-t)*r},e.MoveTowardsAngle=function(t,i,r){var n=e.DeltaAngle(t,i),o=0;return-r180&&(n-=360),t+n*e.Clamp(r)},e.InverseLerp=function(t,i,r){return t!=i?e.Clamp((r-t)/(i-t)):0},e.Hermite=function(e,t,i,r,n){var o=n*n,s=n*o;return e*(2*s-3*o+1)+i*(-2*s+3*o)+t*(s-2*o+n)+r*(s-o)},e.RandomRange=function(e,t){return e===t?e:Math.random()*(t-e)+e},e.RangeToPercent=function(e,t,i){return(e-t)/(i-t)},e.PercentToRange=function(e,t,i){return(i-t)*e+t},e.NormalizeRadians=function(t){return t-=e.TwoPi*Math.floor((t+Math.PI)/e.TwoPi)},e.TwoPi=2*Math.PI,e})();e.Scalar=t})(r||(r={}));var r;!(function(e){function t(e){var t=e.getClassName();return v[t]||(v[t]={}),v[t]}function i(e){var t=e.getClassName();if(y[t])return y[t];y[t]={};for(var i=y[t],r=e,n=t;n;){var o=v[n];for(var s in o)i[s]=o[s];var a=void 0,l=!1;do{if(a=Object.getPrototypeOf(r),!a.getClassName){l=!0;break}if(a.getClassName()!==n)break;r=a}while(a);if(l)break;n=a.getClassName(),r=a}return i}function r(e,i){return function(r,n){var o=t(r);o[n]||(o[n]={type:e,sourceName:i})}}function n(e,t){return void 0===t&&(t=null),function(i,r){var n=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[n]},set:function(t){this[n]!==t&&(this[n]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}function o(e,t){return void 0===t&&(t=null),n(e,t)}function s(e){return r(0,e)}function a(e){return r(1,e)}function l(e){return r(2,e)}function h(e){return r(3,e)}function c(e){return r(4,e)}function u(e){return r(5,e)}function f(e){return r(6,e)}function d(e){return r(7,e)}function p(e){return r(8,e)}function m(e){return r(9,e)}function _(e){return r(10,e)}function g(e){return r(11,e)}var v={},y={},b=function(t,r,n){var o=t();e.Tags&&e.Tags.AddTagsTo(o,r.tags);var s=i(o);for(var a in s){var l=s[a],h=r[a],c=l.type;if(void 0!==h&&null!==h)switch(c){case 0:case 6:case 11:o[a]=h;break;case 1:o[a]=n||h.isRenderTarget?h:h.clone();break;case 2:case 3:case 4:case 5:case 7:case 10:o[a]=n?h:h.clone()}}return o};e.expandToProperty=o,e.serialize=s,e.serializeAsTexture=a,e.serializeAsColor3=l,e.serializeAsFresnelParameters=h,e.serializeAsVector2=c,e.serializeAsVector3=u,e.serializeAsMeshReference=f,e.serializeAsColorCurves=d,e.serializeAsColor4=p,e.serializeAsImageProcessingConfiguration=m,e.serializeAsQuaternion=_,e.serializeAsCameraReference=g;var x=(function(){function t(){}return t.Serialize=function(t,r){r||(r={}),e.Tags&&(r.tags=e.Tags.GetTags(t));var n=i(t);for(var o in n){var s=n[o],a=s.sourceName||o,l=s.type,h=t[o];if(void 0!==h&&null!==h)switch(l){case 0:r[a]=h;break;case 1:r[a]=h.serialize();break;case 2:r[a]=h.asArray();break;case 3:r[a]=h.serialize();break;case 4:case 5:r[a]=h.asArray();break;case 6:r[a]=h.id;break;case 7:r[a]=h.serialize();break;case 8:r[a]=h.asArray();break;case 9:r[a]=h.serialize();break;case 10:r[a]=h.asArray();break;case 11:r[a]=h.id}}return r},t.Parse=function(t,r,n,o){void 0===o&&(o=null);var s=t();o||(o=""),e.Tags&&e.Tags.AddTagsTo(s,r.tags);var a=i(s);for(var l in a){var h=a[l],c=r[h.sourceName||l],u=h.type;if(void 0!==c&&null!==c){var f=s;switch(u){case 0:f[l]=c;break;case 1:n&&(f[l]=e.Texture.Parse(c,n,o));break;case 2:f[l]=e.Color3.FromArray(c);break;case 3:f[l]=e.FresnelParameters.Parse(c);break;case 4:f[l]=e.Vector2.FromArray(c);break;case 5:f[l]=e.Vector3.FromArray(c);break;case 6:n&&(f[l]=n.getLastMeshByID(c));break;case 7:f[l]=e.ColorCurves.Parse(c);break;case 8:f[l]=e.Color4.FromArray(c);break;case 9:f[l]=e.ImageProcessingConfiguration.Parse(c);break;case 10:f[l]=e.Quaternion.FromArray(c);break;case 11:n&&(f[l]=n.getCameraByID(c))}}}return s},t.Clone=function(e,t){return b(e,t,!1)},t.Instanciate=function(e,t){return b(e,t,!0)},t})();e.SerializationHelper=x})(r||(r={}));var r;!(function(e){var t=(function(){function e(){var e=this;this.promise=new Promise(function(t,i){e._resolve=t,e._reject=i})}return Object.defineProperty(e.prototype,"resolve",{get:function(){return this._resolve},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"reject",{get:function(){return this._reject},enumerable:!0,configurable:!0}),e})();e.Deferred=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i,r){void 0===t&&(t=!1),this.initalize(e,t,i,r)}return e.prototype.initalize=function(e,t,i,r){return void 0===t&&(t=!1),this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this},e})();e.EventState=t;var i=(function(){function e(e,t,i){void 0===i&&(i=null),this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1}return e})();e.Observer=i;var r=(function(){function e(){}return e.prototype.dispose=function(){if(this._observers&&this._observables)for(var e=0;e0},r.prototype.clear=function(){this._observers=new Array,this._onObserverAdded=null},r.prototype.clone=function(){var e=new r;return e._observers=this._observers.slice(0),e},r.prototype.hasSpecificMask=function(e){void 0===e&&(e=-1);for(var t=0,i=this._observers;tthis.data.length&&(this.data.length*=2)},e.prototype.forEach=function(e){for(var t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t=this.length?-1:t},e.prototype.contains=function(e){return-1!==this.data.indexOf(e)},e._GlobalId=0,e})();e.SmartArray=t;var i=(function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._duplicateId=0,t}return o(t,e),t.prototype.push=function(t){e.prototype.push.call(this,t),t.__smartArrayFlags||(t.__smartArrayFlags={}),t.__smartArrayFlags[this._id]=this._duplicateId},t.prototype.pushNoDuplicate=function(e){return(!e.__smartArrayFlags||e.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(e),!0)},t.prototype.reset=function(){e.prototype.reset.call(this),this._duplicateId++},t.prototype.concatWithNoDuplicate=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t=e||-1!==i.indexOf("file:")?-1:Math.pow(2,n)*t}},e})();e.RetryStrategy=s;var a,l=function(t,i){return t?t instanceof e.Mesh?null:t instanceof e.SubMesh?t.clone(i):t.clone?t.clone():null:null},h=(function(){function t(){}return t.FetchToRef=function(e,t,i,r,n,o){var s=Math.abs(e)*i%i|0,a=Math.abs(t)*r%r|0,l=4*(s+a*i);o.r=n[l]/255,o.g=n[l+1]/255,o.b=n[l+2]/255,o.a=n[l+3]/255},t.Mix=function(e,t,i){return e*(1-i)+t*i},t.Instantiate=function(e){if(t.RegisteredExternalClasses&&t.RegisteredExternalClasses[e])return t.RegisteredExternalClasses[e];for(var i=e.split("."),r=window||this,n=0,o=i.length;n>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e},t.FloorPOT=function(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)},t.NearestPOT=function(e){var i=t.CeilingPOT(e),r=t.FloorPOT(e);return i-e>e-r?r:i},t.GetExponentOfTwo=function(i,r,n){void 0===n&&(n=e.Engine.SCALEMODE_NEAREST);var o;switch(n){case e.Engine.SCALEMODE_FLOOR:o=t.FloorPOT(i);break;case e.Engine.SCALEMODE_NEAREST:o=t.NearestPOT(i);break;case e.Engine.SCALEMODE_CEILING:default:o=t.CeilingPOT(i)}return Math.min(o,r)},t.GetFilename=function(e){var t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)},t.GetFolderPath=function(e,t){void 0===t&&(t=!1);var i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)},t.GetDOMTextContent=function(e){for(var t="",i=e.firstChild;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t},t.ToDegrees=function(e){return 180*e/Math.PI},t.ToRadians=function(e){return e*Math.PI/180},t.EncodeArrayBufferTobase64=function(e){for(var t,i,r,n,o,s,a,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",c=0,u=new Uint8Array(e);c>2,o=(3&t)<<4|i>>4,s=(15&i)<<2|r>>6,a=63&r,isNaN(i)?s=a=64:isNaN(r)&&(a=64),h+=l.charAt(n)+l.charAt(o)+l.charAt(s)+l.charAt(a);return"data:image/png;base64,"+h},t.ExtractMinAndMaxIndexed=function(t,i,r,n,o){void 0===o&&(o=null) -;for(var s=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new e.Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),l=r;l=(r?t.length/2:t.length))return null;if(r){var n=t;return new e.Vector2(n[2*i+0],n[2*i+1])}return t[i]}},t.ExtractMinAndMaxVector2=function(t,i){void 0===i&&(i=null);for(var r=new e.Vector2(Number.MAX_VALUE,Number.MAX_VALUE),n=new e.Vector2(-Number.MAX_VALUE,-Number.MAX_VALUE),o=0,s=t(o++);s;)r=e.Vector2.Minimize(s,r),n=e.Vector2.Maximize(s,n),s=t(o++);return i&&(r.x-=r.x*i.x+i.y,r.y-=r.y*i.x+i.y,n.x+=n.x*i.x+i.y,n.y+=n.y*i.x+i.y),{minimum:r,maximum:n}},t.MakeArray=function(e,t){return!0===t||void 0!==e&&null!=e?Array.isArray(e)?e:[e]:null},t.GetPointerPrefix=function(){var e="pointer";return!t.IsWindowObjectExist()||window.PointerEvent||navigator.pointerEnabled||(e="mouse"),e},t.QueueNewFrame=function(e,i){return t.IsWindowObjectExist()?(i||(i=window),i.requestAnimationFrame?i.requestAnimationFrame(e):i.msRequestAnimationFrame?i.msRequestAnimationFrame(e):i.webkitRequestAnimationFrame?i.webkitRequestAnimationFrame(e):i.mozRequestAnimationFrame?i.mozRequestAnimationFrame(e):i.oRequestAnimationFrame?i.oRequestAnimationFrame(e):window.setTimeout(e,16)):setTimeout(e,16)},t.RequestFullscreen=function(e){var t=e.requestFullscreen||e.msRequestFullscreen||e.webkitRequestFullscreen||e.mozRequestFullScreen;t&&t.call(e)},t.ExitFullscreen=function(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitCancelFullScreen?document.webkitCancelFullScreen():document.msCancelFullScreen&&document.msCancelFullScreen()},t.SetCorsBehavior=function(e,i){if((!e||0!==e.indexOf("data:"))&&t.CorsBehavior)if("string"==typeof t.CorsBehavior||t.CorsBehavior instanceof String)i.crossOrigin=t.CorsBehavior;else{var r=t.CorsBehavior(e);r&&(i.crossOrigin=r)}},t.CleanUrl=function(e){return e=e.replace(/#/gm,"%23")},t.LoadImage=function(i,r,n,o){var s,a=!1;i instanceof ArrayBuffer?(s=URL.createObjectURL(new Blob([i])),a=!0):i instanceof Blob?(s=URL.createObjectURL(i),a=!0):(s=t.CleanUrl(i),s=t.PreprocessUrl(i));var l=new Image;t.SetCorsBehavior(s,l);var h=function(){a&&l.src&&URL.revokeObjectURL(l.src),l.removeEventListener("load",h),l.removeEventListener("error",c),r(l)},c=function(e){a&&l.src&&URL.revokeObjectURL(l.src),l.removeEventListener("load",h),l.removeEventListener("error",c),t.Error("Error while trying to load image: "+i),n&&n("Error while trying to load image: "+i,e)};l.addEventListener("load",h),l.addEventListener("error",c);var u=function(){l.src=s},f=function(){o&&o.loadImageFromDB(s,l)};if("data:"!==s.substr(0,5)&&o&&o.enableTexturesOffline&&e.Database.IsUASupportingBlobStorage)o.openAsync(f,u);else{if(-1!==s.indexOf("file:")){var d=decodeURIComponent(s.substring(5).toLowerCase());if(e.FilesInput.FilesToLoad[d]){try{var p;try{p=URL.createObjectURL(e.FilesInput.FilesToLoad[d],{oneTimeOnly:!0})}catch(t){p=URL.createObjectURL(e.FilesInput.FilesToLoad[d])}l.src=p,a=!0}catch(e){l.src=""}return l}}u()}return l},t.LoadFile=function(i,r,o,s,a,l){if(i=t.CleanUrl(i),i=t.PreprocessUrl(i),-1!==i.indexOf("file:")){var h=decodeURIComponent(i.substring(5).toLowerCase());if(e.FilesInput.FilesToLoad[h])return t.ReadFile(e.FilesInput.FilesToLoad[h],r,o,a)}var c=t.BaseUrl+i,u=!1,f={onCompleteObservable:new e.Observable,abort:function(){return u=!0}},d=function(){var e=new XMLHttpRequest,i=null;f.abort=function(){u=!0,e.readyState!==(XMLHttpRequest.DONE||4)&&e.abort(),null!==i&&(clearTimeout(i),i=null)};var s=function(h){e.open("GET",c,!0),a&&(e.responseType="arraybuffer"),o&&e.addEventListener("progress",o);var d=function(){e.removeEventListener("loadend",d),f.onCompleteObservable.notifyObservers(f),f.onCompleteObservable.clear()};e.addEventListener("loadend",d);var p=function(){if(!u&&e.readyState===(XMLHttpRequest.DONE||4)){if(e.removeEventListener("readystatechange",p),e.status>=200&&e.status<300||!t.IsWindowObjectExist()&&0===e.status)return void r(a?e.response:e.responseText,e.responseURL);var o=t.DefaultRetryStrategy;if(o){var f=o(c,e,h);if(-1!==f)return e.removeEventListener("loadend",d),e=new XMLHttpRequest,void(i=setTimeout((function(){return s(h+1)}),f))}var m=new n("Error status: "+e.status+" "+e.statusText+" - Unable to load "+c,e);if(!l)throw m;l(e,m)}};e.addEventListener("readystatechange",p),e.send()};s(0)};if(s&&s.enableSceneOffline){var p=function(e){e&&e.status>400?l&&l(e):u||d()},m=function(){u||s&&s.loadFileFromDB(i,(function(e){u||r(e),f.onCompleteObservable.notifyObservers(f)}),o?function(e){u||o(e)}:void 0,p,a)};s.openAsync(m,p)}else d();return f},t.LoadScript=function(e,t,i){var r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.type="text/javascript",n.src=e,n.onload=function(){t&&t()},n.onerror=function(t){i&&i("Unable to load script '"+e+"'",t)},r.appendChild(n)},t.ReadFileAsDataURL=function(t,i,r){var n=new FileReader,o={onCompleteObservable:new e.Observable,abort:function(){return n.abort()}};return n.onloadend=function(e){o.onCompleteObservable.notifyObservers(o)},n.onload=function(e){i(e.target.result)},n.onprogress=r,n.readAsDataURL(t),o},t.ReadFile=function(i,r,n,o){var s=new FileReader,a={onCompleteObservable:new e.Observable,abort:function(){return s.abort()}};return s.onloadend=function(e){return a.onCompleteObservable.notifyObservers(a)},s.onerror=function(e){t.Log("Error while reading file: "+i.name),r(JSON.stringify({autoClear:!0,clearColor:[1,0,0],ambientColor:[0,0,0],gravity:[0,-9.807,0],meshes:[],cameras:[],lights:[]}))},s.onload=function(e){r(e.target.result)},n&&(s.onprogress=n),o?s.readAsArrayBuffer(i):s.readAsText(i),a},t.FileAsURL=function(e){var t=new Blob([e]);return(window.URL||window.webkitURL).createObjectURL(t)},t.Format=function(e,t){return void 0===t&&(t=2),e.toFixed(t)},t.CheckExtends=function(e,t,i){e.xi.x&&(i.x=e.x),e.y>i.y&&(i.y=e.y),e.z>i.z&&(i.z=e.z)},t.DeepCopy=function(e,t,i,r){for(var n in e)if(("_"!==n[0]||r&&-1!==r.indexOf(n))&&(!i||-1===i.indexOf(n))){var o=e[n],s=typeof o;if("function"!==s)try{if("object"===s)if(o instanceof Array){if(t[n]=[],o.length>0)if("object"==typeof o[0])for(var a=0;al&&(f=l,u=f*c);var d=Math.max(0,s-u)/2,p=Math.max(0,l-f)/2,m=e.getRenderingCanvas();h&&m&&h.drawImage(m,d,p,u,f),t.EncodeScreenshotCanvasData(n,o)},t.CreateScreenshotUsingRenderTarget=function(i,r,n,o,s,a,l,h){void 0===s&&(s="image/png"),void 0===a&&(a=1),void 0===l&&(l=!1);var c,u;if(n.precision)c=Math.round(i.getRenderWidth()*n.precision),u=Math.round(c/i.getAspectRatio(r)),n={width:c,height:u};else if(n.width&&n.height)c=n.width,u=n.height;else if(n.width&&!n.height)c=n.width,u=Math.round(c/i.getAspectRatio(r)),n={width:c,height:u};else if(n.height&&!n.width)u=n.height,c=Math.round(u*i.getAspectRatio(r)),n={width:c,height:u};else{if(isNaN(n))return void t.Error("Invalid 'size' parameter !");u=n,c=n}var f=r.getScene(),d=null;f.activeCamera!==r&&(d=f.activeCamera,f.activeCamera=r);var p=new e.RenderTargetTexture("screenShot",n,f,!1,!1,e.Engine.TEXTURETYPE_UNSIGNED_INT,!1,e.Texture.NEAREST_SAMPLINGMODE);p.renderList=null,p.samples=a,l&&p.addPostProcess(new e.FxaaPostProcess("antialiasing",1,f.activeCamera)),p.onAfterRenderObservable.add((function(){t.DumpFramebuffer(c,u,i,o,s,h)})),f.incrementRenderId(),f.resetCachedMaterial(),p.render(!0),p.dispose(),d&&(f.activeCamera=d),r.getProjectionMatrix(!0)},t.ValidateXHRData=function(t,i){void 0===i&&(i=7);try{if(1&i){if(t.responseText&&t.responseText.length>0)return!0;if(1===i)return!1}if(2&i){var r=e.TGATools.GetTGAHeader(t.response);if(r.width&&r.height&&r.width>0&&r.height>0)return!0;if(2===i)return!1}if(4&i){var n=new Uint8Array(t.response,0,3);return 68===n[0]&&68===n[1]&&83===n[2]}}catch(e){}return!1},t.RandomId=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))},t.IsBase64=function(e){return!(e.length<5)&&"data:"===e.substr(0,5)},t.DecodeBase64=function(e){for(var t=atob(e.split(",")[1]),i=t.length,r=new Uint8Array(new ArrayBuffer(i)),n=0;n
";t._AddLogEntry(r)},t._WarnDisabled=function(e){},t._WarnEnabled=function(e){var i=t._FormatMessage(e);console.warn("BJS - "+i);var r="
"+i+"

";t._AddLogEntry(r)},t._ErrorDisabled=function(e){},t._ErrorEnabled=function(e){t.errorsCount++;var i=t._FormatMessage(e);console.error("BJS - "+i);var r="
"+i+"

";t._AddLogEntry(r)},Object.defineProperty(t,"LogCache",{get:function(){return t._LogCache},enumerable:!0,configurable:!0}),t.ClearLogCache=function(){t._LogCache="",t.errorsCount=0},Object.defineProperty(t,"LogLevels",{set:function(e){(e&t.MessageLogLevel)===t.MessageLogLevel?t.Log=t._LogEnabled:t.Log=t._LogDisabled,(e&t.WarningLogLevel)===t.WarningLogLevel?t.Warn=t._WarnEnabled:t.Warn=t._WarnDisabled,(e&t.ErrorLogLevel)===t.ErrorLogLevel?t.Error=t._ErrorEnabled:t.Error=t._ErrorDisabled},enumerable:!0,configurable:!0}),t.IsWindowObjectExist=function(){return"undefined"!=typeof window},Object.defineProperty(t,"PerformanceNoneLogLevel",{get:function(){return t._PerformanceNoneLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceUserMarkLogLevel",{get:function(){return t._PerformanceUserMarkLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceConsoleLogLevel",{get:function(){return t._PerformanceConsoleLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceLogLevel",{set:function(e){return(e&t.PerformanceUserMarkLogLevel)===t.PerformanceUserMarkLogLevel?(t.StartPerformanceCounter=t._StartUserMark,void(t.EndPerformanceCounter=t._EndUserMark)):(e&t.PerformanceConsoleLogLevel)===t.PerformanceConsoleLogLevel?(t.StartPerformanceCounter=t._StartPerformanceConsole,void(t.EndPerformanceCounter=t._EndPerformanceConsole)):(t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,void(t.EndPerformanceCounter=t._EndPerformanceCounterDisabled))},enumerable:!0,configurable:!0}),t._StartPerformanceCounterDisabled=function(e,t){},t._EndPerformanceCounterDisabled=function(e,t){},t._StartUserMark=function(e,i){if(void 0===i&&(i=!0),!t._performance){if(!t.IsWindowObjectExist())return;t._performance=window.performance}i&&t._performance.mark&&t._performance.mark(e+"-Begin")},t._EndUserMark=function(e,i){void 0===i&&(i=!0),i&&t._performance.mark&&(t._performance.mark(e+"-End"),t._performance.measure(e,e+"-Begin",e+"-End"))},t._StartPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._StartUserMark(e,i),console.time&&console.time(e))},t._EndPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._EndUserMark(e,i),console.time&&console.timeEnd(e))},Object.defineProperty(t,"Now",{get:function(){return t.IsWindowObjectExist()&&window.performance&&window.performance.now?window.performance.now():Date.now()},enumerable:!0,configurable:!0}),t.GetClassName=function(e,t){void 0===t&&(t=!1);var i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__}i||(i=typeof e)}return i},t.First=function(e,t){for(var i=0,r=e;i=e.length)return null;var r=e.charCodeAt?e.charCodeAt(i):e[i];return r&&r.getHashCode&&(r=r.getHashCode()),"string"==typeof r?t.hashCodeFromStream(t.arrayOrStringFeeder(r)):r}},t.hashCodeFromStream=function(e){for(var t=0,i=0,r=e(i++);null!=r;)t=(t<<5)-t+r,t|=0,r=e(i++);return t},t.DelayAsync=function(e){return new Promise(function(t){setTimeout((function(){t()}),e)})},t.GetCurrentGradient=function(e,t,i){for(var r=0;r=n.gradient&&e<=o.gradient){i(n,o,(e-n.gradient)/(o.gradient-n.gradient))}}},t.BaseUrl="",t.DefaultRetryStrategy=s.ExponentialBackoff(),t.CorsBehavior="anonymous",t.UseFallbackTexture=!0,t.RegisteredExternalClasses={},t.fallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z",t._tmpFloatArray=new Float32Array(1),t.PreprocessUrl=function(e){return e},t._NoneLogLevel=0,t._MessageLogLevel=1,t._WarningLogLevel=2,t._ErrorLogLevel=4,t._LogCache="",t.errorsCount=0,t.Log=t._LogEnabled,t.Warn=t._WarnEnabled,t.Error=t._ErrorEnabled,t._PerformanceNoneLogLevel=0,t._PerformanceUserMarkLogLevel=1,t._PerformanceConsoleLogLevel=2,t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,t.EndPerformanceCounter=t._EndPerformanceCounterDisabled,t})();e.Tools=h;var c=(function(){function e(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}return Object.defineProperty(e.prototype,"min",{get:function(){return this._min},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"max",{get:function(){return this._max},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"average",{get:function(){return this._average},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lastSecAverage",{get:function(){return this._lastSecAverage},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"current",{get:function(){return this._current},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"total",{get:function(){return this._totalAccumulated},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"count",{get:function(){return this._totalValueCount},enumerable:!0,configurable:!0}),e.prototype.fetchNewFrame=function(){this._totalValueCount++,this._current=0,this._lastSecValueCount++},e.prototype.addCount=function(t,i){e.Enabled&&(this._current+=t,i&&this._fetchResult())},e.prototype.beginMonitoring=function(){e.Enabled&&(this._startMonitoringTime=h.Now)},e.prototype.endMonitoring=function(t){if(void 0===t&&(t=!0),e.Enabled){t&&this.fetchNewFrame();var i=h.Now;this._current=i-this._startMonitoringTime,t&&this._fetchResult()}},e.prototype._fetchResult=function(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;var e=h.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)},e.Enabled=!0,e})();e.PerfCounter=c,e.className=t;var u=(function(){function e(e,t,i,r){void 0===r&&(r=0),this.iterations=e,this._fn=t,this._successCallback=i,this.index=r-1,this._done=!1}return e.prototype.executeNext=function(){this._done||(this.index+1=t)break;if(r(s),o&&o()){e.breakLoop();break}}e.executeNext()}),s)}),n)},e})();e.AsyncLoop=u})(r||(r={}));var r;!(function(e){var t;!(function(e){e[e.Pending=0]="Pending",e[e.Fulfilled=1]="Fulfilled",e[e.Rejected=2]="Rejected"})(t||(t={}));var i=(function(){function e(){this.count=0,this.target=0,this.results=[]}return e})(),r=(function(){function r(e){var i=this;if(this._state=t.Pending,this._children=new Array,this._rejectWasConsumed=!1,e)try{e((function(e){i._resolve(e)}),(function(e){i._reject(e)}))}catch(e){this._reject(e)}}return Object.defineProperty(r.prototype,"_result",{get:function(){return this._resultValue},set:function(e){this._resultValue=e,this._parent&&void 0===this._parent._result&&(this._parent._result=e)},enumerable:!0,configurable:!0}),r.prototype.catch=function(e){return this.then(void 0,e)},r.prototype.then=function(i,n){var o=this,s=new r;return s._onFulfilled=i,s._onRejected=n,this._children.push(s),s._parent=this,this._state!==t.Pending&&e.Tools.SetImmediate((function(){if(o._state===t.Fulfilled||o._rejectWasConsumed){var e=s._resolve(o._result);if(void 0!==e&&null!==e)if(void 0!==e._state){var i=e;s._children.push(i),i._parent=s,s=i}else s._result=e}else s._reject(o._reason)})),s},r.prototype._moveChildren=function(e){var i=this;if((l=this._children).push.apply(l,e.splice(0,e.length)),this._children.forEach((function(e){e._parent=i})),this._state===t.Fulfilled)for(var r=0,n=this._children;r-1){if(f.capture&&f.captureConstraint){var m=f.capture,_=f.captureConstraint,g=new RegExp(m),v=g.exec(h);if(v&&v.length>0){var y=parseInt(v[v.length-1]);if(y>=_)continue}}for(var b=0,x=p;b1&&!this.disableUniformBuffers},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"needPOTTextures",{get:function(){return this._webGLVersion<2||this.forcePOTTextures},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"doNotHandleContextLost",{get:function(){return this._doNotHandleContextLost},set:function(e){this._doNotHandleContextLost=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"performanceMonitor",{get:function(){return this._performanceMonitor},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"texturesSupported",{get:function(){return this._texturesSupported},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"currentViewport",{get:function(){return this._cachedViewport},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"emptyTexture",{get:function(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,i.TEXTUREFORMAT_RGBA,!1,!1,i.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"emptyTexture3D",{get:function(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,i.TEXTUREFORMAT_RGBA,!1,!1,i.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture3D},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"emptyCubeTexture",{get:function(){if(!this._emptyCubeTexture){var e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,i.TEXTUREFORMAT_RGBA,i.TEXTURETYPE_UNSIGNED_INT,!1,!1,i.TEXTURE_NEAREST_SAMPLINGMODE)}return this._emptyCubeTexture},enumerable:!0,configurable:!0}),i.prototype._rebuildInternalTextures=function(){for(var e=this._internalTexturesCache.slice(),t=0,i=e;t1||null!==this._gl.getExtension("OES_standard_derivatives"),this._caps.astc=this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),this._caps.s3tc=this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),this._caps.pvrtc=this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),this._caps.etc1=this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),this._caps.etc2=this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),this._caps.textureAnisotropicFilterExtension=this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.uintIndices=this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),this._caps.fragmentDepthSupported=this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),this._caps.highPrecisionShaderSupported=!0,this._caps.timerQuery=this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)>0),this._caps.colorBufferFloat=this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float"),this._caps.textureFloat=!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloat=!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._webGLVersion>1&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._caps.textureLOD=!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),this._webGLVersion>1)this._caps.drawBuffersExtension=!0;else{var t=this._gl.getExtension("WEBGL_draw_buffers");if(null!==t){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=t.drawBuffersWEBGL.bind(t),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(var i=0;i<16;i++)this._gl["COLOR_ATTACHMENT"+i+"_WEBGL"]=t["COLOR_ATTACHMENT"+i+"_WEBGL"]}else this._caps.drawBuffersExtension=!1}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{var r=this._gl.getExtension("WEBGL_depth_texture");null!=r&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=r.UNSIGNED_INT_24_8_WEBGL)}if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{var n=this._gl.getExtension("OES_vertex_array_object");null!=n?(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=n.createVertexArrayOES.bind(n),this._gl.bindVertexArray=n.bindVertexArrayOES.bind(n),this._gl.deleteVertexArray=n.deleteVertexArrayOES.bind(n)):this._caps.vertexArrayObject=!1}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{var s=this._gl.getExtension("ANGLE_instanced_arrays");null!=s?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=s.drawArraysInstancedANGLE.bind(s),this._gl.drawElementsInstanced=s.drawElementsInstancedANGLE.bind(s),this._gl.vertexAttribDivisor=s.vertexAttribDivisorANGLE.bind(s)):this._caps.instancedArrays=!1}if(this._caps.astc&&this.texturesSupported.push("-astc.ktx"),this._caps.s3tc&&this.texturesSupported.push("-dxt.ktx"),this._caps.pvrtc&&this.texturesSupported.push("-pvrtc.ktx"),this._caps.etc2&&this.texturesSupported.push("-etc2.ktx"),this._caps.etc1&&this.texturesSupported.push("-etc1.ktx"),this._gl.getShaderPrecisionFormat){var a=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);a&&(this._caps.highPrecisionShaderSupported=0!==a.precision)}this.setDepthBuffer(!0),this.setDepthFunctionToLessOrEqual(),this.setDepthWrite(!0),this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(var l=0;l=0&&this._activeRenderLoops.splice(t,1)},i.prototype._renderLoop=function(){if(!this._contextWasLost){var t=!0;if(!this.renderEvenInBackground&&this._windowIsBackground&&(t=!1),t){this.beginFrame();for(var i=0;i0){var r=null;this._vrDisplay&&this._vrDisplay.isPresenting&&(r=this._vrDisplay),this._frameHandler=e.Tools.QueueNewFrame(this._bindedRenderFunction,r)}else this._renderingQueueLaunched=!1},i.prototype.runRenderLoop=function(t){-1===this._activeRenderLoops.indexOf(t)&&(this._activeRenderLoops.push(t),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._bindedRenderFunction=this._renderLoop.bind(this),this._frameHandler=e.Tools.QueueNewFrame(this._bindedRenderFunction)))},i.prototype.switchFullscreen=function(t){this.isFullscreen?e.Tools.ExitFullscreen():(this._pointerLockRequested=t,this._renderingCanvas&&e.Tools.RequestFullscreen(this._renderingCanvas))},i.prototype.clear=function(e,t,i,r){void 0===r&&(r=!1),this.applyStates();var n=0;t&&e&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),n|=this._gl.COLOR_BUFFER_BIT),i&&(this._gl.clearDepth(1),n|=this._gl.DEPTH_BUFFER_BIT),r&&(this._gl.clearStencil(0),n|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(n)},i.prototype.scissorClear=function(e,t,i,r,n){var o=this._gl,s=o.getParameter(o.SCISSOR_TEST),a=o.getParameter(o.SCISSOR_BOX);o.enable(o.SCISSOR_TEST),o.scissor(e,t,i,r),this.clear(n,!0,!0,!0),o.scissor(a[0],a[1],a[2],a[3]),!0===s?o.enable(o.SCISSOR_TEST):o.disable(o.SCISSOR_TEST)},i.prototype._viewport=function(e,t,i,r){e===this._viewportCached.x&&t===this._viewportCached.y&&i===this._viewportCached.z&&r===this._viewportCached.w||(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r,this._gl.viewport(e,t,i,r))},i.prototype.setViewport=function(e,t,i){var r=t||this.getRenderWidth(),n=i||this.getRenderHeight(),o=e.x||0,s=e.y||0;this._cachedViewport=e,this._viewport(o*r,s*n,r*e.width,n*e.height)},i.prototype.setDirectViewport=function(e,t,i,r){var n=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),n},i.prototype.beginFrame=function(){this.onBeginFrameObservable.notifyObservers(this),this._measureFps()},i.prototype.endFrame=function(){this._badOS&&this.flushFramebuffer(),this._vrDisplay&&this._vrDisplay.isPresenting&&this._vrDisplay.submitFrame(),this.onEndFrameObservable.notifyObservers(this)},i.prototype.resize=function(){if(!this._vrDisplay||!this._vrDisplay.isPresenting){var e=this._renderingCanvas?this._renderingCanvas.clientWidth:window.innerWidth,t=this._renderingCanvas?this._renderingCanvas.clientHeight:window.innerHeight;this.setSize(e/this._hardwareScalingLevel,t/this._hardwareScalingLevel)}},i.prototype.setSize=function(e,t){if(this._renderingCanvas&&(this._renderingCanvas.width!==e||this._renderingCanvas.height!==t)){this._renderingCanvas.width=e,this._renderingCanvas.height=t;for(var i=0;i1?"COLOR_ATTACHMENT"+o:"COLOR_ATTACHMENT"+o+"_WEBGL"],r.readBuffer(n[o]),r.drawBuffers(n),r.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(var o=0;o1?"COLOR_ATTACHMENT"+o:"COLOR_ATTACHMENT"+o+"_WEBGL"];r.drawBuffers(n)}for(var o=0;o65535){n=!0;break}r=n?new Uint32Array(e):new Uint16Array(e)}else r=new Uint16Array(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),i.references=1,i.is32Bits=n,i},i.prototype.bindArrayBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(e,this._gl.ARRAY_BUFFER)},i.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e)},i.prototype.bindUniformBufferBase=function(e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e)},i.prototype.bindUniformBlock=function(e,t,i){var r=this._gl.getUniformBlockIndex(e,t);this._gl.uniformBlockBinding(e,r,i)},i.prototype.bindIndexBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)},i.prototype.bindBuffer=function(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e),this._currentBoundBuffer[t]=e)},i.prototype.updateArrayBuffer=function(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)},i.prototype._vertexAttribPointer=function(e,t,i,r,n,o,s){var a=this._currentBufferPointers[t],l=!1;a.active?(a.buffer!==e&&(a.buffer=e,l=!0),a.size!==i&&(a.size=i,l=!0),a.type!==r&&(a.type=r,l=!0),a.normalized!==n&&(a.normalized=n,l=!0),a.stride!==o&&(a.stride=o,l=!0),a.offset!==s&&(a.offset=s,l=!0)):(l=!0,a.active=!0,a.index=t,a.size=i,a.type=r,a.normalized=n,a.stride=o,a.offset=s,a.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),this._gl.vertexAttribPointer(t,i,r,n,o,s))},i.prototype._bindIndexBufferWithCache=function(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)},i.prototype._bindVertexBuffersAttributes=function(e,t){var i=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var r=0;r=0){var o=e[i[r]];if(!o)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);var s=o.getBuffer();s&&(this._vertexAttribPointer(s,n,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(s))))}}},i.prototype.recordVertexArrayObject=function(e,t,i){var r=this._gl.createVertexArray();return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r},i.prototype.bindVertexArrayObject=function(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)},i.prototype.bindBuffersDirectly=function(e,t,i,r,n){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==n){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=n;var o=n.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var s=0,a=0;a=0&&(this._gl.enableVertexAttribArray(l),this._vertexAttribArraysEnabled[l]=!0,this._vertexAttribPointer(e,l,i[a],this._gl.FLOAT,!1,r,s)),s+=4*i[a]}}this._bindIndexBufferWithCache(t)},i.prototype._unbindVertexArrayObject=function(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))},i.prototype.bindBuffers=function(e,t,i){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i)),this._bindIndexBufferWithCache(t)},i.prototype.unbindInstanceAttributes=function(){for(var e,t=0,i=this._currentInstanceLocations.length;t1?"#version 300 es\n#define WEBGL2 \n":"",s=this._compileShader(e,"vertex",i,o),a=this._compileShader(t,"fragment",i,o),l=this._createShaderProgram(s,a,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),l},i.prototype._createShaderProgram=function(e,t,i,r){void 0===r&&(r=null);var n=i.createProgram();if(!n)throw new Error("Unable to create program");if(i.attachShader(n,e),i.attachShader(n,t),this.webGLVersion>1&&r){var o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(n,r),n.transformFeedback=o}if(i.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),!i.getProgramParameter(n,i.LINK_STATUS)){var s=i.getProgramInfoLog(n);if(s)throw new Error(s)}if(this.validateShaderPrograms){i.validateProgram(n);if(!i.getProgramParameter(n,i.VALIDATE_STATUS)){var s=i.getProgramInfoLog(n);if(s)throw new Error(s)}}return i.deleteShader(e),i.deleteShader(t),n},i.prototype.getUniforms=function(e,t){for(var i=new Array,r=0;r-1?p.substring(y).toLowerCase():""),x=null,T=0,E=i._TextureLoaders;Th||t.height>h)return d._prepareWorkingCanvas(),!(!d._workingCanvas||!d._workingContext)&&(d._workingCanvas.width=i,d._workingCanvas.height=r,d._workingContext.drawImage(t,0,0,t.width,t.height,0,0,i,r),s.texImage2D(s.TEXTURE_2D,0,l,l,s.UNSIGNED_BYTE,d._workingCanvas),v.width=i,v.height=r,!1);var c=new e.InternalTexture(d,e.InternalTexture.DATASOURCE_TEMP);return d._bindTextureDirectly(s.TEXTURE_2D,c,!0),s.texImage2D(s.TEXTURE_2D,0,l,l,s.UNSIGNED_BYTE,t),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),d._rescaleTexture(c,v,o,l,(function(){d._releaseTexture(c),d._bindTextureDirectly(s.TEXTURE_2D,v,!0),n()})),!0}),s)};!m||g?h instanceof HTMLImageElement?R(h):e.Tools.LoadImage(p,R,M,o?o.database:null):"string"==typeof h||h instanceof ArrayBuffer||h instanceof Blob?e.Tools.LoadImage(h,R,M,o?o.database:null):R(h)}return v},i.prototype._rescaleTexture=function(t,r,n,o,s){var a=this,l=this.createRenderTargetTexture({width:r.width,height:r.height},{generateMipMaps:!1,type:i.TEXTURETYPE_UNSIGNED_INT,samplingMode:i.TEXTURE_BILINEAR_SAMPLINGMODE,generateDepthBuffer:!1,generateStencilBuffer:!1});this._rescalePostProcess||(this._rescalePostProcess=new e.PassPostProcess("rescale",1,null,i.TEXTURE_BILINEAR_SAMPLINGMODE,this,!1,i.TEXTURETYPE_UNSIGNED_INT)),this._rescalePostProcess.getEffect().executeWhenCompiled((function(){a._rescalePostProcess.onApply=function(e){e._bindTexture("textureSampler",t)};var e=n;e||(e=a.scenes[a.scenes.length-1]),e.postProcessManager.directRender([a._rescalePostProcess],l,!0),a._bindTextureDirectly(a._gl.TEXTURE_2D,r,!0),a._gl.copyTexImage2D(a._gl.TEXTURE_2D,0,o,0,0,r.width,r.height,0),a.unBindFramebuffer(l),a._releaseTexture(l),s&&s()}))},i.prototype.updateRawTexture=function(e,t,r,n,o,s){if(void 0===o&&(o=null),void 0===s&&(s=i.TEXTURETYPE_UNSIGNED_INT),e){var a=this._getRGBABufferInternalSizedFormat(s,r),l=this._getInternalFormat(r),h=this._getWebGLTextureType(s);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(e._bufferView=t,e.format=r,e.type=s,e.invertY=n,e._compression=o),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),o&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[o],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}},i.prototype.createRawTexture=function(t,r,n,o,s,a,l,h,c){void 0===h&&(h=null),void 0===c&&(c=i.TEXTURETYPE_UNSIGNED_INT);var u=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RAW);u.baseWidth=r,u.baseHeight=n,u.width=r,u.height=n,u.format=o,u.generateMipMaps=s,u.samplingMode=l,u.invertY=a,u._compression=h,u.type=c,this._doNotHandleContextLost||(u._bufferView=t),this.updateRawTexture(u,t,o,a,h,c),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);var f=this._getSamplingParameters(l,s);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,f.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,f.min),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},i.prototype._unpackFlipY=function(e){this._unpackFlipYCached!==e&&(this._unpackFlipYCached=e,this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0))},i.prototype._getUnpackAlignement=function(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}, -i.prototype.createDynamicTexture=function(t,i,r,n){var o=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_DYNAMIC);return o.baseWidth=t,o.baseHeight=i,r&&(t=this.needPOTTextures?e.Tools.GetExponentOfTwo(t,this._caps.maxTextureSize):t,i=this.needPOTTextures?e.Tools.GetExponentOfTwo(i,this._caps.maxTextureSize):i),o.width=t,o.height=i,o.isReady=!1,o.generateMipMaps=r,o.samplingMode=n,this.updateTextureSamplingMode(n,o),this._internalTexturesCache.push(o),o},i.prototype.updateTextureSamplingMode=function(e,t){var i=this._getSamplingParameters(e,t.generateMipMaps);t.isCube?(this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):t.is3D?(this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_3D,null)):(this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),t.samplingMode=e},i.prototype.updateDynamicTexture=function(e,t,i,r,n){if(void 0===r&&(r=!1),e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(i),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);var o=n?this._getInternalFormat(n):this._gl.RGBA;this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,o,this._gl.UNSIGNED_BYTE,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0}},i.prototype.updateVideoTexture=function(e,t,i){if(e&&!e._isDisabled){var r=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=document.createElement("canvas");var n=e._workingCanvas.getContext("2d");if(!n)throw new Error("Unable to get 2d context");e._workingContext=n,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),r||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}}},i.prototype.updateTextureComparisonFunction=function(t,r){if(1===this.webGLVersion)return void e.Tools.Error("WebGL 1 does not support texture comparison.");var n=this._gl;t.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,t,!0),0===r?(n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_FUNC,i.LEQUAL),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_MODE,n.NONE)):(n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_FUNC,r),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),0===r?(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_FUNC,i.LEQUAL),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_MODE,n.NONE)):(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_FUNC,r),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),t._comparisonFunction=r},i.prototype._setupDepthStencilTexture=function(e,t,r,n,o){var s=t.width||t,a=t.height||t;e.baseWidth=s,e.baseHeight=a,e.width=s,e.height=a,e.isReady=!0,e.samples=1,e.generateMipMaps=!1,e._generateDepthBuffer=!0,e._generateStencilBuffer=r,e.samplingMode=n?i.TEXTURE_BILINEAR_SAMPLINGMODE:i.TEXTURE_NEAREST_SAMPLINGMODE,e.type=i.TEXTURETYPE_UNSIGNED_INT,e._comparisonFunction=o;var l=this._gl,h=e.isCube?l.TEXTURE_CUBE_MAP:l.TEXTURE_2D,c=this._getSamplingParameters(e.samplingMode,!1);l.texParameteri(h,l.TEXTURE_MAG_FILTER,c.mag),l.texParameteri(h,l.TEXTURE_MIN_FILTER,c.min),l.texParameteri(h,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(h,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),0===o?(l.texParameteri(h,l.TEXTURE_COMPARE_FUNC,i.LEQUAL),l.texParameteri(h,l.TEXTURE_COMPARE_MODE,l.NONE)):(l.texParameteri(h,l.TEXTURE_COMPARE_FUNC,o),l.texParameteri(h,l.TEXTURE_COMPARE_MODE,l.COMPARE_REF_TO_TEXTURE))},i.prototype.createDepthStencilTexture=function(e,t){if(t.isCube){var i=e.width||e;return this._createDepthStencilCubeTexture(i,t)}return this._createDepthStencilTexture(e,t)},i.prototype._createDepthStencilTexture=function(t,i){var r=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_DEPTHTEXTURE);if(!this._caps.depthTextureExtension)return e.Tools.Error("Depth texture is not supported by your browser or hardware."),r;var n=s({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},i),o=this._gl;return this._bindTextureDirectly(o.TEXTURE_2D,r,!0),this._setupDepthStencilTexture(r,t,n.generateStencil,n.bilinearFiltering,n.comparisonFunction),this.webGLVersion>1?n.generateStencil?o.texImage2D(o.TEXTURE_2D,0,o.DEPTH24_STENCIL8,r.width,r.height,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_COMPONENT24,r.width,r.height,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null):n.generateStencil?o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_STENCIL,r.width,r.height,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_COMPONENT,r.width,r.height,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null),this._bindTextureDirectly(o.TEXTURE_2D,null),r},i.prototype._createDepthStencilCubeTexture=function(t,i){var r=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_UNKNOWN);if(r.isCube=!0,1===this.webGLVersion)return e.Tools.Error("Depth cube texture is not supported by WebGL 1."),r;var n=s({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},i),o=this._gl;this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,r,!0),this._setupDepthStencilTexture(r,t,n.generateStencil,n.bilinearFiltering,n.comparisonFunction);for(var a=0;a<6;a++)n.generateStencil?o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,o.DEPTH24_STENCIL8,t,t,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,o.DEPTH_COMPONENT24,t,t,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null);return this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null),r},i.prototype.setFrameBufferDepthStencilTexture=function(e){var t=e.getInternalTexture();if(t&&t._framebuffer&&e.depthStencilTexture){var i=this._gl,r=e.depthStencilTexture;this.bindUnboundFramebuffer(t._framebuffer),r.isCube?r._generateStencilBuffer?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_CUBE_MAP_POSITIVE_X,r._webGLTexture,0):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_CUBE_MAP_POSITIVE_X,r._webGLTexture,0):r._generateStencilBuffer?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_2D,r._webGLTexture,0):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,r._webGLTexture,0),this.bindUnboundFramebuffer(null)}},i.prototype.createRenderTargetTexture=function(t,n){var o=new r;void 0!==n&&"object"==typeof n?(o.generateMipMaps=n.generateMipMaps,o.generateDepthBuffer=void 0===n.generateDepthBuffer||n.generateDepthBuffer,o.generateStencilBuffer=o.generateDepthBuffer&&n.generateStencilBuffer,o.type=void 0===n.type?i.TEXTURETYPE_UNSIGNED_INT:n.type,o.samplingMode=void 0===n.samplingMode?i.TEXTURE_TRILINEAR_SAMPLINGMODE:n.samplingMode,o.format=void 0===n.format?i.TEXTUREFORMAT_RGBA:n.format):(o.generateMipMaps=n,o.generateDepthBuffer=!0,o.generateStencilBuffer=!1,o.type=i.TEXTURETYPE_UNSIGNED_INT,o.samplingMode=i.TEXTURE_TRILINEAR_SAMPLINGMODE,o.format=i.TEXTUREFORMAT_RGBA),o.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering?o.type!==i.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering||(o.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE):o.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE;var s=this._gl,a=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RENDERTARGET);this._bindTextureDirectly(s.TEXTURE_2D,a,!0);var l=t.width||t,h=t.height||t,c=this._getSamplingParameters(o.samplingMode,!!o.generateMipMaps);o.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloat||(o.type=i.TEXTURETYPE_UNSIGNED_INT,e.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,c.mag),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,c.min),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(o.type,o.format),l,h,0,this._getInternalFormat(o.format),this._getWebGLTextureType(o.type),null);var u=this._currentFramebuffer,f=s.createFramebuffer();return this.bindUnboundFramebuffer(f),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,a._webGLTexture,0),a._depthStencilBuffer=this._setupFramebufferDepthAttachments(!!o.generateStencilBuffer,o.generateDepthBuffer,l,h),o.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),this.bindUnboundFramebuffer(u),a._framebuffer=f,a.baseWidth=l,a.baseHeight=h,a.width=l,a.height=h,a.isReady=!0,a.samples=1,a.generateMipMaps=!!o.generateMipMaps,a.samplingMode=o.samplingMode,a.type=o.type,a._generateDepthBuffer=o.generateDepthBuffer,a._generateStencilBuffer=!!o.generateStencilBuffer,this._internalTexturesCache.push(a),a},i.prototype.createMultipleRenderTarget=function(t,r){var n=!1,o=!0,s=!1,a=!1,l=1,h=i.TEXTURETYPE_UNSIGNED_INT,c=i.TEXTURE_TRILINEAR_SAMPLINGMODE,u=new Array,f=new Array;void 0!==r&&(n=void 0!==r.generateMipMaps&&r.generateMipMaps,o=void 0===r.generateDepthBuffer||r.generateDepthBuffer,s=void 0!==r.generateStencilBuffer&&r.generateStencilBuffer,a=void 0!==r.generateDepthTexture&&r.generateDepthTexture,l=r.textureCount||1,r.types&&(u=r.types),r.samplingModes&&(f=r.samplingModes));var d=this._gl,p=d.createFramebuffer();this.bindUnboundFramebuffer(p);for(var m=t.width||t,_=t.height||t,g=[],v=[],y=this._setupFramebufferDepthAttachments(s,o,m,_),b=0;b1?"COLOR_ATTACHMENT"+b:"COLOR_ATTACHMENT"+b+"_WEBGL"];g.push(P),v.push(A),d.activeTexture(d["TEXTURE"+b]),d.bindTexture(d.TEXTURE_2D,P._webGLTexture),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MAG_FILTER,E.mag),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MIN_FILTER,E.min),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),d.texImage2D(d.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(T),m,_,0,d.RGBA,this._getWebGLTextureType(T),null),d.framebufferTexture2D(d.DRAW_FRAMEBUFFER,A,d.TEXTURE_2D,P._webGLTexture,0),n&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(d.TEXTURE_2D,null),P._framebuffer=p,P._depthStencilBuffer=y,P.baseWidth=m,P.baseHeight=_,P.width=m,P.height=_,P.isReady=!0,P.samples=1,P.generateMipMaps=n,P.samplingMode=x,P.type=T,P._generateDepthBuffer=o,P._generateStencilBuffer=s,P._attachments=v,this._internalTexturesCache.push(P)}if(a&&this._caps.depthTextureExtension){var M=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_MULTIRENDERTARGET);d.activeTexture(d.TEXTURE0),d.bindTexture(d.TEXTURE_2D,M._webGLTexture),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MAG_FILTER,d.NEAREST),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MIN_FILTER,d.NEAREST),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),d.texImage2D(d.TEXTURE_2D,0,this.webGLVersion<2?d.DEPTH_COMPONENT:d.DEPTH_COMPONENT16,m,_,0,d.DEPTH_COMPONENT,d.UNSIGNED_SHORT,null),d.framebufferTexture2D(d.FRAMEBUFFER,d.DEPTH_ATTACHMENT,d.TEXTURE_2D,M._webGLTexture,0),M._framebuffer=p,M.baseWidth=m,M.baseHeight=_,M.width=m,M.height=_,M.isReady=!0,M.samples=1,M.generateMipMaps=n,M.samplingMode=d.NEAREST,M._generateDepthBuffer=o,M._generateStencilBuffer=s,g.push(M),this._internalTexturesCache.push(M)}return d.drawBuffers(v),d.bindRenderbuffer(d.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),this.resetTextureCache(),g},i.prototype._setupFramebufferDepthAttachments=function(e,t,i,r,n){void 0===n&&(n=1);var o=null,s=this._gl;return e?(o=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,o),n>1?s.renderbufferStorageMultisample(s.RENDERBUFFER,n,s.DEPTH24_STENCIL8,i,r):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,i,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,o)):t&&(o=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,o),n>1?s.renderbufferStorageMultisample(s.RENDERBUFFER,n,s.DEPTH_COMPONENT16,i,r):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT16,i,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,o)),o},i.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e)return 1;if(e.samples===t)return t;var i=this._gl;if(t=Math.min(t,i.getParameter(i.MAX_SAMPLES)),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),e._MSAARenderBuffer&&(i.deleteRenderbuffer(e._MSAARenderBuffer),e._MSAARenderBuffer=null),t>1){var r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this.bindUnboundFramebuffer(e._MSAAFramebuffer);var n=i.createRenderbuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorageMultisample(i.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(e.type),e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,n),e._MSAARenderBuffer=n}else this.bindUnboundFramebuffer(e._framebuffer);return e.samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.width,e.height,t),i.bindRenderbuffer(i.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),t},i.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||0==e.length)return 1;if(e[0].samples===t)return t;var i=this._gl;t=Math.min(t,i.getParameter(i.MAX_SAMPLES)),e[0]._depthStencilBuffer&&(i.deleteRenderbuffer(e[0]._depthStencilBuffer),e[0]._depthStencilBuffer=null),e[0]._MSAAFramebuffer&&(i.deleteFramebuffer(e[0]._MSAAFramebuffer),e[0]._MSAAFramebuffer=null);for(var r=0;r1){var n=i.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");this.bindUnboundFramebuffer(n);for(var o=this._setupFramebufferDepthAttachments(e[0]._generateStencilBuffer,e[0]._generateDepthBuffer,e[0].width,e[0].height,t),s=[],r=0;r1?"COLOR_ATTACHMENT"+r:"COLOR_ATTACHMENT"+r+"_WEBGL"],h=i.createRenderbuffer();if(!h)throw new Error("Unable to create multi sampled framebuffer");i.bindRenderbuffer(i.RENDERBUFFER,h),i.renderbufferStorageMultisample(i.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(a.type),a.width,a.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,l,i.RENDERBUFFER,h),a._MSAAFramebuffer=n,a._MSAARenderBuffer=h,a.samples=t,a._depthStencilBuffer=o,i.bindRenderbuffer(i.RENDERBUFFER,null),s.push(l)}i.drawBuffers(s)}else this.bindUnboundFramebuffer(e[0]._framebuffer);return this.bindUnboundFramebuffer(null),t},i.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,r,n,o,s){void 0===o&&(o=0),void 0===s&&(s=0);var a=this._gl,l=a.TEXTURE_2D;e.isCube&&(l=a.TEXTURE_CUBE_MAP_POSITIVE_X+o),this._gl.compressedTexImage2D(l,s,t,i,r,0,n)},i.prototype._uploadDataToTextureDirectly=function(t,i,r,n){void 0===r&&(r=0),void 0===n&&(n=0);var o=this._gl,s=this._getWebGLTextureType(t.type),a=this._getInternalFormat(t.format),l=this._getRGBABufferInternalSizedFormat(t.type,a);this._unpackFlipY(t.invertY);var h=o.TEXTURE_2D;t.isCube&&(h=o.TEXTURE_CUBE_MAP_POSITIVE_X+r);var c=Math.round(e.Scalar.Log2(t.width)),u=Math.round(e.Scalar.Log2(t.height)),f=Math.pow(2,Math.max(c-n,0)),d=Math.pow(2,Math.max(u-n,0));o.texImage2D(h,n,l,f,d,0,a,s,i)},i.prototype._uploadArrayBufferViewToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0);var n=this._gl,o=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(o,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(o,null,!0)},i.prototype._uploadImageToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0);var n=this._gl,o=this._getWebGLTextureType(e.type),s=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,s),l=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);var h=n.TEXTURE_2D;e.isCube&&(h=n.TEXTURE_CUBE_MAP_POSITIVE_X+i),n.texImage2D(h,r,a,s,o,t),this._bindTextureDirectly(l,null,!0)},i.prototype.createRenderTargetCubeTexture=function(t,r){var n=s({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:i.TEXTURETYPE_UNSIGNED_INT,samplingMode:i.TEXTURE_TRILINEAR_SAMPLINGMODE,format:i.TEXTUREFORMAT_RGBA},r);n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,n.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering?n.type!==i.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering||(n.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE):n.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE;var o=this._gl,a=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RENDERTARGET);this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,a,!0);var l=this._getSamplingParameters(n.samplingMode,n.generateMipMaps);n.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloat||(n.type=i.TEXTURETYPE_UNSIGNED_INT,e.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,l.mag),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,l.min),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE);for(var h=0;h<6;h++)o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+h,0,this._getRGBABufferInternalSizedFormat(n.type,n.format),t,t,0,this._getInternalFormat(n.format),this._getWebGLTextureType(n.type),null);var c=o.createFramebuffer();return this.bindUnboundFramebuffer(c),a._depthStencilBuffer=this._setupFramebufferDepthAttachments(n.generateStencilBuffer,n.generateDepthBuffer,t,t),n.generateMipMaps&&o.generateMipmap(o.TEXTURE_CUBE_MAP),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null),o.bindRenderbuffer(o.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),a._framebuffer=c,a.width=t,a.height=t,a.isReady=!0,a.isCube=!0,a.samples=1,a.generateMipMaps=n.generateMipMaps,a.samplingMode=n.samplingMode,a.type=n.type,a._generateDepthBuffer=n.generateDepthBuffer,a._generateStencilBuffer=n.generateStencilBuffer,this._internalTexturesCache.push(a),a},i.prototype.createPrefilteredCubeTexture=function(t,i,r,n,o,s,a,l,h){var c=this;void 0===o&&(o=null),void 0===s&&(s=null),void 0===l&&(l=null),void 0===h&&(h=!0);var u=function(t){if(!t)return void(o&&o(null));var s=t.texture;if(h?t.info.sphericalPolynomial&&(s._sphericalPolynomial=t.info.sphericalPolynomial):s._sphericalPolynomial=new e.SphericalPolynomial,s._dataSource=e.InternalTexture.DATASOURCE_CUBEPREFILTERED,c._caps.textureLOD)return void(o&&o(s));var a=c._gl,l=t.width;if(l){for(var u=[],f=0;f<3;f++){var d=f/2,p=1-d,m=n,_=e.Scalar.Log2(l)*r+n,g=m+(_-m)*p,v=Math.round(Math.min(Math.max(g,0),_)),y=new e.InternalTexture(c,e.InternalTexture.DATASOURCE_TEMP);if(y.type=s.type,y.format=s.format,y.width=Math.pow(2,Math.max(e.Scalar.Log2(l)-v,0)),y.height=y.width,y.isCube=!0,c._bindTextureDirectly(a.TEXTURE_CUBE_MAP,y,!0),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),t.isDDS){var b=t.info,x=t.data;c._unpackFlipY(b.isCompressed),e.DDSTools.UploadDDSLevels(c,y,x,b,!0,6,v)}else e.Tools.Warn("DDS is the only prefiltered cube map supported so far.");c._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);var T=new e.BaseTexture(i);T.isCube=!0,T._texture=y,y.isReady=!0,u.push(T)}s._lodTextureHigh=u[2],s._lodTextureMid=u[1],s._lodTextureLow=u[0],o&&o(s)}};return this.createCubeTexture(t,i,null,!1,u,s,a,l,h,r,n)},i.prototype.createCubeTexture=function(t,r,n,o,s,a,l,h,c,u,f,d){var p=this;void 0===s&&(s=null),void 0===a&&(a=null),void 0===h&&(h=null),void 0===c&&(c=!1),void 0===u&&(u=0),void 0===f&&(f=0),void 0===d&&(d=null);var m=this._gl,_=d||new e.InternalTexture(this,e.InternalTexture.DATASOURCE_CUBE);_.isCube=!0,_.url=t,_.generateMipMaps=!o,_._lodGenerationScale=u,_._lodGenerationOffset=f,this._doNotHandleContextLost||(_._extension=h,_._files=n);for(var g=t.lastIndexOf("."),v=h||(g>-1?t.substring(g).toLowerCase():""),y=null,b=0,x=i._TextureLoaders;b>v,b=0;b<6;b++){var x=g[v][b];_&&(x=d._convertRGBtoRGBATextureData(x,y,y,o)),p.texImage2D(b,v,u,y,y,0,c,s,x)}d._bindTextureDirectly(p.TEXTURE_CUBE_MAP,null)}else d.updateRawCubeTexture(m,r,n,o,f);m.isReady=!0,t._removePendingData(m),h&&h()}};return this._loadFile(e,(function(e){g(e)}),void 0,t.database,!0,_),m},i.prototype.updateRawTexture3D=function(e,t,r,n,o,s){void 0===o&&(o=null),void 0===s&&(s=i.TEXTURETYPE_UNSIGNED_INT);var a=this._getWebGLTextureType(s),l=this._getInternalFormat(r),h=this._getRGBABufferInternalSizedFormat(s,r);this._bindTextureDirectly(this._gl.TEXTURE_3D,e,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(e._bufferView=t,e.format=r,e.invertY=n,e._compression=o),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),o&&t?this._gl.compressedTexImage3D(this._gl.TEXTURE_3D,0,this.getCaps().s3tc[o],e.width,e.height,e.depth,0,t):this._gl.texImage3D(this._gl.TEXTURE_3D,0,h,e.width,e.height,e.depth,0,l,a,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_3D),this._bindTextureDirectly(this._gl.TEXTURE_3D,null),e.isReady=!0},i.prototype.createRawTexture3D=function(t,r,n,o,s,a,l,h,c,u){void 0===c&&(c=null),void 0===u&&(u=i.TEXTURETYPE_UNSIGNED_INT);var f=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RAW3D);f.baseWidth=r,f.baseHeight=n,f.baseDepth=o,f.width=r,f.height=n,f.depth=o,f.format=s,f.type=u,f.generateMipMaps=a,f.samplingMode=h,f.is3D=!0,this._doNotHandleContextLost||(f._bufferView=t),this.updateRawTexture3D(f,t,s,l,c,u),this._bindTextureDirectly(this._gl.TEXTURE_3D,f,!0);var d=this._getSamplingParameters(h,a);return this._gl.texParameteri(this._gl.TEXTURE_3D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_3D,this._gl.TEXTURE_MIN_FILTER,d.min),a&&this._gl.generateMipmap(this._gl.TEXTURE_3D),this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._internalTexturesCache.push(f),f},i.prototype._prepareWebGLTextureContinuation=function(e,t,i,r,n){var o=this._gl;if(o){var s=this._getSamplingParameters(n,!i);o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,s.mag),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,s.min),i||r||o.generateMipmap(o.TEXTURE_2D),this._bindTextureDirectly(o.TEXTURE_2D,null),t&&t._removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}},i.prototype._prepareWebGLTexture=function(t,r,n,o,s,a,l,h,c){var u=this;void 0===c&&(c=i.TEXTURE_TRILINEAR_SAMPLINGMODE);var f=this.getCaps().maxTextureSize,d=Math.min(f,this.needPOTTextures?e.Tools.GetExponentOfTwo(n,f):n),p=Math.min(f,this.needPOTTextures?e.Tools.GetExponentOfTwo(o,f):o),m=this._gl;if(m){if(!t._webGLTexture)return void(r&&r._removePendingData(t));this._bindTextureDirectly(m.TEXTURE_2D,t,!0),this._unpackFlipY(void 0===s||!!s),t.baseWidth=n,t.baseHeight=o,t.width=d,t.height=p,t.isReady=!0,h(d,p,(function(){u._prepareWebGLTextureContinuation(t,r,a,l,c)}))||this._prepareWebGLTextureContinuation(t,r,a,l,c)}},i.prototype._convertRGBtoRGBATextureData=function(e,t,r,n){var o;o=n===i.TEXTURETYPE_FLOAT?new Float32Array(t*r*4):new Uint32Array(t*r*4);for(var s=0;s-1?t._designatedSlot:this._nextFreeTextureSlots.length?this._nextFreeTextureSlots[0]:(this._textureCollisions.addCount(1,!1),this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next));return e},i.prototype._linkTrackers=function(e,t){e.next=t,t.previous=e},i.prototype._removeDesignatedSlot=function(e){var t=e._designatedSlot;return-1===t?-1:(e._designatedSlot=-1,this.disableTextureBindingOptimization?-1:(this._linkTrackers(e.previous,e.next),this._boundTexturesCache[t]=null,this._nextFreeTextureSlots.push(t),t))},i.prototype._activateCurrentTexture=function(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)},i.prototype._bindTextureDirectly=function(e,t,i,r){void 0===i&&(i=!1),void 0===r&&(r=!1);var n=!1;i&&t&&t._designatedSlot>-1&&(this._activeChannel=t._designatedSlot);var o=this._boundTexturesCache[this._activeChannel],s=t&&t._initialSlot>-1;if(o!==t||r){if(o&&this._removeDesignatedSlot(o),this._activateCurrentTexture(),this._gl.bindTexture(e,t?t._webGLTexture:null),this._boundTexturesCache[this._activeChannel]=t,t){if(!this.disableTextureBindingOptimization){var a=this._nextFreeTextureSlots.indexOf(this._activeChannel);a>-1&&this._nextFreeTextureSlots.splice(a,1),this._linkTrackers(this._lastBoundInternalTextureTracker.previous,t),this._linkTrackers(t,this._lastBoundInternalTextureTracker)}t._designatedSlot=this._activeChannel}}else i&&(n=!0,this._activateCurrentTexture());return s&&!i&&this._bindSamplerUniformToChannel(t._initialSlot,this._activeChannel),n},i.prototype._bindTexture=function(e,t){e<0||(t&&(e=this._getCorrectTextureChannel(e,t)),this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,t))},i.prototype.setTextureFromPostProcess=function(e,t){this._bindTexture(e,t?t._textures.data[t._currentRenderTextureInd]:null)},i.prototype.setTextureFromPostProcessOutput=function(e,t){this._bindTexture(e,t?t._outputTexture:null)},i.prototype.unbindAllTextures=function(){for(var e=0;e1&&this._bindTextureDirectly(this._gl.TEXTURE_3D,null)},i.prototype.setTexture=function(e,t,i){e<0||(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))},i.prototype.setDepthStencilTexture=function(e,t,i){e<0||(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0):this._setTexture(e,null))},i.prototype._bindSamplerUniformToChannel=function(e,t){var i=this._boundUniforms[e];i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)},i.prototype._getTextureWrapMode=function(e){switch(e){case i.TEXTURE_WRAP_ADDRESSMODE:return this._gl.REPEAT;case i.TEXTURE_CLAMP_ADDRESSMODE:return this._gl.CLAMP_TO_EDGE;case i.TEXTURE_MIRROR_ADDRESSMODE:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT},i.prototype._setTexture=function(e,t,r,n){if(void 0===r&&(r=!1),void 0===n&&(n=!1),!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&this._bindTextureDirectly(this._gl.TEXTURE_3D,null)),!1;if(t.video)this._activeChannel=e,t.update();else if(t.delayLoadState===i.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;var o;o=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:this.emptyTexture,r||(e=this._getCorrectTextureChannel(e,o));var s=!0;if(this._boundTexturesCache[e]===o&&(this._moveBoundTextureOnTop(o),r||this._bindSamplerUniformToChannel(o._initialSlot,e),s=!1),this._activeChannel=e,o&&o.is3D)s&&this._bindTextureDirectly(this._gl.TEXTURE_3D,o,r),o&&o._cachedWrapU!==t.wrapU&&(o._cachedWrapU=t.wrapU,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),o)),o&&o._cachedWrapV!==t.wrapV&&(o._cachedWrapV=t.wrapV,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),o)),o&&o._cachedWrapR!==t.wrapR&&(o._cachedWrapR=t.wrapR,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),o)),this._setAnisotropicLevel(this._gl.TEXTURE_3D,t);else if(o&&o.isCube){if(s&&this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,o,r),o._cachedCoordinatesMode!==t.coordinatesMode){o._cachedCoordinatesMode=t.coordinatesMode;var a=t.coordinatesMode!==i.TEXTURE_CUBIC_MODE&&t.coordinatesMode!==i.TEXTURE_SKYBOX_MODE?this._gl.REPEAT:this._gl.CLAMP_TO_EDGE;this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_S,a,o),this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_T,a)}this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP,t)}else s&&this._bindTextureDirectly(this._gl.TEXTURE_2D,o,r),o&&o._cachedWrapU!==t.wrapU&&(o._cachedWrapU=t.wrapU,this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),o)),o&&o._cachedWrapV!==t.wrapV&&(o._cachedWrapV=t.wrapV,this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),o)),this._setAnisotropicLevel(this._gl.TEXTURE_2D,t);return!0},i.prototype.setTextureArray=function(e,t,i){if(!(e<0)&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(var r=0;r=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||(this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1)},i.prototype.releaseEffects=function(){for(var e in this._compiledEffects)this._deleteProgram(this._compiledEffects[e]._program);this._compiledEffects={}},i.prototype.dispose=function(){for(this.hideLoadingUI(),this.stopRenderLoop();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();i.audioEngine&&i.audioEngine.dispose(),this.releaseEffects(),this.unbindAllAttributes(),this._boundUniforms=[],this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.disableVR(),e.Tools.IsWindowObjectExist()&&(window.removeEventListener("blur",this._onBlur),window.removeEventListener("focus",this._onFocus),window.removeEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted),window.removeEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange),this._onVrDisplayConnect&&(window.removeEventListener("vrdisplayconnect",this._onVrDisplayConnect),this._onVrDisplayDisconnect&&window.removeEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),this._onVrDisplayPresentChange&&window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),this._onVrDisplayConnect=null,this._onVrDisplayDisconnect=null));var t=i.Instances.indexOf(this);t>=0&&i.Instances.splice(t,1),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers=[],this._renderingCanvas=null,this._currentProgram=null,this._bindedRenderFunction=null,this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear(),e.Effect.ResetCache();for(var r=0,n=this._activeRequests;r-1?o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_CUBE_MAP_POSITIVE_X+r,e._webGLTexture,n):o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,e._webGLTexture,n);var a,l=void 0!==e.type?this._getWebGLTextureType(e.type):o.UNSIGNED_BYTE;switch(l){case o.UNSIGNED_BYTE:a=new Uint8Array(4*t*i),l=o.UNSIGNED_BYTE;break;default:a=new Float32Array(4*t*i),l=o.FLOAT}return o.readPixels(0,0,t,i,o.RGBA,l,a),o.bindFramebuffer(o.FRAMEBUFFER,this._currentFramebuffer),a},i.prototype._canRenderToFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(i.TEXTURETYPE_FLOAT)},i.prototype._canRenderToHalfFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(i.TEXTURETYPE_HALF_FLOAT)},i.prototype._canRenderToFramebuffer=function(e){for(var t=this._gl;t.getError()!==t.NO_ERROR;);var i=!0,r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);var n=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&o===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);var s=t.RGBA,a=t.UNSIGNED_BYTE,l=new Uint8Array(4);t.readPixels(0,0,1,1,s,a,l),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(n),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i},i.prototype._getWebGLTextureType=function(e){return e===i.TEXTURETYPE_FLOAT?this._gl.FLOAT:e===i.TEXTURETYPE_HALF_FLOAT?this._gl.HALF_FLOAT_OES:this._gl.UNSIGNED_BYTE},i.prototype._getInternalFormat=function(e){var t=this._gl.RGBA;switch(e){case i.TEXTUREFORMAT_ALPHA:t=this._gl.ALPHA;break;case i.TEXTUREFORMAT_LUMINANCE:t=this._gl.LUMINANCE;break;case i.TEXTUREFORMAT_LUMINANCE_ALPHA:t=this._gl.LUMINANCE_ALPHA;break;case i.TEXTUREFORMAT_RGB:t=this._gl.RGB;break;case i.TEXTUREFORMAT_RGBA:t=this._gl.RGBA;break;case i.TEXTUREFORMAT_R:t=this._gl.RED;break;case i.TEXTUREFORMAT_RG:t=this._gl.RG}return t},i.prototype._getRGBABufferInternalSizedFormat=function(e,t){if(1===this._webGLVersion){if(void 0!==t)switch(t){case i.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case i.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA}return this._gl.RGBA}if(e===i.TEXTURETYPE_FLOAT){if(void 0!==t)switch(t){case i.TEXTUREFORMAT_R:return this._gl.R32F;case i.TEXTUREFORMAT_RG:return this._gl.RG32F;case i.TEXTUREFORMAT_RGB:return this._gl.RGB32F}return this._gl.RGBA32F}if(e===i.TEXTURETYPE_HALF_FLOAT){if(t)switch(t){case i.TEXTUREFORMAT_R:return this._gl.R16F;case i.TEXTUREFORMAT_RG:return this._gl.RG16F;case i.TEXTUREFORMAT_RGB:return this._gl.RGB16F}return this._gl.RGBA16F}if(void 0!==t)switch(t){case i.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case i.TEXTUREFORMAT_RGB:return this._gl.RGB;case i.TEXTUREFORMAT_R:return this._gl.R8;case i.TEXTUREFORMAT_RG:return this._gl.RG8;case i.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA}return this._gl.RGBA},i.prototype._getRGBAMultiSampleBufferFormat=function(e){return e===i.TEXTURETYPE_FLOAT?this._gl.RGBA32F:e===i.TEXTURETYPE_HALF_FLOAT?this._gl.RGBA16F:this._gl.RGBA8},i.prototype._loadFile=function(t,i,r,n,o,s){var a=this,l=e.Tools.LoadFile(t,i,r,n,o,s);return this._activeRequests.push(l),l.onCompleteObservable.add((function(e){a._activeRequests.splice(a._activeRequests.indexOf(e),1)})),l},i.prototype._loadFileAsync=function(e,t,i){var r=this;return new Promise(function(n,o){r._loadFile(e,(function(e){n(e)}),void 0,t,i,(function(e,t){o(t)}))})},i.prototype._partialLoadFile=function(e,t,i,r,n,o){void 0===o&&(o=null);var s=function(e){i[t]=e,6===++i._internalCount&&n(i)},a=function(e,t){o&&e&&o(e.status+" "+e.statusText,t)};this._loadFile(e,s,void 0,void 0,!0,a)},i.prototype._cascadeLoadFiles=function(e,t,i,r){void 0===r&&(r=null);var n=[];n._internalCount=0;for(var o=0;o<6;o++)this._partialLoadFile(i[o],o,n,e,t,r)},i.isSupported=function(){try{var e=document.createElement("canvas");return null!=(e.getContext("webgl")||e.getContext("experimental-webgl"))&&!!window.WebGLRenderingContext}catch(e){return!1}},i.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Macintosh",capture:null,captureConstraint:null,targets:["textureBindingOptimization"]},{key:"iPhone",capture:null,captureConstraint:null,targets:["textureBindingOptimization"]},{key:"iPad",capture:null,captureConstraint:null,targets:["textureBindingOptimization"]}],i.Instances=new Array,i._TextureLoaders=[],i.ALPHA_DISABLE=0,i.ALPHA_ADD=1,i.ALPHA_COMBINE=2,i.ALPHA_SUBTRACT=3,i.ALPHA_MULTIPLY=4,i.ALPHA_MAXIMIZED=5,i.ALPHA_ONEONE=6,i.ALPHA_PREMULTIPLIED=7,i.ALPHA_PREMULTIPLIED_PORTERDUFF=8,i.ALPHA_INTERPOLATE=9,i.ALPHA_SCREENMODE=10,i.DELAYLOADSTATE_NONE=0,i.DELAYLOADSTATE_LOADED=1,i.DELAYLOADSTATE_LOADING=2,i.DELAYLOADSTATE_NOTLOADED=4,i.NEVER=512,i.ALWAYS=519,i.LESS=513,i.EQUAL=514,i.LEQUAL=515,i.GREATER=516,i.GEQUAL=518,i.NOTEQUAL=517,i.KEEP=7680,i.REPLACE=7681,i.INCR=7682,i.DECR=7683,i.INVERT=5386,i.INCR_WRAP=34055,i.DECR_WRAP=34056,i.TEXTURE_CLAMP_ADDRESSMODE=0,i.TEXTURE_WRAP_ADDRESSMODE=1,i.TEXTURE_MIRROR_ADDRESSMODE=2,i.TEXTUREFORMAT_ALPHA=0,i.TEXTUREFORMAT_LUMINANCE=1,i.TEXTUREFORMAT_LUMINANCE_ALPHA=2,i.TEXTUREFORMAT_RGB=4,i.TEXTUREFORMAT_RGBA=5,i.TEXTUREFORMAT_R=6,i.TEXTUREFORMAT_RG=7,i.TEXTURETYPE_UNSIGNED_INT=0,i.TEXTURETYPE_FLOAT=1,i.TEXTURETYPE_HALF_FLOAT=2,i.TEXTURE_NEAREST_SAMPLINGMODE=1,i.TEXTURE_BILINEAR_SAMPLINGMODE=2,i.TEXTURE_TRILINEAR_SAMPLINGMODE=3,i.TEXTURE_NEAREST_NEAREST_MIPLINEAR=1,i.TEXTURE_LINEAR_LINEAR_MIPNEAREST=2,i.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,i.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,i.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,i.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,i.TEXTURE_NEAREST_LINEAR=7,i.TEXTURE_NEAREST_NEAREST=8,i.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,i.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,i.TEXTURE_LINEAR_LINEAR=11,i.TEXTURE_LINEAR_NEAREST=12,i.TEXTURE_EXPLICIT_MODE=0,i.TEXTURE_SPHERICAL_MODE=1,i.TEXTURE_PLANAR_MODE=2,i.TEXTURE_CUBIC_MODE=3,i.TEXTURE_PROJECTION_MODE=4,i.TEXTURE_SKYBOX_MODE=5,i.TEXTURE_INVCUBIC_MODE=6,i.TEXTURE_EQUIRECTANGULAR_MODE=7,i.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,i.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,i.SCALEMODE_FLOOR=1,i.SCALEMODE_NEAREST=2,i.SCALEMODE_CEILING=3,i.CollisionsEpsilon=.001,i.CodeRepository="src/",i.ShadersRepository="src/Shaders/",i})();e.Engine=a})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i){void 0===i&&(i=null),this.state="",this.metadata=null,this.doNotSerialize=!1,this._isDisposed=!1,this.animations=new Array,this._ranges={},this._isEnabled=!0,this._isReady=!0,this._currentRenderId=-1,this._parentRenderId=-1,this._childRenderId=-1,this._animationPropertiesOverride=null,this.onDisposeObservable=new e.Observable,this._behaviors=new Array,this.name=t,this.id=t,this._scene=i||e.Engine.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}return t.AddNodeConstructor=function(e,t){this._NodeConstructors[e]=t},t.Construct=function(e,t,i,r){var n=this._NodeConstructors[e];return n?n(t,i,r):null},t.prototype.isDisposed=function(){return this._isDisposed},Object.defineProperty(t.prototype,"parent",{get:function(){return this._parentNode},set:function(e){if(this._parentNode!==e){if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){var t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1)}this._parentNode=e,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this))}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"Node"},Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEngine=function(){return this._scene.getEngine()},t.prototype.addBehavior=function(e){var t=this;return-1!==this._behaviors.indexOf(e)?this:(e.init(),this._scene.isLoading?this._scene.onDataLoadedObservable.addOnce((function(){e.attach(t)})):e.attach(this),this._behaviors.push(e),this)},t.prototype.removeBehavior=function(e){var t=this._behaviors.indexOf(e);return-1===t?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)},Object.defineProperty(t.prototype,"behaviors",{get:function(){return this._behaviors},enumerable:!0,configurable:!0}),t.prototype.getBehaviorByName=function(e){for(var t=0,i=this._behaviors;tthis.maximumWorld.x&&(this.maximumWorld.x=r.x),r.y>this.maximumWorld.y&&(this.maximumWorld.y=r.y),r.z>this.maximumWorld.z&&(this.maximumWorld.z=r.z)}this.maximumWorld.subtractToRef(this.minimumWorld,this.extendSizeWorld),this.extendSizeWorld.scaleInPlace(.5),this.maximumWorld.addToRef(this.minimumWorld,this.centerWorld),this.centerWorld.scaleInPlace(.5),e.Vector3.FromFloatArrayToRef(t.m,0,this.directions[0]),e.Vector3.FromFloatArrayToRef(t.m,4,this.directions[1]),e.Vector3.FromFloatArrayToRef(t.m,8,this.directions[2]),this._worldMatrix=t},t.prototype.isInFrustum=function(e){return t.IsInFrustum(this.vectorsWorld,e)},t.prototype.isCompletelyInFrustum=function(e){return t.IsCompletelyInFrustum(this.vectorsWorld,e)},t.prototype.intersectsPoint=function(t){var i=-e.Epsilon;return!(this.maximumWorld.x-t.xt.x-this.minimumWorld.x)&&(!(this.maximumWorld.y-t.yt.y-this.minimumWorld.y)&&!(this.maximumWorld.z-t.zt.z-this.minimumWorld.z))},t.prototype.intersectsSphere=function(e){return t.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}, -t.prototype.intersectsMinMax=function(e,t){return!(this.maximumWorld.xt.x)&&(!(this.maximumWorld.yt.y)&&!(this.maximumWorld.zt.z))},t.Intersects=function(e,t){return!(e.maximumWorld.xt.maximumWorld.x)&&(!(e.maximumWorld.yt.maximumWorld.y)&&!(e.maximumWorld.zt.maximumWorld.z))},t.IntersectsSphere=function(t,i,r,n){var o=e.Vector3.Clamp(r,t,i);return e.Vector3.DistanceSquared(r,o)<=n*n},t.IsCompletelyInFrustum=function(e,t){for(var i=0;i<6;i++)for(var r=0;r<8;r++)if(t[i].dotCoordinate(e[r])<0)return!1;return!0},t.IsInFrustum=function(e,t){for(var i=0;i<6;i++){for(var r=8,n=0;n<8&&t[i].dotCoordinate(e[n])<0;n++)--r;if(0===r)return!1}return!0},t})();e.BoundingBox=t})(r||(r={}));var r;!(function(e){var t=function(t,i){var r=e.Vector3.Dot(i.centerWorld,t),n=Math.abs(e.Vector3.Dot(i.directions[0],t))*i.extendSize.x,o=Math.abs(e.Vector3.Dot(i.directions[1],t))*i.extendSize.y,s=Math.abs(e.Vector3.Dot(i.directions[2],t))*i.extendSize.z,a=n+o+s;return{min:r-a,max:r+a}},i=function(e,t,i,r){return!(e>r||i>t)},r=function(e,r,n){var o=t(e,r),s=t(e,n);return i(o.min,o.max,s.min,s.max)},n=(function(){function t(t,i){this.minimum=t,this.maximum=i,this._isLocked=!1,this.boundingBox=new e.BoundingBox(t,i),this.boundingSphere=new e.BoundingSphere(t,i)}return Object.defineProperty(t.prototype,"isLocked",{get:function(){return this._isLocked},set:function(e){this._isLocked=e},enumerable:!0,configurable:!0}),t.prototype.update=function(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))},t.prototype.centerOn=function(t,i){return this.minimum=t.subtract(i),this.maximum=t.add(i),this.boundingBox=new e.BoundingBox(this.minimum,this.maximum),this.boundingSphere=new e.BoundingSphere(this.minimum,this.maximum),this},t.prototype.scale=function(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this},t.prototype.isInFrustum=function(e){return!!this.boundingSphere.isInFrustum(e)&&this.boundingBox.isInFrustum(e)},Object.defineProperty(t.prototype,"diagonalLength",{get:function(){var e=this.boundingBox;return e.maximumWorld.subtract(e.minimumWorld).length()},enumerable:!0,configurable:!0}),t.prototype.isCompletelyInFrustum=function(e){return this.boundingBox.isCompletelyInFrustum(e)},t.prototype._checkCollision=function(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)},t.prototype.intersectsPoint=function(e){return!!this.boundingSphere.centerWorld&&(!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e))},t.prototype.intersects=function(t,i){if(!this.boundingSphere.centerWorld||!t.boundingSphere.centerWorld)return!1;if(!e.BoundingSphere.Intersects(this.boundingSphere,t.boundingSphere))return!1;if(!e.BoundingBox.Intersects(this.boundingBox,t.boundingBox))return!1;if(!i)return!0;var n=this.boundingBox,o=t.boundingBox;return!!r(n.directions[0],n,o)&&(!!r(n.directions[1],n,o)&&(!!r(n.directions[2],n,o)&&(!!r(o.directions[0],n,o)&&(!!r(o.directions[1],n,o)&&(!!r(o.directions[2],n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[1]),n,o)&&!!r(e.Vector3.Cross(n.directions[2],o.directions[2]),n,o))))))))))))))},t})();e.BoundingInfo=n})(r||(r={}));var r;!(function(e){var t=(function(t){function i(r,n,o){void 0===n&&(n=null),void 0===o&&(o=!0);var s=t.call(this,r,n)||this;return s._forward=new e.Vector3(0,0,1),s._forwardInverted=new e.Vector3(0,0,-1),s._up=new e.Vector3(0,1,0),s._right=new e.Vector3(1,0,0),s._rightInverted=new e.Vector3(-1,0,0),s._rotation=e.Vector3.Zero(),s._scaling=e.Vector3.One(),s._isDirty=!1,s.billboardMode=i.BILLBOARDMODE_NONE,s.scalingDeterminant=1,s.infiniteDistance=!1,s.ignoreNonUniformScaling=!1,s.position=e.Vector3.Zero(),s._localWorld=e.Matrix.Zero(),s._worldMatrix=e.Matrix.Zero(),s._worldMatrixDeterminant=0,s._absolutePosition=e.Vector3.Zero(),s._pivotMatrix=e.Matrix.Identity(),s._postMultiplyPivotMatrix=!1,s._isWorldMatrixFrozen=!1,s.onAfterWorldMatrixUpdateObservable=new e.Observable,s._nonUniformScaling=!1,o&&s.getScene().addTransformNode(s),s}return o(i,t),i.prototype.getClassName=function(){return"TransformNode"},Object.defineProperty(i.prototype,"rotation",{get:function(){return this._rotation},set:function(e){this._rotation=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"scaling",{get:function(){return this._scaling},set:function(e){this._scaling=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"rotationQuaternion",{get:function(){return this._rotationQuaternion},set:function(e){this._rotationQuaternion=e,e&&this.rotation.length()&&this.rotation.copyFromFloats(0,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"forward",{get:function(){return e.Vector3.Normalize(e.Vector3.TransformNormal(this.getScene().useRightHandedSystem?this._forwardInverted:this._forward,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"up",{get:function(){return e.Vector3.Normalize(e.Vector3.TransformNormal(this._up,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return e.Vector3.Normalize(e.Vector3.TransformNormal(this.getScene().useRightHandedSystem?this._rightInverted:this._right,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),i.prototype.getWorldMatrix=function(){return this._currentRenderId!==this.getScene().getRenderId()&&this.computeWorldMatrix(),this._worldMatrix},i.prototype._getWorldMatrixDeterminant=function(){return this._worldMatrixDeterminant},Object.defineProperty(i.prototype,"worldMatrixFromCache",{get:function(){return this._worldMatrix},enumerable:!0,configurable:!0}),i.prototype.updatePoseMatrix=function(e){return this._poseMatrix.copyFrom(e),this},i.prototype.getPoseMatrix=function(){return this._poseMatrix},i.prototype._isSynchronized=function(){return!this._isDirty&&(this.billboardMode===this._cache.billboardMode&&this.billboardMode===i.BILLBOARDMODE_NONE&&(!this._cache.pivotMatrixUpdated&&(!this.infiniteDistance&&(!!this._cache.position.equals(this.position)&&(!(this.rotationQuaternion&&!this._cache.rotationQuaternion.equals(this.rotationQuaternion))&&(!!this._cache.rotation.equals(this.rotation)&&!!this._cache.scaling.equals(this.scaling)))))))},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.localMatrixUpdated=!1,this._cache.position=e.Vector3.Zero(),this._cache.scaling=e.Vector3.Zero(),this._cache.rotation=e.Vector3.Zero(),this._cache.rotationQuaternion=new e.Quaternion(0,0,0,0),this._cache.billboardMode=-1},i.prototype.markAsDirty=function(e){return"rotation"===e&&(this.rotationQuaternion=null),this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this},Object.defineProperty(i.prototype,"absolutePosition",{get:function(){return this._absolutePosition},enumerable:!0,configurable:!0}),i.prototype.setPreTransformMatrix=function(e){return this.setPivotMatrix(e,!1)},i.prototype.setPivotMatrix=function(t,i){return void 0===i&&(i=!0),this._pivotMatrix=t.clone(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=i,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=e.Matrix.Invert(this._pivotMatrix)),this},i.prototype.getPivotMatrix=function(){return this._pivotMatrix},i.prototype.freezeWorldMatrix=function(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this._isWorldMatrixFrozen=!0,this},i.prototype.unfreezeWorldMatrix=function(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this},Object.defineProperty(i.prototype,"isWorldMatrixFrozen",{get:function(){return this._isWorldMatrixFrozen},enumerable:!0,configurable:!0}),i.prototype.getAbsolutePosition=function(){return this.computeWorldMatrix(),this._absolutePosition},i.prototype.setAbsolutePosition=function(t){if(!t)return this;var i,r,n;if(void 0===t.x){if(arguments.length<3)return this;i=arguments[0],r=arguments[1],n=arguments[2]}else i=t.x,r=t.y,n=t.z;if(this.parent){var o=this.parent.getWorldMatrix().clone();o.invert();var s=new e.Vector3(i,r,n);this.position=e.Vector3.TransformCoordinates(s,o)}else this.position.x=i,this.position.y=r,this.position.z=n;return this},i.prototype.setPositionWithLocalVector=function(t){return this.computeWorldMatrix(),this.position=e.Vector3.TransformNormal(t,this._localWorld),this},i.prototype.getPositionExpressedInLocalSpace=function(){this.computeWorldMatrix();var t=this._localWorld.clone();return t.invert(),e.Vector3.TransformNormal(this.position,t)},i.prototype.locallyTranslate=function(t){return this.computeWorldMatrix(!0),this.position=e.Vector3.TransformCoordinates(t,this._localWorld),this},i.prototype.lookAt=function(t,r,n,o,s){void 0===r&&(r=0),void 0===n&&(n=0),void 0===o&&(o=0),void 0===s&&(s=e.Space.LOCAL);var a=i._lookAtVectorCache,l=s===e.Space.LOCAL?this.position:this.getAbsolutePosition();t.subtractToRef(l,a);var h=-Math.atan2(a.z,a.x)-Math.PI/2,c=Math.sqrt(a.x*a.x+a.z*a.z),u=Math.atan2(a.y,c);return this.rotationQuaternion?e.Quaternion.RotationYawPitchRollToRef(h+r,u+n,o,this.rotationQuaternion):(this.rotation.x=u+n,this.rotation.y=h+r,this.rotation.z=o),this},i.prototype.getDirection=function(t){var i=e.Vector3.Zero();return this.getDirectionToRef(t,i),i},i.prototype.getDirectionToRef=function(t,i){return e.Vector3.TransformNormalToRef(t,this.getWorldMatrix(),i),this},i.prototype.setPivotPoint=function(t,i){void 0===i&&(i=e.Space.LOCAL),0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);var r=this.getWorldMatrix();if(i==e.Space.WORLD){var n=e.Tmp.Matrix[0];r.invertToRef(n),t=e.Vector3.TransformCoordinates(t,n)}return this.setPivotMatrix(e.Matrix.Translation(-t.x,-t.y,-t.z),!0)},i.prototype.getPivotPoint=function(){var t=e.Vector3.Zero();return this.getPivotPointToRef(t),t},i.prototype.getPivotPointToRef=function(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this},i.prototype.getAbsolutePivotPoint=function(){var t=e.Vector3.Zero();return this.getAbsolutePivotPointToRef(t),t},i.prototype.getAbsolutePivotPointToRef=function(t){return t.x=this._pivotMatrix.m[12],t.y=this._pivotMatrix.m[13],t.z=this._pivotMatrix.m[14],this.getPivotPointToRef(t),e.Vector3.TransformCoordinatesToRef(t,this.getWorldMatrix(),t),this},i.prototype.setParent=function(t){if(!t&&!this.parent)return this;if(t){var i=e.Tmp.Quaternion[0],r=e.Tmp.Vector3[0],n=e.Tmp.Vector3[1],o=e.Tmp.Matrix[0],s=e.Tmp.Matrix[1];this.computeWorldMatrix(!0),t.computeWorldMatrix(!0),t.getWorldMatrix().invertToRef(s),this.getWorldMatrix().multiplyToRef(s,o),o.decompose(n,i,r),this.rotationQuaternion?this.rotationQuaternion.copyFrom(i):i.toEulerAnglesToRef(this.rotation),this.position.x=r.x,this.position.y=r.y,this.position.z=r.z,this.scaling.x=n.x,this.scaling.y=n.y,this.scaling.z=n.z}else{var i=e.Tmp.Quaternion[0],r=e.Tmp.Vector3[0],n=e.Tmp.Vector3[1];this.parent&&this.parent.computeWorldMatrix&&this.parent.computeWorldMatrix(!0),this.computeWorldMatrix(!0),this.getWorldMatrix().decompose(n,i,r),this.rotationQuaternion?this.rotationQuaternion.copyFrom(i):i.toEulerAnglesToRef(this.rotation),this.scaling.x=n.x,this.scaling.y=n.y,this.scaling.z=n.z,this.position.x=r.x,this.position.y=r.y,this.position.z=r.z}return this.parent=t,this},Object.defineProperty(i.prototype,"nonUniformScaling",{get:function(){return this._nonUniformScaling},enumerable:!0,configurable:!0}),i.prototype._updateNonUniformScalingState=function(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)},i.prototype.attachToBone=function(e,t){return this._transformToBoneReferal=t,this.parent=e,e.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this},i.prototype.detachFromBone=function(){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=null,this):this},i.prototype.rotate=function(t,r,n){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation=e.Vector3.Zero());var o;if(n&&n!==e.Space.LOCAL){if(this.parent){var s=this.parent.getWorldMatrix().clone();s.invert(),t=e.Vector3.TransformNormal(t,s)}o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),this.rotationQuaternion.multiplyToRef(o,this.rotationQuaternion);return this},i.prototype.rotateAround=function(t,i,r){return i.normalize(),this.rotationQuaternion||(this.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.copyFromFloats(0,0,0)),t.subtractToRef(this.position,e.Tmp.Vector3[0]),e.Matrix.TranslationToRef(e.Tmp.Vector3[0].x,e.Tmp.Vector3[0].y,e.Tmp.Vector3[0].z,e.Tmp.Matrix[0]),e.Tmp.Matrix[0].invertToRef(e.Tmp.Matrix[2]),e.Matrix.RotationAxisToRef(i,r,e.Tmp.Matrix[1]),e.Tmp.Matrix[2].multiplyToRef(e.Tmp.Matrix[1],e.Tmp.Matrix[2]),e.Tmp.Matrix[2].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[2]),e.Tmp.Matrix[2].decompose(e.Tmp.Vector3[0],e.Tmp.Quaternion[0],e.Tmp.Vector3[1]),this.position.addInPlace(e.Tmp.Vector3[1]),e.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this},i.prototype.translate=function(t,i,r){var n=t.scale(i);if(r&&r!==e.Space.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(n));else{var o=this.getPositionExpressedInLocalSpace().add(n);this.setPositionWithLocalVector(o)}return this},i.prototype.addRotation=function(t,i,r){var n;this.rotationQuaternion?n=this.rotationQuaternion:(n=e.Tmp.Quaternion[1],e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,n));var o=e.Tmp.Quaternion[0];return e.Quaternion.RotationYawPitchRollToRef(i,t,r,o),n.multiplyInPlace(o),this.rotationQuaternion||n.toEulerAnglesToRef(this.rotation),this},i.prototype.computeWorldMatrix=function(t){if(this._isWorldMatrixFrozen)return this._worldMatrix;if(!t&&this.isSynchronized(!0))return this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix;if(this._cache.position.copyFrom(this.position),this._cache.scaling.copyFrom(this.scaling),this._cache.pivotMatrixUpdated=!1,this._cache.billboardMode=this.billboardMode,this._currentRenderId=this.getScene().getRenderId(),this._childRenderId=this.getScene().getRenderId(),this._isDirty=!1,e.Matrix.ScalingToRef(this.scaling.x*this.scalingDeterminant,this.scaling.y*this.scalingDeterminant,this.scaling.z*this.scalingDeterminant,e.Tmp.Matrix[1]),this.rotationQuaternion){this.rotation.length()&&(this.rotationQuaternion.multiplyInPlace(e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)),this.rotation.copyFromFloats(0,0,0))}this.rotationQuaternion?(this.rotationQuaternion.toRotationMatrix(e.Tmp.Matrix[0]),this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,e.Tmp.Matrix[0]),this._cache.rotation.copyFrom(this.rotation));var r=this.getScene().activeCamera;if(this.infiniteDistance&&!this.parent&&r){var n=r.getWorldMatrix(),o=new e.Vector3(n.m[12],n.m[13],n.m[14]);e.Matrix.TranslationToRef(this.position.x+o.x,this.position.y+o.y,this.position.z+o.z,e.Tmp.Matrix[2])}else e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,e.Tmp.Matrix[2]);if(this._pivotMatrix.multiplyToRef(e.Tmp.Matrix[1],e.Tmp.Matrix[4]),e.Tmp.Matrix[4].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[5]),this.billboardMode!==i.BILLBOARDMODE_NONE&&r){if((this.billboardMode&i.BILLBOARDMODE_ALL)!==i.BILLBOARDMODE_ALL){var s=e.Tmp.Vector3[3];this.parent&&this.parent.getWorldMatrix?this._transformToBoneReferal?(this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),e.Tmp.Matrix[6]),e.Vector3.TransformCoordinatesToRef(this.position,e.Tmp.Matrix[6],s)):e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),s):s.copyFrom(this.position),s.subtractInPlace(r.globalPosition);var a=e.Tmp.Vector3[4].copyFromFloats(0,0,0);(this.billboardMode&i.BILLBOARDMODE_X)===i.BILLBOARDMODE_X&&(a.x=Math.atan2(-s.y,s.z)),(this.billboardMode&i.BILLBOARDMODE_Y)===i.BILLBOARDMODE_Y&&(a.y=Math.atan2(s.x,s.z)),(this.billboardMode&i.BILLBOARDMODE_Z)===i.BILLBOARDMODE_Z&&(a.z=Math.atan2(s.y,s.x)),e.Matrix.RotationYawPitchRollToRef(a.y,a.x,a.z,e.Tmp.Matrix[0])}else e.Tmp.Matrix[1].copyFrom(r.getViewMatrix()),e.Tmp.Matrix[1].setTranslationFromFloats(0,0,0),e.Tmp.Matrix[1].invertToRef(e.Tmp.Matrix[0]);e.Tmp.Matrix[1].copyFrom(e.Tmp.Matrix[5]),e.Tmp.Matrix[1].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[5])}return this._postMultiplyPivotMatrix&&e.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse,e.Tmp.Matrix[5]),e.Tmp.Matrix[5].multiplyToRef(e.Tmp.Matrix[2],this._localWorld),this.parent&&this.parent.getWorldMatrix?(this.billboardMode!==i.BILLBOARDMODE_NONE?(this._transformToBoneReferal?(this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),e.Tmp.Matrix[6]),e.Tmp.Matrix[5].copyFrom(e.Tmp.Matrix[6])):e.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix()),this._localWorld.getTranslationToRef(e.Tmp.Vector3[5]),e.Vector3.TransformCoordinatesToRef(e.Tmp.Vector3[5],e.Tmp.Matrix[5],e.Tmp.Vector3[5]),this._worldMatrix.copyFrom(this._localWorld),this._worldMatrix.setTranslation(e.Tmp.Vector3[5])):this._transformToBoneReferal?(this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),e.Tmp.Matrix[6]),e.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()):this._worldMatrix.copyFrom(this._localWorld),this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this.scaling.isNonUniform?this._updateNonUniformScalingState(!0):this.parent&&this.parent._nonUniformScaling?this._updateNonUniformScalingState(this.parent._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=e.Matrix.Invert(this._worldMatrix)),this._worldMatrixDeterminant=this._worldMatrix.determinant(),this._worldMatrix},i.prototype._afterComputeWorldMatrix=function(){},i.prototype.registerAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this},i.prototype.unregisterAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this},i.prototype.clone=function(t,r,n){var o=this,s=e.SerializationHelper.Clone((function(){return new i(t,o.getScene())}),this);if(s.name=t,s.id=t,r&&(s.parent=r),!n)for(var a=this.getDescendants(!0),l=0;le.Engine.CollisionsEpsilon&&o.position.addInPlace(o._diffPositionForCollisions),r&&o.onCollideObservable.notifyObservers(r),o.onCollisionPositionChangeObservable.notifyObservers(o.position)},o.getScene().addMesh(o),o._resyncLightSources(),o}return o(i,t),Object.defineProperty(i,"BILLBOARDMODE_NONE",{get:function(){return e.TransformNode.BILLBOARDMODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_X",{get:function(){return e.TransformNode.BILLBOARDMODE_X},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Y",{get:function(){return e.TransformNode.BILLBOARDMODE_Y},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Z",{get:function(){return e.TransformNode.BILLBOARDMODE_Z},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_ALL",{get:function(){return e.TransformNode.BILLBOARDMODE_ALL},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"facetNb",{get:function(){return this._facetNb},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"partitioningSubdivisions",{get:function(){return this._partitioningSubdivisions},set:function(e){this._partitioningSubdivisions=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"partitioningBBoxRatio",{get:function(){return this._partitioningBBoxRatio},set:function(e){this._partitioningBBoxRatio=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"mustDepthSortFacets",{get:function(){return this._facetDepthSort},set:function(e){this._facetDepthSort=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"facetDepthSortFrom",{get:function(){return this._facetDepthSortFrom},set:function(e){this._facetDepthSortFrom=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"isFacetDataEnabled",{get:function(){return this._facetDataEnabled},enumerable:!0,configurable:!0}),i.prototype._updateNonUniformScalingState=function(e){return!!t.prototype._updateNonUniformScalingState.call(this,e)&&(this._markSubMeshesAsMiscDirty(),!0)},Object.defineProperty(i.prototype,"onCollide",{set:function(e){this._onCollideObserver&&this.onCollideObservable.remove(this._onCollideObserver),this._onCollideObserver=this.onCollideObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onCollisionPositionChange",{set:function(e){this._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver),this._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"isOccluded",{get:function(){return this._isOccluded},set:function(e){this._isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"isOcclusionQueryInProgress",{get:function(){return this._isOcclusionQueryInProgress},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"visibility",{get:function(){return this._visibility},set:function(e){this._visibility!==e&&(this._visibility=e,this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"material",{get:function(){return this._material},set:function(e){this._material!==e&&(this._material=e,this.onMaterialChangedObservable.hasObservers&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&this._unBindEffect())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"receiveShadows",{get:function(){return this._receiveShadows},set:function(e){this._receiveShadows!==e&&(this._receiveShadows=e,this._markSubMeshesAsLightDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"hasVertexAlpha",{get:function(){return this._hasVertexAlpha},set:function(e){this._hasVertexAlpha!==e&&(this._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useVertexColors",{get:function(){return this._useVertexColors},set:function(e){this._useVertexColors!==e&&(this._useVertexColors=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"computeBonesUsingShaders",{get:function(){return this._computeBonesUsingShaders},set:function(e){this._computeBonesUsingShaders!==e&&(this._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"numBoneInfluencers",{get:function(){return this._numBoneInfluencers},set:function(e){this._numBoneInfluencers!==e&&(this._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"applyFog",{get:function(){return this._applyFog},set:function(e){this._applyFog!==e&&(this._applyFog=e,this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"layerMask",{get:function(){return this._layerMask},set:function(e){e!==this._layerMask&&(this._layerMask=e,this._resyncLightSources())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"collisionGroup",{get:function(){return this._collisionGroup},set:function(e){this._collisionGroup=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"_positions",{get:function(){return null},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"skeleton",{get:function(){return this._skeleton},set:function(e){this._skeleton&&this._skeleton.needInitialSkinMatrix&&this._skeleton._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._skeleton=e,this._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"AbstractMesh"},i.prototype.toString=function(t){var i="Name: "+this.name+", isInstance: "+(this instanceof e.InstancedMesh?"YES":"NO");return i+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0),this._skeleton&&(i+=", skeleton: "+this._skeleton.name),t&&(i+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],i+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingFreezeWorldMatrix?"YES":"NO")),i},i.prototype._rebuild=function(){if(this._occlusionQuery&&(this._occlusionQuery=null),this._edgesRenderer&&this._edgesRenderer._rebuild(),this.subMeshes)for(var e=0,t=this.subMeshes;e1&&!a._checkCollision(e)||this._collideForSubMesh(a,t,e)}return this},i.prototype._checkCollision=function(t){return this._boundingInfo&&this._boundingInfo._checkCollision(t)?(e.Matrix.ScalingToRef(1/t._radius.x,1/t._radius.y,1/t._radius.z,this._collisionsScalingMatrix),this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix,this._collisionsTransformMatrix),this._processCollisionsForSubMeshes(t,this._collisionsTransformMatrix),this):this},i.prototype._generatePointsArray=function(){return!1},i.prototype.intersects=function(t,i){var r=new e.PickingInfo;if(!(this.subMeshes&&this._boundingInfo&&t.intersectsSphere(this._boundingInfo.boundingSphere)&&t.intersectsBox(this._boundingInfo.boundingBox)))return r;if(!this._generatePointsArray())return r;var n,o,s=null;if(this._submeshesOctree&&this.useOctreeForPicking){var a=e.Ray.Transform(t,this.getWorldMatrix()),l=this._submeshesOctree.intersectsRay(a);o=l.length,n=l.data}else n=this.subMeshes,o=n.length;for(var h=0;h1)||c.canIntersects(t)){var u=c.intersects(t,this._positions,this.getIndices(),i);if(u&&(i||!s||u.distance65535){o=!0;break}this._depthSortedIndices=o?new Uint32Array(i):new Uint16Array(i)}if(this._facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!this._facetDepthSortFrom){var a=this.getScene().activeCamera;this._facetDepthSortFrom=a?a.position:e.Vector3.Zero()}this._depthSortedFacets=[];for(var l=0;le.Epsilon?n.maximum.x-n.minimum.x:e.Epsilon,this._bbSize.y=n.maximum.y-n.minimum.y>e.Epsilon?n.maximum.y-n.minimum.y:e.Epsilon,this._bbSize.z=n.maximum.z-n.minimum.z>e.Epsilon?n.maximum.z-n.minimum.z:e.Epsilon;var c=this._bbSize.x>this._bbSize.y?this._bbSize.x:this._bbSize.y;if(c=c>this._bbSize.z?c:this._bbSize.z,this._subDiv.max=this._partitioningSubdivisions,this._subDiv.X=Math.floor(this._subDiv.max*this._bbSize.x/c),this._subDiv.Y=Math.floor(this._subDiv.max*this._bbSize.y/c),this._subDiv.Z=Math.floor(this._subDiv.max*this._bbSize.z/c),this._subDiv.X=this._subDiv.X<1?1:this._subDiv.X,this._subDiv.Y=this._subDiv.Y<1?1:this._subDiv.Y,this._subDiv.Z=this._subDiv.Z<1?1:this._subDiv.Z,this._facetParameters.facetNormals=this.getFacetLocalNormals(),this._facetParameters.facetPositions=this.getFacetLocalPositions(),this._facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),this._facetParameters.bInfo=n,this._facetParameters.bbSize=this._bbSize,this._facetParameters.subDiv=this._subDiv,this._facetParameters.ratio=this.partitioningBBoxRatio,this._facetParameters.depthSort=this._facetDepthSort,this._facetDepthSort&&this._facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(this._invertedMatrix),e.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom,this._invertedMatrix,this._facetDepthSortOrigin),this._facetParameters.distanceTo=this._facetDepthSortOrigin),this._facetParameters.depthSortedFacets=this._depthSortedFacets,e.VertexData.ComputeNormals(t,i,r,this._facetParameters),this._facetDepthSort&&this._facetDepthSortEnabled){this._depthSortedFacets.sort(this._facetDepthSortFunction);for(var u=this._depthSortedIndices.length/3|0,l=0;lthis._subDiv.max||o<0||o>this._subDiv.max||s<0||s>this._subDiv.max?null:this._facetPartitioning[n+this._subDiv.max*o+this._subDiv.max*this._subDiv.max*s]},i.prototype.getClosestFacetAtCoordinates=function(t,i,r,n,o,s){void 0===o&&(o=!1),void 0===s&&(s=!0);var a=this.getWorldMatrix(),l=e.Tmp.Matrix[5];a.invertToRef(l);var h=e.Tmp.Vector3[8];e.Vector3.TransformCoordinatesFromFloatsToRef(t,i,r,l,h);var c=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,n,o,s);return n&&e.Vector3.TransformCoordinatesFromFloatsToRef(n.x,n.y,n.z,a,n),c},i.prototype.getClosestFacetAtLocalCoordinates=function(e,t,i,r,n,o){void 0===n&&(n=!1),void 0===o&&(o=!0);var s=null,a=0,l=0,h=0,c=0,u=0,f=0,d=0,p=0,m=this.getFacetLocalPositions(),_=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;for(var v,y,b,x=Number.MAX_VALUE,T=x,E=0;E=0||n&&!o&&c<=0)&&(c=y.x*b.x+y.y*b.y+y.z*b.z,u=-(y.x*e+y.y*t+y.z*i-c)/(y.x*y.x+y.y*y.y+y.z*y.z),f=e+y.x*u,d=t+y.y*u,p=i+y.z*u,a=f-e,l=d-t,h=p-i,(T=a*a+l*l+h*h)0&&-1===this.includedOnlyMeshes.indexOf(e))&&(!(this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e))&&((0===this.includeOnlyWithLayerMask||0!=(this.includeOnlyWithLayerMask&e.layerMask))&&!(0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask)))},i.prototype.getWorldMatrix=function(){this._currentRenderId=this.getScene().getRenderId(),this._childRenderId=this._currentRenderId;var t=this._getWorldMatrix();return this.parent&&this.parent.getWorldMatrix?(this._parentedWorldMatrix||(this._parentedWorldMatrix=e.Matrix.Identity()),t.multiplyToRef(this.parent.getWorldMatrix(),this._parentedWorldMatrix),this._markSyncedWithParent(),this._parentedWorldMatrix):t},i.CompareLightsPriority=function(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority},i.prototype.dispose=function(e,i){void 0===i&&(i=!1),this._shadowGenerator&&(this._shadowGenerator.dispose(),this._shadowGenerator=null),this.getScene().stopAnimation(this);for(var r=0,n=this.getScene().meshes;r0&&(t.excludedMeshesIds=[],this.excludedMeshes.forEach((function(e){t.excludedMeshesIds.push(e.id)}))),this.includedOnlyMeshes.length>0&&(t.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((function(e){t.includedOnlyMeshesIds.push(e.id)}))),e.Animation.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t},i.GetConstructorFromName=function(t,i,r){var n=e.Node.Construct("Light_Type_"+t,i,r);return n||null},i.Parse=function(t,r){var n=i.GetConstructorFromName(t.type,t.name,r);if(!n)return null;var o=e.SerializationHelper.Parse(n,t,r);if(t.excludedMeshesIds&&(o._excludedMeshesIds=t.excludedMeshesIds),t.includedOnlyMeshesIds&&(o._includedOnlyMeshesIds=t.includedOnlyMeshesIds),t.parentId&&(o._waitingParentId=t.parentId),t.animations){for(var s=0;s-1?(e.Tools.Error("You're trying to reuse a post process not defined as reusable."),0):(null==i||i<0?this._postProcesses.push(t):null===this._postProcesses[i]?this._postProcesses[i]=t:this._postProcesses.splice(i,0,t),this._cascadePostProcessesToRigCams(),this._postProcesses.indexOf(t))},i.prototype.detachPostProcess=function(e){var t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._cascadePostProcessesToRigCams()},i.prototype.getWorldMatrix=function(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)},i.prototype._getViewMatrix=function(){return e.Matrix.Identity()},i.prototype.getViewMatrix=function(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childRenderId=this._currentRenderId,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._computedViewMatrix)},i.prototype.freezeProjectionMatrix=function(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)},i.prototype.unfreezeProjectionMatrix=function(){this._doNotComputeProjectionMatrix=!1},i.prototype.getProjectionMatrix=function(t){if(this._doNotComputeProjectionMatrix||!t&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;var r=this.getEngine(),n=this.getScene();if(this.mode===i.PERSPECTIVE_CAMERA)this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=r.getAspectRatio(this),this.minZ<=0&&(this.minZ=.1),n.useRightHandedSystem?e.Matrix.PerspectiveFovRHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED):e.Matrix.PerspectiveFovLHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED);else{var o=r.getRenderWidth()/2,s=r.getRenderHeight()/2;n.useRightHandedSystem?e.Matrix.OrthoOffCenterRHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix):e.Matrix.OrthoOffCenterLHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=r.getRenderWidth(),this._cache.renderHeight=r.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix},i.prototype.getTransformationMatrix=function(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix},i.prototype.updateFrustumPlanes=function(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?e.Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=e.Frustum.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)},i.prototype.isInFrustum=function(e){return this.updateFrustumPlanes(),e.isInFrustum(this._frustumPlanes)},i.prototype.isCompletelyInFrustum=function(e){return this.updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)},i.prototype.getForwardRay=function(t,i,r){void 0===t&&(t=100),i||(i=this.getWorldMatrix()),r||(r=this.position);var n=new e.Vector3(0,0,1),o=e.Vector3.TransformNormal(n,i),s=e.Vector3.Normalize(o);return new e.Ray(r,s,t)},i.prototype.dispose=function(e,r){for(void 0===r&&(r=!1),this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){var n=this._rigCameras.pop();n&&n.dispose()}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses=[];else if(this.cameraRigMode!==i.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses=[];else for(var o=this._postProcesses.length;--o>=0;){var s=this._postProcesses[o];s&&s.dispose(this)}for(var o=this.customRenderTargets.length;--o>=0;)this.customRenderTargets[o].dispose();this.customRenderTargets=[],this._activeMeshes.dispose(),t.prototype.dispose.call(this,e,r)},Object.defineProperty(i.prototype,"leftCamera",{get:function(){return this._rigCameras.length<1?null:this._rigCameras[0]},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"rightCamera",{get:function(){return this._rigCameras.length<2?null:this._rigCameras[1]},enumerable:!0,configurable:!0}),i.prototype.getLeftTarget=function(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()},i.prototype.getRightTarget=function(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()},i.prototype.setCameraRigMode=function(t,r){if(this.cameraRigMode!==t){for(;this._rigCameras.length>0;){var n=this._rigCameras.pop();n&&n.dispose()}if(this.cameraRigMode=t,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=r.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==i.RIG_MODE_NONE){var o=this.createRigCamera(this.name+"_L",0),s=this.createRigCamera(this.name+"_R",1);o&&s&&(this._rigCameras.push(o),this._rigCameras.push(s))}switch(this.cameraRigMode){case i.RIG_MODE_STEREOSCOPIC_ANAGLYPH:this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.AnaglyphPostProcess(this.name+"_anaglyph",1,this._rigCameras);break;case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case i.RIG_MODE_STEREOSCOPIC_OVERUNDER:var a=this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.StereoscopicInterlacePostProcess(this.name+"_stereoInterlace",this._rigCameras,a);break;case i.RIG_MODE_VR:var l=r.vrCameraMetrics||e.VRCameraMetrics.GetDefault();this._rigCameras[0]._cameraRigParams.vrMetrics=l,this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0]._cameraRigParams.vrHMatrix=l.leftHMatrix,this._rigCameras[0]._cameraRigParams.vrPreViewMatrix=l.leftPreViewMatrix,this._rigCameras[0].getProjectionMatrix=this._rigCameras[0]._getVRProjectionMatrix,this._rigCameras[1]._cameraRigParams.vrMetrics=l,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1]._cameraRigParams.vrHMatrix=l.rightHMatrix,this._rigCameras[1]._cameraRigParams.vrPreViewMatrix=l.rightPreViewMatrix,this._rigCameras[1].getProjectionMatrix=this._rigCameras[1]._getVRProjectionMatrix,l.compensateDistortion&&(this._rigCameras[0]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",this._rigCameras[0],!1,l),this._rigCameras[1]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",this._rigCameras[1],!0,l));break;case i.RIG_MODE_WEBVR:if(r.vrDisplay){var h=r.vrDisplay.getEyeParameters("left"),c=r.vrDisplay.getEyeParameters("right");this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0].setCameraRigParameter("left",!0),this._rigCameras[0].setCameraRigParameter("specs",r.specs),this._rigCameras[0].setCameraRigParameter("eyeParameters",h),this._rigCameras[0].setCameraRigParameter("frameData",r.frameData),this._rigCameras[0].setCameraRigParameter("parentCamera",r.parentCamera),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0].getProjectionMatrix=this._getWebVRProjectionMatrix,this._rigCameras[0].parent=this,this._rigCameras[0]._getViewMatrix=this._getWebVRViewMatrix,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1].setCameraRigParameter("eyeParameters",c),this._rigCameras[1].setCameraRigParameter("specs",r.specs),this._rigCameras[1].setCameraRigParameter("frameData",r.frameData),this._rigCameras[1].setCameraRigParameter("parentCamera",r.parentCamera),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1].getProjectionMatrix=this._getWebVRProjectionMatrix,this._rigCameras[1].parent=this,this._rigCameras[1]._getViewMatrix=this._getWebVRViewMatrix,i.UseAlternateWebVRRendering&&(this._rigCameras[1]._skipRendering=!0,this._rigCameras[0]._alternateCamera=this._rigCameras[1])}}this._cascadePostProcessesToRigCams(),this.update()}},i.prototype._getVRProjectionMatrix=function(){return e.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix},i.prototype._updateCameraRotationMatrix=function(){},i.prototype._updateWebVRCameraRotationMatrix=function(){},i.prototype._getWebVRProjectionMatrix=function(){return e.Matrix.Identity()},i.prototype._getWebVRViewMatrix=function(){return e.Matrix.Identity()},i.prototype.setCameraRigParameter=function(t,i){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[t]=i,"interaxialDistance"===t&&(this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(i/.0637))},i.prototype.createRigCamera=function(e,t){return null},i.prototype._updateRigCameras=function(){for(var e=0;ei._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0},t.frontToBackSortCompare=function(e,t){return e._distanceToCamerat._distanceToCamera?1:0},t.prototype.prepare=function(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this._spriteManagers.reset(),this._edgesRenderers.reset()},t.prototype.dispose=function(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()},t.prototype.dispatch=function(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!==i&&void 0!==i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),null!==t._edgesRenderer&&void 0!==t._edgesRenderer&&t._edgesRenderer.isEnabled&&this._edgesRenderers.push(t._edgesRenderer))},t.prototype.dispatchSprites=function(e){this._spriteManagers.push(e)},t.prototype.dispatchParticles=function(e){this._particleSystems.push(e)},t.prototype._renderParticles=function(e){if(0!==this._particleSystems.length){var t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(var i=0;i0){for(var e=0,t=this._transientComponents;er.LongPressDelay&&Math.abs(n._startingPointerPosition.x-n._pointerX)r.DoubleClickDelay&&!s._doubleClickOccured||e!==s._previousButtonPressed)&&(s._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,i(t,s._currentPickResult))},this._initClickEvent=function(i,n,o,a){var l=new t;s._currentPickResult=null;var h=null,c=i.hasSpecificMask(e.PointerEventTypes.POINTERPICK)||n.hasSpecificMask(e.PointerEventTypes.POINTERPICK)||i.hasSpecificMask(e.PointerEventTypes.POINTERTAP)||n.hasSpecificMask(e.PointerEventTypes.POINTERTAP)||i.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)||n.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP);if(!c&&e.ActionManager&&e.ActionManager.HasPickTriggers&&(h=s._initActionManager(h,l))&&(c=h.hasPickTriggers),c){var u=o.button;if(l.hasSwiped=Math.abs(s._startingPointerPosition.x-s._pointerX)>r.DragMovementThreshold||Math.abs(s._startingPointerPosition.y-s._pointerY)>r.DragMovementThreshold,!l.hasSwiped){var f=!r.ExclusiveDoubleClickMode;f||(f=!i.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)&&!n.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP))&&!e.ActionManager.HasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)&&(h=s._initActionManager(h,l))&&(f=!h.hasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)),f?(Date.now()-s._previousStartingPointerTime>r.DoubleClickDelay||u!==s._previousButtonPressed)&&(l.singleClick=!0,a(l,s._currentPickResult)):(s._previousDelayedSimpleClickTimeout=s._delayedSimpleClickTimeout,s._delayedSimpleClickTimeout=window.setTimeout(s._delayedSimpleClick.bind(s,u,l,a),r.DoubleClickDelay));var d=i.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)||n.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP);!d&&e.ActionManager.HasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)&&(h=s._initActionManager(h,l))&&(d=h.hasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)),d&&(u===s._previousButtonPressed&&Date.now()-s._previousStartingPointerTime0&&(i=s.pickSprite(s._unTranslatedPointerX,s._unTranslatedPointerY,s._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,t.button){case 0:i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnLeftPickTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t));break;case 1:i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnCenterPickTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t));break;case 2:i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnRightPickTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickDownTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t))}}},this._onPointerUp=function(t){0!==s._totalPointersPressed&&(s._totalPointersPressed--,s._pickedUpMesh=null,s._meshPickProceed=!1,s._updatePointerPosition(t),s._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,t,(function(i,n){if(s.onPrePointerObservable.hasObservers())if(i.ignore){if(s._checkPrePointerObservable(null,t,e.PointerEventTypes.POINTERUP))return}else if(!i.hasSwiped){if(i.singleClick&&s.onPrePointerObservable.hasSpecificMask(e.PointerEventTypes.POINTERTAP)&&s._checkPrePointerObservable(null,t,e.PointerEventTypes.POINTERTAP))return;if(i.doubleClick&&s.onPrePointerObservable.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)&&s._checkPrePointerObservable(null,t,e.PointerEventTypes.POINTERDOUBLETAP))return}if(s.cameraToUseForPointers||s.activeCamera){if(s._pointerCaptures[t.pointerId]=!1,s.pointerUpPredicate||(s.pointerUpPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()}),!s._meshPickProceed&&(e.ActionManager&&e.ActionManager.HasTriggers||s.onPointerObservable.hasObservers())&&s._initActionManager(null,i),n||(n=s._currentPickResult),s._processPointerUp(n,t,i),!i.ignore&&s.spriteManagers.length>0){var o=s.pickSprite(s._unTranslatedPointerX,s._unTranslatedPointerY,s._spritePredicate,!1,s.cameraToUseForPointers||void 0);o&&(o.hit&&o.pickedSprite&&o.pickedSprite.actionManager&&(o.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickUpTrigger,e.ActionEvent.CreateNewFromSprite(o.pickedSprite,s,t)),o.pickedSprite.actionManager&&Math.abs(s._startingPointerPosition.x-s._pointerX)0)return!1;var t,i=this.getEngine();for(t=0;t0,o=0,s=this._isReadyForMeshStage;o0)for(var a=0,l=this.activeCameras;a0},enumerable:!0,configurable:!0}),r.prototype.executeWhenReady=function(e){var t=this;this.onReadyObservable.add(e),-1===this._executeWhenReadyTimeoutId&&(this._executeWhenReadyTimeoutId=setTimeout((function(){t._checkIsReady()}),150))},r.prototype.whenReadyAsync=function(){var e=this;return new Promise(function(t){e.executeWhenReady((function(){t()}))})},r.prototype._checkIsReady=function(){var e=this;if(this._registerTransientComponents(),this.isReady())return this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=-1);this._executeWhenReadyTimeoutId=setTimeout((function(){e._checkIsReady()}),150)},r.prototype.beginWeightedAnimation=function(e,t,i,r,n,o,s,a,l){void 0===r&&(r=1),void 0===o&&(o=1);var h=this.beginAnimation(e,t,i,n,o,s,a,!1,l);return h.weight=r,h},r.prototype.beginAnimation=function(t,i,r,n,o,s,a,l,h){void 0===o&&(o=1),void 0===l&&(l=!0),i>r&&o>0&&(o*=-1),l&&this.stopAnimation(t,void 0,h),a||(a=new e.Animatable(this,t,i,r,n,o,s));var c=!h||h(t);if(t.animations&&c&&a.appendAnimations(t,t.animations),t.getAnimatables)for(var u=t.getAnimatables(),f=0;f0)return;this._animationTimeLast=t}var i=this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale;this._animationTime+=i,this._animationTimeLast=t;for(var r=0;r0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t},r.prototype.removeParticleSystem=function(e){var t=this.particleSystems.indexOf(e);return-1!==t&&this.particleSystems.splice(t,1),t},r.prototype.removeAnimation=function(e){var t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t},r.prototype.removeAnimationGroup=function(e){var t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t},r.prototype.removeMultiMaterial=function(e){var t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),t},r.prototype.removeMaterial=function(e){var t=this.materials.indexOf(e);return-1!==t&&this.materials.splice(t,1),t},r.prototype.removeActionManager=function(e){var t=this.actionManagers.indexOf(e);return-1!==t&&this.actionManagers.splice(t,1),t},r.prototype.removeTexture=function(e){var t=this.textures.indexOf(e);return-1!==t&&this.textures.splice(t,1),t},r.prototype.addLight=function(e){this.lights.push(e),this.sortLightsByPriority();for(var t=0,i=this.meshes;t-1&&(this.geometries.splice(t,1),this.collisionCoordinator&&this.collisionCoordinator.onGeometryDeleted(e),this.onGeometryRemovedObservable.notifyObservers(e),!0)},r.prototype.getGeometries=function(){return this.geometries},r.prototype.getMeshByID=function(e){for(var t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null},r.prototype.getLastEntryByID=function(e){var t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null},r.prototype.getNodeByID=function(e){var t=this.getMeshByID(e);if(t)return t;var i=this.getLightByID(e);if(i)return i;var r=this.getCameraByID(e);return r||this.getBoneByID(e)},r.prototype.getNodeByName=function(e){var t=this.getMeshByName(e);if(t)return t;var i=this.getLightByName(e);if(i)return i;var r=this.getCameraByName(e);return r||this.getBoneByName(e)},r.prototype.getMeshByName=function(e){for(var t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null},r.prototype.getSkeletonById=function(e){for(var t=0;t0&&(a.alwaysSelectAsActiveMesh||0!=(a.layerMask&this.activeCamera.layerMask)&&a.isInFrustum(this._frustumPlanes))&&(this._activeMeshes.push(a),this.activeCamera._activeMeshes.push(a),a._activate(this._renderId),l!==a&&l._activate(this._renderId),this._activeMesh(a,l)))));if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(var c=0;c0){var n,o;if(t.useOctreeForRenderingSelection&&void 0!==t._submeshesOctree&&null!==t._submeshesOctree){var s=t._submeshesOctree.select(this._frustumPlanes);n=s.length,o=s.data}else o=t.subMeshes,n=o.length;for(var a,l=0;l0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),i&&i.customRenderTargets&&i.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(i.customRenderTargets),this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){e.Tools.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(var s=0;s0),this._renderId++}for(var h=0,c=this._cameraDrawRenderTargetStage;h-1&&(n.trigger===e.ActionManager.OnIntersectionExitTrigger&&n._executeCurrent(e.ActionEvent.CreateNew(i,void 0,s)),i.actionManager.hasSpecificTrigger(e.ActionManager.OnIntersectionExitTrigger,(function(t){var i=t instanceof e.AbstractMesh?t:t.mesh;return s===i}))&&n.trigger!==e.ActionManager.OnIntersectionExitTrigger||i._intersectionsInProgress.splice(l,1))}}}},r.prototype.render=function(t){if(void 0===t&&(t=!0),!this.isDisposed){if(this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(e.ActionManager.OnEveryFrameTrigger),this.simplificationQueue&&!this.simplificationQueue.running&&this.simplificationQueue.executeNext(),this._engine.isDeterministicLockStep()){var i=Math.max(r.MinDeltaTime,Math.min(this._engine.getDeltaTime(),r.MaxDeltaTime))+this._timeAccumulator,n=1e3/60;this._physicsEngine&&(n=1e3*this._physicsEngine.getTimeStep());var o=0,s=this._engine.getLockstepMaxSteps(),a=Math.floor(i/60);a=Math.min(a,s);do{this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=.06*n,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this._physicsEngine&&(this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(n/1e3),this.onAfterPhysicsObservable.notifyObservers(this)),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,o++,i-=n}while(i>0&&o0)for(var c=0;c0),this._intermediateRendering=!0;for(var m=0;m0),this._intermediateRendering=!1,this._renderId++}if(this.customRenderTargets.length>0&&d.restoreDefaultFramebuffer(),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.activeCamera=p,this.proceduralTexturesEnabled){e.Tools.StartPerformanceCounter("Procedural textures",this.proceduralTextures.length>0);for(var g=0;g0)}if((this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil),this.shadowsEnabled)for(var y=0;y0)for(var c=0;c0&&this._engine.clear(null,!1,!0,!0),this._processSubCameras(this.activeCameras[c]);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera)}this._checkIntersections(),e.AudioEngine&&this._updateAudioParameters(),this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this);for(var f=0;f0?this.activeCameras[0]:this.activeCamera)&&i.canUseWebAudio&&i.audioContext){i.audioContext.listener.setPosition(t.position.x,t.position.y,t.position.z),t.rigCameras&&t.rigCameras.length>0&&(t=t.rigCameras[0]);var r=e.Matrix.Invert(t.getViewMatrix()),n=e.Vector3.TransformNormal(new e.Vector3(0,0,-1),r);n.normalize(),isNaN(n.x)||isNaN(n.y)||isNaN(n.z)||i.audioContext.listener.setOrientation(n.x,n.y,n.z,0,1,0);var o;for(o=0;o-1&&this._engine.scenes.splice(a,1),this._engine.wipeCaches(!0),this._isDisposed=!0},Object.defineProperty(r.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!0,configurable:!0}),r.prototype.disposeSounds=function(){if(this._mainSoundTrack){this.mainSoundTrack.dispose();for(var e=0;e=n.distance))&&(n=h,r)))break}return n||new e.PickingInfo},r.prototype._internalMultiPick=function(t,i){if(!e.PickingInfo)return null;for(var r=new Array,n=0;n0)for(var s=0;s=o.distance))&&(o=l,r))break}}return o||new e.PickingInfo},r.prototype.pick=function(t,i,r,n,o){var s=this;if(!e.PickingInfo)return null;var a=this._internalPick((function(e){return s.createPickingRayToRef(t,i,e,s._tempPickingRay,o||null),s._tempPickingRay}),r,n);return a&&(a.ray=this.createPickingRay(t,i,e.Matrix.Identity(),o||null)),a},r.prototype.pickSprite=function(e,t,i,r,n){return this.createPickingRayInCameraSpaceToRef(e,t,this._tempPickingRay,n),this._internalPickSprites(this._tempPickingRay,i,r,n)},r.prototype.pickWithRay=function(t,i,r){var n=this,o=this._internalPick((function(i){return n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(n._pickWithRayInverseMatrix),n._cachedRayForTransform||(n._cachedRayForTransform=e.Ray.Zero()),e.Ray.TransformToRef(t,n._pickWithRayInverseMatrix,n._cachedRayForTransform),n._cachedRayForTransform}),i,r);return o&&(o.ray=t),o},r.prototype.multiPick=function(e,t,i,r){var n=this;return this._internalMultiPick((function(i){return n.createPickingRay(e,t,i,r||null)}),i)},r.prototype.multiPickWithRay=function(t,i){var r=this;return this._internalMultiPick((function(i){return r._pickWithRayInverseMatrix||(r._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(r._pickWithRayInverseMatrix),r._cachedRayForTransform||(r._cachedRayForTransform=e.Ray.Zero()),e.Ray.TransformToRef(t,r._pickWithRayInverseMatrix,r._cachedRayForTransform),r._cachedRayForTransform}),i)},r.prototype.setPointerOverMesh=function(t){this._pointerOverMesh!==t&&(this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)),this._pointerOverMesh=t,this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)))},r.prototype.getPointerOverMesh=function(){return this._pointerOverMesh},r.prototype.setPointerOverSprite=function(t){this._pointerOverSprite!==t&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=t,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)))},r.prototype.getPointerOverSprite=function(){return this._pointerOverSprite},r.prototype.getPhysicsEngine=function(){return this._physicsEngine},r.prototype.enablePhysics=function(t,i){if(void 0===t&&(t=null),this._physicsEngine)return!0;try{return this._physicsEngine=new e.PhysicsEngine(t,i),!0}catch(t){return e.Tools.Error(t.message),!1}},r.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},r.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},r.prototype.deleteCompoundImpostor=function(e){var t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},r.prototype._rebuildGeometries=function(){for(var e=0,t=this.geometries;e=0&&this._scene.textures.splice(e,1),void 0!==this._texture&&(this.releaseInternalTexture(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear())}},t.prototype.serialize=function(){if(!this.name)return null;var t=e.SerializationHelper.Serialize(this);return e.Animation.AppendSerializedAnimations(this,t),t},t.WhenAllReady=function(e,t){var i=e.length;if(0===i)return void t();for(var r,n,o=0;o0},enumerable:!0,configurable:!0}),r.prototype.getLODLevels=function(){return this._LODLevels},r.prototype._sortLODLevels=function(){this._LODLevels.sort((function(e,t){return e.distancet.distance?-1:0}))},r.prototype.addLODLevel=function(t,i){if(i&&i._masterMesh)return e.Tools.Warn("You cannot use a mesh as LOD level twice"),this;var r=new e.MeshLODLevel(t,i);return this._LODLevels.push(r),i&&(i._masterMesh=this),this._sortLODLevels(),this},r.prototype.getLODLevelAtDistance=function(e){for(var t=0;tr)return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,this._LODLevels[this._LODLevels.length-1].mesh),this;for(var n=0;n0;this.computeWorldMatrix();var a=this.material||o.defaultMaterial;if(a)if(a.storeEffectOnSubMeshes)for(var l=0,h=this.subMeshes;l4,s=o?this.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind):null,a=o?this.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind):null,l=this.skeleton.getTransformMatrices(this),h=e.Tmp.Vector3[0],c=e.Tmp.Matrix[0],u=e.Tmp.Matrix[1],f=0,d=0;d0&&(e.Matrix.FromFloat32ArrayToRefScaled(l,Math.floor(16*r[f+p]),m,u),c.addToSelf(u));if(o)for(p=0;p<4;p++)(m=a[f+p])>0&&(e.Matrix.FromFloat32ArrayToRefScaled(l,Math.floor(16*s[f+p]),m,u),c.addToSelf(u));e.Vector3.TransformCoordinatesFromFloatsToRef(i[d],i[d+1],i[d+2],c,h),h.toArray(i,d)}}return i},r.prototype._createGlobalSubMesh=function(t){var i=this.getTotalVertices();if(!i||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){var r=this.getIndices();if(!r)return null;var n=r.length,o=!1;if(t)o=!0;else for(var s=0,a=this.subMeshes;s=n){o=!0;break}if(l.verticesStart+l.verticesCount>=i){o=!0;break}}if(!o)return this.subMeshes[0]}return this.releaseSubMeshes(),new e.SubMesh(0,0,i,0,this.getTotalIndices(),this)},r.prototype.subdivide=function(t){if(!(t<1)){for(var i=this.getTotalIndices(),r=i/t|0,n=0;r%3!=0;)r++;this.releaseSubMeshes();for(var o=0;o=i);o++)e.SubMesh.CreateFromIndices(0,n,Math.min(r,i-n),this),n+=r;this.synchronizeInstances()}},r.prototype.setVerticesData=function(t,i,r,n){if(void 0===r&&(r=!1),this._geometry)this._geometry.setVerticesData(t,i,r,n);else{var o=new e.VertexData;o.set(i,t);var s=this.getScene();new e.Geometry(e.Geometry.RandomId(),s,o,r,this)}return this},r.prototype.markVerticesDataAsUpdatable=function(e,t){void 0===t&&(t=!0);var i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)},r.prototype.setVerticesBuffer=function(t){return this._geometry||(this._geometry=e.Geometry.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(t),this},r.prototype.updateVerticesData=function(e,t,i,r){return this._geometry?(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this},r.prototype.updateMeshPositions=function(t,i){void 0===i&&(i=!0);var r=this.getVerticesData(e.VertexBuffer.PositionKind);if(!r)return this;if(t(r),this.updateVerticesData(e.VertexBuffer.PositionKind,r,!1,!1),i){var n=this.getIndices(),o=this.getVerticesData(e.VertexBuffer.NormalKind);if(!o)return this;e.VertexData.ComputeNormals(r,n,o),this.updateVerticesData(e.VertexBuffer.NormalKind,o,!1,!1)}return this},r.prototype.makeGeometryUnique=function(){if(!this._geometry)return this;var t=this._geometry,i=this._geometry.copy(e.Geometry.RandomId());return t.releaseForMesh(this,!0),i.applyToMesh(this),this},r.prototype.setIndices=function(t,i,r){if(void 0===i&&(i=null),void 0===r&&(r=!1),this._geometry)this._geometry.setIndices(t,i,r);else{var n=new e.VertexData;n.indices=t;var o=this.getScene();new e.Geometry(e.Geometry.RandomId(),o,n,r,this)}return this},r.prototype.updateIndices=function(e,t){return this._geometry?(this._geometry.updateIndices(e,t),this):this},r.prototype.toLeftHanded=function(){return this._geometry?(this._geometry.toLeftHanded(),this):this},r.prototype._bind=function(t,i,r){if(!this._geometry)return this;var n,o=this.getScene().getEngine();if(this._unIndexed)n=null;else switch(r){case e.Material.PointFillMode:n=null;break;case e.Material.WireFrameFillMode:n=t.getLinesIndexBuffer(this.getIndices(),o);break;default:case e.Material.TriangleFillMode:n=this._unIndexed?null:this._geometry.getIndexBuffer()}return this._geometry._bind(i,n),this},r.prototype._draw=function(t,i,r,n){if(void 0===n&&(n=!1),!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this.onBeforeDrawObservable.notifyObservers(this);var o=this.getScene(),s=o.getEngine();if(this._unIndexed||i==e.Material.PointFillMode?s.drawArraysType(i,t.verticesStart,t.verticesCount,r):i==e.Material.WireFrameFillMode?s.drawElementsType(i,0,t.linesIndexCount,r):s.drawElementsType(i,t.indexStart,t.indexCount,r),o._isAlternateRenderingEnabled&&!n){var a=t.effect||this._effectiveMaterial.getEffect();if(!a||!o.activeCamera)return this;o._switchToAlternateCameraConfiguration(!0),this._effectiveMaterial.bindView(a),this._effectiveMaterial.bindViewProjection(a),s.setViewport(o.activeCamera._alternateCamera.viewport),this._draw(t,i,r,!0),s.setViewport(o.activeCamera.viewport),o._switchToAlternateCameraConfiguration(!1),this._effectiveMaterial.bindView(a),this._effectiveMaterial.bindViewProjection(a)}return this},r.prototype.registerBeforeRender=function(e){return this.onBeforeRenderObservable.add(e),this},r.prototype.unregisterBeforeRender=function(e){return this.onBeforeRenderObservable.removeCallback(e),this},r.prototype.registerAfterRender=function(e){return this.onAfterRenderObservable.add(e),this},r.prototype.unregisterAfterRender=function(e){return this.onAfterRenderObservable.removeCallback(e),this},r.prototype._getInstancesRenderList=function(e){var t=this.getScene();if(this._batchCache.mustReturn=!1,this._batchCache.renderSelf[e]=this.isEnabled()&&this.isVisible,this._batchCache.visibleInstances[e]=null,this._visibleInstances){var i=t.getRenderId(),r=t._isInIntermediateRendering()?this._visibleInstances.intermediateDefaultRenderId:this._visibleInstances.defaultRenderId;this._batchCache.visibleInstances[e]=this._visibleInstances[i];var n=this._renderId;!this._batchCache.visibleInstances[e]&&r&&(this._batchCache.visibleInstances[e]=this._visibleInstances[r],i=Math.max(r,i),n=Math.max(this._visibleInstances.selfDefaultRenderId,i));var o=this._batchCache.visibleInstances[e];if(o&&o.length){if(this._renderIdForInstances[e]===i)return this._batchCache.mustReturn=!0,this._batchCache;i!==n&&(this._batchCache.renderSelf[e]=!1)}this._renderIdForInstances[e]=i}return this._batchCache},r.prototype._renderWithInstances=function(t,i,r,n,o){var s=r.visibleInstances[t._id];if(!s)return this;for(var a=s.length+1,l=16*a*4,h=this._instancesBufferSize,c=this._instancesBuffer;this._instancesBufferSizes-1)&&(c=s-1),h>.001){for(var d=1/h,u=0;u<4;u++)n[l+u]*=d;if(o)for(var u=0;u<4;u++)o[l+u]*=d}else c>=4?(o[l+c-4]=1-h,r[l+c-4]=t):(n[l+c]=1-h,i[l+c]=t)}this.setVerticesData(e.VertexBuffer.MatricesIndicesKind,i),r&&this.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,r),this.setVerticesData(e.VertexBuffer.MatricesWeightsKind,n),o&&this.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,o)}},r.prototype._checkDelayState=function(){var t=this.getScene();return this._geometry?this._geometry.load(t):this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADING,this._queueLoad(t)),this},r.prototype._queueLoad=function(t){var i=this;t._addPendingData(this);var r=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return e.Tools.LoadFile(this.delayLoadingFile,(function(r){r instanceof ArrayBuffer?i._delayLoadingFunction(r,i):i._delayLoadingFunction(JSON.parse(r),i),i.instances.forEach((function(e){e._syncSubMeshes()})),i.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,t._removePendingData(i)}),(function(){}),t.database,r),this},r.prototype.isInFrustum=function(t){return this.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADING&&(!!i.prototype.isInFrustum.call(this,t)&&(this._checkDelayState(),!0))},r.prototype.setMaterialByID=function(e){var t,i=this.getScene().materials;for(t=i.length-1;t>-1;t--)if(i[t].id===e)return this.material=i[t],this;var r=this.getScene().multiMaterials;for(t=r.length-1;t>-1;t--)if(r[t].id===e)return this.material=r[t],this;return this},r.prototype.getAnimatables=function(){var e=new Array;return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e},r.prototype.bakeTransformIntoVertices=function(t){if(!this.isVerticesDataPresent(e.VertexBuffer.PositionKind))return this;var i=this.subMeshes.splice(0);this._resetPointsArrayCache();var r,n=this.getVerticesData(e.VertexBuffer.PositionKind),o=new Array;for(r=0;r-1&&(o.morphTargetManager=i.getMorphTargetManagerById(t.morphTargetManagerId)),t.skeletonId>-1&&(o.skeleton=i.getLastSkeletonByID(t.skeletonId),t.numBoneInfluencers&&(o.numBoneInfluencers=t.numBoneInfluencers)),t.animations){for(var s=0;s4,h=l?this.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind):null,c=l?this.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind):null,u=t.getTransformMatrices(this),f=e.Vector3.Zero(),d=new e.Matrix,p=new e.Matrix,m=0,_=0;_0&&(e.Matrix.FromFloat32ArrayToRefScaled(u,Math.floor(16*o[m+a]),g,p),d.addToSelf(p));if(l)for(a=0;a<4;a++)(g=c[m+a])>0&&(e.Matrix.FromFloat32ArrayToRefScaled(u,Math.floor(16*h[m+a]),g,p),d.addToSelf(p));e.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[_],this._sourcePositions[_+1],this._sourcePositions[_+2],d,f),f.toArray(r,_),e.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[_],this._sourceNormals[_+1],this._sourceNormals[_+2],d,f),f.toArray(n,_),d.reset()}return this.updateVerticesData(e.VertexBuffer.PositionKind,r),this.updateVerticesData(e.VertexBuffer.NormalKind,n),this},r.MinMax=function(t){var i=null,r=null;return t.forEach((function(e,t,n){var o=e.getBoundingInfo(),s=o.boundingBox;i&&r?(i.minimizeInPlace(s.minimumWorld),r.maximizeInPlace(s.maximumWorld)):(i=s.minimumWorld,r=s.maximumWorld)})),i&&r?{min:i,max:r}:{min:e.Vector3.Zero(),max:e.Vector3.Zero()}},r.Center=function(t){var i=t instanceof Array?r.MinMax(t):t;return e.Vector3.Center(i.min,i.max)},r.MergeMeshes=function(t,i,n,o,s){void 0===i&&(i=!0);var a;if(!n){var l=0;for(a=0;a65536)return e.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}var h,c=null,u=new Array,f=null;for(a=0;aa&&(a=c)}return new i(e,s,a-s+1,t,r,n,o)},i})(t);e.SubMesh=i})(r||(r={}));var r,s=this&&this.__assign||Object.assign||function(e){for(var t,i=1,r=arguments.length;i=0&&this._scene.materials.splice(i,1),i=0;ia?a:Math.floor(l);var h,c,u,f,d=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,p=i.uvs,m=i.colors,_=[],g=[],v=[],y=[],b=[],x=[],T=[],E=[],P=[],A=[];if(r.length<2){var M=[],S=[];for(u=0;u0&&(I=R[f].subtract(R[f-1]).length(),w=I+T[c],b[c].push(w),T[c]=w),f++;o&&(f--,_.push(R[0].x,R[0].y,R[0].z),I=R[f].subtract(R[0]).length(),w=I+T[c],b[c].push(w),T[c]=w),P[c]=C+D,A[c]=O,O+=C+D}var L,F,B=null,V=null;for(u=0;u1)?1:i.arc||1,l=i.slice&&i.slice<=0?1:i.slice||1,h=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,c=new e.Vector3(n/2,o/2,s/2),u=2+r,f=2*u,d=[],p=[],m=[],_=[],g=0;g<=u;g++){for(var v=g/u,y=v*Math.PI*l,b=0;b<=f;b++){var x=b/f,T=x*Math.PI*2*a,E=e.Matrix.RotationZ(-y),P=e.Matrix.RotationY(T),A=e.Vector3.TransformCoordinates(e.Vector3.Up(),E),M=e.Vector3.TransformCoordinates(A,P),S=M.multiply(c),R=M.divide(c).normalize();p.push(S.x,S.y,S.z),m.push(R.x,R.y,R.z),_.push(x,v)}if(g>0)for(var C=p.length/3,O=C-2*(f+1);O+f+21)?1:i.arc||1,f=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,d=i.faceUV||new Array(3),p=i.faceColors,m=1!==u&&c?2:0,_=h?l:1,g=2+(1+m)*_;for(r=0;r0&&(i.push(a-1),i.push(a)),a++}var f=new t;return f.indices=i,f.positions=r,o&&(f.colors=s),f},t.CreateDashedLines=function(i){var r=i.dashSize||3,n=i.gapSize||1,o=i.dashNb||200,s=i.points,a=new Array,l=new Array,h=e.Vector3.Zero(),c=0,u=0,f=0,d=0,p=0,m=0,_=0;for(_=0;_1)?1:i.arc||1,c=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE;r.push(0,0,0),s.push(.5,.5);for(var u=2*Math.PI*h,f=u/l,d=0;d=r.length)?0:i.type||0,u=i.size,f=i.sizeX||u||1,d=i.sizeY||u||1,p=i.sizeZ||u||1,m=i.custom||r[c],_=m.face.length,g=i.faceUV||new Array(_),v=i.faceColors,y=void 0===i.flat||i.flat,b=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,x=new Array,T=new Array,E=new Array,P=new Array,A=new Array,M=0,S=0,R=new Array,C=0,O=0;if(y)for(O=0;O<_;O++)v&&void 0===v[O]&&(v[O]=new e.Color4(1,1,1,1)),g&&void 0===g[O]&&(g[O]=new e.Vector4(0,0,1,1));if(y)for(O=0;O<_;O++){var D=m.face[O].length;for(s=2*Math.PI/D, -a=.5*Math.tan(s/2),l=.5,C=0;Cn.bbSize.y?n.bbSize.x:n.bbSize.y;$=$>n.bbSize.z?$:n.bbSize.z,w=n.subDiv.X*O/n.bbSize.x,L=n.subDiv.Y*O/n.bbSize.y,F=n.subDiv.Z*O/n.bbSize.z,B=n.subDiv.max*n.subDiv.max,n.facetPartitioning.length=0}for(o=0;o0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),this._indexBuffer&&(this._indexBuffer.references=i)},t.prototype.notifyUpdate=function(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e);for(var t=0,i=this._meshes;t0){for(var i=0;i0){for(var i=0;i0){for(var i=0;i0){var l=new Float32Array(i,a.positionsAttrDesc.offset,a.positionsAttrDesc.count);r.setVerticesData(e.VertexBuffer.PositionKind,l,!1)}if(a.normalsAttrDesc&&a.normalsAttrDesc.count>0){var h=new Float32Array(i,a.normalsAttrDesc.offset,a.normalsAttrDesc.count);r.setVerticesData(e.VertexBuffer.NormalKind,h,!1)}if(a.tangetsAttrDesc&&a.tangetsAttrDesc.count>0){var c=new Float32Array(i,a.tangetsAttrDesc.offset,a.tangetsAttrDesc.count);r.setVerticesData(e.VertexBuffer.TangentKind,c,!1)}if(a.uvsAttrDesc&&a.uvsAttrDesc.count>0){var u=new Float32Array(i,a.uvsAttrDesc.offset,a.uvsAttrDesc.count);r.setVerticesData(e.VertexBuffer.UVKind,u,!1)}if(a.uvs2AttrDesc&&a.uvs2AttrDesc.count>0){var f=new Float32Array(i,a.uvs2AttrDesc.offset,a.uvs2AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV2Kind,f,!1)}if(a.uvs3AttrDesc&&a.uvs3AttrDesc.count>0){var d=new Float32Array(i,a.uvs3AttrDesc.offset,a.uvs3AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV3Kind,d,!1)}if(a.uvs4AttrDesc&&a.uvs4AttrDesc.count>0){var p=new Float32Array(i,a.uvs4AttrDesc.offset,a.uvs4AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV4Kind,p,!1)}if(a.uvs5AttrDesc&&a.uvs5AttrDesc.count>0){var m=new Float32Array(i,a.uvs5AttrDesc.offset,a.uvs5AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV5Kind,m,!1)}if(a.uvs6AttrDesc&&a.uvs6AttrDesc.count>0){var _=new Float32Array(i,a.uvs6AttrDesc.offset,a.uvs6AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV6Kind,_,!1)}if(a.colorsAttrDesc&&a.colorsAttrDesc.count>0){var g=new Float32Array(i,a.colorsAttrDesc.offset,a.colorsAttrDesc.count);r.setVerticesData(e.VertexBuffer.ColorKind,g,!1,a.colorsAttrDesc.stride)}if(a.matricesIndicesAttrDesc&&a.matricesIndicesAttrDesc.count>0){for(var v=new Int32Array(i,a.matricesIndicesAttrDesc.offset,a.matricesIndicesAttrDesc.count),y=[],b=0;b>8),y.push((16711680&x)>>16),y.push(x>>24)}r.setVerticesData(e.VertexBuffer.MatricesIndicesKind,y,!1)}if(a.matricesWeightsAttrDesc&&a.matricesWeightsAttrDesc.count>0){var T=new Float32Array(i,a.matricesWeightsAttrDesc.offset,a.matricesWeightsAttrDesc.count);r.setVerticesData(e.VertexBuffer.MatricesWeightsKind,T,!1)}if(a.indicesAttrDesc&&a.indicesAttrDesc.count>0){var E=new Int32Array(i,a.indicesAttrDesc.offset,a.indicesAttrDesc.count);r.setIndices(E,null)}if(a.subMeshesAttrDesc&&a.subMeshesAttrDesc.count>0){var P=new Int32Array(i,a.subMeshesAttrDesc.offset,5*a.subMeshesAttrDesc.count);r.subMeshes=[];for(var b=0;b>8),y.push((16711680&O)>>16),y.push(O>>24)}r.setVerticesData(e.VertexBuffer.MatricesIndicesKind,y,i.matricesIndices._updatable)}if(i.matricesIndicesExtra)if(i.matricesIndicesExtra._isExpanded)delete i.matricesIndices._isExpanded,r.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,i.matricesIndicesExtra,i.matricesIndicesExtra._updatable);else{for(var y=[],b=0;b>8),y.push((16711680&O)>>16),y.push(O>>24)}r.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,y,i.matricesIndicesExtra._updatable)}i.matricesWeights&&(t._CleanMatricesWeights(i,r),r.setVerticesData(e.VertexBuffer.MatricesWeightsKind,i.matricesWeights,i.matricesWeights._updatable)),i.matricesWeightsExtra&&r.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,i.matricesWeightsExtra,i.matricesWeights._updatable),r.setIndices(i.indices,null)}if(i.subMeshes){r.subMeshes=[];for(var D=0;D-1){var n=i.getScene().getLastSkeletonByID(t.skeletonId);if(n){r=n.bones.length;for(var o=i.getVerticesData(e.VertexBuffer.MatricesIndicesKind),s=i.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind),a=t.matricesWeights,l=t.matricesWeightsExtra,h=t.numBoneInfluencer,c=a.length,u=0;uh-1)&&(d=h-1),f>.001){for(var _=1/f,p=0;p<4;p++)a[u+p]*=_;if(l)for(var p=0;p<4;p++)l[u+p]*=_}else d>=4?(l[u+d-4]=1-f,s[u+d-4]=r):(a[u+d]=1-f,o[u+d]=r)}i.setVerticesData(e.VertexBuffer.MatricesIndicesKind,o),t.matricesWeightsExtra&&i.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,s)}}}},t.Parse=function(i,r,n){if(r.getGeometryByID(i.id))return null;var o=new t(i.id,r,void 0,i.updatable);return e.Tags&&e.Tags.AddTagsTo(o,i.tags),i.delayLoadingFile?(o.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED,o.delayLoadingFile=n+i.delayLoadingFile,o._boundingInfo=new e.BoundingInfo(e.Vector3.FromArray(i.boundingBoxMinimum),e.Vector3.FromArray(i.boundingBoxMaximum)),o._delayInfo=[],i.hasUVs&&o._delayInfo.push(e.VertexBuffer.UVKind),i.hasUVs2&&o._delayInfo.push(e.VertexBuffer.UV2Kind),i.hasUVs3&&o._delayInfo.push(e.VertexBuffer.UV3Kind),i.hasUVs4&&o._delayInfo.push(e.VertexBuffer.UV4Kind),i.hasUVs5&&o._delayInfo.push(e.VertexBuffer.UV5Kind),i.hasUVs6&&o._delayInfo.push(e.VertexBuffer.UV6Kind),i.hasColors&&o._delayInfo.push(e.VertexBuffer.ColorKind),i.hasMatricesIndices&&o._delayInfo.push(e.VertexBuffer.MatricesIndicesKind),i.hasMatricesWeights&&o._delayInfo.push(e.VertexBuffer.MatricesWeightsKind),o._delayLoadingFunction=e.VertexData.ImportVertexData):e.VertexData.ImportVertexData(i,o),r.pushGeometry(o,!0),o},t})();e.Geometry=t;var i=(function(e){function t(t,i,r,n){void 0===r&&(r=!1),void 0===n&&(n=null);var o=e.call(this,t,i,void 0,!1,n)||this;return o._canBeRegenerated=r,o._beingRegenerated=!0,o.regenerate(),o._beingRegenerated=!1,o}return o(t,e),t.prototype.canBeRegenerated=function(){return this._canBeRegenerated},t.prototype.regenerate=function(){this._canBeRegenerated&&(this._beingRegenerated=!0,this.setAllVerticesData(this._regenerateVertexData(),!1),this._beingRegenerated=!1)},t.prototype.asNewGeometry=function(t){return e.prototype.copy.call(this,t)},t.prototype.setAllVerticesData=function(t,i){this._beingRegenerated&&e.prototype.setAllVerticesData.call(this,t,!1)},t.prototype.setVerticesData=function(t,i,r){this._beingRegenerated&&e.prototype.setVerticesData.call(this,t,i,!1)},t.prototype._regenerateVertexData=function(){throw new Error("Abstract method")},t.prototype.copy=function(e){throw new Error("Must be overriden in sub-classes.")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.canBeRegenerated=this.canBeRegenerated(),t},t})(t);e._PrimitiveGeometry=i;var r=(function(t){function i(i,r,n,o,s,a,l,h,c){void 0===c&&(c=e.Mesh.DEFAULTSIDE);var u=t.call(this,i,r,l,h)||this;return u.pathArray=n,u.closeArray=o,u.closePath=s,u.offset=a,u.side=c,u}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateRibbon({pathArray:this.pathArray,closeArray:this.closeArray,closePath:this.closePath,offset:this.offset,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.pathArray,this.closeArray,this.closePath,this.offset,this.canBeRegenerated(),void 0,this.side)},i})(i);e.RibbonGeometry=r;var n=(function(t){function i(i,r,n,o,s,a){void 0===s&&(s=null),void 0===a&&(a=e.Mesh.DEFAULTSIDE);var l=t.call(this,i,r,o,s)||this;return l.size=n,l.side=a,l}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateBox({size:this.size,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.size,this.canBeRegenerated(),void 0,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.size=this.size,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.size,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.BoxGeometry=n;var s=(function(t){function i(i,r,n,o,s,a,l){void 0===a&&(a=null),void 0===l&&(l=e.Mesh.DEFAULTSIDE);var h=t.call(this,i,r,s,a)||this;return h.segments=n,h.diameter=o,h.side=l,h}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateSphere({segments:this.segments,diameter:this.diameter,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.segments,this.diameter,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.segments=this.segments,e.diameter=this.diameter,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.segments,t.diameter,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.SphereGeometry=s;var a=(function(t){function i(i,r,n,o,s,a,l){void 0===a&&(a=null),void 0===l&&(l=e.Mesh.DEFAULTSIDE);var h=t.call(this,i,r,s,a)||this;return h.radius=n,h.tessellation=o,h.side=l,h}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateDisc({radius:this.radius,tessellation:this.tessellation,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.radius,this.tessellation,this.canBeRegenerated(),null,this.side)},i})(i);e.DiscGeometry=a;var l=(function(t){function i(i,r,n,o,s,a,l,h,c,u){void 0===l&&(l=1),void 0===c&&(c=null),void 0===u&&(u=e.Mesh.DEFAULTSIDE);var f=t.call(this,i,r,h,c)||this;return f.height=n,f.diameterTop=o,f.diameterBottom=s,f.tessellation=a,f.subdivisions=l,f.side=u,f}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateCylinder({height:this.height,diameterTop:this.diameterTop,diameterBottom:this.diameterBottom,tessellation:this.tessellation,subdivisions:this.subdivisions,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.height,this.diameterTop,this.diameterBottom,this.tessellation,this.subdivisions,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.height=this.height,e.diameterTop=this.diameterTop,e.diameterBottom=this.diameterBottom,e.tessellation=this.tessellation,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.height,t.diameterTop,t.diameterBottom,t.tessellation,t.subdivisions,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.CylinderGeometry=l -;var h=(function(t){function i(i,r,n,o,s,a,l,h){void 0===l&&(l=null),void 0===h&&(h=e.Mesh.DEFAULTSIDE);var c=t.call(this,i,r,a,l)||this;return c.diameter=n,c.thickness=o,c.tessellation=s,c.side=h,c}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorus({diameter:this.diameter,thickness:this.thickness,tessellation:this.tessellation,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.diameter,this.thickness,this.tessellation,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.diameter=this.diameter,e.thickness=this.thickness,e.tessellation=this.tessellation,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.diameter,t.thickness,t.tessellation,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.TorusGeometry=h;var c=(function(t){function i(e,i,r,n,o,s,a){void 0===a&&(a=null);var l=t.call(this,e,i,s,a)||this;return l.width=r,l.height=n,l.subdivisions=o,l}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateGround({width:this.width,height:this.height,subdivisions:this.subdivisions})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.width,this.height,this.subdivisions,this.canBeRegenerated(),null)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.width=this.width,e.height=this.height,e.subdivisions=this.subdivisions,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.width,t.height,t.subdivisions,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.GroundGeometry=c;var u=(function(t){function i(e,i,r,n,o,s,a,l,h,c){void 0===c&&(c=null);var u=t.call(this,e,i,h,c)||this;return u.xmin=r,u.zmin=n,u.xmax=o,u.zmax=s,u.subdivisions=a,u.precision=l,u}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTiledGround({xmin:this.xmin,zmin:this.zmin,xmax:this.xmax,zmax:this.zmax,subdivisions:this.subdivisions,precision:this.precision})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.xmin,this.zmin,this.xmax,this.zmax,this.subdivisions,this.precision,this.canBeRegenerated(),null)},i})(i);e.TiledGroundGeometry=u;var f=(function(t){function i(i,r,n,o,s,a){void 0===s&&(s=null),void 0===a&&(a=e.Mesh.DEFAULTSIDE);var l=t.call(this,i,r,o,s)||this;return l.size=n,l.side=a,l}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreatePlane({size:this.size,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.size,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.size=this.size,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.size,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.PlaneGeometry=f;var d=(function(t){function i(i,r,n,o,s,a,l,h,c,u,f){void 0===u&&(u=null),void 0===f&&(f=e.Mesh.DEFAULTSIDE);var d=t.call(this,i,r,c,u)||this;return d.radius=n,d.tube=o,d.radialSegments=s,d.tubularSegments=a,d.p=l,d.q=h,d.side=f,d}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorusKnot({radius:this.radius,tube:this.tube,radialSegments:this.radialSegments,tubularSegments:this.tubularSegments,p:this.p,q:this.q,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.radius,this.tube,this.radialSegments,this.tubularSegments,this.p,this.q,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.radius=this.radius,e.tube=this.tube,e.radialSegments=this.radialSegments,e.tubularSegments=this.tubularSegments,e.p=this.p,e.q=this.q,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.radius,t.tube,t.radialSegments,t.tubularSegments,t.p,t.q,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.TorusKnotGeometry=d})(r||(r={}));var r;!(function(e){var t=(function(){function t(e){void 0===e&&(e=30),this._enabled=!0,this._rollingFrameTime=new i(e)}return t.prototype.sampleFrame=function(t){if(void 0===t&&(t=e.Tools.Now),this._enabled){if(null!=this._lastFrameTimeMs){var i=t-this._lastFrameTimeMs;this._rollingFrameTime.add(i)}this._lastFrameTimeMs=t}},Object.defineProperty(t.prototype,"averageFrameTime",{get:function(){return this._rollingFrameTime.average},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"averageFrameTimeVariance",{get:function(){return this._rollingFrameTime.variance},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"instantaneousFrameTime",{get:function(){return this._rollingFrameTime.history(0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"averageFPS",{get:function(){return 1e3/this._rollingFrameTime.average},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"instantaneousFPS",{get:function(){var e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isSaturated",{get:function(){return this._rollingFrameTime.isSaturated()},enumerable:!0,configurable:!0}),t.prototype.enable=function(){this._enabled=!0},t.prototype.disable=function(){this._enabled=!1,this._lastFrameTimeMs=null},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._enabled},enumerable:!0,configurable:!0}),t.prototype.reset=function(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()},t})();e.PerformanceMonitor=t;var i=(function(){function e(e){this._samples=new Array(e),this.reset()}return e.prototype.add=function(e){var t;if(this.isSaturated()){var i=this._samples[this._pos];t=i-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(i-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length},e.prototype.history=function(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;var t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]},e.prototype.isSaturated=function(){return this._sampleCount>=this._samples.length},e.prototype.reset=function(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0},e.prototype._wrapPosition=function(e){var t=this._samples.length;return(e%t+t)%t},e})();e.RollingAverage=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.BindEyePosition=function(e,t){if(t._forcedViewPosition)return void e.setVector3("vEyePosition",t._forcedViewPosition);e.setVector3("vEyePosition",t._mirroredCameraPosition?t._mirroredCameraPosition:t.activeCamera.globalPosition)},t.PrepareDefinesForMergedUV=function(e,t,i){t._needUVs=!0,t[i]=!0,e.getTextureMatrix().isIdentity(!0)?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,0===e.coordinatesIndex?t.MAINUV1=!0:t.MAINUV2=!0):t[i+"DIRECTUV"]=0},t.BindTextureMatrix=function(e,t,i){var r=e.getTextureMatrix();r.isIdentity(!0)||t.updateMatrix(i+"Matrix",r)},t.PrepareDefinesForMisc=function(t,i,r,n,o,s,a){a._areMiscDirty&&(a.LOGARITHMICDEPTH=r,a.POINTSIZE=n,a.FOG=i.fogEnabled&&t.applyFog&&i.fogMode!==e.Scene.FOGMODE_NONE&&o,a.NONUNIFORMSCALING=t.nonUniformScaling,a.ALPHATEST=s)},t.PrepareDefinesForFrameBoundValues=function(e,t,i,r,n){void 0===n&&(n=null);var o=!1;null==n&&(n=void 0!==e.clipPlane&&null!==e.clipPlane),i.CLIPPLANE!==n&&(i.CLIPPLANE=n,o=!0),i.DEPTHPREPASS!==!t.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==r&&(i.INSTANCES=r,o=!0),o&&i.markAsUnprocessed()},t.PrepareDefinesForAttributes=function(t,i,r,n,o,s){if(void 0===o&&(o=!1),void 0===s&&(s=!0),!i._areAttributesDirty&&i._needNormals===i._normals&&i._needUVs===i._uvs)return!1;if(i._normals=i._needNormals,i._uvs=i._needUVs,i.NORMAL=i._needNormals&&t.isVerticesDataPresent(e.VertexBuffer.NormalKind),i._needNormals&&t.isVerticesDataPresent(e.VertexBuffer.TangentKind)&&(i.TANGENT=!0),i._needUVs?(i.UV1=t.isVerticesDataPresent(e.VertexBuffer.UVKind),i.UV2=t.isVerticesDataPresent(e.VertexBuffer.UV2Kind)):(i.UV1=!1,i.UV2=!1),r){var a=t.useVertexColors&&t.isVerticesDataPresent(e.VertexBuffer.ColorKind);i.VERTEXCOLOR=a,i.VERTEXALPHA=t.hasVertexAlpha&&a&&s}if(n&&(t.useBones&&t.computeBonesUsingShaders&&t.skeleton?(i.NUM_BONE_INFLUENCERS=t.numBoneInfluencers,i.BonesPerMesh=t.skeleton.bones.length+1):(i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0)),o){var l=t.morphTargetManager;l?(i.MORPHTARGETS_TANGENT=l.supportsTangents&&i.TANGENT,i.MORPHTARGETS_NORMAL=l.supportsNormals&&i.NORMAL,i.MORPHTARGETS=l.numInfluencers>0,i.NUM_MORPH_INFLUENCERS=l.numInfluencers):(i.MORPHTARGETS_TANGENT=!1,i.MORPHTARGETS_NORMAL=!1,i.MORPHTARGETS=!1,i.NUM_MORPH_INFLUENCERS=0)}return!0},t.PrepareDefinesForLights=function(t,i,r,n,o,s){if(void 0===o&&(o=4),void 0===s&&(s=!1),!r._areLightsDirty)return r._needNormals;var a=0,l=!1,h=!1,c=!1,u=!1,f=!1;if(t.lightsEnabled&&!s)for(var d=0,p=i._lightSources;d0&&(u=!0,_.prepareDefines(r,a))}}if(m.lightmapMode!=e.Light.LIGHTMAP_DEFAULT?(c=!0,r["LIGHTMAPEXCLUDED"+a]=!0,r["LIGHTMAPNOSPECULAR"+a]=m.lightmapMode==e.Light.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+a]=!1,r["LIGHTMAPNOSPECULAR"+a]=!1),++a===o)break}r.SPECULARTERM=f,r.SHADOWS=u;for(var v=a;v0&&(n=r+o,t.addFallback(n,"LIGHT"+o)),e.SHADOWS||(e["SHADOW"+o]&&t.addFallback(r,"SHADOW"+o),e["SHADOWPCF"+o]&&t.addFallback(r,"SHADOWPCF"+o),e["SHADOWPCSS"+o]&&t.addFallback(r,"SHADOWPCSS"+o),e["SHADOWPOISSON"+o]&&t.addFallback(r,"SHADOWPOISSON"+o),e["SHADOWESM"+o]&&t.addFallback(r,"SHADOWESM"+o));return n++},t.PrepareAttributesForMorphTargets=function(t,i,r){var n=r.NUM_MORPH_INFLUENCERS;if(n>0&&e.Engine.LastCreatedEngine)for(var o=e.Engine.LastCreatedEngine.getCaps().maxVertexAttribs,s=i.morphTargetManager,a=s&&s.supportsNormals&&r.NORMAL,l=s&&s.supportsTangents&&r.TANGENT,h=0;ho&&e.Tools.Error("Cannot add more vertex attributes for mesh "+i.name)},t.PrepareAttributesForBones=function(t,i,r,n){r.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,i),t.push(e.VertexBuffer.MatricesIndicesKind),t.push(e.VertexBuffer.MatricesWeightsKind),r.NUM_BONE_INFLUENCERS>4&&(t.push(e.VertexBuffer.MatricesIndicesExtraKind),t.push(e.VertexBuffer.MatricesWeightsExtraKind)))},t.PrepareAttributesForInstances=function(e,t){t.INSTANCES&&(e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"))},t.BindLightShadow=function(e,t,i,r,n){if(e.shadowEnabled&&i.receiveShadows){var o=e.getShadowGenerator();o&&o.bindShadowLight(r,n)}},t.BindLightProperties=function(e,t,i){e.transferToEffect(t,i+"")},t.BindLights=function(i,r,n,o,s,a){void 0===s&&(s=4),void 0===a&&(a=!1);for(var l=Math.min(r._lightSources.length,s),h=0;h0,a.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,a.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===e.Texture.INVCUBIC_MODE,a.REFLECTIONMAP_3D=this._reflectionTexture.isCube,this._reflectionTexture.coordinatesMode){case e.Texture.EXPLICIT_MODE:a.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case e.Texture.PLANAR_MODE:a.setReflectionMode("REFLECTIONMAP_PLANAR");break;case e.Texture.PROJECTION_MODE:a.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case e.Texture.SKYBOX_MODE:a.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case e.Texture.SPHERICAL_MODE:a.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case e.Texture.EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:default:a.setReflectionMode("REFLECTIONMAP_CUBIC")}a.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else a.REFLECTION=!1;if(this._emissiveTexture&&r.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,a,"EMISSIVE")}else a.EMISSIVE=!1;if(this._lightmapTexture&&r.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,a,"LIGHTMAP"),a.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap}else a.LIGHTMAP=!1;if(this._specularTexture&&r.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture,a,"SPECULAR"),a.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else a.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&r.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,a,"BUMP"),a.PARALLAX=this._useParallax,a.PARALLAXOCCLUSION=this._useParallaxOcclusion,a.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else a.BUMP=!1;if(this._refractionTexture&&r.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;a._needUVs=!0,a.REFRACTION=!0,a.REFRACTIONMAP_3D=this._refractionTexture.isCube}else a.REFRACTION=!1;a.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else a.DIFFUSE=!1,a.AMBIENT=!1,a.OPACITY=!1,a.REFLECTION=!1,a.EMISSIVE=!1,a.LIGHTMAP=!1,a.BUMP=!1,a.REFRACTION=!1;a.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),a.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,a.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,a.SPECULAROVERALPHA=this._useSpecularOverAlpha,a.PREMULTIPLYALPHA=this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED||this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF}if(a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a),a.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,a.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if(a._areFresnelDirty&&(r.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(a.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,a.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,a.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,a.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,a.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,a.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,a._needNormals=!0,a.FRESNEL=!0):a.FRESNEL=!1),e.MaterialHelper.PrepareDefinesForMisc(i,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(i),a),e.MaterialHelper.PrepareDefinesForAttributes(i,a,!0,!0,!0),e.MaterialHelper.PrepareDefinesForFrameBoundValues(s,l,a,o),a.isDirty){a.markAsProcessed(),s.resetCachedMaterial();var h=new e.EffectFallbacks;a.REFLECTION&&h.addFallback(0,"REFLECTION"),a.SPECULAR&&h.addFallback(0,"SPECULAR"),a.BUMP&&h.addFallback(0,"BUMP"),a.PARALLAX&&h.addFallback(1,"PARALLAX"),a.PARALLAXOCCLUSION&&h.addFallback(0,"PARALLAXOCCLUSION"),a.SPECULAROVERALPHA&&h.addFallback(0,"SPECULAROVERALPHA"),a.FOG&&h.addFallback(1,"FOG"),a.POINTSIZE&&h.addFallback(0,"POINTSIZE"),a.LOGARITHMICDEPTH&&h.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(a,h,this._maxSimultaneousLights),a.SPECULARTERM&&h.addFallback(0,"SPECULARTERM"),a.DIFFUSEFRESNEL&&h.addFallback(1,"DIFFUSEFRESNEL"),a.OPACITYFRESNEL&&h.addFallback(2,"OPACITYFRESNEL"),a.REFLECTIONFRESNEL&&h.addFallback(3,"REFLECTIONFRESNEL"),a.EMISSIVEFRESNEL&&h.addFallback(4,"EMISSIVEFRESNEL"),a.FRESNEL&&h.addFallback(4,"FRESNEL");var c=[e.VertexBuffer.PositionKind];a.NORMAL&&c.push(e.VertexBuffer.NormalKind),a.UV1&&c.push(e.VertexBuffer.UVKind),a.UV2&&c.push(e.VertexBuffer.UV2Kind),a.VERTEXCOLOR&&c.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(c,i,a,h),e.MaterialHelper.PrepareAttributesForInstances(c,a),e.MaterialHelper.PrepareAttributesForMorphTargets(c,i,a);var u="default",f=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff"],d=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler"],p=["Material","Scene"];e.ImageProcessingConfiguration&&(e.ImageProcessingConfiguration.PrepareUniforms(f,a),e.ImageProcessingConfiguration.PrepareSamplers(d,a)),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:f,uniformBuffersNames:p,samplers:d,defines:a,maxSimultaneousLights:this._maxSimultaneousLights}),this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,f,p,d,a));var m=a.toString();n.setEffect(s.getEngine().createEffect(u,{attributes:c,uniformsNames:f,uniformBuffersNames:p,samplers:d,defines:m,fallbacks:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:a.NUM_MORPH_INFLUENCERS}},l),a),this.buildUniformLayout()}return!(!n.effect||!n.effect.isReady())&&(a._renderId=s.getRenderId(),this._wasPreviouslyReady=!0,!0)},r.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("diffuseLeftColor",4),this._uniformBuffer.addUniform("diffuseRightColor",4),this._uniformBuffer.addUniform("opacityParts",4),this._uniformBuffer.addUniform("reflectionLeftColor",4),this._uniformBuffer.addUniform("reflectionRightColor",4),this._uniformBuffer.addUniform("refractionLeftColor",4),this._uniformBuffer.addUniform("refractionRightColor",4),this._uniformBuffer.addUniform("emissiveLeftColor",4),this._uniformBuffer.addUniform("emissiveRightColor",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vAmbientInfos",2),this._uniformBuffer.addUniform("vOpacityInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("vReflectionPosition",3),this._uniformBuffer.addUniform("vReflectionSize",3),this._uniformBuffer.addUniform("vEmissiveInfos",2),this._uniformBuffer.addUniform("vLightmapInfos",2),this._uniformBuffer.addUniform("vSpecularInfos",2),this._uniformBuffer.addUniform("vBumpInfos",3), -this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("ambientMatrix",16),this._uniformBuffer.addUniform("opacityMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("emissiveMatrix",16),this._uniformBuffer.addUniform("lightmapMatrix",16),this._uniformBuffer.addUniform("specularMatrix",16),this._uniformBuffer.addUniform("bumpMatrix",16),this._uniformBuffer.addUniform("vTangentSpaceParams",2),this._uniformBuffer.addUniform("refractionMatrix",16),this._uniformBuffer.addUniform("vRefractionInfos",4),this._uniformBuffer.addUniform("vSpecularColor",4),this._uniformBuffer.addUniform("vEmissiveColor",3),this._uniformBuffer.addUniform("vDiffuseColor",4),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.create()},r.prototype.unbind=function(){if(this._activeEffect){var e=!1;this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&(this._activeEffect.setTexture("reflection2DSampler",null),e=!0),this._refractionTexture&&this._refractionTexture.isRenderTarget&&(this._activeEffect.setTexture("refraction2DSampler",null),e=!0),e&&this._markAllSubMeshesAsTexturesDirty()}i.prototype.unbind.call(this)},r.prototype.bindForSubMesh=function(t,i,n){var o=this.getScene(),s=n._materialDefines;if(s){var a=n.effect;if(a){this._activeEffect=a,this.bindOnlyWorldMatrix(t),s.OBJECTSPACE_NORMALMAP&&(t.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var l=this._mustRebind(o,a,i.visibility);if(e.MaterialHelper.BindBonesParameters(i,a),l){if(this._uniformBuffer.bindToEffect(a,"Material"),this.bindViewProjection(a),!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync){if(r.FresnelEnabled&&s.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),this._uniformBuffer.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&this._uniformBuffer.updateColor4("opacityParts",new e.Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),this._uniformBuffer.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),this._uniformBuffer.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),this._uniformBuffer.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),o.texturesEnabled){if(this._diffuseTexture&&r.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),e.MaterialHelper.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse"),this._diffuseTexture.hasAlpha&&a.setFloat("alphaCutOff",this.alphaCutOff)),this._ambientTexture&&r.AmbientTextureEnabled&&(this._uniformBuffer.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),e.MaterialHelper.BindTextureMatrix(this._ambientTexture,this._uniformBuffer,"ambient")),this._opacityTexture&&r.OpacityTextureEnabled&&(this._uniformBuffer.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),e.MaterialHelper.BindTextureMatrix(this._opacityTexture,this._uniformBuffer,"opacity")),this._reflectionTexture&&r.ReflectionTextureEnabled&&(this._uniformBuffer.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),this._uniformBuffer.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){var h=this._reflectionTexture;this._uniformBuffer.updateVector3("vReflectionPosition",h.boundingBoxPosition),this._uniformBuffer.updateVector3("vReflectionSize",h.boundingBoxSize)}if(this._emissiveTexture&&r.EmissiveTextureEnabled&&(this._uniformBuffer.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),e.MaterialHelper.BindTextureMatrix(this._emissiveTexture,this._uniformBuffer,"emissive")),this._lightmapTexture&&r.LightmapTextureEnabled&&(this._uniformBuffer.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),e.MaterialHelper.BindTextureMatrix(this._lightmapTexture,this._uniformBuffer,"lightmap")),this._specularTexture&&r.SpecularTextureEnabled&&(this._uniformBuffer.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),e.MaterialHelper.BindTextureMatrix(this._specularTexture,this._uniformBuffer,"specular")),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&r.BumpTextureEnabled&&(this._uniformBuffer.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),e.MaterialHelper.BindTextureMatrix(this._bumpTexture,this._uniformBuffer,"bump"),o._mirroredCameraPosition?this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&r.RefractionTextureEnabled){var c=1;this._refractionTexture.isCube||(this._uniformBuffer.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(c=this._refractionTexture.depth)),this._uniformBuffer.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,c,this.invertRefractionY?-1:1)}}this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.SPECULARTERM&&this._uniformBuffer.updateColor4("vSpecularColor",this.specularColor,this.specularPower),this._uniformBuffer.updateColor3("vEmissiveColor",this.emissiveColor),this._uniformBuffer.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha*i.visibility)}if(o.texturesEnabled&&(this._diffuseTexture&&r.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&r.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&r.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&r.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&r.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&r.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&r.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&r.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&r.RefractionTextureEnabled)){var c=1;this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture)}e.MaterialHelper.BindClipPlane(a,o),o.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),e.MaterialHelper.BindEyePosition(a,o),a.setColor3("vAmbientColor",this._globalAmbientColor)}!l&&this.isFrozen||(o.lightsEnabled&&!this._disableLighting&&e.MaterialHelper.BindLights(o,i,a,s,this._maxSimultaneousLights),(o.fogEnabled&&i.applyFog&&o.fogMode!==e.Scene.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture)&&this.bindView(a),e.MaterialHelper.BindFogParameters(o,i,a),s.NUM_MORPH_INFLUENCERS&&e.MaterialHelper.BindMorphTargetParameters(i,a),e.MaterialHelper.BindLogDepth(s,a,o),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(i,this._activeEffect)}}},r.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e},r.prototype.getActiveTextures=function(){var e=i.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e},r.prototype.hasTexture=function(e){return!!i.prototype.hasTexture.call(this,e)||(this._diffuseTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._emissiveTexture===e||(this._specularTexture===e||(this._bumpTexture===e||(this._lightmapTexture===e||this._refractionTexture===e))))))))},r.prototype.dispose=function(e,t){t&&(this._diffuseTexture&&this._diffuseTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._specularTexture&&this._specularTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),i.prototype.dispose.call(this,e,t)},r.prototype.clone=function(t){var i=this,n=e.SerializationHelper.Clone((function(){return new r(t,i.getScene())}),this);return n.name=t,n.id=t,n},r.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},r.Parse=function(t,i,n){return e.SerializationHelper.Parse((function(){return new r(t.name,i)}),t,i,n)},Object.defineProperty(r,"DiffuseTextureEnabled",{get:function(){return r._DiffuseTextureEnabled},set:function(t){r._DiffuseTextureEnabled!==t&&(r._DiffuseTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"AmbientTextureEnabled",{get:function(){return r._AmbientTextureEnabled},set:function(t){r._AmbientTextureEnabled!==t&&(r._AmbientTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"OpacityTextureEnabled",{get:function(){return r._OpacityTextureEnabled},set:function(t){r._OpacityTextureEnabled!==t&&(r._OpacityTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"ReflectionTextureEnabled",{get:function(){return r._ReflectionTextureEnabled},set:function(t){r._ReflectionTextureEnabled!==t&&(r._ReflectionTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"EmissiveTextureEnabled",{get:function(){return r._EmissiveTextureEnabled},set:function(t){r._EmissiveTextureEnabled!==t&&(r._EmissiveTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"SpecularTextureEnabled",{get:function(){return r._SpecularTextureEnabled},set:function(t){r._SpecularTextureEnabled!==t&&(r._SpecularTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"BumpTextureEnabled",{get:function(){return r._BumpTextureEnabled},set:function(t){r._BumpTextureEnabled!==t&&(r._BumpTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"LightmapTextureEnabled",{get:function(){return r._LightmapTextureEnabled},set:function(t){r._LightmapTextureEnabled!==t&&(r._LightmapTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"RefractionTextureEnabled",{get:function(){return r._RefractionTextureEnabled},set:function(t){r._RefractionTextureEnabled!==t&&(r._RefractionTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"ColorGradingTextureEnabled",{get:function(){return r._ColorGradingTextureEnabled},set:function(t){r._ColorGradingTextureEnabled!==t&&(r._ColorGradingTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"FresnelEnabled",{get:function(){return r._FresnelEnabled},set:function(t){r._FresnelEnabled!==t&&(r._FresnelEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.FresnelDirtyFlag))},enumerable:!0,configurable:!0}),r._DiffuseTextureEnabled=!0,r._AmbientTextureEnabled=!0,r._OpacityTextureEnabled=!0,r._ReflectionTextureEnabled=!0,r._EmissiveTextureEnabled=!0,r._SpecularTextureEnabled=!0,r._BumpTextureEnabled=!0,r._LightmapTextureEnabled=!0,r._RefractionTextureEnabled=!0,r._ColorGradingTextureEnabled=!0,r._FresnelEnabled=!0,n([e.serializeAsTexture("diffuseTexture")],r.prototype,"_diffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],r.prototype,"diffuseTexture",void 0),n([e.serializeAsTexture("ambientTexture")],r.prototype,"_ambientTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"ambientTexture",void 0),n([e.serializeAsTexture("opacityTexture")],r.prototype,"_opacityTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],r.prototype,"opacityTexture",void 0),n([e.serializeAsTexture("reflectionTexture")],r.prototype,"_reflectionTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionTexture",void 0),n([e.serializeAsTexture("emissiveTexture")],r.prototype,"_emissiveTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"emissiveTexture",void 0),n([e.serializeAsTexture("specularTexture")],r.prototype,"_specularTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"specularTexture",void 0),n([e.serializeAsTexture("bumpTexture")],r.prototype,"_bumpTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"bumpTexture",void 0),n([e.serializeAsTexture("lightmapTexture")],r.prototype,"_lightmapTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"lightmapTexture",void 0),n([e.serializeAsTexture("refractionTexture")],r.prototype,"_refractionTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"refractionTexture",void 0),n([e.serializeAsColor3("ambient")],r.prototype,"ambientColor",void 0),n([e.serializeAsColor3("diffuse")],r.prototype,"diffuseColor",void 0),n([e.serializeAsColor3("specular")],r.prototype,"specularColor",void 0),n([e.serializeAsColor3("emissive")],r.prototype,"emissiveColor",void 0),n([e.serialize()],r.prototype,"specularPower",void 0),n([e.serialize("useAlphaFromDiffuseTexture")],r.prototype,"_useAlphaFromDiffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useAlphaFromDiffuseTexture",void 0),n([e.serialize("useEmissiveAsIllumination")],r.prototype,"_useEmissiveAsIllumination",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useEmissiveAsIllumination",void 0),n([e.serialize("linkEmissiveWithDiffuse")],r.prototype,"_linkEmissiveWithDiffuse",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"linkEmissiveWithDiffuse",void 0),n([e.serialize("useSpecularOverAlpha")],r.prototype,"_useSpecularOverAlpha",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useSpecularOverAlpha",void 0),n([e.serialize("useReflectionOverAlpha")],r.prototype,"_useReflectionOverAlpha",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useReflectionOverAlpha",void 0),n([e.serialize("disableLighting")],r.prototype,"_disableLighting",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"disableLighting",void 0),n([e.serialize("useObjectSpaceNormalMap")],r.prototype,"_useObjectSpaceNormalMap",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useObjectSpaceNormalMap",void 0),n([e.serialize("useParallax")],r.prototype,"_useParallax",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useParallax",void 0),n([e.serialize("useParallaxOcclusion")],r.prototype,"_useParallaxOcclusion",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useParallaxOcclusion",void 0),n([e.serialize()],r.prototype,"parallaxScaleBias",void 0),n([e.serialize("roughness")],r.prototype,"_roughness",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"roughness",void 0),n([e.serialize()],r.prototype,"indexOfRefraction",void 0),n([e.serialize()],r.prototype,"invertRefractionY",void 0),n([e.serialize()],r.prototype,"alphaCutOff",void 0),n([e.serialize("useLightmapAsShadowmap")],r.prototype,"_useLightmapAsShadowmap",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useLightmapAsShadowmap",void 0),n([e.serializeAsFresnelParameters("diffuseFresnelParameters")],r.prototype,"_diffuseFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"diffuseFresnelParameters",void 0),n([e.serializeAsFresnelParameters("opacityFresnelParameters")],r.prototype,"_opacityFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")],r.prototype,"opacityFresnelParameters",void 0),n([e.serializeAsFresnelParameters("reflectionFresnelParameters")],r.prototype,"_reflectionFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"reflectionFresnelParameters",void 0),n([e.serializeAsFresnelParameters("refractionFresnelParameters")],r.prototype,"_refractionFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"refractionFresnelParameters",void 0),n([e.serializeAsFresnelParameters("emissiveFresnelParameters")],r.prototype,"_emissiveFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"emissiveFresnelParameters",void 0),n([e.serialize("useReflectionFresnelFromSpecular")],r.prototype,"_useReflectionFresnelFromSpecular",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"useReflectionFresnelFromSpecular",void 0),n([e.serialize("useGlossinessFromSpecularMapAlpha")],r.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useGlossinessFromSpecularMapAlpha",void 0),n([e.serialize("maxSimultaneousLights")],r.prototype,"_maxSimultaneousLights",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"maxSimultaneousLights",void 0),n([e.serialize("invertNormalMapX")],r.prototype,"_invertNormalMapX",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"invertNormalMapX",void 0),n([e.serialize("invertNormalMapY")],r.prototype,"_invertNormalMapY",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"invertNormalMapY",void 0),n([e.serialize("twoSidedLighting")],r.prototype,"_twoSidedLighting",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"twoSidedLighting",void 0),n([e.serialize()],r.prototype,"useLogarithmicDepth",null),r})(e.PushMaterial);e.StandardMaterial=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.x=e.Vector3.Zero(),this.y=e.Vector3.Zero(),this.z=e.Vector3.Zero(),this.xx=e.Vector3.Zero(),this.yy=e.Vector3.Zero(),this.zz=e.Vector3.Zero(),this.xy=e.Vector3.Zero(),this.yz=e.Vector3.Zero(),this.zx=e.Vector3.Zero()}return t.prototype.addAmbient=function(t){var i=new e.Vector3(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.prototype.scale=function(e){this.x=this.x.scale(e),this.y=this.y.scale(e),this.z=this.z.scale(e),this.xx=this.xx.scale(e),this.yy=this.yy.scale(e),this.zz=this.zz.scale(e),this.yz=this.yz.scale(e),this.zx=this.zx.scale(e),this.xy=this.xy.scale(e)},t.FromHarmonics=function(e){var i=new t;return i.x=e.l11.scale(1.02333),i.y=e.l1_1.scale(1.02333),i.z=e.l10.scale(1.02333),i.xx=e.l00.scale(.886277).subtract(e.l20.scale(.247708)).add(e.lL22.scale(.429043)),i.yy=e.l00.scale(.886277).subtract(e.l20.scale(.247708)).subtract(e.lL22.scale(.429043)),i.zz=e.l00.scale(.886277).add(e.l20.scale(.495417)),i.yz=e.l2_1.scale(.858086),i.zx=e.l21.scale(.858086),i.xy=e.l2_2.scale(.858086),i.scale(1/Math.PI),i},t.FromArray=function(i){var r=new t;return e.Vector3.FromArrayToRef(i[0],0,r.x),e.Vector3.FromArrayToRef(i[1],0,r.y),e.Vector3.FromArrayToRef(i[2],0,r.z),e.Vector3.FromArrayToRef(i[3],0,r.xx),e.Vector3.FromArrayToRef(i[4],0,r.yy),e.Vector3.FromArrayToRef(i[5],0,r.zz),e.Vector3.FromArrayToRef(i[6],0,r.yz),e.Vector3.FromArrayToRef(i[7],0,r.zx),e.Vector3.FromArrayToRef(i[8],0,r.xy),r},t})();e.SphericalPolynomial=t;var i=(function(){function t(){this.l00=e.Vector3.Zero(),this.l1_1=e.Vector3.Zero(),this.l10=e.Vector3.Zero(),this.l11=e.Vector3.Zero(),this.l2_2=e.Vector3.Zero(),this.l2_1=e.Vector3.Zero(),this.l20=e.Vector3.Zero(),this.l21=e.Vector3.Zero(),this.lL22=e.Vector3.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e.Vector3(i.r,i.g,i.b),o=n.scale(r);this.l00=this.l00.add(o.scale(.282095)),this.l1_1=this.l1_1.add(o.scale(.488603*t.y)),this.l10=this.l10.add(o.scale(.488603*t.z)),this.l11=this.l11.add(o.scale(.488603*t.x)),this.l2_2=this.l2_2.add(o.scale(1.092548*t.x*t.y)),this.l2_1=this.l2_1.add(o.scale(1.092548*t.y*t.z)),this.l21=this.l21.add(o.scale(1.092548*t.x*t.z)),this.l20=this.l20.add(o.scale(.315392*(3*t.z*t.z-1))),this.lL22=this.lL22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(e){this.l00=this.l00.scale(e),this.l1_1=this.l1_1.scale(e),this.l10=this.l10.scale(e),this.l11=this.l11.scale(e),this.l2_2=this.l2_2.scale(e),this.l2_1=this.l2_1.scale(e),this.l20=this.l20.scale(e),this.l21=this.l21.scale(e),this.lL22=this.lL22.scale(e)},t.prototype.convertIncidentRadianceToIrradiance=function(){this.l00=this.l00.scale(3.141593),this.l1_1=this.l1_1.scale(2.094395),this.l10=this.l10.scale(2.094395),this.l11=this.l11.scale(2.094395),this.l2_2=this.l2_2.scale(.785398),this.l2_1=this.l2_1.scale(.785398),this.l20=this.l20.scale(.785398),this.l21=this.l21.scale(.785398),this.lL22=this.lL22.scale(.785398)},t.prototype.convertIrradianceToLambertianRadiance=function(){this.scale(1/Math.PI)},t.FromPolynomial=function(e){var i=new t;return i.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),i.l1_1=e.y.scale(.977204),i.l10=e.z.scale(.977204),i.l11=e.x.scale(.977204),i.l2_2=e.xy.scale(1.16538),i.l2_1=e.yz.scale(1.16538),i.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),i.l21=e.zx.scale(1.16538),i.lL22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),i.scale(Math.PI),i},t.FromArray=function(i){var r=new t;return e.Vector3.FromArrayToRef(i[0],0,r.l00),e.Vector3.FromArrayToRef(i[1],0,r.l1_1),e.Vector3.FromArrayToRef(i[2],0,r.l10),e.Vector3.FromArrayToRef(i[3],0,r.l11),e.Vector3.FromArrayToRef(i[4],0,r.l2_2),e.Vector3.FromArrayToRef(i[5],0,r.l2_1),e.Vector3.FromArrayToRef(i[6],0,r.l20),e.Vector3.FromArrayToRef(i[7],0,r.l21),e.Vector3.FromArrayToRef(i[8],0,r.lL22),r},t})();e.SphericalHarmonics=i})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}return e})(),i=(function(){function i(){}return i.ConvertCubeMapTextureToSphericalPolynomial=function(t){if(!t.isCube)return null;var i,r,n=t.getSize().width,o=t.readPixels(0),s=t.readPixels(1);t.isRenderTarget?(i=t.readPixels(3),r=t.readPixels(2)):(i=t.readPixels(2),r=t.readPixels(3));var a=t.readPixels(4),l=t.readPixels(5),h=t.gammaSpace,c=e.Engine.TEXTUREFORMAT_RGBA,u=e.Engine.TEXTURETYPE_UNSIGNED_INT;t.textureType&&t.textureType!==e.Engine.TEXTURETYPE_UNSIGNED_INT&&(u=e.Engine.TEXTURETYPE_FLOAT);var f={size:n,right:o,left:s,up:i,down:r,front:a,back:l,format:c,type:u,gammaSpace:h};return this.ConvertCubeMapToSphericalPolynomial(f)},i.ConvertCubeMapToSphericalPolynomial=function(t){for(var i=new e.SphericalHarmonics,r=0,n=2/t.size,o=n,s=.5*n-1,a=0;a<6;a++)for(var l=this.FileFaces[a],h=t[l.name],c=s,u=t.format===e.Engine.TEXTUREFORMAT_RGBA?4:3,f=0;f0&&h.addCPUSkinningFallback(c++,t),i.MORPHTARGETS&&h.addFallback(c++,"MORPHTARGETS");var u=[e.VertexBuffer.PositionKind];i.NORMAL&&u.push(e.VertexBuffer.NormalKind),i.TANGENT&&u.push(e.VertexBuffer.TangentKind),i.UV1&&u.push(e.VertexBuffer.UVKind),i.UV2&&u.push(e.VertexBuffer.UV2Kind),i.VERTEXCOLOR&&u.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(u,t,i,h),e.MaterialHelper.PrepareAttributesForInstances(u,i),e.MaterialHelper.PrepareAttributesForMorphTargets(u,t,i);var f=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vEmissiveColor","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","refractionMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX","vSphericalYY","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vReflectionMicrosurfaceInfos","vRefractionMicrosurfaceInfos","vTangentSpaceParams"],d=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","microSurfaceSampler","environmentBrdfSampler"],p=["Material","Scene"];e.ImageProcessingConfiguration&&(e.ImageProcessingConfiguration.PrepareUniforms(f,i),e.ImageProcessingConfiguration.PrepareSamplers(d,i)),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:f,uniformBuffersNames:p,samplers:d,defines:i,maxSimultaneousLights:this._maxSimultaneousLights});var m=i.toString();return l.createEffect("pbr",{attributes:u,uniformsNames:f,uniformBuffersNames:p,samplers:d,defines:m,fallbacks:h,onCompiled:r,onError:n,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:i.NUM_MORPH_INFLUENCERS}},l)},r.prototype._prepareDefines=function(t,i,r,n){void 0===r&&(r=null),void 0===n&&(n=null);var o=this.getScene(),s=o.getEngine();if(e.MaterialHelper.PrepareDefinesForLights(o,t,i,!0,this._maxSimultaneousLights,this._disableLighting),i._needNormals=!0,i.METALLICWORKFLOW=this.isMetallicWorkflow(),i._areTexturesDirty){if(i._needUVs=!1,o.texturesEnabled){o.getEngine().getCaps().textureLOD&&(i.LODBASEDMICROSFURACE=!0),this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled?e.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture,i,"ALBEDO"):i.ALBEDO=!1,this._ambientTexture&&e.StandardMaterial.AmbientTextureEnabled?(e.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture,i,"AMBIENT"),i.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):i.AMBIENT=!1,this._opacityTexture&&e.StandardMaterial.OpacityTextureEnabled?(e.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture,i,"OPACITY"),i.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):i.OPACITY=!1;var a=this._getReflectionTexture();if(a&&e.StandardMaterial.ReflectionTextureEnabled){switch(i.REFLECTION=!0,i.GAMMAREFLECTION=a.gammaSpace,i.RGBDREFLECTION=a.isRGBD,i.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!a.invertZ:a.invertZ,i.LODINREFLECTIONALPHA=a.lodLevelInAlpha,a.coordinatesMode===e.Texture.INVCUBIC_MODE&&(i.INVERTCUBICMAP=!0),i.REFLECTIONMAP_3D=a.isCube,a.coordinatesMode){case e.Texture.EXPLICIT_MODE:i.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:i.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:i.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:i.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:i.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:default:i.REFLECTIONMAP_CUBIC=!0,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!!a.boundingBoxSize}a.coordinatesMode!==e.Texture.SKYBOX_MODE&&a.sphericalPolynomial&&(i.USESPHERICALFROMREFLECTIONMAP=!0,this._forceIrradianceInFragment||o.getEngine().getCaps().maxVaryingVectors<=8?i.USESPHERICALINVERTEX=!1:i.USESPHERICALINVERTEX=!0)}else i.REFLECTION=!1,i.REFLECTIONMAP_3D=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_CUBIC=!1,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.INVERTCUBICMAP=!1,i.USESPHERICALFROMREFLECTIONMAP=!1,i.USESPHERICALINVERTEX=!1,i.REFLECTIONMAP_OPPOSITEZ=!1,i.LODINREFLECTIONALPHA=!1,i.GAMMAREFLECTION=!1,i.RGBDREFLECTION=!1;this._lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled?(e.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,i,"LIGHTMAP"),i.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,i.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace):i.LIGHTMAP=!1,this._emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled?e.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,i,"EMISSIVE"):i.EMISSIVE=!1,e.StandardMaterial.SpecularTextureEnabled?(this._metallicTexture?(e.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture,i,"REFLECTIVITY"),i.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,i.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,i.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,i.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed):this._reflectivityTexture?(e.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture,i,"REFLECTIVITY"),i.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,i.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap):i.REFLECTIVITY=!1,this._microSurfaceTexture?e.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture,i,"MICROSURFACEMAP"):i.MICROSURFACEMAP=!1):(i.REFLECTIVITY=!1,i.MICROSURFACEMAP=!1),o.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&e.StandardMaterial.BumpTextureEnabled&&!this._disableBumpMap?(e.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,i,"BUMP"),this._useParallax&&this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled?(i.PARALLAX=!0,i.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):i.PARALLAX=!1,i.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):i.BUMP=!1;var l=this._getRefractionTexture();l&&e.StandardMaterial.RefractionTextureEnabled?(i.REFRACTION=!0,i.REFRACTIONMAP_3D=l.isCube,i.GAMMAREFRACTION=l.gammaSpace,i.RGBDREFRACTION=l.isRGBD,i.REFRACTIONMAP_OPPOSITEZ=l.invertZ,i.LODINREFRACTIONALPHA=l.lodLevelInAlpha,this._linkRefractionWithTransparency&&(i.LINKREFRACTIONTOTRANSPARENCY=!0)):i.REFRACTION=!1,this._environmentBRDFTexture&&e.StandardMaterial.ReflectionTextureEnabled?i.ENVIRONMENTBRDF=!0:i.ENVIRONMENTBRDF=!1,this._shouldUseAlphaFromAlbedoTexture()?i.ALPHAFROMALBEDO=!0:i.ALPHAFROMALBEDO=!1}i.SPECULAROVERALPHA=this._useSpecularOverAlpha,i.USEPHYSICALLIGHTFALLOFF=this._usePhysicalLightFalloff,i.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?i.TWOSIDEDLIGHTING=!0:i.TWOSIDEDLIGHTING=!1,i.ALPHATESTVALUE=this._alphaCutOff+(this._alphaCutOff%1==0?".":""),i.PREMULTIPLYALPHA=this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED||this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF,i.ALPHABLEND=this.needAlphaBlendingForMesh(t),i.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,i.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel,i.SPECULARAA=o.getEngine().getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}i._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(i),i.FORCENORMALFORWARD=this._forceNormalForward,i.RADIANCEOCCLUSION=this._useRadianceOcclusion,i.HORIZONOCCLUSION=this._useHorizonOcclusion,i._areMiscDirty&&(e.MaterialHelper.PrepareDefinesForMisc(t,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(t)||this._forceAlphaTest,i),i.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!t.isVerticesDataPresent(e.VertexBuffer.NormalKind)),e.MaterialHelper.PrepareDefinesForFrameBoundValues(o,s,i,!!r,n),e.MaterialHelper.PrepareDefinesForAttributes(t,i,!0,!0,!0,this._transparencyMode!==e.PBRMaterial.PBRMATERIAL_OPAQUE)},r.prototype.forceCompilation=function(e,i,r){var n=this,o=s({clipPlane:!1},r),a=new t,l=this._prepareEffect(e,a,void 0,void 0,void 0,o.clipPlane);l.isReady()?i&&i(this):l.onCompileObservable.add((function(){i&&i(n)}))},r.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("vAlbedoInfos",2),this._uniformBuffer.addUniform("vAmbientInfos",3),this._uniformBuffer.addUniform("vOpacityInfos",2),this._uniformBuffer.addUniform("vEmissiveInfos",2),this._uniformBuffer.addUniform("vLightmapInfos",2),this._uniformBuffer.addUniform("vReflectivityInfos",3),this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos",2),this._uniformBuffer.addUniform("vRefractionInfos",4),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("vReflectionPosition",3),this._uniformBuffer.addUniform("vReflectionSize",3),this._uniformBuffer.addUniform("vBumpInfos",3),this._uniformBuffer.addUniform("albedoMatrix",16),this._uniformBuffer.addUniform("ambientMatrix",16),this._uniformBuffer.addUniform("opacityMatrix",16),this._uniformBuffer.addUniform("emissiveMatrix",16),this._uniformBuffer.addUniform("lightmapMatrix",16),this._uniformBuffer.addUniform("reflectivityMatrix",16),this._uniformBuffer.addUniform("microSurfaceSamplerMatrix",16),this._uniformBuffer.addUniform("bumpMatrix",16),this._uniformBuffer.addUniform("vTangentSpaceParams",2),this._uniformBuffer.addUniform("refractionMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionColor",3),this._uniformBuffer.addUniform("vAlbedoColor",4),this._uniformBuffer.addUniform("vLightingIntensity",4),this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("vReflectivityColor",4),this._uniformBuffer.addUniform("vEmissiveColor",3),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.create()},r.prototype.unbind=function(){this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._uniformBuffer.setTexture("refractionSampler",null),i.prototype.unbind.call(this)},r.prototype.bindForSubMesh=function(t,i,r){var n=this.getScene(),o=r._materialDefines;if(o){var s=r.effect;if(s){this._activeEffect=s,this.bindOnlyWorldMatrix(t),o.OBJECTSPACE_NORMALMAP&&(t.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var a=this._mustRebind(n,s,i.visibility);e.MaterialHelper.BindBonesParameters(i,this._activeEffect);var l=null;if(a){this._uniformBuffer.bindToEffect(s,"Material"),this.bindViewProjection(s),l=this._getReflectionTexture();var h=this._getRefractionTexture();if(!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync){if(n.texturesEnabled){if(this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),e.MaterialHelper.BindTextureMatrix(this._albedoTexture,this._uniformBuffer,"albedo")),this._ambientTexture&&e.StandardMaterial.AmbientTextureEnabled&&(this._uniformBuffer.updateFloat3("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength),e.MaterialHelper.BindTextureMatrix(this._ambientTexture,this._uniformBuffer,"ambient")),this._opacityTexture&&e.StandardMaterial.OpacityTextureEnabled&&(this._uniformBuffer.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),e.MaterialHelper.BindTextureMatrix(this._opacityTexture,this._uniformBuffer,"opacity")),l&&e.StandardMaterial.ReflectionTextureEnabled){if(this._uniformBuffer.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){var c=l;this._uniformBuffer.updateVector3("vReflectionPosition",c.boundingBoxPosition),this._uniformBuffer.updateVector3("vReflectionSize",c.boundingBoxSize)}var u=l.sphericalPolynomial;o.USESPHERICALFROMREFLECTIONMAP&&u&&(this._activeEffect.setFloat3("vSphericalX",u.x.x,u.x.y,u.x.z),this._activeEffect.setFloat3("vSphericalY",u.y.x,u.y.y,u.y.z),this._activeEffect.setFloat3("vSphericalZ",u.z.x,u.z.y,u.z.z),this._activeEffect.setFloat3("vSphericalXX_ZZ",u.xx.x-u.zz.x,u.xx.y-u.zz.y,u.xx.z-u.zz.z),this._activeEffect.setFloat3("vSphericalYY_ZZ",u.yy.x-u.zz.x,u.yy.y-u.zz.y,u.yy.z-u.zz.z),this._activeEffect.setFloat3("vSphericalZZ",u.zz.x,u.zz.y,u.zz.z),this._activeEffect.setFloat3("vSphericalXY",u.xy.x,u.xy.y,u.xy.z),this._activeEffect.setFloat3("vSphericalYZ",u.yz.x,u.yz.y,u.yz.z),this._activeEffect.setFloat3("vSphericalZX",u.zx.x,u.zx.y,u.zx.z)),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}if(this._emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled&&(this._uniformBuffer.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),e.MaterialHelper.BindTextureMatrix(this._emissiveTexture,this._uniformBuffer,"emissive")),this._lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled&&(this._uniformBuffer.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),e.MaterialHelper.BindTextureMatrix(this._lightmapTexture,this._uniformBuffer,"lightmap")),e.StandardMaterial.SpecularTextureEnabled&&(this._metallicTexture?(this._uniformBuffer.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),e.MaterialHelper.BindTextureMatrix(this._metallicTexture,this._uniformBuffer,"reflectivity")):this._reflectivityTexture&&(this._uniformBuffer.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),e.MaterialHelper.BindTextureMatrix(this._reflectivityTexture,this._uniformBuffer,"reflectivity")),this._microSurfaceTexture&&(this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),e.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture,this._uniformBuffer,"microSurfaceSampler"))),this._bumpTexture&&n.getEngine().getCaps().standardDerivatives&&e.StandardMaterial.BumpTextureEnabled&&!this._disableBumpMap&&(this._uniformBuffer.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),e.MaterialHelper.BindTextureMatrix(this._bumpTexture,this._uniformBuffer,"bump"),n._mirroredCameraPosition?this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),h&&e.StandardMaterial.RefractionTextureEnabled){this._uniformBuffer.updateMatrix("refractionMatrix",h.getReflectionTextureMatrix());var f=1;h.isCube||h.depth&&(f=h.depth),this._uniformBuffer.updateFloat4("vRefractionInfos",h.level,this._indexOfRefraction,f,this._invertRefractionY?-1:1),this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos",h.getSize().width,h.lodGenerationScale,h.lodGenerationOffset)}}this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),o.METALLICWORKFLOW?(e.PBRMaterial._scaledReflectivity.r=void 0===this._metallic||null===this._metallic?1:this._metallic,e.PBRMaterial._scaledReflectivity.g=void 0===this._roughness||null===this._roughness?1:this._roughness,this._uniformBuffer.updateColor4("vReflectivityColor",e.PBRMaterial._scaledReflectivity,0)):this._uniformBuffer.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface),this._uniformBuffer.updateColor3("vEmissiveColor",this._emissiveColor),this._uniformBuffer.updateColor3("vReflectionColor",this._reflectionColor),this._uniformBuffer.updateColor4("vAlbedoColor",this._albedoColor,this.alpha*i.visibility),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity,this._lightingInfos.w=this._specularIntensity,this._uniformBuffer.updateVector4("vLightingIntensity",this._lightingInfos)}n.texturesEnabled&&(this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&e.StandardMaterial.AmbientTextureEnabled&&this._uniformBuffer.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&e.StandardMaterial.OpacityTextureEnabled&&this._uniformBuffer.setTexture("opacitySampler",this._opacityTexture),l&&e.StandardMaterial.ReflectionTextureEnabled&&(o.LODBASEDMICROSFURACE?this._uniformBuffer.setTexture("reflectionSampler",l):(this._uniformBuffer.setTexture("reflectionSampler",l._lodTextureMid||l),this._uniformBuffer.setTexture("reflectionSamplerLow",l._lodTextureLow||l),this._uniformBuffer.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l))),o.ENVIRONMENTBRDF&&this._uniformBuffer.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),h&&e.StandardMaterial.RefractionTextureEnabled&&(o.LODBASEDMICROSFURACE?this._uniformBuffer.setTexture("refractionSampler",h):(this._uniformBuffer.setTexture("refractionSampler",h._lodTextureMid||h),this._uniformBuffer.setTexture("refractionSamplerLow",h._lodTextureLow||h),this._uniformBuffer.setTexture("refractionSamplerHigh",h._lodTextureHigh||h))),this._emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled&&this._uniformBuffer.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled&&this._uniformBuffer.setTexture("lightmapSampler",this._lightmapTexture),e.StandardMaterial.SpecularTextureEnabled&&(this._metallicTexture?this._uniformBuffer.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&this._uniformBuffer.setTexture("reflectivitySampler",this._reflectivityTexture),this._microSurfaceTexture&&this._uniformBuffer.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&n.getEngine().getCaps().standardDerivatives&&e.StandardMaterial.BumpTextureEnabled&&!this._disableBumpMap&&this._uniformBuffer.setTexture("bumpSampler",this._bumpTexture)),e.MaterialHelper.BindClipPlane(this._activeEffect,n),n.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor);var d=n._forcedViewPosition?n._forcedViewPosition:n._mirroredCameraPosition?n._mirroredCameraPosition:n.activeCamera.globalPosition,p=n.useRightHandedSystem===(null!=n._mirroredCameraPosition);s.setFloat4("vEyePosition",d.x,d.y,d.z,p?-1:1),s.setColor3("vAmbientColor",this._globalAmbientColor)}!a&&this.isFrozen||(n.lightsEnabled&&!this._disableLighting&&e.MaterialHelper.BindLights(n,i,this._activeEffect,o,this._maxSimultaneousLights,this._usePhysicalLightFalloff),(n.fogEnabled&&i.applyFog&&n.fogMode!==e.Scene.FOGMODE_NONE||l)&&this.bindView(s),e.MaterialHelper.BindFogParameters(n,i,this._activeEffect),o.NUM_MORPH_INFLUENCERS&&e.MaterialHelper.BindMorphTargetParameters(i,this._activeEffect),this._imageProcessingConfiguration.bind(this._activeEffect),e.MaterialHelper.BindLogDepth(o,this._activeEffect,n)),this._uniformBuffer.update(),this._afterBind(i,this._activeEffect)}}},r.prototype.getAnimatables=function(){var e=[];return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e},r.prototype._getReflectionTexture=function(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture},r.prototype._getRefractionTexture=function(){return this._refractionTexture?this._refractionTexture:this._linkRefractionWithTransparency?this.getScene().environmentTexture:null},r.prototype.dispose=function(e,t){t&&(this._albedoTexture&&this._albedoTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._environmentBRDFTexture&&this.getScene()._environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._metallicTexture&&this._metallicTexture.dispose(),this._reflectivityTexture&&this._reflectivityTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),i.prototype.dispose.call(this,e,t)},r._scaledReflectivity=new e.Color3,n([e.serializeAsImageProcessingConfiguration()],r.prototype,"_imageProcessingConfiguration",void 0),n([e.serialize()],r.prototype,"useLogarithmicDepth",null),n([e.serialize()],r.prototype,"transparencyMode",null),r})(e.PushMaterial);e.PBRBaseMaterial=i})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r){var n=t.call(this,i,r)||this;return n.maxSimultaneousLights=4,n.disableLighting=!1,n.invertNormalMapX=!1,n.invertNormalMapY=!1,n.emissiveColor=new e.Color3(0,0,0),n.occlusionStrength=1,n.useLightmapAsShadowmap=!1,n._useAlphaFromAlbedoTexture=!0,n._useAmbientInGrayScale=!0,n}return o(i,t),Object.defineProperty(i.prototype,"doubleSided",{get:function(){return this._twoSidedLighting},set:function(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())},enumerable:!0,configurable:!0}),i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this.environmentTexture&&e.push(this.environmentTexture),this.normalTexture&&e.push(this.normalTexture),this.emissiveTexture&&e.push(this.emissiveTexture),this.occlusionTexture&&e.push(this.occlusionTexture),this.lightmapTexture&&e.push(this.lightmapTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this.lightmapTexture===e},i.prototype.getClassName=function(){return"PBRBaseSimpleMaterial"},n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"maxSimultaneousLights",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"disableLighting",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],i.prototype,"environmentTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapX",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapY",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],i.prototype,"normalTexture",void 0), -n([e.serializeAsColor3("emissive"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveColor",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],i.prototype,"occlusionStrength",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],i.prototype,"occlusionTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],i.prototype,"alphaCutOff",void 0),n([e.serialize()],i.prototype,"doubleSided",null),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty",null)],i.prototype,"lightmapTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLightmapAsShadowmap",void 0),i})(e.PBRBaseMaterial);e.PBRBaseSimpleMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r){var n=t.call(this,i,r)||this;return n.directIntensity=1,n.emissiveIntensity=1,n.environmentIntensity=1,n.specularIntensity=1,n.disableBumpMap=!1,n.ambientTextureStrength=1,n.ambientColor=new e.Color3(0,0,0),n.albedoColor=new e.Color3(1,1,1),n.reflectivityColor=new e.Color3(1,1,1),n.reflectionColor=new e.Color3(1,1,1),n.emissiveColor=new e.Color3(0,0,0),n.microSurface=1,n.indexOfRefraction=.66,n.invertRefractionY=!1,n.linkRefractionWithTransparency=!1,n.useLightmapAsShadowmap=!1,n.useAlphaFromAlbedoTexture=!1,n.forceAlphaTest=!1,n.alphaCutOff=.4,n.useSpecularOverAlpha=!0,n.useMicroSurfaceFromReflectivityMapAlpha=!1,n.useRoughnessFromMetallicTextureAlpha=!0,n.useRoughnessFromMetallicTextureGreen=!1,n.useMetallnessFromMetallicTextureBlue=!1,n.useAmbientOcclusionFromMetallicTextureRed=!1,n.useAmbientInGrayScale=!1,n.useAutoMicroSurfaceFromReflectivityMap=!1,n.usePhysicalLightFalloff=!0,n.useRadianceOverAlpha=!0,n.useObjectSpaceNormalMap=!1,n.useParallax=!1,n.useParallaxOcclusion=!1,n.parallaxScaleBias=.05,n.disableLighting=!1,n.forceIrradianceInFragment=!1,n.maxSimultaneousLights=4,n.invertNormalMapX=!1,n.invertNormalMapY=!1,n.twoSidedLighting=!1,n.useAlphaFresnel=!1,n.useLinearAlphaFresnel=!1,n.environmentBRDFTexture=null,n.forceNormalForward=!1,n.enableSpecularAntiAliasing=!1,n.useHorizonOcclusion=!0,n.useRadianceOcclusion=!0,n.unlit=!1,n._environmentBRDFTexture=e.TextureTools.GetEnvironmentBRDFTexture(r),n}return o(i,t),Object.defineProperty(i,"PBRMATERIAL_OPAQUE",{get:function(){return this._PBRMATERIAL_OPAQUE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"PBRMATERIAL_ALPHATEST",{get:function(){return this._PBRMATERIAL_ALPHATEST},enumerable:!0,configurable:!0}),Object.defineProperty(i,"PBRMATERIAL_ALPHABLEND",{get:function(){return this._PBRMATERIAL_ALPHABLEND},enumerable:!0,configurable:!0}),Object.defineProperty(i,"PBRMATERIAL_ALPHATESTANDBLEND",{get:function(){return this._PBRMATERIAL_ALPHATESTANDBLEND},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurves",{get:function(){return this._imageProcessingConfiguration.colorCurves},set:function(e){this._imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"PBRMaterial"},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this._albedoTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._reflectivityTexture===e||(this._metallicTexture===e||(this._microSurfaceTexture===e||(this._bumpTexture===e||(this._lightmapTexture===e||this._refractionTexture===e)))))))))},i.prototype.clone=function(t){var r=this,n=e.SerializationHelper.Clone((function(){return new i(t,r.getScene())}),this);return n.id=t,n.name=t,n},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRMaterial",t},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,r)}),t,r,n)},i._PBRMATERIAL_OPAQUE=0,i._PBRMATERIAL_ALPHATEST=1,i._PBRMATERIAL_ALPHABLEND=2,i._PBRMATERIAL_ALPHATESTANDBLEND=3,n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"directIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"environmentIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"specularIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"disableBumpMap",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"albedoTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientTextureStrength",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"opacityTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectivityTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallicTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallic",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"roughness",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"microSurfaceTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"bumpTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty",null)],i.prototype,"lightmapTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"refractionTexture",void 0),n([e.serializeAsColor3("ambient"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientColor",void 0),n([e.serializeAsColor3("albedo"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"albedoColor",void 0),n([e.serializeAsColor3("reflectivity"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectivityColor",void 0),n([e.serializeAsColor3("reflection"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionColor",void 0),n([e.serializeAsColor3("emissive"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveColor",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"microSurface",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"indexOfRefraction",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertRefractionY",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"linkRefractionWithTransparency",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLightmapAsShadowmap",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"useAlphaFromAlbedoTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"forceAlphaTest",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"alphaCutOff",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useSpecularOverAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRoughnessFromMetallicTextureGreen",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useMetallnessFromMetallicTextureBlue",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAmbientInGrayScale",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"usePhysicalLightFalloff",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRadianceOverAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useObjectSpaceNormalMap",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useParallax",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useParallaxOcclusion",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"parallaxScaleBias",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"disableLighting",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"forceIrradianceInFragment",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"maxSimultaneousLights",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapX",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapY",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"twoSidedLighting",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAlphaFresnel",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLinearAlphaFresnel",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"environmentBRDFTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"forceNormalForward",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"enableSpecularAntiAliasing",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useHorizonOcclusion",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRadianceOcclusion",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsMiscDirty")],i.prototype,"unlit",void 0),i})(e.PBRBaseMaterial);e.PBRMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i){var r=t.call(this,e,i)||this;return r._useRoughnessFromMetallicTextureAlpha=!1,r._useRoughnessFromMetallicTextureGreen=!0,r._useMetallnessFromMetallicTextureBlue=!0,r.metallic=1,r.roughness=1,r}return o(i,t),i.prototype.getClassName=function(){return"PBRMetallicRoughnessMaterial"},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this.baseTexture&&e.push(this.baseTexture),this.metallicRoughnessTexture&&e.push(this.metallicRoughnessTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this.baseTexture===e||this.metallicRoughnessTexture===e)},i.prototype.clone=function(t){var r=this,n=e.SerializationHelper.Clone((function(){return new i(t,r.getScene())}),this);return n.id=t,n.name=t,n},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRMetallicRoughnessMaterial",t},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,r)}),t,r,n)},n([e.serializeAsColor3(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoColor")],i.prototype,"baseColor",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],i.prototype,"baseTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallic",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"roughness",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],i.prototype,"metallicRoughnessTexture",void 0),i})(e.PBRBaseSimpleMaterial);e.PBRMetallicRoughnessMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i){var r=t.call(this,e,i)||this;return r._useMicroSurfaceFromReflectivityMapAlpha=!0,r}return o(i,t),i.prototype.getClassName=function(){return"PBRSpecularGlossinessMaterial"},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this.diffuseTexture&&e.push(this.diffuseTexture),this.specularGlossinessTexture&&e.push(this.specularGlossinessTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this.diffuseTexture===e||this.specularGlossinessTexture===e)},i.prototype.clone=function(t){var r=this,n=e.SerializationHelper.Clone((function(){return new i(t,r.getScene())}),this);return n.id=t,n.name=t,n},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRSpecularGlossinessMaterial",t},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,r)}),t,r,n)},n([e.serializeAsColor3("diffuse"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoColor")],i.prototype,"diffuseColor",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],i.prototype,"diffuseTexture",void 0),n([e.serializeAsColor3("specular"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],i.prototype,"specularColor",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_microSurface")],i.prototype,"glossiness",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],i.prototype,"specularGlossinessTexture",void 0),i})(e.PBRBaseSimpleMaterial);e.PBRSpecularGlossinessMaterial=t})(r||(r={}));var r;!(function(e){e.CameraInputTypes={};var t=(function(){function t(e){this.attached={},this.camera=e,this.checkInputs=function(){}}return t.prototype.add=function(t){var i=t.getSimpleName();if(this.attached[i])return void e.Tools.Warn("camera input of type "+i+" already exists on camera");this.attached[i]=t,t.camera=this.camera,t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t))),this.attachedElement&&t.attachControl(this.attachedElement)},t.prototype.remove=function(e){for(var t in this.attached){var i=this.attached[t];i===e&&(i.detachControl(this.attachedElement),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}},t.prototype.removeByType=function(e){for(var t in this.attached){var i=this.attached[t];i.getClassName()===e&&(i.detachControl(this.attachedElement),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}},t.prototype._addCheckInputs=function(e){var t=this.checkInputs;return function(){t(),e()}},t.prototype.attachInput=function(e){this.attachedElement&&e.attachControl(this.attachedElement,this.noPreventDefault)},t.prototype.attachElement=function(t,i){if(void 0===i&&(i=!1),!this.attachedElement){i=!e.Camera.ForceAttachControlToAlwaysPreventDefault&&i,this.attachedElement=t,this.noPreventDefault=i;for(var r in this.attached)this.attached[r].attachControl(t,i)}},t.prototype.detachElement=function(e,t){if(void 0===t&&(t=!1),this.attachedElement===e){for(var i in this.attached)this.attached[i].detachControl(e),t&&(this.attached[i].camera=null);this.attachedElement=null}},t.prototype.rebuildInputCheck=function(){this.checkInputs=function(){};for(var e in this.attached){var t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}},t.prototype.clear=function(){this.attachedElement&&this.detachElement(this.attachedElement,!0),this.attached={},this.attachedElement=null,this.checkInputs=function(){}},t.prototype.serialize=function(t){var i={};for(var r in this.attached){var n=this.attached[r],o=e.SerializationHelper.Serialize(n);i[n.getClassName()]=o}t.inputsmgr=i},t.prototype.parse=function(t){var i=t.inputsmgr;if(i){this.clear();for(var r in i){var n=e.CameraInputTypes[r];if(n){var o=i[r],s=e.SerializationHelper.Parse((function(){return new n}),o,null);this.add(s)}}}else for(var r in this.attached){var n=e.CameraInputTypes[this.attached[r].getClassName()];if(n){var s=e.SerializationHelper.Parse((function(){return new n}),t,null);this.remove(this.attached[r]),this.add(s)}}},t})();e.CameraInputsManager=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o){void 0===o&&(o=!0);var s=t.call(this,i,r,n,o)||this;return s.cameraDirection=new e.Vector3(0,0,0),s.cameraRotation=new e.Vector2(0,0),s.rotation=new e.Vector3(0,0,0),s.speed=2,s.noRotationConstraint=!1,s.lockedTarget=null,s._currentTarget=e.Vector3.Zero(),s._viewMatrix=e.Matrix.Zero(),s._camMatrix=e.Matrix.Zero(),s._cameraTransformMatrix=e.Matrix.Zero(),s._cameraRotationMatrix=e.Matrix.Zero(),s._referencePoint=new e.Vector3(0,0,1),s._currentUpVector=new e.Vector3(0,1,0),s._transformedReferencePoint=e.Vector3.Zero(),s._globalCurrentTarget=e.Vector3.Zero(),s._globalCurrentUpVector=e.Vector3.Zero(),s}return o(i,t),i.prototype.getFrontPosition=function(e){this.getWorldMatrix();var t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)},i.prototype._getLockedTargetPosition=function(){return this.lockedTarget?(this.lockedTarget.absolutePosition&&this.lockedTarget.computeWorldMatrix(),this.lockedTarget.absolutePosition||this.lockedTarget):null},i.prototype.storeState=function(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),t.prototype.storeState.call(this)},i.prototype._restoreStateValues=function(){return!!t.prototype._restoreStateValues.call(this)&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.lockedTarget=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new e.Quaternion(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this);var i=this._getLockedTargetPosition();i?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(i):this._cache.lockedTarget=i.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)},i.prototype._isSynchronizedViewMatrix=function(){if(!t.prototype._isSynchronizedViewMatrix.call(this))return!1;var e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))},i.prototype._computeLocalCameraSpeed=function(){var e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))},i.prototype.setTarget=function(t){this.upVector.normalize(),e.Matrix.LookAtLHToRef(this.position,t,this.upVector,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);var i=t.subtract(this.position);i.x>=0?this.rotation.y=-Math.atan(i.z/i.x)+Math.PI/2:this.rotation.y=-Math.atan(i.z/i.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)},i.prototype.getTarget=function(){return this._currentTarget},i.prototype._decideIfNeedsToMove=function(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(e.Tmp.Matrix[0]),e.Vector3.TransformNormalToRef(this.cameraDirection,e.Tmp.Matrix[0],e.Tmp.Vector3[0]),void this.position.addInPlace(e.Tmp.Vector3[0]);this.position.addInPlace(this.cameraDirection)},i.prototype._checkInputs=function(){var i=this._decideIfNeedsToMove(),r=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(i&&this._updatePosition(),r){if(this.rotation.x+=this.cameraRotation.x,this.rotation.y+=this.cameraRotation.y,this.rotationQuaternion){this.rotation.lengthSquared()&&e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}if(!this.noRotationConstraint){var n=Math.PI/2*.95;this.rotation.x>n&&(this.rotation.x=n),this.rotation.x<-n&&(this.rotation.x=-n)}}i&&(Math.abs(this.cameraDirection.x)=0&&r._keys.splice(o,1),i||n.preventDefault()}})))},t.prototype.detachControl=function(e){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys=[]},t.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var t=this.camera,i=0;ie.Engine.CollisionsEpsilon&&(s.position.addInPlace(s._diffPosition),s.onCollide&&r&&s.onCollide(r))})(i)},s.inputs=new e.FreeCameraInputsManager(s),s.inputs.addKeyboard().addMouse(),s}return o(i,t),Object.defineProperty(i.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;return e?e.angularSensibility:0},set:function(e){var t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),i.prototype.attachControl=function(e,t){this.inputs.attachElement(e,t)},i.prototype.detachControl=function(t){this.inputs.detachElement(t),this.cameraDirection=new e.Vector3(0,0,0),this.cameraRotation=new e.Vector2(0,0)},Object.defineProperty(i.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),i.prototype._collideWithWorld=function(t){var i;i=this.parent?e.Vector3.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,i.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset),this._collider||(this._collider=new e.Collider),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;var r=t;this.applyGravity&&(r=t.add(this.getScene().gravity)),this.getScene().collisionCoordinator.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},i.prototype._checkInputs=function(){this._localDirection||(this._localDirection=e.Vector3.Zero(),this._transformedDirection=e.Vector3.Zero()),this.inputs.checkInputs(),t.prototype._checkInputs.call(this)},i.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):t.prototype._updatePosition.call(this)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getClassName=function(){return"FreeCamera"},n([e.serializeAsVector3()],i.prototype,"ellipsoid",void 0),n([e.serializeAsVector3()],i.prototype,"ellipsoidOffset",void 0),n([e.serialize()],i.prototype,"checkCollisions",void 0),n([e.serialize()],i.prototype,"applyGravity",void 0),i})(e.TargetCamera);e.FreeCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._keys=new Array,this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0}return t.prototype.attachControl=function(t,i){var r=this;this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((function(){r._keys=[]})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((function(t){var n=t.event;if(t.type===e.KeyboardEventTypes.KEYDOWN){if(r._ctrlPressed=n.ctrlKey,r._altPressed=n.altKey,-1!==r.keysUp.indexOf(n.keyCode)||-1!==r.keysDown.indexOf(n.keyCode)||-1!==r.keysLeft.indexOf(n.keyCode)||-1!==r.keysRight.indexOf(n.keyCode)||-1!==r.keysReset.indexOf(n.keyCode)){var o=r._keys.indexOf(n.keyCode);-1===o&&r._keys.push(n.keyCode),n.preventDefault&&(i||n.preventDefault())}}else if(-1!==r.keysUp.indexOf(n.keyCode)||-1!==r.keysDown.indexOf(n.keyCode)||-1!==r.keysLeft.indexOf(n.keyCode)||-1!==r.keysRight.indexOf(n.keyCode)||-1!==r.keysReset.indexOf(n.keyCode)){var o=r._keys.indexOf(n.keyCode);o>=0&&r._keys.splice(o,1),n.preventDefault&&(i||n.preventDefault())}})))},t.prototype.detachControl=function(e){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys=[]},t.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var e=this.camera,t=0;t0?a/(1+r.wheelDeltaPercentage):a*(1+r.wheelDeltaPercentage)}else s=o.wheelDelta/(40*r.wheelPrecision);else o.detail&&(s=-o.detail/r.wheelPrecision);s&&(r.camera.inertialRadiusOffset+=s),o.preventDefault&&(i||o.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,e.PointerEventTypes.POINTERWHEEL)},t.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},t.prototype.getClassName=function(){return"ArcRotateCameraMouseWheelInput"},t.prototype.getSimpleName=function(){return"mousewheel"},n([e.serialize()],t.prototype,"wheelPrecision",void 0),n([e.serialize()],t.prototype,"wheelDeltaPercentage",void 0),t})();e.ArcRotateCameraMouseWheelInput=t,e.CameraInputTypes.ArcRotateCameraMouseWheelInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this._isPanClick=!1,this.pinchInwards=!0}return t.prototype.attachControl=function(t,i){var r,n=this,o=this.camera.getEngine(),s=null,a=null,l=0,h=0,c=0,u={x:0,y:0,isPaning:!1,isPinching:!1};this._pointerInput=function(f,d){var p=f.event,m="touch"===f.event.pointerType;if(!o.isInVRExclusivePointerMode&&(f.type===e.PointerEventTypes.POINTERMOVE||-1!==n.buttons.indexOf(p.button))){var _=p.srcElement||p.target;if(f.type===e.PointerEventTypes.POINTERDOWN&&_){try{_.setPointerCapture(p.pointerId)}catch(e){}n._isPanClick=p.button===n.camera._panningMouseButton,r={x:p.clientX,y:p.clientY,pointerId:p.pointerId,type:p.pointerType},null===s?s=r:null===a&&(a=r),i||(p.preventDefault(),t.focus())}else if(f.type===e.PointerEventTypes.POINTERDOUBLETAP)n.camera.restoreState();else if(f.type===e.PointerEventTypes.POINTERUP&&_){try{_.releasePointerCapture(p.pointerId)}catch(e){}r=null,l=0,u.isPaning=!1,u.isPinching=!1,c=0,h=0,m||(a=null),o._badOS?s=a=null:a&&s&&s.pointerId==p.pointerId?(s=a,a=null,r={x:s.x,y:s.y,pointerId:s.pointerId,type:p.pointerType}):s&&a&&a.pointerId==p.pointerId?(a=null,r={x:s.x,y:s.y,pointerId:s.pointerId,type:p.pointerType}):s=a=null,i||p.preventDefault()}else if(f.type===e.PointerEventTypes.POINTERMOVE)if(i||p.preventDefault(),s&&null===a&&r){if(0!==n.panningSensibility&&(p.ctrlKey&&n.camera._useCtrlForPanning||n._isPanClick))n.camera.inertialPanningX+=-(p.clientX-r.x)/n.panningSensibility,n.camera.inertialPanningY+=(p.clientY-r.y)/n.panningSensibility;else{var g=p.clientX-r.x,v=p.clientY-r.y;n.camera.inertialAlphaOffset-=g/n.angularSensibilityX,n.camera.inertialBetaOffset-=v/n.angularSensibilityY}r.x=p.clientX,r.y=p.clientY}else if(s&&a){var y=s.pointerId===p.pointerId?s:a;y.x=p.clientX,y.y=p.clientY;var b=n.pinchInwards?1:-1,x=s.x-a.x,T=s.y-a.y,E=x*x+T*T,P=Math.sqrt(E);if(0===l)return h=P,l=E,u.x=(s.x+a.x)/2,void(u.y=(s.y+a.y)/2);if(n.multiTouchPanAndZoom){if(n.pinchDeltaPercentage?n.camera.inertialRadiusOffset+=.001*(E-l)*n.camera.radius*n.pinchDeltaPercentage:n.camera.inertialRadiusOffset+=(E-l)/(n.pinchPrecision*((n.angularSensibilityX+n.angularSensibilityY)/2)*b),0!==n.panningSensibility){var A=(s.x+a.x)/2,M=(s.y+a.y)/2,S=A-u.x,R=M-u.y;u.x=A,u.y=M,n.camera.inertialPanningX+=-S/n.panningSensibility,n.camera.inertialPanningY+=R/n.panningSensibility}}else{if(c++,u.isPinching||c<20&&Math.abs(P-h)>n.camera.pinchToPanMaxDistance)n.pinchDeltaPercentage?n.camera.inertialRadiusOffset+=.001*(E-l)*n.camera.radius*n.pinchDeltaPercentage:n.camera.inertialRadiusOffset+=(E-l)/(n.pinchPrecision*((n.angularSensibilityX+n.angularSensibilityY)/2)*b),u.isPaning=!1,u.isPinching=!0;else if(r&&r.pointerId===y.pointerId&&0!==n.panningSensibility&&n.multiTouchPanning){if(!u.isPaning)return u.isPaning=!0,u.isPinching=!1,u.x=y.x,void(u.y=y.y);n.camera.inertialPanningX+=-(y.x-u.x)/n.panningSensibility,n.camera.inertialPanningY+=(y.y-u.y)/n.panningSensibility}r&&r.pointerId===p.pointerId&&(u.x=y.x,u.y=y.y)}l=E}}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE|e.PointerEventTypes._POINTERDOUBLETAP),this._onContextMenu=function(e){e.preventDefault()},this.camera._useCtrlForPanning||t.addEventListener("contextmenu",this._onContextMenu,!1),this._onLostFocus=function(){s=a=null,l=0,u.isPaning=!1,u.isPinching=!1,c=0,r=null,h=0},this._onMouseMove=function(e){if(o.isPointerLock){var t=e.movementX||e.mozMovementX||e.webkitMovementX||e.msMovementX||0,r=e.movementY||e.mozMovementY||e.webkitMovementY||e.msMovementY||0;n.camera.inertialAlphaOffset-=t/n.angularSensibilityX,n.camera.inertialBetaOffset-=r/n.angularSensibilityY,i||e.preventDefault()}},this._onGestureStart=function(e){void 0!==window.MSGesture&&(n._MSGestureHandler||(n._MSGestureHandler=new MSGesture,n._MSGestureHandler.target=t),n._MSGestureHandler.addPointer(e.pointerId))},this._onGesture=function(e){n.camera.radius*=e.scale,e.preventDefault&&(i||(e.stopPropagation(),e.preventDefault()))},t.addEventListener("mousemove",this._onMouseMove,!1),t.addEventListener("MSPointerDown",this._onGestureStart,!1),t.addEventListener("MSGestureChange",this._onGesture,!1),e.Tools.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},t.prototype.detachControl=function(t){this._onLostFocus&&e.Tools.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]),t&&this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._onContextMenu&&t.removeEventListener("contextmenu",this._onContextMenu),this._onMouseMove&&t.removeEventListener("mousemove",this._onMouseMove),this._onGestureStart&&t.removeEventListener("MSPointerDown",this._onGestureStart),this._onGesture&&t.removeEventListener("MSGestureChange",this._onGesture),this._isPanClick=!1,this.pinchInwards=!0,this._onMouseMove=null,this._onGestureStart=null,this._onGesture=null,this._MSGestureHandler=null,this._onLostFocus=null,this._onContextMenu=null)},t.prototype.getClassName=function(){return"ArcRotateCameraPointersInput"},t.prototype.getSimpleName=function(){return"pointers"},n([e.serialize()],t.prototype,"buttons",void 0),n([e.serialize()],t.prototype,"angularSensibilityX",void 0),n([e.serialize()],t.prototype,"angularSensibilityY",void 0),n([e.serialize()],t.prototype,"pinchPrecision",void 0),n([e.serialize()],t.prototype,"pinchDeltaPercentage",void 0),n([e.serialize()],t.prototype,"panningSensibility",void 0),n([e.serialize()],t.prototype,"multiTouchPanning",void 0),n([e.serialize()],t.prototype,"multiTouchPanAndZoom",void 0),t})();e.ArcRotateCameraPointersInput=t,e.CameraInputTypes.ArcRotateCameraPointersInput=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e){return t.call(this,e)||this}return o(i,t),i.prototype.addMouseWheel=function(){return this.add(new e.ArcRotateCameraMouseWheelInput),this},i.prototype.addPointers=function(){return this.add(new e.ArcRotateCameraPointersInput),this},i.prototype.addKeyboard=function(){return this.add(new e.ArcRotateCameraKeyboardMoveInput),this},i.prototype.addVRDeviceOrientation=function(){return this.add(new e.ArcRotateCameraVRDeviceOrientationInput),this},i})(e.CameraInputsManager);e.ArcRotateCameraInputsManager=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("ArcRotateCamera",(function(i,r){return function(){return new t(i,0,0,1,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s,a,l){void 0===l&&(l=!0);var h=t.call(this,i,e.Vector3.Zero(),a,l)||this;return h.inertialAlphaOffset=0,h.inertialBetaOffset=0,h.inertialRadiusOffset=0,h.lowerAlphaLimit=null,h.upperAlphaLimit=null,h.lowerBetaLimit=.01,h.upperBetaLimit=Math.PI,h.lowerRadiusLimit=null,h.upperRadiusLimit=null,h.inertialPanningX=0,h.inertialPanningY=0,h.pinchToPanMaxDistance=20,h.panningDistanceLimit=null,h.panningOriginTarget=e.Vector3.Zero(),h.panningInertia=.9,h.zoomOnFactor=1,h.targetScreenOffset=e.Vector2.Zero(),h.allowUpsideDown=!0,h._viewMatrix=new e.Matrix,h.panningAxis=new e.Vector3(1,1,0),h.onMeshTargetChangedObservable=new e.Observable,h.checkCollisions=!1,h.collisionRadius=new e.Vector3(.5,.5,.5),h._previousPosition=e.Vector3.Zero(),h._collisionVelocity=e.Vector3.Zero(),h._newPosition=e.Vector3.Zero(),h._computationVector=e.Vector3.Zero(),h._onCollisionPositionChange=function(e,t,i){void 0===i&&(i=null),h.getScene().workerCollisions&&h.checkCollisions&&t.multiplyInPlace(h._collider._radius),i?(h.setPosition(t),h.onCollide&&h.onCollide(i)):h._previousPosition.copyFrom(h.position);var r=Math.cos(h.alpha),n=Math.sin(h.alpha),o=Math.cos(h.beta),s=Math.sin(h.beta);0===s&&(s=1e-4);var a=h._getTargetPosition();h._computationVector.copyFromFloats(h.radius*r*s,h.radius*o,h.radius*n*s),a.addToRef(h._computationVector,h._newPosition),h.position.copyFrom(h._newPosition);var l=h.upVector;h.allowUpsideDown&&h.beta<0&&(l=l.clone(),l=l.negate()),h._computeViewMatrix(h.position,a,l),h._viewMatrix.m[12]+=h.targetScreenOffset.x,h._viewMatrix.m[13]+=h.targetScreenOffset.y,h._collisionTriggered=!1},h._target=e.Vector3.Zero(),s&&h.setTarget(s),h.alpha=r,h.beta=n,h.radius=o,h.getViewMatrix(),h.inputs=new e.ArcRotateCameraInputsManager(h),h.inputs.addKeyboard().addMouseWheel().addPointers(),h}return o(i,t),Object.defineProperty(i.prototype,"target",{get:function(){return this._target},set:function(e){this.setTarget(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"angularSensibilityX",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"angularSensibilityY",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pinchPrecision",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchPrecision:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pinchDeltaPercentage",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"panningSensibility",{get:function(){var e=this.inputs.attached.pointers;return e?e.panningSensibility:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wheelPrecision",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wheelDeltaPercentage",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"bouncingBehavior",{get:function(){return this._bouncingBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useBouncingBehavior",{get:function(){return null!=this._bouncingBehavior},set:function(t){t!==this.useBouncingBehavior&&(t?(this._bouncingBehavior=new e.BouncingBehavior,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"framingBehavior",{get:function(){return this._framingBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useFramingBehavior",{get:function(){return null!=this._framingBehavior},set:function(t){t!==this.useFramingBehavior&&(t?(this._framingBehavior=new e.FramingBehavior,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"autoRotationBehavior",{get:function(){return this._autoRotationBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useAutoRotationBehavior",{get:function(){return null!=this._autoRotationBehavior},set:function(t){t!==this.useAutoRotationBehavior&&(t?(this._autoRotationBehavior=new e.AutoRotationBehavior,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))},enumerable:!0,configurable:!0}),i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache._target=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=e.Vector2.Zero()},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)},i.prototype._getTargetPosition=function(){if(this._targetHost&&this._targetHost.getAbsolutePosition){var e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}var t=this._getLockedTargetPosition();return t||this._target},i.prototype.storeState=function(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),t.prototype.storeState.call(this)},i.prototype._restoreStateValues=function(){return!!t.prototype._restoreStateValues.call(this)&&(this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.setTarget(this._storedTarget.clone()),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)},i.prototype._isSynchronizedViewMatrix=function(){return!!t.prototype._isSynchronizedViewMatrix.call(this)&&(this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset))},i.prototype.attachControl=function(e,t,i,r){var n=this;void 0===i&&(i=!0),void 0===r&&(r=2),this._useCtrlForPanning=i,this._panningMouseButton=r,this.inputs.attachElement(e,t),this._reset=function(){n.inertialAlphaOffset=0,n.inertialBetaOffset=0,n.inertialRadiusOffset=0,n.inertialPanningX=0,n.inertialPanningY=0}},i.prototype.detachControl=function(e){this.inputs.detachElement(e),this._reset&&this._reset()},i.prototype._checkInputs=function(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){var i=this.inertialAlphaOffset;this.beta<=0&&(i*=-1),this.getScene().useRightHandedSystem&&(i*=-1),this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(i*=-1),this.alpha+=i,this.beta+=this.inertialBetaOffset,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit)},i.prototype.rebuildAnglesAndRadius=function(){this.position.subtractToRef(this._getTargetPosition(),this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4),this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha),this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()},i.prototype.setPosition=function(e){this.position.equals(e)||(this.position.copyFrom(e),this.rebuildAnglesAndRadius())},i.prototype.setTarget=function(e,t,i){if(void 0===t&&(t=!1),void 0===i&&(i=!1),e.getBoundingInfo)this._targetBoundingCenter=t?e.getBoundingInfo().boundingBox.centerWorld.clone():null,this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{var r=e,n=this._getTargetPosition();if(n&&!i&&n.equals(r))return;this._targetHost=null,this._target=r,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}this.rebuildAnglesAndRadius()},i.prototype._getViewMatrix=function(){var t=Math.cos(this.alpha),i=Math.sin(this.alpha),r=Math.cos(this.beta),n=Math.sin(this.beta);0===n&&(n=1e-4);var o=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*t*n,this.radius*r,this.radius*i*n),o.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions)this._collider||(this._collider=new e.Collider),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this.position,this._collisionVelocity),this._collisionTriggered=!0,this.getScene().collisionCoordinator.getNewPosition(this.position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId);else{this.position.copyFrom(this._newPosition);var s=this.upVector;this.allowUpsideDown&&n<0&&(s=s.clone(),s=s.negate()),this._computeViewMatrix(this.position,o,s),this._viewMatrix.m[12]+=this.targetScreenOffset.x,this._viewMatrix.m[13]+=this.targetScreenOffset.y}return this._currentTarget=o,this._viewMatrix},i.prototype.zoomOn=function(t,i){void 0===i&&(i=!1),t=t||this.getScene().meshes;var r=e.Mesh.MinMax(t),n=e.Vector3.Distance(r.min,r.max);this.radius=n*this.zoomOnFactor,this.focusOn({min:r.min,max:r.max,distance:n},i)},i.prototype.focusOn=function(t,i){void 0===i&&(i=!1);var r,n;if(void 0===t.min){var o=t||this.getScene().meshes;r=e.Mesh.MinMax(o),n=e.Vector3.Distance(r.min,r.max)}else{var s=t;r=s,n=s.distance}this._target=e.Mesh.Center(r),i||(this.maxZ=2*n)},i.prototype.createRigCamera=function(t,r){var n=0;switch(this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:n=this._cameraRigParams.stereoHalfAngle*(0===r?1:-1);break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:n=this._cameraRigParams.stereoHalfAngle*(0===r?-1:1)}var o=new i(t,this.alpha+n,this.beta,this.radius,this._target,this.getScene());return o._cameraRigParams={},o},i.prototype._updateRigCameras=function(){ -var i=this._rigCameras[0],r=this._rigCameras[1];switch(i.beta=r.beta=this.beta,i.radius=r.radius=this.radius,this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:i.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}t.prototype._updateRigCameras.call(this)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getClassName=function(){return"ArcRotateCamera"},n([e.serialize()],i.prototype,"alpha",void 0),n([e.serialize()],i.prototype,"beta",void 0),n([e.serialize()],i.prototype,"radius",void 0),n([e.serializeAsVector3("target")],i.prototype,"_target",void 0),n([e.serialize()],i.prototype,"inertialAlphaOffset",void 0),n([e.serialize()],i.prototype,"inertialBetaOffset",void 0),n([e.serialize()],i.prototype,"inertialRadiusOffset",void 0),n([e.serialize()],i.prototype,"lowerAlphaLimit",void 0),n([e.serialize()],i.prototype,"upperAlphaLimit",void 0),n([e.serialize()],i.prototype,"lowerBetaLimit",void 0),n([e.serialize()],i.prototype,"upperBetaLimit",void 0),n([e.serialize()],i.prototype,"lowerRadiusLimit",void 0),n([e.serialize()],i.prototype,"upperRadiusLimit",void 0),n([e.serialize()],i.prototype,"inertialPanningX",void 0),n([e.serialize()],i.prototype,"inertialPanningY",void 0),n([e.serialize()],i.prototype,"pinchToPanMaxDistance",void 0),n([e.serialize()],i.prototype,"panningDistanceLimit",void 0),n([e.serializeAsVector3()],i.prototype,"panningOriginTarget",void 0),n([e.serialize()],i.prototype,"panningInertia",void 0),n([e.serialize()],i.prototype,"zoomOnFactor",void 0),n([e.serialize()],i.prototype,"allowUpsideDown",void 0),i})(e.TargetCamera);e.ArcRotateCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_3",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n){var o=t.call(this,i,n)||this;return o.groundColor=new e.Color3(0,0,0),o.direction=r||e.Vector3.Up(),o}return o(i,t),i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.getClassName=function(){return"HemisphericLight"},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(e.Vector3.Zero())),this.direction},i.prototype.getShadowGenerator=function(){return null},i.prototype.transferToEffect=function(t,i){var r=e.Vector3.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",r.x,r.y,r.z,0,i),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),i),this},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),this._worldMatrix},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_HEMISPHERICLIGHT},i.prototype.prepareLightSpecificDefines=function(e,t){e["HEMILIGHT"+t]=!0},n([e.serializeAsColor3()],i.prototype,"groundColor",void 0),n([e.serializeAsVector3()],i.prototype,"direction",void 0),i})(e.Light);e.HemisphericLight=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(){var e=null!==t&&t.apply(this,arguments)||this;return e._needProjectionMatrixCompute=!0,e}return o(i,t),i.prototype._setPosition=function(e){this._position=e},Object.defineProperty(i.prototype,"position",{get:function(){return this._position},set:function(e){this._setPosition(e)},enumerable:!0,configurable:!0}),i.prototype._setDirection=function(e){this._direction=e},Object.defineProperty(i.prototype,"direction",{get:function(){return this._direction},set:function(e){this._setDirection(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowMinZ",{get:function(){return this._shadowMinZ},set:function(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowMaxZ",{get:function(){return this._shadowMaxZ},set:function(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),i.prototype.computeTransformedInformation=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=e.Vector3.Zero()),e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=e.Vector3.Zero()),e.Vector3.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0)},i.prototype.getDepthScale=function(){return 50},i.prototype.getShadowDirection=function(e){return this.transformedDirection?this.transformedDirection:this.direction},i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(this.position)),this.direction},i.prototype.getRotation=function(){this.direction.normalize();var t=e.Vector3.Cross(this.direction,e.Axis.Y),i=e.Vector3.Cross(t,this.direction);return e.Vector3.RotationFromAxis(t,i,this.direction)},i.prototype.needCube=function(){return!1},i.prototype.needProjectionMatrixCompute=function(){return this._needProjectionMatrixCompute},i.prototype.forceProjectionMatrixCompute=function(){this._needProjectionMatrixCompute=!0},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this._worldMatrix},i.prototype.getDepthMinZ=function(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ},i.prototype.getDepthMaxZ=function(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ},i.prototype.setShadowProjectionMatrix=function(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this},n([e.serializeAsVector3()],i.prototype,"position",null),n([e.serializeAsVector3()],i.prototype,"direction",null),n([e.serialize()],i.prototype,"shadowMinZ",null),n([e.serialize()],i.prototype,"shadowMaxZ",null),i})(e.Light);e.ShadowLight=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_0",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(e,i,r){var n=t.call(this,e,r)||this;return n._shadowAngle=Math.PI/2,n.position=i,n}return o(i,t),Object.defineProperty(i.prototype,"shadowAngle",{get:function(){return this._shadowAngle},set:function(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"direction",{get:function(){return this._direction},set:function(e){var t=this.needCube();this._direction=e,this.needCube()!==t&&this._shadowGenerator&&this._shadowGenerator.recreateShadowMap()},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"PointLight"},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_POINTLIGHT},i.prototype.needCube=function(){return!this.direction},i.prototype.getShadowDirection=function(i){if(this.direction)return t.prototype.getShadowDirection.call(this,i);switch(i){case 0:return new e.Vector3(1,0,0);case 1:return new e.Vector3(-1,0,0);case 2:return new e.Vector3(0,-1,0);case 3:return new e.Vector3(0,1,0);case 4:return new e.Vector3(0,0,1);case 5:return new e.Vector3(0,0,-1)}return e.Vector3.Zero()},i.prototype._setDefaultShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;n&&e.Matrix.PerspectiveFovLHToRef(this.shadowAngle,1,this.getDepthMinZ(n),this.getDepthMaxZ(n),t)},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this)},i.prototype.prepareLightSpecificDefines=function(e,t){e["POINTLIGHT"+t]=!0},n([e.serialize()],i.prototype,"shadowAngle",null),i})(e.ShadowLight);e.PointLight=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_1",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(e,i,r){var n=t.call(this,e,r)||this;return n._shadowFrustumSize=0,n._shadowOrthoScale=.1,n.autoUpdateExtends=!0,n._orthoLeft=Number.MAX_VALUE,n._orthoRight=Number.MIN_VALUE,n._orthoTop=Number.MIN_VALUE,n._orthoBottom=Number.MAX_VALUE,n.position=i.scale(-1),n.direction=i,n}return o(i,t),Object.defineProperty(i.prototype,"shadowFrustumSize",{get:function(){return this._shadowFrustumSize},set:function(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowOrthoScale",{get:function(){return this._shadowOrthoScale},set:function(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"DirectionalLight"},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_DIRECTIONALLIGHT},i.prototype._setDefaultShadowProjectionMatrix=function(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e,t):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)},i.prototype._setDefaultFixedFrustumShadowProjectionMatrix=function(t,i){var r=this.getScene().activeCamera;r&&e.Matrix.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,t)},i.prototype._setDefaultAutoExtendShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;if(n){if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){var o=e.Vector3.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;for(var s=0;sthis._orthoRight&&(this._orthoRight=o.x),o.y>this._orthoTop&&(this._orthoTop=o.y)}}var u=this._orthoRight-this._orthoLeft,f=this._orthoTop-this._orthoBottom;e.Matrix.OrthoOffCenterLHToRef(this._orthoLeft-u*this.shadowOrthoScale,this._orthoRight+u*this.shadowOrthoScale,this._orthoBottom-f*this.shadowOrthoScale,this._orthoTop+f*this.shadowOrthoScale,void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,t)}},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)},i.prototype.getDepthMinZ=function(e){return 1},i.prototype.getDepthMaxZ=function(e){return 1},i.prototype.prepareLightSpecificDefines=function(e,t){e["DIRLIGHT"+t]=!0},n([e.serialize()],i.prototype,"shadowFrustumSize",null),n([e.serialize()],i.prototype,"shadowOrthoScale",null),n([e.serialize()],i.prototype,"autoUpdateExtends",void 0),i})(e.ShadowLight);e.DirectionalLight=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_2",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),e.Vector3.Zero(),0,0,r)}}));var t=(function(t){function i(i,r,n,o,s,a){var l=t.call(this,i,a)||this;return l._projectionTextureMatrix=e.Matrix.Zero(),l._projectionTextureLightNear=1e-6,l._projectionTextureLightFar=1e3,l._projectionTextureUpDirection=e.Vector3.Up(),l._projectionTextureViewLightDirty=!0,l._projectionTextureProjectionLightDirty=!0,l._projectionTextureDirty=!0,l._projectionTextureViewTargetVector=e.Vector3.Zero(),l._projectionTextureViewLightMatrix=e.Matrix.Zero(),l._projectionTextureProjectionLightMatrix=e.Matrix.Zero(),l._projectionTextureScalingMatrix=e.Matrix.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),l.position=r,l.direction=n,l.angle=o,l.exponent=s,l}return o(i,t),Object.defineProperty(i.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowAngleScale",{get:function(){return this._shadowAngleScale},set:function(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureMatrix",{get:function(){return this._projectionTextureMatrix},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureLightNear",{get:function(){return this._projectionTextureLightNear},set:function(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureLightFar",{get:function(){return this._projectionTextureLightFar},set:function(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureUpDirection",{get:function(){return this._projectionTextureUpDirection},set:function(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTexture",{get:function(){return this._projectionTexture},set:function(e){this._projectionTexture=e,this._projectionTextureDirty=!0},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"SpotLight"},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_SPOTLIGHT},i.prototype._setDirection=function(e){t.prototype._setDirection.call(this,e),this._projectionTextureViewLightDirty=!0},i.prototype._setPosition=function(e){t.prototype._setPosition.call(this,e),this._projectionTextureViewLightDirty=!0},i.prototype._setDefaultShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;if(n){this._shadowAngleScale=this._shadowAngleScale||1;var o=this._shadowAngleScale*this._angle;e.Matrix.PerspectiveFovLHToRef(o,1,this.getDepthMinZ(n),this.getDepthMaxZ(n),t)}},i.prototype._computeProjectionTextureViewLightMatrix=function(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.position.addToRef(this.direction,this._projectionTextureViewTargetVector),e.Matrix.LookAtLHToRef(this.position,this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)},i.prototype._computeProjectionTextureProjectionLightMatrix=function(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;var t=this.projectionTextureLightFar,i=this.projectionTextureLightNear,r=t/(t-i),n=-r*i,o=1/Math.tan(this._angle/2);e.Matrix.FromValuesToRef(o/1,0,0,0,0,o,0,0,0,0,r,1,0,0,n,0,this._projectionTextureProjectionLightMatrix)},i.prototype._computeProjectionTextureMatrix=function(){this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(t,i){var r;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,i),r=e.Vector3.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,i),r=e.Vector3.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",r.x,r.y,r.z,Math.cos(.5*this.angle),i),this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),t.setMatrix("textureProjectionMatrix"+i,this._projectionTextureMatrix),t.setTexture("projectionLightSampler"+i,this.projectionTexture)),this},i.prototype.dispose=function(){t.prototype.dispose.call(this),this._projectionTexture&&this._projectionTexture.dispose()},i.prototype.prepareLightSpecificDefines=function(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!this.projectionTexture},n([e.serialize()],i.prototype,"angle",null),n([e.serialize()],i.prototype,"shadowAngleScale",null),n([e.serialize()],i.prototype,"exponent",void 0),n([e.serialize()],i.prototype,"projectionTextureLightNear",null),n([e.serialize()],i.prototype,"projectionTextureLightFar",null),n([e.serialize()],i.prototype,"projectionTextureUpDirection",null),n([e.serializeAsTexture("projectedLightTexture")],i.prototype,"_projectionTexture",void 0),i})(e.ShadowLight);e.SpotLight=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=e.Animation.ANIMATIONLOOPMODE_CYCLE}return t})();e.AnimationPropertiesOverride=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i){this.name=e,this.from=t,this.to=i}return e.prototype.clone=function(){return new e(this.name,this.from,this.to)},e})();e.AnimationRange=t;var i=(function(){function e(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}return e.prototype._clone=function(){return new e(this.frame,this.action,this.onlyOnce)},e})();e.AnimationEvent=i;var r=(function(){function t(e){this.path=e,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e.Vector3(t.x,0,t.y)},t.prototype.moveAhead=function(e){return void 0===e&&(e=.002),this.move(e),this},t.prototype.moveBack=function(e){return void 0===e&&(e=.002),this.move(-e),this},t.prototype.move=function(e){if(Math.abs(e)>1)throw"step size should be less than 1.";return this.value+=e,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.raiseOnChange=function(){var e=this;return this._onchange.forEach((function(t){return t(e)})),this},t.prototype.onchange=function(e){return this._onchange.push(e),this},t})();e.PathCursor=r;var n;!(function(e){e[e.STEP=1]="STEP"})(n=e.AnimationKeyInterpolation||(e.AnimationKeyInterpolation={}));var o=(function(){function i(e,t,r,n,o,s){this.name=e,this.targetProperty=t,this.framePerSecond=r,this.dataType=n,this.loopMode=o,this.enableBlending=s,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=n,this.loopMode=void 0===o?i.ANIMATIONLOOPMODE_CYCLE:o}return i._PrepareAnimation=function(t,r,n,o,s,a,l,h){var c=void 0;if(!isNaN(parseFloat(s))&&isFinite(s)?c=i.ANIMATIONTYPE_FLOAT:s instanceof e.Quaternion?c=i.ANIMATIONTYPE_QUATERNION:s instanceof e.Vector3?c=i.ANIMATIONTYPE_VECTOR3:s instanceof e.Vector2?c=i.ANIMATIONTYPE_VECTOR2:s instanceof e.Color3?c=i.ANIMATIONTYPE_COLOR3:s instanceof e.Size&&(c=i.ANIMATIONTYPE_SIZE),void 0==c)return null;var u=new i(t,r,n,c,l),f=[{frame:0,value:s},{frame:o,value:a}];return u.setKeys(f),void 0!==h&&u.setEasingFunction(h),u},i.CreateAnimation=function(e,t,r,n){var o=new i(e+"Animation",e,r,t,i.ANIMATIONLOOPMODE_CONSTANT);return o.setEasingFunction(n),o},i.CreateAndStartAnimation=function(e,t,r,n,o,s,a,l,h,c){var u=i._PrepareAnimation(e,r,n,o,s,a,l,h);return u?t.getScene().beginDirectAnimation(t,[u],0,o,1===u.loopMode,1,c):null},i.CreateAndStartHierarchyAnimation=function(e,t,r,n,o,s,a,l,h,c,u){var f=i._PrepareAnimation(e,n,o,s,a,l,h,c);return f?t.getScene().beginDirectHierarchyAnimation(t,r,[f],0,s,1===f.loopMode,1,u):null},i.CreateMergeAndStartAnimation=function(e,t,r,n,o,s,a,l,h,c){var u=i._PrepareAnimation(e,r,n,o,s,a,l,h);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,o,1===u.loopMode,1,c)):null},i.TransitionTo=function(e,t,i,r,n,o,s,a){if(void 0===a&&(a=null),s<=0)return i[e]=t,a&&a(),null;var l=n*(s/1e3);o.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(o);var h=r.beginAnimation(i,0,l,!1);return h.onAnimationEnd=a,h},Object.defineProperty(i.prototype,"runtimeAnimations",{get:function(){return this._runtimeAnimations},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"hasRunningRuntimeAnimations",{get:function(){for(var e=0,t=this._runtimeAnimations;e=0;o--)this._keys[o].frame>=r&&this._keys[o].frame<=n&&this._keys.splice(o,1);this._ranges[e]=null}},i.prototype.getRange=function(e){return this._ranges[e]},i.prototype.getKeys=function(){return this._keys},i.prototype.getHighestFrame=function(){for(var e=0,t=0,i=this._keys.length;t0)return a.clone?a.clone():a;var l=this.getKeys(),h=Math.max(0,Math.min(l.length-1,Math.floor(l.length*(e-l[0].frame)/(l[l.length-1].frame-l[0].frame))-1));if(l[h].frame>=e)for(;h-1>=0&&l[h].frame>=e;)h--;for(var c=h;c=e){var f=l[c],d=this._getKeyValue(f.value);if(f.interpolation===n.STEP)return d;var p=this._getKeyValue(u.value),m=void 0!==f.outTangent&&void 0!==u.inTangent,_=u.frame-f.frame,g=(e-f.frame)/_,v=this.getEasingFunction();switch(null!=v&&(g=v.ease(g)),this.dataType){case i.ANIMATIONTYPE_FLOAT:var y=m?this.floatInterpolateFunctionWithTangents(d,f.outTangent*_,p,u.inTangent*_,g):this.floatInterpolateFunction(d,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return y;case i.ANIMATIONLOOPMODE_RELATIVE:return s*t+y}break;case i.ANIMATIONTYPE_QUATERNION:var b=m?this.quaternionInterpolateFunctionWithTangents(d,f.outTangent.scale(_),p,u.inTangent.scale(_),g):this.quaternionInterpolateFunction(d,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return b;case i.ANIMATIONLOOPMODE_RELATIVE:return b.addInPlace(s.scale(t))}return b;case i.ANIMATIONTYPE_VECTOR3:var x=m?this.vector3InterpolateFunctionWithTangents(d,f.outTangent.scale(_),p,u.inTangent.scale(_),g):this.vector3InterpolateFunction(d,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return x;case i.ANIMATIONLOOPMODE_RELATIVE:return x.add(s.scale(t))}case i.ANIMATIONTYPE_VECTOR2:var T=m?this.vector2InterpolateFunctionWithTangents(d,f.outTangent.scale(_),p,u.inTangent.scale(_),g):this.vector2InterpolateFunction(d,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return T;case i.ANIMATIONLOOPMODE_RELATIVE:return T.add(s.scale(t))}case i.ANIMATIONTYPE_SIZE:switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(d,p,g);case i.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(d,p,g).add(s.scale(t))}case i.ANIMATIONTYPE_COLOR3:switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.color3InterpolateFunction(d,p,g);case i.ANIMATIONLOOPMODE_RELATIVE:return this.color3InterpolateFunction(d,p,g).add(s.scale(t))}case i.ANIMATIONTYPE_MATRIX:switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:if(i.AllowMatricesInterpolation)return this.matrixInterpolateFunction(d,p,g,r);case i.ANIMATIONLOOPMODE_RELATIVE:return d}}break}}return this._getKeyValue(l[l.length-1].value)},i.prototype.matrixInterpolateFunction=function(t,r,n,o){return i.AllowMatrixDecomposeForInterpolation?o?(e.Matrix.DecomposeLerpToRef(t,r,n,o),o):e.Matrix.DecomposeLerp(t,r,n):o?(e.Matrix.LerpToRef(t,r,n,o),o):e.Matrix.Lerp(t,r,n)},i.prototype.clone=function(){var e=new i(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(var t in this._ranges){var r=this._ranges[t];r&&(e._ranges[t]=r.clone())}}return e},i.prototype.setKeys=function(e){this._keys=e.slice(0)},i.prototype.serialize=function(){var e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;var t=this.dataType;e.keys=[];for(var r=this.getKeys(),n=0;n=1&&(l=c.values[1]),c.values.length>=2&&(h=c.values[2]);break;case i.ANIMATIONTYPE_QUATERNION:if(r=e.Quaternion.FromArray(c.values),c.values.length>=8){var u=e.Quaternion.FromArray(c.values.slice(4,8));u.equals(e.Quaternion.Zero())||(l=u)}if(c.values.length>=12){var f=e.Quaternion.FromArray(c.values.slice(8,12));f.equals(e.Quaternion.Zero())||(h=f)}break;case i.ANIMATIONTYPE_MATRIX:r=e.Matrix.FromArray(c.values);break;case i.ANIMATIONTYPE_COLOR3:r=e.Color3.FromArray(c.values);break;case i.ANIMATIONTYPE_VECTOR3:default:r=e.Vector3.FromArray(c.values)}var d={};d.frame=c.frame,d.value=r,void 0!=l&&(d.inTangent=l),void 0!=h&&(d.outTangent=h),a.push(d)}if(o.setKeys(a),t.ranges)for(n=0;nr[0].frame&&(this._from=r[0].frame),this._toe){var a={frame:e,value:o.value,inTangent:o.inTangent,outTangent:o.outTangent,interpolation:o.interpolation};n.splice(0,0,a)}if(s.frame-1&&this._scene.animationGroups.splice(e,1)},t.prototype._checkAnimationGroupEnded=function(e){var t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))},t})();e.AnimationGroup=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i,r){var n=this;this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._targetPath="",this._weight=1,this._ratioOffset=0,this._previousDelay=0,this._previousRatio=0,this._animation=t,this._target=e,this._scene=i,this._host=r,t._runtimeAnimations.push(this);var o=t.getEvents();o&&o.length>0&&o.forEach((function(e){n._events.push(e._clone())}))}return Object.defineProperty(t.prototype,"currentFrame",{get:function(){return this._currentFrame},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weight",{get:function(){return this._weight},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentValue",{get:function(){return this._currentValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"targetPath",{get:function(){return this._targetPath},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){return this._activeTarget},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animation",{get:function(){return this._animation},enumerable:!0,configurable:!0}),t.prototype.reset=function(e){if(void 0===e&&(e=!1),e)if(this._target instanceof Array)for(var t=0,i=0,r=this._target;i-1&&this._animation.runtimeAnimations.splice(e,1)},t.prototype._interpolate=function(t,i,r,n,o){return this._currentFrame=t,this._animation.dataType!==e.Animation.ANIMATIONTYPE_MATRIX||this._workValue||(this._workValue=e.Matrix.Zero()),this._animation._interpolate(t,i,this._workValue,r,n,o)},t.prototype.setValue=function(e,t){if(void 0===t&&(t=1),this._target instanceof Array)for(var i=0,r=0,n=this._target;r1){for(var l=t[a[0]],h=1;ht[t.length-1].frame&&(e=t[t.length-1].frame);var i=this._interpolate(e,0,this._getCorrectLoopMode());this.setValue(i,-1)},t.prototype._prepareForSpeedRatioChange=function(e){var t=this._previousDelay*(this._animation.framePerSecond*e)/1e3;this._ratioOffset=this._previousRatio-t},t.prototype.animate=function(t,i,r,n,o,s){void 0===s&&(s=-1);var a=this._animation.targetPropertyPath;if(!a||a.length<1)return this._stopped=!0,!1;var l=!0,h=this._animation.getKeys();if(0!==h[0].frame){var c={frame:0,value:h[0].value};h.splice(0,0,c)}else if(1===h.length){var c={frame:.001,value:h[0].value};h.push(c)}(ih[h.length-1].frame)&&(i=h[0].frame),(rh[h.length-1].frame)&&(r=h[h.length-1].frame),i===r&&(i>h[0].frame?i--:ri&&d>=f||i>r&&d<=f)&&!n)l=!1,p=this._animation._getKeyValue(h[h.length-1].value);else if(this._getCorrectLoopMode()!==e.Animation.ANIMATIONLOOPMODE_CYCLE){var m=r.toString()+i.toString();if(!this._offsetsCache[m]){var _=this._interpolate(i,0,e.Animation.ANIMATIONLOOPMODE_CYCLE),g=this._interpolate(r,0,e.Animation.ANIMATIONLOOPMODE_CYCLE);switch(this._animation.dataType){case e.Animation.ANIMATIONTYPE_FLOAT:this._offsetsCache[m]=g-_;break;case e.Animation.ANIMATIONTYPE_QUATERNION:this._offsetsCache[m]=g.subtract(_);break;case e.Animation.ANIMATIONTYPE_VECTOR3:this._offsetsCache[m]=g.subtract(_);case e.Animation.ANIMATIONTYPE_VECTOR2:this._offsetsCache[m]=g.subtract(_);case e.Animation.ANIMATIONTYPE_SIZE:this._offsetsCache[m]=g.subtract(_);case e.Animation.ANIMATIONTYPE_COLOR3:this._offsetsCache[m]=g.subtract(_)}this._highLimitsCache[m]=g}p=this._highLimitsCache[m],u=this._offsetsCache[m]}if(void 0===u)switch(this._animation.dataType){case e.Animation.ANIMATIONTYPE_FLOAT:u=0;break;case e.Animation.ANIMATIONTYPE_QUATERNION:u=new e.Quaternion(0,0,0,0);break;case e.Animation.ANIMATIONTYPE_VECTOR3:u=e.Vector3.Zero();break;case e.Animation.ANIMATIONTYPE_VECTOR2:u=e.Vector2.Zero();break;case e.Animation.ANIMATIONTYPE_SIZE:u=e.Size.Zero();break;case e.Animation.ANIMATIONTYPE_COLOR3:u=e.Color3.Black()}var v=d/f>>0,y=l?i+d%f:r;if(this._host&&this._host.syncRoot){var b=this._host.syncRoot;y=i+(r-i)*((b.masterFrame-b.fromFrame)/(b.toFrame-b.fromFrame))}var x=this._events;if(f>0&&this.currentFrame>y||f<0&&this.currentFrame0&&y>=x[T].frame&&x[T].frame>=i||f<0&&y<=x[T].frame&&x[T].frame<=i){var P=x[T];P.isDone||(P.onlyOnce&&(x.splice(T,1),T--),P.isDone=!0,P.action())}return l||(this._stopped=!0),l},t})();e.RuntimeAnimation=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a,l){void 0===r&&(r=0),void 0===n&&(n=100),void 0===o&&(o=!1),void 0===s&&(s=1),this.target=i,this.fromFrame=r,this.toFrame=n,this.loopAnimation=o,this.onAnimationEnd=a,this._localDelayOffset=null,this._pausedDelay=null,this._runtimeAnimations=new Array,this._paused=!1,this._speedRatio=1,this._weight=-1,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new e.Observable,this._scene=t,l&&this.appendAnimations(i,l),this._speedRatio=s,t._activeAnimatables.push(this)}return Object.defineProperty(t.prototype,"syncRoot",{get:function(){return this._syncRoot},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"masterFrame",{get:function(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weight",{get:function(){return this._weight},set:function(e){if(-1===e)return void(this._weight=-1);this._weight=Math.min(Math.max(e,0),1)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"speedRatio",{get:function(){return this._speedRatio},set:function(e){for(var t=0;t-1&&(this._scene._activeAnimatables.splice(t,1),this._scene._activeAnimatables.push(this))}return this},t.prototype.getAnimations=function(){return this._runtimeAnimations},t.prototype.appendAnimations=function(t,i){for(var r=0;r-1){for(var r=this._runtimeAnimations,n=r.length-1;n>=0;n--){var o=r[n];e&&o.animation.name!=e||(t&&!t(o.target)||(o.dispose(),r.splice(n,1)))}0==r.length&&(this._scene._activeAnimatables.splice(i,1),this._raiseOnAnimationEnd())}}else{var n=this._scene._activeAnimatables.indexOf(this);if(n>-1){this._scene._activeAnimatables.splice(n,1);for(var r=this._runtimeAnimations,n=0;n=.5?.5*(1-this.easeInCore(2*(1-t)))+.5:.5*this.easeInCore(2*t)},e._EASINGMODE_EASEIN=0,e._EASINGMODE_EASEOUT=1,e._EASINGMODE_EASEINOUT=2,e})();e.EasingFunction=t;var i=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)},t})(t);e.CircleEase=i;var r=(function(e){function t(t){void 0===t&&(t=1);var i=e.call(this)||this;return i.amplitude=t,i}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)},t})(t);e.BackEase=r;var n=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=2);var r=e.call(this)||this;return r.bounces=t,r.bounciness=i,r}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.bounces),i=this.bounciness;i<=1&&(i=1.001);var r=Math.pow(i,t),n=1-i,o=(1-r)/n+.5*r,s=e*o,a=Math.log(-s*(1-i)+1)/Math.log(i),l=Math.floor(a),h=l+1,c=(1-Math.pow(i,l))/(n*o),u=(1-Math.pow(i,h))/(n*o),f=.5*(c+u),d=e-f,p=f-c;return-Math.pow(1/i,t-l)/(p*p)*(d-p)*(d+p)},t})(t);e.BounceEase=n;var s=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e*e},t})(t);e.CubicEase=s;var a=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=3);var r=e.call(this)||this;return r.oscillations=t,r.springiness=i,r}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.oscillations),i=Math.max(0,this.springiness);return(0==i?e:(Math.exp(i*e)-1)/(Math.exp(i)-1))*Math.sin((6.283185307179586*t+1.5707963267948966)*e)},t})(t);e.ElasticEase=a;var l=(function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.exponent=t,i}return o(t,e),t.prototype.easeInCore=function(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)},t})(t);e.ExponentialEase=l;var h=(function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.power=t,i}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.power);return Math.pow(e,t)},t})(t);e.PowerEase=h;var c=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e},t})(t);e.QuadraticEase=c;var u=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e*e*e},t})(t);e.QuarticEase=u;var f=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e*e*e*e},t})(t);e.QuinticEase=f;var d=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return 1-Math.sin(1.5707963267948966*(1-e))},t})(t);e.SineEase=d;var p=(function(t){function i(e,i,r,n){void 0===e&&(e=0),void 0===i&&(i=0),void 0===r&&(r=1),void 0===n&&(n=1);var o=t.call(this)||this;return o.x1=e,o.y1=i,o.x2=r,o.y2=n,o}return o(i,t),i.prototype.easeInCore=function(t){return e.BezierCurve.interpolate(t,this.x1,this.y1,this.x2,this.y2)},i})(t);e.BezierCurveEase=p})(r||(r={}));var r;!(function(e){var t=(function(){function e(e){this._actionManager=e}return e.prototype.isValid=function(){return!0},e.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},e.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},e.prototype.serialize=function(){},e.prototype._serialize=function(e){return{type:2,children:[],name:e.name,properties:e.properties}},e})();e.Condition=t;var i=(function(t){function i(e,r,n,o,s){void 0===s&&(s=i.IsEqual);var a=t.call(this,e)||this;return a.propertyPath=n,a.value=o,a.operator=s,a._target=r,a._effectiveTarget=a._getEffectiveTarget(r,a.propertyPath),a._property=a._getProperty(a.propertyPath),a}return o(i,t),Object.defineProperty(i,"IsEqual",{get:function(){return i._IsEqual},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsDifferent",{get:function(){return i._IsDifferent},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsGreater",{get:function(){return i._IsGreater},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsLesser",{get:function(){return i._IsLesser},enumerable:!0,configurable:!0}),i.prototype.isValid=function(){switch(this.operator){case i.IsGreater:return this._effectiveTarget[this._property]>this.value;case i.IsLesser:return this._effectiveTarget[this._property]-1&&this._scene.actionManagers.splice(e,1)},t.prototype.getScene=function(){return this._scene},t.prototype.hasSpecificTriggers=function(e){for(var t=0;t-1)return!0}return!1},t.prototype.hasSpecificTrigger=function(e,t){for(var i=0;i=t._OnPickTrigger&&i.trigger<=t._OnPointerOutTrigger)return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPickTriggers",{get:function(){for(var e=0;e=t._OnPickTrigger&&i.trigger<=t._OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"HasTriggers",{get:function(){for(var e in t.Triggers)if(t.Triggers.hasOwnProperty(e))return!0;return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"HasPickTriggers",{get:function(){for(var e in t.Triggers)if(t.Triggers.hasOwnProperty(e)){var i=parseInt(e);if(i>=t._OnPickTrigger&&i<=t._OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),t.HasSpecificTrigger=function(e){for(var i in t.Triggers)if(t.Triggers.hasOwnProperty(i)){var r=parseInt(i);if(r===e)return!0}return!1},t.prototype.registerAction=function(i){return i.trigger===t.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(e.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(i),t.Triggers[i.trigger]?t.Triggers[i.trigger]++:t.Triggers[i.trigger]=1,i._actionManager=this,i._prepare(),i)},t.prototype.unregisterAction=function(e){var i=this.actions.indexOf(e);return-1!==i&&(this.actions.splice(i,1),t.Triggers[e.trigger]-=1,0===t.Triggers[e.trigger]&&delete t.Triggers[e.trigger],delete e._actionManager,!0)},t.prototype.processTrigger=function(e,i){for(var r=0;r0;if(2===i.type?f.push(o):f.push(r),m){for(var _=new Array,g=0;g0){var f=u.properties[0].value,d=null===u.properties[0].targetType?f:n.getMeshByName(f);d._meshId&&(d.mesh=n.getMeshByID(d._meshId)),c={trigger:t[u.name],parameter:d}}else c=t[u.name];for(var p=0;p>0;this._vertexData[o+10]=t.cellIndex-s*n,this._vertexData[o+11]=s,this._vertexData[o+12]=t.color.r,this._vertexData[o+13]=t.color.g,this._vertexData[o+14]=t.color.b,this._vertexData[o+15]=t.color.a},t.prototype.intersects=function(t,i,r,n){for(var o=Math.min(this._capacity,this.sprites.length),s=e.Vector3.Zero(),a=e.Vector3.Zero(),l=Number.MAX_VALUE,h=null,c=e.Vector3.Zero(),u=i.getViewMatrix(),f=0;fp&&(l=p,h=d,n))break}}}if(h){var m=new e.PickingInfo;return m.hit=!0,m.pickedSprite=h,m.distance=l,m}return null},t.prototype.render=function(){if(this._effectBase.isReady()&&this._effectFog.isReady()&&this._spriteTexture&&this._spriteTexture.isReady()){for(var t=this._scene.getEngine(),i=this._spriteTexture.getBaseSize(),r=t.getDeltaTime(),n=Math.min(this._capacity,this.sprites.length),o=i.width/this.cellWidth,s=0,a=0;athis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,this.cellIndex>this._toIndex&&(this._loopAnimation?this.cellIndex=this._fromIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()))))},t.prototype.dispose=function(){for(var e=0;et.x)return!1}else if(i=1/this.direction.x,r=(e.x-this.origin.x)*i,n=(t.x-this.origin.x)*i,n===-1/0&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yt.y)return!1}else if(i=1/this.direction.y,r=(e.y-this.origin.y)*i,n=(t.y-this.origin.y)*i,n===-1/0&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zt.z)return!1}else if(i=1/this.direction.z,r=(e.z-this.origin.z)*i,n=(t.z-this.origin.z)*i,n===-1/0&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;return!0},t.prototype.intersectsBox=function(e){return this.intersectsBoxMinMax(e.minimum,e.maximum)},t.prototype.intersectsSphere=function(e){var t=e.center.x-this.origin.x,i=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=t*t+i*i+r*r,o=e.radius*e.radius;if(n<=o)return!0;var s=t*this.direction.x+i*this.direction.y+r*this.direction.z;return!(s<0)&&n-s*s<=o},t.prototype.intersectsTriangle=function(t,i,r){this._edge1||(this._edge1=e.Vector3.Zero(),this._edge2=e.Vector3.Zero(),this._pvec=e.Vector3.Zero(),this._tvec=e.Vector3.Zero(),this._qvec=e.Vector3.Zero()),i.subtractToRef(t,this._edge1),r.subtractToRef(t,this._edge2),e.Vector3.CrossToRef(this.direction,this._edge2,this._pvec);var n=e.Vector3.Dot(this._edge1,this._pvec);if(0===n)return null;var o=1/n;this.origin.subtractToRef(t,this._tvec);var s=e.Vector3.Dot(this._tvec,this._pvec)*o;if(s<0||s>1)return null;e.Vector3.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Vector3.Dot(this.direction,this._qvec)*o;if(a<0||s+a>1)return null;var l=e.Vector3.Dot(this._edge2,this._qvec)*o;return l>this.length?null:new e.IntersectionInfo(s,a,l)},t.prototype.intersectsPlane=function(t){var i,r=e.Vector3.Dot(t.normal,this.direction);if(Math.abs(r)<9.99999997475243e-7)return null;var n=e.Vector3.Dot(t.normal,this.origin);return i=(-t.d-n)/r,i<0?i<-9.99999997475243e-7?null:0:i},t.prototype.intersectsMesh=function(i,r){var n=e.Tmp.Matrix[0];return i.getWorldMatrix().invertToRef(n),this._tmpRay?t.TransformToRef(this,n,this._tmpRay):this._tmpRay=t.Transform(this,n),i.intersects(this._tmpRay,r)},t.prototype.intersectsMeshes=function(e,t,i){i?i.length=0:i=[];for(var r=0;rt.distance?1:0},t.prototype.intersectionSegment=function(i,r,n){var o,s,a,l,h=this.origin.add(this.direction.multiplyByFloats(t.rayl,t.rayl,t.rayl)),c=r.subtract(i),u=h.subtract(this.origin),f=i.subtract(this.origin),d=e.Vector3.Dot(c,c),p=e.Vector3.Dot(c,u),m=e.Vector3.Dot(u,u),_=e.Vector3.Dot(c,f),g=e.Vector3.Dot(u,f),v=d*m-p*p,y=v,b=v;vy&&(s=y,l=g+p,b=m)),l<0?(l=0,-_<0?s=0:-_>d?s=y:(s=-_,y=d)):l>b&&(l=b,-_+p<0?s=0:-_+p>d?s=y:(s=-_+p,y=d)),o=Math.abs(s)0&&a<=this.length&&T.lengthSquared()i.x+r)&&(!(i.x-r>t.x)&&(!(e.y>i.y+r)&&(!(i.y-r>t.y)&&(!(e.z>i.z+r)&&!(i.z-r>t.z)))))},i=(function(){var e={root:0,found:!1};return function(t,i,r,n){e.root=0,e.found=!1;var o=i*i-4*t*r;if(o<0)return e;var s=Math.sqrt(o),a=(-i-s)/(2*t),l=(-i+s)/(2*t);if(a>l){var h=l;l=a,a=h}return a>0&&a0&&l=0))},r.prototype._canDoCollision=function(i,r,n,o){var s=e.Vector3.Distance(this._basePointWorld,i),a=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+a+r)&&!!t(n,o,this._basePointWorld,this._velocityWorldLength+a)},r.prototype._testTriangle=function(t,r,n,o,s,a){var l,h=!1;r||(r=[]),r[t]||(r[t]=new e.Plane(0,0,0,0),r[t].copyFromPoints(n,o,s));var c=r[t];if(a||c.isFrontFacingTo(this._normalizedVelocity,0)){var u=c.signedDistanceTo(this._basePoint),f=e.Vector3.Dot(c.normal,this._velocity);if(0==f){if(Math.abs(u)>=1)return;h=!0,l=0}else{l=(-1-u)/f;var d=(1-u)/f;if(l>d){var p=d;d=l,l=p}if(l>1||d<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);var m=!1,_=1;if(h||(this._basePoint.subtractToRef(c.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(l,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,n,o,s,c.normal)&&(m=!0,_=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!m){var g=this._velocity.lengthSquared(),v=g;this._basePoint.subtractToRef(n,this._tempVector);var y=2*e.Vector3.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,x=i(v,y,b,_);x.found&&(_=x.root,m=!0,this._collisionPoint.copyFrom(n)),this._basePoint.subtractToRef(o,this._tempVector),y=2*e.Vector3.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,x=i(v,y,b,_),x.found&&(_=x.root,m=!0,this._collisionPoint.copyFrom(o)),this._basePoint.subtractToRef(s,this._tempVector),y=2*e.Vector3.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,x=i(v,y,b,_),x.found&&(_=x.root,m=!0,this._collisionPoint.copyFrom(s)),o.subtractToRef(n,this._edge),n.subtractToRef(this._basePoint,this._baseToVertex);var T=this._edge.lengthSquared(),E=e.Vector3.Dot(this._edge,this._velocity),P=e.Vector3.Dot(this._edge,this._baseToVertex);if(v=T*-g+E*E,y=T*(2*e.Vector3.Dot(this._velocity,this._baseToVertex))-2*E*P,b=T*(1-this._baseToVertex.lengthSquared())+P*P,x=i(v,y,b,_),x.found){var A=(E*x.root-P)/T;A>=0&&A<=1&&(_=x.root,m=!0,this._edge.scaleInPlace(A),n.addToRef(this._edge,this._collisionPoint))}s.subtractToRef(o,this._edge),o.subtractToRef(this._basePoint,this._baseToVertex),T=this._edge.lengthSquared(),E=e.Vector3.Dot(this._edge,this._velocity),P=e.Vector3.Dot(this._edge,this._baseToVertex),v=T*-g+E*E,y=T*(2*e.Vector3.Dot(this._velocity,this._baseToVertex))-2*E*P,b=T*(1-this._baseToVertex.lengthSquared())+P*P,x=i(v,y,b,_),x.found&&(A=(E*x.root-P)/T)>=0&&A<=1&&(_=x.root,m=!0,this._edge.scaleInPlace(A),o.addToRef(this._edge,this._collisionPoint)),n.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),T=this._edge.lengthSquared(),E=e.Vector3.Dot(this._edge,this._velocity),P=e.Vector3.Dot(this._edge,this._baseToVertex),v=T*-g+E*E,y=T*(2*e.Vector3.Dot(this._velocity,this._baseToVertex))-2*E*P,b=T*(1-this._baseToVertex.lengthSquared())+P*P,x=i(v,y,b,_),x.found&&(A=(E*x.root-P)/T)>=0&&A<=1&&(_=x.root,m=!0,this._edge.scaleInPlace(A),s.addToRef(this._edge,this._collisionPoint))}if(m){var M=_*this._velocity.length();(!this.collisionFound||M4)){++n._runningUpdated;var e={updatedMeshes:n._addUpdateMeshesList,updatedGeometries:n._addUpdateGeometriesList, -removedGeometries:n._toRemoveGeometryArray,removedMeshes:n._toRemoveMeshesArray},i={payload:e,taskType:t.UPDATE},r=[];for(var o in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(o)&&(r.push(i.payload.updatedGeometries[o].indices.buffer),r.push(i.payload.updatedGeometries[o].normals.buffer),r.push(i.payload.updatedGeometries[o].positions.buffer));n._worker.postMessage(i,r),n._addUpdateMeshesList={},n._addUpdateGeometriesList={},n._toRemoveGeometryArray=[],n._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(r){var o=r.data;if(o.error!=i.SUCCESS)return void e.Tools.Warn("error returned from worker!");switch(o.taskType){case t.INIT:n._init=!0,n._scene.meshes.forEach((function(e){n.onMeshAdded(e)})),n._scene.getGeometries().forEach((function(e){n.onGeometryAdded(e)}));break;case t.UPDATE:n._runningUpdated--;break;case t.COLLIDE:var s=o.payload;if(!n._collisionsCallbackArray[s.collisionId])return;var a=n._collisionsCallbackArray[s.collisionId];if(a){var l=n._scene.getMeshByUniqueID(s.collidedMeshUniqueId);l&&a(s.collisionId,e.Vector3.FromArray(s.newPosition),l)}n._collisionsCallbackArray[s.collisionId]=null}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return r.prototype.getNewPosition=function(e,i,r,n,o,s,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(r._radius,this._scaledPosition),i.divideToRef(r._radius,this._scaledVelocity),this._collisionsCallbackArray[a]=s;var l={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:r._radius.asArray()},collisionId:a,excludedMeshUniqueId:o?o.uniqueId:null,maximumRetry:n},h={payload:l,taskType:t.COLLIDE};this._worker.postMessage(h)}},r.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var r=e.WorkerIncluded?e.Engine.CodeRepository+"Collisions/babylon.collisionWorker.js":URL.createObjectURL(new Blob([e.CollisionWorker],{type:"application/javascript"}));this._worker=new Worker(r),this._worker.onmessage=this._onMessageFromWorker;var n={payload:{},taskType:t.INIT};this._worker.postMessage(n)},r.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},r.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},r.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},r.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},r.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},r.SerializeMesh=function(t){var i=[];t.subMeshes&&(i=t.subMeshes.map((function(e,t){var i=e.getBoundingInfo();return{position:t,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:i.boundingSphere.centerWorld.asArray(),sphereRadius:i.boundingSphere.radiusWorld,boxMinimum:i.boundingBox.minimumWorld.asArray(),boxMaximum:i.boundingBox.maximumWorld.asArray()}})));var r=null;if(t instanceof e.Mesh){var n=t.geometry;r=n?n.id:null}else if(t instanceof e.InstancedMesh){var n=t.sourceMesh&&t.sourceMesh.geometry;r=n?n.id:null}var o=t.getBoundingInfo();return{uniqueId:t.uniqueId,id:t.id,name:t.name,geometryId:r,sphereCenter:o.boundingSphere.centerWorld.asArray(),sphereRadius:o.boundingSphere.radiusWorld,boxMinimum:o.boundingBox.minimumWorld.asArray(),boxMaximum:o.boundingBox.maximumWorld.asArray(),worldMatrixFromCache:t.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:t.checkCollisions}},r.SerializeGeometry=function(t){return{id:t.id,positions:new Float32Array(t.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(t.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Uint32Array(t.getIndices()||[])}},r})();e.CollisionCoordinatorWorker=r;var n=(function(){function t(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return t.prototype.getNewPosition=function(e,t,i,r,n,o,s){e.divideToRef(i._radius,this._scaledPosition),t.divideToRef(i._radius,this._scaledVelocity),i.collidedMesh=null,i._retry=0,i._initialVelocity=this._scaledVelocity,i._initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,r,this._finalPosition,n),this._finalPosition.multiplyInPlace(i._radius),o(s,this._finalPosition,i.collidedMesh)},t.prototype.init=function(e){this._scene=e},t.prototype.destroy=function(){},t.prototype.onMeshAdded=function(e){},t.prototype.onMeshUpdated=function(e){},t.prototype.onMeshRemoved=function(e){},t.prototype.onGeometryAdded=function(e){},t.prototype.onGeometryUpdated=function(e){},t.prototype.onGeometryDeleted=function(e){},t.prototype._collideWithWorld=function(t,i,r,n,o,s){void 0===s&&(s=null);var a=10*e.Engine.CollisionsEpsilon;if(r._retry>=n)return void o.copyFrom(t);var l=s?s.collisionMask:r.collisionMask;r._initialize(t,i,a);for(var h=0;h=n.lifeTime)return l._emitFromParticle(n),l.recycleParticle(n),o--,"continue";var s=n.age/n.lifeTime;l._colorGradients&&l._colorGradients.length>0?e.Tools.GetCurrentGradient(s,l._colorGradients,(function(t,i,r){t!==n._currentColorGradient&&(n._currentColor1.copyFrom(n._currentColor2),i.getColorToRef(n._currentColor2),n._currentColorGradient=t),e.Color4.LerpToRef(n._currentColor1,n._currentColor2,r,n.color)})):(n.colorStep.scaleToRef(l._scaledUpdateSpeed,l._scaledColorStep),n.color.addInPlace(l._scaledColorStep),n.color.a<0&&(n.color.a=0)),l._angularSpeedGradients&&l._angularSpeedGradients.length>0&&e.Tools.GetCurrentGradient(s,l._angularSpeedGradients,(function(t,i,r){t!==n._currentAngularSpeedGradient&&(n._currentAngularSpeed1=n._currentAngularSpeed2,n._currentAngularSpeed2=i.getFactor(),n._currentAngularSpeedGradient=t),n.angularSpeed=e.Scalar.Lerp(n._currentAngularSpeed1,n._currentAngularSpeed2,r)})),n.angle+=n.angularSpeed*l._scaledUpdateSpeed;var a=l._scaledUpdateSpeed;if(l._velocityGradients&&l._velocityGradients.length>0&&e.Tools.GetCurrentGradient(s,l._velocityGradients,(function(t,i,r){t!==n._currentVelocityGradient&&(n._currentVelocity1=n._currentVelocity2,n._currentVelocity2=i.getFactor(),n._currentVelocityGradient=t),a*=e.Scalar.Lerp(n._currentVelocity1,n._currentVelocity2,r)})),n.direction.scaleToRef(a,l._scaledDirection),n.position.addInPlace(l._scaledDirection),i&&r){var h=e.Tmp.Vector3[0],c=e.Tmp.Vector3[1];l._emitterWorldMatrix.getTranslationToRef(c),n.position.subtractToRef(c,h);var u=l._fetchR(h.y,h.z,r.width,r.height,i),f=l._fetchR(h.x+.33,h.z+.33,r.width,r.height,i),d=l._fetchR(h.x-.33,h.y-.33,r.width,r.height,i),p=e.Tmp.Vector3[0],m=e.Tmp.Vector3[1];p.copyFromFloats((2*u-1)*l.noiseStrength.x,(2*f-1)*l.noiseStrength.y,(2*d-1)*l.noiseStrength.z),p.scaleToRef(l._scaledUpdateSpeed,m),n.direction.addInPlace(m)}l.gravity.scaleToRef(l._scaledUpdateSpeed,l._scaledGravity),n.direction.addInPlace(l._scaledGravity),l._sizeGradients&&l._sizeGradients.length>0&&e.Tools.GetCurrentGradient(s,l._sizeGradients,(function(t,i,r){t!==n._currentSizeGradient&&(n._currentSize1=n._currentSize2,n._currentSize2=i.getFactor(),n._currentSizeGradient=t),n.size=e.Scalar.Lerp(n._currentSize1,n._currentSize2,r)})),l._isAnimationSheetEnabled&&n.updateCellIndex()})()}}return t.prototype.getColorGradients=function(){return this._colorGradients},t.prototype.getSizeGradients=function(){return this._sizeGradients},t.prototype.getLifeTimeGradients=function(){return this._lifeTimeGradients},t.prototype.getAngularSpeedGradients=function(){return this._angularSpeedGradients},t.prototype.getVelocityGradients=function(){return this._velocityGradients},Object.defineProperty(t.prototype,"direction1",{get:function(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction2",{get:function(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minEmitBox",{get:function(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxEmitBox",{get:function(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isAnimationSheetEnabled",{get:function(){return this._isAnimationSheetEnabled},set:function(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._resetEffect())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isBillboardBased",{get:function(){return this._isBillboardBased},set:function(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._resetEffect())},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},Object.defineProperty(t.prototype,"particles",{get:function(){return this._particles},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"ParticleSystem"},t.prototype._fetchR=function(e,t,i,r,n){return e=.5*Math.abs(e)+.5,t=.5*Math.abs(t)+.5,n[4*((e*i%i|0)+(t*r%r|0)*i)]/255},t.prototype._addFactorGradient=function(t,i,r,n){var o=new e.FactorGradient;o.gradient=i,o.factor1=r,o.factor2=n,t.push(o),t.sort((function(e,t){return e.gradientt.gradient?1:0}))},t.prototype._removeFactorGradient=function(e,t){if(e)for(var i=0,r=0,n=e;rt.gradient?1:0})),this},t.prototype.removeColorGradient=function(e){if(!this._colorGradients)return this;for(var t=0,i=0,r=this._colorGradients;i0,this.emitter.position){var i=this.emitter;this._emitterWorldMatrix=i.getWorldMatrix()}else{var r=this.emitter;this._emitterWorldMatrix=e.Matrix.Translation(r.x,r.y,r.z)}this.updateFunction(this._particles);for(var n,o,s=this,a=0;a0){var i=e.Scalar.Clamp(s._actualFrame/s.targetStopDuration);e.Tools.GetCurrentGradient(i,s._lifeTimeGradients,(function(t,r,o){var s=t,a=r,l=s.getFactor(),h=a.getFactor(),c=(i-s.gradient)/(a.gradient-s.gradient);n.lifeTime=e.Scalar.Lerp(l,h,c)}))}else n.lifeTime=e.Scalar.RandomRange(s.minLifeTime,s.maxLifeTime);s._sizeGradients&&0!==s._sizeGradients.length?(n._currentSizeGradient=s._sizeGradients[0],n._currentSize1=n._currentSizeGradient.getFactor(),n.size=n._currentSize1,s._sizeGradients.length>1?n._currentSize2=s._sizeGradients[1].getFactor():n._currentSize2=n._currentSize1):n.size=e.Scalar.RandomRange(s.minSize,s.maxSize),n.scale.copyFromFloats(e.Scalar.RandomRange(s.minScaleX,s.maxScaleX),e.Scalar.RandomRange(s.minScaleY,s.maxScaleY)),s._angularSpeedGradients&&0!==s._angularSpeedGradients.length?(n._currentAngularSpeedGradient=s._angularSpeedGradients[0],n.angularSpeed=n._currentAngularSpeedGradient.getFactor(),n._currentAngularSpeed1=n.angularSpeed,s._angularSpeedGradients.length>1?n._currentAngularSpeed2=s._angularSpeedGradients[1].getFactor():n._currentAngularSpeed2=n._currentAngularSpeed1):n.angularSpeed=e.Scalar.RandomRange(s.minAngularSpeed,s.maxAngularSpeed),n.angle=e.Scalar.RandomRange(s.minInitialRotation,s.maxInitialRotation),s._velocityGradients&&s._velocityGradients.length>0&&(n._currentVelocityGradient=s._velocityGradients[0],n._currentVelocity1=n._currentVelocityGradient.getFactor(),s._velocityGradients.length>1?n._currentVelocity2=s._velocityGradients[1].getFactor():n._currentVelocity2=n._currentVelocity1),s._colorGradients&&0!==s._colorGradients.length?(n._currentColorGradient=s._colorGradients[0],n._currentColorGradient.getColorToRef(n.color),n._currentColor1.copyFrom(n.color),s._colorGradients.length>1?s._colorGradients[1].getColorToRef(n._currentColor2):n._currentColor2.copyFrom(n.color)):(o=e.Scalar.RandomRange(0,1),e.Color4.LerpToRef(s.color1,s.color2,o,n.color),s.colorDead.subtractToRef(n.color,s._colorDiff),s._colorDiff.scaleToRef(1/n.lifeTime,n.colorStep)),s._isAnimationSheetEnabled&&(n._initialStartSpriteCellID=s.startSpriteCellID,n._initialEndSpriteCellID=s.endSpriteCellID)})())break}},t._GetAttributeNamesOrOptions=function(t,i){void 0===t&&(t=!1),void 0===i&&(i=!1);var r=[e.VertexBuffer.PositionKind,e.VertexBuffer.ColorKind,"angle","offset","size"];return t&&r.push("cellIndex"),i||r.push("direction"),r},t._GetEffectCreationOptions=function(e){void 0===e&&(e=!1);var t=["invView","view","projection","vClipPlane","textureMask","translationPivot","eyePosition"];return e&&t.push("particlesInfos"),t},t.prototype._getEffect=function(){if(this._customEffect)return this._customEffect;var i=[];if(this._scene.clipPlane&&i.push("#define CLIPPLANE"),this._isAnimationSheetEnabled&&i.push("#define ANIMATESHEET"),this._isBillboardBased)switch(i.push("#define BILLBOARD"),this.billboardMode){case e.AbstractMesh.BILLBOARDMODE_Y:i.push("#define BILLBOARDY");break;case e.AbstractMesh.BILLBOARDMODE_ALL:}var r=i.join("\n");if(this._cachedDefines!==r){this._cachedDefines=r;var n=t._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased),o=t._GetEffectCreationOptions(this._isAnimationSheetEnabled);this._effect=this._scene.getEngine().createEffect("particles",n,o,["diffuseSampler"],r)}return this._effect},t.prototype.animate=function(e){if(void 0===e&&(e=!1),this._started){if(!e){var t=this._getEffect();if(!(this.emitter&&t.isReady()&&this.particleTexture&&this.particleTexture.isReady()))return;if(this._currentRenderId===this._scene.getRenderId())return;this._currentRenderId=this._scene.getRenderId()}this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:this._scene.getAnimationRatio());var i;if(this.manualEmitCount>-1?(i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0):(i=this.emitRate*this._scaledUpdateSpeed>>0,this._newPartsExcess+=this.emitRate*this._scaledUpdateSpeed-i),this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene._toBeDisposed.push(this))),!e){for(var r=0,n=0;n-1&&this._scene.particleSystems.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.prototype.createPointEmitter=function(t,i){var r=new e.PointParticleEmitter;return r.direction1=t,r.direction2=i,this.particleEmitterType=r,r},t.prototype.createHemisphericEmitter=function(t,i){void 0===t&&(t=1),void 0===i&&(i=1);var r=new e.HemisphericParticleEmitter(t,i);return this.particleEmitterType=r,r},t.prototype.createSphereEmitter=function(t,i){void 0===t&&(t=1),void 0===i&&(i=1);var r=new e.SphereParticleEmitter(t,i);return this.particleEmitterType=r,r},t.prototype.createDirectedSphereEmitter=function(t,i,r){void 0===t&&(t=1),void 0===i&&(i=new e.Vector3(0,1,0)),void 0===r&&(r=new e.Vector3(0,1,0));var n=new e.SphereDirectedParticleEmitter(t,i,r);return this.particleEmitterType=n,n},t.prototype.createConeEmitter=function(t,i){void 0===t&&(t=1),void 0===i&&(i=Math.PI/4);var r=new e.ConeParticleEmitter(t,i);return this.particleEmitterType=r,r},t.prototype.createBoxEmitter=function(t,i,r,n){var o=new e.BoxParticleEmitter;return this.particleEmitterType=o,this.direction1=t,this.direction2=i,this.minEmitBox=r,this.maxEmitBox=n,o},t.prototype.clone=function(i,r){var n=null,o=null;if(null!=this.customShader){o=this.customShader;var s=o.shaderOptions.defines.length>0?o.shaderOptions.defines.join("\n"):"";n=this._scene.getEngine().createEffectForParticles(o.shaderPath.fragmentElement,o.shaderOptions.uniforms,o.shaderOptions.samplers,s)}else this._customEffect&&(n=this._customEffect);var a=new t(i,this._capacity,this._scene,n);return a.customShader=o,e.Tools.DeepCopy(this,a,["particles","customShader"]),void 0===r&&(r=this.emitter),a.emitter=r,this.particleTexture&&(a.particleTexture=new e.Texture(this.particleTexture.url,this._scene)),this.preventAutoStart||a.start(),a},t.prototype.serialize=function(){var e={} -;return t._Serialize(e,this),e.textureMask=this.textureMask.asArray(),e.customShader=this.customShader,e.preventAutoStart=this.preventAutoStart,e.isAnimationSheetEnabled=this._isAnimationSheetEnabled,e},t._Serialize=function(t,i){if(t.name=i.name,t.id=i.id,t.capacity=i.getCapacity(),i.emitter.position){var r=i.emitter;t.emitterId=r.id}else{var n=i.emitter;t.emitter=n.asArray()}i.particleEmitterType&&(t.particleEmitterType=i.particleEmitterType.serialize()),i.particleTexture&&(t.textureName=i.particleTexture.name),e.Animation.AppendSerializedAnimations(i,t),t.renderingGroupId=i.renderingGroupId,t.isBillboardBased=i.isBillboardBased,t.minAngularSpeed=i.minAngularSpeed,t.maxAngularSpeed=i.maxAngularSpeed,t.minSize=i.minSize,t.maxSize=i.maxSize,t.minScaleX=i.minScaleX,t.maxScaleX=i.maxScaleX,t.minScaleY=i.minScaleY,t.maxScaleY=i.maxScaleY,t.minEmitPower=i.minEmitPower,t.maxEmitPower=i.maxEmitPower,t.minLifeTime=i.minLifeTime,t.maxLifeTime=i.maxLifeTime,t.emitRate=i.emitRate,t.gravity=i.gravity.asArray(),t.noiseStrength=i.noiseStrength.asArray(),t.color1=i.color1.asArray(),t.color2=i.color2.asArray(),t.colorDead=i.colorDead.asArray(),t.updateSpeed=i.updateSpeed,t.targetStopDuration=i.targetStopDuration,t.blendMode=i.blendMode,t.preWarmCycles=i.preWarmCycles,t.preWarmStepOffset=i.preWarmStepOffset,t.minInitialRotation=i.minInitialRotation,t.maxInitialRotation=i.maxInitialRotation,t.startSpriteCellID=i.startSpriteCellID,t.endSpriteCellID=i.endSpriteCellID,t.spriteCellChangeSpeed=i.spriteCellChangeSpeed,t.spriteCellWidth=i.spriteCellWidth,t.spriteCellHeight=i.spriteCellHeight;var o=i.getColorGradients();if(o){t.colorGradients=[];for(var s=0,a=o;s0?a.shaderOptions.defines.join("\n"):"";s=r.getEngine().createEffectForParticles(a.shaderPath.fragmentElement,a.shaderOptions.uniforms,a.shaderOptions.samplers,l)}var h=new t(o,i.capacity,r,s,i.isAnimationSheetEnabled);return h.customShader=a,i.id&&(h.id=i.id),i.preventAutoStart&&(h.preventAutoStart=i.preventAutoStart),t._Parse(i,h,r,n),h.textureMask=e.Color4.FromArray(i.textureMask),h.preventAutoStart||h.start(),h},t.BLENDMODE_ONEONE=0,t.BLENDMODE_STANDARD=1,t.BLENDMODE_ADD=2,t})();e.ParticleSystem=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.direction1=new e.Vector3(0,1,0),this.direction2=new e.Vector3(0,1,0),this.minEmitBox=new e.Vector3(-.5,-.5,-.5),this.maxEmitBox=new e.Vector3(.5,.5,.5)}return t.prototype.startDirectionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.direction1.x,this.direction2.x),o=e.Scalar.RandomRange(this.direction1.y,this.direction2.y),s=e.Scalar.RandomRange(this.direction1.z,this.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(n,o,s,t,i)},t.prototype.startPositionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),o=e.Scalar.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),s=e.Scalar.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);e.Vector3.TransformCoordinatesFromFloatsToRef(n,o,s,t,i)},t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)},t.prototype.getEffectDefines=function(){return"#define BOXEMITTER"},t.prototype.getClassName=function(){return"BoxParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e},t.prototype.parse=function(t){e.Vector3.FromArrayToRef(t.direction1,0,this.direction1),e.Vector3.FromArrayToRef(t.direction2,0,this.direction2),e.Vector3.FromArrayToRef(t.minEmitBox,0,this.minEmitBox),e.Vector3.FromArrayToRef(t.maxEmitBox,0,this.maxEmitBox)},t})();e.BoxParticleEmitter=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i){void 0===e&&(e=1),void 0===t&&(t=Math.PI),void 0===i&&(i=0),this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}return Object.defineProperty(t.prototype,"radius",{get:function(){return this._radius},set:function(e){this._radius=e,this._buildHeight()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._buildHeight()},enumerable:!0,configurable:!0}),t.prototype._buildHeight=function(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1},t.prototype.startDirectionFunction=function(t,i,r){if(1===Math.abs(Math.cos(this._angle)))e.Vector3.TransformNormalFromFloatsToRef(0,1,0,t,i);else{var n=r.position.subtract(t.getTranslation()).normalize(),o=e.Scalar.RandomRange(0,this.directionRandomizer),s=e.Scalar.RandomRange(0,this.directionRandomizer),a=e.Scalar.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=s,n.z+=a,n.normalize(),e.Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,t,i)}},t.prototype.startPositionFunction=function(t,i,r){var n,o=e.Scalar.RandomRange(0,2*Math.PI);this.emitFromSpawnPointOnly?n=1e-4:(n=e.Scalar.RandomRange(0,this.heightRange),n=1-n*n);var s=this._radius-e.Scalar.RandomRange(0,this._radius*this.radiusRange);s*=n;var a=s*Math.sin(o),l=s*Math.cos(o),h=n*this._height;e.Vector3.TransformCoordinatesFromFloatsToRef(a,h,l,t,i)},t.prototype.clone=function(){var i=new t(this._radius,this._angle,this.directionRandomizer);return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)},t.prototype.getEffectDefines=function(){var e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e},t.prototype.getClassName=function(){return"ConeParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e},t.prototype.parse=function(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer},t})();e.ConeParticleEmitter=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return t.prototype.startDirectionFunction=function(t,i,r){var n=r.position.subtract(t.getTranslation()).normalize(),o=e.Scalar.RandomRange(0,this.directionRandomizer),s=e.Scalar.RandomRange(0,this.directionRandomizer),a=e.Scalar.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=s,n.z+=a,n.normalize(),e.Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,t,i)},t.prototype.startPositionFunction=function(t,i,r){var n=this.radius-e.Scalar.RandomRange(0,this.radius*this.radiusRange),o=e.Scalar.RandomRange(0,1),s=e.Scalar.RandomRange(0,2*Math.PI),a=Math.acos(2*o-1),l=n*Math.cos(s)*Math.sin(a),h=n*Math.cos(a),c=n*Math.sin(s)*Math.sin(a);e.Vector3.TransformCoordinatesFromFloatsToRef(l,h,c,t,i)},t.prototype.clone=function(){var i=new t(this.radius,this.directionRandomizer);return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},t.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER"},t.prototype.getClassName=function(){return"SphereParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},t.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},t})();e.SphereParticleEmitter=t;var i=(function(t){function i(i,r,n){void 0===i&&(i=1),void 0===r&&(r=new e.Vector3(0,1,0)),void 0===n&&(n=new e.Vector3(0,1,0));var o=t.call(this,i)||this;return o.direction1=r,o.direction2=n,o}return o(i,t),i.prototype.startDirectionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.direction1.x,this.direction2.x),o=e.Scalar.RandomRange(this.direction1.y,this.direction2.y),s=e.Scalar.RandomRange(this.direction1.z,this.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(n,o,s,t,i)},i.prototype.clone=function(){var t=new i(this.radius,this.direction1,this.direction2);return e.Tools.DeepCopy(this,t),t},i.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},i.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"},i.prototype.getClassName=function(){return"SphereDirectedParticleEmitter"},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e},i.prototype.parse=function(e){t.prototype.parse.call(this,e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)},i})(t);e.SphereDirectedParticleEmitter=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return t.prototype.startDirectionFunction=function(t,i,r){var n=r.position.subtract(t.getTranslation()).normalize(),o=e.Scalar.RandomRange(0,this.directionRandomizer),s=e.Scalar.RandomRange(0,this.directionRandomizer),a=e.Scalar.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=s,n.z+=a,n.normalize(),e.Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,t,i)},t.prototype.startPositionFunction=function(t,i,r){var n=this.radius-e.Scalar.RandomRange(0,this.radius*this.radiusRange),o=e.Scalar.RandomRange(0,1),s=e.Scalar.RandomRange(0,2*Math.PI),a=Math.acos(2*o-1),l=n*Math.cos(s)*Math.sin(a),h=n*Math.cos(a),c=n*Math.sin(s)*Math.sin(a);e.Vector3.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,t,i)},t.prototype.clone=function(){var i=new t(this.radius,this.directionRandomizer);return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},t.prototype.getEffectDefines=function(){return"#define HEMISPHERICEMITTER"},t.prototype.getClassName=function(){return"HemisphericParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},t.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},t})();e.HemisphericParticleEmitter=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.direction1=new e.Vector3(0,1,0),this.direction2=new e.Vector3(0,1,0)}return t.prototype.startDirectionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.direction1.x,this.direction2.x),o=e.Scalar.RandomRange(this.direction1.y,this.direction2.y),s=e.Scalar.RandomRange(this.direction1.z,this.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(n,o,s,t,i)},t.prototype.startPositionFunction=function(t,i,r){e.Vector3.TransformCoordinatesFromFloatsToRef(0,0,0,t,i)},t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},t.prototype.getEffectDefines=function(){return"#define POINTEMITTER"},t.prototype.getClassName=function(){return"PointParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e},t.prototype.parse=function(t){e.Vector3.FromArrayToRef(t.direction1,0,this.direction1),e.Vector3.FromArrayToRef(t.direction2,0,this.direction2)},t})();e.PointParticleEmitter=t})(r||(r={}));var r;!(function(e){e.AbstractScene.AddParser(e.SceneComponentConstants.NAME_PARTICLESYSTEM,(function(t,i,r,n){var o=e.AbstractScene.GetIndividualParser(e.SceneComponentConstants.NAME_PARTICLESYSTEM);if(o&&void 0!==t.particleSystems&&null!==t.particleSystems)for(var s=0,a=t.particleSystems.length;s4&&(s.push(e.VertexBuffer.MatricesIndicesExtraKind),s.push(e.VertexBuffer.MatricesWeightsExtraKind)),o.push("#define NUM_BONE_INFLUENCERS "+t.numBoneInfluencers),o.push("#define BonesPerMesh "+(t.skeleton.bones.length+1)),a.addCPUSkinningFallback(0,t),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones")):o.push("#define NUM_BONE_INFLUENCERS 0");for(var h in this._textures)if(!this._textures[h].isReady())return!1;t&&this._shouldTurnAlphaTestOn(t)&&o.push("#define ALPHATEST");var c=this._effect,u=o.join("\n");return this._effect=n.createEffect(this._shaderPath,{attributes:s,uniformsNames:this._options.uniforms,uniformBuffersNames:this._options.uniformBuffers,samplers:this._options.samplers,defines:u,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError},n),!!this._effect.isReady()&&(c!==this._effect&&r.resetCachedMaterial(),this._renderId=r.getRenderId(),!0)},i.prototype.bindOnlyWorldMatrix=function(e){var t=this.getScene();this._effect&&(-1!==this._options.uniforms.indexOf("world")&&this._effect.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),this._effect.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&this._effect.setMatrix("worldViewProjection",e.multiply(t.getTransformMatrix())))},i.prototype.bind=function(t,i){if(this.bindOnlyWorldMatrix(t),this._effect&&this.getScene().getCachedMaterial()!==this){-1!==this._options.uniforms.indexOf("view")&&this._effect.setMatrix("view",this.getScene().getViewMatrix()),-1!==this._options.uniforms.indexOf("projection")&&this._effect.setMatrix("projection",this.getScene().getProjectionMatrix()),-1!==this._options.uniforms.indexOf("viewProjection")&&this._effect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.MaterialHelper.BindBonesParameters(i,this._effect);var r;for(r in this._textures)this._effect.setTexture(r,this._textures[r]);for(r in this._textureArrays)this._effect.setTextureArray(r,this._textureArrays[r]);for(r in this._ints)this._effect.setInt(r,this._ints[r]);for(r in this._floats)this._effect.setFloat(r,this._floats[r]);for(r in this._floatsArrays)this._effect.setArray(r,this._floatsArrays[r]);for(r in this._colors3)this._effect.setColor3(r,this._colors3[r]);for(r in this._colors3Arrays)this._effect.setArray3(r,this._colors3Arrays[r]);for(r in this._colors4){var n=this._colors4[r];this._effect.setFloat4(r,n.r,n.g,n.b,n.a)}for(r in this._vectors2)this._effect.setVector2(r,this._vectors2[r]);for(r in this._vectors3)this._effect.setVector3(r,this._vectors3[r]);for(r in this._vectors4)this._effect.setVector4(r,this._vectors4[r]);for(r in this._matrices)this._effect.setMatrix(r,this._matrices[r]);for(r in this._matrices3x3)this._effect.setMatrix3x3(r,this._matrices3x3[r]);for(r in this._matrices2x2)this._effect.setMatrix2x2(r,this._matrices2x2[r]);for(r in this._vectors2Arrays)this._effect.setArray2(r,this._vectors2Arrays[r]);for(r in this._vectors3Arrays)this._effect.setArray3(r,this._vectors3Arrays[r])}this._afterBind(i)},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);for(var i in this._textures)e.push(this._textures[i]);for(var i in this._textureArrays)for(var r=this._textureArrays[i],n=0;nthis._maxX||ithis._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var s=this._getFacetAt(t,i),a=-(s.x*t+s.z*i+s.w)/s.y;return e.Vector3.TransformCoordinatesFromFloatsToRef(0,a,0,r,o),o.y},i.prototype.getNormalAtCoordinates=function(t,i){var r=new e.Vector3(0,1,0);return this.getNormalAtCoordinatesToRef(t,i,r),r},i.prototype.getNormalAtCoordinatesToRef=function(t,i,r){var n=this.getWorldMatrix(),o=e.Tmp.Matrix[5];n.invertToRef(o);var s=e.Tmp.Vector3[8];if(e.Vector3.TransformCoordinatesFromFloatsToRef(t,0,i,o,s),t=s.x,i=s.z,tthis._maxX||ithis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var a=this._getFacetAt(t,i);return e.Vector3.TransformNormalFromFloatsToRef(a.x,a.y,a.z,n,r),this},i.prototype.updateCoordinateHeights=function(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this},i.prototype._getFacetAt=function(e,t){var i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),n=this._heightQuads[r*this._subdivisionsX+i];return t=0;s--){var a=t[s],l=a.getParent();if(l){var h=this._debugLines[n];h||(h=[e.Vector3.Zero(),e.Vector3.Zero()],this._debugLines[n]=h),a.getAbsolutePositionToRef(this.mesh,h[0]),l.getAbsolutePositionToRef(this.mesh,h[1]),h[0].subtractInPlace(o),h[1].subtractInPlace(o),n++}}},t.prototype.update=function(){this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteTransforms(),void 0===this.skeleton.bones[0].length?this._getLinesForBonesNoLength(this.skeleton.bones,this.mesh.getWorldMatrix()):this._getLinesForBonesWithLength(this.skeleton.bones,this.mesh.getWorldMatrix()),this._debugMesh?e.MeshBuilder.CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:this._debugMesh},this._scene):(this._debugMesh=e.MeshBuilder.CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:null},this._scene),this._debugMesh.renderingGroupId=this.renderingGroupId),this._debugMesh.position.copyFrom(this.mesh.position),this._debugMesh.color=this.color},t.prototype.dispose=function(){this._debugMesh&&(this.isEnabled=!1,this._debugMesh.dispose(),this._debugMesh=null)},t})();t.SkeletonViewer=i})(e.Debug||(e.Debug={}))})(r||(r={}));var r;!(function(e){!(function(t){var i=(function(){function t(t,i){void 0===i&&(i=1),this._xline=[e.Vector3.Zero(),e.Vector3.Zero()],this._yline=[e.Vector3.Zero(),e.Vector3.Zero()],this._zline=[e.Vector3.Zero(),e.Vector3.Zero()],this.scaleLines=1,this.scaleLines=i,this._xmesh=e.Mesh.CreateLines("xline",this._xline,t,!0),this._ymesh=e.Mesh.CreateLines("yline",this._yline,t,!0),this._zmesh=e.Mesh.CreateLines("zline",this._zline,t,!0),this._xmesh.renderingGroupId=2,this._ymesh.renderingGroupId=2,this._zmesh.renderingGroupId=2,this._xmesh.material.checkReadyOnlyOnce=!0,this._xmesh.color=new e.Color3(1,0,0),this._ymesh.material.checkReadyOnlyOnce=!0,this._ymesh.color=new e.Color3(0,1,0),this._zmesh.material.checkReadyOnlyOnce=!0,this._zmesh.color=new e.Color3(0,0,1),this.scene=t}return t.prototype.update=function(t,i,r,n){var o=this.scaleLines;this._xmesh&&this._xmesh.position.copyFrom(t),this._ymesh&&this._ymesh.position.copyFrom(t),this._zmesh&&this._zmesh.position.copyFrom(t);var s=this._xline[1];s.x=i.x*o,s.y=i.y*o,s.z=i.z*o,e.Mesh.CreateLines("",this._xline,null,!1,this._xmesh),s=this._yline[1],s.x=r.x*o,s.y=r.y*o,s.z=r.z*o,e.Mesh.CreateLines("",this._yline,null,!1,this._ymesh),s=this._zline[1],s.x=n.x*o,s.y=n.y*o,s.z=n.z*o,e.Mesh.CreateLines("",this._zline,null,!1,this._zmesh)},t.prototype.dispose=function(){this._xmesh&&this._xmesh.dispose(),this._ymesh&&this._ymesh.dispose(),this._zmesh&&this._zmesh.dispose(),this._xmesh=null,this._ymesh=null,this._zmesh=null,this.scene=null},t})();t.AxesViewer=i})(e.Debug||(e.Debug={}))})(r||(r={}));var r;!(function(e){!(function(t){var i=(function(t){function i(i,r,n,o){void 0===o&&(o=1);var s=t.call(this,i,o)||this;return s.pos=e.Vector3.Zero(),s.xaxis=e.Vector3.Zero(),s.yaxis=e.Vector3.Zero(),s.zaxis=e.Vector3.Zero(),s.mesh=n,s.bone=r,s}return o(i,t),i.prototype.update=function(){if(this.mesh&&this.bone){var i=this.bone;i.getAbsolutePositionToRef(this.mesh,this.pos),i.getDirectionToRef(e.Axis.X,this.mesh,this.xaxis),i.getDirectionToRef(e.Axis.Y,this.mesh,this.yaxis),i.getDirectionToRef(e.Axis.Z,this.mesh,this.zaxis),t.prototype.update.call(this,this.pos,this.xaxis,this.yaxis,this.zaxis)}},i.prototype.dispose=function(){this.mesh&&(this.mesh=null,this.bone=null,t.prototype.dispose.call(this))},i})(t.AxesViewer);t.BoneAxesViewer=i})(e.Debug||(e.Debug={}))})(r||(r={}));var r;!(function(e){var t=(function(){function t(e){this.ray=e}return t.CreateAndShow=function(e,i,r){var n=new t(e);return n.show(i,r),n},t.prototype.show=function(t,i){if(!this._renderFunction&&this.ray){var r=this.ray;this._renderFunction=this._render.bind(this),this._scene=t,this._renderPoints=[r.origin,r.origin.add(r.direction.scale(r.length))],this._renderLine=e.Mesh.CreateLines("ray",this._renderPoints,t,!0),this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}i&&this._renderLine&&this._renderLine.color.copyFrom(i)},t.prototype.hide=function(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])},t.prototype._render=function(){var t=this.ray;if(t){var i=this._renderPoints[1],r=Math.min(t.length,1e6);i.copyFrom(t.direction),i.scaleInPlace(r),i.addInPlace(t.origin),e.Mesh.CreateLines("ray",this._renderPoints,this._scene,!0,this._renderLine)}},t.prototype.attachToMesh=function(t,i,r,n){this._attachedToMesh=t;var o=this.ray;o&&(o.direction||(o.direction=e.Vector3.Zero()),o.origin||(o.origin=e.Vector3.Zero()),n&&(o.length=n),r||(r=e.Vector3.Zero()),i||(i=new e.Vector3(0,0,-1)),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(i),this._meshSpaceOrigin.copyFrom(r)):(this._meshSpaceDirection=i.clone(),this._meshSpaceOrigin=r.clone()),this._updateToMeshFunction||(this._updateToMeshFunction=this._updateToMesh.bind(this),this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction)),this._updateToMesh())},t.prototype.detachFromMesh=function(){this._attachedToMesh&&(this._updateToMeshFunction&&this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction),this._attachedToMesh=null,this._updateToMeshFunction=null)},t.prototype._updateToMesh=function(){var t=this.ray;if(this._attachedToMesh&&t){if(this._attachedToMesh._isDisposed)return void this.detachFromMesh();this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,t.direction),e.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),t.origin)}},t.prototype.dispose=function(){this.hide(),this.detachFromMesh(),this.ray=null},t})();e.RayHelper=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){this.BJSINSPECTOR="undefined"!=typeof INSPECTOR?INSPECTOR:void 0,this.onPropertyChangedObservable=new e.Observable,this._scene=t}return t.prototype._createInspector=function(e){void 0===e&&(e={});var t=e.popup||!1,i=e.initialTab||0,r=e.parentElement||null;this._inspector||(this.BJSINSPECTOR=this.BJSINSPECTOR||"undefined"!=typeof INSPECTOR?INSPECTOR:void 0,this._inspector=new this.BJSINSPECTOR.Inspector(this._scene,t,i,r,e.newColors))},t.prototype.isVisible=function(){return!!this._inspector},t.prototype.hide=function(){if(this._inspector){try{this._inspector.dispose()}catch(e){}this.onPropertyChangedObservable.clear(),this._inspector=null}},t.prototype.show=function(i){void 0===i&&(i={}),void 0===this.BJSINSPECTOR?e.Tools.LoadScript(t.InspectorURL,this._createInspector.bind(this,i)):this._createInspector(i)},t.prototype.getActiveTab=function(){return this._inspector?this._inspector.getActiveTabIndex():-1},t.InspectorURL="https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js",t})();e.DebugLayer=t})(r||(r={}));var r;!(function(e){!(function(t){var i=(function(){function t(t){this._impostors=[],this._meshes=[],this._numMeshes=0,this._scene=t||e.Engine.LastCreatedScene;var i=this._scene.getPhysicsEngine();i&&(this._physicsEnginePlugin=i.getPhysicsPlugin())}return t.prototype._updateDebugMeshes=function(){for(var e=this._physicsEnginePlugin,t=0;t0?(this._meshes[i]=this._meshes[this._numMeshes],this._impostors[i]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}},t.prototype._getDebugMaterial=function(t){return this._debugMaterial||(this._debugMaterial=new e.StandardMaterial("",t),this._debugMaterial.wireframe=!0),this._debugMaterial},t.prototype._getDebugBoxMesh=function(t){return this._debugBoxMesh||(this._debugBoxMesh=e.MeshBuilder.CreateBox("physicsBodyBoxViewMesh",{size:1},t),this._debugBoxMesh.renderingGroupId=1,this._debugBoxMesh.rotationQuaternion=e.Quaternion.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(t),t.removeMesh(this._debugBoxMesh)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")},t.prototype._getDebugSphereMesh=function(t){return this._debugSphereMesh||(this._debugSphereMesh=e.MeshBuilder.CreateSphere("physicsBodySphereViewMesh",{diameter:1},t),this._debugSphereMesh.renderingGroupId=1,this._debugSphereMesh.rotationQuaternion=e.Quaternion.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(t),t.removeMesh(this._debugSphereMesh)),this._debugSphereMesh.createInstance("physicsBodyBoxViewInstance")},t.prototype._getDebugMesh=function(t,i){var r=null;if(t.type==e.PhysicsImpostor.BoxImpostor)r=this._getDebugBoxMesh(i),t.getBoxSizeToRef(r.scaling);else if(t.type==e.PhysicsImpostor.SphereImpostor){r=this._getDebugSphereMesh(i);var n=t.getRadius();r.scaling.x=2*n,r.scaling.y=2*n,r.scaling.z=2*n}return r},t.prototype.dispose=function(){for(var e=0;e1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction1",{get:function(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction2",{get:function(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minEmitBox",{get:function(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxEmitBox",{get:function(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)},enumerable:!0,configurable:!0}),t.prototype.getCapacity=function(){return this._capacity},Object.defineProperty(t.prototype,"activeParticleCount",{get:function(){return this._activeCount},set:function(e){this._activeCount=Math.min(e,this._capacity)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isAnimationSheetEnabled",{get:function(){return this._isAnimationSheetEnabled},enumerable:!0,configurable:!0}),t.prototype.isReady=function(){return this._updateEffect?!!(this.emitter&&this._updateEffect.isReady()&&this._renderEffect.isReady()&&this.particleTexture&&this.particleTexture.isReady()):(this._recreateUpdateEffect(),this._recreateRenderEffect(),!1)},t.prototype.isStarted=function(){return this._started},t.prototype.start=function(e){var t=this;if(void 0===e&&(e=0),e)return void setTimeout((function(){t.start(0)}),e);this._started=!0,this._stopped=!1,this._preWarmDone=!1},t.prototype.stop=function(){this._stopped=!0},t.prototype.reset=function(){this._releaseBuffers(),this._releaseVAOs(),this._currentActiveCount=0,this._targetIndex=0},t.prototype.getClassName=function(){return"GPUParticleSystem"},Object.defineProperty(t.prototype,"isBillboardBased",{get:function(){return this._isBillboardBased},set:function(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._releaseBuffers())},enumerable:!0,configurable:!0}),t.prototype.getColorGradients=function(){return this._colorGradients},t.prototype.getSizeGradients=function(){return this._sizeGradients},t.prototype.getAngularSpeedGradients=function(){return this._angularSpeedGradients},t.prototype.getVelocityGradients=function(){return this._velocityGradients},t.prototype._removeGradient=function(e,t,i){if(!t)return this;for(var r=0,n=0,o=t;nt.gradient?1:0})),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeColorGradient=function(e){return this._removeGradient(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this},t.prototype._addFactorGradient=function(t,i,r){var n=new e.FactorGradient;n.gradient=i,n.factor1=r,t.push(n),t.sort((function(e,t){return e.gradientt.gradient?1:0})),this._releaseBuffers()},t.prototype.addSizeGradient=function(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeSizeGradient=function(e){return this._removeGradient(e,this._sizeGradients,this._sizeGradientsTexture), -this._sizeGradientsTexture=null,this},t.prototype.addAngularSpeedGradient=function(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeAngularSpeedGradient=function(e){return this._removeGradient(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this},t.prototype.addVelocityGradient=function(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeVelocityGradient=function(e){return this._removeGradient(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this},t.prototype._createUpdateVAO=function(e){var t={};t.position=e.createVertexBuffer("position",0,3),t.age=e.createVertexBuffer("age",3,1),t.life=e.createVertexBuffer("life",4,1),t.seed=e.createVertexBuffer("seed",5,4),t.size=e.createVertexBuffer("size",9,3);var i=12;this._colorGradientsTexture||(t.color=e.createVertexBuffer("color",i,4),i+=4),t.direction=e.createVertexBuffer("direction",i,3),i+=3,this._isBillboardBased||(t.initialDirection=e.createVertexBuffer("initialDirection",i,3),i+=3),this._angularSpeedGradientsTexture?(t.angle=e.createVertexBuffer("angle",i,1),i+=1):(t.angle=e.createVertexBuffer("angle",i,2),i+=2),this._isAnimationSheetEnabled&&(t.cellIndex=e.createVertexBuffer("cellIndex",i,1),i+=1);var r=this._engine.recordVertexArrayObject(t,null,this._updateEffect);return this._engine.bindArrayBuffer(null),r},t.prototype._createRenderVAO=function(e,t){var i={};i.position=e.createVertexBuffer("position",0,3,this._attributesStrideSize,!0),i.age=e.createVertexBuffer("age",3,1,this._attributesStrideSize,!0),i.life=e.createVertexBuffer("life",4,1,this._attributesStrideSize,!0),i.size=e.createVertexBuffer("size",9,3,this._attributesStrideSize,!0);var r=12;this._colorGradientsTexture||(i.color=e.createVertexBuffer("color",r,4,this._attributesStrideSize,!0),r+=4),r+=3,this._isBillboardBased||(i.initialDirection=e.createVertexBuffer("initialDirection",r,3,this._attributesStrideSize,!0),r+=3),i.angle=e.createVertexBuffer("angle",r,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?r++:r+=2,this._isAnimationSheetEnabled&&(i.cellIndex=e.createVertexBuffer("cellIndex",r,1,this._attributesStrideSize,!0),r+=1),i.offset=t.createVertexBuffer("offset",0,2),i.uv=t.createVertexBuffer("uv",2,2);var n=this._engine.recordVertexArrayObject(i,null,this._renderEffect);return this._engine.bindArrayBuffer(null),n},t.prototype._initialize=function(t){if(void 0===t&&(t=!1),!this._buffer0||t){var i=this._scene.getEngine(),r=new Array;this.isBillboardBased||(this._attributesStrideSize+=3),this._colorGradientsTexture&&(this._attributesStrideSize-=4),this._angularSpeedGradientsTexture&&(this._attributesStrideSize-=1),this._isAnimationSheetEnabled&&(this._attributesStrideSize+=1);for(var n=0;n=this.targetStopDuration&&this.stop()},t.prototype._createFactorGradientTexture=function(t,i){var r=this[i];if(t&&t.length&&!r){for(var n=new Float32Array(this._rawTextureWidth),o=0;o1){var r=0|this._accumulatedCount;this._accumulatedCount-=r,this._currentActiveCount=Math.min(this._activeCount,this._currentActiveCount+r)}if(!this._currentActiveCount)return 0;this._engine.enableEffect(this._updateEffect),this._engine.setState(!1),this._updateEffect.setFloat("currentCount",this._currentActiveCount),this._updateEffect.setFloat("timeDelta",this._timeDelta),this._updateEffect.setFloat("stopFactor",this._stopped?0:1),this._updateEffect.setTexture("randomSampler",this._randomTexture),this._updateEffect.setTexture("randomSampler2",this._randomTexture2),this._updateEffect.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateEffect.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateEffect.setDirectColor4("color1",this.color1),this._updateEffect.setDirectColor4("color2",this.color2)),this._updateEffect.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateEffect.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateEffect.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateEffect.setVector3("gravity",this.gravity),this._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._sizeGradientsTexture),this._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._angularSpeedGradientsTexture),this._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._velocityGradientsTexture),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateEffect),this._isAnimationSheetEnabled&&this._updateEffect.setFloat3("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed),this.noiseTexture&&(this._updateEffect.setTexture("noiseSampler",this.noiseTexture),this._updateEffect.setVector3("noiseStrength",this.noiseStrength));var n;if(this.emitter.position){n=this.emitter.getWorldMatrix()}else{var o=this.emitter;n=e.Matrix.Translation(o.x,o.y,o.z)}if(this._updateEffect.setMatrix("emitterWM",n),this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex],null),this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer()),this._engine.setRasterizerState(!1),this._engine.beginTransformFeedback(!0),this._engine.drawArraysType(e.Material.PointListDrawMode,0,this._currentActiveCount),this._engine.endTransformFeedback(),this._engine.setRasterizerState(!0),this._engine.bindTransformFeedbackBuffer(null),!t){this._engine.enableEffect(this._renderEffect);var s=this._scene.getViewMatrix();if(this._renderEffect.setMatrix("view",s),this._renderEffect.setMatrix("projection",this._scene.getProjectionMatrix()),this._renderEffect.setTexture("textureSampler",this.particleTexture),this._renderEffect.setVector2("translationPivot",this.translationPivot),this._colorGradientsTexture?this._renderEffect.setTexture("colorGradientSampler",this._colorGradientsTexture):this._renderEffect.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){var a=this.particleTexture.getBaseSize();this._renderEffect.setFloat3("sheetInfos",this.spriteCellWidth/a.width,this.spriteCellHeight/a.height,a.width/this.spriteCellWidth)}if(this._isBillboardBased){var l=this._scene.activeCamera;this._renderEffect.setVector3("eyePosition",l.globalPosition)}if(this._scene.clipPlane){var h=this._scene.clipPlane,c=s.clone();c.invert(),this._renderEffect.setMatrix("invView",c),this._renderEffect.setFloat4("vClipPlane",h.normal.x,h.normal.y,h.normal.z,h.d)}switch(this.blendMode){case e.ParticleSystem.BLENDMODE_ADD:this._engine.setAlphaMode(e.Engine.ALPHA_ADD);break;case e.ParticleSystem.BLENDMODE_ONEONE:this._engine.setAlphaMode(e.Engine.ALPHA_ONEONE);break;case e.ParticleSystem.BLENDMODE_STANDARD:this._engine.setAlphaMode(e.Engine.ALPHA_COMBINE)}this.forceDepthWrite&&this._engine.setDepthWrite(!0),this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex],null),this._engine.drawArraysType(e.Material.TriangleFanDrawMode,0,4,this._currentActiveCount),this._engine.setAlphaMode(e.Engine.ALPHA_DISABLE)}2===++this._targetIndex&&(this._targetIndex=0);var u=this._sourceBuffer;return this._sourceBuffer=this._targetBuffer,this._targetBuffer=u,this._currentActiveCount},t.prototype.rebuild=function(){this._initialize(!0)},t.prototype._releaseBuffers=function(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null)},t.prototype._releaseVAOs=function(){if(this._updateVAO){for(var e=0;e-1&&this._scene.particleSystems.splice(t,1),this._releaseBuffers(),this._releaseVAOs(),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._randomTexture&&(this._randomTexture.dispose(),this._randomTexture=null),this._randomTexture2&&(this._randomTexture2.dispose(),this._randomTexture2=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.prototype.clone=function(i,r){var n=new t(i,{capacity:this._capacity,randomTextureSize:this._randomTextureSize},this._scene);return e.Tools.DeepCopy(this,n),void 0===r&&(r=this.emitter),n.emitter=r,this.particleTexture&&(n.particleTexture=new e.Texture(this.particleTexture.url,this._scene)),n},t.prototype.serialize=function(){var t={};return e.ParticleSystem._Serialize(t,this),t.activeParticleCount=this.activeParticleCount,t},t.Parse=function(i,r,n){var o=i.name,s=new t(o,{capacity:i.capacity,randomTextureSize:i.randomTextureSize},r);return i.activeParticleCount&&(s.activeParticleCount=i.activeParticleCount),e.ParticleSystem._Parse(i,s,r,n),s},t})();e.GPUParticleSystem=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a,l){void 0===l&&(l=null),this.idx=0,this.color=new e.Color4(1,1,1,1),this.position=e.Vector3.Zero(),this.rotation=e.Vector3.Zero(),this.scaling=e.Vector3.One(),this.uvs=new e.Vector4(0,0,1,1),this.velocity=e.Vector3.Zero(),this.pivot=e.Vector3.Zero(),this.translateFromPivot=!1,this.alive=!0,this.isVisible=!0,this._pos=0,this._ind=0,this.shapeId=0,this.idxInShape=0,this._stillInvisible=!1,this._rotationMatrix=[1,0,0,0,1,0,0,0,1],this.parentId=null,this._globalPosition=e.Vector3.Zero(),this.idx=t,this._pos=i,this._ind=r,this._model=n,this.shapeId=o,this.idxInShape=s,this._sps=a,l&&(this._modelBoundingInfo=l,this._boundingInfo=new e.BoundingInfo(l.minimum,l.maximum))}return Object.defineProperty(t.prototype,"scale",{get:function(){return this.scaling},set:function(e){this.scaling=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"quaternion",{get:function(){return this.rotationQuaternion},set:function(e){this.rotationQuaternion=e},enumerable:!0,configurable:!0}),t.prototype.intersectsMesh=function(t){return!(!this._boundingInfo||!t._boundingInfo)&&(this._sps._bSphereOnly?e.BoundingSphere.Intersects(this._boundingInfo.boundingSphere,t._boundingInfo.boundingSphere):this._boundingInfo.intersects(t._boundingInfo,!1))},t})();e.SolidParticle=t;var i=(function(){function e(e,t,i,r,n,o){this._indicesLength=0,this.shapeID=e,this._shape=t,this._indicesLength=i,this._shapeUV=r,this._positionFunction=n,this._vertexFunction=o}return e})();e.ModelShape=i;var r=(function(){function e(){this.ind=0,this.indicesLength=0,this.sqDistance=0}return e})();e.DepthSortedParticle=r})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){this.particles=new Array,this.nbParticles=0,this.billboard=!1,this.recomputeNormals=!0,this.counter=0,this.vars={},this._bSphereOnly=!1,this._bSphereRadiusFactor=1,this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._index=0,this._updatable=!0,this._pickable=!1,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._depthSort=!1,this._shapeCounter=0,this._copy=new e.SolidParticle(0,0,0,null,0,0,this),this._color=new e.Color4(0,0,0,0),this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeParticleVertex=!1,this._computeBoundingBox=!1,this._depthSortParticles=!0,this._cam_axisZ=e.Vector3.Zero(),this._cam_axisY=e.Vector3.Zero(),this._cam_axisX=e.Vector3.Zero(),this._axisZ=e.Axis.Z,this._camDir=e.Vector3.Zero(),this._camInvertedPosition=e.Vector3.Zero(),this._rotMatrix=new e.Matrix,this._invertMatrix=new e.Matrix,this._rotated=e.Vector3.Zero(),this._quaternion=new e.Quaternion,this._vertex=e.Vector3.Zero(),this._normal=e.Vector3.Zero(),this._yaw=0,this._pitch=0,this._roll=0,this._halfroll=0,this._halfpitch=0,this._halfyaw=0,this._sinRoll=0,this._cosRoll=0,this._sinPitch=0,this._cosPitch=0,this._sinYaw=0,this._cosYaw=0,this._mustUnrotateFixedNormals=!1,this._minimum=e.Vector3.Zero(),this._maximum=e.Vector3.Zero(),this._minBbox=e.Vector3.Zero(),this._maxBbox=e.Vector3.Zero(),this._particlesIntersect=!1,this._depthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},this._needs32Bits=!1,this._pivotBackTranslation=e.Vector3.Zero(),this._scaledPivot=e.Vector3.Zero(),this._particleHasParent=!1,this.name=t,this._scene=i||e.Engine.LastCreatedScene,this._camera=i.activeCamera,this._pickable=!!r&&r.isPickable,this._depthSort=!!r&&r.enableDepthSort,this._particlesIntersect=!!r&&r.particleIntersection,this._bSphereOnly=!!r&&r.boundingSphereOnly,this._bSphereRadiusFactor=r&&r.bSphereRadiusFactor?r.bSphereRadiusFactor:1,r&&void 0!==r.updatable?this._updatable=r.updatable:this._updatable=!0,this._pickable&&(this.pickedParticles=[]),this._depthSort&&(this.depthSortedParticles=[])}return t.prototype.buildMesh=function(){if(0===this.nbParticles){var t=e.MeshBuilder.CreateDisc("",{radius:1,tessellation:3},this._scene);this.addShape(t,1),t.dispose()}this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),this.recomputeNormals&&e.VertexData.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();var i=new e.VertexData;i.indices=this._depthSort?this._indices:this._indices32,i.set(this._positions32,e.VertexBuffer.PositionKind),i.set(this._normals32,e.VertexBuffer.NormalKind),this._uvs32.length>0&&i.set(this._uvs32,e.VertexBuffer.UVKind),this._colors32.length>0&&i.set(this._colors32,e.VertexBuffer.ColorKind);var r=new e.Mesh(this.name,this._scene);return i.applyToMesh(r,this._updatable),this.mesh=r,this.mesh.isPickable=this._pickable,this._depthSort||(this._indices=null),this._positions=null,this._normals=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0),r},t.prototype.digest=function(t,i){var r=i&&i.facetNb||1,n=i&&i.number||0,o=i&&i.delta||0,s=t.getVerticesData(e.VertexBuffer.PositionKind),a=t.getIndices(),l=t.getVerticesData(e.VertexBuffer.UVKind),h=t.getVerticesData(e.VertexBuffer.ColorKind),c=t.getVerticesData(e.VertexBuffer.NormalKind),u=0,f=a.length/3;n?(n=n>f?f:n,r=Math.round(f/n),o=0):r=r>f?f:r;for(var d=[],p=[],m=[],_=[],g=e.Vector3.Zero(),v=r;uf-r&&(r=f-u),d.length=0,p.length=0,m.length=0,_.length=0;for(var y=0,b=3*u;b<3*(u+r);b++){p.push(y);var x=a[b];d.push(s[3*x],s[3*x+1],s[3*x+2]),l&&m.push(l[2*x],l[2*x+1]),h&&_.push(h[4*x],h[4*x+1],h[4*x+2],h[4*x+3]),y++}var T,E=this.nbParticles,P=this._posToShape(d),A=this._uvsToShapeUV(m);for(T=0;T65535&&(this._needs32Bits=!0)}if(this._pickable){var b=n.length/3;for(m=0;m=this.nbParticles?this.nbParticles-1:i,this._computeBoundingBox&&(0==t&&i==this.nbParticles-1?(e.Vector3.FromFloatsToRef(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,this._minimum),e.Vector3.FromFloatsToRef(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE,this._maximum)):this.mesh._boundingInfo&&(this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum),this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum))),s=this.particles[t]._pos;var f=s/3|0;l=4*f,c=2*f;for(var d=t;d<=i;d++){if(this._particle=this.particles[d],this._shape=this._particle._model._shape,this._shapeUV=this._particle._model._shapeUV,this.updateParticle(this._particle),this._depthSort&&this._depthSortParticles){var p=this.depthSortedParticles[d];p.ind=this._particle._ind,p.indicesLength=this._particle._model._indicesLength,p.sqDistance=e.Vector3.DistanceSquared(this._particle.position,this._camInvertedPosition)}if(!this._particle.alive||this._particle._stillInvisible&&!this._particle.isVisible)u=this._shape.length,s+=3*u,l+=4*u,c+=2*u;else{if(this._particle.isVisible)for(this._particle._stillInvisible=!1,this._particleHasParent=null!==this._particle.parentId,this._scaledPivot.x=this._particle.pivot.x*this._particle.scaling.x,this._scaledPivot.y=this._particle.pivot.y*this._particle.scaling.y,this._scaledPivot.z=this._particle.pivot.z*this._particle.scaling.z,this.billboard&&(this._particle.rotation.x=0,this._particle.rotation.y=0),(this._computeParticleRotation||this.billboard)&&(this._particle.rotationQuaternion?this._quaternion.copyFrom(this._particle.rotationQuaternion):(this._yaw=this._particle.rotation.y,this._pitch=this._particle.rotation.x,this._roll=this._particle.rotation.z,this._quaternionRotationYPR()),this._quaternionToRotationMatrix()),this._particleHasParent?(this._parent=this.particles[this._particle.parentId], -this._rotated.x=this._particle.position.x*this._parent._rotationMatrix[0]+this._particle.position.y*this._parent._rotationMatrix[3]+this._particle.position.z*this._parent._rotationMatrix[6],this._rotated.y=this._particle.position.x*this._parent._rotationMatrix[1]+this._particle.position.y*this._parent._rotationMatrix[4]+this._particle.position.z*this._parent._rotationMatrix[7],this._rotated.z=this._particle.position.x*this._parent._rotationMatrix[2]+this._particle.position.y*this._parent._rotationMatrix[5]+this._particle.position.z*this._parent._rotationMatrix[8],this._particle._globalPosition.x=this._parent._globalPosition.x+this._rotated.x,this._particle._globalPosition.y=this._parent._globalPosition.y+this._rotated.y,this._particle._globalPosition.z=this._parent._globalPosition.z+this._rotated.z,(this._computeParticleRotation||this.billboard)&&(this._particle._rotationMatrix[0]=this._rotMatrix.m[0]*this._parent._rotationMatrix[0]+this._rotMatrix.m[1]*this._parent._rotationMatrix[3]+this._rotMatrix.m[2]*this._parent._rotationMatrix[6],this._particle._rotationMatrix[1]=this._rotMatrix.m[0]*this._parent._rotationMatrix[1]+this._rotMatrix.m[1]*this._parent._rotationMatrix[4]+this._rotMatrix.m[2]*this._parent._rotationMatrix[7],this._particle._rotationMatrix[2]=this._rotMatrix.m[0]*this._parent._rotationMatrix[2]+this._rotMatrix.m[1]*this._parent._rotationMatrix[5]+this._rotMatrix.m[2]*this._parent._rotationMatrix[8],this._particle._rotationMatrix[3]=this._rotMatrix.m[4]*this._parent._rotationMatrix[0]+this._rotMatrix.m[5]*this._parent._rotationMatrix[3]+this._rotMatrix.m[6]*this._parent._rotationMatrix[6],this._particle._rotationMatrix[4]=this._rotMatrix.m[4]*this._parent._rotationMatrix[1]+this._rotMatrix.m[5]*this._parent._rotationMatrix[4]+this._rotMatrix.m[6]*this._parent._rotationMatrix[7],this._particle._rotationMatrix[5]=this._rotMatrix.m[4]*this._parent._rotationMatrix[2]+this._rotMatrix.m[5]*this._parent._rotationMatrix[5]+this._rotMatrix.m[6]*this._parent._rotationMatrix[8],this._particle._rotationMatrix[6]=this._rotMatrix.m[8]*this._parent._rotationMatrix[0]+this._rotMatrix.m[9]*this._parent._rotationMatrix[3]+this._rotMatrix.m[10]*this._parent._rotationMatrix[6],this._particle._rotationMatrix[7]=this._rotMatrix.m[8]*this._parent._rotationMatrix[1]+this._rotMatrix.m[9]*this._parent._rotationMatrix[4]+this._rotMatrix.m[10]*this._parent._rotationMatrix[7],this._particle._rotationMatrix[8]=this._rotMatrix.m[8]*this._parent._rotationMatrix[2]+this._rotMatrix.m[9]*this._parent._rotationMatrix[5]+this._rotMatrix.m[10]*this._parent._rotationMatrix[8])):(this._particle._globalPosition.x=this._particle.position.x,this._particle._globalPosition.y=this._particle.position.y,this._particle._globalPosition.z=this._particle.position.z,(this._computeParticleRotation||this.billboard)&&(this._particle._rotationMatrix[0]=this._rotMatrix.m[0],this._particle._rotationMatrix[1]=this._rotMatrix.m[1],this._particle._rotationMatrix[2]=this._rotMatrix.m[2],this._particle._rotationMatrix[3]=this._rotMatrix.m[4],this._particle._rotationMatrix[4]=this._rotMatrix.m[5],this._particle._rotationMatrix[5]=this._rotMatrix.m[6],this._particle._rotationMatrix[6]=this._rotMatrix.m[8],this._particle._rotationMatrix[7]=this._rotMatrix.m[9],this._particle._rotationMatrix[8]=this._rotMatrix.m[10])),this._particle.translateFromPivot?(this._pivotBackTranslation.x=0,this._pivotBackTranslation.y=0,this._pivotBackTranslation.z=0):(this._pivotBackTranslation.x=this._scaledPivot.x,this._pivotBackTranslation.y=this._scaledPivot.y,this._pivotBackTranslation.z=this._scaledPivot.z),u=0;uthis._maximum.x&&(this._maximum.x=this._positions32[o]),this._positions32[o+1]this._maximum.y&&(this._maximum.y=this._positions32[o+1]),this._positions32[o+2]this._maximum.z&&(this._maximum.z=this._positions32[o+2])),this._computeParticleVertex||(this._normal.x=this._fixedNormal32[o],this._normal.y=this._fixedNormal32[o+1],this._normal.z=this._fixedNormal32[o+2],this._rotated.x=this._normal.x*this._particle._rotationMatrix[0]+this._normal.y*this._particle._rotationMatrix[3]+this._normal.z*this._particle._rotationMatrix[6],this._rotated.y=this._normal.x*this._particle._rotationMatrix[1]+this._normal.y*this._particle._rotationMatrix[4]+this._normal.z*this._particle._rotationMatrix[7],this._rotated.z=this._normal.x*this._particle._rotationMatrix[2]+this._normal.y*this._particle._rotationMatrix[5]+this._normal.z*this._particle._rotationMatrix[8],this._normals32[o]=this._cam_axisX.x*this._rotated.x+this._cam_axisY.x*this._rotated.y+this._cam_axisZ.x*this._rotated.z,this._normals32[o+1]=this._cam_axisX.y*this._rotated.x+this._cam_axisY.y*this._rotated.y+this._cam_axisZ.y*this._rotated.z,this._normals32[o+2]=this._cam_axisX.z*this._rotated.x+this._cam_axisY.z*this._rotated.y+this._cam_axisZ.z*this._rotated.z),this._computeParticleColor&&this._particle.color&&(this._colors32[a]=this._particle.color.r,this._colors32[a+1]=this._particle.color.g,this._colors32[a+2]=this._particle.color.b,this._colors32[a+3]=this._particle.color.a),this._computeParticleTexture&&(this._uvs32[h]=this._shapeUV[2*u]*(this._particle.uvs.z-this._particle.uvs.x)+this._particle.uvs.x,this._uvs32[h+1]=this._shapeUV[2*u+1]*(this._particle.uvs.w-this._particle.uvs.y)+this._particle.uvs.y);else for(this._particle._stillInvisible=!0,u=0;ue.Tmp.Vector3[1].x&&(e.Tmp.Vector3[1].x=l[u].x),l[u].ye.Tmp.Vector3[1].y&&(e.Tmp.Vector3[1].y=l[u].y),l[u].ze.Tmp.Vector3[1].z&&(e.Tmp.Vector3[1].z=l[u].z),u++,r+=3;h._closePath&&(t[r]=l[0].x,t[r+1]=l[0].y,t[r+2]=l[0].z,r+=3)}}(u),h._boundingInfo=new e.BoundingInfo(e.Tmp.Vector3[0],e.Tmp.Vector3[1]),h._boundingInfo.update(h._worldMatrix),h.updateVerticesData(e.VertexBuffer.PositionKind,u,!1,!1),r.colors){for(var f=h.getVerticesData(e.VertexBuffer.ColorKind),d=0;d1?1:r.arc:1,a=void 0===r.closed||r.closed,l=r.shape,h=r.radius||1,c=r.tessellation||64,u=r.clip||0,f=r.updatable,d=t.updateSideOrientation(r.sideOrientation),p=r.cap||e.Mesh.NO_CAP,m=2*Math.PI,_=new Array,g=r.invertUV||!1,v=0,y=0,b=m/c*s,x=new Array;for(v=0;v<=c-u;v++){var x=[];for(p!=e.Mesh.CAP_START&&p!=e.Mesh.CAP_ALL||(x.push(new e.Vector3(0,l[0].y,0)),x.push(new e.Vector3(Math.cos(v*b)*l[0].x*h,l[0].y,Math.sin(v*b)*l[0].x*h))),y=0;y1)?1:r.arc||1;var p,m,_=function(t,i,r,n,o,s,a,l){for(var h,c,u,f,d=i.getTangents(),p=i.getNormals(),m=i.getDistances(),_=2*Math.PI,g=_/o*l,v=function(){return n},y=s||v,b=e.Tmp.Matrix[0],x=a===e.Mesh._NO_CAP||a===e.Mesh.CAP_END?0:2,T=0;T3?0:c,m=_(o,p,v,a,l,h,c,r.arc);var y=t.CreateRibbon(i,{pathArray:m,closePath:!0,closeArray:!1,updatable:f,sideOrientation:d,invertUV:u,frontUVs:r.frontUVs,backUVs:r.backUVs},n);return y.pathArray=m,y.path3D=p,y.tessellation=l,y.cap=c,y.arc=r.arc,y.radius=a,y},t.CreatePolyhedron=function(i,r,n){var o=new e.Mesh(i,n);return r.sideOrientation=t.updateSideOrientation(r.sideOrientation),o._originalBuilderSideOrientation=r.sideOrientation,e.VertexData.CreatePolyhedron(r).applyToMesh(o,r.updatable),o},t.CreateDecal=function(t,i,r){var n=i.getIndices(),o=i.getVerticesData(e.VertexBuffer.PositionKind),s=i.getVerticesData(e.VertexBuffer.NormalKind),a=r.position||e.Vector3.Zero(),l=r.normal||e.Vector3.Up(),h=r.size||e.Vector3.One(),c=r.angle||0;if(!l){var u=new e.Vector3(0,0,1),f=i.getScene().activeCamera,d=e.Vector3.TransformCoordinates(u,f.getWorldMatrix());l=f.globalPosition.subtract(d)}var p=-Math.atan2(l.z,l.x)-Math.PI/2,m=Math.sqrt(l.x*l.x+l.z*l.z),_=Math.atan2(l.y,m),g=e.Matrix.RotationYawPitchRoll(p,_,c).multiply(e.Matrix.Translation(a.x,a.y,a.z)),v=e.Matrix.Invert(g),y=i.getWorldMatrix(),b=y.multiply(v),x=new e.VertexData;x.indices=[],x.positions=[],x.normals=[],x.uvs=[];for(var T=0,E=function(t){var i=new e.PositionNormalVertex;if(!n||!o||!s)return i;var r=n[t];return i.position=new e.Vector3(o[3*r],o[3*r+1],o[3*r+2]),i.position=e.Vector3.TransformCoordinates(i.position,b),i.normal=new e.Vector3(s[3*r],s[3*r+1],s[3*r+2]),i.normal=e.Vector3.TransformNormal(i.normal,b),i},P=function(t,i){if(0===t.length)return t;for(var r=.5*Math.abs(e.Vector3.Dot(h,i)),n=function(t,n){var o=e.Vector3.GetClipFactor(t.position,n.position,i,r);return new e.PositionNormalVertex(e.Vector3.Lerp(t.position,n.position,o),e.Vector3.Lerp(t.normal,n.normal,o))},o=new Array,s=0;s0,l=_>0,c=g>0,(a?1:0)+(l?1:0)+(c?1:0)){case 0:o.push(t[s]),o.push(t[s+1]),o.push(t[s+2]);break;case 1:if(a&&(u=t[s+1],f=t[s+2],d=n(t[s],u),p=n(t[s],f)),l){u=t[s],f=t[s+2],d=n(t[s+1],u),p=n(t[s+1],f),o.push(d),o.push(f.clone()),o.push(u.clone()),o.push(f.clone()),o.push(d.clone()),o.push(p);break}c&&(u=t[s],f=t[s+1],d=n(t[s+2],u),p=n(t[s+2],f)),u&&f&&d&&p&&(o.push(u.clone()),o.push(f.clone()),o.push(d),o.push(p),o.push(d.clone()),o.push(f.clone()));break;case 2:a||(u=t[s].clone(),f=n(u,t[s+1]),d=n(u,t[s+2]),o.push(u),o.push(f),o.push(d)),l||(u=t[s+1].clone(),f=n(u,t[s+2]),d=n(u,t[s]),o.push(u),o.push(f),o.push(d)),c||(u=t[s+2].clone(),f=n(u,t[s]),d=n(u,t[s+1]),o.push(u),o.push(f),o.push(d))}}return o},A=0;A3?0:u,x=T(r,n,b,E,o,s,a,l,u,f);var P=t.CreateRibbon(i,{pathArray:x,closeArray:h,closePath:c,updatable:p,sideOrientation:m,invertUV:g,frontUVs:v||void 0,backUVs:y||void 0 -},d);return P.pathArray=x,P.path3D=b,P.cap=u,P},t})();e.MeshBuilder=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return Object.defineProperty(t,"DecoderAvailable",{get:function(){if("undefined"!=typeof DracoDecoderModule)return!0;var e=t.Configuration.decoder;if(e){if(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly)return!0;if(e.fallbackUrl)return!0}return!1},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){},t.prototype.decodeMeshAsync=function(i,r){var n=i instanceof ArrayBuffer?new Uint8Array(i):i;return t._GetDecoderModule().then((function(t){var i=t.module,o=new e.VertexData,s=new i.DecoderBuffer;s.Init(n,n.byteLength);var a,l,h=new i.Decoder;try{var c=h.GetEncodedGeometryType(s);switch(c){case i.TRIANGULAR_MESH:a=new i.Mesh,l=h.DecodeBufferToMesh(s,a);break;case i.POINT_CLOUD:a=new i.PointCloud,l=h.DecodeBufferToPointCloud(s,a);break;default:throw new Error("Invalid geometry type "+c)}if(!l.ok()||!a.ptr)throw new Error(l.error_msg());var u=a.num_points();if(c===i.TRIANGULAR_MESH){var f=a.num_faces(),d=new i.DracoInt32Array;try{for(var p=new Uint32Array(3*f),m=0;m0&&(h=!0,this._soundLoaded(i));break;case"String":l.push(i);case"Array":0===l.length&&(l=i);for(var c=0;c0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect();else if(e.Engine.audioEngine.audioContext&&this._soundSource){var i=t?e.Engine.audioEngine.audioContext.currentTime+t:e.Engine.audioEngine.audioContext.currentTime;this._soundSource.stop(i),this._soundSource.onended=function(){},this.isPaused||(this._startOffset=0)}this.isPlaying=!1}},t.prototype.pause=function(){this.isPlaying&&(this.isPaused=!0,this._streaming?this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect():e.Engine.audioEngine.audioContext&&(this.stop(0),this._startOffset+=e.Engine.audioEngine.audioContext.currentTime-this._startTime))},t.prototype.setVolume=function(t,i){e.Engine.audioEngine.canUseWebAudio&&this._soundGain&&(i&&e.Engine.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(t,e.Engine.audioEngine.audioContext.currentTime+i)):this._soundGain.gain.value=t),this._volume=t},t.prototype.setPlaybackRate=function(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))},t.prototype.getVolume=function(){return this._volume},t.prototype.attachToMesh=function(e){var t=this;this._connectedMesh&&this._registerFunc&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedMesh=e,this.spatialSound||(this.spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play())),this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh),this._registerFunc=function(e){return t._onRegisterAfterWorldMatrixUpdate(e)},e.registerAfterWorldMatrixUpdate(this._registerFunc)},t.prototype.detachFromMesh=function(){this._connectedMesh&&this._registerFunc&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedMesh=null)},t.prototype._onRegisterAfterWorldMatrixUpdate=function(t){if(t.getBoundingInfo){var i=t,r=i.getBoundingInfo();this.setPosition(r.boundingSphere.centerWorld),e.Engine.audioEngine.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}},t.prototype.clone=function(){var e=this;if(this._streaming)return null;var i=function(){e._isReadyToPlay?(n._audioBuffer=e.getAudioBuffer(),n._isReadyToPlay=!0,n.autoplay&&n.play()):window.setTimeout(i,300)},r={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},n=new t(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,r);return this.useCustomAttenuation&&n.setAttenuationFunction(this._customAttenuationFunction),n.setPosition(this._position),n.setPlaybackRate(this._playbackRate),i(),n},t.prototype.getAudioBuffer=function(){return this._audioBuffer},t.prototype.serialize=function(){var e={name:this.name,url:this.name,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId};return this.spatialSound&&(this._connectedMesh&&(e.connectedMeshId=this._connectedMesh.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e},t.Parse=function(i,r,n,o){var s,a=i.name;s=i.url?n+i.url:n+a;var l,h={autoplay:i.autoplay,loop:i.loop,volume:i.volume,spatialSound:i.spatialSound,maxDistance:i.maxDistance,rolloffFactor:i.rolloffFactor,refDistance:i.refDistance,distanceModel:i.distanceModel,playbackRate:i.playbackRate};if(o){var c=function(){o._isReadyToPlay?(l._audioBuffer=o.getAudioBuffer(),l._isReadyToPlay=!0,l.autoplay&&l.play()):window.setTimeout(c,300)};l=new t(a,new ArrayBuffer(0),r,null,h),c()}else l=new t(a,s,r,function(){r._removePendingData(l)},h),r._addPendingData(l);if(i.position){var u=e.Vector3.FromArray(i.position);l.setPosition(u)}if(i.isDirectional&&(l.setDirectionalCone(i.coneInnerAngle||360,i.coneOuterAngle||360,i.coneOuterGain||0),i.localDirectionToMesh)){var f=e.Vector3.FromArray(i.localDirectionToMesh);l.setLocalDirectionToMesh(f)}if(i.connectedMeshId){var d=r.getMeshByID(i.connectedMeshId);d&&l.attachToMesh(d)}return l},t})();e.Sound=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t){this.id=-1,this._isMainTrack=!1,this._isInitialized=!1,this._scene=e,this.soundCollection=new Array,this._options=t,this._isMainTrack||(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}return t.prototype._initializeSoundTrackAudioGraph=function(){e.Engine.audioEngine.canUseWebAudio&&e.Engine.audioEngine.audioContext&&(this._outputAudioNode=e.Engine.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(e.Engine.audioEngine.masterGain),this._options&&(this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._options.mainTrack&&(this._isMainTrack=this._options.mainTrack)),this._isInitialized=!0)},t.prototype.dispose=function(){if(e.Engine.audioEngine&&e.Engine.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}},t.prototype.AddSound=function(t){this._isInitialized||this._initializeSoundTrackAudioGraph(),e.Engine.audioEngine.canUseWebAudio&&this._outputAudioNode&&t.connectToSoundTrackAudioNode(this._outputAudioNode),t.soundTrackId&&(-1===t.soundTrackId?this._scene.mainSoundTrack.RemoveSound(t):this._scene.soundTracks[t.soundTrackId].RemoveSound(t)),this.soundCollection.push(t),t.soundTrackId=this.id},t.prototype.RemoveSound=function(e){var t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)},t.prototype.setVolume=function(t){e.Engine.audioEngine.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=t)},t.prototype.switchPanningModelToHRTF=function(){if(e.Engine.audioEngine.canUseWebAudio)for(var t=0;t-1?i.substring(_).toLowerCase():""),v=".dds"===g,y=".env"===g;if(y?(m.gammaSpace=!1,m._prefiltered=!1):(m._prefiltered=c,c&&(m.gammaSpace=!1)),m._texture=m._getFromCache(i,o),!s&&(y||v||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),s=[],n))for(var b=0;b0&&(this._postProcesses[0].autoClear=!1))}},i.prototype._shouldRender=function(){return-1===this._currentRefreshId?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)},i.prototype.getRenderSize=function(){return this._size.width?this._size.width:this._size},i.prototype.getRenderWidth=function(){return this._size.width?this._size.width:this._size},i.prototype.getRenderHeight=function(){return this._size.width?this._size.height:this._size},Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype.scale=function(e){var t=this.getRenderSize()*e;this.resize(t)},i.prototype.getReflectionTextureMatrix=function(){return this.isCube?this._textureMatrix:t.prototype.getReflectionTextureMatrix.call(this)},i.prototype.resize=function(e){this.releaseInternalTexture();var t=this.getScene();t&&(this._processSizeParameter(e),this.isCube?this._texture=t.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._texture=t.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions))},i.prototype.render=function(e,t){void 0===e&&(e=!1),void 0===t&&(t=!1);var i=this.getScene();if(i){var r=i.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(var n=0;n=0&&this._renderingManager.dispatchParticles(v))}if(this.isCube)for(var b=0;b<6;b++)this.renderToTarget(b,c,u,e,t),i.incrementRenderId(),i.resetCachedMaterial();else this.renderToTarget(0,c,u,e,t);this.onAfterUnbindObservable.notifyObservers(this),i.activeCamera&&(this.activeCamera&&this.activeCamera!==i.activeCamera&&i.setTransformMatrix(i.activeCamera.getViewMatrix(),i.activeCamera.getProjectionMatrix(!0)),r.setViewport(i.activeCamera.viewport)),i.resetCachedMaterial()}},i.prototype._bestReflectionRenderTargetDimension=function(t,i){var r=t*i,n=e.Tools.NearestPOT(r+16384/(128+r));return Math.min(e.Tools.FloorPOT(t),n)},i.prototype.unbindFrameBuffer=function(e,t){var i=this;this._texture&&e.unBindFramebuffer(this._texture,this.isCube,(function(){i.onAfterRenderObservable.notifyObservers(t)}))},i.prototype.renderToTarget=function(t,i,r,n,o){var s=this.getScene();if(s){var a=s.getEngine();this._texture&&(this._postProcessManager?this._postProcessManager._prepareFrame(this._texture,this._postProcesses):n&&s.postProcessManager._prepareFrame(this._texture)||this._texture&&a.bindFramebuffer(this._texture,this.isCube?t:void 0,void 0,void 0,this.ignoreCameraViewport,this.depthStencilTexture?this.depthStencilTexture:void 0),this.onBeforeRenderObservable.notifyObservers(t),this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):a.clear(this.clearColor||s.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),this._renderingManager.render(this.customRenderFunction,i,this.renderParticles,this.renderSprites),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._texture,t,this._postProcesses,this.ignoreCameraViewport):n&&s.postProcessManager._finalizeFrame(!1,this._texture,t),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),o&&e.Tools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),a),this.isCube&&5!==t?this.onAfterRenderObservable.notifyObservers(t):(this.isCube&&5===t&&a.generateMipMapsForCubemap(this._texture),this.unbindFrameBuffer(a,t)))}},i.prototype.setRenderingOrder=function(e,t,i,r){void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._renderingManager.setRenderingOrder(e,t,i,r)},i.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(var i=0;i=0&&e.customRenderTargets.splice(i,1);for(var r=0,n=e.cameras;r=0&&o.customRenderTargets.splice(i,1)}t.prototype.dispose.call(this)}},i.prototype._rebuild=function(){this.refreshRate===i.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=i.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()},i.prototype.freeRenderingGroups=function(){this._renderingManager&&this._renderingManager.freeRenderingGroups()},i._REFRESHRATE_RENDER_ONCE=0,i._REFRESHRATE_RENDER_ONEVERYFRAME=1,i._REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,i})(e.Texture);e.RenderTargetTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s){var a=this,l=!(!s||!s.generateMipMaps)&&s.generateMipMaps,h=!(!s||!s.generateDepthTexture)&&s.generateDepthTexture,c=!s||void 0===s.doNotChangeAspectRatio||s.doNotChangeAspectRatio;if(a=t.call(this,i,r,o,l,c)||this,a._engine=o.getEngine(),!a.isSupported)return void a.dispose();for(var u=[],f=[],d=0;d1||this._engine.getCaps().drawBuffersExtension},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"textures",{get:function(){return this._textures},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"depthTexture",{get:function(){return this._textures[this._textures.length-1]},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wrapU",{set:function(e){if(this._textures)for(var t=0;t=0;e--)void 0!==this._internalTextures[e]&&(this._internalTextures[e].dispose(),this._internalTextures.splice(e,1))},i})(e.RenderTargetTexture);e.MultiRenderTarget=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l){void 0===s&&(s=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),void 0===l&&(l=!0);var h=t.call(this,i,r,n,o,!0,s,!1,a,l)||this;return h.scene=n,h.mirrorPlane=new e.Plane(0,1,0,1),h._transformMatrix=e.Matrix.Zero(),h._mirrorMatrix=e.Matrix.Zero(),h._adaptiveBlurKernel=0,h._blurKernelX=0,h._blurKernelY=0,h._blurRatio=1,h.ignoreCameraViewport=!0,h._updateGammaSpace(),h._imageProcessingConfigChangeObserver=n.imageProcessingConfiguration.onUpdateParameters.add((function(){h._updateGammaSpace})),h.onBeforeRenderObservable.add((function(){e.Matrix.ReflectionToRef(h.mirrorPlane,h._mirrorMatrix),h._savedViewMatrix=n.getViewMatrix(),h._mirrorMatrix.multiplyToRef(h._savedViewMatrix,h._transformMatrix),n.setTransformMatrix(h._transformMatrix,n.getProjectionMatrix()),n.clipPlane=h.mirrorPlane,n.getEngine().cullBackFaces=!1,n._mirroredCameraPosition=e.Vector3.TransformCoordinates(n.activeCamera.globalPosition,h._mirrorMatrix)})),h.onAfterRenderObservable.add((function(){n.setTransformMatrix(h._savedViewMatrix,n.getProjectionMatrix()),n.getEngine().cullBackFaces=!0,n._mirroredCameraPosition=null,delete n.clipPlane})),h}return o(i,t),Object.defineProperty(i.prototype,"blurRatio",{get:function(){return this._blurRatio},set:function(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"adaptiveBlurKernel",{set:function(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurKernel",{set:function(e){this.blurKernelX=e,this.blurKernelY=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurKernelX",{get:function(){return this._blurKernelX},set:function(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurKernelY",{get:function(){return this._blurKernelY},set:function(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),i.prototype._autoComputeBlurKernel=function(){var e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i},i.prototype._onRatioRescale=function(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()},i.prototype._updateGammaSpace=function(){this.gammaSpace=!this.scene.imageProcessingConfiguration.isEnabled||!this.scene.imageProcessingConfiguration.applyByPostProcess},i.prototype._preparePostProcesses=function(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){var t=this.getScene().getEngine(),i=t.getCaps().textureFloatRender?e.Engine.TEXTURETYPE_FLOAT:e.Engine.TEXTURETYPE_HALF_FLOAT;this._blurX=new e.BlurPostProcess("horizontal blur",new e.Vector2(1,0),this._blurKernelX,this._blurRatio,null,e.Texture.BILINEAR_SAMPLINGMODE,t,!1,i),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._texture:this._blurX.alwaysForcePOT=!0,this._blurY=new e.BlurPostProcess("vertical blur",new e.Vector2(0,1),this._blurKernelY,this._blurRatio,null,e.Texture.BILINEAR_SAMPLINGMODE,t,!1,i),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=this.getSize(),r=new i(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(r.renderList=this.renderList.slice(0)),r},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.mirrorPlane.asArray(),e},i.prototype.dispose=function(){t.prototype.dispose.call(this),this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver)},i})(e.RenderTargetTexture);e.MirrorTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o){var s=t.call(this,i,r,n,o,!0)||this;return s.refractionPlane=new e.Plane(0,1,0,1),s.depth=2,s.onBeforeRenderObservable.add((function(){n.clipPlane=s.refractionPlane})),s.onAfterRenderObservable.add((function(){delete n.clipPlane})),s}return o(i,t),i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=this.getSize(),r=new i(this.name,t.width,e,this._generateMipMaps);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.refractionPlane=this.refractionPlane.clone(),this.renderList&&(r.renderList=this.renderList.slice(0)),r.depth=this.depth,r},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e},i})(e.RenderTargetTexture);e.RefractionTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a){void 0===n&&(n=null),void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===a&&(a=e.Engine.TEXTUREFORMAT_RGBA);var l=t.call(this,null,n,!o,void 0,s,void 0,void 0,void 0,void 0,a)||this;l.name=i,l._engine=l.getScene().getEngine(),l.wrapU=e.Texture.CLAMP_ADDRESSMODE,l.wrapV=e.Texture.CLAMP_ADDRESSMODE,l._generateMipMaps=o,r.getContext?(l._canvas=r,l._texture=l._engine.createDynamicTexture(r.width,r.height,o,s)):(l._canvas=document.createElement("canvas"),r.width||0===r.width?l._texture=l._engine.createDynamicTexture(r.width,r.height,o,s):l._texture=l._engine.createDynamicTexture(r,r,o,s));var h=l.getSize();return l._canvas.width=h.width,l._canvas.height=h.height,l._context=l._canvas.getContext("2d"),l}return o(i,t),Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype._recreate=function(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._engine.createDynamicTexture(e.width,e.height,this._generateMipMaps,this._samplingMode)},i.prototype.scale=function(e){var t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)},i.prototype.scaleTo=function(e,t){var i=this.getSize();i.width=e,i.height=t,this._recreate(i)},i.prototype.getContext=function(){return this._context},i.prototype.clear=function(){var e=this.getSize();this._context.fillRect(0,0,e.width,e.height)},i.prototype.update=function(e,t){void 0===t&&(t=!1),this._engine.updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0)},i.prototype.drawText=function(e,t,i,r,n,o,s,a){void 0===a&&(a=!0);var l=this.getSize();if(o&&(this._context.fillStyle=o,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null===t||void 0===t){var h=this._context.measureText(e);t=(l.width-h.width)/2}if(null===i||void 0===i){var c=parseInt(r.replace(/\D/g,""));i=l.height/2+c/3.65}this._context.fillStyle=n,this._context.fillText(e,t,i),a&&this.update(s)},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=this.getSize(),r=new i(this.name,t,e,this._generateMipMaps);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.wrapU=this.wrapU,r.wrapV=this.wrapV,r},i.prototype.serialize=function(){var i=this.getScene();i&&!i.isReady()&&e.Tools.Warn("The scene must be ready before serializing the dynamic texture");var r=t.prototype.serialize.call(this);return r.base64String=this._canvas.toDataURL(),r.invertY=this._invertY,r.samplingMode=this.samplingMode,r},i.prototype._rebuild=function(){this.update()},i})(e.Texture);e.DynamicTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l){void 0===o&&(o=!1),void 0===s&&(s=!1),void 0===a&&(a=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===l&&(l={autoPlay:!0,loop:!0,autoUpdateTexture:!0});var h=t.call(this,null,n,!o,s)||this;return h._onUserActionRequestedObservable=null,h._stillImageCaptured=!1,h._poster=!1,h._createInternalTexture=function(){if(null!=h._texture){if(!h._poster)return;h._texture.dispose(),h._poster=!1}if(!h._engine.needPOTTextures||e.Tools.IsExponentOfTwo(h.video.videoWidth)&&e.Tools.IsExponentOfTwo(h.video.videoHeight)?(h.wrapU=e.Texture.WRAP_ADDRESSMODE,h.wrapV=e.Texture.WRAP_ADDRESSMODE):(h.wrapU=e.Texture.CLAMP_ADDRESSMODE,h.wrapV=e.Texture.CLAMP_ADDRESSMODE,h._generateMipMaps=!1),h._texture=h._engine.createDynamicTexture(h.video.videoWidth,h.video.videoHeight,h._generateMipMaps,h._samplingMode),h.video.autoplay)h._texture.isReady=!0,h._updateInternalTexture(),h._onLoadObservable&&h._onLoadObservable.hasObservers()&&h.onLoadObservable.notifyObservers(h);else{var t=h.video.onplaying,i=!1;h.video.onplaying=function(){h.video.onplaying=t,h._texture.isReady=!0,h._updateInternalTexture(),i||h.video.pause(),h._onLoadObservable&&h._onLoadObservable.hasObservers()&&h.onLoadObservable.notifyObservers(h)};var r=h.video.play();r?r.then((function(){})).catch((function(){i=!0,h._onUserActionRequestedObservable&&h._onUserActionRequestedObservable.hasObservers()&&h._onUserActionRequestedObservable.notifyObservers(h)})):(h.video.onplaying=t,h._texture.isReady=!0,h._updateInternalTexture(),h._onLoadObservable&&h._onLoadObservable.hasObservers()&&h.onLoadObservable.notifyObservers(h))}},h.reset=function(){null!=h._texture&&(h._poster||(h._texture.dispose(),h._texture=null))},h._updateInternalTexture=function(e){null!=h._texture&&h._texture.isReady&&(h.video.readyState=h.video.HAVE_CURRENT_DATA&&h._createInternalTexture(),l.poster&&(h._texture=h._engine.createTexture(l.poster,!1,!0,n),h._poster=!0),h}return o(i,t),Object.defineProperty(i.prototype,"onUserActionRequestedObservable",{get:function(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new e.Observable),this._onUserActionRequestedObservable},enumerable:!0,configurable:!0}),i.prototype._getName=function(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e},i.prototype._getVideo=function(t){if(t instanceof HTMLVideoElement)return e.Tools.SetCorsBehavior(t.currentSrc,t),t;var i=document.createElement("video");return"string"==typeof t?(e.Tools.SetCorsBehavior(t,i),i.src=t):(e.Tools.SetCorsBehavior(t[0],i),t.forEach((function(e){var t=document.createElement("source");t.src=e,i.appendChild(t)}))),i},i.prototype._rebuild=function(){this.update()},i.prototype.update=function(){this.autoUpdateTexture&&this.updateTexture(!0)},i.prototype.updateTexture=function(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))},i.prototype.updateURL=function(e){this.video.src=e},i.prototype.dispose=function(){t.prototype.dispose.call(this),this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener("canplay",this._createInternalTexture),this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this.reset),this.video.pause()},i.CreateFromWebCam=function(t,r,n){var o=document.createElement("video");o.setAttribute("autoplay",""),o.setAttribute("muted",""),o.setAttribute("playsinline","");var s;n&&n.deviceId&&(s={exact:n.deviceId}),window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,navigator.mediaDevices?navigator.mediaDevices.getUserMedia({video:n}).then((function(e){void 0!==o.mozSrcObject?o.mozSrcObject=e:o.srcObject=e;var n=function(){r&&r(new i("video",o,t,!0,!0)),o.removeEventListener("playing",n)};o.addEventListener("playing",n),o.play()})).catch((function(t){e.Tools.Error(t.name)})):(navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,navigator.getUserMedia&&navigator.getUserMedia({video:{deviceId:s,width:{min:n&&n.minWidth||256,max:n&&n.maxWidth||640},height:{min:n&&n.minHeight||256,max:n&&n.maxHeight||480}}},(function(e){void 0!==o.mozSrcObject?o.mozSrcObject=e:o.src=window.URL&&window.URL.createObjectURL(e)||e,o.play(),r&&r(new i("video",o,t,!0,!0))}),(function(t){e.Tools.Error(t.name)})))},i})(e.Texture);e.VideoTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h,c){void 0===a&&(a=!0),void 0===l&&(l=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT);var u=t.call(this,null,s,!a,l)||this;return u.format=o,u._engine=s.getEngine(),u._texture=s.getEngine().createRawTexture(i,r,n,o,a,l,h,null,c),u.wrapU=e.Texture.CLAMP_ADDRESSMODE,u.wrapV=e.Texture.CLAMP_ADDRESSMODE,u}return o(i,t),i.prototype.update=function(e){this._engine.updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,void 0,this._texture.type)},i.CreateLuminanceTexture=function(t,r,n,o,s,a,l){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_LUMINANCE,o,s,a,l)},i.CreateLuminanceAlphaTexture=function(t,r,n,o,s,a,l){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA,o,s,a,l)},i.CreateAlphaTexture=function(t,r,n,o,s,a,l){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_ALPHA,o,s,a,l)},i.CreateRGBTexture=function(t,r,n,o,s,a,l,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT),new i(t,r,n,e.Engine.TEXTUREFORMAT_RGB,o,s,a,l,h)},i.CreateRGBATexture=function(t,r,n,o,s,a,l,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT),new i(t,r,n,e.Engine.TEXTUREFORMAT_RGBA,o,s,a,l,h)},i.CreateRTexture=function(t,r,n,o,s,a,l,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=e.Engine.TEXTURETYPE_FLOAT),new i(t,r,n,e.Engine.TEXTUREFORMAT_R,o,s,a,l,h)},i})(e.Texture);e.RawTexture=t})(r||(r={}));var r;!(function(e){ -var t=(function(t){function i(i,r,n,o,s,a,l,h,c,u){void 0===l&&(l=!0),void 0===h&&(h=!1),void 0===c&&(c=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===u&&(u=e.Engine.TEXTURETYPE_UNSIGNED_INT);var f=t.call(this,null,a,!l,h)||this;return f.format=s,f._engine=a.getEngine(),f._texture=a.getEngine().createRawTexture3D(i,r,n,o,s,l,h,c,void 0,u),f.is3D=!0,f}return o(i,t),i.prototype.update=function(e){this._texture&&this._engine.updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,void 0,this._texture.type)},i})(e.Texture);e.RawTexture3D=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e){this._vertexBuffers={},this._scene=e}return t.prototype._prepareBuffers=function(){if(!this._vertexBuffers[e.VertexBuffer.PositionKind]){var t=[];t.push(1,1),t.push(-1,1),t.push(-1,-1),t.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(this._scene.getEngine(),t,e.VertexBuffer.PositionKind,!1,!1,2),this._buildIndexBuffer()}},t.prototype._buildIndexBuffer=function(){var e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)},t.prototype._rebuild=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t._rebuild(),this._buildIndexBuffer())},t.prototype._prepareFrame=function(e,t){void 0===e&&(e=null),void 0===t&&(t=null);var i=this._scene.activeCamera;if(!i)return!1;var t=t||i._postProcesses.filter((function(e){return null!=e}));return!(!t||0===t.length||!this._scene.postProcessesEnabled)&&(t[0].activate(i,e,null!==t&&void 0!==t),!0)},t.prototype.directRender=function(t,i,r,n,o){void 0===i&&(i=null),void 0===r&&(r=!1),void 0===n&&(n=0),void 0===o&&(o=0);for(var s=this._scene.getEngine(),a=0;a0){for(var p=0;p0)for(var e=0;e0){var r=this._camera._getFirstPostProcess();r&&r.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}},t})();e.PostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h){return void 0===n&&(n=null),void 0===l&&(l=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1),t.call(this,i,"pass",null,null,r,n,o,s,a,void 0,l,void 0,null,h)||this}return o(i,t),i})(e.PostProcess);e.PassPostProcess=t})(r||(r={}));var r,s=this&&this.__assign||Object.assign||function(e){for(var t,i=1,r=arguments.length;i=1?1:e<=0?0:e,this},t.prototype.setTransparencyShadow=function(e){return this._transparencyShadow=e,this},t.prototype.getShadowMap=function(){return this._shadowMap},t.prototype.getShadowMapForRendering=function(){return this._shadowMap2?this._shadowMap2:this._shadowMap},t.prototype.addShadowCaster=function(e,t){return void 0===t&&(t=!0),this._shadowMap?(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.push(e),t&&(i=this._shadowMap.renderList).push.apply(i,e.getChildMeshes()),this):this;var i},t.prototype.removeShadowCaster=function(e,t){if(void 0===t&&(t=!0),!this._shadowMap||!this._shadowMap.renderList)return this;var i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(var r=0,n=e.getChildren();r1?(this._shadowMap=new e.RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1),this._shadowMap.createDepthStencilTexture(e.Engine.LESS,!0)):this._shadowMap=new e.RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._shadowMap.onBeforeRenderObservable.add((function(e){i._currentFaceIndex=e,i._filter===t.FILTER_PCF&&r.setColorWrite(!1)})),this._shadowMap.customRenderFunction=this._renderForShadowMap.bind(this),this._shadowMap.onAfterUnbindObservable.add((function(){if(i._filter===t.FILTER_PCF&&r.setColorWrite(!0),i.useBlurExponentialShadowMap||i.useBlurCloseExponentialShadowMap){var e=i.getShadowMapForRendering();e&&i._scene.postProcessManager.directRender(i._blurPostProcesses,e.getInternalTexture(),!0)}}));var n=new e.Color4(0,0,0,0),o=new e.Color4(1,1,1,1);this._shadowMap.onClearObservable.add((function(e){i._filter===t.FILTER_PCF?e.clear(o,!1,!0,!1):i.useExponentialShadowMap||i.useBlurExponentialShadowMap?e.clear(n,!0,!0,!1):e.clear(o,!0,!0,!1)}))},t.prototype._initializeBlurRTTAndPostProcesses=function(){var t=this,i=this._scene.getEngine(),r=this._mapSize/this.blurScale;this.useKernelBlur&&1===this.blurScale||(this._shadowMap2=new e.RenderTargetTexture(this._light.name+"_shadowMap2",r,this._scene,!1,!0,this._textureType),this._shadowMap2.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new e.BlurPostProcess(this._light.name+"KernelBlurX",new e.Vector2(1,0),this.blurKernel,1,null,e.Texture.BILINEAR_SAMPLINGMODE,i,!1,this._textureType),this._kernelBlurXPostprocess.width=r,this._kernelBlurXPostprocess.height=r,this._kernelBlurXPostprocess.onApplyObservable.add((function(e){e.setTexture("textureSampler",t._shadowMap)})),this._kernelBlurYPostprocess=new e.BlurPostProcess(this._light.name+"KernelBlurY",new e.Vector2(0,1),this.blurKernel,1,null,e.Texture.BILINEAR_SAMPLINGMODE,i,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===e.Engine.TEXTURETYPE_UNSIGNED_INT&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new e.PostProcess(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,e.Texture.BILINEAR_SAMPLINGMODE,i,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",r,r),e.setTexture("textureSampler",t._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])},t.prototype._renderForShadowMap=function(e,t,i,r){var n,o=this._scene.getEngine();if(r.length){for(o.setColorWrite(!1),n=0;n=a.length)return void(e&&e(i));setTimeout(f,16)}};f()},t.prototype.forceCompilationAsync=function(e){var t=this;return new Promise(function(i){t.forceCompilation((function(){i()}),e)})},t.prototype.isReady=function(t,i){var r=[];this._textureType!==e.Engine.TEXTURETYPE_UNSIGNED_INT&&r.push("#define FLOAT"),this.useExponentialShadowMap||this.useBlurExponentialShadowMap?r.push("#define ESM"):(this.usePercentageCloserFiltering||this.useContactHardeningShadow)&&r.push("#define DEPTHTEXTURE");var n=[e.VertexBuffer.PositionKind],o=t.getMesh(),s=t.getMaterial();if(this.normalBias&&o.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(n.push(e.VertexBuffer.NormalKind),r.push("#define NORMAL"),o.nonUniformScaling&&r.push("#define NONUNIFORMSCALING"),this.getLight().getTypeID()===e.Light.LIGHTTYPEID_DIRECTIONALLIGHT&&r.push("#define DIRECTIONINLIGHTDATA")),s&&s.needAlphaTesting()){var a=s.getAlphaTestTexture();a&&(r.push("#define ALPHATEST"),o.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push(e.VertexBuffer.UVKind),r.push("#define UV1")),o.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&1===a.coordinatesIndex&&(n.push(e.VertexBuffer.UV2Kind),r.push("#define UV2")))}o.useBones&&o.computeBonesUsingShaders?(n.push(e.VertexBuffer.MatricesIndicesKind),n.push(e.VertexBuffer.MatricesWeightsKind),o.numBoneInfluencers>4&&(n.push(e.VertexBuffer.MatricesIndicesExtraKind),n.push(e.VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton.bones.length+1))):r.push("#define NUM_BONE_INFLUENCERS 0");var l=o.morphTargetManager,h=0;l&&l.numInfluencers>0&&(r.push("#define MORPHTARGETS"),h=l.numInfluencers,r.push("#define NUM_MORPH_INFLUENCERS "+h),e.MaterialHelper.PrepareAttributesForMorphTargets(n,o,{NUM_MORPH_INFLUENCERS:h})),i&&(r.push("#define INSTANCES"),n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"));var c=r.join("\n");return this._cachedDefines!==c&&(this._cachedDefines=c,this._effect=this._scene.getEngine().createEffect("shadowMap",n,["world","mBones","viewProjection","diffuseMatrix","lightData","depthValues","biasAndScale","morphTargetInfluences"],["diffuseSampler"],c,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h})),!!this._effect.isReady()&&((this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady())&&(!(this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady())&&!(this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())))},t.prototype.prepareDefines=function(e,i){var r=this._scene,n=this._light;r.shadowsEnabled&&n.shadowEnabled&&(e["SHADOW"+i]=!0,this.useContactHardeningShadow&&(e["SHADOWPCSS"+i]=!0,this._filteringQuality===t.QUALITY_LOW?e["SHADOWLOWQUALITY"+i]=!0:this._filteringQuality===t.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+i]=!0)),this.usePercentageCloserFiltering?(e["SHADOWPCF"+i]=!0,this._filteringQuality===t.QUALITY_LOW?e["SHADOWLOWQUALITY"+i]=!0:this._filteringQuality===t.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+i]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+i]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+i]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+i]=!0),n.needCube()&&(e["SHADOWCUBE"+i]=!0))},t.prototype.bindShadowLight=function(e,i){var r=this._light,n=this._scene;if(n.shadowsEnabled&&r.shadowEnabled){var o=n.activeCamera;if(o){var s=this.getShadowMap();s&&(r.needCube()||i.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===t.FILTER_PCF?(i.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),s.getSize().width,1/s.getSize().width,this.frustumEdgeFalloff,e)):this._filter===t.FILTER_PCSS?(i.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i.setTexture("depthSampler"+e,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/s.getSize().width,this._contactHardeningLightSizeUVRatio*s.getSize().width,this.frustumEdgeFalloff,e)):(i.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/s.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),r._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(o),this.getLight().getDepthMinZ(o)+this.getLight().getDepthMaxZ(o),e))}}},t.prototype.getTransformMatrix=function(){var t=this._scene;if(this._currentRenderID===t.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderID=t.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;var i=this._light.position;if(this._light.computeTransformedInformation()&&(i=this._light.transformedPosition),e.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(e.Vector3.Dot(this._lightDirection,e.Vector3.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!i.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(i),this._cachedDirection.copyFrom(this._lightDirection),e.Matrix.LookAtLHToRef(i,i.add(this._lightDirection),e.Vector3.Up(),this._viewMatrix);var r=this.getShadowMap();if(r){var n=r.renderList;n&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,n)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)} -return this._transformMatrix},t.prototype.recreateShadowMap=function(){var e=this._shadowMap;if(e){var t=e.renderList;this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this.filter,this._applyFilterValues(),this._shadowMap.renderList=t}},t.prototype._disposeBlurPostProcesses=function(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]},t.prototype._disposeRTTandPostProcesses=function(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()},t.prototype.dispose=function(){this._disposeRTTandPostProcesses(),this._light&&(this._light._shadowGenerator=null,this._light._markMeshesAsLightDirty())},t.prototype.serialize=function(){var e={},t=this.getShadowMap();if(!t)return e;if(e.lightId=this._light.id,e.mapSize=t.getRenderSize(),e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.forceBackFacesOnly=this.forceBackFacesOnly,e.depthScale=this.depthScale,e.darkness=this.getDarkness(),e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.filteringQuality=this.filteringQuality,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.renderList=[],t.renderList)for(var i=0;i0){for(var ne=0;ne0){for(var se=0;se-1&&void 0!==d.skeletons&&null!==d.skeletons){if(!1===v.indexOf(b.skeletonId)>-1)for(var D=0,I=d.skeletons.length;D0&&this._textureLoadingCallback(e)}this._currentScene.render()}},t.prototype.drag=function(e){e.stopPropagation(),e.preventDefault()},t.prototype.drop=function(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)},t.prototype._traverseFolder=function(e,t,i,r){var n=this,o=e.createReader(),s=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");o.readEntries((function(e){i.count+=e.length;for(var o=0,a=e;o0){for(var i=new Array,r=[],n=e.dataTransfer?e.dataTransfer.items:null,o=0;o0&&e.Tools.ClearLogCache(),this._engine.stopRenderLoop()),e.SceneLoader.LoadAsync("file:",this._sceneFileToLoad,this._engine,(function(e){t._progressCallback&&t._progressCallback(e)})).then((function(e){t._currentScene&&t._currentScene.dispose(),t._currentScene=e,t._sceneLoadedCallback&&t._sceneLoadedCallback(t._sceneFileToLoad,t._currentScene),t._currentScene.executeWhenReady((function(){t._engine.runRenderLoop((function(){t.renderFunction()}))}))})).catch((function(e){t._errorCallback&&t._errorCallback(t._sceneFileToLoad,t._currentScene,e.message)}))):e.Tools.Error("Please provide a valid .babylon file.")},t.FilesToLoad={},t})();e.FilesInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.EnableFor=function(e){e._tags=e._tags||{},e.hasTags=function(){return t.HasTags(e)},e.addTags=function(i){return t.AddTagsTo(e,i)},e.removeTags=function(i){return t.RemoveTagsFrom(e,i)},e.matchesTagsQuery=function(i){return t.MatchesQuery(e,i)}},t.DisableFor=function(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery},t.HasTags=function(t){return!!t._tags&&!e.Tools.IsEmpty(t._tags)},t.GetTags=function(e,t){if(void 0===t&&(t=!0),!e._tags)return null;if(t){var i=[];for(var r in e._tags)e._tags.hasOwnProperty(r)&&!0===e._tags[r]&&i.push(r);return i.join(" ")}return e._tags},t.AddTagsTo=function(e,i){if(i&&"string"==typeof i){i.split(" ").forEach((function(i,r,n){t._AddTagTo(e,i)}))}},t._AddTagTo=function(e,i){""!==(i=i.trim())&&"true"!==i&&"false"!==i&&(i.match(/[\s]/)||i.match(/^([!]|([|]|[&]){2})/)||(t.EnableFor(e),e._tags[i]=!0))},t.RemoveTagsFrom=function(e,i){if(t.HasTags(e)){var r=i.split(" ");for(var n in r)t._RemoveTagFrom(e,r[n])}},t._RemoveTagFrom=function(e,t){delete e._tags[t]},t.MatchesQuery=function(i,r){return void 0===r||(""===r?t.HasTags(i):e.AndOrNotEvaluator.Eval(r,(function(e){return t.HasTags(i)&&i._tags[e]})))},t})();e.Tags=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){}return e.Eval=function(t,i){return"true"===(t=t.match(/\([^\(\)]*\)/g)?t.replace(/\([^\(\)]*\)/g,(function(t){return t=t.slice(1,t.length-1),e._HandleParenthesisContent(t,i)})):e._HandleParenthesisContent(t,i))||"false"!==t&&e.Eval(t,i)},e._HandleParenthesisContent=function(t,i){i=i||function(e){return"true"===e};var r,n=t.split("||");for(var o in n)if(n.hasOwnProperty(o)){var s=e._SimplifyNegation(n[o].trim()),a=s.split("&&");if(a.length>1)for(var l=0;l=400&&o?o(h):i()}),!1),h.addEventListener("error",(function(t){e.Tools.Error("error on XHR request."),i()}),!1),h.send()}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i()},t.IsUASupportingBlobStorage=!0,t.IDBStorageEnabled=!0,t._ParseURL=function(e){document.createElement("a").href=e;var t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},t._ReturnFullUrlLocation=function(e){return-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")?t._ParseURL(window.location.href)+e:e},t})();e.Database=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._isEnabled=!0,this.leftColor=e.Color3.White(),this.rightColor=e.Color3.Black(),this.bias=0,this.power=1}return Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(t){this._isEnabled!==t&&(this._isEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.FresnelDirtyFlag|e.Material.MiscDirtyFlag))},enumerable:!0,configurable:!0}),t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.serialize=function(){var e={};return e.isEnabled=this.isEnabled,e.leftColor=this.leftColor.asArray(),e.rightColor=this.rightColor.asArray(),e.bias=this.bias,e.power=this.power,e},t.Parse=function(i){var r=new t;return r.isEnabled=i.isEnabled,r.leftColor=e.Color3.FromArray(i.leftColor),r.rightColor=e.Color3.FromArray(i.rightColor),r.bias=i.bias,r.power=i.power||1,r},t})();e.FresnelParameters=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i){var r=t.call(this,e,i,!0)||this;return i.multiMaterials.push(r),r.subMaterials=new Array,r.storeEffectOnSubMeshes=!0,r}return o(i,t),Object.defineProperty(i.prototype,"subMaterials",{get:function(){return this._subMaterials},set:function(e){this._subMaterials=e,this._hookArray(e)},enumerable:!0,configurable:!0}),i.prototype._hookArray=function(e){var t=this,i=e.push;e.push=function(){for(var r=[],n=0;n=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]},i.prototype.getActiveTextures=function(){return(e=t.prototype.getActiveTextures.call(this)).concat.apply(e,this.subMaterials.map((function(e){return e?e.getActiveTextures():[]})));var e},i.prototype.getClassName=function(){return"MultiMaterial"},i.prototype.isReadyForSubMesh=function(e,t,i){for(var r=0;r=0&&r.multiMaterials.splice(n,1),t.prototype.dispose.call(this,e,i)}},i})(e.Material);e.MultiMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250}return t.prototype.attachControl=function(t,i){var r=this,n=null;void 0===this._pointerInput&&(this._onLostFocus=function(e){r._offsetX=null,r._offsetY=null},this._pointerInput=function(t,o){var s=t.event;if("mouse"!==s.pointerType)if(t.type===e.PointerEventTypes.POINTERDOWN){if(i||s.preventDefault(),r._pointerPressed.push(s.pointerId),1!==r._pointerPressed.length)return;n={x:s.clientX,y:s.clientY}}else if(t.type===e.PointerEventTypes.POINTERUP){i||s.preventDefault();var a=r._pointerPressed.indexOf(s.pointerId);if(-1===a)return;if(r._pointerPressed.splice(a,1),0!=a)return;n=null,r._offsetX=null,r._offsetY=null}else if(t.type===e.PointerEventTypes.POINTERMOVE){if(i||s.preventDefault(),!n)return;var a=r._pointerPressed.indexOf(s.pointerId);if(0!=a)return;r._offsetX=s.clientX-n.x,r._offsetY=-(s.clientY-n.y)}}),this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE),this._onLostFocus&&t.addEventListener("blur",this._onLostFocus)},t.prototype.detachControl=function(e){this._pointerInput&&e&&(this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null),this._onLostFocus&&(e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null),this._pointerPressed=[],this._offsetX=null,this._offsetY=null)},t.prototype.checkInputs=function(){if(this._offsetX&&this._offsetY){var t=this.camera;if(t.cameraRotation.y+=this._offsetX/this.touchAngularSensibility,this._pointerPressed.length>1)t.cameraRotation.x+=-this._offsetY/this.touchAngularSensibility;else{var i=t._computeLocalCameraSpeed(),r=new e.Vector3(0,0,i*this._offsetY/this.touchMoveSensibility);e.Matrix.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,0,t._cameraRotationMatrix),t.cameraDirection.addInPlace(e.Vector3.TransformCoordinates(r,t._cameraRotationMatrix))}}},t.prototype.getClassName=function(){return"FreeCameraTouchInput"},t.prototype.getSimpleName=function(){return"touch"},n([e.serialize()],t.prototype,"touchAngularSensibility",void 0),n([e.serialize()],t.prototype,"touchMoveSensibility",void 0),t})();e.FreeCameraTouchInput=t,e.CameraInputTypes.FreeCameraTouchInput=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("TouchCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addTouch(),n._setupInputs(),n}return o(t,e),Object.defineProperty(t.prototype,"touchAngularSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"touchMoveSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"TouchCamera"},t.prototype._setupInputs=function(){var e=this.inputs.attached.mouse;e&&(e.touchEnabled=!1)},t})(e.FreeCamera);e.TouchCamera=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l){void 0===s&&(s=null),void 0===a&&(a=!0),void 0===l&&(l=!1);var h=t.call(this,null,o,!a)||this;h.isCube=l,h.isEnabled=!0,h._currentRefreshId=-1,h._refreshRate=1,h._vertexBuffers={},h._uniforms=new Array,h._samplers=new Array,h._textures={},h._floats={},h._ints={},h._floatsArrays={},h._colors3={},h._colors4={},h._vectors2={},h._vectors3={},h._matrices={},h._fallbackTextureUsed=!1,o=h.getScene(),o.proceduralTextures.push(h),h._engine=o.getEngine(),h.name=i,h.isRenderTarget=!0,h._size=r,h._generateMipMaps=a,h.setFragment(n),h._fallbackTexture=s,l?(h._texture=h._engine.createRenderTargetCubeTexture(r,{generateMipMaps:a}),h.setFloat("face",0)):h._texture=h._engine.createRenderTargetTexture(r,a);var c=[];return c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),h._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(h._engine,c,e.VertexBuffer.PositionKind,!1,!1,2),h._createIndexBuffer(),h}return o(i,t),i.prototype._createIndexBuffer=function(){var e=this._engine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)},i.prototype._rebuild=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&t._rebuild(),this._createIndexBuffer(),this.refreshRate===e.RenderTargetTexture.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=e.RenderTargetTexture.REFRESHRATE_RENDER_ONCE)},i.prototype.reset=function(){if(void 0!==this._effect){this._engine._releaseEffect(this._effect)}},i.prototype.isReady=function(){var t,i=this,r=this._engine;return!!this._fragment&&(!!this._fallbackTextureUsed||(t=void 0!==this._fragment.fragmentElement?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._effect=r.createEffect(t,[e.VertexBuffer.PositionKind],this._uniforms,this._samplers,"",void 0,void 0,(function(){i.releaseInternalTexture(),i._fallbackTexture&&(i._texture=i._fallbackTexture._texture,i._texture&&i._texture.incrementReferences()),i._fallbackTextureUsed=!0})),this._effect.isReady()))},i.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},i.prototype.setFragment=function(e){this._fragment=e},Object.defineProperty(i.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!0,configurable:!0}),i.prototype._shouldRender=function(){return!!(this.isEnabled&&this.isReady()&&this._texture)&&(!this._fallbackTextureUsed&&(-1===this._currentRefreshId?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)))},i.prototype.getRenderSize=function(){return this._size},i.prototype.resize=function(e,t){this._fallbackTextureUsed||(this.releaseInternalTexture(),this._texture=this._engine.createRenderTargetTexture(e,t),this._size=e,this._generateMipMaps=t)},i.prototype._checkUniform=function(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)},i.prototype.setTexture=function(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this},i.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},i.prototype.setInt=function(e,t){return this._checkUniform(e),this._ints[e]=t,this},i.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},i.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},i.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},i.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},i.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},i.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},i.prototype.render=function(t){var i=this.getScene();if(i){var r=this._engine;r.enableEffect(this._effect),r.setState(!1);for(var n in this._textures)this._effect.setTexture(n,this._textures[n]);for(n in this._ints)this._effect.setInt(n,this._ints[n]);for(n in this._floats)this._effect.setFloat(n,this._floats[n]);for(n in this._floatsArrays)this._effect.setArray(n,this._floatsArrays[n]);for(n in this._colors3)this._effect.setColor3(n,this._colors3[n]);for(n in this._colors4){var o=this._colors4[n];this._effect.setFloat4(n,o.r,o.g,o.b,o.a)}for(n in this._vectors2)this._effect.setVector2(n,this._vectors2[n]);for(n in this._vectors3)this._effect.setVector3(n,this._vectors3[n]);for(n in this._matrices)this._effect.setMatrix(n,this._matrices[n]);if(this._texture){if(this.isCube)for(var s=0;s<6;s++)r.bindFramebuffer(this._texture,s,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),this._effect.setFloat("face",s),r.clear(i.clearColor,!0,!0,!0),r.drawElementsType(e.Material.TriangleFillMode,0,6),5===s&&r.generateMipMapsForCubemap(this._texture);else r.bindFramebuffer(this._texture,0,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),r.clear(i.clearColor,!0,!0,!0),r.drawElementsType(e.Material.TriangleFillMode,0,6);r.unBindFramebuffer(this._texture,this.isCube),this.onGenerated&&this.onGenerated()}}},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t},i.prototype.dispose=function(){var i=this.getScene();if(i){var r=i.proceduralTextures.indexOf(this);r>=0&&i.proceduralTextures.splice(r,1);var n=this._vertexBuffers[e.VertexBuffer.PositionKind];n&&(n.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),t.prototype.dispose.call(this)}},n([e.serialize()],i.prototype,"_size",void 0),n([e.serialize()],i.prototype,"_generateMipMaps",void 0),n([e.serialize()],i.prototype,"isEnabled",void 0),n([e.serialize()],i.prototype,"refreshRate",null),i})(e.Texture);e.ProceduralTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i,r,n,o,s){var a=t.call(this,e,r,null,n,o,s)||this;return a._animate=!0,a._time=0,a._texturePath=i,a.loadJson(i),a.refreshRate=1,a}return o(i,t),i.prototype.loadJson=function(t){ -var i=this,r=function(){e.Tools.Log("No config file found in "+t+" trying to use ShadersStore or DOM element");try{i.setFragment(i._texturePath)}catch(t){e.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},n=t+"/config.json",o=new XMLHttpRequest;o.open("GET",n,!0),o.addEventListener("load",(function(){if(200===o.status||e.Tools.ValidateXHRData(o,1))try{i._config=JSON.parse(o.response),i.updateShaderUniforms(),i.updateTextures(),i.setFragment(i._texturePath+"/custom"),i._animate=i._config.animate,i.refreshRate=i._config.refreshrate}catch(e){r()}else r()}),!1),o.addEventListener("error",(function(){r()}),!1);try{o.send()}catch(t){e.Tools.Error("CustomProceduralTexture: Error on XHR send request.")}},i.prototype.isReady=function(){if(!t.prototype.isReady.call(this))return!1;for(var e in this._textures){if(!this._textures[e].isReady())return!1}return!0},i.prototype.render=function(e){var i=this.getScene();this._animate&&i&&(this._time+=.03*i.getAnimationRatio(),this.updateShaderUniforms()),t.prototype.render.call(this,e)},i.prototype.updateTextures=function(){for(var t=0;t.005?0+r:0,i.y=Math.abs(n)>.005?0+n:0;var o=this.gamepad.rightStick;if(o){var s=o.x/this.gamepadAngularSensibility,a=o.y/this.gamepadAngularSensibility;o.x=Math.abs(s)>.001?0+s:0,o.y=Math.abs(a)>.001?0+a:0}else o={x:0,y:0};t.rotationQuaternion?t.rotationQuaternion.toRotationMatrix(this._cameraTransform):e.Matrix.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,0,this._cameraTransform);var l=50*t._computeLocalCameraSpeed();this._vector3.copyFromFloats(i.x*l,0,-i.y*l),e.Vector3.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),t.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(o.y,o.x),t.cameraRotation.addInPlace(this._vector2)}},t.prototype.getClassName=function(){return"FreeCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},n([e.serialize()],t.prototype,"gamepadAngularSensibility",void 0),n([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.FreeCameraGamepadInput=t,e.CameraInputTypes.FreeCameraGamepadInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40}return t.prototype.attachControl=function(t,i){var r=this,n=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=n.onGamepadConnectedObservable.add((function(t){t.type!==e.Gamepad.POSE_ENABLED&&(r.gamepad&&t.type!==e.Gamepad.XBOX||(r.gamepad=t))})),this._onGamepadDisconnectedObserver=n.onGamepadDisconnectedObservable.add((function(e){r.gamepad===e&&(r.gamepad=null)})),this.gamepad=n.getGamepadByType(e.Gamepad.XBOX)},t.prototype.detachControl=function(e){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null},t.prototype.checkInputs=function(){if(this.gamepad){var e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){var i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){var r=t.y/this.gamepadRotationSensibility;0!=r&&Math.abs(r)>.005&&(e.inertialBetaOffset+=r)}}var n=this.gamepad.leftStick;if(n&&0!=n.y){var o=n.y/this.gamepadMoveSensibility;0!=o&&Math.abs(o)>.005&&(this.camera.inertialRadiusOffset-=o)}}},t.prototype.getClassName=function(){return"ArcRotateCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},n([e.serialize()],t.prototype,"gamepadRotationSensibility",void 0),n([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.ArcRotateCameraGamepadInput=t,e.CameraInputTypes.ArcRotateCameraGamepadInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){var i=this;this._scene=t,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new e.Observable,e.Tools.IsWindowObjectExist()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator.getGamepads||navigator.webkitGetGamepads||navigator.msGetGamepads||navigator.webkitGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new e.Observable(function(e){for(var t in i._babylonGamepads){var r=i._babylonGamepads[t];r&&r._isConnected&&i.onGamepadConnectedObservable.notifyObserver(e,r)}}),this._onGamepadConnectedEvent=function(e){var t=e.gamepad;if(!(t.index in i._babylonGamepads&&i._babylonGamepads[t.index].isConnected)){var r;i._babylonGamepads[t.index]?(r=i._babylonGamepads[t.index],r.browserGamepad=t,r._isConnected=!0):r=i._addNewGamepad(t),i.onGamepadConnectedObservable.notifyObservers(r),i._startMonitoringGamepads()}},this._onGamepadDisconnectedEvent=function(e){var t=e.gamepad;for(var r in i._babylonGamepads)if(i._babylonGamepads[r].index===t.index){var n=i._babylonGamepads[r];n._isConnected=!1,i.onGamepadDisconnectedObservable.notifyObservers(n);break}},this._gamepadSupport&&(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported?(window.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1)):this._startMonitoringGamepads())}return Object.defineProperty(t.prototype,"gamepads",{get:function(){return this._babylonGamepads},enumerable:!0,configurable:!0}),t.prototype.getGamepadByType=function(t){void 0===t&&(t=e.Gamepad.XBOX);for(var i=0,r=this._babylonGamepads;i=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}return Object.defineProperty(e.prototype,"isConnected",{get:function(){return this._isConnected},enumerable:!0,configurable:!0}),e.prototype.onleftstickchanged=function(e){this._onleftstickchanged=e},e.prototype.onrightstickchanged=function(e){this._onrightstickchanged=e},Object.defineProperty(e.prototype,"leftStick",{get:function(){return this._leftStick},set:function(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightStick",{get:function(){return this._rightStick},set:function(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e},enumerable:!0,configurable:!0}),e.prototype.update=function(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})},e.prototype.dispose=function(){},e.GAMEPAD=0,e.GENERIC=1,e.XBOX=2,e.POSE_ENABLED=3,e})();e.Gamepad=i;var r=(function(t){function r(r,n,o){var s=t.call(this,r,n,o)||this;return s.onButtonDownObservable=new e.Observable,s.onButtonUpObservable=new e.Observable,s.type=i.GENERIC,s._buttons=new Array(o.buttons.length),s}return o(r,t),r.prototype.onbuttondown=function(e){this._onbuttondown=e},r.prototype.onbuttonup=function(e){this._onbuttonup=e},r.prototype._setButtonValue=function(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},r.prototype.update=function(){t.prototype.update.call(this);for(var e=0;ethis._maxRotationDistFromHeadset){var n=r-(r<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=n;var o=Math.sin(-n),s=Math.cos(-n);this._calculatedPosition.x=this._calculatedPosition.x*s-this._calculatedPosition.z*o,this._calculatedPosition.z=this._calculatedPosition.x*o+this._calculatedPosition.z*s}}},i.prototype.initControllerMesh=function(t,r){var n=this;e.SceneLoader.ImportMesh("",i.MODEL_BASE_URL,i.MODEL_FILENAME,t,(function(i){var o=new e.Mesh("",t);i[1].parent=o,i[1].position.z=-.15,n._defaultModel=o,n.attachToMesh(n._defaultModel),r&&r(n._defaultModel)}))},i.prototype._handleButtonChange=function(e,t,i){if(ethis.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(f>this.maxCameraSpeed||f<-this.maxCameraSpeed)&&(f=f<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new e.Vector3(this.position.x+u,this.position.y+f,this.position.z+d),this.setTarget(o)}},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.lockedTarget&&this.follow(this.lockedTarget)},i.prototype.getClassName=function(){return"FollowCamera"},n([e.serialize()],i.prototype,"radius",void 0),n([e.serialize()],i.prototype,"rotationOffset",void 0),n([e.serialize()],i.prototype,"heightOffset",void 0),n([e.serialize()],i.prototype,"cameraAcceleration",void 0),n([e.serialize()],i.prototype,"maxCameraSpeed",void 0),n([e.serializeAsMeshReference("lockedTargetId")],i.prototype,"lockedTarget",void 0),i})(e.TargetCamera);e.FollowCamera=t;var i=(function(t){function i(i,r,n,o,s,a){var l=t.call(this,i,e.Vector3.Zero(),a)||this;return l.alpha=r,l.beta=n,l.radius=o,l.target=s,l._cartesianCoordinates=e.Vector3.Zero(),l.follow(),l}return o(i,t),i.prototype.follow=function(){if(this.target){this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);var e=this.target.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.follow()},i.prototype.getClassName=function(){return"ArcFollowCamera"},i})(e.TargetCamera);e.ArcFollowCamera=i})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addGamepad(),n}return o(t,e),Object.defineProperty(t.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"UniversalCamera"},t})(e.TouchCamera);e.UniversalCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("GamepadCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(e){function t(t,i,r){return e.call(this,t,i,r)||this}return o(t,e),Object.defineProperty(t.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"GamepadCamera"},t})(e.UniversalCamera);e.GamepadCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this._renderPipelines={}}return e.prototype.addPipeline=function(e){this._renderPipelines[e._name]=e},e.prototype.attachCamerasToRenderPipeline=function(e,t,i){void 0===i&&(i=!1);var r=this._renderPipelines[e];r&&r._attachCameras(t,i)},e.prototype.detachCamerasFromRenderPipeline=function(e,t){var i=this._renderPipelines[e];i&&i._detachCameras(t)},e.prototype.enableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._enableEffect(t,i)},e.prototype.disableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._disableEffect(t,i)},e.prototype.update=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}},e.prototype._rebuild=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t._rebuild()}},e.prototype.dispose=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t.dispose()}},e})();e.PostProcessRenderPipelineManager=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}return Object.defineProperty(t.prototype,"isSupported",{get:function(){for(var e in this._postProcesses)if(this._postProcesses.hasOwnProperty(e))for(var t=this._postProcesses[e],i=0;i=2&&t.length>0){var i=this._renderEffects[t[0]].getPostProcesses();if(i)return i[0].samples=e,!0}return!1},t.prototype.dispose=function(){},n([e.serialize()],t.prototype,"_name",void 0),t})();e.PostProcessRenderPipeline=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){void 0===i&&(i=e.Engine.TEXTURETYPE_FLOAT),void 0===r&&(r=null);var n=this;this._scene=t,this._camera=r;var o=t.getEngine();this._depthMap=new e.RenderTargetTexture("depthMap",{width:o.getRenderWidth(),height:o.getRenderHeight()},this._scene,!1,!0,i),this._depthMap.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._depthMap.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((function(t){t.clear(new e.Color4(1,1,1,1),!0,!0,!0)}));var s=function(t){var i=t.getRenderingMesh(),r=n._scene,o=r.getEngine(),s=t.getMaterial();if(s){o.setState(s.backFaceCulling,0,!1,r.useRightHandedSystem);var a=i._getInstancesRenderList(t._id);if(!a.mustReturn){var l=o.getCaps().instancedArrays&&null!==a.visibleInstances[t._id],h=n._camera||r.activeCamera;if(n.isReady(t,l)&&h){if(o.enableEffect(n._effect),i._bind(t,n._effect,e.Material.TriangleFillMode),n._effect.setMatrix("viewProjection",r.getTransformMatrix()),n._effect.setFloat2("depthValues",h.minZ,h.minZ+h.maxZ),s&&s.needAlphaTesting()){var c=s.getAlphaTestTexture();c&&(n._effect.setTexture("diffuseSampler",c),n._effect.setMatrix("diffuseMatrix",c.getTextureMatrix()))}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&n._effect.setMatrices("mBones",i.skeleton.getTransformMatrices(i)),i._processRendering(t,n._effect,e.Material.TriangleFillMode,a,l,(function(e,t){return n._effect.setMatrix("world",t)}))}}}};this._depthMap.customRenderFunction=function(e,t,i,r){var n;if(r.length){for(o.setColorWrite(!1),n=0;n4&&(o.push(e.VertexBuffer.MatricesIndicesExtraKind),o.push(e.VertexBuffer.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("depth",o,["world","mBones","viewProjection","diffuseMatrix","depthValues"],["diffuseSampler"],a)),this._effect.isReady()},t.prototype.getDepthMap=function(){return this._depthMap},t.prototype.dispose=function(){this._depthMap.dispose()},t})();e.DepthRenderer=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o){var s=t.call(this,r.getEngine(),i)||this;s.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",s.SSAORenderEffect="SSAORenderEffect",s.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",s.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",s.SSAOCombineRenderEffect="SSAOCombineRenderEffect",s.totalStrength=1,s.radius=1e-4,s.area=.0075,s.fallOff=1e-6,s.base=.5,s._firstUpdate=!0,s._scene=r,s._createRandomTexture(),s._depthTexture=r.enableDepthRenderer().getDepthMap();var a=n.ssaoRatio||n,l=n.combineRatio||n;return s._originalColorPostProcess=new e.PassPostProcess("SSAOOriginalSceneColor",l,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),!1),s._createSSAOPostProcess(a),s._createBlurPostProcess(a),s._createSSAOCombinePostProcess(l),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOOriginalSceneColorEffect,function(){return s._originalColorPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAORenderEffect,function(){return s._ssaoPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOBlurHRenderEffect,function(){return s._blurHPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOBlurVRenderEffect,function(){return s._blurVPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOCombineRenderEffect,function(){return s._ssaoCombinePostProcess},!0)),r.postProcessRenderPipelineManager.addPipeline(s),o&&r.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(i,o),s}return o(i,t),i.prototype.dispose=function(e){void 0===e&&(e=!1);for(var i=0;i0?r._ssaoCombinePostProcess.width:r._originalColorPostProcess.width),e.setFloat("near",r._scene.activeCamera.minZ),e.setFloat("far",r._scene.activeCamera.maxZ),e.setFloat("radius",r.radius),e.setTexture("depthSampler",r._depthTexture),r._firstUpdate&&e.setArray("samplerOffsets",r._samplerOffsets))},this._blurVPostProcess=new e.PostProcess("BlurV","ssao2",["outSize","samplerOffsets","near","far","radius"],["depthSampler"],i,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE "+(n?"1":"0")+"\n"),this._blurVPostProcess.onApply=function(e){r._scene.activeCamera&&(e.setFloat("outSize",r._ssaoCombinePostProcess.height>0?r._ssaoCombinePostProcess.height:r._originalColorPostProcess.height),e.setFloat("near",r._scene.activeCamera.minZ),e.setFloat("far",r._scene.activeCamera.maxZ),e.setFloat("radius",r.radius),e.setTexture("depthSampler",r._depthTexture),r._firstUpdate&&(e.setArray("samplerOffsets",r._samplerOffsets),r._firstUpdate=!1))}},i.prototype._rebuild=function(){this._firstUpdate=!0,t.prototype._rebuild.call(this)},i.prototype._generateHemisphere=function(){for(var t,i,r=this.samples,n=[],o=function(e,t){return Math.random()*(t-e)+e},s=0;s=0;a--){var o=Math.pow(3,a),l="#define LUMINANCE_DOWN_SAMPLE\n";0===a&&(l+="#define FINAL_DOWN_SAMPLER");var h=new e.PostProcess("HDRLuminanceDownSample"+a,"standard",["dsOffsets","halfDestPixelSize"],[],{width:o,height:o},null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,l,r);this.luminanceDownSamplePostProcesses.push(h)}var c=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((function(i,r){var o=new Array(18);i.onApply=function(e){if(c){for(var t=0,s=-1;s<2;s++)for(var a=-1;a<2;a++)o[t]=s/c.width,o[t+1]=a/c.height,t+=2;e.setArray2("dsOffsets",o),e.setFloat("halfDestPixelSize",.5/c.width),c=r===n.luminanceDownSamplePostProcesses.length-1?n.luminancePostProcess:i}},r===n.luminanceDownSamplePostProcesses.length-1&&(i.onAfterRender=function(i){var r=t.getEngine().readPixels(0,0,1,1),o=new e.Vector4(1/16581375,1/65025,1/255,1);n._hdrCurrentLuminance=(r[0]*o.x+r[1]*o.y+r[2]*o.z+r[3]*o.w)/100}),n.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLuminanceDownSample"+r,function(){return i},!0))}))},i.prototype._createHdrPostProcess=function(t,i){var r=this;this.hdrPostProcess=new e.PostProcess("HDR","standard",["averageLuminance"],["textureAdderSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define HDR",e.Engine.TEXTURETYPE_UNSIGNED_INT);var n=1,o=0,s=0;this.hdrPostProcess.onApply=function(i){if(i.setTextureFromPostProcess("textureAdderSampler",r._currentDepthOfFieldSource),o+=t.getEngine().getDeltaTime(),n<0)n=r._hdrCurrentLuminance;else{var a=(s-o)/1e3;r._hdrCurrentLuminancen-r.hdrIncreaseRate*a?n-=r.hdrIncreaseRate*a:n=r._hdrCurrentLuminance}n=e.Scalar.Clamp(n,r.hdrMinimumLuminance,1e20),i.setFloat("averageLuminance",n),s=o,r._currentDepthOfFieldSource=r.hdrFinalPostProcess},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDR",function(){return r.hdrPostProcess},!0))},i.prototype._createLensFlarePostProcess=function(t,i){var r=this;this.lensFlarePostProcess=new e.PostProcess("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],i/2,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define LENS_FLARE",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLensFlare",function(){return r.lensFlarePostProcess},!0)),this._createBlurPostProcesses(t,i/4,2),this.lensFlareComposePostProcess=new e.PostProcess("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define LENS_FLARE_COMPOSE",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLensFlareCompose",function(){return r.lensFlareComposePostProcess},!0));var n=new e.Vector2(0,0);this.lensFlarePostProcess.onApply=function(e){e.setTextureFromPostProcess("textureSampler",r._bloomEnabled?r.blurHPostProcesses[0]:r.originalPostProcess),e.setTexture("lensColorSampler",r.lensColorTexture),e.setFloat("strength",r.lensFlareStrength),e.setFloat("ghostDispersal",r.lensFlareGhostDispersal),e.setFloat("haloWidth",r.lensFlareHaloWidth),n.x=r.lensFlarePostProcess.width,n.y=r.lensFlarePostProcess.height,e.setVector2("resolution",n),e.setFloat("distortionStrength",r.lensFlareDistortionStrength)};var o=e.Matrix.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=e.Matrix.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=function(t){if(r._scene.activeCamera){t.setTextureFromPostProcess("otherSampler",r._currentDepthOfFieldSource),t.setTexture("lensDirtSampler",r.lensFlareDirtTexture),t.setTexture("lensStarSampler",r.lensStarTexture);var i=r._scene.activeCamera.getViewMatrix().getRow(0),n=r._scene.activeCamera.getViewMatrix().getRow(2),a=e.Vector3.Dot(i.toVector3(),new e.Vector3(1,0,0))+e.Vector3.Dot(n.toVector3(),new e.Vector3(0,0,1));a*=4;var l=e.Matrix.FromValues(.5*Math.cos(a),-Math.sin(a),0,0,Math.sin(a),.5*Math.cos(a),0,0,0,0,1,0,0,0,0,1),h=s.multiply(l).multiply(o);t.setMatrix("lensStarMatrix",h),r._currentDepthOfFieldSource=r.lensFlareFinalPostProcess}}},i.prototype._createDepthOfFieldPostProcess=function(t,i){var r=this;this.depthOfFieldPostProcess=new e.PostProcess("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define DEPTH_OF_FIELD",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.depthOfFieldPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",r._currentDepthOfFieldSource),e.setTexture("depthSampler",r._getDepthTexture()),e.setFloat("distance",r.depthOfFieldDistance)},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRDepthOfField",function(){return r.depthOfFieldPostProcess},!0))},i.prototype._createMotionBlurPostProcess=function(t,i){var r=this;this.motionBlurPostProcess=new e.PostProcess("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),e.Engine.TEXTURETYPE_UNSIGNED_INT);var n=0,o=e.Matrix.Identity(),s=e.Matrix.Identity(),a=e.Matrix.Identity(),l=e.Vector2.Zero();this.motionBlurPostProcess.onApply=function(e){a=t.getProjectionMatrix().multiply(t.getViewMatrix()),a.invertToRef(s),e.setMatrix("inverseViewProjection",s),e.setMatrix("prevViewProjection",o),o=a,l.x=r.motionBlurPostProcess.width,l.y=r.motionBlurPostProcess.height,e.setVector2("screenSize",l),n=t.getEngine().getFps()/60,e.setFloat("motionScale",n),e.setFloat("motionStrength",r.motionStrength),e.setTexture("depthSampler",r._getDepthTexture())},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRMotionBlur",function(){return r.motionBlurPostProcess},!0))},i.prototype._getDepthTexture=function(){if(this._scene.getEngine().getCaps().drawBuffersExtension){return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]}return this._scene.enableDepthRenderer().getDepthMap()},i.prototype._disposePostProcesses=function(){for(var e=0;e-1?"#define MALI 1\n":null},i})(e.PostProcess);e.FxaaPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h,c,u){void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===u&&(u=!1);var f=t.call(this,i,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],o,s,a,l,h,null,c,void 0,null,u)||this;return f.aberrationAmount=30,f.radialIntensity=0,f.direction=new e.Vector2(.707,.707),f.centerPosition=new e.Vector2(.5,.5),f.onApplyObservable.add((function(e){e.setFloat("chromatic_aberration",f.aberrationAmount),e.setFloat("screen_width",r),e.setFloat("screen_height",n),e.setFloat("radialIntensity",f.radialIntensity),e.setFloat2("direction",f.direction.x,f.direction.y),e.setFloat2("centerPosition",f.centerPosition.x,f.centerPosition.y)})),f}return o(i,t),i})(e.PostProcess);e.ChromaticAberrationPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h){void 0===l&&(l=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1);var c=t.call(this,i,"grain",["intensity","animatedSeed"],[],r,n,o,s,a,null,l,void 0,null,h)||this;return c.intensity=30,c.animated=!1,c.onApplyObservable.add((function(e){e.setFloat("intensity",c.intensity),e.setFloat("animatedSeed",c.animated?Math.random()+1:1)})),c}return o(i,t),i})(e.PostProcess);e.GrainPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h){void 0===l&&(l=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1);var c=t.call(this,i,"sharpen",["sharpnessAmounts","screenSize"],null,r,n,o,s,a,null,l,void 0,null,h)||this;return c.colorAmount=1,c.edgeAmount=.3,c.onApply=function(e){e.setFloat2("screenSize",c.width,c.height),e.setFloat2("sharpnessAmounts",c.edgeAmount,c.colorAmount)},c}return o(i,t),i})(e.PostProcess);e.SharpenPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h,c,u,f){void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===u&&(u=""),void 0===f&&(f=!1);var d=t.call(this,i,"kernelBlur",["delta","direction","cameraMinMaxZ"],["circleOfConfusionSampler"],o,s,a,l,h,null,c,"kernelBlur",{varyingCount:0,depCount:0},!0)||this;return d.direction=r,d.blockCompilation=f,d._packedFloat=!1,d._staticDefines="",d._staticDefines=u,d.onApplyObservable.add((function(e){d._outputTexture?e.setFloat2("delta",1/d._outputTexture.width*d.direction.x,1/d._outputTexture.height*d.direction.y):e.setFloat2("delta",1/d.width*d.direction.x,1/d.height*d.direction.y)})),d.kernel=n,d}return o(i,t),Object.defineProperty(i.prototype,"kernel",{get:function(){return this._idealKernel},set:function(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.blockCompilation||this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"packedFloat",{get:function(){return this._packedFloat},set:function(e){this._packedFloat!==e&&(this._packedFloat=e,this.blockCompilation||this._updateParameters())},enumerable:!0,configurable:!0}),i.prototype.updateEffect=function(e,t,i,r,n,o){void 0===e&&(e=null),void 0===t&&(t=null),void 0===i&&(i=null),this._updateParameters(n,o)},i.prototype._updateParameters=function(e,i){for(var r=this._kernel,n=(r-1)/2,o=[],s=[],a=0,l=0;l0)return Math.max(n,3)}return Math.max(t,3)},i.prototype._gaussianWeight=function(e){var t=Math.sqrt(2*Math.PI)*(1/3),i=-e*e/(1/3*2*(1/3));return 1/t*Math.exp(i)},i.prototype._glslFloat=function(e,t){return void 0===t&&(t=8),e.toFixed(t).replace(/0+$/,"")},i})(e.PostProcess);e.BlurPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h,c,u,f,d,p){void 0===h&&(h=null),void 0===c&&(c=e.Texture.BILINEAR_SAMPLINGMODE),void 0===d&&(d=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===p&&(p=!1);var m=t.call(this,i,n,o,s,a,c=e.Texture.BILINEAR_SAMPLINGMODE,u,f,d=e.Engine.TEXTURETYPE_UNSIGNED_INT,"#define DOF 1\r\n",p)||this;return m.direction=n,m.onApplyObservable.add((function(e){null!=h&&e.setTextureFromPostProcess("textureSampler",h),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",l),r.activeCamera&&e.setFloat2("cameraMinMaxZ",r.activeCamera.minZ,r.activeCamera.maxZ)})),m}return o(i,t),i})(e.BlurPostProcess);e.DepthOfFieldBlurPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){}return e})();e.DepthOfFieldMergePostProcessOptions=t;var i=(function(t){function i(i,r,n,o,s,a,l,h,c,u,f){void 0===u&&(u=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===f&&(f=!1);var d=t.call(this,i,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,a,l,h,c,null,u,void 0,null,!0)||this;return d.blurSteps=o,d.onApplyObservable.add((function(e){e.setTextureFromPostProcess("textureSampler",r),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",n),o.forEach((function(t,i){e.setTextureFromPostProcessOutput("blurStep"+(o.length-i-1),t)}))})),f||d.updateEffect(),d}return o(i,t),i.prototype.updateEffect=function(e,i,r,n,o,s){void 0===e&&(e=null),void 0===i&&(i=null),void 0===r&&(r=null),e||(e="",e+="#define BLUR_LEVEL "+(this.blurSteps.length-1)+"\n"),t.prototype.updateEffect.call(this,e,i,r,n,o,s)},i})(e.PostProcess);e.DepthOfFieldMergePostProcess=i})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h,c){void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var u=t.call(this,i,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],n,o,s,a,l,null,h,void 0,null,c)||this;return u.lensSize=50,u.fStop=1.4,u.focusDistance=2e3,u.focalLength=50,u._depthTexture=null,u._depthTexture=r,u.onApplyObservable.add((function(t){if(!u._depthTexture)return void e.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");t.setTexture("depthSampler",u._depthTexture);var i=u.lensSize/u.fStop,r=i*u.focalLength/(u.focusDistance-u.focalLength);t.setFloat("focusDistance",u.focusDistance),t.setFloat("cocPrecalculation",r),t.setFloat2("cameraMinMaxZ",u._depthTexture.activeCamera.minZ,u._depthTexture.activeCamera.maxZ)})),u}return o(i,t),Object.defineProperty(i.prototype,"depthTexture",{set:function(e){this._depthTexture=e},enumerable:!0,configurable:!0}),i})(e.PostProcess);e.CircleOfConfusionPostProcess=t})(r||(r={}));var r;!(function(e){var t;!(function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"})(t=e.DepthOfFieldEffectBlurLevel||(e.DepthOfFieldEffectBlurLevel={}));var i=(function(i){function r(r,n,o,s,a){void 0===o&&(o=t.Low),void 0===s&&(s=0),void 0===a&&(a=!1);var l=i.call(this,r.getEngine(),"depth of field",(function(){return l._effects}),!0)||this;l._effects=[],l._circleOfConfusion=new e.CircleOfConfusionPostProcess("circleOfConfusion",n,1,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),!1,s,a),l._depthOfFieldBlurY=[],l._depthOfFieldBlurX=[];var h=1,c=15;switch(o){case t.High:h=3,c=51;break;case t.Medium:h=2,c=31;break;default:c=15,h=1}for(var u=c/Math.pow(2,h-1),f=1,d=0;d1&&e.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}},i.prototype._disposePostProcesses=function(e){void 0===e&&(e=!1);for(var t=0;t4&&(o.push(e.VertexBuffer.MatricesIndicesExtraKind),o.push(e.VertexBuffer.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("geometry",o,["world","mBones","viewProjection","diffuseMatrix","view"],["diffuseSampler"],a,void 0,void 0,void 0,{buffersCount:this._enablePosition?3:2})),this._effect.isReady()},t.prototype.getGBuffer=function(){return this._multiRenderTarget},Object.defineProperty(t.prototype,"samples",{get:function(){return this._multiRenderTarget.samples},set:function(e){this._multiRenderTarget.samples=e},enumerable:!0, -configurable:!0}),t.prototype.dispose=function(){this.getGBuffer().dispose()},t.prototype._createRenderTargets=function(){var t=this,i=this._scene.getEngine(),r=this._enablePosition?3:2;if(this._multiRenderTarget=new e.MultiRenderTarget("gBuffer",{width:i.getRenderWidth()*this._ratio,height:i.getRenderHeight()*this._ratio},r,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:e.Engine.TEXTURETYPE_FLOAT}),this.isSupported){this._multiRenderTarget.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null,this._multiRenderTarget.onClearObservable.add((function(t){t.clear(new e.Color4(0,0,0,1),!0,!0,!0)}));var n=function(i){var r=i.getRenderingMesh(),n=t._scene,o=n.getEngine(),s=i.getMaterial();if(s){o.setState(s.backFaceCulling,0,!1,n.useRightHandedSystem);var a=r._getInstancesRenderList(i._id);if(!a.mustReturn){var l=o.getCaps().instancedArrays&&null!==a.visibleInstances[i._id];if(t.isReady(i,l)){if(o.enableEffect(t._effect),r._bind(i,t._effect,e.Material.TriangleFillMode),t._effect.setMatrix("viewProjection",n.getTransformMatrix()),t._effect.setMatrix("view",n.getViewMatrix()),s&&s.needAlphaTesting()){var h=s.getAlphaTestTexture();h&&(t._effect.setTexture("diffuseSampler",h),t._effect.setMatrix("diffuseMatrix",h.getTextureMatrix()))}r.useBones&&r.computeBonesUsingShaders&&r.skeleton&&t._effect.setMatrices("mBones",r.skeleton.getTransformMatrices(r)),r._processRendering(i,t._effect,e.Material.TriangleFillMode,a,l,(function(e,i){return t._effect.setMatrix("world",i)}))}}}};this._multiRenderTarget.customRenderFunction=function(e,t,r,o){var s;if(o.length){for(i.setColorWrite(!1),s=0;s1,n.wrapU=e.Texture.CLAMP_ADDRESSMODE,n.wrapV=e.Texture.CLAMP_ADDRESSMODE,n.wrapR=e.Texture.CLAMP_ADDRESSMODE,n.anisotropicFilteringLevel=1,n._texture=n._getFromCache(i,!0),n._texture||(r.useDelayedTextureLoading?n.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED:n.loadTexture()),n):n}return o(i,t),i.prototype.getTextureMatrix=function(){return this._textureMatrix},i.prototype.load3dlTexture=function(){var t,r=this._engine;t=1===r.webGLVersion?r.createRawTexture(null,1,1,e.Engine.TEXTUREFORMAT_RGBA,!1,!1,e.Texture.BILINEAR_SAMPLINGMODE):r.createRawTexture3D(null,1,1,1,e.Engine.TEXTUREFORMAT_RGBA,!1,!1,e.Texture.BILINEAR_SAMPLINGMODE),this._texture=t;var n=function(n){if("string"==typeof n){for(var o,s=null,a=null,l=n.split("\n"),h=0,c=0,u=0,f=0,d=0,p=0;p0&&(p+1)%4==0)s[p]=255;else{var b=a[p];s[p]=b/d*255}t.is3D?(t.updateSize(h,h,h),r.updateRawTexture3D(t,s,e.Engine.TEXTUREFORMAT_RGBA,!1)):(t.updateSize(h*h,h),r.updateRawTexture(t,s,e.Engine.TEXTUREFORMAT_RGBA,!1))}},o=this.getScene();return o?o._loadFile(this.url,n):this._engine._loadFile(this.url,n),this._texture},i.prototype.loadTexture=function(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this.load3dlTexture()},i.prototype.clone=function(){var e=new i(this.url,this.getScene());return e.level=this.level,e},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,!0),this._texture||this.loadTexture())},i.Parse=function(e,t,r){var n=null;return e.name&&!e.isRenderTarget&&(n=new i(e.name,t),n.name=e.name,n.level=e.level),n},i.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e},i._noneEmptyLineRegex=/\S+/,i})(e.BaseTexture);e.ColorGradingTexture=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._dirty=!0,this._tempColor=new e.Color4(0,0,0,0),this._globalCurve=new e.Color4(0,0,0,0),this._highlightsCurve=new e.Color4(0,0,0,0),this._midtonesCurve=new e.Color4(0,0,0,0),this._shadowsCurve=new e.Color4(0,0,0,0),this._positiveCurve=new e.Color4(0,0,0,0),this._negativeCurve=new e.Color4(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}return Object.defineProperty(t.prototype,"globalHue",{get:function(){return this._globalHue},set:function(e){this._globalHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalDensity",{get:function(){return this._globalDensity},set:function(e){this._globalDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalSaturation",{get:function(){return this._globalSaturation},set:function(e){this._globalSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalExposure",{get:function(){return this._globalExposure},set:function(e){this._globalExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsHue",{get:function(){return this._highlightsHue},set:function(e){this._highlightsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsDensity",{get:function(){return this._highlightsDensity},set:function(e){this._highlightsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsSaturation",{get:function(){return this._highlightsSaturation},set:function(e){this._highlightsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsExposure",{get:function(){return this._highlightsExposure},set:function(e){this._highlightsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesHue",{get:function(){return this._midtonesHue},set:function(e){this._midtonesHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesDensity",{get:function(){return this._midtonesDensity},set:function(e){this._midtonesDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesSaturation",{get:function(){return this._midtonesSaturation},set:function(e){this._midtonesSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesExposure",{get:function(){return this._midtonesExposure},set:function(e){this._midtonesExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsHue",{get:function(){return this._shadowsHue},set:function(e){this._shadowsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsDensity",{get:function(){return this._shadowsDensity},set:function(e){this._shadowsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsSaturation",{get:function(){return this._shadowsSaturation},set:function(e){this._shadowsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsExposure",{get:function(){return this._shadowsExposure},set:function(e){this._shadowsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"ColorCurves"},t.Bind=function(e,t,i,r,n){void 0===i&&(i="vCameraColorCurvePositive"),void 0===r&&(r="vCameraColorCurveNeutral"),void 0===n&&(n="vCameraColorCurveNegative"),e._dirty&&(e._dirty=!1,e.getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e.getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e.getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e.getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(n,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))},t.PrepareUniforms=function(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")},t.prototype.getColorGradingDataToRef=function(e,i,r,n,o){null!=e&&(e=t.clamp(e,0,360),i=t.clamp(i,-100,100),r=t.clamp(r,-100,100),n=t.clamp(n,-100,100),i=t.applyColorGradingSliderNonlinear(i),i*=.5,n=t.applyColorGradingSliderNonlinear(n),i<0&&(i*=-1,e=(e+180)%360),t.fromHSBToRef(e,i,50+.25*n,o),o.scaleToRef(2,o),o.a=1+.01*r)},t.applyColorGradingSliderNonlinear=function(e){e/=100;var t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100},t.fromHSBToRef=function(e,i,r,n){var o=t.clamp(e,0,360),s=t.clamp(i/100,0,1),a=t.clamp(r/100,0,1);if(0===s)n.r=a,n.g=a,n.b=a;else{o/=60;var l=Math.floor(o),h=o-l,c=a*(1-s),u=a*(1-s*h),f=a*(1-s*(1-h));switch(l){case 0:n.r=a,n.g=f,n.b=c;break;case 1:n.r=u,n.g=a,n.b=c;break;case 2:n.r=c,n.g=a,n.b=f;break;case 3:n.r=c,n.g=u,n.b=a;break;case 4:n.r=f,n.g=c,n.b=a;break;default:n.r=a,n.g=c,n.b=u}}n.a=1},t.clamp=function(e,t,i){return Math.min(Math.max(e,t),i)},t.prototype.clone=function(){return e.SerializationHelper.Clone((function(){return new t}),this)},t.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},t.Parse=function(i){return e.SerializationHelper.Parse((function(){return new t}),i,null,null)},n([e.serialize()],t.prototype,"_globalHue",void 0),n([e.serialize()],t.prototype,"_globalDensity",void 0),n([e.serialize()],t.prototype,"_globalSaturation",void 0),n([e.serialize()],t.prototype,"_globalExposure",void 0),n([e.serialize()],t.prototype,"_highlightsHue",void 0),n([e.serialize()],t.prototype,"_highlightsDensity",void 0),n([e.serialize()],t.prototype,"_highlightsSaturation",void 0),n([e.serialize()],t.prototype,"_highlightsExposure",void 0),n([e.serialize()],t.prototype,"_midtonesHue",void 0),n([e.serialize()],t.prototype,"_midtonesDensity",void 0),n([e.serialize()],t.prototype,"_midtonesSaturation",void 0),n([e.serialize()],t.prototype,"_midtonesExposure",void 0),t})();e.ColorCurves=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h,c,u){var f=t.call(this,i,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],a,l,h,c,u)||this;return f.color=n,f.depth=o,f.colorLevel=s,f._ownRefractionTexture=!0,f.onActivateObservable.add((function(t){f._refTexture=f._refTexture||new e.Texture(r,t.getScene())})),f.onApplyObservable.add((function(e){e.setColor3("baseColor",f.color),e.setFloat("depth",f.depth),e.setFloat("colorLevel",f.colorLevel),e.setTexture("refractionSampler",f._refTexture)})),f}return o(i,t),Object.defineProperty(i.prototype,"refractionTexture",{get:function(){return this._refTexture},set:function(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1},enumerable:!0,configurable:!0}),i.prototype.dispose=function(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),t.prototype.dispose.call(this,e)},i})(e.PostProcess);e.RefractionPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){var a=e.call(this,t,"blackAndWhite",["degree"],null,i,r,n,o,s)||this;return a.degree=1,a.onApplyObservable.add((function(e){e.setFloat("degree",a.degree)})),a}return o(t,e),t})(e.PostProcess);e.BlackAndWhitePostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h){void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT);var c=t.call(this,i,"convolution",["kernel","screenSize"],null,n,o,s,a,l,null,h)||this;return c.kernel=r,c.onApply=function(e){e.setFloat2("screenSize",c.width,c.height),e.setArray("kernel",c.kernel)},c}return o(i,t),i.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],i.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],i.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],i.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],i.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],i.GaussianKernel=[0,1,0,1,1,1,0,1,0],i})(e.PostProcess);e.ConvolutionPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i,r,n,o,s,a){var l=e.call(this,t,"filter",["kernelMatrix"],null,r,n,o,s,a)||this;return l.kernelMatrix=i,l.onApply=function(e){e.setMatrix("kernelMatrix",l.kernelMatrix)},l}return o(t,e),t})(e.PostProcess);e.FilterPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(r,n,o,s,a,l,h,c,u){void 0===a&&(a=100),void 0===l&&(l=e.Texture.BILINEAR_SAMPLINGMODE);var f=t.call(this,r,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],n.postProcessRatio||n,o,l,h,c,"#define NUM_SAMPLES "+a)||this;return f._screenCoordinates=e.Vector2.Zero(),f.customMeshPosition=e.Vector3.Zero(),f.useCustomMeshPosition=!1,f.invert=!0,f.excludedMeshes=new Array,f.exposure=.3,f.decay=.96815,f.weight=.58767,f.density=.926,u=null===o?u:o.getScene(),h=u.getEngine(),f._viewPort=new e.Viewport(0,0,1,1).toGlobal(h.getRenderWidth(),h.getRenderHeight()),f.mesh=null!==s?s:i.CreateDefaultMesh("VolumetricLightScatteringMesh",u),f._createPass(u,n.passRatio||n),f.onActivate=function(e){f.isSupported||f.dispose(e),f.onActivate=null},f.onApplyObservable.add((function(e){f._updateMeshScreenCoordinates(u),e.setTexture("lightScatteringSampler",f._volumetricLightScatteringRTT),e.setFloat("exposure",f.exposure),e.setFloat("decay",f.decay),e.setFloat("weight",f.weight),e.setFloat("density",f.density),e.setVector2("meshPositionOnScreen",f._screenCoordinates)})),f}return o(i,t),Object.defineProperty(i.prototype,"useDiffuseColor",{get:function(){return e.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1},set:function(t){e.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"VolumetricLightScatteringPostProcess"},i.prototype._isReady=function(t,i){var r=t.getMesh();if(r===this.mesh&&r.material)return r.material.isReady(r);var n=[],o=[e.VertexBuffer.PositionKind],s=t.getMaterial();s&&(s.needAlphaTesting()&&n.push("#define ALPHATEST"),r.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(o.push(e.VertexBuffer.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(o.push(e.VertexBuffer.UV2Kind),n.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(o.push(e.VertexBuffer.MatricesIndicesKind),o.push(e.VertexBuffer.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._volumetricLightScatteringPass=r.getScene().getEngine().createEffect({vertexElement:"depth",fragmentElement:"volumetricLightScatteringPass"},o,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],a)),this._volumetricLightScatteringPass.isReady()},i.prototype.setCustomMeshPosition=function(e){this.customMeshPosition=e},i.prototype.getCustomMeshPosition=function(){return this.customMeshPosition},i.prototype.dispose=function(e){var i=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==i&&e.getScene().customRenderTargets.splice(i,1),this._volumetricLightScatteringRTT.dispose(),t.prototype.dispose.call(this,e)},i.prototype.getPass=function(){return this._volumetricLightScatteringRTT},i.prototype._meshExcluded=function(e){return this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)},i.prototype._createPass=function(t,i){var r=this,n=t.getEngine();this._volumetricLightScatteringRTT=new e.RenderTargetTexture("volumetricLightScatteringMap",{width:n.getRenderWidth()*i,height:n.getRenderHeight()*i},t,!1,!0,e.Engine.TEXTURETYPE_UNSIGNED_INT),this._volumetricLightScatteringRTT.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;var o=this.getCamera();o?o.customRenderTargets.push(this._volumetricLightScatteringRTT):t.customRenderTargets.push(this._volumetricLightScatteringRTT);var s,a=function(t){var i=t.getRenderingMesh();if(!r._meshExcluded(i)){var n=t.getMaterial();if(n){var o=i.getScene(),s=o.getEngine();s.setState(n.backFaceCulling);var a=i._getInstancesRenderList(t._id);if(!a.mustReturn){var l=s.getCaps().instancedArrays&&null!==a.visibleInstances[t._id];if(r._isReady(t,l)){var h=r._volumetricLightScatteringPass;if(i===r.mesh&&(h=t.effect?t.effect:n.getEffect()),s.enableEffect(h),i._bind(t,h,e.Material.TriangleFillMode),i===r.mesh)n.bind(i.getWorldMatrix(),i);else{if(r._volumetricLightScatteringPass.setMatrix("viewProjection",o.getTransformMatrix()),n&&n.needAlphaTesting()){var c=n.getAlphaTestTexture();r._volumetricLightScatteringPass.setTexture("diffuseSampler",c),c&&r._volumetricLightScatteringPass.setMatrix("diffuseMatrix",c.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&r._volumetricLightScatteringPass.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}i._processRendering(t,r._volumetricLightScatteringPass,e.Material.TriangleFillMode,a,l,(function(e,t){return h.setMatrix("world",t)}))}}}}},l=new e.Color4(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((function(){s=t.clearColor,t.clearColor=l})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((function(){t.clearColor=s})),this._volumetricLightScatteringRTT.customRenderFunction=function(i,r,n,o){var s,l=t.getEngine();if(o.length){for(l.setColorWrite(!1),s=0;st._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0})),l.setAlphaMode(e.Engine.ALPHA_COMBINE),s=0;s=c&&a.frame<=u&&(n?(h=a.value.clone(),_?(l=h.getTranslation(),h.setTranslation(l.scaleInPlace(g))):v&&o?(l=h.getTranslation(),h.setTranslation(l.multiplyInPlace(o))):h=a.value):h=a.value,y.push({frame:a.frame+r,value:h}));return this.animations[0].createRange(i,c+r,u+r),!0},i.prototype.translate=function(t,r,n){void 0===r&&(r=e.Space.LOCAL);var o=this.getLocalMatrix();if(r==e.Space.LOCAL)o.m[12]+=t.x,o.m[13]+=t.y,o.m[14]+=t.z;else{var s=null;n&&(s=n.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var a=i._tmpMats[0],l=i._tmpVecs[0];this._parent&&(n&&s?(a.copyFrom(this._parent.getAbsoluteTransform()),a.multiplyToRef(s,a)):a.copyFrom(this._parent.getAbsoluteTransform())),a.m[12]=0,a.m[13]=0,a.m[14]=0,a.invert(),e.Vector3.TransformCoordinatesToRef(t,a,l),o.m[12]+=l.x,o.m[13]+=l.y,o.m[14]+=l.z}this._markAsDirtyAndDecompose()},i.prototype.setPosition=function(t,r,n){void 0===r&&(r=e.Space.LOCAL);var o=this.getLocalMatrix();if(r==e.Space.LOCAL)o.m[12]=t.x,o.m[13]=t.y,o.m[14]=t.z;else{var s=null;n&&(s=n.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var a=i._tmpMats[0],l=i._tmpVecs[0];this._parent&&(n&&s?(a.copyFrom(this._parent.getAbsoluteTransform()),a.multiplyToRef(s,a)):a.copyFrom(this._parent.getAbsoluteTransform())),a.invert(),e.Vector3.TransformCoordinatesToRef(t,a,l),o.m[12]=l.x,o.m[13]=l.y,o.m[14]=l.z}this._markAsDirtyAndDecompose()},i.prototype.setAbsolutePosition=function(t,i){this.setPosition(t,e.Space.WORLD,i)},i.prototype.scale=function(t,r,n,o){void 0===o&&(o=!1);var s=this.getLocalMatrix(),a=i._tmpMats[0];e.Matrix.ScalingToRef(t,r,n,a),a.multiplyToRef(s,s),a.invert();for(var l=0,h=this.children;l0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,n.x>n.y&&n.x>n.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length){var o=this._bone1.getScale(),s=this._bone2.getScale();this._bone1Length=this._bone1.length*o.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*s.y*this.mesh.scaling.y}else if(this._bone1.children[0]){t.computeWorldMatrix(!0);var a=this._bone2.children[0].getAbsolutePosition(t),l=this._bone2.getAbsolutePosition(t),h=this._bone1.getAbsolutePosition(t);this._bone1Length=e.Vector3.Distance(a,l),this._bone2Length=e.Vector3.Distance(l,h)}this._bone1.getRotationMatrixToRef(e.Space.WORLD,t,this._bone1Mat),this.maxAngle=Math.PI,r&&(r.targetMesh&&(this.targetMesh=r.targetMesh,this.targetMesh.computeWorldMatrix(!0)),r.poleTargetMesh?(this.poleTargetMesh=r.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):r.poleTargetBone?this.poleTargetBone=r.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),r.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(r.poleTargetLocalOffset),r.poleAngle&&(this.poleAngle=r.poleAngle),r.bendAxis&&this._bendAxis.copyFrom(r.bendAxis),r.maxAngle&&(this.maxAngle=r.maxAngle),r.slerpAmount&&(this.slerpAmount=r.slerpAmount))}}return Object.defineProperty(t.prototype,"maxAngle",{get:function(){return this._maxAngle},set:function(e){this._setMaxAngle(e)},enumerable:!0,configurable:!0}),t.prototype._setMaxAngle=function(e){e<0&&(e=0),(e>Math.PI||void 0==e)&&(e=Math.PI),this._maxAngle=e;var t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))},t.prototype.update=function(){var i=this._bone1;if(i){var r=this.targetPosition,n=this.poleTargetPosition,o=t._tmpMats[0],s=t._tmpMats[1];this.targetMesh&&r.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,n):this.poleTargetMesh&&e.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),n);var a=t._tmpVecs[0],l=t._tmpVecs[1],h=t._tmpVecs[2],c=t._tmpVecs[3],u=t._tmpVecs[4],f=t._tmpQuat;i.getAbsolutePositionToRef(this.mesh,a),n.subtractToRef(a,u),0==u.x&&0==u.y&&0==u.z?u.y=1:u.normalize(),r.subtractToRef(a,c),c.normalize(),e.Vector3.CrossToRef(c,u,l),l.normalize(),e.Vector3.CrossToRef(c,l,h),h.normalize(),e.Matrix.FromXYZAxesToRef(h,c,l,o);var d=this._bone1Length,p=this._bone2Length,m=e.Vector3.Distance(a,r);this._maxReach>0&&(m=Math.min(this._maxReach,m));var _=(p*p+m*m-d*d)/(2*p*m),g=(m*m+d*d-p*p)/(2*m*d);_>1&&(_=1),g>1&&(g=1),_<-1&&(_=-1),g<-1&&(g=-1);var v=Math.acos(_),y=Math.acos(g),b=-v-y;if(this._rightHandedSystem)e.Matrix.RotationYawPitchRollToRef(0,0,this._adjustRoll,s),s.multiplyToRef(o,o),e.Matrix.RotationAxisToRef(this._bendAxis,y,s),s.multiplyToRef(o,o);else{var x=t._tmpVecs[5];x.copyFrom(this._bendAxis),x.x*=-1,e.Matrix.RotationAxisToRef(x,-y,s),s.multiplyToRef(o,o)}this.poleAngle&&(e.Matrix.RotationAxisToRef(c,this.poleAngle,s),o.multiplyToRef(s,o)),this._bone1&&(this.slerpAmount<1?(this._slerping||e.Quaternion.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),e.Quaternion.FromRotationMatrixToRef(o,f),e.Quaternion.SlerpToRef(this._bone1Quat,f,this.slerpAmount,this._bone1Quat),b=this._bone2Ang*(1-this.slerpAmount)+b*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,e.Space.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(o,e.Space.WORLD,this.mesh),this._bone1Mat.copyFrom(o),this._slerping=!1)),this._bone2.setAxisAngle(this._bendAxis,b,e.Space.LOCAL),this._bone2Ang=b}},t._tmpVecs=[e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero()],t._tmpQuat=e.Quaternion.Identity(),t._tmpMats=[e.Matrix.Identity(),e.Matrix.Identity()],t})();e.BoneIKController=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n){if(this.upAxis=e.Vector3.Up(),this.upAxisSpace=e.Space.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=e.Quaternion.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=e.Vector3.Forward(),this.mesh=t,this.bone=i,this.target=r,n&&(n.adjustYaw&&(this.adjustYaw=n.adjustYaw),n.adjustPitch&&(this.adjustPitch=n.adjustPitch),n.adjustRoll&&(this.adjustRoll=n.adjustRoll),null!=n.maxYaw?this.maxYaw=n.maxYaw:this.maxYaw=Math.PI,null!=n.minYaw?this.minYaw=n.minYaw:this.minYaw=-Math.PI,null!=n.maxPitch?this.maxPitch=n.maxPitch:this.maxPitch=Math.PI,null!=n.minPitch?this.minPitch=n.minPitch:this.minPitch=-Math.PI,null!=n.slerpAmount&&(this.slerpAmount=n.slerpAmount),null!=n.upAxis&&(this.upAxis=n.upAxis),null!=n.upAxisSpace&&(this.upAxisSpace=n.upAxisSpace),null!=n.yawAxis||null!=n.pitchAxis)){var o=e.Axis.Y,s=e.Axis.X;null!=n.yawAxis&&(o=n.yawAxis.clone(),o.normalize()),null!=n.pitchAxis&&(s=n.pitchAxis.clone(),s.normalize());var a=e.Vector3.Cross(s,o);this._transformYawPitch=e.Matrix.Identity(),e.Matrix.FromXYZAxesToRef(s,o,a,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}i.getParent()||this.upAxisSpace!=e.Space.BONE||(this.upAxisSpace=e.Space.LOCAL)}return Object.defineProperty(t.prototype,"minYaw",{get:function(){return this._minYaw},set:function(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxYaw",{get:function(){return this._maxYaw},set:function(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minPitch",{get:function(){return this._minPitch},set:function(e){this._minPitch=e,this._minPitchTan=Math.tan(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxPitch",{get:function(){return this._maxPitch},set:function(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)},enumerable:!0,configurable:!0}),t.prototype.update=function(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);var i=this.bone,r=t._tmpVecs[0];i.getAbsolutePositionToRef(this.mesh,r);var n=this.target,o=t._tmpMats[0],s=t._tmpMats[1],a=this.mesh,l=i.getParent(),h=t._tmpVecs[1];h.copyFrom(this.upAxis),this.upAxisSpace==e.Space.BONE&&l?(this._transformYawPitch&&e.Vector3.TransformCoordinatesToRef(h,this._transformYawPitchInv,h),l.getDirectionToRef(h,this.mesh,h)):this.upAxisSpace==e.Space.LOCAL&&(a.getDirectionToRef(h,h),1==a.scaling.x&&1==a.scaling.y&&1==a.scaling.z||h.normalize());var c=!1,u=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(c=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(u=!0),c||u){var f=t._tmpMats[2],d=t._tmpMats[3];if(this.upAxisSpace==e.Space.BONE&&1==h.y&&l)l.getRotationMatrixToRef(e.Space.WORLD,this.mesh,f);else if(this.upAxisSpace!=e.Space.LOCAL||1!=h.y||l){var p=t._tmpVecs[2];p.copyFrom(this._fowardAxis),this._transformYawPitch&&e.Vector3.TransformCoordinatesToRef(p,this._transformYawPitchInv,p),l?l.getDirectionToRef(p,this.mesh,p):a.getDirectionToRef(p,p);var m=e.Vector3.Cross(h,p);m.normalize();var p=e.Vector3.Cross(m,h);e.Matrix.FromXYZAxesToRef(m,h,p,f)}else f.copyFrom(a.getWorldMatrix());f.invertToRef(d);var _=null;if(u){var g=t._tmpVecs[3];n.subtractToRef(r,g),e.Vector3.TransformCoordinatesToRef(g,d,g),_=Math.sqrt(g.x*g.x+g.z*g.z);var v=Math.atan2(g.y,_),y=v;v>this._maxPitch?(g.y=this._maxPitchTan*_,y=this._maxPitch):vthis._maxYaw||bMath.PI?this._isAngleBetween(b,this._maxYaw,this._midYawConstraint)?(g.z=this._maxYawCos*_,g.x=this._maxYawSin*_,x=this._maxYaw):this._isAngleBetween(b,this._midYawConstraint,this._minYaw)&&(g.z=this._minYawCos*_,g.x=this._minYawSin*_,x=this._minYaw):b>this._maxYaw?(g.z=this._maxYawCos*_,g.x=this._maxYawSin*_,x=this._maxYaw):bMath.PI){var T=t._tmpVecs[8];T.copyFrom(e.Axis.Z),this._transformYawPitch&&e.Vector3.TransformCoordinatesToRef(T,this._transformYawPitchInv,T);var E=t._tmpMats[4];this._boneQuat.toRotationMatrix(E),this.mesh.getWorldMatrix().multiplyToRef(E,E),e.Vector3.TransformCoordinatesToRef(T,E,T),e.Vector3.TransformCoordinatesToRef(T,d,T);var P=Math.atan2(T.x,T.z);if(this._getAngleBetween(P,b)>this._getAngleBetween(P,this._midYawConstraint)){null==_&&(_=Math.sqrt(g.x*g.x+g.z*g.z));var A=this._getAngleBetween(P,this._maxYaw);this._getAngleBetween(P,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i},t.prototype._getAngleBetween=function(e,t){e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t;var i=0;return i=eMath.PI&&(i=2*Math.PI-i),i},t.prototype._isAngleBetween=function(e,t,i){if(e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t,i%=2*Math.PI,i=i<0?i+2*Math.PI:i,tt&&ei&&e-1&&this._meshesWithPoseMatrix.splice(t,1)},t.prototype._computeTransformMatrices=function(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(var i=0;i0&&(n.animation=i.animations[0].serialize()),e.ranges=[];for(var o in this._ranges){var s=this._ranges[o];if(s){var a={};a.name=o,a.from=s.from,a.to=s.to,e.ranges.push(a)}}}return e},t.Parse=function(i,r){var n=new t(i.name,i.id,r);i.dimensionsAtRest&&(n.dimensionsAtRest=e.Vector3.FromArray(i.dimensionsAtRest)),n.needInitialSkinMatrix=i.needInitialSkinMatrix;var o;for(o=0;o-1&&(a=n.bones[s.parentBoneIndex]);var l=s.rest?e.Matrix.FromArray(s.rest):null,h=new e.Bone(s.name,n,a,e.Matrix.FromArray(s.matrix),l);s.length&&(h.length=s.length),s.metadata&&(h.metadata=s.metadata),s.animation&&h.animations.push(e.Animation.Parse(s.animation))}if(i.ranges)for(o=0;o0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e},t.prototype.sortBones=function(){for(var e=new Array,t=new Array(this.bones.length),i=0;i1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)},t.Rgbe2float=function(e,t,i,r,n,o){n>0?(n=this.Ldexp(1,n-136),e[o+0]=t*n,e[o+1]=i*n,e[o+2]=r*n):(e[o+0]=0,e[o+1]=0,e[o+2]=0)},t.readStringLine=function(e,t){for(var i="",r="",n=t;n32767)throw"HDR Bad header format, unsupported size";return s+=r.length+1,{height:t,width:i,dataPosition:s}},t.GetCubeMapTextureData=function(t,i){var r=new Uint8Array(t),n=this.RGBE_ReadHeader(r),o=this.RGBE_ReadPixels_RLE(r,n);return e.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(o,n.width,n.height,i)},t.RGBE_ReadPixels=function(e,t){return this.RGBE_ReadPixels_RLE(e,t)},t.RGBE_ReadPixels_RLE=function(e,t){for(var i,r,n,o,s,a=t.height,l=t.width,h=t.dataPosition,c=0,u=0,f=0,d=new ArrayBuffer(4*l),p=new Uint8Array(d),m=new ArrayBuffer(t.width*t.height*4*3),_=new Float32Array(m);a>0;){if(i=e[h++],r=e[h++],n=e[h++],o=e[h++],2!=i||2!=r||128&n)throw"HDR Bad header format, not RLE";if((n<<8|o)!=l)throw"HDR Bad header format, wrong scan line width";for(c=0,f=0;f<4;f++)for(u=(f+1)*l;c128){if(0==(s=i-128)||s>u-c)throw"HDR Bad Format, bad scanline data (run)";for(;s-- >0;)p[c++]=r}else{if(0==(s=i)||s>u-c)throw"HDR Bad Format, bad scanline data (non-run)";if(p[c++]=r,--s>0)for(var g=0;g255){var g=255/_;d*=g,p*=g,m*=g}l[3*f+0]=d,l[3*f+1]=p,l[3*f+2]=m}l?a.push(l):a.push(u)}return a},n=this.getScene();n&&(this._texture=n.getEngine().createRawCubeTextureFromUrl(this.url,n,this._size,e.Engine.TEXTUREFORMAT_RGB,n.getEngine().getCaps().textureFloat?e.Engine.TEXTURETYPE_FLOAT:e.Engine.TEXTURETYPE_UNSIGNED_INT,this._noMipmap,r,null,this._onLoad,this._onError))},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=new i(this.url,e,this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t.coordinatesIndex=this.coordinatesIndex,t.coordinatesMode=this.coordinatesMode,t},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this.loadTexture())},i.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},i.prototype.setReflectionTextureMatrix=function(e){this._textureMatrix=e},i.Parse=function(t,r,n){var o=null;return t.name&&!t.isRenderTarget&&(o=new i(n+t.name,r,t.size,t.noMipmap,t.generateHarmonics,t.useInGammaSpace),o.name=t.name,o.hasAlpha=t.hasAlpha,o.level=t.level,o.coordinatesMode=t.coordinatesMode,o.isBlocking=t.isBlocking),o&&(t.boundingBoxPosition&&(o.boundingBoxPosition=e.Vector3.FromArray(t.boundingBoxPosition)),t.boundingBoxSize&&(o.boundingBoxSize=e.Vector3.FromArray(t.boundingBoxSize)),t.rotationY&&(o.rotationY=t.rotationY)),o},i.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e},i._facesMapping=["right","left","up","down","front","back"],i})(e.BaseTexture);e.HDRCubeTexture=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.ConvertPanoramaToCubemap=function(t,i,r,n){if(!t)throw"ConvertPanoramaToCubemap: input cannot be null";if(t.length!=i*r*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(n,this.FACE_FRONT,t,i,r),back:this.CreateCubemapTexture(n,this.FACE_BACK,t,i,r),left:this.CreateCubemapTexture(n,this.FACE_LEFT,t,i,r),right:this.CreateCubemapTexture(n,this.FACE_RIGHT,t,i,r),up:this.CreateCubemapTexture(n,this.FACE_UP,t,i,r),down:this.CreateCubemapTexture(n,this.FACE_DOWN,t,i,r),size:n,type:e.Engine.TEXTURETYPE_FLOAT,format:e.Engine.TEXTUREFORMAT_RGB,gammaSpace:!1}},t.CreateCubemapTexture=function(e,t,i,r,n){for(var o=new ArrayBuffer(e*e*4*3),s=new Float32Array(o),a=t[1].subtract(t[0]).scale(1/e),l=t[3].subtract(t[2]).scale(1/e),h=1/e,c=0,u=0;uMath.PI;)n-=2*Math.PI;var s=n/Math.PI,a=o/Math.PI;s=.5*s+.5;var l=Math.round(s*i);l<0?l=0:l>=i&&(l=i-1);var h=Math.round(a*r);h<0?h=0:h>=r&&(h=r-1);var c=r-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}},t.FACE_FRONT=[new e.Vector3(-1,-1,-1),new e.Vector3(1,-1,-1),new e.Vector3(-1,1,-1),new e.Vector3(1,1,-1)],t.FACE_BACK=[new e.Vector3(1,-1,1),new e.Vector3(-1,-1,1),new e.Vector3(1,1,1),new e.Vector3(-1,1,1)],t.FACE_RIGHT=[new e.Vector3(1,-1,-1),new e.Vector3(1,-1,1),new e.Vector3(1,1,-1),new e.Vector3(1,1,1)],t.FACE_LEFT=[new e.Vector3(-1,-1,1),new e.Vector3(-1,-1,-1),new e.Vector3(-1,1,1),new e.Vector3(-1,1,-1)],t.FACE_DOWN=[new e.Vector3(-1,1,-1),new e.Vector3(1,1,-1),new e.Vector3(-1,1,1),new e.Vector3(1,1,1)],t.FACE_UP=[new e.Vector3(-1,-1,1),new e.Vector3(1,-1,1),new e.Vector3(-1,-1,-1),new e.Vector3(1,-1,-1)],t})();e.PanoramaToCubeMapTools=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i){var r=e.call(this,t.x,t.y)||this;return r.index=i,r}return o(t,e),t})(e.Vector2),r=(function(){function i(){this.elements=new Array}return i.prototype.add=function(e){var i=this,r=new Array;return e.forEach((function(e){if(0===r.length||!e.equalsWithEpsilon(r[0])){var n=new t(e,i.elements.length);r.push(n),i.elements.push(n)}})),r},i.prototype.computeBounds=function(){var t=new e.Vector2(this.elements[0].x,this.elements[0].y),i=new e.Vector2(this.elements[0].x,this.elements[0].y);return this.elements.forEach((function(e){e.xi.x&&(i.x=e.x),e.yi.y&&(i.y=e.y)})),{min:t,max:i,width:i.x-t.x,height:i.y-t.y}},i})(),n=(function(){function t(){}return t.Rectangle=function(t,i,r,n){return[new e.Vector2(t,i),new e.Vector2(r,i),new e.Vector2(r,n),new e.Vector2(t,n)]},t.Circle=function(t,i,r,n){void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=32);for(var o=new Array,s=0,a=2*Math.PI/n,l=0;l0){var d=a.length/3;this._points.elements.forEach((function(e){s.push(0,-1,0),a.push(e.x,-r,e.y),l.push(1-(e.x-h.min.x)/h.width,1-(e.y-h.min.y)/h.height)}));for(var p=c.length,f=0;fs.elements.length-1?s.elements[0]:s.elements[u+1],t.push(d.x,0,d.y),t.push(d.x,-a,d.y),t.push(f.x,0,f.y),t.push(f.x,-a,f.y);var p=new e.Vector3(d.x,0,d.y),m=new e.Vector3(f.x,0,f.y),_=m.subtract(p),g=new e.Vector3(0,1,0),v=e.Vector3.Cross(_,g);v=v.normalize(),r.push(c/o.width,0),r.push(c/o.width,1),c+=_.length(),r.push(c/o.width,0),r.push(c/o.width,1),l?(i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),n.push(h),n.push(h+2),n.push(h+1),n.push(h+1),n.push(h+2),n.push(h+3)):(i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),n.push(h),n.push(h+1),n.push(h+2),n.push(h+1),n.push(h+3),n.push(h+2)),h+=4}},t})();e.PolygonMeshBuilder=s})(r||(r={}));var r;!(function(e){var t=0,i=(function(){function t(e,t,i){this.pos=e,this.normal=t,this.uv=i}return t.prototype.clone=function(){return new t(this.pos.clone(),this.normal.clone(),this.uv.clone())},t.prototype.flip=function(){this.normal=this.normal.scale(-1)},t.prototype.interpolate=function(i,r){return new t(e.Vector3.Lerp(this.pos,i.pos,r),e.Vector3.Lerp(this.normal,i.normal,r),e.Vector2.Lerp(this.uv,i.uv,r))},t})(),r=(function(){function t(e,t){this.normal=e,this.w=t}return t.FromPoints=function(i,r,n){var o=n.subtract(i),s=r.subtract(i);if(0===o.lengthSquared()||0===s.lengthSquared())return null;var a=e.Vector3.Normalize(e.Vector3.Cross(o,s));return new t(a,e.Vector3.Dot(a,i))},t.prototype.clone=function(){return new t(this.normal.clone(),this.w)},t.prototype.flip=function(){this.normal.scaleInPlace(-1),this.w=-this.w},t.prototype.splitPolygon=function(i,r,o,s,a){var l,h,c=0,u=[];for(l=0;lt.EPSILON?1:0;c|=f,u.push(f)}switch(c){case 0:(e.Vector3.Dot(this.normal,i.plane.normal)>0?r:o).push(i);break;case 1:s.push(i);break;case 2:a.push(i);break;case 3:var d=[],p=[];for(l=0;l=3&&(x=new n(d,i.shared),x.plane&&s.push(x)),p.length>=3&&(x=new n(p,i.shared),x.plane&&a.push(x))}},t.EPSILON=1e-5,t})(),n=(function(){function e(e,t){this.vertices=e,this.shared=t,this.plane=r.FromPoints(e[0].pos,e[1].pos,e[2].pos)}return e.prototype.clone=function(){return new e(this.vertices.map((function(e){return e.clone()})),this.shared)},e.prototype.flip=function(){this.vertices.reverse().map((function(e){e.flip()})),this.plane.flip()},e})(),o=(function(){function e(e){this.plane=null,this.front=null,this.back=null,this.polygons=new Array,e&&this.build(e)}return e.prototype.clone=function(){var t=new e;return t.plane=this.plane&&this.plane.clone(),t.front=this.front&&this.front.clone(),t.back=this.back&&this.back.clone(),t.polygons=this.polygons.map((function(e){return e.clone()})),t},e.prototype.invert=function(){for(var e=0;e0);for(var r=0,n=i;r0)}},t})();e.LensFlareSystemSceneComponent=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){this.name=t,this.lensFlares=new Array,this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=r||e.Engine.LastCreatedScene;var n=this._scene._getComponent(e.SceneComponentConstants.NAME_LENSFLARESYSTEM);n||(n=new e.LensFlareSystemSceneComponent(this._scene),r._addComponent(n)),this._emitter=i,this.id=t,r.lensFlareSystems.push(this),this.meshesSelectionPredicate=function(e){return r.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&0!=(e.layerMask&r.activeCamera.layerMask)};var o=r.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(o,s,e.VertexBuffer.PositionKind,!1,!1,2);var a=[];a.push(0),a.push(1),a.push(2),a.push(0),a.push(2),a.push(3),this._indexBuffer=o.createIndexBuffer(a),this._effect=o.createEffect("lensFlare",[e.VertexBuffer.PositionKind],["color","viewportMatrix"],["textureSampler"],"")}return Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEmitter=function(){return this._emitter},t.prototype.setEmitter=function(e){this._emitter=e},t.prototype.getEmitterPosition=function(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position},t.prototype.computeEffectivePosition=function(t){var i=this.getEmitterPosition();return i=e.Vector3.Project(i,e.Matrix.Identity(),this._scene.getTransformMatrix(),t),this._positionX=i.x,this._positionY=i.y,i=e.Vector3.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(t.x-=this.viewportBorder,t.y-=this.viewportBorder, -t.width+=2*this.viewportBorder,t.height+=2*this.viewportBorder,i.x+=this.viewportBorder,i.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder),i.z>0&&(this._positionX>t.x&&this._positionXt.y&&(this._positionY,t.y,t.height),!0)},t.prototype._isVisible=function(){if(!this._isEnabled||!this._scene.activeCamera)return!1;var t=this.getEmitterPosition(),i=t.subtract(this._scene.activeCamera.globalPosition),r=i.length();i.normalize();var n=new e.Ray(this._scene.activeCamera.globalPosition,i),o=this._scene.pickWithRay(n,this.meshesSelectionPredicate,!0);return!o||!o.hit||o.distance>r},t.prototype.render=function(){if(!this._effect.isReady()||!this._scene.activeCamera)return!1;var t=this._scene.getEngine(),i=this._scene.activeCamera.viewport,r=i.toGlobal(t.getRenderWidth(!0),t.getRenderHeight(!0));if(!this.computeEffectivePosition(r))return!1;if(!this._isVisible())return!1;var n,o;n=this._positionXr.x+r.width-this.borderLimit?this._positionX-r.x-r.width+this.borderLimit:0,o=this._positionYr.y+r.height-this.borderLimit?this._positionY-r.y-r.height+this.borderLimit:0;var s=n>o?n:o;(s-=this.viewportBorder)>this.borderLimit&&(s=this.borderLimit);var a=1-s/this.borderLimit;if(a<0)return!1;a>1&&(a=1),this.viewportBorder>0&&(r.x+=this.viewportBorder,r.y+=this.viewportBorder,r.width-=2*this.viewportBorder,r.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);var l=r.x+r.width/2,h=r.y+r.height/2,c=l-this._positionX,u=h-this._positionY;t.enableEffect(this._effect),t.setState(!1),t.setDepthBuffer(!1),t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect);for(var f=0;f-1?this._onBeforePhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerAfterPhysicsStep=function(e){this._onAfterPhysicsStepCallbacks.push(e)},t.prototype.unregisterAfterPhysicsStep=function(t){var i=this._onAfterPhysicsStepCallbacks.indexOf(t);i>-1?this._onAfterPhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerOnPhysicsCollide=function(e,t){var i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})},t.prototype.unregisterOnPhysicsCollide=function(t,i){var r=t instanceof Array?t:[t],n=-1;this._onPhysicsCollideCallbacks.some((function(e,t){if(e.callback===i&&e.otherImpostors.length===r.length){var o=e.otherImpostors.every((function(e){return r.indexOf(e)>-1}));return o&&(n=t),o}return!1}))?this._onPhysicsCollideCallbacks.splice(n,1):e.Tools.Warn("Function to remove was not found")},t.prototype.getParentsRotation=function(){var t=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);t;)t.rotationQuaternion?this._tmpQuat2.copyFrom(t.rotationQuaternion):e.Quaternion.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,t.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),t=t.parent;return this._tmpQuat},t.prototype.applyForce=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this},t.prototype.applyImpulse=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this},t.prototype.createJoint=function(t,i,r){var n=new e.PhysicsJoint(i,r);return this.addJoint(t,n),this},t.prototype.addJoint=function(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this},t.prototype.sleep=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this},t.prototype.wakeUp=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this},t.prototype.clone=function(e){return e?new t(e,this.type,this._options,this._scene):null},t.prototype.dispose=function(){var e=this;this._physicsEngine&&(this._joints.forEach((function(t){e._physicsEngine&&e._physicsEngine.removeJoint(e,t.otherImpostor,t.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)},t.prototype.setDeltaPosition=function(e){this._deltaPosition.copyFrom(e)},t.prototype.setDeltaRotation=function(t){this._deltaRotation||(this._deltaRotation=new e.Quaternion),this._deltaRotation.copyFrom(t),this._deltaRotationConjugated=this._deltaRotation.conjugate()},t.prototype.getBoxSizeToRef=function(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this},t.prototype.getRadius=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0},t.prototype.syncBoneWithImpostor=function(i,r,n,o,s){var a=t._tmpVecs[0],l=this.object;if(l.rotationQuaternion)if(s){var h=t._tmpQuat;l.rotationQuaternion.multiplyToRef(s,h),i.setRotationQuaternion(h,e.Space.WORLD,r)}else i.setRotationQuaternion(l.rotationQuaternion,e.Space.WORLD,r);a.x=0,a.y=0,a.z=0,n&&(a.x=n.x,a.y=n.y,a.z=n.z,i.getDirectionToRef(a,r,a),void 0!==o&&null!==o||(o=n.length()),a.x*=o,a.y*=o,a.z*=o),i.getParent()?(a.addInPlace(l.getAbsolutePosition()),i.setAbsolutePosition(a,r)):(r.setAbsolutePosition(l.getAbsolutePosition()),r.position.x-=a.x,r.position.y-=a.y,r.position.z-=a.z)},t.prototype.syncImpostorWithBone=function(i,r,n,o,s,a){var l=this.object;if(l.rotationQuaternion)if(s){var h=t._tmpQuat;i.getRotationQuaternionToRef(e.Space.WORLD,r,h),h.multiplyToRef(s,l.rotationQuaternion)}else i.getRotationQuaternionToRef(e.Space.WORLD,r,l.rotationQuaternion);var c=t._tmpVecs[0],u=t._tmpVecs[1];a||(a=t._tmpVecs[2],a.x=0,a.y=1,a.z=0),i.getDirectionToRef(a,r,u),i.getAbsolutePositionToRef(r,c),void 0!==o&&null!==o||!n||(o=n.length()),void 0!==o&&null!==o&&(c.x+=u.x*o,c.y+=u.y*o,c.z+=u.z*o),l.setAbsolutePosition(c)},t.DEFAULT_OBJECT_SIZE=new e.Vector3(1,1,1),t.IDENTITY_QUATERNION=e.Quaternion.Identity(),t._tmpVecs=[e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero()],t._tmpQuat=e.Quaternion.Identity(),t.NoImpostor=0,t.SphereImpostor=1,t.BoxImpostor=2,t.PlaneImpostor=3,t.MeshImpostor=4,t.CylinderImpostor=7,t.ParticleImpostor=8,t.HeightmapImpostor=9,t})();e.PhysicsImpostor=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i){if(void 0===i&&(i=new e.CannonJSPlugin),this._physicsPlugin=i,this._impostors=[],this._joints=[],!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");t=t||new e.Vector3(0,-9.807,0),this.setGravity(t),this.setTimeStep()}return t.prototype.setGravity=function(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)},t.prototype.setTimeStep=function(e){void 0===e&&(e=1/60),this._physicsPlugin.setTimeStep(e)},t.prototype.getTimeStep=function(){return this._physicsPlugin.getTimeStep()},t.prototype.dispose=function(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()},t.prototype.getPhysicsPluginName=function(){return this._physicsPlugin.name},t.prototype.addImpostor=function(e){e.uniqueId=this._impostors.push(e),e.parent||this._physicsPlugin.generatePhysicsBody(e)},t.prototype.removeImpostor=function(e){var t=this._impostors.indexOf(e);if(t>-1){var i=this._impostors.splice(t,1);i.length&&(i[0].physicsBody=null)}},t.prototype.addJoint=function(e,t,i){var r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)},t.prototype.removeJoint=function(e,t,i){var r=this._joints.filter((function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e}));r.length&&this._physicsPlugin.removeJoint(r[0])},t.prototype._step=function(e){var t=this;this._impostors.forEach((function(e){e.isBodyInitRequired()&&t._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)},t.prototype.getPhysicsPlugin=function(){return this._physicsPlugin},t.prototype.getImpostors=function(){return this._impostors},t.prototype.getImpostorForPhysicsObject=function(e){for(var t=0;tr)return null;var d=o===s.Constant?n:n*(1-f/r);return{force:l.multiplyByFloats(d,d,d),contactPoint:u}},t.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._sphere.dispose():setTimeout((function(){t._dataFetched||t._sphere.dispose()}),0)},t.prototype._prepareSphere=function(){this._sphere||(this._sphere=e.MeshBuilder.CreateSphere("radialExplosionEventSphere",this._sphereOptions,this._scene),this._sphere.isVisible=!1)},t.prototype._intersectsWithSphere=function(t,i,r){var n=t.object;return this._prepareSphere(),this._sphere.position=i,this._sphere.scaling=new e.Vector3(2*r,2*r,2*r),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(n,!0)},t})();e.PhysicsRadialExplosionEvent=i;var r=(function(){function e(e,t,i,r,n,o){void 0===o&&(o=s.Constant),this._dataFetched=!1,this._physicsHelper=e,this._scene=t,this._origin=i,this._radius=r,this._strength=n,this._falloff=o,this._tickCallback=this._tick.bind(this)}return e.prototype.getData=function(){return this._dataFetched=!0,{sphere:this._sphere}},e.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},e.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._sphere.dispose():setTimeout((function(){t._dataFetched||t._sphere.dispose()}),0)},e.prototype._tick=function(){if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._radius,-1*this._strength,this._falloff);else{var e=this._physicsHelper.applyRadialExplosionForce(this._origin,this._radius,-1*this._strength,this._falloff);e&&(this._sphere=e.getData().sphere.clone("radialExplosionEventSphereClone"))}},e})();e.PhysicsGravitationalFieldEvent=r;var n=(function(){function t(t,i,r,n,o,s){this._scene=t,this._origin=i,this._radius=r,this._strength=n,this._height=o,this._updraftMode=s,this._originTop=e.Vector3.Zero(),this._originDirection=e.Vector3.Zero(),this._cylinderPosition=e.Vector3.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._origin.addToRef(new e.Vector3(0,this._height/2,0),this._cylinderPosition),this._origin.addToRef(new e.Vector3(0,this._height,0),this._originTop),this._updraftMode===a.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=this._tick.bind(this)}return t.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},t.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},t.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},t.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._cylinder.dispose():setTimeout((function(){t._dataFetched||t._cylinder.dispose()}),0)},t.prototype.getImpostorForceAndContactPoint=function(e){if(0===e.mass)return null;if(!this._intersectsWithCylinder(e))return null;var t=e.getObjectCenter();if(this._updraftMode===a.Perpendicular)var i=this._originDirection;else var i=t.subtract(this._originTop);var r=-1*this._strength;return{force:i.multiplyByFloats(r,r,r),contactPoint:t}},t.prototype._tick=function(){var e=this;this._physicsEngine.getImpostors().forEach((function(t){var i=e.getImpostorForceAndContactPoint(t);i&&t.applyForce(i.force,i.contactPoint)}))},t.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=e.MeshBuilder.CreateCylinder("updraftEventCylinder",{height:this._height,diameter:2*this._radius},this._scene),this._cylinder.isVisible=!1)},t.prototype._intersectsWithCylinder=function(e){var t=e.object;return this._prepareCylinder(),this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(t,!0)},t})();e.PhysicsUpdraftEvent=n;var o=(function(){function t(t,i,r,n,o){this._scene=t,this._origin=i,this._radius=r,this._strength=n,this._height=o,this._originTop=e.Vector3.Zero(),this._centripetalForceThreshold=.7,this._updraftMultiplier=.02,this._cylinderPosition=e.Vector3.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._origin.addToRef(new e.Vector3(0,this._height/2,0),this._cylinderPosition),this._origin.addToRef(new e.Vector3(0,this._height,0),this._originTop),this._tickCallback=this._tick.bind(this)}return t.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},t.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},t.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},t.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._cylinder.dispose():setTimeout((function(){t._dataFetched||t._cylinder.dispose()}),0)},t.prototype.getImpostorForceAndContactPoint=function(t){if(0===t.mass)return null;if(!this._intersectsWithCylinder(t))return null;if("Mesh"!==t.object.getClassName()&&"InstancedMesh"!==t.object.getClassName())return null;var i=t.getObjectCenter(),r=new e.Vector3(this._origin.x,i.y,this._origin.z),n=i.subtract(r),o=new e.Ray(r,n,this._radius),s=o.intersectsMesh(t.object),a=s.pickedPoint;if(!a)return null;var l=s.distance/this._radius,h=e.Vector3.Cross(r,i).normalize(),c=a.normalize();if(l>this._centripetalForceThreshold&&(c=c.negate()),l>this._centripetalForceThreshold)var u=c.x*this._strength/8,f=c.y*this._updraftMultiplier,d=c.z*this._strength/8;else var u=(h.x+c.x)/2,f=this._originTop.y*this._updraftMultiplier,d=(h.z+c.z)/2;var p=new e.Vector3(u,f,d);return p=p.multiplyByFloats(this._strength,this._strength,this._strength),{force:p,contactPoint:i}},t.prototype._tick=function(){var e=this;this._physicsEngine.getImpostors().forEach((function(t){var i=e.getImpostorForceAndContactPoint(t);i&&t.applyForce(i.force,i.contactPoint)}))},t.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=e.MeshBuilder.CreateCylinder("vortexEventCylinder",{height:this._height,diameter:2*this._radius},this._scene),this._cylinder.isVisible=!1)},t.prototype._intersectsWithCylinder=function(e){var t=e.object;return this._prepareCylinder(),this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(t,!0)},t})();e.PhysicsVortexEvent=o;var s;!(function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"})(s=e.PhysicsRadialImpulseFalloff||(e.PhysicsRadialImpulseFalloff={}));var a;!(function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"})(a=e.PhysicsUpdraftMode||(e.PhysicsUpdraftMode={}))})(r||(r={}));var r;!(function(t){var i=(function(){function i(i,r){if(void 0===i&&(i=!0),void 0===r&&(r=10),this._useDeltaForWorldStep=i,this.name="CannonJSPlugin",this._physicsMaterials=new Array,this._fixedTimeStep=1/60,this.BJSCANNON=e,this._minus90X=new t.Quaternion(-.7071067811865475,0,0,.7071067811865475),this._plus90X=new t.Quaternion(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=t.Vector3.Zero(),this._tmpDeltaPosition=t.Vector3.Zero(),this._tmpUnityRotation=new t.Quaternion,!this.isSupported())return void t.Tools.Error("CannonJS is not available. Please make sure you included the js file.");this._extendNamespace(),this.world=new this.BJSCANNON.World,this.world.broadphase=new this.BJSCANNON.NaiveBroadphase,this.world.solver.iterations=r}return i.prototype.setGravity=function(e){this.world.gravity.copy(e)},i.prototype.setTimeStep=function(e){this._fixedTimeStep=e},i.prototype.getTimeStep=function(){return this._fixedTimeStep},i.prototype.executeStep=function(e,t){this.world.step(this._fixedTimeStep,this._useDeltaForWorldStep?e:0,3)},i.prototype.applyImpulse=function(e,t,i){var r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),n=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(n,r)},i.prototype.applyForce=function(e,t,i){var r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),n=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(n,r)},i.prototype.generatePhysicsBody=function(e){if(e.parent)return void(e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate()));if(e.isBodyInitRequired()){var t=this._createShape(e),i=e.physicsBody;i&&this.removePhysicsBody(e);var r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),n={mass:e.getParam("mass"),material:r},o=e.getParam("nativeOptions");for(var s in o)o.hasOwnProperty(s)&&(n[s]=o[s]);e.physicsBody=new this.BJSCANNON.Body(n),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){e.physicsBody[t].copy(i[t])})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)},i.prototype._processChildMeshes=function(e){var i=this,r=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],n=e.object.rotationQuaternion;if(r.length){var o=function(r,s){if(n&&s.rotationQuaternion){var a=s.getPhysicsImpostor();if(a){if(a.parent!==e){var l=s.getAbsolutePosition().subtract(e.object.getAbsolutePosition()),h=s.rotationQuaternion.multiply(t.Quaternion.Inverse(n));a.physicsBody&&(i.removePhysicsBody(a),a.physicsBody=null),a.parent=e,a.resetUpdateFlags(),e.physicsBody.addShape(i._createShape(a),new i.BJSCANNON.Vec3(l.x,l.y,l.z),new i.BJSCANNON.Quaternion(h.x,h.y,h.z,h.w)),e.physicsBody.mass+=a.getParam("mass")}}n.multiplyInPlace(s.rotationQuaternion),s.getChildMeshes(!0).filter((function(e){return!!e.physicsImpostor})).forEach(o.bind(i,s.getAbsolutePosition()))}};r.filter((function(e){return!!e.physicsImpostor})).forEach(o.bind(this,e.object.getAbsolutePosition()))}},i.prototype.removePhysicsBody=function(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),this.world.remove(e.physicsBody)},i.prototype.generateJoint=function(e){var i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(i&&r){var n,o=e.joint.jointData,s={pivotA:o.mainPivot?(new this.BJSCANNON.Vec3).copy(o.mainPivot):null, -pivotB:o.connectedPivot?(new this.BJSCANNON.Vec3).copy(o.connectedPivot):null,axisA:o.mainAxis?(new this.BJSCANNON.Vec3).copy(o.mainAxis):null,axisB:o.connectedAxis?(new this.BJSCANNON.Vec3).copy(o.connectedAxis):null,maxForce:o.nativeParams.maxForce,collideConnected:!!o.collision};switch(e.joint.type){case t.PhysicsJoint.HingeJoint:case t.PhysicsJoint.Hinge2Joint:n=new this.BJSCANNON.HingeConstraint(i,r,s);break;case t.PhysicsJoint.DistanceJoint:n=new this.BJSCANNON.DistanceConstraint(i,r,o.maxDistance||2);break;case t.PhysicsJoint.SpringJoint:var a=o;n=new this.BJSCANNON.Spring(i,r,{restLength:a.length,stiffness:a.stiffness,damping:a.damping,localAnchorA:s.pivotA,localAnchorB:s.pivotB});break;case t.PhysicsJoint.LockJoint:n=new this.BJSCANNON.LockConstraint(i,r,s);break;case t.PhysicsJoint.PointToPointJoint:case t.PhysicsJoint.BallAndSocketJoint:default:n=new this.BJSCANNON.PointToPointConstraint(i,s.pivotA,r,s.pivotA,s.maxForce)}n.collideConnected=!!o.collision,e.joint.physicsJoint=n,e.joint.type!==t.PhysicsJoint.SpringJoint?this.world.addConstraint(n):e.mainImpostor.registerAfterPhysicsStep((function(){n.applyForce()}))}},i.prototype.removeJoint=function(e){this.world.removeConstraint(e.joint.physicsJoint)},i.prototype._addMaterial=function(e,t,i){var r,n;for(r=0;r1e3*i));a++);this.time+=r;for(var l=this.time%i,h=l/i,c=e,u=this.bodies,f=0;f!==u.length;f++){var d=u[f];d.type!==t.Body.STATIC&&d.sleepState!==t.Body.SLEEPING?(d.position.vsub(d.previousPosition,c),c.scale(h,c),d.position.vadd(c,d.interpolatedPosition)):(d.interpolatedPosition.copy(d.position),d.interpolatedQuaternion.copy(d.quaternion))}}}},i})();t.CannonJSPlugin=i})(r||(r={}));var r;!(function(e){var i=(function(){function i(i){this.name="OimoJSPlugin",this._tmpImpostorsArray=[],this._tmpPositionVector=e.Vector3.Zero(),this.BJSOIMO=t,this.world=new this.BJSOIMO.World({iterations:i}),this.world.clear()}return i.prototype.setGravity=function(e){this.world.gravity.copy(e)},i.prototype.setTimeStep=function(e){this.world.timeStep=e},i.prototype.getTimeStep=function(){return this.world.timeStep},i.prototype.executeStep=function(e,t){var i=this;t.forEach((function(e){e.beforeStep()})),this.world.step(),t.forEach((function(e){e.afterStep(),i._tmpImpostorsArray[e.uniqueId]=e}));for(var r=this.world.contacts;null!==r;)if(!r.touching||r.body1.sleeping||r.body2.sleeping){var n=this._tmpImpostorsArray[+r.body1.name],o=this._tmpImpostorsArray[+r.body2.name];n&&o?(n.onCollide({body:o.physicsBody}),o.onCollide({body:n.physicsBody}),r=r.next):r=r.next}else r=r.next},i.prototype.applyImpulse=function(e,t,i){var r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))},i.prototype.applyForce=function(t,i,r){e.Tools.Warn("Oimo doesn't support applying force. Using impule instead."),this.applyImpulse(t,i,r)},i.prototype.generatePhysicsBody=function(t){var i=this;if(t.parent)return void(t.physicsBody&&(this.removePhysicsBody(t),t.forceUpdate()));if(t.isBodyInitRequired()){var r={name:t.uniqueId,config:[t.getParam("mass")||1,t.getParam("friction"),t.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==t.getParam("mass"),density:t.getParam("mass"),friction:t.getParam("friction"),restitution:t.getParam("restitution"),world:this.world},n=[t];!(function(e){e.getChildMeshes&&e.getChildMeshes().forEach((function(e){e.physicsImpostor&&n.push(e.physicsImpostor)}))})(t.object);var o=function(t){return Math.max(t,e.PhysicsEngine.Epsilon)},s=new e.Quaternion;n.forEach((function(n){if(n.object.rotationQuaternion){var a=n.object.rotationQuaternion;s=a.clone();var l=a.toEulerAngles(),h=n.getObjectExtendSize();if(n===t){var c=t.getObjectCenter();t.object.getAbsolutePivotPoint().subtractToRef(c,i._tmpPositionVector),i._tmpPositionVector.divideInPlace(t.object.scaling),r.pos.push(c.x),r.pos.push(c.y),r.pos.push(c.z),r.posShape.push(0,0,0),r.rot.push(0),r.rot.push(0),r.rot.push(0),r.rotShape.push(0,0,0)}else{var u=n.object.getAbsolutePosition().subtract(t.object.getAbsolutePosition());r.posShape.push(u.x),r.posShape.push(u.y),r.posShape.push(u.z),r.pos.push(0,0,0),r.rot.push(0),r.rot.push(0),r.rot.push(0),r.rotShape.push(57.29577951308232*l.x),r.rotShape.push(57.29577951308232*l.y),r.rotShape.push(57.29577951308232*l.z)}switch(n.type){case e.PhysicsImpostor.ParticleImpostor:e.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case e.PhysicsImpostor.SphereImpostor:var f=h.x,d=h.y,p=h.z,m=Math.max(o(f),o(d),o(p))/2;r.type.push("sphere"),r.size.push(m),r.size.push(m),r.size.push(m);break;case e.PhysicsImpostor.CylinderImpostor:var _=o(h.x)/2,g=o(h.y);r.type.push("cylinder"),r.size.push(_),r.size.push(g),r.size.push(g);break;case e.PhysicsImpostor.PlaneImpostor:case e.PhysicsImpostor.BoxImpostor:default:var _=o(h.x),g=o(h.y),v=o(h.z);r.type.push("box"),r.size.push(_),r.size.push(g),r.size.push(v)}n.object.rotationQuaternion=a}})),t.physicsBody=this.world.add(r),t.physicsBody.resetQuaternion(s),t.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);t.setDeltaPosition(this._tmpPositionVector)},i.prototype.removePhysicsBody=function(e){this.world.removeRigidBody(e.physicsBody)},i.prototype.generateJoint=function(t){var i=t.mainImpostor.physicsBody,r=t.connectedImpostor.physicsBody;if(i&&r){var n,o=t.joint.jointData,s=o.nativeParams||{},a={body1:i,body2:r,axe1:s.axe1||(o.mainAxis?o.mainAxis.asArray():null),axe2:s.axe2||(o.connectedAxis?o.connectedAxis.asArray():null),pos1:s.pos1||(o.mainPivot?o.mainPivot.asArray():null),pos2:s.pos2||(o.connectedPivot?o.connectedPivot.asArray():null),min:s.min,max:s.max,collision:s.collision||o.collision,spring:s.spring,world:this.world};switch(t.joint.type){case e.PhysicsJoint.BallAndSocketJoint:n="jointBall";break;case e.PhysicsJoint.SpringJoint:e.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");var l=o;a.min=l.length||a.min,a.max=Math.max(a.min,a.max);case e.PhysicsJoint.DistanceJoint:n="jointDistance",a.max=o.maxDistance;break;case e.PhysicsJoint.PrismaticJoint:n="jointPrisme";break;case e.PhysicsJoint.SliderJoint:n="jointSlide";break;case e.PhysicsJoint.WheelJoint:n="jointWheel";break;case e.PhysicsJoint.HingeJoint:default:n="jointHinge"}a.type=n,t.joint.physicsJoint=this.world.add(a)}},i.prototype.removeJoint=function(t){try{this.world.removeJoint(t.joint.physicsJoint)}catch(t){e.Tools.Warn(t)}},i.prototype.isSupported=function(){return void 0!==this.BJSOIMO},i.prototype.setTransformationFromPhysicsBody=function(e){e.physicsBody.sleeping||(e.object.position.copyFrom(e.physicsBody.getPosition()),e.object.rotationQuaternion&&e.object.rotationQuaternion.copyFrom(e.physicsBody.getQuaternion()))},i.prototype.setPhysicsBodyTransformation=function(e,t,i){var r=e.physicsBody;r.position.copy(t),r.orientation.copy(i),r.syncShapes(),r.awake()},i.prototype.setLinearVelocity=function(e,t){e.physicsBody.linearVelocity.copy(t)},i.prototype.setAngularVelocity=function(e,t){e.physicsBody.angularVelocity.copy(t)},i.prototype.getLinearVelocity=function(t){var i=t.physicsBody.linearVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},i.prototype.getAngularVelocity=function(t){var i=t.physicsBody.angularVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},i.prototype.setBodyMass=function(e,t){var i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)},i.prototype.getBodyMass=function(e){return e.physicsBody.shapes.density},i.prototype.getBodyFriction=function(e){return e.physicsBody.shapes.friction},i.prototype.setBodyFriction=function(e,t){e.physicsBody.shapes.friction=t},i.prototype.getBodyRestitution=function(e){return e.physicsBody.shapes.restitution},i.prototype.setBodyRestitution=function(e,t){e.physicsBody.shapes.restitution=t},i.prototype.sleepBody=function(e){e.physicsBody.sleep()},i.prototype.wakeUpBody=function(e){e.physicsBody.awake()},i.prototype.updateDistanceJoint=function(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)},i.prototype.setMotor=function(e,t,i,r){var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setMotor(t,i)},i.prototype.setLimit=function(e,t,i,r){var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setLimit(t,void 0===i?-t:i)},i.prototype.syncMeshWithImpostor=function(e,t){var i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.s)},i.prototype.getRadius=function(e){return e.physicsBody.shapes.radius},i.prototype.getBoxSizeToRef=function(e,t){var i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth},i.prototype.dispose=function(){this.world.clear()},i})();e.OimoJSPlugin=i})(r||(r={}));var r;!(function(e){function t(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}function i(e){return String.fromCharCode(255&e,e>>8&255,e>>16&255,e>>24&255)}var r=t("DXT1"),n=t("DXT3"),o=t("DXT5"),s=t("DX10"),a=(function(){function t(){}return t.GetDDSInfo=function(t){var i=new Int32Array(t,0,31),a=new Int32Array(t,0,35),l=1;131072&i[2]&&(l=Math.max(1,i[7]));var h=i[21],c=h===s?a[32]:0,u=e.Engine.TEXTURETYPE_UNSIGNED_INT;switch(h){case 113:u=e.Engine.TEXTURETYPE_HALF_FLOAT;break;case 116:u=e.Engine.TEXTURETYPE_FLOAT;break;case s:if(10===c){u=e.Engine.TEXTURETYPE_HALF_FLOAT;break}}return{width:i[4],height:i[3],mipmapCount:l,isFourCC:4==(4&i[20]),isRGB:64==(64&i[20]),isLuminance:131072==(131072&i[20]),isCube:512==(512&i[28]),isCompressed:h===r||h===n||h===o,dxgiFormat:c,textureType:u}},t._ToHalfFloat=function(e){t._FloatView||(t._FloatView=new Float32Array(1),t._Int32View=new Int32Array(t._FloatView.buffer)),t._FloatView[0]=e;var i=t._Int32View[0],r=i>>16&32768,n=i>>12&2047,o=i>>23&255;return o<103?r:o>142?(r|=31744,r|=(255==o?0:1)&&8388607&i):o<113?(n|=2048,r|=(n>>114-o)+(n>>113-o&1)):(r|=o-112<<10|n>>1,r+=1&n)},t._FromHalfFloat=function(e){var t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(r/Math.pow(2,10)):31==i?r?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+r/Math.pow(2,10))},t._GetHalfFloatAsFloatRGBAArrayBuffer=function(e,i,r,n,o,s){for(var a=new Float32Array(n),l=new Uint16Array(o,r),h=0,c=0;c>8)},t._GetRGBArrayBuffer=function(e,t,i,r,n,o,s,a){for(var l=new Uint8Array(r),h=new Uint8Array(n,i),c=0,u=0;u0?c.sphericalPolynomial=e.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({size:P[4],right:m[0],left:m[1],up:m[2],down:m[3],front:m[4],back:m[5],format:e.Engine.TEXTUREFORMAT_RGBA,type:e.Engine.TEXTURETYPE_FLOAT,gammaSpace:!1}):c.sphericalPolynomial=void 0},t.StoreLODInAlphaChannel=!1,t})();e.DDSTools=a})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.supportCascades=!0}return t.prototype.canLoad=function(e,t,i,r,n){return 0===e.indexOf(".dds")},t.prototype.transformUrl=function(e,t){return e},t.prototype.getFallbackTextureUrl=function(e,t){return null},t.prototype.loadCubeData=function(t,i,r,n,o){var s,a=i.getEngine(),l=!1;if(Array.isArray(t))for(var h=0;h1)&&i.generateMipMaps,a._unpackFlipY(s.isCompressed),e.DDSTools.UploadDDSLevels(a,i,c,s,l,6,-1,h),s.isFourCC||1!==s.mipmapCount||a.generateMipMapsForCubemap(i)}else{var u=t;s=e.DDSTools.GetDDSInfo(u),i.width=s.width,i.height=s.height,r&&(s.sphericalPolynomial=new e.SphericalPolynomial),l=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&i.generateMipMaps,a._unpackFlipY(s.isCompressed),e.DDSTools.UploadDDSLevels(a,i,u,s,l,6),s.isFourCC||1!==s.mipmapCount||a.generateMipMapsForCubemap(i)}a._setCubeMapTextureParams(l),i.isReady=!0,n&&n({isDDS:!0,width:i.width,info:s,data:t,texture:i})},t.prototype.loadData=function(t,i,r){var n=e.DDSTools.GetDDSInfo(t),o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&i.generateMipMaps&&n.width>>n.mipmapCount-1==1;r(n.width,n.height,!o,n.isFourCC,(function(){e.DDSTools.UploadDDSLevels(i.getEngine(),i,t,n,o,1)}))},t})();e.Engine._TextureLoaders.push(new t)})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.GetTGAHeader=function(e){var t=0;return{id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]}},t.UploadContent=function(i,r){if(r.length<19)return void e.Tools.Error("Unable to load TGA file - Not enough data to contain header");var n=18,o=t.GetTGAHeader(r);if(o.id_length+n>r.length)return void e.Tools.Error("Unable to load TGA file - Not enough data");n+=o.id_length;var s=!1,a=!1,l=!1;switch(o.image_type){case t._TYPE_RLE_INDEXED:s=!0;case t._TYPE_INDEXED:a=!0;break;case t._TYPE_RLE_RGB:s=!0;case t._TYPE_RGB:break;case t._TYPE_RLE_GREY:s=!0;case t._TYPE_GREY:l=!0}var h,c,u=o.pixel_size>>3,f=o.width*o.height*u;if(a&&(c=r.subarray(n,n+=o.colormap_length*(o.colormap_size>>3))),s){h=new Uint8Array(f);for(var d,p,m,_=0,g=new Uint8Array(u);n>t._ORIGIN_SHIFT){default:case t._ORIGIN_UL:v=0,b=1,E=o.width,y=0,x=1,T=o.height;break;case t._ORIGIN_BL:v=0,b=1,E=o.width,y=o.height-1,x=-1,T=-1;break;case t._ORIGIN_UR:v=o.width-1,b=-1,E=-1,y=0,x=1,T=o.height;break;case t._ORIGIN_BR:v=o.width-1,b=-1,E=-1,y=o.height-1,x=-1,T=-1}var P="_getImageData"+(l?"Grey":"")+o.pixel_size+"bits",A=t[P](o,c,h,y,x,T,v,b,E);i.getEngine()._uploadDataToTextureDirectly(i,A)},t._getImageData8bits=function(e,t,i,r,n,o,s,a,l){var h,c,u,f=i,d=t,p=e.width,m=e.height,_=0,g=new Uint8Array(p*m*4);for(u=r;u!==o;u+=n)for(c=s;c!==l;c+=a,_++)h=f[_],g[4*(c+p*u)+3]=255,g[4*(c+p*u)+2]=d[3*h+0],g[4*(c+p*u)+1]=d[3*h+1],g[4*(c+p*u)+0]=d[3*h+2];return g},t._getImageData16bits=function(e,t,i,r,n,o,s,a,l){var h,c,u,f=i,d=e.width,p=e.height,m=0,_=new Uint8Array(d*p*4);for(u=r;u!==o;u+=n)for(c=s;c!==l;c+=a,m+=2){h=f[m+0]+(f[m+1]<<8);var g=255*((31744&h)>>10)/31|0,v=255*((992&h)>>5)/31|0,y=255*(31&h)/31|0;_[4*(c+d*u)+0]=g,_[4*(c+d*u)+1]=v,_[4*(c+d*u)+2]=y,_[4*(c+d*u)+3]=32768&h?0:255}return _},t._getImageData24bits=function(e,t,i,r,n,o,s,a,l){var h,c,u=i,f=e.width,d=e.height,p=0,m=new Uint8Array(f*d*4);for(c=r;c!==o;c+=n)for(h=s;h!==l;h+=a,p+=3)m[4*(h+f*c)+3]=255,m[4*(h+f*c)+2]=u[p+0],m[4*(h+f*c)+1]=u[p+1],m[4*(h+f*c)+0]=u[p+2];return m},t._getImageData32bits=function(e,t,i,r,n,o,s,a,l){var h,c,u=i,f=e.width,d=e.height,p=0,m=new Uint8Array(f*d*4);for(c=r;c!==o;c+=n)for(h=s;h!==l;h+=a,p+=4)m[4*(h+f*c)+2]=u[p+0],m[4*(h+f*c)+1]=u[p+1],m[4*(h+f*c)+0]=u[p+2],m[4*(h+f*c)+3]=u[p+3];return m},t._getImageDataGrey8bits=function(e,t,i,r,n,o,s,a,l){var h,c,u,f=i,d=e.width,p=e.height,m=0,_=new Uint8Array(d*p*4);for(u=r;u!==o;u+=n)for(c=s;c!==l;c+=a,m++)h=f[m],_[4*(c+d*u)+0]=h,_[4*(c+d*u)+1]=h,_[4*(c+d*u)+2]=h,_[4*(c+d*u)+3]=255;return _},t._getImageDataGrey16bits=function(e,t,i,r,n,o,s,a,l){var h,c,u=i,f=e.width,d=e.height,p=0,m=new Uint8Array(f*d*4);for(c=r;c!==o;c+=n)for(h=s;h!==l;h+=a,p+=2)m[4*(h+f*c)+0]=u[p+0],m[4*(h+f*c)+1]=u[p+0],m[4*(h+f*c)+2]=u[p+0],m[4*(h+f*c)+3]=u[p+1];return m},t._TYPE_INDEXED=1,t._TYPE_RGB=2,t._TYPE_GREY=3,t._TYPE_RLE_INDEXED=9,t._TYPE_RLE_RGB=10,t._TYPE_RLE_GREY=11,t._ORIGIN_MASK=48,t._ORIGIN_SHIFT=4,t._ORIGIN_BL=0,t._ORIGIN_BR=1,t._ORIGIN_UL=2,t._ORIGIN_UR=3,t})();e.TGATools=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.supportCascades=!1}return t.prototype.canLoad=function(e,t,i,r,n){return 0===e.indexOf(".tga")},t.prototype.transformUrl=function(e,t){return e},t.prototype.getFallbackTextureUrl=function(e,t){return null},t.prototype.loadCubeData=function(e,t,i,r,n){throw".env not supported in Cube."},t.prototype.loadData=function(t,i,r){var n=new Uint8Array(t),o=e.TGATools.GetTGAHeader(n);r(o.width,o.height,i.generateMipMaps,!1,(function(){e.TGATools.UploadContent(i,n)}))},t})();e.Engine._TextureLoaders.push(new t)})(r||(r={}));var r;!(function(e){var t=(function(){function t(i,r,n,o){this.arrayBuffer=i;var s=new Uint8Array(this.arrayBuffer,0,12);if(171!==s[0]||75!==s[1]||84!==s[2]||88!==s[3]||32!==s[4]||49!==s[5]||49!==s[6]||187!==s[7]||13!==s[8]||10!==s[9]||26!==s[10]||10!==s[11])return void e.Tools.Error("texture missing KTX identifier");var a=new Int32Array(this.arrayBuffer,12,13),l=16909060===a[0];return this.glType=l?this.switchEndainness(a[1]):a[1],this.glTypeSize=l?this.switchEndainness(a[2]):a[2],this.glFormat=l?this.switchEndainness(a[3]):a[3],this.glInternalFormat=l?this.switchEndainness(a[4]):a[4],this.glBaseInternalFormat=l?this.switchEndainness(a[5]):a[5],this.pixelWidth=l?this.switchEndainness(a[6]):a[6],this.pixelHeight=l?this.switchEndainness(a[7]):a[7],this.pixelDepth=l?this.switchEndainness(a[8]):a[8],this.numberOfArrayElements=l?this.switchEndainness(a[9]):a[9],this.numberOfFaces=l?this.switchEndainness(a[10]):a[10],this.numberOfMipmapLevels=l?this.switchEndainness(a[11]):a[11],this.bytesOfKeyValueData=l?this.switchEndainness(a[12]):a[12],0!==this.glType?void e.Tools.Error("only compressed formats currently supported"):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?void e.Tools.Error("only 2D textures currently supported"):0!==this.numberOfArrayElements?void e.Tools.Error("texture arrays not currently supported"):this.numberOfFaces!==r?void e.Tools.Error("number of faces expected"+r+", but found "+this.numberOfFaces):void(this.loadType=t.COMPRESSED_2D))}return t.prototype.switchEndainness=function(e){return(255&e)<<24|(65280&e)<<8|e>>8&65280|e>>24&255},t.prototype.uploadLevels=function(e,i){switch(this.loadType){case t.COMPRESSED_2D:this._upload2DCompressedLevels(e,i);break;case t.TEX_2D:case t.COMPRESSED_3D:case t.TEX_3D:}},t.prototype._upload2DCompressedLevels=function(e,i){for(var r=t.HEADER_LEN+this.bytesOfKeyValueData,n=this.pixelWidth,o=this.pixelHeight,s=i?this.numberOfMipmapLevels:1,a=0;a-1?e.substring(0,i):e)+t}, -t.prototype.getFallbackTextureUrl=function(e,t){var i=new RegExp(t+"$");return e.replace(i,"")},t.prototype.loadCubeData=function(t,i,r,n,o){if(!Array.isArray(t)){var s=i.getEngine(),a=new e.KhronosTextureContainer(t,6),l=a.numberOfMipmapLevels>1&&i.generateMipMaps;s._unpackFlipY(!0),a.uploadLevels(i,i.generateMipMaps),i.width=a.pixelWidth,i.height=a.pixelHeight,s._setCubeMapTextureParams(l),i.isReady=!0}},t.prototype.loadData=function(t,i,r){var n=new e.KhronosTextureContainer(t,1);r(n.pixelWidth,n.pixelHeight,!1,!0,(function(){n.uploadLevels(i,i.generateMipMaps)}))},t})();e.Engine._TextureLoaders.unshift(new t)})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.GetEnvInfo=function(i){for(var r=new DataView(i),n=0,o=0;o0)):!i._pointerCaptures[l.pointerId]&&s.distance>a.distance&&(i.mainSceneTrackerPredicate&&i.mainSceneTrackerPredicate(a.pickedMesh)?(i._notifyObservers(r,a,l),r.skipOnPointerObservable=!0):i._lastPointerEvents[l.pointerId]&&(i.onPointerOutObservable.notifyObservers(l.pointerId),delete i._lastPointerEvents[l.pointerId])),r.type===e.PointerEventTypes.POINTERUP&&i._pointerCaptures[l.pointerId]&&(i._pointerCaptures[l.pointerId]=!1))}}})),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderObservable.add((function(){i.shouldRender&&i.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((function(){i.dispose()})),this._updateCamera()}return Object.defineProperty(t,"DefaultUtilityLayer",{get:function(){return null==t._DefaultUtilityLayer&&(t._DefaultUtilityLayer=new t(e.Engine.LastCreatedScene),t._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((function(){t._DefaultUtilityLayer=null}))),t._DefaultUtilityLayer},enumerable:!0,configurable:!0}),Object.defineProperty(t,"DefaultKeepDepthUtilityLayer",{get:function(){return null==t._DefaultKeepDepthUtilityLayer&&(t._DefaultKeepDepthUtilityLayer=new t(e.Engine.LastCreatedScene),t._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,t._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((function(){t._DefaultKeepDepthUtilityLayer=null}))),t._DefaultKeepDepthUtilityLayer},enumerable:!0,configurable:!0}),t.prototype._notifyObservers=function(t,i,r){t.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new e.PointerInfo(t.type,t.event,i)),this._lastPointerEvents[r.pointerId]=r.pointerType)},t.prototype.render=function(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){var e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}},t.prototype.dispose=function(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()},t.prototype._updateCamera=function(){this.utilityLayerScene.activeCamera=this.originalScene.activeCamera},t._DefaultUtilityLayer=null,t._DefaultKeepDepthUtilityLayer=null,t})();e.UtilityLayerRenderer=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){this.maxDragAngle=0,this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerID=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new e.Observable,this.onDragStartObservable=new e.Observable,this.onDragEndObservable=new e.Observable,this.moveAttached=!0,this.enabled=!0,this.detachCameraControls=!0,this.useObjectOrienationForDragging=!0,this._tmpVector=new e.Vector3(0,0,0),this._alternatePickedPoint=new e.Vector3(0,0,0),this._worldDragAxis=new e.Vector3(0,0,0),this._pointA=new e.Vector3(0,0,0),this._pointB=new e.Vector3(0,0,0),this._pointC=new e.Vector3(0,0,0),this._lineA=new e.Vector3(0,0,0),this._lineB=new e.Vector3(0,0,0),this._localAxis=new e.Vector3(0,0,0),this._lookAt=new e.Vector3(0,0,0),this._options=t||{};var i=0;if(this._options.dragAxis&&i++,this._options.dragPlaneNormal&&i++,i>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}return Object.defineProperty(t.prototype,"name",{get:function(){return"PointerDrag"},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(i){var r=this;this._scene=i.getScene(),this._attachedNode=i,t._planeScene||(this._debugMode?t._planeScene=this._scene:(t._planeScene=new e.Scene(this._scene.getEngine()),t._planeScene.detachControl(),this._scene.getEngine().scenes.pop(),this._scene.onDisposeObservable.addOnce((function(){t._planeScene.dispose(),t._planeScene=null})))),this._dragPlane=e.Mesh.CreatePlane("pointerDragPlane",this._debugMode?1:1e4,t._planeScene,!1,e.Mesh.DOUBLESIDE),this.lastDragPosition=new e.Vector3(0,0,0);var n=new e.Vector3(0,0,0),o=0,s=new e.Vector3(0,0,0),a=function(e){return r._attachedNode==e||e.isDescendantOf(r._attachedNode)},l=null;this._pointerObserver=this._scene.onPointerObservable.add((function(t,i){if(r.enabled)if(t.type==e.PointerEventTypes.POINTERDOWN){if(!r.dragging&&t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh&&t.pickInfo.pickedPoint&&t.pickInfo.ray&&a(t.pickInfo.pickedMesh)){r._updateDragPlanePosition(t.pickInfo.ray,t.pickInfo.pickedPoint);var h=r._pickWithRayOnDragPlane(t.pickInfo.ray);h&&(r.dragging=!0,r.currentDraggingPointerID=t.event.pointerId,r.lastDragPosition.copyFrom(h),r.onDragStartObservable.notifyObservers({dragPlanePoint:h,pointerId:r.currentDraggingPointerID}),s.copyFrom(r._attachedNode.absolutePosition),r.detachCameraControls&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&(r._scene.activeCamera.inputs.attachedElement?(l=r._scene.activeCamera.inputs.attachedElement,r._scene.activeCamera.detachControl(r._scene.activeCamera.inputs.attachedElement)):l=null))}}else if(t.type==e.PointerEventTypes.POINTERUP)r.currentDraggingPointerID==t.event.pointerId&&(r.releaseDrag(),r.detachCameraControls&&l&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&r._scene.activeCamera.attachControl(l,!0));else if(t.type==e.PointerEventTypes.POINTERMOVE&&r.currentDraggingPointerID==t.event.pointerId&&r.dragging&&t.pickInfo&&t.pickInfo.ray){r._moving=!0;var h=r._pickWithRayOnDragPlane(t.pickInfo.ray);h&&(r.updateDragPlane&&r._updateDragPlanePosition(t.pickInfo.ray,h),r._options.dragAxis?(e.Vector3.TransformCoordinatesToRef(r._options.dragAxis,r._attachedNode.getWorldMatrix().getRotationMatrix(),r._worldDragAxis),h.subtractToRef(r.lastDragPosition,r._tmpVector),o=e.Vector3.Dot(r._tmpVector,r._worldDragAxis),r._worldDragAxis.scaleToRef(o,n)):(o=n.length(),h.subtractToRef(r.lastDragPosition,n)),s.addInPlace(n),r.onDragObservable.notifyObservers({dragDistance:o,delta:n,dragPlanePoint:h,dragPlaneNormal:r._dragPlane.forward,pointerId:r.currentDraggingPointerID}),r.lastDragPosition.copyFrom(h))}})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((function(){r._moving&&r.moveAttached&&(s.subtractToRef(r._attachedNode.absolutePosition,r._tmpVector),r._tmpVector.scaleInPlace(.2),r._attachedNode.getAbsolutePosition().addToRef(r._tmpVector,r._tmpVector),r._attachedNode.setAbsolutePosition(r._tmpVector))}))},t.prototype.releaseDrag=function(){this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerID}),this.currentDraggingPointerID=-1,this._moving=!1},t.prototype._pickWithRayOnDragPlane=function(i){var r=this;if(!i)return null;var n=Math.acos(e.Vector3.Dot(this._dragPlane.forward,i.direction));if(n>Math.PI/2&&(n=Math.PI-n),this.maxDragAngle>0&&n>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(i.direction),this._attachedNode.absolutePosition.subtractToRef(i.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(-2*e.Vector3.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);var o=e.Vector3.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-o,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition),this._alternatePickedPoint}return null}var s=t._planeScene.pickWithRay(i,(function(e){return e==r._dragPlane}));return s&&s.hit&&s.pickedMesh&&s.pickedPoint?s.pickedPoint:null},t.prototype._updateDragPlanePosition=function(t,i){this._pointA.copyFrom(i),this._options.dragAxis?(this.useObjectOrienationForDragging?e.Vector3.TransformCoordinatesToRef(this._options.dragAxis,this._attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),this._pointA.addToRef(this._localAxis,this._pointB),t.origin.subtractToRef(this._pointA,this._pointC),this._pointA.addToRef(this._pointC.normalize(),this._pointC),this._pointB.subtractToRef(this._pointA,this._lineA),this._pointC.subtractToRef(this._pointA,this._lineB),e.Vector3.CrossToRef(this._lineA,this._lineB,this._lookAt),e.Vector3.CrossToRef(this._lineA,this._lookAt,this._lookAt),this._lookAt.normalize(),this._dragPlane.position.copyFrom(this._pointA),this._pointA.subtractToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrienationForDragging?e.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal,this._attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.subtractToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(t.origin)),this._dragPlane.computeWorldMatrix(!0)},t.prototype.detach=function(){this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver)},t})();e.PointerDragBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._startDistance=0,this._initialScale=new e.Vector3(0,0,0),this._targetScale=new e.Vector3(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new e.PointerDragBehavior({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new e.PointerDragBehavior({}),this._dragBehaviorB.moveAttached=!1}return Object.defineProperty(t.prototype,"name",{get:function(){return"MultiPointerScale"},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype._getCurrentDistance=function(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()},t.prototype.attach=function(e){var t=this;this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add((function(i){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerID==t._dragBehaviorB.currentDraggingPointerID?t._dragBehaviorA.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))})),this._dragBehaviorB.onDragStartObservable.add((function(i){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerID==t._dragBehaviorB.currentDraggingPointerID?t._dragBehaviorB.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))})),[this._dragBehaviorA,this._dragBehaviorB].forEach((function(e){e.onDragObservable.add((function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var e=t._getCurrentDistance()/t._startDistance;t._initialScale.scaleToRef(e,t._targetScale)}}))})),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var i=t._targetScale.subtract(e.scaling).scaleInPlace(.1);i.length()>.01&&e.scaling.addInPlace(i)}}))},t.prototype.detach=function(){var e=this;this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach((function(t){t.onDragStartObservable.clear(),t.onDragObservable.clear(),e._ownerNode.removeBehavior(t)}))},t})();e.MultiPointerScaleBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._sceneRenderObserver=null,this._targetPosition=new e.Vector3(0,0,0),this._moving=!1,this._startingOrientation=new e.Quaternion,this.zDragFactor=3,this.dragging=!1,this.dragDeltaRatio=.2,this.currentDraggingPointerID=-1,this.detachCameraControls=!0}return Object.defineProperty(t.prototype,"name",{get:function(){return"SixDofDrag"},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(i){var r=this;this._ownerNode=i,this._scene=this._ownerNode.getScene(),t._virtualScene||(t._virtualScene=new e.Scene(this._scene.getEngine()),this._scene.getEngine().scenes.pop());var n=null,o=new e.Vector3(0,0,0);this._virtualOriginMesh=new e.AbstractMesh("",t._virtualScene),this._virtualOriginMesh.rotationQuaternion=new e.Quaternion,this._virtualDragMesh=new e.AbstractMesh("",t._virtualScene),this._virtualDragMesh.rotationQuaternion=new e.Quaternion;var s=function(e){return r._ownerNode==e||e.isDescendantOf(r._ownerNode)},a=null;this._pointerObserver=this._scene.onPointerObservable.add((function(t,i){if(t.type==e.PointerEventTypes.POINTERDOWN){if(!r.dragging&&t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh&&t.pickInfo.ray&&s(t.pickInfo.pickedMesh)){r._scene.activeCamera&&r._scene.activeCamera.cameraRigMode==e.Camera.RIG_MODE_NONE&&t.pickInfo.ray.origin.copyFrom(r._scene.activeCamera.position),n=r._ownerNode,o.copyFrom(t.pickInfo.ray.origin),r._virtualOriginMesh.position.copyFrom(t.pickInfo.ray.origin),r._virtualOriginMesh.lookAt(t.pickInfo.ray.origin.subtract(t.pickInfo.ray.direction)),r._virtualOriginMesh.removeChild(r._virtualDragMesh),r._virtualDragMesh.position.copyFrom(n.absolutePosition),n.rotationQuaternion||(n.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(n.rotation.y,n.rotation.x,n.rotation.z));var l=n.parent;n.setParent(null),r._virtualDragMesh.rotationQuaternion.copyFrom(n.rotationQuaternion),n.setParent(l),r._virtualOriginMesh.addChild(r._virtualDragMesh),r._targetPosition.copyFrom(r._virtualDragMesh.absolutePosition),r.dragging=!0,r.currentDraggingPointerID=t.event.pointerId,r.detachCameraControls&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&(r._scene.activeCamera.inputs.attachedElement?(a=r._scene.activeCamera.inputs.attachedElement,r._scene.activeCamera.detachControl(r._scene.activeCamera.inputs.attachedElement)):a=null)}}else if(t.type==e.PointerEventTypes.POINTERUP)r.currentDraggingPointerID==t.event.pointerId&&(r.dragging=!1,r._moving=!1,r.currentDraggingPointerID=-1,n=null,r._virtualOriginMesh.removeChild(r._virtualDragMesh),r.detachCameraControls&&a&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&r._scene.activeCamera.attachControl(a,!0));else if(t.type==e.PointerEventTypes.POINTERMOVE&&r.currentDraggingPointerID==t.event.pointerId&&r.dragging&&t.pickInfo&&t.pickInfo.ray&&n){var h=r.zDragFactor;r._scene.activeCamera&&r._scene.activeCamera.cameraRigMode==e.Camera.RIG_MODE_NONE&&(t.pickInfo.ray.origin.copyFrom(r._scene.activeCamera.position),h=0);var c=t.pickInfo.ray.origin.subtract(o);o.copyFrom(t.pickInfo.ray.origin);var u=-e.Vector3.Dot(c,t.pickInfo.ray.direction);r._virtualOriginMesh.addChild(r._virtualDragMesh),r._virtualDragMesh.position.z-=r._virtualDragMesh.position.z<1?u*r.zDragFactor:u*h*r._virtualDragMesh.position.z,r._virtualDragMesh.position.z<0&&(r._virtualDragMesh.position.z=0),r._virtualOriginMesh.position.copyFrom(t.pickInfo.ray.origin),r._virtualOriginMesh.lookAt(t.pickInfo.ray.origin.subtract(t.pickInfo.ray.direction)),r._virtualOriginMesh.removeChild(r._virtualDragMesh),r._targetPosition.copyFrom(r._virtualDragMesh.absolutePosition),n.parent&&e.Vector3.TransformCoordinatesToRef(r._targetPosition,e.Matrix.Invert(n.parent.getWorldMatrix()),r._targetPosition),r._moving||r._startingOrientation.copyFrom(r._virtualDragMesh.rotationQuaternion),r._moving=!0}}));var l=new e.Quaternion;this._sceneRenderObserver=i.getScene().onBeforeRenderObservable.add((function(){if(r.dragging&&r._moving&&n){n.position.addInPlace(r._targetPosition.subtract(n.position).scale(r.dragDeltaRatio)),l.copyFrom(r._startingOrientation),l.x=-l.x,l.y=-l.y,l.z=-l.z,r._virtualDragMesh.rotationQuaternion.multiplyToRef(l,l),e.Quaternion.RotationYawPitchRollToRef(l.toEulerAngles("xyz").y,0,0,l),l.multiplyToRef(r._startingOrientation,l);var t=n.parent;n.setParent(null),e.Quaternion.SlerpToRef(n.rotationQuaternion,l,r.dragDeltaRatio,n.rotationQuaternion),n.setParent(t)}}))},t.prototype.detach=function(){this._scene&&this._scene.onPointerObservable.remove(this._pointerObserver),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualOriginMesh&&this._virtualOriginMesh.dispose(),this._virtualDragMesh&&this._virtualDragMesh.dispose()},t})();e.SixDofDragBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n){void 0===i&&(i=new e.Vector3),void 0===r&&(r=0),void 0===n&&(n=!1),this.direction=t,this.rotatedDirection=i,this.diff=r,this.ignore=n}return t})(),i=(function(){function i(i){this.ui=i,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new t(e.Vector3.Up()),new t(e.Vector3.Down()),new t(e.Vector3.Left()),new t(e.Vector3.Right()),new t(e.Vector3.Forward()),new t(e.Vector3.Forward().scaleInPlace(-1))],this._tmpMatrix=new e.Matrix,this._tmpVector=new e.Vector3,this._zeroVector=e.Vector3.Zero(),this._lookAtTmpMatrix=new e.Matrix}return i.prototype.init=function(){},i.prototype._closestFace=function(t){var i=this;return this._faceVectors.forEach((function(r){i._target.rotationQuaternion||(i._target.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(i._target.rotation.y,i._target.rotation.x,i._target.rotation.z)),i._target.rotationQuaternion.toRotationMatrix(i._tmpMatrix),e.Vector3.TransformCoordinatesToRef(r.direction,i._tmpMatrix,r.rotatedDirection),r.diff=e.Vector3.GetAngleBetweenVectors(r.rotatedDirection,t,e.Vector3.Cross(r.rotatedDirection,t))})),this._faceVectors.reduce((function(e,t){return e.ignore?t:t.ignore?e:e.diffo.snapDistance){var t=Math.floor(Math.abs(u)/o.snapDistance);u%=o.snapDistance,e.delta.normalizeToRef(f),f.scaleInPlace(o.snapDistance*t),o.attachedMesh.position.addInPlace(f),d.snapDistance=o.snapDistance*t,o.onSnapObservable.notifyObservers(d)}})),o._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e,t){if(!o._customMeshSet){var i=e.pickInfo&&-1!=o._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh),r=i?a:s;o._rootMesh.getChildMeshes().forEach((function(e){e.material=r,e.color&&(e.color=r.emissiveColor)}))}})),o}return o(i,t),i.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),t.prototype.dispose.call(this)},i})(e.Gizmo);e.AxisDragGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n){void 0===r&&(r=e.Color3.Gray()),void 0===n&&(n=e.UtilityLayerRenderer.DefaultUtilityLayer);var o=t.call(this,n)||this;o._pointerObserver=null,o.snapDistance=0,o.onSnapObservable=new e.Observable;var s=new e.StandardMaterial("",n.utilityLayerScene);s.disableLighting=!0,s.emissiveColor=r;var a=new e.StandardMaterial("",n.utilityLayerScene);a.disableLighting=!0,a.emissiveColor=r.add(new e.Color3(.2,.2,.2));var l=new e.AbstractMesh("",n.utilityLayerScene),h=e.MeshBuilder.CreateBox("yPosMesh",{size:.4},n.utilityLayerScene),c=e.MeshBuilder.CreateLines("yPosMesh",{points:[new e.Vector3(0,0,0),new e.Vector3(0,1.5,0)]},n.utilityLayerScene);c.color=s.emissiveColor,l.addChild(h),l.addChild(c),h.scaling.scaleInPlace(.1),h.material=s,h.rotation.x=Math.PI/2,h.position.z+=.3,c.scaling.scaleInPlace(.2),c.rotation.x=Math.PI/2,c.material=s,l.lookAt(o._rootMesh.position.subtract(i)),o._rootMesh.addChild(l),o.dragBehavior=new e.PointerDragBehavior({dragAxis:i}),o.dragBehavior.moveAttached=!1,o._rootMesh.addBehavior(o.dragBehavior);var u=0,f=new e.Vector3,d={snapDistance:0};return o.dragBehavior.onDragObservable.add((function(e){if(o.attachedMesh){var t=!1,r=0;0==o.snapDistance?i.scaleToRef(e.dragDistance,f):(u+=e.dragDistance,Math.abs(u)>o.snapDistance?(r=Math.floor(u/o.snapDistance),u%=o.snapDistance,i.scaleToRef(o.snapDistance*r,f),t=!0):f.scaleInPlace(0)),o.attachedMesh.scaling.addInPlace(f),t&&(d.snapDistance=o.snapDistance*r,o.onSnapObservable.notifyObservers(d))}})),o._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e,t){if(!o._customMeshSet){var i=e.pickInfo&&-1!=o._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh),r=i?a:s;o._rootMesh.getChildMeshes().forEach((function(e){e.material=r,e.color&&(e.color=r.emissiveColor)}))}})),o}return o(i,t),i.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),t.prototype.dispose.call(this)},i})(e.Gizmo);e.AxisScaleGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n){void 0===r&&(r=e.Color3.Gray()),void 0===n&&(n=e.UtilityLayerRenderer.DefaultUtilityLayer);var o=t.call(this,n)||this;o._pointerObserver=null,o.snapDistance=0,o.onSnapObservable=new e.Observable;var s=new e.StandardMaterial("",n.utilityLayerScene);s.disableLighting=!0,s.emissiveColor=r;var a=new e.StandardMaterial("",n.utilityLayerScene);a.disableLighting=!0,a.emissiveColor=r.add(new e.Color3(.2,.2,.2));for(var l=new e.AbstractMesh("",n.utilityLayerScene),h=new Array,c=0;c<20;c++){var u=2*Math.PI*(c/19);h.push(new e.Vector3(2*Math.sin(u),0,2*Math.cos(u)))}var f=e.Mesh.CreateLines("",h,n.utilityLayerScene);f.color=s.emissiveColor,f.scaling.scaleInPlace(.1),f.material=s,f.rotation.x=Math.PI/2,l.addChild(f),l.lookAt(o._rootMesh.position.subtract(i)),o._rootMesh.addChild(l),o.dragBehavior=new e.PointerDragBehavior({dragPlaneNormal:i}),o.dragBehavior.moveAttached=!1,o.dragBehavior.maxDragAngle=9*Math.PI/20,o.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,o._rootMesh.addBehavior(o.dragBehavior);var d=new e.Vector3;o.dragBehavior.onDragStartObservable.add((function(e){o.attachedMesh&&d.copyFrom(e.dragPlanePoint)}));var p=new e.Matrix,m=new e.Vector3,_=new e.Vector3,g={snapDistance:0},v=0;return o.dragBehavior.onDragObservable.add((function(t){if(o.attachedMesh){o.attachedMesh.rotationQuaternion||(o.attachedMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(o.attachedMesh.rotation.y,o.attachedMesh.rotation.x,o.attachedMesh.rotation.z));var r=t.dragPlanePoint.subtract(o.attachedMesh.position).normalize(),s=d.subtract(o.attachedMesh.position).normalize(),a=e.Vector3.Cross(r,s),l=e.Vector3.Dot(r,s),h=Math.atan2(a.length(),l);if(m.copyFrom(i),_.copyFrom(i),o.updateGizmoRotationToMatchAttachedMesh&&(o.attachedMesh.rotationQuaternion.toRotationMatrix(p),_=e.Vector3.TransformCoordinates(m,p)),n.utilityLayerScene.activeCamera){var c=n.utilityLayerScene.activeCamera.position.subtract(o.attachedMesh.position);e.Vector3.Dot(c,_)>0&&(m.scaleInPlace(-1),_.scaleInPlace(-1))}e.Vector3.Dot(_,a)>0&&(h=-h);var u=!1;if(0!=o.snapDistance)if(v+=h,Math.abs(v)>o.snapDistance){var f=Math.floor(v/o.snapDistance);v%=o.snapDistance,h=o.snapDistance*f,u=!0}else h=0;var y=Math.sin(h/2),b=new e.Quaternion(m.x*y,m.y*y,m.z*y,Math.cos(h/2));o.updateGizmoRotationToMatchAttachedMesh?o.attachedMesh.rotationQuaternion.multiplyToRef(b,o.attachedMesh.rotationQuaternion):b.multiplyToRef(o.attachedMesh.rotationQuaternion,o.attachedMesh.rotationQuaternion),d.copyFrom(t.dragPlanePoint),u&&(g.snapDistance=h,o.onSnapObservable.notifyObservers(g))}})),o._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e,t){if(!o._customMeshSet){var i=e.pickInfo&&-1!=o._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh),r=i?a:s;o._rootMesh.getChildMeshes().forEach((function(e){e.material=r,e.color&&(e.color=r.emissiveColor)}))}})),o}return o(i,t),i.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),t.prototype.dispose.call(this)},i})(e.Gizmo);e.PlaneRotationGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i){void 0===i&&(i=e.UtilityLayerRenderer.DefaultUtilityLayer);var r=t.call(this,i)||this;return r.xGizmo=new e.AxisDragGizmo(new e.Vector3(1,0,0),e.Color3.Green().scale(.5),i),r.yGizmo=new e.AxisDragGizmo(new e.Vector3(0,1,0),e.Color3.Red().scale(.5),i),r.zGizmo=new e.AxisDragGizmo(new e.Vector3(0,0,1),e.Color3.Blue().scale(.5),i),r.attachedMesh=null,r}return o(i,t),Object.defineProperty(i.prototype,"attachedMesh",{set:function(e){this.xGizmo&&(this.xGizmo.attachedMesh=e,this.yGizmo.attachedMesh=e,this.zGizmo.attachedMesh=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!0,configurable:!0}),i.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose()},i.prototype.setCustomMesh=function(t){e.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")},i})(e.Gizmo);e.PositionGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i){void 0===i&&(i=e.UtilityLayerRenderer.DefaultUtilityLayer);var r=t.call(this,i)||this;return r.xGizmo=new e.PlaneRotationGizmo(new e.Vector3(1,0,0),e.Color3.Green().scale(.5),i),r.yGizmo=new e.PlaneRotationGizmo(new e.Vector3(0,1,0),e.Color3.Red().scale(.5),i),r.zGizmo=new e.PlaneRotationGizmo(new e.Vector3(0,0,1),e.Color3.Blue().scale(.5),i),r.attachedMesh=null,r}return o(i,t),Object.defineProperty(i.prototype,"attachedMesh",{set:function(e){this.xGizmo&&(this.xGizmo.attachedMesh=e,this.yGizmo.attachedMesh=e,this.zGizmo.attachedMesh=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!0,configurable:!0}),i.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose()},i.prototype.setCustomMesh=function(t){e.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")},i})(e.Gizmo);e.RotationGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i){void 0===i&&(i=e.UtilityLayerRenderer.DefaultUtilityLayer);var r=t.call(this,i)||this;return r.xGizmo=new e.AxisScaleGizmo(new e.Vector3(1,0,0),e.Color3.Green().scale(.5),i),r.yGizmo=new e.AxisScaleGizmo(new e.Vector3(0,1,0),e.Color3.Red().scale(.5),i),r.zGizmo=new e.AxisScaleGizmo(new e.Vector3(0,0,1),e.Color3.Blue().scale(.5),i),r.attachedMesh=null,r}return o(i,t),Object.defineProperty(i.prototype,"attachedMesh",{set:function(e){this.xGizmo&&(this.xGizmo.attachedMesh=e,this.yGizmo.attachedMesh=e,this.zGizmo.attachedMesh=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!0,configurable:!0}),i.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose()},i})(e.Gizmo);e.ScaleGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r){void 0===i&&(i=e.Color3.Gray()),void 0===r&&(r=e.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer);var n=t.call(this,r)||this;n._boundingDimensions=new e.Vector3(1,1,1),n._renderObserver=null,n._pointerObserver=null,n._scaleDragSpeed=.2,n._tmpQuaternion=new e.Quaternion,n._tmpVector=new e.Vector3(0,0,0),n.rotationSphereSize=.1,n.scaleBoxSize=.1,n.fixedDragMeshScreenSize=!1,n.fixedDragMeshScreenSizeDistanceFactor=10,n.onDragStartObservable=new e.Observable,n.onDragObservable=new e.Observable,n.onDragEndObservable=new e.Observable,n._existingMeshScale=new e.Vector3,n._updateScale=!1,n._anchorMesh=new e.AbstractMesh("anchor",r.utilityLayerScene);var o=new e.StandardMaterial("",r.utilityLayerScene);o.disableLighting=!0,o.emissiveColor=i;var s=new e.StandardMaterial("",r.utilityLayerScene);s.disableLighting=!0,s.emissiveColor=i.clone().add(new e.Color3(.2,.2,.2)),n._lineBoundingBox=new e.AbstractMesh("",r.utilityLayerScene),n._lineBoundingBox.rotationQuaternion=new e.Quaternion;var a=[];a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,0),new e.Vector3(n._boundingDimensions.x,0,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,0),new e.Vector3(0,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,0),new e.Vector3(0,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,0,0),new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,0,0),new e.Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,n._boundingDimensions.y,0),new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,n._boundingDimensions.y,0),new e.Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,n._boundingDimensions.z),new e.Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,n._boundingDimensions.z),new e.Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new e.Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new e.Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.forEach((function(t){t.color=i,t.position.addInPlace(new e.Vector3(-n._boundingDimensions.x/2,-n._boundingDimensions.y/2,-n._boundingDimensions.z/2)),t.isPickable=!1,n._lineBoundingBox.addChild(t)})),n._rootMesh.addChild(n._lineBoundingBox),n._rotateSpheresParent=new e.AbstractMesh("",r.utilityLayerScene),n._rotateSpheresParent.rotationQuaternion=new e.Quaternion;for(var l,h=this,c=0;c<12;c++)!(function(t){var i=e.MeshBuilder.CreateSphere("",{diameter:1},r.utilityLayerScene);i.rotationQuaternion=new e.Quaternion,i.material=o,l=new e.PointerDragBehavior({}),l.moveAttached=!1,l.updateDragPlane=!1,i.addBehavior(l);var s=new e.Vector3(1,0,0),a=0;l.onDragStartObservable.add((function(e){s.copyFrom(i.forward),a=0})),l.onDragObservable.add((function(i){if(n.onDragObservable.notifyObservers({}),n.attachedMesh){var r=s,o=i.dragPlaneNormal.scale(e.Vector3.Dot(i.dragPlaneNormal,r)),l=r.subtract(o).normalizeToNew(),h=-e.Vector3.Dot(l,i.delta);h=h/n._boundingDimensions.length()*n._anchorMesh.scaling.length(),n.attachedMesh.rotationQuaternion||(n.attachedMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(n.attachedMesh.rotation.y,n.attachedMesh.rotation.x,n.attachedMesh.rotation.z)),n._anchorMesh.rotationQuaternion||(n._anchorMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(n._anchorMesh.rotation.y,n._anchorMesh.rotation.x,n._anchorMesh.rotation.z)),a+=h,Math.abs(a)<=2*Math.PI&&(t>=8?e.Quaternion.RotationYawPitchRollToRef(0,0,h,n._tmpQuaternion):t>=4?e.Quaternion.RotationYawPitchRollToRef(h,0,0,n._tmpQuaternion):e.Quaternion.RotationYawPitchRollToRef(0,h,0,n._tmpQuaternion),n._anchorMesh.addChild(n.attachedMesh),n._anchorMesh.rotationQuaternion.multiplyToRef(n._tmpQuaternion,n._anchorMesh.rotationQuaternion),n._anchorMesh.removeChild(n.attachedMesh)),n.updateBoundingBox()}})),l.onDragStartObservable.add((function(){n.onDragStartObservable.notifyObservers({}),n._selectNode(i)})),l.onDragEndObservable.add((function(){n.onDragEndObservable.notifyObservers({}),n._selectNode(null)})),h._rotateSpheresParent.addChild(i)})(c);n._rootMesh.addChild(n._rotateSpheresParent),n._scaleBoxesParent=new e.AbstractMesh("",r.utilityLayerScene),n._scaleBoxesParent.rotationQuaternion=new e.Quaternion;for(var u=0;u<2;u++)for(var f=0;f<2;f++)for(var l,d=this,p=0;p<2;p++)!(function(){var t=e.MeshBuilder.CreateBox("",{size:1},r.utilityLayerScene);t.material=o;var i=new e.Vector3(0==u?-1:1,0==f?-1:1,0==p?-1:1);l=new e.PointerDragBehavior({dragAxis:i}),l.moveAttached=!1,t.addBehavior(l),l.onDragObservable.add((function(i){if(n.onDragObservable.notifyObservers({}),n.attachedMesh){var r=i.dragDistance/n._boundingDimensions.length()*n._anchorMesh.scaling.length(),o=new e.Vector3(r,r,r);o.scaleInPlace(n._scaleDragSpeed),n.updateBoundingBox(),t.absolutePosition.subtractToRef(n._anchorMesh.position,n._tmpVector),n._anchorMesh.position.subtractInPlace(n._tmpVector),n._anchorMesh.addChild(n.attachedMesh),n._anchorMesh.scaling.addInPlace(o),(n._anchorMesh.scaling.x<0||n._anchorMesh.scaling.y<0||n._anchorMesh.scaling.z<0)&&n._anchorMesh.scaling.subtractInPlace(o),n._anchorMesh.removeChild(n.attachedMesh)}})),l.onDragStartObservable.add((function(){n.onDragStartObservable.notifyObservers({}),n._selectNode(t)})),l.onDragEndObservable.add((function(){n.onDragEndObservable.notifyObservers({}),n._selectNode(null)})),d._scaleBoxesParent.addChild(t)})();n._rootMesh.addChild(n._scaleBoxesParent);var m=new Array;return n._pointerObserver=r.utilityLayerScene.onPointerObservable.add((function(e,t){m[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=m[e.event.pointerId]&&(m[e.event.pointerId].material=o,delete m[e.event.pointerId]):n._rotateSpheresParent.getChildMeshes().concat(n._scaleBoxesParent.getChildMeshes()).forEach((function(t){e.pickInfo&&e.pickInfo.pickedMesh==t&&(m[e.event.pointerId]=t,t.material=s)}))})),n._renderObserver=n.gizmoLayer.originalScene.onBeforeRenderObservable.add((function(){n.attachedMesh&&!n._existingMeshScale.equals(n.attachedMesh.scaling)&&n.updateBoundingBox()})),n.updateBoundingBox(),n}return o(i,t),i.prototype._attachedMeshChanged=function(e){e&&(this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),this.updateBoundingBox())},i.prototype._selectNode=function(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((function(t,i){t.isVisible=!e||t==e}))},i.prototype._recurseComputeWorld=function(e){var t=this;e.computeWorldMatrix(!0),e.getChildMeshes().forEach((function(e){t._recurseComputeWorld(e)}))},i.prototype.updateBoundingBox=function(){if(this._update(),this.attachedMesh){this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);var t=this.attachedMesh.getHierarchyBoundingVectors();t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this._recurseComputeWorld(this.attachedMesh)}for(var i=this._rotateSpheresParent.getChildMeshes(),r=0;r<3;r++)for(var n=0;n<2;n++)for(var o=0;o<2;o++){var s=4*r+2*n+o;if(0==r&&(i[s].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*n,this._boundingDimensions.z*o),i[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),i[s].lookAt(e.Vector3.Cross(e.Vector3.Right(),i[s].position.normalizeToNew()).normalizeToNew().add(i[s].position))),1==r&&(i[s].position.set(this._boundingDimensions.x*n,this._boundingDimensions.y/2,this._boundingDimensions.z*o),i[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),i[s].lookAt(e.Vector3.Cross(e.Vector3.Up(),i[s].position.normalizeToNew()).normalizeToNew().add(i[s].position))),2==r&&(i[s].position.set(this._boundingDimensions.x*n,this._boundingDimensions.y*o,this._boundingDimensions.z/2),i[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),i[s].lookAt(e.Vector3.Cross(e.Vector3.Forward(),i[s].position.normalizeToNew()).normalizeToNew().add(i[s].position))),this.fixedDragMeshScreenSize){this._rootMesh.computeWorldMatrix(),this._rotateSpheresParent.computeWorldMatrix(),i[s].computeWorldMatrix(),i[s].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var a=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;i[s].scaling.set(a,a,a)}else i[s].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}for(var l=this._scaleBoxesParent.getChildMeshes(),r=0;r<2;r++)for(var n=0;n<2;n++)for(var o=0;o<2;o++){var s=4*r+2*n+o;if(l[s])if(l[s].position.set(this._boundingDimensions.x*r,this._boundingDimensions.y*n,this._boundingDimensions.z*o),l[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize){this._rootMesh.computeWorldMatrix(),this._scaleBoxesParent.computeWorldMatrix(),l[s].computeWorldMatrix(),l[s].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var a=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;l[s].scaling.set(a,a,a)}else l[s].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize)}this.attachedMesh&&this._existingMeshScale.copyFrom(this.attachedMesh.scaling)},i.prototype.setEnabledRotationAxis=function(e){this._rotateSpheresParent.getChildMeshes().forEach((function(t,i){i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))}))},i.prototype.dispose=function(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),t.prototype.dispose.call(this)},i.MakeNotPickableAndWrapInBoundingBox=function(t){var i=function(e){e.isPickable=!1,e.getChildMeshes().forEach((function(e){i(e)}))};i(t),t.rotationQuaternion||(t.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(t.rotation.y,t.rotation.x,t.rotation.z));var r=t.position.clone(),n=t.rotationQuaternion.clone();t.rotationQuaternion.set(0,0,0,1),t.position.set(0,0,0);var o=e.MeshBuilder.CreateBox("box",{size:1},t.getScene()),s=t.getHierarchyBoundingVectors();return s.max.subtractToRef(s.min,o.scaling),o.position.set((s.max.x+s.min.x)/2,(s.max.y+s.min.y)/2,(s.max.z+s.min.z)/2),t.addChild(o),t.rotationQuaternion.copyFrom(n),t.position.copyFrom(r),t.removeChild(o),o.addChild(t),o.visibility=0,o},i.prototype.setCustomMesh=function(t){e.Tools.Error("Custom meshes are not supported on this gizmo")},i})(e.Gizmo);e.BoundingBoxGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){var i=this;this.scene=t,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObserver=null,this._attachedMesh=null,this._boundingBoxColor=e.Color3.FromHexString("#0984e3"),this._dragBehavior=new e.SixDofDragBehavior,this.attachableMeshes=null,this.usePointerToAttachGizmos=!0,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null},this._pointerObserver=t.onPointerObservable.add((function(t,r){if(i.usePointerToAttachGizmos&&t.type==e.PointerEventTypes.POINTERDOWN)if(t.pickInfo&&t.pickInfo.pickedMesh){var n=t.pickInfo.pickedMesh;if(null==i.attachableMeshes)for(;n&&null!=n.parent;)n=n.parent;else{var o=!1;i.attachableMeshes.forEach((function(e){n&&(n==e||n.isDescendantOf(e))&&(n=e,o=!0)})),o||(n=null)}n instanceof e.AbstractMesh&&i.attachToMesh(n)}else i.attachToMesh(null)}))}return t.prototype.attachToMesh=function(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this._dragBehavior),this._attachedMesh=e;for(var t in this.gizmos){var i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this._dragBehavior)},Object.defineProperty(t.prototype,"positionGizmoEnabled",{get:function(){return this._gizmosEnabled.positionGizmo},set:function(t){t?(this.gizmos.positionGizmo=this.gizmos.positionGizmo||new e.PositionGizmo,this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh=!1,this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedMesh=null),this._gizmosEnabled.positionGizmo=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationGizmoEnabled",{get:function(){return this._gizmosEnabled.rotationGizmo},set:function(t){t?(this.gizmos.rotationGizmo=this.gizmos.rotationGizmo||new e.RotationGizmo,this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh=!1,this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedMesh=null),this._gizmosEnabled.rotationGizmo=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleGizmoEnabled",{get:function(){return this._gizmosEnabled.scaleGizmo},set:function(t){t?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new e.ScaleGizmo,this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedMesh=null),this._gizmosEnabled.scaleGizmo=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"boundingBoxGizmoEnabled",{get:function(){return this._gizmosEnabled.boundingBoxGizmo},set:function(t){t?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new e.BoundingBoxGizmo(this._boundingBoxColor),this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh,this._attachedMesh&&(this._attachedMesh.removeBehavior(this._dragBehavior),this._attachedMesh.addBehavior(this._dragBehavior))):this.gizmos.boundingBoxGizmo&&(this.gizmos.boundingBoxGizmo.attachedMesh=null),this._gizmosEnabled.boundingBoxGizmo=t},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.scene.onPointerObservable.remove(this._pointerObserver);for(var e in this.gizmos){var t=this.gizmos[e];t&&t.dispose()}this._dragBehavior.detach(),this._gizmoLayer.dispose()},t})();e.GizmoManager=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){void 0===i&&(i=0),void 0===r&&(r=null),this.name=t,this.animations=new Array,this._positions=null,this._normals=null,this._tangents=null,this.onInfluenceChanged=new e.Observable,this._animationPropertiesOverride=null,this._scene=r||e.Engine.LastCreatedScene,this.influence=i}return Object.defineProperty(t.prototype,"influence",{get:function(){return this._influence},set:function(e){if(this._influence!==e){var t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPositions",{get:function(){return!!this._positions},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasNormals",{get:function(){return!!this._normals},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasTangents",{get:function(){return!!this._tangents},enumerable:!0,configurable:!0}),t.prototype.setPositions=function(e){this._positions=e},t.prototype.getPositions=function(){return this._positions},t.prototype.setNormals=function(e){this._normals=e},t.prototype.getNormals=function(){return this._normals},t.prototype.setTangents=function(e){this._tangents=e},t.prototype.getTangents=function(){return this._tangents},t.prototype.serialize=function(){var t={};return t.name=this.name,t.influence=this.influence,t.positions=Array.prototype.slice.call(this.getPositions()),this.hasNormals&&(t.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(t.tangents=Array.prototype.slice.call(this.getTangents())), -e.Animation.AppendSerializedAnimations(this,t),t},t.Parse=function(i){var r=new t(i.name,i.influence);if(r.setPositions(i.positions),i.normals&&r.setNormals(i.normals),i.tangents&&r.setTangents(i.tangents),i.animations)for(var n=0;n=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetObservable.splice(t,1)[0]),this._syncActiveTargets(!0))},t.prototype.serialize=function(){var e={};e.id=this.uniqueId,e.targets=[];for(var t=0,i=this._targets;tthis.capacity&&this._depth=2&&t.onControllersAttachedObservable.notifyObservers(t.controllers)}}}))},i})(e.FreeCamera);e.WebVRFreeCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("DeviceOrientationCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n){var o=t.call(this,i,r,n)||this;return o._quaternionCache=new e.Quaternion,o.inputs.addDeviceOrientation(),o}return o(i,t),i.prototype.getClassName=function(){return"DeviceOrientationCamera"},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)},i.prototype.resetToCurrentRotation=function(t){var i=this;void 0===t&&(t=e.Axis.Y),this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new e.Quaternion),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((function(e){t[e]?i._initialQuaternion[e]*=-1:i._initialQuaternion[e]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))},i})(e.FreeCamera);e.DeviceOrientationCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s){void 0===o&&(o=!0), -void 0===s&&(s=e.VRCameraMetrics.GetDefault());var a=t.call(this,i,r,n)||this;return s.compensateDistortion=o,a.setCameraRigMode(e.Camera.RIG_MODE_VR,{vrCameraMetrics:s}),a}return o(i,t),i.prototype.getClassName=function(){return"VRDeviceOrientationFreeCamera"},i})(e.DeviceOrientationCamera);e.VRDeviceOrientationFreeCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera",(function(i,r){return function(){return new t(i,0,0,1,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s,a,l,h){void 0===l&&(l=!0),void 0===h&&(h=e.VRCameraMetrics.GetDefault());var c=t.call(this,i,r,n,o,s,a)||this;return h.compensateDistortion=l,c.setCameraRigMode(e.Camera.RIG_MODE_VR,{vrCameraMetrics:h}),c.inputs.addVRDeviceOrientation(),c}return o(i,t),i.prototype.getClassName=function(){return"VRDeviceOrientationArcRotateCamera"},i})(e.ArcRotateCamera);e.VRDeviceOrientationArcRotateCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s){void 0===o&&(o=!0),void 0===s&&(s=e.VRCameraMetrics.GetDefault());var a=t.call(this,i,r,n,o,s)||this;return a.inputs.addGamepad(),a}return o(i,t),i.prototype.getClassName=function(){return"VRDeviceOrientationGamepadCamera"},i})(e.VRDeviceOrientationFreeCamera);e.VRDeviceOrientationGamepadCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(i,r){if(void 0===r&&(r=null),this.scene=i,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=t._idCounter++,r)this._gazeTracker=r.clone("gazeTracker");else{this._gazeTracker=e.Mesh.CreateTorus("gazeTracker",.0035,.0025,20,i,!1),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;var n=new e.StandardMaterial("targetMat",i);n.specularColor=e.Color3.Black(),n.emissiveColor=new e.Color3(.7,.7,.7),n.backFaceCulling=!1,this._gazeTracker.material=n}}return t.prototype._getForwardRay=function(t){return new e.Ray(e.Vector3.Zero(),new e.Vector3(0,0,t))},t.prototype._selectionPointerDown=function(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})},t.prototype._selectionPointerUp=function(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1},t.prototype._activatePointer=function(){this._activePointer=!0},t.prototype._deactivatePointer=function(){this._activePointer=!1},t.prototype._updatePointerDistance=function(e){void 0===e&&(e=100)},t.prototype.dispose=function(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()},t._idCounter=0,t})(),i=(function(t){function i(i,r,n){var o=t.call(this,r,n)||this;o.webVRController=i,o._laserPointer=e.Mesh.CreateCylinder("laserPointer",1,.004,2e-4,20,1,r,!1);var s=new e.StandardMaterial("laserPointerMat",r);if(s.emissiveColor=new e.Color3(.7,.7,.7),s.alpha=.6,o._laserPointer.material=s,o._laserPointer.rotation.x=Math.PI/2,o._laserPointer.position.z=-.5,o._laserPointer.isVisible=!1,o._laserPointer.isPickable=!1,!i.mesh){var a=new e.Mesh("preloadControllerMesh",r),l=new e.Mesh(e.PoseEnabledController.POINTING_POSE,r);l.rotation.x=-.7,a.addChild(l),i.attachToMesh(a)}return o._setLaserPointerParent(i.mesh),o._meshAttachedObserver=i._meshAttachedObservable.add((function(e){o._setLaserPointerParent(e)})),o}return o(i,t),i.prototype._getForwardRay=function(e){return this.webVRController.getForwardRay(e)},i.prototype._activatePointer=function(){t.prototype._activatePointer.call(this),this._laserPointer.isVisible=!0},i.prototype._deactivatePointer=function(){t.prototype._deactivatePointer.call(this),this._laserPointer.isVisible=!1},i.prototype._setLaserPointerColor=function(e){this._laserPointer.material.emissiveColor=e},i.prototype._setLaserPointerParent=function(t){var i=function(e){e.isPickable=!1,e.getChildMeshes().forEach((function(e){i(e)}))};i(t);var r=t.getChildMeshes();this.webVRController._pointingPoseNode=null;for(var n=0;n=0){t=r[n],this.webVRController._pointingPoseNode=t;break}this._laserPointer.parent=t},i.prototype._updatePointerDistance=function(e){void 0===e&&(e=100),this._laserPointer.scaling.y=e,this._laserPointer.position.z=-e/2},i.prototype.dispose=function(){t.prototype.dispose.call(this),this._laserPointer.dispose(),this._meshAttachedObserver&&this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)},i})(t),r=(function(t){function i(e,i){var r=t.call(this,i)||this;return r.getCamera=e,r}return o(i,t),i.prototype._getForwardRay=function(t){var i=this.getCamera();return i?i.getForwardRay(t):new e.Ray(e.Vector3.Zero(),e.Vector3.Forward())},i})(t),n=(function(){function t(t,n){void 0===n&&(n={});var o=this;if(this.webVROptions=n,this._webVRsupported=!1,this._webVRready=!1,this._webVRrequesting=!1,this._webVRpresenting=!1,this._fullscreenVRpresenting=!1,this.onEnteringVRObservable=new e.Observable,this.onExitingVRObservable=new e.Observable,this.onControllerMeshLoadedObservable=new e.Observable,this._useCustomVRButton=!1,this._teleportationRequested=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._rotationAllowed=!0,this._teleportBackwardsVector=new e.Vector3(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new e.Vector3(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this.leftController=null,this.rightController=null,this.onNewMeshSelected=new e.Observable,this.onNewMeshPicked=new e.Observable,this.onBeforeCameraTeleport=new e.Observable,this.onAfterCameraTeleport=new e.Observable,this.onSelectedMeshUnselected=new e.Observable,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._interactionsRequested=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this._onResize=function(){o.moveButtonToBottomRight(),o._fullscreenVRpresenting&&o._webVRready&&o.exitVR()},this._onFullscreenChange=function(){void 0!==document.fullscreen?o._fullscreenVRpresenting=document.fullscreen:void 0!==document.mozFullScreen?o._fullscreenVRpresenting=document.mozFullScreen:void 0!==document.webkitIsFullScreen?o._fullscreenVRpresenting=document.webkitIsFullScreen:void 0!==document.msIsFullScreen?o._fullscreenVRpresenting=document.msIsFullScreen:void 0!==document.msFullscreenElement&&(o._fullscreenVRpresenting=document.msFullscreenElement),!o._fullscreenVRpresenting&&o._canvas&&(o.exitVR(),o._useCustomVRButton||(o._btnVR.style.top=o._canvas.offsetTop+o._canvas.offsetHeight-70+"px",o._btnVR.style.left=o._canvas.offsetLeft+o._canvas.offsetWidth-100+"px"))},this.beforeRender=function(){o.leftController&&o.leftController._activePointer&&o._castRayAndSelectObject(o.leftController),o.rightController&&o.rightController._activePointer&&o._castRayAndSelectObject(o.rightController),o._noControllerIsActive?o._castRayAndSelectObject(o._cameraGazer):o._cameraGazer._gazeTracker.isVisible=!1},this._onNewGamepadConnected=function(t){if(t.type!==e.Gamepad.POSE_ENABLED)t.leftStick&&t.onleftstickchanged((function(e){o._teleportationInitialized&&o.teleportationEnabled&&(!o.leftController&&!o.rightController||o.leftController&&!o.leftController._activePointer&&o.rightController&&!o.rightController._activePointer)&&(o._checkTeleportWithRay(e,o._cameraGazer),o._checkTeleportBackwards(e,o._cameraGazer))})),t.rightStick&&t.onrightstickchanged((function(e){o._teleportationInitialized&&o._checkRotate(e,o._cameraGazer)})),t.type===e.Gamepad.XBOX&&(t.onbuttondown((function(t){o._interactionsEnabled&&t===e.Xbox360Button.A&&o._cameraGazer._selectionPointerDown()})),t.onbuttonup((function(t){o._interactionsEnabled&&t===e.Xbox360Button.A&&o._cameraGazer._selectionPointerUp()})));else{var r=t,n=new i(r,o._scene,o._cameraGazer._gazeTracker);"right"===r.hand||o.leftController&&o.leftController.webVRController!=r?o.rightController=n:o.leftController=n,o._tryEnableInteractionOnController(n)}},this._tryEnableInteractionOnController=function(e){o._interactionsRequested&&!e._interactionsEnabled&&o._enableInteractionOnController(e),o._teleportationRequested&&!e._teleportationEnabled&&o._enableTeleportationOnController(e)},this._onNewGamepadDisconnected=function(t){t instanceof e.WebVRController&&("left"===t.hand&&null!=o.leftController&&(o.leftController.dispose(),o.leftController=null),"right"===t.hand&&null!=o.rightController&&(o.rightController.dispose(),o.rightController=null))},this._workingVector=e.Vector3.Zero(),this._workingQuaternion=e.Quaternion.Identity(),this._workingMatrix=e.Matrix.Identity(),this._scene=t,this._canvas=t.getEngine().getRenderingCanvas(),void 0===n.createFallbackVRDeviceOrientationFreeCamera&&(n.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===n.createDeviceOrientationCamera&&(n.createDeviceOrientationCamera=!0),void 0===n.laserToggle&&(n.laserToggle=!0),void 0===n.defaultHeight&&(n.defaultHeight=1.7),n.useCustomVRButton&&(this._useCustomVRButton=!0,n.customVRButton&&(this._btnVR=n.customVRButton)),n.rayLength&&(this._rayLength=n.rayLength),this._defaultHeight=n.defaultHeight,n.positionScale&&(this._rayLength*=n.positionScale,this._defaultHeight*=n.positionScale),this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new e.Vector3(0,this._defaultHeight,0),n.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new e.DeviceOrientationCamera("deviceOrientationVRHelper",this._position.clone(),t),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof e.TargetCamera&&this._scene.activeCamera.rotation)){var s=this._scene.activeCamera;s.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(s.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.Quaternion.RotationYawPitchRoll(s.rotation.y,s.rotation.x,s.rotation.z)),this._deviceOrientationCamera.rotation=s.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._canvas&&this._scene.activeCamera.attachControl(this._canvas)}else this._existingCamera=this._scene.activeCamera;if(n.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new e.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper",this._position,this._scene)),this._webVRCamera=new e.WebVRFreeCamera("WebVRHelper",this._position,this._scene,n),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new r(function(){return o.currentVRCamera},t),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";var a=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";a+=".babylonVRicon.vrdisplaypresenting { display: none; }";var l=document.createElement("style");l.appendChild(document.createTextNode(a)),document.getElementsByTagName("head")[0].appendChild(l),this.moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(function(){o.isInVRMode?o.exitVR():o.enterVR()})),window.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("mozfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("msfullscreenchange",this._onFullscreenChange,!1),document.onmsfullscreenchange=this._onFullscreenChange,n.createFallbackVRDeviceOrientationFreeCamera?this.displayVRButton():this._scene.getEngine().onVRDisplayChangedObservable.add((function(e){e.vrDisplay&&o.displayVRButton()})),this._onKeyDown=function(e){27===e.keyCode&&o.isInVRMode&&o.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((function(e,t){o.isInVRMode&&(o.exitVR(),o._fullscreenVRpresenting&&o._scene.getEngine().switchFullscreen(!0))}),e.PointerEventTypes.POINTERDOUBLETAP,!1),this._onVRDisplayChanged=function(e){return o.onVRDisplayChanged(e)},this._onVrDisplayPresentChange=function(){return o.onVrDisplayPresentChange()},this._onVRRequestPresentStart=function(){o._webVRrequesting=!0,o.updateButtonVisibility()},this._onVRRequestPresentComplete=function(e){o._webVRrequesting=!1,o.updateButtonVisibility()},t.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged),t.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),t.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),window.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),t.onDisposeObservable.add((function(){o.dispose()})),this._webVRCamera.onControllerMeshLoadedObservable.add((function(e){return o._onDefaultMeshLoaded(e)})),this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),this.updateButtonVisibility(),this._circleEase=new e.CircleEase,this._circleEase.setEasingMode(e.EasingFunction.EASINGMODE_EASEINOUT),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes})}return Object.defineProperty(t.prototype,"onEnteringVR",{get:function(){return this.onEnteringVRObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onExitingVR",{get:function(){return this.onExitingVRObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onControllerMeshLoaded",{get:function(){return this.onControllerMeshLoadedObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"teleportationTarget",{get:function(){return this._teleportationTarget},set:function(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gazeTrackerMesh",{get:function(){return this._cameraGazer._gazeTracker},set:function(e){e&&(this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker",this.leftController&&(this.leftController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")),this.rightController&&(this.rightController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayGaze",{get:function(){return this._displayGaze},set:function(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1,this.leftController&&(this.leftController._gazeTracker.isVisible=!1),this.rightController&&(this.rightController._gazeTracker.isVisible=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayLaserPointer",{get:function(){return this._displayLaserPointer},set:function(e){this._displayLaserPointer=e,e?(this.rightController&&this.rightController._activatePointer(),this.leftController&&this.leftController._activatePointer()):(this.rightController&&(this.rightController._deactivatePointer(),this.rightController._gazeTracker.isVisible=!1),this.leftController&&(this.leftController._deactivatePointer(),this.leftController._gazeTracker.isVisible=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"deviceOrientationCamera",{get:function(){return this._deviceOrientationCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentVRCamera",{get:function(){return this._webVRready?this._webVRCamera:this._scene.activeCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"webVRCamera",{get:function(){return this._webVRCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vrDeviceOrientationCamera",{get:function(){return this._vrDeviceOrientationCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_teleportationRequestInitiated",{get:function(){return this._cameraGazer._teleportationRequestInitiated||null!==this.leftController&&this.leftController._teleportationRequestInitiated||null!==this.rightController&&this.rightController._teleportationRequestInitiated},enumerable:!0,configurable:!0}),t.prototype._onDefaultMeshLoaded=function(t){this.leftController&&this.leftController.webVRController==t&&t.mesh&&this.leftController._setLaserPointerParent(t.mesh),this.rightController&&this.rightController.webVRController==t&&t.mesh&&this.rightController._setLaserPointerParent(t.mesh);try{this.onControllerMeshLoadedObservable.notifyObservers(t)}catch(t){e.Tools.Warn("Error in your custom logic onControllerMeshLoaded: "+t)}},Object.defineProperty(t.prototype,"isInVRMode",{get:function(){return this._webVRpresenting||this._fullscreenVRpresenting},enumerable:!0,configurable:!0}),t.prototype.onVrDisplayPresentChange=function(){var t=this._scene.getEngine().getVRDevice();if(t){var i=this._webVRpresenting;this._webVRpresenting=t.isPresenting,i&&!this._webVRpresenting&&this.exitVR()}else e.Tools.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");this.updateButtonVisibility()},t.prototype.onVRDisplayChanged=function(e){this._webVRsupported=e.vrSupported,this._webVRready=!!e.vrDisplay,this._webVRpresenting=e.vrDisplay&&e.vrDisplay.isPresenting,this.updateButtonVisibility()},t.prototype.moveButtonToBottomRight=function(){this._canvas&&!this._useCustomVRButton&&(this._btnVR.style.top=this._canvas.offsetTop+this._canvas.offsetHeight-70+"px",this._btnVR.style.left=this._canvas.offsetLeft+this._canvas.offsetWidth-100+"px")},t.prototype.displayVRButton=function(){this._useCustomVRButton||this._btnVRDisplayed||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)},t.prototype.updateButtonVisibility=function(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode?this._btnVR.className+=" vrdisplaypresenting":(this._webVRready&&(this._btnVR.className+=" vrdisplayready"),this._webVRsupported&&(this._btnVR.className+=" vrdisplaysupported"),this._webVRrequesting&&(this._btnVR.className+=" vrdisplayrequesting")))},t.prototype.enterVR=function(){if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(t){e.Tools.Warn("Error in your custom logic onEnteringVR: "+t)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this._existingCamera=this._scene.activeCamera),this._webVRrequesting||(this._webVRready?this._webVRpresenting||(this._webVRCamera.position=this._position,this._scene.activeCamera=this._webVRCamera):this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().switchFullscreen(!0),this.updateButtonVisibility()),this._scene.activeCamera&&this._canvas&&this._scene.activeCamera.attachControl(this._canvas),this._interactionsEnabled&&this._scene.registerBeforeRender(this.beforeRender))},t.prototype.exitVR=function(){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(t){e.Tools.Warn("Error in your custom logic onExitingVR: "+t)}this._webVRpresenting&&this._scene.getEngine().disableVR(),this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._canvas&&this._scene.activeCamera.attachControl(this._canvas)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera),this.updateButtonVisibility(),this._interactionsEnabled&&this._scene.unregisterBeforeRender(this.beforeRender),this._scene.getEngine().resize()},Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)},enumerable:!0,configurable:!0}),t.prototype.enableInteractions=function(){var e=this;this._interactionsEnabled||(this._interactionsRequested=!0,this.leftController&&this._enableInteractionOnController(this.leftController),this.rightController&&this._enableInteractionOnController(this.rightController),this.raySelectionPredicate=function(e){return e.isVisible&&e.isPickable},this.meshSelectionPredicate=function(e){return!0},this._raySelectionPredicate=function(t){return!!(e._isTeleportationFloor(t)||-1===t.name.indexOf("gazeTracker")&&-1===t.name.indexOf("teleportationTarget")&&-1===t.name.indexOf("torusTeleportation"))&&e.raySelectionPredicate(t)},this._interactionsEnabled=!0)},Object.defineProperty(t.prototype,"_noControllerIsActive",{get:function(){return!(this.leftController&&this.leftController._activePointer||this.rightController&&this.rightController._activePointer)},enumerable:!0,configurable:!0}),t.prototype._isTeleportationFloor=function(e){for(var t=0;t-1||this._floorMeshesCollection.push(e))},t.prototype.removeFloorMesh=function(e){if(this._floorMeshesCollection){var t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}},t.prototype.enableTeleportation=function(t){if(void 0===t&&(t={}),!this._teleportationInitialized){this._teleportationRequested=!0,this.enableInteractions(),t.floorMeshName&&(this._floorMeshName=t.floorMeshName),t.floorMeshes&&(this._floorMeshesCollection=t.floorMeshes),null!=this.leftController&&this._enableTeleportationOnController(this.leftController),null!=this.rightController&&this._enableTeleportationOnController(this.rightController);var i=new e.ImageProcessingConfiguration;i.vignetteColor=new e.Color4(0,0,0,0),i.vignetteEnabled=!0,this._postProcessMove=new e.ImageProcessingPostProcess("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,i),this._webVRCamera.detachPostProcess(this._postProcessMove),this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&(this._createTeleportationCircles(),this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))}},t.prototype._enableInteractionOnController=function(e){var t=this;e.webVRController.mesh&&(e._interactionsEnabled=!0,e._activatePointer(),this.webVROptions.laserToggle&&e.webVRController.onMainButtonStateChangedObservable.add((function(i){t._displayLaserPointer&&1===i.value&&(e._activePointer?e._deactivatePointer():e._activatePointer(),t.displayGaze&&(e._gazeTracker.isVisible=e._activePointer))})),e.webVRController.onTriggerStateChangedObservable.add((function(i){var r=e;t._noControllerIsActive&&(r=t._cameraGazer),r._pointerDownOnMeshAsked?i.valuet._padSensibilityUp&&r._selectionPointerDown()})))},t.prototype._checkTeleportWithRay=function(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))},t.prototype._checkTeleportBackwards=function(t,i){if(!i._teleportationRequestInitiated)if(t.y>this._padSensibilityUp&&i._dpadPressed){if(!i._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;var r=e.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),n=this.currentVRCamera.position;this.currentVRCamera.devicePosition&&this.currentVRCamera.deviceRotationQuaternion&&(r=this.currentVRCamera.deviceRotationQuaternion,n=this.currentVRCamera.devicePosition),r.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,e.Quaternion.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),e.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);var o=new e.Ray(n,this._workingVector),s=this._scene.pickWithRay(o,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this._teleportCamera(s.pickedPoint),i._teleportationBackRequestInitiated=!0}}else i._teleportationBackRequestInitiated=!1},t.prototype._enableTeleportationOnController=function(t){var i=this;t.webVRController.mesh&&(t._interactionsEnabled||this._enableInteractionOnController(t),t._interactionsEnabled=!0,t._teleportationEnabled=!0,t.webVRController.controllerType===e.PoseEnabledControllerType.VIVE&&(t._dpadPressed=!1,t.webVRController.onPadStateChangedObservable.add((function(e){t._dpadPressed=e.pressed,t._dpadPressed||(t._rotationLeftAsked=!1,t._rotationRightAsked=!1,t._teleportationBackRequestInitiated=!1)}))),t.webVRController.onPadValuesChangedObservable.add((function(e){i.teleportationEnabled&&(i._checkTeleportBackwards(e,t),i._checkTeleportWithRay(e,t)),i._checkRotate(e,t)})))},t.prototype._createTeleportationCircles=function(){this._teleportationTarget=e.Mesh.CreateGround("teleportationTarget",2,2,2,this._scene),this._teleportationTarget.isPickable=!1;var t=new e.DynamicTexture("DynamicTexture",512,this._scene,!0);t.hasAlpha=!0;var i=t.getContext();i.beginPath(),i.arc(256,256,200,0,2*Math.PI,!1),i.fillStyle=this._teleportationFillColor,i.fill(),i.lineWidth=10,i.strokeStyle=this._teleportationBorderColor,i.stroke(),i.closePath(),t.update();var r=new e.StandardMaterial("TextPlaneMaterial",this._scene);r.diffuseTexture=t,this._teleportationTarget.material=r;var n=e.Mesh.CreateTorus("torusTeleportation",.75,.1,25,this._scene,!1);n.isPickable=!1,n.parent=this._teleportationTarget;var o=new e.Animation("animationInnerCircle","position.y",30,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CYCLE),s=[];s.push({frame:0,value:0}),s.push({frame:30,value:.4}),s.push({frame:60,value:0}),o.setKeys(s);var a=new e.SineEase;a.setEasingMode(e.EasingFunction.EASINGMODE_EASEINOUT),o.setEasingFunction(a),n.animations=[],n.animations.push(o),this._scene.beginAnimation(n,0,60,!0),this._hideTeleportationTarget()},t.prototype._displayTeleportationTarget=function(){this._teleportActive=!0,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!0,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!0))},t.prototype._hideTeleportationTarget=function(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))},t.prototype._rotateCamera=function(t){var i=this;if(this.currentVRCamera instanceof e.FreeCamera){t?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];var r=e.Quaternion.FromRotationMatrix(e.Matrix.RotationY(Math.PI/4*this._rotationAngle)),n=new e.Animation("animationRotation","rotationQuaternion",90,e.Animation.ANIMATIONTYPE_QUATERNION,e.Animation.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),o.push({frame:6,value:r}),n.setKeys(o),n.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(n),this._postProcessMove.animations=[];var s=new e.Animation("animationPP","vignetteWeight",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:4}),a.push({frame:6,value:0}),s.setKeys(a),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);var l=new e.Animation("animationPP2","vignetteStretch",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:3,value:10}),h.push({frame:6,value:0}),l.setKeys(h),l.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,6,!1,1,(function(){i._webVRCamera.detachPostProcess(i._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}},t.prototype._moveTeleportationSelectorTo=function(t,i,r){if(t.pickedPoint){i._teleportationRequestInitiated&&(this._displayTeleportationTarget(),this._haloCenter.copyFrom(t.pickedPoint),this._teleportationTarget.position.copyFrom(t.pickedPoint)) -;var n=this._convertNormalToDirectionOfRay(t.getNormal(!0,!1),r);if(n){var o=e.Vector3.Cross(e.Axis.Y,n),s=e.Vector3.Cross(n,o);e.Vector3.RotationFromAxisToRef(s,n,o,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}},t.prototype._teleportCamera=function(t){var i=this;if(this.currentVRCamera instanceof e.FreeCamera){this.webVRCamera.leftCamera?(this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),this._workingVector.subtractInPlace(this.webVRCamera.position),t.subtractToRef(this._workingVector,this._workingVector)):this._workingVector.copyFrom(t),this.isInVRMode?this._workingVector.y+=this.webVRCamera.deviceDistanceToRoomGround()*this._webVRCamera.deviceScaleFactor:this._workingVector.y+=this._defaultHeight,this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this.currentVRCamera.animations=[];var r=new e.Animation("animationCameraTeleportation","position",90,e.Animation.ANIMATIONTYPE_VECTOR3,e.Animation.ANIMATIONLOOPMODE_CONSTANT),n=[{frame:0,value:this.currentVRCamera.position},{frame:11,value:this._workingVector}];r.setKeys(n),r.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];var o=new e.Animation("animationPP","vignetteWeight",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:0}),s.push({frame:5,value:8}),s.push({frame:11,value:0}),o.setKeys(s),this._postProcessMove.animations.push(o);var a=new e.Animation("animationPP2","vignetteStretch",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:5,value:10}),l.push({frame:11,value:0}),a.setKeys(l),this._postProcessMove.animations.push(a),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,11,!1,1,(function(){i._webVRCamera.detachPostProcess(i._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,11,!1,1,(function(){i.onAfterCameraTeleport.notifyObservers(i._workingVector)})),this._hideTeleportationTarget()}},t.prototype._convertNormalToDirectionOfRay=function(t,i){if(t){Math.acos(e.Vector3.Dot(t,i.direction))i.halfWidth,t&&this._joystickPointerID<0?(this._joystickPointerID=e.pointerId,this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone(),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):i._globalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))},i.prototype._onPointerMove=function(e){if(this._joystickPointerID==e.pointerId){this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY,this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos);var i=this.reverseLeftRight?-1:1,r=i*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,r));break;case t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,r));break;case t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,r))}var n=this.reverseUpDown?1:-1,o=n*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,o));break;case t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,o));break;case t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,o))}}else{var s=this._touches.get(e.pointerId.toString());s&&(s.x=e.clientX,s.y=e.clientY)}},i.prototype._onPointerUp=function(e){if(this._joystickPointerID==e.pointerId)i.vjCanvasContext.clearRect(this._joystickPointerStartPos.x-64,this._joystickPointerStartPos.y-64,128,128),i.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x-42,this._joystickPreviousPointerPos.y-42,84,84),this._joystickPointerID=-1,this.pressed=!1;else{var t=this._touches.get(e.pointerId.toString());t&&i.vjCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(e.pointerId.toString())},i.prototype.setJoystickColor=function(e){this._joystickColor=e},i.prototype.setActionOnTouch=function(e){this._action=e},i.prototype.setAxisForLeftRight=function(e){switch(e){case t.X:case t.Y:case t.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=t.X}},i.prototype.setAxisForUpDown=function(e){switch(e){case t.X:case t.Y:case t.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=t.Y}},i.prototype._drawVirtualJoystick=function(){var e=this;this.pressed&&this._touches.forEach((function(t,r){r.pointerId===e._joystickPointerID?(i.vjCanvasContext.clearRect(e._joystickPointerStartPos.x-64,e._joystickPointerStartPos.y-64,128,128),i.vjCanvasContext.clearRect(e._joystickPreviousPointerPos.x-42,e._joystickPreviousPointerPos.y-42,84,84),i.vjCanvasContext.beginPath(),i.vjCanvasContext.lineWidth=6,i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.arc(e._joystickPointerStartPos.x,e._joystickPointerStartPos.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.lineWidth=2,i.vjCanvasContext.arc(e._joystickPointerStartPos.x,e._joystickPointerStartPos.y,60,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.arc(e._joystickPointerPos.x,e._joystickPointerPos.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),e._joystickPreviousPointerPos=e._joystickPointerPos.clone()):(i.vjCanvasContext.clearRect(r.prevX-44,r.prevY-44,88,88),i.vjCanvasContext.beginPath(),i.vjCanvasContext.fillStyle="white",i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle="red",i.vjCanvasContext.lineWidth=6,i.vjCanvasContext.arc(r.x,r.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),r.prevX=r.x,r.prevY=r.y)})),requestAnimationFrame((function(){e._drawVirtualJoystick()}))},i.prototype.releaseCanvas=function(){i.vjCanvas&&(i.vjCanvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),i.vjCanvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),i.vjCanvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),i.vjCanvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(i.vjCanvas),i.vjCanvas=null)},i._globalJoystickIndex=0,i})();e.VirtualJoystick=i})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VirtualJoysticksCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addVirtualJoystick(),n}return o(t,e),t.prototype.getClassName=function(){return"VirtualJoysticksCamera"},t})(e.FreeCamera);e.VirtualJoysticksCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.prototype.getLeftJoystick=function(){return this._leftjoystick},t.prototype.getRightJoystick=function(){return this._rightjoystick},t.prototype.checkInputs=function(){if(this._leftjoystick){var t=this.camera,i=50*t._computeLocalCameraSpeed(),r=e.Matrix.RotationYawPitchRoll(t.rotation.y,t.rotation.x,0),n=e.Vector3.TransformCoordinates(new e.Vector3(this._leftjoystick.deltaPosition.x*i,this._leftjoystick.deltaPosition.y*i,this._leftjoystick.deltaPosition.z*i),r);t.cameraDirection=t.cameraDirection.add(n),t.cameraRotation=t.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}},t.prototype.attachControl=function(t,i){this._leftjoystick=new e.VirtualJoystick(!0),this._leftjoystick.setAxisForUpDown(e.JoystickAxis.Z),this._leftjoystick.setAxisForLeftRight(e.JoystickAxis.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new e.VirtualJoystick(!1),this._rightjoystick.setAxisForUpDown(e.JoystickAxis.X),this._rightjoystick.setAxisForLeftRight(e.JoystickAxis.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")},t.prototype.detachControl=function(e){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()},t.prototype.getClassName=function(){return"FreeCameraVirtualJoystickInput"},t.prototype.getSimpleName=function(){return"virtualJoystick"},t})();e.FreeCameraVirtualJoystickInput=t,e.CameraInputTypes.FreeCameraVirtualJoystickInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i){this.quality=e,this.distance=t,this.optimizeMesh=i}return e})();e.SimplificationSettings=t;var i=(function(){function t(){this.running=!1,this._simplificationArray=[]}return t.prototype.addTask=function(e){this._simplificationArray.push(e)},t.prototype.executeNext=function(){var e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1},t.prototype.runSimplification=function(t){var i=this;if(t.parallelProcessing)t.settings.forEach((function(e){i.getSimplifier(t).simplify(e,(function(r){t.mesh.addLODLevel(e.distance,r),r.isVisible=!0,e.quality===t.settings[t.settings.length-1].quality&&t.successCallback&&t.successCallback(),i.executeNext()}))}));else{var r=this.getSimplifier(t),n=function(e,i){r.simplify(e,(function(r){t.mesh.addLODLevel(e.distance,r),r.isVisible=!0,i()}))};e.AsyncLoop.Run(t.settings.length,(function(e){n(t.settings[e.index],(function(){e.executeNext()}))}),(function(){t.successCallback&&t.successCallback(),i.executeNext()}))}},t.prototype.getSimplifier=function(e){switch(e.simplificationType){case r.QUADRATIC:default:return new l(e.mesh)}},t})();e.SimplificationQueue=i;var r;!(function(e){e[e.QUADRATIC=0]="QUADRATIC"})(r=e.SimplificationType||(e.SimplificationType={}));var n=(function(){function e(e){this.vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}return e})();e.DecimationTriangle=n;var o=(function(){function e(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new s,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}return e.prototype.updatePosition=function(e){this.position.copyFrom(e)},e})();e.DecimationVertex=o;var s=(function(){function e(e){this.data=new Array(10);for(var t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}return e.prototype.det=function(e,t,i,r,n,o,s,a,l){return this.data[e]*this.data[n]*this.data[l]+this.data[i]*this.data[r]*this.data[a]+this.data[t]*this.data[o]*this.data[s]-this.data[i]*this.data[n]*this.data[s]-this.data[e]*this.data[o]*this.data[a]-this.data[t]*this.data[r]*this.data[l]},e.prototype.addInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e.data[t]},e.prototype.addArrayInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e[t]},e.prototype.add=function(t){for(var i=new e,r=0;r<10;++r)i.data[r]=this.data[r]+t.data[r];return i},e.FromData=function(t,i,r,n){return new e(e.DataFromNumbers(t,i,r,n))},e.DataFromNumbers=function(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]},e})();e.QuadraticMatrix=s;var a=(function(){function e(e,t){this.vertexId=e,this.triangleId=t}return e})();e.Reference=a;var l=(function(){function t(t){this._mesh=t,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=e.Epsilon}return t.prototype.simplify=function(t,i){var r=this;this.initDecimatedMesh(),e.AsyncLoop.Run(this._mesh.subMeshes.length,(function(e){r.initWithMesh(e.index,(function(){r.runDecimation(t,e.index,(function(){e.executeNext()}))}),t.optimizeMesh)}),(function(){setTimeout((function(){i(r._reconstructedMesh)}),0)}))},t.prototype.runDecimation=function(t,i,r){var n=this,o=~~(this.triangles.length*t.quality),s=0,a=this.triangles.length,l=function(t,i){setTimeout((function(){t%5==0&&n.updateMesh(0===t);for(var r=0;rl||r.deleted||r.isDirty))for(var o=0;o<3;++o)if(r.error[o]>0,f,(function(){var t=function(e){if(l){var t=h.indexStart/3+e,i=3*t,r=l[i+0],o=l[i+1],a=l[i+2],c=s.vertices[u[r-h.verticesStart]],f=s.vertices[u[o-h.verticesStart]],d=s.vertices[u[a-h.verticesStart]],p=new n([c,f,d]);p.originalOffset=i,s.triangles.push(p)}};e.AsyncLoop.SyncAsyncForLoop(h.indexCount/3,s.syncIterations,t,(function(){s.init(i)}))}))},t.prototype.init=function(t){var i=this,r=function(t){var r=i.triangles[t];r.normal=e.Vector3.Cross(r.vertices[1].position.subtract(r.vertices[0].position),r.vertices[2].position.subtract(r.vertices[0].position)).normalize();for(var n=0;n<3;n++)r.vertices[n].q.addArrayInPlace(s.DataFromNumbers(r.normal.x,r.normal.y,r.normal.z,-e.Vector3.Dot(r.normal,r.vertices[0].position)))};e.AsyncLoop.SyncAsyncForLoop(this.triangles.length,this.syncIterations,r,(function(){var r=function(e){for(var t=i.triangles[e],r=0;r<3;++r)t.error[r]=i.calculateError(t.vertices[r],t.vertices[(r+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])};e.AsyncLoop.SyncAsyncForLoop(i.triangles.length,i.syncIterations,r,(function(){t()}))}))},t.prototype.reconstructMesh=function(t){var i,r=[];for(i=0;i0&&this._reconstructedMesh.setVerticesData(e.VertexBuffer.UVKind,l),h.length>0&&this._reconstructedMesh.setVerticesData(e.VertexBuffer.ColorKind,h);var b=this._mesh.subMeshes[t];t>0&&(this._reconstructedMesh.subMeshes=[],g.forEach((function(t){e.SubMesh.AddToMesh(t.materialIndex,t.verticesStart,t.verticesCount,t.indexStart,t.indexCount,t.getMesh())})),e.SubMesh.AddToMesh(b.materialIndex,_,d,m,3*r.length,this._reconstructedMesh))},t.prototype.initDecimatedMesh=function(){this._reconstructedMesh=new e.Mesh(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId},t.prototype.isFlipped=function(t,i,r,n,o,s){for(var a=0;a.999)return!0;var p=e.Vector3.Cross(f,d).normalize();if(n[a]=!1,e.Vector3.Dot(p,l.normal)<.2)return!0}else n[a]=!0,s.push(l)}}return!1},t.prototype.updateTriangles=function(e,t,i,r){for(var n=r,o=0;othis.maximumSize&&(n.scale(this.step),i=!1)}}return i},t})(t);e.TextureOptimization=i;var r=(function(e){function t(t,i,r){void 0===t&&(t=0),void 0===i&&(i=2),void 0===r&&(r=.25);var n=e.call(this,t)||this;return n.priority=t,n.maximumScale=i,n.step=r,n._currentScale=-1,n._directionOffset=1,n}return o(t,e),t.prototype.getDescription=function(){return"Setting hardware scaling level to "+this._currentScale},t.prototype.apply=function(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale},t})(t);e.HardwareScalingOptimization=r;var n=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning shadows on/off"},t.prototype.apply=function(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0},t})(t);e.ShadowsOptimization=n;var s=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning post-processes on/off"},t.prototype.apply=function(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0},t})(t);e.PostProcessesOptimization=s;var a=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning lens flares on/off"},t.prototype.apply=function(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0},t})(t);e.LensFlaresOptimization=a;var l=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"},t.prototype.apply=function(e,t){return!this.onApply||this.onApply(e,t)},t})(t);e.CustomOptimization=l;var h=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning particles on/off"},t.prototype.apply=function(e,t){return e.particlesEnabled=t.isInImprovementMode,!0},t})(t);e.ParticlesOptimization=h;var c=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){ -return"Turning render targets off"},t.prototype.apply=function(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0},t})(t);e.RenderTargetsOptimization=c;var u=(function(t){function i(){var i=null!==t&&t.apply(this,arguments)||this;return i._canBeMerged=function(t){if(!(t instanceof e.Mesh))return!1;var i=t;return!i.isDisposed()&&(!(!i.isVisible||!i.isEnabled())&&(!(i.instances.length>0)&&(!i.skeleton&&!i.hasLODLevels)))},i}return o(i,t),Object.defineProperty(i,"UpdateSelectionTree",{get:function(){return i._UpdateSelectionTree},set:function(e){i._UpdateSelectionTree=e},enumerable:!0,configurable:!0}),i.prototype.getDescription=function(){return"Merging similar meshes together"},i.prototype.apply=function(t,r,n){for(var o=t.meshes.slice(0),s=o.length,a=0;a=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);for(var r=!0,n=!0,o=0;o4&&(n.push(e.VertexBuffer.MatricesIndicesExtraKind),n.push(e.VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton?o.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),i&&(r.push("#define INSTANCES"),n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"));var a=r.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("outline",n,["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant"],["diffuseSampler"],a)),this._effect.isReady()},t})();e.OutlineRenderer=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this.edges=new Array,this.edgesConnectedCount=0}return e})(),i=(function(){function i(e,t,i){void 0===t&&(t=.95),void 0===i&&(i=!1),this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this._source=e,this._checkVerticesInsteadOfIndices=i,this._epsilon=t,this._prepareRessources(),this._generateEdgesLines()}return i.prototype._prepareRessources=function(){this._lineShader||(this._lineShader=new e.ShaderMaterial("lineShader",this._source.getScene(),"line",{attributes:["position","normal"],uniforms:["worldViewProjection","color","width","aspectRatio"]}),this._lineShader.disableDepthWrite=!0,this._lineShader.backFaceCulling=!1)},i.prototype._rebuild=function(){var t=this._buffers[e.VertexBuffer.PositionKind];t&&t._rebuild(),(t=this._buffers[e.VertexBuffer.NormalKind])&&t._rebuild();var i=this._source.getScene(),r=i.getEngine();this._ib=r.createIndexBuffer(this._linesIndices)},i.prototype.dispose=function(){var t=this._buffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._buffers[e.VertexBuffer.PositionKind]=null),t=this._buffers[e.VertexBuffer.NormalKind],t&&(t.dispose(),this._buffers[e.VertexBuffer.NormalKind]=null),this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose()},i.prototype._processEdgeForAdjacencies=function(e,t,i,r,n){return e===i&&t===r||e===r&&t===i?0:e===r&&t===n||e===n&&t===r?1:e===n&&t===i||e===i&&t===n?2:-1},i.prototype._processEdgeForAdjacenciesWithVertices=function(e,t,i,r,n){return e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(r)||e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(i)?0:e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(n)||e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(r)?1:e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(i)||e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(n)?2:-1},i.prototype._checkEdge=function(t,i,r,n,o){var s;if(void 0===i)s=!0;else{s=e.Vector3.Dot(r[t],r[i])0){this._previousStencilState=this._engine.getStencilBuffer();for(var r=0,n=i;r-1)){this._renderEffects=!0,this._needStencil=this._needStencil||o.needStencil();var s=o._mainTexture;s._shouldRender()&&(this.scene.incrementRenderId(),s.render(!1,!1))}}this.scene.incrementRenderId()}},t.prototype._setStencil=function(e){this._needStencil&&this._engine.setStencilBuffer(!0)},t.prototype._setStencilBack=function(e){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)},t.prototype._draw=function(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);for(var t=this.scene.effectLayers,i=0;i4&&(s.push(e.VertexBuffer.MatricesIndicesExtraKind),s.push(e.VertexBuffer.MatricesWeightsExtraKind)),o.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),o.push("#define BonesPerMesh "+(a.skeleton?a.skeleton.bones.length+1:0))):o.push("#define NUM_BONE_INFLUENCERS 0");var u=a.morphTargetManager,f=0;u&&u.numInfluencers>0&&(o.push("#define MORPHTARGETS"),f=u.numInfluencers,o.push("#define NUM_MORPH_INFLUENCERS "+f),e.MaterialHelper.PrepareAttributesForMorphTargets(s,a,{NUM_MORPH_INFLUENCERS:f})),i&&(o.push("#define INSTANCES"),s.push("world0"),s.push("world1"),s.push("world2"),s.push("world3"));var d=o.join("\n");return this._cachedDefines!==d&&(this._cachedDefines=d,this._effectLayerMapGenerationEffect=this._scene.getEngine().createEffect("glowMapGeneration",s,["world","mBones","viewProjection","diffuseMatrix","color","emissiveMatrix","morphTargetInfluences"],["diffuseSampler","emissiveSampler"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:f})),this._effectLayerMapGenerationEffect.isReady()},t.prototype.render=function(){var e=this._mergeEffect;if(e.isReady()){for(var t=0;t-1&&this._scene.effectLayers.splice(i,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()},t.prototype.getClassName=function(){return"EffectLayer"},t.Parse=function(t,i,r){return e.Tools.Instantiate(t.customType).Parse(t,i,r)},n([e.serialize()],t.prototype,"name",void 0),n([e.serializeAsColor4()],t.prototype,"neutralColor",void 0),n([e.serialize()],t.prototype,"isEnabled",void 0),n([e.serializeAsCameraReference()],t.prototype,"camera",null),n([e.serialize()],t.prototype,"renderingGroupId",null),t})();e.EffectLayer=t})(r||(r={}));var r;!(function(e){e.AbstractScene.prototype.getHighlightLayerByName=function(e){for(var t=0;t-1&&this._tasks.splice(t,1)},i.prototype._decreaseWaitingTasksCount=function(i){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,i),this.onProgressObservable.notifyObservers(new r(this._waitingTasksCount,this._totalTasksCount,i))}catch(t){e.Tools.Error("Error running progress callbacks."),console.log(t)}if(0===this._waitingTasksCount){try{this.onFinish&&this.onFinish(this._tasks);for(var n=this._tasks.slice(),o=0,s=n;o-1&&this._tasks.splice(a,1)}}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(t){e.Tools.Error("Error running tasks-done callbacks."),console.log(t)}this._isLoading=!1,this._scene.getEngine().hideLoadingUI()}},i.prototype._runTask=function(e){var t=this,i=function(){try{t.onTaskSuccess&&t.onTaskSuccess(e),t.onTaskSuccessObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)}catch(e){r("Error executing task success callbacks",e)}},r=function(i,r){e._setErrorObject(i,r),t.onTaskError&&t.onTaskError(e),t.onTaskErrorObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)};e.run(this._scene,i,r)},i.prototype.reset=function(){return this._isLoading=!1,this._tasks=new Array,this},i.prototype.load=function(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(var e=0;e=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,i,s):n(t,i))||s);return o>3&&s&&Object.defineProperty(t,i,s),s},o=this&&this.__extends||(function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])};return function(t,i){function r(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}})();!(function(e){var t=(function(){function e(){this._defines={},this._currentRank=32,this._maxRank=-1}return e.prototype.unBindMesh=function(){this._mesh=null},e.prototype.addFallback=function(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)},e.prototype.addCPUSkinningFallback=function(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)},Object.defineProperty(e.prototype,"isMoreFallbacks",{get:function(){return this._currentRank<=this._maxRank},enumerable:!0,configurable:!0}),e.prototype.reduce=function(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0&&this._mesh.material){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;for(var i=this._mesh.getScene(),r=0;r-1?i:e.Engine.ShadersRepository+i,this._engine._loadFile(n+".vertex.fx",r)},t.prototype._loadFragmentShader=function(i,r){if(e.Tools.IsWindowObjectExist()&&i instanceof HTMLElement){return void r(e.Tools.GetDOMTextContent(i))}if("base64:"===i.substr(0,7)){return void r(window.atob(i.substr(7)))}if(t.ShadersStore[i+"PixelShader"])return void r(t.ShadersStore[i+"PixelShader"]);if(t.ShadersStore[i+"FragmentShader"])return void r(t.ShadersStore[i+"FragmentShader"]);var n;n="."===i[0]||"/"===i[0]||i.indexOf("http")>-1?i:e.Engine.ShadersRepository+i,this._engine._loadFile(n+".fragment.fx",r)},t.prototype._dumpShadersSource=function(t,i,r){var n=this._engine.webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"",o=n+(r?r+"\n":"");t=o+t,i=o+i;var s=2,a=/\n/gm,l="\n1\t"+t.replace(a,(function(){return"\n"+s+++"\t"}));s=2;var h="\n1\t"+i.replace(a,(function(){return"\n"+s+++"\t"}));this.name.vertexElement?(e.Tools.Error("Vertex shader: "+this.name.vertexElement+l),e.Tools.Error("Fragment shader: "+this.name.fragmentElement+h)):this.name.vertex?(e.Tools.Error("Vertex shader: "+this.name.vertex+l),e.Tools.Error("Fragment shader: "+this.name.fragment+h)):(e.Tools.Error("Vertex shader: "+this.name+l),e.Tools.Error("Fragment shader: "+this.name+h))},t.prototype._processShaderConversion=function(e,t,i){var r=this._processPrecision(e);if(1==this._engine.webGLVersion)return void i(r);if(-1!==r.indexOf("#version 3"))return void i(r.replace("#version 300 es",""));var n=-1!==r.search(/#extension.+GL_EXT_draw_buffers.+require/),o=/#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,s=r.replace(o,"");s=s.replace(/varying(?![\n\r])\s/g,t?"in ":"out "),s=s.replace(/attribute[ \t]/g,"in "),s=s.replace(/[ \t]attribute/g," in"),t&&(s=s.replace(/texture2DLodEXT\s*\(/g,"textureLod("),s=s.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),s=s.replace(/texture2D\s*\(/g,"texture("),s=s.replace(/textureCube\s*\(/g,"texture("),s=s.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),s=s.replace(/gl_FragColor/g,"glFragColor"),s=s.replace(/gl_FragData/g,"glFragData"),s=s.replace(/void\s+?main\s*\(/g,(n?"":"out vec4 glFragColor;\n")+"void main(")),i(s)},t.prototype._processIncludes=function(i,r){for(var n=this,o=/#include<(.+)>(\((.*)\))*(\[(.*)\])*/g,s=o.exec(i),a=new String(i);null!=s;){var l=s[1];if(-1!==l.indexOf("__decl__")&&(l=l.replace(/__decl__/,""),this._engine.supportsUniformBuffers&&(l=l.replace(/Vertex/,"Ubo"),l=l.replace(/Fragment/,"Ubo")),l+="Declaration"),!t.IncludesShadersStore[l]){var h=e.Engine.ShadersRepository+"ShadersInclude/"+l+".fx";return void this._engine._loadFile(h,(function(e){t.IncludesShadersStore[l]=e,n._processIncludes(a,r)}))}var c=t.IncludesShadersStore[l];if(s[2])for(var u=s[3].split(","),f=0;fr.x?r.x:n,n=nr.y?r.y:o,o=oi.x?e.x:i.x,e.y>i.y?e.y:i.y)},t.Transform=function(e,i){var r=t.Zero();return t.TransformToRef(e,i,r),r},t.TransformToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+t.m[13];i.x=r,i.y=n},t.PointInTriangle=function(e,t,i,r){var n=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),o=n<0?-1:1,s=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*o,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*o;return s>0&&a>0&&s+a<2*n*o},t.Distance=function(e,i){return Math.sqrt(t.DistanceSquared(e,i))},t.DistanceSquared=function(e,t){ +var i=e.x-t.x,r=e.y-t.y;return i*i+r*r},t.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},t.DistanceOfPointFromSegment=function(e,i,r){var n=t.DistanceSquared(i,r);if(0===n)return t.Distance(e,i);var o=r.subtract(i),s=Math.max(0,Math.min(1,t.Dot(e.subtract(i),o)/n)),a=i.add(o.multiplyByFloats(s,s));return t.Distance(e,a)},t})();e.Vector2=r;var n=(function(){function t(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this.x=e,this.y=t,this.z=i}return t.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+"}"},t.prototype.getClassName=function(){return"Vector3"},t.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0)},t.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},t.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,this},t.prototype.toQuaternion=function(){return e.Quaternion.RotationYawPitchRoll(this.x,this.y,this.z)},t.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this},t.prototype.add=function(e){return new t(this.x+e.x,this.y+e.y,this.z+e.z)},t.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,this},t.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this},t.prototype.subtract=function(e){return new t(this.x-e.x,this.y-e.y,this.z-e.z)},t.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,this},t.prototype.subtractFromFloats=function(e,i,r){return new t(this.x-e,this.y-i,this.z-r)},t.prototype.subtractFromFloatsToRef=function(e,t,i,r){return r.x=this.x-e,r.y=this.y-t,r.z=this.z-i,this},t.prototype.negate=function(){return new t(-this.x,-this.y,-this.z)},t.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this},t.prototype.scale=function(e){return new t(this.x*e,this.y*e,this.z*e)},t.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,this},t.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,this},t.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z},t.prototype.equalsWithEpsilon=function(t,i){return void 0===i&&(i=e.Epsilon),t&&e.Scalar.WithinEpsilon(this.x,t.x,i)&&e.Scalar.WithinEpsilon(this.y,t.y,i)&&e.Scalar.WithinEpsilon(this.z,t.z,i)},t.prototype.equalsToFloats=function(e,t,i){return this.x===e&&this.y===t&&this.z===i},t.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this},t.prototype.multiply=function(e){return new t(this.x*e.x,this.y*e.y,this.z*e.z)},t.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,this},t.prototype.multiplyByFloats=function(e,i,r){return new t(this.x*e,this.y*i,this.z*r)},t.prototype.divide=function(e){return new t(this.x/e.x,this.y/e.y,this.z/e.z)},t.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,this},t.prototype.divideInPlace=function(e){return this.divideToRef(e,this)},t.prototype.minimizeInPlace=function(e){return e.xthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),this},Object.defineProperty(t.prototype,"isNonUniform",{get:function(){var e=Math.abs(this.x),t=Math.abs(this.y);if(e!==t)return!0;var i=Math.abs(this.z);return e!==i||t!==i},enumerable:!0,configurable:!0}),t.prototype.floor=function(){return new t(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))},t.prototype.fract=function(){return new t(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z))},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},t.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},t.prototype.normalize=function(){var e=this.length();if(0===e||1===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this},t.prototype.normalizeToNew=function(){var e=new t(0,0,0);return this.normalizeToRef(e),e},t.prototype.normalizeToRef=function(e){var t=this.length();if(0===t||1===t)return e.set(this.x,this.y,this.z),e;var i=1/t;return this.scaleToRef(i,e),e},t.prototype.clone=function(){return new t(this.x,this.y,this.z)},t.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this},t.prototype.copyFromFloats=function(e,t,i){return this.x=e,this.y=t,this.z=i,this},t.prototype.set=function(e,t,i){return this.copyFromFloats(e,t,i)},t.GetClipFactor=function(e,i,r,n){var o=t.Dot(e,r)-n;return o/(o-(t.Dot(i,r)-n))},t.GetAngleBetweenVectors=function(e,i,r){var n=e.clone().normalize(),o=i.clone().normalize(),s=t.Dot(n,o),a=t.Cross(n,o);return t.Dot(a,r)>0?Math.acos(s):-Math.acos(s)},t.FromArray=function(e,i){return i||(i=0),new t(e[i],e[i+1],e[i+2])},t.FromFloatArray=function(e,i){return t.FromArray(e,i)},t.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2]},t.FromFloatArrayToRef=function(e,i,r){return t.FromArrayToRef(e,i,r)},t.FromFloatsToRef=function(e,t,i,r){r.x=e,r.y=t,r.z=i},t.Zero=function(){return new t(0,0,0)},t.One=function(){return new t(1,1,1)},t.Up=function(){return new t(0,1,0)},t.Down=function(){return new t(0,-1,0)},t.Forward=function(){return new t(0,0,1)},t.Right=function(){return new t(1,0,0)},t.Left=function(){return new t(-1,0,0)},t.TransformCoordinates=function(e,i){var r=t.Zero();return t.TransformCoordinatesToRef(e,i,r),r},t.TransformCoordinatesToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9]+t.m[13],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10]+t.m[14],s=e.x*t.m[3]+e.y*t.m[7]+e.z*t.m[11]+t.m[15];i.x=r/s,i.y=n/s,i.z=o/s},t.TransformCoordinatesFromFloatsToRef=function(e,t,i,r,n){var o=e*r.m[0]+t*r.m[4]+i*r.m[8]+r.m[12],s=e*r.m[1]+t*r.m[5]+i*r.m[9]+r.m[13],a=e*r.m[2]+t*r.m[6]+i*r.m[10]+r.m[14],l=e*r.m[3]+t*r.m[7]+i*r.m[11]+r.m[15];n.x=o/l,n.y=s/l,n.z=a/l},t.TransformNormal=function(e,i){var r=t.Zero();return t.TransformNormalToRef(e,i,r),r},t.TransformNormalToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10];i.x=r,i.y=n,i.z=o},t.TransformNormalFromFloatsToRef=function(e,t,i,r,n){n.x=e*r.m[0]+t*r.m[4]+i*r.m[8],n.y=e*r.m[1]+t*r.m[5]+i*r.m[9],n.z=e*r.m[2]+t*r.m[6]+i*r.m[10]},t.CatmullRom=function(e,i,r,n,o){var s=o*o,a=o*s;return new t(.5*(2*i.x+(-e.x+r.x)*o+(2*e.x-5*i.x+4*r.x-n.x)*s+(-e.x+3*i.x-3*r.x+n.x)*a),.5*(2*i.y+(-e.y+r.y)*o+(2*e.y-5*i.y+4*r.y-n.y)*s+(-e.y+3*i.y-3*r.y+n.y)*a),.5*(2*i.z+(-e.z+r.z)*o+(2*e.z-5*i.z+4*r.z-n.z)*s+(-e.z+3*i.z-3*r.z+n.z)*a))},t.Clamp=function(e,i,r){var n=e.x;n=n>r.x?r.x:n,n=nr.y?r.y:o,o=or.z?r.z:s,s=sthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this},t.prototype.floor=function(){return new t(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))},t.prototype.fract=function(){return new t(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},t.prototype.normalize=function(){var e=this.length();if(0===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toVector3=function(){return new n(this.x,this.y,this.z)},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},t.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},t.prototype.set=function(e,t,i,r){return this.copyFromFloats(e,t,i,r)},t.FromArray=function(e,i){return i||(i=0),new t(e[i],e[i+1],e[i+2],e[i+3])},t.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3]},t.FromFloatArrayToRef=function(e,i,r){t.FromArrayToRef(e,i,r)},t.FromFloatsToRef=function(e,t,i,r,n){n.x=e,n.y=t,n.z=i,n.w=r},t.Zero=function(){return new t(0,0,0,0)},t.One=function(){return new t(1,1,1,1)},t.Normalize=function(e){var i=t.Zero();return t.NormalizeToRef(e,i),i},t.NormalizeToRef=function(e,t){t.copyFrom(e),t.normalize()},t.Minimize=function(e,t){var i=e.clone();return i.minimizeInPlace(t),i},t.Maximize=function(e,t){var i=e.clone();return i.maximizeInPlace(t),i},t.Distance=function(e,i){return Math.sqrt(t.DistanceSquared(e,i))},t.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y,n=e.z-t.z,o=e.w-t.w;return i*i+r*r+n*n+o*o},t.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},t.TransformNormal=function(e,i){var r=t.Zero();return t.TransformNormalToRef(e,i,r),r},t.TransformNormalToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10];i.x=r,i.y=n,i.z=o,i.w=e.w},t.TransformNormalFromFloatsToRef=function(e,t,i,r,n,o){o.x=e*n.m[0]+t*n.m[4]+i*n.m[8],o.y=e*n.m[1]+t*n.m[5]+i*n.m[9],o.z=e*n.m[2]+t*n.m[6]+i*n.m[10],o.w=r},t})();e.Vector4=o;var s=(function(){function e(e,t){this.width=e,this.height=t}return e.prototype.toString=function(){return"{W: "+this.width+", H: "+this.height+"}"},e.prototype.getClassName=function(){return"Size"},e.prototype.getHashCode=function(){var e=this.width||0;return e=397*e^(this.height||0)},e.prototype.copyFrom=function(e){this.width=e.width,this.height=e.height},e.prototype.copyFromFloats=function(e,t){return this.width=e,this.height=t,this},e.prototype.set=function(e,t){return this.copyFromFloats(e,t)},e.prototype.multiplyByFloats=function(t,i){return new e(this.width*t,this.height*i)},e.prototype.clone=function(){return new e(this.width,this.height)},e.prototype.equals=function(e){return!!e&&(this.width===e.width&&this.height===e.height)},Object.defineProperty(e.prototype,"surface",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),e.Zero=function(){return new e(0,0)},e.prototype.add=function(t){return new e(this.width+t.width,this.height+t.height)},e.prototype.subtract=function(t){return new e(this.width-t.width,this.height-t.height)},e.Lerp=function(t,i,r){return new e(t.width+(i.width-t.width)*r,t.height+(i.height-t.height)*r)},e})();e.Size=s;var a=(function(){function e(e,t,i,r){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=1),this.x=e,this.y=t,this.z=i,this.w=r}return e.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},e.prototype.getClassName=function(){return"Quaternion"},e.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0),e=397*e^(this.w||0)},e.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},e.prototype.clone=function(){return new e(this.x,this.y,this.z,this.w)},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},e.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},e.prototype.set=function(e,t,i,r){return this.copyFromFloats(e,t,i,r)},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},e.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},e.prototype.scale=function(t){return new e(this.x*t,this.y*t,this.z*t,this.w*t)},e.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e,this},e.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,t.w+=this.w*e,this},e.prototype.multiply=function(t){var i=new e(0,0,0,1);return this.multiplyToRef(t,i),i},e.prototype.multiplyToRef=function(e,t){var i=this.x*e.w+this.y*e.z-this.z*e.y+this.w*e.x,r=-this.x*e.z+this.y*e.w+this.z*e.x+this.w*e.y,n=this.x*e.y-this.y*e.x+this.z*e.w+this.w*e.z,o=-this.x*e.x-this.y*e.y-this.z*e.z+this.w*e.w;return t.copyFromFloats(i,r,n,o),this},e.prototype.multiplyInPlace=function(e){return this.multiplyToRef(e,this),this},e.prototype.conjugateToRef=function(e){return e.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},e.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},e.prototype.conjugate=function(){return new e(-this.x,-this.y,-this.z,this.w)},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.prototype.normalize=function(){var e=1/this.length();return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.toEulerAngles=function(e){void 0===e&&(e="YZX");var t=n.Zero();return this.toEulerAnglesToRef(t,e),t},e.prototype.toEulerAnglesToRef=function(e,t){void 0===t&&(t="YZX");var i=this.z,r=this.x,n=this.y,o=this.w,s=o*o,a=i*i,l=r*r,h=n*n,c=n*i-r*o;return c<-.4999999?(e.y=2*Math.atan2(n,o),e.x=Math.PI/2,e.z=0):c>.4999999?(e.y=2*Math.atan2(n,o),e.x=-Math.PI/2,e.z=0):(e.z=Math.atan2(2*(r*n+i*o),-a-l+h+s),e.x=Math.asin(-2*(i*n-r*o)),e.y=Math.atan2(2*(i*r+n*o),a-l-h+s)),this},e.prototype.toRotationMatrix=function(e){var t=this.x*this.x,i=this.y*this.y,r=this.z*this.z,n=this.x*this.y,o=this.z*this.w,s=this.z*this.x,a=this.y*this.w,l=this.y*this.z,h=this.x*this.w;return e.m[0]=1-2*(i+r),e.m[1]=2*(n+o),e.m[2]=2*(s-a),e.m[3]=0,e.m[4]=2*(n-o),e.m[5]=1-2*(r+t),e.m[6]=2*(l+h),e.m[7]=0,e.m[8]=2*(s+a),e.m[9]=2*(l-h),e.m[10]=1-2*(i+t),e.m[11]=0,e.m[12]=0,e.m[13]=0,e.m[14]=0,e.m[15]=1,e._markAsUpdated(),this},e.prototype.fromRotationMatrix=function(t){return e.FromRotationMatrixToRef(t,this),this},e.FromRotationMatrix=function(t){var i=new e;return e.FromRotationMatrixToRef(t,i),i},e.FromRotationMatrixToRef=function(e,t){var i,r=e.m,n=r[0],o=r[4],s=r[8],a=r[1],l=r[5],h=r[9],c=r[2],u=r[6],f=r[10],d=n+l+f;d>0?(i=.5/Math.sqrt(d+1),t.w=.25/i,t.x=(u-h)*i,t.y=(s-c)*i,t.z=(a-o)*i):n>l&&n>f?(i=2*Math.sqrt(1+n-l-f),t.w=(u-h)/i,t.x=.25*i,t.y=(o+a)/i,t.z=(s+c)/i):l>f?(i=2*Math.sqrt(1+l-n-f),t.w=(s-c)/i,t.x=(o+a)/i,t.y=.25*i,t.z=(h+u)/i):(i=2*Math.sqrt(1+f-n-l),t.w=(a-o)/i,t.x=(s+c)/i,t.y=(h+u)/i,t.z=.25*i)},e.Dot=function(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w},e.AreClose=function(t,i){return e.Dot(t,i)>=0},e.Zero=function(){return new e(0,0,0,0)},e.Inverse=function(t){return new e(-t.x,-t.y,-t.z,t.w)},e.Identity=function(){return new e(0,0,0,1)},e.IsIdentity=function(e){return e&&0===e.x&&0===e.y&&0===e.z&&1===e.w},e.RotationAxis=function(t,i){return e.RotationAxisToRef(t,i,new e)},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(t/2);return e.normalize(),i.w=Math.cos(t/2),i.x=e.x*r,i.y=e.y*r,i.z=e.z*r,i},e.FromArray=function(t,i){return i||(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){var n=.5*i,o=.5*t,s=.5*e,a=Math.sin(n),l=Math.cos(n),h=Math.sin(o),c=Math.cos(o),u=Math.sin(s),f=Math.cos(s);r.x=f*h*l+u*c*a,r.y=u*c*l-f*h*a,r.z=f*c*a-u*h*l,r.w=f*c*l+u*h*a},e.RotationAlphaBetaGamma=function(t,i,r){var n=new e;return e.RotationAlphaBetaGammaToRef(t,i,r,n),n},e.RotationAlphaBetaGammaToRef=function(e,t,i,r){var n=.5*(i+e),o=.5*(i-e),s=.5*t;r.x=Math.cos(o)*Math.sin(s),r.y=Math.sin(o)*Math.sin(s),r.z=Math.sin(n)*Math.cos(s),r.w=Math.cos(n)*Math.cos(s)},e.RotationQuaternionFromAxis=function(t,i,r){var n=new e(0,0,0,0);return e.RotationQuaternionFromAxisToRef(t,i,r,n),n},e.RotationQuaternionFromAxisToRef=function(t,i,r,n){var o=E.Matrix[0];l.FromXYZAxesToRef(t.normalize(),i.normalize(),r.normalize(),o),e.FromRotationMatrixToRef(o,n)},e.Slerp=function(t,i,r){var n=e.Identity();return e.SlerpToRef(t,i,r,n),n},e.SlerpToRef=function(e,t,i,r){var n,o,s=e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w,a=!1;if(s<0&&(a=!0,s=-s),s>.999999)o=1-i,n=a?-i:i;else{var l=Math.acos(s),h=1/Math.sin(l);o=Math.sin((1-i)*l)*h,n=a?-Math.sin(i*l)*h:Math.sin(i*l)*h}r.x=o*e.x+n*t.x,r.y=o*e.y+n*t.y,r.z=o*e.z+n*t.z,r.w=o*e.w+n*t.w},e.Hermite=function(t,i,r,n,o){var s=o*o,a=o*s,l=2*a-3*s+1,h=-2*a+3*s,c=a-2*s+o,u=a-s;return new e(t.x*l+r.x*h+i.x*c+n.x*u,t.y*l+r.y*h+i.y*c+n.y*u,t.z*l+r.z*h+i.z*c+n.z*u,t.w*l+r.w*h+i.w*c+n.w*u)},e})();e.Quaternion=a;var l=(function(){function e(){this._isIdentity=!1,this._isIdentityDirty=!0,this.m=new Float32Array(16),this._markAsUpdated()}return e.prototype._markAsUpdated=function(){this.updateFlag=e._updateFlagSeed++,this._isIdentityDirty=!0},e.prototype.isIdentity=function(e){return void 0===e&&(e=!1),this._isIdentityDirty&&(this._isIdentityDirty=!1,1!==this.m[0]||1!==this.m[5]||1!==this.m[15]?this._isIdentity=!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?this._isIdentity=!1:this._isIdentity=!0,e||1===this.m[10]||(this._isIdentity=!1)),this._isIdentity},e.prototype.determinant=function(){var e=this.m[10]*this.m[15]-this.m[11]*this.m[14],t=this.m[9]*this.m[15]-this.m[11]*this.m[13],i=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],n=this.m[8]*this.m[14]-this.m[10]*this.m[12],o=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*e-this.m[6]*t+this.m[7]*i)-this.m[1]*(this.m[4]*e-this.m[6]*r+this.m[7]*n)+this.m[2]*(this.m[4]*t-this.m[5]*r+this.m[7]*o)-this.m[3]*(this.m[4]*i-this.m[5]*n+this.m[6]*o)},e.prototype.toArray=function(){return this.m},e.prototype.asArray=function(){return this.toArray()},e.prototype.invert=function(){return this.invertToRef(this),this},e.prototype.reset=function(){for(var e=0;e<16;e++)this.m[e]=0;return this._markAsUpdated(),this},e.prototype.add=function(t){var i=new e;return this.addToRef(t,i),i},e.prototype.addToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]=this.m[i]+e.m[i];return t._markAsUpdated(),this},e.prototype.addToSelf=function(e){for(var t=0;t<16;t++)this.m[t]+=e.m[t];return this._markAsUpdated(),this},e.prototype.invertToRef=function(e){var t=this.m[0],i=this.m[1],r=this.m[2],n=this.m[3],o=this.m[4],s=this.m[5],a=this.m[6],l=this.m[7],h=this.m[8],c=this.m[9],u=this.m[10],f=this.m[11],d=this.m[12],p=this.m[13],m=this.m[14],_=this.m[15],g=u*_-f*m,v=c*_-f*p,y=c*m-u*p,b=h*_-f*d,x=h*m-u*d,T=h*p-c*d,E=s*g-a*v+l*y,P=-(o*g-a*b+l*x),A=o*v-s*b+l*T,M=-(o*y-s*x+a*T),S=1/(t*E+i*P+r*A+n*M),R=a*_-l*m,C=s*_-l*p,O=s*m-a*p,D=o*_-l*d,I=o*m-a*d,w=o*p-s*d,L=a*f-l*u,F=s*f-l*c,B=s*u-a*c,V=o*f-l*h,N=o*u-a*h,U=o*c-s*h;return e.m[0]=E*S,e.m[4]=P*S,e.m[8]=A*S,e.m[12]=M*S,e.m[1]=-(i*g-r*v+n*y)*S,e.m[5]=(t*g-r*b+n*x)*S,e.m[9]=-(t*v-i*b+n*T)*S,e.m[13]=(t*y-i*x+r*T)*S,e.m[2]=(i*R-r*C+n*O)*S,e.m[6]=-(t*R-r*D+n*I)*S,e.m[10]=(t*C-i*D+n*w)*S,e.m[14]=-(t*O-i*I+r*w)*S,e.m[3]=-(i*L-r*F+n*B)*S,e.m[7]=(t*L-r*V+n*N)*S,e.m[11]=-(t*F-i*V+n*U)*S,e.m[15]=(t*B-i*N+r*U)*S,e._markAsUpdated(),this},e.prototype.setTranslationFromFloats=function(e,t,i){return this.m[12]=e,this.m[13]=t,this.m[14]=i,this._markAsUpdated(),this},e.prototype.setTranslation=function(e){return this.m[12]=e.x,this.m[13]=e.y,this.m[14]=e.z,this._markAsUpdated(),this},e.prototype.getTranslation=function(){return new n(this.m[12],this.m[13],this.m[14])},e.prototype.getTranslationToRef=function(e){return e.x=this.m[12],e.y=this.m[13],e.z=this.m[14],this},e.prototype.removeRotationAndScaling=function(){return this.setRowFromFloats(0,1,0,0,0),this.setRowFromFloats(1,0,1,0,0),this.setRowFromFloats(2,0,0,1,0),this},e.prototype.multiply=function(t){var i=new e;return this.multiplyToRef(t,i),i},e.prototype.copyFrom=function(e){for(var t=0;t<16;t++)this.m[t]=e.m[t];return this._markAsUpdated(),this},e.prototype.copyToArray=function(e,t){void 0===t&&(t=0);for(var i=0;i<16;i++)e[t+i]=this.m[i];return this},e.prototype.multiplyToRef=function(e,t){return this.multiplyToArray(e,t.m,0),t._markAsUpdated(),this},e.prototype.multiplyToArray=function(e,t,i){var r=this.m[0],n=this.m[1],o=this.m[2],s=this.m[3],a=this.m[4],l=this.m[5],h=this.m[6],c=this.m[7],u=this.m[8],f=this.m[9],d=this.m[10],p=this.m[11],m=this.m[12],_=this.m[13],g=this.m[14],v=this.m[15],y=e.m[0],b=e.m[1],x=e.m[2],T=e.m[3],E=e.m[4],P=e.m[5],A=e.m[6],M=e.m[7],S=e.m[8],R=e.m[9],C=e.m[10],O=e.m[11],D=e.m[12],I=e.m[13],w=e.m[14],L=e.m[15];return t[i]=r*y+n*E+o*S+s*D,t[i+1]=r*b+n*P+o*R+s*I,t[i+2]=r*x+n*A+o*C+s*w,t[i+3]=r*T+n*M+o*O+s*L,t[i+4]=a*y+l*E+h*S+c*D,t[i+5]=a*b+l*P+h*R+c*I,t[i+6]=a*x+l*A+h*C+c*w,t[i+7]=a*T+l*M+h*O+c*L,t[i+8]=u*y+f*E+d*S+p*D,t[i+9]=u*b+f*P+d*R+p*I,t[i+10]=u*x+f*A+d*C+p*w,t[i+11]=u*T+f*M+d*O+p*L,t[i+12]=m*y+_*E+g*S+v*D,t[i+13]=m*b+_*P+g*R+v*I,t[i+14]=m*x+_*A+g*C+v*w,t[i+15]=m*T+_*M+g*O+v*L,this},e.prototype.equals=function(e){return e&&this.m[0]===e.m[0]&&this.m[1]===e.m[1]&&this.m[2]===e.m[2]&&this.m[3]===e.m[3]&&this.m[4]===e.m[4]&&this.m[5]===e.m[5]&&this.m[6]===e.m[6]&&this.m[7]===e.m[7]&&this.m[8]===e.m[8]&&this.m[9]===e.m[9]&&this.m[10]===e.m[10]&&this.m[11]===e.m[11]&&this.m[12]===e.m[12]&&this.m[13]===e.m[13]&&this.m[14]===e.m[14]&&this.m[15]===e.m[15]},e.prototype.clone=function(){return e.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},e.prototype.getClassName=function(){return"Matrix"},e.prototype.getHashCode=function(){for(var e=this.m[0]||0,t=1;t<16;t++)e=397*e^(this.m[t]||0);return e},e.prototype.decompose=function(t,i,r){return r&&(r.x=this.m[12],r.y=this.m[13],r.z=this.m[14]),t=t||E.Vector3[0],t.x=Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),this.determinant()<=0&&(t.y*=-1),0===t.x||0===t.y||0===t.z?(i&&(i.x=0,i.y=0,i.z=0,i.w=1),!1):(i&&(e.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,E.Matrix[0]),a.FromRotationMatrixToRef(E.Matrix[0],i)),!0)},e.prototype.getRow=function(e){if(e<0||e>3)return null;var t=4*e;return new o(this.m[t+0],this.m[t+1],this.m[t+2],this.m[t+3])},e.prototype.setRow=function(e,t){if(e<0||e>3)return this;var i=4*e;return this.m[i+0]=t.x,this.m[i+1]=t.y,this.m[i+2]=t.z,this.m[i+3]=t.w,this._markAsUpdated(),this},e.prototype.transpose=function(){return e.Transpose(this)},e.prototype.transposeToRef=function(t){return e.TransposeToRef(this,t),this},e.prototype.setRowFromFloats=function(e,t,i,r,n){if(e<0||e>3)return this;var o=4*e;return this.m[o+0]=t,this.m[o+1]=i,this.m[o+2]=r,this.m[o+3]=n,this._markAsUpdated(),this},e.prototype.scale=function(t){var i=new e;return this.scaleToRef(t,i),i},e.prototype.scaleToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]=this.m[i]*e;return t._markAsUpdated(),this},e.prototype.scaleAndAddToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]+=this.m[i]*e;return t._markAsUpdated(),this},e.prototype.toNormalMatrix=function(t){this.invertToRef(t),t.transpose();var i=t.m;e.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,t)},e.prototype.getRotationMatrix=function(){var t=e.Identity();return this.getRotationMatrixToRef(t),t},e.prototype.getRotationMatrixToRef=function(t){var i=this.m,r=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),n=Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),o=Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);return this.determinant()<=0&&(n*=-1),0===r||0===n||0===o?e.IdentityToRef(t):e.FromValuesToRef(i[0]/r,i[1]/r,i[2]/r,0,i[4]/n,i[5]/n,i[6]/n,0,i[8]/o,i[9]/o,i[10]/o,0,0,0,0,1,t),this},e.FromArray=function(t,i){var r=new e;return i||(i=0),e.FromArrayToRef(t,i,r),r},e.FromArrayToRef=function(e,t,i){for(var r=0;r<16;r++)i.m[r]=e[r+t];i._markAsUpdated()},e.FromFloat32ArrayToRefScaled=function(e,t,i,r){for(var n=0;n<16;n++)r.m[n]=e[n+t]*i;r._markAsUpdated()},e.FromValuesToRef=function(e,t,i,r,n,o,s,a,l,h,c,u,f,d,p,m,_){_.m[0]=e,_.m[1]=t,_.m[2]=i,_.m[3]=r,_.m[4]=n,_.m[5]=o,_.m[6]=s,_.m[7]=a,_.m[8]=l,_.m[9]=h,_.m[10]=c,_.m[11]=u,_.m[12]=f,_.m[13]=d,_.m[14]=p,_.m[15]=m,_._markAsUpdated()},Object.defineProperty(e,"IdentityReadOnly",{get:function(){return e._identityReadOnly},enumerable:!0,configurable:!0}),e.FromValues=function(t,i,r,n,o,s,a,l,h,c,u,f,d,p,m,_){var g=new e;return g.m[0]=t,g.m[1]=i,g.m[2]=r,g.m[3]=n,g.m[4]=o,g.m[5]=s,g.m[6]=a,g.m[7]=l,g.m[8]=h,g.m[9]=c,g.m[10]=u,g.m[11]=f,g.m[12]=d,g.m[13]=p,g.m[14]=m,g.m[15]=_,g},e.Compose=function(t,i,r){var n=e.Identity();return e.ComposeToRef(t,i,r,n),n},e.ComposeToRef=function(t,i,r,n){e.FromValuesToRef(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1,E.Matrix[1]),i.toRotationMatrix(E.Matrix[0]),E.Matrix[1].multiplyToRef(E.Matrix[0],n),n.setTranslation(r)},e.Identity=function(){return e.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},e.IdentityToRef=function(t){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},e.Zero=function(){return e.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},e.RotationX=function(t){var i=new e;return e.RotationXToRef(t,i),i},e.Invert=function(t){var i=new e;return t.invertToRef(i),i},e.RotationXToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[0]=1,t.m[15]=1,t.m[5]=r,t.m[10]=r,t.m[9]=-i,t.m[6]=i,t.m[1]=0,t.m[2]=0,t.m[3]=0,t.m[4]=0,t.m[7]=0,t.m[8]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t._markAsUpdated()},e.RotationY=function(t){var i=new e;return e.RotationYToRef(t,i),i},e.RotationYToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[5]=1,t.m[15]=1,t.m[0]=r,t.m[2]=-i,t.m[8]=i,t.m[10]=r,t.m[1]=0,t.m[3]=0,t.m[4]=0,t.m[6]=0,t.m[7]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t._markAsUpdated()},e.RotationZ=function(t){var i=new e;return e.RotationZToRef(t,i),i},e.RotationZToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[10]=1,t.m[15]=1,t.m[0]=r,t.m[1]=i,t.m[4]=-i,t.m[5]=r,t.m[2]=0,t.m[3]=0,t.m[6]=0,t.m[7]=0,t.m[8]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t._markAsUpdated()},e.RotationAxis=function(t,i){var r=e.Zero();return e.RotationAxisToRef(t,i,r),r},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(-t),n=Math.cos(-t),o=1-n;e.normalize(),i.m[0]=e.x*e.x*o+n,i.m[1]=e.x*e.y*o-e.z*r,i.m[2]=e.x*e.z*o+e.y*r,i.m[3]=0, +i.m[4]=e.y*e.x*o+e.z*r,i.m[5]=e.y*e.y*o+n,i.m[6]=e.y*e.z*o-e.x*r,i.m[7]=0,i.m[8]=e.z*e.x*o-e.y*r,i.m[9]=e.z*e.y*o+e.x*r,i.m[10]=e.z*e.z*o+n,i.m[11]=0,i.m[15]=1,i._markAsUpdated()},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){a.RotationYawPitchRollToRef(e,t,i,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},e.Scaling=function(t,i,r){var n=e.Zero();return e.ScalingToRef(t,i,r,n),n},e.ScalingToRef=function(e,t,i,r){r.m[0]=e,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=t,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=i,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1,r._markAsUpdated()},e.Translation=function(t,i,r){var n=e.Identity();return e.TranslationToRef(t,i,r,n),n},e.TranslationToRef=function(t,i,r,n){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,r,1,n)},e.Lerp=function(t,i,r){var n=e.Zero();return e.LerpToRef(t,i,r,n),n},e.LerpToRef=function(e,t,i,r){for(var n=0;n<16;n++)r.m[n]=e.m[n]*(1-i)+t.m[n]*i;r._markAsUpdated()},e.DecomposeLerp=function(t,i,r){var n=e.Zero();return e.DecomposeLerpToRef(t,i,r,n),n},e.DecomposeLerpToRef=function(t,i,r,o){var s=E.Vector3[0],l=E.Quaternion[0],h=E.Vector3[1];t.decompose(s,l,h);var c=E.Vector3[2],u=E.Quaternion[1],f=E.Vector3[3];i.decompose(c,u,f);var d=E.Vector3[4];n.LerpToRef(s,c,r,d);var p=E.Quaternion[2];a.SlerpToRef(l,u,r,p);var m=E.Vector3[5];n.LerpToRef(h,f,r,m),e.ComposeToRef(d,p,m,o)},e.LookAtLH=function(t,i,r){var n=e.Zero();return e.LookAtLHToRef(t,i,r,n),n},e.LookAtLHToRef=function(t,i,r,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),n.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),n.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-n.Dot(this._xAxis,t),a=-n.Dot(this._yAxis,t),l=-n.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,l,1,o)},e.LookAtRH=function(t,i,r){var n=e.Zero();return e.LookAtRHToRef(t,i,r,n),n},e.LookAtRHToRef=function(t,i,r,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),n.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),n.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-n.Dot(this._xAxis,t),a=-n.Dot(this._yAxis,t),l=-n.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,l,1,o)},e.OrthoLH=function(t,i,r,n){var o=e.Zero();return e.OrthoLHToRef(t,i,r,n,o),o},e.OrthoLHToRef=function(t,i,r,n,o){var s=r,a=n,l=2/t,h=2/i,c=2/(a-s),u=-(a+s)/(a-s);e.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,0,0,u,1,o)},e.OrthoOffCenterLH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterLHToRef=function(t,i,r,n,o,s,a){var l=o,h=s,c=2/(i-t),u=2/(n-r),f=2/(h-l),d=-(h+l)/(h-l),p=(t+i)/(t-i),m=(n+r)/(r-n);e.FromValuesToRef(c,0,0,0,0,u,0,0,0,0,f,0,p,m,d,1,a)},e.OrthoOffCenterRH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterRHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterRHToRef=function(t,i,r,n,o,s,a){e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a.m[10]*=-1},e.PerspectiveLH=function(t,i,r,n){var o=e.Zero(),s=r,a=n,l=2*s/t,h=2*s/i,c=(a+s)/(a-s),u=-2*a*s/(a-s);return e.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,1,0,0,u,0,o),o},e.PerspectiveFovLH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovLHToRef(t,i,r,n,o),o},e.PerspectiveFovLHToRef=function(t,i,r,n,o,s){void 0===s&&(s=!0);var a=r,l=n,h=1/Math.tan(.5*t),c=s?h/i:h,u=s?h:h*i,f=(l+a)/(l-a),d=-2*l*a/(l-a);e.FromValuesToRef(c,0,0,0,0,u,0,0,0,0,f,1,0,0,d,0,o)},e.PerspectiveFovRH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovRHToRef(t,i,r,n,o),o},e.PerspectiveFovRHToRef=function(t,i,r,n,o,s){void 0===s&&(s=!0);var a=r,l=n,h=1/Math.tan(.5*t),c=s?h/i:h,u=s?h:h*i,f=-(l+a)/(l-a),d=-2*l*a/(l-a);e.FromValuesToRef(c,0,0,0,0,u,0,0,0,0,f,-1,0,0,d,0,o)},e.PerspectiveFovWebVRToRef=function(e,t,i,r,n){void 0===n&&(n=!1);var o=n?-1:1,s=Math.tan(e.upDegrees*Math.PI/180),a=Math.tan(e.downDegrees*Math.PI/180),l=Math.tan(e.leftDegrees*Math.PI/180),h=Math.tan(e.rightDegrees*Math.PI/180),c=2/(l+h),u=2/(s+a);r.m[0]=c,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=u,r.m[6]=r.m[7]=0,r.m[8]=(l-h)*c*.5,r.m[9]=-(s-a)*u*.5,r.m[10]=-i/(t-i),r.m[11]=1*o,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=-2*i*t/(i-t),r._markAsUpdated()},e.GetFinalMatrix=function(t,i,r,n,o,s){var a=t.width,l=t.height,h=t.x,c=t.y,u=e.FromValues(a/2,0,0,0,0,-l/2,0,0,0,0,s-o,0,h+a/2,l/2+c,o,1);return i.multiply(r).multiply(n).multiply(u)},e.GetAsMatrix2x2=function(e){return new Float32Array([e.m[0],e.m[1],e.m[4],e.m[5]])},e.GetAsMatrix3x3=function(e){return new Float32Array([e.m[0],e.m[1],e.m[2],e.m[4],e.m[5],e.m[6],e.m[8],e.m[9],e.m[10]])},e.Transpose=function(t){var i=new e;return e.TransposeToRef(t,i),i},e.TransposeToRef=function(e,t){t.m[0]=e.m[0],t.m[1]=e.m[4],t.m[2]=e.m[8],t.m[3]=e.m[12],t.m[4]=e.m[1],t.m[5]=e.m[5],t.m[6]=e.m[9],t.m[7]=e.m[13],t.m[8]=e.m[2],t.m[9]=e.m[6],t.m[10]=e.m[10],t.m[11]=e.m[14],t.m[12]=e.m[3],t.m[13]=e.m[7],t.m[14]=e.m[11],t.m[15]=e.m[15]},e.Reflection=function(t){var i=new e;return e.ReflectionToRef(t,i),i},e.ReflectionToRef=function(e,t){e.normalize();var i=e.normal.x,r=e.normal.y,n=e.normal.z,o=-2*i,s=-2*r,a=-2*n;t.m[0]=o*i+1,t.m[1]=s*i,t.m[2]=a*i,t.m[3]=0,t.m[4]=o*r,t.m[5]=s*r+1,t.m[6]=a*r,t.m[7]=0,t.m[8]=o*n,t.m[9]=s*n,t.m[10]=a*n+1,t.m[11]=0,t.m[12]=o*e.d,t.m[13]=s*e.d,t.m[14]=a*e.d,t.m[15]=1,t._markAsUpdated()},e.FromXYZAxesToRef=function(e,t,i,r){r.m[0]=e.x,r.m[1]=e.y,r.m[2]=e.z,r.m[3]=0,r.m[4]=t.x,r.m[5]=t.y,r.m[6]=t.z,r.m[7]=0,r.m[8]=i.x,r.m[9]=i.y,r.m[10]=i.z,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1,r._markAsUpdated()},e.FromQuaternionToRef=function(e,t){var i=e.x*e.x,r=e.y*e.y,n=e.z*e.z,o=e.x*e.y,s=e.z*e.w,a=e.z*e.x,l=e.y*e.w,h=e.y*e.z,c=e.x*e.w;t.m[0]=1-2*(r+n),t.m[1]=2*(o+s),t.m[2]=2*(a-l),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+c),t.m[7]=0,t.m[8]=2*(a+l),t.m[9]=2*(h-c),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,t._markAsUpdated()},e._tempQuaternion=new a,e._xAxis=n.Zero(),e._yAxis=n.Zero(),e._zAxis=n.Zero(),e._updateFlagSeed=0,e._identityReadOnly=e.Identity(),e})();e.Matrix=l;var h=(function(){function e(e,t,i,r){this.normal=new n(e,t,i),this.d=r}return e.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},e.prototype.clone=function(){return new e(this.normal.x,this.normal.y,this.normal.z,this.d)},e.prototype.getClassName=function(){return"Plane"},e.prototype.getHashCode=function(){var e=this.normal.getHashCode();return e=397*e^(this.d||0)},e.prototype.normalize=function(){var e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this},e.prototype.transform=function(t){var i=l.Transpose(t),r=this.normal.x,n=this.normal.y,o=this.normal.z,s=this.d;return new e(r*i.m[0]+n*i.m[1]+o*i.m[2]+s*i.m[3],r*i.m[4]+n*i.m[5]+o*i.m[6]+s*i.m[7],r*i.m[8]+n*i.m[9]+o*i.m[10]+s*i.m[11],r*i.m[12]+n*i.m[13]+o*i.m[14]+s*i.m[15])},e.prototype.dotCoordinate=function(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d},e.prototype.copyFromPoints=function(e,t,i){var r,n=t.x-e.x,o=t.y-e.y,s=t.z-e.z,a=i.x-e.x,l=i.y-e.y,h=i.z-e.z,c=o*h-s*l,u=s*a-n*h,f=n*l-o*a,d=Math.sqrt(c*c+u*u+f*f);return r=0!==d?1/d:0,this.normal.x=c*r,this.normal.y=u*r,this.normal.z=f*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this},e.prototype.isFrontFacingTo=function(e,t){return n.Dot(this.normal,e)<=t},e.prototype.signedDistanceTo=function(e){return n.Dot(e,this.normal)+this.d},e.FromArray=function(t){return new e(t[0],t[1],t[2],t[3])},e.FromPoints=function(t,i,r){var n=new e(0,0,0,0);return n.copyFromPoints(t,i,r),n},e.FromPositionAndNormal=function(t,i){var r=new e(0,0,0,0);return i.normalize(),r.normal=i,r.d=-(i.x*t.x+i.y*t.y+i.z*t.z),r},e.SignedDistanceToPlaneFromPositionAndNormal=function(e,t,i){var r=-(t.x*e.x+t.y*e.y+t.z*e.z);return n.Dot(i,t)+r},e})();e.Plane=h;var c=(function(){function e(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}return e.prototype.toGlobal=function(t,i){if(t.getRenderWidth){var r=t;return this.toGlobal(r.getRenderWidth(),r.getRenderHeight())}var n=t;return new e(this.x*n,this.y*i,this.width*n,this.height*i)},e.prototype.clone=function(){return new e(this.x,this.y,this.width,this.height)},e})();e.Viewport=c;var u=(function(){function e(){}return e.GetPlanes=function(t){for(var i=[],r=0;r<6;r++)i.push(new h(0,0,0,0));return e.GetPlanesToRef(t,i),i},e.GetNearPlaneToRef=function(e,t){t.normal.x=e.m[3]+e.m[2],t.normal.y=e.m[7]+e.m[6],t.normal.z=e.m[11]+e.m[10],t.d=e.m[15]+e.m[14],t.normalize()},e.GetFarPlaneToRef=function(e,t){t.normal.x=e.m[3]-e.m[2],t.normal.y=e.m[7]-e.m[6],t.normal.z=e.m[11]-e.m[10],t.d=e.m[15]-e.m[14],t.normalize()},e.GetLeftPlaneToRef=function(e,t){t.normal.x=e.m[3]+e.m[0],t.normal.y=e.m[7]+e.m[4],t.normal.z=e.m[11]+e.m[8],t.d=e.m[15]+e.m[12],t.normalize()},e.GetRightPlaneToRef=function(e,t){t.normal.x=e.m[3]-e.m[0],t.normal.y=e.m[7]-e.m[4],t.normal.z=e.m[11]-e.m[8],t.d=e.m[15]-e.m[12],t.normalize()},e.GetTopPlaneToRef=function(e,t){t.normal.x=e.m[3]-e.m[1],t.normal.y=e.m[7]-e.m[5],t.normal.z=e.m[11]-e.m[9],t.d=e.m[15]-e.m[13],t.normalize()},e.GetBottomPlaneToRef=function(e,t){t.normal.x=e.m[3]+e.m[1],t.normal.y=e.m[7]+e.m[5],t.normal.z=e.m[11]+e.m[9],t.d=e.m[15]+e.m[13],t.normalize()},e.GetPlanesToRef=function(t,i){e.GetNearPlaneToRef(t,i[0]),e.GetFarPlaneToRef(t,i[1]),e.GetLeftPlaneToRef(t,i[2]),e.GetRightPlaneToRef(t,i[3]),e.GetTopPlaneToRef(t,i[4]),e.GetBottomPlaneToRef(t,i[5])},e})();e.Frustum=u;!(function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"})(e.Space||(e.Space={}));var f=(function(){function e(){}return e.X=new n(1,0,0),e.Y=new n(0,1,0),e.Z=new n(0,0,1),e})();e.Axis=f;var d=(function(){function e(){}return e.interpolate=function(e,t,i,r,n){for(var o=1-3*r+3*t,s=3*r-6*t,a=3*t,l=e,h=0;h<5;h++){var c=l*l;l-=(o*(c*l)+s*c+a*l-e)*(1/(3*o*c+2*s*l+a)),l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*n+Math.pow(l,3)},e})();e.BezierCurve=d;var p;!(function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"})(p=e.Orientation||(e.Orientation={}));var m=(function(){function e(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}return e.prototype.degrees=function(){return 180*this._radians/Math.PI},e.prototype.radians=function(){return this._radians},e.BetweenTwoPoints=function(t,i){var r=i.subtract(t);return new e(Math.atan2(r.y,r.x))},e.FromRadians=function(t){return new e(t)},e.FromDegrees=function(t){return new e(t*Math.PI/180)},e})();e.Angle=m;var _=(function(){function e(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;var n=Math.pow(t.x,2)+Math.pow(t.y,2),o=(Math.pow(e.x,2)+Math.pow(e.y,2)-n)/2,s=(n-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new r((o*(t.y-i.y)-s*(e.y-t.y))/a,((e.x-t.x)*s-(t.x-i.x)*o)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=m.BetweenTwoPoints(this.centerPoint,this.startPoint);var l=this.startAngle.degrees(),h=m.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),c=m.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();h-l>180&&(h-=360),h-l<-180&&(h+=360),c-h>180&&(c-=360),c-h<-180&&(c+=360),this.orientation=h-l<0?p.CW:p.CCW,this.angle=m.FromDegrees(this.orientation===p.CW?l-c:c-l)}return e})();e.Arc2=_;var g=(function(){function e(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(e,t))}return e.prototype.addLineTo=function(e,t){if(this.closed)return this;var i=new r(e,t),n=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(n).length(),this},e.prototype.addArcTo=function(e,t,i,n,o){if(void 0===o&&(o=36),this.closed)return this;var s=this._points[this._points.length-1],a=new r(e,t),l=new r(i,n),h=new _(s,a,l),c=h.angle.radians()/o;h.orientation===p.CW&&(c*=-1);for(var u=h.startAngle.radians()+c,f=0;f1)return r.Zero();for(var t=e*this.length(),i=0,n=0;n=i&&t<=h){var c=l.normalize(),u=t-i;return new r(s.x+c.x*u,s.y+c.y*u)}i=h}return r.Zero()},e.StartingAt=function(t,i){return new e(t,i)},e})();e.Path2=g;var v=(function(){function t(e,t,i){void 0===t&&(t=null),this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;rt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i},t.prototype._normalVector=function(t,i,r){var o,s=i.length();if(0===s&&(s=1),void 0===r||null===r){var a;a=e.Scalar.WithinEpsilon(Math.abs(i.y)/s,1,e.Epsilon)?e.Scalar.WithinEpsilon(Math.abs(i.x)/s,1,e.Epsilon)?e.Scalar.WithinEpsilon(Math.abs(i.z)/s,1,e.Epsilon)?n.Zero():new n(0,0,1):new n(1,0,0):new n(0,-1,0),o=n.Cross(i,a)}else o=n.Cross(i,r),n.CrossToRef(o,i,o);return o.normalize(),o},t})();e.Path3D=v;var y=(function(){function e(e){this._length=0,this._points=e,this._length=this._computeLength(e)}return e.CreateQuadraticBezier=function(t,i,r,o){o=o>2?o:3;for(var s=new Array,a=function(e,t,i,r){return(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r},l=0;l<=o;l++)s.push(new n(a(l/o,t.x,i.x,r.x),a(l/o,t.y,i.y,r.y),a(l/o,t.z,i.z,r.z)));return new e(s)},e.CreateCubicBezier=function(t,i,r,o,s){s=s>3?s:4;for(var a=new Array,l=function(e,t,i,r,n){return(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*n},h=0;h<=s;h++)a.push(new n(l(h/s,t.x,i.x,r.x,o.x),l(h/s,t.y,i.y,r.y,o.y),l(h/s,t.z,i.z,r.z,o.z)));return new e(a)},e.CreateHermiteSpline=function(t,i,r,o,s){for(var a=new Array,l=1/s,h=0;h<=s;h++)a.push(n.Hermite(t,i,r,o,h*l));return new e(a)},e.CreateCatmullRomSpline=function(t,i,r){var o=new Array,s=1/i,a=0;if(r){for(var l=t.length,h=0;h0?1:-1},e.Clamp=function(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1),Math.min(i,Math.max(t,e))},e.Log2=function(e){return Math.log(e)*Math.LOG2E},e.Repeat=function(e,t){return e-Math.floor(e/t)*t},e.Normalize=function(e,t,i){return(e-t)/(i-t)},e.Denormalize=function(e,t,i){return e*(i-t)+t},e.DeltaAngle=function(t,i){var r=e.Repeat(i-t,360);return r>180&&(r-=360),r},e.PingPong=function(t,i){var r=e.Repeat(t,2*i);return i-Math.abs(r-i)},e.SmoothStep=function(t,i,r){var n=e.Clamp(r);return n=-2*n*n*n+3*n*n,i*n+t*(1-n)},e.MoveTowards=function(t,i,r){return Math.abs(i-t)<=r?i:t+e.Sign(i-t)*r},e.MoveTowardsAngle=function(t,i,r){var n=e.DeltaAngle(t,i),o=0;return-r180&&(n-=360),t+n*e.Clamp(r)},e.InverseLerp=function(t,i,r){return t!=i?e.Clamp((r-t)/(i-t)):0},e.Hermite=function(e,t,i,r,n){var o=n*n,s=n*o;return e*(2*s-3*o+1)+i*(-2*s+3*o)+t*(s-2*o+n)+r*(s-o)},e.RandomRange=function(e,t){return e===t?e:Math.random()*(t-e)+e},e.RangeToPercent=function(e,t,i){return(e-t)/(i-t)},e.PercentToRange=function(e,t,i){return(i-t)*e+t},e.NormalizeRadians=function(t){return t-=e.TwoPi*Math.floor((t+Math.PI)/e.TwoPi)},e.TwoPi=2*Math.PI,e})();e.Scalar=t})(r||(r={}));var r;!(function(e){function t(e){var t=e.getClassName();return v[t]||(v[t]={}),v[t]}function i(e){var t=e.getClassName();if(y[t])return y[t];y[t]={};for(var i=y[t],r=e,n=t;n;){var o=v[n];for(var s in o)i[s]=o[s];var a=void 0,l=!1;do{if(a=Object.getPrototypeOf(r),!a.getClassName){l=!0;break}if(a.getClassName()!==n)break;r=a}while(a);if(l)break;n=a.getClassName(),r=a}return i}function r(e,i){return function(r,n){var o=t(r);o[n]||(o[n]={type:e,sourceName:i})}}function n(e,t){return void 0===t&&(t=null),function(i,r){var n=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[n]},set:function(t){this[n]!==t&&(this[n]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}function o(e,t){return void 0===t&&(t=null),n(e,t)}function s(e){return r(0,e)}function a(e){return r(1,e)}function l(e){return r(2,e)}function h(e){return r(3,e)}function c(e){return r(4,e)}function u(e){return r(5,e)}function f(e){return r(6,e)}function d(e){return r(7,e)}function p(e){return r(8,e)}function m(e){return r(9,e)}function _(e){return r(10,e)}function g(e){return r(11,e)}var v={},y={},b=function(t,r,n){var o=t();e.Tags&&e.Tags.AddTagsTo(o,r.tags);var s=i(o);for(var a in s){var l=s[a],h=r[a],c=l.type;if(void 0!==h&&null!==h)switch(c){case 0:case 6:case 11:o[a]=h;break;case 1:o[a]=n||h.isRenderTarget?h:h.clone();break;case 2:case 3:case 4:case 5:case 7:case 10:o[a]=n?h:h.clone()}}return o};e.expandToProperty=o,e.serialize=s,e.serializeAsTexture=a,e.serializeAsColor3=l,e.serializeAsFresnelParameters=h,e.serializeAsVector2=c,e.serializeAsVector3=u,e.serializeAsMeshReference=f,e.serializeAsColorCurves=d,e.serializeAsColor4=p,e.serializeAsImageProcessingConfiguration=m,e.serializeAsQuaternion=_,e.serializeAsCameraReference=g;var x=(function(){function t(){}return t.Serialize=function(t,r){r||(r={}),e.Tags&&(r.tags=e.Tags.GetTags(t));var n=i(t);for(var o in n){var s=n[o],a=s.sourceName||o,l=s.type,h=t[o];if(void 0!==h&&null!==h)switch(l){case 0:r[a]=h;break;case 1:r[a]=h.serialize();break;case 2:r[a]=h.asArray();break;case 3:r[a]=h.serialize();break;case 4:case 5:r[a]=h.asArray();break;case 6:r[a]=h.id;break;case 7:r[a]=h.serialize();break;case 8:r[a]=h.asArray();break;case 9:r[a]=h.serialize();break;case 10:r[a]=h.asArray();break;case 11:r[a]=h.id}}return r},t.Parse=function(t,r,n,o){void 0===o&&(o=null);var s=t();o||(o=""),e.Tags&&e.Tags.AddTagsTo(s,r.tags);var a=i(s);for(var l in a){var h=a[l],c=r[h.sourceName||l],u=h.type;if(void 0!==c&&null!==c){var f=s;switch(u){case 0:f[l]=c;break;case 1:n&&(f[l]=e.Texture.Parse(c,n,o));break;case 2:f[l]=e.Color3.FromArray(c);break;case 3:f[l]=e.FresnelParameters.Parse(c);break;case 4:f[l]=e.Vector2.FromArray(c);break;case 5:f[l]=e.Vector3.FromArray(c);break;case 6:n&&(f[l]=n.getLastMeshByID(c));break;case 7:f[l]=e.ColorCurves.Parse(c);break;case 8:f[l]=e.Color4.FromArray(c);break;case 9:f[l]=e.ImageProcessingConfiguration.Parse(c);break;case 10:f[l]=e.Quaternion.FromArray(c);break;case 11:n&&(f[l]=n.getCameraByID(c))}}}return s},t.Clone=function(e,t){return b(e,t,!1)},t.Instanciate=function(e,t){return b(e,t,!0)},t})();e.SerializationHelper=x})(r||(r={}));var r;!(function(e){var t=(function(){function e(){var e=this;this.promise=new Promise(function(t,i){e._resolve=t,e._reject=i})}return Object.defineProperty(e.prototype,"resolve",{get:function(){return this._resolve},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"reject",{get:function(){return this._reject},enumerable:!0,configurable:!0}),e})();e.Deferred=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i,r){void 0===t&&(t=!1),this.initalize(e,t,i,r)}return e.prototype.initalize=function(e,t,i,r){return void 0===t&&(t=!1),this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this},e})();e.EventState=t;var i=(function(){function e(e,t,i){void 0===i&&(i=null),this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1}return e})();e.Observer=i;var r=(function(){function e(){}return e.prototype.dispose=function(){if(this._observers&&this._observables)for(var e=0;e0},r.prototype.clear=function(){this._observers=new Array,this._onObserverAdded=null},r.prototype.clone=function(){var e=new r;return e._observers=this._observers.slice(0),e},r.prototype.hasSpecificMask=function(e){void 0===e&&(e=-1);for(var t=0,i=this._observers;tthis.data.length&&(this.data.length*=2)},e.prototype.forEach=function(e){for(var t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t=this.length?-1:t},e.prototype.contains=function(e){return-1!==this.data.indexOf(e)},e._GlobalId=0,e})();e.SmartArray=t;var i=(function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._duplicateId=0,t}return o(t,e),t.prototype.push=function(t){e.prototype.push.call(this,t),t.__smartArrayFlags||(t.__smartArrayFlags={}),t.__smartArrayFlags[this._id]=this._duplicateId},t.prototype.pushNoDuplicate=function(e){return(!e.__smartArrayFlags||e.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(e),!0)},t.prototype.reset=function(){e.prototype.reset.call(this),this._duplicateId++},t.prototype.concatWithNoDuplicate=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t=e||-1!==i.indexOf("file:")?-1:Math.pow(2,n)*t}},e})();e.RetryStrategy=s;var a,l=function(t,i){return t?t instanceof e.Mesh?null:t instanceof e.SubMesh?t.clone(i):t.clone?t.clone():null:null},h=(function(){function t(){}return t.FetchToRef=function(e,t,i,r,n,o){var s=Math.abs(e)*i%i|0,a=Math.abs(t)*r%r|0,l=4*(s+a*i);o.r=n[l]/255,o.g=n[l+1]/255,o.b=n[l+2]/255,o.a=n[l+3]/255},t.Mix=function(e,t,i){return e*(1-i)+t*i},t.Instantiate=function(e){if(t.RegisteredExternalClasses&&t.RegisteredExternalClasses[e])return t.RegisteredExternalClasses[e];for(var i=e.split("."),r=window||this,n=0,o=i.length;n>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e},t.FloorPOT=function(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)},t.NearestPOT=function(e){var i=t.CeilingPOT(e),r=t.FloorPOT(e);return i-e>e-r?r:i},t.GetExponentOfTwo=function(i,r,n){void 0===n&&(n=e.Engine.SCALEMODE_NEAREST);var o;switch(n){case e.Engine.SCALEMODE_FLOOR:o=t.FloorPOT(i);break;case e.Engine.SCALEMODE_NEAREST:o=t.NearestPOT(i);break;case e.Engine.SCALEMODE_CEILING:default:o=t.CeilingPOT(i)}return Math.min(o,r)},t.GetFilename=function(e){var t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)},t.GetFolderPath=function(e,t){void 0===t&&(t=!1);var i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)},t.GetDOMTextContent=function(e){for(var t="",i=e.firstChild;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t},t.ToDegrees=function(e){return 180*e/Math.PI},t.ToRadians=function(e){return e*Math.PI/180},t.EncodeArrayBufferTobase64=function(e){for(var t,i,r,n,o,s,a,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",c=0,u=new Uint8Array(e);c>2,o=(3&t)<<4|i>>4,s=(15&i)<<2|r>>6,a=63&r,isNaN(i)?s=a=64:isNaN(r)&&(a=64),h+=l.charAt(n)+l.charAt(o)+l.charAt(s)+l.charAt(a);return"data:image/png;base64,"+h}, +t.ExtractMinAndMaxIndexed=function(t,i,r,n,o){void 0===o&&(o=null);for(var s=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new e.Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),l=r;l=(r?t.length/2:t.length))return null;if(r){var n=t;return new e.Vector2(n[2*i+0],n[2*i+1])}return t[i]}},t.ExtractMinAndMaxVector2=function(t,i){void 0===i&&(i=null);for(var r=new e.Vector2(Number.MAX_VALUE,Number.MAX_VALUE),n=new e.Vector2(-Number.MAX_VALUE,-Number.MAX_VALUE),o=0,s=t(o++);s;)r=e.Vector2.Minimize(s,r),n=e.Vector2.Maximize(s,n),s=t(o++);return i&&(r.x-=r.x*i.x+i.y,r.y-=r.y*i.x+i.y,n.x+=n.x*i.x+i.y,n.y+=n.y*i.x+i.y),{minimum:r,maximum:n}},t.MakeArray=function(e,t){return!0===t||void 0!==e&&null!=e?Array.isArray(e)?e:[e]:null},t.GetPointerPrefix=function(){var e="pointer";return!t.IsWindowObjectExist()||window.PointerEvent||navigator.pointerEnabled||(e="mouse"),e},t.QueueNewFrame=function(e,i){return t.IsWindowObjectExist()?(i||(i=window),i.requestAnimationFrame?i.requestAnimationFrame(e):i.msRequestAnimationFrame?i.msRequestAnimationFrame(e):i.webkitRequestAnimationFrame?i.webkitRequestAnimationFrame(e):i.mozRequestAnimationFrame?i.mozRequestAnimationFrame(e):i.oRequestAnimationFrame?i.oRequestAnimationFrame(e):window.setTimeout(e,16)):setTimeout(e,16)},t.RequestFullscreen=function(e){var t=e.requestFullscreen||e.msRequestFullscreen||e.webkitRequestFullscreen||e.mozRequestFullScreen;t&&t.call(e)},t.ExitFullscreen=function(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitCancelFullScreen?document.webkitCancelFullScreen():document.msCancelFullScreen&&document.msCancelFullScreen()},t.SetCorsBehavior=function(e,i){if((!e||0!==e.indexOf("data:"))&&t.CorsBehavior)if("string"==typeof t.CorsBehavior||t.CorsBehavior instanceof String)i.crossOrigin=t.CorsBehavior;else{var r=t.CorsBehavior(e);r&&(i.crossOrigin=r)}},t.CleanUrl=function(e){return e=e.replace(/#/gm,"%23")},t.LoadImage=function(i,r,n,o){var s,a=!1;i instanceof ArrayBuffer?(s=URL.createObjectURL(new Blob([i])),a=!0):i instanceof Blob?(s=URL.createObjectURL(i),a=!0):(s=t.CleanUrl(i),s=t.PreprocessUrl(i));var l=new Image;t.SetCorsBehavior(s,l);var h=function(){a&&l.src&&URL.revokeObjectURL(l.src),l.removeEventListener("load",h),l.removeEventListener("error",c),r(l)},c=function(e){a&&l.src&&URL.revokeObjectURL(l.src),l.removeEventListener("load",h),l.removeEventListener("error",c),t.Error("Error while trying to load image: "+i),n&&n("Error while trying to load image: "+i,e)};l.addEventListener("load",h),l.addEventListener("error",c);var u=function(){l.src=s},f=function(){o&&o.loadImageFromDB(s,l)};if("data:"!==s.substr(0,5)&&o&&o.enableTexturesOffline&&e.Database.IsUASupportingBlobStorage)o.openAsync(f,u);else{if(-1!==s.indexOf("file:")){var d=decodeURIComponent(s.substring(5).toLowerCase());if(e.FilesInput.FilesToLoad[d]){try{var p;try{p=URL.createObjectURL(e.FilesInput.FilesToLoad[d],{oneTimeOnly:!0})}catch(t){p=URL.createObjectURL(e.FilesInput.FilesToLoad[d])}l.src=p,a=!0}catch(e){l.src=""}return l}}u()}return l},t.LoadFile=function(i,r,o,s,a,l){if(i=t.CleanUrl(i),i=t.PreprocessUrl(i),-1!==i.indexOf("file:")){var h=decodeURIComponent(i.substring(5).toLowerCase());if(e.FilesInput.FilesToLoad[h])return t.ReadFile(e.FilesInput.FilesToLoad[h],r,o,a)}var c=t.BaseUrl+i,u=!1,f={onCompleteObservable:new e.Observable,abort:function(){return u=!0}},d=function(){var e=new XMLHttpRequest,i=null;f.abort=function(){u=!0,e.readyState!==(XMLHttpRequest.DONE||4)&&e.abort(),null!==i&&(clearTimeout(i),i=null)};var s=function(h){e.open("GET",c,!0),a&&(e.responseType="arraybuffer"),o&&e.addEventListener("progress",o);var d=function(){e.removeEventListener("loadend",d),f.onCompleteObservable.notifyObservers(f),f.onCompleteObservable.clear()};e.addEventListener("loadend",d);var p=function(){if(!u&&e.readyState===(XMLHttpRequest.DONE||4)){if(e.removeEventListener("readystatechange",p),e.status>=200&&e.status<300||!t.IsWindowObjectExist()&&0===e.status)return void r(a?e.response:e.responseText,e.responseURL);var o=t.DefaultRetryStrategy;if(o){var f=o(c,e,h);if(-1!==f)return e.removeEventListener("loadend",d),e=new XMLHttpRequest,void(i=setTimeout((function(){return s(h+1)}),f))}var m=new n("Error status: "+e.status+" "+e.statusText+" - Unable to load "+c,e);if(!l)throw m;l(e,m)}};e.addEventListener("readystatechange",p),e.send()};s(0)};if(s&&s.enableSceneOffline){var p=function(e){e&&e.status>400?l&&l(e):u||d()},m=function(){u||s&&s.loadFileFromDB(i,(function(e){u||r(e),f.onCompleteObservable.notifyObservers(f)}),o?function(e){u||o(e)}:void 0,p,a)};s.openAsync(m,p)}else d();return f},t.LoadScript=function(e,t,i){var r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.type="text/javascript",n.src=e,n.onload=function(){t&&t()},n.onerror=function(t){i&&i("Unable to load script '"+e+"'",t)},r.appendChild(n)},t.ReadFileAsDataURL=function(t,i,r){var n=new FileReader,o={onCompleteObservable:new e.Observable,abort:function(){return n.abort()}};return n.onloadend=function(e){o.onCompleteObservable.notifyObservers(o)},n.onload=function(e){i(e.target.result)},n.onprogress=r,n.readAsDataURL(t),o},t.ReadFile=function(i,r,n,o){var s=new FileReader,a={onCompleteObservable:new e.Observable,abort:function(){return s.abort()}};return s.onloadend=function(e){return a.onCompleteObservable.notifyObservers(a)},s.onerror=function(e){t.Log("Error while reading file: "+i.name),r(JSON.stringify({autoClear:!0,clearColor:[1,0,0],ambientColor:[0,0,0],gravity:[0,-9.807,0],meshes:[],cameras:[],lights:[]}))},s.onload=function(e){r(e.target.result)},n&&(s.onprogress=n),o?s.readAsArrayBuffer(i):s.readAsText(i),a},t.FileAsURL=function(e){var t=new Blob([e]);return(window.URL||window.webkitURL).createObjectURL(t)},t.Format=function(e,t){return void 0===t&&(t=2),e.toFixed(t)},t.CheckExtends=function(e,t,i){e.xi.x&&(i.x=e.x),e.y>i.y&&(i.y=e.y),e.z>i.z&&(i.z=e.z)},t.DeepCopy=function(e,t,i,r){for(var n in e)if(("_"!==n[0]||r&&-1!==r.indexOf(n))&&(!i||-1===i.indexOf(n))){var o=e[n],s=typeof o;if("function"!==s)try{if("object"===s)if(o instanceof Array){if(t[n]=[],o.length>0)if("object"==typeof o[0])for(var a=0;al&&(f=l,u=f*c);var d=Math.max(0,s-u)/2,p=Math.max(0,l-f)/2,m=e.getRenderingCanvas();h&&m&&h.drawImage(m,d,p,u,f),t.EncodeScreenshotCanvasData(n,o)},t.CreateScreenshotUsingRenderTarget=function(i,r,n,o,s,a,l,h){void 0===s&&(s="image/png"),void 0===a&&(a=1),void 0===l&&(l=!1);var c,u;if(n.precision)c=Math.round(i.getRenderWidth()*n.precision),u=Math.round(c/i.getAspectRatio(r)),n={width:c,height:u};else if(n.width&&n.height)c=n.width,u=n.height;else if(n.width&&!n.height)c=n.width,u=Math.round(c/i.getAspectRatio(r)),n={width:c,height:u};else if(n.height&&!n.width)u=n.height,c=Math.round(u*i.getAspectRatio(r)),n={width:c,height:u};else{if(isNaN(n))return void t.Error("Invalid 'size' parameter !");u=n,c=n}var f=r.getScene(),d=null;f.activeCamera!==r&&(d=f.activeCamera,f.activeCamera=r);var p=new e.RenderTargetTexture("screenShot",n,f,!1,!1,e.Engine.TEXTURETYPE_UNSIGNED_INT,!1,e.Texture.NEAREST_SAMPLINGMODE);p.renderList=null,p.samples=a,l&&p.addPostProcess(new e.FxaaPostProcess("antialiasing",1,f.activeCamera)),p.onAfterRenderObservable.add((function(){t.DumpFramebuffer(c,u,i,o,s,h)})),f.incrementRenderId(),f.resetCachedMaterial(),p.render(!0),p.dispose(),d&&(f.activeCamera=d),r.getProjectionMatrix(!0)},t.ValidateXHRData=function(t,i){void 0===i&&(i=7);try{if(1&i){if(t.responseText&&t.responseText.length>0)return!0;if(1===i)return!1}if(2&i){var r=e.TGATools.GetTGAHeader(t.response);if(r.width&&r.height&&r.width>0&&r.height>0)return!0;if(2===i)return!1}if(4&i){var n=new Uint8Array(t.response,0,3);return 68===n[0]&&68===n[1]&&83===n[2]}}catch(e){}return!1},t.RandomId=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))},t.IsBase64=function(e){return!(e.length<5)&&"data:"===e.substr(0,5)},t.DecodeBase64=function(e){for(var t=atob(e.split(",")[1]),i=t.length,r=new Uint8Array(new ArrayBuffer(i)),n=0;n
";t._AddLogEntry(r)},t._WarnDisabled=function(e){},t._WarnEnabled=function(e){var i=t._FormatMessage(e);console.warn("BJS - "+i);var r="
"+i+"

";t._AddLogEntry(r)},t._ErrorDisabled=function(e){},t._ErrorEnabled=function(e){t.errorsCount++;var i=t._FormatMessage(e);console.error("BJS - "+i);var r="
"+i+"

";t._AddLogEntry(r)},Object.defineProperty(t,"LogCache",{get:function(){return t._LogCache},enumerable:!0,configurable:!0}),t.ClearLogCache=function(){t._LogCache="",t.errorsCount=0},Object.defineProperty(t,"LogLevels",{set:function(e){(e&t.MessageLogLevel)===t.MessageLogLevel?t.Log=t._LogEnabled:t.Log=t._LogDisabled,(e&t.WarningLogLevel)===t.WarningLogLevel?t.Warn=t._WarnEnabled:t.Warn=t._WarnDisabled,(e&t.ErrorLogLevel)===t.ErrorLogLevel?t.Error=t._ErrorEnabled:t.Error=t._ErrorDisabled},enumerable:!0,configurable:!0}),t.IsWindowObjectExist=function(){return"undefined"!=typeof window},Object.defineProperty(t,"PerformanceNoneLogLevel",{get:function(){return t._PerformanceNoneLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceUserMarkLogLevel",{get:function(){return t._PerformanceUserMarkLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceConsoleLogLevel",{get:function(){return t._PerformanceConsoleLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceLogLevel",{set:function(e){return(e&t.PerformanceUserMarkLogLevel)===t.PerformanceUserMarkLogLevel?(t.StartPerformanceCounter=t._StartUserMark,void(t.EndPerformanceCounter=t._EndUserMark)):(e&t.PerformanceConsoleLogLevel)===t.PerformanceConsoleLogLevel?(t.StartPerformanceCounter=t._StartPerformanceConsole,void(t.EndPerformanceCounter=t._EndPerformanceConsole)):(t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,void(t.EndPerformanceCounter=t._EndPerformanceCounterDisabled))},enumerable:!0,configurable:!0}),t._StartPerformanceCounterDisabled=function(e,t){},t._EndPerformanceCounterDisabled=function(e,t){},t._StartUserMark=function(e,i){if(void 0===i&&(i=!0),!t._performance){if(!t.IsWindowObjectExist())return;t._performance=window.performance}i&&t._performance.mark&&t._performance.mark(e+"-Begin")},t._EndUserMark=function(e,i){void 0===i&&(i=!0),i&&t._performance.mark&&(t._performance.mark(e+"-End"),t._performance.measure(e,e+"-Begin",e+"-End"))},t._StartPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._StartUserMark(e,i),console.time&&console.time(e))},t._EndPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._EndUserMark(e,i),console.time&&console.timeEnd(e))},Object.defineProperty(t,"Now",{get:function(){return t.IsWindowObjectExist()&&window.performance&&window.performance.now?window.performance.now():Date.now()},enumerable:!0,configurable:!0}),t.GetClassName=function(e,t){void 0===t&&(t=!1);var i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__}i||(i=typeof e)}return i},t.First=function(e,t){for(var i=0,r=e;i=e.length)return null;var r=e.charCodeAt?e.charCodeAt(i):e[i];return r&&r.getHashCode&&(r=r.getHashCode()),"string"==typeof r?t.hashCodeFromStream(t.arrayOrStringFeeder(r)):r}},t.hashCodeFromStream=function(e){for(var t=0,i=0,r=e(i++);null!=r;)t=(t<<5)-t+r,t|=0,r=e(i++);return t},t.DelayAsync=function(e){return new Promise(function(t){setTimeout((function(){t()}),e)})},t.GetCurrentGradient=function(e,t,i){for(var r=0;r=n.gradient&&e<=o.gradient){i(n,o,(e-n.gradient)/(o.gradient-n.gradient))}}},t.BaseUrl="",t.DefaultRetryStrategy=s.ExponentialBackoff(),t.CorsBehavior="anonymous",t.UseFallbackTexture=!0,t.RegisteredExternalClasses={},t.fallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z",t._tmpFloatArray=new Float32Array(1),t.PreprocessUrl=function(e){return e},t._NoneLogLevel=0,t._MessageLogLevel=1,t._WarningLogLevel=2,t._ErrorLogLevel=4,t._LogCache="",t.errorsCount=0,t.Log=t._LogEnabled,t.Warn=t._WarnEnabled,t.Error=t._ErrorEnabled,t._PerformanceNoneLogLevel=0,t._PerformanceUserMarkLogLevel=1,t._PerformanceConsoleLogLevel=2,t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,t.EndPerformanceCounter=t._EndPerformanceCounterDisabled,t})();e.Tools=h;var c=(function(){function e(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}return Object.defineProperty(e.prototype,"min",{get:function(){return this._min},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"max",{get:function(){return this._max},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"average",{get:function(){return this._average},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lastSecAverage",{get:function(){return this._lastSecAverage},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"current",{get:function(){return this._current},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"total",{get:function(){return this._totalAccumulated},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"count",{get:function(){return this._totalValueCount},enumerable:!0,configurable:!0}),e.prototype.fetchNewFrame=function(){this._totalValueCount++,this._current=0,this._lastSecValueCount++},e.prototype.addCount=function(t,i){e.Enabled&&(this._current+=t,i&&this._fetchResult())},e.prototype.beginMonitoring=function(){e.Enabled&&(this._startMonitoringTime=h.Now)},e.prototype.endMonitoring=function(t){if(void 0===t&&(t=!0),e.Enabled){t&&this.fetchNewFrame();var i=h.Now;this._current=i-this._startMonitoringTime,t&&this._fetchResult()}},e.prototype._fetchResult=function(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;var e=h.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)},e.Enabled=!0,e})();e.PerfCounter=c,e.className=t;var u=(function(){function e(e,t,i,r){void 0===r&&(r=0),this.iterations=e,this._fn=t,this._successCallback=i,this.index=r-1,this._done=!1}return e.prototype.executeNext=function(){this._done||(this.index+1=t)break;if(r(s),o&&o()){e.breakLoop();break}}e.executeNext()}),s)}),n)},e})();e.AsyncLoop=u})(r||(r={}));var r;!(function(e){var t;!(function(e){e[e.Pending=0]="Pending",e[e.Fulfilled=1]="Fulfilled",e[e.Rejected=2]="Rejected"})(t||(t={}));var i=(function(){function e(){this.count=0,this.target=0,this.results=[]}return e})(),r=(function(){function r(e){var i=this;if(this._state=t.Pending,this._children=new Array,this._rejectWasConsumed=!1,e)try{e((function(e){i._resolve(e)}),(function(e){i._reject(e)}))}catch(e){this._reject(e)}}return Object.defineProperty(r.prototype,"_result",{get:function(){return this._resultValue},set:function(e){this._resultValue=e,this._parent&&void 0===this._parent._result&&(this._parent._result=e)},enumerable:!0,configurable:!0}),r.prototype.catch=function(e){return this.then(void 0,e)},r.prototype.then=function(i,n){var o=this,s=new r;return s._onFulfilled=i,s._onRejected=n,this._children.push(s),s._parent=this,this._state!==t.Pending&&e.Tools.SetImmediate((function(){if(o._state===t.Fulfilled||o._rejectWasConsumed){var e=s._resolve(o._result);if(void 0!==e&&null!==e)if(void 0!==e._state){var i=e;s._children.push(i),i._parent=s,s=i}else s._result=e}else s._reject(o._reason)})),s},r.prototype._moveChildren=function(e){var i,r=this;if((i=this._children).push.apply(i,e.splice(0,e.length)),this._children.forEach((function(e){e._parent=r})),this._state===t.Fulfilled)for(var n=0,o=this._children;n-1){if(f.capture&&f.captureConstraint){var m=f.capture,_=f.captureConstraint,g=new RegExp(m),v=g.exec(h);if(v&&v.length>0){var y=parseInt(v[v.length-1]);if(y>=_)continue}}for(var b=0,x=p;b1&&!this.disableUniformBuffers},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"needPOTTextures",{get:function(){return this._webGLVersion<2||this.forcePOTTextures},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"doNotHandleContextLost",{get:function(){return this._doNotHandleContextLost},set:function(e){this._doNotHandleContextLost=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"performanceMonitor",{get:function(){return this._performanceMonitor},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"texturesSupported",{get:function(){return this._texturesSupported},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"currentViewport",{get:function(){return this._cachedViewport},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"emptyTexture",{get:function(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,i.TEXTUREFORMAT_RGBA,!1,!1,i.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"emptyTexture3D",{get:function(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,i.TEXTUREFORMAT_RGBA,!1,!1,i.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture3D},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"emptyCubeTexture",{get:function(){if(!this._emptyCubeTexture){var e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,i.TEXTUREFORMAT_RGBA,i.TEXTURETYPE_UNSIGNED_INT,!1,!1,i.TEXTURE_NEAREST_SAMPLINGMODE)}return this._emptyCubeTexture},enumerable:!0,configurable:!0}),i.prototype._rebuildInternalTextures=function(){for(var e=this._internalTexturesCache.slice(),t=0,i=e;t1||null!==this._gl.getExtension("OES_standard_derivatives"),this._caps.astc=this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),this._caps.s3tc=this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),this._caps.pvrtc=this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),this._caps.etc1=this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),this._caps.etc2=this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),this._caps.textureAnisotropicFilterExtension=this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.uintIndices=this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),this._caps.fragmentDepthSupported=this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),this._caps.highPrecisionShaderSupported=!0,this._caps.timerQuery=this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)>0),this._caps.colorBufferFloat=this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float"),this._caps.textureFloat=!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloat=!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._webGLVersion>1&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._caps.textureLOD=!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),this._webGLVersion>1)this._caps.drawBuffersExtension=!0;else{var t=this._gl.getExtension("WEBGL_draw_buffers");if(null!==t){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=t.drawBuffersWEBGL.bind(t),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(var i=0;i<16;i++)this._gl["COLOR_ATTACHMENT"+i+"_WEBGL"]=t["COLOR_ATTACHMENT"+i+"_WEBGL"]}else this._caps.drawBuffersExtension=!1}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{var r=this._gl.getExtension("WEBGL_depth_texture");null!=r&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=r.UNSIGNED_INT_24_8_WEBGL)}if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{var n=this._gl.getExtension("OES_vertex_array_object");null!=n?(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=n.createVertexArrayOES.bind(n),this._gl.bindVertexArray=n.bindVertexArrayOES.bind(n),this._gl.deleteVertexArray=n.deleteVertexArrayOES.bind(n)):this._caps.vertexArrayObject=!1}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{var s=this._gl.getExtension("ANGLE_instanced_arrays");null!=s?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=s.drawArraysInstancedANGLE.bind(s),this._gl.drawElementsInstanced=s.drawElementsInstancedANGLE.bind(s),this._gl.vertexAttribDivisor=s.vertexAttribDivisorANGLE.bind(s)):this._caps.instancedArrays=!1}if(this._caps.astc&&this.texturesSupported.push("-astc.ktx"),this._caps.s3tc&&this.texturesSupported.push("-dxt.ktx"),this._caps.pvrtc&&this.texturesSupported.push("-pvrtc.ktx"),this._caps.etc2&&this.texturesSupported.push("-etc2.ktx"),this._caps.etc1&&this.texturesSupported.push("-etc1.ktx"),this._gl.getShaderPrecisionFormat){var a=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);a&&(this._caps.highPrecisionShaderSupported=0!==a.precision)}this.setDepthBuffer(!0),this.setDepthFunctionToLessOrEqual(),this.setDepthWrite(!0),this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(var l=0;l=0&&this._activeRenderLoops.splice(t,1)},i.prototype._renderLoop=function(){if(!this._contextWasLost){var t=!0;if(!this.renderEvenInBackground&&this._windowIsBackground&&(t=!1),t){this.beginFrame();for(var i=0;i0){var r=null;this._vrDisplay&&this._vrDisplay.isPresenting&&(r=this._vrDisplay),this._frameHandler=e.Tools.QueueNewFrame(this._bindedRenderFunction,r)}else this._renderingQueueLaunched=!1},i.prototype.runRenderLoop=function(t){-1===this._activeRenderLoops.indexOf(t)&&(this._activeRenderLoops.push(t),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._bindedRenderFunction=this._renderLoop.bind(this),this._frameHandler=e.Tools.QueueNewFrame(this._bindedRenderFunction)))},i.prototype.switchFullscreen=function(t){this.isFullscreen?e.Tools.ExitFullscreen():(this._pointerLockRequested=t,this._renderingCanvas&&e.Tools.RequestFullscreen(this._renderingCanvas))},i.prototype.clear=function(e,t,i,r){void 0===r&&(r=!1),this.applyStates();var n=0;t&&e&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),n|=this._gl.COLOR_BUFFER_BIT),i&&(this._gl.clearDepth(1),n|=this._gl.DEPTH_BUFFER_BIT),r&&(this._gl.clearStencil(0),n|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(n)},i.prototype.scissorClear=function(e,t,i,r,n){var o=this._gl,s=o.getParameter(o.SCISSOR_TEST),a=o.getParameter(o.SCISSOR_BOX);o.enable(o.SCISSOR_TEST),o.scissor(e,t,i,r),this.clear(n,!0,!0,!0),o.scissor(a[0],a[1],a[2],a[3]),!0===s?o.enable(o.SCISSOR_TEST):o.disable(o.SCISSOR_TEST)},i.prototype._viewport=function(e,t,i,r){e===this._viewportCached.x&&t===this._viewportCached.y&&i===this._viewportCached.z&&r===this._viewportCached.w||(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r,this._gl.viewport(e,t,i,r))},i.prototype.setViewport=function(e,t,i){var r=t||this.getRenderWidth(),n=i||this.getRenderHeight(),o=e.x||0,s=e.y||0;this._cachedViewport=e,this._viewport(o*r,s*n,r*e.width,n*e.height)},i.prototype.setDirectViewport=function(e,t,i,r){var n=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),n},i.prototype.beginFrame=function(){this.onBeginFrameObservable.notifyObservers(this),this._measureFps()},i.prototype.endFrame=function(){this._badOS&&this.flushFramebuffer(),this._vrDisplay&&this._vrDisplay.isPresenting&&this._vrDisplay.submitFrame(),this.onEndFrameObservable.notifyObservers(this)},i.prototype.resize=function(){if(!this._vrDisplay||!this._vrDisplay.isPresenting){var e=this._renderingCanvas?this._renderingCanvas.clientWidth:window.innerWidth,t=this._renderingCanvas?this._renderingCanvas.clientHeight:window.innerHeight;this.setSize(e/this._hardwareScalingLevel,t/this._hardwareScalingLevel)}},i.prototype.setSize=function(e,t){if(this._renderingCanvas&&(this._renderingCanvas.width!==e||this._renderingCanvas.height!==t)){this._renderingCanvas.width=e,this._renderingCanvas.height=t;for(var i=0;i1?"COLOR_ATTACHMENT"+o:"COLOR_ATTACHMENT"+o+"_WEBGL"],r.readBuffer(n[o]),r.drawBuffers(n),r.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(var o=0;o1?"COLOR_ATTACHMENT"+o:"COLOR_ATTACHMENT"+o+"_WEBGL"];r.drawBuffers(n)}for(var o=0;o65535){n=!0;break}r=n?new Uint32Array(e):new Uint16Array(e)}else r=new Uint16Array(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),i.references=1,i.is32Bits=n,i},i.prototype.bindArrayBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(e,this._gl.ARRAY_BUFFER)},i.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e)},i.prototype.bindUniformBufferBase=function(e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e)},i.prototype.bindUniformBlock=function(e,t,i){var r=this._gl.getUniformBlockIndex(e,t);this._gl.uniformBlockBinding(e,r,i)},i.prototype.bindIndexBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)},i.prototype.bindBuffer=function(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e),this._currentBoundBuffer[t]=e)},i.prototype.updateArrayBuffer=function(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)},i.prototype._vertexAttribPointer=function(e,t,i,r,n,o,s){var a=this._currentBufferPointers[t],l=!1;a.active?(a.buffer!==e&&(a.buffer=e,l=!0),a.size!==i&&(a.size=i,l=!0),a.type!==r&&(a.type=r,l=!0),a.normalized!==n&&(a.normalized=n,l=!0),a.stride!==o&&(a.stride=o,l=!0),a.offset!==s&&(a.offset=s,l=!0)):(l=!0,a.active=!0,a.index=t,a.size=i,a.type=r,a.normalized=n,a.stride=o,a.offset=s,a.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),this._gl.vertexAttribPointer(t,i,r,n,o,s))},i.prototype._bindIndexBufferWithCache=function(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)},i.prototype._bindVertexBuffersAttributes=function(e,t){var i=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var r=0;r=0){var o=e[i[r]];if(!o)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);var s=o.getBuffer();s&&(this._vertexAttribPointer(s,n,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(s))))}}},i.prototype.recordVertexArrayObject=function(e,t,i){var r=this._gl.createVertexArray();return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r},i.prototype.bindVertexArrayObject=function(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)},i.prototype.bindBuffersDirectly=function(e,t,i,r,n){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==n){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=n;var o=n.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var s=0,a=0;a=0&&(this._gl.enableVertexAttribArray(l),this._vertexAttribArraysEnabled[l]=!0,this._vertexAttribPointer(e,l,i[a],this._gl.FLOAT,!1,r,s)),s+=4*i[a]}}this._bindIndexBufferWithCache(t)},i.prototype._unbindVertexArrayObject=function(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))},i.prototype.bindBuffers=function(e,t,i){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i)),this._bindIndexBufferWithCache(t)},i.prototype.unbindInstanceAttributes=function(){for(var e,t=0,i=this._currentInstanceLocations.length;t1?"#version 300 es\n#define WEBGL2 \n":"",s=this._compileShader(e,"vertex",i,o),a=this._compileShader(t,"fragment",i,o),l=this._createShaderProgram(s,a,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),l},i.prototype._createShaderProgram=function(e,t,i,r){void 0===r&&(r=null);var n=i.createProgram();if(!n)throw new Error("Unable to create program");if(i.attachShader(n,e),i.attachShader(n,t),this.webGLVersion>1&&r){var o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(n,r),n.transformFeedback=o}if(i.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),!i.getProgramParameter(n,i.LINK_STATUS)){var s=i.getProgramInfoLog(n);if(s)throw new Error(s)}if(this.validateShaderPrograms){i.validateProgram(n);if(!i.getProgramParameter(n,i.VALIDATE_STATUS)){var s=i.getProgramInfoLog(n);if(s)throw new Error(s)}}return i.deleteShader(e),i.deleteShader(t),n},i.prototype.getUniforms=function(e,t){for(var i=new Array,r=0;r-1?p.substring(y).toLowerCase():""),x=null,T=0,E=i._TextureLoaders;Th||t.height>h)return d._prepareWorkingCanvas(),!(!d._workingCanvas||!d._workingContext)&&(d._workingCanvas.width=i,d._workingCanvas.height=r,d._workingContext.drawImage(t,0,0,t.width,t.height,0,0,i,r),s.texImage2D(s.TEXTURE_2D,0,l,l,s.UNSIGNED_BYTE,d._workingCanvas),v.width=i,v.height=r,!1);var c=new e.InternalTexture(d,e.InternalTexture.DATASOURCE_TEMP);return d._bindTextureDirectly(s.TEXTURE_2D,c,!0),s.texImage2D(s.TEXTURE_2D,0,l,l,s.UNSIGNED_BYTE,t),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),d._rescaleTexture(c,v,o,l,(function(){d._releaseTexture(c),d._bindTextureDirectly(s.TEXTURE_2D,v,!0),n()})),!0}),s)};!m||g?h instanceof HTMLImageElement?R(h):e.Tools.LoadImage(p,R,M,o?o.database:null):"string"==typeof h||h instanceof ArrayBuffer||h instanceof Blob?e.Tools.LoadImage(h,R,M,o?o.database:null):R(h)}return v},i.prototype._rescaleTexture=function(t,r,n,o,s){var a=this,l=this.createRenderTargetTexture({width:r.width,height:r.height},{generateMipMaps:!1,type:i.TEXTURETYPE_UNSIGNED_INT,samplingMode:i.TEXTURE_BILINEAR_SAMPLINGMODE,generateDepthBuffer:!1,generateStencilBuffer:!1});this._rescalePostProcess||(this._rescalePostProcess=new e.PassPostProcess("rescale",1,null,i.TEXTURE_BILINEAR_SAMPLINGMODE,this,!1,i.TEXTURETYPE_UNSIGNED_INT)),this._rescalePostProcess.getEffect().executeWhenCompiled((function(){a._rescalePostProcess.onApply=function(e){e._bindTexture("textureSampler",t)};var e=n;e||(e=a.scenes[a.scenes.length-1]),e.postProcessManager.directRender([a._rescalePostProcess],l,!0),a._bindTextureDirectly(a._gl.TEXTURE_2D,r,!0),a._gl.copyTexImage2D(a._gl.TEXTURE_2D,0,o,0,0,r.width,r.height,0),a.unBindFramebuffer(l),a._releaseTexture(l),s&&s()}))},i.prototype.updateRawTexture=function(e,t,r,n,o,s){if(void 0===o&&(o=null),void 0===s&&(s=i.TEXTURETYPE_UNSIGNED_INT),e){var a=this._getRGBABufferInternalSizedFormat(s,r),l=this._getInternalFormat(r),h=this._getWebGLTextureType(s);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(e._bufferView=t,e.format=r,e.type=s,e.invertY=n,e._compression=o),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),o&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[o],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}},i.prototype.createRawTexture=function(t,r,n,o,s,a,l,h,c){void 0===h&&(h=null),void 0===c&&(c=i.TEXTURETYPE_UNSIGNED_INT);var u=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RAW);u.baseWidth=r,u.baseHeight=n,u.width=r,u.height=n,u.format=o,u.generateMipMaps=s,u.samplingMode=l,u.invertY=a,u._compression=h,u.type=c,this._doNotHandleContextLost||(u._bufferView=t),this.updateRawTexture(u,t,o,a,h,c),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);var f=this._getSamplingParameters(l,s);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,f.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,f.min),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},i.prototype._unpackFlipY=function(e){this._unpackFlipYCached!==e&&(this._unpackFlipYCached=e,this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0))}, +i.prototype._getUnpackAlignement=function(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)},i.prototype.createDynamicTexture=function(t,i,r,n){var o=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_DYNAMIC);return o.baseWidth=t,o.baseHeight=i,r&&(t=this.needPOTTextures?e.Tools.GetExponentOfTwo(t,this._caps.maxTextureSize):t,i=this.needPOTTextures?e.Tools.GetExponentOfTwo(i,this._caps.maxTextureSize):i),o.width=t,o.height=i,o.isReady=!1,o.generateMipMaps=r,o.samplingMode=n,this.updateTextureSamplingMode(n,o),this._internalTexturesCache.push(o),o},i.prototype.updateTextureSamplingMode=function(e,t){var i=this._getSamplingParameters(e,t.generateMipMaps);t.isCube?(this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):t.is3D?(this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_3D,null)):(this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),t.samplingMode=e},i.prototype.updateDynamicTexture=function(e,t,i,r,n){if(void 0===r&&(r=!1),e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(i),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);var o=n?this._getInternalFormat(n):this._gl.RGBA;this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,o,this._gl.UNSIGNED_BYTE,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0}},i.prototype.updateVideoTexture=function(e,t,i){if(e&&!e._isDisabled){var r=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=document.createElement("canvas");var n=e._workingCanvas.getContext("2d");if(!n)throw new Error("Unable to get 2d context");e._workingContext=n,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),r||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}}},i.prototype.updateTextureComparisonFunction=function(t,r){if(1===this.webGLVersion)return void e.Tools.Error("WebGL 1 does not support texture comparison.");var n=this._gl;t.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,t,!0),0===r?(n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_FUNC,i.LEQUAL),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_MODE,n.NONE)):(n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_FUNC,r),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),0===r?(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_FUNC,i.LEQUAL),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_MODE,n.NONE)):(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_FUNC,r),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),t._comparisonFunction=r},i.prototype._setupDepthStencilTexture=function(e,t,r,n,o){var s=t.width||t,a=t.height||t;e.baseWidth=s,e.baseHeight=a,e.width=s,e.height=a,e.isReady=!0,e.samples=1,e.generateMipMaps=!1,e._generateDepthBuffer=!0,e._generateStencilBuffer=r,e.samplingMode=n?i.TEXTURE_BILINEAR_SAMPLINGMODE:i.TEXTURE_NEAREST_SAMPLINGMODE,e.type=i.TEXTURETYPE_UNSIGNED_INT,e._comparisonFunction=o;var l=this._gl,h=e.isCube?l.TEXTURE_CUBE_MAP:l.TEXTURE_2D,c=this._getSamplingParameters(e.samplingMode,!1);l.texParameteri(h,l.TEXTURE_MAG_FILTER,c.mag),l.texParameteri(h,l.TEXTURE_MIN_FILTER,c.min),l.texParameteri(h,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(h,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),0===o?(l.texParameteri(h,l.TEXTURE_COMPARE_FUNC,i.LEQUAL),l.texParameteri(h,l.TEXTURE_COMPARE_MODE,l.NONE)):(l.texParameteri(h,l.TEXTURE_COMPARE_FUNC,o),l.texParameteri(h,l.TEXTURE_COMPARE_MODE,l.COMPARE_REF_TO_TEXTURE))},i.prototype.createDepthStencilTexture=function(e,t){if(t.isCube){var i=e.width||e;return this._createDepthStencilCubeTexture(i,t)}return this._createDepthStencilTexture(e,t)},i.prototype._createDepthStencilTexture=function(t,i){var r=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_DEPTHTEXTURE);if(!this._caps.depthTextureExtension)return e.Tools.Error("Depth texture is not supported by your browser or hardware."),r;var n=s({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},i),o=this._gl;return this._bindTextureDirectly(o.TEXTURE_2D,r,!0),this._setupDepthStencilTexture(r,t,n.generateStencil,n.bilinearFiltering,n.comparisonFunction),this.webGLVersion>1?n.generateStencil?o.texImage2D(o.TEXTURE_2D,0,o.DEPTH24_STENCIL8,r.width,r.height,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_COMPONENT24,r.width,r.height,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null):n.generateStencil?o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_STENCIL,r.width,r.height,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_COMPONENT,r.width,r.height,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null),this._bindTextureDirectly(o.TEXTURE_2D,null),r},i.prototype._createDepthStencilCubeTexture=function(t,i){var r=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_UNKNOWN);if(r.isCube=!0,1===this.webGLVersion)return e.Tools.Error("Depth cube texture is not supported by WebGL 1."),r;var n=s({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},i),o=this._gl;this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,r,!0),this._setupDepthStencilTexture(r,t,n.generateStencil,n.bilinearFiltering,n.comparisonFunction);for(var a=0;a<6;a++)n.generateStencil?o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,o.DEPTH24_STENCIL8,t,t,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,o.DEPTH_COMPONENT24,t,t,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null);return this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null),r},i.prototype.setFrameBufferDepthStencilTexture=function(e){var t=e.getInternalTexture();if(t&&t._framebuffer&&e.depthStencilTexture){var i=this._gl,r=e.depthStencilTexture;this.bindUnboundFramebuffer(t._framebuffer),r.isCube?r._generateStencilBuffer?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_CUBE_MAP_POSITIVE_X,r._webGLTexture,0):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_CUBE_MAP_POSITIVE_X,r._webGLTexture,0):r._generateStencilBuffer?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_2D,r._webGLTexture,0):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,r._webGLTexture,0),this.bindUnboundFramebuffer(null)}},i.prototype.createRenderTargetTexture=function(t,n){var o=new r;void 0!==n&&"object"==typeof n?(o.generateMipMaps=n.generateMipMaps,o.generateDepthBuffer=void 0===n.generateDepthBuffer||n.generateDepthBuffer,o.generateStencilBuffer=o.generateDepthBuffer&&n.generateStencilBuffer,o.type=void 0===n.type?i.TEXTURETYPE_UNSIGNED_INT:n.type,o.samplingMode=void 0===n.samplingMode?i.TEXTURE_TRILINEAR_SAMPLINGMODE:n.samplingMode,o.format=void 0===n.format?i.TEXTUREFORMAT_RGBA:n.format):(o.generateMipMaps=n,o.generateDepthBuffer=!0,o.generateStencilBuffer=!1,o.type=i.TEXTURETYPE_UNSIGNED_INT,o.samplingMode=i.TEXTURE_TRILINEAR_SAMPLINGMODE,o.format=i.TEXTUREFORMAT_RGBA),o.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering?o.type!==i.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering||(o.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE):o.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE;var s=this._gl,a=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RENDERTARGET);this._bindTextureDirectly(s.TEXTURE_2D,a,!0);var l=t.width||t,h=t.height||t,c=this._getSamplingParameters(o.samplingMode,!!o.generateMipMaps);o.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloat||(o.type=i.TEXTURETYPE_UNSIGNED_INT,e.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,c.mag),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,c.min),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(o.type,o.format),l,h,0,this._getInternalFormat(o.format),this._getWebGLTextureType(o.type),null);var u=this._currentFramebuffer,f=s.createFramebuffer();return this.bindUnboundFramebuffer(f),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,a._webGLTexture,0),a._depthStencilBuffer=this._setupFramebufferDepthAttachments(!!o.generateStencilBuffer,o.generateDepthBuffer,l,h),o.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),this.bindUnboundFramebuffer(u),a._framebuffer=f,a.baseWidth=l,a.baseHeight=h,a.width=l,a.height=h,a.isReady=!0,a.samples=1,a.generateMipMaps=!!o.generateMipMaps,a.samplingMode=o.samplingMode,a.type=o.type,a._generateDepthBuffer=o.generateDepthBuffer,a._generateStencilBuffer=!!o.generateStencilBuffer,this._internalTexturesCache.push(a),a},i.prototype.createMultipleRenderTarget=function(t,r){var n=!1,o=!0,s=!1,a=!1,l=1,h=i.TEXTURETYPE_UNSIGNED_INT,c=i.TEXTURE_TRILINEAR_SAMPLINGMODE,u=new Array,f=new Array;void 0!==r&&(n=void 0!==r.generateMipMaps&&r.generateMipMaps,o=void 0===r.generateDepthBuffer||r.generateDepthBuffer,s=void 0!==r.generateStencilBuffer&&r.generateStencilBuffer,a=void 0!==r.generateDepthTexture&&r.generateDepthTexture,l=r.textureCount||1,r.types&&(u=r.types),r.samplingModes&&(f=r.samplingModes));var d=this._gl,p=d.createFramebuffer();this.bindUnboundFramebuffer(p);for(var m=t.width||t,_=t.height||t,g=[],v=[],y=this._setupFramebufferDepthAttachments(s,o,m,_),b=0;b1?"COLOR_ATTACHMENT"+b:"COLOR_ATTACHMENT"+b+"_WEBGL"];g.push(P),v.push(A),d.activeTexture(d["TEXTURE"+b]),d.bindTexture(d.TEXTURE_2D,P._webGLTexture),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MAG_FILTER,E.mag),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MIN_FILTER,E.min),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),d.texImage2D(d.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(T),m,_,0,d.RGBA,this._getWebGLTextureType(T),null),d.framebufferTexture2D(d.DRAW_FRAMEBUFFER,A,d.TEXTURE_2D,P._webGLTexture,0),n&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(d.TEXTURE_2D,null),P._framebuffer=p,P._depthStencilBuffer=y,P.baseWidth=m,P.baseHeight=_,P.width=m,P.height=_,P.isReady=!0,P.samples=1,P.generateMipMaps=n,P.samplingMode=x,P.type=T,P._generateDepthBuffer=o,P._generateStencilBuffer=s,P._attachments=v,this._internalTexturesCache.push(P)}if(a&&this._caps.depthTextureExtension){var M=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_MULTIRENDERTARGET);d.activeTexture(d.TEXTURE0),d.bindTexture(d.TEXTURE_2D,M._webGLTexture),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MAG_FILTER,d.NEAREST),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MIN_FILTER,d.NEAREST),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),d.texImage2D(d.TEXTURE_2D,0,this.webGLVersion<2?d.DEPTH_COMPONENT:d.DEPTH_COMPONENT16,m,_,0,d.DEPTH_COMPONENT,d.UNSIGNED_SHORT,null),d.framebufferTexture2D(d.FRAMEBUFFER,d.DEPTH_ATTACHMENT,d.TEXTURE_2D,M._webGLTexture,0),M._framebuffer=p,M.baseWidth=m,M.baseHeight=_,M.width=m,M.height=_,M.isReady=!0,M.samples=1,M.generateMipMaps=n,M.samplingMode=d.NEAREST,M._generateDepthBuffer=o,M._generateStencilBuffer=s,g.push(M),this._internalTexturesCache.push(M)}return d.drawBuffers(v),d.bindRenderbuffer(d.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),this.resetTextureCache(),g},i.prototype._setupFramebufferDepthAttachments=function(e,t,i,r,n){void 0===n&&(n=1);var o=null,s=this._gl;return e?(o=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,o),n>1?s.renderbufferStorageMultisample(s.RENDERBUFFER,n,s.DEPTH24_STENCIL8,i,r):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,i,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,o)):t&&(o=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,o),n>1?s.renderbufferStorageMultisample(s.RENDERBUFFER,n,s.DEPTH_COMPONENT16,i,r):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT16,i,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,o)),o},i.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e)return 1;if(e.samples===t)return t;var i=this._gl;if(t=Math.min(t,i.getParameter(i.MAX_SAMPLES)),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),e._MSAARenderBuffer&&(i.deleteRenderbuffer(e._MSAARenderBuffer),e._MSAARenderBuffer=null),t>1){var r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this.bindUnboundFramebuffer(e._MSAAFramebuffer);var n=i.createRenderbuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorageMultisample(i.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(e.type),e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,n),e._MSAARenderBuffer=n}else this.bindUnboundFramebuffer(e._framebuffer);return e.samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.width,e.height,t),i.bindRenderbuffer(i.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),t},i.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||0==e.length)return 1;if(e[0].samples===t)return t;var i=this._gl;t=Math.min(t,i.getParameter(i.MAX_SAMPLES)),e[0]._depthStencilBuffer&&(i.deleteRenderbuffer(e[0]._depthStencilBuffer),e[0]._depthStencilBuffer=null),e[0]._MSAAFramebuffer&&(i.deleteFramebuffer(e[0]._MSAAFramebuffer),e[0]._MSAAFramebuffer=null);for(var r=0;r1){var n=i.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");this.bindUnboundFramebuffer(n);for(var o=this._setupFramebufferDepthAttachments(e[0]._generateStencilBuffer,e[0]._generateDepthBuffer,e[0].width,e[0].height,t),s=[],r=0;r1?"COLOR_ATTACHMENT"+r:"COLOR_ATTACHMENT"+r+"_WEBGL"],h=i.createRenderbuffer();if(!h)throw new Error("Unable to create multi sampled framebuffer");i.bindRenderbuffer(i.RENDERBUFFER,h),i.renderbufferStorageMultisample(i.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(a.type),a.width,a.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,l,i.RENDERBUFFER,h),a._MSAAFramebuffer=n,a._MSAARenderBuffer=h,a.samples=t,a._depthStencilBuffer=o,i.bindRenderbuffer(i.RENDERBUFFER,null),s.push(l)}i.drawBuffers(s)}else this.bindUnboundFramebuffer(e[0]._framebuffer);return this.bindUnboundFramebuffer(null),t},i.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,r,n,o,s){void 0===o&&(o=0),void 0===s&&(s=0);var a=this._gl,l=a.TEXTURE_2D;e.isCube&&(l=a.TEXTURE_CUBE_MAP_POSITIVE_X+o),this._gl.compressedTexImage2D(l,s,t,i,r,0,n)},i.prototype._uploadDataToTextureDirectly=function(t,i,r,n){void 0===r&&(r=0),void 0===n&&(n=0);var o=this._gl,s=this._getWebGLTextureType(t.type),a=this._getInternalFormat(t.format),l=this._getRGBABufferInternalSizedFormat(t.type,a);this._unpackFlipY(t.invertY);var h=o.TEXTURE_2D;t.isCube&&(h=o.TEXTURE_CUBE_MAP_POSITIVE_X+r);var c=Math.round(e.Scalar.Log2(t.width)),u=Math.round(e.Scalar.Log2(t.height)),f=Math.pow(2,Math.max(c-n,0)),d=Math.pow(2,Math.max(u-n,0));o.texImage2D(h,n,l,f,d,0,a,s,i)},i.prototype._uploadArrayBufferViewToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0);var n=this._gl,o=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(o,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(o,null,!0)},i.prototype._uploadImageToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0);var n=this._gl,o=this._getWebGLTextureType(e.type),s=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,s),l=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);var h=n.TEXTURE_2D;e.isCube&&(h=n.TEXTURE_CUBE_MAP_POSITIVE_X+i),n.texImage2D(h,r,a,s,o,t),this._bindTextureDirectly(l,null,!0)},i.prototype.createRenderTargetCubeTexture=function(t,r){var n=s({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:i.TEXTURETYPE_UNSIGNED_INT,samplingMode:i.TEXTURE_TRILINEAR_SAMPLINGMODE,format:i.TEXTUREFORMAT_RGBA},r);n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,n.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering?n.type!==i.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering||(n.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE):n.samplingMode=i.TEXTURE_NEAREST_SAMPLINGMODE;var o=this._gl,a=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RENDERTARGET);this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,a,!0);var l=this._getSamplingParameters(n.samplingMode,n.generateMipMaps);n.type!==i.TEXTURETYPE_FLOAT||this._caps.textureFloat||(n.type=i.TEXTURETYPE_UNSIGNED_INT,e.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,l.mag),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,l.min),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE);for(var h=0;h<6;h++)o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+h,0,this._getRGBABufferInternalSizedFormat(n.type,n.format),t,t,0,this._getInternalFormat(n.format),this._getWebGLTextureType(n.type),null);var c=o.createFramebuffer();return this.bindUnboundFramebuffer(c),a._depthStencilBuffer=this._setupFramebufferDepthAttachments(n.generateStencilBuffer,n.generateDepthBuffer,t,t),n.generateMipMaps&&o.generateMipmap(o.TEXTURE_CUBE_MAP),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null),o.bindRenderbuffer(o.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),a._framebuffer=c,a.width=t,a.height=t,a.isReady=!0,a.isCube=!0,a.samples=1,a.generateMipMaps=n.generateMipMaps,a.samplingMode=n.samplingMode,a.type=n.type,a._generateDepthBuffer=n.generateDepthBuffer,a._generateStencilBuffer=n.generateStencilBuffer,this._internalTexturesCache.push(a),a},i.prototype.createPrefilteredCubeTexture=function(t,i,r,n,o,s,a,l,h){var c=this;void 0===o&&(o=null),void 0===s&&(s=null),void 0===l&&(l=null),void 0===h&&(h=!0);var u=function(t){if(!t)return void(o&&o(null));var s=t.texture;if(h?t.info.sphericalPolynomial&&(s._sphericalPolynomial=t.info.sphericalPolynomial):s._sphericalPolynomial=new e.SphericalPolynomial,s._dataSource=e.InternalTexture.DATASOURCE_CUBEPREFILTERED,c._caps.textureLOD)return void(o&&o(s));var a=c._gl,l=t.width;if(l){for(var u=[],f=0;f<3;f++){var d=f/2,p=1-d,m=n,_=e.Scalar.Log2(l)*r+n,g=m+(_-m)*p,v=Math.round(Math.min(Math.max(g,0),_)),y=new e.InternalTexture(c,e.InternalTexture.DATASOURCE_TEMP);if(y.type=s.type,y.format=s.format,y.width=Math.pow(2,Math.max(e.Scalar.Log2(l)-v,0)),y.height=y.width,y.isCube=!0,c._bindTextureDirectly(a.TEXTURE_CUBE_MAP,y,!0),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),t.isDDS){var b=t.info,x=t.data;c._unpackFlipY(b.isCompressed),e.DDSTools.UploadDDSLevels(c,y,x,b,!0,6,v)}else e.Tools.Warn("DDS is the only prefiltered cube map supported so far.");c._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);var T=new e.BaseTexture(i);T.isCube=!0,T._texture=y,y.isReady=!0,u.push(T)}s._lodTextureHigh=u[2],s._lodTextureMid=u[1],s._lodTextureLow=u[0],o&&o(s)}};return this.createCubeTexture(t,i,null,!1,u,s,a,l,h,r,n)},i.prototype.createCubeTexture=function(t,r,n,o,s,a,l,h,c,u,f,d){var p=this;void 0===s&&(s=null),void 0===a&&(a=null),void 0===h&&(h=null),void 0===c&&(c=!1),void 0===u&&(u=0),void 0===f&&(f=0),void 0===d&&(d=null);var m=this._gl,_=d||new e.InternalTexture(this,e.InternalTexture.DATASOURCE_CUBE);_.isCube=!0,_.url=t,_.generateMipMaps=!o,_._lodGenerationScale=u,_._lodGenerationOffset=f,this._doNotHandleContextLost||(_._extension=h,_._files=n);for(var g=t.lastIndexOf("."),v=h||(g>-1?t.substring(g).toLowerCase():""),y=null,b=0,x=i._TextureLoaders;b>v,b=0;b<6;b++){var x=g[v][b];_&&(x=d._convertRGBtoRGBATextureData(x,y,y,o)),p.texImage2D(b,v,u,y,y,0,c,s,x)}d._bindTextureDirectly(p.TEXTURE_CUBE_MAP,null)}else d.updateRawCubeTexture(m,r,n,o,f);m.isReady=!0,t._removePendingData(m),h&&h()}};return this._loadFile(e,(function(e){g(e)}),void 0,t.database,!0,_),m},i.prototype.updateRawTexture3D=function(e,t,r,n,o,s){void 0===o&&(o=null),void 0===s&&(s=i.TEXTURETYPE_UNSIGNED_INT);var a=this._getWebGLTextureType(s),l=this._getInternalFormat(r),h=this._getRGBABufferInternalSizedFormat(s,r);this._bindTextureDirectly(this._gl.TEXTURE_3D,e,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(e._bufferView=t,e.format=r,e.invertY=n,e._compression=o),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),o&&t?this._gl.compressedTexImage3D(this._gl.TEXTURE_3D,0,this.getCaps().s3tc[o],e.width,e.height,e.depth,0,t):this._gl.texImage3D(this._gl.TEXTURE_3D,0,h,e.width,e.height,e.depth,0,l,a,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_3D),this._bindTextureDirectly(this._gl.TEXTURE_3D,null),e.isReady=!0},i.prototype.createRawTexture3D=function(t,r,n,o,s,a,l,h,c,u){void 0===c&&(c=null),void 0===u&&(u=i.TEXTURETYPE_UNSIGNED_INT);var f=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RAW3D);f.baseWidth=r,f.baseHeight=n,f.baseDepth=o,f.width=r,f.height=n,f.depth=o,f.format=s,f.type=u,f.generateMipMaps=a,f.samplingMode=h,f.is3D=!0,this._doNotHandleContextLost||(f._bufferView=t),this.updateRawTexture3D(f,t,s,l,c,u),this._bindTextureDirectly(this._gl.TEXTURE_3D,f,!0);var d=this._getSamplingParameters(h,a);return this._gl.texParameteri(this._gl.TEXTURE_3D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_3D,this._gl.TEXTURE_MIN_FILTER,d.min),a&&this._gl.generateMipmap(this._gl.TEXTURE_3D),this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._internalTexturesCache.push(f),f},i.prototype._prepareWebGLTextureContinuation=function(e,t,i,r,n){var o=this._gl;if(o){var s=this._getSamplingParameters(n,!i);o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,s.mag),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,s.min),i||r||o.generateMipmap(o.TEXTURE_2D),this._bindTextureDirectly(o.TEXTURE_2D,null),t&&t._removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}},i.prototype._prepareWebGLTexture=function(t,r,n,o,s,a,l,h,c){var u=this;void 0===c&&(c=i.TEXTURE_TRILINEAR_SAMPLINGMODE);var f=this.getCaps().maxTextureSize,d=Math.min(f,this.needPOTTextures?e.Tools.GetExponentOfTwo(n,f):n),p=Math.min(f,this.needPOTTextures?e.Tools.GetExponentOfTwo(o,f):o),m=this._gl;if(m){if(!t._webGLTexture)return void(r&&r._removePendingData(t));this._bindTextureDirectly(m.TEXTURE_2D,t,!0),this._unpackFlipY(void 0===s||!!s),t.baseWidth=n,t.baseHeight=o,t.width=d,t.height=p,t.isReady=!0,h(d,p,(function(){u._prepareWebGLTextureContinuation(t,r,a,l,c)}))||this._prepareWebGLTextureContinuation(t,r,a,l,c)}},i.prototype._convertRGBtoRGBATextureData=function(e,t,r,n){var o;o=n===i.TEXTURETYPE_FLOAT?new Float32Array(t*r*4):new Uint32Array(t*r*4);for(var s=0;s-1?t._designatedSlot:this._nextFreeTextureSlots.length?this._nextFreeTextureSlots[0]:(this._textureCollisions.addCount(1,!1),this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next));return e},i.prototype._linkTrackers=function(e,t){e.next=t,t.previous=e},i.prototype._removeDesignatedSlot=function(e){var t=e._designatedSlot;return-1===t?-1:(e._designatedSlot=-1,this.disableTextureBindingOptimization?-1:(this._linkTrackers(e.previous,e.next),this._boundTexturesCache[t]=null,this._nextFreeTextureSlots.push(t),t))},i.prototype._activateCurrentTexture=function(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)},i.prototype._bindTextureDirectly=function(e,t,i,r){void 0===i&&(i=!1),void 0===r&&(r=!1);var n=!1;i&&t&&t._designatedSlot>-1&&(this._activeChannel=t._designatedSlot);var o=this._boundTexturesCache[this._activeChannel],s=t&&t._initialSlot>-1;if(o!==t||r){if(o&&this._removeDesignatedSlot(o),this._activateCurrentTexture(),this._gl.bindTexture(e,t?t._webGLTexture:null),this._boundTexturesCache[this._activeChannel]=t,t){if(!this.disableTextureBindingOptimization){var a=this._nextFreeTextureSlots.indexOf(this._activeChannel);a>-1&&this._nextFreeTextureSlots.splice(a,1),this._linkTrackers(this._lastBoundInternalTextureTracker.previous,t),this._linkTrackers(t,this._lastBoundInternalTextureTracker)}t._designatedSlot=this._activeChannel}}else i&&(n=!0,this._activateCurrentTexture());return s&&!i&&this._bindSamplerUniformToChannel(t._initialSlot,this._activeChannel),n},i.prototype._bindTexture=function(e,t){e<0||(t&&(e=this._getCorrectTextureChannel(e,t)),this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,t))},i.prototype.setTextureFromPostProcess=function(e,t){this._bindTexture(e,t?t._textures.data[t._currentRenderTextureInd]:null)},i.prototype.setTextureFromPostProcessOutput=function(e,t){this._bindTexture(e,t?t._outputTexture:null)},i.prototype.unbindAllTextures=function(){for(var e=0;e1&&this._bindTextureDirectly(this._gl.TEXTURE_3D,null)},i.prototype.setTexture=function(e,t,i){e<0||(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))},i.prototype.setDepthStencilTexture=function(e,t,i){e<0||(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0):this._setTexture(e,null))},i.prototype._bindSamplerUniformToChannel=function(e,t){var i=this._boundUniforms[e];i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)},i.prototype._getTextureWrapMode=function(e){switch(e){case i.TEXTURE_WRAP_ADDRESSMODE:return this._gl.REPEAT;case i.TEXTURE_CLAMP_ADDRESSMODE:return this._gl.CLAMP_TO_EDGE;case i.TEXTURE_MIRROR_ADDRESSMODE:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT},i.prototype._setTexture=function(e,t,r,n){if(void 0===r&&(r=!1),void 0===n&&(n=!1),!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&this._bindTextureDirectly(this._gl.TEXTURE_3D,null)),!1;if(t.video)this._activeChannel=e,t.update();else if(t.delayLoadState===i.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;var o;o=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:this.emptyTexture,r||(e=this._getCorrectTextureChannel(e,o));var s=!0;if(this._boundTexturesCache[e]===o&&(this._moveBoundTextureOnTop(o),r||this._bindSamplerUniformToChannel(o._initialSlot,e),s=!1),this._activeChannel=e,o&&o.is3D)s&&this._bindTextureDirectly(this._gl.TEXTURE_3D,o,r),o&&o._cachedWrapU!==t.wrapU&&(o._cachedWrapU=t.wrapU,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),o)),o&&o._cachedWrapV!==t.wrapV&&(o._cachedWrapV=t.wrapV,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),o)),o&&o._cachedWrapR!==t.wrapR&&(o._cachedWrapR=t.wrapR,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),o)),this._setAnisotropicLevel(this._gl.TEXTURE_3D,t);else if(o&&o.isCube){if(s&&this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,o,r),o._cachedCoordinatesMode!==t.coordinatesMode){o._cachedCoordinatesMode=t.coordinatesMode;var a=t.coordinatesMode!==i.TEXTURE_CUBIC_MODE&&t.coordinatesMode!==i.TEXTURE_SKYBOX_MODE?this._gl.REPEAT:this._gl.CLAMP_TO_EDGE;this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_S,a,o),this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_T,a)}this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP,t)}else s&&this._bindTextureDirectly(this._gl.TEXTURE_2D,o,r),o&&o._cachedWrapU!==t.wrapU&&(o._cachedWrapU=t.wrapU,this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),o)),o&&o._cachedWrapV!==t.wrapV&&(o._cachedWrapV=t.wrapV,this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),o)),this._setAnisotropicLevel(this._gl.TEXTURE_2D,t);return!0},i.prototype.setTextureArray=function(e,t,i){if(!(e<0)&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(var r=0;r=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||(this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1)},i.prototype.releaseEffects=function(){for(var e in this._compiledEffects)this._deleteProgram(this._compiledEffects[e]._program);this._compiledEffects={}},i.prototype.dispose=function(){for(this.hideLoadingUI(),this.stopRenderLoop();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();i.audioEngine&&i.audioEngine.dispose(),this.releaseEffects(),this.unbindAllAttributes(),this._boundUniforms=[],this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.disableVR(),e.Tools.IsWindowObjectExist()&&(window.removeEventListener("blur",this._onBlur),window.removeEventListener("focus",this._onFocus),window.removeEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted),window.removeEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange),this._onVrDisplayConnect&&(window.removeEventListener("vrdisplayconnect",this._onVrDisplayConnect),this._onVrDisplayDisconnect&&window.removeEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),this._onVrDisplayPresentChange&&window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),this._onVrDisplayConnect=null,this._onVrDisplayDisconnect=null));var t=i.Instances.indexOf(this);t>=0&&i.Instances.splice(t,1),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers=[],this._renderingCanvas=null,this._currentProgram=null,this._bindedRenderFunction=null,this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear(),e.Effect.ResetCache();for(var r=0,n=this._activeRequests;r-1?o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_CUBE_MAP_POSITIVE_X+r,e._webGLTexture,n):o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,e._webGLTexture,n);var a,l=void 0!==e.type?this._getWebGLTextureType(e.type):o.UNSIGNED_BYTE;switch(l){case o.UNSIGNED_BYTE:a=new Uint8Array(4*t*i),l=o.UNSIGNED_BYTE;break;default:a=new Float32Array(4*t*i),l=o.FLOAT}return o.readPixels(0,0,t,i,o.RGBA,l,a),o.bindFramebuffer(o.FRAMEBUFFER,this._currentFramebuffer),a},i.prototype._canRenderToFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(i.TEXTURETYPE_FLOAT)},i.prototype._canRenderToHalfFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(i.TEXTURETYPE_HALF_FLOAT)},i.prototype._canRenderToFramebuffer=function(e){for(var t=this._gl;t.getError()!==t.NO_ERROR;);var i=!0,r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);var n=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&o===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);var s=t.RGBA,a=t.UNSIGNED_BYTE,l=new Uint8Array(4);t.readPixels(0,0,1,1,s,a,l),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(n),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i},i.prototype._getWebGLTextureType=function(e){return e===i.TEXTURETYPE_FLOAT?this._gl.FLOAT:e===i.TEXTURETYPE_HALF_FLOAT?this._gl.HALF_FLOAT_OES:this._gl.UNSIGNED_BYTE},i.prototype._getInternalFormat=function(e){var t=this._gl.RGBA;switch(e){case i.TEXTUREFORMAT_ALPHA:t=this._gl.ALPHA;break;case i.TEXTUREFORMAT_LUMINANCE:t=this._gl.LUMINANCE;break;case i.TEXTUREFORMAT_LUMINANCE_ALPHA:t=this._gl.LUMINANCE_ALPHA;break;case i.TEXTUREFORMAT_RGB:t=this._gl.RGB;break;case i.TEXTUREFORMAT_RGBA:t=this._gl.RGBA;break;case i.TEXTUREFORMAT_R:t=this._gl.RED;break;case i.TEXTUREFORMAT_RG:t=this._gl.RG}return t},i.prototype._getRGBABufferInternalSizedFormat=function(e,t){if(1===this._webGLVersion){if(void 0!==t)switch(t){case i.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case i.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA}return this._gl.RGBA}if(e===i.TEXTURETYPE_FLOAT){if(void 0!==t)switch(t){case i.TEXTUREFORMAT_R:return this._gl.R32F;case i.TEXTUREFORMAT_RG:return this._gl.RG32F;case i.TEXTUREFORMAT_RGB:return this._gl.RGB32F}return this._gl.RGBA32F}if(e===i.TEXTURETYPE_HALF_FLOAT){if(t)switch(t){case i.TEXTUREFORMAT_R:return this._gl.R16F;case i.TEXTUREFORMAT_RG:return this._gl.RG16F;case i.TEXTUREFORMAT_RGB:return this._gl.RGB16F}return this._gl.RGBA16F}if(void 0!==t)switch(t){case i.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case i.TEXTUREFORMAT_RGB:return this._gl.RGB;case i.TEXTUREFORMAT_R:return this._gl.R8;case i.TEXTUREFORMAT_RG:return this._gl.RG8;case i.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA}return this._gl.RGBA},i.prototype._getRGBAMultiSampleBufferFormat=function(e){return e===i.TEXTURETYPE_FLOAT?this._gl.RGBA32F:e===i.TEXTURETYPE_HALF_FLOAT?this._gl.RGBA16F:this._gl.RGBA8},i.prototype._loadFile=function(t,i,r,n,o,s){var a=this,l=e.Tools.LoadFile(t,i,r,n,o,s);return this._activeRequests.push(l),l.onCompleteObservable.add((function(e){a._activeRequests.splice(a._activeRequests.indexOf(e),1)})),l},i.prototype._loadFileAsync=function(e,t,i){var r=this;return new Promise(function(n,o){r._loadFile(e,(function(e){n(e)}),void 0,t,i,(function(e,t){o(t)}))})},i.prototype._partialLoadFile=function(e,t,i,r,n,o){void 0===o&&(o=null);var s=function(e){i[t]=e,6===++i._internalCount&&n(i)},a=function(e,t){o&&e&&o(e.status+" "+e.statusText,t)};this._loadFile(e,s,void 0,void 0,!0,a)},i.prototype._cascadeLoadFiles=function(e,t,i,r){void 0===r&&(r=null);var n=[];n._internalCount=0;for(var o=0;o<6;o++)this._partialLoadFile(i[o],o,n,e,t,r)},i.isSupported=function(){try{var e=document.createElement("canvas");return null!=(e.getContext("webgl")||e.getContext("experimental-webgl"))&&!!window.WebGLRenderingContext}catch(e){return!1}},i.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Macintosh",capture:null,captureConstraint:null,targets:["textureBindingOptimization"]},{key:"iPhone",capture:null,captureConstraint:null,targets:["textureBindingOptimization"]},{key:"iPad",capture:null,captureConstraint:null,targets:["textureBindingOptimization"]}],i.Instances=new Array,i._TextureLoaders=[],i.ALPHA_DISABLE=0,i.ALPHA_ADD=1,i.ALPHA_COMBINE=2,i.ALPHA_SUBTRACT=3,i.ALPHA_MULTIPLY=4,i.ALPHA_MAXIMIZED=5,i.ALPHA_ONEONE=6,i.ALPHA_PREMULTIPLIED=7,i.ALPHA_PREMULTIPLIED_PORTERDUFF=8,i.ALPHA_INTERPOLATE=9,i.ALPHA_SCREENMODE=10,i.DELAYLOADSTATE_NONE=0,i.DELAYLOADSTATE_LOADED=1,i.DELAYLOADSTATE_LOADING=2,i.DELAYLOADSTATE_NOTLOADED=4,i.NEVER=512,i.ALWAYS=519,i.LESS=513,i.EQUAL=514,i.LEQUAL=515,i.GREATER=516,i.GEQUAL=518,i.NOTEQUAL=517,i.KEEP=7680,i.REPLACE=7681,i.INCR=7682,i.DECR=7683,i.INVERT=5386,i.INCR_WRAP=34055,i.DECR_WRAP=34056,i.TEXTURE_CLAMP_ADDRESSMODE=0,i.TEXTURE_WRAP_ADDRESSMODE=1,i.TEXTURE_MIRROR_ADDRESSMODE=2,i.TEXTUREFORMAT_ALPHA=0,i.TEXTUREFORMAT_LUMINANCE=1,i.TEXTUREFORMAT_LUMINANCE_ALPHA=2,i.TEXTUREFORMAT_RGB=4,i.TEXTUREFORMAT_RGBA=5,i.TEXTUREFORMAT_R=6,i.TEXTUREFORMAT_RG=7,i.TEXTURETYPE_UNSIGNED_INT=0,i.TEXTURETYPE_FLOAT=1,i.TEXTURETYPE_HALF_FLOAT=2,i.TEXTURE_NEAREST_SAMPLINGMODE=1,i.TEXTURE_BILINEAR_SAMPLINGMODE=2,i.TEXTURE_TRILINEAR_SAMPLINGMODE=3,i.TEXTURE_NEAREST_NEAREST_MIPLINEAR=1,i.TEXTURE_LINEAR_LINEAR_MIPNEAREST=2,i.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,i.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,i.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,i.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,i.TEXTURE_NEAREST_LINEAR=7,i.TEXTURE_NEAREST_NEAREST=8,i.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,i.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,i.TEXTURE_LINEAR_LINEAR=11,i.TEXTURE_LINEAR_NEAREST=12,i.TEXTURE_EXPLICIT_MODE=0,i.TEXTURE_SPHERICAL_MODE=1,i.TEXTURE_PLANAR_MODE=2,i.TEXTURE_CUBIC_MODE=3,i.TEXTURE_PROJECTION_MODE=4,i.TEXTURE_SKYBOX_MODE=5,i.TEXTURE_INVCUBIC_MODE=6,i.TEXTURE_EQUIRECTANGULAR_MODE=7,i.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,i.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,i.SCALEMODE_FLOOR=1,i.SCALEMODE_NEAREST=2,i.SCALEMODE_CEILING=3,i.CollisionsEpsilon=.001,i.CodeRepository="src/",i.ShadersRepository="src/Shaders/",i})();e.Engine=a})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i){void 0===i&&(i=null),this.state="",this.metadata=null,this.doNotSerialize=!1,this._isDisposed=!1,this.animations=new Array,this._ranges={},this._isEnabled=!0,this._isReady=!0,this._currentRenderId=-1,this._parentRenderId=-1,this._childRenderId=-1,this._animationPropertiesOverride=null,this.onDisposeObservable=new e.Observable,this._behaviors=new Array,this.name=t,this.id=t,this._scene=i||e.Engine.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}return t.AddNodeConstructor=function(e,t){this._NodeConstructors[e]=t},t.Construct=function(e,t,i,r){var n=this._NodeConstructors[e];return n?n(t,i,r):null},t.prototype.isDisposed=function(){return this._isDisposed},Object.defineProperty(t.prototype,"parent",{get:function(){return this._parentNode},set:function(e){if(this._parentNode!==e){if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){var t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1)}this._parentNode=e,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this))}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"Node"},Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEngine=function(){return this._scene.getEngine()},t.prototype.addBehavior=function(e){var t=this;return-1!==this._behaviors.indexOf(e)?this:(e.init(),this._scene.isLoading?this._scene.onDataLoadedObservable.addOnce((function(){e.attach(t)})):e.attach(this),this._behaviors.push(e),this)},t.prototype.removeBehavior=function(e){var t=this._behaviors.indexOf(e);return-1===t?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)},Object.defineProperty(t.prototype,"behaviors",{get:function(){return this._behaviors},enumerable:!0,configurable:!0}),t.prototype.getBehaviorByName=function(e){for(var t=0,i=this._behaviors;tthis.maximumWorld.x&&(this.maximumWorld.x=r.x),r.y>this.maximumWorld.y&&(this.maximumWorld.y=r.y),r.z>this.maximumWorld.z&&(this.maximumWorld.z=r.z)}this.maximumWorld.subtractToRef(this.minimumWorld,this.extendSizeWorld),this.extendSizeWorld.scaleInPlace(.5),this.maximumWorld.addToRef(this.minimumWorld,this.centerWorld),this.centerWorld.scaleInPlace(.5),e.Vector3.FromFloatArrayToRef(t.m,0,this.directions[0]),e.Vector3.FromFloatArrayToRef(t.m,4,this.directions[1]),e.Vector3.FromFloatArrayToRef(t.m,8,this.directions[2]),this._worldMatrix=t},t.prototype.isInFrustum=function(e){return t.IsInFrustum(this.vectorsWorld,e)},t.prototype.isCompletelyInFrustum=function(e){return t.IsCompletelyInFrustum(this.vectorsWorld,e)},t.prototype.intersectsPoint=function(t){var i=-e.Epsilon;return!(this.maximumWorld.x-t.xt.x-this.minimumWorld.x)&&(!(this.maximumWorld.y-t.yt.y-this.minimumWorld.y)&&!(this.maximumWorld.z-t.zt.z-this.minimumWorld.z))},t.prototype.intersectsSphere=function(e){ +return t.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)},t.prototype.intersectsMinMax=function(e,t){return!(this.maximumWorld.xt.x)&&(!(this.maximumWorld.yt.y)&&!(this.maximumWorld.zt.z))},t.Intersects=function(e,t){return!(e.maximumWorld.xt.maximumWorld.x)&&(!(e.maximumWorld.yt.maximumWorld.y)&&!(e.maximumWorld.zt.maximumWorld.z))},t.IntersectsSphere=function(t,i,r,n){var o=e.Vector3.Clamp(r,t,i);return e.Vector3.DistanceSquared(r,o)<=n*n},t.IsCompletelyInFrustum=function(e,t){for(var i=0;i<6;i++)for(var r=0;r<8;r++)if(t[i].dotCoordinate(e[r])<0)return!1;return!0},t.IsInFrustum=function(e,t){for(var i=0;i<6;i++){for(var r=8,n=0;n<8&&t[i].dotCoordinate(e[n])<0;n++)--r;if(0===r)return!1}return!0},t})();e.BoundingBox=t})(r||(r={}));var r;!(function(e){var t=function(t,i){var r=e.Vector3.Dot(i.centerWorld,t),n=Math.abs(e.Vector3.Dot(i.directions[0],t))*i.extendSize.x,o=Math.abs(e.Vector3.Dot(i.directions[1],t))*i.extendSize.y,s=Math.abs(e.Vector3.Dot(i.directions[2],t))*i.extendSize.z,a=n+o+s;return{min:r-a,max:r+a}},i=function(e,t,i,r){return!(e>r||i>t)},r=function(e,r,n){var o=t(e,r),s=t(e,n);return i(o.min,o.max,s.min,s.max)},n=(function(){function t(t,i){this.minimum=t,this.maximum=i,this._isLocked=!1,this.boundingBox=new e.BoundingBox(t,i),this.boundingSphere=new e.BoundingSphere(t,i)}return Object.defineProperty(t.prototype,"isLocked",{get:function(){return this._isLocked},set:function(e){this._isLocked=e},enumerable:!0,configurable:!0}),t.prototype.update=function(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))},t.prototype.centerOn=function(t,i){return this.minimum=t.subtract(i),this.maximum=t.add(i),this.boundingBox=new e.BoundingBox(this.minimum,this.maximum),this.boundingSphere=new e.BoundingSphere(this.minimum,this.maximum),this},t.prototype.scale=function(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this},t.prototype.isInFrustum=function(e){return!!this.boundingSphere.isInFrustum(e)&&this.boundingBox.isInFrustum(e)},Object.defineProperty(t.prototype,"diagonalLength",{get:function(){var e=this.boundingBox;return e.maximumWorld.subtract(e.minimumWorld).length()},enumerable:!0,configurable:!0}),t.prototype.isCompletelyInFrustum=function(e){return this.boundingBox.isCompletelyInFrustum(e)},t.prototype._checkCollision=function(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)},t.prototype.intersectsPoint=function(e){return!!this.boundingSphere.centerWorld&&(!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e))},t.prototype.intersects=function(t,i){if(!this.boundingSphere.centerWorld||!t.boundingSphere.centerWorld)return!1;if(!e.BoundingSphere.Intersects(this.boundingSphere,t.boundingSphere))return!1;if(!e.BoundingBox.Intersects(this.boundingBox,t.boundingBox))return!1;if(!i)return!0;var n=this.boundingBox,o=t.boundingBox;return!!r(n.directions[0],n,o)&&(!!r(n.directions[1],n,o)&&(!!r(n.directions[2],n,o)&&(!!r(o.directions[0],n,o)&&(!!r(o.directions[1],n,o)&&(!!r(o.directions[2],n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[1]),n,o)&&!!r(e.Vector3.Cross(n.directions[2],o.directions[2]),n,o))))))))))))))},t})();e.BoundingInfo=n})(r||(r={}));var r;!(function(e){var t=(function(t){function i(r,n,o){void 0===n&&(n=null),void 0===o&&(o=!0);var s=t.call(this,r,n)||this;return s._forward=new e.Vector3(0,0,1),s._forwardInverted=new e.Vector3(0,0,-1),s._up=new e.Vector3(0,1,0),s._right=new e.Vector3(1,0,0),s._rightInverted=new e.Vector3(-1,0,0),s._rotation=e.Vector3.Zero(),s._scaling=e.Vector3.One(),s._isDirty=!1,s.billboardMode=i.BILLBOARDMODE_NONE,s.scalingDeterminant=1,s.infiniteDistance=!1,s.ignoreNonUniformScaling=!1,s.position=e.Vector3.Zero(),s._localWorld=e.Matrix.Zero(),s._worldMatrix=e.Matrix.Zero(),s._worldMatrixDeterminant=0,s._absolutePosition=e.Vector3.Zero(),s._pivotMatrix=e.Matrix.Identity(),s._postMultiplyPivotMatrix=!1,s._isWorldMatrixFrozen=!1,s.onAfterWorldMatrixUpdateObservable=new e.Observable,s._nonUniformScaling=!1,o&&s.getScene().addTransformNode(s),s}return o(i,t),i.prototype.getClassName=function(){return"TransformNode"},Object.defineProperty(i.prototype,"rotation",{get:function(){return this._rotation},set:function(e){this._rotation=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"scaling",{get:function(){return this._scaling},set:function(e){this._scaling=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"rotationQuaternion",{get:function(){return this._rotationQuaternion},set:function(e){this._rotationQuaternion=e,e&&this.rotation.length()&&this.rotation.copyFromFloats(0,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"forward",{get:function(){return e.Vector3.Normalize(e.Vector3.TransformNormal(this.getScene().useRightHandedSystem?this._forwardInverted:this._forward,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"up",{get:function(){return e.Vector3.Normalize(e.Vector3.TransformNormal(this._up,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return e.Vector3.Normalize(e.Vector3.TransformNormal(this.getScene().useRightHandedSystem?this._rightInverted:this._right,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),i.prototype.getWorldMatrix=function(){return this._currentRenderId!==this.getScene().getRenderId()&&this.computeWorldMatrix(),this._worldMatrix},i.prototype._getWorldMatrixDeterminant=function(){return this._worldMatrixDeterminant},Object.defineProperty(i.prototype,"worldMatrixFromCache",{get:function(){return this._worldMatrix},enumerable:!0,configurable:!0}),i.prototype.updatePoseMatrix=function(e){return this._poseMatrix.copyFrom(e),this},i.prototype.getPoseMatrix=function(){return this._poseMatrix},i.prototype._isSynchronized=function(){return!this._isDirty&&(this.billboardMode===this._cache.billboardMode&&this.billboardMode===i.BILLBOARDMODE_NONE&&(!this._cache.pivotMatrixUpdated&&(!this.infiniteDistance&&(!!this._cache.position.equals(this.position)&&(!(this.rotationQuaternion&&!this._cache.rotationQuaternion.equals(this.rotationQuaternion))&&(!!this._cache.rotation.equals(this.rotation)&&!!this._cache.scaling.equals(this.scaling)))))))},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.localMatrixUpdated=!1,this._cache.position=e.Vector3.Zero(),this._cache.scaling=e.Vector3.Zero(),this._cache.rotation=e.Vector3.Zero(),this._cache.rotationQuaternion=new e.Quaternion(0,0,0,0),this._cache.billboardMode=-1},i.prototype.markAsDirty=function(e){return"rotation"===e&&(this.rotationQuaternion=null),this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this},Object.defineProperty(i.prototype,"absolutePosition",{get:function(){return this._absolutePosition},enumerable:!0,configurable:!0}),i.prototype.setPreTransformMatrix=function(e){return this.setPivotMatrix(e,!1)},i.prototype.setPivotMatrix=function(t,i){return void 0===i&&(i=!0),this._pivotMatrix=t.clone(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=i,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=e.Matrix.Invert(this._pivotMatrix)),this},i.prototype.getPivotMatrix=function(){return this._pivotMatrix},i.prototype.freezeWorldMatrix=function(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this._isWorldMatrixFrozen=!0,this},i.prototype.unfreezeWorldMatrix=function(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this},Object.defineProperty(i.prototype,"isWorldMatrixFrozen",{get:function(){return this._isWorldMatrixFrozen},enumerable:!0,configurable:!0}),i.prototype.getAbsolutePosition=function(){return this.computeWorldMatrix(),this._absolutePosition},i.prototype.setAbsolutePosition=function(t){if(!t)return this;var i,r,n;if(void 0===t.x){if(arguments.length<3)return this;i=arguments[0],r=arguments[1],n=arguments[2]}else i=t.x,r=t.y,n=t.z;if(this.parent){var o=this.parent.getWorldMatrix().clone();o.invert();var s=new e.Vector3(i,r,n);this.position=e.Vector3.TransformCoordinates(s,o)}else this.position.x=i,this.position.y=r,this.position.z=n;return this},i.prototype.setPositionWithLocalVector=function(t){return this.computeWorldMatrix(),this.position=e.Vector3.TransformNormal(t,this._localWorld),this},i.prototype.getPositionExpressedInLocalSpace=function(){this.computeWorldMatrix();var t=this._localWorld.clone();return t.invert(),e.Vector3.TransformNormal(this.position,t)},i.prototype.locallyTranslate=function(t){return this.computeWorldMatrix(!0),this.position=e.Vector3.TransformCoordinates(t,this._localWorld),this},i.prototype.lookAt=function(t,r,n,o,s){void 0===r&&(r=0),void 0===n&&(n=0),void 0===o&&(o=0),void 0===s&&(s=e.Space.LOCAL);var a=i._lookAtVectorCache,l=s===e.Space.LOCAL?this.position:this.getAbsolutePosition();t.subtractToRef(l,a);var h=-Math.atan2(a.z,a.x)-Math.PI/2,c=Math.sqrt(a.x*a.x+a.z*a.z),u=Math.atan2(a.y,c);return this.rotationQuaternion?e.Quaternion.RotationYawPitchRollToRef(h+r,u+n,o,this.rotationQuaternion):(this.rotation.x=u+n,this.rotation.y=h+r,this.rotation.z=o),this},i.prototype.getDirection=function(t){var i=e.Vector3.Zero();return this.getDirectionToRef(t,i),i},i.prototype.getDirectionToRef=function(t,i){return e.Vector3.TransformNormalToRef(t,this.getWorldMatrix(),i),this},i.prototype.setPivotPoint=function(t,i){void 0===i&&(i=e.Space.LOCAL),0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);var r=this.getWorldMatrix();if(i==e.Space.WORLD){var n=e.Tmp.Matrix[0];r.invertToRef(n),t=e.Vector3.TransformCoordinates(t,n)}return this.setPivotMatrix(e.Matrix.Translation(-t.x,-t.y,-t.z),!0)},i.prototype.getPivotPoint=function(){var t=e.Vector3.Zero();return this.getPivotPointToRef(t),t},i.prototype.getPivotPointToRef=function(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this},i.prototype.getAbsolutePivotPoint=function(){var t=e.Vector3.Zero();return this.getAbsolutePivotPointToRef(t),t},i.prototype.getAbsolutePivotPointToRef=function(t){return t.x=this._pivotMatrix.m[12],t.y=this._pivotMatrix.m[13],t.z=this._pivotMatrix.m[14],this.getPivotPointToRef(t),e.Vector3.TransformCoordinatesToRef(t,this.getWorldMatrix(),t),this},i.prototype.setParent=function(t){if(!t&&!this.parent)return this;if(t){var i=e.Tmp.Quaternion[0],r=e.Tmp.Vector3[0],n=e.Tmp.Vector3[1],o=e.Tmp.Matrix[0],s=e.Tmp.Matrix[1];this.computeWorldMatrix(!0),t.computeWorldMatrix(!0),t.getWorldMatrix().invertToRef(s),this.getWorldMatrix().multiplyToRef(s,o),o.decompose(n,i,r),this.rotationQuaternion?this.rotationQuaternion.copyFrom(i):i.toEulerAnglesToRef(this.rotation),this.position.x=r.x,this.position.y=r.y,this.position.z=r.z,this.scaling.x=n.x,this.scaling.y=n.y,this.scaling.z=n.z}else{var i=e.Tmp.Quaternion[0],r=e.Tmp.Vector3[0],n=e.Tmp.Vector3[1];this.parent&&this.parent.computeWorldMatrix&&this.parent.computeWorldMatrix(!0),this.computeWorldMatrix(!0),this.getWorldMatrix().decompose(n,i,r),this.rotationQuaternion?this.rotationQuaternion.copyFrom(i):i.toEulerAnglesToRef(this.rotation),this.scaling.x=n.x,this.scaling.y=n.y,this.scaling.z=n.z,this.position.x=r.x,this.position.y=r.y,this.position.z=r.z}return this.parent=t,this},Object.defineProperty(i.prototype,"nonUniformScaling",{get:function(){return this._nonUniformScaling},enumerable:!0,configurable:!0}),i.prototype._updateNonUniformScalingState=function(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)},i.prototype.attachToBone=function(e,t){return this._transformToBoneReferal=t,this.parent=e,e.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this},i.prototype.detachFromBone=function(){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=null,this):this},i.prototype.rotate=function(t,r,n){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation=e.Vector3.Zero());var o;if(n&&n!==e.Space.LOCAL){if(this.parent){var s=this.parent.getWorldMatrix().clone();s.invert(),t=e.Vector3.TransformNormal(t,s)}o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),this.rotationQuaternion.multiplyToRef(o,this.rotationQuaternion);return this},i.prototype.rotateAround=function(t,i,r){return i.normalize(),this.rotationQuaternion||(this.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.copyFromFloats(0,0,0)),t.subtractToRef(this.position,e.Tmp.Vector3[0]),e.Matrix.TranslationToRef(e.Tmp.Vector3[0].x,e.Tmp.Vector3[0].y,e.Tmp.Vector3[0].z,e.Tmp.Matrix[0]),e.Tmp.Matrix[0].invertToRef(e.Tmp.Matrix[2]),e.Matrix.RotationAxisToRef(i,r,e.Tmp.Matrix[1]),e.Tmp.Matrix[2].multiplyToRef(e.Tmp.Matrix[1],e.Tmp.Matrix[2]),e.Tmp.Matrix[2].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[2]),e.Tmp.Matrix[2].decompose(e.Tmp.Vector3[0],e.Tmp.Quaternion[0],e.Tmp.Vector3[1]),this.position.addInPlace(e.Tmp.Vector3[1]),e.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this},i.prototype.translate=function(t,i,r){var n=t.scale(i);if(r&&r!==e.Space.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(n));else{var o=this.getPositionExpressedInLocalSpace().add(n);this.setPositionWithLocalVector(o)}return this},i.prototype.addRotation=function(t,i,r){var n;this.rotationQuaternion?n=this.rotationQuaternion:(n=e.Tmp.Quaternion[1],e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,n));var o=e.Tmp.Quaternion[0];return e.Quaternion.RotationYawPitchRollToRef(i,t,r,o),n.multiplyInPlace(o),this.rotationQuaternion||n.toEulerAnglesToRef(this.rotation),this},i.prototype.computeWorldMatrix=function(t){if(this._isWorldMatrixFrozen)return this._worldMatrix;if(!t&&this.isSynchronized(!0))return this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix;if(this._cache.position.copyFrom(this.position),this._cache.scaling.copyFrom(this.scaling),this._cache.pivotMatrixUpdated=!1,this._cache.billboardMode=this.billboardMode,this._currentRenderId=this.getScene().getRenderId(),this._childRenderId=this.getScene().getRenderId(),this._isDirty=!1,e.Matrix.ScalingToRef(this.scaling.x*this.scalingDeterminant,this.scaling.y*this.scalingDeterminant,this.scaling.z*this.scalingDeterminant,e.Tmp.Matrix[1]),this.rotationQuaternion){this.rotation.length()&&(this.rotationQuaternion.multiplyInPlace(e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)),this.rotation.copyFromFloats(0,0,0))}this.rotationQuaternion?(this.rotationQuaternion.toRotationMatrix(e.Tmp.Matrix[0]),this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,e.Tmp.Matrix[0]),this._cache.rotation.copyFrom(this.rotation));var r=this.getScene().activeCamera;if(this.infiniteDistance&&!this.parent&&r){var n=r.getWorldMatrix(),o=new e.Vector3(n.m[12],n.m[13],n.m[14]);e.Matrix.TranslationToRef(this.position.x+o.x,this.position.y+o.y,this.position.z+o.z,e.Tmp.Matrix[2])}else e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,e.Tmp.Matrix[2]);if(this._pivotMatrix.multiplyToRef(e.Tmp.Matrix[1],e.Tmp.Matrix[4]),e.Tmp.Matrix[4].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[5]),this.billboardMode!==i.BILLBOARDMODE_NONE&&r){if((this.billboardMode&i.BILLBOARDMODE_ALL)!==i.BILLBOARDMODE_ALL){var s=e.Tmp.Vector3[3];this.parent&&this.parent.getWorldMatrix?this._transformToBoneReferal?(this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),e.Tmp.Matrix[6]),e.Vector3.TransformCoordinatesToRef(this.position,e.Tmp.Matrix[6],s)):e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),s):s.copyFrom(this.position),s.subtractInPlace(r.globalPosition);var a=e.Tmp.Vector3[4].copyFromFloats(0,0,0);(this.billboardMode&i.BILLBOARDMODE_X)===i.BILLBOARDMODE_X&&(a.x=Math.atan2(-s.y,s.z)),(this.billboardMode&i.BILLBOARDMODE_Y)===i.BILLBOARDMODE_Y&&(a.y=Math.atan2(s.x,s.z)),(this.billboardMode&i.BILLBOARDMODE_Z)===i.BILLBOARDMODE_Z&&(a.z=Math.atan2(s.y,s.x)),e.Matrix.RotationYawPitchRollToRef(a.y,a.x,a.z,e.Tmp.Matrix[0])}else e.Tmp.Matrix[1].copyFrom(r.getViewMatrix()),e.Tmp.Matrix[1].setTranslationFromFloats(0,0,0),e.Tmp.Matrix[1].invertToRef(e.Tmp.Matrix[0]);e.Tmp.Matrix[1].copyFrom(e.Tmp.Matrix[5]),e.Tmp.Matrix[1].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[5])}return this._postMultiplyPivotMatrix&&e.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse,e.Tmp.Matrix[5]),e.Tmp.Matrix[5].multiplyToRef(e.Tmp.Matrix[2],this._localWorld),this.parent&&this.parent.getWorldMatrix?(this.billboardMode!==i.BILLBOARDMODE_NONE?(this._transformToBoneReferal?(this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),e.Tmp.Matrix[6]),e.Tmp.Matrix[5].copyFrom(e.Tmp.Matrix[6])):e.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix()),this._localWorld.getTranslationToRef(e.Tmp.Vector3[5]),e.Vector3.TransformCoordinatesToRef(e.Tmp.Vector3[5],e.Tmp.Matrix[5],e.Tmp.Vector3[5]),this._worldMatrix.copyFrom(this._localWorld),this._worldMatrix.setTranslation(e.Tmp.Vector3[5])):this._transformToBoneReferal?(this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),e.Tmp.Matrix[6]),e.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()):this._worldMatrix.copyFrom(this._localWorld),this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this.scaling.isNonUniform?this._updateNonUniformScalingState(!0):this.parent&&this.parent._nonUniformScaling?this._updateNonUniformScalingState(this.parent._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=e.Matrix.Invert(this._worldMatrix)),this._worldMatrixDeterminant=this._worldMatrix.determinant(),this._worldMatrix},i.prototype._afterComputeWorldMatrix=function(){},i.prototype.registerAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this},i.prototype.unregisterAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this},i.prototype.clone=function(t,r,n){var o=this,s=e.SerializationHelper.Clone((function(){return new i(t,o.getScene())}),this);if(s.name=t,s.id=t,r&&(s.parent=r),!n)for(var a=this.getDescendants(!0),l=0;le.Engine.CollisionsEpsilon&&o.position.addInPlace(o._diffPositionForCollisions),r&&o.onCollideObservable.notifyObservers(r),o.onCollisionPositionChangeObservable.notifyObservers(o.position)},o.getScene().addMesh(o),o._resyncLightSources(),o}return o(i,t),Object.defineProperty(i,"BILLBOARDMODE_NONE",{get:function(){return e.TransformNode.BILLBOARDMODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_X",{get:function(){return e.TransformNode.BILLBOARDMODE_X},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Y",{get:function(){return e.TransformNode.BILLBOARDMODE_Y},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Z",{get:function(){return e.TransformNode.BILLBOARDMODE_Z},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_ALL",{get:function(){return e.TransformNode.BILLBOARDMODE_ALL},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"facetNb",{get:function(){return this._facetNb},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"partitioningSubdivisions",{get:function(){return this._partitioningSubdivisions},set:function(e){this._partitioningSubdivisions=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"partitioningBBoxRatio",{get:function(){return this._partitioningBBoxRatio},set:function(e){this._partitioningBBoxRatio=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"mustDepthSortFacets",{get:function(){return this._facetDepthSort},set:function(e){this._facetDepthSort=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"facetDepthSortFrom",{get:function(){return this._facetDepthSortFrom},set:function(e){this._facetDepthSortFrom=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"isFacetDataEnabled",{get:function(){return this._facetDataEnabled},enumerable:!0,configurable:!0}),i.prototype._updateNonUniformScalingState=function(e){return!!t.prototype._updateNonUniformScalingState.call(this,e)&&(this._markSubMeshesAsMiscDirty(),!0)},Object.defineProperty(i.prototype,"onCollide",{set:function(e){this._onCollideObserver&&this.onCollideObservable.remove(this._onCollideObserver),this._onCollideObserver=this.onCollideObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onCollisionPositionChange",{set:function(e){this._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver),this._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"isOccluded",{get:function(){return this._isOccluded},set:function(e){this._isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"isOcclusionQueryInProgress",{get:function(){return this._isOcclusionQueryInProgress},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"visibility",{get:function(){return this._visibility},set:function(e){this._visibility!==e&&(this._visibility=e,this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"material",{get:function(){return this._material},set:function(e){this._material!==e&&(this._material=e,this.onMaterialChangedObservable.hasObservers&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&this._unBindEffect())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"receiveShadows",{get:function(){return this._receiveShadows},set:function(e){this._receiveShadows!==e&&(this._receiveShadows=e,this._markSubMeshesAsLightDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"hasVertexAlpha",{get:function(){return this._hasVertexAlpha},set:function(e){this._hasVertexAlpha!==e&&(this._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useVertexColors",{get:function(){return this._useVertexColors},set:function(e){this._useVertexColors!==e&&(this._useVertexColors=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"computeBonesUsingShaders",{get:function(){return this._computeBonesUsingShaders},set:function(e){this._computeBonesUsingShaders!==e&&(this._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"numBoneInfluencers",{get:function(){return this._numBoneInfluencers},set:function(e){this._numBoneInfluencers!==e&&(this._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"applyFog",{get:function(){return this._applyFog},set:function(e){this._applyFog!==e&&(this._applyFog=e,this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"layerMask",{get:function(){return this._layerMask},set:function(e){e!==this._layerMask&&(this._layerMask=e,this._resyncLightSources())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"collisionGroup",{get:function(){return this._collisionGroup},set:function(e){this._collisionGroup=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"_positions",{get:function(){return null},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"skeleton",{get:function(){return this._skeleton},set:function(e){this._skeleton&&this._skeleton.needInitialSkinMatrix&&this._skeleton._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._skeleton=e,this._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"AbstractMesh"},i.prototype.toString=function(t){var i="Name: "+this.name+", isInstance: "+(this instanceof e.InstancedMesh?"YES":"NO");return i+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0),this._skeleton&&(i+=", skeleton: "+this._skeleton.name),t&&(i+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],i+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingFreezeWorldMatrix?"YES":"NO")),i},i.prototype._rebuild=function(){if(this._occlusionQuery&&(this._occlusionQuery=null),this._edgesRenderer&&this._edgesRenderer._rebuild(),this.subMeshes)for(var e=0,t=this.subMeshes;e1&&!a._checkCollision(e)||this._collideForSubMesh(a,t,e)}return this},i.prototype._checkCollision=function(t){return this._boundingInfo&&this._boundingInfo._checkCollision(t)?(e.Matrix.ScalingToRef(1/t._radius.x,1/t._radius.y,1/t._radius.z,this._collisionsScalingMatrix),this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix,this._collisionsTransformMatrix),this._processCollisionsForSubMeshes(t,this._collisionsTransformMatrix),this):this},i.prototype._generatePointsArray=function(){return!1},i.prototype.intersects=function(t,i){var r=new e.PickingInfo;if(!(this.subMeshes&&this._boundingInfo&&t.intersectsSphere(this._boundingInfo.boundingSphere)&&t.intersectsBox(this._boundingInfo.boundingBox)))return r;if(!this._generatePointsArray())return r;var n,o,s=null;if(this._submeshesOctree&&this.useOctreeForPicking){var a=e.Ray.Transform(t,this.getWorldMatrix()),l=this._submeshesOctree.intersectsRay(a);o=l.length,n=l.data}else n=this.subMeshes,o=n.length;for(var h=0;h1)||c.canIntersects(t)){var u=c.intersects(t,this._positions,this.getIndices(),i);if(u&&(i||!s||u.distance65535){o=!0;break}this._depthSortedIndices=o?new Uint32Array(i):new Uint16Array(i)}if(this._facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!this._facetDepthSortFrom){var a=this.getScene().activeCamera;this._facetDepthSortFrom=a?a.position:e.Vector3.Zero()}this._depthSortedFacets=[];for(var l=0;le.Epsilon?n.maximum.x-n.minimum.x:e.Epsilon,this._bbSize.y=n.maximum.y-n.minimum.y>e.Epsilon?n.maximum.y-n.minimum.y:e.Epsilon,this._bbSize.z=n.maximum.z-n.minimum.z>e.Epsilon?n.maximum.z-n.minimum.z:e.Epsilon;var c=this._bbSize.x>this._bbSize.y?this._bbSize.x:this._bbSize.y;if(c=c>this._bbSize.z?c:this._bbSize.z,this._subDiv.max=this._partitioningSubdivisions,this._subDiv.X=Math.floor(this._subDiv.max*this._bbSize.x/c),this._subDiv.Y=Math.floor(this._subDiv.max*this._bbSize.y/c),this._subDiv.Z=Math.floor(this._subDiv.max*this._bbSize.z/c),this._subDiv.X=this._subDiv.X<1?1:this._subDiv.X,this._subDiv.Y=this._subDiv.Y<1?1:this._subDiv.Y,this._subDiv.Z=this._subDiv.Z<1?1:this._subDiv.Z,this._facetParameters.facetNormals=this.getFacetLocalNormals(),this._facetParameters.facetPositions=this.getFacetLocalPositions(),this._facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),this._facetParameters.bInfo=n,this._facetParameters.bbSize=this._bbSize,this._facetParameters.subDiv=this._subDiv,this._facetParameters.ratio=this.partitioningBBoxRatio,this._facetParameters.depthSort=this._facetDepthSort,this._facetDepthSort&&this._facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(this._invertedMatrix),e.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom,this._invertedMatrix,this._facetDepthSortOrigin),this._facetParameters.distanceTo=this._facetDepthSortOrigin),this._facetParameters.depthSortedFacets=this._depthSortedFacets,e.VertexData.ComputeNormals(t,i,r,this._facetParameters),this._facetDepthSort&&this._facetDepthSortEnabled){this._depthSortedFacets.sort(this._facetDepthSortFunction);for(var u=this._depthSortedIndices.length/3|0,l=0;lthis._subDiv.max||o<0||o>this._subDiv.max||s<0||s>this._subDiv.max?null:this._facetPartitioning[n+this._subDiv.max*o+this._subDiv.max*this._subDiv.max*s]},i.prototype.getClosestFacetAtCoordinates=function(t,i,r,n,o,s){void 0===o&&(o=!1),void 0===s&&(s=!0);var a=this.getWorldMatrix(),l=e.Tmp.Matrix[5];a.invertToRef(l);var h=e.Tmp.Vector3[8];e.Vector3.TransformCoordinatesFromFloatsToRef(t,i,r,l,h);var c=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,n,o,s);return n&&e.Vector3.TransformCoordinatesFromFloatsToRef(n.x,n.y,n.z,a,n),c},i.prototype.getClosestFacetAtLocalCoordinates=function(e,t,i,r,n,o){void 0===n&&(n=!1),void 0===o&&(o=!0);var s=null,a=0,l=0,h=0,c=0,u=0,f=0,d=0,p=0,m=this.getFacetLocalPositions(),_=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;for(var v,y,b,x=Number.MAX_VALUE,T=x,E=0;E=0||n&&!o&&c<=0)&&(c=y.x*b.x+y.y*b.y+y.z*b.z,u=-(y.x*e+y.y*t+y.z*i-c)/(y.x*y.x+y.y*y.y+y.z*y.z),f=e+y.x*u,d=t+y.y*u,p=i+y.z*u,a=f-e,l=d-t,h=p-i,(T=a*a+l*l+h*h)0&&-1===this.includedOnlyMeshes.indexOf(e))&&(!(this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e))&&((0===this.includeOnlyWithLayerMask||0!=(this.includeOnlyWithLayerMask&e.layerMask))&&!(0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask)))},i.prototype.getWorldMatrix=function(){this._currentRenderId=this.getScene().getRenderId(),this._childRenderId=this._currentRenderId;var t=this._getWorldMatrix();return this.parent&&this.parent.getWorldMatrix?(this._parentedWorldMatrix||(this._parentedWorldMatrix=e.Matrix.Identity()),t.multiplyToRef(this.parent.getWorldMatrix(),this._parentedWorldMatrix),this._markSyncedWithParent(),this._parentedWorldMatrix):t},i.CompareLightsPriority=function(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority},i.prototype.dispose=function(e,i){void 0===i&&(i=!1),this._shadowGenerator&&(this._shadowGenerator.dispose(),this._shadowGenerator=null),this.getScene().stopAnimation(this);for(var r=0,n=this.getScene().meshes;r0&&(t.excludedMeshesIds=[],this.excludedMeshes.forEach((function(e){t.excludedMeshesIds.push(e.id)}))),this.includedOnlyMeshes.length>0&&(t.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((function(e){t.includedOnlyMeshesIds.push(e.id)}))),e.Animation.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t},i.GetConstructorFromName=function(t,i,r){var n=e.Node.Construct("Light_Type_"+t,i,r);return n||null},i.Parse=function(t,r){var n=i.GetConstructorFromName(t.type,t.name,r);if(!n)return null;var o=e.SerializationHelper.Parse(n,t,r);if(t.excludedMeshesIds&&(o._excludedMeshesIds=t.excludedMeshesIds),t.includedOnlyMeshesIds&&(o._includedOnlyMeshesIds=t.includedOnlyMeshesIds),t.parentId&&(o._waitingParentId=t.parentId),t.animations){for(var s=0;s-1?(e.Tools.Error("You're trying to reuse a post process not defined as reusable."),0):(null==i||i<0?this._postProcesses.push(t):null===this._postProcesses[i]?this._postProcesses[i]=t:this._postProcesses.splice(i,0,t),this._cascadePostProcessesToRigCams(),this._postProcesses.indexOf(t))},i.prototype.detachPostProcess=function(e){var t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._cascadePostProcessesToRigCams()},i.prototype.getWorldMatrix=function(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)},i.prototype._getViewMatrix=function(){return e.Matrix.Identity()},i.prototype.getViewMatrix=function(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childRenderId=this._currentRenderId,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._computedViewMatrix)},i.prototype.freezeProjectionMatrix=function(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)},i.prototype.unfreezeProjectionMatrix=function(){this._doNotComputeProjectionMatrix=!1},i.prototype.getProjectionMatrix=function(t){if(this._doNotComputeProjectionMatrix||!t&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;var r=this.getEngine(),n=this.getScene();if(this.mode===i.PERSPECTIVE_CAMERA)this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=r.getAspectRatio(this),this.minZ<=0&&(this.minZ=.1),n.useRightHandedSystem?e.Matrix.PerspectiveFovRHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED):e.Matrix.PerspectiveFovLHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED);else{var o=r.getRenderWidth()/2,s=r.getRenderHeight()/2;n.useRightHandedSystem?e.Matrix.OrthoOffCenterRHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix):e.Matrix.OrthoOffCenterLHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=r.getRenderWidth(),this._cache.renderHeight=r.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix},i.prototype.getTransformationMatrix=function(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix},i.prototype.updateFrustumPlanes=function(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?e.Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=e.Frustum.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)},i.prototype.isInFrustum=function(e){return this.updateFrustumPlanes(),e.isInFrustum(this._frustumPlanes)},i.prototype.isCompletelyInFrustum=function(e){return this.updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)},i.prototype.getForwardRay=function(t,i,r){void 0===t&&(t=100),i||(i=this.getWorldMatrix()),r||(r=this.position);var n=new e.Vector3(0,0,1),o=e.Vector3.TransformNormal(n,i),s=e.Vector3.Normalize(o);return new e.Ray(r,s,t)},i.prototype.dispose=function(e,r){for(void 0===r&&(r=!1),this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){var n=this._rigCameras.pop();n&&n.dispose()}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses=[];else if(this.cameraRigMode!==i.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses=[];else for(var o=this._postProcesses.length;--o>=0;){var s=this._postProcesses[o];s&&s.dispose(this)}for(var o=this.customRenderTargets.length;--o>=0;)this.customRenderTargets[o].dispose();this.customRenderTargets=[],this._activeMeshes.dispose(),t.prototype.dispose.call(this,e,r)},Object.defineProperty(i.prototype,"leftCamera",{get:function(){return this._rigCameras.length<1?null:this._rigCameras[0]},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"rightCamera",{get:function(){return this._rigCameras.length<2?null:this._rigCameras[1]},enumerable:!0,configurable:!0}),i.prototype.getLeftTarget=function(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()},i.prototype.getRightTarget=function(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()},i.prototype.setCameraRigMode=function(t,r){if(this.cameraRigMode!==t){for(;this._rigCameras.length>0;){var n=this._rigCameras.pop();n&&n.dispose()}if(this.cameraRigMode=t,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=r.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==i.RIG_MODE_NONE){var o=this.createRigCamera(this.name+"_L",0),s=this.createRigCamera(this.name+"_R",1);o&&s&&(this._rigCameras.push(o),this._rigCameras.push(s))}switch(this.cameraRigMode){case i.RIG_MODE_STEREOSCOPIC_ANAGLYPH:this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.AnaglyphPostProcess(this.name+"_anaglyph",1,this._rigCameras);break;case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case i.RIG_MODE_STEREOSCOPIC_OVERUNDER:var a=this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.StereoscopicInterlacePostProcess(this.name+"_stereoInterlace",this._rigCameras,a);break;case i.RIG_MODE_VR:var l=r.vrCameraMetrics||e.VRCameraMetrics.GetDefault();this._rigCameras[0]._cameraRigParams.vrMetrics=l,this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0]._cameraRigParams.vrHMatrix=l.leftHMatrix,this._rigCameras[0]._cameraRigParams.vrPreViewMatrix=l.leftPreViewMatrix,this._rigCameras[0].getProjectionMatrix=this._rigCameras[0]._getVRProjectionMatrix,this._rigCameras[1]._cameraRigParams.vrMetrics=l,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1]._cameraRigParams.vrHMatrix=l.rightHMatrix,this._rigCameras[1]._cameraRigParams.vrPreViewMatrix=l.rightPreViewMatrix,this._rigCameras[1].getProjectionMatrix=this._rigCameras[1]._getVRProjectionMatrix,l.compensateDistortion&&(this._rigCameras[0]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",this._rigCameras[0],!1,l),this._rigCameras[1]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",this._rigCameras[1],!0,l));break;case i.RIG_MODE_WEBVR:if(r.vrDisplay){var h=r.vrDisplay.getEyeParameters("left"),c=r.vrDisplay.getEyeParameters("right");this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0].setCameraRigParameter("left",!0),this._rigCameras[0].setCameraRigParameter("specs",r.specs),this._rigCameras[0].setCameraRigParameter("eyeParameters",h),this._rigCameras[0].setCameraRigParameter("frameData",r.frameData),this._rigCameras[0].setCameraRigParameter("parentCamera",r.parentCamera),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0].getProjectionMatrix=this._getWebVRProjectionMatrix,this._rigCameras[0].parent=this,this._rigCameras[0]._getViewMatrix=this._getWebVRViewMatrix,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1].setCameraRigParameter("eyeParameters",c),this._rigCameras[1].setCameraRigParameter("specs",r.specs),this._rigCameras[1].setCameraRigParameter("frameData",r.frameData),this._rigCameras[1].setCameraRigParameter("parentCamera",r.parentCamera),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1].getProjectionMatrix=this._getWebVRProjectionMatrix,this._rigCameras[1].parent=this,this._rigCameras[1]._getViewMatrix=this._getWebVRViewMatrix,i.UseAlternateWebVRRendering&&(this._rigCameras[1]._skipRendering=!0,this._rigCameras[0]._alternateCamera=this._rigCameras[1])}}this._cascadePostProcessesToRigCams(),this.update()}},i.prototype._getVRProjectionMatrix=function(){return e.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix},i.prototype._updateCameraRotationMatrix=function(){},i.prototype._updateWebVRCameraRotationMatrix=function(){},i.prototype._getWebVRProjectionMatrix=function(){return e.Matrix.Identity()},i.prototype._getWebVRViewMatrix=function(){return e.Matrix.Identity()},i.prototype.setCameraRigParameter=function(t,i){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[t]=i,"interaxialDistance"===t&&(this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(i/.0637))},i.prototype.createRigCamera=function(e,t){return null},i.prototype._updateRigCameras=function(){for(var e=0;ei._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0},t.frontToBackSortCompare=function(e,t){return e._distanceToCamerat._distanceToCamera?1:0},t.prototype.prepare=function(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this._spriteManagers.reset(),this._edgesRenderers.reset()},t.prototype.dispose=function(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()},t.prototype.dispatch=function(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!==i&&void 0!==i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),null!==t._edgesRenderer&&void 0!==t._edgesRenderer&&t._edgesRenderer.isEnabled&&this._edgesRenderers.push(t._edgesRenderer))},t.prototype.dispatchSprites=function(e){this._spriteManagers.push(e)},t.prototype.dispatchParticles=function(e){this._particleSystems.push(e)},t.prototype._renderParticles=function(e){if(0!==this._particleSystems.length){var t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(var i=0;i0){for(var e=0,t=this._transientComponents;er.LongPressDelay&&Math.abs(n._startingPointerPosition.x-n._pointerX)r.DoubleClickDelay&&!s._doubleClickOccured||e!==s._previousButtonPressed)&&(s._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,i(t,s._currentPickResult))},this._initClickEvent=function(i,n,o,a){var l=new t;s._currentPickResult=null;var h=null,c=i.hasSpecificMask(e.PointerEventTypes.POINTERPICK)||n.hasSpecificMask(e.PointerEventTypes.POINTERPICK)||i.hasSpecificMask(e.PointerEventTypes.POINTERTAP)||n.hasSpecificMask(e.PointerEventTypes.POINTERTAP)||i.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)||n.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP);if(!c&&e.ActionManager&&e.ActionManager.HasPickTriggers&&(h=s._initActionManager(h,l))&&(c=h.hasPickTriggers),c){var u=o.button;if(l.hasSwiped=Math.abs(s._startingPointerPosition.x-s._pointerX)>r.DragMovementThreshold||Math.abs(s._startingPointerPosition.y-s._pointerY)>r.DragMovementThreshold,!l.hasSwiped){var f=!r.ExclusiveDoubleClickMode;f||(f=!i.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)&&!n.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP))&&!e.ActionManager.HasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)&&(h=s._initActionManager(h,l))&&(f=!h.hasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)),f?(Date.now()-s._previousStartingPointerTime>r.DoubleClickDelay||u!==s._previousButtonPressed)&&(l.singleClick=!0,a(l,s._currentPickResult)):(s._previousDelayedSimpleClickTimeout=s._delayedSimpleClickTimeout,s._delayedSimpleClickTimeout=window.setTimeout(s._delayedSimpleClick.bind(s,u,l,a),r.DoubleClickDelay));var d=i.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)||n.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP);!d&&e.ActionManager.HasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)&&(h=s._initActionManager(h,l))&&(d=h.hasSpecificTrigger(e.ActionManager.OnDoublePickTrigger)),d&&(u===s._previousButtonPressed&&Date.now()-s._previousStartingPointerTime0&&(i=s.pickSprite(s._unTranslatedPointerX,s._unTranslatedPointerY,s._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,t.button){case 0:i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnLeftPickTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t));break;case 1:i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnCenterPickTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t));break;case 2:i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnRightPickTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickDownTrigger,e.ActionEvent.CreateNewFromSprite(i.pickedSprite,s,t))}}},this._onPointerUp=function(t){0!==s._totalPointersPressed&&(s._totalPointersPressed--,s._pickedUpMesh=null,s._meshPickProceed=!1,s._updatePointerPosition(t),s._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,t,(function(i,n){if(s.onPrePointerObservable.hasObservers())if(i.ignore){if(s._checkPrePointerObservable(null,t,e.PointerEventTypes.POINTERUP))return}else if(!i.hasSwiped){if(i.singleClick&&s.onPrePointerObservable.hasSpecificMask(e.PointerEventTypes.POINTERTAP)&&s._checkPrePointerObservable(null,t,e.PointerEventTypes.POINTERTAP))return;if(i.doubleClick&&s.onPrePointerObservable.hasSpecificMask(e.PointerEventTypes.POINTERDOUBLETAP)&&s._checkPrePointerObservable(null,t,e.PointerEventTypes.POINTERDOUBLETAP))return}if(s.cameraToUseForPointers||s.activeCamera){if(s._pointerCaptures[t.pointerId]=!1,s.pointerUpPredicate||(s.pointerUpPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()}),!s._meshPickProceed&&(e.ActionManager&&e.ActionManager.HasTriggers||s.onPointerObservable.hasObservers())&&s._initActionManager(null,i),n||(n=s._currentPickResult),s._processPointerUp(n,t,i),!i.ignore&&s.spriteManagers.length>0){var o=s.pickSprite(s._unTranslatedPointerX,s._unTranslatedPointerY,s._spritePredicate,!1,s.cameraToUseForPointers||void 0);o&&(o.hit&&o.pickedSprite&&o.pickedSprite.actionManager&&(o.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickUpTrigger,e.ActionEvent.CreateNewFromSprite(o.pickedSprite,s,t)),o.pickedSprite.actionManager&&Math.abs(s._startingPointerPosition.x-s._pointerX)0)return!1;var t,i=this.getEngine();for(t=0;t0,o=0,s=this._isReadyForMeshStage;o0)for(var a=0,l=this.activeCameras;a0},enumerable:!0,configurable:!0}),r.prototype.executeWhenReady=function(e){var t=this;this.onReadyObservable.add(e),-1===this._executeWhenReadyTimeoutId&&(this._executeWhenReadyTimeoutId=setTimeout((function(){t._checkIsReady()}),150))},r.prototype.whenReadyAsync=function(){var e=this;return new Promise(function(t){e.executeWhenReady((function(){t()}))})},r.prototype._checkIsReady=function(){var e=this;if(this._registerTransientComponents(),this.isReady())return this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=-1);this._executeWhenReadyTimeoutId=setTimeout((function(){e._checkIsReady()}),150)},r.prototype.beginWeightedAnimation=function(e,t,i,r,n,o,s,a,l){void 0===r&&(r=1),void 0===o&&(o=1);var h=this.beginAnimation(e,t,i,n,o,s,a,!1,l);return h.weight=r,h},r.prototype.beginAnimation=function(t,i,r,n,o,s,a,l,h){void 0===o&&(o=1),void 0===l&&(l=!0),i>r&&o>0&&(o*=-1),l&&this.stopAnimation(t,void 0,h),a||(a=new e.Animatable(this,t,i,r,n,o,s));var c=!h||h(t);if(t.animations&&c&&a.appendAnimations(t,t.animations),t.getAnimatables)for(var u=t.getAnimatables(),f=0;f0)return;this._animationTimeLast=t}var i=this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale;this._animationTime+=i,this._animationTimeLast=t;for(var r=0;r0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t},r.prototype.removeParticleSystem=function(e){var t=this.particleSystems.indexOf(e);return-1!==t&&this.particleSystems.splice(t,1),t},r.prototype.removeAnimation=function(e){var t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t},r.prototype.removeAnimationGroup=function(e){var t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t},r.prototype.removeMultiMaterial=function(e){var t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),t},r.prototype.removeMaterial=function(e){var t=this.materials.indexOf(e);return-1!==t&&this.materials.splice(t,1),t},r.prototype.removeActionManager=function(e){var t=this.actionManagers.indexOf(e);return-1!==t&&this.actionManagers.splice(t,1),t},r.prototype.removeTexture=function(e){var t=this.textures.indexOf(e);return-1!==t&&this.textures.splice(t,1),t},r.prototype.addLight=function(e){this.lights.push(e),this.sortLightsByPriority();for(var t=0,i=this.meshes;t-1&&(this.geometries.splice(t,1),this.collisionCoordinator&&this.collisionCoordinator.onGeometryDeleted(e),this.onGeometryRemovedObservable.notifyObservers(e),!0)},r.prototype.getGeometries=function(){return this.geometries},r.prototype.getMeshByID=function(e){for(var t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null},r.prototype.getLastEntryByID=function(e){var t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null},r.prototype.getNodeByID=function(e){var t=this.getMeshByID(e);if(t)return t;var i=this.getLightByID(e);if(i)return i;var r=this.getCameraByID(e);return r||this.getBoneByID(e)},r.prototype.getNodeByName=function(e){var t=this.getMeshByName(e);if(t)return t;var i=this.getLightByName(e);if(i)return i;var r=this.getCameraByName(e);return r||this.getBoneByName(e)},r.prototype.getMeshByName=function(e){for(var t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null},r.prototype.getSkeletonById=function(e){for(var t=0;t0&&(a.alwaysSelectAsActiveMesh||0!=(a.layerMask&this.activeCamera.layerMask)&&a.isInFrustum(this._frustumPlanes))&&(this._activeMeshes.push(a),this.activeCamera._activeMeshes.push(a),a._activate(this._renderId),l!==a&&l._activate(this._renderId),this._activeMesh(a,l)))));if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(var c=0;c0){var n,o;if(t.useOctreeForRenderingSelection&&void 0!==t._submeshesOctree&&null!==t._submeshesOctree){var s=t._submeshesOctree.select(this._frustumPlanes);n=s.length,o=s.data}else o=t.subMeshes,n=o.length;for(var a,l=0;l0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),i&&i.customRenderTargets&&i.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(i.customRenderTargets),this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){e.Tools.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(var s=0;s0),this._renderId++}for(var h=0,c=this._cameraDrawRenderTargetStage;h-1&&(n.trigger===e.ActionManager.OnIntersectionExitTrigger&&n._executeCurrent(e.ActionEvent.CreateNew(i,void 0,s)),i.actionManager.hasSpecificTrigger(e.ActionManager.OnIntersectionExitTrigger,(function(t){var i=t instanceof e.AbstractMesh?t:t.mesh;return s===i}))&&n.trigger!==e.ActionManager.OnIntersectionExitTrigger||i._intersectionsInProgress.splice(l,1))}}}},r.prototype.render=function(t){if(void 0===t&&(t=!0),!this.isDisposed){if(this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(e.ActionManager.OnEveryFrameTrigger),this.simplificationQueue&&!this.simplificationQueue.running&&this.simplificationQueue.executeNext(),this._engine.isDeterministicLockStep()){var i=Math.max(r.MinDeltaTime,Math.min(this._engine.getDeltaTime(),r.MaxDeltaTime))+this._timeAccumulator,n=1e3/60;this._physicsEngine&&(n=1e3*this._physicsEngine.getTimeStep());var o=0,s=this._engine.getLockstepMaxSteps(),a=Math.floor(i/60);a=Math.min(a,s);do{this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=.06*n,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this._physicsEngine&&(this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(n/1e3),this.onAfterPhysicsObservable.notifyObservers(this)),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,o++,i-=n}while(i>0&&o0)for(var c=0;c0),this._intermediateRendering=!0;for(var m=0;m0),this._intermediateRendering=!1,this._renderId++}if(this.customRenderTargets.length>0&&d.restoreDefaultFramebuffer(),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.activeCamera=p,this.proceduralTexturesEnabled){e.Tools.StartPerformanceCounter("Procedural textures",this.proceduralTextures.length>0);for(var g=0;g0)}if((this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil),this.shadowsEnabled)for(var y=0;y0)for(var c=0;c0&&this._engine.clear(null,!1,!0,!0),this._processSubCameras(this.activeCameras[c]);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera)}this._checkIntersections(),e.AudioEngine&&this._updateAudioParameters(),this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this);for(var f=0;f0?this.activeCameras[0]:this.activeCamera)&&i.canUseWebAudio&&i.audioContext){i.audioContext.listener.setPosition(t.position.x,t.position.y,t.position.z),t.rigCameras&&t.rigCameras.length>0&&(t=t.rigCameras[0]);var r=e.Matrix.Invert(t.getViewMatrix()),n=e.Vector3.TransformNormal(new e.Vector3(0,0,-1),r);n.normalize(),isNaN(n.x)||isNaN(n.y)||isNaN(n.z)||i.audioContext.listener.setOrientation(n.x,n.y,n.z,0,1,0);var o;for(o=0;o-1&&this._engine.scenes.splice(a,1),this._engine.wipeCaches(!0),this._isDisposed=!0},Object.defineProperty(r.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!0,configurable:!0}),r.prototype.disposeSounds=function(){if(this._mainSoundTrack){this.mainSoundTrack.dispose();for(var e=0;e=n.distance))&&(n=h,r)))break}return n||new e.PickingInfo},r.prototype._internalMultiPick=function(t,i){if(!e.PickingInfo)return null;for(var r=new Array,n=0;n0)for(var s=0;s=o.distance))&&(o=l,r))break}}return o||new e.PickingInfo},r.prototype.pick=function(t,i,r,n,o){var s=this;if(!e.PickingInfo)return null;var a=this._internalPick((function(e){return s.createPickingRayToRef(t,i,e,s._tempPickingRay,o||null),s._tempPickingRay}),r,n);return a&&(a.ray=this.createPickingRay(t,i,e.Matrix.Identity(),o||null)),a},r.prototype.pickSprite=function(e,t,i,r,n){return this.createPickingRayInCameraSpaceToRef(e,t,this._tempPickingRay,n),this._internalPickSprites(this._tempPickingRay,i,r,n)},r.prototype.pickWithRay=function(t,i,r){var n=this,o=this._internalPick((function(i){return n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(n._pickWithRayInverseMatrix),n._cachedRayForTransform||(n._cachedRayForTransform=e.Ray.Zero()),e.Ray.TransformToRef(t,n._pickWithRayInverseMatrix,n._cachedRayForTransform),n._cachedRayForTransform}),i,r);return o&&(o.ray=t),o},r.prototype.multiPick=function(e,t,i,r){var n=this;return this._internalMultiPick((function(i){return n.createPickingRay(e,t,i,r||null)}),i)},r.prototype.multiPickWithRay=function(t,i){var r=this;return this._internalMultiPick((function(i){return r._pickWithRayInverseMatrix||(r._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(r._pickWithRayInverseMatrix),r._cachedRayForTransform||(r._cachedRayForTransform=e.Ray.Zero()),e.Ray.TransformToRef(t,r._pickWithRayInverseMatrix,r._cachedRayForTransform),r._cachedRayForTransform}),i)},r.prototype.setPointerOverMesh=function(t){this._pointerOverMesh!==t&&(this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)),this._pointerOverMesh=t,this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)))},r.prototype.getPointerOverMesh=function(){return this._pointerOverMesh},r.prototype.setPointerOverSprite=function(t){this._pointerOverSprite!==t&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=t,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)))},r.prototype.getPointerOverSprite=function(){return this._pointerOverSprite},r.prototype.getPhysicsEngine=function(){return this._physicsEngine},r.prototype.enablePhysics=function(t,i){if(void 0===t&&(t=null),this._physicsEngine)return!0;try{return this._physicsEngine=new e.PhysicsEngine(t,i),!0}catch(t){return e.Tools.Error(t.message),!1}},r.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},r.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},r.prototype.deleteCompoundImpostor=function(e){var t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},r.prototype._rebuildGeometries=function(){for(var e=0,t=this.geometries;e=0&&this._scene.textures.splice(e,1),void 0!==this._texture&&(this.releaseInternalTexture(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear())}},t.prototype.serialize=function(){if(!this.name)return null;var t=e.SerializationHelper.Serialize(this);return e.Animation.AppendSerializedAnimations(this,t),t},t.WhenAllReady=function(e,t){var i=e.length;if(0===i)return void t();for(var r,n,o=0;o0},enumerable:!0,configurable:!0}),r.prototype.getLODLevels=function(){return this._LODLevels},r.prototype._sortLODLevels=function(){this._LODLevels.sort((function(e,t){return e.distancet.distance?-1:0}))},r.prototype.addLODLevel=function(t,i){if(i&&i._masterMesh)return e.Tools.Warn("You cannot use a mesh as LOD level twice"),this;var r=new e.MeshLODLevel(t,i);return this._LODLevels.push(r),i&&(i._masterMesh=this),this._sortLODLevels(),this},r.prototype.getLODLevelAtDistance=function(e){for(var t=0;tr)return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,this._LODLevels[this._LODLevels.length-1].mesh),this;for(var n=0;n0;this.computeWorldMatrix();var a=this.material||o.defaultMaterial;if(a)if(a.storeEffectOnSubMeshes)for(var l=0,h=this.subMeshes;l4,s=o?this.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind):null,a=o?this.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind):null,l=this.skeleton.getTransformMatrices(this),h=e.Tmp.Vector3[0],c=e.Tmp.Matrix[0],u=e.Tmp.Matrix[1],f=0,d=0;d0&&(e.Matrix.FromFloat32ArrayToRefScaled(l,Math.floor(16*r[f+p]),m,u),c.addToSelf(u));if(o)for(p=0;p<4;p++)(m=a[f+p])>0&&(e.Matrix.FromFloat32ArrayToRefScaled(l,Math.floor(16*s[f+p]),m,u),c.addToSelf(u));e.Vector3.TransformCoordinatesFromFloatsToRef(i[d],i[d+1],i[d+2],c,h),h.toArray(i,d)}}return i},r.prototype._createGlobalSubMesh=function(t){var i=this.getTotalVertices();if(!i||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){var r=this.getIndices();if(!r)return null;var n=r.length,o=!1;if(t)o=!0;else for(var s=0,a=this.subMeshes;s=n){o=!0;break}if(l.verticesStart+l.verticesCount>=i){o=!0;break}}if(!o)return this.subMeshes[0]}return this.releaseSubMeshes(),new e.SubMesh(0,0,i,0,this.getTotalIndices(),this)},r.prototype.subdivide=function(t){if(!(t<1)){for(var i=this.getTotalIndices(),r=i/t|0,n=0;r%3!=0;)r++;this.releaseSubMeshes();for(var o=0;o=i);o++)e.SubMesh.CreateFromIndices(0,n,Math.min(r,i-n),this),n+=r;this.synchronizeInstances()}},r.prototype.setVerticesData=function(t,i,r,n){if(void 0===r&&(r=!1),this._geometry)this._geometry.setVerticesData(t,i,r,n);else{var o=new e.VertexData;o.set(i,t);var s=this.getScene();new e.Geometry(e.Geometry.RandomId(),s,o,r,this)}return this},r.prototype.markVerticesDataAsUpdatable=function(e,t){void 0===t&&(t=!0);var i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)},r.prototype.setVerticesBuffer=function(t){return this._geometry||(this._geometry=e.Geometry.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(t),this},r.prototype.updateVerticesData=function(e,t,i,r){return this._geometry?(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this},r.prototype.updateMeshPositions=function(t,i){void 0===i&&(i=!0);var r=this.getVerticesData(e.VertexBuffer.PositionKind);if(!r)return this;if(t(r),this.updateVerticesData(e.VertexBuffer.PositionKind,r,!1,!1),i){var n=this.getIndices(),o=this.getVerticesData(e.VertexBuffer.NormalKind);if(!o)return this;e.VertexData.ComputeNormals(r,n,o),this.updateVerticesData(e.VertexBuffer.NormalKind,o,!1,!1)}return this},r.prototype.makeGeometryUnique=function(){if(!this._geometry)return this;var t=this._geometry,i=this._geometry.copy(e.Geometry.RandomId());return t.releaseForMesh(this,!0),i.applyToMesh(this),this},r.prototype.setIndices=function(t,i,r){if(void 0===i&&(i=null),void 0===r&&(r=!1),this._geometry)this._geometry.setIndices(t,i,r);else{var n=new e.VertexData;n.indices=t;var o=this.getScene();new e.Geometry(e.Geometry.RandomId(),o,n,r,this)}return this},r.prototype.updateIndices=function(e,t){return this._geometry?(this._geometry.updateIndices(e,t),this):this},r.prototype.toLeftHanded=function(){return this._geometry?(this._geometry.toLeftHanded(),this):this},r.prototype._bind=function(t,i,r){if(!this._geometry)return this;var n,o=this.getScene().getEngine();if(this._unIndexed)n=null;else switch(r){case e.Material.PointFillMode:n=null;break;case e.Material.WireFrameFillMode:n=t.getLinesIndexBuffer(this.getIndices(),o);break;default:case e.Material.TriangleFillMode:n=this._unIndexed?null:this._geometry.getIndexBuffer()}return this._geometry._bind(i,n),this},r.prototype._draw=function(t,i,r,n){if(void 0===n&&(n=!1),!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._onBeforeDrawObservable&&this._onBeforeDrawObservable.notifyObservers(this);var o=this.getScene(),s=o.getEngine();if(this._unIndexed||i==e.Material.PointFillMode?s.drawArraysType(i,t.verticesStart,t.verticesCount,r):i==e.Material.WireFrameFillMode?s.drawElementsType(i,0,t.linesIndexCount,r):s.drawElementsType(i,t.indexStart,t.indexCount,r),o._isAlternateRenderingEnabled&&!n){var a=t.effect||this._effectiveMaterial.getEffect();if(!a||!o.activeCamera)return this;o._switchToAlternateCameraConfiguration(!0),this._effectiveMaterial.bindView(a),this._effectiveMaterial.bindViewProjection(a),s.setViewport(o.activeCamera._alternateCamera.viewport),this._draw(t,i,r,!0),s.setViewport(o.activeCamera.viewport),o._switchToAlternateCameraConfiguration(!1),this._effectiveMaterial.bindView(a),this._effectiveMaterial.bindViewProjection(a)}return this},r.prototype.registerBeforeRender=function(e){return this.onBeforeRenderObservable.add(e),this},r.prototype.unregisterBeforeRender=function(e){return this.onBeforeRenderObservable.removeCallback(e),this},r.prototype.registerAfterRender=function(e){return this.onAfterRenderObservable.add(e),this},r.prototype.unregisterAfterRender=function(e){return this.onAfterRenderObservable.removeCallback(e),this},r.prototype._getInstancesRenderList=function(e){var t=this.getScene();if(this._batchCache.mustReturn=!1,this._batchCache.renderSelf[e]=this.isEnabled()&&this.isVisible,this._batchCache.visibleInstances[e]=null,this._visibleInstances){var i=t.getRenderId(),r=t._isInIntermediateRendering()?this._visibleInstances.intermediateDefaultRenderId:this._visibleInstances.defaultRenderId;this._batchCache.visibleInstances[e]=this._visibleInstances[i];var n=this._renderId;!this._batchCache.visibleInstances[e]&&r&&(this._batchCache.visibleInstances[e]=this._visibleInstances[r],i=Math.max(r,i),n=Math.max(this._visibleInstances.selfDefaultRenderId,i));var o=this._batchCache.visibleInstances[e];if(o&&o.length){if(this._renderIdForInstances[e]===i)return this._batchCache.mustReturn=!0,this._batchCache;i!==n&&(this._batchCache.renderSelf[e]=!1)}this._renderIdForInstances[e]=i}return this._batchCache},r.prototype._renderWithInstances=function(t,i,r,n,o){var s=r.visibleInstances[t._id];if(!s)return this;for(var a=s.length+1,l=16*a*4,h=this._instancesBufferSize,c=this._instancesBuffer;this._instancesBufferSizes-1)&&(c=s-1),h>.001){for(var d=1/h,u=0;u<4;u++)n[l+u]*=d;if(o)for(var u=0;u<4;u++)o[l+u]*=d}else c>=4?(o[l+c-4]=1-h,r[l+c-4]=t):(n[l+c]=1-h,i[l+c]=t)}this.setVerticesData(e.VertexBuffer.MatricesIndicesKind,i),r&&this.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,r),this.setVerticesData(e.VertexBuffer.MatricesWeightsKind,n),o&&this.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,o)}},r.prototype._checkDelayState=function(){var t=this.getScene();return this._geometry?this._geometry.load(t):this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADING,this._queueLoad(t)),this},r.prototype._queueLoad=function(t){var i=this;t._addPendingData(this);var r=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return e.Tools.LoadFile(this.delayLoadingFile,(function(r){r instanceof ArrayBuffer?i._delayLoadingFunction(r,i):i._delayLoadingFunction(JSON.parse(r),i),i.instances.forEach((function(e){e._syncSubMeshes()})),i.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,t._removePendingData(i)}),(function(){}),t.database,r),this},r.prototype.isInFrustum=function(t){return this.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADING&&(!!i.prototype.isInFrustum.call(this,t)&&(this._checkDelayState(),!0))},r.prototype.setMaterialByID=function(e){var t,i=this.getScene().materials;for(t=i.length-1;t>-1;t--)if(i[t].id===e)return this.material=i[t],this;var r=this.getScene().multiMaterials;for(t=r.length-1;t>-1;t--)if(r[t].id===e)return this.material=r[t],this;return this},r.prototype.getAnimatables=function(){var e=new Array;return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e},r.prototype.bakeTransformIntoVertices=function(t){if(!this.isVerticesDataPresent(e.VertexBuffer.PositionKind))return this;var i=this.subMeshes.splice(0);this._resetPointsArrayCache();var r,n=this.getVerticesData(e.VertexBuffer.PositionKind),o=new Array;for(r=0;r-1&&(o.morphTargetManager=i.getMorphTargetManagerById(t.morphTargetManagerId)),t.skeletonId>-1&&(o.skeleton=i.getLastSkeletonByID(t.skeletonId),t.numBoneInfluencers&&(o.numBoneInfluencers=t.numBoneInfluencers)),t.animations){for(var s=0;s4,h=l?this.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind):null,c=l?this.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind):null,u=t.getTransformMatrices(this),f=e.Vector3.Zero(),d=new e.Matrix,p=new e.Matrix,m=0,_=0;_0&&(e.Matrix.FromFloat32ArrayToRefScaled(u,Math.floor(16*o[m+a]),g,p),d.addToSelf(p));if(l)for(a=0;a<4;a++)(g=c[m+a])>0&&(e.Matrix.FromFloat32ArrayToRefScaled(u,Math.floor(16*h[m+a]),g,p),d.addToSelf(p));e.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[_],this._sourcePositions[_+1],this._sourcePositions[_+2],d,f),f.toArray(r,_),e.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[_],this._sourceNormals[_+1],this._sourceNormals[_+2],d,f),f.toArray(n,_),d.reset()}return this.updateVerticesData(e.VertexBuffer.PositionKind,r),this.updateVerticesData(e.VertexBuffer.NormalKind,n),this},r.MinMax=function(t){var i=null,r=null;return t.forEach((function(e,t,n){var o=e.getBoundingInfo(),s=o.boundingBox;i&&r?(i.minimizeInPlace(s.minimumWorld),r.maximizeInPlace(s.maximumWorld)):(i=s.minimumWorld,r=s.maximumWorld)})),i&&r?{min:i,max:r}:{min:e.Vector3.Zero(),max:e.Vector3.Zero()}},r.Center=function(t){var i=t instanceof Array?r.MinMax(t):t;return e.Vector3.Center(i.min,i.max)},r.MergeMeshes=function(t,i,n,o,s){void 0===i&&(i=!0);var a;if(!n){var l=0;for(a=0;a65536)return e.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}var h,c=null,u=new Array,f=null;for(a=0;aa&&(a=c)}return new i(e,s,a-s+1,t,r,n,o)},i})(t);e.SubMesh=i})(r||(r={}));var r,s=this&&this.__assign||Object.assign||function(e){for(var t,i=1,r=arguments.length;i=0&&this._scene.materials.splice(i,1),i=0;ia?a:Math.floor(l);var h,c,u,f,d=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,p=i.uvs,m=i.colors,_=[],g=[],v=[],y=[],b=[],x=[],T=[],E=[],P=[],A=[];if(r.length<2){var M=[],S=[];for(u=0;u0&&(I=R[f].subtract(R[f-1]).length(),w=I+T[c],b[c].push(w),T[c]=w),f++;o&&(f--,_.push(R[0].x,R[0].y,R[0].z),I=R[f].subtract(R[0]).length(),w=I+T[c],b[c].push(w),T[c]=w),P[c]=C+D,A[c]=O,O+=C+D}var L,F,B=null,V=null;for(u=0;u1)?1:i.arc||1,l=i.slice&&i.slice<=0?1:i.slice||1,h=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,c=new e.Vector3(n/2,o/2,s/2),u=2+r,f=2*u,d=[],p=[],m=[],_=[],g=0;g<=u;g++){for(var v=g/u,y=v*Math.PI*l,b=0;b<=f;b++){var x=b/f,T=x*Math.PI*2*a,E=e.Matrix.RotationZ(-y),P=e.Matrix.RotationY(T),A=e.Vector3.TransformCoordinates(e.Vector3.Up(),E),M=e.Vector3.TransformCoordinates(A,P),S=M.multiply(c),R=M.divide(c).normalize();p.push(S.x,S.y,S.z),m.push(R.x,R.y,R.z),_.push(x,v)}if(g>0)for(var C=p.length/3,O=C-2*(f+1);O+f+21)?1:i.arc||1,f=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,d=i.faceUV||new Array(3),p=i.faceColors,m=1!==u&&c?2:0,_=h?l:1,g=2+(1+m)*_;for(r=0;r0&&(i.push(a-1),i.push(a)),a++}var f=new t;return f.indices=i,f.positions=r,o&&(f.colors=s),f},t.CreateDashedLines=function(i){var r=i.dashSize||3,n=i.gapSize||1,o=i.dashNb||200,s=i.points,a=new Array,l=new Array,h=e.Vector3.Zero(),c=0,u=0,f=0,d=0,p=0,m=0,_=0;for(_=0;_1)?1:i.arc||1,c=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE;r.push(0,0,0),s.push(.5,.5);for(var u=2*Math.PI*h,f=u/l,d=0;d=r.length)?0:i.type||0,u=i.size,f=i.sizeX||u||1,d=i.sizeY||u||1,p=i.sizeZ||u||1,m=i.custom||r[c],_=m.face.length,g=i.faceUV||new Array(_),v=i.faceColors,y=void 0===i.flat||i.flat,b=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,x=new Array,T=new Array,E=new Array,P=new Array,A=new Array,M=0,S=0,R=new Array,C=0,O=0;if(y)for(O=0;O<_;O++)v&&void 0===v[O]&&(v[O]=new e.Color4(1,1,1,1)),g&&void 0===g[O]&&(g[O]=new e.Vector4(0,0,1,1));if(y)for(O=0;O<_;O++){var D=m.face[O].length;for(s=2*Math.PI/D,a=.5*Math.tan(s/2),l=.5,C=0;Cn.bbSize.y?n.bbSize.x:n.bbSize.y;$=$>n.bbSize.z?$:n.bbSize.z,w=n.subDiv.X*O/n.bbSize.x,L=n.subDiv.Y*O/n.bbSize.y,F=n.subDiv.Z*O/n.bbSize.z,B=n.subDiv.max*n.subDiv.max,n.facetPartitioning.length=0}for(o=0;o0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),this._indexBuffer&&(this._indexBuffer.references=i)},t.prototype.notifyUpdate=function(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e);for(var t=0,i=this._meshes;t0){for(var i=0;i0){for(var i=0;i0){for(var i=0;i0){var l=new Float32Array(i,a.positionsAttrDesc.offset,a.positionsAttrDesc.count);r.setVerticesData(e.VertexBuffer.PositionKind,l,!1)}if(a.normalsAttrDesc&&a.normalsAttrDesc.count>0){var h=new Float32Array(i,a.normalsAttrDesc.offset,a.normalsAttrDesc.count);r.setVerticesData(e.VertexBuffer.NormalKind,h,!1)}if(a.tangetsAttrDesc&&a.tangetsAttrDesc.count>0){var c=new Float32Array(i,a.tangetsAttrDesc.offset,a.tangetsAttrDesc.count);r.setVerticesData(e.VertexBuffer.TangentKind,c,!1)}if(a.uvsAttrDesc&&a.uvsAttrDesc.count>0){var u=new Float32Array(i,a.uvsAttrDesc.offset,a.uvsAttrDesc.count);r.setVerticesData(e.VertexBuffer.UVKind,u,!1)}if(a.uvs2AttrDesc&&a.uvs2AttrDesc.count>0){var f=new Float32Array(i,a.uvs2AttrDesc.offset,a.uvs2AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV2Kind,f,!1)}if(a.uvs3AttrDesc&&a.uvs3AttrDesc.count>0){var d=new Float32Array(i,a.uvs3AttrDesc.offset,a.uvs3AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV3Kind,d,!1)}if(a.uvs4AttrDesc&&a.uvs4AttrDesc.count>0){var p=new Float32Array(i,a.uvs4AttrDesc.offset,a.uvs4AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV4Kind,p,!1)}if(a.uvs5AttrDesc&&a.uvs5AttrDesc.count>0){var m=new Float32Array(i,a.uvs5AttrDesc.offset,a.uvs5AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV5Kind,m,!1)}if(a.uvs6AttrDesc&&a.uvs6AttrDesc.count>0){var _=new Float32Array(i,a.uvs6AttrDesc.offset,a.uvs6AttrDesc.count);r.setVerticesData(e.VertexBuffer.UV6Kind,_,!1)}if(a.colorsAttrDesc&&a.colorsAttrDesc.count>0){var g=new Float32Array(i,a.colorsAttrDesc.offset,a.colorsAttrDesc.count);r.setVerticesData(e.VertexBuffer.ColorKind,g,!1,a.colorsAttrDesc.stride)}if(a.matricesIndicesAttrDesc&&a.matricesIndicesAttrDesc.count>0){for(var v=new Int32Array(i,a.matricesIndicesAttrDesc.offset,a.matricesIndicesAttrDesc.count),y=[],b=0;b>8),y.push((16711680&x)>>16),y.push(x>>24)}r.setVerticesData(e.VertexBuffer.MatricesIndicesKind,y,!1)}if(a.matricesWeightsAttrDesc&&a.matricesWeightsAttrDesc.count>0){var T=new Float32Array(i,a.matricesWeightsAttrDesc.offset,a.matricesWeightsAttrDesc.count);r.setVerticesData(e.VertexBuffer.MatricesWeightsKind,T,!1)}if(a.indicesAttrDesc&&a.indicesAttrDesc.count>0){var E=new Int32Array(i,a.indicesAttrDesc.offset,a.indicesAttrDesc.count);r.setIndices(E,null)}if(a.subMeshesAttrDesc&&a.subMeshesAttrDesc.count>0){var P=new Int32Array(i,a.subMeshesAttrDesc.offset,5*a.subMeshesAttrDesc.count);r.subMeshes=[];for(var b=0;b>8),y.push((16711680&O)>>16),y.push(O>>24)}r.setVerticesData(e.VertexBuffer.MatricesIndicesKind,y,i.matricesIndices._updatable)}if(i.matricesIndicesExtra)if(i.matricesIndicesExtra._isExpanded)delete i.matricesIndices._isExpanded,r.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,i.matricesIndicesExtra,i.matricesIndicesExtra._updatable);else{for(var y=[],b=0;b>8),y.push((16711680&O)>>16),y.push(O>>24)}r.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,y,i.matricesIndicesExtra._updatable)}i.matricesWeights&&(t._CleanMatricesWeights(i,r),r.setVerticesData(e.VertexBuffer.MatricesWeightsKind,i.matricesWeights,i.matricesWeights._updatable)),i.matricesWeightsExtra&&r.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,i.matricesWeightsExtra,i.matricesWeights._updatable),r.setIndices(i.indices,null)}if(i.subMeshes){r.subMeshes=[];for(var D=0;D-1){var n=i.getScene().getLastSkeletonByID(t.skeletonId);if(n){r=n.bones.length;for(var o=i.getVerticesData(e.VertexBuffer.MatricesIndicesKind),s=i.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind),a=t.matricesWeights,l=t.matricesWeightsExtra,h=t.numBoneInfluencer,c=a.length,u=0;uh-1)&&(d=h-1),f>.001){for(var _=1/f,p=0;p<4;p++)a[u+p]*=_;if(l)for(var p=0;p<4;p++)l[u+p]*=_}else d>=4?(l[u+d-4]=1-f,s[u+d-4]=r):(a[u+d]=1-f,o[u+d]=r)}i.setVerticesData(e.VertexBuffer.MatricesIndicesKind,o),t.matricesWeightsExtra&&i.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,s)}}}},t.Parse=function(i,r,n){if(r.getGeometryByID(i.id))return null;var o=new t(i.id,r,void 0,i.updatable);return e.Tags&&e.Tags.AddTagsTo(o,i.tags),i.delayLoadingFile?(o.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED,o.delayLoadingFile=n+i.delayLoadingFile,o._boundingInfo=new e.BoundingInfo(e.Vector3.FromArray(i.boundingBoxMinimum),e.Vector3.FromArray(i.boundingBoxMaximum)),o._delayInfo=[],i.hasUVs&&o._delayInfo.push(e.VertexBuffer.UVKind),i.hasUVs2&&o._delayInfo.push(e.VertexBuffer.UV2Kind),i.hasUVs3&&o._delayInfo.push(e.VertexBuffer.UV3Kind),i.hasUVs4&&o._delayInfo.push(e.VertexBuffer.UV4Kind),i.hasUVs5&&o._delayInfo.push(e.VertexBuffer.UV5Kind),i.hasUVs6&&o._delayInfo.push(e.VertexBuffer.UV6Kind),i.hasColors&&o._delayInfo.push(e.VertexBuffer.ColorKind),i.hasMatricesIndices&&o._delayInfo.push(e.VertexBuffer.MatricesIndicesKind),i.hasMatricesWeights&&o._delayInfo.push(e.VertexBuffer.MatricesWeightsKind),o._delayLoadingFunction=e.VertexData.ImportVertexData):e.VertexData.ImportVertexData(i,o),r.pushGeometry(o,!0),o},t})();e.Geometry=t;var i=(function(e){function t(t,i,r,n){void 0===r&&(r=!1),void 0===n&&(n=null);var o=e.call(this,t,i,void 0,!1,n)||this;return o._canBeRegenerated=r,o._beingRegenerated=!0,o.regenerate(),o._beingRegenerated=!1,o}return o(t,e),t.prototype.canBeRegenerated=function(){return this._canBeRegenerated},t.prototype.regenerate=function(){this._canBeRegenerated&&(this._beingRegenerated=!0,this.setAllVerticesData(this._regenerateVertexData(),!1),this._beingRegenerated=!1)},t.prototype.asNewGeometry=function(t){return e.prototype.copy.call(this,t)},t.prototype.setAllVerticesData=function(t,i){this._beingRegenerated&&e.prototype.setAllVerticesData.call(this,t,!1)},t.prototype.setVerticesData=function(t,i,r){this._beingRegenerated&&e.prototype.setVerticesData.call(this,t,i,!1)},t.prototype._regenerateVertexData=function(){throw new Error("Abstract method")},t.prototype.copy=function(e){throw new Error("Must be overriden in sub-classes.")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.canBeRegenerated=this.canBeRegenerated(),t},t})(t);e._PrimitiveGeometry=i;var r=(function(t){function i(i,r,n,o,s,a,l,h,c){void 0===c&&(c=e.Mesh.DEFAULTSIDE);var u=t.call(this,i,r,l,h)||this;return u.pathArray=n,u.closeArray=o,u.closePath=s,u.offset=a,u.side=c,u}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateRibbon({pathArray:this.pathArray,closeArray:this.closeArray,closePath:this.closePath,offset:this.offset,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.pathArray,this.closeArray,this.closePath,this.offset,this.canBeRegenerated(),void 0,this.side)},i})(i);e.RibbonGeometry=r;var n=(function(t){function i(i,r,n,o,s,a){void 0===s&&(s=null),void 0===a&&(a=e.Mesh.DEFAULTSIDE);var l=t.call(this,i,r,o,s)||this;return l.size=n,l.side=a,l}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateBox({size:this.size,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.size,this.canBeRegenerated(),void 0,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.size=this.size,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.size,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.BoxGeometry=n;var s=(function(t){function i(i,r,n,o,s,a,l){void 0===a&&(a=null),void 0===l&&(l=e.Mesh.DEFAULTSIDE);var h=t.call(this,i,r,s,a)||this;return h.segments=n,h.diameter=o,h.side=l,h}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateSphere({segments:this.segments,diameter:this.diameter,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.segments,this.diameter,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.segments=this.segments,e.diameter=this.diameter,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.segments,t.diameter,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.SphereGeometry=s;var a=(function(t){function i(i,r,n,o,s,a,l){void 0===a&&(a=null),void 0===l&&(l=e.Mesh.DEFAULTSIDE);var h=t.call(this,i,r,s,a)||this;return h.radius=n, +h.tessellation=o,h.side=l,h}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateDisc({radius:this.radius,tessellation:this.tessellation,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.radius,this.tessellation,this.canBeRegenerated(),null,this.side)},i})(i);e.DiscGeometry=a;var l=(function(t){function i(i,r,n,o,s,a,l,h,c,u){void 0===l&&(l=1),void 0===c&&(c=null),void 0===u&&(u=e.Mesh.DEFAULTSIDE);var f=t.call(this,i,r,h,c)||this;return f.height=n,f.diameterTop=o,f.diameterBottom=s,f.tessellation=a,f.subdivisions=l,f.side=u,f}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateCylinder({height:this.height,diameterTop:this.diameterTop,diameterBottom:this.diameterBottom,tessellation:this.tessellation,subdivisions:this.subdivisions,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.height,this.diameterTop,this.diameterBottom,this.tessellation,this.subdivisions,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.height=this.height,e.diameterTop=this.diameterTop,e.diameterBottom=this.diameterBottom,e.tessellation=this.tessellation,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.height,t.diameterTop,t.diameterBottom,t.tessellation,t.subdivisions,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.CylinderGeometry=l;var h=(function(t){function i(i,r,n,o,s,a,l,h){void 0===l&&(l=null),void 0===h&&(h=e.Mesh.DEFAULTSIDE);var c=t.call(this,i,r,a,l)||this;return c.diameter=n,c.thickness=o,c.tessellation=s,c.side=h,c}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorus({diameter:this.diameter,thickness:this.thickness,tessellation:this.tessellation,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.diameter,this.thickness,this.tessellation,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.diameter=this.diameter,e.thickness=this.thickness,e.tessellation=this.tessellation,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.diameter,t.thickness,t.tessellation,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.TorusGeometry=h;var c=(function(t){function i(e,i,r,n,o,s,a){void 0===a&&(a=null);var l=t.call(this,e,i,s,a)||this;return l.width=r,l.height=n,l.subdivisions=o,l}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateGround({width:this.width,height:this.height,subdivisions:this.subdivisions})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.width,this.height,this.subdivisions,this.canBeRegenerated(),null)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.width=this.width,e.height=this.height,e.subdivisions=this.subdivisions,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.width,t.height,t.subdivisions,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.GroundGeometry=c;var u=(function(t){function i(e,i,r,n,o,s,a,l,h,c){void 0===c&&(c=null);var u=t.call(this,e,i,h,c)||this;return u.xmin=r,u.zmin=n,u.xmax=o,u.zmax=s,u.subdivisions=a,u.precision=l,u}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTiledGround({xmin:this.xmin,zmin:this.zmin,xmax:this.xmax,zmax:this.zmax,subdivisions:this.subdivisions,precision:this.precision})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.xmin,this.zmin,this.xmax,this.zmax,this.subdivisions,this.precision,this.canBeRegenerated(),null)},i})(i);e.TiledGroundGeometry=u;var f=(function(t){function i(i,r,n,o,s,a){void 0===s&&(s=null),void 0===a&&(a=e.Mesh.DEFAULTSIDE);var l=t.call(this,i,r,o,s)||this;return l.size=n,l.side=a,l}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreatePlane({size:this.size,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.size,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.size=this.size,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.size,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.PlaneGeometry=f;var d=(function(t){function i(i,r,n,o,s,a,l,h,c,u,f){void 0===u&&(u=null),void 0===f&&(f=e.Mesh.DEFAULTSIDE);var d=t.call(this,i,r,c,u)||this;return d.radius=n,d.tube=o,d.radialSegments=s,d.tubularSegments=a,d.p=l,d.q=h,d.side=f,d}return o(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorusKnot({radius:this.radius,tube:this.tube,radialSegments:this.radialSegments,tubularSegments:this.tubularSegments,p:this.p,q:this.q,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.radius,this.tube,this.radialSegments,this.tubularSegments,this.p,this.q,this.canBeRegenerated(),null,this.side)},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.radius=this.radius,e.tube=this.tube,e.radialSegments=this.radialSegments,e.tubularSegments=this.tubularSegments,e.p=this.p,e.q=this.q,e},i.Parse=function(t,r){if(r.getGeometryByID(t.id))return null;var n=new i(t.id,r,t.radius,t.tube,t.radialSegments,t.tubularSegments,t.p,t.q,t.canBeRegenerated,null);return e.Tags&&e.Tags.AddTagsTo(n,t.tags),r.pushGeometry(n,!0),n},i})(i);e.TorusKnotGeometry=d})(r||(r={}));var r;!(function(e){var t=(function(){function t(e){void 0===e&&(e=30),this._enabled=!0,this._rollingFrameTime=new i(e)}return t.prototype.sampleFrame=function(t){if(void 0===t&&(t=e.Tools.Now),this._enabled){if(null!=this._lastFrameTimeMs){var i=t-this._lastFrameTimeMs;this._rollingFrameTime.add(i)}this._lastFrameTimeMs=t}},Object.defineProperty(t.prototype,"averageFrameTime",{get:function(){return this._rollingFrameTime.average},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"averageFrameTimeVariance",{get:function(){return this._rollingFrameTime.variance},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"instantaneousFrameTime",{get:function(){return this._rollingFrameTime.history(0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"averageFPS",{get:function(){return 1e3/this._rollingFrameTime.average},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"instantaneousFPS",{get:function(){var e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isSaturated",{get:function(){return this._rollingFrameTime.isSaturated()},enumerable:!0,configurable:!0}),t.prototype.enable=function(){this._enabled=!0},t.prototype.disable=function(){this._enabled=!1,this._lastFrameTimeMs=null},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._enabled},enumerable:!0,configurable:!0}),t.prototype.reset=function(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()},t})();e.PerformanceMonitor=t;var i=(function(){function e(e){this._samples=new Array(e),this.reset()}return e.prototype.add=function(e){var t;if(this.isSaturated()){var i=this._samples[this._pos];t=i-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(i-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length},e.prototype.history=function(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;var t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]},e.prototype.isSaturated=function(){return this._sampleCount>=this._samples.length},e.prototype.reset=function(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0},e.prototype._wrapPosition=function(e){var t=this._samples.length;return(e%t+t)%t},e})();e.RollingAverage=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.BindEyePosition=function(e,t){if(t._forcedViewPosition)return void e.setVector3("vEyePosition",t._forcedViewPosition);e.setVector3("vEyePosition",t._mirroredCameraPosition?t._mirroredCameraPosition:t.activeCamera.globalPosition)},t.PrepareDefinesForMergedUV=function(e,t,i){t._needUVs=!0,t[i]=!0,e.getTextureMatrix().isIdentity(!0)?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,0===e.coordinatesIndex?t.MAINUV1=!0:t.MAINUV2=!0):t[i+"DIRECTUV"]=0},t.BindTextureMatrix=function(e,t,i){var r=e.getTextureMatrix();r.isIdentity(!0)||t.updateMatrix(i+"Matrix",r)},t.PrepareDefinesForMisc=function(t,i,r,n,o,s,a){a._areMiscDirty&&(a.LOGARITHMICDEPTH=r,a.POINTSIZE=n,a.FOG=i.fogEnabled&&t.applyFog&&i.fogMode!==e.Scene.FOGMODE_NONE&&o,a.NONUNIFORMSCALING=t.nonUniformScaling,a.ALPHATEST=s)},t.PrepareDefinesForFrameBoundValues=function(e,t,i,r,n){void 0===n&&(n=null);var o=!1;null==n&&(n=void 0!==e.clipPlane&&null!==e.clipPlane),i.CLIPPLANE!==n&&(i.CLIPPLANE=n,o=!0),i.DEPTHPREPASS!==!t.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==r&&(i.INSTANCES=r,o=!0),o&&i.markAsUnprocessed()},t.PrepareDefinesForAttributes=function(t,i,r,n,o,s){if(void 0===o&&(o=!1),void 0===s&&(s=!0),!i._areAttributesDirty&&i._needNormals===i._normals&&i._needUVs===i._uvs)return!1;if(i._normals=i._needNormals,i._uvs=i._needUVs,i.NORMAL=i._needNormals&&t.isVerticesDataPresent(e.VertexBuffer.NormalKind),i._needNormals&&t.isVerticesDataPresent(e.VertexBuffer.TangentKind)&&(i.TANGENT=!0),i._needUVs?(i.UV1=t.isVerticesDataPresent(e.VertexBuffer.UVKind),i.UV2=t.isVerticesDataPresent(e.VertexBuffer.UV2Kind)):(i.UV1=!1,i.UV2=!1),r){var a=t.useVertexColors&&t.isVerticesDataPresent(e.VertexBuffer.ColorKind);i.VERTEXCOLOR=a,i.VERTEXALPHA=t.hasVertexAlpha&&a&&s}if(n&&(t.useBones&&t.computeBonesUsingShaders&&t.skeleton?(i.NUM_BONE_INFLUENCERS=t.numBoneInfluencers,i.BonesPerMesh=t.skeleton.bones.length+1):(i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0)),o){var l=t.morphTargetManager;l?(i.MORPHTARGETS_TANGENT=l.supportsTangents&&i.TANGENT,i.MORPHTARGETS_NORMAL=l.supportsNormals&&i.NORMAL,i.MORPHTARGETS=l.numInfluencers>0,i.NUM_MORPH_INFLUENCERS=l.numInfluencers):(i.MORPHTARGETS_TANGENT=!1,i.MORPHTARGETS_NORMAL=!1,i.MORPHTARGETS=!1,i.NUM_MORPH_INFLUENCERS=0)}return!0},t.PrepareDefinesForLights=function(t,i,r,n,o,s){if(void 0===o&&(o=4),void 0===s&&(s=!1),!r._areLightsDirty)return r._needNormals;var a=0,l=!1,h=!1,c=!1,u=!1,f=!1;if(t.lightsEnabled&&!s)for(var d=0,p=i._lightSources;d0&&(u=!0,_.prepareDefines(r,a))}}if(m.lightmapMode!=e.Light.LIGHTMAP_DEFAULT?(c=!0,r["LIGHTMAPEXCLUDED"+a]=!0,r["LIGHTMAPNOSPECULAR"+a]=m.lightmapMode==e.Light.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+a]=!1,r["LIGHTMAPNOSPECULAR"+a]=!1),++a===o)break}r.SPECULARTERM=f,r.SHADOWS=u;for(var v=a;v0&&(n=r+o,t.addFallback(n,"LIGHT"+o)),e.SHADOWS||(e["SHADOW"+o]&&t.addFallback(r,"SHADOW"+o),e["SHADOWPCF"+o]&&t.addFallback(r,"SHADOWPCF"+o),e["SHADOWPCSS"+o]&&t.addFallback(r,"SHADOWPCSS"+o),e["SHADOWPOISSON"+o]&&t.addFallback(r,"SHADOWPOISSON"+o),e["SHADOWESM"+o]&&t.addFallback(r,"SHADOWESM"+o));return n++},t.PrepareAttributesForMorphTargets=function(t,i,r){var n=r.NUM_MORPH_INFLUENCERS;if(n>0&&e.Engine.LastCreatedEngine)for(var o=e.Engine.LastCreatedEngine.getCaps().maxVertexAttribs,s=i.morphTargetManager,a=s&&s.supportsNormals&&r.NORMAL,l=s&&s.supportsTangents&&r.TANGENT,h=0;ho&&e.Tools.Error("Cannot add more vertex attributes for mesh "+i.name)},t.PrepareAttributesForBones=function(t,i,r,n){r.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,i),t.push(e.VertexBuffer.MatricesIndicesKind),t.push(e.VertexBuffer.MatricesWeightsKind),r.NUM_BONE_INFLUENCERS>4&&(t.push(e.VertexBuffer.MatricesIndicesExtraKind),t.push(e.VertexBuffer.MatricesWeightsExtraKind)))},t.PrepareAttributesForInstances=function(e,t){t.INSTANCES&&(e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"))},t.BindLightShadow=function(e,t,i,r,n){if(e.shadowEnabled&&i.receiveShadows){var o=e.getShadowGenerator();o&&o.bindShadowLight(r,n)}},t.BindLightProperties=function(e,t,i){e.transferToEffect(t,i+"")},t.BindLights=function(i,r,n,o,s,a){void 0===s&&(s=4),void 0===a&&(a=!1);for(var l=Math.min(r._lightSources.length,s),h=0;h0,a.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,a.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===e.Texture.INVCUBIC_MODE,a.REFLECTIONMAP_3D=this._reflectionTexture.isCube,this._reflectionTexture.coordinatesMode){case e.Texture.EXPLICIT_MODE:a.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case e.Texture.PLANAR_MODE:a.setReflectionMode("REFLECTIONMAP_PLANAR");break;case e.Texture.PROJECTION_MODE:a.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case e.Texture.SKYBOX_MODE:a.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case e.Texture.SPHERICAL_MODE:a.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case e.Texture.EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:default:a.setReflectionMode("REFLECTIONMAP_CUBIC")}a.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else a.REFLECTION=!1;if(this._emissiveTexture&&r.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,a,"EMISSIVE")}else a.EMISSIVE=!1;if(this._lightmapTexture&&r.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,a,"LIGHTMAP"),a.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap}else a.LIGHTMAP=!1;if(this._specularTexture&&r.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture,a,"SPECULAR"),a.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else a.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&r.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,a,"BUMP"),a.PARALLAX=this._useParallax,a.PARALLAXOCCLUSION=this._useParallaxOcclusion,a.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else a.BUMP=!1;if(this._refractionTexture&&r.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;a._needUVs=!0,a.REFRACTION=!0,a.REFRACTIONMAP_3D=this._refractionTexture.isCube}else a.REFRACTION=!1;a.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else a.DIFFUSE=!1,a.AMBIENT=!1,a.OPACITY=!1,a.REFLECTION=!1,a.EMISSIVE=!1,a.LIGHTMAP=!1,a.BUMP=!1,a.REFRACTION=!1;a.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),a.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,a.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,a.SPECULAROVERALPHA=this._useSpecularOverAlpha,a.PREMULTIPLYALPHA=this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED||this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF}if(a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a),a.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,a.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if(a._areFresnelDirty&&(r.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(a.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,a.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,a.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,a.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,a.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,a.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,a._needNormals=!0,a.FRESNEL=!0):a.FRESNEL=!1),e.MaterialHelper.PrepareDefinesForMisc(i,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(i),a),e.MaterialHelper.PrepareDefinesForAttributes(i,a,!0,!0,!0),e.MaterialHelper.PrepareDefinesForFrameBoundValues(s,l,a,o),a.isDirty){a.markAsProcessed(),s.resetCachedMaterial();var h=new e.EffectFallbacks;a.REFLECTION&&h.addFallback(0,"REFLECTION"),a.SPECULAR&&h.addFallback(0,"SPECULAR"),a.BUMP&&h.addFallback(0,"BUMP"),a.PARALLAX&&h.addFallback(1,"PARALLAX"),a.PARALLAXOCCLUSION&&h.addFallback(0,"PARALLAXOCCLUSION"),a.SPECULAROVERALPHA&&h.addFallback(0,"SPECULAROVERALPHA"),a.FOG&&h.addFallback(1,"FOG"),a.POINTSIZE&&h.addFallback(0,"POINTSIZE"),a.LOGARITHMICDEPTH&&h.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(a,h,this._maxSimultaneousLights),a.SPECULARTERM&&h.addFallback(0,"SPECULARTERM"),a.DIFFUSEFRESNEL&&h.addFallback(1,"DIFFUSEFRESNEL"),a.OPACITYFRESNEL&&h.addFallback(2,"OPACITYFRESNEL"),a.REFLECTIONFRESNEL&&h.addFallback(3,"REFLECTIONFRESNEL"),a.EMISSIVEFRESNEL&&h.addFallback(4,"EMISSIVEFRESNEL"),a.FRESNEL&&h.addFallback(4,"FRESNEL");var c=[e.VertexBuffer.PositionKind];a.NORMAL&&c.push(e.VertexBuffer.NormalKind),a.UV1&&c.push(e.VertexBuffer.UVKind),a.UV2&&c.push(e.VertexBuffer.UV2Kind),a.VERTEXCOLOR&&c.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(c,i,a,h),e.MaterialHelper.PrepareAttributesForInstances(c,a),e.MaterialHelper.PrepareAttributesForMorphTargets(c,i,a);var u="default",f=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff"],d=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler"],p=["Material","Scene"];e.ImageProcessingConfiguration&&(e.ImageProcessingConfiguration.PrepareUniforms(f,a),e.ImageProcessingConfiguration.PrepareSamplers(d,a)),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:f,uniformBuffersNames:p,samplers:d,defines:a,maxSimultaneousLights:this._maxSimultaneousLights}),this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,f,p,d,a)) +;var m=a.toString();n.setEffect(s.getEngine().createEffect(u,{attributes:c,uniformsNames:f,uniformBuffersNames:p,samplers:d,defines:m,fallbacks:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:a.NUM_MORPH_INFLUENCERS}},l),a),this.buildUniformLayout()}return!(!n.effect||!n.effect.isReady())&&(a._renderId=s.getRenderId(),this._wasPreviouslyReady=!0,!0)},r.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("diffuseLeftColor",4),this._uniformBuffer.addUniform("diffuseRightColor",4),this._uniformBuffer.addUniform("opacityParts",4),this._uniformBuffer.addUniform("reflectionLeftColor",4),this._uniformBuffer.addUniform("reflectionRightColor",4),this._uniformBuffer.addUniform("refractionLeftColor",4),this._uniformBuffer.addUniform("refractionRightColor",4),this._uniformBuffer.addUniform("emissiveLeftColor",4),this._uniformBuffer.addUniform("emissiveRightColor",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vAmbientInfos",2),this._uniformBuffer.addUniform("vOpacityInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("vReflectionPosition",3),this._uniformBuffer.addUniform("vReflectionSize",3),this._uniformBuffer.addUniform("vEmissiveInfos",2),this._uniformBuffer.addUniform("vLightmapInfos",2),this._uniformBuffer.addUniform("vSpecularInfos",2),this._uniformBuffer.addUniform("vBumpInfos",3),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("ambientMatrix",16),this._uniformBuffer.addUniform("opacityMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("emissiveMatrix",16),this._uniformBuffer.addUniform("lightmapMatrix",16),this._uniformBuffer.addUniform("specularMatrix",16),this._uniformBuffer.addUniform("bumpMatrix",16),this._uniformBuffer.addUniform("vTangentSpaceParams",2),this._uniformBuffer.addUniform("refractionMatrix",16),this._uniformBuffer.addUniform("vRefractionInfos",4),this._uniformBuffer.addUniform("vSpecularColor",4),this._uniformBuffer.addUniform("vEmissiveColor",3),this._uniformBuffer.addUniform("vDiffuseColor",4),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.create()},r.prototype.unbind=function(){if(this._activeEffect){var e=!1;this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&(this._activeEffect.setTexture("reflection2DSampler",null),e=!0),this._refractionTexture&&this._refractionTexture.isRenderTarget&&(this._activeEffect.setTexture("refraction2DSampler",null),e=!0),e&&this._markAllSubMeshesAsTexturesDirty()}i.prototype.unbind.call(this)},r.prototype.bindForSubMesh=function(t,i,n){var o=this.getScene(),s=n._materialDefines;if(s){var a=n.effect;if(a){this._activeEffect=a,this.bindOnlyWorldMatrix(t),s.OBJECTSPACE_NORMALMAP&&(t.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var l=this._mustRebind(o,a,i.visibility);if(e.MaterialHelper.BindBonesParameters(i,a),l){if(this._uniformBuffer.bindToEffect(a,"Material"),this.bindViewProjection(a),!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync){if(r.FresnelEnabled&&s.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),this._uniformBuffer.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&this._uniformBuffer.updateColor4("opacityParts",new e.Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),this._uniformBuffer.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),this._uniformBuffer.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),this._uniformBuffer.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),o.texturesEnabled){if(this._diffuseTexture&&r.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),e.MaterialHelper.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse"),this._diffuseTexture.hasAlpha&&a.setFloat("alphaCutOff",this.alphaCutOff)),this._ambientTexture&&r.AmbientTextureEnabled&&(this._uniformBuffer.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),e.MaterialHelper.BindTextureMatrix(this._ambientTexture,this._uniformBuffer,"ambient")),this._opacityTexture&&r.OpacityTextureEnabled&&(this._uniformBuffer.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),e.MaterialHelper.BindTextureMatrix(this._opacityTexture,this._uniformBuffer,"opacity")),this._reflectionTexture&&r.ReflectionTextureEnabled&&(this._uniformBuffer.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),this._uniformBuffer.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){var h=this._reflectionTexture;this._uniformBuffer.updateVector3("vReflectionPosition",h.boundingBoxPosition),this._uniformBuffer.updateVector3("vReflectionSize",h.boundingBoxSize)}if(this._emissiveTexture&&r.EmissiveTextureEnabled&&(this._uniformBuffer.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),e.MaterialHelper.BindTextureMatrix(this._emissiveTexture,this._uniformBuffer,"emissive")),this._lightmapTexture&&r.LightmapTextureEnabled&&(this._uniformBuffer.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),e.MaterialHelper.BindTextureMatrix(this._lightmapTexture,this._uniformBuffer,"lightmap")),this._specularTexture&&r.SpecularTextureEnabled&&(this._uniformBuffer.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),e.MaterialHelper.BindTextureMatrix(this._specularTexture,this._uniformBuffer,"specular")),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&r.BumpTextureEnabled&&(this._uniformBuffer.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),e.MaterialHelper.BindTextureMatrix(this._bumpTexture,this._uniformBuffer,"bump"),o._mirroredCameraPosition?this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&r.RefractionTextureEnabled){var c=1;this._refractionTexture.isCube||(this._uniformBuffer.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(c=this._refractionTexture.depth)),this._uniformBuffer.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,c,this.invertRefractionY?-1:1)}}this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.SPECULARTERM&&this._uniformBuffer.updateColor4("vSpecularColor",this.specularColor,this.specularPower),this._uniformBuffer.updateColor3("vEmissiveColor",this.emissiveColor),this._uniformBuffer.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha*i.visibility)}if(o.texturesEnabled&&(this._diffuseTexture&&r.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&r.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&r.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&r.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&r.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&r.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&r.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&r.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&r.RefractionTextureEnabled)){var c=1;this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture)}e.MaterialHelper.BindClipPlane(a,o),o.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),e.MaterialHelper.BindEyePosition(a,o),a.setColor3("vAmbientColor",this._globalAmbientColor)}!l&&this.isFrozen||(o.lightsEnabled&&!this._disableLighting&&e.MaterialHelper.BindLights(o,i,a,s,this._maxSimultaneousLights),(o.fogEnabled&&i.applyFog&&o.fogMode!==e.Scene.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture)&&this.bindView(a),e.MaterialHelper.BindFogParameters(o,i,a),s.NUM_MORPH_INFLUENCERS&&e.MaterialHelper.BindMorphTargetParameters(i,a),e.MaterialHelper.BindLogDepth(s,a,o),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(i,this._activeEffect)}}},r.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e},r.prototype.getActiveTextures=function(){var e=i.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e},r.prototype.hasTexture=function(e){return!!i.prototype.hasTexture.call(this,e)||(this._diffuseTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._emissiveTexture===e||(this._specularTexture===e||(this._bumpTexture===e||(this._lightmapTexture===e||this._refractionTexture===e))))))))},r.prototype.dispose=function(e,t){t&&(this._diffuseTexture&&this._diffuseTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._specularTexture&&this._specularTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),i.prototype.dispose.call(this,e,t)},r.prototype.clone=function(t){var i=this,n=e.SerializationHelper.Clone((function(){return new r(t,i.getScene())}),this);return n.name=t,n.id=t,n},r.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},r.Parse=function(t,i,n){return e.SerializationHelper.Parse((function(){return new r(t.name,i)}),t,i,n)},Object.defineProperty(r,"DiffuseTextureEnabled",{get:function(){return r._DiffuseTextureEnabled},set:function(t){r._DiffuseTextureEnabled!==t&&(r._DiffuseTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"AmbientTextureEnabled",{get:function(){return r._AmbientTextureEnabled},set:function(t){r._AmbientTextureEnabled!==t&&(r._AmbientTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"OpacityTextureEnabled",{get:function(){return r._OpacityTextureEnabled},set:function(t){r._OpacityTextureEnabled!==t&&(r._OpacityTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"ReflectionTextureEnabled",{get:function(){return r._ReflectionTextureEnabled},set:function(t){r._ReflectionTextureEnabled!==t&&(r._ReflectionTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"EmissiveTextureEnabled",{get:function(){return r._EmissiveTextureEnabled},set:function(t){r._EmissiveTextureEnabled!==t&&(r._EmissiveTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"SpecularTextureEnabled",{get:function(){return r._SpecularTextureEnabled},set:function(t){r._SpecularTextureEnabled!==t&&(r._SpecularTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"BumpTextureEnabled",{get:function(){return r._BumpTextureEnabled},set:function(t){r._BumpTextureEnabled!==t&&(r._BumpTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"LightmapTextureEnabled",{get:function(){return r._LightmapTextureEnabled},set:function(t){r._LightmapTextureEnabled!==t&&(r._LightmapTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"RefractionTextureEnabled",{get:function(){return r._RefractionTextureEnabled},set:function(t){r._RefractionTextureEnabled!==t&&(r._RefractionTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"ColorGradingTextureEnabled",{get:function(){return r._ColorGradingTextureEnabled},set:function(t){r._ColorGradingTextureEnabled!==t&&(r._ColorGradingTextureEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(r,"FresnelEnabled",{get:function(){return r._FresnelEnabled},set:function(t){r._FresnelEnabled!==t&&(r._FresnelEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.FresnelDirtyFlag))},enumerable:!0,configurable:!0}),r._DiffuseTextureEnabled=!0,r._AmbientTextureEnabled=!0,r._OpacityTextureEnabled=!0,r._ReflectionTextureEnabled=!0,r._EmissiveTextureEnabled=!0,r._SpecularTextureEnabled=!0,r._BumpTextureEnabled=!0,r._LightmapTextureEnabled=!0,r._RefractionTextureEnabled=!0,r._ColorGradingTextureEnabled=!0,r._FresnelEnabled=!0,n([e.serializeAsTexture("diffuseTexture")],r.prototype,"_diffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],r.prototype,"diffuseTexture",void 0),n([e.serializeAsTexture("ambientTexture")],r.prototype,"_ambientTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"ambientTexture",void 0),n([e.serializeAsTexture("opacityTexture")],r.prototype,"_opacityTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],r.prototype,"opacityTexture",void 0),n([e.serializeAsTexture("reflectionTexture")],r.prototype,"_reflectionTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionTexture",void 0),n([e.serializeAsTexture("emissiveTexture")],r.prototype,"_emissiveTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"emissiveTexture",void 0),n([e.serializeAsTexture("specularTexture")],r.prototype,"_specularTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"specularTexture",void 0),n([e.serializeAsTexture("bumpTexture")],r.prototype,"_bumpTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"bumpTexture",void 0),n([e.serializeAsTexture("lightmapTexture")],r.prototype,"_lightmapTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"lightmapTexture",void 0),n([e.serializeAsTexture("refractionTexture")],r.prototype,"_refractionTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"refractionTexture",void 0),n([e.serializeAsColor3("ambient")],r.prototype,"ambientColor",void 0),n([e.serializeAsColor3("diffuse")],r.prototype,"diffuseColor",void 0),n([e.serializeAsColor3("specular")],r.prototype,"specularColor",void 0),n([e.serializeAsColor3("emissive")],r.prototype,"emissiveColor",void 0),n([e.serialize()],r.prototype,"specularPower",void 0),n([e.serialize("useAlphaFromDiffuseTexture")],r.prototype,"_useAlphaFromDiffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useAlphaFromDiffuseTexture",void 0),n([e.serialize("useEmissiveAsIllumination")],r.prototype,"_useEmissiveAsIllumination",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useEmissiveAsIllumination",void 0),n([e.serialize("linkEmissiveWithDiffuse")],r.prototype,"_linkEmissiveWithDiffuse",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"linkEmissiveWithDiffuse",void 0),n([e.serialize("useSpecularOverAlpha")],r.prototype,"_useSpecularOverAlpha",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useSpecularOverAlpha",void 0),n([e.serialize("useReflectionOverAlpha")],r.prototype,"_useReflectionOverAlpha",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useReflectionOverAlpha",void 0),n([e.serialize("disableLighting")],r.prototype,"_disableLighting",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"disableLighting",void 0),n([e.serialize("useObjectSpaceNormalMap")],r.prototype,"_useObjectSpaceNormalMap",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useObjectSpaceNormalMap",void 0),n([e.serialize("useParallax")],r.prototype,"_useParallax",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useParallax",void 0),n([e.serialize("useParallaxOcclusion")],r.prototype,"_useParallaxOcclusion",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useParallaxOcclusion",void 0),n([e.serialize()],r.prototype,"parallaxScaleBias",void 0),n([e.serialize("roughness")],r.prototype,"_roughness",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"roughness",void 0),n([e.serialize()],r.prototype,"indexOfRefraction",void 0),n([e.serialize()],r.prototype,"invertRefractionY",void 0),n([e.serialize()],r.prototype,"alphaCutOff",void 0),n([e.serialize("useLightmapAsShadowmap")],r.prototype,"_useLightmapAsShadowmap",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useLightmapAsShadowmap",void 0),n([e.serializeAsFresnelParameters("diffuseFresnelParameters")],r.prototype,"_diffuseFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"diffuseFresnelParameters",void 0),n([e.serializeAsFresnelParameters("opacityFresnelParameters")],r.prototype,"_opacityFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")],r.prototype,"opacityFresnelParameters",void 0),n([e.serializeAsFresnelParameters("reflectionFresnelParameters")],r.prototype,"_reflectionFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"reflectionFresnelParameters",void 0),n([e.serializeAsFresnelParameters("refractionFresnelParameters")],r.prototype,"_refractionFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"refractionFresnelParameters",void 0),n([e.serializeAsFresnelParameters("emissiveFresnelParameters")],r.prototype,"_emissiveFresnelParameters",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"emissiveFresnelParameters",void 0),n([e.serialize("useReflectionFresnelFromSpecular")],r.prototype,"_useReflectionFresnelFromSpecular",void 0),n([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],r.prototype,"useReflectionFresnelFromSpecular",void 0),n([e.serialize("useGlossinessFromSpecularMapAlpha")],r.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useGlossinessFromSpecularMapAlpha",void 0),n([e.serialize("maxSimultaneousLights")],r.prototype,"_maxSimultaneousLights",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"maxSimultaneousLights",void 0),n([e.serialize("invertNormalMapX")],r.prototype,"_invertNormalMapX",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"invertNormalMapX",void 0),n([e.serialize("invertNormalMapY")],r.prototype,"_invertNormalMapY",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"invertNormalMapY",void 0),n([e.serialize("twoSidedLighting")],r.prototype,"_twoSidedLighting",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"twoSidedLighting",void 0),n([e.serialize()],r.prototype,"useLogarithmicDepth",null),r})(e.PushMaterial);e.StandardMaterial=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.x=e.Vector3.Zero(),this.y=e.Vector3.Zero(),this.z=e.Vector3.Zero(),this.xx=e.Vector3.Zero(),this.yy=e.Vector3.Zero(),this.zz=e.Vector3.Zero(),this.xy=e.Vector3.Zero(),this.yz=e.Vector3.Zero(),this.zx=e.Vector3.Zero()}return t.prototype.addAmbient=function(t){var i=new e.Vector3(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.prototype.scale=function(e){this.x=this.x.scale(e),this.y=this.y.scale(e),this.z=this.z.scale(e),this.xx=this.xx.scale(e),this.yy=this.yy.scale(e),this.zz=this.zz.scale(e),this.yz=this.yz.scale(e),this.zx=this.zx.scale(e),this.xy=this.xy.scale(e)},t.FromHarmonics=function(e){var i=new t;return i.x=e.l11.scale(1.02333),i.y=e.l1_1.scale(1.02333),i.z=e.l10.scale(1.02333),i.xx=e.l00.scale(.886277).subtract(e.l20.scale(.247708)).add(e.lL22.scale(.429043)),i.yy=e.l00.scale(.886277).subtract(e.l20.scale(.247708)).subtract(e.lL22.scale(.429043)),i.zz=e.l00.scale(.886277).add(e.l20.scale(.495417)),i.yz=e.l2_1.scale(.858086),i.zx=e.l21.scale(.858086),i.xy=e.l2_2.scale(.858086),i.scale(1/Math.PI),i},t.FromArray=function(i){var r=new t;return e.Vector3.FromArrayToRef(i[0],0,r.x),e.Vector3.FromArrayToRef(i[1],0,r.y),e.Vector3.FromArrayToRef(i[2],0,r.z),e.Vector3.FromArrayToRef(i[3],0,r.xx),e.Vector3.FromArrayToRef(i[4],0,r.yy),e.Vector3.FromArrayToRef(i[5],0,r.zz),e.Vector3.FromArrayToRef(i[6],0,r.yz),e.Vector3.FromArrayToRef(i[7],0,r.zx),e.Vector3.FromArrayToRef(i[8],0,r.xy),r},t})();e.SphericalPolynomial=t;var i=(function(){function t(){this.l00=e.Vector3.Zero(),this.l1_1=e.Vector3.Zero(),this.l10=e.Vector3.Zero(),this.l11=e.Vector3.Zero(),this.l2_2=e.Vector3.Zero(),this.l2_1=e.Vector3.Zero(),this.l20=e.Vector3.Zero(),this.l21=e.Vector3.Zero(),this.lL22=e.Vector3.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e.Vector3(i.r,i.g,i.b),o=n.scale(r);this.l00=this.l00.add(o.scale(.282095)),this.l1_1=this.l1_1.add(o.scale(.488603*t.y)),this.l10=this.l10.add(o.scale(.488603*t.z)),this.l11=this.l11.add(o.scale(.488603*t.x)),this.l2_2=this.l2_2.add(o.scale(1.092548*t.x*t.y)),this.l2_1=this.l2_1.add(o.scale(1.092548*t.y*t.z)),this.l21=this.l21.add(o.scale(1.092548*t.x*t.z)),this.l20=this.l20.add(o.scale(.315392*(3*t.z*t.z-1))),this.lL22=this.lL22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(e){this.l00=this.l00.scale(e),this.l1_1=this.l1_1.scale(e),this.l10=this.l10.scale(e),this.l11=this.l11.scale(e),this.l2_2=this.l2_2.scale(e),this.l2_1=this.l2_1.scale(e),this.l20=this.l20.scale(e),this.l21=this.l21.scale(e),this.lL22=this.lL22.scale(e)},t.prototype.convertIncidentRadianceToIrradiance=function(){this.l00=this.l00.scale(3.141593),this.l1_1=this.l1_1.scale(2.094395),this.l10=this.l10.scale(2.094395),this.l11=this.l11.scale(2.094395),this.l2_2=this.l2_2.scale(.785398),this.l2_1=this.l2_1.scale(.785398),this.l20=this.l20.scale(.785398),this.l21=this.l21.scale(.785398),this.lL22=this.lL22.scale(.785398)},t.prototype.convertIrradianceToLambertianRadiance=function(){this.scale(1/Math.PI)},t.FromPolynomial=function(e){var i=new t;return i.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),i.l1_1=e.y.scale(.977204),i.l10=e.z.scale(.977204),i.l11=e.x.scale(.977204),i.l2_2=e.xy.scale(1.16538),i.l2_1=e.yz.scale(1.16538),i.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),i.l21=e.zx.scale(1.16538),i.lL22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),i.scale(Math.PI),i},t.FromArray=function(i){var r=new t;return e.Vector3.FromArrayToRef(i[0],0,r.l00),e.Vector3.FromArrayToRef(i[1],0,r.l1_1),e.Vector3.FromArrayToRef(i[2],0,r.l10),e.Vector3.FromArrayToRef(i[3],0,r.l11),e.Vector3.FromArrayToRef(i[4],0,r.l2_2),e.Vector3.FromArrayToRef(i[5],0,r.l2_1),e.Vector3.FromArrayToRef(i[6],0,r.l20),e.Vector3.FromArrayToRef(i[7],0,r.l21),e.Vector3.FromArrayToRef(i[8],0,r.lL22),r},t})();e.SphericalHarmonics=i})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}return e})(),i=(function(){function i(){}return i.ConvertCubeMapTextureToSphericalPolynomial=function(t){if(!t.isCube)return null;var i,r,n=t.getSize().width,o=t.readPixels(0),s=t.readPixels(1);t.isRenderTarget?(i=t.readPixels(3),r=t.readPixels(2)):(i=t.readPixels(2),r=t.readPixels(3));var a=t.readPixels(4),l=t.readPixels(5),h=t.gammaSpace,c=e.Engine.TEXTUREFORMAT_RGBA,u=e.Engine.TEXTURETYPE_UNSIGNED_INT;t.textureType&&t.textureType!==e.Engine.TEXTURETYPE_UNSIGNED_INT&&(u=e.Engine.TEXTURETYPE_FLOAT);var f={size:n,right:o,left:s,up:i,down:r,front:a,back:l,format:c,type:u,gammaSpace:h};return this.ConvertCubeMapToSphericalPolynomial(f)},i.ConvertCubeMapToSphericalPolynomial=function(t){for(var i=new e.SphericalHarmonics,r=0,n=2/t.size,o=n,s=.5*n-1,a=0;a<6;a++)for(var l=this.FileFaces[a],h=t[l.name],c=s,u=t.format===e.Engine.TEXTUREFORMAT_RGBA?4:3,f=0;f0&&h.addCPUSkinningFallback(c++,t),i.MORPHTARGETS&&h.addFallback(c++,"MORPHTARGETS");var u=[e.VertexBuffer.PositionKind];i.NORMAL&&u.push(e.VertexBuffer.NormalKind),i.TANGENT&&u.push(e.VertexBuffer.TangentKind),i.UV1&&u.push(e.VertexBuffer.UVKind),i.UV2&&u.push(e.VertexBuffer.UV2Kind),i.VERTEXCOLOR&&u.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(u,t,i,h),e.MaterialHelper.PrepareAttributesForInstances(u,i),e.MaterialHelper.PrepareAttributesForMorphTargets(u,t,i);var f=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vEmissiveColor","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","refractionMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX","vSphericalYY","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vReflectionMicrosurfaceInfos","vRefractionMicrosurfaceInfos","vTangentSpaceParams"],d=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","microSurfaceSampler","environmentBrdfSampler"],p=["Material","Scene"];e.ImageProcessingConfiguration&&(e.ImageProcessingConfiguration.PrepareUniforms(f,i),e.ImageProcessingConfiguration.PrepareSamplers(d,i)),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:f,uniformBuffersNames:p,samplers:d,defines:i,maxSimultaneousLights:this._maxSimultaneousLights});var m=i.toString();return l.createEffect("pbr",{attributes:u,uniformsNames:f,uniformBuffersNames:p,samplers:d,defines:m,fallbacks:h,onCompiled:r,onError:n,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:i.NUM_MORPH_INFLUENCERS}},l)},r.prototype._prepareDefines=function(t,i,r,n){void 0===r&&(r=null),void 0===n&&(n=null);var o=this.getScene(),s=o.getEngine();if(e.MaterialHelper.PrepareDefinesForLights(o,t,i,!0,this._maxSimultaneousLights,this._disableLighting),i._needNormals=!0,i.METALLICWORKFLOW=this.isMetallicWorkflow(),i._areTexturesDirty){if(i._needUVs=!1,o.texturesEnabled){o.getEngine().getCaps().textureLOD&&(i.LODBASEDMICROSFURACE=!0),this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled?e.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture,i,"ALBEDO"):i.ALBEDO=!1,this._ambientTexture&&e.StandardMaterial.AmbientTextureEnabled?(e.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture,i,"AMBIENT"),i.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):i.AMBIENT=!1,this._opacityTexture&&e.StandardMaterial.OpacityTextureEnabled?(e.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture,i,"OPACITY"),i.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):i.OPACITY=!1;var a=this._getReflectionTexture();if(a&&e.StandardMaterial.ReflectionTextureEnabled){switch(i.REFLECTION=!0,i.GAMMAREFLECTION=a.gammaSpace,i.RGBDREFLECTION=a.isRGBD,i.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!a.invertZ:a.invertZ,i.LODINREFLECTIONALPHA=a.lodLevelInAlpha,a.coordinatesMode===e.Texture.INVCUBIC_MODE&&(i.INVERTCUBICMAP=!0),i.REFLECTIONMAP_3D=a.isCube,a.coordinatesMode){case e.Texture.EXPLICIT_MODE:i.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:i.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:i.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:i.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:i.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:default:i.REFLECTIONMAP_CUBIC=!0,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!!a.boundingBoxSize}a.coordinatesMode!==e.Texture.SKYBOX_MODE&&a.sphericalPolynomial&&(i.USESPHERICALFROMREFLECTIONMAP=!0,this._forceIrradianceInFragment||o.getEngine().getCaps().maxVaryingVectors<=8?i.USESPHERICALINVERTEX=!1:i.USESPHERICALINVERTEX=!0)}else i.REFLECTION=!1,i.REFLECTIONMAP_3D=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_CUBIC=!1,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.INVERTCUBICMAP=!1,i.USESPHERICALFROMREFLECTIONMAP=!1,i.USESPHERICALINVERTEX=!1,i.REFLECTIONMAP_OPPOSITEZ=!1,i.LODINREFLECTIONALPHA=!1,i.GAMMAREFLECTION=!1,i.RGBDREFLECTION=!1;this._lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled?(e.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,i,"LIGHTMAP"),i.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,i.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace):i.LIGHTMAP=!1,this._emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled?e.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,i,"EMISSIVE"):i.EMISSIVE=!1,e.StandardMaterial.SpecularTextureEnabled?(this._metallicTexture?(e.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture,i,"REFLECTIVITY"),i.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,i.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,i.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,i.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed):this._reflectivityTexture?(e.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture,i,"REFLECTIVITY"),i.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,i.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap):i.REFLECTIVITY=!1,this._microSurfaceTexture?e.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture,i,"MICROSURFACEMAP"):i.MICROSURFACEMAP=!1):(i.REFLECTIVITY=!1,i.MICROSURFACEMAP=!1),o.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&e.StandardMaterial.BumpTextureEnabled&&!this._disableBumpMap?(e.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,i,"BUMP"),this._useParallax&&this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled?(i.PARALLAX=!0,i.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):i.PARALLAX=!1,i.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):i.BUMP=!1;var l=this._getRefractionTexture();l&&e.StandardMaterial.RefractionTextureEnabled?(i.REFRACTION=!0,i.REFRACTIONMAP_3D=l.isCube,i.GAMMAREFRACTION=l.gammaSpace,i.RGBDREFRACTION=l.isRGBD,i.REFRACTIONMAP_OPPOSITEZ=l.invertZ,i.LODINREFRACTIONALPHA=l.lodLevelInAlpha,this._linkRefractionWithTransparency&&(i.LINKREFRACTIONTOTRANSPARENCY=!0)):i.REFRACTION=!1,this._environmentBRDFTexture&&e.StandardMaterial.ReflectionTextureEnabled?i.ENVIRONMENTBRDF=!0:i.ENVIRONMENTBRDF=!1,this._shouldUseAlphaFromAlbedoTexture()?i.ALPHAFROMALBEDO=!0:i.ALPHAFROMALBEDO=!1}i.SPECULAROVERALPHA=this._useSpecularOverAlpha,i.USEPHYSICALLIGHTFALLOFF=this._usePhysicalLightFalloff,i.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?i.TWOSIDEDLIGHTING=!0:i.TWOSIDEDLIGHTING=!1,i.ALPHATESTVALUE=this._alphaCutOff+(this._alphaCutOff%1==0?".":""),i.PREMULTIPLYALPHA=this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED||this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF,i.ALPHABLEND=this.needAlphaBlendingForMesh(t),i.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,i.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel,i.SPECULARAA=o.getEngine().getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}i._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(i),i.FORCENORMALFORWARD=this._forceNormalForward,i.RADIANCEOCCLUSION=this._useRadianceOcclusion,i.HORIZONOCCLUSION=this._useHorizonOcclusion,i._areMiscDirty&&(e.MaterialHelper.PrepareDefinesForMisc(t,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(t)||this._forceAlphaTest,i),i.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!t.isVerticesDataPresent(e.VertexBuffer.NormalKind)),e.MaterialHelper.PrepareDefinesForFrameBoundValues(o,s,i,!!r,n),e.MaterialHelper.PrepareDefinesForAttributes(t,i,!0,!0,!0,this._transparencyMode!==e.PBRMaterial.PBRMATERIAL_OPAQUE)},r.prototype.forceCompilation=function(e,i,r){var n=this,o=s({clipPlane:!1},r),a=new t,l=this._prepareEffect(e,a,void 0,void 0,void 0,o.clipPlane);l.isReady()?i&&i(this):l.onCompileObservable.add((function(){i&&i(n)}))},r.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("vAlbedoInfos",2),this._uniformBuffer.addUniform("vAmbientInfos",3),this._uniformBuffer.addUniform("vOpacityInfos",2),this._uniformBuffer.addUniform("vEmissiveInfos",2),this._uniformBuffer.addUniform("vLightmapInfos",2),this._uniformBuffer.addUniform("vReflectivityInfos",3),this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos",2),this._uniformBuffer.addUniform("vRefractionInfos",4),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("vReflectionPosition",3),this._uniformBuffer.addUniform("vReflectionSize",3),this._uniformBuffer.addUniform("vBumpInfos",3),this._uniformBuffer.addUniform("albedoMatrix",16),this._uniformBuffer.addUniform("ambientMatrix",16),this._uniformBuffer.addUniform("opacityMatrix",16),this._uniformBuffer.addUniform("emissiveMatrix",16),this._uniformBuffer.addUniform("lightmapMatrix",16),this._uniformBuffer.addUniform("reflectivityMatrix",16),this._uniformBuffer.addUniform("microSurfaceSamplerMatrix",16),this._uniformBuffer.addUniform("bumpMatrix",16),this._uniformBuffer.addUniform("vTangentSpaceParams",2),this._uniformBuffer.addUniform("refractionMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionColor",3),this._uniformBuffer.addUniform("vAlbedoColor",4),this._uniformBuffer.addUniform("vLightingIntensity",4),this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("vReflectivityColor",4),this._uniformBuffer.addUniform("vEmissiveColor",3),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.create()},r.prototype.unbind=function(){this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._uniformBuffer.setTexture("refractionSampler",null),i.prototype.unbind.call(this)},r.prototype.bindForSubMesh=function(t,i,r){var n=this.getScene(),o=r._materialDefines;if(o){var s=r.effect;if(s){this._activeEffect=s,this.bindOnlyWorldMatrix(t),o.OBJECTSPACE_NORMALMAP&&(t.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var a=this._mustRebind(n,s,i.visibility);e.MaterialHelper.BindBonesParameters(i,this._activeEffect);var l=null;if(a){this._uniformBuffer.bindToEffect(s,"Material"),this.bindViewProjection(s),l=this._getReflectionTexture();var h=this._getRefractionTexture();if(!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync){if(n.texturesEnabled){if(this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),e.MaterialHelper.BindTextureMatrix(this._albedoTexture,this._uniformBuffer,"albedo")),this._ambientTexture&&e.StandardMaterial.AmbientTextureEnabled&&(this._uniformBuffer.updateFloat3("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength),e.MaterialHelper.BindTextureMatrix(this._ambientTexture,this._uniformBuffer,"ambient")),this._opacityTexture&&e.StandardMaterial.OpacityTextureEnabled&&(this._uniformBuffer.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),e.MaterialHelper.BindTextureMatrix(this._opacityTexture,this._uniformBuffer,"opacity")),l&&e.StandardMaterial.ReflectionTextureEnabled){if(this._uniformBuffer.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){var c=l;this._uniformBuffer.updateVector3("vReflectionPosition",c.boundingBoxPosition),this._uniformBuffer.updateVector3("vReflectionSize",c.boundingBoxSize)}var u=l.sphericalPolynomial;o.USESPHERICALFROMREFLECTIONMAP&&u&&(this._activeEffect.setFloat3("vSphericalX",u.x.x,u.x.y,u.x.z),this._activeEffect.setFloat3("vSphericalY",u.y.x,u.y.y,u.y.z),this._activeEffect.setFloat3("vSphericalZ",u.z.x,u.z.y,u.z.z),this._activeEffect.setFloat3("vSphericalXX_ZZ",u.xx.x-u.zz.x,u.xx.y-u.zz.y,u.xx.z-u.zz.z),this._activeEffect.setFloat3("vSphericalYY_ZZ",u.yy.x-u.zz.x,u.yy.y-u.zz.y,u.yy.z-u.zz.z),this._activeEffect.setFloat3("vSphericalZZ",u.zz.x,u.zz.y,u.zz.z),this._activeEffect.setFloat3("vSphericalXY",u.xy.x,u.xy.y,u.xy.z),this._activeEffect.setFloat3("vSphericalYZ",u.yz.x,u.yz.y,u.yz.z),this._activeEffect.setFloat3("vSphericalZX",u.zx.x,u.zx.y,u.zx.z)),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}if(this._emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled&&(this._uniformBuffer.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),e.MaterialHelper.BindTextureMatrix(this._emissiveTexture,this._uniformBuffer,"emissive")),this._lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled&&(this._uniformBuffer.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),e.MaterialHelper.BindTextureMatrix(this._lightmapTexture,this._uniformBuffer,"lightmap")),e.StandardMaterial.SpecularTextureEnabled&&(this._metallicTexture?(this._uniformBuffer.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),e.MaterialHelper.BindTextureMatrix(this._metallicTexture,this._uniformBuffer,"reflectivity")):this._reflectivityTexture&&(this._uniformBuffer.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),e.MaterialHelper.BindTextureMatrix(this._reflectivityTexture,this._uniformBuffer,"reflectivity")),this._microSurfaceTexture&&(this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),e.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture,this._uniformBuffer,"microSurfaceSampler"))),this._bumpTexture&&n.getEngine().getCaps().standardDerivatives&&e.StandardMaterial.BumpTextureEnabled&&!this._disableBumpMap&&(this._uniformBuffer.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),e.MaterialHelper.BindTextureMatrix(this._bumpTexture,this._uniformBuffer,"bump"),n._mirroredCameraPosition?this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),h&&e.StandardMaterial.RefractionTextureEnabled){this._uniformBuffer.updateMatrix("refractionMatrix",h.getReflectionTextureMatrix());var f=1;h.isCube||h.depth&&(f=h.depth),this._uniformBuffer.updateFloat4("vRefractionInfos",h.level,this._indexOfRefraction,f,this._invertRefractionY?-1:1),this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos",h.getSize().width,h.lodGenerationScale,h.lodGenerationOffset)}}this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),o.METALLICWORKFLOW?(e.PBRMaterial._scaledReflectivity.r=void 0===this._metallic||null===this._metallic?1:this._metallic,e.PBRMaterial._scaledReflectivity.g=void 0===this._roughness||null===this._roughness?1:this._roughness,this._uniformBuffer.updateColor4("vReflectivityColor",e.PBRMaterial._scaledReflectivity,0)):this._uniformBuffer.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface),this._uniformBuffer.updateColor3("vEmissiveColor",this._emissiveColor),this._uniformBuffer.updateColor3("vReflectionColor",this._reflectionColor),this._uniformBuffer.updateColor4("vAlbedoColor",this._albedoColor,this.alpha*i.visibility),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity,this._lightingInfos.w=this._specularIntensity,this._uniformBuffer.updateVector4("vLightingIntensity",this._lightingInfos)}n.texturesEnabled&&(this._albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&e.StandardMaterial.AmbientTextureEnabled&&this._uniformBuffer.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&e.StandardMaterial.OpacityTextureEnabled&&this._uniformBuffer.setTexture("opacitySampler",this._opacityTexture),l&&e.StandardMaterial.ReflectionTextureEnabled&&(o.LODBASEDMICROSFURACE?this._uniformBuffer.setTexture("reflectionSampler",l):(this._uniformBuffer.setTexture("reflectionSampler",l._lodTextureMid||l),this._uniformBuffer.setTexture("reflectionSamplerLow",l._lodTextureLow||l),this._uniformBuffer.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l))),o.ENVIRONMENTBRDF&&this._uniformBuffer.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),h&&e.StandardMaterial.RefractionTextureEnabled&&(o.LODBASEDMICROSFURACE?this._uniformBuffer.setTexture("refractionSampler",h):(this._uniformBuffer.setTexture("refractionSampler",h._lodTextureMid||h),this._uniformBuffer.setTexture("refractionSamplerLow",h._lodTextureLow||h),this._uniformBuffer.setTexture("refractionSamplerHigh",h._lodTextureHigh||h))),this._emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled&&this._uniformBuffer.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled&&this._uniformBuffer.setTexture("lightmapSampler",this._lightmapTexture),e.StandardMaterial.SpecularTextureEnabled&&(this._metallicTexture?this._uniformBuffer.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&this._uniformBuffer.setTexture("reflectivitySampler",this._reflectivityTexture),this._microSurfaceTexture&&this._uniformBuffer.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&n.getEngine().getCaps().standardDerivatives&&e.StandardMaterial.BumpTextureEnabled&&!this._disableBumpMap&&this._uniformBuffer.setTexture("bumpSampler",this._bumpTexture)),e.MaterialHelper.BindClipPlane(this._activeEffect,n),n.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor);var d=n._forcedViewPosition?n._forcedViewPosition:n._mirroredCameraPosition?n._mirroredCameraPosition:n.activeCamera.globalPosition,p=n.useRightHandedSystem===(null!=n._mirroredCameraPosition);s.setFloat4("vEyePosition",d.x,d.y,d.z,p?-1:1),s.setColor3("vAmbientColor",this._globalAmbientColor)}!a&&this.isFrozen||(n.lightsEnabled&&!this._disableLighting&&e.MaterialHelper.BindLights(n,i,this._activeEffect,o,this._maxSimultaneousLights,this._usePhysicalLightFalloff),(n.fogEnabled&&i.applyFog&&n.fogMode!==e.Scene.FOGMODE_NONE||l)&&this.bindView(s),e.MaterialHelper.BindFogParameters(n,i,this._activeEffect),o.NUM_MORPH_INFLUENCERS&&e.MaterialHelper.BindMorphTargetParameters(i,this._activeEffect),this._imageProcessingConfiguration.bind(this._activeEffect),e.MaterialHelper.BindLogDepth(o,this._activeEffect,n)),this._uniformBuffer.update(),this._afterBind(i,this._activeEffect)}}},r.prototype.getAnimatables=function(){var e=[];return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e},r.prototype._getReflectionTexture=function(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture},r.prototype._getRefractionTexture=function(){return this._refractionTexture?this._refractionTexture:this._linkRefractionWithTransparency?this.getScene().environmentTexture:null},r.prototype.dispose=function(e,t){t&&(this._albedoTexture&&this._albedoTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._environmentBRDFTexture&&this.getScene()._environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._metallicTexture&&this._metallicTexture.dispose(),this._reflectivityTexture&&this._reflectivityTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),i.prototype.dispose.call(this,e,t)},r._scaledReflectivity=new e.Color3,n([e.serializeAsImageProcessingConfiguration()],r.prototype,"_imageProcessingConfiguration",void 0),n([e.serialize()],r.prototype,"useLogarithmicDepth",null),n([e.serialize()],r.prototype,"transparencyMode",null),r})(e.PushMaterial);e.PBRBaseMaterial=i})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r){var n=t.call(this,i,r)||this;return n.maxSimultaneousLights=4,n.disableLighting=!1,n.invertNormalMapX=!1,n.invertNormalMapY=!1,n.emissiveColor=new e.Color3(0,0,0),n.occlusionStrength=1,n.useLightmapAsShadowmap=!1,n._useAlphaFromAlbedoTexture=!0,n._useAmbientInGrayScale=!0,n}return o(i,t),Object.defineProperty(i.prototype,"doubleSided",{get:function(){return this._twoSidedLighting}, +set:function(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())},enumerable:!0,configurable:!0}),i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this.environmentTexture&&e.push(this.environmentTexture),this.normalTexture&&e.push(this.normalTexture),this.emissiveTexture&&e.push(this.emissiveTexture),this.occlusionTexture&&e.push(this.occlusionTexture),this.lightmapTexture&&e.push(this.lightmapTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this.lightmapTexture===e},i.prototype.getClassName=function(){return"PBRBaseSimpleMaterial"},n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"maxSimultaneousLights",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"disableLighting",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],i.prototype,"environmentTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapX",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapY",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],i.prototype,"normalTexture",void 0),n([e.serializeAsColor3("emissive"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveColor",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],i.prototype,"occlusionStrength",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],i.prototype,"occlusionTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],i.prototype,"alphaCutOff",void 0),n([e.serialize()],i.prototype,"doubleSided",null),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty",null)],i.prototype,"lightmapTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLightmapAsShadowmap",void 0),i})(e.PBRBaseMaterial);e.PBRBaseSimpleMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r){var n=t.call(this,i,r)||this;return n.directIntensity=1,n.emissiveIntensity=1,n.environmentIntensity=1,n.specularIntensity=1,n.disableBumpMap=!1,n.ambientTextureStrength=1,n.ambientColor=new e.Color3(0,0,0),n.albedoColor=new e.Color3(1,1,1),n.reflectivityColor=new e.Color3(1,1,1),n.reflectionColor=new e.Color3(1,1,1),n.emissiveColor=new e.Color3(0,0,0),n.microSurface=1,n.indexOfRefraction=.66,n.invertRefractionY=!1,n.linkRefractionWithTransparency=!1,n.useLightmapAsShadowmap=!1,n.useAlphaFromAlbedoTexture=!1,n.forceAlphaTest=!1,n.alphaCutOff=.4,n.useSpecularOverAlpha=!0,n.useMicroSurfaceFromReflectivityMapAlpha=!1,n.useRoughnessFromMetallicTextureAlpha=!0,n.useRoughnessFromMetallicTextureGreen=!1,n.useMetallnessFromMetallicTextureBlue=!1,n.useAmbientOcclusionFromMetallicTextureRed=!1,n.useAmbientInGrayScale=!1,n.useAutoMicroSurfaceFromReflectivityMap=!1,n.usePhysicalLightFalloff=!0,n.useRadianceOverAlpha=!0,n.useObjectSpaceNormalMap=!1,n.useParallax=!1,n.useParallaxOcclusion=!1,n.parallaxScaleBias=.05,n.disableLighting=!1,n.forceIrradianceInFragment=!1,n.maxSimultaneousLights=4,n.invertNormalMapX=!1,n.invertNormalMapY=!1,n.twoSidedLighting=!1,n.useAlphaFresnel=!1,n.useLinearAlphaFresnel=!1,n.environmentBRDFTexture=null,n.forceNormalForward=!1,n.enableSpecularAntiAliasing=!1,n.useHorizonOcclusion=!0,n.useRadianceOcclusion=!0,n.unlit=!1,n._environmentBRDFTexture=e.TextureTools.GetEnvironmentBRDFTexture(r),n}return o(i,t),Object.defineProperty(i,"PBRMATERIAL_OPAQUE",{get:function(){return this._PBRMATERIAL_OPAQUE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"PBRMATERIAL_ALPHATEST",{get:function(){return this._PBRMATERIAL_ALPHATEST},enumerable:!0,configurable:!0}),Object.defineProperty(i,"PBRMATERIAL_ALPHABLEND",{get:function(){return this._PBRMATERIAL_ALPHABLEND},enumerable:!0,configurable:!0}),Object.defineProperty(i,"PBRMATERIAL_ALPHATESTANDBLEND",{get:function(){return this._PBRMATERIAL_ALPHATESTANDBLEND},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurves",{get:function(){return this._imageProcessingConfiguration.colorCurves},set:function(e){this._imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"PBRMaterial"},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this._albedoTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._reflectivityTexture===e||(this._metallicTexture===e||(this._microSurfaceTexture===e||(this._bumpTexture===e||(this._lightmapTexture===e||this._refractionTexture===e)))))))))},i.prototype.clone=function(t){var r=this,n=e.SerializationHelper.Clone((function(){return new i(t,r.getScene())}),this);return n.id=t,n.name=t,n},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRMaterial",t},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,r)}),t,r,n)},i._PBRMATERIAL_OPAQUE=0,i._PBRMATERIAL_ALPHATEST=1,i._PBRMATERIAL_ALPHABLEND=2,i._PBRMATERIAL_ALPHATESTANDBLEND=3,n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"directIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"environmentIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"specularIntensity",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"disableBumpMap",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"albedoTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientTextureStrength",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"opacityTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectivityTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallicTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallic",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"roughness",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"microSurfaceTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"bumpTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty",null)],i.prototype,"lightmapTexture",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"refractionTexture",void 0),n([e.serializeAsColor3("ambient"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientColor",void 0),n([e.serializeAsColor3("albedo"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"albedoColor",void 0),n([e.serializeAsColor3("reflectivity"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectivityColor",void 0),n([e.serializeAsColor3("reflection"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionColor",void 0),n([e.serializeAsColor3("emissive"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveColor",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"microSurface",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"indexOfRefraction",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertRefractionY",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"linkRefractionWithTransparency",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLightmapAsShadowmap",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"useAlphaFromAlbedoTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"forceAlphaTest",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"alphaCutOff",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useSpecularOverAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRoughnessFromMetallicTextureGreen",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useMetallnessFromMetallicTextureBlue",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAmbientInGrayScale",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"usePhysicalLightFalloff",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRadianceOverAlpha",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useObjectSpaceNormalMap",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useParallax",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useParallaxOcclusion",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"parallaxScaleBias",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"disableLighting",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"forceIrradianceInFragment",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"maxSimultaneousLights",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapX",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapY",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"twoSidedLighting",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAlphaFresnel",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLinearAlphaFresnel",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"environmentBRDFTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"forceNormalForward",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"enableSpecularAntiAliasing",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useHorizonOcclusion",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRadianceOcclusion",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsMiscDirty")],i.prototype,"unlit",void 0),i})(e.PBRBaseMaterial);e.PBRMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i){var r=t.call(this,e,i)||this;return r._useRoughnessFromMetallicTextureAlpha=!1,r._useRoughnessFromMetallicTextureGreen=!0,r._useMetallnessFromMetallicTextureBlue=!0,r.metallic=1,r.roughness=1,r}return o(i,t),i.prototype.getClassName=function(){return"PBRMetallicRoughnessMaterial"},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this.baseTexture&&e.push(this.baseTexture),this.metallicRoughnessTexture&&e.push(this.metallicRoughnessTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this.baseTexture===e||this.metallicRoughnessTexture===e)},i.prototype.clone=function(t){var r=this,n=e.SerializationHelper.Clone((function(){return new i(t,r.getScene())}),this);return n.id=t,n.name=t,n},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRMetallicRoughnessMaterial",t},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,r)}),t,r,n)},n([e.serializeAsColor3(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoColor")],i.prototype,"baseColor",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],i.prototype,"baseTexture",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallic",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"roughness",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],i.prototype,"metallicRoughnessTexture",void 0),i})(e.PBRBaseSimpleMaterial);e.PBRMetallicRoughnessMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i){var r=t.call(this,e,i)||this;return r._useMicroSurfaceFromReflectivityMapAlpha=!0,r}return o(i,t),i.prototype.getClassName=function(){return"PBRSpecularGlossinessMaterial"},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this.diffuseTexture&&e.push(this.diffuseTexture),this.specularGlossinessTexture&&e.push(this.specularGlossinessTexture),e},i.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this.diffuseTexture===e||this.specularGlossinessTexture===e)},i.prototype.clone=function(t){var r=this,n=e.SerializationHelper.Clone((function(){return new i(t,r.getScene())}),this);return n.id=t,n.name=t,n},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRSpecularGlossinessMaterial",t},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,r)}),t,r,n)},n([e.serializeAsColor3("diffuse"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoColor")],i.prototype,"diffuseColor",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],i.prototype,"diffuseTexture",void 0),n([e.serializeAsColor3("specular"),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],i.prototype,"specularColor",void 0),n([e.serialize(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_microSurface")],i.prototype,"glossiness",void 0),n([e.serializeAsTexture(),e.expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],i.prototype,"specularGlossinessTexture",void 0),i})(e.PBRBaseSimpleMaterial);e.PBRSpecularGlossinessMaterial=t})(r||(r={}));var r;!(function(e){e.CameraInputTypes={};var t=(function(){function t(e){this.attached={},this.camera=e,this.checkInputs=function(){}}return t.prototype.add=function(t){var i=t.getSimpleName();if(this.attached[i])return void e.Tools.Warn("camera input of type "+i+" already exists on camera");this.attached[i]=t,t.camera=this.camera,t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t))),this.attachedElement&&t.attachControl(this.attachedElement)},t.prototype.remove=function(e){for(var t in this.attached){var i=this.attached[t];i===e&&(i.detachControl(this.attachedElement),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}},t.prototype.removeByType=function(e){for(var t in this.attached){var i=this.attached[t];i.getClassName()===e&&(i.detachControl(this.attachedElement),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}},t.prototype._addCheckInputs=function(e){var t=this.checkInputs;return function(){t(),e()}},t.prototype.attachInput=function(e){this.attachedElement&&e.attachControl(this.attachedElement,this.noPreventDefault)},t.prototype.attachElement=function(t,i){if(void 0===i&&(i=!1),!this.attachedElement){i=!e.Camera.ForceAttachControlToAlwaysPreventDefault&&i,this.attachedElement=t,this.noPreventDefault=i;for(var r in this.attached)this.attached[r].attachControl(t,i)}},t.prototype.detachElement=function(e,t){if(void 0===t&&(t=!1),this.attachedElement===e){for(var i in this.attached)this.attached[i].detachControl(e),t&&(this.attached[i].camera=null);this.attachedElement=null}},t.prototype.rebuildInputCheck=function(){this.checkInputs=function(){};for(var e in this.attached){var t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}},t.prototype.clear=function(){this.attachedElement&&this.detachElement(this.attachedElement,!0),this.attached={},this.attachedElement=null,this.checkInputs=function(){}},t.prototype.serialize=function(t){var i={};for(var r in this.attached){var n=this.attached[r],o=e.SerializationHelper.Serialize(n);i[n.getClassName()]=o}t.inputsmgr=i},t.prototype.parse=function(t){var i=t.inputsmgr;if(i){this.clear();for(var r in i){var n=e.CameraInputTypes[r];if(n){var o=i[r],s=e.SerializationHelper.Parse((function(){return new n}),o,null);this.add(s)}}}else for(var r in this.attached){var n=e.CameraInputTypes[this.attached[r].getClassName()];if(n){var s=e.SerializationHelper.Parse((function(){return new n}),t,null);this.remove(this.attached[r]),this.add(s)}}},t})();e.CameraInputsManager=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o){void 0===o&&(o=!0);var s=t.call(this,i,r,n,o)||this;return s.cameraDirection=new e.Vector3(0,0,0),s.cameraRotation=new e.Vector2(0,0),s.rotation=new e.Vector3(0,0,0),s.speed=2,s.noRotationConstraint=!1,s.lockedTarget=null,s._currentTarget=e.Vector3.Zero(),s._viewMatrix=e.Matrix.Zero(),s._camMatrix=e.Matrix.Zero(),s._cameraTransformMatrix=e.Matrix.Zero(),s._cameraRotationMatrix=e.Matrix.Zero(),s._referencePoint=new e.Vector3(0,0,1),s._currentUpVector=new e.Vector3(0,1,0),s._transformedReferencePoint=e.Vector3.Zero(),s._globalCurrentTarget=e.Vector3.Zero(),s._globalCurrentUpVector=e.Vector3.Zero(),s}return o(i,t),i.prototype.getFrontPosition=function(e){this.getWorldMatrix();var t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)},i.prototype._getLockedTargetPosition=function(){return this.lockedTarget?(this.lockedTarget.absolutePosition&&this.lockedTarget.computeWorldMatrix(),this.lockedTarget.absolutePosition||this.lockedTarget):null},i.prototype.storeState=function(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),t.prototype.storeState.call(this)},i.prototype._restoreStateValues=function(){return!!t.prototype._restoreStateValues.call(this)&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.lockedTarget=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new e.Quaternion(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this);var i=this._getLockedTargetPosition();i?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(i):this._cache.lockedTarget=i.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)},i.prototype._isSynchronizedViewMatrix=function(){if(!t.prototype._isSynchronizedViewMatrix.call(this))return!1;var e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))},i.prototype._computeLocalCameraSpeed=function(){var e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))},i.prototype.setTarget=function(t){this.upVector.normalize(),e.Matrix.LookAtLHToRef(this.position,t,this.upVector,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);var i=t.subtract(this.position);i.x>=0?this.rotation.y=-Math.atan(i.z/i.x)+Math.PI/2:this.rotation.y=-Math.atan(i.z/i.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)},i.prototype.getTarget=function(){return this._currentTarget},i.prototype._decideIfNeedsToMove=function(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(e.Tmp.Matrix[0]),e.Vector3.TransformNormalToRef(this.cameraDirection,e.Tmp.Matrix[0],e.Tmp.Vector3[0]),void this.position.addInPlace(e.Tmp.Vector3[0]);this.position.addInPlace(this.cameraDirection)},i.prototype._checkInputs=function(){var i=this._decideIfNeedsToMove(),r=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(i&&this._updatePosition(),r){if(this.rotation.x+=this.cameraRotation.x,this.rotation.y+=this.cameraRotation.y,this.rotationQuaternion){this.rotation.lengthSquared()&&e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}if(!this.noRotationConstraint){var n=Math.PI/2*.95;this.rotation.x>n&&(this.rotation.x=n),this.rotation.x<-n&&(this.rotation.x=-n)}}i&&(Math.abs(this.cameraDirection.x)=0&&r._keys.splice(o,1),i||n.preventDefault()}})))},t.prototype.detachControl=function(e){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys=[]},t.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var t=this.camera,i=0;ie.Engine.CollisionsEpsilon&&(s.position.addInPlace(s._diffPosition),s.onCollide&&r&&s.onCollide(r))})(i)},s.inputs=new e.FreeCameraInputsManager(s),s.inputs.addKeyboard().addMouse(),s}return o(i,t),Object.defineProperty(i.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;return e?e.angularSensibility:0},set:function(e){var t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),i.prototype.attachControl=function(e,t){this.inputs.attachElement(e,t)},i.prototype.detachControl=function(t){this.inputs.detachElement(t),this.cameraDirection=new e.Vector3(0,0,0),this.cameraRotation=new e.Vector2(0,0)},Object.defineProperty(i.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),i.prototype._collideWithWorld=function(t){var i;i=this.parent?e.Vector3.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,i.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset),this._collider||(this._collider=new e.Collider),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;var r=t;this.applyGravity&&(r=t.add(this.getScene().gravity)),this.getScene().collisionCoordinator.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},i.prototype._checkInputs=function(){this._localDirection||(this._localDirection=e.Vector3.Zero(),this._transformedDirection=e.Vector3.Zero()),this.inputs.checkInputs(),t.prototype._checkInputs.call(this)},i.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):t.prototype._updatePosition.call(this)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getClassName=function(){return"FreeCamera"},n([e.serializeAsVector3()],i.prototype,"ellipsoid",void 0),n([e.serializeAsVector3()],i.prototype,"ellipsoidOffset",void 0),n([e.serialize()],i.prototype,"checkCollisions",void 0),n([e.serialize()],i.prototype,"applyGravity",void 0),i})(e.TargetCamera);e.FreeCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._keys=new Array,this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0}return t.prototype.attachControl=function(t,i){var r=this;this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((function(){r._keys=[]})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((function(t){var n=t.event;if(t.type===e.KeyboardEventTypes.KEYDOWN){if(r._ctrlPressed=n.ctrlKey,r._altPressed=n.altKey,-1!==r.keysUp.indexOf(n.keyCode)||-1!==r.keysDown.indexOf(n.keyCode)||-1!==r.keysLeft.indexOf(n.keyCode)||-1!==r.keysRight.indexOf(n.keyCode)||-1!==r.keysReset.indexOf(n.keyCode)){var o=r._keys.indexOf(n.keyCode);-1===o&&r._keys.push(n.keyCode),n.preventDefault&&(i||n.preventDefault())}}else if(-1!==r.keysUp.indexOf(n.keyCode)||-1!==r.keysDown.indexOf(n.keyCode)||-1!==r.keysLeft.indexOf(n.keyCode)||-1!==r.keysRight.indexOf(n.keyCode)||-1!==r.keysReset.indexOf(n.keyCode)){var o=r._keys.indexOf(n.keyCode);o>=0&&r._keys.splice(o,1),n.preventDefault&&(i||n.preventDefault())}})))},t.prototype.detachControl=function(e){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys=[]},t.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var e=this.camera,t=0;t0?a/(1+r.wheelDeltaPercentage):a*(1+r.wheelDeltaPercentage)}else s=o.wheelDelta/(40*r.wheelPrecision);else o.detail&&(s=-o.detail/r.wheelPrecision);s&&(r.camera.inertialRadiusOffset+=s),o.preventDefault&&(i||o.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,e.PointerEventTypes.POINTERWHEEL)},t.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},t.prototype.getClassName=function(){return"ArcRotateCameraMouseWheelInput"},t.prototype.getSimpleName=function(){return"mousewheel"},n([e.serialize()],t.prototype,"wheelPrecision",void 0),n([e.serialize()],t.prototype,"wheelDeltaPercentage",void 0),t})();e.ArcRotateCameraMouseWheelInput=t,e.CameraInputTypes.ArcRotateCameraMouseWheelInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this._isPanClick=!1,this.pinchInwards=!0}return t.prototype.attachControl=function(t,i){var r,n=this,o=this.camera.getEngine(),s=null,a=null,l=0,h=0,c=0,u={x:0,y:0,isPaning:!1,isPinching:!1};this._pointerInput=function(f,d){var p=f.event,m="touch"===f.event.pointerType;if(!o.isInVRExclusivePointerMode&&(f.type===e.PointerEventTypes.POINTERMOVE||-1!==n.buttons.indexOf(p.button))){var _=p.srcElement||p.target;if(f.type===e.PointerEventTypes.POINTERDOWN&&_){try{_.setPointerCapture(p.pointerId)}catch(e){}n._isPanClick=p.button===n.camera._panningMouseButton,r={x:p.clientX,y:p.clientY,pointerId:p.pointerId,type:p.pointerType},null===s?s=r:null===a&&(a=r),i||(p.preventDefault(),t.focus())}else if(f.type===e.PointerEventTypes.POINTERDOUBLETAP)n.camera.restoreState();else if(f.type===e.PointerEventTypes.POINTERUP&&_){try{_.releasePointerCapture(p.pointerId)}catch(e){}r=null,l=0,u.isPaning=!1,u.isPinching=!1,c=0,h=0,m||(a=null),o._badOS?s=a=null:a&&s&&s.pointerId==p.pointerId?(s=a,a=null,r={x:s.x,y:s.y,pointerId:s.pointerId,type:p.pointerType}):s&&a&&a.pointerId==p.pointerId?(a=null,r={x:s.x,y:s.y,pointerId:s.pointerId,type:p.pointerType}):s=a=null,i||p.preventDefault()}else if(f.type===e.PointerEventTypes.POINTERMOVE)if(i||p.preventDefault(),s&&null===a&&r){if(0!==n.panningSensibility&&(p.ctrlKey&&n.camera._useCtrlForPanning||n._isPanClick))n.camera.inertialPanningX+=-(p.clientX-r.x)/n.panningSensibility,n.camera.inertialPanningY+=(p.clientY-r.y)/n.panningSensibility;else{var g=p.clientX-r.x,v=p.clientY-r.y;n.camera.inertialAlphaOffset-=g/n.angularSensibilityX,n.camera.inertialBetaOffset-=v/n.angularSensibilityY}r.x=p.clientX,r.y=p.clientY}else if(s&&a){var y=s.pointerId===p.pointerId?s:a;y.x=p.clientX,y.y=p.clientY;var b=n.pinchInwards?1:-1,x=s.x-a.x,T=s.y-a.y,E=x*x+T*T,P=Math.sqrt(E);if(0===l)return h=P,l=E,u.x=(s.x+a.x)/2,void(u.y=(s.y+a.y)/2);if(n.multiTouchPanAndZoom){if(n.pinchDeltaPercentage?n.camera.inertialRadiusOffset+=.001*(E-l)*n.camera.radius*n.pinchDeltaPercentage:n.camera.inertialRadiusOffset+=(E-l)/(n.pinchPrecision*((n.angularSensibilityX+n.angularSensibilityY)/2)*b),0!==n.panningSensibility){var A=(s.x+a.x)/2,M=(s.y+a.y)/2,S=A-u.x,R=M-u.y;u.x=A,u.y=M,n.camera.inertialPanningX+=-S/n.panningSensibility,n.camera.inertialPanningY+=R/n.panningSensibility}}else{if(c++,u.isPinching||c<20&&Math.abs(P-h)>n.camera.pinchToPanMaxDistance)n.pinchDeltaPercentage?n.camera.inertialRadiusOffset+=.001*(E-l)*n.camera.radius*n.pinchDeltaPercentage:n.camera.inertialRadiusOffset+=(E-l)/(n.pinchPrecision*((n.angularSensibilityX+n.angularSensibilityY)/2)*b),u.isPaning=!1,u.isPinching=!0;else if(r&&r.pointerId===y.pointerId&&0!==n.panningSensibility&&n.multiTouchPanning){if(!u.isPaning)return u.isPaning=!0,u.isPinching=!1,u.x=y.x,void(u.y=y.y);n.camera.inertialPanningX+=-(y.x-u.x)/n.panningSensibility,n.camera.inertialPanningY+=(y.y-u.y)/n.panningSensibility}r&&r.pointerId===p.pointerId&&(u.x=y.x,u.y=y.y)}l=E}}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE|e.PointerEventTypes._POINTERDOUBLETAP),this._onContextMenu=function(e){e.preventDefault()},this.camera._useCtrlForPanning||t.addEventListener("contextmenu",this._onContextMenu,!1),this._onLostFocus=function(){s=a=null,l=0,u.isPaning=!1,u.isPinching=!1,c=0,r=null,h=0},this._onMouseMove=function(e){if(o.isPointerLock){var t=e.movementX||e.mozMovementX||e.webkitMovementX||e.msMovementX||0,r=e.movementY||e.mozMovementY||e.webkitMovementY||e.msMovementY||0;n.camera.inertialAlphaOffset-=t/n.angularSensibilityX,n.camera.inertialBetaOffset-=r/n.angularSensibilityY,i||e.preventDefault()}},this._onGestureStart=function(e){void 0!==window.MSGesture&&(n._MSGestureHandler||(n._MSGestureHandler=new MSGesture,n._MSGestureHandler.target=t),n._MSGestureHandler.addPointer(e.pointerId))},this._onGesture=function(e){n.camera.radius*=e.scale,e.preventDefault&&(i||(e.stopPropagation(),e.preventDefault()))},t.addEventListener("mousemove",this._onMouseMove,!1),t.addEventListener("MSPointerDown",this._onGestureStart,!1),t.addEventListener("MSGestureChange",this._onGesture,!1),e.Tools.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},t.prototype.detachControl=function(t){this._onLostFocus&&e.Tools.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]),t&&this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._onContextMenu&&t.removeEventListener("contextmenu",this._onContextMenu),this._onMouseMove&&t.removeEventListener("mousemove",this._onMouseMove),this._onGestureStart&&t.removeEventListener("MSPointerDown",this._onGestureStart),this._onGesture&&t.removeEventListener("MSGestureChange",this._onGesture),this._isPanClick=!1,this.pinchInwards=!0,this._onMouseMove=null,this._onGestureStart=null,this._onGesture=null,this._MSGestureHandler=null,this._onLostFocus=null,this._onContextMenu=null)},t.prototype.getClassName=function(){return"ArcRotateCameraPointersInput"},t.prototype.getSimpleName=function(){return"pointers"},n([e.serialize()],t.prototype,"buttons",void 0),n([e.serialize()],t.prototype,"angularSensibilityX",void 0),n([e.serialize()],t.prototype,"angularSensibilityY",void 0),n([e.serialize()],t.prototype,"pinchPrecision",void 0),n([e.serialize()],t.prototype,"pinchDeltaPercentage",void 0),n([e.serialize()],t.prototype,"panningSensibility",void 0),n([e.serialize()],t.prototype,"multiTouchPanning",void 0),n([e.serialize()],t.prototype,"multiTouchPanAndZoom",void 0),t})();e.ArcRotateCameraPointersInput=t,e.CameraInputTypes.ArcRotateCameraPointersInput=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e){return t.call(this,e)||this}return o(i,t),i.prototype.addMouseWheel=function(){return this.add(new e.ArcRotateCameraMouseWheelInput),this},i.prototype.addPointers=function(){return this.add(new e.ArcRotateCameraPointersInput),this},i.prototype.addKeyboard=function(){return this.add(new e.ArcRotateCameraKeyboardMoveInput),this},i.prototype.addVRDeviceOrientation=function(){return this.add(new e.ArcRotateCameraVRDeviceOrientationInput),this},i})(e.CameraInputsManager);e.ArcRotateCameraInputsManager=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("ArcRotateCamera",(function(i,r){return function(){return new t(i,0,0,1,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s,a,l){void 0===l&&(l=!0);var h=t.call(this,i,e.Vector3.Zero(),a,l)||this;return h.inertialAlphaOffset=0,h.inertialBetaOffset=0,h.inertialRadiusOffset=0,h.lowerAlphaLimit=null,h.upperAlphaLimit=null,h.lowerBetaLimit=.01,h.upperBetaLimit=Math.PI,h.lowerRadiusLimit=null,h.upperRadiusLimit=null,h.inertialPanningX=0,h.inertialPanningY=0,h.pinchToPanMaxDistance=20,h.panningDistanceLimit=null,h.panningOriginTarget=e.Vector3.Zero(),h.panningInertia=.9,h.zoomOnFactor=1,h.targetScreenOffset=e.Vector2.Zero(),h.allowUpsideDown=!0,h._viewMatrix=new e.Matrix,h.panningAxis=new e.Vector3(1,1,0),h.onMeshTargetChangedObservable=new e.Observable,h.checkCollisions=!1,h.collisionRadius=new e.Vector3(.5,.5,.5),h._previousPosition=e.Vector3.Zero(),h._collisionVelocity=e.Vector3.Zero(),h._newPosition=e.Vector3.Zero(),h._computationVector=e.Vector3.Zero(),h._onCollisionPositionChange=function(e,t,i){void 0===i&&(i=null),h.getScene().workerCollisions&&h.checkCollisions&&t.multiplyInPlace(h._collider._radius),i?(h.setPosition(t),h.onCollide&&h.onCollide(i)):h._previousPosition.copyFrom(h.position);var r=Math.cos(h.alpha),n=Math.sin(h.alpha),o=Math.cos(h.beta),s=Math.sin(h.beta);0===s&&(s=1e-4);var a=h._getTargetPosition();h._computationVector.copyFromFloats(h.radius*r*s,h.radius*o,h.radius*n*s),a.addToRef(h._computationVector,h._newPosition),h.position.copyFrom(h._newPosition);var l=h.upVector;h.allowUpsideDown&&h.beta<0&&(l=l.clone(),l=l.negate()),h._computeViewMatrix(h.position,a,l),h._viewMatrix.m[12]+=h.targetScreenOffset.x,h._viewMatrix.m[13]+=h.targetScreenOffset.y,h._collisionTriggered=!1},h._target=e.Vector3.Zero(),s&&h.setTarget(s),h.alpha=r,h.beta=n,h.radius=o,h.getViewMatrix(),h.inputs=new e.ArcRotateCameraInputsManager(h),h.inputs.addKeyboard().addMouseWheel().addPointers(),h}return o(i,t),Object.defineProperty(i.prototype,"target",{get:function(){return this._target},set:function(e){this.setTarget(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"angularSensibilityX",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"angularSensibilityY",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pinchPrecision",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchPrecision:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pinchDeltaPercentage",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"panningSensibility",{get:function(){var e=this.inputs.attached.pointers;return e?e.panningSensibility:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wheelPrecision",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wheelDeltaPercentage",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"bouncingBehavior",{get:function(){return this._bouncingBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useBouncingBehavior",{get:function(){return null!=this._bouncingBehavior},set:function(t){t!==this.useBouncingBehavior&&(t?(this._bouncingBehavior=new e.BouncingBehavior,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"framingBehavior",{get:function(){return this._framingBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useFramingBehavior",{get:function(){return null!=this._framingBehavior},set:function(t){t!==this.useFramingBehavior&&(t?(this._framingBehavior=new e.FramingBehavior,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"autoRotationBehavior",{get:function(){return this._autoRotationBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"useAutoRotationBehavior",{get:function(){return null!=this._autoRotationBehavior},set:function(t){t!==this.useAutoRotationBehavior&&(t?(this._autoRotationBehavior=new e.AutoRotationBehavior,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))},enumerable:!0,configurable:!0}),i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache._target=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=e.Vector2.Zero()},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)},i.prototype._getTargetPosition=function(){if(this._targetHost&&this._targetHost.getAbsolutePosition){var e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}var t=this._getLockedTargetPosition();return t||this._target},i.prototype.storeState=function(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),t.prototype.storeState.call(this)},i.prototype._restoreStateValues=function(){return!!t.prototype._restoreStateValues.call(this)&&(this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.setTarget(this._storedTarget.clone()),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)},i.prototype._isSynchronizedViewMatrix=function(){return!!t.prototype._isSynchronizedViewMatrix.call(this)&&(this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset))},i.prototype.attachControl=function(e,t,i,r){var n=this;void 0===i&&(i=!0),void 0===r&&(r=2),this._useCtrlForPanning=i,this._panningMouseButton=r,this.inputs.attachElement(e,t),this._reset=function(){n.inertialAlphaOffset=0,n.inertialBetaOffset=0,n.inertialRadiusOffset=0,n.inertialPanningX=0,n.inertialPanningY=0}},i.prototype.detachControl=function(e){this.inputs.detachElement(e),this._reset&&this._reset()},i.prototype._checkInputs=function(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){var i=this.inertialAlphaOffset;this.beta<=0&&(i*=-1),this.getScene().useRightHandedSystem&&(i*=-1),this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(i*=-1),this.alpha+=i,this.beta+=this.inertialBetaOffset,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit)},i.prototype.rebuildAnglesAndRadius=function(){this.position.subtractToRef(this._getTargetPosition(),this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4),this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha),this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()},i.prototype.setPosition=function(e){this.position.equals(e)||(this.position.copyFrom(e),this.rebuildAnglesAndRadius())},i.prototype.setTarget=function(e,t,i){if(void 0===t&&(t=!1),void 0===i&&(i=!1),e.getBoundingInfo)this._targetBoundingCenter=t?e.getBoundingInfo().boundingBox.centerWorld.clone():null,this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{var r=e,n=this._getTargetPosition();if(n&&!i&&n.equals(r))return;this._targetHost=null,this._target=r,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}this.rebuildAnglesAndRadius()},i.prototype._getViewMatrix=function(){var t=Math.cos(this.alpha),i=Math.sin(this.alpha),r=Math.cos(this.beta),n=Math.sin(this.beta);0===n&&(n=1e-4);var o=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*t*n,this.radius*r,this.radius*i*n),o.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions)this._collider||(this._collider=new e.Collider),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this.position,this._collisionVelocity),this._collisionTriggered=!0, +this.getScene().collisionCoordinator.getNewPosition(this.position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId);else{this.position.copyFrom(this._newPosition);var s=this.upVector;this.allowUpsideDown&&n<0&&(s=s.clone(),s=s.negate()),this._computeViewMatrix(this.position,o,s),this._viewMatrix.m[12]+=this.targetScreenOffset.x,this._viewMatrix.m[13]+=this.targetScreenOffset.y}return this._currentTarget=o,this._viewMatrix},i.prototype.zoomOn=function(t,i){void 0===i&&(i=!1),t=t||this.getScene().meshes;var r=e.Mesh.MinMax(t),n=e.Vector3.Distance(r.min,r.max);this.radius=n*this.zoomOnFactor,this.focusOn({min:r.min,max:r.max,distance:n},i)},i.prototype.focusOn=function(t,i){void 0===i&&(i=!1);var r,n;if(void 0===t.min){var o=t||this.getScene().meshes;r=e.Mesh.MinMax(o),n=e.Vector3.Distance(r.min,r.max)}else{var s=t;r=s,n=s.distance}this._target=e.Mesh.Center(r),i||(this.maxZ=2*n)},i.prototype.createRigCamera=function(t,r){var n=0;switch(this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:n=this._cameraRigParams.stereoHalfAngle*(0===r?1:-1);break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:n=this._cameraRigParams.stereoHalfAngle*(0===r?-1:1)}var o=new i(t,this.alpha+n,this.beta,this.radius,this._target,this.getScene());return o._cameraRigParams={},o},i.prototype._updateRigCameras=function(){var i=this._rigCameras[0],r=this._rigCameras[1];switch(i.beta=r.beta=this.beta,i.radius=r.radius=this.radius,this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:i.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}t.prototype._updateRigCameras.call(this)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getClassName=function(){return"ArcRotateCamera"},n([e.serialize()],i.prototype,"alpha",void 0),n([e.serialize()],i.prototype,"beta",void 0),n([e.serialize()],i.prototype,"radius",void 0),n([e.serializeAsVector3("target")],i.prototype,"_target",void 0),n([e.serialize()],i.prototype,"inertialAlphaOffset",void 0),n([e.serialize()],i.prototype,"inertialBetaOffset",void 0),n([e.serialize()],i.prototype,"inertialRadiusOffset",void 0),n([e.serialize()],i.prototype,"lowerAlphaLimit",void 0),n([e.serialize()],i.prototype,"upperAlphaLimit",void 0),n([e.serialize()],i.prototype,"lowerBetaLimit",void 0),n([e.serialize()],i.prototype,"upperBetaLimit",void 0),n([e.serialize()],i.prototype,"lowerRadiusLimit",void 0),n([e.serialize()],i.prototype,"upperRadiusLimit",void 0),n([e.serialize()],i.prototype,"inertialPanningX",void 0),n([e.serialize()],i.prototype,"inertialPanningY",void 0),n([e.serialize()],i.prototype,"pinchToPanMaxDistance",void 0),n([e.serialize()],i.prototype,"panningDistanceLimit",void 0),n([e.serializeAsVector3()],i.prototype,"panningOriginTarget",void 0),n([e.serialize()],i.prototype,"panningInertia",void 0),n([e.serialize()],i.prototype,"zoomOnFactor",void 0),n([e.serialize()],i.prototype,"allowUpsideDown",void 0),i})(e.TargetCamera);e.ArcRotateCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_3",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n){var o=t.call(this,i,n)||this;return o.groundColor=new e.Color3(0,0,0),o.direction=r||e.Vector3.Up(),o}return o(i,t),i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.getClassName=function(){return"HemisphericLight"},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(e.Vector3.Zero())),this.direction},i.prototype.getShadowGenerator=function(){return null},i.prototype.transferToEffect=function(t,i){var r=e.Vector3.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",r.x,r.y,r.z,0,i),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),i),this},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),this._worldMatrix},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_HEMISPHERICLIGHT},i.prototype.prepareLightSpecificDefines=function(e,t){e["HEMILIGHT"+t]=!0},n([e.serializeAsColor3()],i.prototype,"groundColor",void 0),n([e.serializeAsVector3()],i.prototype,"direction",void 0),i})(e.Light);e.HemisphericLight=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(){var e=null!==t&&t.apply(this,arguments)||this;return e._needProjectionMatrixCompute=!0,e}return o(i,t),i.prototype._setPosition=function(e){this._position=e},Object.defineProperty(i.prototype,"position",{get:function(){return this._position},set:function(e){this._setPosition(e)},enumerable:!0,configurable:!0}),i.prototype._setDirection=function(e){this._direction=e},Object.defineProperty(i.prototype,"direction",{get:function(){return this._direction},set:function(e){this._setDirection(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowMinZ",{get:function(){return this._shadowMinZ},set:function(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowMaxZ",{get:function(){return this._shadowMaxZ},set:function(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),i.prototype.computeTransformedInformation=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=e.Vector3.Zero()),e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=e.Vector3.Zero()),e.Vector3.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0)},i.prototype.getDepthScale=function(){return 50},i.prototype.getShadowDirection=function(e){return this.transformedDirection?this.transformedDirection:this.direction},i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(this.position)),this.direction},i.prototype.getRotation=function(){this.direction.normalize();var t=e.Vector3.Cross(this.direction,e.Axis.Y),i=e.Vector3.Cross(t,this.direction);return e.Vector3.RotationFromAxis(t,i,this.direction)},i.prototype.needCube=function(){return!1},i.prototype.needProjectionMatrixCompute=function(){return this._needProjectionMatrixCompute},i.prototype.forceProjectionMatrixCompute=function(){this._needProjectionMatrixCompute=!0},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this._worldMatrix},i.prototype.getDepthMinZ=function(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ},i.prototype.getDepthMaxZ=function(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ},i.prototype.setShadowProjectionMatrix=function(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this},n([e.serializeAsVector3()],i.prototype,"position",null),n([e.serializeAsVector3()],i.prototype,"direction",null),n([e.serialize()],i.prototype,"shadowMinZ",null),n([e.serialize()],i.prototype,"shadowMaxZ",null),i})(e.Light);e.ShadowLight=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_0",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(e,i,r){var n=t.call(this,e,r)||this;return n._shadowAngle=Math.PI/2,n.position=i,n}return o(i,t),Object.defineProperty(i.prototype,"shadowAngle",{get:function(){return this._shadowAngle},set:function(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"direction",{get:function(){return this._direction},set:function(e){var t=this.needCube();this._direction=e,this.needCube()!==t&&this._shadowGenerator&&this._shadowGenerator.recreateShadowMap()},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"PointLight"},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_POINTLIGHT},i.prototype.needCube=function(){return!this.direction},i.prototype.getShadowDirection=function(i){if(this.direction)return t.prototype.getShadowDirection.call(this,i);switch(i){case 0:return new e.Vector3(1,0,0);case 1:return new e.Vector3(-1,0,0);case 2:return new e.Vector3(0,-1,0);case 3:return new e.Vector3(0,1,0);case 4:return new e.Vector3(0,0,1);case 5:return new e.Vector3(0,0,-1)}return e.Vector3.Zero()},i.prototype._setDefaultShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;n&&e.Matrix.PerspectiveFovLHToRef(this.shadowAngle,1,this.getDepthMinZ(n),this.getDepthMaxZ(n),t)},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this)},i.prototype.prepareLightSpecificDefines=function(e,t){e["POINTLIGHT"+t]=!0},n([e.serialize()],i.prototype,"shadowAngle",null),i})(e.ShadowLight);e.PointLight=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_1",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(e,i,r){var n=t.call(this,e,r)||this;return n._shadowFrustumSize=0,n._shadowOrthoScale=.1,n.autoUpdateExtends=!0,n._orthoLeft=Number.MAX_VALUE,n._orthoRight=Number.MIN_VALUE,n._orthoTop=Number.MIN_VALUE,n._orthoBottom=Number.MAX_VALUE,n.position=i.scale(-1),n.direction=i,n}return o(i,t),Object.defineProperty(i.prototype,"shadowFrustumSize",{get:function(){return this._shadowFrustumSize},set:function(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowOrthoScale",{get:function(){return this._shadowOrthoScale},set:function(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"DirectionalLight"},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_DIRECTIONALLIGHT},i.prototype._setDefaultShadowProjectionMatrix=function(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e,t):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)},i.prototype._setDefaultFixedFrustumShadowProjectionMatrix=function(t,i){var r=this.getScene().activeCamera;r&&e.Matrix.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,t)},i.prototype._setDefaultAutoExtendShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;if(n){if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){var o=e.Vector3.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;for(var s=0;sthis._orthoRight&&(this._orthoRight=o.x),o.y>this._orthoTop&&(this._orthoTop=o.y)}}var u=this._orthoRight-this._orthoLeft,f=this._orthoTop-this._orthoBottom;e.Matrix.OrthoOffCenterLHToRef(this._orthoLeft-u*this.shadowOrthoScale,this._orthoRight+u*this.shadowOrthoScale,this._orthoBottom-f*this.shadowOrthoScale,this._orthoTop+f*this.shadowOrthoScale,void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,t)}},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)},i.prototype.getDepthMinZ=function(e){return 1},i.prototype.getDepthMaxZ=function(e){return 1},i.prototype.prepareLightSpecificDefines=function(e,t){e["DIRLIGHT"+t]=!0},n([e.serialize()],i.prototype,"shadowFrustumSize",null),n([e.serialize()],i.prototype,"shadowOrthoScale",null),n([e.serialize()],i.prototype,"autoUpdateExtends",void 0),i})(e.ShadowLight);e.DirectionalLight=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("Light_Type_2",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),e.Vector3.Zero(),0,0,r)}}));var t=(function(t){function i(i,r,n,o,s,a){var l=t.call(this,i,a)||this;return l._projectionTextureMatrix=e.Matrix.Zero(),l._projectionTextureLightNear=1e-6,l._projectionTextureLightFar=1e3,l._projectionTextureUpDirection=e.Vector3.Up(),l._projectionTextureViewLightDirty=!0,l._projectionTextureProjectionLightDirty=!0,l._projectionTextureDirty=!0,l._projectionTextureViewTargetVector=e.Vector3.Zero(),l._projectionTextureViewLightMatrix=e.Matrix.Zero(),l._projectionTextureProjectionLightMatrix=e.Matrix.Zero(),l._projectionTextureScalingMatrix=e.Matrix.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),l.position=r,l.direction=n,l.angle=o,l.exponent=s,l}return o(i,t),Object.defineProperty(i.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"shadowAngleScale",{get:function(){return this._shadowAngleScale},set:function(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureMatrix",{get:function(){return this._projectionTextureMatrix},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureLightNear",{get:function(){return this._projectionTextureLightNear},set:function(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureLightFar",{get:function(){return this._projectionTextureLightFar},set:function(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureUpDirection",{get:function(){return this._projectionTextureUpDirection},set:function(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"projectionTexture",{get:function(){return this._projectionTexture},set:function(e){this._projectionTexture=e,this._projectionTextureDirty=!0},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"SpotLight"},i.prototype.getTypeID=function(){return e.Light.LIGHTTYPEID_SPOTLIGHT},i.prototype._setDirection=function(e){t.prototype._setDirection.call(this,e),this._projectionTextureViewLightDirty=!0},i.prototype._setPosition=function(e){t.prototype._setPosition.call(this,e),this._projectionTextureViewLightDirty=!0},i.prototype._setDefaultShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;if(n){this._shadowAngleScale=this._shadowAngleScale||1;var o=this._shadowAngleScale*this._angle;e.Matrix.PerspectiveFovLHToRef(o,1,this.getDepthMinZ(n),this.getDepthMaxZ(n),t)}},i.prototype._computeProjectionTextureViewLightMatrix=function(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.position.addToRef(this.direction,this._projectionTextureViewTargetVector),e.Matrix.LookAtLHToRef(this.position,this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)},i.prototype._computeProjectionTextureProjectionLightMatrix=function(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;var t=this.projectionTextureLightFar,i=this.projectionTextureLightNear,r=t/(t-i),n=-r*i,o=1/Math.tan(this._angle/2);e.Matrix.FromValuesToRef(o/1,0,0,0,0,o,0,0,0,0,r,1,0,0,n,0,this._projectionTextureProjectionLightMatrix)},i.prototype._computeProjectionTextureMatrix=function(){this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(t,i){var r;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,i),r=e.Vector3.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,i),r=e.Vector3.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",r.x,r.y,r.z,Math.cos(.5*this.angle),i),this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),t.setMatrix("textureProjectionMatrix"+i,this._projectionTextureMatrix),t.setTexture("projectionLightSampler"+i,this.projectionTexture)),this},i.prototype.dispose=function(){t.prototype.dispose.call(this),this._projectionTexture&&this._projectionTexture.dispose()},i.prototype.prepareLightSpecificDefines=function(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!this.projectionTexture},n([e.serialize()],i.prototype,"angle",null),n([e.serialize()],i.prototype,"shadowAngleScale",null),n([e.serialize()],i.prototype,"exponent",void 0),n([e.serialize()],i.prototype,"projectionTextureLightNear",null),n([e.serialize()],i.prototype,"projectionTextureLightFar",null),n([e.serialize()],i.prototype,"projectionTextureUpDirection",null),n([e.serializeAsTexture("projectedLightTexture")],i.prototype,"_projectionTexture",void 0),i})(e.ShadowLight);e.SpotLight=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=e.Animation.ANIMATIONLOOPMODE_CYCLE}return t})();e.AnimationPropertiesOverride=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i){this.name=e,this.from=t,this.to=i}return e.prototype.clone=function(){return new e(this.name,this.from,this.to)},e})();e.AnimationRange=t;var i=(function(){function e(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}return e.prototype._clone=function(){return new e(this.frame,this.action,this.onlyOnce)},e})();e.AnimationEvent=i;var r=(function(){function t(e){this.path=e,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e.Vector3(t.x,0,t.y)},t.prototype.moveAhead=function(e){return void 0===e&&(e=.002),this.move(e),this},t.prototype.moveBack=function(e){return void 0===e&&(e=.002),this.move(-e),this},t.prototype.move=function(e){if(Math.abs(e)>1)throw"step size should be less than 1.";return this.value+=e,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.raiseOnChange=function(){var e=this;return this._onchange.forEach((function(t){return t(e)})),this},t.prototype.onchange=function(e){return this._onchange.push(e),this},t})();e.PathCursor=r;var n;!(function(e){e[e.STEP=1]="STEP"})(n=e.AnimationKeyInterpolation||(e.AnimationKeyInterpolation={}));var o=(function(){function i(e,t,r,n,o,s){this.name=e,this.targetProperty=t,this.framePerSecond=r,this.dataType=n,this.loopMode=o,this.enableBlending=s,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=n,this.loopMode=void 0===o?i.ANIMATIONLOOPMODE_CYCLE:o}return i._PrepareAnimation=function(t,r,n,o,s,a,l,h){var c=void 0;if(!isNaN(parseFloat(s))&&isFinite(s)?c=i.ANIMATIONTYPE_FLOAT:s instanceof e.Quaternion?c=i.ANIMATIONTYPE_QUATERNION:s instanceof e.Vector3?c=i.ANIMATIONTYPE_VECTOR3:s instanceof e.Vector2?c=i.ANIMATIONTYPE_VECTOR2:s instanceof e.Color3?c=i.ANIMATIONTYPE_COLOR3:s instanceof e.Size&&(c=i.ANIMATIONTYPE_SIZE),void 0==c)return null;var u=new i(t,r,n,c,l),f=[{frame:0,value:s},{frame:o,value:a}];return u.setKeys(f),void 0!==h&&u.setEasingFunction(h),u},i.CreateAnimation=function(e,t,r,n){var o=new i(e+"Animation",e,r,t,i.ANIMATIONLOOPMODE_CONSTANT);return o.setEasingFunction(n),o},i.CreateAndStartAnimation=function(e,t,r,n,o,s,a,l,h,c){var u=i._PrepareAnimation(e,r,n,o,s,a,l,h);return u?t.getScene().beginDirectAnimation(t,[u],0,o,1===u.loopMode,1,c):null},i.CreateAndStartHierarchyAnimation=function(e,t,r,n,o,s,a,l,h,c,u){var f=i._PrepareAnimation(e,n,o,s,a,l,h,c);return f?t.getScene().beginDirectHierarchyAnimation(t,r,[f],0,s,1===f.loopMode,1,u):null},i.CreateMergeAndStartAnimation=function(e,t,r,n,o,s,a,l,h,c){var u=i._PrepareAnimation(e,r,n,o,s,a,l,h);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,o,1===u.loopMode,1,c)):null},i.TransitionTo=function(e,t,i,r,n,o,s,a){if(void 0===a&&(a=null),s<=0)return i[e]=t,a&&a(),null;var l=n*(s/1e3);o.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(o);var h=r.beginAnimation(i,0,l,!1);return h.onAnimationEnd=a,h},Object.defineProperty(i.prototype,"runtimeAnimations",{get:function(){return this._runtimeAnimations},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"hasRunningRuntimeAnimations",{get:function(){for(var e=0,t=this._runtimeAnimations;e=0;o--)this._keys[o].frame>=r&&this._keys[o].frame<=n&&this._keys.splice(o,1);this._ranges[e]=null}},i.prototype.getRange=function(e){return this._ranges[e]},i.prototype.getKeys=function(){return this._keys},i.prototype.getHighestFrame=function(){for(var e=0,t=0,i=this._keys.length;t0)return a.clone?a.clone():a;var l=this.getKeys(),h=Math.max(0,Math.min(l.length-1,Math.floor(l.length*(e-l[0].frame)/(l[l.length-1].frame-l[0].frame))-1));if(l[h].frame>=e)for(;h-1>=0&&l[h].frame>=e;)h--;for(var c=h;c=e){var f=l[c],d=this._getKeyValue(f.value);if(f.interpolation===n.STEP)return d;var p=this._getKeyValue(u.value),m=void 0!==f.outTangent&&void 0!==u.inTangent,_=u.frame-f.frame,g=(e-f.frame)/_,v=this.getEasingFunction();switch(null!=v&&(g=v.ease(g)),this.dataType){case i.ANIMATIONTYPE_FLOAT:var y=m?this.floatInterpolateFunctionWithTangents(d,f.outTangent*_,p,u.inTangent*_,g):this.floatInterpolateFunction(d,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return y;case i.ANIMATIONLOOPMODE_RELATIVE:return s*t+y}break;case i.ANIMATIONTYPE_QUATERNION:var b=m?this.quaternionInterpolateFunctionWithTangents(d,f.outTangent.scale(_),p,u.inTangent.scale(_),g):this.quaternionInterpolateFunction(d,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return b;case i.ANIMATIONLOOPMODE_RELATIVE:return b.addInPlace(s.scale(t))}return b;case i.ANIMATIONTYPE_VECTOR3:var x=m?this.vector3InterpolateFunctionWithTangents(d,f.outTangent.scale(_),p,u.inTangent.scale(_),g):this.vector3InterpolateFunction(d,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return x;case i.ANIMATIONLOOPMODE_RELATIVE:return x.add(s.scale(t))}case i.ANIMATIONTYPE_VECTOR2:var T=m?this.vector2InterpolateFunctionWithTangents(d,f.outTangent.scale(_),p,u.inTangent.scale(_),g):this.vector2InterpolateFunction(d,p,g);switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return T;case i.ANIMATIONLOOPMODE_RELATIVE:return T.add(s.scale(t))}case i.ANIMATIONTYPE_SIZE:switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(d,p,g);case i.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(d,p,g).add(s.scale(t))}case i.ANIMATIONTYPE_COLOR3:switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.color3InterpolateFunction(d,p,g);case i.ANIMATIONLOOPMODE_RELATIVE:return this.color3InterpolateFunction(d,p,g).add(s.scale(t))}case i.ANIMATIONTYPE_MATRIX:switch(o){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:if(i.AllowMatricesInterpolation)return this.matrixInterpolateFunction(d,p,g,r);case i.ANIMATIONLOOPMODE_RELATIVE:return d}}break}}return this._getKeyValue(l[l.length-1].value)},i.prototype.matrixInterpolateFunction=function(t,r,n,o){return i.AllowMatrixDecomposeForInterpolation?o?(e.Matrix.DecomposeLerpToRef(t,r,n,o),o):e.Matrix.DecomposeLerp(t,r,n):o?(e.Matrix.LerpToRef(t,r,n,o),o):e.Matrix.Lerp(t,r,n)},i.prototype.clone=function(){var e=new i(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(var t in this._ranges){var r=this._ranges[t];r&&(e._ranges[t]=r.clone())}}return e},i.prototype.setKeys=function(e){this._keys=e.slice(0)},i.prototype.serialize=function(){var e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;var t=this.dataType;e.keys=[];for(var r=this.getKeys(),n=0;n=1&&(l=c.values[1]),c.values.length>=2&&(h=c.values[2]);break;case i.ANIMATIONTYPE_QUATERNION:if(r=e.Quaternion.FromArray(c.values),c.values.length>=8){var u=e.Quaternion.FromArray(c.values.slice(4,8));u.equals(e.Quaternion.Zero())||(l=u)}if(c.values.length>=12){var f=e.Quaternion.FromArray(c.values.slice(8,12));f.equals(e.Quaternion.Zero())||(h=f)}break;case i.ANIMATIONTYPE_MATRIX:r=e.Matrix.FromArray(c.values);break;case i.ANIMATIONTYPE_COLOR3:r=e.Color3.FromArray(c.values);break;case i.ANIMATIONTYPE_VECTOR3:default:r=e.Vector3.FromArray(c.values)}var d={};d.frame=c.frame,d.value=r,void 0!=l&&(d.inTangent=l),void 0!=h&&(d.outTangent=h),a.push(d)}if(o.setKeys(a),t.ranges)for(n=0;nr[0].frame&&(this._from=r[0].frame),this._toe){var a={frame:e,value:o.value,inTangent:o.inTangent,outTangent:o.outTangent,interpolation:o.interpolation};n.splice(0,0,a)}if(s.frame-1&&this._scene.animationGroups.splice(e,1)},t.prototype._checkAnimationGroupEnded=function(e){var t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))},t})();e.AnimationGroup=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i,r){var n=this;this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._targetPath="",this._weight=1,this._ratioOffset=0,this._previousDelay=0,this._previousRatio=0,this._animation=t,this._target=e,this._scene=i,this._host=r,t._runtimeAnimations.push(this);var o=t.getEvents();o&&o.length>0&&o.forEach((function(e){n._events.push(e._clone())}))}return Object.defineProperty(t.prototype,"currentFrame",{get:function(){return this._currentFrame},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weight",{get:function(){return this._weight},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentValue",{get:function(){return this._currentValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"targetPath",{get:function(){return this._targetPath},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){return this._activeTarget},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animation",{get:function(){return this._animation},enumerable:!0,configurable:!0}),t.prototype.reset=function(e){if(void 0===e&&(e=!1),e)if(this._target instanceof Array)for(var t=0,i=0,r=this._target;i-1&&this._animation.runtimeAnimations.splice(e,1)},t.prototype._interpolate=function(t,i,r,n,o){return this._currentFrame=t,this._animation.dataType!==e.Animation.ANIMATIONTYPE_MATRIX||this._workValue||(this._workValue=e.Matrix.Zero()),this._animation._interpolate(t,i,this._workValue,r,n,o)},t.prototype.setValue=function(e,t){if(void 0===t&&(t=1),this._target instanceof Array)for(var i=0,r=0,n=this._target;r1){for(var l=t[a[0]],h=1;ht[t.length-1].frame&&(e=t[t.length-1].frame);var i=this._interpolate(e,0,this._getCorrectLoopMode());this.setValue(i,-1)},t.prototype._prepareForSpeedRatioChange=function(e){var t=this._previousDelay*(this._animation.framePerSecond*e)/1e3;this._ratioOffset=this._previousRatio-t},t.prototype.animate=function(t,i,r,n,o,s){void 0===s&&(s=-1);var a=this._animation.targetPropertyPath;if(!a||a.length<1)return this._stopped=!0,!1;var l=!0,h=this._animation.getKeys();if(0!==h[0].frame){var c={frame:0,value:h[0].value};h.splice(0,0,c)}else if(1===h.length){var c={frame:.001,value:h[0].value};h.push(c)}(ih[h.length-1].frame)&&(i=h[0].frame),(rh[h.length-1].frame)&&(r=h[h.length-1].frame),i===r&&(i>h[0].frame?i--:ri&&d>=f||i>r&&d<=f)&&!n)l=!1,p=this._animation._getKeyValue(h[h.length-1].value);else if(this._getCorrectLoopMode()!==e.Animation.ANIMATIONLOOPMODE_CYCLE){var m=r.toString()+i.toString();if(!this._offsetsCache[m]){var _=this._interpolate(i,0,e.Animation.ANIMATIONLOOPMODE_CYCLE),g=this._interpolate(r,0,e.Animation.ANIMATIONLOOPMODE_CYCLE);switch(this._animation.dataType){case e.Animation.ANIMATIONTYPE_FLOAT:this._offsetsCache[m]=g-_;break;case e.Animation.ANIMATIONTYPE_QUATERNION:this._offsetsCache[m]=g.subtract(_);break;case e.Animation.ANIMATIONTYPE_VECTOR3:this._offsetsCache[m]=g.subtract(_);case e.Animation.ANIMATIONTYPE_VECTOR2:this._offsetsCache[m]=g.subtract(_);case e.Animation.ANIMATIONTYPE_SIZE:this._offsetsCache[m]=g.subtract(_);case e.Animation.ANIMATIONTYPE_COLOR3:this._offsetsCache[m]=g.subtract(_)}this._highLimitsCache[m]=g}p=this._highLimitsCache[m],u=this._offsetsCache[m]}if(void 0===u)switch(this._animation.dataType){case e.Animation.ANIMATIONTYPE_FLOAT:u=0;break;case e.Animation.ANIMATIONTYPE_QUATERNION:u=new e.Quaternion(0,0,0,0);break;case e.Animation.ANIMATIONTYPE_VECTOR3:u=e.Vector3.Zero();break;case e.Animation.ANIMATIONTYPE_VECTOR2:u=e.Vector2.Zero();break;case e.Animation.ANIMATIONTYPE_SIZE:u=e.Size.Zero();break;case e.Animation.ANIMATIONTYPE_COLOR3:u=e.Color3.Black()}var v=d/f>>0,y=l?i+d%f:r;if(this._host&&this._host.syncRoot){var b=this._host.syncRoot;y=i+(r-i)*((b.masterFrame-b.fromFrame)/(b.toFrame-b.fromFrame))}var x=this._events;if(f>0&&this.currentFrame>y||f<0&&this.currentFrame0&&y>=x[T].frame&&x[T].frame>=i||f<0&&y<=x[T].frame&&x[T].frame<=i){var P=x[T];P.isDone||(P.onlyOnce&&(x.splice(T,1),T--),P.isDone=!0,P.action())}return l||(this._stopped=!0),l},t})();e.RuntimeAnimation=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a,l){void 0===r&&(r=0),void 0===n&&(n=100),void 0===o&&(o=!1),void 0===s&&(s=1),this.target=i,this.fromFrame=r,this.toFrame=n,this.loopAnimation=o,this.onAnimationEnd=a,this._localDelayOffset=null,this._pausedDelay=null,this._runtimeAnimations=new Array,this._paused=!1,this._speedRatio=1,this._weight=-1,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new e.Observable,this._scene=t,l&&this.appendAnimations(i,l),this._speedRatio=s,t._activeAnimatables.push(this)}return Object.defineProperty(t.prototype,"syncRoot",{get:function(){return this._syncRoot},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"masterFrame",{get:function(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weight",{get:function(){return this._weight},set:function(e){if(-1===e)return void(this._weight=-1);this._weight=Math.min(Math.max(e,0),1)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"speedRatio",{get:function(){return this._speedRatio},set:function(e){for(var t=0;t-1&&(this._scene._activeAnimatables.splice(t,1),this._scene._activeAnimatables.push(this))}return this},t.prototype.getAnimations=function(){return this._runtimeAnimations},t.prototype.appendAnimations=function(t,i){for(var r=0;r-1){for(var r=this._runtimeAnimations,n=r.length-1;n>=0;n--){var o=r[n];e&&o.animation.name!=e||(t&&!t(o.target)||(o.dispose(),r.splice(n,1)))}0==r.length&&(this._scene._activeAnimatables.splice(i,1),this._raiseOnAnimationEnd())}}else{var n=this._scene._activeAnimatables.indexOf(this);if(n>-1){this._scene._activeAnimatables.splice(n,1);for(var r=this._runtimeAnimations,n=0;n=.5?.5*(1-this.easeInCore(2*(1-t)))+.5:.5*this.easeInCore(2*t)},e._EASINGMODE_EASEIN=0,e._EASINGMODE_EASEOUT=1,e._EASINGMODE_EASEINOUT=2,e})();e.EasingFunction=t;var i=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)},t})(t);e.CircleEase=i;var r=(function(e){function t(t){void 0===t&&(t=1);var i=e.call(this)||this;return i.amplitude=t,i}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)},t})(t);e.BackEase=r;var n=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=2);var r=e.call(this)||this;return r.bounces=t,r.bounciness=i,r}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.bounces),i=this.bounciness;i<=1&&(i=1.001);var r=Math.pow(i,t),n=1-i,o=(1-r)/n+.5*r,s=e*o,a=Math.log(-s*(1-i)+1)/Math.log(i),l=Math.floor(a),h=l+1,c=(1-Math.pow(i,l))/(n*o),u=(1-Math.pow(i,h))/(n*o),f=.5*(c+u),d=e-f,p=f-c;return-Math.pow(1/i,t-l)/(p*p)*(d-p)*(d+p)},t})(t);e.BounceEase=n;var s=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e*e},t})(t);e.CubicEase=s;var a=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=3);var r=e.call(this)||this;return r.oscillations=t,r.springiness=i,r}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.oscillations),i=Math.max(0,this.springiness);return(0==i?e:(Math.exp(i*e)-1)/(Math.exp(i)-1))*Math.sin((6.283185307179586*t+1.5707963267948966)*e)},t})(t);e.ElasticEase=a;var l=(function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.exponent=t,i}return o(t,e),t.prototype.easeInCore=function(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)},t})(t);e.ExponentialEase=l;var h=(function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.power=t,i}return o(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.power);return Math.pow(e,t)},t})(t);e.PowerEase=h;var c=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e},t})(t);e.QuadraticEase=c;var u=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e*e*e},t})(t);e.QuarticEase=u;var f=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return e*e*e*e*e},t})(t);e.QuinticEase=f;var d=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.easeInCore=function(e){return 1-Math.sin(1.5707963267948966*(1-e))},t})(t);e.SineEase=d;var p=(function(t){function i(e,i,r,n){void 0===e&&(e=0),void 0===i&&(i=0),void 0===r&&(r=1),void 0===n&&(n=1);var o=t.call(this)||this;return o.x1=e,o.y1=i,o.x2=r,o.y2=n,o}return o(i,t),i.prototype.easeInCore=function(t){return e.BezierCurve.interpolate(t,this.x1,this.y1,this.x2,this.y2)},i})(t);e.BezierCurveEase=p})(r||(r={}));var r;!(function(e){var t=(function(){function e(e){this._actionManager=e}return e.prototype.isValid=function(){return!0},e.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},e.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},e.prototype.serialize=function(){},e.prototype._serialize=function(e){return{type:2,children:[],name:e.name,properties:e.properties}},e})();e.Condition=t;var i=(function(t){function i(e,r,n,o,s){void 0===s&&(s=i.IsEqual);var a=t.call(this,e)||this;return a.propertyPath=n,a.value=o,a.operator=s,a._target=r,a._effectiveTarget=a._getEffectiveTarget(r,a.propertyPath),a._property=a._getProperty(a.propertyPath),a}return o(i,t),Object.defineProperty(i,"IsEqual",{get:function(){return i._IsEqual},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsDifferent",{get:function(){return i._IsDifferent},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsGreater",{get:function(){return i._IsGreater},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsLesser",{get:function(){return i._IsLesser},enumerable:!0,configurable:!0}),i.prototype.isValid=function(){switch(this.operator){case i.IsGreater:return this._effectiveTarget[this._property]>this.value;case i.IsLesser:return this._effectiveTarget[this._property]-1&&this._scene.actionManagers.splice(e,1)},t.prototype.getScene=function(){return this._scene},t.prototype.hasSpecificTriggers=function(e){for(var t=0;t-1)return!0}return!1},t.prototype.hasSpecificTrigger=function(e,t){for(var i=0;i=t._OnPickTrigger&&i.trigger<=t._OnPointerOutTrigger)return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPickTriggers",{get:function(){for(var e=0;e=t._OnPickTrigger&&i.trigger<=t._OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"HasTriggers",{get:function(){for(var e in t.Triggers)if(t.Triggers.hasOwnProperty(e))return!0;return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"HasPickTriggers",{get:function(){for(var e in t.Triggers)if(t.Triggers.hasOwnProperty(e)){var i=parseInt(e);if(i>=t._OnPickTrigger&&i<=t._OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),t.HasSpecificTrigger=function(e){for(var i in t.Triggers)if(t.Triggers.hasOwnProperty(i)){var r=parseInt(i);if(r===e)return!0}return!1},t.prototype.registerAction=function(i){return i.trigger===t.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(e.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(i),t.Triggers[i.trigger]?t.Triggers[i.trigger]++:t.Triggers[i.trigger]=1,i._actionManager=this,i._prepare(),i)},t.prototype.unregisterAction=function(e){var i=this.actions.indexOf(e);return-1!==i&&(this.actions.splice(i,1),t.Triggers[e.trigger]-=1,0===t.Triggers[e.trigger]&&delete t.Triggers[e.trigger],delete e._actionManager,!0)},t.prototype.processTrigger=function(e,i){for(var r=0;r0;if(2===i.type?f.push(o):f.push(r),m){for(var _=new Array,g=0;g0){var f=u.properties[0].value,d=null===u.properties[0].targetType?f:n.getMeshByName(f);d._meshId&&(d.mesh=n.getMeshByID(d._meshId)),c={trigger:t[u.name],parameter:d}}else c=t[u.name];for(var p=0;p>0;this._vertexData[o+10]=t.cellIndex-s*n,this._vertexData[o+11]=s,this._vertexData[o+12]=t.color.r,this._vertexData[o+13]=t.color.g,this._vertexData[o+14]=t.color.b,this._vertexData[o+15]=t.color.a},t.prototype.intersects=function(t,i,r,n){for(var o=Math.min(this._capacity,this.sprites.length),s=e.Vector3.Zero(),a=e.Vector3.Zero(),l=Number.MAX_VALUE,h=null,c=e.Vector3.Zero(),u=i.getViewMatrix(),f=0;fp&&(l=p,h=d,n))break}}}if(h){var m=new e.PickingInfo;return m.hit=!0,m.pickedSprite=h,m.distance=l,m}return null},t.prototype.render=function(){if(this._effectBase.isReady()&&this._effectFog.isReady()&&this._spriteTexture&&this._spriteTexture.isReady()){for(var t=this._scene.getEngine(),i=this._spriteTexture.getBaseSize(),r=t.getDeltaTime(),n=Math.min(this._capacity,this.sprites.length),o=i.width/this.cellWidth,s=0,a=0;athis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,this.cellIndex>this._toIndex&&(this._loopAnimation?this.cellIndex=this._fromIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()))))},t.prototype.dispose=function(){for(var e=0;et.x)return!1}else if(i=1/this.direction.x,r=(e.x-this.origin.x)*i,n=(t.x-this.origin.x)*i,n===-1/0&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yt.y)return!1}else if(i=1/this.direction.y,r=(e.y-this.origin.y)*i,n=(t.y-this.origin.y)*i,n===-1/0&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zt.z)return!1}else if(i=1/this.direction.z,r=(e.z-this.origin.z)*i,n=(t.z-this.origin.z)*i,n===-1/0&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;return!0},t.prototype.intersectsBox=function(e){return this.intersectsBoxMinMax(e.minimum,e.maximum)},t.prototype.intersectsSphere=function(e){var t=e.center.x-this.origin.x,i=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=t*t+i*i+r*r,o=e.radius*e.radius;if(n<=o)return!0;var s=t*this.direction.x+i*this.direction.y+r*this.direction.z;return!(s<0)&&n-s*s<=o},t.prototype.intersectsTriangle=function(t,i,r){this._edge1||(this._edge1=e.Vector3.Zero(),this._edge2=e.Vector3.Zero(),this._pvec=e.Vector3.Zero(),this._tvec=e.Vector3.Zero(),this._qvec=e.Vector3.Zero()),i.subtractToRef(t,this._edge1),r.subtractToRef(t,this._edge2),e.Vector3.CrossToRef(this.direction,this._edge2,this._pvec);var n=e.Vector3.Dot(this._edge1,this._pvec);if(0===n)return null;var o=1/n;this.origin.subtractToRef(t,this._tvec);var s=e.Vector3.Dot(this._tvec,this._pvec)*o;if(s<0||s>1)return null;e.Vector3.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Vector3.Dot(this.direction,this._qvec)*o;if(a<0||s+a>1)return null;var l=e.Vector3.Dot(this._edge2,this._qvec)*o;return l>this.length?null:new e.IntersectionInfo(s,a,l)},t.prototype.intersectsPlane=function(t){var i,r=e.Vector3.Dot(t.normal,this.direction);if(Math.abs(r)<9.99999997475243e-7)return null;var n=e.Vector3.Dot(t.normal,this.origin);return i=(-t.d-n)/r,i<0?i<-9.99999997475243e-7?null:0:i},t.prototype.intersectsMesh=function(i,r){var n=e.Tmp.Matrix[0];return i.getWorldMatrix().invertToRef(n),this._tmpRay?t.TransformToRef(this,n,this._tmpRay):this._tmpRay=t.Transform(this,n),i.intersects(this._tmpRay,r)},t.prototype.intersectsMeshes=function(e,t,i){i?i.length=0:i=[];for(var r=0;rt.distance?1:0},t.prototype.intersectionSegment=function(i,r,n){var o,s,a,l,h=this.origin.add(this.direction.multiplyByFloats(t.rayl,t.rayl,t.rayl)),c=r.subtract(i),u=h.subtract(this.origin),f=i.subtract(this.origin),d=e.Vector3.Dot(c,c),p=e.Vector3.Dot(c,u),m=e.Vector3.Dot(u,u),_=e.Vector3.Dot(c,f),g=e.Vector3.Dot(u,f),v=d*m-p*p,y=v,b=v;vy&&(s=y,l=g+p,b=m)),l<0?(l=0,-_<0?s=0:-_>d?s=y:(s=-_,y=d)):l>b&&(l=b,-_+p<0?s=0:-_+p>d?s=y:(s=-_+p,y=d)),o=Math.abs(s)0&&a<=this.length&&T.lengthSquared()i.x+r)&&(!(i.x-r>t.x)&&(!(e.y>i.y+r)&&(!(i.y-r>t.y)&&(!(e.z>i.z+r)&&!(i.z-r>t.z)))))},i=(function(){var e={root:0,found:!1};return function(t,i,r,n){e.root=0,e.found=!1;var o=i*i-4*t*r;if(o<0)return e;var s=Math.sqrt(o),a=(-i-s)/(2*t),l=(-i+s)/(2*t);if(a>l){var h=l;l=a,a=h}return a>0&&a0&&l=0))},r.prototype._canDoCollision=function(i,r,n,o){var s=e.Vector3.Distance(this._basePointWorld,i),a=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+a+r)&&!!t(n,o,this._basePointWorld,this._velocityWorldLength+a)},r.prototype._testTriangle=function(t,r,n,o,s,a){var l,h=!1;r||(r=[]),r[t]||(r[t]=new e.Plane(0,0,0,0),r[t].copyFromPoints(n,o,s));var c=r[t];if(a||c.isFrontFacingTo(this._normalizedVelocity,0)){var u=c.signedDistanceTo(this._basePoint),f=e.Vector3.Dot(c.normal,this._velocity);if(0==f){if(Math.abs(u)>=1)return;h=!0,l=0}else{l=(-1-u)/f;var d=(1-u)/f;if(l>d){var p=d;d=l,l=p}if(l>1||d<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);var m=!1,_=1;if(h||(this._basePoint.subtractToRef(c.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(l,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,n,o,s,c.normal)&&(m=!0,_=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!m){var g=this._velocity.lengthSquared(),v=g;this._basePoint.subtractToRef(n,this._tempVector);var y=2*e.Vector3.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,x=i(v,y,b,_);x.found&&(_=x.root,m=!0,this._collisionPoint.copyFrom(n)),this._basePoint.subtractToRef(o,this._tempVector),y=2*e.Vector3.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,x=i(v,y,b,_),x.found&&(_=x.root,m=!0,this._collisionPoint.copyFrom(o)),this._basePoint.subtractToRef(s,this._tempVector),y=2*e.Vector3.Dot(this._velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,x=i(v,y,b,_),x.found&&(_=x.root,m=!0,this._collisionPoint.copyFrom(s)),o.subtractToRef(n,this._edge),n.subtractToRef(this._basePoint,this._baseToVertex);var T=this._edge.lengthSquared(),E=e.Vector3.Dot(this._edge,this._velocity),P=e.Vector3.Dot(this._edge,this._baseToVertex);if(v=T*-g+E*E,y=T*(2*e.Vector3.Dot(this._velocity,this._baseToVertex))-2*E*P,b=T*(1-this._baseToVertex.lengthSquared())+P*P,x=i(v,y,b,_),x.found){var A=(E*x.root-P)/T;A>=0&&A<=1&&(_=x.root,m=!0,this._edge.scaleInPlace(A),n.addToRef(this._edge,this._collisionPoint))}s.subtractToRef(o,this._edge),o.subtractToRef(this._basePoint,this._baseToVertex),T=this._edge.lengthSquared(),E=e.Vector3.Dot(this._edge,this._velocity),P=e.Vector3.Dot(this._edge,this._baseToVertex),v=T*-g+E*E,y=T*(2*e.Vector3.Dot(this._velocity,this._baseToVertex))-2*E*P,b=T*(1-this._baseToVertex.lengthSquared())+P*P,x=i(v,y,b,_),x.found&&(A=(E*x.root-P)/T)>=0&&A<=1&&(_=x.root,m=!0,this._edge.scaleInPlace(A),o.addToRef(this._edge,this._collisionPoint)),n.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),T=this._edge.lengthSquared(),E=e.Vector3.Dot(this._edge,this._velocity),P=e.Vector3.Dot(this._edge,this._baseToVertex),v=T*-g+E*E,y=T*(2*e.Vector3.Dot(this._velocity,this._baseToVertex))-2*E*P,b=T*(1-this._baseToVertex.lengthSquared())+P*P,x=i(v,y,b,_),x.found&&(A=(E*x.root-P)/T)>=0&&A<=1&&(_=x.root,m=!0,this._edge.scaleInPlace(A),s.addToRef(this._edge,this._collisionPoint))}if(m){var M=_*this._velocity.length();(!this.collisionFound||M4)){++n._runningUpdated;var e={updatedMeshes:n._addUpdateMeshesList,updatedGeometries:n._addUpdateGeometriesList,removedGeometries:n._toRemoveGeometryArray,removedMeshes:n._toRemoveMeshesArray},i={payload:e,taskType:t.UPDATE},r=[];for(var o in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(o)&&(r.push(i.payload.updatedGeometries[o].indices.buffer),r.push(i.payload.updatedGeometries[o].normals.buffer),r.push(i.payload.updatedGeometries[o].positions.buffer));n._worker.postMessage(i,r),n._addUpdateMeshesList={},n._addUpdateGeometriesList={},n._toRemoveGeometryArray=[],n._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(r){var o=r.data;if(o.error!=i.SUCCESS)return void e.Tools.Warn("error returned from worker!");switch(o.taskType){case t.INIT:n._init=!0,n._scene.meshes.forEach((function(e){n.onMeshAdded(e)})),n._scene.getGeometries().forEach((function(e){n.onGeometryAdded(e)}));break;case t.UPDATE:n._runningUpdated--;break;case t.COLLIDE:var s=o.payload;if(!n._collisionsCallbackArray[s.collisionId])return;var a=n._collisionsCallbackArray[s.collisionId];if(a){var l=n._scene.getMeshByUniqueID(s.collidedMeshUniqueId);l&&a(s.collisionId,e.Vector3.FromArray(s.newPosition),l)}n._collisionsCallbackArray[s.collisionId]=null}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return r.prototype.getNewPosition=function(e,i,r,n,o,s,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(r._radius,this._scaledPosition),i.divideToRef(r._radius,this._scaledVelocity),this._collisionsCallbackArray[a]=s;var l={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:r._radius.asArray()},collisionId:a,excludedMeshUniqueId:o?o.uniqueId:null,maximumRetry:n},h={payload:l,taskType:t.COLLIDE};this._worker.postMessage(h)}},r.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var r=e.WorkerIncluded?e.Engine.CodeRepository+"Collisions/babylon.collisionWorker.js":URL.createObjectURL(new Blob([e.CollisionWorker],{type:"application/javascript"}));this._worker=new Worker(r),this._worker.onmessage=this._onMessageFromWorker;var n={payload:{},taskType:t.INIT};this._worker.postMessage(n)},r.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},r.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},r.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},r.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},r.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},r.SerializeMesh=function(t){var i=[];t.subMeshes&&(i=t.subMeshes.map((function(e,t){var i=e.getBoundingInfo();return{position:t,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:i.boundingSphere.centerWorld.asArray(),sphereRadius:i.boundingSphere.radiusWorld,boxMinimum:i.boundingBox.minimumWorld.asArray(),boxMaximum:i.boundingBox.maximumWorld.asArray()}})));var r=null;if(t instanceof e.Mesh){var n=t.geometry;r=n?n.id:null}else if(t instanceof e.InstancedMesh){var n=t.sourceMesh&&t.sourceMesh.geometry;r=n?n.id:null}var o=t.getBoundingInfo();return{uniqueId:t.uniqueId,id:t.id,name:t.name,geometryId:r,sphereCenter:o.boundingSphere.centerWorld.asArray(),sphereRadius:o.boundingSphere.radiusWorld,boxMinimum:o.boundingBox.minimumWorld.asArray(),boxMaximum:o.boundingBox.maximumWorld.asArray(),worldMatrixFromCache:t.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:t.checkCollisions}},r.SerializeGeometry=function(t){return{id:t.id,positions:new Float32Array(t.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(t.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Uint32Array(t.getIndices()||[])}},r})();e.CollisionCoordinatorWorker=r;var n=(function(){function t(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return t.prototype.getNewPosition=function(e,t,i,r,n,o,s){e.divideToRef(i._radius,this._scaledPosition),t.divideToRef(i._radius,this._scaledVelocity),i.collidedMesh=null,i._retry=0,i._initialVelocity=this._scaledVelocity,i._initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,r,this._finalPosition,n),this._finalPosition.multiplyInPlace(i._radius),o(s,this._finalPosition,i.collidedMesh)},t.prototype.init=function(e){this._scene=e},t.prototype.destroy=function(){},t.prototype.onMeshAdded=function(e){},t.prototype.onMeshUpdated=function(e){},t.prototype.onMeshRemoved=function(e){},t.prototype.onGeometryAdded=function(e){},t.prototype.onGeometryUpdated=function(e){},t.prototype.onGeometryDeleted=function(e){},t.prototype._collideWithWorld=function(t,i,r,n,o,s){void 0===s&&(s=null);var a=10*e.Engine.CollisionsEpsilon;if(r._retry>=n)return void o.copyFrom(t);var l=s?s.collisionMask:r.collisionMask;r._initialize(t,i,a);for(var h=0;h=n.lifeTime)return l._emitFromParticle(n),l.recycleParticle(n),o--,"continue";var s=n.age/n.lifeTime;l._colorGradients&&l._colorGradients.length>0?e.Tools.GetCurrentGradient(s,l._colorGradients,(function(t,i,r){t!==n._currentColorGradient&&(n._currentColor1.copyFrom(n._currentColor2),i.getColorToRef(n._currentColor2),n._currentColorGradient=t),e.Color4.LerpToRef(n._currentColor1,n._currentColor2,r,n.color)})):(n.colorStep.scaleToRef(l._scaledUpdateSpeed,l._scaledColorStep),n.color.addInPlace(l._scaledColorStep),n.color.a<0&&(n.color.a=0)),l._angularSpeedGradients&&l._angularSpeedGradients.length>0&&e.Tools.GetCurrentGradient(s,l._angularSpeedGradients,(function(t,i,r){t!==n._currentAngularSpeedGradient&&(n._currentAngularSpeed1=n._currentAngularSpeed2,n._currentAngularSpeed2=i.getFactor(),n._currentAngularSpeedGradient=t),n.angularSpeed=e.Scalar.Lerp(n._currentAngularSpeed1,n._currentAngularSpeed2,r)})),n.angle+=n.angularSpeed*l._scaledUpdateSpeed;var a=l._scaledUpdateSpeed;if(l._velocityGradients&&l._velocityGradients.length>0&&e.Tools.GetCurrentGradient(s,l._velocityGradients,(function(t,i,r){t!==n._currentVelocityGradient&&(n._currentVelocity1=n._currentVelocity2,n._currentVelocity2=i.getFactor(),n._currentVelocityGradient=t),a*=e.Scalar.Lerp(n._currentVelocity1,n._currentVelocity2,r)})),n.direction.scaleToRef(a,l._scaledDirection),n.position.addInPlace(l._scaledDirection),i&&r){var h=e.Tmp.Vector3[0],c=e.Tmp.Vector3[1];l._emitterWorldMatrix.getTranslationToRef(c),n.position.subtractToRef(c,h);var u=l._fetchR(h.y,h.z,r.width,r.height,i),f=l._fetchR(h.x+.33,h.z+.33,r.width,r.height,i),d=l._fetchR(h.x-.33,h.y-.33,r.width,r.height,i),p=e.Tmp.Vector3[0],m=e.Tmp.Vector3[1];p.copyFromFloats((2*u-1)*l.noiseStrength.x,(2*f-1)*l.noiseStrength.y,(2*d-1)*l.noiseStrength.z),p.scaleToRef(l._scaledUpdateSpeed,m),n.direction.addInPlace(m)}l.gravity.scaleToRef(l._scaledUpdateSpeed,l._scaledGravity),n.direction.addInPlace(l._scaledGravity),l._sizeGradients&&l._sizeGradients.length>0&&e.Tools.GetCurrentGradient(s,l._sizeGradients,(function(t,i,r){t!==n._currentSizeGradient&&(n._currentSize1=n._currentSize2,n._currentSize2=i.getFactor(),n._currentSizeGradient=t),n.size=e.Scalar.Lerp(n._currentSize1,n._currentSize2,r)})),l._isAnimationSheetEnabled&&n.updateCellIndex()})()}}return t.prototype.getColorGradients=function(){return this._colorGradients},t.prototype.getSizeGradients=function(){return this._sizeGradients},t.prototype.getLifeTimeGradients=function(){return this._lifeTimeGradients},t.prototype.getAngularSpeedGradients=function(){return this._angularSpeedGradients},t.prototype.getVelocityGradients=function(){return this._velocityGradients},Object.defineProperty(t.prototype,"direction1",{get:function(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction2",{get:function(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minEmitBox",{get:function(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxEmitBox",{get:function(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isAnimationSheetEnabled",{get:function(){return this._isAnimationSheetEnabled},set:function(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._resetEffect())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isBillboardBased",{get:function(){return this._isBillboardBased},set:function(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._resetEffect())},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},Object.defineProperty(t.prototype,"particles",{get:function(){return this._particles},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"ParticleSystem"},t.prototype._fetchR=function(e,t,i,r,n){return e=.5*Math.abs(e)+.5,t=.5*Math.abs(t)+.5,n[4*((e*i%i|0)+(t*r%r|0)*i)]/255},t.prototype._addFactorGradient=function(t,i,r,n){var o=new e.FactorGradient;o.gradient=i,o.factor1=r,o.factor2=n,t.push(o),t.sort((function(e,t){return e.gradientt.gradient?1:0}))},t.prototype._removeFactorGradient=function(e,t){if(e)for(var i=0,r=0,n=e;rt.gradient?1:0})),this},t.prototype.removeColorGradient=function(e){if(!this._colorGradients)return this;for(var t=0,i=0,r=this._colorGradients;i0,this.emitter.position){var i=this.emitter;this._emitterWorldMatrix=i.getWorldMatrix()}else{var r=this.emitter;this._emitterWorldMatrix=e.Matrix.Translation(r.x,r.y,r.z)}this.updateFunction(this._particles);for(var n,o,s=this,a=0;a0){var i=e.Scalar.Clamp(s._actualFrame/s.targetStopDuration);e.Tools.GetCurrentGradient(i,s._lifeTimeGradients,(function(t,r,o){var s=t,a=r,l=s.getFactor(),h=a.getFactor(),c=(i-s.gradient)/(a.gradient-s.gradient);n.lifeTime=e.Scalar.Lerp(l,h,c)}))}else n.lifeTime=e.Scalar.RandomRange(s.minLifeTime,s.maxLifeTime);s._sizeGradients&&0!==s._sizeGradients.length?(n._currentSizeGradient=s._sizeGradients[0],n._currentSize1=n._currentSizeGradient.getFactor(),n.size=n._currentSize1,s._sizeGradients.length>1?n._currentSize2=s._sizeGradients[1].getFactor():n._currentSize2=n._currentSize1):n.size=e.Scalar.RandomRange(s.minSize,s.maxSize),n.scale.copyFromFloats(e.Scalar.RandomRange(s.minScaleX,s.maxScaleX),e.Scalar.RandomRange(s.minScaleY,s.maxScaleY)),s._angularSpeedGradients&&0!==s._angularSpeedGradients.length?(n._currentAngularSpeedGradient=s._angularSpeedGradients[0],n.angularSpeed=n._currentAngularSpeedGradient.getFactor(),n._currentAngularSpeed1=n.angularSpeed,s._angularSpeedGradients.length>1?n._currentAngularSpeed2=s._angularSpeedGradients[1].getFactor():n._currentAngularSpeed2=n._currentAngularSpeed1):n.angularSpeed=e.Scalar.RandomRange(s.minAngularSpeed,s.maxAngularSpeed),n.angle=e.Scalar.RandomRange(s.minInitialRotation,s.maxInitialRotation),s._velocityGradients&&s._velocityGradients.length>0&&(n._currentVelocityGradient=s._velocityGradients[0],n._currentVelocity1=n._currentVelocityGradient.getFactor(),s._velocityGradients.length>1?n._currentVelocity2=s._velocityGradients[1].getFactor():n._currentVelocity2=n._currentVelocity1),s._colorGradients&&0!==s._colorGradients.length?(n._currentColorGradient=s._colorGradients[0],n._currentColorGradient.getColorToRef(n.color),n._currentColor1.copyFrom(n.color),s._colorGradients.length>1?s._colorGradients[1].getColorToRef(n._currentColor2):n._currentColor2.copyFrom(n.color)):(o=e.Scalar.RandomRange(0,1),e.Color4.LerpToRef(s.color1,s.color2,o,n.color),s.colorDead.subtractToRef(n.color,s._colorDiff),s._colorDiff.scaleToRef(1/n.lifeTime,n.colorStep)),s._isAnimationSheetEnabled&&(n._initialStartSpriteCellID=s.startSpriteCellID,n._initialEndSpriteCellID=s.endSpriteCellID)})())break}},t._GetAttributeNamesOrOptions=function(t,i){void 0===t&&(t=!1),void 0===i&&(i=!1);var r=[e.VertexBuffer.PositionKind,e.VertexBuffer.ColorKind,"angle","offset","size"];return t&&r.push("cellIndex"),i||r.push("direction"),r},t._GetEffectCreationOptions=function(e){void 0===e&&(e=!1);var t=["invView","view","projection","vClipPlane","textureMask","translationPivot","eyePosition"];return e&&t.push("particlesInfos"),t},t.prototype._getEffect=function(){if(this._customEffect)return this._customEffect;var i=[];if(this._scene.clipPlane&&i.push("#define CLIPPLANE"),this._isAnimationSheetEnabled&&i.push("#define ANIMATESHEET"),this._isBillboardBased)switch(i.push("#define BILLBOARD"),this.billboardMode){case e.AbstractMesh.BILLBOARDMODE_Y:i.push("#define BILLBOARDY");break;case e.AbstractMesh.BILLBOARDMODE_ALL:}var r=i.join("\n");if(this._cachedDefines!==r){this._cachedDefines=r;var n=t._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased),o=t._GetEffectCreationOptions(this._isAnimationSheetEnabled);this._effect=this._scene.getEngine().createEffect("particles",n,o,["diffuseSampler"],r)}return this._effect},t.prototype.animate=function(e){if(void 0===e&&(e=!1),this._started){if(!e){var t=this._getEffect();if(!(this.emitter&&t.isReady()&&this.particleTexture&&this.particleTexture.isReady()))return;if(this._currentRenderId===this._scene.getRenderId())return;this._currentRenderId=this._scene.getRenderId()}this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:this._scene.getAnimationRatio());var i;if(this.manualEmitCount>-1?(i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0):(i=this.emitRate*this._scaledUpdateSpeed>>0,this._newPartsExcess+=this.emitRate*this._scaledUpdateSpeed-i),this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene._toBeDisposed.push(this))),!e){for(var r=0,n=0;n-1&&this._scene.particleSystems.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.prototype.createPointEmitter=function(t,i){var r=new e.PointParticleEmitter;return r.direction1=t,r.direction2=i,this.particleEmitterType=r,r},t.prototype.createHemisphericEmitter=function(t,i){void 0===t&&(t=1),void 0===i&&(i=1) +;var r=new e.HemisphericParticleEmitter(t,i);return this.particleEmitterType=r,r},t.prototype.createSphereEmitter=function(t,i){void 0===t&&(t=1),void 0===i&&(i=1);var r=new e.SphereParticleEmitter(t,i);return this.particleEmitterType=r,r},t.prototype.createDirectedSphereEmitter=function(t,i,r){void 0===t&&(t=1),void 0===i&&(i=new e.Vector3(0,1,0)),void 0===r&&(r=new e.Vector3(0,1,0));var n=new e.SphereDirectedParticleEmitter(t,i,r);return this.particleEmitterType=n,n},t.prototype.createConeEmitter=function(t,i){void 0===t&&(t=1),void 0===i&&(i=Math.PI/4);var r=new e.ConeParticleEmitter(t,i);return this.particleEmitterType=r,r},t.prototype.createBoxEmitter=function(t,i,r,n){var o=new e.BoxParticleEmitter;return this.particleEmitterType=o,this.direction1=t,this.direction2=i,this.minEmitBox=r,this.maxEmitBox=n,o},t.prototype.clone=function(i,r){var n=null,o=null;if(null!=this.customShader){o=this.customShader;var s=o.shaderOptions.defines.length>0?o.shaderOptions.defines.join("\n"):"";n=this._scene.getEngine().createEffectForParticles(o.shaderPath.fragmentElement,o.shaderOptions.uniforms,o.shaderOptions.samplers,s)}else this._customEffect&&(n=this._customEffect);var a=new t(i,this._capacity,this._scene,n);return a.customShader=o,e.Tools.DeepCopy(this,a,["particles","customShader"]),void 0===r&&(r=this.emitter),a.emitter=r,this.particleTexture&&(a.particleTexture=new e.Texture(this.particleTexture.url,this._scene)),this.preventAutoStart||a.start(),a},t.prototype.serialize=function(){var e={};return t._Serialize(e,this),e.textureMask=this.textureMask.asArray(),e.customShader=this.customShader,e.preventAutoStart=this.preventAutoStart,e.isAnimationSheetEnabled=this._isAnimationSheetEnabled,e},t._Serialize=function(t,i){if(t.name=i.name,t.id=i.id,t.capacity=i.getCapacity(),i.emitter.position){var r=i.emitter;t.emitterId=r.id}else{var n=i.emitter;t.emitter=n.asArray()}i.particleEmitterType&&(t.particleEmitterType=i.particleEmitterType.serialize()),i.particleTexture&&(t.textureName=i.particleTexture.name),e.Animation.AppendSerializedAnimations(i,t),t.renderingGroupId=i.renderingGroupId,t.isBillboardBased=i.isBillboardBased,t.minAngularSpeed=i.minAngularSpeed,t.maxAngularSpeed=i.maxAngularSpeed,t.minSize=i.minSize,t.maxSize=i.maxSize,t.minScaleX=i.minScaleX,t.maxScaleX=i.maxScaleX,t.minScaleY=i.minScaleY,t.maxScaleY=i.maxScaleY,t.minEmitPower=i.minEmitPower,t.maxEmitPower=i.maxEmitPower,t.minLifeTime=i.minLifeTime,t.maxLifeTime=i.maxLifeTime,t.emitRate=i.emitRate,t.gravity=i.gravity.asArray(),t.noiseStrength=i.noiseStrength.asArray(),t.color1=i.color1.asArray(),t.color2=i.color2.asArray(),t.colorDead=i.colorDead.asArray(),t.updateSpeed=i.updateSpeed,t.targetStopDuration=i.targetStopDuration,t.blendMode=i.blendMode,t.preWarmCycles=i.preWarmCycles,t.preWarmStepOffset=i.preWarmStepOffset,t.minInitialRotation=i.minInitialRotation,t.maxInitialRotation=i.maxInitialRotation,t.startSpriteCellID=i.startSpriteCellID,t.endSpriteCellID=i.endSpriteCellID,t.spriteCellChangeSpeed=i.spriteCellChangeSpeed,t.spriteCellWidth=i.spriteCellWidth,t.spriteCellHeight=i.spriteCellHeight;var o=i.getColorGradients();if(o){t.colorGradients=[];for(var s=0,a=o;s0?a.shaderOptions.defines.join("\n"):"";s=r.getEngine().createEffectForParticles(a.shaderPath.fragmentElement,a.shaderOptions.uniforms,a.shaderOptions.samplers,l)}var h=new t(o,i.capacity,r,s,i.isAnimationSheetEnabled);return h.customShader=a,i.id&&(h.id=i.id),i.preventAutoStart&&(h.preventAutoStart=i.preventAutoStart),t._Parse(i,h,r,n),h.textureMask=e.Color4.FromArray(i.textureMask),h.preventAutoStart||h.start(),h},t.BLENDMODE_ONEONE=0,t.BLENDMODE_STANDARD=1,t.BLENDMODE_ADD=2,t})();e.ParticleSystem=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.direction1=new e.Vector3(0,1,0),this.direction2=new e.Vector3(0,1,0),this.minEmitBox=new e.Vector3(-.5,-.5,-.5),this.maxEmitBox=new e.Vector3(.5,.5,.5)}return t.prototype.startDirectionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.direction1.x,this.direction2.x),o=e.Scalar.RandomRange(this.direction1.y,this.direction2.y),s=e.Scalar.RandomRange(this.direction1.z,this.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(n,o,s,t,i)},t.prototype.startPositionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),o=e.Scalar.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),s=e.Scalar.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);e.Vector3.TransformCoordinatesFromFloatsToRef(n,o,s,t,i)},t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)},t.prototype.getEffectDefines=function(){return"#define BOXEMITTER"},t.prototype.getClassName=function(){return"BoxParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e},t.prototype.parse=function(t){e.Vector3.FromArrayToRef(t.direction1,0,this.direction1),e.Vector3.FromArrayToRef(t.direction2,0,this.direction2),e.Vector3.FromArrayToRef(t.minEmitBox,0,this.minEmitBox),e.Vector3.FromArrayToRef(t.maxEmitBox,0,this.maxEmitBox)},t})();e.BoxParticleEmitter=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i){void 0===e&&(e=1),void 0===t&&(t=Math.PI),void 0===i&&(i=0),this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}return Object.defineProperty(t.prototype,"radius",{get:function(){return this._radius},set:function(e){this._radius=e,this._buildHeight()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._buildHeight()},enumerable:!0,configurable:!0}),t.prototype._buildHeight=function(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1},t.prototype.startDirectionFunction=function(t,i,r){if(1===Math.abs(Math.cos(this._angle)))e.Vector3.TransformNormalFromFloatsToRef(0,1,0,t,i);else{var n=r.position.subtract(t.getTranslation()).normalize(),o=e.Scalar.RandomRange(0,this.directionRandomizer),s=e.Scalar.RandomRange(0,this.directionRandomizer),a=e.Scalar.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=s,n.z+=a,n.normalize(),e.Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,t,i)}},t.prototype.startPositionFunction=function(t,i,r){var n,o=e.Scalar.RandomRange(0,2*Math.PI);this.emitFromSpawnPointOnly?n=1e-4:(n=e.Scalar.RandomRange(0,this.heightRange),n=1-n*n);var s=this._radius-e.Scalar.RandomRange(0,this._radius*this.radiusRange);s*=n;var a=s*Math.sin(o),l=s*Math.cos(o),h=n*this._height;e.Vector3.TransformCoordinatesFromFloatsToRef(a,h,l,t,i)},t.prototype.clone=function(){var i=new t(this._radius,this._angle,this.directionRandomizer);return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)},t.prototype.getEffectDefines=function(){var e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e},t.prototype.getClassName=function(){return"ConeParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e},t.prototype.parse=function(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer},t})();e.ConeParticleEmitter=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return t.prototype.startDirectionFunction=function(t,i,r){var n=r.position.subtract(t.getTranslation()).normalize(),o=e.Scalar.RandomRange(0,this.directionRandomizer),s=e.Scalar.RandomRange(0,this.directionRandomizer),a=e.Scalar.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=s,n.z+=a,n.normalize(),e.Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,t,i)},t.prototype.startPositionFunction=function(t,i,r){var n=this.radius-e.Scalar.RandomRange(0,this.radius*this.radiusRange),o=e.Scalar.RandomRange(0,1),s=e.Scalar.RandomRange(0,2*Math.PI),a=Math.acos(2*o-1),l=n*Math.cos(s)*Math.sin(a),h=n*Math.cos(a),c=n*Math.sin(s)*Math.sin(a);e.Vector3.TransformCoordinatesFromFloatsToRef(l,h,c,t,i)},t.prototype.clone=function(){var i=new t(this.radius,this.directionRandomizer);return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},t.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER"},t.prototype.getClassName=function(){return"SphereParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},t.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},t})();e.SphereParticleEmitter=t;var i=(function(t){function i(i,r,n){void 0===i&&(i=1),void 0===r&&(r=new e.Vector3(0,1,0)),void 0===n&&(n=new e.Vector3(0,1,0));var o=t.call(this,i)||this;return o.direction1=r,o.direction2=n,o}return o(i,t),i.prototype.startDirectionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.direction1.x,this.direction2.x),o=e.Scalar.RandomRange(this.direction1.y,this.direction2.y),s=e.Scalar.RandomRange(this.direction1.z,this.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(n,o,s,t,i)},i.prototype.clone=function(){var t=new i(this.radius,this.direction1,this.direction2);return e.Tools.DeepCopy(this,t),t},i.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},i.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"},i.prototype.getClassName=function(){return"SphereDirectedParticleEmitter"},i.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e},i.prototype.parse=function(e){t.prototype.parse.call(this,e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)},i})(t);e.SphereDirectedParticleEmitter=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return t.prototype.startDirectionFunction=function(t,i,r){var n=r.position.subtract(t.getTranslation()).normalize(),o=e.Scalar.RandomRange(0,this.directionRandomizer),s=e.Scalar.RandomRange(0,this.directionRandomizer),a=e.Scalar.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=s,n.z+=a,n.normalize(),e.Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,t,i)},t.prototype.startPositionFunction=function(t,i,r){var n=this.radius-e.Scalar.RandomRange(0,this.radius*this.radiusRange),o=e.Scalar.RandomRange(0,1),s=e.Scalar.RandomRange(0,2*Math.PI),a=Math.acos(2*o-1),l=n*Math.cos(s)*Math.sin(a),h=n*Math.cos(a),c=n*Math.sin(s)*Math.sin(a);e.Vector3.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,t,i)},t.prototype.clone=function(){var i=new t(this.radius,this.directionRandomizer);return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},t.prototype.getEffectDefines=function(){return"#define HEMISPHERICEMITTER"},t.prototype.getClassName=function(){return"HemisphericParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},t.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},t})();e.HemisphericParticleEmitter=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.direction1=new e.Vector3(0,1,0),this.direction2=new e.Vector3(0,1,0)}return t.prototype.startDirectionFunction=function(t,i,r){var n=e.Scalar.RandomRange(this.direction1.x,this.direction2.x),o=e.Scalar.RandomRange(this.direction1.y,this.direction2.y),s=e.Scalar.RandomRange(this.direction1.z,this.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(n,o,s,t,i)},t.prototype.startPositionFunction=function(t,i,r){e.Vector3.TransformCoordinatesFromFloatsToRef(0,0,0,t,i)},t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},t.prototype.getEffectDefines=function(){return"#define POINTEMITTER"},t.prototype.getClassName=function(){return"PointParticleEmitter"},t.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e},t.prototype.parse=function(t){e.Vector3.FromArrayToRef(t.direction1,0,this.direction1),e.Vector3.FromArrayToRef(t.direction2,0,this.direction2)},t})();e.PointParticleEmitter=t})(r||(r={}));var r;!(function(e){e.AbstractScene.AddParser(e.SceneComponentConstants.NAME_PARTICLESYSTEM,(function(t,i,r,n){var o=e.AbstractScene.GetIndividualParser(e.SceneComponentConstants.NAME_PARTICLESYSTEM);if(o&&void 0!==t.particleSystems&&null!==t.particleSystems)for(var s=0,a=t.particleSystems.length;s4&&(s.push(e.VertexBuffer.MatricesIndicesExtraKind),s.push(e.VertexBuffer.MatricesWeightsExtraKind)),o.push("#define NUM_BONE_INFLUENCERS "+t.numBoneInfluencers),o.push("#define BonesPerMesh "+(t.skeleton.bones.length+1)),a.addCPUSkinningFallback(0,t),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones")):o.push("#define NUM_BONE_INFLUENCERS 0");for(var h in this._textures)if(!this._textures[h].isReady())return!1;t&&this._shouldTurnAlphaTestOn(t)&&o.push("#define ALPHATEST");var c=this._effect,u=o.join("\n");return this._effect=n.createEffect(this._shaderPath,{attributes:s,uniformsNames:this._options.uniforms,uniformBuffersNames:this._options.uniformBuffers,samplers:this._options.samplers,defines:u,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError},n),!!this._effect.isReady()&&(c!==this._effect&&r.resetCachedMaterial(),this._renderId=r.getRenderId(),!0)},i.prototype.bindOnlyWorldMatrix=function(e){var t=this.getScene();this._effect&&(-1!==this._options.uniforms.indexOf("world")&&this._effect.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),this._effect.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&this._effect.setMatrix("worldViewProjection",e.multiply(t.getTransformMatrix())))},i.prototype.bind=function(t,i){if(this.bindOnlyWorldMatrix(t),this._effect&&this.getScene().getCachedMaterial()!==this){-1!==this._options.uniforms.indexOf("view")&&this._effect.setMatrix("view",this.getScene().getViewMatrix()),-1!==this._options.uniforms.indexOf("projection")&&this._effect.setMatrix("projection",this.getScene().getProjectionMatrix()),-1!==this._options.uniforms.indexOf("viewProjection")&&this._effect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.MaterialHelper.BindBonesParameters(i,this._effect);var r;for(r in this._textures)this._effect.setTexture(r,this._textures[r]);for(r in this._textureArrays)this._effect.setTextureArray(r,this._textureArrays[r]);for(r in this._ints)this._effect.setInt(r,this._ints[r]);for(r in this._floats)this._effect.setFloat(r,this._floats[r]);for(r in this._floatsArrays)this._effect.setArray(r,this._floatsArrays[r]);for(r in this._colors3)this._effect.setColor3(r,this._colors3[r]);for(r in this._colors3Arrays)this._effect.setArray3(r,this._colors3Arrays[r]);for(r in this._colors4){var n=this._colors4[r];this._effect.setFloat4(r,n.r,n.g,n.b,n.a)}for(r in this._vectors2)this._effect.setVector2(r,this._vectors2[r]);for(r in this._vectors3)this._effect.setVector3(r,this._vectors3[r]);for(r in this._vectors4)this._effect.setVector4(r,this._vectors4[r]);for(r in this._matrices)this._effect.setMatrix(r,this._matrices[r]);for(r in this._matrices3x3)this._effect.setMatrix3x3(r,this._matrices3x3[r]);for(r in this._matrices2x2)this._effect.setMatrix2x2(r,this._matrices2x2[r]);for(r in this._vectors2Arrays)this._effect.setArray2(r,this._vectors2Arrays[r]);for(r in this._vectors3Arrays)this._effect.setArray3(r,this._vectors3Arrays[r])}this._afterBind(i)},i.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);for(var i in this._textures)e.push(this._textures[i]);for(var i in this._textureArrays)for(var r=this._textureArrays[i],n=0;nthis._maxX||ithis._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var s=this._getFacetAt(t,i),a=-(s.x*t+s.z*i+s.w)/s.y;return e.Vector3.TransformCoordinatesFromFloatsToRef(0,a,0,r,o),o.y},i.prototype.getNormalAtCoordinates=function(t,i){var r=new e.Vector3(0,1,0);return this.getNormalAtCoordinatesToRef(t,i,r),r},i.prototype.getNormalAtCoordinatesToRef=function(t,i,r){var n=this.getWorldMatrix(),o=e.Tmp.Matrix[5];n.invertToRef(o);var s=e.Tmp.Vector3[8];if(e.Vector3.TransformCoordinatesFromFloatsToRef(t,0,i,o,s),t=s.x,i=s.z,tthis._maxX||ithis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var a=this._getFacetAt(t,i);return e.Vector3.TransformNormalFromFloatsToRef(a.x,a.y,a.z,n,r),this},i.prototype.updateCoordinateHeights=function(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this},i.prototype._getFacetAt=function(e,t){var i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),n=this._heightQuads[r*this._subdivisionsX+i];return t=0;s--){var a=t[s],l=a.getParent();if(l){var h=this._debugLines[n];h||(h=[e.Vector3.Zero(),e.Vector3.Zero()],this._debugLines[n]=h),a.getAbsolutePositionToRef(this.mesh,h[0]),l.getAbsolutePositionToRef(this.mesh,h[1]),h[0].subtractInPlace(o),h[1].subtractInPlace(o),n++}}},t.prototype.update=function(){this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteTransforms(),void 0===this.skeleton.bones[0].length?this._getLinesForBonesNoLength(this.skeleton.bones,this.mesh.getWorldMatrix()):this._getLinesForBonesWithLength(this.skeleton.bones,this.mesh.getWorldMatrix()),this._debugMesh?e.MeshBuilder.CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:this._debugMesh},this._scene):(this._debugMesh=e.MeshBuilder.CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:null},this._scene),this._debugMesh.renderingGroupId=this.renderingGroupId),this._debugMesh.position.copyFrom(this.mesh.position),this._debugMesh.color=this.color},t.prototype.dispose=function(){this._debugMesh&&(this.isEnabled=!1,this._debugMesh.dispose(),this._debugMesh=null)},t})();t.SkeletonViewer=i})(e.Debug||(e.Debug={}))})(r||(r={}));var r;!(function(e){!(function(t){var i=(function(){function t(t,i){void 0===i&&(i=1),this._xline=[e.Vector3.Zero(),e.Vector3.Zero()],this._yline=[e.Vector3.Zero(),e.Vector3.Zero()],this._zline=[e.Vector3.Zero(),e.Vector3.Zero()],this.scaleLines=1,this.scaleLines=i,this._xmesh=e.Mesh.CreateLines("xline",this._xline,t,!0),this._ymesh=e.Mesh.CreateLines("yline",this._yline,t,!0),this._zmesh=e.Mesh.CreateLines("zline",this._zline,t,!0),this._xmesh.renderingGroupId=2,this._ymesh.renderingGroupId=2,this._zmesh.renderingGroupId=2,this._xmesh.material.checkReadyOnlyOnce=!0,this._xmesh.color=new e.Color3(1,0,0),this._ymesh.material.checkReadyOnlyOnce=!0,this._ymesh.color=new e.Color3(0,1,0),this._zmesh.material.checkReadyOnlyOnce=!0,this._zmesh.color=new e.Color3(0,0,1),this.scene=t}return t.prototype.update=function(t,i,r,n){var o=this.scaleLines;this._xmesh&&this._xmesh.position.copyFrom(t),this._ymesh&&this._ymesh.position.copyFrom(t),this._zmesh&&this._zmesh.position.copyFrom(t);var s=this._xline[1];s.x=i.x*o,s.y=i.y*o,s.z=i.z*o,e.Mesh.CreateLines("",this._xline,null,!1,this._xmesh),s=this._yline[1],s.x=r.x*o,s.y=r.y*o,s.z=r.z*o,e.Mesh.CreateLines("",this._yline,null,!1,this._ymesh),s=this._zline[1],s.x=n.x*o,s.y=n.y*o,s.z=n.z*o,e.Mesh.CreateLines("",this._zline,null,!1,this._zmesh)},t.prototype.dispose=function(){this._xmesh&&this._xmesh.dispose(),this._ymesh&&this._ymesh.dispose(),this._zmesh&&this._zmesh.dispose(),this._xmesh=null,this._ymesh=null,this._zmesh=null,this.scene=null},t})();t.AxesViewer=i})(e.Debug||(e.Debug={}))})(r||(r={}));var r;!(function(e){!(function(t){var i=(function(t){function i(i,r,n,o){void 0===o&&(o=1);var s=t.call(this,i,o)||this;return s.pos=e.Vector3.Zero(),s.xaxis=e.Vector3.Zero(),s.yaxis=e.Vector3.Zero(),s.zaxis=e.Vector3.Zero(),s.mesh=n,s.bone=r,s}return o(i,t),i.prototype.update=function(){if(this.mesh&&this.bone){var i=this.bone;i.getAbsolutePositionToRef(this.mesh,this.pos),i.getDirectionToRef(e.Axis.X,this.mesh,this.xaxis),i.getDirectionToRef(e.Axis.Y,this.mesh,this.yaxis),i.getDirectionToRef(e.Axis.Z,this.mesh,this.zaxis),t.prototype.update.call(this,this.pos,this.xaxis,this.yaxis,this.zaxis)}},i.prototype.dispose=function(){this.mesh&&(this.mesh=null,this.bone=null,t.prototype.dispose.call(this))},i})(t.AxesViewer);t.BoneAxesViewer=i})(e.Debug||(e.Debug={}))})(r||(r={}));var r;!(function(e){var t=(function(){function t(e){this.ray=e}return t.CreateAndShow=function(e,i,r){var n=new t(e);return n.show(i,r),n},t.prototype.show=function(t,i){if(!this._renderFunction&&this.ray){var r=this.ray;this._renderFunction=this._render.bind(this),this._scene=t,this._renderPoints=[r.origin,r.origin.add(r.direction.scale(r.length))],this._renderLine=e.Mesh.CreateLines("ray",this._renderPoints,t,!0),this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}i&&this._renderLine&&this._renderLine.color.copyFrom(i)},t.prototype.hide=function(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])},t.prototype._render=function(){var t=this.ray;if(t){var i=this._renderPoints[1],r=Math.min(t.length,1e6);i.copyFrom(t.direction),i.scaleInPlace(r),i.addInPlace(t.origin),e.Mesh.CreateLines("ray",this._renderPoints,this._scene,!0,this._renderLine)}},t.prototype.attachToMesh=function(t,i,r,n){this._attachedToMesh=t;var o=this.ray;o&&(o.direction||(o.direction=e.Vector3.Zero()),o.origin||(o.origin=e.Vector3.Zero()),n&&(o.length=n),r||(r=e.Vector3.Zero()),i||(i=new e.Vector3(0,0,-1)),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(i),this._meshSpaceOrigin.copyFrom(r)):(this._meshSpaceDirection=i.clone(),this._meshSpaceOrigin=r.clone()),this._updateToMeshFunction||(this._updateToMeshFunction=this._updateToMesh.bind(this),this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction)),this._updateToMesh())},t.prototype.detachFromMesh=function(){this._attachedToMesh&&(this._updateToMeshFunction&&this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction),this._attachedToMesh=null,this._updateToMeshFunction=null)},t.prototype._updateToMesh=function(){var t=this.ray;if(this._attachedToMesh&&t){if(this._attachedToMesh._isDisposed)return void this.detachFromMesh();this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,t.direction),e.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),t.origin)}},t.prototype.dispose=function(){this.hide(),this.detachFromMesh(),this.ray=null},t})();e.RayHelper=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){this.BJSINSPECTOR="undefined"!=typeof INSPECTOR?INSPECTOR:void 0,this.onPropertyChangedObservable=new e.Observable,this._scene=t}return t.prototype._createInspector=function(e){void 0===e&&(e={});var t=e.popup||!1,i=e.initialTab||0,r=e.parentElement||null;this._inspector||(this.BJSINSPECTOR=this.BJSINSPECTOR||"undefined"!=typeof INSPECTOR?INSPECTOR:void 0,this._inspector=new this.BJSINSPECTOR.Inspector(this._scene,t,i,r,e.newColors))},t.prototype.isVisible=function(){return!!this._inspector},t.prototype.hide=function(){if(this._inspector){try{this._inspector.dispose()}catch(e){}this.onPropertyChangedObservable.clear(),this._inspector=null}},t.prototype.show=function(i){void 0===i&&(i={}),void 0===this.BJSINSPECTOR?e.Tools.LoadScript(t.InspectorURL,this._createInspector.bind(this,i)):this._createInspector(i)},t.prototype.getActiveTab=function(){return this._inspector?this._inspector.getActiveTabIndex():-1},t.InspectorURL="https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js",t})();e.DebugLayer=t})(r||(r={}));var r;!(function(e){!(function(t){var i=(function(){function t(t){this._impostors=[],this._meshes=[],this._numMeshes=0,this._scene=t||e.Engine.LastCreatedScene;var i=this._scene.getPhysicsEngine();i&&(this._physicsEnginePlugin=i.getPhysicsPlugin())}return t.prototype._updateDebugMeshes=function(){for(var e=this._physicsEnginePlugin,t=0;t0?(this._meshes[i]=this._meshes[this._numMeshes],this._impostors[i]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}},t.prototype._getDebugMaterial=function(t){return this._debugMaterial||(this._debugMaterial=new e.StandardMaterial("",t),this._debugMaterial.wireframe=!0),this._debugMaterial},t.prototype._getDebugBoxMesh=function(t){return this._debugBoxMesh||(this._debugBoxMesh=e.MeshBuilder.CreateBox("physicsBodyBoxViewMesh",{size:1},t),this._debugBoxMesh.renderingGroupId=1,this._debugBoxMesh.rotationQuaternion=e.Quaternion.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(t),t.removeMesh(this._debugBoxMesh)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")},t.prototype._getDebugSphereMesh=function(t){return this._debugSphereMesh||(this._debugSphereMesh=e.MeshBuilder.CreateSphere("physicsBodySphereViewMesh",{diameter:1},t),this._debugSphereMesh.renderingGroupId=1,this._debugSphereMesh.rotationQuaternion=e.Quaternion.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(t),t.removeMesh(this._debugSphereMesh)),this._debugSphereMesh.createInstance("physicsBodyBoxViewInstance")},t.prototype._getDebugMesh=function(t,i){var r=null;if(t.type==e.PhysicsImpostor.BoxImpostor)r=this._getDebugBoxMesh(i),t.getBoxSizeToRef(r.scaling);else if(t.type==e.PhysicsImpostor.SphereImpostor){r=this._getDebugSphereMesh(i);var n=t.getRadius();r.scaling.x=2*n,r.scaling.y=2*n,r.scaling.z=2*n}return r},t.prototype.dispose=function(){for(var e=0;e1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction1",{get:function(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"direction2",{get:function(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:e.Vector3.Zero()},set:function(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minEmitBox",{get:function(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxEmitBox",{get:function(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:e.Vector3.Zero()},set:function(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)},enumerable:!0,configurable:!0}),t.prototype.getCapacity=function(){return this._capacity},Object.defineProperty(t.prototype,"activeParticleCount",{get:function(){return this._activeCount},set:function(e){this._activeCount=Math.min(e,this._capacity)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isAnimationSheetEnabled",{get:function(){return this._isAnimationSheetEnabled},enumerable:!0,configurable:!0}),t.prototype.isReady=function(){return this._updateEffect?!!(this.emitter&&this._updateEffect.isReady()&&this._renderEffect.isReady()&&this.particleTexture&&this.particleTexture.isReady()):(this._recreateUpdateEffect(),this._recreateRenderEffect(),!1)},t.prototype.isStarted=function(){return this._started},t.prototype.start=function(e){var t=this;if(void 0===e&&(e=0),e)return void setTimeout((function(){t.start(0)}),e);this._started=!0,this._stopped=!1,this._preWarmDone=!1},t.prototype.stop=function(){this._stopped=!0},t.prototype.reset=function(){this._releaseBuffers(),this._releaseVAOs(),this._currentActiveCount=0,this._targetIndex=0},t.prototype.getClassName=function(){return"GPUParticleSystem"},Object.defineProperty(t.prototype,"isBillboardBased",{get:function(){return this._isBillboardBased},set:function(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._releaseBuffers())}, +enumerable:!0,configurable:!0}),t.prototype.getColorGradients=function(){return this._colorGradients},t.prototype.getSizeGradients=function(){return this._sizeGradients},t.prototype.getAngularSpeedGradients=function(){return this._angularSpeedGradients},t.prototype.getVelocityGradients=function(){return this._velocityGradients},t.prototype._removeGradient=function(e,t,i){if(!t)return this;for(var r=0,n=0,o=t;nt.gradient?1:0})),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeColorGradient=function(e){return this._removeGradient(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this},t.prototype._addFactorGradient=function(t,i,r){var n=new e.FactorGradient;n.gradient=i,n.factor1=r,t.push(n),t.sort((function(e,t){return e.gradientt.gradient?1:0})),this._releaseBuffers()},t.prototype.addSizeGradient=function(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeSizeGradient=function(e){return this._removeGradient(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this},t.prototype.addAngularSpeedGradient=function(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeAngularSpeedGradient=function(e){return this._removeGradient(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this},t.prototype.addVelocityGradient=function(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeVelocityGradient=function(e){return this._removeGradient(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this},t.prototype._createUpdateVAO=function(e){var t={};t.position=e.createVertexBuffer("position",0,3),t.age=e.createVertexBuffer("age",3,1),t.life=e.createVertexBuffer("life",4,1),t.seed=e.createVertexBuffer("seed",5,4),t.size=e.createVertexBuffer("size",9,3);var i=12;this._colorGradientsTexture||(t.color=e.createVertexBuffer("color",i,4),i+=4),t.direction=e.createVertexBuffer("direction",i,3),i+=3,this._isBillboardBased||(t.initialDirection=e.createVertexBuffer("initialDirection",i,3),i+=3),this._angularSpeedGradientsTexture?(t.angle=e.createVertexBuffer("angle",i,1),i+=1):(t.angle=e.createVertexBuffer("angle",i,2),i+=2),this._isAnimationSheetEnabled&&(t.cellIndex=e.createVertexBuffer("cellIndex",i,1),i+=1);var r=this._engine.recordVertexArrayObject(t,null,this._updateEffect);return this._engine.bindArrayBuffer(null),r},t.prototype._createRenderVAO=function(e,t){var i={};i.position=e.createVertexBuffer("position",0,3,this._attributesStrideSize,!0),i.age=e.createVertexBuffer("age",3,1,this._attributesStrideSize,!0),i.life=e.createVertexBuffer("life",4,1,this._attributesStrideSize,!0),i.size=e.createVertexBuffer("size",9,3,this._attributesStrideSize,!0);var r=12;this._colorGradientsTexture||(i.color=e.createVertexBuffer("color",r,4,this._attributesStrideSize,!0),r+=4),r+=3,this._isBillboardBased||(i.initialDirection=e.createVertexBuffer("initialDirection",r,3,this._attributesStrideSize,!0),r+=3),i.angle=e.createVertexBuffer("angle",r,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?r++:r+=2,this._isAnimationSheetEnabled&&(i.cellIndex=e.createVertexBuffer("cellIndex",r,1,this._attributesStrideSize,!0),r+=1),i.offset=t.createVertexBuffer("offset",0,2),i.uv=t.createVertexBuffer("uv",2,2);var n=this._engine.recordVertexArrayObject(i,null,this._renderEffect);return this._engine.bindArrayBuffer(null),n},t.prototype._initialize=function(t){if(void 0===t&&(t=!1),!this._buffer0||t){var i=this._scene.getEngine(),r=new Array;this.isBillboardBased||(this._attributesStrideSize+=3),this._colorGradientsTexture&&(this._attributesStrideSize-=4),this._angularSpeedGradientsTexture&&(this._attributesStrideSize-=1),this._isAnimationSheetEnabled&&(this._attributesStrideSize+=1);for(var n=0;n=this.targetStopDuration&&this.stop()},t.prototype._createFactorGradientTexture=function(t,i){var r=this[i];if(t&&t.length&&!r){for(var n=new Float32Array(this._rawTextureWidth),o=0;o1){var r=0|this._accumulatedCount;this._accumulatedCount-=r,this._currentActiveCount=Math.min(this._activeCount,this._currentActiveCount+r)}if(!this._currentActiveCount)return 0;this._engine.enableEffect(this._updateEffect),this._engine.setState(!1),this._updateEffect.setFloat("currentCount",this._currentActiveCount),this._updateEffect.setFloat("timeDelta",this._timeDelta),this._updateEffect.setFloat("stopFactor",this._stopped?0:1),this._updateEffect.setTexture("randomSampler",this._randomTexture),this._updateEffect.setTexture("randomSampler2",this._randomTexture2),this._updateEffect.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateEffect.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateEffect.setDirectColor4("color1",this.color1),this._updateEffect.setDirectColor4("color2",this.color2)),this._updateEffect.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateEffect.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateEffect.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateEffect.setVector3("gravity",this.gravity),this._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._sizeGradientsTexture),this._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._angularSpeedGradientsTexture),this._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._velocityGradientsTexture),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateEffect),this._isAnimationSheetEnabled&&this._updateEffect.setFloat3("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed),this.noiseTexture&&(this._updateEffect.setTexture("noiseSampler",this.noiseTexture),this._updateEffect.setVector3("noiseStrength",this.noiseStrength));var n;if(this.emitter.position){n=this.emitter.getWorldMatrix()}else{var o=this.emitter;n=e.Matrix.Translation(o.x,o.y,o.z)}if(this._updateEffect.setMatrix("emitterWM",n),this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex],null),this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer()),this._engine.setRasterizerState(!1),this._engine.beginTransformFeedback(!0),this._engine.drawArraysType(e.Material.PointListDrawMode,0,this._currentActiveCount),this._engine.endTransformFeedback(),this._engine.setRasterizerState(!0),this._engine.bindTransformFeedbackBuffer(null),!t){this._engine.enableEffect(this._renderEffect);var s=this._scene.getViewMatrix();if(this._renderEffect.setMatrix("view",s),this._renderEffect.setMatrix("projection",this._scene.getProjectionMatrix()),this._renderEffect.setTexture("textureSampler",this.particleTexture),this._renderEffect.setVector2("translationPivot",this.translationPivot),this._colorGradientsTexture?this._renderEffect.setTexture("colorGradientSampler",this._colorGradientsTexture):this._renderEffect.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){var a=this.particleTexture.getBaseSize();this._renderEffect.setFloat3("sheetInfos",this.spriteCellWidth/a.width,this.spriteCellHeight/a.height,a.width/this.spriteCellWidth)}if(this._isBillboardBased){var l=this._scene.activeCamera;this._renderEffect.setVector3("eyePosition",l.globalPosition)}if(this._scene.clipPlane){var h=this._scene.clipPlane,c=s.clone();c.invert(),this._renderEffect.setMatrix("invView",c),this._renderEffect.setFloat4("vClipPlane",h.normal.x,h.normal.y,h.normal.z,h.d)}switch(this.blendMode){case e.ParticleSystem.BLENDMODE_ADD:this._engine.setAlphaMode(e.Engine.ALPHA_ADD);break;case e.ParticleSystem.BLENDMODE_ONEONE:this._engine.setAlphaMode(e.Engine.ALPHA_ONEONE);break;case e.ParticleSystem.BLENDMODE_STANDARD:this._engine.setAlphaMode(e.Engine.ALPHA_COMBINE)}this.forceDepthWrite&&this._engine.setDepthWrite(!0),this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex],null),this._engine.drawArraysType(e.Material.TriangleFanDrawMode,0,4,this._currentActiveCount),this._engine.setAlphaMode(e.Engine.ALPHA_DISABLE)}2===++this._targetIndex&&(this._targetIndex=0);var u=this._sourceBuffer;return this._sourceBuffer=this._targetBuffer,this._targetBuffer=u,this._currentActiveCount},t.prototype.rebuild=function(){this._initialize(!0)},t.prototype._releaseBuffers=function(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null)},t.prototype._releaseVAOs=function(){if(this._updateVAO){for(var e=0;e-1&&this._scene.particleSystems.splice(t,1),this._releaseBuffers(),this._releaseVAOs(),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._randomTexture&&(this._randomTexture.dispose(),this._randomTexture=null),this._randomTexture2&&(this._randomTexture2.dispose(),this._randomTexture2=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.prototype.clone=function(i,r){var n=new t(i,{capacity:this._capacity,randomTextureSize:this._randomTextureSize},this._scene);return e.Tools.DeepCopy(this,n),void 0===r&&(r=this.emitter),n.emitter=r,this.particleTexture&&(n.particleTexture=new e.Texture(this.particleTexture.url,this._scene)),n},t.prototype.serialize=function(){var t={};return e.ParticleSystem._Serialize(t,this),t.activeParticleCount=this.activeParticleCount,t},t.Parse=function(i,r,n){var o=i.name,s=new t(o,{capacity:i.capacity,randomTextureSize:i.randomTextureSize},r);return i.activeParticleCount&&(s.activeParticleCount=i.activeParticleCount),e.ParticleSystem._Parse(i,s,r,n),s},t})();e.GPUParticleSystem=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a,l){void 0===l&&(l=null),this.idx=0,this.color=new e.Color4(1,1,1,1),this.position=e.Vector3.Zero(),this.rotation=e.Vector3.Zero(),this.scaling=e.Vector3.One(),this.uvs=new e.Vector4(0,0,1,1),this.velocity=e.Vector3.Zero(),this.pivot=e.Vector3.Zero(),this.translateFromPivot=!1,this.alive=!0,this.isVisible=!0,this._pos=0,this._ind=0,this.shapeId=0,this.idxInShape=0,this._stillInvisible=!1,this._rotationMatrix=[1,0,0,0,1,0,0,0,1],this.parentId=null,this._globalPosition=e.Vector3.Zero(),this.idx=t,this._pos=i,this._ind=r,this._model=n,this.shapeId=o,this.idxInShape=s,this._sps=a,l&&(this._modelBoundingInfo=l,this._boundingInfo=new e.BoundingInfo(l.minimum,l.maximum))}return Object.defineProperty(t.prototype,"scale",{get:function(){return this.scaling},set:function(e){this.scaling=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"quaternion",{get:function(){return this.rotationQuaternion},set:function(e){this.rotationQuaternion=e},enumerable:!0,configurable:!0}),t.prototype.intersectsMesh=function(t){return!(!this._boundingInfo||!t._boundingInfo)&&(this._sps._bSphereOnly?e.BoundingSphere.Intersects(this._boundingInfo.boundingSphere,t._boundingInfo.boundingSphere):this._boundingInfo.intersects(t._boundingInfo,!1))},t})();e.SolidParticle=t;var i=(function(){function e(e,t,i,r,n,o){this._indicesLength=0,this.shapeID=e,this._shape=t,this._indicesLength=i,this._shapeUV=r,this._positionFunction=n,this._vertexFunction=o}return e})();e.ModelShape=i;var r=(function(){function e(){this.ind=0,this.indicesLength=0,this.sqDistance=0}return e})();e.DepthSortedParticle=r})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){this.particles=new Array,this.nbParticles=0,this.billboard=!1,this.recomputeNormals=!0,this.counter=0,this.vars={},this._bSphereOnly=!1,this._bSphereRadiusFactor=1,this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._index=0,this._updatable=!0,this._pickable=!1,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._depthSort=!1,this._shapeCounter=0,this._copy=new e.SolidParticle(0,0,0,null,0,0,this),this._color=new e.Color4(0,0,0,0),this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeParticleVertex=!1,this._computeBoundingBox=!1,this._depthSortParticles=!0,this._cam_axisZ=e.Vector3.Zero(),this._cam_axisY=e.Vector3.Zero(),this._cam_axisX=e.Vector3.Zero(),this._axisZ=e.Axis.Z,this._camDir=e.Vector3.Zero(),this._camInvertedPosition=e.Vector3.Zero(),this._rotMatrix=new e.Matrix,this._invertMatrix=new e.Matrix,this._rotated=e.Vector3.Zero(),this._quaternion=new e.Quaternion,this._vertex=e.Vector3.Zero(),this._normal=e.Vector3.Zero(),this._yaw=0,this._pitch=0,this._roll=0,this._halfroll=0,this._halfpitch=0,this._halfyaw=0,this._sinRoll=0,this._cosRoll=0,this._sinPitch=0,this._cosPitch=0,this._sinYaw=0,this._cosYaw=0,this._mustUnrotateFixedNormals=!1,this._minimum=e.Vector3.Zero(),this._maximum=e.Vector3.Zero(),this._minBbox=e.Vector3.Zero(),this._maxBbox=e.Vector3.Zero(),this._particlesIntersect=!1,this._depthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},this._needs32Bits=!1,this._pivotBackTranslation=e.Vector3.Zero(),this._scaledPivot=e.Vector3.Zero(),this._particleHasParent=!1,this.name=t,this._scene=i||e.Engine.LastCreatedScene,this._camera=i.activeCamera,this._pickable=!!r&&r.isPickable,this._depthSort=!!r&&r.enableDepthSort,this._particlesIntersect=!!r&&r.particleIntersection,this._bSphereOnly=!!r&&r.boundingSphereOnly,this._bSphereRadiusFactor=r&&r.bSphereRadiusFactor?r.bSphereRadiusFactor:1,r&&void 0!==r.updatable?this._updatable=r.updatable:this._updatable=!0,this._pickable&&(this.pickedParticles=[]),this._depthSort&&(this.depthSortedParticles=[])}return t.prototype.buildMesh=function(){if(0===this.nbParticles){var t=e.MeshBuilder.CreateDisc("",{radius:1,tessellation:3},this._scene);this.addShape(t,1),t.dispose()}this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),this.recomputeNormals&&e.VertexData.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();var i=new e.VertexData;i.indices=this._depthSort?this._indices:this._indices32,i.set(this._positions32,e.VertexBuffer.PositionKind),i.set(this._normals32,e.VertexBuffer.NormalKind),this._uvs32.length>0&&i.set(this._uvs32,e.VertexBuffer.UVKind),this._colors32.length>0&&i.set(this._colors32,e.VertexBuffer.ColorKind);var r=new e.Mesh(this.name,this._scene);return i.applyToMesh(r,this._updatable),this.mesh=r,this.mesh.isPickable=this._pickable,this._depthSort||(this._indices=null),this._positions=null,this._normals=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0),r},t.prototype.digest=function(t,i){var r=i&&i.facetNb||1,n=i&&i.number||0,o=i&&i.delta||0,s=t.getVerticesData(e.VertexBuffer.PositionKind),a=t.getIndices(),l=t.getVerticesData(e.VertexBuffer.UVKind),h=t.getVerticesData(e.VertexBuffer.ColorKind),c=t.getVerticesData(e.VertexBuffer.NormalKind),u=0,f=a.length/3;n?(n=n>f?f:n,r=Math.round(f/n),o=0):r=r>f?f:r;for(var d=[],p=[],m=[],_=[],g=e.Vector3.Zero(),v=r;uf-r&&(r=f-u),d.length=0,p.length=0,m.length=0,_.length=0;for(var y=0,b=3*u;b<3*(u+r);b++){p.push(y);var x=a[b];d.push(s[3*x],s[3*x+1],s[3*x+2]),l&&m.push(l[2*x],l[2*x+1]),h&&_.push(h[4*x],h[4*x+1],h[4*x+2],h[4*x+3]),y++}var T,E=this.nbParticles,P=this._posToShape(d),A=this._uvsToShapeUV(m);for(T=0;T65535&&(this._needs32Bits=!0)}if(this._pickable){var b=n.length/3;for(m=0;m=this.nbParticles?this.nbParticles-1:i,this._computeBoundingBox&&(0==t&&i==this.nbParticles-1?(e.Vector3.FromFloatsToRef(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,this._minimum), +e.Vector3.FromFloatsToRef(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE,this._maximum)):this.mesh._boundingInfo&&(this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum),this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum))),s=this.particles[t]._pos;var f=s/3|0;l=4*f,c=2*f;for(var d=t;d<=i;d++){if(this._particle=this.particles[d],this._shape=this._particle._model._shape,this._shapeUV=this._particle._model._shapeUV,this.updateParticle(this._particle),this._depthSort&&this._depthSortParticles){var p=this.depthSortedParticles[d];p.ind=this._particle._ind,p.indicesLength=this._particle._model._indicesLength,p.sqDistance=e.Vector3.DistanceSquared(this._particle.position,this._camInvertedPosition)}if(!this._particle.alive||this._particle._stillInvisible&&!this._particle.isVisible)u=this._shape.length,s+=3*u,l+=4*u,c+=2*u;else{if(this._particle.isVisible)for(this._particle._stillInvisible=!1,this._particleHasParent=null!==this._particle.parentId,this._scaledPivot.x=this._particle.pivot.x*this._particle.scaling.x,this._scaledPivot.y=this._particle.pivot.y*this._particle.scaling.y,this._scaledPivot.z=this._particle.pivot.z*this._particle.scaling.z,this.billboard&&(this._particle.rotation.x=0,this._particle.rotation.y=0),(this._computeParticleRotation||this.billboard)&&(this._particle.rotationQuaternion?this._quaternion.copyFrom(this._particle.rotationQuaternion):(this._yaw=this._particle.rotation.y,this._pitch=this._particle.rotation.x,this._roll=this._particle.rotation.z,this._quaternionRotationYPR()),this._quaternionToRotationMatrix()),this._particleHasParent?(this._parent=this.particles[this._particle.parentId],this._rotated.x=this._particle.position.x*this._parent._rotationMatrix[0]+this._particle.position.y*this._parent._rotationMatrix[3]+this._particle.position.z*this._parent._rotationMatrix[6],this._rotated.y=this._particle.position.x*this._parent._rotationMatrix[1]+this._particle.position.y*this._parent._rotationMatrix[4]+this._particle.position.z*this._parent._rotationMatrix[7],this._rotated.z=this._particle.position.x*this._parent._rotationMatrix[2]+this._particle.position.y*this._parent._rotationMatrix[5]+this._particle.position.z*this._parent._rotationMatrix[8],this._particle._globalPosition.x=this._parent._globalPosition.x+this._rotated.x,this._particle._globalPosition.y=this._parent._globalPosition.y+this._rotated.y,this._particle._globalPosition.z=this._parent._globalPosition.z+this._rotated.z,(this._computeParticleRotation||this.billboard)&&(this._particle._rotationMatrix[0]=this._rotMatrix.m[0]*this._parent._rotationMatrix[0]+this._rotMatrix.m[1]*this._parent._rotationMatrix[3]+this._rotMatrix.m[2]*this._parent._rotationMatrix[6],this._particle._rotationMatrix[1]=this._rotMatrix.m[0]*this._parent._rotationMatrix[1]+this._rotMatrix.m[1]*this._parent._rotationMatrix[4]+this._rotMatrix.m[2]*this._parent._rotationMatrix[7],this._particle._rotationMatrix[2]=this._rotMatrix.m[0]*this._parent._rotationMatrix[2]+this._rotMatrix.m[1]*this._parent._rotationMatrix[5]+this._rotMatrix.m[2]*this._parent._rotationMatrix[8],this._particle._rotationMatrix[3]=this._rotMatrix.m[4]*this._parent._rotationMatrix[0]+this._rotMatrix.m[5]*this._parent._rotationMatrix[3]+this._rotMatrix.m[6]*this._parent._rotationMatrix[6],this._particle._rotationMatrix[4]=this._rotMatrix.m[4]*this._parent._rotationMatrix[1]+this._rotMatrix.m[5]*this._parent._rotationMatrix[4]+this._rotMatrix.m[6]*this._parent._rotationMatrix[7],this._particle._rotationMatrix[5]=this._rotMatrix.m[4]*this._parent._rotationMatrix[2]+this._rotMatrix.m[5]*this._parent._rotationMatrix[5]+this._rotMatrix.m[6]*this._parent._rotationMatrix[8],this._particle._rotationMatrix[6]=this._rotMatrix.m[8]*this._parent._rotationMatrix[0]+this._rotMatrix.m[9]*this._parent._rotationMatrix[3]+this._rotMatrix.m[10]*this._parent._rotationMatrix[6],this._particle._rotationMatrix[7]=this._rotMatrix.m[8]*this._parent._rotationMatrix[1]+this._rotMatrix.m[9]*this._parent._rotationMatrix[4]+this._rotMatrix.m[10]*this._parent._rotationMatrix[7],this._particle._rotationMatrix[8]=this._rotMatrix.m[8]*this._parent._rotationMatrix[2]+this._rotMatrix.m[9]*this._parent._rotationMatrix[5]+this._rotMatrix.m[10]*this._parent._rotationMatrix[8])):(this._particle._globalPosition.x=this._particle.position.x,this._particle._globalPosition.y=this._particle.position.y,this._particle._globalPosition.z=this._particle.position.z,(this._computeParticleRotation||this.billboard)&&(this._particle._rotationMatrix[0]=this._rotMatrix.m[0],this._particle._rotationMatrix[1]=this._rotMatrix.m[1],this._particle._rotationMatrix[2]=this._rotMatrix.m[2],this._particle._rotationMatrix[3]=this._rotMatrix.m[4],this._particle._rotationMatrix[4]=this._rotMatrix.m[5],this._particle._rotationMatrix[5]=this._rotMatrix.m[6],this._particle._rotationMatrix[6]=this._rotMatrix.m[8],this._particle._rotationMatrix[7]=this._rotMatrix.m[9],this._particle._rotationMatrix[8]=this._rotMatrix.m[10])),this._particle.translateFromPivot?(this._pivotBackTranslation.x=0,this._pivotBackTranslation.y=0,this._pivotBackTranslation.z=0):(this._pivotBackTranslation.x=this._scaledPivot.x,this._pivotBackTranslation.y=this._scaledPivot.y,this._pivotBackTranslation.z=this._scaledPivot.z),u=0;uthis._maximum.x&&(this._maximum.x=this._positions32[o]),this._positions32[o+1]this._maximum.y&&(this._maximum.y=this._positions32[o+1]),this._positions32[o+2]this._maximum.z&&(this._maximum.z=this._positions32[o+2])),this._computeParticleVertex||(this._normal.x=this._fixedNormal32[o],this._normal.y=this._fixedNormal32[o+1],this._normal.z=this._fixedNormal32[o+2],this._rotated.x=this._normal.x*this._particle._rotationMatrix[0]+this._normal.y*this._particle._rotationMatrix[3]+this._normal.z*this._particle._rotationMatrix[6],this._rotated.y=this._normal.x*this._particle._rotationMatrix[1]+this._normal.y*this._particle._rotationMatrix[4]+this._normal.z*this._particle._rotationMatrix[7],this._rotated.z=this._normal.x*this._particle._rotationMatrix[2]+this._normal.y*this._particle._rotationMatrix[5]+this._normal.z*this._particle._rotationMatrix[8],this._normals32[o]=this._cam_axisX.x*this._rotated.x+this._cam_axisY.x*this._rotated.y+this._cam_axisZ.x*this._rotated.z,this._normals32[o+1]=this._cam_axisX.y*this._rotated.x+this._cam_axisY.y*this._rotated.y+this._cam_axisZ.y*this._rotated.z,this._normals32[o+2]=this._cam_axisX.z*this._rotated.x+this._cam_axisY.z*this._rotated.y+this._cam_axisZ.z*this._rotated.z),this._computeParticleColor&&this._particle.color&&(this._colors32[a]=this._particle.color.r,this._colors32[a+1]=this._particle.color.g,this._colors32[a+2]=this._particle.color.b,this._colors32[a+3]=this._particle.color.a),this._computeParticleTexture&&(this._uvs32[h]=this._shapeUV[2*u]*(this._particle.uvs.z-this._particle.uvs.x)+this._particle.uvs.x,this._uvs32[h+1]=this._shapeUV[2*u+1]*(this._particle.uvs.w-this._particle.uvs.y)+this._particle.uvs.y);else for(this._particle._stillInvisible=!0,u=0;ue.Tmp.Vector3[1].x&&(e.Tmp.Vector3[1].x=l[u].x),l[u].ye.Tmp.Vector3[1].y&&(e.Tmp.Vector3[1].y=l[u].y),l[u].ze.Tmp.Vector3[1].z&&(e.Tmp.Vector3[1].z=l[u].z),u++,r+=3;h._closePath&&(t[r]=l[0].x,t[r+1]=l[0].y,t[r+2]=l[0].z,r+=3)}}(u),h._boundingInfo=new e.BoundingInfo(e.Tmp.Vector3[0],e.Tmp.Vector3[1]),h._boundingInfo.update(h._worldMatrix),h.updateVerticesData(e.VertexBuffer.PositionKind,u,!1,!1),r.colors){for(var f=h.getVerticesData(e.VertexBuffer.ColorKind),d=0;d1?1:r.arc:1,a=void 0===r.closed||r.closed,l=r.shape,h=r.radius||1,c=r.tessellation||64,u=r.clip||0,f=r.updatable,d=t.updateSideOrientation(r.sideOrientation),p=r.cap||e.Mesh.NO_CAP,m=2*Math.PI,_=new Array,g=r.invertUV||!1,v=0,y=0,b=m/c*s,x=new Array;for(v=0;v<=c-u;v++){var x=[];for(p!=e.Mesh.CAP_START&&p!=e.Mesh.CAP_ALL||(x.push(new e.Vector3(0,l[0].y,0)),x.push(new e.Vector3(Math.cos(v*b)*l[0].x*h,l[0].y,Math.sin(v*b)*l[0].x*h))),y=0;y1)?1:r.arc||1;var p,m,_=function(t,i,r,n,o,s,a,l){for(var h,c,u,f,d=i.getTangents(),p=i.getNormals(),m=i.getDistances(),_=2*Math.PI,g=_/o*l,v=function(){return n},y=s||v,b=e.Tmp.Matrix[0],x=a===e.Mesh._NO_CAP||a===e.Mesh.CAP_END?0:2,T=0;T3?0:c,m=_(o,p,v,a,l,h,c,r.arc);var y=t.CreateRibbon(i,{pathArray:m,closePath:!0,closeArray:!1,updatable:f,sideOrientation:d,invertUV:u,frontUVs:r.frontUVs,backUVs:r.backUVs},n);return y.pathArray=m,y.path3D=p,y.tessellation=l,y.cap=c,y.arc=r.arc,y.radius=a,y},t.CreatePolyhedron=function(i,r,n){var o=new e.Mesh(i,n);return r.sideOrientation=t.updateSideOrientation(r.sideOrientation),o._originalBuilderSideOrientation=r.sideOrientation,e.VertexData.CreatePolyhedron(r).applyToMesh(o,r.updatable),o},t.CreateDecal=function(t,i,r){var n=i.getIndices(),o=i.getVerticesData(e.VertexBuffer.PositionKind),s=i.getVerticesData(e.VertexBuffer.NormalKind),a=r.position||e.Vector3.Zero(),l=r.normal||e.Vector3.Up(),h=r.size||e.Vector3.One(),c=r.angle||0;if(!l){var u=new e.Vector3(0,0,1),f=i.getScene().activeCamera,d=e.Vector3.TransformCoordinates(u,f.getWorldMatrix());l=f.globalPosition.subtract(d)}var p=-Math.atan2(l.z,l.x)-Math.PI/2,m=Math.sqrt(l.x*l.x+l.z*l.z),_=Math.atan2(l.y,m),g=e.Matrix.RotationYawPitchRoll(p,_,c).multiply(e.Matrix.Translation(a.x,a.y,a.z)),v=e.Matrix.Invert(g),y=i.getWorldMatrix(),b=y.multiply(v),x=new e.VertexData;x.indices=[],x.positions=[],x.normals=[],x.uvs=[];for(var T=0,E=function(t){var i=new e.PositionNormalVertex;if(!n||!o||!s)return i;var r=n[t];return i.position=new e.Vector3(o[3*r],o[3*r+1],o[3*r+2]),i.position=e.Vector3.TransformCoordinates(i.position,b),i.normal=new e.Vector3(s[3*r],s[3*r+1],s[3*r+2]),i.normal=e.Vector3.TransformNormal(i.normal,b),i},P=function(t,i){if(0===t.length)return t;for(var r=.5*Math.abs(e.Vector3.Dot(h,i)),n=function(t,n){var o=e.Vector3.GetClipFactor(t.position,n.position,i,r);return new e.PositionNormalVertex(e.Vector3.Lerp(t.position,n.position,o),e.Vector3.Lerp(t.normal,n.normal,o))},o=new Array,s=0;s0,l=_>0,c=g>0,(a?1:0)+(l?1:0)+(c?1:0)){case 0:o.push(t[s]),o.push(t[s+1]),o.push(t[s+2]);break;case 1:if(a&&(u=t[s+1],f=t[s+2],d=n(t[s],u),p=n(t[s],f)),l){u=t[s],f=t[s+2],d=n(t[s+1],u),p=n(t[s+1],f),o.push(d),o.push(f.clone()),o.push(u.clone()),o.push(f.clone()),o.push(d.clone()),o.push(p);break}c&&(u=t[s],f=t[s+1],d=n(t[s+2],u),p=n(t[s+2],f)),u&&f&&d&&p&&(o.push(u.clone()),o.push(f.clone()),o.push(d),o.push(p),o.push(d.clone()),o.push(f.clone()));break;case 2:a||(u=t[s].clone(),f=n(u,t[s+1]),d=n(u,t[s+2]),o.push(u),o.push(f),o.push(d)),l||(u=t[s+1].clone(),f=n(u,t[s+2]),d=n(u,t[s]),o.push(u),o.push(f),o.push(d)),c||(u=t[s+2].clone(),f=n(u,t[s]),d=n(u,t[s+1]),o.push(u),o.push(f),o.push(d))}}return o},A=0;A3?0:u,x=T(r,n,b,E,o,s,a,l,u,f);var P=t.CreateRibbon(i,{pathArray:x,closeArray:h,closePath:c,updatable:p,sideOrientation:m,invertUV:g,frontUVs:v||void 0,backUVs:y||void 0},d);return P.pathArray=x,P.path3D=b,P.cap=u,P},t})();e.MeshBuilder=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return Object.defineProperty(t,"DecoderAvailable",{get:function(){if("undefined"!=typeof DracoDecoderModule)return!0;var e=t.Configuration.decoder;if(e){if(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly)return!0;if(e.fallbackUrl)return!0}return!1},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){},t.prototype.decodeMeshAsync=function(i,r){var n=i instanceof ArrayBuffer?new Uint8Array(i):i;return t._GetDecoderModule().then((function(t){var i=t.module,o=new e.VertexData,s=new i.DecoderBuffer;s.Init(n,n.byteLength);var a,l,h=new i.Decoder;try{var c=h.GetEncodedGeometryType(s);switch(c){case i.TRIANGULAR_MESH:a=new i.Mesh,l=h.DecodeBufferToMesh(s,a);break;case i.POINT_CLOUD:a=new i.PointCloud,l=h.DecodeBufferToPointCloud(s,a);break;default:throw new Error("Invalid geometry type "+c)}if(!l.ok()||!a.ptr)throw new Error(l.error_msg());var u=a.num_points();if(c===i.TRIANGULAR_MESH){var f=a.num_faces(),d=new i.DracoInt32Array;try{for(var p=new Uint32Array(3*f),m=0;m0&&(h=!0,this._soundLoaded(i));break;case"String":l.push(i);case"Array":0===l.length&&(l=i);for(var c=0;c0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect();else if(e.Engine.audioEngine.audioContext&&this._soundSource){var i=t?e.Engine.audioEngine.audioContext.currentTime+t:e.Engine.audioEngine.audioContext.currentTime;this._soundSource.stop(i),this._soundSource.onended=function(){},this.isPaused||(this._startOffset=0)}this.isPlaying=!1}},t.prototype.pause=function(){this.isPlaying&&(this.isPaused=!0,this._streaming?this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect():e.Engine.audioEngine.audioContext&&(this.stop(0),this._startOffset+=e.Engine.audioEngine.audioContext.currentTime-this._startTime))},t.prototype.setVolume=function(t,i){e.Engine.audioEngine.canUseWebAudio&&this._soundGain&&(i&&e.Engine.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(t,e.Engine.audioEngine.audioContext.currentTime+i)):this._soundGain.gain.value=t),this._volume=t},t.prototype.setPlaybackRate=function(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))},t.prototype.getVolume=function(){return this._volume},t.prototype.attachToMesh=function(e){var t=this;this._connectedMesh&&this._registerFunc&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedMesh=e,this.spatialSound||(this.spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play())),this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh),this._registerFunc=function(e){return t._onRegisterAfterWorldMatrixUpdate(e)},e.registerAfterWorldMatrixUpdate(this._registerFunc)},t.prototype.detachFromMesh=function(){this._connectedMesh&&this._registerFunc&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedMesh=null)},t.prototype._onRegisterAfterWorldMatrixUpdate=function(t){if(t.getBoundingInfo){var i=t,r=i.getBoundingInfo();this.setPosition(r.boundingSphere.centerWorld),e.Engine.audioEngine.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}},t.prototype.clone=function(){var e=this;if(this._streaming)return null;var i=function(){e._isReadyToPlay?(n._audioBuffer=e.getAudioBuffer(),n._isReadyToPlay=!0,n.autoplay&&n.play()):window.setTimeout(i,300)},r={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},n=new t(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,r);return this.useCustomAttenuation&&n.setAttenuationFunction(this._customAttenuationFunction),n.setPosition(this._position),n.setPlaybackRate(this._playbackRate),i(),n},t.prototype.getAudioBuffer=function(){return this._audioBuffer},t.prototype.serialize=function(){var e={name:this.name,url:this.name,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId};return this.spatialSound&&(this._connectedMesh&&(e.connectedMeshId=this._connectedMesh.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e},t.Parse=function(i,r,n,o){var s,a=i.name;s=i.url?n+i.url:n+a;var l,h={autoplay:i.autoplay,loop:i.loop,volume:i.volume,spatialSound:i.spatialSound,maxDistance:i.maxDistance,rolloffFactor:i.rolloffFactor,refDistance:i.refDistance,distanceModel:i.distanceModel,playbackRate:i.playbackRate};if(o){var c=function(){o._isReadyToPlay?(l._audioBuffer=o.getAudioBuffer(),l._isReadyToPlay=!0,l.autoplay&&l.play()):window.setTimeout(c,300)};l=new t(a,new ArrayBuffer(0),r,null,h),c()}else l=new t(a,s,r,function(){r._removePendingData(l)},h),r._addPendingData(l);if(i.position){var u=e.Vector3.FromArray(i.position);l.setPosition(u)}if(i.isDirectional&&(l.setDirectionalCone(i.coneInnerAngle||360,i.coneOuterAngle||360,i.coneOuterGain||0),i.localDirectionToMesh)){var f=e.Vector3.FromArray(i.localDirectionToMesh);l.setLocalDirectionToMesh(f)}if(i.connectedMeshId){var d=r.getMeshByID(i.connectedMeshId);d&&l.attachToMesh(d)}return l},t})();e.Sound=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t){this.id=-1,this._isMainTrack=!1,this._isInitialized=!1,this._scene=e,this.soundCollection=new Array,this._options=t,this._isMainTrack||(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}return t.prototype._initializeSoundTrackAudioGraph=function(){e.Engine.audioEngine.canUseWebAudio&&e.Engine.audioEngine.audioContext&&(this._outputAudioNode=e.Engine.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(e.Engine.audioEngine.masterGain),this._options&&(this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._options.mainTrack&&(this._isMainTrack=this._options.mainTrack)),this._isInitialized=!0)},t.prototype.dispose=function(){if(e.Engine.audioEngine&&e.Engine.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}},t.prototype.AddSound=function(t){this._isInitialized||this._initializeSoundTrackAudioGraph(),e.Engine.audioEngine.canUseWebAudio&&this._outputAudioNode&&t.connectToSoundTrackAudioNode(this._outputAudioNode),t.soundTrackId&&(-1===t.soundTrackId?this._scene.mainSoundTrack.RemoveSound(t):this._scene.soundTracks[t.soundTrackId].RemoveSound(t)),this.soundCollection.push(t),t.soundTrackId=this.id},t.prototype.RemoveSound=function(e){var t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)},t.prototype.setVolume=function(t){e.Engine.audioEngine.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=t)},t.prototype.switchPanningModelToHRTF=function(){if(e.Engine.audioEngine.canUseWebAudio)for(var t=0;t-1?i.substring(_).toLowerCase():""),v=".dds"===g,y=".env"===g;if(y?(m.gammaSpace=!1,m._prefiltered=!1):(m._prefiltered=c,c&&(m.gammaSpace=!1)),m._texture=m._getFromCache(i,o),!s&&(y||v||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),s=[],n))for(var b=0;b0&&(this._postProcesses[0].autoClear=!1))}},i.prototype._shouldRender=function(){return-1===this._currentRefreshId?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)},i.prototype.getRenderSize=function(){return this._size.width?this._size.width:this._size},i.prototype.getRenderWidth=function(){return this._size.width?this._size.width:this._size},i.prototype.getRenderHeight=function(){return this._size.width?this._size.height:this._size},Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype.scale=function(e){var t=this.getRenderSize()*e;this.resize(t)},i.prototype.getReflectionTextureMatrix=function(){return this.isCube?this._textureMatrix:t.prototype.getReflectionTextureMatrix.call(this)},i.prototype.resize=function(e){this.releaseInternalTexture();var t=this.getScene();t&&(this._processSizeParameter(e),this.isCube?this._texture=t.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._texture=t.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions))},i.prototype.render=function(e,t){void 0===e&&(e=!1),void 0===t&&(t=!1);var i=this.getScene();if(i){var r=i.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(var n=0;n=0&&this._renderingManager.dispatchParticles(v))}if(this.isCube)for(var b=0;b<6;b++)this.renderToTarget(b,c,u,e,t),i.incrementRenderId(),i.resetCachedMaterial();else this.renderToTarget(0,c,u,e,t);this.onAfterUnbindObservable.notifyObservers(this),i.activeCamera&&(this.activeCamera&&this.activeCamera!==i.activeCamera&&i.setTransformMatrix(i.activeCamera.getViewMatrix(),i.activeCamera.getProjectionMatrix(!0)),r.setViewport(i.activeCamera.viewport)),i.resetCachedMaterial()}},i.prototype._bestReflectionRenderTargetDimension=function(t,i){var r=t*i,n=e.Tools.NearestPOT(r+16384/(128+r));return Math.min(e.Tools.FloorPOT(t),n)},i.prototype.unbindFrameBuffer=function(e,t){var i=this;this._texture&&e.unBindFramebuffer(this._texture,this.isCube,(function(){i.onAfterRenderObservable.notifyObservers(t)}))},i.prototype.renderToTarget=function(t,i,r,n,o){var s=this.getScene();if(s){var a=s.getEngine();this._texture&&(this._postProcessManager?this._postProcessManager._prepareFrame(this._texture,this._postProcesses):n&&s.postProcessManager._prepareFrame(this._texture)||this._texture&&a.bindFramebuffer(this._texture,this.isCube?t:void 0,void 0,void 0,this.ignoreCameraViewport,this.depthStencilTexture?this.depthStencilTexture:void 0),this.onBeforeRenderObservable.notifyObservers(t),this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):a.clear(this.clearColor||s.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),this._renderingManager.render(this.customRenderFunction,i,this.renderParticles,this.renderSprites),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._texture,t,this._postProcesses,this.ignoreCameraViewport):n&&s.postProcessManager._finalizeFrame(!1,this._texture,t),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),o&&e.Tools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),a),this.isCube&&5!==t?this.onAfterRenderObservable.notifyObservers(t):(this.isCube&&5===t&&a.generateMipMapsForCubemap(this._texture),this.unbindFrameBuffer(a,t)))}},i.prototype.setRenderingOrder=function(e,t,i,r){void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._renderingManager.setRenderingOrder(e,t,i,r)},i.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(var i=0;i=0&&e.customRenderTargets.splice(i,1);for(var r=0,n=e.cameras;r=0&&o.customRenderTargets.splice(i,1)}t.prototype.dispose.call(this)}},i.prototype._rebuild=function(){this.refreshRate===i.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=i.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()},i.prototype.freeRenderingGroups=function(){this._renderingManager&&this._renderingManager.freeRenderingGroups()},i._REFRESHRATE_RENDER_ONCE=0,i._REFRESHRATE_RENDER_ONEVERYFRAME=1,i._REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,i})(e.Texture);e.RenderTargetTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s){var a=this,l=!(!s||!s.generateMipMaps)&&s.generateMipMaps,h=!(!s||!s.generateDepthTexture)&&s.generateDepthTexture,c=!s||void 0===s.doNotChangeAspectRatio||s.doNotChangeAspectRatio;if(a=t.call(this,i,r,o,l,c)||this,a._engine=o.getEngine(),!a.isSupported)return void a.dispose();for(var u=[],f=[],d=0;d1||this._engine.getCaps().drawBuffersExtension},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"textures",{get:function(){return this._textures},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"depthTexture",{get:function(){return this._textures[this._textures.length-1]},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wrapU",{set:function(e){if(this._textures)for(var t=0;t=0;e--)void 0!==this._internalTextures[e]&&(this._internalTextures[e].dispose(),this._internalTextures.splice(e,1))},i})(e.RenderTargetTexture);e.MultiRenderTarget=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l){void 0===s&&(s=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),void 0===l&&(l=!0);var h=t.call(this,i,r,n,o,!0,s,!1,a,l)||this;return h.scene=n,h.mirrorPlane=new e.Plane(0,1,0,1),h._transformMatrix=e.Matrix.Zero(),h._mirrorMatrix=e.Matrix.Zero(),h._adaptiveBlurKernel=0,h._blurKernelX=0,h._blurKernelY=0,h._blurRatio=1,h.ignoreCameraViewport=!0,h._updateGammaSpace(),h._imageProcessingConfigChangeObserver=n.imageProcessingConfiguration.onUpdateParameters.add((function(){h._updateGammaSpace})),h.onBeforeRenderObservable.add((function(){e.Matrix.ReflectionToRef(h.mirrorPlane,h._mirrorMatrix),h._savedViewMatrix=n.getViewMatrix(),h._mirrorMatrix.multiplyToRef(h._savedViewMatrix,h._transformMatrix),n.setTransformMatrix(h._transformMatrix,n.getProjectionMatrix()),n.clipPlane=h.mirrorPlane,n.getEngine().cullBackFaces=!1,n._mirroredCameraPosition=e.Vector3.TransformCoordinates(n.activeCamera.globalPosition,h._mirrorMatrix)})),h.onAfterRenderObservable.add((function(){n.setTransformMatrix(h._savedViewMatrix,n.getProjectionMatrix()),n.getEngine().cullBackFaces=!0,n._mirroredCameraPosition=null,delete n.clipPlane})),h}return o(i,t),Object.defineProperty(i.prototype,"blurRatio",{get:function(){return this._blurRatio},set:function(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"adaptiveBlurKernel",{set:function(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurKernel",{set:function(e){this.blurKernelX=e,this.blurKernelY=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurKernelX",{get:function(){return this._blurKernelX},set:function(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurKernelY",{get:function(){return this._blurKernelY},set:function(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),i.prototype._autoComputeBlurKernel=function(){var e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i},i.prototype._onRatioRescale=function(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()},i.prototype._updateGammaSpace=function(){this.gammaSpace=!this.scene.imageProcessingConfiguration.isEnabled||!this.scene.imageProcessingConfiguration.applyByPostProcess},i.prototype._preparePostProcesses=function(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){var t=this.getScene().getEngine(),i=t.getCaps().textureFloatRender?e.Engine.TEXTURETYPE_FLOAT:e.Engine.TEXTURETYPE_HALF_FLOAT;this._blurX=new e.BlurPostProcess("horizontal blur",new e.Vector2(1,0),this._blurKernelX,this._blurRatio,null,e.Texture.BILINEAR_SAMPLINGMODE,t,!1,i),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._texture:this._blurX.alwaysForcePOT=!0,this._blurY=new e.BlurPostProcess("vertical blur",new e.Vector2(0,1),this._blurKernelY,this._blurRatio,null,e.Texture.BILINEAR_SAMPLINGMODE,t,!1,i),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=this.getSize(),r=new i(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(r.renderList=this.renderList.slice(0)),r},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.mirrorPlane.asArray(),e},i.prototype.dispose=function(){t.prototype.dispose.call(this),this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver)},i})(e.RenderTargetTexture);e.MirrorTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o){var s=t.call(this,i,r,n,o,!0)||this;return s.refractionPlane=new e.Plane(0,1,0,1),s.depth=2,s.onBeforeRenderObservable.add((function(){n.clipPlane=s.refractionPlane})),s.onAfterRenderObservable.add((function(){delete n.clipPlane})),s}return o(i,t),i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=this.getSize(),r=new i(this.name,t.width,e,this._generateMipMaps);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.refractionPlane=this.refractionPlane.clone(),this.renderList&&(r.renderList=this.renderList.slice(0)),r.depth=this.depth,r},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e},i})(e.RenderTargetTexture);e.RefractionTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a){void 0===n&&(n=null),void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===a&&(a=e.Engine.TEXTUREFORMAT_RGBA);var l=t.call(this,null,n,!o,void 0,s,void 0,void 0,void 0,void 0,a)||this;l.name=i,l._engine=l.getScene().getEngine(),l.wrapU=e.Texture.CLAMP_ADDRESSMODE,l.wrapV=e.Texture.CLAMP_ADDRESSMODE,l._generateMipMaps=o,r.getContext?(l._canvas=r,l._texture=l._engine.createDynamicTexture(r.width,r.height,o,s)):(l._canvas=document.createElement("canvas"),r.width||0===r.width?l._texture=l._engine.createDynamicTexture(r.width,r.height,o,s):l._texture=l._engine.createDynamicTexture(r,r,o,s));var h=l.getSize();return l._canvas.width=h.width,l._canvas.height=h.height,l._context=l._canvas.getContext("2d"),l}return o(i,t),Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype._recreate=function(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._engine.createDynamicTexture(e.width,e.height,this._generateMipMaps,this._samplingMode)},i.prototype.scale=function(e){var t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)},i.prototype.scaleTo=function(e,t){var i=this.getSize();i.width=e,i.height=t,this._recreate(i)},i.prototype.getContext=function(){return this._context},i.prototype.clear=function(){var e=this.getSize();this._context.fillRect(0,0,e.width,e.height)},i.prototype.update=function(e,t){void 0===t&&(t=!1),this._engine.updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0)},i.prototype.drawText=function(e,t,i,r,n,o,s,a){void 0===a&&(a=!0);var l=this.getSize();if(o&&(this._context.fillStyle=o,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null===t||void 0===t){var h=this._context.measureText(e);t=(l.width-h.width)/2}if(null===i||void 0===i){var c=parseInt(r.replace(/\D/g,""));i=l.height/2+c/3.65}this._context.fillStyle=n,this._context.fillText(e,t,i),a&&this.update(s)},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=this.getSize(),r=new i(this.name,t,e,this._generateMipMaps);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.wrapU=this.wrapU,r.wrapV=this.wrapV,r},i.prototype.serialize=function(){var i=this.getScene();i&&!i.isReady()&&e.Tools.Warn("The scene must be ready before serializing the dynamic texture");var r=t.prototype.serialize.call(this);return r.base64String=this._canvas.toDataURL(),r.invertY=this._invertY,r.samplingMode=this.samplingMode,r},i.prototype._rebuild=function(){this.update()},i})(e.Texture);e.DynamicTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l){void 0===o&&(o=!1),void 0===s&&(s=!1),void 0===a&&(a=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===l&&(l={autoPlay:!0,loop:!0,autoUpdateTexture:!0});var h=t.call(this,null,n,!o,s)||this;return h._onUserActionRequestedObservable=null,h._stillImageCaptured=!1,h._poster=!1,h._createInternalTexture=function(){if(null!=h._texture){if(!h._poster)return;h._texture.dispose(),h._poster=!1}if(!h._engine.needPOTTextures||e.Tools.IsExponentOfTwo(h.video.videoWidth)&&e.Tools.IsExponentOfTwo(h.video.videoHeight)?(h.wrapU=e.Texture.WRAP_ADDRESSMODE,h.wrapV=e.Texture.WRAP_ADDRESSMODE):(h.wrapU=e.Texture.CLAMP_ADDRESSMODE,h.wrapV=e.Texture.CLAMP_ADDRESSMODE,h._generateMipMaps=!1),h._texture=h._engine.createDynamicTexture(h.video.videoWidth,h.video.videoHeight,h._generateMipMaps,h._samplingMode),h.video.autoplay)h._texture.isReady=!0,h._updateInternalTexture(),h._onLoadObservable&&h._onLoadObservable.hasObservers()&&h.onLoadObservable.notifyObservers(h);else{var t=h.video.onplaying,i=!1;h.video.onplaying=function(){h.video.onplaying=t,h._texture.isReady=!0,h._updateInternalTexture(),i||h.video.pause(),h._onLoadObservable&&h._onLoadObservable.hasObservers()&&h.onLoadObservable.notifyObservers(h)};var r=h.video.play();r?r.then((function(){})).catch((function(){i=!0,h._onUserActionRequestedObservable&&h._onUserActionRequestedObservable.hasObservers()&&h._onUserActionRequestedObservable.notifyObservers(h)})):(h.video.onplaying=t,h._texture.isReady=!0,h._updateInternalTexture(),h._onLoadObservable&&h._onLoadObservable.hasObservers()&&h.onLoadObservable.notifyObservers(h))}},h.reset=function(){null!=h._texture&&(h._poster||(h._texture.dispose(),h._texture=null))},h._updateInternalTexture=function(e){null!=h._texture&&h._texture.isReady&&(h.video.readyState=h.video.HAVE_CURRENT_DATA&&h._createInternalTexture(),l.poster&&(h._texture=h._engine.createTexture(l.poster,!1,!0,n),h._poster=!0),h}return o(i,t),Object.defineProperty(i.prototype,"onUserActionRequestedObservable",{get:function(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new e.Observable),this._onUserActionRequestedObservable},enumerable:!0,configurable:!0}),i.prototype._getName=function(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e},i.prototype._getVideo=function(t){if(t instanceof HTMLVideoElement)return e.Tools.SetCorsBehavior(t.currentSrc,t),t;var i=document.createElement("video");return"string"==typeof t?(e.Tools.SetCorsBehavior(t,i),i.src=t):(e.Tools.SetCorsBehavior(t[0],i),t.forEach((function(e){var t=document.createElement("source");t.src=e,i.appendChild(t)}))),i},i.prototype._rebuild=function(){this.update()},i.prototype.update=function(){this.autoUpdateTexture&&this.updateTexture(!0)},i.prototype.updateTexture=function(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))},i.prototype.updateURL=function(e){this.video.src=e},i.prototype.dispose=function(){t.prototype.dispose.call(this),this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener("canplay",this._createInternalTexture),this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this.reset),this.video.pause()},i.CreateFromWebCam=function(t,r,n){var o=document.createElement("video");o.setAttribute("autoplay",""),o.setAttribute("muted",""),o.setAttribute("playsinline","");var s;n&&n.deviceId&&(s={exact:n.deviceId}),window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,navigator.mediaDevices?navigator.mediaDevices.getUserMedia({video:n}).then((function(e){void 0!==o.mozSrcObject?o.mozSrcObject=e:o.srcObject=e;var n=function(){r&&r(new i("video",o,t,!0,!0)),o.removeEventListener("playing",n)};o.addEventListener("playing",n),o.play()})).catch((function(t){e.Tools.Error(t.name)})):(navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,navigator.getUserMedia&&navigator.getUserMedia({video:{deviceId:s,width:{min:n&&n.minWidth||256,max:n&&n.maxWidth||640},height:{min:n&&n.minHeight||256,max:n&&n.maxHeight||480}}},(function(e){void 0!==o.mozSrcObject?o.mozSrcObject=e:o.src=window.URL&&window.URL.createObjectURL(e)||e,o.play(),r&&r(new i("video",o,t,!0,!0))}),(function(t){e.Tools.Error(t.name)})))},i})(e.Texture);e.VideoTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h,c){void 0===a&&(a=!0),void 0===l&&(l=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT);var u=t.call(this,null,s,!a,l)||this +;return u.format=o,u._engine=s.getEngine(),u._texture=s.getEngine().createRawTexture(i,r,n,o,a,l,h,null,c),u.wrapU=e.Texture.CLAMP_ADDRESSMODE,u.wrapV=e.Texture.CLAMP_ADDRESSMODE,u}return o(i,t),i.prototype.update=function(e){this._engine.updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,void 0,this._texture.type)},i.CreateLuminanceTexture=function(t,r,n,o,s,a,l){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_LUMINANCE,o,s,a,l)},i.CreateLuminanceAlphaTexture=function(t,r,n,o,s,a,l){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA,o,s,a,l)},i.CreateAlphaTexture=function(t,r,n,o,s,a,l){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_ALPHA,o,s,a,l)},i.CreateRGBTexture=function(t,r,n,o,s,a,l,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT),new i(t,r,n,e.Engine.TEXTUREFORMAT_RGB,o,s,a,l,h)},i.CreateRGBATexture=function(t,r,n,o,s,a,l,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT),new i(t,r,n,e.Engine.TEXTUREFORMAT_RGBA,o,s,a,l,h)},i.CreateRTexture=function(t,r,n,o,s,a,l,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===l&&(l=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=e.Engine.TEXTURETYPE_FLOAT),new i(t,r,n,e.Engine.TEXTUREFORMAT_R,o,s,a,l,h)},i})(e.Texture);e.RawTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h,c,u){void 0===l&&(l=!0),void 0===h&&(h=!1),void 0===c&&(c=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===u&&(u=e.Engine.TEXTURETYPE_UNSIGNED_INT);var f=t.call(this,null,a,!l,h)||this;return f.format=s,f._engine=a.getEngine(),f._texture=a.getEngine().createRawTexture3D(i,r,n,o,s,l,h,c,void 0,u),f.is3D=!0,f}return o(i,t),i.prototype.update=function(e){this._texture&&this._engine.updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,void 0,this._texture.type)},i})(e.Texture);e.RawTexture3D=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e){this._vertexBuffers={},this._scene=e}return t.prototype._prepareBuffers=function(){if(!this._vertexBuffers[e.VertexBuffer.PositionKind]){var t=[];t.push(1,1),t.push(-1,1),t.push(-1,-1),t.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(this._scene.getEngine(),t,e.VertexBuffer.PositionKind,!1,!1,2),this._buildIndexBuffer()}},t.prototype._buildIndexBuffer=function(){var e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)},t.prototype._rebuild=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t._rebuild(),this._buildIndexBuffer())},t.prototype._prepareFrame=function(e,t){void 0===e&&(e=null),void 0===t&&(t=null);var i=this._scene.activeCamera;if(!i)return!1;var t=t||i._postProcesses.filter((function(e){return null!=e}));return!(!t||0===t.length||!this._scene.postProcessesEnabled)&&(t[0].activate(i,e,null!==t&&void 0!==t),!0)},t.prototype.directRender=function(t,i,r,n,o){void 0===i&&(i=null),void 0===r&&(r=!1),void 0===n&&(n=0),void 0===o&&(o=0);for(var s=this._scene.getEngine(),a=0;a0){for(var p=0;p0)for(var e=0;e0){var r=this._camera._getFirstPostProcess();r&&r.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}},t})();e.PostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h){return void 0===n&&(n=null),void 0===l&&(l=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1),t.call(this,i,"pass",null,null,r,n,o,s,a,void 0,l,void 0,null,h)||this}return o(i,t),i})(e.PostProcess);e.PassPostProcess=t})(r||(r={}));var r,s=this&&this.__assign||Object.assign||function(e){for(var t,i=1,r=arguments.length;i=1?1:e<=0?0:e,this},t.prototype.setTransparencyShadow=function(e){return this._transparencyShadow=e,this},t.prototype.getShadowMap=function(){return this._shadowMap},t.prototype.getShadowMapForRendering=function(){return this._shadowMap2?this._shadowMap2:this._shadowMap},t.prototype.addShadowCaster=function(e,t){void 0===t&&(t=!0);var i;return this._shadowMap?(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.push(e),t&&(i=this._shadowMap.renderList).push.apply(i,e.getChildMeshes()),this):this},t.prototype.removeShadowCaster=function(e,t){if(void 0===t&&(t=!0),!this._shadowMap||!this._shadowMap.renderList)return this;var i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(var r=0,n=e.getChildren();r1?(this._shadowMap=new e.RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1),this._shadowMap.createDepthStencilTexture(e.Engine.LESS,!0)):this._shadowMap=new e.RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._shadowMap.onBeforeRenderObservable.add((function(e){i._currentFaceIndex=e,i._filter===t.FILTER_PCF&&r.setColorWrite(!1)})),this._shadowMap.customRenderFunction=this._renderForShadowMap.bind(this),this._shadowMap.onAfterUnbindObservable.add((function(){if(i._filter===t.FILTER_PCF&&r.setColorWrite(!0),i.useBlurExponentialShadowMap||i.useBlurCloseExponentialShadowMap){var e=i.getShadowMapForRendering();e&&i._scene.postProcessManager.directRender(i._blurPostProcesses,e.getInternalTexture(),!0)}}));var n=new e.Color4(0,0,0,0),o=new e.Color4(1,1,1,1);this._shadowMap.onClearObservable.add((function(e){i._filter===t.FILTER_PCF?e.clear(o,!1,!0,!1):i.useExponentialShadowMap||i.useBlurExponentialShadowMap?e.clear(n,!0,!0,!1):e.clear(o,!0,!0,!1)}))},t.prototype._initializeBlurRTTAndPostProcesses=function(){var t=this,i=this._scene.getEngine(),r=this._mapSize/this.blurScale;this.useKernelBlur&&1===this.blurScale||(this._shadowMap2=new e.RenderTargetTexture(this._light.name+"_shadowMap2",r,this._scene,!1,!0,this._textureType),this._shadowMap2.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new e.BlurPostProcess(this._light.name+"KernelBlurX",new e.Vector2(1,0),this.blurKernel,1,null,e.Texture.BILINEAR_SAMPLINGMODE,i,!1,this._textureType),this._kernelBlurXPostprocess.width=r,this._kernelBlurXPostprocess.height=r,this._kernelBlurXPostprocess.onApplyObservable.add((function(e){e.setTexture("textureSampler",t._shadowMap)})),this._kernelBlurYPostprocess=new e.BlurPostProcess(this._light.name+"KernelBlurY",new e.Vector2(0,1),this.blurKernel,1,null,e.Texture.BILINEAR_SAMPLINGMODE,i,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===e.Engine.TEXTURETYPE_UNSIGNED_INT&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new e.PostProcess(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,e.Texture.BILINEAR_SAMPLINGMODE,i,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",r,r),e.setTexture("textureSampler",t._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])},t.prototype._renderForShadowMap=function(e,t,i,r){var n,o=this._scene.getEngine();if(r.length){for(o.setColorWrite(!1),n=0;n=a.length)return void(e&&e(i));setTimeout(f,16)}};f()},t.prototype.forceCompilationAsync=function(e){var t=this;return new Promise(function(i){t.forceCompilation((function(){i()}),e)})},t.prototype.isReady=function(t,i){var r=[];this._textureType!==e.Engine.TEXTURETYPE_UNSIGNED_INT&&r.push("#define FLOAT"),this.useExponentialShadowMap||this.useBlurExponentialShadowMap?r.push("#define ESM"):(this.usePercentageCloserFiltering||this.useContactHardeningShadow)&&r.push("#define DEPTHTEXTURE");var n=[e.VertexBuffer.PositionKind],o=t.getMesh(),s=t.getMaterial();if(this.normalBias&&o.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(n.push(e.VertexBuffer.NormalKind),r.push("#define NORMAL"),o.nonUniformScaling&&r.push("#define NONUNIFORMSCALING"),this.getLight().getTypeID()===e.Light.LIGHTTYPEID_DIRECTIONALLIGHT&&r.push("#define DIRECTIONINLIGHTDATA")),s&&s.needAlphaTesting()){var a=s.getAlphaTestTexture();a&&(r.push("#define ALPHATEST"),o.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push(e.VertexBuffer.UVKind),r.push("#define UV1")),o.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&1===a.coordinatesIndex&&(n.push(e.VertexBuffer.UV2Kind),r.push("#define UV2")))}o.useBones&&o.computeBonesUsingShaders?(n.push(e.VertexBuffer.MatricesIndicesKind),n.push(e.VertexBuffer.MatricesWeightsKind),o.numBoneInfluencers>4&&(n.push(e.VertexBuffer.MatricesIndicesExtraKind),n.push(e.VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton.bones.length+1))):r.push("#define NUM_BONE_INFLUENCERS 0");var l=o.morphTargetManager,h=0;l&&l.numInfluencers>0&&(r.push("#define MORPHTARGETS"),h=l.numInfluencers,r.push("#define NUM_MORPH_INFLUENCERS "+h),e.MaterialHelper.PrepareAttributesForMorphTargets(n,o,{NUM_MORPH_INFLUENCERS:h})),i&&(r.push("#define INSTANCES"),n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"));var c=r.join("\n");return this._cachedDefines!==c&&(this._cachedDefines=c,this._effect=this._scene.getEngine().createEffect("shadowMap",n,["world","mBones","viewProjection","diffuseMatrix","lightData","depthValues","biasAndScale","morphTargetInfluences"],["diffuseSampler"],c,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h})),!!this._effect.isReady()&&((this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady())&&(!(this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady())&&!(this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())))},t.prototype.prepareDefines=function(e,i){var r=this._scene,n=this._light;r.shadowsEnabled&&n.shadowEnabled&&(e["SHADOW"+i]=!0,this.useContactHardeningShadow&&(e["SHADOWPCSS"+i]=!0,this._filteringQuality===t.QUALITY_LOW?e["SHADOWLOWQUALITY"+i]=!0:this._filteringQuality===t.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+i]=!0)),this.usePercentageCloserFiltering?(e["SHADOWPCF"+i]=!0,this._filteringQuality===t.QUALITY_LOW?e["SHADOWLOWQUALITY"+i]=!0:this._filteringQuality===t.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+i]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+i]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+i]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+i]=!0),n.needCube()&&(e["SHADOWCUBE"+i]=!0))},t.prototype.bindShadowLight=function(e,i){var r=this._light,n=this._scene;if(n.shadowsEnabled&&r.shadowEnabled){var o=n.activeCamera;if(o){var s=this.getShadowMap();s&&(r.needCube()||i.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===t.FILTER_PCF?(i.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),s.getSize().width,1/s.getSize().width,this.frustumEdgeFalloff,e)):this._filter===t.FILTER_PCSS?(i.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()), +i.setTexture("depthSampler"+e,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/s.getSize().width,this._contactHardeningLightSizeUVRatio*s.getSize().width,this.frustumEdgeFalloff,e)):(i.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/s.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),r._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(o),this.getLight().getDepthMinZ(o)+this.getLight().getDepthMaxZ(o),e))}}},t.prototype.getTransformMatrix=function(){var t=this._scene;if(this._currentRenderID===t.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderID=t.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;var i=this._light.position;if(this._light.computeTransformedInformation()&&(i=this._light.transformedPosition),e.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(e.Vector3.Dot(this._lightDirection,e.Vector3.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!i.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(i),this._cachedDirection.copyFrom(this._lightDirection),e.Matrix.LookAtLHToRef(i,i.add(this._lightDirection),e.Vector3.Up(),this._viewMatrix);var r=this.getShadowMap();if(r){var n=r.renderList;n&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,n)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix},t.prototype.recreateShadowMap=function(){var e=this._shadowMap;if(e){var t=e.renderList;this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this.filter,this._applyFilterValues(),this._shadowMap.renderList=t}},t.prototype._disposeBlurPostProcesses=function(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]},t.prototype._disposeRTTandPostProcesses=function(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()},t.prototype.dispose=function(){this._disposeRTTandPostProcesses(),this._light&&(this._light._shadowGenerator=null,this._light._markMeshesAsLightDirty())},t.prototype.serialize=function(){var e={},t=this.getShadowMap();if(!t)return e;if(e.lightId=this._light.id,e.mapSize=t.getRenderSize(),e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.forceBackFacesOnly=this.forceBackFacesOnly,e.depthScale=this.depthScale,e.darkness=this.getDarkness(),e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.filteringQuality=this.filteringQuality,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.renderList=[],t.renderList)for(var i=0;i0){for(var ne=0;ne0){for(var se=0;se-1&&void 0!==d.skeletons&&null!==d.skeletons){if(!1===v.indexOf(b.skeletonId)>-1)for(var D=0,I=d.skeletons.length;D0&&this._textureLoadingCallback(e)}this._currentScene.render()}},t.prototype.drag=function(e){e.stopPropagation(),e.preventDefault()},t.prototype.drop=function(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)},t.prototype._traverseFolder=function(e,t,i,r){var n=this,o=e.createReader(),s=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");o.readEntries((function(e){i.count+=e.length;for(var o=0,a=e;o0){for(var i=new Array,r=[],n=e.dataTransfer?e.dataTransfer.items:null,o=0;o0&&e.Tools.ClearLogCache(),this._engine.stopRenderLoop()),e.SceneLoader.LoadAsync("file:",this._sceneFileToLoad,this._engine,(function(e){t._progressCallback&&t._progressCallback(e)})).then((function(e){t._currentScene&&t._currentScene.dispose(),t._currentScene=e,t._sceneLoadedCallback&&t._sceneLoadedCallback(t._sceneFileToLoad,t._currentScene),t._currentScene.executeWhenReady((function(){t._engine.runRenderLoop((function(){t.renderFunction()}))}))})).catch((function(e){t._errorCallback&&t._errorCallback(t._sceneFileToLoad,t._currentScene,e.message)}))):e.Tools.Error("Please provide a valid .babylon file.")},t.FilesToLoad={},t})();e.FilesInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.EnableFor=function(e){e._tags=e._tags||{},e.hasTags=function(){return t.HasTags(e)},e.addTags=function(i){return t.AddTagsTo(e,i)},e.removeTags=function(i){return t.RemoveTagsFrom(e,i)},e.matchesTagsQuery=function(i){return t.MatchesQuery(e,i)}},t.DisableFor=function(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery},t.HasTags=function(t){return!!t._tags&&!e.Tools.IsEmpty(t._tags)},t.GetTags=function(e,t){if(void 0===t&&(t=!0),!e._tags)return null;if(t){var i=[];for(var r in e._tags)e._tags.hasOwnProperty(r)&&!0===e._tags[r]&&i.push(r);return i.join(" ")}return e._tags},t.AddTagsTo=function(e,i){if(i&&"string"==typeof i){i.split(" ").forEach((function(i,r,n){t._AddTagTo(e,i)}))}},t._AddTagTo=function(e,i){""!==(i=i.trim())&&"true"!==i&&"false"!==i&&(i.match(/[\s]/)||i.match(/^([!]|([|]|[&]){2})/)||(t.EnableFor(e),e._tags[i]=!0))},t.RemoveTagsFrom=function(e,i){if(t.HasTags(e)){var r=i.split(" ");for(var n in r)t._RemoveTagFrom(e,r[n])}},t._RemoveTagFrom=function(e,t){delete e._tags[t]},t.MatchesQuery=function(i,r){return void 0===r||(""===r?t.HasTags(i):e.AndOrNotEvaluator.Eval(r,(function(e){return t.HasTags(i)&&i._tags[e]})))},t})();e.Tags=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){}return e.Eval=function(t,i){return"true"===(t=t.match(/\([^\(\)]*\)/g)?t.replace(/\([^\(\)]*\)/g,(function(t){return t=t.slice(1,t.length-1),e._HandleParenthesisContent(t,i)})):e._HandleParenthesisContent(t,i))||"false"!==t&&e.Eval(t,i)},e._HandleParenthesisContent=function(t,i){i=i||function(e){return"true"===e};var r,n=t.split("||");for(var o in n)if(n.hasOwnProperty(o)){var s=e._SimplifyNegation(n[o].trim()),a=s.split("&&");if(a.length>1)for(var l=0;l=400&&o?o(h):i()}),!1),h.addEventListener("error",(function(t){e.Tools.Error("error on XHR request."),i()}),!1),h.send()}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i()},t.IsUASupportingBlobStorage=!0,t.IDBStorageEnabled=!0,t._ParseURL=function(e){document.createElement("a").href=e;var t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},t._ReturnFullUrlLocation=function(e){return-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")?t._ParseURL(window.location.href)+e:e},t})();e.Database=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._isEnabled=!0,this.leftColor=e.Color3.White(),this.rightColor=e.Color3.Black(),this.bias=0,this.power=1}return Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(t){this._isEnabled!==t&&(this._isEnabled=t,e.Engine.MarkAllMaterialsAsDirty(e.Material.FresnelDirtyFlag|e.Material.MiscDirtyFlag))},enumerable:!0,configurable:!0}),t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.serialize=function(){var e={};return e.isEnabled=this.isEnabled,e.leftColor=this.leftColor.asArray(),e.rightColor=this.rightColor.asArray(),e.bias=this.bias,e.power=this.power,e},t.Parse=function(i){var r=new t;return r.isEnabled=i.isEnabled,r.leftColor=e.Color3.FromArray(i.leftColor),r.rightColor=e.Color3.FromArray(i.rightColor),r.bias=i.bias,r.power=i.power||1,r},t})();e.FresnelParameters=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i){var r=t.call(this,e,i,!0)||this;return i.multiMaterials.push(r),r.subMaterials=new Array,r.storeEffectOnSubMeshes=!0,r}return o(i,t),Object.defineProperty(i.prototype,"subMaterials",{get:function(){return this._subMaterials},set:function(e){this._subMaterials=e,this._hookArray(e)},enumerable:!0,configurable:!0}),i.prototype._hookArray=function(e){var t=this,i=e.push;e.push=function(){for(var r=[],n=0;n=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]},i.prototype.getActiveTextures=function(){var e;return(e=t.prototype.getActiveTextures.call(this)).concat.apply(e,this.subMaterials.map((function(e){return e?e.getActiveTextures():[]})))},i.prototype.getClassName=function(){return"MultiMaterial"},i.prototype.isReadyForSubMesh=function(e,t,i){for(var r=0;r=0&&r.multiMaterials.splice(n,1),t.prototype.dispose.call(this,e,i)}},i})(e.Material);e.MultiMaterial=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250}return t.prototype.attachControl=function(t,i){var r=this,n=null;void 0===this._pointerInput&&(this._onLostFocus=function(e){r._offsetX=null,r._offsetY=null},this._pointerInput=function(t,o){var s=t.event;if("mouse"!==s.pointerType)if(t.type===e.PointerEventTypes.POINTERDOWN){if(i||s.preventDefault(),r._pointerPressed.push(s.pointerId),1!==r._pointerPressed.length)return;n={x:s.clientX,y:s.clientY}}else if(t.type===e.PointerEventTypes.POINTERUP){i||s.preventDefault();var a=r._pointerPressed.indexOf(s.pointerId);if(-1===a)return;if(r._pointerPressed.splice(a,1),0!=a)return;n=null,r._offsetX=null,r._offsetY=null}else if(t.type===e.PointerEventTypes.POINTERMOVE){if(i||s.preventDefault(),!n)return;var a=r._pointerPressed.indexOf(s.pointerId);if(0!=a)return;r._offsetX=s.clientX-n.x,r._offsetY=-(s.clientY-n.y)}}),this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE),this._onLostFocus&&t.addEventListener("blur",this._onLostFocus)},t.prototype.detachControl=function(e){this._pointerInput&&e&&(this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null),this._onLostFocus&&(e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null),this._pointerPressed=[],this._offsetX=null,this._offsetY=null)},t.prototype.checkInputs=function(){if(this._offsetX&&this._offsetY){var t=this.camera;if(t.cameraRotation.y+=this._offsetX/this.touchAngularSensibility,this._pointerPressed.length>1)t.cameraRotation.x+=-this._offsetY/this.touchAngularSensibility;else{var i=t._computeLocalCameraSpeed(),r=new e.Vector3(0,0,i*this._offsetY/this.touchMoveSensibility);e.Matrix.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,0,t._cameraRotationMatrix),t.cameraDirection.addInPlace(e.Vector3.TransformCoordinates(r,t._cameraRotationMatrix))}}},t.prototype.getClassName=function(){return"FreeCameraTouchInput"},t.prototype.getSimpleName=function(){return"touch"},n([e.serialize()],t.prototype,"touchAngularSensibility",void 0),n([e.serialize()],t.prototype,"touchMoveSensibility",void 0),t})();e.FreeCameraTouchInput=t,e.CameraInputTypes.FreeCameraTouchInput=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("TouchCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addTouch(),n._setupInputs(),n}return o(t,e),Object.defineProperty(t.prototype,"touchAngularSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"touchMoveSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"TouchCamera"},t.prototype._setupInputs=function(){var e=this.inputs.attached.mouse;e&&(e.touchEnabled=!1)},t})(e.FreeCamera);e.TouchCamera=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l){void 0===s&&(s=null),void 0===a&&(a=!0),void 0===l&&(l=!1);var h=t.call(this,null,o,!a)||this;h.isCube=l,h.isEnabled=!0,h._currentRefreshId=-1,h._refreshRate=1,h._vertexBuffers={},h._uniforms=new Array,h._samplers=new Array,h._textures={},h._floats={},h._ints={},h._floatsArrays={},h._colors3={},h._colors4={},h._vectors2={},h._vectors3={},h._matrices={},h._fallbackTextureUsed=!1,o=h.getScene(),o.proceduralTextures.push(h),h._engine=o.getEngine(),h.name=i,h.isRenderTarget=!0,h._size=r,h._generateMipMaps=a,h.setFragment(n),h._fallbackTexture=s,l?(h._texture=h._engine.createRenderTargetCubeTexture(r,{generateMipMaps:a}),h.setFloat("face",0)):h._texture=h._engine.createRenderTargetTexture(r,a);var c=[];return c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),h._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(h._engine,c,e.VertexBuffer.PositionKind,!1,!1,2),h._createIndexBuffer(),h}return o(i,t),i.prototype._createIndexBuffer=function(){var e=this._engine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)},i.prototype._rebuild=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&t._rebuild(),this._createIndexBuffer(),this.refreshRate===e.RenderTargetTexture.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=e.RenderTargetTexture.REFRESHRATE_RENDER_ONCE)},i.prototype.reset=function(){if(void 0!==this._effect){this._engine._releaseEffect(this._effect)}},i.prototype.isReady=function(){var t,i=this,r=this._engine;return!!this._fragment&&(!!this._fallbackTextureUsed||(t=void 0!==this._fragment.fragmentElement?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._effect=r.createEffect(t,[e.VertexBuffer.PositionKind],this._uniforms,this._samplers,"",void 0,void 0,(function(){i.releaseInternalTexture(),i._fallbackTexture&&(i._texture=i._fallbackTexture._texture,i._texture&&i._texture.incrementReferences()),i._fallbackTextureUsed=!0})),this._effect.isReady()))},i.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},i.prototype.setFragment=function(e){this._fragment=e},Object.defineProperty(i.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!0,configurable:!0}),i.prototype._shouldRender=function(){return!!(this.isEnabled&&this.isReady()&&this._texture)&&(!this._fallbackTextureUsed&&(-1===this._currentRefreshId?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)))},i.prototype.getRenderSize=function(){return this._size},i.prototype.resize=function(e,t){this._fallbackTextureUsed||(this.releaseInternalTexture(),this._texture=this._engine.createRenderTargetTexture(e,t),this._size=e,this._generateMipMaps=t)},i.prototype._checkUniform=function(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)},i.prototype.setTexture=function(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this},i.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},i.prototype.setInt=function(e,t){return this._checkUniform(e),this._ints[e]=t,this},i.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},i.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},i.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},i.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},i.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},i.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},i.prototype.render=function(t){var i=this.getScene();if(i){var r=this._engine;r.enableEffect(this._effect),r.setState(!1);for(var n in this._textures)this._effect.setTexture(n,this._textures[n]);for(n in this._ints)this._effect.setInt(n,this._ints[n]);for(n in this._floats)this._effect.setFloat(n,this._floats[n]);for(n in this._floatsArrays)this._effect.setArray(n,this._floatsArrays[n]);for(n in this._colors3)this._effect.setColor3(n,this._colors3[n]);for(n in this._colors4){var o=this._colors4[n];this._effect.setFloat4(n,o.r,o.g,o.b,o.a)}for(n in this._vectors2)this._effect.setVector2(n,this._vectors2[n]);for(n in this._vectors3)this._effect.setVector3(n,this._vectors3[n]);for(n in this._matrices)this._effect.setMatrix(n,this._matrices[n]);if(this._texture){ +if(this.isCube)for(var s=0;s<6;s++)r.bindFramebuffer(this._texture,s,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),this._effect.setFloat("face",s),r.clear(i.clearColor,!0,!0,!0),r.drawElementsType(e.Material.TriangleFillMode,0,6),5===s&&r.generateMipMapsForCubemap(this._texture);else r.bindFramebuffer(this._texture,0,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),r.clear(i.clearColor,!0,!0,!0),r.drawElementsType(e.Material.TriangleFillMode,0,6);r.unBindFramebuffer(this._texture,this.isCube),this.onGenerated&&this.onGenerated()}}},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t},i.prototype.dispose=function(){var i=this.getScene();if(i){var r=i.proceduralTextures.indexOf(this);r>=0&&i.proceduralTextures.splice(r,1);var n=this._vertexBuffers[e.VertexBuffer.PositionKind];n&&(n.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),t.prototype.dispose.call(this)}},n([e.serialize()],i.prototype,"_size",void 0),n([e.serialize()],i.prototype,"_generateMipMaps",void 0),n([e.serialize()],i.prototype,"isEnabled",void 0),n([e.serialize()],i.prototype,"refreshRate",null),i})(e.Texture);e.ProceduralTexture=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(e,i,r,n,o,s){var a=t.call(this,e,r,null,n,o,s)||this;return a._animate=!0,a._time=0,a._texturePath=i,a.loadJson(i),a.refreshRate=1,a}return o(i,t),i.prototype.loadJson=function(t){var i=this,r=function(){e.Tools.Log("No config file found in "+t+" trying to use ShadersStore or DOM element");try{i.setFragment(i._texturePath)}catch(t){e.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},n=t+"/config.json",o=new XMLHttpRequest;o.open("GET",n,!0),o.addEventListener("load",(function(){if(200===o.status||e.Tools.ValidateXHRData(o,1))try{i._config=JSON.parse(o.response),i.updateShaderUniforms(),i.updateTextures(),i.setFragment(i._texturePath+"/custom"),i._animate=i._config.animate,i.refreshRate=i._config.refreshrate}catch(e){r()}else r()}),!1),o.addEventListener("error",(function(){r()}),!1);try{o.send()}catch(t){e.Tools.Error("CustomProceduralTexture: Error on XHR send request.")}},i.prototype.isReady=function(){if(!t.prototype.isReady.call(this))return!1;for(var e in this._textures){if(!this._textures[e].isReady())return!1}return!0},i.prototype.render=function(e){var i=this.getScene();this._animate&&i&&(this._time+=.03*i.getAnimationRatio(),this.updateShaderUniforms()),t.prototype.render.call(this,e)},i.prototype.updateTextures=function(){for(var t=0;t.005?0+r:0,i.y=Math.abs(n)>.005?0+n:0;var o=this.gamepad.rightStick;if(o){var s=o.x/this.gamepadAngularSensibility,a=o.y/this.gamepadAngularSensibility;o.x=Math.abs(s)>.001?0+s:0,o.y=Math.abs(a)>.001?0+a:0}else o={x:0,y:0};t.rotationQuaternion?t.rotationQuaternion.toRotationMatrix(this._cameraTransform):e.Matrix.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,0,this._cameraTransform);var l=50*t._computeLocalCameraSpeed();this._vector3.copyFromFloats(i.x*l,0,-i.y*l),e.Vector3.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),t.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(o.y,o.x),t.cameraRotation.addInPlace(this._vector2)}},t.prototype.getClassName=function(){return"FreeCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},n([e.serialize()],t.prototype,"gamepadAngularSensibility",void 0),n([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.FreeCameraGamepadInput=t,e.CameraInputTypes.FreeCameraGamepadInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40}return t.prototype.attachControl=function(t,i){var r=this,n=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=n.onGamepadConnectedObservable.add((function(t){t.type!==e.Gamepad.POSE_ENABLED&&(r.gamepad&&t.type!==e.Gamepad.XBOX||(r.gamepad=t))})),this._onGamepadDisconnectedObserver=n.onGamepadDisconnectedObservable.add((function(e){r.gamepad===e&&(r.gamepad=null)})),this.gamepad=n.getGamepadByType(e.Gamepad.XBOX)},t.prototype.detachControl=function(e){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null},t.prototype.checkInputs=function(){if(this.gamepad){var e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){var i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){var r=t.y/this.gamepadRotationSensibility;0!=r&&Math.abs(r)>.005&&(e.inertialBetaOffset+=r)}}var n=this.gamepad.leftStick;if(n&&0!=n.y){var o=n.y/this.gamepadMoveSensibility;0!=o&&Math.abs(o)>.005&&(this.camera.inertialRadiusOffset-=o)}}},t.prototype.getClassName=function(){return"ArcRotateCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},n([e.serialize()],t.prototype,"gamepadRotationSensibility",void 0),n([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.ArcRotateCameraGamepadInput=t,e.CameraInputTypes.ArcRotateCameraGamepadInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){var i=this;this._scene=t,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new e.Observable,e.Tools.IsWindowObjectExist()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator.getGamepads||navigator.webkitGetGamepads||navigator.msGetGamepads||navigator.webkitGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new e.Observable(function(e){for(var t in i._babylonGamepads){var r=i._babylonGamepads[t];r&&r._isConnected&&i.onGamepadConnectedObservable.notifyObserver(e,r)}}),this._onGamepadConnectedEvent=function(e){var t=e.gamepad;if(!(t.index in i._babylonGamepads&&i._babylonGamepads[t.index].isConnected)){var r;i._babylonGamepads[t.index]?(r=i._babylonGamepads[t.index],r.browserGamepad=t,r._isConnected=!0):r=i._addNewGamepad(t),i.onGamepadConnectedObservable.notifyObservers(r),i._startMonitoringGamepads()}},this._onGamepadDisconnectedEvent=function(e){var t=e.gamepad;for(var r in i._babylonGamepads)if(i._babylonGamepads[r].index===t.index){var n=i._babylonGamepads[r];n._isConnected=!1,i.onGamepadDisconnectedObservable.notifyObservers(n);break}},this._gamepadSupport&&(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported?(window.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1)):this._startMonitoringGamepads())}return Object.defineProperty(t.prototype,"gamepads",{get:function(){return this._babylonGamepads},enumerable:!0,configurable:!0}),t.prototype.getGamepadByType=function(t){void 0===t&&(t=e.Gamepad.XBOX);for(var i=0,r=this._babylonGamepads;i=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}return Object.defineProperty(e.prototype,"isConnected",{get:function(){return this._isConnected},enumerable:!0,configurable:!0}),e.prototype.onleftstickchanged=function(e){this._onleftstickchanged=e},e.prototype.onrightstickchanged=function(e){this._onrightstickchanged=e},Object.defineProperty(e.prototype,"leftStick",{get:function(){return this._leftStick},set:function(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightStick",{get:function(){return this._rightStick},set:function(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e},enumerable:!0,configurable:!0}),e.prototype.update=function(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})},e.prototype.dispose=function(){},e.GAMEPAD=0,e.GENERIC=1,e.XBOX=2,e.POSE_ENABLED=3,e})();e.Gamepad=i;var r=(function(t){function r(r,n,o){var s=t.call(this,r,n,o)||this;return s.onButtonDownObservable=new e.Observable,s.onButtonUpObservable=new e.Observable,s.type=i.GENERIC,s._buttons=new Array(o.buttons.length),s}return o(r,t),r.prototype.onbuttondown=function(e){this._onbuttondown=e},r.prototype.onbuttonup=function(e){this._onbuttonup=e},r.prototype._setButtonValue=function(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},r.prototype.update=function(){t.prototype.update.call(this);for(var e=0;ethis._maxRotationDistFromHeadset){var n=r-(r<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=n;var o=Math.sin(-n),s=Math.cos(-n);this._calculatedPosition.x=this._calculatedPosition.x*s-this._calculatedPosition.z*o,this._calculatedPosition.z=this._calculatedPosition.x*o+this._calculatedPosition.z*s}}},i.prototype.initControllerMesh=function(t,r){var n=this;e.SceneLoader.ImportMesh("",i.MODEL_BASE_URL,i.MODEL_FILENAME,t,(function(i){var o=new e.Mesh("",t);i[1].parent=o,i[1].position.z=-.15,n._defaultModel=o,n.attachToMesh(n._defaultModel),r&&r(n._defaultModel)}))},i.prototype._handleButtonChange=function(e,t,i){if(ethis.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(f>this.maxCameraSpeed||f<-this.maxCameraSpeed)&&(f=f<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new e.Vector3(this.position.x+u,this.position.y+f,this.position.z+d),this.setTarget(o)}},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.lockedTarget&&this.follow(this.lockedTarget)},i.prototype.getClassName=function(){return"FollowCamera"},n([e.serialize()],i.prototype,"radius",void 0),n([e.serialize()],i.prototype,"rotationOffset",void 0),n([e.serialize()],i.prototype,"heightOffset",void 0),n([e.serialize()],i.prototype,"cameraAcceleration",void 0),n([e.serialize()],i.prototype,"maxCameraSpeed",void 0),n([e.serializeAsMeshReference("lockedTargetId")],i.prototype,"lockedTarget",void 0),i})(e.TargetCamera);e.FollowCamera=t;var i=(function(t){function i(i,r,n,o,s,a){var l=t.call(this,i,e.Vector3.Zero(),a)||this;return l.alpha=r,l.beta=n,l.radius=o,l.target=s,l._cartesianCoordinates=e.Vector3.Zero(),l.follow(),l}return o(i,t),i.prototype.follow=function(){if(this.target){this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);var e=this.target.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.follow()},i.prototype.getClassName=function(){return"ArcFollowCamera"},i})(e.TargetCamera);e.ArcFollowCamera=i})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addGamepad(),n}return o(t,e),Object.defineProperty(t.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"UniversalCamera"},t})(e.TouchCamera);e.UniversalCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("GamepadCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(e){function t(t,i,r){return e.call(this,t,i,r)||this}return o(t,e),Object.defineProperty(t.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"GamepadCamera"},t})(e.UniversalCamera);e.GamepadCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this._renderPipelines={}}return e.prototype.addPipeline=function(e){this._renderPipelines[e._name]=e},e.prototype.attachCamerasToRenderPipeline=function(e,t,i){void 0===i&&(i=!1);var r=this._renderPipelines[e];r&&r._attachCameras(t,i)},e.prototype.detachCamerasFromRenderPipeline=function(e,t){var i=this._renderPipelines[e];i&&i._detachCameras(t)},e.prototype.enableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._enableEffect(t,i)},e.prototype.disableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._disableEffect(t,i)},e.prototype.update=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}},e.prototype._rebuild=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t._rebuild()}},e.prototype.dispose=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t.dispose()}},e})();e.PostProcessRenderPipelineManager=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}return Object.defineProperty(t.prototype,"isSupported",{get:function(){for(var e in this._postProcesses)if(this._postProcesses.hasOwnProperty(e))for(var t=this._postProcesses[e],i=0;i=2&&t.length>0){var i=this._renderEffects[t[0]].getPostProcesses();if(i)return i[0].samples=e,!0}return!1},t.prototype.dispose=function(){},n([e.serialize()],t.prototype,"_name",void 0),t})();e.PostProcessRenderPipeline=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){void 0===i&&(i=e.Engine.TEXTURETYPE_FLOAT),void 0===r&&(r=null);var n=this;this._scene=t,this._camera=r;var o=t.getEngine();this._depthMap=new e.RenderTargetTexture("depthMap",{width:o.getRenderWidth(),height:o.getRenderHeight()},this._scene,!1,!0,i),this._depthMap.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._depthMap.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((function(t){t.clear(new e.Color4(1,1,1,1),!0,!0,!0)}));var s=function(t){var i=t.getRenderingMesh(),r=n._scene,o=r.getEngine(),s=t.getMaterial();if(s){o.setState(s.backFaceCulling,0,!1,r.useRightHandedSystem);var a=i._getInstancesRenderList(t._id);if(!a.mustReturn){var l=o.getCaps().instancedArrays&&null!==a.visibleInstances[t._id],h=n._camera||r.activeCamera;if(n.isReady(t,l)&&h){if(o.enableEffect(n._effect),i._bind(t,n._effect,e.Material.TriangleFillMode),n._effect.setMatrix("viewProjection",r.getTransformMatrix()),n._effect.setFloat2("depthValues",h.minZ,h.minZ+h.maxZ),s&&s.needAlphaTesting()){var c=s.getAlphaTestTexture();c&&(n._effect.setTexture("diffuseSampler",c),n._effect.setMatrix("diffuseMatrix",c.getTextureMatrix()))}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&n._effect.setMatrices("mBones",i.skeleton.getTransformMatrices(i)),i._processRendering(t,n._effect,e.Material.TriangleFillMode,a,l,(function(e,t){return n._effect.setMatrix("world",t)}))}}}};this._depthMap.customRenderFunction=function(e,t,i,r){var n;if(r.length){for(o.setColorWrite(!1),n=0;n4&&(o.push(e.VertexBuffer.MatricesIndicesExtraKind),o.push(e.VertexBuffer.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("depth",o,["world","mBones","viewProjection","diffuseMatrix","depthValues"],["diffuseSampler"],a)),this._effect.isReady()},t.prototype.getDepthMap=function(){return this._depthMap},t.prototype.dispose=function(){this._depthMap.dispose()},t})();e.DepthRenderer=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o){var s=t.call(this,r.getEngine(),i)||this;s.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",s.SSAORenderEffect="SSAORenderEffect",s.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",s.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",s.SSAOCombineRenderEffect="SSAOCombineRenderEffect",s.totalStrength=1,s.radius=1e-4,s.area=.0075,s.fallOff=1e-6,s.base=.5,s._firstUpdate=!0,s._scene=r,s._createRandomTexture(),s._depthTexture=r.enableDepthRenderer().getDepthMap();var a=n.ssaoRatio||n,l=n.combineRatio||n;return s._originalColorPostProcess=new e.PassPostProcess("SSAOOriginalSceneColor",l,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),!1),s._createSSAOPostProcess(a),s._createBlurPostProcess(a),s._createSSAOCombinePostProcess(l),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOOriginalSceneColorEffect,function(){return s._originalColorPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAORenderEffect,function(){return s._ssaoPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOBlurHRenderEffect,function(){return s._blurHPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOBlurVRenderEffect,function(){return s._blurVPostProcess},!0)),s.addEffect(new e.PostProcessRenderEffect(r.getEngine(),s.SSAOCombineRenderEffect,function(){return s._ssaoCombinePostProcess},!0)),r.postProcessRenderPipelineManager.addPipeline(s),o&&r.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(i,o),s}return o(i,t),i.prototype.dispose=function(e){void 0===e&&(e=!1);for(var i=0;i0?r._ssaoCombinePostProcess.width:r._originalColorPostProcess.width),e.setFloat("near",r._scene.activeCamera.minZ),e.setFloat("far",r._scene.activeCamera.maxZ),e.setFloat("radius",r.radius),e.setTexture("depthSampler",r._depthTexture),r._firstUpdate&&e.setArray("samplerOffsets",r._samplerOffsets))},this._blurVPostProcess=new e.PostProcess("BlurV","ssao2",["outSize","samplerOffsets","near","far","radius"],["depthSampler"],i,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE "+(n?"1":"0")+"\n"),this._blurVPostProcess.onApply=function(e){r._scene.activeCamera&&(e.setFloat("outSize",r._ssaoCombinePostProcess.height>0?r._ssaoCombinePostProcess.height:r._originalColorPostProcess.height),e.setFloat("near",r._scene.activeCamera.minZ),e.setFloat("far",r._scene.activeCamera.maxZ),e.setFloat("radius",r.radius),e.setTexture("depthSampler",r._depthTexture),r._firstUpdate&&(e.setArray("samplerOffsets",r._samplerOffsets),r._firstUpdate=!1))}},i.prototype._rebuild=function(){this._firstUpdate=!0,t.prototype._rebuild.call(this)},i.prototype._generateHemisphere=function(){for(var t,i,r=this.samples,n=[],o=function(e,t){return Math.random()*(t-e)+e},s=0;s=0;a--){var o=Math.pow(3,a),l="#define LUMINANCE_DOWN_SAMPLE\n";0===a&&(l+="#define FINAL_DOWN_SAMPLER");var h=new e.PostProcess("HDRLuminanceDownSample"+a,"standard",["dsOffsets","halfDestPixelSize"],[],{width:o,height:o},null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,l,r);this.luminanceDownSamplePostProcesses.push(h)}var c=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((function(i,r){var o=new Array(18);i.onApply=function(e){if(c){for(var t=0,s=-1;s<2;s++)for(var a=-1;a<2;a++)o[t]=s/c.width,o[t+1]=a/c.height,t+=2;e.setArray2("dsOffsets",o),e.setFloat("halfDestPixelSize",.5/c.width),c=r===n.luminanceDownSamplePostProcesses.length-1?n.luminancePostProcess:i}},r===n.luminanceDownSamplePostProcesses.length-1&&(i.onAfterRender=function(i){var r=t.getEngine().readPixels(0,0,1,1),o=new e.Vector4(1/16581375,1/65025,1/255,1);n._hdrCurrentLuminance=(r[0]*o.x+r[1]*o.y+r[2]*o.z+r[3]*o.w)/100}),n.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLuminanceDownSample"+r,function(){return i},!0))}))},i.prototype._createHdrPostProcess=function(t,i){var r=this;this.hdrPostProcess=new e.PostProcess("HDR","standard",["averageLuminance"],["textureAdderSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define HDR",e.Engine.TEXTURETYPE_UNSIGNED_INT);var n=1,o=0,s=0;this.hdrPostProcess.onApply=function(i){if(i.setTextureFromPostProcess("textureAdderSampler",r._currentDepthOfFieldSource),o+=t.getEngine().getDeltaTime(),n<0)n=r._hdrCurrentLuminance;else{var a=(s-o)/1e3;r._hdrCurrentLuminancen-r.hdrIncreaseRate*a?n-=r.hdrIncreaseRate*a:n=r._hdrCurrentLuminance}n=e.Scalar.Clamp(n,r.hdrMinimumLuminance,1e20),i.setFloat("averageLuminance",n),s=o,r._currentDepthOfFieldSource=r.hdrFinalPostProcess},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDR",function(){return r.hdrPostProcess},!0))},i.prototype._createLensFlarePostProcess=function(t,i){var r=this;this.lensFlarePostProcess=new e.PostProcess("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],i/2,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define LENS_FLARE",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLensFlare",function(){return r.lensFlarePostProcess},!0)),this._createBlurPostProcesses(t,i/4,2),this.lensFlareComposePostProcess=new e.PostProcess("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define LENS_FLARE_COMPOSE",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLensFlareCompose",function(){return r.lensFlareComposePostProcess},!0));var n=new e.Vector2(0,0);this.lensFlarePostProcess.onApply=function(e){e.setTextureFromPostProcess("textureSampler",r._bloomEnabled?r.blurHPostProcesses[0]:r.originalPostProcess),e.setTexture("lensColorSampler",r.lensColorTexture),e.setFloat("strength",r.lensFlareStrength),e.setFloat("ghostDispersal",r.lensFlareGhostDispersal),e.setFloat("haloWidth",r.lensFlareHaloWidth),n.x=r.lensFlarePostProcess.width,n.y=r.lensFlarePostProcess.height,e.setVector2("resolution",n),e.setFloat("distortionStrength",r.lensFlareDistortionStrength)};var o=e.Matrix.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=e.Matrix.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=function(t){if(r._scene.activeCamera){t.setTextureFromPostProcess("otherSampler",r._currentDepthOfFieldSource),t.setTexture("lensDirtSampler",r.lensFlareDirtTexture),t.setTexture("lensStarSampler",r.lensStarTexture);var i=r._scene.activeCamera.getViewMatrix().getRow(0),n=r._scene.activeCamera.getViewMatrix().getRow(2),a=e.Vector3.Dot(i.toVector3(),new e.Vector3(1,0,0))+e.Vector3.Dot(n.toVector3(),new e.Vector3(0,0,1));a*=4;var l=e.Matrix.FromValues(.5*Math.cos(a),-Math.sin(a),0,0,Math.sin(a),.5*Math.cos(a),0,0,0,0,1,0,0,0,0,1),h=s.multiply(l).multiply(o);t.setMatrix("lensStarMatrix",h),r._currentDepthOfFieldSource=r.lensFlareFinalPostProcess}}},i.prototype._createDepthOfFieldPostProcess=function(t,i){var r=this;this.depthOfFieldPostProcess=new e.PostProcess("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define DEPTH_OF_FIELD",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.depthOfFieldPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",r._currentDepthOfFieldSource),e.setTexture("depthSampler",r._getDepthTexture()),e.setFloat("distance",r.depthOfFieldDistance)},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRDepthOfField",function(){return r.depthOfFieldPostProcess},!0))},i.prototype._createMotionBlurPostProcess=function(t,i){var r=this;this.motionBlurPostProcess=new e.PostProcess("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),e.Engine.TEXTURETYPE_UNSIGNED_INT);var n=0,o=e.Matrix.Identity(),s=e.Matrix.Identity(),a=e.Matrix.Identity(),l=e.Vector2.Zero();this.motionBlurPostProcess.onApply=function(e){a=t.getProjectionMatrix().multiply(t.getViewMatrix()),a.invertToRef(s),e.setMatrix("inverseViewProjection",s),e.setMatrix("prevViewProjection",o),o=a,l.x=r.motionBlurPostProcess.width,l.y=r.motionBlurPostProcess.height,e.setVector2("screenSize",l),n=t.getEngine().getFps()/60,e.setFloat("motionScale",n),e.setFloat("motionStrength",r.motionStrength),e.setTexture("depthSampler",r._getDepthTexture())},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRMotionBlur",function(){return r.motionBlurPostProcess},!0))},i.prototype._getDepthTexture=function(){if(this._scene.getEngine().getCaps().drawBuffersExtension){return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]}return this._scene.enableDepthRenderer().getDepthMap()},i.prototype._disposePostProcesses=function(){for(var e=0;e-1?"#define MALI 1\n":null},i})(e.PostProcess);e.FxaaPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h,c,u){void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===u&&(u=!1);var f=t.call(this,i,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],o,s,a,l,h,null,c,void 0,null,u)||this;return f.aberrationAmount=30,f.radialIntensity=0,f.direction=new e.Vector2(.707,.707),f.centerPosition=new e.Vector2(.5,.5),f.onApplyObservable.add((function(e){e.setFloat("chromatic_aberration",f.aberrationAmount),e.setFloat("screen_width",r),e.setFloat("screen_height",n),e.setFloat("radialIntensity",f.radialIntensity),e.setFloat2("direction",f.direction.x,f.direction.y),e.setFloat2("centerPosition",f.centerPosition.x,f.centerPosition.y)})),f}return o(i,t),i})(e.PostProcess);e.ChromaticAberrationPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h){void 0===l&&(l=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1);var c=t.call(this,i,"grain",["intensity","animatedSeed"],[],r,n,o,s,a,null,l,void 0,null,h)||this;return c.intensity=30,c.animated=!1,c.onApplyObservable.add((function(e){e.setFloat("intensity",c.intensity),e.setFloat("animatedSeed",c.animated?Math.random()+1:1)})),c}return o(i,t),i})(e.PostProcess);e.GrainPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h){void 0===l&&(l=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1);var c=t.call(this,i,"sharpen",["sharpnessAmounts","screenSize"],null,r,n,o,s,a,null,l,void 0,null,h)||this;return c.colorAmount=1,c.edgeAmount=.3,c.onApply=function(e){e.setFloat2("screenSize",c.width,c.height),e.setFloat2("sharpnessAmounts",c.edgeAmount,c.colorAmount)},c}return o(i,t),i})(e.PostProcess);e.SharpenPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h,c,u,f){void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===u&&(u=""),void 0===f&&(f=!1);var d=t.call(this,i,"kernelBlur",["delta","direction","cameraMinMaxZ"],["circleOfConfusionSampler"],o,s,a,l,h,null,c,"kernelBlur",{varyingCount:0,depCount:0},!0)||this;return d.direction=r,d.blockCompilation=f,d._packedFloat=!1,d._staticDefines="",d._staticDefines=u,d.onApplyObservable.add((function(e){d._outputTexture?e.setFloat2("delta",1/d._outputTexture.width*d.direction.x,1/d._outputTexture.height*d.direction.y):e.setFloat2("delta",1/d.width*d.direction.x,1/d.height*d.direction.y)})),d.kernel=n,d}return o(i,t),Object.defineProperty(i.prototype,"kernel",{get:function(){return this._idealKernel},set:function(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.blockCompilation||this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"packedFloat",{get:function(){return this._packedFloat},set:function(e){this._packedFloat!==e&&(this._packedFloat=e,this.blockCompilation||this._updateParameters())},enumerable:!0,configurable:!0}),i.prototype.updateEffect=function(e,t,i,r,n,o){void 0===e&&(e=null),void 0===t&&(t=null),void 0===i&&(i=null),this._updateParameters(n,o)},i.prototype._updateParameters=function(e,i){for(var r=this._kernel,n=(r-1)/2,o=[],s=[],a=0,l=0;l0)return Math.max(n,3)}return Math.max(t,3)},i.prototype._gaussianWeight=function(e){var t=Math.sqrt(2*Math.PI)*(1/3),i=-e*e/(1/3*2*(1/3));return 1/t*Math.exp(i)},i.prototype._glslFloat=function(e,t){return void 0===t&&(t=8),e.toFixed(t).replace(/0+$/,"")},i})(e.PostProcess);e.BlurPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h,c,u,f,d,p){void 0===h&&(h=null),void 0===c&&(c=e.Texture.BILINEAR_SAMPLINGMODE),void 0===d&&(d=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===p&&(p=!1);var m=t.call(this,i,n,o,s,a,c=e.Texture.BILINEAR_SAMPLINGMODE,u,f,d=e.Engine.TEXTURETYPE_UNSIGNED_INT,"#define DOF 1\r\n",p)||this;return m.direction=n,m.onApplyObservable.add((function(e){null!=h&&e.setTextureFromPostProcess("textureSampler",h),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",l),r.activeCamera&&e.setFloat2("cameraMinMaxZ",r.activeCamera.minZ,r.activeCamera.maxZ)})),m}return o(i,t),i})(e.BlurPostProcess);e.DepthOfFieldBlurPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){}return e})();e.DepthOfFieldMergePostProcessOptions=t;var i=(function(t){function i(i,r,n,o,s,a,l,h,c,u,f){void 0===u&&(u=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===f&&(f=!1);var d=t.call(this,i,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,a,l,h,c,null,u,void 0,null,!0)||this;return d.blurSteps=o,d.onApplyObservable.add((function(e){e.setTextureFromPostProcess("textureSampler",r),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",n),o.forEach((function(t,i){e.setTextureFromPostProcessOutput("blurStep"+(o.length-i-1),t)}))})),f||d.updateEffect(),d}return o(i,t),i.prototype.updateEffect=function(e,i,r,n,o,s){void 0===e&&(e=null),void 0===i&&(i=null),void 0===r&&(r=null),e||(e="",e+="#define BLUR_LEVEL "+(this.blurSteps.length-1)+"\n"),t.prototype.updateEffect.call(this,e,i,r,n,o,s)},i})(e.PostProcess);e.DepthOfFieldMergePostProcess=i})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h,c){void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var u=t.call(this,i,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],n,o,s,a,l,null,h,void 0,null,c)||this;return u.lensSize=50,u.fStop=1.4,u.focusDistance=2e3,u.focalLength=50,u._depthTexture=null,u._depthTexture=r,u.onApplyObservable.add((function(t){if(!u._depthTexture)return void e.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");t.setTexture("depthSampler",u._depthTexture);var i=u.lensSize/u.fStop,r=i*u.focalLength/(u.focusDistance-u.focalLength);t.setFloat("focusDistance",u.focusDistance),t.setFloat("cocPrecalculation",r),t.setFloat2("cameraMinMaxZ",u._depthTexture.activeCamera.minZ,u._depthTexture.activeCamera.maxZ)})),u}return o(i,t),Object.defineProperty(i.prototype,"depthTexture",{set:function(e){this._depthTexture=e},enumerable:!0,configurable:!0}),i})(e.PostProcess);e.CircleOfConfusionPostProcess=t})(r||(r={}));var r;!(function(e){var t;!(function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"})(t=e.DepthOfFieldEffectBlurLevel||(e.DepthOfFieldEffectBlurLevel={}));var i=(function(i){function r(r,n,o,s,a){void 0===o&&(o=t.Low),void 0===s&&(s=0),void 0===a&&(a=!1);var l=i.call(this,r.getEngine(),"depth of field",(function(){return l._effects}),!0)||this;l._effects=[],l._circleOfConfusion=new e.CircleOfConfusionPostProcess("circleOfConfusion",n,1,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),!1,s,a),l._depthOfFieldBlurY=[],l._depthOfFieldBlurX=[];var h=1,c=15;switch(o){case t.High:h=3,c=51;break;case t.Medium:h=2,c=31;break;default:c=15,h=1}for(var u=c/Math.pow(2,h-1),f=1,d=0;d1&&e.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}},i.prototype._disposePostProcesses=function(e){void 0===e&&(e=!1);for(var t=0;t4&&(o.push(e.VertexBuffer.MatricesIndicesExtraKind),o.push(e.VertexBuffer.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("geometry",o,["world","mBones","viewProjection","diffuseMatrix","view"],["diffuseSampler"],a,void 0,void 0,void 0,{buffersCount:this._enablePosition?3:2})),this._effect.isReady()},t.prototype.getGBuffer=function(){return this._multiRenderTarget},Object.defineProperty(t.prototype,"samples",{get:function(){return this._multiRenderTarget.samples},set:function(e){this._multiRenderTarget.samples=e},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.getGBuffer().dispose()},t.prototype._createRenderTargets=function(){var t=this,i=this._scene.getEngine(),r=this._enablePosition?3:2;if(this._multiRenderTarget=new e.MultiRenderTarget("gBuffer",{width:i.getRenderWidth()*this._ratio,height:i.getRenderHeight()*this._ratio},r,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:e.Engine.TEXTURETYPE_FLOAT}),this.isSupported){this._multiRenderTarget.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null,this._multiRenderTarget.onClearObservable.add((function(t){t.clear(new e.Color4(0,0,0,1),!0,!0,!0)}));var n=function(i){var r=i.getRenderingMesh(),n=t._scene,o=n.getEngine(),s=i.getMaterial();if(s){o.setState(s.backFaceCulling,0,!1,n.useRightHandedSystem);var a=r._getInstancesRenderList(i._id);if(!a.mustReturn){var l=o.getCaps().instancedArrays&&null!==a.visibleInstances[i._id];if(t.isReady(i,l)){if(o.enableEffect(t._effect),r._bind(i,t._effect,e.Material.TriangleFillMode),t._effect.setMatrix("viewProjection",n.getTransformMatrix()),t._effect.setMatrix("view",n.getViewMatrix()),s&&s.needAlphaTesting()){var h=s.getAlphaTestTexture();h&&(t._effect.setTexture("diffuseSampler",h),t._effect.setMatrix("diffuseMatrix",h.getTextureMatrix()))}r.useBones&&r.computeBonesUsingShaders&&r.skeleton&&t._effect.setMatrices("mBones",r.skeleton.getTransformMatrices(r)),r._processRendering(i,t._effect,e.Material.TriangleFillMode,a,l,(function(e,i){return t._effect.setMatrix("world",i)}))}}}};this._multiRenderTarget.customRenderFunction=function(e,t,r,o){var s;if(o.length){for(i.setColorWrite(!1),s=0;s1,n.wrapU=e.Texture.CLAMP_ADDRESSMODE,n.wrapV=e.Texture.CLAMP_ADDRESSMODE,n.wrapR=e.Texture.CLAMP_ADDRESSMODE,n.anisotropicFilteringLevel=1,n._texture=n._getFromCache(i,!0),n._texture||(r.useDelayedTextureLoading?n.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED:n.loadTexture()),n):n}return o(i,t),i.prototype.getTextureMatrix=function(){return this._textureMatrix},i.prototype.load3dlTexture=function(){var t,r=this._engine;t=1===r.webGLVersion?r.createRawTexture(null,1,1,e.Engine.TEXTUREFORMAT_RGBA,!1,!1,e.Texture.BILINEAR_SAMPLINGMODE):r.createRawTexture3D(null,1,1,1,e.Engine.TEXTUREFORMAT_RGBA,!1,!1,e.Texture.BILINEAR_SAMPLINGMODE),this._texture=t;var n=function(n){if("string"==typeof n){for(var o,s=null,a=null,l=n.split("\n"),h=0,c=0,u=0,f=0,d=0,p=0;p0&&(p+1)%4==0)s[p]=255;else{var b=a[p];s[p]=b/d*255}t.is3D?(t.updateSize(h,h,h),r.updateRawTexture3D(t,s,e.Engine.TEXTUREFORMAT_RGBA,!1)):(t.updateSize(h*h,h),r.updateRawTexture(t,s,e.Engine.TEXTUREFORMAT_RGBA,!1))}},o=this.getScene();return o?o._loadFile(this.url,n):this._engine._loadFile(this.url,n),this._texture},i.prototype.loadTexture=function(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this.load3dlTexture()},i.prototype.clone=function(){var e=new i(this.url,this.getScene());return e.level=this.level,e},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,!0),this._texture||this.loadTexture())},i.Parse=function(e,t,r){var n=null;return e.name&&!e.isRenderTarget&&(n=new i(e.name,t),n.name=e.name,n.level=e.level),n},i.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e},i._noneEmptyLineRegex=/\S+/,i})(e.BaseTexture);e.ColorGradingTexture=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._dirty=!0,this._tempColor=new e.Color4(0,0,0,0),this._globalCurve=new e.Color4(0,0,0,0),this._highlightsCurve=new e.Color4(0,0,0,0),this._midtonesCurve=new e.Color4(0,0,0,0),this._shadowsCurve=new e.Color4(0,0,0,0),this._positiveCurve=new e.Color4(0,0,0,0),this._negativeCurve=new e.Color4(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}return Object.defineProperty(t.prototype,"globalHue",{get:function(){return this._globalHue},set:function(e){this._globalHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalDensity",{get:function(){return this._globalDensity},set:function(e){this._globalDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalSaturation",{get:function(){return this._globalSaturation},set:function(e){this._globalSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalExposure",{get:function(){return this._globalExposure},set:function(e){this._globalExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsHue",{get:function(){return this._highlightsHue},set:function(e){this._highlightsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsDensity",{get:function(){return this._highlightsDensity},set:function(e){this._highlightsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsSaturation",{get:function(){return this._highlightsSaturation},set:function(e){this._highlightsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightsExposure",{get:function(){return this._highlightsExposure},set:function(e){this._highlightsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesHue",{get:function(){return this._midtonesHue},set:function(e){this._midtonesHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesDensity",{get:function(){return this._midtonesDensity},set:function(e){this._midtonesDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesSaturation",{get:function(){return this._midtonesSaturation},set:function(e){this._midtonesSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"midtonesExposure",{get:function(){return this._midtonesExposure},set:function(e){this._midtonesExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsHue",{get:function(){return this._shadowsHue},set:function(e){this._shadowsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsDensity",{get:function(){return this._shadowsDensity},set:function(e){this._shadowsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsSaturation",{get:function(){return this._shadowsSaturation},set:function(e){this._shadowsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowsExposure",{get:function(){return this._shadowsExposure},set:function(e){this._shadowsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"ColorCurves"},t.Bind=function(e,t,i,r,n){void 0===i&&(i="vCameraColorCurvePositive"),void 0===r&&(r="vCameraColorCurveNeutral"),void 0===n&&(n="vCameraColorCurveNegative"),e._dirty&&(e._dirty=!1,e.getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e.getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e.getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e.getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(n,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))},t.PrepareUniforms=function(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")},t.prototype.getColorGradingDataToRef=function(e,i,r,n,o){null!=e&&(e=t.clamp(e,0,360),i=t.clamp(i,-100,100),r=t.clamp(r,-100,100),n=t.clamp(n,-100,100),i=t.applyColorGradingSliderNonlinear(i),i*=.5,n=t.applyColorGradingSliderNonlinear(n),i<0&&(i*=-1,e=(e+180)%360),t.fromHSBToRef(e,i,50+.25*n,o),o.scaleToRef(2,o),o.a=1+.01*r)},t.applyColorGradingSliderNonlinear=function(e){e/=100;var t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100},t.fromHSBToRef=function(e,i,r,n){var o=t.clamp(e,0,360),s=t.clamp(i/100,0,1),a=t.clamp(r/100,0,1);if(0===s)n.r=a,n.g=a,n.b=a;else{o/=60;var l=Math.floor(o),h=o-l,c=a*(1-s),u=a*(1-s*h),f=a*(1-s*(1-h));switch(l){case 0:n.r=a,n.g=f,n.b=c;break;case 1:n.r=u,n.g=a,n.b=c;break;case 2:n.r=c,n.g=a,n.b=f;break;case 3:n.r=c,n.g=u,n.b=a;break;case 4:n.r=f,n.g=c,n.b=a;break;default:n.r=a,n.g=c,n.b=u}}n.a=1},t.clamp=function(e,t,i){return Math.min(Math.max(e,t),i)},t.prototype.clone=function(){return e.SerializationHelper.Clone((function(){return new t}),this)},t.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},t.Parse=function(i){return e.SerializationHelper.Parse((function(){return new t}),i,null,null)},n([e.serialize()],t.prototype,"_globalHue",void 0),n([e.serialize()],t.prototype,"_globalDensity",void 0),n([e.serialize()],t.prototype,"_globalSaturation",void 0),n([e.serialize()],t.prototype,"_globalExposure",void 0),n([e.serialize()],t.prototype,"_highlightsHue",void 0),n([e.serialize()],t.prototype,"_highlightsDensity",void 0),n([e.serialize()],t.prototype,"_highlightsSaturation",void 0),n([e.serialize()],t.prototype,"_highlightsExposure",void 0),n([e.serialize()],t.prototype,"_midtonesHue",void 0),n([e.serialize()],t.prototype,"_midtonesDensity",void 0),n([e.serialize()],t.prototype,"_midtonesSaturation",void 0),n([e.serialize()],t.prototype,"_midtonesExposure",void 0),t})();e.ColorCurves=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h,c,u){var f=t.call(this,i,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],a,l,h,c,u)||this;return f.color=n,f.depth=o,f.colorLevel=s,f._ownRefractionTexture=!0,f.onActivateObservable.add((function(t){f._refTexture=f._refTexture||new e.Texture(r,t.getScene())})),f.onApplyObservable.add((function(e){e.setColor3("baseColor",f.color),e.setFloat("depth",f.depth),e.setFloat("colorLevel",f.colorLevel),e.setTexture("refractionSampler",f._refTexture)})),f}return o(i,t),Object.defineProperty(i.prototype,"refractionTexture",{get:function(){return this._refTexture},set:function(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1},enumerable:!0,configurable:!0}),i.prototype.dispose=function(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),t.prototype.dispose.call(this,e)},i})(e.PostProcess);e.RefractionPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){var a=e.call(this,t,"blackAndWhite",["degree"],null,i,r,n,o,s)||this;return a.degree=1,a.onApplyObservable.add((function(e){e.setFloat("degree",a.degree)})),a}return o(t,e),t})(e.PostProcess);e.BlackAndWhitePostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,l,h){void 0===h&&(h=e.Engine.TEXTURETYPE_UNSIGNED_INT);var c=t.call(this,i,"convolution",["kernel","screenSize"],null,n,o,s,a,l,null,h)||this;return c.kernel=r,c.onApply=function(e){e.setFloat2("screenSize",c.width,c.height),e.setArray("kernel",c.kernel)},c}return o(i,t),i.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],i.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],i.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],i.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],i.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],i.GaussianKernel=[0,1,0,1,1,1,0,1,0],i})(e.PostProcess);e.ConvolutionPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i,r,n,o,s,a){var l=e.call(this,t,"filter",["kernelMatrix"],null,r,n,o,s,a)||this;return l.kernelMatrix=i,l.onApply=function(e){e.setMatrix("kernelMatrix",l.kernelMatrix)},l}return o(t,e),t})(e.PostProcess);e.FilterPostProcess=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(r,n,o,s,a,l,h,c,u){void 0===a&&(a=100),void 0===l&&(l=e.Texture.BILINEAR_SAMPLINGMODE);var f=t.call(this,r,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],n.postProcessRatio||n,o,l,h,c,"#define NUM_SAMPLES "+a)||this;return f._screenCoordinates=e.Vector2.Zero(),f.customMeshPosition=e.Vector3.Zero(),f.useCustomMeshPosition=!1,f.invert=!0,f.excludedMeshes=new Array,f.exposure=.3,f.decay=.96815,f.weight=.58767,f.density=.926,u=null===o?u:o.getScene(),h=u.getEngine(),f._viewPort=new e.Viewport(0,0,1,1).toGlobal(h.getRenderWidth(),h.getRenderHeight()),f.mesh=null!==s?s:i.CreateDefaultMesh("VolumetricLightScatteringMesh",u),f._createPass(u,n.passRatio||n),f.onActivate=function(e){f.isSupported||f.dispose(e),f.onActivate=null},f.onApplyObservable.add((function(e){f._updateMeshScreenCoordinates(u),e.setTexture("lightScatteringSampler",f._volumetricLightScatteringRTT),e.setFloat("exposure",f.exposure),e.setFloat("decay",f.decay),e.setFloat("weight",f.weight),e.setFloat("density",f.density),e.setVector2("meshPositionOnScreen",f._screenCoordinates)})),f}return o(i,t),Object.defineProperty(i.prototype,"useDiffuseColor",{get:function(){return e.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1},set:function(t){e.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")},enumerable:!0,configurable:!0}),i.prototype.getClassName=function(){return"VolumetricLightScatteringPostProcess"},i.prototype._isReady=function(t,i){var r=t.getMesh();if(r===this.mesh&&r.material)return r.material.isReady(r);var n=[],o=[e.VertexBuffer.PositionKind],s=t.getMaterial();s&&(s.needAlphaTesting()&&n.push("#define ALPHATEST"),r.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(o.push(e.VertexBuffer.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(o.push(e.VertexBuffer.UV2Kind),n.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(o.push(e.VertexBuffer.MatricesIndicesKind),o.push(e.VertexBuffer.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._volumetricLightScatteringPass=r.getScene().getEngine().createEffect({vertexElement:"depth",fragmentElement:"volumetricLightScatteringPass"},o,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],a)),this._volumetricLightScatteringPass.isReady()},i.prototype.setCustomMeshPosition=function(e){this.customMeshPosition=e},i.prototype.getCustomMeshPosition=function(){return this.customMeshPosition},i.prototype.dispose=function(e){var i=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==i&&e.getScene().customRenderTargets.splice(i,1),this._volumetricLightScatteringRTT.dispose(),t.prototype.dispose.call(this,e)},i.prototype.getPass=function(){return this._volumetricLightScatteringRTT},i.prototype._meshExcluded=function(e){return this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)},i.prototype._createPass=function(t,i){var r=this,n=t.getEngine();this._volumetricLightScatteringRTT=new e.RenderTargetTexture("volumetricLightScatteringMap",{width:n.getRenderWidth()*i,height:n.getRenderHeight()*i},t,!1,!0,e.Engine.TEXTURETYPE_UNSIGNED_INT),this._volumetricLightScatteringRTT.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;var o=this.getCamera();o?o.customRenderTargets.push(this._volumetricLightScatteringRTT):t.customRenderTargets.push(this._volumetricLightScatteringRTT);var s,a=function(t){var i=t.getRenderingMesh();if(!r._meshExcluded(i)){var n=t.getMaterial();if(n){var o=i.getScene(),s=o.getEngine();s.setState(n.backFaceCulling);var a=i._getInstancesRenderList(t._id);if(!a.mustReturn){var l=s.getCaps().instancedArrays&&null!==a.visibleInstances[t._id];if(r._isReady(t,l)){var h=r._volumetricLightScatteringPass;if(i===r.mesh&&(h=t.effect?t.effect:n.getEffect()),s.enableEffect(h),i._bind(t,h,e.Material.TriangleFillMode),i===r.mesh)n.bind(i.getWorldMatrix(),i);else{if(r._volumetricLightScatteringPass.setMatrix("viewProjection",o.getTransformMatrix()),n&&n.needAlphaTesting()){var c=n.getAlphaTestTexture();r._volumetricLightScatteringPass.setTexture("diffuseSampler",c),c&&r._volumetricLightScatteringPass.setMatrix("diffuseMatrix",c.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&r._volumetricLightScatteringPass.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}i._processRendering(t,r._volumetricLightScatteringPass,e.Material.TriangleFillMode,a,l,(function(e,t){return h.setMatrix("world",t)}))}}}}},l=new e.Color4(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((function(){s=t.clearColor,t.clearColor=l})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((function(){t.clearColor=s})),this._volumetricLightScatteringRTT.customRenderFunction=function(i,r,n,o){var s,l=t.getEngine();if(o.length){for(l.setColorWrite(!1),s=0;st._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0})),l.setAlphaMode(e.Engine.ALPHA_COMBINE),s=0;s=c&&a.frame<=u&&(n?(h=a.value.clone(),_?(l=h.getTranslation(),h.setTranslation(l.scaleInPlace(g))):v&&o?(l=h.getTranslation(),h.setTranslation(l.multiplyInPlace(o))):h=a.value):h=a.value,y.push({frame:a.frame+r,value:h}));return this.animations[0].createRange(i,c+r,u+r),!0},i.prototype.translate=function(t,r,n){void 0===r&&(r=e.Space.LOCAL);var o=this.getLocalMatrix();if(r==e.Space.LOCAL)o.m[12]+=t.x,o.m[13]+=t.y,o.m[14]+=t.z;else{var s=null;n&&(s=n.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var a=i._tmpMats[0],l=i._tmpVecs[0];this._parent&&(n&&s?(a.copyFrom(this._parent.getAbsoluteTransform()),a.multiplyToRef(s,a)):a.copyFrom(this._parent.getAbsoluteTransform())),a.m[12]=0,a.m[13]=0,a.m[14]=0,a.invert(),e.Vector3.TransformCoordinatesToRef(t,a,l),o.m[12]+=l.x,o.m[13]+=l.y,o.m[14]+=l.z}this._markAsDirtyAndDecompose()},i.prototype.setPosition=function(t,r,n){void 0===r&&(r=e.Space.LOCAL);var o=this.getLocalMatrix();if(r==e.Space.LOCAL)o.m[12]=t.x,o.m[13]=t.y,o.m[14]=t.z;else{var s=null;n&&(s=n.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var a=i._tmpMats[0],l=i._tmpVecs[0];this._parent&&(n&&s?(a.copyFrom(this._parent.getAbsoluteTransform()),a.multiplyToRef(s,a)):a.copyFrom(this._parent.getAbsoluteTransform())),a.invert(),e.Vector3.TransformCoordinatesToRef(t,a,l),o.m[12]=l.x,o.m[13]=l.y,o.m[14]=l.z}this._markAsDirtyAndDecompose()},i.prototype.setAbsolutePosition=function(t,i){this.setPosition(t,e.Space.WORLD,i)},i.prototype.scale=function(t,r,n,o){void 0===o&&(o=!1);var s=this.getLocalMatrix(),a=i._tmpMats[0];e.Matrix.ScalingToRef(t,r,n,a),a.multiplyToRef(s,s),a.invert();for(var l=0,h=this.children;l0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,n.x>n.y&&n.x>n.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length){var o=this._bone1.getScale(),s=this._bone2.getScale();this._bone1Length=this._bone1.length*o.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*s.y*this.mesh.scaling.y}else if(this._bone1.children[0]){t.computeWorldMatrix(!0);var a=this._bone2.children[0].getAbsolutePosition(t),l=this._bone2.getAbsolutePosition(t),h=this._bone1.getAbsolutePosition(t);this._bone1Length=e.Vector3.Distance(a,l),this._bone2Length=e.Vector3.Distance(l,h)}this._bone1.getRotationMatrixToRef(e.Space.WORLD,t,this._bone1Mat),this.maxAngle=Math.PI,r&&(r.targetMesh&&(this.targetMesh=r.targetMesh,this.targetMesh.computeWorldMatrix(!0)),r.poleTargetMesh?(this.poleTargetMesh=r.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):r.poleTargetBone?this.poleTargetBone=r.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),r.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(r.poleTargetLocalOffset),r.poleAngle&&(this.poleAngle=r.poleAngle),r.bendAxis&&this._bendAxis.copyFrom(r.bendAxis),r.maxAngle&&(this.maxAngle=r.maxAngle),r.slerpAmount&&(this.slerpAmount=r.slerpAmount))}}return Object.defineProperty(t.prototype,"maxAngle",{get:function(){return this._maxAngle},set:function(e){this._setMaxAngle(e)},enumerable:!0,configurable:!0}),t.prototype._setMaxAngle=function(e){e<0&&(e=0),(e>Math.PI||void 0==e)&&(e=Math.PI),this._maxAngle=e;var t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))},t.prototype.update=function(){var i=this._bone1;if(i){var r=this.targetPosition,n=this.poleTargetPosition,o=t._tmpMats[0],s=t._tmpMats[1];this.targetMesh&&r.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,n):this.poleTargetMesh&&e.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),n);var a=t._tmpVecs[0],l=t._tmpVecs[1],h=t._tmpVecs[2],c=t._tmpVecs[3],u=t._tmpVecs[4],f=t._tmpQuat;i.getAbsolutePositionToRef(this.mesh,a),n.subtractToRef(a,u),0==u.x&&0==u.y&&0==u.z?u.y=1:u.normalize(),r.subtractToRef(a,c),c.normalize(),e.Vector3.CrossToRef(c,u,l),l.normalize(),e.Vector3.CrossToRef(c,l,h),h.normalize(),e.Matrix.FromXYZAxesToRef(h,c,l,o);var d=this._bone1Length,p=this._bone2Length,m=e.Vector3.Distance(a,r);this._maxReach>0&&(m=Math.min(this._maxReach,m));var _=(p*p+m*m-d*d)/(2*p*m),g=(m*m+d*d-p*p)/(2*m*d);_>1&&(_=1),g>1&&(g=1),_<-1&&(_=-1),g<-1&&(g=-1);var v=Math.acos(_),y=Math.acos(g),b=-v-y;if(this._rightHandedSystem)e.Matrix.RotationYawPitchRollToRef(0,0,this._adjustRoll,s),s.multiplyToRef(o,o),e.Matrix.RotationAxisToRef(this._bendAxis,y,s),s.multiplyToRef(o,o);else{var x=t._tmpVecs[5];x.copyFrom(this._bendAxis),x.x*=-1,e.Matrix.RotationAxisToRef(x,-y,s),s.multiplyToRef(o,o)}this.poleAngle&&(e.Matrix.RotationAxisToRef(c,this.poleAngle,s),o.multiplyToRef(s,o)),this._bone1&&(this.slerpAmount<1?(this._slerping||e.Quaternion.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),e.Quaternion.FromRotationMatrixToRef(o,f),e.Quaternion.SlerpToRef(this._bone1Quat,f,this.slerpAmount,this._bone1Quat),b=this._bone2Ang*(1-this.slerpAmount)+b*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,e.Space.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(o,e.Space.WORLD,this.mesh),this._bone1Mat.copyFrom(o),this._slerping=!1)),this._bone2.setAxisAngle(this._bendAxis,b,e.Space.LOCAL),this._bone2Ang=b}},t._tmpVecs=[e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero()],t._tmpQuat=e.Quaternion.Identity(),t._tmpMats=[e.Matrix.Identity(),e.Matrix.Identity()],t})();e.BoneIKController=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n){if(this.upAxis=e.Vector3.Up(),this.upAxisSpace=e.Space.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=e.Quaternion.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=e.Vector3.Forward(),this.mesh=t,this.bone=i,this.target=r,n&&(n.adjustYaw&&(this.adjustYaw=n.adjustYaw),n.adjustPitch&&(this.adjustPitch=n.adjustPitch),n.adjustRoll&&(this.adjustRoll=n.adjustRoll),null!=n.maxYaw?this.maxYaw=n.maxYaw:this.maxYaw=Math.PI,null!=n.minYaw?this.minYaw=n.minYaw:this.minYaw=-Math.PI,null!=n.maxPitch?this.maxPitch=n.maxPitch:this.maxPitch=Math.PI,null!=n.minPitch?this.minPitch=n.minPitch:this.minPitch=-Math.PI,null!=n.slerpAmount&&(this.slerpAmount=n.slerpAmount),null!=n.upAxis&&(this.upAxis=n.upAxis),null!=n.upAxisSpace&&(this.upAxisSpace=n.upAxisSpace),null!=n.yawAxis||null!=n.pitchAxis)){var o=e.Axis.Y,s=e.Axis.X;null!=n.yawAxis&&(o=n.yawAxis.clone(),o.normalize()),null!=n.pitchAxis&&(s=n.pitchAxis.clone(),s.normalize());var a=e.Vector3.Cross(s,o);this._transformYawPitch=e.Matrix.Identity(),e.Matrix.FromXYZAxesToRef(s,o,a,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}i.getParent()||this.upAxisSpace!=e.Space.BONE||(this.upAxisSpace=e.Space.LOCAL)}return Object.defineProperty(t.prototype,"minYaw",{get:function(){return this._minYaw},set:function(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxYaw",{get:function(){return this._maxYaw},set:function(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minPitch",{get:function(){return this._minPitch},set:function(e){this._minPitch=e,this._minPitchTan=Math.tan(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxPitch",{get:function(){return this._maxPitch},set:function(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)},enumerable:!0,configurable:!0}),t.prototype.update=function(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);var i=this.bone,r=t._tmpVecs[0];i.getAbsolutePositionToRef(this.mesh,r);var n=this.target,o=t._tmpMats[0],s=t._tmpMats[1],a=this.mesh,l=i.getParent(),h=t._tmpVecs[1];h.copyFrom(this.upAxis),this.upAxisSpace==e.Space.BONE&&l?(this._transformYawPitch&&e.Vector3.TransformCoordinatesToRef(h,this._transformYawPitchInv,h),l.getDirectionToRef(h,this.mesh,h)):this.upAxisSpace==e.Space.LOCAL&&(a.getDirectionToRef(h,h),1==a.scaling.x&&1==a.scaling.y&&1==a.scaling.z||h.normalize());var c=!1,u=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(c=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(u=!0),c||u){var f=t._tmpMats[2],d=t._tmpMats[3];if(this.upAxisSpace==e.Space.BONE&&1==h.y&&l)l.getRotationMatrixToRef(e.Space.WORLD,this.mesh,f);else if(this.upAxisSpace!=e.Space.LOCAL||1!=h.y||l){var p=t._tmpVecs[2];p.copyFrom(this._fowardAxis),this._transformYawPitch&&e.Vector3.TransformCoordinatesToRef(p,this._transformYawPitchInv,p),l?l.getDirectionToRef(p,this.mesh,p):a.getDirectionToRef(p,p);var m=e.Vector3.Cross(h,p);m.normalize();var p=e.Vector3.Cross(m,h);e.Matrix.FromXYZAxesToRef(m,h,p,f)}else f.copyFrom(a.getWorldMatrix());f.invertToRef(d);var _=null;if(u){var g=t._tmpVecs[3];n.subtractToRef(r,g),e.Vector3.TransformCoordinatesToRef(g,d,g),_=Math.sqrt(g.x*g.x+g.z*g.z);var v=Math.atan2(g.y,_),y=v;v>this._maxPitch?(g.y=this._maxPitchTan*_,y=this._maxPitch):vthis._maxYaw||bMath.PI?this._isAngleBetween(b,this._maxYaw,this._midYawConstraint)?(g.z=this._maxYawCos*_,g.x=this._maxYawSin*_,x=this._maxYaw):this._isAngleBetween(b,this._midYawConstraint,this._minYaw)&&(g.z=this._minYawCos*_,g.x=this._minYawSin*_,x=this._minYaw):b>this._maxYaw?(g.z=this._maxYawCos*_,g.x=this._maxYawSin*_,x=this._maxYaw):bMath.PI){var T=t._tmpVecs[8];T.copyFrom(e.Axis.Z),this._transformYawPitch&&e.Vector3.TransformCoordinatesToRef(T,this._transformYawPitchInv,T);var E=t._tmpMats[4];this._boneQuat.toRotationMatrix(E),this.mesh.getWorldMatrix().multiplyToRef(E,E),e.Vector3.TransformCoordinatesToRef(T,E,T),e.Vector3.TransformCoordinatesToRef(T,d,T);var P=Math.atan2(T.x,T.z);if(this._getAngleBetween(P,b)>this._getAngleBetween(P,this._midYawConstraint)){null==_&&(_=Math.sqrt(g.x*g.x+g.z*g.z));var A=this._getAngleBetween(P,this._maxYaw);this._getAngleBetween(P,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i},t.prototype._getAngleBetween=function(e,t){e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t;var i=0;return i=eMath.PI&&(i=2*Math.PI-i),i},t.prototype._isAngleBetween=function(e,t,i){if(e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t,i%=2*Math.PI,i=i<0?i+2*Math.PI:i,tt&&ei&&e-1&&this._meshesWithPoseMatrix.splice(t,1)},t.prototype._computeTransformMatrices=function(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(var i=0;i0&&(n.animation=i.animations[0].serialize()),e.ranges=[];for(var o in this._ranges){var s=this._ranges[o];if(s){var a={};a.name=o,a.from=s.from,a.to=s.to,e.ranges.push(a)}}}return e},t.Parse=function(i,r){var n=new t(i.name,i.id,r);i.dimensionsAtRest&&(n.dimensionsAtRest=e.Vector3.FromArray(i.dimensionsAtRest)),n.needInitialSkinMatrix=i.needInitialSkinMatrix;var o;for(o=0;o-1&&(a=n.bones[s.parentBoneIndex]);var l=s.rest?e.Matrix.FromArray(s.rest):null,h=new e.Bone(s.name,n,a,e.Matrix.FromArray(s.matrix),l);s.length&&(h.length=s.length),s.metadata&&(h.metadata=s.metadata),s.animation&&h.animations.push(e.Animation.Parse(s.animation))}if(i.ranges)for(o=0;o0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e},t.prototype.sortBones=function(){for(var e=new Array,t=new Array(this.bones.length),i=0;i1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)},t.Rgbe2float=function(e,t,i,r,n,o){n>0?(n=this.Ldexp(1,n-136),e[o+0]=t*n,e[o+1]=i*n,e[o+2]=r*n):(e[o+0]=0,e[o+1]=0,e[o+2]=0)},t.readStringLine=function(e,t){for(var i="",r="",n=t;n32767)throw"HDR Bad header format, unsupported size";return s+=r.length+1,{height:t,width:i,dataPosition:s}},t.GetCubeMapTextureData=function(t,i){var r=new Uint8Array(t),n=this.RGBE_ReadHeader(r),o=this.RGBE_ReadPixels_RLE(r,n);return e.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(o,n.width,n.height,i)},t.RGBE_ReadPixels=function(e,t){return this.RGBE_ReadPixels_RLE(e,t)},t.RGBE_ReadPixels_RLE=function(e,t){for(var i,r,n,o,s,a=t.height,l=t.width,h=t.dataPosition,c=0,u=0,f=0,d=new ArrayBuffer(4*l),p=new Uint8Array(d),m=new ArrayBuffer(t.width*t.height*4*3),_=new Float32Array(m);a>0;){if(i=e[h++],r=e[h++],n=e[h++],o=e[h++],2!=i||2!=r||128&n)throw"HDR Bad header format, not RLE";if((n<<8|o)!=l)throw"HDR Bad header format, wrong scan line width";for(c=0,f=0;f<4;f++)for(u=(f+1)*l;c128){if(0==(s=i-128)||s>u-c)throw"HDR Bad Format, bad scanline data (run)";for(;s-- >0;)p[c++]=r}else{if(0==(s=i)||s>u-c)throw"HDR Bad Format, bad scanline data (non-run)";if(p[c++]=r,--s>0)for(var g=0;g255){var g=255/_;d*=g,p*=g,m*=g}l[3*f+0]=d,l[3*f+1]=p,l[3*f+2]=m}l?a.push(l):a.push(u)}return a},n=this.getScene();n&&(this._texture=n.getEngine().createRawCubeTextureFromUrl(this.url,n,this._size,e.Engine.TEXTUREFORMAT_RGB,n.getEngine().getCaps().textureFloat?e.Engine.TEXTURETYPE_FLOAT:e.Engine.TEXTURETYPE_UNSIGNED_INT,this._noMipmap,r,null,this._onLoad,this._onError))},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var t=new i(this.url,e,this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t.coordinatesIndex=this.coordinatesIndex,t.coordinatesMode=this.coordinatesMode,t},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this.loadTexture())},i.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},i.prototype.setReflectionTextureMatrix=function(e){this._textureMatrix=e},i.Parse=function(t,r,n){var o=null;return t.name&&!t.isRenderTarget&&(o=new i(n+t.name,r,t.size,t.noMipmap,t.generateHarmonics,t.useInGammaSpace),o.name=t.name,o.hasAlpha=t.hasAlpha,o.level=t.level,o.coordinatesMode=t.coordinatesMode,o.isBlocking=t.isBlocking),o&&(t.boundingBoxPosition&&(o.boundingBoxPosition=e.Vector3.FromArray(t.boundingBoxPosition)),t.boundingBoxSize&&(o.boundingBoxSize=e.Vector3.FromArray(t.boundingBoxSize)),t.rotationY&&(o.rotationY=t.rotationY)),o},i.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e},i._facesMapping=["right","left","up","down","front","back"],i})(e.BaseTexture);e.HDRCubeTexture=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.ConvertPanoramaToCubemap=function(t,i,r,n){if(!t)throw"ConvertPanoramaToCubemap: input cannot be null";if(t.length!=i*r*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(n,this.FACE_FRONT,t,i,r),back:this.CreateCubemapTexture(n,this.FACE_BACK,t,i,r),left:this.CreateCubemapTexture(n,this.FACE_LEFT,t,i,r),right:this.CreateCubemapTexture(n,this.FACE_RIGHT,t,i,r),up:this.CreateCubemapTexture(n,this.FACE_UP,t,i,r),down:this.CreateCubemapTexture(n,this.FACE_DOWN,t,i,r),size:n,type:e.Engine.TEXTURETYPE_FLOAT,format:e.Engine.TEXTUREFORMAT_RGB,gammaSpace:!1}},t.CreateCubemapTexture=function(e,t,i,r,n){for(var o=new ArrayBuffer(e*e*4*3),s=new Float32Array(o),a=t[1].subtract(t[0]).scale(1/e),l=t[3].subtract(t[2]).scale(1/e),h=1/e,c=0,u=0;uMath.PI;)n-=2*Math.PI;var s=n/Math.PI,a=o/Math.PI;s=.5*s+.5;var l=Math.round(s*i);l<0?l=0:l>=i&&(l=i-1);var h=Math.round(a*r);h<0?h=0:h>=r&&(h=r-1);var c=r-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}},t.FACE_FRONT=[new e.Vector3(-1,-1,-1),new e.Vector3(1,-1,-1),new e.Vector3(-1,1,-1),new e.Vector3(1,1,-1)],t.FACE_BACK=[new e.Vector3(1,-1,1),new e.Vector3(-1,-1,1),new e.Vector3(1,1,1),new e.Vector3(-1,1,1)],t.FACE_RIGHT=[new e.Vector3(1,-1,-1),new e.Vector3(1,-1,1),new e.Vector3(1,1,-1),new e.Vector3(1,1,1)],t.FACE_LEFT=[new e.Vector3(-1,-1,1),new e.Vector3(-1,-1,-1),new e.Vector3(-1,1,1),new e.Vector3(-1,1,-1)],t.FACE_DOWN=[new e.Vector3(-1,1,-1),new e.Vector3(1,1,-1),new e.Vector3(-1,1,1),new e.Vector3(1,1,1)],t.FACE_UP=[new e.Vector3(-1,-1,1),new e.Vector3(1,-1,1),new e.Vector3(-1,-1,-1),new e.Vector3(1,-1,-1)],t})();e.PanoramaToCubeMapTools=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(t,i){var r=e.call(this,t.x,t.y)||this;return r.index=i,r}return o(t,e),t})(e.Vector2),r=(function(){function i(){this.elements=new Array}return i.prototype.add=function(e){var i=this,r=new Array;return e.forEach((function(e){if(0===r.length||!e.equalsWithEpsilon(r[0])){var n=new t(e,i.elements.length);r.push(n),i.elements.push(n)}})),r},i.prototype.computeBounds=function(){var t=new e.Vector2(this.elements[0].x,this.elements[0].y),i=new e.Vector2(this.elements[0].x,this.elements[0].y);return this.elements.forEach((function(e){e.xi.x&&(i.x=e.x),e.yi.y&&(i.y=e.y)})),{min:t,max:i,width:i.x-t.x,height:i.y-t.y}},i})(),n=(function(){function t(){}return t.Rectangle=function(t,i,r,n){return[new e.Vector2(t,i),new e.Vector2(r,i),new e.Vector2(r,n),new e.Vector2(t,n)]},t.Circle=function(t,i,r,n){void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=32);for(var o=new Array,s=0,a=2*Math.PI/n,l=0;l0){var d=a.length/3;this._points.elements.forEach((function(e){s.push(0,-1,0),a.push(e.x,-r,e.y),l.push(1-(e.x-h.min.x)/h.width,1-(e.y-h.min.y)/h.height)}));for(var p=c.length,f=0;fs.elements.length-1?s.elements[0]:s.elements[u+1],t.push(d.x,0,d.y),t.push(d.x,-a,d.y),t.push(f.x,0,f.y),t.push(f.x,-a,f.y);var p=new e.Vector3(d.x,0,d.y),m=new e.Vector3(f.x,0,f.y),_=m.subtract(p),g=new e.Vector3(0,1,0),v=e.Vector3.Cross(_,g);v=v.normalize(),r.push(c/o.width,0),r.push(c/o.width,1),c+=_.length(),r.push(c/o.width,0),r.push(c/o.width,1),l?(i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),n.push(h),n.push(h+2),n.push(h+1),n.push(h+1),n.push(h+2),n.push(h+3)):(i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),n.push(h),n.push(h+1),n.push(h+2),n.push(h+1),n.push(h+3),n.push(h+2)),h+=4}},t})();e.PolygonMeshBuilder=s})(r||(r={}));var r;!(function(e){var t=0,i=(function(){function t(e,t,i){this.pos=e,this.normal=t,this.uv=i}return t.prototype.clone=function(){return new t(this.pos.clone(),this.normal.clone(),this.uv.clone())},t.prototype.flip=function(){this.normal=this.normal.scale(-1)},t.prototype.interpolate=function(i,r){return new t(e.Vector3.Lerp(this.pos,i.pos,r),e.Vector3.Lerp(this.normal,i.normal,r),e.Vector2.Lerp(this.uv,i.uv,r))},t})(),r=(function(){function t(e,t){this.normal=e,this.w=t}return t.FromPoints=function(i,r,n){var o=n.subtract(i),s=r.subtract(i);if(0===o.lengthSquared()||0===s.lengthSquared())return null;var a=e.Vector3.Normalize(e.Vector3.Cross(o,s));return new t(a,e.Vector3.Dot(a,i))},t.prototype.clone=function(){return new t(this.normal.clone(),this.w)},t.prototype.flip=function(){this.normal.scaleInPlace(-1),this.w=-this.w},t.prototype.splitPolygon=function(i,r,o,s,a){var l,h,c=0,u=[];for(l=0;lt.EPSILON?1:0;c|=f,u.push(f)}switch(c){case 0:(e.Vector3.Dot(this.normal,i.plane.normal)>0?r:o).push(i);break;case 1:s.push(i);break;case 2:a.push(i);break;case 3:var d=[],p=[];for(l=0;l=3&&(x=new n(d,i.shared),x.plane&&s.push(x)),p.length>=3&&(x=new n(p,i.shared),x.plane&&a.push(x))}},t.EPSILON=1e-5,t})(),n=(function(){function e(e,t){this.vertices=e,this.shared=t,this.plane=r.FromPoints(e[0].pos,e[1].pos,e[2].pos)}return e.prototype.clone=function(){return new e(this.vertices.map((function(e){return e.clone()})),this.shared)},e.prototype.flip=function(){this.vertices.reverse().map((function(e){e.flip()})),this.plane.flip()},e})(),o=(function(){function e(e){this.plane=null,this.front=null,this.back=null,this.polygons=new Array,e&&this.build(e)}return e.prototype.clone=function(){var t=new e;return t.plane=this.plane&&this.plane.clone(),t.front=this.front&&this.front.clone(),t.back=this.back&&this.back.clone(),t.polygons=this.polygons.map((function(e){return e.clone()})),t},e.prototype.invert=function(){for(var e=0;e0);for(var r=0,n=i;r0)}},t})();e.LensFlareSystemSceneComponent=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){this.name=t,this.lensFlares=new Array,this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455, +this._vertexBuffers={},this._isEnabled=!0,this._scene=r||e.Engine.LastCreatedScene;var n=this._scene._getComponent(e.SceneComponentConstants.NAME_LENSFLARESYSTEM);n||(n=new e.LensFlareSystemSceneComponent(this._scene),r._addComponent(n)),this._emitter=i,this.id=t,r.lensFlareSystems.push(this),this.meshesSelectionPredicate=function(e){return r.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&0!=(e.layerMask&r.activeCamera.layerMask)};var o=r.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(o,s,e.VertexBuffer.PositionKind,!1,!1,2);var a=[];a.push(0),a.push(1),a.push(2),a.push(0),a.push(2),a.push(3),this._indexBuffer=o.createIndexBuffer(a),this._effect=o.createEffect("lensFlare",[e.VertexBuffer.PositionKind],["color","viewportMatrix"],["textureSampler"],"")}return Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEmitter=function(){return this._emitter},t.prototype.setEmitter=function(e){this._emitter=e},t.prototype.getEmitterPosition=function(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position},t.prototype.computeEffectivePosition=function(t){var i=this.getEmitterPosition();return i=e.Vector3.Project(i,e.Matrix.Identity(),this._scene.getTransformMatrix(),t),this._positionX=i.x,this._positionY=i.y,i=e.Vector3.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(t.x-=this.viewportBorder,t.y-=this.viewportBorder,t.width+=2*this.viewportBorder,t.height+=2*this.viewportBorder,i.x+=this.viewportBorder,i.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder),i.z>0&&(this._positionX>t.x&&this._positionXt.y&&(this._positionY,t.y,t.height),!0)},t.prototype._isVisible=function(){if(!this._isEnabled||!this._scene.activeCamera)return!1;var t=this.getEmitterPosition(),i=t.subtract(this._scene.activeCamera.globalPosition),r=i.length();i.normalize();var n=new e.Ray(this._scene.activeCamera.globalPosition,i),o=this._scene.pickWithRay(n,this.meshesSelectionPredicate,!0);return!o||!o.hit||o.distance>r},t.prototype.render=function(){if(!this._effect.isReady()||!this._scene.activeCamera)return!1;var t=this._scene.getEngine(),i=this._scene.activeCamera.viewport,r=i.toGlobal(t.getRenderWidth(!0),t.getRenderHeight(!0));if(!this.computeEffectivePosition(r))return!1;if(!this._isVisible())return!1;var n,o;n=this._positionXr.x+r.width-this.borderLimit?this._positionX-r.x-r.width+this.borderLimit:0,o=this._positionYr.y+r.height-this.borderLimit?this._positionY-r.y-r.height+this.borderLimit:0;var s=n>o?n:o;(s-=this.viewportBorder)>this.borderLimit&&(s=this.borderLimit);var a=1-s/this.borderLimit;if(a<0)return!1;a>1&&(a=1),this.viewportBorder>0&&(r.x+=this.viewportBorder,r.y+=this.viewportBorder,r.width-=2*this.viewportBorder,r.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);var l=r.x+r.width/2,h=r.y+r.height/2,c=l-this._positionX,u=h-this._positionY;t.enableEffect(this._effect),t.setState(!1),t.setDepthBuffer(!1),t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect);for(var f=0;f-1?this._onBeforePhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerAfterPhysicsStep=function(e){this._onAfterPhysicsStepCallbacks.push(e)},t.prototype.unregisterAfterPhysicsStep=function(t){var i=this._onAfterPhysicsStepCallbacks.indexOf(t);i>-1?this._onAfterPhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerOnPhysicsCollide=function(e,t){var i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})},t.prototype.unregisterOnPhysicsCollide=function(t,i){var r=t instanceof Array?t:[t],n=-1;this._onPhysicsCollideCallbacks.some((function(e,t){if(e.callback===i&&e.otherImpostors.length===r.length){var o=e.otherImpostors.every((function(e){return r.indexOf(e)>-1}));return o&&(n=t),o}return!1}))?this._onPhysicsCollideCallbacks.splice(n,1):e.Tools.Warn("Function to remove was not found")},t.prototype.getParentsRotation=function(){var t=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);t;)t.rotationQuaternion?this._tmpQuat2.copyFrom(t.rotationQuaternion):e.Quaternion.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,t.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),t=t.parent;return this._tmpQuat},t.prototype.applyForce=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this},t.prototype.applyImpulse=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this},t.prototype.createJoint=function(t,i,r){var n=new e.PhysicsJoint(i,r);return this.addJoint(t,n),this},t.prototype.addJoint=function(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this},t.prototype.sleep=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this},t.prototype.wakeUp=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this},t.prototype.clone=function(e){return e?new t(e,this.type,this._options,this._scene):null},t.prototype.dispose=function(){var e=this;this._physicsEngine&&(this._joints.forEach((function(t){e._physicsEngine&&e._physicsEngine.removeJoint(e,t.otherImpostor,t.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)},t.prototype.setDeltaPosition=function(e){this._deltaPosition.copyFrom(e)},t.prototype.setDeltaRotation=function(t){this._deltaRotation||(this._deltaRotation=new e.Quaternion),this._deltaRotation.copyFrom(t),this._deltaRotationConjugated=this._deltaRotation.conjugate()},t.prototype.getBoxSizeToRef=function(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this},t.prototype.getRadius=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0},t.prototype.syncBoneWithImpostor=function(i,r,n,o,s){var a=t._tmpVecs[0],l=this.object;if(l.rotationQuaternion)if(s){var h=t._tmpQuat;l.rotationQuaternion.multiplyToRef(s,h),i.setRotationQuaternion(h,e.Space.WORLD,r)}else i.setRotationQuaternion(l.rotationQuaternion,e.Space.WORLD,r);a.x=0,a.y=0,a.z=0,n&&(a.x=n.x,a.y=n.y,a.z=n.z,i.getDirectionToRef(a,r,a),void 0!==o&&null!==o||(o=n.length()),a.x*=o,a.y*=o,a.z*=o),i.getParent()?(a.addInPlace(l.getAbsolutePosition()),i.setAbsolutePosition(a,r)):(r.setAbsolutePosition(l.getAbsolutePosition()),r.position.x-=a.x,r.position.y-=a.y,r.position.z-=a.z)},t.prototype.syncImpostorWithBone=function(i,r,n,o,s,a){var l=this.object;if(l.rotationQuaternion)if(s){var h=t._tmpQuat;i.getRotationQuaternionToRef(e.Space.WORLD,r,h),h.multiplyToRef(s,l.rotationQuaternion)}else i.getRotationQuaternionToRef(e.Space.WORLD,r,l.rotationQuaternion);var c=t._tmpVecs[0],u=t._tmpVecs[1];a||(a=t._tmpVecs[2],a.x=0,a.y=1,a.z=0),i.getDirectionToRef(a,r,u),i.getAbsolutePositionToRef(r,c),void 0!==o&&null!==o||!n||(o=n.length()),void 0!==o&&null!==o&&(c.x+=u.x*o,c.y+=u.y*o,c.z+=u.z*o),l.setAbsolutePosition(c)},t.DEFAULT_OBJECT_SIZE=new e.Vector3(1,1,1),t.IDENTITY_QUATERNION=e.Quaternion.Identity(),t._tmpVecs=[e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero()],t._tmpQuat=e.Quaternion.Identity(),t.NoImpostor=0,t.SphereImpostor=1,t.BoxImpostor=2,t.PlaneImpostor=3,t.MeshImpostor=4,t.CylinderImpostor=7,t.ParticleImpostor=8,t.HeightmapImpostor=9,t})();e.PhysicsImpostor=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i){if(void 0===i&&(i=new e.CannonJSPlugin),this._physicsPlugin=i,this._impostors=[],this._joints=[],!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");t=t||new e.Vector3(0,-9.807,0),this.setGravity(t),this.setTimeStep()}return t.prototype.setGravity=function(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)},t.prototype.setTimeStep=function(e){void 0===e&&(e=1/60),this._physicsPlugin.setTimeStep(e)},t.prototype.getTimeStep=function(){return this._physicsPlugin.getTimeStep()},t.prototype.dispose=function(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()},t.prototype.getPhysicsPluginName=function(){return this._physicsPlugin.name},t.prototype.addImpostor=function(e){e.uniqueId=this._impostors.push(e),e.parent||this._physicsPlugin.generatePhysicsBody(e)},t.prototype.removeImpostor=function(e){var t=this._impostors.indexOf(e);if(t>-1){var i=this._impostors.splice(t,1);i.length&&(i[0].physicsBody=null)}},t.prototype.addJoint=function(e,t,i){var r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)},t.prototype.removeJoint=function(e,t,i){var r=this._joints.filter((function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e}));r.length&&this._physicsPlugin.removeJoint(r[0])},t.prototype._step=function(e){var t=this;this._impostors.forEach((function(e){e.isBodyInitRequired()&&t._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)},t.prototype.getPhysicsPlugin=function(){return this._physicsPlugin},t.prototype.getImpostors=function(){return this._impostors},t.prototype.getImpostorForPhysicsObject=function(e){for(var t=0;tr)return null;var d=o===s.Constant?n:n*(1-f/r);return{force:l.multiplyByFloats(d,d,d),contactPoint:u}},t.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._sphere.dispose():setTimeout((function(){t._dataFetched||t._sphere.dispose()}),0)},t.prototype._prepareSphere=function(){this._sphere||(this._sphere=e.MeshBuilder.CreateSphere("radialExplosionEventSphere",this._sphereOptions,this._scene),this._sphere.isVisible=!1)},t.prototype._intersectsWithSphere=function(t,i,r){var n=t.object;return this._prepareSphere(),this._sphere.position=i,this._sphere.scaling=new e.Vector3(2*r,2*r,2*r),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(n,!0)},t})();e.PhysicsRadialExplosionEvent=i;var r=(function(){function e(e,t,i,r,n,o){void 0===o&&(o=s.Constant),this._dataFetched=!1,this._physicsHelper=e,this._scene=t,this._origin=i,this._radius=r,this._strength=n,this._falloff=o,this._tickCallback=this._tick.bind(this)}return e.prototype.getData=function(){return this._dataFetched=!0,{sphere:this._sphere}},e.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},e.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._sphere.dispose():setTimeout((function(){t._dataFetched||t._sphere.dispose()}),0)},e.prototype._tick=function(){if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._radius,-1*this._strength,this._falloff);else{var e=this._physicsHelper.applyRadialExplosionForce(this._origin,this._radius,-1*this._strength,this._falloff);e&&(this._sphere=e.getData().sphere.clone("radialExplosionEventSphereClone"))}},e})();e.PhysicsGravitationalFieldEvent=r;var n=(function(){function t(t,i,r,n,o,s){this._scene=t,this._origin=i,this._radius=r,this._strength=n,this._height=o,this._updraftMode=s,this._originTop=e.Vector3.Zero(),this._originDirection=e.Vector3.Zero(),this._cylinderPosition=e.Vector3.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._origin.addToRef(new e.Vector3(0,this._height/2,0),this._cylinderPosition),this._origin.addToRef(new e.Vector3(0,this._height,0),this._originTop),this._updraftMode===a.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=this._tick.bind(this)}return t.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},t.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},t.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},t.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._cylinder.dispose():setTimeout((function(){t._dataFetched||t._cylinder.dispose()}),0)},t.prototype.getImpostorForceAndContactPoint=function(e){if(0===e.mass)return null;if(!this._intersectsWithCylinder(e))return null;var t=e.getObjectCenter();if(this._updraftMode===a.Perpendicular)var i=this._originDirection;else var i=t.subtract(this._originTop);var r=-1*this._strength;return{force:i.multiplyByFloats(r,r,r),contactPoint:t}},t.prototype._tick=function(){var e=this;this._physicsEngine.getImpostors().forEach((function(t){var i=e.getImpostorForceAndContactPoint(t);i&&t.applyForce(i.force,i.contactPoint)}))},t.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=e.MeshBuilder.CreateCylinder("updraftEventCylinder",{height:this._height,diameter:2*this._radius},this._scene),this._cylinder.isVisible=!1)},t.prototype._intersectsWithCylinder=function(e){var t=e.object;return this._prepareCylinder(),this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(t,!0)},t})();e.PhysicsUpdraftEvent=n;var o=(function(){function t(t,i,r,n,o){this._scene=t,this._origin=i,this._radius=r,this._strength=n,this._height=o,this._originTop=e.Vector3.Zero(),this._centripetalForceThreshold=.7,this._updraftMultiplier=.02,this._cylinderPosition=e.Vector3.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._origin.addToRef(new e.Vector3(0,this._height/2,0),this._cylinderPosition),this._origin.addToRef(new e.Vector3(0,this._height,0),this._originTop),this._tickCallback=this._tick.bind(this)}return t.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},t.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},t.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},t.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._cylinder.dispose():setTimeout((function(){t._dataFetched||t._cylinder.dispose()}),0)},t.prototype.getImpostorForceAndContactPoint=function(t){if(0===t.mass)return null;if(!this._intersectsWithCylinder(t))return null;if("Mesh"!==t.object.getClassName()&&"InstancedMesh"!==t.object.getClassName())return null;var i=t.getObjectCenter(),r=new e.Vector3(this._origin.x,i.y,this._origin.z),n=i.subtract(r),o=new e.Ray(r,n,this._radius),s=o.intersectsMesh(t.object),a=s.pickedPoint;if(!a)return null;var l=s.distance/this._radius,h=e.Vector3.Cross(r,i).normalize(),c=a.normalize();if(l>this._centripetalForceThreshold&&(c=c.negate()),l>this._centripetalForceThreshold)var u=c.x*this._strength/8,f=c.y*this._updraftMultiplier,d=c.z*this._strength/8;else var u=(h.x+c.x)/2,f=this._originTop.y*this._updraftMultiplier,d=(h.z+c.z)/2;var p=new e.Vector3(u,f,d);return p=p.multiplyByFloats(this._strength,this._strength,this._strength),{force:p,contactPoint:i}},t.prototype._tick=function(){var e=this;this._physicsEngine.getImpostors().forEach((function(t){var i=e.getImpostorForceAndContactPoint(t);i&&t.applyForce(i.force,i.contactPoint)}))},t.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=e.MeshBuilder.CreateCylinder("vortexEventCylinder",{height:this._height,diameter:2*this._radius},this._scene),this._cylinder.isVisible=!1)},t.prototype._intersectsWithCylinder=function(e){var t=e.object;return this._prepareCylinder(),this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(t,!0)},t})();e.PhysicsVortexEvent=o;var s;!(function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"})(s=e.PhysicsRadialImpulseFalloff||(e.PhysicsRadialImpulseFalloff={}));var a;!(function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"})(a=e.PhysicsUpdraftMode||(e.PhysicsUpdraftMode={}))})(r||(r={}));var r;!(function(t){var i=(function(){function i(i,r){if(void 0===i&&(i=!0),void 0===r&&(r=10),this._useDeltaForWorldStep=i,this.name="CannonJSPlugin",this._physicsMaterials=new Array,this._fixedTimeStep=1/60,this.BJSCANNON=e,this._minus90X=new t.Quaternion(-.7071067811865475,0,0,.7071067811865475),this._plus90X=new t.Quaternion(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=t.Vector3.Zero(),this._tmpDeltaPosition=t.Vector3.Zero(),this._tmpUnityRotation=new t.Quaternion,!this.isSupported())return void t.Tools.Error("CannonJS is not available. Please make sure you included the js file.");this._extendNamespace(),this.world=new this.BJSCANNON.World,this.world.broadphase=new this.BJSCANNON.NaiveBroadphase,this.world.solver.iterations=r}return i.prototype.setGravity=function(e){this.world.gravity.copy(e)},i.prototype.setTimeStep=function(e){this._fixedTimeStep=e},i.prototype.getTimeStep=function(){return this._fixedTimeStep},i.prototype.executeStep=function(e,t){this.world.step(this._fixedTimeStep,this._useDeltaForWorldStep?e:0,3)},i.prototype.applyImpulse=function(e,t,i){var r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),n=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(n,r)},i.prototype.applyForce=function(e,t,i){var r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),n=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(n,r)},i.prototype.generatePhysicsBody=function(e){if(e.parent)return void(e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate()));if(e.isBodyInitRequired()){var t=this._createShape(e),i=e.physicsBody;i&&this.removePhysicsBody(e);var r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),n={mass:e.getParam("mass"),material:r},o=e.getParam("nativeOptions");for(var s in o)o.hasOwnProperty(s)&&(n[s]=o[s]);e.physicsBody=new this.BJSCANNON.Body(n), +e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){e.physicsBody[t].copy(i[t])})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)},i.prototype._processChildMeshes=function(e){var i=this,r=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],n=e.object.rotationQuaternion;if(r.length){var o=function(r,s){if(n&&s.rotationQuaternion){var a=s.getPhysicsImpostor();if(a){if(a.parent!==e){var l=s.getAbsolutePosition().subtract(e.object.getAbsolutePosition()),h=s.rotationQuaternion.multiply(t.Quaternion.Inverse(n));a.physicsBody&&(i.removePhysicsBody(a),a.physicsBody=null),a.parent=e,a.resetUpdateFlags(),e.physicsBody.addShape(i._createShape(a),new i.BJSCANNON.Vec3(l.x,l.y,l.z),new i.BJSCANNON.Quaternion(h.x,h.y,h.z,h.w)),e.physicsBody.mass+=a.getParam("mass")}}n.multiplyInPlace(s.rotationQuaternion),s.getChildMeshes(!0).filter((function(e){return!!e.physicsImpostor})).forEach(o.bind(i,s.getAbsolutePosition()))}};r.filter((function(e){return!!e.physicsImpostor})).forEach(o.bind(this,e.object.getAbsolutePosition()))}},i.prototype.removePhysicsBody=function(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),this.world.remove(e.physicsBody)},i.prototype.generateJoint=function(e){var i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(i&&r){var n,o=e.joint.jointData,s={pivotA:o.mainPivot?(new this.BJSCANNON.Vec3).copy(o.mainPivot):null,pivotB:o.connectedPivot?(new this.BJSCANNON.Vec3).copy(o.connectedPivot):null,axisA:o.mainAxis?(new this.BJSCANNON.Vec3).copy(o.mainAxis):null,axisB:o.connectedAxis?(new this.BJSCANNON.Vec3).copy(o.connectedAxis):null,maxForce:o.nativeParams.maxForce,collideConnected:!!o.collision};switch(e.joint.type){case t.PhysicsJoint.HingeJoint:case t.PhysicsJoint.Hinge2Joint:n=new this.BJSCANNON.HingeConstraint(i,r,s);break;case t.PhysicsJoint.DistanceJoint:n=new this.BJSCANNON.DistanceConstraint(i,r,o.maxDistance||2);break;case t.PhysicsJoint.SpringJoint:var a=o;n=new this.BJSCANNON.Spring(i,r,{restLength:a.length,stiffness:a.stiffness,damping:a.damping,localAnchorA:s.pivotA,localAnchorB:s.pivotB});break;case t.PhysicsJoint.LockJoint:n=new this.BJSCANNON.LockConstraint(i,r,s);break;case t.PhysicsJoint.PointToPointJoint:case t.PhysicsJoint.BallAndSocketJoint:default:n=new this.BJSCANNON.PointToPointConstraint(i,s.pivotA,r,s.pivotA,s.maxForce)}n.collideConnected=!!o.collision,e.joint.physicsJoint=n,e.joint.type!==t.PhysicsJoint.SpringJoint?this.world.addConstraint(n):e.mainImpostor.registerAfterPhysicsStep((function(){n.applyForce()}))}},i.prototype.removeJoint=function(e){this.world.removeConstraint(e.joint.physicsJoint)},i.prototype._addMaterial=function(e,t,i){var r,n;for(r=0;r1e3*i));a++);this.time+=r;for(var l=this.time%i,h=l/i,c=e,u=this.bodies,f=0;f!==u.length;f++){var d=u[f];d.type!==t.Body.STATIC&&d.sleepState!==t.Body.SLEEPING?(d.position.vsub(d.previousPosition,c),c.scale(h,c),d.position.vadd(c,d.interpolatedPosition)):(d.interpolatedPosition.copy(d.position),d.interpolatedQuaternion.copy(d.quaternion))}}}},i})();t.CannonJSPlugin=i})(r||(r={}));var r;!(function(e){var i=(function(){function i(i){this.name="OimoJSPlugin",this._tmpImpostorsArray=[],this._tmpPositionVector=e.Vector3.Zero(),this.BJSOIMO=t,this.world=new this.BJSOIMO.World({iterations:i}),this.world.clear()}return i.prototype.setGravity=function(e){this.world.gravity.copy(e)},i.prototype.setTimeStep=function(e){this.world.timeStep=e},i.prototype.getTimeStep=function(){return this.world.timeStep},i.prototype.executeStep=function(e,t){var i=this;t.forEach((function(e){e.beforeStep()})),this.world.step(),t.forEach((function(e){e.afterStep(),i._tmpImpostorsArray[e.uniqueId]=e}));for(var r=this.world.contacts;null!==r;)if(!r.touching||r.body1.sleeping||r.body2.sleeping){var n=this._tmpImpostorsArray[+r.body1.name],o=this._tmpImpostorsArray[+r.body2.name];n&&o?(n.onCollide({body:o.physicsBody}),o.onCollide({body:n.physicsBody}),r=r.next):r=r.next}else r=r.next},i.prototype.applyImpulse=function(e,t,i){var r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))},i.prototype.applyForce=function(t,i,r){e.Tools.Warn("Oimo doesn't support applying force. Using impule instead."),this.applyImpulse(t,i,r)},i.prototype.generatePhysicsBody=function(t){var i=this;if(t.parent)return void(t.physicsBody&&(this.removePhysicsBody(t),t.forceUpdate()));if(t.isBodyInitRequired()){var r={name:t.uniqueId,config:[t.getParam("mass")||1,t.getParam("friction"),t.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==t.getParam("mass"),density:t.getParam("mass"),friction:t.getParam("friction"),restitution:t.getParam("restitution"),world:this.world},n=[t];!(function(e){e.getChildMeshes&&e.getChildMeshes().forEach((function(e){e.physicsImpostor&&n.push(e.physicsImpostor)}))})(t.object);var o=function(t){return Math.max(t,e.PhysicsEngine.Epsilon)},s=new e.Quaternion;n.forEach((function(n){if(n.object.rotationQuaternion){var a=n.object.rotationQuaternion;s=a.clone();var l=a.toEulerAngles(),h=n.getObjectExtendSize();if(n===t){var c=t.getObjectCenter();t.object.getAbsolutePivotPoint().subtractToRef(c,i._tmpPositionVector),i._tmpPositionVector.divideInPlace(t.object.scaling),r.pos.push(c.x),r.pos.push(c.y),r.pos.push(c.z),r.posShape.push(0,0,0),r.rot.push(0),r.rot.push(0),r.rot.push(0),r.rotShape.push(0,0,0)}else{var u=n.object.getAbsolutePosition().subtract(t.object.getAbsolutePosition());r.posShape.push(u.x),r.posShape.push(u.y),r.posShape.push(u.z),r.pos.push(0,0,0),r.rot.push(0),r.rot.push(0),r.rot.push(0),r.rotShape.push(57.29577951308232*l.x),r.rotShape.push(57.29577951308232*l.y),r.rotShape.push(57.29577951308232*l.z)}switch(n.type){case e.PhysicsImpostor.ParticleImpostor:e.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case e.PhysicsImpostor.SphereImpostor:var f=h.x,d=h.y,p=h.z,m=Math.max(o(f),o(d),o(p))/2;r.type.push("sphere"),r.size.push(m),r.size.push(m),r.size.push(m);break;case e.PhysicsImpostor.CylinderImpostor:var _=o(h.x)/2,g=o(h.y);r.type.push("cylinder"),r.size.push(_),r.size.push(g),r.size.push(g);break;case e.PhysicsImpostor.PlaneImpostor:case e.PhysicsImpostor.BoxImpostor:default:var _=o(h.x),g=o(h.y),v=o(h.z);r.type.push("box"),r.size.push(_),r.size.push(g),r.size.push(v)}n.object.rotationQuaternion=a}})),t.physicsBody=this.world.add(r),t.physicsBody.resetQuaternion(s),t.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);t.setDeltaPosition(this._tmpPositionVector)},i.prototype.removePhysicsBody=function(e){this.world.removeRigidBody(e.physicsBody)},i.prototype.generateJoint=function(t){var i=t.mainImpostor.physicsBody,r=t.connectedImpostor.physicsBody;if(i&&r){var n,o=t.joint.jointData,s=o.nativeParams||{},a={body1:i,body2:r,axe1:s.axe1||(o.mainAxis?o.mainAxis.asArray():null),axe2:s.axe2||(o.connectedAxis?o.connectedAxis.asArray():null),pos1:s.pos1||(o.mainPivot?o.mainPivot.asArray():null),pos2:s.pos2||(o.connectedPivot?o.connectedPivot.asArray():null),min:s.min,max:s.max,collision:s.collision||o.collision,spring:s.spring,world:this.world};switch(t.joint.type){case e.PhysicsJoint.BallAndSocketJoint:n="jointBall";break;case e.PhysicsJoint.SpringJoint:e.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");var l=o;a.min=l.length||a.min,a.max=Math.max(a.min,a.max);case e.PhysicsJoint.DistanceJoint:n="jointDistance",a.max=o.maxDistance;break;case e.PhysicsJoint.PrismaticJoint:n="jointPrisme";break;case e.PhysicsJoint.SliderJoint:n="jointSlide";break;case e.PhysicsJoint.WheelJoint:n="jointWheel";break;case e.PhysicsJoint.HingeJoint:default:n="jointHinge"}a.type=n,t.joint.physicsJoint=this.world.add(a)}},i.prototype.removeJoint=function(t){try{this.world.removeJoint(t.joint.physicsJoint)}catch(t){e.Tools.Warn(t)}},i.prototype.isSupported=function(){return void 0!==this.BJSOIMO},i.prototype.setTransformationFromPhysicsBody=function(e){e.physicsBody.sleeping||(e.object.position.copyFrom(e.physicsBody.getPosition()),e.object.rotationQuaternion&&e.object.rotationQuaternion.copyFrom(e.physicsBody.getQuaternion()))},i.prototype.setPhysicsBodyTransformation=function(e,t,i){var r=e.physicsBody;r.position.copy(t),r.orientation.copy(i),r.syncShapes(),r.awake()},i.prototype.setLinearVelocity=function(e,t){e.physicsBody.linearVelocity.copy(t)},i.prototype.setAngularVelocity=function(e,t){e.physicsBody.angularVelocity.copy(t)},i.prototype.getLinearVelocity=function(t){var i=t.physicsBody.linearVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},i.prototype.getAngularVelocity=function(t){var i=t.physicsBody.angularVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},i.prototype.setBodyMass=function(e,t){var i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)},i.prototype.getBodyMass=function(e){return e.physicsBody.shapes.density},i.prototype.getBodyFriction=function(e){return e.physicsBody.shapes.friction},i.prototype.setBodyFriction=function(e,t){e.physicsBody.shapes.friction=t},i.prototype.getBodyRestitution=function(e){return e.physicsBody.shapes.restitution},i.prototype.setBodyRestitution=function(e,t){e.physicsBody.shapes.restitution=t},i.prototype.sleepBody=function(e){e.physicsBody.sleep()},i.prototype.wakeUpBody=function(e){e.physicsBody.awake()},i.prototype.updateDistanceJoint=function(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)},i.prototype.setMotor=function(e,t,i,r){var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setMotor(t,i)},i.prototype.setLimit=function(e,t,i,r){var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setLimit(t,void 0===i?-t:i)},i.prototype.syncMeshWithImpostor=function(e,t){var i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.s)},i.prototype.getRadius=function(e){return e.physicsBody.shapes.radius},i.prototype.getBoxSizeToRef=function(e,t){var i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth},i.prototype.dispose=function(){this.world.clear()},i})();e.OimoJSPlugin=i})(r||(r={}));var r;!(function(e){function t(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}function i(e){return String.fromCharCode(255&e,e>>8&255,e>>16&255,e>>24&255)}var r=t("DXT1"),n=t("DXT3"),o=t("DXT5"),s=t("DX10"),a=(function(){function t(){}return t.GetDDSInfo=function(t){var i=new Int32Array(t,0,31),a=new Int32Array(t,0,35),l=1;131072&i[2]&&(l=Math.max(1,i[7]));var h=i[21],c=h===s?a[32]:0,u=e.Engine.TEXTURETYPE_UNSIGNED_INT;switch(h){case 113:u=e.Engine.TEXTURETYPE_HALF_FLOAT;break;case 116:u=e.Engine.TEXTURETYPE_FLOAT;break;case s:if(10===c){u=e.Engine.TEXTURETYPE_HALF_FLOAT;break}}return{width:i[4],height:i[3],mipmapCount:l,isFourCC:4==(4&i[20]),isRGB:64==(64&i[20]),isLuminance:131072==(131072&i[20]),isCube:512==(512&i[28]),isCompressed:h===r||h===n||h===o,dxgiFormat:c,textureType:u}},t._ToHalfFloat=function(e){t._FloatView||(t._FloatView=new Float32Array(1),t._Int32View=new Int32Array(t._FloatView.buffer)),t._FloatView[0]=e;var i=t._Int32View[0],r=i>>16&32768,n=i>>12&2047,o=i>>23&255;return o<103?r:o>142?(r|=31744,r|=(255==o?0:1)&&8388607&i):o<113?(n|=2048,r|=(n>>114-o)+(n>>113-o&1)):(r|=o-112<<10|n>>1,r+=1&n)},t._FromHalfFloat=function(e){var t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(r/Math.pow(2,10)):31==i?r?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+r/Math.pow(2,10))},t._GetHalfFloatAsFloatRGBAArrayBuffer=function(e,i,r,n,o,s){for(var a=new Float32Array(n),l=new Uint16Array(o,r),h=0,c=0;c>8)},t._GetRGBArrayBuffer=function(e,t,i,r,n,o,s,a){for(var l=new Uint8Array(r),h=new Uint8Array(n,i),c=0,u=0;u0?c.sphericalPolynomial=e.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({size:P[4],right:m[0],left:m[1],up:m[2],down:m[3],front:m[4],back:m[5],format:e.Engine.TEXTUREFORMAT_RGBA,type:e.Engine.TEXTURETYPE_FLOAT,gammaSpace:!1}):c.sphericalPolynomial=void 0},t.StoreLODInAlphaChannel=!1,t})();e.DDSTools=a})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.supportCascades=!0}return t.prototype.canLoad=function(e,t,i,r,n){return 0===e.indexOf(".dds")},t.prototype.transformUrl=function(e,t){return e},t.prototype.getFallbackTextureUrl=function(e,t){return null},t.prototype.loadCubeData=function(t,i,r,n,o){var s,a=i.getEngine(),l=!1;if(Array.isArray(t))for(var h=0;h1)&&i.generateMipMaps,a._unpackFlipY(s.isCompressed),e.DDSTools.UploadDDSLevels(a,i,c,s,l,6,-1,h),s.isFourCC||1!==s.mipmapCount||a.generateMipMapsForCubemap(i)}else{var u=t;s=e.DDSTools.GetDDSInfo(u),i.width=s.width,i.height=s.height,r&&(s.sphericalPolynomial=new e.SphericalPolynomial),l=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&i.generateMipMaps,a._unpackFlipY(s.isCompressed),e.DDSTools.UploadDDSLevels(a,i,u,s,l,6),s.isFourCC||1!==s.mipmapCount||a.generateMipMapsForCubemap(i)}a._setCubeMapTextureParams(l),i.isReady=!0,n&&n({isDDS:!0,width:i.width,info:s,data:t,texture:i})},t.prototype.loadData=function(t,i,r){var n=e.DDSTools.GetDDSInfo(t),o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&i.generateMipMaps&&n.width>>n.mipmapCount-1==1;r(n.width,n.height,!o,n.isFourCC,(function(){e.DDSTools.UploadDDSLevels(i.getEngine(),i,t,n,o,1)}))},t})();e.Engine._TextureLoaders.push(new t)})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.GetTGAHeader=function(e){var t=0;return{id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]}},t.UploadContent=function(i,r){if(r.length<19)return void e.Tools.Error("Unable to load TGA file - Not enough data to contain header");var n=18,o=t.GetTGAHeader(r);if(o.id_length+n>r.length)return void e.Tools.Error("Unable to load TGA file - Not enough data");n+=o.id_length;var s=!1,a=!1,l=!1;switch(o.image_type){case t._TYPE_RLE_INDEXED:s=!0;case t._TYPE_INDEXED:a=!0;break;case t._TYPE_RLE_RGB:s=!0;case t._TYPE_RGB:break;case t._TYPE_RLE_GREY:s=!0;case t._TYPE_GREY:l=!0}var h,c,u=o.pixel_size>>3,f=o.width*o.height*u;if(a&&(c=r.subarray(n,n+=o.colormap_length*(o.colormap_size>>3))),s){h=new Uint8Array(f);for(var d,p,m,_=0,g=new Uint8Array(u);n>t._ORIGIN_SHIFT){default:case t._ORIGIN_UL:v=0,b=1,E=o.width,y=0,x=1,T=o.height;break;case t._ORIGIN_BL:v=0,b=1,E=o.width,y=o.height-1,x=-1,T=-1;break;case t._ORIGIN_UR:v=o.width-1,b=-1,E=-1,y=0,x=1,T=o.height;break;case t._ORIGIN_BR:v=o.width-1,b=-1,E=-1,y=o.height-1,x=-1,T=-1}var P="_getImageData"+(l?"Grey":"")+o.pixel_size+"bits",A=t[P](o,c,h,y,x,T,v,b,E);i.getEngine()._uploadDataToTextureDirectly(i,A)},t._getImageData8bits=function(e,t,i,r,n,o,s,a,l){var h,c,u,f=i,d=t,p=e.width,m=e.height,_=0,g=new Uint8Array(p*m*4);for(u=r;u!==o;u+=n)for(c=s;c!==l;c+=a,_++)h=f[_],g[4*(c+p*u)+3]=255,g[4*(c+p*u)+2]=d[3*h+0],g[4*(c+p*u)+1]=d[3*h+1],g[4*(c+p*u)+0]=d[3*h+2];return g},t._getImageData16bits=function(e,t,i,r,n,o,s,a,l){var h,c,u,f=i,d=e.width,p=e.height,m=0,_=new Uint8Array(d*p*4);for(u=r;u!==o;u+=n)for(c=s;c!==l;c+=a,m+=2){h=f[m+0]+(f[m+1]<<8);var g=255*((31744&h)>>10)/31|0,v=255*((992&h)>>5)/31|0,y=255*(31&h)/31|0;_[4*(c+d*u)+0]=g,_[4*(c+d*u)+1]=v,_[4*(c+d*u)+2]=y,_[4*(c+d*u)+3]=32768&h?0:255}return _},t._getImageData24bits=function(e,t,i,r,n,o,s,a,l){var h,c,u=i,f=e.width,d=e.height,p=0,m=new Uint8Array(f*d*4);for(c=r;c!==o;c+=n)for(h=s;h!==l;h+=a,p+=3)m[4*(h+f*c)+3]=255,m[4*(h+f*c)+2]=u[p+0],m[4*(h+f*c)+1]=u[p+1],m[4*(h+f*c)+0]=u[p+2];return m},t._getImageData32bits=function(e,t,i,r,n,o,s,a,l){var h,c,u=i,f=e.width,d=e.height,p=0,m=new Uint8Array(f*d*4);for(c=r;c!==o;c+=n)for(h=s;h!==l;h+=a,p+=4)m[4*(h+f*c)+2]=u[p+0],m[4*(h+f*c)+1]=u[p+1],m[4*(h+f*c)+0]=u[p+2],m[4*(h+f*c)+3]=u[p+3];return m},t._getImageDataGrey8bits=function(e,t,i,r,n,o,s,a,l){var h,c,u,f=i,d=e.width,p=e.height,m=0,_=new Uint8Array(d*p*4);for(u=r;u!==o;u+=n)for(c=s;c!==l;c+=a,m++)h=f[m],_[4*(c+d*u)+0]=h,_[4*(c+d*u)+1]=h,_[4*(c+d*u)+2]=h,_[4*(c+d*u)+3]=255;return _},t._getImageDataGrey16bits=function(e,t,i,r,n,o,s,a,l){var h,c,u=i,f=e.width,d=e.height,p=0,m=new Uint8Array(f*d*4);for(c=r;c!==o;c+=n)for(h=s;h!==l;h+=a,p+=2)m[4*(h+f*c)+0]=u[p+0],m[4*(h+f*c)+1]=u[p+0],m[4*(h+f*c)+2]=u[p+0],m[4*(h+f*c)+3]=u[p+1];return m},t._TYPE_INDEXED=1,t._TYPE_RGB=2,t._TYPE_GREY=3,t._TYPE_RLE_INDEXED=9,t._TYPE_RLE_RGB=10,t._TYPE_RLE_GREY=11,t._ORIGIN_MASK=48,t._ORIGIN_SHIFT=4,t._ORIGIN_BL=0,t._ORIGIN_BR=1,t._ORIGIN_UL=2,t._ORIGIN_UR=3,t})();e.TGATools=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.supportCascades=!1}return t.prototype.canLoad=function(e,t,i,r,n){return 0===e.indexOf(".tga")},t.prototype.transformUrl=function(e,t){return e},t.prototype.getFallbackTextureUrl=function(e,t){return null},t.prototype.loadCubeData=function(e,t,i,r,n){throw".env not supported in Cube."},t.prototype.loadData=function(t,i,r){var n=new Uint8Array(t),o=e.TGATools.GetTGAHeader(n);r(o.width,o.height,i.generateMipMaps,!1,(function(){e.TGATools.UploadContent(i,n)}))},t})();e.Engine._TextureLoaders.push(new t)})(r||(r={}));var r;!(function(e){var t=(function(){function t(i,r,n,o){this.arrayBuffer=i;var s=new Uint8Array(this.arrayBuffer,0,12);if(171!==s[0]||75!==s[1]||84!==s[2]||88!==s[3]||32!==s[4]||49!==s[5]||49!==s[6]||187!==s[7]||13!==s[8]||10!==s[9]||26!==s[10]||10!==s[11])return void e.Tools.Error("texture missing KTX identifier");var a=new Int32Array(this.arrayBuffer,12,13),l=16909060===a[0];return this.glType=l?this.switchEndainness(a[1]):a[1],this.glTypeSize=l?this.switchEndainness(a[2]):a[2],this.glFormat=l?this.switchEndainness(a[3]):a[3],this.glInternalFormat=l?this.switchEndainness(a[4]):a[4],this.glBaseInternalFormat=l?this.switchEndainness(a[5]):a[5],this.pixelWidth=l?this.switchEndainness(a[6]):a[6],this.pixelHeight=l?this.switchEndainness(a[7]):a[7],this.pixelDepth=l?this.switchEndainness(a[8]):a[8],this.numberOfArrayElements=l?this.switchEndainness(a[9]):a[9], +this.numberOfFaces=l?this.switchEndainness(a[10]):a[10],this.numberOfMipmapLevels=l?this.switchEndainness(a[11]):a[11],this.bytesOfKeyValueData=l?this.switchEndainness(a[12]):a[12],0!==this.glType?void e.Tools.Error("only compressed formats currently supported"):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?void e.Tools.Error("only 2D textures currently supported"):0!==this.numberOfArrayElements?void e.Tools.Error("texture arrays not currently supported"):this.numberOfFaces!==r?void e.Tools.Error("number of faces expected"+r+", but found "+this.numberOfFaces):void(this.loadType=t.COMPRESSED_2D))}return t.prototype.switchEndainness=function(e){return(255&e)<<24|(65280&e)<<8|e>>8&65280|e>>24&255},t.prototype.uploadLevels=function(e,i){switch(this.loadType){case t.COMPRESSED_2D:this._upload2DCompressedLevels(e,i);break;case t.TEX_2D:case t.COMPRESSED_3D:case t.TEX_3D:}},t.prototype._upload2DCompressedLevels=function(e,i){for(var r=t.HEADER_LEN+this.bytesOfKeyValueData,n=this.pixelWidth,o=this.pixelHeight,s=i?this.numberOfMipmapLevels:1,a=0;a-1?e.substring(0,i):e)+t},t.prototype.getFallbackTextureUrl=function(e,t){var i=new RegExp(t+"$");return e.replace(i,"")},t.prototype.loadCubeData=function(t,i,r,n,o){if(!Array.isArray(t)){var s=i.getEngine(),a=new e.KhronosTextureContainer(t,6),l=a.numberOfMipmapLevels>1&&i.generateMipMaps;s._unpackFlipY(!0),a.uploadLevels(i,i.generateMipMaps),i.width=a.pixelWidth,i.height=a.pixelHeight,s._setCubeMapTextureParams(l),i.isReady=!0}},t.prototype.loadData=function(t,i,r){var n=new e.KhronosTextureContainer(t,1);r(n.pixelWidth,n.pixelHeight,!1,!0,(function(){n.uploadLevels(i,i.generateMipMaps)}))},t})();e.Engine._TextureLoaders.unshift(new t)})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.GetEnvInfo=function(i){for(var r=new DataView(i),n=0,o=0;o0)):!i._pointerCaptures[l.pointerId]&&s.distance>a.distance&&(i.mainSceneTrackerPredicate&&i.mainSceneTrackerPredicate(a.pickedMesh)?(i._notifyObservers(r,a,l),r.skipOnPointerObservable=!0):i._lastPointerEvents[l.pointerId]&&(i.onPointerOutObservable.notifyObservers(l.pointerId),delete i._lastPointerEvents[l.pointerId])),r.type===e.PointerEventTypes.POINTERUP&&i._pointerCaptures[l.pointerId]&&(i._pointerCaptures[l.pointerId]=!1))}}})),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderObservable.add((function(){i.shouldRender&&i.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((function(){i.dispose()})),this._updateCamera()}return Object.defineProperty(t,"DefaultUtilityLayer",{get:function(){return null==t._DefaultUtilityLayer&&(t._DefaultUtilityLayer=new t(e.Engine.LastCreatedScene),t._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((function(){t._DefaultUtilityLayer=null}))),t._DefaultUtilityLayer},enumerable:!0,configurable:!0}),Object.defineProperty(t,"DefaultKeepDepthUtilityLayer",{get:function(){return null==t._DefaultKeepDepthUtilityLayer&&(t._DefaultKeepDepthUtilityLayer=new t(e.Engine.LastCreatedScene),t._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,t._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((function(){t._DefaultKeepDepthUtilityLayer=null}))),t._DefaultKeepDepthUtilityLayer},enumerable:!0,configurable:!0}),t.prototype._notifyObservers=function(t,i,r){t.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new e.PointerInfo(t.type,t.event,i)),this._lastPointerEvents[r.pointerId]=r.pointerType)},t.prototype.render=function(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){var e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}},t.prototype.dispose=function(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()},t.prototype._updateCamera=function(){this.utilityLayerScene.activeCamera=this.originalScene.activeCamera},t._DefaultUtilityLayer=null,t._DefaultKeepDepthUtilityLayer=null,t})();e.UtilityLayerRenderer=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){this.maxDragAngle=0,this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerID=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new e.Observable,this.onDragStartObservable=new e.Observable,this.onDragEndObservable=new e.Observable,this.moveAttached=!0,this.enabled=!0,this.detachCameraControls=!0,this.useObjectOrienationForDragging=!0,this._tmpVector=new e.Vector3(0,0,0),this._alternatePickedPoint=new e.Vector3(0,0,0),this._worldDragAxis=new e.Vector3(0,0,0),this._pointA=new e.Vector3(0,0,0),this._pointB=new e.Vector3(0,0,0),this._pointC=new e.Vector3(0,0,0),this._lineA=new e.Vector3(0,0,0),this._lineB=new e.Vector3(0,0,0),this._localAxis=new e.Vector3(0,0,0),this._lookAt=new e.Vector3(0,0,0),this._options=t||{};var i=0;if(this._options.dragAxis&&i++,this._options.dragPlaneNormal&&i++,i>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}return Object.defineProperty(t.prototype,"name",{get:function(){return"PointerDrag"},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(i){var r=this;this._scene=i.getScene(),this._attachedNode=i,t._planeScene||(this._debugMode?t._planeScene=this._scene:(t._planeScene=new e.Scene(this._scene.getEngine()),t._planeScene.detachControl(),this._scene.getEngine().scenes.pop(),this._scene.onDisposeObservable.addOnce((function(){t._planeScene.dispose(),t._planeScene=null})))),this._dragPlane=e.Mesh.CreatePlane("pointerDragPlane",this._debugMode?1:1e4,t._planeScene,!1,e.Mesh.DOUBLESIDE),this.lastDragPosition=new e.Vector3(0,0,0);var n=new e.Vector3(0,0,0),o=0,s=new e.Vector3(0,0,0),a=function(e){return r._attachedNode==e||e.isDescendantOf(r._attachedNode)},l=null;this._pointerObserver=this._scene.onPointerObservable.add((function(t,i){if(r.enabled)if(t.type==e.PointerEventTypes.POINTERDOWN){if(!r.dragging&&t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh&&t.pickInfo.pickedPoint&&t.pickInfo.ray&&a(t.pickInfo.pickedMesh)){r._updateDragPlanePosition(t.pickInfo.ray,t.pickInfo.pickedPoint);var h=r._pickWithRayOnDragPlane(t.pickInfo.ray);h&&(r.dragging=!0,r.currentDraggingPointerID=t.event.pointerId,r.lastDragPosition.copyFrom(h),r.onDragStartObservable.notifyObservers({dragPlanePoint:h,pointerId:r.currentDraggingPointerID}),s.copyFrom(r._attachedNode.absolutePosition),r.detachCameraControls&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&(r._scene.activeCamera.inputs.attachedElement?(l=r._scene.activeCamera.inputs.attachedElement,r._scene.activeCamera.detachControl(r._scene.activeCamera.inputs.attachedElement)):l=null))}}else if(t.type==e.PointerEventTypes.POINTERUP)r.currentDraggingPointerID==t.event.pointerId&&(r.releaseDrag(),r.detachCameraControls&&l&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&r._scene.activeCamera.attachControl(l,!0));else if(t.type==e.PointerEventTypes.POINTERMOVE&&r.currentDraggingPointerID==t.event.pointerId&&r.dragging&&t.pickInfo&&t.pickInfo.ray){r._moving=!0;var h=r._pickWithRayOnDragPlane(t.pickInfo.ray);h&&(r.updateDragPlane&&r._updateDragPlanePosition(t.pickInfo.ray,h),r._options.dragAxis?(e.Vector3.TransformCoordinatesToRef(r._options.dragAxis,r._attachedNode.getWorldMatrix().getRotationMatrix(),r._worldDragAxis),h.subtractToRef(r.lastDragPosition,r._tmpVector),o=e.Vector3.Dot(r._tmpVector,r._worldDragAxis),r._worldDragAxis.scaleToRef(o,n)):(o=n.length(),h.subtractToRef(r.lastDragPosition,n)),s.addInPlace(n),r.onDragObservable.notifyObservers({dragDistance:o,delta:n,dragPlanePoint:h,dragPlaneNormal:r._dragPlane.forward,pointerId:r.currentDraggingPointerID}),r.lastDragPosition.copyFrom(h))}})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((function(){r._moving&&r.moveAttached&&(s.subtractToRef(r._attachedNode.absolutePosition,r._tmpVector),r._tmpVector.scaleInPlace(.2),r._attachedNode.getAbsolutePosition().addToRef(r._tmpVector,r._tmpVector),r._attachedNode.setAbsolutePosition(r._tmpVector))}))},t.prototype.releaseDrag=function(){this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerID}),this.currentDraggingPointerID=-1,this._moving=!1},t.prototype._pickWithRayOnDragPlane=function(i){var r=this;if(!i)return null;var n=Math.acos(e.Vector3.Dot(this._dragPlane.forward,i.direction));if(n>Math.PI/2&&(n=Math.PI-n),this.maxDragAngle>0&&n>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(i.direction),this._attachedNode.absolutePosition.subtractToRef(i.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(-2*e.Vector3.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);var o=e.Vector3.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-o,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition),this._alternatePickedPoint}return null}var s=t._planeScene.pickWithRay(i,(function(e){return e==r._dragPlane}));return s&&s.hit&&s.pickedMesh&&s.pickedPoint?s.pickedPoint:null},t.prototype._updateDragPlanePosition=function(t,i){this._pointA.copyFrom(i),this._options.dragAxis?(this.useObjectOrienationForDragging?e.Vector3.TransformCoordinatesToRef(this._options.dragAxis,this._attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),this._pointA.addToRef(this._localAxis,this._pointB),t.origin.subtractToRef(this._pointA,this._pointC),this._pointA.addToRef(this._pointC.normalize(),this._pointC),this._pointB.subtractToRef(this._pointA,this._lineA),this._pointC.subtractToRef(this._pointA,this._lineB),e.Vector3.CrossToRef(this._lineA,this._lineB,this._lookAt),e.Vector3.CrossToRef(this._lineA,this._lookAt,this._lookAt),this._lookAt.normalize(),this._dragPlane.position.copyFrom(this._pointA),this._pointA.subtractToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrienationForDragging?e.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal,this._attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.subtractToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(t.origin)),this._dragPlane.computeWorldMatrix(!0)},t.prototype.detach=function(){this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver)},t})();e.PointerDragBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._startDistance=0,this._initialScale=new e.Vector3(0,0,0),this._targetScale=new e.Vector3(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new e.PointerDragBehavior({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new e.PointerDragBehavior({}),this._dragBehaviorB.moveAttached=!1}return Object.defineProperty(t.prototype,"name",{get:function(){return"MultiPointerScale"},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype._getCurrentDistance=function(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()},t.prototype.attach=function(e){var t=this;this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add((function(i){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerID==t._dragBehaviorB.currentDraggingPointerID?t._dragBehaviorA.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))})),this._dragBehaviorB.onDragStartObservable.add((function(i){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerID==t._dragBehaviorB.currentDraggingPointerID?t._dragBehaviorB.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))})),[this._dragBehaviorA,this._dragBehaviorB].forEach((function(e){e.onDragObservable.add((function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var e=t._getCurrentDistance()/t._startDistance;t._initialScale.scaleToRef(e,t._targetScale)}}))})),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var i=t._targetScale.subtract(e.scaling).scaleInPlace(.1);i.length()>.01&&e.scaling.addInPlace(i)}}))},t.prototype.detach=function(){var e=this;this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach((function(t){t.onDragStartObservable.clear(),t.onDragObservable.clear(),e._ownerNode.removeBehavior(t)}))},t})();e.MultiPointerScaleBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._sceneRenderObserver=null,this._targetPosition=new e.Vector3(0,0,0),this._moving=!1,this._startingOrientation=new e.Quaternion,this.zDragFactor=3,this.dragging=!1,this.dragDeltaRatio=.2,this.currentDraggingPointerID=-1,this.detachCameraControls=!0}return Object.defineProperty(t.prototype,"name",{get:function(){return"SixDofDrag"},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(i){var r=this;this._ownerNode=i,this._scene=this._ownerNode.getScene(),t._virtualScene||(t._virtualScene=new e.Scene(this._scene.getEngine()),this._scene.getEngine().scenes.pop());var n=null,o=new e.Vector3(0,0,0);this._virtualOriginMesh=new e.AbstractMesh("",t._virtualScene),this._virtualOriginMesh.rotationQuaternion=new e.Quaternion,this._virtualDragMesh=new e.AbstractMesh("",t._virtualScene),this._virtualDragMesh.rotationQuaternion=new e.Quaternion;var s=function(e){return r._ownerNode==e||e.isDescendantOf(r._ownerNode)},a=null;this._pointerObserver=this._scene.onPointerObservable.add((function(t,i){if(t.type==e.PointerEventTypes.POINTERDOWN){if(!r.dragging&&t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh&&t.pickInfo.ray&&s(t.pickInfo.pickedMesh)){r._scene.activeCamera&&r._scene.activeCamera.cameraRigMode==e.Camera.RIG_MODE_NONE&&t.pickInfo.ray.origin.copyFrom(r._scene.activeCamera.position),n=r._ownerNode,o.copyFrom(t.pickInfo.ray.origin),r._virtualOriginMesh.position.copyFrom(t.pickInfo.ray.origin),r._virtualOriginMesh.lookAt(t.pickInfo.ray.origin.subtract(t.pickInfo.ray.direction)),r._virtualOriginMesh.removeChild(r._virtualDragMesh),r._virtualDragMesh.position.copyFrom(n.absolutePosition),n.rotationQuaternion||(n.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(n.rotation.y,n.rotation.x,n.rotation.z));var l=n.parent;n.setParent(null),r._virtualDragMesh.rotationQuaternion.copyFrom(n.rotationQuaternion),n.setParent(l),r._virtualOriginMesh.addChild(r._virtualDragMesh),r._targetPosition.copyFrom(r._virtualDragMesh.absolutePosition),r.dragging=!0,r.currentDraggingPointerID=t.event.pointerId,r.detachCameraControls&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&(r._scene.activeCamera.inputs.attachedElement?(a=r._scene.activeCamera.inputs.attachedElement,r._scene.activeCamera.detachControl(r._scene.activeCamera.inputs.attachedElement)):a=null)}}else if(t.type==e.PointerEventTypes.POINTERUP)r.currentDraggingPointerID==t.event.pointerId&&(r.dragging=!1,r._moving=!1,r.currentDraggingPointerID=-1,n=null,r._virtualOriginMesh.removeChild(r._virtualDragMesh),r.detachCameraControls&&a&&r._scene.activeCamera&&!r._scene.activeCamera.leftCamera&&r._scene.activeCamera.attachControl(a,!0));else if(t.type==e.PointerEventTypes.POINTERMOVE&&r.currentDraggingPointerID==t.event.pointerId&&r.dragging&&t.pickInfo&&t.pickInfo.ray&&n){var h=r.zDragFactor;r._scene.activeCamera&&r._scene.activeCamera.cameraRigMode==e.Camera.RIG_MODE_NONE&&(t.pickInfo.ray.origin.copyFrom(r._scene.activeCamera.position),h=0);var c=t.pickInfo.ray.origin.subtract(o);o.copyFrom(t.pickInfo.ray.origin);var u=-e.Vector3.Dot(c,t.pickInfo.ray.direction);r._virtualOriginMesh.addChild(r._virtualDragMesh),r._virtualDragMesh.position.z-=r._virtualDragMesh.position.z<1?u*r.zDragFactor:u*h*r._virtualDragMesh.position.z,r._virtualDragMesh.position.z<0&&(r._virtualDragMesh.position.z=0),r._virtualOriginMesh.position.copyFrom(t.pickInfo.ray.origin),r._virtualOriginMesh.lookAt(t.pickInfo.ray.origin.subtract(t.pickInfo.ray.direction)),r._virtualOriginMesh.removeChild(r._virtualDragMesh),r._targetPosition.copyFrom(r._virtualDragMesh.absolutePosition),n.parent&&e.Vector3.TransformCoordinatesToRef(r._targetPosition,e.Matrix.Invert(n.parent.getWorldMatrix()),r._targetPosition),r._moving||r._startingOrientation.copyFrom(r._virtualDragMesh.rotationQuaternion),r._moving=!0}}));var l=new e.Quaternion;this._sceneRenderObserver=i.getScene().onBeforeRenderObservable.add((function(){if(r.dragging&&r._moving&&n){n.position.addInPlace(r._targetPosition.subtract(n.position).scale(r.dragDeltaRatio)),l.copyFrom(r._startingOrientation),l.x=-l.x,l.y=-l.y,l.z=-l.z,r._virtualDragMesh.rotationQuaternion.multiplyToRef(l,l),e.Quaternion.RotationYawPitchRollToRef(l.toEulerAngles("xyz").y,0,0,l),l.multiplyToRef(r._startingOrientation,l);var t=n.parent;n.setParent(null),e.Quaternion.SlerpToRef(n.rotationQuaternion,l,r.dragDeltaRatio,n.rotationQuaternion),n.setParent(t)}}))},t.prototype.detach=function(){this._scene&&this._scene.onPointerObservable.remove(this._pointerObserver),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualOriginMesh&&this._virtualOriginMesh.dispose(),this._virtualDragMesh&&this._virtualDragMesh.dispose()},t})();e.SixDofDragBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r,n){void 0===i&&(i=new e.Vector3),void 0===r&&(r=0),void 0===n&&(n=!1),this.direction=t,this.rotatedDirection=i,this.diff=r,this.ignore=n}return t})(),i=(function(){function i(i){this.ui=i,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new t(e.Vector3.Up()),new t(e.Vector3.Down()),new t(e.Vector3.Left()),new t(e.Vector3.Right()),new t(e.Vector3.Forward()),new t(e.Vector3.Forward().scaleInPlace(-1))],this._tmpMatrix=new e.Matrix,this._tmpVector=new e.Vector3,this._zeroVector=e.Vector3.Zero(),this._lookAtTmpMatrix=new e.Matrix}return i.prototype.init=function(){},i.prototype._closestFace=function(t){var i=this;return this._faceVectors.forEach((function(r){i._target.rotationQuaternion||(i._target.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(i._target.rotation.y,i._target.rotation.x,i._target.rotation.z)),i._target.rotationQuaternion.toRotationMatrix(i._tmpMatrix),e.Vector3.TransformCoordinatesToRef(r.direction,i._tmpMatrix,r.rotatedDirection),r.diff=e.Vector3.GetAngleBetweenVectors(r.rotatedDirection,t,e.Vector3.Cross(r.rotatedDirection,t))})),this._faceVectors.reduce((function(e,t){return e.ignore?t:t.ignore?e:e.diffo.snapDistance){var t=Math.floor(Math.abs(u)/o.snapDistance);u%=o.snapDistance,e.delta.normalizeToRef(f),f.scaleInPlace(o.snapDistance*t),o.attachedMesh.position.addInPlace(f),d.snapDistance=o.snapDistance*t,o.onSnapObservable.notifyObservers(d)}})),o._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e,t){if(!o._customMeshSet){var i=e.pickInfo&&-1!=o._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh),r=i?a:s;o._rootMesh.getChildMeshes().forEach((function(e){e.material=r,e.color&&(e.color=r.emissiveColor)}))}})),o}return o(i,t),i.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),t.prototype.dispose.call(this)},i})(e.Gizmo);e.AxisDragGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n){void 0===r&&(r=e.Color3.Gray()),void 0===n&&(n=e.UtilityLayerRenderer.DefaultUtilityLayer);var o=t.call(this,n)||this;o._pointerObserver=null,o.snapDistance=0,o.onSnapObservable=new e.Observable;var s=new e.StandardMaterial("",n.utilityLayerScene);s.disableLighting=!0,s.emissiveColor=r;var a=new e.StandardMaterial("",n.utilityLayerScene);a.disableLighting=!0,a.emissiveColor=r.add(new e.Color3(.2,.2,.2));var l=new e.AbstractMesh("",n.utilityLayerScene),h=e.MeshBuilder.CreateBox("yPosMesh",{size:.4},n.utilityLayerScene),c=e.MeshBuilder.CreateLines("yPosMesh",{points:[new e.Vector3(0,0,0),new e.Vector3(0,1.5,0)]},n.utilityLayerScene);c.color=s.emissiveColor,l.addChild(h),l.addChild(c),h.scaling.scaleInPlace(.1),h.material=s,h.rotation.x=Math.PI/2,h.position.z+=.3,c.scaling.scaleInPlace(.2),c.rotation.x=Math.PI/2,c.material=s,l.lookAt(o._rootMesh.position.subtract(i)),o._rootMesh.addChild(l),o.dragBehavior=new e.PointerDragBehavior({dragAxis:i}),o.dragBehavior.moveAttached=!1,o._rootMesh.addBehavior(o.dragBehavior);var u=0,f=new e.Vector3,d={snapDistance:0};return o.dragBehavior.onDragObservable.add((function(e){if(o.attachedMesh){var t=!1,r=0;0==o.snapDistance?i.scaleToRef(e.dragDistance,f):(u+=e.dragDistance,Math.abs(u)>o.snapDistance?(r=Math.floor(u/o.snapDistance),u%=o.snapDistance,i.scaleToRef(o.snapDistance*r,f),t=!0):f.scaleInPlace(0)),o.attachedMesh.scaling.addInPlace(f),t&&(d.snapDistance=o.snapDistance*r,o.onSnapObservable.notifyObservers(d))}})),o._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e,t){if(!o._customMeshSet){var i=e.pickInfo&&-1!=o._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh),r=i?a:s;o._rootMesh.getChildMeshes().forEach((function(e){e.material=r,e.color&&(e.color=r.emissiveColor)}))}})),o}return o(i,t),i.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),t.prototype.dispose.call(this)},i})(e.Gizmo);e.AxisScaleGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n){void 0===r&&(r=e.Color3.Gray()),void 0===n&&(n=e.UtilityLayerRenderer.DefaultUtilityLayer);var o=t.call(this,n)||this;o._pointerObserver=null,o.snapDistance=0,o.onSnapObservable=new e.Observable;var s=new e.StandardMaterial("",n.utilityLayerScene);s.disableLighting=!0,s.emissiveColor=r;var a=new e.StandardMaterial("",n.utilityLayerScene);a.disableLighting=!0,a.emissiveColor=r.add(new e.Color3(.2,.2,.2));for(var l=new e.AbstractMesh("",n.utilityLayerScene),h=new Array,c=0;c<20;c++){var u=2*Math.PI*(c/19);h.push(new e.Vector3(2*Math.sin(u),0,2*Math.cos(u)))}var f=e.Mesh.CreateLines("",h,n.utilityLayerScene);f.color=s.emissiveColor,f.scaling.scaleInPlace(.1),f.material=s,f.rotation.x=Math.PI/2,l.addChild(f),l.lookAt(o._rootMesh.position.subtract(i)),o._rootMesh.addChild(l),o.dragBehavior=new e.PointerDragBehavior({dragPlaneNormal:i}),o.dragBehavior.moveAttached=!1,o.dragBehavior.maxDragAngle=9*Math.PI/20,o.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,o._rootMesh.addBehavior(o.dragBehavior);var d=new e.Vector3;o.dragBehavior.onDragStartObservable.add((function(e){o.attachedMesh&&d.copyFrom(e.dragPlanePoint)}));var p=new e.Matrix,m=new e.Vector3,_=new e.Vector3,g={snapDistance:0},v=0;return o.dragBehavior.onDragObservable.add((function(t){if(o.attachedMesh){o.attachedMesh.rotationQuaternion||(o.attachedMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(o.attachedMesh.rotation.y,o.attachedMesh.rotation.x,o.attachedMesh.rotation.z));var r=t.dragPlanePoint.subtract(o.attachedMesh.position).normalize(),s=d.subtract(o.attachedMesh.position).normalize(),a=e.Vector3.Cross(r,s),l=e.Vector3.Dot(r,s),h=Math.atan2(a.length(),l);if(m.copyFrom(i),_.copyFrom(i),o.updateGizmoRotationToMatchAttachedMesh&&(o.attachedMesh.rotationQuaternion.toRotationMatrix(p),_=e.Vector3.TransformCoordinates(m,p)),n.utilityLayerScene.activeCamera){var c=n.utilityLayerScene.activeCamera.position.subtract(o.attachedMesh.position);e.Vector3.Dot(c,_)>0&&(m.scaleInPlace(-1),_.scaleInPlace(-1))}e.Vector3.Dot(_,a)>0&&(h=-h);var u=!1;if(0!=o.snapDistance)if(v+=h,Math.abs(v)>o.snapDistance){var f=Math.floor(v/o.snapDistance);v%=o.snapDistance,h=o.snapDistance*f,u=!0}else h=0;var y=Math.sin(h/2),b=new e.Quaternion(m.x*y,m.y*y,m.z*y,Math.cos(h/2));o.updateGizmoRotationToMatchAttachedMesh?o.attachedMesh.rotationQuaternion.multiplyToRef(b,o.attachedMesh.rotationQuaternion):b.multiplyToRef(o.attachedMesh.rotationQuaternion,o.attachedMesh.rotationQuaternion),d.copyFrom(t.dragPlanePoint),u&&(g.snapDistance=h,o.onSnapObservable.notifyObservers(g))}})),o._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e,t){if(!o._customMeshSet){var i=e.pickInfo&&-1!=o._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh),r=i?a:s;o._rootMesh.getChildMeshes().forEach((function(e){e.material=r,e.color&&(e.color=r.emissiveColor)}))}})),o}return o(i,t),i.prototype._attachedMeshChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),t.prototype.dispose.call(this)},i})(e.Gizmo);e.PlaneRotationGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i){void 0===i&&(i=e.UtilityLayerRenderer.DefaultUtilityLayer);var r=t.call(this,i)||this;return r.xGizmo=new e.AxisDragGizmo(new e.Vector3(1,0,0),e.Color3.Green().scale(.5),i),r.yGizmo=new e.AxisDragGizmo(new e.Vector3(0,1,0),e.Color3.Red().scale(.5),i),r.zGizmo=new e.AxisDragGizmo(new e.Vector3(0,0,1),e.Color3.Blue().scale(.5),i),r.attachedMesh=null,r}return o(i,t),Object.defineProperty(i.prototype,"attachedMesh",{set:function(e){this.xGizmo&&(this.xGizmo.attachedMesh=e,this.yGizmo.attachedMesh=e,this.zGizmo.attachedMesh=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!0,configurable:!0}),i.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose()},i.prototype.setCustomMesh=function(t){e.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")},i})(e.Gizmo);e.PositionGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i){void 0===i&&(i=e.UtilityLayerRenderer.DefaultUtilityLayer);var r=t.call(this,i)||this;return r.xGizmo=new e.PlaneRotationGizmo(new e.Vector3(1,0,0),e.Color3.Green().scale(.5),i),r.yGizmo=new e.PlaneRotationGizmo(new e.Vector3(0,1,0),e.Color3.Red().scale(.5),i),r.zGizmo=new e.PlaneRotationGizmo(new e.Vector3(0,0,1),e.Color3.Blue().scale(.5),i),r.attachedMesh=null,r}return o(i,t),Object.defineProperty(i.prototype,"attachedMesh",{set:function(e){this.xGizmo&&(this.xGizmo.attachedMesh=e,this.yGizmo.attachedMesh=e,this.zGizmo.attachedMesh=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!0,configurable:!0}),i.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose()},i.prototype.setCustomMesh=function(t){e.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")},i})(e.Gizmo);e.RotationGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i){void 0===i&&(i=e.UtilityLayerRenderer.DefaultUtilityLayer);var r=t.call(this,i)||this;return r.xGizmo=new e.AxisScaleGizmo(new e.Vector3(1,0,0),e.Color3.Green().scale(.5),i),r.yGizmo=new e.AxisScaleGizmo(new e.Vector3(0,1,0),e.Color3.Red().scale(.5),i),r.zGizmo=new e.AxisScaleGizmo(new e.Vector3(0,0,1),e.Color3.Blue().scale(.5),i),r.attachedMesh=null,r}return o(i,t),Object.defineProperty(i.prototype,"attachedMesh",{set:function(e){this.xGizmo&&(this.xGizmo.attachedMesh=e,this.yGizmo.attachedMesh=e,this.zGizmo.attachedMesh=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!0,configurable:!0}),i.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose()},i})(e.Gizmo);e.ScaleGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r){void 0===i&&(i=e.Color3.Gray()),void 0===r&&(r=e.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer);var n=t.call(this,r)||this;n._boundingDimensions=new e.Vector3(1,1,1),n._renderObserver=null,n._pointerObserver=null,n._scaleDragSpeed=.2,n._tmpQuaternion=new e.Quaternion,n._tmpVector=new e.Vector3(0,0,0),n.rotationSphereSize=.1,n.scaleBoxSize=.1,n.fixedDragMeshScreenSize=!1,n.fixedDragMeshScreenSizeDistanceFactor=10,n.onDragStartObservable=new e.Observable,n.onDragObservable=new e.Observable,n.onDragEndObservable=new e.Observable,n._existingMeshScale=new e.Vector3,n._updateScale=!1,n._anchorMesh=new e.AbstractMesh("anchor",r.utilityLayerScene);var o=new e.StandardMaterial("",r.utilityLayerScene);o.disableLighting=!0,o.emissiveColor=i;var s=new e.StandardMaterial("",r.utilityLayerScene);s.disableLighting=!0,s.emissiveColor=i.clone().add(new e.Color3(.2,.2,.2)),n._lineBoundingBox=new e.AbstractMesh("",r.utilityLayerScene),n._lineBoundingBox.rotationQuaternion=new e.Quaternion;var a=[];a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,0),new e.Vector3(n._boundingDimensions.x,0,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,0),new e.Vector3(0,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,0),new e.Vector3(0,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,0,0),new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,0,0),new e.Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,n._boundingDimensions.y,0),new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,n._boundingDimensions.y,0),new e.Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,n._boundingDimensions.z),new e.Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(0,0,n._boundingDimensions.z),new e.Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new e.Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new e.Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]},r.utilityLayerScene)),a.push(e.MeshBuilder.CreateLines("lines",{points:[new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new e.Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]},r.utilityLayerScene)),a.forEach((function(t){t.color=i,t.position.addInPlace(new e.Vector3(-n._boundingDimensions.x/2,-n._boundingDimensions.y/2,-n._boundingDimensions.z/2)),t.isPickable=!1,n._lineBoundingBox.addChild(t)})),n._rootMesh.addChild(n._lineBoundingBox),n._rotateSpheresParent=new e.AbstractMesh("",r.utilityLayerScene),n._rotateSpheresParent.rotationQuaternion=new e.Quaternion;for(var l,h=this,c=0;c<12;c++)!(function(t){var i=e.MeshBuilder.CreateSphere("",{diameter:1},r.utilityLayerScene);i.rotationQuaternion=new e.Quaternion,i.material=o,l=new e.PointerDragBehavior({}),l.moveAttached=!1,l.updateDragPlane=!1,i.addBehavior(l);var s=new e.Vector3(1,0,0),a=0;l.onDragStartObservable.add((function(e){s.copyFrom(i.forward),a=0})),l.onDragObservable.add((function(i){if(n.onDragObservable.notifyObservers({}),n.attachedMesh){var r=s,o=i.dragPlaneNormal.scale(e.Vector3.Dot(i.dragPlaneNormal,r)),l=r.subtract(o).normalizeToNew(),h=-e.Vector3.Dot(l,i.delta);h=h/n._boundingDimensions.length()*n._anchorMesh.scaling.length(),n.attachedMesh.rotationQuaternion||(n.attachedMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(n.attachedMesh.rotation.y,n.attachedMesh.rotation.x,n.attachedMesh.rotation.z)),n._anchorMesh.rotationQuaternion||(n._anchorMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(n._anchorMesh.rotation.y,n._anchorMesh.rotation.x,n._anchorMesh.rotation.z)),a+=h,Math.abs(a)<=2*Math.PI&&(t>=8?e.Quaternion.RotationYawPitchRollToRef(0,0,h,n._tmpQuaternion):t>=4?e.Quaternion.RotationYawPitchRollToRef(h,0,0,n._tmpQuaternion):e.Quaternion.RotationYawPitchRollToRef(0,h,0,n._tmpQuaternion),n._anchorMesh.addChild(n.attachedMesh),n._anchorMesh.rotationQuaternion.multiplyToRef(n._tmpQuaternion,n._anchorMesh.rotationQuaternion),n._anchorMesh.removeChild(n.attachedMesh)),n.updateBoundingBox()}})),l.onDragStartObservable.add((function(){n.onDragStartObservable.notifyObservers({}),n._selectNode(i)})),l.onDragEndObservable.add((function(){n.onDragEndObservable.notifyObservers({}),n._selectNode(null)})),h._rotateSpheresParent.addChild(i)})(c);n._rootMesh.addChild(n._rotateSpheresParent),n._scaleBoxesParent=new e.AbstractMesh("",r.utilityLayerScene),n._scaleBoxesParent.rotationQuaternion=new e.Quaternion;for(var u=0;u<2;u++)for(var f=0;f<2;f++)for(var l,d=this,p=0;p<2;p++)!(function(){var t=e.MeshBuilder.CreateBox("",{size:1},r.utilityLayerScene);t.material=o;var i=new e.Vector3(0==u?-1:1,0==f?-1:1,0==p?-1:1);l=new e.PointerDragBehavior({dragAxis:i}),l.moveAttached=!1,t.addBehavior(l),l.onDragObservable.add((function(i){if(n.onDragObservable.notifyObservers({}),n.attachedMesh){var r=i.dragDistance/n._boundingDimensions.length()*n._anchorMesh.scaling.length(),o=new e.Vector3(r,r,r);o.scaleInPlace(n._scaleDragSpeed),n.updateBoundingBox(),t.absolutePosition.subtractToRef(n._anchorMesh.position,n._tmpVector),n._anchorMesh.position.subtractInPlace(n._tmpVector),n._anchorMesh.addChild(n.attachedMesh),n._anchorMesh.scaling.addInPlace(o),(n._anchorMesh.scaling.x<0||n._anchorMesh.scaling.y<0||n._anchorMesh.scaling.z<0)&&n._anchorMesh.scaling.subtractInPlace(o),n._anchorMesh.removeChild(n.attachedMesh)}})),l.onDragStartObservable.add((function(){n.onDragStartObservable.notifyObservers({}),n._selectNode(t)})),l.onDragEndObservable.add((function(){n.onDragEndObservable.notifyObservers({}),n._selectNode(null)})),d._scaleBoxesParent.addChild(t)})();n._rootMesh.addChild(n._scaleBoxesParent);var m=new Array;return n._pointerObserver=r.utilityLayerScene.onPointerObservable.add((function(e,t){m[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=m[e.event.pointerId]&&(m[e.event.pointerId].material=o,delete m[e.event.pointerId]):n._rotateSpheresParent.getChildMeshes().concat(n._scaleBoxesParent.getChildMeshes()).forEach((function(t){e.pickInfo&&e.pickInfo.pickedMesh==t&&(m[e.event.pointerId]=t,t.material=s)}))})),n._renderObserver=n.gizmoLayer.originalScene.onBeforeRenderObservable.add((function(){n.attachedMesh&&!n._existingMeshScale.equals(n.attachedMesh.scaling)&&n.updateBoundingBox()})),n.updateBoundingBox(),n}return o(i,t),i.prototype._attachedMeshChanged=function(e){e&&(this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),this.updateBoundingBox())},i.prototype._selectNode=function(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((function(t,i){t.isVisible=!e||t==e}))},i.prototype._recurseComputeWorld=function(e){var t=this;e.computeWorldMatrix(!0),e.getChildMeshes().forEach((function(e){t._recurseComputeWorld(e)}))},i.prototype.updateBoundingBox=function(){if(this._update(),this.attachedMesh){this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);var t=this.attachedMesh.getHierarchyBoundingVectors();t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this._recurseComputeWorld(this.attachedMesh)}for(var i=this._rotateSpheresParent.getChildMeshes(),r=0;r<3;r++)for(var n=0;n<2;n++)for(var o=0;o<2;o++){var s=4*r+2*n+o;if(0==r&&(i[s].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*n,this._boundingDimensions.z*o),i[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),i[s].lookAt(e.Vector3.Cross(e.Vector3.Right(),i[s].position.normalizeToNew()).normalizeToNew().add(i[s].position))),1==r&&(i[s].position.set(this._boundingDimensions.x*n,this._boundingDimensions.y/2,this._boundingDimensions.z*o),i[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),i[s].lookAt(e.Vector3.Cross(e.Vector3.Up(),i[s].position.normalizeToNew()).normalizeToNew().add(i[s].position))),2==r&&(i[s].position.set(this._boundingDimensions.x*n,this._boundingDimensions.y*o,this._boundingDimensions.z/2),i[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),i[s].lookAt(e.Vector3.Cross(e.Vector3.Forward(),i[s].position.normalizeToNew()).normalizeToNew().add(i[s].position))),this.fixedDragMeshScreenSize){this._rootMesh.computeWorldMatrix(),this._rotateSpheresParent.computeWorldMatrix(),i[s].computeWorldMatrix(),i[s].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var a=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;i[s].scaling.set(a,a,a)}else i[s].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}for(var l=this._scaleBoxesParent.getChildMeshes(),r=0;r<2;r++)for(var n=0;n<2;n++)for(var o=0;o<2;o++){var s=4*r+2*n+o;if(l[s])if(l[s].position.set(this._boundingDimensions.x*r,this._boundingDimensions.y*n,this._boundingDimensions.z*o),l[s].position.addInPlace(new e.Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize){this._rootMesh.computeWorldMatrix(),this._scaleBoxesParent.computeWorldMatrix(),l[s].computeWorldMatrix(),l[s].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var a=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;l[s].scaling.set(a,a,a)}else l[s].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize)}this.attachedMesh&&this._existingMeshScale.copyFrom(this.attachedMesh.scaling)},i.prototype.setEnabledRotationAxis=function(e){this._rotateSpheresParent.getChildMeshes().forEach((function(t,i){i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))}))},i.prototype.dispose=function(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),t.prototype.dispose.call(this)},i.MakeNotPickableAndWrapInBoundingBox=function(t){var i=function(e){e.isPickable=!1,e.getChildMeshes().forEach((function(e){i(e)}))};i(t),t.rotationQuaternion||(t.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(t.rotation.y,t.rotation.x,t.rotation.z));var r=t.position.clone(),n=t.rotationQuaternion.clone();t.rotationQuaternion.set(0,0,0,1),t.position.set(0,0,0);var o=e.MeshBuilder.CreateBox("box",{size:1},t.getScene()),s=t.getHierarchyBoundingVectors();return s.max.subtractToRef(s.min,o.scaling),o.position.set((s.max.x+s.min.x)/2,(s.max.y+s.min.y)/2,(s.max.z+s.min.z)/2),t.addChild(o),t.rotationQuaternion.copyFrom(n),t.position.copyFrom(r),t.removeChild(o),o.addChild(t),o.visibility=0,o},i.prototype.setCustomMesh=function(t){e.Tools.Error("Custom meshes are not supported on this gizmo")},i})(e.Gizmo);e.BoundingBoxGizmo=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){var i=this;this.scene=t,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObserver=null,this._attachedMesh=null,this._boundingBoxColor=e.Color3.FromHexString("#0984e3"),this._dragBehavior=new e.SixDofDragBehavior,this.attachableMeshes=null,this.usePointerToAttachGizmos=!0,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null},this._pointerObserver=t.onPointerObservable.add((function(t,r){if(i.usePointerToAttachGizmos&&t.type==e.PointerEventTypes.POINTERDOWN)if(t.pickInfo&&t.pickInfo.pickedMesh){var n=t.pickInfo.pickedMesh;if(null==i.attachableMeshes)for(;n&&null!=n.parent;)n=n.parent;else{var o=!1;i.attachableMeshes.forEach((function(e){n&&(n==e||n.isDescendantOf(e))&&(n=e,o=!0)})),o||(n=null)}n instanceof e.AbstractMesh&&i.attachToMesh(n)}else i.attachToMesh(null)}))}return t.prototype.attachToMesh=function(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this._dragBehavior),this._attachedMesh=e;for(var t in this.gizmos){var i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this._dragBehavior)},Object.defineProperty(t.prototype,"positionGizmoEnabled",{get:function(){return this._gizmosEnabled.positionGizmo},set:function(t){t?(this.gizmos.positionGizmo=this.gizmos.positionGizmo||new e.PositionGizmo,this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh=!1,this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedMesh=null),this._gizmosEnabled.positionGizmo=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationGizmoEnabled",{get:function(){return this._gizmosEnabled.rotationGizmo},set:function(t){t?(this.gizmos.rotationGizmo=this.gizmos.rotationGizmo||new e.RotationGizmo,this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh=!1,this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedMesh=null),this._gizmosEnabled.rotationGizmo=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleGizmoEnabled",{get:function(){return this._gizmosEnabled.scaleGizmo},set:function(t){t?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new e.ScaleGizmo,this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedMesh=null),this._gizmosEnabled.scaleGizmo=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"boundingBoxGizmoEnabled",{get:function(){return this._gizmosEnabled.boundingBoxGizmo},set:function(t){t?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new e.BoundingBoxGizmo(this._boundingBoxColor),this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh,this._attachedMesh&&(this._attachedMesh.removeBehavior(this._dragBehavior),this._attachedMesh.addBehavior(this._dragBehavior))):this.gizmos.boundingBoxGizmo&&(this.gizmos.boundingBoxGizmo.attachedMesh=null),this._gizmosEnabled.boundingBoxGizmo=t},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.scene.onPointerObservable.remove(this._pointerObserver);for(var e in this.gizmos){var t=this.gizmos[e];t&&t.dispose()}this._dragBehavior.detach(),this._gizmoLayer.dispose()},t})();e.GizmoManager=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t,i,r){void 0===i&&(i=0),void 0===r&&(r=null),this.name=t,this.animations=new Array,this._positions=null,this._normals=null, +this._tangents=null,this.onInfluenceChanged=new e.Observable,this._animationPropertiesOverride=null,this._scene=r||e.Engine.LastCreatedScene,this.influence=i}return Object.defineProperty(t.prototype,"influence",{get:function(){return this._influence},set:function(e){if(this._influence!==e){var t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPositions",{get:function(){return!!this._positions},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasNormals",{get:function(){return!!this._normals},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasTangents",{get:function(){return!!this._tangents},enumerable:!0,configurable:!0}),t.prototype.setPositions=function(e){this._positions=e},t.prototype.getPositions=function(){return this._positions},t.prototype.setNormals=function(e){this._normals=e},t.prototype.getNormals=function(){return this._normals},t.prototype.setTangents=function(e){this._tangents=e},t.prototype.getTangents=function(){return this._tangents},t.prototype.serialize=function(){var t={};return t.name=this.name,t.influence=this.influence,t.positions=Array.prototype.slice.call(this.getPositions()),this.hasNormals&&(t.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(t.tangents=Array.prototype.slice.call(this.getTangents())),e.Animation.AppendSerializedAnimations(this,t),t},t.Parse=function(i){var r=new t(i.name,i.influence);if(r.setPositions(i.positions),i.normals&&r.setNormals(i.normals),i.tangents&&r.setTangents(i.tangents),i.animations)for(var n=0;n=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetObservable.splice(t,1)[0]),this._syncActiveTargets(!0))},t.prototype.serialize=function(){var e={};e.id=this.uniqueId,e.targets=[];for(var t=0,i=this._targets;tthis.capacity&&this._depth=2&&t.onControllersAttachedObservable.notifyObservers(t.controllers)}}}))},i})(e.FreeCamera);e.WebVRFreeCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("DeviceOrientationCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n){var o=t.call(this,i,r,n)||this;return o._quaternionCache=new e.Quaternion,o.inputs.addDeviceOrientation(),o}return o(i,t),i.prototype.getClassName=function(){return"DeviceOrientationCamera"},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)},i.prototype.resetToCurrentRotation=function(t){var i=this;void 0===t&&(t=e.Axis.Y),this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new e.Quaternion),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((function(e){t[e]?i._initialQuaternion[e]*=-1:i._initialQuaternion[e]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))},i})(e.FreeCamera);e.DeviceOrientationCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s){void 0===o&&(o=!0),void 0===s&&(s=e.VRCameraMetrics.GetDefault());var a=t.call(this,i,r,n)||this;return s.compensateDistortion=o,a.setCameraRigMode(e.Camera.RIG_MODE_VR,{vrCameraMetrics:s}),a}return o(i,t),i.prototype.getClassName=function(){return"VRDeviceOrientationFreeCamera"},i})(e.DeviceOrientationCamera);e.VRDeviceOrientationFreeCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera",(function(i,r){return function(){return new t(i,0,0,1,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s,a,l,h){void 0===l&&(l=!0),void 0===h&&(h=e.VRCameraMetrics.GetDefault());var c=t.call(this,i,r,n,o,s,a)||this;return h.compensateDistortion=l,c.setCameraRigMode(e.Camera.RIG_MODE_VR,{vrCameraMetrics:h}),c.inputs.addVRDeviceOrientation(),c}return o(i,t),i.prototype.getClassName=function(){return"VRDeviceOrientationArcRotateCamera"},i})(e.ArcRotateCamera);e.VRDeviceOrientationArcRotateCamera=t})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(t){function i(i,r,n,o,s){void 0===o&&(o=!0),void 0===s&&(s=e.VRCameraMetrics.GetDefault());var a=t.call(this,i,r,n,o,s)||this;return a.inputs.addGamepad(),a}return o(i,t),i.prototype.getClassName=function(){return"VRDeviceOrientationGamepadCamera"},i})(e.VRDeviceOrientationFreeCamera);e.VRDeviceOrientationGamepadCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(i,r){if(void 0===r&&(r=null),this.scene=i,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=t._idCounter++,r)this._gazeTracker=r.clone("gazeTracker");else{this._gazeTracker=e.Mesh.CreateTorus("gazeTracker",.0035,.0025,20,i,!1),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;var n=new e.StandardMaterial("targetMat",i);n.specularColor=e.Color3.Black(),n.emissiveColor=new e.Color3(.7,.7,.7),n.backFaceCulling=!1,this._gazeTracker.material=n}}return t.prototype._getForwardRay=function(t){return new e.Ray(e.Vector3.Zero(),new e.Vector3(0,0,t))},t.prototype._selectionPointerDown=function(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})},t.prototype._selectionPointerUp=function(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1},t.prototype._activatePointer=function(){this._activePointer=!0},t.prototype._deactivatePointer=function(){this._activePointer=!1},t.prototype._updatePointerDistance=function(e){void 0===e&&(e=100)},t.prototype.dispose=function(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()},t._idCounter=0,t})(),i=(function(t){function i(i,r,n){var o=t.call(this,r,n)||this;o.webVRController=i,o._laserPointer=e.Mesh.CreateCylinder("laserPointer",1,.004,2e-4,20,1,r,!1);var s=new e.StandardMaterial("laserPointerMat",r);if(s.emissiveColor=new e.Color3(.7,.7,.7),s.alpha=.6,o._laserPointer.material=s,o._laserPointer.rotation.x=Math.PI/2,o._laserPointer.position.z=-.5,o._laserPointer.isVisible=!1,o._laserPointer.isPickable=!1,!i.mesh){var a=new e.Mesh("preloadControllerMesh",r),l=new e.Mesh(e.PoseEnabledController.POINTING_POSE,r);l.rotation.x=-.7,a.addChild(l),i.attachToMesh(a)}return o._setLaserPointerParent(i.mesh),o._meshAttachedObserver=i._meshAttachedObservable.add((function(e){o._setLaserPointerParent(e)})),o}return o(i,t),i.prototype._getForwardRay=function(e){return this.webVRController.getForwardRay(e)},i.prototype._activatePointer=function(){t.prototype._activatePointer.call(this),this._laserPointer.isVisible=!0},i.prototype._deactivatePointer=function(){t.prototype._deactivatePointer.call(this),this._laserPointer.isVisible=!1},i.prototype._setLaserPointerColor=function(e){this._laserPointer.material.emissiveColor=e},i.prototype._setLaserPointerParent=function(t){var i=function(e){e.isPickable=!1,e.getChildMeshes().forEach((function(e){i(e)}))};i(t);var r=t.getChildMeshes();this.webVRController._pointingPoseNode=null;for(var n=0;n=0){t=r[n],this.webVRController._pointingPoseNode=t;break}this._laserPointer.parent=t},i.prototype._updatePointerDistance=function(e){void 0===e&&(e=100),this._laserPointer.scaling.y=e,this._laserPointer.position.z=-e/2},i.prototype.dispose=function(){t.prototype.dispose.call(this),this._laserPointer.dispose(),this._meshAttachedObserver&&this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)},i})(t),r=(function(t){function i(e,i){var r=t.call(this,i)||this;return r.getCamera=e,r}return o(i,t),i.prototype._getForwardRay=function(t){var i=this.getCamera();return i?i.getForwardRay(t):new e.Ray(e.Vector3.Zero(),e.Vector3.Forward())},i})(t),n=(function(){function t(t,n){void 0===n&&(n={});var o=this;if(this.webVROptions=n,this._webVRsupported=!1,this._webVRready=!1,this._webVRrequesting=!1,this._webVRpresenting=!1,this._fullscreenVRpresenting=!1,this.onEnteringVRObservable=new e.Observable,this.onExitingVRObservable=new e.Observable,this.onControllerMeshLoadedObservable=new e.Observable,this._useCustomVRButton=!1,this._teleportationRequested=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._rotationAllowed=!0,this._teleportBackwardsVector=new e.Vector3(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new e.Vector3(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this.leftController=null,this.rightController=null,this.onNewMeshSelected=new e.Observable,this.onNewMeshPicked=new e.Observable,this.onBeforeCameraTeleport=new e.Observable,this.onAfterCameraTeleport=new e.Observable,this.onSelectedMeshUnselected=new e.Observable,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._interactionsRequested=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this._onResize=function(){o.moveButtonToBottomRight(),o._fullscreenVRpresenting&&o._webVRready&&o.exitVR()},this._onFullscreenChange=function(){void 0!==document.fullscreen?o._fullscreenVRpresenting=document.fullscreen:void 0!==document.mozFullScreen?o._fullscreenVRpresenting=document.mozFullScreen:void 0!==document.webkitIsFullScreen?o._fullscreenVRpresenting=document.webkitIsFullScreen:void 0!==document.msIsFullScreen?o._fullscreenVRpresenting=document.msIsFullScreen:void 0!==document.msFullscreenElement&&(o._fullscreenVRpresenting=document.msFullscreenElement),!o._fullscreenVRpresenting&&o._canvas&&(o.exitVR(),o._useCustomVRButton||(o._btnVR.style.top=o._canvas.offsetTop+o._canvas.offsetHeight-70+"px",o._btnVR.style.left=o._canvas.offsetLeft+o._canvas.offsetWidth-100+"px"))},this.beforeRender=function(){o.leftController&&o.leftController._activePointer&&o._castRayAndSelectObject(o.leftController),o.rightController&&o.rightController._activePointer&&o._castRayAndSelectObject(o.rightController),o._noControllerIsActive?o._castRayAndSelectObject(o._cameraGazer):o._cameraGazer._gazeTracker.isVisible=!1},this._onNewGamepadConnected=function(t){if(t.type!==e.Gamepad.POSE_ENABLED)t.leftStick&&t.onleftstickchanged((function(e){o._teleportationInitialized&&o.teleportationEnabled&&(!o.leftController&&!o.rightController||o.leftController&&!o.leftController._activePointer&&o.rightController&&!o.rightController._activePointer)&&(o._checkTeleportWithRay(e,o._cameraGazer),o._checkTeleportBackwards(e,o._cameraGazer))})),t.rightStick&&t.onrightstickchanged((function(e){o._teleportationInitialized&&o._checkRotate(e,o._cameraGazer)})),t.type===e.Gamepad.XBOX&&(t.onbuttondown((function(t){o._interactionsEnabled&&t===e.Xbox360Button.A&&o._cameraGazer._selectionPointerDown()})),t.onbuttonup((function(t){o._interactionsEnabled&&t===e.Xbox360Button.A&&o._cameraGazer._selectionPointerUp()})));else{var r=t,n=new i(r,o._scene,o._cameraGazer._gazeTracker);"right"===r.hand||o.leftController&&o.leftController.webVRController!=r?o.rightController=n:o.leftController=n,o._tryEnableInteractionOnController(n)}},this._tryEnableInteractionOnController=function(e){o._interactionsRequested&&!e._interactionsEnabled&&o._enableInteractionOnController(e),o._teleportationRequested&&!e._teleportationEnabled&&o._enableTeleportationOnController(e)},this._onNewGamepadDisconnected=function(t){t instanceof e.WebVRController&&("left"===t.hand&&null!=o.leftController&&(o.leftController.dispose(),o.leftController=null),"right"===t.hand&&null!=o.rightController&&(o.rightController.dispose(),o.rightController=null))},this._workingVector=e.Vector3.Zero(),this._workingQuaternion=e.Quaternion.Identity(),this._workingMatrix=e.Matrix.Identity(),this._scene=t,this._canvas=t.getEngine().getRenderingCanvas(),void 0===n.createFallbackVRDeviceOrientationFreeCamera&&(n.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===n.createDeviceOrientationCamera&&(n.createDeviceOrientationCamera=!0),void 0===n.laserToggle&&(n.laserToggle=!0),void 0===n.defaultHeight&&(n.defaultHeight=1.7),n.useCustomVRButton&&(this._useCustomVRButton=!0,n.customVRButton&&(this._btnVR=n.customVRButton)),n.rayLength&&(this._rayLength=n.rayLength),this._defaultHeight=n.defaultHeight,n.positionScale&&(this._rayLength*=n.positionScale,this._defaultHeight*=n.positionScale),this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new e.Vector3(0,this._defaultHeight,0),n.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new e.DeviceOrientationCamera("deviceOrientationVRHelper",this._position.clone(),t),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof e.TargetCamera&&this._scene.activeCamera.rotation)){var s=this._scene.activeCamera;s.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(s.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.Quaternion.RotationYawPitchRoll(s.rotation.y,s.rotation.x,s.rotation.z)),this._deviceOrientationCamera.rotation=s.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._canvas&&this._scene.activeCamera.attachControl(this._canvas)}else this._existingCamera=this._scene.activeCamera;if(n.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new e.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper",this._position,this._scene)),this._webVRCamera=new e.WebVRFreeCamera("WebVRHelper",this._position,this._scene,n),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new r(function(){return o.currentVRCamera},t),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";var a=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";a+=".babylonVRicon.vrdisplaypresenting { display: none; }";var l=document.createElement("style");l.appendChild(document.createTextNode(a)),document.getElementsByTagName("head")[0].appendChild(l),this.moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(function(){o.isInVRMode?o.exitVR():o.enterVR()})),window.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("mozfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("msfullscreenchange",this._onFullscreenChange,!1),document.onmsfullscreenchange=this._onFullscreenChange,n.createFallbackVRDeviceOrientationFreeCamera?this.displayVRButton():this._scene.getEngine().onVRDisplayChangedObservable.add((function(e){e.vrDisplay&&o.displayVRButton()})),this._onKeyDown=function(e){27===e.keyCode&&o.isInVRMode&&o.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((function(e,t){o.isInVRMode&&(o.exitVR(),o._fullscreenVRpresenting&&o._scene.getEngine().switchFullscreen(!0))}),e.PointerEventTypes.POINTERDOUBLETAP,!1),this._onVRDisplayChanged=function(e){return o.onVRDisplayChanged(e)},this._onVrDisplayPresentChange=function(){return o.onVrDisplayPresentChange()},this._onVRRequestPresentStart=function(){o._webVRrequesting=!0,o.updateButtonVisibility()},this._onVRRequestPresentComplete=function(e){o._webVRrequesting=!1,o.updateButtonVisibility()},t.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged),t.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),t.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),window.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),t.onDisposeObservable.add((function(){o.dispose()})),this._webVRCamera.onControllerMeshLoadedObservable.add((function(e){return o._onDefaultMeshLoaded(e)})),this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),this.updateButtonVisibility(),this._circleEase=new e.CircleEase,this._circleEase.setEasingMode(e.EasingFunction.EASINGMODE_EASEINOUT),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes})}return Object.defineProperty(t.prototype,"onEnteringVR",{get:function(){return this.onEnteringVRObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onExitingVR",{get:function(){return this.onExitingVRObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onControllerMeshLoaded",{get:function(){return this.onControllerMeshLoadedObservable},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"teleportationTarget",{get:function(){return this._teleportationTarget},set:function(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gazeTrackerMesh",{get:function(){return this._cameraGazer._gazeTracker},set:function(e){e&&(this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker",this.leftController&&(this.leftController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")),this.rightController&&(this.rightController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayGaze",{get:function(){return this._displayGaze},set:function(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1,this.leftController&&(this.leftController._gazeTracker.isVisible=!1),this.rightController&&(this.rightController._gazeTracker.isVisible=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayLaserPointer",{get:function(){return this._displayLaserPointer},set:function(e){this._displayLaserPointer=e,e?(this.rightController&&this.rightController._activatePointer(),this.leftController&&this.leftController._activatePointer()):(this.rightController&&(this.rightController._deactivatePointer(),this.rightController._gazeTracker.isVisible=!1),this.leftController&&(this.leftController._deactivatePointer(),this.leftController._gazeTracker.isVisible=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"deviceOrientationCamera",{get:function(){return this._deviceOrientationCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentVRCamera",{get:function(){return this._webVRready?this._webVRCamera:this._scene.activeCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"webVRCamera",{get:function(){return this._webVRCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vrDeviceOrientationCamera",{get:function(){return this._vrDeviceOrientationCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_teleportationRequestInitiated",{get:function(){return this._cameraGazer._teleportationRequestInitiated||null!==this.leftController&&this.leftController._teleportationRequestInitiated||null!==this.rightController&&this.rightController._teleportationRequestInitiated},enumerable:!0,configurable:!0}),t.prototype._onDefaultMeshLoaded=function(t){this.leftController&&this.leftController.webVRController==t&&t.mesh&&this.leftController._setLaserPointerParent(t.mesh),this.rightController&&this.rightController.webVRController==t&&t.mesh&&this.rightController._setLaserPointerParent(t.mesh);try{this.onControllerMeshLoadedObservable.notifyObservers(t)}catch(t){e.Tools.Warn("Error in your custom logic onControllerMeshLoaded: "+t)}},Object.defineProperty(t.prototype,"isInVRMode",{get:function(){return this._webVRpresenting||this._fullscreenVRpresenting},enumerable:!0,configurable:!0}),t.prototype.onVrDisplayPresentChange=function(){var t=this._scene.getEngine().getVRDevice();if(t){var i=this._webVRpresenting;this._webVRpresenting=t.isPresenting,i&&!this._webVRpresenting&&this.exitVR()}else e.Tools.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");this.updateButtonVisibility()},t.prototype.onVRDisplayChanged=function(e){this._webVRsupported=e.vrSupported,this._webVRready=!!e.vrDisplay,this._webVRpresenting=e.vrDisplay&&e.vrDisplay.isPresenting,this.updateButtonVisibility()},t.prototype.moveButtonToBottomRight=function(){this._canvas&&!this._useCustomVRButton&&(this._btnVR.style.top=this._canvas.offsetTop+this._canvas.offsetHeight-70+"px",this._btnVR.style.left=this._canvas.offsetLeft+this._canvas.offsetWidth-100+"px")},t.prototype.displayVRButton=function(){this._useCustomVRButton||this._btnVRDisplayed||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)},t.prototype.updateButtonVisibility=function(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode?this._btnVR.className+=" vrdisplaypresenting":(this._webVRready&&(this._btnVR.className+=" vrdisplayready"),this._webVRsupported&&(this._btnVR.className+=" vrdisplaysupported"),this._webVRrequesting&&(this._btnVR.className+=" vrdisplayrequesting")))},t.prototype.enterVR=function(){if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(t){e.Tools.Warn("Error in your custom logic onEnteringVR: "+t)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this._existingCamera=this._scene.activeCamera),this._webVRrequesting||(this._webVRready?this._webVRpresenting||(this._webVRCamera.position=this._position,this._scene.activeCamera=this._webVRCamera):this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().switchFullscreen(!0),this.updateButtonVisibility()),this._scene.activeCamera&&this._canvas&&this._scene.activeCamera.attachControl(this._canvas),this._interactionsEnabled&&this._scene.registerBeforeRender(this.beforeRender))},t.prototype.exitVR=function(){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(t){e.Tools.Warn("Error in your custom logic onExitingVR: "+t)}this._webVRpresenting&&this._scene.getEngine().disableVR(),this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._canvas&&this._scene.activeCamera.attachControl(this._canvas)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera),this.updateButtonVisibility(),this._interactionsEnabled&&this._scene.unregisterBeforeRender(this.beforeRender),this._scene.getEngine().resize()},Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)},enumerable:!0,configurable:!0}),t.prototype.enableInteractions=function(){var e=this;this._interactionsEnabled||(this._interactionsRequested=!0,this.leftController&&this._enableInteractionOnController(this.leftController),this.rightController&&this._enableInteractionOnController(this.rightController),this.raySelectionPredicate=function(e){return e.isVisible&&e.isPickable},this.meshSelectionPredicate=function(e){return!0},this._raySelectionPredicate=function(t){return!!(e._isTeleportationFloor(t)||-1===t.name.indexOf("gazeTracker")&&-1===t.name.indexOf("teleportationTarget")&&-1===t.name.indexOf("torusTeleportation"))&&e.raySelectionPredicate(t)},this._interactionsEnabled=!0)},Object.defineProperty(t.prototype,"_noControllerIsActive",{get:function(){return!(this.leftController&&this.leftController._activePointer||this.rightController&&this.rightController._activePointer)},enumerable:!0,configurable:!0}),t.prototype._isTeleportationFloor=function(e){for(var t=0;t-1||this._floorMeshesCollection.push(e))},t.prototype.removeFloorMesh=function(e){if(this._floorMeshesCollection){var t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}},t.prototype.enableTeleportation=function(t){if(void 0===t&&(t={}),!this._teleportationInitialized){this._teleportationRequested=!0,this.enableInteractions(),t.floorMeshName&&(this._floorMeshName=t.floorMeshName),t.floorMeshes&&(this._floorMeshesCollection=t.floorMeshes),null!=this.leftController&&this._enableTeleportationOnController(this.leftController),null!=this.rightController&&this._enableTeleportationOnController(this.rightController);var i=new e.ImageProcessingConfiguration;i.vignetteColor=new e.Color4(0,0,0,0),i.vignetteEnabled=!0,this._postProcessMove=new e.ImageProcessingPostProcess("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,i),this._webVRCamera.detachPostProcess(this._postProcessMove),this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&(this._createTeleportationCircles(),this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))}},t.prototype._enableInteractionOnController=function(e){var t=this;e.webVRController.mesh&&(e._interactionsEnabled=!0,e._activatePointer(),this.webVROptions.laserToggle&&e.webVRController.onMainButtonStateChangedObservable.add((function(i){t._displayLaserPointer&&1===i.value&&(e._activePointer?e._deactivatePointer():e._activatePointer(),t.displayGaze&&(e._gazeTracker.isVisible=e._activePointer))})),e.webVRController.onTriggerStateChangedObservable.add((function(i){var r=e;t._noControllerIsActive&&(r=t._cameraGazer),r._pointerDownOnMeshAsked?i.valuet._padSensibilityUp&&r._selectionPointerDown()})))},t.prototype._checkTeleportWithRay=function(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))},t.prototype._checkTeleportBackwards=function(t,i){if(!i._teleportationRequestInitiated)if(t.y>this._padSensibilityUp&&i._dpadPressed){if(!i._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;var r=e.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),n=this.currentVRCamera.position;this.currentVRCamera.devicePosition&&this.currentVRCamera.deviceRotationQuaternion&&(r=this.currentVRCamera.deviceRotationQuaternion,n=this.currentVRCamera.devicePosition),r.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,e.Quaternion.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),e.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);var o=new e.Ray(n,this._workingVector),s=this._scene.pickWithRay(o,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this._teleportCamera(s.pickedPoint),i._teleportationBackRequestInitiated=!0}}else i._teleportationBackRequestInitiated=!1},t.prototype._enableTeleportationOnController=function(t){var i=this;t.webVRController.mesh&&(t._interactionsEnabled||this._enableInteractionOnController(t),t._interactionsEnabled=!0,t._teleportationEnabled=!0,t.webVRController.controllerType===e.PoseEnabledControllerType.VIVE&&(t._dpadPressed=!1,t.webVRController.onPadStateChangedObservable.add((function(e){t._dpadPressed=e.pressed,t._dpadPressed||(t._rotationLeftAsked=!1,t._rotationRightAsked=!1,t._teleportationBackRequestInitiated=!1)}))),t.webVRController.onPadValuesChangedObservable.add((function(e){i.teleportationEnabled&&(i._checkTeleportBackwards(e,t),i._checkTeleportWithRay(e,t)),i._checkRotate(e,t)})))},t.prototype._createTeleportationCircles=function(){this._teleportationTarget=e.Mesh.CreateGround("teleportationTarget",2,2,2,this._scene),this._teleportationTarget.isPickable=!1;var t=new e.DynamicTexture("DynamicTexture",512,this._scene,!0);t.hasAlpha=!0;var i=t.getContext();i.beginPath(),i.arc(256,256,200,0,2*Math.PI,!1),i.fillStyle=this._teleportationFillColor,i.fill(),i.lineWidth=10,i.strokeStyle=this._teleportationBorderColor,i.stroke(),i.closePath(),t.update();var r=new e.StandardMaterial("TextPlaneMaterial",this._scene);r.diffuseTexture=t,this._teleportationTarget.material=r;var n=e.Mesh.CreateTorus("torusTeleportation",.75,.1,25,this._scene,!1);n.isPickable=!1,n.parent=this._teleportationTarget;var o=new e.Animation("animationInnerCircle","position.y",30,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CYCLE),s=[];s.push({frame:0,value:0}),s.push({frame:30,value:.4}),s.push({frame:60,value:0}),o.setKeys(s);var a=new e.SineEase;a.setEasingMode(e.EasingFunction.EASINGMODE_EASEINOUT),o.setEasingFunction(a),n.animations=[],n.animations.push(o),this._scene.beginAnimation(n,0,60,!0),this._hideTeleportationTarget()},t.prototype._displayTeleportationTarget=function(){this._teleportActive=!0,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!0,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!0))},t.prototype._hideTeleportationTarget=function(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))},t.prototype._rotateCamera=function(t){var i=this;if(this.currentVRCamera instanceof e.FreeCamera){t?this._rotationAngle++:this._rotationAngle--, +this.currentVRCamera.animations=[];var r=e.Quaternion.FromRotationMatrix(e.Matrix.RotationY(Math.PI/4*this._rotationAngle)),n=new e.Animation("animationRotation","rotationQuaternion",90,e.Animation.ANIMATIONTYPE_QUATERNION,e.Animation.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),o.push({frame:6,value:r}),n.setKeys(o),n.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(n),this._postProcessMove.animations=[];var s=new e.Animation("animationPP","vignetteWeight",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:4}),a.push({frame:6,value:0}),s.setKeys(a),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);var l=new e.Animation("animationPP2","vignetteStretch",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:3,value:10}),h.push({frame:6,value:0}),l.setKeys(h),l.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,6,!1,1,(function(){i._webVRCamera.detachPostProcess(i._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}},t.prototype._moveTeleportationSelectorTo=function(t,i,r){if(t.pickedPoint){i._teleportationRequestInitiated&&(this._displayTeleportationTarget(),this._haloCenter.copyFrom(t.pickedPoint),this._teleportationTarget.position.copyFrom(t.pickedPoint));var n=this._convertNormalToDirectionOfRay(t.getNormal(!0,!1),r);if(n){var o=e.Vector3.Cross(e.Axis.Y,n),s=e.Vector3.Cross(n,o);e.Vector3.RotationFromAxisToRef(s,n,o,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}},t.prototype._teleportCamera=function(t){var i=this;if(this.currentVRCamera instanceof e.FreeCamera){this.webVRCamera.leftCamera?(this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),this._workingVector.subtractInPlace(this.webVRCamera.position),t.subtractToRef(this._workingVector,this._workingVector)):this._workingVector.copyFrom(t),this.isInVRMode?this._workingVector.y+=this.webVRCamera.deviceDistanceToRoomGround()*this._webVRCamera.deviceScaleFactor:this._workingVector.y+=this._defaultHeight,this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this.currentVRCamera.animations=[];var r=new e.Animation("animationCameraTeleportation","position",90,e.Animation.ANIMATIONTYPE_VECTOR3,e.Animation.ANIMATIONLOOPMODE_CONSTANT),n=[{frame:0,value:this.currentVRCamera.position},{frame:11,value:this._workingVector}];r.setKeys(n),r.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];var o=new e.Animation("animationPP","vignetteWeight",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:0}),s.push({frame:5,value:8}),s.push({frame:11,value:0}),o.setKeys(s),this._postProcessMove.animations.push(o);var a=new e.Animation("animationPP2","vignetteStretch",90,e.Animation.ANIMATIONTYPE_FLOAT,e.Animation.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:5,value:10}),l.push({frame:11,value:0}),a.setKeys(l),this._postProcessMove.animations.push(a),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,11,!1,1,(function(){i._webVRCamera.detachPostProcess(i._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,11,!1,1,(function(){i.onAfterCameraTeleport.notifyObservers(i._workingVector)})),this._hideTeleportationTarget()}},t.prototype._convertNormalToDirectionOfRay=function(t,i){if(t){Math.acos(e.Vector3.Dot(t,i.direction))i.halfWidth,t&&this._joystickPointerID<0?(this._joystickPointerID=e.pointerId,this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone(),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):i._globalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))},i.prototype._onPointerMove=function(e){if(this._joystickPointerID==e.pointerId){this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY,this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos);var i=this.reverseLeftRight?-1:1,r=i*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,r));break;case t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,r));break;case t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,r))}var n=this.reverseUpDown?1:-1,o=n*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,o));break;case t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,o));break;case t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,o))}}else{var s=this._touches.get(e.pointerId.toString());s&&(s.x=e.clientX,s.y=e.clientY)}},i.prototype._onPointerUp=function(e){if(this._joystickPointerID==e.pointerId)i.vjCanvasContext.clearRect(this._joystickPointerStartPos.x-64,this._joystickPointerStartPos.y-64,128,128),i.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x-42,this._joystickPreviousPointerPos.y-42,84,84),this._joystickPointerID=-1,this.pressed=!1;else{var t=this._touches.get(e.pointerId.toString());t&&i.vjCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(e.pointerId.toString())},i.prototype.setJoystickColor=function(e){this._joystickColor=e},i.prototype.setActionOnTouch=function(e){this._action=e},i.prototype.setAxisForLeftRight=function(e){switch(e){case t.X:case t.Y:case t.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=t.X}},i.prototype.setAxisForUpDown=function(e){switch(e){case t.X:case t.Y:case t.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=t.Y}},i.prototype._drawVirtualJoystick=function(){var e=this;this.pressed&&this._touches.forEach((function(t,r){r.pointerId===e._joystickPointerID?(i.vjCanvasContext.clearRect(e._joystickPointerStartPos.x-64,e._joystickPointerStartPos.y-64,128,128),i.vjCanvasContext.clearRect(e._joystickPreviousPointerPos.x-42,e._joystickPreviousPointerPos.y-42,84,84),i.vjCanvasContext.beginPath(),i.vjCanvasContext.lineWidth=6,i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.arc(e._joystickPointerStartPos.x,e._joystickPointerStartPos.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.lineWidth=2,i.vjCanvasContext.arc(e._joystickPointerStartPos.x,e._joystickPointerStartPos.y,60,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.arc(e._joystickPointerPos.x,e._joystickPointerPos.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),e._joystickPreviousPointerPos=e._joystickPointerPos.clone()):(i.vjCanvasContext.clearRect(r.prevX-44,r.prevY-44,88,88),i.vjCanvasContext.beginPath(),i.vjCanvasContext.fillStyle="white",i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle="red",i.vjCanvasContext.lineWidth=6,i.vjCanvasContext.arc(r.x,r.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),r.prevX=r.x,r.prevY=r.y)})),requestAnimationFrame((function(){e._drawVirtualJoystick()}))},i.prototype.releaseCanvas=function(){i.vjCanvas&&(i.vjCanvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),i.vjCanvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),i.vjCanvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),i.vjCanvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(i.vjCanvas),i.vjCanvas=null)},i._globalJoystickIndex=0,i})();e.VirtualJoystick=i})(r||(r={}));var r;!(function(e){e.Node.AddNodeConstructor("VirtualJoysticksCamera",(function(i,r){return function(){return new t(i,e.Vector3.Zero(),r)}}));var t=(function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addVirtualJoystick(),n}return o(t,e),t.prototype.getClassName=function(){return"VirtualJoysticksCamera"},t})(e.FreeCamera);e.VirtualJoysticksCamera=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){}return t.prototype.getLeftJoystick=function(){return this._leftjoystick},t.prototype.getRightJoystick=function(){return this._rightjoystick},t.prototype.checkInputs=function(){if(this._leftjoystick){var t=this.camera,i=50*t._computeLocalCameraSpeed(),r=e.Matrix.RotationYawPitchRoll(t.rotation.y,t.rotation.x,0),n=e.Vector3.TransformCoordinates(new e.Vector3(this._leftjoystick.deltaPosition.x*i,this._leftjoystick.deltaPosition.y*i,this._leftjoystick.deltaPosition.z*i),r);t.cameraDirection=t.cameraDirection.add(n),t.cameraRotation=t.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}},t.prototype.attachControl=function(t,i){this._leftjoystick=new e.VirtualJoystick(!0),this._leftjoystick.setAxisForUpDown(e.JoystickAxis.Z),this._leftjoystick.setAxisForLeftRight(e.JoystickAxis.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new e.VirtualJoystick(!1),this._rightjoystick.setAxisForUpDown(e.JoystickAxis.X),this._rightjoystick.setAxisForLeftRight(e.JoystickAxis.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")},t.prototype.detachControl=function(e){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()},t.prototype.getClassName=function(){return"FreeCameraVirtualJoystickInput"},t.prototype.getSimpleName=function(){return"virtualJoystick"},t})();e.FreeCameraVirtualJoystickInput=t,e.CameraInputTypes.FreeCameraVirtualJoystickInput=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(e,t,i){this.quality=e,this.distance=t,this.optimizeMesh=i}return e})();e.SimplificationSettings=t;var i=(function(){function t(){this.running=!1,this._simplificationArray=[]}return t.prototype.addTask=function(e){this._simplificationArray.push(e)},t.prototype.executeNext=function(){var e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1},t.prototype.runSimplification=function(t){var i=this;if(t.parallelProcessing)t.settings.forEach((function(e){i.getSimplifier(t).simplify(e,(function(r){t.mesh.addLODLevel(e.distance,r),r.isVisible=!0,e.quality===t.settings[t.settings.length-1].quality&&t.successCallback&&t.successCallback(),i.executeNext()}))}));else{var r=this.getSimplifier(t),n=function(e,i){r.simplify(e,(function(r){t.mesh.addLODLevel(e.distance,r),r.isVisible=!0,i()}))};e.AsyncLoop.Run(t.settings.length,(function(e){n(t.settings[e.index],(function(){e.executeNext()}))}),(function(){t.successCallback&&t.successCallback(),i.executeNext()}))}},t.prototype.getSimplifier=function(e){switch(e.simplificationType){case r.QUADRATIC:default:return new l(e.mesh)}},t})();e.SimplificationQueue=i;var r;!(function(e){e[e.QUADRATIC=0]="QUADRATIC"})(r=e.SimplificationType||(e.SimplificationType={}));var n=(function(){function e(e){this.vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}return e})();e.DecimationTriangle=n;var o=(function(){function e(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new s,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}return e.prototype.updatePosition=function(e){this.position.copyFrom(e)},e})();e.DecimationVertex=o;var s=(function(){function e(e){this.data=new Array(10);for(var t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}return e.prototype.det=function(e,t,i,r,n,o,s,a,l){return this.data[e]*this.data[n]*this.data[l]+this.data[i]*this.data[r]*this.data[a]+this.data[t]*this.data[o]*this.data[s]-this.data[i]*this.data[n]*this.data[s]-this.data[e]*this.data[o]*this.data[a]-this.data[t]*this.data[r]*this.data[l]},e.prototype.addInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e.data[t]},e.prototype.addArrayInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e[t]},e.prototype.add=function(t){for(var i=new e,r=0;r<10;++r)i.data[r]=this.data[r]+t.data[r];return i},e.FromData=function(t,i,r,n){return new e(e.DataFromNumbers(t,i,r,n))},e.DataFromNumbers=function(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]},e})();e.QuadraticMatrix=s;var a=(function(){function e(e,t){this.vertexId=e,this.triangleId=t}return e})();e.Reference=a;var l=(function(){function t(t){this._mesh=t,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=e.Epsilon}return t.prototype.simplify=function(t,i){var r=this;this.initDecimatedMesh(),e.AsyncLoop.Run(this._mesh.subMeshes.length,(function(e){r.initWithMesh(e.index,(function(){r.runDecimation(t,e.index,(function(){e.executeNext()}))}),t.optimizeMesh)}),(function(){setTimeout((function(){i(r._reconstructedMesh)}),0)}))},t.prototype.runDecimation=function(t,i,r){var n=this,o=~~(this.triangles.length*t.quality),s=0,a=this.triangles.length,l=function(t,i){setTimeout((function(){t%5==0&&n.updateMesh(0===t);for(var r=0;rl||r.deleted||r.isDirty))for(var o=0;o<3;++o)if(r.error[o]>0,f,(function(){var t=function(e){if(l){var t=h.indexStart/3+e,i=3*t,r=l[i+0],o=l[i+1],a=l[i+2],c=s.vertices[u[r-h.verticesStart]],f=s.vertices[u[o-h.verticesStart]],d=s.vertices[u[a-h.verticesStart]],p=new n([c,f,d]);p.originalOffset=i,s.triangles.push(p)}};e.AsyncLoop.SyncAsyncForLoop(h.indexCount/3,s.syncIterations,t,(function(){s.init(i)}))}))},t.prototype.init=function(t){var i=this,r=function(t){var r=i.triangles[t];r.normal=e.Vector3.Cross(r.vertices[1].position.subtract(r.vertices[0].position),r.vertices[2].position.subtract(r.vertices[0].position)).normalize();for(var n=0;n<3;n++)r.vertices[n].q.addArrayInPlace(s.DataFromNumbers(r.normal.x,r.normal.y,r.normal.z,-e.Vector3.Dot(r.normal,r.vertices[0].position)))};e.AsyncLoop.SyncAsyncForLoop(this.triangles.length,this.syncIterations,r,(function(){var r=function(e){for(var t=i.triangles[e],r=0;r<3;++r)t.error[r]=i.calculateError(t.vertices[r],t.vertices[(r+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])};e.AsyncLoop.SyncAsyncForLoop(i.triangles.length,i.syncIterations,r,(function(){t()}))}))},t.prototype.reconstructMesh=function(t){var i,r=[];for(i=0;i0&&this._reconstructedMesh.setVerticesData(e.VertexBuffer.UVKind,l),h.length>0&&this._reconstructedMesh.setVerticesData(e.VertexBuffer.ColorKind,h);var b=this._mesh.subMeshes[t];t>0&&(this._reconstructedMesh.subMeshes=[],g.forEach((function(t){e.SubMesh.AddToMesh(t.materialIndex,t.verticesStart,t.verticesCount,t.indexStart,t.indexCount,t.getMesh())})),e.SubMesh.AddToMesh(b.materialIndex,_,d,m,3*r.length,this._reconstructedMesh))},t.prototype.initDecimatedMesh=function(){this._reconstructedMesh=new e.Mesh(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId},t.prototype.isFlipped=function(t,i,r,n,o,s){for(var a=0;a.999)return!0;var p=e.Vector3.Cross(f,d).normalize();if(n[a]=!1,e.Vector3.Dot(p,l.normal)<.2)return!0}else n[a]=!0,s.push(l)}}return!1},t.prototype.updateTriangles=function(e,t,i,r){for(var n=r,o=0;othis.maximumSize&&(n.scale(this.step),i=!1)}}return i},t})(t);e.TextureOptimization=i;var r=(function(e){function t(t,i,r){void 0===t&&(t=0),void 0===i&&(i=2),void 0===r&&(r=.25);var n=e.call(this,t)||this;return n.priority=t,n.maximumScale=i,n.step=r,n._currentScale=-1,n._directionOffset=1,n}return o(t,e),t.prototype.getDescription=function(){return"Setting hardware scaling level to "+this._currentScale},t.prototype.apply=function(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step, +e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale},t})(t);e.HardwareScalingOptimization=r;var n=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning shadows on/off"},t.prototype.apply=function(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0},t})(t);e.ShadowsOptimization=n;var s=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning post-processes on/off"},t.prototype.apply=function(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0},t})(t);e.PostProcessesOptimization=s;var a=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning lens flares on/off"},t.prototype.apply=function(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0},t})(t);e.LensFlaresOptimization=a;var l=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"},t.prototype.apply=function(e,t){return!this.onApply||this.onApply(e,t)},t})(t);e.CustomOptimization=l;var h=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning particles on/off"},t.prototype.apply=function(e,t){return e.particlesEnabled=t.isInImprovementMode,!0},t})(t);e.ParticlesOptimization=h;var c=(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.getDescription=function(){return"Turning render targets off"},t.prototype.apply=function(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0},t})(t);e.RenderTargetsOptimization=c;var u=(function(t){function i(){var i=null!==t&&t.apply(this,arguments)||this;return i._canBeMerged=function(t){if(!(t instanceof e.Mesh))return!1;var i=t;return!i.isDisposed()&&(!(!i.isVisible||!i.isEnabled())&&(!(i.instances.length>0)&&(!i.skeleton&&!i.hasLODLevels)))},i}return o(i,t),Object.defineProperty(i,"UpdateSelectionTree",{get:function(){return i._UpdateSelectionTree},set:function(e){i._UpdateSelectionTree=e},enumerable:!0,configurable:!0}),i.prototype.getDescription=function(){return"Merging similar meshes together"},i.prototype.apply=function(t,r,n){for(var o=t.meshes.slice(0),s=o.length,a=0;a=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);for(var r=!0,n=!0,o=0;o4&&(n.push(e.VertexBuffer.MatricesIndicesExtraKind),n.push(e.VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton?o.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),i&&(r.push("#define INSTANCES"),n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"));var a=r.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("outline",n,["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant"],["diffuseSampler"],a)),this._effect.isReady()},t})();e.OutlineRenderer=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this.edges=new Array,this.edgesConnectedCount=0}return e})(),i=(function(){function i(e,t,i){void 0===t&&(t=.95),void 0===i&&(i=!1),this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this._source=e,this._checkVerticesInsteadOfIndices=i,this._epsilon=t,this._prepareRessources(),this._generateEdgesLines()}return i.prototype._prepareRessources=function(){this._lineShader||(this._lineShader=new e.ShaderMaterial("lineShader",this._source.getScene(),"line",{attributes:["position","normal"],uniforms:["worldViewProjection","color","width","aspectRatio"]}),this._lineShader.disableDepthWrite=!0,this._lineShader.backFaceCulling=!1)},i.prototype._rebuild=function(){var t=this._buffers[e.VertexBuffer.PositionKind];t&&t._rebuild(),(t=this._buffers[e.VertexBuffer.NormalKind])&&t._rebuild();var i=this._source.getScene(),r=i.getEngine();this._ib=r.createIndexBuffer(this._linesIndices)},i.prototype.dispose=function(){var t=this._buffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._buffers[e.VertexBuffer.PositionKind]=null),t=this._buffers[e.VertexBuffer.NormalKind],t&&(t.dispose(),this._buffers[e.VertexBuffer.NormalKind]=null),this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose()},i.prototype._processEdgeForAdjacencies=function(e,t,i,r,n){return e===i&&t===r||e===r&&t===i?0:e===r&&t===n||e===n&&t===r?1:e===n&&t===i||e===i&&t===n?2:-1},i.prototype._processEdgeForAdjacenciesWithVertices=function(e,t,i,r,n){return e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(r)||e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(i)?0:e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(n)||e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(r)?1:e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(i)||e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(n)?2:-1},i.prototype._checkEdge=function(t,i,r,n,o){var s;if(void 0===i)s=!0;else{s=e.Vector3.Dot(r[t],r[i])0){this._previousStencilState=this._engine.getStencilBuffer();for(var r=0,n=i;r-1)){this._renderEffects=!0,this._needStencil=this._needStencil||o.needStencil();var s=o._mainTexture;s._shouldRender()&&(this.scene.incrementRenderId(),s.render(!1,!1))}}this.scene.incrementRenderId()}},t.prototype._setStencil=function(e){this._needStencil&&this._engine.setStencilBuffer(!0)},t.prototype._setStencilBack=function(e){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)},t.prototype._draw=function(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);for(var t=this.scene.effectLayers,i=0;i4&&(s.push(e.VertexBuffer.MatricesIndicesExtraKind),s.push(e.VertexBuffer.MatricesWeightsExtraKind)),o.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),o.push("#define BonesPerMesh "+(a.skeleton?a.skeleton.bones.length+1:0))):o.push("#define NUM_BONE_INFLUENCERS 0");var u=a.morphTargetManager,f=0;u&&u.numInfluencers>0&&(o.push("#define MORPHTARGETS"),f=u.numInfluencers,o.push("#define NUM_MORPH_INFLUENCERS "+f),e.MaterialHelper.PrepareAttributesForMorphTargets(s,a,{NUM_MORPH_INFLUENCERS:f})),i&&(o.push("#define INSTANCES"),s.push("world0"),s.push("world1"),s.push("world2"),s.push("world3"));var d=o.join("\n");return this._cachedDefines!==d&&(this._cachedDefines=d,this._effectLayerMapGenerationEffect=this._scene.getEngine().createEffect("glowMapGeneration",s,["world","mBones","viewProjection","diffuseMatrix","color","emissiveMatrix","morphTargetInfluences"],["diffuseSampler","emissiveSampler"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:f})),this._effectLayerMapGenerationEffect.isReady()},t.prototype.render=function(){var e=this._mergeEffect;if(e.isReady()){for(var t=0;t-1&&this._scene.effectLayers.splice(i,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()},t.prototype.getClassName=function(){return"EffectLayer"},t.Parse=function(t,i,r){return e.Tools.Instantiate(t.customType).Parse(t,i,r)},n([e.serialize()],t.prototype,"name",void 0),n([e.serializeAsColor4()],t.prototype,"neutralColor",void 0),n([e.serialize()],t.prototype,"isEnabled",void 0),n([e.serializeAsCameraReference()],t.prototype,"camera",null),n([e.serialize()],t.prototype,"renderingGroupId",null),t})();e.EffectLayer=t})(r||(r={}));var r;!(function(e){e.AbstractScene.prototype.getHighlightLayerByName=function(e){for(var t=0;t-1&&this._tasks.splice(t,1)},i.prototype._decreaseWaitingTasksCount=function(i){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,i),this.onProgressObservable.notifyObservers(new r(this._waitingTasksCount,this._totalTasksCount,i))}catch(t){e.Tools.Error("Error running progress callbacks."),console.log(t)}if(0===this._waitingTasksCount){try{this.onFinish&&this.onFinish(this._tasks);for(var n=this._tasks.slice(),o=0,s=n;o-1&&this._tasks.splice(a,1)}}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(t){e.Tools.Error("Error running tasks-done callbacks."),console.log(t)}this._isLoading=!1,this._scene.getEngine().hideLoadingUI()}},i.prototype._runTask=function(e){var t=this,i=function(){try{t.onTaskSuccess&&t.onTaskSuccess(e),t.onTaskSuccessObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)}catch(e){r("Error executing task success callbacks",e)}},r=function(i,r){e._setErrorObject(i,r),t.onTaskError&&t.onTaskError(e),t.onTaskErrorObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)};e.run(this._scene,i,r)},i.prototype.reset=function(){return this._isLoading=!1,this._tasks=new Array,this},i.prototype.load=function(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(var e=0;eu.upperRadiusLimit?u.upperRadiusLimit:c),c):0},t.prototype._maintainCameraAboveGround=function(){var i=this;if(!(this._elevationReturnTime<0)){var r=e.Tools.Now-this._lastInteractionTime,n=.5*Math.PI-this._defaultElevation,o=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>o&&r>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=e.Animation.CreateAnimation("beta",e.Animation.ANIMATIONTYPE_FLOAT,60,t.EasingFunction));var s=e.Animation.TransitionTo("beta",n,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(function(){i._clearAnimationLocks(),i.stopAllAnimations()}));s&&this._animatables.push(s)}}},t.prototype._getFrustumSlope=function(){var t=this._attachedCamera;if(!t)return e.Vector2.Zero();var i=t.getScene().getEngine(),r=i.getAspectRatio(t),n=Math.tan(t.fov/2),o=n*r;return new e.Vector2(o,n)},t.prototype._clearAnimationLocks=function(){this._betaIsAnimating=!1},t.prototype._applyUserInteraction=function(){this.isUserIsMoving&&(this._lastInteractionTime=e.Tools.Now,this.stopAllAnimations(),this._clearAnimationLocks())},t.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()},Object.defineProperty(t.prototype,"isUserIsMoving",{get:function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},enumerable:!0,configurable:!0}),t.EasingFunction=new e.ExponentialEase,t.EasingMode=e.EasingFunction.EASINGMODE_EASEINOUT,t.IgnoreBoundsSizeMode=0,t.FitFrustumSidesMode=1,t})();e.FramingBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}return Object.defineProperty(t.prototype,"name",{get:function(){return"Bouncing"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"autoTransitionRange",{get:function(){return this._autoTransitionRange},set:function(e){var t=this;if(this._autoTransitionRange!==e){this._autoTransitionRange=e;var i=this._attachedCamera;i&&(e?this._onMeshTargetChangedObserver=i.onMeshTargetChangedObservable.add((function(e){if(e){e.computeWorldMatrix(!0);var i=e.getBoundingInfo().diagonalLength;t.lowerRadiusTransitionRange=.05*i,t.upperRadiusTransitionRange=.05*i}})):this._onMeshTargetChangedObserver&&i.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(e){var t=this;this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((function(){t._attachedCamera&&(t._isRadiusAtLimit(t._attachedCamera.lowerRadiusLimit)&&t._applyBoundRadiusAnimation(t.lowerRadiusTransitionRange),t._isRadiusAtLimit(t._attachedCamera.upperRadiusLimit)&&t._applyBoundRadiusAnimation(t.upperRadiusTransitionRange))}))},t.prototype.detach=function(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)},t.prototype._isRadiusAtLimit=function(e){return!!this._attachedCamera&&(this._attachedCamera.radius===e&&!this._radiusIsAnimating)},t.prototype._applyBoundRadiusAnimation=function(i){var r=this;if(this._attachedCamera){this._radiusBounceTransition||(t.EasingFunction.setEasingMode(t.EasingMode),this._radiusBounceTransition=e.Animation.CreateAnimation("radius",e.Animation.ANIMATIONTYPE_FLOAT,60,t.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;var n=e.Animation.TransitionTo("radius",this._attachedCamera.radius+i,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,(function(){return r._clearAnimationLocks()}));n&&this._animatables.push(n)}},t.prototype._clearAnimationLocks=function(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)},t.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()},t.EasingFunction=new e.BackEase(.3),t.EasingMode=e.EasingFunction.EASINGMODE_EASEOUT,t})();e.BouncingBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}return Object.defineProperty(t.prototype,"name",{get:function(){return"AutoRotation"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(e){this._zoomStopsAnimation=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"idleRotationSpeed",{get:function(){return this._idleRotationSpeed},set:function(e){this._idleRotationSpeed=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"idleRotationWaitTime",{get:function(){return this._idleRotationWaitTime},set:function(e){this._idleRotationWaitTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"idleRotationSpinupTime",{get:function(){return this._idleRotationSpinupTime},set:function(e){this._idleRotationSpinupTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationInProgress",{get:function(){return Math.abs(this._cameraRotationSpeed)>0},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(t){var i=this;this._attachedCamera=t;var r=this._attachedCamera.getScene();this._onPrePointerObservableObserver=r.onPrePointerObservable.add((function(t){if(t.type===e.PointerEventTypes.POINTERDOWN)return void(i._isPointerDown=!0);t.type===e.PointerEventTypes.POINTERUP&&(i._isPointerDown=!1)})),this._onAfterCheckInputsObserver=t.onAfterCheckInputsObservable.add((function(){var t=e.Tools.Now,r=0;null!=i._lastFrameTime&&(r=t-i._lastFrameTime),i._lastFrameTime=t,i._applyUserInteraction();var n=t-i._lastInteractionTime-i._idleRotationWaitTime,o=Math.max(Math.min(n/i._idleRotationSpinupTime,1),0);i._cameraRotationSpeed=i._idleRotationSpeed*o,i._attachedCamera&&(i._attachedCamera.alpha-=i._cameraRotationSpeed*(r/1e3))}))},t.prototype.detach=function(){if(this._attachedCamera){var e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}},t.prototype._userIsZooming=function(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset},t.prototype._shouldAnimationStopForInteraction=function(){if(!this._attachedCamera)return!1;var e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()},t.prototype._applyUserInteraction=function(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=e.Tools.Now)},t.prototype._userIsMoving=function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},t})();e.AutoRotationBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}return e})();e.NullEngineOptions=t;var i=(function(i){function r(r){void 0===r&&(r=new t);var n=i.call(this,null)||this;return void 0===r.deterministicLockstep&&(r.deterministicLockstep=!1),void 0===r.lockstepMaxSteps&&(r.lockstepMaxSteps=4),n._options=r,n._caps=new e.EngineCapabilities,n._caps.maxTexturesImageUnits=16,n._caps.maxVertexTextureImageUnits=16,n._caps.maxTextureSize=512,n._caps.maxCubemapTextureSize=512,n._caps.maxRenderTextureSize=512,n._caps.maxVertexAttribs=16,n._caps.maxVaryingVectors=16,n._caps.maxFragmentUniformVectors=16,n._caps.maxVertexUniformVectors=16,n._caps.standardDerivatives=!1,n._caps.astc=null,n._caps.s3tc=null,n._caps.pvrtc=null,n._caps.etc1=null,n._caps.etc2=null,n._caps.textureAnisotropicFilterExtension=null,n._caps.maxAnisotropy=0,n._caps.uintIndices=!1,n._caps.fragmentDepthSupported=!1,n._caps.highPrecisionShaderSupported=!0,n._caps.colorBufferFloat=!1,n._caps.textureFloat=!1,n._caps.textureFloatLinearFiltering=!1,n._caps.textureFloatRender=!1,n._caps.textureHalfFloat=!1,n._caps.textureHalfFloatLinearFiltering=!1,n._caps.textureHalfFloatRender=!1,n._caps.textureLOD=!1,n._caps.drawBuffersExtension=!1,n._caps.depthTextureExtension=!1,n._caps.vertexArrayObject=!1,n._caps.instancedArrays=!1,e.Tools.Log("Babylon.js null engine (v"+e.Engine.Version+") launched"),"undefined"==typeof URL&&(URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(Blob=function(){}),n}return o(r,i),r.prototype.isDeterministicLockStep=function(){return this._options.deterministicLockstep},r.prototype.getLockstepMaxSteps=function(){return this._options.lockstepMaxSteps},r.prototype.getHardwareScalingLevel=function(){return 1},r.prototype.createVertexBuffer=function(e){return{capacity:0,references:1,is32Bits:!1}},r.prototype.createIndexBuffer=function(e){return{capacity:0,references:1,is32Bits:!1}},r.prototype.clear=function(e,t,i,r){void 0===r&&(r=!1)},r.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth},r.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight},r.prototype.setViewport=function(e,t,i){this._cachedViewport=e},r.prototype.createShaderProgram=function(e,t,i,r){return{transformFeedback:null,__SPECTOR_rebuildProgram:null}},r.prototype.getUniforms=function(e,t){return[]},r.prototype.getAttributes=function(e,t){return[]},r.prototype.bindSamplers=function(e){this._currentEffect=null},r.prototype.enableEffect=function(e){this._currentEffect=e,e.onBind&&e.onBind(e),e.onBindObservable.notifyObservers(e)},r.prototype.setState=function(e,t,i,r){void 0===t&&(t=0),void 0===r&&(r=!1)},r.prototype.setIntArray=function(e,t){},r.prototype.setIntArray2=function(e,t){},r.prototype.setIntArray3=function(e,t){},r.prototype.setIntArray4=function(e,t){},r.prototype.setFloatArray=function(e,t){},r.prototype.setFloatArray2=function(e,t){},r.prototype.setFloatArray3=function(e,t){},r.prototype.setFloatArray4=function(e,t){},r.prototype.setArray=function(e,t){},r.prototype.setArray2=function(e,t){},r.prototype.setArray3=function(e,t){},r.prototype.setArray4=function(e,t){},r.prototype.setMatrices=function(e,t){},r.prototype.setMatrix=function(e,t){},r.prototype.setMatrix3x3=function(e,t){},r.prototype.setMatrix2x2=function(e,t){},r.prototype.setFloat=function(e,t){},r.prototype.setFloat2=function(e,t,i){},r.prototype.setFloat3=function(e,t,i,r){},r.prototype.setBool=function(e,t){},r.prototype.setFloat4=function(e,t,i,r,n){},r.prototype.setColor3=function(e,t){},r.prototype.setColor4=function(e,t,i){},r.prototype.setAlphaMode=function(t,i){void 0===i&&(i=!1),this._alphaMode!==t&&(this._alphaState.alphaBlend=t!==e.Engine.ALPHA_DISABLE,i||this.setDepthWrite(t===e.Engine.ALPHA_DISABLE),this._alphaMode=t)},r.prototype.bindBuffers=function(e,t,i){},r.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilState.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},r.prototype.draw=function(e,t,i,r){},r.prototype.drawElementsType=function(e,t,i,r){},r.prototype.drawArraysType=function(e,t,i,r){},r.prototype._createTexture=function(){return{}},r.prototype._releaseTexture=function(e){},r.prototype.createTexture=function(t,i,r,n,o,s,a,l,h,c){void 0===o&&(o=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===s&&(s=null),void 0===a&&(a=null),void 0===l&&(l=null);var u=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_URL),f=String(t);return u.url=f,u.generateMipMaps=!i,u.samplingMode=o,u.invertY=r,u.baseWidth=this._options.textureSize,u.baseHeight=this._options.textureSize,u.width=this._options.textureSize,u.height=this._options.textureSize,c&&(u.format=c),u.isReady=!0,s&&s(),this._internalTexturesCache.push(u),u},r.prototype.createRenderTargetTexture=function(t,i){var r=new e.RenderTargetCreationOptions;void 0!==i&&"object"==typeof i?(r.generateMipMaps=i.generateMipMaps,r.generateDepthBuffer=void 0===i.generateDepthBuffer||i.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&i.generateStencilBuffer,r.type=void 0===i.type?e.Engine.TEXTURETYPE_UNSIGNED_INT:i.type,r.samplingMode=void 0===i.samplingMode?e.Texture.TRILINEAR_SAMPLINGMODE:i.samplingMode):(r.generateMipMaps=i,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.type=e.Engine.TEXTURETYPE_UNSIGNED_INT,r.samplingMode=e.Texture.TRILINEAR_SAMPLINGMODE);var n=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RENDERTARGET),o=t.width||t,s=t.height||t;return n._depthStencilBuffer={},n._framebuffer={},n.baseWidth=o,n.baseHeight=s,n.width=o,n.height=s,n.isReady=!0,n.samples=1,n.generateMipMaps=!!r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,n._generateDepthBuffer=r.generateDepthBuffer,n._generateStencilBuffer=!!r.generateStencilBuffer,this._internalTexturesCache.push(n),n},r.prototype.updateTextureSamplingMode=function(e,t){t.samplingMode=e},r.prototype.bindFramebuffer=function(e,t,i,r,n){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer,this._cachedViewport&&!n&&this.setViewport(this._cachedViewport,i,r)},r.prototype.unBindFramebuffer=function(e,t,i){void 0===t&&(t=!1),this._currentRenderTarget=null,i&&(e._MSAAFramebuffer&&(this._currentFramebuffer=e._framebuffer),i()),this._currentFramebuffer=null},r.prototype.createDynamicVertexBuffer=function(e){return{capacity:1,references:1,is32Bits:!1}},r.prototype.updateDynamicTexture=function(e,t,i,r,n){void 0===r&&(r=!1)},r.prototype.getError=function(){return 0},r.prototype._getUnpackAlignement=function(){return 1},r.prototype._unpackFlipY=function(e){},r.prototype.updateDynamicIndexBuffer=function(e,t,i){void 0===i&&(i=0)},r.prototype.updateDynamicVertexBuffer=function(e,t,i,r){},r.prototype._bindTextureDirectly=function(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)},r.prototype._bindTexture=function(e,t){e<0||this._bindTextureDirectly(0,t)},r.prototype._releaseBuffer=function(e){return 0===--e.references},r.prototype.releaseEffects=function(){},r.prototype.displayLoadingUI=function(){},r.prototype.hideLoadingUI=function(){},r.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,r,n,o,s){void 0===o&&(o=0),void 0===s&&(s=0)},r.prototype._uploadDataToTextureDirectly=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},r.prototype._uploadArrayBufferViewToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},r.prototype._uploadImageToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},r})(e.Engine);e.NullEngine=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){this.engine=t,this._captureGPUFrameTime=!1,this._gpuFrameTime=new e.PerfCounter,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new e.PerfCounter,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}return Object.defineProperty(t.prototype,"gpuFrameTimeCounter",{get:function(){return this._gpuFrameTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureGPUFrameTime",{get:function(){return this._captureGPUFrameTime},set:function(e){var t=this;e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.engine.onBeginFrameObservable.add((function(){t._gpuFrameTimeToken||(t._gpuFrameTimeToken=t.engine.startTimeQuery())})),this._onEndFrameObserver=this.engine.onEndFrameObservable.add((function(){if(t._gpuFrameTimeToken){var e=t.engine.endTimeQuery(t._gpuFrameTimeToken);e>-1&&(t._gpuFrameTimeToken=null,t._gpuFrameTime.fetchNewFrame(),t._gpuFrameTime.addCount(e,!0))}}))):(this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shaderCompilationTimeCounter",{get:function(){return this._shaderCompilationTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureShaderCompilationTime",{get:function(){return this._captureShaderCompilationTime},set:function(e){var t=this;e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add((function(){t._shaderCompilationTime.fetchNewFrame(),t._shaderCompilationTime.beginMonitoring()})),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add((function(){t._shaderCompilationTime.endMonitoring()}))):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null},t})();e.EngineInstrumentation=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){var i=this;this.scene=t,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new e.PerfCounter,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new e.PerfCounter,this._captureFrameTime=!1,this._frameTime=new e.PerfCounter,this._captureRenderTime=!1,this._renderTime=new e.PerfCounter,this._captureInterFrameTime=!1,this._interFrameTime=new e.PerfCounter,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new e.PerfCounter,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new e.PerfCounter,this._capturePhysicsTime=!1,this._physicsTime=new e.PerfCounter,this._captureAnimationsTime=!1,this._animationsTime=new e.PerfCounter,this._captureCameraRenderTime=!1,this._cameraRenderTime=new e.PerfCounter,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=t.onBeforeAnimationsObservable.add((function(){i._captureActiveMeshesEvaluationTime&&i._activeMeshesEvaluationTime.fetchNewFrame(),i._captureRenderTargetsRenderTime&&i._renderTargetsRenderTime.fetchNewFrame(),i._captureFrameTime&&(e.Tools.StartPerformanceCounter("Scene rendering"),i._frameTime.beginMonitoring()),i._captureInterFrameTime&&i._interFrameTime.endMonitoring(),i._captureParticlesRenderTime&&i._particlesRenderTime.fetchNewFrame(),i._captureSpritesRenderTime&&i._spritesRenderTime.fetchNewFrame(),i._captureAnimationsTime&&i._animationsTime.beginMonitoring(),i.scene.getEngine()._drawCalls.fetchNewFrame(),i.scene.getEngine()._textureCollisions.fetchNewFrame()})),this._onAfterRenderObserver=t.onAfterRenderObservable.add((function(){i._captureFrameTime&&(e.Tools.EndPerformanceCounter("Scene rendering"),i._frameTime.endMonitoring()),i._captureRenderTime&&i._renderTime.endMonitoring(!1),i._captureInterFrameTime&&i._interFrameTime.beginMonitoring()}))}return Object.defineProperty(t.prototype,"activeMeshesEvaluationTimeCounter",{get:function(){return this._activeMeshesEvaluationTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureActiveMeshesEvaluationTime",{get:function(){return this._captureActiveMeshesEvaluationTime},set:function(t){var i=this;t!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=t,t?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add((function(){e.Tools.StartPerformanceCounter("Active meshes evaluation"),i._activeMeshesEvaluationTime.beginMonitoring()})),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add((function(){e.Tools.EndPerformanceCounter("Active meshes evaluation"),i._activeMeshesEvaluationTime.endMonitoring()}))):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderTargetsRenderTimeCounter",{get:function(){return this._renderTargetsRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureRenderTargetsRenderTime",{get:function(){return this._captureRenderTargetsRenderTime},set:function(t){var i=this;t!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=t,t?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add((function(){e.Tools.StartPerformanceCounter("Render targets rendering"),i._renderTargetsRenderTime.beginMonitoring()})),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add((function(){e.Tools.EndPerformanceCounter("Render targets rendering"),i._renderTargetsRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"particlesRenderTimeCounter",{get:function(){return this._particlesRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureParticlesRenderTime",{get:function(){return this._captureParticlesRenderTime},set:function(t){var i=this;t!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=t,t?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add((function(){e.Tools.StartPerformanceCounter("Particles"),i._particlesRenderTime.beginMonitoring()})),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add((function(){e.Tools.EndPerformanceCounter("Particles"),i._particlesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"spritesRenderTimeCounter",{get:function(){return this._spritesRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureSpritesRenderTime",{get:function(){return this._captureSpritesRenderTime},set:function(t){var i=this;t!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=t,t?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add((function(){e.Tools.StartPerformanceCounter("Sprites"),i._spritesRenderTime.beginMonitoring()})),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add((function(){e.Tools.EndPerformanceCounter("Sprites"),i._spritesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"physicsTimeCounter",{get:function(){return this._physicsTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"capturePhysicsTime",{get:function(){return this._capturePhysicsTime},set:function(t){var i=this;t!==this._capturePhysicsTime&&(this._capturePhysicsTime=t,t?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add((function(){e.Tools.StartPerformanceCounter("Physics"),i._physicsTime.beginMonitoring()})), -this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add((function(){e.Tools.EndPerformanceCounter("Physics"),i._physicsTime.endMonitoring()}))):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationsTimeCounter",{get:function(){return this._animationsTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureAnimationsTime",{get:function(){return this._captureAnimationsTime},set:function(e){var t=this;e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add((function(){t._animationsTime.endMonitoring()})):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"frameTimeCounter",{get:function(){return this._frameTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureFrameTime",{get:function(){return this._captureFrameTime},set:function(e){this._captureFrameTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"interFrameTimeCounter",{get:function(){return this._interFrameTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureInterFrameTime",{get:function(){return this._captureInterFrameTime},set:function(e){this._captureInterFrameTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderTimeCounter",{get:function(){return this._renderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureRenderTime",{get:function(){return this._captureRenderTime},set:function(t){var i=this;t!==this._captureRenderTime&&(this._captureRenderTime=t,t?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add((function(){i._renderTime.beginMonitoring(),e.Tools.StartPerformanceCounter("Main render")})),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add((function(){i._renderTime.endMonitoring(!1),e.Tools.EndPerformanceCounter("Main render")}))):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraRenderTimeCounter",{get:function(){return this._cameraRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureCameraRenderTime",{get:function(){return this._captureCameraRenderTime},set:function(t){var i=this;t!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=t,t?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add((function(t){i._cameraRenderTime.beginMonitoring(),e.Tools.StartPerformanceCounter("Rendering camera "+t.name)})),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add((function(t){i._cameraRenderTime.endMonitoring(!1),e.Tools.EndPerformanceCounter("Rendering camera "+t.name)}))):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"drawCallsCounter",{get:function(){return this.scene.getEngine()._drawCalls},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"textureCollisionsCounter",{get:function(){return this.scene.getEngine()._textureCollisions},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null,this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null,this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null},t})();e.SceneInstrumentation=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this._timeElapsedQueryEnded=!1}return e})();e._TimeToken=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.DIFFUSEDIRECTUV=0,t.GAMMADIFFUSE=!1,t.DIFFUSEHASALPHA=!1,t.OPACITYFRESNEL=!1,t.REFLECTIONBLUR=!1,t.REFLECTIONFRESNEL=!1,t.REFLECTIONFALLOFF=!1,t.TEXTURELODSUPPORT=!1,t.PREMULTIPLYALPHA=!1,t.USERGBCOLOR=!1,t.USEHIGHLIGHTANDSHADOWCOLORS=!1,t.NOISE=!1,t.REFLECTIONBGR=!1,t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=!1,t.CONTRAST=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.EXPOSURE=!1,t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.EQUIRECTANGULAR_RELFECTION_FOV=!1,t.MAINUV1=!1,t.MAINUV2=!1,t.UV1=!1,t.UV2=!1,t.CLIPPLANE=!1,t.POINTSIZE=!1,t.FOG=!1,t.NORMAL=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.SHADOWFLOAT=!1,t.rebuild(),t}return o(t,e),t})(e.MaterialDefines),i=(function(i){function r(t,r){var n=i.call(this,t,r)||this;return n.primaryColor=e.Color3.White(),n._primaryColorShadowLevel=0,n._primaryColorHighlightLevel=0,n.reflectionTexture=null,n.reflectionBlur=0,n.diffuseTexture=null,n._shadowLights=null,n.shadowLights=null,n.shadowLevel=0,n.sceneCenter=e.Vector3.Zero(),n.opacityFresnel=!0,n.reflectionFresnel=!1,n.reflectionFalloffDistance=0,n.reflectionAmount=1,n.reflectionReflectance0=.05,n.reflectionReflectance90=.5,n.useRGBColor=!0,n.enableNoise=!1,n._fovMultiplier=1,n.useEquirectangularFOV=!1,n._maxSimultaneousLights=4,n.maxSimultaneousLights=4,n._imageProcessingObserver=null,n.switchToBGR=!1,n._renderTargets=new e.SmartArray(16),n._reflectionControls=e.Vector4.Zero(),n._white=e.Color3.White(),n._primaryShadowColor=e.Color3.Black(),n._primaryHighlightColor=e.Color3.Black(),n._attachImageProcessingConfiguration(null),n.getRenderTargetTextures=function(){return n._renderTargets.reset(),n._diffuseTexture&&n._diffuseTexture.isRenderTarget&&n._renderTargets.push(n._diffuseTexture),n._reflectionTexture&&n._reflectionTexture.isRenderTarget&&n._renderTargets.push(n._reflectionTexture),n._renderTargets},n}return o(r,i),Object.defineProperty(r.prototype,"_perceptualColor",{get:function(){return this.__perceptualColor},set:function(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"primaryColorShadowLevel",{get:function(){return this._primaryColorShadowLevel},set:function(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"primaryColorHighlightLevel",{get:function(){return this._primaryColorHighlightLevel},set:function(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"reflectionStandardFresnelWeight",{set:function(e){var t=e;t<.5?(t*=2,this.reflectionReflectance0=r.StandardReflectance0*t,this.reflectionReflectance90=r.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=r.StandardReflectance0+(1-r.StandardReflectance0)*t,this.reflectionReflectance90=r.StandardReflectance90+(1-r.StandardReflectance90)*t)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"fovMultiplier",{get:function(){return this._fovMultiplier},set:function(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))},enumerable:!0,configurable:!0}),r.prototype._attachImageProcessingConfiguration=function(e){var t=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((function(e){t._computePrimaryColorFromPerceptualColor(),t._markAllSubMeshesAsImageProcessingDirty()}))))},Object.defineProperty(r.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this.imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorCurves",{get:function(){return this.imageProcessingConfiguration.colorCurves},set:function(e){this.imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),r.prototype.needAlphaTesting=function(){return!0},r.prototype.needAlphaBlending=function(){return this.alpha<0||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha},r.prototype.isReadyForSubMesh=function(i,r,n){var o=this;if(void 0===n&&(n=!1),r.effect&&this.isFrozen&&this._wasPreviouslyReady)return!0;r._materialDefines||(r._materialDefines=new t);var s=this.getScene(),a=r._materialDefines;if(!this.checkReadyOnEveryCall&&r.effect&&a._renderId===s.getRenderId())return!0;var l=s.getEngine();if(e.MaterialHelper.PrepareDefinesForLights(s,i,a,!1,this._maxSimultaneousLights),a._needNormals=!0,a._areTexturesDirty){if(a._needUVs=!1,s.texturesEnabled){if(s.getEngine().getCaps().textureLOD&&(a.TEXTURELODSUPPORT=!0),this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture,a,"DIFFUSE"),a.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,a.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,a.OPACITYFRESNEL=this._opacityFresnel}else a.DIFFUSE=!1,a.DIFFUSEHASALPHA=!1,a.GAMMADIFFUSE=!1,a.OPACITYFRESNEL=!1;var h=this._reflectionTexture;if(h&&e.StandardMaterial.ReflectionTextureEnabled){if(!h.isReadyOrNotBlocking())return!1;switch(a.REFLECTION=!0,a.GAMMAREFLECTION=h.gammaSpace,a.RGBDREFLECTION=h.isRGBD,a.REFLECTIONBLUR=this._reflectionBlur>0,a.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!h.invertZ:h.invertZ,a.LODINREFLECTIONALPHA=h.lodLevelInAlpha,a.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,a.REFLECTIONBGR=this.switchToBGR,h.coordinatesMode===e.Texture.INVCUBIC_MODE&&(a.INVERTCUBICMAP=!0),a.REFLECTIONMAP_3D=h.isCube,h.coordinatesMode){case e.Texture.EXPLICIT_MODE:a.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:a.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:a.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:a.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:a.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:default:a.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(a.REFLECTIONFRESNEL=!0,a.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(a.REFLECTIONFRESNEL=!1,a.REFLECTIONFALLOFF=!1)}else a.REFLECTION=!1,a.REFLECTIONFRESNEL=!1,a.REFLECTIONFALLOFF=!1,a.REFLECTIONBLUR=!1,a.REFLECTIONMAP_3D=!1,a.REFLECTIONMAP_SPHERICAL=!1,a.REFLECTIONMAP_PLANAR=!1,a.REFLECTIONMAP_CUBIC=!1,a.REFLECTIONMAP_PROJECTION=!1,a.REFLECTIONMAP_SKYBOX=!1,a.REFLECTIONMAP_EXPLICIT=!1,a.REFLECTIONMAP_EQUIRECTANGULAR=!1,a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,a.INVERTCUBICMAP=!1,a.REFLECTIONMAP_OPPOSITEZ=!1,a.LODINREFLECTIONALPHA=!1,a.GAMMAREFLECTION=!1,a.RGBDREFLECTION=!1}a.PREMULTIPLYALPHA=this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED||this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF,a.USERGBCOLOR=this._useRGBColor,a.NOISE=this._enableNoise}if(a._areLightsDirty&&(a.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel)),a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a)}if(e.MaterialHelper.PrepareDefinesForMisc(i,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(i),a),e.MaterialHelper.PrepareDefinesForFrameBoundValues(s,l,a,n),e.MaterialHelper.PrepareDefinesForAttributes(i,a,!1,!0,!1)&&i&&(s.getEngine().getCaps().standardDerivatives||i.isVerticesDataPresent(e.VertexBuffer.NormalKind)||(i.createNormals(!0),e.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: "+i.name))),a.isDirty){a.markAsProcessed(),s.resetCachedMaterial();var c=new e.EffectFallbacks;a.FOG&&c.addFallback(0,"FOG"),a.POINTSIZE&&c.addFallback(1,"POINTSIZE"),e.MaterialHelper.HandleFallbacksForShadows(a,c,this._maxSimultaneousLights),a.NUM_BONE_INFLUENCERS>0&&c.addCPUSkinningFallback(0,i);var u=[e.VertexBuffer.PositionKind];a.NORMAL&&u.push(e.VertexBuffer.NormalKind),a.UV1&&u.push(e.VertexBuffer.UVKind),a.UV2&&u.push(e.VertexBuffer.UV2Kind),e.MaterialHelper.PrepareAttributesForBones(u,i,a,c),e.MaterialHelper.PrepareAttributesForInstances(u,a);var f=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","vClipPlane","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"],d=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],p=["Material","Scene"];e.ImageProcessingConfiguration&&(e.ImageProcessingConfiguration.PrepareUniforms(f,a),e.ImageProcessingConfiguration.PrepareSamplers(d,a)),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:f,uniformBuffersNames:p,samplers:d,defines:a,maxSimultaneousLights:this._maxSimultaneousLights});var m=function(e){o.onCompiled&&o.onCompiled(e),o.bindSceneUniformBuffer(e,s.getSceneUniformBuffer())},_=a.toString();r.setEffect(s.getEngine().createEffect("background",{attributes:u,uniformsNames:f,uniformBuffersNames:p,samplers:d,defines:_,fallbacks:c,onCompiled:m,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},l),a),this.buildUniformLayout()}return!(!r.effect||!r.effect.isReady())&&(a._renderId=s.getRenderId(),this._wasPreviouslyReady=!0,!0)},r.prototype._computePrimaryColorFromPerceptualColor=function(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())},r.prototype._computePrimaryColors=function(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))},r.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.create()},r.prototype.unbind=function(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),i.prototype.unbind.call(this)},r.prototype.bindOnlyWorldMatrix=function(e){this._activeEffect.setMatrix("world",e)},r.prototype.bindForSubMesh=function(t,i,r){var n=this.getScene(),o=r._materialDefines;if(o){var s=r.effect;if(s){this._activeEffect=s,this.bindOnlyWorldMatrix(t),e.MaterialHelper.BindBonesParameters(i,this._activeEffect);var a=this._mustRebind(n,s,i.visibility);if(a){this._uniformBuffer.bindToEffect(s,"Material"),this.bindViewProjection(s);var l=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(n.texturesEnabled&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),e.MaterialHelper.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),l&&e.StandardMaterial.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",l.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),o.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),n.texturesEnabled&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),l&&e.StandardMaterial.ReflectionTextureEnabled&&(o.REFLECTIONBLUR&&o.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",l):o.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",l._lodTextureMid||l),this._uniformBuffer.setTexture("reflectionSamplerLow",l._lodTextureLow||l),this._uniformBuffer.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)):this._uniformBuffer.setTexture("reflectionSampler",l),o.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w)))),e.MaterialHelper.BindClipPlane(this._activeEffect,n),e.MaterialHelper.BindEyePosition(s,n)}!a&&this.isFrozen||(n.lightsEnabled&&e.MaterialHelper.BindLights(n,i,this._activeEffect,o,this._maxSimultaneousLights,!1),this.bindView(s),e.MaterialHelper.BindFogParameters(n,i,this._activeEffect),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(i,this._activeEffect)}}},r.prototype.dispose=function(e,t){void 0===e&&(e=!1),void 0===t&&(t=!1),t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),i.prototype.dispose.call(this,e)},r.prototype.clone=function(t){var i=this;return e.SerializationHelper.Clone((function(){return new r(t,i.getScene())}),this)},r.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.BackgroundMaterial",t},r.prototype.getClassName=function(){return"BackgroundMaterial"},r.Parse=function(t,i,n){return e.SerializationHelper.Parse((function(){return new r(t.name,i)}),t,i,n)},r.StandardReflectance0=.05,r.StandardReflectance90=.5,n([e.serializeAsColor3()],r.prototype,"_primaryColor",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"primaryColor",void 0),n([e.serializeAsColor3()],r.prototype,"__perceptualColor",void 0),n([e.serialize()],r.prototype,"_primaryColorShadowLevel",void 0),n([e.serialize()],r.prototype,"_primaryColorHighlightLevel",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"primaryColorHighlightLevel",null),n([e.serializeAsTexture()],r.prototype,"_reflectionTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionTexture",void 0),n([e.serialize()],r.prototype,"_reflectionBlur",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionBlur",void 0),n([e.serializeAsTexture()],r.prototype,"_diffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"diffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"shadowLights",void 0),n([e.serialize()],r.prototype,"_shadowLevel",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"shadowLevel",void 0),n([e.serializeAsVector3()],r.prototype,"_sceneCenter",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"sceneCenter",void 0),n([e.serialize()],r.prototype,"_opacityFresnel",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"opacityFresnel",void 0),n([e.serialize()],r.prototype,"_reflectionFresnel",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionFresnel",void 0),n([e.serialize()],r.prototype,"_reflectionFalloffDistance",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionFalloffDistance",void 0),n([e.serialize()],r.prototype,"_reflectionAmount",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionAmount",void 0),n([e.serialize()],r.prototype,"_reflectionReflectance0",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionReflectance0",void 0),n([e.serialize()],r.prototype,"_reflectionReflectance90",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionReflectance90",void 0),n([e.serialize()],r.prototype,"_useRGBColor",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useRGBColor",void 0),n([e.serialize()],r.prototype,"_enableNoise",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"enableNoise",void 0),n([e.serialize()],r.prototype,"_maxSimultaneousLights",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"maxSimultaneousLights",void 0),n([e.serializeAsImageProcessingConfiguration()],r.prototype,"_imageProcessingConfiguration",void 0),r})(e.PushMaterial);e.BackgroundMaterial=i})(r||(r={}));var r,s=this&&this.__assign||Object.assign||function(e){for(var t,i=1,r=arguments.length;ii&&(i=2*a,r=i),i*=1.1,r*=1.5,n=o.min.add(s.scale(.5)),n.y=o.min.y-this._options.groundYBias}return{groundSize:i,skyboxSize:r,rootPosition:n}},t.prototype._setupGround=function(t){var i=this;this._ground&&!this._ground.isDisposed()||(this._ground=e.Mesh.CreatePlane("BackgroundPlane",t.groundSize,this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((function(){i._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow},t.prototype._setupGroundMaterial=function(){this._groundMaterial||(this._groundMaterial=new e.BackgroundMaterial("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)},t.prototype._setupGroundDiffuseTexture=function(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof e.BaseTexture)return void(this._groundMaterial.diffuseTexture=this._options.groundTexture);var t=new e.Texture(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler);t.gammaSpace=!1,t.hasAlpha=!0,this._groundMaterial.diffuseTexture=t}},t.prototype._setupGroundMirrorTexture=function(t){var i=e.Texture.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new e.MirrorTexture("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,e.Texture.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new e.Plane(0,-1,0,t.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=i,this._groundMirror.wrapV=i,this._groundMirror.gammaSpace=!1,this._groundMirror.renderList))for(var r=0;rthis.occlusionRetryCount))return;this._isOcclusionQueryInProgress=!1,this._occlusionInternalRetryCounter=0,this._isOccluded=this.occlusionType!==e.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC&&this._isOccluded}}var r=this.getScene();if(r.getBoundingBoxRenderer){var n=r.getBoundingBoxRenderer();this._occlusionQuery||(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(this.occlusionQueryAlgorithmType,this._occlusionQuery),n.renderOcclusionBoundingBox(this),t.endOcclusionQuery(this.occlusionQueryAlgorithmType),this._isOcclusionQueryInProgress=!0}}})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===r&&(r=256),void 0===n&&(n=e.Engine.LastCreatedScene);var a=t.call(this,i,r,"noise",n,o,s)||this;return a._time=0,a.brightness=.2,a.octaves=3,a.persistence=.8,a.animationSpeedFactor=1,a._updateShaderUniforms(),a}return o(i,t),i.prototype._updateShaderUniforms=function(){var e=this.getScene();e&&(this._time+=e.getAnimationRatio()*this.animationSpeedFactor*.01,this.setFloat("brightness",this.brightness),this.setInt("octaves",this.octaves),this.setFloat("persistence",this.persistence),this.setFloat("timeScale",this._time))},i.prototype.render=function(e){this._updateShaderUniforms(),t.prototype.render.call(this,e)},i.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this,t.prototype.serialize.call(this));return i.customType="BABYLON.NoiseProceduralTexture",i},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,t._size,r,void 0,t._generateMipMaps)}),t,r,n)},i})(e.ProceduralTexture);e.NoiseProceduralTexture=t})(r||(r={})),r.Effect.ShadersStore={defaultVertexShader:"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n",defaultPixelShader:"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#include\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include\n#include\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n", -pbrVertexShader:"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include\n\n#include\n\n#include\n\n#include[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include\n}",pbrPixelShader:"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include\n#include\n#include\n\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n\n#include\nvoid main(void) {\n#include\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include\n#include(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}",rgbdEncodePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}",rgbdDecodePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}",spritesVertexShader:"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}",spritesPixelShader:"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include\ngl_FragColor=color;\n}",particlesVertexShader:"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}",particlesPixelShader:"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}",colorVertexShader:"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}",colorPixelShader:"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}", -gpuRenderParticlesVertexShader:"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}",gpuRenderParticlesPixelShader:"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n",gpuUpdateParticlesVertexShader:"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}",gpuUpdateParticlesPixelShader:"#version 300 es\nvoid main() {\ndiscard;\n}\n",postprocessVertexShader:"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}",passPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}",shadowMapVertexShader:"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n\n#include\n#include\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",shadowMapPixelShader:"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}",depthBoxBlurPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}",proceduralVertexShader:"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}",depthVertexShader:"\nattribute vec3 position;\n#include\n\n#include\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",depthPixelShader:"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}",ssaoPixelShader:"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; imaxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}", +Object.defineProperty(t.prototype,"radiusScale",{get:function(){return this._radiusScale},set:function(e){this._radiusScale=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"positionScale",{get:function(){return this._positionScale},set:function(e){this._positionScale=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"defaultElevation",{get:function(){return this._defaultElevation},set:function(e){this._defaultElevation=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"elevationReturnTime",{get:function(){return this._elevationReturnTime},set:function(e){this._elevationReturnTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"elevationReturnWaitTime",{get:function(){return this._elevationReturnWaitTime},set:function(e){this._elevationReturnWaitTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(e){this._zoomStopsAnimation=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"framingTime",{get:function(){return this._framingTime},set:function(e){this._framingTime=e},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(i){var r=this;this._attachedCamera=i;var n=this._attachedCamera.getScene();t.EasingFunction.setEasingMode(t.EasingMode),this._onPrePointerObservableObserver=n.onPrePointerObservable.add((function(t){if(t.type===e.PointerEventTypes.POINTERDOWN)return void(r._isPointerDown=!0);t.type===e.PointerEventTypes.POINTERUP&&(r._isPointerDown=!1)})),this._onMeshTargetChangedObserver=i.onMeshTargetChangedObservable.add((function(e){e&&r.zoomOnMesh(e)})),this._onAfterCheckInputsObserver=i.onAfterCheckInputsObservable.add((function(){r._applyUserInteraction(),r._maintainCameraAboveGround()}))},t.prototype.detach=function(){if(this._attachedCamera){var e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}},t.prototype.zoomOnMesh=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=null),e.computeWorldMatrix(!0);var r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)},t.prototype.zoomOnMeshHierarchy=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=null),e.computeWorldMatrix(!0);var r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)},t.prototype.zoomOnMeshesHierarchy=function(t,i,r){void 0===i&&(i=!1),void 0===r&&(r=null);for(var n=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new e.Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=0;su.upperRadiusLimit?u.upperRadiusLimit:c),c):0},t.prototype._maintainCameraAboveGround=function(){var i=this;if(!(this._elevationReturnTime<0)){var r=e.Tools.Now-this._lastInteractionTime,n=.5*Math.PI-this._defaultElevation,o=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>o&&r>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=e.Animation.CreateAnimation("beta",e.Animation.ANIMATIONTYPE_FLOAT,60,t.EasingFunction));var s=e.Animation.TransitionTo("beta",n,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(function(){i._clearAnimationLocks(),i.stopAllAnimations()}));s&&this._animatables.push(s)}}},t.prototype._getFrustumSlope=function(){var t=this._attachedCamera;if(!t)return e.Vector2.Zero();var i=t.getScene().getEngine(),r=i.getAspectRatio(t),n=Math.tan(t.fov/2),o=n*r;return new e.Vector2(o,n)},t.prototype._clearAnimationLocks=function(){this._betaIsAnimating=!1},t.prototype._applyUserInteraction=function(){this.isUserIsMoving&&(this._lastInteractionTime=e.Tools.Now,this.stopAllAnimations(),this._clearAnimationLocks())},t.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()},Object.defineProperty(t.prototype,"isUserIsMoving",{get:function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},enumerable:!0,configurable:!0}),t.EasingFunction=new e.ExponentialEase,t.EasingMode=e.EasingFunction.EASINGMODE_EASEINOUT,t.IgnoreBoundsSizeMode=0,t.FitFrustumSidesMode=1,t})();e.FramingBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}return Object.defineProperty(t.prototype,"name",{get:function(){return"Bouncing"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"autoTransitionRange",{get:function(){return this._autoTransitionRange},set:function(e){var t=this;if(this._autoTransitionRange!==e){this._autoTransitionRange=e;var i=this._attachedCamera;i&&(e?this._onMeshTargetChangedObserver=i.onMeshTargetChangedObservable.add((function(e){if(e){e.computeWorldMatrix(!0);var i=e.getBoundingInfo().diagonalLength;t.lowerRadiusTransitionRange=.05*i,t.upperRadiusTransitionRange=.05*i}})):this._onMeshTargetChangedObserver&&i.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(e){var t=this;this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((function(){t._attachedCamera&&(t._isRadiusAtLimit(t._attachedCamera.lowerRadiusLimit)&&t._applyBoundRadiusAnimation(t.lowerRadiusTransitionRange),t._isRadiusAtLimit(t._attachedCamera.upperRadiusLimit)&&t._applyBoundRadiusAnimation(t.upperRadiusTransitionRange))}))},t.prototype.detach=function(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)},t.prototype._isRadiusAtLimit=function(e){return!!this._attachedCamera&&(this._attachedCamera.radius===e&&!this._radiusIsAnimating)},t.prototype._applyBoundRadiusAnimation=function(i){var r=this;if(this._attachedCamera){this._radiusBounceTransition||(t.EasingFunction.setEasingMode(t.EasingMode),this._radiusBounceTransition=e.Animation.CreateAnimation("radius",e.Animation.ANIMATIONTYPE_FLOAT,60,t.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;var n=e.Animation.TransitionTo("radius",this._attachedCamera.radius+i,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,(function(){return r._clearAnimationLocks()}));n&&this._animatables.push(n)}},t.prototype._clearAnimationLocks=function(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)},t.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()},t.EasingFunction=new e.BackEase(.3),t.EasingMode=e.EasingFunction.EASINGMODE_EASEOUT,t})();e.BouncingBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}return Object.defineProperty(t.prototype,"name",{get:function(){return"AutoRotation"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(e){this._zoomStopsAnimation=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"idleRotationSpeed",{get:function(){return this._idleRotationSpeed},set:function(e){this._idleRotationSpeed=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"idleRotationWaitTime",{get:function(){return this._idleRotationWaitTime},set:function(e){this._idleRotationWaitTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"idleRotationSpinupTime",{get:function(){return this._idleRotationSpinupTime},set:function(e){this._idleRotationSpinupTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationInProgress",{get:function(){return Math.abs(this._cameraRotationSpeed)>0},enumerable:!0,configurable:!0}),t.prototype.init=function(){},t.prototype.attach=function(t){var i=this;this._attachedCamera=t;var r=this._attachedCamera.getScene();this._onPrePointerObservableObserver=r.onPrePointerObservable.add((function(t){if(t.type===e.PointerEventTypes.POINTERDOWN)return void(i._isPointerDown=!0);t.type===e.PointerEventTypes.POINTERUP&&(i._isPointerDown=!1)})),this._onAfterCheckInputsObserver=t.onAfterCheckInputsObservable.add((function(){var t=e.Tools.Now,r=0;null!=i._lastFrameTime&&(r=t-i._lastFrameTime),i._lastFrameTime=t,i._applyUserInteraction();var n=t-i._lastInteractionTime-i._idleRotationWaitTime,o=Math.max(Math.min(n/i._idleRotationSpinupTime,1),0);i._cameraRotationSpeed=i._idleRotationSpeed*o,i._attachedCamera&&(i._attachedCamera.alpha-=i._cameraRotationSpeed*(r/1e3))}))},t.prototype.detach=function(){if(this._attachedCamera){var e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}},t.prototype._userIsZooming=function(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset},t.prototype._shouldAnimationStopForInteraction=function(){if(!this._attachedCamera)return!1;var e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()},t.prototype._applyUserInteraction=function(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=e.Tools.Now)},t.prototype._userIsMoving=function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},t})();e.AutoRotationBehavior=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}return e})();e.NullEngineOptions=t;var i=(function(i){function r(r){void 0===r&&(r=new t);var n=i.call(this,null)||this;return void 0===r.deterministicLockstep&&(r.deterministicLockstep=!1),void 0===r.lockstepMaxSteps&&(r.lockstepMaxSteps=4),n._options=r,n._caps=new e.EngineCapabilities,n._caps.maxTexturesImageUnits=16,n._caps.maxVertexTextureImageUnits=16,n._caps.maxTextureSize=512,n._caps.maxCubemapTextureSize=512,n._caps.maxRenderTextureSize=512,n._caps.maxVertexAttribs=16,n._caps.maxVaryingVectors=16,n._caps.maxFragmentUniformVectors=16,n._caps.maxVertexUniformVectors=16,n._caps.standardDerivatives=!1,n._caps.astc=null,n._caps.s3tc=null,n._caps.pvrtc=null,n._caps.etc1=null,n._caps.etc2=null,n._caps.textureAnisotropicFilterExtension=null,n._caps.maxAnisotropy=0,n._caps.uintIndices=!1,n._caps.fragmentDepthSupported=!1,n._caps.highPrecisionShaderSupported=!0,n._caps.colorBufferFloat=!1,n._caps.textureFloat=!1,n._caps.textureFloatLinearFiltering=!1,n._caps.textureFloatRender=!1,n._caps.textureHalfFloat=!1,n._caps.textureHalfFloatLinearFiltering=!1,n._caps.textureHalfFloatRender=!1,n._caps.textureLOD=!1,n._caps.drawBuffersExtension=!1,n._caps.depthTextureExtension=!1,n._caps.vertexArrayObject=!1,n._caps.instancedArrays=!1,e.Tools.Log("Babylon.js null engine (v"+e.Engine.Version+") launched"),"undefined"==typeof URL&&(URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(Blob=function(){}),n}return o(r,i),r.prototype.isDeterministicLockStep=function(){return this._options.deterministicLockstep},r.prototype.getLockstepMaxSteps=function(){return this._options.lockstepMaxSteps},r.prototype.getHardwareScalingLevel=function(){return 1},r.prototype.createVertexBuffer=function(e){return{capacity:0,references:1,is32Bits:!1}},r.prototype.createIndexBuffer=function(e){return{capacity:0,references:1,is32Bits:!1}},r.prototype.clear=function(e,t,i,r){void 0===r&&(r=!1)},r.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth},r.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight},r.prototype.setViewport=function(e,t,i){this._cachedViewport=e},r.prototype.createShaderProgram=function(e,t,i,r){return{transformFeedback:null,__SPECTOR_rebuildProgram:null}},r.prototype.getUniforms=function(e,t){return[]},r.prototype.getAttributes=function(e,t){return[]},r.prototype.bindSamplers=function(e){this._currentEffect=null},r.prototype.enableEffect=function(e){this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e)},r.prototype.setState=function(e,t,i,r){void 0===t&&(t=0),void 0===r&&(r=!1)},r.prototype.setIntArray=function(e,t){},r.prototype.setIntArray2=function(e,t){},r.prototype.setIntArray3=function(e,t){},r.prototype.setIntArray4=function(e,t){},r.prototype.setFloatArray=function(e,t){},r.prototype.setFloatArray2=function(e,t){},r.prototype.setFloatArray3=function(e,t){},r.prototype.setFloatArray4=function(e,t){},r.prototype.setArray=function(e,t){},r.prototype.setArray2=function(e,t){},r.prototype.setArray3=function(e,t){},r.prototype.setArray4=function(e,t){},r.prototype.setMatrices=function(e,t){},r.prototype.setMatrix=function(e,t){},r.prototype.setMatrix3x3=function(e,t){},r.prototype.setMatrix2x2=function(e,t){},r.prototype.setFloat=function(e,t){},r.prototype.setFloat2=function(e,t,i){},r.prototype.setFloat3=function(e,t,i,r){},r.prototype.setBool=function(e,t){},r.prototype.setFloat4=function(e,t,i,r,n){},r.prototype.setColor3=function(e,t){},r.prototype.setColor4=function(e,t,i){},r.prototype.setAlphaMode=function(t,i){void 0===i&&(i=!1),this._alphaMode!==t&&(this._alphaState.alphaBlend=t!==e.Engine.ALPHA_DISABLE,i||this.setDepthWrite(t===e.Engine.ALPHA_DISABLE),this._alphaMode=t)},r.prototype.bindBuffers=function(e,t,i){},r.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilState.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},r.prototype.draw=function(e,t,i,r){},r.prototype.drawElementsType=function(e,t,i,r){},r.prototype.drawArraysType=function(e,t,i,r){},r.prototype._createTexture=function(){return{}},r.prototype._releaseTexture=function(e){},r.prototype.createTexture=function(t,i,r,n,o,s,a,l,h,c){void 0===o&&(o=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===s&&(s=null),void 0===a&&(a=null),void 0===l&&(l=null);var u=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_URL),f=String(t);return u.url=f,u.generateMipMaps=!i,u.samplingMode=o,u.invertY=r,u.baseWidth=this._options.textureSize,u.baseHeight=this._options.textureSize,u.width=this._options.textureSize,u.height=this._options.textureSize,c&&(u.format=c),u.isReady=!0,s&&s(),this._internalTexturesCache.push(u),u},r.prototype.createRenderTargetTexture=function(t,i){var r=new e.RenderTargetCreationOptions;void 0!==i&&"object"==typeof i?(r.generateMipMaps=i.generateMipMaps,r.generateDepthBuffer=void 0===i.generateDepthBuffer||i.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&i.generateStencilBuffer,r.type=void 0===i.type?e.Engine.TEXTURETYPE_UNSIGNED_INT:i.type,r.samplingMode=void 0===i.samplingMode?e.Texture.TRILINEAR_SAMPLINGMODE:i.samplingMode):(r.generateMipMaps=i,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.type=e.Engine.TEXTURETYPE_UNSIGNED_INT,r.samplingMode=e.Texture.TRILINEAR_SAMPLINGMODE);var n=new e.InternalTexture(this,e.InternalTexture.DATASOURCE_RENDERTARGET),o=t.width||t,s=t.height||t;return n._depthStencilBuffer={},n._framebuffer={},n.baseWidth=o,n.baseHeight=s,n.width=o,n.height=s,n.isReady=!0,n.samples=1,n.generateMipMaps=!!r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,n._generateDepthBuffer=r.generateDepthBuffer,n._generateStencilBuffer=!!r.generateStencilBuffer,this._internalTexturesCache.push(n),n},r.prototype.updateTextureSamplingMode=function(e,t){t.samplingMode=e},r.prototype.bindFramebuffer=function(e,t,i,r,n){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer,this._cachedViewport&&!n&&this.setViewport(this._cachedViewport,i,r)},r.prototype.unBindFramebuffer=function(e,t,i){void 0===t&&(t=!1),this._currentRenderTarget=null,i&&(e._MSAAFramebuffer&&(this._currentFramebuffer=e._framebuffer),i()),this._currentFramebuffer=null},r.prototype.createDynamicVertexBuffer=function(e){return{capacity:1,references:1,is32Bits:!1}},r.prototype.updateDynamicTexture=function(e,t,i,r,n){void 0===r&&(r=!1)},r.prototype.getError=function(){return 0},r.prototype._getUnpackAlignement=function(){return 1},r.prototype._unpackFlipY=function(e){},r.prototype.updateDynamicIndexBuffer=function(e,t,i){void 0===i&&(i=0)},r.prototype.updateDynamicVertexBuffer=function(e,t,i,r){},r.prototype._bindTextureDirectly=function(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)},r.prototype._bindTexture=function(e,t){e<0||this._bindTextureDirectly(0,t)},r.prototype._releaseBuffer=function(e){return 0===--e.references},r.prototype.releaseEffects=function(){},r.prototype.displayLoadingUI=function(){},r.prototype.hideLoadingUI=function(){},r.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,r,n,o,s){void 0===o&&(o=0),void 0===s&&(s=0)},r.prototype._uploadDataToTextureDirectly=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},r.prototype._uploadArrayBufferViewToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},r.prototype._uploadImageToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},r})(e.Engine);e.NullEngine=i})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){this.engine=t,this._captureGPUFrameTime=!1,this._gpuFrameTime=new e.PerfCounter,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new e.PerfCounter,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}return Object.defineProperty(t.prototype,"gpuFrameTimeCounter",{get:function(){return this._gpuFrameTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureGPUFrameTime",{get:function(){return this._captureGPUFrameTime},set:function(e){var t=this;e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.engine.onBeginFrameObservable.add((function(){t._gpuFrameTimeToken||(t._gpuFrameTimeToken=t.engine.startTimeQuery())})),this._onEndFrameObserver=this.engine.onEndFrameObservable.add((function(){if(t._gpuFrameTimeToken){var e=t.engine.endTimeQuery(t._gpuFrameTimeToken);e>-1&&(t._gpuFrameTimeToken=null,t._gpuFrameTime.fetchNewFrame(),t._gpuFrameTime.addCount(e,!0))}}))):(this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shaderCompilationTimeCounter",{get:function(){return this._shaderCompilationTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureShaderCompilationTime",{get:function(){return this._captureShaderCompilationTime},set:function(e){var t=this;e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add((function(){t._shaderCompilationTime.fetchNewFrame(),t._shaderCompilationTime.beginMonitoring()})),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add((function(){t._shaderCompilationTime.endMonitoring()}))):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null},t})();e.EngineInstrumentation=t})(r||(r={}));var r;!(function(e){var t=(function(){function t(t){var i=this;this.scene=t,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new e.PerfCounter,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new e.PerfCounter,this._captureFrameTime=!1,this._frameTime=new e.PerfCounter,this._captureRenderTime=!1,this._renderTime=new e.PerfCounter,this._captureInterFrameTime=!1,this._interFrameTime=new e.PerfCounter,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new e.PerfCounter,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new e.PerfCounter,this._capturePhysicsTime=!1,this._physicsTime=new e.PerfCounter,this._captureAnimationsTime=!1,this._animationsTime=new e.PerfCounter,this._captureCameraRenderTime=!1,this._cameraRenderTime=new e.PerfCounter,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=t.onBeforeAnimationsObservable.add((function(){i._captureActiveMeshesEvaluationTime&&i._activeMeshesEvaluationTime.fetchNewFrame(),i._captureRenderTargetsRenderTime&&i._renderTargetsRenderTime.fetchNewFrame(),i._captureFrameTime&&(e.Tools.StartPerformanceCounter("Scene rendering"),i._frameTime.beginMonitoring()),i._captureInterFrameTime&&i._interFrameTime.endMonitoring(),i._captureParticlesRenderTime&&i._particlesRenderTime.fetchNewFrame(),i._captureSpritesRenderTime&&i._spritesRenderTime.fetchNewFrame(),i._captureAnimationsTime&&i._animationsTime.beginMonitoring(),i.scene.getEngine()._drawCalls.fetchNewFrame(),i.scene.getEngine()._textureCollisions.fetchNewFrame()})),this._onAfterRenderObserver=t.onAfterRenderObservable.add((function(){i._captureFrameTime&&(e.Tools.EndPerformanceCounter("Scene rendering"),i._frameTime.endMonitoring()),i._captureRenderTime&&i._renderTime.endMonitoring(!1),i._captureInterFrameTime&&i._interFrameTime.beginMonitoring()}))}return Object.defineProperty(t.prototype,"activeMeshesEvaluationTimeCounter",{get:function(){return this._activeMeshesEvaluationTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureActiveMeshesEvaluationTime",{get:function(){return this._captureActiveMeshesEvaluationTime},set:function(t){var i=this;t!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=t,t?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add((function(){e.Tools.StartPerformanceCounter("Active meshes evaluation"),i._activeMeshesEvaluationTime.beginMonitoring()})),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add((function(){e.Tools.EndPerformanceCounter("Active meshes evaluation"),i._activeMeshesEvaluationTime.endMonitoring()}))):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderTargetsRenderTimeCounter",{get:function(){return this._renderTargetsRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureRenderTargetsRenderTime",{get:function(){return this._captureRenderTargetsRenderTime},set:function(t){var i=this;t!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=t,t?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add((function(){e.Tools.StartPerformanceCounter("Render targets rendering"),i._renderTargetsRenderTime.beginMonitoring()})),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add((function(){e.Tools.EndPerformanceCounter("Render targets rendering"),i._renderTargetsRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"particlesRenderTimeCounter",{get:function(){return this._particlesRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureParticlesRenderTime",{get:function(){return this._captureParticlesRenderTime},set:function(t){var i=this;t!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=t,t?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add((function(){e.Tools.StartPerformanceCounter("Particles"),i._particlesRenderTime.beginMonitoring()})),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add((function(){e.Tools.EndPerformanceCounter("Particles"),i._particlesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"spritesRenderTimeCounter",{get:function(){return this._spritesRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureSpritesRenderTime",{get:function(){return this._captureSpritesRenderTime},set:function(t){var i=this;t!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=t,t?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add((function(){e.Tools.StartPerformanceCounter("Sprites"),i._spritesRenderTime.beginMonitoring()})),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add((function(){e.Tools.EndPerformanceCounter("Sprites"),i._spritesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"physicsTimeCounter",{get:function(){return this._physicsTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"capturePhysicsTime",{get:function(){return this._capturePhysicsTime},set:function(t){var i=this;t!==this._capturePhysicsTime&&(this._capturePhysicsTime=t,t?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add((function(){e.Tools.StartPerformanceCounter("Physics"), +i._physicsTime.beginMonitoring()})),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add((function(){e.Tools.EndPerformanceCounter("Physics"),i._physicsTime.endMonitoring()}))):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationsTimeCounter",{get:function(){return this._animationsTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureAnimationsTime",{get:function(){return this._captureAnimationsTime},set:function(e){var t=this;e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add((function(){t._animationsTime.endMonitoring()})):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"frameTimeCounter",{get:function(){return this._frameTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureFrameTime",{get:function(){return this._captureFrameTime},set:function(e){this._captureFrameTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"interFrameTimeCounter",{get:function(){return this._interFrameTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureInterFrameTime",{get:function(){return this._captureInterFrameTime},set:function(e){this._captureInterFrameTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderTimeCounter",{get:function(){return this._renderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureRenderTime",{get:function(){return this._captureRenderTime},set:function(t){var i=this;t!==this._captureRenderTime&&(this._captureRenderTime=t,t?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add((function(){i._renderTime.beginMonitoring(),e.Tools.StartPerformanceCounter("Main render")})),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add((function(){i._renderTime.endMonitoring(!1),e.Tools.EndPerformanceCounter("Main render")}))):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraRenderTimeCounter",{get:function(){return this._cameraRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"captureCameraRenderTime",{get:function(){return this._captureCameraRenderTime},set:function(t){var i=this;t!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=t,t?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add((function(t){i._cameraRenderTime.beginMonitoring(),e.Tools.StartPerformanceCounter("Rendering camera "+t.name)})),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add((function(t){i._cameraRenderTime.endMonitoring(!1),e.Tools.EndPerformanceCounter("Rendering camera "+t.name)}))):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"drawCallsCounter",{get:function(){return this.scene.getEngine()._drawCalls},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"textureCollisionsCounter",{get:function(){return this.scene.getEngine()._textureCollisions},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null,this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null,this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null},t})();e.SceneInstrumentation=t})(r||(r={}));var r;!(function(e){var t=(function(){function e(){this._timeElapsedQueryEnded=!1}return e})();e._TimeToken=t})(r||(r={}));var r;!(function(e){var t=(function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.DIFFUSEDIRECTUV=0,t.GAMMADIFFUSE=!1,t.DIFFUSEHASALPHA=!1,t.OPACITYFRESNEL=!1,t.REFLECTIONBLUR=!1,t.REFLECTIONFRESNEL=!1,t.REFLECTIONFALLOFF=!1,t.TEXTURELODSUPPORT=!1,t.PREMULTIPLYALPHA=!1,t.USERGBCOLOR=!1,t.USEHIGHLIGHTANDSHADOWCOLORS=!1,t.NOISE=!1,t.REFLECTIONBGR=!1,t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=!1,t.CONTRAST=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.EXPOSURE=!1,t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.EQUIRECTANGULAR_RELFECTION_FOV=!1,t.MAINUV1=!1,t.MAINUV2=!1,t.UV1=!1,t.UV2=!1,t.CLIPPLANE=!1,t.POINTSIZE=!1,t.FOG=!1,t.NORMAL=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.SHADOWFLOAT=!1,t.rebuild(),t}return o(t,e),t})(e.MaterialDefines),i=(function(i){function r(t,r){var n=i.call(this,t,r)||this;return n.primaryColor=e.Color3.White(),n._primaryColorShadowLevel=0,n._primaryColorHighlightLevel=0,n.reflectionTexture=null,n.reflectionBlur=0,n.diffuseTexture=null,n._shadowLights=null,n.shadowLights=null,n.shadowLevel=0,n.sceneCenter=e.Vector3.Zero(),n.opacityFresnel=!0,n.reflectionFresnel=!1,n.reflectionFalloffDistance=0,n.reflectionAmount=1,n.reflectionReflectance0=.05,n.reflectionReflectance90=.5,n.useRGBColor=!0,n.enableNoise=!1,n._fovMultiplier=1,n.useEquirectangularFOV=!1,n._maxSimultaneousLights=4,n.maxSimultaneousLights=4,n._imageProcessingObserver=null,n.switchToBGR=!1,n._renderTargets=new e.SmartArray(16),n._reflectionControls=e.Vector4.Zero(),n._white=e.Color3.White(),n._primaryShadowColor=e.Color3.Black(),n._primaryHighlightColor=e.Color3.Black(),n._attachImageProcessingConfiguration(null),n.getRenderTargetTextures=function(){return n._renderTargets.reset(),n._diffuseTexture&&n._diffuseTexture.isRenderTarget&&n._renderTargets.push(n._diffuseTexture),n._reflectionTexture&&n._reflectionTexture.isRenderTarget&&n._renderTargets.push(n._reflectionTexture),n._renderTargets},n}return o(r,i),Object.defineProperty(r.prototype,"_perceptualColor",{get:function(){return this.__perceptualColor},set:function(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"primaryColorShadowLevel",{get:function(){return this._primaryColorShadowLevel},set:function(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"primaryColorHighlightLevel",{get:function(){return this._primaryColorHighlightLevel},set:function(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"reflectionStandardFresnelWeight",{set:function(e){var t=e;t<.5?(t*=2,this.reflectionReflectance0=r.StandardReflectance0*t,this.reflectionReflectance90=r.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=r.StandardReflectance0+(1-r.StandardReflectance0)*t,this.reflectionReflectance90=r.StandardReflectance90+(1-r.StandardReflectance90)*t)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"fovMultiplier",{get:function(){return this._fovMultiplier},set:function(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))},enumerable:!0,configurable:!0}),r.prototype._attachImageProcessingConfiguration=function(e){var t=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((function(e){t._computePrimaryColorFromPerceptualColor(),t._markAllSubMeshesAsImageProcessingDirty()}))))},Object.defineProperty(r.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this.imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"cameraColorCurves",{get:function(){return this.imageProcessingConfiguration.colorCurves},set:function(e){this.imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),r.prototype.needAlphaTesting=function(){return!0},r.prototype.needAlphaBlending=function(){return this.alpha<0||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha},r.prototype.isReadyForSubMesh=function(i,r,n){var o=this;if(void 0===n&&(n=!1),r.effect&&this.isFrozen&&this._wasPreviouslyReady)return!0;r._materialDefines||(r._materialDefines=new t);var s=this.getScene(),a=r._materialDefines;if(!this.checkReadyOnEveryCall&&r.effect&&a._renderId===s.getRenderId())return!0;var l=s.getEngine();if(e.MaterialHelper.PrepareDefinesForLights(s,i,a,!1,this._maxSimultaneousLights),a._needNormals=!0,a._areTexturesDirty){if(a._needUVs=!1,s.texturesEnabled){if(s.getEngine().getCaps().textureLOD&&(a.TEXTURELODSUPPORT=!0),this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;e.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture,a,"DIFFUSE"),a.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,a.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,a.OPACITYFRESNEL=this._opacityFresnel}else a.DIFFUSE=!1,a.DIFFUSEHASALPHA=!1,a.GAMMADIFFUSE=!1,a.OPACITYFRESNEL=!1;var h=this._reflectionTexture;if(h&&e.StandardMaterial.ReflectionTextureEnabled){if(!h.isReadyOrNotBlocking())return!1;switch(a.REFLECTION=!0,a.GAMMAREFLECTION=h.gammaSpace,a.RGBDREFLECTION=h.isRGBD,a.REFLECTIONBLUR=this._reflectionBlur>0,a.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!h.invertZ:h.invertZ,a.LODINREFLECTIONALPHA=h.lodLevelInAlpha,a.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,a.REFLECTIONBGR=this.switchToBGR,h.coordinatesMode===e.Texture.INVCUBIC_MODE&&(a.INVERTCUBICMAP=!0),a.REFLECTIONMAP_3D=h.isCube,h.coordinatesMode){case e.Texture.EXPLICIT_MODE:a.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:a.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:a.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:a.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:a.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:default:a.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(a.REFLECTIONFRESNEL=!0,a.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(a.REFLECTIONFRESNEL=!1,a.REFLECTIONFALLOFF=!1)}else a.REFLECTION=!1,a.REFLECTIONFRESNEL=!1,a.REFLECTIONFALLOFF=!1,a.REFLECTIONBLUR=!1,a.REFLECTIONMAP_3D=!1,a.REFLECTIONMAP_SPHERICAL=!1,a.REFLECTIONMAP_PLANAR=!1,a.REFLECTIONMAP_CUBIC=!1,a.REFLECTIONMAP_PROJECTION=!1,a.REFLECTIONMAP_SKYBOX=!1,a.REFLECTIONMAP_EXPLICIT=!1,a.REFLECTIONMAP_EQUIRECTANGULAR=!1,a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,a.INVERTCUBICMAP=!1,a.REFLECTIONMAP_OPPOSITEZ=!1,a.LODINREFLECTIONALPHA=!1,a.GAMMAREFLECTION=!1,a.RGBDREFLECTION=!1}a.PREMULTIPLYALPHA=this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED||this.alphaMode===e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF,a.USERGBCOLOR=this._useRGBColor,a.NOISE=this._enableNoise}if(a._areLightsDirty&&(a.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel)),a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a)}if(e.MaterialHelper.PrepareDefinesForMisc(i,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(i),a),e.MaterialHelper.PrepareDefinesForFrameBoundValues(s,l,a,n),e.MaterialHelper.PrepareDefinesForAttributes(i,a,!1,!0,!1)&&i&&(s.getEngine().getCaps().standardDerivatives||i.isVerticesDataPresent(e.VertexBuffer.NormalKind)||(i.createNormals(!0),e.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: "+i.name))),a.isDirty){a.markAsProcessed(),s.resetCachedMaterial();var c=new e.EffectFallbacks;a.FOG&&c.addFallback(0,"FOG"),a.POINTSIZE&&c.addFallback(1,"POINTSIZE"),e.MaterialHelper.HandleFallbacksForShadows(a,c,this._maxSimultaneousLights),a.NUM_BONE_INFLUENCERS>0&&c.addCPUSkinningFallback(0,i);var u=[e.VertexBuffer.PositionKind];a.NORMAL&&u.push(e.VertexBuffer.NormalKind),a.UV1&&u.push(e.VertexBuffer.UVKind),a.UV2&&u.push(e.VertexBuffer.UV2Kind),e.MaterialHelper.PrepareAttributesForBones(u,i,a,c),e.MaterialHelper.PrepareAttributesForInstances(u,a);var f=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","vClipPlane","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"],d=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],p=["Material","Scene"];e.ImageProcessingConfiguration&&(e.ImageProcessingConfiguration.PrepareUniforms(f,a),e.ImageProcessingConfiguration.PrepareSamplers(d,a)),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:f,uniformBuffersNames:p,samplers:d,defines:a,maxSimultaneousLights:this._maxSimultaneousLights});var m=function(e){o.onCompiled&&o.onCompiled(e),o.bindSceneUniformBuffer(e,s.getSceneUniformBuffer())},_=a.toString();r.setEffect(s.getEngine().createEffect("background",{attributes:u,uniformsNames:f,uniformBuffersNames:p,samplers:d,defines:_,fallbacks:c,onCompiled:m,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},l),a),this.buildUniformLayout()}return!(!r.effect||!r.effect.isReady())&&(a._renderId=s.getRenderId(),this._wasPreviouslyReady=!0,!0)},r.prototype._computePrimaryColorFromPerceptualColor=function(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())},r.prototype._computePrimaryColors=function(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))},r.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.create()},r.prototype.unbind=function(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),i.prototype.unbind.call(this)},r.prototype.bindOnlyWorldMatrix=function(e){this._activeEffect.setMatrix("world",e)},r.prototype.bindForSubMesh=function(t,i,r){var n=this.getScene(),o=r._materialDefines;if(o){var s=r.effect;if(s){this._activeEffect=s,this.bindOnlyWorldMatrix(t),e.MaterialHelper.BindBonesParameters(i,this._activeEffect);var a=this._mustRebind(n,s,i.visibility);if(a){this._uniformBuffer.bindToEffect(s,"Material"),this.bindViewProjection(s);var l=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(n.texturesEnabled&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),e.MaterialHelper.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),l&&e.StandardMaterial.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",l.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),o.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),n.texturesEnabled&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),l&&e.StandardMaterial.ReflectionTextureEnabled&&(o.REFLECTIONBLUR&&o.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",l):o.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",l._lodTextureMid||l),this._uniformBuffer.setTexture("reflectionSamplerLow",l._lodTextureLow||l),this._uniformBuffer.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)):this._uniformBuffer.setTexture("reflectionSampler",l),o.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w)))),e.MaterialHelper.BindClipPlane(this._activeEffect,n),e.MaterialHelper.BindEyePosition(s,n)}!a&&this.isFrozen||(n.lightsEnabled&&e.MaterialHelper.BindLights(n,i,this._activeEffect,o,this._maxSimultaneousLights,!1),this.bindView(s),e.MaterialHelper.BindFogParameters(n,i,this._activeEffect),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(i,this._activeEffect)}}},r.prototype.dispose=function(e,t){void 0===e&&(e=!1),void 0===t&&(t=!1),t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),i.prototype.dispose.call(this,e)},r.prototype.clone=function(t){var i=this;return e.SerializationHelper.Clone((function(){return new r(t,i.getScene())}),this)},r.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.BackgroundMaterial",t},r.prototype.getClassName=function(){return"BackgroundMaterial"},r.Parse=function(t,i,n){return e.SerializationHelper.Parse((function(){return new r(t.name,i)}),t,i,n)},r.StandardReflectance0=.05,r.StandardReflectance90=.5,n([e.serializeAsColor3()],r.prototype,"_primaryColor",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"primaryColor",void 0),n([e.serializeAsColor3()],r.prototype,"__perceptualColor",void 0),n([e.serialize()],r.prototype,"_primaryColorShadowLevel",void 0),n([e.serialize()],r.prototype,"_primaryColorHighlightLevel",void 0),n([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],r.prototype,"primaryColorHighlightLevel",null),n([e.serializeAsTexture()],r.prototype,"_reflectionTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionTexture",void 0),n([e.serialize()],r.prototype,"_reflectionBlur",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionBlur",void 0),n([e.serializeAsTexture()],r.prototype,"_diffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"diffuseTexture",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"shadowLights",void 0),n([e.serialize()],r.prototype,"_shadowLevel",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"shadowLevel",void 0),n([e.serializeAsVector3()],r.prototype,"_sceneCenter",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"sceneCenter",void 0),n([e.serialize()],r.prototype,"_opacityFresnel",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"opacityFresnel",void 0),n([e.serialize()],r.prototype,"_reflectionFresnel",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionFresnel",void 0),n([e.serialize()],r.prototype,"_reflectionFalloffDistance",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionFalloffDistance",void 0),n([e.serialize()],r.prototype,"_reflectionAmount",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionAmount",void 0),n([e.serialize()],r.prototype,"_reflectionReflectance0",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionReflectance0",void 0),n([e.serialize()],r.prototype,"_reflectionReflectance90",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"reflectionReflectance90",void 0),n([e.serialize()],r.prototype,"_useRGBColor",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useRGBColor",void 0),n([e.serialize()],r.prototype,"_enableNoise",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"enableNoise",void 0),n([e.serialize()],r.prototype,"_maxSimultaneousLights",void 0),n([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],r.prototype,"maxSimultaneousLights",void 0),n([e.serializeAsImageProcessingConfiguration()],r.prototype,"_imageProcessingConfiguration",void 0),r})(e.PushMaterial);e.BackgroundMaterial=i})(r||(r={}));var r,s=this&&this.__assign||Object.assign||function(e){for(var t,i=1,r=arguments.length;ii&&(i=2*a,r=i),i*=1.1,r*=1.5,n=o.min.add(s.scale(.5)),n.y=o.min.y-this._options.groundYBias}return{groundSize:i,skyboxSize:r,rootPosition:n}},t.prototype._setupGround=function(t){var i=this;this._ground&&!this._ground.isDisposed()||(this._ground=e.Mesh.CreatePlane("BackgroundPlane",t.groundSize,this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((function(){i._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow},t.prototype._setupGroundMaterial=function(){this._groundMaterial||(this._groundMaterial=new e.BackgroundMaterial("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=e.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)},t.prototype._setupGroundDiffuseTexture=function(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof e.BaseTexture)return void(this._groundMaterial.diffuseTexture=this._options.groundTexture);var t=new e.Texture(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler);t.gammaSpace=!1,t.hasAlpha=!0,this._groundMaterial.diffuseTexture=t}},t.prototype._setupGroundMirrorTexture=function(t){var i=e.Texture.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new e.MirrorTexture("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,e.Texture.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new e.Plane(0,-1,0,t.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=i,this._groundMirror.wrapV=i,this._groundMirror.gammaSpace=!1,this._groundMirror.renderList))for(var r=0;rthis.occlusionRetryCount))return;this._isOcclusionQueryInProgress=!1,this._occlusionInternalRetryCounter=0,this._isOccluded=this.occlusionType!==e.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC&&this._isOccluded}}var r=this.getScene();if(r.getBoundingBoxRenderer){var n=r.getBoundingBoxRenderer();this._occlusionQuery||(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(this.occlusionQueryAlgorithmType,this._occlusionQuery),n.renderOcclusionBoundingBox(this),t.endOcclusionQuery(this.occlusionQueryAlgorithmType),this._isOcclusionQueryInProgress=!0}}})(r||(r={}));var r;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===r&&(r=256),void 0===n&&(n=e.Engine.LastCreatedScene);var a=t.call(this,i,r,"noise",n,o,s)||this;return a._time=0,a.brightness=.2,a.octaves=3,a.persistence=.8,a.animationSpeedFactor=1,a._updateShaderUniforms(),a}return o(i,t),i.prototype._updateShaderUniforms=function(){var e=this.getScene();e&&(this._time+=e.getAnimationRatio()*this.animationSpeedFactor*.01,this.setFloat("brightness",this.brightness),this.setInt("octaves",this.octaves),this.setFloat("persistence",this.persistence),this.setFloat("timeScale",this._time))},i.prototype.render=function(e){this._updateShaderUniforms(),t.prototype.render.call(this,e)},i.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this,t.prototype.serialize.call(this));return i.customType="BABYLON.NoiseProceduralTexture",i},i.Parse=function(t,r,n){return e.SerializationHelper.Parse((function(){return new i(t.name,t._size,r,void 0,t._generateMipMaps)}),t,r,n)},i})(e.ProceduralTexture);e.NoiseProceduralTexture=t})(r||(r={})),r.Effect.ShadersStore={defaultVertexShader:"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n", +defaultPixelShader:"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#include\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include\n#include\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n",pbrVertexShader:"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include\n\n#include\n\n#include\n\n#include[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include\n}", +pbrPixelShader:"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include\n#include\n#include\n\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n\n#include\nvoid main(void) {\n#include\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include\n#include(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}",rgbdEncodePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}",rgbdDecodePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}",spritesVertexShader:"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}",spritesPixelShader:"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include\ngl_FragColor=color;\n}",particlesVertexShader:"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}",particlesPixelShader:"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}",colorVertexShader:"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}",colorPixelShader:"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}",gpuRenderParticlesVertexShader:"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}",gpuRenderParticlesPixelShader:"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n", +gpuUpdateParticlesVertexShader:"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}",gpuUpdateParticlesPixelShader:"#version 300 es\nvoid main() {\ndiscard;\n}\n",postprocessVertexShader:"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}",passPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}",shadowMapVertexShader:"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n\n#include\n#include\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",shadowMapPixelShader:"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}",depthBoxBlurPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}",proceduralVertexShader:"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}",depthVertexShader:"\nattribute vec3 position;\n#include\n\n#include\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",depthPixelShader:"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}",ssaoPixelShader:"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; imaxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}", depthOfFieldPixelShader:"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n",standardPixelShader:"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminanceshadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n",fxaaVertexShader:"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}",fxaaPixelShader:"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}",sharpenPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}",kernelBlurVertexShader:"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}",kernelBlurPixelShader:"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}",depthOfFieldMergePixelShader:"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n",circleOfConfusionPixelShader:"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n",bloomMergePixelShader:"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n",extractHighlightsPixelShader:"#include\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}",geometryVertexShader:"precision highp float;\nprecision highp int;\n#include\n#include\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include\n#include\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",geometryPixelShader:"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include[3]\n#else\n#include[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}",refractionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}",blackAndWhitePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}", convolutionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}",filterPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}",volumetricLightScatteringPixelShader:"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i\n#include\n#include\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}",lensFlareVertexShader:"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}",lensFlarePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}",anaglyphPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}",stereoscopicInterlacePixelShader:"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}",vrDistortionCorrectionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}",glowBlurPostProcessPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}",glowMapGenerationPixelShader:"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}",glowMapGenerationVertexShader:"\nattribute vec3 position;\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n\n#include\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",glowMapMergePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}",glowMapMergeVertexShader:"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}",lineVertexShader:"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}",linePixelShader:"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}",outlineVertexShader:"\nattribute vec3 position;\nattribute vec3 normal;\n#include\n\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n",outlinePixelShader:"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n}",layerVertexShader:"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}",layerPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}",backgroundVertexShader:"precision highp float;\n#include<__decl__backgroundVertex>\n#include\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n\n#include\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include\n\n#include\n\n#include[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",backgroundPixelShader:"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#include\n#include\n\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n",noisePixelShader:"\n\nuniform float brightness;\nuniform int octaves;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif",instancesDeclaration:"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif",pointCloudVertexDeclaration:"#ifdef POINTSIZE\nuniform float pointSize;\n#endif",bumpVertexDeclaration:"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n",clipPlaneVertexDeclaration:"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif",fogVertexDeclaration:"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif",morphTargetsVertexGlobalDeclaration:"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif",morphTargetsVertexDeclaration:"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif",logDepthDeclaration:"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif",morphTargetsVertex:"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif",instancesVertex:"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif",bonesVertex:"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif",bumpVertex:"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif",clipPlaneVertex:"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif",fogVertex:"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif",shadowsVertex:"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif",pointCloudVertex:"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif",logDepthVertex:"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif",helperFunctions:"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}",lightFragmentDeclaration:"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif", lightsFragmentFunctions:"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}",lightUboDeclaration:"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif",defaultVertexDeclaration:"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n",defaultFragmentDeclaration:"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif",defaultUboDeclaration:"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};",shadowsFragmentFunctions:"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx * @param blockCompilation If the shader should not be compiled imediatly. (default: false) */ - function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) { + function PostProcess( + /** Name of the PostProcess. */ + name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) { if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; } if (defines === void 0) { defines = null; } if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } @@ -68663,6 +68743,7 @@ var BABYLON; */ ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) { if (includeDescendants === void 0) { includeDescendants = true; } + var _a; if (!this._shadowMap) { return this; } @@ -68674,7 +68755,6 @@ var BABYLON; (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes()); } return this; - var _a; }; /** * Helper function to remove a mesh and its descendants from the list of shadow casters @@ -72014,6 +72094,7 @@ var BABYLON; return this.subMaterials[index]; }; MultiMaterial.prototype.getActiveTextures = function () { + var _a; return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { if (subMaterial) { return subMaterial.getActiveTextures(); @@ -72022,7 +72103,6 @@ var BABYLON; return []; } })); - var _a; }; // Methods MultiMaterial.prototype.getClassName = function () { @@ -77685,7 +77765,9 @@ var BABYLON; * @param textureType Type of textures used when performing the post process. (default: 0) * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ - function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) { + function BlurPostProcess(name, + /** The direction in which to blur the image. */ + direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) { if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; } if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } if (defines === void 0) { defines = ""; } @@ -78317,7 +78399,9 @@ var BABYLON; * @param textureType Type of textures used when performing the post process. (default: 0) * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ - function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) { + function BloomMergePostProcess(name, originalFromInput, blurred, + /** Weight of the bloom to be added to the original input. */ + weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) { if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } if (blockCompilation === void 0) { blockCompilation = false; } var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this; @@ -80779,7 +80863,9 @@ var BABYLON; * @param reusable If the post process can be reused on the same frame. (default: false) * @param textureType Type of textures used when performing the post process. (default: 0) */ - function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) { + function ConvolutionPostProcess(name, + /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ + kernel, options, camera, samplingMode, engine, reusable, textureType) { if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this; _this.kernel = kernel; @@ -90022,7 +90108,9 @@ var BABYLON; * Instantiates a UtilityLayerRenderer * @param originalScene the original scene that will be rendered on top of */ - function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) { + function UtilityLayerRenderer( + /** the original scene that will be rendered on top of */ + originalScene) { var _this = this; this.originalScene = originalScene; this._pointerCaptures = {}; @@ -91034,7 +91122,9 @@ var BABYLON; * Creates a gizmo * @param gizmoLayer The utility layer the gizmo will be added to */ - function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) { + function Gizmo( + /** The utility layer the gizmo will be added to */ + gizmoLayer) { if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; } var _this = this; this.gizmoLayer = gizmoLayer; @@ -94539,7 +94629,9 @@ var BABYLON; * @param scene The scene the VRExperienceHelper belongs to. * @param webVROptions Options to modify the vr experience helper's behavior. */ - function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) { + function VRExperienceHelper(scene, + /** Options to modify the vr experience helper's behavior. */ + webVROptions) { if (webVROptions === void 0) { webVROptions = {}; } var _this = this; this.webVROptions = webVROptions; @@ -102513,7 +102605,9 @@ var BABYLON; if (effect.onBind) { effect.onBind(effect); } - effect.onBindObservable.notifyObservers(effect); + if (effect._onBindObservable) { + effect._onBindObservable.notifyObservers(effect); + } }; NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) { if (zOffset === void 0) { zOffset = 0; } diff --git a/dist/preview release/gui/babylon.gui.min.js b/dist/preview release/gui/babylon.gui.min.js index 223c0ca6fae..8f8450c4b4a 100644 --- a/dist/preview release/gui/babylon.gui.min.js +++ b/dist/preview release/gui/babylon.gui.min.js @@ -1,2 +1,2 @@ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("babylonjs")):"function"==typeof define&&define.amd?define("babylonjs-gui",["babylonjs"],e):"object"==typeof exports?exports["babylonjs-gui"]=e(require("babylonjs")):(t.BABYLON=t.BABYLON||{},t.BABYLON.GUI=e(t.BABYLON))}(window,function(t){return function(t){var e={};function i(r){if(e[r])return e[r].exports;var n=e[r]={i:r,l:!1,exports:{}};return t[r].call(n.exports,n,n.exports,i),n.l=!0,n.exports}return i.m=t,i.c=e,i.d=function(t,e,r){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(i.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var n in t)i.d(r,n,function(e){return t[e]}.bind(null,n));return r},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=49)}([function(e,i){e.exports=t},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=i(2),n=i(0),o=i(6),s=i(19),a=function(){function t(e){this.name=e,this._alpha=1,this._alphaSet=!1,this._zIndex=0,this._currentMeasure=o.Measure.Empty(),this._fontFamily="Arial",this._fontStyle="",this._fontWeight="",this._fontSize=new r.ValueAndUnit(18,r.ValueAndUnit.UNITMODE_PIXEL,!1),this._width=new r.ValueAndUnit(1,r.ValueAndUnit.UNITMODE_PERCENTAGE,!1),this._height=new r.ValueAndUnit(1,r.ValueAndUnit.UNITMODE_PERCENTAGE,!1),this._color="",this._style=null,this._horizontalAlignment=t.HORIZONTAL_ALIGNMENT_CENTER,this._verticalAlignment=t.VERTICAL_ALIGNMENT_CENTER,this._isDirty=!0,this._tempParentMeasure=o.Measure.Empty(),this._cachedParentMeasure=o.Measure.Empty(),this._paddingLeft=new r.ValueAndUnit(0),this._paddingRight=new r.ValueAndUnit(0),this._paddingTop=new r.ValueAndUnit(0),this._paddingBottom=new r.ValueAndUnit(0),this._left=new r.ValueAndUnit(0),this._top=new r.ValueAndUnit(0),this._scaleX=1,this._scaleY=1,this._rotation=0,this._transformCenterX=.5,this._transformCenterY=.5,this._transformMatrix=s.Matrix2D.Identity(),this._invertTransformMatrix=s.Matrix2D.Identity(),this._transformedPosition=n.Vector2.Zero(),this._onlyMeasureMode=!1,this._isMatrixDirty=!0,this._isVisible=!0,this._fontSet=!1,this._dummyVector2=n.Vector2.Zero(),this._downCount=0,this._enterCount=-1,this._doNotRender=!1,this._downPointerIds={},this.isHitTestVisible=!0,this.isPointerBlocker=!1,this.isFocusInvisible=!1,this.shadowOffsetX=0,this.shadowOffsetY=0,this.shadowBlur=0,this.shadowColor="#000",this._linkOffsetX=new r.ValueAndUnit(0),this._linkOffsetY=new r.ValueAndUnit(0),this.onPointerMoveObservable=new n.Observable,this.onPointerOutObservable=new n.Observable,this.onPointerDownObservable=new n.Observable,this.onPointerUpObservable=new n.Observable,this.onPointerClickObservable=new n.Observable,this.onPointerEnterObservable=new n.Observable,this.onDirtyObservable=new n.Observable,this.onAfterDrawObservable=new n.Observable}return Object.defineProperty(t.prototype,"typeName",{get:function(){return this._getTypeName()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontOffset",{get:function(){return this._fontOffset},set:function(t){this._fontOffset=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"alpha",{get:function(){return this._alpha},set:function(t){this._alpha!==t&&(this._alphaSet=!0,this._alpha=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleX",{get:function(){return this._scaleX},set:function(t){this._scaleX!==t&&(this._scaleX=t,this._markAsDirty(),this._markMatrixAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleY",{get:function(){return this._scaleY},set:function(t){this._scaleY!==t&&(this._scaleY=t,this._markAsDirty(),this._markMatrixAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this._rotation},set:function(t){this._rotation!==t&&(this._rotation=t,this._markAsDirty(),this._markMatrixAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transformCenterY",{get:function(){return this._transformCenterY},set:function(t){this._transformCenterY!==t&&(this._transformCenterY=t,this._markAsDirty(),this._markMatrixAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transformCenterX",{get:function(){return this._transformCenterX},set:function(t){this._transformCenterX!==t&&(this._transformCenterX=t,this._markAsDirty(),this._markMatrixAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"horizontalAlignment",{get:function(){return this._horizontalAlignment},set:function(t){this._horizontalAlignment!==t&&(this._horizontalAlignment=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"verticalAlignment",{get:function(){return this._verticalAlignment},set:function(t){this._verticalAlignment!==t&&(this._verticalAlignment=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"width",{get:function(){return this._width.toString(this._host)},set:function(t){this._width.toString(this._host)!==t&&this._width.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"widthInPixels",{get:function(){return this._width.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"height",{get:function(){return this._height.toString(this._host)},set:function(t){this._height.toString(this._host)!==t&&this._height.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"heightInPixels",{get:function(){return this._height.getValueInPixel(this._host,this._cachedParentMeasure.height)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontFamily",{get:function(){return this._fontFamily},set:function(t){this._fontFamily!==t&&(this._fontFamily=t,this._resetFontCache())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontStyle",{get:function(){return this._fontStyle},set:function(t){this._fontStyle!==t&&(this._fontStyle=t,this._resetFontCache())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontWeight",{get:function(){return this._fontWeight},set:function(t){this._fontWeight!==t&&(this._fontWeight=t,this._resetFontCache())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"style",{get:function(){return this._style},set:function(t){var e=this;this._style&&(this._style.onChangedObservable.remove(this._styleObserver),this._styleObserver=null),this._style=t,this._style&&(this._styleObserver=this._style.onChangedObservable.add(function(){e._markAsDirty(),e._resetFontCache()})),this._markAsDirty(),this._resetFontCache()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_isFontSizeInPercentage",{get:function(){return this._fontSize.isPercentage},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontSizeInPixels",{get:function(){var t=this._style?this._style._fontSize:this._fontSize;return t.isPixel?t.getValue(this._host):t.getValueInPixel(this._host,this._tempParentMeasure.height||this._cachedParentMeasure.height)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontSize",{get:function(){return this._fontSize.toString(this._host)},set:function(t){this._fontSize.toString(this._host)!==t&&this._fontSize.fromString(t)&&(this._markAsDirty(),this._resetFontCache())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"color",{get:function(){return this._color},set:function(t){this._color!==t&&(this._color=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"zIndex",{get:function(){return this._zIndex},set:function(t){this.zIndex!==t&&(this._zIndex=t,this._root&&this._root._reOrderControl(this))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"notRenderable",{get:function(){return this._doNotRender},set:function(t){this._doNotRender!==t&&(this._doNotRender=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isVisible",{get:function(){return this._isVisible},set:function(t){this._isVisible!==t&&(this._isVisible=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isDirty",{get:function(){return this._isDirty},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingLeft",{get:function(){return this._paddingLeft.toString(this._host)},set:function(t){this._paddingLeft.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingLeftInPixels",{get:function(){return this._paddingLeft.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingRight",{get:function(){return this._paddingRight.toString(this._host)},set:function(t){this._paddingRight.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingRightInPixels",{get:function(){return this._paddingRight.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingTop",{get:function(){return this._paddingTop.toString(this._host)},set:function(t){this._paddingTop.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingTopInPixels",{get:function(){return this._paddingTop.getValueInPixel(this._host,this._cachedParentMeasure.height)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingBottom",{get:function(){return this._paddingBottom.toString(this._host)},set:function(t){this._paddingBottom.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingBottomInPixels",{get:function(){return this._paddingBottom.getValueInPixel(this._host,this._cachedParentMeasure.height)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"left",{get:function(){return this._left.toString(this._host)},set:function(t){this._left.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"leftInPixels",{get:function(){return this._left.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"top",{get:function(){return this._top.toString(this._host)},set:function(t){this._top.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"topInPixels",{get:function(){return this._top.getValueInPixel(this._host,this._cachedParentMeasure.height)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"linkOffsetX",{get:function(){return this._linkOffsetX.toString(this._host)},set:function(t){this._linkOffsetX.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"linkOffsetXInPixels",{get:function(){return this._linkOffsetX.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"linkOffsetY",{get:function(){return this._linkOffsetY.toString(this._host)},set:function(t){this._linkOffsetY.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"linkOffsetYInPixels",{get:function(){return this._linkOffsetY.getValueInPixel(this._host,this._cachedParentMeasure.height)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"centerX",{get:function(){return this._currentMeasure.left+this._currentMeasure.width/2},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"centerY",{get:function(){return this._currentMeasure.top+this._currentMeasure.height/2},enumerable:!0,configurable:!0}),t.prototype._getTypeName=function(){return"Control"},t.prototype._resetFontCache=function(){this._fontSet=!0,this._markAsDirty()},t.prototype.getLocalCoordinates=function(t){var e=n.Vector2.Zero();return this.getLocalCoordinatesToRef(t,e),e},t.prototype.getLocalCoordinatesToRef=function(t,e){return e.x=t.x-this._currentMeasure.left,e.y=t.y-this._currentMeasure.top,this},t.prototype.getParentLocalCoordinates=function(t){var e=n.Vector2.Zero();return e.x=t.x-this._cachedParentMeasure.left,e.y=t.y-this._cachedParentMeasure.top,e},t.prototype.moveToVector3=function(e,i){if(this._host&&this._root===this._host._rootContainer){this.horizontalAlignment=t.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=t.VERTICAL_ALIGNMENT_TOP;var r=this._host._getGlobalViewport(i),o=n.Vector3.Project(e,n.Matrix.Identity(),i.getTransformMatrix(),r);this._moveToProjectedPosition(o),o.z<0||o.z>1?this.notRenderable=!0:this.notRenderable=!1}else n.Tools.Error("Cannot move a control to a vector3 if the control is not at root level")},t.prototype.linkWithMesh=function(e){if(!this._host||this._root&&this._root!==this._host._rootContainer)e&&n.Tools.Error("Cannot link a control to a mesh if the control is not at root level");else{var i=this._host._linkedControls.indexOf(this);if(-1!==i)return this._linkedMesh=e,void(e||this._host._linkedControls.splice(i,1));e&&(this.horizontalAlignment=t.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=t.VERTICAL_ALIGNMENT_TOP,this._linkedMesh=e,this._onlyMeasureMode=0===this._currentMeasure.width||0===this._currentMeasure.height,this._host._linkedControls.push(this))}},t.prototype._moveToProjectedPosition=function(t){var e=this._left.getValue(this._host),i=this._top.getValue(this._host),r=t.x+this._linkOffsetX.getValue(this._host)-this._currentMeasure.width/2,n=t.y+this._linkOffsetY.getValue(this._host)-this._currentMeasure.height/2;this._left.ignoreAdaptiveScaling&&this._top.ignoreAdaptiveScaling&&(Math.abs(r-e)<.5&&(r=e),Math.abs(n-i)<.5&&(n=i)),this.left=r+"px",this.top=n+"px",this._left.ignoreAdaptiveScaling=!0,this._top.ignoreAdaptiveScaling=!0},t.prototype._markMatrixAsDirty=function(){this._isMatrixDirty=!0,this._markAsDirty()},t.prototype._markAsDirty=function(){this._isDirty=!0,this._host&&this._host.markAsDirty()},t.prototype._markAllAsDirty=function(){this._markAsDirty(),this._font&&this._prepareFont()},t.prototype._link=function(t,e){this._root=t,this._host=e},t.prototype._transform=function(t){if(this._isMatrixDirty||1!==this._scaleX||1!==this._scaleY||0!==this._rotation){var e=this._currentMeasure.width*this._transformCenterX+this._currentMeasure.left,i=this._currentMeasure.height*this._transformCenterY+this._currentMeasure.top;t.translate(e,i),t.rotate(this._rotation),t.scale(this._scaleX,this._scaleY),t.translate(-e,-i),(this._isMatrixDirty||this._cachedOffsetX!==e||this._cachedOffsetY!==i)&&(this._cachedOffsetX=e,this._cachedOffsetY=i,this._isMatrixDirty=!1,s.Matrix2D.ComposeToRef(-e,-i,this._rotation,this._scaleX,this._scaleY,this._root?this._root._transformMatrix:null,this._transformMatrix),this._transformMatrix.invertToRef(this._invertTransformMatrix))}},t.prototype._applyStates=function(t){this._fontSet&&(this._prepareFont(),this._fontSet=!1),this._font&&(t.font=this._font),this._color&&(t.fillStyle=this._color),this._alphaSet&&(t.globalAlpha=this._alpha)},t.prototype._processMeasures=function(t,e){return!this._isDirty&&this._cachedParentMeasure.isEqualsTo(t)||(this._isDirty=!1,this._currentMeasure.copyFrom(t),this._preMeasure(t,e),this._measure(),this._computeAlignment(t,e),this._currentMeasure.left=0|this._currentMeasure.left,this._currentMeasure.top=0|this._currentMeasure.top,this._currentMeasure.width=0|this._currentMeasure.width,this._currentMeasure.height=0|this._currentMeasure.height,this._additionalProcessing(t,e),this._cachedParentMeasure.copyFrom(t),this.onDirtyObservable.hasObservers()&&this.onDirtyObservable.notifyObservers(this)),!(this._currentMeasure.left>t.left+t.width)&&(!(this._currentMeasure.left+this._currentMeasure.widtht.top+t.height)&&(!(this._currentMeasure.top+this._currentMeasure.heightthis._currentMeasure.left+this._currentMeasure.width)&&(!(ethis._currentMeasure.top+this._currentMeasure.height)&&(this.isPointerBlocker&&(this._host._shouldBlockPointer=!0),!0))))},t.prototype._processPicking=function(t,e,i,r,n){return!(!this.isHitTestVisible||!this.isVisible||this._doNotRender)&&(!!this.contains(t,e)&&(this._processObservables(i,t,e,r,n),!0))},t.prototype._onPointerMove=function(t,e){this.onPointerMoveObservable.notifyObservers(e,-1,t,this)&&null!=this.parent&&this.parent._onPointerMove(t,e)},t.prototype._onPointerEnter=function(t){return!(this._enterCount>0)&&(-1===this._enterCount&&(this._enterCount=0),this._enterCount++,this.onPointerEnterObservable.notifyObservers(this,-1,t,this)&&null!=this.parent&&this.parent._onPointerEnter(t),!0)},t.prototype._onPointerOut=function(t){this._enterCount=0,this.onPointerOutObservable.notifyObservers(this,-1,t,this)&&null!=this.parent&&this.parent._onPointerOut(t)},t.prototype._onPointerDown=function(t,e,i,r){return 0===this._downCount&&(this._downCount++,this._downPointerIds[i]=!0,this.onPointerDownObservable.notifyObservers(new s.Vector2WithInfo(e,r),-1,t,this)&&null!=this.parent&&this.parent._onPointerDown(t,e,i,r),!0)},t.prototype._onPointerUp=function(t,e,i,r,n){this._downCount=0,delete this._downPointerIds[i];var o=n;n&&(this._enterCount>0||-1===this._enterCount)&&(o=this.onPointerClickObservable.notifyObservers(new s.Vector2WithInfo(e,r),-1,t,this)),this.onPointerUpObservable.notifyObservers(new s.Vector2WithInfo(e,r),-1,t,this)&&null!=this.parent&&this.parent._onPointerUp(t,e,i,r,o)},t.prototype._forcePointerUp=function(t){if(void 0===t&&(t=null),null!==t)this._onPointerUp(this,n.Vector2.Zero(),t,0,!0);else for(var e in this._downPointerIds)this._onPointerUp(this,n.Vector2.Zero(),+e,0,!0)},t.prototype._processObservables=function(t,e,i,r,o){if(this._dummyVector2.copyFromFloats(e,i),t===n.PointerEventTypes.POINTERMOVE){this._onPointerMove(this,this._dummyVector2);var s=this._host._lastControlOver[r];return s&&s!==this&&s._onPointerOut(this),s!==this&&this._onPointerEnter(this),this._host._lastControlOver[r]=this,!0}return t===n.PointerEventTypes.POINTERDOWN?(this._onPointerDown(this,this._dummyVector2,r,o),this._host._lastControlDown[r]=this,this._host._lastPickedControl=this,!0):t===n.PointerEventTypes.POINTERUP&&(this._host._lastControlDown[r]&&this._host._lastControlDown[r]._onPointerUp(this,this._dummyVector2,r,o,!0),delete this._host._lastControlDown[r],!0)},t.prototype._prepareFont=function(){(this._font||this._fontSet)&&(this._style?this._font=this._style.fontStyle+" "+this._style.fontWeight+" "+this.fontSizeInPixels+"px "+this._style.fontFamily:this._font=this._fontStyle+" "+this._fontWeight+" "+this.fontSizeInPixels+"px "+this._fontFamily,this._fontOffset=t._GetFontOffset(this._font))},t.prototype.dispose=function(){this.onDirtyObservable.clear(),this.onAfterDrawObservable.clear(),this.onPointerDownObservable.clear(),this.onPointerEnterObservable.clear(),this.onPointerMoveObservable.clear(),this.onPointerOutObservable.clear(),this.onPointerUpObservable.clear(),this.onPointerClickObservable.clear(),this._styleObserver&&this._style&&(this._style.onChangedObservable.remove(this._styleObserver),this._styleObserver=null),this._root&&(this._root.removeControl(this),this._root=null),this._host._linkedControls.indexOf(this)>-1&&this.linkWithMesh(null)},Object.defineProperty(t,"HORIZONTAL_ALIGNMENT_LEFT",{get:function(){return t._HORIZONTAL_ALIGNMENT_LEFT},enumerable:!0,configurable:!0}),Object.defineProperty(t,"HORIZONTAL_ALIGNMENT_RIGHT",{get:function(){return t._HORIZONTAL_ALIGNMENT_RIGHT},enumerable:!0,configurable:!0}),Object.defineProperty(t,"HORIZONTAL_ALIGNMENT_CENTER",{get:function(){return t._HORIZONTAL_ALIGNMENT_CENTER},enumerable:!0,configurable:!0}),Object.defineProperty(t,"VERTICAL_ALIGNMENT_TOP",{get:function(){return t._VERTICAL_ALIGNMENT_TOP},enumerable:!0,configurable:!0}),Object.defineProperty(t,"VERTICAL_ALIGNMENT_BOTTOM",{get:function(){return t._VERTICAL_ALIGNMENT_BOTTOM},enumerable:!0,configurable:!0}),Object.defineProperty(t,"VERTICAL_ALIGNMENT_CENTER",{get:function(){return t._VERTICAL_ALIGNMENT_CENTER},enumerable:!0,configurable:!0}),t._GetFontOffset=function(e){if(t._FontHeightSizes[e])return t._FontHeightSizes[e];var i=document.createElement("span");i.innerHTML="Hg",i.style.font=e;var r=document.createElement("div");r.style.display="inline-block",r.style.width="1px",r.style.height="0px",r.style.verticalAlign="bottom";var n=document.createElement("div");n.appendChild(i),n.appendChild(r),document.body.appendChild(n);var o=0,s=0;try{s=r.getBoundingClientRect().top-i.getBoundingClientRect().top,r.style.verticalAlign="baseline",o=r.getBoundingClientRect().top-i.getBoundingClientRect().top}finally{document.body.removeChild(n)}var a={ascent:o,height:s,descent:s-o};return t._FontHeightSizes[e]=a,a},t.drawEllipse=function(t,e,i,r,n){n.translate(t,e),n.scale(i,r),n.beginPath(),n.arc(0,0,1,0,2*Math.PI),n.closePath(),n.scale(1/i,1/r),n.translate(-t,-e)},t._HORIZONTAL_ALIGNMENT_LEFT=0,t._HORIZONTAL_ALIGNMENT_RIGHT=1,t._HORIZONTAL_ALIGNMENT_CENTER=2,t._VERTICAL_ALIGNMENT_TOP=0,t._VERTICAL_ALIGNMENT_BOTTOM=1,t._VERTICAL_ALIGNMENT_CENTER=2,t._FontHeightSizes={},t.AddHeader=function(){},t}();e.Control=a},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(e,i,r){void 0===i&&(i=t.UNITMODE_PIXEL),void 0===r&&(r=!0),this.unit=i,this.negativeValueAllowed=r,this._value=1,this.ignoreAdaptiveScaling=!1,this._value=e}return Object.defineProperty(t.prototype,"isPercentage",{get:function(){return this.unit===t.UNITMODE_PERCENTAGE},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isPixel",{get:function(){return this.unit===t.UNITMODE_PIXEL},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"internalValue",{get:function(){return this._value},enumerable:!0,configurable:!0}),t.prototype.getValueInPixel=function(t,e){return this.isPixel?this.getValue(t):this.getValue(t)*e},t.prototype.getValue=function(e){if(e&&!this.ignoreAdaptiveScaling&&this.unit!==t.UNITMODE_PERCENTAGE){var i=0,r=0;if(e.idealWidth&&(i=this._value*e.getSize().width/e.idealWidth),e.idealHeight&&(r=this._value*e.getSize().height/e.idealHeight),e.useSmallestIdeal&&e.idealWidth&&e.idealHeight)return window.innerWidtht.zIndex)return void this._children.splice(e,0,t);this._children.push(t),t.parent=this,this._markAsDirty()},e.prototype._markMatrixAsDirty=function(){t.prototype._markMatrixAsDirty.call(this);for(var e=0;e=0&&(this.width=i+"px"),this.adaptHeightToChildren&&r>=0&&(this.height=r+"px")}e.restore(),this.onAfterDrawObservable.hasObservers()&&this.onAfterDrawObservable.notifyObservers(this)}},e.prototype._processPicking=function(e,i,r,n,o){if(!this.isVisible||this.notRenderable)return!1;if(!t.prototype.contains.call(this,e,i))return!1;for(var s=this._children.length-1;s>=0;s--){if(this._children[s]._processPicking(e,i,r,n,o))return!0}return!!this.isHitTestVisible&&this._processObservables(r,e,i,n,o)},e.prototype._clipForChildren=function(t){},e.prototype._additionalProcessing=function(e,i){t.prototype._additionalProcessing.call(this,e,i),this._measureForChildren.copyFrom(this._currentMeasure)},e.prototype.dispose=function(){t.prototype.dispose.call(this);for(var e=0,i=this._children;ei));d++);else for(d=0;di));p++);f=0;for(var y=0,g=this._children;yr&&(r=h._currentMeasure.width),h.verticalAlignment=s.Control.VERTICAL_ALIGNMENT_TOP):(h.left=r+"px",h._left.ignoreAdaptiveScaling||h._markAsDirty(),h._left.ignoreAdaptiveScaling=!0,r+=h._currentMeasure.width,h._currentMeasure.height>n&&(n=h._currentMeasure.height),h.horizontalAlignment=s.Control.HORIZONTAL_ALIGNMENT_LEFT),h._currentMeasure.copyFrom(this._tempMeasureStore)}this._doNotTrackManualChanges=!0;var l,u,c=this.height,_=this.width;this._manualHeight||(this.height=n+"px"),this._manualWidth||(this.width=r+"px"),l=_!==this.width||!this._width.ignoreAdaptiveScaling,(u=c!==this.height||!this._height.ignoreAdaptiveScaling)&&(this._height.ignoreAdaptiveScaling=!0),l&&(this._width.ignoreAdaptiveScaling=!0),this._doNotTrackManualChanges=!1,(l||u)&&this._markAllAsDirty(),t.prototype._preMeasure.call(this,e,i)},e}(n.Container);e.StackPanel=a},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n,o=i(0),s=i(2),a=i(1);!function(t){t[t.Clip=0]="Clip",t[t.WordWrap=1]="WordWrap",t[t.Ellipsis=2]="Ellipsis"}(n=e.TextWrapping||(e.TextWrapping={}));var h=function(t){function e(e,i){void 0===i&&(i="");var r=t.call(this,e)||this;return r.name=e,r._text="",r._textWrapping=n.Clip,r._textHorizontalAlignment=a.Control.HORIZONTAL_ALIGNMENT_CENTER,r._textVerticalAlignment=a.Control.VERTICAL_ALIGNMENT_CENTER,r._resizeToFit=!1,r._lineSpacing=new s.ValueAndUnit(0),r._outlineWidth=0,r._outlineColor="white",r.onTextChangedObservable=new o.Observable,r.onLinesReadyObservable=new o.Observable,r.text=i,r}return r(e,t),Object.defineProperty(e.prototype,"lines",{get:function(){return this._lines},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"resizeToFit",{get:function(){return this._resizeToFit},set:function(t){this._resizeToFit=t,this._resizeToFit&&(this._width.ignoreAdaptiveScaling=!0,this._height.ignoreAdaptiveScaling=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"textWrapping",{get:function(){return this._textWrapping},set:function(t){this._textWrapping!==t&&(this._textWrapping=+t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"text",{get:function(){return this._text},set:function(t){this._text!==t&&(this._text=t,this._markAsDirty(),this.onTextChangedObservable.notifyObservers(this))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"textHorizontalAlignment",{get:function(){return this._textHorizontalAlignment},set:function(t){this._textHorizontalAlignment!==t&&(this._textHorizontalAlignment=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"textVerticalAlignment",{get:function(){return this._textVerticalAlignment},set:function(t){this._textVerticalAlignment!==t&&(this._textVerticalAlignment=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lineSpacing",{get:function(){return this._lineSpacing.toString(this._host)},set:function(t){this._lineSpacing.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outlineWidth",{get:function(){return this._outlineWidth},set:function(t){this._outlineWidth!==t&&(this._outlineWidth=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outlineColor",{get:function(){return this._outlineColor},set:function(t){this._outlineColor!==t&&(this._outlineColor=t,this._markAsDirty())},enumerable:!0,configurable:!0}),e.prototype._getTypeName=function(){return"TextBlock"},e.prototype._drawText=function(t,e,i,r){var n=this._currentMeasure.width,o=0;switch(this._textHorizontalAlignment){case a.Control.HORIZONTAL_ALIGNMENT_LEFT:o=0;break;case a.Control.HORIZONTAL_ALIGNMENT_RIGHT:o=n-e;break;case a.Control.HORIZONTAL_ALIGNMENT_CENTER:o=(n-e)/2}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(r.shadowColor=this.shadowColor,r.shadowBlur=this.shadowBlur,r.shadowOffsetX=this.shadowOffsetX,r.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&r.strokeText(t,this._currentMeasure.left+o,i),r.fillText(t,this._currentMeasure.left+o,i)},e.prototype._draw=function(t,e){e.save(),this._applyStates(e),this._processMeasures(t,e)&&this._renderLines(e),e.restore()},e.prototype._applyStates=function(e){t.prototype._applyStates.call(this,e),this.outlineWidth&&(e.lineWidth=this.outlineWidth,e.strokeStyle=this.outlineColor)},e.prototype._additionalProcessing=function(t,e){this._lines=this._breakLines(this._currentMeasure.width,e),this.onLinesReadyObservable.notifyObservers(this)},e.prototype._breakLines=function(t,e){var i=[],r=this.text.split("\n");if(this._textWrapping!==n.Ellipsis||this._resizeToFit)if(this._textWrapping!==n.WordWrap||this._resizeToFit)for(var o=0,s=r;oe&&(t+="…");t.length>2&&r>e;)t=t.slice(0,-2)+"…",r=i.measureText(t).width;return{text:t,width:r}},e.prototype._parseLineWordWrap=function(t,e,i){void 0===t&&(t="");for(var r=[],n=t.split(" "),o=0,s=0;s0?t+" "+n[s]:n[0],h=i.measureText(a).width;h>e&&s>0?(r.push({text:t,width:o}),t=n[s],o=i.measureText(t).width):(o=h,t=a)}return r.push({text:t,width:o}),r},e.prototype._renderLines=function(t){var e=this._currentMeasure.height;this._fontOffset||(this._fontOffset=a.Control._GetFontOffset(t.font));var i=0;switch(this._textVerticalAlignment){case a.Control.VERTICAL_ALIGNMENT_TOP:i=this._fontOffset.ascent;break;case a.Control.VERTICAL_ALIGNMENT_BOTTOM:i=e-this._fontOffset.height*(this._lines.length-1)-this._fontOffset.descent;break;case a.Control.VERTICAL_ALIGNMENT_CENTER:i=this._fontOffset.ascent+(e-this._fontOffset.height*this._lines.length)/2}i+=this._currentMeasure.top;for(var r=0,n=0;nr&&(r=o.width)}this._resizeToFit&&(this.width=this.paddingLeftInPixels+this.paddingRightInPixels+r+"px",this.height=this.paddingTopInPixels+this.paddingBottomInPixels+this._fontOffset.height*this._lines.length+"px")},e.prototype.computeExpectedHeight=function(){if(this.text&&this.widthInPixels){var t=document.createElement("canvas").getContext("2d");if(t){this._applyStates(t),this._fontOffset||(this._fontOffset=a.Control._GetFontOffset(t.font));var e=this._lines?this._lines:this._breakLines(this.widthInPixels-this.paddingLeftInPixels-this.paddingRightInPixels,t);return this.paddingTopInPixels+this.paddingBottomInPixels+this._fontOffset.height*e.length}}return 0},e.prototype.dispose=function(){t.prototype.dispose.call(this),this.onTextChangedObservable.clear()},e}(a.Control);e.TextBlock=h},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(14),o=i(0),s=i(16),a=function(t){function e(e){var i=t.call(this,e)||this;return i._contentResolution=512,i._contentScaleRatio=2,i.pointerEnterAnimation=function(){i.mesh&&(i._currentMaterial.emissiveColor=o.Color3.Red())},i.pointerOutAnimation=function(){i._currentMaterial.emissiveColor=o.Color3.Black()},i.pointerDownAnimation=function(){i.mesh&&i.mesh.scaling.scaleInPlace(.95)},i.pointerUpAnimation=function(){i.mesh&&i.mesh.scaling.scaleInPlace(1/.95)},i}return r(e,t),Object.defineProperty(e.prototype,"contentResolution",{get:function(){return this._contentResolution},set:function(t){this._contentResolution!==t&&(this._contentResolution=t,this._resetContent())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"contentScaleRatio",{get:function(){return this._contentScaleRatio},set:function(t){this._contentScaleRatio!==t&&(this._contentScaleRatio=t,this._resetContent())},enumerable:!0,configurable:!0}),e.prototype._disposeFacadeTexture=function(){this._facadeTexture&&(this._facadeTexture.dispose(),this._facadeTexture=null)},e.prototype._resetContent=function(){this._disposeFacadeTexture(),this.content=this._content},Object.defineProperty(e.prototype,"content",{get:function(){return this._content},set:function(t){this._content=t,this._host&&this._host.utilityLayer&&(this._facadeTexture||(this._facadeTexture=new s.AdvancedDynamicTexture("Facade",this._contentResolution,this._contentResolution,this._host.utilityLayer.utilityLayerScene,!0,o.Texture.TRILINEAR_SAMPLINGMODE),this._facadeTexture.rootContainer.scaleX=this._contentScaleRatio,this._facadeTexture.rootContainer.scaleY=this._contentScaleRatio,this._facadeTexture.premulAlpha=!0),this._facadeTexture.addControl(t),this._applyFacade(this._facadeTexture))},enumerable:!0,configurable:!0}),e.prototype._applyFacade=function(t){this._currentMaterial.emissiveTexture=t},e.prototype._getTypeName=function(){return"Button3D"},e.prototype._createNode=function(t){for(var e=new Array(6),i=0;i<6;i++)e[i]=new o.Vector4(0,0,0,0);return e[1]=new o.Vector4(0,0,1,1),o.MeshBuilder.CreateBox(this.name+"_rootMesh",{width:1,height:1,depth:.08,faceUV:e},t)},e.prototype._affectMaterial=function(t){var e=new o.StandardMaterial(this.name+"Material",t.getScene());e.specularColor=o.Color3.Black(),t.material=e,this._currentMaterial=e,this._resetContent()},e.prototype.dispose=function(){t.prototype.dispose.call(this),this._disposeFacadeTexture(),this._currentMaterial&&this._currentMaterial.dispose()},e}(n.AbstractButton3D);e.Button3D=a},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=i(0),n=i(13),o=function(){function t(t){this.name=t,this._downCount=0,this._enterCount=-1,this._downPointerIds={},this._isVisible=!0,this.onPointerMoveObservable=new r.Observable,this.onPointerOutObservable=new r.Observable,this.onPointerDownObservable=new r.Observable,this.onPointerUpObservable=new r.Observable,this.onPointerClickObservable=new r.Observable,this.onPointerEnterObservable=new r.Observable,this._behaviors=new Array}return Object.defineProperty(t.prototype,"position",{get:function(){return this._node?this._node.position:r.Vector3.Zero()},set:function(t){this._node&&(this._node.position=t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this._node?this._node.scaling:new r.Vector3(1,1,1)},set:function(t){this._node&&(this._node.scaling=t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"behaviors",{get:function(){return this._behaviors},enumerable:!0,configurable:!0}),t.prototype.addBehavior=function(t){var e=this;if(-1!==this._behaviors.indexOf(t))return this;t.init();var i=this._host.scene;return i.isLoading?i.onDataLoadedObservable.addOnce(function(){t.attach(e)}):t.attach(this),this._behaviors.push(t),this},t.prototype.removeBehavior=function(t){var e=this._behaviors.indexOf(t);return-1===e?this:(this._behaviors[e].detach(),this._behaviors.splice(e,1),this)},t.prototype.getBehaviorByName=function(t){for(var e=0,i=this._behaviors;e0)&&(-1===this._enterCount&&(this._enterCount=0),this._enterCount++,this.onPointerEnterObservable.notifyObservers(this,-1,t,this),this.pointerEnterAnimation&&this.pointerEnterAnimation(),!0)},t.prototype._onPointerOut=function(t){this._enterCount=0,this.onPointerOutObservable.notifyObservers(this,-1,t,this),this.pointerOutAnimation&&this.pointerOutAnimation()},t.prototype._onPointerDown=function(t,e,i,r){return 0===this._downCount&&(this._downCount++,this._downPointerIds[i]=!0,this.onPointerDownObservable.notifyObservers(new n.Vector3WithInfo(e,r),-1,t,this),this.pointerDownAnimation&&this.pointerDownAnimation(),!0)},t.prototype._onPointerUp=function(t,e,i,r,o){this._downCount=0,delete this._downPointerIds[i],o&&(this._enterCount>0||-1===this._enterCount)&&this.onPointerClickObservable.notifyObservers(new n.Vector3WithInfo(e,r),-1,t,this),this.onPointerUpObservable.notifyObservers(new n.Vector3WithInfo(e,r),-1,t,this),this.pointerUpAnimation&&this.pointerUpAnimation()},t.prototype.forcePointerUp=function(t){if(void 0===t&&(t=null),null!==t)this._onPointerUp(this,r.Vector3.Zero(),t,0,!0);else for(var e in this._downPointerIds)this._onPointerUp(this,r.Vector3.Zero(),+e,0,!0)},t.prototype._processObservables=function(t,e,i,n){if(t===r.PointerEventTypes.POINTERMOVE){this._onPointerMove(this,e);var o=this._host._lastControlOver[i];return o&&o!==this&&o._onPointerOut(this),o!==this&&this._onPointerEnter(this),this._host._lastControlOver[i]=this,!0}return t===r.PointerEventTypes.POINTERDOWN?(this._onPointerDown(this,e,i,n),this._host._lastControlDown[i]=this,this._host._lastPickedControl=this,!0):t===r.PointerEventTypes.POINTERUP&&(this._host._lastControlDown[i]&&this._host._lastControlDown[i]._onPointerUp(this,e,i,n,!0),delete this._host._lastControlDown[i],!0)},t.prototype._disposeNode=function(){this._node&&(this._node.dispose(),this._node=null)},t.prototype.dispose=function(){this.onPointerDownObservable.clear(),this.onPointerEnterObservable.clear(),this.onPointerMoveObservable.clear(),this.onPointerOutObservable.clear(),this.onPointerUpObservable.clear(),this.onPointerClickObservable.clear(),this._disposeNode();for(var t=0,e=this._behaviors;t>0,l=this.cellId%a;r=this.cellWidth*l,n=this.cellHeight*h,o=this.cellWidth,s=this.cellHeight}if(this._applyStates(i),this._processMeasures(t,i)&&this._loaded)switch(this._stretch){case e.STRETCH_NONE:case e.STRETCH_FILL:i.drawImage(this._domImage,r,n,o,s,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case e.STRETCH_UNIFORM:var u=this._currentMeasure.width/o,c=this._currentMeasure.height/s,_=Math.min(u,c),f=(this._currentMeasure.width-o*_)/2,p=(this._currentMeasure.height-s*_)/2;i.drawImage(this._domImage,r,n,o,s,this._currentMeasure.left+f,this._currentMeasure.top+p,o*_,s*_);break;case e.STRETCH_EXTEND:i.drawImage(this._domImage,r,n,o,s,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height),this._autoScale&&this.synchronizeSizeWithContent(),this._root&&this._root.parent&&(this._root.width=this.width,this._root.height=this.height)}i.restore()},Object.defineProperty(e,"STRETCH_NONE",{get:function(){return e._STRETCH_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(e,"STRETCH_FILL",{get:function(){return e._STRETCH_FILL},enumerable:!0,configurable:!0}),Object.defineProperty(e,"STRETCH_UNIFORM",{get:function(){return e._STRETCH_UNIFORM},enumerable:!0,configurable:!0}),Object.defineProperty(e,"STRETCH_EXTEND",{get:function(){return e._STRETCH_EXTEND},enumerable:!0,configurable:!0}),e._STRETCH_NONE=0,e._STRETCH_FILL=1,e._STRETCH_UNIFORM=2,e._STRETCH_EXTEND=3,e}(n.Control);e.Image=s},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}(),n=this&&this.__decorate||function(t,e,i,r){var n,o=arguments.length,s=o<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,i,r);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(s=(o<3?n(s):o>3?n(e,i,s):n(e,i))||s);return o>3&&s&&Object.defineProperty(e,i,s),s};Object.defineProperty(e,"__esModule",{value:!0});var o=i(0);i(31).registerShader();var s=function(t){function e(){var e=t.call(this)||this;return e.INNERGLOW=!1,e.BORDER=!1,e.HOVERLIGHT=!1,e.rebuild(),e}return r(e,t),e}(o.MaterialDefines);e.FluentMaterialDefines=s;var a=function(t){function e(e,i){var r=t.call(this,e,i)||this;return r.innerGlowColorIntensity=.5,r.innerGlowColor=new o.Color3(1,1,1),r.alpha=1,r.albedoColor=new o.Color3(.3,.35,.4),r.renderBorders=!1,r.borderWidth=.5,r.edgeSmoothingValue=.02,r.borderMinValue=.1,r.renderHoverLight=!1,r.hoverRadius=1,r.hoverColor=new o.Color4(.3,.3,.3,1),r.hoverPosition=o.Vector3.Zero(),r}return r(e,t),e.prototype.needAlphaBlending=function(){return 1!==this.alpha},e.prototype.needAlphaTesting=function(){return!1},e.prototype.getAlphaTestTexture=function(){return null},e.prototype.isReadyForSubMesh=function(t,e,i){if(this.isFrozen&&this._wasPreviouslyReady&&e.effect)return!0;e._materialDefines||(e._materialDefines=new s);var r=this.getScene(),n=e._materialDefines;if(!this.checkReadyOnEveryCall&&e.effect&&n._renderId===r.getRenderId())return!0;n._areTexturesDirty&&(n.INNERGLOW=this.innerGlowColorIntensity>0,n.BORDER=this.renderBorders,n.HOVERLIGHT=this.renderHoverLight);var a=r.getEngine();if(n.isDirty){n.markAsProcessed(),r.resetCachedMaterial();var h=[o.VertexBuffer.PositionKind];h.push(o.VertexBuffer.NormalKind),h.push(o.VertexBuffer.UVKind);var l=["world","viewProjection","innerGlowColor","albedoColor","borderWidth","edgeSmoothingValue","scaleFactor","borderMinValue","hoverColor","hoverPosition","hoverRadius"],u=new Array,c=new Array;o.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:l,uniformBuffersNames:c,samplers:u,defines:n,maxSimultaneousLights:4});var _=n.toString();e.setEffect(r.getEngine().createEffect("fluent",{attributes:h,uniformsNames:l,uniformBuffersNames:c,samplers:u,defines:_,fallbacks:null,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},a))}return!(!e.effect||!e.effect.isReady())&&(n._renderId=r.getRenderId(),this._wasPreviouslyReady=!0,!0)},e.prototype.bindForSubMesh=function(t,e,i){var r=this.getScene(),n=i._materialDefines;if(n){var s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(t),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._mustRebind(r,s)&&(this._activeEffect.setColor4("albedoColor",this.albedoColor,this.alpha),n.INNERGLOW&&this._activeEffect.setColor4("innerGlowColor",this.innerGlowColor,this.innerGlowColorIntensity),n.BORDER&&(this._activeEffect.setFloat("borderWidth",this.borderWidth),this._activeEffect.setFloat("edgeSmoothingValue",this.edgeSmoothingValue),this._activeEffect.setFloat("borderMinValue",this.borderMinValue),e.getBoundingInfo().boundingBox.extendSize.multiplyToRef(e.scaling,o.Tmp.Vector3[0]),this._activeEffect.setVector3("scaleFactor",o.Tmp.Vector3[0])),n.HOVERLIGHT&&(this._activeEffect.setDirectColor4("hoverColor",this.hoverColor),this._activeEffect.setFloat("hoverRadius",this.hoverRadius),this._activeEffect.setVector3("hoverPosition",this.hoverPosition))),this._afterBind(e,this._activeEffect))}},e.prototype.getActiveTextures=function(){return t.prototype.getActiveTextures.call(this)},e.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)},e.prototype.dispose=function(e){t.prototype.dispose.call(this,e)},e.prototype.clone=function(t){var i=this;return o.SerializationHelper.Clone(function(){return new e(t,i.getScene())},this)},e.prototype.serialize=function(){var t=o.SerializationHelper.Serialize(this);return t.customType="BABYLON.GUI.FluentMaterial",t},e.prototype.getClassName=function(){return"FluentMaterial"},e.Parse=function(t,i,r){return o.SerializationHelper.Parse(function(){return new e(t.name,i)},t,i,r)},n([o.serialize(),o.expandToProperty("_markAllSubMeshesAsTexturesDirty")],e.prototype,"innerGlowColorIntensity",void 0),n([o.serializeAsColor3()],e.prototype,"innerGlowColor",void 0),n([o.serialize()],e.prototype,"alpha",void 0),n([o.serializeAsColor3()],e.prototype,"albedoColor",void 0),n([o.serialize(),o.expandToProperty("_markAllSubMeshesAsTexturesDirty")],e.prototype,"renderBorders",void 0),n([o.serialize()],e.prototype,"borderWidth",void 0),n([o.serialize()],e.prototype,"edgeSmoothingValue",void 0),n([o.serialize()],e.prototype,"borderMinValue",void 0),n([o.serialize(),o.expandToProperty("_markAllSubMeshesAsTexturesDirty")],e.prototype,"renderHoverLight",void 0),n([o.serialize()],e.prototype,"hoverRadius",void 0),n([o.serializeAsColor4()],e.prototype,"hoverColor",void 0),n([o.serializeAsVector3()],e.prototype,"hoverPosition",void 0),e}(o.PushMaterial);e.FluentMaterial=a},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=function(t){function e(e,i){void 0===i&&(i=0);var r=t.call(this,e.x,e.y,e.z)||this;return r.buttonIndex=i,r}return r(e,t),e}(i(0).Vector3);e.Vector3WithInfo=n},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(10),o=i(0),s=function(t){function e(e){return t.call(this,e)||this}return r(e,t),e.prototype._getTypeName=function(){return"AbstractButton3D"},e.prototype._createNode=function(t){return new o.TransformNode("button"+this.name)},e}(n.Control3D);e.AbstractButton3D=s},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=i(0),n=i(2),o=function(){function t(t){this._fontFamily="Arial",this._fontStyle="",this._fontWeight="",this._fontSize=new n.ValueAndUnit(18,n.ValueAndUnit.UNITMODE_PIXEL,!1),this.onChangedObservable=new r.Observable,this._host=t}return Object.defineProperty(t.prototype,"fontSize",{get:function(){return this._fontSize.toString(this._host)},set:function(t){this._fontSize.toString(this._host)!==t&&this._fontSize.fromString(t)&&this.onChangedObservable.notifyObservers(this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontFamily",{get:function(){return this._fontFamily},set:function(t){this._fontFamily!==t&&(this._fontFamily=t,this.onChangedObservable.notifyObservers(this))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontStyle",{get:function(){return this._fontStyle},set:function(t){this._fontStyle!==t&&(this._fontStyle=t,this.onChangedObservable.notifyObservers(this))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontWeight",{get:function(){return this._fontWeight},set:function(t){this._fontWeight!==t&&(this._fontWeight=t,this.onChangedObservable.notifyObservers(this))},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.onChangedObservable.clear()},t}();e.Style=o},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(0),o=i(4),s=i(15),a=i(6),h=function(t){function e(e,i,r,s,a,h){void 0===i&&(i=0),void 0===r&&(r=0),void 0===a&&(a=!1),void 0===h&&(h=n.Texture.NEAREST_SAMPLINGMODE);var l=t.call(this,e,{width:i,height:r},s,a,h,n.Engine.TEXTUREFORMAT_RGBA)||this;return l._isDirty=!1,l._rootContainer=new o.Container("root"),l._lastControlOver={},l._lastControlDown={},l._capturingControl={},l._linkedControls=new Array,l._isFullscreen=!1,l._fullscreenViewport=new n.Viewport(0,0,1,1),l._idealWidth=0,l._idealHeight=0,l._useSmallestIdeal=!1,l._renderAtIdealSize=!1,l._blockNextFocusCheck=!1,l._renderScale=1,l.premulAlpha=!1,(s=l.getScene())&&l._texture?(l._renderObserver=s.onBeforeCameraRenderObservable.add(function(t){return l._checkUpdate(t)}),l._preKeyboardObserver=s.onPreKeyboardObservable.add(function(t){l._focusedControl&&(t.type===n.KeyboardEventTypes.KEYDOWN&&l._focusedControl.processKeyboard(t.event),t.skipOnPointerObservable=!0)}),l._rootContainer._link(null,l),l.hasAlpha=!0,i&&r||(l._resizeObserver=s.getEngine().onResizeObservable.add(function(){return l._onResize()}),l._onResize()),l._texture.isReady=!0,l):l}return r(e,t),Object.defineProperty(e.prototype,"renderScale",{get:function(){return this._renderScale},set:function(t){t!==this._renderScale&&(this._renderScale=t,this._onResize())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"background",{get:function(){return this._background},set:function(t){this._background!==t&&(this._background=t,this.markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"idealWidth",{get:function(){return this._idealWidth},set:function(t){this._idealWidth!==t&&(this._idealWidth=t,this.markAsDirty(),this._rootContainer._markAllAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"idealHeight",{get:function(){return this._idealHeight},set:function(t){this._idealHeight!==t&&(this._idealHeight=t,this.markAsDirty(),this._rootContainer._markAllAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useSmallestIdeal",{get:function(){return this._useSmallestIdeal},set:function(t){this._useSmallestIdeal!==t&&(this._useSmallestIdeal=t,this.markAsDirty(),this._rootContainer._markAllAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderAtIdealSize",{get:function(){return this._renderAtIdealSize},set:function(t){this._renderAtIdealSize!==t&&(this._renderAtIdealSize=t,this._onResize())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"layer",{get:function(){return this._layerToDispose},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rootContainer",{get:function(){return this._rootContainer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"focusedControl",{get:function(){return this._focusedControl},set:function(t){this._focusedControl!=t&&(this._focusedControl&&this._focusedControl.onBlur(),t&&t.onFocus(),this._focusedControl=t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isForeground",{get:function(){return!this.layer||!this.layer.isBackground},set:function(t){this.layer&&this.layer.isBackground!==!t&&(this.layer.isBackground=!t)},enumerable:!0,configurable:!0}),e.prototype.executeOnAllControls=function(t,e){e||(e=this._rootContainer);for(var i=0,r=e.children;i1?s.notRenderable=!0:(s.notRenderable=!1,l.scaleInPlace(this.renderScale),s._moveToProjectedPosition(l))}else n.Tools.SetImmediate(function(){s.linkWithMesh(null)})}}}(this._isDirty||this._rootContainer.isDirty)&&(this._isDirty=!1,this._render(),this.update(!0,this.premulAlpha))}},e.prototype._render=function(){var t=this.getSize(),e=t.width,i=t.height,r=this.getContext();r.clearRect(0,0,e,i),this._background&&(r.save(),r.fillStyle=this._background,r.fillRect(0,0,e,i),r.restore()),r.font="18px Arial",r.strokeStyle="white";var n=new a.Measure(0,0,e,i);this._rootContainer._draw(n,r)},e.prototype._doPicking=function(t,e,i,r,o){var s=this.getScene();if(s){var a=s.getEngine(),h=this.getSize();this._isFullscreen&&(t*=h.width/a.getRenderWidth(),e*=h.height/a.getRenderHeight()),this._capturingControl[r]?this._capturingControl[r]._processObservables(i,t,e,r,o):(this._rootContainer._processPicking(t,e,i,r,o)||i===n.PointerEventTypes.POINTERMOVE&&(this._lastControlOver[r]&&this._lastControlOver[r]._onPointerOut(this._lastControlOver[r]),delete this._lastControlOver[r]),this._manageFocus())}},e.prototype._cleanControlAfterRemovalFromList=function(t,e){for(var i in t){if(t.hasOwnProperty(i))t[i]===e&&delete t[i]}},e.prototype._cleanControlAfterRemoval=function(t){this._cleanControlAfterRemovalFromList(this._lastControlDown,t),this._cleanControlAfterRemovalFromList(this._lastControlOver,t)},e.prototype.attach=function(){var t=this,e=this.getScene();e&&(this._pointerMoveObserver=e.onPrePointerObservable.add(function(i,r){if(!e.isPointerCaptured(i.event.pointerId)&&(i.type===n.PointerEventTypes.POINTERMOVE||i.type===n.PointerEventTypes.POINTERUP||i.type===n.PointerEventTypes.POINTERDOWN)&&e){var o=e.cameraToUseForPointers||e.activeCamera;if(o){var s=e.getEngine(),a=o.viewport,h=(e.pointerX/s.getHardwareScalingLevel()-a.x*s.getRenderWidth())/a.width,l=(e.pointerY/s.getHardwareScalingLevel()-a.y*s.getRenderHeight())/a.height;t._shouldBlockPointer=!1,t._doPicking(h,l,i.type,i.event.pointerId||0,i.event.button),i.skipOnPointerObservable=t._shouldBlockPointer}}}),this._attachToOnPointerOut(e))},e.prototype.attachToMesh=function(t,e){var i=this;void 0===e&&(e=!0);var r=this.getScene();r&&(this._pointerObserver=r.onPointerObservable.add(function(e,r){if(e.type===n.PointerEventTypes.POINTERMOVE||e.type===n.PointerEventTypes.POINTERUP||e.type===n.PointerEventTypes.POINTERDOWN){var o=e.event.pointerId||0;if(e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh===t){var s=e.pickInfo.getTextureCoordinates();if(s){var a=i.getSize();i._doPicking(s.x*a.width,(1-s.y)*a.height,e.type,o,e.event.button)}}else e.type===n.PointerEventTypes.POINTERUP?(i._lastControlDown[o]&&i._lastControlDown[o]._forcePointerUp(o),delete i._lastControlDown[o],i.focusedControl=null):e.type===n.PointerEventTypes.POINTERMOVE&&(i._lastControlOver[o]&&i._lastControlOver[o]._onPointerOut(i._lastControlOver[o]),delete i._lastControlOver[o])}}),t.enablePointerMoveEvents=e,this._attachToOnPointerOut(r))},e.prototype.moveFocusToControl=function(t){this.focusedControl=t,this._lastPickedControl=t,this._blockNextFocusCheck=!0},e.prototype._manageFocus=function(){if(this._blockNextFocusCheck)return this._blockNextFocusCheck=!1,void(this._lastPickedControl=this._focusedControl);if(this._focusedControl&&this._focusedControl!==this._lastPickedControl){if(this._lastPickedControl.isFocusInvisible)return;this.focusedControl=null}},e.prototype._attachToOnPointerOut=function(t){var e=this;this._canvasPointerOutObserver=t.getEngine().onCanvasPointerOutObservable.add(function(t){e._lastControlOver[t.pointerId]&&e._lastControlOver[t.pointerId]._onPointerOut(e._lastControlOver[t.pointerId]),delete e._lastControlOver[t.pointerId],e._lastControlDown[t.pointerId]&&e._lastControlDown[t.pointerId]._forcePointerUp(),delete e._lastControlDown[t.pointerId]})},e.CreateForMesh=function(t,i,r,o){void 0===i&&(i=1024),void 0===r&&(r=1024),void 0===o&&(o=!0);var s=new e(t.name+" AdvancedDynamicTexture",i,r,t.getScene(),!0,n.Texture.TRILINEAR_SAMPLINGMODE),a=new n.StandardMaterial("AdvancedDynamicTextureMaterial",t.getScene());return a.backFaceCulling=!1,a.diffuseColor=n.Color3.Black(),a.specularColor=n.Color3.Black(),a.emissiveTexture=s,a.opacityTexture=s,t.material=a,s.attachToMesh(t,o),s},e.CreateFullscreenUI=function(t,i,r,o){void 0===i&&(i=!0),void 0===r&&(r=null),void 0===o&&(o=n.Texture.BILINEAR_SAMPLINGMODE);var s=new e(t,0,0,r,!1,o),a=new n.Layer(t+"_layer",null,r,!i);return a.texture=s,s._layerToDispose=a,s._isFullscreen=!0,s.attach(),s},e}(n.DynamicTexture);e.AdvancedDynamicTexture=h},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=i(2),n=i(0),o=function(){function t(t){this._multiLine=t,this._x=new r.ValueAndUnit(0),this._y=new r.ValueAndUnit(0),this._point=new n.Vector2(0,0)}return Object.defineProperty(t.prototype,"x",{get:function(){return this._x.toString(this._multiLine._host)},set:function(t){this._x.toString(this._multiLine._host)!==t&&this._x.fromString(t)&&this._multiLine._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._y.toString(this._multiLine._host)},set:function(t){this._y.toString(this._multiLine._host)!==t&&this._y.fromString(t)&&this._multiLine._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"control",{get:function(){return this._control},set:function(t){this._control!==t&&(this._control&&this._controlObserver&&(this._control.onDirtyObservable.remove(this._controlObserver),this._controlObserver=null),this._control=t,this._control&&(this._controlObserver=this._control.onDirtyObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"mesh",{get:function(){return this._mesh},set:function(t){this._mesh!==t&&(this._mesh&&this._meshObserver&&this._mesh.getScene().onAfterCameraRenderObservable.remove(this._meshObserver),this._mesh=t,this._mesh&&(this._meshObserver=this._mesh.getScene().onAfterCameraRenderObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())},enumerable:!0,configurable:!0}),t.prototype.translate=function(){return this._point=this._translatePoint(),this._point},t.prototype._translatePoint=function(){if(null!=this._mesh)return this._multiLine._host.getProjectedPosition(this._mesh.getBoundingInfo().boundingSphere.center,this._mesh.getWorldMatrix());if(null!=this._control)return new n.Vector2(this._control.centerX,this._control.centerY);var t=this._multiLine._host,e=this._x.getValueInPixel(t,Number(t._canvas.width)),i=this._y.getValueInPixel(t,Number(t._canvas.height));return new n.Vector2(e,i)},t.prototype.dispose=function(){this.control=null,this.mesh=null},t}();e.MultiLinePoint=o},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),o=i(2),s=i(0),a=function(t){function e(e,i){void 0===i&&(i="");var r=t.call(this,e)||this;return r.name=e,r._text="",r._placeholderText="",r._background="#222222",r._focusedBackground="#000000",r._placeholderColor="gray",r._thickness=1,r._margin=new o.ValueAndUnit(10,o.ValueAndUnit.UNITMODE_PIXEL),r._autoStretchWidth=!0,r._maxWidth=new o.ValueAndUnit(1,o.ValueAndUnit.UNITMODE_PERCENTAGE,!1),r._isFocused=!1,r._blinkIsEven=!1,r._cursorOffset=0,r._deadKey=!1,r._addKey=!0,r._currentKey="",r.promptMessage="Please enter text:",r.onTextChangedObservable=new s.Observable,r.onBeforeKeyAddObservable=new s.Observable,r.onFocusObservable=new s.Observable,r.onBlurObservable=new s.Observable,r.text=i,r}return r(e,t),Object.defineProperty(e.prototype,"maxWidth",{get:function(){return this._maxWidth.toString(this._host)},set:function(t){this._maxWidth.toString(this._host)!==t&&this._maxWidth.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maxWidthInPixels",{get:function(){return this._maxWidth.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"margin",{get:function(){return this._margin.toString(this._host)},set:function(t){this._margin.toString(this._host)!==t&&this._margin.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"marginInPixels",{get:function(){return this._margin.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"autoStretchWidth",{get:function(){return this._autoStretchWidth},set:function(t){this._autoStretchWidth!==t&&(this._autoStretchWidth=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"thickness",{get:function(){return this._thickness},set:function(t){this._thickness!==t&&(this._thickness=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"focusedBackground",{get:function(){return this._focusedBackground},set:function(t){this._focusedBackground!==t&&(this._focusedBackground=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"background",{get:function(){return this._background},set:function(t){this._background!==t&&(this._background=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"placeholderColor",{get:function(){return this._placeholderColor},set:function(t){this._placeholderColor!==t&&(this._placeholderColor=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"placeholderText",{get:function(){return this._placeholderText},set:function(t){this._placeholderText!==t&&(this._placeholderText=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"deadKey",{get:function(){return this._deadKey},set:function(t){this._deadKey=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"addKey",{get:function(){return this._addKey},set:function(t){this._addKey=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentKey",{get:function(){return this._currentKey},set:function(t){this._currentKey=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"text",{get:function(){return this._text},set:function(t){this._text!==t&&(this._text=t,this._markAsDirty(),this.onTextChangedObservable.notifyObservers(this))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"width",{get:function(){return this._width.toString(this._host)},set:function(t){this._width.toString(this._host)!==t&&(this._width.fromString(t)&&this._markAsDirty(),this.autoStretchWidth=!1)},enumerable:!0,configurable:!0}),e.prototype.onBlur=function(){this._isFocused=!1,this._scrollLeft=null,this._cursorOffset=0,clearTimeout(this._blinkTimeout),this._markAsDirty(),this.onBlurObservable.notifyObservers(this)},e.prototype.onFocus=function(){if(this._scrollLeft=null,this._isFocused=!0,this._blinkIsEven=!1,this._cursorOffset=0,this._markAsDirty(),this.onFocusObservable.notifyObservers(this),-1!==navigator.userAgent.indexOf("Mobile")){var t=prompt(this.promptMessage);return null!==t&&(this.text=t),void(this._host.focusedControl=null)}},e.prototype._getTypeName=function(){return"InputText"},e.prototype.processKey=function(t,e){switch(t){case 32:e=" ";break;case 8:if(this._text&&this._text.length>0)if(0===this._cursorOffset)this.text=this._text.substr(0,this._text.length-1);else(i=this._text.length-this._cursorOffset)>0&&(this.text=this._text.slice(0,i-1)+this._text.slice(i));return;case 46:if(this._text&&this._text.length>0){var i=this._text.length-this._cursorOffset;this.text=this._text.slice(0,i)+this._text.slice(i+1),this._cursorOffset--}return;case 13:return void(this._host.focusedControl=null);case 35:return this._cursorOffset=0,this._blinkIsEven=!1,void this._markAsDirty();case 36:return this._cursorOffset=this._text.length,this._blinkIsEven=!1,void this._markAsDirty();case 37:return this._cursorOffset++,this._cursorOffset>this._text.length&&(this._cursorOffset=this._text.length),this._blinkIsEven=!1,void this._markAsDirty();case 39:return this._cursorOffset--,this._cursorOffset<0&&(this._cursorOffset=0),this._blinkIsEven=!1,void this._markAsDirty();case 222:return void(this.deadKey=!0)}if(e&&(-1===t||32===t||t>47&&t<58||t>64&&t<91||t>185&&t<193||t>218&&t<223||t>95&&t<112)&&(this._currentKey=e,this.onBeforeKeyAddObservable.notifyObservers(this),e=this._currentKey,this._addKey))if(0===this._cursorOffset)this.text+=e;else{var r=this._text.length-this._cursorOffset;this.text=this._text.slice(0,r)+e+this._text.slice(r)}},e.prototype.processKeyboard=function(t){this.processKey(t.keyCode,t.key)},e.prototype._draw=function(t,e){var i=this;if(e.save(),this._applyStates(e),this._processMeasures(t,e)){(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._focusedBackground,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._background,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._fontOffset||(this._fontOffset=n.Control._GetFontOffset(e.font));var r=this._currentMeasure.left+this._margin.getValueInPixel(this._host,t.width);this.color&&(e.fillStyle=this.color);var o=this._beforeRenderText(this._text);this._isFocused||this._text||!this._placeholderText||(o=this._placeholderText,this._placeholderColor&&(e.fillStyle=this._placeholderColor)),this._textWidth=e.measureText(o).width;var s=2*this._margin.getValueInPixel(this._host,t.width);this._autoStretchWidth&&(this.width=Math.min(this._maxWidth.getValueInPixel(this._host,t.width),this._textWidth+s)+"px");var a=this._fontOffset.ascent+(this._currentMeasure.height-this._fontOffset.height)/2,h=this._width.getValueInPixel(this._host,t.width)-s;if(e.save(),e.beginPath(),e.rect(r,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,h+2,this._currentMeasure.height),e.clip(),this._isFocused&&this._textWidth>h){var l=r-this._textWidth+h;this._scrollLeft||(this._scrollLeft=l)}else this._scrollLeft=r;if(e.fillText(o,this._scrollLeft,this._currentMeasure.top+a),this._isFocused){if(this._clickedCoordinate){var u=this._scrollLeft+this._textWidth-this._clickedCoordinate,c=0;this._cursorOffset=0;var _=0;do{this._cursorOffset&&(_=Math.abs(u-c)),this._cursorOffset++,c=e.measureText(o.substr(o.length-this._cursorOffset,this._cursorOffset)).width}while(c=this._cursorOffset);Math.abs(u-c)>_&&this._cursorOffset--,this._blinkIsEven=!1,this._clickedCoordinate=null}if(!this._blinkIsEven){var f=this.text.substr(this._text.length-this._cursorOffset),p=e.measureText(f).width,d=this._scrollLeft+this._textWidth-p;dr+h&&(this._scrollLeft+=r+h-d,d=r+h,this._markAsDirty()),e.fillRect(d,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,2,this._fontOffset.height)}clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout(function(){i._blinkIsEven=!i._blinkIsEven,i._markAsDirty()},500)}e.restore(),this._thickness&&(this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness))}e.restore()},e.prototype._onPointerDown=function(e,i,r,n){return!!t.prototype._onPointerDown.call(this,e,i,r,n)&&(this._clickedCoordinate=i.x,this._host.focusedControl===this?(clearTimeout(this._blinkTimeout),this._markAsDirty(),!0):(this._host.focusedControl=this,!0))},e.prototype._onPointerUp=function(e,i,r,n,o){t.prototype._onPointerUp.call(this,e,i,r,n,o)},e.prototype._beforeRenderText=function(t){return t},e.prototype.dispose=function(){t.prototype.dispose.call(this),this.onBlurObservable.clear(),this.onFocusObservable.clear(),this.onTextChangedObservable.clear()},e}(n.Control);e.InputText=a},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(0),o=function(t){function e(e,i){void 0===i&&(i=0);var r=t.call(this,e.x,e.y)||this;return r.buttonIndex=i,r}return r(e,t),e}(n.Vector2);e.Vector2WithInfo=o;var s=function(){function t(t,e,i,r,n,o){this.m=new Float32Array(6),this.fromValues(t,e,i,r,n,o)}return t.prototype.fromValues=function(t,e,i,r,n,o){return this.m[0]=t,this.m[1]=e,this.m[2]=i,this.m[3]=r,this.m[4]=n,this.m[5]=o,this},t.prototype.determinant=function(){return this.m[0]*this.m[3]-this.m[1]*this.m[2]},t.prototype.invertToRef=function(t){var e=this.m[0],i=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],a=this.m[5],h=this.determinant();if(h0?this.margin:0}}},e}(n.Container3D);e.StackPanel3D=s},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(5),o=i(0),s=i(3),a=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._radius=5,e}return r(e,t),Object.defineProperty(e.prototype,"radius",{get:function(){return this._radius},set:function(t){var e=this;this._radius!==t&&(this._radius=t,o.Tools.SetImmediate(function(){e._arrangeChildren()}))},enumerable:!0,configurable:!0}),e.prototype._mapGridNode=function(t,e){var i=t.mesh;if(i){var r=this._sphericalMapping(e);switch(t.position=r,this.orientation){case s.Container3D.FACEORIGIN_ORIENTATION:i.lookAt(new BABYLON.Vector3(-r.x,-r.y,-r.z));break;case s.Container3D.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new BABYLON.Vector3(2*r.x,2*r.y,2*r.z));break;case s.Container3D.FACEFORWARD_ORIENTATION:break;case s.Container3D.FACEFORWARDREVERSED_ORIENTATION:i.rotate(BABYLON.Axis.Y,Math.PI,BABYLON.Space.LOCAL)}}},e.prototype._sphericalMapping=function(t){var e=new o.Vector3(0,0,this._radius),i=t.y/this._radius,r=-t.x/this._radius;return o.Matrix.RotationYawPitchRollToRef(r,i,0,o.Tmp.Matrix[0]),o.Vector3.TransformNormal(e,o.Tmp.Matrix[0])},e}(n.VolumeBasedPanel);e.SpherePanel=a},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(5),o=i(0),s=i(3),a=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._iteration=100,e}return r(e,t),Object.defineProperty(e.prototype,"iteration",{get:function(){return this._iteration},set:function(t){var e=this;this._iteration!==t&&(this._iteration=t,o.Tools.SetImmediate(function(){e._arrangeChildren()}))},enumerable:!0,configurable:!0}),e.prototype._mapGridNode=function(t,e){var i=t.mesh,r=this._scatterMapping(e);if(i){switch(this.orientation){case s.Container3D.FACEORIGIN_ORIENTATION:case s.Container3D.FACEFORWARD_ORIENTATION:i.lookAt(new o.Vector3(0,0,-1));break;case s.Container3D.FACEFORWARDREVERSED_ORIENTATION:case s.Container3D.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new o.Vector3(0,0,1))}t.position=r}},e.prototype._scatterMapping=function(t){return t.x=(1-2*Math.random())*this._cellWidth,t.y=(1-2*Math.random())*this._cellHeight,t},e.prototype._finalProcessing=function(){for(var t=[],e=0,i=this._children;er?-1:0});for(var s=Math.pow(this.margin,2),a=Math.max(this._cellWidth,this._cellHeight),h=o.Tmp.Vector2[0],l=o.Tmp.Vector3[0],u=0;uareaXZ && areaYZ>areaXY)\n{\nscaledBorderWidth*=minOverMiddleScale;\n}\n}\nelse if (abs(normal.y) == 1.0) \n{\nscale.x=scale.z;\nif (areaXZ>areaXY && areaXZ>areaYZ)\n{\nscaledBorderWidth*=minOverMiddleScale;\n}\n}\nelse \n{\nif (areaXY>areaYZ && areaXY>areaXZ)\n{\nscaledBorderWidth*=minOverMiddleScale;\n}\n}\nfloat scaleRatio=min(scale.x,scale.y)/max(scale.x,scale.y);\nif (scale.x>scale.y)\n{\nscaleInfo.x=1.0-(scaledBorderWidth*scaleRatio);\nscaleInfo.y=1.0-scaledBorderWidth;\n}\nelse\n{\nscaleInfo.x=1.0-scaledBorderWidth;\nscaleInfo.y=1.0-(scaledBorderWidth*scaleRatio);\n} \n#endif \nvec4 worldPos=world*vec4(position,1.0);\n#ifdef HOVERLIGHT\nworldPosition=worldPos.xyz;\n#endif\ngl_Position=viewProjection*worldPos;\n}\n"},function(t,e){t.exports="precision highp float;\nvarying vec2 vUV;\nuniform vec4 albedoColor;\n#ifdef INNERGLOW\nuniform vec4 innerGlowColor;\n#endif\n#ifdef BORDER\nvarying vec2 scaleInfo;\nuniform float edgeSmoothingValue;\nuniform float borderMinValue;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;\nuniform vec3 hoverPosition;\nuniform vec4 hoverColor;\nuniform float hoverRadius;\n#endif\nvoid main(void) {\nvec3 albedo=albedoColor.rgb;\nfloat alpha=albedoColor.a;\n#ifdef HOVERLIGHT\nfloat pointToHover=(1.0-clamp(length(hoverPosition-worldPosition)/hoverRadius,0.,1.))*hoverColor.a;\nalbedo=clamp(albedo+hoverColor.rgb*pointToHover,0.,1.);\n#else\nfloat pointToHover=1.0;\n#endif\n#ifdef BORDER \nfloat borderPower=10.0;\nfloat inverseBorderPower=1.0/borderPower;\nvec3 borderColor=albedo*borderPower;\nvec2 distanceToEdge;\ndistanceToEdge.x=abs(vUV.x-0.5)*2.0;\ndistanceToEdge.y=abs(vUV.y-0.5)*2.0;\nfloat borderValue=max(smoothstep(scaleInfo.x-edgeSmoothingValue,scaleInfo.x+edgeSmoothingValue,distanceToEdge.x),\nsmoothstep(scaleInfo.y-edgeSmoothingValue,scaleInfo.y+edgeSmoothingValue,distanceToEdge.y));\nborderColor=borderColor*borderValue*max(borderMinValue*inverseBorderPower,pointToHover); \nalbedo+=borderColor;\nalpha=max(alpha,borderValue);\n#endif\n#ifdef INNERGLOW\n\nvec2 uvGlow=(vUV-vec2(0.5,0.5))*(innerGlowColor.a*2.0);\nuvGlow=uvGlow*uvGlow;\nuvGlow=uvGlow*uvGlow;\nalbedo+=mix(vec3(0.0,0.0,0.0),innerGlowColor.rgb,uvGlow.x+uvGlow.y); \n#endif\ngl_FragColor=vec4(albedo,alpha);\n}"},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=i(0),n=i(30);e.fShader=n;var o=i(29);e.vShader=o,e.registerShader=function(){r.Effect.ShadersStore.fluentVertexShader=o,r.Effect.ShadersStore.fluentPixelShader=n}},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(9),o=i(0),s=i(12),a=i(7),h=i(11),l=i(8),u=function(t){function e(e,i){void 0===i&&(i=!0);var r=t.call(this,e)||this;return r._shareMaterials=!0,r._shareMaterials=i,r.pointerEnterAnimation=function(){r.mesh&&r._frontPlate.setEnabled(!0)},r.pointerOutAnimation=function(){r.mesh&&r._frontPlate.setEnabled(!1)},r}return r(e,t),Object.defineProperty(e.prototype,"text",{get:function(){return this._text},set:function(t){this._text!==t&&(this._text=t,this._rebuildContent())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"imageUrl",{get:function(){return this._imageUrl},set:function(t){this._imageUrl!==t&&(this._imageUrl=t,this._rebuildContent())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"backMaterial",{get:function(){return this._backMaterial},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"frontMaterial",{get:function(){return this._frontMaterial},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"plateMaterial",{get:function(){return this._plateMaterial},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"shareMaterials",{get:function(){return this._shareMaterials},enumerable:!0,configurable:!0}),e.prototype._getTypeName=function(){return"HolographicButton"},e.prototype._rebuildContent=function(){this._disposeFacadeTexture();var t=new a.StackPanel;if(t.isVertical=!0,this._imageUrl){var e=new h.Image;e.source=this._imageUrl,e.paddingTop="40px",e.height="180px",e.width="100px",e.paddingBottom="40px",t.addControl(e)}if(this._text){var i=new l.TextBlock;i.text=this._text,i.color="white",i.height="30px",i.fontSize=24,t.addControl(i)}this._frontPlate&&(this.content=t)},e.prototype._createNode=function(e){return this._backPlate=o.MeshBuilder.CreateBox(this.name+"BackMesh",{width:1,height:1,depth:.08},e),this._frontPlate=o.MeshBuilder.CreateBox(this.name+"FrontMesh",{width:1,height:1,depth:.08},e),this._frontPlate.parent=this._backPlate,this._frontPlate.position.z=-.08,this._frontPlate.isPickable=!1,this._frontPlate.setEnabled(!1),this._textPlate=t.prototype._createNode.call(this,e),this._textPlate.parent=this._backPlate,this._textPlate.position.z=-.08,this._textPlate.isPickable=!1,this._backPlate},e.prototype._applyFacade=function(t){this._plateMaterial.emissiveTexture=t,this._plateMaterial.opacityTexture=t},e.prototype._createBackMaterial=function(t){var e=this;this._backMaterial=new s.FluentMaterial(this.name+"Back Material",t.getScene()),this._backMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add(function(t){t?(e._backMaterial.hoverPosition=t,e._backMaterial.hoverColor.a=1):e._backMaterial.hoverColor.a=0})},e.prototype._createFrontMaterial=function(t){this._frontMaterial=new s.FluentMaterial(this.name+"Front Material",t.getScene()),this._frontMaterial.innerGlowColorIntensity=0,this._frontMaterial.alpha=.5,this._frontMaterial.renderBorders=!0},e.prototype._createPlateMaterial=function(t){this._plateMaterial=new o.StandardMaterial(this.name+"Plate Material",t.getScene()),this._plateMaterial.specularColor=o.Color3.Black()},e.prototype._affectMaterial=function(t){this._shareMaterials?(this._host._sharedMaterials.backFluentMaterial?this._backMaterial=this._host._sharedMaterials.backFluentMaterial:(this._createBackMaterial(t),this._host._sharedMaterials.backFluentMaterial=this._backMaterial),this._host._sharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._sharedMaterials.frontFluentMaterial:(this._createFrontMaterial(t),this._host._sharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(t),this._createFrontMaterial(t)),this._createPlateMaterial(t),this._backPlate.material=this._backMaterial,this._frontPlate.material=this._frontMaterial,this._textPlate.material=this._plateMaterial,this._rebuildContent()},e.prototype.dispose=function(){t.prototype.dispose.call(this),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))},e}(n.Button3D);e.HolographicButton=u},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(5),o=i(0),s=i(3),a=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._radius=5,e}return r(e,t),Object.defineProperty(e.prototype,"radius",{get:function(){return this._radius},set:function(t){var e=this;this._radius!==t&&(this._radius=t,o.Tools.SetImmediate(function(){e._arrangeChildren()}))},enumerable:!0,configurable:!0}),e.prototype._mapGridNode=function(t,e){var i=t.mesh;if(i){var r=this._cylindricalMapping(e);switch(t.position=r,this.orientation){case s.Container3D.FACEORIGIN_ORIENTATION:i.lookAt(new BABYLON.Vector3(-r.x,r.y,-r.z));break;case s.Container3D.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new BABYLON.Vector3(2*r.x,r.y,2*r.z));break;case s.Container3D.FACEFORWARD_ORIENTATION:break;case s.Container3D.FACEFORWARDREVERSED_ORIENTATION:i.rotate(BABYLON.Axis.Y,Math.PI,BABYLON.Space.LOCAL)}}},e.prototype._cylindricalMapping=function(t){var e=new o.Vector3(0,t.y,this._radius),i=t.x/this._radius;return o.Matrix.RotationYawPitchRollToRef(i,0,0,o.Tmp.Matrix[0]),o.Vector3.TransformNormal(e,o.Tmp.Matrix[0])},e}(n.VolumeBasedPanel);e.CylinderPanel=a},function(t,e,i){"use strict";function r(t){for(var i in t)e.hasOwnProperty(i)||(e[i]=t[i])}Object.defineProperty(e,"__esModule",{value:!0}),r(i(14)),r(i(9)),r(i(3)),r(i(10)),r(i(33)),r(i(32)),r(i(28)),r(i(27)),r(i(26)),r(i(25)),r(i(24)),r(i(5))},function(t,e,i){"use strict";function r(t){for(var i in t)e.hasOwnProperty(i)||(e[i]=t[i])}Object.defineProperty(e,"__esModule",{value:!0}),r(i(34)),r(i(23)),r(i(22)),r(i(13))},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=i(1),n=i(7),o=i(8);e.name="Statics",r.Control.AddHeader=function(t,e,i,s){var a=new n.StackPanel("panel"),h=!s||s.isHorizontal,l=!s||s.controlFirst;a.isVertical=!h;var u=new o.TextBlock("header");return u.text=e,u.textHorizontalAlignment=r.Control.HORIZONTAL_ALIGNMENT_LEFT,h?u.width=i:u.height=i,l?(a.addControl(t),a.addControl(u),u.paddingLeft="5px"):(a.addControl(u),a.addControl(t),u.paddingRight="5px"),u.shadowBlur=t.shadowBlur,u.shadowColor=t.shadowColor,u.shadowOffsetX=t.shadowOffsetX,u.shadowOffsetY=t.shadowOffsetY,a}},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),o=i(2),s=i(0),a=function(t){function e(e){var i=t.call(this,e)||this;return i.name=e,i._thumbWidth=new o.ValueAndUnit(20,o.ValueAndUnit.UNITMODE_PIXEL,!1),i._minimum=0,i._maximum=100,i._value=50,i._isVertical=!1,i._background="black",i._borderColor="white",i._barOffset=new o.ValueAndUnit(5,o.ValueAndUnit.UNITMODE_PIXEL,!1),i._isThumbCircle=!1,i._isThumbClamped=!1,i.onValueChangedObservable=new s.Observable,i._pointerIsDown=!1,i.isPointerBlocker=!0,i}return r(e,t),Object.defineProperty(e.prototype,"borderColor",{get:function(){return this._borderColor},set:function(t){this._borderColor!==t&&(this._borderColor=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"background",{get:function(){return this._background},set:function(t){this._background!==t&&(this._background=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"barOffset",{get:function(){return this._barOffset.toString(this._host)},set:function(t){this._barOffset.toString(this._host)!==t&&this._barOffset.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"barOffsetInPixels",{get:function(){return this._barOffset.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"thumbWidth",{get:function(){return this._thumbWidth.toString(this._host)},set:function(t){this._thumbWidth.toString(this._host)!==t&&this._thumbWidth.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"thumbWidthInPixels",{get:function(){return this._thumbWidth.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"minimum",{get:function(){return this._minimum},set:function(t){this._minimum!==t&&(this._minimum=t,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maximum",{get:function(){return this._maximum},set:function(t){this._maximum!==t&&(this._maximum=t,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this._value},set:function(t){t=Math.max(Math.min(t,this._maximum),this._minimum),this._value!==t&&(this._value=t,this._markAsDirty(),this.onValueChangedObservable.notifyObservers(this._value))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isVertical",{get:function(){return this._isVertical},set:function(t){this._isVertical!==t&&(this._isVertical=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isThumbCircle",{get:function(){return this._isThumbCircle},set:function(t){this._isThumbCircle!==t&&(this._isThumbCircle=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isThumbClamped",{get:function(){return this._isThumbClamped},set:function(t){this._isThumbClamped!==t&&(this._isThumbClamped=t,this._markAsDirty())},enumerable:!0,configurable:!0}),e.prototype._getTypeName=function(){return"Slider"},e.prototype._getThumbThickness=function(t,e){var i=0;switch(t){case"circle":i=this._thumbWidth.isPixel?Math.max(this._thumbWidth.getValue(this._host),e):e*this._thumbWidth.getValue(this._host);break;case"rectangle":i=this._thumbWidth.isPixel?Math.min(this._thumbWidth.getValue(this._host),e):e*this._thumbWidth.getValue(this._host)}return i},e.prototype._draw=function(t,e){if(e.save(),this._applyStates(e),this._processMeasures(t,e)){var i=0,r=this.isThumbCircle?"circle":"rectangle",n=this._currentMeasure.left,o=this._currentMeasure.top,s=this._currentMeasure.width,a=this._currentMeasure.height,h=Math.max(this._currentMeasure.width,this._currentMeasure.height),l=Math.min(this._currentMeasure.width,this._currentMeasure.height),u=this._getThumbThickness(r,l);h-=u;var c=0;if(this._isVertical&&this._currentMeasure.height1?this.selectedShiftThickness:0),s.text=t>0?s.text.toUpperCase():s.text.toLowerCase()}}}},Object.defineProperty(e.prototype,"connectedInputText",{get:function(){return this._connectedInputText},enumerable:!0,configurable:!0}),e.prototype.connect=function(t){var e=this;this.isVisible=!1,this._connectedInputText=t,this._onFocusObserver=t.onFocusObservable.add(function(){e.isVisible=!0}),this._onBlurObserver=t.onBlurObservable.add(function(){e.isVisible=!1}),this._onKeyPressObserver=this.onKeyPressObservable.add(function(t){if(e._connectedInputText){switch(t){case"⇧":return e.shiftState++,e.shiftState>2&&(e.shiftState=0),void e.applyShiftState(e.shiftState);case"←":return void e._connectedInputText.processKey(8);case"↵":return void e._connectedInputText.processKey(13)}e._connectedInputText.processKey(-1,e.shiftState?t.toUpperCase():t),1===e.shiftState&&(e.shiftState=0,e.applyShiftState(e.shiftState))}})},e.prototype.disconnect=function(){this._connectedInputText&&(this._connectedInputText.onFocusObservable.remove(this._onFocusObserver),this._connectedInputText.onBlurObservable.remove(this._onBlurObserver),this.onKeyPressObservable.remove(this._onKeyPressObserver),this._connectedInputText=null)},e.CreateDefaultLayout=function(){var t=new e;return t.addKeysRow(["1","2","3","4","5","6","7","8","9","0","←"]),t.addKeysRow(["q","w","e","r","t","y","u","i","o","p"]),t.addKeysRow(["a","s","d","f","g","h","j","k","l",";","'","↵"]),t.addKeysRow(["⇧","z","x","c","v","b","n","m",",",".","/"]),t.addKeysRow([" "],[{width:"200px"}]),t},e}(n.StackPanel);e.VirtualKeyboard=h},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),o=i(0),s=function(t){function e(e){var i=t.call(this,e)||this;return i.name=e,i._isChecked=!1,i._background="black",i._checkSizeRatio=.8,i._thickness=1,i.group="",i.onIsCheckedChangedObservable=new o.Observable,i.isPointerBlocker=!0,i}return r(e,t),Object.defineProperty(e.prototype,"thickness",{get:function(){return this._thickness},set:function(t){this._thickness!==t&&(this._thickness=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"checkSizeRatio",{get:function(){return this._checkSizeRatio},set:function(t){t=Math.max(Math.min(1,t),0),this._checkSizeRatio!==t&&(this._checkSizeRatio=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"background",{get:function(){return this._background},set:function(t){this._background!==t&&(this._background=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isChecked",{get:function(){return this._isChecked},set:function(t){var e=this;this._isChecked!==t&&(this._isChecked=t,this._markAsDirty(),this.onIsCheckedChangedObservable.notifyObservers(t),this._isChecked&&this._host&&this._host.executeOnAllControls(function(t){if(t!==e&&void 0!==t.group){var i=t;i.group===e.group&&(i.isChecked=!1)}}))},enumerable:!0,configurable:!0}),e.prototype._getTypeName=function(){return"RadioButton"},e.prototype._draw=function(t,e){if(e.save(),this._applyStates(e),this._processMeasures(t,e)){var i=this._currentMeasure.width-this._thickness,r=this._currentMeasure.height-this._thickness;if((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),n.Control.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,e),e.fillStyle=this._background,e.fill(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),e.strokeStyle=this.color,e.lineWidth=this._thickness,e.stroke(),this._isChecked){e.fillStyle=this.color;var o=i*this._checkSizeRatio,s=r*this._checkSizeRatio;n.Control.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,o/2-this._thickness/2,s/2-this._thickness/2,e),e.fill()}}e.restore()},e.prototype._onPointerDown=function(e,i,r,n){return!!t.prototype._onPointerDown.call(this,e,i,r,n)&&(this.isChecked||(this.isChecked=!0),!0)},e}(n.Control);e.RadioButton=s},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),o=i(17),s=i(0),a=function(t){function e(e){var i=t.call(this,e)||this;return i.name=e,i._lineWidth=1,i.onPointUpdate=function(){i._markAsDirty()},i.isHitTestVisible=!1,i._horizontalAlignment=n.Control.HORIZONTAL_ALIGNMENT_LEFT,i._verticalAlignment=n.Control.VERTICAL_ALIGNMENT_TOP,i._dash=[],i._points=[],i}return r(e,t),Object.defineProperty(e.prototype,"dash",{get:function(){return this._dash},set:function(t){this._dash!==t&&(this._dash=t,this._markAsDirty())},enumerable:!0,configurable:!0}),e.prototype.getAt=function(t){return this._points[t]||(this._points[t]=new o.MultiLinePoint(this)),this._points[t]},e.prototype.add=function(){for(var t=this,e=[],i=0;ii._maxX)&&(i._maxX=t._point.x),(null==i._maxY||t._point.y>i._maxY)&&(i._maxY=t._point.y))}),null==this._minX&&(this._minX=0),null==this._minY&&(this._minY=0),null==this._maxX&&(this._maxX=0),null==this._maxY&&(this._maxY=0)},e.prototype._measure=function(){null!=this._minX&&null!=this._maxX&&null!=this._minY&&null!=this._maxY&&(this._currentMeasure.width=Math.abs(this._maxX-this._minX)+this._lineWidth,this._currentMeasure.height=Math.abs(this._maxY-this._minY)+this._lineWidth)},e.prototype._computeAlignment=function(t,e){null!=this._minX&&null!=this._minY&&(this._currentMeasure.left=this._minX-this._lineWidth/2,this._currentMeasure.top=this._minY-this._lineWidth/2)},e.prototype.dispose=function(){for(;this._points.length>0;)this.remove(this._points.length-1);t.prototype.dispose.call(this)},e}(n.Control);e.MultiLine=a},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),o=i(2),s=i(0),a=function(t){function e(e){var i=t.call(this,e)||this;return i.name=e,i._lineWidth=1,i._x1=new o.ValueAndUnit(0),i._y1=new o.ValueAndUnit(0),i._x2=new o.ValueAndUnit(0),i._y2=new o.ValueAndUnit(0),i._dash=new Array,i.isHitTestVisible=!1,i._horizontalAlignment=n.Control.HORIZONTAL_ALIGNMENT_LEFT,i._verticalAlignment=n.Control.VERTICAL_ALIGNMENT_TOP,i}return r(e,t),Object.defineProperty(e.prototype,"dash",{get:function(){return this._dash},set:function(t){this._dash!==t&&(this._dash=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"connectedControl",{get:function(){return this._connectedControl},set:function(t){var e=this;this._connectedControl!==t&&(this._connectedControlDirtyObserver&&this._connectedControl&&(this._connectedControl.onDirtyObservable.remove(this._connectedControlDirtyObserver),this._connectedControlDirtyObserver=null),t&&(this._connectedControlDirtyObserver=t.onDirtyObservable.add(function(){return e._markAsDirty()})),this._connectedControl=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"x1",{get:function(){return this._x1.toString(this._host)},set:function(t){this._x1.toString(this._host)!==t&&this._x1.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"y1",{get:function(){return this._y1.toString(this._host)},set:function(t){this._y1.toString(this._host)!==t&&this._y1.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"x2",{get:function(){return this._x2.toString(this._host)},set:function(t){this._x2.toString(this._host)!==t&&this._x2.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"y2",{get:function(){return this._y2.toString(this._host)},set:function(t){this._y2.toString(this._host)!==t&&this._y2.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lineWidth",{get:function(){return this._lineWidth},set:function(t){this._lineWidth!==t&&(this._lineWidth=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"horizontalAlignment",{set:function(t){},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"verticalAlignment",{set:function(t){},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_effectiveX2",{get:function(){return(this._connectedControl?this._connectedControl.centerX:0)+this._x2.getValue(this._host)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_effectiveY2",{get:function(){return(this._connectedControl?this._connectedControl.centerY:0)+this._y2.getValue(this._host)},enumerable:!0,configurable:!0}),e.prototype._getTypeName=function(){return"Line"},e.prototype._draw=function(t,e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),this._processMeasures(t,e)&&(e.strokeStyle=this.color,e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath(),e.moveTo(this._x1.getValue(this._host),this._y1.getValue(this._host)),e.lineTo(this._effectiveX2,this._effectiveY2),e.stroke()),e.restore()},e.prototype._measure=function(){this._currentMeasure.width=Math.abs(this._x1.getValue(this._host)-this._effectiveX2)+this._lineWidth,this._currentMeasure.height=Math.abs(this._y1.getValue(this._host)-this._effectiveY2)+this._lineWidth},e.prototype._computeAlignment=function(t,e){this._currentMeasure.left=Math.min(this._x1.getValue(this._host),this._effectiveX2)-this._lineWidth/2,this._currentMeasure.top=Math.min(this._y1.getValue(this._host),this._effectiveY2)-this._lineWidth/2},e.prototype.moveToVector3=function(t,e,i){if(void 0===i&&(i=!1),this._host&&this._root===this._host._rootContainer){var r=this._host._getGlobalViewport(e),n=s.Vector3.Project(t,s.Matrix.Identity(),e.getTransformMatrix(),r);this._moveToProjectedPosition(n,i),n.z<0||n.z>1?this.notRenderable=!0:this.notRenderable=!1}else s.Tools.Error("Cannot move a control to a vector3 if the control is not at root level")},e.prototype._moveToProjectedPosition=function(t,e){void 0===e&&(e=!1);var i=t.x+this._linkOffsetX.getValue(this._host)+"px",r=t.y+this._linkOffsetY.getValue(this._host)+"px";e?(this.x2=i,this.y2=r,this._x2.ignoreAdaptiveScaling=!0,this._y2.ignoreAdaptiveScaling=!0):(this.x1=i,this.y1=r,this._x1.ignoreAdaptiveScaling=!0,this._y1.ignoreAdaptiveScaling=!0)},e}(n.Control);e.Line=a},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r(e,t),e.prototype._beforeRenderText=function(t){for(var e="",i=0;i=this._rowDefinitions.length?this:(this._rowDefinitions[t]=new o.ValueAndUnit(e,i?o.ValueAndUnit.UNITMODE_PIXEL:o.ValueAndUnit.UNITMODE_PERCENTAGE),this._markAsDirty(),this)},e.prototype.setColumnDefinition=function(t,e,i){return void 0===i&&(i=!1),t<0||t>=this._columnDefinitions.length?this:(this._columnDefinitions[t]=new o.ValueAndUnit(e,i?o.ValueAndUnit.UNITMODE_PIXEL:o.ValueAndUnit.UNITMODE_PERCENTAGE),this._markAsDirty(),this)},e.prototype._removeCell=function(e,i){if(e){t.prototype.removeControl.call(this,e);for(var r=0,n=e.children;r=this._columnDefinitions.length)return this;for(var e=0;e=this._rowDefinitions.length)return this;for(var e=0;ea||_150?.04:-.16*(t-50)/100+.2;var g=(f-h)/(t-h);o[d+3]=g1-y?255*(1-(g-(1-y))/y):255}}return r.putImageData(n,0,0),i},e.prototype._RGBtoHSV=function(t,e){var i=t.r,r=t.g,n=t.b,o=Math.max(i,r,n),s=Math.min(i,r,n),a=0,h=0,l=o,u=o-s;0!==o&&(h=u/o),o!=s&&(o==i?(a=(r-n)/u,r=0&&o<=1?(a=n,h=s):o>=1&&o<=2?(a=s,h=n):o>=2&&o<=3?(h=n,l=s):o>=3&&o<=4?(h=s,l=n):o>=4&&o<=5?(a=s,l=n):o>=5&&o<=6&&(a=n,l=s);var u=i-n;r.set(a+u,h+u,l+u)},e.prototype._draw=function(t,e){if(e.save(),this._applyStates(e),this._processMeasures(t,e)){var i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),r=.2*i,n=this._currentMeasure.left,o=this._currentMeasure.top;this._colorWheelCanvas&&this._colorWheelCanvas.width==2*i||(this._colorWheelCanvas=this._createColorWheelCanvas(i,r)),this._updateSquareProps(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY,e.fillRect(this._squareLeft,this._squareTop,this._squareSize,this._squareSize)),e.drawImage(this._colorWheelCanvas,n,o),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._drawGradientSquare(this._h,this._squareLeft,this._squareTop,this._squareSize,this._squareSize,e);var s=this._squareLeft+this._squareSize*this._s,a=this._squareTop+this._squareSize*(1-this._v);this._drawCircle(s,a,.04*i,e);var h=i-.5*r;s=n+i+Math.cos((this._h-180)*Math.PI/180)*h,a=o+i+Math.sin((this._h-180)*Math.PI/180)*h,this._drawCircle(s,a,.35*r,e)}e.restore()},e.prototype._updateValueFromPointer=function(t,e){if(this._pointerStartedOnWheel){var i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),r=i+this._currentMeasure.left,n=i+this._currentMeasure.top;this._h=180*Math.atan2(e-n,t-r)/Math.PI+180}else this._pointerStartedOnSquare&&(this._updateSquareProps(),this._s=(t-this._squareLeft)/this._squareSize,this._v=1-(e-this._squareTop)/this._squareSize,this._s=Math.min(this._s,1),this._s=Math.max(this._s,1e-5),this._v=Math.min(this._v,1),this._v=Math.max(this._v,1e-5));this._HSVtoRGB(this._h,this._s,this._v,this._tmpColor),this.value=this._tmpColor},e.prototype._isPointOnSquare=function(t){this._updateSquareProps();var e=this._squareLeft,i=this._squareTop,r=this._squareSize;return t.x>=e&&t.x<=e+r&&t.y>=i&&t.y<=i+r},e.prototype._isPointOnWheel=function(t){var e=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),i=e+this._currentMeasure.left,r=e+this._currentMeasure.top,n=e-.2*e,o=e*e,s=n*n,a=t.x-i,h=t.y-r,l=a*a+h*h;return l<=o&&l>=s},e.prototype._onPointerDown=function(e,i,r,n){return!!t.prototype._onPointerDown.call(this,e,i,r,n)&&(this._pointerIsDown=!0,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._isPointOnSquare(i)?this._pointerStartedOnSquare=!0:this._isPointOnWheel(i)&&(this._pointerStartedOnWheel=!0),this._updateValueFromPointer(i.x,i.y),this._host._capturingControl[r]=this,!0)},e.prototype._onPointerMove=function(e,i){this._pointerIsDown&&this._updateValueFromPointer(i.x,i.y),t.prototype._onPointerMove.call(this,e,i)},e.prototype._onPointerUp=function(e,i,r,n,o){this._pointerIsDown=!1,delete this._host._capturingControl[r],t.prototype._onPointerUp.call(this,e,i,r,n,o)},e}(n.Control);e.ColorPicker=s},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),o=i(0),s=function(t){function e(e){var i=t.call(this,e)||this;return i.name=e,i._isChecked=!1,i._background="black",i._checkSizeRatio=.8,i._thickness=1,i.onIsCheckedChangedObservable=new o.Observable,i.isPointerBlocker=!0,i}return r(e,t),Object.defineProperty(e.prototype,"thickness",{get:function(){return this._thickness},set:function(t){this._thickness!==t&&(this._thickness=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"checkSizeRatio",{get:function(){return this._checkSizeRatio},set:function(t){t=Math.max(Math.min(1,t),0),this._checkSizeRatio!==t&&(this._checkSizeRatio=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"background",{get:function(){return this._background},set:function(t){this._background!==t&&(this._background=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isChecked",{get:function(){return this._isChecked},set:function(t){this._isChecked!==t&&(this._isChecked=t,this._markAsDirty(),this.onIsCheckedChangedObservable.notifyObservers(t))},enumerable:!0,configurable:!0}),e.prototype._getTypeName=function(){return"CheckBox"},e.prototype._draw=function(t,e){if(e.save(),this._applyStates(e),this._processMeasures(t,e)){var i=this._currentMeasure.width-this._thickness,r=this._currentMeasure.height-this._thickness;if((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),e.fillStyle=this._background,e.fillRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,i,r),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._isChecked){e.fillStyle=this.color;var n=i*this._checkSizeRatio,o=r*this._checkSizeRatio;e.fillRect(this._currentMeasure.left+this._thickness/2+(i-n)/2,this._currentMeasure.top+this._thickness/2+(r-o)/2,n,o)}e.strokeStyle=this.color,e.lineWidth=this._thickness,e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,i,r)}e.restore()},e.prototype._onPointerDown=function(e,i,r,n){return!!t.prototype._onPointerDown.call(this,e,i,r,n)&&(this.isChecked=!this.isChecked,!0)},e}(n.Control);e.Checkbox=s},function(t,e,i){"use strict";function r(t){for(var i in t)e.hasOwnProperty(i)||(e[i]=t[i])}Object.defineProperty(e,"__esModule",{value:!0}),r(i(21)),r(i(46)),r(i(45)),r(i(4)),r(i(1)),r(i(44)),r(i(43)),r(i(11)),r(i(18)),r(i(42)),r(i(41)),r(i(40)),r(i(39)),r(i(7)),r(i(8)),r(i(38)),r(i(37)),r(i(20)),r(i(36))},function(t,e,i){"use strict";function r(t){for(var i in t)e.hasOwnProperty(i)||(e[i]=t[i])}Object.defineProperty(e,"__esModule",{value:!0}),r(i(47)),r(i(16)),r(i(19)),r(i(6)),r(i(17)),r(i(15)),r(i(2))},function(t,e,i){"use strict";function r(t){for(var i in t)e.hasOwnProperty(i)||(e[i]=t[i])}Object.defineProperty(e,"__esModule",{value:!0}),r(i(48)),r(i(35))}])}); +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("babylonjs")):"function"==typeof define&&define.amd?define("babylonjs-gui",["babylonjs"],e):"object"==typeof exports?exports["babylonjs-gui"]=e(require("babylonjs")):(t.BABYLON=t.BABYLON||{},t.BABYLON.GUI=e(t.BABYLON))}(window,function(t){return function(t){var e={};function i(r){if(e[r])return e[r].exports;var n=e[r]={i:r,l:!1,exports:{}};return t[r].call(n.exports,n,n.exports,i),n.l=!0,n.exports}return i.m=t,i.c=e,i.d=function(t,e,r){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(i.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var n in t)i.d(r,n,function(e){return t[e]}.bind(null,n));return r},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=22)}([function(e,i){e.exports=t},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=i(2),n=i(0),o=i(5),s=i(14),a=function(){function t(e){this.name=e,this._alpha=1,this._alphaSet=!1,this._zIndex=0,this._currentMeasure=o.Measure.Empty(),this._fontFamily="Arial",this._fontStyle="",this._fontWeight="",this._fontSize=new r.ValueAndUnit(18,r.ValueAndUnit.UNITMODE_PIXEL,!1),this._width=new r.ValueAndUnit(1,r.ValueAndUnit.UNITMODE_PERCENTAGE,!1),this._height=new r.ValueAndUnit(1,r.ValueAndUnit.UNITMODE_PERCENTAGE,!1),this._color="",this._style=null,this._horizontalAlignment=t.HORIZONTAL_ALIGNMENT_CENTER,this._verticalAlignment=t.VERTICAL_ALIGNMENT_CENTER,this._isDirty=!0,this._tempParentMeasure=o.Measure.Empty(),this._cachedParentMeasure=o.Measure.Empty(),this._paddingLeft=new r.ValueAndUnit(0),this._paddingRight=new r.ValueAndUnit(0),this._paddingTop=new r.ValueAndUnit(0),this._paddingBottom=new r.ValueAndUnit(0),this._left=new r.ValueAndUnit(0),this._top=new r.ValueAndUnit(0),this._scaleX=1,this._scaleY=1,this._rotation=0,this._transformCenterX=.5,this._transformCenterY=.5,this._transformMatrix=s.Matrix2D.Identity(),this._invertTransformMatrix=s.Matrix2D.Identity(),this._transformedPosition=n.Vector2.Zero(),this._onlyMeasureMode=!1,this._isMatrixDirty=!0,this._isVisible=!0,this._fontSet=!1,this._dummyVector2=n.Vector2.Zero(),this._downCount=0,this._enterCount=-1,this._doNotRender=!1,this._downPointerIds={},this.isHitTestVisible=!0,this.isPointerBlocker=!1,this.isFocusInvisible=!1,this.shadowOffsetX=0,this.shadowOffsetY=0,this.shadowBlur=0,this.shadowColor="#000",this._linkOffsetX=new r.ValueAndUnit(0),this._linkOffsetY=new r.ValueAndUnit(0),this.onPointerMoveObservable=new n.Observable,this.onPointerOutObservable=new n.Observable,this.onPointerDownObservable=new n.Observable,this.onPointerUpObservable=new n.Observable,this.onPointerClickObservable=new n.Observable,this.onPointerEnterObservable=new n.Observable,this.onDirtyObservable=new n.Observable,this.onAfterDrawObservable=new n.Observable}return Object.defineProperty(t.prototype,"typeName",{get:function(){return this._getTypeName()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontOffset",{get:function(){return this._fontOffset},set:function(t){this._fontOffset=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"alpha",{get:function(){return this._alpha},set:function(t){this._alpha!==t&&(this._alphaSet=!0,this._alpha=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleX",{get:function(){return this._scaleX},set:function(t){this._scaleX!==t&&(this._scaleX=t,this._markAsDirty(),this._markMatrixAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleY",{get:function(){return this._scaleY},set:function(t){this._scaleY!==t&&(this._scaleY=t,this._markAsDirty(),this._markMatrixAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this._rotation},set:function(t){this._rotation!==t&&(this._rotation=t,this._markAsDirty(),this._markMatrixAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transformCenterY",{get:function(){return this._transformCenterY},set:function(t){this._transformCenterY!==t&&(this._transformCenterY=t,this._markAsDirty(),this._markMatrixAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transformCenterX",{get:function(){return this._transformCenterX},set:function(t){this._transformCenterX!==t&&(this._transformCenterX=t,this._markAsDirty(),this._markMatrixAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"horizontalAlignment",{get:function(){return this._horizontalAlignment},set:function(t){this._horizontalAlignment!==t&&(this._horizontalAlignment=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"verticalAlignment",{get:function(){return this._verticalAlignment},set:function(t){this._verticalAlignment!==t&&(this._verticalAlignment=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"width",{get:function(){return this._width.toString(this._host)},set:function(t){this._width.toString(this._host)!==t&&this._width.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"widthInPixels",{get:function(){return this._width.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"height",{get:function(){return this._height.toString(this._host)},set:function(t){this._height.toString(this._host)!==t&&this._height.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"heightInPixels",{get:function(){return this._height.getValueInPixel(this._host,this._cachedParentMeasure.height)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontFamily",{get:function(){return this._fontFamily},set:function(t){this._fontFamily!==t&&(this._fontFamily=t,this._resetFontCache())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontStyle",{get:function(){return this._fontStyle},set:function(t){this._fontStyle!==t&&(this._fontStyle=t,this._resetFontCache())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontWeight",{get:function(){return this._fontWeight},set:function(t){this._fontWeight!==t&&(this._fontWeight=t,this._resetFontCache())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"style",{get:function(){return this._style},set:function(t){var e=this;this._style&&(this._style.onChangedObservable.remove(this._styleObserver),this._styleObserver=null),this._style=t,this._style&&(this._styleObserver=this._style.onChangedObservable.add(function(){e._markAsDirty(),e._resetFontCache()})),this._markAsDirty(),this._resetFontCache()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_isFontSizeInPercentage",{get:function(){return this._fontSize.isPercentage},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontSizeInPixels",{get:function(){var t=this._style?this._style._fontSize:this._fontSize;return t.isPixel?t.getValue(this._host):t.getValueInPixel(this._host,this._tempParentMeasure.height||this._cachedParentMeasure.height)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontSize",{get:function(){return this._fontSize.toString(this._host)},set:function(t){this._fontSize.toString(this._host)!==t&&this._fontSize.fromString(t)&&(this._markAsDirty(),this._resetFontCache())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"color",{get:function(){return this._color},set:function(t){this._color!==t&&(this._color=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"zIndex",{get:function(){return this._zIndex},set:function(t){this.zIndex!==t&&(this._zIndex=t,this._root&&this._root._reOrderControl(this))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"notRenderable",{get:function(){return this._doNotRender},set:function(t){this._doNotRender!==t&&(this._doNotRender=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isVisible",{get:function(){return this._isVisible},set:function(t){this._isVisible!==t&&(this._isVisible=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isDirty",{get:function(){return this._isDirty},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingLeft",{get:function(){return this._paddingLeft.toString(this._host)},set:function(t){this._paddingLeft.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingLeftInPixels",{get:function(){return this._paddingLeft.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingRight",{get:function(){return this._paddingRight.toString(this._host)},set:function(t){this._paddingRight.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingRightInPixels",{get:function(){return this._paddingRight.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingTop",{get:function(){return this._paddingTop.toString(this._host)},set:function(t){this._paddingTop.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingTopInPixels",{get:function(){return this._paddingTop.getValueInPixel(this._host,this._cachedParentMeasure.height)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingBottom",{get:function(){return this._paddingBottom.toString(this._host)},set:function(t){this._paddingBottom.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paddingBottomInPixels",{get:function(){return this._paddingBottom.getValueInPixel(this._host,this._cachedParentMeasure.height)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"left",{get:function(){return this._left.toString(this._host)},set:function(t){this._left.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"leftInPixels",{get:function(){return this._left.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"top",{get:function(){return this._top.toString(this._host)},set:function(t){this._top.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"topInPixels",{get:function(){return this._top.getValueInPixel(this._host,this._cachedParentMeasure.height)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"linkOffsetX",{get:function(){return this._linkOffsetX.toString(this._host)},set:function(t){this._linkOffsetX.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"linkOffsetXInPixels",{get:function(){return this._linkOffsetX.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"linkOffsetY",{get:function(){return this._linkOffsetY.toString(this._host)},set:function(t){this._linkOffsetY.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"linkOffsetYInPixels",{get:function(){return this._linkOffsetY.getValueInPixel(this._host,this._cachedParentMeasure.height)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"centerX",{get:function(){return this._currentMeasure.left+this._currentMeasure.width/2},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"centerY",{get:function(){return this._currentMeasure.top+this._currentMeasure.height/2},enumerable:!0,configurable:!0}),t.prototype._getTypeName=function(){return"Control"},t.prototype._resetFontCache=function(){this._fontSet=!0,this._markAsDirty()},t.prototype.getLocalCoordinates=function(t){var e=n.Vector2.Zero();return this.getLocalCoordinatesToRef(t,e),e},t.prototype.getLocalCoordinatesToRef=function(t,e){return e.x=t.x-this._currentMeasure.left,e.y=t.y-this._currentMeasure.top,this},t.prototype.getParentLocalCoordinates=function(t){var e=n.Vector2.Zero();return e.x=t.x-this._cachedParentMeasure.left,e.y=t.y-this._cachedParentMeasure.top,e},t.prototype.moveToVector3=function(e,i){if(this._host&&this._root===this._host._rootContainer){this.horizontalAlignment=t.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=t.VERTICAL_ALIGNMENT_TOP;var r=this._host._getGlobalViewport(i),o=n.Vector3.Project(e,n.Matrix.Identity(),i.getTransformMatrix(),r);this._moveToProjectedPosition(o),o.z<0||o.z>1?this.notRenderable=!0:this.notRenderable=!1}else n.Tools.Error("Cannot move a control to a vector3 if the control is not at root level")},t.prototype.linkWithMesh=function(e){if(!this._host||this._root&&this._root!==this._host._rootContainer)e&&n.Tools.Error("Cannot link a control to a mesh if the control is not at root level");else{var i=this._host._linkedControls.indexOf(this);if(-1!==i)return this._linkedMesh=e,void(e||this._host._linkedControls.splice(i,1));e&&(this.horizontalAlignment=t.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=t.VERTICAL_ALIGNMENT_TOP,this._linkedMesh=e,this._onlyMeasureMode=0===this._currentMeasure.width||0===this._currentMeasure.height,this._host._linkedControls.push(this))}},t.prototype._moveToProjectedPosition=function(t){var e=this._left.getValue(this._host),i=this._top.getValue(this._host),r=t.x+this._linkOffsetX.getValue(this._host)-this._currentMeasure.width/2,n=t.y+this._linkOffsetY.getValue(this._host)-this._currentMeasure.height/2;this._left.ignoreAdaptiveScaling&&this._top.ignoreAdaptiveScaling&&(Math.abs(r-e)<.5&&(r=e),Math.abs(n-i)<.5&&(n=i)),this.left=r+"px",this.top=n+"px",this._left.ignoreAdaptiveScaling=!0,this._top.ignoreAdaptiveScaling=!0},t.prototype._markMatrixAsDirty=function(){this._isMatrixDirty=!0,this._markAsDirty()},t.prototype._markAsDirty=function(){this._isDirty=!0,this._host&&this._host.markAsDirty()},t.prototype._markAllAsDirty=function(){this._markAsDirty(),this._font&&this._prepareFont()},t.prototype._link=function(t,e){this._root=t,this._host=e},t.prototype._transform=function(t){if(this._isMatrixDirty||1!==this._scaleX||1!==this._scaleY||0!==this._rotation){var e=this._currentMeasure.width*this._transformCenterX+this._currentMeasure.left,i=this._currentMeasure.height*this._transformCenterY+this._currentMeasure.top;t.translate(e,i),t.rotate(this._rotation),t.scale(this._scaleX,this._scaleY),t.translate(-e,-i),(this._isMatrixDirty||this._cachedOffsetX!==e||this._cachedOffsetY!==i)&&(this._cachedOffsetX=e,this._cachedOffsetY=i,this._isMatrixDirty=!1,s.Matrix2D.ComposeToRef(-e,-i,this._rotation,this._scaleX,this._scaleY,this._root?this._root._transformMatrix:null,this._transformMatrix),this._transformMatrix.invertToRef(this._invertTransformMatrix))}},t.prototype._applyStates=function(t){this._fontSet&&(this._prepareFont(),this._fontSet=!1),this._font&&(t.font=this._font),this._color&&(t.fillStyle=this._color),this._alphaSet&&(t.globalAlpha=this._alpha)},t.prototype._processMeasures=function(t,e){return!this._isDirty&&this._cachedParentMeasure.isEqualsTo(t)||(this._isDirty=!1,this._currentMeasure.copyFrom(t),this._preMeasure(t,e),this._measure(),this._computeAlignment(t,e),this._currentMeasure.left=0|this._currentMeasure.left,this._currentMeasure.top=0|this._currentMeasure.top,this._currentMeasure.width=0|this._currentMeasure.width,this._currentMeasure.height=0|this._currentMeasure.height,this._additionalProcessing(t,e),this._cachedParentMeasure.copyFrom(t),this.onDirtyObservable.hasObservers()&&this.onDirtyObservable.notifyObservers(this)),!(this._currentMeasure.left>t.left+t.width)&&(!(this._currentMeasure.left+this._currentMeasure.widtht.top+t.height)&&(!(this._currentMeasure.top+this._currentMeasure.heightthis._currentMeasure.left+this._currentMeasure.width)&&(!(ethis._currentMeasure.top+this._currentMeasure.height)&&(this.isPointerBlocker&&(this._host._shouldBlockPointer=!0),!0))))},t.prototype._processPicking=function(t,e,i,r,n){return!(!this.isHitTestVisible||!this.isVisible||this._doNotRender)&&(!!this.contains(t,e)&&(this._processObservables(i,t,e,r,n),!0))},t.prototype._onPointerMove=function(t,e){this.onPointerMoveObservable.notifyObservers(e,-1,t,this)&&null!=this.parent&&this.parent._onPointerMove(t,e)},t.prototype._onPointerEnter=function(t){return!(this._enterCount>0)&&(-1===this._enterCount&&(this._enterCount=0),this._enterCount++,this.onPointerEnterObservable.notifyObservers(this,-1,t,this)&&null!=this.parent&&this.parent._onPointerEnter(t),!0)},t.prototype._onPointerOut=function(t){this._enterCount=0,this.onPointerOutObservable.notifyObservers(this,-1,t,this)&&null!=this.parent&&this.parent._onPointerOut(t)},t.prototype._onPointerDown=function(t,e,i,r){return 0===this._downCount&&(this._downCount++,this._downPointerIds[i]=!0,this.onPointerDownObservable.notifyObservers(new s.Vector2WithInfo(e,r),-1,t,this)&&null!=this.parent&&this.parent._onPointerDown(t,e,i,r),!0)},t.prototype._onPointerUp=function(t,e,i,r,n){this._downCount=0,delete this._downPointerIds[i];var o=n;n&&(this._enterCount>0||-1===this._enterCount)&&(o=this.onPointerClickObservable.notifyObservers(new s.Vector2WithInfo(e,r),-1,t,this)),this.onPointerUpObservable.notifyObservers(new s.Vector2WithInfo(e,r),-1,t,this)&&null!=this.parent&&this.parent._onPointerUp(t,e,i,r,o)},t.prototype._forcePointerUp=function(t){if(void 0===t&&(t=null),null!==t)this._onPointerUp(this,n.Vector2.Zero(),t,0,!0);else for(var e in this._downPointerIds)this._onPointerUp(this,n.Vector2.Zero(),+e,0,!0)},t.prototype._processObservables=function(t,e,i,r,o){if(this._dummyVector2.copyFromFloats(e,i),t===n.PointerEventTypes.POINTERMOVE){this._onPointerMove(this,this._dummyVector2);var s=this._host._lastControlOver[r];return s&&s!==this&&s._onPointerOut(this),s!==this&&this._onPointerEnter(this),this._host._lastControlOver[r]=this,!0}return t===n.PointerEventTypes.POINTERDOWN?(this._onPointerDown(this,this._dummyVector2,r,o),this._host._lastControlDown[r]=this,this._host._lastPickedControl=this,!0):t===n.PointerEventTypes.POINTERUP&&(this._host._lastControlDown[r]&&this._host._lastControlDown[r]._onPointerUp(this,this._dummyVector2,r,o,!0),delete this._host._lastControlDown[r],!0)},t.prototype._prepareFont=function(){(this._font||this._fontSet)&&(this._style?this._font=this._style.fontStyle+" "+this._style.fontWeight+" "+this.fontSizeInPixels+"px "+this._style.fontFamily:this._font=this._fontStyle+" "+this._fontWeight+" "+this.fontSizeInPixels+"px "+this._fontFamily,this._fontOffset=t._GetFontOffset(this._font))},t.prototype.dispose=function(){this.onDirtyObservable.clear(),this.onAfterDrawObservable.clear(),this.onPointerDownObservable.clear(),this.onPointerEnterObservable.clear(),this.onPointerMoveObservable.clear(),this.onPointerOutObservable.clear(),this.onPointerUpObservable.clear(),this.onPointerClickObservable.clear(),this._styleObserver&&this._style&&(this._style.onChangedObservable.remove(this._styleObserver),this._styleObserver=null),this._root&&(this._root.removeControl(this),this._root=null),this._host._linkedControls.indexOf(this)>-1&&this.linkWithMesh(null)},Object.defineProperty(t,"HORIZONTAL_ALIGNMENT_LEFT",{get:function(){return t._HORIZONTAL_ALIGNMENT_LEFT},enumerable:!0,configurable:!0}),Object.defineProperty(t,"HORIZONTAL_ALIGNMENT_RIGHT",{get:function(){return t._HORIZONTAL_ALIGNMENT_RIGHT},enumerable:!0,configurable:!0}),Object.defineProperty(t,"HORIZONTAL_ALIGNMENT_CENTER",{get:function(){return t._HORIZONTAL_ALIGNMENT_CENTER},enumerable:!0,configurable:!0}),Object.defineProperty(t,"VERTICAL_ALIGNMENT_TOP",{get:function(){return t._VERTICAL_ALIGNMENT_TOP},enumerable:!0,configurable:!0}),Object.defineProperty(t,"VERTICAL_ALIGNMENT_BOTTOM",{get:function(){return t._VERTICAL_ALIGNMENT_BOTTOM},enumerable:!0,configurable:!0}),Object.defineProperty(t,"VERTICAL_ALIGNMENT_CENTER",{get:function(){return t._VERTICAL_ALIGNMENT_CENTER},enumerable:!0,configurable:!0}),t._GetFontOffset=function(e){if(t._FontHeightSizes[e])return t._FontHeightSizes[e];var i=document.createElement("span");i.innerHTML="Hg",i.style.font=e;var r=document.createElement("div");r.style.display="inline-block",r.style.width="1px",r.style.height="0px",r.style.verticalAlign="bottom";var n=document.createElement("div");n.appendChild(i),n.appendChild(r),document.body.appendChild(n);var o=0,s=0;try{s=r.getBoundingClientRect().top-i.getBoundingClientRect().top,r.style.verticalAlign="baseline",o=r.getBoundingClientRect().top-i.getBoundingClientRect().top}finally{document.body.removeChild(n)}var a={ascent:o,height:s,descent:s-o};return t._FontHeightSizes[e]=a,a},t.drawEllipse=function(t,e,i,r,n){n.translate(t,e),n.scale(i,r),n.beginPath(),n.arc(0,0,1,0,2*Math.PI),n.closePath(),n.scale(1/i,1/r),n.translate(-t,-e)},t._HORIZONTAL_ALIGNMENT_LEFT=0,t._HORIZONTAL_ALIGNMENT_RIGHT=1,t._HORIZONTAL_ALIGNMENT_CENTER=2,t._VERTICAL_ALIGNMENT_TOP=0,t._VERTICAL_ALIGNMENT_BOTTOM=1,t._VERTICAL_ALIGNMENT_CENTER=2,t._FontHeightSizes={},t.AddHeader=function(){},t}();e.Control=a},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(e,i,r){void 0===i&&(i=t.UNITMODE_PIXEL),void 0===r&&(r=!0),this.unit=i,this.negativeValueAllowed=r,this._value=1,this.ignoreAdaptiveScaling=!1,this._value=e}return Object.defineProperty(t.prototype,"isPercentage",{get:function(){return this.unit===t.UNITMODE_PERCENTAGE},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isPixel",{get:function(){return this.unit===t.UNITMODE_PIXEL},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"internalValue",{get:function(){return this._value},enumerable:!0,configurable:!0}),t.prototype.getValueInPixel=function(t,e){return this.isPixel?this.getValue(t):this.getValue(t)*e},t.prototype.getValue=function(e){if(e&&!this.ignoreAdaptiveScaling&&this.unit!==t.UNITMODE_PERCENTAGE){var i=0,r=0;if(e.idealWidth&&(i=this._value*e.getSize().width/e.idealWidth),e.idealHeight&&(r=this._value*e.getSize().height/e.idealHeight),e.useSmallestIdeal&&e.idealWidth&&e.idealHeight)return window.innerWidtht.zIndex)return void this._children.splice(e,0,t);this._children.push(t),t.parent=this,this._markAsDirty()},e.prototype._markMatrixAsDirty=function(){t.prototype._markMatrixAsDirty.call(this);for(var e=0;e=0&&(this.width=i+"px"),this.adaptHeightToChildren&&r>=0&&(this.height=r+"px")}e.restore(),this.onAfterDrawObservable.hasObservers()&&this.onAfterDrawObservable.notifyObservers(this)}},e.prototype._processPicking=function(e,i,r,n,o){if(!this.isVisible||this.notRenderable)return!1;if(!t.prototype.contains.call(this,e,i))return!1;for(var s=this._children.length-1;s>=0;s--){if(this._children[s]._processPicking(e,i,r,n,o))return!0}return!!this.isHitTestVisible&&this._processObservables(r,e,i,n,o)},e.prototype._clipForChildren=function(t){},e.prototype._additionalProcessing=function(e,i){t.prototype._additionalProcessing.call(this,e,i),this._measureForChildren.copyFrom(this._currentMeasure)},e.prototype.dispose=function(){t.prototype.dispose.call(this);for(var e=0,i=this._children;ei));d++);else for(d=0;di));p++);f=0;for(var y=0,g=this._children;ye&&(t+="…");t.length>2&&r>e;)t=t.slice(0,-2)+"…",r=i.measureText(t).width;return{text:t,width:r}},e.prototype._parseLineWordWrap=function(t,e,i){void 0===t&&(t="");for(var r=[],n=t.split(" "),o=0,s=0;s0?t+" "+n[s]:n[0],h=i.measureText(a).width;h>e&&s>0?(r.push({text:t,width:o}),t=n[s],o=i.measureText(t).width):(o=h,t=a)}return r.push({text:t,width:o}),r},e.prototype._renderLines=function(t){var e=this._currentMeasure.height;this._fontOffset||(this._fontOffset=a.Control._GetFontOffset(t.font));var i=0;switch(this._textVerticalAlignment){case a.Control.VERTICAL_ALIGNMENT_TOP:i=this._fontOffset.ascent;break;case a.Control.VERTICAL_ALIGNMENT_BOTTOM:i=e-this._fontOffset.height*(this._lines.length-1)-this._fontOffset.descent;break;case a.Control.VERTICAL_ALIGNMENT_CENTER:i=this._fontOffset.ascent+(e-this._fontOffset.height*this._lines.length)/2}i+=this._currentMeasure.top;for(var r=0,n=0;nr&&(r=o.width)}this._resizeToFit&&(this.width=this.paddingLeftInPixels+this.paddingRightInPixels+r+"px",this.height=this.paddingTopInPixels+this.paddingBottomInPixels+this._fontOffset.height*this._lines.length+"px")},e.prototype.computeExpectedHeight=function(){if(this.text&&this.widthInPixels){var t=document.createElement("canvas").getContext("2d");if(t){this._applyStates(t),this._fontOffset||(this._fontOffset=a.Control._GetFontOffset(t.font));var e=this._lines?this._lines:this._breakLines(this.widthInPixels-this.paddingLeftInPixels-this.paddingRightInPixels,t);return this.paddingTopInPixels+this.paddingBottomInPixels+this._fontOffset.height*e.length}}return 0},e.prototype.dispose=function(){t.prototype.dispose.call(this),this.onTextChangedObservable.clear()},e}(a.Control);e.TextBlock=h},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(4),o=i(5),s=i(1),a=function(t){function e(e){var i=t.call(this,e)||this;return i.name=e,i._isVertical=!0,i._manualWidth=!1,i._manualHeight=!1,i._doNotTrackManualChanges=!1,i._tempMeasureStore=o.Measure.Empty(),i}return r(e,t),Object.defineProperty(e.prototype,"isVertical",{get:function(){return this._isVertical},set:function(t){this._isVertical!==t&&(this._isVertical=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"width",{get:function(){return this._width.toString(this._host)},set:function(t){this._doNotTrackManualChanges||(this._manualWidth=!0),this._width.toString(this._host)!==t&&this._width.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return this._height.toString(this._host)},set:function(t){this._doNotTrackManualChanges||(this._manualHeight=!0),this._height.toString(this._host)!==t&&this._height.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),e.prototype._getTypeName=function(){return"StackPanel"},e.prototype._preMeasure=function(e,i){for(var r=0,n=0,o=0,a=this._children;or&&(r=h._currentMeasure.width),h.verticalAlignment=s.Control.VERTICAL_ALIGNMENT_TOP):(h.left=r+"px",h._left.ignoreAdaptiveScaling||h._markAsDirty(),h._left.ignoreAdaptiveScaling=!0,r+=h._currentMeasure.width,h._currentMeasure.height>n&&(n=h._currentMeasure.height),h.horizontalAlignment=s.Control.HORIZONTAL_ALIGNMENT_LEFT),h._currentMeasure.copyFrom(this._tempMeasureStore)}this._doNotTrackManualChanges=!0;var l,u,c=this.height,_=this.width;this._manualHeight||(this.height=n+"px"),this._manualWidth||(this.width=r+"px"),l=_!==this.width||!this._width.ignoreAdaptiveScaling,(u=c!==this.height||!this._height.ignoreAdaptiveScaling)&&(this._height.ignoreAdaptiveScaling=!0),l&&(this._width.ignoreAdaptiveScaling=!0),this._doNotTrackManualChanges=!1,(l||u)&&this._markAllAsDirty(),t.prototype._preMeasure.call(this,e,i)},e}(n.Container);e.StackPanel=a},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),o=i(0),s=function(t){function e(i,r){void 0===r&&(r=null);var n=t.call(this,i)||this;return n.name=i,n._loaded=!1,n._stretch=e.STRETCH_FILL,n._autoScale=!1,n._sourceLeft=0,n._sourceTop=0,n._sourceWidth=0,n._sourceHeight=0,n._cellWidth=0,n._cellHeight=0,n._cellId=-1,n.source=r,n}return r(e,t),Object.defineProperty(e.prototype,"sourceLeft",{get:function(){return this._sourceLeft},set:function(t){this._sourceLeft!==t&&(this._sourceLeft=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"sourceTop",{get:function(){return this._sourceTop},set:function(t){this._sourceTop!==t&&(this._sourceTop=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"sourceWidth",{get:function(){return this._sourceWidth},set:function(t){this._sourceWidth!==t&&(this._sourceWidth=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"sourceHeight",{get:function(){return this._sourceHeight},set:function(t){this._sourceHeight!==t&&(this._sourceHeight=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"autoScale",{get:function(){return this._autoScale},set:function(t){this._autoScale!==t&&(this._autoScale=t,t&&this._loaded&&this.synchronizeSizeWithContent())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stretch",{get:function(){return this._stretch},set:function(t){this._stretch!==t&&(this._stretch=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"domImage",{get:function(){return this._domImage},set:function(t){var e=this;this._domImage=t,this._loaded=!1,this._domImage.width?this._onImageLoaded():this._domImage.onload=function(){e._onImageLoaded()}},enumerable:!0,configurable:!0}),e.prototype._onImageLoaded=function(){this._imageWidth=this._domImage.width,this._imageHeight=this._domImage.height,this._loaded=!0,this._autoScale&&this.synchronizeSizeWithContent(),this._markAsDirty()},Object.defineProperty(e.prototype,"source",{set:function(t){var e=this;this._source!==t&&(this._loaded=!1,this._source=t,this._domImage=new Image,this._domImage.onload=function(){e._onImageLoaded()},t&&(o.Tools.SetCorsBehavior(t,this._domImage),this._domImage.src=t))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cellWidth",{get:function(){return this._cellWidth},set:function(t){this._cellWidth!==t&&(this._cellWidth=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cellHeight",{get:function(){return this._cellHeight},set:function(t){this._cellHeight!==t&&(this._cellHeight=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cellId",{get:function(){return this._cellId},set:function(t){this._cellId!==t&&(this._cellId=t,this._markAsDirty())},enumerable:!0,configurable:!0}),e.prototype._getTypeName=function(){return"Image"},e.prototype.synchronizeSizeWithContent=function(){this._loaded&&(this.width=this._domImage.width+"px",this.height=this._domImage.height+"px")},e.prototype._draw=function(t,i){var r,n,o,s;if(i.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(i.shadowColor=this.shadowColor,i.shadowBlur=this.shadowBlur,i.shadowOffsetX=this.shadowOffsetX,i.shadowOffsetY=this.shadowOffsetY),-1==this.cellId)r=this._sourceLeft,n=this._sourceTop,o=this._sourceWidth?this._sourceWidth:this._imageWidth,s=this._sourceHeight?this._sourceHeight:this._imageHeight;else{var a=this._domImage.naturalWidth/this.cellWidth,h=this.cellId/a>>0,l=this.cellId%a;r=this.cellWidth*l,n=this.cellHeight*h,o=this.cellWidth,s=this.cellHeight}if(this._applyStates(i),this._processMeasures(t,i)&&this._loaded)switch(this._stretch){case e.STRETCH_NONE:case e.STRETCH_FILL:i.drawImage(this._domImage,r,n,o,s,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case e.STRETCH_UNIFORM:var u=this._currentMeasure.width/o,c=this._currentMeasure.height/s,_=Math.min(u,c),f=(this._currentMeasure.width-o*_)/2,p=(this._currentMeasure.height-s*_)/2;i.drawImage(this._domImage,r,n,o,s,this._currentMeasure.left+f,this._currentMeasure.top+p,o*_,s*_);break;case e.STRETCH_EXTEND:i.drawImage(this._domImage,r,n,o,s,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height),this._autoScale&&this.synchronizeSizeWithContent(),this._root&&this._root.parent&&(this._root.width=this.width,this._root.height=this.height)}i.restore()},Object.defineProperty(e,"STRETCH_NONE",{get:function(){return e._STRETCH_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(e,"STRETCH_FILL",{get:function(){return e._STRETCH_FILL},enumerable:!0,configurable:!0}),Object.defineProperty(e,"STRETCH_UNIFORM",{get:function(){return e._STRETCH_UNIFORM},enumerable:!0,configurable:!0}),Object.defineProperty(e,"STRETCH_EXTEND",{get:function(){return e._STRETCH_EXTEND},enumerable:!0,configurable:!0}),e._STRETCH_NONE=0,e._STRETCH_FILL=1,e._STRETCH_UNIFORM=2,e._STRETCH_EXTEND=3,e}(n.Control);e.Image=s},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=i(0),n=i(20),o=function(){function t(t){this.name=t,this._downCount=0,this._enterCount=-1,this._downPointerIds={},this._isVisible=!0,this.onPointerMoveObservable=new r.Observable,this.onPointerOutObservable=new r.Observable,this.onPointerDownObservable=new r.Observable,this.onPointerUpObservable=new r.Observable,this.onPointerClickObservable=new r.Observable,this.onPointerEnterObservable=new r.Observable,this._behaviors=new Array}return Object.defineProperty(t.prototype,"position",{get:function(){return this._node?this._node.position:r.Vector3.Zero()},set:function(t){this._node&&(this._node.position=t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this._node?this._node.scaling:new r.Vector3(1,1,1)},set:function(t){this._node&&(this._node.scaling=t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"behaviors",{get:function(){return this._behaviors},enumerable:!0,configurable:!0}),t.prototype.addBehavior=function(t){var e=this;if(-1!==this._behaviors.indexOf(t))return this;t.init();var i=this._host.scene;return i.isLoading?i.onDataLoadedObservable.addOnce(function(){t.attach(e)}):t.attach(this),this._behaviors.push(t),this},t.prototype.removeBehavior=function(t){var e=this._behaviors.indexOf(t);return-1===e?this:(this._behaviors[e].detach(),this._behaviors.splice(e,1),this)},t.prototype.getBehaviorByName=function(t){for(var e=0,i=this._behaviors;e0)&&(-1===this._enterCount&&(this._enterCount=0),this._enterCount++,this.onPointerEnterObservable.notifyObservers(this,-1,t,this),this.pointerEnterAnimation&&this.pointerEnterAnimation(),!0)},t.prototype._onPointerOut=function(t){this._enterCount=0,this.onPointerOutObservable.notifyObservers(this,-1,t,this),this.pointerOutAnimation&&this.pointerOutAnimation()},t.prototype._onPointerDown=function(t,e,i,r){return 0===this._downCount&&(this._downCount++,this._downPointerIds[i]=!0,this.onPointerDownObservable.notifyObservers(new n.Vector3WithInfo(e,r),-1,t,this),this.pointerDownAnimation&&this.pointerDownAnimation(),!0)},t.prototype._onPointerUp=function(t,e,i,r,o){this._downCount=0,delete this._downPointerIds[i],o&&(this._enterCount>0||-1===this._enterCount)&&this.onPointerClickObservable.notifyObservers(new n.Vector3WithInfo(e,r),-1,t,this),this.onPointerUpObservable.notifyObservers(new n.Vector3WithInfo(e,r),-1,t,this),this.pointerUpAnimation&&this.pointerUpAnimation()},t.prototype.forcePointerUp=function(t){if(void 0===t&&(t=null),null!==t)this._onPointerUp(this,r.Vector3.Zero(),t,0,!0);else for(var e in this._downPointerIds)this._onPointerUp(this,r.Vector3.Zero(),+e,0,!0)},t.prototype._processObservables=function(t,e,i,n){if(t===r.PointerEventTypes.POINTERMOVE){this._onPointerMove(this,e);var o=this._host._lastControlOver[i];return o&&o!==this&&o._onPointerOut(this),o!==this&&this._onPointerEnter(this),this._host._lastControlOver[i]=this,!0}return t===r.PointerEventTypes.POINTERDOWN?(this._onPointerDown(this,e,i,n),this._host._lastControlDown[i]=this,this._host._lastPickedControl=this,!0):t===r.PointerEventTypes.POINTERUP&&(this._host._lastControlDown[i]&&this._host._lastControlDown[i]._onPointerUp(this,e,i,n,!0),delete this._host._lastControlDown[i],!0)},t.prototype._disposeNode=function(){this._node&&(this._node.dispose(),this._node=null)},t.prototype.dispose=function(){this.onPointerDownObservable.clear(),this.onPointerEnterObservable.clear(),this.onPointerMoveObservable.clear(),this.onPointerOutObservable.clear(),this.onPointerUpObservable.clear(),this.onPointerClickObservable.clear(),this._disposeNode();for(var t=0,e=this._behaviors;t0)if(0===this._cursorOffset)this.text=this._text.substr(0,this._text.length-1);else(i=this._text.length-this._cursorOffset)>0&&(this.text=this._text.slice(0,i-1)+this._text.slice(i));return;case 46:if(this._text&&this._text.length>0){var i=this._text.length-this._cursorOffset;this.text=this._text.slice(0,i)+this._text.slice(i+1),this._cursorOffset--}return;case 13:return void(this._host.focusedControl=null);case 35:return this._cursorOffset=0,this._blinkIsEven=!1,void this._markAsDirty();case 36:return this._cursorOffset=this._text.length,this._blinkIsEven=!1,void this._markAsDirty();case 37:return this._cursorOffset++,this._cursorOffset>this._text.length&&(this._cursorOffset=this._text.length),this._blinkIsEven=!1,void this._markAsDirty();case 39:return this._cursorOffset--,this._cursorOffset<0&&(this._cursorOffset=0),this._blinkIsEven=!1,void this._markAsDirty();case 222:return void(this.deadKey=!0)}if(e&&(-1===t||32===t||t>47&&t<58||t>64&&t<91||t>185&&t<193||t>218&&t<223||t>95&&t<112)&&(this._currentKey=e,this.onBeforeKeyAddObservable.notifyObservers(this),e=this._currentKey,this._addKey))if(0===this._cursorOffset)this.text+=e;else{var r=this._text.length-this._cursorOffset;this.text=this._text.slice(0,r)+e+this._text.slice(r)}},e.prototype.processKeyboard=function(t){this.processKey(t.keyCode,t.key)},e.prototype._draw=function(t,e){var i=this;if(e.save(),this._applyStates(e),this._processMeasures(t,e)){(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._focusedBackground,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._background,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._fontOffset||(this._fontOffset=n.Control._GetFontOffset(e.font));var r=this._currentMeasure.left+this._margin.getValueInPixel(this._host,t.width);this.color&&(e.fillStyle=this.color);var o=this._beforeRenderText(this._text);this._isFocused||this._text||!this._placeholderText||(o=this._placeholderText,this._placeholderColor&&(e.fillStyle=this._placeholderColor)),this._textWidth=e.measureText(o).width;var s=2*this._margin.getValueInPixel(this._host,t.width);this._autoStretchWidth&&(this.width=Math.min(this._maxWidth.getValueInPixel(this._host,t.width),this._textWidth+s)+"px");var a=this._fontOffset.ascent+(this._currentMeasure.height-this._fontOffset.height)/2,h=this._width.getValueInPixel(this._host,t.width)-s;if(e.save(),e.beginPath(),e.rect(r,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,h+2,this._currentMeasure.height),e.clip(),this._isFocused&&this._textWidth>h){var l=r-this._textWidth+h;this._scrollLeft||(this._scrollLeft=l)}else this._scrollLeft=r;if(e.fillText(o,this._scrollLeft,this._currentMeasure.top+a),this._isFocused){if(this._clickedCoordinate){var u=this._scrollLeft+this._textWidth-this._clickedCoordinate,c=0;this._cursorOffset=0;var _=0;do{this._cursorOffset&&(_=Math.abs(u-c)),this._cursorOffset++,c=e.measureText(o.substr(o.length-this._cursorOffset,this._cursorOffset)).width}while(c=this._cursorOffset);Math.abs(u-c)>_&&this._cursorOffset--,this._blinkIsEven=!1,this._clickedCoordinate=null}if(!this._blinkIsEven){var f=this.text.substr(this._text.length-this._cursorOffset),p=e.measureText(f).width,d=this._scrollLeft+this._textWidth-p;dr+h&&(this._scrollLeft+=r+h-d,d=r+h,this._markAsDirty()),e.fillRect(d,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,2,this._fontOffset.height)}clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout(function(){i._blinkIsEven=!i._blinkIsEven,i._markAsDirty()},500)}e.restore(),this._thickness&&(this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness))}e.restore()},e.prototype._onPointerDown=function(e,i,r,n){return!!t.prototype._onPointerDown.call(this,e,i,r,n)&&(this._clickedCoordinate=i.x,this._host.focusedControl===this?(clearTimeout(this._blinkTimeout),this._markAsDirty(),!0):(this._host.focusedControl=this,!0))},e.prototype._onPointerUp=function(e,i,r,n,o){t.prototype._onPointerUp.call(this,e,i,r,n,o)},e.prototype._beforeRenderText=function(t){return t},e.prototype.dispose=function(){t.prototype.dispose.call(this),this.onBlurObservable.clear(),this.onFocusObservable.clear(),this.onTextChangedObservable.clear()},e}(n.Control);e.InputText=a},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=i(2),n=i(0),o=function(){function t(t){this._multiLine=t,this._x=new r.ValueAndUnit(0),this._y=new r.ValueAndUnit(0),this._point=new n.Vector2(0,0)}return Object.defineProperty(t.prototype,"x",{get:function(){return this._x.toString(this._multiLine._host)},set:function(t){this._x.toString(this._multiLine._host)!==t&&this._x.fromString(t)&&this._multiLine._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._y.toString(this._multiLine._host)},set:function(t){this._y.toString(this._multiLine._host)!==t&&this._y.fromString(t)&&this._multiLine._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"control",{get:function(){return this._control},set:function(t){this._control!==t&&(this._control&&this._controlObserver&&(this._control.onDirtyObservable.remove(this._controlObserver),this._controlObserver=null),this._control=t,this._control&&(this._controlObserver=this._control.onDirtyObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"mesh",{get:function(){return this._mesh},set:function(t){this._mesh!==t&&(this._mesh&&this._meshObserver&&this._mesh.getScene().onAfterCameraRenderObservable.remove(this._meshObserver),this._mesh=t,this._mesh&&(this._meshObserver=this._mesh.getScene().onAfterCameraRenderObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())},enumerable:!0,configurable:!0}),t.prototype.translate=function(){return this._point=this._translatePoint(),this._point},t.prototype._translatePoint=function(){if(null!=this._mesh)return this._multiLine._host.getProjectedPosition(this._mesh.getBoundingInfo().boundingSphere.center,this._mesh.getWorldMatrix());if(null!=this._control)return new n.Vector2(this._control.centerX,this._control.centerY);var t=this._multiLine._host,e=this._x.getValueInPixel(t,Number(t._canvas.width)),i=this._y.getValueInPixel(t,Number(t._canvas.height));return new n.Vector2(e,i)},t.prototype.dispose=function(){this.control=null,this.mesh=null},t}();e.MultiLinePoint=o},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(0),o=i(4),s=i(18),a=i(5),h=function(t){function e(e,i,r,s,a,h){void 0===i&&(i=0),void 0===r&&(r=0),void 0===a&&(a=!1),void 0===h&&(h=n.Texture.NEAREST_SAMPLINGMODE);var l=t.call(this,e,{width:i,height:r},s,a,h,n.Engine.TEXTUREFORMAT_RGBA)||this;return l._isDirty=!1,l._rootContainer=new o.Container("root"),l._lastControlOver={},l._lastControlDown={},l._capturingControl={},l._linkedControls=new Array,l._isFullscreen=!1,l._fullscreenViewport=new n.Viewport(0,0,1,1),l._idealWidth=0,l._idealHeight=0,l._useSmallestIdeal=!1,l._renderAtIdealSize=!1,l._blockNextFocusCheck=!1,l._renderScale=1,l.premulAlpha=!1,(s=l.getScene())&&l._texture?(l._renderObserver=s.onBeforeCameraRenderObservable.add(function(t){return l._checkUpdate(t)}),l._preKeyboardObserver=s.onPreKeyboardObservable.add(function(t){l._focusedControl&&(t.type===n.KeyboardEventTypes.KEYDOWN&&l._focusedControl.processKeyboard(t.event),t.skipOnPointerObservable=!0)}),l._rootContainer._link(null,l),l.hasAlpha=!0,i&&r||(l._resizeObserver=s.getEngine().onResizeObservable.add(function(){return l._onResize()}),l._onResize()),l._texture.isReady=!0,l):l}return r(e,t),Object.defineProperty(e.prototype,"renderScale",{get:function(){return this._renderScale},set:function(t){t!==this._renderScale&&(this._renderScale=t,this._onResize())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"background",{get:function(){return this._background},set:function(t){this._background!==t&&(this._background=t,this.markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"idealWidth",{get:function(){return this._idealWidth},set:function(t){this._idealWidth!==t&&(this._idealWidth=t,this.markAsDirty(),this._rootContainer._markAllAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"idealHeight",{get:function(){return this._idealHeight},set:function(t){this._idealHeight!==t&&(this._idealHeight=t,this.markAsDirty(),this._rootContainer._markAllAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useSmallestIdeal",{get:function(){return this._useSmallestIdeal},set:function(t){this._useSmallestIdeal!==t&&(this._useSmallestIdeal=t,this.markAsDirty(),this._rootContainer._markAllAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderAtIdealSize",{get:function(){return this._renderAtIdealSize},set:function(t){this._renderAtIdealSize!==t&&(this._renderAtIdealSize=t,this._onResize())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"layer",{get:function(){return this._layerToDispose},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rootContainer",{get:function(){return this._rootContainer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"focusedControl",{get:function(){return this._focusedControl},set:function(t){this._focusedControl!=t&&(this._focusedControl&&this._focusedControl.onBlur(),t&&t.onFocus(),this._focusedControl=t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isForeground",{get:function(){return!this.layer||!this.layer.isBackground},set:function(t){this.layer&&this.layer.isBackground!==!t&&(this.layer.isBackground=!t)},enumerable:!0,configurable:!0}),e.prototype.executeOnAllControls=function(t,e){e||(e=this._rootContainer);for(var i=0,r=e.children;i1?s.notRenderable=!0:(s.notRenderable=!1,l.scaleInPlace(this.renderScale),s._moveToProjectedPosition(l))}else n.Tools.SetImmediate(function(){s.linkWithMesh(null)})}}}(this._isDirty||this._rootContainer.isDirty)&&(this._isDirty=!1,this._render(),this.update(!0,this.premulAlpha))}},e.prototype._render=function(){var t=this.getSize(),e=t.width,i=t.height,r=this.getContext();r.clearRect(0,0,e,i),this._background&&(r.save(),r.fillStyle=this._background,r.fillRect(0,0,e,i),r.restore()),r.font="18px Arial",r.strokeStyle="white";var n=new a.Measure(0,0,e,i);this._rootContainer._draw(n,r)},e.prototype._doPicking=function(t,e,i,r,o){var s=this.getScene();if(s){var a=s.getEngine(),h=this.getSize();this._isFullscreen&&(t*=h.width/a.getRenderWidth(),e*=h.height/a.getRenderHeight()),this._capturingControl[r]?this._capturingControl[r]._processObservables(i,t,e,r,o):(this._rootContainer._processPicking(t,e,i,r,o)||i===n.PointerEventTypes.POINTERMOVE&&(this._lastControlOver[r]&&this._lastControlOver[r]._onPointerOut(this._lastControlOver[r]),delete this._lastControlOver[r]),this._manageFocus())}},e.prototype._cleanControlAfterRemovalFromList=function(t,e){for(var i in t){if(t.hasOwnProperty(i))t[i]===e&&delete t[i]}},e.prototype._cleanControlAfterRemoval=function(t){this._cleanControlAfterRemovalFromList(this._lastControlDown,t),this._cleanControlAfterRemovalFromList(this._lastControlOver,t)},e.prototype.attach=function(){var t=this,e=this.getScene();e&&(this._pointerMoveObserver=e.onPrePointerObservable.add(function(i,r){if(!e.isPointerCaptured(i.event.pointerId)&&(i.type===n.PointerEventTypes.POINTERMOVE||i.type===n.PointerEventTypes.POINTERUP||i.type===n.PointerEventTypes.POINTERDOWN)&&e){var o=e.cameraToUseForPointers||e.activeCamera;if(o){var s=e.getEngine(),a=o.viewport,h=(e.pointerX/s.getHardwareScalingLevel()-a.x*s.getRenderWidth())/a.width,l=(e.pointerY/s.getHardwareScalingLevel()-a.y*s.getRenderHeight())/a.height;t._shouldBlockPointer=!1,t._doPicking(h,l,i.type,i.event.pointerId||0,i.event.button),i.skipOnPointerObservable=t._shouldBlockPointer}}}),this._attachToOnPointerOut(e))},e.prototype.attachToMesh=function(t,e){var i=this;void 0===e&&(e=!0);var r=this.getScene();r&&(this._pointerObserver=r.onPointerObservable.add(function(e,r){if(e.type===n.PointerEventTypes.POINTERMOVE||e.type===n.PointerEventTypes.POINTERUP||e.type===n.PointerEventTypes.POINTERDOWN){var o=e.event.pointerId||0;if(e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh===t){var s=e.pickInfo.getTextureCoordinates();if(s){var a=i.getSize();i._doPicking(s.x*a.width,(1-s.y)*a.height,e.type,o,e.event.button)}}else e.type===n.PointerEventTypes.POINTERUP?(i._lastControlDown[o]&&i._lastControlDown[o]._forcePointerUp(o),delete i._lastControlDown[o],i.focusedControl=null):e.type===n.PointerEventTypes.POINTERMOVE&&(i._lastControlOver[o]&&i._lastControlOver[o]._onPointerOut(i._lastControlOver[o]),delete i._lastControlOver[o])}}),t.enablePointerMoveEvents=e,this._attachToOnPointerOut(r))},e.prototype.moveFocusToControl=function(t){this.focusedControl=t,this._lastPickedControl=t,this._blockNextFocusCheck=!0},e.prototype._manageFocus=function(){if(this._blockNextFocusCheck)return this._blockNextFocusCheck=!1,void(this._lastPickedControl=this._focusedControl);if(this._focusedControl&&this._focusedControl!==this._lastPickedControl){if(this._lastPickedControl.isFocusInvisible)return;this.focusedControl=null}},e.prototype._attachToOnPointerOut=function(t){var e=this;this._canvasPointerOutObserver=t.getEngine().onCanvasPointerOutObservable.add(function(t){e._lastControlOver[t.pointerId]&&e._lastControlOver[t.pointerId]._onPointerOut(e._lastControlOver[t.pointerId]),delete e._lastControlOver[t.pointerId],e._lastControlDown[t.pointerId]&&e._lastControlDown[t.pointerId]._forcePointerUp(),delete e._lastControlDown[t.pointerId]})},e.CreateForMesh=function(t,i,r,o){void 0===i&&(i=1024),void 0===r&&(r=1024),void 0===o&&(o=!0);var s=new e(t.name+" AdvancedDynamicTexture",i,r,t.getScene(),!0,n.Texture.TRILINEAR_SAMPLINGMODE),a=new n.StandardMaterial("AdvancedDynamicTextureMaterial",t.getScene());return a.backFaceCulling=!1,a.diffuseColor=n.Color3.Black(),a.specularColor=n.Color3.Black(),a.emissiveTexture=s,a.opacityTexture=s,t.material=a,s.attachToMesh(t,o),s},e.CreateFullscreenUI=function(t,i,r,o){void 0===i&&(i=!0),void 0===r&&(r=null),void 0===o&&(o=n.Texture.BILINEAR_SAMPLINGMODE);var s=new e(t,0,0,r,!1,o),a=new n.Layer(t+"_layer",null,r,!i);return a.texture=s,s._layerToDispose=a,s._isFullscreen=!0,s.attach(),s},e}(n.DynamicTexture);e.AdvancedDynamicTexture=h},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=i(0),n=i(2),o=function(){function t(t){this._fontFamily="Arial",this._fontStyle="",this._fontWeight="",this._fontSize=new n.ValueAndUnit(18,n.ValueAndUnit.UNITMODE_PIXEL,!1),this.onChangedObservable=new r.Observable,this._host=t}return Object.defineProperty(t.prototype,"fontSize",{get:function(){return this._fontSize.toString(this._host)},set:function(t){this._fontSize.toString(this._host)!==t&&this._fontSize.fromString(t)&&this.onChangedObservable.notifyObservers(this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontFamily",{get:function(){return this._fontFamily},set:function(t){this._fontFamily!==t&&(this._fontFamily=t,this.onChangedObservable.notifyObservers(this))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontStyle",{get:function(){return this._fontStyle},set:function(t){this._fontStyle!==t&&(this._fontStyle=t,this.onChangedObservable.notifyObservers(this))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fontWeight",{get:function(){return this._fontWeight},set:function(t){this._fontWeight!==t&&(this._fontWeight=t,this.onChangedObservable.notifyObservers(this))},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.onChangedObservable.clear()},t}();e.Style=o},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(10),o=i(0),s=function(t){function e(e){return t.call(this,e)||this}return r(e,t),e.prototype._getTypeName=function(){return"AbstractButton3D"},e.prototype._createNode=function(t){return new o.TransformNode("button"+this.name)},e}(n.Control3D);e.AbstractButton3D=s},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=function(t){function e(e,i){void 0===i&&(i=0);var r=t.call(this,e.x,e.y,e.z)||this;return r.buttonIndex=i,r}return r(e,t),e}(i(0).Vector3);e.Vector3WithInfo=n},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}(),n=this&&this.__decorate||function(t,e,i,r){var n,o=arguments.length,s=o<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,i,r);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(s=(o<3?n(s):o>3?n(e,i,s):n(e,i))||s);return o>3&&s&&Object.defineProperty(e,i,s),s};Object.defineProperty(e,"__esModule",{value:!0});var o=i(0);i(40).registerShader();var s=function(t){function e(){var e=t.call(this)||this;return e.INNERGLOW=!1,e.BORDER=!1,e.HOVERLIGHT=!1,e.rebuild(),e}return r(e,t),e}(o.MaterialDefines);e.FluentMaterialDefines=s;var a=function(t){function e(e,i){var r=t.call(this,e,i)||this;return r.innerGlowColorIntensity=.5,r.innerGlowColor=new o.Color3(1,1,1),r.alpha=1,r.albedoColor=new o.Color3(.3,.35,.4),r.renderBorders=!1,r.borderWidth=.5,r.edgeSmoothingValue=.02,r.borderMinValue=.1,r.renderHoverLight=!1,r.hoverRadius=1,r.hoverColor=new o.Color4(.3,.3,.3,1),r.hoverPosition=o.Vector3.Zero(),r}return r(e,t),e.prototype.needAlphaBlending=function(){return 1!==this.alpha},e.prototype.needAlphaTesting=function(){return!1},e.prototype.getAlphaTestTexture=function(){return null},e.prototype.isReadyForSubMesh=function(t,e,i){if(this.isFrozen&&this._wasPreviouslyReady&&e.effect)return!0;e._materialDefines||(e._materialDefines=new s);var r=this.getScene(),n=e._materialDefines;if(!this.checkReadyOnEveryCall&&e.effect&&n._renderId===r.getRenderId())return!0;n._areTexturesDirty&&(n.INNERGLOW=this.innerGlowColorIntensity>0,n.BORDER=this.renderBorders,n.HOVERLIGHT=this.renderHoverLight);var a=r.getEngine();if(n.isDirty){n.markAsProcessed(),r.resetCachedMaterial();var h=[o.VertexBuffer.PositionKind];h.push(o.VertexBuffer.NormalKind),h.push(o.VertexBuffer.UVKind);var l=["world","viewProjection","innerGlowColor","albedoColor","borderWidth","edgeSmoothingValue","scaleFactor","borderMinValue","hoverColor","hoverPosition","hoverRadius"],u=new Array,c=new Array;o.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:l,uniformBuffersNames:c,samplers:u,defines:n,maxSimultaneousLights:4});var _=n.toString();e.setEffect(r.getEngine().createEffect("fluent",{attributes:h,uniformsNames:l,uniformBuffersNames:c,samplers:u,defines:_,fallbacks:null,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},a))}return!(!e.effect||!e.effect.isReady())&&(n._renderId=r.getRenderId(),this._wasPreviouslyReady=!0,!0)},e.prototype.bindForSubMesh=function(t,e,i){var r=this.getScene(),n=i._materialDefines;if(n){var s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(t),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._mustRebind(r,s)&&(this._activeEffect.setColor4("albedoColor",this.albedoColor,this.alpha),n.INNERGLOW&&this._activeEffect.setColor4("innerGlowColor",this.innerGlowColor,this.innerGlowColorIntensity),n.BORDER&&(this._activeEffect.setFloat("borderWidth",this.borderWidth),this._activeEffect.setFloat("edgeSmoothingValue",this.edgeSmoothingValue),this._activeEffect.setFloat("borderMinValue",this.borderMinValue),e.getBoundingInfo().boundingBox.extendSize.multiplyToRef(e.scaling,o.Tmp.Vector3[0]),this._activeEffect.setVector3("scaleFactor",o.Tmp.Vector3[0])),n.HOVERLIGHT&&(this._activeEffect.setDirectColor4("hoverColor",this.hoverColor),this._activeEffect.setFloat("hoverRadius",this.hoverRadius),this._activeEffect.setVector3("hoverPosition",this.hoverPosition))),this._afterBind(e,this._activeEffect))}},e.prototype.getActiveTextures=function(){return t.prototype.getActiveTextures.call(this)},e.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)},e.prototype.dispose=function(e){t.prototype.dispose.call(this,e)},e.prototype.clone=function(t){var i=this;return o.SerializationHelper.Clone(function(){return new e(t,i.getScene())},this)},e.prototype.serialize=function(){var t=o.SerializationHelper.Serialize(this);return t.customType="BABYLON.GUI.FluentMaterial",t},e.prototype.getClassName=function(){return"FluentMaterial"},e.Parse=function(t,i,r){return o.SerializationHelper.Parse(function(){return new e(t.name,i)},t,i,r)},n([o.serialize(),o.expandToProperty("_markAllSubMeshesAsTexturesDirty")],e.prototype,"innerGlowColorIntensity",void 0),n([o.serializeAsColor3()],e.prototype,"innerGlowColor",void 0),n([o.serialize()],e.prototype,"alpha",void 0),n([o.serializeAsColor3()],e.prototype,"albedoColor",void 0),n([o.serialize(),o.expandToProperty("_markAllSubMeshesAsTexturesDirty")],e.prototype,"renderBorders",void 0),n([o.serialize()],e.prototype,"borderWidth",void 0),n([o.serialize()],e.prototype,"edgeSmoothingValue",void 0),n([o.serialize()],e.prototype,"borderMinValue",void 0),n([o.serialize(),o.expandToProperty("_markAllSubMeshesAsTexturesDirty")],e.prototype,"renderHoverLight",void 0),n([o.serialize()],e.prototype,"hoverRadius",void 0),n([o.serializeAsColor4()],e.prototype,"hoverColor",void 0),n([o.serializeAsVector3()],e.prototype,"hoverPosition",void 0),e}(o.PushMaterial);e.FluentMaterial=a},function(t,e,i){"use strict";function r(t){for(var i in t)e.hasOwnProperty(i)||(e[i]=t[i])}Object.defineProperty(e,"__esModule",{value:!0}),r(i(23)),r(i(36))},function(t,e,i){"use strict";function r(t){for(var i in t)e.hasOwnProperty(i)||(e[i]=t[i])}Object.defineProperty(e,"__esModule",{value:!0}),r(i(24)),r(i(17)),r(i(14)),r(i(5)),r(i(16)),r(i(18)),r(i(2))},function(t,e,i){"use strict";function r(t){for(var i in t)e.hasOwnProperty(i)||(e[i]=t[i])}Object.defineProperty(e,"__esModule",{value:!0}),r(i(12)),r(i(25)),r(i(26)),r(i(4)),r(i(1)),r(i(27)),r(i(28)),r(i(9)),r(i(15)),r(i(29)),r(i(30)),r(i(31)),r(i(32)),r(i(8)),r(i(7)),r(i(33)),r(i(34)),r(i(13)),r(i(35))},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),o=i(0),s=function(t){function e(e){var i=t.call(this,e)||this;return i.name=e,i._isChecked=!1,i._background="black",i._checkSizeRatio=.8,i._thickness=1,i.onIsCheckedChangedObservable=new o.Observable,i.isPointerBlocker=!0,i}return r(e,t),Object.defineProperty(e.prototype,"thickness",{get:function(){return this._thickness},set:function(t){this._thickness!==t&&(this._thickness=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"checkSizeRatio",{get:function(){return this._checkSizeRatio},set:function(t){t=Math.max(Math.min(1,t),0),this._checkSizeRatio!==t&&(this._checkSizeRatio=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"background",{get:function(){return this._background},set:function(t){this._background!==t&&(this._background=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isChecked",{get:function(){return this._isChecked},set:function(t){this._isChecked!==t&&(this._isChecked=t,this._markAsDirty(),this.onIsCheckedChangedObservable.notifyObservers(t))},enumerable:!0,configurable:!0}),e.prototype._getTypeName=function(){return"CheckBox"},e.prototype._draw=function(t,e){if(e.save(),this._applyStates(e),this._processMeasures(t,e)){var i=this._currentMeasure.width-this._thickness,r=this._currentMeasure.height-this._thickness;if((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),e.fillStyle=this._background,e.fillRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,i,r),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._isChecked){e.fillStyle=this.color;var n=i*this._checkSizeRatio,o=r*this._checkSizeRatio;e.fillRect(this._currentMeasure.left+this._thickness/2+(i-n)/2,this._currentMeasure.top+this._thickness/2+(r-o)/2,n,o)}e.strokeStyle=this.color,e.lineWidth=this._thickness,e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,i,r)}e.restore()},e.prototype._onPointerDown=function(e,i,r,n){return!!t.prototype._onPointerDown.call(this,e,i,r,n)&&(this.isChecked=!this.isChecked,!0)},e}(n.Control);e.Checkbox=s},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),o=i(0),s=function(t){function e(e){var i=t.call(this,e)||this;return i.name=e,i._value=o.Color3.Red(),i._tmpColor=new o.Color3,i._pointerStartedOnSquare=!1,i._pointerStartedOnWheel=!1,i._squareLeft=0,i._squareTop=0,i._squareSize=0,i._h=360,i._s=1,i._v=1,i.onValueChangedObservable=new o.Observable,i._pointerIsDown=!1,i.value=new o.Color3(.88,.1,.1),i.size="200px",i.isPointerBlocker=!0,i}return r(e,t),Object.defineProperty(e.prototype,"value",{get:function(){return this._value},set:function(t){this._value.equals(t)||(this._value.copyFrom(t),this._RGBtoHSV(this._value,this._tmpColor),this._h=this._tmpColor.r,this._s=Math.max(this._tmpColor.g,1e-5),this._v=Math.max(this._tmpColor.b,1e-5),this._markAsDirty(),this.onValueChangedObservable.notifyObservers(this._value))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"width",{set:function(t){this._width.toString(this._host)!==t&&this._width.fromString(t)&&(this._height.fromString(t),this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"height",{set:function(t){this._height.toString(this._host)!==t&&this._height.fromString(t)&&(this._width.fromString(t),this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this.width},set:function(t){this.width=t},enumerable:!0,configurable:!0}),e.prototype._getTypeName=function(){return"ColorPicker"},e.prototype._updateSquareProps=function(){var t=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),e=2*(t-.2*t)/Math.sqrt(2),i=t-.5*e;this._squareLeft=this._currentMeasure.left+i,this._squareTop=this._currentMeasure.top+i,this._squareSize=e},e.prototype._drawGradientSquare=function(t,e,i,r,n,o){var s=o.createLinearGradient(e,i,r+e,i);s.addColorStop(0,"#fff"),s.addColorStop(1,"hsl("+t+", 100%, 50%)"),o.fillStyle=s,o.fillRect(e,i,r,n);var a=o.createLinearGradient(e,i,e,n+i);a.addColorStop(0,"rgba(0,0,0,0)"),a.addColorStop(1,"#000"),o.fillStyle=a,o.fillRect(e,i,r,n)},e.prototype._drawCircle=function(t,e,i,r){r.beginPath(),r.arc(t,e,i+1,0,2*Math.PI,!1),r.lineWidth=3,r.strokeStyle="#333333",r.stroke(),r.beginPath(),r.arc(t,e,i,0,2*Math.PI,!1),r.lineWidth=3,r.strokeStyle="#ffffff",r.stroke()},e.prototype._createColorWheelCanvas=function(t,e){var i=document.createElement("canvas");i.width=2*t,i.height=2*t;for(var r=i.getContext("2d"),n=r.getImageData(0,0,2*t,2*t),o=n.data,s=this._tmpColor,a=t*t,h=t-e,l=h*h,u=-t;ua||_150?.04:-.16*(t-50)/100+.2;var g=(f-h)/(t-h);o[d+3]=g1-y?255*(1-(g-(1-y))/y):255}}return r.putImageData(n,0,0),i},e.prototype._RGBtoHSV=function(t,e){var i=t.r,r=t.g,n=t.b,o=Math.max(i,r,n),s=Math.min(i,r,n),a=0,h=0,l=o,u=o-s;0!==o&&(h=u/o),o!=s&&(o==i?(a=(r-n)/u,r=0&&o<=1?(a=n,h=s):o>=1&&o<=2?(a=s,h=n):o>=2&&o<=3?(h=n,l=s):o>=3&&o<=4?(h=s,l=n):o>=4&&o<=5?(a=s,l=n):o>=5&&o<=6&&(a=n,l=s);var u=i-n;r.set(a+u,h+u,l+u)},e.prototype._draw=function(t,e){if(e.save(),this._applyStates(e),this._processMeasures(t,e)){var i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),r=.2*i,n=this._currentMeasure.left,o=this._currentMeasure.top;this._colorWheelCanvas&&this._colorWheelCanvas.width==2*i||(this._colorWheelCanvas=this._createColorWheelCanvas(i,r)),this._updateSquareProps(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY,e.fillRect(this._squareLeft,this._squareTop,this._squareSize,this._squareSize)),e.drawImage(this._colorWheelCanvas,n,o),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._drawGradientSquare(this._h,this._squareLeft,this._squareTop,this._squareSize,this._squareSize,e);var s=this._squareLeft+this._squareSize*this._s,a=this._squareTop+this._squareSize*(1-this._v);this._drawCircle(s,a,.04*i,e);var h=i-.5*r;s=n+i+Math.cos((this._h-180)*Math.PI/180)*h,a=o+i+Math.sin((this._h-180)*Math.PI/180)*h,this._drawCircle(s,a,.35*r,e)}e.restore()},e.prototype._updateValueFromPointer=function(t,e){if(this._pointerStartedOnWheel){var i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),r=i+this._currentMeasure.left,n=i+this._currentMeasure.top;this._h=180*Math.atan2(e-n,t-r)/Math.PI+180}else this._pointerStartedOnSquare&&(this._updateSquareProps(),this._s=(t-this._squareLeft)/this._squareSize,this._v=1-(e-this._squareTop)/this._squareSize,this._s=Math.min(this._s,1),this._s=Math.max(this._s,1e-5),this._v=Math.min(this._v,1),this._v=Math.max(this._v,1e-5));this._HSVtoRGB(this._h,this._s,this._v,this._tmpColor),this.value=this._tmpColor},e.prototype._isPointOnSquare=function(t){this._updateSquareProps();var e=this._squareLeft,i=this._squareTop,r=this._squareSize;return t.x>=e&&t.x<=e+r&&t.y>=i&&t.y<=i+r},e.prototype._isPointOnWheel=function(t){var e=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),i=e+this._currentMeasure.left,r=e+this._currentMeasure.top,n=e-.2*e,o=e*e,s=n*n,a=t.x-i,h=t.y-r,l=a*a+h*h;return l<=o&&l>=s},e.prototype._onPointerDown=function(e,i,r,n){return!!t.prototype._onPointerDown.call(this,e,i,r,n)&&(this._pointerIsDown=!0,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._isPointOnSquare(i)?this._pointerStartedOnSquare=!0:this._isPointOnWheel(i)&&(this._pointerStartedOnWheel=!0),this._updateValueFromPointer(i.x,i.y),this._host._capturingControl[r]=this,!0)},e.prototype._onPointerMove=function(e,i){this._pointerIsDown&&this._updateValueFromPointer(i.x,i.y),t.prototype._onPointerMove.call(this,e,i)},e.prototype._onPointerUp=function(e,i,r,n,o){this._pointerIsDown=!1,delete this._host._capturingControl[r],t.prototype._onPointerUp.call(this,e,i,r,n,o)},e}(n.Control);e.ColorPicker=s},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(4),o=i(1),s=function(t){function e(e){var i=t.call(this,e)||this;return i.name=e,i._thickness=1,i}return r(e,t),Object.defineProperty(e.prototype,"thickness",{get:function(){return this._thickness},set:function(t){this._thickness!==t&&(this._thickness=t,this._markAsDirty())},enumerable:!0,configurable:!0}),e.prototype._getTypeName=function(){return"Ellipse"},e.prototype._localDraw=function(t){t.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(t.shadowColor=this.shadowColor,t.shadowBlur=this.shadowBlur,t.shadowOffsetX=this.shadowOffsetX,t.shadowOffsetY=this.shadowOffsetY),o.Control.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,t),this._background&&(t.fillStyle=this._background,t.fill()),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0),this._thickness&&(this.color&&(t.strokeStyle=this.color),t.lineWidth=this._thickness,t.stroke()),t.restore()},e.prototype._additionalProcessing=function(e,i){t.prototype._additionalProcessing.call(this,e,i),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness},e.prototype._clipForChildren=function(t){o.Control.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2,this._currentMeasure.height/2,t),t.clip()},e}(n.Container);e.Ellipse=s},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(4),o=i(2),s=i(1),a=function(t){function e(e){var i=t.call(this,e)||this;return i.name=e,i._rowDefinitions=new Array,i._columnDefinitions=new Array,i._cells={},i._childControls=new Array,i}return r(e,t),Object.defineProperty(e.prototype,"children",{get:function(){return this._childControls},enumerable:!0,configurable:!0}),e.prototype.addRowDefinition=function(t,e){return void 0===e&&(e=!1),this._rowDefinitions.push(new o.ValueAndUnit(t,e?o.ValueAndUnit.UNITMODE_PIXEL:o.ValueAndUnit.UNITMODE_PERCENTAGE)),this._markAsDirty(),this},e.prototype.addColumnDefinition=function(t,e){return void 0===e&&(e=!1),this._columnDefinitions.push(new o.ValueAndUnit(t,e?o.ValueAndUnit.UNITMODE_PIXEL:o.ValueAndUnit.UNITMODE_PERCENTAGE)),this._markAsDirty(),this},e.prototype.setRowDefinition=function(t,e,i){return void 0===i&&(i=!1),t<0||t>=this._rowDefinitions.length?this:(this._rowDefinitions[t]=new o.ValueAndUnit(e,i?o.ValueAndUnit.UNITMODE_PIXEL:o.ValueAndUnit.UNITMODE_PERCENTAGE),this._markAsDirty(),this)},e.prototype.setColumnDefinition=function(t,e,i){return void 0===i&&(i=!1),t<0||t>=this._columnDefinitions.length?this:(this._columnDefinitions[t]=new o.ValueAndUnit(e,i?o.ValueAndUnit.UNITMODE_PIXEL:o.ValueAndUnit.UNITMODE_PERCENTAGE),this._markAsDirty(),this)},e.prototype._removeCell=function(e,i){if(e){t.prototype.removeControl.call(this,e);for(var r=0,n=e.children;r=this._columnDefinitions.length)return this;for(var e=0;e=this._rowDefinitions.length)return this;for(var e=0;e1?this.notRenderable=!0:this.notRenderable=!1}else s.Tools.Error("Cannot move a control to a vector3 if the control is not at root level")},e.prototype._moveToProjectedPosition=function(t,e){void 0===e&&(e=!1);var i=t.x+this._linkOffsetX.getValue(this._host)+"px",r=t.y+this._linkOffsetY.getValue(this._host)+"px";e?(this.x2=i,this.y2=r,this._x2.ignoreAdaptiveScaling=!0,this._y2.ignoreAdaptiveScaling=!0):(this.x1=i,this.y1=r,this._x1.ignoreAdaptiveScaling=!0,this._y1.ignoreAdaptiveScaling=!0)},e}(n.Control);e.Line=a},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),o=i(16),s=i(0),a=function(t){function e(e){var i=t.call(this,e)||this;return i.name=e,i._lineWidth=1,i.onPointUpdate=function(){i._markAsDirty()},i.isHitTestVisible=!1,i._horizontalAlignment=n.Control.HORIZONTAL_ALIGNMENT_LEFT,i._verticalAlignment=n.Control.VERTICAL_ALIGNMENT_TOP,i._dash=[],i._points=[],i}return r(e,t),Object.defineProperty(e.prototype,"dash",{get:function(){return this._dash},set:function(t){this._dash!==t&&(this._dash=t,this._markAsDirty())},enumerable:!0,configurable:!0}),e.prototype.getAt=function(t){return this._points[t]||(this._points[t]=new o.MultiLinePoint(this)),this._points[t]},e.prototype.add=function(){for(var t=this,e=[],i=0;ii._maxX)&&(i._maxX=t._point.x),(null==i._maxY||t._point.y>i._maxY)&&(i._maxY=t._point.y))}),null==this._minX&&(this._minX=0),null==this._minY&&(this._minY=0),null==this._maxX&&(this._maxX=0),null==this._maxY&&(this._maxY=0)},e.prototype._measure=function(){null!=this._minX&&null!=this._maxX&&null!=this._minY&&null!=this._maxY&&(this._currentMeasure.width=Math.abs(this._maxX-this._minX)+this._lineWidth,this._currentMeasure.height=Math.abs(this._maxY-this._minY)+this._lineWidth)},e.prototype._computeAlignment=function(t,e){null!=this._minX&&null!=this._minY&&(this._currentMeasure.left=this._minX-this._lineWidth/2,this._currentMeasure.top=this._minY-this._lineWidth/2)},e.prototype.dispose=function(){for(;this._points.length>0;)this.remove(this._points.length-1);t.prototype.dispose.call(this)},e}(n.Control);e.MultiLine=a},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),o=i(0),s=function(t){function e(e){var i=t.call(this,e)||this;return i.name=e,i._isChecked=!1,i._background="black",i._checkSizeRatio=.8,i._thickness=1,i.group="",i.onIsCheckedChangedObservable=new o.Observable,i.isPointerBlocker=!0,i}return r(e,t),Object.defineProperty(e.prototype,"thickness",{get:function(){return this._thickness},set:function(t){this._thickness!==t&&(this._thickness=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"checkSizeRatio",{get:function(){return this._checkSizeRatio},set:function(t){t=Math.max(Math.min(1,t),0),this._checkSizeRatio!==t&&(this._checkSizeRatio=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"background",{get:function(){return this._background},set:function(t){this._background!==t&&(this._background=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isChecked",{get:function(){return this._isChecked},set:function(t){var e=this;this._isChecked!==t&&(this._isChecked=t,this._markAsDirty(),this.onIsCheckedChangedObservable.notifyObservers(t),this._isChecked&&this._host&&this._host.executeOnAllControls(function(t){if(t!==e&&void 0!==t.group){var i=t;i.group===e.group&&(i.isChecked=!1)}}))},enumerable:!0,configurable:!0}),e.prototype._getTypeName=function(){return"RadioButton"},e.prototype._draw=function(t,e){if(e.save(),this._applyStates(e),this._processMeasures(t,e)){var i=this._currentMeasure.width-this._thickness,r=this._currentMeasure.height-this._thickness;if((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),n.Control.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,e),e.fillStyle=this._background,e.fill(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),e.strokeStyle=this.color,e.lineWidth=this._thickness,e.stroke(),this._isChecked){e.fillStyle=this.color;var o=i*this._checkSizeRatio,s=r*this._checkSizeRatio;n.Control.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,o/2-this._thickness/2,s/2-this._thickness/2,e),e.fill()}}e.restore()},e.prototype._onPointerDown=function(e,i,r,n){return!!t.prototype._onPointerDown.call(this,e,i,r,n)&&(this.isChecked||(this.isChecked=!0),!0)},e}(n.Control);e.RadioButton=s},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(8),o=i(0),s=i(12),a=function(){return function(){}}();e.KeyPropertySet=a;var h=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.onKeyPressObservable=new o.Observable,e.defaultButtonWidth="40px",e.defaultButtonHeight="40px",e.defaultButtonPaddingLeft="2px",e.defaultButtonPaddingRight="2px",e.defaultButtonPaddingTop="2px",e.defaultButtonPaddingBottom="2px",e.defaultButtonColor="#DDD",e.defaultButtonBackground="#070707",e.shiftButtonColor="#7799FF",e.selectedShiftThickness=1,e.shiftState=0,e}return r(e,t),e.prototype._getTypeName=function(){return"VirtualKeyboard"},e.prototype._createKey=function(t,e){var i=this,r=s.Button.CreateSimpleButton(t,t);return r.width=e&&e.width?e.width:this.defaultButtonWidth,r.height=e&&e.height?e.height:this.defaultButtonHeight,r.color=e&&e.color?e.color:this.defaultButtonColor,r.background=e&&e.background?e.background:this.defaultButtonBackground,r.paddingLeft=e&&e.paddingLeft?e.paddingLeft:this.defaultButtonPaddingLeft,r.paddingRight=e&&e.paddingRight?e.paddingRight:this.defaultButtonPaddingRight,r.paddingTop=e&&e.paddingTop?e.paddingTop:this.defaultButtonPaddingTop,r.paddingBottom=e&&e.paddingBottom?e.paddingBottom:this.defaultButtonPaddingBottom,r.thickness=0,r.isFocusInvisible=!0,r.shadowColor=this.shadowColor,r.shadowBlur=this.shadowBlur,r.shadowOffsetX=this.shadowOffsetX,r.shadowOffsetY=this.shadowOffsetY,r.onPointerUpObservable.add(function(){i.onKeyPressObservable.notifyObservers(t)}),r},e.prototype.addKeysRow=function(t,e){var i=new n.StackPanel;i.isVertical=!1,i.isFocusInvisible=!0;for(var r=0;r1?this.selectedShiftThickness:0),s.text=t>0?s.text.toUpperCase():s.text.toLowerCase()}}}},Object.defineProperty(e.prototype,"connectedInputText",{get:function(){return this._connectedInputText},enumerable:!0,configurable:!0}),e.prototype.connect=function(t){var e=this;this.isVisible=!1,this._connectedInputText=t,this._onFocusObserver=t.onFocusObservable.add(function(){e.isVisible=!0}),this._onBlurObserver=t.onBlurObservable.add(function(){e.isVisible=!1}),this._onKeyPressObserver=this.onKeyPressObservable.add(function(t){if(e._connectedInputText){switch(t){case"⇧":return e.shiftState++,e.shiftState>2&&(e.shiftState=0),void e.applyShiftState(e.shiftState);case"←":return void e._connectedInputText.processKey(8);case"↵":return void e._connectedInputText.processKey(13)}e._connectedInputText.processKey(-1,e.shiftState?t.toUpperCase():t),1===e.shiftState&&(e.shiftState=0,e.applyShiftState(e.shiftState))}})},e.prototype.disconnect=function(){this._connectedInputText&&(this._connectedInputText.onFocusObservable.remove(this._onFocusObserver),this._connectedInputText.onBlurObservable.remove(this._onBlurObserver),this.onKeyPressObservable.remove(this._onKeyPressObserver),this._connectedInputText=null)},e.CreateDefaultLayout=function(){var t=new e;return t.addKeysRow(["1","2","3","4","5","6","7","8","9","0","←"]),t.addKeysRow(["q","w","e","r","t","y","u","i","o","p"]),t.addKeysRow(["a","s","d","f","g","h","j","k","l",";","'","↵"]),t.addKeysRow(["⇧","z","x","c","v","b","n","m",",",".","/"]),t.addKeysRow([" "],[{width:"200px"}]),t},e}(n.StackPanel);e.VirtualKeyboard=h},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),o=i(2),s=i(0),a=function(t){function e(e){var i=t.call(this,e)||this;return i.name=e,i._thumbWidth=new o.ValueAndUnit(20,o.ValueAndUnit.UNITMODE_PIXEL,!1),i._minimum=0,i._maximum=100,i._value=50,i._isVertical=!1,i._background="black",i._borderColor="white",i._barOffset=new o.ValueAndUnit(5,o.ValueAndUnit.UNITMODE_PIXEL,!1),i._isThumbCircle=!1,i._isThumbClamped=!1,i.onValueChangedObservable=new s.Observable,i._pointerIsDown=!1,i.isPointerBlocker=!0,i}return r(e,t),Object.defineProperty(e.prototype,"borderColor",{get:function(){return this._borderColor},set:function(t){this._borderColor!==t&&(this._borderColor=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"background",{get:function(){return this._background},set:function(t){this._background!==t&&(this._background=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"barOffset",{get:function(){return this._barOffset.toString(this._host)},set:function(t){this._barOffset.toString(this._host)!==t&&this._barOffset.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"barOffsetInPixels",{get:function(){return this._barOffset.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"thumbWidth",{get:function(){return this._thumbWidth.toString(this._host)},set:function(t){this._thumbWidth.toString(this._host)!==t&&this._thumbWidth.fromString(t)&&this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"thumbWidthInPixels",{get:function(){return this._thumbWidth.getValueInPixel(this._host,this._cachedParentMeasure.width)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"minimum",{get:function(){return this._minimum},set:function(t){this._minimum!==t&&(this._minimum=t,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maximum",{get:function(){return this._maximum},set:function(t){this._maximum!==t&&(this._maximum=t,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this._value},set:function(t){t=Math.max(Math.min(t,this._maximum),this._minimum),this._value!==t&&(this._value=t,this._markAsDirty(),this.onValueChangedObservable.notifyObservers(this._value))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isVertical",{get:function(){return this._isVertical},set:function(t){this._isVertical!==t&&(this._isVertical=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isThumbCircle",{get:function(){return this._isThumbCircle},set:function(t){this._isThumbCircle!==t&&(this._isThumbCircle=t,this._markAsDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isThumbClamped",{get:function(){return this._isThumbClamped},set:function(t){this._isThumbClamped!==t&&(this._isThumbClamped=t,this._markAsDirty())},enumerable:!0,configurable:!0}),e.prototype._getTypeName=function(){return"Slider"},e.prototype._getThumbThickness=function(t,e){var i=0;switch(t){case"circle":i=this._thumbWidth.isPixel?Math.max(this._thumbWidth.getValue(this._host),e):e*this._thumbWidth.getValue(this._host);break;case"rectangle":i=this._thumbWidth.isPixel?Math.min(this._thumbWidth.getValue(this._host),e):e*this._thumbWidth.getValue(this._host)}return i},e.prototype._draw=function(t,e){if(e.save(),this._applyStates(e),this._processMeasures(t,e)){var i=0,r=this.isThumbCircle?"circle":"rectangle",n=this._currentMeasure.left,o=this._currentMeasure.top,s=this._currentMeasure.width,a=this._currentMeasure.height,h=Math.max(this._currentMeasure.width,this._currentMeasure.height),l=Math.min(this._currentMeasure.width,this._currentMeasure.height),u=this._getThumbThickness(r,l);h-=u;var c=0;if(this._isVertical&&this._currentMeasure.heightareaXZ && areaYZ>areaXY)\n{\nscaledBorderWidth*=minOverMiddleScale;\n}\n}\nelse if (abs(normal.y) == 1.0) \n{\nscale.x=scale.z;\nif (areaXZ>areaXY && areaXZ>areaYZ)\n{\nscaledBorderWidth*=minOverMiddleScale;\n}\n}\nelse \n{\nif (areaXY>areaYZ && areaXY>areaXZ)\n{\nscaledBorderWidth*=minOverMiddleScale;\n}\n}\nfloat scaleRatio=min(scale.x,scale.y)/max(scale.x,scale.y);\nif (scale.x>scale.y)\n{\nscaleInfo.x=1.0-(scaledBorderWidth*scaleRatio);\nscaleInfo.y=1.0-scaledBorderWidth;\n}\nelse\n{\nscaleInfo.x=1.0-scaledBorderWidth;\nscaleInfo.y=1.0-(scaledBorderWidth*scaleRatio);\n} \n#endif \nvec4 worldPos=world*vec4(position,1.0);\n#ifdef HOVERLIGHT\nworldPosition=worldPos.xyz;\n#endif\ngl_Position=viewProjection*worldPos;\n}\n"},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=function(t){function e(e,i){var r=t.call(this,i)||this;return r._currentMesh=e,r.pointerEnterAnimation=function(){r.mesh&&r.mesh.scaling.scaleInPlace(1.1)},r.pointerOutAnimation=function(){r.mesh&&r.mesh.scaling.scaleInPlace(1/1.1)},r.pointerDownAnimation=function(){r.mesh&&r.mesh.scaling.scaleInPlace(.95)},r.pointerUpAnimation=function(){r.mesh&&r.mesh.scaling.scaleInPlace(1/.95)},r}return r(e,t),e.prototype._getTypeName=function(){return"MeshButton3D"},e.prototype._createNode=function(t){var e=this;return this._currentMesh.getChildMeshes().forEach(function(t){t.metadata=e}),this._currentMesh},e.prototype._affectMaterial=function(t){},e}(i(11).Button3D);e.MeshButton3D=n},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(0),o=i(3),s=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r(e,t),e.prototype._mapGridNode=function(t,e){var i=t.mesh;if(i){t.position=e.clone();var r=n.Tmp.Vector3[0];switch(r.copyFrom(e),this.orientation){case o.Container3D.FACEORIGIN_ORIENTATION:case o.Container3D.FACEFORWARD_ORIENTATION:r.addInPlace(new BABYLON.Vector3(0,0,-1)),i.lookAt(r);break;case o.Container3D.FACEFORWARDREVERSED_ORIENTATION:case o.Container3D.FACEORIGINREVERSED_ORIENTATION:r.addInPlace(new BABYLON.Vector3(0,0,1)),i.lookAt(r)}}},e}(i(6).VolumeBasedPanel);e.PlanePanel=s},function(t,e,i){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(e,i){function r(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0});var n=i(6),o=i(0),s=i(3),a=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._iteration=100,e}return r(e,t),Object.defineProperty(e.prototype,"iteration",{get:function(){return this._iteration},set:function(t){var e=this;this._iteration!==t&&(this._iteration=t,o.Tools.SetImmediate(function(){e._arrangeChildren()}))},enumerable:!0,configurable:!0}),e.prototype._mapGridNode=function(t,e){var i=t.mesh,r=this._scatterMapping(e);if(i){switch(this.orientation){case s.Container3D.FACEORIGIN_ORIENTATION:case s.Container3D.FACEFORWARD_ORIENTATION:i.lookAt(new o.Vector3(0,0,-1));break;case s.Container3D.FACEFORWARDREVERSED_ORIENTATION:case s.Container3D.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new o.Vector3(0,0,1))}t.position=r}},e.prototype._scatterMapping=function(t){return t.x=(1-2*Math.random())*this._cellWidth,t.y=(1-2*Math.random())*this._cellHeight,t},e.prototype._finalProcessing=function(){for(var t=[],e=0,i=this._children;er?-1:0});for(var s=Math.pow(this.margin,2),a=Math.max(this._cellWidth,this._cellHeight),h=o.Tmp.Vector2[0],l=o.Tmp.Vector3[0],u=0;u0?this.margin:0}}},e}(n.Container3D);e.StackPanel3D=s},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),function(t){for(var i in t)e.hasOwnProperty(i)||(e[i]=t[i])}(i(21))},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=i(0),n=i(3),o=function(){function t(t){var e=this;this._lastControlOver={},this._lastControlDown={},this.onPickedPointChangedObservable=new r.Observable,this._sharedMaterials={},this._scene=t||r.Engine.LastCreatedScene,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(function(){e._sceneDisposeObserver=null,e._utilityLayer=null,e.dispose()}),this._utilityLayer=new r.UtilityLayerRenderer(this._scene),this._utilityLayer.onlyCheckPointerDownEvents=!1,this._utilityLayer.mainSceneTrackerPredicate=function(t){return t&&t.metadata&&t.metadata._node},this._rootContainer=new n.Container3D("RootContainer"),this._rootContainer._host=this;var i=this._utilityLayer.utilityLayerScene;this._pointerOutObserver=this._utilityLayer.onPointerOutObservable.add(function(t){e._handlePointerOut(t,!0)}),this._pointerObserver=i.onPointerObservable.add(function(t,i){e._doPicking(t)}),this._utilityLayer.utilityLayerScene.autoClear=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,new r.HemisphericLight("hemi",r.Vector3.Up(),this._utilityLayer.utilityLayerScene)}return Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"utilityLayer",{get:function(){return this._utilityLayer},enumerable:!0,configurable:!0}),t.prototype._handlePointerOut=function(t,e){var i=this._lastControlOver[t];i&&(i._onPointerOut(i),delete this._lastControlOver[t]),e&&this._lastControlDown[t]&&(this._lastControlDown[t].forcePointerUp(),delete this._lastControlDown[t]),this.onPickedPointChangedObservable.notifyObservers(null)},t.prototype._doPicking=function(t){if(!this._utilityLayer||!this._utilityLayer.utilityLayerScene.activeCamera)return!1;var e=t.event,i=e.pointerId||0,n=e.button,o=t.pickInfo;if(!o||!o.hit)return this._handlePointerOut(i,t.type===r.PointerEventTypes.POINTERUP),!1;var s=o.pickedMesh.metadata;return o.pickedPoint&&this.onPickedPointChangedObservable.notifyObservers(o.pickedPoint),s._processObservables(t.type,o.pickedPoint,i,n)||t.type===r.PointerEventTypes.POINTERMOVE&&(this._lastControlOver[i]&&this._lastControlOver[i]._onPointerOut(this._lastControlOver[i]),delete this._lastControlOver[i]),t.type===r.PointerEventTypes.POINTERUP&&(this._lastControlDown[e.pointerId]&&(this._lastControlDown[e.pointerId].forcePointerUp(),delete this._lastControlDown[e.pointerId]),"touch"===e.pointerType&&this._handlePointerOut(i,!1)),!0},Object.defineProperty(t.prototype,"rootContainer",{get:function(){return this._rootContainer},enumerable:!0,configurable:!0}),t.prototype.containsControl=function(t){return this._rootContainer.containsControl(t)},t.prototype.addControl=function(t){return this._rootContainer.addControl(t),this},t.prototype.removeControl=function(t){return this._rootContainer.removeControl(t),this},t.prototype.dispose=function(){for(var t in this._rootContainer.dispose(),this._sharedMaterials)this._sharedMaterials.hasOwnProperty(t)&&this._sharedMaterials[t].dispose();this._sharedMaterials={},this._pointerOutObserver&&this._utilityLayer&&(this._utilityLayer.onPointerOutObservable.remove(this._pointerOutObserver),this._pointerOutObserver=null),this.onPickedPointChangedObservable.clear();var e=this._utilityLayer?this._utilityLayer.utilityLayerScene:null;e&&this._pointerObserver&&(e.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=null),this._scene&&this._sceneDisposeObserver&&(this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null),this._utilityLayer&&this._utilityLayer.dispose()},t}();e.GUI3DManager=o}])}); //# sourceMappingURL=babylon.gui.min.js.map \ No newline at end of file diff --git a/dist/preview release/gui/babylon.gui.min.js.map b/dist/preview release/gui/babylon.gui.min.js.map index b27e63cb6cd..1bd42deba83 100644 --- a/dist/preview release/gui/babylon.gui.min.js.map +++ b/dist/preview release/gui/babylon.gui.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack://BABYLON.GUI/webpack/universalModuleDefinition","webpack://BABYLON.GUI/webpack/bootstrap","webpack://BABYLON.GUI/external {\"root\":\"BABYLON\",\"commonjs\":\"babylonjs\",\"commonjs2\":\"babylonjs\",\"amd\":\"babylonjs\"}","webpack://BABYLON.GUI/./src/2D/controls/control.ts","webpack://BABYLON.GUI/./src/2D/valueAndUnit.ts","webpack://BABYLON.GUI/./src/3D/controls/container3D.ts","webpack://BABYLON.GUI/./src/2D/controls/container.ts","webpack://BABYLON.GUI/./src/3D/controls/volumeBasedPanel.ts","webpack://BABYLON.GUI/./src/2D/measure.ts","webpack://BABYLON.GUI/./src/2D/controls/stackPanel.ts","webpack://BABYLON.GUI/./src/2D/controls/textBlock.ts","webpack://BABYLON.GUI/./src/3D/controls/button3D.ts","webpack://BABYLON.GUI/./src/3D/controls/control3D.ts","webpack://BABYLON.GUI/./src/2D/controls/image.ts","webpack://BABYLON.GUI/./src/3D/materials/fluentMaterial.ts","webpack://BABYLON.GUI/./src/3D/vector3WithInfo.ts","webpack://BABYLON.GUI/./src/3D/controls/abstractButton3D.ts","webpack://BABYLON.GUI/./src/2D/style.ts","webpack://BABYLON.GUI/./src/2D/advancedDynamicTexture.ts","webpack://BABYLON.GUI/./src/2D/multiLinePoint.ts","webpack://BABYLON.GUI/./src/2D/controls/inputText.ts","webpack://BABYLON.GUI/./src/2D/math2D.ts","webpack://BABYLON.GUI/./src/2D/controls/rectangle.ts","webpack://BABYLON.GUI/./src/2D/controls/button.ts","webpack://BABYLON.GUI/./src/3D/gui3DManager.ts","webpack://BABYLON.GUI/./src/3D/materials/index.ts","webpack://BABYLON.GUI/./src/3D/controls/stackPanel3D.ts","webpack://BABYLON.GUI/./src/3D/controls/spherePanel.ts","webpack://BABYLON.GUI/./src/3D/controls/scatterPanel.ts","webpack://BABYLON.GUI/./src/3D/controls/planePanel.ts","webpack://BABYLON.GUI/./src/3D/controls/meshButton3D.ts","webpack://BABYLON.GUI/./src/3D/materials/shaders/fluent.vertex.fx","webpack://BABYLON.GUI/./src/3D/materials/shaders/fluent.fragment.fx","webpack://BABYLON.GUI/./src/3D/materials/shaders/fluent.ts","webpack://BABYLON.GUI/./src/3D/controls/holographicButton.ts","webpack://BABYLON.GUI/./src/3D/controls/cylinderPanel.ts","webpack://BABYLON.GUI/./src/3D/controls/index.ts","webpack://BABYLON.GUI/./src/3D/index.ts","webpack://BABYLON.GUI/./src/2D/controls/statics.ts","webpack://BABYLON.GUI/./src/2D/controls/slider.ts","webpack://BABYLON.GUI/./src/2D/controls/virtualKeyboard.ts","webpack://BABYLON.GUI/./src/2D/controls/radioButton.ts","webpack://BABYLON.GUI/./src/2D/controls/multiLine.ts","webpack://BABYLON.GUI/./src/2D/controls/line.ts","webpack://BABYLON.GUI/./src/2D/controls/inputPassword.ts","webpack://BABYLON.GUI/./src/2D/controls/grid.ts","webpack://BABYLON.GUI/./src/2D/controls/ellipse.ts","webpack://BABYLON.GUI/./src/2D/controls/colorpicker.ts","webpack://BABYLON.GUI/./src/2D/controls/checkbox.ts","webpack://BABYLON.GUI/./src/2D/controls/index.ts","webpack://BABYLON.GUI/./src/2D/index.ts","webpack://BABYLON.GUI/./src/index.ts"],"names":["root","factory","exports","module","require","define","amd","window","__WEBPACK_EXTERNAL_MODULE__0__","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","valueAndUnit_1","babylonjs_1","measure_1","math2D_1","Control","this","_alpha","_alphaSet","_zIndex","_currentMeasure","Measure","Empty","_fontFamily","_fontStyle","_fontWeight","_fontSize","ValueAndUnit","UNITMODE_PIXEL","_width","UNITMODE_PERCENTAGE","_height","_color","_style","_horizontalAlignment","HORIZONTAL_ALIGNMENT_CENTER","_verticalAlignment","VERTICAL_ALIGNMENT_CENTER","_isDirty","_tempParentMeasure","_cachedParentMeasure","_paddingLeft","_paddingRight","_paddingTop","_paddingBottom","_left","_top","_scaleX","_scaleY","_rotation","_transformCenterX","_transformCenterY","_transformMatrix","Matrix2D","Identity","_invertTransformMatrix","_transformedPosition","Vector2","Zero","_onlyMeasureMode","_isMatrixDirty","_isVisible","_fontSet","_dummyVector2","_downCount","_enterCount","_doNotRender","_downPointerIds","isHitTestVisible","isPointerBlocker","isFocusInvisible","shadowOffsetX","shadowOffsetY","shadowBlur","shadowColor","_linkOffsetX","_linkOffsetY","onPointerMoveObservable","Observable","onPointerOutObservable","onPointerDownObservable","onPointerUpObservable","onPointerClickObservable","onPointerEnterObservable","onDirtyObservable","onAfterDrawObservable","_getTypeName","_fontOffset","offset","_markAsDirty","_markMatrixAsDirty","toString","_host","fromString","getValueInPixel","width","height","_resetFontCache","_this","onChangedObservable","remove","_styleObserver","add","isPercentage","fontSizeToUse","isPixel","getValue","zIndex","_root","_reOrderControl","left","top","getLocalCoordinates","globalCoordinates","result","getLocalCoordinatesToRef","x","y","getParentLocalCoordinates","moveToVector3","position","scene","_rootContainer","horizontalAlignment","HORIZONTAL_ALIGNMENT_LEFT","verticalAlignment","VERTICAL_ALIGNMENT_TOP","globalViewport","_getGlobalViewport","projectedPosition","Vector3","Project","Matrix","getTransformMatrix","_moveToProjectedPosition","z","notRenderable","Tools","Error","linkWithMesh","mesh","index","_linkedControls","indexOf","_linkedMesh","splice","push","oldLeft","oldTop","newLeft","newTop","ignoreAdaptiveScaling","Math","abs","markAsDirty","_markAllAsDirty","_font","_prepareFont","_link","host","_transform","context","offsetX","offsetY","translate","rotate","scale","_cachedOffsetX","_cachedOffsetY","ComposeToRef","invertToRef","_applyStates","font","fillStyle","globalAlpha","_processMeasures","parentMeasure","isEqualsTo","copyFrom","_preMeasure","_measure","_computeAlignment","_additionalProcessing","hasObservers","notifyObservers","_clip","clip","beginPath","leftShadowOffset","min","rightShadowOffset","max","topShadowOffset","bottomShadowOffset","rect","parentWidth","parentHeight","HORIZONTAL_ALIGNMENT_RIGHT","VERTICAL_ALIGNMENT_BOTTOM","_draw","contains","transformCoordinates","_shouldBlockPointer","_processPicking","type","pointerId","buttonIndex","isVisible","_processObservables","_onPointerMove","target","coordinates","parent","_onPointerEnter","_onPointerOut","_onPointerDown","Vector2WithInfo","_onPointerUp","notifyClick","canNotifyClick","_forcePointerUp","copyFromFloats","PointerEventTypes","POINTERMOVE","previousControlOver","_lastControlOver","POINTERDOWN","_lastControlDown","_lastPickedControl","POINTERUP","fontStyle","fontWeight","fontSizeInPixels","fontFamily","_GetFontOffset","dispose","clear","removeControl","_HORIZONTAL_ALIGNMENT_LEFT","_HORIZONTAL_ALIGNMENT_RIGHT","_HORIZONTAL_ALIGNMENT_CENTER","_VERTICAL_ALIGNMENT_TOP","_VERTICAL_ALIGNMENT_BOTTOM","_VERTICAL_ALIGNMENT_CENTER","_FontHeightSizes","text","document","createElement","innerHTML","style","block","display","verticalAlign","div","appendChild","body","fontAscent","fontHeight","getBoundingClientRect","removeChild","ascent","descent","drawEllipse","arc","PI","closePath","AddHeader","unit","negativeValueAllowed","_value","refValue","idealWidth","getSize","idealHeight","useSmallestIdeal","innerWidth","innerHeight","source","match","_Regex","exec","length","sourceValue","parseFloat","sourceUnit","_UNITMODE_PERCENTAGE","_UNITMODE_PIXEL","control3D_1","Container3D","_super","_blockLayout","_children","Array","__extends","_arrangeChildren","updateLayout","containsControl","control","addControl","utilityLayer","_prepareNode","utilityLayerScene","node","blockLayout","_createNode","TransformNode","_disposeNode","_i","_a","UNSET_ORIENTATION","FACEORIGIN_ORIENTATION","FACEORIGINREVERSED_ORIENTATION","FACEFORWARD_ORIENTATION","FACEFORWARDREVERSED_ORIENTATION","Control3D","control_1","Container","_measureForChildren","_adaptWidthToChildren","_adaptHeightToChildren","_background","getChildByName","children","child","getChildByType","typeName","_cleanControlAfterRemoval","_localDraw","fillRect","save","_clipForChildren","computedWidth","computedHeight","adaptWidthToChildren","adaptHeightToChildren","restore","container3D_1","VolumeBasedPanel","_columns","_rows","_rowThenColum","_orientation","margin","SetImmediate","_cellWidth","_cellHeight","rows","columns","controlCount","currentInverseWorld","Invert","computeWorldMatrix","boundingBox","getHierarchyBoundingVectors","extendSize","Tmp","diff","subtractToRef","scaleInPlace","TransformNormalToRef","ceil","startOffsetX","startOffsetY","nodeGrid","cellCounter","_b","_c","_mapGridNode","_finalProcessing","other","container_1","StackPanel","_isVertical","_manualWidth","_manualHeight","_doNotTrackManualChanges","_tempMeasureStore","stackWidth","stackHeight","panelWidthChanged","panelHeightChanged","previousHeight","previousWidth","TextWrapping","TextBlock","_text","_textWrapping","Clip","_textHorizontalAlignment","_textVerticalAlignment","_resizeToFit","_lineSpacing","_outlineWidth","_outlineColor","onTextChangedObservable","onLinesReadyObservable","_lines","_drawText","textWidth","outlineWidth","strokeText","fillText","_renderLines","lineWidth","strokeStyle","outlineColor","_breakLines","refWidth","lines","split","Ellipsis","WordWrap","_lines_3","_line","_parseLine","_lines_2","apply","_parseLineWordWrap","_lines_1","_parseLineEllipsis","line","measureText","slice","words","testLine","testWidth","rootY","maxLineWidth","internalValue","paddingLeftInPixels","paddingRightInPixels","paddingTopInPixels","paddingBottomInPixels","computeExpectedHeight","widthInPixels","getContext","abstractButton3D_1","advancedDynamicTexture_1","Button3D","_contentResolution","_contentScaleRatio","pointerEnterAnimation","_currentMaterial","emissiveColor","Color3","Red","pointerOutAnimation","Black","pointerDownAnimation","scaling","pointerUpAnimation","_resetContent","_disposeFacadeTexture","_facadeTexture","content","_content","AdvancedDynamicTexture","Texture","TRILINEAR_SAMPLINGMODE","rootContainer","scaleX","scaleY","premulAlpha","_applyFacade","facadeTexture","emissiveTexture","faceUV","Vector4","MeshBuilder","CreateBox","depth","_affectMaterial","material","StandardMaterial","getScene","specularColor","AbstractButton3D","vector3WithInfo_1","_behaviors","_node","addBehavior","behavior","init","isLoading","onDataLoadedObservable","addOnce","attach","removeBehavior","detach","getBehaviorByName","setEnabled","AbstractMesh","linkToTransformNode","metadata","isPickable","Vector3WithInfo","forcePointerUp","pickedPoint","GUIImage","url","_loaded","_stretch","STRETCH_FILL","_autoScale","_sourceLeft","_sourceTop","_sourceWidth","_sourceHeight","_cellId","synchronizeSizeWithContent","_domImage","_onImageLoaded","onload","_imageWidth","_imageHeight","_source","Image","SetCorsBehavior","src","cellId","rowCount","naturalWidth","cellWidth","column","row","cellHeight","STRETCH_NONE","drawImage","STRETCH_UNIFORM","hRatio","vRatio","ratio","centerX","centerY","STRETCH_EXTEND","_STRETCH_NONE","_STRETCH_FILL","_STRETCH_UNIFORM","_STRETCH_EXTEND","registerShader","FluentMaterialDefines","INNERGLOW","BORDER","HOVERLIGHT","rebuild","MaterialDefines","FluentMaterial","innerGlowColorIntensity","innerGlowColor","alpha","albedoColor","renderBorders","borderWidth","edgeSmoothingValue","borderMinValue","renderHoverLight","hoverRadius","hoverColor","Color4","hoverPosition","needAlphaBlending","needAlphaTesting","getAlphaTestTexture","isReadyForSubMesh","subMesh","useInstances","isFrozen","_wasPreviouslyReady","effect","_materialDefines","defines","checkReadyOnEveryCall","_renderId","getRenderId","_areTexturesDirty","engine","getEngine","isDirty","markAsProcessed","resetCachedMaterial","attribs","VertexBuffer","PositionKind","NormalKind","UVKind","uniforms","samplers","uniformBuffers","MaterialHelper","PrepareUniformsAndSamplersList","uniformsNames","uniformBuffersNames","maxSimultaneousLights","join","setEffect","createEffect","attributes","fallbacks","onCompiled","onError","indexParameters","isReady","bindForSubMesh","world","_activeEffect","bindOnlyWorldMatrix","setMatrix","_mustRebind","setColor4","setFloat","getBoundingInfo","multiplyToRef","setVector3","setDirectColor4","_afterBind","getActiveTextures","hasTexture","texture","forceDisposeEffect","clone","SerializationHelper","Clone","serialize","serializationObject","Serialize","customType","getClassName","Parse","rootUrl","__decorate","expandToProperty","serializeAsColor3","serializeAsColor4","serializeAsVector3","PushMaterial","Style","style_1","generateMipMaps","samplingMode","NEAREST_SAMPLINGMODE","Engine","TEXTUREFORMAT_RGBA","_capturingControl","_isFullscreen","_fullscreenViewport","Viewport","_idealWidth","_idealHeight","_useSmallestIdeal","_renderAtIdealSize","_blockNextFocusCheck","_renderScale","_texture","_renderObserver","onBeforeCameraRenderObservable","camera","_checkUpdate","_preKeyboardObserver","onPreKeyboardObservable","info","_focusedControl","KeyboardEventTypes","KEYDOWN","processKeyboard","event","skipOnPointerObservable","hasAlpha","_resizeObserver","onResizeObservable","_onResize","_layerToDispose","onBlur","onFocus","layer","isBackground","executeOnAllControls","func","container","_isFontSizeInPercentage","createStyle","_pointerMoveObserver","onPrePointerObservable","_pointerObserver","onPointerObservable","_canvasPointerOutObserver","onCanvasPointerOutObservable","textureSize","renderWidth","getRenderWidth","renderHeight","getRenderHeight","scaleTo","toGlobal","getProjectedPosition","worldMatrix","renderScale","layerMask","isDisposed","boundingSphere","center","getWorldMatrix","_render","update","clearRect","measure","_doPicking","_manageFocus","_cleanControlAfterRemovalFromList","list","pi","state","isPointerCaptured","cameraToUseForPointers","activeCamera","viewport","pointerX","getHardwareScalingLevel","pointerY","button","_attachToOnPointerOut","attachToMesh","supportPointerMove","pickInfo","hit","pickedMesh","uv","getTextureCoordinates","size","focusedControl","enablePointerMoveEvents","moveFocusToControl","pointerEvent","CreateForMesh","backFaceCulling","diffuseColor","opacityTexture","CreateFullscreenUI","foreground","sampling","BILINEAR_SAMPLINGMODE","Layer","DynamicTexture","MultiLinePoint","multiLine","_multiLine","_x","_y","_point","_control","_controlObserver","onPointUpdate","_mesh","_meshObserver","onAfterCameraRenderObservable","_translatePoint","xValue","Number","_canvas","yValue","InputText","_placeholderText","_focusedBackground","_placeholderColor","_thickness","_margin","_autoStretchWidth","_maxWidth","_isFocused","_blinkIsEven","_cursorOffset","_deadKey","_addKey","_currentKey","promptMessage","onBeforeKeyAddObservable","onFocusObservable","onBlurObservable","flag","autoStretchWidth","_scrollLeft","clearTimeout","_blinkTimeout","navigator","userAgent","prompt","processKey","keyCode","substr","deletePosition","deadKey","insertPosition","evt","clipTextLeft","color","_beforeRenderText","_textWidth","marginWidth","availableWidth","textLeft","_clickedCoordinate","absoluteCursorPosition","currentSize","previousDist","cursorOffsetText","cursorOffsetWidth","cursorLeft","setTimeout","strokeRect","m00","m01","m10","m11","m20","m21","Float32Array","fromValues","determinant","l0","l1","l2","l3","l4","l5","det","Epsilon","detDiv","det4","det5","r0","r1","r2","r3","r4","r5","TranslationToRef","ScalingToRef","RotationToRef","angle","sin","cos","tx","ty","parentMatrix","_TempPreTranslationMatrix","_TempScalingMatrix","_TempRotationMatrix","_TempPostTranslationMatrix","_TempCompose0","_TempCompose1","_TempCompose2","Rectangle","_cornerRadius","_drawRoundedRect","fill","stroke","radius","moveTo","lineTo","quadraticCurveTo","rectangle_1","textBlock_1","image_1","Button","thickness","CreateImageButton","imageUrl","textBlock","textWrapping","textHorizontalAlignment","paddingLeft","iconImage","stretch","CreateImageOnlyButton","CreateSimpleButton","CreateImageWithCenterTextButton","GUI3DManager","onPickedPointChangedObservable","_sharedMaterials","_scene","LastCreatedScene","_sceneDisposeObserver","onDisposeObservable","_utilityLayer","UtilityLayerRenderer","onlyCheckPointerDownEvents","mainSceneTrackerPredicate","_pointerOutObserver","_handlePointerOut","autoClear","autoClearDepthAndStencil","HemisphericLight","Up","isPointerUp","pickingInfo","pointerType","materialName","__export","StackPanel3D","isVertical","extendSizes","TransformNormal","volumeBasedPanel_1","SpherePanel","arguments","_radius","nodePosition","newPos","_sphericalMapping","orientation","lookAt","BABYLON","Axis","Y","Space","LOCAL","xAngle","yAngle","RotationYawPitchRollToRef","ScatterPanel","_iteration","_scatterMapping","random","meshes","count","sort","a","b","distance1","lengthSquared","distance2","radiusPaddingSquared","pow","cellSize","difference2D","difference","j","combinedRadius","distance","normalize","sqrt","addInPlace","subtractInPlace","PlanePanel","MeshButton3D","_currentMesh","getChildMeshes","forEach","fShader","vShader","Effect","ShadersStore","button3D_1","fluentMaterial_1","stackPanel_1","HolographicButton","shareMaterials","_shareMaterials","_frontPlate","_rebuildContent","_imageUrl","_backMaterial","_frontMaterial","_plateMaterial","panel","image","paddingTop","paddingBottom","fontSize","_backPlate","_textPlate","_createBackMaterial","_pickedPointObserver","_createFrontMaterial","_createPlateMaterial","CylinderPanel","_cylindricalMapping","options","isHorizontal","controlFirst","header","paddingRight","Slider","_thumbWidth","_minimum","_maximum","_borderColor","_barOffset","_isThumbCircle","_isThumbClamped","onValueChangedObservable","_pointerIsDown","_getThumbThickness","backgroundLength","thumbThickness","effectiveBarOffset","isThumbCircle","backgroundBoxLength","backgroundBoxThickness","effectiveThumbThickness","console","error","isThumbClamped","thumbPosition","_updateValueFromPointer","rotation","button_1","KeyPropertySet","VirtualKeyboard","onKeyPressObservable","defaultButtonWidth","defaultButtonHeight","defaultButtonPaddingLeft","defaultButtonPaddingRight","defaultButtonPaddingTop","defaultButtonPaddingBottom","defaultButtonColor","defaultButtonBackground","shiftButtonColor","selectedShiftThickness","shiftState","_createKey","propertySet","background","addKeysRow","keys","propertySets","properties","applyShiftState","rowContainer","button_tblock","toUpperCase","toLowerCase","_connectedInputText","connect","input","_onFocusObserver","_onBlurObserver","_onKeyPressObserver","disconnect","CreateDefaultLayout","returnValue","RadioButton","_isChecked","_checkSizeRatio","group","onIsCheckedChangedObservable","undefined","childRadio","isChecked","actualWidth","actualHeight","offsetWidth","offseHeight","multiLinePoint_1","MultiLine","_lineWidth","_dash","_points","getAt","items","map","item","point","setLineDash","first","_minX","_minY","_maxX","_maxY","Line","_x1","_y1","_x2","_y2","_connectedControl","_connectedControlDirtyObserver","_effectiveX2","_effectiveY2","end","x2","y2","x1","y1","InputPassword","txt","Grid","_rowDefinitions","_columnDefinitions","_cells","_childControls","addRowDefinition","addColumnDefinition","setRowDefinition","setColumnDefinition","_removeCell","cell","childIndex","_offsetCell","previousKey","_tag","removeColumnDefinition","removeRowDefinition","goodContainer","widths","heights","lefts","tops","globalWidthPercentage","availableHeight","globalHeightPercentage","_d","_e","_f","_g","parseInt","Ellipse","ColorPicker","_tmpColor","_pointerStartedOnSquare","_pointerStartedOnWheel","_squareLeft","_squareTop","_squareSize","_h","_s","_v","equals","_RGBtoHSV","g","_updateSquareProps","squareSize","_drawGradientSquare","hueValue","lgh","createLinearGradient","addColorStop","lgv","_drawCircle","_createColorWheelCanvas","canvas","getImageData","data","maxDistSq","innerRadius","minDistSq","distSq","dist","ang","atan2","_HSVtoRGB","alphaAmount","alphaRatio","putImageData","h","v","dm","hue","saturation","chroma","set","wheelThickness","_colorWheelCanvas","cx","cy","_isPointOnSquare","_isPointOnWheel","radiusSq","innerRadiusSq","dx","dy","Checkbox"],"mappings":"CAAA,SAAAA,EAAAC,GACA,iBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,EAAAG,QAAA,cACA,mBAAAC,eAAAC,IACAD,OAAA,8BAAAJ,GACA,iBAAAC,QACAA,QAAA,iBAAAD,EAAAG,QAAA,eAEAJ,EAAA,QAAAA,EAAA,YAAyCA,EAAA,YAAAC,EAAAD,EAAA,UARzC,CASCO,OAAA,SAAAC,GACD,mBCTA,IAAAC,KAGA,SAAAC,EAAAC,GAGA,GAAAF,EAAAE,GACA,OAAAF,EAAAE,GAAAT,QAGA,IAAAC,EAAAM,EAAAE,IACAC,EAAAD,EACAE,GAAA,EACAX,YAUA,OANAY,EAAAH,GAAAI,KAAAZ,EAAAD,QAAAC,IAAAD,QAAAQ,GAGAP,EAAAU,GAAA,EAGAV,EAAAD,QA0DA,OArDAQ,EAAAM,EAAAF,EAGAJ,EAAAO,EAAAR,EAGAC,EAAAQ,EAAA,SAAAhB,EAAAiB,EAAAC,GACAV,EAAAW,EAAAnB,EAAAiB,IACAG,OAAAC,eAAArB,EAAAiB,GAA0CK,YAAA,EAAAC,IAAAL,KAK1CV,EAAAgB,EAAA,SAAAxB,GACA,oBAAAyB,eAAAC,aACAN,OAAAC,eAAArB,EAAAyB,OAAAC,aAAwDC,MAAA,WAExDP,OAAAC,eAAArB,EAAA,cAAiD2B,OAAA,KAQjDnB,EAAAoB,EAAA,SAAAD,EAAAE,GAEA,GADA,EAAAA,IAAAF,EAAAnB,EAAAmB,IACA,EAAAE,EAAA,OAAAF,EACA,KAAAE,GAAA,iBAAAF,QAAAG,WAAA,OAAAH,EACA,IAAAI,EAAAX,OAAAY,OAAA,MAGA,GAFAxB,EAAAgB,EAAAO,GACAX,OAAAC,eAAAU,EAAA,WAAyCT,YAAA,EAAAK,UACzC,EAAAE,GAAA,iBAAAF,EAAA,QAAAM,KAAAN,EAAAnB,EAAAQ,EAAAe,EAAAE,EAAA,SAAAA,GAAgH,OAAAN,EAAAM,IAAqBC,KAAA,KAAAD,IACrI,OAAAF,GAIAvB,EAAA2B,EAAA,SAAAlC,GACA,IAAAiB,EAAAjB,KAAA6B,WACA,WAA2B,OAAA7B,EAAA,SAC3B,WAAiC,OAAAA,GAEjC,OADAO,EAAAQ,EAAAE,EAAA,IAAAA,GACAA,GAIAV,EAAAW,EAAA,SAAAiB,EAAAC,GAAsD,OAAAjB,OAAAkB,UAAAC,eAAA1B,KAAAuB,EAAAC,IAGtD7B,EAAAgC,EAAA,GAIAhC,IAAAiC,EAAA,oBClFAxC,EAAAD,QAAAM,iFCEA,IAAAoC,EAAAlC,EAAA,GACAmC,EAAAnC,EAAA,GACAoC,EAAApC,EAAA,GAEAqC,EAAArC,EAAA,IAMAsC,EAAA,WAirBI,SAAAA,EAEW7B,GAAA8B,KAAA9B,OAlrBH8B,KAAAC,OAAS,EACTD,KAAAE,WAAY,EACZF,KAAAG,QAAU,EAQXH,KAAAI,gBAAkBP,EAAAQ,QAAQC,QACzBN,KAAAO,YAAc,QACdP,KAAAQ,WAAa,GACbR,KAAAS,YAAc,GACdT,KAAAU,UAAY,IAAIf,EAAAgB,aAAa,GAAIhB,EAAAgB,aAAaC,gBAAgB,GAG/DZ,KAAAa,OAAS,IAAIlB,EAAAgB,aAAa,EAAGhB,EAAAgB,aAAaG,qBAAqB,GAE/Dd,KAAAe,QAAU,IAAIpB,EAAAgB,aAAa,EAAGhB,EAAAgB,aAAaG,qBAAqB,GAG/Dd,KAAAgB,OAAS,GACThB,KAAAiB,OAA0B,KAGxBjB,KAAAkB,qBAAuBnB,EAAQoB,4BAE/BnB,KAAAoB,mBAAqBrB,EAAQsB,0BAC/BrB,KAAAsB,UAAW,EAEZtB,KAAAuB,mBAAqB1B,EAAAQ,QAAQC,QAE1BN,KAAAwB,qBAAuB3B,EAAAQ,QAAQC,QACjCN,KAAAyB,aAAe,IAAI9B,EAAAgB,aAAa,GAChCX,KAAA0B,cAAgB,IAAI/B,EAAAgB,aAAa,GACjCX,KAAA2B,YAAc,IAAIhC,EAAAgB,aAAa,GAC/BX,KAAA4B,eAAiB,IAAIjC,EAAAgB,aAAa,GAEnCX,KAAA6B,MAAQ,IAAIlC,EAAAgB,aAAa,GAEzBX,KAAA8B,KAAO,IAAInC,EAAAgB,aAAa,GACvBX,KAAA+B,QAAU,EACV/B,KAAAgC,QAAU,EACVhC,KAAAiC,UAAY,EACZjC,KAAAkC,kBAAoB,GACpBlC,KAAAmC,kBAAoB,GACpBnC,KAAAoC,iBAAmBtC,EAAAuC,SAASC,WAE1BtC,KAAAuC,uBAAyBzC,EAAAuC,SAASC,WAElCtC,KAAAwC,qBAAuB5C,EAAA6C,QAAQC,OACjC1C,KAAA2C,kBAAmB,EACnB3C,KAAA4C,gBAAiB,EAGjB5C,KAAA6C,YAAa,EAGb7C,KAAA8C,UAAW,EACX9C,KAAA+C,cAAgBnD,EAAA6C,QAAQC,OACxB1C,KAAAgD,WAAa,EACbhD,KAAAiD,aAAe,EACfjD,KAAAkD,cAAe,EACflD,KAAAmD,mBAMDnD,KAAAoD,kBAAmB,EAEnBpD,KAAAqD,kBAAmB,EAEnBrD,KAAAsD,kBAAmB,EAGnBtD,KAAAuD,cAAgB,EAEhBvD,KAAAwD,cAAgB,EAEhBxD,KAAAyD,WAAa,EAEbzD,KAAA0D,YAAc,OAGX1D,KAAA2D,aAAe,IAAIhE,EAAAgB,aAAa,GAEhCX,KAAA4D,aAAe,IAAIjE,EAAAgB,aAAa,GAYnCX,KAAA6D,wBAA0B,IAAIjE,EAAAkE,WAK9B9D,KAAA+D,uBAAyB,IAAInE,EAAAkE,WAK7B9D,KAAAgE,wBAA0B,IAAIpE,EAAAkE,WAK9B9D,KAAAiE,sBAAwB,IAAIrE,EAAAkE,WAK5B9D,KAAAkE,yBAA2B,IAAItE,EAAAkE,WAK/B9D,KAAAmE,yBAA2B,IAAIvE,EAAAkE,WAK/B9D,KAAAoE,kBAAoB,IAAIxE,EAAAkE,WAKxB9D,KAAAqE,sBAAwB,IAAIzE,EAAAkE,WA6vCvC,OAvyCIzF,OAAAC,eAAWyB,EAAAR,UAAA,gBAAX,WACI,OAAOS,KAAKsE,gDA4ChBjG,OAAAC,eAAWyB,EAAAR,UAAA,kBAAX,WACI,OAAOS,KAAKuE,iBAGhB,SAAsBC,GAClBxE,KAAKuE,YAAcC,mCAIvBnG,OAAAC,eAAWyB,EAAAR,UAAA,aAAX,WACI,OAAOS,KAAKC,YAGhB,SAAiBrB,GACToB,KAAKC,SAAWrB,IAGpBoB,KAAKE,WAAY,EACjBF,KAAKC,OAASrB,EACdoB,KAAKyE,iDAMTpG,OAAAC,eAAWyB,EAAAR,UAAA,cAAX,WACI,OAAOS,KAAK+B,aAGhB,SAAkBnD,GACVoB,KAAK+B,UAAYnD,IAIrBoB,KAAK+B,QAAUnD,EACfoB,KAAKyE,eACLzE,KAAK0E,uDAMTrG,OAAAC,eAAWyB,EAAAR,UAAA,cAAX,WACI,OAAOS,KAAKgC,aAGhB,SAAkBpD,GACVoB,KAAKgC,UAAYpD,IAIrBoB,KAAKgC,QAAUpD,EACfoB,KAAKyE,eACLzE,KAAK0E,uDAMTrG,OAAAC,eAAWyB,EAAAR,UAAA,gBAAX,WACI,OAAOS,KAAKiC,eAGhB,SAAoBrD,GACZoB,KAAKiC,YAAcrD,IAIvBoB,KAAKiC,UAAYrD,EACjBoB,KAAKyE,eACLzE,KAAK0E,uDAMTrG,OAAAC,eAAWyB,EAAAR,UAAA,wBAAX,WACI,OAAOS,KAAKmC,uBAGhB,SAA4BvD,GACpBoB,KAAKmC,oBAAsBvD,IAI/BoB,KAAKmC,kBAAoBvD,EACzBoB,KAAKyE,eACLzE,KAAK0E,uDAMTrG,OAAAC,eAAWyB,EAAAR,UAAA,wBAAX,WACI,OAAOS,KAAKkC,uBAGhB,SAA4BtD,GACpBoB,KAAKkC,oBAAsBtD,IAI/BoB,KAAKkC,kBAAoBtD,EACzBoB,KAAKyE,eACLzE,KAAK0E,uDAOTrG,OAAAC,eAAWyB,EAAAR,UAAA,2BAAX,WACI,OAAOS,KAAKkB,0BAGhB,SAA+BtC,GACvBoB,KAAKkB,uBAAyBtC,IAIlCoB,KAAKkB,qBAAuBtC,EAC5BoB,KAAKyE,iDAOTpG,OAAAC,eAAWyB,EAAAR,UAAA,yBAAX,WACI,OAAOS,KAAKoB,wBAGhB,SAA6BxC,GACrBoB,KAAKoB,qBAAuBxC,IAIhCoB,KAAKoB,mBAAqBxC,EAC1BoB,KAAKyE,iDAOTpG,OAAAC,eAAWyB,EAAAR,UAAA,aAAX,WACI,OAAOS,KAAKa,OAAO8D,SAAS3E,KAAK4E,YAWrC,SAAiBhG,GACToB,KAAKa,OAAO8D,SAAS3E,KAAK4E,SAAWhG,GAIrCoB,KAAKa,OAAOgE,WAAWjG,IACvBoB,KAAKyE,gDAVbpG,OAAAC,eAAWyB,EAAAR,UAAA,qBAAX,WACI,OAAOS,KAAKa,OAAOiE,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBuD,wCAiB7E1G,OAAAC,eAAWyB,EAAAR,UAAA,cAAX,WACI,OAAOS,KAAKe,QAAQ4D,SAAS3E,KAAK4E,YAWtC,SAAkBhG,GACVoB,KAAKe,QAAQ4D,SAAS3E,KAAK4E,SAAWhG,GAItCoB,KAAKe,QAAQ8D,WAAWjG,IACxBoB,KAAKyE,gDAVbpG,OAAAC,eAAWyB,EAAAR,UAAA,sBAAX,WACI,OAAOS,KAAKe,QAAQ+D,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBwD,yCAc9E3G,OAAAC,eAAWyB,EAAAR,UAAA,kBAAX,WACI,OAAOS,KAAKO,iBAGhB,SAAsB3B,GACdoB,KAAKO,cAAgB3B,IAIzBoB,KAAKO,YAAc3B,EACnBoB,KAAKiF,oDAIT5G,OAAAC,eAAWyB,EAAAR,UAAA,iBAAX,WACI,OAAOS,KAAKQ,gBAGhB,SAAqB5B,GACboB,KAAKQ,aAAe5B,IAIxBoB,KAAKQ,WAAa5B,EAClBoB,KAAKiF,oDAIT5G,OAAAC,eAAWyB,EAAAR,UAAA,kBAAX,WACI,OAAOS,KAAKS,iBAGhB,SAAsB7B,GACdoB,KAAKS,cAAgB7B,IAIzBoB,KAAKS,YAAc7B,EACnBoB,KAAKiF,oDAOT5G,OAAAC,eAAWyB,EAAAR,UAAA,aAAX,WACI,OAAOS,KAAKiB,YAGhB,SAAiBrC,GAAjB,IAAAsG,EAAAlF,KACQA,KAAKiB,SACLjB,KAAKiB,OAAOkE,oBAAoBC,OAAOpF,KAAKqF,gBAC5CrF,KAAKqF,eAAiB,MAG1BrF,KAAKiB,OAASrC,EAEVoB,KAAKiB,SACLjB,KAAKqF,eAAiBrF,KAAKiB,OAAOkE,oBAAoBG,IAAI,WACtDJ,EAAKT,eACLS,EAAKD,qBAIbjF,KAAKyE,eACLzE,KAAKiF,mDAIT5G,OAAAC,eAAWyB,EAAAR,UAAA,+BAAX,WACI,OAAOS,KAAKU,UAAU6E,8CAI1BlH,OAAAC,eAAWyB,EAAAR,UAAA,wBAAX,WACI,IAAIiG,EAAgBxF,KAAKiB,OAASjB,KAAKiB,OAAOP,UAAYV,KAAKU,UAE/D,OAAI8E,EAAcC,QACPD,EAAcE,SAAS1F,KAAK4E,OAGhCY,EAAcV,gBAAgB9E,KAAK4E,MAAO5E,KAAKuB,mBAAmByD,QAAUhF,KAAKwB,qBAAqBwD,yCAIjH3G,OAAAC,eAAWyB,EAAAR,UAAA,gBAAX,WACI,OAAOS,KAAKU,UAAUiE,SAAS3E,KAAK4E,YAGxC,SAAoBhG,GACZoB,KAAKU,UAAUiE,SAAS3E,KAAK4E,SAAWhG,GAIxCoB,KAAKU,UAAUmE,WAAWjG,KAC1BoB,KAAKyE,eACLzE,KAAKiF,oDAKb5G,OAAAC,eAAWyB,EAAAR,UAAA,aAAX,WACI,OAAOS,KAAKgB,YAGhB,SAAiBpC,GACToB,KAAKgB,SAAWpC,IAIpBoB,KAAKgB,OAASpC,EACdoB,KAAKyE,iDAITpG,OAAAC,eAAWyB,EAAAR,UAAA,cAAX,WACI,OAAOS,KAAKG,aAGhB,SAAkBvB,GACVoB,KAAK2F,SAAW/G,IAIpBoB,KAAKG,QAAUvB,EAEXoB,KAAK4F,OACL5F,KAAK4F,MAAMC,gBAAgB7F,wCAKnC3B,OAAAC,eAAWyB,EAAAR,UAAA,qBAAX,WACI,OAAOS,KAAKkD,kBAGhB,SAAyBtE,GACjBoB,KAAKkD,eAAiBtE,IAI1BoB,KAAKkD,aAAetE,EACpBoB,KAAKyE,iDAITpG,OAAAC,eAAWyB,EAAAR,UAAA,iBAAX,WACI,OAAOS,KAAK6C,gBAGhB,SAAqBjE,GACboB,KAAK6C,aAAejE,IAIxBoB,KAAK6C,WAAajE,EAClBoB,KAAKyE,iDAITpG,OAAAC,eAAWyB,EAAAR,UAAA,eAAX,WACI,OAAOS,KAAKsB,0CAOhBjD,OAAAC,eAAWyB,EAAAR,UAAA,mBAAX,WACI,OAAOS,KAAKyB,aAAakD,SAAS3E,KAAK4E,YAW3C,SAAuBhG,GACfoB,KAAKyB,aAAaoD,WAAWjG,IAC7BoB,KAAKyE,gDANbpG,OAAAC,eAAWyB,EAAAR,UAAA,2BAAX,WACI,OAAOS,KAAKyB,aAAaqD,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBuD,wCAanF1G,OAAAC,eAAWyB,EAAAR,UAAA,oBAAX,WACI,OAAOS,KAAK0B,cAAciD,SAAS3E,KAAK4E,YAW5C,SAAwBhG,GAChBoB,KAAK0B,cAAcmD,WAAWjG,IAC9BoB,KAAKyE,gDANbpG,OAAAC,eAAWyB,EAAAR,UAAA,4BAAX,WACI,OAAOS,KAAK0B,cAAcoD,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBuD,wCAapF1G,OAAAC,eAAWyB,EAAAR,UAAA,kBAAX,WACI,OAAOS,KAAK2B,YAAYgD,SAAS3E,KAAK4E,YAW1C,SAAsBhG,GACdoB,KAAK2B,YAAYkD,WAAWjG,IAC5BoB,KAAKyE,gDANbpG,OAAAC,eAAWyB,EAAAR,UAAA,0BAAX,WACI,OAAOS,KAAK2B,YAAYmD,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBwD,yCAalF3G,OAAAC,eAAWyB,EAAAR,UAAA,qBAAX,WACI,OAAOS,KAAK4B,eAAe+C,SAAS3E,KAAK4E,YAW7C,SAAyBhG,GACjBoB,KAAK4B,eAAeiD,WAAWjG,IAC/BoB,KAAKyE,gDANbpG,OAAAC,eAAWyB,EAAAR,UAAA,6BAAX,WACI,OAAOS,KAAK4B,eAAekD,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBwD,yCAarF3G,OAAAC,eAAWyB,EAAAR,UAAA,YAAX,WACI,OAAOS,KAAK6B,MAAM8C,SAAS3E,KAAK4E,YAWpC,SAAgBhG,GACRoB,KAAK6B,MAAMgD,WAAWjG,IACtBoB,KAAKyE,gDANbpG,OAAAC,eAAWyB,EAAAR,UAAA,oBAAX,WACI,OAAOS,KAAK6B,MAAMiD,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBuD,wCAa5E1G,OAAAC,eAAWyB,EAAAR,UAAA,WAAX,WACI,OAAOS,KAAK8B,KAAK6C,SAAS3E,KAAK4E,YAWnC,SAAehG,GACPoB,KAAK8B,KAAK+C,WAAWjG,IACrBoB,KAAKyE,gDANbpG,OAAAC,eAAWyB,EAAAR,UAAA,mBAAX,WACI,OAAOS,KAAK8B,KAAKgD,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBwD,yCAa3E3G,OAAAC,eAAWyB,EAAAR,UAAA,mBAAX,WACI,OAAOS,KAAK2D,aAAagB,SAAS3E,KAAK4E,YAW3C,SAAuBhG,GACfoB,KAAK2D,aAAakB,WAAWjG,IAC7BoB,KAAKyE,gDANbpG,OAAAC,eAAWyB,EAAAR,UAAA,2BAAX,WACI,OAAOS,KAAK2D,aAAamB,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBuD,wCAanF1G,OAAAC,eAAWyB,EAAAR,UAAA,mBAAX,WACI,OAAOS,KAAK4D,aAAae,SAAS3E,KAAK4E,YAW3C,SAAuBhG,GACfoB,KAAK4D,aAAaiB,WAAWjG,IAC7BoB,KAAKyE,gDANbpG,OAAAC,eAAWyB,EAAAR,UAAA,2BAAX,WACI,OAAOS,KAAK4D,aAAakB,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBwD,yCAUnF3G,OAAAC,eAAWyB,EAAAR,UAAA,eAAX,WACI,OAAOS,KAAKI,gBAAgB0F,KAAO9F,KAAKI,gBAAgB2E,MAAQ,mCAIpE1G,OAAAC,eAAWyB,EAAAR,UAAA,eAAX,WACI,OAAOS,KAAKI,gBAAgB2F,IAAM/F,KAAKI,gBAAgB4E,OAAS,mCAe1DjF,EAAAR,UAAA+E,aAAV,WACI,MAAO,WAIJvE,EAAAR,UAAA0F,gBAAP,WACIjF,KAAK8C,UAAW,EAChB9C,KAAKyE,gBAQF1E,EAAAR,UAAAyG,oBAAP,SAA2BC,GACvB,IAAIC,EAAStG,EAAA6C,QAAQC,OAIrB,OAFA1C,KAAKmG,yBAAyBF,EAAmBC,GAE1CA,GASJnG,EAAAR,UAAA4G,yBAAP,SAAgCF,EAA4BC,GAGxD,OAFAA,EAAOE,EAAIH,EAAkBG,EAAIpG,KAAKI,gBAAgB0F,KACtDI,EAAOG,EAAIJ,EAAkBI,EAAIrG,KAAKI,gBAAgB2F,IAC/C/F,MAQJD,EAAAR,UAAA+G,0BAAP,SAAiCL,GAC7B,IAAIC,EAAStG,EAAA6C,QAAQC,OAKrB,OAHAwD,EAAOE,EAAIH,EAAkBG,EAAIpG,KAAKwB,qBAAqBsE,KAC3DI,EAAOG,EAAIJ,EAAkBI,EAAIrG,KAAKwB,qBAAqBuE,IAEpDG,GAQJnG,EAAAR,UAAAgH,cAAP,SAAqBC,EAAmBC,GACpC,GAAKzG,KAAK4E,OAAS5E,KAAK4F,QAAU5F,KAAK4E,MAAM8B,eAA7C,CAKA1G,KAAK2G,oBAAsB5G,EAAQ6G,0BACnC5G,KAAK6G,kBAAoB9G,EAAQ+G,uBAEjC,IAAIC,EAAiB/G,KAAK4E,MAAMoC,mBAAmBP,GAC/CQ,EAAoBrH,EAAAsH,QAAQC,QAAQX,EAAU5G,EAAAwH,OAAO9E,WAAYmE,EAAMY,qBAAsBN,GAEjG/G,KAAKsH,yBAAyBL,GAE1BA,EAAkBM,EAAI,GAAKN,EAAkBM,EAAI,EACjDvH,KAAKwH,eAAgB,EAGzBxH,KAAKwH,eAAgB,OAhBjB5H,EAAA6H,MAAMC,MAAM,2EAwBb3H,EAAAR,UAAAoI,aAAP,SAAoBC,GAChB,IAAK5H,KAAK4E,OAAS5E,KAAK4F,OAAS5F,KAAK4F,QAAU5F,KAAK4E,MAAM8B,eACnDkB,GACAhI,EAAA6H,MAAMC,MAAM,2EAFpB,CAOA,IAAIG,EAAQ7H,KAAK4E,MAAMkD,gBAAgBC,QAAQ/H,MAC/C,IAAe,IAAX6H,EAKA,OAJA7H,KAAKgI,YAAcJ,OACdA,GACD5H,KAAK4E,MAAMkD,gBAAgBG,OAAOJ,EAAO,IAGrCD,IAIZ5H,KAAK2G,oBAAsB5G,EAAQ6G,0BACnC5G,KAAK6G,kBAAoB9G,EAAQ+G,uBACjC9G,KAAKgI,YAAcJ,EACnB5H,KAAK2C,iBAAkD,IAA/B3C,KAAKI,gBAAgB2E,OAA+C,IAAhC/E,KAAKI,gBAAgB4E,OACjFhF,KAAK4E,MAAMkD,gBAAgBI,KAAKlI,SAI7BD,EAAAR,UAAA+H,yBAAP,SAAgCL,GAC5B,IAAIkB,EAAUnI,KAAK6B,MAAM6D,SAAS1F,KAAK4E,OACnCwD,EAASpI,KAAK8B,KAAK4D,SAAS1F,KAAK4E,OAEjCyD,EAAYpB,EAAkBb,EAAIpG,KAAK2D,aAAa+B,SAAS1F,KAAK4E,OAAU5E,KAAKI,gBAAgB2E,MAAQ,EACzGuD,EAAWrB,EAAkBZ,EAAIrG,KAAK4D,aAAa8B,SAAS1F,KAAK4E,OAAU5E,KAAKI,gBAAgB4E,OAAS,EAEzGhF,KAAK6B,MAAM0G,uBAAyBvI,KAAK8B,KAAKyG,wBAC1CC,KAAKC,IAAIJ,EAAUF,GAAW,KAC9BE,EAAUF,GAGVK,KAAKC,IAAIH,EAASF,GAAU,KAC5BE,EAASF,IAIjBpI,KAAK8F,KAAOuC,EAAU,KACtBrI,KAAK+F,IAAMuC,EAAS,KAEpBtI,KAAK6B,MAAM0G,uBAAwB,EACnCvI,KAAK8B,KAAKyG,uBAAwB,GAI/BxI,EAAAR,UAAAmF,mBAAP,WACI1E,KAAK4C,gBAAiB,EACtB5C,KAAKyE,gBAIF1E,EAAAR,UAAAkF,aAAP,WACIzE,KAAKsB,UAAW,EAEXtB,KAAK4E,OAGV5E,KAAK4E,MAAM8D,eAIR3I,EAAAR,UAAAoJ,gBAAP,WACI3I,KAAKyE,eAEDzE,KAAK4I,OACL5I,KAAK6I,gBAKN9I,EAAAR,UAAAuJ,MAAP,SAAa/L,EAA2BgM,GACpC/I,KAAK4F,MAAQ7I,EACbiD,KAAK4E,MAAQmE,GAIPhJ,EAAAR,UAAAyJ,WAAV,SAAqBC,GACjB,GAAKjJ,KAAK4C,gBAAmC,IAAjB5C,KAAK+B,SAAkC,IAAjB/B,KAAKgC,SAAoC,IAAnBhC,KAAKiC,UAA7E,CAKA,IAAIiH,EAAUlJ,KAAKI,gBAAgB2E,MAAQ/E,KAAKkC,kBAAoBlC,KAAKI,gBAAgB0F,KACrFqD,EAAUnJ,KAAKI,gBAAgB4E,OAAShF,KAAKmC,kBAAoBnC,KAAKI,gBAAgB2F,IAC1FkD,EAAQG,UAAUF,EAASC,GAG3BF,EAAQI,OAAOrJ,KAAKiC,WAGpBgH,EAAQK,MAAMtJ,KAAK+B,QAAS/B,KAAKgC,SAGjCiH,EAAQG,WAAWF,GAAUC,IAGzBnJ,KAAK4C,gBAAkB5C,KAAKuJ,iBAAmBL,GAAWlJ,KAAKwJ,iBAAmBL,KAClFnJ,KAAKuJ,eAAiBL,EACtBlJ,KAAKwJ,eAAiBL,EACtBnJ,KAAK4C,gBAAiB,EAEtB9C,EAAAuC,SAASoH,cAAcP,GAAUC,EAASnJ,KAAKiC,UAAWjC,KAAK+B,QAAS/B,KAAKgC,QAAShC,KAAK4F,MAAQ5F,KAAK4F,MAAMxD,iBAAmB,KAAMpC,KAAKoC,kBAE5IpC,KAAKoC,iBAAiBsH,YAAY1J,KAAKuC,2BAKrCxC,EAAAR,UAAAoK,aAAV,SAAuBV,GACfjJ,KAAK8C,WACL9C,KAAK6I,eACL7I,KAAK8C,UAAW,GAGhB9C,KAAK4I,QACLK,EAAQW,KAAO5J,KAAK4I,OAGpB5I,KAAKgB,SACLiI,EAAQY,UAAY7J,KAAKgB,QAGzBhB,KAAKE,YACL+I,EAAQa,YAAc9J,KAAKC,SAKzBF,EAAAR,UAAAwK,iBAAV,SAA2BC,EAAwBf,GA2B/C,OA1BIjJ,KAAKsB,UAAatB,KAAKwB,qBAAqByI,WAAWD,KACvDhK,KAAKsB,UAAW,EAChBtB,KAAKI,gBAAgB8J,SAASF,GAG9BhK,KAAKmK,YAAYH,EAAef,GAEhCjJ,KAAKoK,WACLpK,KAAKqK,kBAAkBL,EAAef,GAGtCjJ,KAAKI,gBAAgB0F,KAAmC,EAA5B9F,KAAKI,gBAAgB0F,KACjD9F,KAAKI,gBAAgB2F,IAAiC,EAA3B/F,KAAKI,gBAAgB2F,IAChD/F,KAAKI,gBAAgB2E,MAAqC,EAA7B/E,KAAKI,gBAAgB2E,MAClD/E,KAAKI,gBAAgB4E,OAAuC,EAA9BhF,KAAKI,gBAAgB4E,OAGnDhF,KAAKsK,sBAAsBN,EAAef,GAE1CjJ,KAAKwB,qBAAqB0I,SAASF,GAE/BhK,KAAKoE,kBAAkBmG,gBACvBvK,KAAKoE,kBAAkBoG,gBAAgBxK,SAI3CA,KAAKI,gBAAgB0F,KAAOkE,EAAclE,KAAOkE,EAAcjF,WAI/D/E,KAAKI,gBAAgB0F,KAAO9F,KAAKI,gBAAgB2E,MAAQiF,EAAclE,UAIvE9F,KAAKI,gBAAgB2F,IAAMiE,EAAcjE,IAAMiE,EAAchF,YAI7DhF,KAAKI,gBAAgB2F,IAAM/F,KAAKI,gBAAgB4E,OAASgF,EAAcjE,OAK3E/F,KAAKgJ,WAAWC,GAEZjJ,KAAK2C,kBACL3C,KAAK2C,kBAAmB,GACjB,IAIX3C,KAAKyK,MAAMxB,GACXA,EAAQyB,QAED,QAID3K,EAAAR,UAAAkL,MAAV,SAAgBxB,GAGZ,GAFAA,EAAQ0B,YAEJ3K,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,cAAe,CAC7D,IAAID,EAAgBvD,KAAKuD,cACrBC,EAAgBxD,KAAKwD,cACrBC,EAAazD,KAAKyD,WAElBmH,EAAmBpC,KAAKqC,IAAIrC,KAAKqC,IAAItH,EAAe,GAAkB,EAAbE,EAAgB,GACzEqH,EAAoBtC,KAAKuC,IAAIvC,KAAKuC,IAAIxH,EAAe,GAAkB,EAAbE,EAAgB,GAC1EuH,EAAkBxC,KAAKqC,IAAIrC,KAAKqC,IAAIrH,EAAe,GAAkB,EAAbC,EAAgB,GACxEwH,EAAqBzC,KAAKuC,IAAIvC,KAAKuC,IAAIvH,EAAe,GAAkB,EAAbC,EAAgB,GAE/EwF,EAAQiC,KAAKlL,KAAKI,gBAAgB0F,KAAO8E,EACrC5K,KAAKI,gBAAgB2F,IAAMiF,EAC3BhL,KAAKI,gBAAgB2E,MAAQ+F,EAAoBF,EACjD5K,KAAKI,gBAAgB4E,OAASiG,EAAqBD,QAEvD/B,EAAQiC,KAAKlL,KAAKI,gBAAgB0F,KAAM9F,KAAKI,gBAAgB2F,IAAK/F,KAAKI,gBAAgB2E,MAAO/E,KAAKI,gBAAgB4E,SAKpHjF,EAAAR,UAAA6K,SAAP,WAEQpK,KAAKa,OAAO4E,QACZzF,KAAKI,gBAAgB2E,MAAQ/E,KAAKa,OAAO6E,SAAS1F,KAAK4E,OAEvD5E,KAAKI,gBAAgB2E,OAAS/E,KAAKa,OAAO6E,SAAS1F,KAAK4E,OAGxD5E,KAAKe,QAAQ0E,QACbzF,KAAKI,gBAAgB4E,OAAShF,KAAKe,QAAQ2E,SAAS1F,KAAK4E,OAEzD5E,KAAKI,gBAAgB4E,QAAUhF,KAAKe,QAAQ2E,SAAS1F,KAAK4E,QAKxD7E,EAAAR,UAAA8K,kBAAV,SAA4BL,EAAwBf,GAChD,IAAIlE,EAAQ/E,KAAKI,gBAAgB2E,MAC7BC,EAAShF,KAAKI,gBAAgB4E,OAE9BmG,EAAcnB,EAAcjF,MAC5BqG,EAAepB,EAAchF,OAG7BoB,EAAI,EACJC,EAAI,EAER,OAAQrG,KAAK2G,qBACT,KAAK5G,EAAQ6G,0BACTR,EAAI,EACJ,MACJ,KAAKrG,EAAQsL,2BACTjF,EAAI+E,EAAcpG,EAClB,MACJ,KAAKhF,EAAQoB,4BACTiF,GAAK+E,EAAcpG,GAAS,EAIpC,OAAQ/E,KAAK6G,mBACT,KAAK9G,EAAQ+G,uBACTT,EAAI,EACJ,MACJ,KAAKtG,EAAQuL,0BACTjF,EAAI+E,EAAepG,EACnB,MACJ,KAAKjF,EAAQsB,0BACTgF,GAAK+E,EAAepG,GAAU,EAIlChF,KAAKyB,aAAagE,SAClBzF,KAAKI,gBAAgB0F,MAAQ9F,KAAKyB,aAAaiE,SAAS1F,KAAK4E,OAC7D5E,KAAKI,gBAAgB2E,OAAS/E,KAAKyB,aAAaiE,SAAS1F,KAAK4E,SAE9D5E,KAAKI,gBAAgB0F,MAAQqF,EAAcnL,KAAKyB,aAAaiE,SAAS1F,KAAK4E,OAC3E5E,KAAKI,gBAAgB2E,OAASoG,EAAcnL,KAAKyB,aAAaiE,SAAS1F,KAAK4E,QAG5E5E,KAAK0B,cAAc+D,QACnBzF,KAAKI,gBAAgB2E,OAAS/E,KAAK0B,cAAcgE,SAAS1F,KAAK4E,OAE/D5E,KAAKI,gBAAgB2E,OAASoG,EAAcnL,KAAK0B,cAAcgE,SAAS1F,KAAK4E,OAG7E5E,KAAK2B,YAAY8D,SACjBzF,KAAKI,gBAAgB2F,KAAO/F,KAAK2B,YAAY+D,SAAS1F,KAAK4E,OAC3D5E,KAAKI,gBAAgB4E,QAAUhF,KAAK2B,YAAY+D,SAAS1F,KAAK4E,SAE9D5E,KAAKI,gBAAgB2F,KAAOqF,EAAepL,KAAK2B,YAAY+D,SAAS1F,KAAK4E,OAC1E5E,KAAKI,gBAAgB4E,QAAUoG,EAAepL,KAAK2B,YAAY+D,SAAS1F,KAAK4E,QAG7E5E,KAAK4B,eAAe6D,QACpBzF,KAAKI,gBAAgB4E,QAAUhF,KAAK4B,eAAe8D,SAAS1F,KAAK4E,OAEjE5E,KAAKI,gBAAgB4E,QAAUoG,EAAepL,KAAK4B,eAAe8D,SAAS1F,KAAK4E,OAGhF5E,KAAK6B,MAAM4D,QACXzF,KAAKI,gBAAgB0F,MAAQ9F,KAAK6B,MAAM6D,SAAS1F,KAAK4E,OAEtD5E,KAAKI,gBAAgB0F,MAAQqF,EAAcnL,KAAK6B,MAAM6D,SAAS1F,KAAK4E,OAGpE5E,KAAK8B,KAAK2D,QACVzF,KAAKI,gBAAgB2F,KAAO/F,KAAK8B,KAAK4D,SAAS1F,KAAK4E,OAEpD5E,KAAKI,gBAAgB2F,KAAOqF,EAAepL,KAAK8B,KAAK4D,SAAS1F,KAAK4E,OAGvE5E,KAAKI,gBAAgB0F,MAAQM,EAC7BpG,KAAKI,gBAAgB2F,KAAOM,GAItBtG,EAAAR,UAAA4K,YAAV,SAAsBH,EAAwBf,KAKpClJ,EAAAR,UAAA+K,sBAAV,SAAgCN,EAAwBf,KAKjDlJ,EAAAR,UAAAgM,MAAP,SAAavB,EAAwBf,KAU9BlJ,EAAAR,UAAAiM,SAAP,SAAgBpF,EAAWC,GAQvB,OANArG,KAAKuC,uBAAuBkJ,qBAAqBrF,EAAGC,EAAGrG,KAAKwC,sBAE5D4D,EAAIpG,KAAKwC,qBAAqB4D,EAC9BC,EAAIrG,KAAKwC,qBAAqB6D,IAG1BD,EAAIpG,KAAKI,gBAAgB0F,UAIzBM,EAAIpG,KAAKI,gBAAgB0F,KAAO9F,KAAKI,gBAAgB2E,WAIrDsB,EAAIrG,KAAKI,gBAAgB2F,SAIzBM,EAAIrG,KAAKI,gBAAgB2F,IAAM/F,KAAKI,gBAAgB4E,UAIpDhF,KAAKqD,mBACLrD,KAAK4E,MAAM8G,qBAAsB,IAE9B,OAIJ3L,EAAAR,UAAAoM,gBAAP,SAAuBvF,EAAWC,EAAWuF,EAAcC,EAAmBC,GAC1E,SAAK9L,KAAKoD,mBAAqBpD,KAAK+L,WAAa/L,KAAKkD,kBAIjDlD,KAAKwL,SAASpF,EAAGC,KAItBrG,KAAKgM,oBAAoBJ,EAAMxF,EAAGC,EAAGwF,EAAWC,IAEzC,KAIJ/L,EAAAR,UAAA0M,eAAP,SAAsBC,EAAiBC,GACVnM,KAAK6D,wBAAwB2G,gBAAgB2B,GAAc,EAAGD,EAAQlM,OAE/D,MAAfA,KAAKoM,QAAgBpM,KAAKoM,OAAOH,eAAeC,EAAQC,IAItEpM,EAAAR,UAAA8M,gBAAP,SAAuBH,GACnB,QAAIlM,KAAKiD,YAAc,MAIG,IAAtBjD,KAAKiD,cACLjD,KAAKiD,YAAc,GAEvBjD,KAAKiD,cAEoBjD,KAAKmE,yBAAyBqG,gBAAgBxK,MAAO,EAAGkM,EAAQlM,OAEzD,MAAfA,KAAKoM,QAAgBpM,KAAKoM,OAAOC,gBAAgBH,IAE3D,IAIJnM,EAAAR,UAAA+M,cAAP,SAAqBJ,GACjBlM,KAAKiD,YAAc,EAEMjD,KAAK+D,uBAAuByG,gBAAgBxK,MAAO,EAAGkM,EAAQlM,OAEvD,MAAfA,KAAKoM,QAAgBpM,KAAKoM,OAAOE,cAAcJ,IAI7DnM,EAAAR,UAAAgN,eAAP,SAAsBL,EAAiBC,EAAsBN,EAAmBC,GAC5E,OAAwB,IAApB9L,KAAKgD,aAIThD,KAAKgD,aAELhD,KAAKmD,gBAAgB0I,IAAa,EAET7L,KAAKgE,wBAAwBwG,gBAAgB,IAAI1K,EAAA0M,gBAAgBL,EAAaL,IAAe,EAAGI,EAAQlM,OAEjG,MAAfA,KAAKoM,QAAgBpM,KAAKoM,OAAOG,eAAeL,EAAQC,EAAaN,EAAWC,IAE1F,IAIJ/L,EAAAR,UAAAkN,aAAP,SAAoBP,EAAiBC,EAAsBN,EAAmBC,EAAqBY,GAC/F1M,KAAKgD,WAAa,SAEXhD,KAAKmD,gBAAgB0I,GAE5B,IAAIc,EAA0BD,EAC1BA,IAAgB1M,KAAKiD,YAAc,IAA2B,IAAtBjD,KAAKiD,eAC7C0J,EAAiB3M,KAAKkE,yBAAyBsG,gBAAgB,IAAI1K,EAAA0M,gBAAgBL,EAAaL,IAAe,EAAGI,EAAQlM,OAErGA,KAAKiE,sBAAsBuG,gBAAgB,IAAI1K,EAAA0M,gBAAgBL,EAAaL,IAAe,EAAGI,EAAQlM,OAE/F,MAAfA,KAAKoM,QAAgBpM,KAAKoM,OAAOK,aAAaP,EAAQC,EAAaN,EAAWC,EAAaa,IAIzG5M,EAAAR,UAAAqN,gBAAP,SAAuBf,GACnB,QADmB,IAAAA,MAAA,MACD,OAAdA,EACA7L,KAAKyM,aAAazM,KAAMJ,EAAA6C,QAAQC,OAAQmJ,EAAW,GAAG,QAEtD,IAAK,IAAI3M,KAAOc,KAAKmD,gBACjBnD,KAAKyM,aAAazM,KAAMJ,EAAA6C,QAAQC,QAASxD,EAAe,GAAG,IAMhEa,EAAAR,UAAAyM,oBAAP,SAA2BJ,EAAcxF,EAAWC,EAAWwF,EAAmBC,GAE9E,GADA9L,KAAK+C,cAAc8J,eAAezG,EAAGC,GACjCuF,IAAShM,EAAAkN,kBAAkBC,YAAa,CACxC/M,KAAKiM,eAAejM,KAAMA,KAAK+C,eAE/B,IAAIiK,EAAsBhN,KAAK4E,MAAMqI,iBAAiBpB,GAUtD,OATImB,GAAuBA,IAAwBhN,MAC/CgN,EAAoBV,cAActM,MAGlCgN,IAAwBhN,MACxBA,KAAKqM,gBAAgBrM,MAGzBA,KAAK4E,MAAMqI,iBAAiBpB,GAAa7L,MAClC,EAGX,OAAI4L,IAAShM,EAAAkN,kBAAkBI,aAC3BlN,KAAKuM,eAAevM,KAAMA,KAAK+C,cAAe8I,EAAWC,GACzD9L,KAAK4E,MAAMuI,iBAAiBtB,GAAa7L,KACzCA,KAAK4E,MAAMwI,mBAAqBpN,MACzB,GAGP4L,IAAShM,EAAAkN,kBAAkBO,YACvBrN,KAAK4E,MAAMuI,iBAAiBtB,IAC5B7L,KAAK4E,MAAMuI,iBAAiBtB,GAAWY,aAAazM,KAAMA,KAAK+C,cAAe8I,EAAWC,GAAa,UAEnG9L,KAAK4E,MAAMuI,iBAAiBtB,IAC5B,IAMP9L,EAAAR,UAAAsJ,aAAR,YACS7I,KAAK4I,OAAU5I,KAAK8C,YAIrB9C,KAAKiB,OACLjB,KAAK4I,MAAQ5I,KAAKiB,OAAOqM,UAAY,IAAMtN,KAAKiB,OAAOsM,WAAa,IAAMvN,KAAKwN,iBAAmB,MAAQxN,KAAKiB,OAAOwM,WAEtHzN,KAAK4I,MAAQ5I,KAAKQ,WAAa,IAAMR,KAAKS,YAAc,IAAMT,KAAKwN,iBAAmB,MAAQxN,KAAKO,YAGvGP,KAAKuE,YAAcxE,EAAQ2N,eAAe1N,KAAK4I,SAI5C7I,EAAAR,UAAAoO,QAAP,WACI3N,KAAKoE,kBAAkBwJ,QACvB5N,KAAKqE,sBAAsBuJ,QAC3B5N,KAAKgE,wBAAwB4J,QAC7B5N,KAAKmE,yBAAyByJ,QAC9B5N,KAAK6D,wBAAwB+J,QAC7B5N,KAAK+D,uBAAuB6J,QAC5B5N,KAAKiE,sBAAsB2J,QAC3B5N,KAAKkE,yBAAyB0J,QAE1B5N,KAAKqF,gBAAkBrF,KAAKiB,SAC5BjB,KAAKiB,OAAOkE,oBAAoBC,OAAOpF,KAAKqF,gBAC5CrF,KAAKqF,eAAiB,MAGtBrF,KAAK4F,QACL5F,KAAK4F,MAAMiI,cAAc7N,MACzBA,KAAK4F,MAAQ,MAGL5F,KAAK4E,MAAMkD,gBAAgBC,QAAQ/H,OAClC,GACTA,KAAK2H,aAAa,OAc1BtJ,OAAAC,eAAkByB,EAAA,iCAAlB,WACI,OAAOA,EAAQ+N,4DAInBzP,OAAAC,eAAkByB,EAAA,kCAAlB,WACI,OAAOA,EAAQgO,6DAInB1P,OAAAC,eAAkByB,EAAA,mCAAlB,WACI,OAAOA,EAAQiO,8DAInB3P,OAAAC,eAAkByB,EAAA,8BAAlB,WACI,OAAOA,EAAQkO,yDAInB5P,OAAAC,eAAkByB,EAAA,iCAAlB,WACI,OAAOA,EAAQmO,4DAInB7P,OAAAC,eAAkByB,EAAA,iCAAlB,WACI,OAAOA,EAAQoO,4DAMLpO,EAAA2N,eAAd,SAA6B9D,GAEzB,GAAI7J,EAAQqO,iBAAiBxE,GACzB,OAAO7J,EAAQqO,iBAAiBxE,GAGpC,IAAIyE,EAAOC,SAASC,cAAc,QAClCF,EAAKG,UAAY,KACjBH,EAAKI,MAAM7E,KAAOA,EAElB,IAAI8E,EAAQJ,SAASC,cAAc,OACnCG,EAAMD,MAAME,QAAU,eACtBD,EAAMD,MAAM1J,MAAQ,MACpB2J,EAAMD,MAAMzJ,OAAS,MACrB0J,EAAMD,MAAMG,cAAgB,SAE5B,IAAIC,EAAMP,SAASC,cAAc,OACjCM,EAAIC,YAAYT,GAChBQ,EAAIC,YAAYJ,GAEhBJ,SAASS,KAAKD,YAAYD,GAE1B,IAAIG,EAAa,EACbC,EAAa,EACjB,IACIA,EAAaP,EAAMQ,wBAAwBnJ,IAAMsI,EAAKa,wBAAwBnJ,IAC9E2I,EAAMD,MAAMG,cAAgB,WAC5BI,EAAaN,EAAMQ,wBAAwBnJ,IAAMsI,EAAKa,wBAAwBnJ,YAE9EuI,SAASS,KAAKI,YAAYN,GAE9B,IAAI3I,GAAWkJ,OAAQJ,EAAYhK,OAAQiK,EAAYI,QAASJ,EAAaD,GAG7E,OAFAjP,EAAQqO,iBAAiBxE,GAAQ1D,EAE1BA,GAkBMnG,EAAAuP,YAAjB,SAA6BlJ,EAAWC,EAAWtB,EAAeC,EAAgBiE,GAC9EA,EAAQG,UAAUhD,EAAGC,GACrB4C,EAAQK,MAAMvE,EAAOC,GAErBiE,EAAQ0B,YACR1B,EAAQsG,IAAI,EAAG,EAAG,EAAG,EAAG,EAAI/G,KAAKgH,IACjCvG,EAAQwG,YAERxG,EAAQK,MAAM,EAAIvE,EAAO,EAAIC,GAC7BiE,EAAQG,WAAWhD,GAAIC,IAtGZtG,EAAA+N,2BAA6B,EAC7B/N,EAAAgO,4BAA8B,EAC9BhO,EAAAiO,6BAA+B,EAE/BjO,EAAAkO,wBAA0B,EAC1BlO,EAAAmO,2BAA6B,EAC7BnO,EAAAoO,2BAA6B,EAgC7BpO,EAAAqO,oBAoDDrO,EAAA2P,UAAuI,aAczJ3P,EAr4CA,GAAa9C,EAAA8C,yFCPb,IAAAY,EAAA,WAcI,SAAAA,EAAmB/B,EAER+Q,EAEAC,QAFA,IAAAD,MAAOhP,EAAaC,qBAEpB,IAAAgP,OAAA,GAFA5P,KAAA2P,OAEA3P,KAAA4P,uBAjBH5P,KAAA6P,OAAS,EAKV7P,KAAAuI,uBAAwB,EAa3BvI,KAAK6P,OAASjR,EA0ItB,OAtIIP,OAAAC,eAAWqC,EAAApB,UAAA,oBAAX,WACI,OAAOS,KAAK2P,OAAShP,EAAaG,qDAItCzC,OAAAC,eAAWqC,EAAApB,UAAA,eAAX,WACI,OAAOS,KAAK2P,OAAShP,EAAaC,gDAItCvC,OAAAC,eAAWqC,EAAApB,UAAA,qBAAX,WACI,OAAOS,KAAK6P,wCASTlP,EAAApB,UAAAuF,gBAAP,SAAuBiE,EAA8B+G,GACjD,OAAI9P,KAAKyF,QACEzF,KAAK0F,SAASqD,GAGlB/I,KAAK0F,SAASqD,GAAQ+G,GAQ1BnP,EAAApB,UAAAmG,SAAP,SAAgBqD,GACZ,GAAIA,IAAS/I,KAAKuI,uBAAyBvI,KAAK2P,OAAShP,EAAaG,oBAAqB,CACvF,IAAIiE,EAAgB,EAChBC,EAAiB,EAUrB,GARI+D,EAAKgH,aACLhL,EAAS/E,KAAK6P,OAAS9G,EAAKiH,UAAUjL,MAASgE,EAAKgH,YAGpDhH,EAAKkH,cACLjL,EAAUhF,KAAK6P,OAAS9G,EAAKiH,UAAUhL,OAAU+D,EAAKkH,aAGtDlH,EAAKmH,kBAAoBnH,EAAKgH,YAAchH,EAAKkH,YACjD,OAAO3S,OAAO6S,WAAa7S,OAAO8S,YAAcrL,EAAQC,EAG5D,GAAI+D,EAAKgH,WACL,OAAOhL,EAGX,GAAIgE,EAAKkH,YACL,OAAOjL,EAGf,OAAOhF,KAAK6P,QAQTlP,EAAApB,UAAAoF,SAAP,SAAgBoE,GACZ,OAAQ/I,KAAK2P,MACT,KAAKhP,EAAaG,oBACd,OAA8B,IAAtBd,KAAK0F,SAASqD,GAAe,IACzC,KAAKpI,EAAaC,eACd,OAAOZ,KAAK0F,SAASqD,GAAQ,KAGrC,OAAO/I,KAAK2P,KAAKhL,YAQdhE,EAAApB,UAAAsF,WAAP,SAAkBwL,GACd,IAAIC,EAAQ3P,EAAa4P,OAAOC,KAAKH,EAAO1L,YAE5C,IAAK2L,GAA0B,IAAjBA,EAAMG,OAChB,OAAO,EAGX,IAAIC,EAAcC,WAAWL,EAAM,IAC/BM,EAAa5Q,KAAK2P,KAQtB,GANK3P,KAAK4P,sBACFc,EAAc,IACdA,EAAc,GAID,IAAjBJ,EAAMG,OACN,OAAQH,EAAM,IACV,IAAK,KACDM,EAAajQ,EAAaC,eAC1B,MACJ,IAAK,IACDgQ,EAAajQ,EAAaG,oBAC1B4P,GAAe,IAK3B,OAAIA,IAAgB1Q,KAAK6P,QAAUe,IAAe5Q,KAAK2P,QAIvD3P,KAAK6P,OAASa,EACd1Q,KAAK2P,KAAOiB,GAEL,IASXvS,OAAAC,eAAkBqC,EAAA,2BAAlB,WACI,OAAOA,EAAakQ,sDAIxBxS,OAAAC,eAAkBqC,EAAA,sBAAlB,WACI,OAAOA,EAAamQ,iDAXTnQ,EAAA4P,OAAS,0BACT5P,EAAAkQ,qBAAuB,EACvBlQ,EAAAmQ,gBAAkB,EAWrCnQ,EA7JA,GAAa1D,EAAA0D,qaCLb,IAAAoQ,EAAAtT,EAAA,IACAmC,EAAAnC,EAAA,GAKAuT,EAAA,SAAAC,GAuCI,SAAAD,EAAY9S,GAAZ,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YAvCPkF,EAAAgM,cAAe,EAKbhM,EAAAiM,UAAY,IAAIC,QAmJ9B,OAzJiCC,EAAAL,EAAAC,GAW7B5S,OAAAC,eAAW0S,EAAAzR,UAAA,gBAAX,WACI,OAAOS,KAAKmR,2CAOhB9S,OAAAC,eAAW0S,EAAAzR,UAAA,mBAAX,WACI,OAAOS,KAAKkR,kBAGhB,SAAuBtS,GACfoB,KAAKkR,eAAiBtS,IAI1BoB,KAAKkR,aAAetS,EAEfoB,KAAKkR,cACNlR,KAAKsR,qDAgBNN,EAAAzR,UAAAgS,aAAP,WAEI,OADAvR,KAAKsR,mBACEtR,MAQJgR,EAAAzR,UAAAiS,gBAAP,SAAuBC,GACnB,OAA4C,IAArCzR,KAAKmR,UAAUpJ,QAAQ0J,IAQ3BT,EAAAzR,UAAAmS,WAAP,SAAkBD,GAGd,OAAe,IAFHzR,KAAKmR,UAAUpJ,QAAQ0J,GAGxBzR,MAEXyR,EAAQrF,OAASpM,KACjByR,EAAQ7M,MAAQ5E,KAAK4E,MAErB5E,KAAKmR,UAAUjJ,KAAKuJ,GAEhBzR,KAAK4E,MAAM+M,eACXF,EAAQG,aAAa5R,KAAK4E,MAAM+M,aAAaE,mBAEzCJ,EAAQK,OACRL,EAAQK,KAAK1F,OAASpM,KAAK8R,MAG1B9R,KAAK+R,aACN/R,KAAKsR,oBAINtR,OAODgR,EAAAzR,UAAA+R,iBAAV,aAGUN,EAAAzR,UAAAyS,YAAV,SAAsBvL,GAClB,OAAO,IAAI7G,EAAAqS,cAAc,gBAAiBxL,IAQvCuK,EAAAzR,UAAAsO,cAAP,SAAqB4D,GACjB,IAAI5J,EAAQ7H,KAAKmR,UAAUpJ,QAAQ0J,GASnC,OAPe,IAAX5J,IACA7H,KAAKmR,UAAUlJ,OAAOJ,EAAO,GAE7B4J,EAAQrF,OAAS,KACjBqF,EAAQS,gBAGLlS,MAGDgR,EAAAzR,UAAA+E,aAAV,WACI,MAAO,eAMJ0M,EAAAzR,UAAAoO,QAAP,WACI,IAAoB,IAAAwE,EAAA,EAAAC,EAAApS,KAAKmR,UAALgB,EAAAC,EAAA3B,OAAA0B,IAAgB,CAApBC,EAAAD,GACJxE,UAGZ3N,KAAKmR,aAELF,EAAA1R,UAAMoO,QAAO7P,KAAAkC,OAIMgR,EAAAqB,kBAAoB,EAGpBrB,EAAAsB,uBAAyB,EAGzBtB,EAAAuB,+BAAiC,EAGjCvB,EAAAwB,wBAA0B,EAG1BxB,EAAAyB,gCAAkC,EAE7DzB,EAzJA,CAAiCD,EAAA2B,WAApBzV,EAAA+T,oaCNb,IAAA2B,EAAAlV,EAAA,GACAoC,EAAApC,EAAA,GAQAmV,EAAA,SAAA3B,GAyEI,SAAA2B,EAAmB1U,GAAnB,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OAvETgH,EAAAiM,UAAY,IAAIC,MAEhBlM,EAAA2N,oBAAsBhT,EAAAQ,QAAQC,QAI9B4E,EAAA4N,uBAAwB,EAExB5N,EAAA6N,wBAAyB,IAgUvC,OA1U+B1B,EAAAuB,EAAA3B,GAa3B5S,OAAAC,eAAWsU,EAAArT,UAAA,6BAAX,WACI,OAAOS,KAAK+S,4BAGhB,SAAiCnU,GACzBoB,KAAK+S,yBAA2BnU,IAIpCoB,KAAK+S,uBAAyBnU,EAE1BA,IACAoB,KAAKgF,OAAS,QAGlBhF,KAAKyE,iDAITpG,OAAAC,eAAWsU,EAAArT,UAAA,4BAAX,WACI,OAAOS,KAAK8S,2BAGhB,SAAgClU,GACxBoB,KAAK8S,wBAA0BlU,IAInCoB,KAAK8S,sBAAwBlU,EAEzBA,IACAoB,KAAK+E,MAAQ,QAGjB/E,KAAKyE,iDAITpG,OAAAC,eAAWsU,EAAArT,UAAA,kBAAX,WACI,OAAOS,KAAKgT,iBAGhB,SAAsBpU,GACdoB,KAAKgT,cAAgBpU,IAIzBoB,KAAKgT,YAAcpU,EACnBoB,KAAKyE,iDAITpG,OAAAC,eAAWsU,EAAArT,UAAA,gBAAX,WACI,OAAOS,KAAKmR,2CAWNyB,EAAArT,UAAA+E,aAAV,WACI,MAAO,aAQJsO,EAAArT,UAAA0T,eAAP,SAAsB/U,GAClB,IAAkB,IAAAiU,EAAA,EAAAC,EAAApS,KAAKkT,SAALf,EAAAC,EAAA3B,OAAA0B,IAAe,CAA5B,IAAIgB,EAAKf,EAAAD,GACV,GAAIgB,EAAMjV,OAASA,EACf,OAAOiV,EAIf,OAAO,MASJP,EAAArT,UAAA6T,eAAP,SAAsBlV,EAAc0N,GAChC,IAAkB,IAAAuG,EAAA,EAAAC,EAAApS,KAAKkT,SAALf,EAAAC,EAAA3B,OAAA0B,IAAe,CAA5B,IAAIgB,EAAKf,EAAAD,GACV,GAAIgB,EAAME,WAAazH,EACnB,OAAOuH,EAIf,OAAO,MAQJP,EAAArT,UAAAiS,gBAAP,SAAuBC,GACnB,OAA2C,IAApCzR,KAAKkT,SAASnL,QAAQ0J,IAQ1BmB,EAAArT,UAAAmS,WAAP,SAAkBD,GACd,OAAKA,GAMU,IAFHzR,KAAKmR,UAAUpJ,QAAQ0J,GAGxBzR,MAEXyR,EAAQ3I,MAAM9I,KAAMA,KAAK4E,OAEzB6M,EAAQ9I,kBAER3I,KAAK6F,gBAAgB4L,GAErBzR,KAAKyE,eACEzE,MAfIA,MAuBR4S,EAAArT,UAAAsO,cAAP,SAAqB4D,GACjB,IAAI5J,EAAQ7H,KAAKmR,UAAUpJ,QAAQ0J,GAenC,OAbe,IAAX5J,IACA7H,KAAKmR,UAAUlJ,OAAOJ,EAAO,GAE7B4J,EAAQrF,OAAS,MAGrBqF,EAAQ9J,aAAa,MAEjB3H,KAAK4E,OACL5E,KAAK4E,MAAM0O,0BAA0B7B,GAGzCzR,KAAKyE,eACEzE,MAIJ4S,EAAArT,UAAAsG,gBAAP,SAAuB4L,GACnBzR,KAAK6N,cAAc4D,GAEnB,IAAK,IAAI5J,EAAQ,EAAGA,EAAQ7H,KAAKmR,UAAUV,OAAQ5I,IAC/C,GAAI7H,KAAKmR,UAAUtJ,GAAOlC,OAAS8L,EAAQ9L,OAEvC,YADA3F,KAAKmR,UAAUlJ,OAAOJ,EAAO,EAAG4J,GAKxCzR,KAAKmR,UAAUjJ,KAAKuJ,GAEpBA,EAAQrF,OAASpM,KAEjBA,KAAKyE,gBAIFmO,EAAArT,UAAAmF,mBAAP,WACIuM,EAAA1R,UAAMmF,mBAAkB5G,KAAAkC,MAExB,IAAK,IAAI6H,EAAQ,EAAGA,EAAQ7H,KAAKmR,UAAUV,OAAQ5I,IAC/C7H,KAAKmR,UAAUtJ,GAAOnD,sBAKvBkO,EAAArT,UAAAoJ,gBAAP,WACIsI,EAAA1R,UAAMoJ,gBAAe7K,KAAAkC,MAErB,IAAK,IAAI6H,EAAQ,EAAGA,EAAQ7H,KAAKmR,UAAUV,OAAQ5I,IAC/C7H,KAAKmR,UAAUtJ,GAAOc,mBAKpBiK,EAAArT,UAAAgU,WAAV,SAAqBtK,GACbjJ,KAAKgT,eACDhT,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQvF,YAAc1D,KAAK0D,YAC3BuF,EAAQxF,WAAazD,KAAKyD,WAC1BwF,EAAQ1F,cAAgBvD,KAAKuD,cAC7B0F,EAAQzF,cAAgBxD,KAAKwD,eAGjCyF,EAAQY,UAAY7J,KAAKgT,YACzB/J,EAAQuK,SAASxT,KAAKI,gBAAgB0F,KAAM9F,KAAKI,gBAAgB2F,IAAK/F,KAAKI,gBAAgB2E,MAAO/E,KAAKI,gBAAgB4E,SAEnHhF,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQxF,WAAa,EACrBwF,EAAQ1F,cAAgB,EACxB0F,EAAQzF,cAAgB,KAM7BoP,EAAArT,UAAAuJ,MAAP,SAAa/L,EAA2BgM,GACpCkI,EAAA1R,UAAMuJ,MAAKhL,KAAAkC,KAACjD,EAAMgM,GAElB,IAAkB,IAAAoJ,EAAA,EAAAC,EAAApS,KAAKmR,UAALgB,EAAAC,EAAA3B,OAAA0B,IAAgB,CAApBC,EAAAD,GACJrJ,MAAM/L,EAAMgM,KAKnB6J,EAAArT,UAAAgM,MAAP,SAAavB,EAAwBf,GACjC,GAAKjJ,KAAK+L,YAAa/L,KAAKwH,cAA5B,CAOA,GAJAyB,EAAQwK,OAERzT,KAAK2J,aAAaV,GAEdjJ,KAAK+J,iBAAiBC,EAAef,GAAU,CAC/CjJ,KAAKuT,WAAWtK,GAEhBjJ,KAAK0T,iBAAiBzK,GAKtB,IAHA,IAAI0K,GAAiB,EACjBC,GAAkB,EAEJzB,EAAA,EAAAC,EAAApS,KAAKmR,UAALgB,EAAAC,EAAA3B,OAAA0B,IAAgB,CAA7B,IAAIgB,EAAKf,EAAAD,GACNgB,EAAMpH,YAAcoH,EAAM3L,gBAC1B2L,EAAM5R,mBAAmB2I,SAASlK,KAAK6S,qBACvCM,EAAM5H,MAAMvL,KAAK6S,oBAAqB5J,GAElCkK,EAAM9O,sBAAsBkG,gBAC5B4I,EAAM9O,sBAAsBmG,gBAAgB2I,GAG5CnT,KAAK6T,sBAAwBV,EAAMtS,OAAO4E,UAC1CkO,EAAgBnL,KAAKuC,IAAI4I,EAAeR,EAAM/S,gBAAgB2E,QAE9D/E,KAAK8T,uBAAyBX,EAAMpS,QAAQ0E,UAC5CmO,EAAiBpL,KAAKuC,IAAI6I,EAAgBT,EAAM/S,gBAAgB4E,UAKxEhF,KAAK6T,sBAAwBF,GAAiB,IAC9C3T,KAAK+E,MAAQ4O,EAAgB,MAE7B3T,KAAK8T,uBAAyBF,GAAkB,IAChD5T,KAAKgF,OAAS4O,EAAiB,MAGvC3K,EAAQ8K,UAEJ/T,KAAKqE,sBAAsBkG,gBAC3BvK,KAAKqE,sBAAsBmG,gBAAgBxK,QAK5C4S,EAAArT,UAAAoM,gBAAP,SAAuBvF,EAAWC,EAAWuF,EAAcC,EAAmBC,GAC1E,IAAK9L,KAAK+L,WAAa/L,KAAKwH,cACxB,OAAO,EAGX,IAAKyJ,EAAA1R,UAAMiM,SAAQ1N,KAAAkC,KAACoG,EAAGC,GACnB,OAAO,EAIX,IAAK,IAAIwB,EAAQ7H,KAAKmR,UAAUV,OAAS,EAAG5I,GAAS,EAAGA,IAAS,CAE7D,GADY7H,KAAKmR,UAAUtJ,GACjB8D,gBAAgBvF,EAAGC,EAAGuF,EAAMC,EAAWC,GAC7C,OAAO,EAIf,QAAK9L,KAAKoD,kBAIHpD,KAAKgM,oBAAoBJ,EAAMxF,EAAGC,EAAGwF,EAAWC,IAIjD8G,EAAArT,UAAAmU,iBAAV,SAA2BzK,KAKjB2J,EAAArT,UAAA+K,sBAAV,SAAgCN,EAAwBf,GACpDgI,EAAA1R,UAAM+K,sBAAqBxM,KAAAkC,KAACgK,EAAef,GAE3CjJ,KAAK6S,oBAAoB3I,SAASlK,KAAKI,kBAIpCwS,EAAArT,UAAAoO,QAAP,WACIsD,EAAA1R,UAAMoO,QAAO7P,KAAAkC,MAEb,IAAoB,IAAAmS,EAAA,EAAAC,EAAApS,KAAKmR,UAALgB,EAAAC,EAAA3B,OAAA0B,IAAgB,CAApBC,EAAAD,GACJxE,YAGpBiF,EA1UA,CAA+BD,EAAA5S,SAAlB9C,EAAA2V,kaCTb,IAAAoB,EAAAvW,EAAA,GACAmC,EAAAnC,EAAA,GAMAwW,EAAA,SAAAhD,GAsFI,SAAAgD,IAAA,IAAA/O,EACI+L,EAAAnT,KAAAkC,OAAOA,YAtFHkF,EAAAgP,SAAW,GACXhP,EAAAiP,MAAQ,EACRjP,EAAAkP,eAAgB,EAEhBlP,EAAAmP,aAAeL,EAAAhD,YAAYsB,uBAQ5BpN,EAAAoP,OAAS,IA0KpB,OAvL+CjD,EAAA4C,EAAAhD,GAyB3C5S,OAAAC,eAAW2V,EAAA1U,UAAA,mBAAX,WACI,OAAOS,KAAKqU,kBAGhB,SAAuBzV,GAAvB,IAAAsG,EAAAlF,KACQA,KAAKqU,eAAiBzV,IAI1BoB,KAAKqU,aAAezV,EAEpBgB,EAAA6H,MAAM8M,aAAa,WACfrP,EAAKoM,uDAQbjT,OAAAC,eAAW2V,EAAA1U,UAAA,eAAX,WACI,OAAOS,KAAKkU,cAGhB,SAAmBtV,GAAnB,IAAAsG,EAAAlF,KACQA,KAAKkU,WAAatV,IAItBoB,KAAKkU,SAAWtV,EAChBoB,KAAKoU,eAAgB,EAErBxU,EAAA6H,MAAM8M,aAAa,WACfrP,EAAKoM,uDAQbjT,OAAAC,eAAW2V,EAAA1U,UAAA,YAAX,WACI,OAAOS,KAAKmU,WAGhB,SAAgBvV,GAAhB,IAAAsG,EAAAlF,KACQA,KAAKmU,QAAUvV,IAInBoB,KAAKmU,MAAQvV,EACboB,KAAKoU,eAAgB,EAErBxU,EAAA6H,MAAM8M,aAAa,WACfrP,EAAKoM,uDAWH2C,EAAA1U,UAAA+R,iBAAV,WACItR,KAAKwU,WAAa,EAClBxU,KAAKyU,YAAc,EAQnB,IAPA,IAAIC,EAAO,EACPC,EAAU,EACVC,EAAe,EAEfC,EAAsBjV,EAAAwH,OAAO0N,OAAO9U,KAAK8R,KAAMiD,oBAAmB,IAGpD5C,EAAA,EAAAC,EAAApS,KAAKmR,UAALgB,EAAAC,EAAA3B,OAAA0B,IAAgB,CAC9B,IADKgB,EAAKf,EAAAD,IACCvK,KAAX,CAIAgN,IACAzB,EAAMvL,KAAKmN,oBAAmB,GAG9B,IAAIC,EAAc7B,EAAMvL,KAAKqN,8BACzBC,EAAatV,EAAAuV,IAAIjO,QAAQ,GACzBkO,EAAOxV,EAAAuV,IAAIjO,QAAQ,GAEvB8N,EAAYjK,IAAIsK,cAAcL,EAAYnK,IAAKuK,GAE/CA,EAAKE,aAAa,IAElB1V,EAAAsH,QAAQqO,qBAAqBH,EAAMP,EAAqBK,GAExDlV,KAAKwU,WAAahM,KAAKuC,IAAI/K,KAAKwU,WAA2B,EAAfU,EAAW9O,GACvDpG,KAAKyU,YAAcjM,KAAKuC,IAAI/K,KAAKyU,YAA4B,EAAfS,EAAW7O,IAG7DrG,KAAKwU,YAA4B,EAAdxU,KAAKsU,OACxBtU,KAAKyU,aAA6B,EAAdzU,KAAKsU,OAGrBtU,KAAKoU,eACLO,EAAU3U,KAAKkU,SACfQ,EAAOlM,KAAKgN,KAAKZ,EAAe5U,KAAKkU,YAErCQ,EAAO1U,KAAKmU,MACZQ,EAAUnM,KAAKgN,KAAKZ,EAAe5U,KAAKmU,QAG5C,IAAIsB,EAA0B,GAAVd,EAAiB3U,KAAKwU,WACtCkB,EAAuB,GAAPhB,EAAc1U,KAAKyU,YACnCkB,KACAC,EAAc,EAElB,GAAI5V,KAAKoU,cACL,IAAK,IAAI3V,EAAI,EAAGA,EAAIiW,EAAMjW,IACtB,IAAK,IAAIT,EAAI,EAAGA,EAAI2W,IAChBgB,EAASzN,KAAK,IAAItI,EAAAsH,QAASlJ,EAAIgC,KAAKwU,WAAciB,EAAezV,KAAKwU,WAAa,EAAI/V,EAAIuB,KAAKyU,YAAeiB,EAAe1V,KAAKyU,YAAc,EAAG,QACpJmB,EACkBhB,IAHO5W,UASjC,IAASA,EAAI,EAAGA,EAAI2W,EAAS3W,IACzB,IAASS,EAAI,EAAGA,EAAIiW,IAChBiB,EAASzN,KAAK,IAAItI,EAAAsH,QAASlJ,EAAIgC,KAAKwU,WAAciB,EAAezV,KAAKwU,WAAa,EAAI/V,EAAIuB,KAAKyU,YAAeiB,EAAe1V,KAAKyU,YAAc,EAAG,QACpJmB,EACkBhB,IAHInW,KAUlCmX,EAAc,EACd,IAAkB,IAAAC,EAAA,EAAAC,EAAA9V,KAAKmR,UAAL0E,EAAAC,EAAArF,OAAAoF,IAAgB,CAA7B,IAAI1C,KAAK2C,EAAAD,IACCjO,OAIX5H,KAAK+V,aAAa5C,EAAOwC,EAASC,IAElCA,KAGJ5V,KAAKgW,oBAOC/B,EAAA1U,UAAAyW,iBAAV,aAGJ/B,EAvLA,CAA+CD,EAAAhD,aAAzB/T,EAAAgX,kGCHtB,IAAA5T,EAAA,WAQI,SAAAA,EAEWyF,EAEAC,EAEAhB,EAEAC,GANAhF,KAAA8F,OAEA9F,KAAA+F,MAEA/F,KAAA+E,QAEA/E,KAAAgF,SAgDf,OAxCW3E,EAAAd,UAAA2K,SAAP,SAAgB+L,GACZjW,KAAK8F,KAAOmQ,EAAMnQ,KAClB9F,KAAK+F,IAAMkQ,EAAMlQ,IACjB/F,KAAK+E,MAAQkR,EAAMlR,MACnB/E,KAAKgF,OAASiR,EAAMjR,QAQjB3E,EAAAd,UAAA0K,WAAP,SAAkBgM,GAEd,OAAIjW,KAAK8F,OAASmQ,EAAMnQ,OAIpB9F,KAAK+F,MAAQkQ,EAAMlQ,MAInB/F,KAAK+E,QAAUkR,EAAMlR,OAIrB/E,KAAKgF,SAAWiR,EAAMjR,UAWhB3E,EAAAC,MAAd,WACI,OAAO,IAAID,EAAQ,EAAG,EAAG,EAAG,IAEpCA,EAhEA,GAAapD,EAAAoD,gaCJb,IAAA6V,EAAAzY,EAAA,GACAoC,EAAApC,EAAA,GACAkV,EAAAlV,EAAA,GAKA0Y,EAAA,SAAAlF,GA+DI,SAAAkF,EAAmBjY,GAAnB,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OA9DXgH,EAAAkR,aAAc,EACdlR,EAAAmR,cAAe,EACfnR,EAAAoR,eAAgB,EAChBpR,EAAAqR,0BAA2B,EAC3BrR,EAAAsR,kBAAoB3W,EAAAQ,QAAQC,UA4IxC,OAjJgC+Q,EAAA8E,EAAAlF,GAQ5B5S,OAAAC,eAAW6X,EAAA5W,UAAA,kBAAX,WACI,OAAOS,KAAKoW,iBAGhB,SAAsBxX,GACdoB,KAAKoW,cAAgBxX,IAIzBoB,KAAKoW,YAAcxX,EACnBoB,KAAKyE,iDAITpG,OAAAC,eAAW6X,EAAA5W,UAAA,aAcX,WACI,OAAOS,KAAKa,OAAO8D,SAAS3E,KAAK4E,YAfrC,SAAiBhG,GACRoB,KAAKuW,2BACNvW,KAAKqW,cAAe,GAGpBrW,KAAKa,OAAO8D,SAAS3E,KAAK4E,SAAWhG,GAIrCoB,KAAKa,OAAOgE,WAAWjG,IACvBoB,KAAKyE,gDASbpG,OAAAC,eAAW6X,EAAA5W,UAAA,cAcX,WACI,OAAOS,KAAKe,QAAQ4D,SAAS3E,KAAK4E,YAftC,SAAkBhG,GACToB,KAAKuW,2BACNvW,KAAKsW,eAAgB,GAGrBtW,KAAKe,QAAQ4D,SAAS3E,KAAK4E,SAAWhG,GAItCoB,KAAKe,QAAQ8D,WAAWjG,IACxBoB,KAAKyE,gDAgBH0R,EAAA5W,UAAA+E,aAAV,WACI,MAAO,cAGD6R,EAAA5W,UAAA4K,YAAV,SAAsBH,EAAwBf,GAG1C,IAFA,IAAIwN,EAAa,EACbC,EAAc,EACAvE,EAAA,EAAAC,EAAApS,KAAKmR,UAALgB,EAAAC,EAAA3B,OAAA0B,IAAgB,CAA7B,IAAIgB,EAAKf,EAAAD,GACVnS,KAAKwW,kBAAkBtM,SAASiJ,EAAM/S,iBACtC+S,EAAM/S,gBAAgB8J,SAASF,GAC/BmJ,EAAM/I,WAEFpK,KAAKoW,aACLjD,EAAMpN,IAAM2Q,EAAc,KACrBvD,EAAMrR,KAAKyG,uBACZ4K,EAAM1O,eAEV0O,EAAMrR,KAAKyG,uBAAwB,EACnCmO,GAAevD,EAAM/S,gBAAgB4E,OACjCmO,EAAM/S,gBAAgB2E,MAAQ0R,IAC9BA,EAAatD,EAAM/S,gBAAgB2E,OAEvCoO,EAAMtM,kBAAoB8L,EAAA5S,QAAQ+G,yBAElCqM,EAAMrN,KAAO2Q,EAAa,KACrBtD,EAAMtR,MAAM0G,uBACb4K,EAAM1O,eAEV0O,EAAMtR,MAAM0G,uBAAwB,EACpCkO,GAActD,EAAM/S,gBAAgB2E,MAChCoO,EAAM/S,gBAAgB4E,OAAS0R,IAC/BA,EAAcvD,EAAM/S,gBAAgB4E,QAExCmO,EAAMxM,oBAAsBgM,EAAA5S,QAAQ6G,2BAGxCuM,EAAM/S,gBAAgB8J,SAASlK,KAAKwW,mBAGxCxW,KAAKuW,0BAA2B,EAKhC,IAAII,EACAC,EAEAC,EAAiB7W,KAAKgF,OACtB8R,EAAgB9W,KAAK+E,MAEpB/E,KAAKsW,gBAENtW,KAAKgF,OAAS0R,EAAc,MAE3B1W,KAAKqW,eAENrW,KAAK+E,MAAQ0R,EAAa,MAG9BE,EAAoBG,IAAkB9W,KAAK+E,QAAU/E,KAAKa,OAAO0H,uBACjEqO,EAAqBC,IAAmB7W,KAAKgF,SAAWhF,KAAKe,QAAQwH,yBAGjEvI,KAAKe,QAAQwH,uBAAwB,GAGrCoO,IACA3W,KAAKa,OAAO0H,uBAAwB,GAGxCvI,KAAKuW,0BAA2B,GAE5BI,GAAqBC,IACrB5W,KAAK2I,kBAGTsI,EAAA1R,UAAM4K,YAAWrM,KAAAkC,KAACgK,EAAef,IAEzCkN,EAjJA,CAAgCD,EAAAtD,WAAnB3V,EAAAkZ,maCPb,IAQYY,EARZnX,EAAAnC,EAAA,GAEAkC,EAAAlC,EAAA,GACAkV,EAAAlV,EAAA,IAKA,SAAYsZ,GAIRA,IAAA,eAKAA,IAAA,uBAKAA,IAAA,uBAdJ,CAAYA,EAAA9Z,EAAA8Z,eAAA9Z,EAAA8Z,kBAoBZ,IAAAC,EAAA,SAAA/F,GAoLI,SAAA+F,EAIW9Y,EACPmQ,QAAA,IAAAA,MAAA,IALJ,IAAAnJ,EAMI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YAFJkF,EAAAhH,OAvLHgH,EAAA+R,MAAQ,GACR/R,EAAAgS,cAAgBH,EAAaI,KAC7BjS,EAAAkS,yBAA2BzE,EAAA5S,QAAQoB,4BACnC+D,EAAAmS,uBAAyB1E,EAAA5S,QAAQsB,0BAGjC6D,EAAAoS,cAAwB,EACxBpS,EAAAqS,aAA6B,IAAI5X,EAAAgB,aAAa,GAC9CuE,EAAAsS,cAAwB,EACxBtS,EAAAuS,cAAwB,QAIzBvS,EAAAwS,wBAA0B,IAAI9X,EAAAkE,WAK9BoB,EAAAyS,uBAAyB,IAAI/X,EAAAkE,WAyKhCoB,EAAKmJ,KAAOA,IAsMpB,OAlY+BgD,EAAA2F,EAAA/F,GAwB3B5S,OAAAC,eAAW0Y,EAAAzX,UAAA,aAAX,WACI,OAAOS,KAAK4X,wCAMhBvZ,OAAAC,eAAW0Y,EAAAzX,UAAA,mBAAX,WACI,OAAOS,KAAKsX,kBAMhB,SAAuB1Y,GACnBoB,KAAKsX,aAAe1Y,EAEhBoB,KAAKsX,eACLtX,KAAKa,OAAO0H,uBAAwB,EACpCvI,KAAKe,QAAQwH,uBAAwB,oCAO7ClK,OAAAC,eAAW0Y,EAAAzX,UAAA,oBAAX,WACI,OAAOS,KAAKkX,mBAMhB,SAAwBtY,GAChBoB,KAAKkX,gBAAkBtY,IAG3BoB,KAAKkX,eAAiBtY,EACtBoB,KAAKyE,iDAMTpG,OAAAC,eAAW0Y,EAAAzX,UAAA,YAAX,WACI,OAAOS,KAAKiX,WAMhB,SAAgBrY,GACRoB,KAAKiX,QAAUrY,IAGnBoB,KAAKiX,MAAQrY,EACboB,KAAKyE,eAELzE,KAAK0X,wBAAwBlN,gBAAgBxK,wCAMjD3B,OAAAC,eAAW0Y,EAAAzX,UAAA,+BAAX,WACI,OAAOS,KAAKoX,8BAMhB,SAAmCxY,GAC3BoB,KAAKoX,2BAA6BxY,IAItCoB,KAAKoX,yBAA2BxY,EAChCoB,KAAKyE,iDAMTpG,OAAAC,eAAW0Y,EAAAzX,UAAA,6BAAX,WACI,OAAOS,KAAKqX,4BAMhB,SAAiCzY,GACzBoB,KAAKqX,yBAA2BzY,IAIpCoB,KAAKqX,uBAAyBzY,EAC9BoB,KAAKyE,iDAMTpG,OAAAC,eAAW0Y,EAAAzX,UAAA,mBASX,WACI,OAAOS,KAAKuX,aAAa5S,SAAS3E,KAAK4E,YAV3C,SAAuBhG,GACfoB,KAAKuX,aAAa1S,WAAWjG,IAC7BoB,KAAKyE,gDAcbpG,OAAAC,eAAW0Y,EAAAzX,UAAA,oBAAX,WACI,OAAOS,KAAKwX,mBAMhB,SAAwB5Y,GAChBoB,KAAKwX,gBAAkB5Y,IAG3BoB,KAAKwX,cAAgB5Y,EACrBoB,KAAKyE,iDAMTpG,OAAAC,eAAW0Y,EAAAzX,UAAA,oBAAX,WACI,OAAOS,KAAKyX,mBAMhB,SAAwB7Y,GAChBoB,KAAKyX,gBAAkB7Y,IAG3BoB,KAAKyX,cAAgB7Y,EACrBoB,KAAKyE,iDAmBCuS,EAAAzX,UAAA+E,aAAV,WACI,MAAO,aAGH0S,EAAAzX,UAAAsY,UAAR,SAAkBxJ,EAAcyJ,EAAmBzR,EAAW4C,GAC1D,IAAIlE,EAAQ/E,KAAKI,gBAAgB2E,MAC7BqB,EAAI,EACR,OAAQpG,KAAKoX,0BACT,KAAKzE,EAAA5S,QAAQ6G,0BACTR,EAAI,EACJ,MACJ,KAAKuM,EAAA5S,QAAQsL,2BACTjF,EAAIrB,EAAQ+S,EACZ,MACJ,KAAKnF,EAAA5S,QAAQoB,4BACTiF,GAAKrB,EAAQ+S,GAAa,GAI9B9X,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQvF,YAAc1D,KAAK0D,YAC3BuF,EAAQxF,WAAazD,KAAKyD,WAC1BwF,EAAQ1F,cAAgBvD,KAAKuD,cAC7B0F,EAAQzF,cAAgBxD,KAAKwD,eAG7BxD,KAAK+X,cACL9O,EAAQ+O,WAAW3J,EAAMrO,KAAKI,gBAAgB0F,KAAOM,EAAGC,GAE5D4C,EAAQgP,SAAS5J,EAAMrO,KAAKI,gBAAgB0F,KAAOM,EAAGC,IAInD2Q,EAAAzX,UAAAgM,MAAP,SAAavB,EAAwBf,GACjCA,EAAQwK,OAERzT,KAAK2J,aAAaV,GAEdjJ,KAAK+J,iBAAiBC,EAAef,IAErCjJ,KAAKkY,aAAajP,GAEtBA,EAAQ8K,WAGFiD,EAAAzX,UAAAoK,aAAV,SAAuBV,GACnBgI,EAAA1R,UAAMoK,aAAY7L,KAAAkC,KAACiJ,GACfjJ,KAAK+X,eACL9O,EAAQkP,UAAYnY,KAAK+X,aACzB9O,EAAQmP,YAAcpY,KAAKqY,eAIzBrB,EAAAzX,UAAA+K,sBAAV,SAAgCN,EAAwBf,GACpDjJ,KAAK4X,OAAS5X,KAAKsY,YAAYtY,KAAKI,gBAAgB2E,MAAOkE,GAC3DjJ,KAAK2X,uBAAuBnN,gBAAgBxK,OAGtCgX,EAAAzX,UAAA+Y,YAAV,SAAsBC,EAAkBtP,GACpC,IAAIuP,KACAZ,EAAS5X,KAAKqO,KAAKoK,MAAM,MAE7B,GAAIzY,KAAKkX,gBAAkBH,EAAa2B,UAAa1Y,KAAKsX,aAInD,GAAItX,KAAKkX,gBAAkBH,EAAa4B,UAAa3Y,KAAKsX,aAK7D,IAAkB,IAAAzB,EAAA,EAAA+C,EAAAhB,EAAA/B,EAAA+C,EAAAnI,OAAAoF,IAAQ,CAAjBgD,EAAKD,EAAA/C,GACV2C,EAAMtQ,KAAKlI,KAAK8Y,WAAWD,EAAO5P,SALtC,IAAkB,IAAAmJ,EAAA,EAAA2G,EAAAnB,EAAAxF,EAAA2G,EAAAtI,OAAA2B,IAAQ,CAArB,IAAIyG,EAAKE,EAAA3G,GACVoG,EAAMtQ,KAAI8Q,MAAVR,EAAcxY,KAAKiZ,mBAAmBJ,EAAON,EAAUtP,SAL3D,IAAkB,IAAAkJ,EAAA,EAAA+G,EAAAtB,EAAAzF,EAAA+G,EAAAzI,OAAA0B,IAAQ,CAArB,IAAI0G,EAAKK,EAAA/G,GACVqG,EAAMtQ,KAAKlI,KAAKmZ,mBAAmBN,EAAON,EAAUtP,IAY5D,OAAOuP,GAGDxB,EAAAzX,UAAAuZ,WAAV,SAAqBM,EAAmBnQ,GACpC,YADiB,IAAAmQ,MAAA,KACR/K,KAAM+K,EAAMrU,MAAOkE,EAAQoQ,YAAYD,GAAMrU,QAGhDiS,EAAAzX,UAAA4Z,mBAAV,SAA6BC,EAAmBrU,EAC5CkE,QADyB,IAAAmQ,MAAA,IAEzB,IAAIjB,EAAYlP,EAAQoQ,YAAYD,GAAMrU,MAK1C,IAHIoT,EAAYpT,IACZqU,GAAQ,KAELA,EAAK3I,OAAS,GAAK0H,EAAYpT,GAClCqU,EAAOA,EAAKE,MAAM,GAAI,GAAK,IAC3BnB,EAAYlP,EAAQoQ,YAAYD,GAAMrU,MAG1C,OAASsJ,KAAM+K,EAAMrU,MAAOoT,IAGtBnB,EAAAzX,UAAA0Z,mBAAV,SAA6BG,EAAmBrU,EAC5CkE,QADyB,IAAAmQ,MAAA,IAMzB,IAJA,IAAIZ,KACAe,EAAQH,EAAKX,MAAM,KACnBN,EAAY,EAEP/Y,EAAI,EAAGA,EAAIma,EAAM9I,OAAQrR,IAAK,CACnC,IAAIoa,EAAWpa,EAAI,EAAIga,EAAO,IAAMG,EAAMna,GAAKma,EAAM,GAEjDE,EADUxQ,EAAQoQ,YAAYG,GACVzU,MACpB0U,EAAY1U,GAAS3F,EAAI,GACzBoZ,EAAMtQ,MAAOmG,KAAM+K,EAAMrU,MAAOoT,IAChCiB,EAAOG,EAAMna,GACb+Y,EAAYlP,EAAQoQ,YAAYD,GAAMrU,QAGtCoT,EAAYsB,EACZL,EAAOI,GAKf,OAFAhB,EAAMtQ,MAAOmG,KAAM+K,EAAMrU,MAAOoT,IAEzBK,GAGDxB,EAAAzX,UAAA2Y,aAAV,SAAuBjP,GACnB,IAAIjE,EAAShF,KAAKI,gBAAgB4E,OAE7BhF,KAAKuE,cACNvE,KAAKuE,YAAcoO,EAAA5S,QAAQ2N,eAAezE,EAAQW,OAEtD,IAAI8P,EAAQ,EACZ,OAAQ1Z,KAAKqX,wBACT,KAAK1E,EAAA5S,QAAQ+G,uBACT4S,EAAQ1Z,KAAKuE,YAAY6K,OACzB,MACJ,KAAKuD,EAAA5S,QAAQuL,0BACToO,EAAQ1U,EAAShF,KAAKuE,YAAYS,QAAUhF,KAAK4X,OAAOnH,OAAS,GAAKzQ,KAAKuE,YAAY8K,QACvF,MACJ,KAAKsD,EAAA5S,QAAQsB,0BACTqY,EAAQ1Z,KAAKuE,YAAY6K,QAAUpK,EAAShF,KAAKuE,YAAYS,OAAShF,KAAK4X,OAAOnH,QAAU,EAIpGiJ,GAAS1Z,KAAKI,gBAAgB2F,IAI9B,IAFA,IAAI4T,EAAuB,EAElBhc,EAAI,EAAGA,EAAIqC,KAAK4X,OAAOnH,OAAQ9S,IAAK,CACzC,IAAMyb,EAAOpZ,KAAK4X,OAAOja,GAEf,IAANA,GAA+C,IAApCqC,KAAKuX,aAAaqC,gBAEzB5Z,KAAKuX,aAAa9R,QAClBiU,GAAS1Z,KAAKuX,aAAa7R,SAAS1F,KAAK4E,OAEzC8U,GAAiB1Z,KAAKuX,aAAa7R,SAAS1F,KAAK4E,OAAS5E,KAAKe,QAAQ+D,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBwD,SAIrIhF,KAAK6X,UAAUuB,EAAK/K,KAAM+K,EAAKrU,MAAO2U,EAAOzQ,GAC7CyQ,GAAS1Z,KAAKuE,YAAYS,OAEtBoU,EAAKrU,MAAQ4U,IAAcA,EAAeP,EAAKrU,OAGnD/E,KAAKsX,eACLtX,KAAK+E,MAAQ/E,KAAK6Z,oBAAsB7Z,KAAK8Z,qBAAuBH,EAAe,KACnF3Z,KAAKgF,OAAShF,KAAK+Z,mBAAqB/Z,KAAKga,sBAAwBha,KAAKuE,YAAYS,OAAShF,KAAK4X,OAAOnH,OAAS,OAQrHuG,EAAAzX,UAAA0a,sBAAP,WACI,GAAIja,KAAKqO,MAAQrO,KAAKka,cAAe,CACjC,IAAMjR,EAAUqF,SAASC,cAAc,UAAU4L,WAAW,MAC5D,GAAIlR,EAAS,CACTjJ,KAAK2J,aAAaV,GACbjJ,KAAKuE,cACNvE,KAAKuE,YAAcoO,EAAA5S,QAAQ2N,eAAezE,EAAQW,OAEtD,IAAM4O,EAAQxY,KAAK4X,OAAS5X,KAAK4X,OAAS5X,KAAKsY,YAC3CtY,KAAKka,cAAgBla,KAAK6Z,oBAAsB7Z,KAAK8Z,qBAAsB7Q,GAC/E,OAAOjJ,KAAK+Z,mBAAqB/Z,KAAKga,sBAAwBha,KAAKuE,YAAYS,OAASwT,EAAM/H,QAGtG,OAAO,GAGXuG,EAAAzX,UAAAoO,QAAA,WACIsD,EAAA1R,UAAMoO,QAAO7P,KAAAkC,MAEbA,KAAK0X,wBAAwB9J,SAErCoJ,EAlYA,CAA+BrE,EAAA5S,SAAlB9C,EAAA+Z,kaC5Bb,IAAAoD,EAAA3c,EAAA,IACAmC,EAAAnC,EAAA,GACA4c,EAAA5c,EAAA,IAMA6c,EAAA,SAAArJ,GAwDI,SAAAqJ,EAAYpc,GAAZ,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YApDPkF,EAAAqV,mBAAqB,IACrBrV,EAAAsV,mBAAqB,EAuDzBtV,EAAKuV,sBAAwB,WACpBvV,EAAK0C,OAGS1C,EAAKwV,iBAAkBC,cAAgB/a,EAAAgb,OAAOC,QAGrE3V,EAAK4V,oBAAsB,WACJ5V,EAAKwV,iBAAkBC,cAAgB/a,EAAAgb,OAAOG,SAGrE7V,EAAK8V,qBAAuB,WACnB9V,EAAK0C,MAIV1C,EAAK0C,KAAKqT,QAAQ3F,aAAa,MAGnCpQ,EAAKgW,mBAAqB,WACjBhW,EAAK0C,MAIV1C,EAAK0C,KAAKqT,QAAQ3F,aAAa,EAAM,QAoFjD,OAzK8BjE,EAAAiJ,EAAArJ,GAW1B5S,OAAAC,eAAWgc,EAAA/a,UAAA,yBAAX,WACI,OAAOS,KAAKua,wBAGhB,SAA6B3b,GACrBoB,KAAKua,qBAAuB3b,IAIhCoB,KAAKua,mBAAqB3b,EAC1BoB,KAAKmb,kDAMT9c,OAAAC,eAAWgc,EAAA/a,UAAA,yBAAX,WACI,OAAOS,KAAKwa,wBAGhB,SAA6B5b,GACrBoB,KAAKwa,qBAAuB5b,IAIhCoB,KAAKwa,mBAAqB5b,EAC1BoB,KAAKmb,kDAGCb,EAAA/a,UAAA6b,sBAAV,WACQpb,KAAKqb,iBACLrb,KAAKqb,eAAe1N,UACpB3N,KAAKqb,eAAiB,OAIpBf,EAAA/a,UAAA4b,cAAV,WACInb,KAAKob,wBACLpb,KAAKsb,QAAUtb,KAAKub,UA2CxBld,OAAAC,eAAWgc,EAAA/a,UAAA,eAAX,WACI,OAAOS,KAAKub,cAGhB,SAAmB3c,GACfoB,KAAKub,SAAW3c,EAEXoB,KAAK4E,OAAU5E,KAAK4E,MAAM+M,eAI1B3R,KAAKqb,iBACNrb,KAAKqb,eAAiB,IAAIhB,EAAAmB,uBAAuB,SAAUxb,KAAKua,mBAAoBva,KAAKua,mBAAoBva,KAAK4E,MAAM+M,aAAaE,mBAAmB,EAAMjS,EAAA6b,QAAQC,wBACtK1b,KAAKqb,eAAeM,cAAcC,OAAS5b,KAAKwa,mBAChDxa,KAAKqb,eAAeM,cAAcE,OAAS7b,KAAKwa,mBAChDxa,KAAKqb,eAAeS,aAAc,GAGtC9b,KAAKqb,eAAe3J,WAAW9S,GAE/BoB,KAAK+b,aAAa/b,KAAKqb,kDAQjBf,EAAA/a,UAAAwc,aAAV,SAAuBC,GACbhc,KAAK0a,iBAAkBuB,gBAAkBD,GAGzC1B,EAAA/a,UAAA+E,aAAV,WACI,MAAO,YAIDgW,EAAA/a,UAAAyS,YAAV,SAAsBvL,GAGlB,IAFA,IAAIyV,EAAS,IAAI9K,MAAM,GAEdzT,EAAI,EAAGA,EAAI,EAAGA,IACnBue,EAAOve,GAAK,IAAIiC,EAAAuc,QAAQ,EAAG,EAAG,EAAG,GAWrC,OATAD,EAAO,GAAK,IAAItc,EAAAuc,QAAQ,EAAG,EAAG,EAAG,GAEtBvc,EAAAwc,YAAYC,UAAUrc,KAAK9B,KAAO,aACzC6G,MAAO,EACPC,OAAQ,EACRsX,MAAO,IACPJ,OAAQA,GACTzV,IAKG6T,EAAA/a,UAAAgd,gBAAV,SAA0B3U,GACtB,IAAI4U,EAAW,IAAI5c,EAAA6c,iBAAiBzc,KAAK9B,KAAO,WAAY0J,EAAK8U,YACjEF,EAASG,cAAgB/c,EAAAgb,OAAOG,QAEhCnT,EAAK4U,SAAWA,EAChBxc,KAAK0a,iBAAmB8B,EAExBxc,KAAKmb,iBAMFb,EAAA/a,UAAAoO,QAAP,WACIsD,EAAA1R,UAAMoO,QAAO7P,KAAAkC,MAEbA,KAAKob,wBAEDpb,KAAK0a,kBACL1a,KAAK0a,iBAAiB/M,WAGlC2M,EAzKA,CAA8BF,EAAAwC,kBAAjB3f,EAAAqd,0FCRb,IAAA1a,EAAAnC,EAAA,GAEAof,EAAApf,EAAA,IAMAiV,EAAA,WAuLI,SAAAA,EAEWxU,GAAA8B,KAAA9B,OArLH8B,KAAAgD,WAAa,EACbhD,KAAAiD,aAAe,EACfjD,KAAAmD,mBACAnD,KAAA6C,YAAa,EAgDd7C,KAAA6D,wBAA0B,IAAIjE,EAAAkE,WAK9B9D,KAAA+D,uBAAyB,IAAInE,EAAAkE,WAK7B9D,KAAAgE,wBAA0B,IAAIpE,EAAAkE,WAK9B9D,KAAAiE,sBAAwB,IAAIrE,EAAAkE,WAK5B9D,KAAAkE,yBAA2B,IAAItE,EAAAkE,WAK/B9D,KAAAmE,yBAA2B,IAAIvE,EAAAkE,WAQ9B9D,KAAA8c,WAAa,IAAI1L,MAwU7B,OAtZI/S,OAAAC,eAAWoU,EAAAnT,UAAA,gBAAX,WACI,OAAKS,KAAK+c,MAIH/c,KAAK+c,MAAMvW,SAHP5G,EAAAsH,QAAQxE,YAMvB,SAAoB9D,GACXoB,KAAK+c,QAIV/c,KAAK+c,MAAMvW,SAAW5H,oCAI1BP,OAAAC,eAAWoU,EAAAnT,UAAA,eAAX,WACI,OAAKS,KAAK+c,MAIH/c,KAAK+c,MAAM9B,QAHP,IAAIrb,EAAAsH,QAAQ,EAAG,EAAG,QAMjC,SAAmBtI,GACVoB,KAAK+c,QAIV/c,KAAK+c,MAAM9B,QAAUrc,oCAsDzBP,OAAAC,eAAWoU,EAAAnT,UAAA,iBAAX,WACI,OAAOS,KAAK8c,4CASTpK,EAAAnT,UAAAyd,YAAP,SAAmBC,GAAnB,IAAA/X,EAAAlF,KAGI,IAAe,IAFHA,KAAK8c,WAAW/U,QAAQkV,GAGhC,OAAOjd,KAGXid,EAASC,OACT,IAAIzW,EAAQzG,KAAK4E,MAAM6B,MAWvB,OAVIA,EAAM0W,UAEN1W,EAAM2W,uBAAuBC,QAAQ,WACjCJ,EAASK,OAAOpY,KAGpB+X,EAASK,OAAOtd,MAEpBA,KAAK8c,WAAW5U,KAAK+U,GAEdjd,MASJ0S,EAAAnT,UAAAge,eAAP,SAAsBN,GAClB,IAAIpV,EAAQ7H,KAAK8c,WAAW/U,QAAQkV,GAEpC,OAAe,IAAXpV,EACO7H,MAGXA,KAAK8c,WAAWjV,GAAO2V,SACvBxd,KAAK8c,WAAW7U,OAAOJ,EAAO,GAEvB7H,OASJ0S,EAAAnT,UAAAke,kBAAP,SAAyBvf,GACrB,IAAqB,IAAAiU,EAAA,EAAAC,EAAApS,KAAK8c,WAAL3K,EAAAC,EAAA3B,OAAA0B,IAAiB,CAAjC,IAAI8K,EAAQ7K,EAAAD,GACb,GAAI8K,EAAS/e,OAASA,EAClB,OAAO+e,EAIf,OAAO,MAIX5e,OAAAC,eAAWoU,EAAAnT,UAAA,iBAAX,WACI,OAAOS,KAAK6C,gBAGhB,SAAqBjE,GACjB,GAAIoB,KAAK6C,aAAejE,EAAxB,CAIAoB,KAAK6C,WAAajE,EAElB,IAAIgJ,EAAO5H,KAAK4H,KACZA,GACAA,EAAK8V,WAAW9e,qCAgBxBP,OAAAC,eAAWoU,EAAAnT,UAAA,gBAAX,WACI,OAAOS,KAAKsE,gDAGNoO,EAAAnT,UAAA+E,aAAV,WACI,MAAO,aAMXjG,OAAAC,eAAWoU,EAAAnT,UAAA,YAAX,WACI,OAAOS,KAAK+c,uCAMhB1e,OAAAC,eAAWoU,EAAAnT,UAAA,YAAX,WACI,OAAIS,KAAK+c,iBAAiBnd,EAAA+d,aACf3d,KAAK+c,MAGT,sCAQJrK,EAAAnT,UAAAqe,oBAAP,SAA2B9L,GAIvB,OAHI9R,KAAK+c,QACL/c,KAAK+c,MAAM3Q,OAAS0F,GAEjB9R,MAIJ0S,EAAAnT,UAAAqS,aAAP,SAAoBnL,GAChB,IAAKzG,KAAK+c,MAAO,CAGb,GAFA/c,KAAK+c,MAAQ/c,KAAKgS,YAAYvL,IAEzBzG,KAAK8R,KACN,OAEJ9R,KAAK+c,MAAOc,SAAW7d,KACvBA,KAAK+c,MAAOvW,SAAWxG,KAAKwG,SAC5BxG,KAAK+c,MAAO9B,QAAUjb,KAAKib,QAE3B,IAAIrT,EAAO5H,KAAK4H,KACZA,IACAA,EAAKkW,YAAa,EAElB9d,KAAKuc,gBAAgB3U,MAWvB8K,EAAAnT,UAAAyS,YAAV,SAAsBvL,GAElB,OAAO,MAODiM,EAAAnT,UAAAgd,gBAAV,SAA0B3U,GACtBA,EAAK4U,SAAW,MAMb9J,EAAAnT,UAAA0M,eAAP,SAAsBC,EAAmBC,GACrCnM,KAAK6D,wBAAwB2G,gBAAgB2B,GAAc,EAAGD,EAAQlM,OAInE0S,EAAAnT,UAAA8M,gBAAP,SAAuBH,GACnB,QAAIlM,KAAKiD,YAAc,MAIG,IAAtBjD,KAAKiD,cACLjD,KAAKiD,YAAc,GAGvBjD,KAAKiD,cAELjD,KAAKmE,yBAAyBqG,gBAAgBxK,MAAO,EAAGkM,EAAQlM,MAE5DA,KAAKya,uBACLza,KAAKya,yBAGF,IAIJ/H,EAAAnT,UAAA+M,cAAP,SAAqBJ,GACjBlM,KAAKiD,YAAc,EAEnBjD,KAAK+D,uBAAuByG,gBAAgBxK,MAAO,EAAGkM,EAAQlM,MAE1DA,KAAK8a,qBACL9a,KAAK8a,uBAKNpI,EAAAnT,UAAAgN,eAAP,SAAsBL,EAAmBC,EAAsBN,EAAmBC,GAC9E,OAAwB,IAApB9L,KAAKgD,aAIThD,KAAKgD,aAELhD,KAAKmD,gBAAgB0I,IAAa,EAElC7L,KAAKgE,wBAAwBwG,gBAAgB,IAAIqS,EAAAkB,gBAAgB5R,EAAaL,IAAe,EAAGI,EAAQlM,MAEpGA,KAAKgb,sBACLhb,KAAKgb,wBAGF,IAIJtI,EAAAnT,UAAAkN,aAAP,SAAoBP,EAAmBC,EAAsBN,EAAmBC,EAAqBY,GACjG1M,KAAKgD,WAAa,SAEXhD,KAAKmD,gBAAgB0I,GAExBa,IAAgB1M,KAAKiD,YAAc,IAA2B,IAAtBjD,KAAKiD,cAC7CjD,KAAKkE,yBAAyBsG,gBAAgB,IAAIqS,EAAAkB,gBAAgB5R,EAAaL,IAAe,EAAGI,EAAQlM,MAE7GA,KAAKiE,sBAAsBuG,gBAAgB,IAAIqS,EAAAkB,gBAAgB5R,EAAaL,IAAe,EAAGI,EAAQlM,MAElGA,KAAKkb,oBACLlb,KAAKkb,sBAKNxI,EAAAnT,UAAAye,eAAP,SAAsBnS,GAClB,QADkB,IAAAA,MAAA,MACA,OAAdA,EACA7L,KAAKyM,aAAazM,KAAMJ,EAAAsH,QAAQxE,OAAQmJ,EAAW,GAAG,QAEtD,IAAK,IAAI3M,KAAOc,KAAKmD,gBACjBnD,KAAKyM,aAAazM,KAAMJ,EAAAsH,QAAQxE,QAASxD,EAAe,GAAG,IAMhEwT,EAAAnT,UAAAyM,oBAAP,SAA2BJ,EAAcqS,EAAsBpS,EAAmBC,GAC9E,GAAIF,IAAShM,EAAAkN,kBAAkBC,YAAa,CACxC/M,KAAKiM,eAAejM,KAAMie,GAE1B,IAAIjR,EAAsBhN,KAAK4E,MAAMqI,iBAAiBpB,GAUtD,OATImB,GAAuBA,IAAwBhN,MAC/CgN,EAAoBV,cAActM,MAGlCgN,IAAwBhN,MACxBA,KAAKqM,gBAAgBrM,MAGzBA,KAAK4E,MAAMqI,iBAAiBpB,GAAa7L,MAClC,EAGX,OAAI4L,IAAShM,EAAAkN,kBAAkBI,aAC3BlN,KAAKuM,eAAevM,KAAMie,EAAapS,EAAWC,GAClD9L,KAAK4E,MAAMuI,iBAAiBtB,GAAa7L,KACzCA,KAAK4E,MAAMwI,mBAAqBpN,MACzB,GAGP4L,IAAShM,EAAAkN,kBAAkBO,YACvBrN,KAAK4E,MAAMuI,iBAAiBtB,IAC5B7L,KAAK4E,MAAMuI,iBAAiBtB,GAAWY,aAAazM,KAAMie,EAAapS,EAAWC,GAAa,UAE5F9L,KAAK4E,MAAMuI,iBAAiBtB,IAC5B,IAOR6G,EAAAnT,UAAA2S,aAAP,WACQlS,KAAK+c,QACL/c,KAAK+c,MAAMpP,UACX3N,KAAK+c,MAAQ,OAOdrK,EAAAnT,UAAAoO,QAAP,WACI3N,KAAKgE,wBAAwB4J,QAC7B5N,KAAKmE,yBAAyByJ,QAC9B5N,KAAK6D,wBAAwB+J,QAC7B5N,KAAK+D,uBAAuB6J,QAC5B5N,KAAKiE,sBAAsB2J,QAC3B5N,KAAKkE,yBAAyB0J,QAE9B5N,KAAKkS,eAGL,IAAqB,IAAAC,EAAA,EAAAC,EAAApS,KAAK8c,WAAL3K,EAAAC,EAAA3B,OAAA0B,IAAiB,CAArBC,EAAAD,GACJqL,WAGrB9K,EAhaA,GAAazV,EAAAyV,kaCRb,IAAAC,EAAAlV,EAAA,GACAmC,EAAAnC,EAAA,GAMAygB,EAAA,SAAAjN,GAoOI,SAAAiN,EAAmBhgB,EAAeigB,QAAA,IAAAA,MAAA,MAAlC,IAAAjZ,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OAhOXgH,EAAAkZ,SAAU,EACVlZ,EAAAmZ,SAAWH,EAASI,aAEpBpZ,EAAAqZ,YAAa,EAEbrZ,EAAAsZ,YAAc,EACdtZ,EAAAuZ,WAAa,EACbvZ,EAAAwZ,aAAe,EACfxZ,EAAAyZ,cAAgB,EAEhBzZ,EAAAsP,WAAqB,EACrBtP,EAAAuP,YAAsB,EACtBvP,EAAA0Z,SAAmB,EAuNvB1Z,EAAKmL,OAAS8N,IA8GtB,OArVuB9M,EAAA6M,EAAAjN,GAqBnB5S,OAAAC,eAAW4f,EAAA3e,UAAA,kBAAX,WACI,OAAOS,KAAKwe,iBAGhB,SAAsB5f,GACdoB,KAAKwe,cAAgB5f,IAIzBoB,KAAKwe,YAAc5f,EAEnBoB,KAAKyE,iDAMTpG,OAAAC,eAAW4f,EAAA3e,UAAA,iBAAX,WACI,OAAOS,KAAKye,gBAGhB,SAAqB7f,GACboB,KAAKye,aAAe7f,IAIxBoB,KAAKye,WAAa7f,EAElBoB,KAAKyE,iDAMTpG,OAAAC,eAAW4f,EAAA3e,UAAA,mBAAX,WACI,OAAOS,KAAK0e,kBAGhB,SAAuB9f,GACfoB,KAAK0e,eAAiB9f,IAI1BoB,KAAK0e,aAAe9f,EAEpBoB,KAAKyE,iDAMTpG,OAAAC,eAAW4f,EAAA3e,UAAA,oBAAX,WACI,OAAOS,KAAK2e,mBAGhB,SAAwB/f,GAChBoB,KAAK2e,gBAAkB/f,IAI3BoB,KAAK2e,cAAgB/f,EAErBoB,KAAKyE,iDAOTpG,OAAAC,eAAW4f,EAAA3e,UAAA,iBAAX,WACI,OAAOS,KAAKue,gBAGhB,SAAqB3f,GACboB,KAAKue,aAAe3f,IAIxBoB,KAAKue,WAAa3f,EAEdA,GAASoB,KAAKoe,SACdpe,KAAK6e,+DAKbxgB,OAAAC,eAAW4f,EAAA3e,UAAA,eAAX,WACI,OAAOS,KAAKqe,cAGhB,SAAmBzf,GACXoB,KAAKqe,WAAazf,IAItBoB,KAAKqe,SAAWzf,EAEhBoB,KAAKyE,iDAMTpG,OAAAC,eAAW4f,EAAA3e,UAAA,gBAaX,WACI,OAAOS,KAAK8e,eAdhB,SAAoBlgB,GAApB,IAAAsG,EAAAlF,KACIA,KAAK8e,UAAYlgB,EACjBoB,KAAKoe,SAAU,EAEXpe,KAAK8e,UAAU/Z,MACf/E,KAAK+e,iBAEL/e,KAAK8e,UAAUE,OAAS,WACpB9Z,EAAK6Z,mDASTb,EAAA3e,UAAAwf,eAAR,WACI/e,KAAKif,YAAcjf,KAAK8e,UAAU/Z,MAClC/E,KAAKkf,aAAelf,KAAK8e,UAAU9Z,OACnChF,KAAKoe,SAAU,EAEXpe,KAAKue,YACLve,KAAK6e,6BAGT7e,KAAKyE,gBAMTpG,OAAAC,eAAW4f,EAAA3e,UAAA,cAAX,SAAkBX,GAAlB,IAAAsG,EAAAlF,KACQA,KAAKmf,UAAYvgB,IAIrBoB,KAAKoe,SAAU,EACfpe,KAAKmf,QAAUvgB,EAEfoB,KAAK8e,UAAY,IAAIM,MAErBpf,KAAK8e,UAAUE,OAAS,WACpB9Z,EAAK6Z,kBAELngB,IACAgB,EAAA6H,MAAM4X,gBAAgBzgB,EAAOoB,KAAK8e,WAClC9e,KAAK8e,UAAUQ,IAAM1gB,qCAQ7BP,OAAAC,eAAI4f,EAAA3e,UAAA,iBAAJ,WACI,OAAOS,KAAKwU,gBAEhB,SAAc5V,GACNoB,KAAKwU,aAAe5V,IAIxBoB,KAAKwU,WAAa5V,EAClBoB,KAAKyE,iDAOTpG,OAAAC,eAAI4f,EAAA3e,UAAA,kBAAJ,WACI,OAAOS,KAAKyU,iBAEhB,SAAe7V,GACPoB,KAAKyU,cAAgB7V,IAIzBoB,KAAKyU,YAAc7V,EACnBoB,KAAKyE,iDAOTpG,OAAAC,eAAI4f,EAAA3e,UAAA,cAAJ,WACI,OAAOS,KAAK4e,aAEhB,SAAWhgB,GACHoB,KAAK4e,UAAYhgB,IAIrBoB,KAAK4e,QAAUhgB,EACfoB,KAAKyE,iDAcCyZ,EAAA3e,UAAA+E,aAAV,WACI,MAAO,SAIJ4Z,EAAA3e,UAAAsf,2BAAP,WACS7e,KAAKoe,UAIVpe,KAAK+E,MAAQ/E,KAAK8e,UAAU/Z,MAAQ,KACpC/E,KAAKgF,OAAShF,KAAK8e,UAAU9Z,OAAS,OAGnCkZ,EAAA3e,UAAAgM,MAAP,SAAavB,EAAwBf,GAUjC,IAAI7C,EAAGC,EAAGtB,EAAOC,EACjB,GAVAiE,EAAQwK,QAEJzT,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQvF,YAAc1D,KAAK0D,YAC3BuF,EAAQxF,WAAazD,KAAKyD,WAC1BwF,EAAQ1F,cAAgBvD,KAAKuD,cAC7B0F,EAAQzF,cAAgBxD,KAAKwD,gBAIb,GAAhBxD,KAAKuf,OACLnZ,EAAIpG,KAAKwe,YACTnY,EAAIrG,KAAKye,WAET1Z,EAAQ/E,KAAK0e,aAAe1e,KAAK0e,aAAe1e,KAAKif,YACrDja,EAAShF,KAAK2e,cAAgB3e,KAAK2e,cAAgB3e,KAAKkf,iBAEvD,CACD,IAAIM,EAAWxf,KAAK8e,UAAUW,aAAezf,KAAK0f,UAC9CC,EAAU3f,KAAKuf,OAASC,GAAa,EACrCI,EAAM5f,KAAKuf,OAASC,EAExBpZ,EAAIpG,KAAK0f,UAAYE,EACrBvZ,EAAIrG,KAAK6f,WAAaF,EACtB5a,EAAQ/E,KAAK0f,UACb1a,EAAShF,KAAK6f,WAIlB,GADA7f,KAAK2J,aAAaV,GACdjJ,KAAK+J,iBAAiBC,EAAef,IACjCjJ,KAAKoe,QACL,OAAQpe,KAAKqe,UACT,KAAKH,EAAS4B,aAId,KAAK5B,EAASI,aACVrV,EAAQ8W,UAAU/f,KAAK8e,UAAW1Y,EAAGC,EAAGtB,EAAOC,EAC3ChF,KAAKI,gBAAgB0F,KAAM9F,KAAKI,gBAAgB2F,IAAK/F,KAAKI,gBAAgB2E,MAAO/E,KAAKI,gBAAgB4E,QAC1G,MACJ,KAAKkZ,EAAS8B,gBACV,IAAIC,EAASjgB,KAAKI,gBAAgB2E,MAAQA,EACtCmb,EAASlgB,KAAKI,gBAAgB4E,OAASA,EACvCmb,EAAQ3X,KAAKqC,IAAIoV,EAAQC,GACzBE,GAAWpgB,KAAKI,gBAAgB2E,MAAQA,EAAQob,GAAS,EACzDE,GAAWrgB,KAAKI,gBAAgB4E,OAASA,EAASmb,GAAS,EAE/DlX,EAAQ8W,UAAU/f,KAAK8e,UAAW1Y,EAAGC,EAAGtB,EAAOC,EAC3ChF,KAAKI,gBAAgB0F,KAAOsa,EAASpgB,KAAKI,gBAAgB2F,IAAMsa,EAAStb,EAAQob,EAAOnb,EAASmb,GACrG,MACJ,KAAKjC,EAASoC,eACVrX,EAAQ8W,UAAU/f,KAAK8e,UAAW1Y,EAAGC,EAAGtB,EAAOC,EAC3ChF,KAAKI,gBAAgB0F,KAAM9F,KAAKI,gBAAgB2F,IAAK/F,KAAKI,gBAAgB2E,MAAO/E,KAAKI,gBAAgB4E,QACtGhF,KAAKue,YACLve,KAAK6e,6BAEL7e,KAAK4F,OAAS5F,KAAK4F,MAAMwG,SACzBpM,KAAK4F,MAAMb,MAAQ/E,KAAK+E,MACxB/E,KAAK4F,MAAMZ,OAAShF,KAAKgF,QAM7CiE,EAAQ8K,WAUZ1V,OAAAC,eAAkB4f,EAAA,oBAAlB,WACI,OAAOA,EAASqC,+CAIpBliB,OAAAC,eAAkB4f,EAAA,oBAAlB,WACI,OAAOA,EAASsC,+CAIpBniB,OAAAC,eAAkB4f,EAAA,uBAAlB,WACI,OAAOA,EAASuC,kDAIpBpiB,OAAAC,eAAkB4f,EAAA,sBAAlB,WACI,OAAOA,EAASwC,iDAtBLxC,EAAAqC,cAAgB,EAChBrC,EAAAsC,cAAgB,EAChBtC,EAAAuC,iBAAmB,EACnBvC,EAAAwC,gBAAkB,EAqBrCxC,EArVA,CAAuBvL,EAAA5S,SAuVF9C,EAAAmiB,MAAAlB,qvBC9VrB,IAAAte,EAAAnC,EAAA,GAEAA,EAAA,IAGAkjB,iBAGA,IAAAC,EAAA,SAAA3P,GAKI,SAAA2P,IAAA,IAAA1b,EACI+L,EAAAnT,KAAAkC,OAAOA,YALJkF,EAAA2b,WAAY,EACZ3b,EAAA4b,QAAS,EACT5b,EAAA6b,YAAa,EAIhB7b,EAAK8b,YAEb,OAT2C3P,EAAAuP,EAAA3P,GAS3C2P,EATA,CAA2ChhB,EAAAqhB,iBAA9BhkB,EAAA2jB,wBAcb,IAAAM,EAAA,SAAAjQ,GAkFI,SAAAiQ,EAAYhjB,EAAcuI,GAA1B,IAAAvB,EACI+L,EAAAnT,KAAAkC,KAAM9B,EAAMuI,IAAMzG,YA5EfkF,EAAAic,wBAA0B,GAM1Bjc,EAAAkc,eAAiB,IAAIxhB,EAAAgb,OAAO,EAAK,EAAK,GAMtC1V,EAAAmc,MAAQ,EAMRnc,EAAAoc,YAAc,IAAI1hB,EAAAgb,OAAO,GAAK,IAAM,IAOpC1V,EAAAqc,eAAgB,EAMhBrc,EAAAsc,YAAc,GAMdtc,EAAAuc,mBAAqB,IAMrBvc,EAAAwc,eAAiB,GAOjBxc,EAAAyc,kBAAmB,EAMnBzc,EAAA0c,YAAc,EAMd1c,EAAA2c,WAAa,IAAIjiB,EAAAkiB,OAAO,GAAK,GAAK,GAAK,GAMvC5c,EAAA6c,cAAgBniB,EAAAsH,QAAQxE,SAuLnC,OAlQoC2O,EAAA6P,EAAAjQ,GAsFzBiQ,EAAA3hB,UAAAyiB,kBAAP,WACI,OAAsB,IAAfhiB,KAAKqhB,OAGTH,EAAA3hB,UAAA0iB,iBAAP,WACI,OAAO,GAGJf,EAAA3hB,UAAA2iB,oBAAP,WACI,OAAO,MAGJhB,EAAA3hB,UAAA4iB,kBAAP,SAAyBva,EAAoBwa,EAAkBC,GAC3D,GAAIriB,KAAKsiB,UACDtiB,KAAKuiB,qBAAuBH,EAAQI,OACpC,OAAO,EAIVJ,EAAQK,mBACTL,EAAQK,iBAAmB,IAAI7B,GAGnC,IAAIna,EAAQzG,KAAK0c,WACbgG,EAAiCN,EAAQK,iBAC7C,IAAKziB,KAAK2iB,uBAAyBP,EAAQI,QACnCE,EAAQE,YAAcnc,EAAMoc,cAC5B,OAAO,EAIXH,EAAQI,oBACRJ,EAAQ7B,UAAY7gB,KAAKmhB,wBAA0B,EACnDuB,EAAQ5B,OAAS9gB,KAAKuhB,cACtBmB,EAAQ3B,WAAa/gB,KAAK2hB,kBAG9B,IAAIoB,EAAStc,EAAMuc,YAEnB,GAAIN,EAAQO,QAAS,CACjBP,EAAQQ,kBACRzc,EAAM0c,sBAGN,IAAIC,GAAWxjB,EAAAyjB,aAAaC,cAC5BF,EAAQlb,KAAKtI,EAAAyjB,aAAaE,YAC1BH,EAAQlb,KAAKtI,EAAAyjB,aAAaG,QAE1B,IAEIC,GAAY,QAAS,iBAAkB,iBAAkB,cAAe,cAAe,qBAAsB,cAAe,iBAC5H,aAAc,gBAAiB,eAG/BC,EAAW,IAAItS,MACfuS,EAAiB,IAAIvS,MAEzBxR,EAAAgkB,eAAeC,gCACXC,cAAeL,EACfM,oBAAqBJ,EACrBD,SAAUA,EACVhB,QAASA,EACTsB,sBAAuB,IAG3B,IAAIC,EAAOvB,EAAQ/d,WACnByd,EAAQ8B,UAAUzd,EAAMuc,YAAYmB,aAlBnB,UAoBTC,WAAYhB,EACZU,cAAeL,EACfM,oBAAqBJ,EACrBD,SAAUA,EACVhB,QAASuB,EACTI,UAAW,KACXC,WAAYtkB,KAAKskB,WACjBC,QAASvkB,KAAKukB,QACdC,iBAAmBR,sBAAuB,IAC3CjB,IAIX,SAAKX,EAAQI,SAAWJ,EAAQI,OAAOiC,aAIvC/B,EAAQE,UAAYnc,EAAMoc,cAC1B7iB,KAAKuiB,qBAAsB,GAEpB,IAGJrB,EAAA3hB,UAAAmlB,eAAP,SAAsBC,EAAe/c,EAAYwa,GAC7C,IAAI3b,EAAQzG,KAAK0c,WAEbgG,EAAiCN,EAAQK,iBAC7C,GAAKC,EAAL,CAIA,IAAIF,EAASJ,EAAQI,OAChBA,IAGLxiB,KAAK4kB,cAAgBpC,EAGrBxiB,KAAK6kB,oBAAoBF,GACzB3kB,KAAK4kB,cAAcE,UAAU,iBAAkBre,EAAMY,sBAGjDrH,KAAK+kB,YAAYte,EAAO+b,KACxBxiB,KAAK4kB,cAAcI,UAAU,cAAehlB,KAAKshB,YAAathB,KAAKqhB,OAE/DqB,EAAQ7B,WACR7gB,KAAK4kB,cAAcI,UAAU,iBAAkBhlB,KAAKohB,eAAgBphB,KAAKmhB,yBAGzEuB,EAAQ5B,SACR9gB,KAAK4kB,cAAcK,SAAS,cAAejlB,KAAKwhB,aAChDxhB,KAAK4kB,cAAcK,SAAS,qBAAsBjlB,KAAKyhB,oBACvDzhB,KAAK4kB,cAAcK,SAAS,iBAAkBjlB,KAAK0hB,gBAEnD9Z,EAAKsd,kBAAkBlQ,YAAYE,WAAWiQ,cAAcvd,EAAKqT,QAASrb,EAAAuV,IAAIjO,QAAQ,IACtFlH,KAAK4kB,cAAcQ,WAAW,cAAexlB,EAAAuV,IAAIjO,QAAQ,KAGzDwb,EAAQ3B,aACR/gB,KAAK4kB,cAAcS,gBAAgB,aAAcrlB,KAAK6hB,YACtD7hB,KAAK4kB,cAAcK,SAAS,cAAejlB,KAAK4hB,aAChD5hB,KAAK4kB,cAAcQ,WAAW,gBAAiBplB,KAAK+hB,iBAI5D/hB,KAAKslB,WAAW1d,EAAM5H,KAAK4kB,kBAGxB1D,EAAA3hB,UAAAgmB,kBAAP,WAGI,OAFqBtU,EAAA1R,UAAMgmB,kBAAiBznB,KAAAkC,OAKzCkhB,EAAA3hB,UAAAimB,WAAP,SAAkBC,GACd,QAAIxU,EAAA1R,UAAMimB,WAAU1nB,KAAAkC,KAACylB,IAOlBvE,EAAA3hB,UAAAoO,QAAP,SAAe+X,GACXzU,EAAA1R,UAAMoO,QAAO7P,KAAAkC,KAAC0lB,IAGXxE,EAAA3hB,UAAAomB,MAAP,SAAaznB,GAAb,IAAAgH,EAAAlF,KACI,OAAOJ,EAAAgmB,oBAAoBC,MAAM,WAAM,WAAI3E,EAAehjB,EAAMgH,EAAKwX,aAAa1c,OAG/EkhB,EAAA3hB,UAAAumB,UAAP,WACI,IAAIC,EAAsBnmB,EAAAgmB,oBAAoBI,UAAUhmB,MAExD,OADA+lB,EAAoBE,WAAa,6BAC1BF,GAGJ7E,EAAA3hB,UAAA2mB,aAAP,WACI,MAAO,kBAIGhF,EAAAiF,MAAd,SAAoB9V,EAAa5J,EAAc2f,GAC3C,OAAOxmB,EAAAgmB,oBAAoBO,MAAM,WAAM,WAAIjF,EAAe7Q,EAAOnS,KAAMuI,IAAQ4J,EAAQ5J,EAAO2f,IAzPlGC,GAFCzmB,EAAAkmB,YACAlmB,EAAA0mB,iBAAiB,mFAOlBD,GADCzmB,EAAA2mB,0DAODF,GADCzmB,EAAAkmB,yCAODO,GADCzmB,EAAA2mB,uDAQDF,GAFCzmB,EAAAkmB,YACAlmB,EAAA0mB,iBAAiB,yEAOlBD,GADCzmB,EAAAkmB,+CAODO,GADCzmB,EAAAkmB,sDAODO,GADCzmB,EAAAkmB,kDAQDO,GAFCzmB,EAAAkmB,YACAlmB,EAAA0mB,iBAAiB,4EAOlBD,GADCzmB,EAAAkmB,+CAODO,GADCzmB,EAAA4mB,sDAODH,GADCzmB,EAAA6mB,0DAwLLvF,EAlQA,CAAoCthB,EAAA8mB,cAAvBzpB,EAAAikB,uaCtBb,IAKAnD,EAAA,SAAA9M,GAMI,SAAA8M,EAAmB1N,EAERvE,QAAA,IAAAA,MAAA,GAFX,IAAA5G,EAGI+L,EAAAnT,KAAAkC,KAAMqQ,EAAOjK,EAAGiK,EAAOhK,EAAGgK,EAAO9I,IAAEvH,YAD5BkF,EAAA4G,gBAGf,OAXqCuF,EAAA0M,EAAA9M,GAWrC8M,EAXA,CALAtgB,EAAA,GAKqCyJ,SAAxBjK,EAAA8gB,waCLb,IAAAhN,EAAAtT,EAAA,IACAmC,EAAAnC,EAAA,GAKAmf,EAAA,SAAA3L,GAKI,SAAA2L,EAAY1e,UACR+S,EAAAnT,KAAAkC,KAAM9B,IAAK8B,KAWnB,OAjBsCqR,EAAAuL,EAAA3L,GASxB2L,EAAArd,UAAA+E,aAAV,WACI,MAAO,oBAIDsY,EAAArd,UAAAyS,YAAV,SAAsBvL,GAClB,OAAO,IAAI7G,EAAAqS,cAAc,SAAWjS,KAAK9B,OAEjD0e,EAjBA,CAAsC7L,EAAA2B,WAAzBzV,EAAA2f,kGCNb,IAAAhd,EAAAnC,EAAA,GAEAkC,EAAAlC,EAAA,GAMAkpB,EAAA,WAkBI,SAAAA,EAAmB5d,GAjBX/I,KAAAO,YAAc,QACdP,KAAAQ,WAAa,GACbR,KAAAS,YAAc,GAIfT,KAAAU,UAAY,IAAIf,EAAAgB,aAAa,GAAIhB,EAAAgB,aAAaC,gBAAgB,GAK9DZ,KAAAmF,oBAAsB,IAAIvF,EAAAkE,WAO7B9D,KAAK4E,MAAQmE,EAsErB,OAhEI1K,OAAAC,eAAWqoB,EAAApnB,UAAA,gBAAX,WACI,OAAOS,KAAKU,UAAUiE,SAAS3E,KAAK4E,YAGxC,SAAoBhG,GACZoB,KAAKU,UAAUiE,SAAS3E,KAAK4E,SAAWhG,GAIxCoB,KAAKU,UAAUmE,WAAWjG,IAC1BoB,KAAKmF,oBAAoBqF,gBAAgBxK,uCAOjD3B,OAAAC,eAAWqoB,EAAApnB,UAAA,kBAAX,WACI,OAAOS,KAAKO,iBAGhB,SAAsB3B,GACdoB,KAAKO,cAAgB3B,IAIzBoB,KAAKO,YAAc3B,EACnBoB,KAAKmF,oBAAoBqF,gBAAgBxK,wCAM7C3B,OAAAC,eAAWqoB,EAAApnB,UAAA,iBAAX,WACI,OAAOS,KAAKQ,gBAGhB,SAAqB5B,GACboB,KAAKQ,aAAe5B,IAIxBoB,KAAKQ,WAAa5B,EAClBoB,KAAKmF,oBAAoBqF,gBAAgBxK,wCAI7C3B,OAAAC,eAAWqoB,EAAApnB,UAAA,kBAAX,WACI,OAAOS,KAAKS,iBAGhB,SAAsB7B,GACdoB,KAAKS,cAAgB7B,IAIzBoB,KAAKS,YAAc7B,EACnBoB,KAAKmF,oBAAoBqF,gBAAgBxK,wCAItC2mB,EAAApnB,UAAAoO,QAAP,WACI3N,KAAKmF,oBAAoByI,SAEjC+Y,EAzFA,GAAa1pB,EAAA0pB,8ZCRb,IAAA/mB,EAAAnC,EAAA,GACAyY,EAAAzY,EAAA,GAEAmpB,EAAAnpB,EAAA,IACAoC,EAAApC,EAAA,GAyBA+d,EAAA,SAAAvK,GAmNI,SAAAuK,EAAYtd,EAAc6G,EAAWC,EAAYyB,EAAwBogB,EAAyBC,QAAxE,IAAA/hB,MAAA,QAAW,IAAAC,MAAA,QAAoC,IAAA6hB,OAAA,QAAyB,IAAAC,MAAelnB,EAAA6b,QAAQsL,sBAAzH,IAAA7hB,EACI+L,EAAAnT,KAAAkC,KAAM9B,GAAQ6G,MAAOA,EAAOC,OAAQA,GAAUyB,EAAOogB,EAAiBC,EAAclnB,EAAAonB,OAAOC,qBAAmBjnB,KAI9G,OAvNIkF,EAAA5D,UAAW,EASZ4D,EAAAwB,eAAiB,IAAIwP,EAAAtD,UAAU,QAI/B1N,EAAA+H,oBAEA/H,EAAAiI,oBAEAjI,EAAAgiB,qBAMAhiB,EAAA4C,gBAAkB,IAAIsJ,MACrBlM,EAAAiiB,eAAgB,EAChBjiB,EAAAkiB,oBAAsB,IAAIxnB,EAAAynB,SAAS,EAAG,EAAG,EAAG,GAC5CniB,EAAAoiB,YAAc,EACdpiB,EAAAqiB,aAAe,EACfriB,EAAAsiB,mBAA6B,EAC7BtiB,EAAAuiB,oBAAqB,EAErBviB,EAAAwiB,sBAAuB,EACvBxiB,EAAAyiB,aAAe,EAKhBziB,EAAA4W,aAAc,GAgLjBrV,EAAQvB,EAAKwX,aAEExX,EAAK0iB,UAIpB1iB,EAAK2iB,gBAAkBphB,EAAMqhB,+BAA+BxiB,IAAI,SAACyiB,GAAmB,OAAA7iB,EAAK8iB,aAAaD,KACtG7iB,EAAK+iB,qBAAuBxhB,EAAMyhB,wBAAwB5iB,IAAI,SAAA6iB,GACrDjjB,EAAKkjB,kBAIND,EAAKvc,OAAShM,EAAAyoB,mBAAmBC,SACjCpjB,EAAKkjB,gBAAgBG,gBAAgBJ,EAAKK,OAG9CL,EAAKM,yBAA0B,KAGnCvjB,EAAKwB,eAAeoC,MAAM,KAAM5D,GAEhCA,EAAKwjB,UAAW,EAEX3jB,GAAUC,IACXE,EAAKyjB,gBAAkBliB,EAAMuc,YAAY4F,mBAAmBtjB,IAAI,WAAM,OAAAJ,EAAK2jB,cAC3E3jB,EAAK2jB,aAGT3jB,EAAK0iB,SAASnD,SAAU,OAgehC,OAltB4CpT,EAAAmK,EAAAvK,GA4CxC5S,OAAAC,eAAWkd,EAAAjc,UAAA,mBAAX,WACI,OAAOS,KAAK2nB,kBAGhB,SAAuB/oB,GACfA,IAAUoB,KAAK2nB,eAInB3nB,KAAK2nB,aAAe/oB,EAEpBoB,KAAK6oB,8CAITxqB,OAAAC,eAAWkd,EAAAjc,UAAA,kBAAX,WACI,OAAOS,KAAKgT,iBAGhB,SAAsBpU,GACdoB,KAAKgT,cAAgBpU,IAIzBoB,KAAKgT,YAAcpU,EACnBoB,KAAK0I,gDAQTrK,OAAAC,eAAWkd,EAAAjc,UAAA,kBAAX,WACI,OAAOS,KAAKsnB,iBAGhB,SAAsB1oB,GACdoB,KAAKsnB,cAAgB1oB,IAIzBoB,KAAKsnB,YAAc1oB,EACnBoB,KAAK0I,cACL1I,KAAK0G,eAAeiC,oDAQxBtK,OAAAC,eAAWkd,EAAAjc,UAAA,mBAAX,WACI,OAAOS,KAAKunB,kBAGhB,SAAuB3oB,GACfoB,KAAKunB,eAAiB3oB,IAI1BoB,KAAKunB,aAAe3oB,EACpBoB,KAAK0I,cACL1I,KAAK0G,eAAeiC,oDAOxBtK,OAAAC,eAAWkd,EAAAjc,UAAA,wBAAX,WACI,OAAOS,KAAKwnB,uBAGhB,SAA4B5oB,GACpBoB,KAAKwnB,oBAAsB5oB,IAI/BoB,KAAKwnB,kBAAoB5oB,EACzBoB,KAAK0I,cACL1I,KAAK0G,eAAeiC,oDAOxBtK,OAAAC,eAAWkd,EAAAjc,UAAA,yBAAX,WACI,OAAOS,KAAKynB,wBAGhB,SAA6B7oB,GACrBoB,KAAKynB,qBAAuB7oB,IAIhCoB,KAAKynB,mBAAqB7oB,EAC1BoB,KAAK6oB,8CAMTxqB,OAAAC,eAAWkd,EAAAjc,UAAA,aAAX,WACI,OAAOS,KAAK8oB,iDAMhBzqB,OAAAC,eAAWkd,EAAAjc,UAAA,qBAAX,WACI,OAAOS,KAAK0G,gDAMhBrI,OAAAC,eAAWkd,EAAAjc,UAAA,sBAAX,WACI,OAAOS,KAAKooB,qBAGhB,SAA0B3W,GAClBzR,KAAKooB,iBAAmB3W,IAIxBzR,KAAKooB,iBACLpoB,KAAKooB,gBAAgBW,SAGrBtX,GACAA,EAAQuX,UAGZhpB,KAAKooB,gBAAkB3W,oCAM3BpT,OAAAC,eAAWkd,EAAAjc,UAAA,oBAAX,WACI,OAAKS,KAAKipB,QAGDjpB,KAAKipB,MAAMC,kBAGxB,SAAwBtqB,GACfoB,KAAKipB,OAGNjpB,KAAKipB,MAAMC,gBAAkBtqB,IAGjCoB,KAAKipB,MAAMC,cAAgBtqB,oCAmDxB4c,EAAAjc,UAAA4pB,qBAAP,SAA4BC,EAAkCC,GACrDA,IACDA,EAAYrpB,KAAK0G,gBAGrB,IAAkB,IAAAyL,EAAA,EAAAC,EAAAiX,EAAUnW,SAAVf,EAAAC,EAAA3B,OAAA0B,IAAoB,CAAjC,IAAIgB,EAAKf,EAAAD,GACAgB,EAAOD,SACblT,KAAKmpB,qBAAqBC,EAAkBjW,GAGhDiW,EAAKjW,KAONqI,EAAAjc,UAAAmJ,YAAP,WACI1I,KAAKsB,UAAW,EAEhBtB,KAAKmpB,qBAAqB,SAAC1X,GACnBA,EAAQ6X,yBACR7X,EAAQxM,qBAUbuW,EAAAjc,UAAAgqB,YAAP,WACI,OAAO,IAAI3C,EAAAD,MAAM3mB,OAQdwb,EAAAjc,UAAAmS,WAAP,SAAkBD,GAGd,OAFAzR,KAAK0G,eAAegL,WAAWD,GAExBzR,MAQJwb,EAAAjc,UAAAsO,cAAP,SAAqB4D,GAEjB,OADAzR,KAAK0G,eAAemH,cAAc4D,GAC3BzR,MAMJwb,EAAAjc,UAAAoO,QAAP,WACI,IAAIlH,EAAQzG,KAAK0c,WAEZjW,IAILA,EAAMqhB,+BAA+B1iB,OAAOpF,KAAK6nB,iBAE7C7nB,KAAK2oB,iBACLliB,EAAMuc,YAAY4F,mBAAmBxjB,OAAOpF,KAAK2oB,iBAGjD3oB,KAAKwpB,sBACL/iB,EAAMgjB,uBAAuBrkB,OAAOpF,KAAKwpB,sBAGzCxpB,KAAK0pB,kBACLjjB,EAAMkjB,oBAAoBvkB,OAAOpF,KAAK0pB,kBAGtC1pB,KAAKioB,sBACLxhB,EAAMyhB,wBAAwB9iB,OAAOpF,KAAKioB,sBAG1CjoB,KAAK4pB,2BACLnjB,EAAMuc,YAAY6G,6BAA6BzkB,OAAOpF,KAAK4pB,2BAG3D5pB,KAAK8oB,kBACL9oB,KAAK8oB,gBAAgBrD,QAAU,KAC/BzlB,KAAK8oB,gBAAgBnb,UACrB3N,KAAK8oB,gBAAkB,MAG3B9oB,KAAK0G,eAAeiH,UAEpBsD,EAAA1R,UAAMoO,QAAO7P,KAAAkC,QAGTwb,EAAAjc,UAAAspB,UAAR,WACI,IAAIpiB,EAAQzG,KAAK0c,WAEjB,GAAKjW,EAAL,CAKA,IAAIsc,EAAStc,EAAMuc,YACf8G,EAAc9pB,KAAKgQ,UACnB+Z,EAAchH,EAAOiH,iBAAmBhqB,KAAK2nB,aAC7CsC,EAAelH,EAAOmH,kBAAoBlqB,KAAK2nB,aAE/C3nB,KAAKynB,qBACDznB,KAAKsnB,aACL2C,EAAgBA,EAAejqB,KAAKsnB,YAAeyC,EACnDA,EAAc/pB,KAAKsnB,aACZtnB,KAAKunB,eACZwC,EAAeA,EAAc/pB,KAAKunB,aAAgB0C,EAClDA,EAAejqB,KAAKunB,eAIxBuC,EAAY/kB,QAAUglB,GAAeD,EAAY9kB,SAAWilB,IAC5DjqB,KAAKmqB,QAAQJ,EAAaE,GAE1BjqB,KAAK0I,eAED1I,KAAKsnB,aAAetnB,KAAKunB,eACzBvnB,KAAK0G,eAAeiC,qBAMzB6S,EAAAjc,UAAAyH,mBAAP,SAA0BP,GACtB,IAAIsc,EAAStc,EAAMuc,YACnB,OAAOhjB,KAAKonB,oBAAoBgD,SAASrH,EAAOiH,iBAAkBjH,EAAOmH,oBAStE1O,EAAAjc,UAAA8qB,qBAAP,SAA4B7jB,EAAmB8jB,GAC3C,IAAI7jB,EAAQzG,KAAK0c,WAEjB,IAAKjW,EACD,OAAO7G,EAAA6C,QAAQC,OAGnB,IAAIqE,EAAiB/G,KAAKgH,mBAAmBP,GACzCQ,EAAoBrH,EAAAsH,QAAQC,QAAQX,EAAU8jB,EAAa7jB,EAAMY,qBAAsBN,GAI3F,OAFAE,EAAkBqO,aAAatV,KAAKuqB,aAE7B,IAAI3qB,EAAA6C,QAAQwE,EAAkBb,EAAGa,EAAkBZ,IAGtDmV,EAAAjc,UAAAyoB,aAAR,SAAqBD,GACjB,IAAI/nB,KAAK8oB,iBACuD,IAAvDf,EAAOyC,UAAYxqB,KAAK8oB,gBAAgB0B,WADjD,CAMA,GAAIxqB,KAAKmnB,eAAiBnnB,KAAK8H,gBAAgB2I,OAAQ,CACnD,IAAIhK,EAAQzG,KAAK0c,WAEjB,IAAKjW,EACD,OAKJ,IAFA,IAAIM,EAAiB/G,KAAKgH,mBAAmBP,GAEzB0L,EAAA,EAAAC,EAAApS,KAAK8H,gBAALqK,EAAAC,EAAA3B,OAAA0B,IAAsB,CAArC,IAAIV,EAAOW,EAAAD,GACZ,GAAKV,EAAQ1F,UAAb,CAIA,IAAInE,EAAO6J,EAAQzJ,YAEnB,GAAKJ,IAAQA,EAAK6iB,aAAlB,CAQA,IAAIjkB,EAAWoB,EAAKsd,kBAAkBwF,eAAeC,OACjD1jB,EAAoBrH,EAAAsH,QAAQC,QAAQX,EAAUoB,EAAKgjB,iBAAkBnkB,EAAMY,qBAAsBN,GAEjGE,EAAkBM,EAAI,GAAKN,EAAkBM,EAAI,EACjDkK,EAAQjK,eAAgB,GAG5BiK,EAAQjK,eAAgB,EAExBP,EAAkBqO,aAAatV,KAAKuqB,aACpC9Y,EAAQnK,yBAAyBL,SAjB7BrH,EAAA6H,MAAM8M,aAAa,WACf9C,EAAQ9J,aAAa,WAoBhC3H,KAAKsB,UAAatB,KAAK0G,eAAeuc,WAG3CjjB,KAAKsB,UAAW,EAEhBtB,KAAK6qB,UACL7qB,KAAK8qB,QAAO,EAAM9qB,KAAK8b,gBAGnBN,EAAAjc,UAAAsrB,QAAR,WACI,IAAIf,EAAc9pB,KAAKgQ,UACnB+Z,EAAcD,EAAY/kB,MAC1BklB,EAAeH,EAAY9kB,OAG3BiE,EAAUjJ,KAAKma,aACnBlR,EAAQ8hB,UAAU,EAAG,EAAGhB,EAAaE,GACjCjqB,KAAKgT,cACL/J,EAAQwK,OACRxK,EAAQY,UAAY7J,KAAKgT,YACzB/J,EAAQuK,SAAS,EAAG,EAAGuW,EAAaE,GACpChhB,EAAQ8K,WAIZ9K,EAAQW,KAAO,aACfX,EAAQmP,YAAc,QACtB,IAAI4S,EAAU,IAAInrB,EAAAQ,QAAQ,EAAG,EAAG0pB,EAAaE,GAC7CjqB,KAAK0G,eAAe6E,MAAMyf,EAAS/hB,IAG/BuS,EAAAjc,UAAA0rB,WAAR,SAAmB7kB,EAAWC,EAAWuF,EAAcC,EAAmBC,GACtE,IAAIrF,EAAQzG,KAAK0c,WAEjB,GAAKjW,EAAL,CAIA,IAAIsc,EAAStc,EAAMuc,YACf8G,EAAc9pB,KAAKgQ,UAEnBhQ,KAAKmnB,gBACL/gB,GAAS0jB,EAAY/kB,MAAQge,EAAOiH,iBACpC3jB,GAASyjB,EAAY9kB,OAAS+d,EAAOmH,mBAGrClqB,KAAKknB,kBAAkBrb,GACvB7L,KAAKknB,kBAAkBrb,GAAWG,oBAAoBJ,EAAMxF,EAAGC,EAAGwF,EAAWC,IAI5E9L,KAAK0G,eAAeiF,gBAAgBvF,EAAGC,EAAGuF,EAAMC,EAAWC,IAExDF,IAAShM,EAAAkN,kBAAkBC,cACvB/M,KAAKiN,iBAAiBpB,IACtB7L,KAAKiN,iBAAiBpB,GAAWS,cAActM,KAAKiN,iBAAiBpB,WAGlE7L,KAAKiN,iBAAiBpB,IAIrC7L,KAAKkrB,kBAIF1P,EAAAjc,UAAA4rB,kCAAP,SAAyCC,EAAwC3Z,GAC7E,IAAK,IAAI5F,KAAauf,EAAM,CACxB,GAAKA,EAAK5rB,eAAeqM,GAIHuf,EAAKvf,KACH4F,UACb2Z,EAAKvf,KAMjB2P,EAAAjc,UAAA+T,0BAAP,SAAiC7B,GAC7BzR,KAAKmrB,kCAAkCnrB,KAAKmN,iBAAkBsE,GAC9DzR,KAAKmrB,kCAAkCnrB,KAAKiN,iBAAkBwE,IAI3D+J,EAAAjc,UAAA+d,OAAP,eAAApY,EAAAlF,KACQyG,EAAQzG,KAAK0c,WACZjW,IAILzG,KAAKwpB,qBAAuB/iB,EAAMgjB,uBAAuBnkB,IAAI,SAAC+lB,EAAIC,GAC9D,IAAI7kB,EAAO8kB,kBAAkCF,EAAQ,MAAGxf,aAIpDwf,EAAGzf,OAAShM,EAAAkN,kBAAkBC,aAC3Bse,EAAGzf,OAAShM,EAAAkN,kBAAkBO,WAC9Bge,EAAGzf,OAAShM,EAAAkN,kBAAkBI,cAIhCzG,EAAL,CAIA,IAAIshB,EAASthB,EAAM+kB,wBAA0B/kB,EAAMglB,aAEnD,GAAK1D,EAAL,CAGA,IAAIhF,EAAStc,EAAMuc,YACf0I,EAAW3D,EAAO2D,SAClBtlB,GAAKK,EAAMklB,SAAW5I,EAAO6I,0BAA4BF,EAAStlB,EAAI2c,EAAOiH,kBAAoB0B,EAAS3mB,MAC1GsB,GAAKI,EAAMolB,SAAW9I,EAAO6I,0BAA4BF,EAASrlB,EAAI0c,EAAOmH,mBAAqBwB,EAAS1mB,OAE/GE,EAAKwG,qBAAsB,EAC3BxG,EAAK+lB,WAAW7kB,EAAGC,EAAGglB,EAAGzf,KAAOyf,EAAG7C,MAAuB3c,WAAa,EAAGwf,EAAG7C,MAAMsD,QAEnFT,EAAG5C,wBAA0BvjB,EAAKwG,wBAGtC1L,KAAK+rB,sBAAsBtlB,KAQxB+U,EAAAjc,UAAAysB,aAAP,SAAoBpkB,EAAoBqkB,GAAxC,IAAA/mB,EAAAlF,UAAwC,IAAAisB,OAAA,GACpC,IAAIxlB,EAAQzG,KAAK0c,WACZjW,IAGLzG,KAAK0pB,iBAAmBjjB,EAAMkjB,oBAAoBrkB,IAAI,SAAC+lB,EAAIC,GACvD,GAAID,EAAGzf,OAAShM,EAAAkN,kBAAkBC,aAC3Bse,EAAGzf,OAAShM,EAAAkN,kBAAkBO,WAC9Bge,EAAGzf,OAAShM,EAAAkN,kBAAkBI,YAFrC,CAKA,IAAIrB,EAAawf,EAAG7C,MAAuB3c,WAAa,EACxD,GAAIwf,EAAGa,UAAYb,EAAGa,SAASC,KAAOd,EAAGa,SAASE,aAAexkB,EAAM,CACnE,IAAIykB,EAAKhB,EAAGa,SAASI,wBAErB,GAAID,EAAI,CACJ,IAAIE,EAAOrnB,EAAK8K,UAEhB9K,EAAK+lB,WAAWoB,EAAGjmB,EAAImmB,EAAKxnB,OAAQ,EAAMsnB,EAAGhmB,GAAKkmB,EAAKvnB,OAAQqmB,EAAGzf,KAAMC,EAAWwf,EAAG7C,MAAMsD,cAEzFT,EAAGzf,OAAShM,EAAAkN,kBAAkBO,WACjCnI,EAAKiI,iBAAiBtB,IACtB3G,EAAKiI,iBAAiBtB,GAAWe,gBAAgBf,UAE9C3G,EAAKiI,iBAAiBtB,GAE7B3G,EAAKsnB,eAAiB,MACfnB,EAAGzf,OAAShM,EAAAkN,kBAAkBC,cACjC7H,EAAK+H,iBAAiBpB,IACtB3G,EAAK+H,iBAAiBpB,GAAWS,cAAcpH,EAAK+H,iBAAiBpB,WAElE3G,EAAK+H,iBAAiBpB,OAIrCjE,EAAK6kB,wBAA0BR,EAC/BjsB,KAAK+rB,sBAAsBtlB,KAOxB+U,EAAAjc,UAAAmtB,mBAAP,SAA0Bjb,GACtBzR,KAAKwsB,eAAiB/a,EACtBzR,KAAKoN,mBAA0BqE,EAC/BzR,KAAK0nB,sBAAuB,GAGxBlM,EAAAjc,UAAA2rB,aAAR,WACI,GAAIlrB,KAAK0nB,qBAGL,OAFA1nB,KAAK0nB,sBAAuB,OAC5B1nB,KAAKoN,mBAA0BpN,KAAKooB,iBAKxC,GAAIpoB,KAAKooB,iBACDpoB,KAAKooB,kBAA0BpoB,KAAKoN,mBAAqB,CACzD,GAAIpN,KAAKoN,mBAAmB9J,iBACxB,OAGJtD,KAAKwsB,eAAiB,OAK1BhR,EAAAjc,UAAAwsB,sBAAR,SAA8BtlB,GAA9B,IAAAvB,EAAAlF,KACIA,KAAK4pB,0BAA4BnjB,EAAMuc,YAAY6G,6BAA6BvkB,IAAI,SAACqnB,GAC7EznB,EAAK+H,iBAAiB0f,EAAa9gB,YACnC3G,EAAK+H,iBAAiB0f,EAAa9gB,WAAWS,cAAcpH,EAAK+H,iBAAiB0f,EAAa9gB,mBAE5F3G,EAAK+H,iBAAiB0f,EAAa9gB,WAEtC3G,EAAKiI,iBAAiBwf,EAAa9gB,YACnC3G,EAAKiI,iBAAiBwf,EAAa9gB,WAAWe,yBAE3C1H,EAAKiI,iBAAiBwf,EAAa9gB,cAapC2P,EAAAoR,cAAd,SAA4BhlB,EAAoB7C,EAAcC,EAAeinB,QAA7B,IAAAlnB,MAAA,WAAc,IAAAC,MAAA,WAAe,IAAAinB,OAAA,GACzE,IAAI/lB,EAAS,IAAIsV,EAAuB5T,EAAK1J,KAAO,0BAA2B6G,EAAOC,EAAQ4C,EAAK8U,YAAY,EAAM9c,EAAA6b,QAAQC,wBAEzHc,EAAW,IAAI5c,EAAA6c,iBAAiB,iCAAkC7U,EAAK8U,YAW3E,OAVAF,EAASqQ,iBAAkB,EAC3BrQ,EAASsQ,aAAeltB,EAAAgb,OAAOG,QAC/ByB,EAASG,cAAgB/c,EAAAgb,OAAOG,QAChCyB,EAASP,gBAAkB/V,EAC3BsW,EAASuQ,eAAiB7mB,EAE1B0B,EAAK4U,SAAWA,EAEhBtW,EAAO8lB,aAAapkB,EAAMqkB,GAEnB/lB,GAeGsV,EAAAwR,mBAAd,SAAiC9uB,EAAc+uB,EAA4BxmB,EAA+BymB,QAA3D,IAAAD,OAAA,QAA4B,IAAAxmB,MAAA,WAA+B,IAAAymB,MAAWttB,EAAA6b,QAAQ0R,uBACzH,IAAIjnB,EAAS,IAAIsV,EAAuBtd,EAAM,EAAG,EAAGuI,GAAO,EAAOymB,GAG9DjE,EAAQ,IAAIrpB,EAAAwtB,MAAMlvB,EAAO,SAAU,KAAMuI,GAAQwmB,GASrD,OARAhE,EAAMxD,QAAUvf,EAEhBA,EAAO4iB,gBAAkBG,EACzB/iB,EAAOihB,eAAgB,EAGvBjhB,EAAOoX,SAEApX,GAEfsV,EAltBA,CAA4C5b,EAAAytB,gBAA/BpwB,EAAAue,wGC5Bb,IAAA7b,EAAAlC,EAAA,GAEAmC,EAAAnC,EAAA,GAOA6vB,EAAA,WAmBI,SAAAA,EAAYC,GACRvtB,KAAKwtB,WAAaD,EAElBvtB,KAAKytB,GAAK,IAAI9tB,EAAAgB,aAAa,GAC3BX,KAAK0tB,GAAK,IAAI/tB,EAAAgB,aAAa,GAE3BX,KAAK2tB,OAAS,IAAI/tB,EAAA6C,QAAQ,EAAG,GAkHrC,OA9GIpE,OAAAC,eAAWgvB,EAAA/tB,UAAA,SAAX,WACI,OAAOS,KAAKytB,GAAG9oB,SAAS3E,KAAKwtB,WAAW5oB,YAG5C,SAAahG,GACLoB,KAAKytB,GAAG9oB,SAAS3E,KAAKwtB,WAAW5oB,SAAWhG,GAI5CoB,KAAKytB,GAAG5oB,WAAWjG,IACnBoB,KAAKwtB,WAAW/oB,gDAKxBpG,OAAAC,eAAWgvB,EAAA/tB,UAAA,SAAX,WACI,OAAOS,KAAK0tB,GAAG/oB,SAAS3E,KAAKwtB,WAAW5oB,YAG5C,SAAahG,GACLoB,KAAK0tB,GAAG/oB,SAAS3E,KAAKwtB,WAAW5oB,SAAWhG,GAI5CoB,KAAK0tB,GAAG7oB,WAAWjG,IACnBoB,KAAKwtB,WAAW/oB,gDAKxBpG,OAAAC,eAAWgvB,EAAA/tB,UAAA,eAAX,WACI,OAAOS,KAAK4tB,cAGhB,SAAmBhvB,GACXoB,KAAK4tB,WAAahvB,IAIlBoB,KAAK4tB,UAAY5tB,KAAK6tB,mBACtB7tB,KAAK4tB,SAASxpB,kBAAkBgB,OAAOpF,KAAK6tB,kBAE5C7tB,KAAK6tB,iBAAmB,MAG5B7tB,KAAK4tB,SAAWhvB,EAEZoB,KAAK4tB,WACL5tB,KAAK6tB,iBAAmB7tB,KAAK4tB,SAASxpB,kBAAkBkB,IAAItF,KAAKwtB,WAAWM,gBAGhF9tB,KAAKwtB,WAAW/oB,iDAIpBpG,OAAAC,eAAWgvB,EAAA/tB,UAAA,YAAX,WACI,OAAOS,KAAK+tB,WAGhB,SAAgBnvB,GACRoB,KAAK+tB,QAAUnvB,IAIfoB,KAAK+tB,OAAS/tB,KAAKguB,eACnBhuB,KAAK+tB,MAAMrR,WAAWuR,8BAA8B7oB,OAAOpF,KAAKguB,eAGpEhuB,KAAK+tB,MAAQnvB,EAEToB,KAAK+tB,QACL/tB,KAAKguB,cAAgBhuB,KAAK+tB,MAAMrR,WAAWuR,8BAA8B3oB,IAAItF,KAAKwtB,WAAWM,gBAGjG9tB,KAAKwtB,WAAW/oB,iDAOb6oB,EAAA/tB,UAAA6J,UAAP,WAGI,OAFApJ,KAAK2tB,OAAS3tB,KAAKkuB,kBAEZluB,KAAK2tB,QAGRL,EAAA/tB,UAAA2uB,gBAAR,WACI,GAAkB,MAAdluB,KAAK+tB,MACL,OAAO/tB,KAAKwtB,WAAW5oB,MAAMylB,qBAAqBrqB,KAAK+tB,MAAM7I,kBAAkBwF,eAAeC,OAAQ3qB,KAAK+tB,MAAMnD,kBAEhH,GAAqB,MAAjB5qB,KAAK4tB,SACV,OAAO,IAAIhuB,EAAA6C,QAAQzC,KAAK4tB,SAASxN,QAASpgB,KAAK4tB,SAASvN,SAGxD,IAAItX,EAAY/I,KAAKwtB,WAAW5oB,MAE5BupB,EAAiBnuB,KAAKytB,GAAG3oB,gBAAgBiE,EAAMqlB,OAAOrlB,EAAKslB,QAAQtpB,QACnEupB,EAAiBtuB,KAAK0tB,GAAG5oB,gBAAgBiE,EAAMqlB,OAAOrlB,EAAKslB,QAAQrpB,SAEvE,OAAO,IAAIpF,EAAA6C,QAAQ0rB,EAAQG,IAK5BhB,EAAA/tB,UAAAoO,QAAP,WACI3N,KAAKyR,QAAU,KACfzR,KAAK4H,KAAO,MAGpB0lB,EA3IA,GAAarwB,EAAAqwB,uaCVb,IAAA3a,EAAAlV,EAAA,GAEAkC,EAAAlC,EAAA,GACAmC,EAAAnC,EAAA,GAMA8wB,EAAA,SAAAtd,GA4NI,SAAAsd,EAAmBrwB,EAAemQ,QAAA,IAAAA,MAAA,IAAlC,IAAAnJ,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OA3NXgH,EAAA+R,MAAQ,GACR/R,EAAAspB,iBAAmB,GACnBtpB,EAAA8N,YAAc,UACd9N,EAAAupB,mBAAqB,UACrBvpB,EAAAwpB,kBAAoB,OACpBxpB,EAAAypB,WAAa,EACbzpB,EAAA0pB,QAAU,IAAIjvB,EAAAgB,aAAa,GAAIhB,EAAAgB,aAAaC,gBAC5CsE,EAAA2pB,mBAAoB,EACpB3pB,EAAA4pB,UAAY,IAAInvB,EAAAgB,aAAa,EAAGhB,EAAAgB,aAAaG,qBAAqB,GAClEoE,EAAA6pB,YAAa,EAEb7pB,EAAA8pB,cAAe,EACf9pB,EAAA+pB,cAAgB,EAIhB/pB,EAAAgqB,UAAW,EACXhqB,EAAAiqB,SAAU,EACVjqB,EAAAkqB,YAAc,GAGflqB,EAAAmqB,cAAgB,qBAGhBnqB,EAAAwS,wBAA0B,IAAI9X,EAAAkE,WAE9BoB,EAAAoqB,yBAA2B,IAAI1vB,EAAAkE,WAE/BoB,EAAAqqB,kBAAoB,IAAI3vB,EAAAkE,WAExBoB,EAAAsqB,iBAAmB,IAAI5vB,EAAAkE,WAgM1BoB,EAAKmJ,KAAOA,IAiTpB,OAhhB+BgD,EAAAkd,EAAAtd,GAkC3B5S,OAAAC,eAAWiwB,EAAAhvB,UAAA,gBAAX,WACI,OAAOS,KAAK8uB,UAAUnqB,SAAS3E,KAAK4E,YAQxC,SAAoBhG,GACZoB,KAAK8uB,UAAUnqB,SAAS3E,KAAK4E,SAAWhG,GAIxCoB,KAAK8uB,UAAUjqB,WAAWjG,IAC1BoB,KAAKyE,gDAVbpG,OAAAC,eAAWiwB,EAAAhvB,UAAA,wBAAX,WACI,OAAOS,KAAK8uB,UAAUhqB,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBuD,wCAchF1G,OAAAC,eAAWiwB,EAAAhvB,UAAA,cAAX,WACI,OAAOS,KAAK4uB,QAAQjqB,SAAS3E,KAAK4E,YAQtC,SAAkBhG,GACVoB,KAAK4uB,QAAQjqB,SAAS3E,KAAK4E,SAAWhG,GAItCoB,KAAK4uB,QAAQ/pB,WAAWjG,IACxBoB,KAAKyE,gDAVbpG,OAAAC,eAAWiwB,EAAAhvB,UAAA,sBAAX,WACI,OAAOS,KAAK4uB,QAAQ9pB,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBuD,wCAc9E1G,OAAAC,eAAWiwB,EAAAhvB,UAAA,wBAAX,WACI,OAAOS,KAAK6uB,uBAGhB,SAA4BjwB,GACpBoB,KAAK6uB,oBAAsBjwB,IAI/BoB,KAAK6uB,kBAAoBjwB,EACzBoB,KAAKyE,iDAITpG,OAAAC,eAAWiwB,EAAAhvB,UAAA,iBAAX,WACI,OAAOS,KAAK2uB,gBAGhB,SAAqB/vB,GACboB,KAAK2uB,aAAe/vB,IAIxBoB,KAAK2uB,WAAa/vB,EAClBoB,KAAKyE,iDAITpG,OAAAC,eAAWiwB,EAAAhvB,UAAA,yBAAX,WACI,OAAOS,KAAKyuB,wBAGhB,SAA6B7vB,GACrBoB,KAAKyuB,qBAAuB7vB,IAIhCoB,KAAKyuB,mBAAqB7vB,EAC1BoB,KAAKyE,iDAITpG,OAAAC,eAAWiwB,EAAAhvB,UAAA,kBAAX,WACI,OAAOS,KAAKgT,iBAGhB,SAAsBpU,GACdoB,KAAKgT,cAAgBpU,IAIzBoB,KAAKgT,YAAcpU,EACnBoB,KAAKyE,iDAITpG,OAAAC,eAAWiwB,EAAAhvB,UAAA,wBAAX,WACI,OAAOS,KAAK0uB,uBAGhB,SAA4B9vB,GACpBoB,KAAK0uB,oBAAsB9vB,IAI/BoB,KAAK0uB,kBAAoB9vB,EACzBoB,KAAKyE,iDAITpG,OAAAC,eAAWiwB,EAAAhvB,UAAA,uBAAX,WACI,OAAOS,KAAKwuB,sBAGhB,SAA2B5vB,GACnBoB,KAAKwuB,mBAAqB5vB,IAG9BoB,KAAKwuB,iBAAmB5vB,EACxBoB,KAAKyE,iDAITpG,OAAAC,eAAWiwB,EAAAhvB,UAAA,eAAX,WACI,OAAOS,KAAKkvB,cAGhB,SAAmBO,GACfzvB,KAAKkvB,SAAWO,mCAIpBpxB,OAAAC,eAAWiwB,EAAAhvB,UAAA,cAAX,WACI,OAAOS,KAAKmvB,aAGhB,SAAkBM,GACdzvB,KAAKmvB,QAAUM,mCAInBpxB,OAAAC,eAAWiwB,EAAAhvB,UAAA,kBAAX,WACI,OAAOS,KAAKovB,iBAGhB,SAAsBlwB,GAClBc,KAAKovB,YAAclwB,mCAIvBb,OAAAC,eAAWiwB,EAAAhvB,UAAA,YAAX,WACI,OAAOS,KAAKiX,WAGhB,SAAgBrY,GACRoB,KAAKiX,QAAUrY,IAGnBoB,KAAKiX,MAAQrY,EACboB,KAAKyE,eAELzE,KAAK0X,wBAAwBlN,gBAAgBxK,wCAIjD3B,OAAAC,eAAWiwB,EAAAhvB,UAAA,aAAX,WACI,OAAOS,KAAKa,OAAO8D,SAAS3E,KAAK4E,YAGrC,SAAiBhG,GACToB,KAAKa,OAAO8D,SAAS3E,KAAK4E,SAAWhG,IAIrCoB,KAAKa,OAAOgE,WAAWjG,IACvBoB,KAAKyE,eAGTzE,KAAK0vB,kBAAmB,oCAerBnB,EAAAhvB,UAAAwpB,OAAP,WACI/oB,KAAK+uB,YAAa,EAClB/uB,KAAK2vB,YAAc,KACnB3vB,KAAKivB,cAAgB,EACrBW,aAAa5vB,KAAK6vB,eAClB7vB,KAAKyE,eAELzE,KAAKwvB,iBAAiBhlB,gBAAgBxK,OAInCuuB,EAAAhvB,UAAAypB,QAAP,WASI,GARAhpB,KAAK2vB,YAAc,KACnB3vB,KAAK+uB,YAAa,EAClB/uB,KAAKgvB,cAAe,EACpBhvB,KAAKivB,cAAgB,EACrBjvB,KAAKyE,eAELzE,KAAKuvB,kBAAkB/kB,gBAAgBxK,OAEQ,IAA3C8vB,UAAUC,UAAUhoB,QAAQ,UAAkB,CAC9C,IAAInJ,EAAQoxB,OAAOhwB,KAAKqvB,eAMxB,OAJc,OAAVzwB,IACAoB,KAAKqO,KAAOzP,QAEhBoB,KAAK4E,MAAM4nB,eAAiB,QAK1B+B,EAAAhvB,UAAA+E,aAAV,WACI,MAAO,aAIJiqB,EAAAhvB,UAAA0wB,WAAP,SAAkBC,EAAiBhxB,GAE/B,OAAQgxB,GACJ,KAAK,GACDhxB,EAAM,IACN,MACJ,KAAK,EACD,GAAIc,KAAKiX,OAASjX,KAAKiX,MAAMxG,OAAS,EAClC,GAA2B,IAAvBzQ,KAAKivB,cACLjvB,KAAKqO,KAAOrO,KAAKiX,MAAMkZ,OAAO,EAAGnwB,KAAKiX,MAAMxG,OAAS,QAEjD2f,EAAiBpwB,KAAKiX,MAAMxG,OAASzQ,KAAKivB,eACzB,IACjBjvB,KAAKqO,KAAOrO,KAAKiX,MAAMqC,MAAM,EAAG8W,EAAiB,GAAKpwB,KAAKiX,MAAMqC,MAAM8W,IAInF,OACJ,KAAK,GACD,GAAIpwB,KAAKiX,OAASjX,KAAKiX,MAAMxG,OAAS,EAAG,CACrC,IAAI2f,EAAiBpwB,KAAKiX,MAAMxG,OAASzQ,KAAKivB,cAC9CjvB,KAAKqO,KAAOrO,KAAKiX,MAAMqC,MAAM,EAAG8W,GAAkBpwB,KAAKiX,MAAMqC,MAAM8W,EAAiB,GACpFpwB,KAAKivB,gBAET,OACJ,KAAK,GAED,YADAjvB,KAAK4E,MAAM4nB,eAAiB,MAEhC,KAAK,GAID,OAHAxsB,KAAKivB,cAAgB,EACrBjvB,KAAKgvB,cAAe,OACpBhvB,KAAKyE,eAET,KAAK,GAID,OAHAzE,KAAKivB,cAAgBjvB,KAAKiX,MAAMxG,OAChCzQ,KAAKgvB,cAAe,OACpBhvB,KAAKyE,eAET,KAAK,GAOD,OANAzE,KAAKivB,gBACDjvB,KAAKivB,cAAgBjvB,KAAKiX,MAAMxG,SAChCzQ,KAAKivB,cAAgBjvB,KAAKiX,MAAMxG,QAEpCzQ,KAAKgvB,cAAe,OACpBhvB,KAAKyE,eAET,KAAK,GAOD,OANAzE,KAAKivB,gBACDjvB,KAAKivB,cAAgB,IACrBjvB,KAAKivB,cAAgB,GAEzBjvB,KAAKgvB,cAAe,OACpBhvB,KAAKyE,eAET,KAAK,IAED,YADAzE,KAAKqwB,SAAU,GAKvB,GAAInxB,KACe,IAAbgxB,GACe,KAAZA,GACAA,EAAU,IAAMA,EAAU,IAC1BA,EAAU,IAAMA,EAAU,IAC1BA,EAAU,KAAOA,EAAU,KAC3BA,EAAU,KAAOA,EAAU,KAC3BA,EAAU,IAAMA,EAAU,OAC/BlwB,KAAKovB,YAAclwB,EACnBc,KAAKsvB,yBAAyB9kB,gBAAgBxK,MAC9Cd,EAAMc,KAAKovB,YACPpvB,KAAKmvB,SACL,GAA2B,IAAvBnvB,KAAKivB,cACLjvB,KAAKqO,MAAQnP,MACV,CACH,IAAIoxB,EAAiBtwB,KAAKiX,MAAMxG,OAASzQ,KAAKivB,cAE9CjvB,KAAKqO,KAAOrO,KAAKiX,MAAMqC,MAAM,EAAGgX,GAAkBpxB,EAAMc,KAAKiX,MAAMqC,MAAMgX,KAOlF/B,EAAAhvB,UAAAgpB,gBAAP,SAAuBgI,GACnBvwB,KAAKiwB,WAAWM,EAAIL,QAASK,EAAIrxB,MAG9BqvB,EAAAhvB,UAAAgM,MAAP,SAAavB,EAAwBf,GAArC,IAAA/D,EAAAlF,KAII,GAHAiJ,EAAQwK,OAERzT,KAAK2J,aAAaV,GACdjJ,KAAK+J,iBAAiBC,EAAef,GAAU,EAE3CjJ,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQvF,YAAc1D,KAAK0D,YAC3BuF,EAAQxF,WAAazD,KAAKyD,WAC1BwF,EAAQ1F,cAAgBvD,KAAKuD,cAC7B0F,EAAQzF,cAAgBxD,KAAKwD,eAI7BxD,KAAK+uB,WACD/uB,KAAKyuB,qBACLxlB,EAAQY,UAAY7J,KAAKyuB,mBAEzBxlB,EAAQuK,SAASxT,KAAKI,gBAAgB0F,KAAM9F,KAAKI,gBAAgB2F,IAAK/F,KAAKI,gBAAgB2E,MAAO/E,KAAKI,gBAAgB4E,SAEpHhF,KAAKgT,cACZ/J,EAAQY,UAAY7J,KAAKgT,YAEzB/J,EAAQuK,SAASxT,KAAKI,gBAAgB0F,KAAM9F,KAAKI,gBAAgB2F,IAAK/F,KAAKI,gBAAgB2E,MAAO/E,KAAKI,gBAAgB4E,UAGvHhF,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQxF,WAAa,EACrBwF,EAAQ1F,cAAgB,EACxB0F,EAAQzF,cAAgB,GAGvBxD,KAAKuE,cACNvE,KAAKuE,YAAcoO,EAAA5S,QAAQ2N,eAAezE,EAAQW,OAItD,IAAI4mB,EAAexwB,KAAKI,gBAAgB0F,KAAO9F,KAAK4uB,QAAQ9pB,gBAAgB9E,KAAK4E,MAAOoF,EAAcjF,OAClG/E,KAAKywB,QACLxnB,EAAQY,UAAY7J,KAAKywB,OAG7B,IAAIpiB,EAAOrO,KAAK0wB,kBAAkB1wB,KAAKiX,OAElCjX,KAAK+uB,YAAe/uB,KAAKiX,QAASjX,KAAKwuB,mBACxCngB,EAAOrO,KAAKwuB,iBAERxuB,KAAK0uB,oBACLzlB,EAAQY,UAAY7J,KAAK0uB,oBAIjC1uB,KAAK2wB,WAAa1nB,EAAQoQ,YAAYhL,GAAMtJ,MAC5C,IAAI6rB,EAA8E,EAAhE5wB,KAAK4uB,QAAQ9pB,gBAAgB9E,KAAK4E,MAAOoF,EAAcjF,OACrE/E,KAAK6uB,oBACL7uB,KAAK+E,MAAQyD,KAAKqC,IAAI7K,KAAK8uB,UAAUhqB,gBAAgB9E,KAAK4E,MAAOoF,EAAcjF,OAAQ/E,KAAK2wB,WAAaC,GAAe,MAG5H,IAAIlX,EAAQ1Z,KAAKuE,YAAY6K,QAAUpP,KAAKI,gBAAgB4E,OAAShF,KAAKuE,YAAYS,QAAU,EAC5F6rB,EAAiB7wB,KAAKa,OAAOiE,gBAAgB9E,KAAK4E,MAAOoF,EAAcjF,OAAS6rB,EAMpF,GALA3nB,EAAQwK,OACRxK,EAAQ0B,YACR1B,EAAQiC,KAAKslB,EAAcxwB,KAAKI,gBAAgB2F,KAAO/F,KAAKI,gBAAgB4E,OAAShF,KAAKuE,YAAYS,QAAU,EAAG6rB,EAAiB,EAAG7wB,KAAKI,gBAAgB4E,QAC5JiE,EAAQyB,OAEJ1K,KAAK+uB,YAAc/uB,KAAK2wB,WAAaE,EAAgB,CACrD,IAAIC,EAAWN,EAAexwB,KAAK2wB,WAAaE,EAC3C7wB,KAAK2vB,cACN3vB,KAAK2vB,YAAcmB,QAGvB9wB,KAAK2vB,YAAca,EAMvB,GAHAvnB,EAAQgP,SAAS5J,EAAMrO,KAAK2vB,YAAa3vB,KAAKI,gBAAgB2F,IAAM2T,GAGhE1Z,KAAK+uB,WAAY,CAGjB,GAAI/uB,KAAK+wB,mBAAoB,CACzB,IACIC,EADgBhxB,KAAK2vB,YAAc3vB,KAAK2wB,WACC3wB,KAAK+wB,mBAC9CE,EAAc,EAClBjxB,KAAKivB,cAAgB,EACrB,IAAIiC,EAAe,EACnB,GACQlxB,KAAKivB,gBACLiC,EAAe1oB,KAAKC,IAAIuoB,EAAyBC,IAErDjxB,KAAKivB,gBACLgC,EAAchoB,EAAQoQ,YAAYhL,EAAK8hB,OAAO9hB,EAAKoC,OAASzQ,KAAKivB,cAAejvB,KAAKivB,gBAAgBlqB,YAEhGksB,EAAcD,GAA2B3iB,EAAKoC,QAAUzQ,KAAKivB,eAGlEzmB,KAAKC,IAAIuoB,EAAyBC,GAAeC,GACjDlxB,KAAKivB,gBAGTjvB,KAAKgvB,cAAe,EACpBhvB,KAAK+wB,mBAAqB,KAI9B,IAAK/wB,KAAKgvB,aAAc,CACpB,IAAImC,EAAmBnxB,KAAKqO,KAAK8hB,OAAOnwB,KAAKiX,MAAMxG,OAASzQ,KAAKivB,eAC7DmC,EAAoBnoB,EAAQoQ,YAAY8X,GAAkBpsB,MAC1DssB,EAAarxB,KAAK2vB,YAAc3vB,KAAK2wB,WAAaS,EAElDC,EAAab,GACbxwB,KAAK2vB,aAAgBa,EAAea,EACpCA,EAAab,EACbxwB,KAAKyE,gBACE4sB,EAAab,EAAeK,IACnC7wB,KAAK2vB,aAAgBa,EAAeK,EAAiBQ,EACrDA,EAAab,EAAeK,EAC5B7wB,KAAKyE,gBAETwE,EAAQuK,SAAS6d,EAAYrxB,KAAKI,gBAAgB2F,KAAO/F,KAAKI,gBAAgB4E,OAAShF,KAAKuE,YAAYS,QAAU,EAAG,EAAGhF,KAAKuE,YAAYS,QAG7I4qB,aAAa5vB,KAAK6vB,eAClB7vB,KAAK6vB,cAAqByB,WAAW,WACjCpsB,EAAK8pB,cAAgB9pB,EAAK8pB,aAC1B9pB,EAAKT,gBACN,KAGPwE,EAAQ8K,UAGJ/T,KAAK2uB,aACD3uB,KAAKywB,QACLxnB,EAAQmP,YAAcpY,KAAKywB,OAE/BxnB,EAAQkP,UAAYnY,KAAK2uB,WAEzB1lB,EAAQsoB,WAAWvxB,KAAKI,gBAAgB0F,KAAO9F,KAAK2uB,WAAa,EAAG3uB,KAAKI,gBAAgB2F,IAAM/F,KAAK2uB,WAAa,EAC7G3uB,KAAKI,gBAAgB2E,MAAQ/E,KAAK2uB,WAAY3uB,KAAKI,gBAAgB4E,OAAShF,KAAK2uB,aAG7F1lB,EAAQ8K,WAGLwa,EAAAhvB,UAAAgN,eAAP,SAAsBL,EAAiBC,EAAsBN,EAAmBC,GAC5E,QAAKmF,EAAA1R,UAAMgN,eAAczO,KAAAkC,KAACkM,EAAQC,EAAaN,EAAWC,KAI1D9L,KAAK+wB,mBAAqB5kB,EAAY/F,EAClCpG,KAAK4E,MAAM4nB,iBAAmBxsB,MAE9B4vB,aAAa5vB,KAAK6vB,eAClB7vB,KAAKyE,gBACE,IAEXzE,KAAK4E,MAAM4nB,eAAiBxsB,MAErB,KAGJuuB,EAAAhvB,UAAAkN,aAAP,SAAoBP,EAAiBC,EAAsBN,EAAmBC,EAAqBY,GAC/FuE,EAAA1R,UAAMkN,aAAY3O,KAAAkC,KAACkM,EAAQC,EAAaN,EAAWC,EAAaY,IAG1D6hB,EAAAhvB,UAAAmxB,kBAAV,SAA4BriB,GACxB,OAAOA,GAGJkgB,EAAAhvB,UAAAoO,QAAP,WACIsD,EAAA1R,UAAMoO,QAAO7P,KAAAkC,MAEbA,KAAKwvB,iBAAiB5hB,QACtB5N,KAAKuvB,kBAAkB3hB,QACvB5N,KAAK0X,wBAAwB9J,SAErC2gB,EAhhBA,CAA+B5b,EAAA5S,SAAlB9C,EAAAsxB,kaCTb,IAAA3uB,EAAAnC,EAAA,GAKA+O,EAAA,SAAAyE,GAMI,SAAAzE,EAAmB6D,EAERvE,QAAA,IAAAA,MAAA,GAFX,IAAA5G,EAGI+L,EAAAnT,KAAAkC,KAAMqQ,EAAOjK,EAAGiK,EAAOhK,IAAErG,YADlBkF,EAAA4G,gBAGf,OAXqCuF,EAAA7E,EAAAyE,GAWrCzE,EAXA,CAAqC5M,EAAA6C,SAAxBxF,EAAAuP,kBAcb,IAAAnK,EAAA,WAaI,SAAAA,EAAYmvB,EAAaC,EAAaC,EAAaC,EAAaC,EAAaC,GAXtE7xB,KAAAjC,EAAI,IAAI+zB,aAAa,GAYxB9xB,KAAK+xB,WAAWP,EAAKC,EAAKC,EAAKC,EAAKC,EAAKC,GA2KjD,OA9JWxvB,EAAA9C,UAAAwyB,WAAP,SAAkBP,EAAaC,EAAaC,EAAaC,EAAaC,EAAaC,GAI/E,OAHA7xB,KAAKjC,EAAE,GAAKyzB,EAAKxxB,KAAKjC,EAAE,GAAK0zB,EAC7BzxB,KAAKjC,EAAE,GAAK2zB,EAAK1xB,KAAKjC,EAAE,GAAK4zB,EAC7B3xB,KAAKjC,EAAE,GAAK6zB,EAAK5xB,KAAKjC,EAAE,GAAK8zB,EACtB7xB,MAOJqC,EAAA9C,UAAAyyB,YAAP,WACI,OAAOhyB,KAAKjC,EAAE,GAAKiC,KAAKjC,EAAE,GAAKiC,KAAKjC,EAAE,GAAKiC,KAAKjC,EAAE,IAQ/CsE,EAAA9C,UAAAmK,YAAP,SAAmBxD,GACf,IAAI+rB,EAAKjyB,KAAKjC,EAAE,GAAQm0B,EAAKlyB,KAAKjC,EAAE,GAChCo0B,EAAKnyB,KAAKjC,EAAE,GAAQq0B,EAAKpyB,KAAKjC,EAAE,GAChCs0B,EAAKryB,KAAKjC,EAAE,GAAQu0B,EAAKtyB,KAAKjC,EAAE,GAEhCw0B,EAAMvyB,KAAKgyB,cACf,GAAIO,EAAO3yB,EAAA4yB,QAAU5yB,EAAA4yB,QAIjB,OAHAtsB,EAAOnI,EAAE,GAAK,EAAGmI,EAAOnI,EAAE,GAAK,EAC/BmI,EAAOnI,EAAE,GAAK,EAAGmI,EAAOnI,EAAE,GAAK,EAC/BmI,EAAOnI,EAAE,GAAK,EAAGmI,EAAOnI,EAAE,GAAK,EACxBiC,KAGX,IAAIyyB,EAAS,EAAIF,EAEbG,EAAOP,EAAKG,EAAKF,EAAKC,EACtBM,EAAOT,EAAKG,EAAKJ,EAAKK,EAM1B,OAJApsB,EAAOnI,EAAE,GAAKq0B,EAAKK,EAAQvsB,EAAOnI,EAAE,IAAMm0B,EAAKO,EAC/CvsB,EAAOnI,EAAE,IAAMo0B,EAAKM,EAAQvsB,EAAOnI,EAAE,GAAKk0B,EAAKQ,EAC/CvsB,EAAOnI,EAAE,GAAK20B,EAAOD,EAAQvsB,EAAOnI,EAAE,GAAK40B,EAAOF,EAE3CzyB,MASJqC,EAAA9C,UAAA4lB,cAAP,SAAqBlP,EAAiB/P,GAClC,IAAI+rB,EAAKjyB,KAAKjC,EAAE,GAAQm0B,EAAKlyB,KAAKjC,EAAE,GAChCo0B,EAAKnyB,KAAKjC,EAAE,GAAQq0B,EAAKpyB,KAAKjC,EAAE,GAChCs0B,EAAKryB,KAAKjC,EAAE,GAAQu0B,EAAKtyB,KAAKjC,EAAE,GAEhC60B,EAAK3c,EAAMlY,EAAE,GAAQ80B,EAAK5c,EAAMlY,EAAE,GAClC+0B,EAAK7c,EAAMlY,EAAE,GAAQg1B,EAAK9c,EAAMlY,EAAE,GAClCi1B,EAAK/c,EAAMlY,EAAE,GAAQk1B,EAAKhd,EAAMlY,EAAE,GAMtC,OAJAmI,EAAOnI,EAAE,GAAKk0B,EAAKW,EAAKV,EAAKY,EAAI5sB,EAAOnI,EAAE,GAAKk0B,EAAKY,EAAKX,EAAKa,EAC9D7sB,EAAOnI,EAAE,GAAKo0B,EAAKS,EAAKR,EAAKU,EAAI5sB,EAAOnI,EAAE,GAAKo0B,EAAKU,EAAKT,EAAKW,EAC9D7sB,EAAOnI,EAAE,GAAKs0B,EAAKO,EAAKN,EAAKQ,EAAKE,EAAI9sB,EAAOnI,EAAE,GAAKs0B,EAAKQ,EAAKP,EAAKS,EAAKE,EAEjEjzB,MAUJqC,EAAA9C,UAAAkM,qBAAP,SAA4BrF,EAAWC,EAAWH,GAI9C,OAHAA,EAAOE,EAAIA,EAAIpG,KAAKjC,EAAE,GAAKsI,EAAIrG,KAAKjC,EAAE,GAAKiC,KAAKjC,EAAE,GAClDmI,EAAOG,EAAID,EAAIpG,KAAKjC,EAAE,GAAKsI,EAAIrG,KAAKjC,EAAE,GAAKiC,KAAKjC,EAAE,GAE3CiC,MAQGqC,EAAAC,SAAd,WACI,OAAO,IAAID,EAAS,EAAG,EAAG,EAAG,EAAG,EAAG,IASzBA,EAAA6wB,iBAAd,SAA+B9sB,EAAWC,EAAWH,GACjDA,EAAO6rB,WAAW,EAAG,EAAG,EAAG,EAAG3rB,EAAGC,IASvBhE,EAAA8wB,aAAd,SAA2B/sB,EAAWC,EAAWH,GAC7CA,EAAO6rB,WAAW3rB,EAAG,EAAG,EAAGC,EAAG,EAAG,IAQvBhE,EAAA+wB,cAAd,SAA4BC,EAAentB,GACvC,IAAIxG,EAAI8I,KAAK8qB,IAAID,GACbr1B,EAAIwK,KAAK+qB,IAAIF,GAEjBntB,EAAO6rB,WAAW/zB,EAAG0B,GAAIA,EAAG1B,EAAG,EAAG,IAqBxBqE,EAAAoH,aAAd,SAA2B+pB,EAAYC,EAAYJ,EAAezX,EAAgBC,EAAgB6X,EAAkCxtB,GAChI7D,EAAS6wB,iBAAiBM,EAAIC,EAAIpxB,EAASsxB,2BAE3CtxB,EAAS8wB,aAAavX,EAAQC,EAAQxZ,EAASuxB,oBAE/CvxB,EAAS+wB,cAAcC,EAAOhxB,EAASwxB,qBAEvCxxB,EAAS6wB,kBAAkBM,GAAKC,EAAIpxB,EAASyxB,4BAE7CzxB,EAASsxB,0BAA0BxO,cAAc9iB,EAASuxB,mBAAoBvxB,EAAS0xB,eACvF1xB,EAAS0xB,cAAc5O,cAAc9iB,EAASwxB,oBAAqBxxB,EAAS2xB,eACxEN,GACArxB,EAAS2xB,cAAc7O,cAAc9iB,EAASyxB,2BAA4BzxB,EAAS4xB,eACnF5xB,EAAS4xB,cAAc9O,cAAcuO,EAAcxtB,IAEnD7D,EAAS2xB,cAAc7O,cAAc9iB,EAASyxB,2BAA4B5tB,IAjCnE7D,EAAAsxB,0BAA4BtxB,EAASC,WACrCD,EAAAyxB,2BAA6BzxB,EAASC,WACtCD,EAAAwxB,oBAAsBxxB,EAASC,WAC/BD,EAAAuxB,mBAAqBvxB,EAASC,WAC9BD,EAAA0xB,cAAgB1xB,EAASC,WACzBD,EAAA2xB,cAAgB3xB,EAASC,WACzBD,EAAA4xB,cAAgB5xB,EAASC,WA8B5CD,EAzLA,GAAapF,EAAAoF,iaCnBb,IAIA6xB,EAAA,SAAAjjB,GAwCI,SAAAijB,EAAmBh2B,GAAnB,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OAvCXgH,EAAAypB,WAAa,EACbzpB,EAAAivB,cAAgB,IAgI5B,OAlI+B9iB,EAAA6iB,EAAAjjB,GAK3B5S,OAAAC,eAAW41B,EAAA30B,UAAA,iBAAX,WACI,OAAOS,KAAK2uB,gBAGhB,SAAqB/vB,GACboB,KAAK2uB,aAAe/vB,IAIxBoB,KAAK2uB,WAAa/vB,EAClBoB,KAAKyE,iDAITpG,OAAAC,eAAW41B,EAAA30B,UAAA,oBAAX,WACI,OAAOS,KAAKm0B,mBAGhB,SAAwBv1B,GAChBA,EAAQ,IACRA,EAAQ,GAGRoB,KAAKm0B,gBAAkBv1B,IAI3BoB,KAAKm0B,cAAgBv1B,EACrBoB,KAAKyE,iDAWCyvB,EAAA30B,UAAA+E,aAAV,WACI,MAAO,aAGD4vB,EAAA30B,UAAAgU,WAAV,SAAqBtK,GACjBA,EAAQwK,QAEJzT,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQvF,YAAc1D,KAAK0D,YAC3BuF,EAAQxF,WAAazD,KAAKyD,WAC1BwF,EAAQ1F,cAAgBvD,KAAKuD,cAC7B0F,EAAQzF,cAAgBxD,KAAKwD,eAG7BxD,KAAKgT,cACL/J,EAAQY,UAAY7J,KAAKgT,YAErBhT,KAAKm0B,eACLn0B,KAAKo0B,iBAAiBnrB,EAASjJ,KAAK2uB,WAAa,GACjD1lB,EAAQorB,QAERprB,EAAQuK,SAASxT,KAAKI,gBAAgB0F,KAAM9F,KAAKI,gBAAgB2F,IAAK/F,KAAKI,gBAAgB2E,MAAO/E,KAAKI,gBAAgB4E,SAI3HhF,KAAK2uB,cAED3uB,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQxF,WAAa,EACrBwF,EAAQ1F,cAAgB,EACxB0F,EAAQzF,cAAgB,GAGxBxD,KAAKywB,QACLxnB,EAAQmP,YAAcpY,KAAKywB,OAE/BxnB,EAAQkP,UAAYnY,KAAK2uB,WAErB3uB,KAAKm0B,eACLn0B,KAAKo0B,iBAAiBnrB,EAASjJ,KAAK2uB,WAAa,GACjD1lB,EAAQqrB,UAERrrB,EAAQsoB,WAAWvxB,KAAKI,gBAAgB0F,KAAO9F,KAAK2uB,WAAa,EAAG3uB,KAAKI,gBAAgB2F,IAAM/F,KAAK2uB,WAAa,EAC7G3uB,KAAKI,gBAAgB2E,MAAQ/E,KAAK2uB,WAAY3uB,KAAKI,gBAAgB4E,OAAShF,KAAK2uB,aAI7F1lB,EAAQ8K,WAGFmgB,EAAA30B,UAAA+K,sBAAV,SAAgCN,EAAwBf,GACpDgI,EAAA1R,UAAM+K,sBAAqBxM,KAAAkC,KAACgK,EAAef,GAE3CjJ,KAAK6S,oBAAoB9N,OAAS,EAAI/E,KAAK2uB,WAC3C3uB,KAAK6S,oBAAoB7N,QAAU,EAAIhF,KAAK2uB,WAC5C3uB,KAAK6S,oBAAoB/M,MAAQ9F,KAAK2uB,WACtC3uB,KAAK6S,oBAAoB9M,KAAO/F,KAAK2uB,YAGjCuF,EAAA30B,UAAA60B,iBAAR,SAAyBnrB,EAAmCzE,QAAA,IAAAA,MAAA,GACxD,IAAI4B,EAAIpG,KAAKI,gBAAgB0F,KAAOtB,EAChC6B,EAAIrG,KAAKI,gBAAgB2F,IAAMvB,EAC/BO,EAAQ/E,KAAKI,gBAAgB2E,MAAiB,EAATP,EACrCQ,EAAShF,KAAKI,gBAAgB4E,OAAkB,EAATR,EAEvC+vB,EAAS/rB,KAAKqC,IAAI7F,EAAS,EAAI,EAAGwD,KAAKqC,IAAI9F,EAAQ,EAAI,EAAG/E,KAAKm0B,gBAEnElrB,EAAQ0B,YACR1B,EAAQurB,OAAOpuB,EAAImuB,EAAQluB,GAC3B4C,EAAQwrB,OAAOruB,EAAIrB,EAAQwvB,EAAQluB,GACnC4C,EAAQyrB,iBAAiBtuB,EAAIrB,EAAOsB,EAAGD,EAAIrB,EAAOsB,EAAIkuB,GACtDtrB,EAAQwrB,OAAOruB,EAAIrB,EAAOsB,EAAIrB,EAASuvB,GACvCtrB,EAAQyrB,iBAAiBtuB,EAAIrB,EAAOsB,EAAIrB,EAAQoB,EAAIrB,EAAQwvB,EAAQluB,EAAIrB,GACxEiE,EAAQwrB,OAAOruB,EAAImuB,EAAQluB,EAAIrB,GAC/BiE,EAAQyrB,iBAAiBtuB,EAAGC,EAAIrB,EAAQoB,EAAGC,EAAIrB,EAASuvB,GACxDtrB,EAAQwrB,OAAOruB,EAAGC,EAAIkuB,GACtBtrB,EAAQyrB,iBAAiBtuB,EAAGC,EAAGD,EAAImuB,EAAQluB,GAC3C4C,EAAQwG,aAGFykB,EAAA30B,UAAAmU,iBAAV,SAA2BzK,GACnBjJ,KAAKm0B,gBACLn0B,KAAKo0B,iBAAiBnrB,EAASjJ,KAAK2uB,YACpC1lB,EAAQyB,SAGpBwpB,EAlIA,CAJAz2B,EAAA,GAI+BmV,WAAlB3V,EAAAi3B,kaCJb,IAAAS,EAAAl3B,EAAA,IACAkV,EAAAlV,EAAA,GACAm3B,EAAAn3B,EAAA,GACAo3B,EAAAp3B,EAAA,IAMAq3B,EAAA,SAAA7jB,GAsBI,SAAA6jB,EAAmB52B,GAAnB,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OAGfgH,EAAK6vB,UAAY,EACjB7vB,EAAK7B,kBAAmB,EAExB6B,EAAKuV,sBAAwB,WACzBvV,EAAKmc,OAAS,IAGlBnc,EAAK4V,oBAAsB,WACvB5V,EAAKmc,OAAS,IAGlBnc,EAAK8V,qBAAuB,WACxB9V,EAAK0W,QAAU,IACf1W,EAAK2W,QAAU,KAGnB3W,EAAKgW,mBAAqB,WACtBhW,EAAK0W,QAAU,IACf1W,EAAK2W,QAAU,OA4J3B,OAvM4BxK,EAAAyjB,EAAA7jB,GA+Cd6jB,EAAAv1B,UAAA+E,aAAV,WACI,MAAO,UAKJwwB,EAAAv1B,UAAAoM,gBAAP,SAAuBvF,EAAWC,EAAWuF,EAAcC,EAAmBC,GAC1E,SAAK9L,KAAKoD,mBAAqBpD,KAAK+L,WAAa/L,KAAKwH,mBAIjDyJ,EAAA1R,UAAMiM,SAAQ1N,KAAAkC,KAACoG,EAAGC,KAIvBrG,KAAKgM,oBAAoBJ,EAAMxF,EAAGC,EAAGwF,EAAWC,IAEzC,KAIJgpB,EAAAv1B,UAAA8M,gBAAP,SAAuBH,GACnB,QAAK+E,EAAA1R,UAAM8M,gBAAevO,KAAAkC,KAACkM,KAIvBlM,KAAKya,uBACLza,KAAKya,yBAGF,IAIJqa,EAAAv1B,UAAA+M,cAAP,SAAqBJ,GACblM,KAAK8a,qBACL9a,KAAK8a,sBAGT7J,EAAA1R,UAAM+M,cAAaxO,KAAAkC,KAACkM,IAIjB4oB,EAAAv1B,UAAAgN,eAAP,SAAsBL,EAAiBC,EAAsBN,EAAmBC,GAC5E,QAAKmF,EAAA1R,UAAMgN,eAAczO,KAAAkC,KAACkM,EAAQC,EAAaN,EAAWC,KAKtD9L,KAAKgb,sBACLhb,KAAKgb,wBAGF,IAIJ8Z,EAAAv1B,UAAAkN,aAAP,SAAoBP,EAAiBC,EAAsBN,EAAmBC,EAAqBY,GAC3F1M,KAAKkb,oBACLlb,KAAKkb,qBAGTjK,EAAA1R,UAAMkN,aAAY3O,KAAAkC,KAACkM,EAAQC,EAAaN,EAAWC,EAAaY,IAWtDooB,EAAAE,kBAAd,SAAgC92B,EAAcmQ,EAAc4mB,GACxD,IAAI/uB,EAAS,IAAI4uB,EAAO52B,GAGpBg3B,EAAY,IAAIN,EAAA5d,UAAU9Y,EAAO,UAAWmQ,GAChD6mB,EAAUC,cAAe,EACzBD,EAAUE,wBAA0BziB,EAAA5S,QAAQoB,4BAC5C+zB,EAAUG,YAAc,MACxBnvB,EAAOwL,WAAWwjB,GAGlB,IAAII,EAAY,IAAIT,EAAAzV,MAAMlhB,EAAO,QAAS+2B,GAM1C,OALAK,EAAUvwB,MAAQ,MAClBuwB,EAAUC,QAAUV,EAAAzV,MAAMY,gBAC1BsV,EAAU3uB,oBAAsBgM,EAAA5S,QAAQ6G,0BACxCV,EAAOwL,WAAW4jB,GAEXpvB,GASG4uB,EAAAU,sBAAd,SAAoCt3B,EAAc+2B,GAC9C,IAAI/uB,EAAS,IAAI4uB,EAAO52B,GAGpBo3B,EAAY,IAAIT,EAAAzV,MAAMlhB,EAAO,QAAS+2B,GAK1C,OAJAK,EAAUC,QAAUV,EAAAzV,MAAMd,aAC1BgX,EAAU3uB,oBAAsBgM,EAAA5S,QAAQ6G,0BACxCV,EAAOwL,WAAW4jB,GAEXpvB,GASG4uB,EAAAW,mBAAd,SAAiCv3B,EAAcmQ,GAC3C,IAAInI,EAAS,IAAI4uB,EAAO52B,GAGpBg3B,EAAY,IAAIN,EAAA5d,UAAU9Y,EAAO,UAAWmQ,GAKhD,OAJA6mB,EAAUC,cAAe,EACzBD,EAAUE,wBAA0BziB,EAAA5S,QAAQoB,4BAC5C+E,EAAOwL,WAAWwjB,GAEXhvB,GAUG4uB,EAAAY,gCAAd,SAA8Cx3B,EAAcmQ,EAAc4mB,GACtE,IAAI/uB,EAAS,IAAI4uB,EAAO52B,GAGpBo3B,EAAY,IAAIT,EAAAzV,MAAMlhB,EAAO,QAAS+2B,GAC1CK,EAAUC,QAAUV,EAAAzV,MAAMd,aAC1BpY,EAAOwL,WAAW4jB,GAGlB,IAAIJ,EAAY,IAAIN,EAAA5d,UAAU9Y,EAAO,UAAWmQ,GAKhD,OAJA6mB,EAAUC,cAAe,EACzBD,EAAUE,wBAA0BziB,EAAA5S,QAAQoB,4BAC5C+E,EAAOwL,WAAWwjB,GAEXhvB,GAEf4uB,EAvMA,CAA4BH,EAAAT,WAAfj3B,EAAA63B,wFCTb,IAAAl1B,EAAAnC,EAAA,GACAuW,EAAAvW,EAAA,GAOAk4B,EAAA,WAqCI,SAAAA,EAAmBlvB,GAAnB,IAAAvB,EAAAlF,KA3BOA,KAAAiN,oBAEAjN,KAAAmN,oBAKAnN,KAAA41B,+BAAiC,IAAIh2B,EAAAkE,WAIrC9D,KAAA61B,oBAiBH71B,KAAK81B,OAASrvB,GAAS7G,EAAAonB,OAAO+O,iBAC9B/1B,KAAKg2B,sBAAwBh2B,KAAK81B,OAAOG,oBAAoB3wB,IAAI,WAC7DJ,EAAK8wB,sBAAwB,KAC7B9wB,EAAKgxB,cAAgB,KACrBhxB,EAAKyI,YAGT3N,KAAKk2B,cAAgB,IAAIt2B,EAAAu2B,qBAAqBn2B,KAAK81B,QACnD91B,KAAKk2B,cAAcE,4BAA6B,EAChDp2B,KAAKk2B,cAAcG,0BAA4B,SAACzuB,GAC5C,OAAOA,GAAQA,EAAKiW,UAAYjW,EAAKiW,SAASd,OAIlD/c,KAAK0G,eAAiB,IAAIsN,EAAAhD,YAAY,iBACtChR,KAAK0G,eAAe9B,MAAQ5E,KAC5B,IAAI6R,EAAoB7R,KAAKk2B,cAAcrkB,kBAG3C7R,KAAKs2B,oBAAsBt2B,KAAKk2B,cAAcnyB,uBAAuBuB,IAAI,SAACuG,GACtE3G,EAAKqxB,kBAAkB1qB,GAAW,KAGtC7L,KAAK0pB,iBAAmB7X,EAAkB8X,oBAAoBrkB,IAAI,SAAC+lB,EAAIC,GACnEpmB,EAAK+lB,WAAWI,KAIpBrrB,KAAKk2B,cAAcrkB,kBAAkB2kB,WAAY,EACjDx2B,KAAKk2B,cAAcrkB,kBAAkB4kB,0BAA2B,EAChE,IAAI72B,EAAA82B,iBAAiB,OAAQ92B,EAAAsH,QAAQyvB,KAAM32B,KAAKk2B,cAAcrkB,mBAgJtE,OA5LIxT,OAAAC,eAAWq3B,EAAAp2B,UAAA,aAAX,WACI,OAAOS,KAAK81B,wCAIhBz3B,OAAAC,eAAWq3B,EAAAp2B,UAAA,oBAAX,WACI,OAAOS,KAAKk2B,+CAyCRP,EAAAp2B,UAAAg3B,kBAAR,SAA0B1qB,EAAmB+qB,GACzC,IAAI5pB,EAAsBhN,KAAKiN,iBAAiBpB,GAC5CmB,IACAA,EAAoBV,cAAcU,UAC3BhN,KAAKiN,iBAAiBpB,IAG7B+qB,GACI52B,KAAKmN,iBAAiBtB,KACtB7L,KAAKmN,iBAAiBtB,GAAWmS,wBAC1Bhe,KAAKmN,iBAAiBtB,IAIrC7L,KAAK41B,+BAA+BprB,gBAAgB,OAGhDmrB,EAAAp2B,UAAA0rB,WAAR,SAAmBI,GACf,IAAKrrB,KAAKk2B,gBAAkBl2B,KAAKk2B,cAAcrkB,kBAAkB4Z,aAC7D,OAAO,EAGX,IAAIkB,EAA8BtB,EAAQ,MAEtCxf,EAAY8gB,EAAa9gB,WAAa,EACtCC,EAAc6gB,EAAab,OAE3B+K,EAAcxL,EAAGa,SACrB,IAAK2K,IAAgBA,EAAY1K,IAE7B,OADAnsB,KAAKu2B,kBAAkB1qB,EAAWwf,EAAGzf,OAAShM,EAAAkN,kBAAkBO,YACzD,EAGX,IAAIoE,EAAsBolB,EAAYzK,WAAoB,SA2B1D,OA1BIyK,EAAY5Y,aACZje,KAAK41B,+BAA+BprB,gBAAgBqsB,EAAY5Y,aAG/DxM,EAAQzF,oBAAoBqf,EAAGzf,KAAMirB,EAAY5Y,YAAcpS,EAAWC,IAEvEuf,EAAGzf,OAAShM,EAAAkN,kBAAkBC,cAC1B/M,KAAKiN,iBAAiBpB,IACtB7L,KAAKiN,iBAAiBpB,GAAWS,cAActM,KAAKiN,iBAAiBpB,WAGlE7L,KAAKiN,iBAAiBpB,IAIjCwf,EAAGzf,OAAShM,EAAAkN,kBAAkBO,YAC1BrN,KAAKmN,iBAAiBwf,EAAa9gB,aACnC7L,KAAKmN,iBAAiBwf,EAAa9gB,WAAWmS,wBACvChe,KAAKmN,iBAAiBwf,EAAa9gB,YAGb,UAA7B8gB,EAAamK,aACb92B,KAAKu2B,kBAAkB1qB,GAAW,KAInC,GAMXxN,OAAAC,eAAWq3B,EAAAp2B,UAAA,qBAAX,WACI,OAAOS,KAAK0G,gDAQTivB,EAAAp2B,UAAAiS,gBAAP,SAAuBC,GACnB,OAAOzR,KAAK0G,eAAe8K,gBAAgBC,IAQxCkkB,EAAAp2B,UAAAmS,WAAP,SAAkBD,GAEd,OADAzR,KAAK0G,eAAegL,WAAWD,GACxBzR,MAQJ21B,EAAAp2B,UAAAsO,cAAP,SAAqB4D,GAEjB,OADAzR,KAAK0G,eAAemH,cAAc4D,GAC3BzR,MAMJ21B,EAAAp2B,UAAAoO,QAAP,WAGI,IAAK,IAAIopB,KAFT/2B,KAAK0G,eAAeiH,UAEK3N,KAAK61B,iBACrB71B,KAAK61B,iBAAiBr2B,eAAeu3B,IAI1C/2B,KAAK61B,iBAAiBkB,GAAcppB,UAGxC3N,KAAK61B,oBAED71B,KAAKs2B,qBAAuBt2B,KAAKk2B,gBACjCl2B,KAAKk2B,cAAcnyB,uBAAuBqB,OAAOpF,KAAKs2B,qBACtDt2B,KAAKs2B,oBAAsB,MAG/Bt2B,KAAK41B,+BAA+BhoB,QAEpC,IAAIiE,EAAoB7R,KAAKk2B,cAAgBl2B,KAAKk2B,cAAcrkB,kBAAoB,KAEhFA,GACI7R,KAAK0pB,mBACL7X,EAAkB8X,oBAAoBvkB,OAAOpF,KAAK0pB,kBAClD1pB,KAAK0pB,iBAAmB,MAG5B1pB,KAAK81B,QACD91B,KAAKg2B,wBACLh2B,KAAK81B,OAAOG,oBAAoB7wB,OAAOpF,KAAKg2B,uBAC5Ch2B,KAAKg2B,sBAAwB,MAIjCh2B,KAAKk2B,eACLl2B,KAAKk2B,cAAcvoB,WAG/BgoB,EApNA,GAAa14B,EAAA04B,0JCRbqB,CAAAv5B,EAAA,2ZCAA,IAAAuW,EAAAvW,EAAA,GACAmC,EAAAnC,EAAA,GAKAw5B,EAAA,SAAAhmB,GA+BI,SAAAgmB,EAAmBC,QAAA,IAAAA,OAAA,GAAnB,IAAAhyB,EACI+L,EAAAnT,KAAAkC,OAAOA,YA/BHkF,EAAAkR,aAAc,EAwBflR,EAAAoP,OAAS,GASZpP,EAAKkR,YAAc8gB,IAmE3B,OArGkC7lB,EAAA4lB,EAAAhmB,GAM9B5S,OAAAC,eAAW24B,EAAA13B,UAAA,kBAAX,WACI,OAAOS,KAAKoW,iBAGhB,SAAsBxX,GAAtB,IAAAsG,EAAAlF,KACQA,KAAKoW,cAAgBxX,IAIzBoB,KAAKoW,YAAcxX,EAEnBgB,EAAA6H,MAAM8M,aAAa,WACfrP,EAAKoM,uDAmBH2lB,EAAA13B,UAAA+R,iBAAV,WASI,IARA,IAmCI9M,EAnCAO,EAAQ,EACRC,EAAS,EACT4P,EAAe,EACfuiB,KAEAtiB,EAAsBjV,EAAAwH,OAAO0N,OAAO9U,KAAK8R,KAAMiD,oBAAmB,IAGpD5C,EAAA,EAAAC,EAAApS,KAAKmR,UAALgB,EAAAC,EAAA3B,OAAA0B,IAAgB,CAC9B,IADKgB,EAAKf,EAAAD,IACCvK,KAAX,CAIAgN,IACAzB,EAAMvL,KAAKmN,oBAAmB,GAC9B5B,EAAMvL,KAAKgjB,iBAAiBzF,cAActQ,EAAqBjV,EAAAuV,IAAI/N,OAAO,IAE1E,IAAI4N,EAAc7B,EAAMvL,KAAKsd,kBAAkBlQ,YAC3CE,EAAatV,EAAAsH,QAAQkwB,gBAAgBpiB,EAAYE,WAAYtV,EAAAuV,IAAI/N,OAAO,IAC5E+vB,EAAYjvB,KAAKgN,GAEblV,KAAKoW,YACLpR,GAAUkQ,EAAW7O,EAErBtB,GAASmQ,EAAW9O,GAIxBpG,KAAKoW,YACLpR,IAAW4P,EAAe,GAAK5U,KAAKsU,OAAS,EAE7CvP,IAAU6P,EAAe,GAAK5U,KAAKsU,OAAS,EAM5C9P,EADAxE,KAAKoW,aACKpR,GAEAD,EAId,IADA,IAAI8C,EAAQ,EACMgO,EAAA,EAAAC,EAAA9V,KAAKmR,UAAL0E,EAAAC,EAAArF,OAAAoF,IAAgB,CAA7B,IAAI1C,EACL,IADKA,EAAK2C,EAAAD,IACCjO,KAAX,CAGAgN,IACIM,EAAaiiB,EAAYtvB,KAEzB7H,KAAKoW,aACLjD,EAAM3M,SAASH,EAAI7B,EAAS0Q,EAAW7O,EACvC8M,EAAM3M,SAASJ,EAAI,EACnB5B,GAAyB,EAAf0Q,EAAW7O,IAErB8M,EAAM3M,SAASJ,EAAI5B,EAAS0Q,EAAW9O,EACvC+M,EAAM3M,SAASH,EAAI,EACnB7B,GAAyB,EAAf0Q,EAAW9O,GAGzB5B,GAAWoQ,EAAe,EAAI5U,KAAKsU,OAAS,KAGxD2iB,EArGA,CAAkCjjB,EAAAhD,aAArB/T,EAAAg6B,qaCNb,IAAAI,EAAA55B,EAAA,GACAmC,EAAAnC,EAAA,GAEAuW,EAAAvW,EAAA,GAKA65B,EAAA,SAAArmB,GAAA,SAAAqmB,IAAA,IAAApyB,EAAA,OAAA+L,KAAA+H,MAAAhZ,KAAAu3B,YAAAv3B,YACYkF,EAAAsyB,QAAU,IAwDtB,OAzDiCnmB,EAAAimB,EAAArmB,GAM7B5S,OAAAC,eAAWg5B,EAAA/3B,UAAA,cAAX,WACI,OAAOS,KAAKw3B,aAGhB,SAAkB54B,GAAlB,IAAAsG,EAAAlF,KACQA,KAAKw3B,UAAY54B,IAIrBoB,KAAKw3B,QAAU54B,EAEfgB,EAAA6H,MAAM8M,aAAa,WACfrP,EAAKoM,uDAIHgmB,EAAA/3B,UAAAwW,aAAV,SAAuBtE,EAAoBgmB,GACvC,IAAI7vB,EAAO6J,EAAQ7J,KAEnB,GAAKA,EAAL,CAIA,IAAI8vB,EAAS13B,KAAK23B,kBAAkBF,GAGpC,OAFAhmB,EAAQjL,SAAWkxB,EAEX13B,KAAK43B,aACT,KAAK5jB,EAAAhD,YAAYsB,uBACb1K,EAAKiwB,OAAO,IAAIC,QAAQ5wB,SAASwwB,EAAOtxB,GAAIsxB,EAAOrxB,GAAIqxB,EAAOnwB,IAC9D,MACJ,KAAKyM,EAAAhD,YAAYuB,+BACb3K,EAAKiwB,OAAO,IAAIC,QAAQ5wB,QAAQ,EAAIwwB,EAAOtxB,EAAG,EAAIsxB,EAAOrxB,EAAG,EAAIqxB,EAAOnwB,IACvE,MACJ,KAAKyM,EAAAhD,YAAYwB,wBACb,MACJ,KAAKwB,EAAAhD,YAAYyB,gCACb7K,EAAKyB,OAAOyuB,QAAQC,KAAKC,EAAGxvB,KAAKgH,GAAIsoB,QAAQG,MAAMC,UAKvDZ,EAAA/3B,UAAAo4B,kBAAR,SAA0BtnB,GACtB,IAAIqnB,EAAS,IAAI93B,EAAAsH,QAAQ,EAAG,EAAGlH,KAAKw3B,SAEhCW,EAAU9nB,EAAOhK,EAAIrG,KAAKw3B,QAC1BY,GAAW/nB,EAAOjK,EAAIpG,KAAKw3B,QAI/B,OAFA53B,EAAAwH,OAAOixB,0BAA0BD,EAAQD,EAAQ,EAAGv4B,EAAAuV,IAAI/N,OAAO,IAExDxH,EAAAsH,QAAQkwB,gBAAgBM,EAAQ93B,EAAAuV,IAAI/N,OAAO,KAE1DkwB,EAzDA,CAAiCD,EAAApjB,kBAApBhX,EAAAq6B,oaCRb,IAAAD,EAAA55B,EAAA,GACAmC,EAAAnC,EAAA,GAEAuW,EAAAvW,EAAA,GAKA66B,EAAA,SAAArnB,GAAA,SAAAqnB,IAAA,IAAApzB,EAAA,OAAA+L,KAAA+H,MAAAhZ,KAAAu3B,YAAAv3B,YACYkF,EAAAqzB,WAAa,MAuGzB,OAxGkClnB,EAAAinB,EAAArnB,GAM9B5S,OAAAC,eAAWg6B,EAAA/4B,UAAA,iBAAX,WACI,OAAOS,KAAKu4B,gBAGhB,SAAqB35B,GAArB,IAAAsG,EAAAlF,KACQA,KAAKu4B,aAAe35B,IAIxBoB,KAAKu4B,WAAa35B,EAElBgB,EAAA6H,MAAM8M,aAAa,WACfrP,EAAKoM,uDAIHgnB,EAAA/4B,UAAAwW,aAAV,SAAuBtE,EAAoBgmB,GACvC,IAAI7vB,EAAO6J,EAAQ7J,KACf8vB,EAAS13B,KAAKw4B,gBAAgBf,GAElC,GAAK7vB,EAAL,CAIA,OAAQ5H,KAAK43B,aACT,KAAK5jB,EAAAhD,YAAYsB,uBACjB,KAAK0B,EAAAhD,YAAYwB,wBACb5K,EAAKiwB,OAAO,IAAIj4B,EAAAsH,QAAQ,EAAG,GAAI,IAC/B,MACJ,KAAK8M,EAAAhD,YAAYyB,gCACjB,KAAKuB,EAAAhD,YAAYuB,+BACb3K,EAAKiwB,OAAO,IAAIj4B,EAAAsH,QAAQ,EAAG,EAAG,IAItCuK,EAAQjL,SAAWkxB,IAGfY,EAAA/4B,UAAAi5B,gBAAR,SAAwBnoB,GAIpB,OAHAA,EAAOjK,GAAK,EAAsB,EAAhBoC,KAAKiwB,UAAkBz4B,KAAKwU,WAC9CnE,EAAOhK,GAAK,EAAsB,EAAhBmC,KAAKiwB,UAAkBz4B,KAAKyU,YAEvCpE,GAGDioB,EAAA/4B,UAAAyW,iBAAV,WAEI,IADA,IAAI0iB,KACcvmB,EAAA,EAAAC,EAAApS,KAAKmR,UAALgB,EAAAC,EAAA3B,OAAA0B,IAAgB,CAA7B,IAAIgB,EAAKf,EAAAD,GACLgB,EAAMvL,MAIX8wB,EAAOxwB,KAAKiL,EAAMvL,MAGtB,IAAK,IAAI+wB,EAAQ,EAAGA,EAAQ34B,KAAKu4B,WAAYI,IAAS,CAClDD,EAAOE,KAAK,SAACC,EAAGC,GACZ,IAAIC,EAAYF,EAAEryB,SAASwyB,gBACvBC,EAAYH,EAAEtyB,SAASwyB,gBAE3B,OAAID,EAAYE,EACL,EACAF,EAAYE,GACX,EAGL,IAQX,IALA,IAAIC,EAAuB1wB,KAAK2wB,IAAIn5B,KAAKsU,OAAQ,GAC7C8kB,EAAW5wB,KAAKuC,IAAI/K,KAAKwU,WAAYxU,KAAKyU,aAC1C4kB,EAAez5B,EAAAuV,IAAI1S,QAAQ,GAC3B62B,EAAa15B,EAAAuV,IAAIjO,QAAQ,GAEpBvJ,EAAI,EAAGA,EAAI+6B,EAAOjoB,OAAS,EAAG9S,IACnC,IAAK,IAAI47B,EAAI57B,EAAI,EAAG47B,EAAIb,EAAOjoB,OAAQ8oB,IACnC,GAAI57B,GAAK47B,EAAG,CACRb,EAAOa,GAAG/yB,SAAS6O,cAAcqjB,EAAO/6B,GAAG6I,SAAU8yB,GAGrDD,EAAajzB,EAAIkzB,EAAWlzB,EAC5BizB,EAAahzB,EAAIizB,EAAWjzB,EAC5B,IAAImzB,EAAiBJ,EACjBK,EAAWJ,EAAaL,gBAAkBE,GAE9CO,GADoBjxB,KAAKqC,IAAI4uB,EAAUP,IAGvB1wB,KAAK2wB,IAAIK,EAAgB,KACrCH,EAAaK,YACbJ,EAAWhkB,aAAsD,IAAxCkkB,EAAiBhxB,KAAKmxB,KAAKF,KACpDf,EAAOa,GAAG/yB,SAASozB,WAAWN,GAC9BZ,EAAO/6B,GAAG6I,SAASqzB,gBAAgBP,OAO/DhB,EAxGA,CAAkCjB,EAAApjB,kBAArBhX,EAAAq7B,qaCRb,IAAA14B,EAAAnC,EAAA,GACAuW,EAAAvW,EAAA,GAOAq8B,EAAA,SAAA7oB,GAAA,SAAA6oB,mDA2BA,OA3BgCzoB,EAAAyoB,EAAA7oB,GAClB6oB,EAAAv6B,UAAAwW,aAAV,SAAuBtE,EAAoBgmB,GACvC,IAAI7vB,EAAO6J,EAAQ7J,KAEnB,GAAKA,EAAL,CAIA6J,EAAQjL,SAAWixB,EAAa9R,QAChC,IAAIzZ,EAAStM,EAAAuV,IAAIjO,QAAQ,GAIzB,OAFAgF,EAAOhC,SAASutB,GAERz3B,KAAK43B,aACT,KAAK5jB,EAAAhD,YAAYsB,uBACjB,KAAK0B,EAAAhD,YAAYwB,wBACbtG,EAAO0tB,WAAW,IAAI9B,QAAQ5wB,QAAQ,EAAG,GAAI,IAC7CU,EAAKiwB,OAAO3rB,GACZ,MACJ,KAAK8H,EAAAhD,YAAYyB,gCACjB,KAAKuB,EAAAhD,YAAYuB,+BACbrG,EAAO0tB,WAAW,IAAI9B,QAAQ5wB,QAAQ,EAAG,EAAG,IAC5CU,EAAKiwB,OAAO3rB,MAK5B4tB,EA3BA,CALAr8B,EAAA,GAKgCwW,kBAAnBhX,EAAA68B,maCPb,IAKAC,EAAA,SAAA9oB,GASI,SAAA8oB,EAAYnyB,EAAY1J,GAAxB,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YACXkF,EAAK80B,aAAepyB,EAMpB1C,EAAKuV,sBAAwB,WACpBvV,EAAK0C,MAGV1C,EAAK0C,KAAKqT,QAAQ3F,aAAa,MAGnCpQ,EAAK4V,oBAAsB,WAClB5V,EAAK0C,MAGV1C,EAAK0C,KAAKqT,QAAQ3F,aAAa,EAAM,MAGzCpQ,EAAK8V,qBAAuB,WACnB9V,EAAK0C,MAGV1C,EAAK0C,KAAKqT,QAAQ3F,aAAa,MAGnCpQ,EAAKgW,mBAAqB,WACjBhW,EAAK0C,MAGV1C,EAAK0C,KAAKqT,QAAQ3F,aAAa,EAAM,QAkBjD,OA5DkCjE,EAAA0oB,EAAA9oB,GA8CpB8oB,EAAAx6B,UAAA+E,aAAV,WACI,MAAO,gBAIDy1B,EAAAx6B,UAAAyS,YAAV,SAAsBvL,GAAtB,IAAAvB,EAAAlF,KAII,OAHAA,KAAKg6B,aAAaC,iBAAiBC,QAAQ,SAACtyB,GACxCA,EAAKiW,SAAW3Y,IAEblF,KAAKg6B,cAGND,EAAAx6B,UAAAgd,gBAAV,SAA0B3U,KAE9BmyB,EA5DA,CALAt8B,EAAA,GAKkC6c,UAArBrd,EAAA88B,8BCNb78B,EAAAD,QAAA,+/CCAAC,EAAAD,QAAA,qiDCAA,IAAA2C,EAAAnC,EAAA,GAEM08B,EAAU18B,EAAQ,IASfR,EAAAk9B,UART,IAAMC,EAAU38B,EAAQ,IAQNR,EAAAm9B,UANlBn9B,EAAA0jB,eAAA,WAEI/gB,EAAAy6B,OAAOC,aAAiC,mBAAIF,EAC5Cx6B,EAAAy6B,OAAOC,aAAgC,kBAAIH,yZCR/C,IAAAI,EAAA98B,EAAA,GACAmC,EAAAnC,EAAA,GACA+8B,EAAA/8B,EAAA,IACAg9B,EAAAh9B,EAAA,GACAo3B,EAAAp3B,EAAA,IACAm3B,EAAAn3B,EAAA,GAMAi9B,EAAA,SAAAzpB,GA4EI,SAAAypB,EAAYx8B,EAAey8B,QAAA,IAAAA,OAAA,GAA3B,IAAAz1B,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YAvEPkF,EAAA01B,iBAAkB,EAyEtB11B,EAAK01B,gBAAkBD,EAGvBz1B,EAAKuV,sBAAwB,WACpBvV,EAAK0C,MAGV1C,EAAK21B,YAAYnd,YAAW,IAGhCxY,EAAK4V,oBAAsB,WAClB5V,EAAK0C,MAGV1C,EAAK21B,YAAYnd,YAAW,MA8IxC,OA3OuCrM,EAAAqpB,EAAAzpB,GAenC5S,OAAAC,eAAWo8B,EAAAn7B,UAAA,YAAX,WACI,OAAOS,KAAKiX,WAGhB,SAAgBrY,GACRoB,KAAKiX,QAAUrY,IAInBoB,KAAKiX,MAAQrY,EACboB,KAAK86B,oDAMTz8B,OAAAC,eAAWo8B,EAAAn7B,UAAA,gBAAX,WACI,OAAOS,KAAK+6B,eAGhB,SAAoBn8B,GACZoB,KAAK+6B,YAAcn8B,IAIvBoB,KAAK+6B,UAAYn8B,EACjBoB,KAAK86B,oDAMTz8B,OAAAC,eAAWo8B,EAAAn7B,UAAA,oBAAX,WACI,OAAOS,KAAKg7B,+CAMhB38B,OAAAC,eAAWo8B,EAAAn7B,UAAA,qBAAX,WACI,OAAOS,KAAKi7B,gDAMhB58B,OAAAC,eAAWo8B,EAAAn7B,UAAA,qBAAX,WACI,OAAOS,KAAKk7B,gDAMhB78B,OAAAC,eAAWo8B,EAAAn7B,UAAA,sBAAX,WACI,OAAOS,KAAK46B,iDA4BNF,EAAAn7B,UAAA+E,aAAV,WACI,MAAO,qBAGHo2B,EAAAn7B,UAAAu7B,gBAAR,WACI96B,KAAKob,wBAEL,IAAI+f,EAAQ,IAAIV,EAAAtkB,WAGhB,GAFAglB,EAAMjE,YAAa,EAEfl3B,KAAK+6B,UAAW,CAChB,IAAIK,EAAQ,IAAIvG,EAAAzV,MAChBgc,EAAM/qB,OAASrQ,KAAK+6B,UACpBK,EAAMC,WAAa,OACnBD,EAAMp2B,OAAS,QACfo2B,EAAMr2B,MAAQ,QACdq2B,EAAME,cAAgB,OACtBH,EAAMzpB,WAAW0pB,GAGrB,GAAIp7B,KAAKiX,MAAO,CACZ,IAAI5I,EAAO,IAAIumB,EAAA5d,UACf3I,EAAKA,KAAOrO,KAAKiX,MACjB5I,EAAKoiB,MAAQ,QACbpiB,EAAKrJ,OAAS,OACdqJ,EAAKktB,SAAW,GAChBJ,EAAMzpB,WAAWrD,GAGjBrO,KAAK66B,cACL76B,KAAKsb,QAAU6f,IAKbT,EAAAn7B,UAAAyS,YAAV,SAAsBvL,GAuBlB,OAtBAzG,KAAKw7B,WAAa57B,EAAAwc,YAAYC,UAAUrc,KAAK9B,KAAO,YAChD6G,MAAO,EACPC,OAAQ,EACRsX,MAAO,KACR7V,GAEHzG,KAAK66B,YAAcj7B,EAAAwc,YAAYC,UAAUrc,KAAK9B,KAAO,aACjD6G,MAAO,EACPC,OAAQ,EACRsX,MAAO,KACR7V,GAEHzG,KAAK66B,YAAYzuB,OAASpM,KAAKw7B,WAC/Bx7B,KAAK66B,YAAYr0B,SAASe,GAAK,IAC/BvH,KAAK66B,YAAY/c,YAAa,EAC9B9d,KAAK66B,YAAYnd,YAAW,GAE5B1d,KAAKy7B,WAAmBxqB,EAAA1R,UAAMyS,YAAWlU,KAAAkC,KAACyG,GAC1CzG,KAAKy7B,WAAWrvB,OAASpM,KAAKw7B,WAC9Bx7B,KAAKy7B,WAAWj1B,SAASe,GAAK,IAC9BvH,KAAKy7B,WAAW3d,YAAa,EAEtB9d,KAAKw7B,YAGNd,EAAAn7B,UAAAwc,aAAV,SAAuBC,GACnBhc,KAAKk7B,eAAejf,gBAAkBD,EACtChc,KAAKk7B,eAAenO,eAAiB/Q,GAGjC0e,EAAAn7B,UAAAm8B,oBAAR,SAA4B9zB,GAA5B,IAAA1C,EAAAlF,KACIA,KAAKg7B,cAAgB,IAAIR,EAAAtZ,eAAelhB,KAAK9B,KAAO,gBAAiB0J,EAAK8U,YAC1E1c,KAAKg7B,cAAcrZ,kBAAmB,EACtC3hB,KAAK27B,qBAAuB37B,KAAK4E,MAAMgxB,+BAA+BtwB,IAAI,SAAA2Y,GAClEA,GACA/Y,EAAK81B,cAAcjZ,cAAgB9D,EACnC/Y,EAAK81B,cAAcnZ,WAAWgX,EAAI,GAElC3zB,EAAK81B,cAAcnZ,WAAWgX,EAAI,KAKtC6B,EAAAn7B,UAAAq8B,qBAAR,SAA6Bh0B,GACzB5H,KAAKi7B,eAAiB,IAAIT,EAAAtZ,eAAelhB,KAAK9B,KAAO,iBAAkB0J,EAAK8U,YAC5E1c,KAAKi7B,eAAe9Z,wBAA0B,EAC9CnhB,KAAKi7B,eAAe5Z,MAAQ,GAC5BrhB,KAAKi7B,eAAe1Z,eAAgB,GAGhCmZ,EAAAn7B,UAAAs8B,qBAAR,SAA6Bj0B,GACzB5H,KAAKk7B,eAAiB,IAAIt7B,EAAA6c,iBAAiBzc,KAAK9B,KAAO,iBAAkB0J,EAAK8U,YAC9E1c,KAAKk7B,eAAeve,cAAgB/c,EAAAgb,OAAOG,SAGrC2f,EAAAn7B,UAAAgd,gBAAV,SAA0B3U,GAElB5H,KAAK46B,iBACA56B,KAAK4E,MAAMixB,iBAAqC,mBAIjD71B,KAAKg7B,cAAgBh7B,KAAK4E,MAAMixB,iBAAqC,oBAHrE71B,KAAK07B,oBAAoB9zB,GACzB5H,KAAK4E,MAAMixB,iBAAqC,mBAAI71B,KAAKg7B,eAMxDh7B,KAAK4E,MAAMixB,iBAAsC,oBAIlD71B,KAAKi7B,eAAiBj7B,KAAK4E,MAAMixB,iBAAsC,qBAHvE71B,KAAK47B,qBAAqBh0B,GAC1B5H,KAAK4E,MAAMixB,iBAAsC,oBAAI71B,KAAKi7B,kBAK9Dj7B,KAAK07B,oBAAoB9zB,GACzB5H,KAAK47B,qBAAqBh0B,IAG9B5H,KAAK67B,qBAAqBj0B,GAC1B5H,KAAKw7B,WAAWhf,SAAWxc,KAAKg7B,cAChCh7B,KAAK66B,YAAYre,SAAWxc,KAAKi7B,eACjCj7B,KAAKy7B,WAAWjf,SAAWxc,KAAKk7B,eAEhCl7B,KAAK86B,mBAMFJ,EAAAn7B,UAAAoO,QAAP,WACIsD,EAAA1R,UAAMoO,QAAO7P,KAAAkC,MAERA,KAAK26B,iBACN36B,KAAKg7B,cAAcrtB,UACnB3N,KAAKi7B,eAAettB,UACpB3N,KAAKk7B,eAAevtB,UAEhB3N,KAAK27B,uBACL37B,KAAK4E,MAAMgxB,+BAA+BxwB,OAAOpF,KAAK27B,sBACtD37B,KAAK27B,qBAAuB,QAI5CjB,EA3OA,CAAuCH,EAAAjgB,UAA1Brd,EAAAy9B,0aCXb,IAAArD,EAAA55B,EAAA,GACAmC,EAAAnC,EAAA,GAEAuW,EAAAvW,EAAA,GAKAq+B,EAAA,SAAA7qB,GAAA,SAAA6qB,IAAA,IAAA52B,EAAA,OAAA+L,KAAA+H,MAAAhZ,KAAAu3B,YAAAv3B,YACYkF,EAAAsyB,QAAU,IAsDtB,OAvDmCnmB,EAAAyqB,EAAA7qB,GAM/B5S,OAAAC,eAAWw9B,EAAAv8B,UAAA,cAAX,WACI,OAAOS,KAAKw3B,aAGhB,SAAkB54B,GAAlB,IAAAsG,EAAAlF,KACQA,KAAKw3B,UAAY54B,IAIrBoB,KAAKw3B,QAAU54B,EAEfgB,EAAA6H,MAAM8M,aAAa,WACfrP,EAAKoM,uDAIHwqB,EAAAv8B,UAAAwW,aAAV,SAAuBtE,EAAoBgmB,GACvC,IAAI7vB,EAAO6J,EAAQ7J,KAEnB,GAAKA,EAAL,CAGA,IAAI8vB,EAAS13B,KAAK+7B,oBAAoBtE,GAGtC,OAFAhmB,EAAQjL,SAAWkxB,EAEX13B,KAAK43B,aACT,KAAK5jB,EAAAhD,YAAYsB,uBACb1K,EAAKiwB,OAAO,IAAIC,QAAQ5wB,SAASwwB,EAAOtxB,EAAGsxB,EAAOrxB,GAAIqxB,EAAOnwB,IAC7D,MACJ,KAAKyM,EAAAhD,YAAYuB,+BACb3K,EAAKiwB,OAAO,IAAIC,QAAQ5wB,QAAQ,EAAIwwB,EAAOtxB,EAAGsxB,EAAOrxB,EAAG,EAAIqxB,EAAOnwB,IACnE,MACJ,KAAKyM,EAAAhD,YAAYwB,wBACb,MACJ,KAAKwB,EAAAhD,YAAYyB,gCACb7K,EAAKyB,OAAOyuB,QAAQC,KAAKC,EAAGxvB,KAAKgH,GAAIsoB,QAAQG,MAAMC,UAKvD4D,EAAAv8B,UAAAw8B,oBAAR,SAA4B1rB,GACxB,IAAIqnB,EAAS,IAAI93B,EAAAsH,QAAQ,EAAGmJ,EAAOhK,EAAGrG,KAAKw3B,SAEvCY,EAAU/nB,EAAOjK,EAAIpG,KAAKw3B,QAI9B,OAFA53B,EAAAwH,OAAOixB,0BAA0BD,EAAQ,EAAG,EAAGx4B,EAAAuV,IAAI/N,OAAO,IAEnDxH,EAAAsH,QAAQkwB,gBAAgBM,EAAQ93B,EAAAuV,IAAI/N,OAAO,KAE1D00B,EAvDA,CAAmCzE,EAAApjB,kBAAtBhX,EAAA6+B,6JCRb9E,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,IACAu5B,EAAAv5B,EAAA,IACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,iJCXAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KAEAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,oFCJA,IAAAkV,EAAAlV,EAAA,GACAg9B,EAAAh9B,EAAA,GACAm3B,EAAAn3B,EAAA,GAQSR,EAAAiB,KAFI,UAYbyU,EAAA5S,QAAQ2P,UAAY,SAAU+B,EAAkBpD,EAAcke,EAAuByP,GACjF,IAAIb,EAAQ,IAAIV,EAAAtkB,WAAW,SACvB8lB,GAAeD,GAAUA,EAAQC,aACjCC,GAAeF,GAAUA,EAAQE,aAErCf,EAAMjE,YAAc+E,EAEpB,IAAIE,EAAS,IAAIvH,EAAA5d,UAAU,UAwB3B,OAvBAmlB,EAAO9tB,KAAOA,EACd8tB,EAAO/G,wBAA0BziB,EAAA5S,QAAQ6G,0BACrCq1B,EACAE,EAAOp3B,MAAQwnB,EAEf4P,EAAOn3B,OAASunB,EAGhB2P,GACAf,EAAMzpB,WAAWD,GACjB0pB,EAAMzpB,WAAWyqB,GACjBA,EAAO9G,YAAc,QAErB8F,EAAMzpB,WAAWyqB,GACjBhB,EAAMzpB,WAAWD,GACjB0qB,EAAOC,aAAe,OAG1BD,EAAO14B,WAAagO,EAAQhO,WAC5B04B,EAAOz4B,YAAc+N,EAAQ/N,YAC7By4B,EAAO54B,cAAgBkO,EAAQlO,cAC/B44B,EAAO34B,cAAgBiO,EAAQjO,cAExB23B,yZCnDX,IAAAxoB,EAAAlV,EAAA,GACAkC,EAAAlC,EAAA,GACAmC,EAAAnC,EAAA,GAMA4+B,EAAA,SAAAprB,GAkLI,SAAAorB,EAAmBn+B,GAAnB,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OAjLXgH,EAAAo3B,YAAc,IAAI38B,EAAAgB,aAAa,GAAIhB,EAAAgB,aAAaC,gBAAgB,GAChEsE,EAAAq3B,SAAW,EACXr3B,EAAAs3B,SAAW,IACXt3B,EAAA2K,OAAS,GACT3K,EAAAkR,aAAc,EACdlR,EAAA8N,YAAc,QACd9N,EAAAu3B,aAAe,QACfv3B,EAAAw3B,WAAa,IAAI/8B,EAAAgB,aAAa,EAAGhB,EAAAgB,aAAaC,gBAAgB,GAC9DsE,EAAAy3B,gBAAiB,EACjBz3B,EAAA03B,iBAAkB,EAGnB13B,EAAA23B,yBAA2B,IAAIj9B,EAAAkE,WA8Y9BoB,EAAA43B,gBAAiB,EAtOrB53B,EAAK7B,kBAAmB,IAkRhC,OAvc4BgO,EAAAgrB,EAAAprB,GAgBxB5S,OAAAC,eAAW+9B,EAAA98B,UAAA,mBAAX,WACI,OAAOS,KAAKy8B,kBAGhB,SAAuB79B,GACfoB,KAAKy8B,eAAiB79B,IAI1BoB,KAAKy8B,aAAe79B,EACpBoB,KAAKyE,iDAITpG,OAAAC,eAAW+9B,EAAA98B,UAAA,kBAAX,WACI,OAAOS,KAAKgT,iBAGhB,SAAsBpU,GACdoB,KAAKgT,cAAgBpU,IAIzBoB,KAAKgT,YAAcpU,EACnBoB,KAAKyE,iDAITpG,OAAAC,eAAW+9B,EAAA98B,UAAA,iBAAX,WACI,OAAOS,KAAK08B,WAAW/3B,SAAS3E,KAAK4E,YAQzC,SAAqBhG,GACboB,KAAK08B,WAAW/3B,SAAS3E,KAAK4E,SAAWhG,GAIzCoB,KAAK08B,WAAW73B,WAAWjG,IAC3BoB,KAAKyE,gDAVbpG,OAAAC,eAAW+9B,EAAA98B,UAAA,yBAAX,WACI,OAAOS,KAAK08B,WAAW53B,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBuD,wCAcjF1G,OAAAC,eAAW+9B,EAAA98B,UAAA,kBAAX,WACI,OAAOS,KAAKs8B,YAAY33B,SAAS3E,KAAK4E,YAQ1C,SAAsBhG,GACdoB,KAAKs8B,YAAY33B,SAAS3E,KAAK4E,SAAWhG,GAI1CoB,KAAKs8B,YAAYz3B,WAAWjG,IAC5BoB,KAAKyE,gDAVbpG,OAAAC,eAAW+9B,EAAA98B,UAAA,0BAAX,WACI,OAAOS,KAAKs8B,YAAYx3B,gBAAgB9E,KAAK4E,MAAO5E,KAAKwB,qBAAqBuD,wCAclF1G,OAAAC,eAAW+9B,EAAA98B,UAAA,eAAX,WACI,OAAOS,KAAKu8B,cAGhB,SAAmB39B,GACXoB,KAAKu8B,WAAa39B,IAItBoB,KAAKu8B,SAAW39B,EAChBoB,KAAKyE,eAELzE,KAAKpB,MAAQ4J,KAAKuC,IAAIvC,KAAKqC,IAAI7K,KAAKpB,MAAOoB,KAAKw8B,UAAWx8B,KAAKu8B,4CAIpEl+B,OAAAC,eAAW+9B,EAAA98B,UAAA,eAAX,WACI,OAAOS,KAAKw8B,cAGhB,SAAmB59B,GACXoB,KAAKw8B,WAAa59B,IAItBoB,KAAKw8B,SAAW59B,EAChBoB,KAAKyE,eAELzE,KAAKpB,MAAQ4J,KAAKuC,IAAIvC,KAAKqC,IAAI7K,KAAKpB,MAAOoB,KAAKw8B,UAAWx8B,KAAKu8B,4CAIpEl+B,OAAAC,eAAW+9B,EAAA98B,UAAA,aAAX,WACI,OAAOS,KAAK6P,YAGhB,SAAiBjR,GACbA,EAAQ4J,KAAKuC,IAAIvC,KAAKqC,IAAIjM,EAAOoB,KAAKw8B,UAAWx8B,KAAKu8B,UAElDv8B,KAAK6P,SAAWjR,IAIpBoB,KAAK6P,OAASjR,EACdoB,KAAKyE,eACLzE,KAAK68B,yBAAyBryB,gBAAgBxK,KAAK6P,0CAIvDxR,OAAAC,eAAW+9B,EAAA98B,UAAA,kBAAX,WACI,OAAOS,KAAKoW,iBAGhB,SAAsBxX,GACdoB,KAAKoW,cAAgBxX,IAIzBoB,KAAKoW,YAAcxX,EACnBoB,KAAKyE,iDAITpG,OAAAC,eAAW+9B,EAAA98B,UAAA,qBAAX,WACI,OAAOS,KAAK28B,oBAGhB,SAAyB/9B,GACjBoB,KAAK28B,iBAAmB/9B,IAI5BoB,KAAK28B,eAAiB/9B,EACtBoB,KAAKyE,iDAITpG,OAAAC,eAAW+9B,EAAA98B,UAAA,sBAAX,WACI,OAAOS,KAAK48B,qBAGhB,SAA0Bh+B,GAClBoB,KAAK48B,kBAAoBh+B,IAI7BoB,KAAK48B,gBAAkBh+B,EACvBoB,KAAKyE,iDAaC43B,EAAA98B,UAAA+E,aAAV,WACI,MAAO,UAGD+3B,EAAA98B,UAAAw9B,mBAAV,SAA6BnxB,EAAcoxB,GACvC,IAAIC,EAAiB,EACrB,OAAQrxB,GACJ,IAAK,SAEGqxB,EADAj9B,KAAKs8B,YAAY72B,QACA+C,KAAKuC,IAAI/K,KAAKs8B,YAAY52B,SAAS1F,KAAK4E,OAAQo4B,GAGhDA,EAAmBh9B,KAAKs8B,YAAY52B,SAAS1F,KAAK4E,OAEvE,MACJ,IAAK,YAEGq4B,EADAj9B,KAAKs8B,YAAY72B,QACA+C,KAAKqC,IAAI7K,KAAKs8B,YAAY52B,SAAS1F,KAAK4E,OAAQo4B,GAGhDA,EAAmBh9B,KAAKs8B,YAAY52B,SAAS1F,KAAK4E,OAG/E,OAAOq4B,GAIJZ,EAAA98B,UAAAgM,MAAP,SAAavB,EAAwBf,GAIjC,GAHAA,EAAQwK,OAERzT,KAAK2J,aAAaV,GACdjJ,KAAK+J,iBAAiBC,EAAef,GAAU,CAE/C,IAAIi0B,EAAqB,EACrBtxB,EAAO5L,KAAKm9B,cAAgB,SAAW,YACvCr3B,EAAO9F,KAAKI,gBAAgB0F,KAC5BC,EAAM/F,KAAKI,gBAAgB2F,IAC3BhB,EAAQ/E,KAAKI,gBAAgB2E,MAC7BC,EAAShF,KAAKI,gBAAgB4E,OAE9Bo4B,EAAsB50B,KAAKuC,IAAI/K,KAAKI,gBAAgB2E,MAAO/E,KAAKI,gBAAgB4E,QAChFq4B,EAAyB70B,KAAKqC,IAAI7K,KAAKI,gBAAgB2E,MAAO/E,KAAKI,gBAAgB4E,QAEnFs4B,EAA0Bt9B,KAAK+8B,mBAAmBnxB,EAAMyxB,GAC5DD,GAAuBE,EAEvB,IAAI/I,EAAS,EAIb,GAAKv0B,KAAKoW,aAAepW,KAAKI,gBAAgB4E,OAAShF,KAAKI,gBAAgB2E,MAExE,YADAw4B,QAAQC,MAAM,uCAUlBH,GAAgD,GAN5CH,EADAl9B,KAAK08B,WAAWj3B,QACK+C,KAAKqC,IAAI7K,KAAK08B,WAAWh3B,SAAS1F,KAAK4E,OAAQy4B,GAG/CA,EAAyBr9B,KAAK08B,WAAWh3B,SAAS1F,KAAK4E,QAK5E5E,KAAKoW,aACLtQ,GAAQo3B,EACHl9B,KAAKy9B,iBACN13B,GAAQu3B,EAA0B,GAGtCt4B,EAASo4B,EACTr4B,EAAQs4B,IAIRt3B,GAAOm3B,EACFl9B,KAAKy9B,iBACN33B,GAASw3B,EAA0B,GAEvCt4B,EAASq4B,EACTt4B,EAAQq4B,GAGRp9B,KAAKy9B,gBAAkBz9B,KAAKm9B,eACxBn9B,KAAKoW,YACLrQ,GAAQu3B,EAA0B,EAElCx3B,GAASw3B,EAA0B,EAEvC/I,EAAS8I,EAAyB,GAGlC9I,GAAU+I,EAA0BJ,GAAsB,GAG1Dl9B,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQvF,YAAc1D,KAAK0D,YAC3BuF,EAAQxF,WAAazD,KAAKyD,WAC1BwF,EAAQ1F,cAAgBvD,KAAKuD,cAC7B0F,EAAQzF,cAAgBxD,KAAKwD,eAGjC,IAAIk6B,EAAiB19B,KAAgB,aAAMA,KAAKw8B,SAAWx8B,KAAK6P,SAAW7P,KAAKw8B,SAAWx8B,KAAKu8B,UAAaa,GAAwBp9B,KAAK6P,OAAS7P,KAAKu8B,WAAav8B,KAAKw8B,SAAWx8B,KAAKu8B,UAAaa,EACvMn0B,EAAQY,UAAY7J,KAAKgT,YAErBhT,KAAKoW,YACDpW,KAAKy9B,eACDz9B,KAAKm9B,eACLl0B,EAAQ0B,YACR1B,EAAQsG,IAAIzJ,EAAOu3B,EAAyB,EAAGt3B,EAAKwuB,EAAQ/rB,KAAKgH,GAAI,EAAIhH,KAAKgH,IAC9EvG,EAAQorB,OACRprB,EAAQuK,SAAS1N,EAAMC,EAAKhB,EAAOC,IAGnCiE,EAAQuK,SAAS1N,EAAMC,EAAKhB,EAAOC,EAASs4B,GAIhDr0B,EAAQuK,SAAS1N,EAAMC,EAAKhB,EAAOC,GAInChF,KAAKy9B,eACDz9B,KAAKm9B,eACLl0B,EAAQ0B,YACR1B,EAAQsG,IAAIzJ,EAAOs3B,EAAqBr3B,EAAOs3B,EAAyB,EAAI9I,EAAQ,EAAG,EAAI/rB,KAAKgH,IAChGvG,EAAQorB,OACRprB,EAAQuK,SAAS1N,EAAMC,EAAKhB,EAAOC,IAGnCiE,EAAQuK,SAAS1N,EAAMC,EAAKhB,EAAQu4B,EAAyBt4B,GAIjEiE,EAAQuK,SAAS1N,EAAMC,EAAKhB,EAAOC,IAIvChF,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQxF,WAAa,EACrBwF,EAAQ1F,cAAgB,EACxB0F,EAAQzF,cAAgB,GAG5ByF,EAAQY,UAAY7J,KAAKywB,MACrBzwB,KAAKoW,YACDpW,KAAKy9B,eACDz9B,KAAKm9B,eACLl0B,EAAQ0B,YACR1B,EAAQsG,IAAIzJ,EAAOu3B,EAAyB,EAAGt3B,EAAMq3B,EAAqB7I,EAAQ,EAAG,EAAI/rB,KAAKgH,IAC9FvG,EAAQorB,OACRprB,EAAQuK,SAAS1N,EAAMC,EAAM23B,EAAe34B,EAAOC,EAAS04B,IAG5Dz0B,EAAQuK,SAAS1N,EAAMC,EAAM23B,EAAe34B,EAAO/E,KAAKI,gBAAgB4E,OAAS04B,GAIrFz0B,EAAQuK,SAAS1N,EAAMC,EAAM23B,EAAe34B,EAAOC,EAAS04B,GAI5D19B,KAAKy9B,gBACDz9B,KAAKm9B,eACLl0B,EAAQ0B,YACR1B,EAAQsG,IAAIzJ,EAAMC,EAAMs3B,EAAyB,EAAG9I,EAAQ,EAAG,EAAI/rB,KAAKgH,IACxEvG,EAAQorB,OACRprB,EAAQuK,SAAS1N,EAAMC,EAAK23B,EAAe14B,IAO/CiE,EAAQuK,SAAS1N,EAAMC,EAAK23B,EAAe14B,IAK/ChF,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQvF,YAAc1D,KAAK0D,YAC3BuF,EAAQxF,WAAazD,KAAKyD,WAC1BwF,EAAQ1F,cAAgBvD,KAAKuD,cAC7B0F,EAAQzF,cAAgBxD,KAAKwD,eAE7BxD,KAAK28B,gBACL1zB,EAAQ0B,YACJ3K,KAAKoW,YACLnN,EAAQsG,IAAIzJ,EAAOu3B,EAAyB,EAAGt3B,EAAM23B,EAAenJ,EAAQ,EAAG,EAAI/rB,KAAKgH,IAGxFvG,EAAQsG,IAAIzJ,EAAO43B,EAAe33B,EAAOs3B,EAAyB,EAAI9I,EAAQ,EAAG,EAAI/rB,KAAKgH,IAE9FvG,EAAQorB,QACJr0B,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQxF,WAAa,EACrBwF,EAAQ1F,cAAgB,EACxB0F,EAAQzF,cAAgB,GAE5ByF,EAAQmP,YAAcpY,KAAKy8B,aAC3BxzB,EAAQqrB,WAGJt0B,KAAKoW,YACLnN,EAAQuK,SAAS1N,EAAOo3B,EAAoBl9B,KAAKI,gBAAgB2F,IAAM23B,EAAe19B,KAAKI,gBAAgB2E,MAAOu4B,GAGlHr0B,EAAQuK,SAASxT,KAAKI,gBAAgB0F,KAAO43B,EAAe19B,KAAKI,gBAAgB2F,IAAKu3B,EAAyBt9B,KAAKI,gBAAgB4E,SAEpIhF,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQxF,WAAa,EACrBwF,EAAQ1F,cAAgB,EACxB0F,EAAQzF,cAAgB,GAE5ByF,EAAQmP,YAAcpY,KAAKy8B,aACvBz8B,KAAKoW,YACLnN,EAAQsoB,WAAWzrB,EAAOo3B,EAAoBl9B,KAAKI,gBAAgB2F,IAAM23B,EAAe19B,KAAKI,gBAAgB2E,MAAOu4B,GAGpHr0B,EAAQsoB,WAAWvxB,KAAKI,gBAAgB0F,KAAO43B,EAAe19B,KAAKI,gBAAgB2F,IAAKu3B,EAAyBt9B,KAAKI,gBAAgB4E,SAIlJiE,EAAQ8K,WAOJsoB,EAAA98B,UAAAo+B,wBAAR,SAAgCv3B,EAAWC,GAClB,GAAjBrG,KAAK49B,WACL59B,KAAKuC,uBAAuBkJ,qBAAqBrF,EAAGC,EAAGrG,KAAKwC,sBAC5D4D,EAAIpG,KAAKwC,qBAAqB4D,EAC9BC,EAAIrG,KAAKwC,qBAAqB6D,GAG9BrG,KAAKoW,YACLpW,KAAKpB,MAAQoB,KAAKu8B,UAAY,GAAMl2B,EAAIrG,KAAKI,gBAAgB2F,KAAO/F,KAAKI,gBAAgB4E,SAAYhF,KAAKw8B,SAAWx8B,KAAKu8B,UAG1Hv8B,KAAKpB,MAAQoB,KAAKu8B,UAAan2B,EAAIpG,KAAKI,gBAAgB0F,MAAQ9F,KAAKI,gBAAgB2E,OAAU/E,KAAKw8B,SAAWx8B,KAAKu8B,WAIrHF,EAAA98B,UAAAgN,eAAP,SAAsBL,EAAiBC,EAAsBN,EAAmBC,GAC5E,QAAKmF,EAAA1R,UAAMgN,eAAczO,KAAAkC,KAACkM,EAAQC,EAAaN,EAAWC,KAI1D9L,KAAK88B,gBAAiB,EAEtB98B,KAAK29B,wBAAwBxxB,EAAY/F,EAAG+F,EAAY9F,GACxDrG,KAAK4E,MAAMsiB,kBAAkBrb,GAAa7L,MAEnC,IAGJq8B,EAAA98B,UAAA0M,eAAP,SAAsBC,EAAiBC,GAC/BnM,KAAK88B,gBACL98B,KAAK29B,wBAAwBxxB,EAAY/F,EAAG+F,EAAY9F,GAG5D4K,EAAA1R,UAAM0M,eAAcnO,KAAAkC,KAACkM,EAAQC,IAG1BkwB,EAAA98B,UAAAkN,aAAP,SAAoBP,EAAiBC,EAAsBN,EAAmBC,EAAqBY,GAC/F1M,KAAK88B,gBAAiB,SAEf98B,KAAK4E,MAAMsiB,kBAAkBrb,GACpCoF,EAAA1R,UAAMkN,aAAY3O,KAAAkC,KAACkM,EAAQC,EAAaN,EAAWC,EAAaY,IAExE2vB,EAvcA,CAA4B1pB,EAAA5S,SAAf9C,EAAAo/B,+ZCRb,IAAA5B,EAAAh9B,EAAA,GACAmC,EAAAnC,EAAA,GACAogC,EAAApgC,EAAA,IASAqgC,EAAA,WAiBA,OAjBA,gBAAa7gC,EAAA6gC,iBAsBb,IAAAC,EAAA,SAAA9sB,GAAA,SAAA8sB,IAAA,IAAA74B,EAAA,OAAA+L,KAAA+H,MAAAhZ,KAAAu3B,YAAAv3B,YAEWkF,EAAA84B,qBAAuB,IAAIp+B,EAAAkE,WAG3BoB,EAAA+4B,mBAAqB,OAErB/4B,EAAAg5B,oBAAsB,OAGtBh5B,EAAAi5B,yBAA2B,MAE3Bj5B,EAAAk5B,0BAA4B,MAE5Bl5B,EAAAm5B,wBAA0B,MAE1Bn5B,EAAAo5B,2BAA6B,MAG7Bp5B,EAAAq5B,mBAAqB,OAErBr5B,EAAAs5B,wBAA0B,UAG1Bt5B,EAAAu5B,iBAAmB,UAEnBv5B,EAAAw5B,uBAAyB,EAGzBx5B,EAAAy5B,WAAa,IAkLxB,OA/MqCttB,EAAA0sB,EAAA9sB,GA+BvB8sB,EAAAx+B,UAAA+E,aAAV,WACI,MAAO,mBAGHy5B,EAAAx+B,UAAAq/B,WAAR,SAAmB1/B,EAAa2/B,GAAhC,IAAA35B,EAAAlF,KACQ8rB,EAAS+R,EAAA/I,OAAOW,mBAAmBv2B,EAAKA,GAuB5C,OArBA4sB,EAAO/mB,MAAQ85B,GAAeA,EAAY95B,MAAQ85B,EAAY95B,MAAQ/E,KAAKi+B,mBAC3EnS,EAAO9mB,OAAS65B,GAAeA,EAAY75B,OAAS65B,EAAY75B,OAAShF,KAAKk+B,oBAC9EpS,EAAO2E,MAAQoO,GAAeA,EAAYpO,MAAQoO,EAAYpO,MAAQzwB,KAAKu+B,mBAC3EzS,EAAOgT,WAAaD,GAAeA,EAAYC,WAAaD,EAAYC,WAAa9+B,KAAKw+B,wBAC1F1S,EAAOuJ,YAAcwJ,GAAeA,EAAYxJ,YAAcwJ,EAAYxJ,YAAcr1B,KAAKm+B,yBAC7FrS,EAAOsQ,aAAeyC,GAAeA,EAAYzC,aAAeyC,EAAYzC,aAAep8B,KAAKo+B,0BAChGtS,EAAOuP,WAAawD,GAAeA,EAAYxD,WAAawD,EAAYxD,WAAar7B,KAAKq+B,wBAC1FvS,EAAOwP,cAAgBuD,GAAeA,EAAYvD,cAAgBuD,EAAYvD,cAAgBt7B,KAAKs+B,2BAEnGxS,EAAOiJ,UAAY,EACnBjJ,EAAOxoB,kBAAmB,EAE1BwoB,EAAOpoB,YAAc1D,KAAK0D,YAC1BooB,EAAOroB,WAAazD,KAAKyD,WACzBqoB,EAAOvoB,cAAgBvD,KAAKuD,cAC5BuoB,EAAOtoB,cAAgBxD,KAAKwD,cAE5BsoB,EAAO7nB,sBAAsBqB,IAAI,WAC7BJ,EAAK84B,qBAAqBxzB,gBAAgBtL,KAGvC4sB,GAQJiS,EAAAx+B,UAAAw/B,WAAP,SAAkBC,EAAqBC,GACnC,IAAI9D,EAAQ,IAAIV,EAAAtkB,WAChBglB,EAAMjE,YAAa,EACnBiE,EAAM73B,kBAAmB,EAEzB,IAAK,IAAI3F,EAAI,EAAGA,EAAIqhC,EAAKvuB,OAAQ9S,IAAK,CAClC,IAAIuhC,EAAa,KAEbD,GAAgBA,EAAaxuB,SAAWuuB,EAAKvuB,SAC7CyuB,EAAaD,EAAathC,IAG9Bw9B,EAAMzpB,WAAW1R,KAAK4+B,WAAWI,EAAKrhC,GAAIuhC,IAG9Cl/B,KAAK0R,WAAWypB,IAOb4C,EAAAx+B,UAAA4/B,gBAAP,SAAuBR,GACnB,GAAK3+B,KAAKkT,SAIV,IAAK,IAAIvV,EAAI,EAAGA,EAAIqC,KAAKkT,SAASzC,OAAQ9S,IAAK,CAC3C,IAAIiiB,EAAM5f,KAAKkT,SAASvV,GACxB,GAAKiiB,GAAoBA,EAAK1M,SAK9B,IADA,IAAIksB,EAA0Bxf,EACrB2Z,EAAI,EAAGA,EAAI6F,EAAalsB,SAASzC,OAAQ8oB,IAAK,CACnD,IAAIzN,EAASsT,EAAalsB,SAASqmB,GAEnC,GAAKzN,GAAWA,EAAO5Y,SAAS,GAAhC,CAIA,IAAImsB,EAAgBvT,EAAO5Y,SAAS,GAET,MAAvBmsB,EAAchxB,OACdyd,EAAO2E,MAASkO,EAAa3+B,KAAKy+B,iBAAmBz+B,KAAKu+B,mBAC1DzS,EAAOiJ,UAAa4J,EAAa,EAAI3+B,KAAK0+B,uBAAyB,GAGvEW,EAAchxB,KAAQswB,EAAa,EAAIU,EAAchxB,KAAKixB,cAAgBD,EAAchxB,KAAKkxB,kBAWzGlhC,OAAAC,eAAWy/B,EAAAx+B,UAAA,0BAAX,WACI,OAAOS,KAAKw/B,qDAOTzB,EAAAx+B,UAAAkgC,QAAP,SAAeC,GAAf,IAAAx6B,EAAAlF,KACIA,KAAK+L,WAAY,EACjB/L,KAAKw/B,oBAAsBE,EAG3B1/B,KAAK2/B,iBAAmBD,EAAMnQ,kBAAkBjqB,IAAI,WAChDJ,EAAK6G,WAAY,IAGrB/L,KAAK4/B,gBAAkBF,EAAMlQ,iBAAiBlqB,IAAI,WAC9CJ,EAAK6G,WAAY,IAGrB/L,KAAK6/B,oBAAsB7/B,KAAKg+B,qBAAqB14B,IAAI,SAACpG,GACtD,GAAKgG,EAAKs6B,oBAAV,CAGA,OAAQtgC,GACJ,IAAK,IAMD,OALAgG,EAAKy5B,aACDz5B,EAAKy5B,WAAa,IAClBz5B,EAAKy5B,WAAa,QAEtBz5B,EAAKi6B,gBAAgBj6B,EAAKy5B,YAE9B,IAAK,IAED,YADAz5B,EAAKs6B,oBAAoBvP,WAAW,GAExC,IAAK,IAED,YADA/qB,EAAKs6B,oBAAoBvP,WAAW,IAG5C/qB,EAAKs6B,oBAAoBvP,YAAY,EAAI/qB,EAAKy5B,WAAaz/B,EAAIogC,cAAgBpgC,GAEvD,IAApBgG,EAAKy5B,aACLz5B,EAAKy5B,WAAa,EAClBz5B,EAAKi6B,gBAAgBj6B,EAAKy5B,iBAQ/BZ,EAAAx+B,UAAAugC,WAAP,WACS9/B,KAAKw/B,sBAIVx/B,KAAKw/B,oBAAoBjQ,kBAAkBnqB,OAAOpF,KAAK2/B,kBACvD3/B,KAAKw/B,oBAAoBhQ,iBAAiBpqB,OAAOpF,KAAK4/B,iBACtD5/B,KAAKg+B,qBAAqB54B,OAAOpF,KAAK6/B,qBAEtC7/B,KAAKw/B,oBAAsB,OASjBzB,EAAAgC,oBAAd,WACI,IAAIC,EAAc,IAAIjC,EAQtB,OANAiC,EAAYjB,YAAY,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,MAC1EiB,EAAYjB,YAAY,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,MACrEiB,EAAYjB,YAAY,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,MAC/EiB,EAAYjB,YAAY,IAAU,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,MAC/EiB,EAAYjB,YAAY,OAASh6B,MAAO,WAEjCi7B,GAEfjC,EA/MA,CAAqCtD,EAAAtkB,YAAxBlZ,EAAA8gC,waCjCb,IAAAprB,EAAAlV,EAAA,GACAmC,EAAAnC,EAAA,GAMAwiC,EAAA,SAAAhvB,GA6FI,SAAAgvB,EAAmB/hC,GAAnB,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OA5FXgH,EAAAg7B,YAAa,EACbh7B,EAAA8N,YAAc,QACd9N,EAAAi7B,gBAAkB,GAClBj7B,EAAAypB,WAAa,EAiBdzpB,EAAAk7B,MAAQ,GAGRl7B,EAAAm7B,6BAA+B,IAAIzgC,EAAAkE,WAwEtCoB,EAAK7B,kBAAmB,IAoEhC,OApKiCgO,EAAA4uB,EAAAhvB,GAO7B5S,OAAAC,eAAW2hC,EAAA1gC,UAAA,iBAAX,WACI,OAAOS,KAAK2uB,gBAGhB,SAAqB/vB,GACboB,KAAK2uB,aAAe/vB,IAIxBoB,KAAK2uB,WAAa/vB,EAClBoB,KAAKyE,iDAUTpG,OAAAC,eAAW2hC,EAAA1gC,UAAA,sBAAX,WACI,OAAOS,KAAKmgC,qBAGhB,SAA0BvhC,GACtBA,EAAQ4J,KAAKuC,IAAIvC,KAAKqC,IAAI,EAAGjM,GAAQ,GAEjCoB,KAAKmgC,kBAAoBvhC,IAI7BoB,KAAKmgC,gBAAkBvhC,EACvBoB,KAAKyE,iDAITpG,OAAAC,eAAW2hC,EAAA1gC,UAAA,kBAAX,WACI,OAAOS,KAAKgT,iBAGhB,SAAsBpU,GACdoB,KAAKgT,cAAgBpU,IAIzBoB,KAAKgT,YAAcpU,EACnBoB,KAAKyE,iDAITpG,OAAAC,eAAW2hC,EAAA1gC,UAAA,iBAAX,WACI,OAAOS,KAAKkgC,gBAGhB,SAAqBthC,GAArB,IAAAsG,EAAAlF,KACQA,KAAKkgC,aAAethC,IAIxBoB,KAAKkgC,WAAathC,EAClBoB,KAAKyE,eAELzE,KAAKqgC,6BAA6B71B,gBAAgB5L,GAE9CoB,KAAKkgC,YAAclgC,KAAK4E,OAExB5E,KAAK4E,MAAMukB,qBAAqB,SAAC1X,GAC7B,GAAIA,IAAYvM,QAIao7B,IAAnB7uB,EAAS2uB,MAAnB,CAGA,IAAIG,EAA2B9uB,EAC3B8uB,EAAWH,QAAUl7B,EAAKk7B,QAC1BG,EAAWC,WAAY,wCAgB7BP,EAAA1gC,UAAA+E,aAAV,WACI,MAAO,eAGJ27B,EAAA1gC,UAAAgM,MAAP,SAAavB,EAAwBf,GAIjC,GAHAA,EAAQwK,OAERzT,KAAK2J,aAAaV,GACdjJ,KAAK+J,iBAAiBC,EAAef,GAAU,CAC/C,IAAIw3B,EAAczgC,KAAKI,gBAAgB2E,MAAQ/E,KAAK2uB,WAChD+R,EAAe1gC,KAAKI,gBAAgB4E,OAAShF,KAAK2uB,WA4BtD,IA1BI3uB,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQvF,YAAc1D,KAAK0D,YAC3BuF,EAAQxF,WAAazD,KAAKyD,WAC1BwF,EAAQ1F,cAAgBvD,KAAKuD,cAC7B0F,EAAQzF,cAAgBxD,KAAKwD,eAIjCmP,EAAA5S,QAAQuP,YAAYtP,KAAKI,gBAAgB0F,KAAO9F,KAAKI,gBAAgB2E,MAAQ,EAAG/E,KAAKI,gBAAgB2F,IAAM/F,KAAKI,gBAAgB4E,OAAS,EACrIhF,KAAKI,gBAAgB2E,MAAQ,EAAI/E,KAAK2uB,WAAa,EAAG3uB,KAAKI,gBAAgB4E,OAAS,EAAIhF,KAAK2uB,WAAa,EAAG1lB,GAEjHA,EAAQY,UAAY7J,KAAKgT,YACzB/J,EAAQorB,QAEJr0B,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQxF,WAAa,EACrBwF,EAAQ1F,cAAgB,EACxB0F,EAAQzF,cAAgB,GAG5ByF,EAAQmP,YAAcpY,KAAKywB,MAC3BxnB,EAAQkP,UAAYnY,KAAK2uB,WAEzB1lB,EAAQqrB,SAGJt0B,KAAKkgC,WAAY,CACjBj3B,EAAQY,UAAY7J,KAAKywB,MACzB,IAAIkQ,EAAcF,EAAczgC,KAAKmgC,gBACjCS,EAAcF,EAAe1gC,KAAKmgC,gBAEtCxtB,EAAA5S,QAAQuP,YAAYtP,KAAKI,gBAAgB0F,KAAO9F,KAAKI,gBAAgB2E,MAAQ,EAAG/E,KAAKI,gBAAgB2F,IAAM/F,KAAKI,gBAAgB4E,OAAS,EACrI27B,EAAc,EAAI3gC,KAAK2uB,WAAa,EAAGiS,EAAc,EAAI5gC,KAAK2uB,WAAa,EAAG1lB,GAElFA,EAAQorB,QAIhBprB,EAAQ8K,WAILksB,EAAA1gC,UAAAgN,eAAP,SAAsBL,EAAiBC,EAAsBN,EAAmBC,GAC5E,QAAKmF,EAAA1R,UAAMgN,eAAczO,KAAAkC,KAACkM,EAAQC,EAAaN,EAAWC,KAIrD9L,KAAKwgC,YACNxgC,KAAKwgC,WAAY,IAGd,IAEfP,EApKA,CAAiCttB,EAAA5S,SAApB9C,EAAAgjC,oaCPb,IAAAttB,EAAAlV,EAAA,GACAojC,EAAApjC,EAAA,IACAmC,EAAAnC,EAAA,GAOAqjC,EAAA,SAAA7vB,GAeI,SAAA6vB,EAAmB5iC,GAAnB,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OAbXgH,EAAA67B,WAAqB,EAoDtB77B,EAAA4oB,cAAgB,WACnB5oB,EAAKT,gBArCLS,EAAK9B,kBAAmB,EACxB8B,EAAKhE,qBAAuByR,EAAA5S,QAAQ6G,0BACpC1B,EAAK9D,mBAAqBuR,EAAA5S,QAAQ+G,uBAElC5B,EAAK87B,SACL97B,EAAK+7B,aAwNb,OA/O+B5vB,EAAAyvB,EAAA7vB,GA2B3B5S,OAAAC,eAAWwiC,EAAAvhC,UAAA,YAAX,WACI,OAAOS,KAAKghC,WAGhB,SAAgBpiC,GACRoB,KAAKghC,QAAUpiC,IAInBoB,KAAKghC,MAAQpiC,EACboB,KAAKyE,iDAQFq8B,EAAAvhC,UAAA2hC,MAAP,SAAar5B,GAKT,OAJK7H,KAAKihC,QAAQp5B,KACd7H,KAAKihC,QAAQp5B,GAAS,IAAIg5B,EAAAvT,eAAettB,OAGtCA,KAAKihC,QAAQp5B,IAajBi5B,EAAAvhC,UAAA+F,IAAP,mBAAAJ,EAAAlF,KAAWmhC,KAAAhvB,EAAA,EAAAA,EAAAolB,UAAA9mB,OAAA0B,IAAAgvB,EAAAhvB,GAAAolB,UAAAplB,GACP,OAAOgvB,EAAMC,IAAI,SAAAC,GAAQ,OAAAn8B,EAAKgD,KAAKm5B,MAQhCP,EAAAvhC,UAAA2I,KAAP,SAAYm5B,GACR,IAAIC,EAAwBthC,KAAKkhC,MAAMlhC,KAAKihC,QAAQxwB,QAEpD,OAAY,MAAR4wB,EAAqBC,GAErBD,aAAgBzhC,EAAA+d,aAChB2jB,EAAM15B,KAAOy5B,EAERA,aAAgB1uB,EAAA5S,QACrBuhC,EAAM7vB,QAAU4vB,EAED,MAAVA,EAAKj7B,GAAuB,MAAVi7B,EAAKh7B,IAC5Bi7B,EAAMl7B,EAAIi7B,EAAKj7B,EACfk7B,EAAMj7B,EAAIg7B,EAAKh7B,GAGZi7B,IAOJR,EAAAvhC,UAAA6F,OAAP,SAAcxG,GACV,IAAIiJ,EAEJ,GAAIjJ,aAAiBiiC,EAAAvT,gBAGjB,IAAe,KAFfzlB,EAAQ7H,KAAKihC,QAAQl5B,QAAQnJ,IAGzB,YAIJiJ,EAAQjJ,EAGZ,IAAI0iC,EAAkCthC,KAAKihC,QAAQp5B,GAE9Cy5B,IAILA,EAAM3zB,UAEN3N,KAAKihC,QAAQh5B,OAAOJ,EAAO,KAI/BxJ,OAAAC,eAAWwiC,EAAAvhC,UAAA,iBAAX,WACI,OAAOS,KAAK+gC,gBAGhB,SAAqBniC,GACboB,KAAK+gC,aAAeniC,IAIxBoB,KAAK+gC,WAAaniC,EAClBoB,KAAKyE,iDAGTpG,OAAAC,eAAWwiC,EAAAvhC,UAAA,2BAAX,SAA+BX,qCAI/BP,OAAAC,eAAWwiC,EAAAvhC,UAAA,yBAAX,SAA6BX,qCAInBkiC,EAAAvhC,UAAA+E,aAAV,WACI,MAAO,aAGJw8B,EAAAvhC,UAAAgM,MAAP,SAAavB,EAAwBf,GAYjC,GAXAA,EAAQwK,QAEJzT,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQvF,YAAc1D,KAAK0D,YAC3BuF,EAAQxF,WAAazD,KAAKyD,WAC1BwF,EAAQ1F,cAAgBvD,KAAKuD,cAC7B0F,EAAQzF,cAAgBxD,KAAKwD,eAGjCxD,KAAK2J,aAAaV,GAEdjJ,KAAK+J,iBAAiBC,EAAef,GAAU,CAC/CA,EAAQmP,YAAcpY,KAAKywB,MAC3BxnB,EAAQkP,UAAYnY,KAAK+gC,WACzB93B,EAAQs4B,YAAYvhC,KAAKghC,OAEzB/3B,EAAQ0B,YAER,IAAI62B,GAAiB,EAErBxhC,KAAKihC,QAAQ/G,QAAQ,SAAAoH,GACZA,IAIDE,GACAv4B,EAAQurB,OAAO8M,EAAM3T,OAAOvnB,EAAGk7B,EAAM3T,OAAOtnB,GAE5Cm7B,GAAQ,GAGRv4B,EAAQwrB,OAAO6M,EAAM3T,OAAOvnB,EAAGk7B,EAAM3T,OAAOtnB,MAIpD4C,EAAQqrB,SAGZrrB,EAAQ8K,WAGF+sB,EAAAvhC,UAAA+K,sBAAV,SAAgCN,EAAwBf,GAAxD,IAAA/D,EAAAlF,KACIA,KAAKyhC,MAAQ,KACbzhC,KAAK0hC,MAAQ,KACb1hC,KAAK2hC,MAAQ,KACb3hC,KAAK4hC,MAAQ,KAEb5hC,KAAKihC,QAAQ/G,QAAQ,SAACoH,EAAOz5B,GACpBy5B,IAILA,EAAMl4B,aAEY,MAAdlE,EAAKu8B,OAAiBH,EAAM3T,OAAOvnB,EAAIlB,EAAKu8B,SAAOv8B,EAAKu8B,MAAQH,EAAM3T,OAAOvnB,IAC/D,MAAdlB,EAAKw8B,OAAiBJ,EAAM3T,OAAOtnB,EAAInB,EAAKw8B,SAAOx8B,EAAKw8B,MAAQJ,EAAM3T,OAAOtnB,IAC/D,MAAdnB,EAAKy8B,OAAiBL,EAAM3T,OAAOvnB,EAAIlB,EAAKy8B,SAAOz8B,EAAKy8B,MAAQL,EAAM3T,OAAOvnB,IAC/D,MAAdlB,EAAK08B,OAAiBN,EAAM3T,OAAOtnB,EAAInB,EAAK08B,SAAO18B,EAAK08B,MAAQN,EAAM3T,OAAOtnB,MAGnE,MAAdrG,KAAKyhC,QAAezhC,KAAKyhC,MAAQ,GACnB,MAAdzhC,KAAK0hC,QAAe1hC,KAAK0hC,MAAQ,GACnB,MAAd1hC,KAAK2hC,QAAe3hC,KAAK2hC,MAAQ,GACnB,MAAd3hC,KAAK4hC,QAAe5hC,KAAK4hC,MAAQ,IAGlCd,EAAAvhC,UAAA6K,SAAP,WACsB,MAAdpK,KAAKyhC,OAA+B,MAAdzhC,KAAK2hC,OAA+B,MAAd3hC,KAAK0hC,OAA+B,MAAd1hC,KAAK4hC,QAI3E5hC,KAAKI,gBAAgB2E,MAAQyD,KAAKC,IAAIzI,KAAK2hC,MAAQ3hC,KAAKyhC,OAASzhC,KAAK+gC,WACtE/gC,KAAKI,gBAAgB4E,OAASwD,KAAKC,IAAIzI,KAAK4hC,MAAQ5hC,KAAK0hC,OAAS1hC,KAAK+gC,aAGjED,EAAAvhC,UAAA8K,kBAAV,SAA4BL,EAAwBf,GAC9B,MAAdjJ,KAAKyhC,OAA+B,MAAdzhC,KAAK0hC,QAI/B1hC,KAAKI,gBAAgB0F,KAAO9F,KAAKyhC,MAAQzhC,KAAK+gC,WAAa,EAC3D/gC,KAAKI,gBAAgB2F,IAAM/F,KAAK0hC,MAAQ1hC,KAAK+gC,WAAa,IAGvDD,EAAAvhC,UAAAoO,QAAP,WACI,KAAO3N,KAAKihC,QAAQxwB,OAAS,GACzBzQ,KAAKoF,OAAOpF,KAAKihC,QAAQxwB,OAAS,GAGtCQ,EAAA1R,UAAMoO,QAAO7P,KAAAkC,OAGrB8gC,EA/OA,CAA+BnuB,EAAA5S,SAAlB9C,EAAA6jC,kaCTb,IAAAnuB,EAAAlV,EAAA,GACAkC,EAAAlC,EAAA,GACAmC,EAAAnC,EAAA,GAIAokC,EAAA,SAAA5wB,GA+II,SAAA4wB,EAAmB3jC,GAAnB,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OA9IXgH,EAAA67B,WAAa,EACb77B,EAAA48B,IAAM,IAAIniC,EAAAgB,aAAa,GACvBuE,EAAA68B,IAAM,IAAIpiC,EAAAgB,aAAa,GACvBuE,EAAA88B,IAAM,IAAIriC,EAAAgB,aAAa,GACvBuE,EAAA+8B,IAAM,IAAItiC,EAAAgB,aAAa,GACvBuE,EAAA87B,MAAQ,IAAI5vB,MA4IhBlM,EAAK9B,kBAAmB,EACxB8B,EAAKhE,qBAAuByR,EAAA5S,QAAQ6G,0BACpC1B,EAAK9D,mBAAqBuR,EAAA5S,QAAQ+G,yBA0F1C,OA9O0BuK,EAAAwwB,EAAA5wB,GAWtB5S,OAAAC,eAAWujC,EAAAtiC,UAAA,YAAX,WACI,OAAOS,KAAKghC,WAGhB,SAAgBpiC,GACRoB,KAAKghC,QAAUpiC,IAInBoB,KAAKghC,MAAQpiC,EACboB,KAAKyE,iDAITpG,OAAAC,eAAWujC,EAAAtiC,UAAA,wBAAX,WACI,OAAOS,KAAKkiC,uBAGhB,SAA4BtjC,GAA5B,IAAAsG,EAAAlF,KACQA,KAAKkiC,oBAAsBtjC,IAI3BoB,KAAKmiC,gCAAkCniC,KAAKkiC,oBAC5CliC,KAAKkiC,kBAAkB99B,kBAAkBgB,OAAOpF,KAAKmiC,gCACrDniC,KAAKmiC,+BAAiC,MAGtCvjC,IACAoB,KAAKmiC,+BAAiCvjC,EAAMwF,kBAAkBkB,IAAI,WAAM,OAAAJ,EAAKT,kBAGjFzE,KAAKkiC,kBAAoBtjC,EACzBoB,KAAKyE,iDAITpG,OAAAC,eAAWujC,EAAAtiC,UAAA,UAAX,WACI,OAAOS,KAAK8hC,IAAIn9B,SAAS3E,KAAK4E,YAGlC,SAAchG,GACNoB,KAAK8hC,IAAIn9B,SAAS3E,KAAK4E,SAAWhG,GAIlCoB,KAAK8hC,IAAIj9B,WAAWjG,IACpBoB,KAAKyE,gDAKbpG,OAAAC,eAAWujC,EAAAtiC,UAAA,UAAX,WACI,OAAOS,KAAK+hC,IAAIp9B,SAAS3E,KAAK4E,YAGlC,SAAchG,GACNoB,KAAK+hC,IAAIp9B,SAAS3E,KAAK4E,SAAWhG,GAIlCoB,KAAK+hC,IAAIl9B,WAAWjG,IACpBoB,KAAKyE,gDAKbpG,OAAAC,eAAWujC,EAAAtiC,UAAA,UAAX,WACI,OAAOS,KAAKgiC,IAAIr9B,SAAS3E,KAAK4E,YAGlC,SAAchG,GACNoB,KAAKgiC,IAAIr9B,SAAS3E,KAAK4E,SAAWhG,GAIlCoB,KAAKgiC,IAAIn9B,WAAWjG,IACpBoB,KAAKyE,gDAKbpG,OAAAC,eAAWujC,EAAAtiC,UAAA,UAAX,WACI,OAAOS,KAAKiiC,IAAIt9B,SAAS3E,KAAK4E,YAGlC,SAAchG,GACNoB,KAAKiiC,IAAIt9B,SAAS3E,KAAK4E,SAAWhG,GAIlCoB,KAAKiiC,IAAIp9B,WAAWjG,IACpBoB,KAAKyE,gDAKbpG,OAAAC,eAAWujC,EAAAtiC,UAAA,iBAAX,WACI,OAAOS,KAAK+gC,gBAGhB,SAAqBniC,GACboB,KAAK+gC,aAAeniC,IAIxBoB,KAAK+gC,WAAaniC,EAClBoB,KAAKyE,iDAITpG,OAAAC,eAAWujC,EAAAtiC,UAAA,2BAAX,SAA+BX,qCAK/BP,OAAAC,eAAWujC,EAAAtiC,UAAA,yBAAX,SAA6BX,qCAI7BP,OAAAC,eAAYujC,EAAAtiC,UAAA,oBAAZ,WACI,OAAQS,KAAKkiC,kBAAoBliC,KAAKkiC,kBAAkB9hB,QAAU,GAAKpgB,KAAKgiC,IAAIt8B,SAAS1F,KAAK4E,wCAGlGvG,OAAAC,eAAYujC,EAAAtiC,UAAA,oBAAZ,WACI,OAAQS,KAAKkiC,kBAAoBliC,KAAKkiC,kBAAkB7hB,QAAU,GAAKrgB,KAAKiiC,IAAIv8B,SAAS1F,KAAK4E,wCAexFi9B,EAAAtiC,UAAA+E,aAAV,WACI,MAAO,QAGJu9B,EAAAtiC,UAAAgM,MAAP,SAAavB,EAAwBf,GACjCA,EAAQwK,QAEJzT,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQvF,YAAc1D,KAAK0D,YAC3BuF,EAAQxF,WAAazD,KAAKyD,WAC1BwF,EAAQ1F,cAAgBvD,KAAKuD,cAC7B0F,EAAQzF,cAAgBxD,KAAKwD,eAGjCxD,KAAK2J,aAAaV,GACdjJ,KAAK+J,iBAAiBC,EAAef,KACrCA,EAAQmP,YAAcpY,KAAKywB,MAC3BxnB,EAAQkP,UAAYnY,KAAK+gC,WACzB93B,EAAQs4B,YAAYvhC,KAAKghC,OAEzB/3B,EAAQ0B,YACR1B,EAAQurB,OAAOx0B,KAAK8hC,IAAIp8B,SAAS1F,KAAK4E,OAAQ5E,KAAK+hC,IAAIr8B,SAAS1F,KAAK4E,QAErEqE,EAAQwrB,OAAOz0B,KAAKoiC,aAAcpiC,KAAKqiC,cAEvCp5B,EAAQqrB,UAGZrrB,EAAQ8K,WAGL8tB,EAAAtiC,UAAA6K,SAAP,WAEIpK,KAAKI,gBAAgB2E,MAAQyD,KAAKC,IAAIzI,KAAK8hC,IAAIp8B,SAAS1F,KAAK4E,OAAS5E,KAAKoiC,cAAgBpiC,KAAK+gC,WAChG/gC,KAAKI,gBAAgB4E,OAASwD,KAAKC,IAAIzI,KAAK+hC,IAAIr8B,SAAS1F,KAAK4E,OAAS5E,KAAKqiC,cAAgBriC,KAAK+gC,YAG3Fc,EAAAtiC,UAAA8K,kBAAV,SAA4BL,EAAwBf,GAChDjJ,KAAKI,gBAAgB0F,KAAO0C,KAAKqC,IAAI7K,KAAK8hC,IAAIp8B,SAAS1F,KAAK4E,OAAQ5E,KAAKoiC,cAAgBpiC,KAAK+gC,WAAa,EAC3G/gC,KAAKI,gBAAgB2F,IAAMyC,KAAKqC,IAAI7K,KAAK+hC,IAAIr8B,SAAS1F,KAAK4E,OAAQ5E,KAAKqiC,cAAgBriC,KAAK+gC,WAAa,GASvGc,EAAAtiC,UAAAgH,cAAP,SAAqBC,EAAmBC,EAAc67B,GAClD,QADkD,IAAAA,OAAA,GAC7CtiC,KAAK4E,OAAS5E,KAAK4F,QAAU5F,KAAK4E,MAAM8B,eAA7C,CAKA,IAAIK,EAAiB/G,KAAK4E,MAAMoC,mBAAmBP,GAC/CQ,EAAoBrH,EAAAsH,QAAQC,QAAQX,EAAU5G,EAAAwH,OAAO9E,WAAYmE,EAAMY,qBAAsBN,GAEjG/G,KAAKsH,yBAAyBL,EAAmBq7B,GAE7Cr7B,EAAkBM,EAAI,GAAKN,EAAkBM,EAAI,EACjDvH,KAAKwH,eAAgB,EAGzBxH,KAAKwH,eAAgB,OAbjB5H,EAAA6H,MAAMC,MAAM,2EAqBbm6B,EAAAtiC,UAAA+H,yBAAP,SAAgCL,EAA4Bq7B,QAAA,IAAAA,OAAA,GACxD,IAAIl8B,EAAaa,EAAkBb,EAAIpG,KAAK2D,aAAa+B,SAAS1F,KAAK4E,OAAU,KAC7EyB,EAAaY,EAAkBZ,EAAIrG,KAAK4D,aAAa8B,SAAS1F,KAAK4E,OAAU,KAE7E09B,GACAtiC,KAAKuiC,GAAKn8B,EACVpG,KAAKwiC,GAAKn8B,EACVrG,KAAKgiC,IAAIz5B,uBAAwB,EACjCvI,KAAKiiC,IAAI15B,uBAAwB,IAEjCvI,KAAKyiC,GAAKr8B,EACVpG,KAAK0iC,GAAKr8B,EACVrG,KAAK8hC,IAAIv5B,uBAAwB,EACjCvI,KAAK+hC,IAAIx5B,uBAAwB,IAG7Cs5B,EA9OA,CAA0BlvB,EAAA5S,SAAb9C,EAAA4kC,6ZCNb,IAKAc,EAAA,SAAA1xB,GAAA,SAAA0xB,mDAQA,OARmCtxB,EAAAsxB,EAAA1xB,GACrB0xB,EAAApjC,UAAAmxB,kBAAV,SAA4BriB,GAExB,IADA,IAAIu0B,EAAM,GACDjlC,EAAI,EAAGA,EAAI0Q,EAAKoC,OAAQ9S,IAC7BilC,GAAO,IAEX,OAAOA,GAEfD,EARA,CALAllC,EAAA,IAKmC8wB,WAAtBtxB,EAAA0lC,saCLb,IAAAzsB,EAAAzY,EAAA,GACAkC,EAAAlC,EAAA,GACAkV,EAAAlV,EAAA,GAMAolC,EAAA,SAAA5xB,GAiPI,SAAA4xB,EAAmB3kC,GAAnB,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OAhPXgH,EAAA49B,gBAAkB,IAAI1xB,MACtBlM,EAAA69B,mBAAqB,IAAI3xB,MACzBlM,EAAA89B,UACA99B,EAAA+9B,eAAiB,IAAI7xB,QAkVjC,OAtV0BC,EAAAwxB,EAAA5xB,GAOtB5S,OAAAC,eAAWukC,EAAAtjC,UAAA,gBAAX,WACI,OAAOS,KAAKijC,gDASTJ,EAAAtjC,UAAA2jC,iBAAP,SAAwBl+B,EAAgBS,GAKpC,YALoC,IAAAA,OAAA,GACpCzF,KAAK8iC,gBAAgB56B,KAAK,IAAIvI,EAAAgB,aAAaqE,EAAQS,EAAU9F,EAAAgB,aAAaC,eAAiBjB,EAAAgB,aAAaG,sBAExGd,KAAKyE,eAEEzE,MASJ6iC,EAAAtjC,UAAA4jC,oBAAP,SAA2Bp+B,EAAeU,GAKtC,YALsC,IAAAA,OAAA,GACtCzF,KAAK+iC,mBAAmB76B,KAAK,IAAIvI,EAAAgB,aAAaoE,EAAOU,EAAU9F,EAAAgB,aAAaC,eAAiBjB,EAAAgB,aAAaG,sBAE1Gd,KAAKyE,eAEEzE,MAUJ6iC,EAAAtjC,UAAA6jC,iBAAP,SAAwBv7B,EAAe7C,EAAgBS,GACnD,YADmD,IAAAA,OAAA,GAC/CoC,EAAQ,GAAKA,GAAS7H,KAAK8iC,gBAAgBryB,OACpCzQ,MAGXA,KAAK8iC,gBAAgBj7B,GAAS,IAAIlI,EAAAgB,aAAaqE,EAAQS,EAAU9F,EAAAgB,aAAaC,eAAiBjB,EAAAgB,aAAaG,qBAE5Gd,KAAKyE,eAEEzE,OAUJ6iC,EAAAtjC,UAAA8jC,oBAAP,SAA2Bx7B,EAAe9C,EAAeU,GACrD,YADqD,IAAAA,OAAA,GACjDoC,EAAQ,GAAKA,GAAS7H,KAAK+iC,mBAAmBtyB,OACvCzQ,MAGXA,KAAK+iC,mBAAmBl7B,GAAS,IAAIlI,EAAAgB,aAAaoE,EAAOU,EAAU9F,EAAAgB,aAAaC,eAAiBjB,EAAAgB,aAAaG,qBAE9Gd,KAAKyE,eAEEzE,OAGH6iC,EAAAtjC,UAAA+jC,YAAR,SAAoBC,EAAiBrkC,GACjC,GAAKqkC,EAAL,CAIAtyB,EAAA1R,UAAMsO,cAAa/P,KAAAkC,KAACujC,GAEpB,IAAoB,IAAApxB,EAAA,EAAAC,EAAAmxB,EAAKrwB,SAALf,EAAAC,EAAA3B,OAAA0B,IAAe,CAA9B,IAAIV,EAAOW,EAAAD,GACRqxB,EAAaxjC,KAAKijC,eAAel7B,QAAQ0J,IAEzB,IAAhB+xB,GACAxjC,KAAKijC,eAAeh7B,OAAOu7B,EAAY,UAIxCxjC,KAAKgjC,OAAO9jC,KAGf2jC,EAAAtjC,UAAAkkC,YAAR,SAAoBC,EAAqBxkC,GACrC,GAAKc,KAAKgjC,OAAO9jC,GAAjB,CAIAc,KAAKgjC,OAAOU,GAAe1jC,KAAKgjC,OAAO9jC,GAEvC,IAAoB,IAAAiT,EAAA,EAAAC,EAAApS,KAAKgjC,OAAOU,GAAaxwB,SAAzBf,EAAAC,EAAA3B,OAAA0B,IAAmC,CAAvCC,EAAAD,GACJwxB,KAAOD,SAGZ1jC,KAAKgjC,OAAO9jC,KAQhB2jC,EAAAtjC,UAAAqkC,uBAAP,SAA8B/7B,GAC1B,GAAIA,EAAQ,GAAKA,GAAS7H,KAAK+iC,mBAAmBtyB,OAC9C,OAAOzQ,KAGX,IAAK,IAAIoG,EAAI,EAAGA,EAAIpG,KAAK8iC,gBAAgBryB,OAAQrK,IAAK,CAClD,IAAIlH,EAASkH,EAAC,IAAIyB,EACd07B,EAAOvjC,KAAKgjC,OAAO9jC,GAEvBc,KAAKsjC,YAAYC,EAAMrkC,GAG3B,IAASkH,EAAI,EAAGA,EAAIpG,KAAK8iC,gBAAgBryB,OAAQrK,IAC7C,IAAK,IAAIC,EAAIwB,EAAQ,EAAGxB,EAAIrG,KAAK+iC,mBAAmBtyB,OAAQpK,IAAK,CAC7D,IAAIq9B,EAAiBt9B,EAAC,KAAIC,EAAI,GAC1BnH,EAASkH,EAAC,IAAIC,EAElBrG,KAAKyjC,YAAYC,EAAaxkC,GAQtC,OAJAc,KAAK+iC,mBAAmB96B,OAAOJ,EAAO,GAEtC7H,KAAKyE,eAEEzE,MAQJ6iC,EAAAtjC,UAAAskC,oBAAP,SAA2Bh8B,GACvB,GAAIA,EAAQ,GAAKA,GAAS7H,KAAK8iC,gBAAgBryB,OAC3C,OAAOzQ,KAGX,IAAK,IAAIqG,EAAI,EAAGA,EAAIrG,KAAK+iC,mBAAmBtyB,OAAQpK,IAAK,CACrD,IAAInH,EAAS2I,EAAK,IAAIxB,EAClBk9B,EAAOvjC,KAAKgjC,OAAO9jC,GAEvBc,KAAKsjC,YAAYC,EAAMrkC,GAG3B,IAASmH,EAAI,EAAGA,EAAIrG,KAAK+iC,mBAAmBtyB,OAAQpK,IAChD,IAAK,IAAID,EAAIyB,EAAQ,EAAGzB,EAAIpG,KAAK8iC,gBAAgBryB,OAAQrK,IAAK,CAC1D,IAAIs9B,EAAiBt9B,EAAI,EAAC,IAAIC,EAC1BnH,EAASkH,EAAC,IAAIC,EAElBrG,KAAKyjC,YAAYC,EAAaxkC,GAQtC,OAJAc,KAAK8iC,gBAAgB76B,OAAOJ,EAAO,GAEnC7H,KAAKyE,eAEEzE,MAUJ6iC,EAAAtjC,UAAAmS,WAAP,SAAkBD,EAAkBmO,EAAiBD,QAAjB,IAAAC,MAAA,QAAiB,IAAAD,MAAA,GACb,IAAhC3f,KAAK8iC,gBAAgBryB,QAErBzQ,KAAKkjC,iBAAiB,GAAG,GAGU,IAAnCljC,KAAK+iC,mBAAmBtyB,QAExBzQ,KAAKmjC,oBAAoB,GAAG,GAGhC,IAEIjkC,EAFIsJ,KAAKqC,IAAI+U,EAAK5f,KAAK8iC,gBAAgBryB,OAAS,GAEtC,IADNjI,KAAKqC,IAAI8U,EAAQ3f,KAAK+iC,mBAAmBtyB,OAAS,GAEtDqzB,EAAgB9jC,KAAKgjC,OAAO9jC,GAgBhC,OAdK4kC,IACDA,EAAgB,IAAI5tB,EAAAtD,UAAU1T,GAC9Bc,KAAKgjC,OAAO9jC,GAAO4kC,EACnBA,EAAcn9B,oBAAsBgM,EAAA5S,QAAQ6G,0BAC5Ck9B,EAAcj9B,kBAAoB8L,EAAA5S,QAAQ+G,uBAC1CmK,EAAA1R,UAAMmS,WAAU5T,KAAAkC,KAAC8jC,IAGrBA,EAAcpyB,WAAWD,GACzBzR,KAAKijC,eAAe/6B,KAAKuJ,GACzBA,EAAQkyB,KAAOzkC,EAEfc,KAAKyE,eAEEzE,MAQJ6iC,EAAAtjC,UAAAsO,cAAP,SAAqB4D,GACjB,IAAI5J,EAAQ7H,KAAKijC,eAAel7B,QAAQ0J,IAEzB,IAAX5J,GACA7H,KAAKijC,eAAeh7B,OAAOJ,EAAO,GAGtC,IAAI07B,EAAOvjC,KAAKgjC,OAAOvxB,EAAQkyB,MAO/B,OALIJ,GACAA,EAAK11B,cAAc4D,GAGvBzR,KAAKyE,eACEzE,MAWD6iC,EAAAtjC,UAAA+E,aAAV,WACI,MAAO,QAGDu+B,EAAAtjC,UAAA+K,sBAAV,SAAgCN,EAAwBf,GAapD,IAZA,IAAI86B,KACAC,KACAC,KACAC,KAEArT,EAAiB7wB,KAAKI,gBAAgB2E,MACtCo/B,EAAwB,EACxBC,EAAkBpkC,KAAKI,gBAAgB4E,OACvCq/B,EAAyB,EAGzBx8B,EAAQ,EACMsK,EAAA,EAAAC,EAAApS,KAAK8iC,gBAAL3wB,EAAAC,EAAA3B,OAAA0B,IAAsB,CACpC,IADKvT,EAAKwT,EAAAD,IACA1M,QAEN2+B,GADIp/B,EAASpG,EAAM8G,SAAS1F,KAAK4E,OAEjCo/B,EAAQn8B,GAAS7C,OAEjBq/B,GAA0BzlC,EAAMgb,cAEpC/R,IAGJ,IAAI9B,EAAM,EACV8B,EAAQ,EACR,IAAkB,IAAAgO,EAAA,EAAAC,EAAA9V,KAAK8iC,gBAALjtB,EAAAC,EAAArF,OAAAoF,IAAsB,CAAnC,IAIO7Q,EAJHpG,EAAKkX,EAAAD,GAGV,GAFAquB,EAAKh8B,KAAKnC,GAELnH,EAAM6G,QAKPM,GAAOnH,EAAM8G,SAAS1F,KAAK4E,YAH3BmB,GADIf,EAAUpG,EAAMgb,cAAgByqB,EAA0BD,EAE9DJ,EAAQn8B,GAAS7C,EAIrB6C,IAIJA,EAAQ,EACR,IAAkB,IAAAy8B,EAAA,EAAAC,EAAAvkC,KAAK+iC,mBAALuB,EAAAC,EAAA9zB,OAAA6zB,IAAyB,CACvC,IADK1lC,EAAK2lC,EAAAD,IACA7+B,QAENorB,GADI9rB,EAAQnG,EAAM8G,SAAS1F,KAAK4E,OAEhCm/B,EAAOl8B,GAAS9C,OAEhBo/B,GAAyBvlC,EAAMgb,cAEnC/R,IAGJ,IAAI/B,EAAO,EACX+B,EAAQ,EACR,IAAkB,IAAA28B,EAAA,EAAAC,EAAAzkC,KAAK+iC,mBAALyB,EAAAC,EAAAh0B,OAAA+zB,IAAyB,CAAtC,IAGOz/B,EAHHnG,EAAK6lC,EAAAD,GAEV,GADAP,EAAM/7B,KAAKpC,GACNlH,EAAM6G,QAKPK,GAAQlH,EAAM8G,SAAS1F,KAAK4E,YAH5BkB,GADIf,EAASnG,EAAMgb,cAAgBuqB,EAAyBtT,EAE5DkT,EAAOl8B,GAAS9C,EAIpB8C,IAIJ,IAAK,IAAI3I,KAAOc,KAAKgjC,OACjB,GAAKhjC,KAAKgjC,OAAOxjC,eAAeN,GAAhC,CAGA,IAAIuZ,EAAQvZ,EAAIuZ,MAAM,KAClBrS,EAAIs+B,SAASjsB,EAAM,IACnBpS,EAAIq+B,SAASjsB,EAAM,IACnB8qB,EAAOvjC,KAAKgjC,OAAO9jC,GAEvBqkC,EAAKz9B,KAAOm+B,EAAM59B,GAAK,KACvBk9B,EAAKx9B,IAAMm+B,EAAK99B,GAAK,KACrBm9B,EAAKx+B,MAAQg/B,EAAO19B,GAAK,KACzBk9B,EAAKv+B,OAASg/B,EAAQ59B,GAAK,KAG/B6K,EAAA1R,UAAM+K,sBAAqBxM,KAAAkC,KAACgK,EAAef,IAIxC45B,EAAAtjC,UAAAoO,QAAP,WACIsD,EAAA1R,UAAMoO,QAAO7P,KAAAkC,MAEb,IAAoB,IAAAmS,EAAA,EAAAC,EAAApS,KAAKijC,eAAL9wB,EAAAC,EAAA3B,OAAA0B,IAAqB,CAAzBC,EAAAD,GACJxE,YAGpBk1B,EAtVA,CAA0B3sB,EAAAtD,WAAb3V,EAAA4lC,6ZCRb,IAAA3sB,EAAAzY,EAAA,GACAkV,EAAAlV,EAAA,GAIAknC,EAAA,SAAA1zB,GAqBI,SAAA0zB,EAAmBzmC,GAAnB,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OApBXgH,EAAAypB,WAAa,IAgFzB,OAjF6Btd,EAAAszB,EAAA1zB,GAIzB5S,OAAAC,eAAWqmC,EAAAplC,UAAA,iBAAX,WACI,OAAOS,KAAK2uB,gBAGhB,SAAqB/vB,GACboB,KAAK2uB,aAAe/vB,IAIxBoB,KAAK2uB,WAAa/vB,EAClBoB,KAAKyE,iDAWCkgC,EAAAplC,UAAA+E,aAAV,WACI,MAAO,WAGDqgC,EAAAplC,UAAAgU,WAAV,SAAqBtK,GACjBA,EAAQwK,QAEJzT,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQvF,YAAc1D,KAAK0D,YAC3BuF,EAAQxF,WAAazD,KAAKyD,WAC1BwF,EAAQ1F,cAAgBvD,KAAKuD,cAC7B0F,EAAQzF,cAAgBxD,KAAKwD,eAGjCmP,EAAA5S,QAAQuP,YAAYtP,KAAKI,gBAAgB0F,KAAO9F,KAAKI,gBAAgB2E,MAAQ,EAAG/E,KAAKI,gBAAgB2F,IAAM/F,KAAKI,gBAAgB4E,OAAS,EACrIhF,KAAKI,gBAAgB2E,MAAQ,EAAI/E,KAAK2uB,WAAa,EAAG3uB,KAAKI,gBAAgB4E,OAAS,EAAIhF,KAAK2uB,WAAa,EAAG1lB,GAE7GjJ,KAAKgT,cACL/J,EAAQY,UAAY7J,KAAKgT,YAEzB/J,EAAQorB,SAGRr0B,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQxF,WAAa,EACrBwF,EAAQ1F,cAAgB,EACxB0F,EAAQzF,cAAgB,GAGxBxD,KAAK2uB,aACD3uB,KAAKywB,QACLxnB,EAAQmP,YAAcpY,KAAKywB,OAE/BxnB,EAAQkP,UAAYnY,KAAK2uB,WAEzB1lB,EAAQqrB,UAGZrrB,EAAQ8K,WAGF4wB,EAAAplC,UAAA+K,sBAAV,SAAgCN,EAAwBf,GACpDgI,EAAA1R,UAAM+K,sBAAqBxM,KAAAkC,KAACgK,EAAef,GAE3CjJ,KAAK6S,oBAAoB9N,OAAS,EAAI/E,KAAK2uB,WAC3C3uB,KAAK6S,oBAAoB7N,QAAU,EAAIhF,KAAK2uB,WAC5C3uB,KAAK6S,oBAAoB/M,MAAQ9F,KAAK2uB,WACtC3uB,KAAK6S,oBAAoB9M,KAAO/F,KAAK2uB,YAG/BgW,EAAAplC,UAAAmU,iBAAV,SAA2BzK,GAEvB0J,EAAA5S,QAAQuP,YAAYtP,KAAKI,gBAAgB0F,KAAO9F,KAAKI,gBAAgB2E,MAAQ,EAAG/E,KAAKI,gBAAgB2F,IAAM/F,KAAKI,gBAAgB4E,OAAS,EAAGhF,KAAKI,gBAAgB2E,MAAQ,EAAG/E,KAAKI,gBAAgB4E,OAAS,EAAGiE,GAE7MA,EAAQyB,QAEhBi6B,EAjFA,CAA6BzuB,EAAAtD,WAAhB3V,EAAA0nC,gaCLb,IAAAhyB,EAAAlV,EAAA,GACAmC,EAAAnC,EAAA,GAIAmnC,EAAA,SAAA3zB,GAkFI,SAAA2zB,EAAmB1mC,GAAnB,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OA/EXgH,EAAA2K,OAAiBjQ,EAAAgb,OAAOC,MACxB3V,EAAA2/B,UAAY,IAAIjlC,EAAAgb,OAEhB1V,EAAA4/B,yBAA0B,EAC1B5/B,EAAA6/B,wBAAyB,EAEzB7/B,EAAA8/B,YAAc,EACd9/B,EAAA+/B,WAAa,EACb//B,EAAAggC,YAAc,EAEdhgC,EAAAigC,GAAK,IACLjgC,EAAAkgC,GAAK,EACLlgC,EAAAmgC,GAAK,EAKNngC,EAAA23B,yBAA2B,IAAIj9B,EAAAkE,WAkT9BoB,EAAA43B,gBAAiB,EAlPrB53B,EAAKtG,MAAQ,IAAIgB,EAAAgb,OAAO,IAAK,GAAI,IACjC1V,EAAKqnB,KAAO,QACZrnB,EAAK7B,kBAAmB,IAgVhC,OAtaiCgO,EAAAuzB,EAAA3zB,GAuB7B5S,OAAAC,eAAWsmC,EAAArlC,UAAA,aAAX,WACI,OAAOS,KAAK6P,YAGhB,SAAiBjR,GACToB,KAAK6P,OAAOy1B,OAAO1mC,KAIvBoB,KAAK6P,OAAO3F,SAAStL,GAErBoB,KAAKulC,UAAUvlC,KAAK6P,OAAQ7P,KAAK6kC,WAEjC7kC,KAAKmlC,GAAKnlC,KAAK6kC,UAAUpmC,EACzBuB,KAAKolC,GAAK58B,KAAKuC,IAAI/K,KAAK6kC,UAAUW,EAAG,MACrCxlC,KAAKqlC,GAAK78B,KAAKuC,IAAI/K,KAAK6kC,UAAU/L,EAAG,MAErC94B,KAAKyE,eAELzE,KAAK68B,yBAAyBryB,gBAAgBxK,KAAK6P,0CAIvDxR,OAAAC,eAAWsmC,EAAArlC,UAAA,aAAX,SAAiBX,GACToB,KAAKa,OAAO8D,SAAS3E,KAAK4E,SAAWhG,GAIrCoB,KAAKa,OAAOgE,WAAWjG,KACvBoB,KAAKe,QAAQ8D,WAAWjG,GACxBoB,KAAKyE,iDAKbpG,OAAAC,eAAWsmC,EAAArlC,UAAA,cAAX,SAAkBX,GACVoB,KAAKe,QAAQ4D,SAAS3E,KAAK4E,SAAWhG,GAItCoB,KAAKe,QAAQ8D,WAAWjG,KACxBoB,KAAKa,OAAOgE,WAAWjG,GACvBoB,KAAKyE,iDAKbpG,OAAAC,eAAWsmC,EAAArlC,UAAA,YAAX,WACI,OAAOS,KAAK+E,WAGhB,SAAgBnG,GACZoB,KAAK+E,MAAQnG,mCAcPgmC,EAAArlC,UAAA+E,aAAV,WACI,MAAO,eAGHsgC,EAAArlC,UAAAkmC,mBAAR,WACI,IAAIlR,EAA6E,GAApE/rB,KAAKqC,IAAI7K,KAAKI,gBAAgB2E,MAAO/E,KAAKI,gBAAgB4E,QAGnE0gC,EAD4C,GAA3BnR,EADS,GAATA,GAEa/rB,KAAKmxB,KAAK,GACxCn1B,EAAS+vB,EAAsB,GAAbmR,EAEtB1lC,KAAKglC,YAAchlC,KAAKI,gBAAgB0F,KAAOtB,EAC/CxE,KAAKilC,WAAajlC,KAAKI,gBAAgB2F,IAAMvB,EAC7CxE,KAAKklC,YAAcQ,GAGfd,EAAArlC,UAAAomC,oBAAR,SAA4BC,EAAkB9/B,EAAcC,EAAahB,EAAeC,EAAgBiE,GACpG,IAAI48B,EAAM58B,EAAQ68B,qBAAqBhgC,EAAMC,EAAKhB,EAAQe,EAAMC,GAChE8/B,EAAIE,aAAa,EAAG,QACpBF,EAAIE,aAAa,EAAG,OAASH,EAAW,gBAExC38B,EAAQY,UAAYg8B,EACpB58B,EAAQuK,SAAS1N,EAAMC,EAAKhB,EAAOC,GAEnC,IAAIghC,EAAM/8B,EAAQ68B,qBAAqBhgC,EAAMC,EAAKD,EAAMd,EAASe,GACjEigC,EAAID,aAAa,EAAG,iBACpBC,EAAID,aAAa,EAAG,QAEpB98B,EAAQY,UAAYm8B,EACpB/8B,EAAQuK,SAAS1N,EAAMC,EAAKhB,EAAOC,IAG/B4/B,EAAArlC,UAAA0mC,YAAR,SAAoB7lB,EAAiBC,EAAiBkU,EAAgBtrB,GAClEA,EAAQ0B,YACR1B,EAAQsG,IAAI6Q,EAASC,EAASkU,EAAS,EAAG,EAAG,EAAI/rB,KAAKgH,IAAI,GAC1DvG,EAAQkP,UAAY,EACpBlP,EAAQmP,YAAc,UACtBnP,EAAQqrB,SACRrrB,EAAQ0B,YACR1B,EAAQsG,IAAI6Q,EAASC,EAASkU,EAAQ,EAAG,EAAI/rB,KAAKgH,IAAI,GACtDvG,EAAQkP,UAAY,EACpBlP,EAAQmP,YAAc,UACtBnP,EAAQqrB,UAGJsQ,EAAArlC,UAAA2mC,wBAAR,SAAgC3R,EAAgBQ,GAC5C,IAAIoR,EAAS73B,SAASC,cAAc,UACpC43B,EAAOphC,MAAiB,EAATwvB,EACf4R,EAAOnhC,OAAkB,EAATuvB,EAUhB,IATA,IAAItrB,EAAoCk9B,EAAOhsB,WAAW,MACtDihB,EAAQnyB,EAAQm9B,aAAa,EAAG,EAAY,EAAT7R,EAAqB,EAATA,GAC/C8R,EAAOjL,EAAMiL,KAEb5V,EAAQzwB,KAAK6kC,UACbyB,EAAY/R,EAASA,EACrBgS,EAAchS,EAASQ,EACvByR,EAAYD,EAAcA,EAErBngC,GAAKmuB,EAAQnuB,EAAImuB,EAAQnuB,IAC9B,IAAK,IAAIC,GAAKkuB,EAAQluB,EAAIkuB,EAAQluB,IAAK,CAEnC,IAAIogC,EAASrgC,EAAIA,EAAIC,EAAIA,EAEzB,KAAIogC,EAASH,GAAaG,EAASD,GAAnC,CAIA,IAAIE,EAAOl+B,KAAKmxB,KAAK8M,GACjBE,EAAMn+B,KAAKo+B,MAAMvgC,EAAGD,GAExBpG,KAAK6mC,UAAgB,IAANF,EAAYn+B,KAAKgH,GAAK,IAAKk3B,EAAOnS,EAAQ,EAAG9D,GAE5D,IAAI5oB,EAAuD,GAA7CzB,EAAImuB,EAA0B,GAAdluB,EAAIkuB,GAAcA,GAEhD8R,EAAKx+B,GAAmB,IAAV4oB,EAAMhyB,EACpB4nC,EAAKx+B,EAAQ,GAAe,IAAV4oB,EAAM+U,EACxBa,EAAKx+B,EAAQ,GAAe,IAAV4oB,EAAMqI,EACxB,IAGIgO,EAAc,GAOdA,EADAvS,EAHc,GAFH,GAOJA,EAJO,IAFH,KASG,KAAyBA,EARzB,IAQiD,IAVpD,GAaf,IAAIwS,GAAcL,EAAOH,IAAgBhS,EAASgS,GAG9CF,EAAKx+B,EAAQ,GADbk/B,EAAaD,EACYC,EAAaD,EAApB,IACXC,EAAa,EAAID,EACN,KAAO,GAAQC,GAAc,EAAID,IAAgBA,GAEjD,KAQ9B,OAFA79B,EAAQ+9B,aAAa5L,EAAO,EAAG,GAExB+K,GAGHvB,EAAArlC,UAAAgmC,UAAR,SAAkB9U,EAAevqB,GAC7B,IAAIzH,EAAIgyB,EAAMhyB,EACV+mC,EAAI/U,EAAM+U,EACV1M,EAAIrI,EAAMqI,EAEV/tB,EAAMvC,KAAKuC,IAAItM,EAAG+mC,EAAG1M,GACrBjuB,EAAMrC,KAAKqC,IAAIpM,EAAG+mC,EAAG1M,GACrBmO,EAAI,EACJvnC,EAAI,EACJwnC,EAAIn8B,EAEJo8B,EAAKp8B,EAAMF,EAEH,IAARE,IACArL,EAAIynC,EAAKp8B,GAGTA,GAAOF,IACHE,GAAOtM,GACPwoC,GAAKzB,EAAI1M,GAAKqO,EACV3B,EAAI1M,IACJmO,GAAK,IAEFl8B,GAAOy6B,EACdyB,GAAKnO,EAAIr6B,GAAK0oC,EAAK,EACZp8B,GAAO+tB,IACdmO,GAAKxoC,EAAI+mC,GAAK2B,EAAK,GAEvBF,GAAK,IAGT/gC,EAAOzH,EAAIwoC,EACX/gC,EAAOs/B,EAAI9lC,EACXwG,EAAO4yB,EAAIoO,GAGPtC,EAAArlC,UAAAsnC,UAAR,SAAkBO,EAAaC,EAAoBzoC,EAAesH,GAC9D,IAAIohC,EAAS1oC,EAAQyoC,EACjBJ,EAAIG,EAAM,GACVhhC,EAAIkhC,GAAU,EAAI9+B,KAAKC,IAAKw+B,EAAI,EAAK,IACrCxoC,EAAI,EACJ+mC,EAAI,EACJ1M,EAAI,EAEJmO,GAAK,GAAKA,GAAK,GACfxoC,EAAI6oC,EACJ9B,EAAIp/B,GACG6gC,GAAK,GAAKA,GAAK,GACtBxoC,EAAI2H,EACJo/B,EAAI8B,GACGL,GAAK,GAAKA,GAAK,GACtBzB,EAAI8B,EACJxO,EAAI1yB,GACG6gC,GAAK,GAAKA,GAAK,GACtBzB,EAAIp/B,EACJ0yB,EAAIwO,GACGL,GAAK,GAAKA,GAAK,GACtBxoC,EAAI2H,EACJ0yB,EAAIwO,GACGL,GAAK,GAAKA,GAAK,IACtBxoC,EAAI6oC,EACJxO,EAAI1yB,GAGR,IAAIrI,EAAIa,EAAQ0oC,EAChBphC,EAAOqhC,IAAK9oC,EAAIV,EAAKynC,EAAIznC,EAAK+6B,EAAI/6B,IAI/B6mC,EAAArlC,UAAAgM,MAAP,SAAavB,EAAwBf,GAIjC,GAHAA,EAAQwK,OAERzT,KAAK2J,aAAaV,GACdjJ,KAAK+J,iBAAiBC,EAAef,GAAU,CAE/C,IAAIsrB,EAA6E,GAApE/rB,KAAKqC,IAAI7K,KAAKI,gBAAgB2E,MAAO/E,KAAKI,gBAAgB4E,QACnEwiC,EAA0B,GAATjT,EACjBzuB,EAAO9F,KAAKI,gBAAgB0F,KAC5BC,EAAM/F,KAAKI,gBAAgB2F,IAE1B/F,KAAKynC,mBAAqBznC,KAAKynC,kBAAkB1iC,OAAkB,EAATwvB,IAC3Dv0B,KAAKynC,kBAAoBznC,KAAKkmC,wBAAwB3R,EAAQiT,IAGlExnC,KAAKylC,sBAEDzlC,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQvF,YAAc1D,KAAK0D,YAC3BuF,EAAQxF,WAAazD,KAAKyD,WAC1BwF,EAAQ1F,cAAgBvD,KAAKuD,cAC7B0F,EAAQzF,cAAgBxD,KAAKwD,cAE7ByF,EAAQuK,SAASxT,KAAKglC,YAAahlC,KAAKilC,WAAYjlC,KAAKklC,YAAallC,KAAKklC,cAG/Ej8B,EAAQ8W,UAAU/f,KAAKynC,kBAAmB3hC,EAAMC,IAE5C/F,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQxF,WAAa,EACrBwF,EAAQ1F,cAAgB,EACxB0F,EAAQzF,cAAgB,GAG5BxD,KAAK2lC,oBAAoB3lC,KAAKmlC,GAC1BnlC,KAAKglC,YACLhlC,KAAKilC,WACLjlC,KAAKklC,YACLllC,KAAKklC,YACLj8B,GAEJ,IAAIy+B,EAAK1nC,KAAKglC,YAAchlC,KAAKklC,YAAcllC,KAAKolC,GAChDuC,EAAK3nC,KAAKilC,WAAajlC,KAAKklC,aAAe,EAAIllC,KAAKqlC,IAExDrlC,KAAKimC,YAAYyB,EAAIC,EAAa,IAATpT,EAActrB,GAEvC,IAAIy9B,EAAOnS,EAA0B,GAAjBiT,EACpBE,EAAK5hC,EAAOyuB,EAAS/rB,KAAK+qB,KAAKvzB,KAAKmlC,GAAK,KAAO38B,KAAKgH,GAAK,KAAOk3B,EACjEiB,EAAK5hC,EAAMwuB,EAAS/rB,KAAK8qB,KAAKtzB,KAAKmlC,GAAK,KAAO38B,KAAKgH,GAAK,KAAOk3B,EAChE1mC,KAAKimC,YAAYyB,EAAIC,EAAqB,IAAjBH,EAAsBv+B,GAGnDA,EAAQ8K,WAMJ6wB,EAAArlC,UAAAo+B,wBAAR,SAAgCv3B,EAAWC,GACvC,GAAIrG,KAAK+kC,uBAAwB,CAC7B,IAAIxQ,EAA6E,GAApE/rB,KAAKqC,IAAI7K,KAAKI,gBAAgB2E,MAAO/E,KAAKI,gBAAgB4E,QACnEob,EAAUmU,EAASv0B,KAAKI,gBAAgB0F,KACxCua,EAAUkU,EAASv0B,KAAKI,gBAAgB2F,IAC5C/F,KAAKmlC,GAA4C,IAAvC38B,KAAKo+B,MAAMvgC,EAAIga,EAASja,EAAIga,GAAiB5X,KAAKgH,GAAK,SAE5DxP,KAAK8kC,0BACV9kC,KAAKylC,qBACLzlC,KAAKolC,IAAMh/B,EAAIpG,KAAKglC,aAAehlC,KAAKklC,YACxCllC,KAAKqlC,GAAK,GAAKh/B,EAAIrG,KAAKilC,YAAcjlC,KAAKklC,YAC3CllC,KAAKolC,GAAK58B,KAAKqC,IAAI7K,KAAKolC,GAAI,GAC5BplC,KAAKolC,GAAK58B,KAAKuC,IAAI/K,KAAKolC,GAAI,MAC5BplC,KAAKqlC,GAAK78B,KAAKqC,IAAI7K,KAAKqlC,GAAI,GAC5BrlC,KAAKqlC,GAAK78B,KAAKuC,IAAI/K,KAAKqlC,GAAI,OAGhCrlC,KAAK6mC,UAAU7mC,KAAKmlC,GAAInlC,KAAKolC,GAAIplC,KAAKqlC,GAAIrlC,KAAK6kC,WAE/C7kC,KAAKpB,MAAQoB,KAAK6kC,WAGdD,EAAArlC,UAAAqoC,iBAAR,SAAyBz7B,GACrBnM,KAAKylC,qBAEL,IAAI3/B,EAAO9F,KAAKglC,YACZj/B,EAAM/F,KAAKilC,WACX1Y,EAAOvsB,KAAKklC,YAEhB,OAAI/4B,EAAY/F,GAAKN,GAAQqG,EAAY/F,GAAKN,EAAOymB,GACjDpgB,EAAY9F,GAAKN,GAAOoG,EAAY9F,GAAKN,EAAMwmB,GAO/CqY,EAAArlC,UAAAsoC,gBAAR,SAAwB17B,GACpB,IAAIooB,EAA6E,GAApE/rB,KAAKqC,IAAI7K,KAAKI,gBAAgB2E,MAAO/E,KAAKI,gBAAgB4E,QACnEob,EAAUmU,EAASv0B,KAAKI,gBAAgB0F,KACxCua,EAAUkU,EAASv0B,KAAKI,gBAAgB2F,IAExCwgC,EAAchS,EADY,GAATA,EAEjBuT,EAAWvT,EAASA,EACpBwT,EAAgBxB,EAAcA,EAE9ByB,EAAK77B,EAAY/F,EAAIga,EACrB6nB,EAAK97B,EAAY9F,EAAIga,EAErBomB,EAASuB,EAAKA,EAAKC,EAAKA,EAE5B,OAAIxB,GAAUqB,GAAYrB,GAAUsB,GAOjCnD,EAAArlC,UAAAgN,eAAP,SAAsBL,EAAiBC,EAAsBN,EAAmBC,GAC5E,QAAKmF,EAAA1R,UAAMgN,eAAczO,KAAAkC,KAACkM,EAAQC,EAAaN,EAAWC,KAI1D9L,KAAK88B,gBAAiB,EAEtB98B,KAAK8kC,yBAA0B,EAC/B9kC,KAAK+kC,wBAAyB,EAE1B/kC,KAAK4nC,iBAAiBz7B,GACtBnM,KAAK8kC,yBAA0B,EACxB9kC,KAAK6nC,gBAAgB17B,KAC5BnM,KAAK+kC,wBAAyB,GAGlC/kC,KAAK29B,wBAAwBxxB,EAAY/F,EAAG+F,EAAY9F,GACxDrG,KAAK4E,MAAMsiB,kBAAkBrb,GAAa7L,MAEnC,IAGJ4kC,EAAArlC,UAAA0M,eAAP,SAAsBC,EAAiBC,GAC/BnM,KAAK88B,gBACL98B,KAAK29B,wBAAwBxxB,EAAY/F,EAAG+F,EAAY9F,GAG5D4K,EAAA1R,UAAM0M,eAAcnO,KAAAkC,KAACkM,EAAQC,IAG1By4B,EAAArlC,UAAAkN,aAAP,SAAoBP,EAAiBC,EAAsBN,EAAmBC,EAAqBY,GAC/F1M,KAAK88B,gBAAiB,SAEf98B,KAAK4E,MAAMsiB,kBAAkBrb,GACpCoF,EAAA1R,UAAMkN,aAAY3O,KAAAkC,KAACkM,EAAQC,EAAaN,EAAWC,EAAaY,IAExEk4B,EAtaA,CAAiCjyB,EAAA5S,SAApB9C,EAAA2nC,oaCLb,IAAAjyB,EAAAlV,EAAA,GAEAmC,EAAAnC,EAAA,GAKAyqC,EAAA,SAAAj3B,GA2EI,SAAAi3B,EAAmBhqC,GAAnB,IAAAgH,EACI+L,EAAAnT,KAAAkC,KAAM9B,IAAK8B,YADIkF,EAAAhH,OA1EXgH,EAAAg7B,YAAa,EACbh7B,EAAA8N,YAAc,QACd9N,EAAAi7B,gBAAkB,GAClBj7B,EAAAypB,WAAa,EAmBdzpB,EAAAm7B,6BAA+B,IAAIzgC,EAAAkE,WAsDtCoB,EAAK7B,kBAAmB,IA4DhC,OAzI8BgO,EAAA62B,EAAAj3B,GAO1B5S,OAAAC,eAAW4pC,EAAA3oC,UAAA,iBAAX,WACI,OAAOS,KAAK2uB,gBAGhB,SAAqB/vB,GACboB,KAAK2uB,aAAe/vB,IAIxBoB,KAAK2uB,WAAa/vB,EAClBoB,KAAKyE,iDASTpG,OAAAC,eAAW4pC,EAAA3oC,UAAA,sBAAX,WACI,OAAOS,KAAKmgC,qBAGhB,SAA0BvhC,GACtBA,EAAQ4J,KAAKuC,IAAIvC,KAAKqC,IAAI,EAAGjM,GAAQ,GAEjCoB,KAAKmgC,kBAAoBvhC,IAI7BoB,KAAKmgC,gBAAkBvhC,EACvBoB,KAAKyE,iDAITpG,OAAAC,eAAW4pC,EAAA3oC,UAAA,kBAAX,WACI,OAAOS,KAAKgT,iBAGhB,SAAsBpU,GACdoB,KAAKgT,cAAgBpU,IAIzBoB,KAAKgT,YAAcpU,EACnBoB,KAAKyE,iDAITpG,OAAAC,eAAW4pC,EAAA3oC,UAAA,iBAAX,WACI,OAAOS,KAAKkgC,gBAGhB,SAAqBthC,GACboB,KAAKkgC,aAAethC,IAIxBoB,KAAKkgC,WAAathC,EAClBoB,KAAKyE,eAELzE,KAAKqgC,6BAA6B71B,gBAAgB5L,qCAY5CspC,EAAA3oC,UAAA+E,aAAV,WACI,MAAO,YAIJ4jC,EAAA3oC,UAAAgM,MAAP,SAAavB,EAAwBf,GAIjC,GAHAA,EAAQwK,OAERzT,KAAK2J,aAAaV,GACdjJ,KAAK+J,iBAAiBC,EAAef,GAAU,CAC/C,IAAIw3B,EAAczgC,KAAKI,gBAAgB2E,MAAQ/E,KAAK2uB,WAChD+R,EAAe1gC,KAAKI,gBAAgB4E,OAAShF,KAAK2uB,WAkBtD,IAhBI3uB,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQvF,YAAc1D,KAAK0D,YAC3BuF,EAAQxF,WAAazD,KAAKyD,WAC1BwF,EAAQ1F,cAAgBvD,KAAKuD,cAC7B0F,EAAQzF,cAAgBxD,KAAKwD,eAGjCyF,EAAQY,UAAY7J,KAAKgT,YACzB/J,EAAQuK,SAASxT,KAAKI,gBAAgB0F,KAAO9F,KAAK2uB,WAAa,EAAG3uB,KAAKI,gBAAgB2F,IAAM/F,KAAK2uB,WAAa,EAAG8R,EAAaC,IAE3H1gC,KAAKyD,YAAczD,KAAKuD,eAAiBvD,KAAKwD,iBAC9CyF,EAAQxF,WAAa,EACrBwF,EAAQ1F,cAAgB,EACxB0F,EAAQzF,cAAgB,GAGxBxD,KAAKkgC,WAAY,CACjBj3B,EAAQY,UAAY7J,KAAKywB,MACzB,IAAIkQ,EAAcF,EAAczgC,KAAKmgC,gBACjCS,EAAcF,EAAe1gC,KAAKmgC,gBAEtCl3B,EAAQuK,SAASxT,KAAKI,gBAAgB0F,KAAO9F,KAAK2uB,WAAa,GAAK8R,EAAcE,GAAe,EAAG3gC,KAAKI,gBAAgB2F,IAAM/F,KAAK2uB,WAAa,GAAK+R,EAAeE,GAAe,EAAGD,EAAaC,GAGxM33B,EAAQmP,YAAcpY,KAAKywB,MAC3BxnB,EAAQkP,UAAYnY,KAAK2uB,WAEzB1lB,EAAQsoB,WAAWvxB,KAAKI,gBAAgB0F,KAAO9F,KAAK2uB,WAAa,EAAG3uB,KAAKI,gBAAgB2F,IAAM/F,KAAK2uB,WAAa,EAAG8R,EAAaC,GAErIz3B,EAAQ8K,WAMLm0B,EAAA3oC,UAAAgN,eAAP,SAAsBL,EAAiBC,EAAsBN,EAAmBC,GAC5E,QAAKmF,EAAA1R,UAAMgN,eAAczO,KAAAkC,KAACkM,EAAQC,EAAaN,EAAWC,KAI1D9L,KAAKwgC,WAAaxgC,KAAKwgC,WAEhB,IAEf0H,EAzIA,CAA8Bv1B,EAAA5S,SAAjB9C,EAAAirC,wJCPblR,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,IACAu5B,EAAAv5B,EAAA,IACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,IACAu5B,EAAAv5B,EAAA,IACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KAEAu5B,EAAAv5B,EAAA,kJCnBAu5B,EAAAv5B,EAAA,KAEAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,IACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA,iJCPAu5B,EAAAv5B,EAAA,KACAu5B,EAAAv5B,EAAA","file":"babylon.gui.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"babylonjs\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"babylonjs-gui\", [\"babylonjs\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"babylonjs-gui\"] = factory(require(\"babylonjs\"));\n\telse\n\t\troot[\"BABYLON\"] = root[\"BABYLON\"] || {}, root[\"BABYLON\"][\"GUI\"] = factory(root[\"BABYLON\"]);\n})(window, function(__WEBPACK_EXTERNAL_MODULE__0__) {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 49);\n","module.exports = __WEBPACK_EXTERNAL_MODULE__0__;","import { Container } from \"./container\";\r\nimport { AdvancedDynamicTexture } from \"../advancedDynamicTexture\";\r\nimport { ValueAndUnit } from \"../valueAndUnit\";\r\nimport { Nullable, Observer, Vector2, AbstractMesh, Observable, Vector3, Scene, Tools, Matrix, PointerEventTypes } from \"babylonjs\";\r\nimport { Measure } from \"../measure\";\r\nimport { Style } from \"../style\";\r\nimport { Matrix2D, Vector2WithInfo } from \"../math2D\";\r\n\r\n/**\r\n * Root class used for all 2D controls\r\n * @see http://doc.babylonjs.com/how_to/gui#controls\r\n */\r\nexport class Control {\r\n private _alpha = 1;\r\n private _alphaSet = false;\r\n private _zIndex = 0;\r\n /** @hidden */\r\n public _root: Nullable;\r\n /** @hidden */\r\n public _host: AdvancedDynamicTexture;\r\n /** Gets or sets the control parent */\r\n public parent: Nullable;\r\n /** @hidden */\r\n public _currentMeasure = Measure.Empty();\r\n private _fontFamily = \"Arial\";\r\n private _fontStyle = \"\";\r\n private _fontWeight = \"\";\r\n private _fontSize = new ValueAndUnit(18, ValueAndUnit.UNITMODE_PIXEL, false);\r\n private _font: string;\r\n /** @hidden */\r\n public _width = new ValueAndUnit(1, ValueAndUnit.UNITMODE_PERCENTAGE, false);\r\n /** @hidden */\r\n public _height = new ValueAndUnit(1, ValueAndUnit.UNITMODE_PERCENTAGE, false);\r\n /** @hidden */\r\n protected _fontOffset: { ascent: number, height: number, descent: number };\r\n private _color = \"\";\r\n private _style: Nullable {{#if fillScreen}} {{/if}} "},function(e,t){e.exports=" "},function(e,t){e.exports="Error loading the model"},function(e,t){e.exports=" {{#unless disable}} {{/unless}} "},function(e,t){e.exports="HELP"},function(e,t){e.exports=" "},function(e,t){e.exports=' {{#if (or (not animations) hideAnimations)}} {{#if hideLogo}} {{else}} {{/if}} {{/if}} {{#if disableOnFullscreen}} {{/if}} '},function(e,t){e.exports="
{{closeText}}
"},function(e,t){e.exports="SHARE"},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(2),n=i(2),o=i(2);t.defaultConfiguration={version:"3.2.0-alpha4",templates:{main:{html:r.defaultTemplate,params:{babylonFont:n.babylonFont,noEscape:!0}},fillContainer:{html:r.fillContainer,params:{disable:!1}},loadingScreen:{html:r.loadingScreen,params:{backgroundColor:"#000000",loadingImage:o.loading}},viewer:{html:r.defaultViewer,params:{enableDragAndDrop:!1}},navBar:{html:r.navbar,params:{speedList:{"0.5x":"0.5","1.0x":"1.0","1.5x":"1.5","2.0x":"2.0"},logoImage:o.babylonLogo,logoText:"BabylonJS",logoLink:"https://babylonjs.com",hideHelp:!0,hideHd:!0,hideVr:!0,hidePrint:!0,disableOnFullscreen:!1,text:{hdButton:"Toggle HD",fullscreenButton:"Toggle Fullscreen",helpButton:"Help",vrButton:"Toggle VR",printButton:"3D Print Object"}},events:{pointerdown:{".navbar-control":!0,".help-button":!0},input:{".progress-wrapper":!0},pointerup:{".progress-wrapper":!0}}},overlay:{html:r.overlay,params:{closeImage:o.close,closeText:"Close"}},help:{html:r.help},share:{html:r.share},error:{html:r.error}},camera:{behaviors:{autoRotate:{type:0},framing:{type:2,zoomOnBoundingInfo:!0,zoomStopsAnimation:!1},bouncing:{type:1}}},skybox:{},ground:{receiveShadows:!0},engine:{antialiasing:!0},scene:{}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(0);t.extendedConfiguration={version:"3.2.0",extends:"default",camera:{exposure:3.034578,fov:.7853981633974483,contrast:1.6,toneMappingEnabled:!0,upperBetaLimit:1.3962634015954636+Math.PI/2,lowerBetaLimit:Math.PI/2-1.4835298641951802,behaviors:{framing:{type:2,mode:0,positionScale:.5,defaultElevation:.2617993877991494,elevationReturnWaitTime:3e3,elevationReturnTime:2e3,framingTime:500,zoomStopsAnimation:!1,radiusScale:.866},autoRotate:{type:0,idleRotationWaitTime:4e3,idleRotationSpeed:.17453292519943295,idleRotationSpinupTime:2500,zoomStopsAnimation:!1},bouncing:{type:1,lowerRadiusTransitionRange:.05,upperRadiusTransitionRange:-.2}},upperRadiusLimit:5,lowerRadiusLimit:.5,frameOnModelLoad:!0,framingElevation:.2617993877991494,framingRotation:1.5707963267948966,radius:2,alpha:1.5708,beta:.5*Math.PI-.2618,wheelPrecision:300,minZ:.1,maxZ:50,fovMode:0,pinchPrecision:1500,panningSensibility:3e3},lights:{light0:{type:0,frustumEdgeFalloff:0,intensity:7,intensityMode:0,radius:.6,range:4.4,spotAngle:60,diffuse:{r:1,g:1,b:1},position:{x:-2,y:2.5,z:2},target:{x:0,y:0,z:0},enabled:!0,shadowEnabled:!0,shadowBufferSize:512,shadowMinZ:1,shadowMaxZ:10,shadowFieldOfView:60,shadowFrustumSize:2,shadowConfig:{useBlurCloseExponentialShadowMap:!0,useKernelBlur:!0,blurScale:1,bias:.001,depthScale:450,frustumEdgeFalloff:0}},light1:{type:0,frustumEdgeFalloff:0,intensity:7,intensityMode:0,radius:.4,range:5.8,spotAngle:57,diffuse:{r:1,g:1,b:1},position:{x:4,y:3,z:-.5},target:{x:0,y:0,z:0},enabled:!0,shadowEnabled:!1,shadowBufferSize:512,shadowMinZ:.2,shadowMaxZ:10,shadowFieldOfView:28,shadowFrustumSize:2},light2:{type:0,frustumEdgeFalloff:0,intensity:1,intensityMode:0,radius:.5,range:6,spotAngle:42.85,diffuse:{r:.8,g:.8,b:.8},position:{x:-1,y:3,z:-3},target:{x:0,y:0,z:0},enabled:!0,shadowEnabled:!1,shadowBufferSize:512,shadowMinZ:.2,shadowMaxZ:10,shadowFieldOfView:45,shadowFrustumSize:2}},ground:{shadowLevel:.9,texture:"Ground_2.0-1024.png",material:{primaryColorHighlightLevel:.035,primaryColorShadowLevel:0,enableNoise:!0,useRGBColor:!1,maxSimultaneousLights:1,diffuseTexture:{gammaSpace:!0}},opacity:1,mirror:!1,receiveShadows:!0,size:5},skybox:{scale:11,cubeTexture:{url:"Skybox_2.0-256.dds"},material:{primaryColorHighlightLevel:.03,primaryColorShadowLevel:.03,enableNoise:!0,useRGBColor:!1,reflectionTexture:{gammaSpace:!0}}},engine:{renderInBackground:!0},scene:{flags:{shadowsEnabled:!0,particlesEnabled:!1,collisionsEnabled:!1,lightsEnabled:!0,texturesEnabled:!0,lensFlaresEnabled:!1,proceduralTexturesEnabled:!1,renderTargetsEnabled:!0,spritesEnabled:!1,skeletonsEnabled:!0,audioEnabled:!1},defaultMaterial:{materialType:"pbr",reflectivityColor:{r:.1,g:.1,b:.1},microSurface:.6},clearColor:{r:.9,g:.9,b:.9,a:1},imageProcessingConfiguration:{vignetteCentreX:0,vignetteCentreY:0,vignetteColor:{r:.086,g:.184,b:.259,a:1},vignetteWeight:.855,vignetteStretch:.5,vignetteBlendMode:0,vignetteCameraFov:.7853981633974483,isEnabled:!0,colorCurves:{shadowsHue:0,shadowsDensity:0,shadowsSaturation:0,shadowsExposure:0,midtonesHue:0,midtonesDensity:0,midtonesExposure:0,midtonesSaturation:0,highlightsHue:0,highlightsDensity:0,highlightsExposure:0,highlightsSaturation:0}},assetsRootURL:"https://viewer.babylonjs.com/assets/environment/"},loaderPlugins:{extendedMaterial:!0,applyMaterialConfig:!0,msftLod:!0,telemetry:!0},model:{rotationOffsetAxis:{x:0,y:-1,z:0},rotationOffsetAngle:r.Tools.ToRadians(210),material:{directEnabled:!0,directIntensity:.884,emissiveIntensity:1.04,environmentIntensity:.6},entryAnimation:{scaling:{x:0,y:0,z:0},time:.5,easingFunction:4,easingMode:1},exitAnimation:{scaling:{x:0,y:0,z:0},time:.5,easingFunction:4,easingMode:1},normalize:!0,castShadow:!0,receiveShadows:!0},environmentMap:{texture:"EnvMap_3.0-256.env",rotationY:3,tintLevel:.4,mainColor:{r:.8823529411764706,g:.8823529411764706,b:.8823529411764706}},lab:{defaultRenderingPipelines:{bloomEnabled:!0,bloomThreshold:1,fxaaEnabled:!0,bloomWeight:.05}}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shadowDirectionalLightConfiguration={model:{receiveShadows:!0,castShadow:!0},ground:{receiveShadows:!0},lights:{shadowDirectionalLight:{type:1,shadowEnabled:!0,target:{x:0,y:0,z:.5},position:{x:1.49,y:2.39,z:-1.33},diffuse:{r:.867,g:.816,b:.788},intensity:4.887,intensityMode:0,shadowBufferSize:1024,shadowFrustumSize:6,shadowFieldOfView:50.977,shadowMinZ:.1,shadowMaxZ:10,shadowConfig:{blurKernel:32,useBlurCloseExponentialShadowMap:!0}}}},t.shadowSpotlLightConfiguration={model:{receiveShadows:!0,castShadow:!0},ground:{receiveShadows:!0},lights:{shadowSpotLight:{type:2,intensity:2,shadowEnabled:!0,target:{x:0,y:0,z:.5},position:{x:0,y:3.5,z:3.7},angle:1,shadowOrthoScale:.5,shadowBufferSize:1024,shadowMinZ:.1,shadowMaxZ:50,shadowConfig:{frustumEdgeFalloff:.5,blurKernel:32,useBlurExponentialShadowMap:!0}}}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.environmentMapConfiguration={lab:{assetsRootURL:"/assets/environment/",environmentMap:{texture:"EnvMap_2.0-256.env",rotationY:0,tintLevel:.4}}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e){var t=this;this._animationGroup=e,this._state=0,this._playMode=1,this._animationGroup.onAnimationEndObservable.add(function(){t.stop(),t._state=4})}return Object.defineProperty(e.prototype,"name",{get:function(){return this._animationGroup.name},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"speedRatio",{get:function(){return this._animationGroup.speedRatio},set:function(e){this._animationGroup.speedRatio=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"frames",{get:function(){return this._animationGroup.to-this._animationGroup.from},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentFrame",{get:function(){return this._animationGroup.targetedAnimations[0]&&this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]?this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame-this._animationGroup.from:0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"fps",{get:function(){for(var e=0;e0?(t(),n._forceShadowUpdate=!1):n.models.every(function(e){return e.shadowsRenderedAfterLoad?e.state===o.ModelState.COMPLETE&&!e.currentAnimation:(e.shadowsRenderedAfterLoad=!0,!1)})||t()}),n._observablesManager&&n._observablesManager.onSceneInitObservable.notifyObserversWithPromise(n.scene)}),this._observablesManager&&(this._observablesManager.onModelLoadedObservable.add(function(e){for(var t=0,i=n.scene.lights;t0,this._defaultRenderingPipeline.bloomWeight=void 0!==t.bloomWeight&&t.bloomWeight||this._defaultRenderingPipeline.bloomWeight),this._defaultRenderingPipeline.bloomEnabled=i,this._defaultRenderingPipeline.fxaaEnabled=this.fxaaEnabled}}else this._defaultRenderingPipeline&&(this._defaultRenderingPipeline.dispose(),this._defaultRenderingPipeline=null,this.scene.autoClearDepthAndStencil=!0,this.scene.autoClear=!0,this.scene.imageProcessingConfiguration.applyByPostProcess=!1)},Object.defineProperty(e.prototype,"bloomEnabled",{get:function(){return this._bloomEnabled},set:function(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._rebuildPostprocesses(),this._defaultRenderingPipeline&&(this._defaultRenderingPipelineShouldBuild=!1,this._defaultRenderingPipeline.prepare(),this.scene.imageProcessingConfiguration.applyByPostProcess=!0))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"fxaaEnabled",{get:function(){return this._fxaaEnabled},set:function(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._rebuildPostprocesses(),this._defaultRenderingPipeline&&(this._defaultRenderingPipelineShouldBuild=!1,this._defaultRenderingPipeline.prepare(),this.scene.imageProcessingConfiguration.applyByPostProcess=!0))},enumerable:!0,configurable:!0}),e.prototype._configureScene=function(e){if(this.scene){var t=e.clearColor,i=this.scene.clearColor;if(t&&(void 0!==t.r&&(i.r=t.r),void 0!==t.g&&(i.g=t.g),void 0!==t.b&&(i.b=t.b),void 0!==t.a&&(i.a=t.a)),e.assetsRootURL&&(this._assetsRootURL=e.assetsRootURL),e.imageProcessingConfiguration&&s.extendClassWithConfig(this.scene.imageProcessingConfiguration,e.imageProcessingConfiguration),e.animationPropertiesOverride&&s.extendClassWithConfig(this.scene.animationPropertiesOverride,e.animationPropertiesOverride),e.environmentTexture&&(!this.scene.environmentTexture||this.scene.environmentTexture.url!==e.environmentTexture)){this.scene.environmentTexture&&this.scene.environmentTexture.dispose&&this.scene.environmentTexture.dispose();var n=r.CubeTexture.CreateFromPrefilteredData(e.environmentTexture,this.scene);this.scene.environmentTexture=n}!0===e.debug?this.scene.debugLayer.show():!1===e.debug&&this.scene.debugLayer.isVisible()&&this.scene.debugLayer.hide(),e.disableHdr?this._handleHardwareLimitations(!1):this._handleHardwareLimitations(!0),void 0!==e.renderInBackground&&(this._engine.renderEvenInBackground=!!e.renderInBackground);var o=this._engine.getRenderingCanvas();if(o&&(this.camera&&e.disableCameraControl?this.camera.detachControl(o):this.camera&&!1===e.disableCameraControl&&this.camera.attachControl(o)),e.defaultMaterial){var a=e.defaultMaterial;("standard"===a.materialType&&"StandardMaterial"!==this.scene.defaultMaterial.getClassName()||"pbr"===a.materialType&&"PBRMaterial"!==this.scene.defaultMaterial.getClassName())&&(this.scene.defaultMaterial.dispose(),"standard"===a.materialType?this.scene.defaultMaterial=new r.StandardMaterial("defaultMaterial",this.scene):this.scene.defaultMaterial=new r.PBRMaterial("defaultMaterial",this.scene)),s.extendClassWithConfig(this.scene.defaultMaterial,a)}e.flags&&s.extendClassWithConfig(this.scene,e.flags),this.onSceneConfiguredObservable.notifyObservers({sceneManager:this,object:this.scene,newConfiguration:e})}},e.prototype._configureOptimizer=function(e){var t=this;if("boolean"==typeof e)this.sceneOptimizer&&(this.sceneOptimizer.stop(),this.sceneOptimizer.dispose(),delete this.sceneOptimizer),e&&(this.sceneOptimizer=new r.SceneOptimizer(this.scene),this.sceneOptimizer.start());else{var i=new r.SceneOptimizerOptions(e.targetFrameRate,e.trackerDuration);if(e.degradation)switch(e.degradation){case"low":i=r.SceneOptimizerOptions.LowDegradationAllowed(e.targetFrameRate);break;case"moderate":i=r.SceneOptimizerOptions.ModerateDegradationAllowed(e.targetFrameRate);break;case"hight":i=r.SceneOptimizerOptions.HighDegradationAllowed(e.targetFrameRate)}if(this.sceneOptimizer&&(this.sceneOptimizer.stop(),this.sceneOptimizer.dispose()),e.custom){var n=l.getCustomOptimizerByName(e.custom,e.improvementMode);n&&i.addCustomOptimization(function(){return n(t)},function(){return"Babylon Viewer "+e.custom+" custom optimization"})}this.sceneOptimizer=new r.SceneOptimizer(this.scene,i,e.autoGeneratePriorities,e.improvementMode),this.sceneOptimizer.start()}this.onSceneOptimizerConfiguredObservable.notifyObservers({sceneManager:this,object:this.sceneOptimizer,newConfiguration:e})},e.prototype._configureVR=function(e){var t=this;if(e.disabled)this._vrHelper&&(this._vrHelper.isInVRMode&&this._vrHelper.exitVR(),this._vrHelper.dispose(),this._vrHelper=void 0);else{var i,n=c.deepmerge({useCustomVRButton:!0,createDeviceOrientationCamera:!1,trackPosition:!0},e.vrOptions||{});if(this._vrHelper=this.scene.createDefaultVRExperience(n),e.disableInteractions||this._vrHelper.enableInteractions(),!e.disableTeleportation){var o=e.overrideFloorMeshName||"BackgroundPlane";this._vrHelper.enableTeleportation({floorMeshName:o})}if(e.rotateUsingControllers)this._vrHelper.onControllerMeshLoadedObservable.add(function(e){e.onTriggerStateChangedObservable.add(function(n){e.mesh&&e.mesh.rotationQuaternion&&(n.pressed?i||(t.models[0].rootMesh.rotationQuaternion=t.models[0].rootMesh.rotationQuaternion||new r.Quaternion,i=e.mesh.rotationQuaternion.conjugate().multiply(t.models[0].rootMesh.rotationQuaternion)):i=null)}),t.scene.registerBeforeRender(function(){t.models[0]&&(i&&e.mesh&&e.mesh.rotationQuaternion?t.models[0].rootMesh.rotationQuaternion.copyFrom(e.mesh.rotationQuaternion).multiplyInPlace(i):t.models[0].rootMesh.rotationQuaternion=null)})});this.onVRConfiguredObservable.notifyObservers({sceneManager:this,object:this._vrHelper,newConfiguration:e})}},e.prototype._configureEnvironmentMap=function(e){if(e.texture&&(this.scene.environmentTexture=new BABYLON.CubeTexture(this._getAssetUrl(e.texture),this.scene)),this.scene.environmentTexture){var t=r.Quaternion.RotationAxis(r.Axis.Y,e.rotationY||0);r.Matrix.FromQuaternionToRef(t,this.scene.environmentTexture.getReflectionTextureMatrix())}if(e.mainColor){this._configurationContainer.mainColor=this.mainColor||r.Color3.White();var i=e.mainColor;void 0!==i.r&&(this.mainColor.r=i.r),void 0!==i.g&&(this.mainColor.g=i.g),void 0!==i.b&&(this.mainColor.b=i.b),this.reflectionColor.copyFrom(this.mainColor);var o=n.getConfigurationKey("environmentMap.tintLevel",this._globalConfiguration)||0;this.reflectionColor.toLinearSpaceToRef(this.reflectionColor),this.reflectionColor.scaleToRef(1/this.scene.imageProcessingConfiguration.exposure,this.reflectionColor);var s=r.Color3.Lerp(this._white,this.reflectionColor,o);this.reflectionColor.copyFrom(s),this.environmentHelper&&(this.environmentHelper.groundMaterial&&(this.environmentHelper.groundMaterial._perceptualColor=this.mainColor),this.environmentHelper.skyboxMaterial&&(this.environmentHelper.skyboxMaterial._perceptualColor=this.mainColor))}},e.prototype._configureCamera=function(e){var t=this;if(void 0===e&&(e={}),!this.scene.activeCamera){var i=!0;this._globalConfiguration.scene&&this._globalConfiguration.scene.disableCameraControl&&(i=!1),this.scene.createDefaultCamera(!0,!0,i),this.camera=this.scene.activeCamera,this.camera.setTarget(r.Vector3.Zero())}if(this.camera||(this.camera=this.scene.activeCamera),e.position){var o=this.camera.position.clone();s.extendClassWithConfig(o,e.position),this.camera.setPosition(o)}if(e.target){var a=this.camera.target.clone();s.extendClassWithConfig(a,e.target),this.camera.setTarget(a)}if(e.rotation&&(this.camera.rotationQuaternion=new r.Quaternion(e.rotation.x||0,e.rotation.y||0,e.rotation.z||0,e.rotation.w||0)),e.behaviors)for(var l in e.behaviors)void 0!==e.behaviors[l]&&this._setCameraBehavior(l,e.behaviors[l]);var c=this.scene.getWorldExtends(function(e){return!t.environmentHelper||e!==t.environmentHelper.ground&&e!==t.environmentHelper.rootMesh&&e!==t.environmentHelper.skybox}),u=c.max.subtract(c.min).length();isFinite(u)&&(this.camera.upperRadiusLimit=4*u),this.scene.imageProcessingConfiguration&&(this.scene.imageProcessingConfiguration.colorCurvesEnabled=!0,this.scene.imageProcessingConfiguration.vignetteEnabled=!0,this.scene.imageProcessingConfiguration.toneMappingEnabled=!!n.getConfigurationKey("camera.toneMappingEnabled",this._globalConfiguration)),s.extendClassWithConfig(this.camera,e),this.onCameraConfiguredObservable.notifyObservers({sceneManager:this,object:this.camera,newConfiguration:e})},e.prototype._configureEnvironment=function(e,t){var i=this;if(e||t){var n={createGround:!!t&&this._groundEnabled,createSkybox:!!e,setupImageProcessing:!1};if(t){var o="boolean"==typeof t?{}:t,a=o.size||"object"==typeof e&&e.scale;a&&(n.groundSize=a),n.enableGroundShadow=!0===o||o.receiveShadows,void 0!==o.shadowLevel&&(n.groundShadowLevel=o.shadowLevel),n.enableGroundMirror=!!o.mirror&&this.groundMirrorEnabled,o.texture&&(n.groundTexture=this._getAssetUrl(o.texture)),o.color&&(n.groundColor=new r.Color3(o.color.r,o.color.g,o.color.b)),void 0!==o.opacity&&(n.groundOpacity=o.opacity),o.mirror&&(n.enableGroundMirror=!0,"object"==typeof o.mirror&&(void 0!==o.mirror.amount&&(n.groundMirrorAmount=o.mirror.amount),void 0!==o.mirror.sizeRatio&&(n.groundMirrorSizeRatio=o.mirror.sizeRatio),void 0!==o.mirror.blurKernel&&(n.groundMirrorBlurKernel=o.mirror.blurKernel),void 0!==o.mirror.fresnelWeight&&(n.groundMirrorFresnelWeight=o.mirror.fresnelWeight),void 0!==o.mirror.fallOffDistance&&(n.groundMirrorFallOffDistance=o.mirror.fallOffDistance),void 0!==this._defaultPipelineTextureType&&(n.groundMirrorTextureType=this._defaultPipelineTextureType)))}var l=!1;if(e){var c=!0===e?{}:e;c.material&&c.material.imageProcessingConfiguration&&(n.setupImageProcessing=!1);var u=c.scale;u&&(n.skyboxSize=u),n.sizeAuto=!n.skyboxSize,c.color&&(n.skyboxColor=new r.Color3(c.color.r,c.color.g,c.color.b)),c.cubeTexture&&c.cubeTexture.url&&("string"==typeof c.cubeTexture.url?n.skyboxTexture=this._getAssetUrl(c.cubeTexture.url):l=!0),c.material&&(l=!0)}if(n.setupImageProcessing=!1,this.environmentHelper)this.environmentHelper.rootMesh.getScene()!==this.scene?(this.environmentHelper.dispose(),this.environmentHelper=this.scene.createDefaultEnvironment(n)):(this.environmentHelper.ground&&this.environmentHelper.ground.dispose(),this.environmentHelper.skybox&&this.environmentHelper.skybox.dispose(),this.environmentHelper.updateOptions(n));else this.environmentHelper=this.scene.createDefaultEnvironment(n);this.environmentHelper.rootMesh&&this._globalConfiguration.scene&&void 0!==this._globalConfiguration.scene.environmentRotationY&&(this.environmentHelper.rootMesh.rotation.y=this._globalConfiguration.scene.environmentRotationY);var h="boolean"==typeof t?{}:t;if(this.environmentHelper.groundMaterial&&h&&(this.environmentHelper.groundMaterial._perceptualColor=this.mainColor,h.material&&s.extendClassWithConfig(this.environmentHelper.groundMaterial,h.material),this.environmentHelper.groundMirror)){var d=this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace(),f=Math.pow(2,-this.scene.imageProcessingConfiguration.exposure)*Math.PI;d.scaleToRef(1/f,d),this.environmentHelper.groundMirror.clearColor.r=r.Scalar.Clamp(d.r),this.environmentHelper.groundMirror.clearColor.g=r.Scalar.Clamp(d.g),this.environmentHelper.groundMirror.clearColor.b=r.Scalar.Clamp(d.b),this.environmentHelper.groundMirror.clearColor.a=1,this.groundMirrorEnabled||(this.environmentHelper.groundMaterial.reflectionTexture=null)}var p=this.environmentHelper.skyboxMaterial;p&&(p._perceptualColor=this.mainColor,l&&"object"==typeof e&&e.material&&s.extendClassWithConfig(p,e.material))}else this.environmentHelper&&(this.environmentHelper.dispose(),this.environmentHelper=void 0);this._observablesManager&&this._observablesManager.onModelLoadedObservable.add(function(e){i._updateGroundMirrorRenderList(e)}),this.onEnvironmentConfiguredObservable.notifyObservers({sceneManager:this,object:this.environmentHelper,newConfiguration:{skybox:e,ground:t}})},e.prototype._configureLights=function(e){var t=this;void 0===e&&(e={});var i=Object.keys(e).filter(function(e){return"globalRotation"!==e});if(i.length){var n=this.scene.lights.map(function(e){return e.name}),o=Object.keys(this._globalConfiguration.lights||[]);Object.keys(o).length!==n.length&&n.forEach(function(e){-1===o.indexOf(e)&&t.scene.getLightByName(e).dispose()}),i.forEach(function(i,o){var a,l={type:0};if("object"==typeof e[i]&&(l=e[i]),"number"==typeof e[i]&&(l.type=e[i]),l.name=i,-1===n.indexOf(i)){if(!(c=r.Light.GetConstructorFromName(l.type,l.name,t.scene)))return;a=c()}else if(a=t.scene.getLightByName(i),"boolean"==typeof e[i]&&(l.type=a.getTypeID()),n=n.filter(function(e){return e!==i}),void 0!==l.type&&a.getTypeID()!==l.type){var c;if(a.dispose(),!(c=r.Light.GetConstructorFromName(l.type,l.name,t.scene)))return;a=c()}if(!1!==e[i]){var u=void 0!==l.enabled?l.enabled:!l.disabled;if(a.setEnabled(u),s.extendClassWithConfig(a,l),a instanceof r.ShadowLight){if(a.shadowMinZ=a.shadowMinZ||.2,a.shadowMaxZ=Math.min(10,a.shadowMaxZ||10),l.target){if(a.setDirectionToTarget){var h=r.Vector3.Zero().copyFrom(l.target);a.setDirectionToTarget(h)}}else if(l.direction){var d=r.Vector3.Zero().copyFrom(l.direction);a.direction=d}var f=!1;if(a.getTypeID()===BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT)a.shadowFrustumSize=l.shadowFrustumSize||2,f=!0;else if(a.getTypeID()===BABYLON.Light.LIGHTTYPEID_SPOTLIGHT){var p=a;void 0!==l.spotAngle&&(p.angle=l.spotAngle*Math.PI/180),p.angle&&l.shadowFieldOfView&&(p.shadowAngleScale=l.shadowFieldOfView/p.angle),f=!0}else a.getTypeID()===BABYLON.Light.LIGHTTYPEID_POINTLIGHT&&(l.shadowFieldOfView&&(a.shadowAngle=l.shadowFieldOfView*Math.PI/180),f=!0);var m=a.getShadowGenerator();if(f&&l.shadowEnabled&&t._maxShadows){var g=l.shadowBufferSize||256;m||(m=new r.ShadowGenerator(g,a));var _=t.getBlurKernel(a,g);m.bias=t._shadowGeneratorBias,m.blurKernel=_,s.extendClassWithConfig(m,l.shadowConfig||{}),t._observablesManager&&t._observablesManager.onModelLoadedObservable.add(function(e){t._updateShadowRenderList(m,e)}),t._updateShadowRenderList(m)}else m&&m.dispose()}}else a.dispose()});var a=this._globalConfiguration.lights||{};Object.keys(a).sort().forEach(function(e,i){a[e];var r=t.scene.getLightByName(e);r&&(r.renderPriority=-i)})}else this.scene.lights.length||this.scene.createDefaultLight(!0);this.onLightsConfiguredObservable.notifyObservers({sceneManager:this,object:this.scene.lights,newConfiguration:e})},e.prototype._updateShadowRenderList=function(e,t,i){var n=t?t.meshes:this.scene.meshes,o=e.getShadowMap();if(o){i&&o.renderList?o.renderList.length=0:o.renderList=o.renderList||[];for(var s=0;s1){var i=r.Scalar.Clamp(e.scene.getEngine().getHardwareScalingLevel()-.25,0,1);return e.scene.getEngine().setHardwareScalingLevel(i),!1}if(!e.scene.postProcessesEnabled)return e.scene.postProcessesEnabled=!0,!1;if(!e.groundEnabled)return e.groundEnabled=!0,!1;if(t&&!e.fxaaEnabled)return e.fxaaEnabled=!0,!1;var n=Math.max(.5,1/(window.devicePixelRatio||2));if(e.scene.getEngine().getHardwareScalingLevel()>n)return i=r.Scalar.Clamp(e.scene.getEngine().getHardwareScalingLevel()-.25,0,n),e.scene.getEngine().setHardwareScalingLevel(i),!1;return e.processShadows?t&&!e.bloomEnabled?(e.bloomEnabled=!0,!1):!!e.groundMirrorEnabled||(e.groundMirrorEnabled=!0,!1):(e.processShadows=!0,!1)},t.extendedDegrade=function(e){var t=e.defaultRenderingPipeline;if(e.groundMirrorEnabled)return e.groundMirrorEnabled=!1,!1;if(t&&e.bloomEnabled)return e.bloomEnabled=!1,!1;if(e.processShadows)return e.processShadows=!1,!1;if(e.scene.getEngine().getHardwareScalingLevel()<1){var i=r.Scalar.Clamp(e.scene.getEngine().getHardwareScalingLevel()+.25,0,1);return e.scene.getEngine().setHardwareScalingLevel(i),!1}if(t&&e.fxaaEnabled)return e.fxaaEnabled=!1,!1;if(e.groundEnabled)return e.groundEnabled=!1,!1;if(e.scene.postProcessesEnabled)return e.scene.postProcessesEnabled=!1,!1;if(e.scene.getEngine().getHardwareScalingLevel()<1.25)return i=r.Scalar.Clamp(e.scene.getEngine().getHardwareScalingLevel()+.25,0,1.25),e.scene.getEngine().setHardwareScalingLevel(i),!1;return!0}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(0),n=i(1),o=i(18),s=i(64),a=i(1),l=function(){function e(e){this.containerElement=e,this.templates={},this.onTemplateInit=new r.Observable,this.onTemplateLoaded=new r.Observable,this.onTemplateStateChange=new r.Observable,this.onAllLoaded=new r.Observable,this.onEventTriggered=new r.Observable,this.eventManager=new s.EventManager(this)}return e.prototype.initTemplate=function(e){var t=this,i=function(e,r,o){var s=t.templates[r],a=(Object.keys(e).map(function(t){return i(e[t],t,s)}),function(){var e=o&&o.parent.querySelectorAll(n.camelToKebab(r)),i=e&&e.length&&e.item(e.length-1)||t.containerElement;s.appendTo(i),t._checkLoadedState()});return o&&!o.parent?o.onAppended.add(function(){a()}):a(),s};return this._buildHTMLTree(e).then(function(e){t.templates.main?i(e,"main"):t._checkLoadedState()})},e.prototype._buildHTMLTree=function(e){var t=this,i=Object.keys(e).map(function(i){if(!e[i])return Promise.resolve(!1);var r=new c(i,e[i]);return r.onLoaded.add(function(){t.onTemplateLoaded.notifyObservers(r)}),r.onStateChange.add(function(){t.onTemplateStateChange.notifyObservers(r)}),t.onTemplateInit.notifyObservers(r),r.onEventTriggered.add(function(e){return t.onEventTriggered.notifyObservers(e)}),t.templates[i]=r,r.initPromise});return Promise.all(i).then(function(){var e={},i=function(e,r){t.templates[r].isInHtmlTree=!0,t.templates[r].getChildElements().filter(function(e){return!!t.templates[e]}).forEach(function(t){e[t]={},i(e[t],t)})};return t.templates.main&&i(e,"main"),e})},e.prototype.getCanvas=function(){return this.containerElement.querySelector("canvas")},e.prototype.getTemplate=function(e){return this.templates[e]},e.prototype._checkLoadedState=function(){var e=this;(0===Object.keys(this.templates).length||Object.keys(this.templates).every(function(t){return e.templates[t].isLoaded&&!!e.templates[t].parent||!e.templates[t].isInHtmlTree}))&&this.onAllLoaded.notifyObservers(this)},e.prototype.dispose=function(){var e=this;Object.keys(this.templates).forEach(function(t){e.templates[t].dispose()}),this.templates={},this.eventManager.dispose(),this.onTemplateInit.clear(),this.onAllLoaded.clear(),this.onEventTriggered.clear(),this.onTemplateLoaded.clear(),this.onTemplateStateChange.clear()},e}();t.TemplateManager=l,o.registerHelper("eachInMap",function(e,t){var i="";return Object.keys(e).map(function(r){var n=e[r];"object"==typeof n?(n.id=n.id||r,i+=t.fn(n)):i+=t.fn({id:r,value:n})}),i}),o.registerHelper("add",function(e,t){return e+t}),o.registerHelper("eq",function(e,t){return e==t}),o.registerHelper("or",function(e,t){return e||t}),o.registerHelper("not",function(e){return!e}),o.registerHelper("count",function(e){return e.length}),o.registerHelper("gt",function(e,t){return e>t});var c=function(){function e(e,t){var i=this;this.name=e,this._configuration=t,this.onLoaded=new r.Observable,this.onAppended=new r.Observable,this.onStateChange=new r.Observable,this.onEventTriggered=new r.Observable,this.onParamsUpdated=new r.Observable,this.onHTMLRendered=new r.Observable,this.loadRequests=[],this.isLoaded=!1,this.isShown=!1,this.isInHtmlTree=!1;var n=this._getTemplateAsHtml(t);this.initPromise=n.then(function(e){if(e){i._htmlTemplate=e;var t=o.compile(e,{noEscape:i._configuration.params&&!!i._configuration.params.noEscape}),r=i._configuration.params||{};i._rawHtml=t(r);try{i._fragment=document.createRange().createContextualFragment(i._rawHtml)}catch(e){var n=document.createElement(i.name);n.innerHTML=i._rawHtml,i._fragment=n}i.isLoaded=!0,i.isShown=!0,i.onLoaded.notifyObservers(i)}return i})}return e.prototype.updateParams=function(e,t){void 0===t&&(t=!0),this._configuration.params=t?a.deepmerge(this._configuration.params,e):e,this.isLoaded;var i=o.compile(this._htmlTemplate),r=this._configuration.params||{};this._rawHtml=i(r);try{this._fragment=document.createRange().createContextualFragment(this._rawHtml)}catch(e){var n=document.createElement(this.name);n.innerHTML=this._rawHtml,this._fragment=n}this.parent&&this.appendTo(this.parent,!0)},e.prototype.redraw=function(){this.updateParams({})},Object.defineProperty(e.prototype,"configuration",{get:function(){return this._configuration},enumerable:!0,configurable:!0}),e.prototype.getChildElements=function(){var e=[],t=this._fragment&&this._fragment.children;if(!this._fragment){var i=this.parent.querySelector(this.name);i&&(t=i.querySelectorAll("*"))}t||(t=this._fragment.querySelectorAll("*"));for(var r=0;r\n.hd-icon:after {\n font-size: 16px;\n content: "\\F765";\n}\n\n.hd-toggled span.hd-icon:after {\n content: "\\F766";\n}\n\n\n {{/unless}}\n',t}(i(7).AbstractViewerNavbarButton);t.HDButtonPlugin=n},function(e,t,i){"use strict";var r=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])};return function(t,i){function r(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(t,"__esModule",{value:!0});var n=i(7),o=i(0),s=function(e){function t(i){var r=e.call(this,"print","print-button",t.HtmlTemplate)||this;return r._viewer=i,r._viewer.onModelLoadedObservable.add(function(e){if(r._currentModelUrl="",e.configuration.url){var t=o.Tools.GetFilename(e.configuration.url)||e.configuration.url,i=e.configuration.root||o.Tools.GetFolderPath(e.configuration.url),n=e.configuration.loader||t.split(".").pop()||"",s=!1;["gltf","glb","obj","stl"].forEach(function(e){-1!==n.indexOf(e)&&(s=!0)}),s&&(r._currentModelUrl=i+t)}}),r}return r(t,e),t.prototype.onEvent=function(e){if(this._currentModelUrl){var t=this._currentModelUrl.replace(/https?:\/\//,"com.microsoft.builder3d://");window.open(t,"_self")}},t.HtmlTemplate='\n{{#unless hidePrint}}\n\n\n {{/unless}}\n',t}(n.AbstractViewerNavbarButton);t.PrintButtonPlugin=s},function(e,t,i){ /*! * PEP v0.4.3 | https://github.com/jquery/PEP * Copyright jQuery Foundation and other contributors | http://jquery.org/license */ -e.exports=function(){"use strict";var e=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],t=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0];function i(i,r){r=r||Object.create(null);var n=document.createEvent("Event");n.initEvent(i,r.bubbles||!1,r.cancelable||!1);for(var o,s=2;s=a}return this.firstXY=null,t}},findTouch:function(e,t){for(var i,r=0,n=e.length;r=t.length){var i=[];I.forEach(function(e,r){if(1!==r&&!this.findTouch(t,r-2)){var n=e.out;i.push(n)}},this),i.forEach(this.cancelOut,this)}},touchstart:function(e){this.vacuumTouches(e),this.setPrimaryTouch(e.changedTouches[0]),this.dedupSynthMouse(e),this.scrolling||(this.clickCount++,this.processTouches(e,this.overDown))},overDown:function(e){I.set(e.pointerId,{target:e.target,out:e,outTarget:e.target}),c.enterOver(e),c.down(e)},touchmove:function(e){this.scrolling||(this.shouldScroll(e)?(this.scrolling=!0,this.touchcancel(e)):(e.preventDefault(),this.processTouches(e,this.moveOverOut)))},moveOverOut:function(e){var t=e,i=I.get(t.pointerId);if(i){var r=i.out,n=i.outTarget;c.move(t),r&&n!==t.target&&(r.relatedTarget=t.target,t.relatedTarget=n,r.target=n,t.target?(c.leaveOut(r),c.enterOver(t)):(t.target=n,t.relatedTarget=null,this.cancelOut(t))),i.out=t,i.outTarget=t.target}},touchend:function(e){this.dedupSynthMouse(e),this.processTouches(e,this.upOut)},upOut:function(e){this.scrolling||(c.up(e),c.leaveOut(e)),this.cleanUpPointer(e)},touchcancel:function(e){this.processTouches(e,this.cancelOut)},cancelOut:function(e){c.cancel(e),c.leaveOut(e),this.cleanUpPointer(e)},cleanUpPointer:function(e){I.delete(e.pointerId),this.removePrimaryPointer(e)},dedupSynthMouse:function(e){var t=R.lastTouches,i=e.changedTouches[0];if(this.isPrimaryTouch(i)){var r={x:i.clientX,y:i.clientY};t.push(r);var n=function(e,t){var i=e.indexOf(t);i>-1&&e.splice(i,1)}.bind(null,t,r);setTimeout(n,2500)}}};C=new _(L.elementAdded,L.elementRemoved,L.elementChanged,L);var B,F,N,V=c.pointermap,U=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,k={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(e){c.listen(e,this.events)},unregister:function(e){c.unlisten(e,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(e){var t=e;return U&&((t=c.cloneEvent(e)).pointerType=this.POINTER_TYPES[e.pointerType]),t},cleanup:function(e){V.delete(e)},MSPointerDown:function(e){V.set(e.pointerId,e);var t=this.prepareEvent(e);c.down(t)},MSPointerMove:function(e){var t=this.prepareEvent(e);c.move(t)},MSPointerUp:function(e){var t=this.prepareEvent(e);c.up(t),this.cleanup(e.pointerId)},MSPointerOut:function(e){var t=this.prepareEvent(e);c.leaveOut(t)},MSPointerOver:function(e){var t=this.prepareEvent(e);c.enterOver(t)},MSPointerCancel:function(e){var t=this.prepareEvent(e);c.cancel(t),this.cleanup(e.pointerId)},MSLostPointerCapture:function(e){var t=c.makeEvent("lostpointercapture",e);c.dispatchEvent(t)},MSGotPointerCapture:function(e){var t=c.makeEvent("gotpointercapture",e);c.dispatchEvent(t)}};function z(e){if(!c.pointermap.has(e)){var t=new Error("InvalidPointerId");throw t.name="InvalidPointerId",t}}function G(e){for(var t=e.parentNode;t&&t!==e.ownerDocument;)t=t.parentNode;if(!t){var i=new Error("InvalidStateError");throw i.name="InvalidStateError",i}}function H(e){var t=c.pointermap.get(e);return 0!==t.buttons}return window.navigator.msPointerEnabled?(B=function(e){z(e),G(this),H(e)&&(c.setCapture(e,this,!0),this.msSetPointerCapture(e))},F=function(e){z(e),c.releaseCapture(e,!0),this.msReleasePointerCapture(e)}):(B=function(e){z(e),G(this),H(e)&&c.setCapture(e,this)},F=function(e){z(e),c.releaseCapture(e)}),N=function(e){return!!c.captureInfo[e]},function(){if(E){b.forEach(function(e){String(e)===e?(T+=A(e)+y(e)+"\n",x&&(T+=v(e)+y(e)+"\n")):(T+=e.selectors.map(A)+y(e.rule)+"\n",x&&(T+=e.selectors.map(v)+y(e.rule)+"\n"))});var e=document.createElement("style");e.textContent=T,document.head.appendChild(e)}}(),function(){if(!window.PointerEvent){if(window.PointerEvent=i,window.navigator.msPointerEnabled){var e=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:e,enumerable:!0}),c.registerSource("ms",k)}else Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),c.registerSource("mouse",R),void 0!==window.ontouchstart&&c.registerSource("touch",L);c.register(document)}}(),window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:B},releasePointerCapture:{value:F},hasPointerCapture:{value:N}}),{dispatcher:c,Installer:_,PointerEvent:i,PointerMap:r,targetFinding:u}}()},function(e,t,i){"use strict";var r=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])};return function(t,i){function r(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(t,"__esModule",{value:!0});var n=i(3),o=i(0),s=function(e){function t(i){var r=e.call(this,"print","print-button",t.HtmlTemplate)||this;return r._viewer=i,r._viewer.onModelLoadedObservable.add(function(e){if(r._currentModelUrl="",e.configuration.url){var t=o.Tools.GetFilename(e.configuration.url)||e.configuration.url,i=e.configuration.root||o.Tools.GetFolderPath(e.configuration.url),n=e.configuration.loader||t.split(".").pop()||"",s=!1;["gltf","glb","obj","stl"].forEach(function(e){-1!==n.indexOf(e)&&(s=!0)}),s&&(r._currentModelUrl=i+t)}}),r}return r(t,e),t.prototype.onEvent=function(e){if(this._currentModelUrl){var t=this._currentModelUrl.replace(/https?:\/\//,"com.microsoft.builder3d://");window.open(t,"_self")}},t.HtmlTemplate='\n{{#unless hidePrint}}\n\n\n {{/unless}}\n',t}(n.AbstractViewerNavbarButton);t.PrintButtonPlugin=s},function(e,t,i){"use strict";var r=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])};return function(t,i){function r(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}();Object.defineProperty(t,"__esModule",{value:!0});var n=function(e){function t(i){var r=e.call(this,"hd","hd-button",t.HtmlTemplate)||this;return r._viewer=i,r}return r(t,e),t.prototype.onEvent=function(e){var t=e.template.parent.querySelector(".hd-button");t&&(t.classList.contains("hd-toggled")?t.classList.remove("hd-toggled"):t.classList.add("hd-toggled")),this._viewer.toggleHD()},t.HtmlTemplate='\n{{#unless hideHd}}\n\n\n {{/unless}}\n',t}(i(3).AbstractViewerNavbarButton);t.HDButtonPlugin=n},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e){var t=this;this._templateManager=e,this._callbacksContainer={},this._templateManager.onEventTriggered.add(function(e){t._eventTriggered(e)})}return e.prototype.registerCallback=function(e,t,i,r){this._callbacksContainer[e]||(this._callbacksContainer[e]=[]),this._callbacksContainer[e].push({eventType:i,callback:t,selector:r})},e.prototype.unregisterCallback=function(e,t,i,r){var n=this._callbacksContainer[e]||[];this._callbacksContainer[e]=n.filter(function(e){return!(e.eventType&&e.eventType!==i||e.selector&&e.selector!==r)})},e.prototype._eventTriggered=function(e){var t=e.template.name,i=e.event.type,r=e.selector;(this._callbacksContainer[t]||[]).filter(function(e){return!(e.eventType&&e.eventType!==i||e.selector&&e.selector!==r)}).forEach(function(t){t.callback(e)})},e.prototype.dispose=function(){this._callbacksContainer={}},e}();t.EventManager=r},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(0),n=i(1),o=i(8),s=i(23),a=i(1),l=function(){function e(e){this.containerElement=e,this.templates={},this.onTemplateInit=new r.Observable,this.onTemplateLoaded=new r.Observable,this.onTemplateStateChange=new r.Observable,this.onAllLoaded=new r.Observable,this.onEventTriggered=new r.Observable,this.eventManager=new s.EventManager(this)}return e.prototype.initTemplate=function(e){var t=this,i=function(e,r,o){var s=t.templates[r],a=(Object.keys(e).map(function(t){return i(e[t],t,s)}),function(){var e=o&&o.parent.querySelectorAll(n.camelToKebab(r)),i=e&&e.length&&e.item(e.length-1)||t.containerElement;s.appendTo(i),t._checkLoadedState()});return o&&!o.parent?o.onAppended.add(function(){a()}):a(),s};return this._buildHTMLTree(e).then(function(e){t.templates.main?i(e,"main"):t._checkLoadedState()})},e.prototype._buildHTMLTree=function(e){var t=this,i=Object.keys(e).map(function(i){if(!e[i])return Promise.resolve(!1);var r=new c(i,e[i]);return r.onLoaded.add(function(){t.onTemplateLoaded.notifyObservers(r)}),r.onStateChange.add(function(){t.onTemplateStateChange.notifyObservers(r)}),t.onTemplateInit.notifyObservers(r),r.onEventTriggered.add(function(e){return t.onEventTriggered.notifyObservers(e)}),t.templates[i]=r,r.initPromise});return Promise.all(i).then(function(){var e={},i=function(e,r){t.templates[r].isInHtmlTree=!0,t.templates[r].getChildElements().filter(function(e){return!!t.templates[e]}).forEach(function(t){e[t]={},i(e[t],t)})};return t.templates.main&&i(e,"main"),e})},e.prototype.getCanvas=function(){return this.containerElement.querySelector("canvas")},e.prototype.getTemplate=function(e){return this.templates[e]},e.prototype._checkLoadedState=function(){var e=this;(0===Object.keys(this.templates).length||Object.keys(this.templates).every(function(t){return e.templates[t].isLoaded&&!!e.templates[t].parent||!e.templates[t].isInHtmlTree}))&&this.onAllLoaded.notifyObservers(this)},e.prototype.dispose=function(){var e=this;Object.keys(this.templates).forEach(function(t){e.templates[t].dispose()}),this.templates={},this.eventManager.dispose(),this.onTemplateInit.clear(),this.onAllLoaded.clear(),this.onEventTriggered.clear(),this.onTemplateLoaded.clear(),this.onTemplateStateChange.clear()},e}();t.TemplateManager=l,o.registerHelper("eachInMap",function(e,t){var i="";return Object.keys(e).map(function(r){var n=e[r];"object"==typeof n?(n.id=n.id||r,i+=t.fn(n)):i+=t.fn({id:r,value:n})}),i}),o.registerHelper("add",function(e,t){return e+t}),o.registerHelper("eq",function(e,t){return e==t}),o.registerHelper("or",function(e,t){return e||t}),o.registerHelper("not",function(e){return!e}),o.registerHelper("count",function(e){return e.length}),o.registerHelper("gt",function(e,t){return e>t});var c=function(){function e(e,t){var i=this;this.name=e,this._configuration=t,this.onLoaded=new r.Observable,this.onAppended=new r.Observable,this.onStateChange=new r.Observable,this.onEventTriggered=new r.Observable,this.onParamsUpdated=new r.Observable,this.onHTMLRendered=new r.Observable,this.loadRequests=[],this.isLoaded=!1,this.isShown=!1,this.isInHtmlTree=!1;var n=this._getTemplateAsHtml(t);this.initPromise=n.then(function(e){if(e){i._htmlTemplate=e;var t=o.compile(e,{noEscape:i._configuration.params&&!!i._configuration.params.noEscape}),r=i._configuration.params||{};i._rawHtml=t(r);try{i._fragment=document.createRange().createContextualFragment(i._rawHtml)}catch(e){var n=document.createElement(i.name);n.innerHTML=i._rawHtml,i._fragment=n}i.isLoaded=!0,i.isShown=!0,i.onLoaded.notifyObservers(i)}return i})}return e.prototype.updateParams=function(e,t){void 0===t&&(t=!0),this._configuration.params=t?a.deepmerge(this._configuration.params,e):e,this.isLoaded;var i=o.compile(this._htmlTemplate),r=this._configuration.params||{};this._rawHtml=i(r);try{this._fragment=document.createRange().createContextualFragment(this._rawHtml)}catch(e){var n=document.createElement(this.name);n.innerHTML=this._rawHtml,this._fragment=n}this.parent&&this.appendTo(this.parent,!0)},e.prototype.redraw=function(){this.updateParams({})},Object.defineProperty(e.prototype,"configuration",{get:function(){return this._configuration},enumerable:!0,configurable:!0}),e.prototype.getChildElements=function(){var e=[],t=this._fragment&&this._fragment.children;if(!this._fragment){var i=this.parent.querySelector(this.name);i&&(t=i.querySelectorAll("*"))}t||(t=this._fragment.querySelectorAll("*"));for(var r=0;r1){var i=r.Scalar.Clamp(e.scene.getEngine().getHardwareScalingLevel()-.25,0,1);return e.scene.getEngine().setHardwareScalingLevel(i),!1}if(!e.scene.postProcessesEnabled)return e.scene.postProcessesEnabled=!0,!1;if(!e.groundEnabled)return e.groundEnabled=!0,!1;if(t&&!e.fxaaEnabled)return e.fxaaEnabled=!0,!1;var n=Math.max(.5,1/(window.devicePixelRatio||2));if(e.scene.getEngine().getHardwareScalingLevel()>n)return i=r.Scalar.Clamp(e.scene.getEngine().getHardwareScalingLevel()-.25,0,n),e.scene.getEngine().setHardwareScalingLevel(i),!1;return e.processShadows?t&&!e.bloomEnabled?(e.bloomEnabled=!0,!1):!!e.groundMirrorEnabled||(e.groundMirrorEnabled=!0,!1):(e.processShadows=!0,!1)},t.extendedDegrade=function(e){var t=e.defaultRenderingPipeline;if(e.groundMirrorEnabled)return e.groundMirrorEnabled=!1,!1;if(t&&e.bloomEnabled)return e.bloomEnabled=!1,!1;if(e.processShadows)return e.processShadows=!1,!1;if(e.scene.getEngine().getHardwareScalingLevel()<1){var i=r.Scalar.Clamp(e.scene.getEngine().getHardwareScalingLevel()+.25,0,1);return e.scene.getEngine().setHardwareScalingLevel(i),!1}if(t&&e.fxaaEnabled)return e.fxaaEnabled=!1,!1;if(e.groundEnabled)return e.groundEnabled=!1,!1;if(e.scene.postProcessesEnabled)return e.scene.postProcessesEnabled=!1,!1;if(e.scene.getEngine().getHardwareScalingLevel()<1.25)return i=r.Scalar.Clamp(e.scene.getEngine().getHardwareScalingLevel()+.25,0,1.25),e.scene.getEngine().setHardwareScalingLevel(i),!1;return!0}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(0),n=i(10),o=function(){function e(){}return e.Parse=function(t){for(var i={irradiancePolynomialCoefficients:{x:new r.Vector3(0,0,0),y:new r.Vector3(0,0,0),z:new r.Vector3(0,0,0),xx:new r.Vector3(0,0,0),yy:new r.Vector3(0,0,0),zz:new r.Vector3(0,0,0),yz:new r.Vector3(0,0,0),zx:new r.Vector3(0,0,0),xy:new r.Vector3(0,0,0)},textureIntensityScale:1},o=[134,22,135,150,246,214,150,54],s=new DataView(t),a=0,l=0;l0?(t(),n._forceShadowUpdate=!1):n.models.every(function(e){return e.shadowsRenderedAfterLoad?e.state===o.ModelState.COMPLETE&&!e.currentAnimation:(e.shadowsRenderedAfterLoad=!0,!1)})||t()}),n._observablesManager&&n._observablesManager.onSceneInitObservable.notifyObserversWithPromise(n.scene)}),this._observablesManager&&(this._observablesManager.onModelLoadedObservable.add(function(e){for(var t=0,i=n.scene.lights;t0,this._defaultRenderingPipeline.bloomWeight=void 0!==t.bloomWeight&&t.bloomWeight||this._defaultRenderingPipeline.bloomWeight),this._defaultRenderingPipeline.bloomEnabled=i,this._defaultRenderingPipeline.fxaaEnabled=this.fxaaEnabled}}else this._defaultRenderingPipeline&&(this._defaultRenderingPipeline.dispose(),this._defaultRenderingPipeline=null,this.scene.autoClearDepthAndStencil=!0,this.scene.autoClear=!0,this.scene.imageProcessingConfiguration.applyByPostProcess=!1)},Object.defineProperty(e.prototype,"bloomEnabled",{get:function(){return this._bloomEnabled},set:function(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._rebuildPostprocesses(),this._defaultRenderingPipeline&&(this._defaultRenderingPipelineShouldBuild=!1,this._defaultRenderingPipeline.prepare(),this.scene.imageProcessingConfiguration.applyByPostProcess=!0))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"fxaaEnabled",{get:function(){return this._fxaaEnabled},set:function(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._rebuildPostprocesses(),this._defaultRenderingPipeline&&(this._defaultRenderingPipelineShouldBuild=!1,this._defaultRenderingPipeline.prepare(),this.scene.imageProcessingConfiguration.applyByPostProcess=!0))},enumerable:!0,configurable:!0}),e.prototype._configureScene=function(e){if(this.scene){var t=e.clearColor,i=this.scene.clearColor;if(t&&(void 0!==t.r&&(i.r=t.r),void 0!==t.g&&(i.g=t.g),void 0!==t.b&&(i.b=t.b),void 0!==t.a&&(i.a=t.a)),e.assetsRootURL&&(this._assetsRootURL=e.assetsRootURL),e.imageProcessingConfiguration&&s.extendClassWithConfig(this.scene.imageProcessingConfiguration,e.imageProcessingConfiguration),e.animationPropertiesOverride&&s.extendClassWithConfig(this.scene.animationPropertiesOverride,e.animationPropertiesOverride),e.environmentTexture&&(!this.scene.environmentTexture||this.scene.environmentTexture.url!==e.environmentTexture)){this.scene.environmentTexture&&this.scene.environmentTexture.dispose&&this.scene.environmentTexture.dispose();var n=r.CubeTexture.CreateFromPrefilteredData(e.environmentTexture,this.scene);this.scene.environmentTexture=n}!0===e.debug?this.scene.debugLayer.show():!1===e.debug&&this.scene.debugLayer.isVisible()&&this.scene.debugLayer.hide(),e.disableHdr?this._handleHardwareLimitations(!1):this._handleHardwareLimitations(!0),void 0!==e.renderInBackground&&(this._engine.renderEvenInBackground=!!e.renderInBackground);var o=this._engine.getRenderingCanvas();if(o&&(this.camera&&e.disableCameraControl?this.camera.detachControl(o):this.camera&&!1===e.disableCameraControl&&this.camera.attachControl(o)),e.defaultMaterial){var a=e.defaultMaterial;("standard"===a.materialType&&"StandardMaterial"!==this.scene.defaultMaterial.getClassName()||"pbr"===a.materialType&&"PBRMaterial"!==this.scene.defaultMaterial.getClassName())&&(this.scene.defaultMaterial.dispose(),"standard"===a.materialType?this.scene.defaultMaterial=new r.StandardMaterial("defaultMaterial",this.scene):this.scene.defaultMaterial=new r.PBRMaterial("defaultMaterial",this.scene)),s.extendClassWithConfig(this.scene.defaultMaterial,a)}e.flags&&s.extendClassWithConfig(this.scene,e.flags),this.onSceneConfiguredObservable.notifyObservers({sceneManager:this,object:this.scene,newConfiguration:e})}},e.prototype._configureOptimizer=function(e){var t=this;if("boolean"==typeof e)this.sceneOptimizer&&(this.sceneOptimizer.stop(),this.sceneOptimizer.dispose(),delete this.sceneOptimizer),e&&(this.sceneOptimizer=new r.SceneOptimizer(this.scene),this.sceneOptimizer.start());else{var i=new r.SceneOptimizerOptions(e.targetFrameRate,e.trackerDuration);if(e.degradation)switch(e.degradation){case"low":i=r.SceneOptimizerOptions.LowDegradationAllowed(e.targetFrameRate);break;case"moderate":i=r.SceneOptimizerOptions.ModerateDegradationAllowed(e.targetFrameRate);break;case"hight":i=r.SceneOptimizerOptions.HighDegradationAllowed(e.targetFrameRate)}if(this.sceneOptimizer&&(this.sceneOptimizer.stop(),this.sceneOptimizer.dispose()),e.custom){var n=l.getCustomOptimizerByName(e.custom,e.improvementMode);n&&i.addCustomOptimization(function(){return n(t)},function(){return"Babylon Viewer "+e.custom+" custom optimization"})}this.sceneOptimizer=new r.SceneOptimizer(this.scene,i,e.autoGeneratePriorities,e.improvementMode),this.sceneOptimizer.start()}this.onSceneOptimizerConfiguredObservable.notifyObservers({sceneManager:this,object:this.sceneOptimizer,newConfiguration:e})},e.prototype._configureVR=function(e){var t=this;if(e.disabled)this._vrHelper&&(this._vrHelper.isInVRMode&&this._vrHelper.exitVR(),this._vrHelper.dispose(),this._vrHelper=void 0);else{var i,n=c.deepmerge({useCustomVRButton:!0,createDeviceOrientationCamera:!1,trackPosition:!0},e.vrOptions||{});if(this._vrHelper=this.scene.createDefaultVRExperience(n),e.disableInteractions||this._vrHelper.enableInteractions(),!e.disableTeleportation){var o=e.overrideFloorMeshName||"BackgroundPlane";this._vrHelper.enableTeleportation({floorMeshName:o})}if(e.rotateUsingControllers)this._vrHelper.onControllerMeshLoadedObservable.add(function(e){e.onTriggerStateChangedObservable.add(function(n){e.mesh&&e.mesh.rotationQuaternion&&(n.pressed?i||(t.models[0].rootMesh.rotationQuaternion=t.models[0].rootMesh.rotationQuaternion||new r.Quaternion,i=e.mesh.rotationQuaternion.conjugate().multiply(t.models[0].rootMesh.rotationQuaternion)):i=null)}),t.scene.registerBeforeRender(function(){t.models[0]&&(i&&e.mesh&&e.mesh.rotationQuaternion?t.models[0].rootMesh.rotationQuaternion.copyFrom(e.mesh.rotationQuaternion).multiplyInPlace(i):t.models[0].rootMesh.rotationQuaternion=null)})});this.onVRConfiguredObservable.notifyObservers({sceneManager:this,object:this._vrHelper,newConfiguration:e})}},e.prototype._configureEnvironmentMap=function(e){if(e.texture&&(this.scene.environmentTexture=new BABYLON.CubeTexture(this._getAssetUrl(e.texture),this.scene)),this.scene.environmentTexture){var t=r.Quaternion.RotationAxis(r.Axis.Y,e.rotationY||0);r.Matrix.FromQuaternionToRef(t,this.scene.environmentTexture.getReflectionTextureMatrix())}if(e.mainColor){this._configurationContainer.mainColor=this.mainColor||r.Color3.White();var i=e.mainColor;void 0!==i.r&&(this.mainColor.r=i.r),void 0!==i.g&&(this.mainColor.g=i.g),void 0!==i.b&&(this.mainColor.b=i.b),this.reflectionColor.copyFrom(this.mainColor);var o=n.getConfigurationKey("environmentMap.tintLevel",this._globalConfiguration)||0;this.reflectionColor.toLinearSpaceToRef(this.reflectionColor),this.reflectionColor.scaleToRef(1/this.scene.imageProcessingConfiguration.exposure,this.reflectionColor);var s=r.Color3.Lerp(this._white,this.reflectionColor,o);this.reflectionColor.copyFrom(s),this.environmentHelper&&(this.environmentHelper.groundMaterial&&(this.environmentHelper.groundMaterial._perceptualColor=this.mainColor),this.environmentHelper.skyboxMaterial&&(this.environmentHelper.skyboxMaterial._perceptualColor=this.mainColor))}},e.prototype._configureCamera=function(e){var t=this;if(void 0===e&&(e={}),!this.scene.activeCamera){var i=!0;this._globalConfiguration.scene&&this._globalConfiguration.scene.disableCameraControl&&(i=!1),this.scene.createDefaultCamera(!0,!0,i),this.camera=this.scene.activeCamera,this.camera.setTarget(r.Vector3.Zero())}if(this.camera||(this.camera=this.scene.activeCamera),e.position){var o=this.camera.position.clone();s.extendClassWithConfig(o,e.position),this.camera.setPosition(o)}if(e.target){var a=this.camera.target.clone();s.extendClassWithConfig(a,e.target),this.camera.setTarget(a)}if(e.rotation&&(this.camera.rotationQuaternion=new r.Quaternion(e.rotation.x||0,e.rotation.y||0,e.rotation.z||0,e.rotation.w||0)),e.behaviors)for(var l in e.behaviors)void 0!==e.behaviors[l]&&this._setCameraBehavior(l,e.behaviors[l]);var c=this.scene.getWorldExtends(function(e){return!t.environmentHelper||e!==t.environmentHelper.ground&&e!==t.environmentHelper.rootMesh&&e!==t.environmentHelper.skybox}),u=c.max.subtract(c.min).length();isFinite(u)&&(this.camera.upperRadiusLimit=4*u),this.scene.imageProcessingConfiguration&&(this.scene.imageProcessingConfiguration.colorCurvesEnabled=!0,this.scene.imageProcessingConfiguration.vignetteEnabled=!0,this.scene.imageProcessingConfiguration.toneMappingEnabled=!!n.getConfigurationKey("camera.toneMappingEnabled",this._globalConfiguration)),s.extendClassWithConfig(this.camera,e),this.onCameraConfiguredObservable.notifyObservers({sceneManager:this,object:this.camera,newConfiguration:e})},e.prototype._configureEnvironment=function(e,t){var i=this;if(e||t){var n={createGround:!!t&&this._groundEnabled,createSkybox:!!e,setupImageProcessing:!1};if(t){var o="boolean"==typeof t?{}:t,a=o.size||"object"==typeof e&&e.scale;a&&(n.groundSize=a),n.enableGroundShadow=!0===o||o.receiveShadows,void 0!==o.shadowLevel&&(n.groundShadowLevel=o.shadowLevel),n.enableGroundMirror=!!o.mirror&&this.groundMirrorEnabled,o.texture&&(n.groundTexture=this._getAssetUrl(o.texture)),o.color&&(n.groundColor=new r.Color3(o.color.r,o.color.g,o.color.b)),void 0!==o.opacity&&(n.groundOpacity=o.opacity),o.mirror&&(n.enableGroundMirror=!0,"object"==typeof o.mirror&&(void 0!==o.mirror.amount&&(n.groundMirrorAmount=o.mirror.amount),void 0!==o.mirror.sizeRatio&&(n.groundMirrorSizeRatio=o.mirror.sizeRatio),void 0!==o.mirror.blurKernel&&(n.groundMirrorBlurKernel=o.mirror.blurKernel),void 0!==o.mirror.fresnelWeight&&(n.groundMirrorFresnelWeight=o.mirror.fresnelWeight),void 0!==o.mirror.fallOffDistance&&(n.groundMirrorFallOffDistance=o.mirror.fallOffDistance),void 0!==this._defaultPipelineTextureType&&(n.groundMirrorTextureType=this._defaultPipelineTextureType)))}var l=!1;if(e){var c=!0===e?{}:e;c.material&&c.material.imageProcessingConfiguration&&(n.setupImageProcessing=!1);var u=c.scale;u&&(n.skyboxSize=u),n.sizeAuto=!n.skyboxSize,c.color&&(n.skyboxColor=new r.Color3(c.color.r,c.color.g,c.color.b)),c.cubeTexture&&c.cubeTexture.url&&("string"==typeof c.cubeTexture.url?n.skyboxTexture=this._getAssetUrl(c.cubeTexture.url):l=!0),c.material&&(l=!0)}if(n.setupImageProcessing=!1,this.environmentHelper)this.environmentHelper.rootMesh.getScene()!==this.scene?(this.environmentHelper.dispose(),this.environmentHelper=this.scene.createDefaultEnvironment(n)):(this.environmentHelper.ground&&this.environmentHelper.ground.dispose(),this.environmentHelper.skybox&&this.environmentHelper.skybox.dispose(),this.environmentHelper.updateOptions(n));else this.environmentHelper=this.scene.createDefaultEnvironment(n);this.environmentHelper.rootMesh&&this._globalConfiguration.scene&&void 0!==this._globalConfiguration.scene.environmentRotationY&&(this.environmentHelper.rootMesh.rotation.y=this._globalConfiguration.scene.environmentRotationY);var h="boolean"==typeof t?{}:t;if(this.environmentHelper.groundMaterial&&h&&(this.environmentHelper.groundMaterial._perceptualColor=this.mainColor,h.material&&s.extendClassWithConfig(this.environmentHelper.groundMaterial,h.material),this.environmentHelper.groundMirror)){var d=this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace(),f=Math.pow(2,-this.scene.imageProcessingConfiguration.exposure)*Math.PI;d.scaleToRef(1/f,d),this.environmentHelper.groundMirror.clearColor.r=r.Scalar.Clamp(d.r),this.environmentHelper.groundMirror.clearColor.g=r.Scalar.Clamp(d.g),this.environmentHelper.groundMirror.clearColor.b=r.Scalar.Clamp(d.b),this.environmentHelper.groundMirror.clearColor.a=1,this.groundMirrorEnabled||(this.environmentHelper.groundMaterial.reflectionTexture=null)}var p=this.environmentHelper.skyboxMaterial;p&&(p._perceptualColor=this.mainColor,l&&"object"==typeof e&&e.material&&s.extendClassWithConfig(p,e.material))}else this.environmentHelper&&(this.environmentHelper.dispose(),this.environmentHelper=void 0);this._observablesManager&&this._observablesManager.onModelLoadedObservable.add(function(e){i._updateGroundMirrorRenderList(e)}),this.onEnvironmentConfiguredObservable.notifyObservers({sceneManager:this,object:this.environmentHelper,newConfiguration:{skybox:e,ground:t}})},e.prototype._configureLights=function(e){var t=this;void 0===e&&(e={});var i=Object.keys(e).filter(function(e){return"globalRotation"!==e});if(i.length){var n=this.scene.lights.map(function(e){return e.name}),o=Object.keys(this._globalConfiguration.lights||[]);Object.keys(o).length!==n.length&&n.forEach(function(e){-1===o.indexOf(e)&&t.scene.getLightByName(e).dispose()}),i.forEach(function(i,o){var a,l={type:0};if("object"==typeof e[i]&&(l=e[i]),"number"==typeof e[i]&&(l.type=e[i]),l.name=i,-1===n.indexOf(i)){if(!(c=r.Light.GetConstructorFromName(l.type,l.name,t.scene)))return;a=c()}else if(a=t.scene.getLightByName(i),"boolean"==typeof e[i]&&(l.type=a.getTypeID()),n=n.filter(function(e){return e!==i}),void 0!==l.type&&a.getTypeID()!==l.type){var c;if(a.dispose(),!(c=r.Light.GetConstructorFromName(l.type,l.name,t.scene)))return;a=c()}if(!1!==e[i]){var u=void 0!==l.enabled?l.enabled:!l.disabled;if(a.setEnabled(u),s.extendClassWithConfig(a,l),a instanceof r.ShadowLight){if(a.shadowMinZ=a.shadowMinZ||.2,a.shadowMaxZ=Math.min(10,a.shadowMaxZ||10),l.target){if(a.setDirectionToTarget){var h=r.Vector3.Zero().copyFrom(l.target);a.setDirectionToTarget(h)}}else if(l.direction){var d=r.Vector3.Zero().copyFrom(l.direction);a.direction=d}var f=!1;if(a.getTypeID()===BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT)a.shadowFrustumSize=l.shadowFrustumSize||2,f=!0;else if(a.getTypeID()===BABYLON.Light.LIGHTTYPEID_SPOTLIGHT){var p=a;void 0!==l.spotAngle&&(p.angle=l.spotAngle*Math.PI/180),p.angle&&l.shadowFieldOfView&&(p.shadowAngleScale=l.shadowFieldOfView/p.angle),f=!0}else a.getTypeID()===BABYLON.Light.LIGHTTYPEID_POINTLIGHT&&(l.shadowFieldOfView&&(a.shadowAngle=l.shadowFieldOfView*Math.PI/180),f=!0);var m=a.getShadowGenerator();if(f&&l.shadowEnabled&&t._maxShadows){var g=l.shadowBufferSize||256;m||(m=new r.ShadowGenerator(g,a));var _=t.getBlurKernel(a,g);m.bias=t._shadowGeneratorBias,m.blurKernel=_,s.extendClassWithConfig(m,l.shadowConfig||{}),t._observablesManager&&t._observablesManager.onModelLoadedObservable.add(function(e){t._updateShadowRenderList(m,e)}),t._updateShadowRenderList(m)}else m&&m.dispose()}}else a.dispose()});var a=this._globalConfiguration.lights||{};Object.keys(a).sort().forEach(function(e,i){a[e];var r=t.scene.getLightByName(e);r&&(r.renderPriority=-i)})}else this.scene.lights.length||this.scene.createDefaultLight(!0);this.onLightsConfiguredObservable.notifyObservers({sceneManager:this,object:this.scene.lights,newConfiguration:e})},e.prototype._updateShadowRenderList=function(e,t,i){var n=t?t.meshes:this.scene.meshes,o=e.getShadowMap();if(o){i&&o.renderList?o.renderList.length=0:o.renderList=o.renderList||[];for(var s=0;s=a}return this.firstXY=null,t}},findTouch:function(e,t){for(var i,r=0,n=e.length;r=t.length){var i=[];I.forEach(function(e,r){if(1!==r&&!this.findTouch(t,r-2)){var n=e.out;i.push(n)}},this),i.forEach(this.cancelOut,this)}},touchstart:function(e){this.vacuumTouches(e),this.setPrimaryTouch(e.changedTouches[0]),this.dedupSynthMouse(e),this.scrolling||(this.clickCount++,this.processTouches(e,this.overDown))},overDown:function(e){I.set(e.pointerId,{target:e.target,out:e,outTarget:e.target}),c.enterOver(e),c.down(e)},touchmove:function(e){this.scrolling||(this.shouldScroll(e)?(this.scrolling=!0,this.touchcancel(e)):(e.preventDefault(),this.processTouches(e,this.moveOverOut)))},moveOverOut:function(e){var t=e,i=I.get(t.pointerId);if(i){var r=i.out,n=i.outTarget;c.move(t),r&&n!==t.target&&(r.relatedTarget=t.target,t.relatedTarget=n,r.target=n,t.target?(c.leaveOut(r),c.enterOver(t)):(t.target=n,t.relatedTarget=null,this.cancelOut(t))),i.out=t,i.outTarget=t.target}},touchend:function(e){this.dedupSynthMouse(e),this.processTouches(e,this.upOut)},upOut:function(e){this.scrolling||(c.up(e),c.leaveOut(e)),this.cleanUpPointer(e)},touchcancel:function(e){this.processTouches(e,this.cancelOut)},cancelOut:function(e){c.cancel(e),c.leaveOut(e),this.cleanUpPointer(e)},cleanUpPointer:function(e){I.delete(e.pointerId),this.removePrimaryPointer(e)},dedupSynthMouse:function(e){var t=R.lastTouches,i=e.changedTouches[0];if(this.isPrimaryTouch(i)){var r={x:i.clientX,y:i.clientY};t.push(r);var n=function(e,t){var i=e.indexOf(t);i>-1&&e.splice(i,1)}.bind(null,t,r);setTimeout(n,2500)}}};C=new _(L.elementAdded,L.elementRemoved,L.elementChanged,L);var B,F,N,V=c.pointermap,U=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,k={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(e){c.listen(e,this.events)},unregister:function(e){c.unlisten(e,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(e){var t=e;return U&&((t=c.cloneEvent(e)).pointerType=this.POINTER_TYPES[e.pointerType]),t},cleanup:function(e){V.delete(e)},MSPointerDown:function(e){V.set(e.pointerId,e);var t=this.prepareEvent(e);c.down(t)},MSPointerMove:function(e){var t=this.prepareEvent(e);c.move(t)},MSPointerUp:function(e){var t=this.prepareEvent(e);c.up(t),this.cleanup(e.pointerId)},MSPointerOut:function(e){var t=this.prepareEvent(e);c.leaveOut(t)},MSPointerOver:function(e){var t=this.prepareEvent(e);c.enterOver(t)},MSPointerCancel:function(e){var t=this.prepareEvent(e);c.cancel(t),this.cleanup(e.pointerId)},MSLostPointerCapture:function(e){var t=c.makeEvent("lostpointercapture",e);c.dispatchEvent(t)},MSGotPointerCapture:function(e){var t=c.makeEvent("gotpointercapture",e);c.dispatchEvent(t)}};function z(e){if(!c.pointermap.has(e)){var t=new Error("InvalidPointerId");throw t.name="InvalidPointerId",t}}function G(e){for(var t=e.parentNode;t&&t!==e.ownerDocument;)t=t.parentNode;if(!t){var i=new Error("InvalidStateError");throw i.name="InvalidStateError",i}}function H(e){var t=c.pointermap.get(e);return 0!==t.buttons}return window.navigator.msPointerEnabled?(B=function(e){z(e),G(this),H(e)&&(c.setCapture(e,this,!0),this.msSetPointerCapture(e))},F=function(e){z(e),c.releaseCapture(e,!0),this.msReleasePointerCapture(e)}):(B=function(e){z(e),G(this),H(e)&&c.setCapture(e,this)},F=function(e){z(e),c.releaseCapture(e)}),N=function(e){return!!c.captureInfo[e]},function(){if(E){b.forEach(function(e){String(e)===e?(T+=A(e)+y(e)+"\n",x&&(T+=v(e)+y(e)+"\n")):(T+=e.selectors.map(A)+y(e.rule)+"\n",x&&(T+=e.selectors.map(v)+y(e.rule)+"\n"))});var e=document.createElement("style");e.textContent=T,document.head.appendChild(e)}}(),function(){if(!window.PointerEvent){if(window.PointerEvent=i,window.navigator.msPointerEnabled){var e=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:e,enumerable:!0}),c.registerSource("ms",k)}else Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),c.registerSource("mouse",R),void 0!==window.ontouchstart&&c.registerSource("touch",L);c.register(document)}}(),window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:B},releasePointerCapture:{value:F},hasPointerCapture:{value:N}}),{dispatcher:c,Installer:_,PointerEvent:i,PointerMap:r,targetFinding:u}}()},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(9),n=i(3),o=i(4);function s(e){void 0===e&&(e="babylon");for(var t=document.querySelectorAll(e),i=0;i=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};\nvar __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();\nvar BABYLON;\n(function (BABYLON) {\n /**\n * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.\n * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)\n */\n var EffectFallbacks = /** @class */ (function () {\n function EffectFallbacks() {\n this._defines = {};\n this._currentRank = 32;\n this._maxRank = -1;\n }\n /**\n * Removes the fallback from the bound mesh.\n */\n EffectFallbacks.prototype.unBindMesh = function () {\n this._mesh = null;\n };\n /**\n * Adds a fallback on the specified property.\n * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)\n * @param define The name of the define in the shader\n */\n EffectFallbacks.prototype.addFallback = function (rank, define) {\n if (!this._defines[rank]) {\n if (rank < this._currentRank) {\n this._currentRank = rank;\n }\n if (rank > this._maxRank) {\n this._maxRank = rank;\n }\n this._defines[rank] = new Array();\n }\n this._defines[rank].push(define);\n };\n /**\n * Sets the mesh to use CPU skinning when needing to fallback.\n * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)\n * @param mesh The mesh to use the fallbacks.\n */\n EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {\n this._mesh = mesh;\n if (rank < this._currentRank) {\n this._currentRank = rank;\n }\n if (rank > this._maxRank) {\n this._maxRank = rank;\n }\n };\n Object.defineProperty(EffectFallbacks.prototype, \"isMoreFallbacks\", {\n /**\n * Checks to see if more fallbacks are still availible.\n */\n get: function () {\n return this._currentRank <= this._maxRank;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Removes the defines that shoould be removed when falling back.\n * @param currentDefines defines the current define statements for the shader.\n * @param effect defines the current effect we try to compile\n * @returns The resulting defines with defines of the current rank removed.\n */\n EffectFallbacks.prototype.reduce = function (currentDefines, effect) {\n // First we try to switch to CPU skinning\n if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {\n this._mesh.computeBonesUsingShaders = false;\n currentDefines = currentDefines.replace(\"#define NUM_BONE_INFLUENCERS \" + this._mesh.numBoneInfluencers, \"#define NUM_BONE_INFLUENCERS 0\");\n effect._bonesComputationForcedToCPU = true;\n var scene = this._mesh.getScene();\n for (var index = 0; index < scene.meshes.length; index++) {\n var otherMesh = scene.meshes[index];\n if (!otherMesh.material) {\n continue;\n }\n if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {\n continue;\n }\n if (otherMesh.material.getEffect() === effect) {\n otherMesh.computeBonesUsingShaders = false;\n }\n else if (otherMesh.subMeshes) {\n for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n var subMeshEffect = subMesh.effect;\n if (subMeshEffect === effect) {\n otherMesh.computeBonesUsingShaders = false;\n break;\n }\n }\n }\n }\n }\n else {\n var currentFallbacks = this._defines[this._currentRank];\n if (currentFallbacks) {\n for (var index = 0; index < currentFallbacks.length; index++) {\n currentDefines = currentDefines.replace(\"#define \" + currentFallbacks[index], \"\");\n }\n }\n this._currentRank++;\n }\n return currentDefines;\n };\n return EffectFallbacks;\n }());\n BABYLON.EffectFallbacks = EffectFallbacks;\n /**\n * Options to be used when creating an effect.\n */\n var EffectCreationOptions = /** @class */ (function () {\n function EffectCreationOptions() {\n }\n return EffectCreationOptions;\n }());\n BABYLON.EffectCreationOptions = EffectCreationOptions;\n /**\n * Effect containing vertex and fragment shader that can be executed on an object.\n */\n var Effect = /** @class */ (function () {\n /**\n * Instantiates an effect.\n * An effect can be used to create/manage/execute vertex and fragment shaders.\n * @param baseName Name of the effect.\n * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.\n * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.\n * @param samplers List of sampler variables that will be passed to the shader.\n * @param engine Engine to be used to render the effect\n * @param defines Define statements to be added to the shader.\n * @param fallbacks Possible fallbacks for this effect to improve performance when needed.\n * @param onCompiled Callback that will be called when the shader is compiled.\n * @param onError Callback that will be called if an error occurs during shader compilation.\n * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})\n */\n function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {\n if (samplers === void 0) { samplers = null; }\n if (defines === void 0) { defines = null; }\n if (fallbacks === void 0) { fallbacks = null; }\n if (onCompiled === void 0) { onCompiled = null; }\n if (onError === void 0) { onError = null; }\n var _this = this;\n /**\n * Unique ID of the effect.\n */\n this.uniqueId = 0;\n /**\n * Observable that will be called when the shader is compiled.\n */\n this.onCompileObservable = new BABYLON.Observable();\n /**\n * Observable that will be called if an error occurs during shader compilation.\n */\n this.onErrorObservable = new BABYLON.Observable();\n /**\n * Observable that will be called when effect is bound.\n */\n this.onBindObservable = new BABYLON.Observable();\n /** @hidden */\n this._bonesComputationForcedToCPU = false;\n this._uniformBuffersNames = {};\n this._isReady = false;\n this._compilationError = \"\";\n this.name = baseName;\n if (attributesNamesOrOptions.attributes) {\n var options = attributesNamesOrOptions;\n this._engine = uniformsNamesOrEngine;\n this._attributesNames = options.attributes;\n this._uniformsNames = options.uniformsNames.concat(options.samplers);\n this._samplers = options.samplers.slice();\n this.defines = options.defines;\n this.onError = options.onError;\n this.onCompiled = options.onCompiled;\n this._fallbacks = options.fallbacks;\n this._indexParameters = options.indexParameters;\n this._transformFeedbackVaryings = options.transformFeedbackVaryings;\n if (options.uniformBuffersNames) {\n for (var i = 0; i < options.uniformBuffersNames.length; i++) {\n this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;\n }\n }\n }\n else {\n this._engine = engine;\n this.defines = defines;\n this._uniformsNames = uniformsNamesOrEngine.concat(samplers);\n this._samplers = samplers ? samplers.slice() : [];\n this._attributesNames = attributesNamesOrOptions;\n this.onError = onError;\n this.onCompiled = onCompiled;\n this._indexParameters = indexParameters;\n this._fallbacks = fallbacks;\n }\n this.uniqueId = Effect._uniqueIdSeed++;\n var vertexSource;\n var fragmentSource;\n if (baseName.vertexElement) {\n vertexSource = document.getElementById(baseName.vertexElement);\n if (!vertexSource) {\n vertexSource = baseName.vertexElement;\n }\n }\n else {\n vertexSource = baseName.vertex || baseName;\n }\n if (baseName.fragmentElement) {\n fragmentSource = document.getElementById(baseName.fragmentElement);\n if (!fragmentSource) {\n fragmentSource = baseName.fragmentElement;\n }\n }\n else {\n fragmentSource = baseName.fragment || baseName;\n }\n this._loadVertexShader(vertexSource, function (vertexCode) {\n _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {\n _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {\n _this._loadFragmentShader(fragmentSource, function (fragmentCode) {\n _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {\n _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {\n if (baseName) {\n var vertex = baseName.vertexElement || baseName.vertex || baseName;\n var fragment = baseName.fragmentElement || baseName.fragment || baseName;\n _this._vertexSourceCode = \"#define SHADER_NAME vertex:\" + vertex + \"\\n\" + migratedVertexCode;\n _this._fragmentSourceCode = \"#define SHADER_NAME fragment:\" + fragment + \"\\n\" + migratedFragmentCode;\n }\n else {\n _this._vertexSourceCode = migratedVertexCode;\n _this._fragmentSourceCode = migratedFragmentCode;\n }\n _this._prepareEffect();\n });\n });\n });\n });\n });\n });\n }\n Object.defineProperty(Effect.prototype, \"key\", {\n /**\n * Unique key for this effect\n */\n get: function () {\n return this._key;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * If the effect has been compiled and prepared.\n * @returns if the effect is compiled and prepared.\n */\n Effect.prototype.isReady = function () {\n return this._isReady;\n };\n /**\n * The engine the effect was initialized with.\n * @returns the engine.\n */\n Effect.prototype.getEngine = function () {\n return this._engine;\n };\n /**\n * The compiled webGL program for the effect\n * @returns the webGL program.\n */\n Effect.prototype.getProgram = function () {\n return this._program;\n };\n /**\n * The set of names of attribute variables for the shader.\n * @returns An array of attribute names.\n */\n Effect.prototype.getAttributesNames = function () {\n return this._attributesNames;\n };\n /**\n * Returns the attribute at the given index.\n * @param index The index of the attribute.\n * @returns The location of the attribute.\n */\n Effect.prototype.getAttributeLocation = function (index) {\n return this._attributes[index];\n };\n /**\n * Returns the attribute based on the name of the variable.\n * @param name of the attribute to look up.\n * @returns the attribute location.\n */\n Effect.prototype.getAttributeLocationByName = function (name) {\n var index = this._attributesNames.indexOf(name);\n return this._attributes[index];\n };\n /**\n * The number of attributes.\n * @returns the numnber of attributes.\n */\n Effect.prototype.getAttributesCount = function () {\n return this._attributes.length;\n };\n /**\n * Gets the index of a uniform variable.\n * @param uniformName of the uniform to look up.\n * @returns the index.\n */\n Effect.prototype.getUniformIndex = function (uniformName) {\n return this._uniformsNames.indexOf(uniformName);\n };\n /**\n * Returns the attribute based on the name of the variable.\n * @param uniformName of the uniform to look up.\n * @returns the location of the uniform.\n */\n Effect.prototype.getUniform = function (uniformName) {\n return this._uniforms[this._uniformsNames.indexOf(uniformName)];\n };\n /**\n * Returns an array of sampler variable names\n * @returns The array of sampler variable neames.\n */\n Effect.prototype.getSamplers = function () {\n return this._samplers;\n };\n /**\n * The error from the last compilation.\n * @returns the error string.\n */\n Effect.prototype.getCompilationError = function () {\n return this._compilationError;\n };\n /**\n * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.\n * @param func The callback to be used.\n */\n Effect.prototype.executeWhenCompiled = function (func) {\n if (this.isReady()) {\n func(this);\n return;\n }\n this.onCompileObservable.add(function (effect) {\n func(effect);\n });\n };\n /** @hidden */\n Effect.prototype._loadVertexShader = function (vertex, callback) {\n if (BABYLON.Tools.IsWindowObjectExist()) {\n // DOM element ?\n if (vertex instanceof HTMLElement) {\n var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);\n callback(vertexCode);\n return;\n }\n }\n // Base64 encoded ?\n if (vertex.substr(0, 7) === \"base64:\") {\n var vertexBinary = window.atob(vertex.substr(7));\n callback(vertexBinary);\n return;\n }\n // Is in local store ?\n if (Effect.ShadersStore[vertex + \"VertexShader\"]) {\n callback(Effect.ShadersStore[vertex + \"VertexShader\"]);\n return;\n }\n var vertexShaderUrl;\n if (vertex[0] === \".\" || vertex[0] === \"/\" || vertex.indexOf(\"http\") > -1) {\n vertexShaderUrl = vertex;\n }\n else {\n vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;\n }\n // Vertex shader\n this._engine._loadFile(vertexShaderUrl + \".vertex.fx\", callback);\n };\n /** @hidden */\n Effect.prototype._loadFragmentShader = function (fragment, callback) {\n if (BABYLON.Tools.IsWindowObjectExist()) {\n // DOM element ?\n if (fragment instanceof HTMLElement) {\n var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);\n callback(fragmentCode);\n return;\n }\n }\n // Base64 encoded ?\n if (fragment.substr(0, 7) === \"base64:\") {\n var fragmentBinary = window.atob(fragment.substr(7));\n callback(fragmentBinary);\n return;\n }\n // Is in local store ?\n if (Effect.ShadersStore[fragment + \"PixelShader\"]) {\n callback(Effect.ShadersStore[fragment + \"PixelShader\"]);\n return;\n }\n if (Effect.ShadersStore[fragment + \"FragmentShader\"]) {\n callback(Effect.ShadersStore[fragment + \"FragmentShader\"]);\n return;\n }\n var fragmentShaderUrl;\n if (fragment[0] === \".\" || fragment[0] === \"/\" || fragment.indexOf(\"http\") > -1) {\n fragmentShaderUrl = fragment;\n }\n else {\n fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;\n }\n // Fragment shader\n this._engine._loadFile(fragmentShaderUrl + \".fragment.fx\", callback);\n };\n /** @hidden */\n Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {\n // Rebuild shaders source code\n var shaderVersion = (this._engine.webGLVersion > 1) ? \"#version 300 es\\n#define WEBGL2 \\n\" : \"\";\n var prefix = shaderVersion + (defines ? defines + \"\\n\" : \"\");\n vertexCode = prefix + vertexCode;\n fragmentCode = prefix + fragmentCode;\n // Number lines of shaders source code\n var i = 2;\n var regex = /\\n/gm;\n var formattedVertexCode = \"\\n1\\t\" + vertexCode.replace(regex, function () { return \"\\n\" + (i++) + \"\\t\"; });\n i = 2;\n var formattedFragmentCode = \"\\n1\\t\" + fragmentCode.replace(regex, function () { return \"\\n\" + (i++) + \"\\t\"; });\n // Dump shaders name and formatted source code\n if (this.name.vertexElement) {\n BABYLON.Tools.Error(\"Vertex shader: \" + this.name.vertexElement + formattedVertexCode);\n BABYLON.Tools.Error(\"Fragment shader: \" + this.name.fragmentElement + formattedFragmentCode);\n }\n else if (this.name.vertex) {\n BABYLON.Tools.Error(\"Vertex shader: \" + this.name.vertex + formattedVertexCode);\n BABYLON.Tools.Error(\"Fragment shader: \" + this.name.fragment + formattedFragmentCode);\n }\n else {\n BABYLON.Tools.Error(\"Vertex shader: \" + this.name + formattedVertexCode);\n BABYLON.Tools.Error(\"Fragment shader: \" + this.name + formattedFragmentCode);\n }\n };\n ;\n Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {\n var preparedSourceCode = this._processPrecision(sourceCode);\n if (this._engine.webGLVersion == 1) {\n callback(preparedSourceCode);\n return;\n }\n // Already converted\n if (preparedSourceCode.indexOf(\"#version 3\") !== -1) {\n callback(preparedSourceCode.replace(\"#version 300 es\", \"\"));\n return;\n }\n var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;\n // Remove extensions \n // #extension GL_OES_standard_derivatives : enable\n // #extension GL_EXT_shader_texture_lod : enable\n // #extension GL_EXT_frag_depth : enable\n // #extension GL_EXT_draw_buffers : require\n var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;\n var result = preparedSourceCode.replace(regex, \"\");\n // Migrate to GLSL v300\n result = result.replace(/varying(?![\\n\\r])\\s/g, isFragment ? \"in \" : \"out \");\n result = result.replace(/attribute[ \\t]/g, \"in \");\n result = result.replace(/[ \\t]attribute/g, \" in\");\n if (isFragment) {\n result = result.replace(/texture2DLodEXT\\s*\\(/g, \"textureLod(\");\n result = result.replace(/textureCubeLodEXT\\s*\\(/g, \"textureLod(\");\n result = result.replace(/texture2D\\s*\\(/g, \"texture(\");\n result = result.replace(/textureCube\\s*\\(/g, \"texture(\");\n result = result.replace(/gl_FragDepthEXT/g, \"gl_FragDepth\");\n result = result.replace(/gl_FragColor/g, \"glFragColor\");\n result = result.replace(/gl_FragData/g, \"glFragData\");\n result = result.replace(/void\\s+?main\\s*\\(/g, (hasDrawBuffersExtension ? \"\" : \"out vec4 glFragColor;\\n\") + \"void main(\");\n }\n callback(result);\n };\n Effect.prototype._processIncludes = function (sourceCode, callback) {\n var _this = this;\n var regex = /#include<(.+)>(\\((.*)\\))*(\\[(.*)\\])*/g;\n var match = regex.exec(sourceCode);\n var returnValue = new String(sourceCode);\n while (match != null) {\n var includeFile = match[1];\n // Uniform declaration\n if (includeFile.indexOf(\"__decl__\") !== -1) {\n includeFile = includeFile.replace(/__decl__/, \"\");\n if (this._engine.supportsUniformBuffers) {\n includeFile = includeFile.replace(/Vertex/, \"Ubo\");\n includeFile = includeFile.replace(/Fragment/, \"Ubo\");\n }\n includeFile = includeFile + \"Declaration\";\n }\n if (Effect.IncludesShadersStore[includeFile]) {\n // Substitution\n var includeContent = Effect.IncludesShadersStore[includeFile];\n if (match[2]) {\n var splits = match[3].split(\",\");\n for (var index = 0; index < splits.length; index += 2) {\n var source = new RegExp(splits[index], \"g\");\n var dest = splits[index + 1];\n includeContent = includeContent.replace(source, dest);\n }\n }\n if (match[4]) {\n var indexString = match[5];\n if (indexString.indexOf(\"..\") !== -1) {\n var indexSplits = indexString.split(\"..\");\n var minIndex = parseInt(indexSplits[0]);\n var maxIndex = parseInt(indexSplits[1]);\n var sourceIncludeContent = includeContent.slice(0);\n includeContent = \"\";\n if (isNaN(maxIndex)) {\n maxIndex = this._indexParameters[indexSplits[1]];\n }\n for (var i = minIndex; i < maxIndex; i++) {\n if (!this._engine.supportsUniformBuffers) {\n // Ubo replacement\n sourceIncludeContent = sourceIncludeContent.replace(/light\\{X\\}.(\\w*)/g, function (str, p1) {\n return p1 + \"{X}\";\n });\n }\n includeContent += sourceIncludeContent.replace(/\\{X\\}/g, i.toString()) + \"\\n\";\n }\n }\n else {\n if (!this._engine.supportsUniformBuffers) {\n // Ubo replacement\n includeContent = includeContent.replace(/light\\{X\\}.(\\w*)/g, function (str, p1) {\n return p1 + \"{X}\";\n });\n }\n includeContent = includeContent.replace(/\\{X\\}/g, indexString);\n }\n }\n // Replace\n returnValue = returnValue.replace(match[0], includeContent);\n }\n else {\n var includeShaderUrl = BABYLON.Engine.ShadersRepository + \"ShadersInclude/\" + includeFile + \".fx\";\n this._engine._loadFile(includeShaderUrl, function (fileContent) {\n Effect.IncludesShadersStore[includeFile] = fileContent;\n _this._processIncludes(returnValue, callback);\n });\n return;\n }\n match = regex.exec(sourceCode);\n }\n callback(returnValue);\n };\n Effect.prototype._processPrecision = function (source) {\n if (source.indexOf(\"precision highp float\") === -1) {\n if (!this._engine.getCaps().highPrecisionShaderSupported) {\n source = \"precision mediump float;\\n\" + source;\n }\n else {\n source = \"precision highp float;\\n\" + source;\n }\n }\n else {\n if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump\n source = source.replace(\"precision highp float\", \"precision mediump float\");\n }\n }\n return source;\n };\n /**\n * Recompiles the webGL program\n * @param vertexSourceCode The source code for the vertex shader.\n * @param fragmentSourceCode The source code for the fragment shader.\n * @param onCompiled Callback called when completed.\n * @param onError Callback called on error.\n */\n Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {\n var _this = this;\n this._isReady = false;\n this._vertexSourceCodeOverride = vertexSourceCode;\n this._fragmentSourceCodeOverride = fragmentSourceCode;\n this.onError = function (effect, error) {\n if (onError) {\n onError(error);\n }\n };\n this.onCompiled = function () {\n var scenes = _this.getEngine().scenes;\n for (var i = 0; i < scenes.length; i++) {\n scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n }\n if (onCompiled) {\n onCompiled(_this._program);\n }\n };\n this._fallbacks = null;\n this._prepareEffect();\n };\n /**\n * Gets the uniform locations of the the specified variable names\n * @param names THe names of the variables to lookup.\n * @returns Array of locations in the same order as variable names.\n */\n Effect.prototype.getSpecificUniformLocations = function (names) {\n var engine = this._engine;\n return engine.getUniforms(this._program, names);\n };\n /**\n * Prepares the effect\n */\n Effect.prototype._prepareEffect = function () {\n var attributesNames = this._attributesNames;\n var defines = this.defines;\n var fallbacks = this._fallbacks;\n this._valueCache = {};\n var previousProgram = this._program;\n try {\n var engine = this._engine;\n if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {\n this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);\n }\n else {\n this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);\n }\n this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);\n if (engine.supportsUniformBuffers) {\n for (var name in this._uniformBuffersNames) {\n this.bindUniformBlock(name, this._uniformBuffersNames[name]);\n }\n }\n this._uniforms = engine.getUniforms(this._program, this._uniformsNames);\n this._attributes = engine.getAttributes(this._program, attributesNames);\n var index;\n for (index = 0; index < this._samplers.length; index++) {\n var sampler = this.getUniform(this._samplers[index]);\n if (sampler == null) {\n this._samplers.splice(index, 1);\n index--;\n }\n }\n engine.bindSamplers(this);\n this._compilationError = \"\";\n this._isReady = true;\n if (this.onCompiled) {\n this.onCompiled(this);\n }\n this.onCompileObservable.notifyObservers(this);\n this.onCompileObservable.clear();\n // Unbind mesh reference in fallbacks\n if (this._fallbacks) {\n this._fallbacks.unBindMesh();\n }\n if (previousProgram) {\n this.getEngine()._deleteProgram(previousProgram);\n }\n }\n catch (e) {\n this._compilationError = e.message;\n // Let's go through fallbacks then\n BABYLON.Tools.Error(\"Unable to compile effect:\");\n BABYLON.Tools.Error(\"Uniforms: \" + this._uniformsNames.map(function (uniform) {\n return \" \" + uniform;\n }));\n BABYLON.Tools.Error(\"Attributes: \" + attributesNames.map(function (attribute) {\n return \" \" + attribute;\n }));\n BABYLON.Tools.Error(\"Error: \" + this._compilationError);\n if (previousProgram) {\n this._program = previousProgram;\n this._isReady = true;\n if (this.onError) {\n this.onError(this, this._compilationError);\n }\n this.onErrorObservable.notifyObservers(this);\n }\n if (fallbacks && fallbacks.isMoreFallbacks) {\n BABYLON.Tools.Error(\"Trying next fallback.\");\n this.defines = fallbacks.reduce(this.defines, this);\n this._prepareEffect();\n }\n else { // Sorry we did everything we can\n if (this.onError) {\n this.onError(this, this._compilationError);\n }\n this.onErrorObservable.notifyObservers(this);\n this.onErrorObservable.clear();\n // Unbind mesh reference in fallbacks\n if (this._fallbacks) {\n this._fallbacks.unBindMesh();\n }\n }\n }\n };\n Object.defineProperty(Effect.prototype, \"isSupported\", {\n /**\n * Checks if the effect is supported. (Must be called after compilation)\n */\n get: function () {\n return this._compilationError === \"\";\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Binds a texture to the engine to be used as output of the shader.\n * @param channel Name of the output variable.\n * @param texture Texture to bind.\n */\n Effect.prototype._bindTexture = function (channel, texture) {\n this._engine._bindTexture(this._samplers.indexOf(channel), texture);\n };\n /**\n * Sets a texture on the engine to be used in the shader.\n * @param channel Name of the sampler variable.\n * @param texture Texture to set.\n */\n Effect.prototype.setTexture = function (channel, texture) {\n this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);\n };\n /**\n * Sets a depth stencil texture from a render target on the engine to be used in the shader.\n * @param channel Name of the sampler variable.\n * @param texture Texture to set.\n */\n Effect.prototype.setDepthStencilTexture = function (channel, texture) {\n this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);\n };\n /**\n * Sets an array of textures on the engine to be used in the shader.\n * @param channel Name of the variable.\n * @param textures Textures to set.\n */\n Effect.prototype.setTextureArray = function (channel, textures) {\n if (this._samplers.indexOf(channel + \"Ex\") === -1) {\n var initialPos = this._samplers.indexOf(channel);\n for (var index = 1; index < textures.length; index++) {\n this._samplers.splice(initialPos + index, 0, channel + \"Ex\");\n }\n }\n this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);\n };\n /**\n * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)\n * @param channel Name of the sampler variable.\n * @param postProcess Post process to get the input texture from.\n */\n Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {\n this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);\n };\n /**\n * (Warning! setTextureFromPostProcessOutput may be desired instead)\n * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)\n * @param channel Name of the sampler variable.\n * @param postProcess Post process to get the output texture from.\n */\n Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {\n this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);\n };\n /** @hidden */\n Effect.prototype._cacheMatrix = function (uniformName, matrix) {\n var cache = this._valueCache[uniformName];\n var flag = matrix.updateFlag;\n if (cache !== undefined && cache === flag) {\n return false;\n }\n this._valueCache[uniformName] = flag;\n return true;\n };\n /** @hidden */\n Effect.prototype._cacheFloat2 = function (uniformName, x, y) {\n var cache = this._valueCache[uniformName];\n if (!cache) {\n cache = [x, y];\n this._valueCache[uniformName] = cache;\n return true;\n }\n var changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n return changed;\n };\n /** @hidden */\n Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {\n var cache = this._valueCache[uniformName];\n if (!cache) {\n cache = [x, y, z];\n this._valueCache[uniformName] = cache;\n return true;\n }\n var changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n if (cache[2] !== z) {\n cache[2] = z;\n changed = true;\n }\n return changed;\n };\n /** @hidden */\n Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {\n var cache = this._valueCache[uniformName];\n if (!cache) {\n cache = [x, y, z, w];\n this._valueCache[uniformName] = cache;\n return true;\n }\n var changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n if (cache[2] !== z) {\n cache[2] = z;\n changed = true;\n }\n if (cache[3] !== w) {\n cache[3] = w;\n changed = true;\n }\n return changed;\n };\n /**\n * Binds a buffer to a uniform.\n * @param buffer Buffer to bind.\n * @param name Name of the uniform variable to bind to.\n */\n Effect.prototype.bindUniformBuffer = function (buffer, name) {\n var bufferName = this._uniformBuffersNames[name];\n if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {\n return;\n }\n Effect._baseCache[bufferName] = buffer;\n this._engine.bindUniformBufferBase(buffer, bufferName);\n };\n /**\n * Binds block to a uniform.\n * @param blockName Name of the block to bind.\n * @param index Index to bind.\n */\n Effect.prototype.bindUniformBlock = function (blockName, index) {\n this._engine.bindUniformBlock(this._program, blockName, index);\n };\n /**\n * Sets an interger value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n * @returns this effect.\n */\n Effect.prototype.setInt = function (uniformName, value) {\n var cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value)\n return this;\n this._valueCache[uniformName] = value;\n this._engine.setInt(this.getUniform(uniformName), value);\n return this;\n };\n /**\n * Sets an int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setIntArray = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setIntArray2 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray2(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setIntArray3 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray3(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setIntArray4 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray4(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an float array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setFloatArray = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setFloatArray2 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray2(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setFloatArray3 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray3(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setFloatArray4 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray4(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setArray = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setArray2 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray2(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setArray3 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray3(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setArray4 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray4(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets matrices on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrices matrices to be set.\n * @returns this effect.\n */\n Effect.prototype.setMatrices = function (uniformName, matrices) {\n if (!matrices) {\n return this;\n }\n this._valueCache[uniformName] = null;\n this._engine.setMatrices(this.getUniform(uniformName), matrices);\n return this;\n };\n /**\n * Sets matrix on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n * @returns this effect.\n */\n Effect.prototype.setMatrix = function (uniformName, matrix) {\n if (this._cacheMatrix(uniformName, matrix)) {\n this._engine.setMatrix(this.getUniform(uniformName), matrix);\n }\n return this;\n };\n /**\n * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n * @returns this effect.\n */\n Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {\n this._valueCache[uniformName] = null;\n this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);\n return this;\n };\n /**\n * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n * @returns this effect.\n */\n Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {\n this._valueCache[uniformName] = null;\n this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);\n return this;\n };\n /**\n * Sets a float on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value value to be set.\n * @returns this effect.\n */\n Effect.prototype.setFloat = function (uniformName, value) {\n var cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value)\n return this;\n this._valueCache[uniformName] = value;\n this._engine.setFloat(this.getUniform(uniformName), value);\n return this;\n };\n /**\n * Sets a boolean on a uniform variable.\n * @param uniformName Name of the variable.\n * @param bool value to be set.\n * @returns this effect.\n */\n Effect.prototype.setBool = function (uniformName, bool) {\n var cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === bool)\n return this;\n this._valueCache[uniformName] = bool;\n this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);\n return this;\n };\n /**\n * Sets a Vector2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector2 vector2 to be set.\n * @returns this effect.\n */\n Effect.prototype.setVector2 = function (uniformName, vector2) {\n if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {\n this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);\n }\n return this;\n };\n /**\n * Sets a float2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float2.\n * @param y Second float in float2.\n * @returns this effect.\n */\n Effect.prototype.setFloat2 = function (uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n this._engine.setFloat2(this.getUniform(uniformName), x, y);\n }\n return this;\n };\n /**\n * Sets a Vector3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector3 Value to be set.\n * @returns this effect.\n */\n Effect.prototype.setVector3 = function (uniformName, vector3) {\n if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {\n this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);\n }\n return this;\n };\n /**\n * Sets a float3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float3.\n * @param y Second float in float3.\n * @param z Third float in float3.\n * @returns this effect.\n */\n Effect.prototype.setFloat3 = function (uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n this._engine.setFloat3(this.getUniform(uniformName), x, y, z);\n }\n return this;\n };\n /**\n * Sets a Vector4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector4 Value to be set.\n * @returns this effect.\n */\n Effect.prototype.setVector4 = function (uniformName, vector4) {\n if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {\n this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);\n }\n return this;\n };\n /**\n * Sets a float4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float4.\n * @param y Second float in float4.\n * @param z Third float in float4.\n * @param w Fourth float in float4.\n * @returns this effect.\n */\n Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);\n }\n return this;\n };\n /**\n * Sets a Color3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @returns this effect.\n */\n Effect.prototype.setColor3 = function (uniformName, color3) {\n if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {\n this._engine.setColor3(this.getUniform(uniformName), color3);\n }\n return this;\n };\n /**\n * Sets a Color4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @param alpha Alpha value to be set.\n * @returns this effect.\n */\n Effect.prototype.setColor4 = function (uniformName, color3, alpha) {\n if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {\n this._engine.setColor4(this.getUniform(uniformName), color3, alpha);\n }\n return this;\n };\n /**\n * Sets a Color4 on a uniform variable\n * @param uniformName defines the name of the variable\n * @param color4 defines the value to be set\n * @returns this effect.\n */\n Effect.prototype.setDirectColor4 = function (uniformName, color4) {\n if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {\n this._engine.setDirectColor4(this.getUniform(uniformName), color4);\n }\n return this;\n };\n /**\n * This function will add a new shader to the shader store\n * @param name the name of the shader\n * @param pixelShader optional pixel shader content\n * @param vertexShader optional vertex shader content\n */\n Effect.RegisterShader = function (name, pixelShader, vertexShader) {\n if (pixelShader) {\n Effect.ShadersStore[name + \"PixelShader\"] = pixelShader;\n }\n if (vertexShader) {\n Effect.ShadersStore[name + \"VertexShader\"] = vertexShader;\n }\n };\n /**\n * Resets the cache of effects.\n */\n Effect.ResetCache = function () {\n Effect._baseCache = {};\n };\n Effect._uniqueIdSeed = 0;\n Effect._baseCache = {};\n /**\n * Store of each shader (The can be looked up using effect.key)\n */\n Effect.ShadersStore = {};\n /**\n * Store of each included file for a shader (The can be looked up using effect.key)\n */\n Effect.IncludesShadersStore = {};\n return Effect;\n }());\n BABYLON.Effect = Effect;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.effect.js.map\n\n\n\n//# sourceMappingURL=babylon.types.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var KeyboardEventTypes = /** @class */ (function () {\n function KeyboardEventTypes() {\n }\n Object.defineProperty(KeyboardEventTypes, \"KEYDOWN\", {\n get: function () {\n return KeyboardEventTypes._KEYDOWN;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(KeyboardEventTypes, \"KEYUP\", {\n get: function () {\n return KeyboardEventTypes._KEYUP;\n },\n enumerable: true,\n configurable: true\n });\n KeyboardEventTypes._KEYDOWN = 0x01;\n KeyboardEventTypes._KEYUP = 0x02;\n return KeyboardEventTypes;\n }());\n BABYLON.KeyboardEventTypes = KeyboardEventTypes;\n var KeyboardInfo = /** @class */ (function () {\n function KeyboardInfo(type, event) {\n this.type = type;\n this.event = event;\n }\n return KeyboardInfo;\n }());\n BABYLON.KeyboardInfo = KeyboardInfo;\n /**\n * This class is used to store keyboard related info for the onPreKeyboardObservable event.\n * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable\n */\n var KeyboardInfoPre = /** @class */ (function (_super) {\n __extends(KeyboardInfoPre, _super);\n function KeyboardInfoPre(type, event) {\n var _this = _super.call(this, type, event) || this;\n _this.skipOnPointerObservable = false;\n return _this;\n }\n return KeyboardInfoPre;\n }(KeyboardInfo));\n BABYLON.KeyboardInfoPre = KeyboardInfoPre;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.keyboardEvents.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var PointerEventTypes = /** @class */ (function () {\n function PointerEventTypes() {\n }\n Object.defineProperty(PointerEventTypes, \"POINTERDOWN\", {\n get: function () {\n return PointerEventTypes._POINTERDOWN;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointerEventTypes, \"POINTERUP\", {\n get: function () {\n return PointerEventTypes._POINTERUP;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointerEventTypes, \"POINTERMOVE\", {\n get: function () {\n return PointerEventTypes._POINTERMOVE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointerEventTypes, \"POINTERWHEEL\", {\n get: function () {\n return PointerEventTypes._POINTERWHEEL;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointerEventTypes, \"POINTERPICK\", {\n get: function () {\n return PointerEventTypes._POINTERPICK;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointerEventTypes, \"POINTERTAP\", {\n get: function () {\n return PointerEventTypes._POINTERTAP;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointerEventTypes, \"POINTERDOUBLETAP\", {\n get: function () {\n return PointerEventTypes._POINTERDOUBLETAP;\n },\n enumerable: true,\n configurable: true\n });\n PointerEventTypes._POINTERDOWN = 0x01;\n PointerEventTypes._POINTERUP = 0x02;\n PointerEventTypes._POINTERMOVE = 0x04;\n PointerEventTypes._POINTERWHEEL = 0x08;\n PointerEventTypes._POINTERPICK = 0x10;\n PointerEventTypes._POINTERTAP = 0x20;\n PointerEventTypes._POINTERDOUBLETAP = 0x40;\n return PointerEventTypes;\n }());\n BABYLON.PointerEventTypes = PointerEventTypes;\n var PointerInfoBase = /** @class */ (function () {\n function PointerInfoBase(type, event) {\n this.type = type;\n this.event = event;\n }\n return PointerInfoBase;\n }());\n BABYLON.PointerInfoBase = PointerInfoBase;\n /**\n * This class is used to store pointer related info for the onPrePointerObservable event.\n * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable\n */\n var PointerInfoPre = /** @class */ (function (_super) {\n __extends(PointerInfoPre, _super);\n function PointerInfoPre(type, event, localX, localY) {\n var _this = _super.call(this, type, event) || this;\n /**\n * Ray from a pointer if availible (eg. 6dof controller)\n */\n _this.ray = null;\n _this.skipOnPointerObservable = false;\n _this.localPosition = new BABYLON.Vector2(localX, localY);\n return _this;\n }\n return PointerInfoPre;\n }(PointerInfoBase));\n BABYLON.PointerInfoPre = PointerInfoPre;\n /**\n * This type contains all the data related to a pointer event in Babylon.js.\n * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.\n */\n var PointerInfo = /** @class */ (function (_super) {\n __extends(PointerInfo, _super);\n function PointerInfo(type, event, pickInfo) {\n var _this = _super.call(this, type, event) || this;\n _this.pickInfo = pickInfo;\n return _this;\n }\n return PointerInfo;\n }(PointerInfoBase));\n BABYLON.PointerInfo = PointerInfo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pointerEvents.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.ToGammaSpace = 1 / 2.2;\n BABYLON.ToLinearSpace = 2.2;\n BABYLON.Epsilon = 0.001;\n /**\n * Class used to hold a RBG color\n */\n var Color3 = /** @class */ (function () {\n /**\n * Creates a new Color3 object from red, green, blue values, all between 0 and 1\n * @param r defines the red component (between 0 and 1, default is 0)\n * @param g defines the green component (between 0 and 1, default is 0)\n * @param b defines the blue component (between 0 and 1, default is 0)\n */\n function Color3(\n /**\n * Defines the red component (between 0 and 1, default is 0)\n */\n r, \n /**\n * Defines the green component (between 0 and 1, default is 0)\n */\n g, \n /**\n * Defines the blue component (between 0 and 1, default is 0)\n */\n b) {\n if (r === void 0) { r = 0; }\n if (g === void 0) { g = 0; }\n if (b === void 0) { b = 0; }\n this.r = r;\n this.g = g;\n this.b = b;\n }\n /**\n * Creates a string with the Color3 current values\n * @returns the string representation of the Color3 object\n */\n Color3.prototype.toString = function () {\n return \"{R: \" + this.r + \" G:\" + this.g + \" B:\" + this.b + \"}\";\n };\n /**\n * Returns the string \"Color3\"\n * @returns \"Color3\"\n */\n Color3.prototype.getClassName = function () {\n return \"Color3\";\n };\n /**\n * Compute the Color3 hash code\n * @returns an unique number that can be used to hash Color3 objects\n */\n Color3.prototype.getHashCode = function () {\n var hash = this.r || 0;\n hash = (hash * 397) ^ (this.g || 0);\n hash = (hash * 397) ^ (this.b || 0);\n return hash;\n };\n // Operators\n /**\n * Stores in the given array from the given starting index the red, green, blue values as successive elements\n * @param array defines the array where to store the r,g,b components\n * @param index defines an optional index in the target array to define where to start storing values\n * @returns the current Color3 object\n */\n Color3.prototype.toArray = function (array, index) {\n if (index === undefined) {\n index = 0;\n }\n array[index] = this.r;\n array[index + 1] = this.g;\n array[index + 2] = this.b;\n return this;\n };\n /**\n * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha\n * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)\n * @returns a new {BABYLON.Color4} object\n */\n Color3.prototype.toColor4 = function (alpha) {\n if (alpha === void 0) { alpha = 1; }\n return new Color4(this.r, this.g, this.b, alpha);\n };\n /**\n * Returns a new array populated with 3 numeric elements : red, green and blue values\n * @returns the new array\n */\n Color3.prototype.asArray = function () {\n var result = new Array();\n this.toArray(result, 0);\n return result;\n };\n /**\n * Returns the luminance value\n * @returns a float value\n */\n Color3.prototype.toLuminance = function () {\n return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;\n };\n /**\n * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object\n * @param otherColor defines the second operand\n * @returns the new Color3 object\n */\n Color3.prototype.multiply = function (otherColor) {\n return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);\n };\n /**\n * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object \"result\"\n * @param otherColor defines the second operand\n * @param result defines the Color3 object where to store the result\n * @returns the current Color3\n */\n Color3.prototype.multiplyToRef = function (otherColor, result) {\n result.r = this.r * otherColor.r;\n result.g = this.g * otherColor.g;\n result.b = this.b * otherColor.b;\n return this;\n };\n /**\n * Determines equality between Color3 objects\n * @param otherColor defines the second operand\n * @returns true if the rgb values are equal to the given ones\n */\n Color3.prototype.equals = function (otherColor) {\n return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;\n };\n /**\n * Determines equality between the current Color3 object and a set of r,b,g values\n * @param r defines the red component to check\n * @param g defines the green component to check\n * @param b defines the blue component to check\n * @returns true if the rgb values are equal to the given ones\n */\n Color3.prototype.equalsFloats = function (r, g, b) {\n return this.r === r && this.g === g && this.b === b;\n };\n /**\n * Multiplies in place each rgb value by scale\n * @param scale defines the scaling factor\n * @returns the updated Color3\n */\n Color3.prototype.scale = function (scale) {\n return new Color3(this.r * scale, this.g * scale, this.b * scale);\n };\n /**\n * Multiplies the rgb values by scale and stores the result into \"result\"\n * @param scale defines the scaling factor\n * @param result defines the Color3 object where to store the result\n * @returns the unmodified current Color3\n */\n Color3.prototype.scaleToRef = function (scale, result) {\n result.r = this.r * scale;\n result.g = this.g * scale;\n result.b = this.b * scale;\n return this;\n };\n /**\n * Scale the current Color3 values by a factor and add the result to a given Color3\n * @param scale defines the scale factor\n * @param result defines color to store the result into\n * @returns the unmodified current Color3\n */\n Color3.prototype.scaleAndAddToRef = function (scale, result) {\n result.r += this.r * scale;\n result.g += this.g * scale;\n result.b += this.b * scale;\n return this;\n };\n /**\n * Clamps the rgb values by the min and max values and stores the result into \"result\"\n * @param min defines minimum clamping value (default is 0)\n * @param max defines maximum clamping value (default is 1)\n * @param result defines color to store the result into\n * @returns the original Color3\n */\n Color3.prototype.clampToRef = function (min, max, result) {\n if (min === void 0) { min = 0; }\n if (max === void 0) { max = 1; }\n result.r = BABYLON.Scalar.Clamp(this.r, min, max);\n result.g = BABYLON.Scalar.Clamp(this.g, min, max);\n result.b = BABYLON.Scalar.Clamp(this.b, min, max);\n return this;\n };\n /**\n * Creates a new Color3 set with the added values of the current Color3 and of the given one\n * @param otherColor defines the second operand\n * @returns the new Color3\n */\n Color3.prototype.add = function (otherColor) {\n return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);\n };\n /**\n * Stores the result of the addition of the current Color3 and given one rgb values into \"result\"\n * @param otherColor defines the second operand\n * @param result defines Color3 object to store the result into\n * @returns the unmodified current Color3\n */\n Color3.prototype.addToRef = function (otherColor, result) {\n result.r = this.r + otherColor.r;\n result.g = this.g + otherColor.g;\n result.b = this.b + otherColor.b;\n return this;\n };\n /**\n * Returns a new Color3 set with the subtracted values of the given one from the current Color3\n * @param otherColor defines the second operand\n * @returns the new Color3\n */\n Color3.prototype.subtract = function (otherColor) {\n return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);\n };\n /**\n * Stores the result of the subtraction of given one from the current Color3 rgb values into \"result\"\n * @param otherColor defines the second operand\n * @param result defines Color3 object to store the result into\n * @returns the unmodified current Color3\n */\n Color3.prototype.subtractToRef = function (otherColor, result) {\n result.r = this.r - otherColor.r;\n result.g = this.g - otherColor.g;\n result.b = this.b - otherColor.b;\n return this;\n };\n /**\n * Copy the current object\n * @returns a new Color3 copied the current one\n */\n Color3.prototype.clone = function () {\n return new Color3(this.r, this.g, this.b);\n };\n /**\n * Copies the rgb values from the source in the current Color3\n * @param source defines the source Color3 object\n * @returns the updated Color3 object\n */\n Color3.prototype.copyFrom = function (source) {\n this.r = source.r;\n this.g = source.g;\n this.b = source.b;\n return this;\n };\n /**\n * Updates the Color3 rgb values from the given floats\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @returns the current Color3 object\n */\n Color3.prototype.copyFromFloats = function (r, g, b) {\n this.r = r;\n this.g = g;\n this.b = b;\n return this;\n };\n /**\n * Updates the Color3 rgb values from the given floats\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @returns the current Color3 object\n */\n Color3.prototype.set = function (r, g, b) {\n return this.copyFromFloats(r, g, b);\n };\n /**\n * Compute the Color3 hexadecimal code as a string\n * @returns a string containing the hexadecimal representation of the Color3 object\n */\n Color3.prototype.toHexString = function () {\n var intR = (this.r * 255) | 0;\n var intG = (this.g * 255) | 0;\n var intB = (this.b * 255) | 0;\n return \"#\" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);\n };\n /**\n * Computes a new Color3 converted from the current one to linear space\n * @returns a new Color3 object\n */\n Color3.prototype.toLinearSpace = function () {\n var convertedColor = new Color3();\n this.toLinearSpaceToRef(convertedColor);\n return convertedColor;\n };\n /**\n * Converts the Color3 values to linear space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color3 object where to store the linear space version\n * @returns the unmodified Color3\n */\n Color3.prototype.toLinearSpaceToRef = function (convertedColor) {\n convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);\n convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);\n convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);\n return this;\n };\n /**\n * Computes a new Color3 converted from the current one to gamma space\n * @returns a new Color3 object\n */\n Color3.prototype.toGammaSpace = function () {\n var convertedColor = new Color3();\n this.toGammaSpaceToRef(convertedColor);\n return convertedColor;\n };\n /**\n * Converts the Color3 values to gamma space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color3 object where to store the gamma space version\n * @returns the unmodified Color3\n */\n Color3.prototype.toGammaSpaceToRef = function (convertedColor) {\n convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);\n convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);\n convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);\n return this;\n };\n // Statics\n /**\n * Creates a new Color3 from the string containing valid hexadecimal values\n * @param hex defines a string containing valid hexadecimal values\n * @returns a new Color3 object\n */\n Color3.FromHexString = function (hex) {\n if (hex.substring(0, 1) !== \"#\" || hex.length !== 7) {\n return new Color3(0, 0, 0);\n }\n var r = parseInt(hex.substring(1, 3), 16);\n var g = parseInt(hex.substring(3, 5), 16);\n var b = parseInt(hex.substring(5, 7), 16);\n return Color3.FromInts(r, g, b);\n };\n /**\n * Creates a new Vector3 from the starting index of the given array\n * @param array defines the source array\n * @param offset defines an offset in the source array\n * @returns a new Color3 object\n */\n Color3.FromArray = function (array, offset) {\n if (offset === void 0) { offset = 0; }\n return new Color3(array[offset], array[offset + 1], array[offset + 2]);\n };\n /**\n * Creates a new Color3 from integer values (< 256)\n * @param r defines the red component to read from (value between 0 and 255)\n * @param g defines the green component to read from (value between 0 and 255)\n * @param b defines the blue component to read from (value between 0 and 255)\n * @returns a new Color3 object\n */\n Color3.FromInts = function (r, g, b) {\n return new Color3(r / 255.0, g / 255.0, b / 255.0);\n };\n /**\n * Creates a new Color3 with values linearly interpolated of \"amount\" between the start Color3 and the end Color3\n * @param start defines the start Color3 value\n * @param end defines the end Color3 value\n * @param amount defines the gradient value between start and end\n * @returns a new Color3 object\n */\n Color3.Lerp = function (start, end, amount) {\n var r = start.r + ((end.r - start.r) * amount);\n var g = start.g + ((end.g - start.g) * amount);\n var b = start.b + ((end.b - start.b) * amount);\n return new Color3(r, g, b);\n };\n /**\n * Returns a Color3 value containing a red color\n * @returns a new Color3 object\n */\n Color3.Red = function () { return new Color3(1, 0, 0); };\n /**\n * Returns a Color3 value containing a green color\n * @returns a new Color3 object\n */\n Color3.Green = function () { return new Color3(0, 1, 0); };\n /**\n * Returns a Color3 value containing a blue color\n * @returns a new Color3 object\n */\n Color3.Blue = function () { return new Color3(0, 0, 1); };\n /**\n * Returns a Color3 value containing a black color\n * @returns a new Color3 object\n */\n Color3.Black = function () { return new Color3(0, 0, 0); };\n /**\n * Returns a Color3 value containing a white color\n * @returns a new Color3 object\n */\n Color3.White = function () { return new Color3(1, 1, 1); };\n /**\n * Returns a Color3 value containing a purple color\n * @returns a new Color3 object\n */\n Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };\n /**\n * Returns a Color3 value containing a magenta color\n * @returns a new Color3 object\n */\n Color3.Magenta = function () { return new Color3(1, 0, 1); };\n /**\n * Returns a Color3 value containing a yellow color\n * @returns a new Color3 object\n */\n Color3.Yellow = function () { return new Color3(1, 1, 0); };\n /**\n * Returns a Color3 value containing a gray color\n * @returns a new Color3 object\n */\n Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };\n /**\n * Returns a Color3 value containing a teal color\n * @returns a new Color3 object\n */\n Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };\n /**\n * Returns a Color3 value containing a random color\n * @returns a new Color3 object\n */\n Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };\n return Color3;\n }());\n BABYLON.Color3 = Color3;\n /**\n * Class used to hold a RBGA color\n */\n var Color4 = /** @class */ (function () {\n /**\n * Creates a new Color4 object from red, green, blue values, all between 0 and 1\n * @param r defines the red component (between 0 and 1, default is 0)\n * @param g defines the green component (between 0 and 1, default is 0)\n * @param b defines the blue component (between 0 and 1, default is 0)\n * @param a defines the alpha component (between 0 and 1, default is 1)\n */\n function Color4(\n /**\n * Defines the red component (between 0 and 1, default is 0)\n */\n r, \n /**\n * Defines the green component (between 0 and 1, default is 0)\n */\n g, \n /**\n * Defines the blue component (between 0 and 1, default is 0)\n */\n b, \n /**\n * Defines the alpha component (between 0 and 1, default is 1)\n */\n a) {\n if (r === void 0) { r = 0; }\n if (g === void 0) { g = 0; }\n if (b === void 0) { b = 0; }\n if (a === void 0) { a = 1; }\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n }\n // Operators\n /**\n * Adds in place the given Color4 values to the current Color4 object\n * @param right defines the second operand\n * @returns the current updated Color4 object\n */\n Color4.prototype.addInPlace = function (right) {\n this.r += right.r;\n this.g += right.g;\n this.b += right.b;\n this.a += right.a;\n return this;\n };\n /**\n * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values\n * @returns the new array\n */\n Color4.prototype.asArray = function () {\n var result = new Array();\n this.toArray(result, 0);\n return result;\n };\n /**\n * Stores from the starting index in the given array the Color4 successive values\n * @param array defines the array where to store the r,g,b components\n * @param index defines an optional index in the target array to define where to start storing values\n * @returns the current Color4 object\n */\n Color4.prototype.toArray = function (array, index) {\n if (index === undefined) {\n index = 0;\n }\n array[index] = this.r;\n array[index + 1] = this.g;\n array[index + 2] = this.b;\n array[index + 3] = this.a;\n return this;\n };\n /**\n * Creates a new Color4 set with the added values of the current Color4 and of the given one\n * @param right defines the second operand\n * @returns a new Color4 object\n */\n Color4.prototype.add = function (right) {\n return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);\n };\n /**\n * Creates a new Color4 set with the subtracted values of the given one from the current Color4\n * @param right defines the second operand\n * @returns a new Color4 object\n */\n Color4.prototype.subtract = function (right) {\n return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);\n };\n /**\n * Subtracts the given ones from the current Color4 values and stores the results in \"result\"\n * @param right defines the second operand\n * @param result defines the Color4 object where to store the result\n * @returns the current Color4 object\n */\n Color4.prototype.subtractToRef = function (right, result) {\n result.r = this.r - right.r;\n result.g = this.g - right.g;\n result.b = this.b - right.b;\n result.a = this.a - right.a;\n return this;\n };\n /**\n * Creates a new Color4 with the current Color4 values multiplied by scale\n * @param scale defines the scaling factor to apply\n * @returns a new Color4 object\n */\n Color4.prototype.scale = function (scale) {\n return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);\n };\n /**\n * Multiplies the current Color4 values by scale and stores the result in \"result\"\n * @param scale defines the scaling factor to apply\n * @param result defines the Color4 object where to store the result\n * @returns the current unmodified Color4\n */\n Color4.prototype.scaleToRef = function (scale, result) {\n result.r = this.r * scale;\n result.g = this.g * scale;\n result.b = this.b * scale;\n result.a = this.a * scale;\n return this;\n };\n /**\n * Scale the current Color4 values by a factor and add the result to a given Color4\n * @param scale defines the scale factor\n * @param result defines the Color4 object where to store the result\n * @returns the unmodified current Color4\n */\n Color4.prototype.scaleAndAddToRef = function (scale, result) {\n result.r += this.r * scale;\n result.g += this.g * scale;\n result.b += this.b * scale;\n result.a += this.a * scale;\n return this;\n };\n /**\n * Clamps the rgb values by the min and max values and stores the result into \"result\"\n * @param min defines minimum clamping value (default is 0)\n * @param max defines maximum clamping value (default is 1)\n * @param result defines color to store the result into.\n * @returns the cuurent Color4\n */\n Color4.prototype.clampToRef = function (min, max, result) {\n if (min === void 0) { min = 0; }\n if (max === void 0) { max = 1; }\n result.r = BABYLON.Scalar.Clamp(this.r, min, max);\n result.g = BABYLON.Scalar.Clamp(this.g, min, max);\n result.b = BABYLON.Scalar.Clamp(this.b, min, max);\n result.a = BABYLON.Scalar.Clamp(this.a, min, max);\n return this;\n };\n /**\n * Multipy an Color4 value by another and return a new Color4 object\n * @param color defines the Color4 value to multiply by\n * @returns a new Color4 object\n */\n Color4.prototype.multiply = function (color) {\n return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);\n };\n /**\n * Multipy a Color4 value by another and push the result in a reference value\n * @param color defines the Color4 value to multiply by\n * @param result defines the Color4 to fill the result in\n * @returns the result Color4\n */\n Color4.prototype.multiplyToRef = function (color, result) {\n result.r = this.r * color.r;\n result.g = this.g * color.g;\n result.b = this.b * color.b;\n result.a = this.a * color.a;\n return result;\n };\n /**\n * Creates a string with the Color4 current values\n * @returns the string representation of the Color4 object\n */\n Color4.prototype.toString = function () {\n return \"{R: \" + this.r + \" G:\" + this.g + \" B:\" + this.b + \" A:\" + this.a + \"}\";\n };\n /**\n * Returns the string \"Color4\"\n * @returns \"Color4\"\n */\n Color4.prototype.getClassName = function () {\n return \"Color4\";\n };\n /**\n * Compute the Color4 hash code\n * @returns an unique number that can be used to hash Color4 objects\n */\n Color4.prototype.getHashCode = function () {\n var hash = this.r || 0;\n hash = (hash * 397) ^ (this.g || 0);\n hash = (hash * 397) ^ (this.b || 0);\n hash = (hash * 397) ^ (this.a || 0);\n return hash;\n };\n /**\n * Creates a new Color4 copied from the current one\n * @returns a new Color4 object\n */\n Color4.prototype.clone = function () {\n return new Color4(this.r, this.g, this.b, this.a);\n };\n /**\n * Copies the given Color4 values into the current one\n * @param source defines the source Color4 object\n * @returns the current updated Color4 object\n */\n Color4.prototype.copyFrom = function (source) {\n this.r = source.r;\n this.g = source.g;\n this.b = source.b;\n this.a = source.a;\n return this;\n };\n /**\n * Copies the given float values into the current one\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @param a defines the alpha component to read from\n * @returns the current updated Color4 object\n */\n Color4.prototype.copyFromFloats = function (r, g, b, a) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n return this;\n };\n /**\n * Copies the given float values into the current one\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @param a defines the alpha component to read from\n * @returns the current updated Color4 object\n */\n Color4.prototype.set = function (r, g, b, a) {\n return this.copyFromFloats(r, g, b, a);\n };\n /**\n * Compute the Color4 hexadecimal code as a string\n * @returns a string containing the hexadecimal representation of the Color4 object\n */\n Color4.prototype.toHexString = function () {\n var intR = (this.r * 255) | 0;\n var intG = (this.g * 255) | 0;\n var intB = (this.b * 255) | 0;\n var intA = (this.a * 255) | 0;\n return \"#\" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);\n };\n /**\n * Computes a new Color4 converted from the current one to linear space\n * @returns a new Color4 object\n */\n Color4.prototype.toLinearSpace = function () {\n var convertedColor = new Color4();\n this.toLinearSpaceToRef(convertedColor);\n return convertedColor;\n };\n /**\n * Converts the Color4 values to linear space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color4 object where to store the linear space version\n * @returns the unmodified Color4\n */\n Color4.prototype.toLinearSpaceToRef = function (convertedColor) {\n convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);\n convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);\n convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);\n convertedColor.a = this.a;\n return this;\n };\n /**\n * Computes a new Color4 converted from the current one to gamma space\n * @returns a new Color4 object\n */\n Color4.prototype.toGammaSpace = function () {\n var convertedColor = new Color4();\n this.toGammaSpaceToRef(convertedColor);\n return convertedColor;\n };\n /**\n * Converts the Color4 values to gamma space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color4 object where to store the gamma space version\n * @returns the unmodified Color4\n */\n Color4.prototype.toGammaSpaceToRef = function (convertedColor) {\n convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);\n convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);\n convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);\n convertedColor.a = this.a;\n return this;\n };\n // Statics\n /**\n * Creates a new Color4 from the string containing valid hexadecimal values\n * @param hex defines a string containing valid hexadecimal values\n * @returns a new Color4 object\n */\n Color4.FromHexString = function (hex) {\n if (hex.substring(0, 1) !== \"#\" || hex.length !== 9) {\n return new Color4(0.0, 0.0, 0.0, 0.0);\n }\n var r = parseInt(hex.substring(1, 3), 16);\n var g = parseInt(hex.substring(3, 5), 16);\n var b = parseInt(hex.substring(5, 7), 16);\n var a = parseInt(hex.substring(7, 9), 16);\n return Color4.FromInts(r, g, b, a);\n };\n /**\n * Creates a new Color4 object set with the linearly interpolated values of \"amount\" between the left Color4 object and the right Color4 object\n * @param left defines the start value\n * @param right defines the end value\n * @param amount defines the gradient factor\n * @returns a new Color4 object\n */\n Color4.Lerp = function (left, right, amount) {\n var result = new Color4(0.0, 0.0, 0.0, 0.0);\n Color4.LerpToRef(left, right, amount, result);\n return result;\n };\n /**\n * Set the given \"result\" with the linearly interpolated values of \"amount\" between the left Color4 object and the right Color4 object\n * @param left defines the start value\n * @param right defines the end value\n * @param amount defines the gradient factor\n * @param result defines the Color4 object where to store data\n */\n Color4.LerpToRef = function (left, right, amount, result) {\n result.r = left.r + (right.r - left.r) * amount;\n result.g = left.g + (right.g - left.g) * amount;\n result.b = left.b + (right.b - left.b) * amount;\n result.a = left.a + (right.a - left.a) * amount;\n };\n /**\n * Creates a new Color4 from the starting index element of the given array\n * @param array defines the source array to read from\n * @param offset defines the offset in the source array\n * @returns a new Color4 object\n */\n Color4.FromArray = function (array, offset) {\n if (offset === void 0) { offset = 0; }\n return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n };\n /**\n * Creates a new Color3 from integer values (< 256)\n * @param r defines the red component to read from (value between 0 and 255)\n * @param g defines the green component to read from (value between 0 and 255)\n * @param b defines the blue component to read from (value between 0 and 255)\n * @param a defines the alpha component to read from (value between 0 and 255)\n * @returns a new Color3 object\n */\n Color4.FromInts = function (r, g, b, a) {\n return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);\n };\n /**\n * Check the content of a given array and convert it to an array containing RGBA data\n * If the original array was already containing count * 4 values then it is returned directly\n * @param colors defines the array to check\n * @param count defines the number of RGBA data to expect\n * @returns an array containing count * 4 values (RGBA)\n */\n Color4.CheckColors4 = function (colors, count) {\n // Check if color3 was used\n if (colors.length === count * 3) {\n var colors4 = [];\n for (var index = 0; index < colors.length; index += 3) {\n var newIndex = (index / 3) * 4;\n colors4[newIndex] = colors[index];\n colors4[newIndex + 1] = colors[index + 1];\n colors4[newIndex + 2] = colors[index + 2];\n colors4[newIndex + 3] = 1.0;\n }\n return colors4;\n }\n return colors;\n };\n return Color4;\n }());\n BABYLON.Color4 = Color4;\n /**\n * Class representing a vector containing 2 coordinates\n */\n var Vector2 = /** @class */ (function () {\n /**\n * Creates a new Vector2 from the given x and y coordinates\n * @param x defines the first coordinate\n * @param y defines the second coordinate\n */\n function Vector2(\n /** defines the first coordinate */\n x, \n /** defines the second coordinate */\n y) {\n if (x === void 0) { x = 0; }\n if (y === void 0) { y = 0; }\n this.x = x;\n this.y = y;\n }\n /**\n * Gets a string with the Vector2 coordinates\n * @returns a string with the Vector2 coordinates\n */\n Vector2.prototype.toString = function () {\n return \"{X: \" + this.x + \" Y:\" + this.y + \"}\";\n };\n /**\n * Gets class name\n * @returns the string \"Vector2\"\n */\n Vector2.prototype.getClassName = function () {\n return \"Vector2\";\n };\n /**\n * Gets current vector hash code\n * @returns the Vector2 hash code as a number\n */\n Vector2.prototype.getHashCode = function () {\n var hash = this.x || 0;\n hash = (hash * 397) ^ (this.y || 0);\n return hash;\n };\n // Operators\n /**\n * Sets the Vector2 coordinates in the given array or Float32Array from the given index.\n * @param array defines the source array\n * @param index defines the offset in source array\n * @returns the current Vector2\n */\n Vector2.prototype.toArray = function (array, index) {\n if (index === void 0) { index = 0; }\n array[index] = this.x;\n array[index + 1] = this.y;\n return this;\n };\n /**\n * Copy the current vector to an array\n * @returns a new array with 2 elements: the Vector2 coordinates.\n */\n Vector2.prototype.asArray = function () {\n var result = new Array();\n this.toArray(result, 0);\n return result;\n };\n /**\n * Sets the Vector2 coordinates with the given Vector2 coordinates\n * @param source defines the source Vector2\n * @returns the current updated Vector2\n */\n Vector2.prototype.copyFrom = function (source) {\n this.x = source.x;\n this.y = source.y;\n return this;\n };\n /**\n * Sets the Vector2 coordinates with the given floats\n * @param x defines the first coordinate\n * @param y defines the second coordinate\n * @returns the current updated Vector2\n */\n Vector2.prototype.copyFromFloats = function (x, y) {\n this.x = x;\n this.y = y;\n return this;\n };\n /**\n * Sets the Vector2 coordinates with the given floats\n * @param x defines the first coordinate\n * @param y defines the second coordinate\n * @returns the current updated Vector2\n */\n Vector2.prototype.set = function (x, y) {\n return this.copyFromFloats(x, y);\n };\n /**\n * Add another vector with the current one\n * @param otherVector defines the other vector\n * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates\n */\n Vector2.prototype.add = function (otherVector) {\n return new Vector2(this.x + otherVector.x, this.y + otherVector.y);\n };\n /**\n * Sets the \"result\" coordinates with the addition of the current Vector2 and the given one coordinates\n * @param otherVector defines the other vector\n * @param result defines the target vector\n * @returns the unmodified current Vector2\n */\n Vector2.prototype.addToRef = function (otherVector, result) {\n result.x = this.x + otherVector.x;\n result.y = this.y + otherVector.y;\n return this;\n };\n /**\n * Set the Vector2 coordinates by adding the given Vector2 coordinates\n * @param otherVector defines the other vector\n * @returns the current updated Vector2\n */\n Vector2.prototype.addInPlace = function (otherVector) {\n this.x += otherVector.x;\n this.y += otherVector.y;\n return this;\n };\n /**\n * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates\n * @param otherVector defines the other vector\n * @returns a new Vector2\n */\n Vector2.prototype.addVector3 = function (otherVector) {\n return new Vector2(this.x + otherVector.x, this.y + otherVector.y);\n };\n /**\n * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2\n * @param otherVector defines the other vector\n * @returns a new Vector2\n */\n Vector2.prototype.subtract = function (otherVector) {\n return new Vector2(this.x - otherVector.x, this.y - otherVector.y);\n };\n /**\n * Sets the \"result\" coordinates with the subtraction of the given one from the current Vector2 coordinates.\n * @param otherVector defines the other vector\n * @param result defines the target vector\n * @returns the unmodified current Vector2\n */\n Vector2.prototype.subtractToRef = function (otherVector, result) {\n result.x = this.x - otherVector.x;\n result.y = this.y - otherVector.y;\n return this;\n };\n /**\n * Sets the current Vector2 coordinates by subtracting from it the given one coordinates\n * @param otherVector defines the other vector\n * @returns the current updated Vector2\n */\n Vector2.prototype.subtractInPlace = function (otherVector) {\n this.x -= otherVector.x;\n this.y -= otherVector.y;\n return this;\n };\n /**\n * Multiplies in place the current Vector2 coordinates by the given ones\n * @param otherVector defines the other vector\n * @returns the current updated Vector2\n */\n Vector2.prototype.multiplyInPlace = function (otherVector) {\n this.x *= otherVector.x;\n this.y *= otherVector.y;\n return this;\n };\n /**\n * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates\n * @param otherVector defines the other vector\n * @returns a new Vector2\n */\n Vector2.prototype.multiply = function (otherVector) {\n return new Vector2(this.x * otherVector.x, this.y * otherVector.y);\n };\n /**\n * Sets \"result\" coordinates with the multiplication of the current Vector2 and the given one coordinates\n * @param otherVector defines the other vector\n * @param result defines the target vector\n * @returns the unmodified current Vector2\n */\n Vector2.prototype.multiplyToRef = function (otherVector, result) {\n result.x = this.x * otherVector.x;\n result.y = this.y * otherVector.y;\n return this;\n };\n /**\n * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats\n * @param x defines the first coordinate\n * @param y defines the second coordinate\n * @returns a new Vector2\n */\n Vector2.prototype.multiplyByFloats = function (x, y) {\n return new Vector2(this.x * x, this.y * y);\n };\n /**\n * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates\n * @param otherVector defines the other vector\n * @returns a new Vector2\n */\n Vector2.prototype.divide = function (otherVector) {\n return new Vector2(this.x / otherVector.x, this.y / otherVector.y);\n };\n /**\n * Sets the \"result\" coordinates with the Vector2 divided by the given one coordinates\n * @param otherVector defines the other vector\n * @param result defines the target vector\n * @returns the unmodified current Vector2\n */\n Vector2.prototype.divideToRef = function (otherVector, result) {\n result.x = this.x / otherVector.x;\n result.y = this.y / otherVector.y;\n return this;\n };\n /**\n * Divides the current Vector2 coordinates by the given ones\n * @param otherVector defines the other vector\n * @returns the current updated Vector2\n */\n Vector2.prototype.divideInPlace = function (otherVector) {\n return this.divideToRef(otherVector, this);\n };\n /**\n * Gets a new Vector2 with current Vector2 negated coordinates\n * @returns a new Vector2\n */\n Vector2.prototype.negate = function () {\n return new Vector2(-this.x, -this.y);\n };\n /**\n * Multiply the Vector2 coordinates by scale\n * @param scale defines the scaling factor\n * @returns the current updated Vector2\n */\n Vector2.prototype.scaleInPlace = function (scale) {\n this.x *= scale;\n this.y *= scale;\n return this;\n };\n /**\n * Returns a new Vector2 scaled by \"scale\" from the current Vector2\n * @param scale defines the scaling factor\n * @returns a new Vector2\n */\n Vector2.prototype.scale = function (scale) {\n var result = new Vector2(0, 0);\n this.scaleToRef(scale, result);\n return result;\n };\n /**\n * Scale the current Vector2 values by a factor to a given Vector2\n * @param scale defines the scale factor\n * @param result defines the Vector2 object where to store the result\n * @returns the unmodified current Vector2\n */\n Vector2.prototype.scaleToRef = function (scale, result) {\n result.x = this.x * scale;\n result.y = this.y * scale;\n return this;\n };\n /**\n * Scale the current Vector2 values by a factor and add the result to a given Vector2\n * @param scale defines the scale factor\n * @param result defines the Vector2 object where to store the result\n * @returns the unmodified current Vector2\n */\n Vector2.prototype.scaleAndAddToRef = function (scale, result) {\n result.x += this.x * scale;\n result.y += this.y * scale;\n return this;\n };\n /**\n * Gets a boolean if two vectors are equals\n * @param otherVector defines the other vector\n * @returns true if the given vector coordinates strictly equal the current Vector2 ones\n */\n Vector2.prototype.equals = function (otherVector) {\n return otherVector && this.x === otherVector.x && this.y === otherVector.y;\n };\n /**\n * Gets a boolean if two vectors are equals (using an epsilon value)\n * @param otherVector defines the other vector\n * @param epsilon defines the minimal distance to consider equality\n * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.\n */\n Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {\n if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }\n return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);\n };\n /**\n * Gets a new Vector2 from current Vector2 floored values\n * @returns a new Vector2\n */\n Vector2.prototype.floor = function () {\n return new Vector2(Math.floor(this.x), Math.floor(this.y));\n };\n /**\n * Gets a new Vector2 from current Vector2 floored values\n * @returns a new Vector2\n */\n Vector2.prototype.fract = function () {\n return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));\n };\n // Properties\n /**\n * Gets the length of the vector\n * @returns the vector length (float)\n */\n Vector2.prototype.length = function () {\n return Math.sqrt(this.x * this.x + this.y * this.y);\n };\n /**\n * Gets the vector squared length\n * @returns the vector squared length (float)\n */\n Vector2.prototype.lengthSquared = function () {\n return (this.x * this.x + this.y * this.y);\n };\n // Methods\n /**\n * Normalize the vector\n * @returns the current updated Vector2\n */\n Vector2.prototype.normalize = function () {\n var len = this.length();\n if (len === 0)\n return this;\n var num = 1.0 / len;\n this.x *= num;\n this.y *= num;\n return this;\n };\n /**\n * Gets a new Vector2 copied from the Vector2\n * @returns a new Vector2\n */\n Vector2.prototype.clone = function () {\n return new Vector2(this.x, this.y);\n };\n // Statics\n /**\n * Gets a new Vector2(0, 0)\n * @returns a new Vector2\n */\n Vector2.Zero = function () {\n return new Vector2(0, 0);\n };\n /**\n * Gets a new Vector2(1, 1)\n * @returns a new Vector2\n */\n Vector2.One = function () {\n return new Vector2(1, 1);\n };\n /**\n * Gets a new Vector2 set from the given index element of the given array\n * @param array defines the data source\n * @param offset defines the offset in the data source\n * @returns a new Vector2\n */\n Vector2.FromArray = function (array, offset) {\n if (offset === void 0) { offset = 0; }\n return new Vector2(array[offset], array[offset + 1]);\n };\n /**\n * Sets \"result\" from the given index element of the given array\n * @param array defines the data source\n * @param offset defines the offset in the data source\n * @param result defines the target vector\n */\n Vector2.FromArrayToRef = function (array, offset, result) {\n result.x = array[offset];\n result.y = array[offset + 1];\n };\n /**\n * Gets a new Vector2 located for \"amount\" (float) on the CatmullRom spline defined by the given four Vector2\n * @param value1 defines 1st point of control\n * @param value2 defines 2nd point of control\n * @param value3 defines 3rd point of control\n * @param value4 defines 4th point of control\n * @param amount defines the interpolation factor\n * @returns a new Vector2\n */\n Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {\n var squared = amount * amount;\n var cubed = amount * squared;\n var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +\n (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +\n ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));\n var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +\n (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +\n ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));\n return new Vector2(x, y);\n };\n /**\n * Returns a new Vector2 set with same the coordinates than \"value\" ones if the vector \"value\" is in the square defined by \"min\" and \"max\".\n * If a coordinate of \"value\" is lower than \"min\" coordinates, the returned Vector2 is given this \"min\" coordinate.\n * If a coordinate of \"value\" is greater than \"max\" coordinates, the returned Vector2 is given this \"max\" coordinate\n * @param value defines the value to clamp\n * @param min defines the lower limit\n * @param max defines the upper limit\n * @returns a new Vector2\n */\n Vector2.Clamp = function (value, min, max) {\n var x = value.x;\n x = (x > max.x) ? max.x : x;\n x = (x < min.x) ? min.x : x;\n var y = value.y;\n y = (y > max.y) ? max.y : y;\n y = (y < min.y) ? min.y : y;\n return new Vector2(x, y);\n };\n /**\n * Returns a new Vector2 located for \"amount\" (float) on the Hermite spline defined by the vectors \"value1\", \"value3\", \"tangent1\", \"tangent2\"\n * @param value1 defines the 1st control point\n * @param tangent1 defines the outgoing tangent\n * @param value2 defines the 2nd control point\n * @param tangent2 defines the incoming tangent\n * @param amount defines the interpolation factor\n * @returns a new Vector2\n */\n Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {\n var squared = amount * amount;\n var cubed = amount * squared;\n var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;\n var part2 = (-2.0 * cubed) + (3.0 * squared);\n var part3 = (cubed - (2.0 * squared)) + amount;\n var part4 = cubed - squared;\n var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);\n var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);\n return new Vector2(x, y);\n };\n /**\n * Returns a new Vector2 located for \"amount\" (float) on the linear interpolation between the vector \"start\" adn the vector \"end\".\n * @param start defines the start vector\n * @param end defines the end vector\n * @param amount defines the interpolation factor\n * @returns a new Vector2\n */\n Vector2.Lerp = function (start, end, amount) {\n var x = start.x + ((end.x - start.x) * amount);\n var y = start.y + ((end.y - start.y) * amount);\n return new Vector2(x, y);\n };\n /**\n * Gets the dot product of the vector \"left\" and the vector \"right\"\n * @param left defines first vector\n * @param right defines second vector\n * @returns the dot product (float)\n */\n Vector2.Dot = function (left, right) {\n return left.x * right.x + left.y * right.y;\n };\n /**\n * Returns a new Vector2 equal to the normalized given vector\n * @param vector defines the vector to normalize\n * @returns a new Vector2\n */\n Vector2.Normalize = function (vector) {\n var newVector = vector.clone();\n newVector.normalize();\n return newVector;\n };\n /**\n * Gets a new Vector2 set with the minimal coordinate values from the \"left\" and \"right\" vectors\n * @param left defines 1st vector\n * @param right defines 2nd vector\n * @returns a new Vector2\n */\n Vector2.Minimize = function (left, right) {\n var x = (left.x < right.x) ? left.x : right.x;\n var y = (left.y < right.y) ? left.y : right.y;\n return new Vector2(x, y);\n };\n /**\n * Gets a new Vecto2 set with the maximal coordinate values from the \"left\" and \"right\" vectors\n * @param left defines 1st vector\n * @param right defines 2nd vector\n * @returns a new Vector2\n */\n Vector2.Maximize = function (left, right) {\n var x = (left.x > right.x) ? left.x : right.x;\n var y = (left.y > right.y) ? left.y : right.y;\n return new Vector2(x, y);\n };\n /**\n * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix\n * @param vector defines the vector to transform\n * @param transformation defines the matrix to apply\n * @returns a new Vector2\n */\n Vector2.Transform = function (vector, transformation) {\n var r = Vector2.Zero();\n Vector2.TransformToRef(vector, transformation, r);\n return r;\n };\n /**\n * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector \"result\" coordinates\n * @param vector defines the vector to transform\n * @param transformation defines the matrix to apply\n * @param result defines the target vector\n */\n Vector2.TransformToRef = function (vector, transformation, result) {\n var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];\n var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];\n result.x = x;\n result.y = y;\n };\n /**\n * Determines if a given vector is included in a triangle\n * @param p defines the vector to test\n * @param p0 defines 1st triangle point\n * @param p1 defines 2nd triangle point\n * @param p2 defines 3rd triangle point\n * @returns true if the point \"p\" is in the triangle defined by the vertors \"p0\", \"p1\", \"p2\"\n */\n Vector2.PointInTriangle = function (p, p0, p1, p2) {\n var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);\n var sign = a < 0 ? -1 : 1;\n var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;\n var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;\n return s > 0 && t > 0 && (s + t) < 2 * a * sign;\n };\n /**\n * Gets the distance between the vectors \"value1\" and \"value2\"\n * @param value1 defines first vector\n * @param value2 defines second vector\n * @returns the distance between vectors\n */\n Vector2.Distance = function (value1, value2) {\n return Math.sqrt(Vector2.DistanceSquared(value1, value2));\n };\n /**\n * Returns the squared distance between the vectors \"value1\" and \"value2\"\n * @param value1 defines first vector\n * @param value2 defines second vector\n * @returns the squared distance between vectors\n */\n Vector2.DistanceSquared = function (value1, value2) {\n var x = value1.x - value2.x;\n var y = value1.y - value2.y;\n return (x * x) + (y * y);\n };\n /**\n * Gets a new Vector2 located at the center of the vectors \"value1\" and \"value2\"\n * @param value1 defines first vector\n * @param value2 defines second vector\n * @returns a new Vector2\n */\n Vector2.Center = function (value1, value2) {\n var center = value1.add(value2);\n center.scaleInPlace(0.5);\n return center;\n };\n /**\n * Gets the shortest distance (float) between the point \"p\" and the segment defined by the two points \"segA\" and \"segB\".\n * @param p defines the middle point\n * @param segA defines one point of the segment\n * @param segB defines the other point of the segment\n * @returns the shortest distance\n */\n Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {\n var l2 = Vector2.DistanceSquared(segA, segB);\n if (l2 === 0.0) {\n return Vector2.Distance(p, segA);\n }\n var v = segB.subtract(segA);\n var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));\n var proj = segA.add(v.multiplyByFloats(t, t));\n return Vector2.Distance(p, proj);\n };\n return Vector2;\n }());\n BABYLON.Vector2 = Vector2;\n /**\n * Classed used to store (x,y,z) vector representation\n * A Vector3 is the main object used in 3D geometry\n * It can represent etiher the coordinates of a point the space, either a direction\n * Reminder: Babylon.js uses a left handed forward facing system\n */\n var Vector3 = /** @class */ (function () {\n /**\n * Creates a new Vector3 object from the given x, y, z (floats) coordinates.\n * @param x defines the first coordinates (on X axis)\n * @param y defines the second coordinates (on Y axis)\n * @param z defines the third coordinates (on Z axis)\n */\n function Vector3(\n /**\n * Defines the first coordinates (on X axis)\n */\n x, \n /**\n * Defines the second coordinates (on Y axis)\n */\n y, \n /**\n * Defines the third coordinates (on Z axis)\n */\n z) {\n if (x === void 0) { x = 0; }\n if (y === void 0) { y = 0; }\n if (z === void 0) { z = 0; }\n this.x = x;\n this.y = y;\n this.z = z;\n }\n /**\n * Creates a string representation of the Vector3\n * @returns a string with the Vector3 coordinates.\n */\n Vector3.prototype.toString = function () {\n return \"{X: \" + this.x + \" Y:\" + this.y + \" Z:\" + this.z + \"}\";\n };\n /**\n * Gets the class name\n * @returns the string \"Vector3\"\n */\n Vector3.prototype.getClassName = function () {\n return \"Vector3\";\n };\n /**\n * Creates the Vector3 hash code\n * @returns a number which tends to be unique between Vector3 instances\n */\n Vector3.prototype.getHashCode = function () {\n var hash = this.x || 0;\n hash = (hash * 397) ^ (this.y || 0);\n hash = (hash * 397) ^ (this.z || 0);\n return hash;\n };\n // Operators\n /**\n * Creates an array containing three elements : the coordinates of the Vector3\n * @returns a new array of numbers\n */\n Vector3.prototype.asArray = function () {\n var result = [];\n this.toArray(result, 0);\n return result;\n };\n /**\n * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3\n * @param array defines the destination array\n * @param index defines the offset in the destination array\n * @returns the current Vector3\n */\n Vector3.prototype.toArray = function (array, index) {\n if (index === void 0) { index = 0; }\n array[index] = this.x;\n array[index + 1] = this.y;\n array[index + 2] = this.z;\n return this;\n };\n /**\n * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)\n * @returns a new Quaternion object, computed from the Vector3 coordinates\n */\n Vector3.prototype.toQuaternion = function () {\n return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);\n };\n /**\n * Adds the given vector to the current Vector3\n * @param otherVector defines the second operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.addInPlace = function (otherVector) {\n this.x += otherVector.x;\n this.y += otherVector.y;\n this.z += otherVector.z;\n return this;\n };\n /**\n * Gets a new Vector3, result of the addition the current Vector3 and the given vector\n * @param otherVector defines the second operand\n * @returns the resulting Vector3\n */\n Vector3.prototype.add = function (otherVector) {\n return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);\n };\n /**\n * Adds the current Vector3 to the given one and stores the result in the vector \"result\"\n * @param otherVector defines the second operand\n * @param result defines the Vector3 object where to store the result\n * @returns the current Vector3\n */\n Vector3.prototype.addToRef = function (otherVector, result) {\n result.x = this.x + otherVector.x;\n result.y = this.y + otherVector.y;\n result.z = this.z + otherVector.z;\n return this;\n };\n /**\n * Subtract the given vector from the current Vector3\n * @param otherVector defines the second operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.subtractInPlace = function (otherVector) {\n this.x -= otherVector.x;\n this.y -= otherVector.y;\n this.z -= otherVector.z;\n return this;\n };\n /**\n * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3\n * @param otherVector defines the second operand\n * @returns the resulting Vector3\n */\n Vector3.prototype.subtract = function (otherVector) {\n return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);\n };\n /**\n * Subtracts the given vector from the current Vector3 and stores the result in the vector \"result\".\n * @param otherVector defines the second operand\n * @param result defines the Vector3 object where to store the result\n * @returns the current Vector3\n */\n Vector3.prototype.subtractToRef = function (otherVector, result) {\n result.x = this.x - otherVector.x;\n result.y = this.y - otherVector.y;\n result.z = this.z - otherVector.z;\n return this;\n };\n /**\n * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates\n * @param x defines the x coordinate of the operand\n * @param y defines the y coordinate of the operand\n * @param z defines the z coordinate of the operand\n * @returns the resulting Vector3\n */\n Vector3.prototype.subtractFromFloats = function (x, y, z) {\n return new Vector3(this.x - x, this.y - y, this.z - z);\n };\n /**\n * Subtracts the given floats from the current Vector3 coordinates and set the given vector \"result\" with this result\n * @param x defines the x coordinate of the operand\n * @param y defines the y coordinate of the operand\n * @param z defines the z coordinate of the operand\n * @param result defines the Vector3 object where to store the result\n * @returns the current Vector3\n */\n Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {\n result.x = this.x - x;\n result.y = this.y - y;\n result.z = this.z - z;\n return this;\n };\n /**\n * Gets a new Vector3 set with the current Vector3 negated coordinates\n * @returns a new Vector3\n */\n Vector3.prototype.negate = function () {\n return new Vector3(-this.x, -this.y, -this.z);\n };\n /**\n * Multiplies the Vector3 coordinates by the float \"scale\"\n * @param scale defines the multiplier factor\n * @returns the current updated Vector3\n */\n Vector3.prototype.scaleInPlace = function (scale) {\n this.x *= scale;\n this.y *= scale;\n this.z *= scale;\n return this;\n };\n /**\n * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float \"scale\"\n * @param scale defines the multiplier factor\n * @returns a new Vector3\n */\n Vector3.prototype.scale = function (scale) {\n return new Vector3(this.x * scale, this.y * scale, this.z * scale);\n };\n /**\n * Multiplies the current Vector3 coordinates by the float \"scale\" and stores the result in the given vector \"result\" coordinates\n * @param scale defines the multiplier factor\n * @param result defines the Vector3 object where to store the result\n * @returns the current Vector3\n */\n Vector3.prototype.scaleToRef = function (scale, result) {\n result.x = this.x * scale;\n result.y = this.y * scale;\n result.z = this.z * scale;\n return this;\n };\n /**\n * Scale the current Vector3 values by a factor and add the result to a given Vector3\n * @param scale defines the scale factor\n * @param result defines the Vector3 object where to store the result\n * @returns the unmodified current Vector3\n */\n Vector3.prototype.scaleAndAddToRef = function (scale, result) {\n result.x += this.x * scale;\n result.y += this.y * scale;\n result.z += this.z * scale;\n return this;\n };\n /**\n * Returns true if the current Vector3 and the given vector coordinates are strictly equal\n * @param otherVector defines the second operand\n * @returns true if both vectors are equals\n */\n Vector3.prototype.equals = function (otherVector) {\n return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;\n };\n /**\n * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon\n * @param otherVector defines the second operand\n * @param epsilon defines the minimal distance to define values as equals\n * @returns true if both vectors are distant less than epsilon\n */\n Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {\n if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }\n return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);\n };\n /**\n * Returns true if the current Vector3 coordinates equals the given floats\n * @param x defines the x coordinate of the operand\n * @param y defines the y coordinate of the operand\n * @param z defines the z coordinate of the operand\n * @returns true if both vectors are equals\n */\n Vector3.prototype.equalsToFloats = function (x, y, z) {\n return this.x === x && this.y === y && this.z === z;\n };\n /**\n * Multiplies the current Vector3 coordinates by the given ones\n * @param otherVector defines the second operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.multiplyInPlace = function (otherVector) {\n this.x *= otherVector.x;\n this.y *= otherVector.y;\n this.z *= otherVector.z;\n return this;\n };\n /**\n * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector\n * @param otherVector defines the second operand\n * @returns the new Vector3\n */\n Vector3.prototype.multiply = function (otherVector) {\n return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);\n };\n /**\n * Multiplies the current Vector3 by the given one and stores the result in the given vector \"result\"\n * @param otherVector defines the second operand\n * @param result defines the Vector3 object where to store the result\n * @returns the current Vector3\n */\n Vector3.prototype.multiplyToRef = function (otherVector, result) {\n result.x = this.x * otherVector.x;\n result.y = this.y * otherVector.y;\n result.z = this.z * otherVector.z;\n return this;\n };\n /**\n * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats\n * @param x defines the x coordinate of the operand\n * @param y defines the y coordinate of the operand\n * @param z defines the z coordinate of the operand\n * @returns the new Vector3\n */\n Vector3.prototype.multiplyByFloats = function (x, y, z) {\n return new Vector3(this.x * x, this.y * y, this.z * z);\n };\n /**\n * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones\n * @param otherVector defines the second operand\n * @returns the new Vector3\n */\n Vector3.prototype.divide = function (otherVector) {\n return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);\n };\n /**\n * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector \"result\"\n * @param otherVector defines the second operand\n * @param result defines the Vector3 object where to store the result\n * @returns the current Vector3\n */\n Vector3.prototype.divideToRef = function (otherVector, result) {\n result.x = this.x / otherVector.x;\n result.y = this.y / otherVector.y;\n result.z = this.z / otherVector.z;\n return this;\n };\n /**\n * Divides the current Vector3 coordinates by the given ones.\n * @param otherVector defines the second operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.divideInPlace = function (otherVector) {\n return this.divideToRef(otherVector, this);\n };\n /**\n * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones\n * @param other defines the second operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.minimizeInPlace = function (other) {\n if (other.x < this.x)\n this.x = other.x;\n if (other.y < this.y)\n this.y = other.y;\n if (other.z < this.z)\n this.z = other.z;\n return this;\n };\n /**\n * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.\n * @param other defines the second operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.maximizeInPlace = function (other) {\n if (other.x > this.x)\n this.x = other.x;\n if (other.y > this.y)\n this.y = other.y;\n if (other.z > this.z)\n this.z = other.z;\n return this;\n };\n Object.defineProperty(Vector3.prototype, \"isNonUniform\", {\n /**\n * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same\n */\n get: function () {\n var absX = Math.abs(this.x);\n var absY = Math.abs(this.y);\n if (absX !== absY) {\n return true;\n }\n var absZ = Math.abs(this.z);\n if (absX !== absZ) {\n return true;\n }\n if (absY !== absZ) {\n return true;\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets a new Vector3 from current Vector3 floored values\n * @returns a new Vector3\n */\n Vector3.prototype.floor = function () {\n return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));\n };\n /**\n * Gets a new Vector3 from current Vector3 floored values\n * @returns a new Vector3\n */\n Vector3.prototype.fract = function () {\n return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));\n };\n // Properties\n /**\n * Gets the length of the Vector3\n * @returns the length of the Vecto3\n */\n Vector3.prototype.length = function () {\n return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);\n };\n /**\n * Gets the squared length of the Vector3\n * @returns squared length of the Vector3\n */\n Vector3.prototype.lengthSquared = function () {\n return (this.x * this.x + this.y * this.y + this.z * this.z);\n };\n /**\n * Normalize the current Vector3.\n * Please note that this is an in place operation.\n * @returns the current updated Vector3\n */\n Vector3.prototype.normalize = function () {\n var len = this.length();\n if (len === 0 || len === 1.0)\n return this;\n var num = 1.0 / len;\n this.x *= num;\n this.y *= num;\n this.z *= num;\n return this;\n };\n /**\n * Normalize the current Vector3 to a new vector\n * @returns the new Vector3\n */\n Vector3.prototype.normalizeToNew = function () {\n var normalized = new Vector3(0, 0, 0);\n this.normalizeToRef(normalized);\n return normalized;\n };\n /**\n * Normalize the current Vector3 to the reference\n * @param reference define the Vector3 to update\n * @returns the updated Vector3\n */\n Vector3.prototype.normalizeToRef = function (reference) {\n var len = this.length();\n if (len === 0 || len === 1.0) {\n reference.set(this.x, this.y, this.z);\n return reference;\n }\n var scale = 1.0 / len;\n this.scaleToRef(scale, reference);\n return reference;\n };\n /**\n * Creates a new Vector3 copied from the current Vector3\n * @returns the new Vector3\n */\n Vector3.prototype.clone = function () {\n return new Vector3(this.x, this.y, this.z);\n };\n /**\n * Copies the given vector coordinates to the current Vector3 ones\n * @param source defines the source Vector3\n * @returns the current updated Vector3\n */\n Vector3.prototype.copyFrom = function (source) {\n this.x = source.x;\n this.y = source.y;\n this.z = source.z;\n return this;\n };\n /**\n * Copies the given floats to the current Vector3 coordinates\n * @param x defines the x coordinate of the operand\n * @param y defines the y coordinate of the operand\n * @param z defines the z coordinate of the operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.copyFromFloats = function (x, y, z) {\n this.x = x;\n this.y = y;\n this.z = z;\n return this;\n };\n /**\n * Copies the given floats to the current Vector3 coordinates\n * @param x defines the x coordinate of the operand\n * @param y defines the y coordinate of the operand\n * @param z defines the z coordinate of the operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.set = function (x, y, z) {\n return this.copyFromFloats(x, y, z);\n };\n // Statics\n /**\n * Get the clip factor between two vectors\n * @param vector0 defines the first operand\n * @param vector1 defines the second operand\n * @param axis defines the axis to use\n * @param size defines the size along the axis\n * @returns the clip factor\n */\n Vector3.GetClipFactor = function (vector0, vector1, axis, size) {\n var d0 = Vector3.Dot(vector0, axis) - size;\n var d1 = Vector3.Dot(vector1, axis) - size;\n var s = d0 / (d0 - d1);\n return s;\n };\n /**\n * Get angle between two vectors\n * @param vector0 angle between vector0 and vector1\n * @param vector1 angle between vector0 and vector1\n * @param normal direction of the normal\n * @return the angle between vector0 and vector1\n */\n Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {\n var v0 = vector0.clone().normalize();\n var v1 = vector1.clone().normalize();\n var dot = Vector3.Dot(v0, v1);\n var n = Vector3.Cross(v0, v1);\n if (Vector3.Dot(n, normal) > 0) {\n return Math.acos(dot);\n }\n return -Math.acos(dot);\n };\n /**\n * Returns a new Vector3 set from the index \"offset\" of the given array\n * @param array defines the source array\n * @param offset defines the offset in the source array\n * @returns the new Vector3\n */\n Vector3.FromArray = function (array, offset) {\n if (!offset) {\n offset = 0;\n }\n return new Vector3(array[offset], array[offset + 1], array[offset + 2]);\n };\n /**\n * Returns a new Vector3 set from the index \"offset\" of the given Float32Array\n * This function is deprecated. Use FromArray instead\n * @param array defines the source array\n * @param offset defines the offset in the source array\n * @returns the new Vector3\n */\n Vector3.FromFloatArray = function (array, offset) {\n return Vector3.FromArray(array, offset);\n };\n /**\n * Sets the given vector \"result\" with the element values from the index \"offset\" of the given array\n * @param array defines the source array\n * @param offset defines the offset in the source array\n * @param result defines the Vector3 where to store the result\n */\n Vector3.FromArrayToRef = function (array, offset, result) {\n result.x = array[offset];\n result.y = array[offset + 1];\n result.z = array[offset + 2];\n };\n /**\n * Sets the given vector \"result\" with the element values from the index \"offset\" of the given Float32Array\n * This function is deprecated. Use FromArrayToRef instead.\n * @param array defines the source array\n * @param offset defines the offset in the source array\n * @param result defines the Vector3 where to store the result\n */\n Vector3.FromFloatArrayToRef = function (array, offset, result) {\n return Vector3.FromArrayToRef(array, offset, result);\n };\n /**\n * Sets the given vector \"result\" with the given floats.\n * @param x defines the x coordinate of the source\n * @param y defines the y coordinate of the source\n * @param z defines the z coordinate of the source\n * @param result defines the Vector3 where to store the result\n */\n Vector3.FromFloatsToRef = function (x, y, z, result) {\n result.x = x;\n result.y = y;\n result.z = z;\n };\n /**\n * Returns a new Vector3 set to (0.0, 0.0, 0.0)\n * @returns a new empty Vector3\n */\n Vector3.Zero = function () {\n return new Vector3(0.0, 0.0, 0.0);\n };\n /**\n * Returns a new Vector3 set to (1.0, 1.0, 1.0)\n * @returns a new unit Vector3\n */\n Vector3.One = function () {\n return new Vector3(1.0, 1.0, 1.0);\n };\n /**\n * Returns a new Vector3 set to (0.0, 1.0, 0.0)\n * @returns a new up Vector3\n */\n Vector3.Up = function () {\n return new Vector3(0.0, 1.0, 0.0);\n };\n /**\n * Returns a new Vector3 set to (0.0, -1.0, 0.0)\n * @returns a new down Vector3\n */\n Vector3.Down = function () {\n return new Vector3(0.0, -1.0, 0.0);\n };\n /**\n * Returns a new Vector3 set to (0.0, 0.0, 1.0)\n * @returns a new forward Vector3\n */\n Vector3.Forward = function () {\n return new Vector3(0.0, 0.0, 1.0);\n };\n /**\n * Returns a new Vector3 set to (1.0, 0.0, 0.0)\n * @returns a new right Vector3\n */\n Vector3.Right = function () {\n return new Vector3(1.0, 0.0, 0.0);\n };\n /**\n * Returns a new Vector3 set to (-1.0, 0.0, 0.0)\n * @returns a new left Vector3\n */\n Vector3.Left = function () {\n return new Vector3(-1.0, 0.0, 0.0);\n };\n /**\n * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.\n * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)\n * @param vector defines the Vector3 to transform\n * @param transformation defines the transformation matrix\n * @returns the transformed Vector3\n */\n Vector3.TransformCoordinates = function (vector, transformation) {\n var result = Vector3.Zero();\n Vector3.TransformCoordinatesToRef(vector, transformation, result);\n return result;\n };\n /**\n * Sets the given vector \"result\" coordinates with the result of the transformation by the given matrix of the given vector\n * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)\n * @param vector defines the Vector3 to transform\n * @param transformation defines the transformation matrix\n * @param result defines the Vector3 where to store the result\n */\n Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {\n var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];\n var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];\n var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];\n var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];\n result.x = x / w;\n result.y = y / w;\n result.z = z / w;\n };\n /**\n * Sets the given vector \"result\" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)\n * This method computes tranformed coordinates only, not transformed direction vectors\n * @param x define the x coordinate of the source vector\n * @param y define the y coordinate of the source vector\n * @param z define the z coordinate of the source vector\n * @param transformation defines the transformation matrix\n * @param result defines the Vector3 where to store the result\n */\n Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {\n var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];\n var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];\n var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];\n var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];\n result.x = rx / rw;\n result.y = ry / rw;\n result.z = rz / rw;\n };\n /**\n * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector\n * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)\n * @param vector defines the Vector3 to transform\n * @param transformation defines the transformation matrix\n * @returns the new Vector3\n */\n Vector3.TransformNormal = function (vector, transformation) {\n var result = Vector3.Zero();\n Vector3.TransformNormalToRef(vector, transformation, result);\n return result;\n };\n /**\n * Sets the given vector \"result\" with the result of the normal transformation by the given matrix of the given vector\n * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)\n * @param vector defines the Vector3 to transform\n * @param transformation defines the transformation matrix\n * @param result defines the Vector3 where to store the result\n */\n Vector3.TransformNormalToRef = function (vector, transformation, result) {\n var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);\n var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);\n var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);\n result.x = x;\n result.y = y;\n result.z = z;\n };\n /**\n * Sets the given vector \"result\" with the result of the normal transformation by the given matrix of the given floats (x, y, z)\n * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)\n * @param x define the x coordinate of the source vector\n * @param y define the y coordinate of the source vector\n * @param z define the z coordinate of the source vector\n * @param transformation defines the transformation matrix\n * @param result defines the Vector3 where to store the result\n */\n Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {\n result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);\n result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);\n result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);\n };\n /**\n * Returns a new Vector3 located for \"amount\" on the CatmullRom interpolation spline defined by the vectors \"value1\", \"value2\", \"value3\", \"value4\"\n * @param value1 defines the first control point\n * @param value2 defines the second control point\n * @param value3 defines the third control point\n * @param value4 defines the fourth control point\n * @param amount defines the amount on the spline to use\n * @returns the new Vector3\n */\n Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {\n var squared = amount * amount;\n var cubed = amount * squared;\n var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +\n (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +\n ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));\n var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +\n (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +\n ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));\n var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +\n (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +\n ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));\n return new Vector3(x, y, z);\n };\n /**\n * Returns a new Vector3 set with the coordinates of \"value\", if the vector \"value\" is in the cube defined by the vectors \"min\" and \"max\"\n * If a coordinate value of \"value\" is lower than one of the \"min\" coordinate, then this \"value\" coordinate is set with the \"min\" one\n * If a coordinate value of \"value\" is greater than one of the \"max\" coordinate, then this \"value\" coordinate is set with the \"max\" one\n * @param value defines the current value\n * @param min defines the lower range value\n * @param max defines the upper range value\n * @returns the new Vector3\n */\n Vector3.Clamp = function (value, min, max) {\n var x = value.x;\n x = (x > max.x) ? max.x : x;\n x = (x < min.x) ? min.x : x;\n var y = value.y;\n y = (y > max.y) ? max.y : y;\n y = (y < min.y) ? min.y : y;\n var z = value.z;\n z = (z > max.z) ? max.z : z;\n z = (z < min.z) ? min.z : z;\n return new Vector3(x, y, z);\n };\n /**\n * Returns a new Vector3 located for \"amount\" (float) on the Hermite interpolation spline defined by the vectors \"value1\", \"tangent1\", \"value2\", \"tangent2\"\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent vector\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent vector\n * @param amount defines the amount on the interpolation spline (between 0 and 1)\n * @returns the new Vector3\n */\n Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {\n var squared = amount * amount;\n var cubed = amount * squared;\n var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;\n var part2 = (-2.0 * cubed) + (3.0 * squared);\n var part3 = (cubed - (2.0 * squared)) + amount;\n var part4 = cubed - squared;\n var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);\n var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);\n var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);\n return new Vector3(x, y, z);\n };\n /**\n * Returns a new Vector3 located for \"amount\" (float) on the linear interpolation between the vectors \"start\" and \"end\"\n * @param start defines the start value\n * @param end defines the end value\n * @param amount max defines amount between both (between 0 and 1)\n * @returns the new Vector3\n */\n Vector3.Lerp = function (start, end, amount) {\n var result = new Vector3(0, 0, 0);\n Vector3.LerpToRef(start, end, amount, result);\n return result;\n };\n /**\n * Sets the given vector \"result\" with the result of the linear interpolation from the vector \"start\" for \"amount\" to the vector \"end\"\n * @param start defines the start value\n * @param end defines the end value\n * @param amount max defines amount between both (between 0 and 1)\n * @param result defines the Vector3 where to store the result\n */\n Vector3.LerpToRef = function (start, end, amount, result) {\n result.x = start.x + ((end.x - start.x) * amount);\n result.y = start.y + ((end.y - start.y) * amount);\n result.z = start.z + ((end.z - start.z) * amount);\n };\n /**\n * Returns the dot product (float) between the vectors \"left\" and \"right\"\n * @param left defines the left operand\n * @param right defines the right operand\n * @returns the dot product\n */\n Vector3.Dot = function (left, right) {\n return (left.x * right.x + left.y * right.y + left.z * right.z);\n };\n /**\n * Returns a new Vector3 as the cross product of the vectors \"left\" and \"right\"\n * The cross product is then orthogonal to both \"left\" and \"right\"\n * @param left defines the left operand\n * @param right defines the right operand\n * @returns the cross product\n */\n Vector3.Cross = function (left, right) {\n var result = Vector3.Zero();\n Vector3.CrossToRef(left, right, result);\n return result;\n };\n /**\n * Sets the given vector \"result\" with the cross product of \"left\" and \"right\"\n * The cross product is then orthogonal to both \"left\" and \"right\"\n * @param left defines the left operand\n * @param right defines the right operand\n * @param result defines the Vector3 where to store the result\n */\n Vector3.CrossToRef = function (left, right, result) {\n MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;\n MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;\n MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;\n result.copyFrom(MathTmp.Vector3[0]);\n };\n /**\n * Returns a new Vector3 as the normalization of the given vector\n * @param vector defines the Vector3 to normalize\n * @returns the new Vector3\n */\n Vector3.Normalize = function (vector) {\n var result = Vector3.Zero();\n Vector3.NormalizeToRef(vector, result);\n return result;\n };\n /**\n * Sets the given vector \"result\" with the normalization of the given first vector\n * @param vector defines the Vector3 to normalize\n * @param result defines the Vector3 where to store the result\n */\n Vector3.NormalizeToRef = function (vector, result) {\n result.copyFrom(vector);\n result.normalize();\n };\n /**\n * Project a Vector3 onto screen space\n * @param vector defines the Vector3 to project\n * @param world defines the world matrix to use\n * @param transform defines the transform (view x projection) matrix to use\n * @param viewport defines the screen viewport to use\n * @returns the new Vector3\n */\n Vector3.Project = function (vector, world, transform, viewport) {\n var cw = viewport.width;\n var ch = viewport.height;\n var cx = viewport.x;\n var cy = viewport.y;\n var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());\n Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);\n var matrix = MathTmp.Matrix[0];\n world.multiplyToRef(transform, matrix);\n matrix.multiplyToRef(viewportMatrix, matrix);\n return Vector3.TransformCoordinates(vector, matrix);\n };\n /**\n * Unproject from screen space to object space\n * @param source defines the screen space Vector3 to use\n * @param viewportWidth defines the current width of the viewport\n * @param viewportHeight defines the current height of the viewport\n * @param world defines the world matrix to use (can be set to Identity to go to world space)\n * @param transform defines the transform (view x projection) matrix to use\n * @returns the new Vector3\n */\n Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {\n var matrix = MathTmp.Matrix[0];\n world.multiplyToRef(transform, matrix);\n matrix.invert();\n source.x = source.x / viewportWidth * 2 - 1;\n source.y = -(source.y / viewportHeight * 2 - 1);\n var vector = Vector3.TransformCoordinates(source, matrix);\n var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];\n if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {\n vector = vector.scale(1.0 / num);\n }\n return vector;\n };\n /**\n * Unproject from screen space to object space\n * @param source defines the screen space Vector3 to use\n * @param viewportWidth defines the current width of the viewport\n * @param viewportHeight defines the current height of the viewport\n * @param world defines the world matrix to use (can be set to Identity to go to world space)\n * @param view defines the view matrix to use\n * @param projection defines the projection matrix to use\n * @returns the new Vector3\n */\n Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {\n var result = Vector3.Zero();\n Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);\n return result;\n };\n /**\n * Unproject from screen space to object space\n * @param source defines the screen space Vector3 to use\n * @param viewportWidth defines the current width of the viewport\n * @param viewportHeight defines the current height of the viewport\n * @param world defines the world matrix to use (can be set to Identity to go to world space)\n * @param view defines the view matrix to use\n * @param projection defines the projection matrix to use\n * @param result defines the Vector3 where to store the result\n */\n Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {\n Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);\n };\n /**\n * Unproject from screen space to object space\n * @param sourceX defines the screen space x coordinate to use\n * @param sourceY defines the screen space y coordinate to use\n * @param sourceZ defines the screen space z coordinate to use\n * @param viewportWidth defines the current width of the viewport\n * @param viewportHeight defines the current height of the viewport\n * @param world defines the world matrix to use (can be set to Identity to go to world space)\n * @param view defines the view matrix to use\n * @param projection defines the projection matrix to use\n * @param result defines the Vector3 where to store the result\n */\n Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {\n var matrix = MathTmp.Matrix[0];\n world.multiplyToRef(view, matrix);\n matrix.multiplyToRef(projection, matrix);\n matrix.invert();\n var screenSource = MathTmp.Vector3[0];\n screenSource.x = sourceX / viewportWidth * 2 - 1;\n screenSource.y = -(sourceY / viewportHeight * 2 - 1);\n screenSource.z = 2 * sourceZ - 1.0;\n Vector3.TransformCoordinatesToRef(screenSource, matrix, result);\n var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];\n if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {\n result.scaleInPlace(1.0 / num);\n }\n };\n /**\n * Gets the minimal coordinate values between two Vector3\n * @param left defines the first operand\n * @param right defines the second operand\n * @returns the new Vector3\n */\n Vector3.Minimize = function (left, right) {\n var min = left.clone();\n min.minimizeInPlace(right);\n return min;\n };\n /**\n * Gets the maximal coordinate values between two Vector3\n * @param left defines the first operand\n * @param right defines the second operand\n * @returns the new Vector3\n */\n Vector3.Maximize = function (left, right) {\n var max = left.clone();\n max.maximizeInPlace(right);\n return max;\n };\n /**\n * Returns the distance between the vectors \"value1\" and \"value2\"\n * @param value1 defines the first operand\n * @param value2 defines the second operand\n * @returns the distance\n */\n Vector3.Distance = function (value1, value2) {\n return Math.sqrt(Vector3.DistanceSquared(value1, value2));\n };\n /**\n * Returns the squared distance between the vectors \"value1\" and \"value2\"\n * @param value1 defines the first operand\n * @param value2 defines the second operand\n * @returns the squared distance\n */\n Vector3.DistanceSquared = function (value1, value2) {\n var x = value1.x - value2.x;\n var y = value1.y - value2.y;\n var z = value1.z - value2.z;\n return (x * x) + (y * y) + (z * z);\n };\n /**\n * Returns a new Vector3 located at the center between \"value1\" and \"value2\"\n * @param value1 defines the first operand\n * @param value2 defines the second operand\n * @returns the new Vector3\n */\n Vector3.Center = function (value1, value2) {\n var center = value1.add(value2);\n center.scaleInPlace(0.5);\n return center;\n };\n /**\n * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),\n * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply\n * to something in order to rotate it from its local system to the given target system\n * Note: axis1, axis2 and axis3 are normalized during this operation\n * @param axis1 defines the first axis\n * @param axis2 defines the second axis\n * @param axis3 defines the third axis\n * @returns a new Vector3\n */\n Vector3.RotationFromAxis = function (axis1, axis2, axis3) {\n var rotation = Vector3.Zero();\n Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);\n return rotation;\n };\n /**\n * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3\n * @param axis1 defines the first axis\n * @param axis2 defines the second axis\n * @param axis3 defines the third axis\n * @param ref defines the Vector3 where to store the result\n */\n Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {\n var quat = MathTmp.Quaternion[0];\n Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);\n quat.toEulerAnglesToRef(ref);\n };\n return Vector3;\n }());\n BABYLON.Vector3 = Vector3;\n //Vector4 class created for EulerAngle class conversion to Quaternion\n var Vector4 = /** @class */ (function () {\n /**\n * Creates a Vector4 object from the given floats.\n */\n function Vector4(x, y, z, w) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n }\n /**\n * Returns the string with the Vector4 coordinates.\n */\n Vector4.prototype.toString = function () {\n return \"{X: \" + this.x + \" Y:\" + this.y + \" Z:\" + this.z + \" W:\" + this.w + \"}\";\n };\n /**\n * Returns the string \"Vector4\".\n */\n Vector4.prototype.getClassName = function () {\n return \"Vector4\";\n };\n /**\n * Returns the Vector4 hash code.\n */\n Vector4.prototype.getHashCode = function () {\n var hash = this.x || 0;\n hash = (hash * 397) ^ (this.y || 0);\n hash = (hash * 397) ^ (this.z || 0);\n hash = (hash * 397) ^ (this.w || 0);\n return hash;\n };\n // Operators\n /**\n * Returns a new array populated with 4 elements : the Vector4 coordinates.\n */\n Vector4.prototype.asArray = function () {\n var result = new Array();\n this.toArray(result, 0);\n return result;\n };\n /**\n * Populates the given array from the given index with the Vector4 coordinates.\n * Returns the Vector4.\n */\n Vector4.prototype.toArray = function (array, index) {\n if (index === undefined) {\n index = 0;\n }\n array[index] = this.x;\n array[index + 1] = this.y;\n array[index + 2] = this.z;\n array[index + 3] = this.w;\n return this;\n };\n /**\n * Adds the given vector to the current Vector4.\n * Returns the updated Vector4.\n */\n Vector4.prototype.addInPlace = function (otherVector) {\n this.x += otherVector.x;\n this.y += otherVector.y;\n this.z += otherVector.z;\n this.w += otherVector.w;\n return this;\n };\n /**\n * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.\n */\n Vector4.prototype.add = function (otherVector) {\n return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);\n };\n /**\n * Updates the given vector \"result\" with the result of the addition of the current Vector4 and the given one.\n * Returns the current Vector4.\n */\n Vector4.prototype.addToRef = function (otherVector, result) {\n result.x = this.x + otherVector.x;\n result.y = this.y + otherVector.y;\n result.z = this.z + otherVector.z;\n result.w = this.w + otherVector.w;\n return this;\n };\n /**\n * Subtract in place the given vector from the current Vector4.\n * Returns the updated Vector4.\n */\n Vector4.prototype.subtractInPlace = function (otherVector) {\n this.x -= otherVector.x;\n this.y -= otherVector.y;\n this.z -= otherVector.z;\n this.w -= otherVector.w;\n return this;\n };\n /**\n * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.\n */\n Vector4.prototype.subtract = function (otherVector) {\n return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);\n };\n /**\n * Sets the given vector \"result\" with the result of the subtraction of the given vector from the current Vector4.\n * Returns the current Vector4.\n */\n Vector4.prototype.subtractToRef = function (otherVector, result) {\n result.x = this.x - otherVector.x;\n result.y = this.y - otherVector.y;\n result.z = this.z - otherVector.z;\n result.w = this.w - otherVector.w;\n return this;\n };\n /**\n * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.\n */\n Vector4.prototype.subtractFromFloats = function (x, y, z, w) {\n return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);\n };\n /**\n * Sets the given vector \"result\" set with the result of the subtraction of the given floats from the current Vector4 coordinates.\n * Returns the current Vector4.\n */\n Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {\n result.x = this.x - x;\n result.y = this.y - y;\n result.z = this.z - z;\n result.w = this.w - w;\n return this;\n };\n /**\n * Returns a new Vector4 set with the current Vector4 negated coordinates.\n */\n Vector4.prototype.negate = function () {\n return new Vector4(-this.x, -this.y, -this.z, -this.w);\n };\n /**\n * Multiplies the current Vector4 coordinates by scale (float).\n * Returns the updated Vector4.\n */\n Vector4.prototype.scaleInPlace = function (scale) {\n this.x *= scale;\n this.y *= scale;\n this.z *= scale;\n this.w *= scale;\n return this;\n };\n /**\n * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).\n */\n Vector4.prototype.scale = function (scale) {\n return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);\n };\n /**\n * Sets the given vector \"result\" with the current Vector4 coordinates multiplied by scale (float).\n * Returns the current Vector4.\n */\n Vector4.prototype.scaleToRef = function (scale, result) {\n result.x = this.x * scale;\n result.y = this.y * scale;\n result.z = this.z * scale;\n result.w = this.w * scale;\n return this;\n };\n /**\n * Scale the current Vector4 values by a factor and add the result to a given Vector4\n * @param scale defines the scale factor\n * @param result defines the Vector4 object where to store the result\n * @returns the unmodified current Vector4\n */\n Vector4.prototype.scaleAndAddToRef = function (scale, result) {\n result.x += this.x * scale;\n result.y += this.y * scale;\n result.z += this.z * scale;\n result.w += this.w * scale;\n return this;\n };\n /**\n * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.\n */\n Vector4.prototype.equals = function (otherVector) {\n return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;\n };\n /**\n * Boolean : True if the current Vector4 coordinates are each beneath the distance \"epsilon\" from the given vector ones.\n */\n Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {\n if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }\n return otherVector\n && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)\n && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)\n && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)\n && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);\n };\n /**\n * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.\n */\n Vector4.prototype.equalsToFloats = function (x, y, z, w) {\n return this.x === x && this.y === y && this.z === z && this.w === w;\n };\n /**\n * Multiplies in place the current Vector4 by the given one.\n * Returns the updated Vector4.\n */\n Vector4.prototype.multiplyInPlace = function (otherVector) {\n this.x *= otherVector.x;\n this.y *= otherVector.y;\n this.z *= otherVector.z;\n this.w *= otherVector.w;\n return this;\n };\n /**\n * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.\n */\n Vector4.prototype.multiply = function (otherVector) {\n return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);\n };\n /**\n * Updates the given vector \"result\" with the multiplication result of the current Vector4 and the given one.\n * Returns the current Vector4.\n */\n Vector4.prototype.multiplyToRef = function (otherVector, result) {\n result.x = this.x * otherVector.x;\n result.y = this.y * otherVector.y;\n result.z = this.z * otherVector.z;\n result.w = this.w * otherVector.w;\n return this;\n };\n /**\n * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.\n */\n Vector4.prototype.multiplyByFloats = function (x, y, z, w) {\n return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);\n };\n /**\n * Returns a new Vector4 set with the division result of the current Vector4 by the given one.\n */\n Vector4.prototype.divide = function (otherVector) {\n return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);\n };\n /**\n * Updates the given vector \"result\" with the division result of the current Vector4 by the given one.\n * Returns the current Vector4.\n */\n Vector4.prototype.divideToRef = function (otherVector, result) {\n result.x = this.x / otherVector.x;\n result.y = this.y / otherVector.y;\n result.z = this.z / otherVector.z;\n result.w = this.w / otherVector.w;\n return this;\n };\n /**\n * Divides the current Vector3 coordinates by the given ones.\n * @returns the updated Vector3.\n */\n Vector4.prototype.divideInPlace = function (otherVector) {\n return this.divideToRef(otherVector, this);\n };\n /**\n * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones\n * @param other defines the second operand\n * @returns the current updated Vector4\n */\n Vector4.prototype.minimizeInPlace = function (other) {\n if (other.x < this.x)\n this.x = other.x;\n if (other.y < this.y)\n this.y = other.y;\n if (other.z < this.z)\n this.z = other.z;\n if (other.w < this.w)\n this.w = other.w;\n return this;\n };\n /**\n * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones\n * @param other defines the second operand\n * @returns the current updated Vector4\n */\n Vector4.prototype.maximizeInPlace = function (other) {\n if (other.x > this.x)\n this.x = other.x;\n if (other.y > this.y)\n this.y = other.y;\n if (other.z > this.z)\n this.z = other.z;\n if (other.w > this.w)\n this.w = other.w;\n return this;\n };\n /**\n * Gets a new Vector4 from current Vector4 floored values\n * @returns a new Vector4\n */\n Vector4.prototype.floor = function () {\n return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));\n };\n /**\n * Gets a new Vector4 from current Vector3 floored values\n * @returns a new Vector4\n */\n Vector4.prototype.fract = function () {\n return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));\n };\n // Properties\n /**\n * Returns the Vector4 length (float).\n */\n Vector4.prototype.length = function () {\n return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);\n };\n /**\n * Returns the Vector4 squared length (float).\n */\n Vector4.prototype.lengthSquared = function () {\n return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);\n };\n // Methods\n /**\n * Normalizes in place the Vector4.\n * Returns the updated Vector4.\n */\n Vector4.prototype.normalize = function () {\n var len = this.length();\n if (len === 0)\n return this;\n var num = 1.0 / len;\n this.x *= num;\n this.y *= num;\n this.z *= num;\n this.w *= num;\n return this;\n };\n /**\n * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.\n */\n Vector4.prototype.toVector3 = function () {\n return new Vector3(this.x, this.y, this.z);\n };\n /**\n * Returns a new Vector4 copied from the current one.\n */\n Vector4.prototype.clone = function () {\n return new Vector4(this.x, this.y, this.z, this.w);\n };\n /**\n * Updates the current Vector4 with the given one coordinates.\n * Returns the updated Vector4.\n */\n Vector4.prototype.copyFrom = function (source) {\n this.x = source.x;\n this.y = source.y;\n this.z = source.z;\n this.w = source.w;\n return this;\n };\n /**\n * Updates the current Vector4 coordinates with the given floats.\n * Returns the updated Vector4.\n */\n Vector4.prototype.copyFromFloats = function (x, y, z, w) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n return this;\n };\n /**\n * Updates the current Vector4 coordinates with the given floats.\n * Returns the updated Vector4.\n */\n Vector4.prototype.set = function (x, y, z, w) {\n return this.copyFromFloats(x, y, z, w);\n };\n // Statics\n /**\n * Returns a new Vector4 set from the starting index of the given array.\n */\n Vector4.FromArray = function (array, offset) {\n if (!offset) {\n offset = 0;\n }\n return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n };\n /**\n * Updates the given vector \"result\" from the starting index of the given array.\n */\n Vector4.FromArrayToRef = function (array, offset, result) {\n result.x = array[offset];\n result.y = array[offset + 1];\n result.z = array[offset + 2];\n result.w = array[offset + 3];\n };\n /**\n * Updates the given vector \"result\" from the starting index of the given Float32Array.\n */\n Vector4.FromFloatArrayToRef = function (array, offset, result) {\n Vector4.FromArrayToRef(array, offset, result);\n };\n /**\n * Updates the given vector \"result\" coordinates from the given floats.\n */\n Vector4.FromFloatsToRef = function (x, y, z, w, result) {\n result.x = x;\n result.y = y;\n result.z = z;\n result.w = w;\n };\n /**\n * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)\n */\n Vector4.Zero = function () {\n return new Vector4(0.0, 0.0, 0.0, 0.0);\n };\n /**\n * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)\n */\n Vector4.One = function () {\n return new Vector4(1.0, 1.0, 1.0, 1.0);\n };\n /**\n * Returns a new normalized Vector4 from the given one.\n */\n Vector4.Normalize = function (vector) {\n var result = Vector4.Zero();\n Vector4.NormalizeToRef(vector, result);\n return result;\n };\n /**\n * Updates the given vector \"result\" from the normalization of the given one.\n */\n Vector4.NormalizeToRef = function (vector, result) {\n result.copyFrom(vector);\n result.normalize();\n };\n Vector4.Minimize = function (left, right) {\n var min = left.clone();\n min.minimizeInPlace(right);\n return min;\n };\n Vector4.Maximize = function (left, right) {\n var max = left.clone();\n max.maximizeInPlace(right);\n return max;\n };\n /**\n * Returns the distance (float) between the vectors \"value1\" and \"value2\".\n */\n Vector4.Distance = function (value1, value2) {\n return Math.sqrt(Vector4.DistanceSquared(value1, value2));\n };\n /**\n * Returns the squared distance (float) between the vectors \"value1\" and \"value2\".\n */\n Vector4.DistanceSquared = function (value1, value2) {\n var x = value1.x - value2.x;\n var y = value1.y - value2.y;\n var z = value1.z - value2.z;\n var w = value1.w - value2.w;\n return (x * x) + (y * y) + (z * z) + (w * w);\n };\n /**\n * Returns a new Vector4 located at the center between the vectors \"value1\" and \"value2\".\n */\n Vector4.Center = function (value1, value2) {\n var center = value1.add(value2);\n center.scaleInPlace(0.5);\n return center;\n };\n /**\n * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.\n * This methods computes transformed normalized direction vectors only.\n */\n Vector4.TransformNormal = function (vector, transformation) {\n var result = Vector4.Zero();\n Vector4.TransformNormalToRef(vector, transformation, result);\n return result;\n };\n /**\n * Sets the given vector \"result\" with the result of the normal transformation by the given matrix of the given vector.\n * This methods computes transformed normalized direction vectors only.\n */\n Vector4.TransformNormalToRef = function (vector, transformation, result) {\n var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);\n var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);\n var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);\n result.x = x;\n result.y = y;\n result.z = z;\n result.w = vector.w;\n };\n /**\n * Sets the given vector \"result\" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).\n * This methods computes transformed normalized direction vectors only.\n */\n Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {\n result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);\n result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);\n result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);\n result.w = w;\n };\n return Vector4;\n }());\n BABYLON.Vector4 = Vector4;\n var Size = /** @class */ (function () {\n /**\n * Creates a Size object from the given width and height (floats).\n */\n function Size(width, height) {\n this.width = width;\n this.height = height;\n }\n // Returns a string with the Size width and height. \n Size.prototype.toString = function () {\n return \"{W: \" + this.width + \", H: \" + this.height + \"}\";\n };\n /**\n * Returns the string \"Size\"\n */\n Size.prototype.getClassName = function () {\n return \"Size\";\n };\n /**\n * Returns the Size hash code.\n */\n Size.prototype.getHashCode = function () {\n var hash = this.width || 0;\n hash = (hash * 397) ^ (this.height || 0);\n return hash;\n };\n /**\n * Updates the current size from the given one.\n * Returns the updated Size.\n */\n Size.prototype.copyFrom = function (src) {\n this.width = src.width;\n this.height = src.height;\n };\n /**\n * Updates in place the current Size from the given floats.\n * Returns the updated Size.\n */\n Size.prototype.copyFromFloats = function (width, height) {\n this.width = width;\n this.height = height;\n return this;\n };\n /**\n * Updates in place the current Size from the given floats.\n * Returns the updated Size.\n */\n Size.prototype.set = function (width, height) {\n return this.copyFromFloats(width, height);\n };\n /**\n * Returns a new Size set with the multiplication result of the current Size and the given floats.\n */\n Size.prototype.multiplyByFloats = function (w, h) {\n return new Size(this.width * w, this.height * h);\n };\n /**\n * Returns a new Size copied from the given one.\n */\n Size.prototype.clone = function () {\n return new Size(this.width, this.height);\n };\n /**\n * Boolean : True if the current Size and the given one width and height are strictly equal.\n */\n Size.prototype.equals = function (other) {\n if (!other) {\n return false;\n }\n return (this.width === other.width) && (this.height === other.height);\n };\n Object.defineProperty(Size.prototype, \"surface\", {\n /**\n * Returns the surface of the Size : width * height (float).\n */\n get: function () {\n return this.width * this.height;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a new Size set to (0.0, 0.0)\n */\n Size.Zero = function () {\n return new Size(0.0, 0.0);\n };\n /**\n * Returns a new Size set as the addition result of the current Size and the given one.\n */\n Size.prototype.add = function (otherSize) {\n var r = new Size(this.width + otherSize.width, this.height + otherSize.height);\n return r;\n };\n /**\n * Returns a new Size set as the subtraction result of the given one from the current Size.\n */\n Size.prototype.subtract = function (otherSize) {\n var r = new Size(this.width - otherSize.width, this.height - otherSize.height);\n return r;\n };\n /**\n * Returns a new Size set at the linear interpolation \"amount\" between \"start\" and \"end\".\n */\n Size.Lerp = function (start, end, amount) {\n var w = start.width + ((end.width - start.width) * amount);\n var h = start.height + ((end.height - start.height) * amount);\n return new Size(w, h);\n };\n return Size;\n }());\n BABYLON.Size = Size;\n /**\n * Class used to store quaternion data\n * @see https://en.wikipedia.org/wiki/Quaternion\n * @see http://doc.babylonjs.com/features/position,_rotation,_scaling\n */\n var Quaternion = /** @class */ (function () {\n /**\n * Creates a new Quaternion from the given floats\n * @param x defines the first component (0 by default)\n * @param y defines the second component (0 by default)\n * @param z defines the third component (0 by default)\n * @param w defines the fourth component (1.0 by default)\n */\n function Quaternion(\n /** defines the first component (0 by default) */\n x, \n /** defines the second component (0 by default) */\n y, \n /** defines the third component (0 by default) */\n z, \n /** defines the fourth component (1.0 by default) */\n w) {\n if (x === void 0) { x = 0.0; }\n if (y === void 0) { y = 0.0; }\n if (z === void 0) { z = 0.0; }\n if (w === void 0) { w = 1.0; }\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n }\n /**\n * Gets a string representation for the current quaternion\n * @returns a string with the Quaternion coordinates\n */\n Quaternion.prototype.toString = function () {\n return \"{X: \" + this.x + \" Y:\" + this.y + \" Z:\" + this.z + \" W:\" + this.w + \"}\";\n };\n /**\n * Gets the class name of the quaternion\n * @returns the string \"Quaternion\"\n */\n Quaternion.prototype.getClassName = function () {\n return \"Quaternion\";\n };\n /**\n * Gets a hash code for this quaternion\n * @returns the quaternion hash code\n */\n Quaternion.prototype.getHashCode = function () {\n var hash = this.x || 0;\n hash = (hash * 397) ^ (this.y || 0);\n hash = (hash * 397) ^ (this.z || 0);\n hash = (hash * 397) ^ (this.w || 0);\n return hash;\n };\n /**\n * Copy the quaternion to an array\n * @returns a new array populated with 4 elements from the quaternion coordinates\n */\n Quaternion.prototype.asArray = function () {\n return [this.x, this.y, this.z, this.w];\n };\n /**\n * Check if two quaternions are equals\n * @param otherQuaternion defines the second operand\n * @return true if the current quaternion and the given one coordinates are strictly equals\n */\n Quaternion.prototype.equals = function (otherQuaternion) {\n return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;\n };\n /**\n * Clone the current quaternion\n * @returns a new quaternion copied from the current one\n */\n Quaternion.prototype.clone = function () {\n return new Quaternion(this.x, this.y, this.z, this.w);\n };\n /**\n * Copy a quaternion to the current one\n * @param other defines the other quaternion\n * @returns the updated current quaternion\n */\n Quaternion.prototype.copyFrom = function (other) {\n this.x = other.x;\n this.y = other.y;\n this.z = other.z;\n this.w = other.w;\n return this;\n };\n /**\n * Updates the current quaternion with the given float coordinates\n * @param x defines the x coordinate\n * @param y defines the y coordinate\n * @param z defines the z coordinate\n * @param w defines the w coordinate\n * @returns the updated current quaternion\n */\n Quaternion.prototype.copyFromFloats = function (x, y, z, w) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n return this;\n };\n /**\n * Updates the current quaternion from the given float coordinates\n * @param x defines the x coordinate\n * @param y defines the y coordinate\n * @param z defines the z coordinate\n * @param w defines the w coordinate\n * @returns the updated current quaternion\n */\n Quaternion.prototype.set = function (x, y, z, w) {\n return this.copyFromFloats(x, y, z, w);\n };\n /**\n * Adds two quaternions\n * @param other defines the second operand\n * @returns a new quaternion as the addition result of the given one and the current quaternion\n */\n Quaternion.prototype.add = function (other) {\n return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);\n };\n /**\n * Add a quaternion to the current one\n * @param other defines the quaternion to add\n * @returns the current quaternion\n */\n Quaternion.prototype.addInPlace = function (other) {\n this.x += other.x;\n this.y += other.y;\n this.z += other.z;\n this.w += other.w;\n return this;\n };\n /**\n * Subtract two quaternions\n * @param other defines the second operand\n * @returns a new quaternion as the subtraction result of the given one from the current one\n */\n Quaternion.prototype.subtract = function (other) {\n return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);\n };\n /**\n * Multiplies the current quaternion by a scale factor\n * @param value defines the scale factor\n * @returns a new quaternion set by multiplying the current quaternion coordinates by the float \"scale\"\n */\n Quaternion.prototype.scale = function (value) {\n return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);\n };\n /**\n * Scale the current quaternion values by a factor and stores the result to a given quaternion\n * @param scale defines the scale factor\n * @param result defines the Quaternion object where to store the result\n * @returns the unmodified current quaternion\n */\n Quaternion.prototype.scaleToRef = function (scale, result) {\n result.x = this.x * scale;\n result.y = this.y * scale;\n result.z = this.z * scale;\n result.w = this.w * scale;\n return this;\n };\n /**\n * Multiplies in place the current quaternion by a scale factor\n * @param value defines the scale factor\n * @returns the current modified quaternion\n */\n Quaternion.prototype.scaleInPlace = function (value) {\n this.x *= value;\n this.y *= value;\n this.z *= value;\n this.w *= value;\n return this;\n };\n /**\n * Scale the current quaternion values by a factor and add the result to a given quaternion\n * @param scale defines the scale factor\n * @param result defines the Quaternion object where to store the result\n * @returns the unmodified current quaternion\n */\n Quaternion.prototype.scaleAndAddToRef = function (scale, result) {\n result.x += this.x * scale;\n result.y += this.y * scale;\n result.z += this.z * scale;\n result.w += this.w * scale;\n return this;\n };\n /**\n * Multiplies two quaternions\n * @param q1 defines the second operand\n * @returns a new quaternion set as the multiplication result of the current one with the given one \"q1\"\n */\n Quaternion.prototype.multiply = function (q1) {\n var result = new Quaternion(0, 0, 0, 1.0);\n this.multiplyToRef(q1, result);\n return result;\n };\n /**\n * Sets the given \"result\" as the the multiplication result of the current one with the given one \"q1\"\n * @param q1 defines the second operand\n * @param result defines the target quaternion\n * @returns the current quaternion\n */\n Quaternion.prototype.multiplyToRef = function (q1, result) {\n var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;\n var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;\n var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;\n var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;\n result.copyFromFloats(x, y, z, w);\n return this;\n };\n /**\n * Updates the current quaternion with the multiplication of itself with the given one \"q1\"\n * @param q1 defines the second operand\n * @returns the currentupdated quaternion\n */\n Quaternion.prototype.multiplyInPlace = function (q1) {\n this.multiplyToRef(q1, this);\n return this;\n };\n /**\n * Conjugates (1-q) the current quaternion and stores the result in the given quaternion\n * @param ref defines the target quaternion\n * @returns the current quaternion\n */\n Quaternion.prototype.conjugateToRef = function (ref) {\n ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);\n return this;\n };\n /**\n * Conjugates in place (1-q) the current quaternion\n * @returns the current updated quaternion\n */\n Quaternion.prototype.conjugateInPlace = function () {\n this.x *= -1;\n this.y *= -1;\n this.z *= -1;\n return this;\n };\n /**\n * Conjugates in place (1-q) the current quaternion\n * @returns a new quaternion\n */\n Quaternion.prototype.conjugate = function () {\n var result = new Quaternion(-this.x, -this.y, -this.z, this.w);\n return result;\n };\n /**\n * Gets length of current quaternion\n * @returns the quaternion length (float)\n */\n Quaternion.prototype.length = function () {\n return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));\n };\n /**\n * Normalize in place the current quaternion\n * @returns the current updated quaternion\n */\n Quaternion.prototype.normalize = function () {\n var length = 1.0 / this.length();\n this.x *= length;\n this.y *= length;\n this.z *= length;\n this.w *= length;\n return this;\n };\n /**\n * Returns a new Vector3 set with the Euler angles translated from the current quaternion\n * @param order is a reserved parameter and is ignore for now\n * @returns a new Vector3 containing the Euler angles\n */\n Quaternion.prototype.toEulerAngles = function (order) {\n if (order === void 0) { order = \"YZX\"; }\n var result = Vector3.Zero();\n this.toEulerAnglesToRef(result, order);\n return result;\n };\n /**\n * Sets the given vector3 \"result\" with the Euler angles translated from the current quaternion\n * @param result defines the vector which will be filled with the Euler angles\n * @param order is a reserved parameter and is ignore for now\n * @returns the current unchanged quaternion\n */\n Quaternion.prototype.toEulerAnglesToRef = function (result, order) {\n if (order === void 0) { order = \"YZX\"; }\n var qz = this.z;\n var qx = this.x;\n var qy = this.y;\n var qw = this.w;\n var sqw = qw * qw;\n var sqz = qz * qz;\n var sqx = qx * qx;\n var sqy = qy * qy;\n var zAxisY = qy * qz - qx * qw;\n var limit = .4999999;\n if (zAxisY < -limit) {\n result.y = 2 * Math.atan2(qy, qw);\n result.x = Math.PI / 2;\n result.z = 0;\n }\n else if (zAxisY > limit) {\n result.y = 2 * Math.atan2(qy, qw);\n result.x = -Math.PI / 2;\n result.z = 0;\n }\n else {\n result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));\n result.x = Math.asin(-2.0 * (qz * qy - qx * qw));\n result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));\n }\n return this;\n };\n /**\n * Updates the given rotation matrix with the current quaternion values\n * @param result defines the target matrix\n * @returns the current unchanged quaternion\n */\n Quaternion.prototype.toRotationMatrix = function (result) {\n var xx = this.x * this.x;\n var yy = this.y * this.y;\n var zz = this.z * this.z;\n var xy = this.x * this.y;\n var zw = this.z * this.w;\n var zx = this.z * this.x;\n var yw = this.y * this.w;\n var yz = this.y * this.z;\n var xw = this.x * this.w;\n result.m[0] = 1.0 - (2.0 * (yy + zz));\n result.m[1] = 2.0 * (xy + zw);\n result.m[2] = 2.0 * (zx - yw);\n result.m[3] = 0;\n result.m[4] = 2.0 * (xy - zw);\n result.m[5] = 1.0 - (2.0 * (zz + xx));\n result.m[6] = 2.0 * (yz + xw);\n result.m[7] = 0;\n result.m[8] = 2.0 * (zx + yw);\n result.m[9] = 2.0 * (yz - xw);\n result.m[10] = 1.0 - (2.0 * (yy + xx));\n result.m[11] = 0;\n result.m[12] = 0;\n result.m[13] = 0;\n result.m[14] = 0;\n result.m[15] = 1.0;\n result._markAsUpdated();\n return this;\n };\n /**\n * Updates the current quaternion from the given rotation matrix values\n * @param matrix defines the source matrix\n * @returns the current updated quaternion\n */\n Quaternion.prototype.fromRotationMatrix = function (matrix) {\n Quaternion.FromRotationMatrixToRef(matrix, this);\n return this;\n };\n // Statics\n /**\n * Creates a new quaternion from a rotation matrix\n * @param matrix defines the source matrix\n * @returns a new quaternion created from the given rotation matrix values\n */\n Quaternion.FromRotationMatrix = function (matrix) {\n var result = new Quaternion();\n Quaternion.FromRotationMatrixToRef(matrix, result);\n return result;\n };\n /**\n * Updates the given quaternion with the given rotation matrix values\n * @param matrix defines the source matrix\n * @param result defines the target quaternion\n */\n Quaternion.FromRotationMatrixToRef = function (matrix, result) {\n var data = matrix.m;\n var m11 = data[0], m12 = data[4], m13 = data[8];\n var m21 = data[1], m22 = data[5], m23 = data[9];\n var m31 = data[2], m32 = data[6], m33 = data[10];\n var trace = m11 + m22 + m33;\n var s;\n if (trace > 0) {\n s = 0.5 / Math.sqrt(trace + 1.0);\n result.w = 0.25 / s;\n result.x = (m32 - m23) * s;\n result.y = (m13 - m31) * s;\n result.z = (m21 - m12) * s;\n }\n else if (m11 > m22 && m11 > m33) {\n s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);\n result.w = (m32 - m23) / s;\n result.x = 0.25 * s;\n result.y = (m12 + m21) / s;\n result.z = (m13 + m31) / s;\n }\n else if (m22 > m33) {\n s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);\n result.w = (m13 - m31) / s;\n result.x = (m12 + m21) / s;\n result.y = 0.25 * s;\n result.z = (m23 + m32) / s;\n }\n else {\n s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);\n result.w = (m21 - m12) / s;\n result.x = (m13 + m31) / s;\n result.y = (m23 + m32) / s;\n result.z = 0.25 * s;\n }\n };\n /**\n * Returns the dot product (float) between the quaternions \"left\" and \"right\"\n * @param left defines the left operand\n * @param right defines the right operand\n * @returns the dot product\n */\n Quaternion.Dot = function (left, right) {\n return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);\n };\n /**\n * Checks if the two quaternions are close to each other\n * @param quat0 defines the first quaternion to check\n * @param quat1 defines the second quaternion to check\n * @returns true if the two quaternions are close to each other\n */\n Quaternion.AreClose = function (quat0, quat1) {\n var dot = Quaternion.Dot(quat0, quat1);\n return dot >= 0;\n };\n /**\n * Creates an empty quaternion\n * @returns a new quaternion set to (0.0, 0.0, 0.0)\n */\n Quaternion.Zero = function () {\n return new Quaternion(0.0, 0.0, 0.0, 0.0);\n };\n /**\n * Inverse a given quaternion\n * @param q defines the source quaternion\n * @returns a new quaternion as the inverted current quaternion\n */\n Quaternion.Inverse = function (q) {\n return new Quaternion(-q.x, -q.y, -q.z, q.w);\n };\n /**\n * Creates an identity quaternion\n * @returns the identity quaternion\n */\n Quaternion.Identity = function () {\n return new Quaternion(0.0, 0.0, 0.0, 1.0);\n };\n /**\n * Gets a boolean indicating if the given quaternion is identity\n * @param quaternion defines the quaternion to check\n * @returns true if the quaternion is identity\n */\n Quaternion.IsIdentity = function (quaternion) {\n return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;\n };\n /**\n * Creates a quaternion from a rotation around an axis\n * @param axis defines the axis to use\n * @param angle defines the angle to use\n * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)\n */\n Quaternion.RotationAxis = function (axis, angle) {\n return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());\n };\n /**\n * Creates a rotation around an axis and stores it into the given quaternion\n * @param axis defines the axis to use\n * @param angle defines the angle to use\n * @param result defines the target quaternion\n * @returns the target quaternion\n */\n Quaternion.RotationAxisToRef = function (axis, angle, result) {\n var sin = Math.sin(angle / 2);\n axis.normalize();\n result.w = Math.cos(angle / 2);\n result.x = axis.x * sin;\n result.y = axis.y * sin;\n result.z = axis.z * sin;\n return result;\n };\n /**\n * Creates a new quaternion from data stored into an array\n * @param array defines the data source\n * @param offset defines the offset in the source array where the data starts\n * @returns a new quaternion\n */\n Quaternion.FromArray = function (array, offset) {\n if (!offset) {\n offset = 0;\n }\n return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n };\n /**\n * Creates a new quaternion from the given Euler float angles (y, x, z)\n * @param yaw defines the rotation around Y axis\n * @param pitch defines the rotation around X axis\n * @param roll defines the rotation around Z axis\n * @returns the new quaternion\n */\n Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {\n var q = new Quaternion();\n Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);\n return q;\n };\n /**\n * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion\n * @param yaw defines the rotation around Y axis\n * @param pitch defines the rotation around X axis\n * @param roll defines the rotation around Z axis\n * @param result defines the target quaternion\n */\n Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {\n // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)\n var halfRoll = roll * 0.5;\n var halfPitch = pitch * 0.5;\n var halfYaw = yaw * 0.5;\n var sinRoll = Math.sin(halfRoll);\n var cosRoll = Math.cos(halfRoll);\n var sinPitch = Math.sin(halfPitch);\n var cosPitch = Math.cos(halfPitch);\n var sinYaw = Math.sin(halfYaw);\n var cosYaw = Math.cos(halfYaw);\n result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);\n result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);\n result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);\n result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);\n };\n /**\n * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation\n * @param alpha defines the rotation around first axis\n * @param beta defines the rotation around second axis\n * @param gamma defines the rotation around third axis\n * @returns the new quaternion\n */\n Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {\n var result = new Quaternion();\n Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);\n return result;\n };\n /**\n * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion\n * @param alpha defines the rotation around first axis\n * @param beta defines the rotation around second axis\n * @param gamma defines the rotation around third axis\n * @param result defines the target quaternion\n */\n Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {\n // Produces a quaternion from Euler angles in the z-x-z orientation\n var halfGammaPlusAlpha = (gamma + alpha) * 0.5;\n var halfGammaMinusAlpha = (gamma - alpha) * 0.5;\n var halfBeta = beta * 0.5;\n result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);\n result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);\n result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);\n result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);\n };\n /**\n * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)\n * @param axis1 defines the first axis\n * @param axis2 defines the second axis\n * @param axis3 defines the third axis\n * @returns the new quaternion\n */\n Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {\n var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);\n Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);\n return quat;\n };\n /**\n * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion\n * @param axis1 defines the first axis\n * @param axis2 defines the second axis\n * @param axis3 defines the third axis\n * @param ref defines the target quaternion\n */\n Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {\n var rotMat = MathTmp.Matrix[0];\n Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);\n Quaternion.FromRotationMatrixToRef(rotMat, ref);\n };\n /**\n * Interpolates between two quaternions\n * @param left defines first quaternion\n * @param right defines second quaternion\n * @param amount defines the gradient to use\n * @returns the new interpolated quaternion\n */\n Quaternion.Slerp = function (left, right, amount) {\n var result = Quaternion.Identity();\n Quaternion.SlerpToRef(left, right, amount, result);\n return result;\n };\n /**\n * Interpolates between two quaternions and stores it into a target quaternion\n * @param left defines first quaternion\n * @param right defines second quaternion\n * @param amount defines the gradient to use\n * @param result defines the target quaternion\n */\n Quaternion.SlerpToRef = function (left, right, amount, result) {\n var num2;\n var num3;\n var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);\n var flag = false;\n if (num4 < 0) {\n flag = true;\n num4 = -num4;\n }\n if (num4 > 0.999999) {\n num3 = 1 - amount;\n num2 = flag ? -amount : amount;\n }\n else {\n var num5 = Math.acos(num4);\n var num6 = (1.0 / Math.sin(num5));\n num3 = (Math.sin((1.0 - amount) * num5)) * num6;\n num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);\n }\n result.x = (num3 * left.x) + (num2 * right.x);\n result.y = (num3 * left.y) + (num2 * right.y);\n result.z = (num3 * left.z) + (num2 * right.z);\n result.w = (num3 * left.w) + (num2 * right.w);\n };\n /**\n * Interpolate between two quaternions using Hermite interpolation\n * @param value1 defines first quaternion\n * @param tangent1 defines the incoming tangent\n * @param value2 defines second quaternion\n * @param tangent2 defines the outgoing tangent\n * @param amount defines the target quaternion\n * @returns the new interpolated quaternion\n */\n Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {\n var squared = amount * amount;\n var cubed = amount * squared;\n var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;\n var part2 = (-2.0 * cubed) + (3.0 * squared);\n var part3 = (cubed - (2.0 * squared)) + amount;\n var part4 = cubed - squared;\n var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);\n var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);\n var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);\n var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);\n return new Quaternion(x, y, z, w);\n };\n return Quaternion;\n }());\n BABYLON.Quaternion = Quaternion;\n /**\n * Class used to store matrix data (4x4)\n */\n var Matrix = /** @class */ (function () {\n /**\n * Creates an empty matrix (filled with zeros)\n */\n function Matrix() {\n this._isIdentity = false;\n this._isIdentityDirty = true;\n /**\n * Gets or sets the internal data of the matrix\n */\n this.m = new Float32Array(16);\n this._markAsUpdated();\n }\n /** @hidden */\n Matrix.prototype._markAsUpdated = function () {\n this.updateFlag = Matrix._updateFlagSeed++;\n this._isIdentityDirty = true;\n };\n // Properties\n /**\n * Check if the current matrix is indentity\n * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)\n * @returns true is the matrix is the identity matrix\n */\n Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {\n if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }\n if (this._isIdentityDirty) {\n this._isIdentityDirty = false;\n if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {\n this._isIdentity = false;\n }\n else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||\n this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||\n this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||\n this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {\n this._isIdentity = false;\n }\n else {\n this._isIdentity = true;\n }\n if (!considerAsTextureMatrix && this.m[10] !== 1.0) {\n this._isIdentity = false;\n }\n }\n return this._isIdentity;\n };\n /**\n * Gets the determinant of the matrix\n * @returns the matrix determinant\n */\n Matrix.prototype.determinant = function () {\n var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);\n var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);\n var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);\n var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);\n var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);\n var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);\n return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -\n (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -\n (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));\n };\n // Methods\n /**\n * Returns the matrix as a Float32Array\n * @returns the matrix underlying array\n */\n Matrix.prototype.toArray = function () {\n return this.m;\n };\n /**\n * Returns the matrix as a Float32Array\n * @returns the matrix underlying array.\n */\n Matrix.prototype.asArray = function () {\n return this.toArray();\n };\n /**\n * Inverts the current matrix in place\n * @returns the current inverted matrix\n */\n Matrix.prototype.invert = function () {\n this.invertToRef(this);\n return this;\n };\n /**\n * Sets all the matrix elements to zero\n * @returns the current matrix\n */\n Matrix.prototype.reset = function () {\n for (var index = 0; index < 16; index++) {\n this.m[index] = 0.0;\n }\n this._markAsUpdated();\n return this;\n };\n /**\n * Adds the current matrix with a second one\n * @param other defines the matrix to add\n * @returns a new matrix as the addition of the current matrix and the given one\n */\n Matrix.prototype.add = function (other) {\n var result = new Matrix();\n this.addToRef(other, result);\n return result;\n };\n /**\n * Sets the given matrix \"result\" to the addition of the current matrix and the given one\n * @param other defines the matrix to add\n * @param result defines the target matrix\n * @returns the current matrix\n */\n Matrix.prototype.addToRef = function (other, result) {\n for (var index = 0; index < 16; index++) {\n result.m[index] = this.m[index] + other.m[index];\n }\n result._markAsUpdated();\n return this;\n };\n /**\n * Adds in place the given matrix to the current matrix\n * @param other defines the second operand\n * @returns the current updated matrix\n */\n Matrix.prototype.addToSelf = function (other) {\n for (var index = 0; index < 16; index++) {\n this.m[index] += other.m[index];\n }\n this._markAsUpdated();\n return this;\n };\n /**\n * Sets the given matrix to the current inverted Matrix\n * @param other defines the target matrix\n * @returns the unmodified current matrix\n */\n Matrix.prototype.invertToRef = function (other) {\n var l1 = this.m[0];\n var l2 = this.m[1];\n var l3 = this.m[2];\n var l4 = this.m[3];\n var l5 = this.m[4];\n var l6 = this.m[5];\n var l7 = this.m[6];\n var l8 = this.m[7];\n var l9 = this.m[8];\n var l10 = this.m[9];\n var l11 = this.m[10];\n var l12 = this.m[11];\n var l13 = this.m[12];\n var l14 = this.m[13];\n var l15 = this.m[14];\n var l16 = this.m[15];\n var l17 = (l11 * l16) - (l12 * l15);\n var l18 = (l10 * l16) - (l12 * l14);\n var l19 = (l10 * l15) - (l11 * l14);\n var l20 = (l9 * l16) - (l12 * l13);\n var l21 = (l9 * l15) - (l11 * l13);\n var l22 = (l9 * l14) - (l10 * l13);\n var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);\n var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));\n var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);\n var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));\n var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));\n var l28 = (l7 * l16) - (l8 * l15);\n var l29 = (l6 * l16) - (l8 * l14);\n var l30 = (l6 * l15) - (l7 * l14);\n var l31 = (l5 * l16) - (l8 * l13);\n var l32 = (l5 * l15) - (l7 * l13);\n var l33 = (l5 * l14) - (l6 * l13);\n var l34 = (l7 * l12) - (l8 * l11);\n var l35 = (l6 * l12) - (l8 * l10);\n var l36 = (l6 * l11) - (l7 * l10);\n var l37 = (l5 * l12) - (l8 * l9);\n var l38 = (l5 * l11) - (l7 * l9);\n var l39 = (l5 * l10) - (l6 * l9);\n other.m[0] = l23 * l27;\n other.m[4] = l24 * l27;\n other.m[8] = l25 * l27;\n other.m[12] = l26 * l27;\n other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;\n other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;\n other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;\n other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;\n other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;\n other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;\n other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;\n other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;\n other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;\n other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;\n other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;\n other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;\n other._markAsUpdated();\n return this;\n };\n /**\n * Inserts the translation vector (using 3 floats) in the current matrix\n * @param x defines the 1st component of the translation\n * @param y defines the 2nd component of the translation\n * @param z defines the 3rd component of the translation\n * @returns the current updated matrix\n */\n Matrix.prototype.setTranslationFromFloats = function (x, y, z) {\n this.m[12] = x;\n this.m[13] = y;\n this.m[14] = z;\n this._markAsUpdated();\n return this;\n };\n /**\n * Inserts the translation vector in the current matrix\n * @param vector3 defines the translation to insert\n * @returns the current updated matrix\n */\n Matrix.prototype.setTranslation = function (vector3) {\n this.m[12] = vector3.x;\n this.m[13] = vector3.y;\n this.m[14] = vector3.z;\n this._markAsUpdated();\n return this;\n };\n /**\n * Gets the translation value of the current matrix\n * @returns a new Vector3 as the extracted translation from the matrix\n */\n Matrix.prototype.getTranslation = function () {\n return new Vector3(this.m[12], this.m[13], this.m[14]);\n };\n /**\n * Fill a Vector3 with the extracted translation from the matrix\n * @param result defines the Vector3 where to store the translation\n * @returns the current matrix\n */\n Matrix.prototype.getTranslationToRef = function (result) {\n result.x = this.m[12];\n result.y = this.m[13];\n result.z = this.m[14];\n return this;\n };\n /**\n * Remove rotation and scaling part from the matrix\n * @returns the updated matrix\n */\n Matrix.prototype.removeRotationAndScaling = function () {\n this.setRowFromFloats(0, 1, 0, 0, 0);\n this.setRowFromFloats(1, 0, 1, 0, 0);\n this.setRowFromFloats(2, 0, 0, 1, 0);\n return this;\n };\n /**\n * Multiply two matrices\n * @param other defines the second operand\n * @returns a new matrix set with the multiplication result of the current Matrix and the given one\n */\n Matrix.prototype.multiply = function (other) {\n var result = new Matrix();\n this.multiplyToRef(other, result);\n return result;\n };\n /**\n * Copy the current matrix from the given one\n * @param other defines the source matrix\n * @returns the current updated matrix\n */\n Matrix.prototype.copyFrom = function (other) {\n for (var index = 0; index < 16; index++) {\n this.m[index] = other.m[index];\n }\n this._markAsUpdated();\n return this;\n };\n /**\n * Populates the given array from the starting index with the current matrix values\n * @param array defines the target array\n * @param offset defines the offset in the target array where to start storing values\n * @returns the current matrix\n */\n Matrix.prototype.copyToArray = function (array, offset) {\n if (offset === void 0) { offset = 0; }\n for (var index = 0; index < 16; index++) {\n array[offset + index] = this.m[index];\n }\n return this;\n };\n /**\n * Sets the given matrix \"result\" with the multiplication result of the current Matrix and the given one\n * @param other defines the second operand\n * @param result defines the matrix where to store the multiplication\n * @returns the current matrix\n */\n Matrix.prototype.multiplyToRef = function (other, result) {\n this.multiplyToArray(other, result.m, 0);\n result._markAsUpdated();\n return this;\n };\n /**\n * Sets the Float32Array \"result\" from the given index \"offset\" with the multiplication of the current matrix and the given one\n * @param other defines the second operand\n * @param result defines the array where to store the multiplication\n * @param offset defines the offset in the target array where to start storing values\n * @returns the current matrix\n */\n Matrix.prototype.multiplyToArray = function (other, result, offset) {\n var tm0 = this.m[0];\n var tm1 = this.m[1];\n var tm2 = this.m[2];\n var tm3 = this.m[3];\n var tm4 = this.m[4];\n var tm5 = this.m[5];\n var tm6 = this.m[6];\n var tm7 = this.m[7];\n var tm8 = this.m[8];\n var tm9 = this.m[9];\n var tm10 = this.m[10];\n var tm11 = this.m[11];\n var tm12 = this.m[12];\n var tm13 = this.m[13];\n var tm14 = this.m[14];\n var tm15 = this.m[15];\n var om0 = other.m[0];\n var om1 = other.m[1];\n var om2 = other.m[2];\n var om3 = other.m[3];\n var om4 = other.m[4];\n var om5 = other.m[5];\n var om6 = other.m[6];\n var om7 = other.m[7];\n var om8 = other.m[8];\n var om9 = other.m[9];\n var om10 = other.m[10];\n var om11 = other.m[11];\n var om12 = other.m[12];\n var om13 = other.m[13];\n var om14 = other.m[14];\n var om15 = other.m[15];\n result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;\n result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;\n result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;\n result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;\n result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;\n result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;\n result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;\n result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;\n result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;\n result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;\n result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;\n result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;\n result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;\n result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;\n result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;\n result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;\n return this;\n };\n /**\n * Check equality between this matrix and a second one\n * @param value defines the second matrix to compare\n * @returns true is the current matrix and the given one values are strictly equal\n */\n Matrix.prototype.equals = function (value) {\n return value &&\n (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&\n this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&\n this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&\n this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);\n };\n /**\n * Clone the current matrix\n * @returns a new matrix from the current matrix\n */\n Matrix.prototype.clone = function () {\n return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);\n };\n /**\n * Returns the name of the current matrix class\n * @returns the string \"Matrix\"\n */\n Matrix.prototype.getClassName = function () {\n return \"Matrix\";\n };\n /**\n * Gets the hash code of the current matrix\n * @returns the hash code\n */\n Matrix.prototype.getHashCode = function () {\n var hash = this.m[0] || 0;\n for (var i = 1; i < 16; i++) {\n hash = (hash * 397) ^ (this.m[i] || 0);\n }\n return hash;\n };\n /**\n * Decomposes the current Matrix into a translation, rotation and scaling components\n * @param scale defines the scale vector3 given as a reference to update\n * @param rotation defines the rotation quaternion given as a reference to update\n * @param translation defines the translation vector3 given as a reference to update\n * @returns true if operation was successful\n */\n Matrix.prototype.decompose = function (scale, rotation, translation) {\n if (translation) {\n translation.x = this.m[12];\n translation.y = this.m[13];\n translation.z = this.m[14];\n }\n scale = scale || MathTmp.Vector3[0];\n scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);\n scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);\n scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);\n if (this.determinant() <= 0) {\n scale.y *= -1;\n }\n if (scale.x === 0 || scale.y === 0 || scale.z === 0) {\n if (rotation) {\n rotation.x = 0;\n rotation.y = 0;\n rotation.z = 0;\n rotation.w = 1;\n }\n return false;\n }\n if (rotation) {\n Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);\n Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);\n }\n return true;\n };\n /**\n * Gets specific row of the matrix\n * @param index defines the number of the row to get\n * @returns the index-th row of the current matrix as a new Vector4\n */\n Matrix.prototype.getRow = function (index) {\n if (index < 0 || index > 3) {\n return null;\n }\n var i = index * 4;\n return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);\n };\n /**\n * Sets the index-th row of the current matrix to the vector4 values\n * @param index defines the number of the row to set\n * @param row defines the target vector4\n * @returns the updated current matrix\n */\n Matrix.prototype.setRow = function (index, row) {\n if (index < 0 || index > 3) {\n return this;\n }\n var i = index * 4;\n this.m[i + 0] = row.x;\n this.m[i + 1] = row.y;\n this.m[i + 2] = row.z;\n this.m[i + 3] = row.w;\n this._markAsUpdated();\n return this;\n };\n /**\n * Compute the transpose of the matrix\n * @returns the new transposed matrix\n */\n Matrix.prototype.transpose = function () {\n return Matrix.Transpose(this);\n };\n /**\n * Compute the transpose of the matrix and store it in a given matrix\n * @param result defines the target matrix\n * @returns the current matrix\n */\n Matrix.prototype.transposeToRef = function (result) {\n Matrix.TransposeToRef(this, result);\n return this;\n };\n /**\n * Sets the index-th row of the current matrix with the given 4 x float values\n * @param index defines the row index\n * @param x defines the x component to set\n * @param y defines the y component to set\n * @param z defines the z component to set\n * @param w defines the w component to set\n * @returns the updated current matrix\n */\n Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {\n if (index < 0 || index > 3) {\n return this;\n }\n var i = index * 4;\n this.m[i + 0] = x;\n this.m[i + 1] = y;\n this.m[i + 2] = z;\n this.m[i + 3] = w;\n this._markAsUpdated();\n return this;\n };\n /**\n * Compute a new matrix set with the current matrix values multiplied by scale (float)\n * @param scale defines the scale factor\n * @returns a new matrix\n */\n Matrix.prototype.scale = function (scale) {\n var result = new Matrix();\n this.scaleToRef(scale, result);\n return result;\n };\n /**\n * Scale the current matrix values by a factor to a given result matrix\n * @param scale defines the scale factor\n * @param result defines the matrix to store the result\n * @returns the current matrix\n */\n Matrix.prototype.scaleToRef = function (scale, result) {\n for (var index = 0; index < 16; index++) {\n result.m[index] = this.m[index] * scale;\n }\n result._markAsUpdated();\n return this;\n };\n /**\n * Scale the current matrix values by a factor and add the result to a given matrix\n * @param scale defines the scale factor\n * @param result defines the Matrix to store the result\n * @returns the current matrix\n */\n Matrix.prototype.scaleAndAddToRef = function (scale, result) {\n for (var index = 0; index < 16; index++) {\n result.m[index] += this.m[index] * scale;\n }\n result._markAsUpdated();\n return this;\n };\n /**\n * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).\n * @param ref matrix to store the result\n */\n Matrix.prototype.toNormalMatrix = function (ref) {\n this.invertToRef(ref);\n ref.transpose();\n var m = ref.m;\n Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);\n };\n /**\n * Gets only rotation part of the current matrix\n * @returns a new matrix sets to the extracted rotation matrix from the current one\n */\n Matrix.prototype.getRotationMatrix = function () {\n var result = Matrix.Identity();\n this.getRotationMatrixToRef(result);\n return result;\n };\n /**\n * Extracts the rotation matrix from the current one and sets it as the given \"result\"\n * @param result defines the target matrix to store data to\n * @returns the current matrix\n */\n Matrix.prototype.getRotationMatrixToRef = function (result) {\n var m = this.m;\n var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);\n var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);\n var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);\n if (this.determinant() <= 0) {\n sy *= -1;\n }\n if (sx === 0 || sy === 0 || sz === 0) {\n Matrix.IdentityToRef(result);\n }\n else {\n Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);\n }\n return this;\n };\n // Statics\n /**\n * Creates a matrix from an array\n * @param array defines the source array\n * @param offset defines an offset in the source array\n * @returns a new Matrix set from the starting index of the given array\n */\n Matrix.FromArray = function (array, offset) {\n var result = new Matrix();\n if (!offset) {\n offset = 0;\n }\n Matrix.FromArrayToRef(array, offset, result);\n return result;\n };\n /**\n * Copy the content of an array into a given matrix\n * @param array defines the source array\n * @param offset defines an offset in the source array\n * @param result defines the target matrix\n */\n Matrix.FromArrayToRef = function (array, offset, result) {\n for (var index = 0; index < 16; index++) {\n result.m[index] = array[index + offset];\n }\n result._markAsUpdated();\n };\n /**\n * Stores an array into a matrix after having multiplied each component by a given factor\n * @param array defines the source array\n * @param offset defines the offset in the source array\n * @param scale defines the scaling factor\n * @param result defines the target matrix\n */\n Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {\n for (var index = 0; index < 16; index++) {\n result.m[index] = array[index + offset] * scale;\n }\n result._markAsUpdated();\n };\n /**\n * Stores a list of values (16) inside a given matrix\n * @param initialM11 defines 1st value of 1st row\n * @param initialM12 defines 2nd value of 1st row\n * @param initialM13 defines 3rd value of 1st row\n * @param initialM14 defines 4th value of 1st row\n * @param initialM21 defines 1st value of 2nd row\n * @param initialM22 defines 2nd value of 2nd row\n * @param initialM23 defines 3rd value of 2nd row\n * @param initialM24 defines 4th value of 2nd row\n * @param initialM31 defines 1st value of 3rd row\n * @param initialM32 defines 2nd value of 3rd row\n * @param initialM33 defines 3rd value of 3rd row\n * @param initialM34 defines 4th value of 3rd row\n * @param initialM41 defines 1st value of 4th row\n * @param initialM42 defines 2nd value of 4th row\n * @param initialM43 defines 3rd value of 4th row\n * @param initialM44 defines 4th value of 4th row\n * @param result defines the target matrix\n */\n Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {\n result.m[0] = initialM11;\n result.m[1] = initialM12;\n result.m[2] = initialM13;\n result.m[3] = initialM14;\n result.m[4] = initialM21;\n result.m[5] = initialM22;\n result.m[6] = initialM23;\n result.m[7] = initialM24;\n result.m[8] = initialM31;\n result.m[9] = initialM32;\n result.m[10] = initialM33;\n result.m[11] = initialM34;\n result.m[12] = initialM41;\n result.m[13] = initialM42;\n result.m[14] = initialM43;\n result.m[15] = initialM44;\n result._markAsUpdated();\n };\n Object.defineProperty(Matrix, \"IdentityReadOnly\", {\n /**\n * Gets an identity matrix that must not be updated\n */\n get: function () {\n return Matrix._identityReadOnly;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Creates new matrix from a list of values (16)\n * @param initialM11 defines 1st value of 1st row\n * @param initialM12 defines 2nd value of 1st row\n * @param initialM13 defines 3rd value of 1st row\n * @param initialM14 defines 4th value of 1st row\n * @param initialM21 defines 1st value of 2nd row\n * @param initialM22 defines 2nd value of 2nd row\n * @param initialM23 defines 3rd value of 2nd row\n * @param initialM24 defines 4th value of 2nd row\n * @param initialM31 defines 1st value of 3rd row\n * @param initialM32 defines 2nd value of 3rd row\n * @param initialM33 defines 3rd value of 3rd row\n * @param initialM34 defines 4th value of 3rd row\n * @param initialM41 defines 1st value of 4th row\n * @param initialM42 defines 2nd value of 4th row\n * @param initialM43 defines 3rd value of 4th row\n * @param initialM44 defines 4th value of 4th row\n * @returns the new matrix\n */\n Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {\n var result = new Matrix();\n result.m[0] = initialM11;\n result.m[1] = initialM12;\n result.m[2] = initialM13;\n result.m[3] = initialM14;\n result.m[4] = initialM21;\n result.m[5] = initialM22;\n result.m[6] = initialM23;\n result.m[7] = initialM24;\n result.m[8] = initialM31;\n result.m[9] = initialM32;\n result.m[10] = initialM33;\n result.m[11] = initialM34;\n result.m[12] = initialM41;\n result.m[13] = initialM42;\n result.m[14] = initialM43;\n result.m[15] = initialM44;\n return result;\n };\n /**\n * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)\n * @param scale defines the scale vector3\n * @param rotation defines the rotation quaternion\n * @param translation defines the translation vector3\n * @returns a new matrix\n */\n Matrix.Compose = function (scale, rotation, translation) {\n var result = Matrix.Identity();\n Matrix.ComposeToRef(scale, rotation, translation, result);\n return result;\n };\n /**\n * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)\n * @param scale defines the scale vector3\n * @param rotation defines the rotation quaternion\n * @param translation defines the translation vector3\n * @param result defines the target matrix\n */\n Matrix.ComposeToRef = function (scale, rotation, translation, result) {\n Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);\n rotation.toRotationMatrix(MathTmp.Matrix[0]);\n MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);\n result.setTranslation(translation);\n };\n /**\n * Creates a new identity matrix\n * @returns a new identity matrix\n */\n Matrix.Identity = function () {\n return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n };\n /**\n * Creates a new identity matrix and stores the result in a given matrix\n * @param result defines the target matrix\n */\n Matrix.IdentityToRef = function (result) {\n Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);\n };\n /**\n * Creates a new zero matrix\n * @returns a new zero matrix\n */\n Matrix.Zero = function () {\n return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the X axis\n * @param angle defines the angle (in radians) to use\n * @return the new matrix\n */\n Matrix.RotationX = function (angle) {\n var result = new Matrix();\n Matrix.RotationXToRef(angle, result);\n return result;\n };\n /**\n * Creates a new matrix as the invert of a given matrix\n * @param source defines the source matrix\n * @returns the new matrix\n */\n Matrix.Invert = function (source) {\n var result = new Matrix();\n source.invertToRef(result);\n return result;\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the X axis and stores it in a given matrix\n * @param angle defines the angle (in radians) to use\n * @param result defines the target matrix\n */\n Matrix.RotationXToRef = function (angle, result) {\n var s = Math.sin(angle);\n var c = Math.cos(angle);\n result.m[0] = 1.0;\n result.m[15] = 1.0;\n result.m[5] = c;\n result.m[10] = c;\n result.m[9] = -s;\n result.m[6] = s;\n result.m[1] = 0.0;\n result.m[2] = 0.0;\n result.m[3] = 0.0;\n result.m[4] = 0.0;\n result.m[7] = 0.0;\n result.m[8] = 0.0;\n result.m[11] = 0.0;\n result.m[12] = 0.0;\n result.m[13] = 0.0;\n result.m[14] = 0.0;\n result._markAsUpdated();\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the Y axis\n * @param angle defines the angle (in radians) to use\n * @return the new matrix\n */\n Matrix.RotationY = function (angle) {\n var result = new Matrix();\n Matrix.RotationYToRef(angle, result);\n return result;\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the Y axis and stores it in a given matrix\n * @param angle defines the angle (in radians) to use\n * @param result defines the target matrix\n */\n Matrix.RotationYToRef = function (angle, result) {\n var s = Math.sin(angle);\n var c = Math.cos(angle);\n result.m[5] = 1.0;\n result.m[15] = 1.0;\n result.m[0] = c;\n result.m[2] = -s;\n result.m[8] = s;\n result.m[10] = c;\n result.m[1] = 0.0;\n result.m[3] = 0.0;\n result.m[4] = 0.0;\n result.m[6] = 0.0;\n result.m[7] = 0.0;\n result.m[9] = 0.0;\n result.m[11] = 0.0;\n result.m[12] = 0.0;\n result.m[13] = 0.0;\n result.m[14] = 0.0;\n result._markAsUpdated();\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the Z axis\n * @param angle defines the angle (in radians) to use\n * @return the new matrix\n */\n Matrix.RotationZ = function (angle) {\n var result = new Matrix();\n Matrix.RotationZToRef(angle, result);\n return result;\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the Z axis and stores it in a given matrix\n * @param angle defines the angle (in radians) to use\n * @param result defines the target matrix\n */\n Matrix.RotationZToRef = function (angle, result) {\n var s = Math.sin(angle);\n var c = Math.cos(angle);\n result.m[10] = 1.0;\n result.m[15] = 1.0;\n result.m[0] = c;\n result.m[1] = s;\n result.m[4] = -s;\n result.m[5] = c;\n result.m[2] = 0.0;\n result.m[3] = 0.0;\n result.m[6] = 0.0;\n result.m[7] = 0.0;\n result.m[8] = 0.0;\n result.m[9] = 0.0;\n result.m[11] = 0.0;\n result.m[12] = 0.0;\n result.m[13] = 0.0;\n result.m[14] = 0.0;\n result._markAsUpdated();\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the given axis\n * @param axis defines the axis to use\n * @param angle defines the angle (in radians) to use\n * @return the new matrix\n */\n Matrix.RotationAxis = function (axis, angle) {\n var result = Matrix.Zero();\n Matrix.RotationAxisToRef(axis, angle, result);\n return result;\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the given axis and stores it in a given matrix\n * @param axis defines the axis to use\n * @param angle defines the angle (in radians) to use\n * @param result defines the target matrix\n */\n Matrix.RotationAxisToRef = function (axis, angle, result) {\n var s = Math.sin(-angle);\n var c = Math.cos(-angle);\n var c1 = 1 - c;\n axis.normalize();\n result.m[0] = (axis.x * axis.x) * c1 + c;\n result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);\n result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);\n result.m[3] = 0.0;\n result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);\n result.m[5] = (axis.y * axis.y) * c1 + c;\n result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);\n result.m[7] = 0.0;\n result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);\n result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);\n result.m[10] = (axis.z * axis.z) * c1 + c;\n result.m[11] = 0.0;\n result.m[15] = 1.0;\n result._markAsUpdated();\n };\n /**\n * Creates a rotation matrix\n * @param yaw defines the yaw angle in radians (Y axis)\n * @param pitch defines the pitch angle in radians (X axis)\n * @param roll defines the roll angle in radians (X axis)\n * @returns the new rotation matrix\n */\n Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {\n var result = new Matrix();\n Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);\n return result;\n };\n /**\n * Creates a rotation matrix and stores it in a given matrix\n * @param yaw defines the yaw angle in radians (Y axis)\n * @param pitch defines the pitch angle in radians (X axis)\n * @param roll defines the roll angle in radians (X axis)\n * @param result defines the target matrix\n */\n Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {\n Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);\n this._tempQuaternion.toRotationMatrix(result);\n };\n /**\n * Creates a scaling matrix\n * @param x defines the scale factor on X axis\n * @param y defines the scale factor on Y axis\n * @param z defines the scale factor on Z axis\n * @returns the new matrix\n */\n Matrix.Scaling = function (x, y, z) {\n var result = Matrix.Zero();\n Matrix.ScalingToRef(x, y, z, result);\n return result;\n };\n /**\n * Creates a scaling matrix and stores it in a given matrix\n * @param x defines the scale factor on X axis\n * @param y defines the scale factor on Y axis\n * @param z defines the scale factor on Z axis\n * @param result defines the target matrix\n */\n Matrix.ScalingToRef = function (x, y, z, result) {\n result.m[0] = x;\n result.m[1] = 0.0;\n result.m[2] = 0.0;\n result.m[3] = 0.0;\n result.m[4] = 0.0;\n result.m[5] = y;\n result.m[6] = 0.0;\n result.m[7] = 0.0;\n result.m[8] = 0.0;\n result.m[9] = 0.0;\n result.m[10] = z;\n result.m[11] = 0.0;\n result.m[12] = 0.0;\n result.m[13] = 0.0;\n result.m[14] = 0.0;\n result.m[15] = 1.0;\n result._markAsUpdated();\n };\n /**\n * Creates a translation matrix\n * @param x defines the translation on X axis\n * @param y defines the translation on Y axis\n * @param z defines the translationon Z axis\n * @returns the new matrix\n */\n Matrix.Translation = function (x, y, z) {\n var result = Matrix.Identity();\n Matrix.TranslationToRef(x, y, z, result);\n return result;\n };\n /**\n * Creates a translation matrix and stores it in a given matrix\n * @param x defines the translation on X axis\n * @param y defines the translation on Y axis\n * @param z defines the translationon Z axis\n * @param result defines the target matrix\n */\n Matrix.TranslationToRef = function (x, y, z, result) {\n Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);\n };\n /**\n * Returns a new Matrix whose values are the interpolated values for \"gradient\" (float) between the ones of the matrices \"startValue\" and \"endValue\".\n * @param startValue defines the start value\n * @param endValue defines the end value\n * @param gradient defines the gradient factor\n * @returns the new matrix\n */\n Matrix.Lerp = function (startValue, endValue, gradient) {\n var result = Matrix.Zero();\n Matrix.LerpToRef(startValue, endValue, gradient, result);\n return result;\n };\n /**\n * Set the given matrix \"result\" as the interpolated values for \"gradient\" (float) between the ones of the matrices \"startValue\" and \"endValue\".\n * @param startValue defines the start value\n * @param endValue defines the end value\n * @param gradient defines the gradient factor\n * @param result defines the Matrix object where to store data\n */\n Matrix.LerpToRef = function (startValue, endValue, gradient, result) {\n for (var index = 0; index < 16; index++) {\n result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;\n }\n result._markAsUpdated();\n };\n /**\n * Builds a new matrix whose values are computed by:\n * * decomposing the the \"startValue\" and \"endValue\" matrices into their respective scale, rotation and translation matrices\n * * interpolating for \"gradient\" (float) the values between each of these decomposed matrices between the start and the end\n * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices\n * @param startValue defines the first matrix\n * @param endValue defines the second matrix\n * @param gradient defines the gradient between the two matrices\n * @returns the new matrix\n */\n Matrix.DecomposeLerp = function (startValue, endValue, gradient) {\n var result = Matrix.Zero();\n Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);\n return result;\n };\n /**\n * Update a matrix to values which are computed by:\n * * decomposing the the \"startValue\" and \"endValue\" matrices into their respective scale, rotation and translation matrices\n * * interpolating for \"gradient\" (float) the values between each of these decomposed matrices between the start and the end\n * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices\n * @param startValue defines the first matrix\n * @param endValue defines the second matrix\n * @param gradient defines the gradient between the two matrices\n * @param result defines the target matrix\n */\n Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {\n var startScale = MathTmp.Vector3[0];\n var startRotation = MathTmp.Quaternion[0];\n var startTranslation = MathTmp.Vector3[1];\n startValue.decompose(startScale, startRotation, startTranslation);\n var endScale = MathTmp.Vector3[2];\n var endRotation = MathTmp.Quaternion[1];\n var endTranslation = MathTmp.Vector3[3];\n endValue.decompose(endScale, endRotation, endTranslation);\n var resultScale = MathTmp.Vector3[4];\n Vector3.LerpToRef(startScale, endScale, gradient, resultScale);\n var resultRotation = MathTmp.Quaternion[2];\n Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);\n var resultTranslation = MathTmp.Vector3[5];\n Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);\n Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);\n };\n /**\n * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like \"up\"\n * This function works in left handed mode\n * @param eye defines the final position of the entity\n * @param target defines where the entity should look at\n * @param up defines the up vector for the entity\n * @returns the new matrix\n */\n Matrix.LookAtLH = function (eye, target, up) {\n var result = Matrix.Zero();\n Matrix.LookAtLHToRef(eye, target, up, result);\n return result;\n };\n /**\n * Sets the given \"result\" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like \"up\".\n * This function works in left handed mode\n * @param eye defines the final position of the entity\n * @param target defines where the entity should look at\n * @param up defines the up vector for the entity\n * @param result defines the target matrix\n */\n Matrix.LookAtLHToRef = function (eye, target, up, result) {\n // Z axis\n target.subtractToRef(eye, this._zAxis);\n this._zAxis.normalize();\n // X axis\n Vector3.CrossToRef(up, this._zAxis, this._xAxis);\n if (this._xAxis.lengthSquared() === 0) {\n this._xAxis.x = 1.0;\n }\n else {\n this._xAxis.normalize();\n }\n // Y axis\n Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);\n this._yAxis.normalize();\n // Eye angles\n var ex = -Vector3.Dot(this._xAxis, eye);\n var ey = -Vector3.Dot(this._yAxis, eye);\n var ez = -Vector3.Dot(this._zAxis, eye);\n return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);\n };\n /**\n * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like \"up\"\n * This function works in right handed mode\n * @param eye defines the final position of the entity\n * @param target defines where the entity should look at\n * @param up defines the up vector for the entity\n * @returns the new matrix\n */\n Matrix.LookAtRH = function (eye, target, up) {\n var result = Matrix.Zero();\n Matrix.LookAtRHToRef(eye, target, up, result);\n return result;\n };\n /**\n * Sets the given \"result\" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like \"up\".\n * This function works in right handed mode\n * @param eye defines the final position of the entity\n * @param target defines where the entity should look at\n * @param up defines the up vector for the entity\n * @param result defines the target matrix\n */\n Matrix.LookAtRHToRef = function (eye, target, up, result) {\n // Z axis\n eye.subtractToRef(target, this._zAxis);\n this._zAxis.normalize();\n // X axis\n Vector3.CrossToRef(up, this._zAxis, this._xAxis);\n if (this._xAxis.lengthSquared() === 0) {\n this._xAxis.x = 1.0;\n }\n else {\n this._xAxis.normalize();\n }\n // Y axis\n Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);\n this._yAxis.normalize();\n // Eye angles\n var ex = -Vector3.Dot(this._xAxis, eye);\n var ey = -Vector3.Dot(this._yAxis, eye);\n var ez = -Vector3.Dot(this._zAxis, eye);\n return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);\n };\n /**\n * Create a left-handed orthographic projection matrix\n * @param width defines the viewport width\n * @param height defines the viewport height\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @returns a new matrix as a left-handed orthographic projection matrix\n */\n Matrix.OrthoLH = function (width, height, znear, zfar) {\n var matrix = Matrix.Zero();\n Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);\n return matrix;\n };\n /**\n * Store a left-handed orthographic projection to a given matrix\n * @param width defines the viewport width\n * @param height defines the viewport height\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @param result defines the target matrix\n */\n Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {\n var n = znear;\n var f = zfar;\n var a = 2.0 / width;\n var b = 2.0 / height;\n var c = 2.0 / (f - n);\n var d = -(f + n) / (f - n);\n Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);\n };\n /**\n * Create a left-handed orthographic projection matrix\n * @param left defines the viewport left coordinate\n * @param right defines the viewport right coordinate\n * @param bottom defines the viewport bottom coordinate\n * @param top defines the viewport top coordinate\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @returns a new matrix as a left-handed orthographic projection matrix\n */\n Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {\n var matrix = Matrix.Zero();\n Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);\n return matrix;\n };\n /**\n * Stores a left-handed orthographic projection into a given matrix\n * @param left defines the viewport left coordinate\n * @param right defines the viewport right coordinate\n * @param bottom defines the viewport bottom coordinate\n * @param top defines the viewport top coordinate\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @param result defines the target matrix\n */\n Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {\n var n = znear;\n var f = zfar;\n var a = 2.0 / (right - left);\n var b = 2.0 / (top - bottom);\n var c = 2.0 / (f - n);\n var d = -(f + n) / (f - n);\n var i0 = (left + right) / (left - right);\n var i1 = (top + bottom) / (bottom - top);\n Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);\n };\n /**\n * Creates a right-handed orthographic projection matrix\n * @param left defines the viewport left coordinate\n * @param right defines the viewport right coordinate\n * @param bottom defines the viewport bottom coordinate\n * @param top defines the viewport top coordinate\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @returns a new matrix as a right-handed orthographic projection matrix\n */\n Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {\n var matrix = Matrix.Zero();\n Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);\n return matrix;\n };\n /**\n * Stores a right-handed orthographic projection into a given matrix\n * @param left defines the viewport left coordinate\n * @param right defines the viewport right coordinate\n * @param bottom defines the viewport bottom coordinate\n * @param top defines the viewport top coordinate\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @param result defines the target matrix\n */\n Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {\n Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);\n result.m[10] *= -1.0;\n };\n /**\n * Creates a left-handed perspective projection matrix\n * @param width defines the viewport width\n * @param height defines the viewport height\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @returns a new matrix as a left-handed perspective projection matrix\n */\n Matrix.PerspectiveLH = function (width, height, znear, zfar) {\n var matrix = Matrix.Zero();\n var n = znear;\n var f = zfar;\n var a = 2.0 * n / width;\n var b = 2.0 * n / height;\n var c = (f + n) / (f - n);\n var d = -2.0 * f * n / (f - n);\n Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);\n return matrix;\n };\n /**\n * Creates a left-handed perspective projection matrix\n * @param fov defines the horizontal field of view\n * @param aspect defines the aspect ratio\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @returns a new matrix as a left-handed perspective projection matrix\n */\n Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {\n var matrix = Matrix.Zero();\n Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);\n return matrix;\n };\n /**\n * Stores a left-handed perspective projection into a given matrix\n * @param fov defines the horizontal field of view\n * @param aspect defines the aspect ratio\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @param result defines the target matrix\n * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally\n */\n Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {\n if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }\n var n = znear;\n var f = zfar;\n var t = 1.0 / (Math.tan(fov * 0.5));\n var a = isVerticalFovFixed ? (t / aspect) : t;\n var b = isVerticalFovFixed ? t : (t * aspect);\n var c = (f + n) / (f - n);\n var d = -2.0 * f * n / (f - n);\n Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);\n };\n /**\n * Creates a right-handed perspective projection matrix\n * @param fov defines the horizontal field of view\n * @param aspect defines the aspect ratio\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @returns a new matrix as a right-handed perspective projection matrix\n */\n Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {\n var matrix = Matrix.Zero();\n Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);\n return matrix;\n };\n /**\n * Stores a right-handed perspective projection into a given matrix\n * @param fov defines the horizontal field of view\n * @param aspect defines the aspect ratio\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @param result defines the target matrix\n * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally\n */\n Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {\n //alternatively this could be expressed as:\n // m = PerspectiveFovLHToRef\n // m[10] *= -1.0;\n // m[11] *= -1.0;\n if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }\n var n = znear;\n var f = zfar;\n var t = 1.0 / (Math.tan(fov * 0.5));\n var a = isVerticalFovFixed ? (t / aspect) : t;\n var b = isVerticalFovFixed ? t : (t * aspect);\n var c = -(f + n) / (f - n);\n var d = -2 * f * n / (f - n);\n Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);\n };\n /**\n * Stores a perspective projection for WebVR info a given matrix\n * @param fov defines the field of view\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @param result defines the target matrix\n * @param rightHanded defines if the matrix must be in right-handed mode (false by default)\n */\n Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {\n if (rightHanded === void 0) { rightHanded = false; }\n var rightHandedFactor = rightHanded ? -1 : 1;\n var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);\n var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);\n var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);\n var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);\n var xScale = 2.0 / (leftTan + rightTan);\n var yScale = 2.0 / (upTan + downTan);\n result.m[0] = xScale;\n result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;\n result.m[5] = yScale;\n result.m[6] = result.m[7] = 0.0;\n result.m[8] = ((leftTan - rightTan) * xScale * 0.5);\n result.m[9] = -((upTan - downTan) * yScale * 0.5);\n result.m[10] = -zfar / (znear - zfar);\n result.m[11] = 1.0 * rightHandedFactor;\n result.m[12] = result.m[13] = result.m[15] = 0.0;\n result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);\n result._markAsUpdated();\n };\n /**\n * Computes a complete transformation matrix\n * @param viewport defines the viewport to use\n * @param world defines the world matrix\n * @param view defines the view matrix\n * @param projection defines the projection matrix\n * @param zmin defines the near clip plane\n * @param zmax defines the far clip plane\n * @returns the transformation matrix\n */\n Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {\n var cw = viewport.width;\n var ch = viewport.height;\n var cx = viewport.x;\n var cy = viewport.y;\n var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);\n return world.multiply(view).multiply(projection).multiply(viewportMatrix);\n };\n /**\n * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array\n * @param matrix defines the matrix to use\n * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix\n */\n Matrix.GetAsMatrix2x2 = function (matrix) {\n return new Float32Array([\n matrix.m[0], matrix.m[1],\n matrix.m[4], matrix.m[5]\n ]);\n };\n /**\n * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array\n * @param matrix defines the matrix to use\n * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix\n */\n Matrix.GetAsMatrix3x3 = function (matrix) {\n return new Float32Array([\n matrix.m[0], matrix.m[1], matrix.m[2],\n matrix.m[4], matrix.m[5], matrix.m[6],\n matrix.m[8], matrix.m[9], matrix.m[10]\n ]);\n };\n /**\n * Compute the transpose of a given matrix\n * @param matrix defines the matrix to transpose\n * @returns the new matrix\n */\n Matrix.Transpose = function (matrix) {\n var result = new Matrix();\n Matrix.TransposeToRef(matrix, result);\n return result;\n };\n /**\n * Compute the transpose of a matrix and store it in a target matrix\n * @param matrix defines the matrix to transpose\n * @param result defines the target matrix\n */\n Matrix.TransposeToRef = function (matrix, result) {\n result.m[0] = matrix.m[0];\n result.m[1] = matrix.m[4];\n result.m[2] = matrix.m[8];\n result.m[3] = matrix.m[12];\n result.m[4] = matrix.m[1];\n result.m[5] = matrix.m[5];\n result.m[6] = matrix.m[9];\n result.m[7] = matrix.m[13];\n result.m[8] = matrix.m[2];\n result.m[9] = matrix.m[6];\n result.m[10] = matrix.m[10];\n result.m[11] = matrix.m[14];\n result.m[12] = matrix.m[3];\n result.m[13] = matrix.m[7];\n result.m[14] = matrix.m[11];\n result.m[15] = matrix.m[15];\n };\n /**\n * Computes a reflection matrix from a plane\n * @param plane defines the reflection plane\n * @returns a new matrix\n */\n Matrix.Reflection = function (plane) {\n var matrix = new Matrix();\n Matrix.ReflectionToRef(plane, matrix);\n return matrix;\n };\n /**\n * Computes a reflection matrix from a plane\n * @param plane defines the reflection plane\n * @param result defines the target matrix\n */\n Matrix.ReflectionToRef = function (plane, result) {\n plane.normalize();\n var x = plane.normal.x;\n var y = plane.normal.y;\n var z = plane.normal.z;\n var temp = -2 * x;\n var temp2 = -2 * y;\n var temp3 = -2 * z;\n result.m[0] = (temp * x) + 1;\n result.m[1] = temp2 * x;\n result.m[2] = temp3 * x;\n result.m[3] = 0.0;\n result.m[4] = temp * y;\n result.m[5] = (temp2 * y) + 1;\n result.m[6] = temp3 * y;\n result.m[7] = 0.0;\n result.m[8] = temp * z;\n result.m[9] = temp2 * z;\n result.m[10] = (temp3 * z) + 1;\n result.m[11] = 0.0;\n result.m[12] = temp * plane.d;\n result.m[13] = temp2 * plane.d;\n result.m[14] = temp3 * plane.d;\n result.m[15] = 1.0;\n result._markAsUpdated();\n };\n /**\n * Sets the given matrix as a rotation matrix composed from the 3 left handed axes\n * @param xaxis defines the value of the 1st axis\n * @param yaxis defines the value of the 2nd axis\n * @param zaxis defines the value of the 3rd axis\n * @param result defines the target matrix\n */\n Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {\n result.m[0] = xaxis.x;\n result.m[1] = xaxis.y;\n result.m[2] = xaxis.z;\n result.m[3] = 0.0;\n result.m[4] = yaxis.x;\n result.m[5] = yaxis.y;\n result.m[6] = yaxis.z;\n result.m[7] = 0.0;\n result.m[8] = zaxis.x;\n result.m[9] = zaxis.y;\n result.m[10] = zaxis.z;\n result.m[11] = 0.0;\n result.m[12] = 0.0;\n result.m[13] = 0.0;\n result.m[14] = 0.0;\n result.m[15] = 1.0;\n result._markAsUpdated();\n };\n /**\n * Creates a rotation matrix from a quaternion and stores it in a target matrix\n * @param quat defines the quaternion to use\n * @param result defines the target matrix\n */\n Matrix.FromQuaternionToRef = function (quat, result) {\n var xx = quat.x * quat.x;\n var yy = quat.y * quat.y;\n var zz = quat.z * quat.z;\n var xy = quat.x * quat.y;\n var zw = quat.z * quat.w;\n var zx = quat.z * quat.x;\n var yw = quat.y * quat.w;\n var yz = quat.y * quat.z;\n var xw = quat.x * quat.w;\n result.m[0] = 1.0 - (2.0 * (yy + zz));\n result.m[1] = 2.0 * (xy + zw);\n result.m[2] = 2.0 * (zx - yw);\n result.m[3] = 0.0;\n result.m[4] = 2.0 * (xy - zw);\n result.m[5] = 1.0 - (2.0 * (zz + xx));\n result.m[6] = 2.0 * (yz + xw);\n result.m[7] = 0.0;\n result.m[8] = 2.0 * (zx + yw);\n result.m[9] = 2.0 * (yz - xw);\n result.m[10] = 1.0 - (2.0 * (yy + xx));\n result.m[11] = 0.0;\n result.m[12] = 0.0;\n result.m[13] = 0.0;\n result.m[14] = 0.0;\n result.m[15] = 1.0;\n result._markAsUpdated();\n };\n Matrix._tempQuaternion = new Quaternion();\n Matrix._xAxis = Vector3.Zero();\n Matrix._yAxis = Vector3.Zero();\n Matrix._zAxis = Vector3.Zero();\n Matrix._updateFlagSeed = 0;\n Matrix._identityReadOnly = Matrix.Identity();\n return Matrix;\n }());\n BABYLON.Matrix = Matrix;\n var Plane = /** @class */ (function () {\n /**\n * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0\n */\n function Plane(a, b, c, d) {\n this.normal = new Vector3(a, b, c);\n this.d = d;\n }\n /**\n * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].\n */\n Plane.prototype.asArray = function () {\n return [this.normal.x, this.normal.y, this.normal.z, this.d];\n };\n // Methods\n /**\n * Returns a new plane copied from the current Plane.\n */\n Plane.prototype.clone = function () {\n return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);\n };\n /**\n * Returns the string \"Plane\".\n */\n Plane.prototype.getClassName = function () {\n return \"Plane\";\n };\n /**\n * Returns the Plane hash code.\n */\n Plane.prototype.getHashCode = function () {\n var hash = this.normal.getHashCode();\n hash = (hash * 397) ^ (this.d || 0);\n return hash;\n };\n /**\n * Normalize the current Plane in place.\n * Returns the updated Plane.\n */\n Plane.prototype.normalize = function () {\n var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));\n var magnitude = 0.0;\n if (norm !== 0) {\n magnitude = 1.0 / norm;\n }\n this.normal.x *= magnitude;\n this.normal.y *= magnitude;\n this.normal.z *= magnitude;\n this.d *= magnitude;\n return this;\n };\n /**\n * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.\n */\n Plane.prototype.transform = function (transformation) {\n var transposedMatrix = Matrix.Transpose(transformation);\n var x = this.normal.x;\n var y = this.normal.y;\n var z = this.normal.z;\n var d = this.d;\n var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);\n var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);\n var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);\n var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);\n return new Plane(normalX, normalY, normalZ, finalD);\n };\n /**\n * Returns the dot product (float) of the point coordinates and the plane normal.\n */\n Plane.prototype.dotCoordinate = function (point) {\n return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);\n };\n /**\n * Updates the current Plane from the plane defined by the three given points.\n * Returns the updated Plane.\n */\n Plane.prototype.copyFromPoints = function (point1, point2, point3) {\n var x1 = point2.x - point1.x;\n var y1 = point2.y - point1.y;\n var z1 = point2.z - point1.z;\n var x2 = point3.x - point1.x;\n var y2 = point3.y - point1.y;\n var z2 = point3.z - point1.z;\n var yz = (y1 * z2) - (z1 * y2);\n var xz = (z1 * x2) - (x1 * z2);\n var xy = (x1 * y2) - (y1 * x2);\n var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));\n var invPyth;\n if (pyth !== 0) {\n invPyth = 1.0 / pyth;\n }\n else {\n invPyth = 0.0;\n }\n this.normal.x = yz * invPyth;\n this.normal.y = xz * invPyth;\n this.normal.z = xy * invPyth;\n this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));\n return this;\n };\n /**\n * Boolean : True is the vector \"direction\" is the same side than the plane normal.\n */\n Plane.prototype.isFrontFacingTo = function (direction, epsilon) {\n var dot = Vector3.Dot(this.normal, direction);\n return (dot <= epsilon);\n };\n /**\n * Returns the signed distance (float) from the given point to the Plane.\n */\n Plane.prototype.signedDistanceTo = function (point) {\n return Vector3.Dot(point, this.normal) + this.d;\n };\n // Statics\n /**\n * Returns a new Plane from the given array.\n */\n Plane.FromArray = function (array) {\n return new Plane(array[0], array[1], array[2], array[3]);\n };\n /**\n * Returns a new Plane defined by the three given points.\n */\n Plane.FromPoints = function (point1, point2, point3) {\n var result = new Plane(0.0, 0.0, 0.0, 0.0);\n result.copyFromPoints(point1, point2, point3);\n return result;\n };\n /**\n * Returns a new Plane the normal vector to this plane at the given origin point.\n * Note : the vector \"normal\" is updated because normalized.\n */\n Plane.FromPositionAndNormal = function (origin, normal) {\n var result = new Plane(0.0, 0.0, 0.0, 0.0);\n normal.normalize();\n result.normal = normal;\n result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);\n return result;\n };\n /**\n * Returns the signed distance between the plane defined by the normal vector at the \"origin\"\" point and the given other point.\n */\n Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {\n var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);\n return Vector3.Dot(point, normal) + d;\n };\n return Plane;\n }());\n BABYLON.Plane = Plane;\n var Viewport = /** @class */ (function () {\n /**\n * Creates a Viewport object located at (x, y) and sized (width, height).\n */\n function Viewport(x, y, width, height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {\n if (renderWidthOrEngine.getRenderWidth) {\n var engine = renderWidthOrEngine;\n return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n }\n var renderWidth = renderWidthOrEngine;\n return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);\n };\n /**\n * Returns a new Viewport copied from the current one.\n */\n Viewport.prototype.clone = function () {\n return new Viewport(this.x, this.y, this.width, this.height);\n };\n return Viewport;\n }());\n BABYLON.Viewport = Viewport;\n var Frustum = /** @class */ (function () {\n function Frustum() {\n }\n /**\n * Returns a new array of 6 Frustum planes computed by the given transformation matrix.\n */\n Frustum.GetPlanes = function (transform) {\n var frustumPlanes = [];\n for (var index = 0; index < 6; index++) {\n frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));\n }\n Frustum.GetPlanesToRef(transform, frustumPlanes);\n return frustumPlanes;\n };\n Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {\n frustumPlane.normal.x = transform.m[3] + transform.m[2];\n frustumPlane.normal.y = transform.m[7] + transform.m[6];\n frustumPlane.normal.z = transform.m[11] + transform.m[10];\n frustumPlane.d = transform.m[15] + transform.m[14];\n frustumPlane.normalize();\n };\n Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {\n frustumPlane.normal.x = transform.m[3] - transform.m[2];\n frustumPlane.normal.y = transform.m[7] - transform.m[6];\n frustumPlane.normal.z = transform.m[11] - transform.m[10];\n frustumPlane.d = transform.m[15] - transform.m[14];\n frustumPlane.normalize();\n };\n Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {\n frustumPlane.normal.x = transform.m[3] + transform.m[0];\n frustumPlane.normal.y = transform.m[7] + transform.m[4];\n frustumPlane.normal.z = transform.m[11] + transform.m[8];\n frustumPlane.d = transform.m[15] + transform.m[12];\n frustumPlane.normalize();\n };\n Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {\n frustumPlane.normal.x = transform.m[3] - transform.m[0];\n frustumPlane.normal.y = transform.m[7] - transform.m[4];\n frustumPlane.normal.z = transform.m[11] - transform.m[8];\n frustumPlane.d = transform.m[15] - transform.m[12];\n frustumPlane.normalize();\n };\n Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {\n frustumPlane.normal.x = transform.m[3] - transform.m[1];\n frustumPlane.normal.y = transform.m[7] - transform.m[5];\n frustumPlane.normal.z = transform.m[11] - transform.m[9];\n frustumPlane.d = transform.m[15] - transform.m[13];\n frustumPlane.normalize();\n };\n Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {\n frustumPlane.normal.x = transform.m[3] + transform.m[1];\n frustumPlane.normal.y = transform.m[7] + transform.m[5];\n frustumPlane.normal.z = transform.m[11] + transform.m[9];\n frustumPlane.d = transform.m[15] + transform.m[13];\n frustumPlane.normalize();\n };\n /**\n * Sets the given array \"frustumPlanes\" with the 6 Frustum planes computed by the given transformation matrix.\n */\n Frustum.GetPlanesToRef = function (transform, frustumPlanes) {\n // Near\n Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);\n // Far\n Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);\n // Left\n Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);\n // Right\n Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);\n // Top\n Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);\n // Bottom\n Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);\n };\n return Frustum;\n }());\n BABYLON.Frustum = Frustum;\n /** Defines supported spaces */\n var Space;\n (function (Space) {\n /** Local (object) space */\n Space[Space[\"LOCAL\"] = 0] = \"LOCAL\";\n /** World space */\n Space[Space[\"WORLD\"] = 1] = \"WORLD\";\n /** Bone space */\n Space[Space[\"BONE\"] = 2] = \"BONE\";\n })(Space = BABYLON.Space || (BABYLON.Space = {}));\n /** Defines the 3 main axes */\n var Axis = /** @class */ (function () {\n function Axis() {\n }\n /** X axis */\n Axis.X = new Vector3(1.0, 0.0, 0.0);\n /** Y axis */\n Axis.Y = new Vector3(0.0, 1.0, 0.0);\n /** Z axis */\n Axis.Z = new Vector3(0.0, 0.0, 1.0);\n return Axis;\n }());\n BABYLON.Axis = Axis;\n ;\n var BezierCurve = /** @class */ (function () {\n function BezierCurve() {\n }\n /**\n * Returns the cubic Bezier interpolated value (float) at \"t\" (float) from the given x1, y1, x2, y2 floats.\n */\n BezierCurve.interpolate = function (t, x1, y1, x2, y2) {\n // Extract X (which is equal to time here)\n var f0 = 1 - 3 * x2 + 3 * x1;\n var f1 = 3 * x2 - 6 * x1;\n var f2 = 3 * x1;\n var refinedT = t;\n for (var i = 0; i < 5; i++) {\n var refinedT2 = refinedT * refinedT;\n var refinedT3 = refinedT2 * refinedT;\n var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;\n var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);\n refinedT -= (x - t) * slope;\n refinedT = Math.min(1, Math.max(0, refinedT));\n }\n // Resolve cubic bezier for the given x\n return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +\n 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +\n Math.pow(refinedT, 3);\n };\n return BezierCurve;\n }());\n BABYLON.BezierCurve = BezierCurve;\n /**\n * Defines potential orientation for back face culling\n */\n var Orientation;\n (function (Orientation) {\n /**\n * Clockwise\n */\n Orientation[Orientation[\"CW\"] = 0] = \"CW\";\n /** Counter clockwise */\n Orientation[Orientation[\"CCW\"] = 1] = \"CCW\";\n })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));\n /**\n * Defines angle representation\n */\n var Angle = /** @class */ (function () {\n /**\n * Creates an Angle object of \"radians\" radians (float).\n */\n function Angle(radians) {\n this._radians = radians;\n if (this._radians < 0.0)\n this._radians += (2.0 * Math.PI);\n }\n /**\n * Get value in degrees\n * @returns the Angle value in degrees (float)\n */\n Angle.prototype.degrees = function () {\n return this._radians * 180.0 / Math.PI;\n };\n /**\n * Get value in radians\n * @returns the Angle value in radians (float)\n */\n Angle.prototype.radians = function () {\n return this._radians;\n };\n /**\n * Gets a new Angle object valued with the angle value in radians between the two given vectors\n * @param a defines first vector\n * @param b defines second vector\n * @returns a new Angle\n */\n Angle.BetweenTwoPoints = function (a, b) {\n var delta = b.subtract(a);\n var theta = Math.atan2(delta.y, delta.x);\n return new Angle(theta);\n };\n /**\n * Gets a new Angle object from the given float in radians\n * @param radians defines the angle value in radians\n * @returns a new Angle\n */\n Angle.FromRadians = function (radians) {\n return new Angle(radians);\n };\n /**\n * Gets a new Angle object from the given float in degrees\n * @param degrees defines the angle value in degrees\n * @returns a new Angle\n */\n Angle.FromDegrees = function (degrees) {\n return new Angle(degrees * Math.PI / 180.0);\n };\n return Angle;\n }());\n BABYLON.Angle = Angle;\n var Arc2 = /** @class */ (function () {\n /**\n * Creates an Arc object from the three given points : start, middle and end.\n */\n function Arc2(startPoint, midPoint, endPoint) {\n this.startPoint = startPoint;\n this.midPoint = midPoint;\n this.endPoint = endPoint;\n var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);\n var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;\n var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;\n var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);\n this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);\n this.radius = this.centerPoint.subtract(this.startPoint).length();\n this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);\n var a1 = this.startAngle.degrees();\n var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();\n var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();\n // angles correction\n if (a2 - a1 > +180.0)\n a2 -= 360.0;\n if (a2 - a1 < -180.0)\n a2 += 360.0;\n if (a3 - a2 > +180.0)\n a3 -= 360.0;\n if (a3 - a2 < -180.0)\n a3 += 360.0;\n this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;\n this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);\n }\n return Arc2;\n }());\n BABYLON.Arc2 = Arc2;\n var Path2 = /** @class */ (function () {\n /**\n * Creates a Path2 object from the starting 2D coordinates x and y.\n */\n function Path2(x, y) {\n this._points = new Array();\n this._length = 0.0;\n this.closed = false;\n this._points.push(new Vector2(x, y));\n }\n /**\n * Adds a new segment until the given coordinates (x, y) to the current Path2.\n * Returns the updated Path2.\n */\n Path2.prototype.addLineTo = function (x, y) {\n if (this.closed) {\n return this;\n }\n var newPoint = new Vector2(x, y);\n var previousPoint = this._points[this._points.length - 1];\n this._points.push(newPoint);\n this._length += newPoint.subtract(previousPoint).length();\n return this;\n };\n /**\n * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.\n * Returns the updated Path2.\n */\n Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {\n if (numberOfSegments === void 0) { numberOfSegments = 36; }\n if (this.closed) {\n return this;\n }\n var startPoint = this._points[this._points.length - 1];\n var midPoint = new Vector2(midX, midY);\n var endPoint = new Vector2(endX, endY);\n var arc = new Arc2(startPoint, midPoint, endPoint);\n var increment = arc.angle.radians() / numberOfSegments;\n if (arc.orientation === Orientation.CW)\n increment *= -1;\n var currentAngle = arc.startAngle.radians() + increment;\n for (var i = 0; i < numberOfSegments; i++) {\n var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;\n var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;\n this.addLineTo(x, y);\n currentAngle += increment;\n }\n return this;\n };\n /**\n * Closes the Path2.\n * Returns the Path2.\n */\n Path2.prototype.close = function () {\n this.closed = true;\n return this;\n };\n /**\n * Returns the Path2 total length (float).\n */\n Path2.prototype.length = function () {\n var result = this._length;\n if (!this.closed) {\n var lastPoint = this._points[this._points.length - 1];\n var firstPoint = this._points[0];\n result += (firstPoint.subtract(lastPoint).length());\n }\n return result;\n };\n /**\n * Returns the Path2 internal array of points.\n */\n Path2.prototype.getPoints = function () {\n return this._points;\n };\n /**\n * Returns a new Vector2 located at a percentage of the Path2 total length on this path.\n */\n Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {\n if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {\n return Vector2.Zero();\n }\n var lengthPosition = normalizedLengthPosition * this.length();\n var previousOffset = 0;\n for (var i = 0; i < this._points.length; i++) {\n var j = (i + 1) % this._points.length;\n var a = this._points[i];\n var b = this._points[j];\n var bToA = b.subtract(a);\n var nextOffset = (bToA.length() + previousOffset);\n if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {\n var dir = bToA.normalize();\n var localOffset = lengthPosition - previousOffset;\n return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));\n }\n previousOffset = nextOffset;\n }\n return Vector2.Zero();\n };\n /**\n * Returns a new Path2 starting at the coordinates (x, y).\n */\n Path2.StartingAt = function (x, y) {\n return new Path2(x, y);\n };\n return Path2;\n }());\n BABYLON.Path2 = Path2;\n var Path3D = /** @class */ (function () {\n /**\n * new Path3D(path, normal, raw)\n * Creates a Path3D. A Path3D is a logical math object, so not a mesh.\n * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D\n * path : an array of Vector3, the curve axis of the Path3D\n * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.\n * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.\n */\n function Path3D(path, firstNormal, raw) {\n if (firstNormal === void 0) { firstNormal = null; }\n this.path = path;\n this._curve = new Array();\n this._distances = new Array();\n this._tangents = new Array();\n this._normals = new Array();\n this._binormals = new Array();\n for (var p = 0; p < path.length; p++) {\n this._curve[p] = path[p].clone(); // hard copy\n }\n this._raw = raw || false;\n this._compute(firstNormal);\n }\n /**\n * Returns the Path3D array of successive Vector3 designing its curve.\n */\n Path3D.prototype.getCurve = function () {\n return this._curve;\n };\n /**\n * Returns an array populated with tangent vectors on each Path3D curve point.\n */\n Path3D.prototype.getTangents = function () {\n return this._tangents;\n };\n /**\n * Returns an array populated with normal vectors on each Path3D curve point.\n */\n Path3D.prototype.getNormals = function () {\n return this._normals;\n };\n /**\n * Returns an array populated with binormal vectors on each Path3D curve point.\n */\n Path3D.prototype.getBinormals = function () {\n return this._binormals;\n };\n /**\n * Returns an array populated with distances (float) of the i-th point from the first curve point.\n */\n Path3D.prototype.getDistances = function () {\n return this._distances;\n };\n /**\n * Forces the Path3D tangent, normal, binormal and distance recomputation.\n * Returns the same object updated.\n */\n Path3D.prototype.update = function (path, firstNormal) {\n if (firstNormal === void 0) { firstNormal = null; }\n for (var p = 0; p < path.length; p++) {\n this._curve[p].x = path[p].x;\n this._curve[p].y = path[p].y;\n this._curve[p].z = path[p].z;\n }\n this._compute(firstNormal);\n return this;\n };\n // private function compute() : computes tangents, normals and binormals\n Path3D.prototype._compute = function (firstNormal) {\n var l = this._curve.length;\n // first and last tangents\n this._tangents[0] = this._getFirstNonNullVector(0);\n if (!this._raw) {\n this._tangents[0].normalize();\n }\n this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);\n if (!this._raw) {\n this._tangents[l - 1].normalize();\n }\n // normals and binormals at first point : arbitrary vector with _normalVector()\n var tg0 = this._tangents[0];\n var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);\n this._normals[0] = pp0;\n if (!this._raw) {\n this._normals[0].normalize();\n }\n this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);\n if (!this._raw) {\n this._binormals[0].normalize();\n }\n this._distances[0] = 0.0;\n // normals and binormals : next points\n var prev; // previous vector (segment)\n var cur; // current vector (segment)\n var curTang; // current tangent\n // previous normal\n var prevBinor; // previous binormal\n for (var i = 1; i < l; i++) {\n // tangents\n prev = this._getLastNonNullVector(i);\n if (i < l - 1) {\n cur = this._getFirstNonNullVector(i);\n this._tangents[i] = prev.add(cur);\n this._tangents[i].normalize();\n }\n this._distances[i] = this._distances[i - 1] + prev.length();\n // normals and binormals\n // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html\n curTang = this._tangents[i];\n prevBinor = this._binormals[i - 1];\n this._normals[i] = Vector3.Cross(prevBinor, curTang);\n if (!this._raw) {\n this._normals[i].normalize();\n }\n this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);\n if (!this._raw) {\n this._binormals[i].normalize();\n }\n }\n };\n // private function getFirstNonNullVector(index)\n // returns the first non null vector from index : curve[index + N].subtract(curve[index])\n Path3D.prototype._getFirstNonNullVector = function (index) {\n var i = 1;\n var nNVector = this._curve[index + i].subtract(this._curve[index]);\n while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {\n i++;\n nNVector = this._curve[index + i].subtract(this._curve[index]);\n }\n return nNVector;\n };\n // private function getLastNonNullVector(index)\n // returns the last non null vector from index : curve[index].subtract(curve[index - N])\n Path3D.prototype._getLastNonNullVector = function (index) {\n var i = 1;\n var nLVector = this._curve[index].subtract(this._curve[index - i]);\n while (nLVector.length() === 0 && index > i + 1) {\n i++;\n nLVector = this._curve[index].subtract(this._curve[index - i]);\n }\n return nLVector;\n };\n // private function normalVector(v0, vt, va) :\n // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane\n // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0\n Path3D.prototype._normalVector = function (v0, vt, va) {\n var normal0;\n var tgl = vt.length();\n if (tgl === 0.0) {\n tgl = 1.0;\n }\n if (va === undefined || va === null) {\n var point;\n if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane\n point = new Vector3(0.0, -1.0, 0.0);\n }\n else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {\n point = new Vector3(1.0, 0.0, 0.0);\n }\n else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {\n point = new Vector3(0.0, 0.0, 1.0);\n }\n else {\n point = Vector3.Zero();\n }\n normal0 = Vector3.Cross(vt, point);\n }\n else {\n normal0 = Vector3.Cross(vt, va);\n Vector3.CrossToRef(normal0, vt, normal0);\n }\n normal0.normalize();\n return normal0;\n };\n return Path3D;\n }());\n BABYLON.Path3D = Path3D;\n var Curve3 = /** @class */ (function () {\n /**\n * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.\n * A Curve3 is designed from a series of successive Vector3.\n * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object\n */\n function Curve3(points) {\n this._length = 0.0;\n this._points = points;\n this._length = this._computeLength(points);\n }\n /**\n * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve\n * @param v0 (Vector3) the origin point of the Quadratic Bezier\n * @param v1 (Vector3) the control point\n * @param v2 (Vector3) the end point of the Quadratic Bezier\n * @param nbPoints (integer) the wanted number of points in the curve\n */\n Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {\n nbPoints = nbPoints > 2 ? nbPoints : 3;\n var bez = new Array();\n var equation = function (t, val0, val1, val2) {\n var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;\n return res;\n };\n for (var i = 0; i <= nbPoints; i++) {\n bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));\n }\n return new Curve3(bez);\n };\n /**\n * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve\n * @param v0 (Vector3) the origin point of the Cubic Bezier\n * @param v1 (Vector3) the first control point\n * @param v2 (Vector3) the second control point\n * @param v3 (Vector3) the end point of the Cubic Bezier\n * @param nbPoints (integer) the wanted number of points in the curve\n */\n Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {\n nbPoints = nbPoints > 3 ? nbPoints : 4;\n var bez = new Array();\n var equation = function (t, val0, val1, val2, val3) {\n var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;\n return res;\n };\n for (var i = 0; i <= nbPoints; i++) {\n bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));\n }\n return new Curve3(bez);\n };\n /**\n * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline\n * @param p1 (Vector3) the origin point of the Hermite Spline\n * @param t1 (Vector3) the tangent vector at the origin point\n * @param p2 (Vector3) the end point of the Hermite Spline\n * @param t2 (Vector3) the tangent vector at the end point\n * @param nbPoints (integer) the wanted number of points in the curve\n */\n Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {\n var hermite = new Array();\n var step = 1.0 / nbPoints;\n for (var i = 0; i <= nbPoints; i++) {\n hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));\n }\n return new Curve3(hermite);\n };\n /**\n * Returns a Curve3 object along a CatmullRom Spline curve :\n * @param points (array of Vector3) the points the spline must pass through. At least, four points required\n * @param nbPoints (integer) the wanted number of points between each curve control points\n * @param closed (boolean) optional with default false, when true forms a closed loop from the points\n */\n Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {\n var catmullRom = new Array();\n var step = 1.0 / nbPoints;\n var amount = 0.0;\n if (closed) {\n var pointsCount = points.length;\n for (var i = 0; i < pointsCount; i++) {\n amount = 0;\n for (var c = 0; c < nbPoints; c++) {\n catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));\n amount += step;\n }\n }\n catmullRom.push(catmullRom[0]);\n }\n else {\n var totalPoints = new Array();\n totalPoints.push(points[0].clone());\n Array.prototype.push.apply(totalPoints, points);\n totalPoints.push(points[points.length - 1].clone());\n for (var i = 0; i < totalPoints.length - 3; i++) {\n amount = 0;\n for (var c = 0; c < nbPoints; c++) {\n catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));\n amount += step;\n }\n }\n i--;\n catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));\n }\n return new Curve3(catmullRom);\n };\n /**\n * Returns the Curve3 stored array of successive Vector3\n */\n Curve3.prototype.getPoints = function () {\n return this._points;\n };\n /**\n * Returns the computed length (float) of the curve.\n */\n Curve3.prototype.length = function () {\n return this._length;\n };\n /**\n * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);\n * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.\n * curveA and curveB keep unchanged.\n */\n Curve3.prototype.continue = function (curve) {\n var lastPoint = this._points[this._points.length - 1];\n var continuedPoints = this._points.slice();\n var curvePoints = curve.getPoints();\n for (var i = 1; i < curvePoints.length; i++) {\n continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));\n }\n var continuedCurve = new Curve3(continuedPoints);\n return continuedCurve;\n };\n Curve3.prototype._computeLength = function (path) {\n var l = 0;\n for (var i = 1; i < path.length; i++) {\n l += (path[i].subtract(path[i - 1])).length();\n }\n return l;\n };\n return Curve3;\n }());\n BABYLON.Curve3 = Curve3;\n // Vertex formats\n var PositionNormalVertex = /** @class */ (function () {\n function PositionNormalVertex(position, normal) {\n if (position === void 0) { position = Vector3.Zero(); }\n if (normal === void 0) { normal = Vector3.Up(); }\n this.position = position;\n this.normal = normal;\n }\n PositionNormalVertex.prototype.clone = function () {\n return new PositionNormalVertex(this.position.clone(), this.normal.clone());\n };\n return PositionNormalVertex;\n }());\n BABYLON.PositionNormalVertex = PositionNormalVertex;\n var PositionNormalTextureVertex = /** @class */ (function () {\n function PositionNormalTextureVertex(position, normal, uv) {\n if (position === void 0) { position = Vector3.Zero(); }\n if (normal === void 0) { normal = Vector3.Up(); }\n if (uv === void 0) { uv = Vector2.Zero(); }\n this.position = position;\n this.normal = normal;\n this.uv = uv;\n }\n PositionNormalTextureVertex.prototype.clone = function () {\n return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());\n };\n return PositionNormalTextureVertex;\n }());\n BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;\n // Temporary pre-allocated objects for engine internal use\n // usage in any internal function :\n // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3\n // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix\n var Tmp = /** @class */ (function () {\n function Tmp() {\n }\n Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];\n Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];\n Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough\n Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),\n Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough\n Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough\n Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough\n Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),\n Matrix.Zero(), Matrix.Zero(),\n Matrix.Zero(), Matrix.Zero(),\n Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough\n return Tmp;\n }());\n BABYLON.Tmp = Tmp;\n // Same as Tmp but not exported to keep it only for math functions to avoid conflicts\n var MathTmp = /** @class */ (function () {\n function MathTmp() {\n }\n MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];\n MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];\n MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];\n return MathTmp;\n }());\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.math.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Scalar = /** @class */ (function () {\n function Scalar() {\n }\n /**\n * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)\n */\n Scalar.WithinEpsilon = function (a, b, epsilon) {\n if (epsilon === void 0) { epsilon = 1.401298E-45; }\n var num = a - b;\n return -epsilon <= num && num <= epsilon;\n };\n /**\n * Returns a string : the upper case translation of the number i to hexadecimal.\n */\n Scalar.ToHex = function (i) {\n var str = i.toString(16);\n if (i <= 15) {\n return (\"0\" + str).toUpperCase();\n }\n return str.toUpperCase();\n };\n /**\n * Returns -1 if value is negative and +1 is value is positive.\n * Returns the value itself if it's equal to zero.\n */\n Scalar.Sign = function (value) {\n value = +value; // convert to a number\n if (value === 0 || isNaN(value))\n return value;\n return value > 0 ? 1 : -1;\n };\n /**\n * Returns the value itself if it's between min and max.\n * Returns min if the value is lower than min.\n * Returns max if the value is greater than max.\n */\n Scalar.Clamp = function (value, min, max) {\n if (min === void 0) { min = 0; }\n if (max === void 0) { max = 1; }\n return Math.min(max, Math.max(min, value));\n };\n /**\n * Returns the log2 of value.\n */\n Scalar.Log2 = function (value) {\n return Math.log(value) * Math.LOG2E;\n };\n /**\n * Loops the value, so that it is never larger than length and never smaller than 0.\n *\n * This is similar to the modulo operator but it works with floating point numbers.\n * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.\n * With t = 5 and length = 2.5, the result would be 0.0.\n * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator\n */\n Scalar.Repeat = function (value, length) {\n return value - Math.floor(value / length) * length;\n };\n /**\n * Normalize the value between 0.0 and 1.0 using min and max values\n */\n Scalar.Normalize = function (value, min, max) {\n return (value - min) / (max - min);\n };\n /**\n * Denormalize the value from 0.0 and 1.0 using min and max values\n */\n Scalar.Denormalize = function (normalized, min, max) {\n return (normalized * (max - min) + min);\n };\n /**\n * Calculates the shortest difference between two given angles given in degrees.\n */\n Scalar.DeltaAngle = function (current, target) {\n var num = Scalar.Repeat(target - current, 360.0);\n if (num > 180.0) {\n num -= 360.0;\n }\n return num;\n };\n /**\n * PingPongs the value t, so that it is never larger than length and never smaller than 0.\n *\n * The returned value will move back and forth between 0 and length\n */\n Scalar.PingPong = function (tx, length) {\n var t = Scalar.Repeat(tx, length * 2.0);\n return length - Math.abs(t - length);\n };\n /**\n * Interpolates between min and max with smoothing at the limits.\n *\n * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up\n * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.\n */\n Scalar.SmoothStep = function (from, to, tx) {\n var t = Scalar.Clamp(tx);\n t = -2.0 * t * t * t + 3.0 * t * t;\n return to * t + from * (1.0 - t);\n };\n /**\n * Moves a value current towards target.\n *\n * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.\n * Negative values of maxDelta pushes the value away from target.\n */\n Scalar.MoveTowards = function (current, target, maxDelta) {\n var result = 0;\n if (Math.abs(target - current) <= maxDelta) {\n result = target;\n }\n else {\n result = current + Scalar.Sign(target - current) * maxDelta;\n }\n return result;\n };\n /**\n * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.\n *\n * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta\n * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.\n */\n Scalar.MoveTowardsAngle = function (current, target, maxDelta) {\n var num = Scalar.DeltaAngle(current, target);\n var result = 0;\n if (-maxDelta < num && num < maxDelta) {\n result = target;\n }\n else {\n target = current + num;\n result = Scalar.MoveTowards(current, target, maxDelta);\n }\n return result;\n };\n /**\n * Creates a new scalar with values linearly interpolated of \"amount\" between the start scalar and the end scalar.\n */\n Scalar.Lerp = function (start, end, amount) {\n return start + ((end - start) * amount);\n };\n /**\n * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.\n * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.\n */\n Scalar.LerpAngle = function (start, end, amount) {\n var num = Scalar.Repeat(end - start, 360.0);\n if (num > 180.0) {\n num -= 360.0;\n }\n return start + num * Scalar.Clamp(amount);\n };\n /**\n * Calculates the linear parameter t that produces the interpolant value within the range [a, b].\n */\n Scalar.InverseLerp = function (a, b, value) {\n var result = 0;\n if (a != b) {\n result = Scalar.Clamp((value - a) / (b - a));\n }\n else {\n result = 0.0;\n }\n return result;\n };\n /**\n * Returns a new scalar located for \"amount\" (float) on the Hermite spline defined by the scalars \"value1\", \"value3\", \"tangent1\", \"tangent2\".\n */\n Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {\n var squared = amount * amount;\n var cubed = amount * squared;\n var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;\n var part2 = (-2.0 * cubed) + (3.0 * squared);\n var part3 = (cubed - (2.0 * squared)) + amount;\n var part4 = cubed - squared;\n return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);\n };\n /**\n * Returns a random float number between and min and max values\n */\n Scalar.RandomRange = function (min, max) {\n if (min === max)\n return min;\n return ((Math.random() * (max - min)) + min);\n };\n /**\n * This function returns percentage of a number in a given range.\n *\n * RangeToPercent(40,20,60) will return 0.5 (50%)\n * RangeToPercent(34,0,100) will return 0.34 (34%)\n */\n Scalar.RangeToPercent = function (number, min, max) {\n return ((number - min) / (max - min));\n };\n /**\n * This function returns number that corresponds to the percentage in a given range.\n *\n * PercentToRange(0.34,0,100) will return 34.\n */\n Scalar.PercentToRange = function (percent, min, max) {\n return ((max - min) * percent + min);\n };\n /**\n * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.\n * @param angle The angle to normalize in radian.\n * @return The converted angle.\n */\n Scalar.NormalizeRadians = function (angle) {\n // More precise but slower version kept for reference.\n // angle = angle % Tools.TwoPi;\n // angle = (angle + Tools.TwoPi) % Tools.TwoPi;\n //if (angle > Math.PI) {\n //\tangle -= Tools.TwoPi;\n //}\n angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));\n return angle;\n };\n /**\n * Two pi constants convenient for computation.\n */\n Scalar.TwoPi = Math.PI * 2;\n return Scalar;\n }());\n BABYLON.Scalar = Scalar;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.math.scalar.js.map\n\n\n\n//# sourceMappingURL=babylon.mixins.js.map\n\n// Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800\n// Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/\n// Definitions by: Nico Kemnitz \n// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n\n//# sourceMappingURL=babylon.webgl2.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var __decoratorInitialStore = {};\n var __mergedStore = {};\n var _copySource = function (creationFunction, source, instanciate) {\n var destination = creationFunction();\n // Tags\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(destination, source.tags);\n }\n var classStore = getMergedStore(destination);\n // Properties\n for (var property in classStore) {\n var propertyDescriptor = classStore[property];\n var sourceProperty = source[property];\n var propertyType = propertyDescriptor.type;\n if (sourceProperty !== undefined && sourceProperty !== null) {\n switch (propertyType) {\n case 0: // Value\n case 6: // Mesh reference\n case 11: // Camera reference\n destination[property] = sourceProperty;\n break;\n case 1: // Texture\n destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();\n break;\n case 2: // Color3\n case 3: // FresnelParameters\n case 4: // Vector2\n case 5: // Vector3\n case 7: // Color Curves\n case 10: // Quaternion\n destination[property] = instanciate ? sourceProperty : sourceProperty.clone();\n break;\n }\n }\n }\n return destination;\n };\n function getDirectStore(target) {\n var classKey = target.getClassName();\n if (!__decoratorInitialStore[classKey]) {\n __decoratorInitialStore[classKey] = {};\n }\n return __decoratorInitialStore[classKey];\n }\n /**\n * Return the list of properties flagged as serializable\n * @param target: host object\n */\n function getMergedStore(target) {\n var classKey = target.getClassName();\n if (__mergedStore[classKey]) {\n return __mergedStore[classKey];\n }\n __mergedStore[classKey] = {};\n var store = __mergedStore[classKey];\n var currentTarget = target;\n var currentKey = classKey;\n while (currentKey) {\n var initialStore = __decoratorInitialStore[currentKey];\n for (var property in initialStore) {\n store[property] = initialStore[property];\n }\n var parent_1 = void 0;\n var done = false;\n do {\n parent_1 = Object.getPrototypeOf(currentTarget);\n if (!parent_1.getClassName) {\n done = true;\n break;\n }\n if (parent_1.getClassName() !== currentKey) {\n break;\n }\n currentTarget = parent_1;\n } while (parent_1);\n if (done) {\n break;\n }\n currentKey = parent_1.getClassName();\n currentTarget = parent_1;\n }\n return store;\n }\n function generateSerializableMember(type, sourceName) {\n return function (target, propertyKey) {\n var classStore = getDirectStore(target);\n if (!classStore[propertyKey]) {\n classStore[propertyKey] = { type: type, sourceName: sourceName };\n }\n };\n }\n function generateExpandMember(setCallback, targetKey) {\n if (targetKey === void 0) { targetKey = null; }\n return function (target, propertyKey) {\n var key = targetKey || (\"_\" + propertyKey);\n Object.defineProperty(target, propertyKey, {\n get: function () {\n return this[key];\n },\n set: function (value) {\n if (this[key] === value) {\n return;\n }\n this[key] = value;\n target[setCallback].apply(this);\n },\n enumerable: true,\n configurable: true\n });\n };\n }\n function expandToProperty(callback, targetKey) {\n if (targetKey === void 0) { targetKey = null; }\n return generateExpandMember(callback, targetKey);\n }\n BABYLON.expandToProperty = expandToProperty;\n function serialize(sourceName) {\n return generateSerializableMember(0, sourceName); // value member\n }\n BABYLON.serialize = serialize;\n function serializeAsTexture(sourceName) {\n return generateSerializableMember(1, sourceName); // texture member\n }\n BABYLON.serializeAsTexture = serializeAsTexture;\n function serializeAsColor3(sourceName) {\n return generateSerializableMember(2, sourceName); // color3 member\n }\n BABYLON.serializeAsColor3 = serializeAsColor3;\n function serializeAsFresnelParameters(sourceName) {\n return generateSerializableMember(3, sourceName); // fresnel parameters member\n }\n BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;\n function serializeAsVector2(sourceName) {\n return generateSerializableMember(4, sourceName); // vector2 member\n }\n BABYLON.serializeAsVector2 = serializeAsVector2;\n function serializeAsVector3(sourceName) {\n return generateSerializableMember(5, sourceName); // vector3 member\n }\n BABYLON.serializeAsVector3 = serializeAsVector3;\n function serializeAsMeshReference(sourceName) {\n return generateSerializableMember(6, sourceName); // mesh reference member\n }\n BABYLON.serializeAsMeshReference = serializeAsMeshReference;\n function serializeAsColorCurves(sourceName) {\n return generateSerializableMember(7, sourceName); // color curves\n }\n BABYLON.serializeAsColorCurves = serializeAsColorCurves;\n function serializeAsColor4(sourceName) {\n return generateSerializableMember(8, sourceName); // color 4\n }\n BABYLON.serializeAsColor4 = serializeAsColor4;\n function serializeAsImageProcessingConfiguration(sourceName) {\n return generateSerializableMember(9, sourceName); // image processing\n }\n BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;\n function serializeAsQuaternion(sourceName) {\n return generateSerializableMember(10, sourceName); // quaternion member\n }\n BABYLON.serializeAsQuaternion = serializeAsQuaternion;\n /**\n * Decorator used to define property that can be serialized as reference to a camera\n * @param sourceName defines the name of the property to decorate\n */\n function serializeAsCameraReference(sourceName) {\n return generateSerializableMember(11, sourceName); // camera reference member\n }\n BABYLON.serializeAsCameraReference = serializeAsCameraReference;\n var SerializationHelper = /** @class */ (function () {\n function SerializationHelper() {\n }\n SerializationHelper.Serialize = function (entity, serializationObject) {\n if (!serializationObject) {\n serializationObject = {};\n }\n // Tags\n if (BABYLON.Tags) {\n serializationObject.tags = BABYLON.Tags.GetTags(entity);\n }\n var serializedProperties = getMergedStore(entity);\n // Properties\n for (var property in serializedProperties) {\n var propertyDescriptor = serializedProperties[property];\n var targetPropertyName = propertyDescriptor.sourceName || property;\n var propertyType = propertyDescriptor.type;\n var sourceProperty = entity[property];\n if (sourceProperty !== undefined && sourceProperty !== null) {\n switch (propertyType) {\n case 0: // Value\n serializationObject[targetPropertyName] = sourceProperty;\n break;\n case 1: // Texture\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 2: // Color3\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 3: // FresnelParameters\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 4: // Vector2\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 5: // Vector3\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 6: // Mesh reference\n serializationObject[targetPropertyName] = sourceProperty.id;\n break;\n case 7: // Color Curves\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 8: // Color 4\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 9: // Image Processing\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 10: // Quaternion\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 11: // Camera reference\n serializationObject[targetPropertyName] = sourceProperty.id;\n break;\n }\n }\n }\n return serializationObject;\n };\n SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {\n if (rootUrl === void 0) { rootUrl = null; }\n var destination = creationFunction();\n if (!rootUrl) {\n rootUrl = \"\";\n }\n // Tags\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(destination, source.tags);\n }\n var classStore = getMergedStore(destination);\n // Properties\n for (var property in classStore) {\n var propertyDescriptor = classStore[property];\n var sourceProperty = source[propertyDescriptor.sourceName || property];\n var propertyType = propertyDescriptor.type;\n if (sourceProperty !== undefined && sourceProperty !== null) {\n var dest = destination;\n switch (propertyType) {\n case 0: // Value\n dest[property] = sourceProperty;\n break;\n case 1: // Texture\n if (scene) {\n dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);\n }\n break;\n case 2: // Color3\n dest[property] = BABYLON.Color3.FromArray(sourceProperty);\n break;\n case 3: // FresnelParameters\n dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);\n break;\n case 4: // Vector2\n dest[property] = BABYLON.Vector2.FromArray(sourceProperty);\n break;\n case 5: // Vector3\n dest[property] = BABYLON.Vector3.FromArray(sourceProperty);\n break;\n case 6: // Mesh reference\n if (scene) {\n dest[property] = scene.getLastMeshByID(sourceProperty);\n }\n break;\n case 7: // Color Curves\n dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);\n break;\n case 8: // Color 4\n dest[property] = BABYLON.Color4.FromArray(sourceProperty);\n break;\n case 9: // Image Processing\n dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);\n break;\n case 10: // Quaternion\n dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);\n break;\n case 11: // Camera reference\n if (scene) {\n dest[property] = scene.getCameraByID(sourceProperty);\n }\n break;\n }\n }\n }\n return destination;\n };\n SerializationHelper.Clone = function (creationFunction, source) {\n return _copySource(creationFunction, source, false);\n };\n SerializationHelper.Instanciate = function (creationFunction, source) {\n return _copySource(creationFunction, source, true);\n };\n return SerializationHelper;\n }());\n BABYLON.SerializationHelper = SerializationHelper;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.decorators.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Wrapper class for promise with external resolve and reject.\n */\n var Deferred = /** @class */ (function () {\n /**\n * Constructor for this deferred object.\n */\n function Deferred() {\n var _this = this;\n this.promise = new Promise(function (resolve, reject) {\n _this._resolve = resolve;\n _this._reject = reject;\n });\n }\n Object.defineProperty(Deferred.prototype, \"resolve\", {\n /**\n * The resolve method of the promise associated with this deferred object.\n */\n get: function () {\n return this._resolve;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Deferred.prototype, \"reject\", {\n /**\n * The reject method of the promise associated with this deferred object.\n */\n get: function () {\n return this._reject;\n },\n enumerable: true,\n configurable: true\n });\n return Deferred;\n }());\n BABYLON.Deferred = Deferred;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.deferred.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A class serves as a medium between the observable and its observers\n */\n var EventState = /** @class */ (function () {\n /**\n * Create a new EventState\n * @param mask defines the mask associated with this state\n * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true\n * @param target defines the original target of the state\n * @param currentTarget defines the current target of the state\n */\n function EventState(mask, skipNextObservers, target, currentTarget) {\n if (skipNextObservers === void 0) { skipNextObservers = false; }\n this.initalize(mask, skipNextObservers, target, currentTarget);\n }\n /**\n * Initialize the current event state\n * @param mask defines the mask associated with this state\n * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true\n * @param target defines the original target of the state\n * @param currentTarget defines the current target of the state\n * @returns the current event state\n */\n EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {\n if (skipNextObservers === void 0) { skipNextObservers = false; }\n this.mask = mask;\n this.skipNextObservers = skipNextObservers;\n this.target = target;\n this.currentTarget = currentTarget;\n return this;\n };\n return EventState;\n }());\n BABYLON.EventState = EventState;\n /**\n * Represent an Observer registered to a given Observable object.\n */\n var Observer = /** @class */ (function () {\n /**\n * Creates a new observer\n * @param callback defines the callback to call when the observer is notified\n * @param mask defines the mask of the observer (used to filter notifications)\n * @param scope defines the current scope used to restore the JS context\n */\n function Observer(\n /**\n * Defines the callback to call when the observer is notified\n */\n callback, \n /**\n * Defines the mask of the observer (used to filter notifications)\n */\n mask, \n /**\n * Defines the current scope used to restore the JS context\n */\n scope) {\n if (scope === void 0) { scope = null; }\n this.callback = callback;\n this.mask = mask;\n this.scope = scope;\n /** @hidden */\n this._willBeUnregistered = false;\n /**\n * Gets or sets a property defining that the observer as to be unregistered after the next notification\n */\n this.unregisterOnNextCall = false;\n }\n return Observer;\n }());\n BABYLON.Observer = Observer;\n /**\n * Represent a list of observers registered to multiple Observables object.\n */\n var MultiObserver = /** @class */ (function () {\n function MultiObserver() {\n }\n /**\n * Release associated resources\n */\n MultiObserver.prototype.dispose = function () {\n if (this._observers && this._observables) {\n for (var index = 0; index < this._observers.length; index++) {\n this._observables[index].remove(this._observers[index]);\n }\n }\n this._observers = null;\n this._observables = null;\n };\n /**\n * Raise a callback when one of the observable will notify\n * @param observables defines a list of observables to watch\n * @param callback defines the callback to call on notification\n * @param mask defines the mask used to filter notifications\n * @param scope defines the current scope used to restore the JS context\n * @returns the new MultiObserver\n */\n MultiObserver.Watch = function (observables, callback, mask, scope) {\n if (mask === void 0) { mask = -1; }\n if (scope === void 0) { scope = null; }\n var result = new MultiObserver();\n result._observers = new Array();\n result._observables = observables;\n for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {\n var observable = observables_1[_i];\n var observer = observable.add(callback, mask, false, scope);\n if (observer) {\n result._observers.push(observer);\n }\n }\n return result;\n };\n return MultiObserver;\n }());\n BABYLON.MultiObserver = MultiObserver;\n /**\n * The Observable class is a simple implementation of the Observable pattern.\n *\n * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.\n * This enable a more fine grained execution without having to rely on multiple different Observable objects.\n * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).\n * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.\n */\n var Observable = /** @class */ (function () {\n /**\n * Creates a new observable\n * @param onObserverAdded defines a callback to call when a new observer is added\n */\n function Observable(onObserverAdded) {\n this._observers = new Array();\n this._eventState = new EventState(0);\n if (onObserverAdded) {\n this._onObserverAdded = onObserverAdded;\n }\n }\n /**\n * Create a new Observer with the specified callback\n * @param callback the callback that will be executed for that Observer\n * @param mask the mask used to filter observers\n * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.\n * @param scope optional scope for the callback to be called from\n * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification\n * @returns the new observer created for the callback\n */\n Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {\n if (mask === void 0) { mask = -1; }\n if (insertFirst === void 0) { insertFirst = false; }\n if (scope === void 0) { scope = null; }\n if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }\n if (!callback) {\n return null;\n }\n var observer = new Observer(callback, mask, scope);\n observer.unregisterOnNextCall = unregisterOnFirstCall;\n if (insertFirst) {\n this._observers.unshift(observer);\n }\n else {\n this._observers.push(observer);\n }\n if (this._onObserverAdded) {\n this._onObserverAdded(observer);\n }\n return observer;\n };\n /**\n * Create a new Observer with the specified callback and unregisters after the next notification\n * @param callback the callback that will be executed for that Observer\n * @returns the new observer created for the callback\n */\n Observable.prototype.addOnce = function (callback) {\n return this.add(callback, undefined, undefined, undefined, true);\n };\n /**\n * Remove an Observer from the Observable object\n * @param observer the instance of the Observer to remove\n * @returns false if it doesn't belong to this Observable\n */\n Observable.prototype.remove = function (observer) {\n if (!observer) {\n return false;\n }\n var index = this._observers.indexOf(observer);\n if (index !== -1) {\n this._deferUnregister(observer);\n return true;\n }\n return false;\n };\n /**\n * Remove a callback from the Observable object\n * @param callback the callback to remove\n * @param scope optional scope. If used only the callbacks with this scope will be removed\n * @returns false if it doesn't belong to this Observable\n */\n Observable.prototype.removeCallback = function (callback, scope) {\n for (var index = 0; index < this._observers.length; index++) {\n if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {\n this._deferUnregister(this._observers[index]);\n return true;\n }\n }\n return false;\n };\n Observable.prototype._deferUnregister = function (observer) {\n var _this = this;\n observer.unregisterOnNextCall = false;\n observer._willBeUnregistered = true;\n BABYLON.Tools.SetImmediate(function () {\n _this._remove(observer);\n });\n };\n // This should only be called when not iterating over _observers to avoid callback skipping.\n // Removes an observer from the _observer Array.\n Observable.prototype._remove = function (observer) {\n if (!observer) {\n return false;\n }\n var index = this._observers.indexOf(observer);\n if (index !== -1) {\n this._observers.splice(index, 1);\n return true;\n }\n return false;\n };\n /**\n * Notify all Observers by calling their respective callback with the given data\n * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute\n * @param eventData defines the data to send to all observers\n * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)\n * @param target defines the original target of the state\n * @param currentTarget defines the current target of the state\n * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)\n */\n Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {\n if (mask === void 0) { mask = -1; }\n if (!this._observers.length) {\n return true;\n }\n var state = this._eventState;\n state.mask = mask;\n state.target = target;\n state.currentTarget = currentTarget;\n state.skipNextObservers = false;\n state.lastReturnValue = eventData;\n for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {\n var obs = _a[_i];\n if (obs._willBeUnregistered) {\n continue;\n }\n if (obs.mask & mask) {\n if (obs.scope) {\n state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);\n }\n else {\n state.lastReturnValue = obs.callback(eventData, state);\n }\n if (obs.unregisterOnNextCall) {\n this._deferUnregister(obs);\n }\n }\n if (state.skipNextObservers) {\n return false;\n }\n }\n return true;\n };\n /**\n * Calling this will execute each callback, expecting it to be a promise or return a value.\n * If at any point in the chain one function fails, the promise will fail and the execution will not continue.\n * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object\n * and it is crucial that all callbacks will be executed.\n * The order of the callbacks is kept, callbacks are not executed parallel.\n *\n * @param eventData The data to be sent to each callback\n * @param mask is used to filter observers defaults to -1\n * @param target defines the callback target (see EventState)\n * @param currentTarget defines he current object in the bubbling phase\n * @returns {Promise} will return a Promise than resolves when all callbacks executed successfully.\n */\n Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {\n var _this = this;\n if (mask === void 0) { mask = -1; }\n // create an empty promise\n var p = Promise.resolve(eventData);\n // no observers? return this promise.\n if (!this._observers.length) {\n return p;\n }\n var state = this._eventState;\n state.mask = mask;\n state.target = target;\n state.currentTarget = currentTarget;\n state.skipNextObservers = false;\n // execute one callback after another (not using Promise.all, the order is important)\n this._observers.forEach(function (obs) {\n if (state.skipNextObservers) {\n return;\n }\n if (obs._willBeUnregistered) {\n return;\n }\n if (obs.mask & mask) {\n if (obs.scope) {\n p = p.then(function (lastReturnedValue) {\n state.lastReturnValue = lastReturnedValue;\n return obs.callback.apply(obs.scope, [eventData, state]);\n });\n }\n else {\n p = p.then(function (lastReturnedValue) {\n state.lastReturnValue = lastReturnedValue;\n return obs.callback(eventData, state);\n });\n }\n if (obs.unregisterOnNextCall) {\n _this._deferUnregister(obs);\n }\n }\n });\n // return the eventData\n return p.then(function () { return eventData; });\n };\n /**\n * Notify a specific observer\n * @param observer defines the observer to notify\n * @param eventData defines the data to be sent to each callback\n * @param mask is used to filter observers defaults to -1\n */\n Observable.prototype.notifyObserver = function (observer, eventData, mask) {\n if (mask === void 0) { mask = -1; }\n var state = this._eventState;\n state.mask = mask;\n state.skipNextObservers = false;\n observer.callback(eventData, state);\n };\n /**\n * Gets a boolean indicating if the observable has at least one observer\n * @returns true is the Observable has at least one Observer registered\n */\n Observable.prototype.hasObservers = function () {\n return this._observers.length > 0;\n };\n /**\n * Clear the list of observers\n */\n Observable.prototype.clear = function () {\n this._observers = new Array();\n this._onObserverAdded = null;\n };\n /**\n * Clone the current observable\n * @returns a new observable\n */\n Observable.prototype.clone = function () {\n var result = new Observable();\n result._observers = this._observers.slice(0);\n return result;\n };\n /**\n * Does this observable handles observer registered with a given mask\n * @param mask defines the mask to be tested\n * @return whether or not one observer registered with the given mask is handeled\n **/\n Observable.prototype.hasSpecificMask = function (mask) {\n if (mask === void 0) { mask = -1; }\n for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {\n var obs = _a[_i];\n if (obs.mask & mask || obs.mask === mask) {\n return true;\n }\n }\n return false;\n };\n return Observable;\n }());\n BABYLON.Observable = Observable;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.observable.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var SmartArray = /** @class */ (function () {\n function SmartArray(capacity) {\n this.length = 0;\n this.data = new Array(capacity);\n this._id = SmartArray._GlobalId++;\n }\n SmartArray.prototype.push = function (value) {\n this.data[this.length++] = value;\n if (this.length > this.data.length) {\n this.data.length *= 2;\n }\n };\n SmartArray.prototype.forEach = function (func) {\n for (var index = 0; index < this.length; index++) {\n func(this.data[index]);\n }\n };\n SmartArray.prototype.sort = function (compareFn) {\n this.data.sort(compareFn);\n };\n SmartArray.prototype.reset = function () {\n this.length = 0;\n };\n SmartArray.prototype.dispose = function () {\n this.reset();\n if (this.data) {\n this.data.length = 0;\n this.data = [];\n }\n };\n SmartArray.prototype.concat = function (array) {\n if (array.length === 0) {\n return;\n }\n if (this.length + array.length > this.data.length) {\n this.data.length = (this.length + array.length) * 2;\n }\n for (var index = 0; index < array.length; index++) {\n this.data[this.length++] = (array.data || array)[index];\n }\n };\n SmartArray.prototype.indexOf = function (value) {\n var position = this.data.indexOf(value);\n if (position >= this.length) {\n return -1;\n }\n return position;\n };\n SmartArray.prototype.contains = function (value) {\n return this.data.indexOf(value) !== -1;\n };\n // Statics\n SmartArray._GlobalId = 0;\n return SmartArray;\n }());\n BABYLON.SmartArray = SmartArray;\n var SmartArrayNoDuplicate = /** @class */ (function (_super) {\n __extends(SmartArrayNoDuplicate, _super);\n function SmartArrayNoDuplicate() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this._duplicateId = 0;\n return _this;\n }\n SmartArrayNoDuplicate.prototype.push = function (value) {\n _super.prototype.push.call(this, value);\n if (!value.__smartArrayFlags) {\n value.__smartArrayFlags = {};\n }\n value.__smartArrayFlags[this._id] = this._duplicateId;\n };\n SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {\n if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {\n return false;\n }\n this.push(value);\n return true;\n };\n SmartArrayNoDuplicate.prototype.reset = function () {\n _super.prototype.reset.call(this);\n this._duplicateId++;\n };\n SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {\n if (array.length === 0) {\n return;\n }\n if (this.length + array.length > this.data.length) {\n this.data.length = (this.length + array.length) * 2;\n }\n for (var index = 0; index < array.length; index++) {\n var item = (array.data || array)[index];\n this.pushNoDuplicate(item);\n }\n };\n return SmartArrayNoDuplicate;\n }(SmartArray));\n BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.smartArray.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /** Class used to store color gradient */\n var ColorGradient = /** @class */ (function () {\n function ColorGradient() {\n }\n /**\n * Will get a color picked randomly between color1 and color2.\n * If color2 is undefined then color1 will be used\n * @param result defines the target Color4 to store the result in\n */\n ColorGradient.prototype.getColorToRef = function (result) {\n if (!this.color2) {\n result.copyFrom(this.color1);\n return;\n }\n BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);\n };\n return ColorGradient;\n }());\n BABYLON.ColorGradient = ColorGradient;\n /** Class used to store factor gradient */\n var FactorGradient = /** @class */ (function () {\n function FactorGradient() {\n }\n /**\n * Will get a number picked randomly between factor1 and factor2.\n * If factor2 is undefined then factor1 will be used\n * @returns the picked number\n */\n FactorGradient.prototype.getFactor = function () {\n if (this.factor2 === undefined) {\n return this.factor1;\n }\n return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());\n };\n return FactorGradient;\n }());\n BABYLON.FactorGradient = FactorGradient;\n // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript\n // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work\n var LoadFileError = /** @class */ (function (_super) {\n __extends(LoadFileError, _super);\n function LoadFileError(message, request) {\n var _this = _super.call(this, message) || this;\n _this.request = request;\n _this.name = \"LoadFileError\";\n LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);\n return _this;\n }\n // Polyfill for Object.setPrototypeOf if necessary.\n LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });\n return LoadFileError;\n }(Error));\n BABYLON.LoadFileError = LoadFileError;\n var RetryStrategy = /** @class */ (function () {\n function RetryStrategy() {\n }\n RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {\n if (maxRetries === void 0) { maxRetries = 3; }\n if (baseInterval === void 0) { baseInterval = 500; }\n return function (url, request, retryIndex) {\n if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf(\"file:\") !== -1) {\n return -1;\n }\n return Math.pow(2, retryIndex) * baseInterval;\n };\n };\n return RetryStrategy;\n }());\n BABYLON.RetryStrategy = RetryStrategy;\n // Screenshots\n var screenshotCanvas;\n var cloneValue = function (source, destinationObject) {\n if (!source)\n return null;\n if (source instanceof BABYLON.Mesh) {\n return null;\n }\n if (source instanceof BABYLON.SubMesh) {\n return source.clone(destinationObject);\n }\n else if (source.clone) {\n return source.clone();\n }\n return null;\n };\n var Tools = /** @class */ (function () {\n function Tools() {\n }\n /**\n * Read the content of a byte array at a specified coordinates (taking in account wrapping)\n * @param u defines the coordinate on X axis\n * @param v defines the coordinate on Y axis\n * @param width defines the width of the source data\n * @param height defines the height of the source data\n * @param pixels defines the source byte array\n * @param color defines the output color\n */\n Tools.FetchToRef = function (u, v, width, height, pixels, color) {\n var wrappedU = ((Math.abs(u) * width) % width) | 0;\n var wrappedV = ((Math.abs(v) * height) % height) | 0;\n var position = (wrappedU + wrappedV * width) * 4;\n color.r = pixels[position] / 255;\n color.g = pixels[position + 1] / 255;\n color.b = pixels[position + 2] / 255;\n color.a = pixels[position + 3] / 255;\n };\n /**\n * Interpolates between a and b via alpha\n * @param a The lower value (returned when alpha = 0)\n * @param b The upper value (returned when alpha = 1)\n * @param alpha The interpolation-factor\n * @return The mixed value\n */\n Tools.Mix = function (a, b, alpha) {\n return a * (1 - alpha) + b * alpha;\n };\n Tools.Instantiate = function (className) {\n if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {\n return Tools.RegisteredExternalClasses[className];\n }\n var arr = className.split(\".\");\n var fn = (window || this);\n for (var i = 0, len = arr.length; i < len; i++) {\n fn = fn[arr[i]];\n }\n if (typeof fn !== \"function\") {\n return null;\n }\n return fn;\n };\n /**\n * Provides a slice function that will work even on IE\n * @param data defines the array to slice\n * @param start defines the start of the data (optional)\n * @param end defines the end of the data (optional)\n * @returns the new sliced array\n */\n Tools.Slice = function (data, start, end) {\n if (data.slice) {\n return data.slice(start, end);\n }\n return Array.prototype.slice.call(data, start, end);\n };\n Tools.SetImmediate = function (action) {\n if (Tools.IsWindowObjectExist() && window.setImmediate) {\n window.setImmediate(action);\n }\n else {\n setTimeout(action, 1);\n }\n };\n Tools.IsExponentOfTwo = function (value) {\n var count = 1;\n do {\n count *= 2;\n } while (count < value);\n return count === value;\n };\n /**\n * Returns the nearest 32-bit single precision float representation of a Number\n * @param value A Number. If the parameter is of a different type, it will get converted\n * to a number or to NaN if it cannot be converted\n * @returns number\n */\n Tools.FloatRound = function (value) {\n if (Math.fround) {\n return Math.fround(value);\n }\n return (Tools._tmpFloatArray[0] = value);\n };\n /**\n * Find the next highest power of two.\n * @param x Number to start search from.\n * @return Next highest power of two.\n */\n Tools.CeilingPOT = function (x) {\n x--;\n x |= x >> 1;\n x |= x >> 2;\n x |= x >> 4;\n x |= x >> 8;\n x |= x >> 16;\n x++;\n return x;\n };\n /**\n * Find the next lowest power of two.\n * @param x Number to start search from.\n * @return Next lowest power of two.\n */\n Tools.FloorPOT = function (x) {\n x = x | (x >> 1);\n x = x | (x >> 2);\n x = x | (x >> 4);\n x = x | (x >> 8);\n x = x | (x >> 16);\n return x - (x >> 1);\n };\n /**\n * Find the nearest power of two.\n * @param x Number to start search from.\n * @return Next nearest power of two.\n */\n Tools.NearestPOT = function (x) {\n var c = Tools.CeilingPOT(x);\n var f = Tools.FloorPOT(x);\n return (c - x) > (x - f) ? f : c;\n };\n Tools.GetExponentOfTwo = function (value, max, mode) {\n if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }\n var pot;\n switch (mode) {\n case BABYLON.Engine.SCALEMODE_FLOOR:\n pot = Tools.FloorPOT(value);\n break;\n case BABYLON.Engine.SCALEMODE_NEAREST:\n pot = Tools.NearestPOT(value);\n break;\n case BABYLON.Engine.SCALEMODE_CEILING:\n default:\n pot = Tools.CeilingPOT(value);\n break;\n }\n return Math.min(pot, max);\n };\n Tools.GetFilename = function (path) {\n var index = path.lastIndexOf(\"/\");\n if (index < 0)\n return path;\n return path.substring(index + 1);\n };\n /**\n * Extracts the \"folder\" part of a path (everything before the filename).\n * @param uri The URI to extract the info from\n * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present\n * @returns The \"folder\" part of the path\n */\n Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {\n if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }\n var index = uri.lastIndexOf(\"/\");\n if (index < 0) {\n if (returnUnchangedIfNoSlash) {\n return uri;\n }\n return \"\";\n }\n return uri.substring(0, index + 1);\n };\n Tools.GetDOMTextContent = function (element) {\n var result = \"\";\n var child = element.firstChild;\n while (child) {\n if (child.nodeType === 3) {\n result += child.textContent;\n }\n child = child.nextSibling;\n }\n return result;\n };\n Tools.ToDegrees = function (angle) {\n return angle * 180 / Math.PI;\n };\n Tools.ToRadians = function (angle) {\n return angle * Math.PI / 180;\n };\n Tools.EncodeArrayBufferTobase64 = function (buffer) {\n var keyStr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n var output = \"\";\n var chr1, chr2, chr3, enc1, enc2, enc3, enc4;\n var i = 0;\n var bytes = new Uint8Array(buffer);\n while (i < bytes.length) {\n chr1 = bytes[i++];\n chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index \n chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here\n enc1 = chr1 >> 2;\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\n enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);\n enc4 = chr3 & 63;\n if (isNaN(chr2)) {\n enc3 = enc4 = 64;\n }\n else if (isNaN(chr3)) {\n enc4 = 64;\n }\n output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +\n keyStr.charAt(enc3) + keyStr.charAt(enc4);\n }\n return \"data:image/png;base64,\" + output;\n };\n Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {\n if (bias === void 0) { bias = null; }\n var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n for (var index = indexStart; index < indexStart + indexCount; index++) {\n var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);\n minimum = BABYLON.Vector3.Minimize(current, minimum);\n maximum = BABYLON.Vector3.Maximize(current, maximum);\n }\n if (bias) {\n minimum.x -= minimum.x * bias.x + bias.y;\n minimum.y -= minimum.y * bias.x + bias.y;\n minimum.z -= minimum.z * bias.x + bias.y;\n maximum.x += maximum.x * bias.x + bias.y;\n maximum.y += maximum.y * bias.x + bias.y;\n maximum.z += maximum.z * bias.x + bias.y;\n }\n return {\n minimum: minimum,\n maximum: maximum\n };\n };\n Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {\n if (bias === void 0) { bias = null; }\n var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n if (!stride) {\n stride = 3;\n }\n for (var index = start; index < start + count; index++) {\n var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);\n minimum = BABYLON.Vector3.Minimize(current, minimum);\n maximum = BABYLON.Vector3.Maximize(current, maximum);\n }\n if (bias) {\n minimum.x -= minimum.x * bias.x + bias.y;\n minimum.y -= minimum.y * bias.x + bias.y;\n minimum.z -= minimum.z * bias.x + bias.y;\n maximum.x += maximum.x * bias.x + bias.y;\n maximum.y += maximum.y * bias.x + bias.y;\n maximum.z += maximum.z * bias.x + bias.y;\n }\n return {\n minimum: minimum,\n maximum: maximum\n };\n };\n Tools.Vector2ArrayFeeder = function (array) {\n return function (index) {\n var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);\n var length = isFloatArray ? array.length / 2 : array.length;\n if (index >= length) {\n return null;\n }\n if (isFloatArray) {\n var fa = array;\n return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);\n }\n var a = array;\n return a[index];\n };\n };\n Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {\n if (bias === void 0) { bias = null; }\n var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);\n var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);\n var i = 0;\n var cur = feeder(i++);\n while (cur) {\n minimum = BABYLON.Vector2.Minimize(cur, minimum);\n maximum = BABYLON.Vector2.Maximize(cur, maximum);\n cur = feeder(i++);\n }\n if (bias) {\n minimum.x -= minimum.x * bias.x + bias.y;\n minimum.y -= minimum.y * bias.x + bias.y;\n maximum.x += maximum.x * bias.x + bias.y;\n maximum.y += maximum.y * bias.x + bias.y;\n }\n return {\n minimum: minimum,\n maximum: maximum\n };\n };\n Tools.MakeArray = function (obj, allowsNullUndefined) {\n if (allowsNullUndefined !== true && (obj === undefined || obj == null))\n return null;\n return Array.isArray(obj) ? obj : [obj];\n };\n // Misc.\n Tools.GetPointerPrefix = function () {\n var eventPrefix = \"pointer\";\n // Check if pointer events are supported\n if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {\n eventPrefix = \"mouse\";\n }\n return eventPrefix;\n };\n /**\n * @param func - the function to be called\n * @param requester - the object that will request the next frame. Falls back to window.\n */\n Tools.QueueNewFrame = function (func, requester) {\n if (!Tools.IsWindowObjectExist()) {\n return setTimeout(func, 16);\n }\n if (!requester) {\n requester = window;\n }\n if (requester.requestAnimationFrame) {\n return requester.requestAnimationFrame(func);\n }\n else if (requester.msRequestAnimationFrame) {\n return requester.msRequestAnimationFrame(func);\n }\n else if (requester.webkitRequestAnimationFrame) {\n return requester.webkitRequestAnimationFrame(func);\n }\n else if (requester.mozRequestAnimationFrame) {\n return requester.mozRequestAnimationFrame(func);\n }\n else if (requester.oRequestAnimationFrame) {\n return requester.oRequestAnimationFrame(func);\n }\n else {\n return window.setTimeout(func, 16);\n }\n };\n Tools.RequestFullscreen = function (element) {\n var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;\n if (!requestFunction)\n return;\n requestFunction.call(element);\n };\n Tools.ExitFullscreen = function () {\n if (document.exitFullscreen) {\n document.exitFullscreen();\n }\n else if (document.mozCancelFullScreen) {\n document.mozCancelFullScreen();\n }\n else if (document.webkitCancelFullScreen) {\n document.webkitCancelFullScreen();\n }\n else if (document.msCancelFullScreen) {\n document.msCancelFullScreen();\n }\n };\n Tools.SetCorsBehavior = function (url, element) {\n if (url && url.indexOf(\"data:\") === 0) {\n return;\n }\n if (Tools.CorsBehavior) {\n if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {\n element.crossOrigin = Tools.CorsBehavior;\n }\n else {\n var result = Tools.CorsBehavior(url);\n if (result) {\n element.crossOrigin = result;\n }\n }\n }\n };\n // External files\n Tools.CleanUrl = function (url) {\n url = url.replace(/#/mg, \"%23\");\n return url;\n };\n /**\n * Loads an image as an HTMLImageElement.\n * @param input url string, ArrayBuffer, or Blob to load\n * @param onLoad callback called when the image successfully loads\n * @param onError callback called when the image fails to load\n * @param database database for caching\n * @returns the HTMLImageElement of the loaded image\n */\n Tools.LoadImage = function (input, onLoad, onError, database) {\n var url;\n var usingObjectURL = false;\n if (input instanceof ArrayBuffer) {\n url = URL.createObjectURL(new Blob([input]));\n usingObjectURL = true;\n }\n else if (input instanceof Blob) {\n url = URL.createObjectURL(input);\n usingObjectURL = true;\n }\n else {\n url = Tools.CleanUrl(input);\n url = Tools.PreprocessUrl(input);\n }\n var img = new Image();\n Tools.SetCorsBehavior(url, img);\n var loadHandler = function () {\n if (usingObjectURL && img.src) {\n URL.revokeObjectURL(img.src);\n }\n img.removeEventListener(\"load\", loadHandler);\n img.removeEventListener(\"error\", errorHandler);\n onLoad(img);\n };\n var errorHandler = function (err) {\n if (usingObjectURL && img.src) {\n URL.revokeObjectURL(img.src);\n }\n img.removeEventListener(\"load\", loadHandler);\n img.removeEventListener(\"error\", errorHandler);\n Tools.Error(\"Error while trying to load image: \" + input);\n if (onError) {\n onError(\"Error while trying to load image: \" + input, err);\n }\n };\n img.addEventListener(\"load\", loadHandler);\n img.addEventListener(\"error\", errorHandler);\n var noIndexedDB = function () {\n img.src = url;\n };\n var loadFromIndexedDB = function () {\n if (database) {\n database.loadImageFromDB(url, img);\n }\n };\n //ANY database to do!\n if (url.substr(0, 5) !== \"data:\" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {\n database.openAsync(loadFromIndexedDB, noIndexedDB);\n }\n else {\n if (url.indexOf(\"file:\") !== -1) {\n var textureName = decodeURIComponent(url.substring(5).toLowerCase());\n if (BABYLON.FilesInput.FilesToLoad[textureName]) {\n try {\n var blobURL;\n try {\n blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });\n }\n catch (ex) {\n // Chrome doesn't support oneTimeOnly parameter\n blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);\n }\n img.src = blobURL;\n usingObjectURL = true;\n }\n catch (e) {\n img.src = \"\";\n }\n return img;\n }\n }\n noIndexedDB();\n }\n return img;\n };\n Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {\n url = Tools.CleanUrl(url);\n url = Tools.PreprocessUrl(url);\n // If file and file input are set\n if (url.indexOf(\"file:\") !== -1) {\n var fileName = decodeURIComponent(url.substring(5).toLowerCase());\n if (BABYLON.FilesInput.FilesToLoad[fileName]) {\n return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);\n }\n }\n var loadUrl = Tools.BaseUrl + url;\n var aborted = false;\n var fileRequest = {\n onCompleteObservable: new BABYLON.Observable(),\n abort: function () { return aborted = true; },\n };\n var requestFile = function () {\n var request = new XMLHttpRequest();\n var retryHandle = null;\n fileRequest.abort = function () {\n aborted = true;\n if (request.readyState !== (XMLHttpRequest.DONE || 4)) {\n request.abort();\n }\n if (retryHandle !== null) {\n clearTimeout(retryHandle);\n retryHandle = null;\n }\n };\n var retryLoop = function (retryIndex) {\n request.open('GET', loadUrl, true);\n if (useArrayBuffer) {\n request.responseType = \"arraybuffer\";\n }\n if (onProgress) {\n request.addEventListener(\"progress\", onProgress);\n }\n var onLoadEnd = function () {\n request.removeEventListener(\"loadend\", onLoadEnd);\n fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n fileRequest.onCompleteObservable.clear();\n };\n request.addEventListener(\"loadend\", onLoadEnd);\n var onReadyStateChange = function () {\n if (aborted) {\n return;\n }\n // In case of undefined state in some browsers.\n if (request.readyState === (XMLHttpRequest.DONE || 4)) {\n // Some browsers have issues where onreadystatechange can be called multiple times with the same value.\n request.removeEventListener(\"readystatechange\", onReadyStateChange);\n if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {\n onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);\n return;\n }\n var retryStrategy = Tools.DefaultRetryStrategy;\n if (retryStrategy) {\n var waitTime = retryStrategy(loadUrl, request, retryIndex);\n if (waitTime !== -1) {\n // Prevent the request from completing for retry.\n request.removeEventListener(\"loadend\", onLoadEnd);\n request = new XMLHttpRequest();\n retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);\n return;\n }\n }\n var e = new LoadFileError(\"Error status: \" + request.status + \" \" + request.statusText + \" - Unable to load \" + loadUrl, request);\n if (onError) {\n onError(request, e);\n }\n else {\n throw e;\n }\n }\n };\n request.addEventListener(\"readystatechange\", onReadyStateChange);\n request.send();\n };\n retryLoop(0);\n };\n // Caching all files\n if (database && database.enableSceneOffline) {\n var noIndexedDB_1 = function (request) {\n if (request && request.status > 400) {\n if (onError) {\n onError(request);\n }\n }\n else {\n if (!aborted) {\n requestFile();\n }\n }\n };\n var loadFromIndexedDB = function () {\n // TODO: database needs to support aborting and should return a IFileRequest\n if (aborted) {\n return;\n }\n if (database) {\n database.loadFileFromDB(url, function (data) {\n if (!aborted) {\n onSuccess(data);\n }\n fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n }, onProgress ? function (event) {\n if (!aborted) {\n onProgress(event);\n }\n } : undefined, noIndexedDB_1, useArrayBuffer);\n }\n };\n database.openAsync(loadFromIndexedDB, noIndexedDB_1);\n }\n else {\n requestFile();\n }\n return fileRequest;\n };\n /**\n * Load a script (identified by an url). When the url returns, the\n * content of this file is added into a new script element, attached to the DOM (body element)\n */\n Tools.LoadScript = function (scriptUrl, onSuccess, onError) {\n var head = document.getElementsByTagName('head')[0];\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.src = scriptUrl;\n script.onload = function () {\n if (onSuccess) {\n onSuccess();\n }\n };\n script.onerror = function (e) {\n if (onError) {\n onError(\"Unable to load script '\" + scriptUrl + \"'\", e);\n }\n };\n head.appendChild(script);\n };\n Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {\n var reader = new FileReader();\n var request = {\n onCompleteObservable: new BABYLON.Observable(),\n abort: function () { return reader.abort(); },\n };\n reader.onloadend = function (e) {\n request.onCompleteObservable.notifyObservers(request);\n };\n reader.onload = function (e) {\n //target doesn't have result from ts 1.3\n callback(e.target['result']);\n };\n reader.onprogress = progressCallback;\n reader.readAsDataURL(fileToLoad);\n return request;\n };\n Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {\n var reader = new FileReader();\n var request = {\n onCompleteObservable: new BABYLON.Observable(),\n abort: function () { return reader.abort(); },\n };\n reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };\n reader.onerror = function (e) {\n Tools.Log(\"Error while reading file: \" + fileToLoad.name);\n callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));\n };\n reader.onload = function (e) {\n //target doesn't have result from ts 1.3\n callback(e.target['result']);\n };\n if (progressCallBack) {\n reader.onprogress = progressCallBack;\n }\n if (!useArrayBuffer) {\n // Asynchronous read\n reader.readAsText(fileToLoad);\n }\n else {\n reader.readAsArrayBuffer(fileToLoad);\n }\n return request;\n };\n //returns a downloadable url to a file content.\n Tools.FileAsURL = function (content) {\n var fileBlob = new Blob([content]);\n var url = window.URL || window.webkitURL;\n var link = url.createObjectURL(fileBlob);\n return link;\n };\n // Misc.\n Tools.Format = function (value, decimals) {\n if (decimals === void 0) { decimals = 2; }\n return value.toFixed(decimals);\n };\n Tools.CheckExtends = function (v, min, max) {\n if (v.x < min.x)\n min.x = v.x;\n if (v.y < min.y)\n min.y = v.y;\n if (v.z < min.z)\n min.z = v.z;\n if (v.x > max.x)\n max.x = v.x;\n if (v.y > max.y)\n max.y = v.y;\n if (v.z > max.z)\n max.z = v.z;\n };\n Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {\n for (var prop in source) {\n if (prop[0] === \"_\" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {\n continue;\n }\n if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {\n continue;\n }\n var sourceValue = source[prop];\n var typeOfSourceValue = typeof sourceValue;\n if (typeOfSourceValue === \"function\") {\n continue;\n }\n try {\n if (typeOfSourceValue === \"object\") {\n if (sourceValue instanceof Array) {\n destination[prop] = [];\n if (sourceValue.length > 0) {\n if (typeof sourceValue[0] == \"object\") {\n for (var index = 0; index < sourceValue.length; index++) {\n var clonedValue = cloneValue(sourceValue[index], destination);\n if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done\n destination[prop].push(clonedValue);\n }\n }\n }\n else {\n destination[prop] = sourceValue.slice(0);\n }\n }\n }\n else {\n destination[prop] = cloneValue(sourceValue, destination);\n }\n }\n else {\n destination[prop] = sourceValue;\n }\n }\n catch (e) {\n // Just ignore error (it could be because of a read-only property)\n }\n }\n };\n Tools.IsEmpty = function (obj) {\n for (var i in obj) {\n if (obj.hasOwnProperty(i)) {\n return false;\n }\n }\n return true;\n };\n Tools.RegisterTopRootEvents = function (events) {\n for (var index = 0; index < events.length; index++) {\n var event = events[index];\n window.addEventListener(event.name, event.handler, false);\n try {\n if (window.parent) {\n window.parent.addEventListener(event.name, event.handler, false);\n }\n }\n catch (e) {\n // Silently fails...\n }\n }\n };\n Tools.UnregisterTopRootEvents = function (events) {\n for (var index = 0; index < events.length; index++) {\n var event = events[index];\n window.removeEventListener(event.name, event.handler);\n try {\n if (window.parent) {\n window.parent.removeEventListener(event.name, event.handler);\n }\n }\n catch (e) {\n // Silently fails...\n }\n }\n };\n Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {\n if (mimeType === void 0) { mimeType = \"image/png\"; }\n // Read the contents of the framebuffer\n var numberOfChannelsByLine = width * 4;\n var halfHeight = height / 2;\n //Reading datas from WebGL\n var data = engine.readPixels(0, 0, width, height);\n //To flip image on Y axis.\n for (var i = 0; i < halfHeight; i++) {\n for (var j = 0; j < numberOfChannelsByLine; j++) {\n var currentCell = j + i * numberOfChannelsByLine;\n var targetLine = height - i - 1;\n var targetCell = j + targetLine * numberOfChannelsByLine;\n var temp = data[currentCell];\n data[currentCell] = data[targetCell];\n data[targetCell] = temp;\n }\n }\n // Create a 2D canvas to store the result\n if (!screenshotCanvas) {\n screenshotCanvas = document.createElement('canvas');\n }\n screenshotCanvas.width = width;\n screenshotCanvas.height = height;\n var context = screenshotCanvas.getContext('2d');\n if (context) {\n // Copy the pixels to a 2D canvas\n var imageData = context.createImageData(width, height);\n var castData = (imageData.data);\n castData.set(data);\n context.putImageData(imageData, 0, 0);\n Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);\n }\n };\n /**\n * Converts the canvas data to blob.\n * This acts as a polyfill for browsers not supporting the to blob function.\n * @param canvas Defines the canvas to extract the data from\n * @param successCallback Defines the callback triggered once the data are available\n * @param mimeType Defines the mime type of the result\n */\n Tools.ToBlob = function (canvas, successCallback, mimeType) {\n if (mimeType === void 0) { mimeType = \"image/png\"; }\n // We need HTMLCanvasElement.toBlob for HD screenshots\n if (!canvas.toBlob) {\n // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)\n canvas.toBlob = function (callback, type, quality) {\n var _this = this;\n setTimeout(function () {\n var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);\n for (var i = 0; i < len; i++) {\n arr[i] = binStr.charCodeAt(i);\n }\n callback(new Blob([arr]));\n });\n };\n }\n canvas.toBlob(function (blob) {\n successCallback(blob);\n }, mimeType);\n };\n /**\n * Encodes the canvas data to base 64 or automatically download the result if filename is defined\n * @param successCallback Defines the callback triggered once the data are available\n * @param mimeType Defines the mime type of the result\n * @param fileName The filename to download. If present, the result will automatically be downloaded\n */\n Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {\n if (mimeType === void 0) { mimeType = \"image/png\"; }\n if (successCallback) {\n var base64Image = screenshotCanvas.toDataURL(mimeType);\n successCallback(base64Image);\n }\n else {\n this.ToBlob(screenshotCanvas, function (blob) {\n //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.\n if ((\"download\" in document.createElement(\"a\"))) {\n if (!fileName) {\n var date = new Date();\n var stringDate = (date.getFullYear() + \"-\" + (date.getMonth() + 1)).slice(2) + \"-\" + date.getDate() + \"_\" + date.getHours() + \"-\" + ('0' + date.getMinutes()).slice(-2);\n fileName = \"screenshot_\" + stringDate + \".png\";\n }\n Tools.Download(blob, fileName);\n }\n else {\n var url = URL.createObjectURL(blob);\n var newWindow = window.open(\"\");\n if (!newWindow)\n return;\n var img = newWindow.document.createElement(\"img\");\n img.onload = function () {\n // no longer need to read the blob so it's revoked\n URL.revokeObjectURL(url);\n };\n img.src = url;\n newWindow.document.body.appendChild(img);\n }\n }, mimeType);\n }\n };\n /**\n * Downloads a blob in the browser\n * @param blob defines the blob to download\n * @param fileName defines the name of the downloaded file\n */\n Tools.Download = function (blob, fileName) {\n if (navigator && navigator.msSaveBlob) {\n navigator.msSaveBlob(blob, fileName);\n return;\n }\n var url = window.URL.createObjectURL(blob);\n var a = document.createElement(\"a\");\n document.body.appendChild(a);\n a.style.display = \"none\";\n a.href = url;\n a.download = fileName;\n a.addEventListener(\"click\", function () {\n if (a.parentElement) {\n a.parentElement.removeChild(a);\n }\n });\n a.click();\n window.URL.revokeObjectURL(url);\n };\n Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {\n if (mimeType === void 0) { mimeType = \"image/png\"; }\n var width;\n var height;\n // If a precision value is specified\n if (size.precision) {\n width = Math.round(engine.getRenderWidth() * size.precision);\n height = Math.round(width / engine.getAspectRatio(camera));\n }\n else if (size.width && size.height) {\n width = size.width;\n height = size.height;\n }\n //If passing only width, computing height to keep display canvas ratio.\n else if (size.width && !size.height) {\n width = size.width;\n height = Math.round(width / engine.getAspectRatio(camera));\n }\n //If passing only height, computing width to keep display canvas ratio.\n else if (size.height && !size.width) {\n height = size.height;\n width = Math.round(height * engine.getAspectRatio(camera));\n }\n //Assuming here that \"size\" parameter is a number\n else if (!isNaN(size)) {\n height = size;\n width = size;\n }\n else {\n Tools.Error(\"Invalid 'size' parameter !\");\n return;\n }\n if (!screenshotCanvas) {\n screenshotCanvas = document.createElement('canvas');\n }\n screenshotCanvas.width = width;\n screenshotCanvas.height = height;\n var renderContext = screenshotCanvas.getContext(\"2d\");\n var ratio = engine.getRenderWidth() / engine.getRenderHeight();\n var newWidth = width;\n var newHeight = newWidth / ratio;\n if (newHeight > height) {\n newHeight = height;\n newWidth = newHeight * ratio;\n }\n var offsetX = Math.max(0, width - newWidth) / 2;\n var offsetY = Math.max(0, height - newHeight) / 2;\n var renderingCanvas = engine.getRenderingCanvas();\n if (renderContext && renderingCanvas) {\n renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);\n }\n Tools.EncodeScreenshotCanvasData(successCallback, mimeType);\n };\n /**\n * Generates an image screenshot from the specified camera.\n *\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution.\n * @param successCallback The callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it.\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types.\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @constructor\n */\n Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {\n if (mimeType === void 0) { mimeType = \"image/png\"; }\n if (samples === void 0) { samples = 1; }\n if (antialiasing === void 0) { antialiasing = false; }\n var width;\n var height;\n //If a precision value is specified\n if (size.precision) {\n width = Math.round(engine.getRenderWidth() * size.precision);\n height = Math.round(width / engine.getAspectRatio(camera));\n size = { width: width, height: height };\n }\n else if (size.width && size.height) {\n width = size.width;\n height = size.height;\n }\n //If passing only width, computing height to keep display canvas ratio.\n else if (size.width && !size.height) {\n width = size.width;\n height = Math.round(width / engine.getAspectRatio(camera));\n size = { width: width, height: height };\n }\n //If passing only height, computing width to keep display canvas ratio.\n else if (size.height && !size.width) {\n height = size.height;\n width = Math.round(height * engine.getAspectRatio(camera));\n size = { width: width, height: height };\n }\n //Assuming here that \"size\" parameter is a number\n else if (!isNaN(size)) {\n height = size;\n width = size;\n }\n else {\n Tools.Error(\"Invalid 'size' parameter !\");\n return;\n }\n var scene = camera.getScene();\n var previousCamera = null;\n if (scene.activeCamera !== camera) {\n previousCamera = scene.activeCamera;\n scene.activeCamera = camera;\n }\n //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)\n var texture = new BABYLON.RenderTargetTexture(\"screenShot\", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);\n texture.renderList = null;\n texture.samples = samples;\n if (antialiasing) {\n texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));\n }\n texture.onAfterRenderObservable.add(function () {\n Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);\n });\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n texture.render(true);\n texture.dispose();\n if (previousCamera) {\n scene.activeCamera = previousCamera;\n }\n camera.getProjectionMatrix(true); // Force cache refresh;\n };\n // XHR response validator for local file scenario\n Tools.ValidateXHRData = function (xhr, dataType) {\n // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all\n if (dataType === void 0) { dataType = 7; }\n try {\n if (dataType & 1) {\n if (xhr.responseText && xhr.responseText.length > 0) {\n return true;\n }\n else if (dataType === 1) {\n return false;\n }\n }\n if (dataType & 2) {\n // Check header width and height since there is no \"TGA\" magic number\n var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);\n if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {\n return true;\n }\n else if (dataType === 2) {\n return false;\n }\n }\n if (dataType & 4) {\n // Check for the \"DDS\" magic number\n var ddsHeader = new Uint8Array(xhr.response, 0, 3);\n if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {\n return true;\n }\n else {\n return false;\n }\n }\n }\n catch (e) {\n // Global protection\n }\n return false;\n };\n /**\n * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523\n * Be aware Math.random() could cause collisions, but:\n * \"All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide\"\n */\n Tools.RandomId = function () {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n };\n /**\n * Test if the given uri is a base64 string.\n * @param uri The uri to test\n * @return True if the uri is a base64 string or false otherwise.\n */\n Tools.IsBase64 = function (uri) {\n return uri.length < 5 ? false : uri.substr(0, 5) === \"data:\";\n };\n /**\n * Decode the given base64 uri.\n * @param uri The uri to decode\n * @return The decoded base64 data.\n */\n Tools.DecodeBase64 = function (uri) {\n var decodedString = atob(uri.split(\",\")[1]);\n var bufferLength = decodedString.length;\n var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));\n for (var i = 0; i < bufferLength; i++) {\n bufferView[i] = decodedString.charCodeAt(i);\n }\n return bufferView.buffer;\n };\n Object.defineProperty(Tools, \"NoneLogLevel\", {\n get: function () {\n return Tools._NoneLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"MessageLogLevel\", {\n get: function () {\n return Tools._MessageLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"WarningLogLevel\", {\n get: function () {\n return Tools._WarningLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"ErrorLogLevel\", {\n get: function () {\n return Tools._ErrorLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"AllLogLevel\", {\n get: function () {\n return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Tools._AddLogEntry = function (entry) {\n Tools._LogCache = entry + Tools._LogCache;\n if (Tools.OnNewCacheEntry) {\n Tools.OnNewCacheEntry(entry);\n }\n };\n Tools._FormatMessage = function (message) {\n var padStr = function (i) { return (i < 10) ? \"0\" + i : \"\" + i; };\n var date = new Date();\n return \"[\" + padStr(date.getHours()) + \":\" + padStr(date.getMinutes()) + \":\" + padStr(date.getSeconds()) + \"]: \" + message;\n };\n Tools._LogDisabled = function (message) {\n // nothing to do\n };\n Tools._LogEnabled = function (message) {\n var formattedMessage = Tools._FormatMessage(message);\n console.log(\"BJS - \" + formattedMessage);\n var entry = \"
\" + formattedMessage + \"

\";\n Tools._AddLogEntry(entry);\n };\n Tools._WarnDisabled = function (message) {\n // nothing to do\n };\n Tools._WarnEnabled = function (message) {\n var formattedMessage = Tools._FormatMessage(message);\n console.warn(\"BJS - \" + formattedMessage);\n var entry = \"
\" + formattedMessage + \"

\";\n Tools._AddLogEntry(entry);\n };\n Tools._ErrorDisabled = function (message) {\n // nothing to do\n };\n Tools._ErrorEnabled = function (message) {\n Tools.errorsCount++;\n var formattedMessage = Tools._FormatMessage(message);\n console.error(\"BJS - \" + formattedMessage);\n var entry = \"
\" + formattedMessage + \"

\";\n Tools._AddLogEntry(entry);\n };\n Object.defineProperty(Tools, \"LogCache\", {\n get: function () {\n return Tools._LogCache;\n },\n enumerable: true,\n configurable: true\n });\n Tools.ClearLogCache = function () {\n Tools._LogCache = \"\";\n Tools.errorsCount = 0;\n };\n Object.defineProperty(Tools, \"LogLevels\", {\n set: function (level) {\n if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {\n Tools.Log = Tools._LogEnabled;\n }\n else {\n Tools.Log = Tools._LogDisabled;\n }\n if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {\n Tools.Warn = Tools._WarnEnabled;\n }\n else {\n Tools.Warn = Tools._WarnDisabled;\n }\n if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {\n Tools.Error = Tools._ErrorEnabled;\n }\n else {\n Tools.Error = Tools._ErrorDisabled;\n }\n },\n enumerable: true,\n configurable: true\n });\n Tools.IsWindowObjectExist = function () {\n return (typeof window) !== \"undefined\";\n };\n Object.defineProperty(Tools, \"PerformanceNoneLogLevel\", {\n get: function () {\n return Tools._PerformanceNoneLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"PerformanceUserMarkLogLevel\", {\n get: function () {\n return Tools._PerformanceUserMarkLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"PerformanceConsoleLogLevel\", {\n get: function () {\n return Tools._PerformanceConsoleLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"PerformanceLogLevel\", {\n set: function (level) {\n if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {\n Tools.StartPerformanceCounter = Tools._StartUserMark;\n Tools.EndPerformanceCounter = Tools._EndUserMark;\n return;\n }\n if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {\n Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;\n Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;\n return;\n }\n Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;\n Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;\n },\n enumerable: true,\n configurable: true\n });\n Tools._StartPerformanceCounterDisabled = function (counterName, condition) {\n };\n Tools._EndPerformanceCounterDisabled = function (counterName, condition) {\n };\n Tools._StartUserMark = function (counterName, condition) {\n if (condition === void 0) { condition = true; }\n if (!Tools._performance) {\n if (!Tools.IsWindowObjectExist()) {\n return;\n }\n Tools._performance = window.performance;\n }\n if (!condition || !Tools._performance.mark) {\n return;\n }\n Tools._performance.mark(counterName + \"-Begin\");\n };\n Tools._EndUserMark = function (counterName, condition) {\n if (condition === void 0) { condition = true; }\n if (!condition || !Tools._performance.mark) {\n return;\n }\n Tools._performance.mark(counterName + \"-End\");\n Tools._performance.measure(counterName, counterName + \"-Begin\", counterName + \"-End\");\n };\n Tools._StartPerformanceConsole = function (counterName, condition) {\n if (condition === void 0) { condition = true; }\n if (!condition) {\n return;\n }\n Tools._StartUserMark(counterName, condition);\n if (console.time) {\n console.time(counterName);\n }\n };\n Tools._EndPerformanceConsole = function (counterName, condition) {\n if (condition === void 0) { condition = true; }\n if (!condition) {\n return;\n }\n Tools._EndUserMark(counterName, condition);\n if (console.time) {\n console.timeEnd(counterName);\n }\n };\n Object.defineProperty(Tools, \"Now\", {\n get: function () {\n if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {\n return window.performance.now();\n }\n return Date.now();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * This method will return the name of the class used to create the instance of the given object.\n * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.\n * @param object the object to get the class name from\n * @return the name of the class, will be \"object\" for a custom data type not using the @className decorator\n */\n Tools.GetClassName = function (object, isType) {\n if (isType === void 0) { isType = false; }\n var name = null;\n if (!isType && object.getClassName) {\n name = object.getClassName();\n }\n else {\n if (object instanceof Object) {\n var classObj = isType ? object : Object.getPrototypeOf(object);\n name = classObj.constructor[\"__bjsclassName__\"];\n }\n if (!name) {\n name = typeof object;\n }\n }\n return name;\n };\n Tools.First = function (array, predicate) {\n for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {\n var el = array_1[_i];\n if (predicate(el)) {\n return el;\n }\n }\n return null;\n };\n /**\n * This method will return the name of the full name of the class, including its owning module (if any).\n * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).\n * @param object the object to get the class name from\n * @return a string that can have two forms: \"moduleName.className\" if module was specified when the class' Name was registered or \"className\" if there was not module specified.\n */\n Tools.getFullClassName = function (object, isType) {\n if (isType === void 0) { isType = false; }\n var className = null;\n var moduleName = null;\n if (!isType && object.getClassName) {\n className = object.getClassName();\n }\n else {\n if (object instanceof Object) {\n var classObj = isType ? object : Object.getPrototypeOf(object);\n className = classObj.constructor[\"__bjsclassName__\"];\n moduleName = classObj.constructor[\"__bjsmoduleName__\"];\n }\n if (!className) {\n className = typeof object;\n }\n }\n if (!className) {\n return null;\n }\n return ((moduleName != null) ? (moduleName + \".\") : \"\") + className;\n };\n /**\n * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.\n * @param array\n */\n Tools.arrayOrStringFeeder = function (array) {\n return function (index) {\n if (index >= array.length) {\n return null;\n }\n var val = array.charCodeAt ? array.charCodeAt(index) : array[index];\n if (val && val.getHashCode) {\n val = val.getHashCode();\n }\n if (typeof val === \"string\") {\n return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));\n }\n return val;\n };\n };\n /**\n * Compute the hashCode of a stream of number\n * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.\n * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.\n * @return the hash code computed\n */\n Tools.hashCodeFromStream = function (feeder) {\n // Based from here: http://stackoverflow.com/a/7616484/802124\n var hash = 0;\n var index = 0;\n var chr = feeder(index++);\n while (chr != null) {\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n chr = feeder(index++);\n }\n return hash;\n };\n /**\n * Returns a promise that resolves after the given amount of time.\n * @param delay Number of milliseconds to delay\n * @returns Promise that resolves after the given amount of time\n */\n Tools.DelayAsync = function (delay) {\n return new Promise(function (resolve) {\n setTimeout(function () {\n resolve();\n }, delay);\n });\n };\n /**\n * Gets the current gradient from an array of IValueGradient\n * @param ratio defines the current ratio to get\n * @param gradients defines the array of IValueGradient\n * @param updateFunc defines the callback function used to get the final value from the selected gradients\n */\n Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {\n for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {\n var currentGradient = gradients[gradientIndex];\n var nextGradient = gradients[gradientIndex + 1];\n if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {\n var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);\n updateFunc(currentGradient, nextGradient, scale);\n }\n }\n };\n Tools.BaseUrl = \"\";\n Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();\n /**\n * Default behaviour for cors in the application.\n * It can be a string if the expected behavior is identical in the entire app.\n * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)\n */\n Tools.CorsBehavior = \"anonymous\";\n Tools.UseFallbackTexture = true;\n /**\n * Use this object to register external classes like custom textures or material\n * to allow the laoders to instantiate them\n */\n Tools.RegisteredExternalClasses = {};\n // Used in case of a texture loading problem \n Tools.fallbackTexture = \"data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z\";\n Tools._tmpFloatArray = new Float32Array(1);\n Tools.PreprocessUrl = function (url) {\n return url;\n };\n // Logs\n Tools._NoneLogLevel = 0;\n Tools._MessageLogLevel = 1;\n Tools._WarningLogLevel = 2;\n Tools._ErrorLogLevel = 4;\n Tools._LogCache = \"\";\n Tools.errorsCount = 0;\n Tools.Log = Tools._LogEnabled;\n Tools.Warn = Tools._WarnEnabled;\n Tools.Error = Tools._ErrorEnabled;\n // Performances\n Tools._PerformanceNoneLogLevel = 0;\n Tools._PerformanceUserMarkLogLevel = 1;\n Tools._PerformanceConsoleLogLevel = 2;\n Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;\n Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;\n return Tools;\n }());\n BABYLON.Tools = Tools;\n /**\n * This class is used to track a performance counter which is number based.\n * The user has access to many properties which give statistics of different nature\n *\n * The implementer can track two kinds of Performance Counter: time and count\n * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.\n * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.\n */\n var PerfCounter = /** @class */ (function () {\n function PerfCounter() {\n this._startMonitoringTime = 0;\n this._min = 0;\n this._max = 0;\n this._average = 0;\n this._lastSecAverage = 0;\n this._current = 0;\n this._totalValueCount = 0;\n this._totalAccumulated = 0;\n this._lastSecAccumulated = 0;\n this._lastSecTime = 0;\n this._lastSecValueCount = 0;\n }\n Object.defineProperty(PerfCounter.prototype, \"min\", {\n /**\n * Returns the smallest value ever\n */\n get: function () {\n return this._min;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerfCounter.prototype, \"max\", {\n /**\n * Returns the biggest value ever\n */\n get: function () {\n return this._max;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerfCounter.prototype, \"average\", {\n /**\n * Returns the average value since the performance counter is running\n */\n get: function () {\n return this._average;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerfCounter.prototype, \"lastSecAverage\", {\n /**\n * Returns the average value of the last second the counter was monitored\n */\n get: function () {\n return this._lastSecAverage;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerfCounter.prototype, \"current\", {\n /**\n * Returns the current value\n */\n get: function () {\n return this._current;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerfCounter.prototype, \"total\", {\n get: function () {\n return this._totalAccumulated;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerfCounter.prototype, \"count\", {\n get: function () {\n return this._totalValueCount;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Call this method to start monitoring a new frame.\n * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.\n */\n PerfCounter.prototype.fetchNewFrame = function () {\n this._totalValueCount++;\n this._current = 0;\n this._lastSecValueCount++;\n };\n /**\n * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)\n * @param newCount the count value to add to the monitored count\n * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.\n */\n PerfCounter.prototype.addCount = function (newCount, fetchResult) {\n if (!PerfCounter.Enabled) {\n return;\n }\n this._current += newCount;\n if (fetchResult) {\n this._fetchResult();\n }\n };\n /**\n * Start monitoring this performance counter\n */\n PerfCounter.prototype.beginMonitoring = function () {\n if (!PerfCounter.Enabled) {\n return;\n }\n this._startMonitoringTime = Tools.Now;\n };\n /**\n * Compute the time lapsed since the previous beginMonitoring() call.\n * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter\n */\n PerfCounter.prototype.endMonitoring = function (newFrame) {\n if (newFrame === void 0) { newFrame = true; }\n if (!PerfCounter.Enabled) {\n return;\n }\n if (newFrame) {\n this.fetchNewFrame();\n }\n var currentTime = Tools.Now;\n this._current = currentTime - this._startMonitoringTime;\n if (newFrame) {\n this._fetchResult();\n }\n };\n PerfCounter.prototype._fetchResult = function () {\n this._totalAccumulated += this._current;\n this._lastSecAccumulated += this._current;\n // Min/Max update\n this._min = Math.min(this._min, this._current);\n this._max = Math.max(this._max, this._current);\n this._average = this._totalAccumulated / this._totalValueCount;\n // Reset last sec?\n var now = Tools.Now;\n if ((now - this._lastSecTime) > 1000) {\n this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;\n this._lastSecTime = now;\n this._lastSecAccumulated = 0;\n this._lastSecValueCount = 0;\n }\n };\n PerfCounter.Enabled = true;\n return PerfCounter;\n }());\n BABYLON.PerfCounter = PerfCounter;\n /**\n * Use this className as a decorator on a given class definition to add it a name and optionally its module.\n * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.\n * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified\n * @param name The name of the class, case should be preserved\n * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.\n */\n function className(name, module) {\n return function (target) {\n target[\"__bjsclassName__\"] = name;\n target[\"__bjsmoduleName__\"] = (module != null) ? module : null;\n };\n }\n BABYLON.className = className;\n /**\n * An implementation of a loop for asynchronous functions.\n */\n var AsyncLoop = /** @class */ (function () {\n /**\n * Constroctor.\n * @param iterations the number of iterations.\n * @param _fn the function to run each iteration\n * @param _successCallback the callback that will be called upon succesful execution\n * @param offset starting offset.\n */\n function AsyncLoop(iterations, _fn, _successCallback, offset) {\n if (offset === void 0) { offset = 0; }\n this.iterations = iterations;\n this._fn = _fn;\n this._successCallback = _successCallback;\n this.index = offset - 1;\n this._done = false;\n }\n /**\n * Execute the next iteration. Must be called after the last iteration was finished.\n */\n AsyncLoop.prototype.executeNext = function () {\n if (!this._done) {\n if (this.index + 1 < this.iterations) {\n ++this.index;\n this._fn(this);\n }\n else {\n this.breakLoop();\n }\n }\n };\n /**\n * Break the loop and run the success callback.\n */\n AsyncLoop.prototype.breakLoop = function () {\n this._done = true;\n this._successCallback();\n };\n /**\n * Helper function\n */\n AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {\n if (offset === void 0) { offset = 0; }\n var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);\n loop.executeNext();\n return loop;\n };\n /**\n * A for-loop that will run a given number of iterations synchronous and the rest async.\n * @param iterations total number of iterations\n * @param syncedIterations number of synchronous iterations in each async iteration.\n * @param fn the function to call each iteration.\n * @param callback a success call back that will be called when iterating stops.\n * @param breakFunction a break condition (optional)\n * @param timeout timeout settings for the setTimeout function. default - 0.\n * @constructor\n */\n AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {\n if (timeout === void 0) { timeout = 0; }\n AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {\n if (breakFunction && breakFunction())\n loop.breakLoop();\n else {\n setTimeout(function () {\n for (var i = 0; i < syncedIterations; ++i) {\n var iteration = (loop.index * syncedIterations) + i;\n if (iteration >= iterations)\n break;\n fn(iteration);\n if (breakFunction && breakFunction()) {\n loop.breakLoop();\n break;\n }\n }\n loop.executeNext();\n }, timeout);\n }\n }, callback);\n };\n return AsyncLoop;\n }());\n BABYLON.AsyncLoop = AsyncLoop;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.tools.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var PromiseStates;\n (function (PromiseStates) {\n PromiseStates[PromiseStates[\"Pending\"] = 0] = \"Pending\";\n PromiseStates[PromiseStates[\"Fulfilled\"] = 1] = \"Fulfilled\";\n PromiseStates[PromiseStates[\"Rejected\"] = 2] = \"Rejected\";\n })(PromiseStates || (PromiseStates = {}));\n var FulFillmentAgregator = /** @class */ (function () {\n function FulFillmentAgregator() {\n this.count = 0;\n this.target = 0;\n this.results = [];\n }\n return FulFillmentAgregator;\n }());\n var InternalPromise = /** @class */ (function () {\n function InternalPromise(resolver) {\n var _this = this;\n this._state = PromiseStates.Pending;\n this._children = new Array();\n this._rejectWasConsumed = false;\n if (!resolver) {\n return;\n }\n try {\n resolver(function (value) {\n _this._resolve(value);\n }, function (reason) {\n _this._reject(reason);\n });\n }\n catch (e) {\n this._reject(e);\n }\n }\n Object.defineProperty(InternalPromise.prototype, \"_result\", {\n get: function () {\n return this._resultValue;\n },\n set: function (value) {\n this._resultValue = value;\n if (this._parent && this._parent._result === undefined) {\n this._parent._result = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n InternalPromise.prototype.catch = function (onRejected) {\n return this.then(undefined, onRejected);\n };\n InternalPromise.prototype.then = function (onFulfilled, onRejected) {\n var _this = this;\n var newPromise = new InternalPromise();\n newPromise._onFulfilled = onFulfilled;\n newPromise._onRejected = onRejected;\n // Composition\n this._children.push(newPromise);\n newPromise._parent = this;\n if (this._state !== PromiseStates.Pending) {\n BABYLON.Tools.SetImmediate(function () {\n if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {\n var returnedValue = newPromise._resolve(_this._result);\n if (returnedValue !== undefined && returnedValue !== null) {\n if (returnedValue._state !== undefined) {\n var returnedPromise = returnedValue;\n newPromise._children.push(returnedPromise);\n returnedPromise._parent = newPromise;\n newPromise = returnedPromise;\n }\n else {\n newPromise._result = returnedValue;\n }\n }\n }\n else {\n newPromise._reject(_this._reason);\n }\n });\n }\n return newPromise;\n };\n InternalPromise.prototype._moveChildren = function (children) {\n var _this = this;\n (_a = this._children).push.apply(_a, children.splice(0, children.length));\n this._children.forEach(function (child) {\n child._parent = _this;\n });\n if (this._state === PromiseStates.Fulfilled) {\n for (var _i = 0, _b = this._children; _i < _b.length; _i++) {\n var child = _b[_i];\n child._resolve(this._result);\n }\n }\n else if (this._state === PromiseStates.Rejected) {\n for (var _c = 0, _d = this._children; _c < _d.length; _c++) {\n var child = _d[_c];\n child._reject(this._reason);\n }\n }\n var _a;\n };\n InternalPromise.prototype._resolve = function (value) {\n try {\n this._state = PromiseStates.Fulfilled;\n var returnedValue = null;\n if (this._onFulfilled) {\n returnedValue = this._onFulfilled(value);\n }\n if (returnedValue !== undefined && returnedValue !== null) {\n if (returnedValue._state !== undefined) {\n // Transmit children\n var returnedPromise = returnedValue;\n returnedPromise._parent = this;\n returnedPromise._moveChildren(this._children);\n value = returnedPromise._result;\n }\n else {\n value = returnedValue;\n }\n }\n this._result = value;\n for (var _i = 0, _a = this._children; _i < _a.length; _i++) {\n var child = _a[_i];\n child._resolve(value);\n }\n this._children.length = 0;\n delete this._onFulfilled;\n delete this._onRejected;\n }\n catch (e) {\n this._reject(e, true);\n }\n };\n InternalPromise.prototype._reject = function (reason, onLocalThrow) {\n if (onLocalThrow === void 0) { onLocalThrow = false; }\n this._state = PromiseStates.Rejected;\n this._reason = reason;\n if (this._onRejected && !onLocalThrow) {\n try {\n this._onRejected(reason);\n this._rejectWasConsumed = true;\n }\n catch (e) {\n reason = e;\n }\n }\n for (var _i = 0, _a = this._children; _i < _a.length; _i++) {\n var child = _a[_i];\n if (this._rejectWasConsumed) {\n child._resolve(null);\n }\n else {\n child._reject(reason);\n }\n }\n this._children.length = 0;\n delete this._onFulfilled;\n delete this._onRejected;\n };\n InternalPromise.resolve = function (value) {\n var newPromise = new InternalPromise();\n newPromise._resolve(value);\n return newPromise;\n };\n InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {\n promise.then(function (value) {\n agregator.results[index] = value;\n agregator.count++;\n if (agregator.count === agregator.target) {\n agregator.rootPromise._resolve(agregator.results);\n }\n return null;\n }, function (reason) {\n if (agregator.rootPromise._state !== PromiseStates.Rejected) {\n agregator.rootPromise._reject(reason);\n }\n });\n };\n InternalPromise.all = function (promises) {\n var newPromise = new InternalPromise();\n var agregator = new FulFillmentAgregator();\n agregator.target = promises.length;\n agregator.rootPromise = newPromise;\n if (promises.length) {\n for (var index = 0; index < promises.length; index++) {\n InternalPromise._RegisterForFulfillment(promises[index], agregator, index);\n }\n }\n else {\n newPromise._resolve([]);\n }\n return newPromise;\n };\n InternalPromise.race = function (promises) {\n var newPromise = new InternalPromise();\n if (promises.length) {\n for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {\n var promise = promises_1[_i];\n promise.then(function (value) {\n if (newPromise) {\n newPromise._resolve(value);\n newPromise = null;\n }\n return null;\n }, function (reason) {\n if (newPromise) {\n newPromise._reject(reason);\n newPromise = null;\n }\n });\n }\n }\n return newPromise;\n };\n return InternalPromise;\n }());\n /**\n * Helper class that provides a small promise polyfill\n */\n var PromisePolyfill = /** @class */ (function () {\n function PromisePolyfill() {\n }\n /**\n * Static function used to check if the polyfill is required\n * If this is the case then the function will inject the polyfill to window.Promise\n * @param force defines a boolean used to force the injection (mostly for testing purposes)\n */\n PromisePolyfill.Apply = function (force) {\n if (force === void 0) { force = false; }\n if (force || typeof Promise === 'undefined') {\n var root = window;\n root.Promise = InternalPromise;\n }\n };\n return PromisePolyfill;\n }());\n BABYLON.PromisePolyfill = PromisePolyfill;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.promise.js.map\n\n/// \nvar BABYLON;\n(function (BABYLON) {\n /**\n * Helper class to push actions to a pool of workers.\n */\n var WorkerPool = /** @class */ (function () {\n /**\n * Constructor\n * @param workers Array of workers to use for actions\n */\n function WorkerPool(workers) {\n this._pendingActions = new Array();\n this._workerInfos = workers.map(function (worker) { return ({\n worker: worker,\n active: false\n }); });\n }\n /**\n * Terminates all workers and clears any pending actions.\n */\n WorkerPool.prototype.dispose = function () {\n for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {\n var workerInfo = _a[_i];\n workerInfo.worker.terminate();\n }\n delete this._workerInfos;\n delete this._pendingActions;\n };\n /**\n * Pushes an action to the worker pool. If all the workers are active, the action will be\n * pended until a worker has completed its action.\n * @param action The action to perform. Call onComplete when the action is complete.\n */\n WorkerPool.prototype.push = function (action) {\n for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {\n var workerInfo = _a[_i];\n if (!workerInfo.active) {\n this._execute(workerInfo, action);\n return;\n }\n }\n this._pendingActions.push(action);\n };\n WorkerPool.prototype._execute = function (workerInfo, action) {\n var _this = this;\n workerInfo.active = true;\n action(workerInfo.worker, function () {\n workerInfo.active = false;\n var nextAction = _this._pendingActions.shift();\n if (nextAction) {\n _this._execute(workerInfo, nextAction);\n }\n });\n };\n return WorkerPool;\n }());\n BABYLON.WorkerPool = WorkerPool;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.workerPool.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * @hidden\n **/\n var _AlphaState = /** @class */ (function () {\n /**\n * Initializes the state.\n */\n function _AlphaState() {\n this._isAlphaBlendDirty = false;\n this._isBlendFunctionParametersDirty = false;\n this._isBlendEquationParametersDirty = false;\n this._isBlendConstantsDirty = false;\n this._alphaBlend = false;\n this._blendFunctionParameters = new Array(4);\n this._blendEquationParameters = new Array(2);\n this._blendConstants = new Array(4);\n this.reset();\n }\n Object.defineProperty(_AlphaState.prototype, \"isDirty\", {\n get: function () {\n return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_AlphaState.prototype, \"alphaBlend\", {\n get: function () {\n return this._alphaBlend;\n },\n set: function (value) {\n if (this._alphaBlend === value) {\n return;\n }\n this._alphaBlend = value;\n this._isAlphaBlendDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {\n if (this._blendConstants[0] === r &&\n this._blendConstants[1] === g &&\n this._blendConstants[2] === b &&\n this._blendConstants[3] === a) {\n return;\n }\n this._blendConstants[0] = r;\n this._blendConstants[1] = g;\n this._blendConstants[2] = b;\n this._blendConstants[3] = a;\n this._isBlendConstantsDirty = true;\n };\n _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {\n if (this._blendFunctionParameters[0] === value0 &&\n this._blendFunctionParameters[1] === value1 &&\n this._blendFunctionParameters[2] === value2 &&\n this._blendFunctionParameters[3] === value3) {\n return;\n }\n this._blendFunctionParameters[0] = value0;\n this._blendFunctionParameters[1] = value1;\n this._blendFunctionParameters[2] = value2;\n this._blendFunctionParameters[3] = value3;\n this._isBlendFunctionParametersDirty = true;\n };\n _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {\n if (this._blendEquationParameters[0] === rgb &&\n this._blendEquationParameters[1] === alpha) {\n return;\n }\n this._blendEquationParameters[0] = rgb;\n this._blendEquationParameters[1] = alpha;\n this._isBlendEquationParametersDirty = true;\n };\n _AlphaState.prototype.reset = function () {\n this._alphaBlend = false;\n this._blendFunctionParameters[0] = null;\n this._blendFunctionParameters[1] = null;\n this._blendFunctionParameters[2] = null;\n this._blendFunctionParameters[3] = null;\n this._blendEquationParameters[0] = null;\n this._blendEquationParameters[1] = null;\n this._blendConstants[0] = null;\n this._blendConstants[1] = null;\n this._blendConstants[2] = null;\n this._blendConstants[3] = null;\n this._isAlphaBlendDirty = true;\n this._isBlendFunctionParametersDirty = false;\n this._isBlendEquationParametersDirty = false;\n this._isBlendConstantsDirty = false;\n };\n _AlphaState.prototype.apply = function (gl) {\n if (!this.isDirty) {\n return;\n }\n // Alpha blend\n if (this._isAlphaBlendDirty) {\n if (this._alphaBlend) {\n gl.enable(gl.BLEND);\n }\n else {\n gl.disable(gl.BLEND);\n }\n this._isAlphaBlendDirty = false;\n }\n // Alpha function\n if (this._isBlendFunctionParametersDirty) {\n gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);\n this._isBlendFunctionParametersDirty = false;\n }\n // Alpha equation\n if (this._isBlendEquationParametersDirty) {\n gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);\n this._isBlendEquationParametersDirty = false;\n }\n // Constants\n if (this._isBlendConstantsDirty) {\n gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);\n this._isBlendConstantsDirty = false;\n }\n };\n return _AlphaState;\n }());\n BABYLON._AlphaState = _AlphaState;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.alphaCullingState.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * @hidden\n **/\n var _DepthCullingState = /** @class */ (function () {\n /**\n * Initializes the state.\n */\n function _DepthCullingState() {\n this._isDepthTestDirty = false;\n this._isDepthMaskDirty = false;\n this._isDepthFuncDirty = false;\n this._isCullFaceDirty = false;\n this._isCullDirty = false;\n this._isZOffsetDirty = false;\n this._isFrontFaceDirty = false;\n this.reset();\n }\n Object.defineProperty(_DepthCullingState.prototype, \"isDirty\", {\n get: function () {\n return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"zOffset\", {\n get: function () {\n return this._zOffset;\n },\n set: function (value) {\n if (this._zOffset === value) {\n return;\n }\n this._zOffset = value;\n this._isZOffsetDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"cullFace\", {\n get: function () {\n return this._cullFace;\n },\n set: function (value) {\n if (this._cullFace === value) {\n return;\n }\n this._cullFace = value;\n this._isCullFaceDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"cull\", {\n get: function () {\n return this._cull;\n },\n set: function (value) {\n if (this._cull === value) {\n return;\n }\n this._cull = value;\n this._isCullDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"depthFunc\", {\n get: function () {\n return this._depthFunc;\n },\n set: function (value) {\n if (this._depthFunc === value) {\n return;\n }\n this._depthFunc = value;\n this._isDepthFuncDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"depthMask\", {\n get: function () {\n return this._depthMask;\n },\n set: function (value) {\n if (this._depthMask === value) {\n return;\n }\n this._depthMask = value;\n this._isDepthMaskDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"depthTest\", {\n get: function () {\n return this._depthTest;\n },\n set: function (value) {\n if (this._depthTest === value) {\n return;\n }\n this._depthTest = value;\n this._isDepthTestDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"frontFace\", {\n get: function () {\n return this._frontFace;\n },\n set: function (value) {\n if (this._frontFace === value) {\n return;\n }\n this._frontFace = value;\n this._isFrontFaceDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n _DepthCullingState.prototype.reset = function () {\n this._depthMask = true;\n this._depthTest = true;\n this._depthFunc = null;\n this._cullFace = null;\n this._cull = null;\n this._zOffset = 0;\n this._frontFace = null;\n this._isDepthTestDirty = true;\n this._isDepthMaskDirty = true;\n this._isDepthFuncDirty = false;\n this._isCullFaceDirty = false;\n this._isCullDirty = false;\n this._isZOffsetDirty = false;\n this._isFrontFaceDirty = false;\n };\n _DepthCullingState.prototype.apply = function (gl) {\n if (!this.isDirty) {\n return;\n }\n // Cull\n if (this._isCullDirty) {\n if (this.cull) {\n gl.enable(gl.CULL_FACE);\n }\n else {\n gl.disable(gl.CULL_FACE);\n }\n this._isCullDirty = false;\n }\n // Cull face\n if (this._isCullFaceDirty) {\n gl.cullFace(this.cullFace);\n this._isCullFaceDirty = false;\n }\n // Depth mask\n if (this._isDepthMaskDirty) {\n gl.depthMask(this.depthMask);\n this._isDepthMaskDirty = false;\n }\n // Depth test\n if (this._isDepthTestDirty) {\n if (this.depthTest) {\n gl.enable(gl.DEPTH_TEST);\n }\n else {\n gl.disable(gl.DEPTH_TEST);\n }\n this._isDepthTestDirty = false;\n }\n // Depth func\n if (this._isDepthFuncDirty) {\n gl.depthFunc(this.depthFunc);\n this._isDepthFuncDirty = false;\n }\n // zOffset\n if (this._isZOffsetDirty) {\n if (this.zOffset) {\n gl.enable(gl.POLYGON_OFFSET_FILL);\n gl.polygonOffset(this.zOffset, 0);\n }\n else {\n gl.disable(gl.POLYGON_OFFSET_FILL);\n }\n this._isZOffsetDirty = false;\n }\n // Front face\n if (this._isFrontFaceDirty) {\n gl.frontFace(this.frontFace);\n this._isFrontFaceDirty = false;\n }\n };\n return _DepthCullingState;\n }());\n BABYLON._DepthCullingState = _DepthCullingState;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.depthCullingState.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * @hidden\n **/\n var _StencilState = /** @class */ (function () {\n function _StencilState() {\n this._isStencilTestDirty = false;\n this._isStencilMaskDirty = false;\n this._isStencilFuncDirty = false;\n this._isStencilOpDirty = false;\n this.reset();\n }\n Object.defineProperty(_StencilState.prototype, \"isDirty\", {\n get: function () {\n return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilFunc\", {\n get: function () {\n return this._stencilFunc;\n },\n set: function (value) {\n if (this._stencilFunc === value) {\n return;\n }\n this._stencilFunc = value;\n this._isStencilFuncDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilFuncRef\", {\n get: function () {\n return this._stencilFuncRef;\n },\n set: function (value) {\n if (this._stencilFuncRef === value) {\n return;\n }\n this._stencilFuncRef = value;\n this._isStencilFuncDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilFuncMask\", {\n get: function () {\n return this._stencilFuncMask;\n },\n set: function (value) {\n if (this._stencilFuncMask === value) {\n return;\n }\n this._stencilFuncMask = value;\n this._isStencilFuncDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilOpStencilFail\", {\n get: function () {\n return this._stencilOpStencilFail;\n },\n set: function (value) {\n if (this._stencilOpStencilFail === value) {\n return;\n }\n this._stencilOpStencilFail = value;\n this._isStencilOpDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilOpDepthFail\", {\n get: function () {\n return this._stencilOpDepthFail;\n },\n set: function (value) {\n if (this._stencilOpDepthFail === value) {\n return;\n }\n this._stencilOpDepthFail = value;\n this._isStencilOpDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilOpStencilDepthPass\", {\n get: function () {\n return this._stencilOpStencilDepthPass;\n },\n set: function (value) {\n if (this._stencilOpStencilDepthPass === value) {\n return;\n }\n this._stencilOpStencilDepthPass = value;\n this._isStencilOpDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilMask\", {\n get: function () {\n return this._stencilMask;\n },\n set: function (value) {\n if (this._stencilMask === value) {\n return;\n }\n this._stencilMask = value;\n this._isStencilMaskDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilTest\", {\n get: function () {\n return this._stencilTest;\n },\n set: function (value) {\n if (this._stencilTest === value) {\n return;\n }\n this._stencilTest = value;\n this._isStencilTestDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n _StencilState.prototype.reset = function () {\n this._stencilTest = false;\n this._stencilMask = 0xFF;\n this._stencilFunc = BABYLON.Engine.ALWAYS;\n this._stencilFuncRef = 1;\n this._stencilFuncMask = 0xFF;\n this._stencilOpStencilFail = BABYLON.Engine.KEEP;\n this._stencilOpDepthFail = BABYLON.Engine.KEEP;\n this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;\n this._isStencilTestDirty = true;\n this._isStencilMaskDirty = true;\n this._isStencilFuncDirty = true;\n this._isStencilOpDirty = true;\n };\n _StencilState.prototype.apply = function (gl) {\n if (!this.isDirty) {\n return;\n }\n // Stencil test\n if (this._isStencilTestDirty) {\n if (this.stencilTest) {\n gl.enable(gl.STENCIL_TEST);\n }\n else {\n gl.disable(gl.STENCIL_TEST);\n }\n this._isStencilTestDirty = false;\n }\n // Stencil mask\n if (this._isStencilMaskDirty) {\n gl.stencilMask(this.stencilMask);\n this._isStencilMaskDirty = false;\n }\n // Stencil func\n if (this._isStencilFuncDirty) {\n gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);\n this._isStencilFuncDirty = false;\n }\n // Stencil op\n if (this._isStencilOpDirty) {\n gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);\n this._isStencilOpDirty = false;\n }\n };\n return _StencilState;\n }());\n BABYLON._StencilState = _StencilState;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stencilState.js.map\n\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Keeps track of all the buffer info used in engine.\n */\n var BufferPointer = /** @class */ (function () {\n function BufferPointer() {\n }\n return BufferPointer;\n }());\n /**\n * Interface for attribute information associated with buffer instanciation\n */\n var InstancingAttributeInfo = /** @class */ (function () {\n function InstancingAttributeInfo() {\n }\n return InstancingAttributeInfo;\n }());\n BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;\n /**\n * Define options used to create a render target texture\n */\n var RenderTargetCreationOptions = /** @class */ (function () {\n function RenderTargetCreationOptions() {\n }\n return RenderTargetCreationOptions;\n }());\n BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;\n /**\n * Define options used to create a depth texture\n */\n var DepthTextureCreationOptions = /** @class */ (function () {\n function DepthTextureCreationOptions() {\n }\n return DepthTextureCreationOptions;\n }());\n BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;\n /**\n * Class used to describe the capabilities of the engine relatively to the current browser\n */\n var EngineCapabilities = /** @class */ (function () {\n function EngineCapabilities() {\n }\n return EngineCapabilities;\n }());\n BABYLON.EngineCapabilities = EngineCapabilities;\n /**\n * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio\n */\n var Engine = /** @class */ (function () {\n /**\n * Creates a new engine\n * @param canvasOrContext defines the canvas or WebGL context to use for rendering\n * @param antialias defines enable antialiasing (default: false)\n * @param options defines further options to be sent to the getContext() function\n * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)\n */\n function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {\n if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }\n var _this = this;\n // Public members\n /**\n * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required\n */\n this.forcePOTTextures = false;\n /**\n * Gets a boolean indicating if the engine is currently rendering in fullscreen mode\n */\n this.isFullscreen = false;\n /**\n * Gets a boolean indicating if the pointer is currently locked\n */\n this.isPointerLock = false;\n /**\n * Gets or sets a boolean indicating if back faces must be culled (true by default)\n */\n this.cullBackFaces = true;\n /**\n * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun\n */\n this.renderEvenInBackground = true;\n /**\n * Gets or sets a boolean indicating that cache can be kept between frames\n */\n this.preventCacheWipeBetweenFrames = false;\n /**\n * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest\n **/\n this.enableOfflineSupport = false;\n /**\n * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)\n **/\n this.disableManifestCheck = false;\n /**\n * Gets the list of created scenes\n */\n this.scenes = new Array();\n /**\n * Gets the list of created postprocesses\n */\n this.postProcesses = new Array();\n /** Gets or sets a boolean indicating if the engine should validate programs after compilation */\n this.validateShaderPrograms = false;\n // Observables\n /**\n * Observable event triggered each time the rendering canvas is resized\n */\n this.onResizeObservable = new BABYLON.Observable();\n /**\n * Observable event triggered each time the canvas loses focus\n */\n this.onCanvasBlurObservable = new BABYLON.Observable();\n /**\n * Observable event triggered each time the canvas gains focus\n */\n this.onCanvasFocusObservable = new BABYLON.Observable();\n /**\n * Observable event triggered each time the canvas receives pointerout event\n */\n this.onCanvasPointerOutObservable = new BABYLON.Observable();\n /**\n * Observable event triggered before each texture is initialized\n */\n this.onBeforeTextureInitObservable = new BABYLON.Observable();\n //WebVR\n this._vrDisplay = undefined;\n this._vrSupported = false;\n this._vrExclusivePointerMode = false;\n // Uniform buffers list\n /**\n * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported\n */\n this.disableUniformBuffers = false;\n /** @hidden */\n this._uniformBuffers = new Array();\n // Observables\n /**\n * Observable raised when the engine begins a new frame\n */\n this.onBeginFrameObservable = new BABYLON.Observable();\n /**\n * Observable raised when the engine ends the current frame\n */\n this.onEndFrameObservable = new BABYLON.Observable();\n /**\n * Observable raised when the engine is about to compile a shader\n */\n this.onBeforeShaderCompilationObservable = new BABYLON.Observable();\n /**\n * Observable raised when the engine has jsut compiled a shader\n */\n this.onAfterShaderCompilationObservable = new BABYLON.Observable();\n this._windowIsBackground = false;\n this._webGLVersion = 1.0;\n /** @hidden */\n this._badOS = false;\n /** @hidden */\n this._badDesktopOS = false;\n /**\n * Gets or sets a value indicating if we want to disable texture binding optmization.\n * This could be required on some buggy drivers which wants to have textures bound in a progressive order.\n * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is\n */\n this.disableTextureBindingOptimization = false;\n /**\n * Observable signaled when VR display mode changes\n */\n this.onVRDisplayChangedObservable = new BABYLON.Observable();\n /**\n * Observable signaled when VR request present is complete\n */\n this.onVRRequestPresentComplete = new BABYLON.Observable();\n /**\n * Observable signaled when VR request present starts\n */\n this.onVRRequestPresentStart = new BABYLON.Observable();\n this._colorWrite = true;\n /** @hidden */\n this._drawCalls = new BABYLON.PerfCounter();\n /** @hidden */\n this._textureCollisions = new BABYLON.PerfCounter();\n this._renderingQueueLaunched = false;\n this._activeRenderLoops = new Array();\n // Deterministic lockstepMaxSteps\n this._deterministicLockstep = false;\n this._lockstepMaxSteps = 4;\n // Lost context\n /**\n * Observable signaled when a context lost event is raised\n */\n this.onContextLostObservable = new BABYLON.Observable();\n /**\n * Observable signaled when a context restored event is raised\n */\n this.onContextRestoredObservable = new BABYLON.Observable();\n this._contextWasLost = false;\n this._doNotHandleContextLost = false;\n // FPS\n this._performanceMonitor = new BABYLON.PerformanceMonitor();\n this._fps = 60;\n this._deltaTime = 0;\n /**\n * Turn this value on if you want to pause FPS computation when in background\n */\n this.disablePerformanceMonitorInBackground = false;\n // States\n /** @hidden */\n this._depthCullingState = new BABYLON._DepthCullingState();\n /** @hidden */\n this._stencilState = new BABYLON._StencilState();\n /** @hidden */\n this._alphaState = new BABYLON._AlphaState();\n /** @hidden */\n this._alphaMode = Engine.ALPHA_DISABLE;\n // Cache\n this._internalTexturesCache = new Array();\n /** @hidden */\n this._activeChannel = 0;\n this._currentTextureChannel = -1;\n /** @hidden */\n this._boundTexturesCache = {};\n this._compiledEffects = {};\n this._vertexAttribArraysEnabled = [];\n this._uintIndicesCurrentlySet = false;\n this._currentBoundBuffer = new Array();\n /** @hidden */\n this._currentFramebuffer = null;\n this._currentBufferPointers = new Array();\n this._currentInstanceLocations = new Array();\n this._currentInstanceBuffers = new Array();\n this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();\n this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();\n this._vaoRecordInProgress = false;\n this._mustWipeVertexAttributes = false;\n this._nextFreeTextureSlots = new Array();\n this._maxSimultaneousTextures = 0;\n this._activeRequests = new Array();\n // Hardware supported Compressed Textures\n this._texturesSupported = new Array();\n /**\n * Defines whether the engine has been created with the premultipliedAlpha option on or not.\n */\n this.premultipliedAlpha = true;\n this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);\n this._onVRFullScreenTriggered = function () {\n if (_this._vrDisplay && _this._vrDisplay.isPresenting) {\n //get the old size before we change\n _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());\n _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();\n //get the width and height, change the render size\n var leftEye = _this._vrDisplay.getEyeParameters('left');\n _this.setHardwareScalingLevel(1);\n _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);\n }\n else {\n _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);\n _this.setSize(_this._oldSize.width, _this._oldSize.height);\n }\n };\n this._unpackFlipYCached = null;\n this._boundUniforms = {};\n // Register promises\n BABYLON.PromisePolyfill.Apply();\n var canvas = null;\n Engine.Instances.push(this);\n if (!canvasOrContext) {\n return;\n }\n options = options || {};\n if (canvasOrContext.getContext) {\n canvas = canvasOrContext;\n this._renderingCanvas = canvas;\n if (antialias != null) {\n options.antialias = antialias;\n }\n if (options.deterministicLockstep === undefined) {\n options.deterministicLockstep = false;\n }\n if (options.lockstepMaxSteps === undefined) {\n options.lockstepMaxSteps = 4;\n }\n if (options.preserveDrawingBuffer === undefined) {\n options.preserveDrawingBuffer = false;\n }\n if (options.audioEngine === undefined) {\n options.audioEngine = true;\n }\n if (options.stencil === undefined) {\n options.stencil = true;\n }\n if (options.premultipliedAlpha === false) {\n this.premultipliedAlpha = false;\n }\n this._deterministicLockstep = options.deterministicLockstep;\n this._lockstepMaxSteps = options.lockstepMaxSteps;\n this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;\n // Exceptions\n if (navigator && navigator.userAgent) {\n var ua = navigator.userAgent;\n for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {\n var exception = _a[_i];\n var key = exception.key;\n var targets = exception.targets;\n if (ua.indexOf(key) > -1) {\n if (exception.capture && exception.captureConstraint) {\n var capture = exception.capture;\n var constraint = exception.captureConstraint;\n var regex = new RegExp(capture);\n var matches = regex.exec(ua);\n if (matches && matches.length > 0) {\n var capturedValue = parseInt(matches[matches.length - 1]);\n if (capturedValue >= constraint) {\n continue;\n }\n }\n }\n for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {\n var target = targets_1[_b];\n switch (target) {\n case \"uniformBuffer\":\n this.disableUniformBuffers = true;\n break;\n case \"textureBindingOptimization\":\n this.disableTextureBindingOptimization = true;\n break;\n }\n }\n }\n }\n }\n // GL\n if (!options.disableWebGL2Support) {\n try {\n this._gl = (canvas.getContext(\"webgl2\", options) || canvas.getContext(\"experimental-webgl2\", options));\n if (this._gl) {\n this._webGLVersion = 2.0;\n }\n }\n catch (e) {\n // Do nothing\n }\n }\n if (!this._gl) {\n if (!canvas) {\n throw new Error(\"The provided canvas is null or undefined.\");\n }\n try {\n this._gl = (canvas.getContext(\"webgl\", options) || canvas.getContext(\"experimental-webgl\", options));\n }\n catch (e) {\n throw new Error(\"WebGL not supported\");\n }\n }\n if (!this._gl) {\n throw new Error(\"WebGL not supported\");\n }\n this._onCanvasFocus = function () {\n _this.onCanvasFocusObservable.notifyObservers(_this);\n };\n this._onCanvasBlur = function () {\n _this.onCanvasBlurObservable.notifyObservers(_this);\n };\n canvas.addEventListener(\"focus\", this._onCanvasFocus);\n canvas.addEventListener(\"blur\", this._onCanvasBlur);\n this._onBlur = function () {\n if (_this.disablePerformanceMonitorInBackground) {\n _this._performanceMonitor.disable();\n }\n _this._windowIsBackground = true;\n };\n this._onFocus = function () {\n if (_this.disablePerformanceMonitorInBackground) {\n _this._performanceMonitor.enable();\n }\n _this._windowIsBackground = false;\n };\n this._onCanvasPointerOut = function (ev) {\n _this.onCanvasPointerOutObservable.notifyObservers(ev);\n };\n window.addEventListener(\"blur\", this._onBlur);\n window.addEventListener(\"focus\", this._onFocus);\n canvas.addEventListener(\"pointerout\", this._onCanvasPointerOut);\n // Context lost\n if (!this._doNotHandleContextLost) {\n this._onContextLost = function (evt) {\n evt.preventDefault();\n _this._contextWasLost = true;\n BABYLON.Tools.Warn(\"WebGL context lost.\");\n _this.onContextLostObservable.notifyObservers(_this);\n };\n this._onContextRestored = function (evt) {\n // Adding a timeout to avoid race condition at browser level\n setTimeout(function () {\n // Rebuild gl context\n _this._initGLContext();\n // Rebuild effects\n _this._rebuildEffects();\n // Rebuild textures\n _this._rebuildInternalTextures();\n // Rebuild buffers\n _this._rebuildBuffers();\n // Cache\n _this.wipeCaches(true);\n BABYLON.Tools.Warn(\"WebGL context successfully restored.\");\n _this.onContextRestoredObservable.notifyObservers(_this);\n _this._contextWasLost = false;\n }, 0);\n };\n canvas.addEventListener(\"webglcontextlost\", this._onContextLost, false);\n canvas.addEventListener(\"webglcontextrestored\", this._onContextRestored, false);\n }\n }\n else {\n this._gl = canvasOrContext;\n this._renderingCanvas = this._gl.canvas;\n if (this._gl.renderbufferStorageMultisample) {\n this._webGLVersion = 2.0;\n }\n options.stencil = this._gl.getContextAttributes().stencil;\n }\n // Viewport\n var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;\n this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;\n this.resize();\n this._isStencilEnable = options.stencil ? true : false;\n this._initGLContext();\n if (canvas) {\n // Fullscreen\n this._onFullscreenChange = function () {\n if (document.fullscreen !== undefined) {\n _this.isFullscreen = document.fullscreen;\n }\n else if (document.mozFullScreen !== undefined) {\n _this.isFullscreen = document.mozFullScreen;\n }\n else if (document.webkitIsFullScreen !== undefined) {\n _this.isFullscreen = document.webkitIsFullScreen;\n }\n else if (document.msIsFullScreen !== undefined) {\n _this.isFullscreen = document.msIsFullScreen;\n }\n // Pointer lock\n if (_this.isFullscreen && _this._pointerLockRequested && canvas) {\n canvas.requestPointerLock = canvas.requestPointerLock ||\n canvas.msRequestPointerLock ||\n canvas.mozRequestPointerLock ||\n canvas.webkitRequestPointerLock;\n if (canvas.requestPointerLock) {\n canvas.requestPointerLock();\n }\n }\n };\n document.addEventListener(\"fullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"mozfullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"webkitfullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"msfullscreenchange\", this._onFullscreenChange, false);\n // Pointer lock\n this._onPointerLockChange = function () {\n _this.isPointerLock = (document.mozPointerLockElement === canvas ||\n document.webkitPointerLockElement === canvas ||\n document.msPointerLockElement === canvas ||\n document.pointerLockElement === canvas);\n };\n document.addEventListener(\"pointerlockchange\", this._onPointerLockChange, false);\n document.addEventListener(\"mspointerlockchange\", this._onPointerLockChange, false);\n document.addEventListener(\"mozpointerlockchange\", this._onPointerLockChange, false);\n document.addEventListener(\"webkitpointerlockchange\", this._onPointerLockChange, false);\n this._onVRDisplayPointerRestricted = function () {\n if (canvas) {\n canvas.requestPointerLock();\n }\n };\n this._onVRDisplayPointerUnrestricted = function () {\n document.exitPointerLock();\n };\n window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);\n window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);\n }\n if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {\n Engine.audioEngine = new BABYLON.AudioEngine();\n }\n // Prepare buffer pointers\n for (var i = 0; i < this._caps.maxVertexAttribs; i++) {\n this._currentBufferPointers[i] = new BufferPointer();\n }\n this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);\n // Load WebVR Devices\n if (options.autoEnableWebVR) {\n this.initWebVR();\n }\n // Detect if we are running on a faulty buggy OS.\n this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);\n // Detect if we are running on a faulty buggy desktop OS.\n this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n console.log(\"Babylon.js engine (v\" + Engine.Version + \") launched\");\n this.enableOfflineSupport = (BABYLON.Database !== undefined);\n }\n Object.defineProperty(Engine, \"LastCreatedEngine\", {\n /**\n * Gets the latest created engine\n */\n get: function () {\n if (Engine.Instances.length === 0) {\n return null;\n }\n return Engine.Instances[Engine.Instances.length - 1];\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine, \"LastCreatedScene\", {\n /**\n * Gets the latest created scene\n */\n get: function () {\n var lastCreatedEngine = Engine.LastCreatedEngine;\n if (!lastCreatedEngine) {\n return null;\n }\n if (lastCreatedEngine.scenes.length === 0) {\n return null;\n }\n return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation\n * @param flag defines which part of the materials must be marked as dirty\n * @param predicate defines a predicate used to filter which materials should be affected\n */\n Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {\n for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {\n var engine = Engine.Instances[engineIndex];\n for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {\n engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);\n }\n }\n };\n Object.defineProperty(Engine, \"Version\", {\n /**\n * Returns the current version of the framework\n */\n get: function () {\n return \"3.3.0-alpha.13\";\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"isInVRExclusivePointerMode\", {\n /**\n * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers\n * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input\n */\n get: function () {\n return this._vrExclusivePointerMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"supportsUniformBuffers\", {\n /**\n * Gets a boolean indicating that the engine supports uniform buffers\n * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets\n */\n get: function () {\n return this.webGLVersion > 1 && !this.disableUniformBuffers;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"needPOTTextures\", {\n /**\n * Gets a boolean indicating that only power of 2 textures are supported\n * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them\n */\n get: function () {\n return this._webGLVersion < 2 || this.forcePOTTextures;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"doNotHandleContextLost\", {\n /**\n * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost\n */\n get: function () {\n return this._doNotHandleContextLost;\n },\n set: function (value) {\n this._doNotHandleContextLost = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"performanceMonitor\", {\n /**\n * Gets the performance monitor attached to this engine\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation\n */\n get: function () {\n return this._performanceMonitor;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"texturesSupported\", {\n /**\n * Gets the list of texture formats supported\n */\n get: function () {\n return this._texturesSupported;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"textureFormatInUse\", {\n /**\n * Gets the list of texture formats in use\n */\n get: function () {\n return this._textureFormatInUse;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"currentViewport\", {\n /**\n * Gets the current viewport\n */\n get: function () {\n return this._cachedViewport;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"emptyTexture\", {\n /**\n * Gets the default empty texture\n */\n get: function () {\n if (!this._emptyTexture) {\n this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);\n }\n return this._emptyTexture;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"emptyTexture3D\", {\n /**\n * Gets the default empty 3D texture\n */\n get: function () {\n if (!this._emptyTexture3D) {\n this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);\n }\n return this._emptyTexture3D;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"emptyCubeTexture\", {\n /**\n * Gets the default empty cube texture\n */\n get: function () {\n if (!this._emptyCubeTexture) {\n var faceData = new Uint8Array(4);\n var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];\n this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);\n }\n return this._emptyCubeTexture;\n },\n enumerable: true,\n configurable: true\n });\n Engine.prototype._rebuildInternalTextures = function () {\n var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies\n for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {\n var internalTexture = currentState_1[_i];\n internalTexture._rebuild();\n }\n };\n Engine.prototype._rebuildEffects = function () {\n for (var key in this._compiledEffects) {\n var effect = this._compiledEffects[key];\n effect._prepareEffect();\n }\n BABYLON.Effect.ResetCache();\n };\n Engine.prototype._rebuildBuffers = function () {\n // Index / Vertex\n for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {\n var scene = _a[_i];\n scene.resetCachedMaterial();\n scene._rebuildGeometries();\n scene._rebuildTextures();\n }\n // Uniforms\n for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {\n var uniformBuffer = _c[_b];\n uniformBuffer._rebuild();\n }\n };\n Engine.prototype._initGLContext = function () {\n // Caps\n this._caps = new EngineCapabilities();\n this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);\n this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);\n this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);\n this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);\n this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);\n this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);\n this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);\n this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);\n this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);\n this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);\n // Infos\n this._glVersion = this._gl.getParameter(this._gl.VERSION);\n var rendererInfo = this._gl.getExtension(\"WEBGL_debug_renderer_info\");\n if (rendererInfo != null) {\n this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);\n this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);\n }\n if (!this._glVendor) {\n this._glVendor = \"Unknown vendor\";\n }\n if (!this._glRenderer) {\n this._glRenderer = \"Unknown renderer\";\n }\n // Constants\n this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).\n if (this._gl.RGBA16F !== 0x881A) {\n this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.\n }\n if (this._gl.RGBA32F !== 0x8814) {\n this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.\n }\n if (this._gl.DEPTH24_STENCIL8 !== 35056) {\n this._gl.DEPTH24_STENCIL8 = 35056;\n }\n // Extensions\n this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);\n this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');\n this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');\n this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');\n this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');\n this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||\n this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3\n this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');\n this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;\n this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;\n this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;\n this._caps.highPrecisionShaderSupported = true;\n this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension(\"EXT_disjoint_timer_query\");\n if (this._caps.timerQuery) {\n if (this._webGLVersion === 1) {\n this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);\n }\n this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;\n }\n // Checks if some of the format renders first to allow the use of webgl inspector.\n this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');\n this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;\n this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;\n this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;\n this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;\n this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;\n if (this._webGLVersion > 1) {\n this._gl.HALF_FLOAT_OES = 0x140B;\n }\n this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();\n this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;\n // Draw buffers\n if (this._webGLVersion > 1) {\n this._caps.drawBuffersExtension = true;\n }\n else {\n var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');\n if (drawBuffersExtension !== null) {\n this._caps.drawBuffersExtension = true;\n this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);\n this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;\n for (var i = 0; i < 16; i++) {\n this._gl[\"COLOR_ATTACHMENT\" + i + \"_WEBGL\"] = drawBuffersExtension[\"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n }\n }\n else {\n this._caps.drawBuffersExtension = false;\n }\n }\n // Depth Texture\n if (this._webGLVersion > 1) {\n this._caps.depthTextureExtension = true;\n }\n else {\n var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');\n if (depthTextureExtension != null) {\n this._caps.depthTextureExtension = true;\n this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;\n }\n }\n // Vertex array object\n if (this._webGLVersion > 1) {\n this._caps.vertexArrayObject = true;\n }\n else {\n var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');\n if (vertexArrayObjectExtension != null) {\n this._caps.vertexArrayObject = true;\n this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);\n this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);\n this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);\n }\n else {\n this._caps.vertexArrayObject = false;\n }\n }\n // Instances count\n if (this._webGLVersion > 1) {\n this._caps.instancedArrays = true;\n }\n else {\n var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');\n if (instanceExtension != null) {\n this._caps.instancedArrays = true;\n this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);\n this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);\n this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);\n }\n else {\n this._caps.instancedArrays = false;\n }\n }\n // Intelligently add supported compressed formats in order to check for.\n // Check for ASTC support first as it is most powerful and to be very cross platform.\n // Next PVRTC & DXT, which are probably superior to ETC1/2.\n // Likely no hardware which supports both PVR & DXT, so order matters little.\n // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.\n if (this._caps.astc)\n this.texturesSupported.push('-astc.ktx');\n if (this._caps.s3tc)\n this.texturesSupported.push('-dxt.ktx');\n if (this._caps.pvrtc)\n this.texturesSupported.push('-pvrtc.ktx');\n if (this._caps.etc2)\n this.texturesSupported.push('-etc2.ktx');\n if (this._caps.etc1)\n this.texturesSupported.push('-etc1.ktx');\n if (this._gl.getShaderPrecisionFormat) {\n var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);\n if (highp) {\n this._caps.highPrecisionShaderSupported = highp.precision !== 0;\n }\n }\n // Depth buffer\n this.setDepthBuffer(true);\n this.setDepthFunctionToLessOrEqual();\n this.setDepthWrite(true);\n // Texture maps\n this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;\n for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {\n this._nextFreeTextureSlots.push(slot);\n }\n };\n Object.defineProperty(Engine.prototype, \"webGLVersion\", {\n /**\n * Gets version of the current webGL context\n */\n get: function () {\n return this._webGLVersion;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"isStencilEnable\", {\n /**\n * Returns true if the stencil buffer has been enabled through the creation option of the context.\n */\n get: function () {\n return this._isStencilEnable;\n },\n enumerable: true,\n configurable: true\n });\n Engine.prototype._prepareWorkingCanvas = function () {\n if (this._workingCanvas) {\n return;\n }\n this._workingCanvas = document.createElement(\"canvas\");\n var context = this._workingCanvas.getContext(\"2d\");\n if (context) {\n this._workingContext = context;\n }\n };\n /**\n * Reset the texture cache to empty state\n */\n Engine.prototype.resetTextureCache = function () {\n for (var key in this._boundTexturesCache) {\n if (!this._boundTexturesCache.hasOwnProperty(key)) {\n continue;\n }\n var boundTexture = this._boundTexturesCache[key];\n if (boundTexture) {\n this._removeDesignatedSlot(boundTexture);\n }\n this._boundTexturesCache[key] = null;\n }\n if (!this.disableTextureBindingOptimization) {\n this._nextFreeTextureSlots = [];\n for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {\n this._nextFreeTextureSlots.push(slot);\n }\n }\n this._currentTextureChannel = -1;\n };\n /**\n * Gets a boolean indicating that the engine is running in deterministic lock step mode\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n * @returns true if engine is in deterministic lock step mode\n */\n Engine.prototype.isDeterministicLockStep = function () {\n return this._deterministicLockstep;\n };\n /**\n * Gets the max steps when engine is running in deterministic lock step\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n * @returns the max steps\n */\n Engine.prototype.getLockstepMaxSteps = function () {\n return this._lockstepMaxSteps;\n };\n /**\n * Gets an object containing information about the current webGL context\n * @returns an object containing the vender, the renderer and the version of the current webGL context\n */\n Engine.prototype.getGlInfo = function () {\n return {\n vendor: this._glVendor,\n renderer: this._glRenderer,\n version: this._glVersion\n };\n };\n /**\n * Gets current aspect ratio\n * @param camera defines the camera to use to get the aspect ratio\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the aspect ratio\n */\n Engine.prototype.getAspectRatio = function (camera, useScreen) {\n if (useScreen === void 0) { useScreen = false; }\n var viewport = camera.viewport;\n return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);\n };\n /**\n * Gets current screen aspect ratio\n * @returns a number defining the aspect ratio\n */\n Engine.prototype.getScreenAspectRatio = function () {\n return (this.getRenderWidth(true)) / (this.getRenderHeight(true));\n };\n /**\n * Gets the current render width\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the current render width\n */\n Engine.prototype.getRenderWidth = function (useScreen) {\n if (useScreen === void 0) { useScreen = false; }\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.width;\n }\n return this._gl.drawingBufferWidth;\n };\n /**\n * Gets the current render height\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the current render height\n */\n Engine.prototype.getRenderHeight = function (useScreen) {\n if (useScreen === void 0) { useScreen = false; }\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.height;\n }\n return this._gl.drawingBufferHeight;\n };\n /**\n * Gets the HTML canvas attached with the current webGL context\n * @returns a HTML canvas\n */\n Engine.prototype.getRenderingCanvas = function () {\n return this._renderingCanvas;\n };\n /**\n * Gets the client rect of the HTML canvas attached with the current webGL context\n * @returns a client rectanglee\n */\n Engine.prototype.getRenderingCanvasClientRect = function () {\n if (!this._renderingCanvas) {\n return null;\n }\n return this._renderingCanvas.getBoundingClientRect();\n };\n /**\n * Defines the hardware scaling level.\n * By default the hardware scaling level is computed from the window device ratio.\n * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.\n * @param level defines the level to use\n */\n Engine.prototype.setHardwareScalingLevel = function (level) {\n this._hardwareScalingLevel = level;\n this.resize();\n };\n /**\n * Gets the current hardware scaling level.\n * By default the hardware scaling level is computed from the window device ratio.\n * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.\n * @returns a number indicating the current hardware scaling level\n */\n Engine.prototype.getHardwareScalingLevel = function () {\n return this._hardwareScalingLevel;\n };\n /**\n * Gets the list of loaded textures\n * @returns an array containing all loaded textures\n */\n Engine.prototype.getLoadedTexturesCache = function () {\n return this._internalTexturesCache;\n };\n /**\n * Gets the object containing all engine capabilities\n * @returns the EngineCapabilities object\n */\n Engine.prototype.getCaps = function () {\n return this._caps;\n };\n Object.defineProperty(Engine.prototype, \"drawCalls\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"drawCalls is deprecated. Please use SceneInstrumentation class\");\n return 0;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"drawCallsPerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the current depth function\n * @returns a number defining the depth function\n */\n Engine.prototype.getDepthFunction = function () {\n return this._depthCullingState.depthFunc;\n };\n /**\n * Sets the current depth function\n * @param depthFunc defines the function to use\n */\n Engine.prototype.setDepthFunction = function (depthFunc) {\n this._depthCullingState.depthFunc = depthFunc;\n };\n /**\n * Sets the current depth function to GREATER\n */\n Engine.prototype.setDepthFunctionToGreater = function () {\n this._depthCullingState.depthFunc = this._gl.GREATER;\n };\n /**\n * Sets the current depth function to GEQUAL\n */\n Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {\n this._depthCullingState.depthFunc = this._gl.GEQUAL;\n };\n /**\n * Sets the current depth function to LESS\n */\n Engine.prototype.setDepthFunctionToLess = function () {\n this._depthCullingState.depthFunc = this._gl.LESS;\n };\n /**\n * Sets the current depth function to LEQUAL\n */\n Engine.prototype.setDepthFunctionToLessOrEqual = function () {\n this._depthCullingState.depthFunc = this._gl.LEQUAL;\n };\n /**\n * Gets a boolean indicating if stencil buffer is enabled\n * @returns the current stencil buffer state\n */\n Engine.prototype.getStencilBuffer = function () {\n return this._stencilState.stencilTest;\n };\n /**\n * Enable or disable the stencil buffer\n * @param enable defines if the stencil buffer must be enabled or disabled\n */\n Engine.prototype.setStencilBuffer = function (enable) {\n this._stencilState.stencilTest = enable;\n };\n /**\n * Gets the current stencil mask\n * @returns a number defining the new stencil mask to use\n */\n Engine.prototype.getStencilMask = function () {\n return this._stencilState.stencilMask;\n };\n /**\n * Sets the current stencil mask\n * @param mask defines the new stencil mask to use\n */\n Engine.prototype.setStencilMask = function (mask) {\n this._stencilState.stencilMask = mask;\n };\n /**\n * Gets the current stencil function\n * @returns a number defining the stencil function to use\n */\n Engine.prototype.getStencilFunction = function () {\n return this._stencilState.stencilFunc;\n };\n /**\n * Gets the current stencil reference value\n * @returns a number defining the stencil reference value to use\n */\n Engine.prototype.getStencilFunctionReference = function () {\n return this._stencilState.stencilFuncRef;\n };\n /**\n * Gets the current stencil mask\n * @returns a number defining the stencil mask to use\n */\n Engine.prototype.getStencilFunctionMask = function () {\n return this._stencilState.stencilFuncMask;\n };\n /**\n * Sets the current stencil function\n * @param stencilFunc defines the new stencil function to use\n */\n Engine.prototype.setStencilFunction = function (stencilFunc) {\n this._stencilState.stencilFunc = stencilFunc;\n };\n /**\n * Sets the current stencil reference\n * @param reference defines the new stencil reference to use\n */\n Engine.prototype.setStencilFunctionReference = function (reference) {\n this._stencilState.stencilFuncRef = reference;\n };\n /**\n * Sets the current stencil mask\n * @param mask defines the new stencil mask to use\n */\n Engine.prototype.setStencilFunctionMask = function (mask) {\n this._stencilState.stencilFuncMask = mask;\n };\n /**\n * Gets the current stencil operation when stencil fails\n * @returns a number defining stencil operation to use when stencil fails\n */\n Engine.prototype.getStencilOperationFail = function () {\n return this._stencilState.stencilOpStencilFail;\n };\n /**\n * Gets the current stencil operation when depth fails\n * @returns a number defining stencil operation to use when depth fails\n */\n Engine.prototype.getStencilOperationDepthFail = function () {\n return this._stencilState.stencilOpDepthFail;\n };\n /**\n * Gets the current stencil operation when stencil passes\n * @returns a number defining stencil operation to use when stencil passes\n */\n Engine.prototype.getStencilOperationPass = function () {\n return this._stencilState.stencilOpStencilDepthPass;\n };\n /**\n * Sets the stencil operation to use when stencil fails\n * @param operation defines the stencil operation to use when stencil fails\n */\n Engine.prototype.setStencilOperationFail = function (operation) {\n this._stencilState.stencilOpStencilFail = operation;\n };\n /**\n * Sets the stencil operation to use when depth fails\n * @param operation defines the stencil operation to use when depth fails\n */\n Engine.prototype.setStencilOperationDepthFail = function (operation) {\n this._stencilState.stencilOpDepthFail = operation;\n };\n /**\n * Sets the stencil operation to use when stencil passes\n * @param operation defines the stencil operation to use when stencil passes\n */\n Engine.prototype.setStencilOperationPass = function (operation) {\n this._stencilState.stencilOpStencilDepthPass = operation;\n };\n /**\n * Sets a boolean indicating if the dithering state is enabled or disabled\n * @param value defines the dithering state\n */\n Engine.prototype.setDitheringState = function (value) {\n if (value) {\n this._gl.enable(this._gl.DITHER);\n }\n else {\n this._gl.disable(this._gl.DITHER);\n }\n };\n /**\n * Sets a boolean indicating if the rasterizer state is enabled or disabled\n * @param value defines the rasterizer state\n */\n Engine.prototype.setRasterizerState = function (value) {\n if (value) {\n this._gl.disable(this._gl.RASTERIZER_DISCARD);\n }\n else {\n this._gl.enable(this._gl.RASTERIZER_DISCARD);\n }\n };\n /**\n * stop executing a render loop function and remove it from the execution array\n * @param renderFunction defines the function to be removed. If not provided all functions will be removed.\n */\n Engine.prototype.stopRenderLoop = function (renderFunction) {\n if (!renderFunction) {\n this._activeRenderLoops = [];\n return;\n }\n var index = this._activeRenderLoops.indexOf(renderFunction);\n if (index >= 0) {\n this._activeRenderLoops.splice(index, 1);\n }\n };\n /** @hidden */\n Engine.prototype._renderLoop = function () {\n if (!this._contextWasLost) {\n var shouldRender = true;\n if (!this.renderEvenInBackground && this._windowIsBackground) {\n shouldRender = false;\n }\n if (shouldRender) {\n // Start new frame\n this.beginFrame();\n for (var index = 0; index < this._activeRenderLoops.length; index++) {\n var renderFunction = this._activeRenderLoops[index];\n renderFunction();\n }\n // Present\n this.endFrame();\n }\n }\n if (this._activeRenderLoops.length > 0) {\n // Register new frame\n var requester = null;\n if (this._vrDisplay && this._vrDisplay.isPresenting)\n requester = this._vrDisplay;\n this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);\n }\n else {\n this._renderingQueueLaunched = false;\n }\n };\n /**\n * Register and execute a render loop. The engine can have more than one render function\n * @param renderFunction defines the function to continuously execute\n */\n Engine.prototype.runRenderLoop = function (renderFunction) {\n if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {\n return;\n }\n this._activeRenderLoops.push(renderFunction);\n if (!this._renderingQueueLaunched) {\n this._renderingQueueLaunched = true;\n this._bindedRenderFunction = this._renderLoop.bind(this);\n this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);\n }\n };\n /**\n * Toggle full screen mode\n * @param requestPointerLock defines if a pointer lock should be requested from the user\n * @param options defines an option object to be sent to the requestFullscreen function\n */\n Engine.prototype.switchFullscreen = function (requestPointerLock) {\n if (this.isFullscreen) {\n BABYLON.Tools.ExitFullscreen();\n }\n else {\n this._pointerLockRequested = requestPointerLock;\n if (this._renderingCanvas) {\n BABYLON.Tools.RequestFullscreen(this._renderingCanvas);\n }\n }\n };\n /**\n * Clear the current render buffer or the current render target (if any is set up)\n * @param color defines the color to use\n * @param backBuffer defines if the back buffer must be cleared\n * @param depth defines if the depth buffer must be cleared\n * @param stencil defines if the stencil buffer must be cleared\n */\n Engine.prototype.clear = function (color, backBuffer, depth, stencil) {\n if (stencil === void 0) { stencil = false; }\n this.applyStates();\n var mode = 0;\n if (backBuffer && color) {\n this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);\n mode |= this._gl.COLOR_BUFFER_BIT;\n }\n if (depth) {\n this._gl.clearDepth(1.0);\n mode |= this._gl.DEPTH_BUFFER_BIT;\n }\n if (stencil) {\n this._gl.clearStencil(0);\n mode |= this._gl.STENCIL_BUFFER_BIT;\n }\n this._gl.clear(mode);\n };\n /**\n * Executes a scissor clear (ie. a clear on a specific portion of the screen)\n * @param x defines the x-coordinate of the top left corner of the clear rectangle\n * @param y defines the y-coordinate of the corner of the clear rectangle\n * @param width defines the width of the clear rectangle\n * @param height defines the height of the clear rectangle\n * @param clearColor defines the clear color\n */\n Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {\n var gl = this._gl;\n // Save state\n var curScissor = gl.getParameter(gl.SCISSOR_TEST);\n var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);\n // Change state\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(x, y, width, height);\n // Clear\n this.clear(clearColor, true, true, true);\n // Restore state\n gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);\n if (curScissor === true) {\n gl.enable(gl.SCISSOR_TEST);\n }\n else {\n gl.disable(gl.SCISSOR_TEST);\n }\n };\n /** @hidden */\n Engine.prototype._viewport = function (x, y, width, height) {\n if (x !== this._viewportCached.x ||\n y !== this._viewportCached.y ||\n width !== this._viewportCached.z ||\n height !== this._viewportCached.w) {\n this._viewportCached.x = x;\n this._viewportCached.y = y;\n this._viewportCached.z = width;\n this._viewportCached.w = height;\n this._gl.viewport(x, y, width, height);\n }\n };\n /**\n * Set the WebGL's viewport\n * @param viewport defines the viewport element to be used\n * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used\n * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used\n */\n Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {\n var width = requiredWidth || this.getRenderWidth();\n var height = requiredHeight || this.getRenderHeight();\n var x = viewport.x || 0;\n var y = viewport.y || 0;\n this._cachedViewport = viewport;\n this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);\n };\n /**\n * Directly set the WebGL Viewport\n * @param x defines the x coordinate of the viewport (in screen space)\n * @param y defines the y coordinate of the viewport (in screen space)\n * @param width defines the width of the viewport (in screen space)\n * @param height defines the height of the viewport (in screen space)\n * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state\n */\n Engine.prototype.setDirectViewport = function (x, y, width, height) {\n var currentViewport = this._cachedViewport;\n this._cachedViewport = null;\n this._viewport(x, y, width, height);\n return currentViewport;\n };\n /**\n * Begin a new frame\n */\n Engine.prototype.beginFrame = function () {\n this.onBeginFrameObservable.notifyObservers(this);\n this._measureFps();\n };\n /**\n * Enf the current frame\n */\n Engine.prototype.endFrame = function () {\n // Force a flush in case we are using a bad OS.\n if (this._badOS) {\n this.flushFramebuffer();\n }\n // Submit frame to the vr device, if enabled\n if (this._vrDisplay && this._vrDisplay.isPresenting) {\n // TODO: We should only submit the frame if we read frameData successfully.\n this._vrDisplay.submitFrame();\n }\n this.onEndFrameObservable.notifyObservers(this);\n };\n /**\n * Resize the view according to the canvas' size\n */\n Engine.prototype.resize = function () {\n // We're not resizing the size of the canvas while in VR mode & presenting\n if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {\n var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;\n var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;\n this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);\n }\n };\n /**\n * Force a specific size of the canvas\n * @param width defines the new canvas' width\n * @param height defines the new canvas' height\n */\n Engine.prototype.setSize = function (width, height) {\n if (!this._renderingCanvas) {\n return;\n }\n if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {\n return;\n }\n this._renderingCanvas.width = width;\n this._renderingCanvas.height = height;\n for (var index = 0; index < this.scenes.length; index++) {\n var scene = this.scenes[index];\n for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {\n var cam = scene.cameras[camIndex];\n cam._currentRenderId = 0;\n }\n }\n if (this.onResizeObservable.hasObservers) {\n this.onResizeObservable.notifyObservers(this);\n }\n };\n // WebVR functions\n /**\n * Gets a boolean indicating if a webVR device was detected\n * @returns true if a webVR device was detected\n */\n Engine.prototype.isVRDevicePresent = function () {\n return !!this._vrDisplay;\n };\n /**\n * Gets the current webVR device\n * @returns the current webVR device (or null)\n */\n Engine.prototype.getVRDevice = function () {\n return this._vrDisplay;\n };\n /**\n * Initializes a webVR display and starts listening to display change events\n * The onVRDisplayChangedObservable will be notified upon these changes\n * @returns The onVRDisplayChangedObservable\n */\n Engine.prototype.initWebVR = function () {\n this.initWebVRAsync();\n return this.onVRDisplayChangedObservable;\n };\n /**\n * Initializes a webVR display and starts listening to display change events\n * The onVRDisplayChangedObservable will be notified upon these changes\n * @returns A promise containing a VRDisplay and if vr is supported\n */\n Engine.prototype.initWebVRAsync = function () {\n var _this = this;\n var notifyObservers = function () {\n var eventArgs = {\n vrDisplay: _this._vrDisplay,\n vrSupported: _this._vrSupported\n };\n _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);\n _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });\n };\n if (!this._onVrDisplayConnect) {\n this._onVrDisplayConnect = function (event) {\n _this._vrDisplay = event.display;\n notifyObservers();\n };\n this._onVrDisplayDisconnect = function () {\n _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);\n _this._vrDisplay = undefined;\n _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);\n notifyObservers();\n };\n this._onVrDisplayPresentChange = function () {\n _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;\n };\n window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);\n window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);\n window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);\n }\n this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();\n this._webVRInitPromise.then(notifyObservers);\n return this._webVRInitPromise;\n };\n /**\n * Call this function to switch to webVR mode\n * Will do nothing if webVR is not supported or if there is no webVR device\n * @see http://doc.babylonjs.com/how_to/webvr_camera\n */\n Engine.prototype.enableVR = function () {\n var _this = this;\n if (this._vrDisplay && !this._vrDisplay.isPresenting) {\n var onResolved = function () {\n _this.onVRRequestPresentComplete.notifyObservers(true);\n _this._onVRFullScreenTriggered();\n };\n var onRejected = function () {\n _this.onVRRequestPresentComplete.notifyObservers(false);\n };\n this.onVRRequestPresentStart.notifyObservers(this);\n this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);\n }\n };\n /**\n * Call this function to leave webVR mode\n * Will do nothing if webVR is not supported or if there is no webVR device\n * @see http://doc.babylonjs.com/how_to/webvr_camera\n */\n Engine.prototype.disableVR = function () {\n if (this._vrDisplay && this._vrDisplay.isPresenting) {\n this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);\n }\n };\n Engine.prototype._getVRDisplaysAsync = function () {\n var _this = this;\n return new Promise(function (res, rej) {\n if (navigator.getVRDisplays) {\n navigator.getVRDisplays().then(function (devices) {\n _this._vrSupported = true;\n // note that devices may actually be an empty array. This is fine;\n // we expect this._vrDisplay to be undefined in this case.\n _this._vrDisplay = devices[0];\n res({\n vrDisplay: _this._vrDisplay,\n vrSupported: _this._vrSupported\n });\n });\n }\n else {\n _this._vrDisplay = undefined;\n _this._vrSupported = false;\n res({\n vrDisplay: _this._vrDisplay,\n vrSupported: _this._vrSupported\n });\n }\n });\n };\n /**\n * Binds the frame buffer to the specified texture.\n * @param texture The texture to render to or null for the default canvas\n * @param faceIndex The face of the texture to render to in case of cube texture\n * @param requiredWidth The width of the target to render to\n * @param requiredHeight The height of the target to render to\n * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true\n * @param depthStencilTexture The depth stencil texture to use to render\n * @param lodLevel defines le lod level to bind to the frame buffer\n */\n Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {\n if (lodLevel === void 0) { lodLevel = 0; }\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n this._currentRenderTarget = texture;\n this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);\n var gl = this._gl;\n if (texture.isCube) {\n if (faceIndex === undefined) {\n faceIndex = 0;\n }\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);\n if (depthStencilTexture) {\n if (depthStencilTexture._generateStencilBuffer) {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);\n }\n else {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);\n }\n }\n }\n if (this._cachedViewport && !forceFullscreenViewport) {\n this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);\n }\n else {\n if (!requiredWidth) {\n requiredWidth = texture.width;\n if (lodLevel) {\n requiredWidth = requiredWidth / Math.pow(2, lodLevel);\n }\n }\n if (!requiredHeight) {\n requiredHeight = texture.height;\n if (lodLevel) {\n requiredHeight = requiredHeight / Math.pow(2, lodLevel);\n }\n }\n this._viewport(0, 0, requiredWidth, requiredHeight);\n }\n this.wipeCaches();\n };\n Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {\n if (this._currentFramebuffer !== framebuffer) {\n this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);\n this._currentFramebuffer = framebuffer;\n }\n };\n /**\n * Unbind the current render target texture from the webGL context\n * @param texture defines the render target texture to unbind\n * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated\n * @param onBeforeUnbind defines a function which will be called before the effective unbind\n */\n Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {\n if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }\n this._currentRenderTarget = null;\n // If MSAA, we need to bitblt back to main texture\n var gl = this._gl;\n if (texture._MSAAFramebuffer) {\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);\n gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);\n }\n if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {\n this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);\n gl.generateMipmap(gl.TEXTURE_2D);\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n }\n if (onBeforeUnbind) {\n if (texture._MSAAFramebuffer) {\n // Bind the correct framebuffer\n this.bindUnboundFramebuffer(texture._framebuffer);\n }\n onBeforeUnbind();\n }\n this.bindUnboundFramebuffer(null);\n };\n /**\n * Unbind a list of render target textures from the webGL context\n * This is used only when drawBuffer extension or webGL2 are active\n * @param textures defines the render target textures to unbind\n * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated\n * @param onBeforeUnbind defines a function which will be called before the effective unbind\n */\n Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {\n if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }\n this._currentRenderTarget = null;\n // If MSAA, we need to bitblt back to main texture\n var gl = this._gl;\n if (textures[0]._MSAAFramebuffer) {\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);\n var attachments = textures[0]._attachments;\n if (!attachments) {\n attachments = new Array(textures.length);\n textures[0]._attachments = attachments;\n }\n for (var i = 0; i < textures.length; i++) {\n var texture = textures[i];\n for (var j = 0; j < attachments.length; j++) {\n attachments[j] = gl.NONE;\n }\n attachments[i] = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n gl.readBuffer(attachments[i]);\n gl.drawBuffers(attachments);\n gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);\n }\n for (var i = 0; i < attachments.length; i++) {\n attachments[i] = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n }\n gl.drawBuffers(attachments);\n }\n for (var i = 0; i < textures.length; i++) {\n var texture = textures[i];\n if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {\n this._bindTextureDirectly(gl.TEXTURE_2D, texture);\n gl.generateMipmap(gl.TEXTURE_2D);\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n }\n }\n if (onBeforeUnbind) {\n if (textures[0]._MSAAFramebuffer) {\n // Bind the correct framebuffer\n this.bindUnboundFramebuffer(textures[0]._framebuffer);\n }\n onBeforeUnbind();\n }\n this.bindUnboundFramebuffer(null);\n };\n /**\n * Force the mipmap generation for the given render target texture\n * @param texture defines the render target texture to use\n */\n Engine.prototype.generateMipMapsForCubemap = function (texture) {\n if (texture.generateMipMaps) {\n var gl = this._gl;\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n gl.generateMipmap(gl.TEXTURE_CUBE_MAP);\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n }\n };\n /**\n * Force a webGL flush (ie. a flush of all waiting webGL commands)\n */\n Engine.prototype.flushFramebuffer = function () {\n this._gl.flush();\n };\n /**\n * Unbind the current render target and bind the default framebuffer\n */\n Engine.prototype.restoreDefaultFramebuffer = function () {\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n else {\n this.bindUnboundFramebuffer(null);\n }\n if (this._cachedViewport) {\n this.setViewport(this._cachedViewport);\n }\n this.wipeCaches();\n };\n // UBOs\n /**\n * Create an uniform buffer\n * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets\n * @param elements defines the content of the uniform buffer\n * @returns the webGL uniform buffer\n */\n Engine.prototype.createUniformBuffer = function (elements) {\n var ubo = this._gl.createBuffer();\n if (!ubo) {\n throw new Error(\"Unable to create uniform buffer\");\n }\n this.bindUniformBuffer(ubo);\n if (elements instanceof Float32Array) {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);\n }\n else {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);\n }\n this.bindUniformBuffer(null);\n ubo.references = 1;\n return ubo;\n };\n /**\n * Create a dynamic uniform buffer\n * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets\n * @param elements defines the content of the uniform buffer\n * @returns the webGL uniform buffer\n */\n Engine.prototype.createDynamicUniformBuffer = function (elements) {\n var ubo = this._gl.createBuffer();\n if (!ubo) {\n throw new Error(\"Unable to create dynamic uniform buffer\");\n }\n this.bindUniformBuffer(ubo);\n if (elements instanceof Float32Array) {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);\n }\n else {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);\n }\n this.bindUniformBuffer(null);\n ubo.references = 1;\n return ubo;\n };\n /**\n * Update an existing uniform buffer\n * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets\n * @param uniformBuffer defines the target uniform buffer\n * @param elements defines the content to update\n * @param offset defines the offset in the uniform buffer where update should start\n * @param count defines the size of the data to update\n */\n Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {\n this.bindUniformBuffer(uniformBuffer);\n if (offset === undefined) {\n offset = 0;\n }\n if (count === undefined) {\n if (elements instanceof Float32Array) {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);\n }\n else {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));\n }\n }\n else {\n if (elements instanceof Float32Array) {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));\n }\n else {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));\n }\n }\n this.bindUniformBuffer(null);\n };\n // VBOs\n Engine.prototype._resetVertexBufferBinding = function () {\n this.bindArrayBuffer(null);\n this._cachedVertexBuffers = null;\n };\n /**\n * Creates a vertex buffer\n * @param data the data for the vertex buffer\n * @returns the new WebGL static buffer\n */\n Engine.prototype.createVertexBuffer = function (data) {\n var vbo = this._gl.createBuffer();\n if (!vbo) {\n throw new Error(\"Unable to create vertex buffer\");\n }\n this.bindArrayBuffer(vbo);\n if (data instanceof Array) {\n this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);\n }\n else {\n this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);\n }\n this._resetVertexBufferBinding();\n vbo.references = 1;\n return vbo;\n };\n /**\n * Creates a dynamic vertex buffer\n * @param data the data for the dynamic vertex buffer\n * @returns the new WebGL dynamic buffer\n */\n Engine.prototype.createDynamicVertexBuffer = function (data) {\n var vbo = this._gl.createBuffer();\n if (!vbo) {\n throw new Error(\"Unable to create dynamic vertex buffer\");\n }\n this.bindArrayBuffer(vbo);\n if (data instanceof Array) {\n this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);\n }\n else {\n this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);\n }\n this._resetVertexBufferBinding();\n vbo.references = 1;\n return vbo;\n };\n /**\n * Update a dynamic index buffer\n * @param indexBuffer defines the target index buffer\n * @param indices defines the data to update\n * @param offset defines the offset in the target index buffer where update should start\n */\n Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {\n if (offset === void 0) { offset = 0; }\n // Force cache update\n this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;\n this.bindIndexBuffer(indexBuffer);\n var arrayBuffer;\n if (indices instanceof Uint16Array || indices instanceof Uint32Array) {\n arrayBuffer = indices;\n }\n else {\n arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);\n }\n this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);\n this._resetIndexBufferBinding();\n };\n /**\n * Updates a dynamic vertex buffer.\n * @param vertexBuffer the vertex buffer to update\n * @param data the data used to update the vertex buffer\n * @param byteOffset the byte offset of the data\n * @param byteLength the byte length of the data\n */\n Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {\n this.bindArrayBuffer(vertexBuffer);\n if (byteOffset === undefined) {\n byteOffset = 0;\n }\n if (byteLength === undefined) {\n if (data instanceof Array) {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));\n }\n else {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);\n }\n }\n else {\n if (data instanceof Array) {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));\n }\n else {\n if (data instanceof ArrayBuffer) {\n data = new Uint8Array(data, byteOffset, byteLength);\n }\n else {\n data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);\n }\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);\n }\n }\n this._resetVertexBufferBinding();\n };\n Engine.prototype._resetIndexBufferBinding = function () {\n this.bindIndexBuffer(null);\n this._cachedIndexBuffer = null;\n };\n /**\n * Creates a new index buffer\n * @param indices defines the content of the index buffer\n * @param updatable defines if the index buffer must be updatable\n * @returns a new webGL buffer\n */\n Engine.prototype.createIndexBuffer = function (indices, updatable) {\n var vbo = this._gl.createBuffer();\n if (!vbo) {\n throw new Error(\"Unable to create index buffer\");\n }\n this.bindIndexBuffer(vbo);\n // Check for 32 bits indices\n var arrayBuffer;\n var need32Bits = false;\n if (indices instanceof Uint16Array) {\n arrayBuffer = indices;\n }\n else {\n //check 32 bit support\n if (this._caps.uintIndices) {\n if (indices instanceof Uint32Array) {\n arrayBuffer = indices;\n need32Bits = true;\n }\n else {\n //number[] or Int32Array, check if 32 bit is necessary\n for (var index = 0; index < indices.length; index++) {\n if (indices[index] > 65535) {\n need32Bits = true;\n break;\n }\n }\n arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);\n }\n }\n else {\n //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)\n arrayBuffer = new Uint16Array(indices);\n }\n }\n this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);\n this._resetIndexBufferBinding();\n vbo.references = 1;\n vbo.is32Bits = need32Bits;\n return vbo;\n };\n /**\n * Bind a webGL buffer to the webGL context\n * @param buffer defines the buffer to bind\n */\n Engine.prototype.bindArrayBuffer = function (buffer) {\n if (!this._vaoRecordInProgress) {\n this._unbindVertexArrayObject();\n }\n this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);\n };\n /**\n * Bind an uniform buffer to the current webGL context\n * @param buffer defines the buffer to bind\n */\n Engine.prototype.bindUniformBuffer = function (buffer) {\n this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);\n };\n /**\n * Bind a buffer to the current webGL context at a given location\n * @param buffer defines the buffer to bind\n * @param location defines the index where to bind the buffer\n */\n Engine.prototype.bindUniformBufferBase = function (buffer, location) {\n this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);\n };\n /**\n * Bind a specific block at a given index in a specific shader program\n * @param shaderProgram defines the shader program\n * @param blockName defines the block name\n * @param index defines the index where to bind the block\n */\n Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {\n var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);\n this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);\n };\n ;\n Engine.prototype.bindIndexBuffer = function (buffer) {\n if (!this._vaoRecordInProgress) {\n this._unbindVertexArrayObject();\n }\n this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);\n };\n Engine.prototype.bindBuffer = function (buffer, target) {\n if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {\n this._gl.bindBuffer(target, buffer);\n this._currentBoundBuffer[target] = buffer;\n }\n };\n /**\n * update the bound buffer with the given data\n * @param data defines the data to update\n */\n Engine.prototype.updateArrayBuffer = function (data) {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);\n };\n Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {\n var pointer = this._currentBufferPointers[indx];\n var changed = false;\n if (!pointer.active) {\n changed = true;\n pointer.active = true;\n pointer.index = indx;\n pointer.size = size;\n pointer.type = type;\n pointer.normalized = normalized;\n pointer.stride = stride;\n pointer.offset = offset;\n pointer.buffer = buffer;\n }\n else {\n if (pointer.buffer !== buffer) {\n pointer.buffer = buffer;\n changed = true;\n }\n if (pointer.size !== size) {\n pointer.size = size;\n changed = true;\n }\n if (pointer.type !== type) {\n pointer.type = type;\n changed = true;\n }\n if (pointer.normalized !== normalized) {\n pointer.normalized = normalized;\n changed = true;\n }\n if (pointer.stride !== stride) {\n pointer.stride = stride;\n changed = true;\n }\n if (pointer.offset !== offset) {\n pointer.offset = offset;\n changed = true;\n }\n }\n if (changed || this._vaoRecordInProgress) {\n this.bindArrayBuffer(buffer);\n this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);\n }\n };\n Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {\n if (indexBuffer == null) {\n return;\n }\n if (this._cachedIndexBuffer !== indexBuffer) {\n this._cachedIndexBuffer = indexBuffer;\n this.bindIndexBuffer(indexBuffer);\n this._uintIndicesCurrentlySet = indexBuffer.is32Bits;\n }\n };\n Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {\n var attributes = effect.getAttributesNames();\n if (!this._vaoRecordInProgress) {\n this._unbindVertexArrayObject();\n }\n this.unbindAllAttributes();\n for (var index = 0; index < attributes.length; index++) {\n var order = effect.getAttributeLocation(index);\n if (order >= 0) {\n var vertexBuffer = vertexBuffers[attributes[index]];\n if (!vertexBuffer) {\n continue;\n }\n this._gl.enableVertexAttribArray(order);\n if (!this._vaoRecordInProgress) {\n this._vertexAttribArraysEnabled[order] = true;\n }\n var buffer = vertexBuffer.getBuffer();\n if (buffer) {\n this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);\n if (vertexBuffer.getIsInstanced()) {\n this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());\n if (!this._vaoRecordInProgress) {\n this._currentInstanceLocations.push(order);\n this._currentInstanceBuffers.push(buffer);\n }\n }\n }\n }\n }\n };\n /**\n * Records a vertex array object\n * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects\n * @param vertexBuffers defines the list of vertex buffers to store\n * @param indexBuffer defines the index buffer to store\n * @param effect defines the effect to store\n * @returns the new vertex array object\n */\n Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {\n var vao = this._gl.createVertexArray();\n this._vaoRecordInProgress = true;\n this._gl.bindVertexArray(vao);\n this._mustWipeVertexAttributes = true;\n this._bindVertexBuffersAttributes(vertexBuffers, effect);\n this.bindIndexBuffer(indexBuffer);\n this._vaoRecordInProgress = false;\n this._gl.bindVertexArray(null);\n return vao;\n };\n /**\n * Bind a specific vertex array object\n * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects\n * @param vertexArrayObject defines the vertex array object to bind\n * @param indexBuffer defines the index buffer to bind\n */\n Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {\n if (this._cachedVertexArrayObject !== vertexArrayObject) {\n this._cachedVertexArrayObject = vertexArrayObject;\n this._gl.bindVertexArray(vertexArrayObject);\n this._cachedVertexBuffers = null;\n this._cachedIndexBuffer = null;\n this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;\n this._mustWipeVertexAttributes = true;\n }\n };\n /**\n * Bind webGl buffers directly to the webGL context\n * @param vertexBuffer defines the vertex buffer to bind\n * @param indexBuffer defines the index buffer to bind\n * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer\n * @param vertexStrideSize defines the vertex stride of the vertex buffer\n * @param effect defines the effect associated with the vertex buffer\n */\n Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {\n if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {\n this._cachedVertexBuffers = vertexBuffer;\n this._cachedEffectForVertexBuffers = effect;\n var attributesCount = effect.getAttributesCount();\n this._unbindVertexArrayObject();\n this.unbindAllAttributes();\n var offset = 0;\n for (var index = 0; index < attributesCount; index++) {\n if (index < vertexDeclaration.length) {\n var order = effect.getAttributeLocation(index);\n if (order >= 0) {\n this._gl.enableVertexAttribArray(order);\n this._vertexAttribArraysEnabled[order] = true;\n this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);\n }\n offset += vertexDeclaration[index] * 4;\n }\n }\n }\n this._bindIndexBufferWithCache(indexBuffer);\n };\n Engine.prototype._unbindVertexArrayObject = function () {\n if (!this._cachedVertexArrayObject) {\n return;\n }\n this._cachedVertexArrayObject = null;\n this._gl.bindVertexArray(null);\n };\n /**\n * Bind a list of vertex buffers to the webGL context\n * @param vertexBuffers defines the list of vertex buffers to bind\n * @param indexBuffer defines the index buffer to bind\n * @param effect defines the effect associated with the vertex buffers\n */\n Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {\n if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {\n this._cachedVertexBuffers = vertexBuffers;\n this._cachedEffectForVertexBuffers = effect;\n this._bindVertexBuffersAttributes(vertexBuffers, effect);\n }\n this._bindIndexBufferWithCache(indexBuffer);\n };\n /**\n * Unbind all instance attributes\n */\n Engine.prototype.unbindInstanceAttributes = function () {\n var boundBuffer;\n for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {\n var instancesBuffer = this._currentInstanceBuffers[i];\n if (boundBuffer != instancesBuffer && instancesBuffer.references) {\n boundBuffer = instancesBuffer;\n this.bindArrayBuffer(instancesBuffer);\n }\n var offsetLocation = this._currentInstanceLocations[i];\n this._gl.vertexAttribDivisor(offsetLocation, 0);\n }\n this._currentInstanceBuffers.length = 0;\n this._currentInstanceLocations.length = 0;\n };\n /**\n * Release and free the memory of a vertex array object\n * @param vao defines the vertex array object to delete\n */\n Engine.prototype.releaseVertexArrayObject = function (vao) {\n this._gl.deleteVertexArray(vao);\n };\n /** @hidden */\n Engine.prototype._releaseBuffer = function (buffer) {\n buffer.references--;\n if (buffer.references === 0) {\n this._gl.deleteBuffer(buffer);\n return true;\n }\n return false;\n };\n /**\n * Creates a webGL buffer to use with instanciation\n * @param capacity defines the size of the buffer\n * @returns the webGL buffer\n */\n Engine.prototype.createInstancesBuffer = function (capacity) {\n var buffer = this._gl.createBuffer();\n if (!buffer) {\n throw new Error(\"Unable to create instance buffer\");\n }\n buffer.capacity = capacity;\n this.bindArrayBuffer(buffer);\n this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);\n return buffer;\n };\n /**\n * Delete a webGL buffer used with instanciation\n * @param buffer defines the webGL buffer to delete\n */\n Engine.prototype.deleteInstancesBuffer = function (buffer) {\n this._gl.deleteBuffer(buffer);\n };\n /**\n * Update the content of a webGL buffer used with instanciation and bind it to the webGL context\n * @param instancesBuffer defines the webGL buffer to update and bind\n * @param data defines the data to store in the buffer\n * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer\n */\n Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {\n this.bindArrayBuffer(instancesBuffer);\n if (data) {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);\n }\n if (offsetLocations[0].index !== undefined) {\n var stride = 0;\n for (var i = 0; i < offsetLocations.length; i++) {\n var ai = offsetLocations[i];\n stride += ai.attributeSize * 4;\n }\n for (var i = 0; i < offsetLocations.length; i++) {\n var ai = offsetLocations[i];\n if (!this._vertexAttribArraysEnabled[ai.index]) {\n this._gl.enableVertexAttribArray(ai.index);\n this._vertexAttribArraysEnabled[ai.index] = true;\n }\n this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);\n this._gl.vertexAttribDivisor(ai.index, 1);\n this._currentInstanceLocations.push(ai.index);\n this._currentInstanceBuffers.push(instancesBuffer);\n }\n }\n else {\n for (var index = 0; index < 4; index++) {\n var offsetLocation = offsetLocations[index];\n if (!this._vertexAttribArraysEnabled[offsetLocation]) {\n this._gl.enableVertexAttribArray(offsetLocation);\n this._vertexAttribArraysEnabled[offsetLocation] = true;\n }\n this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);\n this._gl.vertexAttribDivisor(offsetLocation, 1);\n this._currentInstanceLocations.push(offsetLocation);\n this._currentInstanceBuffers.push(instancesBuffer);\n }\n }\n };\n /**\n * Apply all cached states (depth, culling, stencil and alpha)\n */\n Engine.prototype.applyStates = function () {\n this._depthCullingState.apply(this._gl);\n this._stencilState.apply(this._gl);\n this._alphaState.apply(this._gl);\n };\n /**\n * Send a draw order\n * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)\n * @param indexStart defines the starting index\n * @param indexCount defines the number of index to draw\n * @param instancesCount defines the number of instances to draw (if instanciation is enabled)\n */\n Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {\n this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);\n };\n /**\n * Draw a list of points\n * @param verticesStart defines the index of first vertex to draw\n * @param verticesCount defines the count of vertices to draw\n * @param instancesCount defines the number of instances to draw (if instanciation is enabled)\n */\n Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {\n this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);\n };\n /**\n * Draw a list of unindexed primitives\n * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)\n * @param verticesStart defines the index of first vertex to draw\n * @param verticesCount defines the count of vertices to draw\n * @param instancesCount defines the number of instances to draw (if instanciation is enabled)\n */\n Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {\n this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);\n };\n /**\n * Draw a list of indexed primitives\n * @param fillMode defines the primitive to use\n * @param indexStart defines the starting index\n * @param indexCount defines the number of index to draw\n * @param instancesCount defines the number of instances to draw (if instanciation is enabled)\n */\n Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {\n // Apply states\n this.applyStates();\n this._drawCalls.addCount(1, false);\n // Render\n var drawMode = this._drawMode(fillMode);\n var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;\n var mult = this._uintIndicesCurrentlySet ? 4 : 2;\n if (instancesCount) {\n this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);\n }\n else {\n this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);\n }\n };\n /**\n * Draw a list of unindexed primitives\n * @param fillMode defines the primitive to use\n * @param verticesStart defines the index of first vertex to draw\n * @param verticesCount defines the count of vertices to draw\n * @param instancesCount defines the number of instances to draw (if instanciation is enabled)\n */\n Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {\n // Apply states\n this.applyStates();\n this._drawCalls.addCount(1, false);\n var drawMode = this._drawMode(fillMode);\n if (instancesCount) {\n this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);\n }\n else {\n this._gl.drawArrays(drawMode, verticesStart, verticesCount);\n }\n };\n Engine.prototype._drawMode = function (fillMode) {\n switch (fillMode) {\n // Triangle views\n case BABYLON.Material.TriangleFillMode:\n return this._gl.TRIANGLES;\n case BABYLON.Material.PointFillMode:\n return this._gl.POINTS;\n case BABYLON.Material.WireFrameFillMode:\n return this._gl.LINES;\n // Draw modes\n case BABYLON.Material.PointListDrawMode:\n return this._gl.POINTS;\n case BABYLON.Material.LineListDrawMode:\n return this._gl.LINES;\n case BABYLON.Material.LineLoopDrawMode:\n return this._gl.LINE_LOOP;\n case BABYLON.Material.LineStripDrawMode:\n return this._gl.LINE_STRIP;\n case BABYLON.Material.TriangleStripDrawMode:\n return this._gl.TRIANGLE_STRIP;\n case BABYLON.Material.TriangleFanDrawMode:\n return this._gl.TRIANGLE_FAN;\n default:\n return this._gl.TRIANGLES;\n }\n };\n // Shaders\n /** @hidden */\n Engine.prototype._releaseEffect = function (effect) {\n if (this._compiledEffects[effect._key]) {\n delete this._compiledEffects[effect._key];\n this._deleteProgram(effect.getProgram());\n }\n };\n /** @hidden */\n Engine.prototype._deleteProgram = function (program) {\n if (program) {\n program.__SPECTOR_rebuildProgram = null;\n if (program.transformFeedback) {\n this.deleteTransformFeedback(program.transformFeedback);\n program.transformFeedback = null;\n }\n this._gl.deleteProgram(program);\n }\n };\n /**\n * Create a new effect (used to store vertex/fragment shaders)\n * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)\n * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object\n * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use\n * @param samplers defines an array of string used to represent textures\n * @param defines defines the string containing the defines to use to compile the shaders\n * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails\n * @param onCompiled defines a function to call when the effect creation is successful\n * @param onError defines a function to call when the effect creation has failed\n * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)\n * @returns the new Effect\n */\n Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {\n var vertex = baseName.vertexElement || baseName.vertex || baseName;\n var fragment = baseName.fragmentElement || baseName.fragment || baseName;\n var name = vertex + \"+\" + fragment + \"@\" + (defines ? defines : attributesNamesOrOptions.defines);\n if (this._compiledEffects[name]) {\n var compiledEffect = this._compiledEffects[name];\n if (onCompiled && compiledEffect.isReady()) {\n onCompiled(compiledEffect);\n }\n return compiledEffect;\n }\n var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);\n effect._key = name;\n this._compiledEffects[name] = effect;\n return effect;\n };\n Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {\n return this._compileRawShader(shaderVersion + (defines ? defines + \"\\n\" : \"\") + source, type);\n };\n ;\n Engine.prototype._compileRawShader = function (source, type) {\n var gl = this._gl;\n var shader = gl.createShader(type === \"vertex\" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n var log = gl.getShaderInfoLog(shader);\n if (log) {\n throw new Error(log);\n }\n }\n if (!shader) {\n throw new Error(\"Something went wrong while compile the shader.\");\n }\n return shader;\n };\n ;\n /**\n * Directly creates a webGL program\n * @param vertexCode defines the vertex shader code to use\n * @param fragmentCode defines the fragment shader code to use\n * @param context defines the webGL context to use (if not set, the current one will be used)\n * @param transformFeedbackVaryings defines the list of transform feedback varyings to use\n * @returns the new webGL program\n */\n Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {\n if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }\n context = context || this._gl;\n var vertexShader = this._compileRawShader(vertexCode, \"vertex\");\n var fragmentShader = this._compileRawShader(fragmentCode, \"fragment\");\n return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);\n };\n /**\n * Creates a webGL program\n * @param vertexCode defines the vertex shader code to use\n * @param fragmentCode defines the fragment shader code to use\n * @param defines defines the string containing the defines to use to compile the shaders\n * @param context defines the webGL context to use (if not set, the current one will be used)\n * @param transformFeedbackVaryings defines the list of transform feedback varyings to use\n * @returns the new webGL program\n */\n Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {\n if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }\n context = context || this._gl;\n this.onBeforeShaderCompilationObservable.notifyObservers(this);\n var shaderVersion = (this._webGLVersion > 1) ? \"#version 300 es\\n#define WEBGL2 \\n\" : \"\";\n var vertexShader = this._compileShader(vertexCode, \"vertex\", defines, shaderVersion);\n var fragmentShader = this._compileShader(fragmentCode, \"fragment\", defines, shaderVersion);\n var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);\n this.onAfterShaderCompilationObservable.notifyObservers(this);\n return program;\n };\n Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {\n if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }\n var shaderProgram = context.createProgram();\n if (!shaderProgram) {\n throw new Error(\"Unable to create program\");\n }\n context.attachShader(shaderProgram, vertexShader);\n context.attachShader(shaderProgram, fragmentShader);\n if (this.webGLVersion > 1 && transformFeedbackVaryings) {\n var transformFeedback = this.createTransformFeedback();\n this.bindTransformFeedback(transformFeedback);\n this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);\n shaderProgram.transformFeedback = transformFeedback;\n }\n context.linkProgram(shaderProgram);\n if (this.webGLVersion > 1 && transformFeedbackVaryings) {\n this.bindTransformFeedback(null);\n }\n var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);\n if (!linked) {\n var error = context.getProgramInfoLog(shaderProgram);\n if (error) {\n throw new Error(error);\n }\n }\n if (this.validateShaderPrograms) {\n context.validateProgram(shaderProgram);\n var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);\n if (!validated) {\n var error = context.getProgramInfoLog(shaderProgram);\n if (error) {\n throw new Error(error);\n }\n }\n }\n context.deleteShader(vertexShader);\n context.deleteShader(fragmentShader);\n return shaderProgram;\n };\n /**\n * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names\n * @param shaderProgram defines the webGL program to use\n * @param uniformsNames defines the list of uniform names\n * @returns an array of webGL uniform locations\n */\n Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {\n var results = new Array();\n for (var index = 0; index < uniformsNames.length; index++) {\n results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));\n }\n return results;\n };\n /**\n * Gets the lsit of active attributes for a given webGL program\n * @param shaderProgram defines the webGL program to use\n * @param attributesNames defines the list of attribute names to get\n * @returns an array of indices indicating the offset of each attribute\n */\n Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {\n var results = [];\n for (var index = 0; index < attributesNames.length; index++) {\n try {\n results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));\n }\n catch (e) {\n results.push(-1);\n }\n }\n return results;\n };\n /**\n * Activates an effect, mkaing it the current one (ie. the one used for rendering)\n * @param effect defines the effect to activate\n */\n Engine.prototype.enableEffect = function (effect) {\n if (!effect) {\n return;\n }\n // Use program\n this.bindSamplers(effect);\n this._currentEffect = effect;\n if (effect.onBind) {\n effect.onBind(effect);\n }\n effect.onBindObservable.notifyObservers(effect);\n };\n /**\n * Set the value of an uniform to an array of int32\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n */\n Engine.prototype.setIntArray = function (uniform, array) {\n if (!uniform)\n return;\n this._gl.uniform1iv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of int32 (stored as vec2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n */\n Engine.prototype.setIntArray2 = function (uniform, array) {\n if (!uniform || array.length % 2 !== 0)\n return;\n this._gl.uniform2iv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of int32 (stored as vec3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n */\n Engine.prototype.setIntArray3 = function (uniform, array) {\n if (!uniform || array.length % 3 !== 0)\n return;\n this._gl.uniform3iv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of int32 (stored as vec4)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n */\n Engine.prototype.setIntArray4 = function (uniform, array) {\n if (!uniform || array.length % 4 !== 0)\n return;\n this._gl.uniform4iv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of float32\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n */\n Engine.prototype.setFloatArray = function (uniform, array) {\n if (!uniform)\n return;\n this._gl.uniform1fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of float32 (stored as vec2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n */\n Engine.prototype.setFloatArray2 = function (uniform, array) {\n if (!uniform || array.length % 2 !== 0)\n return;\n this._gl.uniform2fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of float32 (stored as vec3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n */\n Engine.prototype.setFloatArray3 = function (uniform, array) {\n if (!uniform || array.length % 3 !== 0)\n return;\n this._gl.uniform3fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of float32 (stored as vec4)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n */\n Engine.prototype.setFloatArray4 = function (uniform, array) {\n if (!uniform || array.length % 4 !== 0)\n return;\n this._gl.uniform4fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of number\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n */\n Engine.prototype.setArray = function (uniform, array) {\n if (!uniform)\n return;\n this._gl.uniform1fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of number (stored as vec2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n */\n Engine.prototype.setArray2 = function (uniform, array) {\n if (!uniform || array.length % 2 !== 0)\n return;\n this._gl.uniform2fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of number (stored as vec3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n */\n Engine.prototype.setArray3 = function (uniform, array) {\n if (!uniform || array.length % 3 !== 0)\n return;\n this._gl.uniform3fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of number (stored as vec4)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n */\n Engine.prototype.setArray4 = function (uniform, array) {\n if (!uniform || array.length % 4 !== 0)\n return;\n this._gl.uniform4fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of float32 (stored as matrices)\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrices defines the array of float32 to store\n */\n Engine.prototype.setMatrices = function (uniform, matrices) {\n if (!uniform)\n return;\n this._gl.uniformMatrix4fv(uniform, false, matrices);\n };\n /**\n * Set the value of an uniform to a matrix\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrix defines the matrix to store\n */\n Engine.prototype.setMatrix = function (uniform, matrix) {\n if (!uniform)\n return;\n this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());\n };\n /**\n * Set the value of an uniform to a matrix (3x3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrix defines the Float32Array representing the 3x3 matrix to store\n */\n Engine.prototype.setMatrix3x3 = function (uniform, matrix) {\n if (!uniform)\n return;\n this._gl.uniformMatrix3fv(uniform, false, matrix);\n };\n /**\n * Set the value of an uniform to a matrix (2x2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrix defines the Float32Array representing the 2x2 matrix to store\n */\n Engine.prototype.setMatrix2x2 = function (uniform, matrix) {\n if (!uniform)\n return;\n this._gl.uniformMatrix2fv(uniform, false, matrix);\n };\n /**\n * Set the value of an uniform to a number (int)\n * @param uniform defines the webGL uniform location where to store the value\n * @param value defines the int number to store\n */\n Engine.prototype.setInt = function (uniform, value) {\n if (!uniform)\n return;\n this._gl.uniform1i(uniform, value);\n };\n /**\n * Set the value of an uniform to a number (float)\n * @param uniform defines the webGL uniform location where to store the value\n * @param value defines the float number to store\n */\n Engine.prototype.setFloat = function (uniform, value) {\n if (!uniform)\n return;\n this._gl.uniform1f(uniform, value);\n };\n /**\n * Set the value of an uniform to a vec2\n * @param uniform defines the webGL uniform location where to store the value\n * @param x defines the 1st component of the value\n * @param y defines the 2nd component of the value\n */\n Engine.prototype.setFloat2 = function (uniform, x, y) {\n if (!uniform)\n return;\n this._gl.uniform2f(uniform, x, y);\n };\n /**\n * Set the value of an uniform to a vec3\n * @param uniform defines the webGL uniform location where to store the value\n * @param x defines the 1st component of the value\n * @param y defines the 2nd component of the value\n * @param z defines the 3rd component of the value\n */\n Engine.prototype.setFloat3 = function (uniform, x, y, z) {\n if (!uniform)\n return;\n this._gl.uniform3f(uniform, x, y, z);\n };\n /**\n * Set the value of an uniform to a boolean\n * @param uniform defines the webGL uniform location where to store the value\n * @param bool defines the boolean to store\n */\n Engine.prototype.setBool = function (uniform, bool) {\n if (!uniform)\n return;\n this._gl.uniform1i(uniform, bool);\n };\n /**\n * Set the value of an uniform to a vec4\n * @param uniform defines the webGL uniform location where to store the value\n * @param x defines the 1st component of the value\n * @param y defines the 2nd component of the value\n * @param z defines the 3rd component of the value\n * @param w defines the 4th component of the value\n */\n Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {\n if (!uniform)\n return;\n this._gl.uniform4f(uniform, x, y, z, w);\n };\n /**\n * Set the value of an uniform to a Color3\n * @param uniform defines the webGL uniform location where to store the value\n * @param color3 defines the color to store\n */\n Engine.prototype.setColor3 = function (uniform, color3) {\n if (!uniform)\n return;\n this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);\n };\n /**\n * Set the value of an uniform to a Color3 and an alpha value\n * @param uniform defines the webGL uniform location where to store the value\n * @param color3 defines the color to store\n * @param alpha defines the alpha component to store\n */\n Engine.prototype.setColor4 = function (uniform, color3, alpha) {\n if (!uniform)\n return;\n this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);\n };\n /**\n * Sets a Color4 on a uniform variable\n * @param uniform defines the uniform location\n * @param color4 defines the value to be set\n */\n Engine.prototype.setDirectColor4 = function (uniform, color4) {\n if (!uniform)\n return;\n this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);\n };\n // States\n /**\n * Set various states to the webGL context\n * @param culling defines backface culling state\n * @param zOffset defines the value to apply to zOffset (0 by default)\n * @param force defines if states must be applied even if cache is up to date\n * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)\n */\n Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {\n if (zOffset === void 0) { zOffset = 0; }\n if (reverseSide === void 0) { reverseSide = false; }\n // Culling\n if (this._depthCullingState.cull !== culling || force) {\n this._depthCullingState.cull = culling;\n }\n // Cull face\n var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;\n if (this._depthCullingState.cullFace !== cullFace || force) {\n this._depthCullingState.cullFace = cullFace;\n }\n // Z offset\n this.setZOffset(zOffset);\n // Front face\n var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;\n if (this._depthCullingState.frontFace !== frontFace || force) {\n this._depthCullingState.frontFace = frontFace;\n }\n };\n /**\n * Set the z offset to apply to current rendering\n * @param value defines the offset to apply\n */\n Engine.prototype.setZOffset = function (value) {\n this._depthCullingState.zOffset = value;\n };\n /**\n * Gets the current value of the zOffset\n * @returns the current zOffset state\n */\n Engine.prototype.getZOffset = function () {\n return this._depthCullingState.zOffset;\n };\n /**\n * Enable or disable depth buffering\n * @param enable defines the state to set\n */\n Engine.prototype.setDepthBuffer = function (enable) {\n this._depthCullingState.depthTest = enable;\n };\n /**\n * Gets a boolean indicating if depth writing is enabled\n * @returns the current depth writing state\n */\n Engine.prototype.getDepthWrite = function () {\n return this._depthCullingState.depthMask;\n };\n /**\n * Enable or disable depth writing\n * @param enable defines the state to set\n */\n Engine.prototype.setDepthWrite = function (enable) {\n this._depthCullingState.depthMask = enable;\n };\n /**\n * Enable or disable color writing\n * @param enable defines the state to set\n */\n Engine.prototype.setColorWrite = function (enable) {\n this._gl.colorMask(enable, enable, enable, enable);\n this._colorWrite = enable;\n };\n /**\n * Gets a boolean indicating if color writing is enabled\n * @returns the current color writing state\n */\n Engine.prototype.getColorWrite = function () {\n return this._colorWrite;\n };\n /**\n * Sets alpha constants used by some alpha blending modes\n * @param r defines the red component\n * @param g defines the green component\n * @param b defines the blue component\n * @param a defines the alpha component\n */\n Engine.prototype.setAlphaConstants = function (r, g, b, a) {\n this._alphaState.setAlphaBlendConstants(r, g, b, a);\n };\n /**\n * Sets the current alpha mode\n * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)\n * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)\n * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered\n */\n Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {\n if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }\n if (this._alphaMode === mode) {\n return;\n }\n switch (mode) {\n case Engine.ALPHA_DISABLE:\n this._alphaState.alphaBlend = false;\n break;\n case Engine.ALPHA_PREMULTIPLIED:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_COMBINE:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_ONEONE:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_ADD:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_SUBTRACT:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_MULTIPLY:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_MAXIMIZED:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_INTERPOLATE:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_SCREENMODE:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n }\n if (!noDepthWriteChange) {\n this.setDepthWrite(mode === Engine.ALPHA_DISABLE);\n }\n this._alphaMode = mode;\n };\n /**\n * Gets the current alpha mode\n * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered\n * @returns the current alpha mode\n */\n Engine.prototype.getAlphaMode = function () {\n return this._alphaMode;\n };\n // Textures\n /**\n * Clears the list of texture accessible through engine.\n * This can help preventing texture load conflict due to name collision.\n */\n Engine.prototype.clearInternalTexturesCache = function () {\n this._internalTexturesCache = [];\n };\n /**\n * Force the entire cache to be cleared\n * You should not have to use this function unless your engine needs to share the webGL context with another engine\n * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)\n */\n Engine.prototype.wipeCaches = function (bruteForce) {\n if (this.preventCacheWipeBetweenFrames && !bruteForce) {\n return;\n }\n this._currentEffect = null;\n this._unpackFlipYCached = null;\n this._viewportCached.x = 0;\n this._viewportCached.y = 0;\n this._viewportCached.z = 0;\n this._viewportCached.w = 0;\n if (bruteForce) {\n this.resetTextureCache();\n this._currentProgram = null;\n this._stencilState.reset();\n this._depthCullingState.reset();\n this.setDepthFunctionToLessOrEqual();\n this._alphaState.reset();\n }\n this._resetVertexBufferBinding();\n this._cachedIndexBuffer = null;\n this._cachedEffectForVertexBuffers = null;\n this._unbindVertexArrayObject();\n this.bindIndexBuffer(null);\n };\n /**\n * Set the compressed texture format to use, based on the formats you have, and the formats\n * supported by the hardware / browser.\n *\n * Khronos Texture Container (.ktx) files are used to support this. This format has the\n * advantage of being specifically designed for OpenGL. Header elements directly correspond\n * to API arguments needed to compressed textures. This puts the burden on the container\n * generator to house the arcane code for determining these for current & future formats.\n *\n * for description see https://www.khronos.org/opengles/sdk/tools/KTX/\n * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/\n *\n * Note: The result of this call is not taken into account when a texture is base64.\n *\n * @param formatsAvailable defines the list of those format families you have created\n * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)\n *\n * Current families are astc, dxt, pvrtc, etc2, & etc1.\n * @returns The extension selected.\n */\n Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {\n for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {\n for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {\n if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {\n return this._textureFormatInUse = this._texturesSupported[i];\n }\n }\n }\n // actively set format to nothing, to allow this to be called more than once\n // and possibly fail the 2nd time\n this._textureFormatInUse = null;\n return null;\n };\n Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {\n var gl = this._gl;\n var magFilter = gl.NEAREST;\n var minFilter = gl.NEAREST;\n switch (samplingMode) {\n case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:\n magFilter = gl.LINEAR;\n if (generateMipMaps) {\n minFilter = gl.LINEAR_MIPMAP_NEAREST;\n }\n else {\n minFilter = gl.LINEAR;\n }\n break;\n case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:\n magFilter = gl.LINEAR;\n if (generateMipMaps) {\n minFilter = gl.LINEAR_MIPMAP_LINEAR;\n }\n else {\n minFilter = gl.LINEAR;\n }\n break;\n case Engine.TEXTURE_NEAREST_SAMPLINGMODE:\n magFilter = gl.NEAREST;\n if (generateMipMaps) {\n minFilter = gl.NEAREST_MIPMAP_LINEAR;\n }\n else {\n minFilter = gl.NEAREST;\n }\n break;\n case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:\n magFilter = gl.NEAREST;\n if (generateMipMaps) {\n minFilter = gl.NEAREST_MIPMAP_NEAREST;\n }\n else {\n minFilter = gl.NEAREST;\n }\n break;\n case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:\n magFilter = gl.NEAREST;\n if (generateMipMaps) {\n minFilter = gl.LINEAR_MIPMAP_NEAREST;\n }\n else {\n minFilter = gl.LINEAR;\n }\n break;\n case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:\n magFilter = gl.NEAREST;\n if (generateMipMaps) {\n minFilter = gl.LINEAR_MIPMAP_LINEAR;\n }\n else {\n minFilter = gl.LINEAR;\n }\n break;\n case Engine.TEXTURE_NEAREST_LINEAR:\n magFilter = gl.NEAREST;\n minFilter = gl.LINEAR;\n break;\n case Engine.TEXTURE_NEAREST_NEAREST:\n magFilter = gl.NEAREST;\n minFilter = gl.NEAREST;\n break;\n case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:\n magFilter = gl.LINEAR;\n if (generateMipMaps) {\n minFilter = gl.NEAREST_MIPMAP_NEAREST;\n }\n else {\n minFilter = gl.NEAREST;\n }\n break;\n case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:\n magFilter = gl.LINEAR;\n if (generateMipMaps) {\n minFilter = gl.NEAREST_MIPMAP_LINEAR;\n }\n else {\n minFilter = gl.NEAREST;\n }\n break;\n case Engine.TEXTURE_LINEAR_LINEAR:\n magFilter = gl.LINEAR;\n minFilter = gl.LINEAR;\n break;\n case Engine.TEXTURE_LINEAR_NEAREST:\n magFilter = gl.LINEAR;\n minFilter = gl.NEAREST;\n break;\n }\n return {\n min: minFilter,\n mag: magFilter\n };\n };\n Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {\n if (onErrorCallBack === void 0) { onErrorCallBack = null; }\n var img;\n var onload = function () {\n loadedImages[index] = img;\n loadedImages._internalCount++;\n if (scene) {\n scene._removePendingData(img);\n }\n if (loadedImages._internalCount === 6) {\n onfinish(loadedImages);\n }\n };\n var onerror = function (message, exception) {\n if (scene) {\n scene._removePendingData(img);\n }\n if (onErrorCallBack) {\n onErrorCallBack(message, exception);\n }\n };\n img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);\n if (scene) {\n scene._addPendingData(img);\n }\n };\n Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {\n if (onError === void 0) { onError = null; }\n var loadedImages = [];\n loadedImages._internalCount = 0;\n for (var index = 0; index < 6; index++) {\n this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);\n }\n };\n ;\n /** @hidden */\n Engine.prototype._createTexture = function () {\n var texture = this._gl.createTexture();\n if (!texture) {\n throw new Error(\"Unable to create texture\");\n }\n return texture;\n };\n /**\n * Usually called from BABYLON.Texture.ts.\n * Passed information to create a WebGLTexture\n * @param urlArg defines a value which contains one of the following:\n * * A conventional http URL, e.g. 'http://...' or 'file://...'\n * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'\n * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'\n * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file\n * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file\n * @param scene needed for loading to the correct scene\n * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)\n * @param onLoad optional callback to be called upon successful completion\n * @param onError optional callback to be called upon failure\n * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob\n * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities\n * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures\n * @param forcedExtension defines the extension to use to pick the right loader\n * @returns a InternalTexture for assignment back into BABYLON.Texture\n */\n Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {\n var _this = this;\n if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (buffer === void 0) { buffer = null; }\n if (fallback === void 0) { fallback = null; }\n if (format === void 0) { format = null; }\n if (forcedExtension === void 0) { forcedExtension = null; }\n var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback\n var fromData = url.substr(0, 5) === \"data:\";\n var fromBlob = url.substr(0, 5) === \"blob:\";\n var isBase64 = fromData && url.indexOf(\"base64\") !== -1;\n var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);\n // establish the file extension, if possible\n var lastDot = url.lastIndexOf('.');\n var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : \"\");\n var loader = null;\n for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {\n var availableLoader = _a[_i];\n if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {\n loader = availableLoader;\n break;\n }\n }\n if (loader) {\n url = loader.transformUrl(url, this._textureFormatInUse);\n }\n if (scene) {\n scene._addPendingData(texture);\n }\n texture.url = url;\n texture.generateMipMaps = !noMipmap;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n if (!this._doNotHandleContextLost) {\n // Keep a link to the buffer only if we plan to handle context lost\n texture._buffer = buffer;\n }\n var onLoadObserver = null;\n if (onLoad && !fallback) {\n onLoadObserver = texture.onLoadedObservable.add(onLoad);\n }\n if (!fallback)\n this._internalTexturesCache.push(texture);\n var onInternalError = function (message, exception) {\n if (scene) {\n scene._removePendingData(texture);\n }\n var customFallback = false;\n if (loader) {\n var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);\n if (fallbackUrl) {\n // Add Back\n customFallback = true;\n _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);\n }\n }\n if (!customFallback) {\n if (onLoadObserver) {\n texture.onLoadedObservable.remove(onLoadObserver);\n }\n if (BABYLON.Tools.UseFallbackTexture) {\n _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);\n }\n }\n if (onError) {\n onError(message || \"Unknown error\", exception);\n }\n };\n // processing for non-image formats\n if (loader) {\n var callback = function (data) {\n loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {\n _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {\n done();\n return false;\n }, samplingMode);\n });\n };\n if (!buffer) {\n this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {\n onInternalError(\"Unable to load \" + (request ? request.responseURL : url, exception));\n });\n }\n else {\n callback(buffer);\n }\n }\n else {\n var onload = function (img) {\n if (fromBlob && !_this._doNotHandleContextLost) {\n // We need to store the image if we need to rebuild the texture\n // in case of a webgl context lost\n texture._buffer = img;\n }\n _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {\n var gl = _this._gl;\n var isPot = (img.width === potWidth && img.height === potHeight);\n var internalFormat = format ? _this._getInternalFormat(format) : ((extension === \".jpg\") ? gl.RGB : gl.RGBA);\n if (isPot) {\n gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);\n return false;\n }\n var maxTextureSize = _this._caps.maxTextureSize;\n if (img.width > maxTextureSize || img.height > maxTextureSize) {\n _this._prepareWorkingCanvas();\n if (!_this._workingCanvas || !_this._workingContext) {\n return false;\n }\n _this._workingCanvas.width = potWidth;\n _this._workingCanvas.height = potHeight;\n _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);\n gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);\n texture.width = potWidth;\n texture.height = potHeight;\n return false;\n }\n else {\n // Using shaders when possible to rescale because canvas.drawImage is lossy\n var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);\n _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);\n gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {\n _this._releaseTexture(source_1);\n _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);\n continuationCallback();\n });\n }\n return true;\n }, samplingMode);\n };\n if (!fromData || isBase64) {\n if (buffer instanceof HTMLImageElement) {\n onload(buffer);\n }\n else {\n BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);\n }\n }\n else if (typeof buffer === \"string\" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {\n BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);\n }\n else {\n onload(buffer);\n }\n }\n return texture;\n };\n Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {\n var _this = this;\n var rtt = this.createRenderTargetTexture({\n width: destination.width,\n height: destination.height,\n }, {\n generateMipMaps: false,\n type: Engine.TEXTURETYPE_UNSIGNED_INT,\n samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,\n generateDepthBuffer: false,\n generateStencilBuffer: false\n });\n if (!this._rescalePostProcess) {\n this._rescalePostProcess = new BABYLON.PassPostProcess(\"rescale\", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);\n }\n this._rescalePostProcess.getEffect().executeWhenCompiled(function () {\n _this._rescalePostProcess.onApply = function (effect) {\n effect._bindTexture(\"textureSampler\", source);\n };\n var hostingScene = scene;\n if (!hostingScene) {\n hostingScene = _this.scenes[_this.scenes.length - 1];\n }\n hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);\n _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);\n _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);\n _this.unBindFramebuffer(rtt);\n _this._releaseTexture(rtt);\n if (onComplete) {\n onComplete();\n }\n });\n };\n /**\n * Update a raw texture\n * @param texture defines the texture to update\n * @param data defines the data to store in the texture\n * @param format defines the format of the data\n * @param invertY defines if data must be stored with Y axis inverted\n * @param compression defines the compression used (null by default)\n * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)\n */\n Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {\n if (compression === void 0) { compression = null; }\n if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (!texture) {\n return;\n }\n // babylon's internalSizedFomat but gl's texImage2D internalFormat\n var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);\n // babylon's internalFormat but gl's texImage2D format\n var internalFormat = this._getInternalFormat(format);\n var textureType = this._getWebGLTextureType(type);\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n texture.format = format;\n texture.type = type;\n texture.invertY = invertY;\n texture._compression = compression;\n }\n if (texture.width % 4 !== 0) {\n this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);\n }\n if (compression && data) {\n this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);\n }\n else {\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);\n }\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n // this.resetTextureCache();\n texture.isReady = true;\n };\n /**\n * Creates a raw texture\n * @param data defines the data to store in the texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param format defines the format of the data\n * @param generateMipMaps defines if the engine should generate the mip levels\n * @param invertY defines if data must be stored with Y axis inverted\n * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)\n * @param compression defines the compression used (null by default)\n * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)\n * @returns the raw texture inside an InternalTexture\n */\n Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {\n if (compression === void 0) { compression = null; }\n if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.format = format;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture._compression = compression;\n texture.type = type;\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n this.updateRawTexture(texture, data, format, invertY, compression, type);\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n // Filters\n var filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);\n if (generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n this._internalTexturesCache.push(texture);\n return texture;\n };\n /** @hidden */\n Engine.prototype._unpackFlipY = function (value) {\n if (this._unpackFlipYCached !== value) {\n this._unpackFlipYCached = value;\n this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);\n }\n };\n /** @hidden */\n Engine.prototype._getUnpackAlignement = function () {\n return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);\n };\n /**\n * Creates a dynamic texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param generateMipMaps defines if the engine should generate the mip levels\n * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)\n * @returns the dynamic texture inside an InternalTexture\n */\n Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);\n texture.baseWidth = width;\n texture.baseHeight = height;\n if (generateMipMaps) {\n width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;\n height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;\n }\n // this.resetTextureCache();\n texture.width = width;\n texture.height = height;\n texture.isReady = false;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n this.updateTextureSamplingMode(samplingMode, texture);\n this._internalTexturesCache.push(texture);\n return texture;\n };\n /**\n * Update the sampling mode of a given texture\n * @param samplingMode defines the required sampling mode\n * @param texture defines the texture to update\n */\n Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {\n var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);\n if (texture.isCube) {\n this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);\n this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n }\n else if (texture.is3D) {\n this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);\n this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);\n this._bindTextureDirectly(this._gl.TEXTURE_3D, null);\n }\n else {\n this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);\n this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n }\n texture.samplingMode = samplingMode;\n };\n /**\n * Update the content of a dynamic texture\n * @param texture defines the texture to update\n * @param canvas defines the canvas containing the source\n * @param invertY defines if data must be stored with Y axis inverted\n * @param premulAlpha defines if alpha is stored as premultiplied\n * @param format defines the format of the data\n */\n Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {\n if (premulAlpha === void 0) { premulAlpha = false; }\n if (!texture) {\n return;\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n this._unpackFlipY(invertY);\n if (premulAlpha) {\n this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);\n }\n var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n if (premulAlpha) {\n this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);\n }\n texture.isReady = true;\n };\n /**\n * Update a video texture\n * @param texture defines the texture to update\n * @param video defines the video element to use\n * @param invertY defines if data must be stored with Y axis inverted\n */\n Engine.prototype.updateVideoTexture = function (texture, video, invertY) {\n if (!texture || texture._isDisabled) {\n return;\n }\n var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n this._unpackFlipY(!invertY); // Video are upside down by default\n try {\n // Testing video texture support\n if (this._videoTextureSupported === undefined) {\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);\n if (this._gl.getError() !== 0) {\n this._videoTextureSupported = false;\n }\n else {\n this._videoTextureSupported = true;\n }\n }\n // Copy video through the current working canvas if video texture is not supported\n if (!this._videoTextureSupported) {\n if (!texture._workingCanvas) {\n texture._workingCanvas = document.createElement(\"canvas\");\n var context = texture._workingCanvas.getContext(\"2d\");\n if (!context) {\n throw new Error(\"Unable to get 2d context\");\n }\n texture._workingContext = context;\n texture._workingCanvas.width = texture.width;\n texture._workingCanvas.height = texture.height;\n }\n texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);\n }\n else {\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);\n }\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n if (!wasPreviouslyBound) {\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n }\n // this.resetTextureCache();\n texture.isReady = true;\n }\n catch (ex) {\n // Something unexpected\n // Let's disable the texture\n texture._isDisabled = true;\n }\n };\n /**\n * Updates a depth texture Comparison Mode and Function.\n * If the comparison Function is equal to 0, the mode will be set to none.\n * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.\n * @param texture The texture to set the comparison function for\n * @param comparisonFunction The comparison function to set, 0 if no comparison required\n */\n Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {\n if (this.webGLVersion === 1) {\n BABYLON.Tools.Error(\"WebGL 1 does not support texture comparison.\");\n return;\n }\n var gl = this._gl;\n if (texture.isCube) {\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);\n if (comparisonFunction === 0) {\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);\n }\n else {\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n }\n else {\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n if (comparisonFunction === 0) {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);\n }\n else {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n }\n texture._comparisonFunction = comparisonFunction;\n };\n Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {\n var width = size.width || size;\n var height = size.height || size;\n internalTexture.baseWidth = width;\n internalTexture.baseHeight = height;\n internalTexture.width = width;\n internalTexture.height = height;\n internalTexture.isReady = true;\n internalTexture.samples = 1;\n internalTexture.generateMipMaps = false;\n internalTexture._generateDepthBuffer = true;\n internalTexture._generateStencilBuffer = generateStencil;\n internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;\n internalTexture._comparisonFunction = comparisonFunction;\n var gl = this._gl;\n var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;\n var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);\n gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);\n gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);\n gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n if (comparisonFunction === 0) {\n gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);\n gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);\n }\n else {\n gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);\n gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);\n }\n };\n /**\n * Creates a depth stencil texture.\n * This is only available in WebGL 2 or with the depth texture extension available.\n * @param size The size of face edge in the texture.\n * @param options The options defining the texture.\n * @returns The texture\n */\n Engine.prototype.createDepthStencilTexture = function (size, options) {\n if (options.isCube) {\n var width = size.width || size;\n return this._createDepthStencilCubeTexture(width, options);\n }\n else {\n return this._createDepthStencilTexture(size, options);\n }\n };\n /**\n * Creates a depth stencil texture.\n * This is only available in WebGL 2 or with the depth texture extension available.\n * @param size The size of face edge in the texture.\n * @param options The options defining the texture.\n * @returns The texture\n */\n Engine.prototype._createDepthStencilTexture = function (size, options) {\n var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);\n if (!this._caps.depthTextureExtension) {\n BABYLON.Tools.Error(\"Depth texture is not supported by your browser or hardware.\");\n return internalTexture;\n }\n var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);\n var gl = this._gl;\n this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);\n this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);\n if (this.webGLVersion > 1) {\n if (internalOptions.generateStencil) {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);\n }\n else {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);\n }\n }\n else {\n if (internalOptions.generateStencil) {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);\n }\n else {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);\n }\n }\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n return internalTexture;\n };\n /**\n * Creates a depth stencil cube texture.\n * This is only available in WebGL 2.\n * @param size The size of face edge in the cube texture.\n * @param options The options defining the cube texture.\n * @returns The cube texture\n */\n Engine.prototype._createDepthStencilCubeTexture = function (size, options) {\n var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);\n internalTexture.isCube = true;\n if (this.webGLVersion === 1) {\n BABYLON.Tools.Error(\"Depth cube texture is not supported by WebGL 1.\");\n return internalTexture;\n }\n var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);\n var gl = this._gl;\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);\n this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);\n // Create the depth/stencil buffer\n for (var face = 0; face < 6; face++) {\n if (internalOptions.generateStencil) {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);\n }\n else {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);\n }\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n return internalTexture;\n };\n /**\n * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.\n * @param renderTarget The render target to set the frame buffer for\n */\n Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {\n // Create the framebuffer\n var internalTexture = renderTarget.getInternalTexture();\n if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {\n return;\n }\n var gl = this._gl;\n var depthStencilTexture = renderTarget.depthStencilTexture;\n this.bindUnboundFramebuffer(internalTexture._framebuffer);\n if (depthStencilTexture.isCube) {\n if (depthStencilTexture._generateStencilBuffer) {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);\n }\n else {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);\n }\n }\n else {\n if (depthStencilTexture._generateStencilBuffer) {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);\n }\n else {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);\n }\n }\n this.bindUnboundFramebuffer(null);\n };\n /**\n * Creates a new render target texture\n * @param size defines the size of the texture\n * @param options defines the options used to create the texture\n * @returns a new render target texture stored in an InternalTexture\n */\n Engine.prototype.createRenderTargetTexture = function (size, options) {\n var fullOptions = new RenderTargetCreationOptions();\n if (options !== undefined && typeof options === \"object\") {\n fullOptions.generateMipMaps = options.generateMipMaps;\n fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;\n fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;\n fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;\n fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;\n }\n else {\n fullOptions.generateMipMaps = options;\n fullOptions.generateDepthBuffer = true;\n fullOptions.generateStencilBuffer = false;\n fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;\n fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;\n fullOptions.format = Engine.TEXTUREFORMAT_RGBA;\n }\n if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n }\n else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n }\n var gl = this._gl;\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);\n this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);\n var width = size.width || size;\n var height = size.height || size;\n var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);\n if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {\n fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;\n BABYLON.Tools.Warn(\"Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type\");\n }\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);\n // Create the framebuffer\n var currentFrameBuffer = this._currentFramebuffer;\n var framebuffer = gl.createFramebuffer();\n this.bindUnboundFramebuffer(framebuffer);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);\n texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);\n if (fullOptions.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n // Unbind\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n gl.bindRenderbuffer(gl.RENDERBUFFER, null);\n this.bindUnboundFramebuffer(currentFrameBuffer);\n texture._framebuffer = framebuffer;\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n texture.samples = 1;\n texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n texture._generateDepthBuffer = fullOptions.generateDepthBuffer;\n texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;\n // this.resetTextureCache();\n this._internalTexturesCache.push(texture);\n return texture;\n };\n /**\n * Create a multi render target texture\n * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target\n * @param size defines the size of the texture\n * @param options defines the creation options\n * @returns the cube texture as an InternalTexture\n */\n Engine.prototype.createMultipleRenderTarget = function (size, options) {\n var generateMipMaps = false;\n var generateDepthBuffer = true;\n var generateStencilBuffer = false;\n var generateDepthTexture = false;\n var textureCount = 1;\n var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;\n var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;\n var types = new Array();\n var samplingModes = new Array();\n if (options !== undefined) {\n generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;\n generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;\n generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;\n textureCount = options.textureCount || 1;\n if (options.types) {\n types = options.types;\n }\n if (options.samplingModes) {\n samplingModes = options.samplingModes;\n }\n }\n var gl = this._gl;\n // Create the framebuffer\n var framebuffer = gl.createFramebuffer();\n this.bindUnboundFramebuffer(framebuffer);\n var width = size.width || size;\n var height = size.height || size;\n var textures = [];\n var attachments = [];\n var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);\n for (var i = 0; i < textureCount; i++) {\n var samplingMode = samplingModes[i] || defaultSamplingMode;\n var type = types[i] || defaultType;\n if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n }\n else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n }\n var filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {\n type = Engine.TEXTURETYPE_UNSIGNED_INT;\n BABYLON.Tools.Warn(\"Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type\");\n }\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);\n var attachment = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n textures.push(texture);\n attachments.push(attachment);\n gl.activeTexture(gl[\"TEXTURE\" + i]);\n gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);\n gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);\n if (generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n // Unbind\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n texture._framebuffer = framebuffer;\n texture._depthStencilBuffer = depthStencilBuffer;\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n texture.samples = 1;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.type = type;\n texture._generateDepthBuffer = generateDepthBuffer;\n texture._generateStencilBuffer = generateStencilBuffer;\n texture._attachments = attachments;\n this._internalTexturesCache.push(texture);\n }\n if (generateDepthTexture && this._caps.depthTextureExtension) {\n // Depth texture\n var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);\n depthTexture._framebuffer = framebuffer;\n depthTexture.baseWidth = width;\n depthTexture.baseHeight = height;\n depthTexture.width = width;\n depthTexture.height = height;\n depthTexture.isReady = true;\n depthTexture.samples = 1;\n depthTexture.generateMipMaps = generateMipMaps;\n depthTexture.samplingMode = gl.NEAREST;\n depthTexture._generateDepthBuffer = generateDepthBuffer;\n depthTexture._generateStencilBuffer = generateStencilBuffer;\n textures.push(depthTexture);\n this._internalTexturesCache.push(depthTexture);\n }\n gl.drawBuffers(attachments);\n gl.bindRenderbuffer(gl.RENDERBUFFER, null);\n this.bindUnboundFramebuffer(null);\n this.resetTextureCache();\n return textures;\n };\n Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {\n if (samples === void 0) { samples = 1; }\n var depthStencilBuffer = null;\n var gl = this._gl;\n // Create the depth/stencil buffer\n if (generateStencilBuffer) {\n depthStencilBuffer = gl.createRenderbuffer();\n gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);\n if (samples > 1) {\n gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);\n }\n else {\n gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);\n }\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);\n }\n else if (generateDepthBuffer) {\n depthStencilBuffer = gl.createRenderbuffer();\n gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);\n if (samples > 1) {\n gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);\n }\n else {\n gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);\n }\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);\n }\n return depthStencilBuffer;\n };\n /**\n * Updates the sample count of a render target texture\n * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets\n * @param texture defines the texture to update\n * @param samples defines the sample count to set\n * @returns the effective sample count (could be 0 if multisample render targets are not supported)\n */\n Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {\n if (this.webGLVersion < 2 || !texture) {\n return 1;\n }\n if (texture.samples === samples) {\n return samples;\n }\n var gl = this._gl;\n samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));\n // Dispose previous render buffers\n if (texture._depthStencilBuffer) {\n gl.deleteRenderbuffer(texture._depthStencilBuffer);\n texture._depthStencilBuffer = null;\n }\n if (texture._MSAAFramebuffer) {\n gl.deleteFramebuffer(texture._MSAAFramebuffer);\n texture._MSAAFramebuffer = null;\n }\n if (texture._MSAARenderBuffer) {\n gl.deleteRenderbuffer(texture._MSAARenderBuffer);\n texture._MSAARenderBuffer = null;\n }\n if (samples > 1) {\n var framebuffer = gl.createFramebuffer();\n if (!framebuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n texture._MSAAFramebuffer = framebuffer;\n this.bindUnboundFramebuffer(texture._MSAAFramebuffer);\n var colorRenderbuffer = gl.createRenderbuffer();\n if (!colorRenderbuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);\n gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);\n texture._MSAARenderBuffer = colorRenderbuffer;\n }\n else {\n this.bindUnboundFramebuffer(texture._framebuffer);\n }\n texture.samples = samples;\n texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);\n gl.bindRenderbuffer(gl.RENDERBUFFER, null);\n this.bindUnboundFramebuffer(null);\n return samples;\n };\n /**\n * Update the sample count for a given multiple render target texture\n * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets\n * @param textures defines the textures to update\n * @param samples defines the sample count to set\n * @returns the effective sample count (could be 0 if multisample render targets are not supported)\n */\n Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {\n if (this.webGLVersion < 2 || !textures || textures.length == 0) {\n return 1;\n }\n if (textures[0].samples === samples) {\n return samples;\n }\n var gl = this._gl;\n samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));\n // Dispose previous render buffers\n if (textures[0]._depthStencilBuffer) {\n gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);\n textures[0]._depthStencilBuffer = null;\n }\n if (textures[0]._MSAAFramebuffer) {\n gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);\n textures[0]._MSAAFramebuffer = null;\n }\n for (var i = 0; i < textures.length; i++) {\n if (textures[i]._MSAARenderBuffer) {\n gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);\n textures[i]._MSAARenderBuffer = null;\n }\n }\n if (samples > 1) {\n var framebuffer = gl.createFramebuffer();\n if (!framebuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n this.bindUnboundFramebuffer(framebuffer);\n var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);\n var attachments = [];\n for (var i = 0; i < textures.length; i++) {\n var texture = textures[i];\n var attachment = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n var colorRenderbuffer = gl.createRenderbuffer();\n if (!colorRenderbuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);\n gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);\n texture._MSAAFramebuffer = framebuffer;\n texture._MSAARenderBuffer = colorRenderbuffer;\n texture.samples = samples;\n texture._depthStencilBuffer = depthStencilBuffer;\n gl.bindRenderbuffer(gl.RENDERBUFFER, null);\n attachments.push(attachment);\n }\n gl.drawBuffers(attachments);\n }\n else {\n this.bindUnboundFramebuffer(textures[0]._framebuffer);\n }\n this.bindUnboundFramebuffer(null);\n return samples;\n };\n /** @hidden */\n Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n var gl = this._gl;\n var target = gl.TEXTURE_2D;\n if (texture.isCube) {\n target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;\n }\n this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);\n };\n /** @hidden */\n Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n var gl = this._gl;\n var textureType = this._getWebGLTextureType(texture.type);\n var format = this._getInternalFormat(texture.format);\n var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);\n this._unpackFlipY(texture.invertY);\n var target = gl.TEXTURE_2D;\n if (texture.isCube) {\n target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;\n }\n var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));\n var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));\n var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));\n var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));\n gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);\n };\n /** @hidden */\n Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n var gl = this._gl;\n var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;\n this._bindTextureDirectly(bindTarget, texture, true);\n this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);\n this._bindTextureDirectly(bindTarget, null, true);\n };\n /** @hidden */\n Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n var gl = this._gl;\n var textureType = this._getWebGLTextureType(texture.type);\n var format = this._getInternalFormat(texture.format);\n var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);\n var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;\n this._bindTextureDirectly(bindTarget, texture, true);\n this._unpackFlipY(texture.invertY);\n var target = gl.TEXTURE_2D;\n if (texture.isCube) {\n target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;\n }\n gl.texImage2D(target, lod, internalFormat, format, textureType, image);\n this._bindTextureDirectly(bindTarget, null, true);\n };\n /**\n * Creates a new render target cube texture\n * @param size defines the size of the texture\n * @param options defines the options used to create the texture\n * @returns a new render target cube texture stored in an InternalTexture\n */\n Engine.prototype.createRenderTargetCubeTexture = function (size, options) {\n var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;\n if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n }\n else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n }\n var gl = this._gl;\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);\n if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {\n fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;\n BABYLON.Tools.Warn(\"Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type\");\n }\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n for (var face = 0; face < 6; face++) {\n gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);\n }\n // Create the framebuffer\n var framebuffer = gl.createFramebuffer();\n this.bindUnboundFramebuffer(framebuffer);\n texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);\n // MipMaps\n if (fullOptions.generateMipMaps) {\n gl.generateMipmap(gl.TEXTURE_CUBE_MAP);\n }\n // Unbind\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n gl.bindRenderbuffer(gl.RENDERBUFFER, null);\n this.bindUnboundFramebuffer(null);\n texture._framebuffer = framebuffer;\n texture.width = size;\n texture.height = size;\n texture.isReady = true;\n texture.isCube = true;\n texture.samples = 1;\n texture.generateMipMaps = fullOptions.generateMipMaps;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n texture._generateDepthBuffer = fullOptions.generateDepthBuffer;\n texture._generateStencilBuffer = fullOptions.generateStencilBuffer;\n this._internalTexturesCache.push(texture);\n return texture;\n };\n /**\n * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)\n * @param rootUrl defines the url where the file to load is located\n * @param scene defines the current scene\n * @param lodScale defines scale to apply to the mip map selection\n * @param lodOffset defines offset to apply to the mip map selection\n * @param onLoad defines an optional callback raised when the texture is loaded\n * @param onError defines an optional callback raised if there is an issue to load the texture\n * @param format defines the format of the data\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture\n * @returns the cube texture as an InternalTexture\n */\n Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {\n var _this = this;\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (forcedExtension === void 0) { forcedExtension = null; }\n if (createPolynomials === void 0) { createPolynomials = true; }\n var callback = function (loadData) {\n if (!loadData) {\n if (onLoad) {\n onLoad(null);\n }\n return;\n }\n var texture = loadData.texture;\n if (!createPolynomials) {\n texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();\n }\n else if (loadData.info.sphericalPolynomial) {\n texture._sphericalPolynomial = loadData.info.sphericalPolynomial;\n }\n texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;\n if (_this._caps.textureLOD) {\n // Do not add extra process if texture lod is supported.\n if (onLoad) {\n onLoad(texture);\n }\n return;\n }\n var mipSlices = 3;\n var gl = _this._gl;\n var width = loadData.width;\n if (!width) {\n return;\n }\n var textures = [];\n for (var i = 0; i < mipSlices; i++) {\n //compute LOD from even spacing in smoothness (matching shader calculation)\n var smoothness = i / (mipSlices - 1);\n var roughness = 1 - smoothness;\n var minLODIndex = lodOffset; // roughness = 0\n var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1\n var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;\n var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));\n var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);\n glTextureFromLod.type = texture.type;\n glTextureFromLod.format = texture.format;\n glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));\n glTextureFromLod.height = glTextureFromLod.width;\n glTextureFromLod.isCube = true;\n _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n if (loadData.isDDS) {\n var info = loadData.info;\n var data = loadData.data;\n _this._unpackFlipY(info.isCompressed);\n BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);\n }\n else {\n BABYLON.Tools.Warn(\"DDS is the only prefiltered cube map supported so far.\");\n }\n _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n // Wrap in a base texture for easy binding.\n var lodTexture = new BABYLON.BaseTexture(scene);\n lodTexture.isCube = true;\n lodTexture._texture = glTextureFromLod;\n glTextureFromLod.isReady = true;\n textures.push(lodTexture);\n }\n texture._lodTextureHigh = textures[2];\n texture._lodTextureMid = textures[1];\n texture._lodTextureLow = textures[0];\n if (onLoad) {\n onLoad(texture);\n }\n };\n return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);\n };\n /**\n * Creates a cube texture\n * @param rootUrl defines the url where the files to load is located\n * @param scene defines the current scene\n * @param files defines the list of files to load (1 per face)\n * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)\n * @param onLoad defines an optional callback raised when the texture is loaded\n * @param onError defines an optional callback raised if there is an issue to load the texture\n * @param format defines the format of the data\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param createPolynomials if a polynomial sphere should be created for the cube texture\n * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness\n * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness\n * @param fallback defines texture to use while falling back when (compressed) texture file not found.\n * @returns the cube texture as an InternalTexture\n */\n Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {\n var _this = this;\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (forcedExtension === void 0) { forcedExtension = null; }\n if (createPolynomials === void 0) { createPolynomials = false; }\n if (lodScale === void 0) { lodScale = 0; }\n if (lodOffset === void 0) { lodOffset = 0; }\n if (fallback === void 0) { fallback = null; }\n var gl = this._gl;\n var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);\n texture.isCube = true;\n texture.url = rootUrl;\n texture.generateMipMaps = !noMipmap;\n texture._lodGenerationScale = lodScale;\n texture._lodGenerationOffset = lodOffset;\n if (!this._doNotHandleContextLost) {\n texture._extension = forcedExtension;\n texture._files = files;\n }\n var lastDot = rootUrl.lastIndexOf('.');\n var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : \"\");\n var loader = null;\n for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {\n var availableLoader = _a[_i];\n if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {\n loader = availableLoader;\n break;\n }\n }\n var onInternalError = function (request, exception) {\n if (loader) {\n var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);\n if (fallbackUrl) {\n _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);\n }\n }\n if (onError && request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n };\n if (loader) {\n rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);\n var onloaddata = function (data) {\n _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);\n };\n if (files && files.length === 6) {\n if (loader.supportCascades) {\n this._cascadeLoadFiles(scene, onloaddata, files, onError);\n }\n else if (onError) {\n onError(\"Textures type does not support cascades.\");\n }\n }\n else {\n this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);\n }\n }\n else {\n if (!files) {\n throw new Error(\"Cannot load cubemap because files were not defined\");\n }\n this._cascadeLoadImgs(rootUrl, scene, function (imgs) {\n var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;\n var height = width;\n _this._prepareWorkingCanvas();\n if (!_this._workingCanvas || !_this._workingContext) {\n return;\n }\n _this._workingCanvas.width = width;\n _this._workingCanvas.height = height;\n var faces = [\n gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z\n ];\n _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n _this._unpackFlipY(false);\n var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;\n for (var index = 0; index < faces.length; index++) {\n _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);\n gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);\n }\n if (!noMipmap) {\n gl.generateMipmap(gl.TEXTURE_CUBE_MAP);\n }\n _this._setCubeMapTextureParams(!noMipmap);\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n if (format) {\n texture.format = format;\n }\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n }, files, onError);\n }\n this._internalTexturesCache.push(texture);\n return texture;\n };\n /**\n * @hidden\n */\n Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {\n var gl = this._gl;\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n // this.resetTextureCache();\n };\n /**\n * Update a raw cube texture\n * @param texture defines the texture to udpdate\n * @param data defines the data to store\n * @param format defines the data format\n * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)\n * @param invertY defines if data must be stored with Y axis inverted\n * @param compression defines the compression used (null by default)\n * @param level defines which level of the texture to update\n */\n Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {\n if (compression === void 0) { compression = null; }\n if (level === void 0) { level = 0; }\n texture._bufferViewArray = data;\n texture.format = format;\n texture.type = type;\n texture.invertY = invertY;\n texture._compression = compression;\n var gl = this._gl;\n var textureType = this._getWebGLTextureType(type);\n var internalFormat = this._getInternalFormat(format);\n var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);\n var needConversion = false;\n if (internalFormat === gl.RGB) {\n internalFormat = gl.RGBA;\n needConversion = true;\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));\n if (texture.width % 4 !== 0) {\n gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);\n }\n // Data are known to be in +X +Y +Z -X -Y -Z\n for (var faceIndex = 0; faceIndex < 6; faceIndex++) {\n var faceData = data[faceIndex];\n if (compression) {\n gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);\n }\n else {\n if (needConversion) {\n faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);\n }\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);\n }\n }\n var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));\n if (isPot && texture.generateMipMaps && level === 0) {\n this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n // this.resetTextureCache();\n texture.isReady = true;\n };\n /**\n * Creates a new raw cube texture\n * @param data defines the array of data to use to create each face\n * @param size defines the size of the textures\n * @param format defines the format of the data\n * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)\n * @param generateMipMaps defines if the engine should generate the mip levels\n * @param invertY defines if data must be stored with Y axis inverted\n * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)\n * @param compression defines the compression used (null by default)\n * @returns the cube texture as an InternalTexture\n */\n Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {\n if (compression === void 0) { compression = null; }\n var gl = this._gl;\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);\n texture.isCube = true;\n texture.format = format;\n texture.type = type;\n if (!this._doNotHandleContextLost) {\n texture._bufferViewArray = data;\n }\n var textureType = this._getWebGLTextureType(type);\n var internalFormat = this._getInternalFormat(format);\n if (internalFormat === gl.RGB) {\n internalFormat = gl.RGBA;\n }\n // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable\n if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {\n generateMipMaps = false;\n samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n BABYLON.Tools.Warn(\"Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.\");\n }\n else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {\n generateMipMaps = false;\n samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n BABYLON.Tools.Warn(\"Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.\");\n }\n else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {\n generateMipMaps = false;\n BABYLON.Tools.Warn(\"Render to float textures is not supported. Mipmap generation forced to false.\");\n }\n else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {\n generateMipMaps = false;\n BABYLON.Tools.Warn(\"Render to half float textures is not supported. Mipmap generation forced to false.\");\n }\n var width = size;\n var height = width;\n texture.width = width;\n texture.height = height;\n // Double check on POT to generate Mips.\n var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));\n if (!isPot) {\n generateMipMaps = false;\n }\n // Upload data if needed. The texture won't be ready until then.\n if (data) {\n this.updateRawCubeTexture(texture, data, format, type, invertY, compression);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);\n // Filters\n if (data && generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);\n }\n var filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n texture.generateMipMaps = generateMipMaps;\n return texture;\n };\n /**\n * Creates a new raw cube texture from a specified url\n * @param url defines the url where the data is located\n * @param scene defines the current scene\n * @param size defines the size of the textures\n * @param format defines the format of the data\n * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)\n * @param noMipmap defines if the engine should avoid generating the mip levels\n * @param callback defines a callback used to extract texture data from loaded data\n * @param mipmapGenerator defines to provide an optional tool to generate mip levels\n * @param onLoad defines a callback called when texture is loaded\n * @param onError defines a callback called if there is an error\n * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)\n * @param invertY defines if data must be stored with Y axis inverted\n * @returns the cube texture as an InternalTexture\n */\n Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {\n var _this = this;\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }\n if (invertY === void 0) { invertY = false; }\n var gl = this._gl;\n var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);\n scene._addPendingData(texture);\n texture.url = url;\n this._internalTexturesCache.push(texture);\n var onerror = function (request, exception) {\n scene._removePendingData(texture);\n if (onError && request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n };\n var internalCallback = function (data) {\n var width = texture.width;\n var faceDataArrays = callback(data);\n if (!faceDataArrays) {\n return;\n }\n if (mipmapGenerator) {\n var textureType = _this._getWebGLTextureType(type);\n var internalFormat = _this._getInternalFormat(format);\n var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);\n var needConversion = false;\n if (internalFormat === gl.RGB) {\n internalFormat = gl.RGBA;\n needConversion = true;\n }\n _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n _this._unpackFlipY(false);\n var mipData = mipmapGenerator(faceDataArrays);\n for (var level = 0; level < mipData.length; level++) {\n var mipSize = width >> level;\n for (var faceIndex = 0; faceIndex < 6; faceIndex++) {\n var mipFaceData = mipData[level][faceIndex];\n if (needConversion) {\n mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);\n }\n gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);\n }\n }\n _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n }\n else {\n _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);\n }\n texture.isReady = true;\n // this.resetTextureCache();\n scene._removePendingData(texture);\n if (onLoad) {\n onLoad();\n }\n };\n this._loadFile(url, function (data) {\n internalCallback(data);\n }, undefined, scene.database, true, onerror);\n return texture;\n };\n ;\n /**\n * Update a raw 3D texture\n * @param texture defines the texture to update\n * @param data defines the data to store\n * @param format defines the data format\n * @param invertY defines if data must be stored with Y axis inverted\n * @param compression defines the used compression (can be null)\n * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)\n */\n Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {\n if (compression === void 0) { compression = null; }\n if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }\n var internalType = this._getWebGLTextureType(textureType);\n var internalFormat = this._getInternalFormat(format);\n var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);\n this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);\n this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n texture.format = format;\n texture.invertY = invertY;\n texture._compression = compression;\n }\n if (texture.width % 4 !== 0) {\n this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);\n }\n if (compression && data) {\n this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);\n }\n else {\n this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);\n }\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_3D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_3D, null);\n // this.resetTextureCache();\n texture.isReady = true;\n };\n /**\n * Creates a new raw 3D texture\n * @param data defines the data used to create the texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param depth defines the depth of the texture\n * @param format defines the format of the texture\n * @param generateMipMaps defines if the engine must generate mip levels\n * @param invertY defines if data must be stored with Y axis inverted\n * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)\n * @param compression defines the compressed used (can be null)\n * @param textureType defines the compressed used (can be null)\n * @returns a new raw 3D texture (stored in an InternalTexture)\n */\n Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {\n if (compression === void 0) { compression = null; }\n if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.baseDepth = depth;\n texture.width = width;\n texture.height = height;\n texture.depth = depth;\n texture.format = format;\n texture.type = textureType;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.is3D = true;\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);\n this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);\n // Filters\n var filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);\n this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);\n if (generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_3D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_3D, null);\n this._internalTexturesCache.push(texture);\n return texture;\n };\n Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {\n var gl = this._gl;\n if (!gl) {\n return;\n }\n var filters = this._getSamplingParameters(samplingMode, !noMipmap);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);\n if (!noMipmap && !isCompressed) {\n gl.generateMipmap(gl.TEXTURE_2D);\n }\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n // this.resetTextureCache();\n if (scene) {\n scene._removePendingData(texture);\n }\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n };\n Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {\n var _this = this;\n if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }\n var maxTextureSize = this.getCaps().maxTextureSize;\n var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);\n var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);\n var gl = this._gl;\n if (!gl) {\n return;\n }\n if (!texture._webGLTexture) {\n // this.resetTextureCache();\n if (scene) {\n scene._removePendingData(texture);\n }\n return;\n }\n this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);\n this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = potWidth;\n texture.height = potHeight;\n texture.isReady = true;\n if (processFunction(potWidth, potHeight, function () {\n _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);\n })) {\n // Returning as texture needs extra async steps\n return;\n }\n this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);\n };\n Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {\n // Create new RGBA data container.\n var rgbaData;\n if (textureType === Engine.TEXTURETYPE_FLOAT) {\n rgbaData = new Float32Array(width * height * 4);\n }\n else {\n rgbaData = new Uint32Array(width * height * 4);\n }\n // Convert each pixel.\n for (var x = 0; x < width; x++) {\n for (var y = 0; y < height; y++) {\n var index = (y * width + x) * 3;\n var newIndex = (y * width + x) * 4;\n // Map Old Value to new value.\n rgbaData[newIndex + 0] = rgbData[index + 0];\n rgbaData[newIndex + 1] = rgbData[index + 1];\n rgbaData[newIndex + 2] = rgbData[index + 2];\n // Add fully opaque alpha channel.\n rgbaData[newIndex + 3] = 1;\n }\n }\n return rgbaData;\n };\n /** @hidden */\n Engine.prototype._releaseFramebufferObjects = function (texture) {\n var gl = this._gl;\n if (texture._framebuffer) {\n gl.deleteFramebuffer(texture._framebuffer);\n texture._framebuffer = null;\n }\n if (texture._depthStencilBuffer) {\n gl.deleteRenderbuffer(texture._depthStencilBuffer);\n texture._depthStencilBuffer = null;\n }\n if (texture._MSAAFramebuffer) {\n gl.deleteFramebuffer(texture._MSAAFramebuffer);\n texture._MSAAFramebuffer = null;\n }\n if (texture._MSAARenderBuffer) {\n gl.deleteRenderbuffer(texture._MSAARenderBuffer);\n texture._MSAARenderBuffer = null;\n }\n };\n /** @hidden */\n Engine.prototype._releaseTexture = function (texture) {\n var gl = this._gl;\n this._releaseFramebufferObjects(texture);\n gl.deleteTexture(texture._webGLTexture);\n // Unbind channels\n this.unbindAllTextures();\n var index = this._internalTexturesCache.indexOf(texture);\n if (index !== -1) {\n this._internalTexturesCache.splice(index, 1);\n }\n // Integrated fixed lod samplers.\n if (texture._lodTextureHigh) {\n texture._lodTextureHigh.dispose();\n }\n if (texture._lodTextureMid) {\n texture._lodTextureMid.dispose();\n }\n if (texture._lodTextureLow) {\n texture._lodTextureLow.dispose();\n }\n // Set output texture of post process to null if the texture has been released/disposed\n this.scenes.forEach(function (scene) {\n scene.postProcesses.forEach(function (postProcess) {\n if (postProcess._outputTexture == texture) {\n postProcess._outputTexture = null;\n }\n });\n scene.cameras.forEach(function (camera) {\n camera._postProcesses.forEach(function (postProcess) {\n if (postProcess) {\n if (postProcess._outputTexture == texture) {\n postProcess._outputTexture = null;\n }\n }\n });\n });\n });\n };\n Engine.prototype.setProgram = function (program) {\n if (this._currentProgram !== program) {\n this._gl.useProgram(program);\n this._currentProgram = program;\n }\n };\n /**\n * Binds an effect to the webGL context\n * @param effect defines the effect to bind\n */\n Engine.prototype.bindSamplers = function (effect) {\n this.setProgram(effect.getProgram());\n var samplers = effect.getSamplers();\n for (var index = 0; index < samplers.length; index++) {\n var uniform = effect.getUniform(samplers[index]);\n if (uniform) {\n this._boundUniforms[index] = uniform;\n }\n }\n this._currentEffect = null;\n };\n Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {\n if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {\n return;\n }\n // Remove\n this._linkTrackers(internalTexture.previous, internalTexture.next);\n // Bind last to it\n this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);\n // Bind to dummy\n this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);\n };\n Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {\n if (!internalTexture) {\n return -1;\n }\n internalTexture._initialSlot = channel;\n if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel\n if (channel !== internalTexture._designatedSlot) {\n this._textureCollisions.addCount(1, false);\n }\n }\n else {\n if (channel !== internalTexture._designatedSlot) {\n if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot\n return internalTexture._designatedSlot;\n }\n else {\n // No slot for this texture, let's pick a new one (if we find a free slot)\n if (this._nextFreeTextureSlots.length) {\n return this._nextFreeTextureSlots[0];\n }\n // We need to recycle the oldest bound texture, sorry.\n this._textureCollisions.addCount(1, false);\n return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);\n }\n }\n }\n return channel;\n };\n Engine.prototype._linkTrackers = function (previous, next) {\n previous.next = next;\n next.previous = previous;\n };\n Engine.prototype._removeDesignatedSlot = function (internalTexture) {\n var currentSlot = internalTexture._designatedSlot;\n if (currentSlot === -1) {\n return -1;\n }\n internalTexture._designatedSlot = -1;\n if (this.disableTextureBindingOptimization) {\n return -1;\n }\n // Remove from bound list\n this._linkTrackers(internalTexture.previous, internalTexture.next);\n // Free the slot\n this._boundTexturesCache[currentSlot] = null;\n this._nextFreeTextureSlots.push(currentSlot);\n return currentSlot;\n };\n Engine.prototype._activateCurrentTexture = function () {\n if (this._currentTextureChannel !== this._activeChannel) {\n this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);\n this._currentTextureChannel = this._activeChannel;\n }\n };\n /** @hidden */\n Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {\n if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }\n if (force === void 0) { force = false; }\n var wasPreviouslyBound = false;\n if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {\n this._activeChannel = texture._designatedSlot;\n }\n var currentTextureBound = this._boundTexturesCache[this._activeChannel];\n var isTextureForRendering = texture && texture._initialSlot > -1;\n if (currentTextureBound !== texture || force) {\n if (currentTextureBound) {\n this._removeDesignatedSlot(currentTextureBound);\n }\n this._activateCurrentTexture();\n this._gl.bindTexture(target, texture ? texture._webGLTexture : null);\n this._boundTexturesCache[this._activeChannel] = texture;\n if (texture) {\n if (!this.disableTextureBindingOptimization) {\n var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);\n if (slotIndex > -1) {\n this._nextFreeTextureSlots.splice(slotIndex, 1);\n }\n this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);\n this._linkTrackers(texture, this._lastBoundInternalTextureTracker);\n }\n texture._designatedSlot = this._activeChannel;\n }\n }\n else if (forTextureDataUpdate) {\n wasPreviouslyBound = true;\n this._activateCurrentTexture();\n }\n if (isTextureForRendering && !forTextureDataUpdate) {\n this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);\n }\n return wasPreviouslyBound;\n };\n /** @hidden */\n Engine.prototype._bindTexture = function (channel, texture) {\n if (channel < 0) {\n return;\n }\n if (texture) {\n channel = this._getCorrectTextureChannel(channel, texture);\n }\n this._activeChannel = channel;\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);\n };\n /**\n * Sets a texture to the webGL context from a postprocess\n * @param channel defines the channel to use\n * @param postProcess defines the source postprocess\n */\n Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {\n this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);\n };\n /**\n * Binds the output of the passed in post process to the texture channel specified\n * @param channel The channel the texture should be bound to\n * @param postProcess The post process which's output should be bound\n */\n Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {\n this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);\n };\n /**\n * Unbind all textures from the webGL context\n */\n Engine.prototype.unbindAllTextures = function () {\n for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {\n this._activeChannel = channel;\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n if (this.webGLVersion > 1) {\n this._bindTextureDirectly(this._gl.TEXTURE_3D, null);\n }\n }\n };\n /**\n * Sets a texture to the according uniform.\n * @param channel The texture channel\n * @param uniform The uniform to set\n * @param texture The texture to apply\n */\n Engine.prototype.setTexture = function (channel, uniform, texture) {\n if (channel < 0) {\n return;\n }\n if (uniform) {\n this._boundUniforms[channel] = uniform;\n }\n this._setTexture(channel, texture);\n };\n /**\n * Sets a depth stencil texture from a render target to the according uniform.\n * @param channel The texture channel\n * @param uniform The uniform to set\n * @param texture The render target texture containing the depth stencil texture to apply\n */\n Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {\n if (channel < 0) {\n return;\n }\n if (uniform) {\n this._boundUniforms[channel] = uniform;\n }\n if (!texture || !texture.depthStencilTexture) {\n this._setTexture(channel, null);\n }\n else {\n this._setTexture(channel, texture, false, true);\n }\n };\n Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {\n var uniform = this._boundUniforms[sourceSlot];\n if (uniform._currentState === destination) {\n return;\n }\n this._gl.uniform1i(uniform, destination);\n uniform._currentState = destination;\n };\n Engine.prototype._getTextureWrapMode = function (mode) {\n switch (mode) {\n case Engine.TEXTURE_WRAP_ADDRESSMODE:\n return this._gl.REPEAT;\n case Engine.TEXTURE_CLAMP_ADDRESSMODE:\n return this._gl.CLAMP_TO_EDGE;\n case Engine.TEXTURE_MIRROR_ADDRESSMODE:\n return this._gl.MIRRORED_REPEAT;\n }\n return this._gl.REPEAT;\n };\n Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {\n if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }\n if (depthStencilTexture === void 0) { depthStencilTexture = false; }\n // Not ready?\n if (!texture) {\n if (this._boundTexturesCache[channel] != null) {\n this._activeChannel = channel;\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n if (this.webGLVersion > 1) {\n this._bindTextureDirectly(this._gl.TEXTURE_3D, null);\n }\n }\n return false;\n }\n // Video\n if (texture.video) {\n this._activeChannel = channel;\n texture.update();\n }\n else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading\n texture.delayLoad();\n return false;\n }\n var internalTexture;\n if (depthStencilTexture) {\n internalTexture = texture.depthStencilTexture;\n }\n else if (texture.isReady()) {\n internalTexture = texture.getInternalTexture();\n }\n else if (texture.isCube) {\n internalTexture = this.emptyCubeTexture;\n }\n else if (texture.is3D) {\n internalTexture = this.emptyTexture3D;\n }\n else {\n internalTexture = this.emptyTexture;\n }\n if (!isPartOfTextureArray) {\n channel = this._getCorrectTextureChannel(channel, internalTexture);\n }\n var needToBind = true;\n if (this._boundTexturesCache[channel] === internalTexture) {\n this._moveBoundTextureOnTop(internalTexture);\n if (!isPartOfTextureArray) {\n this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);\n }\n needToBind = false;\n }\n this._activeChannel = channel;\n if (internalTexture && internalTexture.is3D) {\n if (needToBind) {\n this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);\n }\n if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {\n internalTexture._cachedWrapU = texture.wrapU;\n this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);\n }\n if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {\n internalTexture._cachedWrapV = texture.wrapV;\n this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);\n }\n if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {\n internalTexture._cachedWrapR = texture.wrapR;\n this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);\n }\n this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);\n }\n else if (internalTexture && internalTexture.isCube) {\n if (needToBind) {\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);\n }\n if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {\n internalTexture._cachedCoordinatesMode = texture.coordinatesMode;\n // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.\n var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;\n this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);\n this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);\n }\n this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);\n }\n else {\n if (needToBind) {\n this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);\n }\n if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {\n internalTexture._cachedWrapU = texture.wrapU;\n this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);\n }\n if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {\n internalTexture._cachedWrapV = texture.wrapV;\n this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);\n }\n this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);\n }\n return true;\n };\n /**\n * Sets an array of texture to the webGL context\n * @param channel defines the channel where the texture array must be set\n * @param uniform defines the associated uniform location\n * @param textures defines the array of textures to bind\n */\n Engine.prototype.setTextureArray = function (channel, uniform, textures) {\n if (channel < 0 || !uniform) {\n return;\n }\n if (!this._textureUnits || this._textureUnits.length !== textures.length) {\n this._textureUnits = new Int32Array(textures.length);\n }\n for (var i = 0; i < textures.length; i++) {\n this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());\n }\n this._gl.uniform1iv(uniform, this._textureUnits);\n for (var index = 0; index < textures.length; index++) {\n this._setTexture(this._textureUnits[index], textures[index], true);\n }\n };\n /** @hidden */\n Engine.prototype._setAnisotropicLevel = function (target, texture) {\n var internalTexture = texture.getInternalTexture();\n if (!internalTexture) {\n return;\n }\n var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;\n var value = texture.anisotropicFilteringLevel;\n if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST\n && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR\n && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {\n value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear\n }\n if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {\n this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);\n internalTexture._cachedAnisotropicFilteringLevel = value;\n }\n };\n Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {\n this._bindTextureDirectly(target, texture, true, true);\n this._gl.texParameterf(target, parameter, value);\n };\n Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {\n if (texture) {\n this._bindTextureDirectly(target, texture, true, true);\n }\n this._gl.texParameteri(target, parameter, value);\n };\n /**\n * Reads pixels from the current frame buffer. Please note that this function can be slow\n * @param x defines the x coordinate of the rectangle where pixels must be read\n * @param y defines the y coordinate of the rectangle where pixels must be read\n * @param width defines the width of the rectangle where pixels must be read\n * @param height defines the height of the rectangle where pixels must be read\n * @returns a Uint8Array containing RGBA colors\n */\n Engine.prototype.readPixels = function (x, y, width, height) {\n var data = new Uint8Array(height * width * 4);\n this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);\n return data;\n };\n /**\n * Add an externaly attached data from its key.\n * This method call will fail and return false, if such key already exists.\n * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.\n * @param key the unique key that identifies the data\n * @param data the data object to associate to the key for this Engine instance\n * @return true if no such key were already present and the data was added successfully, false otherwise\n */\n Engine.prototype.addExternalData = function (key, data) {\n if (!this._externalData) {\n this._externalData = new BABYLON.StringDictionary();\n }\n return this._externalData.add(key, data);\n };\n /**\n * Get an externaly attached data from its key\n * @param key the unique key that identifies the data\n * @return the associated data, if present (can be null), or undefined if not present\n */\n Engine.prototype.getExternalData = function (key) {\n if (!this._externalData) {\n this._externalData = new BABYLON.StringDictionary();\n }\n return this._externalData.get(key);\n };\n /**\n * Get an externaly attached data from its key, create it using a factory if it's not already present\n * @param key the unique key that identifies the data\n * @param factory the factory that will be called to create the instance if and only if it doesn't exists\n * @return the associated data, can be null if the factory returned null.\n */\n Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {\n if (!this._externalData) {\n this._externalData = new BABYLON.StringDictionary();\n }\n return this._externalData.getOrAddWithFactory(key, factory);\n };\n /**\n * Remove an externaly attached data from the Engine instance\n * @param key the unique key that identifies the data\n * @return true if the data was successfully removed, false if it doesn't exist\n */\n Engine.prototype.removeExternalData = function (key) {\n if (!this._externalData) {\n this._externalData = new BABYLON.StringDictionary();\n }\n return this._externalData.remove(key);\n };\n /**\n * Unbind all vertex attributes from the webGL context\n */\n Engine.prototype.unbindAllAttributes = function () {\n if (this._mustWipeVertexAttributes) {\n this._mustWipeVertexAttributes = false;\n for (var i = 0; i < this._caps.maxVertexAttribs; i++) {\n this._gl.disableVertexAttribArray(i);\n this._vertexAttribArraysEnabled[i] = false;\n this._currentBufferPointers[i].active = false;\n }\n return;\n }\n for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {\n if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {\n continue;\n }\n this._gl.disableVertexAttribArray(i);\n this._vertexAttribArraysEnabled[i] = false;\n this._currentBufferPointers[i].active = false;\n }\n };\n /**\n * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled\n */\n Engine.prototype.releaseEffects = function () {\n for (var name in this._compiledEffects) {\n this._deleteProgram(this._compiledEffects[name]._program);\n }\n this._compiledEffects = {};\n };\n /**\n * Dispose and release all associated resources\n */\n Engine.prototype.dispose = function () {\n this.hideLoadingUI();\n this.stopRenderLoop();\n // Release postProcesses\n while (this.postProcesses.length) {\n this.postProcesses[0].dispose();\n }\n // Empty texture\n if (this._emptyTexture) {\n this._releaseTexture(this._emptyTexture);\n this._emptyTexture = null;\n }\n if (this._emptyCubeTexture) {\n this._releaseTexture(this._emptyCubeTexture);\n this._emptyCubeTexture = null;\n }\n // Rescale PP\n if (this._rescalePostProcess) {\n this._rescalePostProcess.dispose();\n }\n // Release scenes\n while (this.scenes.length) {\n this.scenes[0].dispose();\n }\n // Release audio engine\n if (Engine.audioEngine) {\n Engine.audioEngine.dispose();\n }\n // Release effects\n this.releaseEffects();\n // Unbind\n this.unbindAllAttributes();\n this._boundUniforms = [];\n if (this._dummyFramebuffer) {\n this._gl.deleteFramebuffer(this._dummyFramebuffer);\n }\n //WebVR\n this.disableVR();\n // Events\n if (BABYLON.Tools.IsWindowObjectExist()) {\n window.removeEventListener(\"blur\", this._onBlur);\n window.removeEventListener(\"focus\", this._onFocus);\n window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);\n window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);\n if (this._renderingCanvas) {\n this._renderingCanvas.removeEventListener(\"focus\", this._onCanvasFocus);\n this._renderingCanvas.removeEventListener(\"blur\", this._onCanvasBlur);\n this._renderingCanvas.removeEventListener(\"pointerout\", this._onCanvasPointerOut);\n if (!this._doNotHandleContextLost) {\n this._renderingCanvas.removeEventListener(\"webglcontextlost\", this._onContextLost);\n this._renderingCanvas.removeEventListener(\"webglcontextrestored\", this._onContextRestored);\n }\n }\n document.removeEventListener(\"fullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"mozfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"webkitfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"msfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"pointerlockchange\", this._onPointerLockChange);\n document.removeEventListener(\"mspointerlockchange\", this._onPointerLockChange);\n document.removeEventListener(\"mozpointerlockchange\", this._onPointerLockChange);\n document.removeEventListener(\"webkitpointerlockchange\", this._onPointerLockChange);\n if (this._onVrDisplayConnect) {\n window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);\n if (this._onVrDisplayDisconnect) {\n window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);\n }\n if (this._onVrDisplayPresentChange) {\n window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);\n }\n this._onVrDisplayConnect = null;\n this._onVrDisplayDisconnect = null;\n }\n }\n // Remove from Instances\n var index = Engine.Instances.indexOf(this);\n if (index >= 0) {\n Engine.Instances.splice(index, 1);\n }\n this._workingCanvas = null;\n this._workingContext = null;\n this._currentBufferPointers = [];\n this._renderingCanvas = null;\n this._currentProgram = null;\n this._bindedRenderFunction = null;\n this.onResizeObservable.clear();\n this.onCanvasBlurObservable.clear();\n this.onCanvasFocusObservable.clear();\n this.onCanvasPointerOutObservable.clear();\n this.onBeginFrameObservable.clear();\n this.onEndFrameObservable.clear();\n BABYLON.Effect.ResetCache();\n // Abort active requests\n for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {\n var request = _a[_i];\n request.abort();\n }\n };\n // Loading screen\n /**\n * Display the loading screen\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n Engine.prototype.displayLoadingUI = function () {\n if (!BABYLON.Tools.IsWindowObjectExist()) {\n return;\n }\n var loadingScreen = this.loadingScreen;\n if (loadingScreen) {\n loadingScreen.displayLoadingUI();\n }\n };\n /**\n * Hide the loading screen\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n Engine.prototype.hideLoadingUI = function () {\n if (!BABYLON.Tools.IsWindowObjectExist()) {\n return;\n }\n var loadingScreen = this.loadingScreen;\n if (loadingScreen) {\n loadingScreen.hideLoadingUI();\n }\n };\n Object.defineProperty(Engine.prototype, \"loadingScreen\", {\n /**\n * Gets the current loading screen object\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n get: function () {\n if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)\n this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);\n return this._loadingScreen;\n },\n /**\n * Sets the current loading screen object\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n set: function (loadingScreen) {\n this._loadingScreen = loadingScreen;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"loadingUIText\", {\n /**\n * Sets the current loading screen text\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n set: function (text) {\n this.loadingScreen.loadingUIText = text;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"loadingUIBackgroundColor\", {\n /**\n * Sets the current loading screen background color\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n set: function (color) {\n this.loadingScreen.loadingUIBackgroundColor = color;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Attach a new callback raised when context lost event is fired\n * @param callback defines the callback to call\n */\n Engine.prototype.attachContextLostEvent = function (callback) {\n if (this._renderingCanvas) {\n this._renderingCanvas.addEventListener(\"webglcontextlost\", callback, false);\n }\n };\n /**\n * Attach a new callback raised when context restored event is fired\n * @param callback defines the callback to call\n */\n Engine.prototype.attachContextRestoredEvent = function (callback) {\n if (this._renderingCanvas) {\n this._renderingCanvas.addEventListener(\"webglcontextrestored\", callback, false);\n }\n };\n /**\n * Gets the source code of the vertex shader associated with a specific webGL program\n * @param program defines the program to use\n * @returns a string containing the source code of the vertex shader associated with the program\n */\n Engine.prototype.getVertexShaderSource = function (program) {\n var shaders = this._gl.getAttachedShaders(program);\n if (!shaders) {\n return null;\n }\n return this._gl.getShaderSource(shaders[0]);\n };\n /**\n * Gets the source code of the fragment shader associated with a specific webGL program\n * @param program defines the program to use\n * @returns a string containing the source code of the fragment shader associated with the program\n */\n Engine.prototype.getFragmentShaderSource = function (program) {\n var shaders = this._gl.getAttachedShaders(program);\n if (!shaders) {\n return null;\n }\n return this._gl.getShaderSource(shaders[1]);\n };\n /**\n * Get the current error code of the webGL context\n * @returns the error code\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError\n */\n Engine.prototype.getError = function () {\n return this._gl.getError();\n };\n // FPS\n /**\n * Gets the current framerate\n * @returns a number representing the framerate\n */\n Engine.prototype.getFps = function () {\n return this._fps;\n };\n /**\n * Gets the time spent between current and previous frame\n * @returns a number representing the delta time in ms\n */\n Engine.prototype.getDeltaTime = function () {\n return this._deltaTime;\n };\n Engine.prototype._measureFps = function () {\n this._performanceMonitor.sampleFrame();\n this._fps = this._performanceMonitor.averageFPS;\n this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;\n };\n /** @hidden */\n Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {\n if (faceIndex === void 0) { faceIndex = -1; }\n if (level === void 0) { level = 0; }\n var gl = this._gl;\n if (!this._dummyFramebuffer) {\n var dummy = gl.createFramebuffer();\n if (!dummy) {\n throw new Error(\"Unable to create dummy framebuffer\");\n }\n this._dummyFramebuffer = dummy;\n }\n gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);\n if (faceIndex > -1) {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);\n }\n else {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);\n }\n var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;\n var buffer;\n switch (readType) {\n case gl.UNSIGNED_BYTE:\n buffer = new Uint8Array(4 * width * height);\n readType = gl.UNSIGNED_BYTE;\n break;\n default:\n buffer = new Float32Array(4 * width * height);\n readType = gl.FLOAT;\n break;\n }\n gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);\n gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);\n return buffer;\n };\n Engine.prototype._canRenderToFloatFramebuffer = function () {\n if (this._webGLVersion > 1) {\n return this._caps.colorBufferFloat;\n }\n return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);\n };\n Engine.prototype._canRenderToHalfFloatFramebuffer = function () {\n if (this._webGLVersion > 1) {\n return this._caps.colorBufferFloat;\n }\n return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);\n };\n // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture\n Engine.prototype._canRenderToFramebuffer = function (type) {\n var gl = this._gl;\n //clear existing errors\n while (gl.getError() !== gl.NO_ERROR) { }\n var successful = true;\n var texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n var fb = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, fb);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);\n successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);\n successful = successful && (gl.getError() === gl.NO_ERROR);\n //try render by clearing frame buffer's color buffer\n if (successful) {\n gl.clear(gl.COLOR_BUFFER_BIT);\n successful = successful && (gl.getError() === gl.NO_ERROR);\n }\n //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)\n if (successful) {\n //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n var readFormat = gl.RGBA;\n var readType = gl.UNSIGNED_BYTE;\n var buffer = new Uint8Array(4);\n gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);\n successful = successful && (gl.getError() === gl.NO_ERROR);\n }\n //clean up\n gl.deleteTexture(texture);\n gl.deleteFramebuffer(fb);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n //clear accumulated errors\n while (!successful && (gl.getError() !== gl.NO_ERROR)) { }\n return successful;\n };\n /** @hidden */\n Engine.prototype._getWebGLTextureType = function (type) {\n if (type === Engine.TEXTURETYPE_FLOAT) {\n return this._gl.FLOAT;\n }\n else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {\n // Add Half Float Constant.\n return this._gl.HALF_FLOAT_OES;\n }\n return this._gl.UNSIGNED_BYTE;\n };\n ;\n Engine.prototype._getInternalFormat = function (format) {\n var internalFormat = this._gl.RGBA;\n switch (format) {\n case Engine.TEXTUREFORMAT_ALPHA:\n internalFormat = this._gl.ALPHA;\n break;\n case Engine.TEXTUREFORMAT_LUMINANCE:\n internalFormat = this._gl.LUMINANCE;\n break;\n case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:\n internalFormat = this._gl.LUMINANCE_ALPHA;\n break;\n case Engine.TEXTUREFORMAT_RGB:\n internalFormat = this._gl.RGB;\n break;\n case Engine.TEXTUREFORMAT_RGBA:\n internalFormat = this._gl.RGBA;\n break;\n case Engine.TEXTUREFORMAT_R:\n internalFormat = this._gl.RED;\n break;\n case Engine.TEXTUREFORMAT_RG:\n internalFormat = this._gl.RG;\n break;\n }\n return internalFormat;\n };\n /** @hidden */\n Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {\n if (this._webGLVersion === 1) {\n if (format !== undefined) {\n switch (format) {\n case Engine.TEXTUREFORMAT_LUMINANCE:\n return this._gl.LUMINANCE;\n case Engine.TEXTUREFORMAT_ALPHA:\n return this._gl.ALPHA;\n }\n }\n return this._gl.RGBA;\n }\n if (type === Engine.TEXTURETYPE_FLOAT) {\n if (format !== undefined) {\n switch (format) {\n case Engine.TEXTUREFORMAT_R:\n return this._gl.R32F;\n case Engine.TEXTUREFORMAT_RG:\n return this._gl.RG32F;\n case Engine.TEXTUREFORMAT_RGB:\n return this._gl.RGB32F;\n }\n }\n return this._gl.RGBA32F;\n }\n if (type === Engine.TEXTURETYPE_HALF_FLOAT) {\n if (format) {\n switch (format) {\n case Engine.TEXTUREFORMAT_R:\n return this._gl.R16F;\n case Engine.TEXTUREFORMAT_RG:\n return this._gl.RG16F;\n case Engine.TEXTUREFORMAT_RGB:\n return this._gl.RGB16F;\n }\n }\n return this._gl.RGBA16F;\n }\n if (format !== undefined) {\n switch (format) {\n case Engine.TEXTUREFORMAT_LUMINANCE:\n return this._gl.LUMINANCE;\n case Engine.TEXTUREFORMAT_RGB:\n return this._gl.RGB;\n case Engine.TEXTUREFORMAT_R:\n return this._gl.R8;\n case Engine.TEXTUREFORMAT_RG:\n return this._gl.RG8;\n case Engine.TEXTUREFORMAT_ALPHA:\n return this._gl.ALPHA;\n }\n }\n return this._gl.RGBA;\n };\n ;\n /** @hidden */\n Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {\n if (type === Engine.TEXTURETYPE_FLOAT) {\n return this._gl.RGBA32F;\n }\n else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {\n return this._gl.RGBA16F;\n }\n return this._gl.RGBA8;\n };\n ;\n /** @hidden */\n Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {\n var _this = this;\n var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);\n this._activeRequests.push(request);\n request.onCompleteObservable.add(function (request) {\n _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);\n });\n return request;\n };\n /** @hidden */\n Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this._loadFile(url, function (data) {\n resolve(data);\n }, undefined, database, useArrayBuffer, function (request, exception) {\n reject(exception);\n });\n });\n };\n Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {\n if (onErrorCallBack === void 0) { onErrorCallBack = null; }\n var onload = function (data) {\n loadedFiles[index] = data;\n loadedFiles._internalCount++;\n if (loadedFiles._internalCount === 6) {\n onfinish(loadedFiles);\n }\n };\n var onerror = function (request, exception) {\n if (onErrorCallBack && request) {\n onErrorCallBack(request.status + \" \" + request.statusText, exception);\n }\n };\n this._loadFile(url, onload, undefined, undefined, true, onerror);\n };\n Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {\n if (onError === void 0) { onError = null; }\n var loadedFiles = [];\n loadedFiles._internalCount = 0;\n for (var index = 0; index < 6; index++) {\n this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);\n }\n };\n // Statics\n /**\n * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)\n * @returns true if the engine can be created\n * @ignorenaming\n */\n Engine.isSupported = function () {\n try {\n var tempcanvas = document.createElement(\"canvas\");\n var gl = tempcanvas.getContext(\"webgl\") || tempcanvas.getContext(\"experimental-webgl\");\n return gl != null && !!window.WebGLRenderingContext;\n }\n catch (e) {\n return false;\n }\n };\n /** Use this array to turn off some WebGL2 features on known buggy browsers version */\n Engine.ExceptionList = [\n { key: \"Chrome/63.0\", capture: \"63\\\\.0\\\\.3239\\\\.(\\\\d+)\", captureConstraint: 108, targets: [\"uniformBuffer\"] },\n { key: \"Firefox/58\", capture: null, captureConstraint: null, targets: [\"uniformBuffer\"] },\n { key: \"Firefox/59\", capture: null, captureConstraint: null, targets: [\"uniformBuffer\"] },\n { key: \"Macintosh\", capture: null, captureConstraint: null, targets: [\"textureBindingOptimization\"] },\n { key: \"iPhone\", capture: null, captureConstraint: null, targets: [\"textureBindingOptimization\"] },\n { key: \"iPad\", capture: null, captureConstraint: null, targets: [\"textureBindingOptimization\"] }\n ];\n /** Gets the list of created engines */\n Engine.Instances = new Array();\n /**\n * Hidden\n */\n Engine._TextureLoaders = [];\n // Const statics\n /** Defines that alpha blending is disabled */\n Engine.ALPHA_DISABLE = 0;\n /** Defines that alpha blending to SRC ALPHA * SRC + DEST */\n Engine.ALPHA_ADD = 1;\n /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */\n Engine.ALPHA_COMBINE = 2;\n /** Defines that alpha blending to DEST - SRC * DEST */\n Engine.ALPHA_SUBTRACT = 3;\n /** Defines that alpha blending to SRC * DEST */\n Engine.ALPHA_MULTIPLY = 4;\n /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */\n Engine.ALPHA_MAXIMIZED = 5;\n /** Defines that alpha blending to SRC + DEST */\n Engine.ALPHA_ONEONE = 6;\n /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */\n Engine.ALPHA_PREMULTIPLIED = 7;\n /**\n * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST\n * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA\n */\n Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;\n /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */\n Engine.ALPHA_INTERPOLATE = 9;\n /**\n * Defines that alpha blending to SRC + (1 - SRC) * DEST\n * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA\n */\n Engine.ALPHA_SCREENMODE = 10;\n /** Defines that the ressource is not delayed*/\n Engine.DELAYLOADSTATE_NONE = 0;\n /** Defines that the ressource was successfully delay loaded */\n Engine.DELAYLOADSTATE_LOADED = 1;\n /** Defines that the ressource is currently delay loading */\n Engine.DELAYLOADSTATE_LOADING = 2;\n /** Defines that the ressource is delayed and has not started loading */\n Engine.DELAYLOADSTATE_NOTLOADED = 4;\n // Depht or Stencil test Constants.\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */\n Engine.NEVER = 0x0200;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */\n Engine.ALWAYS = 0x0207;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */\n Engine.LESS = 0x0201;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */\n Engine.EQUAL = 0x0202;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */\n Engine.LEQUAL = 0x0203;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */\n Engine.GREATER = 0x0204;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */\n Engine.GEQUAL = 0x0206;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */\n Engine.NOTEQUAL = 0x0205;\n // Stencil Actions Constants.\n /** Passed to stencilOperation to specify that stencil value must be kept */\n Engine.KEEP = 0x1E00;\n /** Passed to stencilOperation to specify that stencil value must be replaced */\n Engine.REPLACE = 0x1E01;\n /** Passed to stencilOperation to specify that stencil value must be incremented */\n Engine.INCR = 0x1E02;\n /** Passed to stencilOperation to specify that stencil value must be decremented */\n Engine.DECR = 0x1E03;\n /** Passed to stencilOperation to specify that stencil value must be inverted */\n Engine.INVERT = 0x150A;\n /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */\n Engine.INCR_WRAP = 0x8507;\n /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */\n Engine.DECR_WRAP = 0x8508;\n /** Texture is not repeating outside of 0..1 UVs */\n Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;\n /** Texture is repeating outside of 0..1 UVs */\n Engine.TEXTURE_WRAP_ADDRESSMODE = 1;\n /** Texture is repeating and mirrored */\n Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;\n /** ALPHA */\n Engine.TEXTUREFORMAT_ALPHA = 0;\n /** LUMINANCE */\n Engine.TEXTUREFORMAT_LUMINANCE = 1;\n /** LUMINANCE_ALPHA */\n Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;\n /** RGB */\n Engine.TEXTUREFORMAT_RGB = 4;\n /** RGBA */\n Engine.TEXTUREFORMAT_RGBA = 5;\n /** R */\n Engine.TEXTUREFORMAT_R = 6;\n /** RG */\n Engine.TEXTUREFORMAT_RG = 7;\n /** UNSIGNED_INT */\n Engine.TEXTURETYPE_UNSIGNED_INT = 0;\n /** FLOAT */\n Engine.TEXTURETYPE_FLOAT = 1;\n /** HALF_FLOAT */\n Engine.TEXTURETYPE_HALF_FLOAT = 2;\n /** nearest is mag = nearest and min = nearest and mip = linear */\n Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;\n /** Bilinear is mag = linear and min = linear and mip = nearest */\n Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;\n /** Trilinear is mag = linear and min = linear and mip = linear */\n Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;\n /** nearest is mag = nearest and min = nearest and mip = linear */\n Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;\n /** Bilinear is mag = linear and min = linear and mip = nearest */\n Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;\n /** Trilinear is mag = linear and min = linear and mip = linear */\n Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;\n /** mag = nearest and min = nearest and mip = nearest */\n Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;\n /** mag = nearest and min = linear and mip = nearest */\n Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;\n /** mag = nearest and min = linear and mip = linear */\n Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;\n /** mag = nearest and min = linear and mip = none */\n Engine.TEXTURE_NEAREST_LINEAR = 7;\n /** mag = nearest and min = nearest and mip = none */\n Engine.TEXTURE_NEAREST_NEAREST = 8;\n /** mag = linear and min = nearest and mip = nearest */\n Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;\n /** mag = linear and min = nearest and mip = linear */\n Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;\n /** mag = linear and min = linear and mip = none */\n Engine.TEXTURE_LINEAR_LINEAR = 11;\n /** mag = linear and min = nearest and mip = none */\n Engine.TEXTURE_LINEAR_NEAREST = 12;\n /** Explicit coordinates mode */\n Engine.TEXTURE_EXPLICIT_MODE = 0;\n /** Spherical coordinates mode */\n Engine.TEXTURE_SPHERICAL_MODE = 1;\n /** Planar coordinates mode */\n Engine.TEXTURE_PLANAR_MODE = 2;\n /** Cubic coordinates mode */\n Engine.TEXTURE_CUBIC_MODE = 3;\n /** Projection coordinates mode */\n Engine.TEXTURE_PROJECTION_MODE = 4;\n /** Skybox coordinates mode */\n Engine.TEXTURE_SKYBOX_MODE = 5;\n /** Inverse Cubic coordinates mode */\n Engine.TEXTURE_INVCUBIC_MODE = 6;\n /** Equirectangular coordinates mode */\n Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;\n /** Equirectangular Fixed coordinates mode */\n Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;\n /** Equirectangular Fixed Mirrored coordinates mode */\n Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;\n // Texture rescaling mode\n /** Defines that texture rescaling will use a floor to find the closer power of 2 size */\n Engine.SCALEMODE_FLOOR = 1;\n /** Defines that texture rescaling will look for the nearest power of 2 size */\n Engine.SCALEMODE_NEAREST = 2;\n /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */\n Engine.SCALEMODE_CEILING = 3;\n // Updatable statics so stick with vars here\n /**\n * Gets or sets the epsilon value used by collision engine\n */\n Engine.CollisionsEpsilon = 0.001;\n /**\n * Gets or sets the relative url used to load code if using the engine in non-minified mode\n */\n Engine.CodeRepository = \"src/\";\n /**\n * Gets or sets the relative url used to load shaders if using the engine in non-minified mode\n */\n Engine.ShadersRepository = \"src/Shaders/\";\n return Engine;\n }());\n BABYLON.Engine = Engine;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.engine.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Node is the basic class for all scene objects (Mesh, Light Camera).\n */\n var Node = /** @class */ (function () {\n /**\n * Creates a new Node\n * @param {string} name - the name and id to be given to this node\n * @param {BABYLON.Scene} the scene this node will be added to\n */\n function Node(name, scene) {\n if (scene === void 0) { scene = null; }\n /**\n * Gets or sets a string used to store user defined state for the node\n */\n this.state = \"\";\n /**\n * Gets or sets an object used to store user defined information for the node\n */\n this.metadata = null;\n /**\n * Gets or sets a boolean used to define if the node must be serialized\n */\n this.doNotSerialize = false;\n /** @hidden */\n this._isDisposed = false;\n /**\n * Gets a list of Animations associated with the node\n */\n this.animations = new Array();\n this._ranges = {};\n this._isEnabled = true;\n this._isReady = true;\n /** @hidden */\n this._currentRenderId = -1;\n this._parentRenderId = -1;\n this._childRenderId = -1;\n this._animationPropertiesOverride = null;\n /**\n * An event triggered when the mesh is disposed\n */\n this.onDisposeObservable = new BABYLON.Observable();\n // Behaviors\n this._behaviors = new Array();\n this.name = name;\n this.id = name;\n this._scene = (scene || BABYLON.Engine.LastCreatedScene);\n this.uniqueId = this._scene.getUniqueId();\n this._initCache();\n }\n /**\n * Add a new node constructor\n * @param type defines the type name of the node to construct\n * @param constructorFunc defines the constructor function\n */\n Node.AddNodeConstructor = function (type, constructorFunc) {\n this._NodeConstructors[type] = constructorFunc;\n };\n /**\n * Returns a node constructor based on type name\n * @param type defines the type name\n * @param name defines the new node name\n * @param scene defines the hosting scene\n * @param options defines optional options to transmit to constructors\n * @returns the new constructor or null\n */\n Node.Construct = function (type, name, scene, options) {\n var constructorFunc = this._NodeConstructors[type];\n if (!constructorFunc) {\n return null;\n }\n return constructorFunc(name, scene, options);\n };\n /**\n * Gets a boolean indicating if the node has been disposed\n * @returns true if the node was disposed\n */\n Node.prototype.isDisposed = function () {\n return this._isDisposed;\n };\n Object.defineProperty(Node.prototype, \"parent\", {\n get: function () {\n return this._parentNode;\n },\n /**\n * Gets or sets the parent of the node\n */\n set: function (parent) {\n if (this._parentNode === parent) {\n return;\n }\n // Remove self from list of children of parent\n if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {\n var index = this._parentNode._children.indexOf(this);\n if (index !== -1) {\n this._parentNode._children.splice(index, 1);\n }\n }\n // Store new parent\n this._parentNode = parent;\n // Add as child to new parent\n if (this._parentNode) {\n if (this._parentNode._children === undefined || this._parentNode._children === null) {\n this._parentNode._children = new Array();\n }\n this._parentNode._children.push(this);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Node.prototype, \"animationPropertiesOverride\", {\n /**\n * Gets or sets the animation properties override\n */\n get: function () {\n if (!this._animationPropertiesOverride) {\n return this._scene.animationPropertiesOverride;\n }\n return this._animationPropertiesOverride;\n },\n set: function (value) {\n this._animationPropertiesOverride = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets a string idenfifying the name of the class\n * @returns \"Node\" string\n */\n Node.prototype.getClassName = function () {\n return \"Node\";\n };\n Object.defineProperty(Node.prototype, \"onDispose\", {\n /**\n * Sets a callback that will be raised when the node will be disposed\n */\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the scene of the node\n * @returns a {BABYLON.Scene}\n */\n Node.prototype.getScene = function () {\n return this._scene;\n };\n /**\n * Gets the engine of the node\n * @returns a {BABYLON.Engine}\n */\n Node.prototype.getEngine = function () {\n return this._scene.getEngine();\n };\n /**\n * Attach a behavior to the node\n * @see http://doc.babylonjs.com/features/behaviour\n * @param behavior defines the behavior to attach\n * @returns the current Node\n */\n Node.prototype.addBehavior = function (behavior) {\n var _this = this;\n var index = this._behaviors.indexOf(behavior);\n if (index !== -1) {\n return this;\n }\n behavior.init();\n if (this._scene.isLoading) {\n // We defer the attach when the scene will be loaded\n this._scene.onDataLoadedObservable.addOnce(function () {\n behavior.attach(_this);\n });\n }\n else {\n behavior.attach(this);\n }\n this._behaviors.push(behavior);\n return this;\n };\n /**\n * Remove an attached behavior\n * @see http://doc.babylonjs.com/features/behaviour\n * @param behavior defines the behavior to attach\n * @returns the current Node\n */\n Node.prototype.removeBehavior = function (behavior) {\n var index = this._behaviors.indexOf(behavior);\n if (index === -1) {\n return this;\n }\n this._behaviors[index].detach();\n this._behaviors.splice(index, 1);\n return this;\n };\n Object.defineProperty(Node.prototype, \"behaviors\", {\n /**\n * Gets the list of attached behaviors\n * @see http://doc.babylonjs.com/features/behaviour\n */\n get: function () {\n return this._behaviors;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets an attached behavior by name\n * @param name defines the name of the behavior to look for\n * @see http://doc.babylonjs.com/features/behaviour\n * @returns null if behavior was not found else the requested behavior\n */\n Node.prototype.getBehaviorByName = function (name) {\n for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {\n var behavior = _a[_i];\n if (behavior.name === name) {\n return behavior;\n }\n }\n return null;\n };\n /**\n * Returns the world matrix of the node\n * @returns a matrix containing the node's world matrix\n */\n Node.prototype.getWorldMatrix = function () {\n return BABYLON.Matrix.Identity();\n };\n /** @hidden */\n Node.prototype._getWorldMatrixDeterminant = function () {\n return 1;\n };\n // override it in derived class if you add new variables to the cache\n // and call the parent class method\n /** @hidden */\n Node.prototype._initCache = function () {\n this._cache = {};\n this._cache.parent = undefined;\n };\n /** @hidden */\n Node.prototype.updateCache = function (force) {\n if (!force && this.isSynchronized())\n return;\n this._cache.parent = this.parent;\n this._updateCache();\n };\n // override it in derived class if you add new variables to the cache\n // and call the parent class method if !ignoreParentClass\n /** @hidden */\n Node.prototype._updateCache = function (ignoreParentClass) {\n };\n // override it in derived class if you add new variables to the cache\n /** @hidden */\n Node.prototype._isSynchronized = function () {\n return true;\n };\n /** @hidden */\n Node.prototype._markSyncedWithParent = function () {\n if (this.parent) {\n this._parentRenderId = this.parent._childRenderId;\n }\n };\n /** @hidden */\n Node.prototype.isSynchronizedWithParent = function () {\n if (!this.parent) {\n return true;\n }\n if (this._parentRenderId !== this.parent._childRenderId) {\n return false;\n }\n return this.parent.isSynchronized();\n };\n /** @hidden */\n Node.prototype.isSynchronized = function (updateCache) {\n var check = this.hasNewParent();\n check = check || !this.isSynchronizedWithParent();\n check = check || !this._isSynchronized();\n if (updateCache)\n this.updateCache(true);\n return !check;\n };\n /** @hidden */\n Node.prototype.hasNewParent = function (update) {\n if (this._cache.parent === this.parent)\n return false;\n if (update)\n this._cache.parent = this.parent;\n return true;\n };\n /**\n * Is this node ready to be used/rendered\n * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)\n * @return true if the node is ready\n */\n Node.prototype.isReady = function (completeCheck) {\n if (completeCheck === void 0) { completeCheck = false; }\n return this._isReady;\n };\n /**\n * Is this node enabled?\n * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true\n * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors\n * @return whether this node (and its parent) is enabled\n */\n Node.prototype.isEnabled = function (checkAncestors) {\n if (checkAncestors === void 0) { checkAncestors = true; }\n if (checkAncestors === false) {\n return this._isEnabled;\n }\n if (this._isEnabled === false) {\n return false;\n }\n if (this.parent !== undefined && this.parent !== null) {\n return this.parent.isEnabled(checkAncestors);\n }\n return true;\n };\n /**\n * Set the enabled state of this node\n * @param value defines the new enabled state\n */\n Node.prototype.setEnabled = function (value) {\n this._isEnabled = value;\n };\n /**\n * Is this node a descendant of the given node?\n * The function will iterate up the hierarchy until the ancestor was found or no more parents defined\n * @param ancestor defines the parent node to inspect\n * @returns a boolean indicating if this node is a descendant of the given node\n */\n Node.prototype.isDescendantOf = function (ancestor) {\n if (this.parent) {\n if (this.parent === ancestor) {\n return true;\n }\n return this.parent.isDescendantOf(ancestor);\n }\n return false;\n };\n /** @hidden */\n Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {\n if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }\n if (!this._children) {\n return;\n }\n for (var index = 0; index < this._children.length; index++) {\n var item = this._children[index];\n if (!predicate || predicate(item)) {\n results.push(item);\n }\n if (!directDescendantsOnly) {\n item._getDescendants(results, false, predicate);\n }\n }\n };\n /**\n * Will return all nodes that have this node as ascendant\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @return all children nodes of all types\n */\n Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {\n var results = new Array();\n this._getDescendants(results, directDescendantsOnly, predicate);\n return results;\n };\n /**\n * Get all child-meshes of this node\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @returns an array of {BABYLON.AbstractMesh}\n */\n Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {\n var results = [];\n this._getDescendants(results, directDescendantsOnly, function (node) {\n return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));\n });\n return results;\n };\n /**\n * Get all child-transformNodes of this node\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @returns an array of {BABYLON.TransformNode}\n */\n Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {\n var results = [];\n this._getDescendants(results, directDescendantsOnly, function (node) {\n return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));\n });\n return results;\n };\n /**\n * Get all direct children of this node\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @returns an array of {BABYLON.Node}\n */\n Node.prototype.getChildren = function (predicate) {\n return this.getDescendants(true, predicate);\n };\n /** @hidden */\n Node.prototype._setReady = function (state) {\n if (state === this._isReady) {\n return;\n }\n if (!state) {\n this._isReady = false;\n return;\n }\n if (this.onReady) {\n this.onReady(this);\n }\n this._isReady = true;\n };\n /**\n * Get an animation by name\n * @param name defines the name of the animation to look for\n * @returns null if not found else the requested animation\n */\n Node.prototype.getAnimationByName = function (name) {\n for (var i = 0; i < this.animations.length; i++) {\n var animation = this.animations[i];\n if (animation.name === name) {\n return animation;\n }\n }\n return null;\n };\n /**\n * Creates an animation range for this node\n * @param name defines the name of the range\n * @param from defines the starting key\n * @param to defines the end key\n */\n Node.prototype.createAnimationRange = function (name, from, to) {\n // check name not already in use\n if (!this._ranges[name]) {\n this._ranges[name] = new BABYLON.AnimationRange(name, from, to);\n for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {\n if (this.animations[i]) {\n this.animations[i].createRange(name, from, to);\n }\n }\n }\n };\n /**\n * Delete a specific animation range\n * @param name defines the name of the range to delete\n * @param deleteFrames defines if animation frames from the range must be deleted as well\n */\n Node.prototype.deleteAnimationRange = function (name, deleteFrames) {\n if (deleteFrames === void 0) { deleteFrames = true; }\n for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {\n if (this.animations[i]) {\n this.animations[i].deleteRange(name, deleteFrames);\n }\n }\n this._ranges[name] = null; // said much faster than 'delete this._range[name]' \n };\n /**\n * Get an animation range by name\n * @param name defines the name of the animation range to look for\n * @returns null if not found else the requested animation range\n */\n Node.prototype.getAnimationRange = function (name) {\n return this._ranges[name];\n };\n /**\n * Will start the animation sequence\n * @param name defines the range frames for animation sequence\n * @param loop defines if the animation should loop (false by default)\n * @param speedRatio defines the speed factor in which to run the animation (1 by default)\n * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)\n * @returns the object created for this animation. If range does not exist, it will return null\n */\n Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {\n var range = this.getAnimationRange(name);\n if (!range) {\n return null;\n }\n return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);\n };\n /**\n * Serialize animation ranges into a JSON compatible object\n * @returns serialization object\n */\n Node.prototype.serializeAnimationRanges = function () {\n var serializationRanges = [];\n for (var name in this._ranges) {\n var localRange = this._ranges[name];\n if (!localRange) {\n continue;\n }\n var range = {};\n range.name = name;\n range.from = localRange.from;\n range.to = localRange.to;\n serializationRanges.push(range);\n }\n return serializationRanges;\n };\n /**\n * Computes the world matrix of the node\n * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch\n * @returns the world matrix\n */\n Node.prototype.computeWorldMatrix = function (force) {\n return BABYLON.Matrix.Identity();\n };\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n if (!doNotRecurse) {\n var nodes = this.getDescendants(true);\n for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {\n var node = nodes_1[_i];\n node.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n }\n else {\n var transformNodes = this.getChildTransformNodes(true);\n for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {\n var transformNode = transformNodes_1[_a];\n transformNode.parent = null;\n transformNode.computeWorldMatrix(true);\n }\n }\n this.parent = null;\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n // Behaviors\n for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {\n var behavior = _c[_b];\n behavior.detach();\n }\n this._behaviors = [];\n this._isDisposed = true;\n };\n /**\n * Parse animation range data from a serialization object and store them into a given node\n * @param node defines where to store the animation ranges\n * @param parsedNode defines the serialization object to read data from\n * @param scene defines the hosting scene\n */\n Node.ParseAnimationRanges = function (node, parsedNode, scene) {\n if (parsedNode.ranges) {\n for (var index = 0; index < parsedNode.ranges.length; index++) {\n var data = parsedNode.ranges[index];\n node.createAnimationRange(data.name, data.from, data.to);\n }\n }\n };\n Node._NodeConstructors = {};\n __decorate([\n BABYLON.serialize()\n ], Node.prototype, \"name\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Node.prototype, \"id\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Node.prototype, \"uniqueId\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Node.prototype, \"state\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Node.prototype, \"metadata\", void 0);\n return Node;\n }());\n BABYLON.Node = Node;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.node.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var BoundingSphere = /** @class */ (function () {\n /**\n * Creates a new bounding sphere\n * @param min defines the minimum vector (in local space)\n * @param max defines the maximum vector (in local space)\n */\n function BoundingSphere(min, max) {\n this._tempRadiusVector = BABYLON.Vector3.Zero();\n this.reConstruct(min, max);\n }\n /**\n * Recreates the entire bounding sphere from scratch\n * @param min defines the new minimum vector (in local space)\n * @param max defines the new maximum vector (in local space)\n */\n BoundingSphere.prototype.reConstruct = function (min, max) {\n this.minimum = min.clone();\n this.maximum = max.clone();\n var distance = BABYLON.Vector3.Distance(min, max);\n this.center = BABYLON.Vector3.Lerp(min, max, 0.5);\n this.radius = distance * 0.5;\n this.centerWorld = BABYLON.Vector3.Zero();\n this._update(BABYLON.Matrix.Identity());\n };\n /**\n * Scale the current bounding sphere by applying a scale factor\n * @param factor defines the scale factor to apply\n * @returns the current bounding box\n */\n BoundingSphere.prototype.scale = function (factor) {\n var newRadius = this.radius * factor;\n var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);\n var min = this.center.subtract(newRadiusVector);\n var max = this.center.add(newRadiusVector);\n this.reConstruct(min, max);\n return this;\n };\n // Methods\n BoundingSphere.prototype._update = function (world) {\n BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);\n this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;\n };\n BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {\n for (var i = 0; i < 6; i++) {\n if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)\n return false;\n }\n return true;\n };\n BoundingSphere.prototype.intersectsPoint = function (point) {\n var x = this.centerWorld.x - point.x;\n var y = this.centerWorld.y - point.y;\n var z = this.centerWorld.z - point.z;\n var distance = Math.sqrt((x * x) + (y * y) + (z * z));\n if (this.radiusWorld < distance)\n return false;\n return true;\n };\n // Statics\n BoundingSphere.Intersects = function (sphere0, sphere1) {\n var x = sphere0.centerWorld.x - sphere1.centerWorld.x;\n var y = sphere0.centerWorld.y - sphere1.centerWorld.y;\n var z = sphere0.centerWorld.z - sphere1.centerWorld.z;\n var distance = Math.sqrt((x * x) + (y * y) + (z * z));\n if (sphere0.radiusWorld + sphere1.radiusWorld < distance)\n return false;\n return true;\n };\n return BoundingSphere;\n }());\n BABYLON.BoundingSphere = BoundingSphere;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boundingSphere.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var BoundingBox = /** @class */ (function () {\n /**\n * Creates a new bounding box\n * @param min defines the minimum vector (in local space)\n * @param max defines the maximum vector (in local space)\n */\n function BoundingBox(min, max) {\n this.vectorsWorld = new Array();\n this.reConstruct(min, max);\n }\n // Methods\n /**\n * Recreates the entire bounding box from scratch\n * @param min defines the new minimum vector (in local space)\n * @param max defines the new maximum vector (in local space)\n */\n BoundingBox.prototype.reConstruct = function (min, max) {\n this.minimum = min.clone();\n this.maximum = max.clone();\n // Bounding vectors\n this.vectors = new Array();\n this.vectors.push(this.minimum.clone());\n this.vectors.push(this.maximum.clone());\n this.vectors.push(this.minimum.clone());\n this.vectors[2].x = this.maximum.x;\n this.vectors.push(this.minimum.clone());\n this.vectors[3].y = this.maximum.y;\n this.vectors.push(this.minimum.clone());\n this.vectors[4].z = this.maximum.z;\n this.vectors.push(this.maximum.clone());\n this.vectors[5].z = this.minimum.z;\n this.vectors.push(this.maximum.clone());\n this.vectors[6].x = this.minimum.x;\n this.vectors.push(this.maximum.clone());\n this.vectors[7].y = this.minimum.y;\n // OBB\n this.center = this.maximum.add(this.minimum).scale(0.5);\n this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);\n this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n // World\n for (var index = 0; index < this.vectors.length; index++) {\n this.vectorsWorld[index] = BABYLON.Vector3.Zero();\n }\n this.minimumWorld = BABYLON.Vector3.Zero();\n this.maximumWorld = BABYLON.Vector3.Zero();\n this.centerWorld = BABYLON.Vector3.Zero();\n this.extendSizeWorld = BABYLON.Vector3.Zero();\n this._update(this._worldMatrix || BABYLON.Matrix.Identity());\n };\n /**\n * Scale the current bounding box by applying a scale factor\n * @param factor defines the scale factor to apply\n * @returns the current bounding box\n */\n BoundingBox.prototype.scale = function (factor) {\n var diff = this.maximum.subtract(this.minimum);\n var distance = diff.length() * factor;\n diff.normalize();\n var newRadius = diff.scale(distance / 2);\n var min = this.center.subtract(newRadius);\n var max = this.center.add(newRadius);\n this.reConstruct(min, max);\n return this;\n };\n BoundingBox.prototype.getWorldMatrix = function () {\n return this._worldMatrix;\n };\n BoundingBox.prototype.setWorldMatrix = function (matrix) {\n this._worldMatrix.copyFrom(matrix);\n return this;\n };\n BoundingBox.prototype._update = function (world) {\n BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);\n BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);\n for (var index = 0; index < this.vectors.length; index++) {\n var v = this.vectorsWorld[index];\n BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);\n if (v.x < this.minimumWorld.x)\n this.minimumWorld.x = v.x;\n if (v.y < this.minimumWorld.y)\n this.minimumWorld.y = v.y;\n if (v.z < this.minimumWorld.z)\n this.minimumWorld.z = v.z;\n if (v.x > this.maximumWorld.x)\n this.maximumWorld.x = v.x;\n if (v.y > this.maximumWorld.y)\n this.maximumWorld.y = v.y;\n if (v.z > this.maximumWorld.z)\n this.maximumWorld.z = v.z;\n }\n // Extend\n this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);\n this.extendSizeWorld.scaleInPlace(0.5);\n // OBB\n this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);\n this.centerWorld.scaleInPlace(0.5);\n BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);\n BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);\n BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);\n this._worldMatrix = world;\n };\n BoundingBox.prototype.isInFrustum = function (frustumPlanes) {\n return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);\n };\n BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {\n return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);\n };\n BoundingBox.prototype.intersectsPoint = function (point) {\n var delta = -BABYLON.Epsilon;\n if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)\n return false;\n if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)\n return false;\n if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)\n return false;\n return true;\n };\n BoundingBox.prototype.intersectsSphere = function (sphere) {\n return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);\n };\n BoundingBox.prototype.intersectsMinMax = function (min, max) {\n if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)\n return false;\n if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)\n return false;\n if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)\n return false;\n return true;\n };\n // Statics\n BoundingBox.Intersects = function (box0, box1) {\n if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)\n return false;\n if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)\n return false;\n if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)\n return false;\n return true;\n };\n BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {\n var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);\n var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);\n return (num <= (sphereRadius * sphereRadius));\n };\n BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {\n for (var p = 0; p < 6; p++) {\n for (var i = 0; i < 8; i++) {\n if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {\n return false;\n }\n }\n }\n return true;\n };\n BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {\n for (var p = 0; p < 6; p++) {\n var inCount = 8;\n for (var i = 0; i < 8; i++) {\n if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {\n --inCount;\n }\n else {\n break;\n }\n }\n if (inCount === 0)\n return false;\n }\n return true;\n };\n return BoundingBox;\n }());\n BABYLON.BoundingBox = BoundingBox;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boundingBox.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var computeBoxExtents = function (axis, box) {\n var p = BABYLON.Vector3.Dot(box.centerWorld, axis);\n var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;\n var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;\n var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;\n var r = r0 + r1 + r2;\n return {\n min: p - r,\n max: p + r\n };\n };\n var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };\n var axisOverlap = function (axis, box0, box1) {\n var result0 = computeBoxExtents(axis, box0);\n var result1 = computeBoxExtents(axis, box1);\n return extentsOverlap(result0.min, result0.max, result1.min, result1.max);\n };\n var BoundingInfo = /** @class */ (function () {\n function BoundingInfo(minimum, maximum) {\n this.minimum = minimum;\n this.maximum = maximum;\n this._isLocked = false;\n this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);\n this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);\n }\n Object.defineProperty(BoundingInfo.prototype, \"isLocked\", {\n get: function () {\n return this._isLocked;\n },\n set: function (value) {\n this._isLocked = value;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n BoundingInfo.prototype.update = function (world) {\n if (this._isLocked) {\n return;\n }\n this.boundingBox._update(world);\n this.boundingSphere._update(world);\n };\n /**\n * Recreate the bounding info to be centered around a specific point given a specific extend.\n * @param center New center of the bounding info\n * @param extend New extend of the bounding info\n */\n BoundingInfo.prototype.centerOn = function (center, extend) {\n this.minimum = center.subtract(extend);\n this.maximum = center.add(extend);\n this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);\n this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);\n return this;\n };\n /**\n * Scale the current bounding info by applying a scale factor\n * @param factor defines the scale factor to apply\n * @returns the current bounding info\n */\n BoundingInfo.prototype.scale = function (factor) {\n this.boundingBox.scale(factor);\n this.boundingSphere.scale(factor);\n return this;\n };\n BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {\n if (!this.boundingSphere.isInFrustum(frustumPlanes))\n return false;\n return this.boundingBox.isInFrustum(frustumPlanes);\n };\n Object.defineProperty(BoundingInfo.prototype, \"diagonalLength\", {\n /**\n * Gets the world distance between the min and max points of the bounding box\n */\n get: function () {\n var boundingBox = this.boundingBox;\n var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);\n return size.length();\n },\n enumerable: true,\n configurable: true\n });\n BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {\n return this.boundingBox.isCompletelyInFrustum(frustumPlanes);\n };\n BoundingInfo.prototype._checkCollision = function (collider) {\n return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);\n };\n BoundingInfo.prototype.intersectsPoint = function (point) {\n if (!this.boundingSphere.centerWorld) {\n return false;\n }\n if (!this.boundingSphere.intersectsPoint(point)) {\n return false;\n }\n if (!this.boundingBox.intersectsPoint(point)) {\n return false;\n }\n return true;\n };\n BoundingInfo.prototype.intersects = function (boundingInfo, precise) {\n if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {\n return false;\n }\n if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {\n return false;\n }\n if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {\n return false;\n }\n if (!precise) {\n return true;\n }\n var box0 = this.boundingBox;\n var box1 = boundingInfo.boundingBox;\n if (!axisOverlap(box0.directions[0], box0, box1))\n return false;\n if (!axisOverlap(box0.directions[1], box0, box1))\n return false;\n if (!axisOverlap(box0.directions[2], box0, box1))\n return false;\n if (!axisOverlap(box1.directions[0], box0, box1))\n return false;\n if (!axisOverlap(box1.directions[1], box0, box1))\n return false;\n if (!axisOverlap(box1.directions[2], box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))\n return false;\n return true;\n };\n return BoundingInfo;\n }());\n BABYLON.BoundingInfo = BoundingInfo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boundingInfo.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var TransformNode = /** @class */ (function (_super) {\n __extends(TransformNode, _super);\n function TransformNode(name, scene, isPure) {\n if (scene === void 0) { scene = null; }\n if (isPure === void 0) { isPure = true; }\n var _this = _super.call(this, name, scene) || this;\n _this._forward = new BABYLON.Vector3(0, 0, 1);\n _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);\n _this._up = new BABYLON.Vector3(0, 1, 0);\n _this._right = new BABYLON.Vector3(1, 0, 0);\n _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);\n // Properties\n _this._rotation = BABYLON.Vector3.Zero();\n _this._scaling = BABYLON.Vector3.One();\n _this._isDirty = false;\n /**\n * Set the billboard mode. Default is 0.\n *\n * | Value | Type | Description |\n * | --- | --- | --- |\n * | 0 | BILLBOARDMODE_NONE | |\n * | 1 | BILLBOARDMODE_X | |\n * | 2 | BILLBOARDMODE_Y | |\n * | 4 | BILLBOARDMODE_Z | |\n * | 7 | BILLBOARDMODE_ALL | |\n *\n */\n _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;\n _this.scalingDeterminant = 1;\n _this.infiniteDistance = false;\n /**\n * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.\n * By default the system will update normals to compensate\n */\n _this.ignoreNonUniformScaling = false;\n _this.position = BABYLON.Vector3.Zero();\n _this._localWorld = BABYLON.Matrix.Zero();\n _this._worldMatrix = BABYLON.Matrix.Zero();\n _this._worldMatrixDeterminant = 0;\n _this._absolutePosition = BABYLON.Vector3.Zero();\n _this._pivotMatrix = BABYLON.Matrix.Identity();\n _this._postMultiplyPivotMatrix = false;\n _this._isWorldMatrixFrozen = false;\n /**\n * An event triggered after the world matrix is updated\n */\n _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();\n _this._nonUniformScaling = false;\n if (isPure) {\n _this.getScene().addTransformNode(_this);\n }\n return _this;\n }\n /**\n * Gets a string idenfifying the name of the class\n * @returns \"TransformNode\" string\n */\n TransformNode.prototype.getClassName = function () {\n return \"TransformNode\";\n };\n Object.defineProperty(TransformNode.prototype, \"rotation\", {\n /**\n * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.\n * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!\n * Default : (0.0, 0.0, 0.0)\n */\n get: function () {\n return this._rotation;\n },\n set: function (newRotation) {\n this._rotation = newRotation;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TransformNode.prototype, \"scaling\", {\n /**\n * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.\n * Default : (1.0, 1.0, 1.0)\n */\n get: function () {\n return this._scaling;\n },\n /**\n * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.\n * Default : (1.0, 1.0, 1.0)\n */\n set: function (newScaling) {\n this._scaling = newScaling;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TransformNode.prototype, \"rotationQuaternion\", {\n /**\n * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.\n * It's null by default.\n * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\\ is then ignored and set to (0.0, 0.0, 0.0)\n */\n get: function () {\n return this._rotationQuaternion;\n },\n set: function (quaternion) {\n this._rotationQuaternion = quaternion;\n //reset the rotation vector. \n if (quaternion && this.rotation.length()) {\n this.rotation.copyFromFloats(0.0, 0.0, 0.0);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TransformNode.prototype, \"forward\", {\n /**\n * The forward direction of that transform in world space.\n */\n get: function () {\n return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TransformNode.prototype, \"up\", {\n /**\n * The up direction of that transform in world space.\n */\n get: function () {\n return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TransformNode.prototype, \"right\", {\n /**\n * The right direction of that transform in world space.\n */\n get: function () {\n return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the latest update of the World matrix\n * Returns a Matrix.\n */\n TransformNode.prototype.getWorldMatrix = function () {\n if (this._currentRenderId !== this.getScene().getRenderId()) {\n this.computeWorldMatrix();\n }\n return this._worldMatrix;\n };\n /** @hidden */\n TransformNode.prototype._getWorldMatrixDeterminant = function () {\n return this._worldMatrixDeterminant;\n };\n Object.defineProperty(TransformNode.prototype, \"worldMatrixFromCache\", {\n /**\n * Returns directly the latest state of the mesh World matrix.\n * A Matrix is returned.\n */\n get: function () {\n return this._worldMatrix;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Copies the paramater passed Matrix into the mesh Pose matrix.\n * Returns the TransformNode.\n */\n TransformNode.prototype.updatePoseMatrix = function (matrix) {\n this._poseMatrix.copyFrom(matrix);\n return this;\n };\n /**\n * Returns the mesh Pose matrix.\n * Returned object : Matrix\n */\n TransformNode.prototype.getPoseMatrix = function () {\n return this._poseMatrix;\n };\n TransformNode.prototype._isSynchronized = function () {\n if (this._isDirty) {\n return false;\n }\n if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)\n return false;\n if (this._cache.pivotMatrixUpdated) {\n return false;\n }\n if (this.infiniteDistance) {\n return false;\n }\n if (!this._cache.position.equals(this.position))\n return false;\n if (this.rotationQuaternion) {\n if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))\n return false;\n }\n if (!this._cache.rotation.equals(this.rotation))\n return false;\n if (!this._cache.scaling.equals(this.scaling))\n return false;\n return true;\n };\n TransformNode.prototype._initCache = function () {\n _super.prototype._initCache.call(this);\n this._cache.localMatrixUpdated = false;\n this._cache.position = BABYLON.Vector3.Zero();\n this._cache.scaling = BABYLON.Vector3.Zero();\n this._cache.rotation = BABYLON.Vector3.Zero();\n this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);\n this._cache.billboardMode = -1;\n };\n TransformNode.prototype.markAsDirty = function (property) {\n if (property === \"rotation\") {\n this.rotationQuaternion = null;\n }\n this._currentRenderId = Number.MAX_VALUE;\n this._isDirty = true;\n return this;\n };\n Object.defineProperty(TransformNode.prototype, \"absolutePosition\", {\n /**\n * Returns the current mesh absolute position.\n * Retuns a Vector3.\n */\n get: function () {\n return this._absolutePosition;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Sets a new matrix to apply before all other transformation\n * @param matrix defines the transform matrix\n * @returns the current TransformNode\n */\n TransformNode.prototype.setPreTransformMatrix = function (matrix) {\n return this.setPivotMatrix(matrix, false);\n };\n /**\n * Sets a new pivot matrix to the current node\n * @param matrix defines the new pivot matrix to use\n * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect\n * @returns the current TransformNode\n */\n TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {\n if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }\n this._pivotMatrix = matrix.clone();\n this._cache.pivotMatrixUpdated = true;\n this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;\n if (this._postMultiplyPivotMatrix) {\n if (!this._pivotMatrixInverse) {\n this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);\n }\n else {\n this._pivotMatrix.invertToRef(this._pivotMatrixInverse);\n }\n }\n return this;\n };\n /**\n * Returns the mesh pivot matrix.\n * Default : Identity.\n * A Matrix is returned.\n */\n TransformNode.prototype.getPivotMatrix = function () {\n return this._pivotMatrix;\n };\n /**\n * Prevents the World matrix to be computed any longer.\n * Returns the TransformNode.\n */\n TransformNode.prototype.freezeWorldMatrix = function () {\n this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily\n this.computeWorldMatrix(true);\n this._isWorldMatrixFrozen = true;\n return this;\n };\n /**\n * Allows back the World matrix computation.\n * Returns the TransformNode.\n */\n TransformNode.prototype.unfreezeWorldMatrix = function () {\n this._isWorldMatrixFrozen = false;\n this.computeWorldMatrix(true);\n return this;\n };\n Object.defineProperty(TransformNode.prototype, \"isWorldMatrixFrozen\", {\n /**\n * True if the World matrix has been frozen.\n * Returns a boolean.\n */\n get: function () {\n return this._isWorldMatrixFrozen;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Retuns the mesh absolute position in the World.\n * Returns a Vector3.\n */\n TransformNode.prototype.getAbsolutePosition = function () {\n this.computeWorldMatrix();\n return this._absolutePosition;\n };\n /**\n * Sets the mesh absolute position in the World from a Vector3 or an Array(3).\n * Returns the TransformNode.\n */\n TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {\n if (!absolutePosition) {\n return this;\n }\n var absolutePositionX;\n var absolutePositionY;\n var absolutePositionZ;\n if (absolutePosition.x === undefined) {\n if (arguments.length < 3) {\n return this;\n }\n absolutePositionX = arguments[0];\n absolutePositionY = arguments[1];\n absolutePositionZ = arguments[2];\n }\n else {\n absolutePositionX = absolutePosition.x;\n absolutePositionY = absolutePosition.y;\n absolutePositionZ = absolutePosition.z;\n }\n if (this.parent) {\n var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();\n invertParentWorldMatrix.invert();\n var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);\n this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);\n }\n else {\n this.position.x = absolutePositionX;\n this.position.y = absolutePositionY;\n this.position.z = absolutePositionZ;\n }\n return this;\n };\n /**\n * Sets the mesh position in its local space.\n * Returns the TransformNode.\n */\n TransformNode.prototype.setPositionWithLocalVector = function (vector3) {\n this.computeWorldMatrix();\n this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);\n return this;\n };\n /**\n * Returns the mesh position in the local space from the current World matrix values.\n * Returns a new Vector3.\n */\n TransformNode.prototype.getPositionExpressedInLocalSpace = function () {\n this.computeWorldMatrix();\n var invLocalWorldMatrix = this._localWorld.clone();\n invLocalWorldMatrix.invert();\n return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);\n };\n /**\n * Translates the mesh along the passed Vector3 in its local space.\n * Returns the TransformNode.\n */\n TransformNode.prototype.locallyTranslate = function (vector3) {\n this.computeWorldMatrix(true);\n this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);\n return this;\n };\n /**\n * Orients a mesh towards a target point. Mesh must be drawn facing user.\n * @param targetPoint the position (must be in same space as current mesh) to look at\n * @param yawCor optional yaw (y-axis) correction in radians\n * @param pitchCor optional pitch (x-axis) correction in radians\n * @param rollCor optional roll (z-axis) correction in radians\n * @param space the choosen space of the target\n * @returns the TransformNode.\n */\n TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {\n if (yawCor === void 0) { yawCor = 0; }\n if (pitchCor === void 0) { pitchCor = 0; }\n if (rollCor === void 0) { rollCor = 0; }\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n var dv = TransformNode._lookAtVectorCache;\n var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();\n targetPoint.subtractToRef(pos, dv);\n var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;\n var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);\n var pitch = Math.atan2(dv.y, len);\n if (this.rotationQuaternion) {\n BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);\n }\n else {\n this.rotation.x = pitch + pitchCor;\n this.rotation.y = yaw + yawCor;\n this.rotation.z = rollCor;\n }\n return this;\n };\n /**\n * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.\n * This Vector3 is expressed in the World space.\n */\n TransformNode.prototype.getDirection = function (localAxis) {\n var result = BABYLON.Vector3.Zero();\n this.getDirectionToRef(localAxis, result);\n return result;\n };\n /**\n * Sets the Vector3 \"result\" as the rotated Vector3 \"localAxis\" in the same rotation than the mesh.\n * localAxis is expressed in the mesh local space.\n * result is computed in the Wordl space from the mesh World matrix.\n * Returns the TransformNode.\n */\n TransformNode.prototype.getDirectionToRef = function (localAxis, result) {\n BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);\n return this;\n };\n /**\n * Sets a new pivot point to the current node\n * @param point defines the new pivot point to use\n * @param space defines if the point is in world or local space (local by default)\n * @returns the current TransformNode\n */\n TransformNode.prototype.setPivotPoint = function (point, space) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (this.getScene().getRenderId() == 0) {\n this.computeWorldMatrix(true);\n }\n var wm = this.getWorldMatrix();\n if (space == BABYLON.Space.WORLD) {\n var tmat = BABYLON.Tmp.Matrix[0];\n wm.invertToRef(tmat);\n point = BABYLON.Vector3.TransformCoordinates(point, tmat);\n }\n return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);\n };\n /**\n * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.\n */\n TransformNode.prototype.getPivotPoint = function () {\n var point = BABYLON.Vector3.Zero();\n this.getPivotPointToRef(point);\n return point;\n };\n /**\n * Sets the passed Vector3 \"result\" with the coordinates of the mesh pivot point in the local space.\n * Returns the TransformNode.\n */\n TransformNode.prototype.getPivotPointToRef = function (result) {\n result.x = -this._pivotMatrix.m[12];\n result.y = -this._pivotMatrix.m[13];\n result.z = -this._pivotMatrix.m[14];\n return this;\n };\n /**\n * Returns a new Vector3 set with the mesh pivot point World coordinates.\n */\n TransformNode.prototype.getAbsolutePivotPoint = function () {\n var point = BABYLON.Vector3.Zero();\n this.getAbsolutePivotPointToRef(point);\n return point;\n };\n /**\n * Sets the Vector3 \"result\" coordinates with the mesh pivot point World coordinates.\n * Returns the TransformNode.\n */\n TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {\n result.x = this._pivotMatrix.m[12];\n result.y = this._pivotMatrix.m[13];\n result.z = this._pivotMatrix.m[14];\n this.getPivotPointToRef(result);\n BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);\n return this;\n };\n /**\n * Defines the passed node as the parent of the current node.\n * The node will remain exactly where it is and its position / rotation will be updated accordingly\n * Returns the TransformNode.\n */\n TransformNode.prototype.setParent = function (node) {\n if (!node && !this.parent) {\n return this;\n }\n if (!node) {\n var rotation = BABYLON.Tmp.Quaternion[0];\n var position = BABYLON.Tmp.Vector3[0];\n var scale = BABYLON.Tmp.Vector3[1];\n if (this.parent && this.parent.computeWorldMatrix) {\n this.parent.computeWorldMatrix(true);\n }\n this.computeWorldMatrix(true);\n this.getWorldMatrix().decompose(scale, rotation, position);\n if (this.rotationQuaternion) {\n this.rotationQuaternion.copyFrom(rotation);\n }\n else {\n rotation.toEulerAnglesToRef(this.rotation);\n }\n this.scaling.x = scale.x;\n this.scaling.y = scale.y;\n this.scaling.z = scale.z;\n this.position.x = position.x;\n this.position.y = position.y;\n this.position.z = position.z;\n }\n else {\n var rotation = BABYLON.Tmp.Quaternion[0];\n var position = BABYLON.Tmp.Vector3[0];\n var scale = BABYLON.Tmp.Vector3[1];\n var diffMatrix = BABYLON.Tmp.Matrix[0];\n var invParentMatrix = BABYLON.Tmp.Matrix[1];\n this.computeWorldMatrix(true);\n node.computeWorldMatrix(true);\n node.getWorldMatrix().invertToRef(invParentMatrix);\n this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);\n diffMatrix.decompose(scale, rotation, position);\n if (this.rotationQuaternion) {\n this.rotationQuaternion.copyFrom(rotation);\n }\n else {\n rotation.toEulerAnglesToRef(this.rotation);\n }\n this.position.x = position.x;\n this.position.y = position.y;\n this.position.z = position.z;\n this.scaling.x = scale.x;\n this.scaling.y = scale.y;\n this.scaling.z = scale.z;\n }\n this.parent = node;\n return this;\n };\n Object.defineProperty(TransformNode.prototype, \"nonUniformScaling\", {\n get: function () {\n return this._nonUniformScaling;\n },\n enumerable: true,\n configurable: true\n });\n TransformNode.prototype._updateNonUniformScalingState = function (value) {\n if (this._nonUniformScaling === value) {\n return false;\n }\n this._nonUniformScaling = value;\n return true;\n };\n /**\n * Attach the current TransformNode to another TransformNode associated with a bone\n * @param bone Bone affecting the TransformNode\n * @param affectedTransformNode TransformNode associated with the bone\n */\n TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {\n this._transformToBoneReferal = affectedTransformNode;\n this.parent = bone;\n if (bone.getWorldMatrix().determinant() < 0) {\n this.scalingDeterminant *= -1;\n }\n return this;\n };\n TransformNode.prototype.detachFromBone = function () {\n if (!this.parent) {\n return this;\n }\n if (this.parent.getWorldMatrix().determinant() < 0) {\n this.scalingDeterminant *= -1;\n }\n this._transformToBoneReferal = null;\n this.parent = null;\n return this;\n };\n /**\n * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.\n * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.\n * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.\n * The passed axis is also normalized.\n * Returns the TransformNode.\n */\n TransformNode.prototype.rotate = function (axis, amount, space) {\n axis.normalize();\n if (!this.rotationQuaternion) {\n this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);\n this.rotation = BABYLON.Vector3.Zero();\n }\n var rotationQuaternion;\n if (!space || space === BABYLON.Space.LOCAL) {\n rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);\n this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);\n }\n else {\n if (this.parent) {\n var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();\n invertParentWorldMatrix.invert();\n axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);\n }\n rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);\n rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n }\n return this;\n };\n /**\n * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.\n * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.\n * The passed axis is also normalized.\n * Returns the TransformNode.\n * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm\n */\n TransformNode.prototype.rotateAround = function (point, axis, amount) {\n axis.normalize();\n if (!this.rotationQuaternion) {\n this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);\n this.rotation.copyFromFloats(0, 0, 0);\n }\n point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);\n BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);\n BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);\n BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);\n BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);\n BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);\n BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);\n this.position.addInPlace(BABYLON.Tmp.Vector3[1]);\n BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n return this;\n };\n /**\n * Translates the mesh along the axis vector for the passed distance in the given space.\n * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.\n * Returns the TransformNode.\n */\n TransformNode.prototype.translate = function (axis, distance, space) {\n var displacementVector = axis.scale(distance);\n if (!space || space === BABYLON.Space.LOCAL) {\n var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);\n this.setPositionWithLocalVector(tempV3);\n }\n else {\n this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));\n }\n return this;\n };\n /**\n * Adds a rotation step to the mesh current rotation.\n * x, y, z are Euler angles expressed in radians.\n * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.\n * This means this rotation is made in the mesh local space only.\n * It's useful to set a custom rotation order different from the BJS standard one YXZ.\n * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.\n * ```javascript\n * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);\n * ```\n * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.\n * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.\n * Returns the TransformNode.\n */\n TransformNode.prototype.addRotation = function (x, y, z) {\n var rotationQuaternion;\n if (this.rotationQuaternion) {\n rotationQuaternion = this.rotationQuaternion;\n }\n else {\n rotationQuaternion = BABYLON.Tmp.Quaternion[1];\n BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);\n }\n var accumulation = BABYLON.Tmp.Quaternion[0];\n BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);\n rotationQuaternion.multiplyInPlace(accumulation);\n if (!this.rotationQuaternion) {\n rotationQuaternion.toEulerAnglesToRef(this.rotation);\n }\n return this;\n };\n /**\n * Computes the mesh World matrix and returns it.\n * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.\n * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.\n * If the parameter `force`is set to `true`, the actual computation is done.\n * Returns the mesh World Matrix.\n */\n TransformNode.prototype.computeWorldMatrix = function (force) {\n if (this._isWorldMatrixFrozen) {\n return this._worldMatrix;\n }\n if (!force && this.isSynchronized(true)) {\n this._currentRenderId = this.getScene().getRenderId();\n return this._worldMatrix;\n }\n this._cache.position.copyFrom(this.position);\n this._cache.scaling.copyFrom(this.scaling);\n this._cache.pivotMatrixUpdated = false;\n this._cache.billboardMode = this.billboardMode;\n this._currentRenderId = this.getScene().getRenderId();\n this._childRenderId = this.getScene().getRenderId();\n this._isDirty = false;\n // Scaling\n BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);\n // Rotation\n //rotate, if quaternion is set and rotation was used\n if (this.rotationQuaternion) {\n var len = this.rotation.length();\n if (len) {\n this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));\n this.rotation.copyFromFloats(0, 0, 0);\n }\n }\n if (this.rotationQuaternion) {\n this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);\n this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);\n }\n else {\n BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);\n this._cache.rotation.copyFrom(this.rotation);\n }\n // Translation\n var camera = this.getScene().activeCamera;\n if (this.infiniteDistance && !this.parent && camera) {\n var cameraWorldMatrix = camera.getWorldMatrix();\n var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);\n BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);\n }\n else {\n BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);\n }\n // Composing transformations\n this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);\n BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);\n // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)\n if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {\n // Need to decompose each rotation here\n var currentPosition = BABYLON.Tmp.Vector3[3];\n if (this.parent && this.parent.getWorldMatrix) {\n if (this._transformToBoneReferal) {\n this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);\n BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);\n }\n else {\n BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);\n }\n }\n else {\n currentPosition.copyFrom(this.position);\n }\n currentPosition.subtractInPlace(camera.globalPosition);\n var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {\n finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);\n }\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {\n finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);\n }\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {\n finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);\n }\n BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);\n }\n else {\n BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());\n BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);\n BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);\n }\n BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);\n BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);\n }\n // Post multiply inverse of pivotMatrix\n if (this._postMultiplyPivotMatrix) {\n BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);\n }\n // Local world\n BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);\n // Parent\n if (this.parent && this.parent.getWorldMatrix) {\n if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {\n if (this._transformToBoneReferal) {\n this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);\n BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);\n }\n else {\n BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());\n }\n this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);\n BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);\n this._worldMatrix.copyFrom(this._localWorld);\n this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);\n }\n else {\n if (this._transformToBoneReferal) {\n this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);\n BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);\n }\n else {\n this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);\n }\n }\n this._markSyncedWithParent();\n }\n else {\n this._worldMatrix.copyFrom(this._localWorld);\n }\n // Normal matrix\n if (!this.ignoreNonUniformScaling) {\n if (this.scaling.isNonUniform) {\n this._updateNonUniformScalingState(true);\n }\n else if (this.parent && this.parent._nonUniformScaling) {\n this._updateNonUniformScalingState(this.parent._nonUniformScaling);\n }\n else {\n this._updateNonUniformScalingState(false);\n }\n }\n else {\n this._updateNonUniformScalingState(false);\n }\n this._afterComputeWorldMatrix();\n // Absolute position\n this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);\n // Callbacks\n this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);\n if (!this._poseMatrix) {\n this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);\n }\n // Cache the determinant\n this._worldMatrixDeterminant = this._worldMatrix.determinant();\n return this._worldMatrix;\n };\n TransformNode.prototype._afterComputeWorldMatrix = function () {\n };\n /**\n * If you'd like to be called back after the mesh position, rotation or scaling has been updated.\n * @param func: callback function to add\n *\n * Returns the TransformNode.\n */\n TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {\n this.onAfterWorldMatrixUpdateObservable.add(func);\n return this;\n };\n /**\n * Removes a registered callback function.\n * Returns the TransformNode.\n */\n TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {\n this.onAfterWorldMatrixUpdateObservable.removeCallback(func);\n return this;\n };\n /**\n * Clone the current transform node\n * Returns the new transform node\n * @param name Name of the new clone\n * @param newParent New parent for the clone\n * @param doNotCloneChildren Do not clone children hierarchy\n */\n TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {\n var _this = this;\n var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);\n result.name = name;\n result.id = name;\n if (newParent) {\n result.parent = newParent;\n }\n if (!doNotCloneChildren) {\n // Children\n var directDescendants = this.getDescendants(true);\n for (var index = 0; index < directDescendants.length; index++) {\n var child = directDescendants[index];\n if (child.clone) {\n child.clone(name + \".\" + child.name, result);\n }\n }\n }\n return result;\n };\n TransformNode.prototype.serialize = function (currentSerializationObject) {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);\n serializationObject.type = this.getClassName();\n // Parent\n if (this.parent) {\n serializationObject.parentId = this.parent.id;\n }\n if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {\n serializationObject.tags = BABYLON.Tags.GetTags(this);\n }\n serializationObject.localMatrix = this.getPivotMatrix().asArray();\n serializationObject.isEnabled = this.isEnabled();\n // Parent\n if (this.parent) {\n serializationObject.parentId = this.parent.id;\n }\n return serializationObject;\n };\n // Statics\n /**\n * Returns a new TransformNode object parsed from the source provided.\n * The parameter `parsedMesh` is the source.\n * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with\n */\n TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {\n var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);\n }\n if (parsedTransformNode.localMatrix) {\n transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));\n }\n else if (parsedTransformNode.pivotMatrix) {\n transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));\n }\n transformNode.setEnabled(parsedTransformNode.isEnabled);\n // Parent\n if (parsedTransformNode.parentId) {\n transformNode._waitingParentId = parsedTransformNode.parentId;\n }\n return transformNode;\n };\n /**\n * Releases resources associated with this transform node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from scene\n this.getScene().removeTransformNode(this);\n this.onAfterWorldMatrixUpdateObservable.clear();\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n // Statics\n TransformNode.BILLBOARDMODE_NONE = 0;\n TransformNode.BILLBOARDMODE_X = 1;\n TransformNode.BILLBOARDMODE_Y = 2;\n TransformNode.BILLBOARDMODE_Z = 4;\n TransformNode.BILLBOARDMODE_ALL = 7;\n TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);\n TransformNode._rotationAxisCache = new BABYLON.Quaternion();\n __decorate([\n BABYLON.serializeAsVector3()\n ], TransformNode.prototype, \"_rotation\", void 0);\n __decorate([\n BABYLON.serializeAsQuaternion()\n ], TransformNode.prototype, \"_rotationQuaternion\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], TransformNode.prototype, \"_scaling\", void 0);\n __decorate([\n BABYLON.serialize()\n ], TransformNode.prototype, \"billboardMode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], TransformNode.prototype, \"scalingDeterminant\", void 0);\n __decorate([\n BABYLON.serialize()\n ], TransformNode.prototype, \"infiniteDistance\", void 0);\n __decorate([\n BABYLON.serialize()\n ], TransformNode.prototype, \"ignoreNonUniformScaling\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], TransformNode.prototype, \"position\", void 0);\n return TransformNode;\n }(BABYLON.Node));\n BABYLON.TransformNode = TransformNode;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.transformNode.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to store all common mesh properties\n */\n var AbstractMesh = /** @class */ (function (_super) {\n __extends(AbstractMesh, _super);\n // Constructor\n /**\n * Creates a new AbstractMesh\n * @param name defines the name of the mesh\n * @param scene defines the hosting scene\n */\n function AbstractMesh(name, scene) {\n if (scene === void 0) { scene = null; }\n var _this = _super.call(this, name, scene, false) || this;\n _this._facetNb = 0; // facet number\n _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space \n _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box\n _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?\n _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation\n _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data\n _this._subDiv = {\n max: 1,\n X: 1,\n Y: 1,\n Z: 1\n };\n _this._facetDepthSort = false; // is the facet depth sort to be computed\n _this._facetDepthSortEnabled = false; // is the facet depth sort initialized\n // Events\n /**\n * An event triggered when this mesh collides with another one\n */\n _this.onCollideObservable = new BABYLON.Observable();\n /**\n * An event triggered when the collision's position changes\n */\n _this.onCollisionPositionChangeObservable = new BABYLON.Observable();\n /**\n * An event triggered when material is changed\n */\n _this.onMaterialChangedObservable = new BABYLON.Observable();\n // Properties\n /**\n * Gets or sets the orientation for POV movement & rotation\n */\n _this.definedFacingForward = true;\n /**\n * This property determines the type of occlusion query algorithm to run in WebGl, you can use:\n * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.\n * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.\n * @see http://doc.babylonjs.com/features/occlusionquery\n */\n _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;\n /**\n * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:\n * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.\n * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.\n * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.\n * @see http://doc.babylonjs.com/features/occlusionquery\n */\n _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;\n /**\n * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.\n * The default value is -1 which means don't break the query and wait till the result\n * @see http://doc.babylonjs.com/features/occlusionquery\n */\n _this.occlusionRetryCount = -1;\n /** @hidden */\n _this._occlusionInternalRetryCounter = 0;\n /** @hidden */\n _this._isOccluded = false;\n /** @hidden */\n _this._isOcclusionQueryInProgress = false;\n _this._visibility = 1.0;\n /** Gets or sets the alpha index used to sort transparent meshes\n * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index\n */\n _this.alphaIndex = Number.MAX_VALUE;\n /**\n * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true\n */\n _this.isVisible = true;\n /**\n * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true\n */\n _this.isPickable = true;\n /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */\n _this.showSubMeshesBoundingBox = false;\n /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)\n * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares\n */\n _this.isBlocker = false;\n /**\n * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)\n */\n _this.enablePointerMoveEvents = false;\n /**\n * Specifies the rendering group id for this mesh (0 by default)\n * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups\n */\n _this.renderingGroupId = 0;\n _this._receiveShadows = false;\n /**\n * Gets or sets a boolean indicating if the outline must be rendered as well\n * @see https://www.babylonjs-playground.com/#10WJ5S#3\n */\n _this.renderOutline = false;\n /** Defines color to use when rendering outline */\n _this.outlineColor = BABYLON.Color3.Red();\n /** Define width to use when rendering outline */\n _this.outlineWidth = 0.02;\n /**\n * Gets or sets a boolean indicating if the overlay must be rendered as well\n * @see https://www.babylonjs-playground.com/#10WJ5S#2\n */\n _this.renderOverlay = false;\n /** Defines color to use when rendering overlay */\n _this.overlayColor = BABYLON.Color3.Red();\n /** Defines alpha to use when rendering overlay */\n _this.overlayAlpha = 0.5;\n _this._hasVertexAlpha = false;\n _this._useVertexColors = true;\n _this._computeBonesUsingShaders = true;\n _this._numBoneInfluencers = 4;\n _this._applyFog = true;\n /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */\n _this.useOctreeForRenderingSelection = true;\n /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */\n _this.useOctreeForPicking = true;\n /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */\n _this.useOctreeForCollisions = true;\n _this._layerMask = 0x0FFFFFFF;\n /**\n * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)\n */\n _this.alwaysSelectAsActiveMesh = false;\n /**\n * Gets or sets the current action manager\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions\n */\n _this.actionManager = null;\n /**\n * Gets or sets impostor used for physic simulation\n * @see http://doc.babylonjs.com/features/physics_engine\n */\n _this.physicsImpostor = null;\n // Collisions\n _this._checkCollisions = false;\n _this._collisionMask = -1;\n _this._collisionGroup = -1;\n /**\n * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */\n _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);\n /**\n * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */\n _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);\n _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);\n _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);\n // Edges\n /**\n * Defines edge width used when edgesRenderer is enabled\n * @see https://www.babylonjs-playground.com/#10OJSG#13\n */\n _this.edgesWidth = 1;\n /**\n * Defines edge color used when edgesRenderer is enabled\n * @see https://www.babylonjs-playground.com/#10OJSG#13\n */\n _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);\n // Cache\n _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();\n _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();\n /** @hidden */\n _this._renderId = 0;\n /** @hidden */\n _this._intersectionsInProgress = new Array();\n /** @hidden */\n _this._unIndexed = false;\n /** @hidden */\n _this._lightSources = new Array();\n _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {\n if (collidedMesh === void 0) { collidedMesh = null; }\n //TODO move this to the collision coordinator!\n if (_this.getScene().workerCollisions)\n newPosition.multiplyInPlace(_this._collider._radius);\n newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);\n if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {\n _this.position.addInPlace(_this._diffPositionForCollisions);\n }\n if (collidedMesh) {\n _this.onCollideObservable.notifyObservers(collidedMesh);\n }\n _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);\n };\n _this.getScene().addMesh(_this);\n _this._resyncLightSources();\n return _this;\n }\n Object.defineProperty(AbstractMesh, \"BILLBOARDMODE_NONE\", {\n /**\n * No billboard\n */\n get: function () {\n return BABYLON.TransformNode.BILLBOARDMODE_NONE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh, \"BILLBOARDMODE_X\", {\n /** Billboard on X axis */\n get: function () {\n return BABYLON.TransformNode.BILLBOARDMODE_X;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh, \"BILLBOARDMODE_Y\", {\n /** Billboard on Y axis */\n get: function () {\n return BABYLON.TransformNode.BILLBOARDMODE_Y;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh, \"BILLBOARDMODE_Z\", {\n /** Billboard on Z axis */\n get: function () {\n return BABYLON.TransformNode.BILLBOARDMODE_Z;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh, \"BILLBOARDMODE_ALL\", {\n /** Billboard on all axes */\n get: function () {\n return BABYLON.TransformNode.BILLBOARDMODE_ALL;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"facetNb\", {\n /**\n * Gets the number of facets in the mesh\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet\n */\n get: function () {\n return this._facetNb;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"partitioningSubdivisions\", {\n /**\n * Gets or set the number (integer) of subdivisions per axis in the partioning space\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning\n */\n get: function () {\n return this._partitioningSubdivisions;\n },\n set: function (nb) {\n this._partitioningSubdivisions = nb;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"partitioningBBoxRatio\", {\n /**\n * The ratio (float) to apply to the bouding box size to set to the partioning space.\n * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning\n */\n get: function () {\n return this._partitioningBBoxRatio;\n },\n set: function (ratio) {\n this._partitioningBBoxRatio = ratio;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"mustDepthSortFacets\", {\n /**\n * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.\n * Works only for updatable meshes.\n * Doesn't work with multi-materials\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort\n */\n get: function () {\n return this._facetDepthSort;\n },\n set: function (sort) {\n this._facetDepthSort = sort;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"facetDepthSortFrom\", {\n /**\n * The location (Vector3) where the facet depth sort must be computed from.\n * By default, the active camera position.\n * Used only when facet depth sort is enabled\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort\n */\n get: function () {\n return this._facetDepthSortFrom;\n },\n set: function (location) {\n this._facetDepthSortFrom = location;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"isFacetDataEnabled\", {\n /**\n * gets a boolean indicating if facetData is enabled\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet\n */\n get: function () {\n return this._facetDataEnabled;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n AbstractMesh.prototype._updateNonUniformScalingState = function (value) {\n if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {\n return false;\n }\n this._markSubMeshesAsMiscDirty();\n return true;\n };\n Object.defineProperty(AbstractMesh.prototype, \"onCollide\", {\n /** Set a function to call when this mesh collides with another one */\n set: function (callback) {\n if (this._onCollideObserver) {\n this.onCollideObservable.remove(this._onCollideObserver);\n }\n this._onCollideObserver = this.onCollideObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"onCollisionPositionChange\", {\n /** Set a function to call when the collision's position changes */\n set: function (callback) {\n if (this._onCollisionPositionChangeObserver) {\n this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);\n }\n this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"isOccluded\", {\n /**\n * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not\n * @see http://doc.babylonjs.com/features/occlusionquery\n */\n get: function () {\n return this._isOccluded;\n },\n set: function (value) {\n this._isOccluded = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"isOcclusionQueryInProgress\", {\n /**\n * Flag to check the progress status of the query\n * @see http://doc.babylonjs.com/features/occlusionquery\n */\n get: function () {\n return this._isOcclusionQueryInProgress;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"visibility\", {\n /**\n * Gets or sets mesh visibility between 0 and 1 (default is 1)\n */\n get: function () {\n return this._visibility;\n },\n /**\n * Gets or sets mesh visibility between 0 and 1 (default is 1)\n */\n set: function (value) {\n if (this._visibility === value) {\n return;\n }\n this._visibility = value;\n this._markSubMeshesAsMiscDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"material\", {\n /** Gets or sets current material */\n get: function () {\n return this._material;\n },\n set: function (value) {\n if (this._material === value) {\n return;\n }\n this._material = value;\n if (this.onMaterialChangedObservable.hasObservers) {\n this.onMaterialChangedObservable.notifyObservers(this);\n }\n if (!this.subMeshes) {\n return;\n }\n this._unBindEffect();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"receiveShadows\", {\n /**\n * Gets or sets a boolean indicating that this mesh can receive realtime shadows\n * @see http://doc.babylonjs.com/babylon101/shadows\n */\n get: function () {\n return this._receiveShadows;\n },\n set: function (value) {\n if (this._receiveShadows === value) {\n return;\n }\n this._receiveShadows = value;\n this._markSubMeshesAsLightDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"hasVertexAlpha\", {\n /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */\n get: function () {\n return this._hasVertexAlpha;\n },\n set: function (value) {\n if (this._hasVertexAlpha === value) {\n return;\n }\n this._hasVertexAlpha = value;\n this._markSubMeshesAsAttributesDirty();\n this._markSubMeshesAsMiscDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"useVertexColors\", {\n /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */\n get: function () {\n return this._useVertexColors;\n },\n set: function (value) {\n if (this._useVertexColors === value) {\n return;\n }\n this._useVertexColors = value;\n this._markSubMeshesAsAttributesDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"computeBonesUsingShaders\", {\n /**\n * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)\n */\n get: function () {\n return this._computeBonesUsingShaders;\n },\n set: function (value) {\n if (this._computeBonesUsingShaders === value) {\n return;\n }\n this._computeBonesUsingShaders = value;\n this._markSubMeshesAsAttributesDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"numBoneInfluencers\", {\n /** Gets or sets the number of allowed bone influences per vertex (4 by default) */\n get: function () {\n return this._numBoneInfluencers;\n },\n set: function (value) {\n if (this._numBoneInfluencers === value) {\n return;\n }\n this._numBoneInfluencers = value;\n this._markSubMeshesAsAttributesDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"applyFog\", {\n /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */\n get: function () {\n return this._applyFog;\n },\n set: function (value) {\n if (this._applyFog === value) {\n return;\n }\n this._applyFog = value;\n this._markSubMeshesAsMiscDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"layerMask\", {\n /**\n * Gets or sets the current layer mask (default is 0x0FFFFFFF)\n * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures\n */\n get: function () {\n return this._layerMask;\n },\n set: function (value) {\n if (value === this._layerMask) {\n return;\n }\n this._layerMask = value;\n this._resyncLightSources();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"collisionMask\", {\n /**\n * Gets or sets a collision mask used to mask collisions (default is -1).\n * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0\n */\n get: function () {\n return this._collisionMask;\n },\n set: function (mask) {\n this._collisionMask = !isNaN(mask) ? mask : -1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"collisionGroup\", {\n /**\n * Gets or sets the current collision group mask (-1 by default).\n * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0\n */\n get: function () {\n return this._collisionGroup;\n },\n set: function (mask) {\n this._collisionGroup = !isNaN(mask) ? mask : -1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"_positions\", {\n /** @hidden */\n get: function () {\n return null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"skeleton\", {\n get: function () {\n return this._skeleton;\n },\n /**\n * Gets or sets a skeleton to apply skining transformations\n * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons\n */\n set: function (value) {\n if (this._skeleton && this._skeleton.needInitialSkinMatrix) {\n this._skeleton._unregisterMeshWithPoseMatrix(this);\n }\n if (value && value.needInitialSkinMatrix) {\n value._registerMeshWithPoseMatrix(this);\n }\n this._skeleton = value;\n if (!this._skeleton) {\n this._bonesTransformMatrices = null;\n }\n this._markSubMeshesAsAttributesDirty();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"AbstractMesh\"\n * @returns \"AbstractMesh\"\n */\n AbstractMesh.prototype.getClassName = function () {\n return \"AbstractMesh\";\n };\n /**\n * Gets a string representation of the current mesh\n * @param fullDetails defines a boolean indicating if full details must be included\n * @returns a string representation of the current mesh\n */\n AbstractMesh.prototype.toString = function (fullDetails) {\n var ret = \"Name: \" + this.name + \", isInstance: \" + (this instanceof BABYLON.InstancedMesh ? \"YES\" : \"NO\");\n ret += \", # of submeshes: \" + (this.subMeshes ? this.subMeshes.length : 0);\n if (this._skeleton) {\n ret += \", skeleton: \" + this._skeleton.name;\n }\n if (fullDetails) {\n ret += \", billboard mode: \" + ([\"NONE\", \"X\", \"Y\", null, \"Z\", null, null, \"ALL\"])[this.billboardMode];\n ret += \", freeze wrld mat: \" + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? \"YES\" : \"NO\");\n }\n return ret;\n };\n /** @hidden */\n AbstractMesh.prototype._rebuild = function () {\n if (this._occlusionQuery) {\n this._occlusionQuery = null;\n }\n if (this._edgesRenderer) {\n this._edgesRenderer._rebuild();\n }\n if (!this.subMeshes) {\n return;\n }\n for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n subMesh._rebuild();\n }\n };\n /** @hidden */\n AbstractMesh.prototype._resyncLightSources = function () {\n this._lightSources.length = 0;\n for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {\n var light = _a[_i];\n if (!light.isEnabled()) {\n continue;\n }\n if (light.canAffectMesh(this)) {\n this._lightSources.push(light);\n }\n }\n this._markSubMeshesAsLightDirty();\n };\n /** @hidden */\n AbstractMesh.prototype._resyncLighSource = function (light) {\n var isIn = light.isEnabled() && light.canAffectMesh(this);\n var index = this._lightSources.indexOf(light);\n if (index === -1) {\n if (!isIn) {\n return;\n }\n this._lightSources.push(light);\n }\n else {\n if (isIn) {\n return;\n }\n this._lightSources.splice(index, 1);\n }\n this._markSubMeshesAsLightDirty();\n };\n /** @hidden */\n AbstractMesh.prototype._unBindEffect = function () {\n for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n subMesh.setEffect(null);\n }\n };\n /** @hidden */\n AbstractMesh.prototype._removeLightSource = function (light) {\n var index = this._lightSources.indexOf(light);\n if (index === -1) {\n return;\n }\n this._lightSources.splice(index, 1);\n this._markSubMeshesAsLightDirty();\n };\n AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {\n if (!this.subMeshes) {\n return;\n }\n for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n if (subMesh._materialDefines) {\n func(subMesh._materialDefines);\n }\n }\n };\n /** @hidden */\n AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {\n this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });\n };\n /** @hidden */\n AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {\n this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });\n };\n /** @hidden */\n AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {\n if (!this.subMeshes) {\n return;\n }\n for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n var material = subMesh.getMaterial();\n if (material) {\n material.markAsDirty(BABYLON.Material.MiscDirtyFlag);\n }\n }\n };\n Object.defineProperty(AbstractMesh.prototype, \"scaling\", {\n /**\n * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)\n */\n get: function () {\n return this._scaling;\n },\n set: function (newScaling) {\n this._scaling = newScaling;\n if (this.physicsImpostor) {\n this.physicsImpostor.forceUpdate();\n }\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n /**\n * Disables the mesh edge rendering mode\n * @returns the currentAbstractMesh\n */\n AbstractMesh.prototype.disableEdgesRendering = function () {\n if (this._edgesRenderer) {\n this._edgesRenderer.dispose();\n this._edgesRenderer = null;\n }\n return this;\n };\n /**\n * Enables the edge rendering mode on the mesh.\n * This mode makes the mesh edges visible\n * @param epsilon defines the maximal distance between two angles to detect a face\n * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces\n * @returns the currentAbstractMesh\n * @see https://www.babylonjs-playground.com/#19O9TU#0\n */\n AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {\n if (epsilon === void 0) { epsilon = 0.95; }\n if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }\n this.disableEdgesRendering();\n this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);\n return this;\n };\n Object.defineProperty(AbstractMesh.prototype, \"edgesRenderer\", {\n /**\n * Gets the edgesRenderer associated with the mesh\n */\n get: function () {\n return this._edgesRenderer;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"isBlocked\", {\n /**\n * Returns true if the mesh is blocked. Implemented by child classes\n */\n get: function () {\n return false;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the mesh itself by default. Implemented by child classes\n * @param camera defines the camera to use to pick the right LOD level\n * @returns the currentAbstractMesh\n */\n AbstractMesh.prototype.getLOD = function (camera) {\n return this;\n };\n /**\n * Returns 0 by default. Implemented by child classes\n * @returns an integer\n */\n AbstractMesh.prototype.getTotalVertices = function () {\n return 0;\n };\n /**\n * Returns null by default. Implemented by child classes\n * @returns null\n */\n AbstractMesh.prototype.getIndices = function () {\n return null;\n };\n /**\n * Returns the array of the requested vertex data kind. Implemented by child classes\n * @param kind defines the vertex data kind to use\n * @returns null\n */\n AbstractMesh.prototype.getVerticesData = function (kind) {\n return null;\n };\n /**\n * Sets the vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.\n * Note that a new underlying VertexBuffer object is created each call.\n * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.\n * @param kind defines vertex data kind:\n * * BABYLON.VertexBuffer.PositionKind\n * * BABYLON.VertexBuffer.UVKind\n * * BABYLON.VertexBuffer.UV2Kind\n * * BABYLON.VertexBuffer.UV3Kind\n * * BABYLON.VertexBuffer.UV4Kind\n * * BABYLON.VertexBuffer.UV5Kind\n * * BABYLON.VertexBuffer.UV6Kind\n * * BABYLON.VertexBuffer.ColorKind\n * * BABYLON.VertexBuffer.MatricesIndicesKind\n * * BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * * BABYLON.VertexBuffer.MatricesWeightsKind\n * * BABYLON.VertexBuffer.MatricesWeightsExtraKind\n * @param data defines the data source\n * @param updatable defines if the data must be flagged as updatable (or static)\n * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind\n * @returns the current mesh\n */\n AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {\n return this;\n };\n /**\n * Updates the existing vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, it is simply returned as it is.\n * @param kind defines vertex data kind:\n * * BABYLON.VertexBuffer.PositionKind\n * * BABYLON.VertexBuffer.UVKind\n * * BABYLON.VertexBuffer.UV2Kind\n * * BABYLON.VertexBuffer.UV3Kind\n * * BABYLON.VertexBuffer.UV4Kind\n * * BABYLON.VertexBuffer.UV5Kind\n * * BABYLON.VertexBuffer.UV6Kind\n * * BABYLON.VertexBuffer.ColorKind\n * * BABYLON.VertexBuffer.MatricesIndicesKind\n * * BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * * BABYLON.VertexBuffer.MatricesWeightsKind\n * * BABYLON.VertexBuffer.MatricesWeightsExtraKind\n * @param data defines the data source\n * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed\n * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh\n * @returns the current mesh\n */\n AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {\n return this;\n };\n /**\n * Sets the mesh indices,\n * If the mesh has no geometry, a new Geometry object is created and set to the mesh.\n * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)\n * @param totalVertices Defines the total number of vertices\n * @returns the current mesh\n */\n AbstractMesh.prototype.setIndices = function (indices, totalVertices) {\n return this;\n };\n /**\n * Gets a boolean indicating if specific vertex data is present\n * @param kind defines the vertex data kind to use\n * @returns true is data kind is present\n */\n AbstractMesh.prototype.isVerticesDataPresent = function (kind) {\n return false;\n };\n /**\n * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined\n * @returns a BoundingInfo\n */\n AbstractMesh.prototype.getBoundingInfo = function () {\n if (this._masterMesh) {\n return this._masterMesh.getBoundingInfo();\n }\n if (!this._boundingInfo) {\n // this._boundingInfo is being created here\n this._updateBoundingInfo();\n }\n // cannot be null.\n return this._boundingInfo;\n };\n /**\n * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)\n * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box\n * @returns the current mesh\n */\n AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {\n if (includeDescendants === void 0) { includeDescendants = true; }\n var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);\n var sizeVec = boundingVectors.max.subtract(boundingVectors.min);\n var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);\n if (maxDimension === 0) {\n return this;\n }\n var scale = 1 / maxDimension;\n this.scaling.scaleInPlace(scale);\n return this;\n };\n /**\n * Overwrite the current bounding info\n * @param boundingInfo defines the new bounding info\n * @returns the current mesh\n */\n AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {\n this._boundingInfo = boundingInfo;\n return this;\n };\n Object.defineProperty(AbstractMesh.prototype, \"useBones\", {\n /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */\n get: function () {\n return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n AbstractMesh.prototype._preActivate = function () {\n };\n /** @hidden */\n AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {\n };\n /** @hidden */\n AbstractMesh.prototype._activate = function (renderId) {\n this._renderId = renderId;\n };\n /**\n * Gets the current world matrix\n * @returns a Matrix\n */\n AbstractMesh.prototype.getWorldMatrix = function () {\n if (this._masterMesh) {\n return this._masterMesh.getWorldMatrix();\n }\n return _super.prototype.getWorldMatrix.call(this);\n };\n /** @hidden */\n AbstractMesh.prototype._getWorldMatrixDeterminant = function () {\n if (this._masterMesh) {\n return this._masterMesh._getWorldMatrixDeterminant();\n }\n return _super.prototype._getWorldMatrixDeterminant.call(this);\n };\n // ================================== Point of View Movement =================================\n /**\n * Perform relative position change from the point of view of behind the front of the mesh.\n * This is performed taking into account the meshes current rotation, so you do not have to care.\n * Supports definition of mesh facing forward or backward\n * @param amountRight defines the distance on the right axis\n * @param amountUp defines the distance on the up axis\n * @param amountForward defines the distance on the forward axis\n * @returns the current mesh\n */\n AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {\n this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));\n return this;\n };\n /**\n * Calculate relative position change from the point of view of behind the front of the mesh.\n * This is performed taking into account the meshes current rotation, so you do not have to care.\n * Supports definition of mesh facing forward or backward\n * @param amountRight defines the distance on the right axis\n * @param amountUp defines the distance on the up axis\n * @param amountForward defines the distance on the forward axis\n * @returns the new displacement vector\n */\n AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {\n var rotMatrix = new BABYLON.Matrix();\n var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);\n rotQuaternion.toRotationMatrix(rotMatrix);\n var translationDelta = BABYLON.Vector3.Zero();\n var defForwardMult = this.definedFacingForward ? -1 : 1;\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);\n return translationDelta;\n };\n // ================================== Point of View Rotation =================================\n /**\n * Perform relative rotation change from the point of view of behind the front of the mesh.\n * Supports definition of mesh facing forward or backward\n * @param flipBack defines the flip\n * @param twirlClockwise defines the twirl\n * @param tiltRight defines the tilt\n * @returns the current mesh\n */\n AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {\n this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));\n return this;\n };\n /**\n * Calculate relative rotation change from the point of view of behind the front of the mesh.\n * Supports definition of mesh facing forward or backward.\n * @param flipBack defines the flip\n * @param twirlClockwise defines the twirl\n * @param tiltRight defines the tilt\n * @returns the new rotation vector\n */\n AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {\n var defForwardMult = this.definedFacingForward ? 1 : -1;\n return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);\n };\n /**\n * Return the minimum and maximum world vectors of the entire hierarchy under current mesh\n * @param includeDescendants Include bounding info from descendants as well (true by default)\n * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors\n * @returns the new bounding vectors\n */\n AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {\n if (includeDescendants === void 0) { includeDescendants = true; }\n if (predicate === void 0) { predicate = null; }\n // Ensures that all world matrix will be recomputed.\n this.getScene().incrementRenderId();\n this.computeWorldMatrix(true);\n var min;\n var max;\n var boundingInfo = this.getBoundingInfo();\n if (!this.subMeshes) {\n min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n }\n else {\n min = boundingInfo.boundingBox.minimumWorld;\n max = boundingInfo.boundingBox.maximumWorld;\n }\n if (includeDescendants) {\n var descendants = this.getDescendants(false);\n for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {\n var descendant = descendants_1[_i];\n var childMesh = descendant;\n childMesh.computeWorldMatrix(true);\n // Filters meshes based on custom predicate function.\n if (predicate && !predicate(childMesh)) {\n continue;\n }\n //make sure we have the needed params to get mix and max\n if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {\n continue;\n }\n var childBoundingInfo = childMesh.getBoundingInfo();\n var boundingBox = childBoundingInfo.boundingBox;\n var minBox = boundingBox.minimumWorld;\n var maxBox = boundingBox.maximumWorld;\n BABYLON.Tools.CheckExtends(minBox, min, max);\n BABYLON.Tools.CheckExtends(maxBox, min, max);\n }\n }\n return {\n min: min,\n max: max\n };\n };\n /** @hidden */\n AbstractMesh.prototype._updateBoundingInfo = function () {\n this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);\n this._boundingInfo.update(this.worldMatrixFromCache);\n this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);\n return this;\n };\n /** @hidden */\n AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {\n if (!this.subMeshes) {\n return this;\n }\n for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {\n var subMesh = this.subMeshes[subIndex];\n if (!subMesh.IsGlobal) {\n subMesh.updateBoundingInfo(matrix);\n }\n }\n return this;\n };\n /** @hidden */\n AbstractMesh.prototype._afterComputeWorldMatrix = function () {\n // Bounding info\n this._updateBoundingInfo();\n };\n /**\n * Returns `true` if the mesh is within the frustum defined by the passed array of planes.\n * A mesh is in the frustum if its bounding box intersects the frustum\n * @param frustumPlanes defines the frustum to test\n * @returns true if the mesh is in the frustum planes\n */\n AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {\n return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);\n };\n /**\n * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.\n * A mesh is completely in the frustum if its bounding box it completely inside the frustum.\n * @param frustumPlanes defines the frustum to test\n * @returns true if the mesh is completely in the frustum planes\n */\n AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {\n return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);\n };\n /**\n * True if the mesh intersects another mesh or a SolidParticle object\n * @param mesh defines a target mesh or SolidParticle to test\n * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)\n * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes\n * @returns true if there is an intersection\n */\n AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {\n if (precise === void 0) { precise = false; }\n if (!this._boundingInfo || !mesh._boundingInfo) {\n return false;\n }\n if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {\n return true;\n }\n if (includeDescendants) {\n for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {\n var child = _a[_i];\n if (child.intersectsMesh(mesh, precise, true)) {\n return true;\n }\n }\n }\n return false;\n };\n /**\n * Returns true if the passed point (Vector3) is inside the mesh bounding box\n * @param point defines the point to test\n * @returns true if there is an intersection\n */\n AbstractMesh.prototype.intersectsPoint = function (point) {\n if (!this._boundingInfo) {\n return false;\n }\n return this._boundingInfo.intersectsPoint(point);\n };\n /**\n * Gets the current physics impostor\n * @see http://doc.babylonjs.com/features/physics_engine\n * @returns a physics impostor or null\n */\n AbstractMesh.prototype.getPhysicsImpostor = function () {\n return this.physicsImpostor;\n };\n /**\n * Gets the position of the current mesh in camera space\n * @param camera defines the camera to use\n * @returns a position\n */\n AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {\n if (camera === void 0) { camera = null; }\n if (!camera) {\n camera = this.getScene().activeCamera;\n }\n return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());\n };\n /**\n * Returns the distance from the mesh to the active camera\n * @param camera defines the camera to use\n * @returns the distance\n */\n AbstractMesh.prototype.getDistanceToCamera = function (camera) {\n if (camera === void 0) { camera = null; }\n if (!camera) {\n camera = this.getScene().activeCamera;\n }\n return this.absolutePosition.subtract(camera.position).length();\n };\n /**\n * Apply a physic impulse to the mesh\n * @param force defines the force to apply\n * @param contactPoint defines where to apply the force\n * @returns the current mesh\n * @see http://doc.babylonjs.com/how_to/using_the_physics_engine\n */\n AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {\n if (!this.physicsImpostor) {\n return this;\n }\n this.physicsImpostor.applyImpulse(force, contactPoint);\n return this;\n };\n /**\n * Creates a physic joint between two meshes\n * @param otherMesh defines the other mesh to use\n * @param pivot1 defines the pivot to use on this mesh\n * @param pivot2 defines the pivot to use on the other mesh\n * @param options defines additional options (can be plugin dependent)\n * @returns the current mesh\n * @see https://www.babylonjs-playground.com/#0BS5U0#0\n */\n AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {\n if (!this.physicsImpostor || !otherMesh.physicsImpostor) {\n return this;\n }\n this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {\n mainPivot: pivot1,\n connectedPivot: pivot2,\n nativeParams: options\n });\n return this;\n };\n Object.defineProperty(AbstractMesh.prototype, \"checkCollisions\", {\n // Collisions\n /**\n * Gets or sets a boolean indicating that this mesh can be used in the collision engine\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */\n get: function () {\n return this._checkCollisions;\n },\n set: function (collisionEnabled) {\n this._checkCollisions = collisionEnabled;\n if (this.getScene().workerCollisions) {\n this.getScene().collisionCoordinator.onMeshUpdated(this);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"collider\", {\n /**\n * Gets Collider object used to compute collisions (not physics)\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */\n get: function () {\n return this._collider;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Move the mesh using collision engine\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n * @param displacement defines the requested displacement vector\n * @returns the current mesh\n */\n AbstractMesh.prototype.moveWithCollisions = function (displacement) {\n var globalPosition = this.getAbsolutePosition();\n globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);\n if (!this._collider) {\n this._collider = new BABYLON.Collider();\n }\n this._collider._radius = this.ellipsoid;\n this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);\n return this;\n };\n // Submeshes octree\n /**\n * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.\n * Please note that you must have a decent number of submeshes to get performance improvements when using an octree\n * @param maxCapacity defines the maximum size of each block (64 by default)\n * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)\n * @returns the new octree\n * @see https://www.babylonjs-playground.com/#NA4OQ#12\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees\n */\n AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {\n if (maxCapacity === void 0) { maxCapacity = 64; }\n if (maxDepth === void 0) { maxDepth = 2; }\n if (!this._submeshesOctree) {\n this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);\n }\n this.computeWorldMatrix(true);\n var boundingInfo = this.getBoundingInfo();\n // Update octree\n var bbox = boundingInfo.boundingBox;\n this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);\n return this._submeshesOctree;\n };\n // Collisions\n /** @hidden */\n AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {\n this._generatePointsArray();\n if (!this._positions) {\n return this;\n }\n // Transformation\n if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {\n subMesh._lastColliderTransformMatrix = transformMatrix.clone();\n subMesh._lastColliderWorldVertices = [];\n subMesh._trianglePlanes = [];\n var start = subMesh.verticesStart;\n var end = (subMesh.verticesStart + subMesh.verticesCount);\n for (var i = start; i < end; i++) {\n subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));\n }\n }\n // Collide\n collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());\n if (collider.collisionFound) {\n collider.collidedMesh = this;\n }\n return this;\n };\n /** @hidden */\n AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {\n var subMeshes;\n var len;\n // Octrees\n if (this._submeshesOctree && this.useOctreeForCollisions) {\n var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);\n var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);\n len = intersections.length;\n subMeshes = intersections.data;\n }\n else {\n subMeshes = this.subMeshes;\n len = subMeshes.length;\n }\n for (var index = 0; index < len; index++) {\n var subMesh = subMeshes[index];\n // Bounding test\n if (len > 1 && !subMesh._checkCollision(collider))\n continue;\n this._collideForSubMesh(subMesh, transformMatrix, collider);\n }\n return this;\n };\n /** @hidden */\n AbstractMesh.prototype._checkCollision = function (collider) {\n // Bounding box test\n if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))\n return this;\n // Transformation matrix\n BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);\n this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);\n this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);\n return this;\n };\n // Picking\n /** @hidden */\n AbstractMesh.prototype._generatePointsArray = function () {\n return false;\n };\n /**\n * Checks if the passed Ray intersects with the mesh\n * @param ray defines the ray to use\n * @param fastCheck defines if fast mode (but less precise) must be used (false by default)\n * @returns the picking info\n * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh\n */\n AbstractMesh.prototype.intersects = function (ray, fastCheck) {\n var pickingInfo = new BABYLON.PickingInfo();\n if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {\n return pickingInfo;\n }\n if (!this._generatePointsArray()) {\n return pickingInfo;\n }\n var intersectInfo = null;\n // Octrees\n var subMeshes;\n var len;\n if (this._submeshesOctree && this.useOctreeForPicking) {\n var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());\n var intersections = this._submeshesOctree.intersectsRay(worldRay);\n len = intersections.length;\n subMeshes = intersections.data;\n }\n else {\n subMeshes = this.subMeshes;\n len = subMeshes.length;\n }\n for (var index = 0; index < len; index++) {\n var subMesh = subMeshes[index];\n // Bounding test\n if (len > 1 && !subMesh.canIntersects(ray))\n continue;\n var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);\n if (currentIntersectInfo) {\n if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {\n intersectInfo = currentIntersectInfo;\n intersectInfo.subMeshId = index;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n if (intersectInfo) {\n // Get picked point\n var world = this.getWorldMatrix();\n var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);\n var direction = ray.direction.clone();\n direction = direction.scale(intersectInfo.distance);\n var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);\n var pickedPoint = worldOrigin.add(worldDirection);\n // Return result\n pickingInfo.hit = true;\n pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);\n pickingInfo.pickedPoint = pickedPoint;\n pickingInfo.pickedMesh = this;\n pickingInfo.bu = intersectInfo.bu || 0;\n pickingInfo.bv = intersectInfo.bv || 0;\n pickingInfo.faceId = intersectInfo.faceId;\n pickingInfo.subMeshId = intersectInfo.subMeshId;\n return pickingInfo;\n }\n return pickingInfo;\n };\n /**\n * Clones the current mesh\n * @param name defines the mesh name\n * @param newParent defines the new mesh parent\n * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)\n * @returns the new mesh\n */\n AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {\n return null;\n };\n /**\n * Disposes all the submeshes of the current meshnp\n * @returns the current mesh\n */\n AbstractMesh.prototype.releaseSubMeshes = function () {\n if (this.subMeshes) {\n while (this.subMeshes.length) {\n this.subMeshes[0].dispose();\n }\n }\n else {\n this.subMeshes = new Array();\n }\n return this;\n };\n /**\n * Releases resources associated with this abstract mesh.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n var _this = this;\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n var index;\n // Smart Array Retainers.\n this.getScene().freeActiveMeshes();\n this.getScene().freeRenderingGroups();\n // Action manager\n if (this.actionManager !== undefined && this.actionManager !== null) {\n this.actionManager.dispose();\n this.actionManager = null;\n }\n // Skeleton\n this._skeleton = null;\n // Physics\n if (this.physicsImpostor) {\n this.physicsImpostor.dispose( /*!doNotRecurse*/);\n }\n // Intersections in progress\n for (index = 0; index < this._intersectionsInProgress.length; index++) {\n var other = this._intersectionsInProgress[index];\n var pos = other._intersectionsInProgress.indexOf(this);\n other._intersectionsInProgress.splice(pos, 1);\n }\n this._intersectionsInProgress = [];\n // Lights\n var lights = this.getScene().lights;\n lights.forEach(function (light) {\n var meshIndex = light.includedOnlyMeshes.indexOf(_this);\n if (meshIndex !== -1) {\n light.includedOnlyMeshes.splice(meshIndex, 1);\n }\n meshIndex = light.excludedMeshes.indexOf(_this);\n if (meshIndex !== -1) {\n light.excludedMeshes.splice(meshIndex, 1);\n }\n // Shadow generators\n var generator = light.getShadowGenerator();\n if (generator) {\n var shadowMap = generator.getShadowMap();\n if (shadowMap && shadowMap.renderList) {\n meshIndex = shadowMap.renderList.indexOf(_this);\n if (meshIndex !== -1) {\n shadowMap.renderList.splice(meshIndex, 1);\n }\n }\n }\n });\n // Edges\n if (this._edgesRenderer) {\n this._edgesRenderer.dispose();\n this._edgesRenderer = null;\n }\n // SubMeshes\n if (this.getClassName() !== \"InstancedMesh\") {\n this.releaseSubMeshes();\n }\n // Octree\n var sceneOctree = this.getScene().selectionOctree;\n if (sceneOctree !== undefined && sceneOctree !== null) {\n var index = sceneOctree.dynamicContent.indexOf(this);\n if (index !== -1) {\n sceneOctree.dynamicContent.splice(index, 1);\n }\n }\n // Query\n var engine = this.getScene().getEngine();\n if (this._occlusionQuery) {\n this._isOcclusionQueryInProgress = false;\n engine.deleteQuery(this._occlusionQuery);\n this._occlusionQuery = null;\n }\n // Engine\n engine.wipeCaches();\n // Remove from scene\n this.getScene().removeMesh(this);\n if (disposeMaterialAndTextures) {\n if (this.material) {\n this.material.dispose(false, true);\n }\n }\n if (!doNotRecurse) {\n // Particles\n for (index = 0; index < this.getScene().particleSystems.length; index++) {\n if (this.getScene().particleSystems[index].emitter === this) {\n this.getScene().particleSystems[index].dispose();\n index--;\n }\n }\n }\n // facet data\n if (this._facetDataEnabled) {\n this.disableFacetData();\n }\n this.onAfterWorldMatrixUpdateObservable.clear();\n this.onCollideObservable.clear();\n this.onCollisionPositionChangeObservable.clear();\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n /**\n * Adds the passed mesh as a child to the current mesh\n * @param mesh defines the child mesh\n * @returns the current mesh\n */\n AbstractMesh.prototype.addChild = function (mesh) {\n mesh.setParent(this);\n return this;\n };\n /**\n * Removes the passed mesh from the current mesh children list\n * @param mesh defines the child mesh\n * @returns the current mesh\n */\n AbstractMesh.prototype.removeChild = function (mesh) {\n mesh.setParent(null);\n return this;\n };\n // Facet data\n /** @hidden */\n AbstractMesh.prototype._initFacetData = function () {\n if (!this._facetNormals) {\n this._facetNormals = new Array();\n }\n if (!this._facetPositions) {\n this._facetPositions = new Array();\n }\n if (!this._facetPartitioning) {\n this._facetPartitioning = new Array();\n }\n this._facetNb = (this.getIndices().length / 3) | 0;\n this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10\n this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box\n for (var f = 0; f < this._facetNb; f++) {\n this._facetNormals[f] = BABYLON.Vector3.Zero();\n this._facetPositions[f] = BABYLON.Vector3.Zero();\n }\n this._facetDataEnabled = true;\n return this;\n };\n /**\n * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.\n * This method can be called within the render loop.\n * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation\n * @returns the current mesh\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.updateFacetData = function () {\n if (!this._facetDataEnabled) {\n this._initFacetData();\n }\n var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var indices = this.getIndices();\n var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var bInfo = this.getBoundingInfo();\n if (this._facetDepthSort && !this._facetDepthSortEnabled) {\n // init arrays, matrix and sort function on first call\n this._facetDepthSortEnabled = true;\n if (indices instanceof Uint16Array) {\n this._depthSortedIndices = new Uint16Array(indices);\n }\n else if (indices instanceof Uint32Array) {\n this._depthSortedIndices = new Uint32Array(indices);\n }\n else {\n var needs32bits = false;\n for (var i = 0; i < indices.length; i++) {\n if (indices[i] > 65535) {\n needs32bits = true;\n break;\n }\n }\n if (needs32bits) {\n this._depthSortedIndices = new Uint32Array(indices);\n }\n else {\n this._depthSortedIndices = new Uint16Array(indices);\n }\n }\n this._facetDepthSortFunction = function (f1, f2) {\n return (f2.sqDistance - f1.sqDistance);\n };\n if (!this._facetDepthSortFrom) {\n var camera = this.getScene().activeCamera;\n this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();\n }\n this._depthSortedFacets = [];\n for (var f = 0; f < this._facetNb; f++) {\n var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };\n this._depthSortedFacets.push(depthSortedFacet);\n }\n this._invertedMatrix = BABYLON.Matrix.Identity();\n this._facetDepthSortOrigin = BABYLON.Vector3.Zero();\n }\n this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;\n this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;\n this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;\n var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;\n bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;\n this._subDiv.max = this._partitioningSubdivisions;\n this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis\n this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis\n this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);\n this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision\n this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;\n this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;\n // set the parameters for ComputeNormals()\n this._facetParameters.facetNormals = this.getFacetLocalNormals();\n this._facetParameters.facetPositions = this.getFacetLocalPositions();\n this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();\n this._facetParameters.bInfo = bInfo;\n this._facetParameters.bbSize = this._bbSize;\n this._facetParameters.subDiv = this._subDiv;\n this._facetParameters.ratio = this.partitioningBBoxRatio;\n this._facetParameters.depthSort = this._facetDepthSort;\n if (this._facetDepthSort && this._facetDepthSortEnabled) {\n this.computeWorldMatrix(true);\n this._worldMatrix.invertToRef(this._invertedMatrix);\n BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);\n this._facetParameters.distanceTo = this._facetDepthSortOrigin;\n }\n this._facetParameters.depthSortedFacets = this._depthSortedFacets;\n BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);\n if (this._facetDepthSort && this._facetDepthSortEnabled) {\n this._depthSortedFacets.sort(this._facetDepthSortFunction);\n var l = (this._depthSortedIndices.length / 3) | 0;\n for (var f = 0; f < l; f++) {\n var sind = this._depthSortedFacets[f].ind;\n this._depthSortedIndices[f * 3] = indices[sind];\n this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];\n this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];\n }\n this.updateIndices(this._depthSortedIndices);\n }\n return this;\n };\n /**\n * Returns the facetLocalNormals array.\n * The normals are expressed in the mesh local spac\n * @returns an array of Vector3\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetLocalNormals = function () {\n if (!this._facetNormals) {\n this.updateFacetData();\n }\n return this._facetNormals;\n };\n /**\n * Returns the facetLocalPositions array.\n * The facet positions are expressed in the mesh local space\n * @returns an array of Vector3\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetLocalPositions = function () {\n if (!this._facetPositions) {\n this.updateFacetData();\n }\n return this._facetPositions;\n };\n /**\n * Returns the facetLocalPartioning array\n * @returns an array of array of numbers\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetLocalPartitioning = function () {\n if (!this._facetPartitioning) {\n this.updateFacetData();\n }\n return this._facetPartitioning;\n };\n /**\n * Returns the i-th facet position in the world system.\n * This method allocates a new Vector3 per call\n * @param i defines the facet index\n * @returns a new Vector3\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetPosition = function (i) {\n var pos = BABYLON.Vector3.Zero();\n this.getFacetPositionToRef(i, pos);\n return pos;\n };\n /**\n * Sets the reference Vector3 with the i-th facet position in the world system\n * @param i defines the facet index\n * @param ref defines the target vector\n * @returns the current mesh\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {\n var localPos = (this.getFacetLocalPositions())[i];\n var world = this.getWorldMatrix();\n BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);\n return this;\n };\n /**\n * Returns the i-th facet normal in the world system.\n * This method allocates a new Vector3 per call\n * @param i defines the facet index\n * @returns a new Vector3\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetNormal = function (i) {\n var norm = BABYLON.Vector3.Zero();\n this.getFacetNormalToRef(i, norm);\n return norm;\n };\n /**\n * Sets the reference Vector3 with the i-th facet normal in the world system\n * @param i defines the facet index\n * @param ref defines the target vector\n * @returns the current mesh\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {\n var localNorm = (this.getFacetLocalNormals())[i];\n BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);\n return this;\n };\n /**\n * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system)\n * @param x defines x coordinate\n * @param y defines y coordinate\n * @param z defines z coordinate\n * @returns the array of facet indexes\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {\n var bInfo = this.getBoundingInfo();\n var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);\n var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);\n var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);\n if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {\n return null;\n }\n return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];\n };\n /**\n * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found\n * @param projected sets as the (x,y,z) world projection on the facet\n * @param checkFace if true (default false), only the facet \"facing\" to (x,y,z) or only the ones \"turning their backs\", according to the parameter \"facing\" are returned\n * @param facing if facing and checkFace are true, only the facet \"facing\" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet \"turning their backs\" to (x, y, z) are returned : negative dot (x, y, z) * facet position\n * @param x defines x coordinate\n * @param y defines y coordinate\n * @param z defines z coordinate\n * @returns the face index if found (or null instead)\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {\n if (checkFace === void 0) { checkFace = false; }\n if (facing === void 0) { facing = true; }\n var world = this.getWorldMatrix();\n var invMat = BABYLON.Tmp.Matrix[5];\n world.invertToRef(invMat);\n var invVect = BABYLON.Tmp.Vector3[8];\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space\n var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);\n if (projected) {\n // tranform the local computed projected vector to world coordinates\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);\n }\n return closest;\n };\n /**\n * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found\n * @param projected sets as the (x,y,z) local projection on the facet\n * @param checkFace if true (default false), only the facet \"facing\" to (x,y,z) or only the ones \"turning their backs\", according to the parameter \"facing\" are returned\n * @param facing if facing and checkFace are true, only the facet \"facing\" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet \"turning their backs\" to (x, y, z) are returned : negative dot (x, y, z) * facet position\n * @param x defines x coordinate\n * @param y defines y coordinate\n * @param z defines z coordinate\n * @returns the face index if found (or null instead)\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {\n if (checkFace === void 0) { checkFace = false; }\n if (facing === void 0) { facing = true; }\n var closest = null;\n var tmpx = 0.0;\n var tmpy = 0.0;\n var tmpz = 0.0;\n var d = 0.0; // tmp dot facet normal * facet position\n var t0 = 0.0;\n var projx = 0.0;\n var projy = 0.0;\n var projz = 0.0;\n // Get all the facets in the same partitioning block than (x, y, z)\n var facetPositions = this.getFacetLocalPositions();\n var facetNormals = this.getFacetLocalNormals();\n var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);\n if (!facetsInBlock) {\n return null;\n }\n // Get the closest facet to (x, y, z)\n var shortest = Number.MAX_VALUE; // init distance vars\n var tmpDistance = shortest;\n var fib; // current facet in the block\n var norm; // current facet normal\n var p0; // current facet barycenter position\n // loop on all the facets in the current partitioning block\n for (var idx = 0; idx < facetsInBlock.length; idx++) {\n fib = facetsInBlock[idx];\n norm = facetNormals[fib];\n p0 = facetPositions[fib];\n d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;\n if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {\n // compute (x,y,z) projection on the facet = (projx, projy, projz)\n d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;\n t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);\n projx = x + norm.x * t0;\n projy = y + norm.y * t0;\n projz = z + norm.z * t0;\n tmpx = projx - x;\n tmpy = projy - y;\n tmpz = projz - z;\n tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet\n if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)\n shortest = tmpDistance;\n closest = fib;\n if (projected) {\n projected.x = projx;\n projected.y = projy;\n projected.z = projz;\n }\n }\n }\n }\n return closest;\n };\n /**\n * Returns the object \"parameter\" set with all the expected parameters for facetData computation by ComputeNormals()\n * @returns the parameters\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetDataParameters = function () {\n return this._facetParameters;\n };\n /**\n * Disables the feature FacetData and frees the related memory\n * @returns the current mesh\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.disableFacetData = function () {\n if (this._facetDataEnabled) {\n this._facetDataEnabled = false;\n this._facetPositions = new Array();\n this._facetNormals = new Array();\n this._facetPartitioning = new Array();\n this._facetParameters = null;\n this._depthSortedIndices = new Uint32Array(0);\n }\n return this;\n };\n /**\n * Updates the AbstractMesh indices array\n * @param indices defines the data source\n * @returns the current mesh\n */\n AbstractMesh.prototype.updateIndices = function (indices) {\n return this;\n };\n /**\n * Creates new normals data for the mesh\n * @param updatable defines if the normal vertex buffer must be flagged as updatable\n * @returns the current mesh\n */\n AbstractMesh.prototype.createNormals = function (updatable) {\n var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var indices = this.getIndices();\n var normals;\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n }\n else {\n normals = [];\n }\n BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });\n this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);\n return this;\n };\n /**\n * Align the mesh with a normal\n * @param normal defines the normal to use\n * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)\n * @returns the current mesh\n */\n AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {\n if (!upDirection) {\n upDirection = BABYLON.Axis.Y;\n }\n var axisX = BABYLON.Tmp.Vector3[0];\n var axisZ = BABYLON.Tmp.Vector3[1];\n BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);\n BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);\n if (this.rotationQuaternion) {\n BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);\n }\n else {\n BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);\n }\n return this;\n };\n /** @hidden */\n AbstractMesh.prototype._checkOcclusionQuery = function () {\n this._isOccluded = false;\n };\n /** No occlusion */\n AbstractMesh.OCCLUSION_TYPE_NONE = 0;\n /** Occlusion set to optimisitic */\n AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;\n /** Occlusion set to strict */\n AbstractMesh.OCCLUSION_TYPE_STRICT = 2;\n /** Use an accurante occlusion algorithm */\n AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;\n /** Use a conservative occlusion algorithm */\n AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;\n return AbstractMesh;\n }(BABYLON.TransformNode));\n BABYLON.AbstractMesh = AbstractMesh;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.abstractMesh.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Base class of all the lights in Babylon. It groups all the generic information about lights.\n * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.\n * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.\n */\n var Light = /** @class */ (function (_super) {\n __extends(Light, _super);\n /**\n * Creates a Light object in the scene.\n * Documentation : http://doc.babylonjs.com/tutorials/lights\n * @param name The firendly name of the light\n * @param scene The scene the light belongs too\n */\n function Light(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n /**\n * Diffuse gives the basic color to an object.\n */\n _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);\n /**\n * Specular produces a highlight color on an object.\n * Note: This is note affecting PBR materials.\n */\n _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);\n /**\n * Strength of the light.\n * Note: By default it is define in the framework own unit.\n * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.\n */\n _this.intensity = 1.0;\n /**\n * Defines how far from the source the light is impacting in scene units.\n * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.\n */\n _this.range = Number.MAX_VALUE;\n /**\n * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type\n * of light.\n */\n _this._photometricScale = 1.0;\n _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;\n _this._radius = 0.00001;\n /**\n * Defines the rendering priority of the lights. It can help in case of fallback or number of lights\n * exceeding the number allowed of the materials.\n */\n _this.renderPriority = 0;\n _this._shadowEnabled = true;\n _this._excludeWithLayerMask = 0;\n _this._includeOnlyWithLayerMask = 0;\n _this._lightmapMode = 0;\n /**\n * @hidden Internal use only.\n */\n _this._excludedMeshesIds = new Array();\n /**\n * @hidden Internal use only.\n */\n _this._includedOnlyMeshesIds = new Array();\n _this.getScene().addLight(_this);\n _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());\n _this._buildUniformLayout();\n _this.includedOnlyMeshes = new Array();\n _this.excludedMeshes = new Array();\n _this._resyncMeshes();\n return _this;\n }\n Object.defineProperty(Light.prototype, \"intensityMode\", {\n /**\n * Gets the photometric scale used to interpret the intensity.\n * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.\n */\n get: function () {\n return this._intensityMode;\n },\n /**\n * Sets the photometric scale used to interpret the intensity.\n * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.\n */\n set: function (value) {\n this._intensityMode = value;\n this._computePhotometricScale();\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(Light.prototype, \"radius\", {\n /**\n * Gets the light radius used by PBR Materials to simulate soft area lights.\n */\n get: function () {\n return this._radius;\n },\n /**\n * sets the light radius used by PBR Materials to simulate soft area lights.\n */\n set: function (value) {\n this._radius = value;\n this._computePhotometricScale();\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(Light.prototype, \"shadowEnabled\", {\n /**\n * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching\n * the current shadow generator.\n */\n get: function () {\n return this._shadowEnabled;\n },\n /**\n * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching\n * the current shadow generator.\n */\n set: function (value) {\n if (this._shadowEnabled === value) {\n return;\n }\n this._shadowEnabled = value;\n this._markMeshesAsLightDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Light.prototype, \"includedOnlyMeshes\", {\n /**\n * Gets the only meshes impacted by this light.\n */\n get: function () {\n return this._includedOnlyMeshes;\n },\n /**\n * Sets the only meshes impacted by this light.\n */\n set: function (value) {\n this._includedOnlyMeshes = value;\n this._hookArrayForIncludedOnly(value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Light.prototype, \"excludedMeshes\", {\n /**\n * Gets the meshes not impacted by this light.\n */\n get: function () {\n return this._excludedMeshes;\n },\n /**\n * Sets the meshes not impacted by this light.\n */\n set: function (value) {\n this._excludedMeshes = value;\n this._hookArrayForExcluded(value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Light.prototype, \"excludeWithLayerMask\", {\n /**\n * Gets the layer id use to find what meshes are not impacted by the light.\n * Inactive if 0\n */\n get: function () {\n return this._excludeWithLayerMask;\n },\n /**\n * Sets the layer id use to find what meshes are not impacted by the light.\n * Inactive if 0\n */\n set: function (value) {\n this._excludeWithLayerMask = value;\n this._resyncMeshes();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Light.prototype, \"includeOnlyWithLayerMask\", {\n /**\n * Gets the layer id use to find what meshes are impacted by the light.\n * Inactive if 0\n */\n get: function () {\n return this._includeOnlyWithLayerMask;\n },\n /**\n * Sets the layer id use to find what meshes are impacted by the light.\n * Inactive if 0\n */\n set: function (value) {\n this._includeOnlyWithLayerMask = value;\n this._resyncMeshes();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Light.prototype, \"lightmapMode\", {\n /**\n * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)\n */\n get: function () {\n return this._lightmapMode;\n },\n /**\n * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)\n */\n set: function (value) {\n if (this._lightmapMode === value) {\n return;\n }\n this._lightmapMode = value;\n this._markMeshesAsLightDirty();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"Light\".\n * @returns the class name\n */\n Light.prototype.getClassName = function () {\n return \"Light\";\n };\n /**\n * Converts the light information to a readable string for debug purpose.\n * @param fullDetails Supports for multiple levels of logging within scene loading\n * @returns the human readable light info\n */\n Light.prototype.toString = function (fullDetails) {\n var ret = \"Name: \" + this.name;\n ret += \", type: \" + ([\"Point\", \"Directional\", \"Spot\", \"Hemispheric\"])[this.getTypeID()];\n if (this.animations) {\n for (var i = 0; i < this.animations.length; i++) {\n ret += \", animation[0]: \" + this.animations[i].toString(fullDetails);\n }\n }\n if (fullDetails) {\n }\n return ret;\n };\n /**\n * Set the enabled state of this node.\n * @param value - the new enabled state\n */\n Light.prototype.setEnabled = function (value) {\n _super.prototype.setEnabled.call(this, value);\n this._resyncMeshes();\n };\n /**\n * Returns the Light associated shadow generator if any.\n * @return the associated shadow generator.\n */\n Light.prototype.getShadowGenerator = function () {\n return this._shadowGenerator;\n };\n /**\n * Returns a Vector3, the absolute light position in the World.\n * @returns the world space position of the light\n */\n Light.prototype.getAbsolutePosition = function () {\n return BABYLON.Vector3.Zero();\n };\n /**\n * Specifies if the light will affect the passed mesh.\n * @param mesh The mesh to test against the light\n * @return true the mesh is affected otherwise, false.\n */\n Light.prototype.canAffectMesh = function (mesh) {\n if (!mesh) {\n return true;\n }\n if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {\n return false;\n }\n if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {\n return false;\n }\n if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {\n return false;\n }\n if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {\n return false;\n }\n return true;\n };\n /**\n * Computes and Returns the light World matrix.\n * @returns the world matrix\n */\n Light.prototype.getWorldMatrix = function () {\n this._currentRenderId = this.getScene().getRenderId();\n this._childRenderId = this._currentRenderId;\n var worldMatrix = this._getWorldMatrix();\n if (this.parent && this.parent.getWorldMatrix) {\n if (!this._parentedWorldMatrix) {\n this._parentedWorldMatrix = BABYLON.Matrix.Identity();\n }\n worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);\n this._markSyncedWithParent();\n return this._parentedWorldMatrix;\n }\n return worldMatrix;\n };\n /**\n * Sort function to order lights for rendering.\n * @param a First Light object to compare to second.\n * @param b Second Light object to compare first.\n * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.\n */\n Light.CompareLightsPriority = function (a, b) {\n //shadow-casting lights have priority over non-shadow-casting lights\n //the renderPrioirty is a secondary sort criterion\n if (a.shadowEnabled !== b.shadowEnabled) {\n return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);\n }\n return b.renderPriority - a.renderPriority;\n };\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n if (this._shadowGenerator) {\n this._shadowGenerator.dispose();\n this._shadowGenerator = null;\n }\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from meshes\n for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n mesh._removeLightSource(this);\n }\n this._uniformBuffer.dispose();\n // Remove from scene\n this.getScene().removeLight(this);\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n /**\n * Returns the light type ID (integer).\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n Light.prototype.getTypeID = function () {\n return 0;\n };\n /**\n * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.\n * @returns the scaled intensity in intensity mode unit\n */\n Light.prototype.getScaledIntensity = function () {\n return this._photometricScale * this.intensity;\n };\n /**\n * Returns a new Light object, named \"name\", from the current one.\n * @param name The name of the cloned light\n * @returns the new created light\n */\n Light.prototype.clone = function (name) {\n var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());\n if (!constructor) {\n return null;\n }\n return BABYLON.SerializationHelper.Clone(constructor, this);\n };\n /**\n * Serializes the current light into a Serialization object.\n * @returns the serialized object.\n */\n Light.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n // Type\n serializationObject.type = this.getTypeID();\n // Parent\n if (this.parent) {\n serializationObject.parentId = this.parent.id;\n }\n // Inclusion / exclusions\n if (this.excludedMeshes.length > 0) {\n serializationObject.excludedMeshesIds = [];\n this.excludedMeshes.forEach(function (mesh) {\n serializationObject.excludedMeshesIds.push(mesh.id);\n });\n }\n if (this.includedOnlyMeshes.length > 0) {\n serializationObject.includedOnlyMeshesIds = [];\n this.includedOnlyMeshes.forEach(function (mesh) {\n serializationObject.includedOnlyMeshesIds.push(mesh.id);\n });\n }\n // Animations \n BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);\n serializationObject.ranges = this.serializeAnimationRanges();\n return serializationObject;\n };\n /**\n * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.\n * This new light is named \"name\" and added to the passed scene.\n * @param type Type according to the types available in Light.LIGHTTYPEID_x\n * @param name The friendly name of the light\n * @param scene The scene the new light will belong to\n * @returns the constructor function\n */\n Light.GetConstructorFromName = function (type, name, scene) {\n var constructorFunc = BABYLON.Node.Construct(\"Light_Type_\" + type, name, scene);\n if (constructorFunc) {\n return constructorFunc;\n }\n // Default to no light for none present once.\n return null;\n };\n /**\n * Parses the passed \"parsedLight\" and returns a new instanced Light from this parsing.\n * @param parsedLight The JSON representation of the light\n * @param scene The scene to create the parsed light in\n * @returns the created light after parsing\n */\n Light.Parse = function (parsedLight, scene) {\n var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);\n if (!constructor) {\n return null;\n }\n var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);\n // Inclusion / exclusions\n if (parsedLight.excludedMeshesIds) {\n light._excludedMeshesIds = parsedLight.excludedMeshesIds;\n }\n if (parsedLight.includedOnlyMeshesIds) {\n light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;\n }\n // Parent\n if (parsedLight.parentId) {\n light._waitingParentId = parsedLight.parentId;\n }\n // Animations\n if (parsedLight.animations) {\n for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {\n var parsedAnimation = parsedLight.animations[animationIndex];\n light.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);\n }\n if (parsedLight.autoAnimate) {\n scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);\n }\n return light;\n };\n Light.prototype._hookArrayForExcluded = function (array) {\n var _this = this;\n var oldPush = array.push;\n array.push = function () {\n var items = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n items[_i] = arguments[_i];\n }\n var result = oldPush.apply(array, items);\n for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {\n var item = items_1[_a];\n item._resyncLighSource(_this);\n }\n return result;\n };\n var oldSplice = array.splice;\n array.splice = function (index, deleteCount) {\n var deleted = oldSplice.apply(array, [index, deleteCount]);\n for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {\n var item = deleted_1[_i];\n item._resyncLighSource(_this);\n }\n return deleted;\n };\n for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {\n var item = array_1[_i];\n item._resyncLighSource(this);\n }\n };\n Light.prototype._hookArrayForIncludedOnly = function (array) {\n var _this = this;\n var oldPush = array.push;\n array.push = function () {\n var items = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n items[_i] = arguments[_i];\n }\n var result = oldPush.apply(array, items);\n _this._resyncMeshes();\n return result;\n };\n var oldSplice = array.splice;\n array.splice = function (index, deleteCount) {\n var deleted = oldSplice.apply(array, [index, deleteCount]);\n _this._resyncMeshes();\n return deleted;\n };\n this._resyncMeshes();\n };\n Light.prototype._resyncMeshes = function () {\n for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n mesh._resyncLighSource(this);\n }\n };\n /**\n * Forces the meshes to update their light related information in their rendering used effects\n * @hidden Internal Use Only\n */\n Light.prototype._markMeshesAsLightDirty = function () {\n for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n if (mesh._lightSources.indexOf(this) !== -1) {\n mesh._markSubMeshesAsLightDirty();\n }\n }\n };\n /**\n * Recomputes the cached photometric scale if needed.\n */\n Light.prototype._computePhotometricScale = function () {\n this._photometricScale = this._getPhotometricScale();\n this.getScene().resetCachedMaterial();\n };\n /**\n * Returns the Photometric Scale according to the light type and intensity mode.\n */\n Light.prototype._getPhotometricScale = function () {\n var photometricScale = 0.0;\n var lightTypeID = this.getTypeID();\n //get photometric mode\n var photometricMode = this.intensityMode;\n if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {\n if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {\n photometricMode = Light.INTENSITYMODE_ILLUMINANCE;\n }\n else {\n photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;\n }\n }\n //compute photometric scale\n switch (lightTypeID) {\n case Light.LIGHTTYPEID_POINTLIGHT:\n case Light.LIGHTTYPEID_SPOTLIGHT:\n switch (photometricMode) {\n case Light.INTENSITYMODE_LUMINOUSPOWER:\n photometricScale = 1.0 / (4.0 * Math.PI);\n break;\n case Light.INTENSITYMODE_LUMINOUSINTENSITY:\n photometricScale = 1.0;\n break;\n case Light.INTENSITYMODE_LUMINANCE:\n photometricScale = this.radius * this.radius;\n break;\n }\n break;\n case Light.LIGHTTYPEID_DIRECTIONALLIGHT:\n switch (photometricMode) {\n case Light.INTENSITYMODE_ILLUMINANCE:\n photometricScale = 1.0;\n break;\n case Light.INTENSITYMODE_LUMINANCE:\n // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.\n // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).\n var apexAngleRadians = this.radius;\n // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).\n apexAngleRadians = Math.max(apexAngleRadians, 0.001);\n var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));\n photometricScale = solidAngle;\n break;\n }\n break;\n case Light.LIGHTTYPEID_HEMISPHERICLIGHT:\n // No fall off in hemisperic light.\n photometricScale = 1.0;\n break;\n }\n return photometricScale;\n };\n /**\n * Reorder the light in the scene according to their defined priority.\n * @hidden Internal Use Only\n */\n Light.prototype._reorderLightsInScene = function () {\n var scene = this.getScene();\n if (this._renderPriority != 0) {\n scene.requireLightSorting = true;\n }\n this.getScene().sortLightsByPriority();\n };\n //lightmapMode Consts\n /**\n * If every light affecting the material is in this lightmapMode,\n * material.lightmapTexture adds or multiplies\n * (depends on material.useLightmapAsShadowmap)\n * after every other light calculations.\n */\n Light.LIGHTMAP_DEFAULT = 0;\n /**\n * material.lightmapTexture as only diffuse lighting from this light\n * adds only specular lighting from this light\n * adds dynamic shadows\n */\n Light.LIGHTMAP_SPECULAR = 1;\n /**\n * material.lightmapTexture as only lighting\n * no light calculation from this light\n * only adds dynamic shadows from this light\n */\n Light.LIGHTMAP_SHADOWSONLY = 2;\n // Intensity Mode Consts\n /**\n * Each light type uses the default quantity according to its type:\n * point/spot lights use luminous intensity\n * directional lights use illuminance\n */\n Light.INTENSITYMODE_AUTOMATIC = 0;\n /**\n * lumen (lm)\n */\n Light.INTENSITYMODE_LUMINOUSPOWER = 1;\n /**\n * candela (lm/sr)\n */\n Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;\n /**\n * lux (lm/m^2)\n */\n Light.INTENSITYMODE_ILLUMINANCE = 3;\n /**\n * nit (cd/m^2)\n */\n Light.INTENSITYMODE_LUMINANCE = 4;\n // Light types ids const.\n /**\n * Light type const id of the point light.\n */\n Light.LIGHTTYPEID_POINTLIGHT = 0;\n /**\n * Light type const id of the directional light.\n */\n Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;\n /**\n * Light type const id of the spot light.\n */\n Light.LIGHTTYPEID_SPOTLIGHT = 2;\n /**\n * Light type const id of the hemispheric light.\n */\n Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;\n __decorate([\n BABYLON.serializeAsColor3()\n ], Light.prototype, \"diffuse\", void 0);\n __decorate([\n BABYLON.serializeAsColor3()\n ], Light.prototype, \"specular\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Light.prototype, \"intensity\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Light.prototype, \"range\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Light.prototype, \"intensityMode\", null);\n __decorate([\n BABYLON.serialize()\n ], Light.prototype, \"radius\", null);\n __decorate([\n BABYLON.serialize()\n ], Light.prototype, \"_renderPriority\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_reorderLightsInScene\")\n ], Light.prototype, \"renderPriority\", void 0);\n __decorate([\n BABYLON.serialize(\"shadowEnabled\")\n ], Light.prototype, \"_shadowEnabled\", void 0);\n __decorate([\n BABYLON.serialize(\"excludeWithLayerMask\")\n ], Light.prototype, \"_excludeWithLayerMask\", void 0);\n __decorate([\n BABYLON.serialize(\"includeOnlyWithLayerMask\")\n ], Light.prototype, \"_includeOnlyWithLayerMask\", void 0);\n __decorate([\n BABYLON.serialize(\"lightmapMode\")\n ], Light.prototype, \"_lightmapMode\", void 0);\n return Light;\n }(BABYLON.Node));\n BABYLON.Light = Light;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.light.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var Camera = /** @class */ (function (_super) {\n __extends(Camera, _super);\n function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {\n if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }\n var _this = _super.call(this, name, scene) || this;\n /**\n * The vector the camera should consider as up.\n * (default is Vector3(0, 1, 0) aka Vector3.Up())\n */\n _this.upVector = BABYLON.Vector3.Up();\n _this.orthoLeft = null;\n _this.orthoRight = null;\n _this.orthoBottom = null;\n _this.orthoTop = null;\n /**\n * FOV is set in Radians. (default is 0.8)\n */\n _this.fov = 0.8;\n _this.minZ = 1;\n _this.maxZ = 10000.0;\n _this.inertia = 0.9;\n _this.mode = Camera.PERSPECTIVE_CAMERA;\n _this.isIntermediate = false;\n _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);\n /**\n * Restricts the camera to viewing objects with the same layerMask.\n * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0\n */\n _this.layerMask = 0x0FFFFFFF;\n /**\n * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)\n */\n _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;\n // Camera rig members\n _this.cameraRigMode = Camera.RIG_MODE_NONE;\n _this._rigCameras = new Array();\n _this._webvrViewMatrix = BABYLON.Matrix.Identity();\n _this._skipRendering = false;\n _this.customRenderTargets = new Array();\n // Observables\n _this.onViewMatrixChangedObservable = new BABYLON.Observable();\n _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();\n _this.onAfterCheckInputsObservable = new BABYLON.Observable();\n _this.onRestoreStateObservable = new BABYLON.Observable();\n // Cache\n _this._computedViewMatrix = BABYLON.Matrix.Identity();\n _this._projectionMatrix = new BABYLON.Matrix();\n _this._doNotComputeProjectionMatrix = false;\n _this._worldMatrix = BABYLON.Matrix.Identity();\n _this._postProcesses = new Array();\n _this._transformMatrix = BABYLON.Matrix.Zero();\n _this._activeMeshes = new BABYLON.SmartArray(256);\n _this._globalPosition = BABYLON.Vector3.Zero();\n _this._refreshFrustumPlanes = true;\n _this.getScene().addCamera(_this);\n if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {\n _this.getScene().activeCamera = _this;\n }\n _this.position = position;\n return _this;\n }\n Object.defineProperty(Camera, \"PERSPECTIVE_CAMERA\", {\n get: function () {\n return Camera._PERSPECTIVE_CAMERA;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"ORTHOGRAPHIC_CAMERA\", {\n get: function () {\n return Camera._ORTHOGRAPHIC_CAMERA;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"FOVMODE_VERTICAL_FIXED\", {\n /**\n * This is the default FOV mode for perspective cameras.\n * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.\n *\n */\n get: function () {\n return Camera._FOVMODE_VERTICAL_FIXED;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"FOVMODE_HORIZONTAL_FIXED\", {\n /**\n * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.\n *\n */\n get: function () {\n return Camera._FOVMODE_HORIZONTAL_FIXED;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_NONE\", {\n get: function () {\n return Camera._RIG_MODE_NONE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_STEREOSCOPIC_ANAGLYPH\", {\n get: function () {\n return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL\", {\n get: function () {\n return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED\", {\n get: function () {\n return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_STEREOSCOPIC_OVERUNDER\", {\n get: function () {\n return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_VR\", {\n get: function () {\n return Camera._RIG_MODE_VR;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_WEBVR\", {\n get: function () {\n return Camera._RIG_MODE_WEBVR;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Store current camera state (fov, position, etc..)\n */\n Camera.prototype.storeState = function () {\n this._stateStored = true;\n this._storedFov = this.fov;\n return this;\n };\n /**\n * Restores the camera state values if it has been stored. You must call storeState() first\n */\n Camera.prototype._restoreStateValues = function () {\n if (!this._stateStored) {\n return false;\n }\n this.fov = this._storedFov;\n return true;\n };\n /**\n * Restored camera state. You must call storeState() first\n */\n Camera.prototype.restoreState = function () {\n if (this._restoreStateValues()) {\n this.onRestoreStateObservable.notifyObservers(this);\n return true;\n }\n return false;\n };\n Camera.prototype.getClassName = function () {\n return \"Camera\";\n };\n /**\n * @param {boolean} fullDetails - support for multiple levels of logging within scene loading\n */\n Camera.prototype.toString = function (fullDetails) {\n var ret = \"Name: \" + this.name;\n ret += \", type: \" + this.getClassName();\n if (this.animations) {\n for (var i = 0; i < this.animations.length; i++) {\n ret += \", animation[0]: \" + this.animations[i].toString(fullDetails);\n }\n }\n if (fullDetails) {\n }\n return ret;\n };\n Object.defineProperty(Camera.prototype, \"globalPosition\", {\n get: function () {\n return this._globalPosition;\n },\n enumerable: true,\n configurable: true\n });\n Camera.prototype.getActiveMeshes = function () {\n return this._activeMeshes;\n };\n Camera.prototype.isActiveMesh = function (mesh) {\n return (this._activeMeshes.indexOf(mesh) !== -1);\n };\n /**\n * Is this camera ready to be used/rendered\n * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)\n * @return true if the camera is ready\n */\n Camera.prototype.isReady = function (completeCheck) {\n if (completeCheck === void 0) { completeCheck = false; }\n if (completeCheck) {\n for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {\n var pp = _a[_i];\n if (pp && !pp.isReady()) {\n return false;\n }\n }\n }\n return _super.prototype.isReady.call(this, completeCheck);\n };\n //Cache\n Camera.prototype._initCache = function () {\n _super.prototype._initCache.call(this);\n this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.mode = undefined;\n this._cache.minZ = undefined;\n this._cache.maxZ = undefined;\n this._cache.fov = undefined;\n this._cache.fovMode = undefined;\n this._cache.aspectRatio = undefined;\n this._cache.orthoLeft = undefined;\n this._cache.orthoRight = undefined;\n this._cache.orthoBottom = undefined;\n this._cache.orthoTop = undefined;\n this._cache.renderWidth = undefined;\n this._cache.renderHeight = undefined;\n };\n Camera.prototype._updateCache = function (ignoreParentClass) {\n if (!ignoreParentClass) {\n _super.prototype._updateCache.call(this);\n }\n this._cache.position.copyFrom(this.position);\n this._cache.upVector.copyFrom(this.upVector);\n };\n // Synchronized\n Camera.prototype._isSynchronized = function () {\n return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();\n };\n Camera.prototype._isSynchronizedViewMatrix = function () {\n if (!_super.prototype._isSynchronized.call(this))\n return false;\n return this._cache.position.equals(this.position)\n && this._cache.upVector.equals(this.upVector)\n && this.isSynchronizedWithParent();\n };\n Camera.prototype._isSynchronizedProjectionMatrix = function () {\n var check = this._cache.mode === this.mode\n && this._cache.minZ === this.minZ\n && this._cache.maxZ === this.maxZ;\n if (!check) {\n return false;\n }\n var engine = this.getEngine();\n if (this.mode === Camera.PERSPECTIVE_CAMERA) {\n check = this._cache.fov === this.fov\n && this._cache.fovMode === this.fovMode\n && this._cache.aspectRatio === engine.getAspectRatio(this);\n }\n else {\n check = this._cache.orthoLeft === this.orthoLeft\n && this._cache.orthoRight === this.orthoRight\n && this._cache.orthoBottom === this.orthoBottom\n && this._cache.orthoTop === this.orthoTop\n && this._cache.renderWidth === engine.getRenderWidth()\n && this._cache.renderHeight === engine.getRenderHeight();\n }\n return check;\n };\n // Controls\n Camera.prototype.attachControl = function (element, noPreventDefault) {\n };\n Camera.prototype.detachControl = function (element) {\n };\n Camera.prototype.update = function () {\n this._checkInputs();\n if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n this._updateRigCameras();\n }\n };\n Camera.prototype._checkInputs = function () {\n this.onAfterCheckInputsObservable.notifyObservers(this);\n };\n Object.defineProperty(Camera.prototype, \"rigCameras\", {\n get: function () {\n return this._rigCameras;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera.prototype, \"rigPostProcess\", {\n get: function () {\n return this._rigPostProcess;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Internal, gets the first post proces.\n * @returns the first post process to be run on this camera.\n */\n Camera.prototype._getFirstPostProcess = function () {\n for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {\n if (this._postProcesses[ppIndex] !== null) {\n return this._postProcesses[ppIndex];\n }\n }\n return null;\n };\n Camera.prototype._cascadePostProcessesToRigCams = function () {\n // invalidate framebuffer\n var firstPostProcess = this._getFirstPostProcess();\n if (firstPostProcess) {\n firstPostProcess.markTextureDirty();\n }\n // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera\n for (var i = 0, len = this._rigCameras.length; i < len; i++) {\n var cam = this._rigCameras[i];\n var rigPostProcess = cam._rigPostProcess;\n // for VR rig, there does not have to be a post process\n if (rigPostProcess) {\n var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;\n if (isPass) {\n // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses\n cam.isIntermediate = this._postProcesses.length === 0;\n }\n cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);\n rigPostProcess.markTextureDirty();\n }\n else {\n cam._postProcesses = this._postProcesses.slice(0);\n }\n }\n };\n Camera.prototype.attachPostProcess = function (postProcess, insertAt) {\n if (insertAt === void 0) { insertAt = null; }\n if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {\n BABYLON.Tools.Error(\"You're trying to reuse a post process not defined as reusable.\");\n return 0;\n }\n if (insertAt == null || insertAt < 0) {\n this._postProcesses.push(postProcess);\n }\n else if (this._postProcesses[insertAt] === null) {\n this._postProcesses[insertAt] = postProcess;\n }\n else {\n this._postProcesses.splice(insertAt, 0, postProcess);\n }\n this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated\n return this._postProcesses.indexOf(postProcess);\n };\n Camera.prototype.detachPostProcess = function (postProcess) {\n var idx = this._postProcesses.indexOf(postProcess);\n if (idx !== -1) {\n this._postProcesses[idx] = null;\n }\n this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated\n };\n Camera.prototype.getWorldMatrix = function () {\n if (this._isSynchronizedViewMatrix()) {\n return this._worldMatrix;\n }\n // Getting the the view matrix will also compute the world matrix.\n this.getViewMatrix();\n return this._worldMatrix;\n };\n Camera.prototype._getViewMatrix = function () {\n return BABYLON.Matrix.Identity();\n };\n Camera.prototype.getViewMatrix = function (force) {\n if (!force && this._isSynchronizedViewMatrix()) {\n return this._computedViewMatrix;\n }\n this.updateCache();\n this._computedViewMatrix = this._getViewMatrix();\n this._currentRenderId = this.getScene().getRenderId();\n this._childRenderId = this._currentRenderId;\n this._refreshFrustumPlanes = true;\n if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {\n this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);\n }\n this.onViewMatrixChangedObservable.notifyObservers(this);\n this._computedViewMatrix.invertToRef(this._worldMatrix);\n return this._computedViewMatrix;\n };\n Camera.prototype.freezeProjectionMatrix = function (projection) {\n this._doNotComputeProjectionMatrix = true;\n if (projection !== undefined) {\n this._projectionMatrix = projection;\n }\n };\n ;\n Camera.prototype.unfreezeProjectionMatrix = function () {\n this._doNotComputeProjectionMatrix = false;\n };\n ;\n Camera.prototype.getProjectionMatrix = function (force) {\n if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {\n return this._projectionMatrix;\n }\n // Cache\n this._cache.mode = this.mode;\n this._cache.minZ = this.minZ;\n this._cache.maxZ = this.maxZ;\n // Matrix\n this._refreshFrustumPlanes = true;\n var engine = this.getEngine();\n var scene = this.getScene();\n if (this.mode === Camera.PERSPECTIVE_CAMERA) {\n this._cache.fov = this.fov;\n this._cache.fovMode = this.fovMode;\n this._cache.aspectRatio = engine.getAspectRatio(this);\n if (this.minZ <= 0) {\n this.minZ = 0.1;\n }\n if (scene.useRightHandedSystem) {\n BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);\n }\n else {\n BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);\n }\n }\n else {\n var halfWidth = engine.getRenderWidth() / 2.0;\n var halfHeight = engine.getRenderHeight() / 2.0;\n if (scene.useRightHandedSystem) {\n BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);\n }\n else {\n BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);\n }\n this._cache.orthoLeft = this.orthoLeft;\n this._cache.orthoRight = this.orthoRight;\n this._cache.orthoBottom = this.orthoBottom;\n this._cache.orthoTop = this.orthoTop;\n this._cache.renderWidth = engine.getRenderWidth();\n this._cache.renderHeight = engine.getRenderHeight();\n }\n this.onProjectionMatrixChangedObservable.notifyObservers(this);\n return this._projectionMatrix;\n };\n /**\n * Gets the transformation matrix (ie. the multiplication of view by projection matrices)\n * @returns a Matrix\n */\n Camera.prototype.getTransformationMatrix = function () {\n this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);\n return this._transformMatrix;\n };\n Camera.prototype.updateFrustumPlanes = function () {\n if (!this._refreshFrustumPlanes) {\n return;\n }\n this.getTransformationMatrix();\n if (!this._frustumPlanes) {\n this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);\n }\n else {\n BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);\n }\n this._refreshFrustumPlanes = false;\n };\n Camera.prototype.isInFrustum = function (target) {\n this.updateFrustumPlanes();\n return target.isInFrustum(this._frustumPlanes);\n };\n Camera.prototype.isCompletelyInFrustum = function (target) {\n this.updateFrustumPlanes();\n return target.isCompletelyInFrustum(this._frustumPlanes);\n };\n Camera.prototype.getForwardRay = function (length, transform, origin) {\n if (length === void 0) { length = 100; }\n if (!transform) {\n transform = this.getWorldMatrix();\n }\n if (!origin) {\n origin = this.position;\n }\n var forward = new BABYLON.Vector3(0, 0, 1);\n var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);\n var direction = BABYLON.Vector3.Normalize(forwardWorld);\n return new BABYLON.Ray(origin, direction, length);\n };\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n // Observables\n this.onViewMatrixChangedObservable.clear();\n this.onProjectionMatrixChangedObservable.clear();\n this.onAfterCheckInputsObservable.clear();\n this.onRestoreStateObservable.clear();\n // Inputs\n if (this.inputs) {\n this.inputs.clear();\n }\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from scene\n this.getScene().removeCamera(this);\n while (this._rigCameras.length > 0) {\n var camera = this._rigCameras.pop();\n if (camera) {\n camera.dispose();\n }\n }\n // Postprocesses\n if (this._rigPostProcess) {\n this._rigPostProcess.dispose(this);\n this._rigPostProcess = null;\n this._postProcesses = [];\n }\n else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n this._rigPostProcess = null;\n this._postProcesses = [];\n }\n else {\n var i = this._postProcesses.length;\n while (--i >= 0) {\n var postProcess = this._postProcesses[i];\n if (postProcess) {\n postProcess.dispose(this);\n }\n }\n }\n // Render targets\n var i = this.customRenderTargets.length;\n while (--i >= 0) {\n this.customRenderTargets[i].dispose();\n }\n this.customRenderTargets = [];\n // Active Meshes\n this._activeMeshes.dispose();\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n Object.defineProperty(Camera.prototype, \"leftCamera\", {\n // ---- Camera rigs section ----\n get: function () {\n if (this._rigCameras.length < 1) {\n return null;\n }\n return this._rigCameras[0];\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera.prototype, \"rightCamera\", {\n get: function () {\n if (this._rigCameras.length < 2) {\n return null;\n }\n return this._rigCameras[1];\n },\n enumerable: true,\n configurable: true\n });\n Camera.prototype.getLeftTarget = function () {\n if (this._rigCameras.length < 1) {\n return null;\n }\n return this._rigCameras[0].getTarget();\n };\n Camera.prototype.getRightTarget = function () {\n if (this._rigCameras.length < 2) {\n return null;\n }\n return this._rigCameras[1].getTarget();\n };\n Camera.prototype.setCameraRigMode = function (mode, rigParams) {\n if (this.cameraRigMode === mode) {\n return;\n }\n while (this._rigCameras.length > 0) {\n var camera = this._rigCameras.pop();\n if (camera) {\n camera.dispose();\n }\n }\n this.cameraRigMode = mode;\n this._cameraRigParams = {};\n //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,\n //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced\n this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;\n this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);\n // create the rig cameras, unless none\n if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n var leftCamera = this.createRigCamera(this.name + \"_L\", 0);\n var rightCamera = this.createRigCamera(this.name + \"_R\", 1);\n if (leftCamera && rightCamera) {\n this._rigCameras.push(leftCamera);\n this._rigCameras.push(rightCamera);\n }\n }\n switch (this.cameraRigMode) {\n case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + \"_passthru\", 1.0, this._rigCameras[0]);\n this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + \"_anaglyph\", 1.0, this._rigCameras);\n break;\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;\n this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + \"_passthru\", 1.0, this._rigCameras[0]);\n this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + \"_stereoInterlace\", this._rigCameras, isStereoscopicHoriz);\n break;\n case Camera.RIG_MODE_VR:\n var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();\n this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;\n this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);\n this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();\n this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;\n this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;\n this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;\n this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;\n this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);\n this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();\n this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;\n this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;\n this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;\n if (metrics.compensateDistortion) {\n this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess(\"VR_Distort_Compensation_Left\", this._rigCameras[0], false, metrics);\n this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess(\"VR_Distort_Compensation_Right\", this._rigCameras[1], true, metrics);\n }\n break;\n case Camera.RIG_MODE_WEBVR:\n if (rigParams.vrDisplay) {\n var leftEye = rigParams.vrDisplay.getEyeParameters('left');\n var rightEye = rigParams.vrDisplay.getEyeParameters('right');\n //Left eye\n this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);\n this._rigCameras[0].setCameraRigParameter(\"left\", true);\n //leaving this for future reference\n this._rigCameras[0].setCameraRigParameter(\"specs\", rigParams.specs);\n this._rigCameras[0].setCameraRigParameter(\"eyeParameters\", leftEye);\n this._rigCameras[0].setCameraRigParameter(\"frameData\", rigParams.frameData);\n this._rigCameras[0].setCameraRigParameter(\"parentCamera\", rigParams.parentCamera);\n this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();\n this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;\n this._rigCameras[0].parent = this;\n this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;\n //Right eye\n this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);\n this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);\n this._rigCameras[1].setCameraRigParameter(\"specs\", rigParams.specs);\n this._rigCameras[1].setCameraRigParameter(\"frameData\", rigParams.frameData);\n this._rigCameras[1].setCameraRigParameter(\"parentCamera\", rigParams.parentCamera);\n this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();\n this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;\n this._rigCameras[1].parent = this;\n this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;\n if (Camera.UseAlternateWebVRRendering) {\n this._rigCameras[1]._skipRendering = true;\n this._rigCameras[0]._alternateCamera = this._rigCameras[1];\n }\n }\n break;\n }\n this._cascadePostProcessesToRigCams();\n this.update();\n };\n Camera.prototype._getVRProjectionMatrix = function () {\n BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);\n this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);\n return this._projectionMatrix;\n };\n Camera.prototype._updateCameraRotationMatrix = function () {\n //Here for WebVR\n };\n Camera.prototype._updateWebVRCameraRotationMatrix = function () {\n //Here for WebVR\n };\n /**\n * This function MUST be overwritten by the different WebVR cameras available.\n * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.\n */\n Camera.prototype._getWebVRProjectionMatrix = function () {\n return BABYLON.Matrix.Identity();\n };\n /**\n * This function MUST be overwritten by the different WebVR cameras available.\n * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.\n */\n Camera.prototype._getWebVRViewMatrix = function () {\n return BABYLON.Matrix.Identity();\n };\n Camera.prototype.setCameraRigParameter = function (name, value) {\n if (!this._cameraRigParams) {\n this._cameraRigParams = {};\n }\n this._cameraRigParams[name] = value;\n //provisionnally:\n if (name === \"interaxialDistance\") {\n this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);\n }\n };\n /**\n * needs to be overridden by children so sub has required properties to be copied\n */\n Camera.prototype.createRigCamera = function (name, cameraIndex) {\n return null;\n };\n /**\n * May need to be overridden by children\n */\n Camera.prototype._updateRigCameras = function () {\n for (var i = 0; i < this._rigCameras.length; i++) {\n this._rigCameras[i].minZ = this.minZ;\n this._rigCameras[i].maxZ = this.maxZ;\n this._rigCameras[i].fov = this.fov;\n }\n // only update viewport when ANAGLYPH\n if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {\n this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;\n }\n };\n Camera.prototype._setupInputs = function () {\n };\n Camera.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n // Type\n serializationObject.type = this.getClassName();\n // Parent\n if (this.parent) {\n serializationObject.parentId = this.parent.id;\n }\n if (this.inputs) {\n this.inputs.serialize(serializationObject);\n }\n // Animations\n BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);\n serializationObject.ranges = this.serializeAnimationRanges();\n return serializationObject;\n };\n Camera.prototype.clone = function (name) {\n return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);\n };\n Camera.prototype.getDirection = function (localAxis) {\n var result = BABYLON.Vector3.Zero();\n this.getDirectionToRef(localAxis, result);\n return result;\n };\n Camera.prototype.getDirectionToRef = function (localAxis, result) {\n BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);\n };\n Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {\n if (interaxial_distance === void 0) { interaxial_distance = 0; }\n if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }\n var constructorFunc = BABYLON.Node.Construct(type, name, scene, {\n interaxial_distance: interaxial_distance,\n isStereoscopicSideBySide: isStereoscopicSideBySide\n });\n if (constructorFunc) {\n return constructorFunc;\n }\n // Default to universal camera\n return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };\n };\n Camera.prototype.computeWorldMatrix = function () {\n return this.getWorldMatrix();\n };\n Camera.Parse = function (parsedCamera, scene) {\n var type = parsedCamera.type;\n var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);\n var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);\n // Parent\n if (parsedCamera.parentId) {\n camera._waitingParentId = parsedCamera.parentId;\n }\n //If camera has an input manager, let it parse inputs settings\n if (camera.inputs) {\n camera.inputs.parse(parsedCamera);\n camera._setupInputs();\n }\n if (camera.setPosition) { // need to force position\n camera.position.copyFromFloats(0, 0, 0);\n camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));\n }\n // Target\n if (parsedCamera.target) {\n if (camera.setTarget) {\n camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));\n }\n }\n // Apply 3d rig, when found\n if (parsedCamera.cameraRigMode) {\n var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};\n camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);\n }\n // Animations\n if (parsedCamera.animations) {\n for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {\n var parsedAnimation = parsedCamera.animations[animationIndex];\n camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);\n }\n if (parsedCamera.autoAnimate) {\n scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);\n }\n return camera;\n };\n // Statics\n Camera._PERSPECTIVE_CAMERA = 0;\n Camera._ORTHOGRAPHIC_CAMERA = 1;\n Camera._FOVMODE_VERTICAL_FIXED = 0;\n Camera._FOVMODE_HORIZONTAL_FIXED = 1;\n Camera._RIG_MODE_NONE = 0;\n Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;\n Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;\n Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;\n Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;\n Camera._RIG_MODE_VR = 20;\n Camera._RIG_MODE_WEBVR = 21;\n Camera.ForceAttachControlToAlwaysPreventDefault = false;\n Camera.UseAlternateWebVRRendering = false;\n __decorate([\n BABYLON.serializeAsVector3()\n ], Camera.prototype, \"position\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], Camera.prototype, \"upVector\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"orthoLeft\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"orthoRight\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"orthoBottom\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"orthoTop\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"fov\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"minZ\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"maxZ\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"inertia\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"mode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"layerMask\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"fovMode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"cameraRigMode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"interaxialDistance\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"isStereoscopicSideBySide\", void 0);\n return Camera;\n }(BABYLON.Node));\n BABYLON.Camera = Camera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.camera.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var RenderingManager = /** @class */ (function () {\n function RenderingManager(scene) {\n /**\n * Hidden\n */\n this._useSceneAutoClearSetup = false;\n this._renderingGroups = new Array();\n this._autoClearDepthStencil = {};\n this._customOpaqueSortCompareFn = {};\n this._customAlphaTestSortCompareFn = {};\n this._customTransparentSortCompareFn = {};\n this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();\n this._scene = scene;\n for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {\n this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };\n }\n }\n RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {\n if (depth === void 0) { depth = true; }\n if (stencil === void 0) { stencil = true; }\n if (this._depthStencilBufferAlreadyCleaned) {\n return;\n }\n this._scene.getEngine().clear(null, false, depth, stencil);\n this._depthStencilBufferAlreadyCleaned = true;\n };\n RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {\n // Update the observable context (not null as it only goes away on dispose)\n var info = this._renderingGroupInfo;\n info.scene = this._scene;\n info.camera = this._scene.activeCamera;\n // Dispatch sprites\n if (renderSprites) {\n for (var index = 0; index < this._scene.spriteManagers.length; index++) {\n var manager = this._scene.spriteManagers[index];\n this.dispatchSprites(manager);\n }\n }\n // Render\n for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;\n var renderingGroup = this._renderingGroups[index];\n if (!renderingGroup)\n continue;\n var renderingGroupMask = Math.pow(2, index);\n info.renderingGroupId = index;\n // Before Observable\n this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);\n // Clear depth/stencil if needed\n if (RenderingManager.AUTOCLEAR) {\n var autoClear = this._useSceneAutoClearSetup ?\n this._scene.getAutoClearDepthStencilSetup(index) :\n this._autoClearDepthStencil[index];\n if (autoClear && autoClear.autoClear) {\n this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);\n }\n }\n // Render\n for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {\n var step = _a[_i];\n step.action(index);\n }\n renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);\n for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {\n var step = _c[_b];\n step.action(index);\n }\n // After Observable\n this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);\n }\n };\n RenderingManager.prototype.reset = function () {\n for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n var renderingGroup = this._renderingGroups[index];\n if (renderingGroup) {\n renderingGroup.prepare();\n }\n }\n };\n RenderingManager.prototype.dispose = function () {\n this.freeRenderingGroups();\n this._renderingGroups.length = 0;\n this._renderingGroupInfo = null;\n };\n /**\n * Clear the info related to rendering groups preventing retention points during dispose.\n */\n RenderingManager.prototype.freeRenderingGroups = function () {\n for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n var renderingGroup = this._renderingGroups[index];\n if (renderingGroup) {\n renderingGroup.dispose();\n }\n }\n };\n RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {\n if (this._renderingGroups[renderingGroupId] === undefined) {\n this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);\n }\n };\n RenderingManager.prototype.dispatchSprites = function (spriteManager) {\n var renderingGroupId = spriteManager.renderingGroupId || 0;\n this._prepareRenderingGroup(renderingGroupId);\n this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);\n };\n RenderingManager.prototype.dispatchParticles = function (particleSystem) {\n var renderingGroupId = particleSystem.renderingGroupId || 0;\n this._prepareRenderingGroup(renderingGroupId);\n this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);\n };\n /**\n * @param subMesh The submesh to dispatch\n * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.\n * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.\n */\n RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {\n if (mesh === undefined) {\n mesh = subMesh.getMesh();\n }\n var renderingGroupId = mesh.renderingGroupId || 0;\n this._prepareRenderingGroup(renderingGroupId);\n this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);\n };\n /**\n * Overrides the default sort function applied in the renderging group to prepare the meshes.\n * This allowed control for front to back rendering or reversly depending of the special needs.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param opaqueSortCompareFn The opaque queue comparison function use to sort.\n * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.\n * @param transparentSortCompareFn The transparent queue comparison function use to sort.\n */\n RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {\n if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }\n if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }\n if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }\n this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;\n this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;\n this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;\n if (this._renderingGroups[renderingGroupId]) {\n var group = this._renderingGroups[renderingGroupId];\n group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];\n group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];\n group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];\n }\n };\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n * @param depth Automatically clears depth between groups if true and autoClear is true.\n * @param stencil Automatically clears stencil between groups if true and autoClear is true.\n */\n RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {\n if (depth === void 0) { depth = true; }\n if (stencil === void 0) { stencil = true; }\n this._autoClearDepthStencil[renderingGroupId] = {\n autoClear: autoClearDepthStencil,\n depth: depth,\n stencil: stencil\n };\n };\n /**\n * Gets the current auto clear configuration for one rendering group of the rendering\n * manager.\n * @param index the rendering group index to get the information for\n * @returns The auto clear setup for the requested rendering group\n */\n RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {\n return this._autoClearDepthStencil[index];\n };\n /**\n * The max id used for rendering groups (not included)\n */\n RenderingManager.MAX_RENDERINGGROUPS = 4;\n /**\n * The min id used for rendering groups (included)\n */\n RenderingManager.MIN_RENDERINGGROUPS = 0;\n /**\n * Used to globally prevent autoclearing scenes.\n */\n RenderingManager.AUTOCLEAR = true;\n return RenderingManager;\n }());\n BABYLON.RenderingManager = RenderingManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.renderingManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var RenderingGroup = /** @class */ (function () {\n /**\n * Creates a new rendering group.\n * @param index The rendering group index\n * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied\n * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied\n * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied\n */\n function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {\n if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }\n if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }\n if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }\n this.index = index;\n this._opaqueSubMeshes = new BABYLON.SmartArray(256);\n this._transparentSubMeshes = new BABYLON.SmartArray(256);\n this._alphaTestSubMeshes = new BABYLON.SmartArray(256);\n this._depthOnlySubMeshes = new BABYLON.SmartArray(256);\n this._particleSystems = new BABYLON.SmartArray(256);\n this._spriteManagers = new BABYLON.SmartArray(256);\n this._edgesRenderers = new BABYLON.SmartArray(16);\n this._scene = scene;\n this.opaqueSortCompareFn = opaqueSortCompareFn;\n this.alphaTestSortCompareFn = alphaTestSortCompareFn;\n this.transparentSortCompareFn = transparentSortCompareFn;\n }\n Object.defineProperty(RenderingGroup.prototype, \"opaqueSortCompareFn\", {\n /**\n * Set the opaque sort comparison function.\n * If null the sub meshes will be render in the order they were created\n */\n set: function (value) {\n this._opaqueSortCompareFn = value;\n if (value) {\n this._renderOpaque = this.renderOpaqueSorted;\n }\n else {\n this._renderOpaque = RenderingGroup.renderUnsorted;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderingGroup.prototype, \"alphaTestSortCompareFn\", {\n /**\n * Set the alpha test sort comparison function.\n * If null the sub meshes will be render in the order they were created\n */\n set: function (value) {\n this._alphaTestSortCompareFn = value;\n if (value) {\n this._renderAlphaTest = this.renderAlphaTestSorted;\n }\n else {\n this._renderAlphaTest = RenderingGroup.renderUnsorted;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderingGroup.prototype, \"transparentSortCompareFn\", {\n /**\n * Set the transparent sort comparison function.\n * If null the sub meshes will be render in the order they were created\n */\n set: function (value) {\n if (value) {\n this._transparentSortCompareFn = value;\n }\n else {\n this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;\n }\n this._renderTransparent = this.renderTransparentSorted;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Render all the sub meshes contained in the group.\n * @param customRenderFunction Used to override the default render behaviour of the group.\n * @returns true if rendered some submeshes.\n */\n RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {\n if (customRenderFunction) {\n customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);\n return;\n }\n var engine = this._scene.getEngine();\n // Depth only\n if (this._depthOnlySubMeshes.length !== 0) {\n engine.setColorWrite(false);\n this._renderAlphaTest(this._depthOnlySubMeshes);\n engine.setColorWrite(true);\n }\n // Opaque\n if (this._opaqueSubMeshes.length !== 0) {\n this._renderOpaque(this._opaqueSubMeshes);\n }\n // Alpha test\n if (this._alphaTestSubMeshes.length !== 0) {\n this._renderAlphaTest(this._alphaTestSubMeshes);\n }\n var stencilState = engine.getStencilBuffer();\n engine.setStencilBuffer(false);\n // Sprites\n if (renderSprites) {\n this._renderSprites();\n }\n // Particles\n if (renderParticles) {\n this._renderParticles(activeMeshes);\n }\n if (this.onBeforeTransparentRendering) {\n this.onBeforeTransparentRendering();\n }\n // Transparent\n if (this._transparentSubMeshes.length !== 0) {\n this._renderTransparent(this._transparentSubMeshes);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n }\n // Set back stencil to false in case it changes before the edge renderer.\n engine.setStencilBuffer(false);\n // Edges\n for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {\n this._edgesRenderers.data[edgesRendererIndex].render();\n }\n // Restore Stencil state.\n engine.setStencilBuffer(stencilState);\n };\n /**\n * Renders the opaque submeshes in the order from the opaqueSortCompareFn.\n * @param subMeshes The submeshes to render\n */\n RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {\n return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);\n };\n /**\n * Renders the opaque submeshes in the order from the alphatestSortCompareFn.\n * @param subMeshes The submeshes to render\n */\n RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {\n return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);\n };\n /**\n * Renders the opaque submeshes in the order from the transparentSortCompareFn.\n * @param subMeshes The submeshes to render\n */\n RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {\n return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);\n };\n /**\n * Renders the submeshes in a specified order.\n * @param subMeshes The submeshes to sort before render\n * @param sortCompareFn The comparison function use to sort\n * @param cameraPosition The camera position use to preprocess the submeshes to help sorting\n * @param transparent Specifies to activate blending if true\n */\n RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {\n var subIndex = 0;\n var subMesh;\n var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();\n for (; subIndex < subMeshes.length; subIndex++) {\n subMesh = subMeshes.data[subIndex];\n subMesh._alphaIndex = subMesh.getMesh().alphaIndex;\n subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();\n }\n var sortedArray = subMeshes.data.slice(0, subMeshes.length);\n if (sortCompareFn) {\n sortedArray.sort(sortCompareFn);\n }\n for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {\n subMesh = sortedArray[subIndex];\n if (transparent) {\n var material = subMesh.getMaterial();\n if (material && material.needDepthPrePass) {\n var engine = material.getScene().getEngine();\n engine.setColorWrite(false);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n subMesh.render(false);\n engine.setColorWrite(true);\n }\n }\n subMesh.render(transparent);\n }\n };\n /**\n * Renders the submeshes in the order they were dispatched (no sort applied).\n * @param subMeshes The submeshes to render\n */\n RenderingGroup.renderUnsorted = function (subMeshes) {\n for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {\n var submesh = subMeshes.data[subIndex];\n submesh.render(false);\n }\n };\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are rendered back to front if in the same alpha index.\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n RenderingGroup.defaultTransparentSortCompare = function (a, b) {\n // Alpha index first\n if (a._alphaIndex > b._alphaIndex) {\n return 1;\n }\n if (a._alphaIndex < b._alphaIndex) {\n return -1;\n }\n // Then distance to camera\n return RenderingGroup.backToFrontSortCompare(a, b);\n };\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are rendered back to front.\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n RenderingGroup.backToFrontSortCompare = function (a, b) {\n // Then distance to camera\n if (a._distanceToCamera < b._distanceToCamera) {\n return 1;\n }\n if (a._distanceToCamera > b._distanceToCamera) {\n return -1;\n }\n return 0;\n };\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are rendered front to back (prevent overdraw).\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n RenderingGroup.frontToBackSortCompare = function (a, b) {\n // Then distance to camera\n if (a._distanceToCamera < b._distanceToCamera) {\n return -1;\n }\n if (a._distanceToCamera > b._distanceToCamera) {\n return 1;\n }\n return 0;\n };\n /**\n * Resets the different lists of submeshes to prepare a new frame.\n */\n RenderingGroup.prototype.prepare = function () {\n this._opaqueSubMeshes.reset();\n this._transparentSubMeshes.reset();\n this._alphaTestSubMeshes.reset();\n this._depthOnlySubMeshes.reset();\n this._particleSystems.reset();\n this._spriteManagers.reset();\n this._edgesRenderers.reset();\n };\n RenderingGroup.prototype.dispose = function () {\n this._opaqueSubMeshes.dispose();\n this._transparentSubMeshes.dispose();\n this._alphaTestSubMeshes.dispose();\n this._depthOnlySubMeshes.dispose();\n this._particleSystems.dispose();\n this._spriteManagers.dispose();\n this._edgesRenderers.dispose();\n };\n /**\n * Inserts the submesh in its correct queue depending on its material.\n * @param subMesh The submesh to dispatch\n * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.\n * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.\n */\n RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {\n // Get mesh and materials if not provided\n if (mesh === undefined) {\n mesh = subMesh.getMesh();\n }\n if (material === undefined) {\n material = subMesh.getMaterial();\n }\n if (material === null || material === undefined) {\n return;\n }\n if (material.needAlphaBlendingForMesh(mesh)) { // Transparent\n this._transparentSubMeshes.push(subMesh);\n }\n else if (material.needAlphaTesting()) { // Alpha test\n if (material.needDepthPrePass) {\n this._depthOnlySubMeshes.push(subMesh);\n }\n this._alphaTestSubMeshes.push(subMesh);\n }\n else {\n if (material.needDepthPrePass) {\n this._depthOnlySubMeshes.push(subMesh);\n }\n this._opaqueSubMeshes.push(subMesh); // Opaque\n }\n if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {\n this._edgesRenderers.push(mesh._edgesRenderer);\n }\n };\n RenderingGroup.prototype.dispatchSprites = function (spriteManager) {\n this._spriteManagers.push(spriteManager);\n };\n RenderingGroup.prototype.dispatchParticles = function (particleSystem) {\n this._particleSystems.push(particleSystem);\n };\n RenderingGroup.prototype._renderParticles = function (activeMeshes) {\n if (this._particleSystems.length === 0) {\n return;\n }\n // Particles\n var activeCamera = this._scene.activeCamera;\n this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);\n for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {\n var particleSystem = this._particleSystems.data[particleIndex];\n if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {\n continue;\n }\n var emitter = particleSystem.emitter;\n if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {\n this._scene._activeParticles.addCount(particleSystem.render(), false);\n }\n }\n this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);\n };\n RenderingGroup.prototype._renderSprites = function () {\n if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {\n return;\n }\n // Sprites \n var activeCamera = this._scene.activeCamera;\n this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);\n for (var id = 0; id < this._spriteManagers.length; id++) {\n var spriteManager = this._spriteManagers.data[id];\n if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {\n spriteManager.render();\n }\n }\n this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);\n };\n return RenderingGroup;\n }());\n BABYLON.RenderingGroup = RenderingGroup;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.renderingGroup.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Groups all the scene component constants in one place to ease maintenance.\n * @hidden\n */\n var SceneComponentConstants = /** @class */ (function () {\n function SceneComponentConstants() {\n }\n SceneComponentConstants.NAME_EFFECTLAYER = \"EffectLayer\";\n SceneComponentConstants.NAME_LAYER = \"Layer\";\n SceneComponentConstants.NAME_LENSFLARESYSTEM = \"LensFlareSystem\";\n SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = \"BoundingBoxRenderer\";\n SceneComponentConstants.NAME_PARTICLESYSTEM = \"ParticleSystem\";\n SceneComponentConstants.NAME_GAMEPAD = \"Gamepad\";\n SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;\n SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;\n SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;\n SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;\n SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;\n SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;\n SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;\n SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;\n SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;\n SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;\n SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;\n SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;\n SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;\n SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;\n return SceneComponentConstants;\n }());\n BABYLON.SceneComponentConstants = SceneComponentConstants;\n /**\n * Repressentation of a stage in the scene (Basically a list of ordered steps)\n * @hidden\n */\n var Stage = /** @class */ (function (_super) {\n __extends(Stage, _super);\n /**\n * Hide ctor from the rest of the world.\n * @param items The items to add.\n */\n function Stage(items) {\n return _super.apply(this, items) || this;\n }\n /**\n * Creates a new Stage.\n * @returns A new instance of a Stage\n */\n Stage.Create = function () {\n return Object.create(Stage.prototype);\n };\n /**\n * Registers a step in an ordered way in the targeted stage.\n * @param index Defines the position to register the step in\n * @param component Defines the component attached to the step\n * @param action Defines the action to launch during the step\n */\n Stage.prototype.registerStep = function (index, component, action) {\n var i = 0;\n var maxIndex = Number.MAX_VALUE;\n for (; i < this.length && i < maxIndex; i++) {\n var step = this[i];\n maxIndex = step.index;\n }\n this.splice(i, 0, { index: index, component: component, action: action.bind(component) });\n };\n /**\n * Clears all the steps from the stage.\n */\n Stage.prototype.clear = function () {\n this.length = 0;\n };\n return Stage;\n }(Array));\n BABYLON.Stage = Stage;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sceneComponent.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Base class of the scene acting as a container for the different elements composing a scene.\n * This class is dynamically extended by the different components of the scene increasing\n * flexibility and reducing coupling\n */\n var AbstractScene = /** @class */ (function () {\n function AbstractScene() {\n /** All of the cameras added to this scene\n * @see http://doc.babylonjs.com/babylon101/cameras\n */\n this.cameras = new Array();\n /**\n * All of the lights added to this scene\n * @see http://doc.babylonjs.com/babylon101/lights\n */\n this.lights = new Array();\n /**\n * All of the (abstract) meshes added to this scene\n */\n this.meshes = new Array();\n /**\n * The list of skeletons added to the scene\n * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons\n */\n this.skeletons = new Array();\n /**\n * All of the particle systems added to this scene\n * @see http://doc.babylonjs.com/babylon101/particles\n */\n this.particleSystems = new Array();\n /**\n * Gets a list of Animations associated with the scene\n */\n this.animations = [];\n /**\n * All of the animation groups added to this scene\n * @see http://doc.babylonjs.com/how_to/group\n */\n this.animationGroups = new Array();\n /**\n * All of the multi-materials added to this scene\n * @see http://doc.babylonjs.com/how_to/multi_materials\n */\n this.multiMaterials = new Array();\n /**\n * All of the materials added to this scene\n * @see http://doc.babylonjs.com/babylon101/materials\n */\n this.materials = new Array();\n /**\n * The list of morph target managers added to the scene\n * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh\n */\n this.morphTargetManagers = new Array();\n /**\n * The list of geometries used in the scene.\n */\n this.geometries = new Array();\n /**\n * All of the tranform nodes added to this scene\n * @see http://doc.babylonjs.com/how_to/transformnode\n */\n this.transformNodes = new Array();\n /**\n * ActionManagers available on the scene.\n */\n this.actionManagers = new Array();\n /**\n * Sounds to keep.\n */\n this.sounds = new Array();\n /**\n * Textures to keep.\n */\n this.textures = new Array();\n }\n /**\n * Adds a parser in the list of available ones\n * @param name Defines the name of the parser\n * @param parser Defines the parser to add\n */\n AbstractScene.AddParser = function (name, parser) {\n this._BabylonFileParsers[name] = parser;\n };\n /**\n * Gets a general parser from the list of avaialble ones\n * @param name Defines the name of the parser\n * @returns the requested parser or null\n */\n AbstractScene.GetParser = function (name) {\n if (this._BabylonFileParsers[name]) {\n return this._BabylonFileParsers[name];\n }\n return null;\n };\n /**\n * Adds n individual parser in the list of available ones\n * @param name Defines the name of the parser\n * @param parser Defines the parser to add\n */\n AbstractScene.AddIndividualParser = function (name, parser) {\n this._IndividualBabylonFileParsers[name] = parser;\n };\n /**\n * Gets an individual parser from the list of avaialble ones\n * @param name Defines the name of the parser\n * @returns the requested parser or null\n */\n AbstractScene.GetIndividualParser = function (name) {\n if (this._IndividualBabylonFileParsers[name]) {\n return this._IndividualBabylonFileParsers[name];\n }\n return null;\n };\n /**\n * Parser json data and populate both a scene and its associated container object\n * @param jsonData Defines the data to parse\n * @param scene Defines the scene to parse the data for\n * @param container Defines the container attached to the parsing sequence\n * @param rootUrl Defines the root url of the data\n */\n AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {\n for (var parserName in this._BabylonFileParsers) {\n if (this._BabylonFileParsers.hasOwnProperty(parserName)) {\n this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);\n }\n }\n };\n /**\n * Stores the list of available parsers in the application.\n */\n AbstractScene._BabylonFileParsers = {};\n /**\n * Stores the list of available individual parsers in the application.\n */\n AbstractScene._IndividualBabylonFileParsers = {};\n return AbstractScene;\n }());\n BABYLON.AbstractScene = AbstractScene;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.abstractScene.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /** @hidden */\n var ClickInfo = /** @class */ (function () {\n function ClickInfo() {\n this._singleClick = false;\n this._doubleClick = false;\n this._hasSwiped = false;\n this._ignore = false;\n }\n Object.defineProperty(ClickInfo.prototype, \"singleClick\", {\n get: function () {\n return this._singleClick;\n },\n set: function (b) {\n this._singleClick = b;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ClickInfo.prototype, \"doubleClick\", {\n get: function () {\n return this._doubleClick;\n },\n set: function (b) {\n this._doubleClick = b;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ClickInfo.prototype, \"hasSwiped\", {\n get: function () {\n return this._hasSwiped;\n },\n set: function (b) {\n this._hasSwiped = b;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ClickInfo.prototype, \"ignore\", {\n get: function () {\n return this._ignore;\n },\n set: function (b) {\n this._ignore = b;\n },\n enumerable: true,\n configurable: true\n });\n return ClickInfo;\n }());\n /**\n * This class is used by the onRenderingGroupObservable\n */\n var RenderingGroupInfo = /** @class */ (function () {\n function RenderingGroupInfo() {\n }\n return RenderingGroupInfo;\n }());\n BABYLON.RenderingGroupInfo = RenderingGroupInfo;\n /**\n * Represents a scene to be rendered by the engine.\n * @see http://doc.babylonjs.com/features/scene\n */\n var Scene = /** @class */ (function (_super) {\n __extends(Scene, _super);\n /**\n * Creates a new Scene\n * @param engine defines the engine to use to render this scene\n */\n function Scene(engine) {\n var _this = _super.call(this) || this;\n // Members\n /**\n * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame\n */\n _this.autoClear = true;\n /**\n * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame\n */\n _this.autoClearDepthAndStencil = true;\n /**\n * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))\n */\n _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);\n /**\n * Defines the color used to simulate the ambient color (Default is (0, 0, 0))\n */\n _this.ambientColor = new BABYLON.Color3(0, 0, 0);\n _this._forceWireframe = false;\n _this._forcePointsCloud = false;\n /**\n * Gets or sets a boolean indicating if animations are enabled\n */\n _this.animationsEnabled = true;\n _this._animationPropertiesOverride = null;\n /**\n * Gets or sets a boolean indicating if a constant deltatime has to be used\n * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate\n */\n _this.useConstantAnimationDeltaTime = false;\n /**\n * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated\n * Please note that it requires to run a ray cast through the scene on every frame\n */\n _this.constantlyUpdateMeshUnderPointer = false;\n /**\n * Defines the HTML cursor to use when hovering over interactive elements\n */\n _this.hoverCursor = \"pointer\";\n /**\n * Defines the HTML default cursor to use (empty by default)\n */\n _this.defaultCursor = \"\";\n /**\n * This is used to call preventDefault() on pointer down\n * in order to block unwanted artifacts like system double clicks\n */\n _this.preventDefaultOnPointerDown = true;\n // Metadata\n /**\n * Gets or sets user defined metadata\n */\n _this.metadata = null;\n /**\n * Use this array to add regular expressions used to disable offline support for specific urls\n */\n _this.disableOfflineSupportExceptionRules = new Array();\n /**\n * An event triggered when the scene is disposed.\n */\n _this.onDisposeObservable = new BABYLON.Observable();\n _this._onDisposeObserver = null;\n /**\n * An event triggered before rendering the scene (right after animations and physics)\n */\n _this.onBeforeRenderObservable = new BABYLON.Observable();\n _this._onBeforeRenderObserver = null;\n /**\n * An event triggered after rendering the scene\n */\n _this.onAfterRenderObservable = new BABYLON.Observable();\n _this._onAfterRenderObserver = null;\n /**\n * An event triggered before animating the scene\n */\n _this.onBeforeAnimationsObservable = new BABYLON.Observable();\n /**\n * An event triggered after animations processing\n */\n _this.onAfterAnimationsObservable = new BABYLON.Observable();\n /**\n * An event triggered before draw calls are ready to be sent\n */\n _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();\n /**\n * An event triggered after draw calls have been sent\n */\n _this.onAfterDrawPhaseObservable = new BABYLON.Observable();\n /**\n * An event triggered when physic simulation is about to be run\n */\n _this.onBeforePhysicsObservable = new BABYLON.Observable();\n /**\n * An event triggered when physic simulation has been done\n */\n _this.onAfterPhysicsObservable = new BABYLON.Observable();\n /**\n * An event triggered when the scene is ready\n */\n _this.onReadyObservable = new BABYLON.Observable();\n /**\n * An event triggered before rendering a camera\n */\n _this.onBeforeCameraRenderObservable = new BABYLON.Observable();\n _this._onBeforeCameraRenderObserver = null;\n /**\n * An event triggered after rendering a camera\n */\n _this.onAfterCameraRenderObservable = new BABYLON.Observable();\n _this._onAfterCameraRenderObserver = null;\n /**\n * An event triggered when active meshes evaluation is about to start\n */\n _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();\n /**\n * An event triggered when active meshes evaluation is done\n */\n _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();\n /**\n * An event triggered when particles rendering is about to start\n * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)\n */\n _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();\n /**\n * An event triggered when particles rendering is done\n * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)\n */\n _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();\n /**\n * An event triggered when sprites rendering is about to start\n * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)\n */\n _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();\n /**\n * An event triggered when sprites rendering is done\n * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)\n */\n _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();\n /**\n * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed\n */\n _this.onDataLoadedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a camera is created\n */\n _this.onNewCameraAddedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a camera is removed\n */\n _this.onCameraRemovedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a light is created\n */\n _this.onNewLightAddedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a light is removed\n */\n _this.onLightRemovedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a geometry is created\n */\n _this.onNewGeometryAddedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a geometry is removed\n */\n _this.onGeometryRemovedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a transform node is created\n */\n _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a transform node is removed\n */\n _this.onTransformNodeRemovedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a mesh is created\n */\n _this.onNewMeshAddedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a mesh is removed\n */\n _this.onMeshRemovedObservable = new BABYLON.Observable();\n /**\n * An event triggered when render targets are about to be rendered\n * Can happen multiple times per frame.\n */\n _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered when render targets were rendered.\n * Can happen multiple times per frame.\n */\n _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered before calculating deterministic simulation step\n */\n _this.onBeforeStepObservable = new BABYLON.Observable();\n /**\n * An event triggered after calculating deterministic simulation step\n */\n _this.onAfterStepObservable = new BABYLON.Observable();\n /**\n * This Observable will be triggered before rendering each renderingGroup of each rendered camera.\n * The RenderinGroupInfo class contains all the information about the context in which the observable is called\n * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)\n */\n _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();\n /**\n * This Observable will be triggered after rendering each renderingGroup of each rendered camera.\n * The RenderinGroupInfo class contains all the information about the context in which the observable is called\n * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)\n */\n _this.onAfterRenderingGroupObservable = new BABYLON.Observable();\n // Animations\n _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);\n /**\n * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).\n * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true\n */\n _this.onPrePointerObservable = new BABYLON.Observable();\n /**\n * Observable event triggered each time an input event is received from the rendering canvas\n */\n _this.onPointerObservable = new BABYLON.Observable();\n _this._meshPickProceed = false;\n _this._currentPickResult = null;\n _this._previousPickResult = null;\n _this._totalPointersPressed = 0;\n _this._doubleClickOccured = false;\n /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */\n _this.cameraToUseForPointers = null;\n _this._pointerX = 0;\n _this._pointerY = 0;\n _this._startingPointerPosition = new BABYLON.Vector2(0, 0);\n _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);\n _this._startingPointerTime = 0;\n _this._previousStartingPointerTime = 0;\n _this._pointerCaptures = {};\n // Deterministic lockstep\n _this._timeAccumulator = 0;\n _this._currentStepId = 0;\n _this._currentInternalStep = 0;\n // Keyboard\n /**\n * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()\n * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true\n */\n _this.onPreKeyboardObservable = new BABYLON.Observable();\n /**\n * Observable event triggered each time an keyboard event is received from the hosting window\n */\n _this.onKeyboardObservable = new BABYLON.Observable();\n // Coordinates system\n _this._useRightHandedSystem = false;\n // Fog\n _this._fogEnabled = true;\n _this._fogMode = Scene.FOGMODE_NONE;\n /**\n * Gets or sets the fog color to use\n * @see http://doc.babylonjs.com/babylon101/environment#fog\n */\n _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);\n /**\n * Gets or sets the fog density to use\n * @see http://doc.babylonjs.com/babylon101/environment#fog\n */\n _this.fogDensity = 0.1;\n /**\n * Gets or sets the fog start distance to use\n * @see http://doc.babylonjs.com/babylon101/environment#fog\n */\n _this.fogStart = 0;\n /**\n * Gets or sets the fog end distance to use\n * @see http://doc.babylonjs.com/babylon101/environment#fog\n */\n _this.fogEnd = 1000.0;\n // Lights\n _this._shadowsEnabled = true;\n _this._lightsEnabled = true;\n /** All of the active cameras added to this scene. */\n _this.activeCameras = new Array();\n // Textures\n _this._texturesEnabled = true;\n // Particles\n /**\n * Gets or sets a boolean indicating if particles are enabled on this scene\n */\n _this.particlesEnabled = true;\n // Sprites\n /**\n * Gets or sets a boolean indicating if sprites are enabled on this scene\n */\n _this.spritesEnabled = true;\n /**\n * All of the sprite managers added to this scene\n * @see http://doc.babylonjs.com/babylon101/sprites\n */\n _this.spriteManagers = new Array();\n // Skeletons\n _this._skeletonsEnabled = true;\n // Lens flares\n /**\n * Gets or sets a boolean indicating if lens flares are enabled on this scene\n */\n _this.lensFlaresEnabled = true;\n // Collisions\n /**\n * Gets or sets a boolean indicating if collisions are enabled on this scene\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */\n _this.collisionsEnabled = true;\n /**\n * Defines the gravity applied to this scene (used only for collisions)\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */\n _this.gravity = new BABYLON.Vector3(0, -9.807, 0);\n // Postprocesses\n /**\n * Gets or sets a boolean indicating if postprocesses are enabled on this scene\n */\n _this.postProcessesEnabled = true;\n /**\n * The list of postprocesses added to the scene\n */\n _this.postProcesses = new Array();\n // Customs render targets\n /**\n * Gets or sets a boolean indicating if render targets are enabled on this scene\n */\n _this.renderTargetsEnabled = true;\n /**\n * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes\n * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com\n */\n _this.dumpNextRenderTargets = false;\n /**\n * The list of user defined render targets added to the scene\n */\n _this.customRenderTargets = new Array();\n /**\n * Gets the list of meshes imported to the scene through SceneLoader\n */\n _this.importedMeshesFiles = new Array();\n // Probes\n /**\n * Gets or sets a boolean indicating if probes are enabled on this scene\n */\n _this.probesEnabled = true;\n /**\n * The list of reflection probes added to the scene\n * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes\n */\n _this.reflectionProbes = new Array();\n _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);\n // Procedural textures\n /**\n * Gets or sets a boolean indicating if procedural textures are enabled on this scene\n */\n _this.proceduralTexturesEnabled = true;\n /**\n * The list of procedural textures added to the scene\n * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures\n */\n _this.proceduralTextures = new Array();\n /**\n * The list of sound tracks added to the scene\n * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music\n */\n _this.soundTracks = new Array();\n _this._audioEnabled = true;\n _this._headphone = false;\n // Performance counters\n _this._totalVertices = new BABYLON.PerfCounter();\n /** @hidden */\n _this._activeIndices = new BABYLON.PerfCounter();\n /** @hidden */\n _this._activeParticles = new BABYLON.PerfCounter();\n /** @hidden */\n _this._activeBones = new BABYLON.PerfCounter();\n _this._animationTime = 0;\n /**\n * Gets or sets a general scale for animation speed\n * @see https://www.babylonjs-playground.com/#IBU2W7#3\n */\n _this.animationTimeScale = 1;\n _this._renderId = 0;\n _this._executeWhenReadyTimeoutId = -1;\n _this._intermediateRendering = false;\n _this._viewUpdateFlag = -1;\n _this._projectionUpdateFlag = -1;\n _this._alternateViewUpdateFlag = -1;\n _this._alternateProjectionUpdateFlag = -1;\n /** @hidden */\n _this._toBeDisposed = new BABYLON.SmartArray(256);\n _this._activeRequests = new Array();\n _this._pendingData = new Array();\n _this._isDisposed = false;\n /**\n * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered\n * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)\n */\n _this.dispatchAllSubMeshesOfActiveMeshes = false;\n _this._activeMeshes = new BABYLON.SmartArray(256);\n _this._processedMaterials = new BABYLON.SmartArray(256);\n _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);\n /** @hidden */\n _this._activeParticleSystems = new BABYLON.SmartArray(256);\n _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);\n _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);\n /** @hidden */\n _this._activeAnimatables = new Array();\n _this._transformMatrix = BABYLON.Matrix.Zero();\n _this._useAlternateCameraConfiguration = false;\n _this._alternateRendering = false;\n /**\n * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)\n * This is useful if there are more lights that the maximum simulteanous authorized\n */\n _this.requireLightSorting = false;\n _this._depthRenderer = {};\n /**\n * Backing store of defined scene components.\n */\n _this._components = [];\n /**\n * Backing store of defined scene components.\n */\n _this._serializableComponents = [];\n /**\n * List of components to register on the next registration step.\n */\n _this._transientComponents = [];\n /**\n * Defines the actions happening before camera updates.\n */\n _this._beforeCameraUpdateStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening during the per mesh ready checks.\n */\n _this._isReadyForMeshStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening before evaluate active mesh checks.\n */\n _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening during the evaluate sub mesh checks.\n */\n _this._evaluateSubMeshStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening during the active mesh stage.\n */\n _this._activeMeshStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening during the per camera render target step.\n */\n _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening just before the active camera is drawing.\n */\n _this._beforeCameraDrawStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening just before a rendering group is drawing.\n */\n _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening just after a rendering group has been drawn.\n */\n _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening just after the active camera has been drawn.\n */\n _this._afterCameraDrawStage = BABYLON.Stage.Create();\n _this._activeMeshesFrozen = false;\n /** @hidden */\n _this._allowPostProcessClear = true;\n _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;\n _this._engine = engine || BABYLON.Engine.LastCreatedEngine;\n _this._engine.scenes.push(_this);\n _this._uid = null;\n _this._renderingManager = new BABYLON.RenderingManager(_this);\n if (BABYLON.PostProcessManager) {\n _this.postProcessManager = new BABYLON.PostProcessManager(_this);\n }\n if (BABYLON.OutlineRenderer) {\n _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);\n }\n if (BABYLON.Tools.IsWindowObjectExist()) {\n _this.attachControl();\n }\n //simplification queue\n if (BABYLON.SimplificationQueue) {\n _this.simplificationQueue = new BABYLON.SimplificationQueue();\n }\n //collision coordinator initialization. For now legacy per default.\n _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));\n // Uniform Buffer\n _this._createUbo();\n // Default Image processing definition\n if (BABYLON.ImageProcessingConfiguration) {\n _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();\n }\n return _this;\n }\n Object.defineProperty(Scene, \"FOGMODE_NONE\", {\n /** The fog is deactivated */\n get: function () {\n return Scene._FOGMODE_NONE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene, \"FOGMODE_EXP\", {\n /** The fog density is following an exponential function */\n get: function () {\n return Scene._FOGMODE_EXP;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene, \"FOGMODE_EXP2\", {\n /** The fog density is following an exponential function faster than FOGMODE_EXP */\n get: function () {\n return Scene._FOGMODE_EXP2;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene, \"FOGMODE_LINEAR\", {\n /** The fog density is following a linear function. */\n get: function () {\n return Scene._FOGMODE_LINEAR;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"environmentTexture\", {\n /**\n * Texture used in all pbr material as the reflection texture.\n * As in the majority of the scene they are the same (exception for multi room and so on),\n * this is easier to reference from here than from all the materials.\n */\n get: function () {\n return this._environmentTexture;\n },\n /**\n * Texture used in all pbr material as the reflection texture.\n * As in the majority of the scene they are the same (exception for multi room and so on),\n * this is easier to set here than in all the materials.\n */\n set: function (value) {\n if (this._environmentTexture === value) {\n return;\n }\n this._environmentTexture = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"imageProcessingConfiguration\", {\n /**\n * Default image processing configuration used either in the rendering\n * Forward main pass or through the imageProcessingPostProcess if present.\n * As in the majority of the scene they are the same (exception for multi camera),\n * this is easier to reference from here than from all the materials and post process.\n *\n * No setter as we it is a shared configuration, you can set the values instead.\n */\n get: function () {\n return this._imageProcessingConfiguration;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"forceWireframe\", {\n get: function () {\n return this._forceWireframe;\n },\n /**\n * Gets or sets a boolean indicating if all rendering must be done in wireframe\n */\n set: function (value) {\n if (this._forceWireframe === value) {\n return;\n }\n this._forceWireframe = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"forcePointsCloud\", {\n get: function () {\n return this._forcePointsCloud;\n },\n /**\n * Gets or sets a boolean indicating if all rendering must be done in point cloud\n */\n set: function (value) {\n if (this._forcePointsCloud === value) {\n return;\n }\n this._forcePointsCloud = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"animationPropertiesOverride\", {\n /**\n * Gets or sets the animation properties override\n */\n get: function () {\n return this._animationPropertiesOverride;\n },\n set: function (value) {\n this._animationPropertiesOverride = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"onDispose\", {\n /** Sets a function to be executed when this scene is disposed. */\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"beforeRender\", {\n /** Sets a function to be executed before rendering this scene */\n set: function (callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n if (callback) {\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"afterRender\", {\n /** Sets a function to be executed after rendering this scene */\n set: function (callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n if (callback) {\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"beforeCameraRender\", {\n /** Sets a function to be executed before rendering a camera*/\n set: function (callback) {\n if (this._onBeforeCameraRenderObserver) {\n this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n }\n this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"afterCameraRender\", {\n /** Sets a function to be executed after rendering a camera*/\n set: function (callback) {\n if (this._onAfterCameraRenderObserver) {\n this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);\n }\n this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"unTranslatedPointer\", {\n /**\n * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)\n */\n get: function () {\n return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"useRightHandedSystem\", {\n get: function () {\n return this._useRightHandedSystem;\n },\n /**\n * Gets or sets a boolean indicating if the scene must use right-handed coordinates system\n */\n set: function (value) {\n if (this._useRightHandedSystem === value) {\n return;\n }\n this._useRightHandedSystem = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Sets the step Id used by deterministic lock step\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n * @param newStepId defines the step Id\n */\n Scene.prototype.setStepId = function (newStepId) {\n this._currentStepId = newStepId;\n };\n ;\n /**\n * Gets the step Id used by deterministic lock step\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n * @returns the step Id\n */\n Scene.prototype.getStepId = function () {\n return this._currentStepId;\n };\n ;\n /**\n * Gets the internal step used by deterministic lock step\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n * @returns the internal step\n */\n Scene.prototype.getInternalStep = function () {\n return this._currentInternalStep;\n };\n ;\n Object.defineProperty(Scene.prototype, \"fogEnabled\", {\n get: function () {\n return this._fogEnabled;\n },\n /**\n * Gets or sets a boolean indicating if fog is enabled on this scene\n * @see http://doc.babylonjs.com/babylon101/environment#fog\n */\n set: function (value) {\n if (this._fogEnabled === value) {\n return;\n }\n this._fogEnabled = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"fogMode\", {\n get: function () {\n return this._fogMode;\n },\n /**\n * Gets or sets the fog mode to use\n * @see http://doc.babylonjs.com/babylon101/environment#fog\n */\n set: function (value) {\n if (this._fogMode === value) {\n return;\n }\n this._fogMode = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"shadowsEnabled\", {\n get: function () {\n return this._shadowsEnabled;\n },\n /**\n * Gets or sets a boolean indicating if shadows are enabled on this scene\n */\n set: function (value) {\n if (this._shadowsEnabled === value) {\n return;\n }\n this._shadowsEnabled = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"lightsEnabled\", {\n get: function () {\n return this._lightsEnabled;\n },\n /**\n * Gets or sets a boolean indicating if lights are enabled on this scene\n */\n set: function (value) {\n if (this._lightsEnabled === value) {\n return;\n }\n this._lightsEnabled = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"defaultMaterial\", {\n /** The default material used on meshes when no material is affected */\n get: function () {\n if (!this._defaultMaterial) {\n this._defaultMaterial = new BABYLON.StandardMaterial(\"default material\", this);\n }\n return this._defaultMaterial;\n },\n /** The default material used on meshes when no material is affected */\n set: function (value) {\n this._defaultMaterial = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"texturesEnabled\", {\n get: function () {\n return this._texturesEnabled;\n },\n /**\n * Gets or sets a boolean indicating if textures are enabled on this scene\n */\n set: function (value) {\n if (this._texturesEnabled === value) {\n return;\n }\n this._texturesEnabled = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"skeletonsEnabled\", {\n get: function () {\n return this._skeletonsEnabled;\n },\n /**\n * Gets or sets a boolean indicating if skeletons are enabled on this scene\n */\n set: function (value) {\n if (this._skeletonsEnabled === value) {\n return;\n }\n this._skeletonsEnabled = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"postProcessRenderPipelineManager\", {\n /**\n * Gets the postprocess render pipeline manager\n * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline\n * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline\n */\n get: function () {\n if (!this._postProcessRenderPipelineManager) {\n this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();\n }\n return this._postProcessRenderPipelineManager;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"mainSoundTrack\", {\n /**\n * Gets the main soundtrack associated with the scene\n */\n get: function () {\n if (!this._mainSoundTrack) {\n this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });\n }\n return this._mainSoundTrack;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"_isAlternateRenderingEnabled\", {\n /** @hidden */\n get: function () {\n return this._alternateRendering;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"frustumPlanes\", {\n /**\n * Gets the list of frustum planes (built from the active camera)\n */\n get: function () {\n return this._frustumPlanes;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"geometryBufferRenderer\", {\n /**\n * Gets the current geometry buffer associated to the scene.\n */\n get: function () {\n return this._geometryBufferRenderer;\n },\n /**\n * Sets the current geometry buffer for the scene.\n */\n set: function (geometryBufferRenderer) {\n if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {\n this._geometryBufferRenderer = geometryBufferRenderer;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Registers the transient components if needed.\n */\n Scene.prototype._registerTransientComponents = function () {\n // Register components that have been associated lately to the scene.\n if (this._transientComponents.length > 0) {\n for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {\n var component = _a[_i];\n component.register();\n }\n this._transientComponents = [];\n }\n };\n /**\n * Add a component to the scene.\n * Note that the ccomponent could be registered on th next frame if this is called after\n * the register component stage.\n * @param component Defines the component to add to the scene\n */\n Scene.prototype._addComponent = function (component) {\n this._components.push(component);\n this._transientComponents.push(component);\n var serializableComponent = component;\n if (serializableComponent.addFromContainer) {\n this._serializableComponents.push(serializableComponent);\n }\n };\n /**\n * Gets a component from the scene.\n * @param name defines the name of the component to retrieve\n * @returns the component or null if not present\n */\n Scene.prototype._getComponent = function (name) {\n for (var _i = 0, _a = this._components; _i < _a.length; _i++) {\n var component = _a[_i];\n if (component.name === name) {\n return component;\n }\n }\n return null;\n };\n Object.defineProperty(Scene.prototype, \"debugLayer\", {\n /**\n * Gets the debug layer (aka Inspector) associated with the scene\n * @see http://doc.babylonjs.com/features/playground_debuglayer\n */\n get: function () {\n if (!this._debugLayer) {\n this._debugLayer = new BABYLON.DebugLayer(this);\n }\n return this._debugLayer;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"workerCollisions\", {\n /**\n * Gets a boolean indicating if collisions are processed on a web worker\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21\n */\n get: function () {\n return this._workerCollisions;\n },\n set: function (enabled) {\n if (!BABYLON.CollisionCoordinatorLegacy) {\n return;\n }\n enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);\n this._workerCollisions = enabled;\n if (this.collisionCoordinator) {\n this.collisionCoordinator.destroy();\n }\n this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();\n this.collisionCoordinator.init(this);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"selectionOctree\", {\n /**\n * Gets the octree used to boost mesh selection (picking)\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees\n */\n get: function () {\n return this._selectionOctree;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"meshUnderPointer\", {\n /**\n * Gets the mesh that is currently under the pointer\n */\n get: function () {\n return this._pointerOverMesh;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"pointerX\", {\n /**\n * Gets the current on-screen X position of the pointer\n */\n get: function () {\n return this._pointerX;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"pointerY\", {\n /**\n * Gets the current on-screen Y position of the pointer\n */\n get: function () {\n return this._pointerY;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the cached material (ie. the latest rendered one)\n * @returns the cached material\n */\n Scene.prototype.getCachedMaterial = function () {\n return this._cachedMaterial;\n };\n /**\n * Gets the cached effect (ie. the latest rendered one)\n * @returns the cached effect\n */\n Scene.prototype.getCachedEffect = function () {\n return this._cachedEffect;\n };\n /**\n * Gets the cached visibility state (ie. the latest rendered one)\n * @returns the cached visibility state\n */\n Scene.prototype.getCachedVisibility = function () {\n return this._cachedVisibility;\n };\n /**\n * Gets a boolean indicating if the current material / effect / visibility must be bind again\n * @param material defines the current material\n * @param effect defines the current effect\n * @param visibility defines the current visibility state\n * @returns true if one parameter is not cached\n */\n Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {\n if (visibility === void 0) { visibility = 1; }\n return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;\n };\n /**\n * Gets the outline renderer associated with the scene\n * @returns a OutlineRenderer\n */\n Scene.prototype.getOutlineRenderer = function () {\n return this._outlineRenderer;\n };\n /**\n * Gets the engine associated with the scene\n * @returns an Engine\n */\n Scene.prototype.getEngine = function () {\n return this._engine;\n };\n /**\n * Gets the total number of vertices rendered per frame\n * @returns the total number of vertices rendered per frame\n */\n Scene.prototype.getTotalVertices = function () {\n return this._totalVertices.current;\n };\n Object.defineProperty(Scene.prototype, \"totalVerticesPerfCounter\", {\n /**\n * Gets the performance counter for total vertices\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation\n */\n get: function () {\n return this._totalVertices;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)\n * @returns the total number of active indices rendered per frame\n */\n Scene.prototype.getActiveIndices = function () {\n return this._activeIndices.current;\n };\n Object.defineProperty(Scene.prototype, \"totalActiveIndicesPerfCounter\", {\n /**\n * Gets the performance counter for active indices\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation\n */\n get: function () {\n return this._activeIndices;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the total number of active particles rendered per frame\n * @returns the total number of active particles rendered per frame\n */\n Scene.prototype.getActiveParticles = function () {\n return this._activeParticles.current;\n };\n Object.defineProperty(Scene.prototype, \"activeParticlesPerfCounter\", {\n /**\n * Gets the performance counter for active particles\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation\n */\n get: function () {\n return this._activeParticles;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the total number of active bones rendered per frame\n * @returns the total number of active bones rendered per frame\n */\n Scene.prototype.getActiveBones = function () {\n return this._activeBones.current;\n };\n Object.defineProperty(Scene.prototype, \"activeBonesPerfCounter\", {\n /**\n * Gets the performance counter for active bones\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation\n */\n get: function () {\n return this._activeBones;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Scene.prototype.getInterFramePerfCounter = function () {\n BABYLON.Tools.Warn(\"getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n Object.defineProperty(Scene.prototype, \"interFramePerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"interFramePerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Scene.prototype.getLastFrameDuration = function () {\n BABYLON.Tools.Warn(\"getLastFrameDuration is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n Object.defineProperty(Scene.prototype, \"lastFramePerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"lastFramePerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Scene.prototype.getEvaluateActiveMeshesDuration = function () {\n BABYLON.Tools.Warn(\"getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n Object.defineProperty(Scene.prototype, \"evaluateActiveMeshesDurationPerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the array of active meshes\n * @returns an array of AbstractMesh\n */\n Scene.prototype.getActiveMeshes = function () {\n return this._activeMeshes;\n };\n /** @hidden */\n Scene.prototype.getRenderTargetsDuration = function () {\n BABYLON.Tools.Warn(\"getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n /** @hidden */\n Scene.prototype.getRenderDuration = function () {\n BABYLON.Tools.Warn(\"getRenderDuration is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n Object.defineProperty(Scene.prototype, \"renderDurationPerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Scene.prototype.getParticlesDuration = function () {\n BABYLON.Tools.Warn(\"getParticlesDuration is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n Object.defineProperty(Scene.prototype, \"particlesDurationPerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Scene.prototype.getSpritesDuration = function () {\n BABYLON.Tools.Warn(\"getSpritesDuration is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n Object.defineProperty(Scene.prototype, \"spriteDuractionPerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)\n * @returns a number\n */\n Scene.prototype.getAnimationRatio = function () {\n return this._animationRatio !== undefined ? this._animationRatio : 1;\n };\n /**\n * Gets an unique Id for the current frame\n * @returns a number\n */\n Scene.prototype.getRenderId = function () {\n return this._renderId;\n };\n /** Call this function if you want to manually increment the render Id*/\n Scene.prototype.incrementRenderId = function () {\n this._renderId++;\n };\n Scene.prototype._updatePointerPosition = function (evt) {\n var canvasRect = this._engine.getRenderingCanvasClientRect();\n if (!canvasRect) {\n return;\n }\n this._pointerX = evt.clientX - canvasRect.left;\n this._pointerY = evt.clientY - canvasRect.top;\n this._unTranslatedPointerX = this._pointerX;\n this._unTranslatedPointerY = this._pointerY;\n };\n Scene.prototype._createUbo = function () {\n this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);\n this._sceneUbo.addUniform(\"viewProjection\", 16);\n this._sceneUbo.addUniform(\"view\", 16);\n };\n Scene.prototype._createAlternateUbo = function () {\n this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);\n this._alternateSceneUbo.addUniform(\"viewProjection\", 16);\n this._alternateSceneUbo.addUniform(\"view\", 16);\n };\n // Pointers handling\n Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {\n var result = this.pickSprite(x, y, predicate, fastCheck, camera);\n if (result) {\n result.ray = originalPointerInfo ? originalPointerInfo.ray : null;\n }\n return result;\n };\n Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {\n if (pointerInfo.pickInfo) {\n if (!pointerInfo.pickInfo.ray) {\n pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);\n }\n }\n };\n /**\n * Use this method to simulate a pointer move on a mesh\n * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay\n * @param pickResult pickingInfo of the object wished to simulate pointer event on\n * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)\n * @returns the current scene\n */\n Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {\n var evt = new PointerEvent(\"pointermove\", pointerEventInit);\n if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {\n return this;\n }\n return this._processPointerMove(pickResult, evt);\n };\n Scene.prototype._processPointerMove = function (pickResult, evt) {\n var canvas = this._engine.getRenderingCanvas();\n if (!canvas) {\n return this;\n }\n if (pickResult && pickResult.hit && pickResult.pickedMesh) {\n this.setPointerOverSprite(null);\n this.setPointerOverMesh(pickResult.pickedMesh);\n if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {\n if (this._pointerOverMesh.actionManager.hoverCursor) {\n canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;\n }\n else {\n canvas.style.cursor = this.hoverCursor;\n }\n }\n else {\n canvas.style.cursor = this.defaultCursor;\n }\n }\n else {\n this.setPointerOverMesh(null);\n // Sprites\n pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);\n if (pickResult && pickResult.hit && pickResult.pickedSprite) {\n this.setPointerOverSprite(pickResult.pickedSprite);\n if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {\n canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;\n }\n else {\n canvas.style.cursor = this.hoverCursor;\n }\n }\n else {\n this.setPointerOverSprite(null);\n // Restore pointer\n canvas.style.cursor = this.defaultCursor;\n }\n }\n if (pickResult) {\n var type = evt.type === \"mousewheel\" || evt.type === \"DOMMouseScroll\" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;\n if (this.onPointerMove) {\n this.onPointerMove(evt, pickResult, type);\n }\n if (this.onPointerObservable.hasObservers()) {\n var pi = new BABYLON.PointerInfo(type, evt, pickResult);\n this._setRayOnPointerInfo(pi);\n this.onPointerObservable.notifyObservers(pi, type);\n }\n }\n return this;\n };\n Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {\n var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);\n if (pickResult) {\n pi.ray = pickResult.ray;\n }\n this.onPrePointerObservable.notifyObservers(pi, type);\n if (pi.skipOnPointerObservable) {\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Use this method to simulate a pointer down on a mesh\n * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay\n * @param pickResult pickingInfo of the object wished to simulate pointer event on\n * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)\n * @returns the current scene\n */\n Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {\n var evt = new PointerEvent(\"pointerdown\", pointerEventInit);\n if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {\n return this;\n }\n return this._processPointerDown(pickResult, evt);\n };\n Scene.prototype._processPointerDown = function (pickResult, evt) {\n var _this = this;\n if (pickResult && pickResult.hit && pickResult.pickedMesh) {\n this._pickedDownMesh = pickResult.pickedMesh;\n var actionManager = pickResult.pickedMesh.actionManager;\n if (actionManager) {\n if (actionManager.hasPickTriggers) {\n actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n switch (evt.button) {\n case 0:\n actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n break;\n case 1:\n actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n break;\n case 2:\n actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n break;\n }\n }\n if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {\n window.setTimeout(function () {\n var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, _this.cameraToUseForPointers);\n if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {\n if (_this._totalPointersPressed !== 0 &&\n ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&\n (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&\n Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {\n _this._startingPointerTime = 0;\n actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n }\n }\n }, Scene.LongPressDelay);\n }\n }\n }\n if (pickResult) {\n var type = BABYLON.PointerEventTypes.POINTERDOWN;\n if (this.onPointerDown) {\n this.onPointerDown(evt, pickResult, type);\n }\n if (this.onPointerObservable.hasObservers()) {\n var pi = new BABYLON.PointerInfo(type, evt, pickResult);\n this._setRayOnPointerInfo(pi);\n this.onPointerObservable.notifyObservers(pi, type);\n }\n }\n return this;\n };\n /**\n * Use this method to simulate a pointer up on a mesh\n * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay\n * @param pickResult pickingInfo of the object wished to simulate pointer event on\n * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)\n * @returns the current scene\n */\n Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {\n var evt = new PointerEvent(\"pointerup\", pointerEventInit);\n var clickInfo = new ClickInfo();\n clickInfo.singleClick = true;\n clickInfo.ignore = true;\n if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {\n return this;\n }\n return this._processPointerUp(pickResult, evt, clickInfo);\n };\n Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {\n if (pickResult && pickResult && pickResult.pickedMesh) {\n this._pickedUpMesh = pickResult.pickedMesh;\n if (this._pickedDownMesh === this._pickedUpMesh) {\n if (this.onPointerPick) {\n this.onPointerPick(evt, pickResult);\n }\n if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {\n var type_1 = BABYLON.PointerEventTypes.POINTERPICK;\n var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);\n this._setRayOnPointerInfo(pi);\n this.onPointerObservable.notifyObservers(pi, type_1);\n }\n }\n if (pickResult.pickedMesh.actionManager) {\n if (clickInfo.ignore) {\n pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n }\n if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {\n pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n }\n if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {\n pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n }\n }\n }\n if (this._pickedDownMesh &&\n this._pickedDownMesh.actionManager &&\n this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&\n this._pickedDownMesh !== this._pickedUpMesh) {\n this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));\n }\n var type = BABYLON.PointerEventTypes.POINTERUP;\n if (this.onPointerObservable.hasObservers()) {\n if (!clickInfo.ignore) {\n if (!clickInfo.hasSwiped) {\n if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {\n var type_2 = BABYLON.PointerEventTypes.POINTERTAP;\n var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);\n this._setRayOnPointerInfo(pi);\n this.onPointerObservable.notifyObservers(pi, type_2);\n }\n if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {\n var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;\n var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);\n this._setRayOnPointerInfo(pi);\n this.onPointerObservable.notifyObservers(pi, type_3);\n }\n }\n }\n else {\n var pi = new BABYLON.PointerInfo(type, evt, pickResult);\n this._setRayOnPointerInfo(pi);\n this.onPointerObservable.notifyObservers(pi, type);\n }\n }\n if (this.onPointerUp) {\n this.onPointerUp(evt, pickResult, type);\n }\n return this;\n };\n /**\n * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)\n * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)\n * @returns true if the pointer was captured\n */\n Scene.prototype.isPointerCaptured = function (pointerId) {\n if (pointerId === void 0) { pointerId = 0; }\n return this._pointerCaptures[pointerId];\n };\n /**\n * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp\n * @param attachUp defines if you want to attach events to pointerup\n * @param attachDown defines if you want to attach events to pointerdown\n * @param attachMove defines if you want to attach events to pointermove\n */\n Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {\n var _this = this;\n if (attachUp === void 0) { attachUp = true; }\n if (attachDown === void 0) { attachDown = true; }\n if (attachMove === void 0) { attachMove = true; }\n this._initActionManager = function (act, clickInfo) {\n if (!_this._meshPickProceed) {\n var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);\n _this._currentPickResult = pickResult;\n if (pickResult) {\n act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;\n }\n _this._meshPickProceed = true;\n }\n return act;\n };\n this._delayedSimpleClick = function (btn, clickInfo, cb) {\n // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different\n if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||\n btn !== _this._previousButtonPressed) {\n _this._doubleClickOccured = false;\n clickInfo.singleClick = true;\n clickInfo.ignore = false;\n cb(clickInfo, _this._currentPickResult);\n }\n };\n this._initClickEvent = function (obs1, obs2, evt, cb) {\n var clickInfo = new ClickInfo();\n _this._currentPickResult = null;\n var act = null;\n var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)\n || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)\n || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);\n if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {\n act = _this._initActionManager(act, clickInfo);\n if (act)\n checkPicking = act.hasPickTriggers;\n }\n if (checkPicking) {\n var btn = evt.button;\n clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||\n Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;\n if (!clickInfo.hasSwiped) {\n var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;\n if (!checkSingleClickImmediately) {\n checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&\n !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);\n if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {\n act = _this._initActionManager(act, clickInfo);\n if (act)\n checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);\n }\n }\n if (checkSingleClickImmediately) {\n // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required\n if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||\n btn !== _this._previousButtonPressed) {\n clickInfo.singleClick = true;\n cb(clickInfo, _this._currentPickResult);\n }\n }\n // at least one double click is required to be check and exclusive double click is enabled\n else {\n // wait that no double click has been raised during the double click delay\n _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;\n _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);\n }\n var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||\n obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);\n if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {\n act = _this._initActionManager(act, clickInfo);\n if (act)\n checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);\n }\n if (checkDoubleClick) {\n // two successive keys pressed are equal, double click delay is not over and double click has not just occurred\n if (btn === _this._previousButtonPressed &&\n Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&\n !_this._doubleClickOccured) {\n // pointer has not moved for 2 clicks, it's a double click\n if (!clickInfo.hasSwiped &&\n Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&\n Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {\n _this._previousStartingPointerTime = 0;\n _this._doubleClickOccured = true;\n clickInfo.doubleClick = true;\n clickInfo.ignore = false;\n if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {\n clearTimeout(_this._previousDelayedSimpleClickTimeout);\n }\n _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;\n cb(clickInfo, _this._currentPickResult);\n }\n // if the two successive clicks are too far, it's just two simple clicks\n else {\n _this._doubleClickOccured = false;\n _this._previousStartingPointerTime = _this._startingPointerTime;\n _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;\n _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;\n _this._previousButtonPressed = btn;\n if (Scene.ExclusiveDoubleClickMode) {\n if (_this._previousDelayedSimpleClickTimeout) {\n clearTimeout(_this._previousDelayedSimpleClickTimeout);\n }\n _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;\n cb(clickInfo, _this._previousPickResult);\n }\n else {\n cb(clickInfo, _this._currentPickResult);\n }\n }\n }\n // just the first click of the double has been raised\n else {\n _this._doubleClickOccured = false;\n _this._previousStartingPointerTime = _this._startingPointerTime;\n _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;\n _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;\n _this._previousButtonPressed = btn;\n }\n }\n }\n }\n clickInfo.ignore = true;\n cb(clickInfo, _this._currentPickResult);\n };\n this._spritePredicate = function (sprite) {\n return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;\n };\n this._onPointerMove = function (evt) {\n _this._updatePointerPosition(evt);\n // PreObservable support\n if (_this._checkPrePointerObservable(null, evt, evt.type === \"mousewheel\" || evt.type === \"DOMMouseScroll\" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {\n return;\n }\n if (!_this.cameraToUseForPointers && !_this.activeCamera) {\n return;\n }\n if (!_this.pointerMovePredicate) {\n _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };\n }\n // Meshes\n var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);\n _this._processPointerMove(pickResult, evt);\n };\n this._onPointerDown = function (evt) {\n _this._totalPointersPressed++;\n _this._pickedDownMesh = null;\n _this._meshPickProceed = false;\n _this._updatePointerPosition(evt);\n if (_this.preventDefaultOnPointerDown && canvas) {\n evt.preventDefault();\n canvas.focus();\n }\n // PreObservable support\n if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {\n return;\n }\n if (!_this.cameraToUseForPointers && !_this.activeCamera) {\n return;\n }\n _this._pointerCaptures[evt.pointerId] = true;\n _this._startingPointerPosition.x = _this._pointerX;\n _this._startingPointerPosition.y = _this._pointerY;\n _this._startingPointerTime = Date.now();\n if (!_this.pointerDownPredicate) {\n _this.pointerDownPredicate = function (mesh) {\n return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();\n };\n }\n // Meshes\n _this._pickedDownMesh = null;\n var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);\n _this._processPointerDown(pickResult, evt);\n // Sprites\n _this._pickedDownSprite = null;\n if (_this.spriteManagers.length > 0) {\n pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);\n if (pickResult && pickResult.hit && pickResult.pickedSprite) {\n if (pickResult.pickedSprite.actionManager) {\n _this._pickedDownSprite = pickResult.pickedSprite;\n switch (evt.button) {\n case 0:\n pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));\n break;\n case 1:\n pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));\n break;\n case 2:\n pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));\n break;\n }\n if (pickResult.pickedSprite.actionManager) {\n pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));\n }\n }\n }\n }\n };\n this._onPointerUp = function (evt) {\n if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF \n return; // So we need to test it the pointer down was pressed before.\n }\n _this._totalPointersPressed--;\n _this._pickedUpMesh = null;\n _this._meshPickProceed = false;\n _this._updatePointerPosition(evt);\n _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {\n // PreObservable support\n if (_this.onPrePointerObservable.hasObservers()) {\n if (!clickInfo.ignore) {\n if (!clickInfo.hasSwiped) {\n if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {\n if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {\n return;\n }\n }\n if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {\n if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {\n return;\n }\n }\n }\n }\n else {\n if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {\n return;\n }\n }\n }\n if (!_this.cameraToUseForPointers && !_this.activeCamera) {\n return;\n }\n _this._pointerCaptures[evt.pointerId] = false;\n if (!_this.pointerUpPredicate) {\n _this.pointerUpPredicate = function (mesh) {\n return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();\n };\n }\n // Meshes\n if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {\n _this._initActionManager(null, clickInfo);\n }\n if (!pickResult) {\n pickResult = _this._currentPickResult;\n }\n _this._processPointerUp(pickResult, evt, clickInfo);\n // Sprites\n if (!clickInfo.ignore) {\n if (_this.spriteManagers.length > 0) {\n var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);\n if (spritePickResult) {\n if (spritePickResult.hit && spritePickResult.pickedSprite) {\n if (spritePickResult.pickedSprite.actionManager) {\n spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));\n if (spritePickResult.pickedSprite.actionManager) {\n if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {\n spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));\n }\n }\n }\n }\n if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {\n _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));\n }\n }\n }\n }\n _this._previousPickResult = _this._currentPickResult;\n });\n };\n this._onKeyDown = function (evt) {\n var type = BABYLON.KeyboardEventTypes.KEYDOWN;\n if (_this.onPreKeyboardObservable.hasObservers()) {\n var pi = new BABYLON.KeyboardInfoPre(type, evt);\n _this.onPreKeyboardObservable.notifyObservers(pi, type);\n if (pi.skipOnPointerObservable) {\n return;\n }\n }\n if (_this.onKeyboardObservable.hasObservers()) {\n var pi = new BABYLON.KeyboardInfo(type, evt);\n _this.onKeyboardObservable.notifyObservers(pi, type);\n }\n if (_this.actionManager) {\n _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));\n }\n };\n this._onKeyUp = function (evt) {\n var type = BABYLON.KeyboardEventTypes.KEYUP;\n if (_this.onPreKeyboardObservable.hasObservers()) {\n var pi = new BABYLON.KeyboardInfoPre(type, evt);\n _this.onPreKeyboardObservable.notifyObservers(pi, type);\n if (pi.skipOnPointerObservable) {\n return;\n }\n }\n if (_this.onKeyboardObservable.hasObservers()) {\n var pi = new BABYLON.KeyboardInfo(type, evt);\n _this.onKeyboardObservable.notifyObservers(pi, type);\n }\n if (_this.actionManager) {\n _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));\n }\n };\n var engine = this.getEngine();\n this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {\n if (!canvas) {\n return;\n }\n canvas.addEventListener(\"keydown\", _this._onKeyDown, false);\n canvas.addEventListener(\"keyup\", _this._onKeyUp, false);\n });\n this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {\n if (!canvas) {\n return;\n }\n canvas.removeEventListener(\"keydown\", _this._onKeyDown);\n canvas.removeEventListener(\"keyup\", _this._onKeyUp);\n });\n var eventPrefix = BABYLON.Tools.GetPointerPrefix();\n var canvas = this._engine.getRenderingCanvas();\n if (!canvas) {\n return;\n }\n if (attachMove) {\n canvas.addEventListener(eventPrefix + \"move\", this._onPointerMove, false);\n // Wheel\n canvas.addEventListener('mousewheel', this._onPointerMove, false);\n canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);\n }\n if (attachDown) {\n canvas.addEventListener(eventPrefix + \"down\", this._onPointerDown, false);\n }\n if (attachUp) {\n window.addEventListener(eventPrefix + \"up\", this._onPointerUp, false);\n }\n canvas.tabIndex = 1;\n };\n /** Detaches all event handlers*/\n Scene.prototype.detachControl = function () {\n var engine = this.getEngine();\n var eventPrefix = BABYLON.Tools.GetPointerPrefix();\n var canvas = engine.getRenderingCanvas();\n if (!canvas) {\n return;\n }\n canvas.removeEventListener(eventPrefix + \"move\", this._onPointerMove);\n canvas.removeEventListener(eventPrefix + \"down\", this._onPointerDown);\n window.removeEventListener(eventPrefix + \"up\", this._onPointerUp);\n if (this._onCanvasBlurObserver) {\n engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n if (this._onCanvasFocusObserver) {\n engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);\n }\n // Wheel\n canvas.removeEventListener('mousewheel', this._onPointerMove);\n canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);\n // Keyboard\n canvas.removeEventListener(\"keydown\", this._onKeyDown);\n canvas.removeEventListener(\"keyup\", this._onKeyUp);\n // Observables\n this.onKeyboardObservable.clear();\n this.onPreKeyboardObservable.clear();\n this.onPointerObservable.clear();\n this.onPrePointerObservable.clear();\n };\n /**\n * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)\n * Delay loaded resources are not taking in account\n * @return true if all required resources are ready\n */\n Scene.prototype.isReady = function () {\n if (this._isDisposed) {\n return false;\n }\n if (this._pendingData.length > 0) {\n return false;\n }\n var index;\n var engine = this.getEngine();\n // Geometries\n for (index = 0; index < this.geometries.length; index++) {\n var geometry = this.geometries[index];\n if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {\n return false;\n }\n }\n // Meshes\n for (index = 0; index < this.meshes.length; index++) {\n var mesh = this.meshes[index];\n if (!mesh.isEnabled()) {\n continue;\n }\n if (!mesh.subMeshes || mesh.subMeshes.length === 0) {\n continue;\n }\n if (!mesh.isReady(true)) {\n return false;\n }\n var hardwareInstancedRendering = mesh.getClassName() === \"InstancedMesh\" || engine.getCaps().instancedArrays && mesh.instances.length > 0;\n // Is Ready For Mesh\n for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {\n var step = _a[_i];\n if (!step.action(mesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n // Post-processes\n if (this.activeCameras && this.activeCameras.length > 0) {\n for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {\n var camera = _c[_b];\n if (!camera.isReady(true)) {\n return false;\n }\n }\n }\n else if (this.activeCamera) {\n if (!this.activeCamera.isReady(true)) {\n return false;\n }\n }\n // Particles\n for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {\n var particleSystem = _e[_d];\n if (!particleSystem.isReady()) {\n return false;\n }\n }\n return true;\n };\n /** Resets all cached information relative to material (including effect and visibility) */\n Scene.prototype.resetCachedMaterial = function () {\n this._cachedMaterial = null;\n this._cachedEffect = null;\n this._cachedVisibility = null;\n };\n /**\n * Registers a function to be called before every frame render\n * @param func defines the function to register\n */\n Scene.prototype.registerBeforeRender = function (func) {\n this.onBeforeRenderObservable.add(func);\n };\n /**\n * Unregisters a function called before every frame render\n * @param func defines the function to unregister\n */\n Scene.prototype.unregisterBeforeRender = function (func) {\n this.onBeforeRenderObservable.removeCallback(func);\n };\n /**\n * Registers a function to be called after every frame render\n * @param func defines the function to register\n */\n Scene.prototype.registerAfterRender = function (func) {\n this.onAfterRenderObservable.add(func);\n };\n /**\n * Unregisters a function called after every frame render\n * @param func defines the function to unregister\n */\n Scene.prototype.unregisterAfterRender = function (func) {\n this.onAfterRenderObservable.removeCallback(func);\n };\n Scene.prototype._executeOnceBeforeRender = function (func) {\n var _this = this;\n var execFunc = function () {\n func();\n setTimeout(function () {\n _this.unregisterBeforeRender(execFunc);\n });\n };\n this.registerBeforeRender(execFunc);\n };\n /**\n * The provided function will run before render once and will be disposed afterwards.\n * A timeout delay can be provided so that the function will be executed in N ms.\n * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.\n * @param func The function to be executed.\n * @param timeout optional delay in ms\n */\n Scene.prototype.executeOnceBeforeRender = function (func, timeout) {\n var _this = this;\n if (timeout !== undefined) {\n setTimeout(function () {\n _this._executeOnceBeforeRender(func);\n }, timeout);\n }\n else {\n this._executeOnceBeforeRender(func);\n }\n };\n /** @hidden */\n Scene.prototype._addPendingData = function (data) {\n this._pendingData.push(data);\n };\n /** @hidden */\n Scene.prototype._removePendingData = function (data) {\n var wasLoading = this.isLoading;\n var index = this._pendingData.indexOf(data);\n if (index !== -1) {\n this._pendingData.splice(index, 1);\n }\n if (wasLoading && !this.isLoading) {\n this.onDataLoadedObservable.notifyObservers(this);\n }\n };\n /**\n * Returns the number of items waiting to be loaded\n * @returns the number of items waiting to be loaded\n */\n Scene.prototype.getWaitingItemsCount = function () {\n return this._pendingData.length;\n };\n Object.defineProperty(Scene.prototype, \"isLoading\", {\n /**\n * Returns a boolean indicating if the scene is still loading data\n */\n get: function () {\n return this._pendingData.length > 0;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Registers a function to be executed when the scene is ready\n * @param {Function} func - the function to be executed\n */\n Scene.prototype.executeWhenReady = function (func) {\n var _this = this;\n this.onReadyObservable.add(func);\n if (this._executeWhenReadyTimeoutId !== -1) {\n return;\n }\n this._executeWhenReadyTimeoutId = setTimeout(function () {\n _this._checkIsReady();\n }, 150);\n };\n /**\n * Returns a promise that resolves when the scene is ready\n * @returns A promise that resolves when the scene is ready\n */\n Scene.prototype.whenReadyAsync = function () {\n var _this = this;\n return new Promise(function (resolve) {\n _this.executeWhenReady(function () {\n resolve();\n });\n });\n };\n /** @hidden */\n Scene.prototype._checkIsReady = function () {\n var _this = this;\n this._registerTransientComponents();\n if (this.isReady()) {\n this.onReadyObservable.notifyObservers(this);\n this.onReadyObservable.clear();\n this._executeWhenReadyTimeoutId = -1;\n return;\n }\n this._executeWhenReadyTimeoutId = setTimeout(function () {\n _this._checkIsReady();\n }, 150);\n };\n // Animations\n /**\n * Will start the animation sequence of a given target\n * @param target defines the target\n * @param from defines from which frame should animation start\n * @param to defines until which frame should animation run.\n * @param weight defines the weight to apply to the animation (1.0 by default)\n * @param loop defines if the animation loops\n * @param speedRatio defines the speed in which to run the animation (1.0 by default)\n * @param onAnimationEnd defines the function to be executed when the animation ends\n * @param animatable defines an animatable object. If not provided a new one will be created from the given params\n * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)\n * @returns the animatable object created for this animation\n */\n Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {\n if (weight === void 0) { weight = 1.0; }\n if (speedRatio === void 0) { speedRatio = 1.0; }\n var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);\n returnedAnimatable.weight = weight;\n return returnedAnimatable;\n };\n /**\n * Will start the animation sequence of a given target\n * @param target defines the target\n * @param from defines from which frame should animation start\n * @param to defines until which frame should animation run.\n * @param loop defines if the animation loops\n * @param speedRatio defines the speed in which to run the animation (1.0 by default)\n * @param onAnimationEnd defines the function to be executed when the animation ends\n * @param animatable defines an animatable object. If not provided a new one will be created from the given params\n * @param stopCurrent defines if the current animations must be stopped first (true by default)\n * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)\n * @returns the animatable object created for this animation\n */\n Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {\n if (speedRatio === void 0) { speedRatio = 1.0; }\n if (stopCurrent === void 0) { stopCurrent = true; }\n if (from > to && speedRatio > 0) {\n speedRatio *= -1;\n }\n if (stopCurrent) {\n this.stopAnimation(target, undefined, targetMask);\n }\n if (!animatable) {\n animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);\n }\n var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;\n // Local animations\n if (target.animations && shouldRunTargetAnimations) {\n animatable.appendAnimations(target, target.animations);\n }\n // Children animations\n if (target.getAnimatables) {\n var animatables = target.getAnimatables();\n for (var index = 0; index < animatables.length; index++) {\n this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);\n }\n }\n animatable.reset();\n return animatable;\n };\n /**\n * Begin a new animation on a given node\n * @param target defines the target where the animation will take place\n * @param animations defines the list of animations to start\n * @param from defines the initial value\n * @param to defines the final value\n * @param loop defines if you want animation to loop (off by default)\n * @param speedRatio defines the speed ratio to apply to all animations\n * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)\n * @returns the list of created animatables\n */\n Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {\n if (speedRatio === undefined) {\n speedRatio = 1.0;\n }\n var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);\n return animatable;\n };\n /**\n * Begin a new animation on a given node and its hierarchy\n * @param target defines the root node where the animation will take place\n * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.\n * @param animations defines the list of animations to start\n * @param from defines the initial value\n * @param to defines the final value\n * @param loop defines if you want animation to loop (off by default)\n * @param speedRatio defines the speed ratio to apply to all animations\n * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)\n * @returns the list of animatables created for all nodes\n */\n Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {\n var children = target.getDescendants(directDescendantsOnly);\n var result = [];\n result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));\n for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {\n var child = children_1[_i];\n result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));\n }\n return result;\n };\n /**\n * Gets the animatable associated with a specific target\n * @param target defines the target of the animatable\n * @returns the required animatable if found\n */\n Scene.prototype.getAnimatableByTarget = function (target) {\n for (var index = 0; index < this._activeAnimatables.length; index++) {\n if (this._activeAnimatables[index].target === target) {\n return this._activeAnimatables[index];\n }\n }\n return null;\n };\n /**\n * Gets all animatables associated with a given target\n * @param target defines the target to look animatables for\n * @returns an array of Animatables\n */\n Scene.prototype.getAllAnimatablesByTarget = function (target) {\n var result = [];\n for (var index = 0; index < this._activeAnimatables.length; index++) {\n if (this._activeAnimatables[index].target === target) {\n result.push(this._activeAnimatables[index]);\n }\n }\n return result;\n };\n Object.defineProperty(Scene.prototype, \"animatables\", {\n /**\n * Gets all animatable attached to the scene\n */\n get: function () {\n return this._activeAnimatables;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Will stop the animation of the given target\n * @param target - the target\n * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)\n * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)\n */\n Scene.prototype.stopAnimation = function (target, animationName, targetMask) {\n var animatables = this.getAllAnimatablesByTarget(target);\n for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {\n var animatable = animatables_1[_i];\n animatable.stop(animationName, targetMask);\n }\n };\n /**\n * Stops and removes all animations that have been applied to the scene\n */\n Scene.prototype.stopAllAnimations = function () {\n if (this._activeAnimatables) {\n for (var i = 0; i < this._activeAnimatables.length; i++) {\n this._activeAnimatables[i].stop();\n }\n this._activeAnimatables = [];\n }\n for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {\n var group = _a[_i];\n group.stop();\n }\n };\n Scene.prototype._animate = function () {\n if (!this.animationsEnabled || this._activeAnimatables.length === 0) {\n return;\n }\n // Getting time\n var now = BABYLON.Tools.Now;\n if (!this._animationTimeLast) {\n if (this._pendingData.length > 0) {\n return;\n }\n this._animationTimeLast = now;\n }\n var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;\n this._animationTime += deltaTime;\n this._animationTimeLast = now;\n for (var index = 0; index < this._activeAnimatables.length; index++) {\n this._activeAnimatables[index]._animate(this._animationTime);\n }\n // Late animation bindings\n this._processLateAnimationBindings();\n };\n /** @hidden */\n Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {\n var target = runtimeAnimation.target;\n this._registeredForLateAnimationBindings.pushNoDuplicate(target);\n if (!target._lateAnimationHolders) {\n target._lateAnimationHolders = {};\n }\n if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {\n target._lateAnimationHolders[runtimeAnimation.targetPath] = {\n totalWeight: 0,\n animations: [],\n originalValue: originalValue\n };\n }\n target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);\n target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;\n };\n Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {\n var normalizer = 1.0;\n var finalPosition = BABYLON.Tmp.Vector3[0];\n var finalScaling = BABYLON.Tmp.Vector3[1];\n var finalQuaternion = BABYLON.Tmp.Quaternion[0];\n var startIndex = 0;\n var originalAnimation = holder.animations[0];\n var originalValue = holder.originalValue;\n var scale = 1;\n if (holder.totalWeight < 1.0) {\n // We need to mix the original value in \n originalValue.decompose(finalScaling, finalQuaternion, finalPosition);\n scale = 1.0 - holder.totalWeight;\n }\n else {\n startIndex = 1;\n // We need to normalize the weights\n normalizer = holder.totalWeight;\n originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);\n scale = originalAnimation.weight / normalizer;\n if (scale == 1) {\n return originalAnimation.currentValue;\n }\n }\n finalScaling.scaleInPlace(scale);\n finalPosition.scaleInPlace(scale);\n finalQuaternion.scaleInPlace(scale);\n for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {\n var runtimeAnimation = holder.animations[animIndex];\n var scale = runtimeAnimation.weight / normalizer;\n var currentPosition = BABYLON.Tmp.Vector3[2];\n var currentScaling = BABYLON.Tmp.Vector3[3];\n var currentQuaternion = BABYLON.Tmp.Quaternion[1];\n runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);\n currentScaling.scaleAndAddToRef(scale, finalScaling);\n currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);\n currentPosition.scaleAndAddToRef(scale, finalPosition);\n }\n BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);\n return originalAnimation._workValue;\n };\n Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {\n var originalAnimation = holder.animations[0];\n var originalValue = holder.originalValue;\n if (holder.animations.length === 1) {\n return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));\n }\n var normalizer = 1.0;\n var quaternions;\n var weights;\n if (holder.totalWeight < 1.0) {\n var scale = 1.0 - holder.totalWeight;\n quaternions = [];\n weights = [];\n quaternions.push(originalValue);\n weights.push(scale);\n }\n else {\n if (holder.animations.length === 2) { // Slerp as soon as we can\n return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);\n }\n quaternions = [];\n weights = [];\n normalizer = holder.totalWeight;\n }\n for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {\n var runtimeAnimation = holder.animations[animIndex];\n quaternions.push(runtimeAnimation.currentValue);\n weights.push(runtimeAnimation.weight / normalizer);\n }\n // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions\n var cumulativeAmount = 0;\n var cumulativeQuaternion = null;\n for (var index = 0; index < quaternions.length;) {\n if (!cumulativeQuaternion) {\n cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));\n cumulativeAmount = weights[index] + weights[index + 1];\n index += 2;\n continue;\n }\n cumulativeAmount += weights[index];\n BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);\n index++;\n }\n return cumulativeQuaternion;\n };\n Scene.prototype._processLateAnimationBindings = function () {\n if (!this._registeredForLateAnimationBindings.length) {\n return;\n }\n for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {\n var target = this._registeredForLateAnimationBindings.data[index];\n for (var path in target._lateAnimationHolders) {\n var holder = target._lateAnimationHolders[path];\n var originalAnimation = holder.animations[0];\n var originalValue = holder.originalValue;\n var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix\n var finalValue = void 0;\n if (matrixDecomposeMode) {\n finalValue = this._processLateAnimationBindingsForMatrices(holder);\n }\n else {\n var quaternionMode = originalValue.w !== undefined;\n if (quaternionMode) {\n finalValue = this._processLateAnimationBindingsForQuaternions(holder);\n }\n else {\n var startIndex = 0;\n var normalizer = 1.0;\n if (holder.totalWeight < 1.0) {\n // We need to mix the original value in \n if (originalValue.scale) {\n finalValue = originalValue.scale(1.0 - holder.totalWeight);\n }\n else {\n finalValue = originalValue * (1.0 - holder.totalWeight);\n }\n }\n else {\n // We need to normalize the weights\n normalizer = holder.totalWeight;\n var scale_1 = originalAnimation.weight / normalizer;\n if (scale_1 !== 1) {\n if (originalAnimation.currentValue.scale) {\n finalValue = originalAnimation.currentValue.scale(scale_1);\n }\n else {\n finalValue = originalAnimation.currentValue * scale_1;\n }\n }\n else {\n finalValue = originalAnimation.currentValue;\n }\n startIndex = 1;\n }\n for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {\n var runtimeAnimation = holder.animations[animIndex];\n var scale = runtimeAnimation.weight / normalizer;\n if (runtimeAnimation.currentValue.scaleAndAddToRef) {\n runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);\n }\n else {\n finalValue += runtimeAnimation.currentValue * scale;\n }\n }\n }\n }\n target[path] = finalValue;\n }\n target._lateAnimationHolders = {};\n }\n this._registeredForLateAnimationBindings.reset();\n };\n // Matrix\n /** @hidden */\n Scene.prototype._switchToAlternateCameraConfiguration = function (active) {\n this._useAlternateCameraConfiguration = active;\n };\n /**\n * Gets the current view matrix\n * @returns a Matrix\n */\n Scene.prototype.getViewMatrix = function () {\n return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;\n };\n /**\n * Gets the current projection matrix\n * @returns a Matrix\n */\n Scene.prototype.getProjectionMatrix = function () {\n return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;\n };\n /**\n * Gets the current transform matrix\n * @returns a Matrix made of View * Projection\n */\n Scene.prototype.getTransformMatrix = function () {\n return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;\n };\n /**\n * Sets the current transform matrix\n * @param view defines the View matrix to use\n * @param projection defines the Projection matrix to use\n */\n Scene.prototype.setTransformMatrix = function (view, projection) {\n if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {\n return;\n }\n this._viewUpdateFlag = view.updateFlag;\n this._projectionUpdateFlag = projection.updateFlag;\n this._viewMatrix = view;\n this._projectionMatrix = projection;\n this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);\n // Update frustum\n if (!this._frustumPlanes) {\n this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);\n }\n else {\n BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);\n }\n if (this.activeCamera && this.activeCamera._alternateCamera) {\n var otherCamera = this.activeCamera._alternateCamera;\n otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);\n BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane\n }\n if (this._sceneUbo.useUbo) {\n this._sceneUbo.updateMatrix(\"viewProjection\", this._transformMatrix);\n this._sceneUbo.updateMatrix(\"view\", this._viewMatrix);\n this._sceneUbo.update();\n }\n };\n /** @hidden */\n Scene.prototype._setAlternateTransformMatrix = function (view, projection) {\n if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {\n return;\n }\n this._alternateViewUpdateFlag = view.updateFlag;\n this._alternateProjectionUpdateFlag = projection.updateFlag;\n this._alternateViewMatrix = view;\n this._alternateProjectionMatrix = projection;\n if (!this._alternateTransformMatrix) {\n this._alternateTransformMatrix = BABYLON.Matrix.Zero();\n }\n this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);\n if (!this._alternateSceneUbo) {\n this._createAlternateUbo();\n }\n if (this._alternateSceneUbo.useUbo) {\n this._alternateSceneUbo.updateMatrix(\"viewProjection\", this._alternateTransformMatrix);\n this._alternateSceneUbo.updateMatrix(\"view\", this._alternateViewMatrix);\n this._alternateSceneUbo.update();\n }\n };\n /**\n * Gets the uniform buffer used to store scene data\n * @returns a UniformBuffer\n */\n Scene.prototype.getSceneUniformBuffer = function () {\n return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;\n };\n /**\n * Gets an unique (relatively to the current scene) Id\n * @returns an unique number for the scene\n */\n Scene.prototype.getUniqueId = function () {\n var result = Scene._uniqueIdCounter;\n Scene._uniqueIdCounter++;\n return result;\n };\n /**\n * Add a mesh to the list of scene's meshes\n * @param newMesh defines the mesh to add\n * @param recursive if all child meshes should also be added to the scene\n */\n Scene.prototype.addMesh = function (newMesh, recursive) {\n var _this = this;\n if (recursive === void 0) { recursive = false; }\n this.meshes.push(newMesh);\n //notify the collision coordinator\n if (this.collisionCoordinator) {\n this.collisionCoordinator.onMeshAdded(newMesh);\n }\n newMesh._resyncLightSources();\n this.onNewMeshAddedObservable.notifyObservers(newMesh);\n if (recursive) {\n newMesh.getChildMeshes().forEach(function (m) {\n _this.addMesh(m);\n });\n }\n };\n /**\n * Remove a mesh for the list of scene's meshes\n * @param toRemove defines the mesh to remove\n * @param recursive if all child meshes should also be removed from the scene\n * @returns the index where the mesh was in the mesh list\n */\n Scene.prototype.removeMesh = function (toRemove, recursive) {\n var _this = this;\n if (recursive === void 0) { recursive = false; }\n var index = this.meshes.indexOf(toRemove);\n if (index !== -1) {\n // Remove from the scene if mesh found\n this.meshes.splice(index, 1);\n }\n this.onMeshRemovedObservable.notifyObservers(toRemove);\n if (recursive) {\n toRemove.getChildMeshes().forEach(function (m) {\n _this.removeMesh(m);\n });\n }\n return index;\n };\n /**\n * Add a transform node to the list of scene's transform nodes\n * @param newTransformNode defines the transform node to add\n */\n Scene.prototype.addTransformNode = function (newTransformNode) {\n this.transformNodes.push(newTransformNode);\n this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);\n };\n /**\n * Remove a transform node for the list of scene's transform nodes\n * @param toRemove defines the transform node to remove\n * @returns the index where the transform node was in the transform node list\n */\n Scene.prototype.removeTransformNode = function (toRemove) {\n var index = this.transformNodes.indexOf(toRemove);\n if (index !== -1) {\n // Remove from the scene if found\n this.transformNodes.splice(index, 1);\n }\n this.onTransformNodeRemovedObservable.notifyObservers(toRemove);\n return index;\n };\n /**\n * Remove a skeleton for the list of scene's skeletons\n * @param toRemove defines the skeleton to remove\n * @returns the index where the skeleton was in the skeleton list\n */\n Scene.prototype.removeSkeleton = function (toRemove) {\n var index = this.skeletons.indexOf(toRemove);\n if (index !== -1) {\n // Remove from the scene if found\n this.skeletons.splice(index, 1);\n }\n return index;\n };\n /**\n * Remove a morph target for the list of scene's morph targets\n * @param toRemove defines the morph target to remove\n * @returns the index where the morph target was in the morph target list\n */\n Scene.prototype.removeMorphTargetManager = function (toRemove) {\n var index = this.morphTargetManagers.indexOf(toRemove);\n if (index !== -1) {\n // Remove from the scene if found\n this.morphTargetManagers.splice(index, 1);\n }\n return index;\n };\n /**\n * Remove a light for the list of scene's lights\n * @param toRemove defines the light to remove\n * @returns the index where the light was in the light list\n */\n Scene.prototype.removeLight = function (toRemove) {\n var index = this.lights.indexOf(toRemove);\n if (index !== -1) {\n // Remove from meshes\n for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n mesh._removeLightSource(toRemove);\n }\n // Remove from the scene if mesh found\n this.lights.splice(index, 1);\n this.sortLightsByPriority();\n }\n this.onLightRemovedObservable.notifyObservers(toRemove);\n return index;\n };\n /**\n * Remove a camera for the list of scene's cameras\n * @param toRemove defines the camera to remove\n * @returns the index where the camera was in the camera list\n */\n Scene.prototype.removeCamera = function (toRemove) {\n var index = this.cameras.indexOf(toRemove);\n if (index !== -1) {\n // Remove from the scene if mesh found\n this.cameras.splice(index, 1);\n }\n // Remove from activeCameras\n var index2 = this.activeCameras.indexOf(toRemove);\n if (index2 !== -1) {\n // Remove from the scene if mesh found\n this.activeCameras.splice(index2, 1);\n }\n // Reset the activeCamera\n if (this.activeCamera === toRemove) {\n if (this.cameras.length > 0) {\n this.activeCamera = this.cameras[0];\n }\n else {\n this.activeCamera = null;\n }\n }\n this.onCameraRemovedObservable.notifyObservers(toRemove);\n return index;\n };\n /**\n * Remove a particle system for the list of scene's particle systems\n * @param toRemove defines the particle system to remove\n * @returns the index where the particle system was in the particle system list\n */\n Scene.prototype.removeParticleSystem = function (toRemove) {\n var index = this.particleSystems.indexOf(toRemove);\n if (index !== -1) {\n this.particleSystems.splice(index, 1);\n }\n return index;\n };\n /**\n * Remove a animation for the list of scene's animations\n * @param toRemove defines the animation to remove\n * @returns the index where the animation was in the animation list\n */\n Scene.prototype.removeAnimation = function (toRemove) {\n var index = this.animations.indexOf(toRemove);\n if (index !== -1) {\n this.animations.splice(index, 1);\n }\n return index;\n };\n /**\n * Removes the given animation group from this scene.\n * @param toRemove The animation group to remove\n * @returns The index of the removed animation group\n */\n Scene.prototype.removeAnimationGroup = function (toRemove) {\n var index = this.animationGroups.indexOf(toRemove);\n if (index !== -1) {\n this.animationGroups.splice(index, 1);\n }\n return index;\n };\n /**\n * Removes the given multi-material from this scene.\n * @param toRemove The multi-material to remove\n * @returns The index of the removed multi-material\n */\n Scene.prototype.removeMultiMaterial = function (toRemove) {\n var index = this.multiMaterials.indexOf(toRemove);\n if (index !== -1) {\n this.multiMaterials.splice(index, 1);\n }\n return index;\n };\n /**\n * Removes the given material from this scene.\n * @param toRemove The material to remove\n * @returns The index of the removed material\n */\n Scene.prototype.removeMaterial = function (toRemove) {\n var index = this.materials.indexOf(toRemove);\n if (index !== -1) {\n this.materials.splice(index, 1);\n }\n return index;\n };\n /**\n * Removes the given action manager from this scene.\n * @param toRemove The action manager to remove\n * @returns The index of the removed action manager\n */\n Scene.prototype.removeActionManager = function (toRemove) {\n var index = this.actionManagers.indexOf(toRemove);\n if (index !== -1) {\n this.actionManagers.splice(index, 1);\n }\n return index;\n };\n /**\n * Removes the given texture from this scene.\n * @param toRemove The texture to remove\n * @returns The index of the removed texture\n */\n Scene.prototype.removeTexture = function (toRemove) {\n var index = this.textures.indexOf(toRemove);\n if (index !== -1) {\n this.textures.splice(index, 1);\n }\n return index;\n };\n /**\n * Adds the given light to this scene\n * @param newLight The light to add\n */\n Scene.prototype.addLight = function (newLight) {\n this.lights.push(newLight);\n this.sortLightsByPriority();\n // Add light to all meshes (To support if the light is removed and then readded)\n for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n if (mesh._lightSources.indexOf(newLight) === -1) {\n mesh._lightSources.push(newLight);\n mesh._resyncLightSources();\n }\n }\n this.onNewLightAddedObservable.notifyObservers(newLight);\n };\n /**\n * Sorts the list list based on light priorities\n */\n Scene.prototype.sortLightsByPriority = function () {\n if (this.requireLightSorting) {\n this.lights.sort(BABYLON.Light.CompareLightsPriority);\n }\n };\n /**\n * Adds the given camera to this scene\n * @param newCamera The camera to add\n */\n Scene.prototype.addCamera = function (newCamera) {\n this.cameras.push(newCamera);\n this.onNewCameraAddedObservable.notifyObservers(newCamera);\n };\n /**\n * Adds the given skeleton to this scene\n * @param newSkeleton The skeleton to add\n */\n Scene.prototype.addSkeleton = function (newSkeleton) {\n this.skeletons.push(newSkeleton);\n };\n /**\n * Adds the given particle system to this scene\n * @param newParticleSystem The particle system to add\n */\n Scene.prototype.addParticleSystem = function (newParticleSystem) {\n this.particleSystems.push(newParticleSystem);\n };\n /**\n * Adds the given animation to this scene\n * @param newAnimation The animation to add\n */\n Scene.prototype.addAnimation = function (newAnimation) {\n this.animations.push(newAnimation);\n };\n /**\n * Adds the given animation group to this scene.\n * @param newAnimationGroup The animation group to add\n */\n Scene.prototype.addAnimationGroup = function (newAnimationGroup) {\n this.animationGroups.push(newAnimationGroup);\n };\n /**\n * Adds the given multi-material to this scene\n * @param newMultiMaterial The multi-material to add\n */\n Scene.prototype.addMultiMaterial = function (newMultiMaterial) {\n this.multiMaterials.push(newMultiMaterial);\n };\n /**\n * Adds the given material to this scene\n * @param newMaterial The material to add\n */\n Scene.prototype.addMaterial = function (newMaterial) {\n this.materials.push(newMaterial);\n };\n /**\n * Adds the given morph target to this scene\n * @param newMorphTargetManager The morph target to add\n */\n Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {\n this.morphTargetManagers.push(newMorphTargetManager);\n };\n /**\n * Adds the given geometry to this scene\n * @param newGeometry The geometry to add\n */\n Scene.prototype.addGeometry = function (newGeometry) {\n this.geometries.push(newGeometry);\n };\n /**\n * Adds the given action manager to this scene\n * @param newActionManager The action manager to add\n */\n Scene.prototype.addActionManager = function (newActionManager) {\n this.actionManagers.push(newActionManager);\n };\n /**\n * Adds the given texture to this scene.\n * @param newTexture The texture to add\n */\n Scene.prototype.addTexture = function (newTexture) {\n this.textures.push(newTexture);\n };\n /**\n * Switch active camera\n * @param newCamera defines the new active camera\n * @param attachControl defines if attachControl must be called for the new active camera (default: true)\n */\n Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {\n if (attachControl === void 0) { attachControl = true; }\n var canvas = this._engine.getRenderingCanvas();\n if (!canvas) {\n return;\n }\n if (this.activeCamera) {\n this.activeCamera.detachControl(canvas);\n }\n this.activeCamera = newCamera;\n if (attachControl) {\n newCamera.attachControl(canvas);\n }\n };\n /**\n * sets the active camera of the scene using its ID\n * @param id defines the camera's ID\n * @return the new active camera or null if none found.\n */\n Scene.prototype.setActiveCameraByID = function (id) {\n var camera = this.getCameraByID(id);\n if (camera) {\n this.activeCamera = camera;\n return camera;\n }\n return null;\n };\n /**\n * sets the active camera of the scene using its name\n * @param name defines the camera's name\n * @returns the new active camera or null if none found.\n */\n Scene.prototype.setActiveCameraByName = function (name) {\n var camera = this.getCameraByName(name);\n if (camera) {\n this.activeCamera = camera;\n return camera;\n }\n return null;\n };\n /**\n * get an animation group using its name\n * @param name defines the material's name\n * @return the animation group or null if none found.\n */\n Scene.prototype.getAnimationGroupByName = function (name) {\n for (var index = 0; index < this.animationGroups.length; index++) {\n if (this.animationGroups[index].name === name) {\n return this.animationGroups[index];\n }\n }\n return null;\n };\n /**\n * get a material using its id\n * @param id defines the material's ID\n * @return the material or null if none found.\n */\n Scene.prototype.getMaterialByID = function (id) {\n for (var index = 0; index < this.materials.length; index++) {\n if (this.materials[index].id === id) {\n return this.materials[index];\n }\n }\n return null;\n };\n /**\n * Gets a material using its name\n * @param name defines the material's name\n * @return the material or null if none found.\n */\n Scene.prototype.getMaterialByName = function (name) {\n for (var index = 0; index < this.materials.length; index++) {\n if (this.materials[index].name === name) {\n return this.materials[index];\n }\n }\n return null;\n };\n /**\n * Gets a camera using its id\n * @param id defines the id to look for\n * @returns the camera or null if not found\n */\n Scene.prototype.getCameraByID = function (id) {\n for (var index = 0; index < this.cameras.length; index++) {\n if (this.cameras[index].id === id) {\n return this.cameras[index];\n }\n }\n return null;\n };\n /**\n * Gets a camera using its unique id\n * @param uniqueId defines the unique id to look for\n * @returns the camera or null if not found\n */\n Scene.prototype.getCameraByUniqueID = function (uniqueId) {\n for (var index = 0; index < this.cameras.length; index++) {\n if (this.cameras[index].uniqueId === uniqueId) {\n return this.cameras[index];\n }\n }\n return null;\n };\n /**\n * Gets a camera using its name\n * @param name defines the camera's name\n * @return the camera or null if none found.\n */\n Scene.prototype.getCameraByName = function (name) {\n for (var index = 0; index < this.cameras.length; index++) {\n if (this.cameras[index].name === name) {\n return this.cameras[index];\n }\n }\n return null;\n };\n /**\n * Gets a bone using its id\n * @param id defines the bone's id\n * @return the bone or null if not found\n */\n Scene.prototype.getBoneByID = function (id) {\n for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {\n var skeleton = this.skeletons[skeletonIndex];\n for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {\n if (skeleton.bones[boneIndex].id === id) {\n return skeleton.bones[boneIndex];\n }\n }\n }\n return null;\n };\n /**\n * Gets a bone using its id\n * @param name defines the bone's name\n * @return the bone or null if not found\n */\n Scene.prototype.getBoneByName = function (name) {\n for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {\n var skeleton = this.skeletons[skeletonIndex];\n for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {\n if (skeleton.bones[boneIndex].name === name) {\n return skeleton.bones[boneIndex];\n }\n }\n }\n return null;\n };\n /**\n * Gets a light node using its name\n * @param name defines the the light's name\n * @return the light or null if none found.\n */\n Scene.prototype.getLightByName = function (name) {\n for (var index = 0; index < this.lights.length; index++) {\n if (this.lights[index].name === name) {\n return this.lights[index];\n }\n }\n return null;\n };\n /**\n * Gets a light node using its id\n * @param id defines the light's id\n * @return the light or null if none found.\n */\n Scene.prototype.getLightByID = function (id) {\n for (var index = 0; index < this.lights.length; index++) {\n if (this.lights[index].id === id) {\n return this.lights[index];\n }\n }\n return null;\n };\n /**\n * Gets a light node using its scene-generated unique ID\n * @param uniqueId defines the light's unique id\n * @return the light or null if none found.\n */\n Scene.prototype.getLightByUniqueID = function (uniqueId) {\n for (var index = 0; index < this.lights.length; index++) {\n if (this.lights[index].uniqueId === uniqueId) {\n return this.lights[index];\n }\n }\n return null;\n };\n /**\n * Gets a particle system by id\n * @param id defines the particle system id\n * @return the corresponding system or null if none found\n */\n Scene.prototype.getParticleSystemByID = function (id) {\n for (var index = 0; index < this.particleSystems.length; index++) {\n if (this.particleSystems[index].id === id) {\n return this.particleSystems[index];\n }\n }\n return null;\n };\n /**\n * Gets a geometry using its ID\n * @param id defines the geometry's id\n * @return the geometry or null if none found.\n */\n Scene.prototype.getGeometryByID = function (id) {\n for (var index = 0; index < this.geometries.length; index++) {\n if (this.geometries[index].id === id) {\n return this.geometries[index];\n }\n }\n return null;\n };\n /**\n * Add a new geometry to this scene\n * @param geometry defines the geometry to be added to the scene.\n * @param force defines if the geometry must be pushed even if a geometry with this id already exists\n * @return a boolean defining if the geometry was added or not\n */\n Scene.prototype.pushGeometry = function (geometry, force) {\n if (!force && this.getGeometryByID(geometry.id)) {\n return false;\n }\n this.geometries.push(geometry);\n //notify the collision coordinator\n if (this.collisionCoordinator) {\n this.collisionCoordinator.onGeometryAdded(geometry);\n }\n this.onNewGeometryAddedObservable.notifyObservers(geometry);\n return true;\n };\n /**\n * Removes an existing geometry\n * @param geometry defines the geometry to be removed from the scene\n * @return a boolean defining if the geometry was removed or not\n */\n Scene.prototype.removeGeometry = function (geometry) {\n var index = this.geometries.indexOf(geometry);\n if (index > -1) {\n this.geometries.splice(index, 1);\n //notify the collision coordinator\n if (this.collisionCoordinator) {\n this.collisionCoordinator.onGeometryDeleted(geometry);\n }\n this.onGeometryRemovedObservable.notifyObservers(geometry);\n return true;\n }\n return false;\n };\n /**\n * Gets the list of geometries attached to the scene\n * @returns an array of Geometry\n */\n Scene.prototype.getGeometries = function () {\n return this.geometries;\n };\n /**\n * Gets the first added mesh found of a given ID\n * @param id defines the id to search for\n * @return the mesh found or null if not found at all\n */\n Scene.prototype.getMeshByID = function (id) {\n for (var index = 0; index < this.meshes.length; index++) {\n if (this.meshes[index].id === id) {\n return this.meshes[index];\n }\n }\n return null;\n };\n /**\n * Gets a list of meshes using their id\n * @param id defines the id to search for\n * @returns a list of meshes\n */\n Scene.prototype.getMeshesByID = function (id) {\n return this.meshes.filter(function (m) {\n return m.id === id;\n });\n };\n /**\n * Gets the first added transform node found of a given ID\n * @param id defines the id to search for\n * @return the found transform node or null if not found at all.\n */\n Scene.prototype.getTransformNodeByID = function (id) {\n for (var index = 0; index < this.transformNodes.length; index++) {\n if (this.transformNodes[index].id === id) {\n return this.transformNodes[index];\n }\n }\n return null;\n };\n /**\n * Gets a list of transform nodes using their id\n * @param id defines the id to search for\n * @returns a list of transform nodes\n */\n Scene.prototype.getTransformNodesByID = function (id) {\n return this.transformNodes.filter(function (m) {\n return m.id === id;\n });\n };\n /**\n * Gets a mesh with its auto-generated unique id\n * @param uniqueId defines the unique id to search for\n * @return the found mesh or null if not found at all.\n */\n Scene.prototype.getMeshByUniqueID = function (uniqueId) {\n for (var index = 0; index < this.meshes.length; index++) {\n if (this.meshes[index].uniqueId === uniqueId) {\n return this.meshes[index];\n }\n }\n return null;\n };\n /**\n * Gets a the last added mesh using a given id\n * @param id defines the id to search for\n * @return the found mesh or null if not found at all.\n */\n Scene.prototype.getLastMeshByID = function (id) {\n for (var index = this.meshes.length - 1; index >= 0; index--) {\n if (this.meshes[index].id === id) {\n return this.meshes[index];\n }\n }\n return null;\n };\n /**\n * Gets a the last added node (Mesh, Camera, Light) using a given id\n * @param id defines the id to search for\n * @return the found node or null if not found at all\n */\n Scene.prototype.getLastEntryByID = function (id) {\n var index;\n for (index = this.meshes.length - 1; index >= 0; index--) {\n if (this.meshes[index].id === id) {\n return this.meshes[index];\n }\n }\n for (index = this.transformNodes.length - 1; index >= 0; index--) {\n if (this.transformNodes[index].id === id) {\n return this.transformNodes[index];\n }\n }\n for (index = this.cameras.length - 1; index >= 0; index--) {\n if (this.cameras[index].id === id) {\n return this.cameras[index];\n }\n }\n for (index = this.lights.length - 1; index >= 0; index--) {\n if (this.lights[index].id === id) {\n return this.lights[index];\n }\n }\n return null;\n };\n /**\n * Gets a node (Mesh, Camera, Light) using a given id\n * @param id defines the id to search for\n * @return the found node or null if not found at all\n */\n Scene.prototype.getNodeByID = function (id) {\n var mesh = this.getMeshByID(id);\n if (mesh) {\n return mesh;\n }\n var light = this.getLightByID(id);\n if (light) {\n return light;\n }\n var camera = this.getCameraByID(id);\n if (camera) {\n return camera;\n }\n var bone = this.getBoneByID(id);\n return bone;\n };\n /**\n * Gets a node (Mesh, Camera, Light) using a given name\n * @param name defines the name to search for\n * @return the found node or null if not found at all.\n */\n Scene.prototype.getNodeByName = function (name) {\n var mesh = this.getMeshByName(name);\n if (mesh) {\n return mesh;\n }\n var light = this.getLightByName(name);\n if (light) {\n return light;\n }\n var camera = this.getCameraByName(name);\n if (camera) {\n return camera;\n }\n var bone = this.getBoneByName(name);\n return bone;\n };\n /**\n * Gets a mesh using a given name\n * @param name defines the name to search for\n * @return the found mesh or null if not found at all.\n */\n Scene.prototype.getMeshByName = function (name) {\n for (var index = 0; index < this.meshes.length; index++) {\n if (this.meshes[index].name === name) {\n return this.meshes[index];\n }\n }\n return null;\n };\n /**\n * Gets a transform node using a given name\n * @param name defines the name to search for\n * @return the found transform node or null if not found at all.\n */\n Scene.prototype.getTransformNodeByName = function (name) {\n for (var index = 0; index < this.transformNodes.length; index++) {\n if (this.transformNodes[index].name === name) {\n return this.transformNodes[index];\n }\n }\n return null;\n };\n /**\n * Gets a sound using a given name\n * @param name defines the name to search for\n * @return the found sound or null if not found at all.\n */\n Scene.prototype.getSoundByName = function (name) {\n var index;\n if (BABYLON.AudioEngine) {\n for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {\n if (this.mainSoundTrack.soundCollection[index].name === name) {\n return this.mainSoundTrack.soundCollection[index];\n }\n }\n for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {\n for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {\n if (this.soundTracks[sdIndex].soundCollection[index].name === name) {\n return this.soundTracks[sdIndex].soundCollection[index];\n }\n }\n }\n }\n return null;\n };\n /**\n * Gets a skeleton using a given id (if many are found, this function will pick the last one)\n * @param id defines the id to search for\n * @return the found skeleton or null if not found at all.\n */\n Scene.prototype.getLastSkeletonByID = function (id) {\n for (var index = this.skeletons.length - 1; index >= 0; index--) {\n if (this.skeletons[index].id === id) {\n return this.skeletons[index];\n }\n }\n return null;\n };\n /**\n * Gets a skeleton using a given id (if many are found, this function will pick the first one)\n * @param id defines the id to search for\n * @return the found skeleton or null if not found at all.\n */\n Scene.prototype.getSkeletonById = function (id) {\n for (var index = 0; index < this.skeletons.length; index++) {\n if (this.skeletons[index].id === id) {\n return this.skeletons[index];\n }\n }\n return null;\n };\n /**\n * Gets a skeleton using a given name\n * @param name defines the name to search for\n * @return the found skeleton or null if not found at all.\n */\n Scene.prototype.getSkeletonByName = function (name) {\n for (var index = 0; index < this.skeletons.length; index++) {\n if (this.skeletons[index].name === name) {\n return this.skeletons[index];\n }\n }\n return null;\n };\n /**\n * Gets a morph target manager using a given id (if many are found, this function will pick the last one)\n * @param id defines the id to search for\n * @return the found morph target manager or null if not found at all.\n */\n Scene.prototype.getMorphTargetManagerById = function (id) {\n for (var index = 0; index < this.morphTargetManagers.length; index++) {\n if (this.morphTargetManagers[index].uniqueId === id) {\n return this.morphTargetManagers[index];\n }\n }\n return null;\n };\n /**\n * Gets a boolean indicating if the given mesh is active\n * @param mesh defines the mesh to look for\n * @returns true if the mesh is in the active list\n */\n Scene.prototype.isActiveMesh = function (mesh) {\n return (this._activeMeshes.indexOf(mesh) !== -1);\n };\n Object.defineProperty(Scene.prototype, \"uid\", {\n /**\n * Return a unique id as a string which can serve as an identifier for the scene\n */\n get: function () {\n if (!this._uid) {\n this._uid = BABYLON.Tools.RandomId();\n }\n return this._uid;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Add an externaly attached data from its key.\n * This method call will fail and return false, if such key already exists.\n * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.\n * @param key the unique key that identifies the data\n * @param data the data object to associate to the key for this Engine instance\n * @return true if no such key were already present and the data was added successfully, false otherwise\n */\n Scene.prototype.addExternalData = function (key, data) {\n if (!this._externalData) {\n this._externalData = new BABYLON.StringDictionary();\n }\n return this._externalData.add(key, data);\n };\n /**\n * Get an externaly attached data from its key\n * @param key the unique key that identifies the data\n * @return the associated data, if present (can be null), or undefined if not present\n */\n Scene.prototype.getExternalData = function (key) {\n if (!this._externalData) {\n return null;\n }\n return this._externalData.get(key);\n };\n /**\n * Get an externaly attached data from its key, create it using a factory if it's not already present\n * @param key the unique key that identifies the data\n * @param factory the factory that will be called to create the instance if and only if it doesn't exists\n * @return the associated data, can be null if the factory returned null.\n */\n Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {\n if (!this._externalData) {\n this._externalData = new BABYLON.StringDictionary();\n }\n return this._externalData.getOrAddWithFactory(key, factory);\n };\n /**\n * Remove an externaly attached data from the Engine instance\n * @param key the unique key that identifies the data\n * @return true if the data was successfully removed, false if it doesn't exist\n */\n Scene.prototype.removeExternalData = function (key) {\n return this._externalData.remove(key);\n };\n Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {\n if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {\n for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {\n var step = _a[_i];\n step.action(mesh, subMesh);\n }\n var material = subMesh.getMaterial();\n if (material !== null && material !== undefined) {\n // Render targets\n if (material.getRenderTargetTextures !== undefined) {\n if (this._processedMaterials.indexOf(material) === -1) {\n this._processedMaterials.push(material);\n this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());\n }\n }\n // Dispatch\n this._activeIndices.addCount(subMesh.indexCount, false);\n this._renderingManager.dispatch(subMesh, mesh, material);\n }\n }\n };\n /**\n * Clear the processed materials smart array preventing retention point in material dispose.\n */\n Scene.prototype.freeProcessedMaterials = function () {\n this._processedMaterials.dispose();\n };\n /**\n * Clear the active meshes smart array preventing retention point in mesh dispose.\n */\n Scene.prototype.freeActiveMeshes = function () {\n this._activeMeshes.dispose();\n if (this.activeCamera && this.activeCamera._activeMeshes) {\n this.activeCamera._activeMeshes.dispose();\n }\n if (this.activeCameras) {\n for (var i = 0; i < this.activeCameras.length; i++) {\n var activeCamera = this.activeCameras[i];\n if (activeCamera && activeCamera._activeMeshes) {\n activeCamera._activeMeshes.dispose();\n }\n }\n }\n };\n /**\n * Clear the info related to rendering groups preventing retention points during dispose.\n */\n Scene.prototype.freeRenderingGroups = function () {\n if (this._renderingManager) {\n this._renderingManager.freeRenderingGroups();\n }\n if (this.textures) {\n for (var i = 0; i < this.textures.length; i++) {\n var texture = this.textures[i];\n if (texture && texture.renderList) {\n texture.freeRenderingGroups();\n }\n }\n }\n };\n /** @hidden */\n Scene.prototype._isInIntermediateRendering = function () {\n return this._intermediateRendering;\n };\n /**\n * Defines the current active mesh candidate provider\n * @param provider defines the provider to use\n */\n Scene.prototype.setActiveMeshCandidateProvider = function (provider) {\n this._activeMeshCandidateProvider = provider;\n };\n /**\n * Gets the current active mesh candidate provider\n * @returns the current active mesh candidate provider\n */\n Scene.prototype.getActiveMeshCandidateProvider = function () {\n return this._activeMeshCandidateProvider;\n };\n /**\n * Use this function to stop evaluating active meshes. The current list will be keep alive between frames\n * @returns the current scene\n */\n Scene.prototype.freezeActiveMeshes = function () {\n if (!this.activeCamera) {\n return this;\n }\n if (!this._frustumPlanes) {\n this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());\n }\n this._evaluateActiveMeshes();\n this._activeMeshesFrozen = true;\n return this;\n };\n /**\n * Use this function to restart evaluating active meshes on every frame\n * @returns the current scene\n */\n Scene.prototype.unfreezeActiveMeshes = function () {\n this._activeMeshesFrozen = false;\n return this;\n };\n Scene.prototype._evaluateActiveMeshes = function () {\n if (this._activeMeshesFrozen && this._activeMeshes.length) {\n return;\n }\n if (!this.activeCamera) {\n return;\n }\n this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);\n this.activeCamera._activeMeshes.reset();\n this._activeMeshes.reset();\n this._renderingManager.reset();\n this._processedMaterials.reset();\n this._activeParticleSystems.reset();\n this._activeSkeletons.reset();\n this._softwareSkinnedMeshes.reset();\n for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {\n var step = _a[_i];\n step.action();\n }\n // Meshes\n var meshes;\n var len;\n var checkIsEnabled = true;\n // Determine mesh candidates\n if (this._activeMeshCandidateProvider !== undefined) {\n // Use _activeMeshCandidateProvider\n meshes = this._activeMeshCandidateProvider.getMeshes(this);\n checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;\n if (meshes !== undefined) {\n len = meshes.length;\n }\n else {\n len = 0;\n }\n }\n else if (this._selectionOctree !== undefined) {\n // Octree\n var selection = this._selectionOctree.select(this._frustumPlanes);\n meshes = selection.data;\n len = selection.length;\n }\n else {\n // Full scene traversal\n len = this.meshes.length;\n meshes = this.meshes;\n }\n // Check each mesh\n for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {\n mesh = meshes[meshIndex];\n if (mesh.isBlocked) {\n continue;\n }\n this._totalVertices.addCount(mesh.getTotalVertices(), false);\n if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {\n continue;\n }\n mesh.computeWorldMatrix();\n // Intersections\n if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {\n this._meshesForIntersections.pushNoDuplicate(mesh);\n }\n // Switch to current LOD\n meshLOD = mesh.getLOD(this.activeCamera);\n if (meshLOD === undefined || meshLOD === null) {\n continue;\n }\n mesh._preActivate();\n if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {\n this._activeMeshes.push(mesh);\n this.activeCamera._activeMeshes.push(mesh);\n mesh._activate(this._renderId);\n if (meshLOD !== mesh) {\n meshLOD._activate(this._renderId);\n }\n this._activeMesh(mesh, meshLOD);\n }\n }\n this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);\n // Particle systems\n if (this.particlesEnabled) {\n this.onBeforeParticlesRenderingObservable.notifyObservers(this);\n for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {\n var particleSystem = this.particleSystems[particleIndex];\n if (!particleSystem.isStarted() || !particleSystem.emitter) {\n continue;\n }\n var emitter = particleSystem.emitter;\n if (!emitter.position || emitter.isEnabled()) {\n this._activeParticleSystems.push(particleSystem);\n particleSystem.animate();\n this._renderingManager.dispatchParticles(particleSystem);\n }\n }\n this.onAfterParticlesRenderingObservable.notifyObservers(this);\n }\n };\n Scene.prototype._activeMesh = function (sourceMesh, mesh) {\n if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {\n if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {\n mesh.skeleton.prepare();\n }\n if (!mesh.computeBonesUsingShaders) {\n this._softwareSkinnedMeshes.pushNoDuplicate(mesh);\n }\n }\n for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {\n var step = _a[_i];\n step.action(sourceMesh, mesh);\n }\n if (mesh !== undefined && mesh !== null\n && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {\n // Submeshes Octrees\n var len;\n var subMeshes;\n if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {\n var intersections = mesh._submeshesOctree.select(this._frustumPlanes);\n len = intersections.length;\n subMeshes = intersections.data;\n }\n else {\n subMeshes = mesh.subMeshes;\n len = subMeshes.length;\n }\n for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {\n subMesh = subMeshes[subIndex];\n this._evaluateSubMesh(subMesh, mesh);\n }\n }\n };\n /**\n * Update the transform matrix to update from the current active camera\n * @param force defines a boolean used to force the update even if cache is up to date\n */\n Scene.prototype.updateTransformMatrix = function (force) {\n if (!this.activeCamera) {\n return;\n }\n this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));\n };\n /**\n * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)\n * @param alternateCamera defines the camera to use\n */\n Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {\n this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());\n };\n Scene.prototype._renderForCamera = function (camera, rigParent) {\n if (camera && camera._skipRendering) {\n return;\n }\n var engine = this._engine;\n this.activeCamera = camera;\n if (!this.activeCamera)\n throw new Error(\"Active camera not set\");\n // Viewport\n engine.setViewport(this.activeCamera.viewport);\n // Camera\n this.resetCachedMaterial();\n this._renderId++;\n this.updateTransformMatrix();\n if (camera._alternateCamera) {\n this.updateAlternateTransformMatrix(camera._alternateCamera);\n this._alternateRendering = true;\n }\n this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);\n // Meshes\n this._evaluateActiveMeshes();\n // Software skinning\n for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {\n var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];\n mesh.applySkeleton(mesh.skeleton);\n }\n // Render targets\n this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);\n if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {\n this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);\n }\n if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {\n this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);\n }\n if (this.renderTargetsEnabled) {\n this._intermediateRendering = true;\n if (this._renderTargets.length > 0) {\n BABYLON.Tools.StartPerformanceCounter(\"Render targets\", this._renderTargets.length > 0);\n for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {\n var renderTarget = this._renderTargets.data[renderIndex];\n if (renderTarget._shouldRender()) {\n this._renderId++;\n var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;\n renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);\n }\n }\n BABYLON.Tools.EndPerformanceCounter(\"Render targets\", this._renderTargets.length > 0);\n this._renderId++;\n }\n for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {\n var step = _a[_i];\n step.action(this.activeCamera);\n }\n this._intermediateRendering = false;\n engine.restoreDefaultFramebuffer(); // Restore back buffer if needed\n }\n this.onAfterRenderTargetsRenderObservable.notifyObservers(this);\n // Prepare Frame\n if (this.postProcessManager) {\n this.postProcessManager._prepareFrame();\n }\n // Before Camera Draw\n for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {\n var step = _c[_b];\n step.action(this.activeCamera);\n }\n // Render\n this.onBeforeDrawPhaseObservable.notifyObservers(this);\n this._renderingManager.render(null, null, true, true);\n this.onAfterDrawPhaseObservable.notifyObservers(this);\n // After Camera Draw\n for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {\n var step = _e[_d];\n step.action(this.activeCamera);\n }\n // Finalize frame\n if (this.postProcessManager) {\n this.postProcessManager._finalizeFrame(camera.isIntermediate);\n }\n // Reset some special arrays\n this._renderTargets.reset();\n this._alternateRendering = false;\n this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);\n };\n Scene.prototype._processSubCameras = function (camera) {\n if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {\n this._renderForCamera(camera);\n return;\n }\n // rig cameras\n for (var index = 0; index < camera._rigCameras.length; index++) {\n this._renderForCamera(camera._rigCameras[index], camera);\n }\n this.activeCamera = camera;\n this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());\n };\n Scene.prototype._checkIntersections = function () {\n for (var index = 0; index < this._meshesForIntersections.length; index++) {\n var sourceMesh = this._meshesForIntersections.data[index];\n if (!sourceMesh.actionManager) {\n continue;\n }\n for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {\n var action = sourceMesh.actionManager.actions[actionIndex];\n if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {\n var parameters = action.getTriggerParameter();\n var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;\n var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);\n var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);\n if (areIntersecting && currentIntersectionInProgress === -1) {\n if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {\n action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));\n sourceMesh._intersectionsInProgress.push(otherMesh);\n }\n else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {\n sourceMesh._intersectionsInProgress.push(otherMesh);\n }\n }\n else if (!areIntersecting && currentIntersectionInProgress > -1) {\n //They intersected, and now they don't.\n //is this trigger an exit trigger? execute an event.\n if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {\n action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));\n }\n //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.\n if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {\n var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;\n return otherMesh === parameterMesh;\n }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {\n sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);\n }\n }\n }\n }\n }\n };\n /**\n * Render the scene\n * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)\n */\n Scene.prototype.render = function (updateCameras) {\n if (updateCameras === void 0) { updateCameras = true; }\n if (this.isDisposed) {\n return;\n }\n // Register components that have been associated lately to the scene.\n this._registerTransientComponents();\n this._activeParticles.fetchNewFrame();\n this._totalVertices.fetchNewFrame();\n this._activeIndices.fetchNewFrame();\n this._activeBones.fetchNewFrame();\n this._meshesForIntersections.reset();\n this.resetCachedMaterial();\n this.onBeforeAnimationsObservable.notifyObservers(this);\n // Actions\n if (this.actionManager) {\n this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);\n }\n //Simplification Queue\n if (this.simplificationQueue && !this.simplificationQueue.running) {\n this.simplificationQueue.executeNext();\n }\n if (this._engine.isDeterministicLockStep()) {\n var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;\n var defaultFPS = (60.0 / 1000.0);\n var defaultFrameTime = 1000 / 60; // frame time in MS\n if (this._physicsEngine) {\n defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;\n }\n var stepsTaken = 0;\n var maxSubSteps = this._engine.getLockstepMaxSteps();\n var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));\n internalSteps = Math.min(internalSteps, maxSubSteps);\n do {\n this.onBeforeStepObservable.notifyObservers(this);\n // Animations\n this._animationRatio = defaultFrameTime * defaultFPS;\n this._animate();\n this.onAfterAnimationsObservable.notifyObservers(this);\n // Physics\n if (this._physicsEngine) {\n this.onBeforePhysicsObservable.notifyObservers(this);\n this._physicsEngine._step(defaultFrameTime / 1000);\n this.onAfterPhysicsObservable.notifyObservers(this);\n }\n this.onAfterStepObservable.notifyObservers(this);\n this._currentStepId++;\n stepsTaken++;\n deltaTime -= defaultFrameTime;\n } while (deltaTime > 0 && stepsTaken < internalSteps);\n this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;\n }\n else {\n // Animations\n var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));\n this._animationRatio = deltaTime * (60.0 / 1000.0);\n this._animate();\n this.onAfterAnimationsObservable.notifyObservers(this);\n // Physics\n if (this._physicsEngine) {\n this.onBeforePhysicsObservable.notifyObservers(this);\n this._physicsEngine._step(deltaTime / 1000.0);\n this.onAfterPhysicsObservable.notifyObservers(this);\n }\n }\n // Before camera update steps\n for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {\n var step = _a[_i];\n step.action();\n }\n // Update Cameras\n if (updateCameras) {\n if (this.activeCameras.length > 0) {\n for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {\n var camera = this.activeCameras[cameraIndex];\n camera.update();\n if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {\n // rig cameras\n for (var index = 0; index < camera._rigCameras.length; index++) {\n camera._rigCameras[index].update();\n }\n }\n }\n }\n else if (this.activeCamera) {\n this.activeCamera.update();\n if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {\n // rig cameras\n for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {\n this.activeCamera._rigCameras[index].update();\n }\n }\n }\n }\n // Before render\n this.onBeforeRenderObservable.notifyObservers(this);\n // Customs render targets\n this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);\n var engine = this.getEngine();\n var currentActiveCamera = this.activeCamera;\n if (this.renderTargetsEnabled) {\n BABYLON.Tools.StartPerformanceCounter(\"Custom render targets\", this.customRenderTargets.length > 0);\n this._intermediateRendering = true;\n for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {\n var renderTarget = this.customRenderTargets[customIndex];\n if (renderTarget._shouldRender()) {\n this._renderId++;\n this.activeCamera = renderTarget.activeCamera || this.activeCamera;\n if (!this.activeCamera)\n throw new Error(\"Active camera not set\");\n // Viewport\n engine.setViewport(this.activeCamera.viewport);\n // Camera\n this.updateTransformMatrix();\n renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);\n }\n }\n BABYLON.Tools.EndPerformanceCounter(\"Custom render targets\", this.customRenderTargets.length > 0);\n this._intermediateRendering = false;\n this._renderId++;\n }\n // Restore back buffer\n if (this.customRenderTargets.length > 0) {\n engine.restoreDefaultFramebuffer();\n }\n this.onAfterRenderTargetsRenderObservable.notifyObservers(this);\n this.activeCamera = currentActiveCamera;\n // Procedural textures\n if (this.proceduralTexturesEnabled) {\n BABYLON.Tools.StartPerformanceCounter(\"Procedural textures\", this.proceduralTextures.length > 0);\n for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {\n var proceduralTexture = this.proceduralTextures[proceduralIndex];\n if (proceduralTexture._shouldRender()) {\n proceduralTexture.render();\n }\n }\n BABYLON.Tools.EndPerformanceCounter(\"Procedural textures\", this.proceduralTextures.length > 0);\n }\n // Clear\n if (this.autoClearDepthAndStencil || this.autoClear) {\n this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);\n }\n // Shadows\n if (this.shadowsEnabled) {\n for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {\n var light = this.lights[lightIndex];\n var shadowGenerator = light.getShadowGenerator();\n if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {\n var shadowMap = (shadowGenerator.getShadowMap());\n if (this.textures.indexOf(shadowMap) !== -1) {\n this._renderTargets.push(shadowMap);\n }\n }\n }\n }\n // Depth renderer\n for (var key in this._depthRenderer) {\n this._renderTargets.push(this._depthRenderer[key].getDepthMap());\n }\n // Geometry renderer\n if (this._geometryBufferRenderer) {\n this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());\n }\n // RenderPipeline\n if (this._postProcessRenderPipelineManager) {\n this._postProcessRenderPipelineManager.update();\n }\n // Multi-cameras?\n if (this.activeCameras.length > 0) {\n for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {\n if (cameraIndex > 0) {\n this._engine.clear(null, false, true, true);\n }\n this._processSubCameras(this.activeCameras[cameraIndex]);\n }\n }\n else {\n if (!this.activeCamera) {\n throw new Error(\"No camera defined\");\n }\n this._processSubCameras(this.activeCamera);\n }\n // Intersection checks\n this._checkIntersections();\n // Update the audio listener attached to the camera\n if (BABYLON.AudioEngine) {\n this._updateAudioParameters();\n }\n // After render\n if (this.afterRender) {\n this.afterRender();\n }\n this.onAfterRenderObservable.notifyObservers(this);\n // Cleaning\n for (var index = 0; index < this._toBeDisposed.length; index++) {\n var data = this._toBeDisposed.data[index];\n if (data) {\n data.dispose();\n }\n this._toBeDisposed[index] = null;\n }\n this._toBeDisposed.reset();\n if (this.dumpNextRenderTargets) {\n this.dumpNextRenderTargets = false;\n }\n this._activeBones.addCount(0, true);\n this._activeIndices.addCount(0, true);\n this._activeParticles.addCount(0, true);\n };\n Scene.prototype._updateAudioParameters = function () {\n if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {\n return;\n }\n var listeningCamera;\n var audioEngine = BABYLON.Engine.audioEngine;\n if (this.activeCameras.length > 0) {\n listeningCamera = this.activeCameras[0];\n }\n else {\n listeningCamera = this.activeCamera;\n }\n if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {\n audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);\n // for VR cameras\n if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {\n listeningCamera = listeningCamera.rigCameras[0];\n }\n var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());\n var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);\n cameraDirection.normalize();\n // To avoid some errors on GearVR\n if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {\n audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);\n }\n var i;\n for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {\n var sound = this.mainSoundTrack.soundCollection[i];\n if (sound.useCustomAttenuation) {\n sound.updateDistanceFromListener();\n }\n }\n for (i = 0; i < this.soundTracks.length; i++) {\n for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {\n sound = this.soundTracks[i].soundCollection[j];\n if (sound.useCustomAttenuation) {\n sound.updateDistanceFromListener();\n }\n }\n }\n }\n };\n Object.defineProperty(Scene.prototype, \"audioEnabled\", {\n // Audio\n /**\n * Gets or sets if audio support is enabled\n * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music\n */\n get: function () {\n return this._audioEnabled;\n },\n set: function (value) {\n this._audioEnabled = value;\n if (BABYLON.AudioEngine) {\n if (this._audioEnabled) {\n this._enableAudio();\n }\n else {\n this._disableAudio();\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Scene.prototype._disableAudio = function () {\n var i;\n for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {\n this.mainSoundTrack.soundCollection[i].pause();\n }\n for (i = 0; i < this.soundTracks.length; i++) {\n for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {\n this.soundTracks[i].soundCollection[j].pause();\n }\n }\n };\n Scene.prototype._enableAudio = function () {\n var i;\n for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {\n if (this.mainSoundTrack.soundCollection[i].isPaused) {\n this.mainSoundTrack.soundCollection[i].play();\n }\n }\n for (i = 0; i < this.soundTracks.length; i++) {\n for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {\n if (this.soundTracks[i].soundCollection[j].isPaused) {\n this.soundTracks[i].soundCollection[j].play();\n }\n }\n }\n };\n Object.defineProperty(Scene.prototype, \"headphone\", {\n /**\n * Gets or sets if audio will be output to headphones\n * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music\n */\n get: function () {\n return this._headphone;\n },\n set: function (value) {\n this._headphone = value;\n if (BABYLON.AudioEngine) {\n if (this._headphone) {\n this._switchAudioModeForHeadphones();\n }\n else {\n this._switchAudioModeForNormalSpeakers();\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Scene.prototype._switchAudioModeForHeadphones = function () {\n this.mainSoundTrack.switchPanningModelToHRTF();\n for (var i = 0; i < this.soundTracks.length; i++) {\n this.soundTracks[i].switchPanningModelToHRTF();\n }\n };\n Scene.prototype._switchAudioModeForNormalSpeakers = function () {\n this.mainSoundTrack.switchPanningModelToEqualPower();\n for (var i = 0; i < this.soundTracks.length; i++) {\n this.soundTracks[i].switchPanningModelToEqualPower();\n }\n };\n /**\n * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.\n * @param camera The camera to create the depth renderer on (default: scene's active camera)\n * @returns the created depth renderer\n */\n Scene.prototype.enableDepthRenderer = function (camera) {\n camera = camera || this.activeCamera;\n if (!camera) {\n throw \"No camera available to enable depth renderer\";\n }\n if (!this._depthRenderer[camera.id]) {\n var textureType = 0;\n if (this._engine.getCaps().textureHalfFloatRender) {\n textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else if (this._engine.getCaps().textureFloatRender) {\n textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n else {\n throw \"Depth renderer does not support int texture type\";\n }\n this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);\n }\n return this._depthRenderer[camera.id];\n };\n /**\n * Disables a depth renderer for a given camera\n * @param camera The camera to disable the depth renderer on (default: scene's active camera)\n */\n Scene.prototype.disableDepthRenderer = function (camera) {\n camera = camera || this.activeCamera;\n if (!camera || !this._depthRenderer[camera.id]) {\n return;\n }\n this._depthRenderer[camera.id].dispose();\n delete this._depthRenderer[camera.id];\n };\n /**\n * Enables a GeometryBufferRender and associates it with the scene\n * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)\n * @returns the GeometryBufferRenderer\n */\n Scene.prototype.enableGeometryBufferRenderer = function (ratio) {\n if (ratio === void 0) { ratio = 1; }\n if (this._geometryBufferRenderer) {\n return this._geometryBufferRenderer;\n }\n this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);\n if (!this._geometryBufferRenderer.isSupported) {\n this._geometryBufferRenderer = null;\n }\n return this._geometryBufferRenderer;\n };\n /**\n * Disables the GeometryBufferRender associated with the scene\n */\n Scene.prototype.disableGeometryBufferRenderer = function () {\n if (!this._geometryBufferRenderer) {\n return;\n }\n this._geometryBufferRenderer.dispose();\n this._geometryBufferRenderer = null;\n };\n /**\n * Freeze all materials\n * A frozen material will not be updatable but should be faster to render\n */\n Scene.prototype.freezeMaterials = function () {\n for (var i = 0; i < this.materials.length; i++) {\n this.materials[i].freeze();\n }\n };\n /**\n * Unfreeze all materials\n * A frozen material will not be updatable but should be faster to render\n */\n Scene.prototype.unfreezeMaterials = function () {\n for (var i = 0; i < this.materials.length; i++) {\n this.materials[i].unfreeze();\n }\n };\n /**\n * Releases all held ressources\n */\n Scene.prototype.dispose = function () {\n this.beforeRender = null;\n this.afterRender = null;\n this.skeletons = [];\n this.morphTargetManagers = [];\n this._transientComponents = [];\n this._isReadyForMeshStage.clear();\n this._beforeEvaluateActiveMeshStage.clear();\n this._evaluateSubMeshStage.clear();\n this._activeMeshStage.clear();\n this._cameraDrawRenderTargetStage.clear();\n this._beforeCameraDrawStage.clear();\n this._beforeRenderingGroupDrawStage.clear();\n this._afterRenderingGroupDrawStage.clear();\n this._afterCameraDrawStage.clear();\n this._beforeCameraUpdateStage.clear();\n for (var _i = 0, _a = this._components; _i < _a.length; _i++) {\n var component = _a[_i];\n component.dispose();\n }\n this.importedMeshesFiles = new Array();\n this.stopAllAnimations();\n this.resetCachedMaterial();\n for (var key in this._depthRenderer) {\n this._depthRenderer[key].dispose();\n }\n // Smart arrays\n if (this.activeCamera) {\n this.activeCamera._activeMeshes.dispose();\n this.activeCamera = null;\n }\n this._activeMeshes.dispose();\n this._renderingManager.dispose();\n this._processedMaterials.dispose();\n this._activeParticleSystems.dispose();\n this._activeSkeletons.dispose();\n this._softwareSkinnedMeshes.dispose();\n this._renderTargets.dispose();\n this._registeredForLateAnimationBindings.dispose();\n this._meshesForIntersections.dispose();\n this._toBeDisposed.dispose();\n // Abort active requests\n for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {\n var request = _c[_b];\n request.abort();\n }\n // Debug layer\n if (this._debugLayer) {\n this._debugLayer.hide();\n }\n // Events\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onBeforeRenderObservable.clear();\n this.onAfterRenderObservable.clear();\n this.onBeforeRenderTargetsRenderObservable.clear();\n this.onAfterRenderTargetsRenderObservable.clear();\n this.onAfterStepObservable.clear();\n this.onBeforeStepObservable.clear();\n this.onBeforeActiveMeshesEvaluationObservable.clear();\n this.onAfterActiveMeshesEvaluationObservable.clear();\n this.onBeforeParticlesRenderingObservable.clear();\n this.onAfterParticlesRenderingObservable.clear();\n this.onBeforeSpritesRenderingObservable.clear();\n this.onAfterSpritesRenderingObservable.clear();\n this.onBeforeDrawPhaseObservable.clear();\n this.onAfterDrawPhaseObservable.clear();\n this.onBeforePhysicsObservable.clear();\n this.onAfterPhysicsObservable.clear();\n this.onBeforeAnimationsObservable.clear();\n this.onAfterAnimationsObservable.clear();\n this.onDataLoadedObservable.clear();\n this.onBeforeRenderingGroupObservable.clear();\n this.onAfterRenderingGroupObservable.clear();\n this.detachControl();\n // Release sounds & sounds tracks\n if (BABYLON.AudioEngine) {\n this.disposeSounds();\n }\n // VR Helper\n if (this.VRHelper) {\n this.VRHelper.dispose();\n }\n // Detach cameras\n var canvas = this._engine.getRenderingCanvas();\n if (canvas) {\n var index;\n for (index = 0; index < this.cameras.length; index++) {\n this.cameras[index].detachControl(canvas);\n }\n }\n // Release animation groups\n while (this.animationGroups.length) {\n this.animationGroups[0].dispose();\n }\n // Release lights\n while (this.lights.length) {\n this.lights[0].dispose();\n }\n // Release meshes\n while (this.meshes.length) {\n this.meshes[0].dispose(true);\n }\n while (this.transformNodes.length) {\n this.removeTransformNode(this.transformNodes[0]);\n }\n // Release cameras\n while (this.cameras.length) {\n this.cameras[0].dispose();\n }\n // Release materials\n if (this.defaultMaterial) {\n this.defaultMaterial.dispose();\n }\n while (this.multiMaterials.length) {\n this.multiMaterials[0].dispose();\n }\n while (this.materials.length) {\n this.materials[0].dispose();\n }\n // Release particles\n while (this.particleSystems.length) {\n this.particleSystems[0].dispose();\n }\n // Release sprites\n while (this.spriteManagers.length) {\n this.spriteManagers[0].dispose();\n }\n // Release postProcesses\n while (this.postProcesses.length) {\n this.postProcesses[0].dispose();\n }\n // Release textures\n while (this.textures.length) {\n this.textures[0].dispose();\n }\n // Release UBO\n this._sceneUbo.dispose();\n if (this._alternateSceneUbo) {\n this._alternateSceneUbo.dispose();\n }\n // Post-processes\n this.postProcessManager.dispose();\n if (this._postProcessRenderPipelineManager) {\n this._postProcessRenderPipelineManager.dispose();\n }\n // Physics\n if (this._physicsEngine) {\n this.disablePhysicsEngine();\n }\n // Remove from engine\n index = this._engine.scenes.indexOf(this);\n if (index > -1) {\n this._engine.scenes.splice(index, 1);\n }\n this._engine.wipeCaches(true);\n this._isDisposed = true;\n };\n Object.defineProperty(Scene.prototype, \"isDisposed\", {\n /**\n * Gets if the scene is already disposed\n */\n get: function () {\n return this._isDisposed;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Releases sounds & soundtracks\n */\n Scene.prototype.disposeSounds = function () {\n if (!this._mainSoundTrack) {\n return;\n }\n this.mainSoundTrack.dispose();\n for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {\n this.soundTracks[scIndex].dispose();\n }\n };\n /**\n * Call this function to reduce memory footprint of the scene.\n * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)\n */\n Scene.prototype.clearCachedVertexData = function () {\n for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {\n var mesh = this.meshes[meshIndex];\n var geometry = mesh.geometry;\n if (geometry) {\n geometry._indices = [];\n for (var vbName in geometry._vertexBuffers) {\n if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {\n continue;\n }\n geometry._vertexBuffers[vbName]._buffer._data = null;\n }\n }\n }\n };\n /**\n * This function will remove the local cached buffer data from texture.\n * It will save memory but will prevent the texture from being rebuilt\n */\n Scene.prototype.cleanCachedTextureBuffer = function () {\n for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {\n var baseTexture = _a[_i];\n var buffer = baseTexture._buffer;\n if (buffer) {\n baseTexture._buffer = null;\n }\n }\n };\n // Octrees\n /**\n * Get the world extend vectors with an optional filter\n *\n * @param filterPredicate the predicate - which meshes should be included when calculating the world size\n * @returns {{ min: Vector3; max: Vector3 }} min and max vectors\n */\n Scene.prototype.getWorldExtends = function (filterPredicate) {\n var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n filterPredicate = filterPredicate || (function () { return true; });\n this.meshes.filter(filterPredicate).forEach(function (mesh) {\n mesh.computeWorldMatrix(true);\n if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {\n return;\n }\n var boundingInfo = mesh.getBoundingInfo();\n var minBox = boundingInfo.boundingBox.minimumWorld;\n var maxBox = boundingInfo.boundingBox.maximumWorld;\n BABYLON.Tools.CheckExtends(minBox, min, max);\n BABYLON.Tools.CheckExtends(maxBox, min, max);\n });\n return {\n min: min,\n max: max\n };\n };\n /**\n * Creates or updates the octree used to boost selection (picking)\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees\n * @param maxCapacity defines the maximum capacity per leaf\n * @param maxDepth defines the maximum depth of the octree\n * @returns an octree of AbstractMesh\n */\n Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {\n if (maxCapacity === void 0) { maxCapacity = 64; }\n if (maxDepth === void 0) { maxDepth = 2; }\n if (!this._selectionOctree) {\n this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);\n }\n var worldExtends = this.getWorldExtends();\n // Update octree\n this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);\n return this._selectionOctree;\n };\n // Picking\n /**\n * Creates a ray that can be used to pick in the scene\n * @param x defines the x coordinate of the origin (on-screen)\n * @param y defines the y coordinate of the origin (on-screen)\n * @param world defines the world matrix to use if you want to pick in object space (instead of world space)\n * @param camera defines the camera to use for the picking\n * @param cameraViewSpace defines if picking will be done in view space (false by default)\n * @returns a Ray\n */\n Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {\n if (cameraViewSpace === void 0) { cameraViewSpace = false; }\n var result = BABYLON.Ray.Zero();\n this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);\n return result;\n };\n /**\n * Creates a ray that can be used to pick in the scene\n * @param x defines the x coordinate of the origin (on-screen)\n * @param y defines the y coordinate of the origin (on-screen)\n * @param world defines the world matrix to use if you want to pick in object space (instead of world space)\n * @param result defines the ray where to store the picking ray\n * @param camera defines the camera to use for the picking\n * @param cameraViewSpace defines if picking will be done in view space (false by default)\n * @returns the current scene\n */\n Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {\n if (cameraViewSpace === void 0) { cameraViewSpace = false; }\n var engine = this._engine;\n if (!camera) {\n if (!this.activeCamera)\n throw new Error(\"Active camera not set\");\n camera = this.activeCamera;\n }\n var cameraViewport = camera.viewport;\n var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n // Moving coordinates to local viewport world\n x = x / this._engine.getHardwareScalingLevel() - viewport.x;\n y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);\n result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());\n return this;\n };\n /**\n * Creates a ray that can be used to pick in the scene\n * @param x defines the x coordinate of the origin (on-screen)\n * @param y defines the y coordinate of the origin (on-screen)\n * @param camera defines the camera to use for the picking\n * @returns a Ray\n */\n Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {\n var result = BABYLON.Ray.Zero();\n this.createPickingRayInCameraSpaceToRef(x, y, result, camera);\n return result;\n };\n /**\n * Creates a ray that can be used to pick in the scene\n * @param x defines the x coordinate of the origin (on-screen)\n * @param y defines the y coordinate of the origin (on-screen)\n * @param result defines the ray where to store the picking ray\n * @param camera defines the camera to use for the picking\n * @returns the current scene\n */\n Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {\n if (!BABYLON.PickingInfo) {\n return this;\n }\n var engine = this._engine;\n if (!camera) {\n if (!this.activeCamera)\n throw new Error(\"Active camera not set\");\n camera = this.activeCamera;\n }\n var cameraViewport = camera.viewport;\n var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n var identity = BABYLON.Matrix.Identity();\n // Moving coordinates to local viewport world\n x = x / this._engine.getHardwareScalingLevel() - viewport.x;\n y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);\n result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());\n return this;\n };\n Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {\n if (!BABYLON.PickingInfo) {\n return null;\n }\n var pickingInfo = null;\n for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {\n var mesh = this.meshes[meshIndex];\n if (predicate) {\n if (!predicate(mesh)) {\n continue;\n }\n }\n else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {\n continue;\n }\n var world = mesh.getWorldMatrix();\n var ray = rayFunction(world);\n var result = mesh.intersects(ray, fastCheck);\n if (!result || !result.hit)\n continue;\n if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)\n continue;\n pickingInfo = result;\n if (fastCheck) {\n break;\n }\n }\n return pickingInfo || new BABYLON.PickingInfo();\n };\n Scene.prototype._internalMultiPick = function (rayFunction, predicate) {\n if (!BABYLON.PickingInfo) {\n return null;\n }\n var pickingInfos = new Array();\n for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {\n var mesh = this.meshes[meshIndex];\n if (predicate) {\n if (!predicate(mesh)) {\n continue;\n }\n }\n else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {\n continue;\n }\n var world = mesh.getWorldMatrix();\n var ray = rayFunction(world);\n var result = mesh.intersects(ray, false);\n if (!result || !result.hit)\n continue;\n pickingInfos.push(result);\n }\n return pickingInfos;\n };\n Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {\n if (!BABYLON.PickingInfo) {\n return null;\n }\n var pickingInfo = null;\n if (!camera) {\n if (!this.activeCamera) {\n return null;\n }\n camera = this.activeCamera;\n }\n if (this.spriteManagers.length > 0) {\n for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {\n var spriteManager = this.spriteManagers[spriteIndex];\n if (!spriteManager.isPickable) {\n continue;\n }\n var result = spriteManager.intersects(ray, camera, predicate, fastCheck);\n if (!result || !result.hit)\n continue;\n if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)\n continue;\n pickingInfo = result;\n if (fastCheck) {\n break;\n }\n }\n }\n return pickingInfo || new BABYLON.PickingInfo();\n };\n /** Launch a ray to try to pick a mesh in the scene\n * @param x position on screen\n * @param y position on screen\n * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true\n * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.\n * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used\n * @returns a PickingInfo\n */\n Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {\n var _this = this;\n if (!BABYLON.PickingInfo) {\n return null;\n }\n var result = this._internalPick(function (world) {\n _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);\n return _this._tempPickingRay;\n }, predicate, fastCheck);\n if (result) {\n result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);\n }\n return result;\n };\n /** Launch a ray to try to pick a sprite in the scene\n * @param x position on screen\n * @param y position on screen\n * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true\n * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.\n * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used\n * @returns a PickingInfo\n */\n Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {\n this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);\n return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);\n };\n /** Use the given ray to pick a mesh in the scene\n * @param ray The ray to use to pick meshes\n * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true\n * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null\n * @returns a PickingInfo\n */\n Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {\n var _this = this;\n var result = this._internalPick(function (world) {\n if (!_this._pickWithRayInverseMatrix) {\n _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();\n }\n world.invertToRef(_this._pickWithRayInverseMatrix);\n if (!_this._cachedRayForTransform) {\n _this._cachedRayForTransform = BABYLON.Ray.Zero();\n }\n BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);\n return _this._cachedRayForTransform;\n }, predicate, fastCheck);\n if (result) {\n result.ray = ray;\n }\n return result;\n };\n /**\n * Launch a ray to try to pick a mesh in the scene\n * @param x X position on screen\n * @param y Y position on screen\n * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true\n * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used\n * @returns an array of PickingInfo\n */\n Scene.prototype.multiPick = function (x, y, predicate, camera) {\n var _this = this;\n return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);\n };\n /**\n * Launch a ray to try to pick a mesh in the scene\n * @param ray Ray to use\n * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true\n * @returns an array of PickingInfo\n */\n Scene.prototype.multiPickWithRay = function (ray, predicate) {\n var _this = this;\n return this._internalMultiPick(function (world) {\n if (!_this._pickWithRayInverseMatrix) {\n _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();\n }\n world.invertToRef(_this._pickWithRayInverseMatrix);\n if (!_this._cachedRayForTransform) {\n _this._cachedRayForTransform = BABYLON.Ray.Zero();\n }\n BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);\n return _this._cachedRayForTransform;\n }, predicate);\n };\n /**\n * Force the value of meshUnderPointer\n * @param mesh defines the mesh to use\n */\n Scene.prototype.setPointerOverMesh = function (mesh) {\n if (this._pointerOverMesh === mesh) {\n return;\n }\n if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {\n this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));\n }\n this._pointerOverMesh = mesh;\n if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {\n this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));\n }\n };\n /**\n * Gets the mesh under the pointer\n * @returns a Mesh or null if no mesh is under the pointer\n */\n Scene.prototype.getPointerOverMesh = function () {\n return this._pointerOverMesh;\n };\n /**\n * Force the sprite under the pointer\n * @param sprite defines the sprite to use\n */\n Scene.prototype.setPointerOverSprite = function (sprite) {\n if (this._pointerOverSprite === sprite) {\n return;\n }\n if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {\n this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));\n }\n this._pointerOverSprite = sprite;\n if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {\n this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));\n }\n };\n /**\n * Gets the sprite under the pointer\n * @returns a Sprite or null if no sprite is under the pointer\n */\n Scene.prototype.getPointerOverSprite = function () {\n return this._pointerOverSprite;\n };\n // Physics\n /**\n * Gets the current physics engine\n * @returns a PhysicsEngine or null if none attached\n */\n Scene.prototype.getPhysicsEngine = function () {\n return this._physicsEngine;\n };\n /**\n * Enables physics to the current scene\n * @param gravity defines the scene's gravity for the physics engine\n * @param plugin defines the physics engine to be used. defaults to OimoJS.\n * @return a boolean indicating if the physics engine was initialized\n */\n Scene.prototype.enablePhysics = function (gravity, plugin) {\n if (gravity === void 0) { gravity = null; }\n if (this._physicsEngine) {\n return true;\n }\n try {\n this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);\n return true;\n }\n catch (e) {\n BABYLON.Tools.Error(e.message);\n return false;\n }\n };\n /**\n * Disables and disposes the physics engine associated with the scene\n */\n Scene.prototype.disablePhysicsEngine = function () {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.dispose();\n this._physicsEngine = null;\n };\n /**\n * Gets a boolean indicating if there is an active physics engine\n * @returns a boolean indicating if there is an active physics engine\n */\n Scene.prototype.isPhysicsEnabled = function () {\n return this._physicsEngine !== undefined;\n };\n /**\n * Deletes a physics compound impostor\n * @param compound defines the compound to delete\n */\n Scene.prototype.deleteCompoundImpostor = function (compound) {\n var mesh = compound.parts[0].mesh;\n if (mesh.physicsImpostor) {\n mesh.physicsImpostor.dispose( /*true*/);\n mesh.physicsImpostor = null;\n }\n };\n // Misc.\n /** @hidden */\n Scene.prototype._rebuildGeometries = function () {\n for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {\n var geometry = _a[_i];\n geometry._rebuild();\n }\n for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {\n var mesh = _c[_b];\n mesh._rebuild();\n }\n if (this.postProcessManager) {\n this.postProcessManager._rebuild();\n }\n for (var _d = 0, _e = this._components; _d < _e.length; _d++) {\n var component = _e[_d];\n component.rebuild();\n }\n for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {\n var system = _g[_f];\n system.rebuild();\n }\n if (this._postProcessRenderPipelineManager) {\n this._postProcessRenderPipelineManager._rebuild();\n }\n };\n /** @hidden */\n Scene.prototype._rebuildTextures = function () {\n for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {\n var texture = _a[_i];\n texture._rebuild();\n }\n this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n };\n /**\n * Creates a default light for the scene.\n * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light\n * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light\n */\n Scene.prototype.createDefaultLight = function (replace) {\n if (replace === void 0) { replace = false; }\n // Dispose existing light in replace mode.\n if (replace) {\n if (this.lights) {\n for (var i = 0; i < this.lights.length; i++) {\n this.lights[i].dispose();\n }\n }\n }\n // Light\n if (this.lights.length === 0) {\n new BABYLON.HemisphericLight(\"default light\", BABYLON.Vector3.Up(), this);\n }\n };\n /**\n * Creates a default camera for the scene.\n * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera\n * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera\n * @param replace has default false, when true replaces the active camera in the scene\n * @param attachCameraControls has default false, when true attaches camera controls to the canvas.\n */\n Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {\n if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }\n if (replace === void 0) { replace = false; }\n if (attachCameraControls === void 0) { attachCameraControls = false; }\n // Dispose existing camera in replace mode.\n if (replace) {\n if (this.activeCamera) {\n this.activeCamera.dispose();\n this.activeCamera = null;\n }\n }\n // Camera\n if (!this.activeCamera) {\n var worldExtends = this.getWorldExtends();\n var worldSize = worldExtends.max.subtract(worldExtends.min);\n var worldCenter = worldExtends.min.add(worldSize.scale(0.5));\n var camera;\n var radius = worldSize.length() * 1.5;\n // empty scene scenario!\n if (!isFinite(radius)) {\n radius = 1;\n worldCenter.copyFromFloats(0, 0, 0);\n }\n if (createArcRotateCamera) {\n var arcRotateCamera = new BABYLON.ArcRotateCamera(\"default camera\", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);\n arcRotateCamera.lowerRadiusLimit = radius * 0.01;\n arcRotateCamera.wheelPrecision = 100 / radius;\n camera = arcRotateCamera;\n }\n else {\n var freeCamera = new BABYLON.FreeCamera(\"default camera\", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);\n freeCamera.setTarget(worldCenter);\n camera = freeCamera;\n }\n camera.minZ = radius * 0.01;\n camera.maxZ = radius * 1000;\n camera.speed = radius * 0.2;\n this.activeCamera = camera;\n var canvas = this.getEngine().getRenderingCanvas();\n if (attachCameraControls && canvas) {\n camera.attachControl(canvas);\n }\n }\n };\n /**\n * Creates a default camera and a default light.\n * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light\n * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera\n * @param replace has the default false, when true replaces the active camera/light in the scene\n * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.\n */\n Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {\n if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }\n if (replace === void 0) { replace = false; }\n if (attachCameraControls === void 0) { attachCameraControls = false; }\n this.createDefaultLight(replace);\n this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);\n };\n /**\n * Creates a new sky box\n * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox\n * @param environmentTexture defines the texture to use as environment texture\n * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used\n * @param scale defines the overall scale of the skybox\n * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1\n * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture\n * @returns a new mesh holding the sky box\n */\n Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {\n if (pbr === void 0) { pbr = false; }\n if (scale === void 0) { scale = 1000; }\n if (blur === void 0) { blur = 0; }\n if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }\n if (!environmentTexture) {\n BABYLON.Tools.Warn(\"Can not create default skybox without environment texture.\");\n return null;\n }\n if (setGlobalEnvTexture) {\n if (environmentTexture) {\n this.environmentTexture = environmentTexture;\n }\n }\n // Skybox\n var hdrSkybox = BABYLON.Mesh.CreateBox(\"hdrSkyBox\", scale, this);\n if (pbr) {\n var hdrSkyboxMaterial = new BABYLON.PBRMaterial(\"skyBox\", this);\n hdrSkyboxMaterial.backFaceCulling = false;\n hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();\n if (hdrSkyboxMaterial.reflectionTexture) {\n hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;\n }\n hdrSkyboxMaterial.microSurface = 1.0 - blur;\n hdrSkyboxMaterial.disableLighting = true;\n hdrSkyboxMaterial.twoSidedLighting = true;\n hdrSkybox.infiniteDistance = true;\n hdrSkybox.material = hdrSkyboxMaterial;\n }\n else {\n var skyboxMaterial = new BABYLON.StandardMaterial(\"skyBox\", this);\n skyboxMaterial.backFaceCulling = false;\n skyboxMaterial.reflectionTexture = environmentTexture.clone();\n if (skyboxMaterial.reflectionTexture) {\n skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;\n }\n skyboxMaterial.disableLighting = true;\n hdrSkybox.infiniteDistance = true;\n hdrSkybox.material = skyboxMaterial;\n }\n return hdrSkybox;\n };\n /**\n * Creates a new environment\n * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment\n * @param options defines the options you can use to configure the environment\n * @returns the new EnvironmentHelper\n */\n Scene.prototype.createDefaultEnvironment = function (options) {\n if (BABYLON.EnvironmentHelper) {\n return new BABYLON.EnvironmentHelper(options, this);\n }\n return null;\n };\n /**\n * Creates a new VREXperienceHelper\n * @see http://doc.babylonjs.com/how_to/webvr_helper\n * @param webVROptions defines the options used to create the new VREXperienceHelper\n * @returns a new VREXperienceHelper\n */\n Scene.prototype.createDefaultVRExperience = function (webVROptions) {\n if (webVROptions === void 0) { webVROptions = {}; }\n return new BABYLON.VRExperienceHelper(this, webVROptions);\n };\n // Tags\n Scene.prototype._getByTags = function (list, tagsQuery, forEach) {\n if (tagsQuery === undefined) {\n // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)\n return list;\n }\n var listByTags = [];\n forEach = forEach || (function (item) { return; });\n for (var i in list) {\n var item = list[i];\n if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {\n listByTags.push(item);\n forEach(item);\n }\n }\n return listByTags;\n };\n /**\n * Get a list of meshes by tags\n * @param tagsQuery defines the tags query to use\n * @param forEach defines a predicate used to filter results\n * @returns an array of Mesh\n */\n Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {\n return this._getByTags(this.meshes, tagsQuery, forEach);\n };\n /**\n * Get a list of cameras by tags\n * @param tagsQuery defines the tags query to use\n * @param forEach defines a predicate used to filter results\n * @returns an array of Camera\n */\n Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {\n return this._getByTags(this.cameras, tagsQuery, forEach);\n };\n /**\n * Get a list of lights by tags\n * @param tagsQuery defines the tags query to use\n * @param forEach defines a predicate used to filter results\n * @returns an array of Light\n */\n Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {\n return this._getByTags(this.lights, tagsQuery, forEach);\n };\n /**\n * Get a list of materials by tags\n * @param tagsQuery defines the tags query to use\n * @param forEach defines a predicate used to filter results\n * @returns an array of Material\n */\n Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {\n return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));\n };\n /**\n * Overrides the default sort function applied in the renderging group to prepare the meshes.\n * This allowed control for front to back rendering or reversly depending of the special needs.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param opaqueSortCompareFn The opaque queue comparison function use to sort.\n * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.\n * @param transparentSortCompareFn The transparent queue comparison function use to sort.\n */\n Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {\n if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }\n if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }\n if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }\n this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);\n };\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n * @param depth Automatically clears depth between groups if true and autoClear is true.\n * @param stencil Automatically clears stencil between groups if true and autoClear is true.\n */\n Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {\n if (depth === void 0) { depth = true; }\n if (stencil === void 0) { stencil = true; }\n this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);\n };\n /**\n * Gets the current auto clear configuration for one rendering group of the rendering\n * manager.\n * @param index the rendering group index to get the information for\n * @returns The auto clear setup for the requested rendering group\n */\n Scene.prototype.getAutoClearDepthStencilSetup = function (index) {\n return this._renderingManager.getAutoClearDepthStencilSetup(index);\n };\n /**\n * Will flag all materials as dirty to trigger new shader compilation\n * @param flag defines the flag used to specify which material part must be marked as dirty\n * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty\n */\n Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {\n for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {\n var material = _a[_i];\n if (predicate && !predicate(material)) {\n continue;\n }\n material.markAsDirty(flag);\n }\n };\n /** @hidden */\n Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {\n var _this = this;\n var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);\n this._activeRequests.push(request);\n request.onCompleteObservable.add(function (request) {\n _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);\n });\n return request;\n };\n /** @hidden */\n Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this._loadFile(url, function (data) {\n resolve(data);\n }, undefined, useDatabase, useArrayBuffer, function (request, exception) {\n reject(exception);\n });\n });\n };\n // Statics\n Scene._FOGMODE_NONE = 0;\n Scene._FOGMODE_EXP = 1;\n Scene._FOGMODE_EXP2 = 2;\n Scene._FOGMODE_LINEAR = 3;\n Scene._uniqueIdCounter = 0;\n /**\n * Gets or sets the minimum deltatime when deterministic lock step is enabled\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n */\n Scene.MinDeltaTime = 1.0;\n /**\n * Gets or sets the maximum deltatime when deterministic lock step is enabled\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n */\n Scene.MaxDeltaTime = 1000.0;\n /** The distance in pixel that you have to move to prevent some events */\n Scene.DragMovementThreshold = 10; // in pixels\n /** Time in milliseconds to wait to raise long press events if button is still pressed */\n Scene.LongPressDelay = 500; // in milliseconds\n /** Time in milliseconds with two consecutive clicks will be considered as a double click */\n Scene.DoubleClickDelay = 300; // in milliseconds\n /** If you need to check double click without raising a single click at first click, enable this flag */\n Scene.ExclusiveDoubleClickMode = false;\n return Scene;\n }(BABYLON.AbstractScene));\n BABYLON.Scene = Scene;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.scene.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Set of assets to keep when moving a scene into an asset container.\n */\n var KeepAssets = /** @class */ (function (_super) {\n __extends(KeepAssets, _super);\n function KeepAssets() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n return KeepAssets;\n }(BABYLON.AbstractScene));\n BABYLON.KeepAssets = KeepAssets;\n /**\n * Container with a set of assets that can be added or removed from a scene.\n */\n var AssetContainer = /** @class */ (function (_super) {\n __extends(AssetContainer, _super);\n /**\n * Instantiates an AssetContainer.\n * @param scene The scene the AssetContainer belongs to.\n */\n function AssetContainer(scene) {\n var _this = _super.call(this) || this;\n _this.scene = scene;\n return _this;\n }\n /**\n * Adds all the assets from the container to the scene.\n */\n AssetContainer.prototype.addAllToScene = function () {\n var _this = this;\n this.cameras.forEach(function (o) {\n _this.scene.addCamera(o);\n });\n this.lights.forEach(function (o) {\n _this.scene.addLight(o);\n });\n this.meshes.forEach(function (o) {\n _this.scene.addMesh(o);\n });\n this.skeletons.forEach(function (o) {\n _this.scene.addSkeleton(o);\n });\n this.animations.forEach(function (o) {\n _this.scene.addAnimation(o);\n });\n this.animationGroups.forEach(function (o) {\n _this.scene.addAnimationGroup(o);\n });\n this.multiMaterials.forEach(function (o) {\n _this.scene.addMultiMaterial(o);\n });\n this.materials.forEach(function (o) {\n _this.scene.addMaterial(o);\n });\n this.morphTargetManagers.forEach(function (o) {\n _this.scene.addMorphTargetManager(o);\n });\n this.geometries.forEach(function (o) {\n _this.scene.addGeometry(o);\n });\n this.transformNodes.forEach(function (o) {\n _this.scene.addTransformNode(o);\n });\n this.actionManagers.forEach(function (o) {\n _this.scene.addActionManager(o);\n });\n this.sounds.forEach(function (o) {\n o.play();\n o.autoplay = true;\n _this.scene.mainSoundTrack.AddSound(o);\n });\n this.textures.forEach(function (o) {\n _this.scene.addTexture(o);\n });\n for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {\n var component = _a[_i];\n component.addFromContainer(this.scene);\n }\n };\n /**\n * Removes all the assets in the container from the scene\n */\n AssetContainer.prototype.removeAllFromScene = function () {\n var _this = this;\n this.cameras.forEach(function (o) {\n _this.scene.removeCamera(o);\n });\n this.lights.forEach(function (o) {\n _this.scene.removeLight(o);\n });\n this.meshes.forEach(function (o) {\n _this.scene.removeMesh(o);\n });\n this.skeletons.forEach(function (o) {\n _this.scene.removeSkeleton(o);\n });\n this.animations.forEach(function (o) {\n _this.scene.removeAnimation(o);\n });\n this.animationGroups.forEach(function (o) {\n _this.scene.removeAnimationGroup(o);\n });\n this.multiMaterials.forEach(function (o) {\n _this.scene.removeMultiMaterial(o);\n });\n this.materials.forEach(function (o) {\n _this.scene.removeMaterial(o);\n });\n this.morphTargetManagers.forEach(function (o) {\n _this.scene.removeMorphTargetManager(o);\n });\n this.geometries.forEach(function (o) {\n _this.scene.removeGeometry(o);\n });\n this.transformNodes.forEach(function (o) {\n _this.scene.removeTransformNode(o);\n });\n this.actionManagers.forEach(function (o) {\n _this.scene.removeActionManager(o);\n });\n this.sounds.forEach(function (o) {\n o.stop();\n o.autoplay = false;\n _this.scene.mainSoundTrack.RemoveSound(o);\n });\n this.textures.forEach(function (o) {\n _this.scene.removeTexture(o);\n });\n for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {\n var component = _a[_i];\n component.removeFromContainer(this.scene);\n }\n };\n AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {\n if (!sourceAssets) {\n return;\n }\n for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {\n var asset = sourceAssets_1[_i];\n var move = true;\n if (keepAssets) {\n for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {\n var keepAsset = keepAssets_1[_a];\n if (asset === keepAsset) {\n move = false;\n break;\n }\n }\n }\n if (move) {\n targetAssets.push(asset);\n }\n }\n };\n /**\n * Removes all the assets contained in the scene and adds them to the container.\n * @param keepAssets Set of assets to keep in the scene. (default: empty)\n */\n AssetContainer.prototype.moveAllFromScene = function (keepAssets) {\n if (keepAssets === undefined) {\n keepAssets = new KeepAssets();\n }\n for (var key in this) {\n if (this.hasOwnProperty(key)) {\n this[key] = this[key] || [];\n this._moveAssets(this.scene[key], this[key], keepAssets[key]);\n }\n }\n this.removeAllFromScene();\n };\n /**\n * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.\n * @returns the root mesh\n */\n AssetContainer.prototype.createRootMesh = function () {\n var rootMesh = new BABYLON.Mesh(\"assetContainerRootMesh\", this.scene);\n this.meshes.forEach(function (m) {\n if (!m.parent) {\n rootMesh.addChild(m);\n }\n });\n this.meshes.unshift(rootMesh);\n return rootMesh;\n };\n return AssetContainer;\n }(BABYLON.AbstractScene));\n BABYLON.AssetContainer = AssetContainer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.assetContainer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Buffer = /** @class */ (function () {\n /**\n * Constructor\n * @param engine the engine\n * @param data the data to use for this buffer\n * @param updatable whether the data is updatable\n * @param stride the stride (optional)\n * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)\n * @param instanced whether the buffer is instanced (optional)\n * @param useBytes set to true if the stride in in bytes (optional)\n */\n function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {\n if (stride === void 0) { stride = 0; }\n if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }\n if (instanced === void 0) { instanced = false; }\n if (useBytes === void 0) { useBytes = false; }\n if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'\n this._engine = engine.getScene().getEngine();\n }\n else {\n this._engine = engine;\n }\n this._updatable = updatable;\n this._instanced = instanced;\n this._data = data;\n this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;\n if (!postponeInternalCreation) { // by default\n this.create();\n }\n }\n /**\n * Create a new {BABYLON.VertexBuffer} based on the current buffer\n * @param kind defines the vertex buffer kind (position, normal, etc.)\n * @param offset defines offset in the buffer (0 by default)\n * @param size defines the size in floats of attributes (position is 3 for instance)\n * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)\n * @param instanced defines if the vertex buffer contains indexed data\n * @param useBytes defines if the offset and stride are in bytes\n * @returns the new vertex buffer\n */\n Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {\n if (useBytes === void 0) { useBytes = false; }\n var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;\n var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;\n // a lot of these parameters are ignored as they are overriden by the buffer\n return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);\n };\n // Properties\n Buffer.prototype.isUpdatable = function () {\n return this._updatable;\n };\n Buffer.prototype.getData = function () {\n return this._data;\n };\n Buffer.prototype.getBuffer = function () {\n return this._buffer;\n };\n /**\n * Gets the stride in float32 units (i.e. byte stride / 4).\n * May not be an integer if the byte stride is not divisible by 4.\n * DEPRECATED. Use byteStride instead.\n * @returns the stride in float32 units\n */\n Buffer.prototype.getStrideSize = function () {\n return this.byteStride / Float32Array.BYTES_PER_ELEMENT;\n };\n // Methods\n Buffer.prototype.create = function (data) {\n if (data === void 0) { data = null; }\n if (!data && this._buffer) {\n return; // nothing to do\n }\n data = data || this._data;\n if (!data) {\n return;\n }\n if (!this._buffer) { // create buffer\n if (this._updatable) {\n this._buffer = this._engine.createDynamicVertexBuffer(data);\n this._data = data;\n }\n else {\n this._buffer = this._engine.createVertexBuffer(data);\n }\n }\n else if (this._updatable) { // update buffer\n this._engine.updateDynamicVertexBuffer(this._buffer, data);\n this._data = data;\n }\n };\n Buffer.prototype._rebuild = function () {\n this._buffer = null;\n this.create(this._data);\n };\n Buffer.prototype.update = function (data) {\n this.create(data);\n };\n /**\n * Updates the data directly.\n * @param data the new data\n * @param offset the new offset\n * @param vertexCount the vertex count (optional)\n * @param useBytes set to true if the offset is in bytes\n */\n Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {\n if (useBytes === void 0) { useBytes = false; }\n if (!this._buffer) {\n return;\n }\n if (this._updatable) { // update buffer\n this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));\n this._data = null;\n }\n };\n Buffer.prototype.dispose = function () {\n if (!this._buffer) {\n return;\n }\n if (this._engine._releaseBuffer(this._buffer)) {\n this._buffer = null;\n }\n };\n return Buffer;\n }());\n BABYLON.Buffer = Buffer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.buffer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var VertexBuffer = /** @class */ (function () {\n /**\n * Constructor\n * @param engine the engine\n * @param data the data to use for this vertex buffer\n * @param kind the vertex buffer kind\n * @param updatable whether the data is updatable\n * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)\n * @param stride the stride (optional)\n * @param instanced whether the buffer is instanced (optional)\n * @param offset the offset of the data (optional)\n * @param size the number of components (optional)\n * @param type the type of the component (optional)\n * @param normalized whether the data contains normalized data (optional)\n * @param useBytes set to true if stride and offset are in bytes (optional)\n */\n function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {\n if (normalized === void 0) { normalized = false; }\n if (useBytes === void 0) { useBytes = false; }\n if (data instanceof BABYLON.Buffer) {\n this._buffer = data;\n this._ownsBuffer = false;\n }\n else {\n this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);\n this._ownsBuffer = true;\n }\n this._kind = kind;\n if (type == undefined) {\n var data_1 = this.getData();\n this.type = VertexBuffer.FLOAT;\n if (data_1 instanceof Int8Array)\n this.type = VertexBuffer.BYTE;\n else if (data_1 instanceof Uint8Array)\n this.type = VertexBuffer.UNSIGNED_BYTE;\n else if (data_1 instanceof Int16Array)\n this.type = VertexBuffer.SHORT;\n else if (data_1 instanceof Uint16Array)\n this.type = VertexBuffer.UNSIGNED_SHORT;\n else if (data_1 instanceof Int32Array)\n this.type = VertexBuffer.INT;\n else if (data_1 instanceof Uint32Array)\n this.type = VertexBuffer.UNSIGNED_INT;\n }\n else {\n this.type = type;\n }\n var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);\n if (useBytes) {\n this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));\n this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);\n this.byteOffset = offset || 0;\n }\n else {\n this._size = size || stride || VertexBuffer.DeduceStride(kind);\n this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));\n this.byteOffset = (offset || 0) * typeByteLength;\n }\n this.normalized = normalized;\n this._instanced = instanced !== undefined ? instanced : false;\n this._instanceDivisor = instanced ? 1 : 0;\n }\n Object.defineProperty(VertexBuffer.prototype, \"instanceDivisor\", {\n /**\n * Gets or sets the instance divisor when in instanced mode\n */\n get: function () {\n return this._instanceDivisor;\n },\n set: function (value) {\n this._instanceDivisor = value;\n if (value == 0) {\n this._instanced = false;\n }\n else {\n this._instanced = true;\n }\n },\n enumerable: true,\n configurable: true\n });\n VertexBuffer.prototype._rebuild = function () {\n if (!this._buffer) {\n return;\n }\n this._buffer._rebuild();\n };\n /**\n * Returns the kind of the VertexBuffer (string).\n */\n VertexBuffer.prototype.getKind = function () {\n return this._kind;\n };\n // Properties\n /**\n * Boolean : is the VertexBuffer updatable ?\n */\n VertexBuffer.prototype.isUpdatable = function () {\n return this._buffer.isUpdatable();\n };\n /**\n * Returns an array of numbers or a typed array containing the VertexBuffer data.\n */\n VertexBuffer.prototype.getData = function () {\n return this._buffer.getData();\n };\n /**\n * Returns the WebGLBuffer associated to the VertexBuffer.\n */\n VertexBuffer.prototype.getBuffer = function () {\n return this._buffer.getBuffer();\n };\n /**\n * Returns the stride as a multiple of the type byte length.\n * DEPRECATED. Use byteStride instead.\n */\n VertexBuffer.prototype.getStrideSize = function () {\n return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);\n };\n /**\n * Returns the offset as a multiple of the type byte length.\n * DEPRECATED. Use byteOffset instead.\n */\n VertexBuffer.prototype.getOffset = function () {\n return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);\n };\n /**\n * Returns the number of components per vertex attribute (integer).\n */\n VertexBuffer.prototype.getSize = function () {\n return this._size;\n };\n /**\n * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?\n */\n VertexBuffer.prototype.getIsInstanced = function () {\n return this._instanced;\n };\n /**\n * Returns the instancing divisor, zero for non-instanced (integer).\n */\n VertexBuffer.prototype.getInstanceDivisor = function () {\n return this._instanceDivisor;\n };\n // Methods\n /**\n * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.\n * Returns the created WebGLBuffer.\n */\n VertexBuffer.prototype.create = function (data) {\n return this._buffer.create(data);\n };\n /**\n * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.\n * This function will create a new buffer if the current one is not updatable\n * Returns the updated WebGLBuffer.\n */\n VertexBuffer.prototype.update = function (data) {\n return this._buffer.update(data);\n };\n /**\n * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.\n * Returns the directly updated WebGLBuffer.\n * @param data the new data\n * @param offset the new offset\n * @param useBytes set to true if the offset is in bytes\n */\n VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {\n if (useBytes === void 0) { useBytes = false; }\n this._buffer.updateDirectly(data, offset, undefined, useBytes);\n };\n /**\n * Disposes the VertexBuffer and the underlying WebGLBuffer.\n */\n VertexBuffer.prototype.dispose = function () {\n if (this._ownsBuffer) {\n this._buffer.dispose();\n }\n };\n /**\n * Enumerates each value of this vertex buffer as numbers.\n * @param count the number of values to enumerate\n * @param callback the callback function called for each value\n */\n VertexBuffer.prototype.forEach = function (count, callback) {\n VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);\n };\n Object.defineProperty(VertexBuffer, \"PositionKind\", {\n get: function () {\n return VertexBuffer._PositionKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"NormalKind\", {\n get: function () {\n return VertexBuffer._NormalKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"TangentKind\", {\n get: function () {\n return VertexBuffer._TangentKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"UVKind\", {\n get: function () {\n return VertexBuffer._UVKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"UV2Kind\", {\n get: function () {\n return VertexBuffer._UV2Kind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"UV3Kind\", {\n get: function () {\n return VertexBuffer._UV3Kind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"UV4Kind\", {\n get: function () {\n return VertexBuffer._UV4Kind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"UV5Kind\", {\n get: function () {\n return VertexBuffer._UV5Kind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"UV6Kind\", {\n get: function () {\n return VertexBuffer._UV6Kind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"ColorKind\", {\n get: function () {\n return VertexBuffer._ColorKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"MatricesIndicesKind\", {\n get: function () {\n return VertexBuffer._MatricesIndicesKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"MatricesWeightsKind\", {\n get: function () {\n return VertexBuffer._MatricesWeightsKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"MatricesIndicesExtraKind\", {\n get: function () {\n return VertexBuffer._MatricesIndicesExtraKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"MatricesWeightsExtraKind\", {\n get: function () {\n return VertexBuffer._MatricesWeightsExtraKind;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Deduces the stride given a kind.\n * @param kind The kind string to deduce\n * @returns The deduced stride\n */\n VertexBuffer.DeduceStride = function (kind) {\n switch (kind) {\n case VertexBuffer.UVKind:\n case VertexBuffer.UV2Kind:\n case VertexBuffer.UV3Kind:\n case VertexBuffer.UV4Kind:\n case VertexBuffer.UV5Kind:\n case VertexBuffer.UV6Kind:\n return 2;\n case VertexBuffer.NormalKind:\n case VertexBuffer.PositionKind:\n return 3;\n case VertexBuffer.ColorKind:\n case VertexBuffer.MatricesIndicesKind:\n case VertexBuffer.MatricesIndicesExtraKind:\n case VertexBuffer.MatricesWeightsKind:\n case VertexBuffer.MatricesWeightsExtraKind:\n case VertexBuffer.TangentKind:\n return 4;\n default:\n throw new Error(\"Invalid kind '\" + kind + \"'\");\n }\n };\n /**\n * Gets the byte length of the given type.\n * @param type the type\n * @returns the number of bytes\n */\n VertexBuffer.GetTypeByteLength = function (type) {\n switch (type) {\n case VertexBuffer.BYTE:\n case VertexBuffer.UNSIGNED_BYTE:\n return 1;\n case VertexBuffer.SHORT:\n case VertexBuffer.UNSIGNED_SHORT:\n return 2;\n case VertexBuffer.INT:\n case VertexBuffer.FLOAT:\n return 4;\n default:\n throw new Error(\"Invalid type '\" + type + \"'\");\n }\n };\n /**\n * Enumerates each value of the given parameters as numbers.\n * @param data the data to enumerate\n * @param byteOffset the byte offset of the data\n * @param byteStride the byte stride of the data\n * @param componentCount the number of components per element\n * @param componentType the type of the component\n * @param count the total number of components\n * @param normalized whether the data is normalized\n * @param callback the callback function called for each value\n */\n VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {\n if (data instanceof Array) {\n var offset = byteOffset / 4;\n var stride = byteStride / 4;\n for (var index = 0; index < count; index += componentCount) {\n for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {\n callback(data[offset + componentIndex], index + componentIndex);\n }\n offset += stride;\n }\n }\n else {\n var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);\n var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);\n for (var index = 0; index < count; index += componentCount) {\n var componentByteOffset = byteOffset;\n for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {\n var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);\n callback(value, index + componentIndex);\n componentByteOffset += componentByteLength;\n }\n byteOffset += byteStride;\n }\n }\n };\n VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {\n switch (type) {\n case VertexBuffer.BYTE: {\n var value = dataView.getInt8(byteOffset);\n if (normalized) {\n value = Math.max(value / 127, -1);\n }\n return value;\n }\n case VertexBuffer.UNSIGNED_BYTE: {\n var value = dataView.getUint8(byteOffset);\n if (normalized) {\n value = value / 255;\n }\n return value;\n }\n case VertexBuffer.SHORT: {\n var value = dataView.getInt16(byteOffset, true);\n if (normalized) {\n value = Math.max(value / 16383, -1);\n }\n return value;\n }\n case VertexBuffer.UNSIGNED_SHORT: {\n var value = dataView.getUint16(byteOffset, true);\n if (normalized) {\n value = value / 65535;\n }\n return value;\n }\n case VertexBuffer.FLOAT: {\n return dataView.getFloat32(byteOffset, true);\n }\n default: {\n throw new Error(\"Invalid component type \" + type);\n }\n }\n };\n /**\n * The byte type.\n */\n VertexBuffer.BYTE = 5120;\n /**\n * The unsigned byte type.\n */\n VertexBuffer.UNSIGNED_BYTE = 5121;\n /**\n * The short type.\n */\n VertexBuffer.SHORT = 5122;\n /**\n * The unsigned short type.\n */\n VertexBuffer.UNSIGNED_SHORT = 5123;\n /**\n * The integer type.\n */\n VertexBuffer.INT = 5124;\n /**\n * The unsigned integer type.\n */\n VertexBuffer.UNSIGNED_INT = 5125;\n /**\n * The float type.\n */\n VertexBuffer.FLOAT = 5126;\n // Enums\n VertexBuffer._PositionKind = \"position\";\n VertexBuffer._NormalKind = \"normal\";\n VertexBuffer._TangentKind = \"tangent\";\n VertexBuffer._UVKind = \"uv\";\n VertexBuffer._UV2Kind = \"uv2\";\n VertexBuffer._UV3Kind = \"uv3\";\n VertexBuffer._UV4Kind = \"uv4\";\n VertexBuffer._UV5Kind = \"uv5\";\n VertexBuffer._UV6Kind = \"uv6\";\n VertexBuffer._ColorKind = \"color\";\n VertexBuffer._MatricesIndicesKind = \"matricesIndices\";\n VertexBuffer._MatricesWeightsKind = \"matricesWeights\";\n VertexBuffer._MatricesIndicesExtraKind = \"matricesIndicesExtra\";\n VertexBuffer._MatricesWeightsExtraKind = \"matricesWeightsExtra\";\n return VertexBuffer;\n }());\n BABYLON.VertexBuffer = VertexBuffer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vertexBuffer.js.map\n\n\n\n//# sourceMappingURL=babylon.internalTextureLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context\n */\n var DummyInternalTextureTracker = /** @class */ (function () {\n function DummyInternalTextureTracker() {\n /**\n * Gets or set the previous tracker in the list\n */\n this.previous = null;\n /**\n * Gets or set the next tracker in the list\n */\n this.next = null;\n }\n return DummyInternalTextureTracker;\n }());\n BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.internalTextureTracker.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to store data associated with WebGL texture data for the engine\n * This class should not be used directly\n */\n var InternalTexture = /** @class */ (function () {\n /**\n * Creates a new InternalTexture\n * @param engine defines the engine to use\n * @param dataSource defines the type of data that will be used\n */\n function InternalTexture(engine, dataSource) {\n /**\n * Observable called when the texture is loaded\n */\n this.onLoadedObservable = new BABYLON.Observable();\n /**\n * Gets or set the previous tracker in the list\n */\n this.previous = null;\n /**\n * Gets or set the next tracker in the list\n */\n this.next = null;\n // Private\n /** @hidden */\n this._initialSlot = -1;\n /** @hidden */\n this._designatedSlot = -1;\n /** @hidden */\n this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;\n /** @hidden */\n this._comparisonFunction = 0;\n /** @hidden */\n this._sphericalPolynomial = null;\n /** @hidden */\n this._lodGenerationScale = 0;\n /** @hidden */\n this._lodGenerationOffset = 0;\n /** @hidden */\n this._isRGBD = false;\n /** @hidden */\n this._references = 1;\n this._engine = engine;\n this._dataSource = dataSource;\n this._webGLTexture = engine._createTexture();\n }\n /**\n * Gets the Engine the texture belongs to.\n * @returns The babylon engine\n */\n InternalTexture.prototype.getEngine = function () {\n return this._engine;\n };\n Object.defineProperty(InternalTexture.prototype, \"dataSource\", {\n /**\n * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)\n */\n get: function () {\n return this._dataSource;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)\n */\n InternalTexture.prototype.incrementReferences = function () {\n this._references++;\n };\n /**\n * Change the size of the texture (not the size of the content)\n * @param width defines the new width\n * @param height defines the new height\n * @param depth defines the new depth (1 by default)\n */\n InternalTexture.prototype.updateSize = function (width, height, depth) {\n if (depth === void 0) { depth = 1; }\n this.width = width;\n this.height = height;\n this.depth = depth;\n this.baseWidth = width;\n this.baseHeight = height;\n this.baseDepth = depth;\n this._size = width * height * depth;\n };\n /** @hidden */\n InternalTexture.prototype._rebuild = function () {\n var _this = this;\n var proxy;\n this.isReady = false;\n this._cachedCoordinatesMode = null;\n this._cachedWrapU = null;\n this._cachedWrapV = null;\n this._cachedAnisotropicFilteringLevel = null;\n switch (this._dataSource) {\n case InternalTexture.DATASOURCE_TEMP:\n return;\n case InternalTexture.DATASOURCE_URL:\n proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {\n _this.isReady = true;\n }, null, this._buffer, undefined, this.format);\n proxy._swapAndDie(this);\n return;\n case InternalTexture.DATASOURCE_RAW:\n proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);\n proxy._swapAndDie(this);\n this.isReady = true;\n return;\n case InternalTexture.DATASOURCE_RAW3D:\n proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);\n proxy._swapAndDie(this);\n this.isReady = true;\n return;\n case InternalTexture.DATASOURCE_DYNAMIC:\n proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);\n proxy._swapAndDie(this);\n // The engine will make sure to update content so no need to flag it as isReady = true\n return;\n case InternalTexture.DATASOURCE_RENDERTARGET:\n var options = new BABYLON.RenderTargetCreationOptions();\n options.generateDepthBuffer = this._generateDepthBuffer;\n options.generateMipMaps = this.generateMipMaps;\n options.generateStencilBuffer = this._generateStencilBuffer;\n options.samplingMode = this.samplingMode;\n options.type = this.type;\n if (this.isCube) {\n proxy = this._engine.createRenderTargetCubeTexture(this.width, options);\n }\n else {\n var size = {\n width: this.width,\n height: this.height\n };\n proxy = this._engine.createRenderTargetTexture(size, options);\n }\n proxy._swapAndDie(this);\n this.isReady = true;\n return;\n case InternalTexture.DATASOURCE_DEPTHTEXTURE:\n var depthTextureOptions = {\n bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,\n comparisonFunction: this._comparisonFunction,\n generateStencil: this._generateStencilBuffer,\n isCube: this.isCube\n };\n proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);\n proxy._swapAndDie(this);\n this.isReady = true;\n return;\n case InternalTexture.DATASOURCE_CUBE:\n proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {\n _this.isReady = true;\n }, null, this.format, this._extension);\n proxy._swapAndDie(this);\n return;\n case InternalTexture.DATASOURCE_CUBERAW:\n proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);\n proxy._swapAndDie(this);\n this.isReady = true;\n return;\n case InternalTexture.DATASOURCE_CUBERAW_RGBD:\n proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);\n BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {\n _this.isReady = true;\n });\n proxy._swapAndDie(this);\n return;\n case InternalTexture.DATASOURCE_CUBEPREFILTERED:\n proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {\n if (proxy) {\n proxy._swapAndDie(_this);\n }\n _this.isReady = true;\n }, null, this.format, this._extension);\n proxy._sphericalPolynomial = this._sphericalPolynomial;\n return;\n }\n };\n InternalTexture.prototype._swapAndDie = function (target) {\n target._webGLTexture = this._webGLTexture;\n if (this._framebuffer) {\n target._framebuffer = this._framebuffer;\n }\n if (this._depthStencilBuffer) {\n target._depthStencilBuffer = this._depthStencilBuffer;\n }\n if (this._lodTextureHigh) {\n if (target._lodTextureHigh) {\n target._lodTextureHigh.dispose();\n }\n target._lodTextureHigh = this._lodTextureHigh;\n }\n if (this._lodTextureMid) {\n if (target._lodTextureMid) {\n target._lodTextureMid.dispose();\n }\n target._lodTextureMid = this._lodTextureMid;\n }\n if (this._lodTextureLow) {\n if (target._lodTextureLow) {\n target._lodTextureLow.dispose();\n }\n target._lodTextureLow = this._lodTextureLow;\n }\n var cache = this._engine.getLoadedTexturesCache();\n var index = cache.indexOf(this);\n if (index !== -1) {\n cache.splice(index, 1);\n }\n };\n /**\n * Dispose the current allocated resources\n */\n InternalTexture.prototype.dispose = function () {\n if (!this._webGLTexture) {\n return;\n }\n this._references--;\n if (this._references === 0) {\n this._engine._releaseTexture(this);\n this._webGLTexture = null;\n this.previous = null;\n this.next = null;\n }\n };\n /**\n * The source of the texture data is unknown\n */\n InternalTexture.DATASOURCE_UNKNOWN = 0;\n /**\n * Texture data comes from an URL\n */\n InternalTexture.DATASOURCE_URL = 1;\n /**\n * Texture data is only used for temporary storage\n */\n InternalTexture.DATASOURCE_TEMP = 2;\n /**\n * Texture data comes from raw data (ArrayBuffer)\n */\n InternalTexture.DATASOURCE_RAW = 3;\n /**\n * Texture content is dynamic (video or dynamic texture)\n */\n InternalTexture.DATASOURCE_DYNAMIC = 4;\n /**\n * Texture content is generated by rendering to it\n */\n InternalTexture.DATASOURCE_RENDERTARGET = 5;\n /**\n * Texture content is part of a multi render target process\n */\n InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;\n /**\n * Texture data comes from a cube data file\n */\n InternalTexture.DATASOURCE_CUBE = 7;\n /**\n * Texture data comes from a raw cube data\n */\n InternalTexture.DATASOURCE_CUBERAW = 8;\n /**\n * Texture data come from a prefiltered cube data file\n */\n InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;\n /**\n * Texture content is raw 3D data\n */\n InternalTexture.DATASOURCE_RAW3D = 10;\n /**\n * Texture content is a depth texture\n */\n InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;\n /**\n * Texture data comes from a raw cube data encoded with RGBD\n */\n InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;\n return InternalTexture;\n }());\n BABYLON.InternalTexture = InternalTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.internalTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var BaseTexture = /** @class */ (function () {\n function BaseTexture(scene) {\n this._hasAlpha = false;\n this.getAlphaFromRGB = false;\n this.level = 1;\n this.coordinatesIndex = 0;\n this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;\n this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;\n this.isCube = false;\n this.is3D = false;\n this.gammaSpace = true;\n this.invertZ = false;\n this.lodLevelInAlpha = false;\n this.isRenderTarget = false;\n this.animations = new Array();\n /**\n * An event triggered when the texture is disposed.\n */\n this.onDisposeObservable = new BABYLON.Observable();\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;\n this._cachedSize = BABYLON.Size.Zero();\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n if (this._scene) {\n this._scene.textures.push(this);\n }\n this._uid = null;\n }\n Object.defineProperty(BaseTexture.prototype, \"hasAlpha\", {\n get: function () {\n return this._hasAlpha;\n },\n set: function (value) {\n if (this._hasAlpha === value) {\n return;\n }\n this._hasAlpha = value;\n if (this._scene) {\n this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"coordinatesMode\", {\n get: function () {\n return this._coordinatesMode;\n },\n /**\n * How a texture is mapped.\n *\n * | Value | Type | Description |\n * | ----- | ----------------------------------- | ----------- |\n * | 0 | EXPLICIT_MODE | |\n * | 1 | SPHERICAL_MODE | |\n * | 2 | PLANAR_MODE | |\n * | 3 | CUBIC_MODE | |\n * | 4 | PROJECTION_MODE | |\n * | 5 | SKYBOX_MODE | |\n * | 6 | INVCUBIC_MODE | |\n * | 7 | EQUIRECTANGULAR_MODE | |\n * | 8 | FIXED_EQUIRECTANGULAR_MODE | |\n * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |\n */\n set: function (value) {\n if (this._coordinatesMode === value) {\n return;\n }\n this._coordinatesMode = value;\n if (this._scene) {\n this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"isRGBD\", {\n /**\n * Gets whether or not the texture contains RGBD data.\n */\n get: function () {\n return this._texture != null && this._texture._isRGBD;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"lodGenerationOffset\", {\n get: function () {\n if (this._texture)\n return this._texture._lodGenerationOffset;\n return 0.0;\n },\n set: function (value) {\n if (this._texture)\n this._texture._lodGenerationOffset = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"lodGenerationScale\", {\n get: function () {\n if (this._texture)\n return this._texture._lodGenerationScale;\n return 0.0;\n },\n set: function (value) {\n if (this._texture)\n this._texture._lodGenerationScale = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"uid\", {\n get: function () {\n if (!this._uid) {\n this._uid = BABYLON.Tools.RandomId();\n }\n return this._uid;\n },\n enumerable: true,\n configurable: true\n });\n BaseTexture.prototype.toString = function () {\n return this.name;\n };\n BaseTexture.prototype.getClassName = function () {\n return \"BaseTexture\";\n };\n Object.defineProperty(BaseTexture.prototype, \"onDispose\", {\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"isBlocking\", {\n get: function () {\n return true;\n },\n enumerable: true,\n configurable: true\n });\n BaseTexture.prototype.getScene = function () {\n return this._scene;\n };\n BaseTexture.prototype.getTextureMatrix = function () {\n return BABYLON.Matrix.IdentityReadOnly;\n };\n BaseTexture.prototype.getReflectionTextureMatrix = function () {\n return BABYLON.Matrix.IdentityReadOnly;\n };\n BaseTexture.prototype.getInternalTexture = function () {\n return this._texture;\n };\n BaseTexture.prototype.isReadyOrNotBlocking = function () {\n return !this.isBlocking || this.isReady();\n };\n BaseTexture.prototype.isReady = function () {\n if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {\n this.delayLoad();\n return false;\n }\n if (this._texture) {\n return this._texture.isReady;\n }\n return false;\n };\n BaseTexture.prototype.getSize = function () {\n if (this._texture) {\n if (this._texture.width) {\n this._cachedSize.width = this._texture.width;\n this._cachedSize.height = this._texture.height;\n return this._cachedSize;\n }\n if (this._texture._size) {\n this._cachedSize.width = this._texture._size;\n this._cachedSize.height = this._texture._size;\n return this._cachedSize;\n }\n }\n return this._cachedSize;\n };\n BaseTexture.prototype.getBaseSize = function () {\n if (!this.isReady() || !this._texture)\n return BABYLON.Size.Zero();\n if (this._texture._size) {\n return new BABYLON.Size(this._texture._size, this._texture._size);\n }\n return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);\n };\n BaseTexture.prototype.scale = function (ratio) {\n };\n Object.defineProperty(BaseTexture.prototype, \"canRescale\", {\n get: function () {\n return false;\n },\n enumerable: true,\n configurable: true\n });\n BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {\n if (!this._scene) {\n return null;\n }\n var texturesCache = this._scene.getEngine().getLoadedTexturesCache();\n for (var index = 0; index < texturesCache.length; index++) {\n var texturesCacheEntry = texturesCache[index];\n if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {\n if (!sampling || sampling === texturesCacheEntry.samplingMode) {\n texturesCacheEntry.incrementReferences();\n return texturesCacheEntry;\n }\n }\n }\n return null;\n };\n BaseTexture.prototype._rebuild = function () {\n };\n BaseTexture.prototype.delayLoad = function () {\n };\n BaseTexture.prototype.clone = function () {\n return null;\n };\n Object.defineProperty(BaseTexture.prototype, \"textureType\", {\n get: function () {\n if (!this._texture) {\n return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"textureFormat\", {\n get: function () {\n if (!this._texture) {\n return BABYLON.Engine.TEXTUREFORMAT_RGBA;\n }\n return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.\n * This will returns an RGBA array buffer containing either in values (0-255) or\n * float values (0-1) depending of the underlying buffer type.\n * @param faceIndex The face of the texture to read (in case of cube texture)\n * @param level The LOD level of the texture to read (in case of Mip Maps)\n * @returns The Array buffer containing the pixels data.\n */\n BaseTexture.prototype.readPixels = function (faceIndex, level) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (level === void 0) { level = 0; }\n if (!this._texture) {\n return null;\n }\n var size = this.getSize();\n var width = size.width;\n var height = size.height;\n var scene = this.getScene();\n if (!scene) {\n return null;\n }\n var engine = scene.getEngine();\n if (level != 0) {\n width = width / Math.pow(2, level);\n height = height / Math.pow(2, level);\n width = Math.round(width);\n height = Math.round(height);\n }\n if (this._texture.isCube) {\n return engine._readTexturePixels(this._texture, width, height, faceIndex, level);\n }\n return engine._readTexturePixels(this._texture, width, height, -1, level);\n };\n BaseTexture.prototype.releaseInternalTexture = function () {\n if (this._texture) {\n this._texture.dispose();\n this._texture = null;\n }\n };\n Object.defineProperty(BaseTexture.prototype, \"sphericalPolynomial\", {\n get: function () {\n if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {\n return null;\n }\n if (!this._texture._sphericalPolynomial) {\n this._texture._sphericalPolynomial =\n BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);\n }\n return this._texture._sphericalPolynomial;\n },\n set: function (value) {\n if (this._texture) {\n this._texture._sphericalPolynomial = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"_lodTextureHigh\", {\n get: function () {\n if (this._texture) {\n return this._texture._lodTextureHigh;\n }\n return null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"_lodTextureMid\", {\n get: function () {\n if (this._texture) {\n return this._texture._lodTextureMid;\n }\n return null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"_lodTextureLow\", {\n get: function () {\n if (this._texture) {\n return this._texture._lodTextureLow;\n }\n return null;\n },\n enumerable: true,\n configurable: true\n });\n BaseTexture.prototype.dispose = function () {\n if (!this._scene) {\n return;\n }\n // Animations\n this._scene.stopAnimation(this);\n // Remove from scene\n this._scene._removePendingData(this);\n var index = this._scene.textures.indexOf(this);\n if (index >= 0) {\n this._scene.textures.splice(index, 1);\n }\n if (this._texture === undefined) {\n return;\n }\n // Release\n this.releaseInternalTexture();\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n };\n BaseTexture.prototype.serialize = function () {\n if (!this.name) {\n return null;\n }\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n // Animations\n BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);\n return serializationObject;\n };\n BaseTexture.WhenAllReady = function (textures, callback) {\n var numRemaining = textures.length;\n if (numRemaining === 0) {\n callback();\n return;\n }\n var _loop_1 = function () {\n texture = textures[i];\n if (texture.isReady()) {\n if (--numRemaining === 0) {\n callback();\n }\n }\n else {\n onLoadObservable = texture.onLoadObservable;\n var onLoadCallback_1 = function () {\n onLoadObservable.removeCallback(onLoadCallback_1);\n if (--numRemaining === 0) {\n callback();\n }\n };\n onLoadObservable.add(onLoadCallback_1);\n }\n };\n var texture, onLoadObservable;\n for (var i = 0; i < textures.length; i++) {\n _loop_1();\n }\n };\n BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"name\", void 0);\n __decorate([\n BABYLON.serialize(\"hasAlpha\")\n ], BaseTexture.prototype, \"_hasAlpha\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"getAlphaFromRGB\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"level\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"coordinatesIndex\", void 0);\n __decorate([\n BABYLON.serialize(\"coordinatesMode\")\n ], BaseTexture.prototype, \"_coordinatesMode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"wrapU\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"wrapV\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"wrapR\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"anisotropicFilteringLevel\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"isCube\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"is3D\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"gammaSpace\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"invertZ\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"lodLevelInAlpha\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"lodGenerationOffset\", null);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"lodGenerationScale\", null);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"isRenderTarget\", void 0);\n return BaseTexture;\n }());\n BABYLON.BaseTexture = BaseTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.baseTexture.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var Texture = /** @class */ (function (_super) {\n __extends(Texture, _super);\n function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {\n if (noMipmap === void 0) { noMipmap = false; }\n if (invertY === void 0) { invertY = true; }\n if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (buffer === void 0) { buffer = null; }\n if (deleteBuffer === void 0) { deleteBuffer = false; }\n var _this = _super.call(this, scene) || this;\n _this.uOffset = 0;\n _this.vOffset = 0;\n _this.uScale = 1.0;\n _this.vScale = 1.0;\n _this.uAng = 0;\n _this.vAng = 0;\n _this.wAng = 0;\n /**\n * Defines the center of rotation (U)\n */\n _this.uRotationCenter = 0.5;\n /**\n * Defines the center of rotation (V)\n */\n _this.vRotationCenter = 0.5;\n /**\n * Defines the center of rotation (W)\n */\n _this.wRotationCenter = 0.5;\n _this._isBlocking = true;\n _this.name = url || \"\";\n _this.url = url;\n _this._noMipmap = noMipmap;\n _this._invertY = invertY;\n _this._samplingMode = samplingMode;\n _this._buffer = buffer;\n _this._deleteBuffer = deleteBuffer;\n if (format) {\n _this._format = format;\n }\n scene = _this.getScene();\n if (!scene) {\n return _this;\n }\n scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);\n var load = function () {\n if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {\n _this.onLoadObservable.notifyObservers(_this);\n }\n if (onLoad) {\n onLoad();\n }\n if (!_this.isBlocking && scene) {\n scene.resetCachedMaterial();\n }\n };\n if (!_this.url) {\n _this._delayedOnLoad = load;\n _this._delayedOnError = onError;\n return _this;\n }\n _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);\n if (!_this._texture) {\n if (!scene.useDelayedTextureLoading) {\n _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);\n if (deleteBuffer) {\n delete _this._buffer;\n }\n }\n else {\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n _this._delayedOnLoad = load;\n _this._delayedOnError = onError;\n }\n }\n else {\n if (_this._texture.isReady) {\n BABYLON.Tools.SetImmediate(function () { return load(); });\n }\n else {\n _this._texture.onLoadedObservable.add(load);\n }\n }\n return _this;\n }\n Object.defineProperty(Texture.prototype, \"noMipmap\", {\n get: function () {\n return this._noMipmap;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Texture.prototype, \"isBlocking\", {\n get: function () {\n return this._isBlocking;\n },\n set: function (value) {\n this._isBlocking = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Texture.prototype, \"samplingMode\", {\n get: function () {\n return this._samplingMode;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Update the url (and optional buffer) of this texture if url was null during construction.\n * @param url the url of the texture\n * @param buffer the buffer of the texture (defaults to null)\n */\n Texture.prototype.updateURL = function (url, buffer) {\n if (buffer === void 0) { buffer = null; }\n if (this.url) {\n throw new Error(\"URL is already set\");\n }\n this.url = url;\n this._buffer = buffer;\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n this.delayLoad();\n };\n Texture.prototype.delayLoad = function () {\n if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {\n return;\n }\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;\n this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);\n if (!this._texture) {\n this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);\n if (this._deleteBuffer) {\n delete this._buffer;\n }\n }\n else {\n if (this._delayedOnLoad) {\n if (this._texture.isReady) {\n BABYLON.Tools.SetImmediate(this._delayedOnLoad);\n }\n else {\n this._texture.onLoadedObservable.add(this._delayedOnLoad);\n }\n }\n }\n this._delayedOnLoad = null;\n this._delayedOnError = null;\n };\n Texture.prototype.updateSamplingMode = function (samplingMode) {\n if (!this._texture) {\n return;\n }\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this._samplingMode = samplingMode;\n scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);\n };\n Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {\n x *= this.uScale;\n y *= this.vScale;\n x -= this.uRotationCenter * this.uScale;\n y -= this.vRotationCenter * this.vScale;\n z -= this.wRotationCenter;\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);\n t.x += this.uRotationCenter * this.uScale + this.uOffset;\n t.y += this.vRotationCenter * this.vScale + this.vOffset;\n t.z += this.wRotationCenter;\n };\n Texture.prototype.getTextureMatrix = function () {\n var _this = this;\n if (this.uOffset === this._cachedUOffset &&\n this.vOffset === this._cachedVOffset &&\n this.uScale === this._cachedUScale &&\n this.vScale === this._cachedVScale &&\n this.uAng === this._cachedUAng &&\n this.vAng === this._cachedVAng &&\n this.wAng === this._cachedWAng) {\n return this._cachedTextureMatrix;\n }\n this._cachedUOffset = this.uOffset;\n this._cachedVOffset = this.vOffset;\n this._cachedUScale = this.uScale;\n this._cachedVScale = this.vScale;\n this._cachedUAng = this.uAng;\n this._cachedVAng = this.vAng;\n this._cachedWAng = this.wAng;\n if (!this._cachedTextureMatrix) {\n this._cachedTextureMatrix = BABYLON.Matrix.Zero();\n this._rowGenerationMatrix = new BABYLON.Matrix();\n this._t0 = BABYLON.Vector3.Zero();\n this._t1 = BABYLON.Vector3.Zero();\n this._t2 = BABYLON.Vector3.Zero();\n }\n BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);\n this._prepareRowForTextureGeneration(0, 0, 0, this._t0);\n this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);\n this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);\n this._t1.subtractInPlace(this._t0);\n this._t2.subtractInPlace(this._t0);\n BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);\n this._cachedTextureMatrix.m[0] = this._t1.x;\n this._cachedTextureMatrix.m[1] = this._t1.y;\n this._cachedTextureMatrix.m[2] = this._t1.z;\n this._cachedTextureMatrix.m[4] = this._t2.x;\n this._cachedTextureMatrix.m[5] = this._t2.y;\n this._cachedTextureMatrix.m[6] = this._t2.z;\n this._cachedTextureMatrix.m[8] = this._t0.x;\n this._cachedTextureMatrix.m[9] = this._t0.y;\n this._cachedTextureMatrix.m[10] = this._t0.z;\n var scene = this.getScene();\n if (!scene) {\n return this._cachedTextureMatrix;\n }\n scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {\n return mat.hasTexture(_this);\n });\n return this._cachedTextureMatrix;\n };\n Texture.prototype.getReflectionTextureMatrix = function () {\n var _this = this;\n var scene = this.getScene();\n if (!scene) {\n return this._cachedTextureMatrix;\n }\n if (this.uOffset === this._cachedUOffset &&\n this.vOffset === this._cachedVOffset &&\n this.uScale === this._cachedUScale &&\n this.vScale === this._cachedVScale &&\n this.coordinatesMode === this._cachedCoordinatesMode) {\n if (this.coordinatesMode === Texture.PROJECTION_MODE) {\n if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {\n return this._cachedTextureMatrix;\n }\n }\n else {\n return this._cachedTextureMatrix;\n }\n }\n if (!this._cachedTextureMatrix) {\n this._cachedTextureMatrix = BABYLON.Matrix.Zero();\n }\n if (!this._projectionModeMatrix) {\n this._projectionModeMatrix = BABYLON.Matrix.Zero();\n }\n this._cachedUOffset = this.uOffset;\n this._cachedVOffset = this.vOffset;\n this._cachedUScale = this.uScale;\n this._cachedVScale = this.vScale;\n this._cachedCoordinatesMode = this.coordinatesMode;\n switch (this.coordinatesMode) {\n case Texture.PLANAR_MODE:\n BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);\n this._cachedTextureMatrix[0] = this.uScale;\n this._cachedTextureMatrix[5] = this.vScale;\n this._cachedTextureMatrix[12] = this.uOffset;\n this._cachedTextureMatrix[13] = this.vOffset;\n break;\n case Texture.PROJECTION_MODE:\n BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);\n this._projectionModeMatrix.m[0] = 0.5;\n this._projectionModeMatrix.m[5] = -0.5;\n this._projectionModeMatrix.m[10] = 0.0;\n this._projectionModeMatrix.m[12] = 0.5;\n this._projectionModeMatrix.m[13] = 0.5;\n this._projectionModeMatrix.m[14] = 1.0;\n this._projectionModeMatrix.m[15] = 1.0;\n var projectionMatrix = scene.getProjectionMatrix();\n this._cachedProjectionMatrixId = projectionMatrix.updateFlag;\n projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);\n break;\n default:\n BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);\n break;\n }\n scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {\n return (mat.getActiveTextures().indexOf(_this) !== -1);\n });\n return this._cachedTextureMatrix;\n };\n Texture.prototype.clone = function () {\n var _this = this;\n return BABYLON.SerializationHelper.Clone(function () {\n return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);\n }, this);\n };\n Object.defineProperty(Texture.prototype, \"onLoadObservable\", {\n get: function () {\n if (!this._onLoadObservable) {\n this._onLoadObservable = new BABYLON.Observable();\n }\n return this._onLoadObservable;\n },\n enumerable: true,\n configurable: true\n });\n Texture.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n if (typeof this._buffer === \"string\" && this._buffer.substr(0, 5) === \"data:\") {\n serializationObject.base64String = this._buffer;\n serializationObject.name = serializationObject.name.replace(\"data:\", \"\");\n }\n serializationObject.invertY = this._invertY;\n serializationObject.samplingMode = this.samplingMode;\n return serializationObject;\n };\n Texture.prototype.getClassName = function () {\n return \"Texture\";\n };\n Texture.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n if (this._onLoadObservable) {\n this._onLoadObservable.clear();\n this._onLoadObservable = null;\n }\n this._delayedOnLoad = null;\n this._delayedOnError = null;\n };\n // Statics\n Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {\n if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }\n return new Texture(\"data:\" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);\n };\n Texture.Parse = function (parsedTexture, scene, rootUrl) {\n if (parsedTexture.customType) {\n var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);\n // Update Sampling Mode\n var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);\n if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {\n if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {\n parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);\n }\n }\n return parsedCustomTexture;\n }\n if (parsedTexture.isCube) {\n return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);\n }\n if (!parsedTexture.name && !parsedTexture.isRenderTarget) {\n return null;\n }\n var texture = BABYLON.SerializationHelper.Parse(function () {\n var generateMipMaps = true;\n if (parsedTexture.noMipmap) {\n generateMipMaps = false;\n }\n if (parsedTexture.mirrorPlane) {\n var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);\n mirrorTexture._waitingRenderList = parsedTexture.renderList;\n mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);\n return mirrorTexture;\n }\n else if (parsedTexture.isRenderTarget) {\n var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);\n renderTargetTexture._waitingRenderList = parsedTexture.renderList;\n return renderTargetTexture;\n }\n else {\n var texture;\n if (parsedTexture.base64String) {\n texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);\n }\n else {\n var url = rootUrl + parsedTexture.name;\n if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {\n url = parsedTexture.url;\n }\n texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);\n }\n return texture;\n }\n }, parsedTexture, scene);\n // Update Sampling Mode\n if (parsedTexture.samplingMode) {\n var sampling = parsedTexture.samplingMode;\n if (texture._samplingMode !== sampling) {\n texture.updateSamplingMode(sampling);\n }\n }\n // Animations\n if (parsedTexture.animations) {\n for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {\n var parsedAnimation = parsedTexture.animations[animationIndex];\n texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n }\n return texture;\n };\n Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {\n if (deleteBuffer === void 0) { deleteBuffer = false; }\n if (noMipmap === void 0) { noMipmap = false; }\n if (invertY === void 0) { invertY = true; }\n if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }\n if (name.substr(0, 5) !== \"data:\") {\n name = \"data:\" + name;\n }\n return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);\n };\n // Constants\n Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear\n Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;\n Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest\n Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;\n Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear\n Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;\n Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;\n Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;\n Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;\n Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;\n Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;\n Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;\n Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;\n Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;\n Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;\n Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;\n Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;\n Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;\n Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;\n Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;\n Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;\n Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;\n Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;\n Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;\n Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;\n Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;\n Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;\n /**\n * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file\n */\n Texture.UseSerializedUrlIfAny = false;\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"url\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"uOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"vOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"uScale\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"vScale\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"uAng\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"vAng\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"wAng\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"uRotationCenter\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"vRotationCenter\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"wRotationCenter\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"isBlocking\", null);\n return Texture;\n }(BABYLON.BaseTexture));\n BABYLON.Texture = Texture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.texture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * @hidden\n **/\n var _InstancesBatch = /** @class */ (function () {\n function _InstancesBatch() {\n this.mustReturn = false;\n this.visibleInstances = new Array();\n this.renderSelf = new Array();\n }\n return _InstancesBatch;\n }());\n BABYLON._InstancesBatch = _InstancesBatch;\n var Mesh = /** @class */ (function (_super) {\n __extends(Mesh, _super);\n /**\n * @constructor\n * @param {string} name The value used by scene.getMeshByName() to do a lookup.\n * @param {Scene} scene The scene to add this mesh to.\n * @param {Node} parent The parent of this mesh, if it has one\n * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.\n * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.\n * When false, achieved by calling a clone(), also passing False.\n * This will make creation of children, recursive.\n * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.\n */\n function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {\n if (scene === void 0) { scene = null; }\n if (parent === void 0) { parent = null; }\n if (source === void 0) { source = null; }\n if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }\n var _this = _super.call(this, name, scene) || this;\n // Events \n /**\n * An event triggered before rendering the mesh\n */\n _this.onBeforeRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered after rendering the mesh\n */\n _this.onAfterRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered before drawing the mesh\n */\n _this.onBeforeDrawObservable = new BABYLON.Observable();\n // Members\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;\n _this.instances = new Array();\n _this._LODLevels = new Array();\n _this._visibleInstances = {};\n _this._renderIdForInstances = new Array();\n _this._batchCache = new _InstancesBatch();\n _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances\n // Use by builder only to know what orientation were the mesh build in.\n _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;\n _this.overrideMaterialSideOrientation = null;\n _this._areNormalsFrozen = false; // Will be used by ribbons mainly\n // Will be used to save a source mesh reference, If any\n _this._source = null;\n scene = _this.getScene();\n if (source) {\n // Geometry\n if (source._geometry) {\n source._geometry.applyToMesh(_this);\n }\n // Deep copy\n BABYLON.Tools.DeepCopy(source, _this, [\"name\", \"material\", \"skeleton\", \"instances\", \"parent\", \"uniqueId\",\n \"source\", \"metadata\", \"hasLODLevels\", \"geometry\", \"isBlocked\", \"areNormalsFrozen\"], [\"_poseMatrix\"]);\n // Source mesh\n _this._source = source;\n // Metadata\n if (source.metadata && source.metadata.clone) {\n _this.metadata = source.metadata.clone();\n }\n else {\n _this.metadata = source.metadata;\n }\n // Tags\n if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {\n BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));\n }\n // Parent\n _this.parent = source.parent;\n // Pivot\n _this.setPivotMatrix(source.getPivotMatrix());\n _this.id = name + \".\" + source.id;\n // Material\n _this.material = source.material;\n var index;\n if (!doNotCloneChildren) {\n // Children\n var directDescendants = source.getDescendants(true);\n for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {\n var child = directDescendants[index_1];\n if (child.clone) {\n child.clone(name + \".\" + child.name, _this);\n }\n }\n }\n // Physics clone \n var physicsEngine = _this.getScene().getPhysicsEngine();\n if (clonePhysicsImpostor && physicsEngine) {\n var impostor = physicsEngine.getImpostorForPhysicsObject(source);\n if (impostor) {\n _this.physicsImpostor = impostor.clone(_this);\n }\n }\n // Particles\n for (index = 0; index < scene.particleSystems.length; index++) {\n var system = scene.particleSystems[index];\n if (system.emitter === source) {\n system.clone(system.name, _this);\n }\n }\n _this.refreshBoundingInfo();\n _this.computeWorldMatrix(true);\n }\n // Parent\n if (parent !== null) {\n _this.parent = parent;\n }\n return _this;\n }\n Object.defineProperty(Mesh, \"FRONTSIDE\", {\n /**\n * Mesh side orientation : usually the external or front surface\n */\n get: function () {\n return Mesh._FRONTSIDE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"BACKSIDE\", {\n /**\n * Mesh side orientation : usually the internal or back surface\n */\n get: function () {\n return Mesh._BACKSIDE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"DOUBLESIDE\", {\n /**\n * Mesh side orientation : both internal and external or front and back surfaces\n */\n get: function () {\n return Mesh._DOUBLESIDE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"DEFAULTSIDE\", {\n /**\n * Mesh side orientation : by default, `FRONTSIDE`\n */\n get: function () {\n return Mesh._DEFAULTSIDE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"NO_CAP\", {\n /**\n * Mesh cap setting : no cap\n */\n get: function () {\n return Mesh._NO_CAP;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"CAP_START\", {\n /**\n * Mesh cap setting : one cap at the beginning of the mesh\n */\n get: function () {\n return Mesh._CAP_START;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"CAP_END\", {\n /**\n * Mesh cap setting : one cap at the end of the mesh\n */\n get: function () {\n return Mesh._CAP_END;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"CAP_ALL\", {\n /**\n * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh\n */\n get: function () {\n return Mesh._CAP_ALL;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh.prototype, \"onBeforeDraw\", {\n set: function (callback) {\n if (this._onBeforeDrawObserver) {\n this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);\n }\n this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh.prototype, \"morphTargetManager\", {\n get: function () {\n return this._morphTargetManager;\n },\n set: function (value) {\n if (this._morphTargetManager === value) {\n return;\n }\n this._morphTargetManager = value;\n this._syncGeometryWithMorphTargetManager();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh.prototype, \"source\", {\n get: function () {\n return this._source;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh.prototype, \"isUnIndexed\", {\n get: function () {\n return this._unIndexed;\n },\n set: function (value) {\n if (this._unIndexed !== value) {\n this._unIndexed = value;\n this._markSubMeshesAsAttributesDirty();\n }\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n /**\n * Returns the string \"Mesh\".\n */\n Mesh.prototype.getClassName = function () {\n return \"Mesh\";\n };\n /**\n * Returns a string.\n * @param {boolean} fullDetails - support for multiple levels of logging within scene loading\n */\n Mesh.prototype.toString = function (fullDetails) {\n var ret = _super.prototype.toString.call(this, fullDetails);\n ret += \", n vertices: \" + this.getTotalVertices();\n ret += \", parent: \" + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : \"NONE\"));\n if (this.animations) {\n for (var i = 0; i < this.animations.length; i++) {\n ret += \", animation[0]: \" + this.animations[i].toString(fullDetails);\n }\n }\n if (fullDetails) {\n if (this._geometry) {\n var ib = this.getIndices();\n var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (vb && ib) {\n ret += \", flat shading: \" + (vb.length / 3 === ib.length ? \"YES\" : \"NO\");\n }\n }\n else {\n ret += \", flat shading: UNKNOWN\";\n }\n }\n return ret;\n };\n Mesh.prototype._unBindEffect = function () {\n _super.prototype._unBindEffect.call(this);\n for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {\n var instance = _a[_i];\n instance._unBindEffect();\n }\n };\n Object.defineProperty(Mesh.prototype, \"hasLODLevels\", {\n /**\n * True if the mesh has some Levels Of Details (LOD).\n * Returns a boolean.\n */\n get: function () {\n return this._LODLevels.length > 0;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh\n * @returns an array of {BABYLON.MeshLODLevel}\n */\n Mesh.prototype.getLODLevels = function () {\n return this._LODLevels;\n };\n Mesh.prototype._sortLODLevels = function () {\n this._LODLevels.sort(function (a, b) {\n if (a.distance < b.distance) {\n return 1;\n }\n if (a.distance > b.distance) {\n return -1;\n }\n return 0;\n });\n };\n /**\n * Add a mesh as LOD level triggered at the given distance.\n * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD\n * @param distance The distance from the center of the object to show this level\n * @param mesh The mesh to be added as LOD level (can be null)\n * @return This mesh (for chaining)\n */\n Mesh.prototype.addLODLevel = function (distance, mesh) {\n if (mesh && mesh._masterMesh) {\n BABYLON.Tools.Warn(\"You cannot use a mesh as LOD level twice\");\n return this;\n }\n var level = new BABYLON.MeshLODLevel(distance, mesh);\n this._LODLevels.push(level);\n if (mesh) {\n mesh._masterMesh = this;\n }\n this._sortLODLevels();\n return this;\n };\n /**\n * Returns the LOD level mesh at the passed distance or null if not found.\n * It is related to the method `addLODLevel(distance, mesh)`.\n * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD\n * Returns an object Mesh or `null`.\n */\n Mesh.prototype.getLODLevelAtDistance = function (distance) {\n for (var index = 0; index < this._LODLevels.length; index++) {\n var level = this._LODLevels[index];\n if (level.distance === distance) {\n return level.mesh;\n }\n }\n return null;\n };\n /**\n * Remove a mesh from the LOD array\n * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD\n * @param {Mesh} mesh The mesh to be removed.\n * @return {Mesh} This mesh (for chaining)\n */\n Mesh.prototype.removeLODLevel = function (mesh) {\n for (var index = 0; index < this._LODLevels.length; index++) {\n if (this._LODLevels[index].mesh === mesh) {\n this._LODLevels.splice(index, 1);\n if (mesh) {\n mesh._masterMesh = null;\n }\n }\n }\n this._sortLODLevels();\n return this;\n };\n /**\n * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.\n * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod\n */\n Mesh.prototype.getLOD = function (camera, boundingSphere) {\n if (!this._LODLevels || this._LODLevels.length === 0) {\n return this;\n }\n var bSphere;\n if (boundingSphere) {\n bSphere = boundingSphere;\n }\n else {\n var boundingInfo = this.getBoundingInfo();\n bSphere = boundingInfo.boundingSphere;\n }\n var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();\n if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {\n if (this.onLODLevelSelection) {\n this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);\n }\n return this;\n }\n for (var index = 0; index < this._LODLevels.length; index++) {\n var level = this._LODLevels[index];\n if (level.distance < distanceToCamera) {\n if (level.mesh) {\n level.mesh._preActivate();\n level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);\n }\n if (this.onLODLevelSelection) {\n this.onLODLevelSelection(distanceToCamera, this, level.mesh);\n }\n return level.mesh;\n }\n }\n if (this.onLODLevelSelection) {\n this.onLODLevelSelection(distanceToCamera, this, this);\n }\n return this;\n };\n Object.defineProperty(Mesh.prototype, \"geometry\", {\n /**\n * Returns the mesh internal Geometry object.\n */\n get: function () {\n return this._geometry;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.\n */\n Mesh.prototype.getTotalVertices = function () {\n if (this._geometry === null || this._geometry === undefined) {\n return 0;\n }\n return this._geometry.getTotalVertices();\n };\n /**\n * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).\n * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.\n * You can force the copy with forceCopy === true\n * Returns null if the mesh has no geometry or no vertex buffer.\n * Possible `kind` values :\n * - BABYLON.VertexBuffer.PositionKind\n * - BABYLON.VertexBuffer.UVKind\n * - BABYLON.VertexBuffer.UV2Kind\n * - BABYLON.VertexBuffer.UV3Kind\n * - BABYLON.VertexBuffer.UV4Kind\n * - BABYLON.VertexBuffer.UV5Kind\n * - BABYLON.VertexBuffer.UV6Kind\n * - BABYLON.VertexBuffer.ColorKind\n * - BABYLON.VertexBuffer.MatricesIndicesKind\n * - BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * - BABYLON.VertexBuffer.MatricesWeightsKind\n * - BABYLON.VertexBuffer.MatricesWeightsExtraKind\n */\n Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {\n if (!this._geometry) {\n return null;\n }\n return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);\n };\n /**\n * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.\n * Returns `null` if the mesh has no geometry.\n * Possible `kind` values :\n * - BABYLON.VertexBuffer.PositionKind\n * - BABYLON.VertexBuffer.UVKind\n * - BABYLON.VertexBuffer.UV2Kind\n * - BABYLON.VertexBuffer.UV3Kind\n * - BABYLON.VertexBuffer.UV4Kind\n * - BABYLON.VertexBuffer.UV5Kind\n * - BABYLON.VertexBuffer.UV6Kind\n * - BABYLON.VertexBuffer.ColorKind\n * - BABYLON.VertexBuffer.MatricesIndicesKind\n * - BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * - BABYLON.VertexBuffer.MatricesWeightsKind\n * - BABYLON.VertexBuffer.MatricesWeightsExtraKind\n */\n Mesh.prototype.getVertexBuffer = function (kind) {\n if (!this._geometry) {\n return null;\n }\n return this._geometry.getVertexBuffer(kind);\n };\n Mesh.prototype.isVerticesDataPresent = function (kind) {\n if (!this._geometry) {\n if (this._delayInfo) {\n return this._delayInfo.indexOf(kind) !== -1;\n }\n return false;\n }\n return this._geometry.isVerticesDataPresent(kind);\n };\n /**\n * Returns a boolean defining if the vertex data for the requested `kind` is updatable.\n * Possible `kind` values :\n * - BABYLON.VertexBuffer.PositionKind\n * - BABYLON.VertexBuffer.UVKind\n * - BABYLON.VertexBuffer.UV2Kind\n * - BABYLON.VertexBuffer.UV3Kind\n * - BABYLON.VertexBuffer.UV4Kind\n * - BABYLON.VertexBuffer.UV5Kind\n * - BABYLON.VertexBuffer.UV6Kind\n * - BABYLON.VertexBuffer.ColorKind\n * - BABYLON.VertexBuffer.MatricesIndicesKind\n * - BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * - BABYLON.VertexBuffer.MatricesWeightsKind\n * - BABYLON.VertexBuffer.MatricesWeightsExtraKind\n */\n Mesh.prototype.isVertexBufferUpdatable = function (kind) {\n if (!this._geometry) {\n if (this._delayInfo) {\n return this._delayInfo.indexOf(kind) !== -1;\n }\n return false;\n }\n return this._geometry.isVertexBufferUpdatable(kind);\n };\n /**\n * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.\n * Possible `kind` values :\n * - BABYLON.VertexBuffer.PositionKind\n * - BABYLON.VertexBuffer.UVKind\n * - BABYLON.VertexBuffer.UV2Kind\n * - BABYLON.VertexBuffer.UV3Kind\n * - BABYLON.VertexBuffer.UV4Kind\n * - BABYLON.VertexBuffer.UV5Kind\n * - BABYLON.VertexBuffer.UV6Kind\n * - BABYLON.VertexBuffer.ColorKind\n * - BABYLON.VertexBuffer.MatricesIndicesKind\n * - BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * - BABYLON.VertexBuffer.MatricesWeightsKind\n * - BABYLON.VertexBuffer.MatricesWeightsExtraKind\n */\n Mesh.prototype.getVerticesDataKinds = function () {\n if (!this._geometry) {\n var result = new Array();\n if (this._delayInfo) {\n this._delayInfo.forEach(function (kind, index, array) {\n result.push(kind);\n });\n }\n return result;\n }\n return this._geometry.getVerticesDataKinds();\n };\n /**\n * Returns a positive integer : the total number of indices in this mesh geometry.\n * Returns zero if the mesh has no geometry.\n */\n Mesh.prototype.getTotalIndices = function () {\n if (!this._geometry) {\n return 0;\n }\n return this._geometry.getTotalIndices();\n };\n /**\n * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.\n * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.\n * Returns an empty array if the mesh has no geometry.\n */\n Mesh.prototype.getIndices = function (copyWhenShared) {\n if (!this._geometry) {\n return [];\n }\n return this._geometry.getIndices(copyWhenShared);\n };\n Object.defineProperty(Mesh.prototype, \"isBlocked\", {\n get: function () {\n return this._masterMesh !== null && this._masterMesh !== undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Determine if the current mesh is ready to be rendered\n * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)\n * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)\n * @returns true if all associated assets are ready (material, textures, shaders)\n */\n Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {\n if (completeCheck === void 0) { completeCheck = false; }\n if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }\n if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {\n return false;\n }\n if (!_super.prototype.isReady.call(this, completeCheck)) {\n return false;\n }\n if (!this.subMeshes || this.subMeshes.length === 0) {\n return true;\n }\n if (!completeCheck) {\n return true;\n }\n var engine = this.getEngine();\n var scene = this.getScene();\n var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;\n this.computeWorldMatrix();\n var mat = this.material || scene.defaultMaterial;\n if (mat) {\n if (mat.storeEffectOnSubMeshes) {\n for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n var effectiveMaterial = subMesh.getMaterial();\n if (effectiveMaterial) {\n if (effectiveMaterial.storeEffectOnSubMeshes) {\n if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n else {\n if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n }\n }\n else {\n if (!mat.isReady(this, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n // Shadows\n for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {\n var light = _c[_b];\n var generator = light.getShadowGenerator();\n if (generator) {\n for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {\n var subMesh = _e[_d];\n if (!generator.isReady(subMesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n }\n // LOD\n for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {\n var lod = _g[_f];\n if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {\n return false;\n }\n }\n return true;\n };\n Object.defineProperty(Mesh.prototype, \"areNormalsFrozen\", {\n /**\n * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.\n * This property is pertinent only for updatable parametric shapes.\n */\n get: function () {\n return this._areNormalsFrozen;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.\n * It has no effect at all on other shapes.\n * It prevents the mesh normals from being recomputed on next `positions` array update.\n * Returns the Mesh.\n */\n Mesh.prototype.freezeNormals = function () {\n this._areNormalsFrozen = true;\n return this;\n };\n /**\n * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.\n * It has no effect at all on other shapes.\n * It reactivates the mesh normals computation if it was previously frozen.\n * Returns the Mesh.\n */\n Mesh.prototype.unfreezeNormals = function () {\n this._areNormalsFrozen = false;\n return this;\n };\n Object.defineProperty(Mesh.prototype, \"overridenInstanceCount\", {\n /**\n * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs\n */\n set: function (count) {\n this._overridenInstanceCount = count;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n Mesh.prototype._preActivate = function () {\n var sceneRenderId = this.getScene().getRenderId();\n if (this._preActivateId === sceneRenderId) {\n return this;\n }\n this._preActivateId = sceneRenderId;\n this._visibleInstances = null;\n return this;\n };\n Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {\n if (this._visibleInstances) {\n this._visibleInstances.intermediateDefaultRenderId = renderId;\n }\n return this;\n };\n Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {\n if (!this._visibleInstances) {\n this._visibleInstances = {};\n this._visibleInstances.defaultRenderId = renderId;\n this._visibleInstances.selfDefaultRenderId = this._renderId;\n }\n if (!this._visibleInstances[renderId]) {\n this._visibleInstances[renderId] = new Array();\n }\n this._visibleInstances[renderId].push(instance);\n return this;\n };\n /**\n * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.\n * This means the mesh underlying bounding box and sphere are recomputed.\n * Returns the Mesh.\n */\n Mesh.prototype.refreshBoundingInfo = function () {\n return this._refreshBoundingInfo(false);\n };\n Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {\n if (this._boundingInfo && this._boundingInfo.isLocked) {\n return this;\n }\n var data = this._getPositionData(applySkeleton);\n if (data) {\n var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());\n this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);\n }\n if (this.subMeshes) {\n for (var index = 0; index < this.subMeshes.length; index++) {\n this.subMeshes[index].refreshBoundingInfo();\n }\n }\n this._updateBoundingInfo();\n return this;\n };\n Mesh.prototype._getPositionData = function (applySkeleton) {\n var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (data && applySkeleton && this.skeleton) {\n data = BABYLON.Tools.Slice(data);\n var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);\n var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (matricesWeightsData && matricesIndicesData) {\n var needExtras = this.numBoneInfluencers > 4;\n var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;\n var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;\n var skeletonMatrices = this.skeleton.getTransformMatrices(this);\n var tempVector = BABYLON.Tmp.Vector3[0];\n var finalMatrix = BABYLON.Tmp.Matrix[0];\n var tempMatrix = BABYLON.Tmp.Matrix[1];\n var matWeightIdx = 0;\n for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {\n finalMatrix.reset();\n var inf;\n var weight;\n for (inf = 0; inf < 4; inf++) {\n weight = matricesWeightsData[matWeightIdx + inf];\n if (weight > 0) {\n BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);\n finalMatrix.addToSelf(tempMatrix);\n }\n }\n if (needExtras) {\n for (inf = 0; inf < 4; inf++) {\n weight = matricesWeightsExtraData[matWeightIdx + inf];\n if (weight > 0) {\n BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);\n finalMatrix.addToSelf(tempMatrix);\n }\n }\n }\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);\n tempVector.toArray(data, index);\n }\n }\n }\n return data;\n };\n Mesh.prototype._createGlobalSubMesh = function (force) {\n var totalVertices = this.getTotalVertices();\n if (!totalVertices || !this.getIndices()) {\n return null;\n }\n // Check if we need to recreate the submeshes\n if (this.subMeshes && this.subMeshes.length > 0) {\n var ib = this.getIndices();\n if (!ib) {\n return null;\n }\n var totalIndices = ib.length;\n var needToRecreate = false;\n if (force) {\n needToRecreate = true;\n }\n else {\n for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {\n var submesh = _a[_i];\n if (submesh.indexStart + submesh.indexCount >= totalIndices) {\n needToRecreate = true;\n break;\n }\n if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {\n needToRecreate = true;\n break;\n }\n }\n }\n if (!needToRecreate) {\n return this.subMeshes[0];\n }\n }\n this.releaseSubMeshes();\n return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);\n };\n Mesh.prototype.subdivide = function (count) {\n if (count < 1) {\n return;\n }\n var totalIndices = this.getTotalIndices();\n var subdivisionSize = (totalIndices / count) | 0;\n var offset = 0;\n // Ensure that subdivisionSize is a multiple of 3\n while (subdivisionSize % 3 !== 0) {\n subdivisionSize++;\n }\n this.releaseSubMeshes();\n for (var index = 0; index < count; index++) {\n if (offset >= totalIndices) {\n break;\n }\n BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);\n offset += subdivisionSize;\n }\n this.synchronizeInstances();\n };\n Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {\n if (updatable === void 0) { updatable = false; }\n if (!this._geometry) {\n var vertexData = new BABYLON.VertexData();\n vertexData.set(data, kind);\n var scene = this.getScene();\n new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);\n }\n else {\n this._geometry.setVerticesData(kind, data, updatable, stride);\n }\n return this;\n };\n Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {\n if (updatable === void 0) { updatable = true; }\n var vb = this.getVertexBuffer(kind);\n if (!vb || vb.isUpdatable() === updatable) {\n return;\n }\n this.setVerticesData(kind, this.getVerticesData(kind), updatable);\n };\n /**\n * Sets the mesh VertexBuffer.\n * Returns the Mesh.\n */\n Mesh.prototype.setVerticesBuffer = function (buffer) {\n if (!this._geometry) {\n this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);\n }\n this._geometry.setVerticesBuffer(buffer);\n return this;\n };\n Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {\n if (!this._geometry) {\n return this;\n }\n if (!makeItUnique) {\n this._geometry.updateVerticesData(kind, data, updateExtends);\n }\n else {\n this.makeGeometryUnique();\n this.updateVerticesData(kind, data, updateExtends, false);\n }\n return this;\n };\n /**\n * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.\n * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions\n * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.\n * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.\n * Returns the Mesh.\n */\n Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {\n if (computeNormals === void 0) { computeNormals = true; }\n var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!positions) {\n return this;\n }\n positionFunction(positions);\n this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);\n if (computeNormals) {\n var indices = this.getIndices();\n var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n if (!normals) {\n return this;\n }\n BABYLON.VertexData.ComputeNormals(positions, indices, normals);\n this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);\n }\n return this;\n };\n /**\n * Creates a un-shared specific occurence of the geometry for the mesh.\n * Returns the Mesh.\n */\n Mesh.prototype.makeGeometryUnique = function () {\n if (!this._geometry) {\n return this;\n }\n var oldGeometry = this._geometry;\n var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());\n oldGeometry.releaseForMesh(this, true);\n geometry.applyToMesh(this);\n return this;\n };\n Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {\n if (totalVertices === void 0) { totalVertices = null; }\n if (updatable === void 0) { updatable = false; }\n if (!this._geometry) {\n var vertexData = new BABYLON.VertexData();\n vertexData.indices = indices;\n var scene = this.getScene();\n new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);\n }\n else {\n this._geometry.setIndices(indices, totalVertices, updatable);\n }\n return this;\n };\n /**\n * Update the current index buffer\n * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)\n * Returns the Mesh.\n */\n Mesh.prototype.updateIndices = function (indices, offset) {\n if (!this._geometry) {\n return this;\n }\n this._geometry.updateIndices(indices, offset);\n return this;\n };\n /**\n * Invert the geometry to move from a right handed system to a left handed one.\n * Returns the Mesh.\n */\n Mesh.prototype.toLeftHanded = function () {\n if (!this._geometry) {\n return this;\n }\n this._geometry.toLeftHanded();\n return this;\n };\n Mesh.prototype._bind = function (subMesh, effect, fillMode) {\n if (!this._geometry) {\n return this;\n }\n var engine = this.getScene().getEngine();\n // Wireframe\n var indexToBind;\n if (this._unIndexed) {\n indexToBind = null;\n }\n else {\n switch (fillMode) {\n case BABYLON.Material.PointFillMode:\n indexToBind = null;\n break;\n case BABYLON.Material.WireFrameFillMode:\n indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);\n break;\n default:\n case BABYLON.Material.TriangleFillMode:\n indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();\n break;\n }\n }\n // VBOs\n this._geometry._bind(effect, indexToBind);\n return this;\n };\n Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {\n if (alternate === void 0) { alternate = false; }\n if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {\n return this;\n }\n this.onBeforeDrawObservable.notifyObservers(this);\n var scene = this.getScene();\n var engine = scene.getEngine();\n if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {\n // or triangles as points\n engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);\n }\n else if (fillMode == BABYLON.Material.WireFrameFillMode) {\n // Triangles as wireframe\n engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);\n }\n else {\n engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);\n }\n if (scene._isAlternateRenderingEnabled && !alternate) {\n var effect = subMesh.effect || this._effectiveMaterial.getEffect();\n if (!effect || !scene.activeCamera) {\n return this;\n }\n scene._switchToAlternateCameraConfiguration(true);\n this._effectiveMaterial.bindView(effect);\n this._effectiveMaterial.bindViewProjection(effect);\n engine.setViewport(scene.activeCamera._alternateCamera.viewport);\n this._draw(subMesh, fillMode, instancesCount, true);\n engine.setViewport(scene.activeCamera.viewport);\n scene._switchToAlternateCameraConfiguration(false);\n this._effectiveMaterial.bindView(effect);\n this._effectiveMaterial.bindViewProjection(effect);\n }\n return this;\n };\n /**\n * Registers for this mesh a javascript function called just before the rendering process.\n * This function is passed the current mesh.\n * Return the Mesh.\n */\n Mesh.prototype.registerBeforeRender = function (func) {\n this.onBeforeRenderObservable.add(func);\n return this;\n };\n /**\n * Disposes a previously registered javascript function called before the rendering.\n * This function is passed the current mesh.\n * Returns the Mesh.\n */\n Mesh.prototype.unregisterBeforeRender = function (func) {\n this.onBeforeRenderObservable.removeCallback(func);\n return this;\n };\n /**\n * Registers for this mesh a javascript function called just after the rendering is complete.\n * This function is passed the current mesh.\n * Returns the Mesh.\n */\n Mesh.prototype.registerAfterRender = function (func) {\n this.onAfterRenderObservable.add(func);\n return this;\n };\n /**\n * Disposes a previously registered javascript function called after the rendering.\n * This function is passed the current mesh.\n * Return the Mesh.\n */\n Mesh.prototype.unregisterAfterRender = function (func) {\n this.onAfterRenderObservable.removeCallback(func);\n return this;\n };\n Mesh.prototype._getInstancesRenderList = function (subMeshId) {\n var scene = this.getScene();\n this._batchCache.mustReturn = false;\n this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;\n this._batchCache.visibleInstances[subMeshId] = null;\n if (this._visibleInstances) {\n var currentRenderId = scene.getRenderId();\n var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);\n this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];\n var selfRenderId = this._renderId;\n if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {\n this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];\n currentRenderId = Math.max(defaultRenderId, currentRenderId);\n selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);\n }\n var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];\n if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {\n if (this._renderIdForInstances[subMeshId] === currentRenderId) {\n this._batchCache.mustReturn = true;\n return this._batchCache;\n }\n if (currentRenderId !== selfRenderId) {\n this._batchCache.renderSelf[subMeshId] = false;\n }\n }\n this._renderIdForInstances[subMeshId] = currentRenderId;\n }\n return this._batchCache;\n };\n Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {\n var visibleInstances = batch.visibleInstances[subMesh._id];\n if (!visibleInstances) {\n return this;\n }\n var matricesCount = visibleInstances.length + 1;\n var bufferSize = matricesCount * 16 * 4;\n var currentInstancesBufferSize = this._instancesBufferSize;\n var instancesBuffer = this._instancesBuffer;\n while (this._instancesBufferSize < bufferSize) {\n this._instancesBufferSize *= 2;\n }\n if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {\n this._instancesData = new Float32Array(this._instancesBufferSize / 4);\n }\n var offset = 0;\n var instancesCount = 0;\n var world = this.getWorldMatrix();\n if (batch.renderSelf[subMesh._id]) {\n world.copyToArray(this._instancesData, offset);\n offset += 16;\n instancesCount++;\n }\n if (visibleInstances) {\n for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {\n var instance = visibleInstances[instanceIndex];\n instance.getWorldMatrix().copyToArray(this._instancesData, offset);\n offset += 16;\n instancesCount++;\n }\n }\n if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {\n if (instancesBuffer) {\n instancesBuffer.dispose();\n }\n instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);\n this._instancesBuffer = instancesBuffer;\n this.setVerticesBuffer(instancesBuffer.createVertexBuffer(\"world0\", 0, 4));\n this.setVerticesBuffer(instancesBuffer.createVertexBuffer(\"world1\", 4, 4));\n this.setVerticesBuffer(instancesBuffer.createVertexBuffer(\"world2\", 8, 4));\n this.setVerticesBuffer(instancesBuffer.createVertexBuffer(\"world3\", 12, 4));\n }\n else {\n instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);\n }\n this._bind(subMesh, effect, fillMode);\n this._draw(subMesh, fillMode, instancesCount);\n engine.unbindInstanceAttributes();\n return this;\n };\n Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {\n var scene = this.getScene();\n var engine = scene.getEngine();\n if (hardwareInstancedRendering) {\n this._renderWithInstances(subMesh, fillMode, batch, effect, engine);\n }\n else {\n if (batch.renderSelf[subMesh._id]) {\n // Draw\n if (onBeforeDraw) {\n onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);\n }\n this._draw(subMesh, fillMode, this._overridenInstanceCount);\n }\n var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];\n if (visibleInstancesForSubMesh) {\n for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {\n var instance = visibleInstancesForSubMesh[instanceIndex];\n // World\n var world = instance.getWorldMatrix();\n if (onBeforeDraw) {\n onBeforeDraw(true, world, effectiveMaterial);\n }\n // Draw\n this._draw(subMesh, fillMode);\n }\n }\n }\n return this;\n };\n /**\n * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager\n * @param subMesh defines the subMesh to render\n * @param enableAlphaMode defines if alpha mode can be changed\n * @returns the current mesh\n */\n Mesh.prototype.render = function (subMesh, enableAlphaMode) {\n this._checkOcclusionQuery();\n if (this._isOccluded) {\n return this;\n }\n var scene = this.getScene();\n // Managing instances\n var batch = this._getInstancesRenderList(subMesh._id);\n if (batch.mustReturn) {\n return this;\n }\n // Checking geometry state\n if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {\n return this;\n }\n this.onBeforeRenderObservable.notifyObservers(this);\n var engine = scene.getEngine();\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);\n // Material\n var material = subMesh.getMaterial();\n if (!material) {\n return this;\n }\n this._effectiveMaterial = material;\n if (this._effectiveMaterial.storeEffectOnSubMeshes) {\n if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {\n return this;\n }\n }\n else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {\n return this;\n }\n // Alpha mode\n if (enableAlphaMode) {\n engine.setAlphaMode(this._effectiveMaterial.alphaMode);\n }\n // Outline - step 1\n var savedDepthWrite = engine.getDepthWrite();\n if (this.renderOutline) {\n engine.setDepthWrite(false);\n scene.getOutlineRenderer().render(subMesh, batch);\n engine.setDepthWrite(savedDepthWrite);\n }\n var effect;\n if (this._effectiveMaterial.storeEffectOnSubMeshes) {\n effect = subMesh.effect;\n }\n else {\n effect = this._effectiveMaterial.getEffect();\n }\n if (!effect) {\n return this;\n }\n var sideOrientation = this.overrideMaterialSideOrientation;\n if (sideOrientation == null) {\n sideOrientation = this._effectiveMaterial.sideOrientation;\n if (this._getWorldMatrixDeterminant() < 0) {\n sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);\n }\n }\n var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);\n if (this._effectiveMaterial.forceDepthWrite) {\n engine.setDepthWrite(true);\n }\n // Bind\n var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);\n if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB\n this._bind(subMesh, effect, fillMode);\n }\n var world = this.getWorldMatrix();\n if (this._effectiveMaterial.storeEffectOnSubMeshes) {\n this._effectiveMaterial.bindForSubMesh(world, this, subMesh);\n }\n else {\n this._effectiveMaterial.bind(world, this);\n }\n if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {\n engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);\n this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);\n engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);\n }\n // Draw\n this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);\n // Unbind\n this._effectiveMaterial.unbind();\n // Outline - step 2\n if (this.renderOutline && savedDepthWrite) {\n engine.setDepthWrite(true);\n engine.setColorWrite(false);\n scene.getOutlineRenderer().render(subMesh, batch);\n engine.setColorWrite(true);\n }\n // Overlay\n if (this.renderOverlay) {\n var currentMode = engine.getAlphaMode();\n engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);\n scene.getOutlineRenderer().render(subMesh, batch, true);\n engine.setAlphaMode(currentMode);\n }\n this.onAfterRenderObservable.notifyObservers(this);\n return this;\n };\n Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {\n if (isInstance && effectiveMaterial) {\n effectiveMaterial.bindOnlyWorldMatrix(world);\n }\n };\n /**\n * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.\n */\n Mesh.prototype.getEmittedParticleSystems = function () {\n var results = new Array();\n for (var index = 0; index < this.getScene().particleSystems.length; index++) {\n var particleSystem = this.getScene().particleSystems[index];\n if (particleSystem.emitter === this) {\n results.push(particleSystem);\n }\n }\n return results;\n };\n /**\n * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.\n */\n Mesh.prototype.getHierarchyEmittedParticleSystems = function () {\n var results = new Array();\n var descendants = this.getDescendants();\n descendants.push(this);\n for (var index = 0; index < this.getScene().particleSystems.length; index++) {\n var particleSystem = this.getScene().particleSystems[index];\n var emitter = particleSystem.emitter;\n if (emitter.position && descendants.indexOf(emitter) !== -1) {\n results.push(particleSystem);\n }\n }\n return results;\n };\n /**\n * Normalize matrix weights so that all vertices have a total weight set to 1\n */\n Mesh.prototype.cleanMatrixWeights = function () {\n var epsilon = 1e-3;\n var noInfluenceBoneIndex = 0.0;\n if (this.skeleton) {\n noInfluenceBoneIndex = this.skeleton.bones.length;\n }\n else {\n return;\n }\n var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);\n var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);\n var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n var influencers = this.numBoneInfluencers;\n var size = matricesWeights.length;\n for (var i = 0; i < size; i += 4) {\n var weight = 0.0;\n var firstZeroWeight = -1;\n for (var j = 0; j < 4; j++) {\n var w = matricesWeights[i + j];\n weight += w;\n if (w < epsilon && firstZeroWeight < 0) {\n firstZeroWeight = j;\n }\n }\n if (matricesWeightsExtra) {\n for (var j = 0; j < 4; j++) {\n var w = matricesWeightsExtra[i + j];\n weight += w;\n if (w < epsilon && firstZeroWeight < 0) {\n firstZeroWeight = j + 4;\n }\n }\n }\n if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {\n firstZeroWeight = influencers - 1;\n }\n if (weight > epsilon) {\n var mweight = 1.0 / weight;\n for (var j = 0; j < 4; j++) {\n matricesWeights[i + j] *= mweight;\n }\n if (matricesWeightsExtra) {\n for (var j = 0; j < 4; j++) {\n matricesWeightsExtra[i + j] *= mweight;\n }\n }\n }\n else {\n if (firstZeroWeight >= 4) {\n matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;\n matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;\n }\n else {\n matricesWeights[i + firstZeroWeight] = 1.0 - weight;\n matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;\n }\n }\n }\n this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);\n if (matricesIndicesExtra) {\n this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);\n }\n this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);\n if (matricesWeightsExtra) {\n this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);\n }\n };\n Mesh.prototype._checkDelayState = function () {\n var scene = this.getScene();\n if (this._geometry) {\n this._geometry.load(scene);\n }\n else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;\n this._queueLoad(scene);\n }\n return this;\n };\n Mesh.prototype._queueLoad = function (scene) {\n var _this = this;\n scene._addPendingData(this);\n var getBinaryData = (this.delayLoadingFile.indexOf(\".babylonbinarymeshdata\") !== -1);\n BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {\n if (data instanceof ArrayBuffer) {\n _this._delayLoadingFunction(data, _this);\n }\n else {\n _this._delayLoadingFunction(JSON.parse(data), _this);\n }\n _this.instances.forEach(function (instance) {\n instance._syncSubMeshes();\n });\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;\n scene._removePendingData(_this);\n }, function () { }, scene.database, getBinaryData);\n return this;\n };\n /**\n * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.\n */\n Mesh.prototype.isInFrustum = function (frustumPlanes) {\n if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {\n return false;\n }\n if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {\n return false;\n }\n this._checkDelayState();\n return true;\n };\n /**\n * Sets the mesh material by the material or multiMaterial `id` property.\n * The material `id` is a string identifying the material or the multiMaterial.\n * This method returns the Mesh.\n */\n Mesh.prototype.setMaterialByID = function (id) {\n var materials = this.getScene().materials;\n var index;\n for (index = materials.length - 1; index > -1; index--) {\n if (materials[index].id === id) {\n this.material = materials[index];\n return this;\n }\n }\n // Multi\n var multiMaterials = this.getScene().multiMaterials;\n for (index = multiMaterials.length - 1; index > -1; index--) {\n if (multiMaterials[index].id === id) {\n this.material = multiMaterials[index];\n return this;\n }\n }\n return this;\n };\n /**\n * Returns as a new array populated with the mesh material and/or skeleton, if any.\n */\n Mesh.prototype.getAnimatables = function () {\n var results = new Array();\n if (this.material) {\n results.push(this.material);\n }\n if (this.skeleton) {\n results.push(this.skeleton);\n }\n return results;\n };\n /**\n * Modifies the mesh geometry according to the passed transformation matrix.\n * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.\n * The mesh normals are modified accordingly the same transformation.\n * tuto : http://doc.babylonjs.com/resources/baking_transformations\n * Note that, under the hood, this method sets a new VertexBuffer each call.\n * Returns the Mesh.\n */\n Mesh.prototype.bakeTransformIntoVertices = function (transform) {\n // Position\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {\n return this;\n }\n var submeshes = this.subMeshes.splice(0);\n this._resetPointsArrayCache();\n var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var temp = new Array();\n var index;\n for (index = 0; index < data.length; index += 3) {\n BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);\n }\n this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());\n // Normals\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n return this;\n }\n data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n temp = [];\n for (index = 0; index < data.length; index += 3) {\n BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);\n }\n this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());\n // flip faces?\n if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {\n this.flipFaces();\n }\n // Restore submeshes\n this.releaseSubMeshes();\n this.subMeshes = submeshes;\n return this;\n };\n /**\n * Modifies the mesh geometry according to its own current World Matrix.\n * The mesh World Matrix is then reset.\n * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.\n * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations\n * Note that, under the hood, this method sets a new VertexBuffer each call.\n * Returns the Mesh.\n */\n Mesh.prototype.bakeCurrentTransformIntoVertices = function () {\n this.bakeTransformIntoVertices(this.computeWorldMatrix(true));\n this.scaling.copyFromFloats(1, 1, 1);\n this.position.copyFromFloats(0, 0, 0);\n this.rotation.copyFromFloats(0, 0, 0);\n //only if quaternion is already set\n if (this.rotationQuaternion) {\n this.rotationQuaternion = BABYLON.Quaternion.Identity();\n }\n this._worldMatrix = BABYLON.Matrix.Identity();\n return this;\n };\n Object.defineProperty(Mesh.prototype, \"_positions\", {\n // Cache\n get: function () {\n if (this._geometry) {\n return this._geometry._positions;\n }\n return null;\n },\n enumerable: true,\n configurable: true\n });\n Mesh.prototype._resetPointsArrayCache = function () {\n if (this._geometry) {\n this._geometry._resetPointsArrayCache();\n }\n return this;\n };\n Mesh.prototype._generatePointsArray = function () {\n if (this._geometry) {\n return this._geometry._generatePointsArray();\n }\n return false;\n };\n /**\n * Returns a new Mesh object generated from the current mesh properties.\n * This method must not get confused with createInstance().\n * The parameter `name` is a string, the name given to the new mesh.\n * The optional parameter `newParent` can be any Node object (default `null`).\n * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.\n * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.\n */\n Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {\n if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }\n return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);\n };\n /**\n * Releases resources associated with this mesh.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n var _this = this;\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n this.morphTargetManager = null;\n if (this._geometry) {\n this._geometry.releaseForMesh(this, true);\n }\n // Sources\n var meshes = this.getScene().meshes;\n meshes.forEach(function (abstractMesh) {\n var mesh = abstractMesh;\n if (mesh._source && mesh._source === _this) {\n mesh._source = null;\n }\n });\n this._source = null;\n // Instances\n if (this._instancesBuffer) {\n this._instancesBuffer.dispose();\n this._instancesBuffer = null;\n }\n while (this.instances.length) {\n this.instances[0].dispose();\n }\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n /**\n * Modifies the mesh geometry according to a displacement map.\n * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.\n * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.\n * This method returns nothing.\n * The parameter `url` is a string, the URL from the image file is to be downloaded.\n * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.\n * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.\n * The parameter `uvOffset` is an optional vector2 used to offset UV.\n * The parameter `uvScale` is an optional vector2 used to scale UV.\n *\n * Returns the Mesh.\n */\n Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {\n var _this = this;\n var scene = this.getScene();\n var onload = function (img) {\n // Getting height map data\n var canvas = document.createElement(\"canvas\");\n var context = canvas.getContext(\"2d\");\n var heightMapWidth = img.width;\n var heightMapHeight = img.height;\n canvas.width = heightMapWidth;\n canvas.height = heightMapHeight;\n context.drawImage(img, 0, 0);\n // Create VertexData from map data\n //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949\n var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;\n _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);\n //execute success callback, if set\n if (onSuccess) {\n onSuccess(_this);\n }\n };\n BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);\n return this;\n };\n /**\n * Modifies the mesh geometry according to a displacementMap buffer.\n * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.\n * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.\n * This method returns nothing.\n * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.\n * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.\n * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.\n * The parameter `uvOffset` is an optional vector2 used to offset UV.\n * The parameter `uvScale` is an optional vector2 used to scale UV.\n *\n * Returns the Mesh.\n */\n Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)\n || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)\n || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n BABYLON.Tools.Warn(\"Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing\");\n return this;\n }\n var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);\n var position = BABYLON.Vector3.Zero();\n var normal = BABYLON.Vector3.Zero();\n var uv = BABYLON.Vector2.Zero();\n uvOffset = uvOffset || BABYLON.Vector2.Zero();\n uvScale = uvScale || new BABYLON.Vector2(1, 1);\n for (var index = 0; index < positions.length; index += 3) {\n BABYLON.Vector3.FromArrayToRef(positions, index, position);\n BABYLON.Vector3.FromArrayToRef(normals, index, normal);\n BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);\n // Compute height\n var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;\n var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;\n var pos = (u + v * heightMapWidth) * 4;\n var r = buffer[pos] / 255.0;\n var g = buffer[pos + 1] / 255.0;\n var b = buffer[pos + 2] / 255.0;\n var gradient = r * 0.3 + g * 0.59 + b * 0.11;\n normal.normalize();\n normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);\n position = position.add(normal);\n position.toArray(positions, index);\n }\n BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);\n this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);\n this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);\n return this;\n };\n /**\n * Modify the mesh to get a flat shading rendering.\n * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.\n * This method returns the Mesh.\n * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.\n */\n Mesh.prototype.convertToFlatShadedMesh = function () {\n /// Update normals and vertices to get a flat shading rendering.\n /// Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face\n var kinds = this.getVerticesDataKinds();\n var vbs = {};\n var data = {};\n var newdata = {};\n var updatableNormals = false;\n var kindIndex;\n var kind;\n for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {\n kind = kinds[kindIndex];\n var vertexBuffer = this.getVertexBuffer(kind);\n if (kind === BABYLON.VertexBuffer.NormalKind) {\n updatableNormals = vertexBuffer.isUpdatable();\n kinds.splice(kindIndex, 1);\n kindIndex--;\n continue;\n }\n vbs[kind] = vertexBuffer;\n data[kind] = vbs[kind].getData();\n newdata[kind] = [];\n }\n // Save previous submeshes\n var previousSubmeshes = this.subMeshes.slice(0);\n var indices = this.getIndices();\n var totalIndices = this.getTotalIndices();\n // Generating unique vertices per face\n var index;\n for (index = 0; index < totalIndices; index++) {\n var vertexIndex = indices[index];\n for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {\n kind = kinds[kindIndex];\n var stride = vbs[kind].getStrideSize();\n for (var offset = 0; offset < stride; offset++) {\n newdata[kind].push(data[kind][vertexIndex * stride + offset]);\n }\n }\n }\n // Updating faces & normal\n var normals = [];\n var positions = newdata[BABYLON.VertexBuffer.PositionKind];\n for (index = 0; index < totalIndices; index += 3) {\n indices[index] = index;\n indices[index + 1] = index + 1;\n indices[index + 2] = index + 2;\n var p1 = BABYLON.Vector3.FromArray(positions, index * 3);\n var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);\n var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);\n var p1p2 = p1.subtract(p2);\n var p3p2 = p3.subtract(p2);\n var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));\n // Store same normals for every vertex\n for (var localIndex = 0; localIndex < 3; localIndex++) {\n normals.push(normal.x);\n normals.push(normal.y);\n normals.push(normal.z);\n }\n }\n this.setIndices(indices);\n this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);\n // Updating vertex buffers\n for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {\n kind = kinds[kindIndex];\n this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());\n }\n // Updating submeshes\n this.releaseSubMeshes();\n for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {\n var previousOne = previousSubmeshes[submeshIndex];\n BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);\n }\n this.synchronizeInstances();\n return this;\n };\n /**\n * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.\n * In other words, more vertices, no more indices and a single bigger VBO.\n * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.\n * Returns the Mesh.\n */\n Mesh.prototype.convertToUnIndexedMesh = function () {\n /// Remove indices by unfolding faces into buffers\n /// Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face\n var kinds = this.getVerticesDataKinds();\n var vbs = {};\n var data = {};\n var newdata = {};\n var kindIndex;\n var kind;\n for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {\n kind = kinds[kindIndex];\n var vertexBuffer = this.getVertexBuffer(kind);\n vbs[kind] = vertexBuffer;\n data[kind] = vbs[kind].getData();\n newdata[kind] = [];\n }\n // Save previous submeshes\n var previousSubmeshes = this.subMeshes.slice(0);\n var indices = this.getIndices();\n var totalIndices = this.getTotalIndices();\n // Generating unique vertices per face\n var index;\n for (index = 0; index < totalIndices; index++) {\n var vertexIndex = indices[index];\n for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {\n kind = kinds[kindIndex];\n var stride = vbs[kind].getStrideSize();\n for (var offset = 0; offset < stride; offset++) {\n newdata[kind].push(data[kind][vertexIndex * stride + offset]);\n }\n }\n }\n // Updating indices\n for (index = 0; index < totalIndices; index += 3) {\n indices[index] = index;\n indices[index + 1] = index + 1;\n indices[index + 2] = index + 2;\n }\n this.setIndices(indices);\n // Updating vertex buffers\n for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {\n kind = kinds[kindIndex];\n this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());\n }\n // Updating submeshes\n this.releaseSubMeshes();\n for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {\n var previousOne = previousSubmeshes[submeshIndex];\n BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);\n }\n this._unIndexed = true;\n this.synchronizeInstances();\n return this;\n };\n /**\n * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.\n * This method returns the Mesh.\n * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.\n */\n Mesh.prototype.flipFaces = function (flipNormals) {\n if (flipNormals === void 0) { flipNormals = false; }\n var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);\n var i;\n if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {\n for (i = 0; i < vertex_data.normals.length; i++) {\n vertex_data.normals[i] *= -1;\n }\n }\n if (vertex_data.indices) {\n var temp;\n for (i = 0; i < vertex_data.indices.length; i += 3) {\n // reassign indices\n temp = vertex_data.indices[i + 1];\n vertex_data.indices[i + 1] = vertex_data.indices[i + 2];\n vertex_data.indices[i + 2] = temp;\n }\n }\n vertex_data.applyToMesh(this);\n return this;\n };\n // Instances\n /**\n * Creates a new InstancedMesh object from the mesh model.\n * An instance shares the same properties and the same material than its model.\n * Only these properties of each instance can then be set individually :\n * - position\n * - rotation\n * - rotationQuaternion\n * - setPivotMatrix\n * - scaling\n * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances\n * Warning : this method is not supported for Line mesh and LineSystem\n */\n Mesh.prototype.createInstance = function (name) {\n return new BABYLON.InstancedMesh(name, this);\n };\n /**\n * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.\n * After this call, all the mesh instances have the same submeshes than the current mesh.\n * This method returns the Mesh.\n */\n Mesh.prototype.synchronizeInstances = function () {\n for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {\n var instance = this.instances[instanceIndex];\n instance._syncSubMeshes();\n }\n return this;\n };\n /**\n * Simplify the mesh according to the given array of settings.\n * Function will return immediately and will simplify async. It returns the Mesh.\n * @param settings a collection of simplification settings.\n * @param parallelProcessing should all levels calculate parallel or one after the other.\n * @param type the type of simplification to run.\n * @param successCallback optional success callback to be called after the simplification finished processing all settings.\n */\n Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {\n if (parallelProcessing === void 0) { parallelProcessing = true; }\n if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }\n this.getScene().simplificationQueue.addTask({\n settings: settings,\n parallelProcessing: parallelProcessing,\n mesh: this,\n simplificationType: simplificationType,\n successCallback: successCallback\n });\n return this;\n };\n /**\n * Optimization of the mesh's indices, in case a mesh has duplicated vertices.\n * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.\n * This should be used together with the simplification to avoid disappearing triangles.\n * Returns the Mesh.\n * @param successCallback an optional success callback to be called after the optimization finished.\n */\n Mesh.prototype.optimizeIndices = function (successCallback) {\n var _this = this;\n var indices = this.getIndices();\n var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!positions || !indices) {\n return this;\n }\n var vectorPositions = new Array();\n for (var pos = 0; pos < positions.length; pos = pos + 3) {\n vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));\n }\n var dupes = new Array();\n BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {\n var realPos = vectorPositions.length - 1 - iteration;\n var testedPosition = vectorPositions[realPos];\n for (var j = 0; j < realPos; ++j) {\n var againstPosition = vectorPositions[j];\n if (testedPosition.equals(againstPosition)) {\n dupes[realPos] = j;\n break;\n }\n }\n }, function () {\n for (var i = 0; i < indices.length; ++i) {\n indices[i] = dupes[indices[i]] || indices[i];\n }\n //indices are now reordered\n var originalSubMeshes = _this.subMeshes.slice(0);\n _this.setIndices(indices);\n _this.subMeshes = originalSubMeshes;\n if (successCallback) {\n successCallback(_this);\n }\n });\n return this;\n };\n Mesh.prototype.serialize = function (serializationObject) {\n serializationObject.name = this.name;\n serializationObject.id = this.id;\n serializationObject.type = this.getClassName();\n if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {\n serializationObject.tags = BABYLON.Tags.GetTags(this);\n }\n serializationObject.position = this.position.asArray();\n if (this.rotationQuaternion) {\n serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();\n }\n else if (this.rotation) {\n serializationObject.rotation = this.rotation.asArray();\n }\n serializationObject.scaling = this.scaling.asArray();\n serializationObject.localMatrix = this.getPivotMatrix().asArray();\n serializationObject.isEnabled = this.isEnabled(false);\n serializationObject.isVisible = this.isVisible;\n serializationObject.infiniteDistance = this.infiniteDistance;\n serializationObject.pickable = this.isPickable;\n serializationObject.receiveShadows = this.receiveShadows;\n serializationObject.billboardMode = this.billboardMode;\n serializationObject.visibility = this.visibility;\n serializationObject.checkCollisions = this.checkCollisions;\n serializationObject.isBlocker = this.isBlocker;\n // Parent\n if (this.parent) {\n serializationObject.parentId = this.parent.id;\n }\n // Geometry\n serializationObject.isUnIndexed = this.isUnIndexed;\n var geometry = this._geometry;\n if (geometry) {\n var geometryId = geometry.id;\n serializationObject.geometryId = geometryId;\n // SubMeshes\n serializationObject.subMeshes = [];\n for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {\n var subMesh = this.subMeshes[subIndex];\n serializationObject.subMeshes.push({\n materialIndex: subMesh.materialIndex,\n verticesStart: subMesh.verticesStart,\n verticesCount: subMesh.verticesCount,\n indexStart: subMesh.indexStart,\n indexCount: subMesh.indexCount\n });\n }\n }\n // Material\n if (this.material) {\n serializationObject.materialId = this.material.id;\n }\n else {\n this.material = null;\n }\n // Morph targets\n if (this.morphTargetManager) {\n serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;\n }\n // Skeleton\n if (this.skeleton) {\n serializationObject.skeletonId = this.skeleton.id;\n }\n // Physics\n //TODO implement correct serialization for physics impostors.\n var impostor = this.getPhysicsImpostor();\n if (impostor) {\n serializationObject.physicsMass = impostor.getParam(\"mass\");\n serializationObject.physicsFriction = impostor.getParam(\"friction\");\n serializationObject.physicsRestitution = impostor.getParam(\"mass\");\n serializationObject.physicsImpostor = impostor.type;\n }\n // Metadata\n if (this.metadata) {\n serializationObject.metadata = this.metadata;\n }\n // Instances\n serializationObject.instances = [];\n for (var index = 0; index < this.instances.length; index++) {\n var instance = this.instances[index];\n var serializationInstance = {\n name: instance.name,\n id: instance.id,\n position: instance.position.asArray(),\n scaling: instance.scaling.asArray()\n };\n if (instance.rotationQuaternion) {\n serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();\n }\n else if (instance.rotation) {\n serializationInstance.rotation = instance.rotation.asArray();\n }\n serializationObject.instances.push(serializationInstance);\n // Animations\n BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);\n serializationInstance.ranges = instance.serializeAnimationRanges();\n }\n // \n // Animations\n BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);\n serializationObject.ranges = this.serializeAnimationRanges();\n // Layer mask\n serializationObject.layerMask = this.layerMask;\n // Alpha\n serializationObject.alphaIndex = this.alphaIndex;\n serializationObject.hasVertexAlpha = this.hasVertexAlpha;\n // Overlay\n serializationObject.overlayAlpha = this.overlayAlpha;\n serializationObject.overlayColor = this.overlayColor.asArray();\n serializationObject.renderOverlay = this.renderOverlay;\n // Fog\n serializationObject.applyFog = this.applyFog;\n // Action Manager\n if (this.actionManager) {\n serializationObject.actions = this.actionManager.serialize(this.name);\n }\n };\n Mesh.prototype._syncGeometryWithMorphTargetManager = function () {\n if (!this.geometry) {\n return;\n }\n this._markSubMeshesAsAttributesDirty();\n var morphTargetManager = this._morphTargetManager;\n if (morphTargetManager && morphTargetManager.vertexCount) {\n if (morphTargetManager.vertexCount !== this.getTotalVertices()) {\n BABYLON.Tools.Error(\"Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.\");\n this.morphTargetManager = null;\n return;\n }\n for (var index = 0; index < morphTargetManager.numInfluencers; index++) {\n var morphTarget = morphTargetManager.getActiveTarget(index);\n var positions = morphTarget.getPositions();\n if (!positions) {\n BABYLON.Tools.Error(\"Invalid morph target. Target must have positions.\");\n return;\n }\n this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);\n var normals = morphTarget.getNormals();\n if (normals) {\n this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);\n }\n var tangents = morphTarget.getTangents();\n if (tangents) {\n this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);\n }\n }\n }\n else {\n var index = 0;\n // Positions\n while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {\n this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);\n if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {\n this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);\n }\n if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {\n this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);\n }\n index++;\n }\n }\n };\n // Statics\n /**\n * Returns a new Mesh object parsed from the source provided.\n * The parameter `parsedMesh` is the source.\n * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with\n */\n Mesh.Parse = function (parsedMesh, scene, rootUrl) {\n var mesh;\n if (parsedMesh.type && parsedMesh.type === \"GroundMesh\") {\n mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);\n }\n else {\n mesh = new Mesh(parsedMesh.name, scene);\n }\n mesh.id = parsedMesh.id;\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);\n }\n mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);\n if (parsedMesh.metadata !== undefined) {\n mesh.metadata = parsedMesh.metadata;\n }\n if (parsedMesh.rotationQuaternion) {\n mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);\n }\n else if (parsedMesh.rotation) {\n mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);\n }\n mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);\n if (parsedMesh.localMatrix) {\n mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));\n }\n else if (parsedMesh.pivotMatrix) {\n mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));\n }\n mesh.setEnabled(parsedMesh.isEnabled);\n mesh.isVisible = parsedMesh.isVisible;\n mesh.infiniteDistance = parsedMesh.infiniteDistance;\n mesh.showBoundingBox = parsedMesh.showBoundingBox;\n mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;\n if (parsedMesh.applyFog !== undefined) {\n mesh.applyFog = parsedMesh.applyFog;\n }\n if (parsedMesh.pickable !== undefined) {\n mesh.isPickable = parsedMesh.pickable;\n }\n if (parsedMesh.alphaIndex !== undefined) {\n mesh.alphaIndex = parsedMesh.alphaIndex;\n }\n mesh.receiveShadows = parsedMesh.receiveShadows;\n mesh.billboardMode = parsedMesh.billboardMode;\n if (parsedMesh.visibility !== undefined) {\n mesh.visibility = parsedMesh.visibility;\n }\n mesh.checkCollisions = parsedMesh.checkCollisions;\n if (parsedMesh.isBlocker !== undefined) {\n mesh.isBlocker = parsedMesh.isBlocker;\n }\n mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;\n // freezeWorldMatrix\n if (parsedMesh.freezeWorldMatrix) {\n mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;\n }\n // Parent\n if (parsedMesh.parentId) {\n mesh._waitingParentId = parsedMesh.parentId;\n }\n // Actions\n if (parsedMesh.actions !== undefined) {\n mesh._waitingActions = parsedMesh.actions;\n }\n // Overlay\n if (parsedMesh.overlayAlpha !== undefined) {\n mesh.overlayAlpha = parsedMesh.overlayAlpha;\n }\n if (parsedMesh.overlayColor !== undefined) {\n mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);\n }\n if (parsedMesh.renderOverlay !== undefined) {\n mesh.renderOverlay = parsedMesh.renderOverlay;\n }\n // Geometry\n mesh.isUnIndexed = !!parsedMesh.isUnIndexed;\n mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;\n if (parsedMesh.delayLoadingFile) {\n mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;\n mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));\n if (parsedMesh._binaryInfo) {\n mesh._binaryInfo = parsedMesh._binaryInfo;\n }\n mesh._delayInfo = [];\n if (parsedMesh.hasUVs) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);\n }\n if (parsedMesh.hasUVs2) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);\n }\n if (parsedMesh.hasUVs3) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);\n }\n if (parsedMesh.hasUVs4) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);\n }\n if (parsedMesh.hasUVs5) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);\n }\n if (parsedMesh.hasUVs6) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);\n }\n if (parsedMesh.hasColors) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);\n }\n if (parsedMesh.hasMatricesIndices) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n }\n if (parsedMesh.hasMatricesWeights) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n }\n mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;\n if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {\n mesh._checkDelayState();\n }\n }\n else {\n BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);\n }\n // Material\n if (parsedMesh.materialId) {\n mesh.setMaterialByID(parsedMesh.materialId);\n }\n else {\n mesh.material = null;\n }\n // Morph targets\n if (parsedMesh.morphTargetManagerId > -1) {\n mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);\n }\n // Skeleton\n if (parsedMesh.skeletonId > -1) {\n mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);\n if (parsedMesh.numBoneInfluencers) {\n mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;\n }\n }\n // Animations\n if (parsedMesh.animations) {\n for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {\n var parsedAnimation = parsedMesh.animations[animationIndex];\n mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);\n }\n if (parsedMesh.autoAnimate) {\n scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);\n }\n // Layer Mask\n if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {\n mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));\n }\n else {\n mesh.layerMask = 0x0FFFFFFF;\n }\n // Physics\n if (parsedMesh.physicsImpostor) {\n mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {\n mass: parsedMesh.physicsMass,\n friction: parsedMesh.physicsFriction,\n restitution: parsedMesh.physicsRestitution\n }, scene);\n }\n // Instances\n if (parsedMesh.instances) {\n for (var index = 0; index < parsedMesh.instances.length; index++) {\n var parsedInstance = parsedMesh.instances[index];\n var instance = mesh.createInstance(parsedInstance.name);\n if (parsedInstance.id) {\n instance.id = parsedInstance.id;\n }\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);\n }\n instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);\n if (parsedInstance.parentId) {\n instance._waitingParentId = parsedInstance.parentId;\n }\n if (parsedInstance.rotationQuaternion) {\n instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);\n }\n else if (parsedInstance.rotation) {\n instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);\n }\n instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);\n instance.checkCollisions = mesh.checkCollisions;\n if (parsedMesh.animations) {\n for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {\n parsedAnimation = parsedMesh.animations[animationIndex];\n instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);\n if (parsedMesh.autoAnimate) {\n scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);\n }\n }\n }\n }\n return mesh;\n };\n /**\n * Creates a ribbon mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.\n *\n * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial\n * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.\n * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.\n * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.\n * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.\n * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.\n * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {\n if (closeArray === void 0) { closeArray = false; }\n if (updatable === void 0) { updatable = false; }\n return BABYLON.MeshBuilder.CreateRibbon(name, {\n pathArray: pathArray,\n closeArray: closeArray,\n closePath: closePath,\n offset: offset,\n updatable: updatable,\n sideOrientation: sideOrientation,\n instance: instance\n }, scene);\n };\n /**\n * Creates a plane polygonal mesh. By default, this is a disc.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).\n * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {\n if (scene === void 0) { scene = null; }\n var options = {\n radius: radius,\n tessellation: tessellation,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateDisc(name, options, scene);\n };\n /**\n * Creates a box mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `size` sets the size (float) of each box side (default 1).\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {\n if (scene === void 0) { scene = null; }\n var options = {\n size: size,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateBox(name, options, scene);\n };\n /**\n * Creates a sphere mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).\n * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {\n var options = {\n segments: segments,\n diameterX: diameter,\n diameterY: diameter,\n diameterZ: diameter,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateSphere(name, options, scene);\n };\n /**\n * Creates a cylinder or a cone mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).\n * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).\n * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter \"diameterBottom\" can't be zero.\n * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.\n * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {\n if (scene === undefined || !(scene instanceof BABYLON.Scene)) {\n if (scene !== undefined) {\n sideOrientation = updatable || Mesh.DEFAULTSIDE;\n updatable = scene;\n }\n scene = subdivisions;\n subdivisions = 1;\n }\n var options = {\n height: height,\n diameterTop: diameterTop,\n diameterBottom: diameterBottom,\n tessellation: tessellation,\n subdivisions: subdivisions,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);\n };\n // Torus (Code from SharpDX.org)\n /**\n * Creates a torus mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `diameter` sets the diameter size (float) of the torus (default 1).\n * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).\n * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {\n var options = {\n diameter: diameter,\n thickness: thickness,\n tessellation: tessellation,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateTorus(name, options, scene);\n };\n /**\n * Creates a torus knot mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).\n * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).\n * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).\n * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {\n var options = {\n radius: radius,\n tube: tube,\n radialSegments: radialSegments,\n tubularSegments: tubularSegments,\n p: p,\n q: q,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);\n };\n /**\n * Creates a line mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.\n * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.\n * The parameter `points` is an array successive Vector3.\n * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines\n * When updating an instance, remember that only point positions can change, not the number of points.\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateLines = function (name, points, scene, updatable, instance) {\n if (scene === void 0) { scene = null; }\n if (updatable === void 0) { updatable = false; }\n if (instance === void 0) { instance = null; }\n var options = {\n points: points,\n updatable: updatable,\n instance: instance\n };\n return BABYLON.MeshBuilder.CreateLines(name, options, scene);\n };\n /**\n * Creates a dashed line mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.\n * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.\n * The parameter `points` is an array successive Vector3.\n * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).\n * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).\n * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).\n * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines\n * When updating an instance, remember that only point positions can change, not the number of points.\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {\n if (scene === void 0) { scene = null; }\n var options = {\n points: points,\n dashSize: dashSize,\n gapSize: gapSize,\n dashNb: dashNb,\n updatable: updatable,\n instance: instance\n };\n return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);\n };\n /**\n * Creates a polygon mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.\n * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.\n * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * Remember you can only change the shape positions, not their number when updating a polygon.\n */\n Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {\n var options = {\n shape: shape,\n holes: holes,\n updatable: updatable,\n sideOrientation: sideOrientation\n };\n return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);\n };\n /**\n * Creates an extruded polygon mesh, with depth in the Y direction.\n * Please consider using the same method from the MeshBuilder class instead.\n */\n Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {\n var options = {\n shape: shape,\n holes: holes,\n depth: depth,\n updatable: updatable,\n sideOrientation: sideOrientation\n };\n return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);\n };\n /**\n * Creates an extruded shape mesh.\n * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.\n * Please consider using the same method from the MeshBuilder class instead.\n *\n * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes\n * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be\n * extruded along the Z axis.\n * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.\n * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.\n * The parameter `scale` (float, default 1) is the value to scale the shape.\n * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape\n * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {\n if (scene === void 0) { scene = null; }\n var options = {\n shape: shape,\n path: path,\n scale: scale,\n rotation: rotation,\n cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,\n sideOrientation: sideOrientation,\n instance: instance,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);\n };\n /**\n * Creates an custom extruded shape mesh.\n * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.\n * Please consider using the same method from the MeshBuilder class instead.\n *\n * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes\n * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be\n * extruded along the Z axis.\n * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.\n * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path\n * and the distance of this point from the begining of the path :\n * ```javascript\n * var rotationFunction = function(i, distance) {\n * // do things\n * return rotationValue; }\n * ```\n * It must returns a float value that will be the rotation in radians applied to the shape on each path point.\n * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path\n * and the distance of this point from the begining of the path :\n * ```javascript\n * var scaleFunction = function(i, distance) {\n * // do things\n * return scaleValue;}\n * ```\n * It must returns a float value that will be the scale value applied to the shape on each path point.\n * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.\n * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.\n * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape\n * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {\n var options = {\n shape: shape,\n path: path,\n scaleFunction: scaleFunction,\n rotationFunction: rotationFunction,\n ribbonCloseArray: ribbonCloseArray,\n ribbonClosePath: ribbonClosePath,\n cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,\n sideOrientation: sideOrientation,\n instance: instance,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);\n };\n /**\n * Creates lathe mesh.\n * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be\n * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.\n * The parameter `radius` (positive float, default 1) is the radius value of the lathe.\n * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {\n var options = {\n shape: shape,\n radius: radius,\n tessellation: tessellation,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateLathe(name, options, scene);\n };\n /**\n * Creates a plane mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {\n var options = {\n size: size,\n width: size,\n height: size,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreatePlane(name, options, scene);\n };\n /**\n * Creates a ground mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.\n * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {\n var options = {\n width: width,\n height: height,\n subdivisions: subdivisions,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateGround(name, options, scene);\n };\n /**\n * Creates a tiled ground mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.\n * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.\n * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the\n * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.\n * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the\n * numbers of subdivisions on the ground width and height of each tile.\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {\n var options = {\n xmin: xmin,\n zmin: zmin,\n xmax: xmax,\n zmax: zmax,\n subdivisions: subdivisions,\n precision: precision,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);\n };\n /**\n * Creates a ground mesh from a height map.\n * tuto : http://doc.babylonjs.com/babylon101/height_map\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `url` sets the URL of the height map image resource.\n * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.\n * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.\n * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.\n * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.\n * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).\n * This function is passed the newly built mesh :\n * ```javascript\n * function(mesh) { // do things\n * return; }\n * ```\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {\n var options = {\n width: width,\n height: height,\n subdivisions: subdivisions,\n minHeight: minHeight,\n maxHeight: maxHeight,\n updatable: updatable,\n onReady: onReady\n };\n return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);\n };\n /**\n * Creates a tube mesh.\n * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.\n * The parameter `radius` (positive float, default 1) sets the tube radius size.\n * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.\n * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.\n * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.\n * It must return a radius value (positive float) :\n * ```javascript\n * var radiusFunction = function(i, distance) {\n * // do things\n * return radius; }\n * ```\n * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {\n var options = {\n path: path,\n radius: radius,\n tessellation: tessellation,\n radiusFunction: radiusFunction,\n arc: 1,\n cap: cap,\n updatable: updatable,\n sideOrientation: sideOrientation,\n instance: instance\n };\n return BABYLON.MeshBuilder.CreateTube(name, options, scene);\n };\n /**\n * Creates a polyhedron mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial\n * to choose the wanted type.\n * The parameter `size` (positive float, default 1) sets the polygon size.\n * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).\n * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.\n * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron\n * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).\n * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors\n * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreatePolyhedron = function (name, options, scene) {\n return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);\n };\n /**\n * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `radius` sets the radius size (float) of the icosphere (default 1).\n * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).\n * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.\n * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateIcoSphere = function (name, options, scene) {\n return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);\n };\n /**\n * Creates a decal mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.\n * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.\n * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.\n * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.\n * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.\n */\n Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {\n var options = {\n position: position,\n normal: normal,\n size: size,\n angle: angle\n };\n return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);\n };\n // Skeletons\n /**\n * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.\n */\n Mesh.prototype.setPositionsForCPUSkinning = function () {\n if (!this._sourcePositions) {\n var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!source) {\n return this._sourcePositions;\n }\n this._sourcePositions = new Float32Array(source);\n if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {\n this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);\n }\n }\n return this._sourcePositions;\n };\n /**\n * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.\n */\n Mesh.prototype.setNormalsForCPUSkinning = function () {\n if (!this._sourceNormals) {\n var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n if (!source) {\n return this._sourceNormals;\n }\n this._sourceNormals = new Float32Array(source);\n if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {\n this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);\n }\n }\n return this._sourceNormals;\n };\n /**\n * Updates the vertex buffer by applying transformation from the bones.\n * Returns the Mesh.\n *\n * @param {skeleton} skeleton to apply\n */\n Mesh.prototype.applySkeleton = function (skeleton) {\n if (!this.geometry) {\n return this;\n }\n if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {\n return this;\n }\n this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {\n return this;\n }\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n return this;\n }\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {\n return this;\n }\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {\n return this;\n }\n if (!this._sourcePositions) {\n var submeshes = this.subMeshes.slice();\n this.setPositionsForCPUSkinning();\n this.subMeshes = submeshes;\n }\n if (!this._sourceNormals) {\n this.setNormalsForCPUSkinning();\n }\n // positionsData checks for not being Float32Array will only pass at most once\n var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!positionsData) {\n return this;\n }\n if (!(positionsData instanceof Float32Array)) {\n positionsData = new Float32Array(positionsData);\n }\n // normalsData checks for not being Float32Array will only pass at most once\n var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n if (!normalsData) {\n return this;\n }\n if (!(normalsData instanceof Float32Array)) {\n normalsData = new Float32Array(normalsData);\n }\n var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);\n var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (!matricesWeightsData || !matricesIndicesData) {\n return this;\n }\n var needExtras = this.numBoneInfluencers > 4;\n var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;\n var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;\n var skeletonMatrices = skeleton.getTransformMatrices(this);\n var tempVector3 = BABYLON.Vector3.Zero();\n var finalMatrix = new BABYLON.Matrix();\n var tempMatrix = new BABYLON.Matrix();\n var matWeightIdx = 0;\n var inf;\n for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {\n var weight;\n for (inf = 0; inf < 4; inf++) {\n weight = matricesWeightsData[matWeightIdx + inf];\n if (weight > 0) {\n BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);\n finalMatrix.addToSelf(tempMatrix);\n }\n }\n if (needExtras) {\n for (inf = 0; inf < 4; inf++) {\n weight = matricesWeightsExtraData[matWeightIdx + inf];\n if (weight > 0) {\n BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);\n finalMatrix.addToSelf(tempMatrix);\n }\n }\n }\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);\n tempVector3.toArray(positionsData, index);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);\n tempVector3.toArray(normalsData, index);\n finalMatrix.reset();\n }\n this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);\n this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);\n return this;\n };\n // Tools\n /**\n * Returns an object `{min:` Vector3`, max:` Vector3`}`\n * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system\n */\n Mesh.MinMax = function (meshes) {\n var minVector = null;\n var maxVector = null;\n meshes.forEach(function (mesh, index, array) {\n var boundingInfo = mesh.getBoundingInfo();\n var boundingBox = boundingInfo.boundingBox;\n if (!minVector || !maxVector) {\n minVector = boundingBox.minimumWorld;\n maxVector = boundingBox.maximumWorld;\n }\n else {\n minVector.minimizeInPlace(boundingBox.minimumWorld);\n maxVector.maximizeInPlace(boundingBox.maximumWorld);\n }\n });\n if (!minVector || !maxVector) {\n return {\n min: BABYLON.Vector3.Zero(),\n max: BABYLON.Vector3.Zero()\n };\n }\n return {\n min: minVector,\n max: maxVector\n };\n };\n /**\n * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.\n */\n Mesh.Center = function (meshesOrMinMaxVector) {\n var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;\n return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);\n };\n /**\n * Merge the array of meshes into a single mesh for performance reasons.\n * @param {Array} meshes - The vertices source. They should all be of the same material. Entries can empty\n * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes\n * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.\n * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.\n * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.\n */\n Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {\n if (disposeSource === void 0) { disposeSource = true; }\n var index;\n if (!allow32BitsIndices) {\n var totalVertices = 0;\n // Counting vertices\n for (index = 0; index < meshes.length; index++) {\n if (meshes[index]) {\n totalVertices += meshes[index].getTotalVertices();\n if (totalVertices > 65536) {\n BABYLON.Tools.Warn(\"Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices\");\n return null;\n }\n }\n }\n }\n // Merge\n var vertexData = null;\n var otherVertexData;\n var indiceArray = new Array();\n var source = null;\n for (index = 0; index < meshes.length; index++) {\n if (meshes[index]) {\n meshes[index].computeWorldMatrix(true);\n otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);\n otherVertexData.transform(meshes[index].getWorldMatrix());\n if (vertexData) {\n vertexData.merge(otherVertexData);\n }\n else {\n vertexData = otherVertexData;\n source = meshes[index];\n }\n if (subdivideWithSubMeshes) {\n indiceArray.push(meshes[index].getTotalIndices());\n }\n }\n }\n source = source;\n if (!meshSubclass) {\n meshSubclass = new Mesh(source.name + \"_merged\", source.getScene());\n }\n vertexData.applyToMesh(meshSubclass);\n // Setting properties\n meshSubclass.material = source.material;\n meshSubclass.checkCollisions = source.checkCollisions;\n // Cleaning\n if (disposeSource) {\n for (index = 0; index < meshes.length; index++) {\n if (meshes[index]) {\n meshes[index].dispose();\n }\n }\n }\n // Subdivide\n if (subdivideWithSubMeshes) {\n //-- removal of global submesh\n meshSubclass.releaseSubMeshes();\n index = 0;\n var offset = 0;\n //-- apply subdivision according to index table\n while (index < indiceArray.length) {\n BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);\n offset += indiceArray[index];\n index++;\n }\n }\n return meshSubclass;\n };\n // Consts\n Mesh._FRONTSIDE = 0;\n Mesh._BACKSIDE = 1;\n Mesh._DOUBLESIDE = 2;\n Mesh._DEFAULTSIDE = 0;\n Mesh._NO_CAP = 0;\n Mesh._CAP_START = 1;\n Mesh._CAP_END = 2;\n Mesh._CAP_ALL = 3;\n return Mesh;\n }(BABYLON.AbstractMesh));\n BABYLON.Mesh = Mesh;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.mesh.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var BaseSubMesh = /** @class */ (function () {\n function BaseSubMesh() {\n }\n Object.defineProperty(BaseSubMesh.prototype, \"effect\", {\n get: function () {\n return this._materialEffect;\n },\n enumerable: true,\n configurable: true\n });\n BaseSubMesh.prototype.setEffect = function (effect, defines) {\n if (defines === void 0) { defines = null; }\n if (this._materialEffect === effect) {\n if (!effect) {\n this._materialDefines = null;\n }\n return;\n }\n this._materialDefines = defines;\n this._materialEffect = effect;\n };\n return BaseSubMesh;\n }());\n BABYLON.BaseSubMesh = BaseSubMesh;\n var SubMesh = /** @class */ (function (_super) {\n __extends(SubMesh, _super);\n function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {\n if (createBoundingBox === void 0) { createBoundingBox = true; }\n var _this = _super.call(this) || this;\n _this.materialIndex = materialIndex;\n _this.verticesStart = verticesStart;\n _this.verticesCount = verticesCount;\n _this.indexStart = indexStart;\n _this.indexCount = indexCount;\n _this._renderId = 0;\n _this._mesh = mesh;\n _this._renderingMesh = renderingMesh || mesh;\n mesh.subMeshes.push(_this);\n _this._trianglePlanes = [];\n _this._id = mesh.subMeshes.length - 1;\n if (createBoundingBox) {\n _this.refreshBoundingInfo();\n mesh.computeWorldMatrix(true);\n }\n return _this;\n }\n SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {\n if (createBoundingBox === void 0) { createBoundingBox = true; }\n return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);\n };\n Object.defineProperty(SubMesh.prototype, \"IsGlobal\", {\n get: function () {\n return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the submesh BoudingInfo object.\n */\n SubMesh.prototype.getBoundingInfo = function () {\n if (this.IsGlobal) {\n return this._mesh.getBoundingInfo();\n }\n return this._boundingInfo;\n };\n /**\n * Sets the submesh BoundingInfo.\n * Return the SubMesh.\n */\n SubMesh.prototype.setBoundingInfo = function (boundingInfo) {\n this._boundingInfo = boundingInfo;\n return this;\n };\n /**\n * Returns the mesh of the current submesh.\n */\n SubMesh.prototype.getMesh = function () {\n return this._mesh;\n };\n /**\n * Returns the rendering mesh of the submesh.\n */\n SubMesh.prototype.getRenderingMesh = function () {\n return this._renderingMesh;\n };\n /**\n * Returns the submesh material.\n */\n SubMesh.prototype.getMaterial = function () {\n var rootMaterial = this._renderingMesh.material;\n if (rootMaterial === null || rootMaterial === undefined) {\n return this._mesh.getScene().defaultMaterial;\n }\n else if (rootMaterial.getSubMaterial) {\n var multiMaterial = rootMaterial;\n var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);\n if (this._currentMaterial !== effectiveMaterial) {\n this._currentMaterial = effectiveMaterial;\n this._materialDefines = null;\n }\n return effectiveMaterial;\n }\n return rootMaterial;\n };\n // Methods\n /**\n * Sets a new updated BoundingInfo object to the submesh.\n * Returns the SubMesh.\n */\n SubMesh.prototype.refreshBoundingInfo = function () {\n this._lastColliderWorldVertices = null;\n if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {\n return this;\n }\n var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!data) {\n this._boundingInfo = this._mesh.getBoundingInfo();\n return this;\n }\n var indices = this._renderingMesh.getIndices();\n var extend;\n //is this the only submesh?\n if (this.indexStart === 0 && this.indexCount === indices.length) {\n var boundingInfo = this._renderingMesh.getBoundingInfo();\n //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.\n extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };\n }\n else {\n extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);\n }\n this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);\n return this;\n };\n SubMesh.prototype._checkCollision = function (collider) {\n var boundingInfo = this.getBoundingInfo();\n return boundingInfo._checkCollision(collider);\n };\n /**\n * Updates the submesh BoundingInfo.\n * Returns the Submesh.\n */\n SubMesh.prototype.updateBoundingInfo = function (world) {\n var boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n this.refreshBoundingInfo();\n boundingInfo = this.getBoundingInfo();\n }\n boundingInfo.update(world);\n return this;\n };\n /**\n * True is the submesh bounding box intersects the frustum defined by the passed array of planes.\n * Boolean returned.\n */\n SubMesh.prototype.isInFrustum = function (frustumPlanes) {\n var boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return false;\n }\n return boundingInfo.isInFrustum(frustumPlanes);\n };\n /**\n * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.\n * Boolean returned.\n */\n SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {\n var boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return false;\n }\n return boundingInfo.isCompletelyInFrustum(frustumPlanes);\n };\n /**\n * Renders the submesh.\n * Returns it.\n */\n SubMesh.prototype.render = function (enableAlphaMode) {\n this._renderingMesh.render(this, enableAlphaMode);\n return this;\n };\n /**\n * Returns a new Index Buffer.\n * Type returned : WebGLBuffer.\n */\n SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {\n if (!this._linesIndexBuffer) {\n var linesIndices = [];\n for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {\n linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);\n }\n this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);\n this.linesIndexCount = linesIndices.length;\n }\n return this._linesIndexBuffer;\n };\n /**\n * True is the passed Ray intersects the submesh bounding box.\n * Boolean returned.\n */\n SubMesh.prototype.canIntersects = function (ray) {\n var boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return false;\n }\n return ray.intersectsBox(boundingInfo.boundingBox);\n };\n /**\n * Returns an object IntersectionInfo.\n */\n SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {\n var intersectInfo = null;\n var material = this.getMaterial();\n if (!material) {\n return null;\n }\n switch (material.fillMode) {\n case BABYLON.Material.PointListDrawMode:\n case BABYLON.Material.LineListDrawMode:\n case BABYLON.Material.LineLoopDrawMode:\n case BABYLON.Material.LineStripDrawMode:\n case BABYLON.Material.TriangleFanDrawMode:\n case BABYLON.Material.TriangleStripDrawMode:\n return null;\n }\n // LineMesh first as it's also a Mesh...\n if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {\n var lineMesh = this._mesh;\n // Line test\n for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {\n var p0 = positions[indices[index]];\n var p1 = positions[indices[index + 1]];\n var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);\n if (length < 0) {\n continue;\n }\n if (fastCheck || !intersectInfo || length < intersectInfo.distance) {\n intersectInfo = new BABYLON.IntersectionInfo(null, null, length);\n if (fastCheck) {\n break;\n }\n }\n }\n }\n else {\n // Triangles test\n for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {\n var p0 = positions[indices[index]];\n var p1 = positions[indices[index + 1]];\n var p2 = positions[indices[index + 2]];\n var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);\n if (currentIntersectInfo) {\n if (currentIntersectInfo.distance < 0) {\n continue;\n }\n if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {\n intersectInfo = currentIntersectInfo;\n intersectInfo.faceId = index / 3;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n }\n return intersectInfo;\n };\n SubMesh.prototype._rebuild = function () {\n if (this._linesIndexBuffer) {\n this._linesIndexBuffer = null;\n }\n };\n // Clone \n /**\n * Creates a new Submesh from the passed Mesh.\n */\n SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {\n var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);\n if (!this.IsGlobal) {\n var boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return result;\n }\n result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);\n }\n return result;\n };\n // Dispose\n /**\n * Disposes the Submesh.\n * Returns nothing.\n */\n SubMesh.prototype.dispose = function () {\n if (this._linesIndexBuffer) {\n this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);\n this._linesIndexBuffer = null;\n }\n // Remove from mesh\n var index = this._mesh.subMeshes.indexOf(this);\n this._mesh.subMeshes.splice(index, 1);\n };\n // Statics\n /**\n * Creates a new Submesh from the passed parameters :\n * - materialIndex (integer) : the index of the main mesh material.\n * - startIndex (integer) : the index where to start the copy in the mesh indices array.\n * - indexCount (integer) : the number of indices to copy then from the startIndex.\n * - mesh (Mesh) : the main mesh to create the submesh from.\n * - renderingMesh (optional Mesh) : rendering mesh.\n */\n SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {\n var minVertexIndex = Number.MAX_VALUE;\n var maxVertexIndex = -Number.MAX_VALUE;\n renderingMesh = (renderingMesh || mesh);\n var indices = renderingMesh.getIndices();\n for (var index = startIndex; index < startIndex + indexCount; index++) {\n var vertexIndex = indices[index];\n if (vertexIndex < minVertexIndex)\n minVertexIndex = vertexIndex;\n if (vertexIndex > maxVertexIndex)\n maxVertexIndex = vertexIndex;\n }\n return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);\n };\n return SubMesh;\n }(BaseSubMesh));\n BABYLON.SubMesh = SubMesh;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.subMesh.js.map\n\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Manages the defines for the Material\n */\n var MaterialDefines = /** @class */ (function () {\n function MaterialDefines() {\n this._isDirty = true;\n /** @hidden */\n this._areLightsDirty = true;\n /** @hidden */\n this._areAttributesDirty = true;\n /** @hidden */\n this._areTexturesDirty = true;\n /** @hidden */\n this._areFresnelDirty = true;\n /** @hidden */\n this._areMiscDirty = true;\n /** @hidden */\n this._areImageProcessingDirty = true;\n /** @hidden */\n this._normals = false;\n /** @hidden */\n this._uvs = false;\n /** @hidden */\n this._needNormals = false;\n /** @hidden */\n this._needUVs = false;\n }\n Object.defineProperty(MaterialDefines.prototype, \"isDirty\", {\n /**\n * Specifies if the material needs to be re-calculated\n */\n get: function () {\n return this._isDirty;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Marks the material to indicate that it has been re-calculated\n */\n MaterialDefines.prototype.markAsProcessed = function () {\n this._isDirty = false;\n this._areAttributesDirty = false;\n this._areTexturesDirty = false;\n this._areFresnelDirty = false;\n this._areLightsDirty = false;\n this._areMiscDirty = false;\n this._areImageProcessingDirty = false;\n };\n /**\n * Marks the material to indicate that it needs to be re-calculated\n */\n MaterialDefines.prototype.markAsUnprocessed = function () {\n this._isDirty = true;\n };\n /**\n * Marks the material to indicate all of its defines need to be re-calculated\n */\n MaterialDefines.prototype.markAllAsDirty = function () {\n this._areTexturesDirty = true;\n this._areAttributesDirty = true;\n this._areLightsDirty = true;\n this._areFresnelDirty = true;\n this._areMiscDirty = true;\n this._areImageProcessingDirty = true;\n this._isDirty = true;\n };\n /**\n * Marks the material to indicate that image processing needs to be re-calculated\n */\n MaterialDefines.prototype.markAsImageProcessingDirty = function () {\n this._areImageProcessingDirty = true;\n this._isDirty = true;\n };\n /**\n * Marks the material to indicate the lights need to be re-calculated\n */\n MaterialDefines.prototype.markAsLightDirty = function () {\n this._areLightsDirty = true;\n this._isDirty = true;\n };\n /**\n * Marks the attribute state as changed\n */\n MaterialDefines.prototype.markAsAttributesDirty = function () {\n this._areAttributesDirty = true;\n this._isDirty = true;\n };\n /**\n * Marks the texture state as changed\n */\n MaterialDefines.prototype.markAsTexturesDirty = function () {\n this._areTexturesDirty = true;\n this._isDirty = true;\n };\n /**\n * Marks the fresnel state as changed\n */\n MaterialDefines.prototype.markAsFresnelDirty = function () {\n this._areFresnelDirty = true;\n this._isDirty = true;\n };\n /**\n * Marks the misc state as changed\n */\n MaterialDefines.prototype.markAsMiscDirty = function () {\n this._areMiscDirty = true;\n this._isDirty = true;\n };\n /**\n * Rebuilds the material defines\n */\n MaterialDefines.prototype.rebuild = function () {\n if (this._keys) {\n delete this._keys;\n }\n this._keys = [];\n for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {\n var key = _a[_i];\n if (key[0] === \"_\") {\n continue;\n }\n this._keys.push(key);\n }\n };\n /**\n * Specifies if two material defines are equal\n * @param other - A material define instance to compare to\n * @returns - Boolean indicating if the material defines are equal (true) or not (false)\n */\n MaterialDefines.prototype.isEqual = function (other) {\n if (this._keys.length !== other._keys.length) {\n return false;\n }\n for (var index = 0; index < this._keys.length; index++) {\n var prop = this._keys[index];\n if (this[prop] !== other[prop]) {\n return false;\n }\n }\n return true;\n };\n /**\n * Clones this instance's defines to another instance\n * @param other - material defines to clone values to\n */\n MaterialDefines.prototype.cloneTo = function (other) {\n if (this._keys.length !== other._keys.length) {\n other._keys = this._keys.slice(0);\n }\n for (var index = 0; index < this._keys.length; index++) {\n var prop = this._keys[index];\n other[prop] = this[prop];\n }\n };\n /**\n * Resets the material define values\n */\n MaterialDefines.prototype.reset = function () {\n for (var index = 0; index < this._keys.length; index++) {\n var prop = this._keys[index];\n var type = typeof this[prop];\n switch (type) {\n case \"number\":\n this[prop] = 0;\n break;\n case \"string\":\n this[prop] = \"\";\n break;\n default:\n this[prop] = false;\n break;\n }\n }\n };\n /**\n * Converts the material define values to a string\n * @returns - String of material define information\n */\n MaterialDefines.prototype.toString = function () {\n var result = \"\";\n for (var index = 0; index < this._keys.length; index++) {\n var prop = this._keys[index];\n var value = this[prop];\n var type = typeof value;\n switch (type) {\n case \"number\":\n case \"string\":\n result += \"#define \" + prop + \" \" + value + \"\\n\";\n break;\n default:\n if (value) {\n result += \"#define \" + prop + \"\\n\";\n }\n break;\n }\n }\n return result;\n };\n return MaterialDefines;\n }());\n BABYLON.MaterialDefines = MaterialDefines;\n /**\n * Base class for the main features of a material in Babylon.js\n */\n var Material = /** @class */ (function () {\n /**\n * Creates a material instance\n * @param name defines the name of the material\n * @param scene defines the scene to reference\n * @param doNotAdd specifies if the material should be added to the scene\n */\n function Material(name, scene, doNotAdd) {\n /**\n * Specifies if the ready state should be checked on each call\n */\n this.checkReadyOnEveryCall = false;\n /**\n * Specifies if the ready state should be checked once\n */\n this.checkReadyOnlyOnce = false;\n /**\n * The state of the material\n */\n this.state = \"\";\n /**\n * The alpha value of the material\n */\n this._alpha = 1.0;\n /**\n * Specifies if back face culling is enabled\n */\n this._backFaceCulling = true;\n /**\n * Specifies if the material should be serialized\n */\n this.doNotSerialize = false;\n /**\n * Specifies if the effect should be stored on sub meshes\n */\n this.storeEffectOnSubMeshes = false;\n /**\n * An event triggered when the material is disposed\n */\n this.onDisposeObservable = new BABYLON.Observable();\n /**\n * An event triggered when the material is bound\n */\n this.onBindObservable = new BABYLON.Observable();\n /**\n * An event triggered when the material is unbound\n */\n this.onUnBindObservable = new BABYLON.Observable();\n /**\n * Stores the value of the alpha mode\n */\n this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;\n /**\n * Stores the state of the need depth pre-pass value\n */\n this._needDepthPrePass = false;\n /**\n * Specifies if depth writing should be disabled\n */\n this.disableDepthWrite = false;\n /**\n * Specifies if depth writing should be forced\n */\n this.forceDepthWrite = false;\n /**\n * Specifies if there should be a separate pass for culling\n */\n this.separateCullingPass = false;\n /**\n * Stores the state specifing if fog should be enabled\n */\n this._fogEnabled = true;\n /**\n * Stores the size of points\n */\n this.pointSize = 1.0;\n /**\n * Stores the z offset value\n */\n this.zOffset = 0;\n /**\n * Specifies if the material was previously ready\n */\n this._wasPreviouslyReady = false;\n /**\n * Stores the fill mode state\n */\n this._fillMode = Material.TriangleFillMode;\n this.name = name;\n this.id = name || BABYLON.Tools.RandomId();\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this.uniqueId = this._scene.getUniqueId();\n if (this._scene.useRightHandedSystem) {\n this.sideOrientation = Material.ClockWiseSideOrientation;\n }\n else {\n this.sideOrientation = Material.CounterClockWiseSideOrientation;\n }\n this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());\n this._useUBO = this.getScene().getEngine().supportsUniformBuffers;\n if (!doNotAdd) {\n this._scene.materials.push(this);\n }\n }\n Object.defineProperty(Material, \"TriangleFillMode\", {\n /**\n * Returns the triangle fill mode\n */\n get: function () {\n return Material._TriangleFillMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"WireFrameFillMode\", {\n /**\n * Returns the wireframe mode\n */\n get: function () {\n return Material._WireFrameFillMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"PointFillMode\", {\n /**\n * Returns the point fill mode\n */\n get: function () {\n return Material._PointFillMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"PointListDrawMode\", {\n /**\n * Returns the point list draw mode\n */\n get: function () {\n return Material._PointListDrawMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"LineListDrawMode\", {\n /**\n * Returns the line list draw mode\n */\n get: function () {\n return Material._LineListDrawMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"LineLoopDrawMode\", {\n /**\n * Returns the line loop draw mode\n */\n get: function () {\n return Material._LineLoopDrawMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"LineStripDrawMode\", {\n /**\n * Returns the line strip draw mode\n */\n get: function () {\n return Material._LineStripDrawMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"TriangleStripDrawMode\", {\n /**\n * Returns the triangle strip draw mode\n */\n get: function () {\n return Material._TriangleStripDrawMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"TriangleFanDrawMode\", {\n /**\n * Returns the triangle fan draw mode\n */\n get: function () {\n return Material._TriangleFanDrawMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"ClockWiseSideOrientation\", {\n /**\n * Returns the clock-wise side orientation\n */\n get: function () {\n return Material._ClockWiseSideOrientation;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"CounterClockWiseSideOrientation\", {\n /**\n * Returns the counter clock-wise side orientation\n */\n get: function () {\n return Material._CounterClockWiseSideOrientation;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"TextureDirtyFlag\", {\n /**\n * Returns the dirty texture flag value\n */\n get: function () {\n return Material._TextureDirtyFlag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"LightDirtyFlag\", {\n /**\n * Returns the dirty light flag value\n */\n get: function () {\n return Material._LightDirtyFlag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"FresnelDirtyFlag\", {\n /**\n * Returns the dirty fresnel flag value\n */\n get: function () {\n return Material._FresnelDirtyFlag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"AttributesDirtyFlag\", {\n /**\n * Returns the dirty attributes flag value\n */\n get: function () {\n return Material._AttributesDirtyFlag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"MiscDirtyFlag\", {\n /**\n * Returns the dirty misc flag value\n */\n get: function () {\n return Material._MiscDirtyFlag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"alpha\", {\n /**\n * Gets the alpha value of the material\n */\n get: function () {\n return this._alpha;\n },\n /**\n * Sets the alpha value of the material\n */\n set: function (value) {\n if (this._alpha === value) {\n return;\n }\n this._alpha = value;\n this.markAsDirty(Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"backFaceCulling\", {\n /**\n * Gets the back-face culling state\n */\n get: function () {\n return this._backFaceCulling;\n },\n /**\n * Sets the back-face culling state\n */\n set: function (value) {\n if (this._backFaceCulling === value) {\n return;\n }\n this._backFaceCulling = value;\n this.markAsDirty(Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"onDispose\", {\n /**\n * Called during a dispose event\n */\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"onBind\", {\n /**\n * Called during a bind event\n */\n set: function (callback) {\n if (this._onBindObserver) {\n this.onBindObservable.remove(this._onBindObserver);\n }\n this._onBindObserver = this.onBindObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"alphaMode\", {\n /**\n * Gets the value of the alpha mode\n */\n get: function () {\n return this._alphaMode;\n },\n /**\n * Sets the value of the alpha mode.\n *\n * | Value | Type | Description |\n * | --- | --- | --- |\n * | 0 | ALPHA_DISABLE | |\n * | 1 | ALPHA_ADD | |\n * | 2 | ALPHA_COMBINE | |\n * | 3 | ALPHA_SUBTRACT | |\n * | 4 | ALPHA_MULTIPLY | |\n * | 5 | ALPHA_MAXIMIZED | |\n * | 6 | ALPHA_ONEONE | |\n * | 7 | ALPHA_PREMULTIPLIED | |\n * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |\n * | 9 | ALPHA_INTERPOLATE | |\n * | 10 | ALPHA_SCREENMODE | |\n *\n */\n set: function (value) {\n if (this._alphaMode === value) {\n return;\n }\n this._alphaMode = value;\n this.markAsDirty(Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"needDepthPrePass\", {\n /**\n * Gets the depth pre-pass value\n */\n get: function () {\n return this._needDepthPrePass;\n },\n /**\n * Sets the need depth pre-pass value\n */\n set: function (value) {\n if (this._needDepthPrePass === value) {\n return;\n }\n this._needDepthPrePass = value;\n if (this._needDepthPrePass) {\n this.checkReadyOnEveryCall = true;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"fogEnabled\", {\n /**\n * Gets the value of the fog enabled state\n */\n get: function () {\n return this._fogEnabled;\n },\n /**\n * Sets the state for enabling fog\n */\n set: function (value) {\n if (this._fogEnabled === value) {\n return;\n }\n this._fogEnabled = value;\n this.markAsDirty(Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"wireframe\", {\n /**\n * Gets a value specifying if wireframe mode is enabled\n */\n get: function () {\n switch (this._fillMode) {\n case Material.WireFrameFillMode:\n case Material.LineListDrawMode:\n case Material.LineLoopDrawMode:\n case Material.LineStripDrawMode:\n return true;\n }\n return this._scene.forceWireframe;\n },\n /**\n * Sets the state of wireframe mode\n */\n set: function (value) {\n this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"pointsCloud\", {\n /**\n * Gets the value specifying if point clouds are enabled\n */\n get: function () {\n switch (this._fillMode) {\n case Material.PointFillMode:\n case Material.PointListDrawMode:\n return true;\n }\n return this._scene.forcePointsCloud;\n },\n /**\n * Sets the state of point cloud mode\n */\n set: function (value) {\n this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"fillMode\", {\n /**\n * Gets the material fill mode\n */\n get: function () {\n return this._fillMode;\n },\n /**\n * Sets the material fill mode\n */\n set: function (value) {\n if (this._fillMode === value) {\n return;\n }\n this._fillMode = value;\n this.markAsDirty(Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a string representation of the current material\n * @param fullDetails defines a boolean indicating which levels of logging is desired\n * @returns a string with material information\n */\n Material.prototype.toString = function (fullDetails) {\n var ret = \"Name: \" + this.name;\n if (fullDetails) {\n }\n return ret;\n };\n /**\n * Gets the class name of the material\n * @returns a string with the class name of the material\n */\n Material.prototype.getClassName = function () {\n return \"Material\";\n };\n Object.defineProperty(Material.prototype, \"isFrozen\", {\n /**\n * Specifies if updates for the material been locked\n */\n get: function () {\n return this.checkReadyOnlyOnce;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Locks updates for the material\n */\n Material.prototype.freeze = function () {\n this.checkReadyOnlyOnce = true;\n };\n /**\n * Unlocks updates for the material\n */\n Material.prototype.unfreeze = function () {\n this.checkReadyOnlyOnce = false;\n };\n /**\n * Specifies if the material is ready to be used\n * @param mesh defines the mesh to check\n * @param useInstances specifies if instances should be used\n * @returns a boolean indicating if the material is ready to be used\n */\n Material.prototype.isReady = function (mesh, useInstances) {\n return true;\n };\n /**\n * Specifies that the submesh is ready to be used\n * @param mesh defines the mesh to check\n * @param subMesh defines which submesh to check\n * @param useInstances specifies that instances should be used\n * @returns a boolean indicating that the submesh is ready or not\n */\n Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {\n return false;\n };\n /**\n * Returns the material effect\n * @returns the effect associated with the material\n */\n Material.prototype.getEffect = function () {\n return this._effect;\n };\n /**\n * Returns the current scene\n * @returns a Scene\n */\n Material.prototype.getScene = function () {\n return this._scene;\n };\n /**\n * Specifies if the material will require alpha blending\n * @returns a boolean specifying if alpha blending is needed\n */\n Material.prototype.needAlphaBlending = function () {\n return (this.alpha < 1.0);\n };\n /**\n * Specifies if the mesh will require alpha blending\n * @param mesh defines the mesh to check\n * @returns a boolean specifying if alpha blending is needed for the mesh\n */\n Material.prototype.needAlphaBlendingForMesh = function (mesh) {\n return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;\n };\n /**\n * Specifies if this material should be rendered in alpha test mode\n * @returns a boolean specifying if an alpha test is needed.\n */\n Material.prototype.needAlphaTesting = function () {\n return false;\n };\n /**\n * Gets the texture used for the alpha test\n * @returns the texture to use for alpha testing\n */\n Material.prototype.getAlphaTestTexture = function () {\n return null;\n };\n /**\n * Marks the material to indicate that it needs to be re-calculated\n */\n Material.prototype.markDirty = function () {\n this._wasPreviouslyReady = false;\n };\n /** @hidden */\n Material.prototype._preBind = function (effect, overrideOrientation) {\n if (overrideOrientation === void 0) { overrideOrientation = null; }\n var engine = this._scene.getEngine();\n var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;\n var reverse = orientation === Material.ClockWiseSideOrientation;\n engine.enableEffect(effect ? effect : this._effect);\n engine.setState(this.backFaceCulling, this.zOffset, false, reverse);\n return reverse;\n };\n /**\n * Binds the material to the mesh\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh to bind the material to\n */\n Material.prototype.bind = function (world, mesh) {\n };\n /**\n * Binds the submesh to the material\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh containing the submesh\n * @param subMesh defines the submesh to bind the material to\n */\n Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {\n };\n /**\n * Binds the world matrix to the material\n * @param world defines the world transformation matrix\n */\n Material.prototype.bindOnlyWorldMatrix = function (world) {\n };\n /**\n * Binds the scene's uniform buffer to the effect.\n * @param effect defines the effect to bind to the scene uniform buffer\n * @param sceneUbo defines the uniform buffer storing scene data\n */\n Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {\n sceneUbo.bindToEffect(effect, \"Scene\");\n };\n /**\n * Binds the view matrix to the effect\n * @param effect defines the effect to bind the view matrix to\n */\n Material.prototype.bindView = function (effect) {\n if (!this._useUBO) {\n effect.setMatrix(\"view\", this.getScene().getViewMatrix());\n }\n else {\n this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());\n }\n };\n /**\n * Binds the view projection matrix to the effect\n * @param effect defines the effect to bind the view projection matrix to\n */\n Material.prototype.bindViewProjection = function (effect) {\n if (!this._useUBO) {\n effect.setMatrix(\"viewProjection\", this.getScene().getTransformMatrix());\n }\n else {\n this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());\n }\n };\n /**\n * Specifies if material alpha testing should be turned on for the mesh\n * @param mesh defines the mesh to check\n */\n Material.prototype._shouldTurnAlphaTestOn = function (mesh) {\n return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());\n };\n /**\n * Processes to execute after binding the material to a mesh\n * @param mesh defines the rendered mesh\n */\n Material.prototype._afterBind = function (mesh) {\n this._scene._cachedMaterial = this;\n if (mesh) {\n this._scene._cachedVisibility = mesh.visibility;\n }\n else {\n this._scene._cachedVisibility = 1;\n }\n if (mesh) {\n this.onBindObservable.notifyObservers(mesh);\n }\n if (this.disableDepthWrite) {\n var engine = this._scene.getEngine();\n this._cachedDepthWriteState = engine.getDepthWrite();\n engine.setDepthWrite(false);\n }\n };\n /**\n * Unbinds the material from the mesh\n */\n Material.prototype.unbind = function () {\n this.onUnBindObservable.notifyObservers(this);\n if (this.disableDepthWrite) {\n var engine = this._scene.getEngine();\n engine.setDepthWrite(this._cachedDepthWriteState);\n }\n };\n /**\n * Gets the active textures from the material\n * @returns an array of textures\n */\n Material.prototype.getActiveTextures = function () {\n return [];\n };\n /**\n * Specifies if the material uses a texture\n * @param texture defines the texture to check against the material\n * @returns a boolean specifying if the material uses the texture\n */\n Material.prototype.hasTexture = function (texture) {\n return false;\n };\n /**\n * Makes a duplicate of the material, and gives it a new name\n * @param name defines the new name for the duplicated material\n * @returns the cloned material\n */\n Material.prototype.clone = function (name) {\n return null;\n };\n /**\n * Gets the meshes bound to the material\n * @returns an array of meshes bound to the material\n */\n Material.prototype.getBindedMeshes = function () {\n var result = new Array();\n for (var index = 0; index < this._scene.meshes.length; index++) {\n var mesh = this._scene.meshes[index];\n if (mesh.material === this) {\n result.push(mesh);\n }\n }\n return result;\n };\n /**\n * Force shader compilation\n * @param mesh defines the mesh associated with this material\n * @param onCompiled defines a function to execute once the material is compiled\n * @param options defines the options to configure the compilation\n */\n Material.prototype.forceCompilation = function (mesh, onCompiled, options) {\n var _this = this;\n var localOptions = __assign({ clipPlane: false }, options);\n var subMesh = new BABYLON.BaseSubMesh();\n var scene = this.getScene();\n var checkReady = function () {\n if (!_this._scene || !_this._scene.getEngine()) {\n return;\n }\n if (subMesh._materialDefines) {\n subMesh._materialDefines._renderId = -1;\n }\n var clipPlaneState = scene.clipPlane;\n if (localOptions.clipPlane) {\n scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);\n }\n if (_this.storeEffectOnSubMeshes) {\n if (_this.isReadyForSubMesh(mesh, subMesh)) {\n if (onCompiled) {\n onCompiled(_this);\n }\n }\n else {\n setTimeout(checkReady, 16);\n }\n }\n else {\n if (_this.isReady(mesh)) {\n if (onCompiled) {\n onCompiled(_this);\n }\n }\n else {\n setTimeout(checkReady, 16);\n }\n }\n if (localOptions.clipPlane) {\n scene.clipPlane = clipPlaneState;\n }\n };\n checkReady();\n };\n /**\n * Force shader compilation\n * @param mesh defines the mesh that will use this material\n * @param options defines additional options for compiling the shaders\n * @returns a promise that resolves when the compilation completes\n */\n Material.prototype.forceCompilationAsync = function (mesh, options) {\n var _this = this;\n return new Promise(function (resolve) {\n _this.forceCompilation(mesh, function () {\n resolve();\n }, options);\n });\n };\n /**\n * Marks a define in the material to indicate that it needs to be re-computed\n * @param flag defines a flag used to determine which parts of the material have to be marked as dirty\n */\n Material.prototype.markAsDirty = function (flag) {\n if (flag & Material.TextureDirtyFlag) {\n this._markAllSubMeshesAsTexturesDirty();\n }\n if (flag & Material.LightDirtyFlag) {\n this._markAllSubMeshesAsLightsDirty();\n }\n if (flag & Material.FresnelDirtyFlag) {\n this._markAllSubMeshesAsFresnelDirty();\n }\n if (flag & Material.AttributesDirtyFlag) {\n this._markAllSubMeshesAsAttributesDirty();\n }\n if (flag & Material.MiscDirtyFlag) {\n this._markAllSubMeshesAsMiscDirty();\n }\n this.getScene().resetCachedMaterial();\n };\n /**\n * Marks all submeshes of a material to indicate that their material defines need to be re-calculated\n * @param func defines a function which checks material defines against the submeshes\n */\n Material.prototype._markAllSubMeshesAsDirty = function (func) {\n for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n if (!mesh.subMeshes) {\n continue;\n }\n for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {\n var subMesh = _c[_b];\n if (subMesh.getMaterial() !== this) {\n continue;\n }\n if (!subMesh._materialDefines) {\n continue;\n }\n func(subMesh._materialDefines);\n }\n }\n };\n /**\n * Indicates that image processing needs to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });\n };\n /**\n * Indicates that textures need to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsTexturesDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });\n };\n /**\n * Indicates that fresnel needs to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsFresnelDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });\n };\n /**\n * Indicates that fresnel and misc need to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) {\n defines.markAsFresnelDirty();\n defines.markAsMiscDirty();\n });\n };\n /**\n * Indicates that lights need to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsLightsDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });\n };\n /**\n * Indicates that attributes need to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsAttributesDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });\n };\n /**\n * Indicates that misc needs to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsMiscDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });\n };\n /**\n * Indicates that textures and misc need to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) {\n defines.markAsTexturesDirty();\n defines.markAsMiscDirty();\n });\n };\n /**\n * Disposes the material\n * @param forceDisposeEffect specifies if effects should be forcefully disposed\n * @param forceDisposeTextures specifies if textures should be forcefully disposed\n */\n Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {\n // Animations\n this.getScene().stopAnimation(this);\n this.getScene().freeProcessedMaterials();\n // Remove from scene\n var index = this._scene.materials.indexOf(this);\n if (index >= 0) {\n this._scene.materials.splice(index, 1);\n }\n // Remove from meshes\n for (index = 0; index < this._scene.meshes.length; index++) {\n var mesh = this._scene.meshes[index];\n if (mesh.material === this) {\n mesh.material = null;\n if (mesh.geometry) {\n var geometry = (mesh.geometry);\n if (this.storeEffectOnSubMeshes) {\n for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n geometry._releaseVertexArrayObject(subMesh._materialEffect);\n if (forceDisposeEffect && subMesh._materialEffect) {\n this._scene.getEngine()._releaseEffect(subMesh._materialEffect);\n }\n }\n }\n else {\n geometry._releaseVertexArrayObject(this._effect);\n }\n }\n }\n }\n this._uniformBuffer.dispose();\n // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect\n if (forceDisposeEffect && this._effect) {\n if (!this.storeEffectOnSubMeshes) {\n this._scene.getEngine()._releaseEffect(this._effect);\n }\n this._effect = null;\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onBindObservable.clear();\n this.onUnBindObservable.clear();\n };\n /**\n * Serializes this material\n * @returns the serialized material object\n */\n Material.prototype.serialize = function () {\n return BABYLON.SerializationHelper.Serialize(this);\n };\n /**\n * Creates a MultiMaterial from parsed MultiMaterial data.\n * @param parsedMultiMaterial defines parsed MultiMaterial data.\n * @param scene defines the hosting scene\n * @returns a new MultiMaterial\n */\n Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {\n var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);\n multiMaterial.id = parsedMultiMaterial.id;\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);\n }\n for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {\n var subMatId = parsedMultiMaterial.materials[matIndex];\n if (subMatId) {\n multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));\n }\n else {\n multiMaterial.subMaterials.push(null);\n }\n }\n return multiMaterial;\n };\n /**\n * Creates a material from parsed material data\n * @param parsedMaterial defines parsed material data\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures\n * @returns a new material\n */\n Material.Parse = function (parsedMaterial, scene, rootUrl) {\n if (!parsedMaterial.customType || parsedMaterial.customType === \"BABYLON.StandardMaterial\") {\n return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);\n }\n if (parsedMaterial.customType === \"BABYLON.PBRMaterial\" && parsedMaterial.overloadedAlbedo) {\n parsedMaterial.customType = \"BABYLON.LegacyPBRMaterial\";\n if (!BABYLON.LegacyPBRMaterial) {\n BABYLON.Tools.Error(\"Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.\");\n return;\n }\n }\n var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);\n return materialType.Parse(parsedMaterial, scene, rootUrl);\n };\n // Triangle views\n Material._TriangleFillMode = 0;\n Material._WireFrameFillMode = 1;\n Material._PointFillMode = 2;\n // Draw modes\n Material._PointListDrawMode = 3;\n Material._LineListDrawMode = 4;\n Material._LineLoopDrawMode = 5;\n Material._LineStripDrawMode = 6;\n Material._TriangleStripDrawMode = 7;\n Material._TriangleFanDrawMode = 8;\n /**\n * Stores the clock-wise side orientation\n */\n Material._ClockWiseSideOrientation = 0;\n /**\n * Stores the counter clock-wise side orientation\n */\n Material._CounterClockWiseSideOrientation = 1;\n /**\n * The dirty texture flag value\n */\n Material._TextureDirtyFlag = 1;\n /**\n * The dirty light flag value\n */\n Material._LightDirtyFlag = 2;\n /**\n * The dirty fresnel flag value\n */\n Material._FresnelDirtyFlag = 4;\n /**\n * The dirty attribute flag value\n */\n Material._AttributesDirtyFlag = 8;\n /**\n * The dirty misc flag value\n */\n Material._MiscDirtyFlag = 16;\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"id\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"uniqueId\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"name\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"checkReadyOnEveryCall\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"checkReadyOnlyOnce\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"state\", void 0);\n __decorate([\n BABYLON.serialize(\"alpha\")\n ], Material.prototype, \"_alpha\", void 0);\n __decorate([\n BABYLON.serialize(\"backFaceCulling\")\n ], Material.prototype, \"_backFaceCulling\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"sideOrientation\", void 0);\n __decorate([\n BABYLON.serialize(\"alphaMode\")\n ], Material.prototype, \"_alphaMode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"_needDepthPrePass\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"disableDepthWrite\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"forceDepthWrite\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"separateCullingPass\", void 0);\n __decorate([\n BABYLON.serialize(\"fogEnabled\")\n ], Material.prototype, \"_fogEnabled\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"pointSize\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"zOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"wireframe\", null);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"pointsCloud\", null);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"fillMode\", null);\n return Material;\n }());\n BABYLON.Material = Material;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.material.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var UniformBuffer = /** @class */ (function () {\n /**\n * Uniform buffer objects.\n *\n * Handles blocks of uniform on the GPU.\n *\n * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.\n *\n * For more information, please refer to :\n * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object\n */\n function UniformBuffer(engine, data, dynamic) {\n this._engine = engine;\n this._noUBO = !engine.supportsUniformBuffers;\n this._dynamic = dynamic;\n this._data = data || [];\n this._uniformLocations = {};\n this._uniformSizes = {};\n this._uniformLocationPointer = 0;\n this._needSync = false;\n if (this._noUBO) {\n this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;\n this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;\n this.updateFloat = this._updateFloatForEffect;\n this.updateFloat2 = this._updateFloat2ForEffect;\n this.updateFloat3 = this._updateFloat3ForEffect;\n this.updateFloat4 = this._updateFloat4ForEffect;\n this.updateMatrix = this._updateMatrixForEffect;\n this.updateVector3 = this._updateVector3ForEffect;\n this.updateVector4 = this._updateVector4ForEffect;\n this.updateColor3 = this._updateColor3ForEffect;\n this.updateColor4 = this._updateColor4ForEffect;\n }\n else {\n this._engine._uniformBuffers.push(this);\n this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;\n this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;\n this.updateFloat = this._updateFloatForUniform;\n this.updateFloat2 = this._updateFloat2ForUniform;\n this.updateFloat3 = this._updateFloat3ForUniform;\n this.updateFloat4 = this._updateFloat4ForUniform;\n this.updateMatrix = this._updateMatrixForUniform;\n this.updateVector3 = this._updateVector3ForUniform;\n this.updateVector4 = this._updateVector4ForUniform;\n this.updateColor3 = this._updateColor3ForUniform;\n this.updateColor4 = this._updateColor4ForUniform;\n }\n }\n Object.defineProperty(UniformBuffer.prototype, \"useUbo\", {\n // Properties\n /**\n * Indicates if the buffer is using the WebGL2 UBO implementation,\n * or just falling back on setUniformXXX calls.\n */\n get: function () {\n return !this._noUBO;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(UniformBuffer.prototype, \"isSync\", {\n /**\n * Indicates if the WebGL underlying uniform buffer is in sync\n * with the javascript cache data.\n */\n get: function () {\n return !this._needSync;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Indicates if the WebGL underlying uniform buffer is dynamic.\n * Also, a dynamic UniformBuffer will disable cache verification and always\n * update the underlying WebGL uniform buffer to the GPU.\n */\n UniformBuffer.prototype.isDynamic = function () {\n return this._dynamic !== undefined;\n };\n /**\n * The data cache on JS side.\n */\n UniformBuffer.prototype.getData = function () {\n return this._bufferData;\n };\n /**\n * The underlying WebGL Uniform buffer.\n */\n UniformBuffer.prototype.getBuffer = function () {\n return this._buffer;\n };\n /**\n * std140 layout specifies how to align data within an UBO structure.\n * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159\n * for specs.\n */\n UniformBuffer.prototype._fillAlignment = function (size) {\n // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components\n // and 4x4 matrices\n // TODO : change if other types are used\n var alignment;\n if (size <= 2) {\n alignment = size;\n }\n else {\n alignment = 4;\n }\n if ((this._uniformLocationPointer % alignment) !== 0) {\n var oldPointer = this._uniformLocationPointer;\n this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);\n var diff = this._uniformLocationPointer - oldPointer;\n for (var i = 0; i < diff; i++) {\n this._data.push(0);\n }\n }\n };\n /**\n * Adds an uniform in the buffer.\n * Warning : the subsequents calls of this function must be in the same order as declared in the shader\n * for the layout to be correct !\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {number|number[]} size Data size, or data directly.\n */\n UniformBuffer.prototype.addUniform = function (name, size) {\n if (this._noUBO) {\n return;\n }\n if (this._uniformLocations[name] !== undefined) {\n // Already existing uniform\n return;\n }\n // This function must be called in the order of the shader layout !\n // size can be the size of the uniform, or data directly\n var data;\n if (size instanceof Array) {\n data = size;\n size = data.length;\n }\n else {\n size = size;\n data = [];\n // Fill with zeros\n for (var i = 0; i < size; i++) {\n data.push(0);\n }\n }\n this._fillAlignment(size);\n this._uniformSizes[name] = size;\n this._uniformLocations[name] = this._uniformLocationPointer;\n this._uniformLocationPointer += size;\n for (var i = 0; i < size; i++) {\n this._data.push(data[i]);\n }\n this._needSync = true;\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {Matrix} mat A 4x4 matrix.\n */\n UniformBuffer.prototype.addMatrix = function (name, mat) {\n this.addUniform(name, Array.prototype.slice.call(mat.toArray()));\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {number} x\n * @param {number} y\n */\n UniformBuffer.prototype.addFloat2 = function (name, x, y) {\n var temp = [x, y];\n this.addUniform(name, temp);\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {number} x\n * @param {number} y\n * @param {number} z\n */\n UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {\n var temp = [x, y, z];\n this.addUniform(name, temp);\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {Color3} color\n */\n UniformBuffer.prototype.addColor3 = function (name, color) {\n var temp = new Array();\n color.toArray(temp);\n this.addUniform(name, temp);\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {Color3} color\n * @param {number} alpha\n */\n UniformBuffer.prototype.addColor4 = function (name, color, alpha) {\n var temp = new Array();\n color.toArray(temp);\n temp.push(alpha);\n this.addUniform(name, temp);\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {Vector3} vector\n */\n UniformBuffer.prototype.addVector3 = function (name, vector) {\n var temp = new Array();\n vector.toArray(temp);\n this.addUniform(name, temp);\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n */\n UniformBuffer.prototype.addMatrix3x3 = function (name) {\n this.addUniform(name, 12);\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n */\n UniformBuffer.prototype.addMatrix2x2 = function (name) {\n this.addUniform(name, 8);\n };\n /**\n * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.\n */\n UniformBuffer.prototype.create = function () {\n if (this._noUBO) {\n return;\n }\n if (this._buffer) {\n return; // nothing to do\n }\n // See spec, alignment must be filled as a vec4\n this._fillAlignment(4);\n this._bufferData = new Float32Array(this._data);\n this._rebuild();\n this._needSync = true;\n };\n UniformBuffer.prototype._rebuild = function () {\n if (this._noUBO) {\n return;\n }\n if (this._dynamic) {\n this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);\n }\n else {\n this._buffer = this._engine.createUniformBuffer(this._bufferData);\n }\n };\n /**\n * Updates the WebGL Uniform Buffer on the GPU.\n * If the `dynamic` flag is set to true, no cache comparison is done.\n * Otherwise, the buffer will be updated only if the cache differs.\n */\n UniformBuffer.prototype.update = function () {\n if (!this._buffer) {\n this.create();\n return;\n }\n if (!this._dynamic && !this._needSync) {\n return;\n }\n this._engine.updateUniformBuffer(this._buffer, this._bufferData);\n this._needSync = false;\n };\n /**\n * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.\n * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.\n * @param {number[]|Float32Array} data Flattened data\n * @param {number} size Size of the data.\n */\n UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {\n var location = this._uniformLocations[uniformName];\n if (location === undefined) {\n if (this._buffer) {\n // Cannot add an uniform if the buffer is already created\n BABYLON.Tools.Error(\"Cannot add an uniform after UBO has been created.\");\n return;\n }\n this.addUniform(uniformName, size);\n location = this._uniformLocations[uniformName];\n }\n if (!this._buffer) {\n this.create();\n }\n if (!this._dynamic) {\n // Cache for static uniform buffers\n var changed = false;\n for (var i = 0; i < size; i++) {\n if (this._bufferData[location + i] !== data[i]) {\n changed = true;\n this._bufferData[location + i] = data[i];\n }\n }\n this._needSync = this._needSync || changed;\n }\n else {\n // No cache for dynamic\n for (var i = 0; i < size; i++) {\n this._bufferData[location + i] = data[i];\n }\n }\n };\n // Update methods\n UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {\n // To match std140, matrix must be realigned\n for (var i = 0; i < 3; i++) {\n UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];\n UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];\n UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];\n UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;\n }\n this.updateUniform(name, UniformBuffer._tempBuffer, 12);\n };\n UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {\n this._currentEffect.setMatrix3x3(name, matrix);\n };\n UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {\n this._currentEffect.setMatrix2x2(name, matrix);\n };\n UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {\n // To match std140, matrix must be realigned\n for (var i = 0; i < 2; i++) {\n UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];\n UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];\n UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;\n UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;\n }\n this.updateUniform(name, UniformBuffer._tempBuffer, 8);\n };\n UniformBuffer.prototype._updateFloatForEffect = function (name, x) {\n this._currentEffect.setFloat(name, x);\n };\n UniformBuffer.prototype._updateFloatForUniform = function (name, x) {\n UniformBuffer._tempBuffer[0] = x;\n this.updateUniform(name, UniformBuffer._tempBuffer, 1);\n };\n UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n this._currentEffect.setFloat2(name + suffix, x, y);\n };\n UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n UniformBuffer._tempBuffer[0] = x;\n UniformBuffer._tempBuffer[1] = y;\n this.updateUniform(name, UniformBuffer._tempBuffer, 2);\n };\n UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n this._currentEffect.setFloat3(name + suffix, x, y, z);\n };\n UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n UniformBuffer._tempBuffer[0] = x;\n UniformBuffer._tempBuffer[1] = y;\n UniformBuffer._tempBuffer[2] = z;\n this.updateUniform(name, UniformBuffer._tempBuffer, 3);\n };\n UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n this._currentEffect.setFloat4(name + suffix, x, y, z, w);\n };\n UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n UniformBuffer._tempBuffer[0] = x;\n UniformBuffer._tempBuffer[1] = y;\n UniformBuffer._tempBuffer[2] = z;\n UniformBuffer._tempBuffer[3] = w;\n this.updateUniform(name, UniformBuffer._tempBuffer, 4);\n };\n UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {\n this._currentEffect.setMatrix(name, mat);\n };\n UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {\n this.updateUniform(name, mat.toArray(), 16);\n };\n UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {\n this._currentEffect.setVector3(name, vector);\n };\n UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {\n vector.toArray(UniformBuffer._tempBuffer);\n this.updateUniform(name, UniformBuffer._tempBuffer, 3);\n };\n UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {\n this._currentEffect.setVector4(name, vector);\n };\n UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {\n vector.toArray(UniformBuffer._tempBuffer);\n this.updateUniform(name, UniformBuffer._tempBuffer, 4);\n };\n UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n this._currentEffect.setColor3(name + suffix, color);\n };\n UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n color.toArray(UniformBuffer._tempBuffer);\n this.updateUniform(name, UniformBuffer._tempBuffer, 3);\n };\n UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n this._currentEffect.setColor4(name + suffix, color, alpha);\n };\n UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n color.toArray(UniformBuffer._tempBuffer);\n UniformBuffer._tempBuffer[3] = alpha;\n this.updateUniform(name, UniformBuffer._tempBuffer, 4);\n };\n /**\n * Sets a sampler uniform on the effect.\n * @param {string} name Name of the sampler.\n * @param {Texture} texture\n */\n UniformBuffer.prototype.setTexture = function (name, texture) {\n this._currentEffect.setTexture(name, texture);\n };\n /**\n * Directly updates the value of the uniform in the cache AND on the GPU.\n * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.\n * @param {number[]|Float32Array} data Flattened data\n */\n UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {\n this.updateUniform(uniformName, data, data.length);\n this.update();\n };\n /**\n * Binds this uniform buffer to an effect.\n * @param {Effect} effect\n * @param {string} name Name of the uniform block in the shader.\n */\n UniformBuffer.prototype.bindToEffect = function (effect, name) {\n this._currentEffect = effect;\n if (this._noUBO || !this._buffer) {\n return;\n }\n effect.bindUniformBuffer(this._buffer, name);\n };\n /**\n * Disposes the uniform buffer.\n */\n UniformBuffer.prototype.dispose = function () {\n if (this._noUBO) {\n return;\n }\n var index = this._engine._uniformBuffers.indexOf(this);\n if (index !== -1) {\n this._engine._uniformBuffers.splice(index, 1);\n }\n if (!this._buffer) {\n return;\n }\n if (this._engine._releaseBuffer(this._buffer)) {\n this._buffer = null;\n }\n };\n // Pool for avoiding memory leaks\n UniformBuffer._MAX_UNIFORM_SIZE = 256;\n UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);\n return UniformBuffer;\n }());\n BABYLON.UniformBuffer = UniformBuffer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.uniformBuffer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance\n */\n var VertexData = /** @class */ (function () {\n function VertexData() {\n }\n /**\n * Uses the passed data array to set the set the values for the specified kind of data\n * @param data a linear array of floating numbers\n * @param kind the type of data that is being set, eg positions, colors etc\n */\n VertexData.prototype.set = function (data, kind) {\n switch (kind) {\n case BABYLON.VertexBuffer.PositionKind:\n this.positions = data;\n break;\n case BABYLON.VertexBuffer.NormalKind:\n this.normals = data;\n break;\n case BABYLON.VertexBuffer.TangentKind:\n this.tangents = data;\n break;\n case BABYLON.VertexBuffer.UVKind:\n this.uvs = data;\n break;\n case BABYLON.VertexBuffer.UV2Kind:\n this.uvs2 = data;\n break;\n case BABYLON.VertexBuffer.UV3Kind:\n this.uvs3 = data;\n break;\n case BABYLON.VertexBuffer.UV4Kind:\n this.uvs4 = data;\n break;\n case BABYLON.VertexBuffer.UV5Kind:\n this.uvs5 = data;\n break;\n case BABYLON.VertexBuffer.UV6Kind:\n this.uvs6 = data;\n break;\n case BABYLON.VertexBuffer.ColorKind:\n this.colors = data;\n break;\n case BABYLON.VertexBuffer.MatricesIndicesKind:\n this.matricesIndices = data;\n break;\n case BABYLON.VertexBuffer.MatricesWeightsKind:\n this.matricesWeights = data;\n break;\n case BABYLON.VertexBuffer.MatricesIndicesExtraKind:\n this.matricesIndicesExtra = data;\n break;\n case BABYLON.VertexBuffer.MatricesWeightsExtraKind:\n this.matricesWeightsExtra = data;\n break;\n }\n };\n /**\n * Associates the vertexData to the passed Mesh.\n * Sets it as updatable or not (default `false`)\n * @param mesh the mesh the vertexData is applied to\n * @param updatable when used and having the value true allows new data to update the vertexData\n * @returns the VertexData\n */\n VertexData.prototype.applyToMesh = function (mesh, updatable) {\n this._applyTo(mesh, updatable);\n return this;\n };\n /**\n * Associates the vertexData to the passed Geometry.\n * Sets it as updatable or not (default `false`)\n * @param geometry the geometry the vertexData is applied to\n * @param updatable when used and having the value true allows new data to update the vertexData\n * @returns VertexData\n */\n VertexData.prototype.applyToGeometry = function (geometry, updatable) {\n this._applyTo(geometry, updatable);\n return this;\n };\n /**\n * Updates the associated mesh\n * @param mesh the mesh to be updated\n * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false\n * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false\n * @returns VertexData\n */\n VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {\n this._update(mesh);\n return this;\n };\n /**\n * Updates the associated geometry\n * @param geometry the geometry to be updated\n * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false\n * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false\n * @returns VertexData.\n */\n VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {\n this._update(geometry);\n return this;\n };\n VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {\n if (updatable === void 0) { updatable = false; }\n if (this.positions) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);\n }\n if (this.normals) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);\n }\n if (this.tangents) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);\n }\n if (this.uvs) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);\n }\n if (this.uvs2) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);\n }\n if (this.uvs3) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);\n }\n if (this.uvs4) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);\n }\n if (this.uvs5) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);\n }\n if (this.uvs6) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);\n }\n if (this.colors) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);\n }\n if (this.matricesIndices) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);\n }\n if (this.matricesWeights) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);\n }\n if (this.matricesIndicesExtra) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);\n }\n if (this.matricesWeightsExtra) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);\n }\n if (this.indices) {\n meshOrGeometry.setIndices(this.indices, null, updatable);\n }\n else {\n meshOrGeometry.setIndices([], null);\n }\n return this;\n };\n VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {\n if (this.positions) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);\n }\n if (this.normals) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);\n }\n if (this.tangents) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);\n }\n if (this.uvs) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);\n }\n if (this.uvs2) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);\n }\n if (this.uvs3) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);\n }\n if (this.uvs4) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);\n }\n if (this.uvs5) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);\n }\n if (this.uvs6) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);\n }\n if (this.colors) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);\n }\n if (this.matricesIndices) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);\n }\n if (this.matricesWeights) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);\n }\n if (this.matricesIndicesExtra) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);\n }\n if (this.matricesWeightsExtra) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);\n }\n if (this.indices) {\n meshOrGeometry.setIndices(this.indices, null);\n }\n return this;\n };\n /**\n * Transforms each position and each normal of the vertexData according to the passed Matrix\n * @param matrix the transforming matrix\n * @returns the VertexData\n */\n VertexData.prototype.transform = function (matrix) {\n var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;\n var transformed = BABYLON.Vector3.Zero();\n var index;\n if (this.positions) {\n var position = BABYLON.Vector3.Zero();\n for (index = 0; index < this.positions.length; index += 3) {\n BABYLON.Vector3.FromArrayToRef(this.positions, index, position);\n BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);\n this.positions[index] = transformed.x;\n this.positions[index + 1] = transformed.y;\n this.positions[index + 2] = transformed.z;\n }\n }\n if (this.normals) {\n var normal = BABYLON.Vector3.Zero();\n for (index = 0; index < this.normals.length; index += 3) {\n BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);\n BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);\n this.normals[index] = transformed.x;\n this.normals[index + 1] = transformed.y;\n this.normals[index + 2] = transformed.z;\n }\n }\n if (this.tangents) {\n var tangent = BABYLON.Vector4.Zero();\n var tangentTransformed = BABYLON.Vector4.Zero();\n for (index = 0; index < this.tangents.length; index += 4) {\n BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);\n BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);\n this.tangents[index] = tangentTransformed.x;\n this.tangents[index + 1] = tangentTransformed.y;\n this.tangents[index + 2] = tangentTransformed.z;\n this.tangents[index + 3] = tangentTransformed.w;\n }\n }\n if (flip && this.indices) {\n for (index = 0; index < this.indices.length; index += 3) {\n var tmp = this.indices[index + 1];\n this.indices[index + 1] = this.indices[index + 2];\n this.indices[index + 2] = tmp;\n }\n }\n return this;\n };\n /**\n * Merges the passed VertexData into the current one\n * @param other the VertexData to be merged into the current one\n * @returns the modified VertexData\n */\n VertexData.prototype.merge = function (other) {\n this._validate();\n other._validate();\n if (!this.normals !== !other.normals ||\n !this.tangents !== !other.tangents ||\n !this.uvs !== !other.uvs ||\n !this.uvs2 !== !other.uvs2 ||\n !this.uvs3 !== !other.uvs3 ||\n !this.uvs4 !== !other.uvs4 ||\n !this.uvs5 !== !other.uvs5 ||\n !this.uvs6 !== !other.uvs6 ||\n !this.colors !== !other.colors ||\n !this.matricesIndices !== !other.matricesIndices ||\n !this.matricesWeights !== !other.matricesWeights ||\n !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||\n !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {\n throw new Error(\"Cannot merge vertex data that do not have the same set of attributes\");\n }\n if (other.indices) {\n if (!this.indices) {\n this.indices = [];\n }\n var offset = this.positions ? this.positions.length / 3 : 0;\n for (var index = 0; index < other.indices.length; index++) {\n //TODO check type - if Int32Array | Uint32Array | Uint16Array!\n this.indices.push(other.indices[index] + offset);\n }\n }\n this.positions = this._mergeElement(this.positions, other.positions);\n this.normals = this._mergeElement(this.normals, other.normals);\n this.tangents = this._mergeElement(this.tangents, other.tangents);\n this.uvs = this._mergeElement(this.uvs, other.uvs);\n this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);\n this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);\n this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);\n this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);\n this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);\n this.colors = this._mergeElement(this.colors, other.colors);\n this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);\n this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);\n this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);\n this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);\n return this;\n };\n VertexData.prototype._mergeElement = function (source, other) {\n if (!source) {\n return other;\n }\n if (!other) {\n return source;\n }\n var len = other.length + source.length;\n var isSrcTypedArray = source instanceof Float32Array;\n var isOthTypedArray = other instanceof Float32Array;\n // use non-loop method when the source is Float32Array\n if (isSrcTypedArray) {\n var ret32 = new Float32Array(len);\n ret32.set(source);\n ret32.set(other, source.length);\n return ret32;\n // source is number[], when other is also use concat\n }\n else if (!isOthTypedArray) {\n return source.concat(other);\n // source is a number[], but other is a Float32Array, loop required\n }\n else {\n var ret = source.slice(0); // copy source to a separate array\n for (var i = 0, len = other.length; i < len; i++) {\n ret.push(other[i]);\n }\n return ret;\n }\n };\n VertexData.prototype._validate = function () {\n if (!this.positions) {\n throw new Error(\"Positions are required\");\n }\n var getElementCount = function (kind, values) {\n var stride = BABYLON.VertexBuffer.DeduceStride(kind);\n if ((values.length % stride) !== 0) {\n throw new Error(\"The \" + kind + \"s array count must be a multiple of \" + stride);\n }\n return values.length / stride;\n };\n var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);\n var validateElementCount = function (kind, values) {\n var elementCount = getElementCount(kind, values);\n if (elementCount !== positionsElementCount) {\n throw new Error(\"The \" + kind + \"s element count (\" + elementCount + \") does not match the positions count (\" + positionsElementCount + \")\");\n }\n };\n if (this.normals)\n validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);\n if (this.tangents)\n validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);\n if (this.uvs)\n validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);\n if (this.uvs2)\n validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);\n if (this.uvs3)\n validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);\n if (this.uvs4)\n validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);\n if (this.uvs5)\n validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);\n if (this.uvs6)\n validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);\n if (this.colors)\n validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);\n if (this.matricesIndices)\n validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);\n if (this.matricesWeights)\n validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);\n if (this.matricesIndicesExtra)\n validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);\n if (this.matricesWeightsExtra)\n validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);\n };\n /**\n * Serializes the VertexData\n * @returns a serialized object\n */\n VertexData.prototype.serialize = function () {\n var serializationObject = this.serialize();\n if (this.positions) {\n serializationObject.positions = this.positions;\n }\n if (this.normals) {\n serializationObject.normals = this.normals;\n }\n if (this.tangents) {\n serializationObject.tangents = this.tangents;\n }\n if (this.uvs) {\n serializationObject.uvs = this.uvs;\n }\n if (this.uvs2) {\n serializationObject.uvs2 = this.uvs2;\n }\n if (this.uvs3) {\n serializationObject.uvs3 = this.uvs3;\n }\n if (this.uvs4) {\n serializationObject.uvs4 = this.uvs4;\n }\n if (this.uvs5) {\n serializationObject.uvs5 = this.uvs5;\n }\n if (this.uvs6) {\n serializationObject.uvs6 = this.uvs6;\n }\n if (this.colors) {\n serializationObject.colors = this.colors;\n }\n if (this.matricesIndices) {\n serializationObject.matricesIndices = this.matricesIndices;\n serializationObject.matricesIndices._isExpanded = true;\n }\n if (this.matricesWeights) {\n serializationObject.matricesWeights = this.matricesWeights;\n }\n if (this.matricesIndicesExtra) {\n serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;\n serializationObject.matricesIndicesExtra._isExpanded = true;\n }\n if (this.matricesWeightsExtra) {\n serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;\n }\n serializationObject.indices = this.indices;\n return serializationObject;\n };\n // Statics\n /**\n * Extracts the vertexData from a mesh\n * @param mesh the mesh from which to extract the VertexData\n * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false\n * @param forceCopy indicating that the VertexData must be cloned, optional, default false\n * @returns the object VertexData associated to the passed mesh\n */\n VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {\n return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);\n };\n /**\n * Extracts the vertexData from the geometry\n * @param geometry the geometry from which to extract the VertexData\n * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false\n * @param forceCopy indicating that the VertexData must be cloned, optional, default false\n * @returns the object VertexData associated to the passed mesh\n */\n VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {\n return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);\n };\n VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {\n var result = new VertexData();\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {\n result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {\n result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {\n result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {\n result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {\n result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {\n result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {\n result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {\n result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {\n result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {\n result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {\n result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);\n }\n result.indices = meshOrGeometry.getIndices(copyWhenShared);\n return result;\n };\n /**\n * Creates the VertexData for a Ribbon\n * @param options an object used to set the following optional parameters for the ribbon, required but can be empty\n * * pathArray array of paths, each of which an array of successive Vector3\n * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false\n * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false\n * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false\n * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional\n * * colors a linear array, of length 4 * number of vertices, of custom color values, optional\n * @returns the VertexData of the ribbon\n */\n VertexData.CreateRibbon = function (options) {\n var pathArray = options.pathArray;\n var closeArray = options.closeArray || false;\n var closePath = options.closePath || false;\n var invertUV = options.invertUV || false;\n var defaultOffset = Math.floor(pathArray[0].length / 2);\n var offset = options.offset || defaultOffset;\n offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var customUV = options.uvs;\n var customColors = options.colors;\n var positions = [];\n var indices = [];\n var normals = [];\n var uvs = [];\n var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id\n var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray\n var uTotalDistance = []; // uTotalDistance[p] : total distance of path p\n var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray\n var minlg; // minimal length among all paths from pathArray\n var lg = []; // array of path lengths : nb of vertex per path\n var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number\n var p; // path iterator\n var i; // point iterator\n var j; // point iterator\n // if single path in pathArray\n if (pathArray.length < 2) {\n var ar1 = [];\n var ar2 = [];\n for (i = 0; i < pathArray[0].length - offset; i++) {\n ar1.push(pathArray[0][i]);\n ar2.push(pathArray[0][i + offset]);\n }\n pathArray = [ar1, ar2];\n }\n // positions and horizontal distances (u)\n var idc = 0;\n var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath\n var path;\n var l;\n minlg = pathArray[0].length;\n var vectlg;\n var dist;\n for (p = 0; p < pathArray.length; p++) {\n uTotalDistance[p] = 0;\n us[p] = [0];\n path = pathArray[p];\n l = path.length;\n minlg = (minlg < l) ? minlg : l;\n j = 0;\n while (j < l) {\n positions.push(path[j].x, path[j].y, path[j].z);\n if (j > 0) {\n vectlg = path[j].subtract(path[j - 1]).length();\n dist = vectlg + uTotalDistance[p];\n us[p].push(dist);\n uTotalDistance[p] = dist;\n }\n j++;\n }\n if (closePath) { // an extra hidden vertex is added in the \"positions\" array\n j--;\n positions.push(path[0].x, path[0].y, path[0].z);\n vectlg = path[j].subtract(path[0]).length();\n dist = vectlg + uTotalDistance[p];\n us[p].push(dist);\n uTotalDistance[p] = dist;\n }\n lg[p] = l + closePathCorr;\n idx[p] = idc;\n idc += (l + closePathCorr);\n }\n // vertical distances (v)\n var path1;\n var path2;\n var vertex1 = null;\n var vertex2 = null;\n for (i = 0; i < minlg + closePathCorr; i++) {\n vTotalDistance[i] = 0;\n vs[i] = [0];\n for (p = 0; p < pathArray.length - 1; p++) {\n path1 = pathArray[p];\n path2 = pathArray[p + 1];\n if (i === minlg) { // closePath\n vertex1 = path1[0];\n vertex2 = path2[0];\n }\n else {\n vertex1 = path1[i];\n vertex2 = path2[i];\n }\n vectlg = vertex2.subtract(vertex1).length();\n dist = vectlg + vTotalDistance[i];\n vs[i].push(dist);\n vTotalDistance[i] = dist;\n }\n if (closeArray && vertex2 && vertex1) {\n path1 = pathArray[p];\n path2 = pathArray[0];\n if (i === minlg) { // closePath\n vertex2 = path2[0];\n }\n vectlg = vertex2.subtract(vertex1).length();\n dist = vectlg + vTotalDistance[i];\n vTotalDistance[i] = dist;\n }\n }\n // uvs\n var u;\n var v;\n if (customUV) {\n for (p = 0; p < customUV.length; p++) {\n uvs.push(customUV[p].x, customUV[p].y);\n }\n }\n else {\n for (p = 0; p < pathArray.length; p++) {\n for (i = 0; i < minlg + closePathCorr; i++) {\n u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;\n v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;\n if (invertUV) {\n uvs.push(v, u);\n }\n else {\n uvs.push(u, v);\n }\n }\n }\n }\n // indices\n p = 0; // path index\n var pi = 0; // positions array index\n var l1 = lg[p] - 1; // path1 length\n var l2 = lg[p + 1] - 1; // path2 length\n var min = (l1 < l2) ? l1 : l2; // current path stop index\n var shft = idx[1] - idx[0]; // shift\n var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate\ton\n while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path\n // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise\n indices.push(pi, pi + shft, pi + 1);\n indices.push(pi + shft + 1, pi + 1, pi + shft);\n pi += 1;\n if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path\n p++;\n if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true\n shft = idx[0] - idx[p];\n l1 = lg[p] - 1;\n l2 = lg[0] - 1;\n }\n else {\n shft = idx[p + 1] - idx[p];\n l1 = lg[p] - 1;\n l2 = lg[p + 1] - 1;\n }\n pi = idx[p];\n min = (l1 < l2) ? l1 + pi : l2 + pi;\n }\n }\n // normals\n VertexData.ComputeNormals(positions, indices, normals);\n if (closePath) { // update both the first and last vertex normals to their average value\n var indexFirst = 0;\n var indexLast = 0;\n for (p = 0; p < pathArray.length; p++) {\n indexFirst = idx[p] * 3;\n if (p + 1 < pathArray.length) {\n indexLast = (idx[p + 1] - 1) * 3;\n }\n else {\n indexLast = normals.length - 3;\n }\n normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;\n normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;\n normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;\n normals[indexLast] = normals[indexFirst];\n normals[indexLast + 1] = normals[indexFirst + 1];\n normals[indexLast + 2] = normals[indexFirst + 2];\n }\n }\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Colors\n var colors = null;\n if (customColors) {\n colors = new Float32Array(customColors.length * 4);\n for (var c = 0; c < customColors.length; c++) {\n colors[c * 4] = customColors[c].r;\n colors[c * 4 + 1] = customColors[c].g;\n colors[c * 4 + 2] = customColors[c].b;\n colors[c * 4 + 3] = customColors[c].a;\n }\n }\n // Result\n var vertexData = new VertexData();\n var positions32 = new Float32Array(positions);\n var normals32 = new Float32Array(normals);\n var uvs32 = new Float32Array(uvs);\n vertexData.indices = indices;\n vertexData.positions = positions32;\n vertexData.normals = normals32;\n vertexData.uvs = uvs32;\n if (colors) {\n vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);\n }\n if (closePath) {\n vertexData._idx = idx;\n }\n return vertexData;\n };\n /**\n * Creates the VertexData for a box\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * size sets the width, height and depth of the box to the value of size, optional default 1\n * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size\n * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size\n * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size\n * * faceUV an array of 6 Vector4 elements used to set different images to each box side\n * * faceColors an array of 6 Color3 elements used to set different colors to each box side\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the box\n */\n VertexData.CreateBox = function (options) {\n var normalsSource = [\n new BABYLON.Vector3(0, 0, 1),\n new BABYLON.Vector3(0, 0, -1),\n new BABYLON.Vector3(1, 0, 0),\n new BABYLON.Vector3(-1, 0, 0),\n new BABYLON.Vector3(0, 1, 0),\n new BABYLON.Vector3(0, -1, 0)\n ];\n var indices = [];\n var positions = [];\n var normals = [];\n var uvs = [];\n var width = options.width || options.size || 1;\n var height = options.height || options.size || 1;\n var depth = options.depth || options.size || 1;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var faceUV = options.faceUV || new Array(6);\n var faceColors = options.faceColors;\n var colors = [];\n // default face colors and UV if undefined\n for (var f = 0; f < 6; f++) {\n if (faceUV[f] === undefined) {\n faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);\n }\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);\n }\n }\n var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);\n // Create each face in turn.\n for (var index = 0; index < normalsSource.length; index++) {\n var normal = normalsSource[index];\n // Get two vectors perpendicular to the face normal and to each other.\n var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);\n var side2 = BABYLON.Vector3.Cross(normal, side1);\n // Six indices (two triangles) per face.\n var verticesLength = positions.length / 3;\n indices.push(verticesLength);\n indices.push(verticesLength + 1);\n indices.push(verticesLength + 2);\n indices.push(verticesLength);\n indices.push(verticesLength + 2);\n indices.push(verticesLength + 3);\n // Four vertices per face.\n var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);\n positions.push(vertex.x, vertex.y, vertex.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(faceUV[index].z, faceUV[index].w);\n if (faceColors) {\n colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);\n }\n vertex = normal.subtract(side1).add(side2).multiply(scaleVector);\n positions.push(vertex.x, vertex.y, vertex.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(faceUV[index].x, faceUV[index].w);\n if (faceColors) {\n colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);\n }\n vertex = normal.add(side1).add(side2).multiply(scaleVector);\n positions.push(vertex.x, vertex.y, vertex.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(faceUV[index].x, faceUV[index].y);\n if (faceColors) {\n colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);\n }\n vertex = normal.add(side1).subtract(side2).multiply(scaleVector);\n positions.push(vertex.x, vertex.y, vertex.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(faceUV[index].z, faceUV[index].y);\n if (faceColors) {\n colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);\n }\n }\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors) {\n var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;\n vertexData.colors = totalColors;\n }\n return vertexData;\n };\n /**\n * Creates the VertexData for an ellipsoid, defaults to a sphere\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * segments sets the number of horizontal strips optional, default 32\n * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1\n * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter\n * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter\n * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter\n * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1\n * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the ellipsoid\n */\n VertexData.CreateSphere = function (options) {\n var segments = options.segments || 32;\n var diameterX = options.diameterX || options.diameter || 1;\n var diameterY = options.diameterY || options.diameter || 1;\n var diameterZ = options.diameterZ || options.diameter || 1;\n var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;\n var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);\n var totalZRotationSteps = 2 + segments;\n var totalYRotationSteps = 2 * totalZRotationSteps;\n var indices = [];\n var positions = [];\n var normals = [];\n var uvs = [];\n for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {\n var normalizedZ = zRotationStep / totalZRotationSteps;\n var angleZ = normalizedZ * Math.PI * slice;\n for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {\n var normalizedY = yRotationStep / totalYRotationSteps;\n var angleY = normalizedY * Math.PI * 2 * arc;\n var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);\n var rotationY = BABYLON.Matrix.RotationY(angleY);\n var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);\n var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);\n var vertex = complete.multiply(radius);\n var normal = complete.divide(radius).normalize();\n positions.push(vertex.x, vertex.y, vertex.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(normalizedY, normalizedZ);\n }\n if (zRotationStep > 0) {\n var verticesCount = positions.length / 3;\n for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {\n indices.push((firstIndex));\n indices.push((firstIndex + 1));\n indices.push(firstIndex + totalYRotationSteps + 1);\n indices.push((firstIndex + totalYRotationSteps + 1));\n indices.push((firstIndex + 1));\n indices.push((firstIndex + totalYRotationSteps + 2));\n }\n }\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData for a cylinder, cone or prism\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * height sets the height (y direction) of the cylinder, optional, default 2\n * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter\n * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter\n * * diameter sets the diameter of the top and bottom of the cone, optional default 1\n * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24\n * * subdivisions` the number of rings along the cylinder height, optional, default 1\n * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false\n * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the cylinder, cone or prism\n */\n VertexData.CreateCylinder = function (options) {\n var height = options.height || 2;\n var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;\n var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;\n var tessellation = options.tessellation || 24;\n var subdivisions = options.subdivisions || 1;\n var hasRings = options.hasRings ? true : false;\n var enclose = options.enclose ? true : false;\n var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var faceUV = options.faceUV || new Array(3);\n var faceColors = options.faceColors;\n // default face colors and UV if undefined\n var quadNb = (arc !== 1 && enclose) ? 2 : 0;\n var ringNb = (hasRings) ? subdivisions : 1;\n var surfaceNb = 2 + (1 + quadNb) * ringNb;\n var f;\n for (f = 0; f < surfaceNb; f++) {\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);\n }\n }\n for (f = 0; f < surfaceNb; f++) {\n if (faceUV && faceUV[f] === undefined) {\n faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);\n }\n }\n var indices = new Array();\n var positions = new Array();\n var normals = new Array();\n var uvs = new Array();\n var colors = new Array();\n var angle_step = Math.PI * 2 * arc / tessellation;\n var angle;\n var h;\n var radius;\n var tan = (diameterBottom - diameterTop) / 2 / height;\n var ringVertex = BABYLON.Vector3.Zero();\n var ringNormal = BABYLON.Vector3.Zero();\n var ringFirstVertex = BABYLON.Vector3.Zero();\n var ringFirstNormal = BABYLON.Vector3.Zero();\n var quadNormal = BABYLON.Vector3.Zero();\n var Y = BABYLON.Axis.Y;\n // positions, normals, uvs\n var i;\n var j;\n var r;\n var ringIdx = 1;\n var s = 1; // surface index\n var cs = 0;\n var v = 0;\n for (i = 0; i <= subdivisions; i++) {\n h = i / subdivisions;\n radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;\n ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;\n for (r = 0; r < ringIdx; r++) {\n if (hasRings) {\n s += r;\n }\n if (enclose) {\n s += 2 * r;\n }\n for (j = 0; j <= tessellation; j++) {\n angle = j * angle_step;\n // position\n ringVertex.x = Math.cos(-angle) * radius;\n ringVertex.y = -height / 2 + h * height;\n ringVertex.z = Math.sin(-angle) * radius;\n // normal\n if (diameterTop === 0 && i === subdivisions) {\n // if no top cap, reuse former normals\n ringNormal.x = normals[normals.length - (tessellation + 1) * 3];\n ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];\n ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];\n }\n else {\n ringNormal.x = ringVertex.x;\n ringNormal.z = ringVertex.z;\n ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;\n ringNormal.normalize();\n }\n // keep first ring vertex values for enclose\n if (j === 0) {\n ringFirstVertex.copyFrom(ringVertex);\n ringFirstNormal.copyFrom(ringNormal);\n }\n positions.push(ringVertex.x, ringVertex.y, ringVertex.z);\n normals.push(ringNormal.x, ringNormal.y, ringNormal.z);\n if (hasRings) {\n v = (cs !== s) ? faceUV[s].y : faceUV[s].w;\n }\n else {\n v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;\n }\n uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);\n if (faceColors) {\n colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);\n }\n }\n // if enclose, add four vertices and their dedicated normals\n if (arc !== 1 && enclose) {\n positions.push(ringVertex.x, ringVertex.y, ringVertex.z);\n positions.push(0, ringVertex.y, 0);\n positions.push(0, ringVertex.y, 0);\n positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);\n BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);\n quadNormal.normalize();\n normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);\n BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);\n quadNormal.normalize();\n normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);\n if (hasRings) {\n v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;\n }\n else {\n v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;\n }\n uvs.push(faceUV[s + 1].x, v);\n uvs.push(faceUV[s + 1].z, v);\n if (hasRings) {\n v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;\n }\n else {\n v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;\n }\n uvs.push(faceUV[s + 2].x, v);\n uvs.push(faceUV[s + 2].z, v);\n if (faceColors) {\n colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);\n colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);\n colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);\n colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);\n }\n }\n if (cs !== s) {\n cs = s;\n }\n }\n }\n // indices\n var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose\n var s;\n i = 0;\n for (s = 0; s < subdivisions; s++) {\n var i0 = 0;\n var i1 = 0;\n var i2 = 0;\n var i3 = 0;\n for (j = 0; j < tessellation; j++) {\n i0 = i * (e + 1) + j;\n i1 = (i + 1) * (e + 1) + j;\n i2 = i * (e + 1) + (j + 1);\n i3 = (i + 1) * (e + 1) + (j + 1);\n indices.push(i0, i1, i2);\n indices.push(i3, i2, i1);\n }\n if (arc !== 1 && enclose) { // if enclose, add two quads\n indices.push(i0 + 2, i1 + 2, i2 + 2);\n indices.push(i3 + 2, i2 + 2, i1 + 2);\n indices.push(i0 + 4, i1 + 4, i2 + 4);\n indices.push(i3 + 4, i2 + 4, i1 + 4);\n }\n i = (hasRings) ? (i + 2) : (i + 1);\n }\n // Caps\n var createCylinderCap = function (isTop) {\n var radius = isTop ? diameterTop / 2 : diameterBottom / 2;\n if (radius === 0) {\n return;\n }\n // Cap positions, normals & uvs\n var angle;\n var circleVector;\n var i;\n var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];\n var c = null;\n if (faceColors) {\n c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];\n }\n // cap center\n var vbase = positions.length / 3;\n var offset = isTop ? height / 2 : -height / 2;\n var center = new BABYLON.Vector3(0, offset, 0);\n positions.push(center.x, center.y, center.z);\n normals.push(0, isTop ? 1 : -1, 0);\n uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);\n if (c) {\n colors.push(c.r, c.g, c.b, c.a);\n }\n var textureScale = new BABYLON.Vector2(0.5, 0.5);\n for (i = 0; i <= tessellation; i++) {\n angle = Math.PI * 2 * i * arc / tessellation;\n var cos = Math.cos(-angle);\n var sin = Math.sin(-angle);\n circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);\n var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);\n positions.push(circleVector.x, circleVector.y, circleVector.z);\n normals.push(0, isTop ? 1 : -1, 0);\n uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);\n if (c) {\n colors.push(c.r, c.g, c.b, c.a);\n }\n }\n // Cap indices\n for (i = 0; i < tessellation; i++) {\n if (!isTop) {\n indices.push(vbase);\n indices.push(vbase + (i + 1));\n indices.push(vbase + (i + 2));\n }\n else {\n indices.push(vbase);\n indices.push(vbase + (i + 2));\n indices.push(vbase + (i + 1));\n }\n }\n };\n // add caps to geometry\n createCylinderCap(false);\n createCylinderCap(true);\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors) {\n vertexData.colors = colors;\n }\n return vertexData;\n };\n /**\n * Creates the VertexData for a torus\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * diameter the diameter of the torus, optional default 1\n * * thickness the diameter of the tube forming the torus, optional default 0.5\n * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the torus\n */\n VertexData.CreateTorus = function (options) {\n var indices = [];\n var positions = [];\n var normals = [];\n var uvs = [];\n var diameter = options.diameter || 1;\n var thickness = options.thickness || 0.5;\n var tessellation = options.tessellation || 16;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var stride = tessellation + 1;\n for (var i = 0; i <= tessellation; i++) {\n var u = i / tessellation;\n var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;\n var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));\n for (var j = 0; j <= tessellation; j++) {\n var v = 1 - j / tessellation;\n var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;\n var dx = Math.cos(innerAngle);\n var dy = Math.sin(innerAngle);\n // Create a vertex.\n var normal = new BABYLON.Vector3(dx, dy, 0);\n var position = normal.scale(thickness / 2);\n var textureCoordinate = new BABYLON.Vector2(u, v);\n position = BABYLON.Vector3.TransformCoordinates(position, transform);\n normal = BABYLON.Vector3.TransformNormal(normal, transform);\n positions.push(position.x, position.y, position.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(textureCoordinate.x, textureCoordinate.y);\n // And create indices for two triangles.\n var nextI = (i + 1) % stride;\n var nextJ = (j + 1) % stride;\n indices.push(i * stride + j);\n indices.push(i * stride + nextJ);\n indices.push(nextI * stride + j);\n indices.push(i * stride + nextJ);\n indices.push(nextI * stride + nextJ);\n indices.push(nextI * stride + j);\n }\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData of the LineSystem\n * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty\n * - lines an array of lines, each line being an array of successive Vector3\n * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point\n * @returns the VertexData of the LineSystem\n */\n VertexData.CreateLineSystem = function (options) {\n var indices = [];\n var positions = [];\n var lines = options.lines;\n var colors = options.colors;\n var vertexColors = [];\n var idx = 0;\n for (var l = 0; l < lines.length; l++) {\n var points = lines[l];\n for (var index = 0; index < points.length; index++) {\n positions.push(points[index].x, points[index].y, points[index].z);\n if (colors) {\n var color = colors[l];\n vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);\n }\n if (index > 0) {\n indices.push(idx - 1);\n indices.push(idx);\n }\n idx++;\n }\n }\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n if (colors) {\n vertexData.colors = vertexColors;\n }\n return vertexData;\n };\n /**\n * Create the VertexData for a DashedLines\n * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty\n * - points an array successive Vector3\n * - dashSize the size of the dashes relative to the dash number, optional, default 3\n * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1\n * - dashNb the intended total number of dashes, optional, default 200\n * @returns the VertexData for the DashedLines\n */\n VertexData.CreateDashedLines = function (options) {\n var dashSize = options.dashSize || 3;\n var gapSize = options.gapSize || 1;\n var dashNb = options.dashNb || 200;\n var points = options.points;\n var positions = new Array();\n var indices = new Array();\n var curvect = BABYLON.Vector3.Zero();\n var lg = 0;\n var nb = 0;\n var shft = 0;\n var dashshft = 0;\n var curshft = 0;\n var idx = 0;\n var i = 0;\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n lg += curvect.length();\n }\n shft = lg / dashNb;\n dashshft = dashSize * shft / (dashSize + gapSize);\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n nb = Math.floor(curvect.length() / shft);\n curvect.normalize();\n for (var j = 0; j < nb; j++) {\n curshft = shft * j;\n positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);\n positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);\n indices.push(idx, idx + 1);\n idx += 2;\n }\n }\n // Result\n var vertexData = new VertexData();\n vertexData.positions = positions;\n vertexData.indices = indices;\n return vertexData;\n };\n /**\n * Creates the VertexData for a Ground\n * @param options an object used to set the following optional parameters for the Ground, required but can be empty\n * - width the width (x direction) of the ground, optional, default 1\n * - height the height (z direction) of the ground, optional, default 1\n * - subdivisions the number of subdivisions per side, optional, default 1\n * @returns the VertexData of the Ground\n */\n VertexData.CreateGround = function (options) {\n var indices = [];\n var positions = [];\n var normals = [];\n var uvs = [];\n var row, col;\n var width = options.width || 1;\n var height = options.height || 1;\n var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;\n var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;\n for (row = 0; row <= subdivisionsY; row++) {\n for (col = 0; col <= subdivisionsX; col++) {\n var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));\n var normal = new BABYLON.Vector3(0, 1.0, 0);\n positions.push(position.x, position.y, position.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);\n }\n }\n for (row = 0; row < subdivisionsY; row++) {\n for (col = 0; col < subdivisionsX; col++) {\n indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));\n indices.push(col + 1 + row * (subdivisionsX + 1));\n indices.push(col + row * (subdivisionsX + 1));\n indices.push(col + (row + 1) * (subdivisionsX + 1));\n indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));\n indices.push(col + row * (subdivisionsX + 1));\n }\n }\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData for a TiledGround by subdividing the ground into tiles\n * @param options an object used to set the following optional parameters for the Ground, required but can be empty\n * * xmin the ground minimum X coordinate, optional, default -1\n * * zmin the ground minimum Z coordinate, optional, default -1\n * * xmax the ground maximum X coordinate, optional, default 1\n * * zmax the ground maximum Z coordinate, optional, default 1\n * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}\n * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}\n * @returns the VertexData of the TiledGround\n */\n VertexData.CreateTiledGround = function (options) {\n var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;\n var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;\n var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;\n var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;\n var subdivisions = options.subdivisions || { w: 1, h: 1 };\n var precision = options.precision || { w: 1, h: 1 };\n var indices = new Array();\n var positions = new Array();\n var normals = new Array();\n var uvs = new Array();\n var row, col, tileRow, tileCol;\n subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;\n subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;\n precision.w = (precision.w < 1) ? 1 : precision.w;\n precision.h = (precision.h < 1) ? 1 : precision.h;\n var tileSize = {\n 'w': (xmax - xmin) / subdivisions.w,\n 'h': (zmax - zmin) / subdivisions.h\n };\n function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {\n // Indices\n var base = positions.length / 3;\n var rowLength = precision.w + 1;\n for (row = 0; row < precision.h; row++) {\n for (col = 0; col < precision.w; col++) {\n var square = [\n base + col + row * rowLength,\n base + (col + 1) + row * rowLength,\n base + (col + 1) + (row + 1) * rowLength,\n base + col + (row + 1) * rowLength\n ];\n indices.push(square[1]);\n indices.push(square[2]);\n indices.push(square[3]);\n indices.push(square[0]);\n indices.push(square[1]);\n indices.push(square[3]);\n }\n }\n // Position, normals and uvs\n var position = BABYLON.Vector3.Zero();\n var normal = new BABYLON.Vector3(0, 1.0, 0);\n for (row = 0; row <= precision.h; row++) {\n position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;\n for (col = 0; col <= precision.w; col++) {\n position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;\n position.y = 0;\n positions.push(position.x, position.y, position.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(col / precision.w, row / precision.h);\n }\n }\n }\n for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {\n for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {\n applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);\n }\n }\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData of the Ground designed from a heightmap\n * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap\n * * width the width (x direction) of the ground\n * * height the height (z direction) of the ground\n * * subdivisions the number of subdivisions per side\n * * minHeight the minimum altitude on the ground, optional, default 0\n * * maxHeight the maximum altitude on the ground, optional default 1\n * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)\n * * buffer the array holding the image color data\n * * bufferWidth the width of image\n * * bufferHeight the height of image\n * @returns the VertexData of the Ground designed from a heightmap\n */\n VertexData.CreateGroundFromHeightMap = function (options) {\n var indices = [];\n var positions = [];\n var normals = [];\n var uvs = [];\n var row, col;\n var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);\n // Vertices\n for (row = 0; row <= options.subdivisions; row++) {\n for (col = 0; col <= options.subdivisions; col++) {\n var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));\n // Compute height\n var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;\n var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;\n var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;\n var r = options.buffer[pos] / 255.0;\n var g = options.buffer[pos + 1] / 255.0;\n var b = options.buffer[pos + 2] / 255.0;\n var gradient = r * filter.r + g * filter.g + b * filter.b;\n position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;\n // Add vertex\n positions.push(position.x, position.y, position.z);\n normals.push(0, 0, 0);\n uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);\n }\n }\n // Indices\n for (row = 0; row < options.subdivisions; row++) {\n for (col = 0; col < options.subdivisions; col++) {\n indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));\n indices.push(col + 1 + row * (options.subdivisions + 1));\n indices.push(col + row * (options.subdivisions + 1));\n indices.push(col + (row + 1) * (options.subdivisions + 1));\n indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));\n indices.push(col + row * (options.subdivisions + 1));\n }\n }\n // Normals\n VertexData.ComputeNormals(positions, indices, normals);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData for a Plane\n * @param options an object used to set the following optional parameters for the plane, required but can be empty\n * * size sets the width and height of the plane to the value of size, optional default 1\n * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size\n * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the box\n */\n VertexData.CreatePlane = function (options) {\n var indices = [];\n var positions = [];\n var normals = [];\n var uvs = [];\n var width = options.width || options.size || 1;\n var height = options.height || options.size || 1;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n // Vertices\n var halfWidth = width / 2.0;\n var halfHeight = height / 2.0;\n positions.push(-halfWidth, -halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(0.0, 0.0);\n positions.push(halfWidth, -halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(1.0, 0.0);\n positions.push(halfWidth, halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(1.0, 1.0);\n positions.push(-halfWidth, halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(0.0, 1.0);\n // Indices\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData of the Disc or regular Polygon\n * @param options an object used to set the following optional parameters for the disc, required but can be empty\n * * radius the radius of the disc, optional default 0.5\n * * tessellation the number of polygon sides, optional, default 64\n * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the box\n */\n VertexData.CreateDisc = function (options) {\n var positions = new Array();\n var indices = new Array();\n var normals = new Array();\n var uvs = new Array();\n var radius = options.radius || 0.5;\n var tessellation = options.tessellation || 64;\n var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n // positions and uvs\n positions.push(0, 0, 0); // disc center first\n uvs.push(0.5, 0.5);\n var theta = Math.PI * 2 * arc;\n var step = theta / tessellation;\n for (var a = 0; a < theta; a += step) {\n var x = Math.cos(a);\n var y = Math.sin(a);\n var u = (x + 1) / 2;\n var v = (1 - y) / 2;\n positions.push(radius * x, radius * y, 0);\n uvs.push(u, v);\n }\n if (arc === 1) {\n positions.push(positions[3], positions[4], positions[5]); // close the circle\n uvs.push(uvs[2], uvs[3]);\n }\n //indices\n var vertexNb = positions.length / 3;\n for (var i = 1; i < vertexNb - 1; i++) {\n indices.push(i + 1, 0, i);\n }\n // result\n VertexData.ComputeNormals(positions, indices, normals);\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()\n * All parameters are provided by MeshBuilder.CreatePolygon as needed\n * @param polygon a mesh built from polygonTriangulation.build()\n * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the Polygon\n */\n VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {\n var faceUV = fUV || new Array(3);\n var faceColors = fColors;\n var colors = [];\n // default face colors and UV if undefined\n for (var f = 0; f < 3; f++) {\n if (faceUV[f] === undefined) {\n faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);\n }\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);\n }\n }\n var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);\n var indices = polygon.getIndices();\n // set face colours and textures\n var idx = 0;\n var face = 0;\n for (var index = 0; index < normals.length; index += 3) {\n //Edge Face no. 1\n if (Math.abs(normals[index + 1]) < 0.001) {\n face = 1;\n }\n //Top Face no. 0\n if (Math.abs(normals[index + 1] - 1) < 0.001) {\n face = 0;\n }\n //Bottom Face no. 2\n if (Math.abs(normals[index + 1] + 1) < 0.001) {\n face = 2;\n }\n idx = index / 3;\n uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;\n uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;\n if (faceColors) {\n colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);\n }\n }\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors) {\n var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;\n vertexData.colors = totalColors;\n }\n return vertexData;\n };\n /**\n * Creates the VertexData of the IcoSphere\n * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty\n * * radius the radius of the IcoSphere, optional default 1\n * * radiusX allows stretching in the x direction, optional, default radius\n * * radiusY allows stretching in the y direction, optional, default radius\n * * radiusZ allows stretching in the z direction, optional, default radius\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the IcoSphere\n */\n VertexData.CreateIcoSphere = function (options) {\n var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var radius = options.radius || 1;\n var flat = (options.flat === undefined) ? true : options.flat;\n var subdivisions = options.subdivisions || 4;\n var radiusX = options.radiusX || radius;\n var radiusY = options.radiusY || radius;\n var radiusZ = options.radiusZ || radius;\n var t = (1 + Math.sqrt(5)) / 2;\n // 12 vertex x,y,z\n var ico_vertices = [\n -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,\n 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,\n t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11\n ];\n // index of 3 vertex makes a face of icopshere\n var ico_indices = [\n 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,\n 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,\n 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,\n 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1\n ];\n // vertex for uv have aliased position, not for UV\n var vertices_unalias_id = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,\n // vertex alias\n 0,\n 2,\n 3,\n 3,\n 3,\n 4,\n 7,\n 8,\n 9,\n 9,\n 10,\n 11 // 23: B + 12\n ];\n // uv as integer step (not pixels !)\n var ico_vertexuv = [\n 5, 1, 3, 1, 6, 4, 0, 0,\n 5, 3, 4, 2, 2, 2, 4, 0,\n 2, 0, 1, 1, 6, 0, 6, 2,\n // vertex alias (for same vertex on different faces)\n 0, 4,\n 3, 3,\n 4, 4,\n 3, 1,\n 4, 2,\n 4, 4,\n 0, 2,\n 1, 1,\n 2, 2,\n 3, 3,\n 1, 3,\n 2, 4 // 23: B + 12\n ];\n // Vertices[0, 1, ...9, A, B] : position on UV plane\n // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)\n // First island of uv mapping\n // v = 4h 3+ 2\n // v = 3h 9+ 4\n // v = 2h 9+ 5 B\n // v = 1h 9 1 0\n // v = 0h 3 8 7 A\n // u = 0 1 2 3 4 5 6 *a\n // Second island of uv mapping\n // v = 4h 0+ B+ 4+\n // v = 3h A+ 2+\n // v = 2h 7+ 6 3+\n // v = 1h 8+ 3+\n // v = 0h\n // u = 0 1 2 3 4 5 6 *a\n // Face layout on texture UV mapping\n // ============\n // \\ 4 /\\ 16 / ======\n // \\ / \\ / /\\ 11 /\n // \\/ 7 \\/ / \\ /\n // ======= / 10 \\/\n // /\\ 17 /\\ =======\n // / \\ / \\ \\ 15 /\\\n // / 8 \\/ 12 \\ \\ / \\\n // ============ \\/ 6 \\\n // \\ 18 /\\ ============\n // \\ / \\ \\ 5 /\\ 0 /\n // \\/ 13 \\ \\ / \\ /\n // ======= \\/ 1 \\/\n // =============\n // /\\ 19 /\\ 2 /\\\n // / \\ / \\ / \\\n // / 14 \\/ 9 \\/ 3 \\\n // ===================\n // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97\n var ustep = 138 / 1024;\n var vstep = 239 / 1024;\n var uoffset = 60 / 1024;\n var voffset = 26 / 1024;\n // Second island should have margin, not to touch the first island\n // avoid any borderline artefact in pixel rounding\n var island_u_offset = -40 / 1024;\n var island_v_offset = +20 / 1024;\n // face is either island 0 or 1 :\n // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]\n var island = [\n 0, 0, 0, 0, 1,\n 0, 0, 1, 1, 0,\n 0, 0, 1, 1, 0,\n 0, 1, 1, 1, 0 // 15 - 19\n ];\n var indices = new Array();\n var positions = new Array();\n var normals = new Array();\n var uvs = new Array();\n var current_indice = 0;\n // prepare array of 3 vector (empty) (to be worked in place, shared for each face)\n var face_vertex_pos = new Array(3);\n var face_vertex_uv = new Array(3);\n var v012;\n for (v012 = 0; v012 < 3; v012++) {\n face_vertex_pos[v012] = BABYLON.Vector3.Zero();\n face_vertex_uv[v012] = BABYLON.Vector2.Zero();\n }\n // create all with normals\n for (var face = 0; face < 20; face++) {\n // 3 vertex per face\n for (v012 = 0; v012 < 3; v012++) {\n // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)\n var v_id = ico_indices[3 * face + v012];\n // vertex have 3D position (x,y,z)\n face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);\n // Normalize to get normal, then scale to radius\n face_vertex_pos[v012].normalize().scaleInPlace(radius);\n // uv Coordinates from vertex ID\n face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);\n }\n // Subdivide the face (interpolate pos, norm, uv)\n // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)\n // - norm is linear interpolation of vertex corner normal\n // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )\n // - uv is linear interpolation\n //\n // Topology is as below for sub-divide by 2\n // vertex shown as v0,v1,v2\n // interp index is i1 to progress in range [v0,v1[\n // interp index is i2 to progress in range [v0,v2[\n // face index as (i1,i2) for /\\ : (i1,i2),(i1+1,i2),(i1,i2+1)\n // and (i1,i2)' for \\/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)\n //\n //\n // i2 v2\n // ^ ^\n // / / \\\n // / / \\\n // / / \\\n // / / (0,1) \\\n // / #---------\\\n // / / \\ (0,0)'/ \\\n // / / \\ / \\\n // / / \\ / \\\n // / / (0,0) \\ / (1,0) \\\n // / #---------#---------\\\n // v0 v1\n //\n // --------------------> i1\n //\n // interp of (i1,i2):\n // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)\n // along i1 : lerp(x0,x1, i1/(S-i2))\n //\n // centroid of triangle is needed to get help normal computation\n // (c1,c2) are used for centroid location\n var interp_vertex = function (i1, i2, c1, c2) {\n // vertex is interpolated from\n // - face_vertex_pos[0..2]\n // - face_vertex_uv[0..2]\n var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);\n var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);\n var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));\n pos_interp.normalize();\n var vertex_normal;\n if (flat) {\n // in flat mode, recalculate normal as face centroid normal\n var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);\n var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);\n vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));\n }\n else {\n // in smooth mode, recalculate normal from each single vertex position\n vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);\n }\n // Vertex normal need correction due to X,Y,Z radius scaling\n vertex_normal.x /= radiusX;\n vertex_normal.y /= radiusY;\n vertex_normal.z /= radiusZ;\n vertex_normal.normalize();\n var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);\n var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);\n var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));\n positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);\n normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);\n uvs.push(uv_interp.x, uv_interp.y);\n // push each vertex has member of a face\n // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)\n indices.push(current_indice);\n current_indice++;\n };\n for (var i2 = 0; i2 < subdivisions; i2++) {\n for (var i1 = 0; i1 + i2 < subdivisions; i1++) {\n // face : (i1,i2) for /\\ :\n // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)\n interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);\n interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);\n interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);\n if (i1 + i2 + 1 < subdivisions) {\n // face : (i1,i2)' for \\/ :\n // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)\n interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);\n interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);\n interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);\n }\n }\n }\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html\n /**\n * Creates the VertexData for a Polyhedron\n * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty\n * * type provided types are:\n * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)\n * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)\n * * size the size of the IcoSphere, optional default 1\n * * sizeX allows stretching in the x direction, optional, default size\n * * sizeY allows stretching in the y direction, optional, default size\n * * sizeZ allows stretching in the z direction, optional, default size\n * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the Polyhedron\n */\n VertexData.CreatePolyhedron = function (options) {\n // provided polyhedron types :\n // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)\n // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)\n var polyhedra = [];\n polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };\n polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };\n polyhedra[2] = {\n vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],\n face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]\n };\n polyhedra[3] = {\n vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],\n face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]\n };\n polyhedra[4] = {\n vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],\n face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]\n };\n polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };\n polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };\n polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };\n polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };\n polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };\n polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };\n polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };\n polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };\n polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };\n polyhedra[14] = {\n vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],\n face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]\n };\n var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;\n var size = options.size;\n var sizeX = options.sizeX || size || 1;\n var sizeY = options.sizeY || size || 1;\n var sizeZ = options.sizeZ || size || 1;\n var data = options.custom || polyhedra[type];\n var nbfaces = data.face.length;\n var faceUV = options.faceUV || new Array(nbfaces);\n var faceColors = options.faceColors;\n var flat = (options.flat === undefined) ? true : options.flat;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var positions = new Array();\n var indices = new Array();\n var normals = new Array();\n var uvs = new Array();\n var colors = new Array();\n var index = 0;\n var faceIdx = 0; // face cursor in the array \"indexes\"\n var indexes = new Array();\n var i = 0;\n var f = 0;\n var u, v, ang, x, y, tmp;\n // default face colors and UV if undefined\n if (flat) {\n for (f = 0; f < nbfaces; f++) {\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);\n }\n if (faceUV && faceUV[f] === undefined) {\n faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);\n }\n }\n }\n if (!flat) {\n for (i = 0; i < data.vertex.length; i++) {\n positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);\n uvs.push(0, 0);\n }\n for (f = 0; f < nbfaces; f++) {\n for (i = 0; i < data.face[f].length - 2; i++) {\n indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);\n }\n }\n }\n else {\n for (f = 0; f < nbfaces; f++) {\n var fl = data.face[f].length; // number of vertices of the current face\n ang = 2 * Math.PI / fl;\n x = 0.5 * Math.tan(ang / 2);\n y = 0.5;\n // positions, uvs, colors\n for (i = 0; i < fl; i++) {\n // positions\n positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);\n indexes.push(index);\n index++;\n // uvs\n u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);\n v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);\n uvs.push(u, v);\n tmp = x * Math.cos(ang) - y * Math.sin(ang);\n y = x * Math.sin(ang) + y * Math.cos(ang);\n x = tmp;\n // colors\n if (faceColors) {\n colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);\n }\n }\n // indices from indexes\n for (i = 0; i < fl - 2; i++) {\n indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);\n }\n faceIdx += fl;\n }\n }\n VertexData.ComputeNormals(positions, indices, normals);\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n var vertexData = new VertexData();\n vertexData.positions = positions;\n vertexData.indices = indices;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors && flat) {\n vertexData.colors = colors;\n }\n return vertexData;\n };\n // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473\n /**\n * Creates the VertexData for a TorusKnot\n * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty\n * * radius the radius of the torus knot, optional, default 2\n * * tube the thickness of the tube, optional, default 0.5\n * * radialSegments the number of sides on each tube segments, optional, default 32\n * * tubularSegments the number of tubes to decompose the knot into, optional, default 32\n * * p the number of windings around the z axis, optional, default 2\n * * q the number of windings around the x axis, optional, default 3\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the Torus Knot\n */\n VertexData.CreateTorusKnot = function (options) {\n var indices = new Array();\n var positions = new Array();\n var normals = new Array();\n var uvs = new Array();\n var radius = options.radius || 2;\n var tube = options.tube || 0.5;\n var radialSegments = options.radialSegments || 32;\n var tubularSegments = options.tubularSegments || 32;\n var p = options.p || 2;\n var q = options.q || 3;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n // Helper\n var getPos = function (angle) {\n var cu = Math.cos(angle);\n var su = Math.sin(angle);\n var quOverP = q / p * angle;\n var cs = Math.cos(quOverP);\n var tx = radius * (2 + cs) * 0.5 * cu;\n var ty = radius * (2 + cs) * su * 0.5;\n var tz = radius * Math.sin(quOverP) * 0.5;\n return new BABYLON.Vector3(tx, ty, tz);\n };\n // Vertices\n var i;\n var j;\n for (i = 0; i <= radialSegments; i++) {\n var modI = i % radialSegments;\n var u = modI / radialSegments * 2 * p * Math.PI;\n var p1 = getPos(u);\n var p2 = getPos(u + 0.01);\n var tang = p2.subtract(p1);\n var n = p2.add(p1);\n var bitan = BABYLON.Vector3.Cross(tang, n);\n n = BABYLON.Vector3.Cross(bitan, tang);\n bitan.normalize();\n n.normalize();\n for (j = 0; j < tubularSegments; j++) {\n var modJ = j % tubularSegments;\n var v = modJ / tubularSegments * 2 * Math.PI;\n var cx = -tube * Math.cos(v);\n var cy = tube * Math.sin(v);\n positions.push(p1.x + cx * n.x + cy * bitan.x);\n positions.push(p1.y + cx * n.y + cy * bitan.y);\n positions.push(p1.z + cx * n.z + cy * bitan.z);\n uvs.push(i / radialSegments);\n uvs.push(j / tubularSegments);\n }\n }\n for (i = 0; i < radialSegments; i++) {\n for (j = 0; j < tubularSegments; j++) {\n var jNext = (j + 1) % tubularSegments;\n var a = i * tubularSegments + j;\n var b = (i + 1) * tubularSegments + j;\n var c = (i + 1) * tubularSegments + jNext;\n var d = i * tubularSegments + jNext;\n indices.push(d);\n indices.push(b);\n indices.push(a);\n indices.push(d);\n indices.push(c);\n indices.push(b);\n }\n }\n // Normals\n VertexData.ComputeNormals(positions, indices, normals);\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n // Tools\n /**\n * Compute normals for given positions and indices\n * @param positions an array of vertex positions, [...., x, y, z, ......]\n * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]\n * @param normals an array of vertex normals, [...., x, y, z, ......]\n * @param options an object used to set the following optional parameters for the TorusKnot, optional\n * * facetNormals : optional array of facet normals (vector3)\n * * facetPositions : optional array of facet positions (vector3)\n * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation\n * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation\n * * bInfo : optional bounding info, required for facetPartitioning computation\n * * bbSize : optional bounding box size data, required for facetPartitioning computation\n * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation\n * * useRightHandedSystem: optional boolean to for right handed system computation\n * * depthSort : optional boolean to enable the facet depth sort computation\n * * distanceTo : optional Vector3 to compute the facet depth from this location\n * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location\n */\n VertexData.ComputeNormals = function (positions, indices, normals, options) {\n // temporary scalar variables\n var index = 0; // facet index \n var p1p2x = 0.0; // p1p2 vector x coordinate\n var p1p2y = 0.0; // p1p2 vector y coordinate\n var p1p2z = 0.0; // p1p2 vector z coordinate\n var p3p2x = 0.0; // p3p2 vector x coordinate\n var p3p2y = 0.0; // p3p2 vector y coordinate\n var p3p2z = 0.0; // p3p2 vector z coordinate\n var faceNormalx = 0.0; // facet normal x coordinate\n var faceNormaly = 0.0; // facet normal y coordinate\n var faceNormalz = 0.0; // facet normal z coordinate\n var length = 0.0; // facet normal length before normalization\n var v1x = 0; // vector1 x index in the positions array\n var v1y = 0; // vector1 y index in the positions array\n var v1z = 0; // vector1 z index in the positions array\n var v2x = 0; // vector2 x index in the positions array\n var v2y = 0; // vector2 y index in the positions array\n var v2z = 0; // vector2 z index in the positions array\n var v3x = 0; // vector3 x index in the positions array\n var v3y = 0; // vector3 y index in the positions array\n var v3z = 0; // vector3 z index in the positions array\n var computeFacetNormals = false;\n var computeFacetPositions = false;\n var computeFacetPartitioning = false;\n var computeDepthSort = false;\n var faceNormalSign = 1;\n var ratio = 0;\n var distanceTo = null;\n if (options) {\n computeFacetNormals = (options.facetNormals) ? true : false;\n computeFacetPositions = (options.facetPositions) ? true : false;\n computeFacetPartitioning = (options.facetPartitioning) ? true : false;\n faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;\n ratio = options.ratio || 0;\n computeDepthSort = (options.depthSort) ? true : false;\n distanceTo = (options.distanceTo);\n if (computeDepthSort) {\n if (distanceTo === undefined) {\n distanceTo = BABYLON.Vector3.Zero();\n }\n var depthSortedFacets = options.depthSortedFacets;\n }\n }\n // facetPartitioning reinit if needed\n var xSubRatio = 0;\n var ySubRatio = 0;\n var zSubRatio = 0;\n var subSq = 0;\n if (computeFacetPartitioning && options && options.bbSize) {\n var ox = 0; // X partitioning index for facet position\n var oy = 0; // Y partinioning index for facet position\n var oz = 0; // Z partinioning index for facet position\n var b1x = 0; // X partitioning index for facet v1 vertex\n var b1y = 0; // Y partitioning index for facet v1 vertex\n var b1z = 0; // z partitioning index for facet v1 vertex\n var b2x = 0; // X partitioning index for facet v2 vertex\n var b2y = 0; // Y partitioning index for facet v2 vertex\n var b2z = 0; // Z partitioning index for facet v2 vertex\n var b3x = 0; // X partitioning index for facet v3 vertex\n var b3y = 0; // Y partitioning index for facet v3 vertex\n var b3z = 0; // Z partitioning index for facet v3 vertex\n var block_idx_o = 0; // facet barycenter block index\n var block_idx_v1 = 0; // v1 vertex block index\n var block_idx_v2 = 0; // v2 vertex block index\n var block_idx_v3 = 0; // v3 vertex block index \n var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;\n bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;\n xSubRatio = options.subDiv.X * ratio / options.bbSize.x;\n ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;\n zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;\n subSq = options.subDiv.max * options.subDiv.max;\n options.facetPartitioning.length = 0;\n }\n // reset the normals\n for (index = 0; index < positions.length; index++) {\n normals[index] = 0.0;\n }\n // Loop : 1 indice triplet = 1 facet\n var nbFaces = (indices.length / 3) | 0;\n for (index = 0; index < nbFaces; index++) {\n // get the indexes of the coordinates of each vertex of the facet\n v1x = indices[index * 3] * 3;\n v1y = v1x + 1;\n v1z = v1x + 2;\n v2x = indices[index * 3 + 1] * 3;\n v2y = v2x + 1;\n v2z = v2x + 2;\n v3x = indices[index * 3 + 2] * 3;\n v3y = v3x + 1;\n v3z = v3x + 2;\n p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2\n p1p2y = positions[v1y] - positions[v2y];\n p1p2z = positions[v1z] - positions[v2z];\n p3p2x = positions[v3x] - positions[v2x];\n p3p2y = positions[v3y] - positions[v2y];\n p3p2z = positions[v3z] - positions[v2z];\n // compute the face normal with the cross product\n faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);\n faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);\n faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);\n // normalize this normal and store it in the array facetData\n length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);\n length = (length === 0) ? 1.0 : length;\n faceNormalx /= length;\n faceNormaly /= length;\n faceNormalz /= length;\n if (computeFacetNormals && options) {\n options.facetNormals[index].x = faceNormalx;\n options.facetNormals[index].y = faceNormaly;\n options.facetNormals[index].z = faceNormalz;\n }\n if (computeFacetPositions && options) {\n // compute and the facet barycenter coordinates in the array facetPositions \n options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;\n options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;\n options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;\n }\n if (computeFacetPartitioning && options) {\n // store the facet indexes in arrays in the main facetPartitioning array :\n // compute each facet vertex (+ facet barycenter) index in the partiniong array\n ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);\n oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);\n oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);\n b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);\n b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);\n b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);\n b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);\n b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);\n b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);\n b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);\n b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);\n b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);\n block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;\n block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;\n block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;\n block_idx_o = ox + options.subDiv.max * oy + subSq * oz;\n options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();\n options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();\n options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();\n options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();\n // push each facet index in each block containing the vertex\n options.facetPartitioning[block_idx_v1].push(index);\n if (block_idx_v2 != block_idx_v1) {\n options.facetPartitioning[block_idx_v2].push(index);\n }\n if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {\n options.facetPartitioning[block_idx_v3].push(index);\n }\n if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {\n options.facetPartitioning[block_idx_o].push(index);\n }\n }\n if (computeDepthSort && options && options.facetPositions) {\n var dsf = depthSortedFacets[index];\n dsf.ind = index * 3;\n dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);\n }\n // compute the normals anyway\n normals[v1x] += faceNormalx; // accumulate all the normals per face\n normals[v1y] += faceNormaly;\n normals[v1z] += faceNormalz;\n normals[v2x] += faceNormalx;\n normals[v2y] += faceNormaly;\n normals[v2z] += faceNormalz;\n normals[v3x] += faceNormalx;\n normals[v3y] += faceNormaly;\n normals[v3z] += faceNormalz;\n }\n // last normalization of each normal\n for (index = 0; index < normals.length / 3; index++) {\n faceNormalx = normals[index * 3];\n faceNormaly = normals[index * 3 + 1];\n faceNormalz = normals[index * 3 + 2];\n length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);\n length = (length === 0) ? 1.0 : length;\n faceNormalx /= length;\n faceNormaly /= length;\n faceNormalz /= length;\n normals[index * 3] = faceNormalx;\n normals[index * 3 + 1] = faceNormaly;\n normals[index * 3 + 2] = faceNormalz;\n }\n };\n VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {\n var li = indices.length;\n var ln = normals.length;\n var i;\n var n;\n sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n switch (sideOrientation) {\n case BABYLON.Mesh.FRONTSIDE:\n // nothing changed\n break;\n case BABYLON.Mesh.BACKSIDE:\n var tmp;\n // indices\n for (i = 0; i < li; i += 3) {\n tmp = indices[i];\n indices[i] = indices[i + 2];\n indices[i + 2] = tmp;\n }\n // normals\n for (n = 0; n < ln; n++) {\n normals[n] = -normals[n];\n }\n break;\n case BABYLON.Mesh.DOUBLESIDE:\n // positions\n var lp = positions.length;\n var l = lp / 3;\n for (var p = 0; p < lp; p++) {\n positions[lp + p] = positions[p];\n }\n // indices\n for (i = 0; i < li; i += 3) {\n indices[i + li] = indices[i + 2] + l;\n indices[i + 1 + li] = indices[i + 1] + l;\n indices[i + 2 + li] = indices[i] + l;\n }\n // normals\n for (n = 0; n < ln; n++) {\n normals[ln + n] = -normals[n];\n }\n // uvs\n var lu = uvs.length;\n var u = 0;\n for (u = 0; u < lu; u++) {\n uvs[u + lu] = uvs[u];\n }\n frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);\n backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);\n u = 0;\n for (i = 0; i < lu / 2; i++) {\n uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];\n uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];\n uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];\n uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];\n u += 2;\n }\n break;\n }\n };\n /**\n * Applies VertexData created from the imported parameters to the geometry\n * @param parsedVertexData the parsed data from an imported file\n * @param geometry the geometry to apply the VertexData to\n */\n VertexData.ImportVertexData = function (parsedVertexData, geometry) {\n var vertexData = new VertexData();\n // positions\n var positions = parsedVertexData.positions;\n if (positions) {\n vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);\n }\n // normals\n var normals = parsedVertexData.normals;\n if (normals) {\n vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);\n }\n // tangents\n var tangents = parsedVertexData.tangents;\n if (tangents) {\n vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);\n }\n // uvs\n var uvs = parsedVertexData.uvs;\n if (uvs) {\n vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);\n }\n // uv2s\n var uv2s = parsedVertexData.uv2s;\n if (uv2s) {\n vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);\n }\n // uv3s\n var uv3s = parsedVertexData.uv3s;\n if (uv3s) {\n vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);\n }\n // uv4s\n var uv4s = parsedVertexData.uv4s;\n if (uv4s) {\n vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);\n }\n // uv5s\n var uv5s = parsedVertexData.uv5s;\n if (uv5s) {\n vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);\n }\n // uv6s\n var uv6s = parsedVertexData.uv6s;\n if (uv6s) {\n vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);\n }\n // colors\n var colors = parsedVertexData.colors;\n if (colors) {\n vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);\n }\n // matricesIndices\n var matricesIndices = parsedVertexData.matricesIndices;\n if (matricesIndices) {\n vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);\n }\n // matricesWeights\n var matricesWeights = parsedVertexData.matricesWeights;\n if (matricesWeights) {\n vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);\n }\n // indices\n var indices = parsedVertexData.indices;\n if (indices) {\n vertexData.indices = indices;\n }\n geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);\n };\n return VertexData;\n }());\n BABYLON.VertexData = VertexData;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.mesh.vertexData.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to store geometry data (vertex buffers + index buffer)\n */\n var Geometry = /** @class */ (function () {\n /**\n * Creates a new geometry\n * @param id defines the unique ID\n * @param scene defines the hosting scene\n * @param vertexData defines the {BABYLON.VertexData} used to get geometry data\n * @param updatable defines if geometry must be updatable (false by default)\n * @param mesh defines the mesh that will be associated with the geometry\n */\n function Geometry(id, scene, vertexData, updatable, mesh) {\n if (updatable === void 0) { updatable = false; }\n if (mesh === void 0) { mesh = null; }\n /**\n * Gets the delay loading state of the geometry (none by default which means not delayed)\n */\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;\n this._totalVertices = 0;\n this._isDisposed = false;\n this._indexBufferIsUpdatable = false;\n this.id = id;\n this._engine = scene.getEngine();\n this._meshes = [];\n this._scene = scene;\n //Init vertex buffer cache\n this._vertexBuffers = {};\n this._indices = [];\n this._updatable = updatable;\n // vertexData\n if (vertexData) {\n this.setAllVerticesData(vertexData, updatable);\n }\n else {\n this._totalVertices = 0;\n this._indices = [];\n }\n if (this._engine.getCaps().vertexArrayObject) {\n this._vertexArrayObjects = {};\n }\n // applyToMesh\n if (mesh) {\n if (mesh.getClassName() === \"LinesMesh\") {\n this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);\n this._updateExtend();\n }\n this.applyToMesh(mesh);\n mesh.computeWorldMatrix(true);\n }\n }\n Object.defineProperty(Geometry.prototype, \"boundingBias\", {\n /**\n * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y\n */\n get: function () {\n return this._boundingBias;\n },\n /**\n * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y\n */\n set: function (value) {\n if (this._boundingBias && this._boundingBias.equals(value)) {\n return;\n }\n this._boundingBias = value.clone();\n this._updateBoundingInfo(true, null);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Static function used to attach a new empty geometry to a mesh\n * @param mesh defines the mesh to attach the geometry to\n * @returns the new {BABYLON.Geometry}\n */\n Geometry.CreateGeometryForMesh = function (mesh) {\n var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());\n geometry.applyToMesh(mesh);\n return geometry;\n };\n Object.defineProperty(Geometry.prototype, \"extend\", {\n /**\n * Gets the current extend of the geometry\n */\n get: function () {\n return this._extend;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the hosting scene\n * @returns the hosting {BABYLON.Scene}\n */\n Geometry.prototype.getScene = function () {\n return this._scene;\n };\n /**\n * Gets the hosting engine\n * @returns the hosting {BABYLON.Engine}\n */\n Geometry.prototype.getEngine = function () {\n return this._engine;\n };\n /**\n * Defines if the geometry is ready to use\n * @returns true if the geometry is ready to be used\n */\n Geometry.prototype.isReady = function () {\n return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;\n };\n Object.defineProperty(Geometry.prototype, \"doNotSerialize\", {\n /**\n * Gets a value indicating that the geometry should not be serialized\n */\n get: function () {\n for (var index = 0; index < this._meshes.length; index++) {\n if (!this._meshes[index].doNotSerialize) {\n return false;\n }\n }\n return true;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Geometry.prototype._rebuild = function () {\n if (this._vertexArrayObjects) {\n this._vertexArrayObjects = {};\n }\n // Index buffer\n if (this._meshes.length !== 0 && this._indices) {\n this._indexBuffer = this._engine.createIndexBuffer(this._indices);\n }\n // Vertex buffers\n for (var key in this._vertexBuffers) {\n var vertexBuffer = this._vertexBuffers[key];\n vertexBuffer._rebuild();\n }\n };\n /**\n * Affects all geometry data in one call\n * @param vertexData defines the geometry data\n * @param updatable defines if the geometry must be flagged as updatable (false as default)\n */\n Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {\n vertexData.applyToGeometry(this, updatable);\n this.notifyUpdate();\n };\n /**\n * Set specific vertex data\n * @param kind defines the data kind (Position, normal, etc...)\n * @param data defines the vertex data to use\n * @param updatable defines if the vertex must be flagged as updatable (false as default)\n * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified\n */\n Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {\n if (updatable === void 0) { updatable = false; }\n var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);\n this.setVerticesBuffer(buffer);\n };\n /**\n * Removes a specific vertex data\n * @param kind defines the data kind (Position, normal, etc...)\n */\n Geometry.prototype.removeVerticesData = function (kind) {\n if (this._vertexBuffers[kind]) {\n this._vertexBuffers[kind].dispose();\n delete this._vertexBuffers[kind];\n }\n };\n /**\n * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data\n * @param buffer defines the vertex buffer to use\n * @param totalVertices defines the total number of vertices for position kind (could be null)\n */\n Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {\n if (totalVertices === void 0) { totalVertices = null; }\n var kind = buffer.getKind();\n if (this._vertexBuffers[kind]) {\n this._vertexBuffers[kind].dispose();\n }\n this._vertexBuffers[kind] = buffer;\n if (kind === BABYLON.VertexBuffer.PositionKind) {\n var data = buffer.getData();\n if (totalVertices != null) {\n this._totalVertices = totalVertices;\n }\n else {\n if (data != null) {\n this._totalVertices = data.length / (buffer.byteStride / 4);\n }\n }\n this._updateExtend(data);\n this._resetPointsArrayCache();\n var meshes = this._meshes;\n var numOfMeshes = meshes.length;\n for (var index = 0; index < numOfMeshes; index++) {\n var mesh = meshes[index];\n mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);\n mesh._createGlobalSubMesh(false);\n mesh.computeWorldMatrix(true);\n }\n }\n this.notifyUpdate(kind);\n if (this._vertexArrayObjects) {\n this._disposeVertexArrayObjects();\n this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported\n }\n };\n /**\n * Update a specific vertex buffer\n * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array\n * It will do nothing if the buffer is not updatable\n * @param kind defines the data kind (Position, normal, etc...)\n * @param data defines the data to use\n * @param offset defines the offset in the target buffer where to store the data\n * @param useBytes set to true if the offset is in bytes\n */\n Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {\n if (useBytes === void 0) { useBytes = false; }\n var vertexBuffer = this.getVertexBuffer(kind);\n if (!vertexBuffer) {\n return;\n }\n vertexBuffer.updateDirectly(data, offset, useBytes);\n this.notifyUpdate(kind);\n };\n /**\n * Update a specific vertex buffer\n * This function will create a new buffer if the current one is not updatable\n * @param kind defines the data kind (Position, normal, etc...)\n * @param data defines the data to use\n * @param updateExtends defines if the geometry extends must be recomputed (false by default)\n */\n Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {\n if (updateExtends === void 0) { updateExtends = false; }\n var vertexBuffer = this.getVertexBuffer(kind);\n if (!vertexBuffer) {\n return;\n }\n vertexBuffer.update(data);\n if (kind === BABYLON.VertexBuffer.PositionKind) {\n this._updateBoundingInfo(updateExtends, data);\n }\n this.notifyUpdate(kind);\n };\n Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {\n if (updateExtends) {\n this._updateExtend(data);\n }\n var meshes = this._meshes;\n var numOfMeshes = meshes.length;\n this._resetPointsArrayCache();\n for (var index = 0; index < numOfMeshes; index++) {\n var mesh = meshes[index];\n if (updateExtends) {\n mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);\n for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {\n var subMesh = mesh.subMeshes[subIndex];\n subMesh.refreshBoundingInfo();\n }\n }\n }\n };\n /** @hidden */\n Geometry.prototype._bind = function (effect, indexToBind) {\n if (!effect) {\n return;\n }\n if (indexToBind === undefined) {\n indexToBind = this._indexBuffer;\n }\n var vbs = this.getVertexBuffers();\n if (!vbs) {\n return;\n }\n if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {\n this._engine.bindBuffers(vbs, indexToBind, effect);\n return;\n }\n // Using VAO\n if (!this._vertexArrayObjects[effect.key]) {\n this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);\n }\n this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);\n };\n /**\n * Gets total number of vertices\n * @returns the total number of vertices\n */\n Geometry.prototype.getTotalVertices = function () {\n if (!this.isReady()) {\n return 0;\n }\n return this._totalVertices;\n };\n /**\n * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.\n * @param kind defines the data kind (Position, normal, etc...)\n * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes\n * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it\n * @returns a float array containing vertex data\n */\n Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {\n var vertexBuffer = this.getVertexBuffer(kind);\n if (!vertexBuffer) {\n return null;\n }\n var data = vertexBuffer.getData();\n if (!data) {\n return null;\n }\n var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);\n var count = this._totalVertices * vertexBuffer.getSize();\n if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {\n var copy_1 = new Array(count);\n vertexBuffer.forEach(count, function (value, index) {\n copy_1[index] = value;\n });\n return copy_1;\n }\n if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {\n if (data instanceof Array) {\n var offset = vertexBuffer.byteOffset / 4;\n return BABYLON.Tools.Slice(data, offset, offset + count);\n }\n else if (data instanceof ArrayBuffer) {\n return new Float32Array(data, vertexBuffer.byteOffset, count);\n }\n else {\n return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);\n }\n }\n if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {\n return BABYLON.Tools.Slice(data);\n }\n return data;\n };\n /**\n * Returns a boolean defining if the vertex data for the requested `kind` is updatable\n * @param kind defines the data kind (Position, normal, etc...)\n * @returns true if the vertex buffer with the specified kind is updatable\n */\n Geometry.prototype.isVertexBufferUpdatable = function (kind) {\n var vb = this._vertexBuffers[kind];\n if (!vb) {\n return false;\n }\n return vb.isUpdatable();\n };\n /**\n * Gets a specific vertex buffer\n * @param kind defines the data kind (Position, normal, etc...)\n * @returns a {BABYLON.VertexBuffer}\n */\n Geometry.prototype.getVertexBuffer = function (kind) {\n if (!this.isReady()) {\n return null;\n }\n return this._vertexBuffers[kind];\n };\n /**\n * Returns all vertex buffers\n * @return an object holding all vertex buffers indexed by kind\n */\n Geometry.prototype.getVertexBuffers = function () {\n if (!this.isReady()) {\n return null;\n }\n return this._vertexBuffers;\n };\n /**\n * Gets a boolean indicating if specific vertex buffer is present\n * @param kind defines the data kind (Position, normal, etc...)\n * @returns true if data is present\n */\n Geometry.prototype.isVerticesDataPresent = function (kind) {\n if (!this._vertexBuffers) {\n if (this._delayInfo) {\n return this._delayInfo.indexOf(kind) !== -1;\n }\n return false;\n }\n return this._vertexBuffers[kind] !== undefined;\n };\n /**\n * Gets a list of all attached data kinds (Position, normal, etc...)\n * @returns a list of string containing all kinds\n */\n Geometry.prototype.getVerticesDataKinds = function () {\n var result = [];\n var kind;\n if (!this._vertexBuffers && this._delayInfo) {\n for (kind in this._delayInfo) {\n result.push(kind);\n }\n }\n else {\n for (kind in this._vertexBuffers) {\n result.push(kind);\n }\n }\n return result;\n };\n /**\n * Update index buffer\n * @param indices defines the indices to store in the index buffer\n * @param offset defines the offset in the target buffer where to store the data\n */\n Geometry.prototype.updateIndices = function (indices, offset) {\n if (!this._indexBuffer) {\n return;\n }\n if (!this._indexBufferIsUpdatable) {\n this.setIndices(indices, null, true);\n }\n else {\n this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);\n }\n };\n /**\n * Creates a new index buffer\n * @param indices defines the indices to store in the index buffer\n * @param totalVertices defines the total number of vertices (could be null)\n * @param updatable defines if the index buffer must be flagged as updatable (false by default)\n */\n Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {\n if (totalVertices === void 0) { totalVertices = null; }\n if (updatable === void 0) { updatable = false; }\n if (this._indexBuffer) {\n this._engine._releaseBuffer(this._indexBuffer);\n }\n this._disposeVertexArrayObjects();\n this._indices = indices;\n this._indexBufferIsUpdatable = updatable;\n if (this._meshes.length !== 0 && this._indices) {\n this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);\n }\n if (totalVertices != undefined) { // including null and undefined\n this._totalVertices = totalVertices;\n }\n var meshes = this._meshes;\n var numOfMeshes = meshes.length;\n for (var index = 0; index < numOfMeshes; index++) {\n meshes[index]._createGlobalSubMesh(true);\n }\n this.notifyUpdate();\n };\n /**\n * Return the total number of indices\n * @returns the total number of indices\n */\n Geometry.prototype.getTotalIndices = function () {\n if (!this.isReady()) {\n return 0;\n }\n return this._indices.length;\n };\n /**\n * Gets the index buffer array\n * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes\n * @returns the index buffer array\n */\n Geometry.prototype.getIndices = function (copyWhenShared) {\n if (!this.isReady()) {\n return null;\n }\n var orig = this._indices;\n if (!copyWhenShared || this._meshes.length === 1) {\n return orig;\n }\n else {\n var len = orig.length;\n var copy = [];\n for (var i = 0; i < len; i++) {\n copy.push(orig[i]);\n }\n return copy;\n }\n };\n /**\n * Gets the index buffer\n * @return the index buffer\n */\n Geometry.prototype.getIndexBuffer = function () {\n if (!this.isReady()) {\n return null;\n }\n return this._indexBuffer;\n };\n /** @hidden */\n Geometry.prototype._releaseVertexArrayObject = function (effect) {\n if (effect === void 0) { effect = null; }\n if (!effect || !this._vertexArrayObjects) {\n return;\n }\n if (this._vertexArrayObjects[effect.key]) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);\n delete this._vertexArrayObjects[effect.key];\n }\n };\n /**\n * Release the associated resources for a specific mesh\n * @param mesh defines the source mesh\n * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it\n */\n Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {\n var meshes = this._meshes;\n var index = meshes.indexOf(mesh);\n if (index === -1) {\n return;\n }\n meshes.splice(index, 1);\n mesh._geometry = null;\n if (meshes.length === 0 && shouldDispose) {\n this.dispose();\n }\n };\n /**\n * Apply current geometry to a given mesh\n * @param mesh defines the mesh to apply geometry to\n */\n Geometry.prototype.applyToMesh = function (mesh) {\n if (mesh._geometry === this) {\n return;\n }\n var previousGeometry = mesh._geometry;\n if (previousGeometry) {\n previousGeometry.releaseForMesh(mesh);\n }\n var meshes = this._meshes;\n // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()\n mesh._geometry = this;\n this._scene.pushGeometry(this);\n meshes.push(mesh);\n if (this.isReady()) {\n this._applyToMesh(mesh);\n }\n else {\n mesh._boundingInfo = this._boundingInfo;\n }\n };\n Geometry.prototype._updateExtend = function (data) {\n if (data === void 0) { data = null; }\n if (!data) {\n data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n }\n this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);\n };\n Geometry.prototype._applyToMesh = function (mesh) {\n var numOfMeshes = this._meshes.length;\n // vertexBuffers\n for (var kind in this._vertexBuffers) {\n if (numOfMeshes === 1) {\n this._vertexBuffers[kind].create();\n }\n var buffer = this._vertexBuffers[kind].getBuffer();\n if (buffer)\n buffer.references = numOfMeshes;\n if (kind === BABYLON.VertexBuffer.PositionKind) {\n if (!this._extend) {\n this._updateExtend();\n }\n mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);\n mesh._createGlobalSubMesh(false);\n //bounding info was just created again, world matrix should be applied again.\n mesh._updateBoundingInfo();\n }\n }\n // indexBuffer\n if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {\n this._indexBuffer = this._engine.createIndexBuffer(this._indices);\n }\n if (this._indexBuffer) {\n this._indexBuffer.references = numOfMeshes;\n }\n };\n Geometry.prototype.notifyUpdate = function (kind) {\n if (this.onGeometryUpdated) {\n this.onGeometryUpdated(this, kind);\n }\n for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n mesh._markSubMeshesAsAttributesDirty();\n }\n };\n /**\n * Load the geometry if it was flagged as delay loaded\n * @param scene defines the hosting scene\n * @param onLoaded defines a callback called when the geometry is loaded\n */\n Geometry.prototype.load = function (scene, onLoaded) {\n if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {\n return;\n }\n if (this.isReady()) {\n if (onLoaded) {\n onLoaded();\n }\n return;\n }\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;\n this._queueLoad(scene, onLoaded);\n };\n Geometry.prototype._queueLoad = function (scene, onLoaded) {\n var _this = this;\n if (!this.delayLoadingFile) {\n return;\n }\n scene._addPendingData(this);\n scene._loadFile(this.delayLoadingFile, function (data) {\n if (!_this._delayLoadingFunction) {\n return;\n }\n _this._delayLoadingFunction(JSON.parse(data), _this);\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;\n _this._delayInfo = [];\n scene._removePendingData(_this);\n var meshes = _this._meshes;\n var numOfMeshes = meshes.length;\n for (var index = 0; index < numOfMeshes; index++) {\n _this._applyToMesh(meshes[index]);\n }\n if (onLoaded) {\n onLoaded();\n }\n }, undefined, true);\n };\n /**\n * Invert the geometry to move from a right handed system to a left handed one.\n */\n Geometry.prototype.toLeftHanded = function () {\n // Flip faces\n var tIndices = this.getIndices(false);\n if (tIndices != null && tIndices.length > 0) {\n for (var i = 0; i < tIndices.length; i += 3) {\n var tTemp = tIndices[i + 0];\n tIndices[i + 0] = tIndices[i + 2];\n tIndices[i + 2] = tTemp;\n }\n this.setIndices(tIndices);\n }\n // Negate position.z\n var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);\n if (tPositions != null && tPositions.length > 0) {\n for (var i = 0; i < tPositions.length; i += 3) {\n tPositions[i + 2] = -tPositions[i + 2];\n }\n this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);\n }\n // Negate normal.z\n var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);\n if (tNormals != null && tNormals.length > 0) {\n for (var i = 0; i < tNormals.length; i += 3) {\n tNormals[i + 2] = -tNormals[i + 2];\n }\n this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);\n }\n };\n // Cache\n /** @hidden */\n Geometry.prototype._resetPointsArrayCache = function () {\n this._positions = null;\n };\n /** @hidden */\n Geometry.prototype._generatePointsArray = function () {\n if (this._positions)\n return true;\n var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!data || data.length === 0) {\n return false;\n }\n this._positions = [];\n for (var index = 0; index < data.length; index += 3) {\n this._positions.push(BABYLON.Vector3.FromArray(data, index));\n }\n return true;\n };\n /**\n * Gets a value indicating if the geometry is disposed\n * @returns true if the geometry was disposed\n */\n Geometry.prototype.isDisposed = function () {\n return this._isDisposed;\n };\n Geometry.prototype._disposeVertexArrayObjects = function () {\n if (this._vertexArrayObjects) {\n for (var kind in this._vertexArrayObjects) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);\n }\n this._vertexArrayObjects = {};\n }\n };\n /**\n * Free all associated resources\n */\n Geometry.prototype.dispose = function () {\n var meshes = this._meshes;\n var numOfMeshes = meshes.length;\n var index;\n for (index = 0; index < numOfMeshes; index++) {\n this.releaseForMesh(meshes[index]);\n }\n this._meshes = [];\n this._disposeVertexArrayObjects();\n for (var kind in this._vertexBuffers) {\n this._vertexBuffers[kind].dispose();\n }\n this._vertexBuffers = {};\n this._totalVertices = 0;\n if (this._indexBuffer) {\n this._engine._releaseBuffer(this._indexBuffer);\n }\n this._indexBuffer = null;\n this._indices = [];\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;\n this.delayLoadingFile = null;\n this._delayLoadingFunction = null;\n this._delayInfo = [];\n this._boundingInfo = null;\n this._scene.removeGeometry(this);\n this._isDisposed = true;\n };\n /**\n * Clone the current geometry into a new geometry\n * @param id defines the unique ID of the new geometry\n * @returns a new geometry object\n */\n Geometry.prototype.copy = function (id) {\n var vertexData = new BABYLON.VertexData();\n vertexData.indices = [];\n var indices = this.getIndices();\n if (indices) {\n for (var index = 0; index < indices.length; index++) {\n vertexData.indices.push(indices[index]);\n }\n }\n var updatable = false;\n var stopChecking = false;\n var kind;\n for (kind in this._vertexBuffers) {\n // using slice() to make a copy of the array and not just reference it\n var data = this.getVerticesData(kind);\n if (data instanceof Float32Array) {\n vertexData.set(new Float32Array(data), kind);\n }\n else {\n vertexData.set(data.slice(0), kind);\n }\n if (!stopChecking) {\n var vb = this.getVertexBuffer(kind);\n if (vb) {\n updatable = vb.isUpdatable();\n stopChecking = !updatable;\n }\n }\n }\n var geometry = new Geometry(id, this._scene, vertexData, updatable);\n geometry.delayLoadState = this.delayLoadState;\n geometry.delayLoadingFile = this.delayLoadingFile;\n geometry._delayLoadingFunction = this._delayLoadingFunction;\n for (kind in this._delayInfo) {\n geometry._delayInfo = geometry._delayInfo || [];\n geometry._delayInfo.push(kind);\n }\n // Bounding info\n geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);\n return geometry;\n };\n /**\n * Serialize the current geometry info (and not the vertices data) into a JSON object\n * @return a JSON representation of the current geometry data (without the vertices data)\n */\n Geometry.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.id = this.id;\n serializationObject.updatable = this._updatable;\n if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {\n serializationObject.tags = BABYLON.Tags.GetTags(this);\n }\n return serializationObject;\n };\n Geometry.prototype.toNumberArray = function (origin) {\n if (Array.isArray(origin)) {\n return origin;\n }\n else {\n return Array.prototype.slice.call(origin);\n }\n };\n /**\n * Serialize all vertices data into a JSON oject\n * @returns a JSON representation of the current geometry data\n */\n Geometry.prototype.serializeVerticeData = function () {\n var serializationObject = this.serialize();\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {\n serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {\n serializationObject.positions._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {\n serializationObject.normals._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {\n serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {\n serializationObject.tangets._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {\n serializationObject.uvs._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {\n serializationObject.uv2s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {\n serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {\n serializationObject.uv3s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {\n serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {\n serializationObject.uv4s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {\n serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {\n serializationObject.uv5s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {\n serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {\n serializationObject.uv6s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {\n serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {\n serializationObject.colors._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {\n serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));\n serializationObject.matricesIndices._isExpanded = true;\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {\n serializationObject.matricesIndices._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {\n serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {\n serializationObject.matricesWeights._updatable = true;\n }\n }\n serializationObject.indices = this.toNumberArray(this.getIndices());\n return serializationObject;\n };\n // Statics\n /**\n * Extracts a clone of a mesh geometry\n * @param mesh defines the source mesh\n * @param id defines the unique ID of the new geometry object\n * @returns the new geometry object\n */\n Geometry.ExtractFromMesh = function (mesh, id) {\n var geometry = mesh._geometry;\n if (!geometry) {\n return null;\n }\n return geometry.copy(id);\n };\n /**\n * You should now use Tools.RandomId(), this method is still here for legacy reasons.\n * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523\n * Be aware Math.random() could cause collisions, but:\n * \"All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide\"\n * @returns a string containing a new GUID\n */\n Geometry.RandomId = function () {\n return BABYLON.Tools.RandomId();\n };\n /** @hidden */\n Geometry._ImportGeometry = function (parsedGeometry, mesh) {\n var scene = mesh.getScene();\n // Geometry\n var geometryId = parsedGeometry.geometryId;\n if (geometryId) {\n var geometry = scene.getGeometryByID(geometryId);\n if (geometry) {\n geometry.applyToMesh(mesh);\n }\n }\n else if (parsedGeometry instanceof ArrayBuffer) {\n var binaryInfo = mesh._binaryInfo;\n if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {\n var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);\n }\n if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {\n var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);\n }\n if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {\n var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);\n }\n if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {\n var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);\n }\n if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {\n var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);\n }\n if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {\n var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);\n }\n if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {\n var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);\n }\n if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {\n var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);\n }\n if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {\n var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);\n }\n if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {\n var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);\n }\n if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {\n var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);\n var floatIndices = [];\n for (var i = 0; i < matricesIndicesData.length; i++) {\n var index = matricesIndicesData[i];\n floatIndices.push(index & 0x000000FF);\n floatIndices.push((index & 0x0000FF00) >> 8);\n floatIndices.push((index & 0x00FF0000) >> 16);\n floatIndices.push(index >> 24);\n }\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);\n }\n if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {\n var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);\n }\n if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {\n var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);\n mesh.setIndices(indicesData, null);\n }\n if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {\n var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);\n mesh.subMeshes = [];\n for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {\n var materialIndex = subMeshesData[(i * 5) + 0];\n var verticesStart = subMeshesData[(i * 5) + 1];\n var verticesCount = subMeshesData[(i * 5) + 2];\n var indexStart = subMeshesData[(i * 5) + 3];\n var indexCount = subMeshesData[(i * 5) + 4];\n BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);\n }\n }\n }\n else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {\n mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);\n mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);\n if (parsedGeometry.tangents) {\n mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);\n }\n if (parsedGeometry.uvs) {\n mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);\n }\n if (parsedGeometry.uvs2) {\n mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);\n }\n if (parsedGeometry.uvs3) {\n mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);\n }\n if (parsedGeometry.uvs4) {\n mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);\n }\n if (parsedGeometry.uvs5) {\n mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);\n }\n if (parsedGeometry.uvs6) {\n mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);\n }\n if (parsedGeometry.colors) {\n mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);\n }\n if (parsedGeometry.matricesIndices) {\n if (!parsedGeometry.matricesIndices._isExpanded) {\n var floatIndices = [];\n for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {\n var matricesIndex = parsedGeometry.matricesIndices[i];\n floatIndices.push(matricesIndex & 0x000000FF);\n floatIndices.push((matricesIndex & 0x0000FF00) >> 8);\n floatIndices.push((matricesIndex & 0x00FF0000) >> 16);\n floatIndices.push(matricesIndex >> 24);\n }\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);\n }\n else {\n delete parsedGeometry.matricesIndices._isExpanded;\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);\n }\n }\n if (parsedGeometry.matricesIndicesExtra) {\n if (!parsedGeometry.matricesIndicesExtra._isExpanded) {\n var floatIndices = [];\n for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {\n var matricesIndex = parsedGeometry.matricesIndicesExtra[i];\n floatIndices.push(matricesIndex & 0x000000FF);\n floatIndices.push((matricesIndex & 0x0000FF00) >> 8);\n floatIndices.push((matricesIndex & 0x00FF0000) >> 16);\n floatIndices.push(matricesIndex >> 24);\n }\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);\n }\n else {\n delete parsedGeometry.matricesIndices._isExpanded;\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);\n }\n }\n if (parsedGeometry.matricesWeights) {\n Geometry._CleanMatricesWeights(parsedGeometry, mesh);\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);\n }\n if (parsedGeometry.matricesWeightsExtra) {\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);\n }\n mesh.setIndices(parsedGeometry.indices, null);\n }\n // SubMeshes\n if (parsedGeometry.subMeshes) {\n mesh.subMeshes = [];\n for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {\n var parsedSubMesh = parsedGeometry.subMeshes[subIndex];\n BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);\n }\n }\n // Flat shading\n if (mesh._shouldGenerateFlatShading) {\n mesh.convertToFlatShadedMesh();\n delete mesh._shouldGenerateFlatShading;\n }\n // Update\n mesh.computeWorldMatrix(true);\n // Octree\n var sceneOctree = scene.selectionOctree;\n if (sceneOctree !== undefined && sceneOctree !== null) {\n sceneOctree.addMesh(mesh);\n }\n };\n Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {\n var epsilon = 1e-3;\n if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {\n return;\n }\n var noInfluenceBoneIndex = 0.0;\n if (parsedGeometry.skeletonId > -1) {\n var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);\n if (!skeleton) {\n return;\n }\n noInfluenceBoneIndex = skeleton.bones.length;\n }\n else {\n return;\n }\n var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);\n var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n var matricesWeights = parsedGeometry.matricesWeights;\n var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;\n var influencers = parsedGeometry.numBoneInfluencer;\n var size = matricesWeights.length;\n for (var i = 0; i < size; i += 4) {\n var weight = 0.0;\n var firstZeroWeight = -1;\n for (var j = 0; j < 4; j++) {\n var w = matricesWeights[i + j];\n weight += w;\n if (w < epsilon && firstZeroWeight < 0) {\n firstZeroWeight = j;\n }\n }\n if (matricesWeightsExtra) {\n for (var j = 0; j < 4; j++) {\n var w = matricesWeightsExtra[i + j];\n weight += w;\n if (w < epsilon && firstZeroWeight < 0) {\n firstZeroWeight = j + 4;\n }\n }\n }\n if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {\n firstZeroWeight = influencers - 1;\n }\n if (weight > epsilon) {\n var mweight = 1.0 / weight;\n for (var j = 0; j < 4; j++) {\n matricesWeights[i + j] *= mweight;\n }\n if (matricesWeightsExtra) {\n for (var j = 0; j < 4; j++) {\n matricesWeightsExtra[i + j] *= mweight;\n }\n }\n }\n else {\n if (firstZeroWeight >= 4) {\n matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;\n matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;\n }\n else {\n matricesWeights[i + firstZeroWeight] = 1.0 - weight;\n matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;\n }\n }\n }\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);\n if (parsedGeometry.matricesWeightsExtra) {\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);\n }\n };\n /**\n * Create a new geometry from persisted data (Using .babylon file format)\n * @param parsedVertexData defines the persisted data\n * @param scene defines the hosting scene\n * @param rootUrl defines the root url to use to load assets (like delayed data)\n * @returns the new geometry object\n */\n Geometry.Parse = function (parsedVertexData, scene, rootUrl) {\n if (scene.getGeometryByID(parsedVertexData.id)) {\n return null; // null since geometry could be something else than a box...\n }\n var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);\n }\n if (parsedVertexData.delayLoadingFile) {\n geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;\n geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));\n geometry._delayInfo = [];\n if (parsedVertexData.hasUVs) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);\n }\n if (parsedVertexData.hasUVs2) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);\n }\n if (parsedVertexData.hasUVs3) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);\n }\n if (parsedVertexData.hasUVs4) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);\n }\n if (parsedVertexData.hasUVs5) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);\n }\n if (parsedVertexData.hasUVs6) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);\n }\n if (parsedVertexData.hasColors) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);\n }\n if (parsedVertexData.hasMatricesIndices) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n }\n if (parsedVertexData.hasMatricesWeights) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n }\n geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;\n }\n else {\n BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);\n }\n scene.pushGeometry(geometry, true);\n return geometry;\n };\n return Geometry;\n }());\n BABYLON.Geometry = Geometry;\n // Primitives\n /// Abstract class\n /**\n * Abstract class used to provide common services for all typed geometries\n * @hidden\n */\n var _PrimitiveGeometry = /** @class */ (function (_super) {\n __extends(_PrimitiveGeometry, _super);\n /**\n * Creates a new typed geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n */\n function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {\n if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }\n if (mesh === void 0) { mesh = null; }\n var _this = _super.call(this, id, scene, undefined, false, mesh) || this;\n _this._canBeRegenerated = _canBeRegenerated;\n _this._beingRegenerated = true;\n _this.regenerate();\n _this._beingRegenerated = false;\n return _this;\n }\n /**\n * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)\n * @returns true if the geometry can be regenerated\n */\n _PrimitiveGeometry.prototype.canBeRegenerated = function () {\n return this._canBeRegenerated;\n };\n /**\n * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values\n */\n _PrimitiveGeometry.prototype.regenerate = function () {\n if (!this._canBeRegenerated) {\n return;\n }\n this._beingRegenerated = true;\n this.setAllVerticesData(this._regenerateVertexData(), false);\n this._beingRegenerated = false;\n };\n /**\n * Clone the geometry\n * @param id defines the unique ID of the new geometry\n * @returns the new geometry\n */\n _PrimitiveGeometry.prototype.asNewGeometry = function (id) {\n return _super.prototype.copy.call(this, id);\n };\n // overrides\n _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {\n if (!this._beingRegenerated) {\n return;\n }\n _super.prototype.setAllVerticesData.call(this, vertexData, false);\n };\n _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {\n if (!this._beingRegenerated) {\n return;\n }\n _super.prototype.setVerticesData.call(this, kind, data, false);\n };\n // to override\n /** @hidden */\n _PrimitiveGeometry.prototype._regenerateVertexData = function () {\n throw new Error(\"Abstract method\");\n };\n _PrimitiveGeometry.prototype.copy = function (id) {\n throw new Error(\"Must be overriden in sub-classes.\");\n };\n _PrimitiveGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.canBeRegenerated = this.canBeRegenerated();\n return serializationObject;\n };\n return _PrimitiveGeometry;\n }(Geometry));\n BABYLON._PrimitiveGeometry = _PrimitiveGeometry;\n /**\n * Creates a ribbon geometry\n * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons\n */\n var RibbonGeometry = /** @class */ (function (_super) {\n __extends(RibbonGeometry, _super);\n /**\n * Creates a ribbon geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param pathArray defines the array of paths to use\n * @param closeArray defines if the last path and the first path must be joined\n * @param closePath defines if the last and first points of each path in your pathArray must be joined\n * @param offset defines the offset between points\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function RibbonGeometry(id, scene, \n /**\n * Defines the array of paths to use\n */\n pathArray, \n /**\n * Defines if the last and first points of each path in your pathArray must be joined\n */\n closeArray, \n /**\n * Defines if the last and first points of each path in your pathArray must be joined\n */\n closePath, \n /**\n * Defines the offset between points\n */\n offset, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.pathArray = pathArray;\n _this.closeArray = closeArray;\n _this.closePath = closePath;\n _this.offset = offset;\n _this.side = side;\n return _this;\n }\n /** @hidden */\n RibbonGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });\n };\n RibbonGeometry.prototype.copy = function (id) {\n return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);\n };\n return RibbonGeometry;\n }(_PrimitiveGeometry));\n BABYLON.RibbonGeometry = RibbonGeometry;\n /**\n * Creates a box geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#box\n */\n var BoxGeometry = /** @class */ (function (_super) {\n __extends(BoxGeometry, _super);\n /**\n * Creates a box geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param size defines the zise of the box (width, height and depth are the same)\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function BoxGeometry(id, scene, \n /**\n * Defines the zise of the box (width, height and depth are the same)\n */\n size, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.size = size;\n _this.side = side;\n return _this;\n }\n BoxGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });\n };\n BoxGeometry.prototype.copy = function (id) {\n return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);\n };\n BoxGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.size = this.size;\n return serializationObject;\n };\n BoxGeometry.Parse = function (parsedBox, scene) {\n if (scene.getGeometryByID(parsedBox.id)) {\n return null; // null since geometry could be something else than a box...\n }\n var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(box, parsedBox.tags);\n }\n scene.pushGeometry(box, true);\n return box;\n };\n return BoxGeometry;\n }(_PrimitiveGeometry));\n BABYLON.BoxGeometry = BoxGeometry;\n /**\n * Creates a sphere geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere\n */\n var SphereGeometry = /** @class */ (function (_super) {\n __extends(SphereGeometry, _super);\n /**\n * Create a new sphere geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param segments defines the number of segments to use to create the sphere\n * @param diameter defines the diameter of the sphere\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function SphereGeometry(id, scene, \n /**\n * Defines the number of segments to use to create the sphere\n */\n segments, \n /**\n * Defines the diameter of the sphere\n */\n diameter, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.segments = segments;\n _this.diameter = diameter;\n _this.side = side;\n return _this;\n }\n SphereGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });\n };\n SphereGeometry.prototype.copy = function (id) {\n return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);\n };\n SphereGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.segments = this.segments;\n serializationObject.diameter = this.diameter;\n return serializationObject;\n };\n SphereGeometry.Parse = function (parsedSphere, scene) {\n if (scene.getGeometryByID(parsedSphere.id)) {\n return null; // null since geometry could be something else than a sphere...\n }\n var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);\n }\n scene.pushGeometry(sphere, true);\n return sphere;\n };\n return SphereGeometry;\n }(_PrimitiveGeometry));\n BABYLON.SphereGeometry = SphereGeometry;\n /**\n * Creates a disc geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon\n */\n var DiscGeometry = /** @class */ (function (_super) {\n __extends(DiscGeometry, _super);\n /**\n * Creates a new disc geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param radius defines the radius of the disc\n * @param tessellation defines the tesselation factor to apply to the disc\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function DiscGeometry(id, scene, \n /**\n * Defines the radius of the disc\n */\n radius, \n /**\n * Defines the tesselation factor to apply to the disc\n */\n tessellation, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.radius = radius;\n _this.tessellation = tessellation;\n _this.side = side;\n return _this;\n }\n DiscGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });\n };\n DiscGeometry.prototype.copy = function (id) {\n return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);\n };\n return DiscGeometry;\n }(_PrimitiveGeometry));\n BABYLON.DiscGeometry = DiscGeometry;\n /**\n * Creates a new cylinder geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone\n */\n var CylinderGeometry = /** @class */ (function (_super) {\n __extends(CylinderGeometry, _super);\n /**\n * Creates a new cylinder geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param height defines the height of the cylinder\n * @param diameterTop defines the diameter of the cylinder's top cap\n * @param diameterBottom defines the diameter of the cylinder's bottom cap\n * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)\n * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function CylinderGeometry(id, scene, \n /**\n * Defines the height of the cylinder\n */\n height, \n /**\n * Defines the diameter of the cylinder's top cap\n */\n diameterTop, \n /**\n * Defines the diameter of the cylinder's bottom cap\n */\n diameterBottom, \n /**\n * Defines the tessellation factor to apply to the cylinder\n */\n tessellation, \n /**\n * Defines the number of subdivisions to apply to the cylinder (1 by default)\n */\n subdivisions, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (subdivisions === void 0) { subdivisions = 1; }\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.height = height;\n _this.diameterTop = diameterTop;\n _this.diameterBottom = diameterBottom;\n _this.tessellation = tessellation;\n _this.subdivisions = subdivisions;\n _this.side = side;\n return _this;\n }\n CylinderGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });\n };\n CylinderGeometry.prototype.copy = function (id) {\n return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);\n };\n CylinderGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.height = this.height;\n serializationObject.diameterTop = this.diameterTop;\n serializationObject.diameterBottom = this.diameterBottom;\n serializationObject.tessellation = this.tessellation;\n return serializationObject;\n };\n CylinderGeometry.Parse = function (parsedCylinder, scene) {\n if (scene.getGeometryByID(parsedCylinder.id)) {\n return null; // null since geometry could be something else than a cylinder...\n }\n var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);\n }\n scene.pushGeometry(cylinder, true);\n return cylinder;\n };\n return CylinderGeometry;\n }(_PrimitiveGeometry));\n BABYLON.CylinderGeometry = CylinderGeometry;\n /**\n * Creates a new torus geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#torus\n */\n var TorusGeometry = /** @class */ (function (_super) {\n __extends(TorusGeometry, _super);\n /**\n * Creates a new torus geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param diameter defines the diameter of the torus\n * @param thickness defines the thickness of the torus (ie. internal diameter)\n * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function TorusGeometry(id, scene, \n /**\n * Defines the diameter of the torus\n */\n diameter, \n /**\n * Defines the thickness of the torus (ie. internal diameter)\n */\n thickness, \n /**\n * Defines the tesselation factor to apply to the torus\n */\n tessellation, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.diameter = diameter;\n _this.thickness = thickness;\n _this.tessellation = tessellation;\n _this.side = side;\n return _this;\n }\n TorusGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });\n };\n TorusGeometry.prototype.copy = function (id) {\n return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);\n };\n TorusGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.diameter = this.diameter;\n serializationObject.thickness = this.thickness;\n serializationObject.tessellation = this.tessellation;\n return serializationObject;\n };\n TorusGeometry.Parse = function (parsedTorus, scene) {\n if (scene.getGeometryByID(parsedTorus.id)) {\n return null; // null since geometry could be something else than a torus...\n }\n var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);\n }\n scene.pushGeometry(torus, true);\n return torus;\n };\n return TorusGeometry;\n }(_PrimitiveGeometry));\n BABYLON.TorusGeometry = TorusGeometry;\n /**\n * Creates a new ground geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#ground\n */\n var GroundGeometry = /** @class */ (function (_super) {\n __extends(GroundGeometry, _super);\n /**\n * Creates a new ground geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param width defines the width of the ground\n * @param height defines the height of the ground\n * @param subdivisions defines the subdivisions to apply to the ground\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n */\n function GroundGeometry(id, scene, \n /**\n * Defines the width of the ground\n */\n width, \n /**\n * Defines the height of the ground\n */\n height, \n /**\n * Defines the subdivisions to apply to the ground\n */\n subdivisions, canBeRegenerated, mesh) {\n if (mesh === void 0) { mesh = null; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.width = width;\n _this.height = height;\n _this.subdivisions = subdivisions;\n return _this;\n }\n GroundGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });\n };\n GroundGeometry.prototype.copy = function (id) {\n return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);\n };\n GroundGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.width = this.width;\n serializationObject.height = this.height;\n serializationObject.subdivisions = this.subdivisions;\n return serializationObject;\n };\n GroundGeometry.Parse = function (parsedGround, scene) {\n if (scene.getGeometryByID(parsedGround.id)) {\n return null; // null since geometry could be something else than a ground...\n }\n var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);\n }\n scene.pushGeometry(ground, true);\n return ground;\n };\n return GroundGeometry;\n }(_PrimitiveGeometry));\n BABYLON.GroundGeometry = GroundGeometry;\n /**\n * Creates a tiled ground geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground\n */\n var TiledGroundGeometry = /** @class */ (function (_super) {\n __extends(TiledGroundGeometry, _super);\n /**\n * Creates a tiled ground geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param xmin defines the minimum value on X axis\n * @param zmin defines the minimum value on Z axis\n * @param xmax defines the maximum value on X axis\n * @param zmax defines the maximum value on Z axis\n * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)\n * @param precision defines the precision to use when computing the tiles\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n */\n function TiledGroundGeometry(id, scene, \n /**\n * Defines the minimum value on X axis\n */\n xmin, \n /**\n * Defines the minimum value on Z axis\n */\n zmin, \n /**\n * Defines the maximum value on X axis\n */\n xmax, \n /**\n * Defines the maximum value on Z axis\n */\n zmax, \n /**\n * Defines the subdivisions to apply to the ground\n */\n subdivisions, \n /**\n * Defines the precision to use when computing the tiles\n */\n precision, canBeRegenerated, mesh) {\n if (mesh === void 0) { mesh = null; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.xmin = xmin;\n _this.zmin = zmin;\n _this.xmax = xmax;\n _this.zmax = zmax;\n _this.subdivisions = subdivisions;\n _this.precision = precision;\n return _this;\n }\n TiledGroundGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });\n };\n TiledGroundGeometry.prototype.copy = function (id) {\n return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);\n };\n return TiledGroundGeometry;\n }(_PrimitiveGeometry));\n BABYLON.TiledGroundGeometry = TiledGroundGeometry;\n /**\n * Creates a plane geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#plane\n */\n var PlaneGeometry = /** @class */ (function (_super) {\n __extends(PlaneGeometry, _super);\n /**\n * Creates a plane geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param size defines the size of the plane (width === height)\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function PlaneGeometry(id, scene, \n /**\n * Defines the size of the plane (width === height)\n */\n size, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.size = size;\n _this.side = side;\n return _this;\n }\n PlaneGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });\n };\n PlaneGeometry.prototype.copy = function (id) {\n return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);\n };\n PlaneGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.size = this.size;\n return serializationObject;\n };\n PlaneGeometry.Parse = function (parsedPlane, scene) {\n if (scene.getGeometryByID(parsedPlane.id)) {\n return null; // null since geometry could be something else than a ground...\n }\n var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);\n }\n scene.pushGeometry(plane, true);\n return plane;\n };\n return PlaneGeometry;\n }(_PrimitiveGeometry));\n BABYLON.PlaneGeometry = PlaneGeometry;\n /**\n * Creates a torus knot geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot\n */\n var TorusKnotGeometry = /** @class */ (function (_super) {\n __extends(TorusKnotGeometry, _super);\n /**\n * Creates a torus knot geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param radius defines the radius of the torus knot\n * @param tube defines the thickness of the torus knot tube\n * @param radialSegments defines the number of radial segments\n * @param tubularSegments defines the number of tubular segments\n * @param p defines the first number of windings\n * @param q defines the second number of windings\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function TorusKnotGeometry(id, scene, \n /**\n * Defines the radius of the torus knot\n */\n radius, \n /**\n * Defines the thickness of the torus knot tube\n */\n tube, \n /**\n * Defines the number of radial segments\n */\n radialSegments, \n /**\n * Defines the number of tubular segments\n */\n tubularSegments, \n /**\n * Defines the first number of windings\n */\n p, \n /**\n * Defines the second number of windings\n */\n q, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.radius = radius;\n _this.tube = tube;\n _this.radialSegments = radialSegments;\n _this.tubularSegments = tubularSegments;\n _this.p = p;\n _this.q = q;\n _this.side = side;\n return _this;\n }\n TorusKnotGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });\n };\n TorusKnotGeometry.prototype.copy = function (id) {\n return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);\n };\n TorusKnotGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.radius = this.radius;\n serializationObject.tube = this.tube;\n serializationObject.radialSegments = this.radialSegments;\n serializationObject.tubularSegments = this.tubularSegments;\n serializationObject.p = this.p;\n serializationObject.q = this.q;\n return serializationObject;\n };\n ;\n TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {\n if (scene.getGeometryByID(parsedTorusKnot.id)) {\n return null; // null since geometry could be something else than a ground...\n }\n var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);\n }\n scene.pushGeometry(torusKnot, true);\n return torusKnot;\n };\n return TorusKnotGeometry;\n }(_PrimitiveGeometry));\n BABYLON.TorusKnotGeometry = TorusKnotGeometry;\n //}\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.geometry.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window\n */\n var PerformanceMonitor = /** @class */ (function () {\n /**\n * constructor\n * @param frameSampleSize The number of samples required to saturate the sliding window\n */\n function PerformanceMonitor(frameSampleSize) {\n if (frameSampleSize === void 0) { frameSampleSize = 30; }\n this._enabled = true;\n this._rollingFrameTime = new RollingAverage(frameSampleSize);\n }\n /**\n * Samples current frame\n * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames\n */\n PerformanceMonitor.prototype.sampleFrame = function (timeMs) {\n if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }\n if (!this._enabled)\n return;\n if (this._lastFrameTimeMs != null) {\n var dt = timeMs - this._lastFrameTimeMs;\n this._rollingFrameTime.add(dt);\n }\n this._lastFrameTimeMs = timeMs;\n };\n Object.defineProperty(PerformanceMonitor.prototype, \"averageFrameTime\", {\n /**\n * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)\n * @return Average frame time in milliseconds\n */\n get: function () {\n return this._rollingFrameTime.average;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerformanceMonitor.prototype, \"averageFrameTimeVariance\", {\n /**\n * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)\n * @return Frame time variance in milliseconds squared\n */\n get: function () {\n return this._rollingFrameTime.variance;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerformanceMonitor.prototype, \"instantaneousFrameTime\", {\n /**\n * Returns the frame time of the most recent frame\n * @return Frame time in milliseconds\n */\n get: function () {\n return this._rollingFrameTime.history(0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerformanceMonitor.prototype, \"averageFPS\", {\n /**\n * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)\n * @return Framerate in frames per second\n */\n get: function () {\n return 1000.0 / this._rollingFrameTime.average;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerformanceMonitor.prototype, \"instantaneousFPS\", {\n /**\n * Returns the average framerate in frames per second using the most recent frame time\n * @return Framerate in frames per second\n */\n get: function () {\n var history = this._rollingFrameTime.history(0);\n if (history === 0) {\n return 0;\n }\n return 1000.0 / history;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerformanceMonitor.prototype, \"isSaturated\", {\n /**\n * Returns true if enough samples have been taken to completely fill the sliding window\n * @return true if saturated\n */\n get: function () {\n return this._rollingFrameTime.isSaturated();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Enables contributions to the sliding window sample set\n */\n PerformanceMonitor.prototype.enable = function () {\n this._enabled = true;\n };\n /**\n * Disables contributions to the sliding window sample set\n * Samples will not be interpolated over the disabled period\n */\n PerformanceMonitor.prototype.disable = function () {\n this._enabled = false;\n //clear last sample to avoid interpolating over the disabled period when next enabled\n this._lastFrameTimeMs = null;\n };\n Object.defineProperty(PerformanceMonitor.prototype, \"isEnabled\", {\n /**\n * Returns true if sampling is enabled\n * @return true if enabled\n */\n get: function () {\n return this._enabled;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Resets performance monitor\n */\n PerformanceMonitor.prototype.reset = function () {\n //clear last sample to avoid interpolating over the disabled period when next enabled\n this._lastFrameTimeMs = null;\n //wipe record\n this._rollingFrameTime.reset();\n };\n return PerformanceMonitor;\n }());\n BABYLON.PerformanceMonitor = PerformanceMonitor;\n /**\n * RollingAverage\n *\n * Utility to efficiently compute the rolling average and variance over a sliding window of samples\n */\n var RollingAverage = /** @class */ (function () {\n /**\n * constructor\n * @param length The number of samples required to saturate the sliding window\n */\n function RollingAverage(length) {\n this._samples = new Array(length);\n this.reset();\n }\n /**\n * Adds a sample to the sample set\n * @param v The sample value\n */\n RollingAverage.prototype.add = function (v) {\n //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance\n var delta;\n //we need to check if we've already wrapped round\n if (this.isSaturated()) {\n //remove bottom of stack from mean\n var bottomValue = this._samples[this._pos];\n delta = bottomValue - this.average;\n this.average -= delta / (this._sampleCount - 1);\n this._m2 -= delta * (bottomValue - this.average);\n }\n else {\n this._sampleCount++;\n }\n //add new value to mean\n delta = v - this.average;\n this.average += delta / (this._sampleCount);\n this._m2 += delta * (v - this.average);\n //set the new variance\n this.variance = this._m2 / (this._sampleCount - 1);\n this._samples[this._pos] = v;\n this._pos++;\n this._pos %= this._samples.length; //positive wrap around\n };\n /**\n * Returns previously added values or null if outside of history or outside the sliding window domain\n * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that\n * @return Value previously recorded with add() or null if outside of range\n */\n RollingAverage.prototype.history = function (i) {\n if ((i >= this._sampleCount) || (i >= this._samples.length)) {\n return 0;\n }\n var i0 = this._wrapPosition(this._pos - 1.0);\n return this._samples[this._wrapPosition(i0 - i)];\n };\n /**\n * Returns true if enough samples have been taken to completely fill the sliding window\n * @return true if sample-set saturated\n */\n RollingAverage.prototype.isSaturated = function () {\n return this._sampleCount >= this._samples.length;\n };\n /**\n * Resets the rolling average (equivalent to 0 samples taken so far)\n */\n RollingAverage.prototype.reset = function () {\n this.average = 0;\n this.variance = 0;\n this._sampleCount = 0;\n this._pos = 0;\n this._m2 = 0;\n };\n /**\n * Wraps a value around the sample range boundaries\n * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.\n * @return Wrapped position in sample range\n */\n RollingAverage.prototype._wrapPosition = function (i) {\n var max = this._samples.length;\n return ((i % max) + max) % max;\n };\n return RollingAverage;\n }());\n BABYLON.RollingAverage = RollingAverage;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.performanceMonitor.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * \"Static Class\" containing the most commonly used helper while dealing with material for\n * rendering purpose.\n *\n * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.\n *\n * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.\n */\n var MaterialHelper = /** @class */ (function () {\n function MaterialHelper() {\n }\n /**\n * Bind the current view position to an effect.\n * @param effect The effect to be bound\n * @param scene The scene the eyes position is used from\n */\n MaterialHelper.BindEyePosition = function (effect, scene) {\n if (scene._forcedViewPosition) {\n effect.setVector3(\"vEyePosition\", scene._forcedViewPosition);\n return;\n }\n effect.setVector3(\"vEyePosition\", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);\n };\n /**\n * Helps preparing the defines values about the UVs in used in the effect.\n * UVs are shared as much as we can accross chanels in the shaders.\n * @param texture The texture we are preparing the UVs for\n * @param defines The defines to update\n * @param key The chanel key \"diffuse\", \"specular\"... used in the shader\n */\n MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {\n defines._needUVs = true;\n defines[key] = true;\n if (texture.getTextureMatrix().isIdentity(true)) {\n defines[key + \"DIRECTUV\"] = texture.coordinatesIndex + 1;\n if (texture.coordinatesIndex === 0) {\n defines[\"MAINUV1\"] = true;\n }\n else {\n defines[\"MAINUV2\"] = true;\n }\n }\n else {\n defines[key + \"DIRECTUV\"] = 0;\n }\n };\n /**\n * Binds a texture matrix value to its corrsponding uniform\n * @param texture The texture to bind the matrix for\n * @param uniformBuffer The uniform buffer receivin the data\n * @param key The chanel key \"diffuse\", \"specular\"... used in the shader\n */\n MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {\n var matrix = texture.getTextureMatrix();\n if (!matrix.isIdentity(true)) {\n uniformBuffer.updateMatrix(key + \"Matrix\", matrix);\n }\n };\n /**\n * Helper used to prepare the list of defines associated with misc. values for shader compilation\n * @param mesh defines the current mesh\n * @param scene defines the current scene\n * @param useLogarithmicDepth defines if logarithmic depth has to be turned on\n * @param pointsCloud defines if point cloud rendering has to be turned on\n * @param fogEnabled defines if fog has to be turned on\n * @param alphaTest defines if alpha testing has to be turned on\n * @param defines defines the current list of defines\n */\n MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {\n if (defines._areMiscDirty) {\n defines[\"LOGARITHMICDEPTH\"] = useLogarithmicDepth;\n defines[\"POINTSIZE\"] = pointsCloud;\n defines[\"FOG\"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);\n defines[\"NONUNIFORMSCALING\"] = mesh.nonUniformScaling;\n defines[\"ALPHATEST\"] = alphaTest;\n }\n };\n /**\n * Helper used to prepare the list of defines associated with frame values for shader compilation\n * @param scene defines the current scene\n * @param engine defines the current engine\n * @param defines specifies the list of active defines\n * @param useInstances defines if instances have to be turned on\n * @param useClipPlane defines if clip plane have to be turned on\n */\n MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {\n if (useClipPlane === void 0) { useClipPlane = null; }\n var changed = false;\n if (useClipPlane == null) {\n useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);\n }\n if (defines[\"CLIPPLANE\"] !== useClipPlane) {\n defines[\"CLIPPLANE\"] = useClipPlane;\n changed = true;\n }\n if (defines[\"DEPTHPREPASS\"] !== !engine.getColorWrite()) {\n defines[\"DEPTHPREPASS\"] = !defines[\"DEPTHPREPASS\"];\n changed = true;\n }\n if (defines[\"INSTANCES\"] !== useInstances) {\n defines[\"INSTANCES\"] = useInstances;\n changed = true;\n }\n if (changed) {\n defines.markAsUnprocessed();\n }\n };\n /**\n * Prepares the defines used in the shader depending on the attributes data available in the mesh\n * @param mesh The mesh containing the geometry data we will draw\n * @param defines The defines to update\n * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)\n * @param useBones Precise whether bones should be used or not (override mesh info)\n * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)\n * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)\n * @returns false if defines are considered not dirty and have not been checked\n */\n MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {\n if (useMorphTargets === void 0) { useMorphTargets = false; }\n if (useVertexAlpha === void 0) { useVertexAlpha = true; }\n if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {\n return false;\n }\n defines._normals = defines._needNormals;\n defines._uvs = defines._needUVs;\n defines[\"NORMAL\"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));\n if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {\n defines[\"TANGENT\"] = true;\n }\n if (defines._needUVs) {\n defines[\"UV1\"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);\n defines[\"UV2\"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);\n }\n else {\n defines[\"UV1\"] = false;\n defines[\"UV2\"] = false;\n }\n if (useVertexColor) {\n var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);\n defines[\"VERTEXCOLOR\"] = hasVertexColors;\n defines[\"VERTEXALPHA\"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;\n }\n if (useBones) {\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n defines[\"NUM_BONE_INFLUENCERS\"] = mesh.numBoneInfluencers;\n defines[\"BonesPerMesh\"] = (mesh.skeleton.bones.length + 1);\n }\n else {\n defines[\"NUM_BONE_INFLUENCERS\"] = 0;\n defines[\"BonesPerMesh\"] = 0;\n }\n }\n if (useMorphTargets) {\n var manager = mesh.morphTargetManager;\n if (manager) {\n defines[\"MORPHTARGETS_TANGENT\"] = manager.supportsTangents && defines[\"TANGENT\"];\n defines[\"MORPHTARGETS_NORMAL\"] = manager.supportsNormals && defines[\"NORMAL\"];\n defines[\"MORPHTARGETS\"] = (manager.numInfluencers > 0);\n defines[\"NUM_MORPH_INFLUENCERS\"] = manager.numInfluencers;\n }\n else {\n defines[\"MORPHTARGETS_TANGENT\"] = false;\n defines[\"MORPHTARGETS_NORMAL\"] = false;\n defines[\"MORPHTARGETS\"] = false;\n defines[\"NUM_MORPH_INFLUENCERS\"] = 0;\n }\n }\n return true;\n };\n /**\n * Prepares the defines related to the light information passed in parameter\n * @param scene The scene we are intending to draw\n * @param mesh The mesh the effect is compiling for\n * @param defines The defines to update\n * @param specularSupported Specifies whether specular is supported or not (override lights data)\n * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max\n * @param disableLighting Specifies whether the lighting is disabled (override scene and light)\n * @returns true if normals will be required for the rest of the effect\n */\n MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {\n if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }\n if (disableLighting === void 0) { disableLighting = false; }\n if (!defines._areLightsDirty) {\n return defines._needNormals;\n }\n var lightIndex = 0;\n var needNormals = false;\n var needRebuild = false;\n var lightmapMode = false;\n var shadowEnabled = false;\n var specularEnabled = false;\n if (scene.lightsEnabled && !disableLighting) {\n for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {\n var light = _a[_i];\n needNormals = true;\n if (defines[\"LIGHT\" + lightIndex] === undefined) {\n needRebuild = true;\n }\n defines[\"LIGHT\" + lightIndex] = true;\n defines[\"SPOTLIGHT\" + lightIndex] = false;\n defines[\"HEMILIGHT\" + lightIndex] = false;\n defines[\"POINTLIGHT\" + lightIndex] = false;\n defines[\"DIRLIGHT\" + lightIndex] = false;\n light.prepareLightSpecificDefines(defines, lightIndex);\n // Specular\n if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {\n specularEnabled = true;\n }\n // Shadows\n defines[\"SHADOW\" + lightIndex] = false;\n defines[\"SHADOWPCF\" + lightIndex] = false;\n defines[\"SHADOWPCSS\" + lightIndex] = false;\n defines[\"SHADOWPOISSON\" + lightIndex] = false;\n defines[\"SHADOWESM\" + lightIndex] = false;\n defines[\"SHADOWCUBE\" + lightIndex] = false;\n defines[\"SHADOWLOWQUALITY\" + lightIndex] = false;\n defines[\"SHADOWMEDIUMQUALITY\" + lightIndex] = false;\n if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {\n var shadowGenerator = light.getShadowGenerator();\n if (shadowGenerator) {\n var shadowMap = shadowGenerator.getShadowMap();\n if (shadowMap) {\n if (shadowMap.renderList && shadowMap.renderList.length > 0) {\n shadowEnabled = true;\n shadowGenerator.prepareDefines(defines, lightIndex);\n }\n }\n }\n }\n if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {\n lightmapMode = true;\n defines[\"LIGHTMAPEXCLUDED\" + lightIndex] = true;\n defines[\"LIGHTMAPNOSPECULAR\" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);\n }\n else {\n defines[\"LIGHTMAPEXCLUDED\" + lightIndex] = false;\n defines[\"LIGHTMAPNOSPECULAR\" + lightIndex] = false;\n }\n lightIndex++;\n if (lightIndex === maxSimultaneousLights)\n break;\n }\n }\n defines[\"SPECULARTERM\"] = specularEnabled;\n defines[\"SHADOWS\"] = shadowEnabled;\n // Resetting all other lights if any\n for (var index = lightIndex; index < maxSimultaneousLights; index++) {\n if (defines[\"LIGHT\" + index] !== undefined) {\n defines[\"LIGHT\" + index] = false;\n defines[\"HEMILIGHT\" + lightIndex] = false;\n defines[\"POINTLIGHT\" + lightIndex] = false;\n defines[\"DIRLIGHT\" + lightIndex] = false;\n defines[\"SPOTLIGHT\" + lightIndex] = false;\n defines[\"SHADOW\" + lightIndex] = false;\n }\n }\n var caps = scene.getEngine().getCaps();\n if (defines[\"SHADOWFLOAT\"] === undefined) {\n needRebuild = true;\n }\n defines[\"SHADOWFLOAT\"] = shadowEnabled &&\n ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||\n (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));\n defines[\"LIGHTMAPEXCLUDED\"] = lightmapMode;\n if (needRebuild) {\n defines.rebuild();\n }\n return needNormals;\n };\n /**\n * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms\n * that won t be acctive due to defines being turned off.\n * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information\n * @param samplersList The samplers list\n * @param defines The defines helping in the list generation\n * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect\n */\n MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {\n if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }\n var uniformsList;\n var uniformBuffersList = null;\n if (uniformsListOrOptions.uniformsNames) {\n var options = uniformsListOrOptions;\n uniformsList = options.uniformsNames;\n uniformBuffersList = options.uniformBuffersNames;\n samplersList = options.samplers;\n defines = options.defines;\n maxSimultaneousLights = options.maxSimultaneousLights;\n }\n else {\n uniformsList = uniformsListOrOptions;\n if (!samplersList) {\n samplersList = [];\n }\n }\n for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {\n if (!defines[\"LIGHT\" + lightIndex]) {\n break;\n }\n uniformsList.push(\"vLightData\" + lightIndex, \"vLightDiffuse\" + lightIndex, \"vLightSpecular\" + lightIndex, \"vLightDirection\" + lightIndex, \"vLightGround\" + lightIndex, \"lightMatrix\" + lightIndex, \"shadowsInfo\" + lightIndex, \"depthValues\" + lightIndex);\n if (uniformBuffersList) {\n uniformBuffersList.push(\"Light\" + lightIndex);\n }\n samplersList.push(\"shadowSampler\" + lightIndex);\n samplersList.push(\"depthSampler\" + lightIndex);\n if (defines[\"PROJECTEDLIGHTTEXTURE\" + lightIndex]) {\n samplersList.push(\"projectionLightSampler\" + lightIndex);\n uniformsList.push(\"textureProjectionMatrix\" + lightIndex);\n }\n }\n if (defines[\"NUM_MORPH_INFLUENCERS\"]) {\n uniformsList.push(\"morphTargetInfluences\");\n }\n };\n /**\n * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)\n * @param defines The defines to update while falling back\n * @param fallbacks The authorized effect fallbacks\n * @param maxSimultaneousLights The maximum number of lights allowed\n * @param rank the current rank of the Effect\n * @returns The newly affected rank\n */\n MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {\n if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }\n if (rank === void 0) { rank = 0; }\n var lightFallbackRank = 0;\n for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {\n if (!defines[\"LIGHT\" + lightIndex]) {\n break;\n }\n if (lightIndex > 0) {\n lightFallbackRank = rank + lightIndex;\n fallbacks.addFallback(lightFallbackRank, \"LIGHT\" + lightIndex);\n }\n if (!defines[\"SHADOWS\"]) {\n if (defines[\"SHADOW\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOW\" + lightIndex);\n }\n if (defines[\"SHADOWPCF\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWPCF\" + lightIndex);\n }\n if (defines[\"SHADOWPCSS\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWPCSS\" + lightIndex);\n }\n if (defines[\"SHADOWPOISSON\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWPOISSON\" + lightIndex);\n }\n if (defines[\"SHADOWESM\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWESM\" + lightIndex);\n }\n }\n }\n return lightFallbackRank++;\n };\n /**\n * Prepares the list of attributes required for morph targets according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param mesh The mesh to prepare the morph targets attributes for\n * @param defines The current Defines of the effect\n */\n MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {\n var influencers = defines[\"NUM_MORPH_INFLUENCERS\"];\n if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {\n var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;\n var manager = mesh.morphTargetManager;\n var normal = manager && manager.supportsNormals && defines[\"NORMAL\"];\n var tangent = manager && manager.supportsTangents && defines[\"TANGENT\"];\n for (var index = 0; index < influencers; index++) {\n attribs.push(BABYLON.VertexBuffer.PositionKind + index);\n if (normal) {\n attribs.push(BABYLON.VertexBuffer.NormalKind + index);\n }\n if (tangent) {\n attribs.push(BABYLON.VertexBuffer.TangentKind + index);\n }\n if (attribs.length > maxAttributesCount) {\n BABYLON.Tools.Error(\"Cannot add more vertex attributes for mesh \" + mesh.name);\n }\n }\n }\n };\n /**\n * Prepares the list of attributes required for bones according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param mesh The mesh to prepare the bones attributes for\n * @param defines The current Defines of the effect\n * @param fallbacks The current efffect fallback strategy\n */\n MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {\n if (defines[\"NUM_BONE_INFLUENCERS\"] > 0) {\n fallbacks.addCPUSkinningFallback(0, mesh);\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (defines[\"NUM_BONE_INFLUENCERS\"] > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n }\n };\n /**\n * Prepares the list of attributes required for instances according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param defines The current Defines of the effect\n */\n MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {\n if (defines[\"INSTANCES\"]) {\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n };\n /**\n * Binds the light shadow information to the effect for the given mesh.\n * @param light The light containing the generator\n * @param scene The scene the lights belongs to\n * @param mesh The mesh we are binding the information to render\n * @param lightIndex The light index in the effect used to render the mesh\n * @param effect The effect we are binding the data to\n */\n MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {\n if (light.shadowEnabled && mesh.receiveShadows) {\n var shadowGenerator = light.getShadowGenerator();\n if (shadowGenerator) {\n shadowGenerator.bindShadowLight(lightIndex, effect);\n }\n }\n };\n /**\n * Binds the light information to the effect.\n * @param light The light containing the generator\n * @param effect The effect we are binding the data to\n * @param lightIndex The light index in the effect used to render\n */\n MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {\n light.transferToEffect(effect, lightIndex + \"\");\n };\n /**\n * Binds the lights information from the scene to the effect for the given mesh.\n * @param scene The scene the lights belongs to\n * @param mesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n * @param defines The generated defines for the effect\n * @param maxSimultaneousLights The maximum number of light that can be bound to the effect\n * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not\n */\n MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {\n if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }\n if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }\n var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);\n for (var i = 0; i < len; i++) {\n var light = mesh._lightSources[i];\n var iAsString = i.toString();\n var scaledIntensity = light.getScaledIntensity();\n light._uniformBuffer.bindToEffect(effect, \"Light\" + i);\n MaterialHelper.BindLightProperties(light, effect, i);\n light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);\n light._uniformBuffer.updateColor4(\"vLightDiffuse\", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);\n if (defines[\"SPECULARTERM\"]) {\n light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);\n light._uniformBuffer.updateColor3(\"vLightSpecular\", BABYLON.Tmp.Color3[1], iAsString);\n }\n // Shadows\n if (scene.shadowsEnabled) {\n this.BindLightShadow(light, scene, mesh, iAsString, effect);\n }\n light._uniformBuffer.update();\n }\n };\n /**\n * Binds the fog information from the scene to the effect for the given mesh.\n * @param scene The scene the lights belongs to\n * @param mesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n */\n MaterialHelper.BindFogParameters = function (scene, mesh, effect) {\n if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {\n effect.setFloat4(\"vFogInfos\", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);\n effect.setColor3(\"vFogColor\", scene.fogColor);\n }\n };\n /**\n * Binds the bones information from the mesh to the effect.\n * @param mesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n */\n MaterialHelper.BindBonesParameters = function (mesh, effect) {\n if (!effect || !mesh) {\n return;\n }\n if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {\n mesh.computeBonesUsingShaders = false;\n }\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n var matrices = mesh.skeleton.getTransformMatrices(mesh);\n if (matrices) {\n effect.setMatrices(\"mBones\", matrices);\n }\n }\n };\n /**\n * Binds the morph targets information from the mesh to the effect.\n * @param abstractMesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n */\n MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {\n var manager = abstractMesh.morphTargetManager;\n if (!abstractMesh || !manager) {\n return;\n }\n effect.setFloatArray(\"morphTargetInfluences\", manager.influences);\n };\n /**\n * Binds the logarithmic depth information from the scene to the effect for the given defines.\n * @param defines The generated defines used in the effect\n * @param effect The effect we are binding the data to\n * @param scene The scene we are willing to render with logarithmic scale for\n */\n MaterialHelper.BindLogDepth = function (defines, effect, scene) {\n if (defines[\"LOGARITHMICDEPTH\"]) {\n effect.setFloat(\"logarithmicDepthConstant\", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));\n }\n };\n /**\n * Binds the clip plane information from the scene to the effect.\n * @param scene The scene the clip plane information are extracted from\n * @param effect The effect we are binding the data to\n */\n MaterialHelper.BindClipPlane = function (effect, scene) {\n if (scene.clipPlane) {\n var clipPlane = scene.clipPlane;\n effect.setFloat4(\"vClipPlane\", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);\n }\n };\n return MaterialHelper;\n }());\n BABYLON.MaterialHelper = MaterialHelper;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.materialHelper.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var PushMaterial = /** @class */ (function (_super) {\n __extends(PushMaterial, _super);\n function PushMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._normalMatrix = new BABYLON.Matrix();\n _this.storeEffectOnSubMeshes = true;\n return _this;\n }\n PushMaterial.prototype.getEffect = function () {\n return this._activeEffect;\n };\n PushMaterial.prototype.isReady = function (mesh, useInstances) {\n if (!mesh) {\n return false;\n }\n if (!mesh.subMeshes || mesh.subMeshes.length === 0) {\n return true;\n }\n return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);\n };\n /**\n * Binds the given world matrix to the active effect\n *\n * @param world the matrix to bind\n */\n PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {\n this._activeEffect.setMatrix(\"world\", world);\n };\n /**\n * Binds the given normal matrix to the active effect\n *\n * @param normalMatrix the matrix to bind\n */\n PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {\n this._activeEffect.setMatrix(\"normalMatrix\", normalMatrix);\n };\n PushMaterial.prototype.bind = function (world, mesh) {\n if (!mesh) {\n return;\n }\n this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);\n };\n PushMaterial.prototype._afterBind = function (mesh, effect) {\n if (effect === void 0) { effect = null; }\n _super.prototype._afterBind.call(this, mesh);\n this.getScene()._cachedEffect = effect;\n };\n PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {\n if (visibility === void 0) { visibility = 1; }\n return scene.isCachedMaterialInvalid(this, effect, visibility);\n };\n return PushMaterial;\n }(BABYLON.Material));\n BABYLON.PushMaterial = PushMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pushMaterial.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /** @hidden */\n var StandardMaterialDefines = /** @class */ (function (_super) {\n __extends(StandardMaterialDefines, _super);\n function StandardMaterialDefines() {\n var _this = _super.call(this) || this;\n _this.MAINUV1 = false;\n _this.MAINUV2 = false;\n _this.DIFFUSE = false;\n _this.DIFFUSEDIRECTUV = 0;\n _this.AMBIENT = false;\n _this.AMBIENTDIRECTUV = 0;\n _this.OPACITY = false;\n _this.OPACITYDIRECTUV = 0;\n _this.OPACITYRGB = false;\n _this.REFLECTION = false;\n _this.EMISSIVE = false;\n _this.EMISSIVEDIRECTUV = 0;\n _this.SPECULAR = false;\n _this.SPECULARDIRECTUV = 0;\n _this.BUMP = false;\n _this.BUMPDIRECTUV = 0;\n _this.PARALLAX = false;\n _this.PARALLAXOCCLUSION = false;\n _this.SPECULAROVERALPHA = false;\n _this.CLIPPLANE = false;\n _this.ALPHATEST = false;\n _this.DEPTHPREPASS = false;\n _this.ALPHAFROMDIFFUSE = false;\n _this.POINTSIZE = false;\n _this.FOG = false;\n _this.SPECULARTERM = false;\n _this.DIFFUSEFRESNEL = false;\n _this.OPACITYFRESNEL = false;\n _this.REFLECTIONFRESNEL = false;\n _this.REFRACTIONFRESNEL = false;\n _this.EMISSIVEFRESNEL = false;\n _this.FRESNEL = false;\n _this.NORMAL = false;\n _this.UV1 = false;\n _this.UV2 = false;\n _this.VERTEXCOLOR = false;\n _this.VERTEXALPHA = false;\n _this.NUM_BONE_INFLUENCERS = 0;\n _this.BonesPerMesh = 0;\n _this.INSTANCES = false;\n _this.GLOSSINESS = false;\n _this.ROUGHNESS = false;\n _this.EMISSIVEASILLUMINATION = false;\n _this.LINKEMISSIVEWITHDIFFUSE = false;\n _this.REFLECTIONFRESNELFROMSPECULAR = false;\n _this.LIGHTMAP = false;\n _this.LIGHTMAPDIRECTUV = 0;\n _this.OBJECTSPACE_NORMALMAP = false;\n _this.USELIGHTMAPASSHADOWMAP = false;\n _this.REFLECTIONMAP_3D = false;\n _this.REFLECTIONMAP_SPHERICAL = false;\n _this.REFLECTIONMAP_PLANAR = false;\n _this.REFLECTIONMAP_CUBIC = false;\n _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\n _this.REFLECTIONMAP_PROJECTION = false;\n _this.REFLECTIONMAP_SKYBOX = false;\n _this.REFLECTIONMAP_EXPLICIT = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n _this.INVERTCUBICMAP = false;\n _this.LOGARITHMICDEPTH = false;\n _this.REFRACTION = false;\n _this.REFRACTIONMAP_3D = false;\n _this.REFLECTIONOVERALPHA = false;\n _this.TWOSIDEDLIGHTING = false;\n _this.SHADOWFLOAT = false;\n _this.MORPHTARGETS = false;\n _this.MORPHTARGETS_NORMAL = false;\n _this.MORPHTARGETS_TANGENT = false;\n _this.NUM_MORPH_INFLUENCERS = 0;\n _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH\n _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7\n _this.IMAGEPROCESSING = false;\n _this.VIGNETTE = false;\n _this.VIGNETTEBLENDMODEMULTIPLY = false;\n _this.VIGNETTEBLENDMODEOPAQUE = false;\n _this.TONEMAPPING = false;\n _this.CONTRAST = false;\n _this.COLORCURVES = false;\n _this.COLORGRADING = false;\n _this.COLORGRADING3D = false;\n _this.SAMPLER3DGREENDEPTH = false;\n _this.SAMPLER3DBGRMAP = false;\n _this.IMAGEPROCESSINGPOSTPROCESS = false;\n /**\n * If the reflection texture on this material is in linear color space\n * @hidden\n */\n _this.IS_REFLECTION_LINEAR = false;\n /**\n * If the refraction texture on this material is in linear color space\n * @hidden\n */\n _this.IS_REFRACTION_LINEAR = false;\n _this.EXPOSURE = false;\n _this.rebuild();\n return _this;\n }\n StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {\n var modes = [\n \"REFLECTIONMAP_CUBIC\", \"REFLECTIONMAP_EXPLICIT\", \"REFLECTIONMAP_PLANAR\",\n \"REFLECTIONMAP_PROJECTION\", \"REFLECTIONMAP_PROJECTION\", \"REFLECTIONMAP_SKYBOX\",\n \"REFLECTIONMAP_SPHERICAL\", \"REFLECTIONMAP_EQUIRECTANGULAR\", \"REFLECTIONMAP_EQUIRECTANGULAR_FIXED\",\n \"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\"\n ];\n for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {\n var mode = modes_1[_i];\n this[mode] = (mode === modeToEnable);\n }\n };\n return StandardMaterialDefines;\n }(BABYLON.MaterialDefines));\n BABYLON.StandardMaterialDefines = StandardMaterialDefines;\n var StandardMaterial = /** @class */ (function (_super) {\n __extends(StandardMaterial, _super);\n function StandardMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this.ambientColor = new BABYLON.Color3(0, 0, 0);\n _this.diffuseColor = new BABYLON.Color3(1, 1, 1);\n _this.specularColor = new BABYLON.Color3(1, 1, 1);\n _this.emissiveColor = new BABYLON.Color3(0, 0, 0);\n _this.specularPower = 64;\n _this._useAlphaFromDiffuseTexture = false;\n _this._useEmissiveAsIllumination = false;\n _this._linkEmissiveWithDiffuse = false;\n _this._useSpecularOverAlpha = false;\n _this._useReflectionOverAlpha = false;\n _this._disableLighting = false;\n _this._useObjectSpaceNormalMap = false;\n _this._useParallax = false;\n _this._useParallaxOcclusion = false;\n _this.parallaxScaleBias = 0.05;\n _this._roughness = 0;\n _this.indexOfRefraction = 0.98;\n _this.invertRefractionY = true;\n /**\n * Defines the alpha limits in alpha test mode\n */\n _this.alphaCutOff = 0.4;\n _this._useLightmapAsShadowmap = false;\n _this._useReflectionFresnelFromSpecular = false;\n _this._useGlossinessFromSpecularMapAlpha = false;\n _this._maxSimultaneousLights = 4;\n /**\n * If sets to true, x component of normal map value will invert (x = 1.0 - x).\n */\n _this._invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will invert (y = 1.0 - y).\n */\n _this._invertNormalMapY = false;\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n */\n _this._twoSidedLighting = false;\n _this._renderTargets = new BABYLON.SmartArray(16);\n _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();\n _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);\n // Setup the default processing configuration to the scene.\n _this._attachImageProcessingConfiguration(null);\n _this.getRenderTargetTextures = function () {\n _this._renderTargets.reset();\n if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {\n _this._renderTargets.push(_this._reflectionTexture);\n }\n if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {\n _this._renderTargets.push(_this._refractionTexture);\n }\n return _this._renderTargets;\n };\n return _this;\n }\n Object.defineProperty(StandardMaterial.prototype, \"imageProcessingConfiguration\", {\n /**\n * Gets the image processing configuration used either in this material.\n */\n get: function () {\n return this._imageProcessingConfiguration;\n },\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set: function (value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Attaches a new image processing configuration to the Standard Material.\n * @param configuration\n */\n StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {\n var _this = this;\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {\n _this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n };\n Object.defineProperty(StandardMaterial.prototype, \"cameraColorCurvesEnabled\", {\n /**\n * Gets wether the color curves effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n },\n /**\n * Sets wether the color curves effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial.prototype, \"cameraColorGradingEnabled\", {\n /**\n * Gets wether the color grading effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n },\n /**\n * Gets wether the color grading effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial.prototype, \"cameraToneMappingEnabled\", {\n /**\n * Gets wether tonemapping is enabled or not.\n */\n get: function () {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n },\n /**\n * Sets wether tonemapping is enabled or not\n */\n set: function (value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(StandardMaterial.prototype, \"cameraExposure\", {\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n get: function () {\n return this._imageProcessingConfiguration.exposure;\n },\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n set: function (value) {\n this._imageProcessingConfiguration.exposure = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(StandardMaterial.prototype, \"cameraContrast\", {\n /**\n * Gets The camera contrast used on this material.\n */\n get: function () {\n return this._imageProcessingConfiguration.contrast;\n },\n /**\n * Sets The camera contrast used on this material.\n */\n set: function (value) {\n this._imageProcessingConfiguration.contrast = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial.prototype, \"cameraColorGradingTexture\", {\n /**\n * Gets the Color Grading 2D Lookup Texture.\n */\n get: function () {\n return this._imageProcessingConfiguration.colorGradingTexture;\n },\n /**\n * Sets the Color Grading 2D Lookup Texture.\n */\n set: function (value) {\n this._imageProcessingConfiguration.colorGradingTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial.prototype, \"cameraColorCurves\", {\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n get: function () {\n return this._imageProcessingConfiguration.colorCurves;\n },\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n set: function (value) {\n this._imageProcessingConfiguration.colorCurves = value;\n },\n enumerable: true,\n configurable: true\n });\n StandardMaterial.prototype.getClassName = function () {\n return \"StandardMaterial\";\n };\n Object.defineProperty(StandardMaterial.prototype, \"useLogarithmicDepth\", {\n get: function () {\n return this._useLogarithmicDepth;\n },\n set: function (value) {\n this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;\n this._markAllSubMeshesAsMiscDirty();\n },\n enumerable: true,\n configurable: true\n });\n StandardMaterial.prototype.needAlphaBlending = function () {\n return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;\n };\n StandardMaterial.prototype.needAlphaTesting = function () {\n return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;\n };\n StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {\n return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;\n };\n StandardMaterial.prototype.getAlphaTestTexture = function () {\n return this._diffuseTexture;\n };\n /**\n * Child classes can use it to update shaders\n */\n StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {\n if (useInstances === void 0) { useInstances = false; }\n if (subMesh.effect && this.isFrozen) {\n if (this._wasPreviouslyReady && subMesh.effect) {\n return true;\n }\n }\n if (!subMesh._materialDefines) {\n subMesh._materialDefines = new StandardMaterialDefines();\n }\n var scene = this.getScene();\n var defines = subMesh._materialDefines;\n if (!this.checkReadyOnEveryCall && subMesh.effect) {\n if (defines._renderId === scene.getRenderId()) {\n return true;\n }\n }\n var engine = scene.getEngine();\n // Lights\n defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);\n // Textures\n if (defines._areTexturesDirty) {\n defines._needUVs = false;\n defines.MAINUV1 = false;\n defines.MAINUV2 = false;\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {\n if (!this._diffuseTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, \"DIFFUSE\");\n }\n }\n else {\n defines.DIFFUSE = false;\n }\n if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {\n if (!this._ambientTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, \"AMBIENT\");\n }\n }\n else {\n defines.AMBIENT = false;\n }\n if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {\n if (!this._opacityTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, \"OPACITY\");\n defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;\n }\n }\n else {\n defines.OPACITY = false;\n }\n if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {\n if (!this._reflectionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n defines._needNormals = true;\n defines.REFLECTION = true;\n defines.ROUGHNESS = (this._roughness > 0);\n defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;\n defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);\n defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;\n switch (this._reflectionTexture.coordinatesMode) {\n case BABYLON.Texture.EXPLICIT_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_EXPLICIT\");\n break;\n case BABYLON.Texture.PLANAR_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_PLANAR\");\n break;\n case BABYLON.Texture.PROJECTION_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_PROJECTION\");\n break;\n case BABYLON.Texture.SKYBOX_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_SKYBOX\");\n break;\n case BABYLON.Texture.SPHERICAL_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_SPHERICAL\");\n break;\n case BABYLON.Texture.EQUIRECTANGULAR_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_EQUIRECTANGULAR\");\n break;\n case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_EQUIRECTANGULAR_FIXED\");\n break;\n case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\");\n break;\n case BABYLON.Texture.CUBIC_MODE:\n case BABYLON.Texture.INVCUBIC_MODE:\n default:\n defines.setReflectionMode(\"REFLECTIONMAP_CUBIC\");\n break;\n }\n defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;\n }\n }\n else {\n defines.REFLECTION = false;\n }\n if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {\n if (!this._emissiveTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, \"EMISSIVE\");\n }\n }\n else {\n defines.EMISSIVE = false;\n }\n if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {\n if (!this._lightmapTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, \"LIGHTMAP\");\n defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;\n }\n }\n else {\n defines.LIGHTMAP = false;\n }\n if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {\n if (!this._specularTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, \"SPECULAR\");\n defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;\n }\n }\n else {\n defines.SPECULAR = false;\n }\n if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {\n // Bump texure can not be not blocking.\n if (!this._bumpTexture.isReady()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, \"BUMP\");\n defines.PARALLAX = this._useParallax;\n defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;\n }\n defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;\n }\n else {\n defines.BUMP = false;\n }\n if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {\n if (!this._refractionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n defines._needUVs = true;\n defines.REFRACTION = true;\n defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;\n }\n }\n else {\n defines.REFRACTION = false;\n }\n defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;\n }\n else {\n defines.DIFFUSE = false;\n defines.AMBIENT = false;\n defines.OPACITY = false;\n defines.REFLECTION = false;\n defines.EMISSIVE = false;\n defines.LIGHTMAP = false;\n defines.BUMP = false;\n defines.REFRACTION = false;\n }\n defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();\n defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;\n defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;\n defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;\n defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n if (!this._imageProcessingConfiguration.isReady()) {\n return false;\n }\n this._imageProcessingConfiguration.prepareDefines(defines);\n defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);\n defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);\n }\n if (defines._areFresnelDirty) {\n if (StandardMaterial.FresnelEnabled) {\n // Fresnel\n if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||\n this._emissiveFresnelParameters || this._refractionFresnelParameters ||\n this._reflectionFresnelParameters) {\n defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);\n defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);\n defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);\n defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;\n defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);\n defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);\n defines._needNormals = true;\n defines.FRESNEL = true;\n }\n }\n else {\n defines.FRESNEL = false;\n }\n }\n // Misc.\n BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);\n // Attribs\n BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);\n // Values that need to be evaluated on every frame\n BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);\n // Get correct effect \n if (defines.isDirty) {\n defines.markAsProcessed();\n scene.resetCachedMaterial();\n // Fallbacks\n var fallbacks = new BABYLON.EffectFallbacks();\n if (defines.REFLECTION) {\n fallbacks.addFallback(0, \"REFLECTION\");\n }\n if (defines.SPECULAR) {\n fallbacks.addFallback(0, \"SPECULAR\");\n }\n if (defines.BUMP) {\n fallbacks.addFallback(0, \"BUMP\");\n }\n if (defines.PARALLAX) {\n fallbacks.addFallback(1, \"PARALLAX\");\n }\n if (defines.PARALLAXOCCLUSION) {\n fallbacks.addFallback(0, \"PARALLAXOCCLUSION\");\n }\n if (defines.SPECULAROVERALPHA) {\n fallbacks.addFallback(0, \"SPECULAROVERALPHA\");\n }\n if (defines.FOG) {\n fallbacks.addFallback(1, \"FOG\");\n }\n if (defines.POINTSIZE) {\n fallbacks.addFallback(0, \"POINTSIZE\");\n }\n if (defines.LOGARITHMICDEPTH) {\n fallbacks.addFallback(0, \"LOGARITHMICDEPTH\");\n }\n BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);\n if (defines.SPECULARTERM) {\n fallbacks.addFallback(0, \"SPECULARTERM\");\n }\n if (defines.DIFFUSEFRESNEL) {\n fallbacks.addFallback(1, \"DIFFUSEFRESNEL\");\n }\n if (defines.OPACITYFRESNEL) {\n fallbacks.addFallback(2, \"OPACITYFRESNEL\");\n }\n if (defines.REFLECTIONFRESNEL) {\n fallbacks.addFallback(3, \"REFLECTIONFRESNEL\");\n }\n if (defines.EMISSIVEFRESNEL) {\n fallbacks.addFallback(4, \"EMISSIVEFRESNEL\");\n }\n if (defines.FRESNEL) {\n fallbacks.addFallback(4, \"FRESNEL\");\n }\n //Attributes\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n if (defines.NORMAL) {\n attribs.push(BABYLON.VertexBuffer.NormalKind);\n }\n if (defines.UV1) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n }\n if (defines.UV2) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n }\n if (defines.VERTEXCOLOR) {\n attribs.push(BABYLON.VertexBuffer.ColorKind);\n }\n BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);\n BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);\n BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);\n var shaderName = \"default\";\n var uniforms = [\"world\", \"view\", \"viewProjection\", \"vEyePosition\", \"vLightsType\", \"vAmbientColor\", \"vDiffuseColor\", \"vSpecularColor\", \"vEmissiveColor\",\n \"vFogInfos\", \"vFogColor\", \"pointSize\",\n \"vDiffuseInfos\", \"vAmbientInfos\", \"vOpacityInfos\", \"vReflectionInfos\", \"vEmissiveInfos\", \"vSpecularInfos\", \"vBumpInfos\", \"vLightmapInfos\", \"vRefractionInfos\",\n \"mBones\",\n \"vClipPlane\", \"diffuseMatrix\", \"ambientMatrix\", \"opacityMatrix\", \"reflectionMatrix\", \"emissiveMatrix\", \"specularMatrix\", \"bumpMatrix\", \"normalMatrix\", \"lightmapMatrix\", \"refractionMatrix\",\n \"diffuseLeftColor\", \"diffuseRightColor\", \"opacityParts\", \"reflectionLeftColor\", \"reflectionRightColor\", \"emissiveLeftColor\", \"emissiveRightColor\", \"refractionLeftColor\", \"refractionRightColor\",\n \"vReflectionPosition\", \"vReflectionSize\",\n \"logarithmicDepthConstant\", \"vTangentSpaceParams\", \"alphaCutOff\"\n ];\n var samplers = [\"diffuseSampler\", \"ambientSampler\", \"opacitySampler\", \"reflectionCubeSampler\", \"reflection2DSampler\", \"emissiveSampler\", \"specularSampler\", \"bumpSampler\", \"lightmapSampler\", \"refractionCubeSampler\", \"refraction2DSampler\"];\n var uniformBuffers = [\"Material\", \"Scene\"];\n if (BABYLON.ImageProcessingConfiguration) {\n BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);\n BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);\n }\n BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: defines,\n maxSimultaneousLights: this._maxSimultaneousLights\n });\n if (this.customShaderNameResolve) {\n shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);\n }\n var join = defines.toString();\n subMesh.setEffect(scene.getEngine().createEffect(shaderName, {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: this.onCompiled,\n onError: this.onError,\n indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }\n }, engine), defines);\n this.buildUniformLayout();\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n this._wasPreviouslyReady = true;\n return true;\n };\n StandardMaterial.prototype.buildUniformLayout = function () {\n // Order is important !\n this._uniformBuffer.addUniform(\"diffuseLeftColor\", 4);\n this._uniformBuffer.addUniform(\"diffuseRightColor\", 4);\n this._uniformBuffer.addUniform(\"opacityParts\", 4);\n this._uniformBuffer.addUniform(\"reflectionLeftColor\", 4);\n this._uniformBuffer.addUniform(\"reflectionRightColor\", 4);\n this._uniformBuffer.addUniform(\"refractionLeftColor\", 4);\n this._uniformBuffer.addUniform(\"refractionRightColor\", 4);\n this._uniformBuffer.addUniform(\"emissiveLeftColor\", 4);\n this._uniformBuffer.addUniform(\"emissiveRightColor\", 4);\n this._uniformBuffer.addUniform(\"vDiffuseInfos\", 2);\n this._uniformBuffer.addUniform(\"vAmbientInfos\", 2);\n this._uniformBuffer.addUniform(\"vOpacityInfos\", 2);\n this._uniformBuffer.addUniform(\"vReflectionInfos\", 2);\n this._uniformBuffer.addUniform(\"vReflectionPosition\", 3);\n this._uniformBuffer.addUniform(\"vReflectionSize\", 3);\n this._uniformBuffer.addUniform(\"vEmissiveInfos\", 2);\n this._uniformBuffer.addUniform(\"vLightmapInfos\", 2);\n this._uniformBuffer.addUniform(\"vSpecularInfos\", 2);\n this._uniformBuffer.addUniform(\"vBumpInfos\", 3);\n this._uniformBuffer.addUniform(\"diffuseMatrix\", 16);\n this._uniformBuffer.addUniform(\"ambientMatrix\", 16);\n this._uniformBuffer.addUniform(\"opacityMatrix\", 16);\n this._uniformBuffer.addUniform(\"reflectionMatrix\", 16);\n this._uniformBuffer.addUniform(\"emissiveMatrix\", 16);\n this._uniformBuffer.addUniform(\"lightmapMatrix\", 16);\n this._uniformBuffer.addUniform(\"specularMatrix\", 16);\n this._uniformBuffer.addUniform(\"bumpMatrix\", 16);\n this._uniformBuffer.addUniform(\"vTangentSpaceParams\", 2);\n this._uniformBuffer.addUniform(\"refractionMatrix\", 16);\n this._uniformBuffer.addUniform(\"vRefractionInfos\", 4);\n this._uniformBuffer.addUniform(\"vSpecularColor\", 4);\n this._uniformBuffer.addUniform(\"vEmissiveColor\", 3);\n this._uniformBuffer.addUniform(\"vDiffuseColor\", 4);\n this._uniformBuffer.addUniform(\"pointSize\", 1);\n this._uniformBuffer.create();\n };\n StandardMaterial.prototype.unbind = function () {\n if (this._activeEffect) {\n var needFlag = false;\n if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._activeEffect.setTexture(\"reflection2DSampler\", null);\n needFlag = true;\n }\n if (this._refractionTexture && this._refractionTexture.isRenderTarget) {\n this._activeEffect.setTexture(\"refraction2DSampler\", null);\n needFlag = true;\n }\n if (needFlag) {\n this._markAllSubMeshesAsTexturesDirty();\n }\n }\n _super.prototype.unbind.call(this);\n };\n StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {\n var scene = this.getScene();\n var defines = subMesh._materialDefines;\n if (!defines) {\n return;\n }\n var effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices \n this.bindOnlyWorldMatrix(world);\n // Normal Matrix\n if (defines.OBJECTSPACE_NORMALMAP) {\n world.toNormalMatrix(this._normalMatrix);\n this.bindOnlyNormalMatrix(this._normalMatrix);\n }\n var mustRebind = this._mustRebind(scene, effect, mesh.visibility);\n // Bones\n BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);\n if (mustRebind) {\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this.bindViewProjection(effect);\n if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {\n if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {\n // Fresnel\n if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {\n this._uniformBuffer.updateColor4(\"diffuseLeftColor\", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);\n this._uniformBuffer.updateColor4(\"diffuseRightColor\", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);\n }\n if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {\n this._uniformBuffer.updateColor4(\"opacityParts\", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);\n }\n if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {\n this._uniformBuffer.updateColor4(\"reflectionLeftColor\", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);\n this._uniformBuffer.updateColor4(\"reflectionRightColor\", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);\n }\n if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {\n this._uniformBuffer.updateColor4(\"refractionLeftColor\", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);\n this._uniformBuffer.updateColor4(\"refractionRightColor\", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);\n }\n if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {\n this._uniformBuffer.updateColor4(\"emissiveLeftColor\", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);\n this._uniformBuffer.updateColor4(\"emissiveRightColor\", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);\n }\n }\n // Textures \n if (scene.texturesEnabled) {\n if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vDiffuseInfos\", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, \"diffuse\");\n if (this._diffuseTexture.hasAlpha) {\n effect.setFloat(\"alphaCutOff\", this.alphaCutOff);\n }\n }\n if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vAmbientInfos\", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, \"ambient\");\n }\n if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vOpacityInfos\", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, \"opacity\");\n }\n if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vReflectionInfos\", this._reflectionTexture.level, this.roughness);\n this._uniformBuffer.updateMatrix(\"reflectionMatrix\", this._reflectionTexture.getReflectionTextureMatrix());\n if (this._reflectionTexture.boundingBoxSize) {\n var cubeTexture = this._reflectionTexture;\n this._uniformBuffer.updateVector3(\"vReflectionPosition\", cubeTexture.boundingBoxPosition);\n this._uniformBuffer.updateVector3(\"vReflectionSize\", cubeTexture.boundingBoxSize);\n }\n }\n if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vEmissiveInfos\", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, \"emissive\");\n }\n if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vLightmapInfos\", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, \"lightmap\");\n }\n if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vSpecularInfos\", this._specularTexture.coordinatesIndex, this._specularTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, \"specular\");\n }\n if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {\n this._uniformBuffer.updateFloat3(\"vBumpInfos\", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);\n BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, \"bump\");\n if (scene._mirroredCameraPosition) {\n this._uniformBuffer.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);\n }\n else {\n this._uniformBuffer.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);\n }\n }\n if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {\n var depth = 1.0;\n if (!this._refractionTexture.isCube) {\n this._uniformBuffer.updateMatrix(\"refractionMatrix\", this._refractionTexture.getReflectionTextureMatrix());\n if (this._refractionTexture.depth) {\n depth = this._refractionTexture.depth;\n }\n }\n this._uniformBuffer.updateFloat4(\"vRefractionInfos\", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);\n }\n }\n // Point size\n if (this.pointsCloud) {\n this._uniformBuffer.updateFloat(\"pointSize\", this.pointSize);\n }\n if (defines.SPECULARTERM) {\n this._uniformBuffer.updateColor4(\"vSpecularColor\", this.specularColor, this.specularPower);\n }\n this._uniformBuffer.updateColor3(\"vEmissiveColor\", this.emissiveColor);\n // Diffuse\n this._uniformBuffer.updateColor4(\"vDiffuseColor\", this.diffuseColor, this.alpha * mesh.visibility);\n }\n // Textures \n if (scene.texturesEnabled) {\n if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {\n effect.setTexture(\"diffuseSampler\", this._diffuseTexture);\n }\n if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {\n effect.setTexture(\"ambientSampler\", this._ambientTexture);\n }\n if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {\n effect.setTexture(\"opacitySampler\", this._opacityTexture);\n }\n if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {\n if (this._reflectionTexture.isCube) {\n effect.setTexture(\"reflectionCubeSampler\", this._reflectionTexture);\n }\n else {\n effect.setTexture(\"reflection2DSampler\", this._reflectionTexture);\n }\n }\n if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {\n effect.setTexture(\"emissiveSampler\", this._emissiveTexture);\n }\n if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {\n effect.setTexture(\"lightmapSampler\", this._lightmapTexture);\n }\n if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {\n effect.setTexture(\"specularSampler\", this._specularTexture);\n }\n if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {\n effect.setTexture(\"bumpSampler\", this._bumpTexture);\n }\n if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {\n var depth = 1.0;\n if (this._refractionTexture.isCube) {\n effect.setTexture(\"refractionCubeSampler\", this._refractionTexture);\n }\n else {\n effect.setTexture(\"refraction2DSampler\", this._refractionTexture);\n }\n }\n }\n // Clip plane\n BABYLON.MaterialHelper.BindClipPlane(effect, scene);\n // Colors\n scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);\n BABYLON.MaterialHelper.BindEyePosition(effect, scene);\n effect.setColor3(\"vAmbientColor\", this._globalAmbientColor);\n }\n if (mustRebind || !this.isFrozen) {\n // Lights\n if (scene.lightsEnabled && !this._disableLighting) {\n BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);\n }\n // View\n if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {\n this.bindView(effect);\n }\n // Fog\n BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);\n // Morph targets\n if (defines.NUM_MORPH_INFLUENCERS) {\n BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);\n }\n // Log. depth\n BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);\n // image processing\n if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {\n this._imageProcessingConfiguration.bind(this._activeEffect);\n }\n }\n this._uniformBuffer.update();\n this._afterBind(mesh, this._activeEffect);\n };\n StandardMaterial.prototype.getAnimatables = function () {\n var results = [];\n if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {\n results.push(this._diffuseTexture);\n }\n if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {\n results.push(this._ambientTexture);\n }\n if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {\n results.push(this._opacityTexture);\n }\n if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {\n results.push(this._reflectionTexture);\n }\n if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {\n results.push(this._emissiveTexture);\n }\n if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {\n results.push(this._specularTexture);\n }\n if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {\n results.push(this._bumpTexture);\n }\n if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {\n results.push(this._lightmapTexture);\n }\n if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {\n results.push(this._refractionTexture);\n }\n return results;\n };\n StandardMaterial.prototype.getActiveTextures = function () {\n var activeTextures = _super.prototype.getActiveTextures.call(this);\n if (this._diffuseTexture) {\n activeTextures.push(this._diffuseTexture);\n }\n if (this._ambientTexture) {\n activeTextures.push(this._ambientTexture);\n }\n if (this._opacityTexture) {\n activeTextures.push(this._opacityTexture);\n }\n if (this._reflectionTexture) {\n activeTextures.push(this._reflectionTexture);\n }\n if (this._emissiveTexture) {\n activeTextures.push(this._emissiveTexture);\n }\n if (this._specularTexture) {\n activeTextures.push(this._specularTexture);\n }\n if (this._bumpTexture) {\n activeTextures.push(this._bumpTexture);\n }\n if (this._lightmapTexture) {\n activeTextures.push(this._lightmapTexture);\n }\n if (this._refractionTexture) {\n activeTextures.push(this._refractionTexture);\n }\n return activeTextures;\n };\n StandardMaterial.prototype.hasTexture = function (texture) {\n if (_super.prototype.hasTexture.call(this, texture)) {\n return true;\n }\n if (this._diffuseTexture === texture) {\n return true;\n }\n if (this._ambientTexture === texture) {\n return true;\n }\n if (this._opacityTexture === texture) {\n return true;\n }\n if (this._reflectionTexture === texture) {\n return true;\n }\n if (this._emissiveTexture === texture) {\n return true;\n }\n if (this._specularTexture === texture) {\n return true;\n }\n if (this._bumpTexture === texture) {\n return true;\n }\n if (this._lightmapTexture === texture) {\n return true;\n }\n if (this._refractionTexture === texture) {\n return true;\n }\n return false;\n };\n StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {\n if (forceDisposeTextures) {\n if (this._diffuseTexture) {\n this._diffuseTexture.dispose();\n }\n if (this._ambientTexture) {\n this._ambientTexture.dispose();\n }\n if (this._opacityTexture) {\n this._opacityTexture.dispose();\n }\n if (this._reflectionTexture) {\n this._reflectionTexture.dispose();\n }\n if (this._emissiveTexture) {\n this._emissiveTexture.dispose();\n }\n if (this._specularTexture) {\n this._specularTexture.dispose();\n }\n if (this._bumpTexture) {\n this._bumpTexture.dispose();\n }\n if (this._lightmapTexture) {\n this._lightmapTexture.dispose();\n }\n if (this._refractionTexture) {\n this._refractionTexture.dispose();\n }\n }\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);\n };\n StandardMaterial.prototype.clone = function (name) {\n var _this = this;\n var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);\n result.name = name;\n result.id = name;\n return result;\n };\n StandardMaterial.prototype.serialize = function () {\n return BABYLON.SerializationHelper.Serialize(this);\n };\n // Statics\n StandardMaterial.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);\n };\n Object.defineProperty(StandardMaterial, \"DiffuseTextureEnabled\", {\n get: function () {\n return StandardMaterial._DiffuseTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._DiffuseTextureEnabled === value) {\n return;\n }\n StandardMaterial._DiffuseTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"AmbientTextureEnabled\", {\n get: function () {\n return StandardMaterial._AmbientTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._AmbientTextureEnabled === value) {\n return;\n }\n StandardMaterial._AmbientTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"OpacityTextureEnabled\", {\n get: function () {\n return StandardMaterial._OpacityTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._OpacityTextureEnabled === value) {\n return;\n }\n StandardMaterial._OpacityTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"ReflectionTextureEnabled\", {\n get: function () {\n return StandardMaterial._ReflectionTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._ReflectionTextureEnabled === value) {\n return;\n }\n StandardMaterial._ReflectionTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"EmissiveTextureEnabled\", {\n get: function () {\n return StandardMaterial._EmissiveTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._EmissiveTextureEnabled === value) {\n return;\n }\n StandardMaterial._EmissiveTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"SpecularTextureEnabled\", {\n get: function () {\n return StandardMaterial._SpecularTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._SpecularTextureEnabled === value) {\n return;\n }\n StandardMaterial._SpecularTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"BumpTextureEnabled\", {\n get: function () {\n return StandardMaterial._BumpTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._BumpTextureEnabled === value) {\n return;\n }\n StandardMaterial._BumpTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"LightmapTextureEnabled\", {\n get: function () {\n return StandardMaterial._LightmapTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._LightmapTextureEnabled === value) {\n return;\n }\n StandardMaterial._LightmapTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"RefractionTextureEnabled\", {\n get: function () {\n return StandardMaterial._RefractionTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._RefractionTextureEnabled === value) {\n return;\n }\n StandardMaterial._RefractionTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"ColorGradingTextureEnabled\", {\n get: function () {\n return StandardMaterial._ColorGradingTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._ColorGradingTextureEnabled === value) {\n return;\n }\n StandardMaterial._ColorGradingTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"FresnelEnabled\", {\n get: function () {\n return StandardMaterial._FresnelEnabled;\n },\n set: function (value) {\n if (StandardMaterial._FresnelEnabled === value) {\n return;\n }\n StandardMaterial._FresnelEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n // Flags used to enable or disable a type of texture for all Standard Materials\n StandardMaterial._DiffuseTextureEnabled = true;\n StandardMaterial._AmbientTextureEnabled = true;\n StandardMaterial._OpacityTextureEnabled = true;\n StandardMaterial._ReflectionTextureEnabled = true;\n StandardMaterial._EmissiveTextureEnabled = true;\n StandardMaterial._SpecularTextureEnabled = true;\n StandardMaterial._BumpTextureEnabled = true;\n StandardMaterial._LightmapTextureEnabled = true;\n StandardMaterial._RefractionTextureEnabled = true;\n StandardMaterial._ColorGradingTextureEnabled = true;\n StandardMaterial._FresnelEnabled = true;\n __decorate([\n BABYLON.serializeAsTexture(\"diffuseTexture\")\n ], StandardMaterial.prototype, \"_diffuseTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n ], StandardMaterial.prototype, \"diffuseTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"ambientTexture\")\n ], StandardMaterial.prototype, \"_ambientTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"ambientTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"opacityTexture\")\n ], StandardMaterial.prototype, \"_opacityTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n ], StandardMaterial.prototype, \"opacityTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"reflectionTexture\")\n ], StandardMaterial.prototype, \"_reflectionTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"reflectionTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"emissiveTexture\")\n ], StandardMaterial.prototype, \"_emissiveTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"emissiveTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"specularTexture\")\n ], StandardMaterial.prototype, \"_specularTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"specularTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"bumpTexture\")\n ], StandardMaterial.prototype, \"_bumpTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"bumpTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"lightmapTexture\")\n ], StandardMaterial.prototype, \"_lightmapTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"lightmapTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"refractionTexture\")\n ], StandardMaterial.prototype, \"_refractionTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"refractionTexture\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"ambient\")\n ], StandardMaterial.prototype, \"ambientColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"diffuse\")\n ], StandardMaterial.prototype, \"diffuseColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"specular\")\n ], StandardMaterial.prototype, \"specularColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"emissive\")\n ], StandardMaterial.prototype, \"emissiveColor\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardMaterial.prototype, \"specularPower\", void 0);\n __decorate([\n BABYLON.serialize(\"useAlphaFromDiffuseTexture\")\n ], StandardMaterial.prototype, \"_useAlphaFromDiffuseTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useAlphaFromDiffuseTexture\", void 0);\n __decorate([\n BABYLON.serialize(\"useEmissiveAsIllumination\")\n ], StandardMaterial.prototype, \"_useEmissiveAsIllumination\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useEmissiveAsIllumination\", void 0);\n __decorate([\n BABYLON.serialize(\"linkEmissiveWithDiffuse\")\n ], StandardMaterial.prototype, \"_linkEmissiveWithDiffuse\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"linkEmissiveWithDiffuse\", void 0);\n __decorate([\n BABYLON.serialize(\"useSpecularOverAlpha\")\n ], StandardMaterial.prototype, \"_useSpecularOverAlpha\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useSpecularOverAlpha\", void 0);\n __decorate([\n BABYLON.serialize(\"useReflectionOverAlpha\")\n ], StandardMaterial.prototype, \"_useReflectionOverAlpha\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useReflectionOverAlpha\", void 0);\n __decorate([\n BABYLON.serialize(\"disableLighting\")\n ], StandardMaterial.prototype, \"_disableLighting\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], StandardMaterial.prototype, \"disableLighting\", void 0);\n __decorate([\n BABYLON.serialize(\"useObjectSpaceNormalMap\")\n ], StandardMaterial.prototype, \"_useObjectSpaceNormalMap\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useObjectSpaceNormalMap\", void 0);\n __decorate([\n BABYLON.serialize(\"useParallax\")\n ], StandardMaterial.prototype, \"_useParallax\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useParallax\", void 0);\n __decorate([\n BABYLON.serialize(\"useParallaxOcclusion\")\n ], StandardMaterial.prototype, \"_useParallaxOcclusion\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useParallaxOcclusion\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardMaterial.prototype, \"parallaxScaleBias\", void 0);\n __decorate([\n BABYLON.serialize(\"roughness\")\n ], StandardMaterial.prototype, \"_roughness\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"roughness\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardMaterial.prototype, \"indexOfRefraction\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardMaterial.prototype, \"invertRefractionY\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardMaterial.prototype, \"alphaCutOff\", void 0);\n __decorate([\n BABYLON.serialize(\"useLightmapAsShadowmap\")\n ], StandardMaterial.prototype, \"_useLightmapAsShadowmap\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useLightmapAsShadowmap\", void 0);\n __decorate([\n BABYLON.serializeAsFresnelParameters(\"diffuseFresnelParameters\")\n ], StandardMaterial.prototype, \"_diffuseFresnelParameters\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n ], StandardMaterial.prototype, \"diffuseFresnelParameters\", void 0);\n __decorate([\n BABYLON.serializeAsFresnelParameters(\"opacityFresnelParameters\")\n ], StandardMaterial.prototype, \"_opacityFresnelParameters\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsFresnelAndMiscDirty\")\n ], StandardMaterial.prototype, \"opacityFresnelParameters\", void 0);\n __decorate([\n BABYLON.serializeAsFresnelParameters(\"reflectionFresnelParameters\")\n ], StandardMaterial.prototype, \"_reflectionFresnelParameters\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n ], StandardMaterial.prototype, \"reflectionFresnelParameters\", void 0);\n __decorate([\n BABYLON.serializeAsFresnelParameters(\"refractionFresnelParameters\")\n ], StandardMaterial.prototype, \"_refractionFresnelParameters\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n ], StandardMaterial.prototype, \"refractionFresnelParameters\", void 0);\n __decorate([\n BABYLON.serializeAsFresnelParameters(\"emissiveFresnelParameters\")\n ], StandardMaterial.prototype, \"_emissiveFresnelParameters\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n ], StandardMaterial.prototype, \"emissiveFresnelParameters\", void 0);\n __decorate([\n BABYLON.serialize(\"useReflectionFresnelFromSpecular\")\n ], StandardMaterial.prototype, \"_useReflectionFresnelFromSpecular\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n ], StandardMaterial.prototype, \"useReflectionFresnelFromSpecular\", void 0);\n __decorate([\n BABYLON.serialize(\"useGlossinessFromSpecularMapAlpha\")\n ], StandardMaterial.prototype, \"_useGlossinessFromSpecularMapAlpha\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useGlossinessFromSpecularMapAlpha\", void 0);\n __decorate([\n BABYLON.serialize(\"maxSimultaneousLights\")\n ], StandardMaterial.prototype, \"_maxSimultaneousLights\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], StandardMaterial.prototype, \"maxSimultaneousLights\", void 0);\n __decorate([\n BABYLON.serialize(\"invertNormalMapX\")\n ], StandardMaterial.prototype, \"_invertNormalMapX\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"invertNormalMapX\", void 0);\n __decorate([\n BABYLON.serialize(\"invertNormalMapY\")\n ], StandardMaterial.prototype, \"_invertNormalMapY\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"invertNormalMapY\", void 0);\n __decorate([\n BABYLON.serialize(\"twoSidedLighting\")\n ], StandardMaterial.prototype, \"_twoSidedLighting\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"twoSidedLighting\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardMaterial.prototype, \"useLogarithmicDepth\", null);\n return StandardMaterial;\n }(BABYLON.PushMaterial));\n BABYLON.StandardMaterial = StandardMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.standardMaterial.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class representing spherical polynomial coefficients to the 3rd degree\n */\n var SphericalPolynomial = /** @class */ (function () {\n function SphericalPolynomial() {\n /**\n * The x coefficients of the spherical polynomial\n */\n this.x = BABYLON.Vector3.Zero();\n /**\n * The y coefficients of the spherical polynomial\n */\n this.y = BABYLON.Vector3.Zero();\n /**\n * The z coefficients of the spherical polynomial\n */\n this.z = BABYLON.Vector3.Zero();\n /**\n * The xx coefficients of the spherical polynomial\n */\n this.xx = BABYLON.Vector3.Zero();\n /**\n * The yy coefficients of the spherical polynomial\n */\n this.yy = BABYLON.Vector3.Zero();\n /**\n * The zz coefficients of the spherical polynomial\n */\n this.zz = BABYLON.Vector3.Zero();\n /**\n * The xy coefficients of the spherical polynomial\n */\n this.xy = BABYLON.Vector3.Zero();\n /**\n * The yz coefficients of the spherical polynomial\n */\n this.yz = BABYLON.Vector3.Zero();\n /**\n * The zx coefficients of the spherical polynomial\n */\n this.zx = BABYLON.Vector3.Zero();\n }\n /**\n * Adds an ambient color to the spherical polynomial\n * @param color the color to add\n */\n SphericalPolynomial.prototype.addAmbient = function (color) {\n var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);\n this.xx = this.xx.add(colorVector);\n this.yy = this.yy.add(colorVector);\n this.zz = this.zz.add(colorVector);\n };\n /**\n * Scales the spherical polynomial by the given amount\n * @param scale the amount to scale\n */\n SphericalPolynomial.prototype.scale = function (scale) {\n this.x = this.x.scale(scale);\n this.y = this.y.scale(scale);\n this.z = this.z.scale(scale);\n this.xx = this.xx.scale(scale);\n this.yy = this.yy.scale(scale);\n this.zz = this.zz.scale(scale);\n this.yz = this.yz.scale(scale);\n this.zx = this.zx.scale(scale);\n this.xy = this.xy.scale(scale);\n };\n /**\n * Gets the spherical polynomial from harmonics\n * @param harmonics the spherical harmonics\n * @returns the spherical polynomial\n */\n SphericalPolynomial.FromHarmonics = function (harmonics) {\n var result = new SphericalPolynomial();\n result.x = harmonics.l11.scale(1.02333);\n result.y = harmonics.l1_1.scale(1.02333);\n result.z = harmonics.l10.scale(1.02333);\n result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));\n result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));\n result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));\n result.yz = harmonics.l2_1.scale(0.858086);\n result.zx = harmonics.l21.scale(0.858086);\n result.xy = harmonics.l2_2.scale(0.858086);\n result.scale(1.0 / Math.PI);\n return result;\n };\n /**\n * Constructs a spherical polynomial from an array.\n * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)\n * @returns the spherical polynomial\n */\n SphericalPolynomial.FromArray = function (data) {\n var sp = new SphericalPolynomial();\n BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);\n BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);\n BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);\n BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);\n BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);\n BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);\n BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);\n BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);\n BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);\n return sp;\n };\n return SphericalPolynomial;\n }());\n BABYLON.SphericalPolynomial = SphericalPolynomial;\n /**\n * Class representing spherical harmonics coefficients to the 3rd degree\n */\n var SphericalHarmonics = /** @class */ (function () {\n function SphericalHarmonics() {\n /**\n * The l0,0 coefficients of the spherical harmonics\n */\n this.l00 = BABYLON.Vector3.Zero();\n /**\n * The l1,-1 coefficients of the spherical harmonics\n */\n this.l1_1 = BABYLON.Vector3.Zero();\n /**\n * The l1,0 coefficients of the spherical harmonics\n */\n this.l10 = BABYLON.Vector3.Zero();\n /**\n * The l1,1 coefficients of the spherical harmonics\n */\n this.l11 = BABYLON.Vector3.Zero();\n /**\n * The l2,-2 coefficients of the spherical harmonics\n */\n this.l2_2 = BABYLON.Vector3.Zero();\n /**\n * The l2,-1 coefficients of the spherical harmonics\n */\n this.l2_1 = BABYLON.Vector3.Zero();\n /**\n * The l2,0 coefficients of the spherical harmonics\n */\n this.l20 = BABYLON.Vector3.Zero();\n /**\n * The l2,1 coefficients of the spherical harmonics\n */\n this.l21 = BABYLON.Vector3.Zero();\n /**\n * The l2,2 coefficients of the spherical harmonics\n */\n this.lL22 = BABYLON.Vector3.Zero();\n }\n /**\n * Adds a light to the spherical harmonics\n * @param direction the direction of the light\n * @param color the color of the light\n * @param deltaSolidAngle the delta solid angle of the light\n */\n SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {\n var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);\n var c = colorVector.scale(deltaSolidAngle);\n this.l00 = this.l00.add(c.scale(0.282095));\n this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));\n this.l10 = this.l10.add(c.scale(0.488603 * direction.z));\n this.l11 = this.l11.add(c.scale(0.488603 * direction.x));\n this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));\n this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));\n this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));\n this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));\n this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));\n };\n /**\n * Scales the spherical harmonics by the given amount\n * @param scale the amount to scale\n */\n SphericalHarmonics.prototype.scale = function (scale) {\n this.l00 = this.l00.scale(scale);\n this.l1_1 = this.l1_1.scale(scale);\n this.l10 = this.l10.scale(scale);\n this.l11 = this.l11.scale(scale);\n this.l2_2 = this.l2_2.scale(scale);\n this.l2_1 = this.l2_1.scale(scale);\n this.l20 = this.l20.scale(scale);\n this.l21 = this.l21.scale(scale);\n this.lL22 = this.lL22.scale(scale);\n };\n /**\n * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.\n *\n * ```\n * E_lm = A_l * L_lm\n * ```\n *\n * In spherical harmonics this convolution amounts to scaling factors for each frequency band.\n * This corresponds to equation 5 in \"An Efficient Representation for Irradiance Environment Maps\", where\n * the scaling factors are given in equation 9.\n */\n SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {\n // Constant (Band 0)\n this.l00 = this.l00.scale(3.141593);\n // Linear (Band 1)\n this.l1_1 = this.l1_1.scale(2.094395);\n this.l10 = this.l10.scale(2.094395);\n this.l11 = this.l11.scale(2.094395);\n // Quadratic (Band 2)\n this.l2_2 = this.l2_2.scale(0.785398);\n this.l2_1 = this.l2_1.scale(0.785398);\n this.l20 = this.l20.scale(0.785398);\n this.l21 = this.l21.scale(0.785398);\n this.lL22 = this.lL22.scale(0.785398);\n };\n /**\n * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.\n *\n * ```\n * L = (1/pi) * E * rho\n * ```\n *\n * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.\n */\n SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {\n this.scale(1.0 / Math.PI);\n // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied\n // (The pixel shader must apply albedo after texture fetches, etc).\n };\n /**\n * Gets the spherical harmonics from polynomial\n * @param polynomial the spherical polynomial\n * @returns the spherical harmonics\n */\n SphericalHarmonics.FromPolynomial = function (polynomial) {\n var result = new SphericalHarmonics();\n result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));\n result.l1_1 = polynomial.y.scale(0.977204);\n result.l10 = polynomial.z.scale(0.977204);\n result.l11 = polynomial.x.scale(0.977204);\n result.l2_2 = polynomial.xy.scale(1.16538);\n result.l2_1 = polynomial.yz.scale(1.16538);\n result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));\n result.l21 = polynomial.zx.scale(1.16538);\n result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));\n result.scale(Math.PI);\n return result;\n };\n /**\n * Constructs a spherical harmonics from an array.\n * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)\n * @returns the spherical harmonics\n */\n SphericalHarmonics.FromArray = function (data) {\n var sh = new SphericalHarmonics();\n BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);\n BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);\n BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);\n BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);\n BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);\n BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);\n BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);\n BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);\n BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);\n return sh;\n };\n return SphericalHarmonics;\n }());\n BABYLON.SphericalHarmonics = SphericalHarmonics;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sphericalPolynomial.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var FileFaceOrientation = /** @class */ (function () {\n function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {\n this.name = name;\n this.worldAxisForNormal = worldAxisForNormal;\n this.worldAxisForFileX = worldAxisForFileX;\n this.worldAxisForFileY = worldAxisForFileY;\n }\n return FileFaceOrientation;\n }());\n ;\n /**\n * Helper class dealing with the extraction of spherical polynomial dataArray\n * from a cube map.\n */\n var CubeMapToSphericalPolynomialTools = /** @class */ (function () {\n function CubeMapToSphericalPolynomialTools() {\n }\n /**\n * Converts a texture to the according Spherical Polynomial data.\n * This extracts the first 3 orders only as they are the only one used in the lighting.\n *\n * @param texture The texture to extract the information from.\n * @return The Spherical Polynomial data.\n */\n CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {\n if (!texture.isCube) {\n // Only supports cube Textures currently.\n return null;\n }\n var size = texture.getSize().width;\n var right = texture.readPixels(0);\n var left = texture.readPixels(1);\n var up;\n var down;\n if (texture.isRenderTarget) {\n up = texture.readPixels(3);\n down = texture.readPixels(2);\n }\n else {\n up = texture.readPixels(2);\n down = texture.readPixels(3);\n }\n var front = texture.readPixels(4);\n var back = texture.readPixels(5);\n var gammaSpace = texture.gammaSpace;\n // Always read as RGBA.\n var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;\n var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {\n type = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n var cubeInfo = {\n size: size,\n right: right,\n left: left,\n up: up,\n down: down,\n front: front,\n back: back,\n format: format,\n type: type,\n gammaSpace: gammaSpace,\n };\n return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);\n };\n /**\n * Converts a cubemap to the according Spherical Polynomial data.\n * This extracts the first 3 orders only as they are the only one used in the lighting.\n *\n * @param cubeInfo The Cube map to extract the information from.\n * @return The Spherical Polynomial data.\n */\n CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {\n var sphericalHarmonics = new BABYLON.SphericalHarmonics();\n var totalSolidAngle = 0.0;\n // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.\n var du = 2.0 / cubeInfo.size;\n var dv = du;\n // The (u,v) of the first texel is half a texel from the corner (-1,-1).\n var minUV = du * 0.5 - 1.0;\n for (var faceIndex = 0; faceIndex < 6; faceIndex++) {\n var fileFace = this.FileFaces[faceIndex];\n var dataArray = cubeInfo[fileFace.name];\n var v = minUV;\n // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).\n // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.\n // Because SP is still linear, so summation is fine in that basis.\n var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;\n for (var y = 0; y < cubeInfo.size; y++) {\n var u = minUV;\n for (var x = 0; x < cubeInfo.size; x++) {\n // World direction (not normalised)\n var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);\n worldDirection.normalize();\n var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);\n var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];\n var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];\n var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];\n // Handle Integer types.\n if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {\n r /= 255;\n g /= 255;\n b /= 255;\n }\n // Handle Gamma space textures.\n if (cubeInfo.gammaSpace) {\n r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);\n g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);\n b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);\n }\n var color = new BABYLON.Color3(r, g, b);\n sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);\n totalSolidAngle += deltaSolidAngle;\n u += du;\n }\n v += dv;\n }\n }\n // Solid angle for entire sphere is 4*pi\n var sphereSolidAngle = 4.0 * Math.PI;\n // Adjust the solid angle to allow for how many faces we processed.\n var facesProcessed = 6.0;\n var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;\n // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle. \n // This is needed because the numerical integration over the cube uses a \n // small angle approximation of solid angle for each texel (see deltaSolidAngle),\n // and also to compensate for accumulative error due to float precision in the summation.\n var correctionFactor = expectedSolidAngle / totalSolidAngle;\n sphericalHarmonics.scale(correctionFactor);\n sphericalHarmonics.convertIncidentRadianceToIrradiance();\n sphericalHarmonics.convertIrradianceToLambertianRadiance();\n return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);\n };\n CubeMapToSphericalPolynomialTools.FileFaces = [\n new FileFaceOrientation(\"right\", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),\n new FileFaceOrientation(\"left\", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),\n new FileFaceOrientation(\"up\", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),\n new FileFaceOrientation(\"down\", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),\n new FileFaceOrientation(\"front\", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),\n new FileFaceOrientation(\"back\", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom\n ];\n return CubeMapToSphericalPolynomialTools;\n }());\n BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Manages the defines for the PBR Material.\n * @hiddenChildren\n */\n var PBRMaterialDefines = /** @class */ (function (_super) {\n __extends(PBRMaterialDefines, _super);\n /**\n * Initializes the PBR Material defines.\n */\n function PBRMaterialDefines() {\n var _this = _super.call(this) || this;\n _this.PBR = true;\n _this.MAINUV1 = false;\n _this.MAINUV2 = false;\n _this.UV1 = false;\n _this.UV2 = false;\n _this.ALBEDO = false;\n _this.ALBEDODIRECTUV = 0;\n _this.VERTEXCOLOR = false;\n _this.AMBIENT = false;\n _this.AMBIENTDIRECTUV = 0;\n _this.AMBIENTINGRAYSCALE = false;\n _this.OPACITY = false;\n _this.VERTEXALPHA = false;\n _this.OPACITYDIRECTUV = 0;\n _this.OPACITYRGB = false;\n _this.ALPHATEST = false;\n _this.DEPTHPREPASS = false;\n _this.ALPHABLEND = false;\n _this.ALPHAFROMALBEDO = false;\n _this.ALPHATESTVALUE = \"0.5\";\n _this.SPECULAROVERALPHA = false;\n _this.RADIANCEOVERALPHA = false;\n _this.ALPHAFRESNEL = false;\n _this.LINEARALPHAFRESNEL = false;\n _this.PREMULTIPLYALPHA = false;\n _this.EMISSIVE = false;\n _this.EMISSIVEDIRECTUV = 0;\n _this.REFLECTIVITY = false;\n _this.REFLECTIVITYDIRECTUV = 0;\n _this.SPECULARTERM = false;\n _this.MICROSURFACEFROMREFLECTIVITYMAP = false;\n _this.MICROSURFACEAUTOMATIC = false;\n _this.LODBASEDMICROSFURACE = false;\n _this.MICROSURFACEMAP = false;\n _this.MICROSURFACEMAPDIRECTUV = 0;\n _this.METALLICWORKFLOW = false;\n _this.ROUGHNESSSTOREINMETALMAPALPHA = false;\n _this.ROUGHNESSSTOREINMETALMAPGREEN = false;\n _this.METALLNESSSTOREINMETALMAPBLUE = false;\n _this.AOSTOREINMETALMAPRED = false;\n _this.ENVIRONMENTBRDF = false;\n _this.NORMAL = false;\n _this.TANGENT = false;\n _this.BUMP = false;\n _this.BUMPDIRECTUV = 0;\n _this.OBJECTSPACE_NORMALMAP = false;\n _this.PARALLAX = false;\n _this.PARALLAXOCCLUSION = false;\n _this.NORMALXYSCALE = true;\n _this.LIGHTMAP = false;\n _this.LIGHTMAPDIRECTUV = 0;\n _this.USELIGHTMAPASSHADOWMAP = false;\n _this.GAMMALIGHTMAP = false;\n _this.REFLECTION = false;\n _this.REFLECTIONMAP_3D = false;\n _this.REFLECTIONMAP_SPHERICAL = false;\n _this.REFLECTIONMAP_PLANAR = false;\n _this.REFLECTIONMAP_CUBIC = false;\n _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\n _this.REFLECTIONMAP_PROJECTION = false;\n _this.REFLECTIONMAP_SKYBOX = false;\n _this.REFLECTIONMAP_EXPLICIT = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n _this.INVERTCUBICMAP = false;\n _this.USESPHERICALFROMREFLECTIONMAP = false;\n _this.USESPHERICALINVERTEX = false;\n _this.REFLECTIONMAP_OPPOSITEZ = false;\n _this.LODINREFLECTIONALPHA = false;\n _this.GAMMAREFLECTION = false;\n _this.RGBDREFLECTION = false;\n _this.RADIANCEOCCLUSION = false;\n _this.HORIZONOCCLUSION = false;\n _this.REFRACTION = false;\n _this.REFRACTIONMAP_3D = false;\n _this.REFRACTIONMAP_OPPOSITEZ = false;\n _this.LODINREFRACTIONALPHA = false;\n _this.GAMMAREFRACTION = false;\n _this.RGBDREFRACTION = false;\n _this.LINKREFRACTIONTOTRANSPARENCY = false;\n _this.INSTANCES = false;\n _this.NUM_BONE_INFLUENCERS = 0;\n _this.BonesPerMesh = 0;\n _this.NONUNIFORMSCALING = false;\n _this.MORPHTARGETS = false;\n _this.MORPHTARGETS_NORMAL = false;\n _this.MORPHTARGETS_TANGENT = false;\n _this.NUM_MORPH_INFLUENCERS = 0;\n _this.IMAGEPROCESSING = false;\n _this.VIGNETTE = false;\n _this.VIGNETTEBLENDMODEMULTIPLY = false;\n _this.VIGNETTEBLENDMODEOPAQUE = false;\n _this.TONEMAPPING = false;\n _this.CONTRAST = false;\n _this.COLORCURVES = false;\n _this.COLORGRADING = false;\n _this.COLORGRADING3D = false;\n _this.SAMPLER3DGREENDEPTH = false;\n _this.SAMPLER3DBGRMAP = false;\n _this.IMAGEPROCESSINGPOSTPROCESS = false;\n _this.EXPOSURE = false;\n _this.USEPHYSICALLIGHTFALLOFF = false;\n _this.TWOSIDEDLIGHTING = false;\n _this.SHADOWFLOAT = false;\n _this.CLIPPLANE = false;\n _this.POINTSIZE = false;\n _this.FOG = false;\n _this.LOGARITHMICDEPTH = false;\n _this.FORCENORMALFORWARD = false;\n _this.SPECULARAA = false;\n _this.UNLIT = false;\n _this.rebuild();\n return _this;\n }\n /**\n * Resets the PBR Material defines.\n */\n PBRMaterialDefines.prototype.reset = function () {\n _super.prototype.reset.call(this);\n this.ALPHATESTVALUE = \"0.5\";\n this.PBR = true;\n };\n return PBRMaterialDefines;\n }(BABYLON.MaterialDefines));\n /**\n * The Physically based material base class of BJS.\n *\n * This offers the main features of a standard PBR material.\n * For more information, please refer to the documentation :\n * http://doc.babylonjs.com/extensions/Physically_Based_Rendering\n */\n var PBRBaseMaterial = /** @class */ (function (_super) {\n __extends(PBRBaseMaterial, _super);\n /**\n * Instantiates a new PBRMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n function PBRBaseMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n /**\n * Intensity of the direct lights e.g. the four lights available in your scene.\n * This impacts both the direct diffuse and specular highlights.\n */\n _this._directIntensity = 1.0;\n /**\n * Intensity of the emissive part of the material.\n * This helps controlling the emissive effect without modifying the emissive color.\n */\n _this._emissiveIntensity = 1.0;\n /**\n * Intensity of the environment e.g. how much the environment will light the object\n * either through harmonics for rough material or through the refelction for shiny ones.\n */\n _this._environmentIntensity = 1.0;\n /**\n * This is a special control allowing the reduction of the specular highlights coming from the\n * four lights of the scene. Those highlights may not be needed in full environment lighting.\n */\n _this._specularIntensity = 1.0;\n /**\n * This stores the direct, emissive, environment, and specular light intensities into a Vector4.\n */\n _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);\n /**\n * Debug Control allowing disabling the bump map on this material.\n */\n _this._disableBumpMap = false;\n /**\n * AKA Occlusion Texture Intensity in other nomenclature.\n */\n _this._ambientTextureStrength = 1.0;\n /**\n * The color of a material in ambient lighting.\n */\n _this._ambientColor = new BABYLON.Color3(0, 0, 0);\n /**\n * AKA Diffuse Color in other nomenclature.\n */\n _this._albedoColor = new BABYLON.Color3(1, 1, 1);\n /**\n * AKA Specular Color in other nomenclature.\n */\n _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);\n /**\n * The color applied when light is reflected from a material.\n */\n _this._reflectionColor = new BABYLON.Color3(1, 1, 1);\n /**\n * The color applied when light is emitted from a material.\n */\n _this._emissiveColor = new BABYLON.Color3(0, 0, 0);\n /**\n * AKA Glossiness in other nomenclature.\n */\n _this._microSurface = 0.9;\n /**\n * source material index of refraction (IOR)' / 'destination material IOR.\n */\n _this._indexOfRefraction = 0.66;\n /**\n * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.\n */\n _this._invertRefractionY = false;\n /**\n * This parameters will make the material used its opacity to control how much it is refracting aginst not.\n * Materials half opaque for instance using refraction could benefit from this control.\n */\n _this._linkRefractionWithTransparency = false;\n /**\n * Specifies that the material will use the light map as a show map.\n */\n _this._useLightmapAsShadowmap = false;\n /**\n * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal\n * makes the reflect vector face the model (under horizon).\n */\n _this._useHorizonOcclusion = true;\n /**\n * This parameters will enable/disable radiance occlusion by preventing the radiance to lit\n * too much the area relying on ambient texture to define their ambient occlusion.\n */\n _this._useRadianceOcclusion = true;\n /**\n * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.\n */\n _this._useAlphaFromAlbedoTexture = false;\n /**\n * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).\n * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.\n */\n _this._useSpecularOverAlpha = true;\n /**\n * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.\n */\n _this._useMicroSurfaceFromReflectivityMapAlpha = false;\n /**\n * Specifies if the metallic texture contains the roughness information in its alpha channel.\n */\n _this._useRoughnessFromMetallicTextureAlpha = true;\n /**\n * Specifies if the metallic texture contains the roughness information in its green channel.\n */\n _this._useRoughnessFromMetallicTextureGreen = false;\n /**\n * Specifies if the metallic texture contains the metallness information in its blue channel.\n */\n _this._useMetallnessFromMetallicTextureBlue = false;\n /**\n * Specifies if the metallic texture contains the ambient occlusion information in its red channel.\n */\n _this._useAmbientOcclusionFromMetallicTextureRed = false;\n /**\n * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.\n */\n _this._useAmbientInGrayScale = false;\n /**\n * In case the reflectivity map does not contain the microsurface information in its alpha channel,\n * The material will try to infer what glossiness each pixel should be.\n */\n _this._useAutoMicroSurfaceFromReflectivityMap = false;\n /**\n * BJS is using an harcoded light falloff based on a manually sets up range.\n * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.\n * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.\n */\n _this._usePhysicalLightFalloff = true;\n /**\n * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).\n * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.\n */\n _this._useRadianceOverAlpha = true;\n /**\n * Allows using an object space normal map (instead of tangent space).\n */\n _this._useObjectSpaceNormalMap = false;\n /**\n * Allows using the bump map in parallax mode.\n */\n _this._useParallax = false;\n /**\n * Allows using the bump map in parallax occlusion mode.\n */\n _this._useParallaxOcclusion = false;\n /**\n * Controls the scale bias of the parallax mode.\n */\n _this._parallaxScaleBias = 0.05;\n /**\n * If sets to true, disables all the lights affecting the material.\n */\n _this._disableLighting = false;\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n _this._maxSimultaneousLights = 4;\n /**\n * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).\n */\n _this._invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).\n */\n _this._invertNormalMapY = false;\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n */\n _this._twoSidedLighting = false;\n /**\n * Defines the alpha limits in alpha test mode.\n */\n _this._alphaCutOff = 0.4;\n /**\n * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.\n */\n _this._forceAlphaTest = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)\n */\n _this._useAlphaFresnel = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)\n */\n _this._useLinearAlphaFresnel = false;\n /**\n * The transparency mode of the material.\n */\n _this._transparencyMode = null;\n /**\n * Specifies the environment BRDF texture used to comput the scale and offset roughness values\n * from cos thetav and roughness:\n * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf\n */\n _this._environmentBRDFTexture = null;\n /**\n * Force the shader to compute irradiance in the fragment shader in order to take bump in account.\n */\n _this._forceIrradianceInFragment = false;\n /**\n * Force normal to face away from face.\n */\n _this._forceNormalForward = false;\n /**\n * Enables specular anti aliasing in the PBR shader.\n * It will both interacts on the Geometry for analytical and IBL lighting.\n * It also prefilter the roughness map based on the bump values.\n */\n _this._enableSpecularAntiAliasing = false;\n /**\n * Stores the available render targets.\n */\n _this._renderTargets = new BABYLON.SmartArray(16);\n /**\n * Sets the global ambient color for the material used in lighting calculations.\n */\n _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);\n /**\n * If set to true, no lighting calculations will be applied.\n */\n _this._unlit = false;\n // Setup the default processing configuration to the scene.\n _this._attachImageProcessingConfiguration(null);\n _this.getRenderTargetTextures = function () {\n _this._renderTargets.reset();\n if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {\n _this._renderTargets.push(_this._reflectionTexture);\n }\n if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {\n _this._renderTargets.push(_this._refractionTexture);\n }\n return _this._renderTargets;\n };\n _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);\n return _this;\n }\n /**\n * Attaches a new image processing configuration to the PBR Material.\n * @param configuration\n */\n PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {\n var _this = this;\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {\n _this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n };\n /**\n * Gets the name of the material class.\n */\n PBRBaseMaterial.prototype.getClassName = function () {\n return \"PBRBaseMaterial\";\n };\n Object.defineProperty(PBRBaseMaterial.prototype, \"useLogarithmicDepth\", {\n /**\n * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.\n */\n get: function () {\n return this._useLogarithmicDepth;\n },\n /**\n * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.\n */\n set: function (value) {\n this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRBaseMaterial.prototype, \"transparencyMode\", {\n /**\n * Gets the current transparency mode.\n */\n get: function () {\n return this._transparencyMode;\n },\n /**\n * Sets the transparency mode of the material.\n *\n * | Value | Type | Description |\n * | ----- | ----------------------------------- | ----------- |\n * | 0 | OPAQUE | |\n * | 1 | ALPHATEST | |\n * | 2 | ALPHABLEND | |\n * | 3 | ALPHATESTANDBLEND | |\n *\n */\n set: function (value) {\n if (this._transparencyMode === value) {\n return;\n }\n this._transparencyMode = value;\n this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);\n this._markAllSubMeshesAsTexturesAndMiscDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRBaseMaterial.prototype, \"_disableAlphaBlending\", {\n /**\n * Returns true if alpha blending should be disabled.\n */\n get: function () {\n return (this._linkRefractionWithTransparency ||\n this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||\n this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Specifies whether or not this material should be rendered in alpha blend mode.\n */\n PBRBaseMaterial.prototype.needAlphaBlending = function () {\n if (this._disableAlphaBlending) {\n return false;\n }\n return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();\n };\n /**\n * Specifies if the mesh will require alpha blending.\n * @param mesh - BJS mesh.\n */\n PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {\n if (this._disableAlphaBlending) {\n return false;\n }\n return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);\n };\n /**\n * Specifies whether or not this material should be rendered in alpha test mode.\n */\n PBRBaseMaterial.prototype.needAlphaTesting = function () {\n if (this._forceAlphaTest) {\n return true;\n }\n if (this._linkRefractionWithTransparency) {\n return false;\n }\n return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);\n };\n /**\n * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.\n */\n PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {\n return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;\n };\n /**\n * Gets the texture used for the alpha test.\n */\n PBRBaseMaterial.prototype.getAlphaTestTexture = function () {\n return this._albedoTexture;\n };\n /**\n * Specifies that the submesh is ready to be used.\n * @param mesh - BJS mesh.\n * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.\n * @param useInstances - Specifies that instances should be used.\n * @returns - boolean indicating that the submesh is ready or not.\n */\n PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {\n if (subMesh.effect && this.isFrozen) {\n if (this._wasPreviouslyReady) {\n return true;\n }\n }\n if (!subMesh._materialDefines) {\n subMesh._materialDefines = new PBRMaterialDefines();\n }\n var defines = subMesh._materialDefines;\n if (!this.checkReadyOnEveryCall && subMesh.effect) {\n if (defines._renderId === this.getScene().getRenderId()) {\n return true;\n }\n }\n var scene = this.getScene();\n var engine = scene.getEngine();\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n if (!this._albedoTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {\n if (!this._ambientTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {\n if (!this._opacityTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n var reflectionTexture = this._getReflectionTexture();\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n if (!reflectionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {\n if (!this._lightmapTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {\n if (!this._emissiveTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (BABYLON.StandardMaterial.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n if (!this._metallicTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n else if (this._reflectivityTexture) {\n if (!this._reflectivityTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._microSurfaceTexture) {\n if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {\n // Bump texture cannot be not blocking.\n if (!this._bumpTexture.isReady()) {\n return false;\n }\n }\n var refractionTexture = this._getRefractionTexture();\n if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {\n if (!refractionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n // This is blocking.\n if (!this._environmentBRDFTexture.isReady()) {\n return false;\n }\n }\n }\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n if (!this._imageProcessingConfiguration.isReady()) {\n return false;\n }\n }\n if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n mesh.createNormals(true);\n BABYLON.Tools.Warn(\"PBRMaterial: Normals have been created for the mesh: \" + mesh.name);\n }\n var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);\n if (effect) {\n scene.resetCachedMaterial();\n subMesh.setEffect(effect, defines);\n this.buildUniformLayout();\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n this._wasPreviouslyReady = true;\n return true;\n };\n /**\n * Specifies if the material uses metallic roughness workflow.\n * @returns boolean specifiying if the material uses metallic roughness workflow.\n */\n PBRBaseMaterial.prototype.isMetallicWorkflow = function () {\n if (this._metallic != null || this._roughness != null || this._metallicTexture) {\n return true;\n }\n return false;\n };\n PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {\n if (onCompiled === void 0) { onCompiled = null; }\n if (onError === void 0) { onError = null; }\n if (useInstances === void 0) { useInstances = null; }\n if (useClipPlane === void 0) { useClipPlane = null; }\n this._prepareDefines(mesh, defines, useInstances, useClipPlane);\n if (!defines.isDirty) {\n return null;\n }\n defines.markAsProcessed();\n var scene = this.getScene();\n var engine = scene.getEngine();\n // Fallbacks\n var fallbacks = new BABYLON.EffectFallbacks();\n var fallbackRank = 0;\n if (defines.USESPHERICALINVERTEX) {\n fallbacks.addFallback(fallbackRank++, \"USESPHERICALINVERTEX\");\n }\n if (defines.FOG) {\n fallbacks.addFallback(fallbackRank, \"FOG\");\n }\n if (defines.SPECULARAA) {\n fallbacks.addFallback(fallbackRank, \"SPECULARAA\");\n }\n if (defines.POINTSIZE) {\n fallbacks.addFallback(fallbackRank, \"POINTSIZE\");\n }\n if (defines.LOGARITHMICDEPTH) {\n fallbacks.addFallback(fallbackRank, \"LOGARITHMICDEPTH\");\n }\n if (defines.PARALLAX) {\n fallbacks.addFallback(fallbackRank, \"PARALLAX\");\n }\n if (defines.PARALLAXOCCLUSION) {\n fallbacks.addFallback(fallbackRank++, \"PARALLAXOCCLUSION\");\n }\n if (defines.ENVIRONMENTBRDF) {\n fallbacks.addFallback(fallbackRank++, \"ENVIRONMENTBRDF\");\n }\n if (defines.TANGENT) {\n fallbacks.addFallback(fallbackRank++, \"TANGENT\");\n }\n if (defines.BUMP) {\n fallbacks.addFallback(fallbackRank++, \"BUMP\");\n }\n fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);\n if (defines.SPECULARTERM) {\n fallbacks.addFallback(fallbackRank++, \"SPECULARTERM\");\n }\n if (defines.USESPHERICALFROMREFLECTIONMAP) {\n fallbacks.addFallback(fallbackRank++, \"USESPHERICALFROMREFLECTIONMAP\");\n }\n if (defines.LIGHTMAP) {\n fallbacks.addFallback(fallbackRank++, \"LIGHTMAP\");\n }\n if (defines.NORMAL) {\n fallbacks.addFallback(fallbackRank++, \"NORMAL\");\n }\n if (defines.AMBIENT) {\n fallbacks.addFallback(fallbackRank++, \"AMBIENT\");\n }\n if (defines.EMISSIVE) {\n fallbacks.addFallback(fallbackRank++, \"EMISSIVE\");\n }\n if (defines.VERTEXCOLOR) {\n fallbacks.addFallback(fallbackRank++, \"VERTEXCOLOR\");\n }\n if (defines.NUM_BONE_INFLUENCERS > 0) {\n fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);\n }\n if (defines.MORPHTARGETS) {\n fallbacks.addFallback(fallbackRank++, \"MORPHTARGETS\");\n }\n //Attributes\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n if (defines.NORMAL) {\n attribs.push(BABYLON.VertexBuffer.NormalKind);\n }\n if (defines.TANGENT) {\n attribs.push(BABYLON.VertexBuffer.TangentKind);\n }\n if (defines.UV1) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n }\n if (defines.UV2) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n }\n if (defines.VERTEXCOLOR) {\n attribs.push(BABYLON.VertexBuffer.ColorKind);\n }\n BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);\n BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);\n BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);\n var uniforms = [\"world\", \"view\", \"viewProjection\", \"vEyePosition\", \"vLightsType\", \"vAmbientColor\", \"vAlbedoColor\", \"vReflectivityColor\", \"vEmissiveColor\", \"vReflectionColor\",\n \"vFogInfos\", \"vFogColor\", \"pointSize\",\n \"vAlbedoInfos\", \"vAmbientInfos\", \"vOpacityInfos\", \"vReflectionInfos\", \"vReflectionPosition\", \"vReflectionSize\", \"vEmissiveInfos\", \"vReflectivityInfos\",\n \"vMicroSurfaceSamplerInfos\", \"vBumpInfos\", \"vLightmapInfos\", \"vRefractionInfos\",\n \"mBones\",\n \"vClipPlane\", \"albedoMatrix\", \"ambientMatrix\", \"opacityMatrix\", \"reflectionMatrix\", \"emissiveMatrix\", \"reflectivityMatrix\", \"normalMatrix\", \"microSurfaceSamplerMatrix\", \"bumpMatrix\", \"lightmapMatrix\", \"refractionMatrix\",\n \"vLightingIntensity\",\n \"logarithmicDepthConstant\",\n \"vSphericalX\", \"vSphericalY\", \"vSphericalZ\",\n \"vSphericalXX\", \"vSphericalYY\", \"vSphericalZZ\",\n \"vSphericalXY\", \"vSphericalYZ\", \"vSphericalZX\",\n \"vReflectionMicrosurfaceInfos\", \"vRefractionMicrosurfaceInfos\",\n \"vTangentSpaceParams\"\n ];\n var samplers = [\"albedoSampler\", \"reflectivitySampler\", \"ambientSampler\", \"emissiveSampler\",\n \"bumpSampler\", \"lightmapSampler\", \"opacitySampler\",\n \"refractionSampler\", \"refractionSamplerLow\", \"refractionSamplerHigh\",\n \"reflectionSampler\", \"reflectionSamplerLow\", \"reflectionSamplerHigh\",\n \"microSurfaceSampler\", \"environmentBrdfSampler\"];\n var uniformBuffers = [\"Material\", \"Scene\"];\n if (BABYLON.ImageProcessingConfiguration) {\n BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);\n BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);\n }\n BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: defines,\n maxSimultaneousLights: this._maxSimultaneousLights\n });\n var join = defines.toString();\n return engine.createEffect(\"pbr\", {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: onCompiled,\n onError: onError,\n indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }\n }, engine);\n };\n PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {\n if (useInstances === void 0) { useInstances = null; }\n if (useClipPlane === void 0) { useClipPlane = null; }\n var scene = this.getScene();\n var engine = scene.getEngine();\n // Lights\n BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);\n defines._needNormals = true;\n // Textures\n defines.METALLICWORKFLOW = this.isMetallicWorkflow();\n if (defines._areTexturesDirty) {\n defines._needUVs = false;\n if (scene.texturesEnabled) {\n if (scene.getEngine().getCaps().textureLOD) {\n defines.LODBASEDMICROSFURACE = true;\n }\n if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, \"ALBEDO\");\n }\n else {\n defines.ALBEDO = false;\n }\n if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, \"AMBIENT\");\n defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;\n }\n else {\n defines.AMBIENT = false;\n }\n if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, \"OPACITY\");\n defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;\n }\n else {\n defines.OPACITY = false;\n }\n var reflectionTexture = this._getReflectionTexture();\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n defines.REFLECTION = true;\n defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;\n defines.RGBDREFLECTION = reflectionTexture.isRGBD;\n defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;\n defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;\n if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {\n defines.INVERTCUBICMAP = true;\n }\n defines.REFLECTIONMAP_3D = reflectionTexture.isCube;\n switch (reflectionTexture.coordinatesMode) {\n case BABYLON.Texture.EXPLICIT_MODE:\n defines.REFLECTIONMAP_EXPLICIT = true;\n break;\n case BABYLON.Texture.PLANAR_MODE:\n defines.REFLECTIONMAP_PLANAR = true;\n break;\n case BABYLON.Texture.PROJECTION_MODE:\n defines.REFLECTIONMAP_PROJECTION = true;\n break;\n case BABYLON.Texture.SKYBOX_MODE:\n defines.REFLECTIONMAP_SKYBOX = true;\n break;\n case BABYLON.Texture.SPHERICAL_MODE:\n defines.REFLECTIONMAP_SPHERICAL = true;\n break;\n case BABYLON.Texture.EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR = true;\n break;\n case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;\n break;\n case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;\n break;\n case BABYLON.Texture.CUBIC_MODE:\n case BABYLON.Texture.INVCUBIC_MODE:\n default:\n defines.REFLECTIONMAP_CUBIC = true;\n defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;\n break;\n }\n if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {\n if (reflectionTexture.sphericalPolynomial) {\n defines.USESPHERICALFROMREFLECTIONMAP = true;\n if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {\n defines.USESPHERICALINVERTEX = false;\n }\n else {\n defines.USESPHERICALINVERTEX = true;\n }\n }\n }\n }\n else {\n defines.REFLECTION = false;\n defines.REFLECTIONMAP_3D = false;\n defines.REFLECTIONMAP_SPHERICAL = false;\n defines.REFLECTIONMAP_PLANAR = false;\n defines.REFLECTIONMAP_CUBIC = false;\n defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\n defines.REFLECTIONMAP_PROJECTION = false;\n defines.REFLECTIONMAP_SKYBOX = false;\n defines.REFLECTIONMAP_EXPLICIT = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n defines.INVERTCUBICMAP = false;\n defines.USESPHERICALFROMREFLECTIONMAP = false;\n defines.USESPHERICALINVERTEX = false;\n defines.REFLECTIONMAP_OPPOSITEZ = false;\n defines.LODINREFLECTIONALPHA = false;\n defines.GAMMAREFLECTION = false;\n defines.RGBDREFLECTION = false;\n }\n if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, \"LIGHTMAP\");\n defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;\n defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;\n }\n else {\n defines.LIGHTMAP = false;\n }\n if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, \"EMISSIVE\");\n }\n else {\n defines.EMISSIVE = false;\n }\n if (BABYLON.StandardMaterial.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, \"REFLECTIVITY\");\n defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;\n defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;\n defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;\n defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;\n }\n else if (this._reflectivityTexture) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, \"REFLECTIVITY\");\n defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;\n defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;\n }\n else {\n defines.REFLECTIVITY = false;\n }\n if (this._microSurfaceTexture) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, \"MICROSURFACEMAP\");\n }\n else {\n defines.MICROSURFACEMAP = false;\n }\n }\n else {\n defines.REFLECTIVITY = false;\n defines.MICROSURFACEMAP = false;\n }\n if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, \"BUMP\");\n if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n defines.PARALLAX = true;\n defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;\n }\n else {\n defines.PARALLAX = false;\n }\n defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;\n }\n else {\n defines.BUMP = false;\n }\n var refractionTexture = this._getRefractionTexture();\n if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {\n defines.REFRACTION = true;\n defines.REFRACTIONMAP_3D = refractionTexture.isCube;\n defines.GAMMAREFRACTION = refractionTexture.gammaSpace;\n defines.RGBDREFRACTION = refractionTexture.isRGBD;\n defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;\n defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;\n if (this._linkRefractionWithTransparency) {\n defines.LINKREFRACTIONTOTRANSPARENCY = true;\n }\n }\n else {\n defines.REFRACTION = false;\n }\n if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n defines.ENVIRONMENTBRDF = true;\n }\n else {\n defines.ENVIRONMENTBRDF = false;\n }\n if (this._shouldUseAlphaFromAlbedoTexture()) {\n defines.ALPHAFROMALBEDO = true;\n }\n else {\n defines.ALPHAFROMALBEDO = false;\n }\n }\n defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;\n defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;\n defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;\n if (!this.backFaceCulling && this._twoSidedLighting) {\n defines.TWOSIDEDLIGHTING = true;\n }\n else {\n defines.TWOSIDEDLIGHTING = false;\n }\n defines.ALPHATESTVALUE = \"\" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? \".\" : \"\");\n defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);\n defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);\n defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;\n defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;\n defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n this._imageProcessingConfiguration.prepareDefines(defines);\n }\n defines.FORCENORMALFORWARD = this._forceNormalForward;\n defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;\n defines.HORIZONOCCLUSION = this._useHorizonOcclusion;\n // Misc.\n if (defines._areMiscDirty) {\n BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);\n defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));\n }\n // Values that need to be evaluated on every frame\n BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);\n // Attribs\n BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);\n };\n /**\n * Force shader compilation\n */\n PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {\n var _this = this;\n var localOptions = __assign({ clipPlane: false }, options);\n var defines = new PBRMaterialDefines();\n var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);\n if (effect.isReady()) {\n if (onCompiled) {\n onCompiled(this);\n }\n }\n else {\n effect.onCompileObservable.add(function () {\n if (onCompiled) {\n onCompiled(_this);\n }\n });\n }\n };\n /**\n * Initializes the uniform buffer layout for the shader.\n */\n PBRBaseMaterial.prototype.buildUniformLayout = function () {\n // Order is important !\n this._uniformBuffer.addUniform(\"vAlbedoInfos\", 2);\n this._uniformBuffer.addUniform(\"vAmbientInfos\", 3);\n this._uniformBuffer.addUniform(\"vOpacityInfos\", 2);\n this._uniformBuffer.addUniform(\"vEmissiveInfos\", 2);\n this._uniformBuffer.addUniform(\"vLightmapInfos\", 2);\n this._uniformBuffer.addUniform(\"vReflectivityInfos\", 3);\n this._uniformBuffer.addUniform(\"vMicroSurfaceSamplerInfos\", 2);\n this._uniformBuffer.addUniform(\"vRefractionInfos\", 4);\n this._uniformBuffer.addUniform(\"vReflectionInfos\", 2);\n this._uniformBuffer.addUniform(\"vReflectionPosition\", 3);\n this._uniformBuffer.addUniform(\"vReflectionSize\", 3);\n this._uniformBuffer.addUniform(\"vBumpInfos\", 3);\n this._uniformBuffer.addUniform(\"albedoMatrix\", 16);\n this._uniformBuffer.addUniform(\"ambientMatrix\", 16);\n this._uniformBuffer.addUniform(\"opacityMatrix\", 16);\n this._uniformBuffer.addUniform(\"emissiveMatrix\", 16);\n this._uniformBuffer.addUniform(\"lightmapMatrix\", 16);\n this._uniformBuffer.addUniform(\"reflectivityMatrix\", 16);\n this._uniformBuffer.addUniform(\"microSurfaceSamplerMatrix\", 16);\n this._uniformBuffer.addUniform(\"bumpMatrix\", 16);\n this._uniformBuffer.addUniform(\"vTangentSpaceParams\", 2);\n this._uniformBuffer.addUniform(\"refractionMatrix\", 16);\n this._uniformBuffer.addUniform(\"reflectionMatrix\", 16);\n this._uniformBuffer.addUniform(\"vReflectionColor\", 3);\n this._uniformBuffer.addUniform(\"vAlbedoColor\", 4);\n this._uniformBuffer.addUniform(\"vLightingIntensity\", 4);\n this._uniformBuffer.addUniform(\"vRefractionMicrosurfaceInfos\", 3);\n this._uniformBuffer.addUniform(\"vReflectionMicrosurfaceInfos\", 3);\n this._uniformBuffer.addUniform(\"vReflectivityColor\", 4);\n this._uniformBuffer.addUniform(\"vEmissiveColor\", 3);\n this._uniformBuffer.addUniform(\"pointSize\", 1);\n this._uniformBuffer.create();\n };\n /**\n * Unbinds the textures.\n */\n PBRBaseMaterial.prototype.unbind = function () {\n if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", null);\n }\n if (this._refractionTexture && this._refractionTexture.isRenderTarget) {\n this._uniformBuffer.setTexture(\"refractionSampler\", null);\n }\n _super.prototype.unbind.call(this);\n };\n /**\n * Binds the submesh data.\n * @param world - The world matrix.\n * @param mesh - The BJS mesh.\n * @param subMesh - A submesh of the BJS mesh.\n */\n PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {\n var scene = this.getScene();\n var defines = subMesh._materialDefines;\n if (!defines) {\n return;\n }\n var effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices\n this.bindOnlyWorldMatrix(world);\n // Normal Matrix\n if (defines.OBJECTSPACE_NORMALMAP) {\n world.toNormalMatrix(this._normalMatrix);\n this.bindOnlyNormalMatrix(this._normalMatrix);\n }\n var mustRebind = this._mustRebind(scene, effect, mesh.visibility);\n // Bones\n BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);\n var reflectionTexture = null;\n if (mustRebind) {\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this.bindViewProjection(effect);\n reflectionTexture = this._getReflectionTexture();\n var refractionTexture = this._getRefractionTexture();\n if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {\n // Texture uniforms\n if (scene.texturesEnabled) {\n if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vAlbedoInfos\", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, \"albedo\");\n }\n if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {\n this._uniformBuffer.updateFloat3(\"vAmbientInfos\", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);\n BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, \"ambient\");\n }\n if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vOpacityInfos\", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, \"opacity\");\n }\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n this._uniformBuffer.updateMatrix(\"reflectionMatrix\", reflectionTexture.getReflectionTextureMatrix());\n this._uniformBuffer.updateFloat2(\"vReflectionInfos\", reflectionTexture.level, 0);\n if (reflectionTexture.boundingBoxSize) {\n var cubeTexture = reflectionTexture;\n this._uniformBuffer.updateVector3(\"vReflectionPosition\", cubeTexture.boundingBoxPosition);\n this._uniformBuffer.updateVector3(\"vReflectionSize\", cubeTexture.boundingBoxSize);\n }\n var polynomials = reflectionTexture.sphericalPolynomial;\n if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {\n this._activeEffect.setFloat3(\"vSphericalX\", polynomials.x.x, polynomials.x.y, polynomials.x.z);\n this._activeEffect.setFloat3(\"vSphericalY\", polynomials.y.x, polynomials.y.y, polynomials.y.z);\n this._activeEffect.setFloat3(\"vSphericalZ\", polynomials.z.x, polynomials.z.y, polynomials.z.z);\n this._activeEffect.setFloat3(\"vSphericalXX_ZZ\", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);\n this._activeEffect.setFloat3(\"vSphericalYY_ZZ\", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);\n this._activeEffect.setFloat3(\"vSphericalZZ\", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);\n this._activeEffect.setFloat3(\"vSphericalXY\", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);\n this._activeEffect.setFloat3(\"vSphericalYZ\", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);\n this._activeEffect.setFloat3(\"vSphericalZX\", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);\n }\n this._uniformBuffer.updateFloat3(\"vReflectionMicrosurfaceInfos\", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);\n }\n if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vEmissiveInfos\", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, \"emissive\");\n }\n if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vLightmapInfos\", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, \"lightmap\");\n }\n if (BABYLON.StandardMaterial.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n this._uniformBuffer.updateFloat3(\"vReflectivityInfos\", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);\n BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, \"reflectivity\");\n }\n else if (this._reflectivityTexture) {\n this._uniformBuffer.updateFloat3(\"vReflectivityInfos\", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);\n BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, \"reflectivity\");\n }\n if (this._microSurfaceTexture) {\n this._uniformBuffer.updateFloat2(\"vMicroSurfaceSamplerInfos\", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, \"microSurfaceSampler\");\n }\n }\n if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {\n this._uniformBuffer.updateFloat3(\"vBumpInfos\", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);\n BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, \"bump\");\n if (scene._mirroredCameraPosition) {\n this._uniformBuffer.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);\n }\n else {\n this._uniformBuffer.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);\n }\n }\n if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {\n this._uniformBuffer.updateMatrix(\"refractionMatrix\", refractionTexture.getReflectionTextureMatrix());\n var depth = 1.0;\n if (!refractionTexture.isCube) {\n if (refractionTexture.depth) {\n depth = refractionTexture.depth;\n }\n }\n this._uniformBuffer.updateFloat4(\"vRefractionInfos\", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);\n this._uniformBuffer.updateFloat3(\"vRefractionMicrosurfaceInfos\", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);\n }\n }\n // Point size\n if (this.pointsCloud) {\n this._uniformBuffer.updateFloat(\"pointSize\", this.pointSize);\n }\n // Colors\n if (defines.METALLICWORKFLOW) {\n BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;\n BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;\n this._uniformBuffer.updateColor4(\"vReflectivityColor\", BABYLON.PBRMaterial._scaledReflectivity, 0);\n }\n else {\n this._uniformBuffer.updateColor4(\"vReflectivityColor\", this._reflectivityColor, this._microSurface);\n }\n this._uniformBuffer.updateColor3(\"vEmissiveColor\", this._emissiveColor);\n this._uniformBuffer.updateColor3(\"vReflectionColor\", this._reflectionColor);\n this._uniformBuffer.updateColor4(\"vAlbedoColor\", this._albedoColor, this.alpha * mesh.visibility);\n // Misc\n this._lightingInfos.x = this._directIntensity;\n this._lightingInfos.y = this._emissiveIntensity;\n this._lightingInfos.z = this._environmentIntensity;\n this._lightingInfos.w = this._specularIntensity;\n this._uniformBuffer.updateVector4(\"vLightingIntensity\", this._lightingInfos);\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n this._uniformBuffer.setTexture(\"albedoSampler\", this._albedoTexture);\n }\n if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {\n this._uniformBuffer.setTexture(\"ambientSampler\", this._ambientTexture);\n }\n if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {\n this._uniformBuffer.setTexture(\"opacitySampler\", this._opacityTexture);\n }\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n if (defines.LODBASEDMICROSFURACE) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture);\n }\n else {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture._lodTextureMid || reflectionTexture);\n this._uniformBuffer.setTexture(\"reflectionSamplerLow\", reflectionTexture._lodTextureLow || reflectionTexture);\n this._uniformBuffer.setTexture(\"reflectionSamplerHigh\", reflectionTexture._lodTextureHigh || reflectionTexture);\n }\n }\n if (defines.ENVIRONMENTBRDF) {\n this._uniformBuffer.setTexture(\"environmentBrdfSampler\", this._environmentBRDFTexture);\n }\n if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {\n if (defines.LODBASEDMICROSFURACE) {\n this._uniformBuffer.setTexture(\"refractionSampler\", refractionTexture);\n }\n else {\n this._uniformBuffer.setTexture(\"refractionSampler\", refractionTexture._lodTextureMid || refractionTexture);\n this._uniformBuffer.setTexture(\"refractionSamplerLow\", refractionTexture._lodTextureLow || refractionTexture);\n this._uniformBuffer.setTexture(\"refractionSamplerHigh\", refractionTexture._lodTextureHigh || refractionTexture);\n }\n }\n if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {\n this._uniformBuffer.setTexture(\"emissiveSampler\", this._emissiveTexture);\n }\n if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {\n this._uniformBuffer.setTexture(\"lightmapSampler\", this._lightmapTexture);\n }\n if (BABYLON.StandardMaterial.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n this._uniformBuffer.setTexture(\"reflectivitySampler\", this._metallicTexture);\n }\n else if (this._reflectivityTexture) {\n this._uniformBuffer.setTexture(\"reflectivitySampler\", this._reflectivityTexture);\n }\n if (this._microSurfaceTexture) {\n this._uniformBuffer.setTexture(\"microSurfaceSampler\", this._microSurfaceTexture);\n }\n }\n if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {\n this._uniformBuffer.setTexture(\"bumpSampler\", this._bumpTexture);\n }\n }\n // Clip plane\n BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);\n // Colors\n scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);\n var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);\n var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));\n effect.setFloat4(\"vEyePosition\", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);\n effect.setColor3(\"vAmbientColor\", this._globalAmbientColor);\n }\n if (mustRebind || !this.isFrozen) {\n // Lights\n if (scene.lightsEnabled && !this._disableLighting) {\n BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);\n }\n // View\n if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {\n this.bindView(effect);\n }\n // Fog\n BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);\n // Morph targets\n if (defines.NUM_MORPH_INFLUENCERS) {\n BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);\n }\n // image processing\n this._imageProcessingConfiguration.bind(this._activeEffect);\n // Log. depth\n BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);\n }\n this._uniformBuffer.update();\n this._afterBind(mesh, this._activeEffect);\n };\n /**\n * Returns the animatable textures.\n * @returns - Array of animatable textures.\n */\n PBRBaseMaterial.prototype.getAnimatables = function () {\n var results = [];\n if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {\n results.push(this._albedoTexture);\n }\n if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {\n results.push(this._ambientTexture);\n }\n if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {\n results.push(this._opacityTexture);\n }\n if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {\n results.push(this._reflectionTexture);\n }\n if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {\n results.push(this._emissiveTexture);\n }\n if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {\n results.push(this._metallicTexture);\n }\n else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {\n results.push(this._reflectivityTexture);\n }\n if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {\n results.push(this._bumpTexture);\n }\n if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {\n results.push(this._lightmapTexture);\n }\n if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {\n results.push(this._refractionTexture);\n }\n return results;\n };\n /**\n * Returns the texture used for reflections.\n * @returns - Reflection texture if present. Otherwise, returns the environment texture.\n */\n PBRBaseMaterial.prototype._getReflectionTexture = function () {\n if (this._reflectionTexture) {\n return this._reflectionTexture;\n }\n return this.getScene().environmentTexture;\n };\n /**\n * Returns the texture used for refraction or null if none is used.\n * @returns - Refection texture if present. If no refraction texture and refraction\n * is linked with transparency, returns environment texture. Otherwise, returns null.\n */\n PBRBaseMaterial.prototype._getRefractionTexture = function () {\n if (this._refractionTexture) {\n return this._refractionTexture;\n }\n if (this._linkRefractionWithTransparency) {\n return this.getScene().environmentTexture;\n }\n return null;\n };\n /**\n * Disposes the resources of the material.\n * @param forceDisposeEffect - Forces the disposal of effects.\n * @param forceDisposeTextures - Forces the disposal of all textures.\n */\n PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {\n if (forceDisposeTextures) {\n if (this._albedoTexture) {\n this._albedoTexture.dispose();\n }\n if (this._ambientTexture) {\n this._ambientTexture.dispose();\n }\n if (this._opacityTexture) {\n this._opacityTexture.dispose();\n }\n if (this._reflectionTexture) {\n this._reflectionTexture.dispose();\n }\n if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {\n this._environmentBRDFTexture.dispose();\n }\n if (this._emissiveTexture) {\n this._emissiveTexture.dispose();\n }\n if (this._metallicTexture) {\n this._metallicTexture.dispose();\n }\n if (this._reflectivityTexture) {\n this._reflectivityTexture.dispose();\n }\n if (this._bumpTexture) {\n this._bumpTexture.dispose();\n }\n if (this._lightmapTexture) {\n this._lightmapTexture.dispose();\n }\n if (this._refractionTexture) {\n this._refractionTexture.dispose();\n }\n }\n this._renderTargets.dispose();\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);\n };\n /**\n * Stores the reflectivity values based on metallic roughness workflow.\n */\n PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();\n __decorate([\n BABYLON.serializeAsImageProcessingConfiguration()\n ], PBRBaseMaterial.prototype, \"_imageProcessingConfiguration\", void 0);\n __decorate([\n BABYLON.serialize()\n ], PBRBaseMaterial.prototype, \"useLogarithmicDepth\", null);\n __decorate([\n BABYLON.serialize()\n ], PBRBaseMaterial.prototype, \"transparencyMode\", null);\n return PBRBaseMaterial;\n }(BABYLON.PushMaterial));\n BABYLON.PBRBaseMaterial = PBRBaseMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pbrBaseMaterial.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The Physically based simple base material of BJS.\n *\n * This enables better naming and convention enforcements on top of the pbrMaterial.\n * It is used as the base class for both the specGloss and metalRough conventions.\n */\n var PBRBaseSimpleMaterial = /** @class */ (function (_super) {\n __extends(PBRBaseSimpleMaterial, _super);\n /**\n * Instantiates a new PBRMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n function PBRBaseSimpleMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n _this.maxSimultaneousLights = 4;\n /**\n * If sets to true, disables all the lights affecting the material.\n */\n _this.disableLighting = false;\n /**\n * If sets to true, x component of normal map value will invert (x = 1.0 - x).\n */\n _this.invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will invert (y = 1.0 - y).\n */\n _this.invertNormalMapY = false;\n /**\n * Emissivie color used to self-illuminate the model.\n */\n _this.emissiveColor = new BABYLON.Color3(0, 0, 0);\n /**\n * Occlusion Channel Strenght.\n */\n _this.occlusionStrength = 1.0;\n _this.useLightmapAsShadowmap = false;\n _this._useAlphaFromAlbedoTexture = true;\n _this._useAmbientInGrayScale = true;\n return _this;\n }\n Object.defineProperty(PBRBaseSimpleMaterial.prototype, \"doubleSided\", {\n /**\n * Gets the current double sided mode.\n */\n get: function () {\n return this._twoSidedLighting;\n },\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n */\n set: function (value) {\n if (this._twoSidedLighting === value) {\n return;\n }\n this._twoSidedLighting = value;\n this.backFaceCulling = !value;\n this._markAllSubMeshesAsTexturesDirty();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Return the active textures of the material.\n */\n PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {\n var activeTextures = _super.prototype.getActiveTextures.call(this);\n if (this.environmentTexture) {\n activeTextures.push(this.environmentTexture);\n }\n if (this.normalTexture) {\n activeTextures.push(this.normalTexture);\n }\n if (this.emissiveTexture) {\n activeTextures.push(this.emissiveTexture);\n }\n if (this.occlusionTexture) {\n activeTextures.push(this.occlusionTexture);\n }\n if (this.lightmapTexture) {\n activeTextures.push(this.lightmapTexture);\n }\n return activeTextures;\n };\n PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {\n if (_super.prototype.hasTexture.call(this, texture)) {\n return true;\n }\n if (this.lightmapTexture === texture) {\n return true;\n }\n return false;\n };\n PBRBaseSimpleMaterial.prototype.getClassName = function () {\n return \"PBRBaseSimpleMaterial\";\n };\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"maxSimultaneousLights\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"disableLighting\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_reflectionTexture\")\n ], PBRBaseSimpleMaterial.prototype, \"environmentTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"invertNormalMapX\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"invertNormalMapY\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_bumpTexture\")\n ], PBRBaseSimpleMaterial.prototype, \"normalTexture\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"emissive\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"emissiveColor\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"emissiveTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_ambientTextureStrength\")\n ], PBRBaseSimpleMaterial.prototype, \"occlusionStrength\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_ambientTexture\")\n ], PBRBaseSimpleMaterial.prototype, \"occlusionTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_alphaCutOff\")\n ], PBRBaseSimpleMaterial.prototype, \"alphaCutOff\", void 0);\n __decorate([\n BABYLON.serialize()\n ], PBRBaseSimpleMaterial.prototype, \"doubleSided\", null);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", null)\n ], PBRBaseSimpleMaterial.prototype, \"lightmapTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"useLightmapAsShadowmap\", void 0);\n return PBRBaseSimpleMaterial;\n }(BABYLON.PBRBaseMaterial));\n BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The Physically based material of BJS.\n *\n * This offers the main features of a standard PBR material.\n * For more information, please refer to the documentation :\n * http://doc.babylonjs.com/extensions/Physically_Based_Rendering\n */\n var PBRMaterial = /** @class */ (function (_super) {\n __extends(PBRMaterial, _super);\n /**\n * Instantiates a new PBRMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n function PBRMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n /**\n * Intensity of the direct lights e.g. the four lights available in your scene.\n * This impacts both the direct diffuse and specular highlights.\n */\n _this.directIntensity = 1.0;\n /**\n * Intensity of the emissive part of the material.\n * This helps controlling the emissive effect without modifying the emissive color.\n */\n _this.emissiveIntensity = 1.0;\n /**\n * Intensity of the environment e.g. how much the environment will light the object\n * either through harmonics for rough material or through the refelction for shiny ones.\n */\n _this.environmentIntensity = 1.0;\n /**\n * This is a special control allowing the reduction of the specular highlights coming from the\n * four lights of the scene. Those highlights may not be needed in full environment lighting.\n */\n _this.specularIntensity = 1.0;\n /**\n * Debug Control allowing disabling the bump map on this material.\n */\n _this.disableBumpMap = false;\n /**\n * AKA Occlusion Texture Intensity in other nomenclature.\n */\n _this.ambientTextureStrength = 1.0;\n /**\n * The color of a material in ambient lighting.\n */\n _this.ambientColor = new BABYLON.Color3(0, 0, 0);\n /**\n * AKA Diffuse Color in other nomenclature.\n */\n _this.albedoColor = new BABYLON.Color3(1, 1, 1);\n /**\n * AKA Specular Color in other nomenclature.\n */\n _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);\n /**\n * The color reflected from the material.\n */\n _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);\n /**\n * The color emitted from the material.\n */\n _this.emissiveColor = new BABYLON.Color3(0, 0, 0);\n /**\n * AKA Glossiness in other nomenclature.\n */\n _this.microSurface = 1.0;\n /**\n * source material index of refraction (IOR)' / 'destination material IOR.\n */\n _this.indexOfRefraction = 0.66;\n /**\n * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.\n */\n _this.invertRefractionY = false;\n /**\n * This parameters will make the material used its opacity to control how much it is refracting aginst not.\n * Materials half opaque for instance using refraction could benefit from this control.\n */\n _this.linkRefractionWithTransparency = false;\n _this.useLightmapAsShadowmap = false;\n /**\n * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.\n */\n _this.useAlphaFromAlbedoTexture = false;\n /**\n * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.\n */\n _this.forceAlphaTest = false;\n /**\n * Defines the alpha limits in alpha test mode.\n */\n _this.alphaCutOff = 0.4;\n /**\n * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).\n * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.\n */\n _this.useSpecularOverAlpha = true;\n /**\n * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.\n */\n _this.useMicroSurfaceFromReflectivityMapAlpha = false;\n /**\n * Specifies if the metallic texture contains the roughness information in its alpha channel.\n */\n _this.useRoughnessFromMetallicTextureAlpha = true;\n /**\n * Specifies if the metallic texture contains the roughness information in its green channel.\n */\n _this.useRoughnessFromMetallicTextureGreen = false;\n /**\n * Specifies if the metallic texture contains the metallness information in its blue channel.\n */\n _this.useMetallnessFromMetallicTextureBlue = false;\n /**\n * Specifies if the metallic texture contains the ambient occlusion information in its red channel.\n */\n _this.useAmbientOcclusionFromMetallicTextureRed = false;\n /**\n * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.\n */\n _this.useAmbientInGrayScale = false;\n /**\n * In case the reflectivity map does not contain the microsurface information in its alpha channel,\n * The material will try to infer what glossiness each pixel should be.\n */\n _this.useAutoMicroSurfaceFromReflectivityMap = false;\n /**\n * BJS is using an harcoded light falloff based on a manually sets up range.\n * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.\n * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.\n */\n _this.usePhysicalLightFalloff = true;\n /**\n * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).\n * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.\n */\n _this.useRadianceOverAlpha = true;\n /**\n * Allows using an object space normal map (instead of tangent space).\n */\n _this.useObjectSpaceNormalMap = false;\n /**\n * Allows using the bump map in parallax mode.\n */\n _this.useParallax = false;\n /**\n * Allows using the bump map in parallax occlusion mode.\n */\n _this.useParallaxOcclusion = false;\n /**\n * Controls the scale bias of the parallax mode.\n */\n _this.parallaxScaleBias = 0.05;\n /**\n * If sets to true, disables all the lights affecting the material.\n */\n _this.disableLighting = false;\n /**\n * Force the shader to compute irradiance in the fragment shader in order to take bump in account.\n */\n _this.forceIrradianceInFragment = false;\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n _this.maxSimultaneousLights = 4;\n /**\n * If sets to true, x component of normal map value will invert (x = 1.0 - x).\n */\n _this.invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will invert (y = 1.0 - y).\n */\n _this.invertNormalMapY = false;\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n */\n _this.twoSidedLighting = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)\n */\n _this.useAlphaFresnel = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)\n */\n _this.useLinearAlphaFresnel = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part.\n */\n _this.environmentBRDFTexture = null;\n /**\n * Force normal to face away from face.\n */\n _this.forceNormalForward = false;\n /**\n * Enables specular anti aliasing in the PBR shader.\n * It will both interacts on the Geometry for analytical and IBL lighting.\n * It also prefilter the roughness map based on the bump values.\n */\n _this.enableSpecularAntiAliasing = false;\n /**\n * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal\n * makes the reflect vector face the model (under horizon).\n */\n _this.useHorizonOcclusion = true;\n /**\n * This parameters will enable/disable radiance occlusion by preventing the radiance to lit\n * too much the area relying on ambient texture to define their ambient occlusion.\n */\n _this.useRadianceOcclusion = true;\n /**\n * If set to true, no lighting calculations will be applied.\n */\n _this.unlit = false;\n _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);\n return _this;\n }\n Object.defineProperty(PBRMaterial, \"PBRMATERIAL_OPAQUE\", {\n /**\n * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.\n */\n get: function () {\n return this._PBRMATERIAL_OPAQUE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial, \"PBRMATERIAL_ALPHATEST\", {\n /**\n * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.\n */\n get: function () {\n return this._PBRMATERIAL_ALPHATEST;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial, \"PBRMATERIAL_ALPHABLEND\", {\n /**\n * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n */\n get: function () {\n return this._PBRMATERIAL_ALPHABLEND;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial, \"PBRMATERIAL_ALPHATESTANDBLEND\", {\n /**\n * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n * They are also discarded below the alpha cutoff threshold to improve performances.\n */\n get: function () {\n return this._PBRMATERIAL_ALPHATESTANDBLEND;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial.prototype, \"imageProcessingConfiguration\", {\n /**\n * Gets the image processing configuration used either in this material.\n */\n get: function () {\n return this._imageProcessingConfiguration;\n },\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set: function (value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial.prototype, \"cameraColorCurvesEnabled\", {\n /**\n * Gets wether the color curves effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n },\n /**\n * Sets wether the color curves effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial.prototype, \"cameraColorGradingEnabled\", {\n /**\n * Gets wether the color grading effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n },\n /**\n * Gets wether the color grading effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial.prototype, \"cameraToneMappingEnabled\", {\n /**\n * Gets wether tonemapping is enabled or not.\n */\n get: function () {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n },\n /**\n * Sets wether tonemapping is enabled or not\n */\n set: function (value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(PBRMaterial.prototype, \"cameraExposure\", {\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n get: function () {\n return this._imageProcessingConfiguration.exposure;\n },\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n set: function (value) {\n this._imageProcessingConfiguration.exposure = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(PBRMaterial.prototype, \"cameraContrast\", {\n /**\n * Gets The camera contrast used on this material.\n */\n get: function () {\n return this._imageProcessingConfiguration.contrast;\n },\n /**\n * Sets The camera contrast used on this material.\n */\n set: function (value) {\n this._imageProcessingConfiguration.contrast = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial.prototype, \"cameraColorGradingTexture\", {\n /**\n * Gets the Color Grading 2D Lookup Texture.\n */\n get: function () {\n return this._imageProcessingConfiguration.colorGradingTexture;\n },\n /**\n * Sets the Color Grading 2D Lookup Texture.\n */\n set: function (value) {\n this._imageProcessingConfiguration.colorGradingTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial.prototype, \"cameraColorCurves\", {\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n get: function () {\n return this._imageProcessingConfiguration.colorCurves;\n },\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n set: function (value) {\n this._imageProcessingConfiguration.colorCurves = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the name of this material class.\n */\n PBRMaterial.prototype.getClassName = function () {\n return \"PBRMaterial\";\n };\n /**\n * Returns an array of the actively used textures.\n * @returns - Array of BaseTextures\n */\n PBRMaterial.prototype.getActiveTextures = function () {\n var activeTextures = _super.prototype.getActiveTextures.call(this);\n if (this._albedoTexture) {\n activeTextures.push(this._albedoTexture);\n }\n if (this._ambientTexture) {\n activeTextures.push(this._ambientTexture);\n }\n if (this._opacityTexture) {\n activeTextures.push(this._opacityTexture);\n }\n if (this._reflectionTexture) {\n activeTextures.push(this._reflectionTexture);\n }\n if (this._emissiveTexture) {\n activeTextures.push(this._emissiveTexture);\n }\n if (this._reflectivityTexture) {\n activeTextures.push(this._reflectivityTexture);\n }\n if (this._metallicTexture) {\n activeTextures.push(this._metallicTexture);\n }\n if (this._microSurfaceTexture) {\n activeTextures.push(this._microSurfaceTexture);\n }\n if (this._bumpTexture) {\n activeTextures.push(this._bumpTexture);\n }\n if (this._lightmapTexture) {\n activeTextures.push(this._lightmapTexture);\n }\n if (this._refractionTexture) {\n activeTextures.push(this._refractionTexture);\n }\n return activeTextures;\n };\n /**\n * Checks to see if a texture is used in the material.\n * @param texture - Base texture to use.\n * @returns - Boolean specifying if a texture is used in the material.\n */\n PBRMaterial.prototype.hasTexture = function (texture) {\n if (_super.prototype.hasTexture.call(this, texture)) {\n return true;\n }\n if (this._albedoTexture === texture) {\n return true;\n }\n if (this._ambientTexture === texture) {\n return true;\n }\n if (this._opacityTexture === texture) {\n return true;\n }\n if (this._reflectionTexture === texture) {\n return true;\n }\n if (this._reflectivityTexture === texture) {\n return true;\n }\n if (this._metallicTexture === texture) {\n return true;\n }\n if (this._microSurfaceTexture === texture) {\n return true;\n }\n if (this._bumpTexture === texture) {\n return true;\n }\n if (this._lightmapTexture === texture) {\n return true;\n }\n if (this._refractionTexture === texture) {\n return true;\n }\n return false;\n };\n /**\n * Makes a duplicate of the current material.\n * @param name - name to use for the new material.\n */\n PBRMaterial.prototype.clone = function (name) {\n var _this = this;\n var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);\n clone.id = name;\n clone.name = name;\n return clone;\n };\n /**\n * Serializes this PBR Material.\n * @returns - An object with the serialized material.\n */\n PBRMaterial.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.PBRMaterial\";\n return serializationObject;\n };\n // Statics\n /**\n * Parses a PBR Material from a serialized object.\n * @param source - Serialized object.\n * @param scene - BJS scene instance.\n * @param rootUrl - url for the scene object\n * @returns - PBRMaterial\n */\n PBRMaterial.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);\n };\n PBRMaterial._PBRMATERIAL_OPAQUE = 0;\n /**\n * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.\n */\n PBRMaterial._PBRMATERIAL_ALPHATEST = 1;\n /**\n * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n */\n PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;\n /**\n * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n * They are also discarded below the alpha cutoff threshold to improve performances.\n */\n PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"directIntensity\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"emissiveIntensity\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"environmentIntensity\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"specularIntensity\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"disableBumpMap\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"albedoTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"ambientTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"ambientTextureStrength\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n ], PBRMaterial.prototype, \"opacityTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"reflectionTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"emissiveTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"reflectivityTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"metallicTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"metallic\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"roughness\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"microSurfaceTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"bumpTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", null)\n ], PBRMaterial.prototype, \"lightmapTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"refractionTexture\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"ambient\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"ambientColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"albedo\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"albedoColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"reflectivity\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"reflectivityColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"reflection\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"reflectionColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"emissive\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"emissiveColor\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"microSurface\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"indexOfRefraction\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"invertRefractionY\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"linkRefractionWithTransparency\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useLightmapAsShadowmap\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n ], PBRMaterial.prototype, \"useAlphaFromAlbedoTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n ], PBRMaterial.prototype, \"forceAlphaTest\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n ], PBRMaterial.prototype, \"alphaCutOff\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useSpecularOverAlpha\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useMicroSurfaceFromReflectivityMapAlpha\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useRoughnessFromMetallicTextureAlpha\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useRoughnessFromMetallicTextureGreen\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useMetallnessFromMetallicTextureBlue\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useAmbientOcclusionFromMetallicTextureRed\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useAmbientInGrayScale\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useAutoMicroSurfaceFromReflectivityMap\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"usePhysicalLightFalloff\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useRadianceOverAlpha\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useObjectSpaceNormalMap\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useParallax\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useParallaxOcclusion\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"parallaxScaleBias\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], PBRMaterial.prototype, \"disableLighting\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"forceIrradianceInFragment\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], PBRMaterial.prototype, \"maxSimultaneousLights\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"invertNormalMapX\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"invertNormalMapY\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"twoSidedLighting\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useAlphaFresnel\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useLinearAlphaFresnel\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"environmentBRDFTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"forceNormalForward\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"enableSpecularAntiAliasing\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useHorizonOcclusion\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useRadianceOcclusion\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n ], PBRMaterial.prototype, \"unlit\", void 0);\n return PBRMaterial;\n }(BABYLON.PBRBaseMaterial));\n BABYLON.PBRMaterial = PBRMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pbrMaterial.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The PBR material of BJS following the metal roughness convention.\n *\n * This fits to the PBR convention in the GLTF definition:\n * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0\n */\n var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {\n __extends(PBRMetallicRoughnessMaterial, _super);\n /**\n * Instantiates a new PBRMetalRoughnessMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n function PBRMetallicRoughnessMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._useRoughnessFromMetallicTextureAlpha = false;\n _this._useRoughnessFromMetallicTextureGreen = true;\n _this._useMetallnessFromMetallicTextureBlue = true;\n _this.metallic = 1.0;\n _this.roughness = 1.0;\n return _this;\n }\n /**\n * Return the currrent class name of the material.\n */\n PBRMetallicRoughnessMaterial.prototype.getClassName = function () {\n return \"PBRMetallicRoughnessMaterial\";\n };\n /**\n * Return the active textures of the material.\n */\n PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {\n var activeTextures = _super.prototype.getActiveTextures.call(this);\n if (this.baseTexture) {\n activeTextures.push(this.baseTexture);\n }\n if (this.metallicRoughnessTexture) {\n activeTextures.push(this.metallicRoughnessTexture);\n }\n return activeTextures;\n };\n /**\n * Checks to see if a texture is used in the material.\n * @param texture - Base texture to use.\n * @returns - Boolean specifying if a texture is used in the material.\n */\n PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {\n if (_super.prototype.hasTexture.call(this, texture)) {\n return true;\n }\n if (this.baseTexture === texture) {\n return true;\n }\n if (this.metallicRoughnessTexture === texture) {\n return true;\n }\n return false;\n };\n /**\n * Makes a duplicate of the current material.\n * @param name - name to use for the new material.\n */\n PBRMetallicRoughnessMaterial.prototype.clone = function (name) {\n var _this = this;\n var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);\n clone.id = name;\n clone.name = name;\n return clone;\n };\n /**\n * Serialize the material to a parsable JSON object.\n */\n PBRMetallicRoughnessMaterial.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.PBRMetallicRoughnessMaterial\";\n return serializationObject;\n };\n /**\n * Parses a JSON object correponding to the serialize function.\n */\n PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);\n };\n __decorate([\n BABYLON.serializeAsColor3(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoColor\")\n ], PBRMetallicRoughnessMaterial.prototype, \"baseColor\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoTexture\")\n ], PBRMetallicRoughnessMaterial.prototype, \"baseTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMetallicRoughnessMaterial.prototype, \"metallic\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMetallicRoughnessMaterial.prototype, \"roughness\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_metallicTexture\")\n ], PBRMetallicRoughnessMaterial.prototype, \"metallicRoughnessTexture\", void 0);\n return PBRMetallicRoughnessMaterial;\n }(BABYLON.PBRBaseSimpleMaterial));\n BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The PBR material of BJS following the specular glossiness convention.\n *\n * This fits to the PBR convention in the GLTF definition:\n * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness\n */\n var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {\n __extends(PBRSpecularGlossinessMaterial, _super);\n /**\n * Instantiates a new PBRSpecularGlossinessMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n function PBRSpecularGlossinessMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._useMicroSurfaceFromReflectivityMapAlpha = true;\n return _this;\n }\n /**\n * Return the currrent class name of the material.\n */\n PBRSpecularGlossinessMaterial.prototype.getClassName = function () {\n return \"PBRSpecularGlossinessMaterial\";\n };\n /**\n * Return the active textures of the material.\n */\n PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {\n var activeTextures = _super.prototype.getActiveTextures.call(this);\n if (this.diffuseTexture) {\n activeTextures.push(this.diffuseTexture);\n }\n if (this.specularGlossinessTexture) {\n activeTextures.push(this.specularGlossinessTexture);\n }\n return activeTextures;\n };\n /**\n * Checks to see if a texture is used in the material.\n * @param texture - Base texture to use.\n * @returns - Boolean specifying if a texture is used in the material.\n */\n PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {\n if (_super.prototype.hasTexture.call(this, texture)) {\n return true;\n }\n if (this.diffuseTexture === texture) {\n return true;\n }\n if (this.specularGlossinessTexture === texture) {\n return true;\n }\n return false;\n };\n /**\n * Makes a duplicate of the current material.\n * @param name - name to use for the new material.\n */\n PBRSpecularGlossinessMaterial.prototype.clone = function (name) {\n var _this = this;\n var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);\n clone.id = name;\n clone.name = name;\n return clone;\n };\n /**\n * Serialize the material to a parsable JSON object.\n */\n PBRSpecularGlossinessMaterial.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.PBRSpecularGlossinessMaterial\";\n return serializationObject;\n };\n /**\n * Parses a JSON object correponding to the serialize function.\n */\n PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);\n };\n __decorate([\n BABYLON.serializeAsColor3(\"diffuse\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoColor\")\n ], PBRSpecularGlossinessMaterial.prototype, \"diffuseColor\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoTexture\")\n ], PBRSpecularGlossinessMaterial.prototype, \"diffuseTexture\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"specular\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_reflectivityColor\")\n ], PBRSpecularGlossinessMaterial.prototype, \"specularColor\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_microSurface\")\n ], PBRSpecularGlossinessMaterial.prototype, \"glossiness\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_reflectivityTexture\")\n ], PBRSpecularGlossinessMaterial.prototype, \"specularGlossinessTexture\", void 0);\n return PBRSpecularGlossinessMaterial;\n }(BABYLON.PBRBaseSimpleMaterial));\n BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.CameraInputTypes = {};\n var CameraInputsManager = /** @class */ (function () {\n function CameraInputsManager(camera) {\n this.attached = {};\n this.camera = camera;\n this.checkInputs = function () { };\n }\n /**\n * Add an input method to a camera\n * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs\n * @param input camera input method\n */\n CameraInputsManager.prototype.add = function (input) {\n var type = input.getSimpleName();\n if (this.attached[type]) {\n BABYLON.Tools.Warn(\"camera input of type \" + type + \" already exists on camera\");\n return;\n }\n this.attached[type] = input;\n input.camera = this.camera;\n //for checkInputs, we are dynamically creating a function\n //the goal is to avoid the performance penalty of looping for inputs in the render loop\n if (input.checkInputs) {\n this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));\n }\n if (this.attachedElement) {\n input.attachControl(this.attachedElement);\n }\n };\n /**\n * Remove a specific input method from a camera\n * example: camera.inputs.remove(camera.inputs.attached.mouse);\n * @param inputToRemove camera input method\n */\n CameraInputsManager.prototype.remove = function (inputToRemove) {\n for (var cam in this.attached) {\n var input = this.attached[cam];\n if (input === inputToRemove) {\n input.detachControl(this.attachedElement);\n input.camera = null;\n delete this.attached[cam];\n this.rebuildInputCheck();\n }\n }\n };\n CameraInputsManager.prototype.removeByType = function (inputType) {\n for (var cam in this.attached) {\n var input = this.attached[cam];\n if (input.getClassName() === inputType) {\n input.detachControl(this.attachedElement);\n input.camera = null;\n delete this.attached[cam];\n this.rebuildInputCheck();\n }\n }\n };\n CameraInputsManager.prototype._addCheckInputs = function (fn) {\n var current = this.checkInputs;\n return function () {\n current();\n fn();\n };\n };\n CameraInputsManager.prototype.attachInput = function (input) {\n if (this.attachedElement) {\n input.attachControl(this.attachedElement, this.noPreventDefault);\n }\n };\n CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {\n if (noPreventDefault === void 0) { noPreventDefault = false; }\n if (this.attachedElement) {\n return;\n }\n noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;\n this.attachedElement = element;\n this.noPreventDefault = noPreventDefault;\n for (var cam in this.attached) {\n this.attached[cam].attachControl(element, noPreventDefault);\n }\n };\n CameraInputsManager.prototype.detachElement = function (element, disconnect) {\n if (disconnect === void 0) { disconnect = false; }\n if (this.attachedElement !== element) {\n return;\n }\n for (var cam in this.attached) {\n this.attached[cam].detachControl(element);\n if (disconnect) {\n this.attached[cam].camera = null;\n }\n }\n this.attachedElement = null;\n };\n CameraInputsManager.prototype.rebuildInputCheck = function () {\n this.checkInputs = function () { };\n for (var cam in this.attached) {\n var input = this.attached[cam];\n if (input.checkInputs) {\n this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));\n }\n }\n };\n /**\n * Remove all attached input methods from a camera\n */\n CameraInputsManager.prototype.clear = function () {\n if (this.attachedElement) {\n this.detachElement(this.attachedElement, true);\n }\n this.attached = {};\n this.attachedElement = null;\n this.checkInputs = function () { };\n };\n CameraInputsManager.prototype.serialize = function (serializedCamera) {\n var inputs = {};\n for (var cam in this.attached) {\n var input = this.attached[cam];\n var res = BABYLON.SerializationHelper.Serialize(input);\n inputs[input.getClassName()] = res;\n }\n serializedCamera.inputsmgr = inputs;\n };\n CameraInputsManager.prototype.parse = function (parsedCamera) {\n var parsedInputs = parsedCamera.inputsmgr;\n if (parsedInputs) {\n this.clear();\n for (var n in parsedInputs) {\n var construct = BABYLON.CameraInputTypes[n];\n if (construct) {\n var parsedinput = parsedInputs[n];\n var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);\n this.add(input);\n }\n }\n }\n else {\n //2016-03-08 this part is for managing backward compatibility\n for (var n in this.attached) {\n var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];\n if (construct) {\n var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);\n this.remove(this.attached[n]);\n this.add(input);\n }\n }\n }\n };\n return CameraInputsManager;\n }());\n BABYLON.CameraInputsManager = CameraInputsManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.cameraInputsManager.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var TargetCamera = /** @class */ (function (_super) {\n __extends(TargetCamera, _super);\n function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {\n if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }\n var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;\n _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);\n _this.cameraRotation = new BABYLON.Vector2(0, 0);\n _this.rotation = new BABYLON.Vector3(0, 0, 0);\n _this.speed = 2.0;\n _this.noRotationConstraint = false;\n _this.lockedTarget = null;\n _this._currentTarget = BABYLON.Vector3.Zero();\n _this._viewMatrix = BABYLON.Matrix.Zero();\n _this._camMatrix = BABYLON.Matrix.Zero();\n _this._cameraTransformMatrix = BABYLON.Matrix.Zero();\n _this._cameraRotationMatrix = BABYLON.Matrix.Zero();\n _this._referencePoint = new BABYLON.Vector3(0, 0, 1);\n _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);\n _this._transformedReferencePoint = BABYLON.Vector3.Zero();\n _this._globalCurrentTarget = BABYLON.Vector3.Zero();\n _this._globalCurrentUpVector = BABYLON.Vector3.Zero();\n return _this;\n }\n TargetCamera.prototype.getFrontPosition = function (distance) {\n this.getWorldMatrix();\n var direction = this.getTarget().subtract(this.position);\n direction.normalize();\n direction.scaleInPlace(distance);\n return this.globalPosition.add(direction);\n };\n TargetCamera.prototype._getLockedTargetPosition = function () {\n if (!this.lockedTarget) {\n return null;\n }\n if (this.lockedTarget.absolutePosition) {\n this.lockedTarget.computeWorldMatrix();\n }\n return this.lockedTarget.absolutePosition || this.lockedTarget;\n };\n TargetCamera.prototype.storeState = function () {\n this._storedPosition = this.position.clone();\n this._storedRotation = this.rotation.clone();\n if (this.rotationQuaternion) {\n this._storedRotationQuaternion = this.rotationQuaternion.clone();\n }\n return _super.prototype.storeState.call(this);\n };\n /**\n * Restored camera state. You must call storeState() first\n */\n TargetCamera.prototype._restoreStateValues = function () {\n if (!_super.prototype._restoreStateValues.call(this)) {\n return false;\n }\n this.position = this._storedPosition.clone();\n this.rotation = this._storedRotation.clone();\n if (this.rotationQuaternion) {\n this.rotationQuaternion = this._storedRotationQuaternion.clone();\n }\n this.cameraDirection.copyFromFloats(0, 0, 0);\n this.cameraRotation.copyFromFloats(0, 0);\n return true;\n };\n // Cache\n TargetCamera.prototype._initCache = function () {\n _super.prototype._initCache.call(this);\n this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n };\n TargetCamera.prototype._updateCache = function (ignoreParentClass) {\n if (!ignoreParentClass) {\n _super.prototype._updateCache.call(this);\n }\n var lockedTargetPosition = this._getLockedTargetPosition();\n if (!lockedTargetPosition) {\n this._cache.lockedTarget = null;\n }\n else {\n if (!this._cache.lockedTarget) {\n this._cache.lockedTarget = lockedTargetPosition.clone();\n }\n else {\n this._cache.lockedTarget.copyFrom(lockedTargetPosition);\n }\n }\n this._cache.rotation.copyFrom(this.rotation);\n if (this.rotationQuaternion)\n this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);\n };\n // Synchronized\n TargetCamera.prototype._isSynchronizedViewMatrix = function () {\n if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {\n return false;\n }\n var lockedTargetPosition = this._getLockedTargetPosition();\n return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)\n && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));\n };\n // Methods\n TargetCamera.prototype._computeLocalCameraSpeed = function () {\n var engine = this.getEngine();\n return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));\n };\n // Target\n TargetCamera.prototype.setTarget = function (target) {\n this.upVector.normalize();\n BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);\n this._camMatrix.invert();\n this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);\n var vDir = target.subtract(this.position);\n if (vDir.x >= 0.0) {\n this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);\n }\n else {\n this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);\n }\n this.rotation.z = 0;\n if (isNaN(this.rotation.x)) {\n this.rotation.x = 0;\n }\n if (isNaN(this.rotation.y)) {\n this.rotation.y = 0;\n }\n if (isNaN(this.rotation.z)) {\n this.rotation.z = 0;\n }\n if (this.rotationQuaternion) {\n BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);\n }\n };\n /**\n * Return the current target position of the camera. This value is expressed in local space.\n */\n TargetCamera.prototype.getTarget = function () {\n return this._currentTarget;\n };\n TargetCamera.prototype._decideIfNeedsToMove = function () {\n return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;\n };\n TargetCamera.prototype._updatePosition = function () {\n if (this.parent) {\n this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);\n BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);\n this.position.addInPlace(BABYLON.Tmp.Vector3[0]);\n return;\n }\n this.position.addInPlace(this.cameraDirection);\n };\n TargetCamera.prototype._checkInputs = function () {\n var needToMove = this._decideIfNeedsToMove();\n var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;\n // Move\n if (needToMove) {\n this._updatePosition();\n }\n // Rotate\n if (needToRotate) {\n this.rotation.x += this.cameraRotation.x;\n this.rotation.y += this.cameraRotation.y;\n //rotate, if quaternion is set and rotation was used\n if (this.rotationQuaternion) {\n var len = this.rotation.lengthSquared();\n if (len) {\n BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);\n }\n }\n if (!this.noRotationConstraint) {\n var limit = (Math.PI / 2) * 0.95;\n if (this.rotation.x > limit)\n this.rotation.x = limit;\n if (this.rotation.x < -limit)\n this.rotation.x = -limit;\n }\n }\n // Inertia\n if (needToMove) {\n if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {\n this.cameraDirection.x = 0;\n }\n if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {\n this.cameraDirection.y = 0;\n }\n if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {\n this.cameraDirection.z = 0;\n }\n this.cameraDirection.scaleInPlace(this.inertia);\n }\n if (needToRotate) {\n if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {\n this.cameraRotation.x = 0;\n }\n if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {\n this.cameraRotation.y = 0;\n }\n this.cameraRotation.scaleInPlace(this.inertia);\n }\n _super.prototype._checkInputs.call(this);\n };\n TargetCamera.prototype._updateCameraRotationMatrix = function () {\n if (this.rotationQuaternion) {\n this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);\n }\n else {\n BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);\n }\n //update the up vector!\n BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);\n };\n TargetCamera.prototype._getViewMatrix = function () {\n if (this.lockedTarget) {\n this.setTarget(this._getLockedTargetPosition());\n }\n // Compute\n this._updateCameraRotationMatrix();\n BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);\n // Computing target and final matrix\n this.position.addToRef(this._transformedReferencePoint, this._currentTarget);\n this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);\n return this._viewMatrix;\n };\n TargetCamera.prototype._computeViewMatrix = function (position, target, up) {\n if (this.parent) {\n var parentWorldMatrix = this.parent.getWorldMatrix();\n BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);\n BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);\n BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);\n this._markSyncedWithParent();\n }\n else {\n this._globalPosition.copyFrom(this.position);\n this._globalCurrentTarget.copyFrom(target);\n this._globalCurrentUpVector.copyFrom(up);\n }\n if (this.getScene().useRightHandedSystem) {\n BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);\n }\n else {\n BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);\n }\n };\n /**\n * @override\n * Override Camera.createRigCamera\n */\n TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {\n if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {\n var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());\n if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {\n if (!this.rotationQuaternion) {\n this.rotationQuaternion = new BABYLON.Quaternion();\n }\n rigCamera._cameraRigParams = {};\n rigCamera.rotationQuaternion = new BABYLON.Quaternion();\n }\n return rigCamera;\n }\n return null;\n };\n /**\n * @override\n * Override Camera._updateRigCameras\n */\n TargetCamera.prototype._updateRigCameras = function () {\n var camLeft = this._rigCameras[0];\n var camRight = this._rigCameras[1];\n switch (this.cameraRigMode) {\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:\n var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;\n var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;\n this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);\n this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);\n camLeft.setTarget(this.getTarget());\n camRight.setTarget(this.getTarget());\n break;\n case BABYLON.Camera.RIG_MODE_VR:\n if (camLeft.rotationQuaternion) {\n camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);\n camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);\n }\n else {\n camLeft.rotation.copyFrom(this.rotation);\n camRight.rotation.copyFrom(this.rotation);\n }\n camLeft.position.copyFrom(this.position);\n camRight.position.copyFrom(this.position);\n break;\n }\n _super.prototype._updateRigCameras.call(this);\n };\n TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {\n if (!this._rigCamTransformMatrix) {\n this._rigCamTransformMatrix = new BABYLON.Matrix();\n }\n var target = this.getTarget();\n BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);\n this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));\n BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);\n };\n TargetCamera.prototype.getClassName = function () {\n return \"TargetCamera\";\n };\n __decorate([\n BABYLON.serializeAsVector3()\n ], TargetCamera.prototype, \"rotation\", void 0);\n __decorate([\n BABYLON.serialize()\n ], TargetCamera.prototype, \"speed\", void 0);\n __decorate([\n BABYLON.serializeAsMeshReference(\"lockedTargetId\")\n ], TargetCamera.prototype, \"lockedTarget\", void 0);\n return TargetCamera;\n }(BABYLON.Camera));\n BABYLON.TargetCamera = TargetCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.targetCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FreeCameraMouseInput = /** @class */ (function () {\n function FreeCameraMouseInput(touchEnabled) {\n if (touchEnabled === void 0) { touchEnabled = true; }\n this.touchEnabled = touchEnabled;\n this.buttons = [0, 1, 2];\n this.angularSensibility = 2000.0;\n this.previousPosition = null;\n }\n FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n var engine = this.camera.getEngine();\n if (!this._pointerInput) {\n this._pointerInput = function (p, s) {\n var evt = p.event;\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n if (!_this.touchEnabled && evt.pointerType === \"touch\") {\n return;\n }\n if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {\n return;\n }\n var srcElement = (evt.srcElement || evt.target);\n if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {\n try {\n srcElement.setPointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error. Execution will continue.\n }\n _this.previousPosition = {\n x: evt.clientX,\n y: evt.clientY\n };\n if (!noPreventDefault) {\n evt.preventDefault();\n element.focus();\n }\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {\n try {\n srcElement.releasePointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error.\n }\n _this.previousPosition = null;\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {\n if (!_this.previousPosition || engine.isPointerLock) {\n return;\n }\n var offsetX = evt.clientX - _this.previousPosition.x;\n if (_this.camera.getScene().useRightHandedSystem)\n offsetX *= -1;\n if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)\n offsetX *= -1;\n _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;\n var offsetY = evt.clientY - _this.previousPosition.y;\n _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;\n _this.previousPosition = {\n x: evt.clientX,\n y: evt.clientY\n };\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n };\n }\n this._onMouseMove = function (evt) {\n if (!engine.isPointerLock) {\n return;\n }\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;\n if (_this.camera.getScene().useRightHandedSystem)\n offsetX *= -1;\n if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)\n offsetX *= -1;\n _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;\n var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;\n _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;\n _this.previousPosition = null;\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n };\n this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);\n element.addEventListener(\"mousemove\", this._onMouseMove, false);\n };\n FreeCameraMouseInput.prototype.detachControl = function (element) {\n if (this._observer && element) {\n this.camera.getScene().onPointerObservable.remove(this._observer);\n if (this._onMouseMove) {\n element.removeEventListener(\"mousemove\", this._onMouseMove);\n }\n this._observer = null;\n this._onMouseMove = null;\n this.previousPosition = null;\n }\n };\n FreeCameraMouseInput.prototype.getClassName = function () {\n return \"FreeCameraMouseInput\";\n };\n FreeCameraMouseInput.prototype.getSimpleName = function () {\n return \"mouse\";\n };\n __decorate([\n BABYLON.serialize()\n ], FreeCameraMouseInput.prototype, \"buttons\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCameraMouseInput.prototype, \"angularSensibility\", void 0);\n return FreeCameraMouseInput;\n }());\n BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;\n BABYLON.CameraInputTypes[\"FreeCameraMouseInput\"] = FreeCameraMouseInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraMouseInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FreeCameraKeyboardMoveInput = /** @class */ (function () {\n function FreeCameraKeyboardMoveInput() {\n this._keys = new Array();\n this.keysUp = [38];\n this.keysDown = [40];\n this.keysLeft = [37];\n this.keysRight = [39];\n }\n FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n if (this._onCanvasBlurObserver) {\n return;\n }\n this._scene = this.camera.getScene();\n this._engine = this._scene.getEngine();\n this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {\n _this._keys = [];\n });\n this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {\n var evt = info.event;\n if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {\n if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||\n _this.keysDown.indexOf(evt.keyCode) !== -1 ||\n _this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n _this.keysRight.indexOf(evt.keyCode) !== -1) {\n var index = _this._keys.indexOf(evt.keyCode);\n if (index === -1) {\n _this._keys.push(evt.keyCode);\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n else {\n if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||\n _this.keysDown.indexOf(evt.keyCode) !== -1 ||\n _this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n _this.keysRight.indexOf(evt.keyCode) !== -1) {\n var index = _this._keys.indexOf(evt.keyCode);\n if (index >= 0) {\n _this._keys.splice(index, 1);\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n });\n };\n FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {\n if (this._scene) {\n if (this._onKeyboardObserver) {\n this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);\n }\n if (this._onCanvasBlurObserver) {\n this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n this._onKeyboardObserver = null;\n this._onCanvasBlurObserver = null;\n }\n this._keys = [];\n };\n FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {\n if (this._onKeyboardObserver) {\n var camera = this.camera;\n // Keyboard\n for (var index = 0; index < this._keys.length; index++) {\n var keyCode = this._keys[index];\n var speed = camera._computeLocalCameraSpeed();\n if (this.keysLeft.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(-speed, 0, 0);\n }\n else if (this.keysUp.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, speed);\n }\n else if (this.keysRight.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(speed, 0, 0);\n }\n else if (this.keysDown.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, -speed);\n }\n if (camera.getScene().useRightHandedSystem) {\n camera._localDirection.z *= -1;\n }\n camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);\n BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);\n camera.cameraDirection.addInPlace(camera._transformedDirection);\n }\n }\n };\n FreeCameraKeyboardMoveInput.prototype.getClassName = function () {\n return \"FreeCameraKeyboardMoveInput\";\n };\n FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {\n this._keys = [];\n };\n FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {\n return \"keyboard\";\n };\n __decorate([\n BABYLON.serialize()\n ], FreeCameraKeyboardMoveInput.prototype, \"keysUp\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCameraKeyboardMoveInput.prototype, \"keysDown\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCameraKeyboardMoveInput.prototype, \"keysLeft\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCameraKeyboardMoveInput.prototype, \"keysRight\", void 0);\n return FreeCameraKeyboardMoveInput;\n }());\n BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;\n BABYLON.CameraInputTypes[\"FreeCameraKeyboardMoveInput\"] = FreeCameraKeyboardMoveInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FreeCameraInputsManager = /** @class */ (function (_super) {\n __extends(FreeCameraInputsManager, _super);\n function FreeCameraInputsManager(camera) {\n return _super.call(this, camera) || this;\n }\n FreeCameraInputsManager.prototype.addKeyboard = function () {\n this.add(new BABYLON.FreeCameraKeyboardMoveInput());\n return this;\n };\n FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {\n if (touchEnabled === void 0) { touchEnabled = true; }\n this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));\n return this;\n };\n FreeCameraInputsManager.prototype.addDeviceOrientation = function () {\n this.add(new BABYLON.FreeCameraDeviceOrientationInput());\n return this;\n };\n FreeCameraInputsManager.prototype.addTouch = function () {\n this.add(new BABYLON.FreeCameraTouchInput());\n return this;\n };\n FreeCameraInputsManager.prototype.addVirtualJoystick = function () {\n this.add(new BABYLON.FreeCameraVirtualJoystickInput());\n return this;\n };\n return FreeCameraInputsManager;\n }(BABYLON.CameraInputsManager));\n BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraInputsManager.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"FreeCamera\", function (name, scene) {\n // Forcing to use the Universal camera\n return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n var FreeCamera = /** @class */ (function (_super) {\n __extends(FreeCamera, _super);\n function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {\n if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }\n var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;\n _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);\n _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);\n _this.checkCollisions = false;\n _this.applyGravity = false;\n _this._needMoveForGravity = false;\n _this._oldPosition = BABYLON.Vector3.Zero();\n _this._diffPosition = BABYLON.Vector3.Zero();\n _this._newPosition = BABYLON.Vector3.Zero();\n // Collisions\n _this._collisionMask = -1;\n _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {\n if (collidedMesh === void 0) { collidedMesh = null; }\n //TODO move this to the collision coordinator!\n if (_this.getScene().workerCollisions)\n newPosition.multiplyInPlace(_this._collider._radius);\n var updatePosition = function (newPos) {\n _this._newPosition.copyFrom(newPos);\n _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);\n if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {\n _this.position.addInPlace(_this._diffPosition);\n if (_this.onCollide && collidedMesh) {\n _this.onCollide(collidedMesh);\n }\n }\n };\n updatePosition(newPosition);\n };\n _this.inputs = new BABYLON.FreeCameraInputsManager(_this);\n _this.inputs.addKeyboard().addMouse();\n return _this;\n }\n Object.defineProperty(FreeCamera.prototype, \"angularSensibility\", {\n //-- begin properties for backward compatibility for inputs\n /**\n * Gets the input sensibility for a mouse input. (default is 2000.0)\n * Higher values reduce sensitivity.\n */\n get: function () {\n var mouse = this.inputs.attached[\"mouse\"];\n if (mouse)\n return mouse.angularSensibility;\n return 0;\n },\n /**\n * Sets the input sensibility for a mouse input. (default is 2000.0)\n * Higher values reduce sensitivity.\n */\n set: function (value) {\n var mouse = this.inputs.attached[\"mouse\"];\n if (mouse)\n mouse.angularSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FreeCamera.prototype, \"keysUp\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysUp;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysUp = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FreeCamera.prototype, \"keysDown\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysDown;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysDown = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FreeCamera.prototype, \"keysLeft\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysLeft;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysLeft = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FreeCamera.prototype, \"keysRight\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysRight;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysRight = value;\n },\n enumerable: true,\n configurable: true\n });\n // Controls\n FreeCamera.prototype.attachControl = function (element, noPreventDefault) {\n this.inputs.attachElement(element, noPreventDefault);\n };\n FreeCamera.prototype.detachControl = function (element) {\n this.inputs.detachElement(element);\n this.cameraDirection = new BABYLON.Vector3(0, 0, 0);\n this.cameraRotation = new BABYLON.Vector2(0, 0);\n };\n Object.defineProperty(FreeCamera.prototype, \"collisionMask\", {\n get: function () {\n return this._collisionMask;\n },\n set: function (mask) {\n this._collisionMask = !isNaN(mask) ? mask : -1;\n },\n enumerable: true,\n configurable: true\n });\n FreeCamera.prototype._collideWithWorld = function (displacement) {\n var globalPosition;\n if (this.parent) {\n globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());\n }\n else {\n globalPosition = this.position;\n }\n globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);\n this._oldPosition.addInPlace(this.ellipsoidOffset);\n if (!this._collider) {\n this._collider = new BABYLON.Collider();\n }\n this._collider._radius = this.ellipsoid;\n this._collider.collisionMask = this._collisionMask;\n //no need for clone, as long as gravity is not on.\n var actualDisplacement = displacement;\n //add gravity to the direction to prevent the dual-collision checking\n if (this.applyGravity) {\n //this prevents mending with cameraDirection, a global variable of the free camera class.\n actualDisplacement = displacement.add(this.getScene().gravity);\n }\n this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);\n };\n FreeCamera.prototype._checkInputs = function () {\n if (!this._localDirection) {\n this._localDirection = BABYLON.Vector3.Zero();\n this._transformedDirection = BABYLON.Vector3.Zero();\n }\n this.inputs.checkInputs();\n _super.prototype._checkInputs.call(this);\n };\n FreeCamera.prototype._decideIfNeedsToMove = function () {\n return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;\n };\n FreeCamera.prototype._updatePosition = function () {\n if (this.checkCollisions && this.getScene().collisionsEnabled) {\n this._collideWithWorld(this.cameraDirection);\n }\n else {\n _super.prototype._updatePosition.call(this);\n }\n };\n FreeCamera.prototype.dispose = function () {\n this.inputs.clear();\n _super.prototype.dispose.call(this);\n };\n FreeCamera.prototype.getClassName = function () {\n return \"FreeCamera\";\n };\n __decorate([\n BABYLON.serializeAsVector3()\n ], FreeCamera.prototype, \"ellipsoid\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], FreeCamera.prototype, \"ellipsoidOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCamera.prototype, \"checkCollisions\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCamera.prototype, \"applyGravity\", void 0);\n return FreeCamera;\n }(BABYLON.TargetCamera));\n BABYLON.FreeCamera = FreeCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {\n function ArcRotateCameraKeyboardMoveInput() {\n this._keys = new Array();\n this.keysUp = [38];\n this.keysDown = [40];\n this.keysLeft = [37];\n this.keysRight = [39];\n this.keysReset = [220];\n this.panningSensibility = 50.0;\n this.zoomingSensibility = 25.0;\n this.useAltToZoom = true;\n }\n ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n if (this._onCanvasBlurObserver) {\n return;\n }\n this._scene = this.camera.getScene();\n this._engine = this._scene.getEngine();\n this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {\n _this._keys = [];\n });\n this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {\n var evt = info.event;\n if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {\n _this._ctrlPressed = evt.ctrlKey;\n _this._altPressed = evt.altKey;\n if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||\n _this.keysDown.indexOf(evt.keyCode) !== -1 ||\n _this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n _this.keysRight.indexOf(evt.keyCode) !== -1 ||\n _this.keysReset.indexOf(evt.keyCode) !== -1) {\n var index = _this._keys.indexOf(evt.keyCode);\n if (index === -1) {\n _this._keys.push(evt.keyCode);\n }\n if (evt.preventDefault) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n else {\n if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||\n _this.keysDown.indexOf(evt.keyCode) !== -1 ||\n _this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n _this.keysRight.indexOf(evt.keyCode) !== -1 ||\n _this.keysReset.indexOf(evt.keyCode) !== -1) {\n var index = _this._keys.indexOf(evt.keyCode);\n if (index >= 0) {\n _this._keys.splice(index, 1);\n }\n if (evt.preventDefault) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n });\n };\n ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {\n if (this._scene) {\n if (this._onKeyboardObserver) {\n this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);\n }\n if (this._onCanvasBlurObserver) {\n this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n this._onKeyboardObserver = null;\n this._onCanvasBlurObserver = null;\n }\n this._keys = [];\n };\n ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {\n if (this._onKeyboardObserver) {\n var camera = this.camera;\n for (var index = 0; index < this._keys.length; index++) {\n var keyCode = this._keys[index];\n if (this.keysLeft.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningX -= 1 / this.panningSensibility;\n }\n else {\n camera.inertialAlphaOffset -= 0.01;\n }\n }\n else if (this.keysUp.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningY += 1 / this.panningSensibility;\n }\n else if (this._altPressed && this.useAltToZoom) {\n camera.inertialRadiusOffset += 1 / this.zoomingSensibility;\n }\n else {\n camera.inertialBetaOffset -= 0.01;\n }\n }\n else if (this.keysRight.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningX += 1 / this.panningSensibility;\n }\n else {\n camera.inertialAlphaOffset += 0.01;\n }\n }\n else if (this.keysDown.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningY -= 1 / this.panningSensibility;\n }\n else if (this._altPressed && this.useAltToZoom) {\n camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;\n }\n else {\n camera.inertialBetaOffset += 0.01;\n }\n }\n else if (this.keysReset.indexOf(keyCode) !== -1) {\n camera.restoreState();\n }\n }\n }\n };\n ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {\n return \"ArcRotateCameraKeyboardMoveInput\";\n };\n ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {\n return \"keyboard\";\n };\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"keysUp\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"keysDown\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"keysLeft\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"keysRight\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"keysReset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"panningSensibility\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"zoomingSensibility\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"useAltToZoom\", void 0);\n return ArcRotateCameraKeyboardMoveInput;\n }());\n BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;\n BABYLON.CameraInputTypes[\"ArcRotateCameraKeyboardMoveInput\"] = ArcRotateCameraKeyboardMoveInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ArcRotateCameraMouseWheelInput = /** @class */ (function () {\n function ArcRotateCameraMouseWheelInput() {\n this.wheelPrecision = 3.0;\n /**\n * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.\n * It defines the percentage of current camera.radius to use as delta when wheel is used.\n */\n this.wheelDeltaPercentage = 0;\n }\n ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n this._wheel = function (p, s) {\n //sanity check - this should be a PointerWheel event.\n if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)\n return;\n var event = p.event;\n var delta = 0;\n if (event.wheelDelta) {\n if (_this.wheelDeltaPercentage) {\n var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;\n if (event.wheelDelta > 0) {\n delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);\n }\n else {\n delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);\n }\n }\n else {\n delta = event.wheelDelta / (_this.wheelPrecision * 40);\n }\n }\n else if (event.detail) {\n delta = -event.detail / _this.wheelPrecision;\n }\n if (delta)\n _this.camera.inertialRadiusOffset += delta;\n if (event.preventDefault) {\n if (!noPreventDefault) {\n event.preventDefault();\n }\n }\n };\n this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);\n };\n ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {\n if (this._observer && element) {\n this.camera.getScene().onPointerObservable.remove(this._observer);\n this._observer = null;\n this._wheel = null;\n }\n };\n ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {\n return \"ArcRotateCameraMouseWheelInput\";\n };\n ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {\n return \"mousewheel\";\n };\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraMouseWheelInput.prototype, \"wheelPrecision\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraMouseWheelInput.prototype, \"wheelDeltaPercentage\", void 0);\n return ArcRotateCameraMouseWheelInput;\n }());\n BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;\n BABYLON.CameraInputTypes[\"ArcRotateCameraMouseWheelInput\"] = ArcRotateCameraMouseWheelInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ArcRotateCameraPointersInput = /** @class */ (function () {\n function ArcRotateCameraPointersInput() {\n this.buttons = [0, 1, 2];\n this.angularSensibilityX = 1000.0;\n this.angularSensibilityY = 1000.0;\n this.pinchPrecision = 12.0;\n /**\n * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.\n * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.\n */\n this.pinchDeltaPercentage = 0;\n this.panningSensibility = 1000.0;\n this.multiTouchPanning = true;\n this.multiTouchPanAndZoom = true;\n this._isPanClick = false;\n this.pinchInwards = true;\n }\n ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n var engine = this.camera.getEngine();\n var cacheSoloPointer; // cache pointer object for better perf on camera rotation\n var pointA = null;\n var pointB = null;\n var previousPinchSquaredDistance = 0;\n var initialDistance = 0;\n var twoFingerActivityCount = 0;\n var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };\n this._pointerInput = function (p, s) {\n var evt = p.event;\n var isTouch = p.event.pointerType === \"touch\";\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {\n return;\n }\n var srcElement = (evt.srcElement || evt.target);\n if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {\n try {\n srcElement.setPointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error. Execution will continue.\n }\n // Manage panning with pan button click\n _this._isPanClick = evt.button === _this.camera._panningMouseButton;\n // manage pointers\n cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };\n if (pointA === null) {\n pointA = cacheSoloPointer;\n }\n else if (pointB === null) {\n pointB = cacheSoloPointer;\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n element.focus();\n }\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {\n _this.camera.restoreState();\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {\n try {\n srcElement.releasePointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error.\n }\n cacheSoloPointer = null;\n previousPinchSquaredDistance = 0;\n previousMultiTouchPanPosition.isPaning = false;\n previousMultiTouchPanPosition.isPinching = false;\n twoFingerActivityCount = 0;\n initialDistance = 0;\n if (!isTouch) {\n pointB = null; // Mouse and pen are mono pointer\n }\n //would be better to use pointers.remove(evt.pointerId) for multitouch gestures, \n //but emptying completly pointers collection is required to fix a bug on iPhone : \n //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers \n //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected\n if (engine._badOS) {\n pointA = pointB = null;\n }\n else {\n //only remove the impacted pointer in case of multitouch allowing on most \n //platforms switching from rotate to zoom and pan seamlessly.\n if (pointB && pointA && pointA.pointerId == evt.pointerId) {\n pointA = pointB;\n pointB = null;\n cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };\n }\n else if (pointA && pointB && pointB.pointerId == evt.pointerId) {\n pointB = null;\n cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };\n }\n else {\n pointA = pointB = null;\n }\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n // One button down\n if (pointA && pointB === null && cacheSoloPointer) {\n if (_this.panningSensibility !== 0 &&\n ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {\n _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;\n _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;\n }\n else {\n var offsetX = evt.clientX - cacheSoloPointer.x;\n var offsetY = evt.clientY - cacheSoloPointer.y;\n _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;\n _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;\n }\n cacheSoloPointer.x = evt.clientX;\n cacheSoloPointer.y = evt.clientY;\n }\n // Two buttons down: pinch/pan\n else if (pointA && pointB) {\n //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers\n var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;\n ed.x = evt.clientX;\n ed.y = evt.clientY;\n var direction = _this.pinchInwards ? 1 : -1;\n var distX = pointA.x - pointB.x;\n var distY = pointA.y - pointB.y;\n var pinchSquaredDistance = (distX * distX) + (distY * distY);\n var pinchDistance = Math.sqrt(pinchSquaredDistance);\n if (previousPinchSquaredDistance === 0) {\n initialDistance = pinchDistance;\n previousPinchSquaredDistance = pinchSquaredDistance;\n previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;\n previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;\n return;\n }\n if (_this.multiTouchPanAndZoom) {\n if (_this.pinchDeltaPercentage) {\n _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;\n }\n else {\n _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /\n (_this.pinchPrecision *\n ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *\n direction);\n }\n if (_this.panningSensibility !== 0) {\n var pointersCenterX = (pointA.x + pointB.x) / 2;\n var pointersCenterY = (pointA.y + pointB.y) / 2;\n var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;\n var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;\n previousMultiTouchPanPosition.x = pointersCenterX;\n previousMultiTouchPanPosition.y = pointersCenterY;\n _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);\n _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);\n }\n }\n else {\n twoFingerActivityCount++;\n if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {\n if (_this.pinchDeltaPercentage) {\n _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;\n }\n else {\n _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /\n (_this.pinchPrecision *\n ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *\n direction);\n }\n previousMultiTouchPanPosition.isPaning = false;\n previousMultiTouchPanPosition.isPinching = true;\n }\n else {\n if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {\n if (!previousMultiTouchPanPosition.isPaning) {\n previousMultiTouchPanPosition.isPaning = true;\n previousMultiTouchPanPosition.isPinching = false;\n previousMultiTouchPanPosition.x = ed.x;\n previousMultiTouchPanPosition.y = ed.y;\n return;\n }\n _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);\n _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);\n }\n }\n if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {\n previousMultiTouchPanPosition.x = ed.x;\n previousMultiTouchPanPosition.y = ed.y;\n }\n }\n previousPinchSquaredDistance = pinchSquaredDistance;\n }\n }\n };\n this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);\n this._onContextMenu = function (evt) {\n evt.preventDefault();\n };\n if (!this.camera._useCtrlForPanning) {\n element.addEventListener(\"contextmenu\", this._onContextMenu, false);\n }\n this._onLostFocus = function () {\n //this._keys = [];\n pointA = pointB = null;\n previousPinchSquaredDistance = 0;\n previousMultiTouchPanPosition.isPaning = false;\n previousMultiTouchPanPosition.isPinching = false;\n twoFingerActivityCount = 0;\n cacheSoloPointer = null;\n initialDistance = 0;\n };\n this._onMouseMove = function (evt) {\n if (!engine.isPointerLock) {\n return;\n }\n var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;\n var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;\n _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;\n _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n };\n this._onGestureStart = function (e) {\n if (window.MSGesture === undefined) {\n return;\n }\n if (!_this._MSGestureHandler) {\n _this._MSGestureHandler = new MSGesture();\n _this._MSGestureHandler.target = element;\n }\n _this._MSGestureHandler.addPointer(e.pointerId);\n };\n this._onGesture = function (e) {\n _this.camera.radius *= e.scale;\n if (e.preventDefault) {\n if (!noPreventDefault) {\n e.stopPropagation();\n e.preventDefault();\n }\n }\n };\n element.addEventListener(\"mousemove\", this._onMouseMove, false);\n element.addEventListener(\"MSPointerDown\", this._onGestureStart, false);\n element.addEventListener(\"MSGestureChange\", this._onGesture, false);\n BABYLON.Tools.RegisterTopRootEvents([\n { name: \"blur\", handler: this._onLostFocus }\n ]);\n };\n ArcRotateCameraPointersInput.prototype.detachControl = function (element) {\n if (this._onLostFocus) {\n BABYLON.Tools.UnregisterTopRootEvents([\n { name: \"blur\", handler: this._onLostFocus }\n ]);\n }\n if (element && this._observer) {\n this.camera.getScene().onPointerObservable.remove(this._observer);\n this._observer = null;\n if (this._onContextMenu) {\n element.removeEventListener(\"contextmenu\", this._onContextMenu);\n }\n if (this._onMouseMove) {\n element.removeEventListener(\"mousemove\", this._onMouseMove);\n }\n if (this._onGestureStart) {\n element.removeEventListener(\"MSPointerDown\", this._onGestureStart);\n }\n if (this._onGesture) {\n element.removeEventListener(\"MSGestureChange\", this._onGesture);\n }\n this._isPanClick = false;\n this.pinchInwards = true;\n this._onMouseMove = null;\n this._onGestureStart = null;\n this._onGesture = null;\n this._MSGestureHandler = null;\n this._onLostFocus = null;\n this._onContextMenu = null;\n }\n };\n ArcRotateCameraPointersInput.prototype.getClassName = function () {\n return \"ArcRotateCameraPointersInput\";\n };\n ArcRotateCameraPointersInput.prototype.getSimpleName = function () {\n return \"pointers\";\n };\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"buttons\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"angularSensibilityX\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"angularSensibilityY\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"pinchPrecision\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"pinchDeltaPercentage\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"panningSensibility\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"multiTouchPanning\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"multiTouchPanAndZoom\", void 0);\n return ArcRotateCameraPointersInput;\n }());\n BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;\n BABYLON.CameraInputTypes[\"ArcRotateCameraPointersInput\"] = ArcRotateCameraPointersInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ArcRotateCameraInputsManager = /** @class */ (function (_super) {\n __extends(ArcRotateCameraInputsManager, _super);\n function ArcRotateCameraInputsManager(camera) {\n return _super.call(this, camera) || this;\n }\n ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {\n this.add(new BABYLON.ArcRotateCameraMouseWheelInput());\n return this;\n };\n ArcRotateCameraInputsManager.prototype.addPointers = function () {\n this.add(new BABYLON.ArcRotateCameraPointersInput());\n return this;\n };\n ArcRotateCameraInputsManager.prototype.addKeyboard = function () {\n this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());\n return this;\n };\n ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {\n this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());\n return this;\n };\n return ArcRotateCameraInputsManager;\n }(BABYLON.CameraInputsManager));\n BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"ArcRotateCamera\", function (name, scene) {\n return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };\n });\n var ArcRotateCamera = /** @class */ (function (_super) {\n __extends(ArcRotateCamera, _super);\n function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {\n if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }\n var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;\n _this.inertialAlphaOffset = 0;\n _this.inertialBetaOffset = 0;\n _this.inertialRadiusOffset = 0;\n _this.lowerAlphaLimit = null;\n _this.upperAlphaLimit = null;\n _this.lowerBetaLimit = 0.01;\n _this.upperBetaLimit = Math.PI;\n _this.lowerRadiusLimit = null;\n _this.upperRadiusLimit = null;\n _this.inertialPanningX = 0;\n _this.inertialPanningY = 0;\n _this.pinchToPanMaxDistance = 20;\n _this.panningDistanceLimit = null;\n _this.panningOriginTarget = BABYLON.Vector3.Zero();\n _this.panningInertia = 0.9;\n //-- end properties for backward compatibility for inputs\n _this.zoomOnFactor = 1;\n _this.targetScreenOffset = BABYLON.Vector2.Zero();\n _this.allowUpsideDown = true;\n _this._viewMatrix = new BABYLON.Matrix();\n // Panning\n _this.panningAxis = new BABYLON.Vector3(1, 1, 0);\n _this.onMeshTargetChangedObservable = new BABYLON.Observable();\n _this.checkCollisions = false;\n _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);\n _this._previousPosition = BABYLON.Vector3.Zero();\n _this._collisionVelocity = BABYLON.Vector3.Zero();\n _this._newPosition = BABYLON.Vector3.Zero();\n _this._computationVector = BABYLON.Vector3.Zero();\n _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {\n if (collidedMesh === void 0) { collidedMesh = null; }\n if (_this.getScene().workerCollisions && _this.checkCollisions) {\n newPosition.multiplyInPlace(_this._collider._radius);\n }\n if (!collidedMesh) {\n _this._previousPosition.copyFrom(_this.position);\n }\n else {\n _this.setPosition(newPosition);\n if (_this.onCollide) {\n _this.onCollide(collidedMesh);\n }\n }\n // Recompute because of constraints\n var cosa = Math.cos(_this.alpha);\n var sina = Math.sin(_this.alpha);\n var cosb = Math.cos(_this.beta);\n var sinb = Math.sin(_this.beta);\n if (sinb === 0) {\n sinb = 0.0001;\n }\n var target = _this._getTargetPosition();\n _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);\n target.addToRef(_this._computationVector, _this._newPosition);\n _this.position.copyFrom(_this._newPosition);\n var up = _this.upVector;\n if (_this.allowUpsideDown && _this.beta < 0) {\n up = up.clone();\n up = up.negate();\n }\n _this._computeViewMatrix(_this.position, target, up);\n _this._viewMatrix.m[12] += _this.targetScreenOffset.x;\n _this._viewMatrix.m[13] += _this.targetScreenOffset.y;\n _this._collisionTriggered = false;\n };\n _this._target = BABYLON.Vector3.Zero();\n if (target) {\n _this.setTarget(target);\n }\n _this.alpha = alpha;\n _this.beta = beta;\n _this.radius = radius;\n _this.getViewMatrix();\n _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);\n _this.inputs.addKeyboard().addMouseWheel().addPointers();\n return _this;\n }\n Object.defineProperty(ArcRotateCamera.prototype, \"target\", {\n get: function () {\n return this._target;\n },\n set: function (value) {\n this.setTarget(value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"angularSensibilityX\", {\n //-- begin properties for backward compatibility for inputs\n get: function () {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers)\n return pointers.angularSensibilityX;\n return 0;\n },\n set: function (value) {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.angularSensibilityX = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"angularSensibilityY\", {\n get: function () {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers)\n return pointers.angularSensibilityY;\n return 0;\n },\n set: function (value) {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.angularSensibilityY = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"pinchPrecision\", {\n get: function () {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers)\n return pointers.pinchPrecision;\n return 0;\n },\n set: function (value) {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.pinchPrecision = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"pinchDeltaPercentage\", {\n get: function () {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers)\n return pointers.pinchDeltaPercentage;\n return 0;\n },\n set: function (value) {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.pinchDeltaPercentage = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"panningSensibility\", {\n get: function () {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers)\n return pointers.panningSensibility;\n return 0;\n },\n set: function (value) {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.panningSensibility = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"keysUp\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysUp;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysUp = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"keysDown\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysDown;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysDown = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"keysLeft\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysLeft;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysLeft = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"keysRight\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysRight;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysRight = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"wheelPrecision\", {\n get: function () {\n var mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel)\n return mousewheel.wheelPrecision;\n return 0;\n },\n set: function (value) {\n var mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel)\n mousewheel.wheelPrecision = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"wheelDeltaPercentage\", {\n get: function () {\n var mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel)\n return mousewheel.wheelDeltaPercentage;\n return 0;\n },\n set: function (value) {\n var mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel)\n mousewheel.wheelDeltaPercentage = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"bouncingBehavior\", {\n get: function () {\n return this._bouncingBehavior;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"useBouncingBehavior\", {\n get: function () {\n return this._bouncingBehavior != null;\n },\n set: function (value) {\n if (value === this.useBouncingBehavior) {\n return;\n }\n if (value) {\n this._bouncingBehavior = new BABYLON.BouncingBehavior();\n this.addBehavior(this._bouncingBehavior);\n }\n else if (this._bouncingBehavior) {\n this.removeBehavior(this._bouncingBehavior);\n this._bouncingBehavior = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"framingBehavior\", {\n get: function () {\n return this._framingBehavior;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"useFramingBehavior\", {\n get: function () {\n return this._framingBehavior != null;\n },\n set: function (value) {\n if (value === this.useFramingBehavior) {\n return;\n }\n if (value) {\n this._framingBehavior = new BABYLON.FramingBehavior();\n this.addBehavior(this._framingBehavior);\n }\n else if (this._framingBehavior) {\n this.removeBehavior(this._framingBehavior);\n this._framingBehavior = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"autoRotationBehavior\", {\n get: function () {\n return this._autoRotationBehavior;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"useAutoRotationBehavior\", {\n get: function () {\n return this._autoRotationBehavior != null;\n },\n set: function (value) {\n if (value === this.useAutoRotationBehavior) {\n return;\n }\n if (value) {\n this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();\n this.addBehavior(this._autoRotationBehavior);\n }\n else if (this._autoRotationBehavior) {\n this.removeBehavior(this._autoRotationBehavior);\n this._autoRotationBehavior = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n // Cache\n ArcRotateCamera.prototype._initCache = function () {\n _super.prototype._initCache.call(this);\n this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.alpha = undefined;\n this._cache.beta = undefined;\n this._cache.radius = undefined;\n this._cache.targetScreenOffset = BABYLON.Vector2.Zero();\n };\n ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {\n if (!ignoreParentClass) {\n _super.prototype._updateCache.call(this);\n }\n this._cache._target.copyFrom(this._getTargetPosition());\n this._cache.alpha = this.alpha;\n this._cache.beta = this.beta;\n this._cache.radius = this.radius;\n this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);\n };\n ArcRotateCamera.prototype._getTargetPosition = function () {\n if (this._targetHost && this._targetHost.getAbsolutePosition) {\n var pos = this._targetHost.getAbsolutePosition();\n if (this._targetBoundingCenter) {\n pos.addToRef(this._targetBoundingCenter, this._target);\n }\n else {\n this._target.copyFrom(pos);\n }\n }\n var lockedTargetPosition = this._getLockedTargetPosition();\n if (lockedTargetPosition) {\n return lockedTargetPosition;\n }\n return this._target;\n };\n ArcRotateCamera.prototype.storeState = function () {\n this._storedAlpha = this.alpha;\n this._storedBeta = this.beta;\n this._storedRadius = this.radius;\n this._storedTarget = this._getTargetPosition().clone();\n return _super.prototype.storeState.call(this);\n };\n /**\n * Restored camera state. You must call storeState() first\n */\n ArcRotateCamera.prototype._restoreStateValues = function () {\n if (!_super.prototype._restoreStateValues.call(this)) {\n return false;\n }\n this.alpha = this._storedAlpha;\n this.beta = this._storedBeta;\n this.radius = this._storedRadius;\n this.setTarget(this._storedTarget.clone());\n this.inertialAlphaOffset = 0;\n this.inertialBetaOffset = 0;\n this.inertialRadiusOffset = 0;\n this.inertialPanningX = 0;\n this.inertialPanningY = 0;\n return true;\n };\n // Synchronized\n ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {\n if (!_super.prototype._isSynchronizedViewMatrix.call(this))\n return false;\n return this._cache._target.equals(this._getTargetPosition())\n && this._cache.alpha === this.alpha\n && this._cache.beta === this.beta\n && this._cache.radius === this.radius\n && this._cache.targetScreenOffset.equals(this.targetScreenOffset);\n };\n // Methods\n ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {\n var _this = this;\n if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }\n if (panningMouseButton === void 0) { panningMouseButton = 2; }\n this._useCtrlForPanning = useCtrlForPanning;\n this._panningMouseButton = panningMouseButton;\n this.inputs.attachElement(element, noPreventDefault);\n this._reset = function () {\n _this.inertialAlphaOffset = 0;\n _this.inertialBetaOffset = 0;\n _this.inertialRadiusOffset = 0;\n _this.inertialPanningX = 0;\n _this.inertialPanningY = 0;\n };\n };\n ArcRotateCamera.prototype.detachControl = function (element) {\n this.inputs.detachElement(element);\n if (this._reset) {\n this._reset();\n }\n };\n ArcRotateCamera.prototype._checkInputs = function () {\n //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.\n if (this._collisionTriggered) {\n return;\n }\n this.inputs.checkInputs();\n // Inertia\n if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {\n var inertialAlphaOffset = this.inertialAlphaOffset;\n if (this.beta <= 0)\n inertialAlphaOffset *= -1;\n if (this.getScene().useRightHandedSystem)\n inertialAlphaOffset *= -1;\n if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)\n inertialAlphaOffset *= -1;\n this.alpha += inertialAlphaOffset;\n this.beta += this.inertialBetaOffset;\n this.radius -= this.inertialRadiusOffset;\n this.inertialAlphaOffset *= this.inertia;\n this.inertialBetaOffset *= this.inertia;\n this.inertialRadiusOffset *= this.inertia;\n if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)\n this.inertialAlphaOffset = 0;\n if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)\n this.inertialBetaOffset = 0;\n if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)\n this.inertialRadiusOffset = 0;\n }\n // Panning inertia\n if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {\n if (!this._localDirection) {\n this._localDirection = BABYLON.Vector3.Zero();\n this._transformedDirection = BABYLON.Vector3.Zero();\n }\n this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);\n this._localDirection.multiplyInPlace(this.panningAxis);\n this._viewMatrix.invertToRef(this._cameraTransformMatrix);\n BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);\n //Eliminate y if map panning is enabled (panningAxis == 1,0,1)\n if (!this.panningAxis.y) {\n this._transformedDirection.y = 0;\n }\n if (!this._targetHost) {\n if (this.panningDistanceLimit) {\n this._transformedDirection.addInPlace(this._target);\n var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);\n if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {\n this._target.copyFrom(this._transformedDirection);\n }\n }\n else {\n this._target.addInPlace(this._transformedDirection);\n }\n }\n this.inertialPanningX *= this.panningInertia;\n this.inertialPanningY *= this.panningInertia;\n if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)\n this.inertialPanningX = 0;\n if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)\n this.inertialPanningY = 0;\n }\n // Limits\n this._checkLimits();\n _super.prototype._checkInputs.call(this);\n };\n ArcRotateCamera.prototype._checkLimits = function () {\n if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {\n if (this.allowUpsideDown && this.beta > Math.PI) {\n this.beta = this.beta - (2 * Math.PI);\n }\n }\n else {\n if (this.beta < this.lowerBetaLimit) {\n this.beta = this.lowerBetaLimit;\n }\n }\n if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {\n if (this.allowUpsideDown && this.beta < -Math.PI) {\n this.beta = this.beta + (2 * Math.PI);\n }\n }\n else {\n if (this.beta > this.upperBetaLimit) {\n this.beta = this.upperBetaLimit;\n }\n }\n if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {\n this.alpha = this.lowerAlphaLimit;\n }\n if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {\n this.alpha = this.upperAlphaLimit;\n }\n if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {\n this.radius = this.lowerRadiusLimit;\n }\n if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {\n this.radius = this.upperRadiusLimit;\n }\n };\n ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {\n this.position.subtractToRef(this._getTargetPosition(), this._computationVector);\n this.radius = this._computationVector.length();\n if (this.radius === 0) {\n this.radius = 0.0001; // Just to avoid division by zero\n }\n // Alpha\n this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));\n if (this._computationVector.z < 0) {\n this.alpha = 2 * Math.PI - this.alpha;\n }\n // Beta\n this.beta = Math.acos(this._computationVector.y / this.radius);\n this._checkLimits();\n };\n ArcRotateCamera.prototype.setPosition = function (position) {\n if (this.position.equals(position)) {\n return;\n }\n this.position.copyFrom(position);\n this.rebuildAnglesAndRadius();\n };\n ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {\n if (toBoundingCenter === void 0) { toBoundingCenter = false; }\n if (allowSamePosition === void 0) { allowSamePosition = false; }\n if (target.getBoundingInfo) {\n if (toBoundingCenter) {\n this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();\n }\n else {\n this._targetBoundingCenter = null;\n }\n this._targetHost = target;\n this._target = this._getTargetPosition();\n this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);\n }\n else {\n var newTarget = target;\n var currentTarget = this._getTargetPosition();\n if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {\n return;\n }\n this._targetHost = null;\n this._target = newTarget;\n this._targetBoundingCenter = null;\n this.onMeshTargetChangedObservable.notifyObservers(null);\n }\n this.rebuildAnglesAndRadius();\n };\n ArcRotateCamera.prototype._getViewMatrix = function () {\n // Compute\n var cosa = Math.cos(this.alpha);\n var sina = Math.sin(this.alpha);\n var cosb = Math.cos(this.beta);\n var sinb = Math.sin(this.beta);\n if (sinb === 0) {\n sinb = 0.0001;\n }\n var target = this._getTargetPosition();\n this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);\n target.addToRef(this._computationVector, this._newPosition);\n if (this.getScene().collisionsEnabled && this.checkCollisions) {\n if (!this._collider) {\n this._collider = new BABYLON.Collider();\n }\n this._collider._radius = this.collisionRadius;\n this._newPosition.subtractToRef(this.position, this._collisionVelocity);\n this._collisionTriggered = true;\n this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);\n }\n else {\n this.position.copyFrom(this._newPosition);\n var up = this.upVector;\n if (this.allowUpsideDown && sinb < 0) {\n up = up.clone();\n up = up.negate();\n }\n this._computeViewMatrix(this.position, target, up);\n this._viewMatrix.m[12] += this.targetScreenOffset.x;\n this._viewMatrix.m[13] += this.targetScreenOffset.y;\n }\n this._currentTarget = target;\n return this._viewMatrix;\n };\n ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {\n if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }\n meshes = meshes || this.getScene().meshes;\n var minMaxVector = BABYLON.Mesh.MinMax(meshes);\n var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);\n this.radius = distance * this.zoomOnFactor;\n this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);\n };\n ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {\n if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }\n var meshesOrMinMaxVector;\n var distance;\n if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes\n var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;\n meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);\n distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);\n }\n else { //minMaxVector and distance\n var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;\n meshesOrMinMaxVector = minMaxVectorAndDistance;\n distance = minMaxVectorAndDistance.distance;\n }\n this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);\n if (!doNotUpdateMaxZ) {\n this.maxZ = distance * 2;\n }\n };\n /**\n * @override\n * Override Camera.createRigCamera\n */\n ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {\n var alphaShift = 0;\n switch (this.cameraRigMode) {\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n case BABYLON.Camera.RIG_MODE_VR:\n alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);\n break;\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);\n break;\n }\n var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());\n rigCam._cameraRigParams = {};\n return rigCam;\n };\n /**\n * @override\n * Override Camera._updateRigCameras\n */\n ArcRotateCamera.prototype._updateRigCameras = function () {\n var camLeft = this._rigCameras[0];\n var camRight = this._rigCameras[1];\n camLeft.beta = camRight.beta = this.beta;\n camLeft.radius = camRight.radius = this.radius;\n switch (this.cameraRigMode) {\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n case BABYLON.Camera.RIG_MODE_VR:\n camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;\n camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;\n break;\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;\n camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;\n break;\n }\n _super.prototype._updateRigCameras.call(this);\n };\n ArcRotateCamera.prototype.dispose = function () {\n this.inputs.clear();\n _super.prototype.dispose.call(this);\n };\n ArcRotateCamera.prototype.getClassName = function () {\n return \"ArcRotateCamera\";\n };\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"alpha\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"beta\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"radius\", void 0);\n __decorate([\n BABYLON.serializeAsVector3(\"target\")\n ], ArcRotateCamera.prototype, \"_target\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"inertialAlphaOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"inertialBetaOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"inertialRadiusOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"lowerAlphaLimit\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"upperAlphaLimit\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"lowerBetaLimit\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"upperBetaLimit\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"lowerRadiusLimit\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"upperRadiusLimit\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"inertialPanningX\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"inertialPanningY\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"pinchToPanMaxDistance\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"panningDistanceLimit\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], ArcRotateCamera.prototype, \"panningOriginTarget\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"panningInertia\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"zoomOnFactor\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"allowUpsideDown\", void 0);\n return ArcRotateCamera;\n }(BABYLON.TargetCamera));\n BABYLON.ArcRotateCamera = ArcRotateCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCamera.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"Light_Type_3\", function (name, scene) {\n return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };\n });\n /**\n * The HemisphericLight simulates the ambient environment light,\n * so the passed direction is the light reflection direction, not the incoming direction.\n */\n var HemisphericLight = /** @class */ (function (_super) {\n __extends(HemisphericLight, _super);\n /**\n * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).\n * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.\n * The HemisphericLight can't cast shadows.\n * Documentation : http://doc.babylonjs.com/tutorials/lights\n * @param name The friendly name of the light\n * @param direction The direction of the light reflection\n * @param scene The scene the light belongs to\n */\n function HemisphericLight(name, direction, scene) {\n var _this = _super.call(this, name, scene) || this;\n /**\n * The groundColor is the light in the opposite direction to the one specified during creation.\n * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.\n */\n _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);\n _this.direction = direction || BABYLON.Vector3.Up();\n return _this;\n }\n HemisphericLight.prototype._buildUniformLayout = function () {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 3);\n this._uniformBuffer.addUniform(\"vLightGround\", 3);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n };\n /**\n * Returns the string \"HemisphericLight\".\n * @return The class name\n */\n HemisphericLight.prototype.getClassName = function () {\n return \"HemisphericLight\";\n };\n /**\n * Sets the HemisphericLight direction towards the passed target (Vector3).\n * Returns the updated direction.\n * @param target The target the direction should point to\n * @return The computed direction\n */\n HemisphericLight.prototype.setDirectionToTarget = function (target) {\n this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));\n return this.direction;\n };\n /**\n * Returns the shadow generator associated to the light.\n * @returns Always null for hemispheric lights because it does not support shadows.\n */\n HemisphericLight.prototype.getShadowGenerator = function () {\n return null;\n };\n /**\n * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The hemispheric light\n */\n HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {\n var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);\n this._uniformBuffer.updateFloat4(\"vLightData\", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);\n this._uniformBuffer.updateColor3(\"vLightGround\", this.groundColor.scale(this.intensity), lightIndex);\n return this;\n };\n /**\n * @hidden internal use only.\n */\n HemisphericLight.prototype._getWorldMatrix = function () {\n if (!this._worldMatrix) {\n this._worldMatrix = BABYLON.Matrix.Identity();\n }\n return this._worldMatrix;\n };\n /**\n * Returns the integer 3.\n * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n HemisphericLight.prototype.getTypeID = function () {\n return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;\n };\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {\n defines[\"HEMILIGHT\" + lightIndex] = true;\n };\n __decorate([\n BABYLON.serializeAsColor3()\n ], HemisphericLight.prototype, \"groundColor\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], HemisphericLight.prototype, \"direction\", void 0);\n return HemisphericLight;\n }(BABYLON.Light));\n BABYLON.HemisphericLight = HemisphericLight;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.hemisphericLight.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Base implementation IShadowLight\n * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.\n */\n var ShadowLight = /** @class */ (function (_super) {\n __extends(ShadowLight, _super);\n function ShadowLight() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this._needProjectionMatrixCompute = true;\n return _this;\n }\n ShadowLight.prototype._setPosition = function (value) {\n this._position = value;\n };\n Object.defineProperty(ShadowLight.prototype, \"position\", {\n /**\n * Sets the position the shadow will be casted from. Also use as the light position for both\n * point and spot lights.\n */\n get: function () {\n return this._position;\n },\n /**\n * Sets the position the shadow will be casted from. Also use as the light position for both\n * point and spot lights.\n */\n set: function (value) {\n this._setPosition(value);\n },\n enumerable: true,\n configurable: true\n });\n ShadowLight.prototype._setDirection = function (value) {\n this._direction = value;\n };\n Object.defineProperty(ShadowLight.prototype, \"direction\", {\n /**\n * In 2d mode (needCube being false), gets the direction used to cast the shadow.\n * Also use as the light direction on spot and directional lights.\n */\n get: function () {\n return this._direction;\n },\n /**\n * In 2d mode (needCube being false), sets the direction used to cast the shadow.\n * Also use as the light direction on spot and directional lights.\n */\n set: function (value) {\n this._setDirection(value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowLight.prototype, \"shadowMinZ\", {\n /**\n * Gets the shadow projection clipping minimum z value.\n */\n get: function () {\n return this._shadowMinZ;\n },\n /**\n * Sets the shadow projection clipping minimum z value.\n */\n set: function (value) {\n this._shadowMinZ = value;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowLight.prototype, \"shadowMaxZ\", {\n /**\n * Sets the shadow projection clipping maximum z value.\n */\n get: function () {\n return this._shadowMaxZ;\n },\n /**\n * Gets the shadow projection clipping maximum z value.\n */\n set: function (value) {\n this._shadowMaxZ = value;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light\n * @returns true if the information has been computed, false if it does not need to (no parenting)\n */\n ShadowLight.prototype.computeTransformedInformation = function () {\n if (this.parent && this.parent.getWorldMatrix) {\n if (!this.transformedPosition) {\n this.transformedPosition = BABYLON.Vector3.Zero();\n }\n BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);\n // In case the direction is present.\n if (this.direction) {\n if (!this.transformedDirection) {\n this.transformedDirection = BABYLON.Vector3.Zero();\n }\n BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);\n }\n return true;\n }\n return false;\n };\n /**\n * Return the depth scale used for the shadow map.\n * @returns the depth scale.\n */\n ShadowLight.prototype.getDepthScale = function () {\n return 50.0;\n };\n /**\n * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.\n * @param faceIndex The index of the face we are computed the direction to generate shadow\n * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true\n */\n ShadowLight.prototype.getShadowDirection = function (faceIndex) {\n return this.transformedDirection ? this.transformedDirection : this.direction;\n };\n /**\n * Returns the ShadowLight absolute position in the World.\n * @returns the position vector in world space\n */\n ShadowLight.prototype.getAbsolutePosition = function () {\n return this.transformedPosition ? this.transformedPosition : this.position;\n };\n /**\n * Sets the ShadowLight direction toward the passed target.\n * @param target The point tot target in local space\n * @returns the updated ShadowLight direction\n */\n ShadowLight.prototype.setDirectionToTarget = function (target) {\n this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));\n return this.direction;\n };\n /**\n * Returns the light rotation in euler definition.\n * @returns the x y z rotation in local space.\n */\n ShadowLight.prototype.getRotation = function () {\n this.direction.normalize();\n var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);\n var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);\n return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);\n };\n /**\n * Returns whether or not the shadow generation require a cube texture or a 2d texture.\n * @returns true if a cube texture needs to be use\n */\n ShadowLight.prototype.needCube = function () {\n return false;\n };\n /**\n * Detects if the projection matrix requires to be recomputed this frame.\n * @returns true if it requires to be recomputed otherwise, false.\n */\n ShadowLight.prototype.needProjectionMatrixCompute = function () {\n return this._needProjectionMatrixCompute;\n };\n /**\n * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.\n */\n ShadowLight.prototype.forceProjectionMatrixCompute = function () {\n this._needProjectionMatrixCompute = true;\n };\n /**\n * Get the world matrix of the sahdow lights.\n * @hidden Internal Use Only\n */\n ShadowLight.prototype._getWorldMatrix = function () {\n if (!this._worldMatrix) {\n this._worldMatrix = BABYLON.Matrix.Identity();\n }\n BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);\n return this._worldMatrix;\n };\n /**\n * Gets the minZ used for shadow according to both the scene and the light.\n * @param activeCamera The camera we are returning the min for\n * @returns the depth min z\n */\n ShadowLight.prototype.getDepthMinZ = function (activeCamera) {\n return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;\n };\n /**\n * Gets the maxZ used for shadow according to both the scene and the light.\n * @param activeCamera The camera we are returning the max for\n * @returns the depth max z\n */\n ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {\n return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;\n };\n /**\n * Sets the shadow projection matrix in parameter to the generated projection matrix.\n * @param matrix The materix to updated with the projection information\n * @param viewMatrix The transform matrix of the light\n * @param renderList The list of mesh to render in the map\n * @returns The current light\n */\n ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {\n if (this.customProjectionMatrixBuilder) {\n this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);\n }\n else {\n this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);\n }\n return this;\n };\n __decorate([\n BABYLON.serializeAsVector3()\n ], ShadowLight.prototype, \"position\", null);\n __decorate([\n BABYLON.serializeAsVector3()\n ], ShadowLight.prototype, \"direction\", null);\n __decorate([\n BABYLON.serialize()\n ], ShadowLight.prototype, \"shadowMinZ\", null);\n __decorate([\n BABYLON.serialize()\n ], ShadowLight.prototype, \"shadowMaxZ\", null);\n return ShadowLight;\n }(BABYLON.Light));\n BABYLON.ShadowLight = ShadowLight;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.shadowLight.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"Light_Type_0\", function (name, scene) {\n return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };\n });\n /**\n * A point light is a light defined by an unique point in world space.\n * The light is emitted in every direction from this point.\n * A good example of a point light is a standard light bulb.\n * Documentation: https://doc.babylonjs.com/babylon101/lights\n */\n var PointLight = /** @class */ (function (_super) {\n __extends(PointLight, _super);\n /**\n * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.\n * A PointLight emits the light in every direction.\n * It can cast shadows.\n * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :\n * ```javascript\n * var pointLight = new BABYLON.PointLight(\"pl\", camera.position, scene);\n * ```\n * Documentation : http://doc.babylonjs.com/tutorials/lights\n * @param name The light friendly name\n * @param position The position of the point light in the scene\n * @param scene The scene the lights belongs to\n */\n function PointLight(name, position, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._shadowAngle = Math.PI / 2;\n _this.position = position;\n return _this;\n }\n Object.defineProperty(PointLight.prototype, \"shadowAngle\", {\n /**\n * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n * This specifies what angle the shadow will use to be created.\n *\n * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.\n */\n get: function () {\n return this._shadowAngle;\n },\n /**\n * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n * This specifies what angle the shadow will use to be created.\n *\n * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.\n */\n set: function (value) {\n this._shadowAngle = value;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointLight.prototype, \"direction\", {\n /**\n * Gets the direction if it has been set.\n * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n */\n get: function () {\n return this._direction;\n },\n /**\n * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n */\n set: function (value) {\n var previousNeedCube = this.needCube();\n this._direction = value;\n if (this.needCube() !== previousNeedCube && this._shadowGenerator) {\n this._shadowGenerator.recreateShadowMap();\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"PointLight\"\n * @returns the class name\n */\n PointLight.prototype.getClassName = function () {\n return \"PointLight\";\n };\n /**\n * Returns the integer 0.\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n PointLight.prototype.getTypeID = function () {\n return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;\n };\n /**\n * Specifies wether or not the shadowmap should be a cube texture.\n * @returns true if the shadowmap needs to be a cube texture.\n */\n PointLight.prototype.needCube = function () {\n return !this.direction;\n };\n /**\n * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).\n * @param faceIndex The index of the face we are computed the direction to generate shadow\n * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true\n */\n PointLight.prototype.getShadowDirection = function (faceIndex) {\n if (this.direction) {\n return _super.prototype.getShadowDirection.call(this, faceIndex);\n }\n else {\n switch (faceIndex) {\n case 0:\n return new BABYLON.Vector3(1.0, 0.0, 0.0);\n case 1:\n return new BABYLON.Vector3(-1.0, 0.0, 0.0);\n case 2:\n return new BABYLON.Vector3(0.0, -1.0, 0.0);\n case 3:\n return new BABYLON.Vector3(0.0, 1.0, 0.0);\n case 4:\n return new BABYLON.Vector3(0.0, 0.0, 1.0);\n case 5:\n return new BABYLON.Vector3(0.0, 0.0, -1.0);\n }\n }\n return BABYLON.Vector3.Zero();\n };\n /**\n * Sets the passed matrix \"matrix\" as a left-handed perspective projection matrix with the following settings :\n * - fov = PI / 2\n * - aspect ratio : 1.0\n * - z-near and far equal to the active camera minZ and maxZ.\n * Returns the PointLight.\n */\n PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {\n var activeCamera = this.getScene().activeCamera;\n if (!activeCamera) {\n return;\n }\n BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);\n };\n PointLight.prototype._buildUniformLayout = function () {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 3);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n };\n /**\n * Sets the passed Effect \"effect\" with the PointLight transformed position (or position, if none) and passed name (string).\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The point light\n */\n PointLight.prototype.transferToEffect = function (effect, lightIndex) {\n if (this.computeTransformedInformation()) {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);\n return this;\n }\n this._uniformBuffer.updateFloat4(\"vLightData\", this.position.x, this.position.y, this.position.z, 0, lightIndex);\n return this;\n };\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {\n defines[\"POINTLIGHT\" + lightIndex] = true;\n };\n __decorate([\n BABYLON.serialize()\n ], PointLight.prototype, \"shadowAngle\", null);\n return PointLight;\n }(BABYLON.ShadowLight));\n BABYLON.PointLight = PointLight;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pointLight.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"Light_Type_1\", function (name, scene) {\n return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };\n });\n /**\n * A directional light is defined by a direction (what a surprise!).\n * The light is emitted from everywhere in the specified direction, and has an infinite range.\n * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.\n * Documentation: https://doc.babylonjs.com/babylon101/lights\n */\n var DirectionalLight = /** @class */ (function (_super) {\n __extends(DirectionalLight, _super);\n /**\n * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).\n * The directional light is emitted from everywhere in the given direction.\n * It can cast shawdows.\n * Documentation : http://doc.babylonjs.com/tutorials/lights\n * @param name The friendly name of the light\n * @param direction The direction of the light\n * @param scene The scene the light belongs to\n */\n function DirectionalLight(name, direction, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._shadowFrustumSize = 0;\n _this._shadowOrthoScale = 0.1;\n /**\n * Automatically compute the projection matrix to best fit (including all the casters)\n * on each frame.\n */\n _this.autoUpdateExtends = true;\n // Cache\n _this._orthoLeft = Number.MAX_VALUE;\n _this._orthoRight = Number.MIN_VALUE;\n _this._orthoTop = Number.MIN_VALUE;\n _this._orthoBottom = Number.MAX_VALUE;\n _this.position = direction.scale(-1.0);\n _this.direction = direction;\n return _this;\n }\n Object.defineProperty(DirectionalLight.prototype, \"shadowFrustumSize\", {\n /**\n * Fix frustum size for the shadow generation. This is disabled if the value is 0.\n */\n get: function () {\n return this._shadowFrustumSize;\n },\n /**\n * Specifies a fix frustum size for the shadow generation.\n */\n set: function (value) {\n this._shadowFrustumSize = value;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DirectionalLight.prototype, \"shadowOrthoScale\", {\n /**\n * Gets the shadow projection scale against the optimal computed one.\n * 0.1 by default which means that the projection window is increase by 10% from the optimal size.\n * This does not impact in fixed frustum size (shadowFrustumSize being set)\n */\n get: function () {\n return this._shadowOrthoScale;\n },\n /**\n * Sets the shadow projection scale against the optimal computed one.\n * 0.1 by default which means that the projection window is increase by 10% from the optimal size.\n * This does not impact in fixed frustum size (shadowFrustumSize being set)\n */\n set: function (value) {\n this._shadowOrthoScale = value;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"DirectionalLight\".\n * @return The class name\n */\n DirectionalLight.prototype.getClassName = function () {\n return \"DirectionalLight\";\n };\n /**\n * Returns the integer 1.\n * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n DirectionalLight.prototype.getTypeID = function () {\n return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;\n };\n /**\n * Sets the passed matrix \"matrix\" as projection matrix for the shadows cast by the light according to the passed view matrix.\n * Returns the DirectionalLight Shadow projection matrix.\n */\n DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {\n if (this.shadowFrustumSize > 0) {\n this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);\n }\n else {\n this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);\n }\n };\n /**\n * Sets the passed matrix \"matrix\" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.\n * Returns the DirectionalLight Shadow projection matrix.\n */\n DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {\n var activeCamera = this.getScene().activeCamera;\n if (!activeCamera) {\n return;\n }\n BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);\n };\n /**\n * Sets the passed matrix \"matrix\" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.\n * Returns the DirectionalLight Shadow projection matrix.\n */\n DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {\n var activeCamera = this.getScene().activeCamera;\n if (!activeCamera) {\n return;\n }\n // Check extends\n if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {\n var tempVector3 = BABYLON.Vector3.Zero();\n this._orthoLeft = Number.MAX_VALUE;\n this._orthoRight = Number.MIN_VALUE;\n this._orthoTop = Number.MIN_VALUE;\n this._orthoBottom = Number.MAX_VALUE;\n for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {\n var mesh = renderList[meshIndex];\n if (!mesh) {\n continue;\n }\n var boundingInfo = mesh.getBoundingInfo();\n var boundingBox = boundingInfo.boundingBox;\n for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {\n BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);\n if (tempVector3.x < this._orthoLeft)\n this._orthoLeft = tempVector3.x;\n if (tempVector3.y < this._orthoBottom)\n this._orthoBottom = tempVector3.y;\n if (tempVector3.x > this._orthoRight)\n this._orthoRight = tempVector3.x;\n if (tempVector3.y > this._orthoTop)\n this._orthoTop = tempVector3.y;\n }\n }\n }\n var xOffset = this._orthoRight - this._orthoLeft;\n var yOffset = this._orthoTop - this._orthoBottom;\n BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);\n };\n DirectionalLight.prototype._buildUniformLayout = function () {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 3);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n };\n /**\n * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The directional light\n */\n DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {\n if (this.computeTransformedInformation()) {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);\n return this;\n }\n this._uniformBuffer.updateFloat4(\"vLightData\", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);\n return this;\n };\n /**\n * Gets the minZ used for shadow according to both the scene and the light.\n *\n * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being\n * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.\n * @param activeCamera The camera we are returning the min for\n * @returns the depth min z\n */\n DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {\n return 1;\n };\n /**\n * Gets the maxZ used for shadow according to both the scene and the light.\n *\n * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being\n * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.\n * @param activeCamera The camera we are returning the max for\n * @returns the depth max z\n */\n DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {\n return 1;\n };\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {\n defines[\"DIRLIGHT\" + lightIndex] = true;\n };\n __decorate([\n BABYLON.serialize()\n ], DirectionalLight.prototype, \"shadowFrustumSize\", null);\n __decorate([\n BABYLON.serialize()\n ], DirectionalLight.prototype, \"shadowOrthoScale\", null);\n __decorate([\n BABYLON.serialize()\n ], DirectionalLight.prototype, \"autoUpdateExtends\", void 0);\n return DirectionalLight;\n }(BABYLON.ShadowLight));\n BABYLON.DirectionalLight = DirectionalLight;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.directionalLight.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"Light_Type_2\", function (name, scene) {\n return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };\n });\n /**\n * A spot light is defined by a position, a direction, an angle, and an exponent.\n * These values define a cone of light starting from the position, emitting toward the direction.\n * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,\n * and the exponent defines the speed of the decay of the light with distance (reach).\n * Documentation: https://doc.babylonjs.com/babylon101/lights\n */\n var SpotLight = /** @class */ (function (_super) {\n __extends(SpotLight, _super);\n /**\n * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.\n * It can cast shadows.\n * Documentation : http://doc.babylonjs.com/tutorials/lights\n * @param name The light friendly name\n * @param position The position of the spot light in the scene\n * @param direction The direction of the light in the scene\n * @param angle The cone angle of the light in Radians\n * @param exponent The light decay speed with the distance from the emission spot\n * @param scene The scene the lights belongs to\n */\n function SpotLight(name, position, direction, angle, exponent, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._projectionTextureMatrix = BABYLON.Matrix.Zero();\n _this._projectionTextureLightNear = 1e-6;\n _this._projectionTextureLightFar = 1000.0;\n _this._projectionTextureUpDirection = BABYLON.Vector3.Up();\n _this._projectionTextureViewLightDirty = true;\n _this._projectionTextureProjectionLightDirty = true;\n _this._projectionTextureDirty = true;\n _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();\n _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();\n _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();\n _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);\n _this.position = position;\n _this.direction = direction;\n _this.angle = angle;\n _this.exponent = exponent;\n return _this;\n }\n Object.defineProperty(SpotLight.prototype, \"angle\", {\n /**\n * Gets the cone angle of the spot light in Radians.\n */\n get: function () {\n return this._angle;\n },\n /**\n * Sets the cone angle of the spot light in Radians.\n */\n set: function (value) {\n this._angle = value;\n this._projectionTextureProjectionLightDirty = true;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpotLight.prototype, \"shadowAngleScale\", {\n /**\n * Allows scaling the angle of the light for shadow generation only.\n */\n get: function () {\n return this._shadowAngleScale;\n },\n /**\n * Allows scaling the angle of the light for shadow generation only.\n */\n set: function (value) {\n this._shadowAngleScale = value;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpotLight.prototype, \"projectionTextureMatrix\", {\n /**\n * Allows reading the projecton texture\n */\n get: function () {\n return this._projectionTextureMatrix;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpotLight.prototype, \"projectionTextureLightNear\", {\n /**\n * Gets the near clip of the Spotlight for texture projection.\n */\n get: function () {\n return this._projectionTextureLightNear;\n },\n /**\n * Sets the near clip of the Spotlight for texture projection.\n */\n set: function (value) {\n this._projectionTextureLightNear = value;\n this._projectionTextureProjectionLightDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpotLight.prototype, \"projectionTextureLightFar\", {\n /**\n * Gets the far clip of the Spotlight for texture projection.\n */\n get: function () {\n return this._projectionTextureLightFar;\n },\n /**\n * Sets the far clip of the Spotlight for texture projection.\n */\n set: function (value) {\n this._projectionTextureLightFar = value;\n this._projectionTextureProjectionLightDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpotLight.prototype, \"projectionTextureUpDirection\", {\n /**\n * Gets the Up vector of the Spotlight for texture projection.\n */\n get: function () {\n return this._projectionTextureUpDirection;\n },\n /**\n * Sets the Up vector of the Spotlight for texture projection.\n */\n set: function (value) {\n this._projectionTextureUpDirection = value;\n this._projectionTextureProjectionLightDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpotLight.prototype, \"projectionTexture\", {\n /**\n * Gets the projection texture of the light.\n */\n get: function () {\n return this._projectionTexture;\n },\n /**\n * Sets the projection texture of the light.\n */\n set: function (value) {\n this._projectionTexture = value;\n this._projectionTextureDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"SpotLight\".\n * @returns the class name\n */\n SpotLight.prototype.getClassName = function () {\n return \"SpotLight\";\n };\n /**\n * Returns the integer 2.\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n SpotLight.prototype.getTypeID = function () {\n return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;\n };\n /**\n * Overrides the direction setter to recompute the projection texture view light Matrix.\n */\n SpotLight.prototype._setDirection = function (value) {\n _super.prototype._setDirection.call(this, value);\n this._projectionTextureViewLightDirty = true;\n };\n /**\n * Overrides the position setter to recompute the projection texture view light Matrix.\n */\n SpotLight.prototype._setPosition = function (value) {\n _super.prototype._setPosition.call(this, value);\n this._projectionTextureViewLightDirty = true;\n };\n /**\n * Sets the passed matrix \"matrix\" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.\n * Returns the SpotLight.\n */\n SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {\n var activeCamera = this.getScene().activeCamera;\n if (!activeCamera) {\n return;\n }\n this._shadowAngleScale = this._shadowAngleScale || 1;\n var angle = this._shadowAngleScale * this._angle;\n BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);\n };\n SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {\n this._projectionTextureViewLightDirty = false;\n this._projectionTextureDirty = true;\n this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);\n BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);\n };\n SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {\n this._projectionTextureProjectionLightDirty = false;\n this._projectionTextureDirty = true;\n var light_far = this.projectionTextureLightFar;\n var light_near = this.projectionTextureLightNear;\n var P = light_far / (light_far - light_near);\n var Q = -P * light_near;\n var S = 1.0 / Math.tan(this._angle / 2.0);\n var A = 1.0;\n BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);\n };\n /**\n * Main function for light texture projection matrix computing.\n */\n SpotLight.prototype._computeProjectionTextureMatrix = function () {\n this._projectionTextureDirty = false;\n this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);\n this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);\n };\n SpotLight.prototype._buildUniformLayout = function () {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 3);\n this._uniformBuffer.addUniform(\"vLightDirection\", 3);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n };\n /**\n * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The spot light\n */\n SpotLight.prototype.transferToEffect = function (effect, lightIndex) {\n var normalizeDirection;\n if (this.computeTransformedInformation()) {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);\n normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);\n }\n else {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);\n normalizeDirection = BABYLON.Vector3.Normalize(this.direction);\n }\n this._uniformBuffer.updateFloat4(\"vLightDirection\", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);\n if (this.projectionTexture && this.projectionTexture.isReady()) {\n if (this._projectionTextureViewLightDirty) {\n this._computeProjectionTextureViewLightMatrix();\n }\n if (this._projectionTextureProjectionLightDirty) {\n this._computeProjectionTextureProjectionLightMatrix();\n }\n if (this._projectionTextureDirty) {\n this._computeProjectionTextureMatrix();\n }\n effect.setMatrix(\"textureProjectionMatrix\" + lightIndex, this._projectionTextureMatrix);\n effect.setTexture(\"projectionLightSampler\" + lightIndex, this.projectionTexture);\n }\n return this;\n };\n /**\n * Disposes the light and the associated resources.\n */\n SpotLight.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n if (this._projectionTexture) {\n this._projectionTexture.dispose();\n }\n };\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {\n defines[\"SPOTLIGHT\" + lightIndex] = true;\n defines[\"PROJECTEDLIGHTTEXTURE\" + lightIndex] = this.projectionTexture ? true : false;\n };\n __decorate([\n BABYLON.serialize()\n ], SpotLight.prototype, \"angle\", null);\n __decorate([\n BABYLON.serialize()\n ], SpotLight.prototype, \"shadowAngleScale\", null);\n __decorate([\n BABYLON.serialize()\n ], SpotLight.prototype, \"exponent\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SpotLight.prototype, \"projectionTextureLightNear\", null);\n __decorate([\n BABYLON.serialize()\n ], SpotLight.prototype, \"projectionTextureLightFar\", null);\n __decorate([\n BABYLON.serialize()\n ], SpotLight.prototype, \"projectionTextureUpDirection\", null);\n __decorate([\n BABYLON.serializeAsTexture(\"projectedLightTexture\")\n ], SpotLight.prototype, \"_projectionTexture\", void 0);\n return SpotLight;\n }(BABYLON.ShadowLight));\n BABYLON.SpotLight = SpotLight;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.spotLight.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to override all child animations of a given target\n */\n var AnimationPropertiesOverride = /** @class */ (function () {\n function AnimationPropertiesOverride() {\n /**\n * Gets or sets a value indicating if animation blending must be used\n */\n this.enableBlending = false;\n /**\n * Gets or sets the blending speed to use when enableBlending is true\n */\n this.blendingSpeed = 0.01;\n /**\n * Gets or sets the default loop mode to use\n */\n this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;\n }\n return AnimationPropertiesOverride;\n }());\n BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.animationPropertiesOverride.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Represents the range of an animation\n */\n var AnimationRange = /** @class */ (function () {\n /**\n * Initializes the range of an animation\n * @param name The name of the animation range\n * @param from The starting frame of the animation\n * @param to The ending frame of the animation\n */\n function AnimationRange(\n /**The name of the animation range**/\n name, \n /**The starting frame of the animation */\n from, \n /**The ending frame of the animation*/\n to) {\n this.name = name;\n this.from = from;\n this.to = to;\n }\n /**\n * Makes a copy of the animation range\n * @returns A copy of the animation range\n */\n AnimationRange.prototype.clone = function () {\n return new AnimationRange(this.name, this.from, this.to);\n };\n return AnimationRange;\n }());\n BABYLON.AnimationRange = AnimationRange;\n /**\n * Composed of a frame, and an action function\n */\n var AnimationEvent = /** @class */ (function () {\n /**\n * Initializes the animation event\n * @param frame The frame for which the event is triggered\n * @param action The event to perform when triggered\n * @param onlyOnce Specifies if the event should be triggered only once\n */\n function AnimationEvent(\n /** The frame for which the event is triggered **/\n frame, \n /** The event to perform when triggered **/\n action, \n /** Specifies if the event should be triggered only once**/\n onlyOnce) {\n this.frame = frame;\n this.action = action;\n this.onlyOnce = onlyOnce;\n /**\n * Specifies if the animation event is done\n */\n this.isDone = false;\n }\n /** @hidden */\n AnimationEvent.prototype._clone = function () {\n return new AnimationEvent(this.frame, this.action, this.onlyOnce);\n };\n return AnimationEvent;\n }());\n BABYLON.AnimationEvent = AnimationEvent;\n /**\n * A cursor which tracks a point on a path\n */\n var PathCursor = /** @class */ (function () {\n /**\n * Initializes the path cursor\n * @param path The path to track\n */\n function PathCursor(path) {\n this.path = path;\n /**\n * Stores path cursor callbacks for when an onchange event is triggered\n */\n this._onchange = new Array();\n /**\n * The value of the path cursor\n */\n this.value = 0;\n /**\n * The animation array of the path cursor\n */\n this.animations = new Array();\n }\n /**\n * Gets the cursor point on the path\n * @returns A point on the path cursor at the cursor location\n */\n PathCursor.prototype.getPoint = function () {\n var point = this.path.getPointAtLengthPosition(this.value);\n return new BABYLON.Vector3(point.x, 0, point.y);\n };\n /**\n * Moves the cursor ahead by the step amount\n * @param step The amount to move the cursor forward\n * @returns This path cursor\n */\n PathCursor.prototype.moveAhead = function (step) {\n if (step === void 0) { step = 0.002; }\n this.move(step);\n return this;\n };\n /**\n * Moves the cursor behind by the step amount\n * @param step The amount to move the cursor back\n * @returns This path cursor\n */\n PathCursor.prototype.moveBack = function (step) {\n if (step === void 0) { step = 0.002; }\n this.move(-step);\n return this;\n };\n /**\n * Moves the cursor by the step amount\n * If the step amount is greater than one, an exception is thrown\n * @param step The amount to move the cursor\n * @returns This path cursor\n */\n PathCursor.prototype.move = function (step) {\n if (Math.abs(step) > 1) {\n throw \"step size should be less than 1.\";\n }\n this.value += step;\n this.ensureLimits();\n this.raiseOnChange();\n return this;\n };\n /**\n * Ensures that the value is limited between zero and one\n * @returns This path cursor\n */\n PathCursor.prototype.ensureLimits = function () {\n while (this.value > 1) {\n this.value -= 1;\n }\n while (this.value < 0) {\n this.value += 1;\n }\n return this;\n };\n /**\n * Runs onchange callbacks on change (used by the animation engine)\n * @returns This path cursor\n */\n PathCursor.prototype.raiseOnChange = function () {\n var _this = this;\n this._onchange.forEach(function (f) { return f(_this); });\n return this;\n };\n /**\n * Executes a function on change\n * @param f A path cursor onchange callback\n * @returns This path cursor\n */\n PathCursor.prototype.onchange = function (f) {\n this._onchange.push(f);\n return this;\n };\n return PathCursor;\n }());\n BABYLON.PathCursor = PathCursor;\n /**\n * Enum for the animation key frame interpolation type\n */\n var AnimationKeyInterpolation;\n (function (AnimationKeyInterpolation) {\n /**\n * Do not interpolate between keys and use the start key value only. Tangents are ignored\n */\n AnimationKeyInterpolation[AnimationKeyInterpolation[\"STEP\"] = 1] = \"STEP\";\n })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));\n /**\n * Class used to store any kind of animation\n */\n var Animation = /** @class */ (function () {\n /**\n * Initializes the animation\n * @param name Name of the animation\n * @param targetProperty Property to animate\n * @param framePerSecond The frames per second of the animation\n * @param dataType The data type of the animation\n * @param loopMode The loop mode of the animation\n * @param enableBlendings Specifies if blending should be enabled\n */\n function Animation(\n /**Name of the animation */\n name, \n /**Property to animate */\n targetProperty, \n /**The frames per second of the animation */\n framePerSecond, \n /**The data type of the animation */\n dataType, \n /**The loop mode of the animation */\n loopMode, \n /**Specifies if blending should be enabled */\n enableBlending) {\n this.name = name;\n this.targetProperty = targetProperty;\n this.framePerSecond = framePerSecond;\n this.dataType = dataType;\n this.loopMode = loopMode;\n this.enableBlending = enableBlending;\n /**\n * @hidden Internal use only\n */\n this._runtimeAnimations = new Array();\n /**\n * The set of event that will be linked to this animation\n */\n this._events = new Array();\n /**\n * Stores the blending speed of the animation\n */\n this.blendingSpeed = 0.01;\n /**\n * Stores the animation ranges for the animation\n */\n this._ranges = {};\n this.targetPropertyPath = targetProperty.split(\".\");\n this.dataType = dataType;\n this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;\n }\n /**\n * @hidden Internal use\n */\n Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {\n var dataType = undefined;\n if (!isNaN(parseFloat(from)) && isFinite(from)) {\n dataType = Animation.ANIMATIONTYPE_FLOAT;\n }\n else if (from instanceof BABYLON.Quaternion) {\n dataType = Animation.ANIMATIONTYPE_QUATERNION;\n }\n else if (from instanceof BABYLON.Vector3) {\n dataType = Animation.ANIMATIONTYPE_VECTOR3;\n }\n else if (from instanceof BABYLON.Vector2) {\n dataType = Animation.ANIMATIONTYPE_VECTOR2;\n }\n else if (from instanceof BABYLON.Color3) {\n dataType = Animation.ANIMATIONTYPE_COLOR3;\n }\n else if (from instanceof BABYLON.Size) {\n dataType = Animation.ANIMATIONTYPE_SIZE;\n }\n if (dataType == undefined) {\n return null;\n }\n var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);\n var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];\n animation.setKeys(keys);\n if (easingFunction !== undefined) {\n animation.setEasingFunction(easingFunction);\n }\n return animation;\n };\n /**\n * Sets up an animation\n * @param property The property to animate\n * @param animationType The animation type to apply\n * @param framePerSecond The frames per second of the animation\n * @param easingFunction The easing function used in the animation\n * @returns The created animation\n */\n Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {\n var animation = new Animation(property + \"Animation\", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);\n animation.setEasingFunction(easingFunction);\n return animation;\n };\n /**\n * Create and start an animation on a node\n * @param name defines the name of the global animation that will be run on all nodes\n * @param node defines the root node where the animation will take place\n * @param targetProperty defines property to animate\n * @param framePerSecond defines the number of frame per second yo use\n * @param totalFrame defines the number of frames in total\n * @param from defines the initial value\n * @param to defines the final value\n * @param loopMode defines which loop mode you want to use (off by default)\n * @param easingFunction defines the easing function to use (linear by default)\n * @param onAnimationEnd defines the callback to call when animation end\n * @returns the animatable created for this animation\n */\n Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {\n var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);\n if (!animation) {\n return null;\n }\n return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);\n };\n /**\n * Create and start an animation on a node and its descendants\n * @param name defines the name of the global animation that will be run on all nodes\n * @param node defines the root node where the animation will take place\n * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used\n * @param targetProperty defines property to animate\n * @param framePerSecond defines the number of frame per second to use\n * @param totalFrame defines the number of frames in total\n * @param from defines the initial value\n * @param to defines the final value\n * @param loopMode defines which loop mode you want to use (off by default)\n * @param easingFunction defines the easing function to use (linear by default)\n * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)\n * @returns the list of animatables created for all nodes\n * @example https://www.babylonjs-playground.com/#MH0VLI\n */\n Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {\n var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);\n if (!animation) {\n return null;\n }\n var scene = node.getScene();\n return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);\n };\n /**\n * Creates a new animation, merges it with the existing animations and starts it\n * @param name Name of the animation\n * @param node Node which contains the scene that begins the animations\n * @param targetProperty Specifies which property to animate\n * @param framePerSecond The frames per second of the animation\n * @param totalFrame The total number of frames\n * @param from The frame at the beginning of the animation\n * @param to The frame at the end of the animation\n * @param loopMode Specifies the loop mode of the animation\n * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations\n * @param onAnimationEnd Callback to run once the animation is complete\n * @returns Nullable animation\n */\n Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {\n var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);\n if (!animation) {\n return null;\n }\n node.animations.push(animation);\n return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);\n };\n /**\n * Transition property of an host to the target Value\n * @param property The property to transition\n * @param targetValue The target Value of the property\n * @param host The object where the property to animate belongs\n * @param scene Scene used to run the animation\n * @param frameRate Framerate (in frame/s) to use\n * @param transition The transition type we want to use\n * @param duration The duration of the animation, in milliseconds\n * @param onAnimationEnd Callback trigger at the end of the animation\n * @returns Nullable animation\n */\n Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {\n if (onAnimationEnd === void 0) { onAnimationEnd = null; }\n if (duration <= 0) {\n host[property] = targetValue;\n if (onAnimationEnd) {\n onAnimationEnd();\n }\n return null;\n }\n var endFrame = frameRate * (duration / 1000);\n transition.setKeys([{\n frame: 0,\n value: host[property].clone ? host[property].clone() : host[property]\n },\n {\n frame: endFrame,\n value: targetValue\n }]);\n if (!host.animations) {\n host.animations = [];\n }\n host.animations.push(transition);\n var animation = scene.beginAnimation(host, 0, endFrame, false);\n animation.onAnimationEnd = onAnimationEnd;\n return animation;\n };\n Object.defineProperty(Animation.prototype, \"runtimeAnimations\", {\n /**\n * Return the array of runtime animations currently using this animation\n */\n get: function () {\n return this._runtimeAnimations;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation.prototype, \"hasRunningRuntimeAnimations\", {\n /**\n * Specifies if any of the runtime animations are currently running\n */\n get: function () {\n for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {\n var runtimeAnimation = _a[_i];\n if (!runtimeAnimation.isStopped) {\n return true;\n }\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n /**\n * Converts the animation to a string\n * @param fullDetails support for multiple levels of logging within scene loading\n * @returns String form of the animation\n */\n Animation.prototype.toString = function (fullDetails) {\n var ret = \"Name: \" + this.name + \", property: \" + this.targetProperty;\n ret += \", datatype: \" + ([\"Float\", \"Vector3\", \"Quaternion\", \"Matrix\", \"Color3\", \"Vector2\"])[this.dataType];\n ret += \", nKeys: \" + (this._keys ? this._keys.length : \"none\");\n ret += \", nRanges: \" + (this._ranges ? Object.keys(this._ranges).length : \"none\");\n if (fullDetails) {\n ret += \", Ranges: {\";\n var first = true;\n for (var name in this._ranges) {\n if (first) {\n ret += \", \";\n first = false;\n }\n ret += name;\n }\n ret += \"}\";\n }\n return ret;\n };\n /**\n * Add an event to this animation\n * @param event Event to add\n */\n Animation.prototype.addEvent = function (event) {\n this._events.push(event);\n };\n /**\n * Remove all events found at the given frame\n * @param frame The frame to remove events from\n */\n Animation.prototype.removeEvents = function (frame) {\n for (var index = 0; index < this._events.length; index++) {\n if (this._events[index].frame === frame) {\n this._events.splice(index, 1);\n index--;\n }\n }\n };\n /**\n * Retrieves all the events from the animation\n * @returns Events from the animation\n */\n Animation.prototype.getEvents = function () {\n return this._events;\n };\n /**\n * Creates an animation range\n * @param name Name of the animation range\n * @param from Starting frame of the animation range\n * @param to Ending frame of the animation\n */\n Animation.prototype.createRange = function (name, from, to) {\n // check name not already in use; could happen for bones after serialized\n if (!this._ranges[name]) {\n this._ranges[name] = new AnimationRange(name, from, to);\n }\n };\n /**\n * Deletes an animation range by name\n * @param name Name of the animation range to delete\n * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)\n */\n Animation.prototype.deleteRange = function (name, deleteFrames) {\n if (deleteFrames === void 0) { deleteFrames = true; }\n var range = this._ranges[name];\n if (!range) {\n return;\n }\n if (deleteFrames) {\n var from = range.from;\n var to = range.to;\n // this loop MUST go high to low for multiple splices to work\n for (var key = this._keys.length - 1; key >= 0; key--) {\n if (this._keys[key].frame >= from && this._keys[key].frame <= to) {\n this._keys.splice(key, 1);\n }\n }\n }\n this._ranges[name] = null; // said much faster than 'delete this._range[name]' \n };\n /**\n * Gets the animation range by name, or null if not defined\n * @param name Name of the animation range\n * @returns Nullable animation range\n */\n Animation.prototype.getRange = function (name) {\n return this._ranges[name];\n };\n /**\n * Gets the key frames from the animation\n * @returns The key frames of the animation\n */\n Animation.prototype.getKeys = function () {\n return this._keys;\n };\n /**\n * Gets the highest frame rate of the animation\n * @returns Highest frame rate of the animation\n */\n Animation.prototype.getHighestFrame = function () {\n var ret = 0;\n for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {\n if (ret < this._keys[key].frame) {\n ret = this._keys[key].frame;\n }\n }\n return ret;\n };\n /**\n * Gets the easing function of the animation\n * @returns Easing function of the animation\n */\n Animation.prototype.getEasingFunction = function () {\n return this._easingFunction;\n };\n /**\n * Sets the easing function of the animation\n * @param easingFunction A custom mathematical formula for animation\n */\n Animation.prototype.setEasingFunction = function (easingFunction) {\n this._easingFunction = easingFunction;\n };\n /**\n * Interpolates a scalar linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated scalar value\n */\n Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {\n return BABYLON.Scalar.Lerp(startValue, endValue, gradient);\n };\n /**\n * Interpolates a scalar cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated scalar value\n */\n Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {\n return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n };\n /**\n * Interpolates a quaternion using a spherical linear interpolation\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated quaternion value\n */\n Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {\n return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);\n };\n /**\n * Interpolates a quaternion cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation curve\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated quaternion value\n */\n Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {\n return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();\n };\n /**\n * Interpolates a Vector3 linearl\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated scalar value\n */\n Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {\n return BABYLON.Vector3.Lerp(startValue, endValue, gradient);\n };\n /**\n * Interpolates a Vector3 cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns InterpolatedVector3 value\n */\n Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {\n return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n };\n /**\n * Interpolates a Vector2 linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Vector2 value\n */\n Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {\n return BABYLON.Vector2.Lerp(startValue, endValue, gradient);\n };\n /**\n * Interpolates a Vector2 cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Vector2 value\n */\n Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {\n return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n };\n /**\n * Interpolates a size linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Size value\n */\n Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {\n return BABYLON.Size.Lerp(startValue, endValue, gradient);\n };\n /**\n * Interpolates a Color3 linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Color3 value\n */\n Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {\n return BABYLON.Color3.Lerp(startValue, endValue, gradient);\n };\n /**\n * @hidden Internal use only\n */\n Animation.prototype._getKeyValue = function (value) {\n if (typeof value === \"function\") {\n return value();\n }\n return value;\n };\n /**\n * @hidden Internal use only\n */\n Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {\n if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {\n return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;\n }\n var keys = this.getKeys();\n // Try to get a hash to find the right key\n var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));\n if (keys[startKeyIndex].frame >= currentFrame) {\n while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {\n startKeyIndex--;\n }\n }\n for (var key = startKeyIndex; key < keys.length; key++) {\n var endKey = keys[key + 1];\n if (endKey.frame >= currentFrame) {\n var startKey = keys[key];\n var startValue = this._getKeyValue(startKey.value);\n if (startKey.interpolation === AnimationKeyInterpolation.STEP) {\n return startValue;\n }\n var endValue = this._getKeyValue(endKey.value);\n var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;\n var frameDelta = endKey.frame - startKey.frame;\n // gradient : percent of currentFrame between the frame inf and the frame sup\n var gradient = (currentFrame - startKey.frame) / frameDelta;\n // check for easingFunction and correction of gradient\n var easingFunction = this.getEasingFunction();\n if (easingFunction != null) {\n gradient = easingFunction.ease(gradient);\n }\n switch (this.dataType) {\n // Float\n case Animation.ANIMATIONTYPE_FLOAT:\n var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n return floatValue;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return offsetValue * repeatCount + floatValue;\n }\n break;\n // Quaternion\n case Animation.ANIMATIONTYPE_QUATERNION:\n var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n return quatValue;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return quatValue.addInPlace(offsetValue.scale(repeatCount));\n }\n return quatValue;\n // Vector3\n case Animation.ANIMATIONTYPE_VECTOR3:\n var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n return vec3Value;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return vec3Value.add(offsetValue.scale(repeatCount));\n }\n // Vector2\n case Animation.ANIMATIONTYPE_VECTOR2:\n var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n return vec2Value;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return vec2Value.add(offsetValue.scale(repeatCount));\n }\n // Size\n case Animation.ANIMATIONTYPE_SIZE:\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n return this.sizeInterpolateFunction(startValue, endValue, gradient);\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));\n }\n // Color3\n case Animation.ANIMATIONTYPE_COLOR3:\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n return this.color3InterpolateFunction(startValue, endValue, gradient);\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));\n }\n // Matrix\n case Animation.ANIMATIONTYPE_MATRIX:\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n if (Animation.AllowMatricesInterpolation) {\n return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);\n }\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return startValue;\n }\n default:\n break;\n }\n break;\n }\n }\n return this._getKeyValue(keys[keys.length - 1].value);\n };\n /**\n * Defines the function to use to interpolate matrices\n * @param startValue defines the start matrix\n * @param endValue defines the end matrix\n * @param gradient defines the gradient between both matrices\n * @param result defines an optional target matrix where to store the interpolation\n * @returns the interpolated matrix\n */\n Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {\n if (Animation.AllowMatrixDecomposeForInterpolation) {\n if (result) {\n BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);\n return result;\n }\n return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);\n }\n if (result) {\n BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);\n return result;\n }\n return BABYLON.Matrix.Lerp(startValue, endValue, gradient);\n };\n /**\n * Makes a copy of the animation\n * @returns Cloned animation\n */\n Animation.prototype.clone = function () {\n var clone = new Animation(this.name, this.targetPropertyPath.join(\".\"), this.framePerSecond, this.dataType, this.loopMode);\n clone.enableBlending = this.enableBlending;\n clone.blendingSpeed = this.blendingSpeed;\n if (this._keys) {\n clone.setKeys(this._keys);\n }\n if (this._ranges) {\n clone._ranges = {};\n for (var name in this._ranges) {\n var range = this._ranges[name];\n if (!range) {\n continue;\n }\n clone._ranges[name] = range.clone();\n }\n }\n return clone;\n };\n /**\n * Sets the key frames of the animation\n * @param values The animation key frames to set\n */\n Animation.prototype.setKeys = function (values) {\n this._keys = values.slice(0);\n };\n /**\n * Serializes the animation to an object\n * @returns Serialized object\n */\n Animation.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.property = this.targetProperty;\n serializationObject.framePerSecond = this.framePerSecond;\n serializationObject.dataType = this.dataType;\n serializationObject.loopBehavior = this.loopMode;\n serializationObject.enableBlending = this.enableBlending;\n serializationObject.blendingSpeed = this.blendingSpeed;\n var dataType = this.dataType;\n serializationObject.keys = [];\n var keys = this.getKeys();\n for (var index = 0; index < keys.length; index++) {\n var animationKey = keys[index];\n var key = {};\n key.frame = animationKey.frame;\n switch (dataType) {\n case Animation.ANIMATIONTYPE_FLOAT:\n key.values = [animationKey.value];\n break;\n case Animation.ANIMATIONTYPE_QUATERNION:\n case Animation.ANIMATIONTYPE_MATRIX:\n case Animation.ANIMATIONTYPE_VECTOR3:\n case Animation.ANIMATIONTYPE_COLOR3:\n key.values = animationKey.value.asArray();\n break;\n }\n serializationObject.keys.push(key);\n }\n serializationObject.ranges = [];\n for (var name in this._ranges) {\n var source = this._ranges[name];\n if (!source) {\n continue;\n }\n var range = {};\n range.name = name;\n range.from = source.from;\n range.to = source.to;\n serializationObject.ranges.push(range);\n }\n return serializationObject;\n };\n Object.defineProperty(Animation, \"ANIMATIONTYPE_FLOAT\", {\n /**\n * Get the float animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_FLOAT;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONTYPE_VECTOR3\", {\n /**\n * Get the Vector3 animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_VECTOR3;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONTYPE_VECTOR2\", {\n /**\n * Get the Vectpr2 animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_VECTOR2;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONTYPE_SIZE\", {\n /**\n * Get the Size animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_SIZE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONTYPE_QUATERNION\", {\n /**\n * Get the Quaternion animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_QUATERNION;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONTYPE_MATRIX\", {\n /**\n * Get the Matrix animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_MATRIX;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONTYPE_COLOR3\", {\n /**\n * Get the Color3 animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_COLOR3;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONLOOPMODE_RELATIVE\", {\n /**\n * Get the Relative Loop Mode\n */\n get: function () {\n return Animation._ANIMATIONLOOPMODE_RELATIVE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONLOOPMODE_CYCLE\", {\n /**\n * Get the Cycle Loop Mode\n */\n get: function () {\n return Animation._ANIMATIONLOOPMODE_CYCLE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONLOOPMODE_CONSTANT\", {\n /**\n * Get the Constant Loop Mode\n */\n get: function () {\n return Animation._ANIMATIONLOOPMODE_CONSTANT;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Animation._UniversalLerp = function (left, right, amount) {\n var constructor = left.constructor;\n if (constructor.Lerp) { // Lerp supported\n return constructor.Lerp(left, right, amount);\n }\n else if (constructor.Slerp) { // Slerp supported\n return constructor.Slerp(left, right, amount);\n }\n else if (left.toFixed) { // Number\n return left * (1.0 - amount) + amount * right;\n }\n else { // Blending not supported\n return right;\n }\n };\n /**\n * Parses an animation object and creates an animation\n * @param parsedAnimation Parsed animation object\n * @returns Animation object\n */\n Animation.Parse = function (parsedAnimation) {\n var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);\n var dataType = parsedAnimation.dataType;\n var keys = [];\n var data;\n var index;\n if (parsedAnimation.enableBlending) {\n animation.enableBlending = parsedAnimation.enableBlending;\n }\n if (parsedAnimation.blendingSpeed) {\n animation.blendingSpeed = parsedAnimation.blendingSpeed;\n }\n for (index = 0; index < parsedAnimation.keys.length; index++) {\n var key = parsedAnimation.keys[index];\n var inTangent;\n var outTangent;\n switch (dataType) {\n case Animation.ANIMATIONTYPE_FLOAT:\n data = key.values[0];\n if (key.values.length >= 1) {\n inTangent = key.values[1];\n }\n if (key.values.length >= 2) {\n outTangent = key.values[2];\n }\n break;\n case Animation.ANIMATIONTYPE_QUATERNION:\n data = BABYLON.Quaternion.FromArray(key.values);\n if (key.values.length >= 8) {\n var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));\n if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {\n inTangent = _inTangent;\n }\n }\n if (key.values.length >= 12) {\n var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));\n if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {\n outTangent = _outTangent;\n }\n }\n break;\n case Animation.ANIMATIONTYPE_MATRIX:\n data = BABYLON.Matrix.FromArray(key.values);\n break;\n case Animation.ANIMATIONTYPE_COLOR3:\n data = BABYLON.Color3.FromArray(key.values);\n break;\n case Animation.ANIMATIONTYPE_VECTOR3:\n default:\n data = BABYLON.Vector3.FromArray(key.values);\n break;\n }\n var keyData = {};\n keyData.frame = key.frame;\n keyData.value = data;\n if (inTangent != undefined) {\n keyData.inTangent = inTangent;\n }\n if (outTangent != undefined) {\n keyData.outTangent = outTangent;\n }\n keys.push(keyData);\n }\n animation.setKeys(keys);\n if (parsedAnimation.ranges) {\n for (index = 0; index < parsedAnimation.ranges.length; index++) {\n data = parsedAnimation.ranges[index];\n animation.createRange(data.name, data.from, data.to);\n }\n }\n return animation;\n };\n /**\n * Appends the serialized animations from the source animations\n * @param source Source containing the animations\n * @param destination Target to store the animations\n */\n Animation.AppendSerializedAnimations = function (source, destination) {\n if (source.animations) {\n destination.animations = [];\n for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {\n var animation = source.animations[animationIndex];\n destination.animations.push(animation.serialize());\n }\n }\n };\n /**\n * Use matrix interpolation instead of using direct key value when animating matrices\n */\n Animation.AllowMatricesInterpolation = false;\n /**\n * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower\n */\n Animation.AllowMatrixDecomposeForInterpolation = true;\n // Statics\n /**\n * Float animation type\n */\n Animation._ANIMATIONTYPE_FLOAT = 0;\n /**\n * Vector3 animation type\n */\n Animation._ANIMATIONTYPE_VECTOR3 = 1;\n /**\n * Quaternion animation type\n */\n Animation._ANIMATIONTYPE_QUATERNION = 2;\n /**\n * Matrix animation type\n */\n Animation._ANIMATIONTYPE_MATRIX = 3;\n /**\n * Color3 animation type\n */\n Animation._ANIMATIONTYPE_COLOR3 = 4;\n /**\n * Vector2 animation type\n */\n Animation._ANIMATIONTYPE_VECTOR2 = 5;\n /**\n * Size animation type\n */\n Animation._ANIMATIONTYPE_SIZE = 6;\n /**\n * Relative Loop Mode\n */\n Animation._ANIMATIONLOOPMODE_RELATIVE = 0;\n /**\n * Cycle Loop Mode\n */\n Animation._ANIMATIONLOOPMODE_CYCLE = 1;\n /**\n * Constant Loop Mode\n */\n Animation._ANIMATIONLOOPMODE_CONSTANT = 2;\n return Animation;\n }());\n BABYLON.Animation = Animation;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.animation.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class defines the direct association between an animation and a target\n */\n var TargetedAnimation = /** @class */ (function () {\n function TargetedAnimation() {\n }\n return TargetedAnimation;\n }());\n BABYLON.TargetedAnimation = TargetedAnimation;\n /**\n * Use this class to create coordinated animations on multiple targets\n */\n var AnimationGroup = /** @class */ (function () {\n function AnimationGroup(name, scene) {\n if (scene === void 0) { scene = null; }\n this.name = name;\n this._targetedAnimations = new Array();\n this._animatables = new Array();\n this._from = Number.MAX_VALUE;\n this._to = -Number.MAX_VALUE;\n this._speedRatio = 1;\n this.onAnimationEndObservable = new BABYLON.Observable();\n /**\n * This observable will notify when all animations have ended.\n */\n this.onAnimationGroupEndObservable = new BABYLON.Observable();\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this._scene.animationGroups.push(this);\n }\n Object.defineProperty(AnimationGroup.prototype, \"from\", {\n /**\n * Gets the first frame\n */\n get: function () {\n return this._from;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AnimationGroup.prototype, \"to\", {\n /**\n * Gets the last frame\n */\n get: function () {\n return this._to;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AnimationGroup.prototype, \"isStarted\", {\n /**\n * Define if the animations are started\n */\n get: function () {\n return this._isStarted;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AnimationGroup.prototype, \"speedRatio\", {\n /**\n * Gets or sets the speed ratio to use for all animations\n */\n get: function () {\n return this._speedRatio;\n },\n /**\n * Gets or sets the speed ratio to use for all animations\n */\n set: function (value) {\n if (this._speedRatio === value) {\n return;\n }\n this._speedRatio = value;\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.speedRatio = this._speedRatio;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AnimationGroup.prototype, \"targetedAnimations\", {\n /**\n * Gets the targeted animations for this animation group\n */\n get: function () {\n return this._targetedAnimations;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AnimationGroup.prototype, \"animatables\", {\n /**\n * returning the list of animatables controlled by this animation group.\n */\n get: function () {\n return this._animatables;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Add an animation (with its target) in the group\n * @param animation defines the animation we want to add\n * @param target defines the target of the animation\n * @returns the {BABYLON.TargetedAnimation} object\n */\n AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {\n var targetedAnimation = {\n animation: animation,\n target: target\n };\n var keys = animation.getKeys();\n if (this._from > keys[0].frame) {\n this._from = keys[0].frame;\n }\n if (this._to < keys[keys.length - 1].frame) {\n this._to = keys[keys.length - 1].frame;\n }\n this._targetedAnimations.push(targetedAnimation);\n return targetedAnimation;\n };\n /**\n * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame\n * It can add constant keys at begin or end\n * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)\n * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)\n */\n AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {\n if (beginFrame === void 0) { beginFrame = null; }\n if (endFrame === void 0) { endFrame = null; }\n if (beginFrame == null)\n beginFrame = this._from;\n if (endFrame == null)\n endFrame = this._to;\n for (var index = 0; index < this._targetedAnimations.length; index++) {\n var targetedAnimation = this._targetedAnimations[index];\n var keys = targetedAnimation.animation.getKeys();\n var startKey = keys[0];\n var endKey = keys[keys.length - 1];\n if (startKey.frame > beginFrame) {\n var newKey = {\n frame: beginFrame,\n value: startKey.value,\n inTangent: startKey.inTangent,\n outTangent: startKey.outTangent,\n interpolation: startKey.interpolation\n };\n keys.splice(0, 0, newKey);\n }\n if (endKey.frame < endFrame) {\n var newKey = {\n frame: endFrame,\n value: endKey.value,\n inTangent: endKey.outTangent,\n outTangent: endKey.outTangent,\n interpolation: endKey.interpolation\n };\n keys.push(newKey);\n }\n }\n this._from = beginFrame;\n this._to = endFrame;\n return this;\n };\n /**\n * Start all animations on given targets\n * @param loop defines if animations must loop\n * @param speedRatio defines the ratio to apply to animation speed (1 by default)\n * @param from defines the from key (optional)\n * @param to defines the to key (optional)\n * @returns the current animation group\n */\n AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {\n var _this = this;\n if (loop === void 0) { loop = false; }\n if (speedRatio === void 0) { speedRatio = 1; }\n if (this._isStarted || this._targetedAnimations.length === 0) {\n return this;\n }\n var _loop_1 = function (targetedAnimation) {\n var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);\n animatable.onAnimationEnd = function () {\n _this.onAnimationEndObservable.notifyObservers(targetedAnimation);\n _this._checkAnimationGroupEnded(animatable);\n };\n this_1._animatables.push(animatable);\n };\n var this_1 = this;\n for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {\n var targetedAnimation = _a[_i];\n _loop_1(targetedAnimation);\n }\n this._speedRatio = speedRatio;\n this._isStarted = true;\n return this;\n };\n /**\n * Pause all animations\n */\n AnimationGroup.prototype.pause = function () {\n if (!this._isStarted) {\n return this;\n }\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.pause();\n }\n return this;\n };\n /**\n * Play all animations to initial state\n * This function will start() the animations if they were not started or will restart() them if they were paused\n * @param loop defines if animations must loop\n */\n AnimationGroup.prototype.play = function (loop) {\n // only if all animatables are ready and exist\n if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {\n if (loop !== undefined) {\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.loopAnimation = loop;\n }\n }\n this.restart();\n }\n else {\n this.stop();\n this.start(loop, this._speedRatio);\n }\n return this;\n };\n /**\n * Reset all animations to initial state\n */\n AnimationGroup.prototype.reset = function () {\n if (!this._isStarted) {\n return this;\n }\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.reset();\n }\n return this;\n };\n /**\n * Restart animations from key 0\n */\n AnimationGroup.prototype.restart = function () {\n if (!this._isStarted) {\n return this;\n }\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.restart();\n }\n return this;\n };\n /**\n * Stop all animations\n */\n AnimationGroup.prototype.stop = function () {\n if (!this._isStarted) {\n return this;\n }\n var list = this._animatables.slice();\n for (var index = 0; index < list.length; index++) {\n list[index].stop();\n }\n this._isStarted = false;\n return this;\n };\n /**\n * Set animation weight for all animatables\n * @param weight defines the weight to use\n * @return the animationGroup\n * @see http://doc.babylonjs.com/babylon101/animations#animation-weights\n */\n AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.weight = weight;\n }\n return this;\n };\n /**\n * Synchronize and normalize all animatables with a source animatable\n * @param root defines the root animatable to synchronize with\n * @return the animationGroup\n * @see http://doc.babylonjs.com/babylon101/animations#animation-weights\n */\n AnimationGroup.prototype.syncAllAnimationsWith = function (root) {\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.syncWith(root);\n }\n return this;\n };\n /**\n * Goes to a specific frame in this animation group\n * @param frame the frame number to go to\n * @return the animationGroup\n */\n AnimationGroup.prototype.goToFrame = function (frame) {\n if (!this._isStarted) {\n return this;\n }\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.goToFrame(frame);\n }\n return this;\n };\n /**\n * Dispose all associated resources\n */\n AnimationGroup.prototype.dispose = function () {\n this._targetedAnimations = [];\n this._animatables = [];\n var index = this._scene.animationGroups.indexOf(this);\n if (index > -1) {\n this._scene.animationGroups.splice(index, 1);\n }\n };\n AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {\n // animatable should be taken out of the array\n var idx = this._animatables.indexOf(animatable);\n if (idx > -1) {\n this._animatables.splice(idx, 1);\n }\n // all animatables were removed? animation group ended!\n if (this._animatables.length === 0) {\n this._isStarted = false;\n this.onAnimationGroupEndObservable.notifyObservers(this);\n }\n };\n return AnimationGroup;\n }());\n BABYLON.AnimationGroup = AnimationGroup;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.animationGroup.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines a runtime animation\n */\n var RuntimeAnimation = /** @class */ (function () {\n /**\n * Create a new RuntimeAnimation object\n * @param target defines the target of the animation\n * @param animation defines the source animation object\n * @param scene defines the hosting scene\n * @param host defines the initiating Animatable\n */\n function RuntimeAnimation(target, animation, scene, host) {\n var _this = this;\n this._events = new Array();\n /**\n * The current frame of the runtime animation\n */\n this._currentFrame = 0;\n /**\n * The original value of the runtime animation\n */\n this._originalValue = new Array();\n /**\n * The offsets cache of the runtime animation\n */\n this._offsetsCache = {};\n /**\n * The high limits cache of the runtime animation\n */\n this._highLimitsCache = {};\n /**\n * Specifies if the runtime animation has been stopped\n */\n this._stopped = false;\n /**\n * The blending factor of the runtime animation\n */\n this._blendingFactor = 0;\n /**\n * The target path of the runtime animation\n */\n this._targetPath = \"\";\n /**\n * The weight of the runtime animation\n */\n this._weight = 1.0;\n /**\n * The ratio offset of the runtime animation\n */\n this._ratioOffset = 0;\n /**\n * The previous delay of the runtime animation\n */\n this._previousDelay = 0;\n /**\n * The previous ratio of the runtime animation\n */\n this._previousRatio = 0;\n this._animation = animation;\n this._target = target;\n this._scene = scene;\n this._host = host;\n animation._runtimeAnimations.push(this);\n // Cloning events locally\n var events = animation.getEvents();\n if (events && events.length > 0) {\n events.forEach(function (e) {\n _this._events.push(e._clone());\n });\n }\n }\n Object.defineProperty(RuntimeAnimation.prototype, \"currentFrame\", {\n /**\n * Gets the current frame of the runtime animation\n */\n get: function () {\n return this._currentFrame;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RuntimeAnimation.prototype, \"weight\", {\n /**\n * Gets the weight of the runtime animation\n */\n get: function () {\n return this._weight;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RuntimeAnimation.prototype, \"currentValue\", {\n /**\n * Gets the current value of the runtime animation\n */\n get: function () {\n return this._currentValue;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RuntimeAnimation.prototype, \"targetPath\", {\n /**\n * Gets the target path of the runtime animation\n */\n get: function () {\n return this._targetPath;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RuntimeAnimation.prototype, \"target\", {\n /**\n * Gets the actual target of the runtime animation\n */\n get: function () {\n return this._activeTarget;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RuntimeAnimation.prototype, \"animation\", {\n /**\n * Gets the animation from the runtime animation\n */\n get: function () {\n return this._animation;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Resets the runtime animation to the beginning\n * @param restoreOriginal defines whether to restore the target property to the original value\n */\n RuntimeAnimation.prototype.reset = function (restoreOriginal) {\n if (restoreOriginal === void 0) { restoreOriginal = false; }\n if (restoreOriginal) {\n if (this._target instanceof Array) {\n var index = 0;\n for (var _i = 0, _a = this._target; _i < _a.length; _i++) {\n var target = _a[_i];\n if (this._originalValue[index] !== undefined) {\n this._setValue(target, this._originalValue[index], -1);\n }\n index++;\n }\n }\n else {\n if (this._originalValue[0] !== undefined) {\n this._setValue(this._target, this._originalValue[0], -1);\n }\n }\n }\n this._offsetsCache = {};\n this._highLimitsCache = {};\n this._currentFrame = 0;\n this._blendingFactor = 0;\n this._originalValue = new Array();\n // Events\n for (var index = 0; index < this._events.length; index++) {\n this._events[index].isDone = false;\n }\n };\n /**\n * Specifies if the runtime animation is stopped\n * @returns Boolean specifying if the runtime animation is stopped\n */\n RuntimeAnimation.prototype.isStopped = function () {\n return this._stopped;\n };\n /**\n * Disposes of the runtime animation\n */\n RuntimeAnimation.prototype.dispose = function () {\n var index = this._animation.runtimeAnimations.indexOf(this);\n if (index > -1) {\n this._animation.runtimeAnimations.splice(index, 1);\n }\n };\n /**\n * Interpolates the animation from the current frame\n * @param currentFrame The frame to interpolate the animation to\n * @param repeatCount The number of times that the animation should loop\n * @param loopMode The type of looping mode to use\n * @param offsetValue Animation offset value\n * @param highLimitValue The high limit value\n * @returns The interpolated value\n */\n RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {\n this._currentFrame = currentFrame;\n if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {\n this._workValue = BABYLON.Matrix.Zero();\n }\n return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);\n };\n /**\n * Apply the interpolated value to the target\n * @param currentValue defines the value computed by the animation\n * @param weight defines the weight to apply to this value (Defaults to 1.0)\n */\n RuntimeAnimation.prototype.setValue = function (currentValue, weight) {\n if (weight === void 0) { weight = 1.0; }\n if (this._target instanceof Array) {\n var index = 0;\n for (var _i = 0, _a = this._target; _i < _a.length; _i++) {\n var target = _a[_i];\n this._setValue(target, currentValue, weight, index);\n index++;\n }\n }\n else {\n this._setValue(this._target, currentValue, weight);\n }\n };\n RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {\n if (targetIndex === void 0) { targetIndex = 0; }\n // Set value\n var path;\n var destination;\n var targetPropertyPath = this._animation.targetPropertyPath;\n if (targetPropertyPath.length > 1) {\n var property = target[targetPropertyPath[0]];\n for (var index = 1; index < targetPropertyPath.length - 1; index++) {\n property = property[targetPropertyPath[index]];\n }\n path = targetPropertyPath[targetPropertyPath.length - 1];\n destination = property;\n }\n else {\n path = targetPropertyPath[0];\n destination = target;\n }\n this._targetPath = path;\n this._activeTarget = destination;\n this._weight = weight;\n if (this._originalValue[targetIndex] === undefined) {\n var originalValue = void 0;\n if (destination.getRestPose && path === \"_matrix\") { // For bones\n originalValue = destination.getRestPose();\n }\n else {\n originalValue = destination[path];\n }\n if (originalValue && originalValue.clone) {\n this._originalValue[targetIndex] = originalValue.clone();\n }\n else {\n this._originalValue[targetIndex] = originalValue;\n }\n }\n // Blending\n var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;\n if (enableBlending && this._blendingFactor <= 1.0) {\n if (!this._originalBlendValue) {\n var originalValue = destination[path];\n if (originalValue.clone) {\n this._originalBlendValue = originalValue.clone();\n }\n else {\n this._originalBlendValue = originalValue;\n }\n }\n if (this._originalBlendValue.m) { // Matrix\n if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {\n if (this._currentValue) {\n BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);\n }\n else {\n this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);\n }\n }\n else {\n if (this._currentValue) {\n BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);\n }\n else {\n this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);\n }\n }\n }\n else {\n this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);\n }\n var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;\n this._blendingFactor += blendingSpeed;\n }\n else {\n this._currentValue = currentValue;\n }\n if (weight !== -1.0) {\n this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);\n }\n else {\n destination[path] = this._currentValue;\n }\n if (target.markAsDirty) {\n target.markAsDirty(this._animation.targetProperty);\n }\n };\n /**\n * Gets the loop pmode of the runtime animation\n * @returns Loop Mode\n */\n RuntimeAnimation.prototype._getCorrectLoopMode = function () {\n if (this._target && this._target.animationPropertiesOverride) {\n return this._target.animationPropertiesOverride.loopMode;\n }\n return this._animation.loopMode;\n };\n /**\n * Move the current animation to a given frame\n * @param frame defines the frame to move to\n */\n RuntimeAnimation.prototype.goToFrame = function (frame) {\n var keys = this._animation.getKeys();\n if (frame < keys[0].frame) {\n frame = keys[0].frame;\n }\n else if (frame > keys[keys.length - 1].frame) {\n frame = keys[keys.length - 1].frame;\n }\n var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());\n this.setValue(currentValue, -1);\n };\n /**\n * @hidden Internal use only\n */\n RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {\n var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;\n this._ratioOffset = this._previousRatio - newRatio;\n };\n /**\n * Execute the current animation\n * @param delay defines the delay to add to the current frame\n * @param from defines the lower bound of the animation range\n * @param to defines the upper bound of the animation range\n * @param loop defines if the current animation must loop\n * @param speedRatio defines the current speed ratio\n * @param weight defines the weight of the animation (default is -1 so no weight)\n * @returns a boolean indicating if the animation is running\n */\n RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {\n if (weight === void 0) { weight = -1.0; }\n var targetPropertyPath = this._animation.targetPropertyPath;\n if (!targetPropertyPath || targetPropertyPath.length < 1) {\n this._stopped = true;\n return false;\n }\n var returnValue = true;\n var keys = this._animation.getKeys();\n // Adding a start key at frame 0 if missing\n if (keys[0].frame !== 0) {\n var newKey = { frame: 0, value: keys[0].value };\n keys.splice(0, 0, newKey);\n }\n // Adding a duplicate key when there is only one key at frame zero\n else if (keys.length === 1) {\n var newKey = { frame: 0.001, value: keys[0].value };\n keys.push(newKey);\n }\n // Check limits\n if (from < keys[0].frame || from > keys[keys.length - 1].frame) {\n from = keys[0].frame;\n }\n if (to < keys[0].frame || to > keys[keys.length - 1].frame) {\n to = keys[keys.length - 1].frame;\n }\n //to and from cannot be the same key\n if (from === to) {\n if (from > keys[0].frame) {\n from--;\n }\n else if (to < keys[keys.length - 1].frame) {\n to++;\n }\n }\n // Compute ratio\n var range = to - from;\n var offsetValue;\n // ratio represents the frame delta between from and to\n var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;\n var highLimitValue = 0;\n this._previousDelay = delay;\n this._previousRatio = ratio;\n if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller\n returnValue = false;\n highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);\n }\n else {\n // Get max value if required\n if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {\n var keyOffset = to.toString() + from.toString();\n if (!this._offsetsCache[keyOffset]) {\n var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);\n var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);\n switch (this._animation.dataType) {\n // Float\n case BABYLON.Animation.ANIMATIONTYPE_FLOAT:\n this._offsetsCache[keyOffset] = toValue - fromValue;\n break;\n // Quaternion\n case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n break;\n // Vector3\n case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n // Vector2\n case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n // Size\n case BABYLON.Animation.ANIMATIONTYPE_SIZE:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n // Color3\n case BABYLON.Animation.ANIMATIONTYPE_COLOR3:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n default:\n break;\n }\n this._highLimitsCache[keyOffset] = toValue;\n }\n highLimitValue = this._highLimitsCache[keyOffset];\n offsetValue = this._offsetsCache[keyOffset];\n }\n }\n if (offsetValue === undefined) {\n switch (this._animation.dataType) {\n // Float\n case BABYLON.Animation.ANIMATIONTYPE_FLOAT:\n offsetValue = 0;\n break;\n // Quaternion\n case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:\n offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);\n break;\n // Vector3\n case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:\n offsetValue = BABYLON.Vector3.Zero();\n break;\n // Vector2\n case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:\n offsetValue = BABYLON.Vector2.Zero();\n break;\n // Size\n case BABYLON.Animation.ANIMATIONTYPE_SIZE:\n offsetValue = BABYLON.Size.Zero();\n break;\n // Color3\n case BABYLON.Animation.ANIMATIONTYPE_COLOR3:\n offsetValue = BABYLON.Color3.Black();\n }\n }\n // Compute value\n var repeatCount = (ratio / range) >> 0;\n var currentFrame = returnValue ? from + ratio % range : to;\n // Need to normalize?\n if (this._host && this._host.syncRoot) {\n var syncRoot = this._host.syncRoot;\n var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);\n currentFrame = from + (to - from) * hostNormalizedFrame;\n }\n // Reset events if looping\n var events = this._events;\n if (range > 0 && this.currentFrame > currentFrame ||\n range < 0 && this.currentFrame < currentFrame) {\n // Need to reset animation events\n for (var index = 0; index < events.length; index++) {\n if (!events[index].onlyOnce) {\n // reset event, the animation is looping\n events[index].isDone = false;\n }\n }\n }\n var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);\n // Set value\n this.setValue(currentValue, weight);\n // Check events\n for (var index = 0; index < events.length; index++) {\n // Make sure current frame has passed event frame and that event frame is within the current range\n // Also, handle both forward and reverse animations\n if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||\n (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {\n var event = events[index];\n if (!event.isDone) {\n // If event should be done only once, remove it.\n if (event.onlyOnce) {\n events.splice(index, 1);\n index--;\n }\n event.isDone = true;\n event.action();\n } // Don't do anything if the event has already be done.\n }\n }\n if (!returnValue) {\n this._stopped = true;\n }\n return returnValue;\n };\n return RuntimeAnimation;\n }());\n BABYLON.RuntimeAnimation = RuntimeAnimation;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.runtimeAnimation.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to store an actual running animation\n */\n var Animatable = /** @class */ (function () {\n /**\n * Creates a new Animatable\n * @param scene defines the hosting scene\n * @param target defines the target object\n * @param fromFrame defines the starting frame number (default is 0)\n * @param toFrame defines the ending frame number (default is 100)\n * @param loopAnimation defines if the animation must loop (default is false)\n * @param speedRatio defines the factor to apply to animation speed (default is 1)\n * @param onAnimationEnd defines a callback to call when animation ends if it is not looping\n * @param animations defines a group of animation to add to the new Animatable\n */\n function Animatable(scene, \n /** defines the target object */\n target, \n /** defines the starting frame number (default is 0) */\n fromFrame, \n /** defines the ending frame number (default is 100) */\n toFrame, \n /** defines if the animation must loop (default is false) */\n loopAnimation, speedRatio, \n /** defines a callback to call when animation ends if it is not looping */\n onAnimationEnd, animations) {\n if (fromFrame === void 0) { fromFrame = 0; }\n if (toFrame === void 0) { toFrame = 100; }\n if (loopAnimation === void 0) { loopAnimation = false; }\n if (speedRatio === void 0) { speedRatio = 1.0; }\n this.target = target;\n this.fromFrame = fromFrame;\n this.toFrame = toFrame;\n this.loopAnimation = loopAnimation;\n this.onAnimationEnd = onAnimationEnd;\n this._localDelayOffset = null;\n this._pausedDelay = null;\n this._runtimeAnimations = new Array();\n this._paused = false;\n this._speedRatio = 1;\n this._weight = -1.0;\n /**\n * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.\n * This will only apply for non looping animation (default is true)\n */\n this.disposeOnEnd = true;\n /**\n * Gets a boolean indicating if the animation has started\n */\n this.animationStarted = false;\n /**\n * Observer raised when the animation ends\n */\n this.onAnimationEndObservable = new BABYLON.Observable();\n this._scene = scene;\n if (animations) {\n this.appendAnimations(target, animations);\n }\n this._speedRatio = speedRatio;\n scene._activeAnimatables.push(this);\n }\n Object.defineProperty(Animatable.prototype, \"syncRoot\", {\n /**\n * Gets the root Animatable used to synchronize and normalize animations\n */\n get: function () {\n return this._syncRoot;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animatable.prototype, \"masterFrame\", {\n /**\n * Gets the current frame of the first RuntimeAnimation\n * Used to synchronize Animatables\n */\n get: function () {\n if (this._runtimeAnimations.length === 0) {\n return 0;\n }\n return this._runtimeAnimations[0].currentFrame;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animatable.prototype, \"weight\", {\n /**\n * Gets or sets the animatable weight (-1.0 by default meaning not weighted)\n */\n get: function () {\n return this._weight;\n },\n set: function (value) {\n if (value === -1) { // -1 is ok and means no weight\n this._weight = -1;\n return;\n }\n // Else weight must be in [0, 1] range\n this._weight = Math.min(Math.max(value, 0), 1.0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animatable.prototype, \"speedRatio\", {\n /**\n * Gets or sets the speed ratio to apply to the animatable (1.0 by default)\n */\n get: function () {\n return this._speedRatio;\n },\n set: function (value) {\n for (var index = 0; index < this._runtimeAnimations.length; index++) {\n var animation = this._runtimeAnimations[index];\n animation._prepareForSpeedRatioChange(value);\n }\n this._speedRatio = value;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n /**\n * Synchronize and normalize current Animatable with a source Animatable\n * This is useful when using animation weights and when animations are not of the same length\n * @param root defines the root Animatable to synchronize with\n * @returns the current Animatable\n */\n Animatable.prototype.syncWith = function (root) {\n this._syncRoot = root;\n if (root) {\n // Make sure this animatable will animate after the root\n var index = this._scene._activeAnimatables.indexOf(this);\n if (index > -1) {\n this._scene._activeAnimatables.splice(index, 1);\n this._scene._activeAnimatables.push(this);\n }\n }\n return this;\n };\n /**\n * Gets the list of runtime animations\n * @returns an array of RuntimeAnimation\n */\n Animatable.prototype.getAnimations = function () {\n return this._runtimeAnimations;\n };\n /**\n * Adds more animations to the current animatable\n * @param target defines the target of the animations\n * @param animations defines the new animations to add\n */\n Animatable.prototype.appendAnimations = function (target, animations) {\n for (var index = 0; index < animations.length; index++) {\n var animation = animations[index];\n this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));\n }\n };\n /**\n * Gets the source animation for a specific property\n * @param property defines the propertyu to look for\n * @returns null or the source animation for the given property\n */\n Animatable.prototype.getAnimationByTargetProperty = function (property) {\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = 0; index < runtimeAnimations.length; index++) {\n if (runtimeAnimations[index].animation.targetProperty === property) {\n return runtimeAnimations[index].animation;\n }\n }\n return null;\n };\n /**\n * Gets the runtime animation for a specific property\n * @param property defines the propertyu to look for\n * @returns null or the runtime animation for the given property\n */\n Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = 0; index < runtimeAnimations.length; index++) {\n if (runtimeAnimations[index].animation.targetProperty === property) {\n return runtimeAnimations[index];\n }\n }\n return null;\n };\n /**\n * Resets the animatable to its original state\n */\n Animatable.prototype.reset = function () {\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].reset(true);\n }\n this._localDelayOffset = null;\n this._pausedDelay = null;\n };\n /**\n * Allows the animatable to blend with current running animations\n * @see http://doc.babylonjs.com/babylon101/animations#animation-blending\n * @param blendingSpeed defines the blending speed to use\n */\n Animatable.prototype.enableBlending = function (blendingSpeed) {\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].animation.enableBlending = true;\n runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;\n }\n };\n /**\n * Disable animation blending\n * @see http://doc.babylonjs.com/babylon101/animations#animation-blending\n */\n Animatable.prototype.disableBlending = function () {\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].animation.enableBlending = false;\n }\n };\n /**\n * Jump directly to a given frame\n * @param frame defines the frame to jump to\n */\n Animatable.prototype.goToFrame = function (frame) {\n var runtimeAnimations = this._runtimeAnimations;\n if (runtimeAnimations[0]) {\n var fps = runtimeAnimations[0].animation.framePerSecond;\n var currentFrame = runtimeAnimations[0].currentFrame;\n var adjustTime = frame - currentFrame;\n var delay = adjustTime * 1000 / (fps * this.speedRatio);\n if (this._localDelayOffset === null) {\n this._localDelayOffset = 0;\n }\n this._localDelayOffset -= delay;\n }\n for (var index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].goToFrame(frame);\n }\n };\n /**\n * Pause the animation\n */\n Animatable.prototype.pause = function () {\n if (this._paused) {\n return;\n }\n this._paused = true;\n };\n /**\n * Restart the animation\n */\n Animatable.prototype.restart = function () {\n this._paused = false;\n };\n Animatable.prototype._raiseOnAnimationEnd = function () {\n if (this.onAnimationEnd) {\n this.onAnimationEnd();\n }\n this.onAnimationEndObservable.notifyObservers(this);\n };\n /**\n * Stop and delete the current animation\n * @param animationName defines a string used to only stop some of the runtime animations instead of all\n * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)\n */\n Animatable.prototype.stop = function (animationName, targetMask) {\n if (animationName || targetMask) {\n var idx = this._scene._activeAnimatables.indexOf(this);\n if (idx > -1) {\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = runtimeAnimations.length - 1; index >= 0; index--) {\n var runtimeAnimation = runtimeAnimations[index];\n if (animationName && runtimeAnimation.animation.name != animationName) {\n continue;\n }\n if (targetMask && !targetMask(runtimeAnimation.target)) {\n continue;\n }\n runtimeAnimation.dispose();\n runtimeAnimations.splice(index, 1);\n }\n if (runtimeAnimations.length == 0) {\n this._scene._activeAnimatables.splice(idx, 1);\n this._raiseOnAnimationEnd();\n }\n }\n }\n else {\n var index = this._scene._activeAnimatables.indexOf(this);\n if (index > -1) {\n this._scene._activeAnimatables.splice(index, 1);\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].dispose();\n }\n this._raiseOnAnimationEnd();\n }\n }\n };\n /**\n * Wait asynchronously for the animation to end\n * @returns a promise which will be fullfilled when the animation ends\n */\n Animatable.prototype.waitAsync = function () {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this.onAnimationEndObservable.add(function () {\n resolve(_this);\n }, undefined, undefined, _this, true);\n });\n };\n /** @hidden */\n Animatable.prototype._animate = function (delay) {\n if (this._paused) {\n this.animationStarted = false;\n if (this._pausedDelay === null) {\n this._pausedDelay = delay;\n }\n return true;\n }\n if (this._localDelayOffset === null) {\n this._localDelayOffset = delay;\n this._pausedDelay = null;\n }\n else if (this._pausedDelay !== null) {\n this._localDelayOffset += delay - this._pausedDelay;\n this._pausedDelay = null;\n }\n if (this._weight === 0) { // We consider that an animation with a weight === 0 is \"actively\" paused\n return true;\n }\n // Animating\n var running = false;\n var runtimeAnimations = this._runtimeAnimations;\n var index;\n for (index = 0; index < runtimeAnimations.length; index++) {\n var animation = runtimeAnimations[index];\n var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);\n running = running || isRunning;\n }\n this.animationStarted = running;\n if (!running) {\n if (this.disposeOnEnd) {\n // Remove from active animatables\n index = this._scene._activeAnimatables.indexOf(this);\n this._scene._activeAnimatables.splice(index, 1);\n // Dispose all runtime animations\n for (index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].dispose();\n }\n }\n this._raiseOnAnimationEnd();\n if (this.disposeOnEnd) {\n this.onAnimationEnd = null;\n this.onAnimationEndObservable.clear();\n }\n }\n return running;\n };\n return Animatable;\n }());\n BABYLON.Animatable = Animatable;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.animatable.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var EasingFunction = /** @class */ (function () {\n function EasingFunction() {\n // Properties\n this._easingMode = EasingFunction.EASINGMODE_EASEIN;\n }\n Object.defineProperty(EasingFunction, \"EASINGMODE_EASEIN\", {\n get: function () {\n return EasingFunction._EASINGMODE_EASEIN;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EasingFunction, \"EASINGMODE_EASEOUT\", {\n get: function () {\n return EasingFunction._EASINGMODE_EASEOUT;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EasingFunction, \"EASINGMODE_EASEINOUT\", {\n get: function () {\n return EasingFunction._EASINGMODE_EASEINOUT;\n },\n enumerable: true,\n configurable: true\n });\n EasingFunction.prototype.setEasingMode = function (easingMode) {\n var n = Math.min(Math.max(easingMode, 0), 2);\n this._easingMode = n;\n };\n EasingFunction.prototype.getEasingMode = function () {\n return this._easingMode;\n };\n EasingFunction.prototype.easeInCore = function (gradient) {\n throw new Error('You must implement this method');\n };\n EasingFunction.prototype.ease = function (gradient) {\n switch (this._easingMode) {\n case EasingFunction.EASINGMODE_EASEIN:\n return this.easeInCore(gradient);\n case EasingFunction.EASINGMODE_EASEOUT:\n return (1 - this.easeInCore(1 - gradient));\n }\n if (gradient >= 0.5) {\n return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);\n }\n return (this.easeInCore(gradient * 2) * 0.5);\n };\n //Statics\n EasingFunction._EASINGMODE_EASEIN = 0;\n EasingFunction._EASINGMODE_EASEOUT = 1;\n EasingFunction._EASINGMODE_EASEINOUT = 2;\n return EasingFunction;\n }());\n BABYLON.EasingFunction = EasingFunction;\n var CircleEase = /** @class */ (function (_super) {\n __extends(CircleEase, _super);\n function CircleEase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n CircleEase.prototype.easeInCore = function (gradient) {\n gradient = Math.max(0, Math.min(1, gradient));\n return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));\n };\n return CircleEase;\n }(EasingFunction));\n BABYLON.CircleEase = CircleEase;\n var BackEase = /** @class */ (function (_super) {\n __extends(BackEase, _super);\n function BackEase(amplitude) {\n if (amplitude === void 0) { amplitude = 1; }\n var _this = _super.call(this) || this;\n _this.amplitude = amplitude;\n return _this;\n }\n BackEase.prototype.easeInCore = function (gradient) {\n var num = Math.max(0, this.amplitude);\n return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));\n };\n return BackEase;\n }(EasingFunction));\n BABYLON.BackEase = BackEase;\n var BounceEase = /** @class */ (function (_super) {\n __extends(BounceEase, _super);\n function BounceEase(bounces, bounciness) {\n if (bounces === void 0) { bounces = 3; }\n if (bounciness === void 0) { bounciness = 2; }\n var _this = _super.call(this) || this;\n _this.bounces = bounces;\n _this.bounciness = bounciness;\n return _this;\n }\n BounceEase.prototype.easeInCore = function (gradient) {\n var y = Math.max(0.0, this.bounces);\n var bounciness = this.bounciness;\n if (bounciness <= 1.0) {\n bounciness = 1.001;\n }\n var num9 = Math.pow(bounciness, y);\n var num5 = 1.0 - bounciness;\n var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);\n var num15 = gradient * num4;\n var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);\n var num3 = Math.floor(num65);\n var num13 = num3 + 1.0;\n var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);\n var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);\n var num7 = (num8 + num12) * 0.5;\n var num6 = gradient - num7;\n var num2 = num7 - num8;\n return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));\n };\n return BounceEase;\n }(EasingFunction));\n BABYLON.BounceEase = BounceEase;\n var CubicEase = /** @class */ (function (_super) {\n __extends(CubicEase, _super);\n function CubicEase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n CubicEase.prototype.easeInCore = function (gradient) {\n return (gradient * gradient * gradient);\n };\n return CubicEase;\n }(EasingFunction));\n BABYLON.CubicEase = CubicEase;\n var ElasticEase = /** @class */ (function (_super) {\n __extends(ElasticEase, _super);\n function ElasticEase(oscillations, springiness) {\n if (oscillations === void 0) { oscillations = 3; }\n if (springiness === void 0) { springiness = 3; }\n var _this = _super.call(this) || this;\n _this.oscillations = oscillations;\n _this.springiness = springiness;\n return _this;\n }\n ElasticEase.prototype.easeInCore = function (gradient) {\n var num2;\n var num3 = Math.max(0.0, this.oscillations);\n var num = Math.max(0.0, this.springiness);\n if (num == 0) {\n num2 = gradient;\n }\n else {\n num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);\n }\n return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));\n };\n return ElasticEase;\n }(EasingFunction));\n BABYLON.ElasticEase = ElasticEase;\n var ExponentialEase = /** @class */ (function (_super) {\n __extends(ExponentialEase, _super);\n function ExponentialEase(exponent) {\n if (exponent === void 0) { exponent = 2; }\n var _this = _super.call(this) || this;\n _this.exponent = exponent;\n return _this;\n }\n ExponentialEase.prototype.easeInCore = function (gradient) {\n if (this.exponent <= 0) {\n return gradient;\n }\n return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));\n };\n return ExponentialEase;\n }(EasingFunction));\n BABYLON.ExponentialEase = ExponentialEase;\n var PowerEase = /** @class */ (function (_super) {\n __extends(PowerEase, _super);\n function PowerEase(power) {\n if (power === void 0) { power = 2; }\n var _this = _super.call(this) || this;\n _this.power = power;\n return _this;\n }\n PowerEase.prototype.easeInCore = function (gradient) {\n var y = Math.max(0.0, this.power);\n return Math.pow(gradient, y);\n };\n return PowerEase;\n }(EasingFunction));\n BABYLON.PowerEase = PowerEase;\n var QuadraticEase = /** @class */ (function (_super) {\n __extends(QuadraticEase, _super);\n function QuadraticEase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n QuadraticEase.prototype.easeInCore = function (gradient) {\n return (gradient * gradient);\n };\n return QuadraticEase;\n }(EasingFunction));\n BABYLON.QuadraticEase = QuadraticEase;\n var QuarticEase = /** @class */ (function (_super) {\n __extends(QuarticEase, _super);\n function QuarticEase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n QuarticEase.prototype.easeInCore = function (gradient) {\n return (gradient * gradient * gradient * gradient);\n };\n return QuarticEase;\n }(EasingFunction));\n BABYLON.QuarticEase = QuarticEase;\n var QuinticEase = /** @class */ (function (_super) {\n __extends(QuinticEase, _super);\n function QuinticEase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n QuinticEase.prototype.easeInCore = function (gradient) {\n return (gradient * gradient * gradient * gradient * gradient);\n };\n return QuinticEase;\n }(EasingFunction));\n BABYLON.QuinticEase = QuinticEase;\n var SineEase = /** @class */ (function (_super) {\n __extends(SineEase, _super);\n function SineEase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n SineEase.prototype.easeInCore = function (gradient) {\n return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));\n };\n return SineEase;\n }(EasingFunction));\n BABYLON.SineEase = SineEase;\n var BezierCurveEase = /** @class */ (function (_super) {\n __extends(BezierCurveEase, _super);\n function BezierCurveEase(x1, y1, x2, y2) {\n if (x1 === void 0) { x1 = 0; }\n if (y1 === void 0) { y1 = 0; }\n if (x2 === void 0) { x2 = 1; }\n if (y2 === void 0) { y2 = 1; }\n var _this = _super.call(this) || this;\n _this.x1 = x1;\n _this.y1 = y1;\n _this.x2 = x2;\n _this.y2 = y2;\n return _this;\n }\n BezierCurveEase.prototype.easeInCore = function (gradient) {\n return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);\n };\n return BezierCurveEase;\n }(EasingFunction));\n BABYLON.BezierCurveEase = BezierCurveEase;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.easing.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A Condition applied to an Action\n */\n var Condition = /** @class */ (function () {\n /**\n * Creates a new Condition\n * @param actionManager the manager of the action the condition is applied to\n */\n function Condition(actionManager) {\n this._actionManager = actionManager;\n }\n /**\n * Check if the current condition is valid\n * @returns a boolean\n */\n Condition.prototype.isValid = function () {\n return true;\n };\n /**\n * Internal only\n * @hidden\n */\n Condition.prototype._getProperty = function (propertyPath) {\n return this._actionManager._getProperty(propertyPath);\n };\n /**\n * Internal only\n * @hidden\n */\n Condition.prototype._getEffectiveTarget = function (target, propertyPath) {\n return this._actionManager._getEffectiveTarget(target, propertyPath);\n };\n /**\n * Serialize placeholder for child classes\n * @returns the serialized object\n */\n Condition.prototype.serialize = function () {\n };\n /**\n * Internal only\n * @hidden\n */\n Condition.prototype._serialize = function (serializedCondition) {\n return {\n type: 2,\n children: [],\n name: serializedCondition.name,\n properties: serializedCondition.properties\n };\n };\n return Condition;\n }());\n BABYLON.Condition = Condition;\n /**\n * Defines specific conditional operators as extensions of Condition\n */\n var ValueCondition = /** @class */ (function (_super) {\n __extends(ValueCondition, _super);\n /**\n * Creates a new ValueCondition\n * @param actionManager manager for the action the condition applies to\n * @param target for the action\n * @param propertyPath path to specify the property of the target the conditional operator uses\n * @param value the value compared by the conditional operator against the current value of the property\n * @param operator the conditional operator, default ValueCondition.IsEqual\n */\n function ValueCondition(actionManager, target, \n /** path to specify the property of the target the conditional operator uses */\n propertyPath, \n /** the value compared by the conditional operator against the current value of the property */\n value, \n /** the conditional operator, default ValueCondition.IsEqual */\n operator) {\n if (operator === void 0) { operator = ValueCondition.IsEqual; }\n var _this = _super.call(this, actionManager) || this;\n _this.propertyPath = propertyPath;\n _this.value = value;\n _this.operator = operator;\n _this._target = target;\n _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);\n _this._property = _this._getProperty(_this.propertyPath);\n return _this;\n }\n Object.defineProperty(ValueCondition, \"IsEqual\", {\n /**\n * returns the number for IsEqual\n */\n get: function () {\n return ValueCondition._IsEqual;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValueCondition, \"IsDifferent\", {\n /**\n * Returns the number for IsDifferent\n */\n get: function () {\n return ValueCondition._IsDifferent;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValueCondition, \"IsGreater\", {\n /**\n * Returns the number for IsGreater\n */\n get: function () {\n return ValueCondition._IsGreater;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValueCondition, \"IsLesser\", {\n /**\n * Returns the number for IsLesser\n */\n get: function () {\n return ValueCondition._IsLesser;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Compares the given value with the property value for the specified conditional operator\n * @returns the result of the comparison\n */\n ValueCondition.prototype.isValid = function () {\n switch (this.operator) {\n case ValueCondition.IsGreater:\n return this._effectiveTarget[this._property] > this.value;\n case ValueCondition.IsLesser:\n return this._effectiveTarget[this._property] < this.value;\n case ValueCondition.IsEqual:\n case ValueCondition.IsDifferent:\n var check;\n if (this.value.equals) {\n check = this.value.equals(this._effectiveTarget[this._property]);\n }\n else {\n check = this.value === this._effectiveTarget[this._property];\n }\n return this.operator === ValueCondition.IsEqual ? check : !check;\n }\n return false;\n };\n /**\n * Serialize the ValueCondition into a JSON compatible object\n * @returns serialization object\n */\n ValueCondition.prototype.serialize = function () {\n return this._serialize({\n name: \"ValueCondition\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: BABYLON.Action._SerializeValueAsString(this.value) },\n { name: \"operator\", value: ValueCondition.GetOperatorName(this.operator) }\n ]\n });\n };\n /**\n * Gets the name of the conditional operator for the ValueCondition\n * @param operator the conditional operator\n * @returns the name\n */\n ValueCondition.GetOperatorName = function (operator) {\n switch (operator) {\n case ValueCondition._IsEqual: return \"IsEqual\";\n case ValueCondition._IsDifferent: return \"IsDifferent\";\n case ValueCondition._IsGreater: return \"IsGreater\";\n case ValueCondition._IsLesser: return \"IsLesser\";\n default: return \"\";\n }\n };\n /**\n * Internal only\n * @hidden\n */\n ValueCondition._IsEqual = 0;\n /**\n * Internal only\n * @hidden\n */\n ValueCondition._IsDifferent = 1;\n /**\n * Internal only\n * @hidden\n */\n ValueCondition._IsGreater = 2;\n /**\n * Internal only\n * @hidden\n */\n ValueCondition._IsLesser = 3;\n return ValueCondition;\n }(Condition));\n BABYLON.ValueCondition = ValueCondition;\n /**\n * Defines a predicate condition as an extension of Condition\n */\n var PredicateCondition = /** @class */ (function (_super) {\n __extends(PredicateCondition, _super);\n /**\n * Creates a new PredicateCondition\n * @param actionManager manager for the action the condition applies to\n * @param predicate defines the predicate function used to validate the condition\n */\n function PredicateCondition(actionManager, \n /** defines the predicate function used to validate the condition */\n predicate) {\n var _this = _super.call(this, actionManager) || this;\n _this.predicate = predicate;\n return _this;\n }\n /**\n * @returns the validity of the predicate condition\n */\n PredicateCondition.prototype.isValid = function () {\n return this.predicate();\n };\n return PredicateCondition;\n }(Condition));\n BABYLON.PredicateCondition = PredicateCondition;\n /**\n * Defines a state condition as an extension of Condition\n */\n var StateCondition = /** @class */ (function (_super) {\n __extends(StateCondition, _super);\n /**\n * Creates a new StateCondition\n * @param actionManager manager for the action the condition applies to\n * @param target of the condition\n * @param value to compare with target state\n */\n function StateCondition(actionManager, target, value) {\n var _this = _super.call(this, actionManager) || this;\n _this.value = value;\n _this._target = target;\n return _this;\n }\n /**\n * @returns the validity of the state\n */\n StateCondition.prototype.isValid = function () {\n return this._target.state === this.value;\n };\n /**\n * Serialize the StateCondition into a JSON compatible object\n * @returns serialization object\n */\n StateCondition.prototype.serialize = function () {\n return this._serialize({\n name: \"StateCondition\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"value\", value: this.value }\n ]\n });\n };\n return StateCondition;\n }(Condition));\n BABYLON.StateCondition = StateCondition;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.condition.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The action to be carried out following a trigger\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions\n */\n var Action = /** @class */ (function () {\n /**\n * Creates a new Action\n * @param triggerOptions the trigger, with or without parameters, for the action\n * @param condition an optional determinant of action\n */\n function Action(\n /** the trigger, with or without parameters, for the action */\n triggerOptions, condition) {\n this.triggerOptions = triggerOptions;\n /**\n * An event triggered prior to action being executed.\n */\n this.onBeforeExecuteObservable = new BABYLON.Observable();\n if (triggerOptions.parameter) {\n this.trigger = triggerOptions.trigger;\n this._triggerParameter = triggerOptions.parameter;\n }\n else {\n this.trigger = triggerOptions;\n }\n this._nextActiveAction = this;\n this._condition = condition;\n }\n /**\n * Internal only\n * @hidden\n */\n Action.prototype._prepare = function () {\n };\n /**\n * Gets the trigger parameters\n * @returns the trigger parameters\n */\n Action.prototype.getTriggerParameter = function () {\n return this._triggerParameter;\n };\n /**\n * Internal only - executes current action event\n * @hidden\n */\n Action.prototype._executeCurrent = function (evt) {\n if (this._nextActiveAction._condition) {\n var condition = this._nextActiveAction._condition;\n var currentRenderId = this._actionManager.getScene().getRenderId();\n // We cache the current evaluation for the current frame\n if (condition._evaluationId === currentRenderId) {\n if (!condition._currentResult) {\n return;\n }\n }\n else {\n condition._evaluationId = currentRenderId;\n if (!condition.isValid()) {\n condition._currentResult = false;\n return;\n }\n condition._currentResult = true;\n }\n }\n this.onBeforeExecuteObservable.notifyObservers(this);\n this._nextActiveAction.execute(evt);\n this.skipToNextActiveAction();\n };\n /**\n * Execute placeholder for child classes\n * @param evt optional action event\n */\n Action.prototype.execute = function (evt) {\n };\n /**\n * Skips to next active action\n */\n Action.prototype.skipToNextActiveAction = function () {\n if (this._nextActiveAction._child) {\n if (!this._nextActiveAction._child._actionManager) {\n this._nextActiveAction._child._actionManager = this._actionManager;\n }\n this._nextActiveAction = this._nextActiveAction._child;\n }\n else {\n this._nextActiveAction = this;\n }\n };\n /**\n * Adds action to chain of actions, may be a DoNothingAction\n * @param action defines the next action to execute\n * @returns The action passed in\n * @see https://www.babylonjs-playground.com/#1T30HR#0\n */\n Action.prototype.then = function (action) {\n this._child = action;\n action._actionManager = this._actionManager;\n action._prepare();\n return action;\n };\n /**\n * Internal only\n * @hidden\n */\n Action.prototype._getProperty = function (propertyPath) {\n return this._actionManager._getProperty(propertyPath);\n };\n /**\n * Internal only\n * @hidden\n */\n Action.prototype._getEffectiveTarget = function (target, propertyPath) {\n return this._actionManager._getEffectiveTarget(target, propertyPath);\n };\n /**\n * Serialize placeholder for child classes\n * @param parent of child\n * @returns the serialized object\n */\n Action.prototype.serialize = function (parent) {\n };\n /**\n * Internal only called by serialize\n * @hidden\n */\n Action.prototype._serialize = function (serializedAction, parent) {\n var serializationObject = {\n type: 1,\n children: [],\n name: serializedAction.name,\n properties: serializedAction.properties || []\n };\n // Serialize child\n if (this._child) {\n this._child.serialize(serializationObject);\n }\n // Check if \"this\" has a condition\n if (this._condition) {\n var serializedCondition = this._condition.serialize();\n serializedCondition.children.push(serializationObject);\n if (parent) {\n parent.children.push(serializedCondition);\n }\n return serializedCondition;\n }\n if (parent) {\n parent.children.push(serializationObject);\n }\n return serializationObject;\n };\n /**\n * Internal only\n * @hidden\n */\n Action._SerializeValueAsString = function (value) {\n if (typeof value === \"number\") {\n return value.toString();\n }\n if (typeof value === \"boolean\") {\n return value ? \"true\" : \"false\";\n }\n if (value instanceof BABYLON.Vector2) {\n return value.x + \", \" + value.y;\n }\n if (value instanceof BABYLON.Vector3) {\n return value.x + \", \" + value.y + \", \" + value.z;\n }\n if (value instanceof BABYLON.Color3) {\n return value.r + \", \" + value.g + \", \" + value.b;\n }\n if (value instanceof BABYLON.Color4) {\n return value.r + \", \" + value.g + \", \" + value.b + \", \" + value.a;\n }\n return value; // string\n };\n /**\n * Internal only\n * @hidden\n */\n Action._GetTargetProperty = function (target) {\n return {\n name: \"target\",\n targetType: target instanceof BABYLON.Mesh ? \"MeshProperties\"\n : target instanceof BABYLON.Light ? \"LightProperties\"\n : target instanceof BABYLON.Camera ? \"CameraProperties\"\n : \"SceneProperties\",\n value: target instanceof BABYLON.Scene ? \"Scene\" : target.name\n };\n };\n return Action;\n }());\n BABYLON.Action = Action;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.action.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * ActionEvent is the event being sent when an action is triggered.\n */\n var ActionEvent = /** @class */ (function () {\n /**\n * Creates a new ActionEvent\n * @param source The mesh or sprite that triggered the action\n * @param pointerX The X mouse cursor position at the time of the event\n * @param pointerY The Y mouse cursor position at the time of the event\n * @param meshUnderPointer The mesh that is currently pointed at (can be null)\n * @param sourceEvent the original (browser) event that triggered the ActionEvent\n * @param additionalData additional data for the event\n */\n function ActionEvent(\n /** The mesh or sprite that triggered the action */\n source, \n /** The X mouse cursor position at the time of the event */\n pointerX, \n /** The Y mouse cursor position at the time of the event */\n pointerY, \n /** The mesh that is currently pointed at (can be null) */\n meshUnderPointer, \n /** the original (browser) event that triggered the ActionEvent */\n sourceEvent, \n /** additional data for the event */\n additionalData) {\n this.source = source;\n this.pointerX = pointerX;\n this.pointerY = pointerY;\n this.meshUnderPointer = meshUnderPointer;\n this.sourceEvent = sourceEvent;\n this.additionalData = additionalData;\n }\n /**\n * Helper function to auto-create an ActionEvent from a source mesh.\n * @param source The source mesh that triggered the event\n * @param evt The original (browser) event\n * @param additionalData additional data for the event\n * @returns the new ActionEvent\n */\n ActionEvent.CreateNew = function (source, evt, additionalData) {\n var scene = source.getScene();\n return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);\n };\n /**\n * Helper function to auto-create an ActionEvent from a source sprite\n * @param source The source sprite that triggered the event\n * @param scene Scene associated with the sprite\n * @param evt The original (browser) event\n * @param additionalData additional data for the event\n * @returns the new ActionEvent\n */\n ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {\n return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);\n };\n /**\n * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew\n * @param scene the scene where the event occurred\n * @param evt The original (browser) event\n * @returns the new ActionEvent\n */\n ActionEvent.CreateNewFromScene = function (scene, evt) {\n return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);\n };\n /**\n * Helper function to auto-create an ActionEvent from a primitive\n * @param prim defines the target primitive\n * @param pointerPos defines the pointer position\n * @param evt The original (browser) event\n * @param additionalData additional data for the event\n * @returns the new ActionEvent\n */\n ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {\n return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);\n };\n return ActionEvent;\n }());\n BABYLON.ActionEvent = ActionEvent;\n /**\n * Action Manager manages all events to be triggered on a given mesh or the global scene.\n * A single scene can have many Action Managers to handle predefined actions on specific meshes.\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions\n */\n var ActionManager = /** @class */ (function () {\n /**\n * Creates a new action manager\n * @param scene defines the hosting scene\n */\n function ActionManager(scene) {\n // Members\n /** Gets the list of actions */\n this.actions = new Array();\n /** Gets the cursor to use when hovering items */\n this.hoverCursor = '';\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n scene.actionManagers.push(this);\n }\n Object.defineProperty(ActionManager, \"NothingTrigger\", {\n /**\n * Nothing\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._NothingTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnPickTrigger\", {\n /**\n * On pick\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnPickTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnLeftPickTrigger\", {\n /**\n * On left pick\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnLeftPickTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnRightPickTrigger\", {\n /**\n * On right pick\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnRightPickTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnCenterPickTrigger\", {\n /**\n * On center pick\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnCenterPickTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnPickDownTrigger\", {\n /**\n * On pick down\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnPickDownTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnDoublePickTrigger\", {\n /**\n * On double pick\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnDoublePickTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnPickUpTrigger\", {\n /**\n * On pick up\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnPickUpTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnPickOutTrigger\", {\n /**\n * On pick out.\n * This trigger will only be raised if you also declared a OnPickDown\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnPickOutTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnLongPressTrigger\", {\n /**\n * On long press\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnLongPressTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnPointerOverTrigger\", {\n /**\n * On pointer over\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnPointerOverTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnPointerOutTrigger\", {\n /**\n * On pointer out\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnPointerOutTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnEveryFrameTrigger\", {\n /**\n * On every frame\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnEveryFrameTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnIntersectionEnterTrigger\", {\n /**\n * On intersection enter\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnIntersectionEnterTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnIntersectionExitTrigger\", {\n /**\n * On intersection exit\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnIntersectionExitTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnKeyDownTrigger\", {\n /**\n * On key down\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnKeyDownTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnKeyUpTrigger\", {\n /**\n * On key up\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnKeyUpTrigger;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n /**\n * Releases all associated resources\n */\n ActionManager.prototype.dispose = function () {\n var index = this._scene.actionManagers.indexOf(this);\n for (var i = 0; i < this.actions.length; i++) {\n var action = this.actions[i];\n ActionManager.Triggers[action.trigger]--;\n if (ActionManager.Triggers[action.trigger] === 0) {\n delete ActionManager.Triggers[action.trigger];\n }\n }\n if (index > -1) {\n this._scene.actionManagers.splice(index, 1);\n }\n };\n /**\n * Gets hosting scene\n * @returns the hosting scene\n */\n ActionManager.prototype.getScene = function () {\n return this._scene;\n };\n /**\n * Does this action manager handles actions of any of the given triggers\n * @param triggers defines the triggers to be tested\n * @return a boolean indicating whether one (or more) of the triggers is handled\n */\n ActionManager.prototype.hasSpecificTriggers = function (triggers) {\n for (var index = 0; index < this.actions.length; index++) {\n var action = this.actions[index];\n if (triggers.indexOf(action.trigger) > -1) {\n return true;\n }\n }\n return false;\n };\n /**\n * Does this action manager handles actions of a given trigger\n * @param trigger defines the trigger to be tested\n * @param parameterPredicate defines an optional predicate to filter triggers by parameter\n * @return whether the trigger is handled\n */\n ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {\n for (var index = 0; index < this.actions.length; index++) {\n var action = this.actions[index];\n if (action.trigger === trigger) {\n if (parameterPredicate) {\n if (parameterPredicate(action.getTriggerParameter())) {\n return true;\n }\n }\n else {\n return true;\n }\n }\n }\n return false;\n };\n Object.defineProperty(ActionManager.prototype, \"hasPointerTriggers\", {\n /**\n * Does this action manager has pointer triggers\n */\n get: function () {\n for (var index = 0; index < this.actions.length; index++) {\n var action = this.actions[index];\n if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {\n return true;\n }\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager.prototype, \"hasPickTriggers\", {\n /**\n * Does this action manager has pick triggers\n */\n get: function () {\n for (var index = 0; index < this.actions.length; index++) {\n var action = this.actions[index];\n if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {\n return true;\n }\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"HasTriggers\", {\n /**\n * Does exist one action manager with at least one trigger\n **/\n get: function () {\n for (var t in ActionManager.Triggers) {\n if (ActionManager.Triggers.hasOwnProperty(t)) {\n return true;\n }\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"HasPickTriggers\", {\n /**\n * Does exist one action manager with at least one pick trigger\n **/\n get: function () {\n for (var t in ActionManager.Triggers) {\n if (ActionManager.Triggers.hasOwnProperty(t)) {\n var t_int = parseInt(t);\n if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {\n return true;\n }\n }\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Does exist one action manager that handles actions of a given trigger\n * @param trigger defines the trigger to be tested\n * @return a boolean indicating whether the trigger is handeled by at least one action manager\n **/\n ActionManager.HasSpecificTrigger = function (trigger) {\n for (var t in ActionManager.Triggers) {\n if (ActionManager.Triggers.hasOwnProperty(t)) {\n var t_int = parseInt(t);\n if (t_int === trigger) {\n return true;\n }\n }\n }\n return false;\n };\n /**\n * Registers an action to this action manager\n * @param action defines the action to be registered\n * @return the action amended (prepared) after registration\n */\n ActionManager.prototype.registerAction = function (action) {\n if (action.trigger === ActionManager.OnEveryFrameTrigger) {\n if (this.getScene().actionManager !== this) {\n BABYLON.Tools.Warn(\"OnEveryFrameTrigger can only be used with scene.actionManager\");\n return null;\n }\n }\n this.actions.push(action);\n if (ActionManager.Triggers[action.trigger]) {\n ActionManager.Triggers[action.trigger]++;\n }\n else {\n ActionManager.Triggers[action.trigger] = 1;\n }\n action._actionManager = this;\n action._prepare();\n return action;\n };\n /**\n * Unregisters an action to this action manager\n * @param action defines the action to be unregistered\n * @return a boolean indicating whether the action has been unregistered\n */\n ActionManager.prototype.unregisterAction = function (action) {\n var index = this.actions.indexOf(action);\n if (index !== -1) {\n this.actions.splice(index, 1);\n ActionManager.Triggers[action.trigger] -= 1;\n if (ActionManager.Triggers[action.trigger] === 0) {\n delete ActionManager.Triggers[action.trigger];\n }\n delete action._actionManager;\n return true;\n }\n return false;\n };\n /**\n * Process a specific trigger\n * @param trigger defines the trigger to process\n * @param evt defines the event details to be processed\n */\n ActionManager.prototype.processTrigger = function (trigger, evt) {\n for (var index = 0; index < this.actions.length; index++) {\n var action = this.actions[index];\n if (action.trigger === trigger) {\n if (evt) {\n if (trigger === ActionManager.OnKeyUpTrigger\n || trigger === ActionManager.OnKeyDownTrigger) {\n var parameter = action.getTriggerParameter();\n if (parameter && parameter !== evt.sourceEvent.keyCode) {\n if (!parameter.toLowerCase) {\n continue;\n }\n var lowerCase = parameter.toLowerCase();\n if (lowerCase !== evt.sourceEvent.key) {\n var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;\n var actualkey = String.fromCharCode(unicode).toLowerCase();\n if (actualkey !== lowerCase) {\n continue;\n }\n }\n }\n }\n }\n action._executeCurrent(evt);\n }\n }\n };\n /** @hidden */\n ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {\n var properties = propertyPath.split(\".\");\n for (var index = 0; index < properties.length - 1; index++) {\n target = target[properties[index]];\n }\n return target;\n };\n /** @hidden */\n ActionManager.prototype._getProperty = function (propertyPath) {\n var properties = propertyPath.split(\".\");\n return properties[properties.length - 1];\n };\n /**\n * Serialize this manager to a JSON object\n * @param name defines the property name to store this manager\n * @returns a JSON representation of this manager\n */\n ActionManager.prototype.serialize = function (name) {\n var root = {\n children: new Array(),\n name: name,\n type: 3,\n properties: new Array() // Empty for root but required\n };\n for (var i = 0; i < this.actions.length; i++) {\n var triggerObject = {\n type: 0,\n children: new Array(),\n name: ActionManager.GetTriggerName(this.actions[i].trigger),\n properties: new Array()\n };\n var triggerOptions = this.actions[i].triggerOptions;\n if (triggerOptions && typeof triggerOptions !== \"number\") {\n if (triggerOptions.parameter instanceof BABYLON.Node) {\n triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));\n }\n else {\n var parameter = {};\n BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, [\"mesh\"]);\n if (triggerOptions.parameter.mesh) {\n parameter._meshId = triggerOptions.parameter.mesh.id;\n }\n triggerObject.properties.push({ name: \"parameter\", targetType: null, value: parameter });\n }\n }\n // Serialize child action, recursively\n this.actions[i].serialize(triggerObject);\n // Add serialized trigger\n root.children.push(triggerObject);\n }\n return root;\n };\n /**\n * Creates a new ActionManager from a JSON data\n * @param parsedActions defines the JSON data to read from\n * @param object defines the hosting mesh\n * @param scene defines the hosting scene\n */\n ActionManager.Parse = function (parsedActions, object, scene) {\n var actionManager = new ActionManager(scene);\n if (object === null)\n scene.actionManager = actionManager;\n else\n object.actionManager = actionManager;\n // instanciate a new object\n var instanciate = function (name, params) {\n // TODO: We will need to find a solution for the next line when using commonjs / es6 .\n var newInstance = Object.create(BABYLON.Tools.Instantiate(\"BABYLON.\" + name).prototype);\n newInstance.constructor.apply(newInstance, params);\n return newInstance;\n };\n var parseParameter = function (name, value, target, propertyPath) {\n if (propertyPath === null) {\n // String, boolean or float\n var floatValue = parseFloat(value);\n if (value === \"true\" || value === \"false\")\n return value === \"true\";\n else\n return isNaN(floatValue) ? value : floatValue;\n }\n var effectiveTarget = propertyPath.split(\".\");\n var values = value.split(\",\");\n // Get effective Target\n for (var i = 0; i < effectiveTarget.length; i++) {\n target = target[effectiveTarget[i]];\n }\n // Return appropriate value with its type\n if (typeof (target) === \"boolean\")\n return values[0] === \"true\";\n if (typeof (target) === \"string\")\n return values[0];\n // Parameters with multiple values such as Vector3 etc.\n var split = new Array();\n for (var i = 0; i < values.length; i++)\n split.push(parseFloat(values[i]));\n if (target instanceof BABYLON.Vector3)\n return BABYLON.Vector3.FromArray(split);\n if (target instanceof BABYLON.Vector4)\n return BABYLON.Vector4.FromArray(split);\n if (target instanceof BABYLON.Color3)\n return BABYLON.Color3.FromArray(split);\n if (target instanceof BABYLON.Color4)\n return BABYLON.Color4.FromArray(split);\n return parseFloat(values[0]);\n };\n // traverse graph per trigger\n var traverse = function (parsedAction, trigger, condition, action, combineArray) {\n if (combineArray === void 0) { combineArray = null; }\n if (parsedAction.detached)\n return;\n var parameters = new Array();\n var target = null;\n var propertyPath = null;\n var combine = parsedAction.combine && parsedAction.combine.length > 0;\n // Parameters\n if (parsedAction.type === 2)\n parameters.push(actionManager);\n else\n parameters.push(trigger);\n if (combine) {\n var actions = new Array();\n for (var j = 0; j < parsedAction.combine.length; j++) {\n traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);\n }\n parameters.push(actions);\n }\n else {\n for (var i = 0; i < parsedAction.properties.length; i++) {\n var value = parsedAction.properties[i].value;\n var name = parsedAction.properties[i].name;\n var targetType = parsedAction.properties[i].targetType;\n if (name === \"target\")\n if (targetType !== null && targetType === \"SceneProperties\")\n value = target = scene;\n else\n value = target = scene.getNodeByName(value);\n else if (name === \"parent\")\n value = scene.getNodeByName(value);\n else if (name === \"sound\")\n value = scene.getSoundByName(value);\n else if (name !== \"propertyPath\") {\n if (parsedAction.type === 2 && name === \"operator\")\n value = BABYLON.ValueCondition[value];\n else\n value = parseParameter(name, value, target, name === \"value\" ? propertyPath : null);\n }\n else {\n propertyPath = value;\n }\n parameters.push(value);\n }\n }\n if (combineArray === null) {\n parameters.push(condition);\n }\n else {\n parameters.push(null);\n }\n // If interpolate value action\n if (parsedAction.name === \"InterpolateValueAction\") {\n var param = parameters[parameters.length - 2];\n parameters[parameters.length - 1] = param;\n parameters[parameters.length - 2] = condition;\n }\n // Action or condition(s) and not CombineAction\n var newAction = instanciate(parsedAction.name, parameters);\n if (newAction instanceof BABYLON.Condition && condition !== null) {\n var nothing = new BABYLON.DoNothingAction(trigger, condition);\n if (action)\n action.then(nothing);\n else\n actionManager.registerAction(nothing);\n action = nothing;\n }\n if (combineArray === null) {\n if (newAction instanceof BABYLON.Condition) {\n condition = newAction;\n newAction = action;\n }\n else {\n condition = null;\n if (action)\n action.then(newAction);\n else\n actionManager.registerAction(newAction);\n }\n }\n else {\n combineArray.push(newAction);\n }\n for (var i = 0; i < parsedAction.children.length; i++)\n traverse(parsedAction.children[i], trigger, condition, newAction, null);\n };\n // triggers\n for (var i = 0; i < parsedActions.children.length; i++) {\n var triggerParams;\n var trigger = parsedActions.children[i];\n if (trigger.properties.length > 0) {\n var param = trigger.properties[0].value;\n var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);\n if (value._meshId) {\n value.mesh = scene.getMeshByID(value._meshId);\n }\n triggerParams = { trigger: ActionManager[trigger.name], parameter: value };\n }\n else\n triggerParams = ActionManager[trigger.name];\n for (var j = 0; j < trigger.children.length; j++) {\n if (!trigger.detached)\n traverse(trigger.children[j], triggerParams, null, null);\n }\n }\n };\n /**\n * Get a trigger name by index\n * @param trigger defines the trigger index\n * @returns a trigger name\n */\n ActionManager.GetTriggerName = function (trigger) {\n switch (trigger) {\n case 0: return \"NothingTrigger\";\n case 1: return \"OnPickTrigger\";\n case 2: return \"OnLeftPickTrigger\";\n case 3: return \"OnRightPickTrigger\";\n case 4: return \"OnCenterPickTrigger\";\n case 5: return \"OnPickDownTrigger\";\n case 6: return \"OnPickUpTrigger\";\n case 7: return \"OnLongPressTrigger\";\n case 8: return \"OnPointerOverTrigger\";\n case 9: return \"OnPointerOutTrigger\";\n case 10: return \"OnEveryFrameTrigger\";\n case 11: return \"OnIntersectionEnterTrigger\";\n case 12: return \"OnIntersectionExitTrigger\";\n case 13: return \"OnKeyDownTrigger\";\n case 14: return \"OnKeyUpTrigger\";\n case 15: return \"OnPickOutTrigger\";\n default: return \"\";\n }\n };\n // Statics\n ActionManager._NothingTrigger = 0;\n ActionManager._OnPickTrigger = 1;\n ActionManager._OnLeftPickTrigger = 2;\n ActionManager._OnRightPickTrigger = 3;\n ActionManager._OnCenterPickTrigger = 4;\n ActionManager._OnPickDownTrigger = 5;\n ActionManager._OnDoublePickTrigger = 6;\n ActionManager._OnPickUpTrigger = 7;\n ActionManager._OnLongPressTrigger = 8;\n ActionManager._OnPointerOverTrigger = 9;\n ActionManager._OnPointerOutTrigger = 10;\n ActionManager._OnEveryFrameTrigger = 11;\n ActionManager._OnIntersectionEnterTrigger = 12;\n ActionManager._OnIntersectionExitTrigger = 13;\n ActionManager._OnKeyDownTrigger = 14;\n ActionManager._OnKeyUpTrigger = 15;\n ActionManager._OnPickOutTrigger = 16;\n /** Gets the list of active triggers */\n ActionManager.Triggers = {};\n return ActionManager;\n }());\n BABYLON.ActionManager = ActionManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.actionManager.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var InterpolateValueAction = /** @class */ (function (_super) {\n __extends(InterpolateValueAction, _super);\n function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {\n if (duration === void 0) { duration = 1000; }\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.propertyPath = propertyPath;\n _this.value = value;\n _this.duration = duration;\n _this.stopOtherAnimations = stopOtherAnimations;\n _this.onInterpolationDone = onInterpolationDone;\n _this.onInterpolationDoneObservable = new BABYLON.Observable();\n _this._target = _this._effectiveTarget = target;\n return _this;\n }\n InterpolateValueAction.prototype._prepare = function () {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n };\n InterpolateValueAction.prototype.execute = function () {\n var _this = this;\n var scene = this._actionManager.getScene();\n var keys = [\n {\n frame: 0,\n value: this._effectiveTarget[this._property]\n }, {\n frame: 100,\n value: this.value\n }\n ];\n var dataType;\n if (typeof this.value === \"number\") {\n dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;\n }\n else if (this.value instanceof BABYLON.Color3) {\n dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;\n }\n else if (this.value instanceof BABYLON.Vector3) {\n dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;\n }\n else if (this.value instanceof BABYLON.Matrix) {\n dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;\n }\n else if (this.value instanceof BABYLON.Quaternion) {\n dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;\n }\n else {\n BABYLON.Tools.Warn(\"InterpolateValueAction: Unsupported type (\" + typeof this.value + \")\");\n return;\n }\n var animation = new BABYLON.Animation(\"InterpolateValueAction\", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n animation.setKeys(keys);\n if (this.stopOtherAnimations) {\n scene.stopAnimation(this._effectiveTarget);\n }\n var wrapper = function () {\n _this.onInterpolationDoneObservable.notifyObservers(_this);\n if (_this.onInterpolationDone) {\n _this.onInterpolationDone();\n }\n };\n scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);\n };\n InterpolateValueAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"InterpolateValueAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: BABYLON.Action._SerializeValueAsString(this.value) },\n { name: \"duration\", value: BABYLON.Action._SerializeValueAsString(this.duration) },\n { name: \"stopOtherAnimations\", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }\n ]\n }, parent);\n };\n return InterpolateValueAction;\n }(BABYLON.Action));\n BABYLON.InterpolateValueAction = InterpolateValueAction;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.interpolateValueAction.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var SwitchBooleanAction = /** @class */ (function (_super) {\n __extends(SwitchBooleanAction, _super);\n function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.propertyPath = propertyPath;\n _this._target = _this._effectiveTarget = target;\n return _this;\n }\n SwitchBooleanAction.prototype._prepare = function () {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n };\n SwitchBooleanAction.prototype.execute = function () {\n this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];\n };\n SwitchBooleanAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"SwitchBooleanAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath }\n ]\n }, parent);\n };\n return SwitchBooleanAction;\n }(BABYLON.Action));\n BABYLON.SwitchBooleanAction = SwitchBooleanAction;\n var SetStateAction = /** @class */ (function (_super) {\n __extends(SetStateAction, _super);\n function SetStateAction(triggerOptions, target, value, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.value = value;\n _this._target = target;\n return _this;\n }\n SetStateAction.prototype.execute = function () {\n this._target.state = this.value;\n };\n SetStateAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"SetStateAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"value\", value: this.value }\n ]\n }, parent);\n };\n return SetStateAction;\n }(BABYLON.Action));\n BABYLON.SetStateAction = SetStateAction;\n var SetValueAction = /** @class */ (function (_super) {\n __extends(SetValueAction, _super);\n function SetValueAction(triggerOptions, target, propertyPath, value, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.propertyPath = propertyPath;\n _this.value = value;\n _this._target = _this._effectiveTarget = target;\n return _this;\n }\n SetValueAction.prototype._prepare = function () {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n };\n SetValueAction.prototype.execute = function () {\n this._effectiveTarget[this._property] = this.value;\n if (this._target.markAsDirty) {\n this._target.markAsDirty(this._property);\n }\n };\n SetValueAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"SetValueAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: BABYLON.Action._SerializeValueAsString(this.value) }\n ]\n }, parent);\n };\n return SetValueAction;\n }(BABYLON.Action));\n BABYLON.SetValueAction = SetValueAction;\n var IncrementValueAction = /** @class */ (function (_super) {\n __extends(IncrementValueAction, _super);\n function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.propertyPath = propertyPath;\n _this.value = value;\n _this._target = _this._effectiveTarget = target;\n return _this;\n }\n IncrementValueAction.prototype._prepare = function () {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n if (typeof this._effectiveTarget[this._property] !== \"number\") {\n BABYLON.Tools.Warn(\"Warning: IncrementValueAction can only be used with number values\");\n }\n };\n IncrementValueAction.prototype.execute = function () {\n this._effectiveTarget[this._property] += this.value;\n if (this._target.markAsDirty) {\n this._target.markAsDirty(this._property);\n }\n };\n IncrementValueAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"IncrementValueAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: BABYLON.Action._SerializeValueAsString(this.value) }\n ]\n }, parent);\n };\n return IncrementValueAction;\n }(BABYLON.Action));\n BABYLON.IncrementValueAction = IncrementValueAction;\n var PlayAnimationAction = /** @class */ (function (_super) {\n __extends(PlayAnimationAction, _super);\n function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.from = from;\n _this.to = to;\n _this.loop = loop;\n _this._target = target;\n return _this;\n }\n PlayAnimationAction.prototype._prepare = function () {\n };\n PlayAnimationAction.prototype.execute = function () {\n var scene = this._actionManager.getScene();\n scene.beginAnimation(this._target, this.from, this.to, this.loop);\n };\n PlayAnimationAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"PlayAnimationAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"from\", value: String(this.from) },\n { name: \"to\", value: String(this.to) },\n { name: \"loop\", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }\n ]\n }, parent);\n };\n return PlayAnimationAction;\n }(BABYLON.Action));\n BABYLON.PlayAnimationAction = PlayAnimationAction;\n var StopAnimationAction = /** @class */ (function (_super) {\n __extends(StopAnimationAction, _super);\n function StopAnimationAction(triggerOptions, target, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this._target = target;\n return _this;\n }\n StopAnimationAction.prototype._prepare = function () {\n };\n StopAnimationAction.prototype.execute = function () {\n var scene = this._actionManager.getScene();\n scene.stopAnimation(this._target);\n };\n StopAnimationAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"StopAnimationAction\",\n properties: [BABYLON.Action._GetTargetProperty(this._target)]\n }, parent);\n };\n return StopAnimationAction;\n }(BABYLON.Action));\n BABYLON.StopAnimationAction = StopAnimationAction;\n var DoNothingAction = /** @class */ (function (_super) {\n __extends(DoNothingAction, _super);\n function DoNothingAction(triggerOptions, condition) {\n if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }\n return _super.call(this, triggerOptions, condition) || this;\n }\n DoNothingAction.prototype.execute = function () {\n };\n DoNothingAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"DoNothingAction\",\n properties: []\n }, parent);\n };\n return DoNothingAction;\n }(BABYLON.Action));\n BABYLON.DoNothingAction = DoNothingAction;\n var CombineAction = /** @class */ (function (_super) {\n __extends(CombineAction, _super);\n function CombineAction(triggerOptions, children, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.children = children;\n return _this;\n }\n CombineAction.prototype._prepare = function () {\n for (var index = 0; index < this.children.length; index++) {\n this.children[index]._actionManager = this._actionManager;\n this.children[index]._prepare();\n }\n };\n CombineAction.prototype.execute = function (evt) {\n for (var index = 0; index < this.children.length; index++) {\n this.children[index].execute(evt);\n }\n };\n CombineAction.prototype.serialize = function (parent) {\n var serializationObject = _super.prototype._serialize.call(this, {\n name: \"CombineAction\",\n properties: [],\n combine: []\n }, parent);\n for (var i = 0; i < this.children.length; i++) {\n serializationObject.combine.push(this.children[i].serialize(null));\n }\n return serializationObject;\n };\n return CombineAction;\n }(BABYLON.Action));\n BABYLON.CombineAction = CombineAction;\n var ExecuteCodeAction = /** @class */ (function (_super) {\n __extends(ExecuteCodeAction, _super);\n function ExecuteCodeAction(triggerOptions, func, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.func = func;\n return _this;\n }\n ExecuteCodeAction.prototype.execute = function (evt) {\n this.func(evt);\n };\n return ExecuteCodeAction;\n }(BABYLON.Action));\n BABYLON.ExecuteCodeAction = ExecuteCodeAction;\n var SetParentAction = /** @class */ (function (_super) {\n __extends(SetParentAction, _super);\n function SetParentAction(triggerOptions, target, parent, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this._target = target;\n _this._parent = parent;\n return _this;\n }\n SetParentAction.prototype._prepare = function () {\n };\n SetParentAction.prototype.execute = function () {\n if (this._target.parent === this._parent) {\n return;\n }\n var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();\n invertParentWorldMatrix.invert();\n this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);\n this._target.parent = this._parent;\n };\n SetParentAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"SetParentAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n BABYLON.Action._GetTargetProperty(this._parent),\n ]\n }, parent);\n };\n return SetParentAction;\n }(BABYLON.Action));\n BABYLON.SetParentAction = SetParentAction;\n var PlaySoundAction = /** @class */ (function (_super) {\n __extends(PlaySoundAction, _super);\n function PlaySoundAction(triggerOptions, sound, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this._sound = sound;\n return _this;\n }\n PlaySoundAction.prototype._prepare = function () {\n };\n PlaySoundAction.prototype.execute = function () {\n if (this._sound !== undefined)\n this._sound.play();\n };\n PlaySoundAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"PlaySoundAction\",\n properties: [{ name: \"sound\", value: this._sound.name }]\n }, parent);\n };\n return PlaySoundAction;\n }(BABYLON.Action));\n BABYLON.PlaySoundAction = PlaySoundAction;\n var StopSoundAction = /** @class */ (function (_super) {\n __extends(StopSoundAction, _super);\n function StopSoundAction(triggerOptions, sound, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this._sound = sound;\n return _this;\n }\n StopSoundAction.prototype._prepare = function () {\n };\n StopSoundAction.prototype.execute = function () {\n if (this._sound !== undefined)\n this._sound.stop();\n };\n StopSoundAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"StopSoundAction\",\n properties: [{ name: \"sound\", value: this._sound.name }]\n }, parent);\n };\n return StopSoundAction;\n }(BABYLON.Action));\n BABYLON.StopSoundAction = StopSoundAction;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.directActions.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var SpriteManager = /** @class */ (function () {\n function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {\n if (epsilon === void 0) { epsilon = 0.01; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n this.name = name;\n this.sprites = new Array();\n this.renderingGroupId = 0;\n this.layerMask = 0x0FFFFFFF;\n this.fogEnabled = true;\n this.isPickable = false;\n /**\n * An event triggered when the manager is disposed.\n */\n this.onDisposeObservable = new BABYLON.Observable();\n this._vertexBuffers = {};\n this._capacity = capacity;\n this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);\n this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n if (cellSize.width && cellSize.height) {\n this.cellWidth = cellSize.width;\n this.cellHeight = cellSize.height;\n }\n else if (cellSize !== undefined) {\n this.cellWidth = cellSize;\n this.cellHeight = cellSize;\n }\n else {\n return;\n }\n this._epsilon = epsilon;\n this._scene = scene;\n this._scene.spriteManagers.push(this);\n var indices = [];\n var index = 0;\n for (var count = 0; count < capacity; count++) {\n indices.push(index);\n indices.push(index + 1);\n indices.push(index + 2);\n indices.push(index);\n indices.push(index + 2);\n indices.push(index + 3);\n index += 4;\n }\n this._indexBuffer = scene.getEngine().createIndexBuffer(indices);\n // VBO\n // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)\n this._vertexData = new Float32Array(capacity * 16 * 4);\n this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);\n var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);\n var options = this._buffer.createVertexBuffer(\"options\", 4, 4);\n var cellInfo = this._buffer.createVertexBuffer(\"cellInfo\", 8, 4);\n var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;\n this._vertexBuffers[\"options\"] = options;\n this._vertexBuffers[\"cellInfo\"] = cellInfo;\n this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;\n // Effects\n this._effectBase = this._scene.getEngine().createEffect(\"sprites\", [BABYLON.VertexBuffer.PositionKind, \"options\", \"cellInfo\", BABYLON.VertexBuffer.ColorKind], [\"view\", \"projection\", \"textureInfos\", \"alphaTest\"], [\"diffuseSampler\"], \"\");\n this._effectFog = this._scene.getEngine().createEffect(\"sprites\", [BABYLON.VertexBuffer.PositionKind, \"options\", \"cellInfo\", BABYLON.VertexBuffer.ColorKind], [\"view\", \"projection\", \"textureInfos\", \"alphaTest\", \"vFogInfos\", \"vFogColor\"], [\"diffuseSampler\"], \"#define FOG\");\n }\n Object.defineProperty(SpriteManager.prototype, \"onDispose\", {\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpriteManager.prototype, \"texture\", {\n get: function () {\n return this._spriteTexture;\n },\n set: function (value) {\n this._spriteTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {\n var arrayOffset = index * 16;\n if (offsetX === 0)\n offsetX = this._epsilon;\n else if (offsetX === 1)\n offsetX = 1 - this._epsilon;\n if (offsetY === 0)\n offsetY = this._epsilon;\n else if (offsetY === 1)\n offsetY = 1 - this._epsilon;\n this._vertexData[arrayOffset] = sprite.position.x;\n this._vertexData[arrayOffset + 1] = sprite.position.y;\n this._vertexData[arrayOffset + 2] = sprite.position.z;\n this._vertexData[arrayOffset + 3] = sprite.angle;\n this._vertexData[arrayOffset + 4] = sprite.width;\n this._vertexData[arrayOffset + 5] = sprite.height;\n this._vertexData[arrayOffset + 6] = offsetX;\n this._vertexData[arrayOffset + 7] = offsetY;\n this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;\n this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;\n var offset = (sprite.cellIndex / rowSize) >> 0;\n this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;\n this._vertexData[arrayOffset + 11] = offset;\n // Color\n this._vertexData[arrayOffset + 12] = sprite.color.r;\n this._vertexData[arrayOffset + 13] = sprite.color.g;\n this._vertexData[arrayOffset + 14] = sprite.color.b;\n this._vertexData[arrayOffset + 15] = sprite.color.a;\n };\n SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {\n var count = Math.min(this._capacity, this.sprites.length);\n var min = BABYLON.Vector3.Zero();\n var max = BABYLON.Vector3.Zero();\n var distance = Number.MAX_VALUE;\n var currentSprite = null;\n var cameraSpacePosition = BABYLON.Vector3.Zero();\n var cameraView = camera.getViewMatrix();\n for (var index = 0; index < count; index++) {\n var sprite = this.sprites[index];\n if (!sprite) {\n continue;\n }\n if (predicate) {\n if (!predicate(sprite)) {\n continue;\n }\n }\n else if (!sprite.isPickable) {\n continue;\n }\n BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);\n min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);\n max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);\n if (ray.intersectsBoxMinMax(min, max)) {\n var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);\n if (distance > currentDistance) {\n distance = currentDistance;\n currentSprite = sprite;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n if (currentSprite) {\n var result = new BABYLON.PickingInfo();\n result.hit = true;\n result.pickedSprite = currentSprite;\n result.distance = distance;\n return result;\n }\n return null;\n };\n SpriteManager.prototype.render = function () {\n // Check\n if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())\n return;\n var engine = this._scene.getEngine();\n var baseSize = this._spriteTexture.getBaseSize();\n // Sprites\n var deltaTime = engine.getDeltaTime();\n var max = Math.min(this._capacity, this.sprites.length);\n var rowSize = baseSize.width / this.cellWidth;\n var offset = 0;\n for (var index = 0; index < max; index++) {\n var sprite = this.sprites[index];\n if (!sprite || !sprite.isVisible) {\n continue;\n }\n sprite._animate(deltaTime);\n this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);\n this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);\n this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);\n this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);\n }\n this._buffer.update(this._vertexData);\n // Render\n var effect = this._effectBase;\n if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {\n effect = this._effectFog;\n }\n engine.enableEffect(effect);\n var viewMatrix = this._scene.getViewMatrix();\n effect.setTexture(\"diffuseSampler\", this._spriteTexture);\n effect.setMatrix(\"view\", viewMatrix);\n effect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n effect.setFloat2(\"textureInfos\", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);\n // Fog\n if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {\n effect.setFloat4(\"vFogInfos\", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);\n effect.setColor3(\"vFogColor\", this._scene.fogColor);\n }\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n // Draw order\n engine.setDepthFunctionToLessOrEqual();\n effect.setBool(\"alphaTest\", true);\n engine.setColorWrite(false);\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);\n engine.setColorWrite(true);\n effect.setBool(\"alphaTest\", false);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n };\n SpriteManager.prototype.dispose = function () {\n if (this._buffer) {\n this._buffer.dispose();\n this._buffer = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n if (this._spriteTexture) {\n this._spriteTexture.dispose();\n this._spriteTexture = null;\n }\n // Remove from scene\n var index = this._scene.spriteManagers.indexOf(this);\n this._scene.spriteManagers.splice(index, 1);\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n };\n return SpriteManager;\n }());\n BABYLON.SpriteManager = SpriteManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.spriteManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Sprite = /** @class */ (function () {\n function Sprite(name, manager) {\n this.name = name;\n this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n this.width = 1.0;\n this.height = 1.0;\n this.angle = 0;\n this.cellIndex = 0;\n this.invertU = 0;\n this.invertV = 0;\n this.animations = new Array();\n this.isPickable = false;\n this._animationStarted = false;\n this._loopAnimation = false;\n this._fromIndex = 0;\n this._toIndex = 0;\n this._delay = 0;\n this._direction = 1;\n this._time = 0;\n /**\n * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true\n */\n this.isVisible = true;\n this._manager = manager;\n this._manager.sprites.push(this);\n this.position = BABYLON.Vector3.Zero();\n }\n Object.defineProperty(Sprite.prototype, \"size\", {\n get: function () {\n return this.width;\n },\n set: function (value) {\n this.width = value;\n this.height = value;\n },\n enumerable: true,\n configurable: true\n });\n Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {\n this._fromIndex = from;\n this._toIndex = to;\n this._loopAnimation = loop;\n this._delay = delay;\n this._animationStarted = true;\n this._direction = from < to ? 1 : -1;\n this.cellIndex = from;\n this._time = 0;\n this._onAnimationEnd = onAnimationEnd;\n };\n Sprite.prototype.stopAnimation = function () {\n this._animationStarted = false;\n };\n Sprite.prototype._animate = function (deltaTime) {\n if (!this._animationStarted)\n return;\n this._time += deltaTime;\n if (this._time > this._delay) {\n this._time = this._time % this._delay;\n this.cellIndex += this._direction;\n if (this.cellIndex > this._toIndex) {\n if (this._loopAnimation) {\n this.cellIndex = this._fromIndex;\n }\n else {\n this.cellIndex = this._toIndex;\n this._animationStarted = false;\n if (this._onAnimationEnd) {\n this._onAnimationEnd();\n }\n if (this.disposeWhenFinishedAnimating) {\n this.dispose();\n }\n }\n }\n }\n };\n Sprite.prototype.dispose = function () {\n for (var i = 0; i < this._manager.sprites.length; i++) {\n if (this._manager.sprites[i] == this) {\n this._manager.sprites.splice(i, 1);\n }\n }\n };\n return Sprite;\n }());\n BABYLON.Sprite = Sprite;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sprite.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var IntersectionInfo = /** @class */ (function () {\n function IntersectionInfo(bu, bv, distance) {\n this.bu = bu;\n this.bv = bv;\n this.distance = distance;\n this.faceId = 0;\n this.subMeshId = 0;\n }\n return IntersectionInfo;\n }());\n BABYLON.IntersectionInfo = IntersectionInfo;\n /**\n * Information about the result of picking within a scene\n * See https://doc.babylonjs.com/babylon101/picking_collisions\n */\n var PickingInfo = /** @class */ (function () {\n function PickingInfo() {\n /**\n * If the pick collided with an object\n */\n this.hit = false;\n /**\n * Distance away where the pick collided\n */\n this.distance = 0;\n /**\n * The location of pick collision\n */\n this.pickedPoint = null;\n /**\n * The mesh corrisponding the the pick collision\n */\n this.pickedMesh = null;\n /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/\n this.bu = 0;\n /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/\n this.bv = 0;\n /** The id of the face on the mesh that was picked */\n this.faceId = -1;\n /** Id of the the submesh that was picked */\n this.subMeshId = 0;\n /** If a sprite was picked, this will be the sprite the pick collided with */\n this.pickedSprite = null;\n /**\n * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.\n */\n this.originMesh = null;\n /**\n * The ray that was used to perform the picking.\n */\n this.ray = null;\n }\n /**\n * Gets the normal corrispodning to the face the pick collided with\n * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)\n * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map\n * @returns The normal corrispodning to the face the pick collided with\n */\n PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {\n if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }\n if (useVerticesNormals === void 0) { useVerticesNormals = true; }\n if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n return null;\n }\n var indices = this.pickedMesh.getIndices();\n if (!indices) {\n return null;\n }\n var result;\n if (useVerticesNormals) {\n var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);\n var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);\n var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);\n normal0 = normal0.scale(this.bu);\n normal1 = normal1.scale(this.bv);\n normal2 = normal2.scale(1.0 - this.bu - this.bv);\n result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);\n }\n else {\n var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);\n var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);\n var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);\n var p1p2 = vertex1.subtract(vertex2);\n var p3p2 = vertex3.subtract(vertex2);\n result = BABYLON.Vector3.Cross(p1p2, p3p2);\n }\n if (useWorldCoordinates) {\n var wm = this.pickedMesh.getWorldMatrix();\n if (this.pickedMesh.nonUniformScaling) {\n BABYLON.Tmp.Matrix[0].copyFrom(wm);\n wm = BABYLON.Tmp.Matrix[0];\n wm.setTranslationFromFloats(0, 0, 0);\n wm.invert();\n wm.transposeToRef(BABYLON.Tmp.Matrix[1]);\n wm = BABYLON.Tmp.Matrix[1];\n }\n result = BABYLON.Vector3.TransformNormal(result, wm);\n }\n result.normalize();\n return result;\n };\n /**\n * Gets the texture coordinates of where the pick occured\n * @returns the vector containing the coordnates of the texture\n */\n PickingInfo.prototype.getTextureCoordinates = function () {\n if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n return null;\n }\n var indices = this.pickedMesh.getIndices();\n if (!indices) {\n return null;\n }\n var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);\n if (!uvs) {\n return null;\n }\n var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);\n var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);\n var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);\n uv0 = uv0.scale(1.0 - this.bu - this.bv);\n uv1 = uv1.scale(this.bu);\n uv2 = uv2.scale(this.bv);\n return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);\n };\n return PickingInfo;\n }());\n BABYLON.PickingInfo = PickingInfo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pickingInfo.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Ray = /** @class */ (function () {\n function Ray(origin, direction, length) {\n if (length === void 0) { length = Number.MAX_VALUE; }\n this.origin = origin;\n this.direction = direction;\n this.length = length;\n }\n // Methods\n Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {\n var d = 0.0;\n var maxValue = Number.MAX_VALUE;\n var inv;\n var min;\n var max;\n var temp;\n if (Math.abs(this.direction.x) < 0.0000001) {\n if (this.origin.x < minimum.x || this.origin.x > maximum.x) {\n return false;\n }\n }\n else {\n inv = 1.0 / this.direction.x;\n min = (minimum.x - this.origin.x) * inv;\n max = (maximum.x - this.origin.x) * inv;\n if (max === -Infinity) {\n max = Infinity;\n }\n if (min > max) {\n temp = min;\n min = max;\n max = temp;\n }\n d = Math.max(min, d);\n maxValue = Math.min(max, maxValue);\n if (d > maxValue) {\n return false;\n }\n }\n if (Math.abs(this.direction.y) < 0.0000001) {\n if (this.origin.y < minimum.y || this.origin.y > maximum.y) {\n return false;\n }\n }\n else {\n inv = 1.0 / this.direction.y;\n min = (minimum.y - this.origin.y) * inv;\n max = (maximum.y - this.origin.y) * inv;\n if (max === -Infinity) {\n max = Infinity;\n }\n if (min > max) {\n temp = min;\n min = max;\n max = temp;\n }\n d = Math.max(min, d);\n maxValue = Math.min(max, maxValue);\n if (d > maxValue) {\n return false;\n }\n }\n if (Math.abs(this.direction.z) < 0.0000001) {\n if (this.origin.z < minimum.z || this.origin.z > maximum.z) {\n return false;\n }\n }\n else {\n inv = 1.0 / this.direction.z;\n min = (minimum.z - this.origin.z) * inv;\n max = (maximum.z - this.origin.z) * inv;\n if (max === -Infinity) {\n max = Infinity;\n }\n if (min > max) {\n temp = min;\n min = max;\n max = temp;\n }\n d = Math.max(min, d);\n maxValue = Math.min(max, maxValue);\n if (d > maxValue) {\n return false;\n }\n }\n return true;\n };\n Ray.prototype.intersectsBox = function (box) {\n return this.intersectsBoxMinMax(box.minimum, box.maximum);\n };\n Ray.prototype.intersectsSphere = function (sphere) {\n var x = sphere.center.x - this.origin.x;\n var y = sphere.center.y - this.origin.y;\n var z = sphere.center.z - this.origin.z;\n var pyth = (x * x) + (y * y) + (z * z);\n var rr = sphere.radius * sphere.radius;\n if (pyth <= rr) {\n return true;\n }\n var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);\n if (dot < 0.0) {\n return false;\n }\n var temp = pyth - (dot * dot);\n return temp <= rr;\n };\n Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {\n if (!this._edge1) {\n this._edge1 = BABYLON.Vector3.Zero();\n this._edge2 = BABYLON.Vector3.Zero();\n this._pvec = BABYLON.Vector3.Zero();\n this._tvec = BABYLON.Vector3.Zero();\n this._qvec = BABYLON.Vector3.Zero();\n }\n vertex1.subtractToRef(vertex0, this._edge1);\n vertex2.subtractToRef(vertex0, this._edge2);\n BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);\n var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);\n if (det === 0) {\n return null;\n }\n var invdet = 1 / det;\n this.origin.subtractToRef(vertex0, this._tvec);\n var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;\n if (bu < 0 || bu > 1.0) {\n return null;\n }\n BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);\n var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;\n if (bv < 0 || bu + bv > 1.0) {\n return null;\n }\n //check if the distance is longer than the predefined length.\n var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;\n if (distance > this.length) {\n return null;\n }\n return new BABYLON.IntersectionInfo(bu, bv, distance);\n };\n Ray.prototype.intersectsPlane = function (plane) {\n var distance;\n var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);\n if (Math.abs(result1) < 9.99999997475243E-07) {\n return null;\n }\n else {\n var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);\n distance = (-plane.d - result2) / result1;\n if (distance < 0.0) {\n if (distance < -9.99999997475243E-07) {\n return null;\n }\n else {\n return 0;\n }\n }\n return distance;\n }\n };\n Ray.prototype.intersectsMesh = function (mesh, fastCheck) {\n var tm = BABYLON.Tmp.Matrix[0];\n mesh.getWorldMatrix().invertToRef(tm);\n if (this._tmpRay) {\n Ray.TransformToRef(this, tm, this._tmpRay);\n }\n else {\n this._tmpRay = Ray.Transform(this, tm);\n }\n return mesh.intersects(this._tmpRay, fastCheck);\n };\n Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {\n if (results) {\n results.length = 0;\n }\n else {\n results = [];\n }\n for (var i = 0; i < meshes.length; i++) {\n var pickInfo = this.intersectsMesh(meshes[i], fastCheck);\n if (pickInfo.hit) {\n results.push(pickInfo);\n }\n }\n results.sort(this._comparePickingInfo);\n return results;\n };\n Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {\n if (pickingInfoA.distance < pickingInfoB.distance) {\n return -1;\n }\n else if (pickingInfoA.distance > pickingInfoB.distance) {\n return 1;\n }\n else {\n return 0;\n }\n };\n /**\n * Intersection test between the ray and a given segment whithin a given tolerance (threshold)\n * @param sega the first point of the segment to test the intersection against\n * @param segb the second point of the segment to test the intersection against\n * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful\n * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection\n */\n Ray.prototype.intersectionSegment = function (sega, segb, threshold) {\n var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));\n var u = segb.subtract(sega);\n var v = rsegb.subtract(this.origin);\n var w = sega.subtract(this.origin);\n var a = BABYLON.Vector3.Dot(u, u); // always >= 0\n var b = BABYLON.Vector3.Dot(u, v);\n var c = BABYLON.Vector3.Dot(v, v); // always >= 0\n var d = BABYLON.Vector3.Dot(u, w);\n var e = BABYLON.Vector3.Dot(v, w);\n var D = a * c - b * b; // always >= 0\n var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0\n var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0\n // compute the line parameters of the two closest points\n if (D < Ray.smallnum) { // the lines are almost parallel\n sN = 0.0; // force using point P0 on segment S1\n sD = 1.0; // to prevent possible division by 0.0 later\n tN = e;\n tD = c;\n }\n else { // get the closest points on the infinite lines\n sN = (b * e - c * d);\n tN = (a * e - b * d);\n if (sN < 0.0) { // sc < 0 => the s=0 edge is visible\n sN = 0.0;\n tN = e;\n tD = c;\n }\n else if (sN > sD) { // sc > 1 => the s=1 edge is visible\n sN = sD;\n tN = e + b;\n tD = c;\n }\n }\n if (tN < 0.0) { // tc < 0 => the t=0 edge is visible\n tN = 0.0;\n // recompute sc for this edge\n if (-d < 0.0) {\n sN = 0.0;\n }\n else if (-d > a)\n sN = sD;\n else {\n sN = -d;\n sD = a;\n }\n }\n else if (tN > tD) { // tc > 1 => the t=1 edge is visible\n tN = tD;\n // recompute sc for this edge\n if ((-d + b) < 0.0) {\n sN = 0;\n }\n else if ((-d + b) > a) {\n sN = sD;\n }\n else {\n sN = (-d + b);\n sD = a;\n }\n }\n // finally do the division to get sc and tc\n sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);\n tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);\n // get the difference of the two closest points\n var qtc = v.multiplyByFloats(tc, tc, tc);\n var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)\n var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result\n if (isIntersected) {\n return qtc.length();\n }\n return -1;\n };\n Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {\n BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);\n BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);\n BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);\n this.direction.normalize();\n return this;\n };\n // Statics\n Ray.Zero = function () {\n return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());\n };\n Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {\n var result = Ray.Zero();\n return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);\n };\n /**\n * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be\n * transformed to the given world matrix.\n * @param origin The origin point\n * @param end The end point\n * @param world a matrix to transform the ray to. Default is the identity matrix.\n */\n Ray.CreateNewFromTo = function (origin, end, world) {\n if (world === void 0) { world = BABYLON.Matrix.Identity(); }\n var direction = end.subtract(origin);\n var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));\n direction.normalize();\n return Ray.Transform(new Ray(origin, direction, length), world);\n };\n Ray.Transform = function (ray, matrix) {\n var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));\n Ray.TransformToRef(ray, matrix, result);\n return result;\n };\n Ray.TransformToRef = function (ray, matrix, result) {\n BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);\n BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);\n result.length = ray.length;\n var dir = result.direction;\n var len = dir.length();\n if (!(len === 0 || len === 1)) {\n var num = 1.0 / len;\n dir.x *= num;\n dir.y *= num;\n dir.z *= num;\n result.length *= len;\n }\n };\n Ray.smallnum = 0.00000001;\n Ray.rayl = 10e8;\n return Ray;\n }());\n BABYLON.Ray = Ray;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.ray.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {\n if (boxMin.x > sphereCenter.x + sphereRadius)\n return false;\n if (sphereCenter.x - sphereRadius > boxMax.x)\n return false;\n if (boxMin.y > sphereCenter.y + sphereRadius)\n return false;\n if (sphereCenter.y - sphereRadius > boxMax.y)\n return false;\n if (boxMin.z > sphereCenter.z + sphereRadius)\n return false;\n if (sphereCenter.z - sphereRadius > boxMax.z)\n return false;\n return true;\n };\n var getLowestRoot = (function () {\n var result = { root: 0, found: false };\n return function (a, b, c, maxR) {\n result.root = 0;\n result.found = false;\n var determinant = b * b - 4.0 * a * c;\n if (determinant < 0)\n return result;\n var sqrtD = Math.sqrt(determinant);\n var r1 = (-b - sqrtD) / (2.0 * a);\n var r2 = (-b + sqrtD) / (2.0 * a);\n if (r1 > r2) {\n var temp = r2;\n r2 = r1;\n r1 = temp;\n }\n if (r1 > 0 && r1 < maxR) {\n result.root = r1;\n result.found = true;\n return result;\n }\n if (r2 > 0 && r2 < maxR) {\n result.root = r2;\n result.found = true;\n return result;\n }\n return result;\n };\n })();\n var Collider = /** @class */ (function () {\n function Collider() {\n this._collisionPoint = BABYLON.Vector3.Zero();\n this._planeIntersectionPoint = BABYLON.Vector3.Zero();\n this._tempVector = BABYLON.Vector3.Zero();\n this._tempVector2 = BABYLON.Vector3.Zero();\n this._tempVector3 = BABYLON.Vector3.Zero();\n this._tempVector4 = BABYLON.Vector3.Zero();\n this._edge = BABYLON.Vector3.Zero();\n this._baseToVertex = BABYLON.Vector3.Zero();\n this._destinationPoint = BABYLON.Vector3.Zero();\n this._slidePlaneNormal = BABYLON.Vector3.Zero();\n this._displacementVector = BABYLON.Vector3.Zero();\n this._radius = BABYLON.Vector3.One();\n this._retry = 0;\n this._basePointWorld = BABYLON.Vector3.Zero();\n this._velocityWorld = BABYLON.Vector3.Zero();\n this._normalizedVelocity = BABYLON.Vector3.Zero();\n this._collisionMask = -1;\n }\n Object.defineProperty(Collider.prototype, \"collisionMask\", {\n get: function () {\n return this._collisionMask;\n },\n set: function (mask) {\n this._collisionMask = !isNaN(mask) ? mask : -1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Collider.prototype, \"slidePlaneNormal\", {\n /**\n * Gets the plane normal used to compute the sliding response (in local space)\n */\n get: function () {\n return this._slidePlaneNormal;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n Collider.prototype._initialize = function (source, dir, e) {\n this._velocity = dir;\n BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);\n this._basePoint = source;\n source.multiplyToRef(this._radius, this._basePointWorld);\n dir.multiplyToRef(this._radius, this._velocityWorld);\n this._velocityWorldLength = this._velocityWorld.length();\n this._epsilon = e;\n this.collisionFound = false;\n };\n Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {\n pa.subtractToRef(point, this._tempVector);\n pb.subtractToRef(point, this._tempVector2);\n BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);\n var d = BABYLON.Vector3.Dot(this._tempVector4, n);\n if (d < 0)\n return false;\n pc.subtractToRef(point, this._tempVector3);\n BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);\n d = BABYLON.Vector3.Dot(this._tempVector4, n);\n if (d < 0)\n return false;\n BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);\n d = BABYLON.Vector3.Dot(this._tempVector4, n);\n return d >= 0;\n };\n Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {\n var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);\n var max = Math.max(this._radius.x, this._radius.y, this._radius.z);\n if (distance > this._velocityWorldLength + max + sphereRadius) {\n return false;\n }\n if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))\n return false;\n return true;\n };\n Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {\n var t0;\n var embeddedInPlane = false;\n //defensive programming, actually not needed.\n if (!trianglePlaneArray) {\n trianglePlaneArray = [];\n }\n if (!trianglePlaneArray[faceIndex]) {\n trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);\n trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);\n }\n var trianglePlane = trianglePlaneArray[faceIndex];\n if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))\n return;\n var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);\n var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);\n if (normalDotVelocity == 0) {\n if (Math.abs(signedDistToTrianglePlane) >= 1.0)\n return;\n embeddedInPlane = true;\n t0 = 0;\n }\n else {\n t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;\n var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;\n if (t0 > t1) {\n var temp = t1;\n t1 = t0;\n t0 = temp;\n }\n if (t0 > 1.0 || t1 < 0.0)\n return;\n if (t0 < 0)\n t0 = 0;\n if (t0 > 1.0)\n t0 = 1.0;\n }\n this._collisionPoint.copyFromFloats(0, 0, 0);\n var found = false;\n var t = 1.0;\n if (!embeddedInPlane) {\n this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);\n this._velocity.scaleToRef(t0, this._tempVector);\n this._planeIntersectionPoint.addInPlace(this._tempVector);\n if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {\n found = true;\n t = t0;\n this._collisionPoint.copyFrom(this._planeIntersectionPoint);\n }\n }\n if (!found) {\n var velocitySquaredLength = this._velocity.lengthSquared();\n var a = velocitySquaredLength;\n this._basePoint.subtractToRef(p1, this._tempVector);\n var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));\n var c = this._tempVector.lengthSquared() - 1.0;\n var lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n t = lowestRoot.root;\n found = true;\n this._collisionPoint.copyFrom(p1);\n }\n this._basePoint.subtractToRef(p2, this._tempVector);\n b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));\n c = this._tempVector.lengthSquared() - 1.0;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n t = lowestRoot.root;\n found = true;\n this._collisionPoint.copyFrom(p2);\n }\n this._basePoint.subtractToRef(p3, this._tempVector);\n b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));\n c = this._tempVector.lengthSquared() - 1.0;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n t = lowestRoot.root;\n found = true;\n this._collisionPoint.copyFrom(p3);\n }\n p2.subtractToRef(p1, this._edge);\n p1.subtractToRef(this._basePoint, this._baseToVertex);\n var edgeSquaredLength = this._edge.lengthSquared();\n var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);\n var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);\n a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;\n b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;\n c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;\n if (f >= 0.0 && f <= 1.0) {\n t = lowestRoot.root;\n found = true;\n this._edge.scaleInPlace(f);\n p1.addToRef(this._edge, this._collisionPoint);\n }\n }\n p3.subtractToRef(p2, this._edge);\n p2.subtractToRef(this._basePoint, this._baseToVertex);\n edgeSquaredLength = this._edge.lengthSquared();\n edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);\n edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);\n a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;\n b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;\n c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;\n if (f >= 0.0 && f <= 1.0) {\n t = lowestRoot.root;\n found = true;\n this._edge.scaleInPlace(f);\n p2.addToRef(this._edge, this._collisionPoint);\n }\n }\n p1.subtractToRef(p3, this._edge);\n p3.subtractToRef(this._basePoint, this._baseToVertex);\n edgeSquaredLength = this._edge.lengthSquared();\n edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);\n edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);\n a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;\n b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;\n c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;\n if (f >= 0.0 && f <= 1.0) {\n t = lowestRoot.root;\n found = true;\n this._edge.scaleInPlace(f);\n p3.addToRef(this._edge, this._collisionPoint);\n }\n }\n }\n if (found) {\n var distToCollision = t * this._velocity.length();\n if (!this.collisionFound || distToCollision < this._nearestDistance) {\n if (!this.intersectionPoint) {\n this.intersectionPoint = this._collisionPoint.clone();\n }\n else {\n this.intersectionPoint.copyFrom(this._collisionPoint);\n }\n this._nearestDistance = distToCollision;\n this.collisionFound = true;\n }\n }\n };\n Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {\n for (var i = indexStart; i < indexEnd; i += 3) {\n var p1 = pts[indices[i] - decal];\n var p2 = pts[indices[i + 1] - decal];\n var p3 = pts[indices[i + 2] - decal];\n this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);\n }\n };\n Collider.prototype._getResponse = function (pos, vel) {\n pos.addToRef(vel, this._destinationPoint);\n vel.scaleInPlace((this._nearestDistance / vel.length()));\n this._basePoint.addToRef(vel, pos);\n pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);\n this._slidePlaneNormal.normalize();\n this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);\n pos.addInPlace(this._displacementVector);\n this.intersectionPoint.addInPlace(this._displacementVector);\n this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));\n this._destinationPoint.subtractInPlace(this._slidePlaneNormal);\n this._destinationPoint.subtractToRef(this.intersectionPoint, vel);\n };\n return Collider;\n }());\n BABYLON.Collider = Collider;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.collider.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n //WebWorker code will be inserted to this variable.\n BABYLON.CollisionWorker = \"\";\n /** Defines supported task for worker process */\n var WorkerTaskType;\n (function (WorkerTaskType) {\n /** Initialization */\n WorkerTaskType[WorkerTaskType[\"INIT\"] = 0] = \"INIT\";\n /** Update of geometry */\n WorkerTaskType[WorkerTaskType[\"UPDATE\"] = 1] = \"UPDATE\";\n /** Evaluate collision */\n WorkerTaskType[WorkerTaskType[\"COLLIDE\"] = 2] = \"COLLIDE\";\n })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));\n /** Defines kind of replies returned by worker */\n var WorkerReplyType;\n (function (WorkerReplyType) {\n /** Success */\n WorkerReplyType[WorkerReplyType[\"SUCCESS\"] = 0] = \"SUCCESS\";\n /** Unkown error */\n WorkerReplyType[WorkerReplyType[\"UNKNOWN_ERROR\"] = 1] = \"UNKNOWN_ERROR\";\n })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));\n var CollisionCoordinatorWorker = /** @class */ (function () {\n function CollisionCoordinatorWorker() {\n var _this = this;\n this._scaledPosition = BABYLON.Vector3.Zero();\n this._scaledVelocity = BABYLON.Vector3.Zero();\n this.onMeshUpdated = function (transformNode) {\n _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);\n };\n this.onGeometryUpdated = function (geometry) {\n _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);\n };\n this._afterRender = function () {\n if (!_this._init)\n return;\n if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {\n return;\n }\n //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.\n //TODO make sure update runs as fast as possible to be able to update 60 FPS.\n if (_this._runningUpdated > 4) {\n return;\n }\n ++_this._runningUpdated;\n var payload = {\n updatedMeshes: _this._addUpdateMeshesList,\n updatedGeometries: _this._addUpdateGeometriesList,\n removedGeometries: _this._toRemoveGeometryArray,\n removedMeshes: _this._toRemoveMeshesArray\n };\n var message = {\n payload: payload,\n taskType: WorkerTaskType.UPDATE\n };\n var serializable = [];\n for (var id in payload.updatedGeometries) {\n if (payload.updatedGeometries.hasOwnProperty(id)) {\n //prepare transferables\n serializable.push(message.payload.updatedGeometries[id].indices.buffer);\n serializable.push(message.payload.updatedGeometries[id].normals.buffer);\n serializable.push(message.payload.updatedGeometries[id].positions.buffer);\n }\n }\n _this._worker.postMessage(message, serializable);\n _this._addUpdateMeshesList = {};\n _this._addUpdateGeometriesList = {};\n _this._toRemoveGeometryArray = [];\n _this._toRemoveMeshesArray = [];\n };\n this._onMessageFromWorker = function (e) {\n var returnData = e.data;\n if (returnData.error != WorkerReplyType.SUCCESS) {\n //TODO what errors can be returned from the worker?\n BABYLON.Tools.Warn(\"error returned from worker!\");\n return;\n }\n switch (returnData.taskType) {\n case WorkerTaskType.INIT:\n _this._init = true;\n //Update the worked with ALL of the scene's current state\n _this._scene.meshes.forEach(function (mesh) {\n _this.onMeshAdded(mesh);\n });\n _this._scene.getGeometries().forEach(function (geometry) {\n _this.onGeometryAdded(geometry);\n });\n break;\n case WorkerTaskType.UPDATE:\n _this._runningUpdated--;\n break;\n case WorkerTaskType.COLLIDE:\n var returnPayload = returnData.payload;\n if (!_this._collisionsCallbackArray[returnPayload.collisionId])\n return;\n var callback = _this._collisionsCallbackArray[returnPayload.collisionId];\n if (callback) {\n var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);\n if (mesh) {\n callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);\n }\n }\n //cleanup\n _this._collisionsCallbackArray[returnPayload.collisionId] = null;\n break;\n }\n };\n this._collisionsCallbackArray = [];\n this._init = false;\n this._runningUpdated = 0;\n this._addUpdateMeshesList = {};\n this._addUpdateGeometriesList = {};\n this._toRemoveGeometryArray = [];\n this._toRemoveMeshesArray = [];\n }\n CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {\n if (!this._init)\n return;\n if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])\n return;\n position.divideToRef(collider._radius, this._scaledPosition);\n displacement.divideToRef(collider._radius, this._scaledVelocity);\n this._collisionsCallbackArray[collisionIndex] = onNewPosition;\n var payload = {\n collider: {\n position: this._scaledPosition.asArray(),\n velocity: this._scaledVelocity.asArray(),\n radius: collider._radius.asArray()\n },\n collisionId: collisionIndex,\n excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,\n maximumRetry: maximumRetry\n };\n var message = {\n payload: payload,\n taskType: WorkerTaskType.COLLIDE\n };\n this._worker.postMessage(message);\n };\n CollisionCoordinatorWorker.prototype.init = function (scene) {\n this._scene = scene;\n this._scene.registerAfterRender(this._afterRender);\n var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + \"Collisions/babylon.collisionWorker.js\" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));\n this._worker = new Worker(workerUrl);\n this._worker.onmessage = this._onMessageFromWorker;\n var message = {\n payload: {},\n taskType: WorkerTaskType.INIT\n };\n this._worker.postMessage(message);\n };\n CollisionCoordinatorWorker.prototype.destroy = function () {\n this._scene.unregisterAfterRender(this._afterRender);\n this._worker.terminate();\n };\n CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {\n mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);\n this.onMeshUpdated(mesh);\n };\n CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {\n this._toRemoveMeshesArray.push(mesh.uniqueId);\n };\n CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {\n //TODO this will break if the user uses his own function. This should be an array of callbacks!\n geometry.onGeometryUpdated = this.onGeometryUpdated;\n this.onGeometryUpdated(geometry);\n };\n CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {\n this._toRemoveGeometryArray.push(geometry.id);\n };\n CollisionCoordinatorWorker.SerializeMesh = function (mesh) {\n var submeshes = [];\n if (mesh.subMeshes) {\n submeshes = mesh.subMeshes.map(function (sm, idx) {\n var boundingInfo = sm.getBoundingInfo();\n return {\n position: idx,\n verticesStart: sm.verticesStart,\n verticesCount: sm.verticesCount,\n indexStart: sm.indexStart,\n indexCount: sm.indexCount,\n hasMaterial: !!sm.getMaterial(),\n sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),\n sphereRadius: boundingInfo.boundingSphere.radiusWorld,\n boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),\n boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()\n };\n });\n }\n var geometryId = null;\n if (mesh instanceof BABYLON.Mesh) {\n var geometry = mesh.geometry;\n geometryId = geometry ? geometry.id : null;\n }\n else if (mesh instanceof BABYLON.InstancedMesh) {\n var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;\n geometryId = geometry ? geometry.id : null;\n }\n var boundingInfo = mesh.getBoundingInfo();\n return {\n uniqueId: mesh.uniqueId,\n id: mesh.id,\n name: mesh.name,\n geometryId: geometryId,\n sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),\n sphereRadius: boundingInfo.boundingSphere.radiusWorld,\n boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),\n boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),\n worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),\n subMeshes: submeshes,\n checkCollisions: mesh.checkCollisions\n };\n };\n CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {\n return {\n id: geometry.id,\n positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),\n normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),\n indices: new Uint32Array(geometry.getIndices() || []),\n };\n };\n return CollisionCoordinatorWorker;\n }());\n BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;\n var CollisionCoordinatorLegacy = /** @class */ (function () {\n function CollisionCoordinatorLegacy() {\n this._scaledPosition = BABYLON.Vector3.Zero();\n this._scaledVelocity = BABYLON.Vector3.Zero();\n this._finalPosition = BABYLON.Vector3.Zero();\n }\n CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {\n position.divideToRef(collider._radius, this._scaledPosition);\n displacement.divideToRef(collider._radius, this._scaledVelocity);\n collider.collidedMesh = null;\n collider._retry = 0;\n collider._initialVelocity = this._scaledVelocity;\n collider._initialPosition = this._scaledPosition;\n this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);\n this._finalPosition.multiplyInPlace(collider._radius);\n //run the callback\n onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);\n };\n CollisionCoordinatorLegacy.prototype.init = function (scene) {\n this._scene = scene;\n };\n CollisionCoordinatorLegacy.prototype.destroy = function () {\n //Legacy need no destruction method.\n };\n //No update in legacy mode\n CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };\n CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };\n CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };\n CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };\n CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };\n CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };\n CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {\n if (excludedMesh === void 0) { excludedMesh = null; }\n var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;\n if (collider._retry >= maximumRetry) {\n finalPosition.copyFrom(position);\n return;\n }\n // Check if this is a mesh else camera or -1\n var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);\n collider._initialize(position, velocity, closeDistance);\n // Check all meshes\n for (var index = 0; index < this._scene.meshes.length; index++) {\n var mesh = this._scene.meshes[index];\n if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {\n mesh._checkCollision(collider);\n }\n }\n if (!collider.collisionFound) {\n position.addToRef(velocity, finalPosition);\n return;\n }\n if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {\n collider._getResponse(position, velocity);\n }\n if (velocity.length() <= closeDistance) {\n finalPosition.copyFrom(position);\n return;\n }\n collider._retry++;\n this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);\n };\n return CollisionCoordinatorLegacy;\n }());\n BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.collisionCoordinator.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A particle represents one of the element emitted by a particle system.\n * This is mainly define by its coordinates, direction, velocity and age.\n */\n var Particle = /** @class */ (function () {\n /**\n * Creates a new instance Particle\n * @param particleSystem the particle system the particle belongs to\n */\n function Particle(\n /**\n * particleSystem the particle system the particle belongs to.\n */\n particleSystem) {\n this.particleSystem = particleSystem;\n /**\n * The world position of the particle in the scene.\n */\n this.position = BABYLON.Vector3.Zero();\n /**\n * The world direction of the particle in the scene.\n */\n this.direction = BABYLON.Vector3.Zero();\n /**\n * The color of the particle.\n */\n this.color = new BABYLON.Color4(0, 0, 0, 0);\n /**\n * The color change of the particle per step.\n */\n this.colorStep = new BABYLON.Color4(0, 0, 0, 0);\n /**\n * Defines how long will the life of the particle be.\n */\n this.lifeTime = 1.0;\n /**\n * The current age of the particle.\n */\n this.age = 0;\n /**\n * The current size of the particle.\n */\n this.size = 0;\n /**\n * The current scale of the particle.\n */\n this.scale = new BABYLON.Vector2(1, 1);\n /**\n * The current angle of the particle.\n */\n this.angle = 0;\n /**\n * Defines how fast is the angle changing.\n */\n this.angularSpeed = 0;\n /**\n * Defines the cell index used by the particle to be rendered from a sprite.\n */\n this.cellIndex = 0;\n /** @hidden */\n this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);\n /** @hidden */\n this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);\n /** @hidden */\n this._currentSize1 = 0;\n /** @hidden */\n this._currentSize2 = 0;\n /** @hidden */\n this._currentAngularSpeed1 = 0;\n /** @hidden */\n this._currentAngularSpeed2 = 0;\n /** @hidden */\n this._currentVelocity1 = 0;\n /** @hidden */\n this._currentVelocity2 = 0;\n if (!this.particleSystem.isAnimationSheetEnabled) {\n return;\n }\n this.updateCellInfoFromSystem();\n }\n Particle.prototype.updateCellInfoFromSystem = function () {\n this.cellIndex = this.particleSystem.startSpriteCellID;\n };\n /**\n * Defines how the sprite cell index is updated for the particle\n */\n Particle.prototype.updateCellIndex = function () {\n var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);\n var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);\n this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;\n };\n /**\n * Copy the properties of particle to another one.\n * @param other the particle to copy the information to.\n */\n Particle.prototype.copyTo = function (other) {\n other.position.copyFrom(this.position);\n if (this._initialDirection) {\n if (other._initialDirection) {\n other._initialDirection.copyFrom(this._initialDirection);\n }\n else {\n other._initialDirection = this._initialDirection.clone();\n }\n }\n else {\n other._initialDirection = null;\n }\n other.direction.copyFrom(this.direction);\n other.color.copyFrom(this.color);\n other.colorStep.copyFrom(this.colorStep);\n other.lifeTime = this.lifeTime;\n other.age = this.age;\n other.size = this.size;\n other.scale.copyFrom(this.scale);\n other.angle = this.angle;\n other.angularSpeed = this.angularSpeed;\n other.particleSystem = this.particleSystem;\n other.cellIndex = this.cellIndex;\n if (this._currentColorGradient) {\n other._currentColorGradient = this._currentColorGradient;\n other._currentColor1.copyFrom(this._currentColor1);\n other._currentColor2.copyFrom(this._currentColor2);\n }\n if (this._currentSizeGradient) {\n other._currentSizeGradient = this._currentSizeGradient;\n other._currentSize1 = this._currentSize1;\n other._currentSize2 = this._currentSize2;\n }\n if (this._currentAngularSpeedGradient) {\n other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;\n other._currentAngularSpeed1 = this._currentAngularSpeed1;\n other._currentAngularSpeed2 = this._currentAngularSpeed2;\n }\n if (this._currentVelocityGradient) {\n other._currentVelocityGradient = this._currentVelocityGradient;\n other._currentVelocity1 = this._currentVelocity1;\n other._currentVelocity2 = this._currentVelocity2;\n }\n if (this.particleSystem.isAnimationSheetEnabled) {\n other._initialStartSpriteCellID = this._initialStartSpriteCellID;\n other._initialEndSpriteCellID = this._initialEndSpriteCellID;\n }\n };\n return Particle;\n }());\n BABYLON.Particle = Particle;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.particle.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This represents a particle system in Babylon.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.\n * @example https://doc.babylonjs.com/babylon101/particles\n */\n var ParticleSystem = /** @class */ (function () {\n /**\n * Instantiates a particle system.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * @param name The name of the particle system\n * @param capacity The max number of particles alive at the same time\n * @param scene The scene the particle system belongs to\n * @param customEffect a custom effect used to change the way particles are rendered by default\n * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture\n * @param epsilon Offset used to render the particles\n */\n function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {\n if (customEffect === void 0) { customEffect = null; }\n if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }\n if (epsilon === void 0) { epsilon = 0.01; }\n var _this = this;\n /**\n * List of animations used by the particle system.\n */\n this.animations = [];\n /**\n * The rendering group used by the Particle system to chose when to render.\n */\n this.renderingGroupId = 0;\n /**\n * The emitter represents the Mesh or position we are attaching the particle system to.\n */\n this.emitter = null;\n /**\n * The maximum number of particles to emit per frame\n */\n this.emitRate = 10;\n /**\n * If you want to launch only a few particles at once, that can be done, as well.\n */\n this.manualEmitCount = -1;\n /**\n * The overall motion speed (0.01 is default update speed, faster updates = faster animation)\n */\n this.updateSpeed = 0.01;\n /**\n * The amount of time the particle system is running (depends of the overall update speed).\n */\n this.targetStopDuration = 0;\n /**\n * Specifies whether the particle system will be disposed once it reaches the end of the animation.\n */\n this.disposeOnStop = false;\n /**\n * Minimum power of emitting particles.\n */\n this.minEmitPower = 1;\n /**\n * Maximum power of emitting particles.\n */\n this.maxEmitPower = 1;\n /**\n * Minimum life time of emitting particles.\n */\n this.minLifeTime = 1;\n /**\n * Maximum life time of emitting particles.\n */\n this.maxLifeTime = 1;\n /**\n * Minimum Size of emitting particles.\n */\n this.minSize = 1;\n /**\n * Maximum Size of emitting particles.\n */\n this.maxSize = 1;\n /**\n * Minimum scale of emitting particles on X axis.\n */\n this.minScaleX = 1;\n /**\n * Maximum scale of emitting particles on X axis.\n */\n this.maxScaleX = 1;\n /**\n * Minimum scale of emitting particles on Y axis.\n */\n this.minScaleY = 1;\n /**\n * Maximum scale of emitting particles on Y axis.\n */\n this.maxScaleY = 1;\n /**\n * Gets or sets the minimal initial rotation in radians.\n */\n this.minInitialRotation = 0;\n /**\n * Gets or sets the maximal initial rotation in radians.\n */\n this.maxInitialRotation = 0;\n /**\n * Minimum angular speed of emitting particles (Z-axis rotation for each particle).\n */\n this.minAngularSpeed = 0;\n /**\n * Maximum angular speed of emitting particles (Z-axis rotation for each particle).\n */\n this.maxAngularSpeed = 0;\n /**\n * The layer mask we are rendering the particles through.\n */\n this.layerMask = 0x0FFFFFFF;\n /**\n * This can help using your own shader to render the particle system.\n * The according effect will be created\n */\n this.customShader = null;\n /**\n * By default particle system starts as soon as they are created. This prevents the\n * automatic start to happen and let you decide when to start emitting particles.\n */\n this.preventAutoStart = false;\n /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */\n this.noiseStrength = new BABYLON.Vector3(10, 10, 10);\n /**\n * Callback triggered when the particle animation is ending.\n */\n this.onAnimationEnd = null;\n /**\n * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.\n */\n this.blendMode = ParticleSystem.BLENDMODE_ONEONE;\n /**\n * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls\n * to override the particles.\n */\n this.forceDepthWrite = false;\n /**\n * You can use gravity if you want to give an orientation to your particles.\n */\n this.gravity = BABYLON.Vector3.Zero();\n this._colorGradients = null;\n this._sizeGradients = null;\n this._lifeTimeGradients = null;\n this._angularSpeedGradients = null;\n this._velocityGradients = null;\n /**\n * Random color of each particle after it has been emitted, between color1 and color2 vectors\n */\n this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * Random color of each particle after it has been emitted, between color1 and color2 vectors\n */\n this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * Color the particle will have at the end of its lifetime\n */\n this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);\n /**\n * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel\n */\n this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)\n */\n this.spriteCellChangeSpeed = 1;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display\n */\n this.startSpriteCellID = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display\n */\n this.endSpriteCellID = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use\n */\n this.spriteCellWidth = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use\n */\n this.spriteCellHeight = 0;\n /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */\n this.preWarmCycles = 0;\n /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */\n this.preWarmStepOffset = 1;\n /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */\n this.translationPivot = new BABYLON.Vector2(0, 0);\n /**\n * An event triggered when the system is disposed\n */\n this.onDisposeObservable = new BABYLON.Observable();\n /**\n * Gets or sets the billboard mode to use when isBillboardBased = true.\n * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far\n */\n this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;\n this._particles = new Array();\n this._stockParticles = new Array();\n this._newPartsExcess = 0;\n this._vertexBuffers = {};\n this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);\n this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);\n this._scaledDirection = BABYLON.Vector3.Zero();\n this._scaledGravity = BABYLON.Vector3.Zero();\n this._currentRenderId = -1;\n this._useInstancing = false;\n this._started = false;\n this._stopped = false;\n this._actualFrame = 0;\n this._isBillboardBased = true;\n // start of sub system methods\n /**\n * \"Recycles\" one of the particle by copying it back to the \"stock\" of particles and removing it from the active list.\n * Its lifetime will start back at 0.\n */\n this.recycleParticle = function (particle) {\n var lastParticle = _this._particles.pop();\n if (lastParticle !== particle) {\n lastParticle.copyTo(particle);\n }\n _this._stockParticles.push(lastParticle);\n };\n this._createParticle = function () {\n var particle;\n if (_this._stockParticles.length !== 0) {\n particle = _this._stockParticles.pop();\n particle.age = 0;\n particle._currentColorGradient = null;\n particle.cellIndex = _this.startSpriteCellID;\n }\n else {\n particle = new BABYLON.Particle(_this);\n }\n return particle;\n };\n this._emitFromParticle = function (particle) {\n if (!_this.subEmitters || _this.subEmitters.length === 0) {\n return;\n }\n var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);\n var subSystem = _this.subEmitters[templateIndex].clone(_this.name + \"_sub\", particle.position.clone());\n subSystem._rootParticleSystem = _this;\n _this.activeSubSystems.push(subSystem);\n subSystem.start();\n };\n this.id = name;\n this.name = name;\n this._capacity = capacity;\n this._epsilon = epsilon;\n this._isAnimationSheetEnabled = isAnimationSheetEnabled;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this._customEffect = customEffect;\n this._scene.particleSystems.push(this);\n this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;\n this._createIndexBuffer();\n this._createVertexBuffers();\n // Default emitter type\n this.particleEmitterType = new BABYLON.BoxParticleEmitter();\n this.updateFunction = function (particles) {\n var noiseTextureData = null;\n var noiseTextureSize = null;\n if (_this.noiseTexture) { // We need to get texture data back to CPU\n noiseTextureData = (_this.noiseTexture.readPixels());\n noiseTextureSize = _this.noiseTexture.getSize();\n }\n var _loop_1 = function () {\n particle = particles[index];\n particle.age += _this._scaledUpdateSpeed;\n if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle\n _this._emitFromParticle(particle);\n _this.recycleParticle(particle);\n index--;\n return \"continue\";\n }\n else {\n var ratio = particle.age / particle.lifeTime;\n // Color\n if (_this._colorGradients && _this._colorGradients.length > 0) {\n BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {\n if (currentGradient !== particle._currentColorGradient) {\n particle._currentColor1.copyFrom(particle._currentColor2);\n nextGradient.getColorToRef(particle._currentColor2);\n particle._currentColorGradient = currentGradient;\n }\n BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);\n });\n }\n else {\n particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);\n particle.color.addInPlace(_this._scaledColorStep);\n if (particle.color.a < 0) {\n particle.color.a = 0;\n }\n }\n // Angular speed\n if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {\n BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {\n if (currentGradient !== particle._currentAngularSpeedGradient) {\n particle._currentAngularSpeed1 = particle._currentAngularSpeed2;\n particle._currentAngularSpeed2 = nextGradient.getFactor();\n particle._currentAngularSpeedGradient = currentGradient;\n }\n particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);\n });\n }\n particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;\n // Direction\n var directionScale_1 = _this._scaledUpdateSpeed;\n if (_this._velocityGradients && _this._velocityGradients.length > 0) {\n BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {\n if (currentGradient !== particle._currentVelocityGradient) {\n particle._currentVelocity1 = particle._currentVelocity2;\n particle._currentVelocity2 = nextGradient.getFactor();\n particle._currentVelocityGradient = currentGradient;\n }\n directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);\n });\n }\n particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);\n particle.position.addInPlace(_this._scaledDirection);\n // Noise\n if (noiseTextureData && noiseTextureSize) {\n var localPosition = BABYLON.Tmp.Vector3[0];\n var emitterPosition = BABYLON.Tmp.Vector3[1];\n _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);\n particle.position.subtractToRef(emitterPosition, localPosition);\n var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);\n var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);\n var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);\n var force = BABYLON.Tmp.Vector3[0];\n var scaledForce = BABYLON.Tmp.Vector3[1];\n force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);\n force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);\n particle.direction.addInPlace(scaledForce);\n }\n // Gravity\n _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);\n particle.direction.addInPlace(_this._scaledGravity);\n // Size\n if (_this._sizeGradients && _this._sizeGradients.length > 0) {\n BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {\n if (currentGradient !== particle._currentSizeGradient) {\n particle._currentSize1 = particle._currentSize2;\n particle._currentSize2 = nextGradient.getFactor();\n particle._currentSizeGradient = currentGradient;\n }\n particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);\n });\n }\n if (_this._isAnimationSheetEnabled) {\n particle.updateCellIndex();\n }\n }\n };\n var particle;\n for (var index = 0; index < particles.length; index++) {\n _loop_1();\n }\n };\n }\n /**\n * Gets the current list of color gradients.\n * You must use addColorGradient and removeColorGradient to udpate this list\n * @returns the list of color gradients\n */\n ParticleSystem.prototype.getColorGradients = function () {\n return this._colorGradients;\n };\n /**\n * Gets the current list of size gradients.\n * You must use addSizeGradient and removeSizeGradient to udpate this list\n * @returns the list of size gradients\n */\n ParticleSystem.prototype.getSizeGradients = function () {\n return this._sizeGradients;\n };\n /**\n * Gets the current list of life time gradients.\n * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list\n * @returns the list of life time gradients\n */\n ParticleSystem.prototype.getLifeTimeGradients = function () {\n return this._lifeTimeGradients;\n };\n /**\n * Gets the current list of angular speed gradients.\n * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list\n * @returns the list of angular speed gradients\n */\n ParticleSystem.prototype.getAngularSpeedGradients = function () {\n return this._angularSpeedGradients;\n };\n /**\n * Gets the current list of velocity gradients.\n * You must use addVelocityGradient and removeVelocityGradient to udpate this list\n * @returns the list of velocity gradients\n */\n ParticleSystem.prototype.getVelocityGradients = function () {\n return this._velocityGradients;\n };\n Object.defineProperty(ParticleSystem.prototype, \"direction1\", {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.direction1) {\n return this.particleEmitterType.direction1;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.direction1) {\n this.particleEmitterType.direction1 = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ParticleSystem.prototype, \"direction2\", {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.direction2) {\n return this.particleEmitterType.direction2;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.direction2) {\n this.particleEmitterType.direction2 = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ParticleSystem.prototype, \"minEmitBox\", {\n /**\n * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.minEmitBox) {\n return this.particleEmitterType.minEmitBox;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.minEmitBox) {\n this.particleEmitterType.minEmitBox = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ParticleSystem.prototype, \"maxEmitBox\", {\n /**\n * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.maxEmitBox) {\n return this.particleEmitterType.maxEmitBox;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.maxEmitBox) {\n this.particleEmitterType.maxEmitBox = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ParticleSystem.prototype, \"onDispose\", {\n /**\n * Sets a callback that will be triggered when the system is disposed\n */\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ParticleSystem.prototype, \"isAnimationSheetEnabled\", {\n /**\n * Gets or sets whether an animation sprite sheet is enabled or not on the particle system\n */\n get: function () {\n return this._isAnimationSheetEnabled;\n },\n set: function (value) {\n if (this._isAnimationSheetEnabled == value) {\n return;\n }\n this._isAnimationSheetEnabled = value;\n this._resetEffect();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ParticleSystem.prototype, \"isBillboardBased\", {\n /**\n * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction\n */\n get: function () {\n return this._isBillboardBased;\n },\n set: function (value) {\n if (this._isBillboardBased === value) {\n return;\n }\n this._isBillboardBased = value;\n this._resetEffect();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Get hosting scene\n * @returns the scene\n */\n ParticleSystem.prototype.getScene = function () {\n return this._scene;\n };\n Object.defineProperty(ParticleSystem.prototype, \"particles\", {\n //end of Sub-emitter\n /**\n * Gets the current list of active particles\n */\n get: function () {\n return this._particles;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"ParticleSystem\"\n * @returns a string containing the class name\n */\n ParticleSystem.prototype.getClassName = function () {\n return \"ParticleSystem\";\n };\n ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {\n u = Math.abs(u) * 0.5 + 0.5;\n v = Math.abs(v) * 0.5 + 0.5;\n var wrappedU = ((u * width) % width) | 0;\n var wrappedV = ((v * height) % height) | 0;\n var position = (wrappedU + wrappedV * width) * 4;\n return pixels[position] / 255;\n };\n ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {\n var newGradient = new BABYLON.FactorGradient();\n newGradient.gradient = gradient;\n newGradient.factor1 = factor;\n newGradient.factor2 = factor2;\n factorGradients.push(newGradient);\n factorGradients.sort(function (a, b) {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n };\n ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {\n if (!factorGradients) {\n return;\n }\n var index = 0;\n for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {\n var factorGradient = factorGradients_1[_i];\n if (factorGradient.gradient === gradient) {\n factorGradients.splice(index, 1);\n break;\n }\n index++;\n }\n };\n /**\n * Adds a new life time gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the life time factor to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {\n if (!this._lifeTimeGradients) {\n this._lifeTimeGradients = [];\n }\n this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);\n return this;\n };\n /**\n * Remove a specific life time gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {\n this._removeFactorGradient(this._lifeTimeGradients, gradient);\n return this;\n };\n /**\n * Adds a new size gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {\n if (!this._sizeGradients) {\n this._sizeGradients = [];\n }\n this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);\n return this;\n };\n /**\n * Remove a specific size gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n ParticleSystem.prototype.removeSizeGradient = function (gradient) {\n this._removeFactorGradient(this._sizeGradients, gradient);\n return this;\n };\n /**\n * Adds a new angular speed gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {\n if (!this._angularSpeedGradients) {\n this._angularSpeedGradients = [];\n }\n this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);\n return this;\n };\n /**\n * Remove a specific angular speed gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {\n this._removeFactorGradient(this._angularSpeedGradients, gradient);\n return this;\n };\n /**\n * Adds a new velocity gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {\n if (!this._velocityGradients) {\n this._velocityGradients = [];\n }\n this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);\n return this;\n };\n /**\n * Remove a specific velocity gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n ParticleSystem.prototype.removeVelocityGradient = function (gradient) {\n this._removeFactorGradient(this._velocityGradients, gradient);\n return this;\n };\n /**\n * Adds a new color gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param color defines the color to affect to the specified gradient\n * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from\n */\n ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {\n if (!this._colorGradients) {\n this._colorGradients = [];\n }\n var colorGradient = new BABYLON.ColorGradient();\n colorGradient.gradient = gradient;\n colorGradient.color1 = color;\n colorGradient.color2 = color2;\n this._colorGradients.push(colorGradient);\n this._colorGradients.sort(function (a, b) {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n return this;\n };\n /**\n * Remove a specific color gradient\n * @param gradient defines the gradient to remove\n */\n ParticleSystem.prototype.removeColorGradient = function (gradient) {\n if (!this._colorGradients) {\n return this;\n }\n var index = 0;\n for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {\n var colorGradient = _a[_i];\n if (colorGradient.gradient === gradient) {\n this._colorGradients.splice(index, 1);\n break;\n }\n index++;\n }\n return this;\n };\n ParticleSystem.prototype._resetEffect = function () {\n if (this._vertexBuffer) {\n this._vertexBuffer.dispose();\n this._vertexBuffer = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n this._createVertexBuffers();\n };\n ParticleSystem.prototype._createVertexBuffers = function () {\n this._vertexBufferSize = this._useInstancing ? 10 : 12;\n if (this._isAnimationSheetEnabled) {\n this._vertexBufferSize += 1;\n }\n if (!this._isBillboardBased) {\n this._vertexBufferSize += 3;\n }\n var engine = this._scene.getEngine();\n this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));\n this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);\n var dataOffset = 0;\n var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;\n dataOffset += 3;\n var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;\n dataOffset += 4;\n var options = this._vertexBuffer.createVertexBuffer(\"angle\", dataOffset, 1, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"angle\"] = options;\n dataOffset += 1;\n var size = this._vertexBuffer.createVertexBuffer(\"size\", dataOffset, 2, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"size\"] = size;\n dataOffset += 2;\n if (this._isAnimationSheetEnabled) {\n var cellIndexBuffer = this._vertexBuffer.createVertexBuffer(\"cellIndex\", dataOffset, 1, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"cellIndex\"] = cellIndexBuffer;\n dataOffset += 1;\n }\n if (!this._isBillboardBased) {\n var directionBuffer = this._vertexBuffer.createVertexBuffer(\"direction\", dataOffset, 3, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"direction\"] = directionBuffer;\n dataOffset += 3;\n }\n var offsets;\n if (this._useInstancing) {\n var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);\n this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);\n offsets = this._spriteBuffer.createVertexBuffer(\"offset\", 0, 2);\n }\n else {\n offsets = this._vertexBuffer.createVertexBuffer(\"offset\", dataOffset, 2, this._vertexBufferSize, this._useInstancing);\n dataOffset += 2;\n }\n this._vertexBuffers[\"offset\"] = offsets;\n };\n ParticleSystem.prototype._createIndexBuffer = function () {\n if (this._useInstancing) {\n return;\n }\n var indices = [];\n var index = 0;\n for (var count = 0; count < this._capacity; count++) {\n indices.push(index);\n indices.push(index + 1);\n indices.push(index + 2);\n indices.push(index);\n indices.push(index + 2);\n indices.push(index + 3);\n index += 4;\n }\n this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);\n };\n /**\n * Gets the maximum number of particles active at the same time.\n * @returns The max number of active particles.\n */\n ParticleSystem.prototype.getCapacity = function () {\n return this._capacity;\n };\n /**\n * Gets Wether there are still active particles in the system.\n * @returns True if it is alive, otherwise false.\n */\n ParticleSystem.prototype.isAlive = function () {\n return this._alive;\n };\n /**\n * Gets Wether the system has been started.\n * @returns True if it has been started, otherwise false.\n */\n ParticleSystem.prototype.isStarted = function () {\n return this._started;\n };\n /**\n * Starts the particle system and begins to emit\n * @param delay defines the delay in milliseconds before starting the system (0 by default)\n */\n ParticleSystem.prototype.start = function (delay) {\n var _this = this;\n if (delay === void 0) { delay = 0; }\n if (delay) {\n setTimeout(function () {\n _this.start(0);\n }, delay);\n return;\n }\n this._started = true;\n this._stopped = false;\n this._actualFrame = 0;\n if (this.subEmitters && this.subEmitters.length != 0) {\n this.activeSubSystems = new Array();\n }\n if (this.preWarmCycles) {\n for (var index = 0; index < this.preWarmCycles; index++) {\n this.animate(true);\n }\n }\n };\n /**\n * Stops the particle system.\n * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.\n */\n ParticleSystem.prototype.stop = function (stopSubEmitters) {\n if (stopSubEmitters === void 0) { stopSubEmitters = true; }\n this._stopped = true;\n if (stopSubEmitters) {\n this._stopSubEmitters();\n }\n };\n // animation sheet\n /**\n * Remove all active particles\n */\n ParticleSystem.prototype.reset = function () {\n this._stockParticles = [];\n this._particles = [];\n };\n /**\n * @hidden (for internal use only)\n */\n ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {\n var offset = index * this._vertexBufferSize;\n this._vertexData[offset++] = particle.position.x;\n this._vertexData[offset++] = particle.position.y;\n this._vertexData[offset++] = particle.position.z;\n this._vertexData[offset++] = particle.color.r;\n this._vertexData[offset++] = particle.color.g;\n this._vertexData[offset++] = particle.color.b;\n this._vertexData[offset++] = particle.color.a;\n this._vertexData[offset++] = particle.angle;\n this._vertexData[offset++] = particle.scale.x * particle.size;\n this._vertexData[offset++] = particle.scale.y * particle.size;\n if (this._isAnimationSheetEnabled) {\n this._vertexData[offset++] = particle.cellIndex;\n }\n if (!this._isBillboardBased) {\n if (particle._initialDirection) {\n this._vertexData[offset++] = particle._initialDirection.x;\n this._vertexData[offset++] = particle._initialDirection.y;\n this._vertexData[offset++] = particle._initialDirection.z;\n }\n else {\n this._vertexData[offset++] = particle.direction.x;\n this._vertexData[offset++] = particle.direction.y;\n this._vertexData[offset++] = particle.direction.z;\n }\n }\n if (!this._useInstancing) {\n if (this._isAnimationSheetEnabled) {\n if (offsetX === 0)\n offsetX = this._epsilon;\n else if (offsetX === 1)\n offsetX = 1 - this._epsilon;\n if (offsetY === 0)\n offsetY = this._epsilon;\n else if (offsetY === 1)\n offsetY = 1 - this._epsilon;\n }\n this._vertexData[offset++] = offsetX;\n this._vertexData[offset++] = offsetY;\n }\n };\n ParticleSystem.prototype._stopSubEmitters = function () {\n if (!this.activeSubSystems) {\n return;\n }\n this.activeSubSystems.forEach(function (subSystem) {\n subSystem.stop(true);\n });\n this.activeSubSystems = new Array();\n };\n ParticleSystem.prototype._removeFromRoot = function () {\n if (!this._rootParticleSystem) {\n return;\n }\n var index = this._rootParticleSystem.activeSubSystems.indexOf(this);\n if (index !== -1) {\n this._rootParticleSystem.activeSubSystems.splice(index, 1);\n }\n };\n // End of sub system methods\n ParticleSystem.prototype._update = function (newParticles) {\n // Update current\n this._alive = this._particles.length > 0;\n if (this.emitter.position) {\n var emitterMesh = this.emitter;\n this._emitterWorldMatrix = emitterMesh.getWorldMatrix();\n }\n else {\n var emitterPosition = this.emitter;\n this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);\n }\n this.updateFunction(this._particles);\n // Add new ones\n var particle;\n var _loop_2 = function () {\n if (this_1._particles.length === this_1._capacity) {\n return \"break\";\n }\n particle = this_1._createParticle();\n this_1._particles.push(particle);\n // Emitter\n var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);\n if (this_1.startPositionFunction) {\n this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);\n }\n else {\n this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);\n }\n if (this_1.startDirectionFunction) {\n this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);\n }\n else {\n this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);\n }\n if (emitPower === 0) {\n if (!particle._initialDirection) {\n particle._initialDirection = particle.direction.clone();\n }\n else {\n particle._initialDirection.copyFrom(particle.direction);\n }\n }\n else {\n particle._initialDirection = null;\n }\n particle.direction.scaleInPlace(emitPower);\n // Life time\n if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {\n var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);\n BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {\n var factorGradient1 = currentGradient;\n var factorGradient2 = nextGradient;\n var lifeTime1 = factorGradient1.getFactor();\n var lifeTime2 = factorGradient2.getFactor();\n var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);\n particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);\n });\n }\n else {\n particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);\n }\n // Size\n if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {\n particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);\n }\n else {\n particle._currentSizeGradient = this_1._sizeGradients[0];\n particle._currentSize1 = particle._currentSizeGradient.getFactor();\n particle.size = particle._currentSize1;\n if (this_1._sizeGradients.length > 1) {\n particle._currentSize2 = this_1._sizeGradients[1].getFactor();\n }\n else {\n particle._currentSize2 = particle._currentSize1;\n }\n }\n // Size and scale\n particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));\n // Angle\n if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {\n particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);\n }\n else {\n particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];\n particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();\n particle._currentAngularSpeed1 = particle.angularSpeed;\n if (this_1._angularSpeedGradients.length > 1) {\n particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();\n }\n else {\n particle._currentAngularSpeed2 = particle._currentAngularSpeed1;\n }\n }\n particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);\n // Velocity\n if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {\n particle._currentVelocityGradient = this_1._velocityGradients[0];\n particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();\n if (this_1._velocityGradients.length > 1) {\n particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();\n }\n else {\n particle._currentVelocity2 = particle._currentVelocity1;\n }\n }\n // Color\n if (!this_1._colorGradients || this_1._colorGradients.length === 0) {\n step = BABYLON.Scalar.RandomRange(0, 1.0);\n BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);\n this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);\n this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);\n }\n else {\n particle._currentColorGradient = this_1._colorGradients[0];\n particle._currentColorGradient.getColorToRef(particle.color);\n particle._currentColor1.copyFrom(particle.color);\n if (this_1._colorGradients.length > 1) {\n this_1._colorGradients[1].getColorToRef(particle._currentColor2);\n }\n else {\n particle._currentColor2.copyFrom(particle.color);\n }\n }\n // Sheet\n if (this_1._isAnimationSheetEnabled) {\n particle._initialStartSpriteCellID = this_1.startSpriteCellID;\n particle._initialEndSpriteCellID = this_1.endSpriteCellID;\n }\n };\n var this_1 = this, step;\n for (var index = 0; index < newParticles; index++) {\n var state_1 = _loop_2();\n if (state_1 === \"break\")\n break;\n }\n };\n /** @hidden */\n ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {\n if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }\n if (isBillboardBased === void 0) { isBillboardBased = false; }\n var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, \"angle\", \"offset\", \"size\"];\n if (isAnimationSheetEnabled) {\n attributeNamesOrOptions.push(\"cellIndex\");\n }\n if (!isBillboardBased) {\n attributeNamesOrOptions.push(\"direction\");\n }\n return attributeNamesOrOptions;\n };\n ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {\n if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }\n var effectCreationOption = [\"invView\", \"view\", \"projection\", \"vClipPlane\", \"textureMask\", \"translationPivot\", \"eyePosition\"];\n if (isAnimationSheetEnabled) {\n effectCreationOption.push(\"particlesInfos\");\n }\n return effectCreationOption;\n };\n ParticleSystem.prototype._getEffect = function () {\n if (this._customEffect) {\n return this._customEffect;\n }\n ;\n var defines = [];\n if (this._scene.clipPlane) {\n defines.push(\"#define CLIPPLANE\");\n }\n if (this._isAnimationSheetEnabled) {\n defines.push(\"#define ANIMATESHEET\");\n }\n if (this._isBillboardBased) {\n defines.push(\"#define BILLBOARD\");\n switch (this.billboardMode) {\n case BABYLON.AbstractMesh.BILLBOARDMODE_Y:\n defines.push(\"#define BILLBOARDY\");\n break;\n case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:\n default:\n break;\n }\n }\n // Effect\n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);\n var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);\n this._effect = this._scene.getEngine().createEffect(\"particles\", attributesNamesOrOptions, effectCreationOption, [\"diffuseSampler\"], join);\n }\n return this._effect;\n };\n /**\n * Animates the particle system for the current frame by emitting new particles and or animating the living ones.\n * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)\n */\n ParticleSystem.prototype.animate = function (preWarmOnly) {\n if (preWarmOnly === void 0) { preWarmOnly = false; }\n if (!this._started)\n return;\n if (!preWarmOnly) {\n var effect = this._getEffect();\n // Check\n if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())\n return;\n if (this._currentRenderId === this._scene.getRenderId()) {\n return;\n }\n this._currentRenderId = this._scene.getRenderId();\n }\n this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());\n // determine the number of particles we need to create\n var newParticles;\n if (this.manualEmitCount > -1) {\n newParticles = this.manualEmitCount;\n this._newPartsExcess = 0;\n this.manualEmitCount = 0;\n }\n else {\n newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);\n this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;\n }\n if (this._newPartsExcess > 1.0) {\n newParticles += this._newPartsExcess >> 0;\n this._newPartsExcess -= this._newPartsExcess >> 0;\n }\n this._alive = false;\n if (!this._stopped) {\n this._actualFrame += this._scaledUpdateSpeed;\n if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)\n this.stop();\n }\n else {\n newParticles = 0;\n }\n this._update(newParticles);\n // Stopped?\n if (this._stopped) {\n if (!this._alive) {\n this._started = false;\n if (this.onAnimationEnd) {\n this.onAnimationEnd();\n }\n if (this.disposeOnStop) {\n this._scene._toBeDisposed.push(this);\n }\n }\n }\n if (!preWarmOnly) {\n // Update VBO\n var offset = 0;\n for (var index = 0; index < this._particles.length; index++) {\n var particle = this._particles[index];\n this._appendParticleVertices(offset, particle);\n offset += this._useInstancing ? 1 : 4;\n }\n if (this._vertexBuffer) {\n this._vertexBuffer.update(this._vertexData);\n }\n }\n if (this.manualEmitCount === 0 && this.disposeOnStop) {\n this.stop();\n }\n };\n ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {\n this._appendParticleVertex(offset++, particle, 0, 0);\n if (!this._useInstancing) {\n this._appendParticleVertex(offset++, particle, 1, 0);\n this._appendParticleVertex(offset++, particle, 1, 1);\n this._appendParticleVertex(offset++, particle, 0, 1);\n }\n };\n /**\n * Rebuilds the particle system.\n */\n ParticleSystem.prototype.rebuild = function () {\n this._createIndexBuffer();\n if (this._vertexBuffer) {\n this._vertexBuffer._rebuild();\n }\n };\n /**\n * Is this system ready to be used/rendered\n * @return true if the system is ready\n */\n ParticleSystem.prototype.isReady = function () {\n var effect = this._getEffect();\n if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {\n return false;\n }\n return true;\n };\n /**\n * Renders the particle system in its current state.\n * @returns the current number of particles\n */\n ParticleSystem.prototype.render = function () {\n var effect = this._getEffect();\n // Check\n if (!this.isReady() || !this._particles.length) {\n return 0;\n }\n var engine = this._scene.getEngine();\n // Render\n engine.enableEffect(effect);\n engine.setState(false);\n var viewMatrix = this._scene.getViewMatrix();\n effect.setTexture(\"diffuseSampler\", this.particleTexture);\n effect.setMatrix(\"view\", viewMatrix);\n effect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n if (this._isAnimationSheetEnabled && this.particleTexture) {\n var baseSize = this.particleTexture.getBaseSize();\n effect.setFloat3(\"particlesInfos\", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);\n }\n effect.setVector2(\"translationPivot\", this.translationPivot);\n effect.setFloat4(\"textureMask\", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);\n if (this._isBillboardBased) {\n var camera = this._scene.activeCamera;\n effect.setVector3(\"eyePosition\", camera.globalPosition);\n }\n if (this._scene.clipPlane) {\n var clipPlane = this._scene.clipPlane;\n var invView = viewMatrix.clone();\n invView.invert();\n effect.setMatrix(\"invView\", invView);\n effect.setFloat4(\"vClipPlane\", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);\n }\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n // Draw order\n switch (this.blendMode) {\n case ParticleSystem.BLENDMODE_ADD:\n engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);\n break;\n case ParticleSystem.BLENDMODE_ONEONE:\n engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);\n break;\n case ParticleSystem.BLENDMODE_STANDARD:\n engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);\n break;\n }\n if (this.forceDepthWrite) {\n engine.setDepthWrite(true);\n }\n if (this._useInstancing) {\n engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);\n engine.unbindInstanceAttributes();\n }\n else {\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);\n }\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n return this._particles.length;\n };\n /**\n * Disposes the particle system and free the associated resources\n * @param disposeTexture defines if the particule texture must be disposed as well (true by default)\n */\n ParticleSystem.prototype.dispose = function (disposeTexture) {\n if (disposeTexture === void 0) { disposeTexture = true; }\n if (this._vertexBuffer) {\n this._vertexBuffer.dispose();\n this._vertexBuffer = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n if (disposeTexture && this.particleTexture) {\n this.particleTexture.dispose();\n this.particleTexture = null;\n }\n if (disposeTexture && this.noiseTexture) {\n this.noiseTexture.dispose();\n this.noiseTexture = null;\n }\n this._removeFromRoot();\n // Remove from scene\n var index = this._scene.particleSystems.indexOf(this);\n if (index > -1) {\n this._scene.particleSystems.splice(index, 1);\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n };\n /**\n * Creates a Point Emitter for the particle system (emits directly from the emitter position)\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the box\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the box\n * @returns the emitter\n */\n ParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {\n var particleEmitter = new BABYLON.PointParticleEmitter();\n particleEmitter.direction1 = direction1;\n particleEmitter.direction2 = direction2;\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n };\n /**\n * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)\n * @param radius The radius of the hemisphere to emit from\n * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius\n * @returns the emitter\n */\n ParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {\n if (radius === void 0) { radius = 1; }\n if (radiusRange === void 0) { radiusRange = 1; }\n var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n };\n /**\n * Creates a Sphere Emitter for the particle system (emits along the sphere radius)\n * @param radius The radius of the sphere to emit from\n * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius\n * @returns the emitter\n */\n ParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {\n if (radius === void 0) { radius = 1; }\n if (radiusRange === void 0) { radiusRange = 1; }\n var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n };\n /**\n * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)\n * @param radius The radius of the sphere to emit from\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere\n * @returns the emitter\n */\n ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {\n if (radius === void 0) { radius = 1; }\n if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }\n if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }\n var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n };\n /**\n * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)\n * @param radius The radius of the cone to emit from\n * @param angle The base angle of the cone\n * @returns the emitter\n */\n ParticleSystem.prototype.createConeEmitter = function (radius, angle) {\n if (radius === void 0) { radius = 1; }\n if (angle === void 0) { angle = Math.PI / 4; }\n var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n };\n /**\n * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the box\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the box\n * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox\n * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox\n * @returns the emitter\n */\n ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {\n var particleEmitter = new BABYLON.BoxParticleEmitter();\n this.particleEmitterType = particleEmitter;\n this.direction1 = direction1;\n this.direction2 = direction2;\n this.minEmitBox = minEmitBox;\n this.maxEmitBox = maxEmitBox;\n return particleEmitter;\n };\n // Clone\n /**\n * Clones the particle system.\n * @param name The name of the cloned object\n * @param newEmitter The new emitter to use\n * @returns the cloned particle system\n */\n ParticleSystem.prototype.clone = function (name, newEmitter) {\n var custom = null;\n var program = null;\n if (this.customShader != null) {\n program = this.customShader;\n var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join(\"\\n\") : \"\";\n custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);\n }\n else if (this._customEffect) {\n custom = this._customEffect;\n }\n var result = new ParticleSystem(name, this._capacity, this._scene, custom);\n result.customShader = program;\n BABYLON.Tools.DeepCopy(this, result, [\"particles\", \"customShader\"]);\n if (newEmitter === undefined) {\n newEmitter = this.emitter;\n }\n result.emitter = newEmitter;\n if (this.particleTexture) {\n result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);\n }\n if (!this.preventAutoStart) {\n result.start();\n }\n return result;\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n ParticleSystem.prototype.serialize = function () {\n var serializationObject = {};\n ParticleSystem._Serialize(serializationObject, this);\n serializationObject.textureMask = this.textureMask.asArray();\n serializationObject.customShader = this.customShader;\n serializationObject.preventAutoStart = this.preventAutoStart;\n serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;\n return serializationObject;\n };\n /** @hidden */\n ParticleSystem._Serialize = function (serializationObject, particleSystem) {\n serializationObject.name = particleSystem.name;\n serializationObject.id = particleSystem.id;\n serializationObject.capacity = particleSystem.getCapacity();\n // Emitter\n if (particleSystem.emitter.position) {\n var emitterMesh = particleSystem.emitter;\n serializationObject.emitterId = emitterMesh.id;\n }\n else {\n var emitterPosition = particleSystem.emitter;\n serializationObject.emitter = emitterPosition.asArray();\n }\n // Emitter\n if (particleSystem.particleEmitterType) {\n serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();\n }\n if (particleSystem.particleTexture) {\n serializationObject.textureName = particleSystem.particleTexture.name;\n }\n // Animations\n BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);\n // Particle system\n serializationObject.renderingGroupId = particleSystem.renderingGroupId;\n serializationObject.isBillboardBased = particleSystem.isBillboardBased;\n serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;\n serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;\n serializationObject.minSize = particleSystem.minSize;\n serializationObject.maxSize = particleSystem.maxSize;\n serializationObject.minScaleX = particleSystem.minScaleX;\n serializationObject.maxScaleX = particleSystem.maxScaleX;\n serializationObject.minScaleY = particleSystem.minScaleY;\n serializationObject.maxScaleY = particleSystem.maxScaleY;\n serializationObject.minEmitPower = particleSystem.minEmitPower;\n serializationObject.maxEmitPower = particleSystem.maxEmitPower;\n serializationObject.minLifeTime = particleSystem.minLifeTime;\n serializationObject.maxLifeTime = particleSystem.maxLifeTime;\n serializationObject.emitRate = particleSystem.emitRate;\n serializationObject.gravity = particleSystem.gravity.asArray();\n serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();\n serializationObject.color1 = particleSystem.color1.asArray();\n serializationObject.color2 = particleSystem.color2.asArray();\n serializationObject.colorDead = particleSystem.colorDead.asArray();\n serializationObject.updateSpeed = particleSystem.updateSpeed;\n serializationObject.targetStopDuration = particleSystem.targetStopDuration;\n serializationObject.blendMode = particleSystem.blendMode;\n serializationObject.preWarmCycles = particleSystem.preWarmCycles;\n serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;\n serializationObject.minInitialRotation = particleSystem.minInitialRotation;\n serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;\n serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;\n serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;\n serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;\n serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;\n serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;\n var colorGradients = particleSystem.getColorGradients();\n if (colorGradients) {\n serializationObject.colorGradients = [];\n for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {\n var colorGradient = colorGradients_1[_i];\n var serializedGradient = {\n gradient: colorGradient.gradient,\n color1: colorGradient.color1.asArray()\n };\n if (colorGradient.color2) {\n serializedGradient.color2 = colorGradient.color2.asArray();\n }\n serializationObject.colorGradients.push(serializedGradient);\n }\n }\n var sizeGradients = particleSystem.getSizeGradients();\n if (sizeGradients) {\n serializationObject.sizeGradients = [];\n for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {\n var sizeGradient = sizeGradients_1[_a];\n var serializedGradient = {\n gradient: sizeGradient.gradient,\n factor1: sizeGradient.factor1\n };\n if (sizeGradient.factor2 !== undefined) {\n serializedGradient.factor2 = sizeGradient.factor2;\n }\n serializationObject.sizeGradients.push(serializedGradient);\n }\n }\n var angularSpeedGradients = particleSystem.getAngularSpeedGradients();\n if (angularSpeedGradients) {\n serializationObject.angularSpeedGradients = [];\n for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {\n var angularSpeedGradient = angularSpeedGradients_1[_b];\n var serializedGradient = {\n gradient: angularSpeedGradient.gradient,\n factor1: angularSpeedGradient.factor1\n };\n if (angularSpeedGradient.factor2 !== undefined) {\n serializedGradient.factor2 = angularSpeedGradient.factor2;\n }\n serializationObject.angularSpeedGradients.push(serializedGradient);\n }\n }\n var velocityGradients = particleSystem.getVelocityGradients();\n if (velocityGradients) {\n serializationObject.velocityGradients = [];\n for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {\n var velocityGradient = velocityGradients_1[_c];\n var serializedGradient = {\n gradient: velocityGradient.gradient,\n factor1: velocityGradient.factor1\n };\n if (velocityGradient.factor2 !== undefined) {\n serializedGradient.factor2 = velocityGradient.factor2;\n }\n serializationObject.velocityGradients.push(serializedGradient);\n }\n }\n if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {\n var noiseTexture = particleSystem.noiseTexture;\n serializationObject.noiseTexture = noiseTexture.serialize();\n }\n };\n /** @hidden */\n ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {\n // Texture\n if (parsedParticleSystem.textureName) {\n particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);\n particleSystem.particleTexture.name = parsedParticleSystem.textureName;\n }\n // Emitter\n if (parsedParticleSystem.emitterId === undefined) {\n particleSystem.emitter = BABYLON.Vector3.Zero();\n }\n else if (parsedParticleSystem.emitterId) {\n particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);\n }\n else {\n particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);\n }\n // Misc.\n if (parsedParticleSystem.renderingGroupId !== undefined) {\n particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;\n }\n if (parsedParticleSystem.isBillboardBased !== undefined) {\n particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;\n }\n // Animations\n if (parsedParticleSystem.animations) {\n for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {\n var parsedAnimation = parsedParticleSystem.animations[animationIndex];\n particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n }\n if (parsedParticleSystem.autoAnimate) {\n scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);\n }\n // Particle system\n particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;\n particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;\n particleSystem.minSize = parsedParticleSystem.minSize;\n particleSystem.maxSize = parsedParticleSystem.maxSize;\n if (parsedParticleSystem.minScaleX) {\n particleSystem.minScaleX = parsedParticleSystem.minScaleX;\n particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;\n particleSystem.minScaleY = parsedParticleSystem.minScaleY;\n particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;\n }\n if (parsedParticleSystem.preWarmCycles !== undefined) {\n particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;\n particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;\n }\n if (parsedParticleSystem.minInitialRotation !== undefined) {\n particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;\n particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;\n }\n particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;\n particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;\n particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;\n particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;\n particleSystem.emitRate = parsedParticleSystem.emitRate;\n particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);\n if (parsedParticleSystem.noiseStrength) {\n particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);\n }\n particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);\n particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);\n particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);\n particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;\n particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;\n particleSystem.blendMode = parsedParticleSystem.blendMode;\n if (parsedParticleSystem.colorGradients) {\n for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {\n var colorGradient = _a[_i];\n particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);\n }\n }\n if (parsedParticleSystem.sizeGradients) {\n for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {\n var sizeGradient = _c[_b];\n particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);\n }\n }\n if (parsedParticleSystem.angularSpeedGradients) {\n for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {\n var angularSpeedGradient = _e[_d];\n particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);\n }\n }\n if (parsedParticleSystem.velocityGradients) {\n for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {\n var velocityGradient = _g[_f];\n particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);\n }\n }\n if (parsedParticleSystem.noiseTexture) {\n particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);\n }\n // Emitter\n var emitterType;\n if (parsedParticleSystem.particleEmitterType) {\n switch (parsedParticleSystem.particleEmitterType.type) {\n case \"SphereParticleEmitter\":\n emitterType = new BABYLON.SphereParticleEmitter();\n break;\n case \"SphereDirectedParticleEmitter\":\n emitterType = new BABYLON.SphereDirectedParticleEmitter();\n break;\n case \"ConeEmitter\":\n case \"ConeParticleEmitter\":\n emitterType = new BABYLON.ConeParticleEmitter();\n break;\n case \"BoxEmitter\":\n case \"BoxParticleEmitter\":\n default:\n emitterType = new BABYLON.BoxParticleEmitter();\n break;\n }\n emitterType.parse(parsedParticleSystem.particleEmitterType);\n }\n else {\n emitterType = new BABYLON.BoxParticleEmitter();\n emitterType.parse(parsedParticleSystem);\n }\n particleSystem.particleEmitterType = emitterType;\n // Animation sheet\n particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;\n particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;\n particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;\n particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;\n particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;\n };\n /**\n * Parses a JSON object to create a particle system.\n * @param parsedParticleSystem The JSON object to parse\n * @param scene The scene to create the particle system in\n * @param rootUrl The root url to use to load external dependencies like texture\n * @returns the Parsed particle system\n */\n ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {\n var name = parsedParticleSystem.name;\n var custom = null;\n var program = null;\n if (parsedParticleSystem.customShader) {\n program = parsedParticleSystem.customShader;\n var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join(\"\\n\") : \"\";\n custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);\n }\n var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);\n particleSystem.customShader = program;\n if (parsedParticleSystem.id) {\n particleSystem.id = parsedParticleSystem.id;\n }\n // Auto start\n if (parsedParticleSystem.preventAutoStart) {\n particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;\n }\n ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);\n particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);\n if (!particleSystem.preventAutoStart) {\n particleSystem.start();\n }\n return particleSystem;\n };\n /**\n * Source color is added to the destination color without alpha affecting the result.\n */\n ParticleSystem.BLENDMODE_ONEONE = 0;\n /**\n * Blend current color and particle color using particle’s alpha.\n */\n ParticleSystem.BLENDMODE_STANDARD = 1;\n /**\n * Add current color and particle color multiplied by particle’s alpha.\n */\n ParticleSystem.BLENDMODE_ADD = 2;\n return ParticleSystem;\n }());\n BABYLON.ParticleSystem = ParticleSystem;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.particleSystem.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Particle emitter emitting particles from the inside of a box.\n * It emits the particles randomly between 2 given directions.\n */\n var BoxParticleEmitter = /** @class */ (function () {\n /**\n * Creates a new instance BoxParticleEmitter\n */\n function BoxParticleEmitter() {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction1 = new BABYLON.Vector3(0, 1.0, 0);\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction2 = new BABYLON.Vector3(0, 1.0, 0);\n /**\n * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n */\n this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);\n /**\n * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n */\n this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n */\n BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {\n var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);\n var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);\n var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n };\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n */\n BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {\n var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);\n var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);\n var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);\n };\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n BoxParticleEmitter.prototype.clone = function () {\n var newOne = new BoxParticleEmitter();\n BABYLON.Tools.DeepCopy(this, newOne);\n return newOne;\n };\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param effect defines the update shader\n */\n BoxParticleEmitter.prototype.applyToShader = function (effect) {\n effect.setVector3(\"direction1\", this.direction1);\n effect.setVector3(\"direction2\", this.direction2);\n effect.setVector3(\"minEmitBox\", this.minEmitBox);\n effect.setVector3(\"maxEmitBox\", this.maxEmitBox);\n };\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containng the defines string\n */\n BoxParticleEmitter.prototype.getEffectDefines = function () {\n return \"#define BOXEMITTER\";\n };\n /**\n * Returns the string \"BoxParticleEmitter\"\n * @returns a string containing the class name\n */\n BoxParticleEmitter.prototype.getClassName = function () {\n return \"BoxParticleEmitter\";\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n BoxParticleEmitter.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n serializationObject.minEmitBox = this.minEmitBox.asArray();\n serializationObject.maxEmitBox = this.maxEmitBox.asArray();\n return serializationObject;\n };\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n BoxParticleEmitter.prototype.parse = function (serializationObject) {\n BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);\n BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);\n BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);\n BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);\n };\n return BoxParticleEmitter;\n }());\n BABYLON.BoxParticleEmitter = BoxParticleEmitter;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boxParticleEmitter.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Particle emitter emitting particles from the inside of a cone.\n * It emits the particles alongside the cone volume from the base to the particle.\n * The emission direction might be randomized.\n */\n var ConeParticleEmitter = /** @class */ (function () {\n /**\n * Creates a new instance ConeParticleEmitter\n * @param radius the radius of the emission cone (1 by default)\n * @param angles the cone base angle (PI by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)\n */\n function ConeParticleEmitter(radius, angle, \n /** defines how much to randomize the particle direction [0-1] (default is 0) */\n directionRandomizer) {\n if (radius === void 0) { radius = 1; }\n if (angle === void 0) { angle = Math.PI; }\n if (directionRandomizer === void 0) { directionRandomizer = 0; }\n this.directionRandomizer = directionRandomizer;\n /**\n * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)\n */\n this.radiusRange = 1;\n /**\n * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)\n */\n this.heightRange = 1;\n /**\n * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)\n */\n this.emitFromSpawnPointOnly = false;\n this.angle = angle;\n this.radius = radius;\n }\n Object.defineProperty(ConeParticleEmitter.prototype, \"radius\", {\n /**\n * Gets or sets the radius of the emission cone\n */\n get: function () {\n return this._radius;\n },\n set: function (value) {\n this._radius = value;\n this._buildHeight();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ConeParticleEmitter.prototype, \"angle\", {\n /**\n * Gets or sets the angle of the emission cone\n */\n get: function () {\n return this._angle;\n },\n set: function (value) {\n this._angle = value;\n this._buildHeight();\n },\n enumerable: true,\n configurable: true\n });\n ConeParticleEmitter.prototype._buildHeight = function () {\n if (this._angle !== 0) {\n this._height = this._radius / Math.tan(this._angle / 2);\n }\n else {\n this._height = 1;\n }\n };\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n */\n ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {\n if (Math.abs(Math.cos(this._angle)) === 1.0) {\n BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);\n }\n else {\n // measure the direction Vector from the emitter to the particle.\n var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();\n var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n direction.x += randX;\n direction.y += randY;\n direction.z += randZ;\n direction.normalize();\n BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);\n }\n };\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n */\n ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {\n var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);\n var h;\n if (!this.emitFromSpawnPointOnly) {\n h = BABYLON.Scalar.RandomRange(0, this.heightRange);\n // Better distribution in a cone at normal angles.\n h = 1 - h * h;\n }\n else {\n h = 0.0001;\n }\n var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);\n radius = radius * h;\n var randX = radius * Math.sin(s);\n var randZ = radius * Math.cos(s);\n var randY = h * this._height;\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);\n };\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n ConeParticleEmitter.prototype.clone = function () {\n var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);\n BABYLON.Tools.DeepCopy(this, newOne);\n return newOne;\n };\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param effect defines the update shader\n */\n ConeParticleEmitter.prototype.applyToShader = function (effect) {\n effect.setFloat2(\"radius\", this._radius, this.radiusRange);\n effect.setFloat(\"coneAngle\", this._angle);\n effect.setFloat2(\"height\", this._height, this.heightRange);\n effect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n };\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containng the defines string\n */\n ConeParticleEmitter.prototype.getEffectDefines = function () {\n var defines = \"#define CONEEMITTER\";\n if (this.emitFromSpawnPointOnly) {\n defines += \"\\n#define CONEEMITTERSPAWNPOINT\";\n }\n return defines;\n };\n /**\n * Returns the string \"ConeParticleEmitter\"\n * @returns a string containing the class name\n */\n ConeParticleEmitter.prototype.getClassName = function () {\n return \"ConeParticleEmitter\";\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n ConeParticleEmitter.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this._radius;\n serializationObject.angle = this._angle;\n serializationObject.directionRandomizer = this.directionRandomizer;\n return serializationObject;\n };\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n ConeParticleEmitter.prototype.parse = function (serializationObject) {\n this.radius = serializationObject.radius;\n this.angle = serializationObject.angle;\n this.directionRandomizer = serializationObject.directionRandomizer;\n };\n return ConeParticleEmitter;\n }());\n BABYLON.ConeParticleEmitter = ConeParticleEmitter;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.coneParticleEmitter.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Particle emitter emitting particles from the inside of a sphere.\n * It emits the particles alongside the sphere radius. The emission direction might be randomized.\n */\n var SphereParticleEmitter = /** @class */ (function () {\n /**\n * Creates a new instance SphereParticleEmitter\n * @param radius the radius of the emission sphere (1 by default)\n * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1]\n */\n function SphereParticleEmitter(\n /**\n * The radius of the emission sphere.\n */\n radius, \n /**\n * The range of emission [0-1] 0 Surface only, 1 Entire Radius.\n */\n radiusRange, \n /**\n * How much to randomize the particle direction [0-1].\n */\n directionRandomizer) {\n if (radius === void 0) { radius = 1; }\n if (radiusRange === void 0) { radiusRange = 1; }\n if (directionRandomizer === void 0) { directionRandomizer = 0; }\n this.radius = radius;\n this.radiusRange = radiusRange;\n this.directionRandomizer = directionRandomizer;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n */\n SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {\n var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();\n var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n direction.x += randX;\n direction.y += randY;\n direction.z += randZ;\n direction.normalize();\n BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);\n };\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n */\n SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {\n var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);\n var v = BABYLON.Scalar.RandomRange(0, 1.0);\n var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);\n var theta = Math.acos(2 * v - 1);\n var randX = randRadius * Math.cos(phi) * Math.sin(theta);\n var randY = randRadius * Math.cos(theta);\n var randZ = randRadius * Math.sin(phi) * Math.sin(theta);\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);\n };\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n SphereParticleEmitter.prototype.clone = function () {\n var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);\n BABYLON.Tools.DeepCopy(this, newOne);\n return newOne;\n };\n /**\n * Called by the {BABYLON.GPUParticleSystem} to setup the update shader\n * @param effect defines the update shader\n */\n SphereParticleEmitter.prototype.applyToShader = function (effect) {\n effect.setFloat(\"radius\", this.radius);\n effect.setFloat(\"radiusRange\", this.radiusRange);\n effect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n };\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containng the defines string\n */\n SphereParticleEmitter.prototype.getEffectDefines = function () {\n return \"#define SPHEREEMITTER\";\n };\n /**\n * Returns the string \"SphereParticleEmitter\"\n * @returns a string containing the class name\n */\n SphereParticleEmitter.prototype.getClassName = function () {\n return \"SphereParticleEmitter\";\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n SphereParticleEmitter.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this.radius;\n serializationObject.radiusRange = this.radiusRange;\n serializationObject.directionRandomizer = this.directionRandomizer;\n return serializationObject;\n };\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n SphereParticleEmitter.prototype.parse = function (serializationObject) {\n this.radius = serializationObject.radius;\n this.radiusRange = serializationObject.radiusRange;\n this.directionRandomizer = serializationObject.directionRandomizer;\n };\n return SphereParticleEmitter;\n }());\n BABYLON.SphereParticleEmitter = SphereParticleEmitter;\n /**\n * Particle emitter emitting particles from the inside of a sphere.\n * It emits the particles randomly between two vectors.\n */\n var SphereDirectedParticleEmitter = /** @class */ (function (_super) {\n __extends(SphereDirectedParticleEmitter, _super);\n /**\n * Creates a new instance SphereDirectedParticleEmitter\n * @param radius the radius of the emission sphere (1 by default)\n * @param direction1 the min limit of the emission direction (up vector by default)\n * @param direction2 the max limit of the emission direction (up vector by default)\n */\n function SphereDirectedParticleEmitter(radius, \n /**\n * The min limit of the emission direction.\n */\n direction1, \n /**\n * The max limit of the emission direction.\n */\n direction2) {\n if (radius === void 0) { radius = 1; }\n if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }\n if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }\n var _this = _super.call(this, radius) || this;\n _this.direction1 = direction1;\n _this.direction2 = direction2;\n return _this;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n */\n SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {\n var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);\n var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);\n var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n };\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n SphereDirectedParticleEmitter.prototype.clone = function () {\n var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);\n BABYLON.Tools.DeepCopy(this, newOne);\n return newOne;\n };\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param effect defines the update shader\n */\n SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {\n effect.setFloat(\"radius\", this.radius);\n effect.setFloat(\"radiusRange\", this.radiusRange);\n effect.setVector3(\"direction1\", this.direction1);\n effect.setVector3(\"direction2\", this.direction2);\n };\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containng the defines string\n */\n SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {\n return \"#define SPHEREEMITTER\\n#define DIRECTEDSPHEREEMITTER\";\n };\n /**\n * Returns the string \"SphereDirectedParticleEmitter\"\n * @returns a string containing the class name\n */\n SphereDirectedParticleEmitter.prototype.getClassName = function () {\n return \"SphereDirectedParticleEmitter\";\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n SphereDirectedParticleEmitter.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n return serializationObject;\n };\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {\n _super.prototype.parse.call(this, serializationObject);\n this.direction1.copyFrom(serializationObject.direction1);\n this.direction2.copyFrom(serializationObject.direction2);\n };\n return SphereDirectedParticleEmitter;\n }(SphereParticleEmitter));\n BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sphereParticleEmitter.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Particle emitter emitting particles from the inside of a hemisphere.\n * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.\n */\n var HemisphericParticleEmitter = /** @class */ (function () {\n /**\n * Creates a new instance HemisphericParticleEmitter\n * @param radius the radius of the emission hemisphere (1 by default)\n * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1]\n */\n function HemisphericParticleEmitter(\n /**\n * The radius of the emission hemisphere.\n */\n radius, \n /**\n * The range of emission [0-1] 0 Surface only, 1 Entire Radius.\n */\n radiusRange, \n /**\n * How much to randomize the particle direction [0-1].\n */\n directionRandomizer) {\n if (radius === void 0) { radius = 1; }\n if (radiusRange === void 0) { radiusRange = 1; }\n if (directionRandomizer === void 0) { directionRandomizer = 0; }\n this.radius = radius;\n this.radiusRange = radiusRange;\n this.directionRandomizer = directionRandomizer;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n */\n HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {\n var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();\n var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n direction.x += randX;\n direction.y += randY;\n direction.z += randZ;\n direction.normalize();\n BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);\n };\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n */\n HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {\n var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);\n var v = BABYLON.Scalar.RandomRange(0, 1.0);\n var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);\n var theta = Math.acos(2 * v - 1);\n var randX = randRadius * Math.cos(phi) * Math.sin(theta);\n var randY = randRadius * Math.cos(theta);\n var randZ = randRadius * Math.sin(phi) * Math.sin(theta);\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);\n };\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n HemisphericParticleEmitter.prototype.clone = function () {\n var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);\n BABYLON.Tools.DeepCopy(this, newOne);\n return newOne;\n };\n /**\n * Called by the {BABYLON.GPUParticleSystem} to setup the update shader\n * @param effect defines the update shader\n */\n HemisphericParticleEmitter.prototype.applyToShader = function (effect) {\n effect.setFloat(\"radius\", this.radius);\n effect.setFloat(\"radiusRange\", this.radiusRange);\n effect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n };\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containng the defines string\n */\n HemisphericParticleEmitter.prototype.getEffectDefines = function () {\n return \"#define HEMISPHERICEMITTER\";\n };\n /**\n * Returns the string \"HemisphericParticleEmitter\"\n * @returns a string containing the class name\n */\n HemisphericParticleEmitter.prototype.getClassName = function () {\n return \"HemisphericParticleEmitter\";\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n HemisphericParticleEmitter.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this.radius;\n serializationObject.radiusRange = this.radiusRange;\n serializationObject.directionRandomizer = this.directionRandomizer;\n return serializationObject;\n };\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n HemisphericParticleEmitter.prototype.parse = function (serializationObject) {\n this.radius = serializationObject.radius;\n this.radiusRange = serializationObject.radiusRange;\n this.directionRandomizer = serializationObject.directionRandomizer;\n };\n return HemisphericParticleEmitter;\n }());\n BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Particle emitter emitting particles from a point.\n * It emits the particles randomly between 2 given directions.\n */\n var PointParticleEmitter = /** @class */ (function () {\n /**\n * Creates a new instance PointParticleEmitter\n */\n function PointParticleEmitter() {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction1 = new BABYLON.Vector3(0, 1.0, 0);\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction2 = new BABYLON.Vector3(0, 1.0, 0);\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n */\n PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {\n var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);\n var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);\n var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n };\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n */\n PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);\n };\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n PointParticleEmitter.prototype.clone = function () {\n var newOne = new PointParticleEmitter();\n BABYLON.Tools.DeepCopy(this, newOne);\n return newOne;\n };\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param effect defines the update shader\n */\n PointParticleEmitter.prototype.applyToShader = function (effect) {\n effect.setVector3(\"direction1\", this.direction1);\n effect.setVector3(\"direction2\", this.direction2);\n };\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containng the defines string\n */\n PointParticleEmitter.prototype.getEffectDefines = function () {\n return \"#define POINTEMITTER\";\n };\n /**\n * Returns the string \"PointParticleEmitter\"\n * @returns a string containing the class name\n */\n PointParticleEmitter.prototype.getClassName = function () {\n return \"PointParticleEmitter\";\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n PointParticleEmitter.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n return serializationObject;\n };\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n PointParticleEmitter.prototype.parse = function (serializationObject) {\n BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);\n BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);\n };\n return PointParticleEmitter;\n }());\n BABYLON.PointParticleEmitter = PointParticleEmitter;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pointParticleEmitter.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n // Adds the parsers to the scene parsers.\n BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {\n var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);\n if (!individualParser) {\n return;\n }\n // Particles Systems\n if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {\n for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {\n var parsedParticleSystem = parsedData.particleSystems[index];\n container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));\n }\n }\n });\n BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {\n if (parsedParticleSystem.activeParticleCount) {\n var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);\n return ps;\n }\n else {\n var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);\n return ps;\n }\n });\n BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {\n if (uniformsNames === void 0) { uniformsNames = []; }\n if (samplers === void 0) { samplers = []; }\n if (defines === void 0) { defines = \"\"; }\n var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();\n var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();\n if (defines.indexOf(\" BILLBOARD\") === -1) {\n defines += \"\\n#define BILLBOARD\\n\";\n }\n if (samplers.indexOf(\"diffuseSampler\") === -1) {\n samplers.push(\"diffuseSampler\");\n }\n return this.createEffect({\n vertex: \"particles\",\n fragmentElement: fragmentName\n }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);\n };\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.particleSystemComponent.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ShaderMaterial = /** @class */ (function (_super) {\n __extends(ShaderMaterial, _super);\n function ShaderMaterial(name, scene, shaderPath, options) {\n var _this = _super.call(this, name, scene) || this;\n _this._textures = {};\n _this._textureArrays = {};\n _this._floats = {};\n _this._ints = {};\n _this._floatsArrays = {};\n _this._colors3 = {};\n _this._colors3Arrays = {};\n _this._colors4 = {};\n _this._vectors2 = {};\n _this._vectors3 = {};\n _this._vectors4 = {};\n _this._matrices = {};\n _this._matrices3x3 = {};\n _this._matrices2x2 = {};\n _this._vectors2Arrays = {};\n _this._vectors3Arrays = {};\n _this._cachedWorldViewMatrix = new BABYLON.Matrix();\n _this._shaderPath = shaderPath;\n options.needAlphaBlending = options.needAlphaBlending || false;\n options.needAlphaTesting = options.needAlphaTesting || false;\n options.attributes = options.attributes || [\"position\", \"normal\", \"uv\"];\n options.uniforms = options.uniforms || [\"worldViewProjection\"];\n options.uniformBuffers = options.uniformBuffers || [];\n options.samplers = options.samplers || [];\n options.defines = options.defines || [];\n _this._options = options;\n return _this;\n }\n ShaderMaterial.prototype.getClassName = function () {\n return \"ShaderMaterial\";\n };\n ShaderMaterial.prototype.needAlphaBlending = function () {\n return this._options.needAlphaBlending;\n };\n ShaderMaterial.prototype.needAlphaTesting = function () {\n return this._options.needAlphaTesting;\n };\n ShaderMaterial.prototype._checkUniform = function (uniformName) {\n if (this._options.uniforms.indexOf(uniformName) === -1) {\n this._options.uniforms.push(uniformName);\n }\n };\n ShaderMaterial.prototype.setTexture = function (name, texture) {\n if (this._options.samplers.indexOf(name) === -1) {\n this._options.samplers.push(name);\n }\n this._textures[name] = texture;\n return this;\n };\n ShaderMaterial.prototype.setTextureArray = function (name, textures) {\n if (this._options.samplers.indexOf(name) === -1) {\n this._options.samplers.push(name);\n }\n this._checkUniform(name);\n this._textureArrays[name] = textures;\n return this;\n };\n ShaderMaterial.prototype.setFloat = function (name, value) {\n this._checkUniform(name);\n this._floats[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setInt = function (name, value) {\n this._checkUniform(name);\n this._ints[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setFloats = function (name, value) {\n this._checkUniform(name);\n this._floatsArrays[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setColor3 = function (name, value) {\n this._checkUniform(name);\n this._colors3[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setColor3Array = function (name, value) {\n this._checkUniform(name);\n this._colors3Arrays[name] = value.reduce(function (arr, color) {\n color.toArray(arr, arr.length);\n return arr;\n }, []);\n return this;\n };\n ShaderMaterial.prototype.setColor4 = function (name, value) {\n this._checkUniform(name);\n this._colors4[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setVector2 = function (name, value) {\n this._checkUniform(name);\n this._vectors2[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setVector3 = function (name, value) {\n this._checkUniform(name);\n this._vectors3[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setVector4 = function (name, value) {\n this._checkUniform(name);\n this._vectors4[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setMatrix = function (name, value) {\n this._checkUniform(name);\n this._matrices[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {\n this._checkUniform(name);\n this._matrices3x3[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {\n this._checkUniform(name);\n this._matrices2x2[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setArray2 = function (name, value) {\n this._checkUniform(name);\n this._vectors2Arrays[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setArray3 = function (name, value) {\n this._checkUniform(name);\n this._vectors3Arrays[name] = value;\n return this;\n };\n ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {\n if (!mesh) {\n return true;\n }\n if (this._effect && (this._effect.defines.indexOf(\"#define INSTANCES\") !== -1) !== useInstances) {\n return false;\n }\n return false;\n };\n ShaderMaterial.prototype.isReady = function (mesh, useInstances) {\n var scene = this.getScene();\n var engine = scene.getEngine();\n if (!this.checkReadyOnEveryCall) {\n if (this._renderId === scene.getRenderId()) {\n if (this._checkCache(scene, mesh, useInstances)) {\n return true;\n }\n }\n }\n // Instances\n var defines = [];\n var attribs = [];\n var fallbacks = new BABYLON.EffectFallbacks();\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n }\n for (var index = 0; index < this._options.defines.length; index++) {\n defines.push(this._options.defines[index]);\n }\n for (var index = 0; index < this._options.attributes.length; index++) {\n attribs.push(this._options.attributes[index]);\n }\n if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {\n attribs.push(BABYLON.VertexBuffer.ColorKind);\n defines.push(\"#define VERTEXCOLOR\");\n }\n // Bones\n if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton.bones.length + 1));\n fallbacks.addCPUSkinningFallback(0, mesh);\n if (this._options.uniforms.indexOf(\"mBones\") === -1) {\n this._options.uniforms.push(\"mBones\");\n }\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Textures\n for (var name in this._textures) {\n if (!this._textures[name].isReady()) {\n return false;\n }\n }\n // Alpha test\n if (mesh && this._shouldTurnAlphaTestOn(mesh)) {\n defines.push(\"#define ALPHATEST\");\n }\n var previousEffect = this._effect;\n var join = defines.join(\"\\n\");\n this._effect = engine.createEffect(this._shaderPath, {\n attributes: attribs,\n uniformsNames: this._options.uniforms,\n uniformBuffersNames: this._options.uniformBuffers,\n samplers: this._options.samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: this.onCompiled,\n onError: this.onError\n }, engine);\n if (!this._effect.isReady()) {\n return false;\n }\n if (previousEffect !== this._effect) {\n scene.resetCachedMaterial();\n }\n this._renderId = scene.getRenderId();\n return true;\n };\n ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {\n var scene = this.getScene();\n if (!this._effect) {\n return;\n }\n if (this._options.uniforms.indexOf(\"world\") !== -1) {\n this._effect.setMatrix(\"world\", world);\n }\n if (this._options.uniforms.indexOf(\"worldView\") !== -1) {\n world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);\n this._effect.setMatrix(\"worldView\", this._cachedWorldViewMatrix);\n }\n if (this._options.uniforms.indexOf(\"worldViewProjection\") !== -1) {\n this._effect.setMatrix(\"worldViewProjection\", world.multiply(scene.getTransformMatrix()));\n }\n };\n ShaderMaterial.prototype.bind = function (world, mesh) {\n // Std values\n this.bindOnlyWorldMatrix(world);\n if (this._effect && this.getScene().getCachedMaterial() !== this) {\n if (this._options.uniforms.indexOf(\"view\") !== -1) {\n this._effect.setMatrix(\"view\", this.getScene().getViewMatrix());\n }\n if (this._options.uniforms.indexOf(\"projection\") !== -1) {\n this._effect.setMatrix(\"projection\", this.getScene().getProjectionMatrix());\n }\n if (this._options.uniforms.indexOf(\"viewProjection\") !== -1) {\n this._effect.setMatrix(\"viewProjection\", this.getScene().getTransformMatrix());\n }\n // Bones\n BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);\n var name;\n // Texture\n for (name in this._textures) {\n this._effect.setTexture(name, this._textures[name]);\n }\n // Texture arrays\n for (name in this._textureArrays) {\n this._effect.setTextureArray(name, this._textureArrays[name]);\n }\n // Int \n for (name in this._ints) {\n this._effect.setInt(name, this._ints[name]);\n }\n // Float \n for (name in this._floats) {\n this._effect.setFloat(name, this._floats[name]);\n }\n // Floats \n for (name in this._floatsArrays) {\n this._effect.setArray(name, this._floatsArrays[name]);\n }\n // Color3 \n for (name in this._colors3) {\n this._effect.setColor3(name, this._colors3[name]);\n }\n for (name in this._colors3Arrays) {\n this._effect.setArray3(name, this._colors3Arrays[name]);\n }\n // Color4 \n for (name in this._colors4) {\n var color = this._colors4[name];\n this._effect.setFloat4(name, color.r, color.g, color.b, color.a);\n }\n // Vector2 \n for (name in this._vectors2) {\n this._effect.setVector2(name, this._vectors2[name]);\n }\n // Vector3 \n for (name in this._vectors3) {\n this._effect.setVector3(name, this._vectors3[name]);\n }\n // Vector4 \n for (name in this._vectors4) {\n this._effect.setVector4(name, this._vectors4[name]);\n }\n // Matrix \n for (name in this._matrices) {\n this._effect.setMatrix(name, this._matrices[name]);\n }\n // Matrix 3x3\n for (name in this._matrices3x3) {\n this._effect.setMatrix3x3(name, this._matrices3x3[name]);\n }\n // Matrix 2x2\n for (name in this._matrices2x2) {\n this._effect.setMatrix2x2(name, this._matrices2x2[name]);\n }\n // Vector2Array \n for (name in this._vectors2Arrays) {\n this._effect.setArray2(name, this._vectors2Arrays[name]);\n }\n // Vector3Array \n for (name in this._vectors3Arrays) {\n this._effect.setArray3(name, this._vectors3Arrays[name]);\n }\n }\n this._afterBind(mesh);\n };\n ShaderMaterial.prototype.getActiveTextures = function () {\n var activeTextures = _super.prototype.getActiveTextures.call(this);\n for (var name in this._textures) {\n activeTextures.push(this._textures[name]);\n }\n for (var name in this._textureArrays) {\n var array = this._textureArrays[name];\n for (var index = 0; index < array.length; index++) {\n activeTextures.push(array[index]);\n }\n }\n return activeTextures;\n };\n ShaderMaterial.prototype.hasTexture = function (texture) {\n if (_super.prototype.hasTexture.call(this, texture)) {\n return true;\n }\n for (var name in this._textures) {\n if (this._textures[name] === texture) {\n return true;\n }\n }\n for (var name in this._textureArrays) {\n var array = this._textureArrays[name];\n for (var index = 0; index < array.length; index++) {\n if (array[index] === texture) {\n return true;\n }\n }\n }\n return false;\n };\n ShaderMaterial.prototype.clone = function (name) {\n var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);\n return newShaderMaterial;\n };\n ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {\n if (forceDisposeTextures) {\n var name;\n for (name in this._textures) {\n this._textures[name].dispose();\n }\n for (name in this._textureArrays) {\n var array = this._textureArrays[name];\n for (var index = 0; index < array.length; index++) {\n array[index].dispose();\n }\n }\n }\n this._textures = {};\n _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);\n };\n ShaderMaterial.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.ShaderMaterial\";\n serializationObject.options = this._options;\n serializationObject.shaderPath = this._shaderPath;\n var name;\n // Texture\n serializationObject.textures = {};\n for (name in this._textures) {\n serializationObject.textures[name] = this._textures[name].serialize();\n }\n // Texture arrays\n serializationObject.textureArrays = {};\n for (name in this._textureArrays) {\n serializationObject.textureArrays[name] = [];\n var array = this._textureArrays[name];\n for (var index = 0; index < array.length; index++) {\n serializationObject.textureArrays[name].push(array[index].serialize());\n }\n }\n // Float \n serializationObject.floats = {};\n for (name in this._floats) {\n serializationObject.floats[name] = this._floats[name];\n }\n // Float s \n serializationObject.FloatArrays = {};\n for (name in this._floatsArrays) {\n serializationObject.FloatArrays[name] = this._floatsArrays[name];\n }\n // Color3 \n serializationObject.colors3 = {};\n for (name in this._colors3) {\n serializationObject.colors3[name] = this._colors3[name].asArray();\n }\n // Color3 array\n serializationObject.colors3Arrays = {};\n for (name in this._colors3Arrays) {\n serializationObject.colors3Arrays[name] = this._colors3Arrays[name];\n }\n // Color4 \n serializationObject.colors4 = {};\n for (name in this._colors4) {\n serializationObject.colors4[name] = this._colors4[name].asArray();\n }\n // Vector2 \n serializationObject.vectors2 = {};\n for (name in this._vectors2) {\n serializationObject.vectors2[name] = this._vectors2[name].asArray();\n }\n // Vector3 \n serializationObject.vectors3 = {};\n for (name in this._vectors3) {\n serializationObject.vectors3[name] = this._vectors3[name].asArray();\n }\n // Vector4 \n serializationObject.vectors4 = {};\n for (name in this._vectors4) {\n serializationObject.vectors4[name] = this._vectors4[name].asArray();\n }\n // Matrix \n serializationObject.matrices = {};\n for (name in this._matrices) {\n serializationObject.matrices[name] = this._matrices[name].asArray();\n }\n // Matrix 3x3\n serializationObject.matrices3x3 = {};\n for (name in this._matrices3x3) {\n serializationObject.matrices3x3[name] = this._matrices3x3[name];\n }\n // Matrix 2x2\n serializationObject.matrices2x2 = {};\n for (name in this._matrices2x2) {\n serializationObject.matrices2x2[name] = this._matrices2x2[name];\n }\n // Vector2Array\n serializationObject.vectors2Arrays = {};\n for (name in this._vectors2Arrays) {\n serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];\n }\n // Vector3Array\n serializationObject.vectors3Arrays = {};\n for (name in this._vectors3Arrays) {\n serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];\n }\n return serializationObject;\n };\n ShaderMaterial.Parse = function (source, scene, rootUrl) {\n var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);\n var name;\n // Texture\n for (name in source.textures) {\n material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));\n }\n // Texture arrays\n for (name in source.textureArrays) {\n var array = source.textureArrays[name];\n var textureArray = new Array();\n for (var index = 0; index < array.length; index++) {\n textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));\n }\n material.setTextureArray(name, textureArray);\n }\n // Float \n for (name in source.floats) {\n material.setFloat(name, source.floats[name]);\n }\n // Float s \n for (name in source.floatsArrays) {\n material.setFloats(name, source.floatsArrays[name]);\n }\n // Color3 \n for (name in source.colors3) {\n material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));\n }\n // Color3 arrays\n for (name in source.colors3Arrays) {\n var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {\n if (i % 3 === 0) {\n arr.push([num]);\n }\n else {\n arr[arr.length - 1].push(num);\n }\n return arr;\n }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });\n material.setColor3Array(name, colors);\n }\n // Color4 \n for (name in source.colors4) {\n material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));\n }\n // Vector2 \n for (name in source.vectors2) {\n material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));\n }\n // Vector3 \n for (name in source.vectors3) {\n material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));\n }\n // Vector4 \n for (name in source.vectors4) {\n material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));\n }\n // Matrix \n for (name in source.matrices) {\n material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));\n }\n // Matrix 3x3\n for (name in source.matrices3x3) {\n material.setMatrix3x3(name, source.matrices3x3[name]);\n }\n // Matrix 2x2\n for (name in source.matrices2x2) {\n material.setMatrix2x2(name, source.matrices2x2[name]);\n }\n // Vector2Array\n for (name in source.vectors2Arrays) {\n material.setArray2(name, source.vectors2Arrays[name]);\n }\n // Vector3Array\n for (name in source.vectors3Arrays) {\n material.setArray3(name, source.vectors3Arrays[name]);\n }\n return material;\n };\n return ShaderMaterial;\n }(BABYLON.Material));\n BABYLON.ShaderMaterial = ShaderMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.shaderMaterial.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GroundMesh = /** @class */ (function (_super) {\n __extends(GroundMesh, _super);\n function GroundMesh(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this.generateOctree = false;\n return _this;\n }\n GroundMesh.prototype.getClassName = function () {\n return \"GroundMesh\";\n };\n Object.defineProperty(GroundMesh.prototype, \"subdivisions\", {\n get: function () {\n return Math.min(this._subdivisionsX, this._subdivisionsY);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GroundMesh.prototype, \"subdivisionsX\", {\n get: function () {\n return this._subdivisionsX;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GroundMesh.prototype, \"subdivisionsY\", {\n get: function () {\n return this._subdivisionsY;\n },\n enumerable: true,\n configurable: true\n });\n GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {\n if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }\n this._subdivisionsX = chunksCount;\n this._subdivisionsY = chunksCount;\n this.subdivide(chunksCount);\n this.createOrUpdateSubmeshesOctree(octreeBlocksSize);\n };\n /**\n * Returns a height (y) value in the Worl system :\n * the ground altitude at the coordinates (x, z) expressed in the World system.\n * Returns the ground y position if (x, z) are outside the ground surface.\n */\n GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {\n var world = this.getWorldMatrix();\n var invMat = BABYLON.Tmp.Matrix[5];\n world.invertToRef(invMat);\n var tmpVect = BABYLON.Tmp.Vector3[8];\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space\n x = tmpVect.x;\n z = tmpVect.z;\n if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {\n return this.position.y;\n }\n if (!this._heightQuads || this._heightQuads.length == 0) {\n this._initHeightQuads();\n this._computeHeightQuads();\n }\n var facet = this._getFacetAt(x, z);\n var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;\n // return y in the World system\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);\n return tmpVect.y;\n };\n /**\n * Returns a normalized vector (Vector3) orthogonal to the ground\n * at the ground coordinates (x, z) expressed in the World system.\n * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.\n */\n GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {\n var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);\n this.getNormalAtCoordinatesToRef(x, z, normal);\n return normal;\n };\n /**\n * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground\n * at the ground coordinates (x, z) expressed in the World system.\n * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.\n * Returns the GroundMesh.\n */\n GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {\n var world = this.getWorldMatrix();\n var tmpMat = BABYLON.Tmp.Matrix[5];\n world.invertToRef(tmpMat);\n var tmpVect = BABYLON.Tmp.Vector3[8];\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space\n x = tmpVect.x;\n z = tmpVect.z;\n if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {\n return this;\n }\n if (!this._heightQuads || this._heightQuads.length == 0) {\n this._initHeightQuads();\n this._computeHeightQuads();\n }\n var facet = this._getFacetAt(x, z);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);\n return this;\n };\n /**\n * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()\n * if the ground has been updated.\n * This can be used in the render loop.\n * Returns the GroundMesh.\n */\n GroundMesh.prototype.updateCoordinateHeights = function () {\n if (!this._heightQuads || this._heightQuads.length == 0) {\n this._initHeightQuads();\n }\n this._computeHeightQuads();\n return this;\n };\n // Returns the element \"facet\" from the heightQuads array relative to (x, z) local coordinates\n GroundMesh.prototype._getFacetAt = function (x, z) {\n // retrieve col and row from x, z coordinates in the ground local system\n var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);\n var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);\n var quad = this._heightQuads[row * this._subdivisionsX + col];\n var facet;\n if (z < quad.slope.x * x + quad.slope.y) {\n facet = quad.facet1;\n }\n else {\n facet = quad.facet2;\n }\n return facet;\n };\n // Creates and populates the heightMap array with \"facet\" elements :\n // a quad is two triangular facets separated by a slope, so a \"facet\" element is 1 slope + 2 facets\n // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h\n // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0\n // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0 \n // Returns the GroundMesh. \n GroundMesh.prototype._initHeightQuads = function () {\n var subdivisionsX = this._subdivisionsX;\n var subdivisionsY = this._subdivisionsY;\n this._heightQuads = new Array();\n for (var row = 0; row < subdivisionsY; row++) {\n for (var col = 0; col < subdivisionsX; col++) {\n var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };\n this._heightQuads[row * subdivisionsX + col] = quad;\n }\n }\n return this;\n };\n // Compute each quad element values and update the the heightMap array :\n // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h\n // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0\n // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0 \n // Returns the GroundMesh. \n GroundMesh.prototype._computeHeightQuads = function () {\n var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!positions) {\n return this;\n }\n var v1 = BABYLON.Tmp.Vector3[3];\n var v2 = BABYLON.Tmp.Vector3[2];\n var v3 = BABYLON.Tmp.Vector3[1];\n var v4 = BABYLON.Tmp.Vector3[0];\n var v1v2 = BABYLON.Tmp.Vector3[4];\n var v1v3 = BABYLON.Tmp.Vector3[5];\n var v1v4 = BABYLON.Tmp.Vector3[6];\n var norm1 = BABYLON.Tmp.Vector3[7];\n var norm2 = BABYLON.Tmp.Vector3[8];\n var i = 0;\n var j = 0;\n var k = 0;\n var cd = 0; // 2D slope coefficient : z = cd * x + h\n var h = 0;\n var d1 = 0; // facet plane equation : ax + by + cz + d = 0\n var d2 = 0;\n var subdivisionsX = this._subdivisionsX;\n var subdivisionsY = this._subdivisionsY;\n for (var row = 0; row < subdivisionsY; row++) {\n for (var col = 0; col < subdivisionsX; col++) {\n i = col * 3;\n j = row * (subdivisionsX + 1) * 3;\n k = (row + 1) * (subdivisionsX + 1) * 3;\n v1.x = positions[j + i];\n v1.y = positions[j + i + 1];\n v1.z = positions[j + i + 2];\n v2.x = positions[j + i + 3];\n v2.y = positions[j + i + 4];\n v2.z = positions[j + i + 5];\n v3.x = positions[k + i];\n v3.y = positions[k + i + 1];\n v3.z = positions[k + i + 2];\n v4.x = positions[k + i + 3];\n v4.y = positions[k + i + 4];\n v4.z = positions[k + i + 5];\n // 2D slope V1V4\n cd = (v4.z - v1.z) / (v4.x - v1.x);\n h = v1.z - cd * v1.x; // v1 belongs to the slope\n // facet equations :\n // we compute each facet normal vector\n // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0\n // we compute the value d by applying the equation to v1 which belongs to the plane\n // then we store the facet equation in a Vector4\n v2.subtractToRef(v1, v1v2);\n v3.subtractToRef(v1, v1v3);\n v4.subtractToRef(v1, v1v4);\n BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class\n BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);\n norm1.normalize();\n norm2.normalize();\n d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);\n d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);\n var quad = this._heightQuads[row * subdivisionsX + col];\n quad.slope.copyFromFloats(cd, h);\n quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);\n quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);\n }\n }\n return this;\n };\n GroundMesh.prototype.serialize = function (serializationObject) {\n _super.prototype.serialize.call(this, serializationObject);\n serializationObject.subdivisionsX = this._subdivisionsX;\n serializationObject.subdivisionsY = this._subdivisionsY;\n serializationObject.minX = this._minX;\n serializationObject.maxX = this._maxX;\n serializationObject.minZ = this._minZ;\n serializationObject.maxZ = this._maxZ;\n serializationObject.width = this._width;\n serializationObject.height = this._height;\n };\n GroundMesh.Parse = function (parsedMesh, scene) {\n var result = new GroundMesh(parsedMesh.name, scene);\n result._subdivisionsX = parsedMesh.subdivisionsX || 1;\n result._subdivisionsY = parsedMesh.subdivisionsY || 1;\n result._minX = parsedMesh.minX;\n result._maxX = parsedMesh.maxX;\n result._minZ = parsedMesh.minZ;\n result._maxZ = parsedMesh.maxZ;\n result._width = parsedMesh.width;\n result._height = parsedMesh.height;\n return result;\n };\n return GroundMesh;\n }(BABYLON.Mesh));\n BABYLON.GroundMesh = GroundMesh;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.groundMesh.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Creates an instance based on a source mesh.\n */\n var InstancedMesh = /** @class */ (function (_super) {\n __extends(InstancedMesh, _super);\n function InstancedMesh(name, source) {\n var _this = _super.call(this, name, source.getScene()) || this;\n source.instances.push(_this);\n _this._sourceMesh = source;\n _this.position.copyFrom(source.position);\n _this.rotation.copyFrom(source.rotation);\n _this.scaling.copyFrom(source.scaling);\n if (source.rotationQuaternion) {\n _this.rotationQuaternion = source.rotationQuaternion.clone();\n }\n _this.infiniteDistance = source.infiniteDistance;\n _this.setPivotMatrix(source.getPivotMatrix());\n _this.refreshBoundingInfo();\n _this._syncSubMeshes();\n return _this;\n }\n /**\n * Returns the string \"InstancedMesh\".\n */\n InstancedMesh.prototype.getClassName = function () {\n return \"InstancedMesh\";\n };\n Object.defineProperty(InstancedMesh.prototype, \"receiveShadows\", {\n // Methods \n get: function () {\n return this._sourceMesh.receiveShadows;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(InstancedMesh.prototype, \"material\", {\n get: function () {\n return this._sourceMesh.material;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(InstancedMesh.prototype, \"visibility\", {\n get: function () {\n return this._sourceMesh.visibility;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(InstancedMesh.prototype, \"skeleton\", {\n get: function () {\n return this._sourceMesh.skeleton;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(InstancedMesh.prototype, \"renderingGroupId\", {\n get: function () {\n return this._sourceMesh.renderingGroupId;\n },\n set: function (value) {\n if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {\n return;\n }\n //no-op with warning\n BABYLON.Tools.Warn(\"Note - setting renderingGroupId of an instanced mesh has no effect on the scene\");\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the total number of vertices (integer).\n */\n InstancedMesh.prototype.getTotalVertices = function () {\n return this._sourceMesh.getTotalVertices();\n };\n Object.defineProperty(InstancedMesh.prototype, \"sourceMesh\", {\n get: function () {\n return this._sourceMesh;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Is this node ready to be used/rendered\n * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)\n * @return {boolean} is it ready\n */\n InstancedMesh.prototype.isReady = function (completeCheck) {\n if (completeCheck === void 0) { completeCheck = false; }\n return this._sourceMesh.isReady(completeCheck, true);\n };\n /**\n * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.\n */\n InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {\n return this._sourceMesh.getVerticesData(kind, copyWhenShared);\n };\n /**\n * Sets the vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.\n * The `data` are either a numeric array either a Float32Array.\n * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.\n * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).\n * Note that a new underlying VertexBuffer object is created each call.\n * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.\n *\n * Possible `kind` values :\n * - BABYLON.VertexBuffer.PositionKind\n * - BABYLON.VertexBuffer.UVKind\n * - BABYLON.VertexBuffer.UV2Kind\n * - BABYLON.VertexBuffer.UV3Kind\n * - BABYLON.VertexBuffer.UV4Kind\n * - BABYLON.VertexBuffer.UV5Kind\n * - BABYLON.VertexBuffer.UV6Kind\n * - BABYLON.VertexBuffer.ColorKind\n * - BABYLON.VertexBuffer.MatricesIndicesKind\n * - BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * - BABYLON.VertexBuffer.MatricesWeightsKind\n * - BABYLON.VertexBuffer.MatricesWeightsExtraKind\n *\n * Returns the Mesh.\n */\n InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {\n if (this.sourceMesh) {\n this.sourceMesh.setVerticesData(kind, data, updatable, stride);\n }\n return this.sourceMesh;\n };\n /**\n * Updates the existing vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, it is simply returned as it is.\n * The `data` are either a numeric array either a Float32Array.\n * No new underlying VertexBuffer object is created.\n * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.\n * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.\n *\n * Possible `kind` values :\n * - BABYLON.VertexBuffer.PositionKind\n * - BABYLON.VertexBuffer.UVKind\n * - BABYLON.VertexBuffer.UV2Kind\n * - BABYLON.VertexBuffer.UV3Kind\n * - BABYLON.VertexBuffer.UV4Kind\n * - BABYLON.VertexBuffer.UV5Kind\n * - BABYLON.VertexBuffer.UV6Kind\n * - BABYLON.VertexBuffer.ColorKind\n * - BABYLON.VertexBuffer.MatricesIndicesKind\n * - BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * - BABYLON.VertexBuffer.MatricesWeightsKind\n * - BABYLON.VertexBuffer.MatricesWeightsExtraKind\n *\n * Returns the Mesh.\n */\n InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {\n if (this.sourceMesh) {\n this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);\n }\n return this.sourceMesh;\n };\n /**\n * Sets the mesh indices.\n * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).\n * If the mesh has no geometry, a new Geometry object is created and set to the mesh.\n * This method creates a new index buffer each call.\n * Returns the Mesh.\n */\n InstancedMesh.prototype.setIndices = function (indices, totalVertices) {\n if (totalVertices === void 0) { totalVertices = null; }\n if (this.sourceMesh) {\n this.sourceMesh.setIndices(indices, totalVertices);\n }\n return this.sourceMesh;\n };\n /**\n * Boolean : True if the mesh owns the requested kind of data.\n */\n InstancedMesh.prototype.isVerticesDataPresent = function (kind) {\n return this._sourceMesh.isVerticesDataPresent(kind);\n };\n /**\n * Returns an array of indices (IndicesArray).\n */\n InstancedMesh.prototype.getIndices = function () {\n return this._sourceMesh.getIndices();\n };\n Object.defineProperty(InstancedMesh.prototype, \"_positions\", {\n get: function () {\n return this._sourceMesh._positions;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Sets a new updated BoundingInfo to the mesh.\n * Returns the mesh.\n */\n InstancedMesh.prototype.refreshBoundingInfo = function () {\n var meshBB = this._sourceMesh.getBoundingInfo();\n this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());\n this._updateBoundingInfo();\n return this;\n };\n InstancedMesh.prototype._preActivate = function () {\n if (this._currentLOD) {\n this._currentLOD._preActivate();\n }\n return this;\n };\n InstancedMesh.prototype._activate = function (renderId) {\n if (this._currentLOD) {\n this._currentLOD._registerInstanceForRenderId(this, renderId);\n }\n return this;\n };\n /**\n * Returns the current associated LOD AbstractMesh.\n */\n InstancedMesh.prototype.getLOD = function (camera) {\n if (!camera) {\n return this;\n }\n var boundingInfo = this.getBoundingInfo();\n this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);\n if (this._currentLOD === this.sourceMesh) {\n return this;\n }\n return this._currentLOD;\n };\n InstancedMesh.prototype._syncSubMeshes = function () {\n this.releaseSubMeshes();\n if (this._sourceMesh.subMeshes) {\n for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {\n this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);\n }\n }\n return this;\n };\n InstancedMesh.prototype._generatePointsArray = function () {\n return this._sourceMesh._generatePointsArray();\n };\n /**\n * Creates a new InstancedMesh from the current mesh.\n * - name (string) : the cloned mesh name\n * - newParent (optional Node) : the optional Node to parent the clone to.\n * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.\n *\n * Returns the clone.\n */\n InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {\n var result = this._sourceMesh.createInstance(name);\n // Deep copy\n BABYLON.Tools.DeepCopy(this, result, [\"name\", \"subMeshes\", \"uniqueId\"], []);\n // Bounding info\n this.refreshBoundingInfo();\n // Parent\n if (newParent) {\n result.parent = newParent;\n }\n if (!doNotCloneChildren) {\n // Children\n for (var index = 0; index < this.getScene().meshes.length; index++) {\n var mesh = this.getScene().meshes[index];\n if (mesh.parent === this) {\n mesh.clone(mesh.name, result);\n }\n }\n }\n result.computeWorldMatrix(true);\n return result;\n };\n /**\n * Disposes the InstancedMesh.\n * Returns nothing.\n */\n InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n // Remove from mesh\n var index = this._sourceMesh.instances.indexOf(this);\n this._sourceMesh.instances.splice(index, 1);\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n return InstancedMesh;\n }(BABYLON.AbstractMesh));\n BABYLON.InstancedMesh = InstancedMesh;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.instancedMesh.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var LinesMesh = /** @class */ (function (_super) {\n __extends(LinesMesh, _super);\n function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {\n if (scene === void 0) { scene = null; }\n if (parent === void 0) { parent = null; }\n var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;\n _this.useVertexColor = useVertexColor;\n _this.useVertexAlpha = useVertexAlpha;\n _this.color = new BABYLON.Color3(1, 1, 1);\n _this.alpha = 1;\n if (source) {\n _this.color = source.color.clone();\n _this.alpha = source.alpha;\n _this.useVertexColor = source.useVertexColor;\n _this.useVertexAlpha = source.useVertexAlpha;\n }\n _this._intersectionThreshold = 0.1;\n var defines = [];\n var options = {\n attributes: [BABYLON.VertexBuffer.PositionKind],\n uniforms: [\"world\", \"viewProjection\"],\n needAlphaBlending: true,\n defines: defines\n };\n if (useVertexAlpha === false) {\n options.needAlphaBlending = false;\n }\n if (!useVertexColor) {\n options.uniforms.push(\"color\");\n }\n else {\n options.defines.push(\"#define VERTEXCOLOR\");\n options.attributes.push(BABYLON.VertexBuffer.ColorKind);\n }\n _this._colorShader = new BABYLON.ShaderMaterial(\"colorShader\", _this.getScene(), \"color\", options);\n return _this;\n }\n Object.defineProperty(LinesMesh.prototype, \"intersectionThreshold\", {\n /**\n * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.\n * This margin is expressed in world space coordinates, so its value may vary.\n * Default value is 0.1\n * @returns the intersection Threshold value.\n */\n get: function () {\n return this._intersectionThreshold;\n },\n /**\n * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.\n * This margin is expressed in world space coordinates, so its value may vary.\n * @param value the new threshold to apply\n */\n set: function (value) {\n if (this._intersectionThreshold === value) {\n return;\n }\n this._intersectionThreshold = value;\n if (this.geometry) {\n this.geometry.boundingBias = new BABYLON.Vector2(0, value);\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"LineMesh\"\n */\n LinesMesh.prototype.getClassName = function () {\n return \"LinesMesh\";\n };\n Object.defineProperty(LinesMesh.prototype, \"material\", {\n /**\n * @hidden\n */\n get: function () {\n return this._colorShader;\n },\n /**\n * @hidden\n */\n set: function (value) {\n // Do nothing\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LinesMesh.prototype, \"checkCollisions\", {\n /**\n * @hidden\n */\n get: function () {\n return false;\n },\n enumerable: true,\n configurable: true\n });\n LinesMesh.prototype.createInstance = function (name) {\n throw new Error(\"LinesMeshes do not support createInstance.\");\n };\n LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {\n if (!this._geometry) {\n return this;\n }\n // VBOs\n this._geometry._bind(this._colorShader.getEffect());\n // Color\n if (!this.useVertexColor) {\n this._colorShader.setColor4(\"color\", this.color.toColor4(this.alpha));\n }\n return this;\n };\n LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {\n if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {\n return this;\n }\n var engine = this.getScene().getEngine();\n // Draw order\n engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);\n return this;\n };\n LinesMesh.prototype.dispose = function (doNotRecurse) {\n this._colorShader.dispose();\n _super.prototype.dispose.call(this, doNotRecurse);\n };\n /**\n * Returns a new LineMesh object cloned from the current one.\n */\n LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {\n return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);\n };\n return LinesMesh;\n }(BABYLON.Mesh));\n BABYLON.LinesMesh = LinesMesh;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.linesMesh.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class implement a typical dictionary using a string as key and the generic type T as value.\n * The underlying implementation relies on an associative array to ensure the best performances.\n * The value can be anything including 'null' but except 'undefined'\n */\n var StringDictionary = /** @class */ (function () {\n function StringDictionary() {\n this._count = 0;\n this._data = {};\n }\n /**\n * This will clear this dictionary and copy the content from the 'source' one.\n * If the T value is a custom object, it won't be copied/cloned, the same object will be used\n * @param source the dictionary to take the content from and copy to this dictionary\n */\n StringDictionary.prototype.copyFrom = function (source) {\n var _this = this;\n this.clear();\n source.forEach(function (t, v) { return _this.add(t, v); });\n };\n /**\n * Get a value based from its key\n * @param key the given key to get the matching value from\n * @return the value if found, otherwise undefined is returned\n */\n StringDictionary.prototype.get = function (key) {\n var val = this._data[key];\n if (val !== undefined) {\n return val;\n }\n return undefined;\n };\n /**\n * Get a value from its key or add it if it doesn't exist.\n * This method will ensure you that a given key/data will be present in the dictionary.\n * @param key the given key to get the matching value from\n * @param factory the factory that will create the value if the key is not present in the dictionary.\n * The factory will only be invoked if there's no data for the given key.\n * @return the value corresponding to the key.\n */\n StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {\n var val = this.get(key);\n if (val !== undefined) {\n return val;\n }\n val = factory(key);\n if (val) {\n this.add(key, val);\n }\n return val;\n };\n /**\n * Get a value from its key if present in the dictionary otherwise add it\n * @param key the key to get the value from\n * @param val if there's no such key/value pair in the dictionary add it with this value\n * @return the value corresponding to the key\n */\n StringDictionary.prototype.getOrAdd = function (key, val) {\n var curVal = this.get(key);\n if (curVal !== undefined) {\n return curVal;\n }\n this.add(key, val);\n return val;\n };\n /**\n * Check if there's a given key in the dictionary\n * @param key the key to check for\n * @return true if the key is present, false otherwise\n */\n StringDictionary.prototype.contains = function (key) {\n return this._data[key] !== undefined;\n };\n /**\n * Add a new key and its corresponding value\n * @param key the key to add\n * @param value the value corresponding to the key\n * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary\n */\n StringDictionary.prototype.add = function (key, value) {\n if (this._data[key] !== undefined) {\n return false;\n }\n this._data[key] = value;\n ++this._count;\n return true;\n };\n StringDictionary.prototype.set = function (key, value) {\n if (this._data[key] === undefined) {\n return false;\n }\n this._data[key] = value;\n return true;\n };\n /**\n * Get the element of the given key and remove it from the dictionary\n * @param key\n */\n StringDictionary.prototype.getAndRemove = function (key) {\n var val = this.get(key);\n if (val !== undefined) {\n delete this._data[key];\n --this._count;\n return val;\n }\n return null;\n };\n /**\n * Remove a key/value from the dictionary.\n * @param key the key to remove\n * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary\n */\n StringDictionary.prototype.remove = function (key) {\n if (this.contains(key)) {\n delete this._data[key];\n --this._count;\n return true;\n }\n return false;\n };\n /**\n * Clear the whole content of the dictionary\n */\n StringDictionary.prototype.clear = function () {\n this._data = {};\n this._count = 0;\n };\n Object.defineProperty(StringDictionary.prototype, \"count\", {\n get: function () {\n return this._count;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Execute a callback on each key/val of the dictionary.\n * Note that you can remove any element in this dictionary in the callback implementation\n * @param callback the callback to execute on a given key/value pair\n */\n StringDictionary.prototype.forEach = function (callback) {\n for (var cur in this._data) {\n var val = this._data[cur];\n callback(cur, val);\n }\n };\n /**\n * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.\n * If the callback returns null or undefined the method will iterate to the next key/value pair\n * Note that you can remove any element in this dictionary in the callback implementation\n * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned\n */\n StringDictionary.prototype.first = function (callback) {\n for (var cur in this._data) {\n var val = this._data[cur];\n var res = callback(cur, val);\n if (res) {\n return res;\n }\n }\n return null;\n };\n return StringDictionary;\n }());\n BABYLON.StringDictionary = StringDictionary;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stringDictionary.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Debug;\n (function (Debug) {\n /**\n * Class used to render a debug view of a given skeleton\n * @see http://www.babylonjs-playground.com/#1BZJVJ#8\n */\n var SkeletonViewer = /** @class */ (function () {\n /**\n * Creates a new SkeletonViewer\n * @param skeleton defines the skeleton to render\n * @param mesh defines the mesh attached to the skeleton\n * @param scene defines the hosting scene\n * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)\n * @param renderingGroupId defines the rendering group id to use with the viewer\n */\n function SkeletonViewer(\n /** defines the skeleton to render */\n skeleton, \n /** defines the mesh attached to the skeleton */\n mesh, scene, \n /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */\n autoUpdateBonesMatrices, \n /** defines the rendering group id to use with the viewer */\n renderingGroupId) {\n if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }\n if (renderingGroupId === void 0) { renderingGroupId = 1; }\n this.skeleton = skeleton;\n this.mesh = mesh;\n this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;\n this.renderingGroupId = renderingGroupId;\n /** Gets or sets the color used to render the skeleton */\n this.color = BABYLON.Color3.White();\n this._debugLines = new Array();\n this._isEnabled = false;\n this._scene = scene;\n this.update();\n this._renderFunction = this.update.bind(this);\n }\n Object.defineProperty(SkeletonViewer.prototype, \"isEnabled\", {\n get: function () {\n return this._isEnabled;\n },\n /** Gets or sets a boolean indicating if the viewer is enabled */\n set: function (value) {\n if (this._isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n if (value) {\n this._scene.registerBeforeRender(this._renderFunction);\n }\n else {\n this._scene.unregisterBeforeRender(this._renderFunction);\n }\n },\n enumerable: true,\n configurable: true\n });\n SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {\n if (x === void 0) { x = 0; }\n if (y === void 0) { y = 0; }\n if (z === void 0) { z = 0; }\n var tmat = BABYLON.Tmp.Matrix[0];\n var parentBone = bone.getParent();\n tmat.copyFrom(bone.getLocalMatrix());\n if (x !== 0 || y !== 0 || z !== 0) {\n var tmat2 = BABYLON.Tmp.Matrix[1];\n BABYLON.Matrix.IdentityToRef(tmat2);\n tmat2.m[12] = x;\n tmat2.m[13] = y;\n tmat2.m[14] = z;\n tmat2.multiplyToRef(tmat, tmat);\n }\n if (parentBone) {\n tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);\n }\n tmat.multiplyToRef(meshMat, tmat);\n position.x = tmat.m[12];\n position.y = tmat.m[13];\n position.z = tmat.m[14];\n };\n SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {\n var len = bones.length;\n var meshPos = this.mesh.position;\n for (var i = 0; i < len; i++) {\n var bone = bones[i];\n var points = this._debugLines[i];\n if (!points) {\n points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n this._debugLines[i] = points;\n }\n this._getBonePosition(points[0], bone, meshMat);\n this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);\n points[0].subtractInPlace(meshPos);\n points[1].subtractInPlace(meshPos);\n }\n };\n SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {\n var len = bones.length;\n var boneNum = 0;\n var meshPos = this.mesh.position;\n for (var i = len - 1; i >= 0; i--) {\n var childBone = bones[i];\n var parentBone = childBone.getParent();\n if (!parentBone) {\n continue;\n }\n var points = this._debugLines[boneNum];\n if (!points) {\n points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n this._debugLines[boneNum] = points;\n }\n childBone.getAbsolutePositionToRef(this.mesh, points[0]);\n parentBone.getAbsolutePositionToRef(this.mesh, points[1]);\n points[0].subtractInPlace(meshPos);\n points[1].subtractInPlace(meshPos);\n boneNum++;\n }\n };\n /** Update the viewer to sync with current skeleton state */\n SkeletonViewer.prototype.update = function () {\n if (this.autoUpdateBonesMatrices) {\n this.skeleton.computeAbsoluteTransforms();\n }\n if (this.skeleton.bones[0].length === undefined) {\n this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());\n }\n else {\n this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());\n }\n if (!this._debugMesh) {\n this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(\"\", { lines: this._debugLines, updatable: true, instance: null }, this._scene);\n this._debugMesh.renderingGroupId = this.renderingGroupId;\n }\n else {\n BABYLON.MeshBuilder.CreateLineSystem(\"\", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);\n }\n this._debugMesh.position.copyFrom(this.mesh.position);\n this._debugMesh.color = this.color;\n };\n /** Release associated resources */\n SkeletonViewer.prototype.dispose = function () {\n if (this._debugMesh) {\n this.isEnabled = false;\n this._debugMesh.dispose();\n this._debugMesh = null;\n }\n };\n return SkeletonViewer;\n }());\n Debug.SkeletonViewer = SkeletonViewer;\n })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.skeletonViewer.js.map\n\n/**\n * Module Debug contains the (visual) components to debug a scene correctly\n */\nvar BABYLON;\n(function (BABYLON) {\n var Debug;\n (function (Debug) {\n /**\n * The Axes viewer will show 3 axes in a specific point in space\n */\n var AxesViewer = /** @class */ (function () {\n /**\n * Creates a new AxesViewer\n * @param scene defines the hosting scene\n * @param scaleLines defines a number used to scale line length (1 by default)\n */\n function AxesViewer(scene, scaleLines) {\n if (scaleLines === void 0) { scaleLines = 1; }\n this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n /**\n * Gets or sets a number used to scale line length\n */\n this.scaleLines = 1;\n this.scaleLines = scaleLines;\n this._xmesh = BABYLON.Mesh.CreateLines(\"xline\", this._xline, scene, true);\n this._ymesh = BABYLON.Mesh.CreateLines(\"yline\", this._yline, scene, true);\n this._zmesh = BABYLON.Mesh.CreateLines(\"zline\", this._zline, scene, true);\n this._xmesh.renderingGroupId = 2;\n this._ymesh.renderingGroupId = 2;\n this._zmesh.renderingGroupId = 2;\n this._xmesh.material.checkReadyOnlyOnce = true;\n this._xmesh.color = new BABYLON.Color3(1, 0, 0);\n this._ymesh.material.checkReadyOnlyOnce = true;\n this._ymesh.color = new BABYLON.Color3(0, 1, 0);\n this._zmesh.material.checkReadyOnlyOnce = true;\n this._zmesh.color = new BABYLON.Color3(0, 0, 1);\n this.scene = scene;\n }\n /**\n * Force the viewer to update\n * @param position defines the position of the viewer\n * @param xaxis defines the x axis of the viewer\n * @param yaxis defines the y axis of the viewer\n * @param zaxis defines the z axis of the viewer\n */\n AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {\n var scaleLines = this.scaleLines;\n if (this._xmesh) {\n this._xmesh.position.copyFrom(position);\n }\n if (this._ymesh) {\n this._ymesh.position.copyFrom(position);\n }\n if (this._zmesh) {\n this._zmesh.position.copyFrom(position);\n }\n var point2 = this._xline[1];\n point2.x = xaxis.x * scaleLines;\n point2.y = xaxis.y * scaleLines;\n point2.z = xaxis.z * scaleLines;\n BABYLON.Mesh.CreateLines(\"\", this._xline, null, false, this._xmesh);\n point2 = this._yline[1];\n point2.x = yaxis.x * scaleLines;\n point2.y = yaxis.y * scaleLines;\n point2.z = yaxis.z * scaleLines;\n BABYLON.Mesh.CreateLines(\"\", this._yline, null, false, this._ymesh);\n point2 = this._zline[1];\n point2.x = zaxis.x * scaleLines;\n point2.y = zaxis.y * scaleLines;\n point2.z = zaxis.z * scaleLines;\n BABYLON.Mesh.CreateLines(\"\", this._zline, null, false, this._zmesh);\n };\n /** Releases resources */\n AxesViewer.prototype.dispose = function () {\n if (this._xmesh) {\n this._xmesh.dispose();\n }\n if (this._ymesh) {\n this._ymesh.dispose();\n }\n if (this._zmesh) {\n this._zmesh.dispose();\n }\n this._xmesh = null;\n this._ymesh = null;\n this._zmesh = null;\n this.scene = null;\n };\n return AxesViewer;\n }());\n Debug.AxesViewer = AxesViewer;\n })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.axesViewer.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var Debug;\n (function (Debug) {\n /**\n * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh\n * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8\n */\n var BoneAxesViewer = /** @class */ (function (_super) {\n __extends(BoneAxesViewer, _super);\n /**\n * Creates a new BoneAxesViewer\n * @param scene defines the hosting scene\n * @param bone defines the target bone\n * @param mesh defines the target mesh\n * @param scaleLines defines a scaling factor for line length (1 by default)\n */\n function BoneAxesViewer(scene, bone, mesh, scaleLines) {\n if (scaleLines === void 0) { scaleLines = 1; }\n var _this = _super.call(this, scene, scaleLines) || this;\n /** Gets current position */\n _this.pos = BABYLON.Vector3.Zero();\n /** Gets direction of X axis */\n _this.xaxis = BABYLON.Vector3.Zero();\n /** Gets direction of Y axis */\n _this.yaxis = BABYLON.Vector3.Zero();\n /** Gets direction of Z axis */\n _this.zaxis = BABYLON.Vector3.Zero();\n _this.mesh = mesh;\n _this.bone = bone;\n return _this;\n }\n /**\n * Force the viewer to update\n */\n BoneAxesViewer.prototype.update = function () {\n if (!this.mesh || !this.bone) {\n return;\n }\n var bone = this.bone;\n bone.getAbsolutePositionToRef(this.mesh, this.pos);\n bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);\n bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);\n bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);\n _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);\n };\n /** Releases resources */\n BoneAxesViewer.prototype.dispose = function () {\n if (this.mesh) {\n this.mesh = null;\n this.bone = null;\n _super.prototype.dispose.call(this);\n }\n };\n return BoneAxesViewer;\n }(Debug.AxesViewer));\n Debug.BoneAxesViewer = BoneAxesViewer;\n })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boneAxesViewer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var RayHelper = /** @class */ (function () {\n function RayHelper(ray) {\n this.ray = ray;\n }\n RayHelper.CreateAndShow = function (ray, scene, color) {\n var helper = new RayHelper(ray);\n helper.show(scene, color);\n return helper;\n };\n RayHelper.prototype.show = function (scene, color) {\n if (!this._renderFunction && this.ray) {\n var ray = this.ray;\n this._renderFunction = this._render.bind(this);\n this._scene = scene;\n this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];\n this._renderLine = BABYLON.Mesh.CreateLines(\"ray\", this._renderPoints, scene, true);\n if (this._renderFunction) {\n this._scene.registerBeforeRender(this._renderFunction);\n }\n }\n if (color && this._renderLine) {\n this._renderLine.color.copyFrom(color);\n }\n };\n RayHelper.prototype.hide = function () {\n if (this._renderFunction && this._scene) {\n this._scene.unregisterBeforeRender(this._renderFunction);\n this._scene = null;\n this._renderFunction = null;\n if (this._renderLine) {\n this._renderLine.dispose();\n this._renderLine = null;\n }\n this._renderPoints = [];\n }\n };\n RayHelper.prototype._render = function () {\n var ray = this.ray;\n if (!ray) {\n return;\n }\n var point = this._renderPoints[1];\n var len = Math.min(ray.length, 1000000);\n point.copyFrom(ray.direction);\n point.scaleInPlace(len);\n point.addInPlace(ray.origin);\n BABYLON.Mesh.CreateLines(\"ray\", this._renderPoints, this._scene, true, this._renderLine);\n };\n RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {\n this._attachedToMesh = mesh;\n var ray = this.ray;\n if (!ray) {\n return;\n }\n if (!ray.direction) {\n ray.direction = BABYLON.Vector3.Zero();\n }\n if (!ray.origin) {\n ray.origin = BABYLON.Vector3.Zero();\n }\n if (length) {\n ray.length = length;\n }\n if (!meshSpaceOrigin) {\n meshSpaceOrigin = BABYLON.Vector3.Zero();\n }\n if (!meshSpaceDirection) {\n // -1 so that this will work with Mesh.lookAt\n meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);\n }\n if (!this._meshSpaceDirection) {\n this._meshSpaceDirection = meshSpaceDirection.clone();\n this._meshSpaceOrigin = meshSpaceOrigin.clone();\n }\n else {\n this._meshSpaceDirection.copyFrom(meshSpaceDirection);\n this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);\n }\n if (!this._updateToMeshFunction) {\n this._updateToMeshFunction = this._updateToMesh.bind(this);\n this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);\n }\n this._updateToMesh();\n };\n RayHelper.prototype.detachFromMesh = function () {\n if (this._attachedToMesh) {\n if (this._updateToMeshFunction) {\n this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);\n }\n this._attachedToMesh = null;\n this._updateToMeshFunction = null;\n }\n };\n RayHelper.prototype._updateToMesh = function () {\n var ray = this.ray;\n if (!this._attachedToMesh || !ray) {\n return;\n }\n if (this._attachedToMesh._isDisposed) {\n this.detachFromMesh();\n return;\n }\n this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);\n BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);\n };\n RayHelper.prototype.dispose = function () {\n this.hide();\n this.detachFromMesh();\n this.ray = null;\n };\n return RayHelper;\n }());\n BABYLON.RayHelper = RayHelper;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.rayHelper.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n // load the inspector using require, if not present in the global namespace.\n var DebugLayer = /** @class */ (function () {\n function DebugLayer(scene) {\n this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;\n this.onPropertyChangedObservable = new BABYLON.Observable();\n this._scene = scene;\n }\n /** Creates the inspector window. */\n DebugLayer.prototype._createInspector = function (config) {\n if (config === void 0) { config = {}; }\n var popup = config.popup || false;\n var initialTab = config.initialTab || 0;\n var parentElement = config.parentElement || null;\n if (!this._inspector) {\n this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;\n this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);\n } // else nothing to do as instance is already created\n };\n DebugLayer.prototype.isVisible = function () {\n if (!this._inspector) {\n return false;\n }\n return true;\n };\n DebugLayer.prototype.hide = function () {\n if (this._inspector) {\n try {\n this._inspector.dispose();\n }\n catch (e) {\n // If the inspector has been removed directly from the inspector tool\n }\n this.onPropertyChangedObservable.clear();\n this._inspector = null;\n }\n };\n /**\n *\n * Launch the debugLayer.\n *\n * initialTab:\n * | Value | Tab Name |\n * | --- | --- |\n * | 0 | Scene |\n * | 1 | Console |\n * | 2 | Stats |\n * | 3 | Textures |\n * | 4 | Mesh |\n * | 5 | Light |\n * | 6 | Material |\n * | 7 | GLTF |\n * | 8 | GUI |\n * | 9 | Physics |\n * | 10 | Camera |\n * | 11 | Audio |\n *\n */\n DebugLayer.prototype.show = function (config) {\n if (config === void 0) { config = {}; }\n if (typeof this.BJSINSPECTOR == 'undefined') {\n // Load inspector and add it to the DOM\n BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));\n }\n else {\n // Otherwise creates the inspector\n this._createInspector(config);\n }\n };\n /**\n * Gets the active tab\n * @return the index of the active tab or -1 if the inspector is hidden\n */\n DebugLayer.prototype.getActiveTab = function () {\n return this._inspector ? this._inspector.getActiveTabIndex() : -1;\n };\n DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';\n return DebugLayer;\n }());\n BABYLON.DebugLayer = DebugLayer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.debugLayer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Debug;\n (function (Debug) {\n /**\n * Used to show the physics impostor around the specific mesh\n */\n var PhysicsViewer = /** @class */ (function () {\n /**\n * Creates a new PhysicsViewer\n * @param scene defines the hosting scene\n */\n function PhysicsViewer(scene) {\n /** @hidden */\n this._impostors = [];\n /** @hidden */\n this._meshes = [];\n /** @hidden */\n this._numMeshes = 0;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n var physicEngine = this._scene.getPhysicsEngine();\n if (physicEngine) {\n this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();\n }\n }\n /** @hidden */\n PhysicsViewer.prototype._updateDebugMeshes = function () {\n var plugin = this._physicsEnginePlugin;\n for (var i = 0; i < this._numMeshes; i++) {\n var impostor = this._impostors[i];\n if (!impostor) {\n continue;\n }\n if (impostor.isDisposed) {\n this.hideImpostor(this._impostors[i--]);\n }\n else {\n var mesh = this._meshes[i];\n if (mesh && plugin) {\n plugin.syncMeshWithImpostor(mesh, impostor);\n }\n }\n }\n };\n /**\n * Renders a specified physic impostor\n * @param impostor defines the impostor to render\n */\n PhysicsViewer.prototype.showImpostor = function (impostor) {\n if (!this._scene) {\n return;\n }\n for (var i = 0; i < this._numMeshes; i++) {\n if (this._impostors[i] == impostor) {\n return;\n }\n }\n var debugMesh = this._getDebugMesh(impostor, this._scene);\n if (debugMesh) {\n this._impostors[this._numMeshes] = impostor;\n this._meshes[this._numMeshes] = debugMesh;\n if (this._numMeshes === 0) {\n this._renderFunction = this._updateDebugMeshes.bind(this);\n this._scene.registerBeforeRender(this._renderFunction);\n }\n this._numMeshes++;\n }\n };\n /**\n * Hides a specified physic impostor\n * @param impostor defines the impostor to hide\n */\n PhysicsViewer.prototype.hideImpostor = function (impostor) {\n if (!impostor || !this._scene) {\n return;\n }\n var removed = false;\n for (var i = 0; i < this._numMeshes; i++) {\n if (this._impostors[i] == impostor) {\n var mesh = this._meshes[i];\n if (!mesh) {\n continue;\n }\n this._scene.removeMesh(mesh);\n mesh.dispose();\n this._numMeshes--;\n if (this._numMeshes > 0) {\n this._meshes[i] = this._meshes[this._numMeshes];\n this._impostors[i] = this._impostors[this._numMeshes];\n this._meshes[this._numMeshes] = null;\n this._impostors[this._numMeshes] = null;\n }\n else {\n this._meshes[0] = null;\n this._impostors[0] = null;\n }\n removed = true;\n break;\n }\n }\n if (removed && this._numMeshes === 0) {\n this._scene.unregisterBeforeRender(this._renderFunction);\n }\n };\n PhysicsViewer.prototype._getDebugMaterial = function (scene) {\n if (!this._debugMaterial) {\n this._debugMaterial = new BABYLON.StandardMaterial('', scene);\n this._debugMaterial.wireframe = true;\n }\n return this._debugMaterial;\n };\n PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {\n if (!this._debugBoxMesh) {\n this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);\n this._debugBoxMesh.renderingGroupId = 1;\n this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();\n this._debugBoxMesh.material = this._getDebugMaterial(scene);\n scene.removeMesh(this._debugBoxMesh);\n }\n return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');\n };\n PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {\n if (!this._debugSphereMesh) {\n this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);\n this._debugSphereMesh.renderingGroupId = 1;\n this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();\n this._debugSphereMesh.material = this._getDebugMaterial(scene);\n scene.removeMesh(this._debugSphereMesh);\n }\n return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');\n };\n PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {\n var mesh = null;\n if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {\n mesh = this._getDebugBoxMesh(scene);\n impostor.getBoxSizeToRef(mesh.scaling);\n }\n else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {\n mesh = this._getDebugSphereMesh(scene);\n var radius = impostor.getRadius();\n mesh.scaling.x = radius * 2;\n mesh.scaling.y = radius * 2;\n mesh.scaling.z = radius * 2;\n }\n return mesh;\n };\n /** Releases all resources */\n PhysicsViewer.prototype.dispose = function () {\n for (var i = 0; i < this._numMeshes; i++) {\n this.hideImpostor(this._impostors[i]);\n }\n if (this._debugBoxMesh) {\n this._debugBoxMesh.dispose();\n }\n if (this._debugSphereMesh) {\n this._debugSphereMesh.dispose();\n }\n if (this._debugMaterial) {\n this._debugMaterial.dispose();\n }\n this._impostors.length = 0;\n this._scene = null;\n this._physicsEnginePlugin = null;\n };\n return PhysicsViewer;\n }());\n Debug.PhysicsViewer = PhysicsViewer;\n })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.physicsViewer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n Object.defineProperty(BABYLON.Scene.prototype, \"forceShowBoundingBoxes\", {\n get: function () {\n return this._forceShowBoundingBoxes || false;\n },\n set: function (value) {\n this._forceShowBoundingBoxes = value;\n // Lazyly creates a BB renderer if needed.\n if (value) {\n this.getBoundingBoxRenderer();\n }\n },\n enumerable: true,\n configurable: true\n });\n BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {\n if (!this._boundingBoxRenderer) {\n this._boundingBoxRenderer = new BoundingBoxRenderer(this);\n }\n return this._boundingBoxRenderer;\n };\n Object.defineProperty(BABYLON.AbstractMesh.prototype, \"showBoundingBox\", {\n get: function () {\n return this._showBoundingBox || false;\n },\n set: function (value) {\n this._showBoundingBox = value;\n // Lazyly creates a BB renderer if needed.\n if (value) {\n this.getScene().getBoundingBoxRenderer();\n }\n },\n enumerable: true,\n configurable: true\n });\n var BoundingBoxRenderer = /** @class */ (function () {\n function BoundingBoxRenderer(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;\n this.frontColor = new BABYLON.Color3(1, 1, 1);\n this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);\n this.showBackLines = true;\n this.renderList = new BABYLON.SmartArray(32);\n this._vertexBuffers = {};\n this.scene = scene;\n scene._addComponent(this);\n }\n /**\n * Registers the component in a given scene\n */\n BoundingBoxRenderer.prototype.register = function () {\n this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);\n this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);\n this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);\n this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);\n };\n BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {\n if (mesh.showSubMeshesBoundingBox) {\n var boundingInfo = subMesh.getBoundingInfo();\n if (boundingInfo !== null && boundingInfo !== undefined) {\n this.renderList.push(boundingInfo.boundingBox);\n }\n }\n };\n BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {\n if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {\n var boundingInfo = sourceMesh.getBoundingInfo();\n this.renderList.push(boundingInfo.boundingBox);\n }\n };\n BoundingBoxRenderer.prototype._prepareRessources = function () {\n if (this._colorShader) {\n return;\n }\n this._colorShader = new BABYLON.ShaderMaterial(\"colorShader\", this.scene, \"color\", {\n attributes: [BABYLON.VertexBuffer.PositionKind],\n uniforms: [\"world\", \"viewProjection\", \"color\"]\n });\n var engine = this.scene.getEngine();\n var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);\n this._createIndexBuffer();\n };\n BoundingBoxRenderer.prototype._createIndexBuffer = function () {\n var engine = this.scene.getEngine();\n this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);\n };\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n BoundingBoxRenderer.prototype.rebuild = function () {\n var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._createIndexBuffer();\n };\n BoundingBoxRenderer.prototype.reset = function () {\n this.renderList.reset();\n };\n BoundingBoxRenderer.prototype.render = function () {\n if (this.renderList.length === 0) {\n return;\n }\n this._prepareRessources();\n if (!this._colorShader.isReady()) {\n return;\n }\n var engine = this.scene.getEngine();\n engine.setDepthWrite(false);\n this._colorShader._preBind();\n for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {\n var boundingBox = this.renderList.data[boundingBoxIndex];\n var min = boundingBox.minimum;\n var max = boundingBox.maximum;\n var diff = max.subtract(min);\n var median = min.add(diff.scale(0.5));\n var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)\n .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))\n .multiply(boundingBox.getWorldMatrix());\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());\n if (this.showBackLines) {\n // Back\n engine.setDepthFunctionToGreaterOrEqual();\n this.scene.resetCachedMaterial();\n this._colorShader.setColor4(\"color\", this.backColor.toColor4());\n this._colorShader.bind(worldMatrix);\n // Draw order\n engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);\n }\n // Front\n engine.setDepthFunctionToLess();\n this.scene.resetCachedMaterial();\n this._colorShader.setColor4(\"color\", this.frontColor.toColor4());\n this._colorShader.bind(worldMatrix);\n // Draw order\n engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);\n }\n this._colorShader.unbind();\n engine.setDepthFunctionToLessOrEqual();\n engine.setDepthWrite(true);\n };\n BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {\n this._prepareRessources();\n if (!this._colorShader.isReady() || !mesh._boundingInfo) {\n return;\n }\n var engine = this.scene.getEngine();\n engine.setDepthWrite(false);\n engine.setColorWrite(false);\n this._colorShader._preBind();\n var boundingBox = mesh._boundingInfo.boundingBox;\n var min = boundingBox.minimum;\n var max = boundingBox.maximum;\n var diff = max.subtract(min);\n var median = min.add(diff.scale(0.5));\n var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)\n .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))\n .multiply(boundingBox.getWorldMatrix());\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());\n engine.setDepthFunctionToLess();\n this.scene.resetCachedMaterial();\n this._colorShader.bind(worldMatrix);\n engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);\n this._colorShader.unbind();\n engine.setDepthFunctionToLessOrEqual();\n engine.setDepthWrite(true);\n engine.setColorWrite(true);\n };\n BoundingBoxRenderer.prototype.dispose = function () {\n if (!this._colorShader) {\n return;\n }\n this.renderList.dispose();\n this._colorShader.dispose();\n var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (buffer) {\n buffer.dispose();\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n this.scene.getEngine()._releaseBuffer(this._indexBuffer);\n };\n return BoundingBoxRenderer;\n }());\n BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boundingBoxRenderer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Engine.prototype.createTransformFeedback = function () {\n return this._gl.createTransformFeedback();\n };\n BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {\n this._gl.deleteTransformFeedback(value);\n };\n BABYLON.Engine.prototype.bindTransformFeedback = function (value) {\n this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);\n };\n BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {\n if (usePoints === void 0) { usePoints = true; }\n this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);\n };\n BABYLON.Engine.prototype.endTransformFeedback = function () {\n this._gl.endTransformFeedback();\n };\n BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {\n this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);\n };\n BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {\n this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);\n };\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.engine.transformFeedback.js.map\n\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This represents a GPU particle system in Babylon\n * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data\n * @see https://www.babylonjs-playground.com/#PU4WYI#4\n */\n var GPUParticleSystem = /** @class */ (function () {\n /**\n * Instantiates a GPU particle system.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * @param name The name of the particle system\n * @param options The options used to create the system\n * @param scene The scene the particle system belongs to\n * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture\n */\n function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {\n if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }\n /**\n * The emitter represents the Mesh or position we are attaching the particle system to.\n */\n this.emitter = null;\n /**\n * The rendering group used by the Particle system to chose when to render.\n */\n this.renderingGroupId = 0;\n /**\n * The layer mask we are rendering the particles through.\n */\n this.layerMask = 0x0FFFFFFF;\n this._accumulatedCount = 0;\n this._targetIndex = 0;\n this._currentRenderId = -1;\n this._started = false;\n this._stopped = false;\n this._timeDelta = 0;\n this._attributesStrideSize = 21;\n this._actualFrame = 0;\n this._rawTextureWidth = 256;\n /**\n * List of animations used by the particle system.\n */\n this.animations = [];\n /**\n * An event triggered when the system is disposed.\n */\n this.onDisposeObservable = new BABYLON.Observable();\n /**\n * The overall motion speed (0.01 is default update speed, faster updates = faster animation)\n */\n this.updateSpeed = 0.01;\n /**\n * The amount of time the particle system is running (depends of the overall update speed).\n */\n this.targetStopDuration = 0;\n /**\n * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.\n */\n this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;\n /**\n * Minimum life time of emitting particles.\n */\n this.minLifeTime = 1;\n /**\n * Maximum life time of emitting particles.\n */\n this.maxLifeTime = 1;\n /**\n * Minimum Size of emitting particles.\n */\n this.minSize = 1;\n /**\n * Maximum Size of emitting particles.\n */\n this.maxSize = 1;\n /**\n * Minimum scale of emitting particles on X axis.\n */\n this.minScaleX = 1;\n /**\n * Maximum scale of emitting particles on X axis.\n */\n this.maxScaleX = 1;\n /**\n * Minimum scale of emitting particles on Y axis.\n */\n this.minScaleY = 1;\n /**\n * Maximum scale of emitting particles on Y axis.\n */\n this.maxScaleY = 1;\n /**\n * Random color of each particle after it has been emitted, between color1 and color2 vectors.\n */\n this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * Random color of each particle after it has been emitted, between color1 and color2 vectors.\n */\n this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * Color the particle will have at the end of its lifetime.\n */\n this.colorDead = new BABYLON.Color4(0, 0, 0, 0);\n /**\n * The maximum number of particles to emit per frame until we reach the activeParticleCount value\n */\n this.emitRate = 100;\n /**\n * You can use gravity if you want to give an orientation to your particles.\n */\n this.gravity = BABYLON.Vector3.Zero();\n /**\n * Minimum power of emitting particles.\n */\n this.minEmitPower = 1;\n /**\n * Maximum power of emitting particles.\n */\n this.maxEmitPower = 1;\n /**\n * Minimum angular speed of emitting particles (Z-axis rotation for each particle).\n */\n this.minAngularSpeed = 0;\n /**\n * Maximum angular speed of emitting particles (Z-axis rotation for each particle).\n */\n this.maxAngularSpeed = 0;\n /**\n * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls\n * to override the particles.\n */\n this.forceDepthWrite = false;\n this._preWarmDone = false;\n /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */\n this.preWarmCycles = 0;\n /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */\n this.preWarmStepOffset = 1;\n /**\n * Gets or sets the minimal initial rotation in radians.\n */\n this.minInitialRotation = 0;\n /**\n * Gets or sets the maximal initial rotation in radians.\n */\n this.maxInitialRotation = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)\n */\n this.spriteCellChangeSpeed = 1;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display\n */\n this.startSpriteCellID = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display\n */\n this.endSpriteCellID = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use\n */\n this.spriteCellWidth = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use\n */\n this.spriteCellHeight = 0;\n /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */\n this.translationPivot = new BABYLON.Vector2(0, 0);\n /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */\n this.noiseStrength = new BABYLON.Vector3(10, 10, 10);\n /**\n * Gets or sets the billboard mode to use when isBillboardBased = true.\n * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far\n */\n this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;\n this._isBillboardBased = true;\n this._colorGradients = null;\n this._angularSpeedGradients = null;\n this._sizeGradients = null;\n this._velocityGradients = null;\n this.id = name;\n this.name = name;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this._engine = this._scene.getEngine();\n if (!options.randomTextureSize) {\n delete options.randomTextureSize;\n }\n var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);\n var optionsAsNumber = options;\n if (isFinite(optionsAsNumber)) {\n fullOptions.capacity = optionsAsNumber;\n }\n this._capacity = fullOptions.capacity;\n this._activeCount = fullOptions.capacity;\n this._currentActiveCount = 0;\n this._isAnimationSheetEnabled = isAnimationSheetEnabled;\n this._scene.particleSystems.push(this);\n this._updateEffectOptions = {\n attributes: [\"position\", \"age\", \"life\", \"seed\", \"size\", \"color\", \"direction\", \"initialDirection\", \"angle\", \"cellIndex\"],\n uniformsNames: [\"currentCount\", \"timeDelta\", \"emitterWM\", \"lifeTime\", \"color1\", \"color2\", \"sizeRange\", \"scaleRange\", \"gravity\", \"emitPower\",\n \"direction1\", \"direction2\", \"minEmitBox\", \"maxEmitBox\", \"radius\", \"directionRandomizer\", \"height\", \"coneAngle\", \"stopFactor\",\n \"angleRange\", \"radiusRange\", \"cellInfos\", \"noiseStrength\"],\n uniformBuffersNames: [],\n samplers: [\"randomSampler\", \"randomSampler2\", \"sizeGradientSampler\", \"angularSpeedGradientSampler\", \"velocityGradientSampler\", \"noiseSampler\"],\n defines: \"\",\n fallbacks: null,\n onCompiled: null,\n onError: null,\n indexParameters: null,\n maxSimultaneousLights: 0,\n transformFeedbackVaryings: []\n };\n this.particleEmitterType = new BABYLON.BoxParticleEmitter();\n // Random data\n var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);\n var d = [];\n for (var i = 0; i < maxTextureSize; ++i) {\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n }\n this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);\n this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n d = [];\n for (var i = 0; i < maxTextureSize; ++i) {\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n }\n this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);\n this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n this._randomTextureSize = maxTextureSize;\n }\n Object.defineProperty(GPUParticleSystem, \"IsSupported\", {\n /**\n * Gets a boolean indicating if the GPU particles can be rendered on current browser\n */\n get: function () {\n if (!BABYLON.Engine.LastCreatedEngine) {\n return false;\n }\n return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GPUParticleSystem.prototype, \"direction1\", {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.direction1) {\n return this.particleEmitterType.direction1;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.direction1) {\n this.particleEmitterType.direction1 = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GPUParticleSystem.prototype, \"direction2\", {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.direction2) {\n return this.particleEmitterType.direction2;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.direction2) {\n this.particleEmitterType.direction2 = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GPUParticleSystem.prototype, \"minEmitBox\", {\n /**\n * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.minEmitBox) {\n return this.particleEmitterType.minEmitBox;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.minEmitBox) {\n this.particleEmitterType.minEmitBox = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GPUParticleSystem.prototype, \"maxEmitBox\", {\n /**\n * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.maxEmitBox) {\n return this.particleEmitterType.maxEmitBox;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.maxEmitBox) {\n this.particleEmitterType.maxEmitBox = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the maximum number of particles active at the same time.\n * @returns The max number of active particles.\n */\n GPUParticleSystem.prototype.getCapacity = function () {\n return this._capacity;\n };\n Object.defineProperty(GPUParticleSystem.prototype, \"activeParticleCount\", {\n /**\n * Gets or set the number of active particles\n */\n get: function () {\n return this._activeCount;\n },\n set: function (value) {\n this._activeCount = Math.min(value, this._capacity);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GPUParticleSystem.prototype, \"isAnimationSheetEnabled\", {\n /**\n * Gets whether an animation sprite sheet is enabled or not on the particle system\n */\n get: function () {\n return this._isAnimationSheetEnabled;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Is this system ready to be used/rendered\n * @return true if the system is ready\n */\n GPUParticleSystem.prototype.isReady = function () {\n if (!this._updateEffect) {\n this._recreateUpdateEffect();\n this._recreateRenderEffect();\n return false;\n }\n if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {\n return false;\n }\n return true;\n };\n /**\n * Gets Wether the system has been started.\n * @returns True if it has been started, otherwise false.\n */\n GPUParticleSystem.prototype.isStarted = function () {\n return this._started;\n };\n /**\n * Starts the particle system and begins to emit\n * @param delay defines the delay in milliseconds before starting the system (0 by default)\n */\n GPUParticleSystem.prototype.start = function (delay) {\n var _this = this;\n if (delay === void 0) { delay = 0; }\n if (delay) {\n setTimeout(function () {\n _this.start(0);\n }, delay);\n return;\n }\n this._started = true;\n this._stopped = false;\n this._preWarmDone = false;\n };\n /**\n * Stops the particle system.\n */\n GPUParticleSystem.prototype.stop = function () {\n this._stopped = true;\n };\n /**\n * Remove all active particles\n */\n GPUParticleSystem.prototype.reset = function () {\n this._releaseBuffers();\n this._releaseVAOs();\n this._currentActiveCount = 0;\n this._targetIndex = 0;\n };\n /**\n * Returns the string \"GPUParticleSystem\"\n * @returns a string containing the class name\n */\n GPUParticleSystem.prototype.getClassName = function () {\n return \"GPUParticleSystem\";\n };\n Object.defineProperty(GPUParticleSystem.prototype, \"isBillboardBased\", {\n /**\n * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction\n */\n get: function () {\n return this._isBillboardBased;\n },\n set: function (value) {\n if (this._isBillboardBased === value) {\n return;\n }\n this._isBillboardBased = value;\n this._releaseBuffers();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the current list of color gradients.\n * You must use addColorGradient and removeColorGradient to udpate this list\n * @returns the list of color gradients\n */\n GPUParticleSystem.prototype.getColorGradients = function () {\n return this._colorGradients;\n };\n /**\n * Gets the current list of size gradients.\n * You must use addSizeGradient and removeSizeGradient to udpate this list\n * @returns the list of size gradients\n */\n GPUParticleSystem.prototype.getSizeGradients = function () {\n return this._sizeGradients;\n };\n /**\n * Gets the current list of angular speed gradients.\n * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list\n * @returns the list of angular speed gradients\n */\n GPUParticleSystem.prototype.getAngularSpeedGradients = function () {\n return this._angularSpeedGradients;\n };\n /**\n * Gets the current list of velocity gradients.\n * You must use addVelocityGradient and removeVelocityGradient to udpate this list\n * @returns the list of angular speed gradients\n */\n GPUParticleSystem.prototype.getVelocityGradients = function () {\n return this._velocityGradients;\n };\n GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {\n if (!gradients) {\n return this;\n }\n var index = 0;\n for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {\n var valueGradient = gradients_1[_i];\n if (valueGradient.gradient === gradient) {\n gradients.splice(index, 1);\n break;\n }\n index++;\n }\n if (texture) {\n texture.dispose();\n }\n this._releaseBuffers();\n return this;\n };\n /**\n * Adds a new color gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param color defines the color to affect to the specified gradient\n * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {\n if (!this._colorGradients) {\n this._colorGradients = [];\n }\n var colorGradient = new BABYLON.ColorGradient();\n colorGradient.gradient = gradient;\n colorGradient.color1 = color1;\n this._colorGradients.push(colorGradient);\n this._colorGradients.sort(function (a, b) {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n if (this._colorGradientsTexture) {\n this._colorGradientsTexture.dispose();\n this._colorGradientsTexture = null;\n }\n this._releaseBuffers();\n return this;\n };\n /**\n * Remove a specific color gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.removeColorGradient = function (gradient) {\n this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);\n this._colorGradientsTexture = null;\n return this;\n };\n GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {\n var valueGradient = new BABYLON.FactorGradient();\n valueGradient.gradient = gradient;\n valueGradient.factor1 = factor;\n factorGradients.push(valueGradient);\n factorGradients.sort(function (a, b) {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n this._releaseBuffers();\n };\n /**\n * Adds a new size gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {\n if (!this._sizeGradients) {\n this._sizeGradients = [];\n }\n this._addFactorGradient(this._sizeGradients, gradient, factor);\n if (this._sizeGradientsTexture) {\n this._sizeGradientsTexture.dispose();\n this._sizeGradientsTexture = null;\n }\n this._releaseBuffers();\n return this;\n };\n /**\n * Remove a specific size gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {\n this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);\n this._sizeGradientsTexture = null;\n return this;\n };\n /**\n * Adds a new angular speed gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {\n if (!this._angularSpeedGradients) {\n this._angularSpeedGradients = [];\n }\n this._addFactorGradient(this._angularSpeedGradients, gradient, factor);\n if (this._angularSpeedGradientsTexture) {\n this._angularSpeedGradientsTexture.dispose();\n this._angularSpeedGradientsTexture = null;\n }\n this._releaseBuffers();\n return this;\n };\n /**\n * Remove a specific angular speed gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {\n this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);\n this._angularSpeedGradientsTexture = null;\n return this;\n };\n /**\n * Adds a new velocity gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {\n if (!this._velocityGradients) {\n this._velocityGradients = [];\n }\n this._addFactorGradient(this._velocityGradients, gradient, factor);\n if (this._velocityGradientsTexture) {\n this._velocityGradientsTexture.dispose();\n this._velocityGradientsTexture = null;\n }\n this._releaseBuffers();\n return this;\n };\n /**\n * Remove a specific velocity gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {\n this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);\n this._velocityGradientsTexture = null;\n return this;\n };\n GPUParticleSystem.prototype._createUpdateVAO = function (source) {\n var updateVertexBuffers = {};\n updateVertexBuffers[\"position\"] = source.createVertexBuffer(\"position\", 0, 3);\n updateVertexBuffers[\"age\"] = source.createVertexBuffer(\"age\", 3, 1);\n updateVertexBuffers[\"life\"] = source.createVertexBuffer(\"life\", 4, 1);\n updateVertexBuffers[\"seed\"] = source.createVertexBuffer(\"seed\", 5, 4);\n updateVertexBuffers[\"size\"] = source.createVertexBuffer(\"size\", 9, 3);\n var offset = 12;\n if (!this._colorGradientsTexture) {\n updateVertexBuffers[\"color\"] = source.createVertexBuffer(\"color\", offset, 4);\n offset += 4;\n }\n updateVertexBuffers[\"direction\"] = source.createVertexBuffer(\"direction\", offset, 3);\n offset += 3;\n if (!this._isBillboardBased) {\n updateVertexBuffers[\"initialDirection\"] = source.createVertexBuffer(\"initialDirection\", offset, 3);\n offset += 3;\n }\n if (this._angularSpeedGradientsTexture) {\n updateVertexBuffers[\"angle\"] = source.createVertexBuffer(\"angle\", offset, 1);\n offset += 1;\n }\n else {\n updateVertexBuffers[\"angle\"] = source.createVertexBuffer(\"angle\", offset, 2);\n offset += 2;\n }\n if (this._isAnimationSheetEnabled) {\n updateVertexBuffers[\"cellIndex\"] = source.createVertexBuffer(\"cellIndex\", offset, 1);\n offset += 1;\n }\n var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);\n this._engine.bindArrayBuffer(null);\n return vao;\n };\n GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {\n var renderVertexBuffers = {};\n renderVertexBuffers[\"position\"] = source.createVertexBuffer(\"position\", 0, 3, this._attributesStrideSize, true);\n renderVertexBuffers[\"age\"] = source.createVertexBuffer(\"age\", 3, 1, this._attributesStrideSize, true);\n renderVertexBuffers[\"life\"] = source.createVertexBuffer(\"life\", 4, 1, this._attributesStrideSize, true);\n renderVertexBuffers[\"size\"] = source.createVertexBuffer(\"size\", 9, 3, this._attributesStrideSize, true);\n var offset = 12;\n if (!this._colorGradientsTexture) {\n renderVertexBuffers[\"color\"] = source.createVertexBuffer(\"color\", offset, 4, this._attributesStrideSize, true);\n offset += 4;\n }\n offset += 3; // Direction\n if (!this._isBillboardBased) {\n renderVertexBuffers[\"initialDirection\"] = source.createVertexBuffer(\"initialDirection\", offset, 3, this._attributesStrideSize, true);\n offset += 3;\n }\n renderVertexBuffers[\"angle\"] = source.createVertexBuffer(\"angle\", offset, 1, this._attributesStrideSize, true);\n if (this._angularSpeedGradientsTexture) {\n offset++;\n }\n else {\n offset += 2;\n }\n if (this._isAnimationSheetEnabled) {\n renderVertexBuffers[\"cellIndex\"] = source.createVertexBuffer(\"cellIndex\", offset, 1, this._attributesStrideSize, true);\n offset += 1;\n }\n renderVertexBuffers[\"offset\"] = spriteSource.createVertexBuffer(\"offset\", 0, 2);\n renderVertexBuffers[\"uv\"] = spriteSource.createVertexBuffer(\"uv\", 2, 2);\n var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);\n this._engine.bindArrayBuffer(null);\n return vao;\n };\n GPUParticleSystem.prototype._initialize = function (force) {\n if (force === void 0) { force = false; }\n if (this._buffer0 && !force) {\n return;\n }\n var engine = this._scene.getEngine();\n var data = new Array();\n if (!this.isBillboardBased) {\n this._attributesStrideSize += 3;\n }\n if (this._colorGradientsTexture) {\n this._attributesStrideSize -= 4;\n }\n if (this._angularSpeedGradientsTexture) {\n this._attributesStrideSize -= 1;\n }\n if (this._isAnimationSheetEnabled) {\n this._attributesStrideSize += 1;\n }\n for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {\n // position\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n // Age and life\n data.push(0.0); // create the particle as a dead one to create a new one at start\n data.push(0.0);\n // Seed\n data.push(Math.random());\n data.push(Math.random());\n data.push(Math.random());\n data.push(Math.random());\n // Size\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n if (!this._colorGradientsTexture) {\n // color\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n }\n // direction\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n if (!this.isBillboardBased) {\n // initialDirection\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n }\n // angle\n data.push(0.0);\n if (!this._angularSpeedGradientsTexture) {\n data.push(0.0);\n }\n if (this._isAnimationSheetEnabled) {\n data.push(0.0);\n }\n }\n // Sprite data\n var spriteData = new Float32Array([0.5, 0.5, 1, 1,\n -0.5, 0.5, 0, 1,\n -0.5, -0.5, 0, 0,\n 0.5, -0.5, 1, 0]);\n // Buffers\n this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);\n this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);\n this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);\n // Update VAO\n this._updateVAO = [];\n this._updateVAO.push(this._createUpdateVAO(this._buffer0));\n this._updateVAO.push(this._createUpdateVAO(this._buffer1));\n // Render VAO\n this._renderVAO = [];\n this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));\n this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));\n // Links\n this._sourceBuffer = this._buffer0;\n this._targetBuffer = this._buffer1;\n };\n /** @hidden */\n GPUParticleSystem.prototype._recreateUpdateEffect = function () {\n var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : \"\";\n if (this._isBillboardBased) {\n defines += \"\\n#define BILLBOARD\";\n }\n if (this._colorGradientsTexture) {\n defines += \"\\n#define COLORGRADIENTS\";\n }\n if (this._sizeGradientsTexture) {\n defines += \"\\n#define SIZEGRADIENTS\";\n }\n if (this._angularSpeedGradientsTexture) {\n defines += \"\\n#define ANGULARSPEEDGRADIENTS\";\n }\n if (this._velocityGradientsTexture) {\n defines += \"\\n#define VELOCITYGRADIENTS\";\n }\n if (this.isAnimationSheetEnabled) {\n defines += \"\\n#define ANIMATESHEET\";\n }\n if (this.noiseTexture) {\n defines += \"\\n#define NOISE\";\n }\n if (this._updateEffect && this._updateEffectOptions.defines === defines) {\n return;\n }\n this._updateEffectOptions.transformFeedbackVaryings = [\"outPosition\", \"outAge\", \"outLife\", \"outSeed\", \"outSize\"];\n if (!this._colorGradientsTexture) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outColor\");\n }\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outDirection\");\n if (!this._isBillboardBased) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outInitialDirection\");\n }\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outAngle\");\n if (this.isAnimationSheetEnabled) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outCellIndex\");\n }\n this._updateEffectOptions.defines = defines;\n this._updateEffect = new BABYLON.Effect(\"gpuUpdateParticles\", this._updateEffectOptions, this._scene.getEngine());\n };\n /** @hidden */\n GPUParticleSystem.prototype._recreateRenderEffect = function () {\n var defines = \"\";\n if (this._scene.clipPlane) {\n defines = \"\\n#define CLIPPLANE\";\n }\n if (this._isBillboardBased) {\n defines += \"\\n#define BILLBOARD\";\n switch (this.billboardMode) {\n case BABYLON.AbstractMesh.BILLBOARDMODE_Y:\n defines += \"\\n#define BILLBOARDY\";\n break;\n case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:\n default:\n break;\n }\n }\n if (this._colorGradientsTexture) {\n defines += \"\\n#define COLORGRADIENTS\";\n }\n if (this.isAnimationSheetEnabled) {\n defines += \"\\n#define ANIMATESHEET\";\n }\n if (this._renderEffect && this._renderEffect.defines === defines) {\n return;\n }\n this._renderEffect = new BABYLON.Effect(\"gpuRenderParticles\", [\"position\", \"age\", \"life\", \"size\", \"color\", \"offset\", \"uv\", \"initialDirection\", \"angle\", \"cellIndex\"], [\"view\", \"projection\", \"colorDead\", \"invView\", \"vClipPlane\", \"sheetInfos\", \"translationPivot\", \"eyePosition\"], [\"textureSampler\", \"colorGradientSampler\"], this._scene.getEngine(), defines);\n };\n /**\n * Animates the particle system for the current frame by emitting new particles and or animating the living ones.\n * @param preWarm defines if we are in the pre-warmimg phase\n */\n GPUParticleSystem.prototype.animate = function (preWarm) {\n if (preWarm === void 0) { preWarm = false; }\n this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());\n this._actualFrame += this._timeDelta;\n if (!this._stopped) {\n if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {\n this.stop();\n }\n }\n };\n GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {\n var texture = this[textureName];\n if (!factorGradients || !factorGradients.length || texture) {\n return;\n }\n var data = new Float32Array(this._rawTextureWidth);\n for (var x = 0; x < this._rawTextureWidth; x++) {\n var ratio = x / this._rawTextureWidth;\n BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {\n data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);\n });\n }\n this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);\n };\n GPUParticleSystem.prototype._createSizeGradientTexture = function () {\n this._createFactorGradientTexture(this._sizeGradients, \"_sizeGradientsTexture\");\n };\n GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {\n this._createFactorGradientTexture(this._angularSpeedGradients, \"_angularSpeedGradientsTexture\");\n };\n GPUParticleSystem.prototype._createVelocityGradientTexture = function () {\n this._createFactorGradientTexture(this._velocityGradients, \"_velocityGradientsTexture\");\n };\n GPUParticleSystem.prototype._createColorGradientTexture = function () {\n if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {\n return;\n }\n var data = new Uint8Array(this._rawTextureWidth * 4);\n var tmpColor = BABYLON.Tmp.Color4[0];\n for (var x = 0; x < this._rawTextureWidth; x++) {\n var ratio = x / this._rawTextureWidth;\n BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {\n BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);\n data[x * 4] = tmpColor.r * 255;\n data[x * 4 + 1] = tmpColor.g * 255;\n data[x * 4 + 2] = tmpColor.b * 255;\n data[x * 4 + 3] = tmpColor.a * 255;\n });\n }\n this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);\n };\n /**\n * Renders the particle system in its current state\n * @param preWarm defines if the system should only update the particles but not render them\n * @returns the current number of particles\n */\n GPUParticleSystem.prototype.render = function (preWarm) {\n if (preWarm === void 0) { preWarm = false; }\n if (!this._started) {\n return 0;\n }\n this._createColorGradientTexture();\n this._createSizeGradientTexture();\n this._createAngularSpeedGradientTexture();\n this._createVelocityGradientTexture();\n this._recreateUpdateEffect();\n this._recreateRenderEffect();\n if (!this.isReady()) {\n return 0;\n }\n if (!preWarm) {\n if (!this._preWarmDone && this.preWarmCycles) {\n for (var index = 0; index < this.preWarmCycles; index++) {\n this.animate(true);\n this.render(true);\n }\n this._preWarmDone = true;\n }\n if (this._currentRenderId === this._scene.getRenderId()) {\n return 0;\n }\n this._currentRenderId = this._scene.getRenderId();\n }\n // Get everything ready to render\n this._initialize();\n this._accumulatedCount += this.emitRate * this._timeDelta;\n if (this._accumulatedCount > 1) {\n var intPart = this._accumulatedCount | 0;\n this._accumulatedCount -= intPart;\n this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);\n }\n if (!this._currentActiveCount) {\n return 0;\n }\n // Enable update effect\n this._engine.enableEffect(this._updateEffect);\n this._engine.setState(false);\n this._updateEffect.setFloat(\"currentCount\", this._currentActiveCount);\n this._updateEffect.setFloat(\"timeDelta\", this._timeDelta);\n this._updateEffect.setFloat(\"stopFactor\", this._stopped ? 0 : 1);\n this._updateEffect.setTexture(\"randomSampler\", this._randomTexture);\n this._updateEffect.setTexture(\"randomSampler2\", this._randomTexture2);\n this._updateEffect.setFloat2(\"lifeTime\", this.minLifeTime, this.maxLifeTime);\n this._updateEffect.setFloat2(\"emitPower\", this.minEmitPower, this.maxEmitPower);\n if (!this._colorGradientsTexture) {\n this._updateEffect.setDirectColor4(\"color1\", this.color1);\n this._updateEffect.setDirectColor4(\"color2\", this.color2);\n }\n this._updateEffect.setFloat2(\"sizeRange\", this.minSize, this.maxSize);\n this._updateEffect.setFloat4(\"scaleRange\", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);\n this._updateEffect.setFloat4(\"angleRange\", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);\n this._updateEffect.setVector3(\"gravity\", this.gravity);\n if (this._sizeGradientsTexture) {\n this._updateEffect.setTexture(\"sizeGradientSampler\", this._sizeGradientsTexture);\n }\n if (this._angularSpeedGradientsTexture) {\n this._updateEffect.setTexture(\"angularSpeedGradientSampler\", this._angularSpeedGradientsTexture);\n }\n if (this._velocityGradientsTexture) {\n this._updateEffect.setTexture(\"velocityGradientSampler\", this._velocityGradientsTexture);\n }\n if (this.particleEmitterType) {\n this.particleEmitterType.applyToShader(this._updateEffect);\n }\n if (this._isAnimationSheetEnabled) {\n this._updateEffect.setFloat3(\"cellInfos\", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);\n }\n if (this.noiseTexture) {\n this._updateEffect.setTexture(\"noiseSampler\", this.noiseTexture);\n this._updateEffect.setVector3(\"noiseStrength\", this.noiseStrength);\n }\n var emitterWM;\n if (this.emitter.position) {\n var emitterMesh = this.emitter;\n emitterWM = emitterMesh.getWorldMatrix();\n }\n else {\n var emitterPosition = this.emitter;\n emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);\n }\n this._updateEffect.setMatrix(\"emitterWM\", emitterWM);\n // Bind source VAO\n this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);\n // Update\n this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());\n this._engine.setRasterizerState(false);\n this._engine.beginTransformFeedback(true);\n this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);\n this._engine.endTransformFeedback();\n this._engine.setRasterizerState(true);\n this._engine.bindTransformFeedbackBuffer(null);\n if (!preWarm) {\n // Enable render effect\n this._engine.enableEffect(this._renderEffect);\n var viewMatrix = this._scene.getViewMatrix();\n this._renderEffect.setMatrix(\"view\", viewMatrix);\n this._renderEffect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n this._renderEffect.setTexture(\"textureSampler\", this.particleTexture);\n this._renderEffect.setVector2(\"translationPivot\", this.translationPivot);\n if (this._colorGradientsTexture) {\n this._renderEffect.setTexture(\"colorGradientSampler\", this._colorGradientsTexture);\n }\n else {\n this._renderEffect.setDirectColor4(\"colorDead\", this.colorDead);\n }\n if (this._isAnimationSheetEnabled && this.particleTexture) {\n var baseSize = this.particleTexture.getBaseSize();\n this._renderEffect.setFloat3(\"sheetInfos\", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);\n }\n if (this._isBillboardBased) {\n var camera = this._scene.activeCamera;\n this._renderEffect.setVector3(\"eyePosition\", camera.globalPosition);\n }\n if (this._scene.clipPlane) {\n var clipPlane = this._scene.clipPlane;\n var invView = viewMatrix.clone();\n invView.invert();\n this._renderEffect.setMatrix(\"invView\", invView);\n this._renderEffect.setFloat4(\"vClipPlane\", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);\n }\n // Draw order\n switch (this.blendMode) {\n case BABYLON.ParticleSystem.BLENDMODE_ADD:\n this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);\n break;\n case BABYLON.ParticleSystem.BLENDMODE_ONEONE:\n this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);\n break;\n case BABYLON.ParticleSystem.BLENDMODE_STANDARD:\n this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);\n break;\n }\n if (this.forceDepthWrite) {\n this._engine.setDepthWrite(true);\n }\n // Bind source VAO\n this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);\n // Render\n this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);\n this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n }\n // Switch VAOs\n this._targetIndex++;\n if (this._targetIndex === 2) {\n this._targetIndex = 0;\n }\n // Switch buffers\n var tmpBuffer = this._sourceBuffer;\n this._sourceBuffer = this._targetBuffer;\n this._targetBuffer = tmpBuffer;\n return this._currentActiveCount;\n };\n /**\n * Rebuilds the particle system\n */\n GPUParticleSystem.prototype.rebuild = function () {\n this._initialize(true);\n };\n GPUParticleSystem.prototype._releaseBuffers = function () {\n if (this._buffer0) {\n this._buffer0.dispose();\n this._buffer0 = null;\n }\n if (this._buffer1) {\n this._buffer1.dispose();\n this._buffer1 = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n };\n GPUParticleSystem.prototype._releaseVAOs = function () {\n if (!this._updateVAO) {\n return;\n }\n for (var index = 0; index < this._updateVAO.length; index++) {\n this._engine.releaseVertexArrayObject(this._updateVAO[index]);\n }\n this._updateVAO = [];\n for (var index = 0; index < this._renderVAO.length; index++) {\n this._engine.releaseVertexArrayObject(this._renderVAO[index]);\n }\n this._renderVAO = [];\n };\n /**\n * Disposes the particle system and free the associated resources\n * @param disposeTexture defines if the particule texture must be disposed as well (true by default)\n */\n GPUParticleSystem.prototype.dispose = function (disposeTexture) {\n if (disposeTexture === void 0) { disposeTexture = true; }\n var index = this._scene.particleSystems.indexOf(this);\n if (index > -1) {\n this._scene.particleSystems.splice(index, 1);\n }\n this._releaseBuffers();\n this._releaseVAOs();\n if (this._colorGradientsTexture) {\n this._colorGradientsTexture.dispose();\n this._colorGradientsTexture = null;\n }\n if (this._sizeGradientsTexture) {\n this._sizeGradientsTexture.dispose();\n this._sizeGradientsTexture = null;\n }\n if (this._angularSpeedGradientsTexture) {\n this._angularSpeedGradientsTexture.dispose();\n this._angularSpeedGradientsTexture = null;\n }\n if (this._velocityGradientsTexture) {\n this._velocityGradientsTexture.dispose();\n this._velocityGradientsTexture = null;\n }\n if (this._randomTexture) {\n this._randomTexture.dispose();\n this._randomTexture = null;\n }\n if (this._randomTexture2) {\n this._randomTexture2.dispose();\n this._randomTexture2 = null;\n }\n if (disposeTexture && this.particleTexture) {\n this.particleTexture.dispose();\n this.particleTexture = null;\n }\n if (disposeTexture && this.noiseTexture) {\n this.noiseTexture.dispose();\n this.noiseTexture = null;\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n };\n /**\n * Clones the particle system.\n * @param name The name of the cloned object\n * @param newEmitter The new emitter to use\n * @returns the cloned particle system\n */\n GPUParticleSystem.prototype.clone = function (name, newEmitter) {\n var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);\n BABYLON.Tools.DeepCopy(this, result);\n if (newEmitter === undefined) {\n newEmitter = this.emitter;\n }\n result.emitter = newEmitter;\n if (this.particleTexture) {\n result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);\n }\n return result;\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n GPUParticleSystem.prototype.serialize = function () {\n var serializationObject = {};\n BABYLON.ParticleSystem._Serialize(serializationObject, this);\n serializationObject.activeParticleCount = this.activeParticleCount;\n return serializationObject;\n };\n /**\n * Parses a JSON object to create a GPU particle system.\n * @param parsedParticleSystem The JSON object to parse\n * @param scene The scene to create the particle system in\n * @param rootUrl The root url to use to load external dependencies like texture\n * @returns the parsed GPU particle system\n */\n GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {\n var name = parsedParticleSystem.name;\n var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);\n if (parsedParticleSystem.activeParticleCount) {\n particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;\n }\n BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);\n return particleSystem;\n };\n return GPUParticleSystem;\n }());\n BABYLON.GPUParticleSystem = GPUParticleSystem;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gpuParticleSystem.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Represents one particle of a solid particle system.\n */\n var SolidParticle = /** @class */ (function () {\n /**\n * Creates a Solid Particle object.\n * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()\n * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.\n * @param positionIndex (integer) is the starting index of the particle vertices in the SPS \"positions\" array.\n * @param indiceIndex (integer) is the starting index of the particle indices in the SPS \"indices\" array.\n * @param model (ModelShape) is a reference to the model shape on what the particle is designed.\n * @param shapeId (integer) is the model shape identifier in the SPS.\n * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))\n * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.\n */\n function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {\n if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }\n /**\n * particle global index\n */\n this.idx = 0;\n /**\n * The color of the particle\n */\n this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * The world space position of the particle.\n */\n this.position = BABYLON.Vector3.Zero();\n /**\n * The world space rotation of the particle. (Not use if rotationQuaternion is set)\n */\n this.rotation = BABYLON.Vector3.Zero();\n /**\n * The scaling of the particle.\n */\n this.scaling = BABYLON.Vector3.One();\n /**\n * The uvs of the particle.\n */\n this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);\n /**\n * The current speed of the particle.\n */\n this.velocity = BABYLON.Vector3.Zero();\n /**\n * The pivot point in the particle local space.\n */\n this.pivot = BABYLON.Vector3.Zero();\n /**\n * Must the particle be translated from its pivot point in its local space ?\n * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.\n * Default : false\n */\n this.translateFromPivot = false;\n /**\n * Is the particle active or not ?\n */\n this.alive = true;\n /**\n * Is the particle visible or not ?\n */\n this.isVisible = true;\n /**\n * Index of this particle in the global \"positions\" array (Internal use)\n */\n this._pos = 0;\n /**\n * Index of this particle in the global \"indices\" array (Internal use)\n */\n this._ind = 0;\n /**\n * ModelShape id of this particle\n */\n this.shapeId = 0;\n /**\n * Index of the particle in its shape id (Internal use)\n */\n this.idxInShape = 0;\n /**\n * Still set as invisible in order to skip useless computations (Internal use)\n */\n this._stillInvisible = false;\n /**\n * Last computed particle rotation matrix\n */\n this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];\n /**\n * Parent particle Id, if any.\n * Default null.\n */\n this.parentId = null;\n /**\n * Internal global position in the SPS.\n */\n this._globalPosition = BABYLON.Vector3.Zero();\n this.idx = particleIndex;\n this._pos = positionIndex;\n this._ind = indiceIndex;\n this._model = model;\n this.shapeId = shapeId;\n this.idxInShape = idxInShape;\n this._sps = sps;\n if (modelBoundingInfo) {\n this._modelBoundingInfo = modelBoundingInfo;\n this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);\n }\n }\n Object.defineProperty(SolidParticle.prototype, \"scale\", {\n /**\n * Legacy support, changed scale to scaling\n */\n get: function () {\n return this.scaling;\n },\n /**\n * Legacy support, changed scale to scaling\n */\n set: function (scale) {\n this.scaling = scale;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticle.prototype, \"quaternion\", {\n /**\n * Legacy support, changed quaternion to rotationQuaternion\n */\n get: function () {\n return this.rotationQuaternion;\n },\n /**\n * Legacy support, changed quaternion to rotationQuaternion\n */\n set: function (q) {\n this.rotationQuaternion = q;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a boolean. True if the particle intersects another particle or another mesh, else false.\n * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)\n * @param target is the object (solid particle or mesh) what the intersection is computed against.\n * @returns true if it intersects\n */\n SolidParticle.prototype.intersectsMesh = function (target) {\n if (!this._boundingInfo || !target._boundingInfo) {\n return false;\n }\n if (this._sps._bSphereOnly) {\n return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);\n }\n return this._boundingInfo.intersects(target._boundingInfo, false);\n };\n return SolidParticle;\n }());\n BABYLON.SolidParticle = SolidParticle;\n /**\n * Represents the shape of the model used by one particle of a solid particle system.\n * SPS internal tool, don't use it manually.\n */\n var ModelShape = /** @class */ (function () {\n /**\n * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.\n * SPS internal tool, don't use it manually.\n * @hidden\n */\n function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {\n /**\n * length of the shape in the model indices array (internal use)\n */\n this._indicesLength = 0;\n this.shapeID = id;\n this._shape = shape;\n this._indicesLength = indicesLength;\n this._shapeUV = shapeUV;\n this._positionFunction = posFunction;\n this._vertexFunction = vtxFunction;\n }\n return ModelShape;\n }());\n BABYLON.ModelShape = ModelShape;\n /**\n * Represents a Depth Sorted Particle in the solid particle system.\n */\n var DepthSortedParticle = /** @class */ (function () {\n function DepthSortedParticle() {\n /**\n * Index of the particle in the \"indices\" array\n */\n this.ind = 0;\n /**\n * Length of the particle shape in the \"indices\" array\n */\n this.indicesLength = 0;\n /**\n * Squared distance from the particle to the camera\n */\n this.sqDistance = 0.0;\n }\n return DepthSortedParticle;\n }());\n BABYLON.DepthSortedParticle = DepthSortedParticle;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.solidParticle.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.\n *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.\n\r\n * The SPS is also a particle system. It provides some methods to manage the particles.\n * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.\n *\n * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System\n */\n var SolidParticleSystem = /** @class */ (function () {\n /**\n * Creates a SPS (Solid Particle System) object.\n * @param name (String) is the SPS name, this will be the underlying mesh name.\n * @param scene (Scene) is the scene in which the SPS is added.\n * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.\n * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.\n * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.\n * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.\n * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).\n * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.\n * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.\n */\n function SolidParticleSystem(name, scene, options) {\n /**\n * The SPS array of Solid Particle objects. Just access each particle as with any classic array.\n * Example : var p = SPS.particles[i];\n */\n this.particles = new Array();\n /**\n * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.\n */\n this.nbParticles = 0;\n /**\n * If the particles must ever face the camera (default false). Useful for planar particles.\n */\n this.billboard = false;\n /**\n * Recompute normals when adding a shape\n */\n this.recomputeNormals = true;\n /**\n * This a counter ofr your own usage. It's not set by any SPS functions.\n */\n this.counter = 0;\n /**\n * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.\n * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns\n */\n this.vars = {};\n /**\n * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)\n */\n this._bSphereOnly = false;\n /**\n * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)\n */\n this._bSphereRadiusFactor = 1.0;\n this._positions = new Array();\n this._indices = new Array();\n this._normals = new Array();\n this._colors = new Array();\n this._uvs = new Array();\n this._index = 0; // indices index\n this._updatable = true;\n this._pickable = false;\n this._isVisibilityBoxLocked = false;\n this._alwaysVisible = false;\n this._depthSort = false;\n this._shapeCounter = 0;\n this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);\n this._color = new BABYLON.Color4(0, 0, 0, 0);\n this._computeParticleColor = true;\n this._computeParticleTexture = true;\n this._computeParticleRotation = true;\n this._computeParticleVertex = false;\n this._computeBoundingBox = false;\n this._depthSortParticles = true;\n this._cam_axisZ = BABYLON.Vector3.Zero();\n this._cam_axisY = BABYLON.Vector3.Zero();\n this._cam_axisX = BABYLON.Vector3.Zero();\n this._axisZ = BABYLON.Axis.Z;\n this._camDir = BABYLON.Vector3.Zero();\n this._camInvertedPosition = BABYLON.Vector3.Zero();\n this._rotMatrix = new BABYLON.Matrix();\n this._invertMatrix = new BABYLON.Matrix();\n this._rotated = BABYLON.Vector3.Zero();\n this._quaternion = new BABYLON.Quaternion();\n this._vertex = BABYLON.Vector3.Zero();\n this._normal = BABYLON.Vector3.Zero();\n this._yaw = 0.0;\n this._pitch = 0.0;\n this._roll = 0.0;\n this._halfroll = 0.0;\n this._halfpitch = 0.0;\n this._halfyaw = 0.0;\n this._sinRoll = 0.0;\n this._cosRoll = 0.0;\n this._sinPitch = 0.0;\n this._cosPitch = 0.0;\n this._sinYaw = 0.0;\n this._cosYaw = 0.0;\n this._mustUnrotateFixedNormals = false;\n this._minimum = BABYLON.Vector3.Zero();\n this._maximum = BABYLON.Vector3.Zero();\n this._minBbox = BABYLON.Vector3.Zero();\n this._maxBbox = BABYLON.Vector3.Zero();\n this._particlesIntersect = false;\n this._depthSortFunction = function (p1, p2) {\n return (p2.sqDistance - p1.sqDistance);\n };\n this._needs32Bits = false;\n this._pivotBackTranslation = BABYLON.Vector3.Zero();\n this._scaledPivot = BABYLON.Vector3.Zero();\n this._particleHasParent = false;\n this.name = name;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this._camera = scene.activeCamera;\n this._pickable = options ? options.isPickable : false;\n this._depthSort = options ? options.enableDepthSort : false;\n this._particlesIntersect = options ? options.particleIntersection : false;\n this._bSphereOnly = options ? options.boundingSphereOnly : false;\n this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;\n if (options && options.updatable !== undefined) {\n this._updatable = options.updatable;\n }\n else {\n this._updatable = true;\n }\n if (this._pickable) {\n this.pickedParticles = [];\n }\n if (this._depthSort) {\n this.depthSortedParticles = [];\n }\n }\n /**\n * Builds the SPS underlying mesh. Returns a standard Mesh.\n * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.\n * @returns the created mesh\n */\n SolidParticleSystem.prototype.buildMesh = function () {\n if (this.nbParticles === 0) {\n var triangle = BABYLON.MeshBuilder.CreateDisc(\"\", { radius: 1, tessellation: 3 }, this._scene);\n this.addShape(triangle, 1);\n triangle.dispose();\n }\n this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);\n this._positions32 = new Float32Array(this._positions);\n this._uvs32 = new Float32Array(this._uvs);\n this._colors32 = new Float32Array(this._colors);\n if (this.recomputeNormals) {\n BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);\n }\n this._normals32 = new Float32Array(this._normals);\n this._fixedNormal32 = new Float32Array(this._normals);\n if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction\n this._unrotateFixedNormals();\n }\n var vertexData = new BABYLON.VertexData();\n vertexData.indices = (this._depthSort) ? this._indices : this._indices32;\n vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);\n vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);\n if (this._uvs32.length > 0) {\n vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);\n }\n if (this._colors32.length > 0) {\n vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);\n }\n var mesh = new BABYLON.Mesh(this.name, this._scene);\n vertexData.applyToMesh(mesh, this._updatable);\n this.mesh = mesh;\n this.mesh.isPickable = this._pickable;\n // free memory\n if (!this._depthSort) {\n this._indices = null;\n }\n this._positions = null;\n this._normals = null;\n this._uvs = null;\n this._colors = null;\n if (!this._updatable) {\n this.particles.length = 0;\n }\n return mesh;\n };\n /**\n * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.\n * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.\n * Thus the particles generated from `digest()` have their property `position` set yet.\n * @param mesh ( Mesh ) is the mesh to be digested\n * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any\n * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets\n * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets\n * @returns the current SPS\n */\n SolidParticleSystem.prototype.digest = function (mesh, options) {\n var size = (options && options.facetNb) || 1;\n var number = (options && options.number) || 0;\n var delta = (options && options.delta) || 0;\n var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var meshInd = mesh.getIndices();\n var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);\n var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);\n var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var f = 0; // facet counter\n var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices\n // compute size from number\n if (number) {\n number = (number > totalFacets) ? totalFacets : number;\n size = Math.round(totalFacets / number);\n delta = 0;\n }\n else {\n size = (size > totalFacets) ? totalFacets : size;\n }\n var facetPos = []; // submesh positions\n var facetInd = []; // submesh indices\n var facetUV = []; // submesh UV\n var facetCol = []; // submesh colors\n var barycenter = BABYLON.Vector3.Zero();\n var sizeO = size;\n while (f < totalFacets) {\n size = sizeO + Math.floor((1 + delta) * Math.random());\n if (f > totalFacets - size) {\n size = totalFacets - f;\n }\n // reset temp arrays\n facetPos.length = 0;\n facetInd.length = 0;\n facetUV.length = 0;\n facetCol.length = 0;\n // iterate over \"size\" facets\n var fi = 0;\n for (var j = f * 3; j < (f + size) * 3; j++) {\n facetInd.push(fi);\n var i = meshInd[j];\n facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);\n if (meshUV) {\n facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);\n }\n if (meshCol) {\n facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);\n }\n fi++;\n }\n // create a model shape for each single particle\n var idx = this.nbParticles;\n var shape = this._posToShape(facetPos);\n var shapeUV = this._uvsToShapeUV(facetUV);\n // compute the barycenter of the shape\n var v;\n for (v = 0; v < shape.length; v++) {\n barycenter.addInPlace(shape[v]);\n }\n barycenter.scaleInPlace(1 / shape.length);\n // shift the shape from its barycenter to the origin\n for (v = 0; v < shape.length; v++) {\n shape[v].subtractInPlace(barycenter);\n }\n var bInfo;\n if (this._particlesIntersect) {\n bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);\n }\n var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);\n // add the particle in the SPS\n var currentPos = this._positions.length;\n var currentInd = this._indices.length;\n this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);\n this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);\n // initialize the particle position\n this.particles[this.nbParticles].position.addInPlace(barycenter);\n this._index += shape.length;\n idx++;\n this.nbParticles++;\n this._shapeCounter++;\n f += size;\n }\n return this;\n };\n // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()\n SolidParticleSystem.prototype._unrotateFixedNormals = function () {\n var index = 0;\n var idx = 0;\n for (var p = 0; p < this.particles.length; p++) {\n this._particle = this.particles[p];\n this._shape = this._particle._model._shape;\n if (this._particle.rotationQuaternion) {\n this._quaternion.copyFrom(this._particle.rotationQuaternion);\n }\n else {\n this._yaw = this._particle.rotation.y;\n this._pitch = this._particle.rotation.x;\n this._roll = this._particle.rotation.z;\n this._quaternionRotationYPR();\n }\n this._quaternionToRotationMatrix();\n this._rotMatrix.invertToRef(this._invertMatrix);\n for (var pt = 0; pt < this._shape.length; pt++) {\n idx = index + pt * 3;\n BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);\n this._fixedNormal32[idx] = this._normal.x;\n this._fixedNormal32[idx + 1] = this._normal.y;\n this._fixedNormal32[idx + 2] = this._normal.z;\n }\n index = idx + 3;\n }\n };\n //reset copy\n SolidParticleSystem.prototype._resetCopy = function () {\n this._copy.position.x = 0;\n this._copy.position.y = 0;\n this._copy.position.z = 0;\n this._copy.rotation.x = 0;\n this._copy.rotation.y = 0;\n this._copy.rotation.z = 0;\n this._copy.rotationQuaternion = null;\n this._copy.scaling.x = 1.0;\n this._copy.scaling.y = 1.0;\n this._copy.scaling.z = 1.0;\n this._copy.uvs.x = 0;\n this._copy.uvs.y = 0;\n this._copy.uvs.z = 1.0;\n this._copy.uvs.w = 1.0;\n this._copy.color = null;\n this._copy.translateFromPivot = false;\n };\n // _meshBuilder : inserts the shape model in the global SPS mesh\n SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {\n var i;\n var u = 0;\n var c = 0;\n var n = 0;\n this._resetCopy();\n if (options && options.positionFunction) { // call to custom positionFunction\n options.positionFunction(this._copy, idx, idxInShape);\n this._mustUnrotateFixedNormals = true;\n }\n if (this._copy.rotationQuaternion) {\n this._quaternion.copyFrom(this._copy.rotationQuaternion);\n }\n else {\n this._yaw = this._copy.rotation.y;\n this._pitch = this._copy.rotation.x;\n this._roll = this._copy.rotation.z;\n this._quaternionRotationYPR();\n }\n this._quaternionToRotationMatrix();\n this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;\n this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;\n this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;\n if (this._copy.translateFromPivot) {\n this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);\n }\n else {\n this._pivotBackTranslation.copyFrom(this._scaledPivot);\n }\n for (i = 0; i < shape.length; i++) {\n this._vertex.x = shape[i].x;\n this._vertex.y = shape[i].y;\n this._vertex.z = shape[i].z;\n if (options && options.vertexFunction) {\n options.vertexFunction(this._copy, this._vertex, i);\n }\n this._vertex.x *= this._copy.scaling.x;\n this._vertex.y *= this._copy.scaling.y;\n this._vertex.z *= this._copy.scaling.z;\n this._vertex.x -= this._scaledPivot.x;\n this._vertex.y -= this._scaledPivot.y;\n this._vertex.z -= this._scaledPivot.z;\n BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);\n this._rotated.addInPlace(this._pivotBackTranslation);\n positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);\n if (meshUV) {\n uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);\n u += 2;\n }\n if (this._copy.color) {\n this._color = this._copy.color;\n }\n else if (meshCol && meshCol[c] !== undefined) {\n this._color.r = meshCol[c];\n this._color.g = meshCol[c + 1];\n this._color.b = meshCol[c + 2];\n this._color.a = meshCol[c + 3];\n }\n else {\n this._color.r = 1.0;\n this._color.g = 1.0;\n this._color.b = 1.0;\n this._color.a = 1.0;\n }\n colors.push(this._color.r, this._color.g, this._color.b, this._color.a);\n c += 4;\n if (!this.recomputeNormals && meshNor) {\n this._normal.x = meshNor[n];\n this._normal.y = meshNor[n + 1];\n this._normal.z = meshNor[n + 2];\n BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);\n normals.push(this._normal.x, this._normal.y, this._normal.z);\n n += 3;\n }\n }\n for (i = 0; i < meshInd.length; i++) {\n var current_ind = p + meshInd[i];\n indices.push(current_ind);\n if (current_ind > 65535) {\n this._needs32Bits = true;\n }\n }\n if (this._pickable) {\n var nbfaces = meshInd.length / 3;\n for (i = 0; i < nbfaces; i++) {\n this.pickedParticles.push({ idx: idx, faceId: i });\n }\n }\n if (this._depthSort) {\n this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());\n }\n return this._copy;\n };\n // returns a shape array from positions array\n SolidParticleSystem.prototype._posToShape = function (positions) {\n var shape = [];\n for (var i = 0; i < positions.length; i += 3) {\n shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));\n }\n return shape;\n };\n // returns a shapeUV array from a Vector4 uvs\n SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {\n var shapeUV = [];\n if (uvs) {\n for (var i = 0; i < uvs.length; i++)\n shapeUV.push(uvs[i]);\n }\n return shapeUV;\n };\n // adds a new particle object in the particles array\n SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {\n if (bInfo === void 0) { bInfo = null; }\n var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);\n this.particles.push(sp);\n return sp;\n };\n /**\n * Adds some particles to the SPS from the model shape. Returns the shape id.\n * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps\n * @param mesh is any Mesh object that will be used as a model for the solid particles.\n * @param nb (positive integer) the number of particles to be created from this model\n * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.\n * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation\n * @returns the number of shapes in the system\n */\n SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {\n var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var meshInd = mesh.getIndices();\n var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);\n var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);\n var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var bbInfo;\n if (this._particlesIntersect) {\n bbInfo = mesh.getBoundingInfo();\n }\n var shape = this._posToShape(meshPos);\n var shapeUV = this._uvsToShapeUV(meshUV);\n var posfunc = options ? options.positionFunction : null;\n var vtxfunc = options ? options.vertexFunction : null;\n var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);\n // particles\n var sp;\n var currentCopy;\n var idx = this.nbParticles;\n for (var i = 0; i < nb; i++) {\n var currentPos = this._positions.length;\n var currentInd = this._indices.length;\n currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);\n if (this._updatable) {\n sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);\n sp.position.copyFrom(currentCopy.position);\n sp.rotation.copyFrom(currentCopy.rotation);\n if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {\n sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);\n }\n if (currentCopy.color && sp.color) {\n sp.color.copyFrom(currentCopy.color);\n }\n sp.scaling.copyFrom(currentCopy.scaling);\n sp.uvs.copyFrom(currentCopy.uvs);\n }\n this._index += shape.length;\n idx++;\n }\n this.nbParticles += nb;\n this._shapeCounter++;\n return this._shapeCounter - 1;\n };\n // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices\n SolidParticleSystem.prototype._rebuildParticle = function (particle) {\n this._resetCopy();\n if (particle._model._positionFunction) { // recall to stored custom positionFunction\n particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);\n }\n if (this._copy.rotationQuaternion) {\n this._quaternion.copyFrom(this._copy.rotationQuaternion);\n }\n else {\n this._yaw = this._copy.rotation.y;\n this._pitch = this._copy.rotation.x;\n this._roll = this._copy.rotation.z;\n this._quaternionRotationYPR();\n }\n this._quaternionToRotationMatrix();\n this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;\n this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;\n this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;\n if (this._copy.translateFromPivot) {\n this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);\n }\n else {\n this._pivotBackTranslation.copyFrom(this._scaledPivot);\n }\n this._shape = particle._model._shape;\n for (var pt = 0; pt < this._shape.length; pt++) {\n this._vertex.x = this._shape[pt].x;\n this._vertex.y = this._shape[pt].y;\n this._vertex.z = this._shape[pt].z;\n if (particle._model._vertexFunction) {\n particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction\n }\n this._vertex.x *= this._copy.scaling.x;\n this._vertex.y *= this._copy.scaling.y;\n this._vertex.z *= this._copy.scaling.z;\n this._vertex.x -= this._scaledPivot.x;\n this._vertex.y -= this._scaledPivot.y;\n this._vertex.z -= this._scaledPivot.z;\n BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);\n this._rotated.addInPlace(this._pivotBackTranslation);\n this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;\n this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;\n this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;\n }\n particle.position.x = 0.0;\n particle.position.y = 0.0;\n particle.position.z = 0.0;\n particle.rotation.x = 0.0;\n particle.rotation.y = 0.0;\n particle.rotation.z = 0.0;\n particle.rotationQuaternion = null;\n particle.scaling.x = 1.0;\n particle.scaling.y = 1.0;\n particle.scaling.z = 1.0;\n particle.uvs.x = 0.0;\n particle.uvs.y = 0.0;\n particle.uvs.z = 1.0;\n particle.uvs.w = 1.0;\n particle.pivot.x = 0.0;\n particle.pivot.y = 0.0;\n particle.pivot.z = 0.0;\n particle.translateFromPivot = false;\n particle.parentId = null;\n };\n /**\n * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.\n * @returns the SPS.\n */\n SolidParticleSystem.prototype.rebuildMesh = function () {\n for (var p = 0; p < this.particles.length; p++) {\n this._rebuildParticle(this.particles[p]);\n }\n this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);\n return this;\n };\n /**\n * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.\n * This method calls `updateParticle()` for each particle of the SPS.\n * For an animated SPS, it is usually called within the render loop.\n * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_\n * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_\n * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_\n * @returns the SPS.\n */\n SolidParticleSystem.prototype.setParticles = function (start, end, update) {\n if (start === void 0) { start = 0; }\n if (end === void 0) { end = this.nbParticles - 1; }\n if (update === void 0) { update = true; }\n if (!this._updatable) {\n return this;\n }\n // custom beforeUpdate\n this.beforeUpdateParticles(start, end, update);\n this._cam_axisX.x = 1.0;\n this._cam_axisX.y = 0.0;\n this._cam_axisX.z = 0.0;\n this._cam_axisY.x = 0.0;\n this._cam_axisY.y = 1.0;\n this._cam_axisY.z = 0.0;\n this._cam_axisZ.x = 0.0;\n this._cam_axisZ.y = 0.0;\n this._cam_axisZ.z = 1.0;\n // cases when the World Matrix is to be computed first\n if (this.billboard || this._depthSort) {\n this.mesh.computeWorldMatrix(true);\n this.mesh._worldMatrix.invertToRef(this._invertMatrix);\n }\n // if the particles will always face the camera\n if (this.billboard) {\n // compute the camera position and un-rotate it by the current mesh rotation\n this._camera.getDirectionToRef(this._axisZ, this._camDir);\n BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);\n this._cam_axisZ.normalize();\n // same for camera up vector extracted from the cam view matrix\n var view = this._camera.getViewMatrix(true);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);\n BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);\n this._cam_axisY.normalize();\n this._cam_axisX.normalize();\n }\n // if depthSort, compute the camera global position in the mesh local system\n if (this._depthSort) {\n BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera\n }\n BABYLON.Matrix.IdentityToRef(this._rotMatrix);\n var idx = 0; // current position index in the global array positions32\n var index = 0; // position start index in the global array positions32 of the current particle\n var colidx = 0; // current color index in the global array colors32\n var colorIndex = 0; // color start index in the global array colors32 of the current particle\n var uvidx = 0; // current uv index in the global array uvs32\n var uvIndex = 0; // uv start index in the global array uvs32 of the current particle\n var pt = 0; // current index in the particle model shape\n if (this.mesh.isFacetDataEnabled) {\n this._computeBoundingBox = true;\n }\n end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;\n if (this._computeBoundingBox) {\n if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch\n BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);\n BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);\n }\n else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.\n if (this.mesh._boundingInfo) {\n this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);\n this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);\n }\n }\n }\n // particle loop\n index = this.particles[start]._pos;\n var vpos = (index / 3) | 0;\n colorIndex = vpos * 4;\n uvIndex = vpos * 2;\n for (var p = start; p <= end; p++) {\n this._particle = this.particles[p];\n this._shape = this._particle._model._shape;\n this._shapeUV = this._particle._model._shapeUV;\n // call to custom user function to update the particle properties\n this.updateParticle(this._particle);\n // camera-particle distance for depth sorting\n if (this._depthSort && this._depthSortParticles) {\n var dsp = this.depthSortedParticles[p];\n dsp.ind = this._particle._ind;\n dsp.indicesLength = this._particle._model._indicesLength;\n dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);\n }\n // skip the computations for inactive or already invisible particles\n if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {\n // increment indexes for the next particle\n pt = this._shape.length;\n index += pt * 3;\n colorIndex += pt * 4;\n uvIndex += pt * 2;\n continue;\n }\n if (this._particle.isVisible) {\n this._particle._stillInvisible = false; // un-mark permanent invisibility\n this._particleHasParent = (this._particle.parentId !== null);\n this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;\n this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;\n this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;\n // particle rotation matrix\n if (this.billboard) {\n this._particle.rotation.x = 0.0;\n this._particle.rotation.y = 0.0;\n }\n if (this._computeParticleRotation || this.billboard) {\n if (this._particle.rotationQuaternion) {\n this._quaternion.copyFrom(this._particle.rotationQuaternion);\n }\n else {\n this._yaw = this._particle.rotation.y;\n this._pitch = this._particle.rotation.x;\n this._roll = this._particle.rotation.z;\n this._quaternionRotationYPR();\n }\n this._quaternionToRotationMatrix();\n }\n if (this._particleHasParent) {\n this._parent = this.particles[this._particle.parentId];\n this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];\n this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];\n this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];\n this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;\n this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;\n this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;\n if (this._computeParticleRotation || this.billboard) {\n this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];\n this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];\n this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];\n this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];\n this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];\n this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];\n this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];\n this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];\n this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];\n }\n }\n else {\n this._particle._globalPosition.x = this._particle.position.x;\n this._particle._globalPosition.y = this._particle.position.y;\n this._particle._globalPosition.z = this._particle.position.z;\n if (this._computeParticleRotation || this.billboard) {\n this._particle._rotationMatrix[0] = this._rotMatrix.m[0];\n this._particle._rotationMatrix[1] = this._rotMatrix.m[1];\n this._particle._rotationMatrix[2] = this._rotMatrix.m[2];\n this._particle._rotationMatrix[3] = this._rotMatrix.m[4];\n this._particle._rotationMatrix[4] = this._rotMatrix.m[5];\n this._particle._rotationMatrix[5] = this._rotMatrix.m[6];\n this._particle._rotationMatrix[6] = this._rotMatrix.m[8];\n this._particle._rotationMatrix[7] = this._rotMatrix.m[9];\n this._particle._rotationMatrix[8] = this._rotMatrix.m[10];\n }\n }\n if (this._particle.translateFromPivot) {\n this._pivotBackTranslation.x = 0.0;\n this._pivotBackTranslation.y = 0.0;\n this._pivotBackTranslation.z = 0.0;\n }\n else {\n this._pivotBackTranslation.x = this._scaledPivot.x;\n this._pivotBackTranslation.y = this._scaledPivot.y;\n this._pivotBackTranslation.z = this._scaledPivot.z;\n }\n // particle vertex loop\n for (pt = 0; pt < this._shape.length; pt++) {\n idx = index + pt * 3;\n colidx = colorIndex + pt * 4;\n uvidx = uvIndex + pt * 2;\n this._vertex.x = this._shape[pt].x;\n this._vertex.y = this._shape[pt].y;\n this._vertex.z = this._shape[pt].z;\n if (this._computeParticleVertex) {\n this.updateParticleVertex(this._particle, this._vertex, pt);\n }\n // positions\n this._vertex.x *= this._particle.scaling.x;\n this._vertex.y *= this._particle.scaling.y;\n this._vertex.z *= this._particle.scaling.z;\n this._vertex.x -= this._scaledPivot.x;\n this._vertex.y -= this._scaledPivot.y;\n this._vertex.z -= this._scaledPivot.z;\n this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];\n this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];\n this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];\n this._rotated.x += this._pivotBackTranslation.x;\n this._rotated.y += this._pivotBackTranslation.y;\n this._rotated.z += this._pivotBackTranslation.z;\n this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;\n this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;\n this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;\n if (this._computeBoundingBox) {\n if (this._positions32[idx] < this._minimum.x) {\n this._minimum.x = this._positions32[idx];\n }\n if (this._positions32[idx] > this._maximum.x) {\n this._maximum.x = this._positions32[idx];\n }\n if (this._positions32[idx + 1] < this._minimum.y) {\n this._minimum.y = this._positions32[idx + 1];\n }\n if (this._positions32[idx + 1] > this._maximum.y) {\n this._maximum.y = this._positions32[idx + 1];\n }\n if (this._positions32[idx + 2] < this._minimum.z) {\n this._minimum.z = this._positions32[idx + 2];\n }\n if (this._positions32[idx + 2] > this._maximum.z) {\n this._maximum.z = this._positions32[idx + 2];\n }\n }\n // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()\n if (!this._computeParticleVertex) {\n this._normal.x = this._fixedNormal32[idx];\n this._normal.y = this._fixedNormal32[idx + 1];\n this._normal.z = this._fixedNormal32[idx + 2];\n this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];\n this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];\n this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];\n this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;\n this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;\n this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;\n }\n if (this._computeParticleColor && this._particle.color) {\n this._colors32[colidx] = this._particle.color.r;\n this._colors32[colidx + 1] = this._particle.color.g;\n this._colors32[colidx + 2] = this._particle.color.b;\n this._colors32[colidx + 3] = this._particle.color.a;\n }\n if (this._computeParticleTexture) {\n this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;\n this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;\n }\n }\n }\n // particle just set invisible : scaled to zero and positioned at the origin\n else {\n this._particle._stillInvisible = true; // mark the particle as invisible\n for (pt = 0; pt < this._shape.length; pt++) {\n idx = index + pt * 3;\n colidx = colorIndex + pt * 4;\n uvidx = uvIndex + pt * 2;\n this._positions32[idx] = 0.0;\n this._positions32[idx + 1] = 0.0;\n this._positions32[idx + 2] = 0.0;\n this._normals32[idx] = 0.0;\n this._normals32[idx + 1] = 0.0;\n this._normals32[idx + 2] = 0.0;\n if (this._computeParticleColor && this._particle.color) {\n this._colors32[colidx] = this._particle.color.r;\n this._colors32[colidx + 1] = this._particle.color.g;\n this._colors32[colidx + 2] = this._particle.color.b;\n this._colors32[colidx + 3] = this._particle.color.a;\n }\n if (this._computeParticleTexture) {\n this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;\n this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;\n }\n }\n }\n // if the particle intersections must be computed : update the bbInfo\n if (this._particlesIntersect) {\n var bInfo = this._particle._boundingInfo;\n var bBox = bInfo.boundingBox;\n var bSphere = bInfo.boundingSphere;\n if (!this._bSphereOnly) {\n // place, scale and rotate the particle bbox within the SPS local system, then update it\n for (var b = 0; b < bBox.vectors.length; b++) {\n this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;\n this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;\n this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;\n this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];\n this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];\n this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];\n bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;\n bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;\n bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;\n }\n bBox._update(this.mesh._worldMatrix);\n }\n // place and scale the particle bouding sphere in the SPS local system, then update it\n this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;\n this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;\n this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;\n this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;\n this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;\n this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;\n bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;\n bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;\n bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;\n bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));\n bSphere._update(this.mesh._worldMatrix);\n }\n // increment indexes for the next particle\n index = idx + 3;\n colorIndex = colidx + 4;\n uvIndex = uvidx + 2;\n }\n // if the VBO must be updated\n if (update) {\n if (this._computeParticleColor) {\n this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);\n }\n if (this._computeParticleTexture) {\n this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);\n }\n this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);\n if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {\n if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {\n // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]\n var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;\n BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);\n for (var i = 0; i < this._normals32.length; i++) {\n this._fixedNormal32[i] = this._normals32[i];\n }\n }\n if (!this.mesh.areNormalsFrozen) {\n this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);\n }\n }\n if (this._depthSort && this._depthSortParticles) {\n this.depthSortedParticles.sort(this._depthSortFunction);\n var dspl = this.depthSortedParticles.length;\n var sorted = 0;\n var lind = 0;\n var sind = 0;\n var sid = 0;\n for (sorted = 0; sorted < dspl; sorted++) {\n lind = this.depthSortedParticles[sorted].indicesLength;\n sind = this.depthSortedParticles[sorted].ind;\n for (var i = 0; i < lind; i++) {\n this._indices32[sid] = this._indices[sind + i];\n sid++;\n }\n }\n this.mesh.updateIndices(this._indices32);\n }\n }\n if (this._computeBoundingBox) {\n this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);\n this.mesh._boundingInfo.update(this.mesh._worldMatrix);\n }\n this.afterUpdateParticles(start, end, update);\n return this;\n };\n SolidParticleSystem.prototype._quaternionRotationYPR = function () {\n this._halfroll = this._roll * 0.5;\n this._halfpitch = this._pitch * 0.5;\n this._halfyaw = this._yaw * 0.5;\n this._sinRoll = Math.sin(this._halfroll);\n this._cosRoll = Math.cos(this._halfroll);\n this._sinPitch = Math.sin(this._halfpitch);\n this._cosPitch = Math.cos(this._halfpitch);\n this._sinYaw = Math.sin(this._halfyaw);\n this._cosYaw = Math.cos(this._halfyaw);\n this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;\n this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;\n this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;\n this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;\n };\n SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {\n this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));\n this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);\n this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);\n this._rotMatrix.m[3] = 0;\n this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);\n this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));\n this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);\n this._rotMatrix.m[7] = 0;\n this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);\n this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);\n this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));\n this._rotMatrix.m[11] = 0;\n this._rotMatrix.m[12] = 0;\n this._rotMatrix.m[13] = 0;\n this._rotMatrix.m[14] = 0;\n this._rotMatrix.m[15] = 1.0;\n };\n /**\n * Disposes the SPS.\n */\n SolidParticleSystem.prototype.dispose = function () {\n this.mesh.dispose();\n this.vars = null;\n // drop references to internal big arrays for the GC\n this._positions = null;\n this._indices = null;\n this._normals = null;\n this._uvs = null;\n this._colors = null;\n this._indices32 = null;\n this._positions32 = null;\n this._normals32 = null;\n this._fixedNormal32 = null;\n this._uvs32 = null;\n this._colors32 = null;\n this.pickedParticles = null;\n };\n /**\n * Visibilty helper : Recomputes the visible size according to the mesh bounding box\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility\n * @returns the SPS.\n */\n SolidParticleSystem.prototype.refreshVisibleSize = function () {\n if (!this._isVisibilityBoxLocked) {\n this.mesh.refreshBoundingInfo();\n }\n return this;\n };\n /**\n * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.\n * @param size the size (float) of the visibility box\n * note : this doesn't lock the SPS mesh bounding box.\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility\n */\n SolidParticleSystem.prototype.setVisibilityBox = function (size) {\n var vis = size / 2;\n this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));\n };\n Object.defineProperty(SolidParticleSystem.prototype, \"isAlwaysVisible\", {\n /**\n * Gets whether the SPS as always visible or not\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility\n */\n get: function () {\n return this._alwaysVisible;\n },\n /**\n * Sets the SPS as always visible or not\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility\n */\n set: function (val) {\n this._alwaysVisible = val;\n this.mesh.alwaysSelectAsActiveMesh = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"isVisibilityBoxLocked\", {\n /**\n * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility\n */\n get: function () {\n return this._isVisibilityBoxLocked;\n },\n /**\n * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility\n */\n set: function (val) {\n this._isVisibilityBoxLocked = val;\n var boundingInfo = this.mesh.getBoundingInfo();\n boundingInfo.isLocked = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"computeParticleRotation\", {\n /**\n * Gets if `setParticles()` computes the particle rotations or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.\n */\n get: function () {\n return this._computeParticleRotation;\n },\n /**\n * Tells to `setParticles()` to compute the particle rotations or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.\n */\n set: function (val) {\n this._computeParticleRotation = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"computeParticleColor\", {\n /**\n * Gets if `setParticles()` computes the particle colors or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.\n */\n get: function () {\n return this._computeParticleColor;\n },\n /**\n * Tells to `setParticles()` to compute the particle colors or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.\n */\n set: function (val) {\n this._computeParticleColor = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"computeParticleTexture\", {\n /**\n * Gets if `setParticles()` computes the particle textures or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.\n */\n get: function () {\n return this._computeParticleTexture;\n },\n set: function (val) {\n this._computeParticleTexture = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"computeParticleVertex\", {\n /**\n * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.\n * Default value : false. The SPS is faster when it's set to false.\n * Note : the particle custom vertex positions aren't stored values.\n */\n get: function () {\n return this._computeParticleVertex;\n },\n /**\n * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.\n * Default value : false. The SPS is faster when it's set to false.\n * Note : the particle custom vertex positions aren't stored values.\n */\n set: function (val) {\n this._computeParticleVertex = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"computeBoundingBox\", {\n /**\n * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.\n */\n get: function () {\n return this._computeBoundingBox;\n },\n /**\n * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.\n */\n set: function (val) {\n this._computeBoundingBox = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"depthSortParticles\", {\n /**\n * Gets if `setParticles()` sorts or not the distance between each particle and the camera.\n * Skipped when `enableDepthSort` is set to `false` (default) at construction time.\n * Default : `true`\n */\n get: function () {\n return this._depthSortParticles;\n },\n /**\n * Tells to `setParticles()` to sort or not the distance between each particle and the camera.\n * Skipped when `enableDepthSort` is set to `false` (default) at construction time.\n * Default : `true`\n */\n set: function (val) {\n this._depthSortParticles = val;\n },\n enumerable: true,\n configurable: true\n });\n // =======================================================================\n // Particle behavior logic\n // these following methods may be overwritten by the user to fit his needs \n /**\n * This function does nothing. It may be overwritten to set all the particle first values.\n * The SPS doesn't call this function, you may have to call it by your own.\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management\n */\n SolidParticleSystem.prototype.initParticles = function () {\n };\n /**\n * This function does nothing. It may be overwritten to recycle a particle.\n * The SPS doesn't call this function, you may have to call it by your own.\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management\n * @param particle The particle to recycle\n * @returns the recycled particle\n */\n SolidParticleSystem.prototype.recycleParticle = function (particle) {\n return particle;\n };\n /**\n * Updates a particle : this function should be overwritten by the user.\n * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management\n * @example : just set a particle position or velocity and recycle conditions\n * @param particle The particle to update\n * @returns the updated particle\n */\n SolidParticleSystem.prototype.updateParticle = function (particle) {\n return particle;\n };\n /**\n * Updates a vertex of a particle : it can be overwritten by the user.\n * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.\n * @param particle the current particle\n * @param vertex the current index of the current particle\n * @param pt the index of the current vertex in the particle shape\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape\n * @example : just set a vertex particle position\n * @returns the updated vertex\n */\n SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {\n return vertex;\n };\n /**\n * This will be called before any other treatment by `setParticles()` and will be passed three parameters.\n * This does nothing and may be overwritten by the user.\n * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param update the boolean update value actually passed to setParticles()\n */\n SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {\n };\n /**\n * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.\n * This will be passed three parameters.\n * This does nothing and may be overwritten by the user.\n * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param update the boolean update value actually passed to setParticles()\n */\n SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {\n };\n return SolidParticleSystem;\n }());\n BABYLON.SolidParticleSystem = SolidParticleSystem;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.solidParticleSystem.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class containing static functions to help procedurally build meshes\n */\n var MeshBuilder = /** @class */ (function () {\n function MeshBuilder() {\n }\n MeshBuilder.updateSideOrientation = function (orientation) {\n if (orientation == BABYLON.Mesh.DOUBLESIDE) {\n return BABYLON.Mesh.DOUBLESIDE;\n }\n if (orientation === undefined || orientation === null) {\n return BABYLON.Mesh.FRONTSIDE;\n }\n return orientation;\n };\n /**\n * Creates a box mesh\n * * The parameter `size` sets the size (float) of each box side (default 1)\n * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)\n * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements)\n * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the box mesh\n */\n MeshBuilder.CreateBox = function (name, options, scene) {\n if (scene === void 0) { scene = null; }\n var box = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n box._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateBox(options);\n vertexData.applyToMesh(box, options.updatable);\n return box;\n };\n /**\n * Creates a sphere mesh\n * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)\n * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)\n * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)\n * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio\n * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude)\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the sphere mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere\n */\n MeshBuilder.CreateSphere = function (name, options, scene) {\n var sphere = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n sphere._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateSphere(options);\n vertexData.applyToMesh(sphere, options.updatable);\n return sphere;\n };\n /**\n * Creates a plane polygonal mesh. By default, this is a disc\n * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)\n * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc\n * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the plane polygonal mesh\n * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon\n */\n MeshBuilder.CreateDisc = function (name, options, scene) {\n if (scene === void 0) { scene = null; }\n var disc = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n disc._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateDisc(options);\n vertexData.applyToMesh(disc, options.updatable);\n return disc;\n };\n /**\n * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided\n * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)\n * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`)\n * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size\n * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the icosahedron mesh\n * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere\n */\n MeshBuilder.CreateIcoSphere = function (name, options, scene) {\n var sphere = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n sphere._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateIcoSphere(options);\n vertexData.applyToMesh(sphere, options.updatable);\n return sphere;\n };\n ;\n /**\n * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters\n * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry\n * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array\n * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array\n * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path\n * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11\n * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones\n * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values\n * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry\n * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the ribbon mesh\n * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial\n * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes\n */\n MeshBuilder.CreateRibbon = function (name, options, scene) {\n if (scene === void 0) { scene = null; }\n var pathArray = options.pathArray;\n var closeArray = options.closeArray;\n var closePath = options.closePath;\n var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n var instance = options.instance;\n var updatable = options.updatable;\n if (instance) { // existing ribbon instance update\n // positionFunction : ribbon case\n // only pathArray and sideOrientation parameters are taken into account for positions update\n BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum\n BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);\n var positionFunction = function (positions) {\n var minlg = pathArray[0].length;\n var i = 0;\n var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;\n for (var si = 1; si <= ns; si++) {\n for (var p = 0; p < pathArray.length; p++) {\n var path = pathArray[p];\n var l = path.length;\n minlg = (minlg < l) ? minlg : l;\n var j = 0;\n while (j < minlg) {\n positions[i] = path[j].x;\n positions[i + 1] = path[j].y;\n positions[i + 2] = path[j].z;\n if (path[j].x < BABYLON.Tmp.Vector3[0].x) {\n BABYLON.Tmp.Vector3[0].x = path[j].x;\n }\n if (path[j].x > BABYLON.Tmp.Vector3[1].x) {\n BABYLON.Tmp.Vector3[1].x = path[j].x;\n }\n if (path[j].y < BABYLON.Tmp.Vector3[0].y) {\n BABYLON.Tmp.Vector3[0].y = path[j].y;\n }\n if (path[j].y > BABYLON.Tmp.Vector3[1].y) {\n BABYLON.Tmp.Vector3[1].y = path[j].y;\n }\n if (path[j].z < BABYLON.Tmp.Vector3[0].z) {\n BABYLON.Tmp.Vector3[0].z = path[j].z;\n }\n if (path[j].z > BABYLON.Tmp.Vector3[1].z) {\n BABYLON.Tmp.Vector3[1].z = path[j].z;\n }\n j++;\n i += 3;\n }\n if (instance._closePath) {\n positions[i] = path[0].x;\n positions[i + 1] = path[0].y;\n positions[i + 2] = path[0].z;\n i += 3;\n }\n }\n }\n };\n var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n positionFunction(positions);\n instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);\n instance._boundingInfo.update(instance._worldMatrix);\n instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);\n if (options.colors) {\n var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);\n for (var c = 0; c < options.colors.length; c++) {\n colors[c * 4] = options.colors[c].r;\n colors[c * 4 + 1] = options.colors[c].g;\n colors[c * 4 + 2] = options.colors[c].b;\n colors[c * 4 + 3] = options.colors[c].a;\n }\n instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);\n }\n if (options.uvs) {\n var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);\n for (var i = 0; i < options.uvs.length; i++) {\n uvs[i * 2] = options.uvs[i].x;\n uvs[i * 2 + 1] = options.uvs[i].y;\n }\n instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);\n }\n if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {\n var indices = instance.getIndices();\n var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;\n BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);\n if (instance._closePath) {\n var indexFirst = 0;\n var indexLast = 0;\n for (var p = 0; p < pathArray.length; p++) {\n indexFirst = instance._idx[p] * 3;\n if (p + 1 < pathArray.length) {\n indexLast = (instance._idx[p + 1] - 1) * 3;\n }\n else {\n indexLast = normals.length - 3;\n }\n normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;\n normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;\n normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;\n normals[indexLast] = normals[indexFirst];\n normals[indexLast + 1] = normals[indexFirst + 1];\n normals[indexLast + 2] = normals[indexFirst + 2];\n }\n }\n if (!(instance.areNormalsFrozen)) {\n instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);\n }\n }\n return instance;\n }\n else { // new ribbon creation\n var ribbon = new BABYLON.Mesh(name, scene);\n ribbon._originalBuilderSideOrientation = sideOrientation;\n var vertexData = BABYLON.VertexData.CreateRibbon(options);\n if (closePath) {\n ribbon._idx = vertexData._idx;\n }\n ribbon._closePath = closePath;\n ribbon._closeArray = closeArray;\n vertexData.applyToMesh(ribbon, updatable);\n return ribbon;\n }\n };\n /**\n * Creates a cylinder or a cone mesh\n * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).\n * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).\n * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter \"diameterBottom\" can't be zero.\n * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.\n * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).\n * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.\n * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.\n * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.\n * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).\n * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3\n * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7\n * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17\n * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.\n * * If `enclose` is false, a ring surface is one element.\n * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.\n * * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the cylinder mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone\n */\n MeshBuilder.CreateCylinder = function (name, options, scene) {\n var cylinder = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n cylinder._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateCylinder(options);\n vertexData.applyToMesh(cylinder, options.updatable);\n return cylinder;\n };\n /**\n * Creates a torus mesh\n * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)\n * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)\n * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the torus mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus\n */\n MeshBuilder.CreateTorus = function (name, options, scene) {\n var torus = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n torus._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateTorus(options);\n vertexData.applyToMesh(torus, options.updatable);\n return torus;\n };\n /**\n * Creates a torus knot mesh\n * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)\n * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)\n * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)\n * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the torus knot mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot\n */\n MeshBuilder.CreateTorusKnot = function (name, options, scene) {\n var torusKnot = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n torusKnot._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateTorusKnot(options);\n vertexData.applyToMesh(torusKnot, options.updatable);\n return torusKnot;\n };\n /**\n * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh\n * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter\n * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function\n * * The parameter `lines` is an array of lines, each line being an array of successive Vector3\n * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter\n * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point\n * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)\n * * Updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines\n * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system\n * @param name defines the name of the new line system\n * @param options defines the options used to create the line system\n * @param scene defines the hosting scene\n * @returns a new line system mesh\n */\n MeshBuilder.CreateLineSystem = function (name, options, scene) {\n var instance = options.instance;\n var lines = options.lines;\n var colors = options.colors;\n if (instance) { // lines update\n var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var vertexColor;\n var lineColors;\n if (colors) {\n vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);\n }\n var i = 0;\n var c = 0;\n for (var l = 0; l < lines.length; l++) {\n var points = lines[l];\n for (var p = 0; p < points.length; p++) {\n positions[i] = points[p].x;\n positions[i + 1] = points[p].y;\n positions[i + 2] = points[p].z;\n if (colors && vertexColor) {\n lineColors = colors[l];\n vertexColor[c] = lineColors[p].r;\n vertexColor[c + 1] = lineColors[p].g;\n vertexColor[c + 2] = lineColors[p].b;\n vertexColor[c + 3] = lineColors[p].a;\n c += 4;\n }\n i += 3;\n }\n }\n instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);\n if (colors && vertexColor) {\n instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);\n }\n return instance;\n }\n // line system creation\n var useVertexColor = (colors) ? true : false;\n var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);\n var vertexData = BABYLON.VertexData.CreateLineSystem(options);\n vertexData.applyToMesh(lineSystem, options.updatable);\n return lineSystem;\n };\n /**\n * Creates a line mesh\n * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter\n * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function\n * * The parameter `points` is an array successive Vector3\n * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines\n * * The optional parameter `colors` is an array of successive Color4, one per line point\n * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)\n * * When updating an instance, remember that only point positions can change, not the number of points\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines\n * @param name defines the name of the new line system\n * @param options defines the options used to create the line system\n * @param scene defines the hosting scene\n * @returns a new line mesh\n */\n MeshBuilder.CreateLines = function (name, options, scene) {\n if (scene === void 0) { scene = null; }\n var colors = (options.colors) ? [options.colors] : null;\n var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);\n return lines;\n };\n /**\n * Creates a dashed line mesh\n * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter\n * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function\n * * The parameter `points` is an array successive Vector3\n * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)\n * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)\n * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)\n * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines\n * * When updating an instance, remember that only point positions can change, not the number of points\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the dashed line mesh\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines\n */\n MeshBuilder.CreateDashedLines = function (name, options, scene) {\n if (scene === void 0) { scene = null; }\n var points = options.points;\n var instance = options.instance;\n var gapSize = options.gapSize || 1;\n var dashSize = options.dashSize || 3;\n if (instance) { // dashed lines update\n var positionFunction = function (positions) {\n var curvect = BABYLON.Vector3.Zero();\n var nbSeg = positions.length / 6;\n var lg = 0;\n var nb = 0;\n var shft = 0;\n var dashshft = 0;\n var curshft = 0;\n var p = 0;\n var i = 0;\n var j = 0;\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n lg += curvect.length();\n }\n shft = lg / nbSeg;\n dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n nb = Math.floor(curvect.length() / shft);\n curvect.normalize();\n j = 0;\n while (j < nb && p < positions.length) {\n curshft = shft * j;\n positions[p] = points[i].x + curshft * curvect.x;\n positions[p + 1] = points[i].y + curshft * curvect.y;\n positions[p + 2] = points[i].z + curshft * curvect.z;\n positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;\n positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;\n positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;\n p += 6;\n j++;\n }\n }\n while (p < positions.length) {\n positions[p] = points[i].x;\n positions[p + 1] = points[i].y;\n positions[p + 2] = points[i].z;\n p += 3;\n }\n };\n instance.updateMeshPositions(positionFunction, false);\n return instance;\n }\n // dashed lines creation\n var dashedLines = new BABYLON.LinesMesh(name, scene);\n var vertexData = BABYLON.VertexData.CreateDashedLines(options);\n vertexData.applyToMesh(dashedLines, options.updatable);\n dashedLines.dashSize = dashSize;\n dashedLines.gapSize = gapSize;\n return dashedLines;\n };\n /**\n * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.\n * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.\n * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.\n * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.\n * * The parameter `scale` (float, default 1) is the value to scale the shape.\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape\n * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the extruded shape mesh\n * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes\n */\n MeshBuilder.ExtrudeShape = function (name, options, scene) {\n if (scene === void 0) { scene = null; }\n var path = options.path;\n var shape = options.shape;\n var scale = options.scale || 1;\n var rotation = options.rotation || 0;\n var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;\n var updatable = options.updatable;\n var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n var instance = options.instance || null;\n var invertUV = options.invertUV || false;\n return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null);\n };\n /**\n * Creates an custom extruded shape mesh.\n * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.\n * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.\n * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.\n * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path\n * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.\n * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path\n * * It must returns a float value that will be the scale value applied to the shape on each path point\n * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`\n * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape\n * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the custom extruded shape mesh\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes\n * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes\n */\n MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {\n var path = options.path;\n var shape = options.shape;\n var scaleFunction = options.scaleFunction || (function () { return 1; });\n var rotationFunction = options.rotationFunction || (function () { return 0; });\n var ribbonCloseArray = options.ribbonCloseArray || false;\n var ribbonClosePath = options.ribbonClosePath || false;\n var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;\n var updatable = options.updatable;\n var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n var instance = options.instance;\n var invertUV = options.invertUV || false;\n return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null);\n };\n /**\n * Creates lathe mesh.\n * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe\n * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero\n * * The parameter `radius` (positive float, default 1) is the radius value of the lathe\n * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe\n * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides\n * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape\n * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter \"arc\"\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the lathe mesh\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe\n */\n MeshBuilder.CreateLathe = function (name, options, scene) {\n var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;\n var closed = (options.closed === undefined) ? true : options.closed;\n var shape = options.shape;\n var radius = options.radius || 1;\n var tessellation = options.tessellation || 64;\n var clip = options.clip || 0;\n var updatable = options.updatable;\n var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n var cap = options.cap || BABYLON.Mesh.NO_CAP;\n var pi2 = Math.PI * 2;\n var paths = new Array();\n var invertUV = options.invertUV || false;\n var i = 0;\n var p = 0;\n var step = pi2 / tessellation * arc;\n var rotated;\n var path = new Array();\n for (i = 0; i <= tessellation - clip; i++) {\n var path = [];\n if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {\n path.push(new BABYLON.Vector3(0, shape[0].y, 0));\n path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));\n }\n for (p = 0; p < shape.length; p++) {\n rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);\n path.push(rotated);\n }\n if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {\n path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));\n path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));\n }\n paths.push(path);\n }\n // lathe ribbon\n var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);\n return lathe;\n };\n /**\n * Creates a plane mesh\n * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)\n * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)\n * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the plane mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane\n */\n MeshBuilder.CreatePlane = function (name, options, scene) {\n var plane = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n plane._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreatePlane(options);\n vertexData.applyToMesh(plane, options.updatable);\n if (options.sourcePlane) {\n plane.translate(options.sourcePlane.normal, options.sourcePlane.d);\n var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));\n var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);\n plane.rotate(vectorProduct, product);\n }\n return plane;\n };\n /**\n * Creates a ground mesh\n * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground\n * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the ground mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane\n */\n MeshBuilder.CreateGround = function (name, options, scene) {\n var ground = new BABYLON.GroundMesh(name, scene);\n ground._setReady(false);\n ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;\n ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;\n ground._width = options.width || 1;\n ground._height = options.height || 1;\n ground._maxX = ground._width / 2;\n ground._maxZ = ground._height / 2;\n ground._minX = -ground._maxX;\n ground._minZ = -ground._maxZ;\n var vertexData = BABYLON.VertexData.CreateGround(options);\n vertexData.applyToMesh(ground, options.updatable);\n ground._setReady(true);\n return ground;\n };\n /**\n * Creates a tiled ground mesh\n * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates\n * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates\n * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile\n * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the tiled ground mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground\n */\n MeshBuilder.CreateTiledGround = function (name, options, scene) {\n var tiledGround = new BABYLON.Mesh(name, scene);\n var vertexData = BABYLON.VertexData.CreateTiledGround(options);\n vertexData.applyToMesh(tiledGround, options.updatable);\n return tiledGround;\n };\n /**\n * Creates a ground mesh from a height map\n * * The parameter `url` sets the URL of the height map image resource.\n * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.\n * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.\n * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.\n * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.\n * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.\n * * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param url defines the url to the height map\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the ground mesh\n * @see http://doc.babylonjs.com/babylon101/height_map\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map\n */\n MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {\n var width = options.width || 10.0;\n var height = options.height || 10.0;\n var subdivisions = options.subdivisions || 1 | 0;\n var minHeight = options.minHeight || 0.0;\n var maxHeight = options.maxHeight || 1.0;\n var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);\n var updatable = options.updatable;\n var onReady = options.onReady;\n var ground = new BABYLON.GroundMesh(name, scene);\n ground._subdivisionsX = subdivisions;\n ground._subdivisionsY = subdivisions;\n ground._width = width;\n ground._height = height;\n ground._maxX = ground._width / 2.0;\n ground._maxZ = ground._height / 2.0;\n ground._minX = -ground._maxX;\n ground._minZ = -ground._maxZ;\n ground._setReady(false);\n var onload = function (img) {\n // Getting height map data\n var canvas = document.createElement(\"canvas\");\n var context = canvas.getContext(\"2d\");\n if (!context) {\n throw new Error(\"Unable to get 2d context for CreateGroundFromHeightMap\");\n }\n if (scene.isDisposed) {\n return;\n }\n var bufferWidth = img.width;\n var bufferHeight = img.height;\n canvas.width = bufferWidth;\n canvas.height = bufferHeight;\n context.drawImage(img, 0, 0);\n // Create VertexData from map data\n // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949\n var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;\n var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({\n width: width, height: height,\n subdivisions: subdivisions,\n minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,\n buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight\n });\n vertexData.applyToMesh(ground, updatable);\n //execute ready callback, if set\n if (onReady) {\n onReady(ground);\n }\n ground._setReady(true);\n };\n BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);\n return ground;\n };\n /**\n * Creates a polygon mesh\n * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh\n * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors\n * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4)\n * * Remember you can only change the shape positions, not their number when updating a polygon\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the polygon mesh\n */\n MeshBuilder.CreatePolygon = function (name, options, scene) {\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n var shape = options.shape;\n var holes = options.holes || [];\n var depth = options.depth || 0;\n var contours = [];\n var hole = [];\n for (var i = 0; i < shape.length; i++) {\n contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);\n }\n var epsilon = 0.00000001;\n if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {\n contours.pop();\n }\n var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);\n for (var hNb = 0; hNb < holes.length; hNb++) {\n hole = [];\n for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {\n hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));\n }\n polygonTriangulation.addHole(hole);\n }\n var polygon = polygonTriangulation.build(options.updatable, depth);\n polygon._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);\n vertexData.applyToMesh(polygon, options.updatable);\n return polygon;\n };\n ;\n /**\n * Creates an extruded polygon mesh, with depth in the Y direction.\n * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements)\n * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the polygon mesh\n */\n MeshBuilder.ExtrudePolygon = function (name, options, scene) {\n return MeshBuilder.CreatePolygon(name, options, scene);\n };\n ;\n /**\n * Creates a tube mesh.\n * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters\n * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube\n * * The parameter `radius` (positive float, default 1) sets the tube radius size\n * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface\n * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`\n * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)\n * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the tube mesh\n * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube\n */\n MeshBuilder.CreateTube = function (name, options, scene) {\n var path = options.path;\n var instance = options.instance;\n var radius = 1.0;\n if (instance) {\n radius = instance.radius;\n }\n if (options.radius !== undefined) {\n radius = options.radius;\n }\n ;\n var tessellation = options.tessellation || 64 | 0;\n var radiusFunction = options.radiusFunction || null;\n var cap = options.cap || BABYLON.Mesh.NO_CAP;\n var invertUV = options.invertUV || false;\n var updatable = options.updatable;\n var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;\n // tube geometry\n var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {\n var tangents = path3D.getTangents();\n var normals = path3D.getNormals();\n var distances = path3D.getDistances();\n var pi2 = Math.PI * 2;\n var step = pi2 / tessellation * arc;\n var returnRadius = function () { return radius; };\n var radiusFunctionFinal = radiusFunction || returnRadius;\n var circlePath;\n var rad;\n var normal;\n var rotated;\n var rotationMatrix = BABYLON.Tmp.Matrix[0];\n var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;\n for (var i = 0; i < path.length; i++) {\n rad = radiusFunctionFinal(i, distances[i]); // current radius\n circlePath = Array(); // current circle array\n normal = normals[i]; // current normal\n for (var t = 0; t < tessellation; t++) {\n BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);\n rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();\n BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);\n rotated.scaleInPlace(rad).addInPlace(path[i]);\n circlePath[t] = rotated;\n }\n circlePaths[index] = circlePath;\n index++;\n }\n // cap\n var capPath = function (nbPoints, pathIndex) {\n var pointCap = Array();\n for (var i = 0; i < nbPoints; i++) {\n pointCap.push(path[pathIndex]);\n }\n return pointCap;\n };\n switch (cap) {\n case BABYLON.Mesh.NO_CAP:\n break;\n case BABYLON.Mesh.CAP_START:\n circlePaths[0] = capPath(tessellation, 0);\n circlePaths[1] = circlePaths[2].slice(0);\n break;\n case BABYLON.Mesh.CAP_END:\n circlePaths[index] = circlePaths[index - 1].slice(0);\n circlePaths[index + 1] = capPath(tessellation, path.length - 1);\n break;\n case BABYLON.Mesh.CAP_ALL:\n circlePaths[0] = capPath(tessellation, 0);\n circlePaths[1] = circlePaths[2].slice(0);\n circlePaths[index] = circlePaths[index - 1].slice(0);\n circlePaths[index + 1] = capPath(tessellation, path.length - 1);\n break;\n default:\n break;\n }\n return circlePaths;\n };\n var path3D;\n var pathArray;\n if (instance) { // tube update\n var arc = options.arc || instance.arc;\n path3D = (instance.path3D).update(path);\n pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);\n instance = MeshBuilder.CreateRibbon(\"\", { pathArray: pathArray, instance: instance });\n instance.path3D = path3D;\n instance.pathArray = pathArray;\n instance.arc = arc;\n instance.radius = radius;\n return instance;\n }\n // tube creation\n path3D = new BABYLON.Path3D(path);\n var newPathArray = new Array();\n cap = (cap < 0 || cap > 3) ? 0 : cap;\n pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);\n var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);\n tube.pathArray = pathArray;\n tube.path3D = path3D;\n tube.tessellation = tessellation;\n tube.cap = cap;\n tube.arc = options.arc;\n tube.radius = radius;\n return tube;\n };\n /**\n * Creates a polyhedron mesh\n * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type\n * * The parameter `size` (positive float, default 1) sets the polygon size\n * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)\n * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`\n * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron\n * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`)\n * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors\n * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the polyhedron mesh\n * @see http://doc.babylonjs.com/how_to/polyhedra_shapes\n */\n MeshBuilder.CreatePolyhedron = function (name, options, scene) {\n var polyhedron = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n polyhedron._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreatePolyhedron(options);\n vertexData.applyToMesh(polyhedron, options.updatable);\n return polyhedron;\n };\n /**\n * Creates a decal mesh.\n * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal\n * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates\n * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates\n * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling\n * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal\n * @param name defines the name of the mesh\n * @param sourceMesh defines the mesh where the decal must be applied\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the decal mesh\n * @see http://doc.babylonjs.com/how_to/decals\n */\n MeshBuilder.CreateDecal = function (name, sourceMesh, options) {\n var indices = sourceMesh.getIndices();\n var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var position = options.position || BABYLON.Vector3.Zero();\n var normal = options.normal || BABYLON.Vector3.Up();\n var size = options.size || BABYLON.Vector3.One();\n var angle = options.angle || 0;\n // Getting correct rotation\n if (!normal) {\n var target = new BABYLON.Vector3(0, 0, 1);\n var camera = sourceMesh.getScene().activeCamera;\n var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());\n normal = camera.globalPosition.subtract(cameraWorldTarget);\n }\n var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;\n var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);\n var pitch = Math.atan2(normal.y, len);\n // Matrix\n var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));\n var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);\n var meshWorldMatrix = sourceMesh.getWorldMatrix();\n var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);\n var vertexData = new BABYLON.VertexData();\n vertexData.indices = [];\n vertexData.positions = [];\n vertexData.normals = [];\n vertexData.uvs = [];\n var currentVertexDataIndex = 0;\n var extractDecalVector3 = function (indexId) {\n var result = new BABYLON.PositionNormalVertex();\n if (!indices || !positions || !normals) {\n return result;\n }\n var vertexId = indices[indexId];\n result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);\n // Send vector to decal local world\n result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);\n // Get normal\n result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);\n result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);\n return result;\n }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js\n var clip = function (vertices, axis) {\n if (vertices.length === 0) {\n return vertices;\n }\n var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));\n var clipVertices = function (v0, v1) {\n var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);\n return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));\n };\n var result = new Array();\n for (var index = 0; index < vertices.length; index += 3) {\n var v1Out;\n var v2Out;\n var v3Out;\n var total = 0;\n var nV1 = null;\n var nV2 = null;\n var nV3 = null;\n var nV4 = null;\n var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;\n var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;\n var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;\n v1Out = d1 > 0;\n v2Out = d2 > 0;\n v3Out = d3 > 0;\n total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);\n switch (total) {\n case 0:\n result.push(vertices[index]);\n result.push(vertices[index + 1]);\n result.push(vertices[index + 2]);\n break;\n case 1:\n if (v1Out) {\n nV1 = vertices[index + 1];\n nV2 = vertices[index + 2];\n nV3 = clipVertices(vertices[index], nV1);\n nV4 = clipVertices(vertices[index], nV2);\n }\n if (v2Out) {\n nV1 = vertices[index];\n nV2 = vertices[index + 2];\n nV3 = clipVertices(vertices[index + 1], nV1);\n nV4 = clipVertices(vertices[index + 1], nV2);\n result.push(nV3);\n result.push(nV2.clone());\n result.push(nV1.clone());\n result.push(nV2.clone());\n result.push(nV3.clone());\n result.push(nV4);\n break;\n }\n if (v3Out) {\n nV1 = vertices[index];\n nV2 = vertices[index + 1];\n nV3 = clipVertices(vertices[index + 2], nV1);\n nV4 = clipVertices(vertices[index + 2], nV2);\n }\n if (nV1 && nV2 && nV3 && nV4) {\n result.push(nV1.clone());\n result.push(nV2.clone());\n result.push(nV3);\n result.push(nV4);\n result.push(nV3.clone());\n result.push(nV2.clone());\n }\n break;\n case 2:\n if (!v1Out) {\n nV1 = vertices[index].clone();\n nV2 = clipVertices(nV1, vertices[index + 1]);\n nV3 = clipVertices(nV1, vertices[index + 2]);\n result.push(nV1);\n result.push(nV2);\n result.push(nV3);\n }\n if (!v2Out) {\n nV1 = vertices[index + 1].clone();\n nV2 = clipVertices(nV1, vertices[index + 2]);\n nV3 = clipVertices(nV1, vertices[index]);\n result.push(nV1);\n result.push(nV2);\n result.push(nV3);\n }\n if (!v3Out) {\n nV1 = vertices[index + 2].clone();\n nV2 = clipVertices(nV1, vertices[index]);\n nV3 = clipVertices(nV1, vertices[index + 1]);\n result.push(nV1);\n result.push(nV2);\n result.push(nV3);\n }\n break;\n case 3:\n break;\n }\n }\n return result;\n };\n for (var index = 0; index < indices.length; index += 3) {\n var faceVertices = new Array();\n faceVertices.push(extractDecalVector3(index));\n faceVertices.push(extractDecalVector3(index + 1));\n faceVertices.push(extractDecalVector3(index + 2));\n // Clip\n faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));\n faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));\n faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));\n faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));\n faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));\n faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));\n if (faceVertices.length === 0) {\n continue;\n }\n // Add UVs and get back to world\n for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {\n var vertex = faceVertices[vIndex];\n //TODO check for Int32Array | Uint32Array | Uint16Array\n vertexData.indices.push(currentVertexDataIndex);\n vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);\n vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);\n vertexData.uvs.push(0.5 + vertex.position.x / size.x);\n vertexData.uvs.push(0.5 + vertex.position.y / size.y);\n currentVertexDataIndex++;\n }\n }\n // Return mesh\n var decal = new BABYLON.Mesh(name, sourceMesh.getScene());\n vertexData.applyToMesh(decal);\n decal.position = position.clone();\n decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);\n return decal;\n };\n // Privates\n MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {\n // extrusion geometry\n var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {\n var tangents = path3D.getTangents();\n var normals = path3D.getNormals();\n var binormals = path3D.getBinormals();\n var distances = path3D.getDistances();\n var angle = 0;\n var returnScale = function () { return scale !== null ? scale : 1; };\n var returnRotation = function () { return rotation !== null ? rotation : 0; };\n var rotate = custom && rotateFunction ? rotateFunction : returnRotation;\n var scl = custom && scaleFunction ? scaleFunction : returnScale;\n var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;\n var rotationMatrix = BABYLON.Tmp.Matrix[0];\n for (var i = 0; i < curve.length; i++) {\n var shapePath = new Array();\n var angleStep = rotate(i, distances[i]);\n var scaleRatio = scl(i, distances[i]);\n for (var p = 0; p < shape.length; p++) {\n BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);\n var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));\n var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();\n BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);\n rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);\n shapePath[p] = rotated;\n }\n shapePaths[index] = shapePath;\n angle += angleStep;\n index++;\n }\n // cap\n var capPath = function (shapePath) {\n var pointCap = Array();\n var barycenter = BABYLON.Vector3.Zero();\n var i;\n for (i = 0; i < shapePath.length; i++) {\n barycenter.addInPlace(shapePath[i]);\n }\n barycenter.scaleInPlace(1.0 / shapePath.length);\n for (i = 0; i < shapePath.length; i++) {\n pointCap.push(barycenter);\n }\n return pointCap;\n };\n switch (cap) {\n case BABYLON.Mesh.NO_CAP:\n break;\n case BABYLON.Mesh.CAP_START:\n shapePaths[0] = capPath(shapePaths[2]);\n shapePaths[1] = shapePaths[2];\n break;\n case BABYLON.Mesh.CAP_END:\n shapePaths[index] = shapePaths[index - 1];\n shapePaths[index + 1] = capPath(shapePaths[index - 1]);\n break;\n case BABYLON.Mesh.CAP_ALL:\n shapePaths[0] = capPath(shapePaths[2]);\n shapePaths[1] = shapePaths[2];\n shapePaths[index] = shapePaths[index - 1];\n shapePaths[index + 1] = capPath(shapePaths[index - 1]);\n break;\n default:\n break;\n }\n return shapePaths;\n };\n var path3D;\n var pathArray;\n if (instance) { // instance update\n path3D = (instance.path3D).update(curve);\n pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);\n instance = BABYLON.Mesh.CreateRibbon(\"\", pathArray, false, false, 0, scene || undefined, false, 0, instance);\n return instance;\n }\n // extruded shape creation\n path3D = new BABYLON.Path3D(curve);\n var newShapePaths = new Array();\n cap = (cap < 0 || cap > 3) ? 0 : cap;\n pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);\n var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);\n extrudedGeneric.pathArray = pathArray;\n extrudedGeneric.path3D = path3D;\n extrudedGeneric.cap = cap;\n return extrudedGeneric;\n };\n return MeshBuilder;\n }());\n BABYLON.MeshBuilder = MeshBuilder;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.meshBuilder.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Draco compression (https://google.github.io/draco/)\n *\n * This class wraps the Draco module.\n *\n * **Encoder**\n *\n * The encoder is not currently implemented.\n *\n * **Decoder**\n *\n * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.\n *\n * To update the configuration, use the following code:\n * ```javascript\n * BABYLON.DracoCompression.Configuration = {\n * decoder: {\n * wasmUrl: \"\",\n * wasmBinaryUrl: \"\",\n * fallbackUrl: \"\",\n * }\n * };\n * ```\n *\n * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.\n * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.\n * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.\n *\n * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:\n * ```javascript\n * var dracoCompression = new BABYLON.DracoCompression();\n * var vertexData = await dracoCompression.decodeMeshAsync(data, {\n * [BABYLON.VertexBuffer.PositionKind]: 0\n * });\n * ```\n *\n * @see https://www.babylonjs-playground.com/#N3EK4B#0\n */\n var DracoCompression = /** @class */ (function () {\n /**\n * Constructor\n */\n function DracoCompression() {\n }\n Object.defineProperty(DracoCompression, \"DecoderAvailable\", {\n /**\n * Returns true if the decoder is available.\n */\n get: function () {\n if (typeof DracoDecoderModule !== \"undefined\") {\n return true;\n }\n var decoder = DracoCompression.Configuration.decoder;\n if (decoder) {\n if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === \"object\") {\n return true;\n }\n if (decoder.fallbackUrl) {\n return true;\n }\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Stop all async operations and release resources.\n */\n DracoCompression.prototype.dispose = function () {\n };\n /**\n * Decode Draco compressed mesh data to vertex data.\n * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data\n * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids\n * @returns A promise that resolves with the decoded vertex data\n */\n DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {\n var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;\n return DracoCompression._GetDecoderModule().then(function (wrappedModule) {\n var module = wrappedModule.module;\n var vertexData = new BABYLON.VertexData();\n var buffer = new module.DecoderBuffer();\n buffer.Init(dataView, dataView.byteLength);\n var decoder = new module.Decoder();\n var geometry;\n var status;\n try {\n var type = decoder.GetEncodedGeometryType(buffer);\n switch (type) {\n case module.TRIANGULAR_MESH:\n geometry = new module.Mesh();\n status = decoder.DecodeBufferToMesh(buffer, geometry);\n break;\n case module.POINT_CLOUD:\n geometry = new module.PointCloud();\n status = decoder.DecodeBufferToPointCloud(buffer, geometry);\n break;\n default:\n throw new Error(\"Invalid geometry type \" + type);\n }\n if (!status.ok() || !geometry.ptr) {\n throw new Error(status.error_msg());\n }\n var numPoints = geometry.num_points();\n if (type === module.TRIANGULAR_MESH) {\n var numFaces = geometry.num_faces();\n var faceIndices = new module.DracoInt32Array();\n try {\n var indices = new Uint32Array(numFaces * 3);\n for (var i = 0; i < numFaces; i++) {\n decoder.GetFaceFromMesh(geometry, i, faceIndices);\n var offset = i * 3;\n indices[offset + 0] = faceIndices.GetValue(0);\n indices[offset + 1] = faceIndices.GetValue(1);\n indices[offset + 2] = faceIndices.GetValue(2);\n }\n vertexData.indices = indices;\n }\n finally {\n module.destroy(faceIndices);\n }\n }\n for (var kind in attributes) {\n var uniqueId = attributes[kind];\n var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);\n var dracoData = new module.DracoFloat32Array();\n try {\n decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);\n var babylonData = new Float32Array(numPoints * attribute.num_components());\n for (var i = 0; i < babylonData.length; i++) {\n babylonData[i] = dracoData.GetValue(i);\n }\n vertexData.set(babylonData, kind);\n }\n finally {\n module.destroy(dracoData);\n }\n }\n }\n finally {\n if (geometry) {\n module.destroy(geometry);\n }\n module.destroy(decoder);\n module.destroy(buffer);\n }\n return vertexData;\n });\n };\n DracoCompression._GetDecoderModule = function () {\n if (!DracoCompression._DecoderModulePromise) {\n var promise = null;\n var config_1 = {};\n if (typeof DracoDecoderModule !== \"undefined\") {\n promise = Promise.resolve();\n }\n else {\n var decoder = DracoCompression.Configuration.decoder;\n if (decoder) {\n if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === \"object\") {\n promise = Promise.all([\n DracoCompression._LoadScriptAsync(decoder.wasmUrl),\n DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {\n config_1.wasmBinary = data;\n })\n ]);\n }\n else if (decoder.fallbackUrl) {\n promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);\n }\n }\n }\n if (!promise) {\n throw new Error(\"Draco decoder module is not available\");\n }\n DracoCompression._DecoderModulePromise = promise.then(function () {\n return new Promise(function (resolve) {\n config_1.onModuleLoaded = function (decoderModule) {\n // decoderModule is Promise-like. Wrap before resolving to avoid loop.\n resolve({ module: decoderModule });\n };\n DracoDecoderModule(config_1);\n });\n });\n }\n return DracoCompression._DecoderModulePromise;\n };\n DracoCompression._LoadScriptAsync = function (url) {\n return new Promise(function (resolve, reject) {\n BABYLON.Tools.LoadScript(url, function () {\n resolve();\n }, function (message) {\n reject(new Error(message));\n });\n });\n };\n DracoCompression._LoadFileAsync = function (url) {\n return new Promise(function (resolve, reject) {\n BABYLON.Tools.LoadFile(url, function (data) {\n resolve(data);\n }, undefined, undefined, true, function (request, exception) {\n reject(exception);\n });\n });\n };\n /**\n * The configuration. Defaults to the following urls:\n * - wasmUrl: \"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js\"\n * - wasmBinaryUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.wasm\"\n * - fallbackUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.js\"\n */\n DracoCompression.Configuration = {\n decoder: {\n wasmUrl: \"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js\",\n wasmBinaryUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.wasm\",\n fallbackUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.js\"\n }\n };\n return DracoCompression;\n }());\n BABYLON.DracoCompression = DracoCompression;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.dracoCompression.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var AudioEngine = /** @class */ (function () {\n function AudioEngine() {\n this._audioContext = null;\n this._audioContextInitialized = false;\n this.canUseWebAudio = false;\n this.WarnedWebAudioUnsupported = false;\n this.unlocked = false;\n this.isMP3supported = false;\n this.isOGGsupported = false;\n if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {\n window.AudioContext = window.AudioContext || window.webkitAudioContext;\n this.canUseWebAudio = true;\n }\n var audioElem = document.createElement('audio');\n try {\n if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs=\"mp3\"').replace(/^no$/, '')) {\n this.isMP3supported = true;\n }\n }\n catch (e) {\n // protect error during capability check.\n }\n try {\n if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs=\"vorbis\"').replace(/^no$/, '')) {\n this.isOGGsupported = true;\n }\n }\n catch (e) {\n // protect error during capability check.\n }\n if (/iPad|iPhone|iPod/.test(navigator.platform)) {\n this._unlockiOSaudio();\n }\n else {\n this.unlocked = true;\n }\n }\n Object.defineProperty(AudioEngine.prototype, \"audioContext\", {\n get: function () {\n if (!this._audioContextInitialized) {\n this._initializeAudioContext();\n }\n return this._audioContext;\n },\n enumerable: true,\n configurable: true\n });\n AudioEngine.prototype._unlockiOSaudio = function () {\n var _this = this;\n var unlockaudio = function () {\n if (!_this.audioContext) {\n return;\n }\n var buffer = _this.audioContext.createBuffer(1, 1, 22050);\n var source = _this.audioContext.createBufferSource();\n source.buffer = buffer;\n source.connect(_this.audioContext.destination);\n source.start(0);\n setTimeout(function () {\n if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {\n _this.unlocked = true;\n window.removeEventListener('touchend', unlockaudio, false);\n if (_this.onAudioUnlocked) {\n _this.onAudioUnlocked();\n }\n }\n }, 0);\n };\n window.addEventListener('touchend', unlockaudio, false);\n };\n AudioEngine.prototype._initializeAudioContext = function () {\n try {\n if (this.canUseWebAudio) {\n this._audioContext = new AudioContext();\n // create a global volume gain node \n this.masterGain = this._audioContext.createGain();\n this.masterGain.gain.value = 1;\n this.masterGain.connect(this._audioContext.destination);\n this._audioContextInitialized = true;\n }\n }\n catch (e) {\n this.canUseWebAudio = false;\n BABYLON.Tools.Error(\"Web Audio: \" + e.message);\n }\n };\n AudioEngine.prototype.dispose = function () {\n if (this.canUseWebAudio && this._audioContextInitialized) {\n if (this._connectedAnalyser && this._audioContext) {\n this._connectedAnalyser.stopDebugCanvas();\n this._connectedAnalyser.dispose();\n this.masterGain.disconnect();\n this.masterGain.connect(this._audioContext.destination);\n this._connectedAnalyser = null;\n }\n this.masterGain.gain.value = 1;\n }\n this.WarnedWebAudioUnsupported = false;\n };\n AudioEngine.prototype.getGlobalVolume = function () {\n if (this.canUseWebAudio && this._audioContextInitialized) {\n return this.masterGain.gain.value;\n }\n else {\n return -1;\n }\n };\n AudioEngine.prototype.setGlobalVolume = function (newVolume) {\n if (this.canUseWebAudio && this._audioContextInitialized) {\n this.masterGain.gain.value = newVolume;\n }\n };\n AudioEngine.prototype.connectToAnalyser = function (analyser) {\n if (this._connectedAnalyser) {\n this._connectedAnalyser.stopDebugCanvas();\n }\n if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {\n this._connectedAnalyser = analyser;\n this.masterGain.disconnect();\n this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);\n }\n };\n return AudioEngine;\n }());\n BABYLON.AudioEngine = AudioEngine;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.audioEngine.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Sound = /** @class */ (function () {\n /**\n * Create a sound and attach it to a scene\n * @param name Name of your sound\n * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams\n * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played\n * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming\n */\n function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {\n if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }\n var _this = this;\n this.autoplay = false;\n this.loop = false;\n this.useCustomAttenuation = false;\n this.spatialSound = false;\n this.refDistance = 1;\n this.rolloffFactor = 1;\n this.maxDistance = 100;\n this.distanceModel = \"linear\";\n this._panningModel = \"equalpower\";\n this._playbackRate = 1;\n this._streaming = false;\n this._startTime = 0;\n this._startOffset = 0;\n this._position = BABYLON.Vector3.Zero();\n this._localDirection = new BABYLON.Vector3(1, 0, 0);\n this._volume = 1;\n this._isReadyToPlay = false;\n this.isPlaying = false;\n this.isPaused = false;\n this._isDirectional = false;\n // Used if you'd like to create a directional sound.\n // If not set, the sound will be omnidirectional\n this._coneInnerAngle = 360;\n this._coneOuterAngle = 360;\n this._coneOuterGain = 0;\n this._isOutputConnected = false;\n this._urlType = \"Unknown\";\n this.name = name;\n this._scene = scene;\n this._readyToPlayCallback = readyToPlayCallback;\n // Default custom attenuation function is a linear attenuation\n this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {\n if (currentDistance < maxDistance) {\n return currentVolume * (1 - currentDistance / maxDistance);\n }\n else {\n return 0;\n }\n };\n if (options) {\n this.autoplay = options.autoplay || false;\n this.loop = options.loop || false;\n // if volume === 0, we need another way to check this option\n if (options.volume !== undefined) {\n this._volume = options.volume;\n }\n this.spatialSound = options.spatialSound || false;\n this.maxDistance = options.maxDistance || 100;\n this.useCustomAttenuation = options.useCustomAttenuation || false;\n this.rolloffFactor = options.rolloffFactor || 1;\n this.refDistance = options.refDistance || 1;\n this.distanceModel = options.distanceModel || \"linear\";\n this._playbackRate = options.playbackRate || 1;\n this._streaming = options.streaming || false;\n }\n if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {\n this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();\n this._soundGain.gain.value = this._volume;\n this._inputAudioNode = this._soundGain;\n this._ouputAudioNode = this._soundGain;\n if (this.spatialSound) {\n this._createSpatialParameters();\n }\n this._scene.mainSoundTrack.AddSound(this);\n var validParameter = true;\n // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound\n if (urlOrArrayBuffer) {\n try {\n if (typeof (urlOrArrayBuffer) === \"string\") {\n this._urlType = \"String\";\n }\n else if (urlOrArrayBuffer instanceof ArrayBuffer) {\n this._urlType = \"ArrayBuffer\";\n }\n else if (urlOrArrayBuffer instanceof MediaStream) {\n this._urlType = \"MediaStream\";\n }\n else if (Array.isArray(urlOrArrayBuffer)) {\n this._urlType = \"Array\";\n }\n var urls = [];\n var codecSupportedFound = false;\n switch (this._urlType) {\n case \"MediaStream\":\n this._streaming = true;\n this._isReadyToPlay = true;\n this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);\n if (this.autoplay) {\n this.play();\n }\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n break;\n case \"ArrayBuffer\":\n if (urlOrArrayBuffer.byteLength > 0) {\n codecSupportedFound = true;\n this._soundLoaded(urlOrArrayBuffer);\n }\n break;\n case \"String\":\n urls.push(urlOrArrayBuffer);\n case \"Array\":\n if (urls.length === 0)\n urls = urlOrArrayBuffer;\n // If we found a supported format, we load it immediately and stop the loop\n for (var i = 0; i < urls.length; i++) {\n var url = urls[i];\n if (url.indexOf(\".mp3\", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {\n codecSupportedFound = true;\n }\n if (url.indexOf(\".ogg\", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {\n codecSupportedFound = true;\n }\n if (url.indexOf(\".wav\", url.length - 4) !== -1) {\n codecSupportedFound = true;\n }\n if (url.indexOf(\"blob:\") !== -1) {\n codecSupportedFound = true;\n }\n if (codecSupportedFound) {\n // Loading sound using XHR2\n if (!this._streaming) {\n this._scene._loadFile(url, function (data) {\n _this._soundLoaded(data);\n }, undefined, true, true, function (exception) {\n if (exception) {\n BABYLON.Tools.Error(\"XHR \" + exception.status + \" error on: \" + url + \".\");\n }\n BABYLON.Tools.Error(\"Sound creation aborted.\");\n _this._scene.mainSoundTrack.RemoveSound(_this);\n });\n }\n // Streaming sound using HTML5 Audio tag\n else {\n this._htmlAudioElement = new Audio(url);\n this._htmlAudioElement.controls = false;\n this._htmlAudioElement.loop = this.loop;\n BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);\n this._htmlAudioElement.preload = \"auto\";\n this._htmlAudioElement.addEventListener(\"canplaythrough\", function () {\n _this._isReadyToPlay = true;\n if (_this.autoplay) {\n _this.play();\n }\n if (_this._readyToPlayCallback) {\n _this._readyToPlayCallback();\n }\n });\n document.body.appendChild(this._htmlAudioElement);\n }\n break;\n }\n }\n break;\n default:\n validParameter = false;\n break;\n }\n if (!validParameter) {\n BABYLON.Tools.Error(\"Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.\");\n }\n else {\n if (!codecSupportedFound) {\n this._isReadyToPlay = true;\n // Simulating a ready to play event to avoid breaking code path\n if (this._readyToPlayCallback) {\n window.setTimeout(function () {\n if (_this._readyToPlayCallback) {\n _this._readyToPlayCallback();\n }\n }, 1000);\n }\n }\n }\n }\n catch (ex) {\n BABYLON.Tools.Error(\"Unexpected error. Sound creation aborted.\");\n this._scene.mainSoundTrack.RemoveSound(this);\n }\n }\n }\n else {\n // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers\n this._scene.mainSoundTrack.AddSound(this);\n if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {\n BABYLON.Tools.Error(\"Web Audio is not supported by your browser.\");\n BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;\n }\n // Simulating a ready to play event to avoid breaking code for non web audio browsers\n if (this._readyToPlayCallback) {\n window.setTimeout(function () {\n if (_this._readyToPlayCallback) {\n _this._readyToPlayCallback();\n }\n }, 1000);\n }\n }\n }\n Sound.prototype.dispose = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio) {\n if (this.isPlaying) {\n this.stop();\n }\n this._isReadyToPlay = false;\n if (this.soundTrackId === -1) {\n this._scene.mainSoundTrack.RemoveSound(this);\n }\n else {\n this._scene.soundTracks[this.soundTrackId].RemoveSound(this);\n }\n if (this._soundGain) {\n this._soundGain.disconnect();\n this._soundGain = null;\n }\n if (this._soundPanner) {\n this._soundPanner.disconnect();\n this._soundPanner = null;\n }\n if (this._soundSource) {\n this._soundSource.disconnect();\n this._soundSource = null;\n }\n this._audioBuffer = null;\n if (this._htmlAudioElement) {\n this._htmlAudioElement.pause();\n this._htmlAudioElement.src = \"\";\n document.body.removeChild(this._htmlAudioElement);\n }\n if (this._streamingSource) {\n this._streamingSource.disconnect();\n }\n if (this._connectedMesh && this._registerFunc) {\n this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);\n this._connectedMesh = null;\n }\n }\n };\n Sound.prototype.isReady = function () {\n return this._isReadyToPlay;\n };\n Sound.prototype._soundLoaded = function (audioData) {\n var _this = this;\n if (!BABYLON.Engine.audioEngine.audioContext) {\n return;\n }\n BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {\n _this._audioBuffer = buffer;\n _this._isReadyToPlay = true;\n if (_this.autoplay) {\n _this.play();\n }\n if (_this._readyToPlayCallback) {\n _this._readyToPlayCallback();\n }\n }, function (err) { BABYLON.Tools.Error(\"Error while decoding audio data for: \" + _this.name + \" / Error: \" + err); });\n };\n Sound.prototype.setAudioBuffer = function (audioBuffer) {\n if (BABYLON.Engine.audioEngine.canUseWebAudio) {\n this._audioBuffer = audioBuffer;\n this._isReadyToPlay = true;\n }\n };\n Sound.prototype.updateOptions = function (options) {\n if (options) {\n this.loop = options.loop || this.loop;\n this.maxDistance = options.maxDistance || this.maxDistance;\n this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;\n this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;\n this.refDistance = options.refDistance || this.refDistance;\n this.distanceModel = options.distanceModel || this.distanceModel;\n this._playbackRate = options.playbackRate || this._playbackRate;\n this._updateSpatialParameters();\n if (this.isPlaying) {\n if (this._streaming && this._htmlAudioElement) {\n this._htmlAudioElement.playbackRate = this._playbackRate;\n }\n else {\n if (this._soundSource) {\n this._soundSource.playbackRate.value = this._playbackRate;\n }\n }\n }\n }\n };\n Sound.prototype._createSpatialParameters = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {\n if (this._scene.headphone) {\n this._panningModel = \"HRTF\";\n }\n this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();\n this._updateSpatialParameters();\n this._soundPanner.connect(this._ouputAudioNode);\n this._inputAudioNode = this._soundPanner;\n }\n };\n Sound.prototype._updateSpatialParameters = function () {\n if (this.spatialSound && this._soundPanner) {\n if (this.useCustomAttenuation) {\n // Tricks to disable in a way embedded Web Audio attenuation \n this._soundPanner.distanceModel = \"linear\";\n this._soundPanner.maxDistance = Number.MAX_VALUE;\n this._soundPanner.refDistance = 1;\n this._soundPanner.rolloffFactor = 1;\n this._soundPanner.panningModel = this._panningModel;\n }\n else {\n this._soundPanner.distanceModel = this.distanceModel;\n this._soundPanner.maxDistance = this.maxDistance;\n this._soundPanner.refDistance = this.refDistance;\n this._soundPanner.rolloffFactor = this.rolloffFactor;\n this._soundPanner.panningModel = this._panningModel;\n }\n }\n };\n Sound.prototype.switchPanningModelToHRTF = function () {\n this._panningModel = \"HRTF\";\n this._switchPanningModel();\n };\n Sound.prototype.switchPanningModelToEqualPower = function () {\n this._panningModel = \"equalpower\";\n this._switchPanningModel();\n };\n Sound.prototype._switchPanningModel = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {\n this._soundPanner.panningModel = this._panningModel;\n }\n };\n Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {\n if (BABYLON.Engine.audioEngine.canUseWebAudio) {\n if (this._isOutputConnected) {\n this._ouputAudioNode.disconnect();\n }\n this._ouputAudioNode.connect(soundTrackAudioNode);\n this._isOutputConnected = true;\n }\n };\n /**\n * Transform this sound into a directional source\n * @param coneInnerAngle Size of the inner cone in degree\n * @param coneOuterAngle Size of the outer cone in degree\n * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)\n */\n Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {\n if (coneOuterAngle < coneInnerAngle) {\n BABYLON.Tools.Error(\"setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.\");\n return;\n }\n this._coneInnerAngle = coneInnerAngle;\n this._coneOuterAngle = coneOuterAngle;\n this._coneOuterGain = coneOuterGain;\n this._isDirectional = true;\n if (this.isPlaying && this.loop) {\n this.stop();\n this.play();\n }\n };\n Sound.prototype.setPosition = function (newPosition) {\n this._position = newPosition;\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {\n this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);\n }\n };\n Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {\n this._localDirection = newLocalDirection;\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {\n this._updateDirection();\n }\n };\n Sound.prototype._updateDirection = function () {\n if (!this._connectedMesh || !this._soundPanner) {\n return;\n }\n var mat = this._connectedMesh.getWorldMatrix();\n var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);\n direction.normalize();\n this._soundPanner.setOrientation(direction.x, direction.y, direction.z);\n };\n Sound.prototype.updateDistanceFromListener = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {\n var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);\n this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);\n }\n };\n Sound.prototype.setAttenuationFunction = function (callback) {\n this._customAttenuationFunction = callback;\n };\n /**\n * Play the sound\n * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.\n * @param offset (optional) Start the sound setting it at a specific time\n */\n Sound.prototype.play = function (time, offset) {\n var _this = this;\n if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {\n try {\n if (this._startOffset < 0) {\n time = -this._startOffset;\n this._startOffset = 0;\n }\n var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;\n if (!this._soundSource || !this._streamingSource) {\n if (this.spatialSound && this._soundPanner) {\n this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);\n if (this._isDirectional) {\n this._soundPanner.coneInnerAngle = this._coneInnerAngle;\n this._soundPanner.coneOuterAngle = this._coneOuterAngle;\n this._soundPanner.coneOuterGain = this._coneOuterGain;\n if (this._connectedMesh) {\n this._updateDirection();\n }\n else {\n this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);\n }\n }\n }\n }\n if (this._streaming) {\n if (!this._streamingSource) {\n this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);\n this._htmlAudioElement.onended = function () { _this._onended(); };\n this._htmlAudioElement.playbackRate = this._playbackRate;\n }\n this._streamingSource.disconnect();\n this._streamingSource.connect(this._inputAudioNode);\n if (this._htmlAudioElement) {\n this._htmlAudioElement.play();\n }\n }\n else {\n this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();\n this._soundSource.buffer = this._audioBuffer;\n this._soundSource.connect(this._inputAudioNode);\n this._soundSource.loop = this.loop;\n this._soundSource.playbackRate.value = this._playbackRate;\n this._soundSource.onended = function () { _this._onended(); };\n if (this._soundSource.buffer) {\n this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);\n }\n }\n this._startTime = startTime;\n this.isPlaying = true;\n this.isPaused = false;\n }\n catch (ex) {\n BABYLON.Tools.Error(\"Error while trying to play audio: \" + this.name + \", \" + ex.message);\n }\n }\n };\n Sound.prototype._onended = function () {\n this.isPlaying = false;\n if (this.onended) {\n this.onended();\n }\n };\n /**\n * Stop the sound\n * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.\n */\n Sound.prototype.stop = function (time) {\n if (this.isPlaying) {\n if (this._streaming) {\n if (this._htmlAudioElement) {\n this._htmlAudioElement.pause();\n // Test needed for Firefox or it will generate an Invalid State Error\n if (this._htmlAudioElement.currentTime > 0) {\n this._htmlAudioElement.currentTime = 0;\n }\n }\n else {\n this._streamingSource.disconnect();\n }\n }\n else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {\n var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;\n this._soundSource.stop(stopTime);\n this._soundSource.onended = function () { };\n if (!this.isPaused) {\n this._startOffset = 0;\n }\n }\n this.isPlaying = false;\n }\n };\n Sound.prototype.pause = function () {\n if (this.isPlaying) {\n this.isPaused = true;\n if (this._streaming) {\n if (this._htmlAudioElement) {\n this._htmlAudioElement.pause();\n }\n else {\n this._streamingSource.disconnect();\n }\n }\n else if (BABYLON.Engine.audioEngine.audioContext) {\n this.stop(0);\n this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;\n }\n }\n };\n Sound.prototype.setVolume = function (newVolume, time) {\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {\n if (time && BABYLON.Engine.audioEngine.audioContext) {\n this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);\n this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);\n this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);\n }\n else {\n this._soundGain.gain.value = newVolume;\n }\n }\n this._volume = newVolume;\n };\n Sound.prototype.setPlaybackRate = function (newPlaybackRate) {\n this._playbackRate = newPlaybackRate;\n if (this.isPlaying) {\n if (this._streaming && this._htmlAudioElement) {\n this._htmlAudioElement.playbackRate = this._playbackRate;\n }\n else if (this._soundSource) {\n this._soundSource.playbackRate.value = this._playbackRate;\n }\n }\n };\n Sound.prototype.getVolume = function () {\n return this._volume;\n };\n Sound.prototype.attachToMesh = function (meshToConnectTo) {\n var _this = this;\n if (this._connectedMesh && this._registerFunc) {\n this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);\n this._registerFunc = null;\n }\n this._connectedMesh = meshToConnectTo;\n if (!this.spatialSound) {\n this.spatialSound = true;\n this._createSpatialParameters();\n if (this.isPlaying && this.loop) {\n this.stop();\n this.play();\n }\n }\n this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);\n this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };\n meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);\n };\n Sound.prototype.detachFromMesh = function () {\n if (this._connectedMesh && this._registerFunc) {\n this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);\n this._registerFunc = null;\n this._connectedMesh = null;\n }\n };\n Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {\n if (!node.getBoundingInfo) {\n return;\n }\n var mesh = node;\n var boundingInfo = mesh.getBoundingInfo();\n this.setPosition(boundingInfo.boundingSphere.centerWorld);\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {\n this._updateDirection();\n }\n };\n Sound.prototype.clone = function () {\n var _this = this;\n if (!this._streaming) {\n var setBufferAndRun = function () {\n if (_this._isReadyToPlay) {\n clonedSound._audioBuffer = _this.getAudioBuffer();\n clonedSound._isReadyToPlay = true;\n if (clonedSound.autoplay) {\n clonedSound.play();\n }\n }\n else {\n window.setTimeout(setBufferAndRun, 300);\n }\n };\n var currentOptions = {\n autoplay: this.autoplay, loop: this.loop,\n volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,\n useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,\n refDistance: this.refDistance, distanceModel: this.distanceModel\n };\n var clonedSound = new Sound(this.name + \"_cloned\", new ArrayBuffer(0), this._scene, null, currentOptions);\n if (this.useCustomAttenuation) {\n clonedSound.setAttenuationFunction(this._customAttenuationFunction);\n }\n clonedSound.setPosition(this._position);\n clonedSound.setPlaybackRate(this._playbackRate);\n setBufferAndRun();\n return clonedSound;\n }\n // Can't clone a streaming sound\n else {\n return null;\n }\n };\n Sound.prototype.getAudioBuffer = function () {\n return this._audioBuffer;\n };\n Sound.prototype.serialize = function () {\n var serializationObject = {\n name: this.name,\n url: this.name,\n autoplay: this.autoplay,\n loop: this.loop,\n volume: this._volume,\n spatialSound: this.spatialSound,\n maxDistance: this.maxDistance,\n rolloffFactor: this.rolloffFactor,\n refDistance: this.refDistance,\n distanceModel: this.distanceModel,\n playbackRate: this._playbackRate,\n panningModel: this._panningModel,\n soundTrackId: this.soundTrackId\n };\n if (this.spatialSound) {\n if (this._connectedMesh)\n serializationObject.connectedMeshId = this._connectedMesh.id;\n serializationObject.position = this._position.asArray();\n serializationObject.refDistance = this.refDistance;\n serializationObject.distanceModel = this.distanceModel;\n serializationObject.isDirectional = this._isDirectional;\n serializationObject.localDirectionToMesh = this._localDirection.asArray();\n serializationObject.coneInnerAngle = this._coneInnerAngle;\n serializationObject.coneOuterAngle = this._coneOuterAngle;\n serializationObject.coneOuterGain = this._coneOuterGain;\n }\n return serializationObject;\n };\n Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {\n var soundName = parsedSound.name;\n var soundUrl;\n if (parsedSound.url) {\n soundUrl = rootUrl + parsedSound.url;\n }\n else {\n soundUrl = rootUrl + soundName;\n }\n var options = {\n autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,\n spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,\n rolloffFactor: parsedSound.rolloffFactor,\n refDistance: parsedSound.refDistance,\n distanceModel: parsedSound.distanceModel,\n playbackRate: parsedSound.playbackRate\n };\n var newSound;\n if (!sourceSound) {\n newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);\n scene._addPendingData(newSound);\n }\n else {\n var setBufferAndRun = function () {\n if (sourceSound._isReadyToPlay) {\n newSound._audioBuffer = sourceSound.getAudioBuffer();\n newSound._isReadyToPlay = true;\n if (newSound.autoplay) {\n newSound.play();\n }\n }\n else {\n window.setTimeout(setBufferAndRun, 300);\n }\n };\n newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);\n setBufferAndRun();\n }\n if (parsedSound.position) {\n var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);\n newSound.setPosition(soundPosition);\n }\n if (parsedSound.isDirectional) {\n newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);\n if (parsedSound.localDirectionToMesh) {\n var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);\n newSound.setLocalDirectionToMesh(localDirectionToMesh);\n }\n }\n if (parsedSound.connectedMeshId) {\n var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);\n if (connectedMesh) {\n newSound.attachToMesh(connectedMesh);\n }\n }\n return newSound;\n };\n return Sound;\n }());\n BABYLON.Sound = Sound;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sound.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var SoundTrack = /** @class */ (function () {\n function SoundTrack(scene, options) {\n this.id = -1;\n this._isMainTrack = false;\n this._isInitialized = false;\n this._scene = scene;\n this.soundCollection = new Array();\n this._options = options;\n if (!this._isMainTrack) {\n this._scene.soundTracks.push(this);\n this.id = this._scene.soundTracks.length - 1;\n }\n }\n SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {\n this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();\n this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);\n if (this._options) {\n if (this._options.volume) {\n this._outputAudioNode.gain.value = this._options.volume;\n }\n if (this._options.mainTrack) {\n this._isMainTrack = this._options.mainTrack;\n }\n }\n this._isInitialized = true;\n }\n };\n SoundTrack.prototype.dispose = function () {\n if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {\n if (this._connectedAnalyser) {\n this._connectedAnalyser.stopDebugCanvas();\n }\n while (this.soundCollection.length) {\n this.soundCollection[0].dispose();\n }\n if (this._outputAudioNode) {\n this._outputAudioNode.disconnect();\n }\n this._outputAudioNode = null;\n }\n };\n SoundTrack.prototype.AddSound = function (sound) {\n if (!this._isInitialized) {\n this._initializeSoundTrackAudioGraph();\n }\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {\n sound.connectToSoundTrackAudioNode(this._outputAudioNode);\n }\n if (sound.soundTrackId) {\n if (sound.soundTrackId === -1) {\n this._scene.mainSoundTrack.RemoveSound(sound);\n }\n else {\n this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);\n }\n }\n this.soundCollection.push(sound);\n sound.soundTrackId = this.id;\n };\n SoundTrack.prototype.RemoveSound = function (sound) {\n var index = this.soundCollection.indexOf(sound);\n if (index !== -1) {\n this.soundCollection.splice(index, 1);\n }\n };\n SoundTrack.prototype.setVolume = function (newVolume) {\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {\n this._outputAudioNode.gain.value = newVolume;\n }\n };\n SoundTrack.prototype.switchPanningModelToHRTF = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio) {\n for (var i = 0; i < this.soundCollection.length; i++) {\n this.soundCollection[i].switchPanningModelToHRTF();\n }\n }\n };\n SoundTrack.prototype.switchPanningModelToEqualPower = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio) {\n for (var i = 0; i < this.soundCollection.length; i++) {\n this.soundCollection[i].switchPanningModelToEqualPower();\n }\n }\n };\n SoundTrack.prototype.connectToAnalyser = function (analyser) {\n if (this._connectedAnalyser) {\n this._connectedAnalyser.stopDebugCanvas();\n }\n this._connectedAnalyser = analyser;\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {\n this._outputAudioNode.disconnect();\n this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);\n }\n };\n return SoundTrack;\n }());\n BABYLON.SoundTrack = SoundTrack;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.soundtrack.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to work with sound analyzer using fast fourier transform (FFT)\n * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music\n */\n var Analyser = /** @class */ (function () {\n /**\n * Creates a new analyser\n * @param scene defines hosting scene\n */\n function Analyser(scene) {\n /**\n * Gets or sets the smoothing\n * @ignorenaming\n */\n this.SMOOTHING = 0.75;\n /**\n * Gets or sets the FFT table size\n * @ignorenaming\n */\n this.FFT_SIZE = 512;\n /**\n * Gets or sets the bar graph amplitude\n * @ignorenaming\n */\n this.BARGRAPHAMPLITUDE = 256;\n /**\n * Gets or sets the position of the debug canvas\n * @ignorenaming\n */\n this.DEBUGCANVASPOS = { x: 20, y: 20 };\n /**\n * Gets or sets the debug canvas size\n * @ignorenaming\n */\n this.DEBUGCANVASSIZE = { width: 320, height: 200 };\n this._scene = scene;\n this._audioEngine = BABYLON.Engine.audioEngine;\n if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {\n this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();\n this._webAudioAnalyser.minDecibels = -140;\n this._webAudioAnalyser.maxDecibels = 0;\n this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);\n this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);\n this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);\n }\n }\n /**\n * Get the number of data values you will have to play with for the visualization\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount\n * @returns a number\n */\n Analyser.prototype.getFrequencyBinCount = function () {\n if (this._audioEngine.canUseWebAudio) {\n return this._webAudioAnalyser.frequencyBinCount;\n }\n else {\n return 0;\n }\n };\n /**\n * Gets the current frequency data as a byte array\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData\n * @returns a Uint8Array\n */\n Analyser.prototype.getByteFrequencyData = function () {\n if (this._audioEngine.canUseWebAudio) {\n this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;\n this._webAudioAnalyser.fftSize = this.FFT_SIZE;\n this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);\n }\n return this._byteFreqs;\n };\n /**\n * Gets the current waveform as a byte array\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData\n * @returns a Uint8Array\n */\n Analyser.prototype.getByteTimeDomainData = function () {\n if (this._audioEngine.canUseWebAudio) {\n this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;\n this._webAudioAnalyser.fftSize = this.FFT_SIZE;\n this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);\n }\n return this._byteTime;\n };\n /**\n * Gets the current frequency data as a float array\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData\n * @returns a Float32Array\n */\n Analyser.prototype.getFloatFrequencyData = function () {\n if (this._audioEngine.canUseWebAudio) {\n this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;\n this._webAudioAnalyser.fftSize = this.FFT_SIZE;\n this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);\n }\n return this._floatFreqs;\n };\n /**\n * Renders the debug canvas\n */\n Analyser.prototype.drawDebugCanvas = function () {\n var _this = this;\n if (this._audioEngine.canUseWebAudio) {\n if (!this._debugCanvas) {\n this._debugCanvas = document.createElement(\"canvas\");\n this._debugCanvas.width = this.DEBUGCANVASSIZE.width;\n this._debugCanvas.height = this.DEBUGCANVASSIZE.height;\n this._debugCanvas.style.position = \"absolute\";\n this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + \"px\";\n this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + \"px\";\n this._debugCanvasContext = this._debugCanvas.getContext(\"2d\");\n document.body.appendChild(this._debugCanvas);\n this._registerFunc = function () {\n _this.drawDebugCanvas();\n };\n this._scene.registerBeforeRender(this._registerFunc);\n }\n if (this._registerFunc && this._debugCanvasContext) {\n var workingArray = this.getByteFrequencyData();\n this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';\n this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);\n // Draw the frequency domain chart.\n for (var i = 0; i < this.getFrequencyBinCount(); i++) {\n var value = workingArray[i];\n var percent = value / this.BARGRAPHAMPLITUDE;\n var height = this.DEBUGCANVASSIZE.height * percent;\n var offset = this.DEBUGCANVASSIZE.height - height - 1;\n var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();\n var hue = i / this.getFrequencyBinCount() * 360;\n this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';\n this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);\n }\n }\n }\n };\n /**\n * Stops rendering the debug canvas and removes it\n */\n Analyser.prototype.stopDebugCanvas = function () {\n if (this._debugCanvas) {\n if (this._registerFunc) {\n this._scene.unregisterBeforeRender(this._registerFunc);\n this._registerFunc = null;\n }\n document.body.removeChild(this._debugCanvas);\n this._debugCanvas = null;\n this._debugCanvasContext = null;\n }\n };\n /**\n * Connects two audio nodes\n * @param inputAudioNode defines first node to connect\n * @param outputAudioNode defines second node to connect\n */\n Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {\n if (this._audioEngine.canUseWebAudio) {\n inputAudioNode.connect(this._webAudioAnalyser);\n this._webAudioAnalyser.connect(outputAudioNode);\n }\n };\n /**\n * Releases all associated resources\n */\n Analyser.prototype.dispose = function () {\n if (this._audioEngine.canUseWebAudio) {\n this._webAudioAnalyser.disconnect();\n }\n };\n return Analyser;\n }());\n BABYLON.Analyser = Analyser;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.analyser.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var CubeTexture = /** @class */ (function (_super) {\n __extends(CubeTexture, _super);\n /**\n * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well\n * as prefiltered data.\n * @param rootUrl defines the url of the texture or the root name of the six images\n * @param scene defines the scene the texture is attached to\n * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...\n * @param noMipmap defines if mipmaps should be created or not\n * @param files defines the six files to load for the different faces\n * @param onLoad defines a callback triggered at the end of the file load if no errors occured\n * @param onError defines a callback triggered in case of error during load\n * @param format defines the internal format to use for the texture once loaded\n * @param prefiltered defines whether or not the texture is created from prefiltered data\n * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name\n * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary\n * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness\n * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness\n * @return the cube texture\n */\n function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {\n if (extensions === void 0) { extensions = null; }\n if (noMipmap === void 0) { noMipmap = false; }\n if (files === void 0) { files = null; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }\n if (prefiltered === void 0) { prefiltered = false; }\n if (forcedExtension === void 0) { forcedExtension = null; }\n if (createPolynomials === void 0) { createPolynomials = false; }\n if (lodScale === void 0) { lodScale = 0.8; }\n if (lodOffset === void 0) { lodOffset = 0; }\n var _this = _super.call(this, scene) || this;\n /**\n * Gets or sets the center of the bounding box associated with the cube texture\n * It must define where the camera used to render the texture was set\n */\n _this.boundingBoxPosition = BABYLON.Vector3.Zero();\n _this._rotationY = 0;\n /** @hidden */\n _this._prefiltered = false;\n _this.name = rootUrl;\n _this.url = rootUrl;\n _this._noMipmap = noMipmap;\n _this.hasAlpha = false;\n _this._format = format;\n _this.isCube = true;\n _this._textureMatrix = BABYLON.Matrix.Identity();\n _this._createPolynomials = createPolynomials;\n _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;\n if (!rootUrl && !files) {\n return _this;\n }\n var lastDot = rootUrl.lastIndexOf(\".\");\n var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : \"\");\n var isDDS = (extension === \".dds\");\n var isEnv = (extension === \".env\");\n if (isEnv) {\n _this.gammaSpace = false;\n _this._prefiltered = false;\n }\n else {\n _this._prefiltered = prefiltered;\n if (prefiltered) {\n _this.gammaSpace = false;\n }\n }\n _this._texture = _this._getFromCache(rootUrl, noMipmap);\n if (!files) {\n if (!isEnv && !isDDS && !extensions) {\n extensions = [\"_px.jpg\", \"_py.jpg\", \"_pz.jpg\", \"_nx.jpg\", \"_ny.jpg\", \"_nz.jpg\"];\n }\n files = [];\n if (extensions) {\n for (var index = 0; index < extensions.length; index++) {\n files.push(rootUrl + extensions[index]);\n }\n }\n }\n _this._files = files;\n if (!_this._texture) {\n if (!scene.useDelayedTextureLoading) {\n if (prefiltered) {\n _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);\n }\n else {\n _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);\n }\n }\n else {\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n }\n }\n else if (onLoad) {\n if (_this._texture.isReady) {\n BABYLON.Tools.SetImmediate(function () { return onLoad(); });\n }\n else {\n _this._texture.onLoadedObservable.add(onLoad);\n }\n }\n return _this;\n }\n Object.defineProperty(CubeTexture.prototype, \"boundingBoxSize\", {\n get: function () {\n return this._boundingBoxSize;\n },\n /**\n * Gets or sets the size of the bounding box associated with the cube texture\n * When defined, the cubemap will switch to local mode\n * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity\n * @example https://www.babylonjs-playground.com/#RNASML\n */\n set: function (value) {\n if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {\n return;\n }\n this._boundingBoxSize = value;\n var scene = this.getScene();\n if (scene) {\n scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CubeTexture.prototype, \"rotationY\", {\n /**\n * Gets texture matrix rotation angle around Y axis radians.\n */\n get: function () {\n return this._rotationY;\n },\n /**\n * Sets texture matrix rotation angle around Y axis in radians.\n */\n set: function (value) {\n this._rotationY = value;\n this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));\n },\n enumerable: true,\n configurable: true\n });\n CubeTexture.CreateFromImages = function (files, scene, noMipmap) {\n var rootUrlKey = \"\";\n files.forEach(function (url) { return rootUrlKey += url; });\n return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);\n };\n /**\n * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.\n * @param url defines the url of the prefiltered texture\n * @param scene defines the scene the texture is attached to\n * @param forcedExtension defines the extension of the file if different from the url\n * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary\n * @return the prefiltered texture\n */\n CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {\n if (forcedExtension === void 0) { forcedExtension = null; }\n if (createPolynomials === void 0) { createPolynomials = true; }\n return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);\n };\n // Methods\n CubeTexture.prototype.delayLoad = function () {\n if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {\n return;\n }\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;\n this._texture = this._getFromCache(this.url, this._noMipmap);\n if (!this._texture) {\n if (this._prefiltered) {\n this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);\n }\n else {\n this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);\n }\n }\n };\n CubeTexture.prototype.getReflectionTextureMatrix = function () {\n return this._textureMatrix;\n };\n CubeTexture.prototype.setReflectionTextureMatrix = function (value) {\n this._textureMatrix = value;\n };\n CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {\n var texture = BABYLON.SerializationHelper.Parse(function () {\n var prefiltered = false;\n if (parsedTexture.prefiltered) {\n prefiltered = parsedTexture.prefiltered;\n }\n return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);\n }, parsedTexture, scene);\n // Local Cubemaps\n if (parsedTexture.boundingBoxPosition) {\n texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);\n }\n if (parsedTexture.boundingBoxSize) {\n texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);\n }\n // Animations\n if (parsedTexture.animations) {\n for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {\n var parsedAnimation = parsedTexture.animations[animationIndex];\n texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n }\n return texture;\n };\n CubeTexture.prototype.clone = function () {\n var _this = this;\n return BABYLON.SerializationHelper.Clone(function () {\n var scene = _this.getScene();\n if (!scene) {\n return _this;\n }\n return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);\n }, this);\n };\n __decorate([\n BABYLON.serialize(\"rotationY\")\n ], CubeTexture.prototype, \"_rotationY\", void 0);\n return CubeTexture;\n }(BABYLON.BaseTexture));\n BABYLON.CubeTexture = CubeTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.cubeTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Raw cube texture where the raw buffers are passed in\n */\n var RawCubeTexture = /** @class */ (function (_super) {\n __extends(RawCubeTexture, _super);\n /**\n * Creates a cube texture where the raw buffers are passed in.\n * @param scene defines the scene the texture is attached to\n * @param data defines the array of data to use to create each face\n * @param size defines the size of the textures\n * @param format defines the format of the data\n * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)\n * @param generateMipMaps defines if the engine should generate the mip levels\n * @param invertY defines if data must be stored with Y axis inverted\n * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)\n * @param compression defines the compression used (null by default)\n */\n function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {\n if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (generateMipMaps === void 0) { generateMipMaps = false; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (compression === void 0) { compression = null; }\n var _this = _super.call(this, \"\", scene) || this;\n _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);\n return _this;\n }\n /**\n * Updates the raw cube texture.\n * @param data defines the data to store\n * @param format defines the data format\n * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)\n * @param invertY defines if data must be stored with Y axis inverted\n * @param compression defines the compression used (null by default)\n * @param level defines which level of the texture to update\n */\n RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {\n if (compression === void 0) { compression = null; }\n if (level === void 0) { level = 0; }\n this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);\n };\n /**\n * Updates a raw cube texture with RGBD encoded data.\n * @param data defines the array of data [mipmap][face] to use to create each face\n * @param sphericalPolynomial defines the spherical polynomial for irradiance\n * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness\n * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness\n * @returns a promsie that resolves when the operation is complete\n */\n RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {\n if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }\n if (lodScale === void 0) { lodScale = 0.8; }\n if (lodOffset === void 0) { lodOffset = 0; }\n return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);\n };\n /**\n * Clones the raw cube texture.\n * @return a new cube texture\n */\n RawCubeTexture.prototype.clone = function () {\n var _this = this;\n return BABYLON.SerializationHelper.Clone(function () {\n var scene = _this.getScene();\n var internalTexture = _this._texture;\n var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);\n if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {\n texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);\n }\n return texture;\n }, this);\n };\n /** @hidden */\n RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {\n internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;\n internalTexture._bufferViewArrayArray = data;\n internalTexture._lodGenerationScale = lodScale;\n internalTexture._lodGenerationOffset = lodOffset;\n internalTexture._sphericalPolynomial = sphericalPolynomial;\n return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {\n internalTexture.isReady = true;\n });\n };\n return RawCubeTexture;\n }(BABYLON.CubeTexture));\n BABYLON.RawCubeTexture = RawCubeTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.rawCubeTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var RenderTargetTexture = /** @class */ (function (_super) {\n __extends(RenderTargetTexture, _super);\n /**\n * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse\n * or used a shadow, depth texture...\n * @param name The friendly name of the texture\n * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)\n * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.\n * @param generateMipMaps True if mip maps need to be generated after render.\n * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT\n * @param type The type of the buffer in the RTT (int, half float, float...)\n * @param isCube True if a cube texture needs to be created\n * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)\n * @param generateDepthBuffer True to generate a depth buffer\n * @param generateStencilBuffer True to generate a stencil buffer\n * @param isMulti True if multiple textures need to be created (Draw Buffers)\n * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)\n */\n function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {\n if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (isCube === void 0) { isCube = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }\n if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }\n if (isMulti === void 0) { isMulti = false; }\n if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }\n var _this = _super.call(this, null, scene, !generateMipMaps) || this;\n _this.isCube = isCube;\n _this.renderParticles = true;\n _this.renderSprites = false;\n _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;\n _this.ignoreCameraViewport = false;\n // Events\n /**\n * An event triggered when the texture is unbind.\n */\n _this.onBeforeBindObservable = new BABYLON.Observable();\n /**\n * An event triggered when the texture is unbind.\n */\n _this.onAfterUnbindObservable = new BABYLON.Observable();\n /**\n * An event triggered before rendering the texture\n */\n _this.onBeforeRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered after rendering the texture\n */\n _this.onAfterRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered after the texture clear\n */\n _this.onClearObservable = new BABYLON.Observable();\n _this._currentRefreshId = -1;\n _this._refreshRate = 1;\n _this._samples = 1;\n /**\n * Gets or sets the center of the bounding box associated with the texture (when in cube mode)\n * It must define where the camera used to render the texture is set\n */\n _this.boundingBoxPosition = BABYLON.Vector3.Zero();\n scene = _this.getScene();\n if (!scene) {\n return _this;\n }\n _this.renderList = new Array();\n _this._engine = scene.getEngine();\n _this.name = name;\n _this.isRenderTarget = true;\n _this._initialSizeParameter = size;\n _this._processSizeParameter(size);\n _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {\n });\n _this._generateMipMaps = generateMipMaps ? true : false;\n _this._doNotChangeAspectRatio = doNotChangeAspectRatio;\n // Rendering groups\n _this._renderingManager = new BABYLON.RenderingManager(scene);\n _this._renderingManager._useSceneAutoClearSetup = true;\n if (isMulti) {\n return _this;\n }\n _this._renderTargetOptions = {\n generateMipMaps: generateMipMaps,\n type: type,\n format: format,\n samplingMode: samplingMode,\n generateDepthBuffer: generateDepthBuffer,\n generateStencilBuffer: generateStencilBuffer\n };\n if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {\n _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n }\n if (isCube) {\n _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);\n _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;\n _this._textureMatrix = BABYLON.Matrix.Identity();\n }\n else {\n _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);\n }\n return _this;\n }\n Object.defineProperty(RenderTargetTexture, \"REFRESHRATE_RENDER_ONCE\", {\n get: function () {\n return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture, \"REFRESHRATE_RENDER_ONEVERYFRAME\", {\n get: function () {\n return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture, \"REFRESHRATE_RENDER_ONEVERYTWOFRAMES\", {\n get: function () {\n return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture.prototype, \"renderList\", {\n /**\n * Use this list to define the list of mesh you want to render.\n */\n get: function () {\n return this._renderList;\n },\n set: function (value) {\n this._renderList = value;\n if (this._renderList) {\n this._hookArray(this._renderList);\n }\n },\n enumerable: true,\n configurable: true\n });\n RenderTargetTexture.prototype._hookArray = function (array) {\n var _this = this;\n var oldPush = array.push;\n array.push = function () {\n var items = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n items[_i] = arguments[_i];\n }\n var result = oldPush.apply(array, items);\n _this.getScene().meshes.forEach(function (mesh) {\n mesh._markSubMeshesAsLightDirty();\n });\n return result;\n };\n var oldSplice = array.splice;\n array.splice = function (index, deleteCount) {\n var deleted = oldSplice.apply(array, [index, deleteCount]);\n _this.getScene().meshes.forEach(function (mesh) {\n mesh._markSubMeshesAsLightDirty();\n });\n return deleted;\n };\n };\n Object.defineProperty(RenderTargetTexture.prototype, \"onAfterUnbind\", {\n set: function (callback) {\n if (this._onAfterUnbindObserver) {\n this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);\n }\n this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture.prototype, \"onBeforeRender\", {\n set: function (callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture.prototype, \"onAfterRender\", {\n set: function (callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture.prototype, \"onClear\", {\n set: function (callback) {\n if (this._onClearObserver) {\n this.onClearObservable.remove(this._onClearObserver);\n }\n this._onClearObserver = this.onClearObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture.prototype, \"renderTargetOptions\", {\n get: function () {\n return this._renderTargetOptions;\n },\n enumerable: true,\n configurable: true\n });\n RenderTargetTexture.prototype._onRatioRescale = function () {\n if (this._sizeRatio) {\n this.resize(this._initialSizeParameter);\n }\n };\n Object.defineProperty(RenderTargetTexture.prototype, \"boundingBoxSize\", {\n get: function () {\n return this._boundingBoxSize;\n },\n /**\n * Gets or sets the size of the bounding box associated with the texture (when in cube mode)\n * When defined, the cubemap will switch to local mode\n * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity\n * @example https://www.babylonjs-playground.com/#RNASML\n */\n set: function (value) {\n if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {\n return;\n }\n this._boundingBoxSize = value;\n var scene = this.getScene();\n if (scene) {\n scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Creates a depth stencil texture.\n * This is only available in WebGL 2 or with the depth texture extension available.\n * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode\n * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture\n * @param generateStencil Specifies whether or not a stencil should be allocated in the texture\n */\n RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {\n if (comparisonFunction === void 0) { comparisonFunction = 0; }\n if (bilinearFiltering === void 0) { bilinearFiltering = true; }\n if (generateStencil === void 0) { generateStencil = false; }\n if (!this.getScene()) {\n return;\n }\n var engine = this.getScene().getEngine();\n this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {\n bilinearFiltering: bilinearFiltering,\n comparisonFunction: comparisonFunction,\n generateStencil: generateStencil,\n isCube: this.isCube\n });\n engine.setFrameBufferDepthStencilTexture(this);\n };\n RenderTargetTexture.prototype._processSizeParameter = function (size) {\n if (size.ratio) {\n this._sizeRatio = size.ratio;\n this._size = {\n width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),\n height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)\n };\n }\n else {\n this._size = size;\n }\n };\n Object.defineProperty(RenderTargetTexture.prototype, \"samples\", {\n get: function () {\n return this._samples;\n },\n set: function (value) {\n if (this._samples === value) {\n return;\n }\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);\n },\n enumerable: true,\n configurable: true\n });\n RenderTargetTexture.prototype.resetRefreshCounter = function () {\n this._currentRefreshId = -1;\n };\n Object.defineProperty(RenderTargetTexture.prototype, \"refreshRate\", {\n get: function () {\n return this._refreshRate;\n },\n // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...\n set: function (value) {\n this._refreshRate = value;\n this.resetRefreshCounter();\n },\n enumerable: true,\n configurable: true\n });\n RenderTargetTexture.prototype.addPostProcess = function (postProcess) {\n if (!this._postProcessManager) {\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this._postProcessManager = new BABYLON.PostProcessManager(scene);\n this._postProcesses = new Array();\n }\n this._postProcesses.push(postProcess);\n this._postProcesses[0].autoClear = false;\n };\n RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {\n if (!this._postProcesses) {\n return;\n }\n if (dispose) {\n for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {\n var postProcess = _a[_i];\n postProcess.dispose();\n }\n }\n this._postProcesses = [];\n };\n RenderTargetTexture.prototype.removePostProcess = function (postProcess) {\n if (!this._postProcesses) {\n return;\n }\n var index = this._postProcesses.indexOf(postProcess);\n if (index === -1) {\n return;\n }\n this._postProcesses.splice(index, 1);\n if (this._postProcesses.length > 0) {\n this._postProcesses[0].autoClear = false;\n }\n };\n RenderTargetTexture.prototype._shouldRender = function () {\n if (this._currentRefreshId === -1) { // At least render once\n this._currentRefreshId = 1;\n return true;\n }\n if (this.refreshRate === this._currentRefreshId) {\n this._currentRefreshId = 1;\n return true;\n }\n this._currentRefreshId++;\n return false;\n };\n RenderTargetTexture.prototype.getRenderSize = function () {\n if (this._size.width) {\n return this._size.width;\n }\n return this._size;\n };\n RenderTargetTexture.prototype.getRenderWidth = function () {\n if (this._size.width) {\n return this._size.width;\n }\n return this._size;\n };\n RenderTargetTexture.prototype.getRenderHeight = function () {\n if (this._size.width) {\n return this._size.height;\n }\n return this._size;\n };\n Object.defineProperty(RenderTargetTexture.prototype, \"canRescale\", {\n get: function () {\n return true;\n },\n enumerable: true,\n configurable: true\n });\n RenderTargetTexture.prototype.scale = function (ratio) {\n var newSize = this.getRenderSize() * ratio;\n this.resize(newSize);\n };\n RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {\n if (this.isCube) {\n return this._textureMatrix;\n }\n return _super.prototype.getReflectionTextureMatrix.call(this);\n };\n RenderTargetTexture.prototype.resize = function (size) {\n this.releaseInternalTexture();\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this._processSizeParameter(size);\n if (this.isCube) {\n this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);\n }\n else {\n this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);\n }\n };\n RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {\n if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }\n if (dumpForDebug === void 0) { dumpForDebug = false; }\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var engine = scene.getEngine();\n if (this.useCameraPostProcesses !== undefined) {\n useCameraPostProcess = this.useCameraPostProcesses;\n }\n if (this._waitingRenderList) {\n this.renderList = [];\n for (var index = 0; index < this._waitingRenderList.length; index++) {\n var id = this._waitingRenderList[index];\n var mesh_1 = scene.getMeshByID(id);\n if (mesh_1) {\n this.renderList.push(mesh_1);\n }\n }\n delete this._waitingRenderList;\n }\n // Is predicate defined?\n if (this.renderListPredicate) {\n if (this.renderList) {\n this.renderList.splice(0); // Clear previous renderList\n }\n else {\n this.renderList = [];\n }\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var sceneMeshes = scene.meshes;\n for (var index = 0; index < sceneMeshes.length; index++) {\n var mesh = sceneMeshes[index];\n if (this.renderListPredicate(mesh)) {\n this.renderList.push(mesh);\n }\n }\n }\n this.onBeforeBindObservable.notifyObservers(this);\n // Set custom projection.\n // Needs to be before binding to prevent changing the aspect ratio.\n var camera;\n if (this.activeCamera) {\n camera = this.activeCamera;\n engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());\n if (this.activeCamera !== scene.activeCamera) {\n scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));\n }\n }\n else {\n camera = scene.activeCamera;\n if (camera) {\n engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());\n }\n }\n // Prepare renderingManager\n this._renderingManager.reset();\n var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;\n var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;\n var sceneRenderId = scene.getRenderId();\n for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {\n var mesh = currentRenderList[meshIndex];\n if (mesh) {\n if (!mesh.isReady(this.refreshRate === 0)) {\n this.resetRefreshCounter();\n continue;\n }\n mesh._preActivateForIntermediateRendering(sceneRenderId);\n var isMasked = void 0;\n if (!this.renderList && camera) {\n isMasked = ((mesh.layerMask & camera.layerMask) === 0);\n }\n else {\n isMasked = false;\n }\n if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {\n mesh._activate(sceneRenderId);\n for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {\n var subMesh = mesh.subMeshes[subIndex];\n scene._activeIndices.addCount(subMesh.indexCount, false);\n this._renderingManager.dispatch(subMesh, mesh);\n }\n }\n }\n }\n for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {\n var particleSystem = scene.particleSystems[particleIndex];\n var emitter = particleSystem.emitter;\n if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {\n continue;\n }\n if (currentRenderList.indexOf(emitter) >= 0) {\n this._renderingManager.dispatchParticles(particleSystem);\n }\n }\n if (this.isCube) {\n for (var face = 0; face < 6; face++) {\n this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n }\n }\n else {\n this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);\n }\n this.onAfterUnbindObservable.notifyObservers(this);\n if (scene.activeCamera) {\n if (this.activeCamera && this.activeCamera !== scene.activeCamera) {\n scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));\n }\n engine.setViewport(scene.activeCamera.viewport);\n }\n scene.resetCachedMaterial();\n };\n RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {\n var minimum = 128;\n var x = renderDimension * scale;\n var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));\n // Ensure we don't exceed the render dimension (while staying POT)\n return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);\n };\n RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {\n var _this = this;\n if (!this._texture) {\n return;\n }\n engine.unBindFramebuffer(this._texture, this.isCube, function () {\n _this.onAfterRenderObservable.notifyObservers(faceIndex);\n });\n };\n RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var engine = scene.getEngine();\n if (!this._texture) {\n return;\n }\n // Bind\n if (this._postProcessManager) {\n this._postProcessManager._prepareFrame(this._texture, this._postProcesses);\n }\n else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {\n if (this._texture) {\n engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);\n }\n }\n this.onBeforeRenderObservable.notifyObservers(faceIndex);\n // Clear\n if (this.onClearObservable.hasObservers()) {\n this.onClearObservable.notifyObservers(engine);\n }\n else {\n engine.clear(this.clearColor || scene.clearColor, true, true, true);\n }\n if (!this._doNotChangeAspectRatio) {\n scene.updateTransformMatrix(true);\n }\n // Render\n this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);\n if (this._postProcessManager) {\n this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);\n }\n else if (useCameraPostProcess) {\n scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);\n }\n if (!this._doNotChangeAspectRatio) {\n scene.updateTransformMatrix(true);\n }\n // Dump ?\n if (dumpForDebug) {\n BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);\n }\n // Unbind\n if (!this.isCube || faceIndex === 5) {\n if (this.isCube) {\n if (faceIndex === 5) {\n engine.generateMipMapsForCubemap(this._texture);\n }\n }\n this.unbindFrameBuffer(engine, faceIndex);\n }\n else {\n this.onAfterRenderObservable.notifyObservers(faceIndex);\n }\n };\n /**\n * Overrides the default sort function applied in the renderging group to prepare the meshes.\n * This allowed control for front to back rendering or reversly depending of the special needs.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param opaqueSortCompareFn The opaque queue comparison function use to sort.\n * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.\n * @param transparentSortCompareFn The transparent queue comparison function use to sort.\n */\n RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {\n if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }\n if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }\n if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }\n this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);\n };\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n */\n RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {\n this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);\n this._renderingManager._useSceneAutoClearSetup = false;\n };\n RenderTargetTexture.prototype.clone = function () {\n var textureSize = this.getSize();\n var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // RenderTarget Texture\n newTexture.coordinatesMode = this.coordinatesMode;\n if (this.renderList) {\n newTexture.renderList = this.renderList.slice(0);\n }\n return newTexture;\n };\n RenderTargetTexture.prototype.serialize = function () {\n if (!this.name) {\n return null;\n }\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.renderTargetSize = this.getRenderSize();\n serializationObject.renderList = [];\n if (this.renderList) {\n for (var index = 0; index < this.renderList.length; index++) {\n serializationObject.renderList.push(this.renderList[index].id);\n }\n }\n return serializationObject;\n };\n // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore\n RenderTargetTexture.prototype.disposeFramebufferObjects = function () {\n var objBuffer = this.getInternalTexture();\n var scene = this.getScene();\n if (objBuffer && scene) {\n scene.getEngine()._releaseFramebufferObjects(objBuffer);\n }\n };\n RenderTargetTexture.prototype.dispose = function () {\n if (this._postProcessManager) {\n this._postProcessManager.dispose();\n this._postProcessManager = null;\n }\n this.clearPostProcesses(true);\n if (this._resizeObserver) {\n this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);\n this._resizeObserver = null;\n }\n this.renderList = null;\n // Remove from custom render targets\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var index = scene.customRenderTargets.indexOf(this);\n if (index >= 0) {\n scene.customRenderTargets.splice(index, 1);\n }\n for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {\n var camera = _a[_i];\n index = camera.customRenderTargets.indexOf(this);\n if (index >= 0) {\n camera.customRenderTargets.splice(index, 1);\n }\n }\n _super.prototype.dispose.call(this);\n };\n RenderTargetTexture.prototype._rebuild = function () {\n if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {\n this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;\n }\n if (this._postProcessManager) {\n this._postProcessManager._rebuild();\n }\n };\n /**\n * Clear the info related to rendering groups preventing retention point in material dispose.\n */\n RenderTargetTexture.prototype.freeRenderingGroups = function () {\n if (this._renderingManager) {\n this._renderingManager.freeRenderingGroups();\n }\n };\n RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;\n RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;\n RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;\n return RenderTargetTexture;\n }(BABYLON.Texture));\n BABYLON.RenderTargetTexture = RenderTargetTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.renderTargetTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n ;\n var MultiRenderTarget = /** @class */ (function (_super) {\n __extends(MultiRenderTarget, _super);\n function MultiRenderTarget(name, size, count, scene, options) {\n var _this = this;\n var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;\n var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;\n var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;\n _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;\n _this._engine = scene.getEngine();\n if (!_this.isSupported) {\n _this.dispose();\n return;\n }\n var types = [];\n var samplingModes = [];\n for (var i = 0; i < count; i++) {\n if (options && options.types && options.types[i] !== undefined) {\n types.push(options.types[i]);\n }\n else {\n types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n }\n if (options && options.samplingModes && options.samplingModes[i] !== undefined) {\n samplingModes.push(options.samplingModes[i]);\n }\n else {\n samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n }\n }\n var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;\n _this._size = size;\n _this._multiRenderTargetOptions = {\n samplingModes: samplingModes,\n generateMipMaps: generateMipMaps,\n generateDepthBuffer: generateDepthBuffer,\n generateStencilBuffer: generateStencilBuffer,\n generateDepthTexture: generateDepthTexture,\n types: types,\n textureCount: count\n };\n _this._createInternalTextures();\n _this._createTextures();\n return _this;\n }\n Object.defineProperty(MultiRenderTarget.prototype, \"isSupported\", {\n get: function () {\n return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MultiRenderTarget.prototype, \"textures\", {\n get: function () {\n return this._textures;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MultiRenderTarget.prototype, \"depthTexture\", {\n get: function () {\n return this._textures[this._textures.length - 1];\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MultiRenderTarget.prototype, \"wrapU\", {\n set: function (wrap) {\n if (this._textures) {\n for (var i = 0; i < this._textures.length; i++) {\n this._textures[i].wrapU = wrap;\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MultiRenderTarget.prototype, \"wrapV\", {\n set: function (wrap) {\n if (this._textures) {\n for (var i = 0; i < this._textures.length; i++) {\n this._textures[i].wrapV = wrap;\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n MultiRenderTarget.prototype._rebuild = function () {\n this.releaseInternalTextures();\n this._createInternalTextures();\n for (var i = 0; i < this._internalTextures.length; i++) {\n var texture = this._textures[i];\n texture._texture = this._internalTextures[i];\n }\n // Keeps references to frame buffer and stencil/depth buffer\n this._texture = this._internalTextures[0];\n };\n MultiRenderTarget.prototype._createInternalTextures = function () {\n this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);\n };\n MultiRenderTarget.prototype._createTextures = function () {\n this._textures = [];\n for (var i = 0; i < this._internalTextures.length; i++) {\n var texture = new BABYLON.Texture(null, this.getScene());\n texture._texture = this._internalTextures[i];\n this._textures.push(texture);\n }\n // Keeps references to frame buffer and stencil/depth buffer\n this._texture = this._internalTextures[0];\n };\n Object.defineProperty(MultiRenderTarget.prototype, \"samples\", {\n get: function () {\n return this._samples;\n },\n set: function (value) {\n if (this._samples === value) {\n return;\n }\n this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);\n },\n enumerable: true,\n configurable: true\n });\n MultiRenderTarget.prototype.resize = function (size) {\n this.releaseInternalTextures();\n this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);\n this._createInternalTextures();\n };\n MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {\n var _this = this;\n engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {\n _this.onAfterRenderObservable.notifyObservers(faceIndex);\n });\n };\n MultiRenderTarget.prototype.dispose = function () {\n this.releaseInternalTextures();\n _super.prototype.dispose.call(this);\n };\n MultiRenderTarget.prototype.releaseInternalTextures = function () {\n if (!this._internalTextures) {\n return;\n }\n for (var i = this._internalTextures.length - 1; i >= 0; i--) {\n if (this._internalTextures[i] !== undefined) {\n this._internalTextures[i].dispose();\n this._internalTextures.splice(i, 1);\n }\n }\n };\n return MultiRenderTarget;\n }(BABYLON.RenderTargetTexture));\n BABYLON.MultiRenderTarget = MultiRenderTarget;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.multiRenderTarget.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var MirrorTexture = /** @class */ (function (_super) {\n __extends(MirrorTexture, _super);\n function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }\n if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }\n var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;\n _this.scene = scene;\n _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);\n _this._transformMatrix = BABYLON.Matrix.Zero();\n _this._mirrorMatrix = BABYLON.Matrix.Zero();\n _this._adaptiveBlurKernel = 0;\n _this._blurKernelX = 0;\n _this._blurKernelY = 0;\n _this._blurRatio = 1.0;\n _this.ignoreCameraViewport = true;\n _this._updateGammaSpace();\n _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {\n _this._updateGammaSpace;\n });\n _this.onBeforeRenderObservable.add(function () {\n BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);\n _this._savedViewMatrix = scene.getViewMatrix();\n _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);\n scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());\n scene.clipPlane = _this.mirrorPlane;\n scene.getEngine().cullBackFaces = false;\n scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);\n });\n _this.onAfterRenderObservable.add(function () {\n scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());\n scene.getEngine().cullBackFaces = true;\n scene._mirroredCameraPosition = null;\n delete scene.clipPlane;\n });\n return _this;\n }\n Object.defineProperty(MirrorTexture.prototype, \"blurRatio\", {\n get: function () {\n return this._blurRatio;\n },\n set: function (value) {\n if (this._blurRatio === value) {\n return;\n }\n this._blurRatio = value;\n this._preparePostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MirrorTexture.prototype, \"adaptiveBlurKernel\", {\n set: function (value) {\n this._adaptiveBlurKernel = value;\n this._autoComputeBlurKernel();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MirrorTexture.prototype, \"blurKernel\", {\n set: function (value) {\n this.blurKernelX = value;\n this.blurKernelY = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MirrorTexture.prototype, \"blurKernelX\", {\n get: function () {\n return this._blurKernelX;\n },\n set: function (value) {\n if (this._blurKernelX === value) {\n return;\n }\n this._blurKernelX = value;\n this._preparePostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MirrorTexture.prototype, \"blurKernelY\", {\n get: function () {\n return this._blurKernelY;\n },\n set: function (value) {\n if (this._blurKernelY === value) {\n return;\n }\n this._blurKernelY = value;\n this._preparePostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n MirrorTexture.prototype._autoComputeBlurKernel = function () {\n var engine = this.getScene().getEngine();\n var dw = this.getRenderWidth() / engine.getRenderWidth();\n var dh = this.getRenderHeight() / engine.getRenderHeight();\n this.blurKernelX = this._adaptiveBlurKernel * dw;\n this.blurKernelY = this._adaptiveBlurKernel * dh;\n };\n MirrorTexture.prototype._onRatioRescale = function () {\n if (this._sizeRatio) {\n this.resize(this._initialSizeParameter);\n if (!this._adaptiveBlurKernel) {\n this._preparePostProcesses();\n }\n }\n if (this._adaptiveBlurKernel) {\n this._autoComputeBlurKernel();\n }\n };\n MirrorTexture.prototype._updateGammaSpace = function () {\n this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;\n };\n MirrorTexture.prototype._preparePostProcesses = function () {\n this.clearPostProcesses(true);\n if (this._blurKernelX && this._blurKernelY) {\n var engine = this.getScene().getEngine();\n var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n this._blurX = new BABYLON.BlurPostProcess(\"horizontal blur\", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);\n this._blurX.autoClear = false;\n if (this._blurRatio === 1 && this.samples < 2 && this._texture) {\n this._blurX.inputTexture = this._texture;\n }\n else {\n this._blurX.alwaysForcePOT = true;\n }\n this._blurY = new BABYLON.BlurPostProcess(\"vertical blur\", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);\n this._blurY.autoClear = false;\n this._blurY.alwaysForcePOT = this._blurRatio !== 1;\n this.addPostProcess(this._blurX);\n this.addPostProcess(this._blurY);\n }\n else {\n if (this._blurY) {\n this.removePostProcess(this._blurY);\n this._blurY.dispose();\n this._blurY = null;\n }\n if (this._blurX) {\n this.removePostProcess(this._blurX);\n this._blurX.dispose();\n this._blurX = null;\n }\n }\n };\n MirrorTexture.prototype.clone = function () {\n var scene = this.getScene();\n if (!scene) {\n return this;\n }\n var textureSize = this.getSize();\n var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // Mirror Texture\n newTexture.mirrorPlane = this.mirrorPlane.clone();\n if (this.renderList) {\n newTexture.renderList = this.renderList.slice(0);\n }\n return newTexture;\n };\n MirrorTexture.prototype.serialize = function () {\n if (!this.name) {\n return null;\n }\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.mirrorPlane = this.mirrorPlane.asArray();\n return serializationObject;\n };\n MirrorTexture.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);\n };\n return MirrorTexture;\n }(BABYLON.RenderTargetTexture));\n BABYLON.MirrorTexture = MirrorTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.mirrorTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Creates a refraction texture used by refraction channel of the standard material.\n * @param name the texture name\n * @param size size of the underlying texture\n * @param scene root scene\n */\n var RefractionTexture = /** @class */ (function (_super) {\n __extends(RefractionTexture, _super);\n function RefractionTexture(name, size, scene, generateMipMaps) {\n var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;\n _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);\n _this.depth = 2.0;\n _this.onBeforeRenderObservable.add(function () {\n scene.clipPlane = _this.refractionPlane;\n });\n _this.onAfterRenderObservable.add(function () {\n delete scene.clipPlane;\n });\n return _this;\n }\n RefractionTexture.prototype.clone = function () {\n var scene = this.getScene();\n if (!scene) {\n return this;\n }\n var textureSize = this.getSize();\n var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // Refraction Texture\n newTexture.refractionPlane = this.refractionPlane.clone();\n if (this.renderList) {\n newTexture.renderList = this.renderList.slice(0);\n }\n newTexture.depth = this.depth;\n return newTexture;\n };\n RefractionTexture.prototype.serialize = function () {\n if (!this.name) {\n return null;\n }\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.mirrorPlane = this.refractionPlane.asArray();\n serializationObject.depth = this.depth;\n return serializationObject;\n };\n return RefractionTexture;\n }(BABYLON.RenderTargetTexture));\n BABYLON.RefractionTexture = RefractionTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.refractionTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A class extending {BABYLON.Texture} allowing drawing on a texture\n * @see http://doc.babylonjs.com/how_to/dynamictexture\n */\n var DynamicTexture = /** @class */ (function (_super) {\n __extends(DynamicTexture, _super);\n /**\n * Creates a {BABYLON.DynamicTexture}\n * @param name defines the name of the texture\n * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height\n * @param scene defines the scene where you want the texture\n * @param generateMipMaps defines the use of MinMaps or not (default is false)\n * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)\n * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)\n */\n function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {\n if (scene === void 0) { scene = null; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }\n var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;\n _this.name = name;\n _this._engine = _this.getScene().getEngine();\n _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this._generateMipMaps = generateMipMaps;\n if (options.getContext) {\n _this._canvas = options;\n _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);\n }\n else {\n _this._canvas = document.createElement(\"canvas\");\n if (options.width || options.width === 0) {\n _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);\n }\n else {\n _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);\n }\n }\n var textureSize = _this.getSize();\n _this._canvas.width = textureSize.width;\n _this._canvas.height = textureSize.height;\n _this._context = _this._canvas.getContext(\"2d\");\n return _this;\n }\n Object.defineProperty(DynamicTexture.prototype, \"canRescale\", {\n /**\n * Gets the current state of canRescale\n */\n get: function () {\n return true;\n },\n enumerable: true,\n configurable: true\n });\n DynamicTexture.prototype._recreate = function (textureSize) {\n this._canvas.width = textureSize.width;\n this._canvas.height = textureSize.height;\n this.releaseInternalTexture();\n this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);\n };\n /**\n * Scales the texture\n * @param ratio the scale factor to apply to both width and height\n */\n DynamicTexture.prototype.scale = function (ratio) {\n var textureSize = this.getSize();\n textureSize.width *= ratio;\n textureSize.height *= ratio;\n this._recreate(textureSize);\n };\n /**\n * Resizes the texture\n * @param width the new width\n * @param height the new height\n */\n DynamicTexture.prototype.scaleTo = function (width, height) {\n var textureSize = this.getSize();\n textureSize.width = width;\n textureSize.height = height;\n this._recreate(textureSize);\n };\n /**\n * Gets the context of the canvas used by the texture\n * @returns the canvas context of the dynamic texture\n */\n DynamicTexture.prototype.getContext = function () {\n return this._context;\n };\n /**\n * Clears the texture\n */\n DynamicTexture.prototype.clear = function () {\n var size = this.getSize();\n this._context.fillRect(0, 0, size.width, size.height);\n };\n /**\n * Updates the texture\n * @param invertY defines the direction for the Y axis (default is true - y increases downwards)\n * @param premulAlpha defines if alpha is stored as premultiplied (default is false)\n */\n DynamicTexture.prototype.update = function (invertY, premulAlpha) {\n if (premulAlpha === void 0) { premulAlpha = false; }\n this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);\n };\n /**\n * Draws text onto the texture\n * @param text defines the text to be drawn\n * @param x defines the placement of the text from the left\n * @param y defines the placement of the text from the top when invertY is true and from the bottom when false\n * @param font defines the font to be used with font-style, font-size, font-name\n * @param color defines the color used for the text\n * @param clearColor defines the color for the canvas, use null to not overwrite canvas\n * @param invertY defines the direction for the Y axis (default is true - y increases downwards)\n * @param update defines whether texture is immediately update (default is true)\n */\n DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {\n if (update === void 0) { update = true; }\n var size = this.getSize();\n if (clearColor) {\n this._context.fillStyle = clearColor;\n this._context.fillRect(0, 0, size.width, size.height);\n }\n this._context.font = font;\n if (x === null || x === undefined) {\n var textSize = this._context.measureText(text);\n x = (size.width - textSize.width) / 2;\n }\n if (y === null || y === undefined) {\n var fontSize = parseInt((font.replace(/\\D/g, '')));\n y = (size.height / 2) + (fontSize / 3.65);\n }\n this._context.fillStyle = color;\n this._context.fillText(text, x, y);\n if (update) {\n this.update(invertY);\n }\n };\n /**\n * Clones the texture\n * @returns the clone of the texture.\n */\n DynamicTexture.prototype.clone = function () {\n var scene = this.getScene();\n if (!scene) {\n return this;\n }\n var textureSize = this.getSize();\n var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // Dynamic Texture\n newTexture.wrapU = this.wrapU;\n newTexture.wrapV = this.wrapV;\n return newTexture;\n };\n /**\n * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized\n * @returns a serialized dynamic texture object\n */\n DynamicTexture.prototype.serialize = function () {\n var scene = this.getScene();\n if (scene && !scene.isReady()) {\n BABYLON.Tools.Warn(\"The scene must be ready before serializing the dynamic texture\");\n }\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.base64String = this._canvas.toDataURL();\n serializationObject.invertY = this._invertY;\n serializationObject.samplingMode = this.samplingMode;\n return serializationObject;\n };\n /** @hidden */\n DynamicTexture.prototype._rebuild = function () {\n this.update();\n };\n return DynamicTexture;\n }(BABYLON.Texture));\n BABYLON.DynamicTexture = DynamicTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.dynamicTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var VideoTexture = /** @class */ (function (_super) {\n __extends(VideoTexture, _super);\n /**\n * Creates a video texture.\n * Sample : https://doc.babylonjs.com/how_to/video_texture\n * @param {string | null} name optional name, will detect from video source, if not defined\n * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.\n * @param {BABYLON.Scene} scene is obviously the current scene.\n * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).\n * @param {boolean} invertY is false by default but can be used to invert video on Y axis\n * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default\n * @param {VideoTextureSettings} [settings] allows finer control over video usage\n */\n function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {\n if (generateMipMaps === void 0) { generateMipMaps = false; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (settings === void 0) { settings = {\n autoPlay: true,\n loop: true,\n autoUpdateTexture: true,\n }; }\n var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;\n _this._onUserActionRequestedObservable = null;\n _this._stillImageCaptured = false;\n _this._poster = false;\n _this._createInternalTexture = function () {\n if (_this._texture != null) {\n if (_this._poster) {\n _this._texture.dispose();\n _this._poster = false;\n }\n else {\n return;\n }\n }\n if (!_this._engine.needPOTTextures ||\n (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {\n _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n }\n else {\n _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this._generateMipMaps = false;\n }\n _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);\n if (!_this.video.autoplay) {\n var oldHandler_1 = _this.video.onplaying;\n var error_1 = false;\n _this.video.onplaying = function () {\n _this.video.onplaying = oldHandler_1;\n _this._texture.isReady = true;\n _this._updateInternalTexture();\n if (!error_1) {\n _this.video.pause();\n }\n if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {\n _this.onLoadObservable.notifyObservers(_this);\n }\n };\n var playing = _this.video.play();\n if (playing) {\n playing.then(function () {\n // Everything is good.\n })\n .catch(function () {\n error_1 = true;\n // On Chrome for instance, new policies might prevent playing without user interaction.\n if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {\n _this._onUserActionRequestedObservable.notifyObservers(_this);\n }\n });\n }\n else {\n _this.video.onplaying = oldHandler_1;\n _this._texture.isReady = true;\n _this._updateInternalTexture();\n if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {\n _this.onLoadObservable.notifyObservers(_this);\n }\n }\n }\n else {\n _this._texture.isReady = true;\n _this._updateInternalTexture();\n if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {\n _this.onLoadObservable.notifyObservers(_this);\n }\n }\n };\n _this.reset = function () {\n if (_this._texture == null) {\n return;\n }\n if (!_this._poster) {\n _this._texture.dispose();\n _this._texture = null;\n }\n };\n _this._updateInternalTexture = function (e) {\n if (_this._texture == null || !_this._texture.isReady) {\n return;\n }\n if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {\n return;\n }\n _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);\n };\n _this._engine = _this.getScene().getEngine();\n _this._generateMipMaps = generateMipMaps;\n _this._samplingMode = samplingMode;\n _this.autoUpdateTexture = settings.autoUpdateTexture;\n _this.name = name || _this._getName(src);\n _this.video = _this._getVideo(src);\n if (settings.poster) {\n _this.video.poster = settings.poster;\n }\n if (settings.autoPlay !== undefined) {\n _this.video.autoplay = settings.autoPlay;\n }\n if (settings.loop !== undefined) {\n _this.video.loop = settings.loop;\n }\n _this.video.setAttribute(\"playsinline\", \"\");\n _this.video.addEventListener(\"canplay\", _this._createInternalTexture);\n _this.video.addEventListener(\"paused\", _this._updateInternalTexture);\n _this.video.addEventListener(\"seeked\", _this._updateInternalTexture);\n _this.video.addEventListener(\"emptied\", _this.reset);\n if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {\n _this._createInternalTexture();\n }\n if (settings.poster) {\n _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);\n _this._poster = true;\n }\n return _this;\n }\n Object.defineProperty(VideoTexture.prototype, \"onUserActionRequestedObservable\", {\n get: function () {\n if (!this._onUserActionRequestedObservable) {\n this._onUserActionRequestedObservable = new BABYLON.Observable();\n }\n return this._onUserActionRequestedObservable;\n },\n enumerable: true,\n configurable: true\n });\n VideoTexture.prototype._getName = function (src) {\n if (src instanceof HTMLVideoElement) {\n return src.currentSrc;\n }\n if (typeof src === \"object\") {\n return src.toString();\n }\n return src;\n };\n ;\n VideoTexture.prototype._getVideo = function (src) {\n if (src instanceof HTMLVideoElement) {\n BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);\n return src;\n }\n var video = document.createElement(\"video\");\n if (typeof src === \"string\") {\n BABYLON.Tools.SetCorsBehavior(src, video);\n video.src = src;\n }\n else {\n BABYLON.Tools.SetCorsBehavior(src[0], video);\n src.forEach(function (url) {\n var source = document.createElement(\"source\");\n source.src = url;\n video.appendChild(source);\n });\n }\n return video;\n };\n ;\n /**\n * Internal method to initiate `update`.\n */\n VideoTexture.prototype._rebuild = function () {\n this.update();\n };\n /**\n * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.\n */\n VideoTexture.prototype.update = function () {\n if (!this.autoUpdateTexture) {\n // Expecting user to call `updateTexture` manually\n return;\n }\n this.updateTexture(true);\n };\n /**\n * Update Texture in `manual` mode. Does not do anything if not visible or paused.\n * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.\n */\n VideoTexture.prototype.updateTexture = function (isVisible) {\n if (!isVisible) {\n return;\n }\n if (this.video.paused && this._stillImageCaptured) {\n return;\n }\n this._stillImageCaptured = true;\n this._updateInternalTexture();\n };\n /**\n * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.\n * @param url New url.\n */\n VideoTexture.prototype.updateURL = function (url) {\n this.video.src = url;\n };\n VideoTexture.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n if (this._onUserActionRequestedObservable) {\n this._onUserActionRequestedObservable.clear();\n this._onUserActionRequestedObservable = null;\n }\n this.video.removeEventListener(\"canplay\", this._createInternalTexture);\n this.video.removeEventListener(\"paused\", this._updateInternalTexture);\n this.video.removeEventListener(\"seeked\", this._updateInternalTexture);\n this.video.removeEventListener(\"emptied\", this.reset);\n this.video.pause();\n };\n VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {\n var video = document.createElement(\"video\");\n video.setAttribute('autoplay', '');\n video.setAttribute('muted', '');\n video.setAttribute('playsinline', '');\n var constraintsDeviceId;\n if (constraints && constraints.deviceId) {\n constraintsDeviceId = {\n exact: constraints.deviceId,\n };\n }\n window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;\n if (navigator.mediaDevices) {\n navigator.mediaDevices.getUserMedia({ video: constraints })\n .then(function (stream) {\n if (video.mozSrcObject !== undefined) {\n // hack for Firefox < 19\n video.mozSrcObject = stream;\n }\n else {\n video.srcObject = stream;\n }\n var onPlaying = function () {\n if (onReady) {\n onReady(new VideoTexture(\"video\", video, scene, true, true));\n }\n video.removeEventListener(\"playing\", onPlaying);\n };\n video.addEventListener(\"playing\", onPlaying);\n video.play();\n })\n .catch(function (err) {\n BABYLON.Tools.Error(err.name);\n });\n }\n else {\n navigator.getUserMedia =\n navigator.getUserMedia ||\n navigator.webkitGetUserMedia ||\n navigator.mozGetUserMedia ||\n navigator.msGetUserMedia;\n if (navigator.getUserMedia) {\n navigator.getUserMedia({\n video: {\n deviceId: constraintsDeviceId,\n width: {\n min: (constraints && constraints.minWidth) || 256,\n max: (constraints && constraints.maxWidth) || 640,\n },\n height: {\n min: (constraints && constraints.minHeight) || 256,\n max: (constraints && constraints.maxHeight) || 480,\n },\n },\n }, function (stream) {\n if (video.mozSrcObject !== undefined) {\n // hack for Firefox < 19\n video.mozSrcObject = stream;\n }\n else {\n video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;\n }\n video.play();\n if (onReady) {\n onReady(new VideoTexture(\"video\", video, scene, true, true));\n }\n }, function (e) {\n BABYLON.Tools.Error(e.name);\n });\n }\n }\n };\n return VideoTexture;\n }(BABYLON.Texture));\n BABYLON.VideoTexture = VideoTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.videoTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var RawTexture = /** @class */ (function (_super) {\n __extends(RawTexture, _super);\n function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;\n _this.format = format;\n _this._engine = scene.getEngine();\n _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);\n _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n return _this;\n }\n RawTexture.prototype.update = function (data) {\n this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);\n };\n // Statics\n RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);\n };\n RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);\n };\n RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);\n };\n RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);\n };\n RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);\n };\n RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }\n return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);\n };\n return RawTexture;\n }(BABYLON.Texture));\n BABYLON.RawTexture = RawTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.rawTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to store 3D textures containing user data\n */\n var RawTexture3D = /** @class */ (function (_super) {\n __extends(RawTexture3D, _super);\n /**\n * Create a new RawTexture3D\n * @param data defines the data of the texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param depth defines the depth of the texture\n * @param format defines the texture format to use\n * @param scene defines the hosting scene\n * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)\n * @param invertY defines if texture must be stored with Y axis inverted\n * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)\n * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)\n */\n function RawTexture3D(data, width, height, depth, \n /** Gets or sets the texture format to use */\n format, scene, generateMipMaps, invertY, samplingMode, textureType) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;\n _this.format = format;\n _this._engine = scene.getEngine();\n _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);\n _this.is3D = true;\n return _this;\n }\n /**\n * Update the texture with new data\n * @param data defines the data to store in the texture\n */\n RawTexture3D.prototype.update = function (data) {\n if (!this._texture) {\n return;\n }\n this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);\n };\n return RawTexture3D;\n }(BABYLON.Texture));\n BABYLON.RawTexture3D = RawTexture3D;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.rawTexture3D.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * PostProcessManager is used to manage one or more post processes or post process pipelines\n * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses\n */\n var PostProcessManager = /** @class */ (function () {\n /**\n * Creates a new instance PostProcess\n * @param scene The scene that the post process is associated with.\n */\n function PostProcessManager(scene) {\n this._vertexBuffers = {};\n this._scene = scene;\n }\n PostProcessManager.prototype._prepareBuffers = function () {\n if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {\n return;\n }\n // VBO\n var vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);\n this._buildIndexBuffer();\n };\n PostProcessManager.prototype._buildIndexBuffer = function () {\n // Indices\n var indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);\n };\n /**\n * Rebuilds the vertex buffers of the manager.\n */\n PostProcessManager.prototype._rebuild = function () {\n var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (!vb) {\n return;\n }\n vb._rebuild();\n this._buildIndexBuffer();\n };\n // Methods\n /**\n * Prepares a frame to be run through a post process.\n * @param sourceTexture The input texture to the post procesess. (default: null)\n * @param postProcesses An array of post processes to be run. (default: null)\n * @returns True if the post processes were able to be run.\n */\n PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {\n if (sourceTexture === void 0) { sourceTexture = null; }\n if (postProcesses === void 0) { postProcesses = null; }\n var camera = this._scene.activeCamera;\n if (!camera) {\n return false;\n }\n var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });\n if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {\n return false;\n }\n postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);\n return true;\n };\n /**\n * Manually render a set of post processes to a texture.\n * @param postProcesses An array of post processes to be run.\n * @param targetTexture The target texture to render to.\n * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight\n * @param faceIndex defines the face to render to if a cubemap is defined as the target\n * @param lodLevel defines which lod of the texture to render to\n */\n PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {\n if (targetTexture === void 0) { targetTexture = null; }\n if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lodLevel === void 0) { lodLevel = 0; }\n var engine = this._scene.getEngine();\n for (var index = 0; index < postProcesses.length; index++) {\n if (index < postProcesses.length - 1) {\n postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);\n }\n else {\n if (targetTexture) {\n engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);\n }\n else {\n engine.restoreDefaultFramebuffer();\n }\n }\n var pp = postProcesses[index];\n var effect = pp.apply();\n if (effect) {\n pp.onBeforeRenderObservable.notifyObservers(effect);\n // VBOs\n this._prepareBuffers();\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n // Draw order\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n pp.onAfterRenderObservable.notifyObservers(effect);\n }\n }\n // Restore depth buffer\n engine.setDepthBuffer(true);\n engine.setDepthWrite(true);\n };\n /**\n * Finalize the result of the output of the postprocesses.\n * @param doNotPresent If true the result will not be displayed to the screen.\n * @param targetTexture The target texture to render to.\n * @param faceIndex The index of the face to bind the target texture to.\n * @param postProcesses The array of post processes to render.\n * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)\n */\n PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {\n if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }\n var camera = this._scene.activeCamera;\n if (!camera) {\n return;\n }\n postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });\n if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {\n return;\n }\n var engine = this._scene.getEngine();\n for (var index = 0, len = postProcesses.length; index < len; index++) {\n var pp = postProcesses[index];\n if (index < len - 1) {\n pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);\n }\n else {\n if (targetTexture) {\n engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);\n pp._outputTexture = targetTexture;\n }\n else {\n engine.restoreDefaultFramebuffer();\n pp._outputTexture = null;\n }\n }\n if (doNotPresent) {\n break;\n }\n var effect = pp.apply();\n if (effect) {\n pp.onBeforeRenderObservable.notifyObservers(effect);\n // VBOs\n this._prepareBuffers();\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n // Draw order\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n pp.onAfterRenderObservable.notifyObservers(effect);\n }\n }\n // Restore states\n engine.setDepthBuffer(true);\n engine.setDepthWrite(true);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n };\n /**\n * Disposes of the post process manager.\n */\n PostProcessManager.prototype.dispose = function () {\n var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (buffer) {\n buffer.dispose();\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n };\n return PostProcessManager;\n }());\n BABYLON.PostProcessManager = PostProcessManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.postProcessManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * PostProcess can be used to apply a shader to a texture after it has been rendered\n * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses\n */\n var PostProcess = /** @class */ (function () {\n /**\n * Creates a new instance PostProcess\n * @param name The name of the PostProcess.\n * @param fragmentUrl The url of the fragment shader to be used.\n * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.\n * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.\n * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param defines String of defines that will be set when running the fragment shader. (default: null)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param vertexUrl The url of the vertex shader to be used. (default: \"postprocess\")\n * @param indexParameters The index parameters to be used for babylons include syntax \"#include[0..varyingCount]\". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx\n * @param blockCompilation If the shader should not be compiled imediatly. (default: false)\n */\n function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }\n if (defines === void 0) { defines = null; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (vertexUrl === void 0) { vertexUrl = \"postprocess\"; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n this.name = name;\n /**\n * Width of the texture to apply the post process on\n */\n this.width = -1;\n /**\n * Height of the texture to apply the post process on\n */\n this.height = -1;\n /**\n * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)\n */\n this._outputTexture = null;\n /**\n * If the buffer needs to be cleared before applying the post process. (default: true)\n * Should be set to false if shader will overwrite all previous pixels.\n */\n this.autoClear = true;\n /**\n * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)\n */\n this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;\n /**\n * Animations to be used for the post processing\n */\n this.animations = new Array();\n /**\n * Enable Pixel Perfect mode where texture is not scaled to be power of 2.\n * Can only be used on a single postprocess or on the last one of a chain. (default: false)\n */\n this.enablePixelPerfectMode = false;\n /**\n * Force the postprocess to be applied without taking in account viewport\n */\n this.forceFullscreenViewport = true;\n /**\n * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)\n *\n * | Value | Type | Description |\n * | ----- | ----------------------------------- | ----------- |\n * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |\n * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |\n * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |\n *\n */\n this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;\n /**\n * Force textures to be a power of two (default: false)\n */\n this.alwaysForcePOT = false;\n /**\n * Number of sample textures (default: 1)\n */\n this.samples = 1;\n /**\n * Modify the scale of the post process to be the same as the viewport (default: false)\n */\n this.adaptScaleToCurrentViewport = false;\n this._reusable = false;\n /**\n * Smart array of input and output textures for the post process.\n */\n this._textures = new BABYLON.SmartArray(2);\n /**\n * The index in _textures that corresponds to the output texture.\n */\n this._currentRenderTextureInd = 0;\n this._scaleRatio = new BABYLON.Vector2(1, 1);\n this._texelSize = BABYLON.Vector2.Zero();\n // Events\n /**\n * An event triggered when the postprocess is activated.\n */\n this.onActivateObservable = new BABYLON.Observable();\n /**\n * An event triggered when the postprocess changes its size.\n */\n this.onSizeChangedObservable = new BABYLON.Observable();\n /**\n * An event triggered when the postprocess applies its effect.\n */\n this.onApplyObservable = new BABYLON.Observable();\n /**\n * An event triggered before rendering the postprocess\n */\n this.onBeforeRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered after rendering the postprocess\n */\n this.onAfterRenderObservable = new BABYLON.Observable();\n if (camera != null) {\n this._camera = camera;\n this._scene = camera.getScene();\n camera.attachPostProcess(this);\n this._engine = this._scene.getEngine();\n this._scene.postProcesses.push(this);\n }\n else if (engine) {\n this._engine = engine;\n this._engine.postProcesses.push(this);\n }\n this._options = options;\n this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;\n this._reusable = reusable || false;\n this._textureType = textureType;\n this._samplers = samplers || [];\n this._samplers.push(\"textureSampler\");\n this._fragmentUrl = fragmentUrl;\n this._vertexUrl = vertexUrl;\n this._parameters = parameters || [];\n this._parameters.push(\"scale\");\n this._indexParameters = indexParameters;\n if (!blockCompilation) {\n this.updateEffect(defines);\n }\n }\n Object.defineProperty(PostProcess.prototype, \"onActivate\", {\n /**\n * A function that is added to the onActivateObservable\n */\n set: function (callback) {\n if (this._onActivateObserver) {\n this.onActivateObservable.remove(this._onActivateObserver);\n }\n if (callback) {\n this._onActivateObserver = this.onActivateObservable.add(callback);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PostProcess.prototype, \"onSizeChanged\", {\n /**\n * A function that is added to the onSizeChangedObservable\n */\n set: function (callback) {\n if (this._onSizeChangedObserver) {\n this.onSizeChangedObservable.remove(this._onSizeChangedObserver);\n }\n this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PostProcess.prototype, \"onApply\", {\n /**\n * A function that is added to the onApplyObservable\n */\n set: function (callback) {\n if (this._onApplyObserver) {\n this.onApplyObservable.remove(this._onApplyObserver);\n }\n this._onApplyObserver = this.onApplyObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PostProcess.prototype, \"onBeforeRender\", {\n /**\n * A function that is added to the onBeforeRenderObservable\n */\n set: function (callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PostProcess.prototype, \"onAfterRender\", {\n /**\n * A function that is added to the onAfterRenderObservable\n */\n set: function (callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PostProcess.prototype, \"inputTexture\", {\n /**\n * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will\n * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.\n */\n get: function () {\n return this._textures.data[this._currentRenderTextureInd];\n },\n set: function (value) {\n this._forcedOutputTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the camera which post process is applied to.\n * @returns The camera the post process is applied to.\n */\n PostProcess.prototype.getCamera = function () {\n return this._camera;\n };\n Object.defineProperty(PostProcess.prototype, \"texelSize\", {\n /**\n * Gets the texel size of the postprocess.\n * See https://en.wikipedia.org/wiki/Texel_(graphics)\n */\n get: function () {\n if (this._shareOutputWithPostProcess) {\n return this._shareOutputWithPostProcess.texelSize;\n }\n if (this._forcedOutputTexture) {\n this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);\n }\n return this._texelSize;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the engine which this post process belongs to.\n * @returns The engine the post process was enabled with.\n */\n PostProcess.prototype.getEngine = function () {\n return this._engine;\n };\n /**\n * The effect that is created when initializing the post process.\n * @returns The created effect corrisponding the the postprocess.\n */\n PostProcess.prototype.getEffect = function () {\n return this._effect;\n };\n /**\n * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.\n * @param postProcess The post process to share the output with.\n * @returns This post process.\n */\n PostProcess.prototype.shareOutputWith = function (postProcess) {\n this._disposeTextures();\n this._shareOutputWithPostProcess = postProcess;\n return this;\n };\n /**\n * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.\n * This should be called if the post process that shares output with this post process is disabled/disposed.\n */\n PostProcess.prototype.useOwnOutput = function () {\n if (this._textures.length == 0) {\n this._textures = new BABYLON.SmartArray(2);\n }\n this._shareOutputWithPostProcess = null;\n };\n /**\n * Updates the effect with the current post process compile time values and recompiles the shader.\n * @param defines Define statements that should be added at the beginning of the shader. (default: null)\n * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)\n * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)\n * @param indexParameters The index parameters to be used for babylons include syntax \"#include[0..varyingCount]\". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx\n * @param onCompiled Called when the shader has been compiled.\n * @param onError Called if there is an error when compiling a shader.\n */\n PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {\n if (defines === void 0) { defines = null; }\n if (uniforms === void 0) { uniforms = null; }\n if (samplers === void 0) { samplers = null; }\n this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, [\"position\"], uniforms || this._parameters, samplers || this._samplers, defines !== null ? defines : \"\", undefined, onCompiled, onError, indexParameters || this._indexParameters);\n };\n /**\n * The post process is reusable if it can be used multiple times within one frame.\n * @returns If the post process is reusable\n */\n PostProcess.prototype.isReusable = function () {\n return this._reusable;\n };\n /** invalidate frameBuffer to hint the postprocess to create a depth buffer */\n PostProcess.prototype.markTextureDirty = function () {\n this.width = -1;\n };\n /**\n * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.\n * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.\n * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.\n * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)\n * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)\n * @returns The target texture that was bound to be written to.\n */\n PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {\n var _this = this;\n if (sourceTexture === void 0) { sourceTexture = null; }\n camera = camera || this._camera;\n var scene = camera.getScene();\n var engine = scene.getEngine();\n var maxSize = engine.getCaps().maxTextureSize;\n var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;\n var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;\n // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen\n var webVRCamera = camera.parent;\n if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {\n requiredWidth /= 2;\n }\n var desiredWidth = (this._options.width || requiredWidth);\n var desiredHeight = this._options.height || requiredHeight;\n if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {\n if (this.adaptScaleToCurrentViewport) {\n var currentViewport = engine.currentViewport;\n if (currentViewport) {\n desiredWidth *= currentViewport.width;\n desiredHeight *= currentViewport.height;\n }\n }\n if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {\n if (!this._options.width) {\n desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;\n }\n if (!this._options.height) {\n desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;\n }\n }\n if (this.width !== desiredWidth || this.height !== desiredHeight) {\n if (this._textures.length > 0) {\n for (var i = 0; i < this._textures.length; i++) {\n this._engine._releaseTexture(this._textures.data[i]);\n }\n this._textures.reset();\n }\n this.width = desiredWidth;\n this.height = desiredHeight;\n var textureSize = { width: this.width, height: this.height };\n var textureOptions = {\n generateMipMaps: false,\n generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,\n generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,\n samplingMode: this.renderTargetSamplingMode,\n type: this._textureType\n };\n this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));\n if (this._reusable) {\n this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));\n }\n this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);\n this.onSizeChangedObservable.notifyObservers(this);\n }\n this._textures.forEach(function (texture) {\n if (texture.samples !== _this.samples) {\n _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);\n }\n });\n }\n var target;\n if (this._shareOutputWithPostProcess) {\n target = this._shareOutputWithPostProcess.inputTexture;\n }\n else if (this._forcedOutputTexture) {\n target = this._forcedOutputTexture;\n this.width = this._forcedOutputTexture.width;\n this.height = this._forcedOutputTexture.height;\n }\n else {\n target = this.inputTexture;\n }\n // Bind the input of this post process to be used as the output of the previous post process.\n if (this.enablePixelPerfectMode) {\n this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);\n this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);\n }\n else {\n this._scaleRatio.copyFromFloats(1, 1);\n this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);\n }\n this.onActivateObservable.notifyObservers(camera);\n // Clear\n if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {\n this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);\n }\n if (this._reusable) {\n this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;\n }\n return target;\n };\n Object.defineProperty(PostProcess.prototype, \"isSupported\", {\n /**\n * If the post process is supported.\n */\n get: function () {\n return this._effect.isSupported;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PostProcess.prototype, \"aspectRatio\", {\n /**\n * The aspect ratio of the output texture.\n */\n get: function () {\n if (this._shareOutputWithPostProcess) {\n return this._shareOutputWithPostProcess.aspectRatio;\n }\n if (this._forcedOutputTexture) {\n return this._forcedOutputTexture.width / this._forcedOutputTexture.height;\n }\n return this.width / this.height;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Get a value indicating if the post-process is ready to be used\n * @returns true if the post-process is ready (shader is compiled)\n */\n PostProcess.prototype.isReady = function () {\n return this._effect && this._effect.isReady();\n };\n /**\n * Binds all textures and uniforms to the shader, this will be run on every pass.\n * @returns the effect corrisponding to this post process. Null if not compiled or not ready.\n */\n PostProcess.prototype.apply = function () {\n // Check\n if (!this._effect || !this._effect.isReady())\n return null;\n // States\n this._engine.enableEffect(this._effect);\n this._engine.setState(false);\n this._engine.setDepthBuffer(false);\n this._engine.setDepthWrite(false);\n // Alpha\n this._engine.setAlphaMode(this.alphaMode);\n if (this.alphaConstants) {\n this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);\n }\n // Bind the output texture of the preivous post process as the input to this post process. \n var source;\n if (this._shareOutputWithPostProcess) {\n source = this._shareOutputWithPostProcess.inputTexture;\n }\n else if (this._forcedOutputTexture) {\n source = this._forcedOutputTexture;\n }\n else {\n source = this.inputTexture;\n }\n this._effect._bindTexture(\"textureSampler\", source);\n // Parameters\n this._effect.setVector2(\"scale\", this._scaleRatio);\n this.onApplyObservable.notifyObservers(this._effect);\n return this._effect;\n };\n PostProcess.prototype._disposeTextures = function () {\n if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {\n return;\n }\n if (this._textures.length > 0) {\n for (var i = 0; i < this._textures.length; i++) {\n this._engine._releaseTexture(this._textures.data[i]);\n }\n }\n this._textures.dispose();\n };\n /**\n * Disposes the post process.\n * @param camera The camera to dispose the post process on.\n */\n PostProcess.prototype.dispose = function (camera) {\n camera = camera || this._camera;\n this._disposeTextures();\n if (this._scene) {\n var index_1 = this._scene.postProcesses.indexOf(this);\n if (index_1 !== -1) {\n this._scene.postProcesses.splice(index_1, 1);\n }\n }\n else {\n var index_2 = this._engine.postProcesses.indexOf(this);\n if (index_2 !== -1) {\n this._engine.postProcesses.splice(index_2, 1);\n }\n }\n if (!camera) {\n return;\n }\n camera.detachPostProcess(this);\n var index = camera._postProcesses.indexOf(this);\n if (index === 0 && camera._postProcesses.length > 0) {\n var firstPostProcess = this._camera._getFirstPostProcess();\n if (firstPostProcess) {\n firstPostProcess.markTextureDirty();\n }\n }\n this.onActivateObservable.clear();\n this.onAfterRenderObservable.clear();\n this.onApplyObservable.clear();\n this.onBeforeRenderObservable.clear();\n this.onSizeChangedObservable.clear();\n };\n return PostProcess;\n }());\n BABYLON.PostProcess = PostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.postProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var PassPostProcess = /** @class */ (function (_super) {\n __extends(PassPostProcess, _super);\n function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (camera === void 0) { camera = null; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n return _super.call(this, name, \"pass\", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;\n }\n return PassPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.PassPostProcess = PassPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.passPostProcess.js.map\n\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Default implementation IShadowGenerator.\n * This is the main object responsible of generating shadows in the framework.\n * Documentation: https://doc.babylonjs.com/babylon101/shadows\n */\n var ShadowGenerator = /** @class */ (function () {\n /**\n * Creates a ShadowGenerator object.\n * A ShadowGenerator is the required tool to use the shadows.\n * Each light casting shadows needs to use its own ShadowGenerator.\n * Documentation : http://doc.babylonjs.com/tutorials/shadows\n * @param mapSize The size of the texture what stores the shadows. Example : 1024.\n * @param light The light object generating the shadows.\n * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.\n */\n function ShadowGenerator(mapSize, light, useFullFloatFirst) {\n this._bias = 0.00005;\n this._normalBias = 0;\n this._blurBoxOffset = 1;\n this._blurScale = 2;\n this._blurKernel = 1;\n this._useKernelBlur = false;\n this._filter = ShadowGenerator.FILTER_NONE;\n this._filteringQuality = ShadowGenerator.QUALITY_HIGH;\n this._contactHardeningLightSizeUVRatio = 0.1;\n this._darkness = 0;\n this._transparencyShadow = false;\n /**\n * Controls the extent to which the shadows fade out at the edge of the frustum\n * Used only by directionals and spots\n */\n this.frustumEdgeFalloff = 0;\n /**\n * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.\n * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.\n * It might on the other hand introduce peter panning.\n */\n this.forceBackFacesOnly = false;\n this._lightDirection = BABYLON.Vector3.Zero();\n this._viewMatrix = BABYLON.Matrix.Zero();\n this._projectionMatrix = BABYLON.Matrix.Zero();\n this._transformMatrix = BABYLON.Matrix.Zero();\n this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._currentFaceIndex = 0;\n this._currentFaceIndexCache = 0;\n this._defaultTextureMatrix = BABYLON.Matrix.Identity();\n this._mapSize = mapSize;\n this._light = light;\n this._scene = light.getScene();\n light._shadowGenerator = this;\n // Texture type fallback from float to int if not supported.\n var caps = this._scene.getEngine().getCaps();\n if (!useFullFloatFirst) {\n if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n else {\n this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n }\n else {\n if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else {\n this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n }\n this._initializeGenerator();\n this._applyFilterValues();\n }\n Object.defineProperty(ShadowGenerator.prototype, \"bias\", {\n /**\n * Gets the bias: offset applied on the depth preventing acnea (in light direction).\n */\n get: function () {\n return this._bias;\n },\n /**\n * Sets the bias: offset applied on the depth preventing acnea (in light direction).\n */\n set: function (bias) {\n this._bias = bias;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"normalBias\", {\n /**\n * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).\n */\n get: function () {\n return this._normalBias;\n },\n /**\n * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).\n */\n set: function (normalBias) {\n this._normalBias = normalBias;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"blurBoxOffset\", {\n /**\n * Gets the blur box offset: offset applied during the blur pass.\n * Only usefull if useKernelBlur = false\n */\n get: function () {\n return this._blurBoxOffset;\n },\n /**\n * Sets the blur box offset: offset applied during the blur pass.\n * Only usefull if useKernelBlur = false\n */\n set: function (value) {\n if (this._blurBoxOffset === value) {\n return;\n }\n this._blurBoxOffset = value;\n this._disposeBlurPostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"blurScale\", {\n /**\n * Gets the blur scale: scale of the blurred texture compared to the main shadow map.\n * 2 means half of the size.\n */\n get: function () {\n return this._blurScale;\n },\n /**\n * Sets the blur scale: scale of the blurred texture compared to the main shadow map.\n * 2 means half of the size.\n */\n set: function (value) {\n if (this._blurScale === value) {\n return;\n }\n this._blurScale = value;\n this._disposeBlurPostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"blurKernel\", {\n /**\n * Gets the blur kernel: kernel size of the blur pass.\n * Only usefull if useKernelBlur = true\n */\n get: function () {\n return this._blurKernel;\n },\n /**\n * Sets the blur kernel: kernel size of the blur pass.\n * Only usefull if useKernelBlur = true\n */\n set: function (value) {\n if (this._blurKernel === value) {\n return;\n }\n this._blurKernel = value;\n this._disposeBlurPostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useKernelBlur\", {\n /**\n * Gets whether the blur pass is a kernel blur (if true) or box blur.\n * Only usefull in filtered mode (useBlurExponentialShadowMap...)\n */\n get: function () {\n return this._useKernelBlur;\n },\n /**\n * Sets whether the blur pass is a kernel blur (if true) or box blur.\n * Only usefull in filtered mode (useBlurExponentialShadowMap...)\n */\n set: function (value) {\n if (this._useKernelBlur === value) {\n return;\n }\n this._useKernelBlur = value;\n this._disposeBlurPostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"depthScale\", {\n /**\n * Gets the depth scale used in ESM mode.\n */\n get: function () {\n return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();\n },\n /**\n * Sets the depth scale used in ESM mode.\n * This can override the scale stored on the light.\n */\n set: function (value) {\n this._depthScale = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"filter\", {\n /**\n * Gets the current mode of the shadow generator (normal, PCF, ESM...).\n * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE\n */\n get: function () {\n return this._filter;\n },\n /**\n * Sets the current mode of the shadow generator (normal, PCF, ESM...).\n * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE\n */\n set: function (value) {\n // Blurring the cubemap is going to be too expensive. Reverting to unblurred version\n if (this._light.needCube()) {\n if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {\n this.useExponentialShadowMap = true;\n return;\n }\n else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {\n this.useCloseExponentialShadowMap = true;\n return;\n }\n // PCF on cubemap would also be expensive\n else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {\n this.usePoissonSampling = true;\n return;\n }\n }\n // Weblg1 fallback for PCF.\n if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {\n if (this._scene.getEngine().webGLVersion === 1) {\n this.usePoissonSampling = true;\n return;\n }\n }\n if (this._filter === value) {\n return;\n }\n this._filter = value;\n this._disposeBlurPostProcesses();\n this._applyFilterValues();\n this._light._markMeshesAsLightDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"usePoissonSampling\", {\n /**\n * Gets if the current filter is set to Poisson Sampling.\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;\n },\n /**\n * Sets the current filter to Poisson Sampling.\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useVarianceShadowMap\", {\n /**\n * Gets if the current filter is set to VSM.\n * DEPRECATED. Should use useExponentialShadowMap instead.\n */\n get: function () {\n BABYLON.Tools.Warn(\"VSM are now replaced by ESM. Please use useExponentialShadowMap instead.\");\n return this.useExponentialShadowMap;\n },\n /**\n * Sets the current filter is to VSM.\n * DEPRECATED. Should use useExponentialShadowMap instead.\n */\n set: function (value) {\n BABYLON.Tools.Warn(\"VSM are now replaced by ESM. Please use useExponentialShadowMap instead.\");\n this.useExponentialShadowMap = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useBlurVarianceShadowMap\", {\n /**\n * Gets if the current filter is set to blurred VSM.\n * DEPRECATED. Should use useBlurExponentialShadowMap instead.\n */\n get: function () {\n BABYLON.Tools.Warn(\"VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.\");\n return this.useBlurExponentialShadowMap;\n },\n /**\n * Sets the current filter is to blurred VSM.\n * DEPRECATED. Should use useBlurExponentialShadowMap instead.\n */\n set: function (value) {\n BABYLON.Tools.Warn(\"VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.\");\n this.useBlurExponentialShadowMap = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useExponentialShadowMap\", {\n /**\n * Gets if the current filter is set to ESM.\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;\n },\n /**\n * Sets the current filter is to ESM.\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useBlurExponentialShadowMap\", {\n /**\n * Gets if the current filter is set to filtered ESM.\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;\n },\n /**\n * Gets if the current filter is set to filtered ESM.\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useCloseExponentialShadowMap\", {\n /**\n * Gets if the current filter is set to \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;\n },\n /**\n * Sets the current filter to \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useBlurCloseExponentialShadowMap\", {\n /**\n * Gets if the current filter is set to filtered \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;\n },\n /**\n * Sets the current filter to filtered \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"usePercentageCloserFiltering\", {\n /**\n * Gets if the current filter is set to \"PCF\" (percentage closer filtering).\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_PCF;\n },\n /**\n * Sets the current filter to \"PCF\" (percentage closer filtering).\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"filteringQuality\", {\n /**\n * Gets the PCF or PCSS Quality.\n * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.\n */\n get: function () {\n return this._filteringQuality;\n },\n /**\n * Sets the PCF or PCSS Quality.\n * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.\n */\n set: function (filteringQuality) {\n this._filteringQuality = filteringQuality;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useContactHardeningShadow\", {\n /**\n * Gets if the current filter is set to \"PCSS\" (contact hardening).\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_PCSS;\n },\n /**\n * Sets the current filter to \"PCSS\" (contact hardening).\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"contactHardeningLightSizeUVRatio\", {\n /**\n * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.\n * Using a ratio helps keeping shape stability independently of the map size.\n *\n * It does not account for the light projection as it was having too much\n * instability during the light setup or during light position changes.\n *\n * Only valid if useContactHardeningShadow is true.\n */\n get: function () {\n return this._contactHardeningLightSizeUVRatio;\n },\n /**\n * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.\n * Using a ratio helps keeping shape stability independently of the map size.\n *\n * It does not account for the light projection as it was having too much\n * instability during the light setup or during light position changes.\n *\n * Only valid if useContactHardeningShadow is true.\n */\n set: function (contactHardeningLightSizeUVRatio) {\n this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.\n * 0 means strongest and 1 would means no shadow.\n * @returns the darkness.\n */\n ShadowGenerator.prototype.getDarkness = function () {\n return this._darkness;\n };\n /**\n * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.\n * @param darkness The darkness value 0 means strongest and 1 would means no shadow.\n * @returns the shadow generator allowing fluent coding.\n */\n ShadowGenerator.prototype.setDarkness = function (darkness) {\n if (darkness >= 1.0)\n this._darkness = 1.0;\n else if (darkness <= 0.0)\n this._darkness = 0.0;\n else\n this._darkness = darkness;\n return this;\n };\n /**\n * Sets the ability to have transparent shadow (boolean).\n * @param transparent True if transparent else False\n * @returns the shadow generator allowing fluent coding\n */\n ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {\n this._transparencyShadow = transparent;\n return this;\n };\n /**\n * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).\n * @returns The render target texture if present otherwise, null\n */\n ShadowGenerator.prototype.getShadowMap = function () {\n return this._shadowMap;\n };\n /**\n * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).\n * @returns The render target texture if the shadow map is present otherwise, null\n */\n ShadowGenerator.prototype.getShadowMapForRendering = function () {\n if (this._shadowMap2) {\n return this._shadowMap2;\n }\n return this._shadowMap;\n };\n /**\n * Helper function to add a mesh and its descendants to the list of shadow casters.\n * @param mesh Mesh to add\n * @param includeDescendants boolean indicating if the descendants should be added. Default to true\n * @returns the Shadow Generator itself\n */\n ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {\n if (includeDescendants === void 0) { includeDescendants = true; }\n if (!this._shadowMap) {\n return this;\n }\n if (!this._shadowMap.renderList) {\n this._shadowMap.renderList = [];\n }\n this._shadowMap.renderList.push(mesh);\n if (includeDescendants) {\n (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());\n }\n return this;\n var _a;\n };\n /**\n * Helper function to remove a mesh and its descendants from the list of shadow casters\n * @param mesh Mesh to remove\n * @param includeDescendants boolean indicating if the descendants should be removed. Default to true\n * @returns the Shadow Generator itself\n */\n ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {\n if (includeDescendants === void 0) { includeDescendants = true; }\n if (!this._shadowMap || !this._shadowMap.renderList) {\n return this;\n }\n var index = this._shadowMap.renderList.indexOf(mesh);\n if (index !== -1) {\n this._shadowMap.renderList.splice(index, 1);\n }\n if (includeDescendants) {\n for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {\n var child = _a[_i];\n this.removeShadowCaster(child);\n }\n }\n return this;\n };\n /**\n * Returns the associated light object.\n * @returns the light generating the shadow\n */\n ShadowGenerator.prototype.getLight = function () {\n return this._light;\n };\n ShadowGenerator.prototype._initializeGenerator = function () {\n this._light._markMeshesAsLightDirty();\n this._initializeShadowMap();\n };\n ShadowGenerator.prototype._initializeShadowMap = function () {\n var _this = this;\n // Render target\n var engine = this._scene.getEngine();\n if (engine.webGLVersion > 1) {\n this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + \"_shadowMap\", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);\n this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);\n }\n else {\n this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + \"_shadowMap\", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());\n }\n this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._shadowMap.anisotropicFilteringLevel = 1;\n this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n this._shadowMap.renderParticles = false;\n this._shadowMap.ignoreCameraViewport = true;\n // Record Face Index before render.\n this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {\n _this._currentFaceIndex = faceIndex;\n if (_this._filter === ShadowGenerator.FILTER_PCF) {\n engine.setColorWrite(false);\n }\n });\n // Custom render function.\n this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);\n // Blur if required afer render.\n this._shadowMap.onAfterUnbindObservable.add(function () {\n if (_this._filter === ShadowGenerator.FILTER_PCF) {\n engine.setColorWrite(true);\n }\n if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {\n return;\n }\n var shadowMap = _this.getShadowMapForRendering();\n if (shadowMap) {\n _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);\n }\n });\n // Clear according to the chosen filter.\n var clearZero = new BABYLON.Color4(0, 0, 0, 0);\n var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n this._shadowMap.onClearObservable.add(function (engine) {\n if (_this._filter === ShadowGenerator.FILTER_PCF) {\n engine.clear(clearOne, false, true, false);\n }\n else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {\n engine.clear(clearZero, true, true, false);\n }\n else {\n engine.clear(clearOne, true, true, false);\n }\n });\n };\n ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {\n var _this = this;\n var engine = this._scene.getEngine();\n var targetSize = this._mapSize / this.blurScale;\n if (!this.useKernelBlur || this.blurScale !== 1.0) {\n this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + \"_shadowMap2\", targetSize, this._scene, false, true, this._textureType);\n this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n }\n if (this.useKernelBlur) {\n this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + \"KernelBlurX\", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);\n this._kernelBlurXPostprocess.width = targetSize;\n this._kernelBlurXPostprocess.height = targetSize;\n this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {\n effect.setTexture(\"textureSampler\", _this._shadowMap);\n });\n this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + \"KernelBlurY\", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);\n this._kernelBlurXPostprocess.autoClear = false;\n this._kernelBlurYPostprocess.autoClear = false;\n if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {\n this._kernelBlurXPostprocess.packedFloat = true;\n this._kernelBlurYPostprocess.packedFloat = true;\n }\n this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];\n }\n else {\n this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + \"DepthBoxBlur\", \"depthBoxBlur\", [\"screenSize\", \"boxOffset\"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, \"#define OFFSET \" + this._blurBoxOffset, this._textureType);\n this._boxBlurPostprocess.onApplyObservable.add(function (effect) {\n effect.setFloat2(\"screenSize\", targetSize, targetSize);\n effect.setTexture(\"textureSampler\", _this._shadowMap);\n });\n this._boxBlurPostprocess.autoClear = false;\n this._blurPostProcesses = [this._boxBlurPostprocess];\n }\n };\n ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {\n var index;\n var engine = this._scene.getEngine();\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);\n }\n if (this._transparencyShadow) {\n for (index = 0; index < transparentSubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);\n }\n }\n };\n ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {\n var _this = this;\n var mesh = subMesh.getRenderingMesh();\n var scene = this._scene;\n var engine = scene.getEngine();\n var material = subMesh.getMaterial();\n if (!material) {\n return;\n }\n // Culling\n engine.setState(material.backFaceCulling);\n // Managing instances\n var batch = mesh._getInstancesRenderList(subMesh._id);\n if (batch.mustReturn) {\n return;\n }\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);\n if (this.isReady(subMesh, hardwareInstancedRendering)) {\n engine.enableEffect(this._effect);\n mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);\n this._effect.setFloat3(\"biasAndScale\", this.bias, this.normalBias, this.depthScale);\n this._effect.setMatrix(\"viewProjection\", this.getTransformMatrix());\n if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {\n this._effect.setVector3(\"lightData\", this._cachedDirection);\n }\n else {\n this._effect.setVector3(\"lightData\", this._cachedPosition);\n }\n if (scene.activeCamera) {\n this._effect.setFloat2(\"depthValues\", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));\n }\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n this._effect.setTexture(\"diffuseSampler\", alphaTexture);\n this._effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n this._effect.setMatrices(\"mBones\", mesh.skeleton.getTransformMatrices((mesh)));\n }\n // Morph targets\n BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);\n if (this.forceBackFacesOnly) {\n engine.setState(true, 0, false, true);\n }\n // Draw\n mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix(\"world\", world); });\n if (this.forceBackFacesOnly) {\n engine.setState(true, 0, false, false);\n }\n }\n else {\n // Need to reset refresh rate of the shadowMap\n if (this._shadowMap) {\n this._shadowMap.resetRefreshCounter();\n }\n }\n };\n ShadowGenerator.prototype._applyFilterValues = function () {\n if (!this._shadowMap) {\n return;\n }\n if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {\n this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);\n }\n else {\n this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n }\n };\n /**\n * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.\n * @param onCompiled Callback triggered at the and of the effects compilation\n * @param options Sets of optional options forcing the compilation with different modes\n */\n ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {\n var _this = this;\n var localOptions = __assign({ useInstances: false }, options);\n var shadowMap = this.getShadowMap();\n if (!shadowMap) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n var renderList = shadowMap.renderList;\n if (!renderList) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n var subMeshes = new Array();\n for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {\n var mesh = renderList_1[_i];\n subMeshes.push.apply(subMeshes, mesh.subMeshes);\n }\n if (subMeshes.length === 0) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n var currentIndex = 0;\n var checkReady = function () {\n if (!_this._scene || !_this._scene.getEngine()) {\n return;\n }\n while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {\n currentIndex++;\n if (currentIndex >= subMeshes.length) {\n if (onCompiled) {\n onCompiled(_this);\n }\n return;\n }\n }\n setTimeout(checkReady, 16);\n };\n checkReady();\n };\n /**\n * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.\n * @param options Sets of optional options forcing the compilation with different modes\n * @returns A promise that resolves when the compilation completes\n */\n ShadowGenerator.prototype.forceCompilationAsync = function (options) {\n var _this = this;\n return new Promise(function (resolve) {\n _this.forceCompilation(function () {\n resolve();\n }, options);\n });\n };\n /**\n * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).\n * @param subMesh The submesh we want to render in the shadow map\n * @param useInstances Defines wether will draw in the map using instances\n * @returns true if ready otherwise, false\n */\n ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {\n var defines = [];\n if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {\n defines.push(\"#define FLOAT\");\n }\n if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {\n defines.push(\"#define ESM\");\n }\n else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {\n defines.push(\"#define DEPTHTEXTURE\");\n }\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n var mesh = subMesh.getMesh();\n var material = subMesh.getMaterial();\n // Normal bias.\n if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n attribs.push(BABYLON.VertexBuffer.NormalKind);\n defines.push(\"#define NORMAL\");\n if (mesh.nonUniformScaling) {\n defines.push(\"#define NONUNIFORMSCALING\");\n }\n if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {\n defines.push(\"#define DIRECTIONINLIGHTDATA\");\n }\n }\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n if (alphaTexture.coordinatesIndex === 1) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton.bones.length + 1));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets \n var manager = mesh.morphTargetManager;\n var morphInfluencers = 0;\n if (manager) {\n if (manager.numInfluencers > 0) {\n defines.push(\"#define MORPHTARGETS\");\n morphInfluencers = manager.numInfluencers;\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + morphInfluencers);\n BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { \"NUM_MORPH_INFLUENCERS\": morphInfluencers });\n }\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n // Get correct effect\n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n this._effect = this._scene.getEngine().createEffect(\"shadowMap\", attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\", \"lightData\", \"depthValues\", \"biasAndScale\", \"morphTargetInfluences\"], [\"diffuseSampler\"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });\n }\n if (!this._effect.isReady()) {\n return false;\n }\n if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {\n if (!this._blurPostProcesses || !this._blurPostProcesses.length) {\n this._initializeBlurRTTAndPostProcesses();\n }\n }\n if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {\n return false;\n }\n if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {\n return false;\n }\n if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {\n return false;\n }\n return true;\n };\n /**\n * Prepare all the defines in a material relying on a shadow map at the specified light index.\n * @param defines Defines of the material we want to update\n * @param lightIndex Index of the light in the enabled light list of the material\n */\n ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {\n var scene = this._scene;\n var light = this._light;\n if (!scene.shadowsEnabled || !light.shadowEnabled) {\n return;\n }\n defines[\"SHADOW\" + lightIndex] = true;\n if (this.useContactHardeningShadow) {\n defines[\"SHADOWPCSS\" + lightIndex] = true;\n if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {\n defines[\"SHADOWLOWQUALITY\" + lightIndex] = true;\n }\n else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {\n defines[\"SHADOWMEDIUMQUALITY\" + lightIndex] = true;\n }\n // else default to high.\n }\n if (this.usePercentageCloserFiltering) {\n defines[\"SHADOWPCF\" + lightIndex] = true;\n if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {\n defines[\"SHADOWLOWQUALITY\" + lightIndex] = true;\n }\n else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {\n defines[\"SHADOWMEDIUMQUALITY\" + lightIndex] = true;\n }\n // else default to high.\n }\n else if (this.usePoissonSampling) {\n defines[\"SHADOWPOISSON\" + lightIndex] = true;\n }\n else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {\n defines[\"SHADOWESM\" + lightIndex] = true;\n }\n else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {\n defines[\"SHADOWCLOSEESM\" + lightIndex] = true;\n }\n if (light.needCube()) {\n defines[\"SHADOWCUBE\" + lightIndex] = true;\n }\n };\n /**\n * Binds the shadow related information inside of an effect (information like near, far, darkness...\n * defined in the generator but impacting the effect).\n * @param lightIndex Index of the light in the enabled light list of the material owning the effect\n * @param effect The effect we are binfing the information for\n */\n ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {\n var light = this._light;\n var scene = this._scene;\n if (!scene.shadowsEnabled || !light.shadowEnabled) {\n return;\n }\n var camera = scene.activeCamera;\n if (!camera) {\n return;\n }\n var shadowMap = this.getShadowMap();\n if (!shadowMap) {\n return;\n }\n if (!light.needCube()) {\n effect.setMatrix(\"lightMatrix\" + lightIndex, this.getTransformMatrix());\n }\n // Only PCF uses depth stencil texture.\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n effect.setDepthStencilTexture(\"shadowSampler\" + lightIndex, this.getShadowMapForRendering());\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);\n }\n else if (this._filter === ShadowGenerator.FILTER_PCSS) {\n effect.setDepthStencilTexture(\"shadowSampler\" + lightIndex, this.getShadowMapForRendering());\n effect.setTexture(\"depthSampler\" + lightIndex, this.getShadowMapForRendering());\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);\n }\n else {\n effect.setTexture(\"shadowSampler\" + lightIndex, this.getShadowMapForRendering());\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);\n }\n light._uniformBuffer.updateFloat2(\"depthValues\", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);\n };\n /**\n * Gets the transformation matrix used to project the meshes into the map from the light point of view.\n * (eq to shadow prjection matrix * light transform matrix)\n * @returns The transform matrix used to create the shadow map\n */\n ShadowGenerator.prototype.getTransformMatrix = function () {\n var scene = this._scene;\n if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {\n return this._transformMatrix;\n }\n this._currentRenderID = scene.getRenderId();\n this._currentFaceIndexCache = this._currentFaceIndex;\n var lightPosition = this._light.position;\n if (this._light.computeTransformedInformation()) {\n lightPosition = this._light.transformedPosition;\n }\n BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);\n if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {\n this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light\n }\n if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {\n this._cachedPosition.copyFrom(lightPosition);\n this._cachedDirection.copyFrom(this._lightDirection);\n BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);\n var shadowMap = this.getShadowMap();\n if (shadowMap) {\n var renderList = shadowMap.renderList;\n if (renderList) {\n this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);\n }\n }\n this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);\n }\n return this._transformMatrix;\n };\n /**\n * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between\n * Cube and 2D textures for instance.\n */\n ShadowGenerator.prototype.recreateShadowMap = function () {\n var shadowMap = this._shadowMap;\n if (!shadowMap) {\n return;\n }\n // Track render list.\n var renderList = shadowMap.renderList;\n // Clean up existing data.\n this._disposeRTTandPostProcesses();\n // Reinitializes.\n this._initializeGenerator();\n // Reaffect the filter to ensure a correct fallback if necessary.\n this.filter = this.filter;\n // Reaffect the filter.\n this._applyFilterValues();\n // Reaffect Render List.\n this._shadowMap.renderList = renderList;\n };\n ShadowGenerator.prototype._disposeBlurPostProcesses = function () {\n if (this._shadowMap2) {\n this._shadowMap2.dispose();\n this._shadowMap2 = null;\n }\n if (this._boxBlurPostprocess) {\n this._boxBlurPostprocess.dispose();\n this._boxBlurPostprocess = null;\n }\n if (this._kernelBlurXPostprocess) {\n this._kernelBlurXPostprocess.dispose();\n this._kernelBlurXPostprocess = null;\n }\n if (this._kernelBlurYPostprocess) {\n this._kernelBlurYPostprocess.dispose();\n this._kernelBlurYPostprocess = null;\n }\n this._blurPostProcesses = [];\n };\n ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {\n if (this._shadowMap) {\n this._shadowMap.dispose();\n this._shadowMap = null;\n }\n this._disposeBlurPostProcesses();\n };\n /**\n * Disposes the ShadowGenerator.\n * Returns nothing.\n */\n ShadowGenerator.prototype.dispose = function () {\n this._disposeRTTandPostProcesses();\n if (this._light) {\n this._light._shadowGenerator = null;\n this._light._markMeshesAsLightDirty();\n }\n };\n /**\n * Serializes the shadow generator setup to a json object.\n * @returns The serialized JSON object\n */\n ShadowGenerator.prototype.serialize = function () {\n var serializationObject = {};\n var shadowMap = this.getShadowMap();\n if (!shadowMap) {\n return serializationObject;\n }\n serializationObject.lightId = this._light.id;\n serializationObject.mapSize = shadowMap.getRenderSize();\n serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;\n serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;\n serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;\n serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;\n serializationObject.usePoissonSampling = this.usePoissonSampling;\n serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;\n serializationObject.depthScale = this.depthScale;\n serializationObject.darkness = this.getDarkness();\n serializationObject.blurBoxOffset = this.blurBoxOffset;\n serializationObject.blurKernel = this.blurKernel;\n serializationObject.blurScale = this.blurScale;\n serializationObject.useKernelBlur = this.useKernelBlur;\n serializationObject.transparencyShadow = this._transparencyShadow;\n serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;\n serializationObject.bias = this.bias;\n serializationObject.normalBias = this.normalBias;\n serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;\n serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;\n serializationObject.filteringQuality = this.filteringQuality;\n serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;\n serializationObject.renderList = [];\n if (shadowMap.renderList) {\n for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {\n var mesh = shadowMap.renderList[meshIndex];\n serializationObject.renderList.push(mesh.id);\n }\n }\n return serializationObject;\n };\n /**\n * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.\n * @param parsedShadowGenerator The JSON object to parse\n * @param scene The scene to create the shadow map for\n * @returns The parsed shadow generator\n */\n ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {\n var light = scene.getLightByID(parsedShadowGenerator.lightId);\n var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);\n var shadowMap = shadowGenerator.getShadowMap();\n for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {\n var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);\n meshes.forEach(function (mesh) {\n if (!shadowMap) {\n return;\n }\n if (!shadowMap.renderList) {\n shadowMap.renderList = [];\n }\n shadowMap.renderList.push(mesh);\n });\n }\n if (parsedShadowGenerator.usePoissonSampling) {\n shadowGenerator.usePoissonSampling = true;\n }\n else if (parsedShadowGenerator.useExponentialShadowMap) {\n shadowGenerator.useExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useBlurExponentialShadowMap) {\n shadowGenerator.useBlurExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useCloseExponentialShadowMap) {\n shadowGenerator.useCloseExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {\n shadowGenerator.useBlurCloseExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.usePercentageCloserFiltering) {\n shadowGenerator.usePercentageCloserFiltering = true;\n }\n else if (parsedShadowGenerator.useContactHardeningShadow) {\n shadowGenerator.useContactHardeningShadow = true;\n }\n if (parsedShadowGenerator.filteringQuality) {\n shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;\n }\n if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {\n shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;\n }\n // Backward compat\n else if (parsedShadowGenerator.useVarianceShadowMap) {\n shadowGenerator.useExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useBlurVarianceShadowMap) {\n shadowGenerator.useBlurExponentialShadowMap = true;\n }\n if (parsedShadowGenerator.depthScale) {\n shadowGenerator.depthScale = parsedShadowGenerator.depthScale;\n }\n if (parsedShadowGenerator.blurScale) {\n shadowGenerator.blurScale = parsedShadowGenerator.blurScale;\n }\n if (parsedShadowGenerator.blurBoxOffset) {\n shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;\n }\n if (parsedShadowGenerator.useKernelBlur) {\n shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;\n }\n if (parsedShadowGenerator.blurKernel) {\n shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;\n }\n if (parsedShadowGenerator.bias !== undefined) {\n shadowGenerator.bias = parsedShadowGenerator.bias;\n }\n if (parsedShadowGenerator.normalBias !== undefined) {\n shadowGenerator.normalBias = parsedShadowGenerator.normalBias;\n }\n if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {\n shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;\n }\n if (parsedShadowGenerator.darkness) {\n shadowGenerator.setDarkness(parsedShadowGenerator.darkness);\n }\n if (parsedShadowGenerator.transparencyShadow) {\n shadowGenerator.setTransparencyShadow(true);\n }\n shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;\n return shadowGenerator;\n };\n /**\n * Shadow generator mode None: no filtering applied.\n */\n ShadowGenerator.FILTER_NONE = 0;\n /**\n * Shadow generator mode ESM: Exponential Shadow Mapping.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\n ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;\n /**\n * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.\n * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)\n */\n ShadowGenerator.FILTER_POISSONSAMPLING = 2;\n /**\n * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\n ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;\n /**\n * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing\n * edge artifacts on steep falloff.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\n ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;\n /**\n * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing\n * edge artifacts on steep falloff.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\n ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;\n /**\n * Shadow generator mode PCF: Percentage Closer Filtering\n * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1\n * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)\n */\n ShadowGenerator.FILTER_PCF = 6;\n /**\n * Shadow generator mode PCSS: Percentage Closering Soft Shadow.\n * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1\n * Contact Hardening\n */\n ShadowGenerator.FILTER_PCSS = 7;\n /**\n * Reserved for PCF and PCSS\n * Highest Quality.\n *\n * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.\n *\n * Execute PCSS with 32 taps blocker search and 64 taps PCF.\n */\n ShadowGenerator.QUALITY_HIGH = 0;\n /**\n * Reserved for PCF and PCSS\n * Good tradeoff for quality/perf cross devices\n *\n * Execute PCF on a 3*3 kernel.\n *\n * Execute PCSS with 16 taps blocker search and 32 taps PCF.\n */\n ShadowGenerator.QUALITY_MEDIUM = 1;\n /**\n * Reserved for PCF and PCSS\n * The lowest quality but the fastest.\n *\n * Execute PCF on a 1*1 kernel.\n *\n * Execute PCSS with 16 taps blocker search and 16 taps PCF.\n */\n ShadowGenerator.QUALITY_LOW = 2;\n return ShadowGenerator;\n }());\n BABYLON.ShadowGenerator = ShadowGenerator;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.shadowGenerator.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var DefaultLoadingScreen = /** @class */ (function () {\n function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {\n if (_loadingText === void 0) { _loadingText = \"\"; }\n if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = \"black\"; }\n var _this = this;\n this._renderingCanvas = _renderingCanvas;\n this._loadingText = _loadingText;\n this._loadingDivBackgroundColor = _loadingDivBackgroundColor;\n // Resize\n this._resizeLoadingUI = function () {\n var canvasRect = _this._renderingCanvas.getBoundingClientRect();\n var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;\n if (!_this._loadingDiv) {\n return;\n }\n _this._loadingDiv.style.position = (canvasPositioning === \"fixed\") ? \"fixed\" : \"absolute\";\n _this._loadingDiv.style.left = canvasRect.left + \"px\";\n _this._loadingDiv.style.top = canvasRect.top + \"px\";\n _this._loadingDiv.style.width = canvasRect.width + \"px\";\n _this._loadingDiv.style.height = canvasRect.height + \"px\";\n };\n }\n DefaultLoadingScreen.prototype.displayLoadingUI = function () {\n if (this._loadingDiv) {\n // Do not add a loading screen if there is already one \n return;\n }\n this._loadingDiv = document.createElement(\"div\");\n this._loadingDiv.id = \"babylonjsLoadingDiv\";\n this._loadingDiv.style.opacity = \"0\";\n this._loadingDiv.style.transition = \"opacity 1.5s ease\";\n this._loadingDiv.style.pointerEvents = \"none\";\n // Loading text\n this._loadingTextDiv = document.createElement(\"div\");\n this._loadingTextDiv.style.position = \"absolute\";\n this._loadingTextDiv.style.left = \"0\";\n this._loadingTextDiv.style.top = \"50%\";\n this._loadingTextDiv.style.marginTop = \"80px\";\n this._loadingTextDiv.style.width = \"100%\";\n this._loadingTextDiv.style.height = \"20px\";\n this._loadingTextDiv.style.fontFamily = \"Arial\";\n this._loadingTextDiv.style.fontSize = \"14px\";\n this._loadingTextDiv.style.color = \"white\";\n this._loadingTextDiv.style.textAlign = \"center\";\n this._loadingTextDiv.innerHTML = \"Loading\";\n this._loadingDiv.appendChild(this._loadingTextDiv);\n //set the predefined text\n this._loadingTextDiv.innerHTML = this._loadingText;\n // Generating keyframes\n var style = document.createElement('style');\n style.type = 'text/css';\n var keyFrames = \"@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\\n 100% { -webkit-transform: rotate(360deg);}\\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\\n 100% { transform: rotate(360deg);}\\n }\";\n style.innerHTML = keyFrames;\n document.getElementsByTagName('head')[0].appendChild(style);\n // Loading img\n var imgBack = new Image();\n imgBack.src = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC\";\n imgBack.style.position = \"absolute\";\n imgBack.style.left = \"50%\";\n imgBack.style.top = \"50%\";\n imgBack.style.marginLeft = \"-60px\";\n imgBack.style.marginTop = \"-60px\";\n imgBack.style.animation = \"spin1 2s infinite ease-in-out\";\n imgBack.style.webkitAnimation = \"spin1 2s infinite ease-in-out\";\n imgBack.style.transformOrigin = \"50% 50%\";\n imgBack.style.webkitTransformOrigin = \"50% 50%\";\n this._loadingDiv.appendChild(imgBack);\n this._resizeLoadingUI();\n window.addEventListener(\"resize\", this._resizeLoadingUI);\n this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;\n document.body.appendChild(this._loadingDiv);\n this._loadingDiv.style.opacity = \"1\";\n };\n DefaultLoadingScreen.prototype.hideLoadingUI = function () {\n var _this = this;\n if (!this._loadingDiv) {\n return;\n }\n var onTransitionEnd = function () {\n if (!_this._loadingDiv) {\n return;\n }\n document.body.removeChild(_this._loadingDiv);\n window.removeEventListener(\"resize\", _this._resizeLoadingUI);\n _this._loadingDiv = null;\n };\n this._loadingDiv.style.opacity = \"0\";\n this._loadingDiv.addEventListener(\"transitionend\", onTransitionEnd);\n };\n Object.defineProperty(DefaultLoadingScreen.prototype, \"loadingUIText\", {\n set: function (text) {\n this._loadingText = text;\n if (this._loadingTextDiv) {\n this._loadingTextDiv.innerHTML = this._loadingText;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultLoadingScreen.prototype, \"loadingUIBackgroundColor\", {\n get: function () {\n return this._loadingDivBackgroundColor;\n },\n set: function (color) {\n this._loadingDivBackgroundColor = color;\n if (!this._loadingDiv) {\n return;\n }\n this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;\n },\n enumerable: true,\n configurable: true\n });\n return DefaultLoadingScreen;\n }());\n BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.loadingScreen.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var SceneLoaderProgressEvent = /** @class */ (function () {\n function SceneLoaderProgressEvent(lengthComputable, loaded, total) {\n this.lengthComputable = lengthComputable;\n this.loaded = loaded;\n this.total = total;\n }\n SceneLoaderProgressEvent.FromProgressEvent = function (event) {\n return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);\n };\n return SceneLoaderProgressEvent;\n }());\n BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;\n var SceneLoader = /** @class */ (function () {\n function SceneLoader() {\n }\n Object.defineProperty(SceneLoader, \"NO_LOGGING\", {\n get: function () {\n return 0;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"MINIMAL_LOGGING\", {\n get: function () {\n return 1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"SUMMARY_LOGGING\", {\n get: function () {\n return 2;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"DETAILED_LOGGING\", {\n get: function () {\n return 3;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"ForceFullSceneLoadingForIncremental\", {\n get: function () {\n return SceneLoader._ForceFullSceneLoadingForIncremental;\n },\n set: function (value) {\n SceneLoader._ForceFullSceneLoadingForIncremental = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"ShowLoadingScreen\", {\n get: function () {\n return SceneLoader._ShowLoadingScreen;\n },\n set: function (value) {\n SceneLoader._ShowLoadingScreen = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"loggingLevel\", {\n get: function () {\n return SceneLoader._loggingLevel;\n },\n set: function (value) {\n SceneLoader._loggingLevel = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"CleanBoneMatrixWeights\", {\n get: function () {\n return SceneLoader._CleanBoneMatrixWeights;\n },\n set: function (value) {\n SceneLoader._CleanBoneMatrixWeights = value;\n },\n enumerable: true,\n configurable: true\n });\n SceneLoader._getDefaultPlugin = function () {\n return SceneLoader._registeredPlugins[\".babylon\"];\n };\n SceneLoader._getPluginForExtension = function (extension) {\n var registeredPlugin = SceneLoader._registeredPlugins[extension];\n if (registeredPlugin) {\n return registeredPlugin;\n }\n BABYLON.Tools.Warn(\"Unable to find a plugin to load \" + extension + \" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type\");\n return SceneLoader._getDefaultPlugin();\n };\n SceneLoader._getPluginForDirectLoad = function (data) {\n for (var extension in SceneLoader._registeredPlugins) {\n var plugin = SceneLoader._registeredPlugins[extension].plugin;\n if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {\n return SceneLoader._registeredPlugins[extension];\n }\n }\n return SceneLoader._getDefaultPlugin();\n };\n SceneLoader._getPluginForFilename = function (sceneFilename) {\n if (sceneFilename.name) {\n sceneFilename = sceneFilename.name;\n }\n var queryStringPosition = sceneFilename.indexOf(\"?\");\n if (queryStringPosition !== -1) {\n sceneFilename = sceneFilename.substring(0, queryStringPosition);\n }\n var dotPosition = sceneFilename.lastIndexOf(\".\");\n var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();\n return SceneLoader._getPluginForExtension(extension);\n };\n // use babylon file loader directly if sceneFilename is prefixed with \"data:\"\n SceneLoader._getDirectLoad = function (sceneFilename) {\n if (sceneFilename.substr && sceneFilename.substr(0, 5) === \"data:\") {\n return sceneFilename.substr(5);\n }\n return null;\n };\n SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {\n var directLoad = SceneLoader._getDirectLoad(sceneFilename);\n var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));\n var plugin;\n if (registeredPlugin.plugin.createPlugin) {\n plugin = registeredPlugin.plugin.createPlugin();\n }\n else {\n plugin = registeredPlugin.plugin;\n }\n var useArrayBuffer = registeredPlugin.isBinary;\n var database;\n SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);\n var dataCallback = function (data, responseURL) {\n if (scene.isDisposed) {\n onError(\"Scene has been disposed\");\n return;\n }\n scene.database = database;\n onSuccess(plugin, data, responseURL);\n };\n var request = null;\n var pluginDisposed = false;\n var onDisposeObservable = plugin.onDisposeObservable;\n if (onDisposeObservable) {\n onDisposeObservable.add(function () {\n pluginDisposed = true;\n if (request) {\n request.abort();\n request = null;\n }\n onDispose();\n });\n }\n var manifestChecked = function () {\n if (pluginDisposed) {\n return;\n }\n var url = rootUrl + sceneFilename;\n request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {\n onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));\n } : undefined, database, useArrayBuffer, function (request, exception) {\n onError(\"Failed to load scene.\" + (exception ? \"\" : \" \" + exception.message), exception);\n });\n };\n if (directLoad) {\n dataCallback(directLoad);\n return plugin;\n }\n if (rootUrl.indexOf(\"file:\") === -1) {\n var engine = scene.getEngine();\n var canUseOfflineSupport = engine.enableOfflineSupport;\n if (canUseOfflineSupport) {\n // Also check for exceptions\n var exceptionFound = false;\n for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {\n var regex = _a[_i];\n if (regex.test(rootUrl + sceneFilename)) {\n exceptionFound = true;\n break;\n }\n }\n canUseOfflineSupport = !exceptionFound;\n }\n if (canUseOfflineSupport) {\n // Checking if a manifest file has been set for this scene and if offline mode has been requested\n database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);\n }\n else {\n manifestChecked();\n }\n }\n // Loading file from disk via input file or drag'n'drop\n else {\n var fileOrString = sceneFilename;\n if (fileOrString.name) { // File\n request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);\n }\n else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {\n request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);\n }\n else {\n onError(\"Unable to find file named \" + sceneFilename);\n }\n }\n return plugin;\n };\n // Public functions\n SceneLoader.GetPluginForExtension = function (extension) {\n return SceneLoader._getPluginForExtension(extension).plugin;\n };\n SceneLoader.IsPluginForExtensionAvailable = function (extension) {\n return !!SceneLoader._registeredPlugins[extension];\n };\n SceneLoader.RegisterPlugin = function (plugin) {\n if (typeof plugin.extensions === \"string\") {\n var extension = plugin.extensions;\n SceneLoader._registeredPlugins[extension.toLowerCase()] = {\n plugin: plugin,\n isBinary: false\n };\n }\n else {\n var extensions = plugin.extensions;\n Object.keys(extensions).forEach(function (extension) {\n SceneLoader._registeredPlugins[extension.toLowerCase()] = {\n plugin: plugin,\n isBinary: extensions[extension].isBinary\n };\n });\n }\n };\n /**\n * Import meshes into a scene\n * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene the instance of BABYLON.Scene to append to\n * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {\n if (sceneFilename === void 0) { sceneFilename = \"\"; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (onSuccess === void 0) { onSuccess = null; }\n if (onProgress === void 0) { onProgress = null; }\n if (onError === void 0) { onError = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n if (!scene) {\n BABYLON.Tools.Error(\"No scene available to import mesh to\");\n return null;\n }\n if (!sceneFilename) {\n sceneFilename = BABYLON.Tools.GetFilename(rootUrl);\n rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);\n }\n if (sceneFilename.substr && sceneFilename.substr(0, 1) === \"/\") {\n BABYLON.Tools.Error(\"Wrong sceneFilename parameter\");\n return null;\n }\n var loadingToken = {};\n scene._addPendingData(loadingToken);\n var disposeHandler = function () {\n scene._removePendingData(loadingToken);\n };\n var errorHandler = function (message, exception) {\n var errorMessage = \"Unable to import meshes from \" + rootUrl + sceneFilename + \": \" + message;\n if (onError) {\n onError(scene, errorMessage, exception);\n }\n else {\n BABYLON.Tools.Error(errorMessage);\n // should the exception be thrown?\n }\n disposeHandler();\n };\n var progressHandler = onProgress ? function (event) {\n try {\n onProgress(event);\n }\n catch (e) {\n errorHandler(\"Error in onProgress callback\", e);\n }\n } : undefined;\n var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {\n scene.importedMeshesFiles.push(rootUrl + sceneFilename);\n if (onSuccess) {\n try {\n onSuccess(meshes, particleSystems, skeletons, animationGroups);\n }\n catch (e) {\n errorHandler(\"Error in onSuccess callback\", e);\n }\n }\n scene._removePendingData(loadingToken);\n };\n return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {\n if (plugin.rewriteRootURL) {\n rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);\n }\n if (sceneFilename === \"\") {\n if (sceneFilename === \"\") {\n rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);\n }\n }\n if (plugin.importMesh) {\n var syncedPlugin = plugin;\n var meshes = new Array();\n var particleSystems = new Array();\n var skeletons = new Array();\n if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {\n return;\n }\n scene.loadingPluginName = plugin.name;\n successHandler(meshes, particleSystems, skeletons, []);\n }\n else {\n var asyncedPlugin = plugin;\n asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {\n scene.loadingPluginName = plugin.name;\n successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);\n }).catch(function (error) {\n errorHandler(error.message, error);\n });\n }\n }, progressHandler, errorHandler, disposeHandler, pluginExtension);\n };\n /**\n * Import meshes into a scene\n * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene the instance of BABYLON.Scene to append to\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups\n */\n SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {\n if (sceneFilename === void 0) { sceneFilename = \"\"; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (onProgress === void 0) { onProgress = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n return new Promise(function (resolve, reject) {\n SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {\n resolve({\n meshes: meshes,\n particleSystems: particleSystems,\n skeletons: skeletons,\n animationGroups: animationGroups\n });\n }, onProgress, function (scene, message, exception) {\n reject(exception || new Error(message));\n }, pluginExtension);\n });\n };\n /**\n * Load a scene\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param engine is the instance of BABYLON.Engine to use to create the scene\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {\n if (onSuccess === void 0) { onSuccess = null; }\n if (onProgress === void 0) { onProgress = null; }\n if (onError === void 0) { onError = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);\n };\n /**\n * Load a scene\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param engine is the instance of BABYLON.Engine to use to create the scene\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded scene\n */\n SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {\n if (onProgress === void 0) { onProgress = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n return new Promise(function (resolve, reject) {\n SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {\n resolve(scene);\n }, onProgress, function (scene, message, exception) {\n reject(exception || new Error(message));\n }, pluginExtension);\n });\n };\n /**\n * Append a scene\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {\n if (sceneFilename === void 0) { sceneFilename = \"\"; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (onSuccess === void 0) { onSuccess = null; }\n if (onProgress === void 0) { onProgress = null; }\n if (onError === void 0) { onError = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n if (!scene) {\n BABYLON.Tools.Error(\"No scene available to append to\");\n return null;\n }\n if (!sceneFilename) {\n sceneFilename = BABYLON.Tools.GetFilename(rootUrl);\n rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);\n }\n if (sceneFilename.substr && sceneFilename.substr(0, 1) === \"/\") {\n BABYLON.Tools.Error(\"Wrong sceneFilename parameter\");\n return null;\n }\n if (SceneLoader.ShowLoadingScreen) {\n scene.getEngine().displayLoadingUI();\n }\n var loadingToken = {};\n scene._addPendingData(loadingToken);\n var disposeHandler = function () {\n scene._removePendingData(loadingToken);\n scene.getEngine().hideLoadingUI();\n };\n var errorHandler = function (message, exception) {\n var errorMessage = \"Unable to load from \" + rootUrl + sceneFilename + (message ? \": \" + message : \"\");\n if (onError) {\n onError(scene, errorMessage, exception);\n }\n else {\n BABYLON.Tools.Error(errorMessage);\n // should the exception be thrown?\n }\n disposeHandler();\n };\n var progressHandler = onProgress ? function (event) {\n try {\n onProgress(event);\n }\n catch (e) {\n errorHandler(\"Error in onProgress callback\", e);\n }\n } : undefined;\n var successHandler = function () {\n if (onSuccess) {\n try {\n onSuccess(scene);\n }\n catch (e) {\n errorHandler(\"Error in onSuccess callback\", e);\n }\n }\n scene._removePendingData(loadingToken);\n };\n return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {\n if (sceneFilename === \"\") {\n rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);\n }\n if (plugin.load) {\n var syncedPlugin = plugin;\n if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {\n return;\n }\n scene.loadingPluginName = plugin.name;\n successHandler();\n }\n else {\n var asyncedPlugin = plugin;\n asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {\n scene.loadingPluginName = plugin.name;\n successHandler();\n }).catch(function (error) {\n errorHandler(error.message, error);\n });\n }\n if (SceneLoader.ShowLoadingScreen) {\n scene.executeWhenReady(function () {\n scene.getEngine().hideLoadingUI();\n });\n }\n }, progressHandler, errorHandler, disposeHandler, pluginExtension);\n };\n /**\n * Append a scene\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The given scene\n */\n SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {\n if (sceneFilename === void 0) { sceneFilename = \"\"; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (onProgress === void 0) { onProgress = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n return new Promise(function (resolve, reject) {\n SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {\n resolve(scene);\n }, onProgress, function (scene, message, exception) {\n reject(exception || new Error(message));\n }, pluginExtension);\n });\n };\n /**\n * Load a scene into an asset container\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {\n if (sceneFilename === void 0) { sceneFilename = \"\"; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (onSuccess === void 0) { onSuccess = null; }\n if (onProgress === void 0) { onProgress = null; }\n if (onError === void 0) { onError = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n if (!scene) {\n BABYLON.Tools.Error(\"No scene available to load asset container to\");\n return null;\n }\n if (!sceneFilename) {\n sceneFilename = BABYLON.Tools.GetFilename(rootUrl);\n rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);\n }\n if (sceneFilename.substr && sceneFilename.substr(0, 1) === \"/\") {\n BABYLON.Tools.Error(\"Wrong sceneFilename parameter\");\n return null;\n }\n var loadingToken = {};\n scene._addPendingData(loadingToken);\n var disposeHandler = function () {\n scene._removePendingData(loadingToken);\n };\n var errorHandler = function (message, exception) {\n var errorMessage = \"Unable to load assets from \" + rootUrl + sceneFilename + (message ? \": \" + message : \"\");\n if (onError) {\n onError(scene, errorMessage, exception);\n }\n else {\n BABYLON.Tools.Error(errorMessage);\n // should the exception be thrown?\n }\n disposeHandler();\n };\n var progressHandler = onProgress ? function (event) {\n try {\n onProgress(event);\n }\n catch (e) {\n errorHandler(\"Error in onProgress callback\", e);\n }\n } : undefined;\n var successHandler = function (assets) {\n if (onSuccess) {\n try {\n onSuccess(assets);\n }\n catch (e) {\n errorHandler(\"Error in onSuccess callback\", e);\n }\n }\n scene._removePendingData(loadingToken);\n };\n return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {\n if (plugin.loadAssetContainer) {\n var syncedPlugin = plugin;\n var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);\n if (!assetContainer) {\n return;\n }\n scene.loadingPluginName = plugin.name;\n successHandler(assetContainer);\n }\n else if (plugin.loadAssetContainerAsync) {\n var asyncedPlugin = plugin;\n asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {\n scene.loadingPluginName = plugin.name;\n successHandler(assetContainer);\n }).catch(function (error) {\n errorHandler(error.message, error);\n });\n }\n else {\n errorHandler(\"LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.\");\n }\n if (SceneLoader.ShowLoadingScreen) {\n scene.executeWhenReady(function () {\n scene.getEngine().hideLoadingUI();\n });\n }\n }, progressHandler, errorHandler, disposeHandler, pluginExtension);\n };\n /**\n * Load a scene into an asset container\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded asset container\n */\n SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {\n if (sceneFilename === void 0) { sceneFilename = \"\"; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (onProgress === void 0) { onProgress = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n return new Promise(function (resolve, reject) {\n SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {\n resolve(assetContainer);\n }, onProgress, function (scene, message, exception) {\n reject(exception || new Error(message));\n }, pluginExtension);\n });\n };\n // Flags\n SceneLoader._ForceFullSceneLoadingForIncremental = false;\n SceneLoader._ShowLoadingScreen = true;\n SceneLoader._CleanBoneMatrixWeights = false;\n SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;\n // Members\n SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();\n SceneLoader._registeredPlugins = {};\n return SceneLoader;\n }());\n BABYLON.SceneLoader = SceneLoader;\n ;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sceneLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var parseMaterialById = function (id, parsedData, scene, rootUrl) {\n for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {\n var parsedMaterial = parsedData.materials[index];\n if (parsedMaterial.id === id) {\n return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);\n }\n }\n return null;\n };\n var isDescendantOf = function (mesh, names, hierarchyIds) {\n for (var i in names) {\n if (mesh.name === names[i]) {\n hierarchyIds.push(mesh.id);\n return true;\n }\n }\n if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {\n hierarchyIds.push(mesh.id);\n return true;\n }\n return false;\n };\n var logOperation = function (operation, producer) {\n return operation + \" of \" + (producer ? producer.file + \" from \" + producer.name + \" version: \" + producer.version + \", exporter version: \" + producer.exporter_version : \"unknown\");\n };\n var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {\n if (addToScene === void 0) { addToScene = false; }\n var container = new BABYLON.AssetContainer(scene);\n // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details\n // when SceneLoader.debugLogging = true (default), or exception encountered.\n // Everything stored in var log instead of writing separate lines to support only writing in exception,\n // and avoid problems with multiple concurrent .babylon loads.\n var log = \"importScene has failed JSON parse\";\n try {\n var parsedData = JSON.parse(data);\n log = \"\";\n var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;\n var index;\n var cache;\n // Lights\n if (parsedData.lights !== undefined && parsedData.lights !== null) {\n for (index = 0, cache = parsedData.lights.length; index < cache; index++) {\n var parsedLight = parsedData.lights[index];\n var light = BABYLON.Light.Parse(parsedLight, scene);\n if (light) {\n container.lights.push(light);\n log += (index === 0 ? \"\\n\\tLights:\" : \"\");\n log += \"\\n\\t\\t\" + light.toString(fullDetails);\n }\n }\n }\n // Animations\n if (parsedData.animations !== undefined && parsedData.animations !== null) {\n for (index = 0, cache = parsedData.animations.length; index < cache; index++) {\n var parsedAnimation = parsedData.animations[index];\n var animation = BABYLON.Animation.Parse(parsedAnimation);\n scene.animations.push(animation);\n container.animations.push(animation);\n log += (index === 0 ? \"\\n\\tAnimations:\" : \"\");\n log += \"\\n\\t\\t\" + animation.toString(fullDetails);\n }\n }\n // Materials\n if (parsedData.materials !== undefined && parsedData.materials !== null) {\n for (index = 0, cache = parsedData.materials.length; index < cache; index++) {\n var parsedMaterial = parsedData.materials[index];\n var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);\n container.materials.push(mat);\n log += (index === 0 ? \"\\n\\tMaterials:\" : \"\");\n log += \"\\n\\t\\t\" + mat.toString(fullDetails);\n }\n }\n if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {\n for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {\n var parsedMultiMaterial = parsedData.multiMaterials[index];\n var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);\n container.multiMaterials.push(mmat);\n log += (index === 0 ? \"\\n\\tMultiMaterials:\" : \"\");\n log += \"\\n\\t\\t\" + mmat.toString(fullDetails);\n }\n }\n // Morph targets\n if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {\n for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {\n var managerData = _a[_i];\n container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));\n }\n }\n // Skeletons\n if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {\n for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {\n var parsedSkeleton = parsedData.skeletons[index];\n var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);\n container.skeletons.push(skeleton);\n log += (index === 0 ? \"\\n\\tSkeletons:\" : \"\");\n log += \"\\n\\t\\t\" + skeleton.toString(fullDetails);\n }\n }\n // Geometries\n var geometries = parsedData.geometries;\n if (geometries !== undefined && geometries !== null) {\n var addedGeometry = new Array();\n // Boxes\n var boxes = geometries.boxes;\n if (boxes !== undefined && boxes !== null) {\n for (index = 0, cache = boxes.length; index < cache; index++) {\n var parsedBox = boxes[index];\n addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));\n }\n }\n // Spheres\n var spheres = geometries.spheres;\n if (spheres !== undefined && spheres !== null) {\n for (index = 0, cache = spheres.length; index < cache; index++) {\n var parsedSphere = spheres[index];\n addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));\n }\n }\n // Cylinders\n var cylinders = geometries.cylinders;\n if (cylinders !== undefined && cylinders !== null) {\n for (index = 0, cache = cylinders.length; index < cache; index++) {\n var parsedCylinder = cylinders[index];\n addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));\n }\n }\n // Toruses\n var toruses = geometries.toruses;\n if (toruses !== undefined && toruses !== null) {\n for (index = 0, cache = toruses.length; index < cache; index++) {\n var parsedTorus = toruses[index];\n addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));\n }\n }\n // Grounds\n var grounds = geometries.grounds;\n if (grounds !== undefined && grounds !== null) {\n for (index = 0, cache = grounds.length; index < cache; index++) {\n var parsedGround = grounds[index];\n addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));\n }\n }\n // Planes\n var planes = geometries.planes;\n if (planes !== undefined && planes !== null) {\n for (index = 0, cache = planes.length; index < cache; index++) {\n var parsedPlane = planes[index];\n addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));\n }\n }\n // TorusKnots\n var torusKnots = geometries.torusKnots;\n if (torusKnots !== undefined && torusKnots !== null) {\n for (index = 0, cache = torusKnots.length; index < cache; index++) {\n var parsedTorusKnot = torusKnots[index];\n addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));\n }\n }\n // VertexData\n var vertexData = geometries.vertexData;\n if (vertexData !== undefined && vertexData !== null) {\n for (index = 0, cache = vertexData.length; index < cache; index++) {\n var parsedVertexData = vertexData[index];\n addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));\n }\n }\n addedGeometry.forEach(function (g) {\n if (g) {\n container.geometries.push(g);\n }\n });\n }\n // Transform nodes\n if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {\n for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {\n var parsedTransformNode = parsedData.transformNodes[index];\n var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);\n container.transformNodes.push(node);\n }\n }\n // Meshes\n if (parsedData.meshes !== undefined && parsedData.meshes !== null) {\n for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {\n var parsedMesh = parsedData.meshes[index];\n var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);\n container.meshes.push(mesh);\n log += (index === 0 ? \"\\n\\tMeshes:\" : \"\");\n log += \"\\n\\t\\t\" + mesh.toString(fullDetails);\n }\n }\n // Cameras\n if (parsedData.cameras !== undefined && parsedData.cameras !== null) {\n for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {\n var parsedCamera = parsedData.cameras[index];\n var camera = BABYLON.Camera.Parse(parsedCamera, scene);\n container.cameras.push(camera);\n log += (index === 0 ? \"\\n\\tCameras:\" : \"\");\n log += \"\\n\\t\\t\" + camera.toString(fullDetails);\n }\n }\n // Browsing all the graph to connect the dots\n for (index = 0, cache = scene.cameras.length; index < cache; index++) {\n var camera = scene.cameras[index];\n if (camera._waitingParentId) {\n camera.parent = scene.getLastEntryByID(camera._waitingParentId);\n camera._waitingParentId = null;\n }\n }\n for (index = 0, cache = scene.lights.length; index < cache; index++) {\n var light_1 = scene.lights[index];\n if (light_1 && light_1._waitingParentId) {\n light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);\n light_1._waitingParentId = null;\n }\n }\n // Sounds\n // TODO: add sound\n var loadedSounds = [];\n var loadedSound;\n if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {\n for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {\n var parsedSound = parsedData.sounds[index];\n if (BABYLON.Engine.audioEngine.canUseWebAudio) {\n if (!parsedSound.url)\n parsedSound.url = parsedSound.name;\n if (!loadedSounds[parsedSound.url]) {\n loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);\n loadedSounds[parsedSound.url] = loadedSound;\n container.sounds.push(loadedSound);\n }\n else {\n container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));\n }\n }\n else {\n container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));\n }\n }\n }\n loadedSounds = [];\n // Connect parents & children and parse actions\n for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {\n var transformNode = scene.transformNodes[index];\n if (transformNode._waitingParentId) {\n transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);\n transformNode._waitingParentId = null;\n }\n }\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n var mesh = scene.meshes[index];\n if (mesh._waitingParentId) {\n mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);\n mesh._waitingParentId = null;\n }\n if (mesh._waitingActions) {\n BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);\n mesh._waitingActions = null;\n }\n }\n // freeze world matrix application\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n var currentMesh = scene.meshes[index];\n if (currentMesh._waitingFreezeWorldMatrix) {\n currentMesh.freezeWorldMatrix();\n currentMesh._waitingFreezeWorldMatrix = null;\n }\n else {\n currentMesh.computeWorldMatrix(true);\n }\n }\n // Shadows\n if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {\n for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {\n var parsedShadowGenerator = parsedData.shadowGenerators[index];\n BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);\n // SG would be available on their associated lights\n }\n }\n // Lights exclusions / inclusions\n for (index = 0, cache = scene.lights.length; index < cache; index++) {\n var light_2 = scene.lights[index];\n // Excluded check\n if (light_2._excludedMeshesIds.length > 0) {\n for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {\n var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);\n if (excludedMesh) {\n light_2.excludedMeshes.push(excludedMesh);\n }\n }\n light_2._excludedMeshesIds = [];\n }\n // Included check\n if (light_2._includedOnlyMeshesIds.length > 0) {\n for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {\n var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);\n if (includedOnlyMesh) {\n light_2.includedOnlyMeshes.push(includedOnlyMesh);\n }\n }\n light_2._includedOnlyMeshesIds = [];\n }\n }\n BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);\n // Actions (scene)\n if (parsedData.actions !== undefined && parsedData.actions !== null) {\n BABYLON.ActionManager.Parse(parsedData.actions, null, scene);\n }\n if (!addToScene) {\n container.removeAllFromScene();\n }\n }\n catch (err) {\n var msg = logOperation(\"loadAssts\", parsedData ? parsedData.producer : \"Unknown\") + log;\n if (onError) {\n onError(msg, err);\n }\n else {\n BABYLON.Tools.Log(msg);\n throw err;\n }\n }\n finally {\n if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {\n BABYLON.Tools.Log(logOperation(\"loadAssts\", parsedData ? parsedData.producer : \"Unknown\") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : \"\"));\n }\n }\n return container;\n };\n BABYLON.SceneLoader.RegisterPlugin({\n name: \"babylon.js\",\n extensions: \".babylon\",\n canDirectLoad: function (data) {\n if (data.indexOf(\"babylon\") !== -1) { // We consider that the producer string is filled\n return true;\n }\n return false;\n },\n importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {\n // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details\n // when SceneLoader.debugLogging = true (default), or exception encountered.\n // Everything stored in var log instead of writing separate lines to support only writing in exception,\n // and avoid problems with multiple concurrent .babylon loads.\n var log = \"importMesh has failed JSON parse\";\n try {\n var parsedData = JSON.parse(data);\n log = \"\";\n var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;\n if (!meshesNames) {\n meshesNames = null;\n }\n else if (!Array.isArray(meshesNames)) {\n meshesNames = [meshesNames];\n }\n var hierarchyIds = new Array();\n if (parsedData.meshes !== undefined && parsedData.meshes !== null) {\n var loadedSkeletonsIds = [];\n var loadedMaterialsIds = [];\n var index;\n var cache;\n for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {\n var parsedMesh = parsedData.meshes[index];\n if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {\n if (meshesNames !== null) {\n // Remove found mesh name from list.\n delete meshesNames[meshesNames.indexOf(parsedMesh.name)];\n }\n //Geometry?\n if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {\n //does the file contain geometries?\n if (parsedData.geometries !== undefined && parsedData.geometries !== null) {\n //find the correct geometry and add it to the scene\n var found = false;\n [\"boxes\", \"spheres\", \"cylinders\", \"toruses\", \"grounds\", \"planes\", \"torusKnots\", \"vertexData\"].forEach(function (geometryType) {\n if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {\n return;\n }\n else {\n parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {\n if (parsedGeometryData.id === parsedMesh.geometryId) {\n switch (geometryType) {\n case \"boxes\":\n BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"spheres\":\n BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"cylinders\":\n BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"toruses\":\n BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"grounds\":\n BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"planes\":\n BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"torusKnots\":\n BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"vertexData\":\n BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);\n break;\n }\n found = true;\n }\n });\n }\n });\n if (found === false) {\n BABYLON.Tools.Warn(\"Geometry not found for mesh \" + parsedMesh.id);\n }\n }\n }\n // Material ?\n if (parsedMesh.materialId) {\n var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);\n if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {\n for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {\n var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];\n if (parsedMultiMaterial.id === parsedMesh.materialId) {\n for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {\n var subMatId = parsedMultiMaterial.materials[matIndex];\n loadedMaterialsIds.push(subMatId);\n var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);\n if (mat) {\n log += \"\\n\\tMaterial \" + mat.toString(fullDetails);\n }\n }\n loadedMaterialsIds.push(parsedMultiMaterial.id);\n var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);\n if (mmat) {\n materialFound = true;\n log += \"\\n\\tMulti-Material \" + mmat.toString(fullDetails);\n }\n break;\n }\n }\n }\n if (materialFound === false) {\n loadedMaterialsIds.push(parsedMesh.materialId);\n var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);\n if (!mat) {\n BABYLON.Tools.Warn(\"Material not found for mesh \" + parsedMesh.id);\n }\n else {\n log += \"\\n\\tMaterial \" + mat.toString(fullDetails);\n }\n }\n }\n // Skeleton ?\n if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {\n var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);\n if (skeletonAlreadyLoaded === false) {\n for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {\n var parsedSkeleton = parsedData.skeletons[skeletonIndex];\n if (parsedSkeleton.id === parsedMesh.skeletonId) {\n var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);\n skeletons.push(skeleton);\n loadedSkeletonsIds.push(parsedSkeleton.id);\n log += \"\\n\\tSkeleton \" + skeleton.toString(fullDetails);\n }\n }\n }\n }\n // Morph targets ?\n if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {\n for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {\n var managerData = _a[_i];\n BABYLON.MorphTargetManager.Parse(managerData, scene);\n }\n }\n var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);\n meshes.push(mesh);\n log += \"\\n\\tMesh \" + mesh.toString(fullDetails);\n }\n }\n // Connecting parents\n var currentMesh;\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n currentMesh = scene.meshes[index];\n if (currentMesh._waitingParentId) {\n currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);\n currentMesh._waitingParentId = null;\n }\n }\n // freeze and compute world matrix application\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n currentMesh = scene.meshes[index];\n if (currentMesh._waitingFreezeWorldMatrix) {\n currentMesh.freezeWorldMatrix();\n currentMesh._waitingFreezeWorldMatrix = null;\n }\n else {\n currentMesh.computeWorldMatrix(true);\n }\n }\n }\n // Particles\n if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {\n var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);\n if (parser) {\n for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {\n var parsedParticleSystem = parsedData.particleSystems[index];\n if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {\n particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));\n }\n }\n }\n }\n return true;\n }\n catch (err) {\n var msg = logOperation(\"importMesh\", parsedData ? parsedData.producer : \"Unknown\") + log;\n if (onError) {\n onError(msg, err);\n }\n else {\n BABYLON.Tools.Log(msg);\n throw err;\n }\n }\n finally {\n if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {\n BABYLON.Tools.Log(logOperation(\"importMesh\", parsedData ? parsedData.producer : \"Unknown\") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : \"\"));\n }\n }\n return false;\n },\n load: function (scene, data, rootUrl, onError) {\n // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details\n // when SceneLoader.debugLogging = true (default), or exception encountered.\n // Everything stored in var log instead of writing separate lines to support only writing in exception,\n // and avoid problems with multiple concurrent .babylon loads.\n var log = \"importScene has failed JSON parse\";\n try {\n var parsedData = JSON.parse(data);\n log = \"\";\n // Scene\n if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {\n scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;\n }\n if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {\n scene.autoClear = parsedData.autoClear;\n }\n if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {\n scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);\n }\n if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {\n scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);\n }\n if (parsedData.gravity !== undefined && parsedData.gravity !== null) {\n scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);\n }\n // Fog\n if (parsedData.fogMode && parsedData.fogMode !== 0) {\n scene.fogMode = parsedData.fogMode;\n scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);\n scene.fogStart = parsedData.fogStart;\n scene.fogEnd = parsedData.fogEnd;\n scene.fogDensity = parsedData.fogDensity;\n log += \"\\tFog mode for scene: \";\n switch (scene.fogMode) {\n // getters not compiling, so using hardcoded\n case 1:\n log += \"exp\\n\";\n break;\n case 2:\n log += \"exp2\\n\";\n break;\n case 3:\n log += \"linear\\n\";\n break;\n }\n }\n //Physics\n if (parsedData.physicsEnabled) {\n var physicsPlugin;\n if (parsedData.physicsEngine === \"cannon\") {\n physicsPlugin = new BABYLON.CannonJSPlugin();\n }\n else if (parsedData.physicsEngine === \"oimo\") {\n physicsPlugin = new BABYLON.OimoJSPlugin();\n }\n log = \"\\tPhysics engine \" + (parsedData.physicsEngine ? parsedData.physicsEngine : \"oimo\") + \" enabled\\n\";\n //else - default engine, which is currently oimo\n var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;\n scene.enablePhysics(physicsGravity, physicsPlugin);\n }\n // Metadata\n if (parsedData.metadata !== undefined && parsedData.metadata !== null) {\n scene.metadata = parsedData.metadata;\n }\n //collisions, if defined. otherwise, default is true\n if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {\n scene.collisionsEnabled = parsedData.collisionsEnabled;\n }\n scene.workerCollisions = !!parsedData.workerCollisions;\n var container = loadAssetContainer(scene, data, rootUrl, onError, true);\n if (!container) {\n return false;\n }\n if (parsedData.autoAnimate) {\n scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);\n }\n if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {\n scene.setActiveCameraByID(parsedData.activeCameraID);\n }\n // Environment texture\t\t\n if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {\n if (parsedData.environmentTextureType && parsedData.environmentTextureType === \"BABYLON.HDRCubeTexture\") {\n var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;\n var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);\n if (parsedData.environmentTextureRotationY) {\n hdrTexture.rotationY = parsedData.environmentTextureRotationY;\n }\n scene.environmentTexture = hdrTexture;\n }\n else {\n var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);\n if (parsedData.environmentTextureRotationY) {\n cubeTexture.rotationY = parsedData.environmentTextureRotationY;\n }\n scene.environmentTexture = cubeTexture;\n }\n if (parsedData.createDefaultSkybox === true) {\n var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;\n var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;\n scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);\n }\n }\n // Finish\n return true;\n }\n catch (err) {\n var msg = logOperation(\"importScene\", parsedData ? parsedData.producer : \"Unknown\") + log;\n if (onError) {\n onError(msg, err);\n }\n else {\n BABYLON.Tools.Log(msg);\n throw err;\n }\n }\n finally {\n if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {\n BABYLON.Tools.Log(logOperation(\"importScene\", parsedData ? parsedData.producer : \"Unknown\") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : \"\"));\n }\n }\n return false;\n },\n loadAssetContainer: function (scene, data, rootUrl, onError) {\n var container = loadAssetContainer(scene, data, rootUrl, onError);\n return container;\n }\n });\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.babylonFileLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var FilesInput = /** @class */ (function () {\n function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {\n this.onProcessFileCallback = function () { return true; };\n this._engine = engine;\n this._currentScene = scene;\n this._sceneLoadedCallback = sceneLoadedCallback;\n this._progressCallback = progressCallback;\n this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;\n this._textureLoadingCallback = textureLoadingCallback;\n this._startingProcessingFilesCallback = startingProcessingFilesCallback;\n this._onReloadCallback = onReloadCallback;\n this._errorCallback = errorCallback;\n }\n FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {\n var _this = this;\n if (elementToMonitor) {\n this._elementToMonitor = elementToMonitor;\n this._dragEnterHandler = function (e) { _this.drag(e); };\n this._dragOverHandler = function (e) { _this.drag(e); };\n this._dropHandler = function (e) { _this.drop(e); };\n this._elementToMonitor.addEventListener(\"dragenter\", this._dragEnterHandler, false);\n this._elementToMonitor.addEventListener(\"dragover\", this._dragOverHandler, false);\n this._elementToMonitor.addEventListener(\"drop\", this._dropHandler, false);\n }\n };\n FilesInput.prototype.dispose = function () {\n if (!this._elementToMonitor) {\n return;\n }\n this._elementToMonitor.removeEventListener(\"dragenter\", this._dragEnterHandler);\n this._elementToMonitor.removeEventListener(\"dragover\", this._dragOverHandler);\n this._elementToMonitor.removeEventListener(\"drop\", this._dropHandler);\n };\n FilesInput.prototype.renderFunction = function () {\n if (this._additionalRenderLoopLogicCallback) {\n this._additionalRenderLoopLogicCallback();\n }\n if (this._currentScene) {\n if (this._textureLoadingCallback) {\n var remaining = this._currentScene.getWaitingItemsCount();\n if (remaining > 0) {\n this._textureLoadingCallback(remaining);\n }\n }\n this._currentScene.render();\n }\n };\n FilesInput.prototype.drag = function (e) {\n e.stopPropagation();\n e.preventDefault();\n };\n FilesInput.prototype.drop = function (eventDrop) {\n eventDrop.stopPropagation();\n eventDrop.preventDefault();\n this.loadFiles(eventDrop);\n };\n FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {\n var _this = this;\n var reader = folder.createReader();\n var relativePath = folder.fullPath.replace(/^\\//, \"\").replace(/(.+?)\\/?$/, \"$1/\");\n reader.readEntries(function (entries) {\n remaining.count += entries.length;\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n var entry = entries_1[_i];\n if (entry.isFile) {\n entry.file(function (file) {\n file.correctName = relativePath + file.name;\n files.push(file);\n if (--remaining.count === 0) {\n callback();\n }\n });\n }\n else if (entry.isDirectory) {\n _this._traverseFolder(entry, files, remaining, callback);\n }\n }\n if (--remaining.count) {\n callback();\n }\n });\n };\n FilesInput.prototype._processFiles = function (files) {\n for (var i = 0; i < files.length; i++) {\n var name = files[i].correctName.toLowerCase();\n var extension = name.split('.').pop();\n if (!this.onProcessFileCallback(files[i], name, extension)) {\n continue;\n }\n if ((extension === \"babylon\" || extension === \"stl\" || extension === \"obj\" || extension === \"gltf\" || extension === \"glb\")\n && name.indexOf(\".binary.babylon\") === -1 && name.indexOf(\".incremental.babylon\") === -1) {\n this._sceneFileToLoad = files[i];\n }\n else {\n FilesInput.FilesToLoad[name] = files[i];\n }\n }\n };\n FilesInput.prototype.loadFiles = function (event) {\n var _this = this;\n if (this._startingProcessingFilesCallback)\n this._startingProcessingFilesCallback();\n // Handling data transfer via drag'n'drop\n if (event && event.dataTransfer && event.dataTransfer.files) {\n this._filesToLoad = event.dataTransfer.files;\n }\n // Handling files from input files\n if (event && event.target && event.target.files) {\n this._filesToLoad = event.target.files;\n }\n if (this._filesToLoad && this._filesToLoad.length > 0) {\n var files_1 = new Array();\n var folders = [];\n var items = event.dataTransfer ? event.dataTransfer.items : null;\n for (var i = 0; i < this._filesToLoad.length; i++) {\n var fileToLoad = this._filesToLoad[i];\n var name_1 = fileToLoad.name.toLowerCase();\n var entry = void 0;\n fileToLoad.correctName = name_1;\n if (items) {\n var item = items[i];\n if (item.getAsEntry) {\n entry = item.getAsEntry();\n }\n else if (item.webkitGetAsEntry) {\n entry = item.webkitGetAsEntry();\n }\n }\n if (!entry) {\n files_1.push(fileToLoad);\n }\n else {\n if (entry.isDirectory) {\n folders.push(entry);\n }\n else {\n files_1.push(fileToLoad);\n }\n }\n }\n if (folders.length === 0) {\n this._processFiles(files_1);\n this._processReload();\n }\n else {\n var remaining = { count: folders.length };\n for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {\n var folder = folders_1[_i];\n this._traverseFolder(folder, files_1, remaining, function () {\n _this._processFiles(files_1);\n if (remaining.count === 0) {\n _this._processReload();\n }\n });\n }\n }\n }\n };\n FilesInput.prototype._processReload = function () {\n if (this._onReloadCallback) {\n this._onReloadCallback(this._sceneFileToLoad);\n }\n else {\n this.reload();\n }\n };\n FilesInput.prototype.reload = function () {\n var _this = this;\n // If a scene file has been provided\n if (this._sceneFileToLoad) {\n if (this._currentScene) {\n if (BABYLON.Tools.errorsCount > 0) {\n BABYLON.Tools.ClearLogCache();\n }\n this._engine.stopRenderLoop();\n }\n BABYLON.SceneLoader.LoadAsync(\"file:\", this._sceneFileToLoad, this._engine, function (progress) {\n if (_this._progressCallback) {\n _this._progressCallback(progress);\n }\n }).then(function (scene) {\n if (_this._currentScene) {\n _this._currentScene.dispose();\n }\n _this._currentScene = scene;\n if (_this._sceneLoadedCallback) {\n _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);\n }\n // Wait for textures and shaders to be ready\n _this._currentScene.executeWhenReady(function () {\n _this._engine.runRenderLoop(function () {\n _this.renderFunction();\n });\n });\n }).catch(function (error) {\n if (_this._errorCallback) {\n _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);\n }\n });\n }\n else {\n BABYLON.Tools.Error(\"Please provide a valid .babylon file.\");\n }\n };\n FilesInput.FilesToLoad = {};\n return FilesInput;\n }());\n BABYLON.FilesInput = FilesInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.filesInput.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Tags = /** @class */ (function () {\n function Tags() {\n }\n Tags.EnableFor = function (obj) {\n obj._tags = obj._tags || {};\n obj.hasTags = function () {\n return Tags.HasTags(obj);\n };\n obj.addTags = function (tagsString) {\n return Tags.AddTagsTo(obj, tagsString);\n };\n obj.removeTags = function (tagsString) {\n return Tags.RemoveTagsFrom(obj, tagsString);\n };\n obj.matchesTagsQuery = function (tagsQuery) {\n return Tags.MatchesQuery(obj, tagsQuery);\n };\n };\n Tags.DisableFor = function (obj) {\n delete obj._tags;\n delete obj.hasTags;\n delete obj.addTags;\n delete obj.removeTags;\n delete obj.matchesTagsQuery;\n };\n Tags.HasTags = function (obj) {\n if (!obj._tags) {\n return false;\n }\n return !BABYLON.Tools.IsEmpty(obj._tags);\n };\n Tags.GetTags = function (obj, asString) {\n if (asString === void 0) { asString = true; }\n if (!obj._tags) {\n return null;\n }\n if (asString) {\n var tagsArray = [];\n for (var tag in obj._tags) {\n if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {\n tagsArray.push(tag);\n }\n }\n return tagsArray.join(\" \");\n }\n else {\n return obj._tags;\n }\n };\n // the tags 'true' and 'false' are reserved and cannot be used as tags\n // a tag cannot start with '||', '&&', and '!'\n // it cannot contain whitespaces\n Tags.AddTagsTo = function (obj, tagsString) {\n if (!tagsString) {\n return;\n }\n if (typeof tagsString !== \"string\") {\n return;\n }\n var tags = tagsString.split(\" \");\n tags.forEach(function (tag, index, array) {\n Tags._AddTagTo(obj, tag);\n });\n };\n Tags._AddTagTo = function (obj, tag) {\n tag = tag.trim();\n if (tag === \"\" || tag === \"true\" || tag === \"false\") {\n return;\n }\n if (tag.match(/[\\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {\n return;\n }\n Tags.EnableFor(obj);\n obj._tags[tag] = true;\n };\n Tags.RemoveTagsFrom = function (obj, tagsString) {\n if (!Tags.HasTags(obj)) {\n return;\n }\n var tags = tagsString.split(\" \");\n for (var t in tags) {\n Tags._RemoveTagFrom(obj, tags[t]);\n }\n };\n Tags._RemoveTagFrom = function (obj, tag) {\n delete obj._tags[tag];\n };\n Tags.MatchesQuery = function (obj, tagsQuery) {\n if (tagsQuery === undefined) {\n return true;\n }\n if (tagsQuery === \"\") {\n return Tags.HasTags(obj);\n }\n return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });\n };\n return Tags;\n }());\n BABYLON.Tags = Tags;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.tags.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to evalaute queries containing `and` and `or` operators\n */\n var AndOrNotEvaluator = /** @class */ (function () {\n function AndOrNotEvaluator() {\n }\n /**\n * Evaluate a query\n * @param query defines the query to evaluate\n * @param evaluateCallback defines the callback used to filter result\n * @returns true if the query matches\n */\n AndOrNotEvaluator.Eval = function (query, evaluateCallback) {\n if (!query.match(/\\([^\\(\\)]*\\)/g)) {\n query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);\n }\n else {\n query = query.replace(/\\([^\\(\\)]*\\)/g, function (r) {\n // remove parenthesis\n r = r.slice(1, r.length - 1);\n return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);\n });\n }\n if (query === \"true\") {\n return true;\n }\n if (query === \"false\") {\n return false;\n }\n return AndOrNotEvaluator.Eval(query, evaluateCallback);\n };\n AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {\n evaluateCallback = evaluateCallback || (function (r) {\n return r === \"true\" ? true : false;\n });\n var result;\n var or = parenthesisContent.split(\"||\");\n for (var i in or) {\n if (or.hasOwnProperty(i)) {\n var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());\n var and = ori.split(\"&&\");\n if (and.length > 1) {\n for (var j = 0; j < and.length; ++j) {\n var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());\n if (andj !== \"true\" && andj !== \"false\") {\n if (andj[0] === \"!\") {\n result = !evaluateCallback(andj.substring(1));\n }\n else {\n result = evaluateCallback(andj);\n }\n }\n else {\n result = andj === \"true\" ? true : false;\n }\n if (!result) { // no need to continue since 'false && ... && ...' will always return false\n ori = \"false\";\n break;\n }\n }\n }\n if (result || ori === \"true\") { // no need to continue since 'true || ... || ...' will always return true\n result = true;\n break;\n }\n // result equals false (or undefined)\n if (ori !== \"true\" && ori !== \"false\") {\n if (ori[0] === \"!\") {\n result = !evaluateCallback(ori.substring(1));\n }\n else {\n result = evaluateCallback(ori);\n }\n }\n else {\n result = ori === \"true\" ? true : false;\n }\n }\n }\n // the whole parenthesis scope is replaced by 'true' or 'false'\n return result ? \"true\" : \"false\";\n };\n AndOrNotEvaluator._SimplifyNegation = function (booleanString) {\n booleanString = booleanString.replace(/^[\\s!]+/, function (r) {\n // remove whitespaces\n r = r.replace(/[\\s]/g, function () { return \"\"; });\n return r.length % 2 ? \"!\" : \"\";\n });\n booleanString = booleanString.trim();\n if (booleanString === \"!true\") {\n booleanString = \"false\";\n }\n else if (booleanString === \"!false\") {\n booleanString = \"true\";\n }\n return booleanString;\n };\n return AndOrNotEvaluator;\n }());\n BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.andOrNotEvaluator.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to enable access to IndexedDB\n * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API\n */\n var Database = /** @class */ (function () {\n /**\n * Creates a new Database\n * @param urlToScene defines the url to load the scene\n * @param callbackManifestChecked defines the callback to use when manifest is checked\n * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)\n */\n function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {\n if (disableManifestCheck === void 0) { disableManifestCheck = false; }\n var _this = this;\n // Handling various flavors of prefixed version of IndexedDB\n this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);\n this.callbackManifestChecked = callbackManifestChecked;\n this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);\n this.db = null;\n this._enableSceneOffline = false;\n this._enableTexturesOffline = false;\n this.manifestVersionFound = 0;\n this.mustUpdateRessources = false;\n this.hasReachedQuota = false;\n if (!Database.IDBStorageEnabled) {\n this.callbackManifestChecked(true);\n }\n else {\n if (disableManifestCheck) {\n this._enableSceneOffline = true;\n this._enableTexturesOffline = true;\n this.manifestVersionFound = 1;\n BABYLON.Tools.SetImmediate(function () {\n _this.callbackManifestChecked(true);\n });\n }\n else {\n this._checkManifestFile();\n }\n }\n }\n Object.defineProperty(Database.prototype, \"enableSceneOffline\", {\n /**\n * Gets a boolean indicating if scene must be saved in the database\n */\n get: function () {\n return this._enableSceneOffline;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Database.prototype, \"enableTexturesOffline\", {\n /**\n * Gets a boolean indicating if textures must be saved in the database\n */\n get: function () {\n return this._enableTexturesOffline;\n },\n enumerable: true,\n configurable: true\n });\n Database.prototype._checkManifestFile = function () {\n var _this = this;\n var noManifestFile = function () {\n _this._enableSceneOffline = false;\n _this._enableTexturesOffline = false;\n _this.callbackManifestChecked(false);\n };\n var timeStampUsed = false;\n var manifestURL = this.currentSceneUrl + \".manifest\";\n var xhr = new XMLHttpRequest();\n if (navigator.onLine) {\n // Adding a timestamp to by-pass browsers' cache\n timeStampUsed = true;\n manifestURL = manifestURL + (manifestURL.match(/\\?/) == null ? \"?\" : \"&\") + Date.now();\n }\n xhr.open(\"GET\", manifestURL, true);\n xhr.addEventListener(\"load\", function () {\n if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {\n try {\n var manifestFile = JSON.parse(xhr.response);\n _this._enableSceneOffline = manifestFile.enableSceneOffline;\n _this._enableTexturesOffline = manifestFile.enableTexturesOffline;\n if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {\n _this.manifestVersionFound = manifestFile.version;\n }\n if (_this.callbackManifestChecked) {\n _this.callbackManifestChecked(true);\n }\n }\n catch (ex) {\n noManifestFile();\n }\n }\n else {\n noManifestFile();\n }\n }, false);\n xhr.addEventListener(\"error\", function (event) {\n if (timeStampUsed) {\n timeStampUsed = false;\n // Let's retry without the timeStamp\n // It could fail when coupled with HTML5 Offline API\n var retryManifestURL = _this.currentSceneUrl + \".manifest\";\n xhr.open(\"GET\", retryManifestURL, true);\n xhr.send();\n }\n else {\n noManifestFile();\n }\n }, false);\n try {\n xhr.send();\n }\n catch (ex) {\n BABYLON.Tools.Error(\"Error on XHR send request.\");\n this.callbackManifestChecked(false);\n }\n };\n /**\n * Open the database and make it available\n * @param successCallback defines the callback to call on success\n * @param errorCallback defines the callback to call on error\n */\n Database.prototype.openAsync = function (successCallback, errorCallback) {\n var _this = this;\n var handleError = function () {\n _this.isSupported = false;\n if (errorCallback)\n errorCallback();\n };\n if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {\n // Your browser doesn't support IndexedDB\n this.isSupported = false;\n if (errorCallback)\n errorCallback();\n }\n else {\n // If the DB hasn't been opened or created yet\n if (!this.db) {\n this.hasReachedQuota = false;\n this.isSupported = true;\n var request = this.idbFactory.open(\"babylonjs\", 1);\n // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB\n request.onerror = function (event) {\n handleError();\n };\n // executes when a version change transaction cannot complete due to other active transactions\n request.onblocked = function (event) {\n BABYLON.Tools.Error(\"IDB request blocked. Please reload the page.\");\n handleError();\n };\n // DB has been opened successfully\n request.onsuccess = function (event) {\n _this.db = request.result;\n successCallback();\n };\n // Initialization of the DB. Creating Scenes & Textures stores\n request.onupgradeneeded = function (event) {\n _this.db = (event.target).result;\n if (_this.db) {\n try {\n _this.db.createObjectStore(\"scenes\", { keyPath: \"sceneUrl\" });\n _this.db.createObjectStore(\"versions\", { keyPath: \"sceneUrl\" });\n _this.db.createObjectStore(\"textures\", { keyPath: \"textureUrl\" });\n }\n catch (ex) {\n BABYLON.Tools.Error(\"Error while creating object stores. Exception: \" + ex.message);\n handleError();\n }\n }\n };\n }\n // DB has already been created and opened\n else {\n if (successCallback)\n successCallback();\n }\n }\n };\n /**\n * Loads an image from the database\n * @param url defines the url to load from\n * @param image defines the target DOM image\n */\n Database.prototype.loadImageFromDB = function (url, image) {\n var _this = this;\n var completeURL = Database._ReturnFullUrlLocation(url);\n var saveAndLoadImage = function () {\n if (!_this.hasReachedQuota && _this.db !== null) {\n // the texture is not yet in the DB, let's try to save it\n _this._saveImageIntoDBAsync(completeURL, image);\n }\n // If the texture is not in the DB and we've reached the DB quota limit\n // let's load it directly from the web\n else {\n image.src = url;\n }\n };\n if (!this.mustUpdateRessources) {\n this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);\n }\n // First time we're download the images or update requested in the manifest file by a version change\n else {\n saveAndLoadImage();\n }\n };\n Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {\n if (this.isSupported && this.db !== null) {\n var texture;\n var transaction = this.db.transaction([\"textures\"]);\n transaction.onabort = function (event) {\n image.src = url;\n };\n transaction.oncomplete = function (event) {\n var blobTextureURL;\n if (texture) {\n var URL = window.URL || window.webkitURL;\n blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });\n image.onerror = function () {\n BABYLON.Tools.Error(\"Error loading image from blob URL: \" + blobTextureURL + \" switching back to web url: \" + url);\n image.src = url;\n };\n image.src = blobTextureURL;\n }\n else {\n notInDBCallback();\n }\n };\n var getRequest = transaction.objectStore(\"textures\").get(url);\n getRequest.onsuccess = function (event) {\n texture = (event.target).result;\n };\n getRequest.onerror = function (event) {\n BABYLON.Tools.Error(\"Error loading texture \" + url + \" from DB.\");\n image.src = url;\n };\n }\n else {\n BABYLON.Tools.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n image.src = url;\n }\n };\n Database.prototype._saveImageIntoDBAsync = function (url, image) {\n var _this = this;\n if (this.isSupported) {\n // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on\n var generateBlobUrl = function () {\n var blobTextureURL;\n if (blob) {\n var URL = window.URL || window.webkitURL;\n try {\n blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });\n }\n // Chrome is raising a type error if we're setting the oneTimeOnly parameter\n catch (ex) {\n blobTextureURL = URL.createObjectURL(blob);\n }\n }\n if (blobTextureURL) {\n image.src = blobTextureURL;\n }\n };\n if (Database.IsUASupportingBlobStorage) { // Create XHR\n var xhr = new XMLHttpRequest(), blob;\n xhr.open(\"GET\", url, true);\n xhr.responseType = \"blob\";\n xhr.addEventListener(\"load\", function () {\n if (xhr.status === 200 && _this.db) {\n // Blob as response (XHR2)\n blob = xhr.response;\n var transaction = _this.db.transaction([\"textures\"], \"readwrite\");\n // the transaction could abort because of a QuotaExceededError error\n transaction.onabort = function (event) {\n try {\n //backwards compatibility with ts 1.0, srcElement doesn't have an \"error\" according to ts 1.3\n var srcElement = (event.srcElement || event.target);\n var error = srcElement.error;\n if (error && error.name === \"QuotaExceededError\") {\n _this.hasReachedQuota = true;\n }\n }\n catch (ex) { }\n generateBlobUrl();\n };\n transaction.oncomplete = function (event) {\n generateBlobUrl();\n };\n var newTexture = { textureUrl: url, data: blob };\n try {\n // Put the blob into the dabase\n var addRequest = transaction.objectStore(\"textures\").put(newTexture);\n addRequest.onsuccess = function (event) {\n };\n addRequest.onerror = function (event) {\n generateBlobUrl();\n };\n }\n catch (ex) {\n // \"DataCloneError\" generated by Chrome when you try to inject blob into IndexedDB\n if (ex.code === 25) {\n Database.IsUASupportingBlobStorage = false;\n }\n image.src = url;\n }\n }\n else {\n image.src = url;\n }\n }, false);\n xhr.addEventListener(\"error\", function (event) {\n BABYLON.Tools.Error(\"Error in XHR request in BABYLON.Database.\");\n image.src = url;\n }, false);\n xhr.send();\n }\n else {\n image.src = url;\n }\n }\n else {\n BABYLON.Tools.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n image.src = url;\n }\n };\n Database.prototype._checkVersionFromDB = function (url, versionLoaded) {\n var _this = this;\n var updateVersion = function () {\n // the version is not yet in the DB or we need to update it\n _this._saveVersionIntoDBAsync(url, versionLoaded);\n };\n this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);\n };\n Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {\n var _this = this;\n if (this.isSupported && this.db) {\n var version;\n try {\n var transaction = this.db.transaction([\"versions\"]);\n transaction.oncomplete = function (event) {\n if (version) {\n // If the version in the JSON file is different from the version in DB\n if (_this.manifestVersionFound !== version.data) {\n _this.mustUpdateRessources = true;\n updateInDBCallback();\n }\n else {\n callback(version.data);\n }\n }\n // version was not found in DB\n else {\n _this.mustUpdateRessources = true;\n updateInDBCallback();\n }\n };\n transaction.onabort = function (event) {\n callback(-1);\n };\n var getRequest = transaction.objectStore(\"versions\").get(url);\n getRequest.onsuccess = function (event) {\n version = (event.target).result;\n };\n getRequest.onerror = function (event) {\n BABYLON.Tools.Error(\"Error loading version for scene \" + url + \" from DB.\");\n callback(-1);\n };\n }\n catch (ex) {\n BABYLON.Tools.Error(\"Error while accessing 'versions' object store (READ OP). Exception: \" + ex.message);\n callback(-1);\n }\n }\n else {\n BABYLON.Tools.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n callback(-1);\n }\n };\n Database.prototype._saveVersionIntoDBAsync = function (url, callback) {\n var _this = this;\n if (this.isSupported && !this.hasReachedQuota && this.db) {\n try {\n // Open a transaction to the database\n var transaction = this.db.transaction([\"versions\"], \"readwrite\");\n // the transaction could abort because of a QuotaExceededError error\n transaction.onabort = function (event) {\n try { //backwards compatibility with ts 1.0, srcElement doesn't have an \"error\" according to ts 1.3\n var error = event.srcElement['error'];\n if (error && error.name === \"QuotaExceededError\") {\n _this.hasReachedQuota = true;\n }\n }\n catch (ex) { }\n callback(-1);\n };\n transaction.oncomplete = function (event) {\n callback(_this.manifestVersionFound);\n };\n var newVersion = { sceneUrl: url, data: this.manifestVersionFound };\n // Put the scene into the database\n var addRequest = transaction.objectStore(\"versions\").put(newVersion);\n addRequest.onsuccess = function (event) {\n };\n addRequest.onerror = function (event) {\n BABYLON.Tools.Error(\"Error in DB add version request in BABYLON.Database.\");\n };\n }\n catch (ex) {\n BABYLON.Tools.Error(\"Error while accessing 'versions' object store (WRITE OP). Exception: \" + ex.message);\n callback(-1);\n }\n }\n else {\n callback(-1);\n }\n };\n /**\n * Loads a file from database\n * @param url defines the URL to load from\n * @param sceneLoaded defines a callback to call on success\n * @param progressCallBack defines a callback to call when progress changed\n * @param errorCallback defines a callback to call on error\n * @param useArrayBuffer defines a boolean to use array buffer instead of text string\n */\n Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {\n var _this = this;\n var completeUrl = Database._ReturnFullUrlLocation(url);\n var saveAndLoadFile = function () {\n // the scene is not yet in the DB, let's try to save it\n _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);\n };\n this._checkVersionFromDB(completeUrl, function (version) {\n if (version !== -1) {\n if (!_this.mustUpdateRessources) {\n _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);\n }\n else {\n _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);\n }\n }\n else {\n if (errorCallback) {\n errorCallback();\n }\n }\n });\n };\n Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {\n if (this.isSupported && this.db) {\n var targetStore;\n if (url.indexOf(\".babylon\") !== -1) {\n targetStore = \"scenes\";\n }\n else {\n targetStore = \"textures\";\n }\n var file;\n var transaction = this.db.transaction([targetStore]);\n transaction.oncomplete = function (event) {\n if (file) {\n callback(file.data);\n }\n // file was not found in DB\n else {\n notInDBCallback();\n }\n };\n transaction.onabort = function (event) {\n notInDBCallback();\n };\n var getRequest = transaction.objectStore(targetStore).get(url);\n getRequest.onsuccess = function (event) {\n file = (event.target).result;\n };\n getRequest.onerror = function (event) {\n BABYLON.Tools.Error(\"Error loading file \" + url + \" from DB.\");\n notInDBCallback();\n };\n }\n else {\n BABYLON.Tools.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n callback();\n }\n };\n Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {\n var _this = this;\n if (this.isSupported) {\n var targetStore;\n if (url.indexOf(\".babylon\") !== -1) {\n targetStore = \"scenes\";\n }\n else {\n targetStore = \"textures\";\n }\n // Create XHR\n var xhr = new XMLHttpRequest();\n var fileData;\n xhr.open(\"GET\", url + \"?\" + Date.now(), true);\n if (useArrayBuffer) {\n xhr.responseType = \"arraybuffer\";\n }\n if (progressCallback) {\n xhr.onprogress = progressCallback;\n }\n xhr.addEventListener(\"load\", function () {\n if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {\n // Blob as response (XHR2)\n //fileData = xhr.responseText;\n fileData = !useArrayBuffer ? xhr.responseText : xhr.response;\n if (!_this.hasReachedQuota && _this.db) {\n // Open a transaction to the database\n var transaction = _this.db.transaction([targetStore], \"readwrite\");\n // the transaction could abort because of a QuotaExceededError error\n transaction.onabort = function (event) {\n try {\n //backwards compatibility with ts 1.0, srcElement doesn't have an \"error\" according to ts 1.3\n var error = event.srcElement['error'];\n if (error && error.name === \"QuotaExceededError\") {\n _this.hasReachedQuota = true;\n }\n }\n catch (ex) { }\n callback(fileData);\n };\n transaction.oncomplete = function (event) {\n callback(fileData);\n };\n var newFile;\n if (targetStore === \"scenes\") {\n newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };\n }\n else {\n newFile = { textureUrl: url, data: fileData };\n }\n try {\n // Put the scene into the database\n var addRequest = transaction.objectStore(targetStore).put(newFile);\n addRequest.onsuccess = function (event) {\n };\n addRequest.onerror = function (event) {\n BABYLON.Tools.Error(\"Error in DB add file request in BABYLON.Database.\");\n };\n }\n catch (ex) {\n callback(fileData);\n }\n }\n else {\n callback(fileData);\n }\n }\n else {\n if (xhr.status >= 400 && errorCallback) {\n errorCallback(xhr);\n }\n else {\n callback();\n }\n }\n }, false);\n xhr.addEventListener(\"error\", function (event) {\n BABYLON.Tools.Error(\"error on XHR request.\");\n callback();\n }, false);\n xhr.send();\n }\n else {\n BABYLON.Tools.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n callback();\n }\n };\n /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */\n Database.IsUASupportingBlobStorage = true;\n /** Gets a boolean indicating if Database storate is enabled */\n Database.IDBStorageEnabled = true;\n Database._ParseURL = function (url) {\n var a = document.createElement('a');\n a.href = url;\n var urlWithoutHash = url.substring(0, url.lastIndexOf(\"#\"));\n var fileName = url.substring(urlWithoutHash.lastIndexOf(\"/\") + 1, url.length);\n var absLocation = url.substring(0, url.indexOf(fileName, 0));\n return absLocation;\n };\n Database._ReturnFullUrlLocation = function (url) {\n if (url.indexOf(\"http:/\") === -1 && url.indexOf(\"https:/\") === -1) {\n return (Database._ParseURL(window.location.href) + url);\n }\n else {\n return url;\n }\n };\n return Database;\n }());\n BABYLON.Database = Database;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.database.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var FresnelParameters = /** @class */ (function () {\n function FresnelParameters() {\n this._isEnabled = true;\n this.leftColor = BABYLON.Color3.White();\n this.rightColor = BABYLON.Color3.Black();\n this.bias = 0;\n this.power = 1;\n }\n Object.defineProperty(FresnelParameters.prototype, \"isEnabled\", {\n get: function () {\n return this._isEnabled;\n },\n set: function (value) {\n if (this._isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n FresnelParameters.prototype.clone = function () {\n var newFresnelParameters = new FresnelParameters();\n BABYLON.Tools.DeepCopy(this, newFresnelParameters);\n return newFresnelParameters;\n };\n FresnelParameters.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.isEnabled = this.isEnabled;\n serializationObject.leftColor = this.leftColor.asArray();\n serializationObject.rightColor = this.rightColor.asArray();\n serializationObject.bias = this.bias;\n serializationObject.power = this.power;\n return serializationObject;\n };\n FresnelParameters.Parse = function (parsedFresnelParameters) {\n var fresnelParameters = new FresnelParameters();\n fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;\n fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);\n fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);\n fresnelParameters.bias = parsedFresnelParameters.bias;\n fresnelParameters.power = parsedFresnelParameters.power || 1.0;\n return fresnelParameters;\n };\n return FresnelParameters;\n }());\n BABYLON.FresnelParameters = FresnelParameters;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.fresnelParameters.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var MultiMaterial = /** @class */ (function (_super) {\n __extends(MultiMaterial, _super);\n function MultiMaterial(name, scene) {\n var _this = _super.call(this, name, scene, true) || this;\n scene.multiMaterials.push(_this);\n _this.subMaterials = new Array();\n _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material\n return _this;\n }\n Object.defineProperty(MultiMaterial.prototype, \"subMaterials\", {\n get: function () {\n return this._subMaterials;\n },\n set: function (value) {\n this._subMaterials = value;\n this._hookArray(value);\n },\n enumerable: true,\n configurable: true\n });\n MultiMaterial.prototype._hookArray = function (array) {\n var _this = this;\n var oldPush = array.push;\n array.push = function () {\n var items = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n items[_i] = arguments[_i];\n }\n var result = oldPush.apply(array, items);\n _this._markAllSubMeshesAsTexturesDirty();\n return result;\n };\n var oldSplice = array.splice;\n array.splice = function (index, deleteCount) {\n var deleted = oldSplice.apply(array, [index, deleteCount]);\n _this._markAllSubMeshesAsTexturesDirty();\n return deleted;\n };\n };\n // Properties\n MultiMaterial.prototype.getSubMaterial = function (index) {\n if (index < 0 || index >= this.subMaterials.length) {\n return this.getScene().defaultMaterial;\n }\n return this.subMaterials[index];\n };\n MultiMaterial.prototype.getActiveTextures = function () {\n return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {\n if (subMaterial) {\n return subMaterial.getActiveTextures();\n }\n else {\n return [];\n }\n }));\n var _a;\n };\n // Methods\n MultiMaterial.prototype.getClassName = function () {\n return \"MultiMaterial\";\n };\n MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {\n for (var index = 0; index < this.subMaterials.length; index++) {\n var subMaterial = this.subMaterials[index];\n if (subMaterial) {\n if (subMaterial.storeEffectOnSubMeshes) {\n if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {\n return false;\n }\n continue;\n }\n if (!subMaterial.isReady(mesh)) {\n return false;\n }\n }\n }\n return true;\n };\n MultiMaterial.prototype.clone = function (name, cloneChildren) {\n var newMultiMaterial = new MultiMaterial(name, this.getScene());\n for (var index = 0; index < this.subMaterials.length; index++) {\n var subMaterial = null;\n var current = this.subMaterials[index];\n if (cloneChildren && current) {\n subMaterial = current.clone(name + \"-\" + current.name);\n }\n else {\n subMaterial = this.subMaterials[index];\n }\n newMultiMaterial.subMaterials.push(subMaterial);\n }\n return newMultiMaterial;\n };\n MultiMaterial.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.id = this.id;\n if (BABYLON.Tags) {\n serializationObject.tags = BABYLON.Tags.GetTags(this);\n }\n serializationObject.materials = [];\n for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {\n var subMat = this.subMaterials[matIndex];\n if (subMat) {\n serializationObject.materials.push(subMat.id);\n }\n else {\n serializationObject.materials.push(null);\n }\n }\n return serializationObject;\n };\n MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var index = scene.multiMaterials.indexOf(this);\n if (index >= 0) {\n scene.multiMaterials.splice(index, 1);\n }\n _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);\n };\n return MultiMaterial;\n }(BABYLON.Material));\n BABYLON.MultiMaterial = MultiMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.multiMaterial.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FreeCameraTouchInput = /** @class */ (function () {\n function FreeCameraTouchInput() {\n this._offsetX = null;\n this._offsetY = null;\n this._pointerPressed = new Array();\n this.touchAngularSensibility = 200000.0;\n this.touchMoveSensibility = 250.0;\n }\n FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n var previousPosition = null;\n if (this._pointerInput === undefined) {\n this._onLostFocus = function (evt) {\n _this._offsetX = null;\n _this._offsetY = null;\n };\n this._pointerInput = function (p, s) {\n var evt = p.event;\n if (evt.pointerType === \"mouse\") {\n return;\n }\n if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n _this._pointerPressed.push(evt.pointerId);\n if (_this._pointerPressed.length !== 1) {\n return;\n }\n previousPosition = {\n x: evt.clientX,\n y: evt.clientY\n };\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n var index = _this._pointerPressed.indexOf(evt.pointerId);\n if (index === -1) {\n return;\n }\n _this._pointerPressed.splice(index, 1);\n if (index != 0) {\n return;\n }\n previousPosition = null;\n _this._offsetX = null;\n _this._offsetY = null;\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n if (!previousPosition) {\n return;\n }\n var index = _this._pointerPressed.indexOf(evt.pointerId);\n if (index != 0) {\n return;\n }\n _this._offsetX = evt.clientX - previousPosition.x;\n _this._offsetY = -(evt.clientY - previousPosition.y);\n }\n };\n }\n this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);\n if (this._onLostFocus) {\n element.addEventListener(\"blur\", this._onLostFocus);\n }\n };\n FreeCameraTouchInput.prototype.detachControl = function (element) {\n if (this._pointerInput && element) {\n if (this._observer) {\n this.camera.getScene().onPointerObservable.remove(this._observer);\n this._observer = null;\n }\n if (this._onLostFocus) {\n element.removeEventListener(\"blur\", this._onLostFocus);\n this._onLostFocus = null;\n }\n this._pointerPressed = [];\n this._offsetX = null;\n this._offsetY = null;\n }\n };\n FreeCameraTouchInput.prototype.checkInputs = function () {\n if (this._offsetX && this._offsetY) {\n var camera = this.camera;\n camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;\n if (this._pointerPressed.length > 1) {\n camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;\n }\n else {\n var speed = camera._computeLocalCameraSpeed();\n var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);\n BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);\n camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));\n }\n }\n };\n FreeCameraTouchInput.prototype.getClassName = function () {\n return \"FreeCameraTouchInput\";\n };\n FreeCameraTouchInput.prototype.getSimpleName = function () {\n return \"touch\";\n };\n __decorate([\n BABYLON.serialize()\n ], FreeCameraTouchInput.prototype, \"touchAngularSensibility\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCameraTouchInput.prototype, \"touchMoveSensibility\", void 0);\n return FreeCameraTouchInput;\n }());\n BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;\n BABYLON.CameraInputTypes[\"FreeCameraTouchInput\"] = FreeCameraTouchInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraTouchInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"TouchCamera\", function (name, scene) {\n return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n // We're mainly based on the logic defined into the FreeCamera code\n var TouchCamera = /** @class */ (function (_super) {\n __extends(TouchCamera, _super);\n //-- end properties for backward compatibility for inputs\n function TouchCamera(name, position, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.inputs.addTouch();\n _this._setupInputs();\n return _this;\n }\n Object.defineProperty(TouchCamera.prototype, \"touchAngularSensibility\", {\n //-- Begin properties for backward compatibility for inputs\n get: function () {\n var touch = this.inputs.attached[\"touch\"];\n if (touch)\n return touch.touchAngularSensibility;\n return 0;\n },\n set: function (value) {\n var touch = this.inputs.attached[\"touch\"];\n if (touch)\n touch.touchAngularSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TouchCamera.prototype, \"touchMoveSensibility\", {\n get: function () {\n var touch = this.inputs.attached[\"touch\"];\n if (touch)\n return touch.touchMoveSensibility;\n return 0;\n },\n set: function (value) {\n var touch = this.inputs.attached[\"touch\"];\n if (touch)\n touch.touchMoveSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n TouchCamera.prototype.getClassName = function () {\n return \"TouchCamera\";\n };\n TouchCamera.prototype._setupInputs = function () {\n var mouse = this.inputs.attached[\"mouse\"];\n if (mouse) {\n mouse.touchEnabled = false;\n }\n };\n return TouchCamera;\n }(BABYLON.FreeCamera));\n BABYLON.TouchCamera = TouchCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.touchCamera.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ProceduralTexture = /** @class */ (function (_super) {\n __extends(ProceduralTexture, _super);\n function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {\n if (fallbackTexture === void 0) { fallbackTexture = null; }\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (isCube === void 0) { isCube = false; }\n var _this = _super.call(this, null, scene, !generateMipMaps) || this;\n _this.isCube = isCube;\n _this.isEnabled = true;\n _this._currentRefreshId = -1;\n _this._refreshRate = 1;\n _this._vertexBuffers = {};\n _this._uniforms = new Array();\n _this._samplers = new Array();\n _this._textures = {};\n _this._floats = {};\n _this._ints = {};\n _this._floatsArrays = {};\n _this._colors3 = {};\n _this._colors4 = {};\n _this._vectors2 = {};\n _this._vectors3 = {};\n _this._matrices = {};\n _this._fallbackTextureUsed = false;\n scene = _this.getScene();\n scene.proceduralTextures.push(_this);\n _this._engine = scene.getEngine();\n _this.name = name;\n _this.isRenderTarget = true;\n _this._size = size;\n _this._generateMipMaps = generateMipMaps;\n _this.setFragment(fragment);\n _this._fallbackTexture = fallbackTexture;\n if (isCube) {\n _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });\n _this.setFloat(\"face\", 0);\n }\n else {\n _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);\n }\n // VBO\n var vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);\n _this._createIndexBuffer();\n return _this;\n }\n ProceduralTexture.prototype._createIndexBuffer = function () {\n var engine = this._engine;\n // Indices\n var indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = engine.createIndexBuffer(indices);\n };\n ProceduralTexture.prototype._rebuild = function () {\n var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._createIndexBuffer();\n if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {\n this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;\n }\n };\n ProceduralTexture.prototype.reset = function () {\n if (this._effect === undefined) {\n return;\n }\n var engine = this._engine;\n engine._releaseEffect(this._effect);\n };\n ProceduralTexture.prototype.isReady = function () {\n var _this = this;\n var engine = this._engine;\n var shaders;\n if (!this._fragment) {\n return false;\n }\n if (this._fallbackTextureUsed) {\n return true;\n }\n if (this._fragment.fragmentElement !== undefined) {\n shaders = { vertex: \"procedural\", fragmentElement: this._fragment.fragmentElement };\n }\n else {\n shaders = { vertex: \"procedural\", fragment: this._fragment };\n }\n this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, \"\", undefined, undefined, function () {\n _this.releaseInternalTexture();\n if (_this._fallbackTexture) {\n _this._texture = _this._fallbackTexture._texture;\n if (_this._texture) {\n _this._texture.incrementReferences();\n }\n }\n _this._fallbackTextureUsed = true;\n });\n return this._effect.isReady();\n };\n ProceduralTexture.prototype.resetRefreshCounter = function () {\n this._currentRefreshId = -1;\n };\n ProceduralTexture.prototype.setFragment = function (fragment) {\n this._fragment = fragment;\n };\n Object.defineProperty(ProceduralTexture.prototype, \"refreshRate\", {\n get: function () {\n return this._refreshRate;\n },\n // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...\n set: function (value) {\n this._refreshRate = value;\n this.resetRefreshCounter();\n },\n enumerable: true,\n configurable: true\n });\n ProceduralTexture.prototype._shouldRender = function () {\n if (!this.isEnabled || !this.isReady() || !this._texture) {\n return false;\n }\n if (this._fallbackTextureUsed) {\n return false;\n }\n if (this._currentRefreshId === -1) { // At least render once\n this._currentRefreshId = 1;\n return true;\n }\n if (this.refreshRate === this._currentRefreshId) {\n this._currentRefreshId = 1;\n return true;\n }\n this._currentRefreshId++;\n return false;\n };\n ProceduralTexture.prototype.getRenderSize = function () {\n return this._size;\n };\n ProceduralTexture.prototype.resize = function (size, generateMipMaps) {\n if (this._fallbackTextureUsed) {\n return;\n }\n this.releaseInternalTexture();\n this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);\n // Update properties\n this._size = size;\n this._generateMipMaps = generateMipMaps;\n };\n ProceduralTexture.prototype._checkUniform = function (uniformName) {\n if (this._uniforms.indexOf(uniformName) === -1) {\n this._uniforms.push(uniformName);\n }\n };\n ProceduralTexture.prototype.setTexture = function (name, texture) {\n if (this._samplers.indexOf(name) === -1) {\n this._samplers.push(name);\n }\n this._textures[name] = texture;\n return this;\n };\n ProceduralTexture.prototype.setFloat = function (name, value) {\n this._checkUniform(name);\n this._floats[name] = value;\n return this;\n };\n /**\n * Set the value of an uniform to an integer value\n * @param name defines the name of the uniform\n * @param value defines the value to set\n * @returns the current procedural texture\n */\n ProceduralTexture.prototype.setInt = function (name, value) {\n this._checkUniform(name);\n this._ints[name] = value;\n return this;\n };\n ProceduralTexture.prototype.setFloats = function (name, value) {\n this._checkUniform(name);\n this._floatsArrays[name] = value;\n return this;\n };\n ProceduralTexture.prototype.setColor3 = function (name, value) {\n this._checkUniform(name);\n this._colors3[name] = value;\n return this;\n };\n ProceduralTexture.prototype.setColor4 = function (name, value) {\n this._checkUniform(name);\n this._colors4[name] = value;\n return this;\n };\n ProceduralTexture.prototype.setVector2 = function (name, value) {\n this._checkUniform(name);\n this._vectors2[name] = value;\n return this;\n };\n ProceduralTexture.prototype.setVector3 = function (name, value) {\n this._checkUniform(name);\n this._vectors3[name] = value;\n return this;\n };\n ProceduralTexture.prototype.setMatrix = function (name, value) {\n this._checkUniform(name);\n this._matrices[name] = value;\n return this;\n };\n ProceduralTexture.prototype.render = function (useCameraPostProcess) {\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var engine = this._engine;\n // Render\n engine.enableEffect(this._effect);\n engine.setState(false);\n // Texture\n for (var name in this._textures) {\n this._effect.setTexture(name, this._textures[name]);\n }\n // Float \n for (name in this._ints) {\n this._effect.setInt(name, this._ints[name]);\n }\n // Float \n for (name in this._floats) {\n this._effect.setFloat(name, this._floats[name]);\n }\n // Floats \n for (name in this._floatsArrays) {\n this._effect.setArray(name, this._floatsArrays[name]);\n }\n // Color3 \n for (name in this._colors3) {\n this._effect.setColor3(name, this._colors3[name]);\n }\n // Color4 \n for (name in this._colors4) {\n var color = this._colors4[name];\n this._effect.setFloat4(name, color.r, color.g, color.b, color.a);\n }\n // Vector2 \n for (name in this._vectors2) {\n this._effect.setVector2(name, this._vectors2[name]);\n }\n // Vector3 \n for (name in this._vectors3) {\n this._effect.setVector3(name, this._vectors3[name]);\n }\n // Matrix \n for (name in this._matrices) {\n this._effect.setMatrix(name, this._matrices[name]);\n }\n if (!this._texture) {\n return;\n }\n if (this.isCube) {\n for (var face = 0; face < 6; face++) {\n engine.bindFramebuffer(this._texture, face, undefined, undefined, true);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);\n this._effect.setFloat(\"face\", face);\n // Clear\n engine.clear(scene.clearColor, true, true, true);\n // Draw order\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n // Mipmaps\n if (face === 5) {\n engine.generateMipMapsForCubemap(this._texture);\n }\n }\n }\n else {\n engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);\n // Clear\n engine.clear(scene.clearColor, true, true, true);\n // Draw order\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n }\n // Unbind\n engine.unBindFramebuffer(this._texture, this.isCube);\n if (this.onGenerated) {\n this.onGenerated();\n }\n };\n ProceduralTexture.prototype.clone = function () {\n var textureSize = this.getSize();\n var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // RenderTarget Texture\n newTexture.coordinatesMode = this.coordinatesMode;\n return newTexture;\n };\n ProceduralTexture.prototype.dispose = function () {\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var index = scene.proceduralTextures.indexOf(this);\n if (index >= 0) {\n scene.proceduralTextures.splice(index, 1);\n }\n var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {\n this._indexBuffer = null;\n }\n _super.prototype.dispose.call(this);\n };\n __decorate([\n BABYLON.serialize()\n ], ProceduralTexture.prototype, \"_size\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ProceduralTexture.prototype, \"_generateMipMaps\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ProceduralTexture.prototype, \"isEnabled\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ProceduralTexture.prototype, \"refreshRate\", null);\n return ProceduralTexture;\n }(BABYLON.Texture));\n BABYLON.ProceduralTexture = ProceduralTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.proceduralTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var CustomProceduralTexture = /** @class */ (function (_super) {\n __extends(CustomProceduralTexture, _super);\n function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {\n var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;\n _this._animate = true;\n _this._time = 0;\n _this._texturePath = texturePath;\n //Try to load json\n _this.loadJson(texturePath);\n _this.refreshRate = 1;\n return _this;\n }\n CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {\n var _this = this;\n var noConfigFile = function () {\n BABYLON.Tools.Log(\"No config file found in \" + jsonUrl + \" trying to use ShadersStore or DOM element\");\n try {\n _this.setFragment(_this._texturePath);\n }\n catch (ex) {\n BABYLON.Tools.Error(\"No json or ShaderStore or DOM element found for CustomProceduralTexture\");\n }\n };\n var configFileUrl = jsonUrl + \"/config.json\";\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", configFileUrl, true);\n xhr.addEventListener(\"load\", function () {\n if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {\n try {\n _this._config = JSON.parse(xhr.response);\n _this.updateShaderUniforms();\n _this.updateTextures();\n _this.setFragment(_this._texturePath + \"/custom\");\n _this._animate = _this._config.animate;\n _this.refreshRate = _this._config.refreshrate;\n }\n catch (ex) {\n noConfigFile();\n }\n }\n else {\n noConfigFile();\n }\n }, false);\n xhr.addEventListener(\"error\", function () {\n noConfigFile();\n }, false);\n try {\n xhr.send();\n }\n catch (ex) {\n BABYLON.Tools.Error(\"CustomProceduralTexture: Error on XHR send request.\");\n }\n };\n CustomProceduralTexture.prototype.isReady = function () {\n if (!_super.prototype.isReady.call(this)) {\n return false;\n }\n for (var name in this._textures) {\n var texture = this._textures[name];\n if (!texture.isReady()) {\n return false;\n }\n }\n return true;\n };\n CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {\n var scene = this.getScene();\n if (this._animate && scene) {\n this._time += scene.getAnimationRatio() * 0.03;\n this.updateShaderUniforms();\n }\n _super.prototype.render.call(this, useCameraPostProcess);\n };\n CustomProceduralTexture.prototype.updateTextures = function () {\n for (var i = 0; i < this._config.sampler2Ds.length; i++) {\n this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + \"/\" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));\n }\n };\n CustomProceduralTexture.prototype.updateShaderUniforms = function () {\n if (this._config) {\n for (var j = 0; j < this._config.uniforms.length; j++) {\n var uniform = this._config.uniforms[j];\n switch (uniform.type) {\n case \"float\":\n this.setFloat(uniform.name, uniform.value);\n break;\n case \"color3\":\n this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));\n break;\n case \"color4\":\n this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));\n break;\n case \"vector2\":\n this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));\n break;\n case \"vector3\":\n this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));\n break;\n }\n }\n }\n this.setFloat(\"time\", this._time);\n };\n Object.defineProperty(CustomProceduralTexture.prototype, \"animate\", {\n get: function () {\n return this._animate;\n },\n set: function (value) {\n this._animate = value;\n },\n enumerable: true,\n configurable: true\n });\n return CustomProceduralTexture;\n }(BABYLON.ProceduralTexture));\n BABYLON.CustomProceduralTexture = CustomProceduralTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.customProceduralTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FreeCameraGamepadInput = /** @class */ (function () {\n function FreeCameraGamepadInput() {\n this.gamepadAngularSensibility = 200;\n this.gamepadMoveSensibility = 40;\n // private members\n this._cameraTransform = BABYLON.Matrix.Identity();\n this._deltaTransform = BABYLON.Vector3.Zero();\n this._vector3 = BABYLON.Vector3.Zero();\n this._vector2 = BABYLON.Vector2.Zero();\n }\n FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n var manager = this.camera.getScene().gamepadManager;\n this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {\n if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {\n // prioritize XBOX gamepads.\n if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {\n _this.gamepad = gamepad;\n }\n }\n });\n this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {\n if (_this.gamepad === gamepad) {\n _this.gamepad = null;\n }\n });\n this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);\n };\n FreeCameraGamepadInput.prototype.detachControl = function (element) {\n this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);\n this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);\n this.gamepad = null;\n };\n FreeCameraGamepadInput.prototype.checkInputs = function () {\n if (this.gamepad && this.gamepad.leftStick) {\n var camera = this.camera;\n var LSValues = this.gamepad.leftStick;\n var normalizedLX = LSValues.x / this.gamepadMoveSensibility;\n var normalizedLY = LSValues.y / this.gamepadMoveSensibility;\n LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;\n LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;\n var RSValues = this.gamepad.rightStick;\n if (RSValues) {\n var normalizedRX = RSValues.x / this.gamepadAngularSensibility;\n var normalizedRY = RSValues.y / this.gamepadAngularSensibility;\n RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;\n RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;\n }\n else {\n RSValues = { x: 0, y: 0 };\n }\n if (!camera.rotationQuaternion) {\n BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);\n }\n else {\n camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);\n }\n var speed = camera._computeLocalCameraSpeed() * 50.0;\n this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);\n BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);\n camera.cameraDirection.addInPlace(this._deltaTransform);\n this._vector2.copyFromFloats(RSValues.y, RSValues.x);\n camera.cameraRotation.addInPlace(this._vector2);\n }\n };\n FreeCameraGamepadInput.prototype.getClassName = function () {\n return \"FreeCameraGamepadInput\";\n };\n FreeCameraGamepadInput.prototype.getSimpleName = function () {\n return \"gamepad\";\n };\n __decorate([\n BABYLON.serialize()\n ], FreeCameraGamepadInput.prototype, \"gamepadAngularSensibility\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCameraGamepadInput.prototype, \"gamepadMoveSensibility\", void 0);\n return FreeCameraGamepadInput;\n }());\n BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;\n BABYLON.CameraInputTypes[\"FreeCameraGamepadInput\"] = FreeCameraGamepadInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraGamepadInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ArcRotateCameraGamepadInput = /** @class */ (function () {\n function ArcRotateCameraGamepadInput() {\n this.gamepadRotationSensibility = 80;\n this.gamepadMoveSensibility = 40;\n }\n ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n var manager = this.camera.getScene().gamepadManager;\n this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {\n if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {\n // prioritize XBOX gamepads.\n if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {\n _this.gamepad = gamepad;\n }\n }\n });\n this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {\n if (_this.gamepad === gamepad) {\n _this.gamepad = null;\n }\n });\n this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);\n };\n ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {\n this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);\n this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);\n this.gamepad = null;\n };\n ArcRotateCameraGamepadInput.prototype.checkInputs = function () {\n if (this.gamepad) {\n var camera = this.camera;\n var RSValues = this.gamepad.rightStick;\n if (RSValues) {\n if (RSValues.x != 0) {\n var normalizedRX = RSValues.x / this.gamepadRotationSensibility;\n if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {\n camera.inertialAlphaOffset += normalizedRX;\n }\n }\n if (RSValues.y != 0) {\n var normalizedRY = RSValues.y / this.gamepadRotationSensibility;\n if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {\n camera.inertialBetaOffset += normalizedRY;\n }\n }\n }\n var LSValues = this.gamepad.leftStick;\n if (LSValues && LSValues.y != 0) {\n var normalizedLY = LSValues.y / this.gamepadMoveSensibility;\n if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {\n this.camera.inertialRadiusOffset -= normalizedLY;\n }\n }\n }\n };\n ArcRotateCameraGamepadInput.prototype.getClassName = function () {\n return \"ArcRotateCameraGamepadInput\";\n };\n ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {\n return \"gamepad\";\n };\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraGamepadInput.prototype, \"gamepadRotationSensibility\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraGamepadInput.prototype, \"gamepadMoveSensibility\", void 0);\n return ArcRotateCameraGamepadInput;\n }());\n BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;\n BABYLON.CameraInputTypes[\"ArcRotateCameraGamepadInput\"] = ArcRotateCameraGamepadInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var GamepadManager = /** @class */ (function () {\n function GamepadManager(_scene) {\n var _this = this;\n this._scene = _scene;\n this._babylonGamepads = [];\n this._oneGamepadConnected = false;\n this._isMonitoring = false;\n this.onGamepadDisconnectedObservable = new BABYLON.Observable();\n if (!BABYLON.Tools.IsWindowObjectExist()) {\n this._gamepadEventSupported = false;\n }\n else {\n this._gamepadEventSupported = 'GamepadEvent' in window;\n this._gamepadSupport = (navigator.getGamepads ||\n navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);\n }\n this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {\n // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected\n for (var i in _this._babylonGamepads) {\n var gamepad = _this._babylonGamepads[i];\n if (gamepad && gamepad._isConnected) {\n _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);\n }\n }\n });\n this._onGamepadConnectedEvent = function (evt) {\n var gamepad = evt.gamepad;\n if (gamepad.index in _this._babylonGamepads) {\n if (_this._babylonGamepads[gamepad.index].isConnected) {\n return;\n }\n }\n var newGamepad;\n if (_this._babylonGamepads[gamepad.index]) {\n newGamepad = _this._babylonGamepads[gamepad.index];\n newGamepad.browserGamepad = gamepad;\n newGamepad._isConnected = true;\n }\n else {\n newGamepad = _this._addNewGamepad(gamepad);\n }\n _this.onGamepadConnectedObservable.notifyObservers(newGamepad);\n _this._startMonitoringGamepads();\n };\n this._onGamepadDisconnectedEvent = function (evt) {\n var gamepad = evt.gamepad;\n // Remove the gamepad from the list of gamepads to monitor.\n for (var i in _this._babylonGamepads) {\n if (_this._babylonGamepads[i].index === gamepad.index) {\n var disconnectedGamepad = _this._babylonGamepads[i];\n disconnectedGamepad._isConnected = false;\n _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);\n break;\n }\n }\n };\n if (this._gamepadSupport) {\n //first add already-connected gamepads\n this._updateGamepadObjects();\n if (this._babylonGamepads.length) {\n this._startMonitoringGamepads();\n }\n // Checking if the gamepad connected event is supported (like in Firefox)\n if (this._gamepadEventSupported) {\n window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);\n window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);\n }\n else {\n this._startMonitoringGamepads();\n }\n }\n }\n Object.defineProperty(GamepadManager.prototype, \"gamepads\", {\n get: function () {\n return this._babylonGamepads;\n },\n enumerable: true,\n configurable: true\n });\n GamepadManager.prototype.getGamepadByType = function (type) {\n if (type === void 0) { type = BABYLON.Gamepad.XBOX; }\n for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {\n var gamepad = _a[_i];\n if (gamepad && gamepad.type === type) {\n return gamepad;\n }\n }\n return null;\n };\n GamepadManager.prototype.dispose = function () {\n if (this._gamepadEventSupported) {\n if (this._onGamepadConnectedEvent) {\n window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);\n }\n if (this._onGamepadDisconnectedEvent) {\n window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);\n }\n this._onGamepadConnectedEvent = null;\n this._onGamepadDisconnectedEvent = null;\n }\n this._babylonGamepads.forEach(function (gamepad) {\n gamepad.dispose();\n });\n this.onGamepadConnectedObservable.clear();\n this.onGamepadDisconnectedObservable.clear();\n this._oneGamepadConnected = false;\n this._stopMonitoringGamepads();\n this._babylonGamepads = [];\n };\n GamepadManager.prototype._addNewGamepad = function (gamepad) {\n if (!this._oneGamepadConnected) {\n this._oneGamepadConnected = true;\n }\n var newGamepad;\n var xboxOne = (gamepad.id.search(\"Xbox One\") !== -1);\n if (xboxOne || gamepad.id.search(\"Xbox 360\") !== -1 || gamepad.id.search(\"xinput\") !== -1) {\n newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);\n }\n // if pose is supported, use the (WebVR) pose enabled controller\n else if (gamepad.pose) {\n newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);\n }\n else {\n newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);\n }\n this._babylonGamepads[newGamepad.index] = newGamepad;\n return newGamepad;\n };\n GamepadManager.prototype._startMonitoringGamepads = function () {\n if (!this._isMonitoring) {\n this._isMonitoring = true;\n //back-comp\n if (!this._scene) {\n this._checkGamepadsStatus();\n }\n }\n };\n GamepadManager.prototype._stopMonitoringGamepads = function () {\n this._isMonitoring = false;\n };\n GamepadManager.prototype._checkGamepadsStatus = function () {\n var _this = this;\n // Hack to be compatible Chrome\n this._updateGamepadObjects();\n for (var i in this._babylonGamepads) {\n var gamepad = this._babylonGamepads[i];\n if (!gamepad || !gamepad.isConnected) {\n continue;\n }\n gamepad.update();\n }\n if (this._isMonitoring && !this._scene) {\n BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });\n }\n };\n // This function is called only on Chrome, which does not properly support\n // connection/disconnection events and forces you to recopy again the gamepad object\n GamepadManager.prototype._updateGamepadObjects = function () {\n var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);\n for (var i = 0; i < gamepads.length; i++) {\n var gamepad = gamepads[i];\n if (gamepad) {\n if (!this._babylonGamepads[gamepad.index]) {\n var newGamepad = this._addNewGamepad(gamepad);\n this.onGamepadConnectedObservable.notifyObservers(newGamepad);\n }\n else {\n // Forced to copy again this object for Chrome for unknown reason\n this._babylonGamepads[i].browserGamepad = gamepad;\n if (!this._babylonGamepads[i].isConnected) {\n this._babylonGamepads[i]._isConnected = true;\n this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);\n }\n }\n }\n }\n };\n return GamepadManager;\n }());\n BABYLON.GamepadManager = GamepadManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gamepadManager.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var StickValues = /** @class */ (function () {\n function StickValues(x, y) {\n this.x = x;\n this.y = y;\n }\n return StickValues;\n }());\n BABYLON.StickValues = StickValues;\n var Gamepad = /** @class */ (function () {\n function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {\n if (leftStickX === void 0) { leftStickX = 0; }\n if (leftStickY === void 0) { leftStickY = 1; }\n if (rightStickX === void 0) { rightStickX = 2; }\n if (rightStickY === void 0) { rightStickY = 3; }\n this.id = id;\n this.index = index;\n this.browserGamepad = browserGamepad;\n this._isConnected = true;\n this._invertLeftStickY = false;\n this.type = Gamepad.GAMEPAD;\n this._leftStickAxisX = leftStickX;\n this._leftStickAxisY = leftStickY;\n this._rightStickAxisX = rightStickX;\n this._rightStickAxisY = rightStickY;\n if (this.browserGamepad.axes.length >= 2) {\n this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };\n }\n if (this.browserGamepad.axes.length >= 4) {\n this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };\n }\n }\n Object.defineProperty(Gamepad.prototype, \"isConnected\", {\n get: function () {\n return this._isConnected;\n },\n enumerable: true,\n configurable: true\n });\n Gamepad.prototype.onleftstickchanged = function (callback) {\n this._onleftstickchanged = callback;\n };\n Gamepad.prototype.onrightstickchanged = function (callback) {\n this._onrightstickchanged = callback;\n };\n Object.defineProperty(Gamepad.prototype, \"leftStick\", {\n get: function () {\n return this._leftStick;\n },\n set: function (newValues) {\n if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {\n this._onleftstickchanged(newValues);\n }\n this._leftStick = newValues;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Gamepad.prototype, \"rightStick\", {\n get: function () {\n return this._rightStick;\n },\n set: function (newValues) {\n if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {\n this._onrightstickchanged(newValues);\n }\n this._rightStick = newValues;\n },\n enumerable: true,\n configurable: true\n });\n Gamepad.prototype.update = function () {\n if (this._leftStick) {\n this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };\n if (this._invertLeftStickY) {\n this.leftStick.y *= -1;\n }\n }\n if (this._rightStick) {\n this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };\n }\n };\n Gamepad.prototype.dispose = function () {\n };\n Gamepad.GAMEPAD = 0;\n Gamepad.GENERIC = 1;\n Gamepad.XBOX = 2;\n Gamepad.POSE_ENABLED = 3;\n return Gamepad;\n }());\n BABYLON.Gamepad = Gamepad;\n var GenericPad = /** @class */ (function (_super) {\n __extends(GenericPad, _super);\n function GenericPad(id, index, browserGamepad) {\n var _this = _super.call(this, id, index, browserGamepad) || this;\n _this.onButtonDownObservable = new BABYLON.Observable();\n _this.onButtonUpObservable = new BABYLON.Observable();\n _this.type = Gamepad.GENERIC;\n _this._buttons = new Array(browserGamepad.buttons.length);\n return _this;\n }\n GenericPad.prototype.onbuttondown = function (callback) {\n this._onbuttondown = callback;\n };\n GenericPad.prototype.onbuttonup = function (callback) {\n this._onbuttonup = callback;\n };\n GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._onbuttondown) {\n this._onbuttondown(buttonIndex);\n }\n this.onButtonDownObservable.notifyObservers(buttonIndex);\n }\n if (newValue === 0) {\n if (this._onbuttonup) {\n this._onbuttonup(buttonIndex);\n }\n this.onButtonUpObservable.notifyObservers(buttonIndex);\n }\n }\n return newValue;\n };\n GenericPad.prototype.update = function () {\n _super.prototype.update.call(this);\n for (var index = 0; index < this._buttons.length; index++) {\n this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);\n }\n };\n GenericPad.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this.onButtonDownObservable.clear();\n this.onButtonUpObservable.clear();\n };\n return GenericPad;\n }(Gamepad));\n BABYLON.GenericPad = GenericPad;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gamepad.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines supported buttons for XBox360 compatible gamepads\n */\n var Xbox360Button;\n (function (Xbox360Button) {\n /** A */\n Xbox360Button[Xbox360Button[\"A\"] = 0] = \"A\";\n /** B */\n Xbox360Button[Xbox360Button[\"B\"] = 1] = \"B\";\n /** X */\n Xbox360Button[Xbox360Button[\"X\"] = 2] = \"X\";\n /** Y */\n Xbox360Button[Xbox360Button[\"Y\"] = 3] = \"Y\";\n /** Start */\n Xbox360Button[Xbox360Button[\"Start\"] = 4] = \"Start\";\n /** Back */\n Xbox360Button[Xbox360Button[\"Back\"] = 5] = \"Back\";\n /** Left button */\n Xbox360Button[Xbox360Button[\"LB\"] = 6] = \"LB\";\n /** Right button */\n Xbox360Button[Xbox360Button[\"RB\"] = 7] = \"RB\";\n /** Left stick */\n Xbox360Button[Xbox360Button[\"LeftStick\"] = 8] = \"LeftStick\";\n /** Right stick */\n Xbox360Button[Xbox360Button[\"RightStick\"] = 9] = \"RightStick\";\n })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));\n /** Defines values for XBox360 DPad */\n var Xbox360Dpad;\n (function (Xbox360Dpad) {\n /** Up */\n Xbox360Dpad[Xbox360Dpad[\"Up\"] = 0] = \"Up\";\n /** Down */\n Xbox360Dpad[Xbox360Dpad[\"Down\"] = 1] = \"Down\";\n /** Left */\n Xbox360Dpad[Xbox360Dpad[\"Left\"] = 2] = \"Left\";\n /** Right */\n Xbox360Dpad[Xbox360Dpad[\"Right\"] = 3] = \"Right\";\n })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));\n /**\n * Defines a XBox360 gamepad\n */\n var Xbox360Pad = /** @class */ (function (_super) {\n __extends(Xbox360Pad, _super);\n /**\n * Creates a new XBox360 gamepad object\n * @param id defines the id of this gamepad\n * @param index defines its index\n * @param gamepad defines the internal HTML gamepad object\n * @param xboxOne defines if it is a XBox One gamepad\n */\n function Xbox360Pad(id, index, gamepad, xboxOne) {\n if (xboxOne === void 0) { xboxOne = false; }\n var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;\n _this._leftTrigger = 0;\n _this._rightTrigger = 0;\n /** Observable raised when a button is pressed */\n _this.onButtonDownObservable = new BABYLON.Observable();\n /** Observable raised when a button is released */\n _this.onButtonUpObservable = new BABYLON.Observable();\n /** Observable raised when a pad is pressed */\n _this.onPadDownObservable = new BABYLON.Observable();\n /** Observable raised when a pad is released */\n _this.onPadUpObservable = new BABYLON.Observable();\n _this._buttonA = 0;\n _this._buttonB = 0;\n _this._buttonX = 0;\n _this._buttonY = 0;\n _this._buttonBack = 0;\n _this._buttonStart = 0;\n _this._buttonLB = 0;\n _this._buttonRB = 0;\n _this._buttonLeftStick = 0;\n _this._buttonRightStick = 0;\n _this._dPadUp = 0;\n _this._dPadDown = 0;\n _this._dPadLeft = 0;\n _this._dPadRight = 0;\n _this._isXboxOnePad = false;\n _this.type = BABYLON.Gamepad.XBOX;\n _this._isXboxOnePad = xboxOne;\n return _this;\n }\n /**\n * Defines the callback to call when left trigger is pressed\n * @param callback defines the callback to use\n */\n Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {\n this._onlefttriggerchanged = callback;\n };\n /**\n * Defines the callback to call when right trigger is pressed\n * @param callback defines the callback to use\n */\n Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {\n this._onrighttriggerchanged = callback;\n };\n Object.defineProperty(Xbox360Pad.prototype, \"leftTrigger\", {\n /**\n * Gets or sets left trigger value\n */\n get: function () {\n return this._leftTrigger;\n },\n set: function (newValue) {\n if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {\n this._onlefttriggerchanged(newValue);\n }\n this._leftTrigger = newValue;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"rightTrigger\", {\n /**\n * Gets or sets right trigger value\n */\n get: function () {\n return this._rightTrigger;\n },\n set: function (newValue) {\n if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {\n this._onrighttriggerchanged(newValue);\n }\n this._rightTrigger = newValue;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Defines the callback to call when a button is pressed\n * @param callback defines the callback to use\n */\n Xbox360Pad.prototype.onbuttondown = function (callback) {\n this._onbuttondown = callback;\n };\n /**\n * Defines the callback to call when a button is released\n * @param callback defines the callback to use\n */\n Xbox360Pad.prototype.onbuttonup = function (callback) {\n this._onbuttonup = callback;\n };\n /**\n * Defines the callback to call when a pad is pressed\n * @param callback defines the callback to use\n */\n Xbox360Pad.prototype.ondpaddown = function (callback) {\n this._ondpaddown = callback;\n };\n /**\n * Defines the callback to call when a pad is released\n * @param callback defines the callback to use\n */\n Xbox360Pad.prototype.ondpadup = function (callback) {\n this._ondpadup = callback;\n };\n Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._onbuttondown) {\n this._onbuttondown(buttonType);\n }\n this.onButtonDownObservable.notifyObservers(buttonType);\n }\n if (newValue === 0) {\n if (this._onbuttonup) {\n this._onbuttonup(buttonType);\n }\n this.onButtonUpObservable.notifyObservers(buttonType);\n }\n }\n return newValue;\n };\n Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._ondpaddown) {\n this._ondpaddown(buttonType);\n }\n this.onPadDownObservable.notifyObservers(buttonType);\n }\n if (newValue === 0) {\n if (this._ondpadup) {\n this._ondpadup(buttonType);\n }\n this.onPadUpObservable.notifyObservers(buttonType);\n }\n }\n return newValue;\n };\n Object.defineProperty(Xbox360Pad.prototype, \"buttonA\", {\n /** Gets or sets value of A button */\n get: function () {\n return this._buttonA;\n },\n set: function (value) {\n this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonB\", {\n /** Gets or sets value of B button */\n get: function () {\n return this._buttonB;\n },\n set: function (value) {\n this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonX\", {\n /** Gets or sets value of X button */\n get: function () {\n return this._buttonX;\n },\n set: function (value) {\n this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonY\", {\n /** Gets or sets value of Y button */\n get: function () {\n return this._buttonY;\n },\n set: function (value) {\n this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonStart\", {\n /** Gets or sets value of Start button */\n get: function () {\n return this._buttonStart;\n },\n set: function (value) {\n this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonBack\", {\n /** Gets or sets value of Back button */\n get: function () {\n return this._buttonBack;\n },\n set: function (value) {\n this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonLB\", {\n /** Gets or sets value of Left button */\n get: function () {\n return this._buttonLB;\n },\n set: function (value) {\n this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonRB\", {\n /** Gets or sets value of Right button */\n get: function () {\n return this._buttonRB;\n },\n set: function (value) {\n this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonLeftStick\", {\n /** Gets or sets value of left stick */\n get: function () {\n return this._buttonLeftStick;\n },\n set: function (value) {\n this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonRightStick\", {\n /** Gets or sets value of right stick */\n get: function () {\n return this._buttonRightStick;\n },\n set: function (value) {\n this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"dPadUp\", {\n /** Gets or sets value of DPad up */\n get: function () {\n return this._dPadUp;\n },\n set: function (value) {\n this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"dPadDown\", {\n /** Gets or sets value of DPad down */\n get: function () {\n return this._dPadDown;\n },\n set: function (value) {\n this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"dPadLeft\", {\n /** Gets or sets value of DPad left */\n get: function () {\n return this._dPadLeft;\n },\n set: function (value) {\n this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"dPadRight\", {\n /** Gets or sets value of DPad right */\n get: function () {\n return this._dPadRight;\n },\n set: function (value) {\n this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Force the gamepad to synchronize with device values\n */\n Xbox360Pad.prototype.update = function () {\n _super.prototype.update.call(this);\n if (this._isXboxOnePad) {\n this.buttonA = this.browserGamepad.buttons[0].value;\n this.buttonB = this.browserGamepad.buttons[1].value;\n this.buttonX = this.browserGamepad.buttons[2].value;\n this.buttonY = this.browserGamepad.buttons[3].value;\n this.buttonLB = this.browserGamepad.buttons[4].value;\n this.buttonRB = this.browserGamepad.buttons[5].value;\n this.leftTrigger = this.browserGamepad.axes[2];\n this.rightTrigger = this.browserGamepad.axes[5];\n this.buttonBack = this.browserGamepad.buttons[9].value;\n this.buttonStart = this.browserGamepad.buttons[8].value;\n this.buttonLeftStick = this.browserGamepad.buttons[6].value;\n this.buttonRightStick = this.browserGamepad.buttons[7].value;\n this.dPadUp = this.browserGamepad.buttons[11].value;\n this.dPadDown = this.browserGamepad.buttons[12].value;\n this.dPadLeft = this.browserGamepad.buttons[13].value;\n this.dPadRight = this.browserGamepad.buttons[14].value;\n }\n else {\n this.buttonA = this.browserGamepad.buttons[0].value;\n this.buttonB = this.browserGamepad.buttons[1].value;\n this.buttonX = this.browserGamepad.buttons[2].value;\n this.buttonY = this.browserGamepad.buttons[3].value;\n this.buttonLB = this.browserGamepad.buttons[4].value;\n this.buttonRB = this.browserGamepad.buttons[5].value;\n this.leftTrigger = this.browserGamepad.buttons[6].value;\n this.rightTrigger = this.browserGamepad.buttons[7].value;\n this.buttonBack = this.browserGamepad.buttons[8].value;\n this.buttonStart = this.browserGamepad.buttons[9].value;\n this.buttonLeftStick = this.browserGamepad.buttons[10].value;\n this.buttonRightStick = this.browserGamepad.buttons[11].value;\n this.dPadUp = this.browserGamepad.buttons[12].value;\n this.dPadDown = this.browserGamepad.buttons[13].value;\n this.dPadLeft = this.browserGamepad.buttons[14].value;\n this.dPadRight = this.browserGamepad.buttons[15].value;\n }\n };\n Xbox360Pad.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this.onButtonDownObservable.clear();\n this.onButtonUpObservable.clear();\n this.onPadDownObservable.clear();\n this.onPadUpObservable.clear();\n };\n return Xbox360Pad;\n }(BABYLON.Gamepad));\n BABYLON.Xbox360Pad = Xbox360Pad;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.xboxGamepad.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the types of pose enabled controllers that are supported\n */\n var PoseEnabledControllerType;\n (function (PoseEnabledControllerType) {\n /**\n * HTC Vive\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"VIVE\"] = 0] = \"VIVE\";\n /**\n * Oculus Rift\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"OCULUS\"] = 1] = \"OCULUS\";\n /**\n * Windows mixed reality\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"WINDOWS\"] = 2] = \"WINDOWS\";\n /**\n * Samsung gear VR\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"GEAR_VR\"] = 3] = \"GEAR_VR\";\n /**\n * Google Daydream\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"DAYDREAM\"] = 4] = \"DAYDREAM\";\n /**\n * Generic\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"GENERIC\"] = 5] = \"GENERIC\";\n })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));\n /**\n * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)\n */\n var PoseEnabledControllerHelper = /** @class */ (function () {\n function PoseEnabledControllerHelper() {\n }\n /**\n * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)\n * @param vrGamepad the gamepad to initialized\n * @returns a vr controller of the type the gamepad identified as\n */\n PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {\n // Oculus Touch\n if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {\n return new BABYLON.OculusTouchController(vrGamepad);\n }\n // Windows Mixed Reality controllers \n else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {\n return new BABYLON.WindowsMotionController(vrGamepad);\n }\n // HTC Vive\n else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {\n return new BABYLON.ViveController(vrGamepad);\n }\n // Samsung/Oculus Gear VR or Oculus Go\n else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {\n return new BABYLON.GearVRController(vrGamepad);\n }\n // Google Daydream\n else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {\n return new BABYLON.DaydreamController(vrGamepad);\n }\n // Generic \n else {\n return new BABYLON.GenericController(vrGamepad);\n }\n };\n return PoseEnabledControllerHelper;\n }());\n BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;\n /**\n * Defines the PoseEnabledController object that contains state of a vr capable controller\n */\n var PoseEnabledController = /** @class */ (function (_super) {\n __extends(PoseEnabledController, _super);\n /**\n * Creates a new PoseEnabledController from a gamepad\n * @param browserGamepad the gamepad that the PoseEnabledController should be created from\n */\n function PoseEnabledController(browserGamepad) {\n var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;\n // Represents device position and rotation in room space. Should only be used to help calculate babylon space values\n _this._deviceRoomPosition = BABYLON.Vector3.Zero();\n _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();\n /**\n * The device position in babylon space\n */\n _this.devicePosition = BABYLON.Vector3.Zero();\n /**\n * The device rotation in babylon space\n */\n _this.deviceRotationQuaternion = new BABYLON.Quaternion();\n /**\n * The scale factor of the device in babylon space\n */\n _this.deviceScaleFactor = 1;\n _this._leftHandSystemQuaternion = new BABYLON.Quaternion();\n /**\n * Internal, matrix used to convert room space to babylon space\n */\n _this._deviceToWorld = BABYLON.Matrix.Identity();\n /**\n * Node to be used when casting a ray from the controller\n */\n _this._pointingPoseNode = null;\n _this._workingMatrix = BABYLON.Matrix.Identity();\n /**\n * @hidden\n */\n _this._meshAttachedObservable = new BABYLON.Observable();\n _this.type = BABYLON.Gamepad.POSE_ENABLED;\n _this.controllerType = PoseEnabledControllerType.GENERIC;\n _this.position = BABYLON.Vector3.Zero();\n _this.rotationQuaternion = new BABYLON.Quaternion();\n _this._calculatedPosition = BABYLON.Vector3.Zero();\n _this._calculatedRotation = new BABYLON.Quaternion();\n BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);\n return _this;\n }\n /**\n * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller\n */\n PoseEnabledController.prototype.update = function () {\n _super.prototype.update.call(this);\n this._updatePoseAndMesh();\n };\n /**\n * Updates only the pose device and mesh without doing any button event checking\n */\n PoseEnabledController.prototype._updatePoseAndMesh = function () {\n var pose = this.browserGamepad.pose;\n this.updateFromDevice(pose);\n BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);\n this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);\n BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);\n this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);\n if (this._mesh) {\n this._mesh.position.copyFrom(this.devicePosition);\n if (this._mesh.rotationQuaternion) {\n this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);\n }\n }\n };\n /**\n * Updates the state of the pose enbaled controller based on the raw pose data from the device\n * @param poseData raw pose fromthe device\n */\n PoseEnabledController.prototype.updateFromDevice = function (poseData) {\n if (poseData) {\n this.rawPose = poseData;\n if (poseData.position) {\n this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);\n if (this._mesh && this._mesh.getScene().useRightHandedSystem) {\n this._deviceRoomPosition.z *= -1;\n }\n this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);\n this._calculatedPosition.addInPlace(this.position);\n }\n var pose = this.rawPose;\n if (poseData.orientation && pose.orientation) {\n this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);\n if (this._mesh) {\n if (this._mesh.getScene().useRightHandedSystem) {\n this._deviceRoomRotationQuaternion.z *= -1;\n this._deviceRoomRotationQuaternion.w *= -1;\n }\n else {\n this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);\n }\n }\n // if the camera is set, rotate to the camera's rotation\n this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);\n }\n }\n };\n /**\n * Attaches a mesh to the controller\n * @param mesh the mesh to be attached\n */\n PoseEnabledController.prototype.attachToMesh = function (mesh) {\n if (this._mesh) {\n this._mesh.parent = null;\n }\n this._mesh = mesh;\n if (this._poseControlledCamera) {\n this._mesh.parent = this._poseControlledCamera;\n }\n if (!this._mesh.rotationQuaternion) {\n this._mesh.rotationQuaternion = new BABYLON.Quaternion();\n }\n // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh\n this._updatePoseAndMesh();\n if (this._pointingPoseNode) {\n var parents = [];\n var obj = this._pointingPoseNode;\n while (obj.parent) {\n parents.push(obj.parent);\n obj = obj.parent;\n }\n parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });\n }\n this._meshAttachedObservable.notifyObservers(mesh);\n };\n /**\n * Attaches the controllers mesh to a camera\n * @param camera the camera the mesh should be attached to\n */\n PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {\n this._poseControlledCamera = camera;\n if (this._mesh) {\n this._mesh.parent = this._poseControlledCamera;\n }\n };\n /**\n * Disposes of the controller\n */\n PoseEnabledController.prototype.dispose = function () {\n if (this._mesh) {\n this._mesh.dispose();\n }\n this._mesh = null;\n _super.prototype.dispose.call(this);\n };\n Object.defineProperty(PoseEnabledController.prototype, \"mesh\", {\n /**\n * The mesh that is attached to the controller\n */\n get: function () {\n return this._mesh;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the ray of the controller in the direction the controller is pointing\n * @param length the length the resulting ray should be\n * @returns a ray in the direction the controller is pointing\n */\n PoseEnabledController.prototype.getForwardRay = function (length) {\n if (length === void 0) { length = 100; }\n if (!this.mesh) {\n return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);\n }\n var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();\n var origin = m.getTranslation();\n var forward = new BABYLON.Vector3(0, 0, -1);\n var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);\n var direction = BABYLON.Vector3.Normalize(forwardWorld);\n return new BABYLON.Ray(origin, direction, length);\n };\n /**\n * Name of the child mesh that can be used to cast a ray from the controller\n */\n PoseEnabledController.POINTING_POSE = \"POINTING_POSE\";\n return PoseEnabledController;\n }(BABYLON.Gamepad));\n BABYLON.PoseEnabledController = PoseEnabledController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.poseEnabledController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the WebVRController object that represents controllers tracked in 3D space\n */\n var WebVRController = /** @class */ (function (_super) {\n __extends(WebVRController, _super);\n /**\n * Creates a new WebVRController from a gamepad\n * @param vrGamepad the gamepad that the WebVRController should be created from\n */\n function WebVRController(vrGamepad) {\n var _this = _super.call(this, vrGamepad) || this;\n // Observables\n /**\n * Fired when the trigger state has changed\n */\n _this.onTriggerStateChangedObservable = new BABYLON.Observable();\n /**\n * Fired when the main button state has changed\n */\n _this.onMainButtonStateChangedObservable = new BABYLON.Observable();\n /**\n * Fired when the secondary button state has changed\n */\n _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();\n /**\n * Fired when the pad state has changed\n */\n _this.onPadStateChangedObservable = new BABYLON.Observable();\n /**\n * Fired when controllers stick values have changed\n */\n _this.onPadValuesChangedObservable = new BABYLON.Observable();\n /**\n * X and Y axis corrisponding to the controllers joystick\n */\n _this.pad = { x: 0, y: 0 };\n // avoid GC, store state in a tmp object\n _this._changes = {\n pressChanged: false,\n touchChanged: false,\n valueChanged: false,\n changed: false\n };\n _this._buttons = new Array(vrGamepad.buttons.length);\n _this.hand = vrGamepad.hand;\n return _this;\n }\n /**\n * Fired when a controller button's state has changed\n * @param callback the callback containing the button that was modified\n */\n WebVRController.prototype.onButtonStateChange = function (callback) {\n this._onButtonStateChange = callback;\n };\n Object.defineProperty(WebVRController.prototype, \"defaultModel\", {\n /**\n * The default controller model for the controller\n */\n get: function () {\n return this._defaultModel;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Updates the state of the controller and mesh based on the current position and rotation of the controller\n */\n WebVRController.prototype.update = function () {\n _super.prototype.update.call(this);\n for (var index = 0; index < this._buttons.length; index++) {\n this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);\n }\n ;\n if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {\n this.pad.x = this.leftStick.x;\n this.pad.y = this.leftStick.y;\n this.onPadValuesChangedObservable.notifyObservers(this.pad);\n }\n };\n WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {\n if (!newState) {\n newState = {\n pressed: false,\n touched: false,\n value: 0\n };\n }\n if (!currentState) {\n this._buttons[buttonIndex] = {\n pressed: newState.pressed,\n touched: newState.touched,\n value: newState.value\n };\n return;\n }\n this._checkChanges(newState, currentState);\n if (this._changes.changed) {\n this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);\n this._handleButtonChange(buttonIndex, newState, this._changes);\n }\n this._buttons[buttonIndex].pressed = newState.pressed;\n this._buttons[buttonIndex].touched = newState.touched;\n // oculus triggers are never 0, thou not touched.\n this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;\n };\n WebVRController.prototype._checkChanges = function (newState, currentState) {\n this._changes.pressChanged = newState.pressed !== currentState.pressed;\n this._changes.touchChanged = newState.touched !== currentState.touched;\n this._changes.valueChanged = newState.value !== currentState.value;\n this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;\n return this._changes;\n };\n /**\n * Disposes of th webVRCOntroller\n */\n WebVRController.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this.onTriggerStateChangedObservable.clear();\n this.onMainButtonStateChangedObservable.clear();\n this.onSecondaryButtonStateChangedObservable.clear();\n this.onPadStateChangedObservable.clear();\n this.onPadValuesChangedObservable.clear();\n };\n return WebVRController;\n }(BABYLON.PoseEnabledController));\n BABYLON.WebVRController = WebVRController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.webVRController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Oculus Touch Controller\n */\n var OculusTouchController = /** @class */ (function (_super) {\n __extends(OculusTouchController, _super);\n /**\n * Creates a new OculusTouchController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n function OculusTouchController(vrGamepad) {\n var _this = _super.call(this, vrGamepad) || this;\n /**\n * Fired when the secondary trigger on this controller is modified\n */\n _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();\n /**\n * Fired when the thumb rest on this controller is modified\n */\n _this.onThumbRestChangedObservable = new BABYLON.Observable();\n _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;\n return _this;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {\n var _this = this;\n var meshName;\n // Hand\n if (this.hand === 'left') {\n meshName = OculusTouchController.MODEL_LEFT_FILENAME;\n }\n else { // Right is the default if no hand is specified\n meshName = OculusTouchController.MODEL_RIGHT_FILENAME;\n }\n BABYLON.SceneLoader.ImportMesh(\"\", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {\n /*\n Parent Mesh name: oculus_touch_left\n - body\n - trigger\n - thumbstick\n - grip\n - button_y\n - button_x\n - button_enter\n */\n _this._defaultModel = newMeshes[1];\n _this.attachToMesh(_this._defaultModel);\n if (meshLoaded) {\n meshLoaded(_this._defaultModel);\n }\n });\n };\n Object.defineProperty(OculusTouchController.prototype, \"onAButtonStateChangedObservable\", {\n /**\n * Fired when the A button on this controller is modified\n */\n get: function () {\n if (this.hand === 'right') {\n return this.onMainButtonStateChangedObservable;\n }\n else {\n throw new Error('No A button on left hand');\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(OculusTouchController.prototype, \"onBButtonStateChangedObservable\", {\n /**\n * Fired when the B button on this controller is modified\n */\n get: function () {\n if (this.hand === 'right') {\n return this.onSecondaryButtonStateChangedObservable;\n }\n else {\n throw new Error('No B button on left hand');\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(OculusTouchController.prototype, \"onXButtonStateChangedObservable\", {\n /**\n * Fired when the X button on this controller is modified\n */\n get: function () {\n if (this.hand === 'left') {\n return this.onMainButtonStateChangedObservable;\n }\n else {\n throw new Error('No X button on right hand');\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(OculusTouchController.prototype, \"onYButtonStateChangedObservable\", {\n /**\n * Fired when the Y button on this controller is modified\n */\n get: function () {\n if (this.hand === 'left') {\n return this.onSecondaryButtonStateChangedObservable;\n }\n else {\n throw new Error('No Y button on right hand');\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Called once for each button that changed state since the last frame\n * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick\n * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)\n * 2) secondary trigger (same)\n * 3) A (right) X (left), touch, pressed = value\n * 4) B / Y\n * 5) thumb rest\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n * @param changes Which properties on the state changed since last frame\n */\n OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {\n var notifyObject = state; //{ state: state, changes: changes };\n var triggerDirection = this.hand === 'right' ? -1 : 1;\n switch (buttonIdx) {\n case 0:\n this.onPadStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 1: // index trigger\n if (this._defaultModel) {\n (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;\n (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;\n (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;\n }\n this.onTriggerStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 2: // secondary trigger\n if (this._defaultModel) {\n (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;\n }\n this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 3:\n if (this._defaultModel) {\n if (notifyObject.pressed) {\n (this._defaultModel.getChildren()[1]).position.y = -0.001;\n }\n else {\n (this._defaultModel.getChildren()[1]).position.y = 0;\n }\n }\n this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 4:\n if (this._defaultModel) {\n if (notifyObject.pressed) {\n (this._defaultModel.getChildren()[2]).position.y = -0.001;\n }\n else {\n (this._defaultModel.getChildren()[2]).position.y = 0;\n }\n }\n this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 5:\n this.onThumbRestChangedObservable.notifyObservers(notifyObject);\n return;\n }\n };\n /**\n * Base Url for the controller model.\n */\n OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';\n /**\n * File name for the left controller model.\n */\n OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';\n /**\n * File name for the right controller model.\n */\n OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';\n return OculusTouchController;\n }(BABYLON.WebVRController));\n BABYLON.OculusTouchController = OculusTouchController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.oculusTouchController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Vive Controller\n */\n var ViveController = /** @class */ (function (_super) {\n __extends(ViveController, _super);\n /**\n * Creates a new ViveController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n function ViveController(vrGamepad) {\n var _this = _super.call(this, vrGamepad) || this;\n _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;\n _this._invertLeftStickY = true;\n return _this;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {\n var _this = this;\n BABYLON.SceneLoader.ImportMesh(\"\", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {\n /*\n Parent Mesh name: ViveWand\n - body\n - r_gripper\n - l_gripper\n - menu_button\n - system_button\n - trackpad\n - trigger\n - LED\n */\n _this._defaultModel = newMeshes[1];\n _this.attachToMesh(_this._defaultModel);\n if (meshLoaded) {\n meshLoaded(_this._defaultModel);\n }\n });\n };\n Object.defineProperty(ViveController.prototype, \"onLeftButtonStateChangedObservable\", {\n /**\n * Fired when the left button on this controller is modified\n */\n get: function () {\n return this.onMainButtonStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ViveController.prototype, \"onRightButtonStateChangedObservable\", {\n /**\n * Fired when the right button on this controller is modified\n */\n get: function () {\n return this.onMainButtonStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ViveController.prototype, \"onMenuButtonStateChangedObservable\", {\n /**\n * Fired when the menu button on this controller is modified\n */\n get: function () {\n return this.onSecondaryButtonStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Called once for each button that changed state since the last frame\n * Vive mapping:\n * 0: touchpad\n * 1: trigger\n * 2: left AND right buttons\n * 3: menu button\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n * @param changes Which properties on the state changed since last frame\n */\n ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {\n var notifyObject = state; //{ state: state, changes: changes };\n switch (buttonIdx) {\n case 0:\n this.onPadStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 1: // index trigger\n if (this._defaultModel) {\n (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;\n }\n this.onTriggerStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 2: // left AND right button\n this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 3:\n if (this._defaultModel) {\n if (notifyObject.pressed) {\n (this._defaultModel.getChildren()[2]).position.y = -0.001;\n }\n else {\n (this._defaultModel.getChildren()[2]).position.y = 0;\n }\n }\n this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n }\n };\n /**\n * Base Url for the controller model.\n */\n ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';\n /**\n * File name for the controller model.\n */\n ViveController.MODEL_FILENAME = 'wand.babylon';\n return ViveController;\n }(BABYLON.WebVRController));\n BABYLON.ViveController = ViveController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.viveController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Generic Controller\n */\n var GenericController = /** @class */ (function (_super) {\n __extends(GenericController, _super);\n /**\n * Creates a new GenericController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n function GenericController(vrGamepad) {\n return _super.call(this, vrGamepad) || this;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {\n var _this = this;\n BABYLON.SceneLoader.ImportMesh(\"\", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {\n _this._defaultModel = newMeshes[1];\n _this.attachToMesh(_this._defaultModel);\n if (meshLoaded) {\n meshLoaded(_this._defaultModel);\n }\n });\n };\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n * @param changes Which properties on the state changed since last frame\n */\n GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {\n console.log(\"Button id: \" + buttonIdx + \"state: \");\n console.dir(state);\n };\n /**\n * Base Url for the controller model.\n */\n GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';\n /**\n * File name for the controller model.\n */\n GenericController.MODEL_FILENAME = 'generic.babylon';\n return GenericController;\n }(BABYLON.WebVRController));\n BABYLON.GenericController = GenericController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.genericController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh\n */\n var LoadedMeshInfo = /** @class */ (function () {\n function LoadedMeshInfo() {\n /**\n * Map of the button meshes contained in the controller\n */\n this.buttonMeshes = {};\n /**\n * Map of the axis meshes contained in the controller\n */\n this.axisMeshes = {};\n }\n return LoadedMeshInfo;\n }());\n /**\n * Defines the WindowsMotionController object that the state of the windows motion controller\n */\n var WindowsMotionController = /** @class */ (function (_super) {\n __extends(WindowsMotionController, _super);\n /**\n * Creates a new WindowsMotionController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n function WindowsMotionController(vrGamepad) {\n var _this = _super.call(this, vrGamepad) || this;\n _this._mapping = {\n // Semantic button names\n buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],\n // A mapping of the button name to glTF model node name\n // that should be transformed by button value.\n buttonMeshNames: {\n 'trigger': 'SELECT',\n 'menu': 'MENU',\n 'grip': 'GRASP',\n 'thumbstick': 'THUMBSTICK_PRESS',\n 'trackpad': 'TOUCHPAD_PRESS'\n },\n // This mapping is used to translate from the Motion Controller to Babylon semantics\n buttonObservableNames: {\n 'trigger': 'onTriggerStateChangedObservable',\n 'menu': 'onSecondaryButtonStateChangedObservable',\n 'grip': 'onMainButtonStateChangedObservable',\n 'thumbstick': 'onPadStateChangedObservable',\n 'trackpad': 'onTrackpadChangedObservable'\n },\n // A mapping of the axis name to glTF model node name\n // that should be transformed by axis value.\n // This array mirrors the browserGamepad.axes array, such that \n // the mesh corresponding to axis 0 is in this array index 0.\n axisMeshNames: [\n 'THUMBSTICK_X',\n 'THUMBSTICK_Y',\n 'TOUCHPAD_TOUCH_X',\n 'TOUCHPAD_TOUCH_Y'\n ],\n pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE\n };\n /**\n * Fired when the trackpad on this controller is clicked\n */\n _this.onTrackpadChangedObservable = new BABYLON.Observable();\n /**\n * Fired when the trackpad on this controller is modified\n */\n _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();\n /**\n * The current x and y values of this controller's trackpad\n */\n _this.trackpad = { x: 0, y: 0 };\n _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;\n _this._loadedMeshInfo = null;\n return _this;\n }\n Object.defineProperty(WindowsMotionController.prototype, \"onTriggerButtonStateChangedObservable\", {\n /**\n * Fired when the trigger on this controller is modified\n */\n get: function () {\n return this.onTriggerStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WindowsMotionController.prototype, \"onMenuButtonStateChangedObservable\", {\n /**\n * Fired when the menu button on this controller is modified\n */\n get: function () {\n return this.onSecondaryButtonStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WindowsMotionController.prototype, \"onGripButtonStateChangedObservable\", {\n /**\n * Fired when the grip button on this controller is modified\n */\n get: function () {\n return this.onMainButtonStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WindowsMotionController.prototype, \"onThumbstickButtonStateChangedObservable\", {\n /**\n * Fired when the thumbstick button on this controller is modified\n */\n get: function () {\n return this.onPadStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WindowsMotionController.prototype, \"onTouchpadButtonStateChangedObservable\", {\n /**\n * Fired when the touchpad button on this controller is modified\n */\n get: function () {\n return this.onTrackpadChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WindowsMotionController.prototype, \"onTouchpadValuesChangedObservable\", {\n /**\n * Fired when the touchpad values on this controller are modified\n */\n get: function () {\n return this.onTrackpadValuesChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n WindowsMotionController.prototype._updateTrackpad = function () {\n if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {\n this.trackpad.x = this.browserGamepad[\"axes\"][2];\n this.trackpad.y = this.browserGamepad[\"axes\"][3];\n this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);\n }\n };\n /**\n * Called once per frame by the engine.\n */\n WindowsMotionController.prototype.update = function () {\n _super.prototype.update.call(this);\n if (this.browserGamepad.axes) {\n this._updateTrackpad();\n // Only need to animate axes if there is a loaded mesh\n if (this._loadedMeshInfo) {\n for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {\n this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);\n }\n }\n }\n };\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n * @param changes Which properties on the state changed since last frame\n */\n WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {\n var buttonName = this._mapping.buttons[buttonIdx];\n if (!buttonName) {\n return;\n }\n // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames\n this._updateTrackpad();\n // Only emit events for buttons that we know how to map from index to name\n var observable = this[(this._mapping.buttonObservableNames)[buttonName]];\n if (observable) {\n observable.notifyObservers(state);\n }\n this._lerpButtonTransform(buttonName, state.value);\n };\n /**\n * Moves the buttons on the controller mesh based on their current state\n * @param buttonName the name of the button to move\n * @param buttonValue the value of the button which determines the buttons new position\n */\n WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {\n // If there is no loaded mesh, there is nothing to transform.\n if (!this._loadedMeshInfo) {\n return;\n }\n var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];\n if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {\n return;\n }\n BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);\n BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);\n };\n /**\n * Moves the axis on the controller mesh based on its current state\n * @param axis the index of the axis\n * @param axisValue the value of the axis which determines the meshes new position\n * @hidden\n */\n WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {\n if (!this._loadedMeshInfo) {\n return;\n }\n var meshInfo = this._loadedMeshInfo.axisMeshes[axis];\n if (!meshInfo) {\n return;\n }\n if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {\n return;\n }\n // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)\n var lerpValue = axisValue * 0.5 + 0.5;\n BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);\n BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);\n };\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {\n var _this = this;\n if (forceDefault === void 0) { forceDefault = false; }\n var path;\n var filename;\n // Checking if GLB loader is present\n if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(\".glb\")) {\n // Determine the device specific folder based on the ID suffix\n var device = 'default';\n if (this.id && !forceDefault) {\n var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);\n device = ((match && match[0]) || device);\n }\n // Hand\n if (this.hand === 'left') {\n filename = WindowsMotionController.MODEL_LEFT_FILENAME;\n }\n else { // Right is the default if no hand is specified\n filename = WindowsMotionController.MODEL_RIGHT_FILENAME;\n }\n path = WindowsMotionController.MODEL_BASE_URL + device + '/';\n }\n else {\n BABYLON.Tools.Warn(\"You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models\");\n path = BABYLON.GenericController.MODEL_BASE_URL;\n filename = BABYLON.GenericController.MODEL_FILENAME;\n }\n BABYLON.SceneLoader.ImportMesh(\"\", path, filename, scene, function (meshes) {\n // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.\n _this._loadedMeshInfo = _this.processModel(scene, meshes);\n if (!_this._loadedMeshInfo) {\n return;\n }\n _this._defaultModel = _this._loadedMeshInfo.rootNode;\n _this.attachToMesh(_this._defaultModel);\n if (meshLoaded) {\n meshLoaded(_this._defaultModel);\n }\n }, null, function (scene, message) {\n BABYLON.Tools.Log(message);\n BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);\n if (!forceDefault) {\n _this.initControllerMesh(scene, meshLoaded, true);\n }\n });\n };\n /**\n * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that\n * can be transformed by button presses and axes values, based on this._mapping.\n *\n * @param scene scene in which the meshes exist\n * @param meshes list of meshes that make up the controller model to process\n * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.\n */\n WindowsMotionController.prototype.processModel = function (scene, meshes) {\n var loadedMeshInfo = null;\n // Create a new mesh to contain the glTF hierarchy\n var parentMesh = new BABYLON.Mesh(this.id + \" \" + this.hand, scene);\n // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'\n var childMesh = null;\n for (var i = 0; i < meshes.length; i++) {\n var mesh = meshes[i];\n if (!mesh.parent) {\n // Exclude controller meshes from picking results\n mesh.isPickable = false;\n // Handle root node, attach to the new parentMesh\n childMesh = mesh;\n break;\n }\n }\n if (childMesh) {\n childMesh.setParent(parentMesh);\n // Create our mesh info. Note that this method will always return non-null.\n loadedMeshInfo = this.createMeshInfo(parentMesh);\n }\n else {\n BABYLON.Tools.Warn('Could not find root node in model file.');\n }\n return loadedMeshInfo;\n };\n WindowsMotionController.prototype.createMeshInfo = function (rootNode) {\n var loadedMeshInfo = new LoadedMeshInfo();\n var i;\n loadedMeshInfo.rootNode = rootNode;\n // Reset the caches\n loadedMeshInfo.buttonMeshes = {};\n loadedMeshInfo.axisMeshes = {};\n // Button Meshes\n for (i = 0; i < this._mapping.buttons.length; i++) {\n var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];\n if (!buttonMeshName) {\n BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);\n continue;\n }\n var buttonMesh = getChildByName(rootNode, buttonMeshName);\n if (!buttonMesh) {\n BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);\n continue;\n }\n var buttonMeshInfo = {\n index: i,\n value: getImmediateChildByName(buttonMesh, 'VALUE'),\n pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),\n unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')\n };\n if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {\n loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;\n }\n else {\n // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.\n BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +\n '(VALUE: ' + !!buttonMeshInfo.value +\n ', PRESSED: ' + !!buttonMeshInfo.pressed +\n ', UNPRESSED:' + !!buttonMeshInfo.unpressed +\n ')');\n }\n }\n // Axis Meshes\n for (i = 0; i < this._mapping.axisMeshNames.length; i++) {\n var axisMeshName = this._mapping.axisMeshNames[i];\n if (!axisMeshName) {\n BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);\n continue;\n }\n var axisMesh = getChildByName(rootNode, axisMeshName);\n if (!axisMesh) {\n BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);\n continue;\n }\n var axisMeshInfo = {\n index: i,\n value: getImmediateChildByName(axisMesh, 'VALUE'),\n min: getImmediateChildByName(axisMesh, 'MIN'),\n max: getImmediateChildByName(axisMesh, 'MAX')\n };\n if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {\n loadedMeshInfo.axisMeshes[i] = axisMeshInfo;\n }\n else {\n // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.\n BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +\n '(VALUE: ' + !!axisMeshInfo.value +\n ', MIN: ' + !!axisMeshInfo.min +\n ', MAX:' + !!axisMeshInfo.max +\n ')');\n }\n }\n // Pointing Ray\n loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);\n if (!loadedMeshInfo.pointingPoseNode) {\n BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);\n }\n else {\n this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;\n }\n return loadedMeshInfo;\n // Look through all children recursively. This will return null if no mesh exists with the given name.\n function getChildByName(node, name) {\n return node.getChildMeshes(false, function (n) { return n.name === name; })[0];\n }\n // Look through only immediate children. This will return null if no mesh exists with the given name.\n function getImmediateChildByName(node, name) {\n return node.getChildMeshes(true, function (n) { return n.name == name; })[0];\n }\n };\n /**\n * Gets the ray of the controller in the direction the controller is pointing\n * @param length the length the resulting ray should be\n * @returns a ray in the direction the controller is pointing\n */\n WindowsMotionController.prototype.getForwardRay = function (length) {\n if (length === void 0) { length = 100; }\n if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {\n return _super.prototype.getForwardRay.call(this, length);\n }\n var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();\n var origin = m.getTranslation();\n var forward = new BABYLON.Vector3(0, 0, -1);\n var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);\n var direction = BABYLON.Vector3.Normalize(forwardWorld);\n return new BABYLON.Ray(origin, direction, length);\n };\n /**\n * Disposes of the controller\n */\n WindowsMotionController.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this.onTrackpadChangedObservable.clear();\n };\n /**\n * The base url used to load the left and right controller models\n */\n WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';\n /**\n * The name of the left controller model file\n */\n WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';\n /**\n * The name of the right controller model file\n */\n WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';\n /**\n * The controller name prefix for this controller type\n */\n WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';\n /**\n * The controller id pattern for this controller type\n */\n WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;\n return WindowsMotionController;\n }(BABYLON.WebVRController));\n BABYLON.WindowsMotionController = WindowsMotionController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.windowsMotionController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Gear VR Controller\n */\n var GearVRController = /** @class */ (function (_super) {\n __extends(GearVRController, _super);\n /**\n * Creates a new GearVRController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n function GearVRController(vrGamepad) {\n var _this = _super.call(this, vrGamepad) || this;\n _this._maxRotationDistFromHeadset = Math.PI / 5;\n _this._draggedRoomRotation = 0;\n _this._tmpVector = new BABYLON.Vector3();\n _this._buttonIndexToObservableNameMap = [\n 'onTrackpadChangedObservable',\n 'onTriggerStateChangedObservable' // Trigger\n ];\n _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;\n // Initial starting position defaults to where hand would be (incase of only 3dof controller)\n _this._calculatedPosition = new BABYLON.Vector3(_this.hand == \"left\" ? -0.15 : 0.15, -0.5, 0.25);\n return _this;\n }\n /**\n * Updates the state of the pose enbaled controller based on the raw pose data from the device\n * @param poseData raw pose fromthe device\n */\n GearVRController.prototype.updateFromDevice = function (poseData) {\n _super.prototype.updateFromDevice.call(this, poseData);\n if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {\n if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {\n var camera = BABYLON.Engine.LastCreatedScene.activeCamera;\n camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);\n // Find the radian distance away that the headset is from the controllers rotation\n var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));\n if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {\n // Only rotate enouph to be within the _maxRotationDistFromHeadset\n var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);\n this._draggedRoomRotation += rotationAmount;\n // Rotate controller around headset\n var sin = Math.sin(-rotationAmount);\n var cos = Math.cos(-rotationAmount);\n this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;\n this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;\n }\n }\n }\n };\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {\n var _this = this;\n BABYLON.SceneLoader.ImportMesh(\"\", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {\n // Offset the controller so it will rotate around the users wrist\n var mesh = new BABYLON.Mesh(\"\", scene);\n newMeshes[1].parent = mesh;\n newMeshes[1].position.z = -0.15;\n _this._defaultModel = mesh;\n _this.attachToMesh(_this._defaultModel);\n if (meshLoaded) {\n meshLoaded(_this._defaultModel);\n }\n });\n };\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n * @param changes Which properties on the state changed since last frame\n */\n GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {\n if (buttonIdx < this._buttonIndexToObservableNameMap.length) {\n var observableName = this._buttonIndexToObservableNameMap[buttonIdx];\n // Only emit events for buttons that we know how to map from index to observable\n var observable = this[observableName];\n if (observable) {\n observable.notifyObservers(state);\n }\n }\n };\n /**\n * Base Url for the controller model.\n */\n GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';\n /**\n * File name for the controller model.\n */\n GearVRController.MODEL_FILENAME = 'generic.babylon';\n /**\n * Gamepad Id prefix used to identify this controller.\n */\n GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'\n return GearVRController;\n }(BABYLON.WebVRController));\n BABYLON.GearVRController = GearVRController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gearVRController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Google Daydream controller\n */\n var DaydreamController = /** @class */ (function (_super) {\n __extends(DaydreamController, _super);\n /**\n * Creates a new DaydreamController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n function DaydreamController(vrGamepad) {\n var _this = _super.call(this, vrGamepad) || this;\n _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;\n return _this;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {\n var _this = this;\n BABYLON.SceneLoader.ImportMesh(\"\", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {\n _this._defaultModel = newMeshes[1];\n _this.attachToMesh(_this._defaultModel);\n if (meshLoaded) {\n meshLoaded(_this._defaultModel);\n }\n });\n };\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n * @param changes Which properties on the state changed since last frame\n */\n DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {\n // Daydream controller only has 1 GamepadButton (on the trackpad).\n if (buttonIdx === 0) {\n var observable = this.onTriggerStateChangedObservable;\n if (observable) {\n observable.notifyObservers(state);\n }\n }\n else {\n // If the app or home buttons are ever made available\n BABYLON.Tools.Warn(\"Unrecognized Daydream button index: \" + buttonIdx);\n }\n };\n /**\n * Base Url for the controller model.\n */\n DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';\n /**\n * File name for the controller model.\n */\n DaydreamController.MODEL_FILENAME = 'generic.babylon';\n /**\n * Gamepad Id prefix used to identify Daydream Controller.\n */\n DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'\n return DaydreamController;\n }(BABYLON.WebVRController));\n BABYLON.DaydreamController = DaydreamController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.daydreamController.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n Object.defineProperty(BABYLON.Scene.prototype, \"gamepadManager\", {\n get: function () {\n if (!this._gamepadManager) {\n this._gamepadManager = new BABYLON.GamepadManager(this);\n var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);\n if (!component) {\n component = new GamepadSystemSceneComponent(this);\n this._addComponent(component);\n }\n }\n return this._gamepadManager;\n },\n enumerable: true,\n configurable: true\n });\n BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {\n this.add(new BABYLON.FreeCameraGamepadInput());\n return this;\n };\n BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {\n this.add(new BABYLON.ArcRotateCameraGamepadInput());\n return this;\n };\n /**\n * Defines the gamepad scene component responsible to manage gamepads in a given scene\n */\n var GamepadSystemSceneComponent = /** @class */ (function () {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n function GamepadSystemSceneComponent(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n GamepadSystemSceneComponent.prototype.register = function () {\n this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);\n };\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n GamepadSystemSceneComponent.prototype.rebuild = function () {\n // Nothing to do for gamepads\n };\n /**\n * Disposes the component and the associated ressources\n */\n GamepadSystemSceneComponent.prototype.dispose = function () {\n var gamepadManager = this.scene._gamepadManager;\n if (gamepadManager) {\n gamepadManager.dispose();\n this.scene._gamepadManager = null;\n }\n };\n GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {\n var gamepadManager = this.scene._gamepadManager;\n if (gamepadManager && gamepadManager._isMonitoring) {\n gamepadManager._checkGamepadsStatus();\n }\n };\n return GamepadSystemSceneComponent;\n }());\n BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gamepadSceneComponent.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"FollowCamera\", function (name, scene) {\n return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n BABYLON.Node.AddNodeConstructor(\"ArcFollowCamera\", function (name, scene) {\n return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };\n });\n var FollowCamera = /** @class */ (function (_super) {\n __extends(FollowCamera, _super);\n function FollowCamera(name, position, scene, lockedTarget) {\n if (lockedTarget === void 0) { lockedTarget = null; }\n var _this = _super.call(this, name, position, scene) || this;\n _this.radius = 12;\n _this.rotationOffset = 0;\n _this.heightOffset = 4;\n _this.cameraAcceleration = 0.05;\n _this.maxCameraSpeed = 20;\n _this.lockedTarget = lockedTarget;\n return _this;\n }\n FollowCamera.prototype.getRadians = function (degrees) {\n return degrees * Math.PI / 180;\n };\n FollowCamera.prototype.follow = function (cameraTarget) {\n if (!cameraTarget)\n return;\n var yRotation;\n if (cameraTarget.rotationQuaternion) {\n var rotMatrix = new BABYLON.Matrix();\n cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);\n yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);\n }\n else {\n yRotation = cameraTarget.rotation.y;\n }\n var radians = this.getRadians(this.rotationOffset) + yRotation;\n var targetPosition = cameraTarget.getAbsolutePosition();\n var targetX = targetPosition.x + Math.sin(radians) * this.radius;\n var targetZ = targetPosition.z + Math.cos(radians) * this.radius;\n var dx = targetX - this.position.x;\n var dy = (targetPosition.y + this.heightOffset) - this.position.y;\n var dz = (targetZ) - this.position.z;\n var vx = dx * this.cameraAcceleration * 2; //this is set to .05\n var vy = dy * this.cameraAcceleration;\n var vz = dz * this.cameraAcceleration * 2;\n if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {\n vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;\n }\n if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {\n vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;\n }\n if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {\n vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;\n }\n this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);\n this.setTarget(targetPosition);\n };\n FollowCamera.prototype._checkInputs = function () {\n _super.prototype._checkInputs.call(this);\n if (this.lockedTarget) {\n this.follow(this.lockedTarget);\n }\n };\n FollowCamera.prototype.getClassName = function () {\n return \"FollowCamera\";\n };\n __decorate([\n BABYLON.serialize()\n ], FollowCamera.prototype, \"radius\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FollowCamera.prototype, \"rotationOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FollowCamera.prototype, \"heightOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FollowCamera.prototype, \"cameraAcceleration\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FollowCamera.prototype, \"maxCameraSpeed\", void 0);\n __decorate([\n BABYLON.serializeAsMeshReference(\"lockedTargetId\")\n ], FollowCamera.prototype, \"lockedTarget\", void 0);\n return FollowCamera;\n }(BABYLON.TargetCamera));\n BABYLON.FollowCamera = FollowCamera;\n var ArcFollowCamera = /** @class */ (function (_super) {\n __extends(ArcFollowCamera, _super);\n function ArcFollowCamera(name, alpha, beta, radius, target, scene) {\n var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;\n _this.alpha = alpha;\n _this.beta = beta;\n _this.radius = radius;\n _this.target = target;\n _this._cartesianCoordinates = BABYLON.Vector3.Zero();\n _this.follow();\n return _this;\n }\n ArcFollowCamera.prototype.follow = function () {\n if (!this.target) {\n return;\n }\n this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);\n this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);\n this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);\n var targetPosition = this.target.getAbsolutePosition();\n this.position = targetPosition.add(this._cartesianCoordinates);\n this.setTarget(targetPosition);\n };\n ArcFollowCamera.prototype._checkInputs = function () {\n _super.prototype._checkInputs.call(this);\n this.follow();\n };\n ArcFollowCamera.prototype.getClassName = function () {\n return \"ArcFollowCamera\";\n };\n return ArcFollowCamera;\n }(BABYLON.TargetCamera));\n BABYLON.ArcFollowCamera = ArcFollowCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.followCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n // We're mainly based on the logic defined into the FreeCamera code\n var UniversalCamera = /** @class */ (function (_super) {\n __extends(UniversalCamera, _super);\n //-- end properties for backward compatibility for inputs\n function UniversalCamera(name, position, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.inputs.addGamepad();\n return _this;\n }\n Object.defineProperty(UniversalCamera.prototype, \"gamepadAngularSensibility\", {\n //-- Begin properties for backward compatibility for inputs\n get: function () {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n return gamepad.gamepadAngularSensibility;\n return 0;\n },\n set: function (value) {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n gamepad.gamepadAngularSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(UniversalCamera.prototype, \"gamepadMoveSensibility\", {\n get: function () {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n return gamepad.gamepadMoveSensibility;\n return 0;\n },\n set: function (value) {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n gamepad.gamepadMoveSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n UniversalCamera.prototype.getClassName = function () {\n return \"UniversalCamera\";\n };\n return UniversalCamera;\n }(BABYLON.TouchCamera));\n BABYLON.UniversalCamera = UniversalCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.universalCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"GamepadCamera\", function (name, scene) {\n return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n // We're mainly based on the logic defined into the FreeCamera code\n var GamepadCamera = /** @class */ (function (_super) {\n __extends(GamepadCamera, _super);\n //-- end properties for backward compatibility for inputs\n function GamepadCamera(name, position, scene) {\n return _super.call(this, name, position, scene) || this;\n }\n Object.defineProperty(GamepadCamera.prototype, \"gamepadAngularSensibility\", {\n //-- Begin properties for backward compatibility for inputs\n get: function () {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n return gamepad.gamepadAngularSensibility;\n return 0;\n },\n set: function (value) {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n gamepad.gamepadAngularSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GamepadCamera.prototype, \"gamepadMoveSensibility\", {\n get: function () {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n return gamepad.gamepadMoveSensibility;\n return 0;\n },\n set: function (value) {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n gamepad.gamepadMoveSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n GamepadCamera.prototype.getClassName = function () {\n return \"GamepadCamera\";\n };\n return GamepadCamera;\n }(BABYLON.UniversalCamera));\n BABYLON.GamepadCamera = GamepadCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gamepadCamera.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var PostProcessRenderPipelineManager = /** @class */ (function () {\n function PostProcessRenderPipelineManager() {\n this._renderPipelines = {};\n }\n PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {\n this._renderPipelines[renderPipeline._name] = renderPipeline;\n };\n PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {\n if (unique === void 0) { unique = false; }\n var renderPipeline = this._renderPipelines[renderPipelineName];\n if (!renderPipeline) {\n return;\n }\n renderPipeline._attachCameras(cameras, unique);\n };\n PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {\n var renderPipeline = this._renderPipelines[renderPipelineName];\n if (!renderPipeline) {\n return;\n }\n renderPipeline._detachCameras(cameras);\n };\n PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {\n var renderPipeline = this._renderPipelines[renderPipelineName];\n if (!renderPipeline) {\n return;\n }\n renderPipeline._enableEffect(renderEffectName, cameras);\n };\n PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {\n var renderPipeline = this._renderPipelines[renderPipelineName];\n if (!renderPipeline) {\n return;\n }\n renderPipeline._disableEffect(renderEffectName, cameras);\n };\n PostProcessRenderPipelineManager.prototype.update = function () {\n for (var renderPipelineName in this._renderPipelines) {\n if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {\n var pipeline = this._renderPipelines[renderPipelineName];\n if (!pipeline.isSupported) {\n pipeline.dispose();\n delete this._renderPipelines[renderPipelineName];\n }\n else {\n pipeline._update();\n }\n }\n }\n };\n PostProcessRenderPipelineManager.prototype._rebuild = function () {\n for (var renderPipelineName in this._renderPipelines) {\n if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {\n var pipeline = this._renderPipelines[renderPipelineName];\n pipeline._rebuild();\n }\n }\n };\n PostProcessRenderPipelineManager.prototype.dispose = function () {\n for (var renderPipelineName in this._renderPipelines) {\n if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {\n var pipeline = this._renderPipelines[renderPipelineName];\n pipeline.dispose();\n }\n }\n };\n return PostProcessRenderPipelineManager;\n }());\n BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This represents a set of one or more post processes in Babylon.\n * A post process can be used to apply a shader to a texture after it is rendered.\n * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline\n */\n var PostProcessRenderEffect = /** @class */ (function () {\n /**\n * Instantiates a post process render effect.\n * A post process can be used to apply a shader to a texture after it is rendered.\n * @param engine The engine the effect is tied to\n * @param name The name of the effect\n * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.\n * @param singleInstance False if this post process can be run on multiple cameras. (default: true)\n */\n function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {\n this._name = name;\n this._singleInstance = singleInstance || true;\n this._getPostProcesses = getPostProcesses;\n this._cameras = {};\n this._indicesForCamera = {};\n this._postProcesses = {};\n }\n Object.defineProperty(PostProcessRenderEffect.prototype, \"isSupported\", {\n /**\n * Checks if all the post processes in the effect are supported.\n */\n get: function () {\n for (var index in this._postProcesses) {\n if (this._postProcesses.hasOwnProperty(index)) {\n var pps = this._postProcesses[index];\n for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {\n if (!pps[ppIndex].isSupported) {\n return false;\n }\n }\n }\n }\n return true;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Updates the current state of the effect\n */\n PostProcessRenderEffect.prototype._update = function () {\n };\n /**\n * Attaches the effect on cameras\n * @param cameras The camera to attach to.\n */\n PostProcessRenderEffect.prototype._attachCameras = function (cameras) {\n var _this = this;\n var cameraKey;\n var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (var i = 0; i < cams.length; i++) {\n var camera = cams[i];\n var cameraName = camera.name;\n if (this._singleInstance) {\n cameraKey = 0;\n }\n else {\n cameraKey = cameraName;\n }\n if (!this._postProcesses[cameraKey]) {\n var postProcess = this._getPostProcesses();\n if (postProcess) {\n this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];\n }\n }\n if (!this._indicesForCamera[cameraName]) {\n this._indicesForCamera[cameraName] = [];\n }\n this._postProcesses[cameraKey].forEach(function (postProcess) {\n var index = camera.attachPostProcess(postProcess);\n _this._indicesForCamera[cameraName].push(index);\n });\n if (!this._cameras[cameraName]) {\n this._cameras[cameraName] = camera;\n }\n }\n };\n /**\n * Detatches the effect on cameras\n * @param cameras The camera to detatch from.\n */\n PostProcessRenderEffect.prototype._detachCameras = function (cameras) {\n var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (var i = 0; i < cams.length; i++) {\n var camera = cams[i];\n var cameraName = camera.name;\n this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {\n camera.detachPostProcess(postProcess);\n });\n if (this._cameras[cameraName]) {\n //this._indicesForCamera.splice(index, 1);\n this._cameras[cameraName] = null;\n }\n }\n };\n /**\n * Enables the effect on given cameras\n * @param cameras The camera to enable.\n */\n PostProcessRenderEffect.prototype._enable = function (cameras) {\n var _this = this;\n var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (var i = 0; i < cams.length; i++) {\n var camera = cams[i];\n var cameraName = camera.name;\n for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {\n if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {\n this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {\n cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);\n });\n }\n }\n }\n };\n /**\n * Disables the effect on the given cameras\n * @param cameras The camera to disable.\n */\n PostProcessRenderEffect.prototype._disable = function (cameras) {\n var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (var i = 0; i < cams.length; i++) {\n var camera = cams[i];\n var cameraName = camera.name;\n this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {\n camera.detachPostProcess(postProcess);\n });\n }\n };\n /**\n * Gets a list of the post processes contained in the effect.\n * @param camera The camera to get the post processes on.\n * @returns The list of the post processes in the effect.\n */\n PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {\n if (this._singleInstance) {\n return this._postProcesses[0];\n }\n else {\n if (!camera) {\n return null;\n }\n return this._postProcesses[camera.name];\n }\n };\n return PostProcessRenderEffect;\n }());\n BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.postProcessRenderEffect.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var PostProcessRenderPipeline = /** @class */ (function () {\n function PostProcessRenderPipeline(engine, name) {\n this.engine = engine;\n this._name = name;\n this._renderEffects = {};\n this._renderEffectsForIsolatedPass = new Array();\n this._cameras = [];\n }\n PostProcessRenderPipeline.prototype.getClassName = function () {\n return \"PostProcessRenderPipeline\";\n };\n Object.defineProperty(PostProcessRenderPipeline.prototype, \"isSupported\", {\n get: function () {\n for (var renderEffectName in this._renderEffects) {\n if (this._renderEffects.hasOwnProperty(renderEffectName)) {\n if (!this._renderEffects[renderEffectName].isSupported) {\n return false;\n }\n }\n }\n return true;\n },\n enumerable: true,\n configurable: true\n });\n PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {\n this._renderEffects[renderEffect._name] = renderEffect;\n };\n // private\n PostProcessRenderPipeline.prototype._rebuild = function () {\n };\n PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {\n var renderEffects = this._renderEffects[renderEffectName];\n if (!renderEffects) {\n return;\n }\n renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));\n };\n PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {\n var renderEffects = this._renderEffects[renderEffectName];\n if (!renderEffects) {\n return;\n }\n renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));\n };\n PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {\n var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n var indicesToDelete = [];\n var i;\n for (i = 0; i < cams.length; i++) {\n var camera = cams[i];\n var cameraName = camera.name;\n if (this._cameras.indexOf(camera) === -1) {\n this._cameras[cameraName] = camera;\n }\n else if (unique) {\n indicesToDelete.push(i);\n }\n }\n for (i = 0; i < indicesToDelete.length; i++) {\n cameras.splice(indicesToDelete[i], 1);\n }\n for (var renderEffectName in this._renderEffects) {\n if (this._renderEffects.hasOwnProperty(renderEffectName)) {\n this._renderEffects[renderEffectName]._attachCameras(cams);\n }\n }\n };\n PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {\n var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (var renderEffectName in this._renderEffects) {\n if (this._renderEffects.hasOwnProperty(renderEffectName)) {\n this._renderEffects[renderEffectName]._detachCameras(cams);\n }\n }\n for (var i = 0; i < cams.length; i++) {\n this._cameras.splice(this._cameras.indexOf(cams[i]), 1);\n }\n };\n PostProcessRenderPipeline.prototype._update = function () {\n for (var renderEffectName in this._renderEffects) {\n if (this._renderEffects.hasOwnProperty(renderEffectName)) {\n this._renderEffects[renderEffectName]._update();\n }\n }\n for (var i = 0; i < this._cameras.length; i++) {\n var cameraName = this._cameras[i].name;\n if (this._renderEffectsForIsolatedPass[cameraName]) {\n this._renderEffectsForIsolatedPass[cameraName]._update();\n }\n }\n };\n PostProcessRenderPipeline.prototype._reset = function () {\n this._renderEffects = {};\n this._renderEffectsForIsolatedPass = new Array();\n };\n PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {\n // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)\n var effectKeys = Object.keys(this._renderEffects);\n if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {\n var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();\n if (postProcesses) {\n postProcesses[0].samples = sampleCount;\n return true;\n }\n }\n return false;\n };\n PostProcessRenderPipeline.prototype.dispose = function () {\n // Must be implemented by children \n };\n __decorate([\n BABYLON.serialize()\n ], PostProcessRenderPipeline.prototype, \"_name\", void 0);\n return PostProcessRenderPipeline;\n }());\n BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.postProcessRenderPipeline.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This represents a depth renderer in Babylon.\n * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing\n */\n var DepthRenderer = /** @class */ (function () {\n /**\n * Instantiates a depth renderer\n * @param scene The scene the renderer belongs to\n * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)\n * @param camera The camera to be used to render the depth map (default: scene's active camera)\n */\n function DepthRenderer(scene, type, camera) {\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }\n if (camera === void 0) { camera = null; }\n var _this = this;\n this._scene = scene;\n this._camera = camera;\n var engine = scene.getEngine();\n // Render target\n this._depthMap = new BABYLON.RenderTargetTexture(\"depthMap\", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);\n this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._depthMap.refreshRate = 1;\n this._depthMap.renderParticles = false;\n this._depthMap.renderList = null;\n // Camera to get depth map from to support multiple concurrent cameras\n this._depthMap.activeCamera = this._camera;\n this._depthMap.ignoreCameraViewport = true;\n this._depthMap.useCameraPostProcesses = false;\n // set default depth value to 1.0 (far away)\n this._depthMap.onClearObservable.add(function (engine) {\n engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);\n });\n // Custom render function\n var renderSubMesh = function (subMesh) {\n var mesh = subMesh.getRenderingMesh();\n var scene = _this._scene;\n var engine = scene.getEngine();\n var material = subMesh.getMaterial();\n if (!material) {\n return;\n }\n // Culling and reverse (right handed system)\n engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);\n // Managing instances\n var batch = mesh._getInstancesRenderList(subMesh._id);\n if (batch.mustReturn) {\n return;\n }\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);\n var camera = _this._camera || scene.activeCamera;\n if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {\n engine.enableEffect(_this._effect);\n mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);\n _this._effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n _this._effect.setFloat2(\"depthValues\", camera.minZ, camera.minZ + camera.maxZ);\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n _this._effect.setTexture(\"diffuseSampler\", alphaTexture);\n _this._effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n _this._effect.setMatrices(\"mBones\", mesh.skeleton.getTransformMatrices(mesh));\n }\n // Draw\n mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix(\"world\", world); });\n }\n };\n this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {\n var index;\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n };\n }\n /**\n * Creates the depth rendering effect and checks if the effect is ready.\n * @param subMesh The submesh to be used to render the depth map of\n * @param useInstances If multiple world instances should be used\n * @returns if the depth renderer is ready to render the depth map\n */\n DepthRenderer.prototype.isReady = function (subMesh, useInstances) {\n var material = subMesh.getMaterial();\n if (material.disableDepthWrite) {\n return false;\n }\n var defines = [];\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n var mesh = subMesh.getMesh();\n // Alpha test\n if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n // Get correct effect \n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n this._effect = this._scene.getEngine().createEffect(\"depth\", attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\", \"depthValues\"], [\"diffuseSampler\"], join);\n }\n return this._effect.isReady();\n };\n /**\n * Gets the texture which the depth map will be written to.\n * @returns The depth map texture\n */\n DepthRenderer.prototype.getDepthMap = function () {\n return this._depthMap;\n };\n /**\n * Disposes of the depth renderer.\n */\n DepthRenderer.prototype.dispose = function () {\n this._depthMap.dispose();\n };\n return DepthRenderer;\n }());\n BABYLON.DepthRenderer = DepthRenderer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.depthRenderer.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var SSAORenderingPipeline = /** @class */ (function (_super) {\n __extends(SSAORenderingPipeline, _super);\n /**\n * @constructor\n * @param {string} name - The rendering pipeline name\n * @param {BABYLON.Scene} scene - The scene linked to this pipeline\n * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }\n * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to\n */\n function SSAORenderingPipeline(name, scene, ratio, cameras) {\n var _this = _super.call(this, scene.getEngine(), name) || this;\n // Members\n /**\n * The PassPostProcess id in the pipeline that contains the original scene color\n */\n _this.SSAOOriginalSceneColorEffect = \"SSAOOriginalSceneColorEffect\";\n /**\n * The SSAO PostProcess id in the pipeline\n */\n _this.SSAORenderEffect = \"SSAORenderEffect\";\n /**\n * The horizontal blur PostProcess id in the pipeline\n */\n _this.SSAOBlurHRenderEffect = \"SSAOBlurHRenderEffect\";\n /**\n * The vertical blur PostProcess id in the pipeline\n */\n _this.SSAOBlurVRenderEffect = \"SSAOBlurVRenderEffect\";\n /**\n * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)\n */\n _this.SSAOCombineRenderEffect = \"SSAOCombineRenderEffect\";\n /**\n * The output strength of the SSAO post-process. Default value is 1.0.\n */\n _this.totalStrength = 1.0;\n /**\n * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006\n */\n _this.radius = 0.0001;\n /**\n * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel\n * Must not be equal to fallOff and superior to fallOff.\n * Default value is 0.975\n */\n _this.area = 0.0075;\n /**\n * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel\n * Must not be equal to area and inferior to area.\n * Default value is 0.0\n */\n _this.fallOff = 0.000001;\n /**\n * The base color of the SSAO post-process\n * The final result is \"base + ssao\" between [0, 1]\n */\n _this.base = 0.5;\n _this._firstUpdate = true;\n _this._scene = scene;\n // Set up assets\n _this._createRandomTexture();\n _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer \"on\"\n var ssaoRatio = ratio.ssaoRatio || ratio;\n var combineRatio = ratio.combineRatio || ratio;\n _this._originalColorPostProcess = new BABYLON.PassPostProcess(\"SSAOOriginalSceneColor\", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);\n _this._createSSAOPostProcess(ssaoRatio);\n _this._createBlurPostProcess(ssaoRatio);\n _this._createSSAOCombinePostProcess(combineRatio);\n // Set up pipeline\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(_this);\n if (cameras)\n scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);\n return _this;\n }\n // Public Methods\n /**\n * Removes the internal pipeline assets and detatches the pipeline from the scene cameras\n */\n SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {\n if (disableDepthRender === void 0) { disableDepthRender = false; }\n for (var i = 0; i < this._scene.cameras.length; i++) {\n var camera = this._scene.cameras[i];\n this._originalColorPostProcess.dispose(camera);\n this._ssaoPostProcess.dispose(camera);\n this._blurHPostProcess.dispose(camera);\n this._blurVPostProcess.dispose(camera);\n this._ssaoCombinePostProcess.dispose(camera);\n }\n this._randomTexture.dispose();\n if (disableDepthRender)\n this._scene.disableDepthRenderer();\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);\n _super.prototype.dispose.call(this);\n };\n // Private Methods\n SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {\n var _this = this;\n var size = 16;\n this._blurHPostProcess = new BABYLON.BlurPostProcess(\"BlurH\", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this._blurVPostProcess = new BABYLON.BlurPostProcess(\"BlurV\", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this._blurHPostProcess.onActivateObservable.add(function () {\n var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();\n _this._blurHPostProcess.kernel = size * dw;\n });\n this._blurVPostProcess.onActivateObservable.add(function () {\n var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();\n _this._blurVPostProcess.kernel = size * dw;\n });\n };\n SSAORenderingPipeline.prototype._rebuild = function () {\n this._firstUpdate = true;\n _super.prototype._rebuild.call(this);\n };\n SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {\n var _this = this;\n var numSamples = 16;\n var sampleSphere = [\n 0.5381, 0.1856, -0.4319,\n 0.1379, 0.2486, 0.4430,\n 0.3371, 0.5679, -0.0057,\n -0.6999, -0.0451, -0.0019,\n 0.0689, -0.1598, -0.8547,\n 0.0560, 0.0069, -0.1843,\n -0.0146, 0.1402, 0.0762,\n 0.0100, -0.1924, -0.0344,\n -0.3577, -0.5301, -0.4358,\n -0.3169, 0.1063, 0.0158,\n 0.0103, -0.5869, 0.0046,\n -0.0897, -0.4940, 0.3287,\n 0.7119, -0.0154, -0.0918,\n -0.0533, 0.0596, -0.5411,\n 0.0352, -0.0631, 0.5460,\n -0.4776, 0.2847, -0.0271\n ];\n var samplesFactor = 1.0 / numSamples;\n this._ssaoPostProcess = new BABYLON.PostProcess(\"ssao\", \"ssao\", [\n \"sampleSphere\", \"samplesFactor\", \"randTextureTiles\", \"totalStrength\", \"radius\",\n \"area\", \"fallOff\", \"base\", \"range\", \"viewport\"\n ], [\"randomSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, \"#define SAMPLES \" + numSamples + \"\\n#define SSAO\");\n this._ssaoPostProcess.onApply = function (effect) {\n if (_this._firstUpdate) {\n effect.setArray3(\"sampleSphere\", sampleSphere);\n effect.setFloat(\"samplesFactor\", samplesFactor);\n effect.setFloat(\"randTextureTiles\", 4.0);\n }\n effect.setFloat(\"totalStrength\", _this.totalStrength);\n effect.setFloat(\"radius\", _this.radius);\n effect.setFloat(\"area\", _this.area);\n effect.setFloat(\"fallOff\", _this.fallOff);\n effect.setFloat(\"base\", _this.base);\n effect.setTexture(\"textureSampler\", _this._depthTexture);\n effect.setTexture(\"randomSampler\", _this._randomTexture);\n };\n };\n SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {\n var _this = this;\n this._ssaoCombinePostProcess = new BABYLON.PostProcess(\"ssaoCombine\", \"ssaoCombine\", [], [\"originalColor\", \"viewport\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._ssaoCombinePostProcess.onApply = function (effect) {\n effect.setVector4(\"viewport\", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));\n effect.setTextureFromPostProcess(\"originalColor\", _this._originalColorPostProcess);\n };\n };\n SSAORenderingPipeline.prototype._createRandomTexture = function () {\n var size = 512;\n this._randomTexture = new BABYLON.DynamicTexture(\"SSAORandomTexture\", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);\n this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n var context = this._randomTexture.getContext();\n var rand = function (min, max) {\n return Math.random() * (max - min) + min;\n };\n var randVector = BABYLON.Vector3.Zero();\n for (var x = 0; x < size; x++) {\n for (var y = 0; y < size; y++) {\n randVector.x = Math.floor(rand(-1.0, 1.0) * 255);\n randVector.y = Math.floor(rand(-1.0, 1.0) * 255);\n randVector.z = Math.floor(rand(-1.0, 1.0) * 255);\n context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';\n context.fillRect(x, y, 1, 1);\n }\n }\n this._randomTexture.update(false);\n };\n __decorate([\n BABYLON.serialize()\n ], SSAORenderingPipeline.prototype, \"totalStrength\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAORenderingPipeline.prototype, \"radius\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAORenderingPipeline.prototype, \"area\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAORenderingPipeline.prototype, \"fallOff\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAORenderingPipeline.prototype, \"base\", void 0);\n return SSAORenderingPipeline;\n }(BABYLON.PostProcessRenderPipeline));\n BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var SSAO2RenderingPipeline = /** @class */ (function (_super) {\n __extends(SSAO2RenderingPipeline, _super);\n /**\n * @constructor\n * @param {string} name - The rendering pipeline name\n * @param {BABYLON.Scene} scene - The scene linked to this pipeline\n * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }\n * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to\n */\n function SSAO2RenderingPipeline(name, scene, ratio, cameras) {\n var _this = _super.call(this, scene.getEngine(), name) || this;\n // Members\n /**\n * The PassPostProcess id in the pipeline that contains the original scene color\n */\n _this.SSAOOriginalSceneColorEffect = \"SSAOOriginalSceneColorEffect\";\n /**\n * The SSAO PostProcess id in the pipeline\n */\n _this.SSAORenderEffect = \"SSAORenderEffect\";\n /**\n * The horizontal blur PostProcess id in the pipeline\n */\n _this.SSAOBlurHRenderEffect = \"SSAOBlurHRenderEffect\";\n /**\n * The vertical blur PostProcess id in the pipeline\n */\n _this.SSAOBlurVRenderEffect = \"SSAOBlurVRenderEffect\";\n /**\n * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)\n */\n _this.SSAOCombineRenderEffect = \"SSAOCombineRenderEffect\";\n /**\n * The output strength of the SSAO post-process. Default value is 1.0.\n */\n _this.totalStrength = 1.0;\n /**\n * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.\n */\n _this.maxZ = 100.0;\n /**\n * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much\n */\n _this.minZAspect = 0.2;\n /**\n * Number of samples used for the SSAO calculations. Default value is 8\n */\n _this._samples = 8;\n /**\n * Are we using bilateral blur ?\n */\n _this._expensiveBlur = true;\n /**\n * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0\n */\n _this.radius = 2.0;\n /**\n * The base color of the SSAO post-process\n * The final result is \"base + ssao\" between [0, 1]\n */\n _this.base = 0.1;\n _this._firstUpdate = true;\n _this._scene = scene;\n _this._ratio = ratio;\n if (!_this.isSupported) {\n BABYLON.Tools.Error(\"SSAO 2 needs WebGL 2 support.\");\n return _this;\n }\n var ssaoRatio = _this._ratio.ssaoRatio || ratio;\n var blurRatio = _this._ratio.blurRatio || ratio;\n // Set up assets\n var geometryBufferRenderer = scene.enableGeometryBufferRenderer();\n _this._createRandomTexture();\n _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];\n _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];\n _this._originalColorPostProcess = new BABYLON.PassPostProcess(\"SSAOOriginalSceneColor\", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);\n _this._createSSAOPostProcess(1.0);\n _this._createBlurPostProcess(ssaoRatio, blurRatio);\n _this._createSSAOCombinePostProcess(blurRatio);\n // Set up pipeline\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(_this);\n if (cameras)\n scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);\n return _this;\n }\n Object.defineProperty(SSAO2RenderingPipeline.prototype, \"samples\", {\n get: function () {\n return this._samples;\n },\n set: function (n) {\n this._ssaoPostProcess.updateEffect(\"#define SAMPLES \" + n + \"\\n#define SSAO\");\n this._samples = n;\n this._sampleSphere = this._generateHemisphere();\n this._firstUpdate = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SSAO2RenderingPipeline.prototype, \"expensiveBlur\", {\n get: function () {\n return this._expensiveBlur;\n },\n set: function (b) {\n this._blurHPostProcess.updateEffect(\"#define BILATERAL_BLUR\\n#define BILATERAL_BLUR_H\\n#define SAMPLES 16\\n#define EXPENSIVE \" + (b ? \"1\" : \"0\") + \"\\n\", null, [\"textureSampler\", \"depthSampler\"]);\n this._blurVPostProcess.updateEffect(\"#define BILATERAL_BLUR\\n#define SAMPLES 16\\n#define EXPENSIVE \" + (b ? \"1\" : \"0\") + \"\\n\", null, [\"textureSampler\", \"depthSampler\"]);\n this._expensiveBlur = b;\n this._firstUpdate = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SSAO2RenderingPipeline, \"IsSupported\", {\n /**\n * Support test.\n */\n get: function () {\n var engine = BABYLON.Engine.LastCreatedEngine;\n if (!engine) {\n return false;\n }\n return engine.getCaps().drawBuffersExtension;\n },\n enumerable: true,\n configurable: true\n });\n // Public Methods\n /**\n * Removes the internal pipeline assets and detatches the pipeline from the scene cameras\n */\n SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {\n if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }\n for (var i = 0; i < this._scene.cameras.length; i++) {\n var camera = this._scene.cameras[i];\n this._originalColorPostProcess.dispose(camera);\n this._ssaoPostProcess.dispose(camera);\n this._blurHPostProcess.dispose(camera);\n this._blurVPostProcess.dispose(camera);\n this._ssaoCombinePostProcess.dispose(camera);\n }\n this._randomTexture.dispose();\n if (disableGeometryBufferRenderer)\n this._scene.disableGeometryBufferRenderer();\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);\n _super.prototype.dispose.call(this);\n };\n // Private Methods\n SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {\n var _this = this;\n this._samplerOffsets = [];\n var expensive = this.expensiveBlur;\n for (var i = -8; i < 8; i++) {\n this._samplerOffsets.push(i * 2 + 0.5);\n }\n this._blurHPostProcess = new BABYLON.PostProcess(\"BlurH\", \"ssao2\", [\"outSize\", \"samplerOffsets\", \"near\", \"far\", \"radius\"], [\"depthSampler\"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, \"#define BILATERAL_BLUR\\n#define BILATERAL_BLUR_H\\n#define SAMPLES 16\\n#define EXPENSIVE \" + (expensive ? \"1\" : \"0\") + \"\\n\");\n this._blurHPostProcess.onApply = function (effect) {\n if (!_this._scene.activeCamera) {\n return;\n }\n effect.setFloat(\"outSize\", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);\n effect.setFloat(\"near\", _this._scene.activeCamera.minZ);\n effect.setFloat(\"far\", _this._scene.activeCamera.maxZ);\n effect.setFloat(\"radius\", _this.radius);\n effect.setTexture(\"depthSampler\", _this._depthTexture);\n if (_this._firstUpdate) {\n effect.setArray(\"samplerOffsets\", _this._samplerOffsets);\n }\n };\n this._blurVPostProcess = new BABYLON.PostProcess(\"BlurV\", \"ssao2\", [\"outSize\", \"samplerOffsets\", \"near\", \"far\", \"radius\"], [\"depthSampler\"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, \"#define BILATERAL_BLUR\\n#define BILATERAL_BLUR_V\\n#define SAMPLES 16\\n#define EXPENSIVE \" + (expensive ? \"1\" : \"0\") + \"\\n\");\n this._blurVPostProcess.onApply = function (effect) {\n if (!_this._scene.activeCamera) {\n return;\n }\n effect.setFloat(\"outSize\", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);\n effect.setFloat(\"near\", _this._scene.activeCamera.minZ);\n effect.setFloat(\"far\", _this._scene.activeCamera.maxZ);\n effect.setFloat(\"radius\", _this.radius);\n effect.setTexture(\"depthSampler\", _this._depthTexture);\n if (_this._firstUpdate) {\n effect.setArray(\"samplerOffsets\", _this._samplerOffsets);\n _this._firstUpdate = false;\n }\n };\n };\n SSAO2RenderingPipeline.prototype._rebuild = function () {\n this._firstUpdate = true;\n _super.prototype._rebuild.call(this);\n };\n SSAO2RenderingPipeline.prototype._generateHemisphere = function () {\n var numSamples = this.samples;\n var result = [];\n var vector, scale;\n var rand = function (min, max) {\n return Math.random() * (max - min) + min;\n };\n var i = 0;\n while (i < numSamples) {\n vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));\n vector.normalize();\n scale = i / numSamples;\n scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);\n vector.scaleInPlace(scale);\n result.push(vector.x, vector.y, vector.z);\n i++;\n }\n return result;\n };\n SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {\n var _this = this;\n var numSamples = this.samples;\n this._sampleSphere = this._generateHemisphere();\n this._ssaoPostProcess = new BABYLON.PostProcess(\"ssao2\", \"ssao2\", [\n \"sampleSphere\", \"samplesFactor\", \"randTextureTiles\", \"totalStrength\", \"radius\",\n \"base\", \"range\", \"projection\", \"near\", \"far\", \"texelSize\",\n \"xViewport\", \"yViewport\", \"maxZ\", \"minZAspect\"\n ], [\"randomSampler\", \"normalSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, \"#define SAMPLES \" + numSamples + \"\\n#define SSAO\");\n this._ssaoPostProcess.onApply = function (effect) {\n if (_this._firstUpdate) {\n effect.setArray3(\"sampleSphere\", _this._sampleSphere);\n effect.setFloat(\"randTextureTiles\", 4.0);\n }\n if (!_this._scene.activeCamera) {\n return;\n }\n effect.setFloat(\"samplesFactor\", 1 / _this.samples);\n effect.setFloat(\"totalStrength\", _this.totalStrength);\n effect.setFloat2(\"texelSize\", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);\n effect.setFloat(\"radius\", _this.radius);\n effect.setFloat(\"maxZ\", _this.maxZ);\n effect.setFloat(\"minZAspect\", _this.minZAspect);\n effect.setFloat(\"base\", _this.base);\n effect.setFloat(\"near\", _this._scene.activeCamera.minZ);\n effect.setFloat(\"far\", _this._scene.activeCamera.maxZ);\n effect.setFloat(\"xViewport\", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));\n effect.setFloat(\"yViewport\", Math.tan(_this._scene.activeCamera.fov / 2));\n effect.setMatrix(\"projection\", _this._scene.getProjectionMatrix());\n effect.setTexture(\"textureSampler\", _this._depthTexture);\n effect.setTexture(\"normalSampler\", _this._normalTexture);\n effect.setTexture(\"randomSampler\", _this._randomTexture);\n };\n };\n SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {\n var _this = this;\n this._ssaoCombinePostProcess = new BABYLON.PostProcess(\"ssaoCombine\", \"ssaoCombine\", [], [\"originalColor\", \"viewport\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._ssaoCombinePostProcess.onApply = function (effect) {\n var viewport = _this._scene.activeCamera.viewport;\n effect.setVector4(\"viewport\", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));\n effect.setTextureFromPostProcess(\"originalColor\", _this._originalColorPostProcess);\n };\n };\n SSAO2RenderingPipeline.prototype._createRandomTexture = function () {\n var size = 512;\n this._randomTexture = new BABYLON.DynamicTexture(\"SSAORandomTexture\", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);\n this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n var context = this._randomTexture.getContext();\n var rand = function (min, max) {\n return Math.random() * (max - min) + min;\n };\n var randVector = BABYLON.Vector3.Zero();\n for (var x = 0; x < size; x++) {\n for (var y = 0; y < size; y++) {\n randVector.x = rand(0.0, 1.0);\n randVector.y = rand(0.0, 1.0);\n randVector.z = 0.0;\n randVector.normalize();\n randVector.scaleInPlace(255);\n randVector.x = Math.floor(randVector.x);\n randVector.y = Math.floor(randVector.y);\n context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';\n context.fillRect(x, y, 1, 1);\n }\n }\n this._randomTexture.update(false);\n };\n /**\n * Serialize the rendering pipeline (Used when exporting)\n * @returns the serialized object\n */\n SSAO2RenderingPipeline.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"SSAO2RenderingPipeline\";\n return serializationObject;\n };\n /**\n * Parse the serialized pipeline\n * @param source Source pipeline.\n * @param scene The scene to load the pipeline to.\n * @param rootUrl The URL of the serialized pipeline.\n * @returns An instantiated pipeline from the serialized object.\n */\n SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);\n };\n __decorate([\n BABYLON.serialize()\n ], SSAO2RenderingPipeline.prototype, \"totalStrength\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAO2RenderingPipeline.prototype, \"maxZ\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAO2RenderingPipeline.prototype, \"minZAspect\", void 0);\n __decorate([\n BABYLON.serialize(\"samples\")\n ], SSAO2RenderingPipeline.prototype, \"_samples\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAO2RenderingPipeline.prototype, \"_ratio\", void 0);\n __decorate([\n BABYLON.serialize(\"expensiveBlur\")\n ], SSAO2RenderingPipeline.prototype, \"_expensiveBlur\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAO2RenderingPipeline.prototype, \"radius\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAO2RenderingPipeline.prototype, \"base\", void 0);\n return SSAO2RenderingPipeline;\n }(BABYLON.PostProcessRenderPipeline));\n BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map\n\n// BABYLON.JS Chromatic Aberration GLSL Shader\n// Author: Olivier Guyot\n// Separates very slightly R, G and B colors on the edges of the screen\n// Inspired by Francois Tarlier & Martins Upitis\n\nvar BABYLON;\n(function (BABYLON) {\n var LensRenderingPipeline = /** @class */ (function (_super) {\n __extends(LensRenderingPipeline, _super);\n /**\n * @constructor\n *\n * Effect parameters are as follow:\n * {\n * chromatic_aberration: number; // from 0 to x (1 for realism)\n * edge_blur: number; // from 0 to x (1 for realism)\n * distortion: number; // from 0 to x (1 for realism)\n * grain_amount: number; // from 0 to 1\n * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise\n * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)\n * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)\n * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)\n * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like \"bokeh\" effect\n * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)\n * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)\n * blur_noise: boolean; // add a little bit of noise to the blur (default: true)\n * }\n * Note: if an effect parameter is unset, effect is disabled\n *\n * @param {string} name - The rendering pipeline name\n * @param {object} parameters - An object containing all parameters (see above)\n * @param {BABYLON.Scene} scene - The scene linked to this pipeline\n * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)\n * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to\n */\n function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {\n if (ratio === void 0) { ratio = 1.0; }\n var _this = _super.call(this, scene.getEngine(), name) || this;\n // Lens effects can be of the following:\n // - chromatic aberration (slight shift of RGB colors)\n // - blur on the edge of the lens\n // - lens distortion\n // - depth-of-field blur & highlights enhancing\n // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)\n // - grain effect (noise or custom texture)\n // Two additional texture samplers are needed:\n // - depth map (for depth-of-field)\n // - grain texture\n /**\n * The chromatic aberration PostProcess id in the pipeline\n */\n _this.LensChromaticAberrationEffect = \"LensChromaticAberrationEffect\";\n /**\n * The highlights enhancing PostProcess id in the pipeline\n */\n _this.HighlightsEnhancingEffect = \"HighlightsEnhancingEffect\";\n /**\n * The depth-of-field PostProcess id in the pipeline\n */\n _this.LensDepthOfFieldEffect = \"LensDepthOfFieldEffect\";\n _this._scene = scene;\n // Fetch texture samplers\n _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer \"on\"\n if (parameters.grain_texture) {\n _this._grainTexture = parameters.grain_texture;\n }\n else {\n _this._createGrainTexture();\n }\n // save parameters\n _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;\n _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;\n _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;\n _this._distortion = parameters.distortion ? parameters.distortion : 0;\n _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;\n _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;\n _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;\n _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;\n _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;\n _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;\n _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;\n // Create effects\n _this._createChromaticAberrationPostProcess(ratio);\n _this._createHighlightsPostProcess(ratio);\n _this._createDepthOfFieldPostProcess(ratio / 4);\n // Set up pipeline\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));\n if (_this._highlightsGain === -1) {\n _this._disableEffect(_this.HighlightsEnhancingEffect, null);\n }\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(_this);\n if (cameras) {\n scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);\n }\n return _this;\n }\n // public methods (self explanatory)\n LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };\n LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };\n LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };\n LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };\n LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };\n LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };\n LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };\n LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };\n LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };\n LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };\n LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };\n LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };\n LensRenderingPipeline.prototype.enablePentagonBokeh = function () {\n this._highlightsPostProcess.updateEffect(\"#define PENTAGON\\n\");\n };\n LensRenderingPipeline.prototype.disablePentagonBokeh = function () {\n this._highlightsPostProcess.updateEffect();\n };\n LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };\n LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };\n LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {\n this._highlightsGain = amount;\n };\n LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {\n if (this._highlightsGain === -1) {\n this._highlightsGain = 1.0;\n }\n this._highlightsThreshold = amount;\n };\n LensRenderingPipeline.prototype.disableHighlights = function () {\n this._highlightsGain = -1;\n };\n /**\n * Removes the internal pipeline assets and detaches the pipeline from the scene cameras\n */\n LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {\n if (disableDepthRender === void 0) { disableDepthRender = false; }\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);\n this._chromaticAberrationPostProcess = null;\n this._highlightsPostProcess = null;\n this._depthOfFieldPostProcess = null;\n this._grainTexture.dispose();\n if (disableDepthRender)\n this._scene.disableDepthRenderer();\n };\n // colors shifting and distortion\n LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {\n var _this = this;\n this._chromaticAberrationPostProcess = new BABYLON.PostProcess(\"LensChromaticAberration\", \"chromaticAberration\", [\"chromatic_aberration\", \"screen_width\", \"screen_height\", \"direction\", \"radialIntensity\", \"centerPosition\"], // uniforms\n [], // samplers\n ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._chromaticAberrationPostProcess.onApply = function (effect) {\n effect.setFloat('chromatic_aberration', _this._chromaticAberration);\n effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());\n effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());\n effect.setFloat('radialIntensity', 1);\n effect.setFloat2('direction', 17, 17);\n effect.setFloat2('centerPosition', 0.5, 0.5);\n };\n };\n // highlights enhancing\n LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {\n var _this = this;\n this._highlightsPostProcess = new BABYLON.PostProcess(\"LensHighlights\", \"lensHighlights\", [\"gain\", \"threshold\", \"screen_width\", \"screen_height\"], // uniforms\n [], // samplers\n ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? \"#define PENTAGON\\n\" : \"\");\n this._highlightsPostProcess.onApply = function (effect) {\n effect.setFloat('gain', _this._highlightsGain);\n effect.setFloat('threshold', _this._highlightsThreshold);\n effect.setTextureFromPostProcess(\"textureSampler\", _this._chromaticAberrationPostProcess);\n effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());\n effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());\n };\n };\n // colors shifting and distortion\n LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {\n var _this = this;\n this._depthOfFieldPostProcess = new BABYLON.PostProcess(\"LensDepthOfField\", \"depthOfField\", [\n \"grain_amount\", \"blur_noise\", \"screen_width\", \"screen_height\", \"distortion\", \"dof_enabled\",\n \"screen_distance\", \"aperture\", \"darken\", \"edge_blur\", \"highlights\", \"near\", \"far\"\n ], [\"depthSampler\", \"grainSampler\", \"highlightsSampler\"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._depthOfFieldPostProcess.onApply = function (effect) {\n effect.setTexture(\"depthSampler\", _this._depthTexture);\n effect.setTexture(\"grainSampler\", _this._grainTexture);\n effect.setTextureFromPostProcess(\"textureSampler\", _this._highlightsPostProcess);\n effect.setTextureFromPostProcess(\"highlightsSampler\", _this._depthOfFieldPostProcess);\n effect.setFloat('grain_amount', _this._grainAmount);\n effect.setBool('blur_noise', _this._blurNoise);\n effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());\n effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());\n effect.setFloat('distortion', _this._distortion);\n effect.setBool('dof_enabled', (_this._dofDistance !== -1));\n effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));\n effect.setFloat('aperture', _this._dofAperture);\n effect.setFloat('darken', _this._dofDarken);\n effect.setFloat('edge_blur', _this._edgeBlur);\n effect.setBool('highlights', (_this._highlightsGain !== -1));\n if (_this._scene.activeCamera) {\n effect.setFloat('near', _this._scene.activeCamera.minZ);\n effect.setFloat('far', _this._scene.activeCamera.maxZ);\n }\n };\n };\n // creates a black and white random noise texture, 512x512\n LensRenderingPipeline.prototype._createGrainTexture = function () {\n var size = 512;\n this._grainTexture = new BABYLON.DynamicTexture(\"LensNoiseTexture\", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n var context = this._grainTexture.getContext();\n var rand = function (min, max) {\n return Math.random() * (max - min) + min;\n };\n var value;\n for (var x = 0; x < size; x++) {\n for (var y = 0; y < size; y++) {\n value = Math.floor(rand(0.42, 0.58) * 255);\n context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';\n context.fillRect(x, y, 1, 1);\n }\n }\n this._grainTexture.update(false);\n };\n return LensRenderingPipeline;\n }(BABYLON.PostProcessRenderPipeline));\n BABYLON.LensRenderingPipeline = LensRenderingPipeline;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.lensRenderingPipeline.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var StandardRenderingPipeline = /** @class */ (function (_super) {\n __extends(StandardRenderingPipeline, _super);\n /**\n * @constructor\n * @param {string} name - The rendering pipeline name\n * @param {BABYLON.Scene} scene - The scene linked to this pipeline\n * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)\n * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be \"reusable\". Can be null.\n * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to\n */\n function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {\n if (originalPostProcess === void 0) { originalPostProcess = null; }\n var _this = _super.call(this, scene.getEngine(), name) || this;\n _this.downSampleX4PostProcess = null;\n _this.brightPassPostProcess = null;\n _this.blurHPostProcesses = [];\n _this.blurVPostProcesses = [];\n _this.textureAdderPostProcess = null;\n _this.volumetricLightPostProcess = null;\n _this.volumetricLightSmoothXPostProcess = null;\n _this.volumetricLightSmoothYPostProcess = null;\n _this.volumetricLightMergePostProces = null;\n _this.volumetricLightFinalPostProcess = null;\n _this.luminancePostProcess = null;\n _this.luminanceDownSamplePostProcesses = [];\n _this.hdrPostProcess = null;\n _this.textureAdderFinalPostProcess = null;\n _this.lensFlareFinalPostProcess = null;\n _this.hdrFinalPostProcess = null;\n _this.lensFlarePostProcess = null;\n _this.lensFlareComposePostProcess = null;\n _this.motionBlurPostProcess = null;\n _this.depthOfFieldPostProcess = null;\n // Values\n _this.brightThreshold = 1.0;\n _this.blurWidth = 512.0;\n _this.horizontalBlur = false;\n _this.exposure = 1.0;\n _this.lensTexture = null;\n _this.volumetricLightCoefficient = 0.2;\n _this.volumetricLightPower = 4.0;\n _this.volumetricLightBlurScale = 64.0;\n _this.sourceLight = null;\n _this.hdrMinimumLuminance = 1.0;\n _this.hdrDecreaseRate = 0.5;\n _this.hdrIncreaseRate = 0.5;\n _this.lensColorTexture = null;\n _this.lensFlareStrength = 20.0;\n _this.lensFlareGhostDispersal = 1.4;\n _this.lensFlareHaloWidth = 0.7;\n _this.lensFlareDistortionStrength = 16.0;\n _this.lensStarTexture = null;\n _this.lensFlareDirtTexture = null;\n _this.depthOfFieldDistance = 10.0;\n _this.depthOfFieldBlurWidth = 64.0;\n _this.motionStrength = 1.0;\n // IAnimatable\n _this.animations = [];\n _this._currentDepthOfFieldSource = null;\n _this._hdrCurrentLuminance = 1.0;\n // Getters and setters\n _this._bloomEnabled = true;\n _this._depthOfFieldEnabled = false;\n _this._vlsEnabled = false;\n _this._lensFlareEnabled = false;\n _this._hdrEnabled = false;\n _this._motionBlurEnabled = false;\n _this._motionBlurSamples = 64.0;\n _this._volumetricLightStepsCount = 50.0;\n _this._cameras = cameras || [];\n // Initialize\n _this._scene = scene;\n _this._basePostProcess = originalPostProcess;\n _this._ratio = ratio;\n // Misc\n _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(_this);\n _this._buildPipeline();\n return _this;\n }\n Object.defineProperty(StandardRenderingPipeline.prototype, \"BloomEnabled\", {\n get: function () {\n return this._bloomEnabled;\n },\n set: function (enabled) {\n if (this._bloomEnabled === enabled) {\n return;\n }\n this._bloomEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"DepthOfFieldEnabled\", {\n get: function () {\n return this._depthOfFieldEnabled;\n },\n set: function (enabled) {\n if (this._depthOfFieldEnabled === enabled) {\n return;\n }\n this._depthOfFieldEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"LensFlareEnabled\", {\n get: function () {\n return this._lensFlareEnabled;\n },\n set: function (enabled) {\n if (this._lensFlareEnabled === enabled) {\n return;\n }\n this._lensFlareEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"HDREnabled\", {\n get: function () {\n return this._hdrEnabled;\n },\n set: function (enabled) {\n if (this._hdrEnabled === enabled) {\n return;\n }\n this._hdrEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"VLSEnabled\", {\n get: function () {\n return this._vlsEnabled;\n },\n set: function (enabled) {\n if (this._vlsEnabled === enabled) {\n return;\n }\n if (enabled) {\n var geometry = this._scene.enableGeometryBufferRenderer();\n if (!geometry) {\n BABYLON.Tools.Warn(\"Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline\");\n return;\n }\n }\n this._vlsEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"MotionBlurEnabled\", {\n get: function () {\n return this._motionBlurEnabled;\n },\n set: function (enabled) {\n if (this._motionBlurEnabled === enabled) {\n return;\n }\n this._motionBlurEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"volumetricLightStepsCount\", {\n get: function () {\n return this._volumetricLightStepsCount;\n },\n set: function (count) {\n if (this.volumetricLightPostProcess) {\n this.volumetricLightPostProcess.updateEffect(\"#define VLS\\n#define NB_STEPS \" + count.toFixed(1));\n }\n this._volumetricLightStepsCount = count;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"motionBlurSamples\", {\n get: function () {\n return this._motionBlurSamples;\n },\n set: function (samples) {\n if (this.motionBlurPostProcess) {\n this.motionBlurPostProcess.updateEffect(\"#define MOTION_BLUR\\n#define MAX_MOTION_SAMPLES \" + samples.toFixed(1));\n }\n this._motionBlurSamples = samples;\n },\n enumerable: true,\n configurable: true\n });\n StandardRenderingPipeline.prototype._buildPipeline = function () {\n var _this = this;\n var ratio = this._ratio;\n var scene = this._scene;\n this._disposePostProcesses();\n this._reset();\n // Create pass post-process\n if (!this._basePostProcess) {\n this.originalPostProcess = new BABYLON.PostProcess(\"HDRPass\", \"standard\", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", this._floatTextureType);\n this.originalPostProcess.onApply = function (effect) {\n _this._currentDepthOfFieldSource = _this.originalPostProcess;\n };\n }\n else {\n this.originalPostProcess = this._basePostProcess;\n }\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRPassPostProcess\", function () { return _this.originalPostProcess; }, true));\n this._currentDepthOfFieldSource = this.originalPostProcess;\n if (this._bloomEnabled) {\n // Create down sample X4 post-process\n this._createDownSampleX4PostProcess(scene, ratio / 2);\n // Create bright pass post-process\n this._createBrightPassPostProcess(scene, ratio / 2);\n // Create gaussian blur post-processes (down sampling blurs)\n this._createBlurPostProcesses(scene, ratio / 4, 1);\n // Create texture adder post-process\n this._createTextureAdderPostProcess(scene, ratio);\n // Create depth-of-field source post-process\n this.textureAdderFinalPostProcess = new BABYLON.PostProcess(\"HDRDepthOfFieldSource\", \"standard\", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRBaseDepthOfFieldSource\", function () { return _this.textureAdderFinalPostProcess; }, true));\n }\n if (this._vlsEnabled) {\n // Create volumetric light\n this._createVolumetricLightPostProcess(scene, ratio);\n // Create volumetric light final post-process\n this.volumetricLightFinalPostProcess = new BABYLON.PostProcess(\"HDRVLSFinal\", \"standard\", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRVLSFinal\", function () { return _this.volumetricLightFinalPostProcess; }, true));\n }\n if (this._lensFlareEnabled) {\n // Create lens flare post-process\n this._createLensFlarePostProcess(scene, ratio);\n // Create depth-of-field source post-process post lens-flare and disable it now\n this.lensFlareFinalPostProcess = new BABYLON.PostProcess(\"HDRPostLensFlareDepthOfFieldSource\", \"standard\", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRPostLensFlareDepthOfFieldSource\", function () { return _this.lensFlareFinalPostProcess; }, true));\n }\n if (this._hdrEnabled) {\n // Create luminance\n this._createLuminancePostProcesses(scene, this._floatTextureType);\n // Create HDR\n this._createHdrPostProcess(scene, ratio);\n // Create depth-of-field source post-process post hdr and disable it now\n this.hdrFinalPostProcess = new BABYLON.PostProcess(\"HDRPostHDReDepthOfFieldSource\", \"standard\", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRPostHDReDepthOfFieldSource\", function () { return _this.hdrFinalPostProcess; }, true));\n }\n if (this._depthOfFieldEnabled) {\n // Create gaussian blur used by depth-of-field\n this._createBlurPostProcesses(scene, ratio / 2, 3, \"depthOfFieldBlurWidth\");\n // Create depth-of-field post-process\n this._createDepthOfFieldPostProcess(scene, ratio);\n }\n if (this._motionBlurEnabled) {\n // Create motion blur post-process\n this._createMotionBlurPostProcess(scene, ratio);\n }\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);\n }\n };\n // Down Sample X4 Post-Processs\n StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {\n var _this = this;\n var downSampleX4Offsets = new Array(32);\n this.downSampleX4PostProcess = new BABYLON.PostProcess(\"HDRDownSampleX4\", \"standard\", [\"dsOffsets\"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define DOWN_SAMPLE_X4\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.downSampleX4PostProcess.onApply = function (effect) {\n var id = 0;\n var width = _this.downSampleX4PostProcess.width;\n var height = _this.downSampleX4PostProcess.height;\n for (var i = -2; i < 2; i++) {\n for (var j = -2; j < 2; j++) {\n downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);\n downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);\n id += 2;\n }\n }\n effect.setArray2(\"dsOffsets\", downSampleX4Offsets);\n };\n // Add to pipeline\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRDownSampleX4\", function () { return _this.downSampleX4PostProcess; }, true));\n };\n // Brightpass Post-Process\n StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {\n var _this = this;\n var brightOffsets = new Array(8);\n this.brightPassPostProcess = new BABYLON.PostProcess(\"HDRBrightPass\", \"standard\", [\"dsOffsets\", \"brightThreshold\"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define BRIGHT_PASS\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.brightPassPostProcess.onApply = function (effect) {\n var sU = (1.0 / _this.brightPassPostProcess.width);\n var sV = (1.0 / _this.brightPassPostProcess.height);\n brightOffsets[0] = -0.5 * sU;\n brightOffsets[1] = 0.5 * sV;\n brightOffsets[2] = 0.5 * sU;\n brightOffsets[3] = 0.5 * sV;\n brightOffsets[4] = -0.5 * sU;\n brightOffsets[5] = -0.5 * sV;\n brightOffsets[6] = 0.5 * sU;\n brightOffsets[7] = -0.5 * sV;\n effect.setArray2(\"dsOffsets\", brightOffsets);\n effect.setFloat(\"brightThreshold\", _this.brightThreshold);\n };\n // Add to pipeline\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRBrightPass\", function () { return _this.brightPassPostProcess; }, true));\n };\n // Create blur H&V post-processes\n StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {\n var _this = this;\n if (blurWidthKey === void 0) { blurWidthKey = \"blurWidth\"; }\n var engine = scene.getEngine();\n var blurX = new BABYLON.BlurPostProcess(\"HDRBlurH\" + \"_\" + indice, new BABYLON.Vector2(1, 0), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n var blurY = new BABYLON.BlurPostProcess(\"HDRBlurV\" + \"_\" + indice, new BABYLON.Vector2(0, 1), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n blurX.onActivateObservable.add(function () {\n var dw = blurX.width / engine.getRenderWidth();\n blurX.kernel = _this[blurWidthKey] * dw;\n });\n blurY.onActivateObservable.add(function () {\n var dw = blurY.height / engine.getRenderHeight();\n blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;\n });\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRBlurH\" + indice, function () { return blurX; }, true));\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRBlurV\" + indice, function () { return blurY; }, true));\n this.blurHPostProcesses.push(blurX);\n this.blurVPostProcesses.push(blurY);\n };\n // Create texture adder post-process\n StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {\n var _this = this;\n this.textureAdderPostProcess = new BABYLON.PostProcess(\"HDRTextureAdder\", \"standard\", [\"exposure\"], [\"otherSampler\", \"lensSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define TEXTURE_ADDER\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.textureAdderPostProcess.onApply = function (effect) {\n effect.setTextureFromPostProcess(\"otherSampler\", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);\n effect.setTexture(\"lensSampler\", _this.lensTexture);\n effect.setFloat(\"exposure\", _this.exposure);\n _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;\n };\n // Add to pipeline\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRTextureAdder\", function () { return _this.textureAdderPostProcess; }, true));\n };\n StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {\n var _this = this;\n var geometryRenderer = scene.enableGeometryBufferRenderer();\n geometryRenderer.enablePosition = true;\n var geometry = geometryRenderer.getGBuffer();\n // Base post-process\n this.volumetricLightPostProcess = new BABYLON.PostProcess(\"HDRVLS\", \"standard\", [\"shadowViewProjection\", \"cameraPosition\", \"sunDirection\", \"sunColor\", \"scatteringCoefficient\", \"scatteringPower\", \"depthValues\"], [\"shadowMapSampler\", \"positionSampler\"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define VLS\\n#define NB_STEPS \" + this._volumetricLightStepsCount.toFixed(1));\n var depthValues = BABYLON.Vector2.Zero();\n this.volumetricLightPostProcess.onApply = function (effect) {\n if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {\n var generator = _this.sourceLight.getShadowGenerator();\n effect.setTexture(\"shadowMapSampler\", generator.getShadowMap());\n effect.setTexture(\"positionSampler\", geometry.textures[2]);\n effect.setColor3(\"sunColor\", _this.sourceLight.diffuse);\n effect.setVector3(\"sunDirection\", _this.sourceLight.getShadowDirection());\n effect.setVector3(\"cameraPosition\", _this._scene.activeCamera.globalPosition);\n effect.setMatrix(\"shadowViewProjection\", generator.getTransformMatrix());\n effect.setFloat(\"scatteringCoefficient\", _this.volumetricLightCoefficient);\n effect.setFloat(\"scatteringPower\", _this.volumetricLightPower);\n depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);\n depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);\n effect.setVector2(\"depthValues\", depthValues);\n }\n };\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRVLS\", function () { return _this.volumetricLightPostProcess; }, true));\n // Smooth\n this._createBlurPostProcesses(scene, ratio / 4, 0, \"volumetricLightBlurScale\");\n // Merge\n this.volumetricLightMergePostProces = new BABYLON.PostProcess(\"HDRVLSMerge\", \"standard\", [], [\"originalSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define VLSMERGE\");\n this.volumetricLightMergePostProces.onApply = function (effect) {\n effect.setTextureFromPostProcess(\"originalSampler\", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);\n _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;\n };\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRVLSMerge\", function () { return _this.volumetricLightMergePostProces; }, true));\n };\n // Create luminance\n StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {\n var _this = this;\n // Create luminance\n var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);\n this.luminancePostProcess = new BABYLON.PostProcess(\"HDRLuminance\", \"standard\", [\"lumOffsets\"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define LUMINANCE\", textureType);\n var offsets = [];\n this.luminancePostProcess.onApply = function (effect) {\n var sU = (1.0 / _this.luminancePostProcess.width);\n var sV = (1.0 / _this.luminancePostProcess.height);\n offsets[0] = -0.5 * sU;\n offsets[1] = 0.5 * sV;\n offsets[2] = 0.5 * sU;\n offsets[3] = 0.5 * sV;\n offsets[4] = -0.5 * sU;\n offsets[5] = -0.5 * sV;\n offsets[6] = 0.5 * sU;\n offsets[7] = -0.5 * sV;\n effect.setArray2(\"lumOffsets\", offsets);\n };\n // Add to pipeline\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRLuminance\", function () { return _this.luminancePostProcess; }, true));\n // Create down sample luminance\n for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {\n var size = Math.pow(3, i);\n var defines = \"#define LUMINANCE_DOWN_SAMPLE\\n\";\n if (i === 0) {\n defines += \"#define FINAL_DOWN_SAMPLER\";\n }\n var postProcess = new BABYLON.PostProcess(\"HDRLuminanceDownSample\" + i, \"standard\", [\"dsOffsets\", \"halfDestPixelSize\"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);\n this.luminanceDownSamplePostProcesses.push(postProcess);\n }\n // Create callbacks and add effects\n var lastLuminance = this.luminancePostProcess;\n this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {\n var downSampleOffsets = new Array(18);\n pp.onApply = function (effect) {\n if (!lastLuminance) {\n return;\n }\n var id = 0;\n for (var x = -1; x < 2; x++) {\n for (var y = -1; y < 2; y++) {\n downSampleOffsets[id] = x / lastLuminance.width;\n downSampleOffsets[id + 1] = y / lastLuminance.height;\n id += 2;\n }\n }\n effect.setArray2(\"dsOffsets\", downSampleOffsets);\n effect.setFloat(\"halfDestPixelSize\", 0.5 / lastLuminance.width);\n if (index === _this.luminanceDownSamplePostProcesses.length - 1) {\n lastLuminance = _this.luminancePostProcess;\n }\n else {\n lastLuminance = pp;\n }\n };\n if (index === _this.luminanceDownSamplePostProcesses.length - 1) {\n pp.onAfterRender = function (effect) {\n var pixel = scene.getEngine().readPixels(0, 0, 1, 1);\n var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;\n };\n }\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRLuminanceDownSample\" + index, function () { return pp; }, true));\n });\n };\n // Create HDR post-process\n StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {\n var _this = this;\n this.hdrPostProcess = new BABYLON.PostProcess(\"HDR\", \"standard\", [\"averageLuminance\"], [\"textureAdderSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define HDR\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n var outputLiminance = 1;\n var time = 0;\n var lastTime = 0;\n this.hdrPostProcess.onApply = function (effect) {\n effect.setTextureFromPostProcess(\"textureAdderSampler\", _this._currentDepthOfFieldSource);\n time += scene.getEngine().getDeltaTime();\n if (outputLiminance < 0) {\n outputLiminance = _this._hdrCurrentLuminance;\n }\n else {\n var dt = (lastTime - time) / 1000.0;\n if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {\n outputLiminance += _this.hdrDecreaseRate * dt;\n }\n else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {\n outputLiminance -= _this.hdrIncreaseRate * dt;\n }\n else {\n outputLiminance = _this._hdrCurrentLuminance;\n }\n }\n outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);\n effect.setFloat(\"averageLuminance\", outputLiminance);\n lastTime = time;\n _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;\n };\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDR\", function () { return _this.hdrPostProcess; }, true));\n };\n // Create lens flare post-process\n StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {\n var _this = this;\n this.lensFlarePostProcess = new BABYLON.PostProcess(\"HDRLensFlare\", \"standard\", [\"strength\", \"ghostDispersal\", \"haloWidth\", \"resolution\", \"distortionStrength\"], [\"lensColorSampler\"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define LENS_FLARE\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRLensFlare\", function () { return _this.lensFlarePostProcess; }, true));\n this._createBlurPostProcesses(scene, ratio / 4, 2);\n this.lensFlareComposePostProcess = new BABYLON.PostProcess(\"HDRLensFlareCompose\", \"standard\", [\"lensStarMatrix\"], [\"otherSampler\", \"lensDirtSampler\", \"lensStarSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define LENS_FLARE_COMPOSE\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRLensFlareCompose\", function () { return _this.lensFlareComposePostProcess; }, true));\n var resolution = new BABYLON.Vector2(0, 0);\n // Lens flare\n this.lensFlarePostProcess.onApply = function (effect) {\n effect.setTextureFromPostProcess(\"textureSampler\", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);\n effect.setTexture(\"lensColorSampler\", _this.lensColorTexture);\n effect.setFloat(\"strength\", _this.lensFlareStrength);\n effect.setFloat(\"ghostDispersal\", _this.lensFlareGhostDispersal);\n effect.setFloat(\"haloWidth\", _this.lensFlareHaloWidth);\n // Shift\n resolution.x = _this.lensFlarePostProcess.width;\n resolution.y = _this.lensFlarePostProcess.height;\n effect.setVector2(\"resolution\", resolution);\n effect.setFloat(\"distortionStrength\", _this.lensFlareDistortionStrength);\n };\n // Compose\n var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n this.lensFlareComposePostProcess.onApply = function (effect) {\n if (!_this._scene.activeCamera) {\n return;\n }\n effect.setTextureFromPostProcess(\"otherSampler\", _this._currentDepthOfFieldSource);\n effect.setTexture(\"lensDirtSampler\", _this.lensFlareDirtTexture);\n effect.setTexture(\"lensStarSampler\", _this.lensStarTexture);\n // Lens start rotation matrix\n var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);\n var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);\n var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));\n camRot *= 4.0;\n var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);\n effect.setMatrix(\"lensStarMatrix\", lensStarMatrix);\n _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;\n };\n };\n // Create depth-of-field post-process\n StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {\n var _this = this;\n this.depthOfFieldPostProcess = new BABYLON.PostProcess(\"HDRDepthOfField\", \"standard\", [\"distance\"], [\"otherSampler\", \"depthSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define DEPTH_OF_FIELD\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.depthOfFieldPostProcess.onApply = function (effect) {\n effect.setTextureFromPostProcess(\"otherSampler\", _this._currentDepthOfFieldSource);\n effect.setTexture(\"depthSampler\", _this._getDepthTexture());\n effect.setFloat(\"distance\", _this.depthOfFieldDistance);\n };\n // Add to pipeline\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRDepthOfField\", function () { return _this.depthOfFieldPostProcess; }, true));\n };\n // Create motion blur post-process\n StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {\n var _this = this;\n this.motionBlurPostProcess = new BABYLON.PostProcess(\"HDRMotionBlur\", \"standard\", [\"inverseViewProjection\", \"prevViewProjection\", \"screenSize\", \"motionScale\", \"motionStrength\"], [\"depthSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define MOTION_BLUR\\n#define MAX_MOTION_SAMPLES \" + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n var motionScale = 0;\n var prevViewProjection = BABYLON.Matrix.Identity();\n var invViewProjection = BABYLON.Matrix.Identity();\n var viewProjection = BABYLON.Matrix.Identity();\n var screenSize = BABYLON.Vector2.Zero();\n this.motionBlurPostProcess.onApply = function (effect) {\n viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());\n viewProjection.invertToRef(invViewProjection);\n effect.setMatrix(\"inverseViewProjection\", invViewProjection);\n effect.setMatrix(\"prevViewProjection\", prevViewProjection);\n prevViewProjection = viewProjection;\n screenSize.x = _this.motionBlurPostProcess.width;\n screenSize.y = _this.motionBlurPostProcess.height;\n effect.setVector2(\"screenSize\", screenSize);\n motionScale = scene.getEngine().getFps() / 60.0;\n effect.setFloat(\"motionScale\", motionScale);\n effect.setFloat(\"motionStrength\", _this.motionStrength);\n effect.setTexture(\"depthSampler\", _this._getDepthTexture());\n };\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRMotionBlur\", function () { return _this.motionBlurPostProcess; }, true));\n };\n StandardRenderingPipeline.prototype._getDepthTexture = function () {\n if (this._scene.getEngine().getCaps().drawBuffersExtension) {\n var renderer = this._scene.enableGeometryBufferRenderer();\n return renderer.getGBuffer().textures[0];\n }\n return this._scene.enableDepthRenderer().getDepthMap();\n };\n StandardRenderingPipeline.prototype._disposePostProcesses = function () {\n for (var i = 0; i < this._cameras.length; i++) {\n var camera = this._cameras[i];\n if (this.originalPostProcess) {\n this.originalPostProcess.dispose(camera);\n }\n if (this.downSampleX4PostProcess) {\n this.downSampleX4PostProcess.dispose(camera);\n }\n if (this.brightPassPostProcess) {\n this.brightPassPostProcess.dispose(camera);\n }\n if (this.textureAdderPostProcess) {\n this.textureAdderPostProcess.dispose(camera);\n }\n if (this.textureAdderFinalPostProcess) {\n this.textureAdderFinalPostProcess.dispose(camera);\n }\n if (this.volumetricLightPostProcess) {\n this.volumetricLightPostProcess.dispose(camera);\n }\n if (this.volumetricLightSmoothXPostProcess) {\n this.volumetricLightSmoothXPostProcess.dispose(camera);\n }\n if (this.volumetricLightSmoothYPostProcess) {\n this.volumetricLightSmoothYPostProcess.dispose(camera);\n }\n if (this.volumetricLightMergePostProces) {\n this.volumetricLightMergePostProces.dispose(camera);\n }\n if (this.volumetricLightFinalPostProcess) {\n this.volumetricLightFinalPostProcess.dispose(camera);\n }\n if (this.lensFlarePostProcess) {\n this.lensFlarePostProcess.dispose(camera);\n }\n if (this.lensFlareComposePostProcess) {\n this.lensFlareComposePostProcess.dispose(camera);\n }\n for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {\n this.luminanceDownSamplePostProcesses[j].dispose(camera);\n }\n if (this.luminancePostProcess) {\n this.luminancePostProcess.dispose(camera);\n }\n if (this.hdrPostProcess) {\n this.hdrPostProcess.dispose(camera);\n }\n if (this.hdrFinalPostProcess) {\n this.hdrFinalPostProcess.dispose(camera);\n }\n if (this.depthOfFieldPostProcess) {\n this.depthOfFieldPostProcess.dispose(camera);\n }\n if (this.motionBlurPostProcess) {\n this.motionBlurPostProcess.dispose(camera);\n }\n for (var j = 0; j < this.blurHPostProcesses.length; j++) {\n this.blurHPostProcesses[j].dispose(camera);\n }\n for (var j = 0; j < this.blurVPostProcesses.length; j++) {\n this.blurVPostProcesses[j].dispose(camera);\n }\n }\n this.originalPostProcess = null;\n this.downSampleX4PostProcess = null;\n this.brightPassPostProcess = null;\n this.textureAdderPostProcess = null;\n this.textureAdderFinalPostProcess = null;\n this.volumetricLightPostProcess = null;\n this.volumetricLightSmoothXPostProcess = null;\n this.volumetricLightSmoothYPostProcess = null;\n this.volumetricLightMergePostProces = null;\n this.volumetricLightFinalPostProcess = null;\n this.lensFlarePostProcess = null;\n this.lensFlareComposePostProcess = null;\n this.luminancePostProcess = null;\n this.hdrPostProcess = null;\n this.hdrFinalPostProcess = null;\n this.depthOfFieldPostProcess = null;\n this.motionBlurPostProcess = null;\n this.luminanceDownSamplePostProcesses = [];\n this.blurHPostProcesses = [];\n this.blurVPostProcesses = [];\n };\n /**\n * Dispose of the pipeline and stop all post processes\n */\n StandardRenderingPipeline.prototype.dispose = function () {\n this._disposePostProcesses();\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n _super.prototype.dispose.call(this);\n };\n /**\n * Serialize the rendering pipeline (Used when exporting)\n * @returns the serialized object\n */\n StandardRenderingPipeline.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n if (this.sourceLight) {\n serializationObject.sourceLightId = this.sourceLight.id;\n }\n serializationObject.customType = \"StandardRenderingPipeline\";\n return serializationObject;\n };\n /**\n * Parse the serialized pipeline\n * @param source Source pipeline.\n * @param scene The scene to load the pipeline to.\n * @param rootUrl The URL of the serialized pipeline.\n * @returns An instantiated pipeline from the serialized object.\n */\n StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {\n var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);\n if (source.sourceLightId) {\n p.sourceLight = scene.getLightByID(source.sourceLightId);\n }\n return p;\n };\n // Luminance steps\n StandardRenderingPipeline.LuminanceSteps = 6;\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"brightThreshold\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"blurWidth\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"horizontalBlur\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"exposure\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"lensTexture\")\n ], StandardRenderingPipeline.prototype, \"lensTexture\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"volumetricLightCoefficient\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"volumetricLightPower\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"volumetricLightBlurScale\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"hdrMinimumLuminance\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"hdrDecreaseRate\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"hdrIncreaseRate\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"lensColorTexture\")\n ], StandardRenderingPipeline.prototype, \"lensColorTexture\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"lensFlareStrength\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"lensFlareGhostDispersal\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"lensFlareHaloWidth\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"lensFlareDistortionStrength\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"lensStarTexture\")\n ], StandardRenderingPipeline.prototype, \"lensStarTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"lensFlareDirtTexture\")\n ], StandardRenderingPipeline.prototype, \"lensFlareDirtTexture\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"depthOfFieldDistance\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"depthOfFieldBlurWidth\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"motionStrength\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"_ratio\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"BloomEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"DepthOfFieldEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"LensFlareEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"HDREnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"VLSEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"MotionBlurEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"volumetricLightStepsCount\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"motionBlurSamples\", null);\n return StandardRenderingPipeline;\n }(BABYLON.PostProcessRenderPipeline));\n BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.standardRenderingPipeline.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FxaaPostProcess = /** @class */ (function (_super) {\n __extends(FxaaPostProcess, _super);\n function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {\n if (camera === void 0) { camera = null; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n var _this = _super.call(this, name, \"fxaa\", [\"texelSize\"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, \"fxaa\", undefined, true) || this;\n var defines = _this._getDefines();\n _this.updateEffect(defines);\n _this.onApplyObservable.add(function (effect) {\n var texelSize = _this.texelSize;\n effect.setFloat2(\"texelSize\", texelSize.x, texelSize.y);\n });\n return _this;\n }\n FxaaPostProcess.prototype._getDefines = function () {\n var engine = this.getEngine();\n if (!engine) {\n return null;\n }\n var glInfo = engine.getGlInfo();\n if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf(\"mali\") > -1) {\n return \"#define MALI 1\\n\";\n }\n return null;\n };\n return FxaaPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.FxaaPostProcess = FxaaPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.fxaaPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen\n */\n var ChromaticAberrationPostProcess = /** @class */ (function (_super) {\n __extends(ChromaticAberrationPostProcess, _super);\n /**\n * Creates a new instance ChromaticAberrationPostProcess\n * @param name The name of the effect.\n * @param screenWidth The width of the screen to apply the effect on.\n * @param screenHeight The height of the screen to apply the effect on.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"chromaticAberration\", [\"chromatic_aberration\", \"screen_width\", \"screen_height\", \"direction\", \"radialIntensity\", \"centerPosition\"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;\n /**\n * The amount of seperation of rgb channels (default: 30)\n */\n _this.aberrationAmount = 30;\n /**\n * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)\n */\n _this.radialIntensity = 0;\n /**\n * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))\n */\n _this.direction = new BABYLON.Vector2(0.707, 0.707);\n /**\n * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))\n */\n _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);\n _this.onApplyObservable.add(function (effect) {\n effect.setFloat('chromatic_aberration', _this.aberrationAmount);\n effect.setFloat('screen_width', screenWidth);\n effect.setFloat('screen_height', screenHeight);\n effect.setFloat('radialIntensity', _this.radialIntensity);\n effect.setFloat2('direction', _this.direction.x, _this.direction.y);\n effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);\n });\n return _this;\n }\n return ChromaticAberrationPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The GrainPostProcess adds noise to the image at mid luminance levels\n */\n var GrainPostProcess = /** @class */ (function (_super) {\n __extends(GrainPostProcess, _super);\n /**\n * Creates a new instance of @see GrainPostProcess\n * @param name The name of the effect.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"grain\", [\"intensity\", \"animatedSeed\"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;\n /**\n * The intensity of the grain added (default: 30)\n */\n _this.intensity = 30;\n /**\n * If the grain should be randomized on every frame\n */\n _this.animated = false;\n _this.onApplyObservable.add(function (effect) {\n effect.setFloat('intensity', _this.intensity);\n effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);\n });\n return _this;\n }\n return GrainPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.GrainPostProcess = GrainPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.grainPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The SharpenPostProcess applies a sharpen kernel to every pixel\n * See http://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n var SharpenPostProcess = /** @class */ (function (_super) {\n __extends(SharpenPostProcess, _super);\n /**\n * Creates a new instance ConvolutionPostProcess\n * @param name The name of the effect.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"sharpen\", [\"sharpnessAmounts\", \"screenSize\"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;\n /**\n * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)\n */\n _this.colorAmount = 1.0;\n /**\n * How much sharpness should be applied (default: 0.3)\n */\n _this.edgeAmount = 0.3;\n _this.onApply = function (effect) {\n effect.setFloat2(\"screenSize\", _this.width, _this.height);\n effect.setFloat2(\"sharpnessAmounts\", _this.edgeAmount, _this.colorAmount);\n };\n return _this;\n }\n return SharpenPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.SharpenPostProcess = SharpenPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sharpenPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The Blur Post Process which blurs an image based on a kernel and direction.\n * Can be used twice in x and y directions to perform a guassian blur in two passes.\n */\n var BlurPostProcess = /** @class */ (function (_super) {\n __extends(BlurPostProcess, _super);\n /**\n * Creates a new instance BlurPostProcess\n * @param name The name of the effect.\n * @param direction The direction in which to blur the image.\n * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.\n * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (defines === void 0) { defines = \"\"; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"kernelBlur\", [\"delta\", \"direction\", \"cameraMinMaxZ\"], [\"circleOfConfusionSampler\"], options, camera, samplingMode, engine, reusable, null, textureType, \"kernelBlur\", { varyingCount: 0, depCount: 0 }, true) || this;\n _this.direction = direction;\n _this.blockCompilation = blockCompilation;\n _this._packedFloat = false;\n _this._staticDefines = \"\";\n _this._staticDefines = defines;\n _this.onApplyObservable.add(function (effect) {\n if (_this._outputTexture) {\n effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);\n }\n else {\n effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);\n }\n });\n _this.kernel = kernel;\n return _this;\n }\n Object.defineProperty(BlurPostProcess.prototype, \"kernel\", {\n /**\n * Gets the length in pixels of the blur sample region\n */\n get: function () {\n return this._idealKernel;\n },\n /**\n * Sets the length in pixels of the blur sample region\n */\n set: function (v) {\n if (this._idealKernel === v) {\n return;\n }\n v = Math.max(v, 1);\n this._idealKernel = v;\n this._kernel = this._nearestBestKernel(v);\n if (!this.blockCompilation) {\n this._updateParameters();\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BlurPostProcess.prototype, \"packedFloat\", {\n /**\n * Gets wether or not the blur is unpacking/repacking floats\n */\n get: function () {\n return this._packedFloat;\n },\n /**\n * Sets wether or not the blur needs to unpack/repack floats\n */\n set: function (v) {\n if (this._packedFloat === v) {\n return;\n }\n this._packedFloat = v;\n if (!this.blockCompilation) {\n this._updateParameters();\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Updates the effect with the current post process compile time values and recompiles the shader.\n * @param defines Define statements that should be added at the beginning of the shader. (default: null)\n * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)\n * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)\n * @param indexParameters The index parameters to be used for babylons include syntax \"#include[0..varyingCount]\". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx\n * @param onCompiled Called when the shader has been compiled.\n * @param onError Called if there is an error when compiling a shader.\n */\n BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {\n if (defines === void 0) { defines = null; }\n if (uniforms === void 0) { uniforms = null; }\n if (samplers === void 0) { samplers = null; }\n this._updateParameters(onCompiled, onError);\n };\n BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {\n // Generate sampling offsets and weights\n var N = this._kernel;\n var centerIndex = (N - 1) / 2;\n // Generate Gaussian sampling weights over kernel\n var offsets = [];\n var weights = [];\n var totalWeight = 0;\n for (var i = 0; i < N; i++) {\n var u = i / (N - 1);\n var w = this._gaussianWeight(u * 2.0 - 1);\n offsets[i] = (i - centerIndex);\n weights[i] = w;\n totalWeight += w;\n }\n // Normalize weights\n for (var i = 0; i < weights.length; i++) {\n weights[i] /= totalWeight;\n }\n // Optimize: combine samples to take advantage of hardware linear sampling\n // Walk from left to center, combining pairs (symmetrically)\n var linearSamplingWeights = [];\n var linearSamplingOffsets = [];\n var linearSamplingMap = [];\n for (var i = 0; i <= centerIndex; i += 2) {\n var j = Math.min(i + 1, Math.floor(centerIndex));\n var singleCenterSample = i === j;\n if (singleCenterSample) {\n linearSamplingMap.push({ o: offsets[i], w: weights[i] });\n }\n else {\n var sharedCell = j === centerIndex;\n var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));\n var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);\n if (offsetLinear === 0) {\n linearSamplingMap.push({ o: offsets[i], w: weights[i] });\n linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });\n }\n else {\n linearSamplingMap.push({ o: offsetLinear, w: weightLinear });\n linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });\n }\n }\n }\n for (var i = 0; i < linearSamplingMap.length; i++) {\n linearSamplingOffsets[i] = linearSamplingMap[i].o;\n linearSamplingWeights[i] = linearSamplingMap[i].w;\n }\n // Replace with optimized\n offsets = linearSamplingOffsets;\n weights = linearSamplingWeights;\n // Generate shaders\n var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;\n var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter\n var varyingCount = Math.min(offsets.length, freeVaryingVec2);\n var defines = \"\";\n defines += this._staticDefines;\n // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.\n if (this._staticDefines.indexOf(\"DOF\") != -1) {\n defines += \"#define CENTER_WEIGHT \" + this._glslFloat(weights[varyingCount - 1]) + \"\\r\\n\";\n varyingCount--;\n }\n for (var i = 0; i < varyingCount; i++) {\n defines += \"#define KERNEL_OFFSET\" + i + \" \" + this._glslFloat(offsets[i]) + \"\\r\\n\";\n defines += \"#define KERNEL_WEIGHT\" + i + \" \" + this._glslFloat(weights[i]) + \"\\r\\n\";\n }\n var depCount = 0;\n for (var i = freeVaryingVec2; i < offsets.length; i++) {\n defines += \"#define KERNEL_DEP_OFFSET\" + depCount + \" \" + this._glslFloat(offsets[i]) + \"\\r\\n\";\n defines += \"#define KERNEL_DEP_WEIGHT\" + depCount + \" \" + this._glslFloat(weights[i]) + \"\\r\\n\";\n depCount++;\n }\n if (this.packedFloat) {\n defines += \"#define PACKEDFLOAT 1\";\n }\n this.blockCompilation = false;\n _super.prototype.updateEffect.call(this, defines, null, null, {\n varyingCount: varyingCount,\n depCount: depCount\n }, onCompiled, onError);\n };\n /**\n * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.\n * Other odd kernels optimize correctly but require proportionally more samples, even kernels are\n * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we\n * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.\n * The gaps between physical kernels are compensated for in the weighting of the samples\n * @param idealKernel Ideal blur kernel.\n * @return Nearest best kernel.\n */\n BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {\n var v = Math.round(idealKernel);\n for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {\n var k = _a[_i];\n if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {\n return Math.max(k, 3);\n }\n }\n return Math.max(v, 3);\n };\n /**\n * Calculates the value of a Gaussian distribution with sigma 3 at a given point.\n * @param x The point on the Gaussian distribution to sample.\n * @return the value of the Gaussian function at x.\n */\n BlurPostProcess.prototype._gaussianWeight = function (x) {\n //reference: Engine/ImageProcessingBlur.cpp #dcc760\n // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],\n // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.\n // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is\n // truncated at around 1.3% of peak strength.\n //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size\n var sigma = (1 / 3);\n var denominator = Math.sqrt(2.0 * Math.PI) * sigma;\n var exponent = -((x * x) / (2.0 * sigma * sigma));\n var weight = (1.0 / denominator) * Math.exp(exponent);\n return weight;\n };\n /**\n * Generates a string that can be used as a floating point number in GLSL.\n * @param x Value to print.\n * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).\n * @return GLSL float string.\n */\n BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {\n if (decimalFigures === void 0) { decimalFigures = 8; }\n return x.toFixed(decimalFigures).replace(/0+$/, '');\n };\n return BlurPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.BlurPostProcess = BlurPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.blurPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The DepthOfFieldBlurPostProcess applied a blur in a give direction.\n * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels\n * based on samples that have a large difference in distance than the center pixel.\n * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf\n */\n var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {\n __extends(DepthOfFieldBlurPostProcess, _super);\n /**\n * Creates a new instance CircleOfConfusionPostProcess\n * @param name The name of the effect.\n * @param scene The scene the effect belongs to.\n * @param direction The direction the blur should be applied.\n * @param kernel The size of the kernel used to blur.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges\n * @param imageToBlur The image to apply the blur to (default: Current rendered frame)\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (imageToBlur === void 0) { imageToBlur = null; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, \"#define DOF 1\\r\\n\", blockCompilation) || this;\n _this.direction = direction;\n _this.onApplyObservable.add(function (effect) {\n if (imageToBlur != null) {\n effect.setTextureFromPostProcess(\"textureSampler\", imageToBlur);\n }\n effect.setTextureFromPostProcessOutput(\"circleOfConfusionSampler\", circleOfConfusion);\n if (scene.activeCamera) {\n effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);\n }\n });\n return _this;\n }\n return DepthOfFieldBlurPostProcess;\n }(BABYLON.BlurPostProcess));\n BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Options to be set when merging outputs from the default pipeline.\n */\n var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {\n function DepthOfFieldMergePostProcessOptions() {\n }\n return DepthOfFieldMergePostProcessOptions;\n }());\n BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;\n /**\n * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.\n */\n var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {\n __extends(DepthOfFieldMergePostProcess, _super);\n /**\n * Creates a new instance of DepthOfFieldMergePostProcess\n * @param name The name of the effect.\n * @param originalFromInput Post process which's input will be used for the merge.\n * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.\n * @param blurSteps Blur post processes from low to high which will be mixed with the original image.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"depthOfFieldMerge\", [], [\"circleOfConfusionSampler\", \"blurStep0\", \"blurStep1\", \"blurStep2\"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;\n _this.blurSteps = blurSteps;\n _this.onApplyObservable.add(function (effect) {\n effect.setTextureFromPostProcess(\"textureSampler\", originalFromInput);\n effect.setTextureFromPostProcessOutput(\"circleOfConfusionSampler\", circleOfConfusion);\n blurSteps.forEach(function (step, index) {\n effect.setTextureFromPostProcessOutput(\"blurStep\" + (blurSteps.length - index - 1), step);\n });\n });\n if (!blockCompilation) {\n _this.updateEffect();\n }\n return _this;\n }\n /**\n * Updates the effect with the current post process compile time values and recompiles the shader.\n * @param defines Define statements that should be added at the beginning of the shader. (default: null)\n * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)\n * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)\n * @param indexParameters The index parameters to be used for babylons include syntax \"#include[0..varyingCount]\". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx\n * @param onCompiled Called when the shader has been compiled.\n * @param onError Called if there is an error when compiling a shader.\n */\n DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {\n if (defines === void 0) { defines = null; }\n if (uniforms === void 0) { uniforms = null; }\n if (samplers === void 0) { samplers = null; }\n if (!defines) {\n defines = \"\";\n defines += \"#define BLUR_LEVEL \" + (this.blurSteps.length - 1) + \"\\n\";\n }\n _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);\n };\n return DepthOfFieldMergePostProcess;\n }(BABYLON.PostProcess));\n BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion\n */\n var CircleOfConfusionPostProcess = /** @class */ (function (_super) {\n __extends(CircleOfConfusionPostProcess, _super);\n /**\n * Creates a new instance CircleOfConfusionPostProcess\n * @param name The name of the effect.\n * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"circleOfConfusion\", [\"cameraMinMaxZ\", \"focusDistance\", \"cocPrecalculation\"], [\"depthSampler\"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;\n /**\n * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.\n */\n _this.lensSize = 50;\n /**\n * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)\n */\n _this.fStop = 1.4;\n /**\n * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)\n */\n _this.focusDistance = 2000;\n /**\n * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)\n */\n _this.focalLength = 50;\n _this._depthTexture = null;\n _this._depthTexture = depthTexture;\n _this.onApplyObservable.add(function (effect) {\n if (!_this._depthTexture) {\n BABYLON.Tools.Warn(\"No depth texture set on CircleOfConfusionPostProcess\");\n return;\n }\n effect.setTexture(\"depthSampler\", _this._depthTexture);\n // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html\n var aperture = _this.lensSize / _this.fStop;\n var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]\n effect.setFloat('focusDistance', _this.focusDistance);\n effect.setFloat('cocPrecalculation', cocPrecalculation);\n effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);\n });\n return _this;\n }\n Object.defineProperty(CircleOfConfusionPostProcess.prototype, \"depthTexture\", {\n /**\n * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.\n */\n set: function (value) {\n this._depthTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n return CircleOfConfusionPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Specifies the level of max blur that should be applied when using the depth of field effect\n */\n var DepthOfFieldEffectBlurLevel;\n (function (DepthOfFieldEffectBlurLevel) {\n /**\n * Subtle blur\n */\n DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel[\"Low\"] = 0] = \"Low\";\n /**\n * Medium blur\n */\n DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel[\"Medium\"] = 1] = \"Medium\";\n /**\n * Large blur\n */\n DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel[\"High\"] = 2] = \"High\";\n })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));\n ;\n /**\n * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.\n */\n var DepthOfFieldEffect = /** @class */ (function (_super) {\n __extends(DepthOfFieldEffect, _super);\n /**\n * Creates a new instance DepthOfFieldEffect\n * @param scene The scene the effect belongs to.\n * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.\n * @param pipelineTextureType The type of texture to be used when performing the post processing.\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {\n if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }\n if (pipelineTextureType === void 0) { pipelineTextureType = 0; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, scene.getEngine(), \"depth of field\", function () {\n return _this._effects;\n }, true) || this;\n /**\n * Internal post processes in depth of field effect\n */\n _this._effects = [];\n // Circle of confusion value for each pixel is used to determine how much to blur that pixel\n _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess(\"circleOfConfusion\", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);\n // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)\n // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts \n // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf\n _this._depthOfFieldBlurY = [];\n _this._depthOfFieldBlurX = [];\n var blurCount = 1;\n var kernelSize = 15;\n switch (blurLevel) {\n case DepthOfFieldEffectBlurLevel.High: {\n blurCount = 3;\n kernelSize = 51;\n break;\n }\n case DepthOfFieldEffectBlurLevel.Medium: {\n blurCount = 2;\n kernelSize = 31;\n break;\n }\n default: {\n kernelSize = 15;\n blurCount = 1;\n break;\n }\n }\n var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);\n var ratio = 1.0;\n for (var i = 0; i < blurCount; i++) {\n var blurY = new BABYLON.DepthOfFieldBlurPostProcess(\"verticle blur\", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);\n blurY.autoClear = false;\n ratio = 0.75 / Math.pow(2, i);\n var blurX = new BABYLON.DepthOfFieldBlurPostProcess(\"horizontal blur\", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);\n blurX.autoClear = false;\n _this._depthOfFieldBlurY.push(blurY);\n _this._depthOfFieldBlurX.push(blurX);\n }\n // Set all post processes on the effect.\n _this._effects = [_this._circleOfConfusion];\n for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {\n _this._effects.push(_this._depthOfFieldBlurY[i]);\n _this._effects.push(_this._depthOfFieldBlurX[i]);\n }\n // Merge blurred images with original image based on circleOfConfusion\n _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess(\"dofMerge\", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);\n _this._dofMerge.autoClear = false;\n _this._effects.push(_this._dofMerge);\n return _this;\n }\n Object.defineProperty(DepthOfFieldEffect.prototype, \"focalLength\", {\n get: function () {\n return this._circleOfConfusion.focalLength;\n },\n /**\n * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)\n */\n set: function (value) {\n this._circleOfConfusion.focalLength = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DepthOfFieldEffect.prototype, \"fStop\", {\n get: function () {\n return this._circleOfConfusion.fStop;\n },\n /**\n * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)\n */\n set: function (value) {\n this._circleOfConfusion.fStop = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DepthOfFieldEffect.prototype, \"focusDistance\", {\n get: function () {\n return this._circleOfConfusion.focusDistance;\n },\n /**\n * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)\n */\n set: function (value) {\n this._circleOfConfusion.focusDistance = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DepthOfFieldEffect.prototype, \"lensSize\", {\n get: function () {\n return this._circleOfConfusion.lensSize;\n },\n /**\n * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.\n */\n set: function (value) {\n this._circleOfConfusion.lensSize = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DepthOfFieldEffect.prototype, \"depthTexture\", {\n /**\n * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.\n */\n set: function (value) {\n this._circleOfConfusion.depthTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes each of the internal effects for a given camera.\n * @param camera The camera to dispose the effect on.\n */\n DepthOfFieldEffect.prototype.disposeEffects = function (camera) {\n for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {\n this._effects[effectIndex].dispose(camera);\n }\n };\n /**\n * Internal\n */\n DepthOfFieldEffect.prototype._updateEffects = function () {\n for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {\n this._effects[effectIndex].updateEffect();\n }\n };\n /**\n * Internal\n * @returns if all the contained post processes are ready.\n */\n DepthOfFieldEffect.prototype._isReady = function () {\n for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {\n if (!this._effects[effectIndex].isReady()) {\n return false;\n }\n }\n return true;\n };\n return DepthOfFieldEffect;\n }(BABYLON.PostProcessRenderEffect));\n BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.depthOfFieldEffect.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.\n */\n var BloomMergePostProcess = /** @class */ (function (_super) {\n __extends(BloomMergePostProcess, _super);\n /**\n * Creates a new instance of @see BloomMergePostProcess\n * @param name The name of the effect.\n * @param originalFromInput Post process which's input will be used for the merge.\n * @param blurred Blurred highlights post process which's output will be used.\n * @param weight Weight of the bloom to be added to the original input.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"bloomMerge\", [\"bloomWeight\"], [\"circleOfConfusionSampler\", \"blurStep0\", \"blurStep1\", \"blurStep2\", \"bloomBlur\"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;\n _this.weight = weight;\n _this.onApplyObservable.add(function (effect) {\n effect.setTextureFromPostProcess(\"textureSampler\", originalFromInput);\n effect.setTextureFromPostProcessOutput(\"bloomBlur\", blurred);\n effect.setFloat(\"bloomWeight\", _this.weight);\n });\n if (!blockCompilation) {\n _this.updateEffect();\n }\n return _this;\n }\n return BloomMergePostProcess;\n }(BABYLON.PostProcess));\n BABYLON.BloomMergePostProcess = BloomMergePostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.bloomMergePostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.\n */\n var ExtractHighlightsPostProcess = /** @class */ (function (_super) {\n __extends(ExtractHighlightsPostProcess, _super);\n function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"extractHighlights\", [\"threshold\", \"exposure\"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;\n /**\n * The luminance threshold, pixels below this value will be set to black.\n */\n _this.threshold = 0.9;\n /**\n * Internal\n */\n _this._exposure = 1;\n /**\n * Post process which has the input texture to be used when performing highlight extraction\n */\n _this._inputPostProcess = null;\n _this.onApplyObservable.add(function (effect) {\n if (_this._inputPostProcess) {\n effect.setTextureFromPostProcess(\"textureSampler\", _this._inputPostProcess);\n }\n effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));\n effect.setFloat('exposure', _this._exposure);\n });\n return _this;\n }\n return ExtractHighlightsPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras\n */\n var BloomEffect = /** @class */ (function (_super) {\n __extends(BloomEffect, _super);\n /**\n * Creates a new instance of @see BloomEffect\n * @param scene The scene the effect belongs to.\n * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.\n * @param bloomKernel The size of the kernel to be used when applying the blur.\n * @param bloomWeight The the strength of bloom.\n * @param pipelineTextureType The type of texture to be used when performing the post processing.\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {\n if (pipelineTextureType === void 0) { pipelineTextureType = 0; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, scene.getEngine(), \"bloom\", function () {\n return _this._effects;\n }, true) || this;\n _this.bloomScale = bloomScale;\n /**\n * Internal\n */\n _this._effects = [];\n _this._downscale = new BABYLON.ExtractHighlightsPostProcess(\"highlights\", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);\n _this._blurX = new BABYLON.BlurPostProcess(\"horizontal blur\", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);\n _this._blurX.alwaysForcePOT = true;\n _this._blurX.autoClear = false;\n _this._blurY = new BABYLON.BlurPostProcess(\"vertical blur\", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);\n _this._blurY.alwaysForcePOT = true;\n _this._blurY.autoClear = false;\n _this.kernel = bloomKernel;\n _this._effects = [_this._downscale, _this._blurX, _this._blurY];\n _this._merge = new BABYLON.BloomMergePostProcess(\"bloomMerge\", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);\n _this._merge.autoClear = false;\n _this._effects.push(_this._merge);\n return _this;\n }\n Object.defineProperty(BloomEffect.prototype, \"threshold\", {\n /**\n * The luminance threshold to find bright areas of the image to bloom.\n */\n get: function () {\n return this._downscale.threshold;\n },\n set: function (value) {\n this._downscale.threshold = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BloomEffect.prototype, \"weight\", {\n /**\n * The strength of the bloom.\n */\n get: function () {\n return this._merge.weight;\n },\n set: function (value) {\n this._merge.weight = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BloomEffect.prototype, \"kernel\", {\n /**\n * Specifies the size of the bloom blur kernel, relative to the final output size\n */\n get: function () {\n return this._blurX.kernel / this.bloomScale;\n },\n set: function (value) {\n this._blurX.kernel = value * this.bloomScale;\n this._blurY.kernel = value * this.bloomScale;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes each of the internal effects for a given camera.\n * @param camera The camera to dispose the effect on.\n */\n BloomEffect.prototype.disposeEffects = function (camera) {\n for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {\n this._effects[effectIndex].dispose(camera);\n }\n };\n /**\n * Internal\n */\n BloomEffect.prototype._updateEffects = function () {\n for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {\n this._effects[effectIndex].updateEffect();\n }\n };\n /**\n * Internal\n * @returns if all the contained post processes are ready.\n */\n BloomEffect.prototype._isReady = function () {\n for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {\n if (!this._effects[effectIndex].isReady()) {\n return false;\n }\n }\n return true;\n };\n return BloomEffect;\n }(BABYLON.PostProcessRenderEffect));\n BABYLON.BloomEffect = BloomEffect;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.bloomEffect.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.\n * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline\n */\n var DefaultRenderingPipeline = /** @class */ (function (_super) {\n __extends(DefaultRenderingPipeline, _super);\n /**\n * @constructor\n * @param {string} name - The rendering pipeline name (default: \"\")\n * @param {boolean} hdr - If high dynamic range textures should be used (default: true)\n * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)\n * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)\n * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)\n */\n function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {\n if (name === void 0) { name = \"\"; }\n if (hdr === void 0) { hdr = true; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (automaticBuild === void 0) { automaticBuild = true; }\n var _this = _super.call(this, scene.getEngine(), name) || this;\n _this._camerasToBeAttached = [];\n /**\n * ID of the sharpen post process,\n */\n _this.SharpenPostProcessId = \"SharpenPostProcessEffect\";\n /**\n * ID of the image processing post process;\n */\n _this.ImageProcessingPostProcessId = \"ImageProcessingPostProcessEffect\";\n /**\n * ID of the Fast Approximate Anti-Aliasing post process;\n */\n _this.FxaaPostProcessId = \"FxaaPostProcessEffect\";\n /**\n * ID of the chromatic aberration post process,\n */\n _this.ChromaticAberrationPostProcessId = \"ChromaticAberrationPostProcessEffect\";\n /**\n * ID of the grain post process\n */\n _this.GrainPostProcessId = \"GrainPostProcessEffect\";\n /**\n * Glow post process which adds a glow to emmisive areas of the image\n */\n _this._glowLayer = null;\n /**\n * Animations which can be used to tweak settings over a period of time\n */\n _this.animations = [];\n _this._imageProcessingConfigurationObserver = null;\n // Values \n _this._sharpenEnabled = false;\n _this._bloomEnabled = false;\n _this._depthOfFieldEnabled = false;\n _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;\n _this._fxaaEnabled = false;\n _this._imageProcessingEnabled = true;\n _this._bloomScale = 0.5;\n _this._chromaticAberrationEnabled = false;\n _this._grainEnabled = false;\n _this._buildAllowed = true;\n _this._resizeObserver = null;\n _this._hardwareScaleLevel = 1.0;\n _this._bloomKernel = 64;\n /**\n * Specifies the weight of the bloom in the final rendering\n */\n _this._bloomWeight = 0.15;\n /**\n * Specifies the luma threshold for the area that will be blurred by the bloom\n */\n _this._bloomThreshold = 0.9;\n _this._samples = 1;\n _this._hasCleared = false;\n _this._prevPostProcess = null;\n _this._prevPrevPostProcess = null;\n _this._cameras = cameras || scene.cameras;\n _this._camerasToBeAttached = _this._cameras.slice();\n _this._buildAllowed = automaticBuild;\n // Initialize\n _this._scene = scene;\n var caps = _this._scene.getEngine().getCaps();\n _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);\n // Misc\n if (_this._hdr) {\n if (caps.textureHalfFloatRender) {\n _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else if (caps.textureFloatRender) {\n _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n }\n else {\n _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n // Attach\n scene.postProcessRenderPipelineManager.addPipeline(_this);\n var engine = _this._scene.getEngine();\n // Create post processes before hand so they can be modified before enabled.\n // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.\n _this.sharpen = new BABYLON.SharpenPostProcess(\"sharpen\", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);\n _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);\n _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);\n _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);\n _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess(\"ChromaticAberration\", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);\n _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);\n _this.grain = new BABYLON.GrainPostProcess(\"Grain\", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);\n _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);\n _this._resizeObserver = engine.onResizeObservable.add(function () {\n _this._hardwareScaleLevel = engine.getHardwareScalingLevel();\n _this.bloomKernel = _this.bloomKernel;\n });\n _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {\n _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;\n });\n _this._buildPipeline();\n return _this;\n }\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"sharpenEnabled\", {\n get: function () {\n return this._sharpenEnabled;\n },\n /**\n * Enable or disable the sharpen process from the pipeline\n */\n set: function (enabled) {\n if (this._sharpenEnabled === enabled) {\n return;\n }\n this._sharpenEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"bloomKernel\", {\n /**\n * Specifies the size of the bloom blur kernel, relative to the final output size\n */\n get: function () {\n return this._bloomKernel;\n },\n set: function (value) {\n this._bloomKernel = value;\n this.bloom.kernel = value / this._hardwareScaleLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"bloomWeight\", {\n get: function () {\n return this._bloomWeight;\n },\n /**\n * The strength of the bloom.\n */\n set: function (value) {\n if (this._bloomWeight === value) {\n return;\n }\n this.bloom.weight = value;\n this._bloomWeight = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"bloomThreshold\", {\n get: function () {\n return this._bloomThreshold;\n },\n /**\n * The strength of the bloom.\n */\n set: function (value) {\n if (this._bloomThreshold === value) {\n return;\n }\n this.bloom.threshold = value;\n this._bloomThreshold = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"bloomScale\", {\n get: function () {\n return this._bloomScale;\n },\n /**\n * The scale of the bloom, lower value will provide better performance.\n */\n set: function (value) {\n if (this._bloomScale === value) {\n return;\n }\n this._bloomScale = value;\n // recreate bloom and dispose old as this setting is not dynamic\n this._rebuildBloom();\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"bloomEnabled\", {\n get: function () {\n return this._bloomEnabled;\n },\n /**\n * Enable or disable the bloom from the pipeline\n */\n set: function (enabled) {\n if (this._bloomEnabled === enabled) {\n return;\n }\n this._bloomEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n DefaultRenderingPipeline.prototype._rebuildBloom = function () {\n // recreate bloom and dispose old as this setting is not dynamic\n var oldBloom = this.bloom;\n this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);\n this.bloom.threshold = oldBloom.threshold;\n for (var i = 0; i < this._cameras.length; i++) {\n oldBloom.disposeEffects(this._cameras[i]);\n }\n };\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"depthOfFieldEnabled\", {\n /**\n * If the depth of field is enabled.\n */\n get: function () {\n return this._depthOfFieldEnabled;\n },\n set: function (enabled) {\n if (this._depthOfFieldEnabled === enabled) {\n return;\n }\n this._depthOfFieldEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"depthOfFieldBlurLevel\", {\n /**\n * Blur level of the depth of field effect. (Higher blur will effect performance)\n */\n get: function () {\n return this._depthOfFieldBlurLevel;\n },\n set: function (value) {\n if (this._depthOfFieldBlurLevel === value) {\n return;\n }\n this._depthOfFieldBlurLevel = value;\n // recreate dof and dispose old as this setting is not dynamic\n var oldDof = this.depthOfField;\n this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);\n this.depthOfField.focalLength = oldDof.focalLength;\n this.depthOfField.focusDistance = oldDof.focusDistance;\n this.depthOfField.fStop = oldDof.fStop;\n this.depthOfField.lensSize = oldDof.lensSize;\n for (var i = 0; i < this._cameras.length; i++) {\n oldDof.disposeEffects(this._cameras[i]);\n }\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"fxaaEnabled\", {\n get: function () {\n return this._fxaaEnabled;\n },\n /**\n * If the anti aliasing is enabled.\n */\n set: function (enabled) {\n if (this._fxaaEnabled === enabled) {\n return;\n }\n this._fxaaEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"samples\", {\n get: function () {\n return this._samples;\n },\n /**\n * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)\n */\n set: function (sampleCount) {\n if (this._samples === sampleCount) {\n return;\n }\n this._samples = sampleCount;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"imageProcessingEnabled\", {\n get: function () {\n return this._imageProcessingEnabled;\n },\n /**\n * If image processing is enabled.\n */\n set: function (enabled) {\n if (this._imageProcessingEnabled === enabled) {\n return;\n }\n this._imageProcessingEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"glowLayerEnabled\", {\n get: function () {\n return this._glowLayer == null;\n },\n /**\n * If glow layer is enabled. (Adds a glow effect to emmissive materials)\n */\n set: function (enabled) {\n if (enabled && !this._glowLayer) {\n this._glowLayer = new BABYLON.GlowLayer(\"\", this._scene);\n }\n else if (!enabled && this._glowLayer) {\n this._glowLayer.dispose();\n this._glowLayer = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"chromaticAberrationEnabled\", {\n get: function () {\n return this._chromaticAberrationEnabled;\n },\n /**\n * Enable or disable the chromaticAberration process from the pipeline\n */\n set: function (enabled) {\n if (this._chromaticAberrationEnabled === enabled) {\n return;\n }\n this._chromaticAberrationEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"grainEnabled\", {\n get: function () {\n return this._grainEnabled;\n },\n /**\n * Enable or disable the grain process from the pipeline\n */\n set: function (enabled) {\n if (this._grainEnabled === enabled) {\n return;\n }\n this._grainEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Force the compilation of the entire pipeline.\n */\n DefaultRenderingPipeline.prototype.prepare = function () {\n var previousState = this._buildAllowed;\n this._buildAllowed = true;\n this._buildPipeline();\n this._buildAllowed = previousState;\n };\n DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {\n if (skipTextureSharing === void 0) { skipTextureSharing = false; }\n if (this._hasCleared) {\n postProcess.autoClear = false;\n }\n else {\n postProcess.autoClear = true;\n this._scene.autoClear = false;\n this._hasCleared = true;\n }\n if (!skipTextureSharing) {\n if (this._prevPrevPostProcess) {\n postProcess.shareOutputWith(this._prevPrevPostProcess);\n }\n else {\n postProcess.useOwnOutput();\n }\n if (this._prevPostProcess) {\n this._prevPrevPostProcess = this._prevPostProcess;\n }\n this._prevPostProcess = postProcess;\n }\n };\n DefaultRenderingPipeline.prototype._buildPipeline = function () {\n var _this = this;\n if (!this._buildAllowed) {\n return;\n }\n this._scene.autoClear = true;\n var engine = this._scene.getEngine();\n this._disposePostProcesses();\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n // get back cameras to be used to reattach pipeline\n this._cameras = this._camerasToBeAttached.slice();\n }\n this._reset();\n this._prevPostProcess = null;\n this._prevPrevPostProcess = null;\n this._hasCleared = false;\n if (this.depthOfFieldEnabled) {\n var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();\n this.depthOfField.depthTexture = depthTexture;\n if (!this.depthOfField._isReady()) {\n this.depthOfField._updateEffects();\n }\n this.addEffect(this.depthOfField);\n this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);\n }\n if (this.bloomEnabled) {\n if (!this.bloom._isReady()) {\n this.bloom._updateEffects();\n }\n this.addEffect(this.bloom);\n this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);\n }\n if (this._imageProcessingEnabled) {\n this.imageProcessing = new BABYLON.ImageProcessingPostProcess(\"imageProcessing\", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);\n if (this._hdr) {\n this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));\n this._setAutoClearAndTextureSharing(this.imageProcessing);\n }\n else {\n this._scene.imageProcessingConfiguration.applyByPostProcess = false;\n }\n }\n if (this.sharpenEnabled) {\n if (!this.sharpen.isReady()) {\n this.sharpen.updateEffect();\n }\n this.addEffect(this._sharpenEffect);\n this._setAutoClearAndTextureSharing(this.sharpen);\n }\n if (this.grainEnabled) {\n if (!this.grain.isReady()) {\n this.grain.updateEffect();\n }\n this.addEffect(this._grainEffect);\n this._setAutoClearAndTextureSharing(this.grain);\n }\n if (this.chromaticAberrationEnabled) {\n if (!this.chromaticAberration.isReady()) {\n this.chromaticAberration.updateEffect();\n }\n this.addEffect(this._chromaticAberrationEffect);\n this._setAutoClearAndTextureSharing(this.chromaticAberration);\n }\n if (this.fxaaEnabled) {\n this.fxaa = new BABYLON.FxaaPostProcess(\"fxaa\", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);\n this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));\n this._setAutoClearAndTextureSharing(this.fxaa, true);\n }\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);\n }\n if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {\n BABYLON.Tools.Warn(\"MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0\");\n }\n };\n DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {\n if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }\n for (var i = 0; i < this._cameras.length; i++) {\n var camera = this._cameras[i];\n if (this.imageProcessing) {\n this.imageProcessing.dispose(camera);\n }\n if (this.fxaa) {\n this.fxaa.dispose(camera);\n }\n // These are created in the constructor and should not be disposed on every pipeline change\n if (disposeNonRecreated) {\n if (this.sharpen) {\n this.sharpen.dispose(camera);\n }\n if (this.depthOfField) {\n this.depthOfField.disposeEffects(camera);\n }\n if (this.bloom) {\n this.bloom.disposeEffects(camera);\n }\n if (this.chromaticAberration) {\n this.chromaticAberration.dispose(camera);\n }\n if (this.grain) {\n this.grain.dispose(camera);\n }\n if (this._glowLayer) {\n this._glowLayer.dispose();\n }\n }\n }\n this.imageProcessing = null;\n this.fxaa = null;\n if (disposeNonRecreated) {\n this.sharpen = null;\n this._sharpenEffect = null;\n this.depthOfField = null;\n this.bloom = null;\n this.chromaticAberration = null;\n this._chromaticAberrationEffect = null;\n this.grain = null;\n this._grainEffect = null;\n this._glowLayer = null;\n }\n };\n /**\n * Adds a camera to the pipeline\n * @param camera the camera to be added\n */\n DefaultRenderingPipeline.prototype.addCamera = function (camera) {\n this._camerasToBeAttached.push(camera);\n this._buildPipeline();\n };\n /**\n * Removes a camera from the pipeline\n * @param camera the camera to remove\n */\n DefaultRenderingPipeline.prototype.removeCamera = function (camera) {\n var index = this._camerasToBeAttached.indexOf(camera);\n this._camerasToBeAttached.splice(index, 1);\n this._buildPipeline();\n };\n /**\n * Dispose of the pipeline and stop all post processes\n */\n DefaultRenderingPipeline.prototype.dispose = function () {\n this._disposePostProcesses(true);\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n this._scene.autoClear = true;\n if (this._resizeObserver) {\n this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);\n this._resizeObserver = null;\n }\n this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);\n _super.prototype.dispose.call(this);\n };\n /**\n * Serialize the rendering pipeline (Used when exporting)\n * @returns the serialized object\n */\n DefaultRenderingPipeline.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"DefaultRenderingPipeline\";\n return serializationObject;\n };\n /**\n * Parse the serialized pipeline\n * @param source Source pipeline.\n * @param scene The scene to load the pipeline to.\n * @param rootUrl The URL of the serialized pipeline.\n * @returns An instantiated pipeline from the serialized object.\n */\n DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);\n };\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"sharpenEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"bloomKernel\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"_bloomWeight\", void 0);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"_bloomThreshold\", void 0);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"_hdr\", void 0);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"bloomWeight\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"bloomThreshold\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"bloomScale\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"bloomEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"depthOfFieldEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"depthOfFieldBlurLevel\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"fxaaEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"samples\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"imageProcessingEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"glowLayerEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"chromaticAberrationEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"grainEnabled\", null);\n return DefaultRenderingPipeline;\n }(BABYLON.PostProcessRenderPipeline));\n BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.defaultRenderingPipeline.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This renderer is helpfull to fill one of the render target with a geometry buffer.\n */\n var GeometryBufferRenderer = /** @class */ (function () {\n /**\n * Creates a new G Buffer for the scene\n * @param scene The scene the buffer belongs to\n * @param ratio How big is the buffer related to the main canvas.\n */\n function GeometryBufferRenderer(scene, ratio) {\n if (ratio === void 0) { ratio = 1; }\n this._enablePosition = false;\n this._scene = scene;\n this._ratio = ratio;\n // Render target\n this._createRenderTargets();\n }\n Object.defineProperty(GeometryBufferRenderer.prototype, \"renderList\", {\n /**\n * Set the render list (meshes to be rendered) used in the G buffer.\n */\n set: function (meshes) {\n this._multiRenderTarget.renderList = meshes;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeometryBufferRenderer.prototype, \"isSupported\", {\n /**\n * Gets wether or not G buffer are supported by the running hardware.\n * This requires draw buffer supports\n */\n get: function () {\n return this._multiRenderTarget.isSupported;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeometryBufferRenderer.prototype, \"enablePosition\", {\n /**\n * Gets wether or not position are enabled for the G buffer.\n */\n get: function () {\n return this._enablePosition;\n },\n /**\n * Sets wether or not position are enabled for the G buffer.\n */\n set: function (enable) {\n this._enablePosition = enable;\n this.dispose();\n this._createRenderTargets();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeometryBufferRenderer.prototype, \"scene\", {\n /**\n * Gets the scene associated with the buffer.\n */\n get: function () {\n return this._scene;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeometryBufferRenderer.prototype, \"ratio\", {\n /**\n * Gets the ratio used by the buffer during its creation.\n * How big is the buffer related to the main canvas.\n */\n get: function () {\n return this._ratio;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Checks wether everything is ready to render a submesh to the G buffer.\n * @param subMesh the submesh to check readiness for\n * @param useInstances is the mesh drawn using instance or not\n * @returns true if ready otherwise false\n */\n GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {\n var material = subMesh.getMaterial();\n if (material && material.disableDepthWrite) {\n return false;\n }\n var defines = [];\n var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];\n var mesh = subMesh.getMesh();\n // Alpha test\n if (material && material.needAlphaTesting()) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n // Buffers\n if (this._enablePosition) {\n defines.push(\"#define POSITION\");\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n // Get correct effect \n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n this._effect = this._scene.getEngine().createEffect(\"geometry\", attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\", \"view\"], [\"diffuseSampler\"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });\n }\n return this._effect.isReady();\n };\n /**\n * Gets the current underlying G Buffer.\n * @returns the buffer\n */\n GeometryBufferRenderer.prototype.getGBuffer = function () {\n return this._multiRenderTarget;\n };\n Object.defineProperty(GeometryBufferRenderer.prototype, \"samples\", {\n /**\n * Gets the number of samples used to render the buffer (anti aliasing).\n */\n get: function () {\n return this._multiRenderTarget.samples;\n },\n /**\n * Sets the number of samples used to render the buffer (anti aliasing).\n */\n set: function (value) {\n this._multiRenderTarget.samples = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes the renderer and frees up associated resources.\n */\n GeometryBufferRenderer.prototype.dispose = function () {\n this.getGBuffer().dispose();\n };\n GeometryBufferRenderer.prototype._createRenderTargets = function () {\n var _this = this;\n var engine = this._scene.getEngine();\n var count = this._enablePosition ? 3 : 2;\n this._multiRenderTarget = new BABYLON.MultiRenderTarget(\"gBuffer\", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });\n if (!this.isSupported) {\n return;\n }\n this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._multiRenderTarget.refreshRate = 1;\n this._multiRenderTarget.renderParticles = false;\n this._multiRenderTarget.renderList = null;\n // set default depth value to 1.0 (far away)\n this._multiRenderTarget.onClearObservable.add(function (engine) {\n engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);\n });\n // Custom render function\n var renderSubMesh = function (subMesh) {\n var mesh = subMesh.getRenderingMesh();\n var scene = _this._scene;\n var engine = scene.getEngine();\n var material = subMesh.getMaterial();\n if (!material) {\n return;\n }\n // Culling\n engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);\n // Managing instances\n var batch = mesh._getInstancesRenderList(subMesh._id);\n if (batch.mustReturn) {\n return;\n }\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);\n if (_this.isReady(subMesh, hardwareInstancedRendering)) {\n engine.enableEffect(_this._effect);\n mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);\n _this._effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n _this._effect.setMatrix(\"view\", scene.getViewMatrix());\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n _this._effect.setTexture(\"diffuseSampler\", alphaTexture);\n _this._effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n _this._effect.setMatrices(\"mBones\", mesh.skeleton.getTransformMatrices(mesh));\n }\n // Draw\n mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix(\"world\", world); });\n }\n };\n this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {\n var index;\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n };\n };\n return GeometryBufferRenderer;\n }());\n BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.geometryBufferRenderer.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This groups together the common properties used for image processing either in direct forward pass\n * or through post processing effect depending on the use of the image processing pipeline in your scene\n * or not.\n */\n var ImageProcessingConfiguration = /** @class */ (function () {\n function ImageProcessingConfiguration() {\n /**\n * Color curves setup used in the effect if colorCurvesEnabled is set to true\n */\n this.colorCurves = new BABYLON.ColorCurves();\n this._colorCurvesEnabled = false;\n this._colorGradingEnabled = false;\n this._colorGradingWithGreenDepth = true;\n this._colorGradingBGR = true;\n this._exposure = 1.0;\n this._toneMappingEnabled = false;\n this._contrast = 1.0;\n /**\n * Vignette stretch size.\n */\n this.vignetteStretch = 0;\n /**\n * Vignette centre X Offset.\n */\n this.vignetteCentreX = 0;\n /**\n * Vignette centre Y Offset.\n */\n this.vignetteCentreY = 0;\n /**\n * Vignette weight or intensity of the vignette effect.\n */\n this.vignetteWeight = 1.5;\n /**\n * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)\n * if vignetteEnabled is set to true.\n */\n this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);\n /**\n * Camera field of view used by the Vignette effect.\n */\n this.vignetteCameraFov = 0.5;\n this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;\n this._vignetteEnabled = false;\n this._applyByPostProcess = false;\n this._isEnabled = true;\n /**\n * An event triggered when the configuration changes and requires Shader to Update some parameters.\n */\n this.onUpdateParameters = new BABYLON.Observable();\n }\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"colorCurvesEnabled\", {\n /**\n * Gets wether the color curves effect is enabled.\n */\n get: function () {\n return this._colorCurvesEnabled;\n },\n /**\n * Sets wether the color curves effect is enabled.\n */\n set: function (value) {\n if (this._colorCurvesEnabled === value) {\n return;\n }\n this._colorCurvesEnabled = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"colorGradingEnabled\", {\n /**\n * Gets wether the color grading effect is enabled.\n */\n get: function () {\n return this._colorGradingEnabled;\n },\n /**\n * Sets wether the color grading effect is enabled.\n */\n set: function (value) {\n if (this._colorGradingEnabled === value) {\n return;\n }\n this._colorGradingEnabled = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"colorGradingWithGreenDepth\", {\n /**\n * Gets wether the color grading effect is using a green depth for the 3d Texture.\n */\n get: function () {\n return this._colorGradingWithGreenDepth;\n },\n /**\n * Sets wether the color grading effect is using a green depth for the 3d Texture.\n */\n set: function (value) {\n if (this._colorGradingWithGreenDepth === value) {\n return;\n }\n this._colorGradingWithGreenDepth = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"colorGradingBGR\", {\n /**\n * Gets wether the color grading texture contains BGR values.\n */\n get: function () {\n return this._colorGradingBGR;\n },\n /**\n * Sets wether the color grading texture contains BGR values.\n */\n set: function (value) {\n if (this._colorGradingBGR === value) {\n return;\n }\n this._colorGradingBGR = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"exposure\", {\n /**\n * Gets the Exposure used in the effect.\n */\n get: function () {\n return this._exposure;\n },\n /**\n * Sets the Exposure used in the effect.\n */\n set: function (value) {\n if (this._exposure === value) {\n return;\n }\n this._exposure = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"toneMappingEnabled\", {\n /**\n * Gets wether the tone mapping effect is enabled.\n */\n get: function () {\n return this._toneMappingEnabled;\n },\n /**\n * Sets wether the tone mapping effect is enabled.\n */\n set: function (value) {\n if (this._toneMappingEnabled === value) {\n return;\n }\n this._toneMappingEnabled = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"contrast\", {\n /**\n * Gets the contrast used in the effect.\n */\n get: function () {\n return this._contrast;\n },\n /**\n * Sets the contrast used in the effect.\n */\n set: function (value) {\n if (this._contrast === value) {\n return;\n }\n this._contrast = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"vignetteBlendMode\", {\n /**\n * Gets the vignette blend mode allowing different kind of effect.\n */\n get: function () {\n return this._vignetteBlendMode;\n },\n /**\n * Sets the vignette blend mode allowing different kind of effect.\n */\n set: function (value) {\n if (this._vignetteBlendMode === value) {\n return;\n }\n this._vignetteBlendMode = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"vignetteEnabled\", {\n /**\n * Gets wether the vignette effect is enabled.\n */\n get: function () {\n return this._vignetteEnabled;\n },\n /**\n * Sets wether the vignette effect is enabled.\n */\n set: function (value) {\n if (this._vignetteEnabled === value) {\n return;\n }\n this._vignetteEnabled = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"applyByPostProcess\", {\n /**\n * Gets wether the image processing is applied through a post process or not.\n */\n get: function () {\n return this._applyByPostProcess;\n },\n /**\n * Sets wether the image processing is applied through a post process or not.\n */\n set: function (value) {\n if (this._applyByPostProcess === value) {\n return;\n }\n this._applyByPostProcess = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"isEnabled\", {\n /**\n * Gets wether the image processing is enabled or not.\n */\n get: function () {\n return this._isEnabled;\n },\n /**\n * Sets wether the image processing is enabled or not.\n */\n set: function (value) {\n if (this._isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Method called each time the image processing information changes requires to recompile the effect.\n */\n ImageProcessingConfiguration.prototype._updateParameters = function () {\n this.onUpdateParameters.notifyObservers(this);\n };\n ImageProcessingConfiguration.prototype.getClassName = function () {\n return \"ImageProcessingConfiguration\";\n };\n /**\n * Prepare the list of uniforms associated with the Image Processing effects.\n * @param uniformsList The list of uniforms used in the effect\n * @param defines the list of defines currently in use\n */\n ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {\n if (defines.EXPOSURE) {\n uniforms.push(\"exposureLinear\");\n }\n if (defines.CONTRAST) {\n uniforms.push(\"contrast\");\n }\n if (defines.COLORGRADING) {\n uniforms.push(\"colorTransformSettings\");\n }\n if (defines.VIGNETTE) {\n uniforms.push(\"vInverseScreenSize\");\n uniforms.push(\"vignetteSettings1\");\n uniforms.push(\"vignetteSettings2\");\n }\n if (defines.COLORCURVES) {\n BABYLON.ColorCurves.PrepareUniforms(uniforms);\n }\n };\n /**\n * Prepare the list of samplers associated with the Image Processing effects.\n * @param uniformsList The list of uniforms used in the effect\n * @param defines the list of defines currently in use\n */\n ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {\n if (defines.COLORGRADING) {\n samplersList.push(\"txColorTransform\");\n }\n };\n /**\n * Prepare the list of defines associated to the shader.\n * @param defines the list of defines to complete\n */\n ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {\n if (forPostProcess === void 0) { forPostProcess = false; }\n if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {\n defines.VIGNETTE = false;\n defines.TONEMAPPING = false;\n defines.CONTRAST = false;\n defines.EXPOSURE = false;\n defines.COLORCURVES = false;\n defines.COLORGRADING = false;\n defines.COLORGRADING3D = false;\n defines.IMAGEPROCESSING = false;\n defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;\n return;\n }\n defines.VIGNETTE = this.vignetteEnabled;\n defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);\n defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;\n defines.TONEMAPPING = this.toneMappingEnabled;\n defines.CONTRAST = (this.contrast !== 1.0);\n defines.EXPOSURE = (this.exposure !== 1.0);\n defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);\n defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);\n if (defines.COLORGRADING) {\n defines.COLORGRADING3D = this.colorGradingTexture.is3D;\n }\n else {\n defines.COLORGRADING3D = false;\n }\n defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;\n defines.SAMPLER3DBGRMAP = this.colorGradingBGR;\n defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;\n defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;\n };\n /**\n * Returns true if all the image processing information are ready.\n */\n ImageProcessingConfiguration.prototype.isReady = function () {\n // Color Grading texure can not be none blocking.\n return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();\n };\n /**\n * Binds the image processing to the shader.\n * @param effect The effect to bind to\n */\n ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {\n if (aspectRatio === void 0) { aspectRatio = 1; }\n // Color Curves\n if (this._colorCurvesEnabled && this.colorCurves) {\n BABYLON.ColorCurves.Bind(this.colorCurves, effect);\n }\n // Vignette\n if (this._vignetteEnabled) {\n var inverseWidth = 1 / effect.getEngine().getRenderWidth();\n var inverseHeight = 1 / effect.getEngine().getRenderHeight();\n effect.setFloat2(\"vInverseScreenSize\", inverseWidth, inverseHeight);\n var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);\n var vignetteScaleX = vignetteScaleY * aspectRatio;\n var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);\n vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);\n vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);\n effect.setFloat4(\"vignetteSettings1\", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);\n var vignettePower = -2.0 * this.vignetteWeight;\n effect.setFloat4(\"vignetteSettings2\", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);\n }\n // Exposure\n effect.setFloat(\"exposureLinear\", this.exposure);\n // Contrast\n effect.setFloat(\"contrast\", this.contrast);\n // Color transform settings\n if (this.colorGradingTexture) {\n effect.setTexture(\"txColorTransform\", this.colorGradingTexture);\n var textureSize = this.colorGradingTexture.getSize().height;\n effect.setFloat4(\"colorTransformSettings\", (textureSize - 1) / textureSize, // textureScale\n 0.5 / textureSize, // textureOffset\n textureSize, // textureSize\n this.colorGradingTexture.level // weight\n );\n }\n };\n /**\n * Clones the current image processing instance.\n * @return The cloned image processing\n */\n ImageProcessingConfiguration.prototype.clone = function () {\n return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);\n };\n /**\n * Serializes the current image processing instance to a json representation.\n * @return a JSON representation\n */\n ImageProcessingConfiguration.prototype.serialize = function () {\n return BABYLON.SerializationHelper.Serialize(this);\n };\n /**\n * Parses the image processing from a json representation.\n * @param source the JSON source to parse\n * @return The parsed image processing\n */\n ImageProcessingConfiguration.Parse = function (source) {\n return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);\n };\n Object.defineProperty(ImageProcessingConfiguration, \"VIGNETTEMODE_MULTIPLY\", {\n /**\n * Used to apply the vignette as a mix with the pixel color.\n */\n get: function () {\n return this._VIGNETTEMODE_MULTIPLY;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration, \"VIGNETTEMODE_OPAQUE\", {\n /**\n * Used to apply the vignette as a replacement of the pixel color.\n */\n get: function () {\n return this._VIGNETTEMODE_OPAQUE;\n },\n enumerable: true,\n configurable: true\n });\n // Static constants associated to the image processing.\n ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;\n ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;\n __decorate([\n BABYLON.serializeAsColorCurves()\n ], ImageProcessingConfiguration.prototype, \"colorCurves\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_colorCurvesEnabled\", void 0);\n __decorate([\n BABYLON.serializeAsTexture()\n ], ImageProcessingConfiguration.prototype, \"colorGradingTexture\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_colorGradingEnabled\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_colorGradingWithGreenDepth\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_colorGradingBGR\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_exposure\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_toneMappingEnabled\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_contrast\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"vignetteStretch\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"vignetteCentreX\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"vignetteCentreY\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"vignetteWeight\", void 0);\n __decorate([\n BABYLON.serializeAsColor4()\n ], ImageProcessingConfiguration.prototype, \"vignetteColor\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"vignetteCameraFov\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_vignetteBlendMode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_vignetteEnabled\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_applyByPostProcess\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_isEnabled\", void 0);\n return ImageProcessingConfiguration;\n }());\n BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.imageProcessingConfiguration.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This represents a color grading texture. This acts as a lookup table LUT, useful during post process\n * It can help converting any input color in a desired output one. This can then be used to create effects\n * from sepia, black and white to sixties or futuristic rendering...\n *\n * The only supported format is currently 3dl.\n * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/\n */\n var ColorGradingTexture = /** @class */ (function (_super) {\n __extends(ColorGradingTexture, _super);\n /**\n * Instantiates a ColorGradingTexture from the following parameters.\n *\n * @param url The location of the color gradind data (currently only supporting 3dl)\n * @param scene The scene the texture will be used in\n */\n function ColorGradingTexture(url, scene) {\n var _this = _super.call(this, scene) || this;\n if (!url) {\n return _this;\n }\n _this._engine = scene.getEngine();\n _this._textureMatrix = BABYLON.Matrix.Identity();\n _this.name = url;\n _this.url = url;\n _this.hasAlpha = false;\n _this.isCube = false;\n _this.is3D = _this._engine.webGLVersion > 1;\n _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.anisotropicFilteringLevel = 1;\n _this._texture = _this._getFromCache(url, true);\n if (!_this._texture) {\n if (!scene.useDelayedTextureLoading) {\n _this.loadTexture();\n }\n else {\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n }\n }\n return _this;\n }\n /**\n * Returns the texture matrix used in most of the material.\n * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).\n */\n ColorGradingTexture.prototype.getTextureMatrix = function () {\n return this._textureMatrix;\n };\n /**\n * Occurs when the file being loaded is a .3dl LUT file.\n */\n ColorGradingTexture.prototype.load3dlTexture = function () {\n var engine = this._engine;\n var texture;\n if (engine.webGLVersion === 1) {\n texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n }\n else {\n texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n }\n this._texture = texture;\n var callback = function (text) {\n if (typeof text !== \"string\") {\n return;\n }\n var data = null;\n var tempData = null;\n var line;\n var lines = text.split('\\n');\n var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;\n var maxColor = 0;\n for (var i = 0; i < lines.length; i++) {\n line = lines[i];\n if (!ColorGradingTexture._noneEmptyLineRegex.test(line))\n continue;\n if (line.indexOf('#') === 0)\n continue;\n var words = line.split(\" \");\n if (size === 0) {\n // Number of space + one\n size = words.length;\n data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8\n tempData = new Float32Array(size * size * size * 4);\n continue;\n }\n if (size != 0) {\n var r = Math.max(parseInt(words[0]), 0);\n var g = Math.max(parseInt(words[1]), 0);\n var b = Math.max(parseInt(words[2]), 0);\n maxColor = Math.max(r, maxColor);\n maxColor = Math.max(g, maxColor);\n maxColor = Math.max(b, maxColor);\n var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;\n if (tempData) {\n tempData[pixelStorageIndex + 0] = r;\n tempData[pixelStorageIndex + 1] = g;\n tempData[pixelStorageIndex + 2] = b;\n }\n pixelIndexSlice++;\n if (pixelIndexSlice % size == 0) {\n pixelIndexH++;\n pixelIndexSlice = 0;\n if (pixelIndexH % size == 0) {\n pixelIndexW++;\n pixelIndexH = 0;\n }\n }\n }\n }\n if (tempData && data) {\n for (var i = 0; i < tempData.length; i++) {\n if (i > 0 && (i + 1) % 4 === 0) {\n data[i] = 255;\n }\n else {\n var value = tempData[i];\n data[i] = (value / maxColor * 255);\n }\n }\n }\n if (texture.is3D) {\n texture.updateSize(size, size, size);\n engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);\n }\n else {\n texture.updateSize(size * size, size);\n engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);\n }\n };\n var scene = this.getScene();\n if (scene) {\n scene._loadFile(this.url, callback);\n }\n else {\n this._engine._loadFile(this.url, callback);\n }\n return this._texture;\n };\n /**\n * Starts the loading process of the texture.\n */\n ColorGradingTexture.prototype.loadTexture = function () {\n if (this.url && this.url.toLocaleLowerCase().indexOf(\".3dl\") == (this.url.length - 4)) {\n this.load3dlTexture();\n }\n };\n /**\n * Clones the color gradind texture.\n */\n ColorGradingTexture.prototype.clone = function () {\n var newTexture = new ColorGradingTexture(this.url, this.getScene());\n // Base texture\n newTexture.level = this.level;\n return newTexture;\n };\n /**\n * Called during delayed load for textures.\n */\n ColorGradingTexture.prototype.delayLoad = function () {\n if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {\n return;\n }\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;\n this._texture = this._getFromCache(this.url, true);\n if (!this._texture) {\n this.loadTexture();\n }\n };\n /**\n * Parses a color grading texture serialized by Babylon.\n * @param parsedTexture The texture information being parsedTexture\n * @param scene The scene to load the texture in\n * @param rootUrl The root url of the data assets to load\n * @return A color gradind texture\n */\n ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {\n var texture = null;\n if (parsedTexture.name && !parsedTexture.isRenderTarget) {\n texture = new ColorGradingTexture(parsedTexture.name, scene);\n texture.name = parsedTexture.name;\n texture.level = parsedTexture.level;\n }\n return texture;\n };\n /**\n * Serializes the LUT texture to json format.\n */\n ColorGradingTexture.prototype.serialize = function () {\n if (!this.name) {\n return null;\n }\n var serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.level = this.level;\n serializationObject.customType = \"BABYLON.ColorGradingTexture\";\n return serializationObject;\n };\n /**\n * Empty line regex stored for GC.\n */\n ColorGradingTexture._noneEmptyLineRegex = /\\S+/;\n return ColorGradingTexture;\n }(BABYLON.BaseTexture));\n BABYLON.ColorGradingTexture = ColorGradingTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.colorGradingTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n var ColorCurves = /** @class */ (function () {\n function ColorCurves() {\n this._dirty = true;\n this._tempColor = new BABYLON.Color4(0, 0, 0, 0);\n this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);\n this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);\n this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);\n this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);\n this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);\n this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);\n this._globalHue = 30;\n this._globalDensity = 0;\n this._globalSaturation = 0;\n this._globalExposure = 0;\n this._highlightsHue = 30;\n this._highlightsDensity = 0;\n this._highlightsSaturation = 0;\n this._highlightsExposure = 0;\n this._midtonesHue = 30;\n this._midtonesDensity = 0;\n this._midtonesSaturation = 0;\n this._midtonesExposure = 0;\n this._shadowsHue = 30;\n this._shadowsDensity = 0;\n this._shadowsSaturation = 0;\n this._shadowsExposure = 0;\n }\n Object.defineProperty(ColorCurves.prototype, \"globalHue\", {\n /**\n * Gets the global Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get: function () {\n return this._globalHue;\n },\n /**\n * Sets the global Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set: function (value) {\n this._globalHue = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"globalDensity\", {\n /**\n * Gets the global Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get: function () {\n return this._globalDensity;\n },\n /**\n * Sets the global Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set: function (value) {\n this._globalDensity = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"globalSaturation\", {\n /**\n * Gets the global Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get: function () {\n return this._globalSaturation;\n },\n /**\n * Sets the global Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set: function (value) {\n this._globalSaturation = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"globalExposure\", {\n /**\n * Gets the global Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get: function () {\n return this._globalExposure;\n },\n /**\n * Sets the global Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set: function (value) {\n this._globalExposure = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"highlightsHue\", {\n /**\n * Gets the highlights Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get: function () {\n return this._highlightsHue;\n },\n /**\n * Sets the highlights Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set: function (value) {\n this._highlightsHue = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"highlightsDensity\", {\n /**\n * Gets the highlights Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get: function () {\n return this._highlightsDensity;\n },\n /**\n * Sets the highlights Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set: function (value) {\n this._highlightsDensity = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"highlightsSaturation\", {\n /**\n * Gets the highlights Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get: function () {\n return this._highlightsSaturation;\n },\n /**\n * Sets the highlights Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set: function (value) {\n this._highlightsSaturation = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"highlightsExposure\", {\n /**\n * Gets the highlights Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get: function () {\n return this._highlightsExposure;\n },\n /**\n * Sets the highlights Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set: function (value) {\n this._highlightsExposure = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"midtonesHue\", {\n /**\n * Gets the midtones Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get: function () {\n return this._midtonesHue;\n },\n /**\n * Sets the midtones Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set: function (value) {\n this._midtonesHue = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"midtonesDensity\", {\n /**\n * Gets the midtones Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get: function () {\n return this._midtonesDensity;\n },\n /**\n * Sets the midtones Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set: function (value) {\n this._midtonesDensity = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"midtonesSaturation\", {\n /**\n * Gets the midtones Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get: function () {\n return this._midtonesSaturation;\n },\n /**\n * Sets the midtones Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set: function (value) {\n this._midtonesSaturation = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"midtonesExposure\", {\n /**\n * Gets the midtones Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get: function () {\n return this._midtonesExposure;\n },\n /**\n * Sets the midtones Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set: function (value) {\n this._midtonesExposure = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"shadowsHue\", {\n /**\n * Gets the shadows Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get: function () {\n return this._shadowsHue;\n },\n /**\n * Sets the shadows Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set: function (value) {\n this._shadowsHue = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"shadowsDensity\", {\n /**\n * Gets the shadows Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get: function () {\n return this._shadowsDensity;\n },\n /**\n * Sets the shadows Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set: function (value) {\n this._shadowsDensity = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"shadowsSaturation\", {\n /**\n * Gets the shadows Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get: function () {\n return this._shadowsSaturation;\n },\n /**\n * Sets the shadows Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set: function (value) {\n this._shadowsSaturation = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"shadowsExposure\", {\n /**\n * Gets the shadows Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get: function () {\n return this._shadowsExposure;\n },\n /**\n * Sets the shadows Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set: function (value) {\n this._shadowsExposure = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n ColorCurves.prototype.getClassName = function () {\n return \"ColorCurves\";\n };\n /**\n * Binds the color curves to the shader.\n * @param colorCurves The color curve to bind\n * @param effect The effect to bind to\n */\n ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {\n if (positiveUniform === void 0) { positiveUniform = \"vCameraColorCurvePositive\"; }\n if (neutralUniform === void 0) { neutralUniform = \"vCameraColorCurveNeutral\"; }\n if (negativeUniform === void 0) { negativeUniform = \"vCameraColorCurveNegative\"; }\n if (colorCurves._dirty) {\n colorCurves._dirty = false;\n // Fill in global info.\n colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);\n // Compute highlights info.\n colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);\n colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);\n // Compute midtones info.\n colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);\n colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);\n // Compute shadows info.\n colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);\n colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);\n // Compute deltas (neutral is midtones).\n colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);\n colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);\n }\n if (effect) {\n effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);\n effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);\n effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);\n }\n };\n /**\n * Prepare the list of uniforms associated with the ColorCurves effects.\n * @param uniformsList The list of uniforms used in the effect\n */\n ColorCurves.PrepareUniforms = function (uniformsList) {\n uniformsList.push(\"vCameraColorCurveNeutral\", \"vCameraColorCurvePositive\", \"vCameraColorCurveNegative\");\n };\n /**\n * Returns color grading data based on a hue, density, saturation and exposure value.\n * @param filterHue The hue of the color filter.\n * @param filterDensity The density of the color filter.\n * @param saturation The saturation.\n * @param exposure The exposure.\n * @param result The result data container.\n */\n ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {\n if (hue == null) {\n return;\n }\n hue = ColorCurves.clamp(hue, 0, 360);\n density = ColorCurves.clamp(density, -100, 100);\n saturation = ColorCurves.clamp(saturation, -100, 100);\n exposure = ColorCurves.clamp(exposure, -100, 100);\n // Remap the slider/config filter density with non-linear mapping and also scale by half\n // so that the maximum filter density is only 50% control. This provides fine control \n // for small values and reasonable range.\n density = ColorCurves.applyColorGradingSliderNonlinear(density);\n density *= 0.5;\n exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);\n if (density < 0) {\n density *= -1;\n hue = (hue + 180) % 360;\n }\n ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);\n result.scaleToRef(2, result);\n result.a = 1 + 0.01 * saturation;\n };\n /**\n * Takes an input slider value and returns an adjusted value that provides extra control near the centre.\n * @param value The input slider value in range [-100,100].\n * @returns Adjusted value.\n */\n ColorCurves.applyColorGradingSliderNonlinear = function (value) {\n value /= 100;\n var x = Math.abs(value);\n x = Math.pow(x, 2);\n if (value < 0) {\n x *= -1;\n }\n x *= 100;\n return x;\n };\n /**\n * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).\n * @param hue The hue (H) input.\n * @param saturation The saturation (S) input.\n * @param brightness The brightness (B) input.\n * @result An RGBA color represented as Vector4.\n */\n ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {\n var h = ColorCurves.clamp(hue, 0, 360);\n var s = ColorCurves.clamp(saturation / 100, 0, 1);\n var v = ColorCurves.clamp(brightness / 100, 0, 1);\n if (s === 0) {\n result.r = v;\n result.g = v;\n result.b = v;\n }\n else {\n // sector 0 to 5\n h /= 60;\n var i = Math.floor(h);\n // fractional part of h\n var f = h - i;\n var p = v * (1 - s);\n var q = v * (1 - s * f);\n var t = v * (1 - s * (1 - f));\n switch (i) {\n case 0:\n result.r = v;\n result.g = t;\n result.b = p;\n break;\n case 1:\n result.r = q;\n result.g = v;\n result.b = p;\n break;\n case 2:\n result.r = p;\n result.g = v;\n result.b = t;\n break;\n case 3:\n result.r = p;\n result.g = q;\n result.b = v;\n break;\n case 4:\n result.r = t;\n result.g = p;\n result.b = v;\n break;\n default: // case 5:\n result.r = v;\n result.g = p;\n result.b = q;\n break;\n }\n }\n result.a = 1;\n };\n /**\n * Returns a value clamped between min and max\n * @param value The value to clamp\n * @param min The minimum of value\n * @param max The maximum of value\n * @returns The clamped value.\n */\n ColorCurves.clamp = function (value, min, max) {\n return Math.min(Math.max(value, min), max);\n };\n /**\n * Clones the current color curve instance.\n * @return The cloned curves\n */\n ColorCurves.prototype.clone = function () {\n return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);\n };\n /**\n * Serializes the current color curve instance to a json representation.\n * @return a JSON representation\n */\n ColorCurves.prototype.serialize = function () {\n return BABYLON.SerializationHelper.Serialize(this);\n };\n /**\n * Parses the color curve from a json representation.\n * @param source the JSON source to parse\n * @return The parsed curves\n */\n ColorCurves.Parse = function (source) {\n return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);\n };\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_globalHue\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_globalDensity\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_globalSaturation\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_globalExposure\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_highlightsHue\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_highlightsDensity\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_highlightsSaturation\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_highlightsExposure\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_midtonesHue\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_midtonesDensity\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_midtonesSaturation\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_midtonesExposure\", void 0);\n return ColorCurves;\n }());\n BABYLON.ColorCurves = ColorCurves;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.colorCurves.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var RefractionPostProcess = /** @class */ (function (_super) {\n __extends(RefractionPostProcess, _super);\n function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {\n var _this = _super.call(this, name, \"refraction\", [\"baseColor\", \"depth\", \"colorLevel\"], [\"refractionSampler\"], options, camera, samplingMode, engine, reusable) || this;\n _this.color = color;\n _this.depth = depth;\n _this.colorLevel = colorLevel;\n _this._ownRefractionTexture = true;\n _this.onActivateObservable.add(function (cam) {\n _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());\n });\n _this.onApplyObservable.add(function (effect) {\n effect.setColor3(\"baseColor\", _this.color);\n effect.setFloat(\"depth\", _this.depth);\n effect.setFloat(\"colorLevel\", _this.colorLevel);\n effect.setTexture(\"refractionSampler\", _this._refTexture);\n });\n return _this;\n }\n Object.defineProperty(RefractionPostProcess.prototype, \"refractionTexture\", {\n /**\n * Gets or sets the refraction texture\n * Please note that you are responsible for disposing the texture if you set it manually\n */\n get: function () {\n return this._refTexture;\n },\n set: function (value) {\n if (this._refTexture && this._ownRefractionTexture) {\n this._refTexture.dispose();\n }\n this._refTexture = value;\n this._ownRefractionTexture = false;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n RefractionPostProcess.prototype.dispose = function (camera) {\n if (this._refTexture && this._ownRefractionTexture) {\n this._refTexture.dispose();\n this._refTexture = null;\n }\n _super.prototype.dispose.call(this, camera);\n };\n return RefractionPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.RefractionPostProcess = RefractionPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.refractionPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var BlackAndWhitePostProcess = /** @class */ (function (_super) {\n __extends(BlackAndWhitePostProcess, _super);\n function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {\n var _this = _super.call(this, name, \"blackAndWhite\", [\"degree\"], null, options, camera, samplingMode, engine, reusable) || this;\n _this.degree = 1;\n _this.onApplyObservable.add(function (effect) {\n effect.setFloat(\"degree\", _this.degree);\n });\n return _this;\n }\n return BlackAndWhitePostProcess;\n }(BABYLON.PostProcess));\n BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the\n * input texture to perform effects such as edge detection or sharpening\n * See http://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n var ConvolutionPostProcess = /** @class */ (function (_super) {\n __extends(ConvolutionPostProcess, _super);\n /**\n * Creates a new instance ConvolutionPostProcess\n * @param name The name of the effect.\n * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n */\n function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n var _this = _super.call(this, name, \"convolution\", [\"kernel\", \"screenSize\"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;\n _this.kernel = kernel;\n _this.onApply = function (effect) {\n effect.setFloat2(\"screenSize\", _this.width, _this.height);\n effect.setArray(\"kernel\", _this.kernel);\n };\n return _this;\n }\n // Statics\n /**\n * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];\n /**\n * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];\n /**\n * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];\n /**\n * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];\n /**\n * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];\n /**\n * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];\n return ConvolutionPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.convolutionPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FilterPostProcess = /** @class */ (function (_super) {\n __extends(FilterPostProcess, _super);\n function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {\n var _this = _super.call(this, name, \"filter\", [\"kernelMatrix\"], null, options, camera, samplingMode, engine, reusable) || this;\n _this.kernelMatrix = kernelMatrix;\n _this.onApply = function (effect) {\n effect.setMatrix(\"kernelMatrix\", _this.kernelMatrix);\n };\n return _this;\n }\n return FilterPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.FilterPostProcess = FilterPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.filterPostProcess.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html\n var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {\n __extends(VolumetricLightScatteringPostProcess, _super);\n /**\n * @constructor\n * @param {string} name - The post-process name\n * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)\n * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to\n * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering\n * @param {number} samples - The post-process quality, default 100\n * @param {number} samplingMode - The post-process filtering mode\n * @param {BABYLON.Engine} engine - The babylon engine\n * @param {boolean} reusable - If the post-process is reusable\n * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If \"camera\" is null (RenderPipelineà, \"scene\" must be provided\n */\n function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {\n if (samples === void 0) { samples = 100; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }\n var _this = _super.call(this, name, \"volumetricLightScattering\", [\"decay\", \"exposure\", \"weight\", \"meshPositionOnScreen\", \"density\"], [\"lightScatteringSampler\"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, \"#define NUM_SAMPLES \" + samples) || this;\n _this._screenCoordinates = BABYLON.Vector2.Zero();\n /**\n * Custom position of the mesh. Used if \"useCustomMeshPosition\" is set to \"true\"\n */\n _this.customMeshPosition = BABYLON.Vector3.Zero();\n /**\n * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)\n */\n _this.useCustomMeshPosition = false;\n /**\n * If the post-process should inverse the light scattering direction\n */\n _this.invert = true;\n /**\n * Array containing the excluded meshes not rendered in the internal pass\n */\n _this.excludedMeshes = new Array();\n /**\n * Controls the overall intensity of the post-process\n */\n _this.exposure = 0.3;\n /**\n * Dissipates each sample's contribution in range [0, 1]\n */\n _this.decay = 0.96815;\n /**\n * Controls the overall intensity of each sample\n */\n _this.weight = 0.58767;\n /**\n * Controls the density of each sample\n */\n _this.density = 0.926;\n scene = ((camera === null) ? scene : camera.getScene()); // parameter \"scene\" can be null.\n engine = scene.getEngine();\n _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n // Configure mesh\n _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh(\"VolumetricLightScatteringMesh\", scene));\n // Configure\n _this._createPass(scene, ratio.passRatio || ratio);\n _this.onActivate = function (camera) {\n if (!_this.isSupported) {\n _this.dispose(camera);\n }\n _this.onActivate = null;\n };\n _this.onApplyObservable.add(function (effect) {\n _this._updateMeshScreenCoordinates(scene);\n effect.setTexture(\"lightScatteringSampler\", _this._volumetricLightScatteringRTT);\n effect.setFloat(\"exposure\", _this.exposure);\n effect.setFloat(\"decay\", _this.decay);\n effect.setFloat(\"weight\", _this.weight);\n effect.setFloat(\"density\", _this.density);\n effect.setVector2(\"meshPositionOnScreen\", _this._screenCoordinates);\n });\n return _this;\n }\n Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, \"useDiffuseColor\", {\n get: function () {\n BABYLON.Tools.Warn(\"VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead\");\n return false;\n },\n set: function (useDiffuseColor) {\n BABYLON.Tools.Warn(\"VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead\");\n },\n enumerable: true,\n configurable: true\n });\n VolumetricLightScatteringPostProcess.prototype.getClassName = function () {\n return \"VolumetricLightScatteringPostProcess\";\n };\n VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {\n var mesh = subMesh.getMesh();\n // Render this.mesh as default\n if (mesh === this.mesh && mesh.material) {\n return mesh.material.isReady(mesh);\n }\n var defines = [];\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n var material = subMesh.getMaterial();\n // Alpha test\n if (material) {\n if (material.needAlphaTesting()) {\n defines.push(\"#define ALPHATEST\");\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n // Get correct effect \n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: \"depth\", fragmentElement: \"volumetricLightScatteringPass\" }, attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\"], [\"diffuseSampler\"], join);\n }\n return this._volumetricLightScatteringPass.isReady();\n };\n /**\n * Sets the new light position for light scattering effect\n * @param {BABYLON.Vector3} The new custom light position\n */\n VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {\n this.customMeshPosition = position;\n };\n /**\n * Returns the light position for light scattering effect\n * @return {BABYLON.Vector3} The custom light position\n */\n VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {\n return this.customMeshPosition;\n };\n /**\n * Disposes the internal assets and detaches the post-process from the camera\n */\n VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {\n var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);\n if (rttIndex !== -1) {\n camera.getScene().customRenderTargets.splice(rttIndex, 1);\n }\n this._volumetricLightScatteringRTT.dispose();\n _super.prototype.dispose.call(this, camera);\n };\n /**\n * Returns the render target texture used by the post-process\n * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process\n */\n VolumetricLightScatteringPostProcess.prototype.getPass = function () {\n return this._volumetricLightScatteringRTT;\n };\n // Private methods\n VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {\n if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {\n return true;\n }\n return false;\n };\n VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {\n var _this = this;\n var engine = scene.getEngine();\n this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture(\"volumetricLightScatteringMap\", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._volumetricLightScatteringRTT.renderList = null;\n this._volumetricLightScatteringRTT.renderParticles = false;\n this._volumetricLightScatteringRTT.ignoreCameraViewport = true;\n var camera = this.getCamera();\n if (camera) {\n camera.customRenderTargets.push(this._volumetricLightScatteringRTT);\n }\n else {\n scene.customRenderTargets.push(this._volumetricLightScatteringRTT);\n }\n // Custom render function for submeshes\n var renderSubMesh = function (subMesh) {\n var mesh = subMesh.getRenderingMesh();\n if (_this._meshExcluded(mesh)) {\n return;\n }\n var material = subMesh.getMaterial();\n if (!material) {\n return;\n }\n var scene = mesh.getScene();\n var engine = scene.getEngine();\n // Culling\n engine.setState(material.backFaceCulling);\n // Managing instances\n var batch = mesh._getInstancesRenderList(subMesh._id);\n if (batch.mustReturn) {\n return;\n }\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);\n if (_this._isReady(subMesh, hardwareInstancedRendering)) {\n var effect = _this._volumetricLightScatteringPass;\n if (mesh === _this.mesh) {\n if (subMesh.effect) {\n effect = subMesh.effect;\n }\n else {\n effect = material.getEffect();\n }\n }\n engine.enableEffect(effect);\n mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);\n if (mesh === _this.mesh) {\n material.bind(mesh.getWorldMatrix(), mesh);\n }\n else {\n _this._volumetricLightScatteringPass.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n _this._volumetricLightScatteringPass.setTexture(\"diffuseSampler\", alphaTexture);\n if (alphaTexture) {\n _this._volumetricLightScatteringPass.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n _this._volumetricLightScatteringPass.setMatrices(\"mBones\", mesh.skeleton.getTransformMatrices(mesh));\n }\n }\n // Draw\n mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix(\"world\", world); });\n }\n };\n // Render target texture callbacks\n var savedSceneClearColor;\n var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);\n this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {\n savedSceneClearColor = scene.clearColor;\n scene.clearColor = sceneClearColor;\n });\n this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {\n scene.clearColor = savedSceneClearColor;\n });\n this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {\n var engine = scene.getEngine();\n var index;\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n if (transparentSubMeshes.length) {\n // Sort sub meshes\n for (index = 0; index < transparentSubMeshes.length; index++) {\n var submesh = transparentSubMeshes.data[index];\n var boundingInfo = submesh.getBoundingInfo();\n if (boundingInfo && scene.activeCamera) {\n submesh._alphaIndex = submesh.getMesh().alphaIndex;\n submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();\n }\n }\n var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);\n sortedArray.sort(function (a, b) {\n // Alpha index first\n if (a._alphaIndex > b._alphaIndex) {\n return 1;\n }\n if (a._alphaIndex < b._alphaIndex) {\n return -1;\n }\n // Then distance to camera\n if (a._distanceToCamera < b._distanceToCamera) {\n return 1;\n }\n if (a._distanceToCamera > b._distanceToCamera) {\n return -1;\n }\n return 0;\n });\n // Render sub meshes\n engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);\n for (index = 0; index < sortedArray.length; index++) {\n renderSubMesh(sortedArray[index]);\n }\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n }\n };\n };\n VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {\n var transform = scene.getTransformMatrix();\n var meshPosition;\n if (this.useCustomMeshPosition) {\n meshPosition = this.customMeshPosition;\n }\n else if (this.attachedNode) {\n meshPosition = this.attachedNode.position;\n }\n else {\n meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;\n }\n var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);\n this._screenCoordinates.x = pos.x / this._viewPort.width;\n this._screenCoordinates.y = pos.y / this._viewPort.height;\n if (this.invert)\n this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;\n };\n // Static methods\n /**\n * Creates a default mesh for the Volumeric Light Scattering post-process\n * @param {string} The mesh name\n * @param {BABYLON.Scene} The scene where to create the mesh\n * @return {BABYLON.Mesh} the default mesh\n */\n VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {\n var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);\n mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;\n var material = new BABYLON.StandardMaterial(name + \"Material\", scene);\n material.emissiveColor = new BABYLON.Color3(1, 1, 1);\n mesh.material = material;\n return mesh;\n };\n __decorate([\n BABYLON.serializeAsVector3()\n ], VolumetricLightScatteringPostProcess.prototype, \"customMeshPosition\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"useCustomMeshPosition\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"invert\", void 0);\n __decorate([\n BABYLON.serializeAsMeshReference()\n ], VolumetricLightScatteringPostProcess.prototype, \"mesh\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"excludedMeshes\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"exposure\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"decay\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"weight\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"density\", void 0);\n return VolumetricLightScatteringPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map\n\n//\n// This post-process allows the modification of rendered colors by using\n// a 'look-up table' (LUT). This effect is also called Color Grading.\n// \n// The object needs to be provided an url to a texture containing the color\n// look-up table: the texture must be 256 pixels wide and 16 pixels high.\n// Use an image editing software to tweak the LUT to match your needs.\n// \n// For an example of a color LUT, see here:\n// http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png\n// For explanations on color grading, see here:\n// http://udn.epicgames.com/Three/ColorGrading.html\n//\n\nvar BABYLON;\n(function (BABYLON) {\n var ColorCorrectionPostProcess = /** @class */ (function (_super) {\n __extends(ColorCorrectionPostProcess, _super);\n function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {\n var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;\n _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);\n _this._colorTableTexture.anisotropicFilteringLevel = 1;\n _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.onApply = function (effect) {\n effect.setTexture(\"colorTable\", _this._colorTableTexture);\n };\n return _this;\n }\n return ColorCorrectionPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /** Defines operator used for tonemapping */\n var TonemappingOperator;\n (function (TonemappingOperator) {\n /** Hable */\n TonemappingOperator[TonemappingOperator[\"Hable\"] = 0] = \"Hable\";\n /** Reinhard */\n TonemappingOperator[TonemappingOperator[\"Reinhard\"] = 1] = \"Reinhard\";\n /** HejiDawson */\n TonemappingOperator[TonemappingOperator[\"HejiDawson\"] = 2] = \"HejiDawson\";\n /** Photographic */\n TonemappingOperator[TonemappingOperator[\"Photographic\"] = 3] = \"Photographic\";\n })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));\n ;\n /**\n * Defines a post process to apply tone mapping\n */\n var TonemapPostProcess = /** @class */ (function (_super) {\n __extends(TonemapPostProcess, _super);\n /**\n * Creates a new TonemapPostProcess\n * @param name defines the name of the postprocess\n * @param _operator defines the operator to use\n * @param exposureAdjustment defines the required exposure adjustement\n * @param camera defines the camera to use (can be null)\n * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)\n * @param engine defines the hosting engine (can be ignore if camera is set)\n * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)\n */\n function TonemapPostProcess(name, _operator, \n /** Defines the required exposure adjustement */\n exposureAdjustment, camera, samplingMode, engine, textureFormat) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }\n if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n var _this = _super.call(this, name, \"tonemap\", [\"_ExposureAdjustment\"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;\n _this._operator = _operator;\n _this.exposureAdjustment = exposureAdjustment;\n var defines = \"#define \";\n if (_this._operator === TonemappingOperator.Hable)\n defines += \"HABLE_TONEMAPPING\";\n else if (_this._operator === TonemappingOperator.Reinhard)\n defines += \"REINHARD_TONEMAPPING\";\n else if (_this._operator === TonemappingOperator.HejiDawson)\n defines += \"OPTIMIZED_HEJIDAWSON_TONEMAPPING\";\n else if (_this._operator === TonemappingOperator.Photographic)\n defines += \"PHOTOGRAPHIC_TONEMAPPING\";\n //sadly a second call to create the effect.\n _this.updateEffect(defines);\n _this.onApply = function (effect) {\n effect.setFloat(\"_ExposureAdjustment\", _this.exposureAdjustment);\n };\n return _this;\n }\n return TonemapPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.TonemapPostProcess = TonemapPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.tonemapPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var DisplayPassPostProcess = /** @class */ (function (_super) {\n __extends(DisplayPassPostProcess, _super);\n function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {\n return _super.call(this, name, \"displayPass\", [\"passSampler\"], [\"passSampler\"], options, camera, samplingMode, engine, reusable) || this;\n }\n return DisplayPassPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.displayPassPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var HighlightsPostProcess = /** @class */ (function (_super) {\n __extends(HighlightsPostProcess, _super);\n function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n return _super.call(this, name, \"highlights\", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;\n }\n return HighlightsPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.HighlightsPostProcess = HighlightsPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.highlightsPostProcess.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ImageProcessingPostProcess = /** @class */ (function (_super) {\n __extends(ImageProcessingPostProcess, _super);\n function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {\n if (camera === void 0) { camera = null; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n var _this = _super.call(this, name, \"imageProcessing\", [], [], options, camera, samplingMode, engine, reusable, null, textureType, \"postprocess\", null, true) || this;\n _this._fromLinearSpace = true;\n /**\n * Defines cache preventing GC.\n */\n _this._defines = {\n IMAGEPROCESSING: false,\n VIGNETTE: false,\n VIGNETTEBLENDMODEMULTIPLY: false,\n VIGNETTEBLENDMODEOPAQUE: false,\n TONEMAPPING: false,\n CONTRAST: false,\n COLORCURVES: false,\n COLORGRADING: false,\n COLORGRADING3D: false,\n FROMLINEARSPACE: false,\n SAMPLER3DGREENDEPTH: false,\n SAMPLER3DBGRMAP: false,\n IMAGEPROCESSINGPOSTPROCESS: false,\n EXPOSURE: false,\n };\n // Setup the configuration as forced by the constructor. This would then not force the \n // scene materials output in linear space and let untouched the default forward pass.\n if (imageProcessingConfiguration) {\n imageProcessingConfiguration.applyByPostProcess = true;\n _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);\n // This will cause the shader to be compiled\n _this.fromLinearSpace = false;\n }\n // Setup the default processing configuration to the scene.\n else {\n _this._attachImageProcessingConfiguration(null, true);\n _this.imageProcessingConfiguration.applyByPostProcess = true;\n }\n _this.onApply = function (effect) {\n _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);\n };\n return _this;\n }\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"imageProcessingConfiguration\", {\n /**\n * Gets the image processing configuration used either in this material.\n */\n get: function () {\n return this._imageProcessingConfiguration;\n },\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set: function (value) {\n this._attachImageProcessingConfiguration(value);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Attaches a new image processing configuration to the PBR Material.\n * @param configuration\n */\n ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {\n var _this = this;\n if (doNotBuild === void 0) { doNotBuild = false; }\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n var scene = null;\n var engine = this.getEngine();\n var camera = this.getCamera();\n if (camera) {\n scene = camera.getScene();\n }\n else if (engine && engine.scenes) {\n var scenes = engine.scenes;\n scene = scenes[scenes.length - 1];\n }\n else {\n scene = BABYLON.Engine.LastCreatedScene;\n }\n this._imageProcessingConfiguration = scene.imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {\n _this._updateParameters();\n });\n }\n // Ensure the effect will be rebuilt.\n if (!doNotBuild) {\n this._updateParameters();\n }\n };\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"colorCurves\", {\n /**\n * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .\n */\n get: function () {\n return this.imageProcessingConfiguration.colorCurves;\n },\n /**\n * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorCurves = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"colorCurvesEnabled\", {\n /**\n * Gets wether the color curves effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n },\n /**\n * Sets wether the color curves effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"colorGradingTexture\", {\n /**\n * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorGradingTexture;\n },\n /**\n * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorGradingTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"colorGradingEnabled\", {\n /**\n * Gets wether the color grading effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n },\n /**\n * Gets wether the color grading effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"exposure\", {\n /**\n * Gets exposure used in the effect.\n */\n get: function () {\n return this.imageProcessingConfiguration.exposure;\n },\n /**\n * Sets exposure used in the effect.\n */\n set: function (value) {\n this.imageProcessingConfiguration.exposure = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"toneMappingEnabled\", {\n /**\n * Gets wether tonemapping is enabled or not.\n */\n get: function () {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n },\n /**\n * Sets wether tonemapping is enabled or not\n */\n set: function (value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"contrast\", {\n /**\n * Gets contrast used in the effect.\n */\n get: function () {\n return this.imageProcessingConfiguration.contrast;\n },\n /**\n * Sets contrast used in the effect.\n */\n set: function (value) {\n this.imageProcessingConfiguration.contrast = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteStretch\", {\n /**\n * Gets Vignette stretch size.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteStretch;\n },\n /**\n * Sets Vignette stretch size.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteStretch = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteCentreX\", {\n /**\n * Gets Vignette centre X Offset.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteCentreX;\n },\n /**\n * Sets Vignette centre X Offset.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteCentreX = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteCentreY\", {\n /**\n * Gets Vignette centre Y Offset.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteCentreY;\n },\n /**\n * Sets Vignette centre Y Offset.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteCentreY = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteWeight\", {\n /**\n * Gets Vignette weight or intensity of the vignette effect.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteWeight;\n },\n /**\n * Sets Vignette weight or intensity of the vignette effect.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteWeight = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteColor\", {\n /**\n * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)\n * if vignetteEnabled is set to true.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteColor;\n },\n /**\n * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)\n * if vignetteEnabled is set to true.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteColor = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteCameraFov\", {\n /**\n * Gets Camera field of view used by the Vignette effect.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteCameraFov;\n },\n /**\n * Sets Camera field of view used by the Vignette effect.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteCameraFov = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteBlendMode\", {\n /**\n * Gets the vignette blend mode allowing different kind of effect.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteBlendMode;\n },\n /**\n * Sets the vignette blend mode allowing different kind of effect.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteBlendMode = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteEnabled\", {\n /**\n * Gets wether the vignette effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteEnabled;\n },\n /**\n * Sets wether the vignette effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"fromLinearSpace\", {\n /**\n * Gets wether the input of the processing is in Gamma or Linear Space.\n */\n get: function () {\n return this._fromLinearSpace;\n },\n /**\n * Sets wether the input of the processing is in Gamma or Linear Space.\n */\n set: function (value) {\n if (this._fromLinearSpace === value) {\n return;\n }\n this._fromLinearSpace = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n ImageProcessingPostProcess.prototype.getClassName = function () {\n return \"ImageProcessingPostProcess\";\n };\n ImageProcessingPostProcess.prototype._updateParameters = function () {\n this._defines.FROMLINEARSPACE = this._fromLinearSpace;\n this.imageProcessingConfiguration.prepareDefines(this._defines, true);\n var defines = \"\";\n for (var define in this._defines) {\n if (this._defines[define]) {\n defines += \"#define \" + define + \";\\r\\n\";\n }\n }\n var samplers = [\"textureSampler\"];\n var uniforms = [\"scale\"];\n if (BABYLON.ImageProcessingConfiguration) {\n BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);\n BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);\n }\n this.updateEffect(defines, uniforms, samplers);\n };\n ImageProcessingPostProcess.prototype.dispose = function (camera) {\n _super.prototype.dispose.call(this, camera);\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n if (this._imageProcessingConfiguration) {\n this.imageProcessingConfiguration.applyByPostProcess = false;\n }\n };\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingPostProcess.prototype, \"_fromLinearSpace\", void 0);\n return ImageProcessingPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.imageProcessingPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to store bone information\n * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons\n */\n var Bone = /** @class */ (function (_super) {\n __extends(Bone, _super);\n /**\n * Create a new bone\n * @param name defines the bone name\n * @param skeleton defines the parent skeleton\n * @param parentBone defines the parent (can be null if the bone is the root)\n * @param localMatrix defines the local matrix\n * @param restPose defines the rest pose matrix\n * @param baseMatrix defines the base matrix\n * @param index defines index of the bone in the hiearchy\n */\n function Bone(\n /**\n * defines the bone name\n */\n name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {\n if (parentBone === void 0) { parentBone = null; }\n if (localMatrix === void 0) { localMatrix = null; }\n if (restPose === void 0) { restPose = null; }\n if (baseMatrix === void 0) { baseMatrix = null; }\n if (index === void 0) { index = null; }\n var _this = _super.call(this, name, skeleton.getScene()) || this;\n _this.name = name;\n /**\n * Gets the list of child bones\n */\n _this.children = new Array();\n /** Gets the animations associated with this bone */\n _this.animations = new Array();\n /**\n * @hidden Internal only\n * Set this value to map this bone to a different index in the transform matrices\n * Set this value to -1 to exclude the bone from the transform matrices\n */\n _this._index = null;\n _this._absoluteTransform = new BABYLON.Matrix();\n _this._invertedAbsoluteTransform = new BABYLON.Matrix();\n _this._scalingDeterminant = 1;\n _this._worldTransform = new BABYLON.Matrix();\n _this._needToDecompose = true;\n _this._needToCompose = false;\n _this._skeleton = skeleton;\n _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();\n _this._restPose = restPose ? restPose : _this._localMatrix.clone();\n _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();\n _this._index = index;\n skeleton.bones.push(_this);\n _this.setParent(parentBone, false);\n if (baseMatrix || localMatrix) {\n _this._updateDifferenceMatrix();\n }\n return _this;\n }\n Object.defineProperty(Bone.prototype, \"_matrix\", {\n /** @hidden */\n get: function () {\n this._compose();\n return this._localMatrix;\n },\n /** @hidden */\n set: function (value) {\n this._localMatrix.copyFrom(value);\n this._needToDecompose = true;\n },\n enumerable: true,\n configurable: true\n });\n // Members\n /**\n * Gets the parent skeleton\n * @returns a skeleton\n */\n Bone.prototype.getSkeleton = function () {\n return this._skeleton;\n };\n /**\n * Gets parent bone\n * @returns a bone or null if the bone is the root of the bone hierarchy\n */\n Bone.prototype.getParent = function () {\n return this._parent;\n };\n /**\n * Sets the parent bone\n * @param parent defines the parent (can be null if the bone is the root)\n * @param updateDifferenceMatrix defines if the difference matrix must be updated\n */\n Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {\n if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }\n if (this._parent === parent) {\n return;\n }\n if (this._parent) {\n var index = this._parent.children.indexOf(this);\n if (index !== -1) {\n this._parent.children.splice(index, 1);\n }\n }\n this._parent = parent;\n if (this._parent) {\n this._parent.children.push(this);\n }\n if (updateDifferenceMatrix) {\n this._updateDifferenceMatrix();\n }\n this.markAsDirty();\n };\n /**\n * Gets the local matrix\n * @returns a matrix\n */\n Bone.prototype.getLocalMatrix = function () {\n this._compose();\n return this._localMatrix;\n };\n /**\n * Gets the base matrix (initial matrix which remains unchanged)\n * @returns a matrix\n */\n Bone.prototype.getBaseMatrix = function () {\n return this._baseMatrix;\n };\n /**\n * Gets the rest pose matrix\n * @returns a matrix\n */\n Bone.prototype.getRestPose = function () {\n return this._restPose;\n };\n /**\n * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)\n */\n Bone.prototype.getWorldMatrix = function () {\n return this._worldTransform;\n };\n /**\n * Sets the local matrix to rest pose matrix\n */\n Bone.prototype.returnToRest = function () {\n this.updateMatrix(this._restPose.clone());\n };\n /**\n * Gets the inverse of the absolute transform matrix.\n * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)\n * @returns a matrix\n */\n Bone.prototype.getInvertedAbsoluteTransform = function () {\n return this._invertedAbsoluteTransform;\n };\n /**\n * Gets the absolute transform matrix (ie base matrix * parent world matrix)\n * @returns a matrix\n */\n Bone.prototype.getAbsoluteTransform = function () {\n return this._absoluteTransform;\n };\n Object.defineProperty(Bone.prototype, \"position\", {\n // Properties (matches AbstractMesh properties)\n /** Gets or sets current position (in local space) */\n get: function () {\n this._decompose();\n return this._localPosition;\n },\n set: function (newPosition) {\n this._decompose();\n this._localPosition.copyFrom(newPosition);\n this._markAsDirtyAndCompose();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Bone.prototype, \"rotation\", {\n /** Gets or sets current rotation (in local space) */\n get: function () {\n return this.getRotation();\n },\n set: function (newRotation) {\n this.setRotation(newRotation);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Bone.prototype, \"rotationQuaternion\", {\n /** Gets or sets current rotation quaternion (in local space) */\n get: function () {\n this._decompose();\n return this._localRotation;\n },\n set: function (newRotation) {\n this.setRotationQuaternion(newRotation);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Bone.prototype, \"scaling\", {\n /** Gets or sets current scaling (in local space) */\n get: function () {\n return this.getScale();\n },\n set: function (newScaling) {\n this.setScale(newScaling);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Bone.prototype, \"animationPropertiesOverride\", {\n /**\n * Gets the animation properties override\n */\n get: function () {\n return this._skeleton.animationPropertiesOverride;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n Bone.prototype._decompose = function () {\n if (!this._needToDecompose) {\n return;\n }\n this._needToDecompose = false;\n if (!this._localScaling) {\n this._localScaling = BABYLON.Vector3.Zero();\n this._localRotation = BABYLON.Quaternion.Zero();\n this._localPosition = BABYLON.Vector3.Zero();\n }\n this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);\n };\n Bone.prototype._compose = function () {\n if (!this._needToCompose) {\n return;\n }\n this._needToCompose = false;\n BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);\n };\n /**\n * Update the base and local matrices\n * @param matrix defines the new base or local matrix\n * @param updateDifferenceMatrix defines if the difference matrix must be updated\n * @param updateLocalMatrix defines if the local matrix should be updated\n */\n Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {\n if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }\n if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }\n this._baseMatrix.copyFrom(matrix);\n if (updateDifferenceMatrix) {\n this._updateDifferenceMatrix();\n }\n if (updateLocalMatrix) {\n this._localMatrix.copyFrom(matrix);\n this._markAsDirtyAndDecompose();\n }\n else {\n this.markAsDirty();\n }\n };\n /** @hidden */\n Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {\n if (updateChildren === void 0) { updateChildren = true; }\n if (!rootMatrix) {\n rootMatrix = this._baseMatrix;\n }\n if (this._parent) {\n rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);\n }\n else {\n this._absoluteTransform.copyFrom(rootMatrix);\n }\n this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);\n if (updateChildren) {\n for (var index = 0; index < this.children.length; index++) {\n this.children[index]._updateDifferenceMatrix();\n }\n }\n this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);\n };\n /**\n * Flag the bone as dirty (Forcing it to update everything)\n */\n Bone.prototype.markAsDirty = function () {\n this._currentRenderId++;\n this._childRenderId++;\n this._skeleton._markAsDirty();\n };\n Bone.prototype._markAsDirtyAndCompose = function () {\n this.markAsDirty();\n this._needToCompose = true;\n };\n Bone.prototype._markAsDirtyAndDecompose = function () {\n this.markAsDirty();\n this._needToDecompose = true;\n };\n /**\n * Copy an animation range from another bone\n * @param source defines the source bone\n * @param rangeName defines the range name to copy\n * @param frameOffset defines the frame offset\n * @param rescaleAsRequired defines if rescaling must be applied if required\n * @param skelDimensionsRatio defines the scaling ratio\n * @returns true if operation was successful\n */\n Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {\n if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }\n if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }\n // all animation may be coming from a library skeleton, so may need to create animation\n if (this.animations.length === 0) {\n this.animations.push(new BABYLON.Animation(this.name, \"_matrix\", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));\n this.animations[0].setKeys([]);\n }\n // get animation info / verify there is such a range from the source bone\n var sourceRange = source.animations[0].getRange(rangeName);\n if (!sourceRange) {\n return false;\n }\n var from = sourceRange.from;\n var to = sourceRange.to;\n var sourceKeys = source.animations[0].getKeys();\n // rescaling prep\n var sourceBoneLength = source.length;\n var sourceParent = source.getParent();\n var parent = this.getParent();\n var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;\n var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;\n var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);\n var destKeys = this.animations[0].getKeys();\n // loop vars declaration\n var orig;\n var origTranslation;\n var mat;\n for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {\n orig = sourceKeys[key];\n if (orig.frame >= from && orig.frame <= to) {\n if (rescaleAsRequired) {\n mat = orig.value.clone();\n // scale based on parent ratio, when bone has parent\n if (parentScalingReqd) {\n origTranslation = mat.getTranslation();\n mat.setTranslation(origTranslation.scaleInPlace(parentRatio));\n // scale based on skeleton dimension ratio when root bone, and value is passed\n }\n else if (dimensionsScalingReqd && skelDimensionsRatio) {\n origTranslation = mat.getTranslation();\n mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));\n // use original when root bone, and no data for skelDimensionsRatio\n }\n else {\n mat = orig.value;\n }\n }\n else {\n mat = orig.value;\n }\n destKeys.push({ frame: orig.frame + frameOffset, value: mat });\n }\n }\n this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);\n return true;\n };\n /**\n * Translate the bone in local or world space\n * @param vec The amount to translate the bone\n * @param space The space that the translation is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.translate = function (vec, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n var lm = this.getLocalMatrix();\n if (space == BABYLON.Space.LOCAL) {\n lm.m[12] += vec.x;\n lm.m[13] += vec.y;\n lm.m[14] += vec.z;\n }\n else {\n var wm = null;\n //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()\n if (mesh) {\n wm = mesh.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteTransforms();\n var tmat = Bone._tmpMats[0];\n var tvec = Bone._tmpVecs[0];\n if (this._parent) {\n if (mesh && wm) {\n tmat.copyFrom(this._parent.getAbsoluteTransform());\n tmat.multiplyToRef(wm, tmat);\n }\n else {\n tmat.copyFrom(this._parent.getAbsoluteTransform());\n }\n }\n tmat.m[12] = 0;\n tmat.m[13] = 0;\n tmat.m[14] = 0;\n tmat.invert();\n BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);\n lm.m[12] += tvec.x;\n lm.m[13] += tvec.y;\n lm.m[14] += tvec.z;\n }\n this._markAsDirtyAndDecompose();\n };\n /**\n * Set the postion of the bone in local or world space\n * @param position The position to set the bone\n * @param space The space that the position is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.setPosition = function (position, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n var lm = this.getLocalMatrix();\n if (space == BABYLON.Space.LOCAL) {\n lm.m[12] = position.x;\n lm.m[13] = position.y;\n lm.m[14] = position.z;\n }\n else {\n var wm = null;\n //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()\n if (mesh) {\n wm = mesh.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteTransforms();\n var tmat = Bone._tmpMats[0];\n var vec = Bone._tmpVecs[0];\n if (this._parent) {\n if (mesh && wm) {\n tmat.copyFrom(this._parent.getAbsoluteTransform());\n tmat.multiplyToRef(wm, tmat);\n }\n else {\n tmat.copyFrom(this._parent.getAbsoluteTransform());\n }\n }\n tmat.invert();\n BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);\n lm.m[12] = vec.x;\n lm.m[13] = vec.y;\n lm.m[14] = vec.z;\n }\n this._markAsDirtyAndDecompose();\n };\n /**\n * Set the absolute position of the bone (world space)\n * @param position The position to set the bone\n * @param mesh The mesh that this bone is attached to\n */\n Bone.prototype.setAbsolutePosition = function (position, mesh) {\n this.setPosition(position, BABYLON.Space.WORLD, mesh);\n };\n /**\n * Scale the bone on the x, y and z axes (in local space)\n * @param x The amount to scale the bone on the x axis\n * @param y The amount to scale the bone on the y axis\n * @param z The amount to scale the bone on the z axis\n * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)\n */\n Bone.prototype.scale = function (x, y, z, scaleChildren) {\n if (scaleChildren === void 0) { scaleChildren = false; }\n var locMat = this.getLocalMatrix();\n // Apply new scaling on top of current local matrix\n var scaleMat = Bone._tmpMats[0];\n BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);\n scaleMat.multiplyToRef(locMat, locMat);\n // Invert scaling matrix and apply the inverse to all children\n scaleMat.invert();\n for (var _i = 0, _a = this.children; _i < _a.length; _i++) {\n var child = _a[_i];\n var cm = child.getLocalMatrix();\n cm.multiplyToRef(scaleMat, cm);\n cm.m[12] *= x;\n cm.m[13] *= y;\n cm.m[14] *= z;\n child._markAsDirtyAndDecompose();\n }\n this._markAsDirtyAndDecompose();\n if (scaleChildren) {\n for (var _b = 0, _c = this.children; _b < _c.length; _b++) {\n var child = _c[_b];\n child.scale(x, y, z, scaleChildren);\n }\n }\n };\n /**\n * Set the bone scaling in local space\n * @param scale defines the scaling vector\n */\n Bone.prototype.setScale = function (scale) {\n this._decompose();\n this._localScaling.copyFrom(scale);\n this._markAsDirtyAndCompose();\n };\n /**\n * Gets the current scaling in local space\n * @returns the current scaling vector\n */\n Bone.prototype.getScale = function () {\n this._decompose();\n return this._localScaling;\n };\n /**\n * Gets the current scaling in local space and stores it in a target vector\n * @param result defines the target vector\n */\n Bone.prototype.getScaleToRef = function (result) {\n this._decompose();\n result.copyFrom(this._localScaling);\n };\n /**\n * Set the yaw, pitch, and roll of the bone in local or world space\n * @param yaw The rotation of the bone on the y axis\n * @param pitch The rotation of the bone on the x axis\n * @param roll The rotation of the bone on the z axis\n * @param space The space that the axes of rotation are in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (space === BABYLON.Space.LOCAL) {\n var quat = Bone._tmpQuat;\n BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);\n this.setRotationQuaternion(quat, space, mesh);\n return;\n }\n var rotMatInv = Bone._tmpMats[0];\n if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {\n return;\n }\n var rotMat = Bone._tmpMats[1];\n BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat);\n this._rotateWithMatrix(rotMat, space, mesh);\n };\n /**\n * Add a rotation to the bone on an axis in local or world space\n * @param axis The axis to rotate the bone on\n * @param amount The amount to rotate the bone\n * @param space The space that the axis is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.rotate = function (axis, amount, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n var rmat = Bone._tmpMats[0];\n rmat.m[12] = 0;\n rmat.m[13] = 0;\n rmat.m[14] = 0;\n BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);\n this._rotateWithMatrix(rmat, space, mesh);\n };\n /**\n * Set the rotation of the bone to a particular axis angle in local or world space\n * @param axis The axis to rotate the bone on\n * @param angle The angle that the bone should be rotated to\n * @param space The space that the axis is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (space === BABYLON.Space.LOCAL) {\n var quat = Bone._tmpQuat;\n BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);\n this.setRotationQuaternion(quat, space, mesh);\n return;\n }\n var rotMatInv = Bone._tmpMats[0];\n if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {\n return;\n }\n var rotMat = Bone._tmpMats[1];\n BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat);\n this._rotateWithMatrix(rotMat, space, mesh);\n };\n /**\n * Set the euler rotation of the bone in local of world space\n * @param rotation The euler rotation that the bone should be set to\n * @param space The space that the rotation is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.setRotation = function (rotation, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);\n };\n /**\n * Set the quaternion rotation of the bone in local of world space\n * @param quat The quaternion rotation that the bone should be set to\n * @param space The space that the rotation is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (space === BABYLON.Space.LOCAL) {\n this._decompose();\n this._localRotation.copyFrom(quat);\n this._markAsDirtyAndCompose();\n return;\n }\n var rotMatInv = Bone._tmpMats[0];\n if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {\n return;\n }\n var rotMat = Bone._tmpMats[1];\n BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat);\n this._rotateWithMatrix(rotMat, space, mesh);\n };\n /**\n * Set the rotation matrix of the bone in local of world space\n * @param rotMat The rotation matrix that the bone should be set to\n * @param space The space that the rotation is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (space === BABYLON.Space.LOCAL) {\n var quat = Bone._tmpQuat;\n BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);\n this.setRotationQuaternion(quat, space, mesh);\n return;\n }\n var rotMatInv = Bone._tmpMats[0];\n if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {\n return;\n }\n var rotMat2 = Bone._tmpMats[1];\n rotMat2.copyFrom(rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat2);\n this._rotateWithMatrix(rotMat2, space, mesh);\n };\n Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n var lmat = this.getLocalMatrix();\n var lx = lmat.m[12];\n var ly = lmat.m[13];\n var lz = lmat.m[14];\n var parent = this.getParent();\n var parentScale = Bone._tmpMats[3];\n var parentScaleInv = Bone._tmpMats[4];\n if (parent && space == BABYLON.Space.WORLD) {\n if (mesh) {\n parentScale.copyFrom(mesh.getWorldMatrix());\n parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);\n }\n else {\n parentScale.copyFrom(parent.getAbsoluteTransform());\n }\n parentScaleInv.copyFrom(parentScale);\n parentScaleInv.invert();\n lmat.multiplyToRef(parentScale, lmat);\n lmat.multiplyToRef(rmat, lmat);\n lmat.multiplyToRef(parentScaleInv, lmat);\n }\n else {\n if (space == BABYLON.Space.WORLD && mesh) {\n parentScale.copyFrom(mesh.getWorldMatrix());\n parentScaleInv.copyFrom(parentScale);\n parentScaleInv.invert();\n lmat.multiplyToRef(parentScale, lmat);\n lmat.multiplyToRef(rmat, lmat);\n lmat.multiplyToRef(parentScaleInv, lmat);\n }\n else {\n lmat.multiplyToRef(rmat, lmat);\n }\n }\n lmat.m[12] = lx;\n lmat.m[13] = ly;\n lmat.m[14] = lz;\n this.computeAbsoluteTransforms();\n this._markAsDirtyAndDecompose();\n };\n Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {\n var scaleMatrix = Bone._tmpMats[2];\n rotMatInv.copyFrom(this.getAbsoluteTransform());\n if (mesh) {\n rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);\n BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);\n }\n rotMatInv.invert();\n if (isNaN(rotMatInv.m[0])) {\n // Matrix failed to invert.\n // This can happen if scale is zero for example.\n return false;\n }\n scaleMatrix.m[0] *= this._scalingDeterminant;\n rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);\n return true;\n };\n /**\n * Get the position of the bone in local or world space\n * @param space The space that the returned position is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @returns The position of the bone\n */\n Bone.prototype.getPosition = function (space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (mesh === void 0) { mesh = null; }\n var pos = BABYLON.Vector3.Zero();\n this.getPositionToRef(space, mesh, pos);\n return pos;\n };\n /**\n * Copy the position of the bone to a vector3 in local or world space\n * @param space The space that the returned position is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @param result The vector3 to copy the position to\n */\n Bone.prototype.getPositionToRef = function (space, mesh, result) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (space == BABYLON.Space.LOCAL) {\n var lm = this.getLocalMatrix();\n result.x = lm.m[12];\n result.y = lm.m[13];\n result.z = lm.m[14];\n }\n else {\n var wm = null;\n //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()\n if (mesh) {\n wm = mesh.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteTransforms();\n var tmat = Bone._tmpMats[0];\n if (mesh && wm) {\n tmat.copyFrom(this.getAbsoluteTransform());\n tmat.multiplyToRef(wm, tmat);\n }\n else {\n tmat = this.getAbsoluteTransform();\n }\n result.x = tmat.m[12];\n result.y = tmat.m[13];\n result.z = tmat.m[14];\n }\n };\n /**\n * Get the absolute position of the bone (world space)\n * @param mesh The mesh that this bone is attached to\n * @returns The absolute position of the bone\n */\n Bone.prototype.getAbsolutePosition = function (mesh) {\n if (mesh === void 0) { mesh = null; }\n var pos = BABYLON.Vector3.Zero();\n this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);\n return pos;\n };\n /**\n * Copy the absolute position of the bone (world space) to the result param\n * @param mesh The mesh that this bone is attached to\n * @param result The vector3 to copy the absolute position to\n */\n Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {\n this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);\n };\n /**\n * Compute the absolute transforms of this bone and its children\n */\n Bone.prototype.computeAbsoluteTransforms = function () {\n this._compose();\n if (this._parent) {\n this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);\n }\n else {\n this._absoluteTransform.copyFrom(this._localMatrix);\n var poseMatrix = this._skeleton.getPoseMatrix();\n if (poseMatrix) {\n this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);\n }\n }\n var children = this.children;\n var len = children.length;\n for (var i = 0; i < len; i++) {\n children[i].computeAbsoluteTransforms();\n }\n };\n /**\n * Get the world direction from an axis that is in the local space of the bone\n * @param localAxis The local direction that is used to compute the world direction\n * @param mesh The mesh that this bone is attached to\n * @returns The world direction\n */\n Bone.prototype.getDirection = function (localAxis, mesh) {\n if (mesh === void 0) { mesh = null; }\n var result = BABYLON.Vector3.Zero();\n this.getDirectionToRef(localAxis, mesh, result);\n return result;\n };\n /**\n * Copy the world direction to a vector3 from an axis that is in the local space of the bone\n * @param localAxis The local direction that is used to compute the world direction\n * @param mesh The mesh that this bone is attached to\n * @param result The vector3 that the world direction will be copied to\n */\n Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {\n if (mesh === void 0) { mesh = null; }\n var wm = null;\n //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()\n if (mesh) {\n wm = mesh.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteTransforms();\n var mat = Bone._tmpMats[0];\n mat.copyFrom(this.getAbsoluteTransform());\n if (mesh && wm) {\n mat.multiplyToRef(wm, mat);\n }\n BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);\n result.normalize();\n };\n /**\n * Get the euler rotation of the bone in local or world space\n * @param space The space that the rotation should be in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @returns The euler rotation\n */\n Bone.prototype.getRotation = function (space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (mesh === void 0) { mesh = null; }\n var result = BABYLON.Vector3.Zero();\n this.getRotationToRef(space, mesh, result);\n return result;\n };\n /**\n * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space\n * @param space The space that the rotation should be in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @param result The vector3 that the rotation should be copied to\n */\n Bone.prototype.getRotationToRef = function (space, mesh, result) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (mesh === void 0) { mesh = null; }\n var quat = Bone._tmpQuat;\n this.getRotationQuaternionToRef(space, mesh, quat);\n quat.toEulerAnglesToRef(result);\n };\n /**\n * Get the quaternion rotation of the bone in either local or world space\n * @param space The space that the rotation should be in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @returns The quaternion rotation\n */\n Bone.prototype.getRotationQuaternion = function (space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (mesh === void 0) { mesh = null; }\n var result = BABYLON.Quaternion.Identity();\n this.getRotationQuaternionToRef(space, mesh, result);\n return result;\n };\n /**\n * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space\n * @param space The space that the rotation should be in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @param result The quaternion that the rotation should be copied to\n */\n Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (mesh === void 0) { mesh = null; }\n if (space == BABYLON.Space.LOCAL) {\n this._decompose();\n result.copyFrom(this._localRotation);\n }\n else {\n var mat = Bone._tmpMats[0];\n var amat = this.getAbsoluteTransform();\n if (mesh) {\n amat.multiplyToRef(mesh.getWorldMatrix(), mat);\n }\n else {\n mat.copyFrom(amat);\n }\n mat.m[0] *= this._scalingDeterminant;\n mat.m[1] *= this._scalingDeterminant;\n mat.m[2] *= this._scalingDeterminant;\n mat.decompose(undefined, result, undefined);\n }\n };\n /**\n * Get the rotation matrix of the bone in local or world space\n * @param space The space that the rotation should be in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @returns The rotation matrix\n */\n Bone.prototype.getRotationMatrix = function (space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n var result = BABYLON.Matrix.Identity();\n this.getRotationMatrixToRef(space, mesh, result);\n return result;\n };\n /**\n * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space\n * @param space The space that the rotation should be in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @param result The quaternion that the rotation should be copied to\n */\n Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (space == BABYLON.Space.LOCAL) {\n this.getLocalMatrix().getRotationMatrixToRef(result);\n }\n else {\n var mat = Bone._tmpMats[0];\n var amat = this.getAbsoluteTransform();\n if (mesh) {\n amat.multiplyToRef(mesh.getWorldMatrix(), mat);\n }\n else {\n mat.copyFrom(amat);\n }\n mat.m[0] *= this._scalingDeterminant;\n mat.m[1] *= this._scalingDeterminant;\n mat.m[2] *= this._scalingDeterminant;\n mat.getRotationMatrixToRef(result);\n }\n };\n /**\n * Get the world position of a point that is in the local space of the bone\n * @param position The local position\n * @param mesh The mesh that this bone is attached to\n * @returns The world position\n */\n Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {\n if (mesh === void 0) { mesh = null; }\n var result = BABYLON.Vector3.Zero();\n this.getAbsolutePositionFromLocalToRef(position, mesh, result);\n return result;\n };\n /**\n * Get the world position of a point that is in the local space of the bone and copy it to the result param\n * @param position The local position\n * @param mesh The mesh that this bone is attached to\n * @param result The vector3 that the world position should be copied to\n */\n Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {\n if (mesh === void 0) { mesh = null; }\n var wm = null;\n //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()\n if (mesh) {\n wm = mesh.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteTransforms();\n var tmat = Bone._tmpMats[0];\n if (mesh && wm) {\n tmat.copyFrom(this.getAbsoluteTransform());\n tmat.multiplyToRef(wm, tmat);\n }\n else {\n tmat = this.getAbsoluteTransform();\n }\n BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);\n };\n /**\n * Get the local position of a point that is in world space\n * @param position The world position\n * @param mesh The mesh that this bone is attached to\n * @returns The local position\n */\n Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {\n if (mesh === void 0) { mesh = null; }\n var result = BABYLON.Vector3.Zero();\n this.getLocalPositionFromAbsoluteToRef(position, mesh, result);\n return result;\n };\n /**\n * Get the local position of a point that is in world space and copy it to the result param\n * @param position The world position\n * @param mesh The mesh that this bone is attached to\n * @param result The vector3 that the local position should be copied to\n */\n Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {\n if (mesh === void 0) { mesh = null; }\n var wm = null;\n //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()\n if (mesh) {\n wm = mesh.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteTransforms();\n var tmat = Bone._tmpMats[0];\n tmat.copyFrom(this.getAbsoluteTransform());\n if (mesh && wm) {\n tmat.multiplyToRef(wm, tmat);\n }\n tmat.invert();\n BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);\n };\n Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n Bone._tmpQuat = BABYLON.Quaternion.Identity();\n Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];\n return Bone;\n }(BABYLON.Node));\n BABYLON.Bone = Bone;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.bone.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to apply inverse kinematics to bones\n * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller\n */\n var BoneIKController = /** @class */ (function () {\n /**\n * Creates a new BoneIKController\n * @param mesh defines the mesh to control\n * @param bone defines the bone to control\n * @param options defines options to set up the controller\n */\n function BoneIKController(mesh, bone, options) {\n /**\n * Gets or sets the target position\n */\n this.targetPosition = BABYLON.Vector3.Zero();\n /**\n * Gets or sets the pole target position\n */\n this.poleTargetPosition = BABYLON.Vector3.Zero();\n /**\n * Gets or sets the pole target local offset\n */\n this.poleTargetLocalOffset = BABYLON.Vector3.Zero();\n /**\n * Gets or sets the pole angle\n */\n this.poleAngle = 0;\n /**\n * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)\n */\n this.slerpAmount = 1;\n this._bone1Quat = BABYLON.Quaternion.Identity();\n this._bone1Mat = BABYLON.Matrix.Identity();\n this._bone2Ang = Math.PI;\n this._maxAngle = Math.PI;\n this._rightHandedSystem = false;\n this._bendAxis = BABYLON.Vector3.Right();\n this._slerping = false;\n this._adjustRoll = 0;\n this._bone2 = bone;\n this._bone1 = bone.getParent();\n if (!this._bone1) {\n return;\n }\n this.mesh = mesh;\n var bonePos = bone.getPosition();\n if (bone.getAbsoluteTransform().determinant() > 0) {\n this._rightHandedSystem = true;\n this._bendAxis.x = 0;\n this._bendAxis.y = 0;\n this._bendAxis.z = -1;\n if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {\n this._adjustRoll = Math.PI * .5;\n this._bendAxis.z = 1;\n }\n }\n if (this._bone1.length) {\n var boneScale1 = this._bone1.getScale();\n var boneScale2 = this._bone2.getScale();\n this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;\n this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;\n }\n else if (this._bone1.children[0]) {\n mesh.computeWorldMatrix(true);\n var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);\n var pos2 = this._bone2.getAbsolutePosition(mesh);\n var pos3 = this._bone1.getAbsolutePosition(mesh);\n this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);\n this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);\n }\n this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);\n this.maxAngle = Math.PI;\n if (options) {\n if (options.targetMesh) {\n this.targetMesh = options.targetMesh;\n this.targetMesh.computeWorldMatrix(true);\n }\n if (options.poleTargetMesh) {\n this.poleTargetMesh = options.poleTargetMesh;\n this.poleTargetMesh.computeWorldMatrix(true);\n }\n else if (options.poleTargetBone) {\n this.poleTargetBone = options.poleTargetBone;\n }\n else if (this._bone1.getParent()) {\n this.poleTargetBone = this._bone1.getParent();\n }\n if (options.poleTargetLocalOffset) {\n this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);\n }\n if (options.poleAngle) {\n this.poleAngle = options.poleAngle;\n }\n if (options.bendAxis) {\n this._bendAxis.copyFrom(options.bendAxis);\n }\n if (options.maxAngle) {\n this.maxAngle = options.maxAngle;\n }\n if (options.slerpAmount) {\n this.slerpAmount = options.slerpAmount;\n }\n }\n }\n Object.defineProperty(BoneIKController.prototype, \"maxAngle\", {\n /**\n * Gets or sets maximum allowed angle\n */\n get: function () {\n return this._maxAngle;\n },\n set: function (value) {\n this._setMaxAngle(value);\n },\n enumerable: true,\n configurable: true\n });\n BoneIKController.prototype._setMaxAngle = function (ang) {\n if (ang < 0) {\n ang = 0;\n }\n if (ang > Math.PI || ang == undefined) {\n ang = Math.PI;\n }\n this._maxAngle = ang;\n var a = this._bone1Length;\n var b = this._bone2Length;\n this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));\n };\n /**\n * Force the controller to update the bones\n */\n BoneIKController.prototype.update = function () {\n var bone1 = this._bone1;\n if (!bone1) {\n return;\n }\n var target = this.targetPosition;\n var poleTarget = this.poleTargetPosition;\n var mat1 = BoneIKController._tmpMats[0];\n var mat2 = BoneIKController._tmpMats[1];\n if (this.targetMesh) {\n target.copyFrom(this.targetMesh.getAbsolutePosition());\n }\n if (this.poleTargetBone) {\n this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);\n }\n else if (this.poleTargetMesh) {\n BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);\n }\n var bonePos = BoneIKController._tmpVecs[0];\n var zaxis = BoneIKController._tmpVecs[1];\n var xaxis = BoneIKController._tmpVecs[2];\n var yaxis = BoneIKController._tmpVecs[3];\n var upAxis = BoneIKController._tmpVecs[4];\n var _tmpQuat = BoneIKController._tmpQuat;\n bone1.getAbsolutePositionToRef(this.mesh, bonePos);\n poleTarget.subtractToRef(bonePos, upAxis);\n if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {\n upAxis.y = 1;\n }\n else {\n upAxis.normalize();\n }\n target.subtractToRef(bonePos, yaxis);\n yaxis.normalize();\n BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);\n zaxis.normalize();\n BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);\n xaxis.normalize();\n BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);\n var a = this._bone1Length;\n var b = this._bone2Length;\n var c = BABYLON.Vector3.Distance(bonePos, target);\n if (this._maxReach > 0) {\n c = Math.min(this._maxReach, c);\n }\n var acosa = (b * b + c * c - a * a) / (2 * b * c);\n var acosb = (c * c + a * a - b * b) / (2 * c * a);\n if (acosa > 1) {\n acosa = 1;\n }\n if (acosb > 1) {\n acosb = 1;\n }\n if (acosa < -1) {\n acosa = -1;\n }\n if (acosb < -1) {\n acosb = -1;\n }\n var angA = Math.acos(acosa);\n var angB = Math.acos(acosb);\n var angC = -angA - angB;\n if (this._rightHandedSystem) {\n BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);\n mat2.multiplyToRef(mat1, mat1);\n BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);\n mat2.multiplyToRef(mat1, mat1);\n }\n else {\n var _tmpVec = BoneIKController._tmpVecs[5];\n _tmpVec.copyFrom(this._bendAxis);\n _tmpVec.x *= -1;\n BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);\n mat2.multiplyToRef(mat1, mat1);\n }\n if (this.poleAngle) {\n BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);\n mat1.multiplyToRef(mat2, mat1);\n }\n if (this._bone1) {\n if (this.slerpAmount < 1) {\n if (!this._slerping) {\n BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);\n }\n BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);\n BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);\n angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;\n this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);\n this._slerping = true;\n }\n else {\n this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);\n this._bone1Mat.copyFrom(mat1);\n this._slerping = false;\n }\n }\n this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);\n this._bone2Ang = angC;\n };\n BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();\n BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];\n return BoneIKController;\n }());\n BABYLON.BoneIKController = BoneIKController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boneIKController.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to make a bone look toward a point in space\n * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller\n */\n var BoneLookController = /** @class */ (function () {\n /**\n * Create a BoneLookController\n * @param mesh the mesh that the bone belongs to\n * @param bone the bone that will be looking to the target\n * @param target the target Vector3 to look at\n * @param settings optional settings:\n * * maxYaw: the maximum angle the bone will yaw to\n * * minYaw: the minimum angle the bone will yaw to\n * * maxPitch: the maximum angle the bone will pitch to\n * * minPitch: the minimum angle the bone will yaw to\n * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.\n * * upAxis: the up axis of the coordinate system\n * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.\n * * yawAxis: set yawAxis if the bone does not yaw on the y axis\n * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis\n * * adjustYaw: used to make an adjustment to the yaw of the bone\n * * adjustPitch: used to make an adjustment to the pitch of the bone\n * * adjustRoll: used to make an adjustment to the roll of the bone\n **/\n function BoneLookController(mesh, bone, target, options) {\n /**\n * The up axis of the coordinate system that is used when the bone is rotated\n */\n this.upAxis = BABYLON.Vector3.Up();\n /**\n * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD\n */\n this.upAxisSpace = BABYLON.Space.LOCAL;\n /**\n * Used to make an adjustment to the yaw of the bone\n */\n this.adjustYaw = 0;\n /**\n * Used to make an adjustment to the pitch of the bone\n */\n this.adjustPitch = 0;\n /**\n * Used to make an adjustment to the roll of the bone\n */\n this.adjustRoll = 0;\n /**\n * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)\n */\n this.slerpAmount = 1;\n this._boneQuat = BABYLON.Quaternion.Identity();\n this._slerping = false;\n this._firstFrameSkipped = false;\n this._fowardAxis = BABYLON.Vector3.Forward();\n this.mesh = mesh;\n this.bone = bone;\n this.target = target;\n if (options) {\n if (options.adjustYaw) {\n this.adjustYaw = options.adjustYaw;\n }\n if (options.adjustPitch) {\n this.adjustPitch = options.adjustPitch;\n }\n if (options.adjustRoll) {\n this.adjustRoll = options.adjustRoll;\n }\n if (options.maxYaw != null) {\n this.maxYaw = options.maxYaw;\n }\n else {\n this.maxYaw = Math.PI;\n }\n if (options.minYaw != null) {\n this.minYaw = options.minYaw;\n }\n else {\n this.minYaw = -Math.PI;\n }\n if (options.maxPitch != null) {\n this.maxPitch = options.maxPitch;\n }\n else {\n this.maxPitch = Math.PI;\n }\n if (options.minPitch != null) {\n this.minPitch = options.minPitch;\n }\n else {\n this.minPitch = -Math.PI;\n }\n if (options.slerpAmount != null) {\n this.slerpAmount = options.slerpAmount;\n }\n if (options.upAxis != null) {\n this.upAxis = options.upAxis;\n }\n if (options.upAxisSpace != null) {\n this.upAxisSpace = options.upAxisSpace;\n }\n if (options.yawAxis != null || options.pitchAxis != null) {\n var newYawAxis = BABYLON.Axis.Y;\n var newPitchAxis = BABYLON.Axis.X;\n if (options.yawAxis != null) {\n newYawAxis = options.yawAxis.clone();\n newYawAxis.normalize();\n }\n if (options.pitchAxis != null) {\n newPitchAxis = options.pitchAxis.clone();\n newPitchAxis.normalize();\n }\n var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);\n this._transformYawPitch = BABYLON.Matrix.Identity();\n BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);\n this._transformYawPitchInv = this._transformYawPitch.clone();\n this._transformYawPitch.invert();\n }\n }\n if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {\n this.upAxisSpace = BABYLON.Space.LOCAL;\n }\n }\n Object.defineProperty(BoneLookController.prototype, \"minYaw\", {\n /**\n * Gets or sets the minimum yaw angle that the bone can look to\n */\n get: function () {\n return this._minYaw;\n },\n set: function (value) {\n this._minYaw = value;\n this._minYawSin = Math.sin(value);\n this._minYawCos = Math.cos(value);\n if (this._maxYaw != null) {\n this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;\n this._yawRange = this._maxYaw - this._minYaw;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BoneLookController.prototype, \"maxYaw\", {\n /**\n * Gets or sets the maximum yaw angle that the bone can look to\n */\n get: function () {\n return this._maxYaw;\n },\n set: function (value) {\n this._maxYaw = value;\n this._maxYawSin = Math.sin(value);\n this._maxYawCos = Math.cos(value);\n if (this._minYaw != null) {\n this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;\n this._yawRange = this._maxYaw - this._minYaw;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BoneLookController.prototype, \"minPitch\", {\n /**\n * Gets or sets the minimum pitch angle that the bone can look to\n */\n get: function () {\n return this._minPitch;\n },\n set: function (value) {\n this._minPitch = value;\n this._minPitchTan = Math.tan(value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BoneLookController.prototype, \"maxPitch\", {\n /**\n * Gets or sets the maximum pitch angle that the bone can look to\n */\n get: function () {\n return this._maxPitch;\n },\n set: function (value) {\n this._maxPitch = value;\n this._maxPitchTan = Math.tan(value);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())\n */\n BoneLookController.prototype.update = function () {\n //skip the first frame when slerping so that the mesh rotation is correct\n if (this.slerpAmount < 1 && !this._firstFrameSkipped) {\n this._firstFrameSkipped = true;\n return;\n }\n var bone = this.bone;\n var bonePos = BoneLookController._tmpVecs[0];\n bone.getAbsolutePositionToRef(this.mesh, bonePos);\n var target = this.target;\n var _tmpMat1 = BoneLookController._tmpMats[0];\n var _tmpMat2 = BoneLookController._tmpMats[1];\n var mesh = this.mesh;\n var parentBone = bone.getParent();\n var upAxis = BoneLookController._tmpVecs[1];\n upAxis.copyFrom(this.upAxis);\n if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {\n if (this._transformYawPitch) {\n BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);\n }\n parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);\n }\n else if (this.upAxisSpace == BABYLON.Space.LOCAL) {\n mesh.getDirectionToRef(upAxis, upAxis);\n if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {\n upAxis.normalize();\n }\n }\n var checkYaw = false;\n var checkPitch = false;\n if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {\n checkYaw = true;\n }\n if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {\n checkPitch = true;\n }\n if (checkYaw || checkPitch) {\n var spaceMat = BoneLookController._tmpMats[2];\n var spaceMatInv = BoneLookController._tmpMats[3];\n if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {\n parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);\n }\n else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {\n spaceMat.copyFrom(mesh.getWorldMatrix());\n }\n else {\n var forwardAxis = BoneLookController._tmpVecs[2];\n forwardAxis.copyFrom(this._fowardAxis);\n if (this._transformYawPitch) {\n BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);\n }\n if (parentBone) {\n parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);\n }\n else {\n mesh.getDirectionToRef(forwardAxis, forwardAxis);\n }\n var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);\n rightAxis.normalize();\n var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);\n BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);\n }\n spaceMat.invertToRef(spaceMatInv);\n var xzlen = null;\n if (checkPitch) {\n var localTarget = BoneLookController._tmpVecs[3];\n target.subtractToRef(bonePos, localTarget);\n BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);\n xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);\n var pitch = Math.atan2(localTarget.y, xzlen);\n var newPitch = pitch;\n if (pitch > this._maxPitch) {\n localTarget.y = this._maxPitchTan * xzlen;\n newPitch = this._maxPitch;\n }\n else if (pitch < this._minPitch) {\n localTarget.y = this._minPitchTan * xzlen;\n newPitch = this._minPitch;\n }\n if (pitch != newPitch) {\n BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);\n localTarget.addInPlace(bonePos);\n target = localTarget;\n }\n }\n if (checkYaw) {\n var localTarget = BoneLookController._tmpVecs[4];\n target.subtractToRef(bonePos, localTarget);\n BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);\n var yaw = Math.atan2(localTarget.x, localTarget.z);\n var newYaw = yaw;\n if (yaw > this._maxYaw || yaw < this._minYaw) {\n if (xzlen == null) {\n xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);\n }\n if (this._yawRange > Math.PI) {\n if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {\n localTarget.z = this._maxYawCos * xzlen;\n localTarget.x = this._maxYawSin * xzlen;\n newYaw = this._maxYaw;\n }\n else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {\n localTarget.z = this._minYawCos * xzlen;\n localTarget.x = this._minYawSin * xzlen;\n newYaw = this._minYaw;\n }\n }\n else {\n if (yaw > this._maxYaw) {\n localTarget.z = this._maxYawCos * xzlen;\n localTarget.x = this._maxYawSin * xzlen;\n newYaw = this._maxYaw;\n }\n else if (yaw < this._minYaw) {\n localTarget.z = this._minYawCos * xzlen;\n localTarget.x = this._minYawSin * xzlen;\n newYaw = this._minYaw;\n }\n }\n }\n if (this._slerping && this._yawRange > Math.PI) {\n //are we going to be crossing into the min/max region?\n var boneFwd = BoneLookController._tmpVecs[8];\n boneFwd.copyFrom(BABYLON.Axis.Z);\n if (this._transformYawPitch) {\n BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);\n }\n var boneRotMat = BoneLookController._tmpMats[4];\n this._boneQuat.toRotationMatrix(boneRotMat);\n this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);\n BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);\n BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);\n var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);\n var angBtwTar = this._getAngleBetween(boneYaw, yaw);\n var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);\n if (angBtwTar > angBtwMidYaw) {\n if (xzlen == null) {\n xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);\n }\n var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);\n var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);\n if (angBtwMin < angBtwMax) {\n newYaw = boneYaw + Math.PI * .75;\n localTarget.z = Math.cos(newYaw) * xzlen;\n localTarget.x = Math.sin(newYaw) * xzlen;\n }\n else {\n newYaw = boneYaw - Math.PI * .75;\n localTarget.z = Math.cos(newYaw) * xzlen;\n localTarget.x = Math.sin(newYaw) * xzlen;\n }\n }\n }\n if (yaw != newYaw) {\n BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);\n localTarget.addInPlace(bonePos);\n target = localTarget;\n }\n }\n }\n var zaxis = BoneLookController._tmpVecs[5];\n var xaxis = BoneLookController._tmpVecs[6];\n var yaxis = BoneLookController._tmpVecs[7];\n var _tmpQuat = BoneLookController._tmpQuat;\n target.subtractToRef(bonePos, zaxis);\n zaxis.normalize();\n BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);\n xaxis.normalize();\n BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);\n yaxis.normalize();\n BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);\n if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {\n return;\n }\n if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {\n return;\n }\n if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {\n return;\n }\n if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {\n BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);\n _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);\n }\n if (this.slerpAmount < 1) {\n if (!this._slerping) {\n this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);\n }\n if (this._transformYawPitch) {\n this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);\n }\n BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);\n BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);\n this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);\n this._slerping = true;\n }\n else {\n if (this._transformYawPitch) {\n this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);\n }\n this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);\n this._slerping = false;\n }\n };\n BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {\n var angDiff = ang2 - ang1;\n angDiff %= Math.PI * 2;\n if (angDiff > Math.PI) {\n angDiff -= Math.PI * 2;\n }\n else if (angDiff < -Math.PI) {\n angDiff += Math.PI * 2;\n }\n return angDiff;\n };\n BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {\n ang1 %= (2 * Math.PI);\n ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;\n ang2 %= (2 * Math.PI);\n ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;\n var ab = 0;\n if (ang1 < ang2) {\n ab = ang2 - ang1;\n }\n else {\n ab = ang1 - ang2;\n }\n if (ab > Math.PI) {\n ab = Math.PI * 2 - ab;\n }\n return ab;\n };\n BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {\n ang %= (2 * Math.PI);\n ang = (ang < 0) ? ang + (2 * Math.PI) : ang;\n ang1 %= (2 * Math.PI);\n ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;\n ang2 %= (2 * Math.PI);\n ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;\n if (ang1 < ang2) {\n if (ang > ang1 && ang < ang2) {\n return true;\n }\n }\n else {\n if (ang > ang2 && ang < ang1) {\n return true;\n }\n }\n return false;\n };\n BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();\n BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];\n return BoneLookController;\n }());\n BABYLON.BoneLookController = BoneLookController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boneLookController.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to handle skinning animations\n * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons\n */\n var Skeleton = /** @class */ (function () {\n /**\n * Creates a new skeleton\n * @param name defines the skeleton name\n * @param id defines the skeleton Id\n * @param scene defines the hosting scene\n */\n function Skeleton(\n /** defines the skeleton name */\n name, \n /** defines the skeleton Id */\n id, scene) {\n this.name = name;\n this.id = id;\n /**\n * Gets the list of child bones\n */\n this.bones = new Array();\n /**\n * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)\n */\n this.needInitialSkinMatrix = false;\n this._isDirty = true;\n this._meshesWithPoseMatrix = new Array();\n this._identity = BABYLON.Matrix.Identity();\n this._ranges = {};\n this._lastAbsoluteTransformsUpdateId = -1;\n /**\n * Specifies if the skeleton should be serialized\n */\n this.doNotSerialize = false;\n this._animationPropertiesOverride = null;\n // Events\n /**\n * An observable triggered before computing the skeleton's matrices\n */\n this.onBeforeComputeObservable = new BABYLON.Observable();\n this.bones = [];\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n scene.skeletons.push(this);\n //make sure it will recalculate the matrix next time prepare is called.\n this._isDirty = true;\n }\n Object.defineProperty(Skeleton.prototype, \"animationPropertiesOverride\", {\n /**\n * Gets or sets the animation properties override\n */\n get: function () {\n if (!this._animationPropertiesOverride) {\n return this._scene.animationPropertiesOverride;\n }\n return this._animationPropertiesOverride;\n },\n set: function (value) {\n this._animationPropertiesOverride = value;\n },\n enumerable: true,\n configurable: true\n });\n // Members\n /**\n * Gets the list of transform matrices to send to shaders (one matrix per bone)\n * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)\n * @returns a Float32Array containing matrices data\n */\n Skeleton.prototype.getTransformMatrices = function (mesh) {\n if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {\n return mesh._bonesTransformMatrices;\n }\n if (!this._transformMatrices) {\n this.prepare();\n }\n return this._transformMatrices;\n };\n /**\n * Gets the current hosting scene\n * @returns a scene object\n */\n Skeleton.prototype.getScene = function () {\n return this._scene;\n };\n // Methods\n /**\n * Gets a string representing the current skeleton data\n * @param fullDetails defines a boolean indicating if we want a verbose version\n * @returns a string representing the current skeleton data\n */\n Skeleton.prototype.toString = function (fullDetails) {\n var ret = \"Name: \" + this.name + \", nBones: \" + this.bones.length;\n ret += \", nAnimationRanges: \" + (this._ranges ? Object.keys(this._ranges).length : \"none\");\n if (fullDetails) {\n ret += \", Ranges: {\";\n var first = true;\n for (var name_1 in this._ranges) {\n if (first) {\n ret += \", \";\n first = false;\n }\n ret += name_1;\n }\n ret += \"}\";\n }\n return ret;\n };\n /**\n * Get bone's index searching by name\n * @param name defines bone's name to search for\n * @return the indice of the bone. Returns -1 if not found\n */\n Skeleton.prototype.getBoneIndexByName = function (name) {\n for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {\n if (this.bones[boneIndex].name === name) {\n return boneIndex;\n }\n }\n return -1;\n };\n /**\n * Creater a new animation range\n * @param name defines the name of the range\n * @param from defines the start key\n * @param to defines the end key\n */\n Skeleton.prototype.createAnimationRange = function (name, from, to) {\n // check name not already in use\n if (!this._ranges[name]) {\n this._ranges[name] = new BABYLON.AnimationRange(name, from, to);\n for (var i = 0, nBones = this.bones.length; i < nBones; i++) {\n if (this.bones[i].animations[0]) {\n this.bones[i].animations[0].createRange(name, from, to);\n }\n }\n }\n };\n /**\n * Delete a specific animation range\n * @param name defines the name of the range\n * @param deleteFrames defines if frames must be removed as well\n */\n Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {\n if (deleteFrames === void 0) { deleteFrames = true; }\n for (var i = 0, nBones = this.bones.length; i < nBones; i++) {\n if (this.bones[i].animations[0]) {\n this.bones[i].animations[0].deleteRange(name, deleteFrames);\n }\n }\n this._ranges[name] = null; // said much faster than 'delete this._range[name]' \n };\n /**\n * Gets a specific animation range\n * @param name defines the name of the range to look for\n * @returns the requested animation range or null if not found\n */\n Skeleton.prototype.getAnimationRange = function (name) {\n return this._ranges[name];\n };\n /**\n * Gets the list of all animation ranges defined on this skeleton\n * @returns an array\n */\n Skeleton.prototype.getAnimationRanges = function () {\n var animationRanges = [];\n var name;\n var i = 0;\n for (name in this._ranges) {\n animationRanges[i] = this._ranges[name];\n i++;\n }\n return animationRanges;\n };\n /**\n * Copy animation range from a source skeleton.\n * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences\n * @param source defines the source skeleton\n * @param name defines the name of the range to copy\n * @param rescaleAsRequired defines if rescaling must be applied if required\n * @returns true if operation was successful\n */\n Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {\n if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }\n if (this._ranges[name] || !source.getAnimationRange(name)) {\n return false;\n }\n var ret = true;\n var frameOffset = this._getHighestAnimationFrame() + 1;\n // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required\n var boneDict = {};\n var sourceBones = source.bones;\n var nBones;\n var i;\n for (i = 0, nBones = sourceBones.length; i < nBones; i++) {\n boneDict[sourceBones[i].name] = sourceBones[i];\n }\n if (this.bones.length !== sourceBones.length) {\n BABYLON.Tools.Warn(\"copyAnimationRange: this rig has \" + this.bones.length + \" bones, while source as \" + sourceBones.length);\n ret = false;\n }\n var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;\n for (i = 0, nBones = this.bones.length; i < nBones; i++) {\n var boneName = this.bones[i].name;\n var sourceBone = boneDict[boneName];\n if (sourceBone) {\n ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);\n }\n else {\n BABYLON.Tools.Warn(\"copyAnimationRange: not same rig, missing source bone \" + boneName);\n ret = false;\n }\n }\n // do not call createAnimationRange(), since it also is done to bones, which was already done\n var range = source.getAnimationRange(name);\n if (range) {\n this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);\n }\n return ret;\n };\n /**\n * Forces the skeleton to go to rest pose\n */\n Skeleton.prototype.returnToRest = function () {\n for (var index = 0; index < this.bones.length; index++) {\n this.bones[index].returnToRest();\n }\n };\n Skeleton.prototype._getHighestAnimationFrame = function () {\n var ret = 0;\n for (var i = 0, nBones = this.bones.length; i < nBones; i++) {\n if (this.bones[i].animations[0]) {\n var highest = this.bones[i].animations[0].getHighestFrame();\n if (ret < highest) {\n ret = highest;\n }\n }\n }\n return ret;\n };\n /**\n * Begin a specific animation range\n * @param name defines the name of the range to start\n * @param loop defines if looping must be turned on (false by default)\n * @param speedRatio defines the speed ratio to apply (1 by default)\n * @param onAnimationEnd defines a callback which will be called when animation will end\n * @returns a new animatable\n */\n Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {\n var range = this.getAnimationRange(name);\n if (!range) {\n return null;\n }\n return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);\n };\n /** @hidden */\n Skeleton.prototype._markAsDirty = function () {\n this._isDirty = true;\n };\n /** @hidden */\n Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {\n this._meshesWithPoseMatrix.push(mesh);\n };\n /** @hidden */\n Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {\n var index = this._meshesWithPoseMatrix.indexOf(mesh);\n if (index > -1) {\n this._meshesWithPoseMatrix.splice(index, 1);\n }\n };\n /** @hidden */\n Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {\n this.onBeforeComputeObservable.notifyObservers(this);\n for (var index = 0; index < this.bones.length; index++) {\n var bone = this.bones[index];\n var parentBone = bone.getParent();\n if (parentBone) {\n bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());\n }\n else {\n if (initialSkinMatrix) {\n bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());\n }\n else {\n bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());\n }\n }\n if (bone._index !== -1) {\n var mappedIndex = bone._index === null ? index : bone._index;\n bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);\n }\n }\n this._identity.copyToArray(targetMatrix, this.bones.length * 16);\n };\n /**\n * Build all resources required to render a skeleton\n */\n Skeleton.prototype.prepare = function () {\n if (!this._isDirty) {\n return;\n }\n if (this.needInitialSkinMatrix) {\n for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {\n var mesh = this._meshesWithPoseMatrix[index];\n var poseMatrix = mesh.getPoseMatrix();\n if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {\n mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));\n }\n if (this._synchronizedWithMesh !== mesh) {\n this._synchronizedWithMesh = mesh;\n // Prepare bones\n for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {\n var bone = this.bones[boneIndex];\n if (!bone.getParent()) {\n var matrix = bone.getBaseMatrix();\n matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);\n bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);\n }\n }\n }\n this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);\n }\n }\n else {\n if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {\n this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));\n }\n this._computeTransformMatrices(this._transformMatrices, null);\n }\n this._isDirty = false;\n this._scene._activeBones.addCount(this.bones.length, false);\n };\n /**\n * Gets the list of animatables currently running for this skeleton\n * @returns an array of animatables\n */\n Skeleton.prototype.getAnimatables = function () {\n if (!this._animatables || this._animatables.length !== this.bones.length) {\n this._animatables = [];\n for (var index = 0; index < this.bones.length; index++) {\n this._animatables.push(this.bones[index]);\n }\n }\n return this._animatables;\n };\n /**\n * Clone the current skeleton\n * @param name defines the name of the new skeleton\n * @param id defines the id of the enw skeleton\n * @returns the new skeleton\n */\n Skeleton.prototype.clone = function (name, id) {\n var result = new Skeleton(name, id || name, this._scene);\n result.needInitialSkinMatrix = this.needInitialSkinMatrix;\n for (var index = 0; index < this.bones.length; index++) {\n var source = this.bones[index];\n var parentBone = null;\n var parent_1 = source.getParent();\n if (parent_1) {\n var parentIndex = this.bones.indexOf(parent_1);\n parentBone = result.bones[parentIndex];\n }\n var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());\n BABYLON.Tools.DeepCopy(source.animations, bone.animations);\n }\n if (this._ranges) {\n result._ranges = {};\n for (var rangeName in this._ranges) {\n var range = this._ranges[rangeName];\n if (range) {\n result._ranges[rangeName] = range.clone();\n }\n }\n }\n this._isDirty = true;\n return result;\n };\n /**\n * Enable animation blending for this skeleton\n * @param blendingSpeed defines the blending speed to apply\n * @see http://doc.babylonjs.com/babylon101/animations#animation-blending\n */\n Skeleton.prototype.enableBlending = function (blendingSpeed) {\n if (blendingSpeed === void 0) { blendingSpeed = 0.01; }\n this.bones.forEach(function (bone) {\n bone.animations.forEach(function (animation) {\n animation.enableBlending = true;\n animation.blendingSpeed = blendingSpeed;\n });\n });\n };\n /**\n * Releases all resources associated with the current skeleton\n */\n Skeleton.prototype.dispose = function () {\n this._meshesWithPoseMatrix = [];\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from scene\n this.getScene().removeSkeleton(this);\n };\n /**\n * Serialize the skeleton in a JSON object\n * @returns a JSON object\n */\n Skeleton.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.id = this.id;\n if (this.dimensionsAtRest) {\n serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();\n }\n serializationObject.bones = [];\n serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;\n for (var index = 0; index < this.bones.length; index++) {\n var bone = this.bones[index];\n var parent_2 = bone.getParent();\n var serializedBone = {\n parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,\n name: bone.name,\n matrix: bone.getBaseMatrix().toArray(),\n rest: bone.getRestPose().toArray()\n };\n serializationObject.bones.push(serializedBone);\n if (bone.length) {\n serializedBone.length = bone.length;\n }\n if (bone.metadata) {\n serializedBone.metadata = bone.metadata;\n }\n if (bone.animations && bone.animations.length > 0) {\n serializedBone.animation = bone.animations[0].serialize();\n }\n serializationObject.ranges = [];\n for (var name in this._ranges) {\n var source = this._ranges[name];\n if (!source) {\n continue;\n }\n var range = {};\n range.name = name;\n range.from = source.from;\n range.to = source.to;\n serializationObject.ranges.push(range);\n }\n }\n return serializationObject;\n };\n /**\n * Creates a new skeleton from serialized data\n * @param parsedSkeleton defines the serialized data\n * @param scene defines the hosting scene\n * @returns a new skeleton\n */\n Skeleton.Parse = function (parsedSkeleton, scene) {\n var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);\n if (parsedSkeleton.dimensionsAtRest) {\n skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);\n }\n skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;\n var index;\n for (index = 0; index < parsedSkeleton.bones.length; index++) {\n var parsedBone = parsedSkeleton.bones[index];\n var parentBone = null;\n if (parsedBone.parentBoneIndex > -1) {\n parentBone = skeleton.bones[parsedBone.parentBoneIndex];\n }\n var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;\n var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);\n if (parsedBone.length) {\n bone.length = parsedBone.length;\n }\n if (parsedBone.metadata) {\n bone.metadata = parsedBone.metadata;\n }\n if (parsedBone.animation) {\n bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));\n }\n }\n // placed after bones, so createAnimationRange can cascade down\n if (parsedSkeleton.ranges) {\n for (index = 0; index < parsedSkeleton.ranges.length; index++) {\n var data = parsedSkeleton.ranges[index];\n skeleton.createAnimationRange(data.name, data.from, data.to);\n }\n }\n return skeleton;\n };\n /**\n * Compute all node absolute transforms\n * @param forceUpdate defines if computation must be done even if cache is up to date\n */\n Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {\n if (forceUpdate === void 0) { forceUpdate = false; }\n var renderId = this._scene.getRenderId();\n if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {\n this.bones[0].computeAbsoluteTransforms();\n this._lastAbsoluteTransformsUpdateId = renderId;\n }\n };\n /**\n * Gets the root pose matrix\n * @returns a matrix\n */\n Skeleton.prototype.getPoseMatrix = function () {\n var poseMatrix = null;\n if (this._meshesWithPoseMatrix.length > 0) {\n poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();\n }\n return poseMatrix;\n };\n /**\n * Sorts bones per internal index\n */\n Skeleton.prototype.sortBones = function () {\n var bones = new Array();\n var visited = new Array(this.bones.length);\n for (var index = 0; index < this.bones.length; index++) {\n this._sortBones(index, bones, visited);\n }\n this.bones = bones;\n };\n Skeleton.prototype._sortBones = function (index, bones, visited) {\n if (visited[index]) {\n return;\n }\n visited[index] = true;\n var bone = this.bones[index];\n if (bone._index === undefined) {\n bone._index = index;\n }\n var parentBone = bone.getParent();\n if (parentBone) {\n this._sortBones(this.bones.indexOf(parentBone), bones, visited);\n }\n bones.push(bone);\n };\n return Skeleton;\n }());\n BABYLON.Skeleton = Skeleton;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.skeleton.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n ;\n /**\n * This groups tools to convert HDR texture to native colors array.\n */\n var HDRTools = /** @class */ (function () {\n function HDRTools() {\n }\n HDRTools.Ldexp = function (mantissa, exponent) {\n if (exponent > 1023) {\n return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);\n }\n if (exponent < -1074) {\n return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);\n }\n return mantissa * Math.pow(2, exponent);\n };\n HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {\n if (exponent > 0) { /*nonzero pixel*/\n exponent = this.Ldexp(1.0, exponent - (128 + 8));\n float32array[index + 0] = red * exponent;\n float32array[index + 1] = green * exponent;\n float32array[index + 2] = blue * exponent;\n }\n else {\n float32array[index + 0] = 0;\n float32array[index + 1] = 0;\n float32array[index + 2] = 0;\n }\n };\n HDRTools.readStringLine = function (uint8array, startIndex) {\n var line = \"\";\n var character = \"\";\n for (var i = startIndex; i < uint8array.length - startIndex; i++) {\n character = String.fromCharCode(uint8array[i]);\n if (character == \"\\n\") {\n break;\n }\n line += character;\n }\n return line;\n };\n /**\n * Reads header information from an RGBE texture stored in a native array.\n * More information on this format are available here:\n * https://en.wikipedia.org/wiki/RGBE_image_format\n *\n * @param uint8array The binary file stored in native array.\n * @return The header information.\n */\n HDRTools.RGBE_ReadHeader = function (uint8array) {\n var height = 0;\n var width = 0;\n var line = this.readStringLine(uint8array, 0);\n if (line[0] != '#' || line[1] != '?') {\n throw \"Bad HDR Format.\";\n }\n var endOfHeader = false;\n var findFormat = false;\n var lineIndex = 0;\n do {\n lineIndex += (line.length + 1);\n line = this.readStringLine(uint8array, lineIndex);\n if (line == \"FORMAT=32-bit_rle_rgbe\") {\n findFormat = true;\n }\n else if (line.length == 0) {\n endOfHeader = true;\n }\n } while (!endOfHeader);\n if (!findFormat) {\n throw \"HDR Bad header format, unsupported FORMAT\";\n }\n lineIndex += (line.length + 1);\n line = this.readStringLine(uint8array, lineIndex);\n var sizeRegexp = /^\\-Y (.*) \\+X (.*)$/g;\n var match = sizeRegexp.exec(line);\n // TODO. Support +Y and -X if needed.\n if (!match || match.length < 3) {\n throw \"HDR Bad header format, no size\";\n }\n width = parseInt(match[2]);\n height = parseInt(match[1]);\n if (width < 8 || width > 0x7fff) {\n throw \"HDR Bad header format, unsupported size\";\n }\n lineIndex += (line.length + 1);\n return {\n height: height,\n width: width,\n dataPosition: lineIndex\n };\n };\n /**\n * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.\n * This RGBE texture needs to store the information as a panorama.\n *\n * More information on this format are available here:\n * https://en.wikipedia.org/wiki/RGBE_image_format\n *\n * @param buffer The binary file stored in an array buffer.\n * @param size The expected size of the extracted cubemap.\n * @return The Cube Map information.\n */\n HDRTools.GetCubeMapTextureData = function (buffer, size) {\n var uint8array = new Uint8Array(buffer);\n var hdrInfo = this.RGBE_ReadHeader(uint8array);\n var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);\n var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);\n return cubeMapData;\n };\n /**\n * Returns the pixels data extracted from an RGBE texture.\n * This pixels will be stored left to right up to down in the R G B order in one array.\n *\n * More information on this format are available here:\n * https://en.wikipedia.org/wiki/RGBE_image_format\n *\n * @param uint8array The binary file stored in an array buffer.\n * @param hdrInfo The header information of the file.\n * @return The pixels data in RGB right to left up to down order.\n */\n HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {\n // Keep for multi format supports.\n return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);\n };\n HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {\n var num_scanlines = hdrInfo.height;\n var scanline_width = hdrInfo.width;\n var a, b, c, d, count;\n var dataIndex = hdrInfo.dataPosition;\n var index = 0, endIndex = 0, i = 0;\n var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E\n var scanLineArray = new Uint8Array(scanLineArrayBuffer);\n // 3 channels of 4 bytes per pixel in float.\n var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);\n var resultArray = new Float32Array(resultBuffer);\n // read in each successive scanline\n while (num_scanlines > 0) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n c = uint8array[dataIndex++];\n d = uint8array[dataIndex++];\n if (a != 2 || b != 2 || (c & 0x80)) {\n // this file is not run length encoded\n throw \"HDR Bad header format, not RLE\";\n }\n if (((c << 8) | d) != scanline_width) {\n throw \"HDR Bad header format, wrong scan line width\";\n }\n index = 0;\n // read each of the four channels for the scanline into the buffer\n for (i = 0; i < 4; i++) {\n endIndex = (i + 1) * scanline_width;\n while (index < endIndex) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n if (a > 128) {\n // a run of the same value\n count = a - 128;\n if ((count == 0) || (count > endIndex - index)) {\n throw \"HDR Bad Format, bad scanline data (run)\";\n }\n while (count-- > 0) {\n scanLineArray[index++] = b;\n }\n }\n else {\n // a non-run\n count = a;\n if ((count == 0) || (count > endIndex - index)) {\n throw \"HDR Bad Format, bad scanline data (non-run)\";\n }\n scanLineArray[index++] = b;\n if (--count > 0) {\n for (var j = 0; j < count; j++) {\n scanLineArray[index++] = uint8array[dataIndex++];\n }\n }\n }\n }\n }\n // now convert data from buffer into floats\n for (i = 0; i < scanline_width; i++) {\n a = scanLineArray[i];\n b = scanLineArray[i + scanline_width];\n c = scanLineArray[i + 2 * scanline_width];\n d = scanLineArray[i + 3 * scanline_width];\n this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);\n }\n num_scanlines--;\n }\n return resultArray;\n };\n return HDRTools;\n }());\n BABYLON.HDRTools = HDRTools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.hdr.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This represents a texture coming from an HDR input.\n *\n * The only supported format is currently panorama picture stored in RGBE format.\n * Example of such files can be found on HDRLib: http://hdrlib.com/\n */\n var HDRCubeTexture = /** @class */ (function (_super) {\n __extends(HDRCubeTexture, _super);\n /**\n * Instantiates an HDRTexture from the following parameters.\n *\n * @param url The location of the HDR raw data (Panorama stored in RGBE format)\n * @param scene The scene the texture will be used in\n * @param size The cubemap desired size (the more it increases the longer the generation will be)\n * @param noMipmap Forces to not generate the mipmap if true\n * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process\n * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)\n * @param reserved Reserved flag for internal use.\n */\n function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {\n if (noMipmap === void 0) { noMipmap = false; }\n if (generateHarmonics === void 0) { generateHarmonics = true; }\n if (gammaSpace === void 0) { gammaSpace = false; }\n if (reserved === void 0) { reserved = false; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n var _this = _super.call(this, scene) || this;\n _this._generateHarmonics = true;\n _this._onLoad = null;\n _this._onError = null;\n /**\n * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.\n */\n _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;\n _this._isBlocking = true;\n _this._rotationY = 0;\n /**\n * Gets or sets the center of the bounding box associated with the cube texture\n * It must define where the camera used to render the texture was set\n */\n _this.boundingBoxPosition = BABYLON.Vector3.Zero();\n if (!url) {\n return _this;\n }\n _this.name = url;\n _this.url = url;\n _this.hasAlpha = false;\n _this.isCube = true;\n _this._textureMatrix = BABYLON.Matrix.Identity();\n _this._onLoad = onLoad;\n _this._onError = onError;\n _this.gammaSpace = gammaSpace;\n _this._noMipmap = noMipmap;\n _this._size = size;\n _this._texture = _this._getFromCache(url, _this._noMipmap);\n if (!_this._texture) {\n if (!scene.useDelayedTextureLoading) {\n _this.loadTexture();\n }\n else {\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n }\n }\n return _this;\n }\n Object.defineProperty(HDRCubeTexture.prototype, \"isBlocking\", {\n /**\n * Gets wether or not the texture is blocking during loading.\n */\n get: function () {\n return this._isBlocking;\n },\n /**\n * Sets wether or not the texture is blocking during loading.\n */\n set: function (value) {\n this._isBlocking = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(HDRCubeTexture.prototype, \"rotationY\", {\n /**\n * Gets texture matrix rotation angle around Y axis radians.\n */\n get: function () {\n return this._rotationY;\n },\n /**\n * Sets texture matrix rotation angle around Y axis in radians.\n */\n set: function (value) {\n this._rotationY = value;\n this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(HDRCubeTexture.prototype, \"boundingBoxSize\", {\n get: function () {\n return this._boundingBoxSize;\n },\n /**\n * Gets or sets the size of the bounding box associated with the cube texture\n * When defined, the cubemap will switch to local mode\n * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity\n * @example https://www.babylonjs-playground.com/#RNASML\n */\n set: function (value) {\n if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {\n return;\n }\n this._boundingBoxSize = value;\n var scene = this.getScene();\n if (scene) {\n scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Occurs when the file is raw .hdr file.\n */\n HDRCubeTexture.prototype.loadTexture = function () {\n var _this = this;\n var callback = function (buffer) {\n _this.lodGenerationOffset = 0.0;\n _this.lodGenerationScale = 0.8;\n var scene = _this.getScene();\n if (!scene) {\n return null;\n }\n // Extract the raw linear data.\n var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);\n // Generate harmonics if needed.\n if (_this._generateHarmonics) {\n var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);\n _this.sphericalPolynomial = sphericalPolynomial;\n }\n var results = [];\n var byteArray = null;\n // Push each faces.\n for (var j = 0; j < 6; j++) {\n // Create uintarray fallback.\n if (!scene.getEngine().getCaps().textureFloat) {\n // 3 channels of 1 bytes per pixel in bytes.\n var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);\n byteArray = new Uint8Array(byteBuffer);\n }\n var dataFace = (data[HDRCubeTexture._facesMapping[j]]);\n // If special cases.\n if (_this.gammaSpace || byteArray) {\n for (var i = 0; i < _this._size * _this._size; i++) {\n // Put in gamma space if requested.\n if (_this.gammaSpace) {\n dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);\n dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);\n dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);\n }\n // Convert to int texture for fallback.\n if (byteArray) {\n var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);\n var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);\n var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);\n // May use luminance instead if the result is not accurate.\n var max = Math.max(Math.max(r, g), b);\n if (max > 255) {\n var scale = 255 / max;\n r *= scale;\n g *= scale;\n b *= scale;\n }\n byteArray[(i * 3) + 0] = r;\n byteArray[(i * 3) + 1] = g;\n byteArray[(i * 3) + 2] = b;\n }\n }\n }\n if (byteArray) {\n results.push(byteArray);\n }\n else {\n results.push(dataFace);\n }\n }\n return results;\n };\n var scene = this.getScene();\n if (scene) {\n this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);\n }\n };\n HDRCubeTexture.prototype.clone = function () {\n var scene = this.getScene();\n if (!scene) {\n return this;\n }\n var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);\n // Base texture\n newTexture.level = this.level;\n newTexture.wrapU = this.wrapU;\n newTexture.wrapV = this.wrapV;\n newTexture.coordinatesIndex = this.coordinatesIndex;\n newTexture.coordinatesMode = this.coordinatesMode;\n return newTexture;\n };\n // Methods\n HDRCubeTexture.prototype.delayLoad = function () {\n if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {\n return;\n }\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;\n this._texture = this._getFromCache(this.url, this._noMipmap);\n if (!this._texture) {\n this.loadTexture();\n }\n };\n HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {\n return this._textureMatrix;\n };\n HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {\n this._textureMatrix = value;\n };\n HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {\n var texture = null;\n if (parsedTexture.name && !parsedTexture.isRenderTarget) {\n texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);\n texture.name = parsedTexture.name;\n texture.hasAlpha = parsedTexture.hasAlpha;\n texture.level = parsedTexture.level;\n texture.coordinatesMode = parsedTexture.coordinatesMode;\n texture.isBlocking = parsedTexture.isBlocking;\n }\n if (texture) {\n if (parsedTexture.boundingBoxPosition) {\n texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);\n }\n if (parsedTexture.boundingBoxSize) {\n texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);\n }\n if (parsedTexture.rotationY) {\n texture.rotationY = parsedTexture.rotationY;\n }\n }\n return texture;\n };\n HDRCubeTexture.prototype.serialize = function () {\n if (!this.name) {\n return null;\n }\n var serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.hasAlpha = this.hasAlpha;\n serializationObject.isCube = true;\n serializationObject.level = this.level;\n serializationObject.size = this._size;\n serializationObject.coordinatesMode = this.coordinatesMode;\n serializationObject.useInGammaSpace = this.gammaSpace;\n serializationObject.generateHarmonics = this._generateHarmonics;\n serializationObject.customType = \"BABYLON.HDRCubeTexture\";\n serializationObject.noMipmap = this._noMipmap;\n serializationObject.isBlocking = this._isBlocking;\n serializationObject.rotationY = this._rotationY;\n return serializationObject;\n };\n HDRCubeTexture._facesMapping = [\n \"right\",\n \"left\",\n \"up\",\n \"down\",\n \"front\",\n \"back\"\n ];\n return HDRCubeTexture;\n }(BABYLON.BaseTexture));\n BABYLON.HDRCubeTexture = HDRCubeTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.hdrCubeTexture.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.\n */\n var PanoramaToCubeMapTools = /** @class */ (function () {\n function PanoramaToCubeMapTools() {\n }\n /**\n * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).\n *\n * @param float32Array The source data.\n * @param inputWidth The width of the input panorama.\n * @param inputhHeight The height of the input panorama.\n * @param size The willing size of the generated cubemap (each faces will be size * size pixels)\n * @return The cubemap data\n */\n PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {\n if (!float32Array) {\n throw \"ConvertPanoramaToCubemap: input cannot be null\";\n }\n if (float32Array.length != inputWidth * inputHeight * 3) {\n throw \"ConvertPanoramaToCubemap: input size is wrong\";\n }\n var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);\n var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);\n var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);\n var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);\n var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);\n var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);\n return {\n front: textureFront,\n back: textureBack,\n left: textureLeft,\n right: textureRight,\n up: textureUp,\n down: textureDown,\n size: size,\n type: BABYLON.Engine.TEXTURETYPE_FLOAT,\n format: BABYLON.Engine.TEXTUREFORMAT_RGB,\n gammaSpace: false,\n };\n };\n PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {\n var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);\n var textureArray = new Float32Array(buffer);\n var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);\n var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);\n var dy = 1 / texSize;\n var fy = 0;\n for (var y = 0; y < texSize; y++) {\n var xv1 = faceData[0];\n var xv2 = faceData[2];\n for (var x = 0; x < texSize; x++) {\n var v = xv2.subtract(xv1).scale(fy).add(xv1);\n v.normalize();\n var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);\n // 3 channels per pixels\n textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;\n textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;\n textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;\n xv1 = xv1.add(rotDX1);\n xv2 = xv2.add(rotDX2);\n }\n fy += dy;\n }\n return textureArray;\n };\n PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {\n var theta = Math.atan2(vDir.z, vDir.x);\n var phi = Math.acos(vDir.y);\n while (theta < -Math.PI)\n theta += 2 * Math.PI;\n while (theta > Math.PI)\n theta -= 2 * Math.PI;\n var dx = theta / Math.PI;\n var dy = phi / Math.PI;\n // recenter.\n dx = dx * 0.5 + 0.5;\n var px = Math.round(dx * inputWidth);\n if (px < 0)\n px = 0;\n else if (px >= inputWidth)\n px = inputWidth - 1;\n var py = Math.round(dy * inputHeight);\n if (py < 0)\n py = 0;\n else if (py >= inputHeight)\n py = inputHeight - 1;\n var inputY = (inputHeight - py - 1);\n var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];\n var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];\n var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];\n return {\n r: r,\n g: g,\n b: b\n };\n };\n PanoramaToCubeMapTools.FACE_FRONT = [\n new BABYLON.Vector3(-1.0, -1.0, -1.0),\n new BABYLON.Vector3(1.0, -1.0, -1.0),\n new BABYLON.Vector3(-1.0, 1.0, -1.0),\n new BABYLON.Vector3(1.0, 1.0, -1.0)\n ];\n PanoramaToCubeMapTools.FACE_BACK = [\n new BABYLON.Vector3(1.0, -1.0, 1.0),\n new BABYLON.Vector3(-1.0, -1.0, 1.0),\n new BABYLON.Vector3(1.0, 1.0, 1.0),\n new BABYLON.Vector3(-1.0, 1.0, 1.0)\n ];\n PanoramaToCubeMapTools.FACE_RIGHT = [\n new BABYLON.Vector3(1.0, -1.0, -1.0),\n new BABYLON.Vector3(1.0, -1.0, 1.0),\n new BABYLON.Vector3(1.0, 1.0, -1.0),\n new BABYLON.Vector3(1.0, 1.0, 1.0)\n ];\n PanoramaToCubeMapTools.FACE_LEFT = [\n new BABYLON.Vector3(-1.0, -1.0, 1.0),\n new BABYLON.Vector3(-1.0, -1.0, -1.0),\n new BABYLON.Vector3(-1.0, 1.0, 1.0),\n new BABYLON.Vector3(-1.0, 1.0, -1.0)\n ];\n PanoramaToCubeMapTools.FACE_DOWN = [\n new BABYLON.Vector3(-1.0, 1.0, -1.0),\n new BABYLON.Vector3(1.0, 1.0, -1.0),\n new BABYLON.Vector3(-1.0, 1.0, 1.0),\n new BABYLON.Vector3(1.0, 1.0, 1.0)\n ];\n PanoramaToCubeMapTools.FACE_UP = [\n new BABYLON.Vector3(-1.0, -1.0, 1.0),\n new BABYLON.Vector3(1.0, -1.0, 1.0),\n new BABYLON.Vector3(-1.0, -1.0, -1.0),\n new BABYLON.Vector3(1.0, -1.0, -1.0)\n ];\n return PanoramaToCubeMapTools;\n }());\n BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.panoramaToCubemap.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var IndexedVector2 = /** @class */ (function (_super) {\n __extends(IndexedVector2, _super);\n function IndexedVector2(original, index) {\n var _this = _super.call(this, original.x, original.y) || this;\n _this.index = index;\n return _this;\n }\n return IndexedVector2;\n }(BABYLON.Vector2));\n var PolygonPoints = /** @class */ (function () {\n function PolygonPoints() {\n this.elements = new Array();\n }\n PolygonPoints.prototype.add = function (originalPoints) {\n var _this = this;\n var result = new Array();\n originalPoints.forEach(function (point) {\n if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {\n var newPoint = new IndexedVector2(point, _this.elements.length);\n result.push(newPoint);\n _this.elements.push(newPoint);\n }\n });\n return result;\n };\n PolygonPoints.prototype.computeBounds = function () {\n var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);\n var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);\n this.elements.forEach(function (point) {\n // x\n if (point.x < lmin.x) {\n lmin.x = point.x;\n }\n else if (point.x > lmax.x) {\n lmax.x = point.x;\n }\n // y\n if (point.y < lmin.y) {\n lmin.y = point.y;\n }\n else if (point.y > lmax.y) {\n lmax.y = point.y;\n }\n });\n return {\n min: lmin,\n max: lmax,\n width: lmax.x - lmin.x,\n height: lmax.y - lmin.y\n };\n };\n return PolygonPoints;\n }());\n var Polygon = /** @class */ (function () {\n function Polygon() {\n }\n Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {\n return [\n new BABYLON.Vector2(xmin, ymin),\n new BABYLON.Vector2(xmax, ymin),\n new BABYLON.Vector2(xmax, ymax),\n new BABYLON.Vector2(xmin, ymax)\n ];\n };\n Polygon.Circle = function (radius, cx, cy, numberOfSides) {\n if (cx === void 0) { cx = 0; }\n if (cy === void 0) { cy = 0; }\n if (numberOfSides === void 0) { numberOfSides = 32; }\n var result = new Array();\n var angle = 0;\n var increment = (Math.PI * 2) / numberOfSides;\n for (var i = 0; i < numberOfSides; i++) {\n result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));\n angle -= increment;\n }\n return result;\n };\n Polygon.Parse = function (input) {\n var floats = input.split(/[^-+eE\\.\\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });\n var i, result = [];\n for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {\n result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));\n }\n return result;\n };\n Polygon.StartingAt = function (x, y) {\n return BABYLON.Path2.StartingAt(x, y);\n };\n return Polygon;\n }());\n BABYLON.Polygon = Polygon;\n var PolygonMeshBuilder = /** @class */ (function () {\n function PolygonMeshBuilder(name, contours, scene) {\n this._points = new PolygonPoints();\n this._outlinepoints = new PolygonPoints();\n this._holes = new Array();\n this._epoints = new Array();\n this._eholes = new Array();\n this._name = name;\n this._scene = scene;\n var points;\n if (contours instanceof BABYLON.Path2) {\n points = contours.getPoints();\n }\n else {\n points = contours;\n }\n this._addToepoint(points);\n this._points.add(points);\n this._outlinepoints.add(points);\n if (typeof earcut === 'undefined') {\n BABYLON.Tools.Warn(\"Earcut was not found, the polygon will not be built.\");\n }\n }\n PolygonMeshBuilder.prototype._addToepoint = function (points) {\n for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {\n var p = points_1[_i];\n this._epoints.push(p.x, p.y);\n }\n };\n PolygonMeshBuilder.prototype.addHole = function (hole) {\n this._points.add(hole);\n var holepoints = new PolygonPoints();\n holepoints.add(hole);\n this._holes.push(holepoints);\n this._eholes.push(this._epoints.length / 2);\n this._addToepoint(hole);\n return this;\n };\n PolygonMeshBuilder.prototype.build = function (updatable, depth) {\n var _this = this;\n if (updatable === void 0) { updatable = false; }\n if (depth === void 0) { depth = 0; }\n var result = new BABYLON.Mesh(this._name, this._scene);\n var normals = new Array();\n var positions = new Array();\n var uvs = new Array();\n var bounds = this._points.computeBounds();\n this._points.elements.forEach(function (p) {\n normals.push(0, 1.0, 0);\n positions.push(p.x, 0, p.y);\n uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);\n });\n var indices = new Array();\n var res = earcut(this._epoints, this._eholes, 2);\n for (var i = 0; i < res.length; i++) {\n indices.push(res[i]);\n }\n if (depth > 0) {\n var positionscount = (positions.length / 3); //get the current pointcount\n this._points.elements.forEach(function (p) {\n normals.push(0, -1.0, 0);\n positions.push(p.x, -depth, p.y);\n uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);\n });\n var totalCount = indices.length;\n for (var i = 0; i < totalCount; i += 3) {\n var i0 = indices[i + 0];\n var i1 = indices[i + 1];\n var i2 = indices[i + 2];\n indices.push(i2 + positionscount);\n indices.push(i1 + positionscount);\n indices.push(i0 + positionscount);\n }\n //Add the sides\n this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);\n this._holes.forEach(function (hole) {\n _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);\n });\n }\n result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);\n result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);\n result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);\n result.setIndices(indices);\n return result;\n };\n PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {\n var StartIndex = positions.length / 3;\n var ulength = 0;\n for (var i = 0; i < points.elements.length; i++) {\n var p = points.elements[i];\n var p1;\n if ((i + 1) > points.elements.length - 1) {\n p1 = points.elements[0];\n }\n else {\n p1 = points.elements[i + 1];\n }\n positions.push(p.x, 0, p.y);\n positions.push(p.x, -depth, p.y);\n positions.push(p1.x, 0, p1.y);\n positions.push(p1.x, -depth, p1.y);\n var v1 = new BABYLON.Vector3(p.x, 0, p.y);\n var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);\n var v3 = v2.subtract(v1);\n var v4 = new BABYLON.Vector3(0, 1, 0);\n var vn = BABYLON.Vector3.Cross(v3, v4);\n vn = vn.normalize();\n uvs.push(ulength / bounds.width, 0);\n uvs.push(ulength / bounds.width, 1);\n ulength += v3.length();\n uvs.push((ulength / bounds.width), 0);\n uvs.push((ulength / bounds.width), 1);\n if (!flip) {\n normals.push(-vn.x, -vn.y, -vn.z);\n normals.push(-vn.x, -vn.y, -vn.z);\n normals.push(-vn.x, -vn.y, -vn.z);\n normals.push(-vn.x, -vn.y, -vn.z);\n indices.push(StartIndex);\n indices.push(StartIndex + 1);\n indices.push(StartIndex + 2);\n indices.push(StartIndex + 1);\n indices.push(StartIndex + 3);\n indices.push(StartIndex + 2);\n }\n else {\n normals.push(vn.x, vn.y, vn.z);\n normals.push(vn.x, vn.y, vn.z);\n normals.push(vn.x, vn.y, vn.z);\n normals.push(vn.x, vn.y, vn.z);\n indices.push(StartIndex);\n indices.push(StartIndex + 2);\n indices.push(StartIndex + 1);\n indices.push(StartIndex + 1);\n indices.push(StartIndex + 2);\n indices.push(StartIndex + 3);\n }\n StartIndex += 4;\n }\n ;\n };\n return PolygonMeshBuilder;\n }());\n BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.polygonMesh.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n // Unique ID when we import meshes from Babylon to CSG\n var currentCSGMeshId = 0;\n // # class Vertex\n // Represents a vertex of a polygon. Use your own vertex class instead of this\n // one to provide additional features like texture coordinates and vertex\n // colors. Custom vertex classes need to provide a `pos` property and `clone()`,\n // `flip()`, and `interpolate()` methods that behave analogous to the ones\n // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience\n // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`\n // is not used anywhere else. \n // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes\n var Vertex = /** @class */ (function () {\n function Vertex(pos, normal, uv) {\n this.pos = pos;\n this.normal = normal;\n this.uv = uv;\n }\n Vertex.prototype.clone = function () {\n return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());\n };\n // Invert all orientation-specific data (e.g. vertex normal). Called when the\n // orientation of a polygon is flipped.\n Vertex.prototype.flip = function () {\n this.normal = this.normal.scale(-1);\n };\n // Create a new vertex between this vertex and `other` by linearly\n // interpolating all properties using a parameter of `t`. Subclasses should\n // override this to interpolate additional properties.\n Vertex.prototype.interpolate = function (other, t) {\n return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));\n };\n return Vertex;\n }());\n // # class Plane\n // Represents a plane in 3D space.\n var Plane = /** @class */ (function () {\n function Plane(normal, w) {\n this.normal = normal;\n this.w = w;\n }\n Plane.FromPoints = function (a, b, c) {\n var v0 = c.subtract(a);\n var v1 = b.subtract(a);\n if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {\n return null;\n }\n var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));\n return new Plane(n, BABYLON.Vector3.Dot(n, a));\n };\n Plane.prototype.clone = function () {\n return new Plane(this.normal.clone(), this.w);\n };\n Plane.prototype.flip = function () {\n this.normal.scaleInPlace(-1);\n this.w = -this.w;\n };\n // Split `polygon` by this plane if needed, then put the polygon or polygon\n // fragments in the appropriate lists. Coplanar polygons go into either\n // `coplanarFront` or `coplanarBack` depending on their orientation with\n // respect to this plane. Polygons in front or in back of this plane go into\n // either `front` or `back`.\n Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {\n var COPLANAR = 0;\n var FRONT = 1;\n var BACK = 2;\n var SPANNING = 3;\n // Classify each point as well as the entire polygon into one of the above\n // four classes.\n var polygonType = 0;\n var types = [];\n var i;\n var t;\n for (i = 0; i < polygon.vertices.length; i++) {\n t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;\n var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;\n polygonType |= type;\n types.push(type);\n }\n // Put the polygon in the correct list, splitting it when necessary.\n switch (polygonType) {\n case COPLANAR:\n (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);\n break;\n case FRONT:\n front.push(polygon);\n break;\n case BACK:\n back.push(polygon);\n break;\n case SPANNING:\n var f = [], b = [];\n for (i = 0; i < polygon.vertices.length; i++) {\n var j = (i + 1) % polygon.vertices.length;\n var ti = types[i], tj = types[j];\n var vi = polygon.vertices[i], vj = polygon.vertices[j];\n if (ti !== BACK)\n f.push(vi);\n if (ti !== FRONT)\n b.push(ti !== BACK ? vi.clone() : vi);\n if ((ti | tj) === SPANNING) {\n t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));\n var v = vi.interpolate(vj, t);\n f.push(v);\n b.push(v.clone());\n }\n }\n var poly;\n if (f.length >= 3) {\n poly = new Polygon(f, polygon.shared);\n if (poly.plane)\n front.push(poly);\n }\n if (b.length >= 3) {\n poly = new Polygon(b, polygon.shared);\n if (poly.plane)\n back.push(poly);\n }\n break;\n }\n };\n // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a\n // point is on the plane.\n Plane.EPSILON = 1e-5;\n return Plane;\n }());\n // # class Polygon\n // Represents a convex polygon. The vertices used to initialize a polygon must\n // be coplanar and form a convex loop.\n // \n // Each convex polygon has a `shared` property, which is shared between all\n // polygons that are clones of each other or were split from the same polygon.\n // This can be used to define per-polygon properties (such as surface color).\n var Polygon = /** @class */ (function () {\n function Polygon(vertices, shared) {\n this.vertices = vertices;\n this.shared = shared;\n this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);\n }\n Polygon.prototype.clone = function () {\n var vertices = this.vertices.map(function (v) { return v.clone(); });\n return new Polygon(vertices, this.shared);\n };\n Polygon.prototype.flip = function () {\n this.vertices.reverse().map(function (v) { v.flip(); });\n this.plane.flip();\n };\n return Polygon;\n }());\n // # class Node\n // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons\n // by picking a polygon to split along. That polygon (and all other coplanar\n // polygons) are added directly to that node and the other polygons are added to\n // the front and/or back subtrees. This is not a leafy BSP tree since there is\n // no distinction between internal and leaf nodes.\n var Node = /** @class */ (function () {\n function Node(polygons) {\n this.plane = null;\n this.front = null;\n this.back = null;\n this.polygons = new Array();\n if (polygons) {\n this.build(polygons);\n }\n }\n Node.prototype.clone = function () {\n var node = new Node();\n node.plane = this.plane && this.plane.clone();\n node.front = this.front && this.front.clone();\n node.back = this.back && this.back.clone();\n node.polygons = this.polygons.map(function (p) { return p.clone(); });\n return node;\n };\n // Convert solid space to empty space and empty space to solid space.\n Node.prototype.invert = function () {\n for (var i = 0; i < this.polygons.length; i++) {\n this.polygons[i].flip();\n }\n if (this.plane) {\n this.plane.flip();\n }\n if (this.front) {\n this.front.invert();\n }\n if (this.back) {\n this.back.invert();\n }\n var temp = this.front;\n this.front = this.back;\n this.back = temp;\n };\n // Recursively remove all polygons in `polygons` that are inside this BSP\n // tree.\n Node.prototype.clipPolygons = function (polygons) {\n if (!this.plane)\n return polygons.slice();\n var front = new Array(), back = new Array();\n for (var i = 0; i < polygons.length; i++) {\n this.plane.splitPolygon(polygons[i], front, back, front, back);\n }\n if (this.front) {\n front = this.front.clipPolygons(front);\n }\n if (this.back) {\n back = this.back.clipPolygons(back);\n }\n else {\n back = [];\n }\n return front.concat(back);\n };\n // Remove all polygons in this BSP tree that are inside the other BSP tree\n // `bsp`.\n Node.prototype.clipTo = function (bsp) {\n this.polygons = bsp.clipPolygons(this.polygons);\n if (this.front)\n this.front.clipTo(bsp);\n if (this.back)\n this.back.clipTo(bsp);\n };\n // Return a list of all polygons in this BSP tree.\n Node.prototype.allPolygons = function () {\n var polygons = this.polygons.slice();\n if (this.front)\n polygons = polygons.concat(this.front.allPolygons());\n if (this.back)\n polygons = polygons.concat(this.back.allPolygons());\n return polygons;\n };\n // Build a BSP tree out of `polygons`. When called on an existing tree, the\n // new polygons are filtered down to the bottom of the tree and become new\n // nodes there. Each set of polygons is partitioned using the first polygon\n // (no heuristic is used to pick a good split).\n Node.prototype.build = function (polygons) {\n if (!polygons.length)\n return;\n if (!this.plane)\n this.plane = polygons[0].plane.clone();\n var front = new Array(), back = new Array();\n for (var i = 0; i < polygons.length; i++) {\n this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);\n }\n if (front.length) {\n if (!this.front)\n this.front = new Node();\n this.front.build(front);\n }\n if (back.length) {\n if (!this.back)\n this.back = new Node();\n this.back.build(back);\n }\n };\n return Node;\n }());\n var CSG = /** @class */ (function () {\n function CSG() {\n this.polygons = new Array();\n }\n // Convert BABYLON.Mesh to BABYLON.CSG\n CSG.FromMesh = function (mesh) {\n var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;\n var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;\n if (mesh instanceof BABYLON.Mesh) {\n mesh.computeWorldMatrix(true);\n matrix = mesh.getWorldMatrix();\n meshPosition = mesh.position.clone();\n meshRotation = mesh.rotation.clone();\n if (mesh.rotationQuaternion) {\n meshRotationQuaternion = mesh.rotationQuaternion.clone();\n }\n meshScaling = mesh.scaling.clone();\n }\n else {\n throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';\n }\n var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);\n var subMeshes = mesh.subMeshes;\n for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {\n for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {\n vertices = [];\n for (var j = 0; j < 3; j++) {\n var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);\n uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);\n var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);\n position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);\n normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);\n vertex = new Vertex(position, normal, uv);\n vertices.push(vertex);\n }\n polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });\n // To handle the case of degenerated triangle\n // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated\n if (polygon.plane)\n polygons.push(polygon);\n }\n }\n var csg = CSG.FromPolygons(polygons);\n csg.matrix = matrix;\n csg.position = meshPosition;\n csg.rotation = meshRotation;\n csg.scaling = meshScaling;\n csg.rotationQuaternion = meshRotationQuaternion;\n currentCSGMeshId++;\n return csg;\n };\n // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.\n CSG.FromPolygons = function (polygons) {\n var csg = new CSG();\n csg.polygons = polygons;\n return csg;\n };\n CSG.prototype.clone = function () {\n var csg = new CSG();\n csg.polygons = this.polygons.map(function (p) { return p.clone(); });\n csg.copyTransformAttributes(this);\n return csg;\n };\n CSG.prototype.union = function (csg) {\n var a = new Node(this.clone().polygons);\n var b = new Node(csg.clone().polygons);\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);\n };\n CSG.prototype.unionInPlace = function (csg) {\n var a = new Node(this.polygons);\n var b = new Node(csg.polygons);\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n this.polygons = a.allPolygons();\n };\n CSG.prototype.subtract = function (csg) {\n var a = new Node(this.clone().polygons);\n var b = new Node(csg.clone().polygons);\n a.invert();\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n a.invert();\n return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);\n };\n CSG.prototype.subtractInPlace = function (csg) {\n var a = new Node(this.polygons);\n var b = new Node(csg.polygons);\n a.invert();\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n a.invert();\n this.polygons = a.allPolygons();\n };\n CSG.prototype.intersect = function (csg) {\n var a = new Node(this.clone().polygons);\n var b = new Node(csg.clone().polygons);\n a.invert();\n b.clipTo(a);\n b.invert();\n a.clipTo(b);\n b.clipTo(a);\n a.build(b.allPolygons());\n a.invert();\n return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);\n };\n CSG.prototype.intersectInPlace = function (csg) {\n var a = new Node(this.polygons);\n var b = new Node(csg.polygons);\n a.invert();\n b.clipTo(a);\n b.invert();\n a.clipTo(b);\n b.clipTo(a);\n a.build(b.allPolygons());\n a.invert();\n this.polygons = a.allPolygons();\n };\n // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is\n // not modified.\n CSG.prototype.inverse = function () {\n var csg = this.clone();\n csg.inverseInPlace();\n return csg;\n };\n CSG.prototype.inverseInPlace = function () {\n this.polygons.map(function (p) { p.flip(); });\n };\n // This is used to keep meshes transformations so they can be restored\n // when we build back a Babylon Mesh\n // NB : All CSG operations are performed in world coordinates\n CSG.prototype.copyTransformAttributes = function (csg) {\n this.matrix = csg.matrix;\n this.position = csg.position;\n this.rotation = csg.rotation;\n this.scaling = csg.scaling;\n this.rotationQuaternion = csg.rotationQuaternion;\n return this;\n };\n // Build Raw mesh from CSG\n // Coordinates here are in world space\n CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {\n var matrix = this.matrix.clone();\n matrix.invert();\n var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;\n if (keepSubMeshes) {\n // Sort Polygons, since subMeshes are indices range\n polygons.sort(function (a, b) {\n if (a.shared.meshId === b.shared.meshId) {\n return a.shared.subMeshId - b.shared.subMeshId;\n }\n else {\n return a.shared.meshId - b.shared.meshId;\n }\n });\n }\n for (var i = 0, il = polygons.length; i < il; i++) {\n polygon = polygons[i];\n // Building SubMeshes\n if (!subMesh_dict[polygon.shared.meshId]) {\n subMesh_dict[polygon.shared.meshId] = {};\n }\n if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {\n subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {\n indexStart: +Infinity,\n indexEnd: -Infinity,\n materialIndex: polygon.shared.materialIndex\n };\n }\n subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];\n for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {\n polygonIndices[0] = 0;\n polygonIndices[1] = j - 1;\n polygonIndices[2] = j;\n for (var k = 0; k < 3; k++) {\n vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);\n normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);\n uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);\n var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);\n var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);\n vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];\n // Check if 2 points can be merged\n if (!(typeof vertex_idx !== 'undefined' &&\n normals[vertex_idx * 3] === localNormal.x &&\n normals[vertex_idx * 3 + 1] === localNormal.y &&\n normals[vertex_idx * 3 + 2] === localNormal.z &&\n uvs[vertex_idx * 2] === uv.x &&\n uvs[vertex_idx * 2 + 1] === uv.y)) {\n vertices.push(localVertex.x, localVertex.y, localVertex.z);\n uvs.push(uv.x, uv.y);\n normals.push(normal.x, normal.y, normal.z);\n vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;\n }\n indices.push(vertex_idx);\n subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);\n subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);\n currentIndex++;\n }\n }\n }\n mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);\n mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);\n mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);\n mesh.setIndices(indices, null);\n if (keepSubMeshes) {\n // We offset the materialIndex by the previous number of materials in the CSG mixed meshes\n var materialIndexOffset = 0, materialMaxIndex;\n mesh.subMeshes = new Array();\n for (var m in subMesh_dict) {\n materialMaxIndex = -1;\n for (var sm in subMesh_dict[m]) {\n subMesh_obj = subMesh_dict[m][sm];\n BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);\n materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);\n }\n materialIndexOffset += ++materialMaxIndex;\n }\n }\n return mesh;\n };\n // Build Mesh from CSG taking material and transforms into account\n CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {\n var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);\n mesh.material = material;\n mesh.position.copyFrom(this.position);\n mesh.rotation.copyFrom(this.rotation);\n if (this.rotationQuaternion) {\n mesh.rotationQuaternion = this.rotationQuaternion.clone();\n }\n mesh.scaling.copyFrom(this.scaling);\n mesh.computeWorldMatrix(true);\n return mesh;\n };\n return CSG;\n }());\n BABYLON.CSG = CSG;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.csg.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var LensFlare = /** @class */ (function () {\n function LensFlare(size, position, color, imgUrl, system) {\n this.size = size;\n this.position = position;\n this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;\n this.color = color || new BABYLON.Color3(1, 1, 1);\n this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;\n this._system = system;\n system.lensFlares.push(this);\n }\n LensFlare.AddFlare = function (size, position, color, imgUrl, system) {\n return new LensFlare(size, position, color, imgUrl, system);\n };\n LensFlare.prototype.dispose = function () {\n if (this.texture) {\n this.texture.dispose();\n }\n // Remove from scene\n var index = this._system.lensFlares.indexOf(this);\n this._system.lensFlares.splice(index, 1);\n };\n ;\n return LensFlare;\n }());\n BABYLON.LensFlare = LensFlare;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.lensFlare.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n // Adds the parser to the scene parsers.\n BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {\n // Lens flares\n if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {\n for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {\n var parsedLensFlareSystem = parsedData.lensFlareSystems[index];\n var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);\n container.lensFlareSystems.push(lf);\n }\n }\n });\n BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {\n for (var index = 0; index < this.lensFlareSystems.length; index++) {\n if (this.lensFlareSystems[index].name === name) {\n return this.lensFlareSystems[index];\n }\n }\n return null;\n };\n BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {\n for (var index = 0; index < this.lensFlareSystems.length; index++) {\n if (this.lensFlareSystems[index].id === id) {\n return this.lensFlareSystems[index];\n }\n }\n return null;\n };\n BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {\n var index = this.lensFlareSystems.indexOf(toRemove);\n if (index !== -1) {\n this.lensFlareSystems.splice(index, 1);\n }\n return index;\n };\n BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {\n this.lensFlareSystems.push(newLensFlareSystem);\n };\n /**\n * Defines the lens flare scene component responsible to manage any lens flares\n * in a given scene.\n */\n var LensFlareSystemSceneComponent = /** @class */ (function () {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n function LensFlareSystemSceneComponent(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;\n this.scene = scene;\n scene.lensFlareSystems = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n LensFlareSystemSceneComponent.prototype.register = function () {\n this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);\n };\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n LensFlareSystemSceneComponent.prototype.rebuild = function () {\n // Nothing to do for lens flare\n };\n /**\n * Adds all the element from the container to the scene\n * @param container the container holding the elements\n */\n LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {\n var _this = this;\n if (!container.lensFlareSystems) {\n return;\n }\n container.lensFlareSystems.forEach(function (o) {\n _this.scene.addLensFlareSystem(o);\n });\n };\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n */\n LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {\n var _this = this;\n if (!container.lensFlareSystems) {\n return;\n }\n container.lensFlareSystems.forEach(function (o) {\n _this.scene.removeLensFlareSystem(o);\n });\n };\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {\n // Lens flares\n serializationObject.lensFlareSystems = [];\n var lensFlareSystems = this.scene.lensFlareSystems;\n for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {\n var lensFlareSystem = lensFlareSystems_1[_i];\n serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());\n }\n };\n /**\n * Disposes the component and the associated ressources.\n */\n LensFlareSystemSceneComponent.prototype.dispose = function () {\n var lensFlareSystems = this.scene.lensFlareSystems;\n while (lensFlareSystems.length) {\n lensFlareSystems[0].dispose();\n }\n };\n LensFlareSystemSceneComponent.prototype._draw = function (camera) {\n // Lens flares\n if (this.scene.lensFlaresEnabled) {\n var lensFlareSystems = this.scene.lensFlareSystems;\n BABYLON.Tools.StartPerformanceCounter(\"Lens flares\", lensFlareSystems.length > 0);\n for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {\n var lensFlareSystem = lensFlareSystems_2[_i];\n if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {\n lensFlareSystem.render();\n }\n }\n BABYLON.Tools.EndPerformanceCounter(\"Lens flares\", lensFlareSystems.length > 0);\n }\n };\n return LensFlareSystemSceneComponent;\n }());\n BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var LensFlareSystem = /** @class */ (function () {\n function LensFlareSystem(name, emitter, scene) {\n this.name = name;\n this.lensFlares = new Array();\n this.borderLimit = 300;\n this.viewportBorder = 0;\n this.layerMask = 0x0FFFFFFF;\n this._vertexBuffers = {};\n this._isEnabled = true;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);\n if (!component) {\n component = new BABYLON.LensFlareSystemSceneComponent(this._scene);\n scene._addComponent(component);\n }\n this._emitter = emitter;\n this.id = name;\n scene.lensFlareSystems.push(this);\n this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };\n var engine = scene.getEngine();\n // VBO\n var vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);\n // Indices\n var indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = engine.createIndexBuffer(indices);\n // Effects\n this._effect = engine.createEffect(\"lensFlare\", [BABYLON.VertexBuffer.PositionKind], [\"color\", \"viewportMatrix\"], [\"textureSampler\"], \"\");\n }\n Object.defineProperty(LensFlareSystem.prototype, \"isEnabled\", {\n get: function () {\n return this._isEnabled;\n },\n set: function (value) {\n this._isEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n LensFlareSystem.prototype.getScene = function () {\n return this._scene;\n };\n LensFlareSystem.prototype.getEmitter = function () {\n return this._emitter;\n };\n LensFlareSystem.prototype.setEmitter = function (newEmitter) {\n this._emitter = newEmitter;\n };\n LensFlareSystem.prototype.getEmitterPosition = function () {\n return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;\n };\n LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {\n var position = this.getEmitterPosition();\n position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);\n this._positionX = position.x;\n this._positionY = position.y;\n position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());\n if (this.viewportBorder > 0) {\n globalViewport.x -= this.viewportBorder;\n globalViewport.y -= this.viewportBorder;\n globalViewport.width += this.viewportBorder * 2;\n globalViewport.height += this.viewportBorder * 2;\n position.x += this.viewportBorder;\n position.y += this.viewportBorder;\n this._positionX += this.viewportBorder;\n this._positionY += this.viewportBorder;\n }\n if (position.z > 0) {\n if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {\n if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))\n return true;\n }\n return true;\n }\n return false;\n };\n LensFlareSystem.prototype._isVisible = function () {\n if (!this._isEnabled || !this._scene.activeCamera) {\n return false;\n }\n var emitterPosition = this.getEmitterPosition();\n var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);\n var distance = direction.length();\n direction.normalize();\n var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);\n var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);\n return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;\n };\n LensFlareSystem.prototype.render = function () {\n if (!this._effect.isReady() || !this._scene.activeCamera)\n return false;\n var engine = this._scene.getEngine();\n var viewport = this._scene.activeCamera.viewport;\n var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));\n // Position\n if (!this.computeEffectivePosition(globalViewport)) {\n return false;\n }\n // Visibility\n if (!this._isVisible()) {\n return false;\n }\n // Intensity\n var awayX;\n var awayY;\n if (this._positionX < this.borderLimit + globalViewport.x) {\n awayX = this.borderLimit + globalViewport.x - this._positionX;\n }\n else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {\n awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;\n }\n else {\n awayX = 0;\n }\n if (this._positionY < this.borderLimit + globalViewport.y) {\n awayY = this.borderLimit + globalViewport.y - this._positionY;\n }\n else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {\n awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;\n }\n else {\n awayY = 0;\n }\n var away = (awayX > awayY) ? awayX : awayY;\n away -= this.viewportBorder;\n if (away > this.borderLimit) {\n away = this.borderLimit;\n }\n var intensity = 1.0 - (away / this.borderLimit);\n if (intensity < 0) {\n return false;\n }\n if (intensity > 1.0) {\n intensity = 1.0;\n }\n if (this.viewportBorder > 0) {\n globalViewport.x += this.viewportBorder;\n globalViewport.y += this.viewportBorder;\n globalViewport.width -= this.viewportBorder * 2;\n globalViewport.height -= this.viewportBorder * 2;\n this._positionX -= this.viewportBorder;\n this._positionY -= this.viewportBorder;\n }\n // Position\n var centerX = globalViewport.x + globalViewport.width / 2;\n var centerY = globalViewport.y + globalViewport.height / 2;\n var distX = centerX - this._positionX;\n var distY = centerY - this._positionY;\n // Effects\n engine.enableEffect(this._effect);\n engine.setState(false);\n engine.setDepthBuffer(false);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);\n // Flares\n for (var index = 0; index < this.lensFlares.length; index++) {\n var flare = this.lensFlares[index];\n engine.setAlphaMode(flare.alphaMode);\n var x = centerX - (distX * flare.position);\n var y = centerY - (distY * flare.position);\n var cw = flare.size;\n var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);\n var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;\n var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));\n var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);\n this._effect.setMatrix(\"viewportMatrix\", viewportMatrix);\n // Texture\n this._effect.setTexture(\"textureSampler\", flare.texture);\n // Color\n this._effect.setFloat4(\"color\", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);\n // Draw order\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n }\n engine.setDepthBuffer(true);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n return true;\n };\n LensFlareSystem.prototype.dispose = function () {\n var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n while (this.lensFlares.length) {\n this.lensFlares[0].dispose();\n }\n // Remove from scene\n var index = this._scene.lensFlareSystems.indexOf(this);\n this._scene.lensFlareSystems.splice(index, 1);\n };\n LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {\n var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);\n var name = parsedLensFlareSystem.name || \"lensFlareSystem#\" + parsedLensFlareSystem.emitterId;\n var lensFlareSystem = new LensFlareSystem(name, emitter, scene);\n lensFlareSystem.id = parsedLensFlareSystem.id || name;\n lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;\n for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {\n var parsedFlare = parsedLensFlareSystem.flares[index];\n BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : \"\", lensFlareSystem);\n }\n return lensFlareSystem;\n };\n LensFlareSystem.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.id = this.id;\n serializationObject.name = this.name;\n serializationObject.emitterId = this.getEmitter().id;\n serializationObject.borderLimit = this.borderLimit;\n serializationObject.flares = [];\n for (var index = 0; index < this.lensFlares.length; index++) {\n var flare = this.lensFlares[index];\n serializationObject.flares.push({\n size: flare.size,\n position: flare.position,\n color: flare.color.asArray(),\n textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : \"\")\n });\n }\n return serializationObject;\n };\n return LensFlareSystem;\n }());\n BABYLON.LensFlareSystem = LensFlareSystem;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.lensFlareSystem.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This is a holder class for the physics joint created by the physics plugin.\n * It holds a set of functions to control the underlying joint.\n */\n var PhysicsJoint = /** @class */ (function () {\n function PhysicsJoint(type, jointData) {\n this.type = type;\n this.jointData = jointData;\n jointData.nativeParams = jointData.nativeParams || {};\n }\n Object.defineProperty(PhysicsJoint.prototype, \"physicsJoint\", {\n get: function () {\n return this._physicsJoint;\n },\n set: function (newJoint) {\n if (this._physicsJoint) {\n //remove from the wolrd\n }\n this._physicsJoint = newJoint;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PhysicsJoint.prototype, \"physicsPlugin\", {\n set: function (physicsPlugin) {\n this._physicsPlugin = physicsPlugin;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Execute a function that is physics-plugin specific.\n * @param {Function} func the function that will be executed.\n * It accepts two parameters: the physics world and the physics joint.\n */\n PhysicsJoint.prototype.executeNativeFunction = function (func) {\n func(this._physicsPlugin.world, this._physicsJoint);\n };\n //TODO check if the native joints are the same\n //Joint Types\n PhysicsJoint.DistanceJoint = 0;\n PhysicsJoint.HingeJoint = 1;\n PhysicsJoint.BallAndSocketJoint = 2;\n PhysicsJoint.WheelJoint = 3;\n PhysicsJoint.SliderJoint = 4;\n //OIMO\n PhysicsJoint.PrismaticJoint = 5;\n //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)\n PhysicsJoint.UniversalJoint = 6;\n PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;\n //Cannon\n //Similar to a Ball-Joint. Different in params\n PhysicsJoint.PointToPointJoint = 8;\n //Cannon only at the moment\n PhysicsJoint.SpringJoint = 9;\n PhysicsJoint.LockJoint = 10;\n return PhysicsJoint;\n }());\n BABYLON.PhysicsJoint = PhysicsJoint;\n /**\n * A class representing a physics distance joint.\n */\n var DistanceJoint = /** @class */ (function (_super) {\n __extends(DistanceJoint, _super);\n function DistanceJoint(jointData) {\n return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;\n }\n /**\n * Update the predefined distance.\n */\n DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {\n this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);\n };\n return DistanceJoint;\n }(PhysicsJoint));\n BABYLON.DistanceJoint = DistanceJoint;\n var MotorEnabledJoint = /** @class */ (function (_super) {\n __extends(MotorEnabledJoint, _super);\n function MotorEnabledJoint(type, jointData) {\n return _super.call(this, type, jointData) || this;\n }\n /**\n * Set the motor values.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param {number} force the force to apply\n * @param {number} maxForce max force for this motor.\n */\n MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {\n this._physicsPlugin.setMotor(this, force || 0, maxForce);\n };\n /**\n * Set the motor's limits.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n */\n MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {\n this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);\n };\n return MotorEnabledJoint;\n }(PhysicsJoint));\n BABYLON.MotorEnabledJoint = MotorEnabledJoint;\n /**\n * This class represents a single hinge physics joint\n */\n var HingeJoint = /** @class */ (function (_super) {\n __extends(HingeJoint, _super);\n function HingeJoint(jointData) {\n return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;\n }\n /**\n * Set the motor values.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param {number} force the force to apply\n * @param {number} maxForce max force for this motor.\n */\n HingeJoint.prototype.setMotor = function (force, maxForce) {\n this._physicsPlugin.setMotor(this, force || 0, maxForce);\n };\n /**\n * Set the motor's limits.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n */\n HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {\n this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);\n };\n return HingeJoint;\n }(MotorEnabledJoint));\n BABYLON.HingeJoint = HingeJoint;\n /**\n * This class represents a dual hinge physics joint (same as wheel joint)\n */\n var Hinge2Joint = /** @class */ (function (_super) {\n __extends(Hinge2Joint, _super);\n function Hinge2Joint(jointData) {\n return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;\n }\n /**\n * Set the motor values.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param {number} force the force to apply\n * @param {number} maxForce max force for this motor.\n * @param {motorIndex} the motor's index, 0 or 1.\n */\n Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {\n if (motorIndex === void 0) { motorIndex = 0; }\n this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);\n };\n /**\n * Set the motor limits.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param {number} upperLimit the upper limit\n * @param {number} lowerLimit lower limit\n * @param {motorIndex} the motor's index, 0 or 1.\n */\n Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {\n if (motorIndex === void 0) { motorIndex = 0; }\n this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);\n };\n return Hinge2Joint;\n }(MotorEnabledJoint));\n BABYLON.Hinge2Joint = Hinge2Joint;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.physicsJoint.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var PhysicsImpostor = /** @class */ (function () {\n function PhysicsImpostor(object, type, _options, _scene) {\n if (_options === void 0) { _options = { mass: 0 }; }\n var _this = this;\n this.object = object;\n this.type = type;\n this._options = _options;\n this._scene = _scene;\n this._bodyUpdateRequired = false;\n this._onBeforePhysicsStepCallbacks = new Array();\n this._onAfterPhysicsStepCallbacks = new Array();\n this._onPhysicsCollideCallbacks = [];\n this._deltaPosition = BABYLON.Vector3.Zero();\n this._isDisposed = false;\n //temp variables for parent rotation calculations\n //private _mats: Array = [new Matrix(), new Matrix()];\n this._tmpQuat = new BABYLON.Quaternion();\n this._tmpQuat2 = new BABYLON.Quaternion();\n /**\n * this function is executed by the physics engine.\n */\n this.beforeStep = function () {\n if (!_this._physicsEngine) {\n return;\n }\n _this.object.translate(_this._deltaPosition, -1);\n _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);\n _this.object.computeWorldMatrix(false);\n if (_this.object.parent && _this.object.rotationQuaternion) {\n _this.getParentsRotation();\n _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);\n }\n else {\n _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());\n }\n if (!_this._options.disableBidirectionalTransformation) {\n _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);\n }\n _this._onBeforePhysicsStepCallbacks.forEach(function (func) {\n func(_this);\n });\n };\n /**\n * this function is executed by the physics engine.\n */\n this.afterStep = function () {\n if (!_this._physicsEngine) {\n return;\n }\n _this._onAfterPhysicsStepCallbacks.forEach(function (func) {\n func(_this);\n });\n _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);\n // object has now its world rotation. needs to be converted to local.\n if (_this.object.parent && _this.object.rotationQuaternion) {\n _this.getParentsRotation();\n _this._tmpQuat.conjugateInPlace();\n _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);\n }\n // take the position set and make it the absolute position of this object.\n _this.object.setAbsolutePosition(_this.object.position);\n _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);\n _this.object.translate(_this._deltaPosition, 1);\n };\n /**\n * Legacy collision detection event support\n */\n this.onCollideEvent = null;\n //event and body object due to cannon's event-based architecture.\n this.onCollide = function (e) {\n if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {\n return;\n }\n if (!_this._physicsEngine) {\n return;\n }\n var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);\n if (otherImpostor) {\n // Legacy collision detection event support\n if (_this.onCollideEvent) {\n _this.onCollideEvent(_this, otherImpostor);\n }\n _this._onPhysicsCollideCallbacks.filter(function (obj) {\n return obj.otherImpostors.indexOf(otherImpostor) !== -1;\n }).forEach(function (obj) {\n obj.callback(_this, otherImpostor);\n });\n }\n };\n //sanity check!\n if (!this.object) {\n BABYLON.Tools.Error(\"No object was provided. A physics object is obligatory\");\n return;\n }\n //legacy support for old syntax.\n if (!this._scene && object.getScene) {\n this._scene = object.getScene();\n }\n if (!this._scene) {\n return;\n }\n this._physicsEngine = this._scene.getPhysicsEngine();\n if (!this._physicsEngine) {\n BABYLON.Tools.Error(\"Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.\");\n }\n else {\n //set the object's quaternion, if not set\n if (!this.object.rotationQuaternion) {\n if (this.object.rotation) {\n this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);\n }\n else {\n this.object.rotationQuaternion = new BABYLON.Quaternion();\n }\n }\n //default options params\n this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;\n this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;\n this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;\n this._joints = [];\n //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.\n if (!this.object.parent || this._options.ignoreParent) {\n this._init();\n }\n else if (this.object.parent.physicsImpostor) {\n BABYLON.Tools.Warn(\"You must affect impostors to children before affecting impostor to parent.\");\n }\n }\n }\n Object.defineProperty(PhysicsImpostor.prototype, \"isDisposed\", {\n get: function () {\n return this._isDisposed;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PhysicsImpostor.prototype, \"mass\", {\n get: function () {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;\n },\n set: function (value) {\n this.setMass(value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PhysicsImpostor.prototype, \"friction\", {\n get: function () {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;\n },\n set: function (value) {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PhysicsImpostor.prototype, \"restitution\", {\n get: function () {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;\n },\n set: function (value) {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * This function will completly initialize this impostor.\n * It will create a new body - but only if this mesh has no parent.\n * If it has, this impostor will not be used other than to define the impostor\n * of the child mesh.\n */\n PhysicsImpostor.prototype._init = function () {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.removeImpostor(this);\n this.physicsBody = null;\n this._parent = this._parent || this._getPhysicsParent();\n if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {\n this._physicsEngine.addImpostor(this);\n }\n };\n PhysicsImpostor.prototype._getPhysicsParent = function () {\n if (this.object.parent instanceof BABYLON.AbstractMesh) {\n var parentMesh = this.object.parent;\n return parentMesh.physicsImpostor;\n }\n return null;\n };\n /**\n * Should a new body be generated.\n */\n PhysicsImpostor.prototype.isBodyInitRequired = function () {\n return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);\n };\n PhysicsImpostor.prototype.setScalingUpdated = function (updated) {\n this.forceUpdate();\n };\n /**\n * Force a regeneration of this or the parent's impostor's body.\n * Use under cautious - This will remove all joints already implemented.\n */\n PhysicsImpostor.prototype.forceUpdate = function () {\n this._init();\n if (this.parent && !this._options.ignoreParent) {\n this.parent.forceUpdate();\n }\n };\n Object.defineProperty(PhysicsImpostor.prototype, \"physicsBody\", {\n /*public get mesh(): AbstractMesh {\n return this._mesh;\n }*/\n /**\n * Gets the body that holds this impostor. Either its own, or its parent.\n */\n get: function () {\n return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;\n },\n /**\n * Set the physics body. Used mainly by the physics engine/plugin\n */\n set: function (physicsBody) {\n if (this._physicsBody && this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);\n }\n this._physicsBody = physicsBody;\n this.resetUpdateFlags();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PhysicsImpostor.prototype, \"parent\", {\n get: function () {\n return !this._options.ignoreParent && this._parent ? this._parent : null;\n },\n set: function (value) {\n this._parent = value;\n },\n enumerable: true,\n configurable: true\n });\n PhysicsImpostor.prototype.resetUpdateFlags = function () {\n this._bodyUpdateRequired = false;\n };\n PhysicsImpostor.prototype.getObjectExtendSize = function () {\n if (this.object.getBoundingInfo) {\n var q = this.object.rotationQuaternion;\n //reset rotation\n this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;\n //calculate the world matrix with no rotation\n this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);\n var boundingInfo = this.object.getBoundingInfo();\n var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);\n //bring back the rotation\n this.object.rotationQuaternion = q;\n //calculate the world matrix with the new rotation\n this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);\n return size;\n }\n else {\n return PhysicsImpostor.DEFAULT_OBJECT_SIZE;\n }\n };\n PhysicsImpostor.prototype.getObjectCenter = function () {\n if (this.object.getBoundingInfo) {\n var boundingInfo = this.object.getBoundingInfo();\n return boundingInfo.boundingBox.centerWorld;\n }\n else {\n return this.object.position;\n }\n };\n /**\n * Get a specific parametes from the options parameter.\n */\n PhysicsImpostor.prototype.getParam = function (paramName) {\n return this._options[paramName];\n };\n /**\n * Sets a specific parameter in the options given to the physics plugin\n */\n PhysicsImpostor.prototype.setParam = function (paramName, value) {\n this._options[paramName] = value;\n this._bodyUpdateRequired = true;\n };\n /**\n * Specifically change the body's mass option. Won't recreate the physics body object\n */\n PhysicsImpostor.prototype.setMass = function (mass) {\n if (this.getParam(\"mass\") !== mass) {\n this.setParam(\"mass\", mass);\n }\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);\n }\n };\n PhysicsImpostor.prototype.getLinearVelocity = function () {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();\n };\n PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);\n }\n };\n PhysicsImpostor.prototype.getAngularVelocity = function () {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();\n };\n PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);\n }\n };\n /**\n * Execute a function with the physics plugin native code.\n * Provide a function the will have two variables - the world object and the physics body object.\n */\n PhysicsImpostor.prototype.executeNativeFunction = function (func) {\n if (this._physicsEngine) {\n func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);\n }\n };\n /**\n * Register a function that will be executed before the physics world is stepping forward.\n */\n PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {\n this._onBeforePhysicsStepCallbacks.push(func);\n };\n PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {\n var index = this._onBeforePhysicsStepCallbacks.indexOf(func);\n if (index > -1) {\n this._onBeforePhysicsStepCallbacks.splice(index, 1);\n }\n else {\n BABYLON.Tools.Warn(\"Function to remove was not found\");\n }\n };\n /**\n * Register a function that will be executed after the physics step\n */\n PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {\n this._onAfterPhysicsStepCallbacks.push(func);\n };\n PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {\n var index = this._onAfterPhysicsStepCallbacks.indexOf(func);\n if (index > -1) {\n this._onAfterPhysicsStepCallbacks.splice(index, 1);\n }\n else {\n BABYLON.Tools.Warn(\"Function to remove was not found\");\n }\n };\n /**\n * register a function that will be executed when this impostor collides against a different body.\n */\n PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {\n var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];\n this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });\n };\n PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {\n var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];\n var index = -1;\n var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {\n if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {\n // chcek the arrays match\n var sameList = cbDef.otherImpostors.every(function (impostor) {\n return collidedAgainstList.indexOf(impostor) > -1;\n });\n if (sameList) {\n index = idx;\n }\n return sameList;\n }\n return false;\n });\n if (found) {\n this._onPhysicsCollideCallbacks.splice(index, 1);\n }\n else {\n BABYLON.Tools.Warn(\"Function to remove was not found\");\n }\n };\n PhysicsImpostor.prototype.getParentsRotation = function () {\n var parent = this.object.parent;\n this._tmpQuat.copyFromFloats(0, 0, 0, 1);\n while (parent) {\n if (parent.rotationQuaternion) {\n this._tmpQuat2.copyFrom(parent.rotationQuaternion);\n }\n else {\n BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);\n }\n this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);\n parent = parent.parent;\n }\n return this._tmpQuat;\n };\n /**\n * Apply a force\n */\n PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);\n }\n return this;\n };\n /**\n * Apply an impulse\n */\n PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);\n }\n return this;\n };\n /**\n * A help function to create a joint.\n */\n PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {\n var joint = new BABYLON.PhysicsJoint(jointType, jointData);\n this.addJoint(otherImpostor, joint);\n return this;\n };\n /**\n * Add a joint to this impostor with a different impostor.\n */\n PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {\n this._joints.push({\n otherImpostor: otherImpostor,\n joint: joint\n });\n if (this._physicsEngine) {\n this._physicsEngine.addJoint(this, otherImpostor, joint);\n }\n return this;\n };\n /**\n * Will keep this body still, in a sleep mode.\n */\n PhysicsImpostor.prototype.sleep = function () {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().sleepBody(this);\n }\n return this;\n };\n /**\n * Wake the body up.\n */\n PhysicsImpostor.prototype.wakeUp = function () {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);\n }\n return this;\n };\n PhysicsImpostor.prototype.clone = function (newObject) {\n if (!newObject)\n return null;\n return new PhysicsImpostor(newObject, this.type, this._options, this._scene);\n };\n PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {\n var _this = this;\n //no dispose if no physics engine is available.\n if (!this._physicsEngine) {\n return;\n }\n this._joints.forEach(function (j) {\n if (_this._physicsEngine) {\n _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);\n }\n });\n //dispose the physics body\n this._physicsEngine.removeImpostor(this);\n if (this.parent) {\n this.parent.forceUpdate();\n }\n else {\n /*this._object.getChildMeshes().forEach(function(mesh) {\n if (mesh.physicsImpostor) {\n if (disposeChildren) {\n mesh.physicsImpostor.dispose();\n mesh.physicsImpostor = null;\n }\n }\n })*/\n }\n this._isDisposed = true;\n };\n PhysicsImpostor.prototype.setDeltaPosition = function (position) {\n this._deltaPosition.copyFrom(position);\n };\n PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {\n if (!this._deltaRotation) {\n this._deltaRotation = new BABYLON.Quaternion();\n }\n this._deltaRotation.copyFrom(rotation);\n this._deltaRotationConjugated = this._deltaRotation.conjugate();\n };\n PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);\n }\n return this;\n };\n PhysicsImpostor.prototype.getRadius = function () {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;\n };\n /**\n * Sync a bone with this impostor\n * @param bone The bone to sync to the impostor.\n * @param boneMesh The mesh that the bone is influencing.\n * @param jointPivot The pivot of the joint / bone in local space.\n * @param distToJoint Optional distance from the impostor to the joint.\n * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.\n */\n PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {\n var tempVec = PhysicsImpostor._tmpVecs[0];\n var mesh = this.object;\n if (mesh.rotationQuaternion) {\n if (adjustRotation) {\n var tempQuat = PhysicsImpostor._tmpQuat;\n mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);\n bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);\n }\n else {\n bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);\n }\n }\n tempVec.x = 0;\n tempVec.y = 0;\n tempVec.z = 0;\n if (jointPivot) {\n tempVec.x = jointPivot.x;\n tempVec.y = jointPivot.y;\n tempVec.z = jointPivot.z;\n bone.getDirectionToRef(tempVec, boneMesh, tempVec);\n if (distToJoint === undefined || distToJoint === null) {\n distToJoint = jointPivot.length();\n }\n tempVec.x *= distToJoint;\n tempVec.y *= distToJoint;\n tempVec.z *= distToJoint;\n }\n if (bone.getParent()) {\n tempVec.addInPlace(mesh.getAbsolutePosition());\n bone.setAbsolutePosition(tempVec, boneMesh);\n }\n else {\n boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());\n boneMesh.position.x -= tempVec.x;\n boneMesh.position.y -= tempVec.y;\n boneMesh.position.z -= tempVec.z;\n }\n };\n /**\n * Sync impostor to a bone\n * @param bone The bone that the impostor will be synced to.\n * @param boneMesh The mesh that the bone is influencing.\n * @param jointPivot The pivot of the joint / bone in local space.\n * @param distToJoint Optional distance from the impostor to the joint.\n * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.\n * @param boneAxis Optional vector3 axis the bone is aligned with\n */\n PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {\n var mesh = this.object;\n if (mesh.rotationQuaternion) {\n if (adjustRotation) {\n var tempQuat = PhysicsImpostor._tmpQuat;\n bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);\n tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);\n }\n else {\n bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);\n }\n }\n var pos = PhysicsImpostor._tmpVecs[0];\n var boneDir = PhysicsImpostor._tmpVecs[1];\n if (!boneAxis) {\n boneAxis = PhysicsImpostor._tmpVecs[2];\n boneAxis.x = 0;\n boneAxis.y = 1;\n boneAxis.z = 0;\n }\n bone.getDirectionToRef(boneAxis, boneMesh, boneDir);\n bone.getAbsolutePositionToRef(boneMesh, pos);\n if ((distToJoint === undefined || distToJoint === null) && jointPivot) {\n distToJoint = jointPivot.length();\n }\n if (distToJoint !== undefined && distToJoint !== null) {\n pos.x += boneDir.x * distToJoint;\n pos.y += boneDir.y * distToJoint;\n pos.z += boneDir.z * distToJoint;\n }\n mesh.setAbsolutePosition(pos);\n };\n PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);\n PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();\n PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();\n //Impostor types\n PhysicsImpostor.NoImpostor = 0;\n PhysicsImpostor.SphereImpostor = 1;\n PhysicsImpostor.BoxImpostor = 2;\n PhysicsImpostor.PlaneImpostor = 3;\n PhysicsImpostor.MeshImpostor = 4;\n PhysicsImpostor.CylinderImpostor = 7;\n PhysicsImpostor.ParticleImpostor = 8;\n PhysicsImpostor.HeightmapImpostor = 9;\n return PhysicsImpostor;\n }());\n BABYLON.PhysicsImpostor = PhysicsImpostor;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.physicsImpostor.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var PhysicsEngine = /** @class */ (function () {\n function PhysicsEngine(gravity, _physicsPlugin) {\n if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }\n this._physicsPlugin = _physicsPlugin;\n //new methods and parameters\n this._impostors = [];\n this._joints = [];\n if (!this._physicsPlugin.isSupported()) {\n throw new Error(\"Physics Engine \" + this._physicsPlugin.name + \" cannot be found. \"\n + \"Please make sure it is included.\");\n }\n gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);\n this.setGravity(gravity);\n this.setTimeStep();\n }\n PhysicsEngine.prototype.setGravity = function (gravity) {\n this.gravity = gravity;\n this._physicsPlugin.setGravity(this.gravity);\n };\n /**\n * Set the time step of the physics engine.\n * default is 1/60.\n * To slow it down, enter 1/600 for example.\n * To speed it up, 1/30\n * @param {number} newTimeStep the new timestep to apply to this world.\n */\n PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {\n if (newTimeStep === void 0) { newTimeStep = 1 / 60; }\n this._physicsPlugin.setTimeStep(newTimeStep);\n };\n /**\n * Get the time step of the physics engine.\n */\n PhysicsEngine.prototype.getTimeStep = function () {\n return this._physicsPlugin.getTimeStep();\n };\n PhysicsEngine.prototype.dispose = function () {\n this._impostors.forEach(function (impostor) {\n impostor.dispose();\n });\n this._physicsPlugin.dispose();\n };\n PhysicsEngine.prototype.getPhysicsPluginName = function () {\n return this._physicsPlugin.name;\n };\n /**\n * Adding a new impostor for the impostor tracking.\n * This will be done by the impostor itself.\n * @param {PhysicsImpostor} impostor the impostor to add\n */\n PhysicsEngine.prototype.addImpostor = function (impostor) {\n impostor.uniqueId = this._impostors.push(impostor);\n //if no parent, generate the body\n if (!impostor.parent) {\n this._physicsPlugin.generatePhysicsBody(impostor);\n }\n };\n /**\n * Remove an impostor from the engine.\n * This impostor and its mesh will not longer be updated by the physics engine.\n * @param {PhysicsImpostor} impostor the impostor to remove\n */\n PhysicsEngine.prototype.removeImpostor = function (impostor) {\n var index = this._impostors.indexOf(impostor);\n if (index > -1) {\n var removed = this._impostors.splice(index, 1);\n //Is it needed?\n if (removed.length) {\n //this will also remove it from the world.\n removed[0].physicsBody = null;\n }\n }\n };\n /**\n * Add a joint to the physics engine\n * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.\n * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint\n * @param {PhysicsJoint} the joint that will connect both impostors.\n */\n PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {\n var impostorJoint = {\n mainImpostor: mainImpostor,\n connectedImpostor: connectedImpostor,\n joint: joint\n };\n joint.physicsPlugin = this._physicsPlugin;\n this._joints.push(impostorJoint);\n this._physicsPlugin.generateJoint(impostorJoint);\n };\n PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {\n var matchingJoints = this._joints.filter(function (impostorJoint) {\n return (impostorJoint.connectedImpostor === connectedImpostor\n && impostorJoint.joint === joint\n && impostorJoint.mainImpostor === mainImpostor);\n });\n if (matchingJoints.length) {\n this._physicsPlugin.removeJoint(matchingJoints[0]);\n //TODO remove it from the list as well\n }\n };\n /**\n * Called by the scene. no need to call it.\n */\n PhysicsEngine.prototype._step = function (delta) {\n var _this = this;\n //check if any mesh has no body / requires an update\n this._impostors.forEach(function (impostor) {\n if (impostor.isBodyInitRequired()) {\n _this._physicsPlugin.generatePhysicsBody(impostor);\n }\n });\n if (delta > 0.1) {\n delta = 0.1;\n }\n else if (delta <= 0) {\n delta = 1.0 / 60.0;\n }\n this._physicsPlugin.executeStep(delta, this._impostors);\n };\n PhysicsEngine.prototype.getPhysicsPlugin = function () {\n return this._physicsPlugin;\n };\n PhysicsEngine.prototype.getImpostors = function () {\n return this._impostors;\n };\n PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {\n for (var i = 0; i < this._impostors.length; ++i) {\n if (this._impostors[i].object === object) {\n return this._impostors[i];\n }\n }\n return null;\n };\n PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {\n for (var i = 0; i < this._impostors.length; ++i) {\n if (this._impostors[i].physicsBody === body) {\n return this._impostors[i];\n }\n }\n return null;\n };\n // Statics\n PhysicsEngine.Epsilon = 0.001;\n return PhysicsEngine;\n }());\n BABYLON.PhysicsEngine = PhysicsEngine;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.physicsEngine.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var PhysicsHelper = /** @class */ (function () {\n function PhysicsHelper(scene) {\n this._scene = scene;\n this._physicsEngine = this._scene.getPhysicsEngine();\n if (!this._physicsEngine) {\n BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');\n }\n }\n /**\n * @param {Vector3} origin the origin of the explosion\n * @param {number} radius the explosion radius\n * @param {number} strength the explosion strength\n * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant\n */\n PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {\n if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }\n if (!this._physicsEngine) {\n BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');\n return null;\n }\n var impostors = this._physicsEngine.getImpostors();\n if (impostors.length === 0) {\n return null;\n }\n var event = new PhysicsRadialExplosionEvent(this._scene);\n impostors.forEach(function (impostor) {\n var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);\n if (!impostorForceAndContactPoint) {\n return;\n }\n impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);\n });\n event.dispose(false);\n return event;\n };\n /**\n * @param {Vector3} origin the origin of the explosion\n * @param {number} radius the explosion radius\n * @param {number} strength the explosion strength\n * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant\n */\n PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {\n if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }\n if (!this._physicsEngine) {\n BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');\n return null;\n }\n var impostors = this._physicsEngine.getImpostors();\n if (impostors.length === 0) {\n return null;\n }\n var event = new PhysicsRadialExplosionEvent(this._scene);\n impostors.forEach(function (impostor) {\n var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);\n if (!impostorForceAndContactPoint) {\n return;\n }\n impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);\n });\n event.dispose(false);\n return event;\n };\n /**\n * @param {Vector3} origin the origin of the explosion\n * @param {number} radius the explosion radius\n * @param {number} strength the explosion strength\n * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant\n */\n PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {\n if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }\n if (!this._physicsEngine) {\n BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');\n return null;\n }\n var impostors = this._physicsEngine.getImpostors();\n if (impostors.length === 0) {\n return null;\n }\n var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);\n event.dispose(false);\n return event;\n };\n /**\n * @param {Vector3} origin the origin of the updraft\n * @param {number} radius the radius of the updraft\n * @param {number} strength the strength of the updraft\n * @param {number} height the height of the updraft\n * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center\n */\n PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {\n if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }\n if (!this._physicsEngine) {\n BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');\n return null;\n }\n if (this._physicsEngine.getImpostors().length === 0) {\n return null;\n }\n var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);\n event.dispose(false);\n return event;\n };\n /**\n * @param {Vector3} origin the of the vortex\n * @param {number} radius the radius of the vortex\n * @param {number} strength the strength of the vortex\n * @param {number} height the height of the vortex\n */\n PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {\n if (!this._physicsEngine) {\n BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');\n return null;\n }\n if (this._physicsEngine.getImpostors().length === 0) {\n return null;\n }\n var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);\n event.dispose(false);\n return event;\n };\n return PhysicsHelper;\n }());\n BABYLON.PhysicsHelper = PhysicsHelper;\n /***** Radial explosion *****/\n var PhysicsRadialExplosionEvent = /** @class */ (function () {\n function PhysicsRadialExplosionEvent(scene) {\n this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable\n this._rays = [];\n this._dataFetched = false; // check if the data has been fetched. If not, do cleanup\n this._scene = scene;\n }\n /**\n * Returns the data related to the radial explosion event (sphere & rays).\n * @returns {PhysicsRadialExplosionEventData}\n */\n PhysicsRadialExplosionEvent.prototype.getData = function () {\n this._dataFetched = true;\n return {\n sphere: this._sphere,\n rays: this._rays,\n };\n };\n /**\n * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.\n * @param impostor\n * @param {Vector3} origin the origin of the explosion\n * @param {number} radius the explosion radius\n * @param {number} strength the explosion strength\n * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear\n * @returns {Nullable}\n */\n PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {\n if (impostor.mass === 0) {\n return null;\n }\n if (!this._intersectsWithSphere(impostor, origin, radius)) {\n return null;\n }\n if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {\n return null;\n }\n var impostorObjectCenter = impostor.getObjectCenter();\n var direction = impostorObjectCenter.subtract(origin);\n var ray = new BABYLON.Ray(origin, direction, radius);\n this._rays.push(ray);\n var hit = ray.intersectsMesh(impostor.object);\n var contactPoint = hit.pickedPoint;\n if (!contactPoint) {\n return null;\n }\n var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);\n if (distanceFromOrigin > radius) {\n return null;\n }\n var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant\n ? strength\n : strength * (1 - (distanceFromOrigin / radius));\n var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);\n return { force: force, contactPoint: contactPoint };\n };\n /**\n * Disposes the sphere.\n * @param {bolean} force\n */\n PhysicsRadialExplosionEvent.prototype.dispose = function (force) {\n var _this = this;\n if (force === void 0) { force = true; }\n if (force) {\n this._sphere.dispose();\n }\n else {\n setTimeout(function () {\n if (!_this._dataFetched) {\n _this._sphere.dispose();\n }\n }, 0);\n }\n };\n /*** Helpers ***/\n PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {\n if (!this._sphere) {\n this._sphere = BABYLON.MeshBuilder.CreateSphere(\"radialExplosionEventSphere\", this._sphereOptions, this._scene);\n this._sphere.isVisible = false;\n }\n };\n PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {\n var impostorObject = impostor.object;\n this._prepareSphere();\n this._sphere.position = origin;\n this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);\n this._sphere._updateBoundingInfo();\n this._sphere.computeWorldMatrix(true);\n return this._sphere.intersectsMesh(impostorObject, true);\n };\n return PhysicsRadialExplosionEvent;\n }());\n BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;\n /***** Gravitational Field *****/\n var PhysicsGravitationalFieldEvent = /** @class */ (function () {\n function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {\n if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }\n this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup\n this._physicsHelper = physicsHelper;\n this._scene = scene;\n this._origin = origin;\n this._radius = radius;\n this._strength = strength;\n this._falloff = falloff;\n this._tickCallback = this._tick.bind(this);\n }\n /**\n * Returns the data related to the gravitational field event (sphere).\n * @returns {PhysicsGravitationalFieldEventData}\n */\n PhysicsGravitationalFieldEvent.prototype.getData = function () {\n this._dataFetched = true;\n return {\n sphere: this._sphere,\n };\n };\n /**\n * Enables the gravitational field.\n */\n PhysicsGravitationalFieldEvent.prototype.enable = function () {\n this._tickCallback.call(this);\n this._scene.registerBeforeRender(this._tickCallback);\n };\n /**\n * Disables the gravitational field.\n */\n PhysicsGravitationalFieldEvent.prototype.disable = function () {\n this._scene.unregisterBeforeRender(this._tickCallback);\n };\n /**\n * Disposes the sphere.\n * @param {bolean} force\n */\n PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {\n var _this = this;\n if (force === void 0) { force = true; }\n if (force) {\n this._sphere.dispose();\n }\n else {\n setTimeout(function () {\n if (!_this._dataFetched) {\n _this._sphere.dispose();\n }\n }, 0);\n }\n };\n PhysicsGravitationalFieldEvent.prototype._tick = function () {\n // Since the params won't change, we fetch the event only once\n if (this._sphere) {\n this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);\n }\n else {\n var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);\n if (radialExplosionEvent) {\n this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');\n }\n }\n };\n return PhysicsGravitationalFieldEvent;\n }());\n BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;\n /***** Updraft *****/\n var PhysicsUpdraftEvent = /** @class */ (function () {\n function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {\n this._scene = _scene;\n this._origin = _origin;\n this._radius = _radius;\n this._strength = _strength;\n this._height = _height;\n this._updraftMode = _updraftMode;\n this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder\n this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular\n this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom\n this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup\n this._physicsEngine = this._scene.getPhysicsEngine();\n this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);\n this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);\n if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {\n this._originDirection = this._origin.subtract(this._originTop).normalize();\n }\n this._tickCallback = this._tick.bind(this);\n }\n /**\n * Returns the data related to the updraft event (cylinder).\n * @returns {PhysicsUpdraftEventData}\n */\n PhysicsUpdraftEvent.prototype.getData = function () {\n this._dataFetched = true;\n return {\n cylinder: this._cylinder,\n };\n };\n /**\n * Enables the updraft.\n */\n PhysicsUpdraftEvent.prototype.enable = function () {\n this._tickCallback.call(this);\n this._scene.registerBeforeRender(this._tickCallback);\n };\n /**\n * Disables the cortex.\n */\n PhysicsUpdraftEvent.prototype.disable = function () {\n this._scene.unregisterBeforeRender(this._tickCallback);\n };\n /**\n * Disposes the sphere.\n * @param {bolean} force\n */\n PhysicsUpdraftEvent.prototype.dispose = function (force) {\n var _this = this;\n if (force === void 0) { force = true; }\n if (force) {\n this._cylinder.dispose();\n }\n else {\n setTimeout(function () {\n if (!_this._dataFetched) {\n _this._cylinder.dispose();\n }\n }, 0);\n }\n };\n PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {\n if (impostor.mass === 0) {\n return null;\n }\n if (!this._intersectsWithCylinder(impostor)) {\n return null;\n }\n var impostorObjectCenter = impostor.getObjectCenter();\n if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {\n var direction = this._originDirection;\n }\n else {\n var direction = impostorObjectCenter.subtract(this._originTop);\n }\n var multiplier = this._strength * -1;\n var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);\n return { force: force, contactPoint: impostorObjectCenter };\n };\n PhysicsUpdraftEvent.prototype._tick = function () {\n var _this = this;\n this._physicsEngine.getImpostors().forEach(function (impostor) {\n var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);\n if (!impostorForceAndContactPoint) {\n return;\n }\n impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);\n });\n };\n /*** Helpers ***/\n PhysicsUpdraftEvent.prototype._prepareCylinder = function () {\n if (!this._cylinder) {\n this._cylinder = BABYLON.MeshBuilder.CreateCylinder(\"updraftEventCylinder\", {\n height: this._height,\n diameter: this._radius * 2,\n }, this._scene);\n this._cylinder.isVisible = false;\n }\n };\n PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {\n var impostorObject = impostor.object;\n this._prepareCylinder();\n this._cylinder.position = this._cylinderPosition;\n return this._cylinder.intersectsMesh(impostorObject, true);\n };\n return PhysicsUpdraftEvent;\n }());\n BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;\n /***** Vortex *****/\n var PhysicsVortexEvent = /** @class */ (function () {\n function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {\n this._scene = _scene;\n this._origin = _origin;\n this._radius = _radius;\n this._strength = _strength;\n this._height = _height;\n this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder\n this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in\n this._updraftMultiplier = 0.02;\n this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom\n this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup\n this._physicsEngine = this._scene.getPhysicsEngine();\n this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);\n this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);\n this._tickCallback = this._tick.bind(this);\n }\n /**\n * Returns the data related to the vortex event (cylinder).\n * @returns {PhysicsVortexEventData}\n */\n PhysicsVortexEvent.prototype.getData = function () {\n this._dataFetched = true;\n return {\n cylinder: this._cylinder,\n };\n };\n /**\n * Enables the vortex.\n */\n PhysicsVortexEvent.prototype.enable = function () {\n this._tickCallback.call(this);\n this._scene.registerBeforeRender(this._tickCallback);\n };\n /**\n * Disables the cortex.\n */\n PhysicsVortexEvent.prototype.disable = function () {\n this._scene.unregisterBeforeRender(this._tickCallback);\n };\n /**\n * Disposes the sphere.\n * @param {bolean} force\n */\n PhysicsVortexEvent.prototype.dispose = function (force) {\n var _this = this;\n if (force === void 0) { force = true; }\n if (force) {\n this._cylinder.dispose();\n }\n else {\n setTimeout(function () {\n if (!_this._dataFetched) {\n _this._cylinder.dispose();\n }\n }, 0);\n }\n };\n PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {\n if (impostor.mass === 0) {\n return null;\n }\n if (!this._intersectsWithCylinder(impostor)) {\n return null;\n }\n if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {\n return null;\n }\n var impostorObjectCenter = impostor.getObjectCenter();\n var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)\n var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);\n var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);\n var hit = ray.intersectsMesh(impostor.object);\n var contactPoint = hit.pickedPoint;\n if (!contactPoint) {\n return null;\n }\n var absoluteDistanceFromOrigin = hit.distance / this._radius;\n var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();\n var directionToOrigin = contactPoint.normalize();\n if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {\n directionToOrigin = directionToOrigin.negate();\n }\n // TODO: find a more physically based solution\n if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {\n var forceX = directionToOrigin.x * this._strength / 8;\n var forceY = directionToOrigin.y * this._updraftMultiplier;\n var forceZ = directionToOrigin.z * this._strength / 8;\n }\n else {\n var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;\n var forceY = this._originTop.y * this._updraftMultiplier;\n var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;\n }\n var force = new BABYLON.Vector3(forceX, forceY, forceZ);\n force = force.multiplyByFloats(this._strength, this._strength, this._strength);\n return { force: force, contactPoint: impostorObjectCenter };\n };\n PhysicsVortexEvent.prototype._tick = function () {\n var _this = this;\n this._physicsEngine.getImpostors().forEach(function (impostor) {\n var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);\n if (!impostorForceAndContactPoint) {\n return;\n }\n impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);\n });\n };\n /*** Helpers ***/\n PhysicsVortexEvent.prototype._prepareCylinder = function () {\n if (!this._cylinder) {\n this._cylinder = BABYLON.MeshBuilder.CreateCylinder(\"vortexEventCylinder\", {\n height: this._height,\n diameter: this._radius * 2,\n }, this._scene);\n this._cylinder.isVisible = false;\n }\n };\n PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {\n var impostorObject = impostor.object;\n this._prepareCylinder();\n this._cylinder.position = this._cylinderPosition;\n return this._cylinder.intersectsMesh(impostorObject, true);\n };\n return PhysicsVortexEvent;\n }());\n BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;\n /***** Enums *****/\n /**\n * The strenght of the force in correspondence to the distance of the affected object\n */\n var PhysicsRadialImpulseFalloff;\n (function (PhysicsRadialImpulseFalloff) {\n /** Defines that impulse is constant in strength across it's whole radius */\n PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff[\"Constant\"] = 0] = \"Constant\";\n /** DEfines that impulse gets weaker if it's further from the origin */\n PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff[\"Linear\"] = 1] = \"Linear\";\n })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));\n /**\n * The strenght of the force in correspondence to the distance of the affected object\n */\n var PhysicsUpdraftMode;\n (function (PhysicsUpdraftMode) {\n /** Defines that the upstream forces will pull towards the top center of the cylinder */\n PhysicsUpdraftMode[PhysicsUpdraftMode[\"Center\"] = 0] = \"Center\";\n /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */\n PhysicsUpdraftMode[PhysicsUpdraftMode[\"Perpendicular\"] = 1] = \"Perpendicular\";\n })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.physicsHelper.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var CannonJSPlugin = /** @class */ (function () {\n function CannonJSPlugin(_useDeltaForWorldStep, iterations) {\n if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }\n if (iterations === void 0) { iterations = 10; }\n this._useDeltaForWorldStep = _useDeltaForWorldStep;\n this.name = \"CannonJSPlugin\";\n this._physicsMaterials = new Array();\n this._fixedTimeStep = 1 / 60;\n //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html\n this.BJSCANNON = CANNON;\n this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);\n this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);\n this._tmpPosition = BABYLON.Vector3.Zero();\n this._tmpDeltaPosition = BABYLON.Vector3.Zero();\n this._tmpUnityRotation = new BABYLON.Quaternion();\n if (!this.isSupported()) {\n BABYLON.Tools.Error(\"CannonJS is not available. Please make sure you included the js file.\");\n return;\n }\n this._extendNamespace();\n this.world = new this.BJSCANNON.World();\n this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();\n this.world.solver.iterations = iterations;\n }\n CannonJSPlugin.prototype.setGravity = function (gravity) {\n this.world.gravity.copy(gravity);\n };\n CannonJSPlugin.prototype.setTimeStep = function (timeStep) {\n this._fixedTimeStep = timeStep;\n };\n CannonJSPlugin.prototype.getTimeStep = function () {\n return this._fixedTimeStep;\n };\n CannonJSPlugin.prototype.executeStep = function (delta, impostors) {\n this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);\n };\n CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {\n var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);\n var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);\n impostor.physicsBody.applyImpulse(impulse, worldPoint);\n };\n CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {\n var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);\n var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);\n impostor.physicsBody.applyForce(impulse, worldPoint);\n };\n CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {\n //parent-child relationship. Does this impostor has a parent impostor?\n if (impostor.parent) {\n if (impostor.physicsBody) {\n this.removePhysicsBody(impostor);\n //TODO is that needed?\n impostor.forceUpdate();\n }\n return;\n }\n //should a new body be created for this impostor?\n if (impostor.isBodyInitRequired()) {\n var shape = this._createShape(impostor);\n //unregister events, if body is being changed\n var oldBody = impostor.physicsBody;\n if (oldBody) {\n this.removePhysicsBody(impostor);\n }\n //create the body and material\n var material = this._addMaterial(\"mat-\" + impostor.uniqueId, impostor.getParam(\"friction\"), impostor.getParam(\"restitution\"));\n var bodyCreationObject = {\n mass: impostor.getParam(\"mass\"),\n material: material\n };\n // A simple extend, in case native options were used.\n var nativeOptions = impostor.getParam(\"nativeOptions\");\n for (var key in nativeOptions) {\n if (nativeOptions.hasOwnProperty(key)) {\n bodyCreationObject[key] = nativeOptions[key];\n }\n }\n impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);\n impostor.physicsBody.addEventListener(\"collide\", impostor.onCollide);\n this.world.addEventListener(\"preStep\", impostor.beforeStep);\n this.world.addEventListener(\"postStep\", impostor.afterStep);\n impostor.physicsBody.addShape(shape);\n this.world.add(impostor.physicsBody);\n //try to keep the body moving in the right direction by taking old properties.\n //Should be tested!\n if (oldBody) {\n ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {\n impostor.physicsBody[param].copy(oldBody[param]);\n });\n }\n this._processChildMeshes(impostor);\n }\n //now update the body's transformation\n this._updatePhysicsBodyTransformation(impostor);\n };\n CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {\n var _this = this;\n var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];\n var currentRotation = mainImpostor.object.rotationQuaternion;\n if (meshChildren.length) {\n var processMesh = function (localPosition, mesh) {\n if (!currentRotation || !mesh.rotationQuaternion) {\n return;\n }\n var childImpostor = mesh.getPhysicsImpostor();\n if (childImpostor) {\n var parent = childImpostor.parent;\n if (parent !== mainImpostor) {\n var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());\n var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));\n if (childImpostor.physicsBody) {\n _this.removePhysicsBody(childImpostor);\n childImpostor.physicsBody = null;\n }\n childImpostor.parent = mainImpostor;\n childImpostor.resetUpdateFlags();\n mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new _this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new _this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));\n //Add the mass of the children.\n mainImpostor.physicsBody.mass += childImpostor.getParam(\"mass\");\n }\n }\n currentRotation.multiplyInPlace(mesh.rotationQuaternion);\n mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));\n };\n meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));\n }\n };\n CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {\n impostor.physicsBody.removeEventListener(\"collide\", impostor.onCollide);\n this.world.removeEventListener(\"preStep\", impostor.beforeStep);\n this.world.removeEventListener(\"postStep\", impostor.afterStep);\n this.world.remove(impostor.physicsBody);\n };\n CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {\n var mainBody = impostorJoint.mainImpostor.physicsBody;\n var connectedBody = impostorJoint.connectedImpostor.physicsBody;\n if (!mainBody || !connectedBody) {\n return;\n }\n var constraint;\n var jointData = impostorJoint.joint.jointData;\n //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html\n var constraintData = {\n pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,\n pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,\n axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,\n axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,\n maxForce: jointData.nativeParams.maxForce,\n collideConnected: !!jointData.collision\n };\n switch (impostorJoint.joint.type) {\n case BABYLON.PhysicsJoint.HingeJoint:\n case BABYLON.PhysicsJoint.Hinge2Joint:\n constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);\n break;\n case BABYLON.PhysicsJoint.DistanceJoint:\n constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);\n break;\n case BABYLON.PhysicsJoint.SpringJoint:\n var springData = jointData;\n constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {\n restLength: springData.length,\n stiffness: springData.stiffness,\n damping: springData.damping,\n localAnchorA: constraintData.pivotA,\n localAnchorB: constraintData.pivotB\n });\n break;\n case BABYLON.PhysicsJoint.LockJoint:\n constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);\n break;\n case BABYLON.PhysicsJoint.PointToPointJoint:\n case BABYLON.PhysicsJoint.BallAndSocketJoint:\n default:\n constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);\n break;\n }\n //set the collideConnected flag after the creation, since DistanceJoint ignores it.\n constraint.collideConnected = !!jointData.collision;\n impostorJoint.joint.physicsJoint = constraint;\n //don't add spring as constraint, as it is not one.\n if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {\n this.world.addConstraint(constraint);\n }\n else {\n impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {\n constraint.applyForce();\n });\n }\n };\n CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {\n this.world.removeConstraint(impostorJoint.joint.physicsJoint);\n };\n CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {\n var index;\n var mat;\n for (index = 0; index < this._physicsMaterials.length; index++) {\n mat = this._physicsMaterials[index];\n if (mat.friction === friction && mat.restitution === restitution) {\n return mat;\n }\n }\n var currentMat = new this.BJSCANNON.Material(name);\n currentMat.friction = friction;\n currentMat.restitution = restitution;\n this._physicsMaterials.push(currentMat);\n return currentMat;\n };\n CannonJSPlugin.prototype._checkWithEpsilon = function (value) {\n return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;\n };\n CannonJSPlugin.prototype._createShape = function (impostor) {\n var object = impostor.object;\n var returnValue;\n var extendSize = impostor.getObjectExtendSize();\n switch (impostor.type) {\n case BABYLON.PhysicsImpostor.SphereImpostor:\n var radiusX = extendSize.x;\n var radiusY = extendSize.y;\n var radiusZ = extendSize.z;\n returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);\n break;\n //TMP also for cylinder - TODO Cannon supports cylinder natively.\n case BABYLON.PhysicsImpostor.CylinderImpostor:\n returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);\n break;\n case BABYLON.PhysicsImpostor.BoxImpostor:\n var box = extendSize.scale(0.5);\n returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));\n break;\n case BABYLON.PhysicsImpostor.PlaneImpostor:\n BABYLON.Tools.Warn(\"Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead\");\n returnValue = new this.BJSCANNON.Plane();\n break;\n case BABYLON.PhysicsImpostor.MeshImpostor:\n // should transform the vertex data to world coordinates!!\n var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];\n var rawFaces = object.getIndices ? object.getIndices() : [];\n if (!rawVerts)\n return;\n // get only scale! so the object could transform correctly.\n var oldPosition = object.position.clone();\n var oldRotation = object.rotation && object.rotation.clone();\n var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();\n object.position.copyFromFloats(0, 0, 0);\n object.rotation && object.rotation.copyFromFloats(0, 0, 0);\n object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());\n object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();\n var transform = object.computeWorldMatrix(true);\n // convert rawVerts to object space\n var temp = new Array();\n var index;\n for (index = 0; index < rawVerts.length; index += 3) {\n BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);\n }\n BABYLON.Tools.Warn(\"MeshImpostor only collides against spheres.\");\n returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);\n //now set back the transformation!\n object.position.copyFrom(oldPosition);\n oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);\n oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);\n break;\n case BABYLON.PhysicsImpostor.HeightmapImpostor:\n var oldPosition2 = object.position.clone();\n var oldRotation2 = object.rotation && object.rotation.clone();\n var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();\n object.position.copyFromFloats(0, 0, 0);\n object.rotation && object.rotation.copyFromFloats(0, 0, 0);\n object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());\n object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();\n object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);\n returnValue = this._createHeightmap(object);\n object.position.copyFrom(oldPosition2);\n oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);\n oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);\n object.computeWorldMatrix(true);\n break;\n case BABYLON.PhysicsImpostor.ParticleImpostor:\n returnValue = new this.BJSCANNON.Particle();\n break;\n }\n return returnValue;\n };\n CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {\n var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));\n var transform = object.computeWorldMatrix(true);\n // convert rawVerts to object space\n var temp = new Array();\n var index;\n for (index = 0; index < pos.length; index += 3) {\n BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);\n }\n pos = temp;\n var matrix = new Array();\n //For now pointDepth will not be used and will be automatically calculated.\n //Future reference - try and find the best place to add a reference to the pointDepth variable.\n var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);\n var boundingInfo = object.getBoundingInfo();\n var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);\n var minY = boundingInfo.boundingBox.extendSizeWorld.z;\n var elementSize = dim * 2 / arraySize;\n for (var i = 0; i < pos.length; i = i + 3) {\n var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);\n var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);\n var y = -pos[i + 2] + minY;\n if (!matrix[x]) {\n matrix[x] = [];\n }\n if (!matrix[x][z]) {\n matrix[x][z] = y;\n }\n matrix[x][z] = Math.max(y, matrix[x][z]);\n }\n for (var x = 0; x <= arraySize; ++x) {\n if (!matrix[x]) {\n var loc = 1;\n while (!matrix[(x + loc) % arraySize]) {\n loc++;\n }\n matrix[x] = matrix[(x + loc) % arraySize].slice();\n //console.log(\"missing x\", x);\n }\n for (var z = 0; z <= arraySize; ++z) {\n if (!matrix[x][z]) {\n var loc = 1;\n var newValue;\n while (newValue === undefined) {\n newValue = matrix[x][(z + loc++) % arraySize];\n }\n matrix[x][z] = newValue;\n }\n }\n }\n var shape = new this.BJSCANNON.Heightfield(matrix, {\n elementSize: elementSize\n });\n //For future reference, needed for body transformation\n shape.minY = minY;\n return shape;\n };\n CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {\n var object = impostor.object;\n //make sure it is updated...\n object.computeWorldMatrix && object.computeWorldMatrix(true);\n // The delta between the mesh position and the mesh bounding box center\n var bInfo = object.getBoundingInfo();\n if (!bInfo)\n return;\n var center = impostor.getObjectCenter();\n //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)\n this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));\n this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);\n this._tmpPosition.copyFrom(center);\n var quaternion = object.rotationQuaternion;\n if (!quaternion) {\n return;\n }\n //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.\n if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {\n //-90 DEG in X, precalculated\n quaternion = quaternion.multiply(this._minus90X);\n //Invert! (Precalculated, 90 deg in X)\n //No need to clone. this will never change.\n impostor.setDeltaRotation(this._plus90X);\n }\n //If it is a heightfield, if should be centered.\n if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {\n var mesh = object;\n var boundingInfo = mesh.getBoundingInfo();\n //calculate the correct body position:\n var rotationQuaternion = mesh.rotationQuaternion;\n mesh.rotationQuaternion = this._tmpUnityRotation;\n mesh.computeWorldMatrix(true);\n //get original center with no rotation\n var c = center.clone();\n var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);\n //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)\n var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);\n mesh.setPreTransformMatrix(p);\n mesh.computeWorldMatrix(true);\n //calculate the translation\n var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();\n this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);\n //add it inverted to the delta\n this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));\n this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;\n //rotation is back\n mesh.rotationQuaternion = rotationQuaternion;\n mesh.setPreTransformMatrix(oldPivot);\n mesh.computeWorldMatrix(true);\n }\n else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {\n this._tmpDeltaPosition.copyFromFloats(0, 0, 0);\n //this._tmpPosition.copyFrom(object.position);\n }\n impostor.setDeltaPosition(this._tmpDeltaPosition);\n //Now update the impostor object\n impostor.physicsBody.position.copy(this._tmpPosition);\n impostor.physicsBody.quaternion.copy(quaternion);\n };\n CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {\n impostor.object.position.copyFrom(impostor.physicsBody.position);\n if (impostor.object.rotationQuaternion) {\n impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);\n }\n };\n CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {\n impostor.physicsBody.position.copy(newPosition);\n impostor.physicsBody.quaternion.copy(newRotation);\n };\n CannonJSPlugin.prototype.isSupported = function () {\n return this.BJSCANNON !== undefined;\n };\n CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {\n impostor.physicsBody.velocity.copy(velocity);\n };\n CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {\n impostor.physicsBody.angularVelocity.copy(velocity);\n };\n CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {\n var v = impostor.physicsBody.velocity;\n if (!v) {\n return null;\n }\n return new BABYLON.Vector3(v.x, v.y, v.z);\n };\n CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {\n var v = impostor.physicsBody.angularVelocity;\n if (!v) {\n return null;\n }\n return new BABYLON.Vector3(v.x, v.y, v.z);\n };\n CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {\n impostor.physicsBody.mass = mass;\n impostor.physicsBody.updateMassProperties();\n };\n CannonJSPlugin.prototype.getBodyMass = function (impostor) {\n return impostor.physicsBody.mass;\n };\n CannonJSPlugin.prototype.getBodyFriction = function (impostor) {\n return impostor.physicsBody.material.friction;\n };\n CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {\n impostor.physicsBody.material.friction = friction;\n };\n CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {\n return impostor.physicsBody.material.restitution;\n };\n CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {\n impostor.physicsBody.material.restitution = restitution;\n };\n CannonJSPlugin.prototype.sleepBody = function (impostor) {\n impostor.physicsBody.sleep();\n };\n CannonJSPlugin.prototype.wakeUpBody = function (impostor) {\n impostor.physicsBody.wakeUp();\n };\n CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {\n joint.physicsJoint.distance = maxDistance;\n };\n // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {\n // if (!motorIndex) {\n // joint.physicsJoint.enableMotor();\n // }\n // }\n // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {\n // if (!motorIndex) {\n // joint.physicsJoint.disableMotor();\n // }\n // }\n CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {\n if (!motorIndex) {\n joint.physicsJoint.enableMotor();\n joint.physicsJoint.setMotorSpeed(speed);\n if (maxForce) {\n this.setLimit(joint, maxForce);\n }\n }\n };\n CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {\n joint.physicsJoint.motorEquation.maxForce = upperLimit;\n joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;\n };\n CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {\n var body = impostor.physicsBody;\n mesh.position.x = body.position.x;\n mesh.position.y = body.position.y;\n mesh.position.z = body.position.z;\n if (mesh.rotationQuaternion) {\n mesh.rotationQuaternion.x = body.quaternion.x;\n mesh.rotationQuaternion.y = body.quaternion.y;\n mesh.rotationQuaternion.z = body.quaternion.z;\n mesh.rotationQuaternion.w = body.quaternion.w;\n }\n };\n CannonJSPlugin.prototype.getRadius = function (impostor) {\n var shape = impostor.physicsBody.shapes[0];\n return shape.boundingSphereRadius;\n };\n CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {\n var shape = impostor.physicsBody.shapes[0];\n result.x = shape.halfExtents.x * 2;\n result.y = shape.halfExtents.y * 2;\n result.z = shape.halfExtents.z * 2;\n };\n CannonJSPlugin.prototype.dispose = function () {\n };\n CannonJSPlugin.prototype._extendNamespace = function () {\n //this will force cannon to execute at least one step when using interpolation\n var step_tmp1 = new this.BJSCANNON.Vec3();\n var Engine = this.BJSCANNON;\n this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {\n maxSubSteps = maxSubSteps || 10;\n timeSinceLastCalled = timeSinceLastCalled || 0;\n if (timeSinceLastCalled === 0) {\n this.internalStep(dt);\n this.time += dt;\n }\n else {\n var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);\n internalSteps = Math.min(internalSteps, maxSubSteps) || 1;\n var t0 = performance.now();\n for (var i = 0; i !== internalSteps; i++) {\n this.internalStep(dt);\n if (performance.now() - t0 > dt * 1000) {\n break;\n }\n }\n this.time += timeSinceLastCalled;\n var h = this.time % dt;\n var h_div_dt = h / dt;\n var interpvelo = step_tmp1;\n var bodies = this.bodies;\n for (var j = 0; j !== bodies.length; j++) {\n var b = bodies[j];\n if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {\n b.position.vsub(b.previousPosition, interpvelo);\n interpvelo.scale(h_div_dt, interpvelo);\n b.position.vadd(interpvelo, b.interpolatedPosition);\n }\n else {\n b.interpolatedPosition.copy(b.position);\n b.interpolatedQuaternion.copy(b.quaternion);\n }\n }\n }\n };\n };\n return CannonJSPlugin;\n }());\n BABYLON.CannonJSPlugin = CannonJSPlugin;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.cannonJSPlugin.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var OimoJSPlugin = /** @class */ (function () {\n function OimoJSPlugin(iterations) {\n this.name = \"OimoJSPlugin\";\n this._tmpImpostorsArray = [];\n this._tmpPositionVector = BABYLON.Vector3.Zero();\n this.BJSOIMO = OIMO;\n this.world = new this.BJSOIMO.World({\n iterations: iterations\n });\n this.world.clear();\n }\n OimoJSPlugin.prototype.setGravity = function (gravity) {\n this.world.gravity.copy(gravity);\n };\n OimoJSPlugin.prototype.setTimeStep = function (timeStep) {\n this.world.timeStep = timeStep;\n };\n OimoJSPlugin.prototype.getTimeStep = function () {\n return this.world.timeStep;\n };\n OimoJSPlugin.prototype.executeStep = function (delta, impostors) {\n var _this = this;\n impostors.forEach(function (impostor) {\n impostor.beforeStep();\n });\n this.world.step();\n impostors.forEach(function (impostor) {\n impostor.afterStep();\n //update the ordered impostors array\n _this._tmpImpostorsArray[impostor.uniqueId] = impostor;\n });\n //check for collisions\n var contact = this.world.contacts;\n while (contact !== null) {\n if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {\n contact = contact.next;\n continue;\n }\n //is this body colliding with any other? get the impostor\n var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];\n var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];\n if (!mainImpostor || !collidingImpostor) {\n contact = contact.next;\n continue;\n }\n mainImpostor.onCollide({ body: collidingImpostor.physicsBody });\n collidingImpostor.onCollide({ body: mainImpostor.physicsBody });\n contact = contact.next;\n }\n };\n OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {\n var mass = impostor.physicsBody.mass;\n impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));\n };\n OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {\n BABYLON.Tools.Warn(\"Oimo doesn't support applying force. Using impule instead.\");\n this.applyImpulse(impostor, force, contactPoint);\n };\n OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {\n var _this = this;\n //parent-child relationship. Does this impostor has a parent impostor?\n if (impostor.parent) {\n if (impostor.physicsBody) {\n this.removePhysicsBody(impostor);\n //TODO is that needed?\n impostor.forceUpdate();\n }\n return;\n }\n if (impostor.isBodyInitRequired()) {\n var bodyConfig = {\n name: impostor.uniqueId,\n //Oimo must have mass, also for static objects.\n config: [impostor.getParam(\"mass\") || 1, impostor.getParam(\"friction\"), impostor.getParam(\"restitution\")],\n size: [],\n type: [],\n pos: [],\n posShape: [],\n rot: [],\n rotShape: [],\n move: impostor.getParam(\"mass\") !== 0,\n density: impostor.getParam(\"mass\"),\n friction: impostor.getParam(\"friction\"),\n restitution: impostor.getParam(\"restitution\"),\n //Supporting older versions of Oimo\n world: this.world\n };\n var impostors = [impostor];\n var addToArray = function (parent) {\n if (!parent.getChildMeshes)\n return;\n parent.getChildMeshes().forEach(function (m) {\n if (m.physicsImpostor) {\n impostors.push(m.physicsImpostor);\n //m.physicsImpostor._init();\n }\n });\n };\n addToArray(impostor.object);\n var checkWithEpsilon_1 = function (value) {\n return Math.max(value, BABYLON.PhysicsEngine.Epsilon);\n };\n var globalQuaternion_1 = new BABYLON.Quaternion();\n impostors.forEach(function (i) {\n if (!i.object.rotationQuaternion) {\n return;\n }\n //get the correct bounding box\n var oldQuaternion = i.object.rotationQuaternion;\n globalQuaternion_1 = oldQuaternion.clone();\n var rot = oldQuaternion.toEulerAngles();\n var extendSize = i.getObjectExtendSize();\n var radToDeg = 57.295779513082320876;\n if (i === impostor) {\n var center = impostor.getObjectCenter();\n impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);\n _this._tmpPositionVector.divideInPlace(impostor.object.scaling);\n //Can also use Array.prototype.push.apply\n bodyConfig.pos.push(center.x);\n bodyConfig.pos.push(center.y);\n bodyConfig.pos.push(center.z);\n bodyConfig.posShape.push(0, 0, 0);\n //tmp solution\n bodyConfig.rot.push(0);\n bodyConfig.rot.push(0);\n bodyConfig.rot.push(0);\n bodyConfig.rotShape.push(0, 0, 0);\n }\n else {\n var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());\n bodyConfig.posShape.push(localPosition.x);\n bodyConfig.posShape.push(localPosition.y);\n bodyConfig.posShape.push(localPosition.z);\n bodyConfig.pos.push(0, 0, 0);\n //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged\n bodyConfig.rot.push(0);\n bodyConfig.rot.push(0);\n bodyConfig.rot.push(0);\n bodyConfig.rotShape.push(rot.x * radToDeg);\n bodyConfig.rotShape.push(rot.y * radToDeg);\n bodyConfig.rotShape.push(rot.z * radToDeg);\n }\n // register mesh\n switch (i.type) {\n case BABYLON.PhysicsImpostor.ParticleImpostor:\n BABYLON.Tools.Warn(\"No Particle support in OIMO.js. using SphereImpostor instead\");\n case BABYLON.PhysicsImpostor.SphereImpostor:\n var radiusX = extendSize.x;\n var radiusY = extendSize.y;\n var radiusZ = extendSize.z;\n var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;\n bodyConfig.type.push('sphere');\n //due to the way oimo works with compounds, add 3 times\n bodyConfig.size.push(size);\n bodyConfig.size.push(size);\n bodyConfig.size.push(size);\n break;\n case BABYLON.PhysicsImpostor.CylinderImpostor:\n var sizeX = checkWithEpsilon_1(extendSize.x) / 2;\n var sizeY = checkWithEpsilon_1(extendSize.y);\n bodyConfig.type.push('cylinder');\n bodyConfig.size.push(sizeX);\n bodyConfig.size.push(sizeY);\n //due to the way oimo works with compounds, add one more value.\n bodyConfig.size.push(sizeY);\n break;\n case BABYLON.PhysicsImpostor.PlaneImpostor:\n case BABYLON.PhysicsImpostor.BoxImpostor:\n default:\n var sizeX = checkWithEpsilon_1(extendSize.x);\n var sizeY = checkWithEpsilon_1(extendSize.y);\n var sizeZ = checkWithEpsilon_1(extendSize.z);\n bodyConfig.type.push('box');\n //if (i === impostor) {\n bodyConfig.size.push(sizeX);\n bodyConfig.size.push(sizeY);\n bodyConfig.size.push(sizeZ);\n //} else {\n // bodyConfig.size.push(0,0,0);\n //}\n break;\n }\n //actually not needed, but hey...\n i.object.rotationQuaternion = oldQuaternion;\n });\n impostor.physicsBody = this.world.add(bodyConfig);\n // set the quaternion, ignoring the previously defined (euler) rotation\n impostor.physicsBody.resetQuaternion(globalQuaternion_1);\n // update with delta 0, so the body will reveive the new rotation.\n impostor.physicsBody.updatePosition(0);\n }\n else {\n this._tmpPositionVector.copyFromFloats(0, 0, 0);\n }\n impostor.setDeltaPosition(this._tmpPositionVector);\n //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);\n //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);\n };\n OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {\n //impostor.physicsBody.dispose();\n //Same as : (older oimo versions)\n this.world.removeRigidBody(impostor.physicsBody);\n };\n OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {\n var mainBody = impostorJoint.mainImpostor.physicsBody;\n var connectedBody = impostorJoint.connectedImpostor.physicsBody;\n if (!mainBody || !connectedBody) {\n return;\n }\n var jointData = impostorJoint.joint.jointData;\n var options = jointData.nativeParams || {};\n var type;\n var nativeJointData = {\n body1: mainBody,\n body2: connectedBody,\n axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),\n axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),\n pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),\n pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),\n min: options.min,\n max: options.max,\n collision: options.collision || jointData.collision,\n spring: options.spring,\n //supporting older version of Oimo\n world: this.world\n };\n switch (impostorJoint.joint.type) {\n case BABYLON.PhysicsJoint.BallAndSocketJoint:\n type = \"jointBall\";\n break;\n case BABYLON.PhysicsJoint.SpringJoint:\n BABYLON.Tools.Warn(\"OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead\");\n var springData = jointData;\n nativeJointData.min = springData.length || nativeJointData.min;\n //Max should also be set, just make sure it is at least min\n nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);\n case BABYLON.PhysicsJoint.DistanceJoint:\n type = \"jointDistance\";\n nativeJointData.max = jointData.maxDistance;\n break;\n case BABYLON.PhysicsJoint.PrismaticJoint:\n type = \"jointPrisme\";\n break;\n case BABYLON.PhysicsJoint.SliderJoint:\n type = \"jointSlide\";\n break;\n case BABYLON.PhysicsJoint.WheelJoint:\n type = \"jointWheel\";\n break;\n case BABYLON.PhysicsJoint.HingeJoint:\n default:\n type = \"jointHinge\";\n break;\n }\n nativeJointData.type = type;\n impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);\n };\n OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {\n //Bug in Oimo prevents us from disposing a joint in the playground\n //joint.joint.physicsJoint.dispose();\n //So we will bruteforce it!\n try {\n this.world.removeJoint(impostorJoint.joint.physicsJoint);\n }\n catch (e) {\n BABYLON.Tools.Warn(e);\n }\n };\n OimoJSPlugin.prototype.isSupported = function () {\n return this.BJSOIMO !== undefined;\n };\n OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {\n if (!impostor.physicsBody.sleeping) {\n //TODO check that\n /*if (impostor.physicsBody.shapes.next) {\n var parentShape = this._getLastShape(impostor.physicsBody);\n impostor.object.position.copyFrom(parentShape.position);\n console.log(parentShape.position);\n } else {*/\n impostor.object.position.copyFrom(impostor.physicsBody.getPosition());\n //}\n if (impostor.object.rotationQuaternion) {\n impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());\n }\n }\n };\n OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {\n var body = impostor.physicsBody;\n body.position.copy(newPosition);\n body.orientation.copy(newRotation);\n body.syncShapes();\n body.awake();\n };\n /*private _getLastShape(body: any): any {\n var lastShape = body.shapes;\n while (lastShape.next) {\n lastShape = lastShape.next;\n }\n return lastShape;\n }*/\n OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {\n impostor.physicsBody.linearVelocity.copy(velocity);\n };\n OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {\n impostor.physicsBody.angularVelocity.copy(velocity);\n };\n OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {\n var v = impostor.physicsBody.linearVelocity;\n if (!v) {\n return null;\n }\n return new BABYLON.Vector3(v.x, v.y, v.z);\n };\n OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {\n var v = impostor.physicsBody.angularVelocity;\n if (!v) {\n return null;\n }\n return new BABYLON.Vector3(v.x, v.y, v.z);\n };\n OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {\n var staticBody = mass === 0;\n //this will actually set the body's density and not its mass.\n //But this is how oimo treats the mass variable.\n impostor.physicsBody.shapes.density = staticBody ? 1 : mass;\n impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);\n };\n OimoJSPlugin.prototype.getBodyMass = function (impostor) {\n return impostor.physicsBody.shapes.density;\n };\n OimoJSPlugin.prototype.getBodyFriction = function (impostor) {\n return impostor.physicsBody.shapes.friction;\n };\n OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {\n impostor.physicsBody.shapes.friction = friction;\n };\n OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {\n return impostor.physicsBody.shapes.restitution;\n };\n OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {\n impostor.physicsBody.shapes.restitution = restitution;\n };\n OimoJSPlugin.prototype.sleepBody = function (impostor) {\n impostor.physicsBody.sleep();\n };\n OimoJSPlugin.prototype.wakeUpBody = function (impostor) {\n impostor.physicsBody.awake();\n };\n OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {\n joint.physicsJoint.limitMotor.upperLimit = maxDistance;\n if (minDistance !== void 0) {\n joint.physicsJoint.limitMotor.lowerLimit = minDistance;\n }\n };\n OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {\n //TODO separate rotational and transational motors.\n var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;\n if (motor) {\n motor.setMotor(speed, maxForce);\n }\n };\n OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {\n //TODO separate rotational and transational motors.\n var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;\n if (motor) {\n motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);\n }\n };\n OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {\n var body = impostor.physicsBody;\n mesh.position.x = body.position.x;\n mesh.position.y = body.position.y;\n mesh.position.z = body.position.z;\n if (mesh.rotationQuaternion) {\n mesh.rotationQuaternion.x = body.orientation.x;\n mesh.rotationQuaternion.y = body.orientation.y;\n mesh.rotationQuaternion.z = body.orientation.z;\n mesh.rotationQuaternion.w = body.orientation.s;\n }\n };\n OimoJSPlugin.prototype.getRadius = function (impostor) {\n return impostor.physicsBody.shapes.radius;\n };\n OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {\n var shape = impostor.physicsBody.shapes;\n result.x = shape.halfWidth * 2;\n result.y = shape.halfHeight * 2;\n result.z = shape.halfDepth * 2;\n };\n OimoJSPlugin.prototype.dispose = function () {\n this.world.clear();\n };\n return OimoJSPlugin;\n }());\n BABYLON.OimoJSPlugin = OimoJSPlugin;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.oimoJSPlugin.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html\n // All values and structures referenced from:\n // http://msdn.microsoft.com/en-us/library/bb943991.aspx/\n var DDS_MAGIC = 0x20534444;\n var \n //DDSD_CAPS = 0x1,\n //DDSD_HEIGHT = 0x2,\n //DDSD_WIDTH = 0x4,\n //DDSD_PITCH = 0x8,\n //DDSD_PIXELFORMAT = 0x1000,\n DDSD_MIPMAPCOUNT = 0x20000;\n //DDSD_LINEARSIZE = 0x80000,\n //DDSD_DEPTH = 0x800000;\n // var DDSCAPS_COMPLEX = 0x8,\n // DDSCAPS_MIPMAP = 0x400000,\n // DDSCAPS_TEXTURE = 0x1000;\n var DDSCAPS2_CUBEMAP = 0x200;\n // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,\n // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,\n // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,\n // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,\n // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,\n // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,\n // DDSCAPS2_VOLUME = 0x200000;\n var \n //DDPF_ALPHAPIXELS = 0x1,\n //DDPF_ALPHA = 0x2,\n DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, \n //DDPF_YUV = 0x200,\n DDPF_LUMINANCE = 0x20000;\n function FourCCToInt32(value) {\n return value.charCodeAt(0) +\n (value.charCodeAt(1) << 8) +\n (value.charCodeAt(2) << 16) +\n (value.charCodeAt(3) << 24);\n }\n function Int32ToFourCC(value) {\n return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);\n }\n var FOURCC_DXT1 = FourCCToInt32(\"DXT1\");\n var FOURCC_DXT3 = FourCCToInt32(\"DXT3\");\n var FOURCC_DXT5 = FourCCToInt32(\"DXT5\");\n var FOURCC_DX10 = FourCCToInt32(\"DX10\");\n var FOURCC_D3DFMT_R16G16B16A16F = 113;\n var FOURCC_D3DFMT_R32G32B32A32F = 116;\n var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;\n var DXGI_FORMAT_B8G8R8X8_UNORM = 88;\n var headerLengthInt = 31; // The header length in 32 bit ints\n // Offsets into the header array\n var off_magic = 0;\n var off_size = 1;\n var off_flags = 2;\n var off_height = 3;\n var off_width = 4;\n var off_mipmapCount = 7;\n var off_pfFlags = 20;\n var off_pfFourCC = 21;\n var off_RGBbpp = 22;\n var off_RMask = 23;\n var off_GMask = 24;\n var off_BMask = 25;\n var off_AMask = 26;\n // var off_caps1 = 27;\n var off_caps2 = 28;\n // var off_caps3 = 29;\n // var off_caps4 = 30;\n var off_dxgiFormat = 32;\n ;\n var DDSTools = /** @class */ (function () {\n function DDSTools() {\n }\n DDSTools.GetDDSInfo = function (arrayBuffer) {\n var header = new Int32Array(arrayBuffer, 0, headerLengthInt);\n var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);\n var mipmapCount = 1;\n if (header[off_flags] & DDSD_MIPMAPCOUNT) {\n mipmapCount = Math.max(1, header[off_mipmapCount]);\n }\n var fourCC = header[off_pfFourCC];\n var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;\n var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n switch (fourCC) {\n case FOURCC_D3DFMT_R16G16B16A16F:\n textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n break;\n case FOURCC_D3DFMT_R32G32B32A32F:\n textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n break;\n case FOURCC_DX10:\n if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {\n textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n break;\n }\n }\n return {\n width: header[off_width],\n height: header[off_height],\n mipmapCount: mipmapCount,\n isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,\n isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,\n isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,\n isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,\n isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),\n dxgiFormat: dxgiFormat,\n textureType: textureType\n };\n };\n DDSTools._ToHalfFloat = function (value) {\n if (!DDSTools._FloatView) {\n DDSTools._FloatView = new Float32Array(1);\n DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);\n }\n DDSTools._FloatView[0] = value;\n var x = DDSTools._Int32View[0];\n var bits = (x >> 16) & 0x8000; /* Get the sign */\n var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */\n var e = (x >> 23) & 0xff; /* Using int is faster here */\n /* If zero, or denormal, or exponent underflows too much for a denormal\n * half, return signed zero. */\n if (e < 103) {\n return bits;\n }\n /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */\n if (e > 142) {\n bits |= 0x7c00;\n /* If exponent was 0xff and one mantissa bit was set, it means NaN,\n * not Inf, so make sure we set one mantissa bit too. */\n bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);\n return bits;\n }\n /* If exponent underflows but not too much, return a denormal */\n if (e < 113) {\n m |= 0x0800;\n /* Extra rounding may overflow and set mantissa to 0 and exponent\n * to 1, which is OK. */\n bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);\n return bits;\n }\n bits |= ((e - 112) << 10) | (m >> 1);\n bits += m & 1;\n return bits;\n };\n DDSTools._FromHalfFloat = function (value) {\n var s = (value & 0x8000) >> 15;\n var e = (value & 0x7C00) >> 10;\n var f = value & 0x03FF;\n if (e === 0) {\n return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));\n }\n else if (e == 0x1F) {\n return f ? NaN : ((s ? -1 : 1) * Infinity);\n }\n return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));\n };\n DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {\n var destArray = new Float32Array(dataLength);\n var srcData = new Uint16Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 4;\n destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);\n destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);\n destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = lod;\n }\n else {\n destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);\n }\n index += 4;\n }\n }\n return destArray;\n };\n DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {\n if (DDSTools.StoreLODInAlphaChannel) {\n var destArray = new Uint16Array(dataLength);\n var srcData = new Uint16Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 4;\n destArray[index] = srcData[srcPos];\n destArray[index + 1] = srcData[srcPos + 1];\n destArray[index + 2] = srcData[srcPos + 2];\n destArray[index + 3] = DDSTools._ToHalfFloat(lod);\n index += 4;\n }\n }\n return destArray;\n }\n return new Uint16Array(arrayBuffer, dataOffset, dataLength);\n };\n DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {\n if (DDSTools.StoreLODInAlphaChannel) {\n var destArray = new Float32Array(dataLength);\n var srcData = new Float32Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 4;\n destArray[index] = srcData[srcPos];\n destArray[index + 1] = srcData[srcPos + 1];\n destArray[index + 2] = srcData[srcPos + 2];\n destArray[index + 3] = lod;\n index += 4;\n }\n }\n return destArray;\n }\n return new Float32Array(arrayBuffer, dataOffset, dataLength);\n };\n DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {\n var destArray = new Uint8Array(dataLength);\n var srcData = new Float32Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 4;\n destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;\n destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;\n destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = lod;\n }\n else {\n destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;\n }\n index += 4;\n }\n }\n return destArray;\n };\n DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {\n var destArray = new Uint8Array(dataLength);\n var srcData = new Uint16Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 4;\n destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;\n destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;\n destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = lod;\n }\n else {\n destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;\n }\n index += 4;\n }\n }\n return destArray;\n };\n DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {\n var byteArray = new Uint8Array(dataLength);\n var srcData = new Uint8Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 4;\n byteArray[index] = srcData[srcPos + rOffset];\n byteArray[index + 1] = srcData[srcPos + gOffset];\n byteArray[index + 2] = srcData[srcPos + bOffset];\n byteArray[index + 3] = srcData[srcPos + aOffset];\n index += 4;\n }\n }\n return byteArray;\n };\n DDSTools._ExtractLongWordOrder = function (value) {\n if (value === 0 || value === 255 || value === -16777216) {\n return 0;\n }\n return 1 + DDSTools._ExtractLongWordOrder(value >> 8);\n };\n DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {\n var byteArray = new Uint8Array(dataLength);\n var srcData = new Uint8Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 3;\n byteArray[index] = srcData[srcPos + rOffset];\n byteArray[index + 1] = srcData[srcPos + gOffset];\n byteArray[index + 2] = srcData[srcPos + bOffset];\n index += 3;\n }\n }\n return byteArray;\n };\n DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {\n var byteArray = new Uint8Array(dataLength);\n var srcData = new Uint8Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width);\n byteArray[index] = srcData[srcPos];\n index++;\n }\n }\n return byteArray;\n };\n /**\n * Uploads DDS Levels to a Babylon Texture\n * @hidden\n */\n DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {\n if (lodIndex === void 0) { lodIndex = -1; }\n var sphericalPolynomialFaces = null;\n if (info.sphericalPolynomial) {\n sphericalPolynomialFaces = new Array();\n }\n var ext = engine.getCaps().s3tc;\n var header = new Int32Array(arrayBuffer, 0, headerLengthInt);\n var fourCC, width, height, dataLength = 0, dataOffset;\n var byteArray, mipmapCount, mip;\n var internalCompressedFormat = 0;\n var blockBytes = 1;\n if (header[off_magic] !== DDS_MAGIC) {\n BABYLON.Tools.Error(\"Invalid magic number in DDS header\");\n return;\n }\n if (!info.isFourCC && !info.isRGB && !info.isLuminance) {\n BABYLON.Tools.Error(\"Unsupported format, must contain a FourCC, RGB or LUMINANCE code\");\n return;\n }\n if (info.isCompressed && !ext) {\n BABYLON.Tools.Error(\"Compressed textures are not supported on this platform.\");\n return;\n }\n var bpp = header[off_RGBbpp];\n dataOffset = header[off_size] + 4;\n var computeFormats = false;\n if (info.isFourCC) {\n fourCC = header[off_pfFourCC];\n switch (fourCC) {\n case FOURCC_DXT1:\n blockBytes = 8;\n internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;\n break;\n case FOURCC_DXT3:\n blockBytes = 16;\n internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;\n break;\n case FOURCC_DXT5:\n blockBytes = 16;\n internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;\n break;\n case FOURCC_D3DFMT_R16G16B16A16F:\n computeFormats = true;\n break;\n case FOURCC_D3DFMT_R32G32B32A32F:\n computeFormats = true;\n break;\n case FOURCC_DX10:\n // There is an additionnal header so dataOffset need to be changed\n dataOffset += 5 * 4; // 5 uints\n var supported = false;\n switch (info.dxgiFormat) {\n case DXGI_FORMAT_R16G16B16A16_FLOAT:\n computeFormats = true;\n supported = true;\n break;\n case DXGI_FORMAT_B8G8R8X8_UNORM:\n info.isRGB = true;\n info.isFourCC = false;\n bpp = 32;\n supported = true;\n break;\n }\n if (supported) {\n break;\n }\n default:\n console.error(\"Unsupported FourCC code:\", Int32ToFourCC(fourCC));\n return;\n }\n }\n var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);\n var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);\n var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);\n var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);\n if (computeFormats) {\n internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);\n }\n mipmapCount = 1;\n if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {\n mipmapCount = Math.max(1, header[off_mipmapCount]);\n }\n for (var face = 0; face < faces; face++) {\n width = header[off_width];\n height = header[off_height];\n for (mip = 0; mip < mipmapCount; ++mip) {\n if (lodIndex === -1 || lodIndex === mip) {\n // In case of fixed LOD, if the lod has just been uploaded, early exit.\n var i = (lodIndex === -1) ? mip : 0;\n if (!info.isCompressed && info.isFourCC) {\n texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;\n dataLength = width * height * 4;\n var floatArray = null;\n if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation\n if (bpp === 128) {\n floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));\n }\n }\n else if (bpp === 64) {\n floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));\n }\n }\n texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n else {\n if (bpp === 128) {\n texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;\n floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(floatArray);\n }\n }\n else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {\n texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;\n floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(floatArray);\n }\n }\n else { // 64\n texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));\n }\n }\n }\n if (floatArray) {\n engine._uploadDataToTextureDirectly(texture, floatArray, face, i);\n }\n }\n else if (info.isRGB) {\n texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n if (bpp === 24) {\n texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;\n dataLength = width * height * 3;\n byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);\n engine._uploadDataToTextureDirectly(texture, byteArray, face, i);\n }\n else { // 32\n texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;\n dataLength = width * height * 4;\n byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);\n engine._uploadDataToTextureDirectly(texture, byteArray, face, i);\n }\n }\n else if (info.isLuminance) {\n var unpackAlignment = engine._getUnpackAlignement();\n var unpaddedRowSize = width;\n var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;\n dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;\n byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);\n texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;\n texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n engine._uploadDataToTextureDirectly(texture, byteArray, face, i);\n }\n else {\n dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;\n byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);\n texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);\n }\n }\n dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;\n width *= 0.5;\n height *= 0.5;\n width = Math.max(1.0, width);\n height = Math.max(1.0, height);\n }\n if (currentFace !== undefined) {\n // Loading a single face\n break;\n }\n }\n if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {\n info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({\n size: header[off_width],\n right: sphericalPolynomialFaces[0],\n left: sphericalPolynomialFaces[1],\n up: sphericalPolynomialFaces[2],\n down: sphericalPolynomialFaces[3],\n front: sphericalPolynomialFaces[4],\n back: sphericalPolynomialFaces[5],\n format: BABYLON.Engine.TEXTUREFORMAT_RGBA,\n type: BABYLON.Engine.TEXTURETYPE_FLOAT,\n gammaSpace: false,\n });\n }\n else {\n info.sphericalPolynomial = undefined;\n }\n };\n DDSTools.StoreLODInAlphaChannel = false;\n return DDSTools;\n }());\n BABYLON.DDSTools = DDSTools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.dds.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Implementation of the DDS Texture Loader.\n */\n var DDSTextureLoader = /** @class */ (function () {\n function DDSTextureLoader() {\n /**\n * Defines wether the loader supports cascade loading the different faces.\n */\n this.supportCascades = true;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @param fallback defines the fallback internal texture if any\n * @param isBase64 defines whether the texture is encoded as a base64\n * @param isBuffer defines whether the texture data are stored as a buffer\n * @returns true if the loader can load the specified file\n */\n DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {\n return extension.indexOf(\".dds\") === 0;\n };\n /**\n * Transform the url before loading if required.\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the transformed texture\n */\n DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {\n return rootUrl;\n };\n /**\n * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the fallback texture\n */\n DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {\n return null;\n };\n /**\n * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n * @param onError defines the callback to trigger in case of error\n */\n DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {\n var engine = texture.getEngine();\n var info;\n var loadMipmap = false;\n if (Array.isArray(imgs)) {\n for (var index = 0; index < imgs.length; index++) {\n var data_1 = imgs[index];\n info = BABYLON.DDSTools.GetDDSInfo(data_1);\n texture.width = info.width;\n texture.height = info.height;\n loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;\n engine._unpackFlipY(info.isCompressed);\n BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);\n if (!info.isFourCC && info.mipmapCount === 1) {\n engine.generateMipMapsForCubemap(texture);\n }\n }\n }\n else {\n var data = imgs;\n info = BABYLON.DDSTools.GetDDSInfo(data);\n texture.width = info.width;\n texture.height = info.height;\n if (createPolynomials) {\n info.sphericalPolynomial = new BABYLON.SphericalPolynomial();\n }\n loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;\n engine._unpackFlipY(info.isCompressed);\n BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);\n if (!info.isFourCC && info.mipmapCount === 1) {\n engine.generateMipMapsForCubemap(texture);\n }\n }\n engine._setCubeMapTextureParams(loadMipmap);\n texture.isReady = true;\n if (onLoad) {\n onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });\n }\n };\n /**\n * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n DDSTextureLoader.prototype.loadData = function (data, texture, callback) {\n var info = BABYLON.DDSTools.GetDDSInfo(data);\n var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);\n callback(info.width, info.height, !loadMipmap, info.isFourCC, function () {\n BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);\n });\n };\n return DDSTextureLoader;\n }());\n // Register the loader.\n BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.ddsTextureLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /*\n * Based on jsTGALoader - Javascript loader for TGA file\n * By Vincent Thibault\n * @blog http://blog.robrowser.com/javascript-tga-loader.html\n */\n var TGATools = /** @class */ (function () {\n function TGATools() {\n }\n TGATools.GetTGAHeader = function (data) {\n var offset = 0;\n var header = {\n id_length: data[offset++],\n colormap_type: data[offset++],\n image_type: data[offset++],\n colormap_index: data[offset++] | data[offset++] << 8,\n colormap_length: data[offset++] | data[offset++] << 8,\n colormap_size: data[offset++],\n origin: [\n data[offset++] | data[offset++] << 8,\n data[offset++] | data[offset++] << 8\n ],\n width: data[offset++] | data[offset++] << 8,\n height: data[offset++] | data[offset++] << 8,\n pixel_size: data[offset++],\n flags: data[offset++]\n };\n return header;\n };\n /**\n * Uploads TGA content to a Babylon Texture\n * @hidden\n */\n TGATools.UploadContent = function (texture, data) {\n // Not enough data to contain header ?\n if (data.length < 19) {\n BABYLON.Tools.Error(\"Unable to load TGA file - Not enough data to contain header\");\n return;\n }\n // Read Header\n var offset = 18;\n var header = TGATools.GetTGAHeader(data);\n // Assume it's a valid Targa file.\n if (header.id_length + offset > data.length) {\n BABYLON.Tools.Error(\"Unable to load TGA file - Not enough data\");\n return;\n }\n // Skip not needed data\n offset += header.id_length;\n var use_rle = false;\n var use_pal = false;\n var use_grey = false;\n // Get some informations.\n switch (header.image_type) {\n case TGATools._TYPE_RLE_INDEXED:\n use_rle = true;\n case TGATools._TYPE_INDEXED:\n use_pal = true;\n break;\n case TGATools._TYPE_RLE_RGB:\n use_rle = true;\n case TGATools._TYPE_RGB:\n // use_rgb = true;\n break;\n case TGATools._TYPE_RLE_GREY:\n use_rle = true;\n case TGATools._TYPE_GREY:\n use_grey = true;\n break;\n }\n var pixel_data;\n // var numAlphaBits = header.flags & 0xf;\n var pixel_size = header.pixel_size >> 3;\n var pixel_total = header.width * header.height * pixel_size;\n // Read palettes\n var palettes;\n if (use_pal) {\n palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));\n }\n // Read LRE\n if (use_rle) {\n pixel_data = new Uint8Array(pixel_total);\n var c, count, i;\n var localOffset = 0;\n var pixels = new Uint8Array(pixel_size);\n while (offset < pixel_total && localOffset < pixel_total) {\n c = data[offset++];\n count = (c & 0x7f) + 1;\n // RLE pixels\n if (c & 0x80) {\n // Bind pixel tmp array\n for (i = 0; i < pixel_size; ++i) {\n pixels[i] = data[offset++];\n }\n // Copy pixel array\n for (i = 0; i < count; ++i) {\n pixel_data.set(pixels, localOffset + i * pixel_size);\n }\n localOffset += pixel_size * count;\n }\n // Raw pixels\n else {\n count *= pixel_size;\n for (i = 0; i < count; ++i) {\n pixel_data[localOffset + i] = data[offset++];\n }\n localOffset += count;\n }\n }\n }\n // RAW Pixels\n else {\n pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));\n }\n // Load to texture\n var x_start, y_start, x_step, y_step, y_end, x_end;\n switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {\n default:\n case TGATools._ORIGIN_UL:\n x_start = 0;\n x_step = 1;\n x_end = header.width;\n y_start = 0;\n y_step = 1;\n y_end = header.height;\n break;\n case TGATools._ORIGIN_BL:\n x_start = 0;\n x_step = 1;\n x_end = header.width;\n y_start = header.height - 1;\n y_step = -1;\n y_end = -1;\n break;\n case TGATools._ORIGIN_UR:\n x_start = header.width - 1;\n x_step = -1;\n x_end = -1;\n y_start = 0;\n y_step = 1;\n y_end = header.height;\n break;\n case TGATools._ORIGIN_BR:\n x_start = header.width - 1;\n x_step = -1;\n x_end = -1;\n y_start = header.height - 1;\n y_step = -1;\n y_end = -1;\n break;\n }\n // Load the specify method\n var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';\n var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);\n var engine = texture.getEngine();\n engine._uploadDataToTextureDirectly(texture, imageData);\n };\n TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n var image = pixel_data, colormap = palettes;\n var width = header.width, height = header.height;\n var color, i = 0, x, y;\n var imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i++) {\n color = image[i];\n imageData[(x + width * y) * 4 + 3] = 255;\n imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];\n imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];\n imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];\n }\n }\n return imageData;\n };\n TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n var image = pixel_data;\n var width = header.width, height = header.height;\n var color, i = 0, x, y;\n var imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 2) {\n color = image[i + 0] + (image[i + 1] << 8); // Inversed ?\n var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;\n var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;\n var b = ((color & 0x001F) * 255) / 0x1F | 0;\n imageData[(x + width * y) * 4 + 0] = r;\n imageData[(x + width * y) * 4 + 1] = g;\n imageData[(x + width * y) * 4 + 2] = b;\n imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;\n }\n }\n return imageData;\n };\n TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n var image = pixel_data;\n var width = header.width, height = header.height;\n var i = 0, x, y;\n var imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 3) {\n imageData[(x + width * y) * 4 + 3] = 255;\n imageData[(x + width * y) * 4 + 2] = image[i + 0];\n imageData[(x + width * y) * 4 + 1] = image[i + 1];\n imageData[(x + width * y) * 4 + 0] = image[i + 2];\n }\n }\n return imageData;\n };\n TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n var image = pixel_data;\n var width = header.width, height = header.height;\n var i = 0, x, y;\n var imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 4) {\n imageData[(x + width * y) * 4 + 2] = image[i + 0];\n imageData[(x + width * y) * 4 + 1] = image[i + 1];\n imageData[(x + width * y) * 4 + 0] = image[i + 2];\n imageData[(x + width * y) * 4 + 3] = image[i + 3];\n }\n }\n return imageData;\n };\n TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n var image = pixel_data;\n var width = header.width, height = header.height;\n var color, i = 0, x, y;\n var imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i++) {\n color = image[i];\n imageData[(x + width * y) * 4 + 0] = color;\n imageData[(x + width * y) * 4 + 1] = color;\n imageData[(x + width * y) * 4 + 2] = color;\n imageData[(x + width * y) * 4 + 3] = 255;\n }\n }\n return imageData;\n };\n TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n var image = pixel_data;\n var width = header.width, height = header.height;\n var i = 0, x, y;\n var imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 2) {\n imageData[(x + width * y) * 4 + 0] = image[i + 0];\n imageData[(x + width * y) * 4 + 1] = image[i + 0];\n imageData[(x + width * y) * 4 + 2] = image[i + 0];\n imageData[(x + width * y) * 4 + 3] = image[i + 1];\n }\n }\n return imageData;\n };\n //private static _TYPE_NO_DATA = 0;\n TGATools._TYPE_INDEXED = 1;\n TGATools._TYPE_RGB = 2;\n TGATools._TYPE_GREY = 3;\n TGATools._TYPE_RLE_INDEXED = 9;\n TGATools._TYPE_RLE_RGB = 10;\n TGATools._TYPE_RLE_GREY = 11;\n TGATools._ORIGIN_MASK = 0x30;\n TGATools._ORIGIN_SHIFT = 0x04;\n TGATools._ORIGIN_BL = 0x00;\n TGATools._ORIGIN_BR = 0x01;\n TGATools._ORIGIN_UL = 0x02;\n TGATools._ORIGIN_UR = 0x03;\n return TGATools;\n }());\n BABYLON.TGATools = TGATools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.tga.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Implementation of the TGA Texture Loader.\n */\n var TGATextureLoader = /** @class */ (function () {\n function TGATextureLoader() {\n /**\n * Defines wether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @param fallback defines the fallback internal texture if any\n * @param isBase64 defines whether the texture is encoded as a base64\n * @param isBuffer defines whether the texture data are stored as a buffer\n * @returns true if the loader can load the specified file\n */\n TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {\n return extension.indexOf(\".tga\") === 0;\n };\n /**\n * Transform the url before loading if required.\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the transformed texture\n */\n TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {\n return rootUrl;\n };\n /**\n * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the fallback texture\n */\n TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {\n return null;\n };\n /**\n * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n * @param onError defines the callback to trigger in case of error\n */\n TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {\n throw \".env not supported in Cube.\";\n };\n /**\n * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n TGATextureLoader.prototype.loadData = function (data, texture, callback) {\n var uintData = new Uint8Array(data);\n var header = BABYLON.TGATools.GetTGAHeader(uintData);\n callback(header.width, header.height, texture.generateMipMaps, false, function () {\n BABYLON.TGATools.UploadContent(texture, uintData);\n });\n };\n return TGATextureLoader;\n }());\n // Register the loader.\n BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.tgaTextureLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * for description see https://www.khronos.org/opengles/sdk/tools/KTX/\n * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/\n */\n var KhronosTextureContainer = /** @class */ (function () {\n /**\n * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file\n * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or\n * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented\n * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented\n */\n function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {\n this.arrayBuffer = arrayBuffer;\n // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:\n // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\\r', '\\n', '\\x1A', '\\n'\n // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A\n var identifier = new Uint8Array(this.arrayBuffer, 0, 12);\n if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||\n identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {\n BABYLON.Tools.Error(\"texture missing KTX identifier\");\n return;\n }\n // load the reset of the header in native 32 bit int\n var header = new Int32Array(this.arrayBuffer, 12, 13);\n // determine of the remaining header values are recorded in the opposite endianness & require conversion\n var oppositeEndianess = header[0] === 0x01020304;\n // read all the header elements in order they exist in the file, without modification (sans endainness)\n this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures\n this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures\n this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures\n this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)\n this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)\n this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)\n this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)\n this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)\n this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays\n this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6\n this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures\n this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data\n // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.\n if (this.glType !== 0) {\n BABYLON.Tools.Error(\"only compressed formats currently supported\");\n return;\n }\n else {\n // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.\n this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);\n }\n if (this.pixelHeight === 0 || this.pixelDepth !== 0) {\n BABYLON.Tools.Error(\"only 2D textures currently supported\");\n return;\n }\n if (this.numberOfArrayElements !== 0) {\n BABYLON.Tools.Error(\"texture arrays not currently supported\");\n return;\n }\n if (this.numberOfFaces !== facesExpected) {\n BABYLON.Tools.Error(\"number of faces expected\" + facesExpected + \", but found \" + this.numberOfFaces);\n return;\n }\n // we now have a completely validated file, so could use existence of loadType as success\n // would need to make this more elaborate & adjust checks above to support more than one load type\n this.loadType = KhronosTextureContainer.COMPRESSED_2D;\n }\n // not as fast hardware based, but will probably never need to use\n KhronosTextureContainer.prototype.switchEndainness = function (val) {\n return ((val & 0xFF) << 24)\n | ((val & 0xFF00) << 8)\n | ((val >> 8) & 0xFF00)\n | ((val >> 24) & 0xFF);\n };\n /**\n * Uploads KTX content to a Babylon Texture.\n * It is assumed that the texture has already been created & is currently bound\n * @hidden\n */\n KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {\n switch (this.loadType) {\n case KhronosTextureContainer.COMPRESSED_2D:\n this._upload2DCompressedLevels(texture, loadMipmaps);\n break;\n case KhronosTextureContainer.TEX_2D:\n case KhronosTextureContainer.COMPRESSED_3D:\n case KhronosTextureContainer.TEX_3D:\n }\n };\n KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {\n // initialize width & height for level 1\n var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;\n var width = this.pixelWidth;\n var height = this.pixelHeight;\n var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;\n for (var level = 0; level < mipmapCount; level++) {\n var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps\n dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.\n for (var face = 0; face < this.numberOfFaces; face++) {\n var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);\n var engine = texture.getEngine();\n engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);\n dataOffset += imageSize; // add size of the image for the next face/mipmap\n dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image\n }\n width = Math.max(1.0, width * 0.5);\n height = Math.max(1.0, height * 0.5);\n }\n };\n KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)\n // load types\n KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()\n KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()\n KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()\n KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()\n return KhronosTextureContainer;\n }());\n BABYLON.KhronosTextureContainer = KhronosTextureContainer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.khronosTextureContainer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Implementation of the KTX Texture Loader.\n */\n var KTXTextureLoader = /** @class */ (function () {\n function KTXTextureLoader() {\n /**\n * Defines wether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @param fallback defines the fallback internal texture if any\n * @param isBase64 defines whether the texture is encoded as a base64\n * @param isBuffer defines whether the texture data are stored as a buffer\n * @returns true if the loader can load the specified file\n */\n KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {\n if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {\n return true;\n }\n return false;\n };\n /**\n * Transform the url before loading if required.\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the transformed texture\n */\n KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {\n var lastDot = rootUrl.lastIndexOf('.');\n return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;\n };\n /**\n * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the fallback texture\n */\n KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {\n // remove the format appended to the rootUrl in the original createCubeTexture call.\n var exp = new RegExp(\"\" + textureFormatInUse + \"$\");\n return rootUrl.replace(exp, \"\");\n };\n /**\n * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n * @param onError defines the callback to trigger in case of error\n */\n KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {\n if (Array.isArray(data)) {\n return;\n }\n var engine = texture.getEngine();\n var ktx = new BABYLON.KhronosTextureContainer(data, 6);\n var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;\n engine._unpackFlipY(true);\n ktx.uploadLevels(texture, texture.generateMipMaps);\n texture.width = ktx.pixelWidth;\n texture.height = ktx.pixelHeight;\n engine._setCubeMapTextureParams(loadMipmap);\n texture.isReady = true;\n };\n /**\n * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n KTXTextureLoader.prototype.loadData = function (data, texture, callback) {\n var ktx = new BABYLON.KhronosTextureContainer(data, 1);\n callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {\n ktx.uploadLevels(texture, texture.generateMipMaps);\n });\n };\n return KTXTextureLoader;\n }());\n // Register the loader.\n BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.ktxTextureLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Sets of helpers addressing the serialization and deserialization of environment texture\n * stored in a BabylonJS env file.\n * Those files are usually stored as .env files.\n */\n var EnvironmentTextureTools = /** @class */ (function () {\n function EnvironmentTextureTools() {\n }\n /**\n * Gets the environment info from an env file.\n * @param data The array buffer containing the .env bytes.\n * @returns the environment file info (the json header) if successfully parsed.\n */\n EnvironmentTextureTools.GetEnvInfo = function (data) {\n var dataView = new DataView(data);\n var pos = 0;\n for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {\n if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {\n BABYLON.Tools.Error('Not a babylon environment map');\n return null;\n }\n }\n // Read json manifest - collect characters up to null terminator\n var manifestString = '';\n var charCode = 0x00;\n while ((charCode = dataView.getUint8(pos++))) {\n manifestString += String.fromCharCode(charCode);\n }\n var manifest = JSON.parse(manifestString);\n if (manifest.specular) {\n // Extend the header with the position of the payload.\n manifest.specular.specularDataPosition = pos;\n // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.\n manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;\n }\n return manifest;\n };\n /**\n * Creates an environment texture from a loaded cube texture.\n * @param texture defines the cube texture to convert in env file\n * @return a promise containing the environment data if succesfull.\n */\n EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {\n var _this = this;\n var internalTexture = texture.getInternalTexture();\n if (!internalTexture) {\n return Promise.reject(\"The cube texture is invalid.\");\n }\n if (!texture._prefiltered) {\n return Promise.reject(\"The cube texture is invalid (not prefiltered).\");\n }\n var engine = internalTexture.getEngine();\n if (engine && engine.premultipliedAlpha) {\n return Promise.reject(\"Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.\");\n }\n if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {\n return Promise.reject(\"The cube texture should allow HDR (Full Float or Half Float).\");\n }\n var canvas = engine.getRenderingCanvas();\n if (!canvas) {\n return Promise.reject(\"Env texture can only be created when the engine is associated to a canvas.\");\n }\n var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n if (!engine.getCaps().textureFloatRender) {\n textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n if (!engine.getCaps().textureHalfFloatRender) {\n return Promise.reject(\"Env texture can only be created when the browser supports half float or full float rendering.\");\n }\n }\n var cubeWidth = internalTexture.width;\n var hostingScene = new BABYLON.Scene(engine);\n var specularTextures = {};\n var promises = [];\n // Read and collect all mipmaps data from the cube.\n var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);\n mipmapsCount = Math.round(mipmapsCount);\n var _loop_1 = function (i) {\n var faceWidth = Math.pow(2, mipmapsCount - i);\n var _loop_2 = function (face) {\n var data = texture.readPixels(face, i);\n // Creates a temp texture with the face data.\n var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);\n // And rgbdEncode them. \n var promise = new Promise(function (resolve, reject) {\n var rgbdPostProcess = new BABYLON.PostProcess(\"rgbdEncode\", \"rgbdEncode\", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);\n rgbdPostProcess.getEffect().executeWhenCompiled(function () {\n rgbdPostProcess.onApply = function (effect) {\n effect._bindTexture(\"textureSampler\", tempTexture);\n };\n // As the process needs to happen on the main canvas, keep track of the current size\n var currentW = engine.getRenderWidth();\n var currentH = engine.getRenderHeight();\n // Set the desired size for the texture\n engine.setSize(faceWidth, faceWidth);\n hostingScene.postProcessManager.directRender([rgbdPostProcess], null);\n // Reading datas from WebGL\n BABYLON.Tools.ToBlob(canvas, function (blob) {\n var fileReader = new FileReader();\n fileReader.onload = function (event) {\n var arrayBuffer = event.target.result;\n specularTextures[i * 6 + face] = arrayBuffer;\n resolve();\n };\n fileReader.readAsArrayBuffer(blob);\n });\n // Reapply the previous canvas size\n engine.setSize(currentW, currentH);\n });\n });\n promises.push(promise);\n };\n // All faces of the cube.\n for (var face = 0; face < 6; face++) {\n _loop_2(face);\n }\n };\n for (var i = 0; i <= mipmapsCount; i++) {\n _loop_1(i);\n }\n // Once all the textures haves been collected as RGBD stored in PNGs\n return Promise.all(promises).then(function () {\n // We can delete the hosting scene keeping track of all the creation objects\n hostingScene.dispose();\n // Creates the json header for the env texture\n var info = {\n version: 1,\n width: cubeWidth,\n irradiance: _this._CreateEnvTextureIrradiance(texture),\n specular: {\n mipmaps: [],\n lodGenerationScale: texture.lodGenerationScale\n }\n };\n // Sets the specular image data information\n var position = 0;\n for (var i = 0; i <= mipmapsCount; i++) {\n for (var face = 0; face < 6; face++) {\n var byteLength = specularTextures[i * 6 + face].byteLength;\n info.specular.mipmaps.push({\n length: byteLength,\n position: position\n });\n position += byteLength;\n }\n }\n // Encode the JSON as an array buffer\n var infoString = JSON.stringify(info);\n var infoBuffer = new ArrayBuffer(infoString.length + 1);\n var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.\n for (var i = 0, strLen = infoString.length; i < strLen; i++) {\n infoView[i] = infoString.charCodeAt(i);\n }\n // Ends up with a null terminator for easier parsing\n infoView[infoString.length] = 0x00;\n // Computes the final required size and creates the storage\n var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;\n var finalBuffer = new ArrayBuffer(totalSize);\n var finalBufferView = new Uint8Array(finalBuffer);\n var dataView = new DataView(finalBuffer);\n // Copy the magic bytes identifying the file in\n var pos = 0;\n for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {\n dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);\n }\n // Add the json info\n finalBufferView.set(new Uint8Array(infoBuffer), pos);\n pos += infoBuffer.byteLength;\n // Finally inserts the texture data\n for (var i = 0; i <= mipmapsCount; i++) {\n for (var face = 0; face < 6; face++) {\n var dataBuffer = specularTextures[i * 6 + face];\n finalBufferView.set(new Uint8Array(dataBuffer), pos);\n pos += dataBuffer.byteLength;\n }\n }\n // Voila\n return finalBuffer;\n });\n };\n /**\n * Creates a JSON representation of the spherical data.\n * @param texture defines the texture containing the polynomials\n * @return the JSON representation of the spherical info\n */\n EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {\n var polynmials = texture.sphericalPolynomial;\n if (polynmials == null) {\n return null;\n }\n return {\n x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],\n y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],\n z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],\n xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],\n yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],\n zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],\n yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],\n zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],\n xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]\n };\n };\n /**\n * Uploads the texture info contained in the env file to the GPU.\n * @param texture defines the internal texture to upload to\n * @param arrayBuffer defines the buffer cotaining the data to load\n * @param info defines the texture info retrieved through the GetEnvInfo method\n * @returns a promise\n */\n EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {\n if (info.version !== 1) {\n throw new Error(\"Unsupported babylon environment map version \\\"\" + info.version + \"\\\"\");\n }\n var specularInfo = info.specular;\n if (!specularInfo) {\n // Nothing else parsed so far\n return Promise.resolve();\n }\n // Double checks the enclosed info\n var mipmapsCount = BABYLON.Scalar.Log2(info.width);\n mipmapsCount = Math.round(mipmapsCount) + 1;\n if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {\n throw new Error(\"Unsupported specular mipmaps number \\\"\" + specularInfo.mipmaps.length + \"\\\"\");\n }\n texture._lodGenerationScale = specularInfo.lodGenerationScale;\n var imageData = new Array(mipmapsCount);\n for (var i = 0; i < mipmapsCount; i++) {\n imageData[i] = new Array(6);\n for (var face = 0; face < 6; face++) {\n var imageInfo = specularInfo.mipmaps[i * 6 + face];\n imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);\n }\n }\n return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);\n };\n /**\n * Uploads the levels of image data to the GPU.\n * @param texture defines the internal texture to upload to\n * @param imageData defines the array buffer views of image data [mipmap][face]\n * @returns a promise\n */\n EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {\n if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {\n throw new Error(\"Texture size must be a power of two\");\n }\n var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;\n // Gets everything ready.\n var engine = texture.getEngine();\n var expandTexture = false;\n var generateNonLODTextures = false;\n var rgbdPostProcess = null;\n var cubeRtt = null;\n var lodTextures = null;\n var caps = engine.getCaps();\n texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;\n texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n texture.generateMipMaps = true;\n engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);\n // Add extra process if texture lod is not supported\n if (!caps.textureLOD) {\n expandTexture = false;\n generateNonLODTextures = true;\n lodTextures = {};\n }\n // in webgl 1 there are no ways to either render or copy lod level information for float textures.\n else if (engine.webGLVersion < 2) {\n expandTexture = false;\n }\n // If half float available we can uncompress the texture\n else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n expandTexture = true;\n texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n // If full float available we can uncompress the texture\n else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n expandTexture = true;\n texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n // Expand the texture if possible\n if (expandTexture) {\n // Simply run through the decode PP\n rgbdPostProcess = new BABYLON.PostProcess(\"rgbdDecode\", \"rgbdDecode\", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);\n texture._isRGBD = false;\n texture.invertY = false;\n cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {\n generateDepthBuffer: false,\n generateMipMaps: true,\n generateStencilBuffer: false,\n samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,\n type: texture.type,\n format: BABYLON.Engine.TEXTUREFORMAT_RGBA\n });\n }\n else {\n texture._isRGBD = true;\n texture.invertY = true;\n // In case of missing support, applies the same patch than DDS files.\n if (generateNonLODTextures) {\n var mipSlices = 3;\n var scale = texture._lodGenerationScale;\n var offset = texture._lodGenerationOffset;\n for (var i = 0; i < mipSlices; i++) {\n //compute LOD from even spacing in smoothness (matching shader calculation)\n var smoothness = i / (mipSlices - 1);\n var roughness = 1 - smoothness;\n var minLODIndex = offset; // roughness = 0\n var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)\n var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;\n var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));\n var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);\n glTextureFromLod.isCube = true;\n glTextureFromLod.invertY = true;\n glTextureFromLod.generateMipMaps = false;\n engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);\n // Wrap in a base texture for easy binding.\n var lodTexture = new BABYLON.BaseTexture(null);\n lodTexture.isCube = true;\n lodTexture._texture = glTextureFromLod;\n lodTextures[mipmapIndex] = lodTexture;\n switch (i) {\n case 0:\n texture._lodTextureLow = lodTexture;\n break;\n case 1:\n texture._lodTextureMid = lodTexture;\n break;\n case 2:\n texture._lodTextureHigh = lodTexture;\n break;\n }\n }\n }\n }\n var promises = [];\n var _loop_3 = function (i) {\n var _loop_4 = function (face) {\n // Constructs an image element from image data\n var bytes = imageData[i][face];\n var blob = new Blob([bytes], { type: 'image/png' });\n var url = URL.createObjectURL(blob);\n var image = new Image();\n image.src = url;\n // Enqueue promise to upload to the texture.\n var promise = new Promise(function (resolve, reject) {\n image.onload = function () {\n if (expandTexture) {\n var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {\n reject(message);\n }, image);\n rgbdPostProcess.getEffect().executeWhenCompiled(function () {\n // Uncompress the data to a RTT\n rgbdPostProcess.onApply = function (effect) {\n effect._bindTexture(\"textureSampler\", tempTexture_1);\n effect.setFloat2(\"scale\", 1, 1);\n };\n engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);\n // Cleanup\n engine.restoreDefaultFramebuffer();\n tempTexture_1.dispose();\n window.URL.revokeObjectURL(url);\n resolve();\n });\n }\n else {\n engine._uploadImageToTexture(texture, image, face, i);\n // Upload the face to the non lod texture support\n if (generateNonLODTextures) {\n var lodTexture = lodTextures[i];\n if (lodTexture) {\n engine._uploadImageToTexture(lodTexture._texture, image, face, 0);\n }\n }\n resolve();\n }\n };\n image.onerror = function (error) {\n reject(error);\n };\n });\n promises.push(promise);\n };\n // All faces\n for (var face = 0; face < 6; face++) {\n _loop_4(face);\n }\n };\n // All mipmaps up to provided number of images\n for (var i = 0; i < imageData.length; i++) {\n _loop_3(i);\n }\n // Fill remaining mipmaps with black textures.\n if (imageData.length < mipmapsCount) {\n var data = void 0;\n var size = Math.pow(2, mipmapsCount - 1 - imageData.length);\n var dataLength = size * size * 4;\n switch (texture.type) {\n case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {\n data = new Uint8Array(dataLength);\n break;\n }\n case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {\n data = new Uint16Array(dataLength);\n break;\n }\n case BABYLON.Engine.TEXTURETYPE_FLOAT: {\n data = new Float32Array(dataLength);\n break;\n }\n }\n for (var i = imageData.length; i < mipmapsCount; i++) {\n for (var face = 0; face < 6; face++) {\n engine._uploadArrayBufferViewToTexture(texture, data, face, i);\n }\n }\n }\n // Once all done, finishes the cleanup and return\n return Promise.all(promises).then(function () {\n // Release temp RTT.\n if (cubeRtt) {\n engine._releaseFramebufferObjects(cubeRtt);\n cubeRtt._swapAndDie(texture);\n }\n // Release temp Post Process.\n if (rgbdPostProcess) {\n rgbdPostProcess.dispose();\n }\n // Flag internal texture as ready in case they are in use.\n if (generateNonLODTextures) {\n if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {\n texture._lodTextureHigh._texture.isReady = true;\n }\n if (texture._lodTextureMid && texture._lodTextureMid._texture) {\n texture._lodTextureMid._texture.isReady = true;\n }\n if (texture._lodTextureLow && texture._lodTextureLow._texture) {\n texture._lodTextureLow._texture.isReady = true;\n }\n }\n });\n };\n /**\n * Uploads spherical polynomials information to the texture.\n * @param texture defines the texture we are trying to upload the information to\n * @param info defines the environment texture info retrieved through the GetEnvInfo method\n */\n EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {\n if (info.version !== 1) {\n BABYLON.Tools.Warn('Unsupported babylon environment map version \"' + info.version + '\"');\n }\n var irradianceInfo = info.irradiance;\n if (!irradianceInfo) {\n return;\n }\n var sp = new BABYLON.SphericalPolynomial();\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);\n texture._sphericalPolynomial = sp;\n };\n /**\n * Magic number identifying the env file.\n */\n EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];\n return EnvironmentTextureTools;\n }());\n BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.environmentTextureTools.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Implementation of the ENV Texture Loader.\n */\n var ENVTextureLoader = /** @class */ (function () {\n function ENVTextureLoader() {\n /**\n * Defines wether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @param fallback defines the fallback internal texture if any\n * @param isBase64 defines whether the texture is encoded as a base64\n * @param isBuffer defines whether the texture data are stored as a buffer\n * @returns true if the loader can load the specified file\n */\n ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {\n return extension.indexOf(\".env\") === 0;\n };\n /**\n * Transform the url before loading if required.\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the transformed texture\n */\n ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {\n return rootUrl;\n };\n /**\n * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the fallback texture\n */\n ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {\n return null;\n };\n /**\n * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n * @param onError defines the callback to trigger in case of error\n */\n ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {\n if (Array.isArray(data)) {\n return;\n }\n data = data;\n var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);\n if (info) {\n texture.width = info.width;\n texture.height = info.width;\n BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);\n BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {\n texture.isReady = true;\n if (onLoad) {\n onLoad();\n }\n });\n }\n else if (onError) {\n onError(\"Can not parse the environment file\", null);\n }\n };\n /**\n * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n ENVTextureLoader.prototype.loadData = function (data, texture, callback) {\n throw \".env not supported in 2d.\";\n };\n return ENVTextureLoader;\n }());\n // Register the loader.\n BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.envTextureLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Renders a layer on top of an existing scene\n */\n var UtilityLayerRenderer = /** @class */ (function () {\n /**\n * Instantiates a UtilityLayerRenderer\n * @param originalScene the original scene that will be rendered on top of\n */\n function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {\n var _this = this;\n this.originalScene = originalScene;\n this._pointerCaptures = {};\n this._lastPointerEvents = {};\n /**\n * If the utility layer should automatically be rendered on top of existing scene\n */\n this.shouldRender = true;\n /**\n * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene\n */\n this.onlyCheckPointerDownEvents = true;\n /**\n * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)\n */\n this.processAllEvents = false;\n /**\n * Observable raised when the pointer move from the utility layer scene to the main scene\n */\n this.onPointerOutObservable = new BABYLON.Observable();\n // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app\n this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());\n this.utilityLayerScene._allowPostProcessClear = false;\n originalScene.getEngine().scenes.pop();\n // Detach controls on utility scene, events will be fired by logic below to handle picking priority\n this.utilityLayerScene.detachControl();\n this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {\n if (!_this.processAllEvents) {\n if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE\n && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP\n && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {\n return;\n }\n }\n var pointerEvent = (prePointerInfo.event);\n if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {\n _this._pointerCaptures[pointerEvent.pointerId] = false;\n return;\n }\n var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);\n if (!prePointerInfo.ray && utilityScenePick) {\n prePointerInfo.ray = utilityScenePick.ray;\n }\n // always fire the prepointer oversvable\n _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);\n // allow every non pointer down event to flow to the utility layer\n if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {\n if (!prePointerInfo.skipOnPointerObservable) {\n _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));\n }\n if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {\n _this._pointerCaptures[pointerEvent.pointerId] = false;\n }\n return;\n }\n if (_this.utilityLayerScene.autoClearDepthAndStencil) {\n // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene\n if (utilityScenePick && utilityScenePick.hit) {\n if (!prePointerInfo.skipOnPointerObservable) {\n _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));\n }\n prePointerInfo.skipOnPointerObservable = true;\n }\n }\n else {\n var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);\n var pointerEvent_1 = (prePointerInfo.event);\n // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray\n if (originalScenePick && utilityScenePick) {\n // No pick in utility scene\n if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {\n if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {\n // We touched an utility mesh present in the main scene\n _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);\n prePointerInfo.skipOnPointerObservable = true;\n }\n else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {\n _this._pointerCaptures[pointerEvent_1.pointerId] = true;\n }\n }\n else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {\n // We pick something in utility scene or the pick in utility is closer than the one in main scene\n _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);\n // If a previous utility layer set this, do not unset this\n if (!prePointerInfo.skipOnPointerObservable) {\n prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;\n }\n }\n else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {\n // We have a pick in both scenes but main is closer than utility\n // We touched an utility mesh present in the main scene\n if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {\n _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);\n prePointerInfo.skipOnPointerObservable = true;\n }\n else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {\n // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete\n _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);\n delete _this._lastPointerEvents[pointerEvent_1.pointerId];\n }\n }\n if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {\n _this._pointerCaptures[pointerEvent_1.pointerId] = false;\n }\n }\n }\n });\n // Render directly on top of existing scene without clearing\n this.utilityLayerScene.autoClear = false;\n this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {\n if (_this.shouldRender) {\n _this.render();\n }\n });\n this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {\n _this.dispose();\n });\n this._updateCamera();\n }\n Object.defineProperty(UtilityLayerRenderer, \"DefaultUtilityLayer\", {\n /**\n * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)\n */\n get: function () {\n if (UtilityLayerRenderer._DefaultUtilityLayer == null) {\n UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);\n UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {\n UtilityLayerRenderer._DefaultUtilityLayer = null;\n });\n }\n return UtilityLayerRenderer._DefaultUtilityLayer;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(UtilityLayerRenderer, \"DefaultKeepDepthUtilityLayer\", {\n /**\n * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)\n */\n get: function () {\n if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;\n });\n }\n return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;\n },\n enumerable: true,\n configurable: true\n });\n UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {\n if (!prePointerInfo.skipOnPointerObservable) {\n this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));\n this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;\n }\n };\n /**\n * Renders the utility layers scene on top of the original scene\n */\n UtilityLayerRenderer.prototype.render = function () {\n this._updateCamera();\n if (this.utilityLayerScene.activeCamera) {\n // Set the camera's scene to utility layers scene\n var oldScene = this.utilityLayerScene.activeCamera.getScene();\n var camera = this.utilityLayerScene.activeCamera;\n camera._scene = this.utilityLayerScene;\n if (camera.leftCamera) {\n camera.leftCamera._scene = this.utilityLayerScene;\n }\n if (camera.rightCamera) {\n camera.rightCamera._scene = this.utilityLayerScene;\n }\n this.utilityLayerScene.render(false);\n // Reset camera's scene back to original\n camera._scene = oldScene;\n if (camera.leftCamera) {\n camera.leftCamera._scene = oldScene;\n }\n if (camera.rightCamera) {\n camera.rightCamera._scene = oldScene;\n }\n }\n };\n /**\n * Disposes of the renderer\n */\n UtilityLayerRenderer.prototype.dispose = function () {\n this.onPointerOutObservable.clear();\n if (this._afterRenderObserver) {\n this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);\n }\n if (this._sceneDisposeObserver) {\n this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);\n }\n if (this._originalPointerObserver) {\n this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);\n }\n this.utilityLayerScene.dispose();\n };\n UtilityLayerRenderer.prototype._updateCamera = function () {\n this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;\n };\n UtilityLayerRenderer._DefaultUtilityLayer = null;\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;\n return UtilityLayerRenderer;\n }());\n BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.utilityLayerRenderer.js.map\n\n\n\n//# sourceMappingURL=babylon.behavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events\n */\n var PointerDragBehavior = /** @class */ (function () {\n /**\n * Creates a pointer drag behavior that can be attached to a mesh\n * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)\n */\n function PointerDragBehavior(options) {\n /**\n * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)\n */\n this.maxDragAngle = 0;\n /**\n * @hidden\n */\n this._useAlternatePickedPointAboveMaxDragAngle = false;\n /**\n * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)\n */\n this.currentDraggingPointerID = -1;\n /**\n * If the behavior is currently in a dragging state\n */\n this.dragging = false;\n /**\n * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)\n */\n this.dragDeltaRatio = 0.2;\n /**\n * If the drag plane orientation should be updated during the dragging (Default: true)\n */\n this.updateDragPlane = true;\n // Debug mode will display drag planes to help visualize behavior\n this._debugMode = false;\n this._moving = false;\n /**\n * Fires each time the attached mesh is dragged with the pointer\n * * delta between last drag position and current drag position in world space\n * * dragDistance along the drag axis\n * * dragPlaneNormal normal of the current drag plane used during the drag\n * * dragPlanePoint in world space where the drag intersects the drag plane\n */\n this.onDragObservable = new BABYLON.Observable();\n /**\n * Fires each time a drag begins (eg. mouse down on mesh)\n */\n this.onDragStartObservable = new BABYLON.Observable();\n /**\n * Fires each time a drag ends (eg. mouse release after drag)\n */\n this.onDragEndObservable = new BABYLON.Observable();\n /**\n * If the attached mesh should be moved when dragged\n */\n this.moveAttached = true;\n /**\n * If the drag behavior will react to drag events (Default: true)\n */\n this.enabled = true;\n /**\n * If camera controls should be detached during the drag\n */\n this.detachCameraControls = true;\n /**\n * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)\n */\n this.useObjectOrienationForDragging = true;\n this._tmpVector = new BABYLON.Vector3(0, 0, 0);\n this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);\n this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);\n // Variables to avoid instantiation in the below method\n this._pointA = new BABYLON.Vector3(0, 0, 0);\n this._pointB = new BABYLON.Vector3(0, 0, 0);\n this._pointC = new BABYLON.Vector3(0, 0, 0);\n this._lineA = new BABYLON.Vector3(0, 0, 0);\n this._lineB = new BABYLON.Vector3(0, 0, 0);\n this._localAxis = new BABYLON.Vector3(0, 0, 0);\n this._lookAt = new BABYLON.Vector3(0, 0, 0);\n this._options = options ? options : {};\n var optionCount = 0;\n if (this._options.dragAxis) {\n optionCount++;\n }\n if (this._options.dragPlaneNormal) {\n optionCount++;\n }\n if (optionCount > 1) {\n throw \"Multiple drag modes specified in dragBehavior options. Only one expected\";\n }\n }\n Object.defineProperty(PointerDragBehavior.prototype, \"name\", {\n /**\n * The name of the behavior\n */\n get: function () {\n return \"PointerDrag\";\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Initializes the behavior\n */\n PointerDragBehavior.prototype.init = function () { };\n /**\n * Attaches the drag behavior the passed in mesh\n * @param ownerNode The mesh that will be dragged around once attached\n */\n PointerDragBehavior.prototype.attach = function (ownerNode) {\n var _this = this;\n this._scene = ownerNode.getScene();\n this._attachedNode = ownerNode;\n // Initialize drag plane to not interfere with existing scene\n if (!PointerDragBehavior._planeScene) {\n if (this._debugMode) {\n PointerDragBehavior._planeScene = this._scene;\n }\n else {\n PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());\n PointerDragBehavior._planeScene.detachControl();\n this._scene.getEngine().scenes.pop();\n this._scene.onDisposeObservable.addOnce(function () {\n PointerDragBehavior._planeScene.dispose();\n PointerDragBehavior._planeScene = null;\n });\n }\n }\n this._dragPlane = BABYLON.Mesh.CreatePlane(\"pointerDragPlane\", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);\n // State of the drag\n this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);\n var delta = new BABYLON.Vector3(0, 0, 0);\n var dragLength = 0;\n var targetPosition = new BABYLON.Vector3(0, 0, 0);\n var pickPredicate = function (m) {\n return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);\n };\n var attachedElement = null;\n this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {\n if (!_this.enabled) {\n return;\n }\n if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {\n if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {\n _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);\n var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);\n if (pickedPoint) {\n _this.dragging = true;\n _this.currentDraggingPointerID = pointerInfo.event.pointerId;\n _this.lastDragPosition.copyFrom(pickedPoint);\n _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });\n targetPosition.copyFrom(_this._attachedNode.absolutePosition);\n // Detatch camera controls\n if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {\n if (_this._scene.activeCamera.inputs.attachedElement) {\n attachedElement = _this._scene.activeCamera.inputs.attachedElement;\n _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);\n }\n else {\n attachedElement = null;\n }\n }\n }\n }\n }\n else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {\n if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {\n _this.releaseDrag();\n // Reattach camera controls\n if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {\n _this._scene.activeCamera.attachControl(attachedElement, true);\n }\n }\n }\n else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {\n if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {\n _this._moving = true;\n var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);\n if (pickedPoint) {\n if (_this.updateDragPlane) {\n _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);\n }\n // depending on the drag mode option drag accordingly\n if (_this._options.dragAxis) {\n // Convert local drag axis to world\n BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);\n // Project delta drag from the drag plane onto the drag axis\n pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);\n dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);\n _this._worldDragAxis.scaleToRef(dragLength, delta);\n }\n else {\n dragLength = delta.length();\n pickedPoint.subtractToRef(_this.lastDragPosition, delta);\n }\n targetPosition.addInPlace(delta);\n _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });\n _this.lastDragPosition.copyFrom(pickedPoint);\n }\n }\n }\n });\n this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {\n if (_this._moving && _this.moveAttached) {\n // Slowly move mesh to avoid jitter\n targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);\n _this._tmpVector.scaleInPlace(0.2);\n _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);\n _this._attachedNode.setAbsolutePosition(_this._tmpVector);\n }\n });\n };\n PointerDragBehavior.prototype.releaseDrag = function () {\n this.dragging = false;\n this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });\n this.currentDraggingPointerID = -1;\n this._moving = false;\n };\n PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {\n var _this = this;\n if (!ray) {\n return null;\n }\n // Calculate angle between plane normal and ray\n var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));\n // Correct if ray is casted from oposite side\n if (angle > Math.PI / 2) {\n angle = Math.PI - angle;\n }\n // If the angle is too perpendicular to the plane pick another point on the plane where it is looking\n if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {\n if (this._useAlternatePickedPointAboveMaxDragAngle) {\n // Invert ray direction along the towards object axis\n this._tmpVector.copyFrom(ray.direction);\n this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);\n this._alternatePickedPoint.normalize();\n this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));\n this._tmpVector.addInPlace(this._alternatePickedPoint);\n // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point\n var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);\n this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);\n this._alternatePickedPoint.addInPlace(this._tmpVector);\n this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);\n return this._alternatePickedPoint;\n }\n else {\n return null;\n }\n }\n var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });\n if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {\n return pickResult.pickedPoint;\n }\n else {\n return null;\n }\n };\n // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera\n PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {\n this._pointA.copyFrom(dragPlanePosition);\n if (this._options.dragAxis) {\n this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);\n // Calculate plane normal in direction of camera but perpendicular to drag axis\n this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis\n ray.origin.subtractToRef(this._pointA, this._pointC);\n this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera\n // Get perpendicular line from direction to camera and drag axis\n this._pointB.subtractToRef(this._pointA, this._lineA);\n this._pointC.subtractToRef(this._pointA, this._lineB);\n BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);\n // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera\n BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);\n this._lookAt.normalize();\n this._dragPlane.position.copyFrom(this._pointA);\n this._pointA.subtractToRef(this._lookAt, this._lookAt);\n this._dragPlane.lookAt(this._lookAt);\n }\n else if (this._options.dragPlaneNormal) {\n this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);\n this._dragPlane.position.copyFrom(this._pointA);\n this._pointA.subtractToRef(this._localAxis, this._lookAt);\n this._dragPlane.lookAt(this._lookAt);\n }\n else {\n this._dragPlane.position.copyFrom(this._pointA);\n this._dragPlane.lookAt(ray.origin);\n }\n this._dragPlane.computeWorldMatrix(true);\n };\n /**\n * Detaches the behavior from the mesh\n */\n PointerDragBehavior.prototype.detach = function () {\n if (this._pointerObserver) {\n this._scene.onPointerObservable.remove(this._pointerObserver);\n }\n if (this._beforeRenderObserver) {\n this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);\n }\n };\n return PointerDragBehavior;\n }());\n BABYLON.PointerDragBehavior = PointerDragBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pointerDragBehavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A behavior that when attached to a mesh will allow the mesh to be scaled\n */\n var MultiPointerScaleBehavior = /** @class */ (function () {\n function MultiPointerScaleBehavior() {\n this._startDistance = 0;\n this._initialScale = new BABYLON.Vector3(0, 0, 0);\n this._targetScale = new BABYLON.Vector3(0, 0, 0);\n this._sceneRenderObserver = null;\n this._dragBehaviorA = new BABYLON.PointerDragBehavior({});\n this._dragBehaviorA.moveAttached = false;\n this._dragBehaviorB = new BABYLON.PointerDragBehavior({});\n this._dragBehaviorB.moveAttached = false;\n }\n Object.defineProperty(MultiPointerScaleBehavior.prototype, \"name\", {\n /**\n * The name of the behavior\n */\n get: function () {\n return \"MultiPointerScale\";\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Initializes the behavior\n */\n MultiPointerScaleBehavior.prototype.init = function () { };\n MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {\n return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();\n };\n /**\n * Attaches the scale behavior the passed in mesh\n * @param ownerNode The mesh that will be scaled around once attached\n */\n MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {\n var _this = this;\n this._ownerNode = ownerNode;\n // Create 2 drag behaviors such that each will only be triggered by a separate pointer\n this._dragBehaviorA.onDragStartObservable.add(function (e) {\n if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {\n if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {\n _this._dragBehaviorA.releaseDrag();\n }\n else {\n _this._initialScale.copyFrom(ownerNode.scaling);\n _this._startDistance = _this._getCurrentDistance();\n }\n }\n });\n this._dragBehaviorB.onDragStartObservable.add(function (e) {\n if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {\n if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {\n _this._dragBehaviorB.releaseDrag();\n }\n else {\n _this._initialScale.copyFrom(ownerNode.scaling);\n _this._startDistance = _this._getCurrentDistance();\n }\n }\n });\n // Once both drag behaviors are active scale based on the distance between the two pointers\n [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {\n behavior.onDragObservable.add(function () {\n if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {\n var ratio = _this._getCurrentDistance() / _this._startDistance;\n _this._initialScale.scaleToRef(ratio, _this._targetScale);\n }\n });\n });\n ownerNode.addBehavior(this._dragBehaviorA);\n ownerNode.addBehavior(this._dragBehaviorB);\n // On every frame move towards target scaling to avoid jitter caused by vr controllers\n this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {\n if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {\n var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);\n if (change.length() > 0.01) {\n ownerNode.scaling.addInPlace(change);\n }\n }\n });\n };\n /**\n * Detaches the behavior from the mesh\n */\n MultiPointerScaleBehavior.prototype.detach = function () {\n var _this = this;\n this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);\n [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {\n behavior.onDragStartObservable.clear();\n behavior.onDragObservable.clear();\n _this._ownerNode.removeBehavior(behavior);\n });\n };\n return MultiPointerScaleBehavior;\n }());\n BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray\n */\n var SixDofDragBehavior = /** @class */ (function () {\n function SixDofDragBehavior() {\n this._sceneRenderObserver = null;\n this._targetPosition = new BABYLON.Vector3(0, 0, 0);\n this._moving = false;\n this._startingOrientation = new BABYLON.Quaternion();\n /**\n * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)\n */\n this.zDragFactor = 3;\n /**\n * If the behavior is currently in a dragging state\n */\n this.dragging = false;\n /**\n * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)\n */\n this.dragDeltaRatio = 0.2;\n /**\n * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)\n */\n this.currentDraggingPointerID = -1;\n /**\n * If camera controls should be detached during the drag\n */\n this.detachCameraControls = true;\n }\n Object.defineProperty(SixDofDragBehavior.prototype, \"name\", {\n /**\n * The name of the behavior\n */\n get: function () {\n return \"SixDofDrag\";\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Initializes the behavior\n */\n SixDofDragBehavior.prototype.init = function () { };\n /**\n * Attaches the scale behavior the passed in mesh\n * @param ownerNode The mesh that will be scaled around once attached\n */\n SixDofDragBehavior.prototype.attach = function (ownerNode) {\n var _this = this;\n this._ownerNode = ownerNode;\n this._scene = this._ownerNode.getScene();\n if (!SixDofDragBehavior._virtualScene) {\n SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());\n this._scene.getEngine().scenes.pop();\n }\n var pickedMesh = null;\n var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);\n // Setup virtual meshes to be used for dragging without dirtying the existing scene\n this._virtualOriginMesh = new BABYLON.AbstractMesh(\"\", SixDofDragBehavior._virtualScene);\n this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();\n this._virtualDragMesh = new BABYLON.AbstractMesh(\"\", SixDofDragBehavior._virtualScene);\n this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();\n var pickPredicate = function (m) {\n return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);\n };\n var attachedElement = null;\n this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {\n if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {\n if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {\n if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {\n pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);\n }\n pickedMesh = _this._ownerNode;\n lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);\n // Set position and orientation of the controller\n _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);\n _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));\n // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged\n _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);\n _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);\n if (!pickedMesh.rotationQuaternion) {\n pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);\n }\n var oldParent = pickedMesh.parent;\n pickedMesh.setParent(null);\n _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);\n pickedMesh.setParent(oldParent);\n _this._virtualOriginMesh.addChild(_this._virtualDragMesh);\n // Update state\n _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);\n _this.dragging = true;\n _this.currentDraggingPointerID = pointerInfo.event.pointerId;\n // Detatch camera controls\n if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {\n if (_this._scene.activeCamera.inputs.attachedElement) {\n attachedElement = _this._scene.activeCamera.inputs.attachedElement;\n _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);\n }\n else {\n attachedElement = null;\n }\n }\n }\n }\n else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {\n if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {\n _this.dragging = false;\n _this._moving = false;\n _this.currentDraggingPointerID = -1;\n pickedMesh = null;\n _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);\n // Reattach camera controls\n if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {\n _this._scene.activeCamera.attachControl(attachedElement, true);\n }\n }\n }\n else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {\n if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {\n var zDragFactor = _this.zDragFactor;\n if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {\n pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);\n zDragFactor = 0;\n }\n // Calculate controller drag distance in controller space\n var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);\n lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);\n var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);\n _this._virtualOriginMesh.addChild(_this._virtualDragMesh);\n // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away\n _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;\n if (_this._virtualDragMesh.position.z < 0) {\n _this._virtualDragMesh.position.z = 0;\n }\n // Update the controller position\n _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);\n _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));\n _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);\n // Move the virtualObjectsPosition into the picked mesh's space if needed\n _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);\n if (pickedMesh.parent) {\n BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);\n }\n if (!_this._moving) {\n _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);\n }\n _this._moving = true;\n }\n }\n });\n var tmpQuaternion = new BABYLON.Quaternion();\n // On every frame move towards target scaling to avoid jitter caused by vr controllers\n this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {\n if (_this.dragging && _this._moving && pickedMesh) {\n // Slowly move mesh to avoid jitter\n pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));\n // Get change in rotation\n tmpQuaternion.copyFrom(_this._startingOrientation);\n tmpQuaternion.x = -tmpQuaternion.x;\n tmpQuaternion.y = -tmpQuaternion.y;\n tmpQuaternion.z = -tmpQuaternion.z;\n _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);\n // Convert change in rotation to only y axis rotation\n BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles(\"xyz\").y, 0, 0, tmpQuaternion);\n tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);\n // Slowly move mesh to avoid jitter\n var oldParent = pickedMesh.parent;\n pickedMesh.setParent(null);\n BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);\n pickedMesh.setParent(oldParent);\n }\n });\n };\n /**\n * Detaches the behavior from the mesh\n */\n SixDofDragBehavior.prototype.detach = function () {\n if (this._scene) {\n this._scene.onPointerObservable.remove(this._pointerObserver);\n }\n if (this._ownerNode) {\n this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);\n }\n if (this._virtualOriginMesh) {\n this._virtualOriginMesh.dispose();\n }\n if (this._virtualDragMesh) {\n this._virtualDragMesh.dispose();\n }\n };\n return SixDofDragBehavior;\n }());\n BABYLON.SixDofDragBehavior = SixDofDragBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sixDofDragBehavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * @hidden\n */\n var FaceDirectionInfo = /** @class */ (function () {\n function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {\n if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }\n if (diff === void 0) { diff = 0; }\n if (ignore === void 0) { ignore = false; }\n this.direction = direction;\n this.rotatedDirection = rotatedDirection;\n this.diff = diff;\n this.ignore = ignore;\n }\n return FaceDirectionInfo;\n }());\n /**\n * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera\n */\n var AttachToBoxBehavior = /** @class */ (function () {\n /**\n * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera\n * @param ui The transform node that should be attched to the mesh\n */\n function AttachToBoxBehavior(ui) {\n this.ui = ui;\n /**\n * The name of the behavior\n */\n this.name = \"AttachToBoxBehavior\";\n /**\n * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)\n */\n this.distanceAwayFromFace = 0.15;\n /**\n * The distance from the bottom of the face that the UI should be attached to (default: 0.15)\n */\n this.distanceAwayFromBottomOfFace = 0.15;\n this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];\n this._tmpMatrix = new BABYLON.Matrix();\n this._tmpVector = new BABYLON.Vector3();\n this._zeroVector = BABYLON.Vector3.Zero();\n this._lookAtTmpMatrix = new BABYLON.Matrix();\n /* Does nothing */\n }\n /**\n * Initializes the behavior\n */\n AttachToBoxBehavior.prototype.init = function () {\n /* Does nothing */\n };\n AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {\n var _this = this;\n // Go over each face and calculate the angle between the face's normal and targetDirection\n this._faceVectors.forEach(function (v) {\n if (!_this._target.rotationQuaternion) {\n _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);\n }\n _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);\n BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);\n v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));\n });\n // Return the face information of the one with the normal closeset to target direction\n return this._faceVectors.reduce(function (min, p) {\n if (min.ignore) {\n return p;\n }\n else if (p.ignore) {\n return min;\n }\n else {\n return min.diff < p.diff ? min : p;\n }\n }, this._faceVectors[0]);\n };\n AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {\n if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }\n BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);\n this._lookAtTmpMatrix.invert();\n BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);\n };\n /**\n * Attaches the AttachToBoxBehavior to the passed in mesh\n * @param target The mesh that the specified node will be attached to\n */\n AttachToBoxBehavior.prototype.attach = function (target) {\n var _this = this;\n this._target = target;\n this._scene = this._target.getScene();\n // Every frame, update the app bars position\n this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {\n if (!_this._scene.activeCamera) {\n return;\n }\n // Find the face closest to the cameras position\n var cameraPos = _this._scene.activeCamera.position;\n if (_this._scene.activeCamera.devicePosition) {\n cameraPos = _this._scene.activeCamera.devicePosition;\n }\n var facing = _this._closestFace(cameraPos.subtract(target.position));\n if (_this._scene.activeCamera.leftCamera) {\n _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);\n }\n else {\n _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);\n }\n // Get camera up direction\n BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);\n // Ignore faces to not select a parrelel face for the up vector of the UI\n _this._faceVectors.forEach(function (v) {\n if (facing.direction.x && v.direction.x) {\n v.ignore = true;\n }\n if (facing.direction.y && v.direction.y) {\n v.ignore = true;\n }\n if (facing.direction.z && v.direction.z) {\n v.ignore = true;\n }\n });\n var facingUp = _this._closestFace(_this._tmpVector);\n // Unignore faces\n _this._faceVectors.forEach(function (v) {\n v.ignore = false;\n });\n // Position the app bar on that face\n _this.ui.position.copyFrom(target.position);\n if (facing.direction.x) {\n facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);\n _this.ui.position.addInPlace(_this._tmpVector);\n }\n if (facing.direction.y) {\n facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);\n _this.ui.position.addInPlace(_this._tmpVector);\n }\n if (facing.direction.z) {\n facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);\n _this.ui.position.addInPlace(_this._tmpVector);\n }\n // Rotate to be oriented properly to the camera\n if (!_this.ui.rotationQuaternion) {\n _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);\n }\n facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);\n _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);\n // Place ui the correct distance from the bottom of the mesh\n if (facingUp.direction.x) {\n _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);\n }\n if (facingUp.direction.y) {\n _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);\n }\n if (facingUp.direction.z) {\n _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);\n }\n _this.ui.position.addInPlace(_this._tmpVector);\n });\n };\n /**\n * Detaches the behavior from the mesh\n */\n AttachToBoxBehavior.prototype.detach = function () {\n this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);\n };\n return AttachToBoxBehavior;\n }());\n BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.attachToBoxBehavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.\n */\n var Gizmo = /** @class */ (function () {\n /**\n * Creates a gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n */\n function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = this;\n this.gizmoLayer = gizmoLayer;\n this._scaleFactor = 3;\n this._tmpMatrix = new BABYLON.Matrix();\n /**\n * If a custom mesh has been set (Default: false)\n */\n this._customMeshSet = false;\n /**\n * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)\n */\n this.updateGizmoRotationToMatchAttachedMesh = true;\n /**\n * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)\n */\n this.updateGizmoPositionToMatchAttachedMesh = true;\n /**\n * When set, the gizmo will always appear the same size no matter where the camera is (default: false)\n */\n this._updateScale = true;\n this._interactionsEnabled = true;\n this._tempVector = new BABYLON.Vector3();\n this._rootMesh = new BABYLON.Mesh(\"gizmoRootNode\", gizmoLayer.utilityLayerScene);\n this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {\n _this._update();\n });\n this.attachedMesh = null;\n }\n Object.defineProperty(Gizmo.prototype, \"attachedMesh\", {\n /**\n * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)\n * * When set, interactions will be enabled\n */\n get: function () {\n return this._attachedMesh;\n },\n set: function (value) {\n this._attachedMesh = value;\n this._rootMesh.setEnabled(value ? true : false);\n this._attachedMeshChanged(value);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes and replaces the current meshes in the gizmo with the specified mesh\n * @param mesh The mesh to replace the default mesh of the gizmo\n */\n Gizmo.prototype.setCustomMesh = function (mesh) {\n if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {\n throw \"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)\";\n }\n this._rootMesh.getChildMeshes().forEach(function (c) {\n c.dispose();\n });\n mesh.parent = this._rootMesh;\n this._customMeshSet = true;\n };\n Gizmo.prototype._attachedMeshChanged = function (value) {\n };\n /**\n * @hidden\n * Updates the gizmo to match the attached mesh's position/rotation\n */\n Gizmo.prototype._update = function () {\n if (this.attachedMesh) {\n if (this.updateGizmoRotationToMatchAttachedMesh) {\n if (!this._rootMesh.rotationQuaternion) {\n this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);\n }\n // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale\n this._tempVector.copyFrom(this.attachedMesh.scaling);\n if (this.attachedMesh.scaling.x < 0) {\n this.attachedMesh.scaling.x *= -1;\n }\n if (this.attachedMesh.scaling.y < 0) {\n this.attachedMesh.scaling.y *= -1;\n }\n if (this.attachedMesh.scaling.z < 0) {\n this.attachedMesh.scaling.z *= -1;\n }\n this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);\n this.attachedMesh.scaling.copyFrom(this._tempVector);\n this.attachedMesh.computeWorldMatrix();\n BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);\n }\n if (this.updateGizmoPositionToMatchAttachedMesh) {\n this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);\n }\n if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {\n var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;\n if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {\n cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;\n }\n this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);\n var dist = this._tempVector.length() / this._scaleFactor;\n this._rootMesh.scaling.set(dist, dist, dist);\n }\n }\n };\n /**\n * Disposes of the gizmo\n */\n Gizmo.prototype.dispose = function () {\n this._rootMesh.dispose();\n if (this._beforeRenderObserver) {\n this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);\n }\n };\n return Gizmo;\n }());\n BABYLON.Gizmo = Gizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Single axis drag gizmo\n */\n var AxisDragGizmo = /** @class */ (function (_super) {\n __extends(AxisDragGizmo, _super);\n /**\n * Creates an AxisDragGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param dragAxis The axis which the gizmo will be able to drag on\n * @param color The color of the gizmo\n */\n function AxisDragGizmo(dragAxis, color, gizmoLayer) {\n if (color === void 0) { color = BABYLON.Color3.Gray(); }\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this._pointerObserver = null;\n /**\n * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n _this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n _this.onSnapObservable = new BABYLON.Observable();\n // Create Material\n var coloredMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n coloredMaterial.disableLighting = true;\n coloredMaterial.emissiveColor = color;\n var hoverMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n hoverMaterial.disableLighting = true;\n hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));\n // Build mesh on root node\n var arrow = new BABYLON.AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n var arrowMesh = BABYLON.MeshBuilder.CreateCylinder(\"yPosMesh\", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);\n var arrowTail = BABYLON.MeshBuilder.CreateLines(\"yPosMesh\", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);\n arrowTail.color = coloredMaterial.emissiveColor;\n arrow.addChild(arrowMesh);\n arrow.addChild(arrowTail);\n // Position arrow pointing in its drag axis\n arrowMesh.scaling.scaleInPlace(0.05);\n arrowMesh.material = coloredMaterial;\n arrowMesh.rotation.x = Math.PI / 2;\n arrowMesh.position.z += 0.3;\n arrowTail.scaling.scaleInPlace(0.2);\n arrowTail.rotation.x = Math.PI / 2;\n arrowTail.material = coloredMaterial;\n arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));\n _this._rootMesh.addChild(arrow);\n var currentSnapDragDistance = 0;\n var tmpVector = new BABYLON.Vector3();\n var tmpSnapEvent = { snapDistance: 0 };\n // Add drag behavior to handle events when the gizmo is dragged\n _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });\n _this.dragBehavior.moveAttached = false;\n _this._rootMesh.addBehavior(_this.dragBehavior);\n _this.dragBehavior.onDragObservable.add(function (event) {\n if (_this.attachedMesh) {\n // Snapping logic\n if (_this.snapDistance == 0) {\n _this.attachedMesh.position.addInPlace(event.delta);\n }\n else {\n currentSnapDragDistance += event.dragDistance;\n if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {\n var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);\n currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;\n event.delta.normalizeToRef(tmpVector);\n tmpVector.scaleInPlace(_this.snapDistance * dragSteps);\n _this.attachedMesh.position.addInPlace(tmpVector);\n tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;\n _this.onSnapObservable.notifyObservers(tmpSnapEvent);\n }\n }\n }\n });\n _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {\n if (_this._customMeshSet) {\n return;\n }\n var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);\n var material = isHovered ? hoverMaterial : coloredMaterial;\n _this._rootMesh.getChildMeshes().forEach(function (m) {\n m.material = material;\n if (m.color) {\n m.color = material.emissiveColor;\n }\n });\n });\n return _this;\n }\n AxisDragGizmo.prototype._attachedMeshChanged = function (value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n };\n /**\n * Disposes of the gizmo\n */\n AxisDragGizmo.prototype.dispose = function () {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n _super.prototype.dispose.call(this);\n };\n return AxisDragGizmo;\n }(BABYLON.Gizmo));\n BABYLON.AxisDragGizmo = AxisDragGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.axisDragGizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Single axis scale gizmo\n */\n var AxisScaleGizmo = /** @class */ (function (_super) {\n __extends(AxisScaleGizmo, _super);\n /**\n * Creates an AxisScaleGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param dragAxis The axis which the gizmo will be able to scale on\n * @param color The color of the gizmo\n */\n function AxisScaleGizmo(dragAxis, color, gizmoLayer) {\n if (color === void 0) { color = BABYLON.Color3.Gray(); }\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this._pointerObserver = null;\n /**\n * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n _this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n _this.onSnapObservable = new BABYLON.Observable();\n // Create Material\n var coloredMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n coloredMaterial.disableLighting = true;\n coloredMaterial.emissiveColor = color;\n var hoverMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n hoverMaterial.disableLighting = true;\n hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));\n // Build mesh on root node\n var arrow = new BABYLON.AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n var arrowMesh = BABYLON.MeshBuilder.CreateBox(\"yPosMesh\", { size: 0.4 }, gizmoLayer.utilityLayerScene);\n var arrowTail = BABYLON.MeshBuilder.CreateLines(\"yPosMesh\", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);\n arrowTail.color = coloredMaterial.emissiveColor;\n arrow.addChild(arrowMesh);\n arrow.addChild(arrowTail);\n // Position arrow pointing in its drag axis\n arrowMesh.scaling.scaleInPlace(0.1);\n arrowMesh.material = coloredMaterial;\n arrowMesh.rotation.x = Math.PI / 2;\n arrowMesh.position.z += 0.3;\n arrowTail.scaling.scaleInPlace(0.2);\n arrowTail.rotation.x = Math.PI / 2;\n arrowTail.material = coloredMaterial;\n arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));\n _this._rootMesh.addChild(arrow);\n // Add drag behavior to handle events when the gizmo is dragged\n _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });\n _this.dragBehavior.moveAttached = false;\n _this._rootMesh.addBehavior(_this.dragBehavior);\n var currentSnapDragDistance = 0;\n var tmpVector = new BABYLON.Vector3();\n var tmpSnapEvent = { snapDistance: 0 };\n _this.dragBehavior.onDragObservable.add(function (event) {\n if (_this.attachedMesh) {\n // Snapping logic\n var snapped = false;\n var dragSteps = 0;\n if (_this.snapDistance == 0) {\n dragAxis.scaleToRef(event.dragDistance, tmpVector);\n }\n else {\n currentSnapDragDistance += event.dragDistance;\n if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {\n dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);\n currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;\n dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);\n snapped = true;\n }\n else {\n tmpVector.scaleInPlace(0);\n }\n }\n _this.attachedMesh.scaling.addInPlace(tmpVector);\n if (snapped) {\n tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;\n _this.onSnapObservable.notifyObservers(tmpSnapEvent);\n }\n }\n });\n _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {\n if (_this._customMeshSet) {\n return;\n }\n var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);\n var material = isHovered ? hoverMaterial : coloredMaterial;\n _this._rootMesh.getChildMeshes().forEach(function (m) {\n m.material = material;\n if (m.color) {\n m.color = material.emissiveColor;\n }\n });\n });\n return _this;\n }\n AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n };\n /**\n * Disposes of the gizmo\n */\n AxisScaleGizmo.prototype.dispose = function () {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n _super.prototype.dispose.call(this);\n };\n return AxisScaleGizmo;\n }(BABYLON.Gizmo));\n BABYLON.AxisScaleGizmo = AxisScaleGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.axisScaleGizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Single plane rotation gizmo\n */\n var PlaneRotationGizmo = /** @class */ (function (_super) {\n __extends(PlaneRotationGizmo, _super);\n /**\n * Creates a PlaneRotationGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param planeNormal The normal of the plane which the gizmo will be able to rotate on\n * @param color The color of the gizmo\n */\n function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {\n if (color === void 0) { color = BABYLON.Color3.Gray(); }\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this._pointerObserver = null;\n /**\n * Rotation distance in radians that the gizmo will snap to (Default: 0)\n */\n _this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n _this.onSnapObservable = new BABYLON.Observable();\n // Create Material\n var coloredMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n coloredMaterial.disableLighting = true;\n coloredMaterial.emissiveColor = color;\n var hoverMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n hoverMaterial.disableLighting = true;\n hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));\n // Build mesh on root node\n var parentMesh = new BABYLON.AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n // Create circle out of lines\n var tessellation = 20;\n var radius = 2;\n var points = new Array();\n for (var i = 0; i < tessellation; i++) {\n var radian = (2 * Math.PI) * (i / (tessellation - 1));\n points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));\n }\n var rotationMesh = BABYLON.Mesh.CreateLines(\"\", points, gizmoLayer.utilityLayerScene);\n rotationMesh.color = coloredMaterial.emissiveColor;\n // Position arrow pointing in its drag axis\n rotationMesh.scaling.scaleInPlace(0.1);\n rotationMesh.material = coloredMaterial;\n rotationMesh.rotation.x = Math.PI / 2;\n parentMesh.addChild(rotationMesh);\n parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));\n _this._rootMesh.addChild(parentMesh);\n // Add drag behavior to handle events when the gizmo is dragged\n _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });\n _this.dragBehavior.moveAttached = false;\n _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;\n _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;\n _this._rootMesh.addBehavior(_this.dragBehavior);\n var lastDragPosition = new BABYLON.Vector3();\n _this.dragBehavior.onDragStartObservable.add(function (e) {\n if (_this.attachedMesh) {\n lastDragPosition.copyFrom(e.dragPlanePoint);\n }\n });\n var rotationMatrix = new BABYLON.Matrix();\n var planeNormalTowardsCamera = new BABYLON.Vector3();\n var localPlaneNormalTowardsCamera = new BABYLON.Vector3();\n var tmpSnapEvent = { snapDistance: 0 };\n var currentSnapDragDistance = 0;\n _this.dragBehavior.onDragObservable.add(function (event) {\n if (_this.attachedMesh) {\n if (!_this.attachedMesh.rotationQuaternion) {\n _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);\n }\n // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)\n var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();\n var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();\n var cross = BABYLON.Vector3.Cross(newVector, originalVector);\n var dot = BABYLON.Vector3.Dot(newVector, originalVector);\n var angle = Math.atan2(cross.length(), dot);\n planeNormalTowardsCamera.copyFrom(planeNormal);\n localPlaneNormalTowardsCamera.copyFrom(planeNormal);\n if (_this.updateGizmoRotationToMatchAttachedMesh) {\n _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);\n localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);\n }\n // Flip up vector depending on which side the camera is on\n if (gizmoLayer.utilityLayerScene.activeCamera) {\n var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);\n if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {\n planeNormalTowardsCamera.scaleInPlace(-1);\n localPlaneNormalTowardsCamera.scaleInPlace(-1);\n }\n }\n var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;\n if (halfCircleSide)\n angle = -angle;\n // Snapping logic\n var snapped = false;\n if (_this.snapDistance != 0) {\n currentSnapDragDistance += angle;\n if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {\n var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);\n currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;\n angle = _this.snapDistance * dragSteps;\n snapped = true;\n }\n else {\n angle = 0;\n }\n }\n // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)\n var quaternionCoefficient = Math.sin(angle / 2);\n var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));\n if (_this.updateGizmoRotationToMatchAttachedMesh) {\n // Rotate selected mesh quaternion over fixed axis\n _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);\n }\n else {\n // Rotate selected mesh quaternion over rotated axis\n amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);\n }\n lastDragPosition.copyFrom(event.dragPlanePoint);\n if (snapped) {\n tmpSnapEvent.snapDistance = angle;\n _this.onSnapObservable.notifyObservers(tmpSnapEvent);\n }\n }\n });\n _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {\n if (_this._customMeshSet) {\n return;\n }\n var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);\n var material = isHovered ? hoverMaterial : coloredMaterial;\n _this._rootMesh.getChildMeshes().forEach(function (m) {\n m.material = material;\n if (m.color) {\n m.color = material.emissiveColor;\n }\n });\n });\n return _this;\n }\n PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n };\n /**\n * Disposes of the gizmo\n */\n PlaneRotationGizmo.prototype.dispose = function () {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n _super.prototype.dispose.call(this);\n };\n return PlaneRotationGizmo;\n }(BABYLON.Gizmo));\n BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.planeRotationGizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Gizmo that enables dragging a mesh along 3 axis\n */\n var PositionGizmo = /** @class */ (function (_super) {\n __extends(PositionGizmo, _super);\n /**\n * Creates a PositionGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n */\n function PositionGizmo(gizmoLayer) {\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);\n _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);\n _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);\n _this.attachedMesh = null;\n return _this;\n }\n Object.defineProperty(PositionGizmo.prototype, \"attachedMesh\", {\n set: function (mesh) {\n if (this.xGizmo) {\n this.xGizmo.attachedMesh = mesh;\n this.yGizmo.attachedMesh = mesh;\n this.zGizmo.attachedMesh = mesh;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PositionGizmo.prototype, \"updateGizmoRotationToMatchAttachedMesh\", {\n get: function () {\n return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;\n },\n set: function (value) {\n if (this.xGizmo) {\n this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes of the gizmo\n */\n PositionGizmo.prototype.dispose = function () {\n this.xGizmo.dispose();\n this.yGizmo.dispose();\n this.zGizmo.dispose();\n };\n /**\n * CustomMeshes are not supported by this gizmo\n * @param mesh The mesh to replace the default mesh of the gizmo\n */\n PositionGizmo.prototype.setCustomMesh = function (mesh) {\n BABYLON.Tools.Error(\"Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)\");\n };\n return PositionGizmo;\n }(BABYLON.Gizmo));\n BABYLON.PositionGizmo = PositionGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.positionGizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Gizmo that enables rotating a mesh along 3 axis\n */\n var RotationGizmo = /** @class */ (function (_super) {\n __extends(RotationGizmo, _super);\n /**\n * Creates a RotationGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n */\n function RotationGizmo(gizmoLayer) {\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);\n _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);\n _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);\n _this.attachedMesh = null;\n return _this;\n }\n Object.defineProperty(RotationGizmo.prototype, \"attachedMesh\", {\n set: function (mesh) {\n if (this.xGizmo) {\n this.xGizmo.attachedMesh = mesh;\n this.yGizmo.attachedMesh = mesh;\n this.zGizmo.attachedMesh = mesh;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RotationGizmo.prototype, \"updateGizmoRotationToMatchAttachedMesh\", {\n get: function () {\n return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;\n },\n set: function (value) {\n if (this.xGizmo) {\n this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes of the gizmo\n */\n RotationGizmo.prototype.dispose = function () {\n this.xGizmo.dispose();\n this.yGizmo.dispose();\n this.zGizmo.dispose();\n };\n /**\n * CustomMeshes are not supported by this gizmo\n * @param mesh The mesh to replace the default mesh of the gizmo\n */\n RotationGizmo.prototype.setCustomMesh = function (mesh) {\n BABYLON.Tools.Error(\"Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)\");\n };\n return RotationGizmo;\n }(BABYLON.Gizmo));\n BABYLON.RotationGizmo = RotationGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.rotationGizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Gizmo that enables scaling a mesh along 3 axis\n */\n var ScaleGizmo = /** @class */ (function (_super) {\n __extends(ScaleGizmo, _super);\n /**\n * Creates a ScaleGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n */\n function ScaleGizmo(gizmoLayer) {\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);\n _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);\n _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);\n _this.attachedMesh = null;\n return _this;\n }\n Object.defineProperty(ScaleGizmo.prototype, \"attachedMesh\", {\n set: function (mesh) {\n if (this.xGizmo) {\n this.xGizmo.attachedMesh = mesh;\n this.yGizmo.attachedMesh = mesh;\n this.zGizmo.attachedMesh = mesh;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ScaleGizmo.prototype, \"updateGizmoRotationToMatchAttachedMesh\", {\n get: function () {\n return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;\n },\n set: function (value) {\n if (this.xGizmo) {\n this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes of the gizmo\n */\n ScaleGizmo.prototype.dispose = function () {\n this.xGizmo.dispose();\n this.yGizmo.dispose();\n this.zGizmo.dispose();\n };\n return ScaleGizmo;\n }(BABYLON.Gizmo));\n BABYLON.ScaleGizmo = ScaleGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.scaleGizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Bounding box gizmo\n */\n var BoundingBoxGizmo = /** @class */ (function (_super) {\n __extends(BoundingBoxGizmo, _super);\n /**\n * Creates an BoundingBoxGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param color The color of the gizmo\n */\n function BoundingBoxGizmo(color, gizmoLayer) {\n if (color === void 0) { color = BABYLON.Color3.Gray(); }\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);\n _this._renderObserver = null;\n _this._pointerObserver = null;\n _this._scaleDragSpeed = 0.2;\n _this._tmpQuaternion = new BABYLON.Quaternion();\n _this._tmpVector = new BABYLON.Vector3(0, 0, 0);\n /**\n * The size of the rotation spheres attached to the bounding box (Default: 0.1)\n */\n _this.rotationSphereSize = 0.1;\n /**\n * The size of the scale boxes attached to the bounding box (Default: 0.1)\n */\n _this.scaleBoxSize = 0.1;\n /**\n * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)\n */\n _this.fixedDragMeshScreenSize = false;\n /**\n * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)\n */\n _this.fixedDragMeshScreenSizeDistanceFactor = 10;\n /**\n * Fired when a rotation sphere or scale box is dragged\n */\n _this.onDragStartObservable = new BABYLON.Observable();\n /**\n * Fired when a rotation sphere or scale box drag is started\n */\n _this.onDragObservable = new BABYLON.Observable();\n /**\n * Fired when a rotation sphere or scale box drag is needed\n */\n _this.onDragEndObservable = new BABYLON.Observable();\n _this._existingMeshScale = new BABYLON.Vector3();\n // Do not update the gizmo's scale so it has a fixed size to the object its attached to\n _this._updateScale = false;\n _this._anchorMesh = new BABYLON.AbstractMesh(\"anchor\", gizmoLayer.utilityLayerScene);\n // Create Materials\n var coloredMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n coloredMaterial.disableLighting = true;\n coloredMaterial.emissiveColor = color;\n var hoverColoredMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n hoverColoredMaterial.disableLighting = true;\n hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));\n // Build bounding box out of lines\n _this._lineBoundingBox = new BABYLON.AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();\n var lines = [];\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.forEach(function (l) {\n l.color = color;\n l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));\n l.isPickable = false;\n _this._lineBoundingBox.addChild(l);\n });\n _this._rootMesh.addChild(_this._lineBoundingBox);\n // Create rotation spheres\n _this._rotateSpheresParent = new BABYLON.AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();\n var _loop_1 = function (i_1) {\n var sphere = BABYLON.MeshBuilder.CreateSphere(\"\", { diameter: 1 }, gizmoLayer.utilityLayerScene);\n sphere.rotationQuaternion = new BABYLON.Quaternion();\n sphere.material = coloredMaterial;\n // Drag behavior\n _dragBehavior = new BABYLON.PointerDragBehavior({});\n _dragBehavior.moveAttached = false;\n _dragBehavior.updateDragPlane = false;\n sphere.addBehavior(_dragBehavior);\n var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);\n var totalTurnAmountOfDrag = 0;\n _dragBehavior.onDragStartObservable.add(function (event) {\n startingTurnDirection.copyFrom(sphere.forward);\n totalTurnAmountOfDrag = 0;\n });\n _dragBehavior.onDragObservable.add(function (event) {\n _this.onDragObservable.notifyObservers({});\n if (_this.attachedMesh) {\n var worldDragDirection = startingTurnDirection;\n // Project the world right on to the drag plane\n var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));\n var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();\n // project drag delta on to the resulting drag axis and rotate based on that\n var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);\n // Make rotation relative to size of mesh.\n projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();\n // Rotate based on axis\n if (!_this.attachedMesh.rotationQuaternion) {\n _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);\n }\n if (!_this._anchorMesh.rotationQuaternion) {\n _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);\n }\n // Do not allow the object to turn more than a full circle\n totalTurnAmountOfDrag += projectDist;\n if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {\n if (i_1 >= 8) {\n BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);\n }\n else if (i_1 >= 4) {\n BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);\n }\n else {\n BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);\n }\n // Rotate around center of bounding box\n _this._anchorMesh.addChild(_this.attachedMesh);\n _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);\n _this._anchorMesh.removeChild(_this.attachedMesh);\n }\n _this.updateBoundingBox();\n }\n });\n // Selection/deselection\n _dragBehavior.onDragStartObservable.add(function () {\n _this.onDragStartObservable.notifyObservers({});\n _this._selectNode(sphere);\n });\n _dragBehavior.onDragEndObservable.add(function () {\n _this.onDragEndObservable.notifyObservers({});\n _this._selectNode(null);\n });\n this_1._rotateSpheresParent.addChild(sphere);\n };\n var this_1 = this, _dragBehavior;\n for (var i_1 = 0; i_1 < 12; i_1++) {\n _loop_1(i_1);\n }\n _this._rootMesh.addChild(_this._rotateSpheresParent);\n // Create scale cubes\n _this._scaleBoxesParent = new BABYLON.AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();\n for (var i = 0; i < 2; i++) {\n for (var j = 0; j < 2; j++) {\n var _loop_2 = function () {\n var box = BABYLON.MeshBuilder.CreateBox(\"\", { size: 1 }, gizmoLayer.utilityLayerScene);\n box.material = coloredMaterial;\n // Dragging logic\n var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);\n _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });\n _dragBehavior.moveAttached = false;\n box.addBehavior(_dragBehavior);\n _dragBehavior.onDragObservable.add(function (event) {\n _this.onDragObservable.notifyObservers({});\n if (_this.attachedMesh) {\n var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();\n var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);\n deltaScale.scaleInPlace(_this._scaleDragSpeed);\n _this.updateBoundingBox();\n // Scale from the position of the opposite corner \n box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);\n _this._anchorMesh.position.subtractInPlace(_this._tmpVector);\n _this._anchorMesh.addChild(_this.attachedMesh);\n _this._anchorMesh.scaling.addInPlace(deltaScale);\n if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {\n _this._anchorMesh.scaling.subtractInPlace(deltaScale);\n }\n _this._anchorMesh.removeChild(_this.attachedMesh);\n }\n });\n // Selection/deselection\n _dragBehavior.onDragStartObservable.add(function () {\n _this.onDragStartObservable.notifyObservers({});\n _this._selectNode(box);\n });\n _dragBehavior.onDragEndObservable.add(function () {\n _this.onDragEndObservable.notifyObservers({});\n _this._selectNode(null);\n });\n this_2._scaleBoxesParent.addChild(box);\n };\n var this_2 = this, _dragBehavior;\n for (var k = 0; k < 2; k++) {\n _loop_2();\n }\n }\n }\n _this._rootMesh.addChild(_this._scaleBoxesParent);\n // Hover color change\n var pointerIds = new Array();\n _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {\n if (!pointerIds[pointerInfo.event.pointerId]) {\n _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {\n pointerIds[pointerInfo.event.pointerId] = mesh;\n mesh.material = hoverColoredMaterial;\n }\n });\n }\n else {\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {\n pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;\n delete pointerIds[pointerInfo.event.pointerId];\n }\n }\n });\n // Update bounding box positions\n _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {\n // Only update the bouding box if scaling has changed\n if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {\n _this.updateBoundingBox();\n }\n });\n _this.updateBoundingBox();\n return _this;\n }\n BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {\n if (value) {\n // Reset anchor mesh to match attached mesh's scale\n // This is needed to avoid invalid box/sphere position on first drag\n this._anchorMesh.addChild(value);\n this._anchorMesh.removeChild(value);\n this.updateBoundingBox();\n }\n };\n BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {\n this._rotateSpheresParent.getChildMeshes()\n .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {\n m.isVisible = (!selectedMesh || m == selectedMesh);\n });\n };\n BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {\n var _this = this;\n mesh.computeWorldMatrix(true);\n mesh.getChildMeshes().forEach(function (m) {\n _this._recurseComputeWorld(m);\n });\n };\n /**\n * Updates the bounding box information for the Gizmo\n */\n BoundingBoxGizmo.prototype.updateBoundingBox = function () {\n this._update();\n if (this.attachedMesh) {\n // Rotate based on axis\n if (!this.attachedMesh.rotationQuaternion) {\n this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);\n }\n if (!this._anchorMesh.rotationQuaternion) {\n this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);\n }\n this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);\n // Store original position and reset mesh to origin before computing the bounding box\n this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);\n this._tmpVector.copyFrom(this.attachedMesh.position);\n this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);\n this.attachedMesh.position.set(0, 0, 0);\n // Update bounding dimensions/positions \n var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();\n boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);\n // Update gizmo to match bounding box scaling and rotation\n this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);\n this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);\n this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);\n this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);\n this._lineBoundingBox.computeWorldMatrix();\n this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);\n // restore position/rotation values\n this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);\n this.attachedMesh.position.copyFrom(this._tmpVector);\n this._recurseComputeWorld(this.attachedMesh);\n }\n // Update rotation sphere locations\n var rotateSpheres = this._rotateSpheresParent.getChildMeshes();\n for (var i = 0; i < 3; i++) {\n for (var j = 0; j < 2; j++) {\n for (var k = 0; k < 2; k++) {\n var index = ((i * 4) + (j * 2)) + k;\n if (i == 0) {\n rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);\n rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));\n }\n if (i == 1) {\n rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);\n rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));\n }\n if (i == 2) {\n rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);\n rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));\n }\n if (this.fixedDragMeshScreenSize) {\n this._rootMesh.computeWorldMatrix();\n this._rotateSpheresParent.computeWorldMatrix();\n rotateSpheres[index].computeWorldMatrix();\n rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);\n var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;\n rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);\n }\n else {\n rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);\n }\n }\n }\n }\n // Update scale box locations\n var scaleBoxes = this._scaleBoxesParent.getChildMeshes();\n for (var i = 0; i < 2; i++) {\n for (var j = 0; j < 2; j++) {\n for (var k = 0; k < 2; k++) {\n var index = ((i * 4) + (j * 2)) + k;\n if (scaleBoxes[index]) {\n scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);\n scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n if (this.fixedDragMeshScreenSize) {\n this._rootMesh.computeWorldMatrix();\n this._scaleBoxesParent.computeWorldMatrix();\n scaleBoxes[index].computeWorldMatrix();\n scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);\n var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;\n scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);\n }\n else {\n scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);\n }\n }\n }\n }\n }\n if (this.attachedMesh) {\n this._existingMeshScale.copyFrom(this.attachedMesh.scaling);\n }\n };\n /**\n * Enables rotation on the specified axis and disables rotation on the others\n * @param axis The list of axis that should be enabled (eg. \"xy\" or \"xyz\")\n */\n BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {\n this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {\n if (i < 4) {\n m.setEnabled(axis.indexOf(\"x\") != -1);\n }\n else if (i < 8) {\n m.setEnabled(axis.indexOf(\"y\") != -1);\n }\n else {\n m.setEnabled(axis.indexOf(\"z\") != -1);\n }\n });\n };\n /**\n * Disposes of the gizmo\n */\n BoundingBoxGizmo.prototype.dispose = function () {\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);\n this._lineBoundingBox.dispose();\n this._rotateSpheresParent.dispose();\n this._scaleBoxesParent.dispose();\n _super.prototype.dispose.call(this);\n };\n /**\n * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)\n * @param mesh the mesh to wrap in the bounding box mesh and make not pickable\n * @returns the bounding box mesh with the passed in mesh as a child\n */\n BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {\n var makeNotPickable = function (root) {\n root.isPickable = false;\n root.getChildMeshes().forEach(function (c) {\n makeNotPickable(c);\n });\n };\n makeNotPickable(mesh);\n // Reset position to get boudning box from origin with no rotation\n if (!mesh.rotationQuaternion) {\n mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);\n }\n var oldPos = mesh.position.clone();\n var oldRot = mesh.rotationQuaternion.clone();\n mesh.rotationQuaternion.set(0, 0, 0, 1);\n mesh.position.set(0, 0, 0);\n // Update bounding dimensions/positions \n var box = BABYLON.MeshBuilder.CreateBox(\"box\", { size: 1 }, mesh.getScene());\n var boundingMinMax = mesh.getHierarchyBoundingVectors();\n boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);\n box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);\n // Restore original positions\n mesh.addChild(box);\n mesh.rotationQuaternion.copyFrom(oldRot);\n mesh.position.copyFrom(oldPos);\n // Reverse parenting\n mesh.removeChild(box);\n box.addChild(mesh);\n box.visibility = 0;\n return box;\n };\n /**\n * CustomMeshes are not supported by this gizmo\n * @param mesh The mesh to replace the default mesh of the gizmo\n */\n BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {\n BABYLON.Tools.Error(\"Custom meshes are not supported on this gizmo\");\n };\n return BoundingBoxGizmo;\n }(BABYLON.Gizmo));\n BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boundingBoxGizmo.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Helps setup gizmo's in the scene to rotate/scale/position meshes\n */\n var GizmoManager = /** @class */ (function () {\n /**\n * Instatiates a gizmo manager\n * @param scene the scene to overlay the gizmos on top of\n */\n function GizmoManager(scene) {\n var _this = this;\n this.scene = scene;\n this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };\n this._pointerObserver = null;\n this._attachedMesh = null;\n this._boundingBoxColor = BABYLON.Color3.FromHexString(\"#0984e3\");\n this._dragBehavior = new BABYLON.SixDofDragBehavior();\n /**\n * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)\n */\n this.attachableMeshes = null;\n /**\n * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)\n */\n this.usePointerToAttachGizmos = true;\n this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };\n // Instatiate/dispose gizmos based on pointer actions\n this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {\n if (!_this.usePointerToAttachGizmos) {\n return;\n }\n if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {\n var node = pointerInfo.pickInfo.pickedMesh;\n if (_this.attachableMeshes == null) {\n // Attach to the most parent node\n while (node && node.parent != null) {\n node = node.parent;\n }\n }\n else {\n // Attach to the parent node that is an attachableMesh\n var found = false;\n _this.attachableMeshes.forEach(function (mesh) {\n if (node && (node == mesh || node.isDescendantOf(mesh))) {\n node = mesh;\n found = true;\n }\n });\n if (!found) {\n node = null;\n }\n }\n if (node instanceof BABYLON.AbstractMesh) {\n _this.attachToMesh(node);\n }\n }\n else {\n _this.attachToMesh(null);\n }\n }\n });\n }\n /**\n * Attaches a set of gizmos to the specified mesh\n * @param mesh The mesh the gizmo's should be attached to\n */\n GizmoManager.prototype.attachToMesh = function (mesh) {\n if (this._attachedMesh) {\n this._attachedMesh.removeBehavior(this._dragBehavior);\n }\n this._attachedMesh = mesh;\n for (var key in this.gizmos) {\n var gizmo = (this.gizmos[key]);\n if (gizmo && this._gizmosEnabled[key]) {\n gizmo.attachedMesh = mesh;\n }\n }\n if (this.boundingBoxGizmoEnabled && this._attachedMesh) {\n this._attachedMesh.addBehavior(this._dragBehavior);\n }\n };\n Object.defineProperty(GizmoManager.prototype, \"positionGizmoEnabled\", {\n get: function () {\n return this._gizmosEnabled.positionGizmo;\n },\n /**\n * If the position gizmo is enabled\n */\n set: function (value) {\n if (value) {\n this.gizmos.positionGizmo = this.gizmos.positionGizmo || new BABYLON.PositionGizmo();\n this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;\n this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;\n }\n else if (this.gizmos.positionGizmo) {\n this.gizmos.positionGizmo.attachedMesh = null;\n }\n this._gizmosEnabled.positionGizmo = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GizmoManager.prototype, \"rotationGizmoEnabled\", {\n get: function () {\n return this._gizmosEnabled.rotationGizmo;\n },\n /**\n * If the rotation gizmo is enabled\n */\n set: function (value) {\n if (value) {\n this.gizmos.rotationGizmo = this.gizmos.rotationGizmo || new BABYLON.RotationGizmo();\n this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;\n this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;\n }\n else if (this.gizmos.rotationGizmo) {\n this.gizmos.rotationGizmo.attachedMesh = null;\n }\n this._gizmosEnabled.rotationGizmo = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GizmoManager.prototype, \"scaleGizmoEnabled\", {\n get: function () {\n return this._gizmosEnabled.scaleGizmo;\n },\n /**\n * If the scale gizmo is enabled\n */\n set: function (value) {\n if (value) {\n this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();\n this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;\n }\n else if (this.gizmos.scaleGizmo) {\n this.gizmos.scaleGizmo.attachedMesh = null;\n }\n this._gizmosEnabled.scaleGizmo = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GizmoManager.prototype, \"boundingBoxGizmoEnabled\", {\n get: function () {\n return this._gizmosEnabled.boundingBoxGizmo;\n },\n /**\n * If the boundingBox gizmo is enabled\n */\n set: function (value) {\n if (value) {\n this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);\n this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;\n if (this._attachedMesh) {\n this._attachedMesh.removeBehavior(this._dragBehavior);\n this._attachedMesh.addBehavior(this._dragBehavior);\n }\n }\n else if (this.gizmos.boundingBoxGizmo) {\n this.gizmos.boundingBoxGizmo.attachedMesh = null;\n }\n this._gizmosEnabled.boundingBoxGizmo = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes of the gizmo manager\n */\n GizmoManager.prototype.dispose = function () {\n this.scene.onPointerObservable.remove(this._pointerObserver);\n for (var key in this.gizmos) {\n var gizmo = (this.gizmos[key]);\n if (gizmo) {\n gizmo.dispose();\n }\n }\n this._dragBehavior.detach();\n this._gizmoLayer.dispose();\n };\n return GizmoManager;\n }());\n BABYLON.GizmoManager = GizmoManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gizmoManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines a target to use with MorphTargetManager\n * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets\n */\n var MorphTarget = /** @class */ (function () {\n /**\n * Creates a new MorphTarget\n * @param name defines the name of the target\n * @param influence defines the influence to use\n */\n function MorphTarget(\n /** defines the name of the target */\n name, influence, scene) {\n if (influence === void 0) { influence = 0; }\n if (scene === void 0) { scene = null; }\n this.name = name;\n /**\n * Gets or sets the list of animations\n */\n this.animations = new Array();\n this._positions = null;\n this._normals = null;\n this._tangents = null;\n /**\n * Observable raised when the influence changes\n */\n this.onInfluenceChanged = new BABYLON.Observable();\n this._animationPropertiesOverride = null;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this.influence = influence;\n }\n Object.defineProperty(MorphTarget.prototype, \"influence\", {\n /**\n * Gets or sets the influence of this target (ie. its weight in the overall morphing)\n */\n get: function () {\n return this._influence;\n },\n set: function (influence) {\n if (this._influence === influence) {\n return;\n }\n var previous = this._influence;\n this._influence = influence;\n if (this.onInfluenceChanged.hasObservers) {\n this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTarget.prototype, \"animationPropertiesOverride\", {\n /**\n * Gets or sets the animation properties override\n */\n get: function () {\n if (!this._animationPropertiesOverride && this._scene) {\n return this._scene.animationPropertiesOverride;\n }\n return this._animationPropertiesOverride;\n },\n set: function (value) {\n this._animationPropertiesOverride = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTarget.prototype, \"hasPositions\", {\n /**\n * Gets a boolean defining if the target contains position data\n */\n get: function () {\n return !!this._positions;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTarget.prototype, \"hasNormals\", {\n /**\n * Gets a boolean defining if the target contains normal data\n */\n get: function () {\n return !!this._normals;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTarget.prototype, \"hasTangents\", {\n /**\n * Gets a boolean defining if the target contains tangent data\n */\n get: function () {\n return !!this._tangents;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Affects position data to this target\n * @param data defines the position data to use\n */\n MorphTarget.prototype.setPositions = function (data) {\n this._positions = data;\n };\n /**\n * Gets the position data stored in this target\n * @returns a FloatArray containing the position data (or null if not present)\n */\n MorphTarget.prototype.getPositions = function () {\n return this._positions;\n };\n /**\n * Affects normal data to this target\n * @param data defines the normal data to use\n */\n MorphTarget.prototype.setNormals = function (data) {\n this._normals = data;\n };\n /**\n * Gets the normal data stored in this target\n * @returns a FloatArray containing the normal data (or null if not present)\n */\n MorphTarget.prototype.getNormals = function () {\n return this._normals;\n };\n /**\n * Affects tangent data to this target\n * @param data defines the tangent data to use\n */\n MorphTarget.prototype.setTangents = function (data) {\n this._tangents = data;\n };\n /**\n * Gets the tangent data stored in this target\n * @returns a FloatArray containing the tangent data (or null if not present)\n */\n MorphTarget.prototype.getTangents = function () {\n return this._tangents;\n };\n /**\n * Serializes the current target into a Serialization object\n * @returns the serialized object\n */\n MorphTarget.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.influence = this.influence;\n serializationObject.positions = Array.prototype.slice.call(this.getPositions());\n if (this.hasNormals) {\n serializationObject.normals = Array.prototype.slice.call(this.getNormals());\n }\n if (this.hasTangents) {\n serializationObject.tangents = Array.prototype.slice.call(this.getTangents());\n }\n // Animations\n BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);\n return serializationObject;\n };\n // Statics\n /**\n * Creates a new target from serialized data\n * @param serializationObject defines the serialized data to use\n * @returns a new MorphTarget\n */\n MorphTarget.Parse = function (serializationObject) {\n var result = new MorphTarget(serializationObject.name, serializationObject.influence);\n result.setPositions(serializationObject.positions);\n if (serializationObject.normals) {\n result.setNormals(serializationObject.normals);\n }\n if (serializationObject.tangents) {\n result.setTangents(serializationObject.tangents);\n }\n // Animations\n if (serializationObject.animations) {\n for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {\n var parsedAnimation = serializationObject.animations[animationIndex];\n result.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n }\n return result;\n };\n /**\n * Creates a MorphTarget from mesh data\n * @param mesh defines the source mesh\n * @param name defines the name to use for the new target\n * @param influence defines the influence to attach to the target\n * @returns a new MorphTarget\n */\n MorphTarget.FromMesh = function (mesh, name, influence) {\n if (!name) {\n name = mesh.name;\n }\n var result = new MorphTarget(name, influence, mesh.getScene());\n result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {\n result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));\n }\n return result;\n };\n return MorphTarget;\n }());\n BABYLON.MorphTarget = MorphTarget;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.morphTarget.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class is used to deform meshes using morphing between different targets\n * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets\n */\n var MorphTargetManager = /** @class */ (function () {\n /**\n * Creates a new MorphTargetManager\n * @param scene defines the current scene\n */\n function MorphTargetManager(scene) {\n if (scene === void 0) { scene = null; }\n this._targets = new Array();\n this._targetObservable = new Array();\n this._activeTargets = new BABYLON.SmartArray(16);\n this._supportsNormals = false;\n this._supportsTangents = false;\n this._vertexCount = 0;\n this._uniqueId = 0;\n this._tempInfluences = new Array();\n if (!scene) {\n scene = BABYLON.Engine.LastCreatedScene;\n }\n this._scene = scene;\n if (this._scene) {\n this._scene.morphTargetManagers.push(this);\n this._uniqueId = this._scene.getUniqueId();\n }\n }\n Object.defineProperty(MorphTargetManager.prototype, \"uniqueId\", {\n /**\n * Gets the unique ID of this manager\n */\n get: function () {\n return this._uniqueId;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTargetManager.prototype, \"vertexCount\", {\n /**\n * Gets the number of vertices handled by this manager\n */\n get: function () {\n return this._vertexCount;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTargetManager.prototype, \"supportsNormals\", {\n /**\n * Gets a boolean indicating if this manager supports morphing of normals\n */\n get: function () {\n return this._supportsNormals;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTargetManager.prototype, \"supportsTangents\", {\n /**\n * Gets a boolean indicating if this manager supports morphing of tangents\n */\n get: function () {\n return this._supportsTangents;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTargetManager.prototype, \"numTargets\", {\n /**\n * Gets the number of targets stored in this manager\n */\n get: function () {\n return this._targets.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTargetManager.prototype, \"numInfluencers\", {\n /**\n * Gets the number of influencers (ie. the number of targets with influences > 0)\n */\n get: function () {\n return this._activeTargets.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTargetManager.prototype, \"influences\", {\n /**\n * Gets the list of influences (one per target)\n */\n get: function () {\n return this._influences;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the active target at specified index. An active target is a target with an influence > 0\n * @param index defines the index to check\n * @returns the requested target\n */\n MorphTargetManager.prototype.getActiveTarget = function (index) {\n return this._activeTargets.data[index];\n };\n /**\n * Gets the target at specified index\n * @param index defines the index to check\n * @returns the requested target\n */\n MorphTargetManager.prototype.getTarget = function (index) {\n return this._targets[index];\n };\n /**\n * Add a new target to this manager\n * @param target defines the target to add\n */\n MorphTargetManager.prototype.addTarget = function (target) {\n var _this = this;\n this._targets.push(target);\n this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {\n _this._syncActiveTargets(needUpdate);\n }));\n this._syncActiveTargets(true);\n };\n /**\n * Removes a target from the manager\n * @param target defines the target to remove\n */\n MorphTargetManager.prototype.removeTarget = function (target) {\n var index = this._targets.indexOf(target);\n if (index >= 0) {\n this._targets.splice(index, 1);\n target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);\n this._syncActiveTargets(true);\n }\n };\n /**\n * Serializes the current manager into a Serialization object\n * @returns the serialized object\n */\n MorphTargetManager.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.id = this.uniqueId;\n serializationObject.targets = [];\n for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {\n var target = _a[_i];\n serializationObject.targets.push(target.serialize());\n }\n return serializationObject;\n };\n MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {\n var influenceCount = 0;\n this._activeTargets.reset();\n this._supportsNormals = true;\n this._supportsTangents = true;\n this._vertexCount = 0;\n for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {\n var target = _a[_i];\n this._activeTargets.push(target);\n this._tempInfluences[influenceCount++] = target.influence;\n var positions = target.getPositions();\n if (positions) {\n this._supportsNormals = this._supportsNormals && target.hasNormals;\n this._supportsTangents = this._supportsTangents && target.hasTangents;\n var vertexCount = positions.length / 3;\n if (this._vertexCount === 0) {\n this._vertexCount = vertexCount;\n }\n else if (this._vertexCount !== vertexCount) {\n BABYLON.Tools.Error(\"Incompatible target. Targets must all have the same vertices count.\");\n return;\n }\n }\n }\n if (!this._influences || this._influences.length !== influenceCount) {\n this._influences = new Float32Array(influenceCount);\n }\n for (var index = 0; index < influenceCount; index++) {\n this._influences[index] = this._tempInfluences[index];\n }\n if (needUpdate) {\n this.synchronize();\n }\n };\n /**\n * Syncrhonize the targets with all the meshes using this morph target manager\n */\n MorphTargetManager.prototype.synchronize = function () {\n if (!this._scene) {\n return;\n }\n // Flag meshes as dirty to resync with the active targets\n for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n if (mesh.morphTargetManager === this) {\n mesh._syncGeometryWithMorphTargetManager();\n }\n }\n };\n // Statics\n /**\n * Creates a new MorphTargetManager from serialized data\n * @param serializationObject defines the serialized data\n * @param scene defines the hosting scene\n * @returns the new MorphTargetManager\n */\n MorphTargetManager.Parse = function (serializationObject, scene) {\n var result = new MorphTargetManager(scene);\n result._uniqueId = serializationObject.id;\n for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {\n var targetData = _a[_i];\n result.addTarget(BABYLON.MorphTarget.Parse(targetData));\n }\n return result;\n };\n return MorphTargetManager;\n }());\n BABYLON.MorphTargetManager = MorphTargetManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.morphTargetManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Octree = /** @class */ (function () {\n function Octree(creationFunc, maxBlockCapacity, maxDepth) {\n if (maxDepth === void 0) { maxDepth = 2; }\n this.maxDepth = maxDepth;\n this.dynamicContent = new Array();\n this._maxBlockCapacity = maxBlockCapacity || 64;\n this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);\n this._creationFunc = creationFunc;\n }\n // Methods\n Octree.prototype.update = function (worldMin, worldMax, entries) {\n Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);\n };\n Octree.prototype.addMesh = function (entry) {\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.addEntry(entry);\n }\n };\n Octree.prototype.select = function (frustumPlanes, allowDuplicate) {\n this._selectionContent.reset();\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.select(frustumPlanes, this._selectionContent, allowDuplicate);\n }\n if (allowDuplicate) {\n this._selectionContent.concat(this.dynamicContent);\n }\n else {\n this._selectionContent.concatWithNoDuplicate(this.dynamicContent);\n }\n return this._selectionContent;\n };\n Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {\n this._selectionContent.reset();\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);\n }\n if (allowDuplicate) {\n this._selectionContent.concat(this.dynamicContent);\n }\n else {\n this._selectionContent.concatWithNoDuplicate(this.dynamicContent);\n }\n return this._selectionContent;\n };\n Octree.prototype.intersectsRay = function (ray) {\n this._selectionContent.reset();\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.intersectsRay(ray, this._selectionContent);\n }\n this._selectionContent.concatWithNoDuplicate(this.dynamicContent);\n return this._selectionContent;\n };\n Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {\n target.blocks = new Array();\n var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);\n // Segmenting space\n for (var x = 0; x < 2; x++) {\n for (var y = 0; y < 2; y++) {\n for (var z = 0; z < 2; z++) {\n var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));\n var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));\n var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);\n block.addEntries(entries);\n target.blocks.push(block);\n }\n }\n }\n };\n Octree.CreationFuncForMeshes = function (entry, block) {\n var boundingInfo = entry.getBoundingInfo();\n if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {\n block.entries.push(entry);\n }\n };\n Octree.CreationFuncForSubMeshes = function (entry, block) {\n var boundingInfo = entry.getBoundingInfo();\n if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {\n block.entries.push(entry);\n }\n };\n return Octree;\n }());\n BABYLON.Octree = Octree;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.octree.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var OctreeBlock = /** @class */ (function () {\n function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {\n this.entries = new Array();\n this._boundingVectors = new Array();\n this._capacity = capacity;\n this._depth = depth;\n this._maxDepth = maxDepth;\n this._creationFunc = creationFunc;\n this._minPoint = minPoint;\n this._maxPoint = maxPoint;\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors[2].x = maxPoint.x;\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors[3].y = maxPoint.y;\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors[4].z = maxPoint.z;\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors[5].z = minPoint.z;\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors[6].x = minPoint.x;\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors[7].y = minPoint.y;\n }\n Object.defineProperty(OctreeBlock.prototype, \"capacity\", {\n // Property\n get: function () {\n return this._capacity;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(OctreeBlock.prototype, \"minPoint\", {\n get: function () {\n return this._minPoint;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(OctreeBlock.prototype, \"maxPoint\", {\n get: function () {\n return this._maxPoint;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n OctreeBlock.prototype.addEntry = function (entry) {\n if (this.blocks) {\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.addEntry(entry);\n }\n return;\n }\n this._creationFunc(entry, this);\n if (this.entries.length > this.capacity && this._depth < this._maxDepth) {\n this.createInnerBlocks();\n }\n };\n OctreeBlock.prototype.addEntries = function (entries) {\n for (var index = 0; index < entries.length; index++) {\n var mesh = entries[index];\n this.addEntry(mesh);\n }\n };\n OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {\n if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {\n if (this.blocks) {\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.select(frustumPlanes, selection, allowDuplicate);\n }\n return;\n }\n if (allowDuplicate) {\n selection.concat(this.entries);\n }\n else {\n selection.concatWithNoDuplicate(this.entries);\n }\n }\n };\n OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {\n if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {\n if (this.blocks) {\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);\n }\n return;\n }\n if (allowDuplicate) {\n selection.concat(this.entries);\n }\n else {\n selection.concatWithNoDuplicate(this.entries);\n }\n }\n };\n OctreeBlock.prototype.intersectsRay = function (ray, selection) {\n if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {\n if (this.blocks) {\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.intersectsRay(ray, selection);\n }\n return;\n }\n selection.concatWithNoDuplicate(this.entries);\n }\n };\n OctreeBlock.prototype.createInnerBlocks = function () {\n BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);\n };\n return OctreeBlock;\n }());\n BABYLON.OctreeBlock = OctreeBlock;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.octreeBlock.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Postprocess used to generate anaglyphic rendering\n */\n var AnaglyphPostProcess = /** @class */ (function (_super) {\n __extends(AnaglyphPostProcess, _super);\n /**\n * Creates a new AnaglyphPostProcess\n * @param name defines postprocess name\n * @param options defines creation options or target ratio scale\n * @param rigCameras defines cameras using this postprocess\n * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)\n * @param engine defines hosting engine\n * @param reusable defines if the postprocess will be reused multiple times per frame\n */\n function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {\n var _this = _super.call(this, name, \"anaglyph\", null, [\"leftSampler\"], options, rigCameras[1], samplingMode, engine, reusable) || this;\n _this._passedProcess = rigCameras[0]._rigPostProcess;\n _this.onApplyObservable.add(function (effect) {\n effect.setTextureFromPostProcess(\"leftSampler\", _this._passedProcess);\n });\n return _this;\n }\n return AnaglyphPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.anaglyphPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"AnaglyphArcRotateCamera\", function (name, scene, options) {\n return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };\n });\n /**\n * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)\n */\n var AnaglyphArcRotateCamera = /** @class */ (function (_super) {\n __extends(AnaglyphArcRotateCamera, _super);\n /**\n * Creates a new AnaglyphArcRotateCamera\n * @param name defines camera name\n * @param alpha defines alpha angle (in radians)\n * @param beta defines beta angle (in radians)\n * @param radius defines radius\n * @param target defines camera target\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {\n var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns AnaglyphArcRotateCamera\n */\n AnaglyphArcRotateCamera.prototype.getClassName = function () {\n return \"AnaglyphArcRotateCamera\";\n };\n return AnaglyphArcRotateCamera;\n }(BABYLON.ArcRotateCamera));\n BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"AnaglyphFreeCamera\", function (name, scene, options) {\n return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };\n });\n /**\n * Camera used to simulate anaglyphic rendering (based on FreeCamera)\n */\n var AnaglyphFreeCamera = /** @class */ (function (_super) {\n __extends(AnaglyphFreeCamera, _super);\n /**\n * Creates a new AnaglyphFreeCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns AnaglyphFreeCamera\n */\n AnaglyphFreeCamera.prototype.getClassName = function () {\n return \"AnaglyphFreeCamera\";\n };\n return AnaglyphFreeCamera;\n }(BABYLON.FreeCamera));\n BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.anaglyphFreeCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"AnaglyphGamepadCamera\", function (name, scene, options) {\n return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };\n });\n /**\n * Camera used to simulate anaglyphic rendering (based on GamepadCamera)\n */\n var AnaglyphGamepadCamera = /** @class */ (function (_super) {\n __extends(AnaglyphGamepadCamera, _super);\n /**\n * Creates a new AnaglyphGamepadCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns AnaglyphGamepadCamera\n */\n AnaglyphGamepadCamera.prototype.getClassName = function () {\n return \"AnaglyphGamepadCamera\";\n };\n return AnaglyphGamepadCamera;\n }(BABYLON.GamepadCamera));\n BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"AnaglyphUniversalCamera\", function (name, scene, options) {\n return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };\n });\n /**\n * Camera used to simulate anaglyphic rendering (based on UniversalCamera)\n */\n var AnaglyphUniversalCamera = /** @class */ (function (_super) {\n __extends(AnaglyphUniversalCamera, _super);\n /**\n * Creates a new AnaglyphUniversalCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns AnaglyphUniversalCamera\n */\n AnaglyphUniversalCamera.prototype.getClassName = function () {\n return \"AnaglyphUniversalCamera\";\n };\n return AnaglyphUniversalCamera;\n }(BABYLON.UniversalCamera));\n BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {\n __extends(StereoscopicInterlacePostProcess, _super);\n function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {\n var _this = _super.call(this, name, \"stereoscopicInterlace\", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? \"#define IS_STEREOSCOPIC_HORIZ 1\" : undefined) || this;\n _this._passedProcess = rigCameras[0]._rigPostProcess;\n _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);\n _this.onSizeChangedObservable.add(function () {\n _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);\n });\n _this.onApplyObservable.add(function (effect) {\n effect.setTextureFromPostProcess(\"camASampler\", _this._passedProcess);\n effect.setFloat2(\"stepSize\", _this._stepSize.x, _this._stepSize.y);\n });\n return _this;\n }\n return StereoscopicInterlacePostProcess;\n }(BABYLON.PostProcess));\n BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"StereoscopicArcRotateCamera\", function (name, scene, options) {\n return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };\n });\n /**\n * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)\n */\n var StereoscopicArcRotateCamera = /** @class */ (function (_super) {\n __extends(StereoscopicArcRotateCamera, _super);\n /**\n * Creates a new StereoscopicArcRotateCamera\n * @param name defines camera name\n * @param alpha defines alpha angle (in radians)\n * @param beta defines beta angle (in radians)\n * @param radius defines radius\n * @param target defines camera target\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {\n var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns StereoscopicArcRotateCamera\n */\n StereoscopicArcRotateCamera.prototype.getClassName = function () {\n return \"StereoscopicArcRotateCamera\";\n };\n return StereoscopicArcRotateCamera;\n }(BABYLON.ArcRotateCamera));\n BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"StereoscopicFreeCamera\", function (name, scene, options) {\n return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };\n });\n /**\n * Camera used to simulate stereoscopic rendering (based on FreeCamera)\n */\n var StereoscopicFreeCamera = /** @class */ (function (_super) {\n __extends(StereoscopicFreeCamera, _super);\n /**\n * Creates a new StereoscopicFreeCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns StereoscopicFreeCamera\n */\n StereoscopicFreeCamera.prototype.getClassName = function () {\n return \"StereoscopicFreeCamera\";\n };\n return StereoscopicFreeCamera;\n }(BABYLON.FreeCamera));\n BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"StereoscopicGamepadCamera\", function (name, scene, options) {\n return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };\n });\n /**\n * Camera used to simulate stereoscopic rendering (based on GamepadCamera)\n */\n var StereoscopicGamepadCamera = /** @class */ (function (_super) {\n __extends(StereoscopicGamepadCamera, _super);\n /**\n * Creates a new StereoscopicGamepadCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns StereoscopicGamepadCamera\n */\n StereoscopicGamepadCamera.prototype.getClassName = function () {\n return \"StereoscopicGamepadCamera\";\n };\n return StereoscopicGamepadCamera;\n }(BABYLON.GamepadCamera));\n BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"StereoscopicFreeCamera\", function (name, scene, options) {\n return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };\n });\n /**\n * Camera used to simulate stereoscopic rendering (based on UniversalCamera)\n */\n var StereoscopicUniversalCamera = /** @class */ (function (_super) {\n __extends(StereoscopicUniversalCamera, _super);\n /**\n * Creates a new StereoscopicUniversalCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns StereoscopicUniversalCamera\n */\n StereoscopicUniversalCamera.prototype.getClassName = function () {\n return \"StereoscopicUniversalCamera\";\n };\n return StereoscopicUniversalCamera;\n }(BABYLON.UniversalCamera));\n BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {\n __extends(VRDistortionCorrectionPostProcess, _super);\n function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {\n var _this = _super.call(this, name, \"vrDistortionCorrection\", [\n 'LensCenter',\n 'Scale',\n 'ScaleIn',\n 'HmdWarpParam'\n ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;\n _this._isRightEye = isRightEye;\n _this._distortionFactors = vrMetrics.distortionK;\n _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;\n _this._lensCenterOffset = vrMetrics.lensCenterOffset;\n _this.adaptScaleToCurrentViewport = true;\n _this.onSizeChangedObservable.add(function () {\n _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);\n _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);\n _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);\n });\n _this.onApplyObservable.add(function (effect) {\n effect.setFloat2(\"LensCenter\", _this._lensCenter.x, _this._lensCenter.y);\n effect.setFloat2(\"Scale\", _this._scaleFactor.x, _this._scaleFactor.y);\n effect.setFloat2(\"ScaleIn\", _this._scaleIn.x, _this._scaleIn.y);\n effect.setFloat4(\"HmdWarpParam\", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);\n });\n return _this;\n }\n return VRDistortionCorrectionPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.\n * Screen rotation is taken into account.\n */\n var FreeCameraDeviceOrientationInput = /** @class */ (function () {\n function FreeCameraDeviceOrientationInput() {\n var _this = this;\n this._screenOrientationAngle = 0;\n this._screenQuaternion = new BABYLON.Quaternion();\n this._alpha = 0;\n this._beta = 0;\n this._gamma = 0;\n this._orientationChanged = function () {\n _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));\n _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);\n _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));\n };\n this._deviceOrientation = function (evt) {\n _this._alpha = evt.alpha !== null ? evt.alpha : 0;\n _this._beta = evt.beta !== null ? evt.beta : 0;\n _this._gamma = evt.gamma !== null ? evt.gamma : 0;\n };\n this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));\n this._orientationChanged();\n }\n Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, \"camera\", {\n get: function () {\n return this._camera;\n },\n set: function (camera) {\n this._camera = camera;\n if (this._camera != null && !this._camera.rotationQuaternion) {\n this._camera.rotationQuaternion = new BABYLON.Quaternion();\n }\n },\n enumerable: true,\n configurable: true\n });\n FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {\n window.addEventListener(\"orientationchange\", this._orientationChanged);\n window.addEventListener(\"deviceorientation\", this._deviceOrientation);\n //In certain cases, the attach control is called AFTER orientation was changed,\n //So this is needed.\n this._orientationChanged();\n };\n FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {\n window.removeEventListener(\"orientationchange\", this._orientationChanged);\n window.removeEventListener(\"deviceorientation\", this._deviceOrientation);\n };\n FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {\n //if no device orientation provided, don't update the rotation.\n //Only testing against alpha under the assumption thatnorientation will never be so exact when set.\n if (!this._alpha)\n return;\n BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);\n this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);\n this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);\n //Mirror on XY Plane\n this._camera.rotationQuaternion.z *= -1;\n this._camera.rotationQuaternion.w *= -1;\n };\n FreeCameraDeviceOrientationInput.prototype.getClassName = function () {\n return \"FreeCameraDeviceOrientationInput\";\n };\n FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {\n return \"deviceOrientation\";\n };\n return FreeCameraDeviceOrientationInput;\n }());\n BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;\n BABYLON.CameraInputTypes[\"FreeCameraDeviceOrientationInput\"] = FreeCameraDeviceOrientationInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {\n function ArcRotateCameraVRDeviceOrientationInput() {\n this.alphaCorrection = 1;\n this.betaCorrection = 1;\n this.gammaCorrection = 1;\n this._alpha = 0;\n this._gamma = 0;\n this._dirty = false;\n this._deviceOrientationHandler = this._onOrientationEvent.bind(this);\n }\n ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {\n this.camera.attachControl(element, noPreventDefault);\n window.addEventListener(\"deviceorientation\", this._deviceOrientationHandler);\n };\n ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {\n if (evt.alpha !== null) {\n this._alpha = +evt.alpha | 0;\n }\n if (evt.gamma !== null) {\n this._gamma = +evt.gamma | 0;\n }\n this._dirty = true;\n };\n ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {\n if (this._dirty) {\n this._dirty = false;\n if (this._gamma < 0) {\n this._gamma = 180 + this._gamma;\n }\n this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;\n this.camera.beta = (this._gamma / 180.0 * Math.PI);\n }\n };\n ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {\n window.removeEventListener(\"deviceorientation\", this._deviceOrientationHandler);\n };\n ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {\n return \"ArcRotateCameraVRDeviceOrientationInput\";\n };\n ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {\n return \"VRDeviceOrientation\";\n };\n return ArcRotateCameraVRDeviceOrientationInput;\n }());\n BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;\n BABYLON.CameraInputTypes[\"ArcRotateCameraVRDeviceOrientationInput\"] = ArcRotateCameraVRDeviceOrientationInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var VRCameraMetrics = /** @class */ (function () {\n function VRCameraMetrics() {\n this.compensateDistortion = true;\n }\n Object.defineProperty(VRCameraMetrics.prototype, \"aspectRatio\", {\n get: function () {\n return this.hResolution / (2 * this.vResolution);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRCameraMetrics.prototype, \"aspectRatioFov\", {\n get: function () {\n return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRCameraMetrics.prototype, \"leftHMatrix\", {\n get: function () {\n var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);\n var h = (4 * meters) / this.hScreenSize;\n return BABYLON.Matrix.Translation(h, 0, 0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRCameraMetrics.prototype, \"rightHMatrix\", {\n get: function () {\n var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);\n var h = (4 * meters) / this.hScreenSize;\n return BABYLON.Matrix.Translation(-h, 0, 0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRCameraMetrics.prototype, \"leftPreViewMatrix\", {\n get: function () {\n return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRCameraMetrics.prototype, \"rightPreViewMatrix\", {\n get: function () {\n return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);\n },\n enumerable: true,\n configurable: true\n });\n VRCameraMetrics.GetDefault = function () {\n var result = new VRCameraMetrics();\n result.hResolution = 1280;\n result.vResolution = 800;\n result.hScreenSize = 0.149759993;\n result.vScreenSize = 0.0935999975;\n result.vScreenCenter = 0.0467999987;\n result.eyeToScreenDistance = 0.0410000011;\n result.lensSeparationDistance = 0.0635000020;\n result.interpupillaryDistance = 0.0640000030;\n result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];\n result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];\n result.postProcessScaleFactor = 1.714605507808412;\n result.lensCenterOffset = 0.151976421;\n return result;\n };\n return VRCameraMetrics;\n }());\n BABYLON.VRCameraMetrics = VRCameraMetrics;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vrCameraMetrics.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"WebVRFreeCamera\", function (name, scene) {\n return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n BABYLON.Node.AddNodeConstructor(\"WebVRGamepadCamera\", function (name, scene) {\n return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n /**\n * This represents a WebVR camera.\n * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.\n * @example http://doc.babylonjs.com/how_to/webvr_camera\n */\n var WebVRFreeCamera = /** @class */ (function (_super) {\n __extends(WebVRFreeCamera, _super);\n /**\n * Instantiates a WebVRFreeCamera.\n * @param name The name of the WebVRFreeCamera\n * @param position The starting anchor position for the camera\n * @param scene The scene the camera belongs to\n * @param webVROptions a set of customizable options for the webVRCamera\n */\n function WebVRFreeCamera(name, position, scene, webVROptions) {\n if (webVROptions === void 0) { webVROptions = {}; }\n var _this = _super.call(this, name, position, scene) || this;\n _this.webVROptions = webVROptions;\n /**\n * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay\n */\n _this._vrDevice = null;\n /**\n * The rawPose of the vrDevice.\n */\n _this.rawPose = null;\n _this._specsVersion = \"1.1\";\n _this._attached = false;\n _this._descendants = [];\n // Represents device position and rotation in room space. Should only be used to help calculate babylon space values\n _this._deviceRoomPosition = BABYLON.Vector3.Zero();\n /** @hidden */\n _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();\n _this._standingMatrix = null;\n /**\n * Represents device position in babylon space.\n */\n _this.devicePosition = BABYLON.Vector3.Zero();\n /**\n * Represents device rotation in babylon space.\n */\n _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();\n /**\n * The scale of the device to be used when translating from device space to babylon space.\n */\n _this.deviceScaleFactor = 1;\n _this._deviceToWorld = BABYLON.Matrix.Identity();\n _this._worldToDevice = BABYLON.Matrix.Identity();\n /**\n * References to the webVR controllers for the vrDevice.\n */\n _this.controllers = [];\n /**\n * Emits an event when a controller is attached.\n */\n _this.onControllersAttachedObservable = new BABYLON.Observable();\n /**\n * Emits an event when a controller's mesh has been loaded;\n */\n _this.onControllerMeshLoadedObservable = new BABYLON.Observable();\n /**\n * Emits an event when the HMD's pose has been updated.\n */\n _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();\n _this._poseSet = false;\n /**\n * If the rig cameras be used as parent instead of this camera.\n */\n _this.rigParenting = true;\n _this._defaultHeight = undefined;\n _this._workingVector = BABYLON.Vector3.Zero();\n _this._oneVector = BABYLON.Vector3.One();\n _this._workingMatrix = BABYLON.Matrix.Identity();\n _this._cache.position = BABYLON.Vector3.Zero();\n if (webVROptions.defaultHeight) {\n _this._defaultHeight = webVROptions.defaultHeight;\n _this.position.y = _this._defaultHeight;\n }\n _this.minZ = 0.1;\n //legacy support - the compensation boolean was removed.\n if (arguments.length === 5) {\n _this.webVROptions = arguments[4];\n }\n // default webVR options\n if (_this.webVROptions.trackPosition == undefined) {\n _this.webVROptions.trackPosition = true;\n }\n if (_this.webVROptions.controllerMeshes == undefined) {\n _this.webVROptions.controllerMeshes = true;\n }\n if (_this.webVROptions.defaultLightingOnControllers == undefined) {\n _this.webVROptions.defaultLightingOnControllers = true;\n }\n _this.rotationQuaternion = new BABYLON.Quaternion();\n if (_this.webVROptions && _this.webVROptions.positionScale) {\n _this.deviceScaleFactor = _this.webVROptions.positionScale;\n }\n //enable VR\n var engine = _this.getEngine();\n _this._onVREnabled = function (success) { if (success) {\n _this.initControllers();\n } };\n engine.onVRRequestPresentComplete.add(_this._onVREnabled);\n engine.initWebVR().add(function (event) {\n if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {\n return;\n }\n _this._vrDevice = event.vrDisplay;\n //reset the rig parameters.\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });\n if (_this._attached) {\n _this.getEngine().enableVR();\n }\n });\n if (typeof (VRFrameData) !== \"undefined\")\n _this._frameData = new VRFrameData();\n /**\n * The idea behind the following lines:\n * objects that have the camera as parent should actually have the rig cameras as a parent.\n * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,\n * the second will not show it correctly.\n *\n * To solve this - each object that has the camera as parent will be added to a protected array.\n * When the rig camera renders, it will take this array and set all of those to be its children.\n * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.\n * Amazing!\n */\n scene.onBeforeCameraRenderObservable.add(function (camera) {\n if (camera.parent === _this && _this.rigParenting) {\n _this._descendants = _this.getDescendants(true, function (n) {\n // don't take the cameras or the controllers!\n var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });\n var isRigCamera = _this._rigCameras.indexOf(n) !== -1;\n return !isController && !isRigCamera;\n });\n _this._descendants.forEach(function (node) {\n node.parent = camera;\n });\n }\n });\n scene.onAfterCameraRenderObservable.add(function (camera) {\n if (camera.parent === _this && _this.rigParenting) {\n _this._descendants.forEach(function (node) {\n node.parent = _this;\n });\n }\n });\n return _this;\n }\n /**\n * Gets the device distance from the ground in meters.\n * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.\n */\n WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {\n if (this._standingMatrix) {\n // Add standing matrix offset to get real offset from ground in room\n this._standingMatrix.getTranslationToRef(this._workingVector);\n return this._deviceRoomPosition.y + this._workingVector.y;\n }\n //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.\n return this._defaultHeight || 0;\n };\n /**\n * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.\n * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.\n */\n WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {\n var _this = this;\n if (callback === void 0) { callback = function (bool) { }; }\n // Use standing matrix if available\n this.getEngine().initWebVRAsync().then(function (result) {\n if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {\n callback(false);\n }\n else {\n _this._standingMatrix = new BABYLON.Matrix();\n BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);\n if (!_this.getScene().useRightHandedSystem) {\n [2, 6, 8, 9, 14].forEach(function (num) {\n if (_this._standingMatrix) {\n _this._standingMatrix.m[num] *= -1;\n }\n });\n }\n callback(true);\n }\n });\n };\n /**\n * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.\n * @returns A promise with a boolean set to if the standing matrix is supported.\n */\n WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {\n var _this = this;\n return new Promise(function (res, rej) {\n _this.useStandingMatrix(function (supported) {\n res(supported);\n });\n });\n };\n /**\n * Disposes the camera\n */\n WebVRFreeCamera.prototype.dispose = function () {\n this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);\n _super.prototype.dispose.call(this);\n };\n /**\n * Gets a vrController by name.\n * @param name The name of the controller to retreive\n * @returns the controller matching the name specified or null if not found\n */\n WebVRFreeCamera.prototype.getControllerByName = function (name) {\n for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {\n var gp = _a[_i];\n if (gp.hand === name) {\n return gp;\n }\n }\n return null;\n };\n Object.defineProperty(WebVRFreeCamera.prototype, \"leftController\", {\n /**\n * The controller corrisponding to the users left hand.\n */\n get: function () {\n if (!this._leftController) {\n this._leftController = this.getControllerByName(\"left\");\n }\n return this._leftController;\n },\n enumerable: true,\n configurable: true\n });\n ;\n Object.defineProperty(WebVRFreeCamera.prototype, \"rightController\", {\n /**\n * The controller corrisponding to the users right hand.\n */\n get: function () {\n if (!this._rightController) {\n this._rightController = this.getControllerByName(\"right\");\n }\n return this._rightController;\n },\n enumerable: true,\n configurable: true\n });\n ;\n /**\n * Casts a ray forward from the vrCamera's gaze.\n * @param length Length of the ray (default: 100)\n * @returns the ray corrisponding to the gaze\n */\n WebVRFreeCamera.prototype.getForwardRay = function (length) {\n if (length === void 0) { length = 100; }\n if (this.leftCamera) {\n // Use left eye to avoid computation to compute center on every call\n return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera\n }\n else {\n return _super.prototype.getForwardRay.call(this, length);\n }\n };\n /**\n * Updates the camera based on device's frame data\n */\n WebVRFreeCamera.prototype._checkInputs = function () {\n if (this._vrDevice && this._vrDevice.isPresenting) {\n this._vrDevice.getFrameData(this._frameData);\n this.updateFromDevice(this._frameData.pose);\n }\n _super.prototype._checkInputs.call(this);\n };\n /**\n * Updates the poseControlled values based on the input device pose.\n * @param poseData Pose coming from the device\n */\n WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {\n if (poseData && poseData.orientation) {\n this.rawPose = poseData;\n this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);\n if (this.getScene().useRightHandedSystem) {\n this._deviceRoomRotationQuaternion.z *= -1;\n this._deviceRoomRotationQuaternion.w *= -1;\n }\n if (this.webVROptions.trackPosition && this.rawPose.position) {\n this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);\n if (this.getScene().useRightHandedSystem) {\n this._deviceRoomPosition.z *= -1;\n }\n }\n this._poseSet = true;\n }\n };\n /**\n * WebVR's attach control will start broadcasting frames to the device.\n * Note that in certain browsers (chrome for example) this function must be called\n * within a user-interaction callback. Example:\n *
 scene.onPointerDown = function() { camera.attachControl(canvas); }
\n *\n * @param element html element to attach the vrDevice to\n * @param noPreventDefault prevent the default html element operation when attaching the vrDevice\n */\n WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {\n _super.prototype.attachControl.call(this, element, noPreventDefault);\n this._attached = true;\n noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;\n if (this._vrDevice) {\n this.getEngine().enableVR();\n }\n };\n /**\n * Detaches the camera from the html element and disables VR\n *\n * @param element html element to detach from\n */\n WebVRFreeCamera.prototype.detachControl = function (element) {\n this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);\n this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);\n _super.prototype.detachControl.call(this, element);\n this._attached = false;\n this.getEngine().disableVR();\n };\n /**\n * @returns the name of this class\n */\n WebVRFreeCamera.prototype.getClassName = function () {\n return \"WebVRFreeCamera\";\n };\n /**\n * Calls resetPose on the vrDisplay\n * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose\n */\n WebVRFreeCamera.prototype.resetToCurrentRotation = function () {\n //uses the vrDisplay's \"resetPose()\".\n //pitch and roll won't be affected.\n this._vrDevice.resetPose();\n };\n /**\n * Updates the rig cameras (left and right eye)\n */\n WebVRFreeCamera.prototype._updateRigCameras = function () {\n var camLeft = this._rigCameras[0];\n var camRight = this._rigCameras[1];\n camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);\n camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);\n camLeft.position.copyFrom(this._deviceRoomPosition);\n camRight.position.copyFrom(this._deviceRoomPosition);\n };\n /**\n * Updates the cached values of the camera\n * @param ignoreParentClass ignores updating the parent class's cache (default: false)\n */\n WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {\n var _this = this;\n if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {\n // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition\n if (!this.updateCacheCalled) {\n // make sure it is only called once per loop. this.update() might cause an infinite loop.\n this.updateCacheCalled = true;\n this.update();\n }\n // Set working vector to the device position in room space rotated by the new rotation\n this.rotationQuaternion.toRotationMatrix(this._workingMatrix);\n BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);\n // Subtract this vector from the current device position in world to get the translation for the device world matrix\n this.devicePosition.subtractToRef(this._workingVector, this._workingVector);\n BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);\n // Add translation from anchor position\n this._deviceToWorld.getTranslationToRef(this._workingVector);\n this._workingVector.addInPlace(this.position);\n this._workingVector.subtractInPlace(this._cache.position);\n this._deviceToWorld.setTranslation(this._workingVector);\n // Set an inverted matrix to be used when updating the camera\n this._deviceToWorld.invertToRef(this._worldToDevice);\n // Update the gamepad to ensure the mesh is updated on the same frame as camera\n this.controllers.forEach(function (controller) {\n controller._deviceToWorld.copyFrom(_this._deviceToWorld);\n controller.update();\n });\n }\n if (!ignoreParentClass) {\n _super.prototype._updateCache.call(this);\n }\n this.updateCacheCalled = false;\n };\n /**\n * Updates the current device position and rotation in the babylon world\n */\n WebVRFreeCamera.prototype.update = function () {\n // Get current device position in babylon world\n BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);\n // Get current device rotation in babylon world\n BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);\n this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);\n BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);\n if (this._poseSet) {\n this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);\n }\n _super.prototype.update.call(this);\n };\n /**\n * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)\n * @returns an identity matrix\n */\n WebVRFreeCamera.prototype._getViewMatrix = function () {\n return BABYLON.Matrix.Identity();\n };\n /**\n * This function is called by the two RIG cameras.\n * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)\n */\n WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {\n var _this = this;\n // Update the parent camera prior to using a child camera to avoid desynchronization\n var parentCamera = this._cameraRigParams[\"parentCamera\"];\n parentCamera._updateCache();\n //WebVR 1.1\n var viewArray = this._cameraRigParams[\"left\"] ? this._cameraRigParams[\"frameData\"].leftViewMatrix : this._cameraRigParams[\"frameData\"].rightViewMatrix;\n BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);\n if (!this.getScene().useRightHandedSystem) {\n [2, 6, 8, 9, 14].forEach(function (num) {\n _this._webvrViewMatrix.m[num] *= -1;\n });\n }\n // update the camera rotation matrix\n this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);\n BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);\n // Computing target and final matrix\n this.position.addToRef(this._transformedReferencePoint, this._currentTarget);\n // should the view matrix be updated with scale and position offset?\n if (parentCamera.deviceScaleFactor !== 1) {\n this._webvrViewMatrix.invert();\n // scale the position, if set\n if (parentCamera.deviceScaleFactor) {\n this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;\n this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;\n this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;\n }\n this._webvrViewMatrix.invert();\n }\n parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);\n // Compute global position\n this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();\n this._webvrViewMatrix.invertToRef(this._workingMatrix);\n this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);\n this._workingMatrix.getTranslationToRef(this._globalPosition);\n this._markSyncedWithParent();\n return this._webvrViewMatrix;\n };\n WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {\n var _this = this;\n var parentCamera = this.parent;\n parentCamera._vrDevice.depthNear = parentCamera.minZ;\n parentCamera._vrDevice.depthFar = parentCamera.maxZ;\n var projectionArray = this._cameraRigParams[\"left\"] ? this._cameraRigParams[\"frameData\"].leftProjectionMatrix : this._cameraRigParams[\"frameData\"].rightProjectionMatrix;\n BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);\n //babylon compatible matrix\n if (!this.getScene().useRightHandedSystem) {\n [8, 9, 10, 11].forEach(function (num) {\n _this._projectionMatrix.m[num] *= -1;\n });\n }\n return this._projectionMatrix;\n };\n /**\n * Initializes the controllers and their meshes\n */\n WebVRFreeCamera.prototype.initControllers = function () {\n var _this = this;\n this.controllers = [];\n var manager = this.getScene().gamepadManager;\n this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {\n if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {\n var webVrController = gamepad;\n if (webVrController.defaultModel) {\n webVrController.defaultModel.setEnabled(false);\n }\n if (webVrController.hand === \"right\") {\n _this._rightController = null;\n }\n if (webVrController.hand === \"left\") {\n _this._leftController = null;\n }\n var controllerIndex = _this.controllers.indexOf(webVrController);\n if (controllerIndex !== -1) {\n _this.controllers.splice(controllerIndex, 1);\n }\n }\n });\n this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {\n if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {\n var webVrController_1 = gamepad;\n webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;\n webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);\n if (_this.webVROptions.controllerMeshes) {\n if (webVrController_1.defaultModel) {\n webVrController_1.defaultModel.setEnabled(true);\n }\n else {\n // Load the meshes\n webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {\n loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);\n _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);\n if (_this.webVROptions.defaultLightingOnControllers) {\n if (!_this._lightOnControllers) {\n _this._lightOnControllers = new BABYLON.HemisphericLight(\"vrControllersLight\", new BABYLON.Vector3(0, 1, 0), _this.getScene());\n }\n var activateLightOnSubMeshes_1 = function (mesh, light) {\n var children = mesh.getChildren();\n if (children.length !== 0) {\n children.forEach(function (mesh) {\n light.includedOnlyMeshes.push(mesh);\n activateLightOnSubMeshes_1(mesh, light);\n });\n }\n };\n _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);\n activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);\n }\n });\n }\n }\n webVrController_1.attachToPoseControlledCamera(_this);\n // since this is async - sanity check. Is the controller already stored?\n if (_this.controllers.indexOf(webVrController_1) === -1) {\n //add to the controllers array\n _this.controllers.push(webVrController_1);\n // Forced to add some control code for Vive as it doesn't always fill properly the \"hand\" property\n // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...\n // So we're overriding setting left & right manually to be sure\n var firstViveWandDetected = false;\n for (var i = 0; i < _this.controllers.length; i++) {\n if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {\n if (!firstViveWandDetected) {\n firstViveWandDetected = true;\n _this.controllers[i].hand = \"left\";\n }\n else {\n _this.controllers[i].hand = \"right\";\n }\n }\n }\n //did we find enough controllers? Great! let the developer know.\n if (_this.controllers.length >= 2) {\n _this.onControllersAttachedObservable.notifyObservers(_this.controllers);\n }\n }\n }\n });\n };\n return WebVRFreeCamera;\n }(BABYLON.FreeCamera));\n BABYLON.WebVRFreeCamera = WebVRFreeCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.webVRCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"DeviceOrientationCamera\", function (name, scene) {\n return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n // We're mainly based on the logic defined into the FreeCamera code\n /**\n * This is a camera specifically designed to react to device orientation events such as a modern mobile device\n * being tilted forward or back and left or right.\n */\n var DeviceOrientationCamera = /** @class */ (function (_super) {\n __extends(DeviceOrientationCamera, _super);\n /**\n * Creates a new device orientation camera\n * @param name The name of the camera\n * @param position The start position camera\n * @param scene The scene the camera belongs to\n */\n function DeviceOrientationCamera(name, position, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this._quaternionCache = new BABYLON.Quaternion();\n _this.inputs.addDeviceOrientation();\n return _this;\n }\n /**\n * Gets the current instance class name (\"DeviceOrientationCamera\").\n * This helps avoiding instanceof at run time.\n * @returns the class name\n */\n DeviceOrientationCamera.prototype.getClassName = function () {\n return \"DeviceOrientationCamera\";\n };\n /**\n * Checks and applies the current values of the inputs to the camera. (Internal use only)\n */\n DeviceOrientationCamera.prototype._checkInputs = function () {\n _super.prototype._checkInputs.call(this);\n this._quaternionCache.copyFrom(this.rotationQuaternion);\n if (this._initialQuaternion) {\n this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n }\n };\n /**\n * Reset the camera to its default orientation on the specified axis only.\n * @param axis The axis to reset\n */\n DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {\n var _this = this;\n if (axis === void 0) { axis = BABYLON.Axis.Y; }\n //can only work if this camera has a rotation quaternion already.\n if (!this.rotationQuaternion)\n return;\n if (!this._initialQuaternion) {\n this._initialQuaternion = new BABYLON.Quaternion();\n }\n this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);\n ['x', 'y', 'z'].forEach(function (axisName) {\n if (!axis[axisName]) {\n _this._initialQuaternion[axisName] = 0;\n }\n else {\n _this._initialQuaternion[axisName] *= -1;\n }\n });\n this._initialQuaternion.normalize();\n //force rotation update\n this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n };\n return DeviceOrientationCamera;\n }(BABYLON.FreeCamera));\n BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.deviceOrientationCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"VRDeviceOrientationFreeCamera\", function (name, scene) {\n return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {\n __extends(VRDeviceOrientationFreeCamera, _super);\n function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {\n if (compensateDistortion === void 0) { compensateDistortion = true; }\n if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }\n var _this = _super.call(this, name, position, scene) || this;\n vrCameraMetrics.compensateDistortion = compensateDistortion;\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });\n return _this;\n }\n VRDeviceOrientationFreeCamera.prototype.getClassName = function () {\n return \"VRDeviceOrientationFreeCamera\";\n };\n return VRDeviceOrientationFreeCamera;\n }(BABYLON.DeviceOrientationCamera));\n BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"VRDeviceOrientationFreeCamera\", function (name, scene) {\n return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };\n });\n var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {\n __extends(VRDeviceOrientationArcRotateCamera, _super);\n function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {\n if (compensateDistortion === void 0) { compensateDistortion = true; }\n if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }\n var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;\n vrCameraMetrics.compensateDistortion = compensateDistortion;\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });\n _this.inputs.addVRDeviceOrientation();\n return _this;\n }\n VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {\n return \"VRDeviceOrientationArcRotateCamera\";\n };\n return VRDeviceOrientationArcRotateCamera;\n }(BABYLON.ArcRotateCamera));\n BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"VRDeviceOrientationGamepadCamera\", function (name, scene) {\n return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {\n __extends(VRDeviceOrientationGamepadCamera, _super);\n function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {\n if (compensateDistortion === void 0) { compensateDistortion = true; }\n if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }\n var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;\n _this.inputs.addGamepad();\n return _this;\n }\n VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {\n return \"VRDeviceOrientationGamepadCamera\";\n };\n return VRDeviceOrientationGamepadCamera;\n }(BABYLON.VRDeviceOrientationFreeCamera));\n BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var VRExperienceHelperGazer = /** @class */ (function () {\n function VRExperienceHelperGazer(scene, gazeTrackerToClone) {\n if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }\n this.scene = scene;\n this._pointerDownOnMeshAsked = false;\n this._isActionableMesh = false;\n this._teleportationRequestInitiated = false;\n this._teleportationBackRequestInitiated = false;\n this._rotationRightAsked = false;\n this._rotationLeftAsked = false;\n this._dpadPressed = true;\n this._activePointer = false;\n this._id = VRExperienceHelperGazer._idCounter++;\n // Gaze tracker\n if (!gazeTrackerToClone) {\n this._gazeTracker = BABYLON.Mesh.CreateTorus(\"gazeTracker\", 0.0035, 0.0025, 20, scene, false);\n this._gazeTracker.bakeCurrentTransformIntoVertices();\n this._gazeTracker.isPickable = false;\n this._gazeTracker.isVisible = false;\n var targetMat = new BABYLON.StandardMaterial(\"targetMat\", scene);\n targetMat.specularColor = BABYLON.Color3.Black();\n targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);\n targetMat.backFaceCulling = false;\n this._gazeTracker.material = targetMat;\n }\n else {\n this._gazeTracker = gazeTrackerToClone.clone(\"gazeTracker\");\n }\n }\n VRExperienceHelperGazer.prototype._getForwardRay = function (length) {\n return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));\n };\n VRExperienceHelperGazer.prototype._selectionPointerDown = function () {\n this._pointerDownOnMeshAsked = true;\n if (this._currentHit) {\n this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });\n }\n };\n VRExperienceHelperGazer.prototype._selectionPointerUp = function () {\n if (this._currentHit) {\n this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });\n }\n this._pointerDownOnMeshAsked = false;\n };\n VRExperienceHelperGazer.prototype._activatePointer = function () {\n this._activePointer = true;\n };\n VRExperienceHelperGazer.prototype._deactivatePointer = function () {\n this._activePointer = false;\n };\n VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {\n if (distance === void 0) { distance = 100; }\n };\n VRExperienceHelperGazer.prototype.dispose = function () {\n this._interactionsEnabled = false;\n this._teleportationEnabled = false;\n if (this._gazeTracker) {\n this._gazeTracker.dispose();\n }\n };\n VRExperienceHelperGazer._idCounter = 0;\n return VRExperienceHelperGazer;\n }());\n var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {\n __extends(VRExperienceHelperControllerGazer, _super);\n function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {\n var _this = _super.call(this, scene, gazeTrackerToClone) || this;\n _this.webVRController = webVRController;\n // Laser pointer\n _this._laserPointer = BABYLON.Mesh.CreateCylinder(\"laserPointer\", 1, 0.004, 0.0002, 20, 1, scene, false);\n var laserPointerMaterial = new BABYLON.StandardMaterial(\"laserPointerMat\", scene);\n laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);\n laserPointerMaterial.alpha = 0.6;\n _this._laserPointer.material = laserPointerMaterial;\n _this._laserPointer.rotation.x = Math.PI / 2;\n _this._laserPointer.position.z = -0.5;\n _this._laserPointer.isVisible = false;\n _this._laserPointer.isPickable = false;\n if (!webVRController.mesh) {\n // Create an empty mesh that is used prior to loading the high quality model\n var preloadMesh = new BABYLON.Mesh(\"preloadControllerMesh\", scene);\n var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);\n preloadPointerPose.rotation.x = -0.7;\n preloadMesh.addChild(preloadPointerPose);\n webVRController.attachToMesh(preloadMesh);\n }\n _this._setLaserPointerParent(webVRController.mesh);\n _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {\n _this._setLaserPointerParent(mesh);\n });\n return _this;\n }\n VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {\n return this.webVRController.getForwardRay(length);\n };\n VRExperienceHelperControllerGazer.prototype._activatePointer = function () {\n _super.prototype._activatePointer.call(this);\n this._laserPointer.isVisible = true;\n };\n VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {\n _super.prototype._deactivatePointer.call(this);\n this._laserPointer.isVisible = false;\n };\n VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {\n this._laserPointer.material.emissiveColor = color;\n };\n VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {\n var makeNotPick = function (root) {\n root.isPickable = false;\n root.getChildMeshes().forEach(function (c) {\n makeNotPick(c);\n });\n };\n makeNotPick(mesh);\n var childMeshes = mesh.getChildMeshes();\n this.webVRController._pointingPoseNode = null;\n for (var i = 0; i < childMeshes.length; i++) {\n if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {\n mesh = childMeshes[i];\n this.webVRController._pointingPoseNode = mesh;\n break;\n }\n }\n this._laserPointer.parent = mesh;\n };\n VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {\n if (distance === void 0) { distance = 100; }\n this._laserPointer.scaling.y = distance;\n this._laserPointer.position.z = -distance / 2;\n };\n VRExperienceHelperControllerGazer.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this._laserPointer.dispose();\n if (this._meshAttachedObserver) {\n this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);\n }\n };\n return VRExperienceHelperControllerGazer;\n }(VRExperienceHelperGazer));\n var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {\n __extends(VRExperienceHelperCameraGazer, _super);\n function VRExperienceHelperCameraGazer(getCamera, scene) {\n var _this = _super.call(this, scene) || this;\n _this.getCamera = getCamera;\n return _this;\n }\n VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {\n var camera = this.getCamera();\n if (camera) {\n return camera.getForwardRay(length);\n }\n else {\n return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());\n }\n };\n return VRExperienceHelperCameraGazer;\n }(VRExperienceHelperGazer));\n /**\n * Helps to quickly add VR support to an existing scene.\n * See http://doc.babylonjs.com/how_to/webvr_helper\n */\n var VRExperienceHelper = /** @class */ (function () {\n /**\n * Instantiates a VRExperienceHelper.\n * Helps to quickly add VR support to an existing scene.\n * @param scene The scene the VRExperienceHelper belongs to.\n * @param webVROptions Options to modify the vr experience helper's behavior.\n */\n function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {\n if (webVROptions === void 0) { webVROptions = {}; }\n var _this = this;\n this.webVROptions = webVROptions;\n // Can the system support WebVR, even if a headset isn't plugged in?\n this._webVRsupported = false;\n // If WebVR is supported, is a headset plugged in and are we ready to present?\n this._webVRready = false;\n // Are we waiting for the requestPresent callback to complete?\n this._webVRrequesting = false;\n // Are we presenting to the headset right now?\n this._webVRpresenting = false;\n // Are we presenting in the fullscreen fallback?\n this._fullscreenVRpresenting = false;\n /**\n * Observable raised when entering VR.\n */\n this.onEnteringVRObservable = new BABYLON.Observable();\n /**\n * Observable raised when exiting VR.\n */\n this.onExitingVRObservable = new BABYLON.Observable();\n /**\n * Observable raised when controller mesh is loaded.\n */\n this.onControllerMeshLoadedObservable = new BABYLON.Observable();\n this._useCustomVRButton = false;\n this._teleportationRequested = false;\n this._teleportActive = false;\n this._floorMeshesCollection = [];\n this._rotationAllowed = true;\n this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);\n this._isDefaultTeleportationTarget = true;\n this._teleportationFillColor = \"#444444\";\n this._teleportationBorderColor = \"#FFFFFF\";\n this._rotationAngle = 0;\n this._haloCenter = new BABYLON.Vector3(0, 0, 0);\n this._padSensibilityUp = 0.65;\n this._padSensibilityDown = 0.35;\n this.leftController = null;\n this.rightController = null;\n /**\n * Observable raised when a new mesh is selected based on meshSelectionPredicate\n */\n this.onNewMeshSelected = new BABYLON.Observable();\n /**\n * Observable raised when a new mesh is picked based on meshSelectionPredicate\n */\n this.onNewMeshPicked = new BABYLON.Observable();\n /**\n * Observable raised before camera teleportation\n */\n this.onBeforeCameraTeleport = new BABYLON.Observable();\n /**\n * Observable raised after camera teleportation\n */\n this.onAfterCameraTeleport = new BABYLON.Observable();\n /**\n * Observable raised when current selected mesh gets unselected\n */\n this.onSelectedMeshUnselected = new BABYLON.Observable();\n /**\n * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.\n */\n this.teleportationEnabled = true;\n this._teleportationInitialized = false;\n this._interactionsEnabled = false;\n this._interactionsRequested = false;\n this._displayGaze = true;\n this._displayLaserPointer = true;\n this._onResize = function () {\n _this.moveButtonToBottomRight();\n if (_this._fullscreenVRpresenting && _this._webVRready) {\n _this.exitVR();\n }\n };\n this._onFullscreenChange = function () {\n if (document.fullscreen !== undefined) {\n _this._fullscreenVRpresenting = document.fullscreen;\n }\n else if (document.mozFullScreen !== undefined) {\n _this._fullscreenVRpresenting = document.mozFullScreen;\n }\n else if (document.webkitIsFullScreen !== undefined) {\n _this._fullscreenVRpresenting = document.webkitIsFullScreen;\n }\n else if (document.msIsFullScreen !== undefined) {\n _this._fullscreenVRpresenting = document.msIsFullScreen;\n }\n else if (document.msFullscreenElement !== undefined) {\n _this._fullscreenVRpresenting = document.msFullscreenElement;\n }\n if (!_this._fullscreenVRpresenting && _this._canvas) {\n _this.exitVR();\n if (!_this._useCustomVRButton) {\n _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + \"px\";\n _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + \"px\";\n }\n }\n };\n this.beforeRender = function () {\n if (_this.leftController && _this.leftController._activePointer) {\n _this._castRayAndSelectObject(_this.leftController);\n }\n if (_this.rightController && _this.rightController._activePointer) {\n _this._castRayAndSelectObject(_this.rightController);\n }\n if (_this._noControllerIsActive) {\n _this._castRayAndSelectObject(_this._cameraGazer);\n }\n else {\n _this._cameraGazer._gazeTracker.isVisible = false;\n }\n };\n this._onNewGamepadConnected = function (gamepad) {\n if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {\n if (gamepad.leftStick) {\n gamepad.onleftstickchanged(function (stickValues) {\n if (_this._teleportationInitialized && _this.teleportationEnabled) {\n // Listening to classic/xbox gamepad only if no VR controller is active\n if ((!_this.leftController && !_this.rightController) ||\n ((_this.leftController && !_this.leftController._activePointer) &&\n (_this.rightController && !_this.rightController._activePointer))) {\n _this._checkTeleportWithRay(stickValues, _this._cameraGazer);\n _this._checkTeleportBackwards(stickValues, _this._cameraGazer);\n }\n }\n });\n }\n if (gamepad.rightStick) {\n gamepad.onrightstickchanged(function (stickValues) {\n if (_this._teleportationInitialized) {\n _this._checkRotate(stickValues, _this._cameraGazer);\n }\n });\n }\n if (gamepad.type === BABYLON.Gamepad.XBOX) {\n gamepad.onbuttondown(function (buttonPressed) {\n if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {\n _this._cameraGazer._selectionPointerDown();\n }\n });\n gamepad.onbuttonup(function (buttonPressed) {\n if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {\n _this._cameraGazer._selectionPointerUp();\n }\n });\n }\n }\n else {\n var webVRController = gamepad;\n var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);\n if (webVRController.hand === \"right\" || (_this.leftController && _this.leftController.webVRController != webVRController)) {\n _this.rightController = controller;\n }\n else {\n _this.leftController = controller;\n }\n _this._tryEnableInteractionOnController(controller);\n }\n };\n // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded\n this._tryEnableInteractionOnController = function (controller) {\n if (_this._interactionsRequested && !controller._interactionsEnabled) {\n _this._enableInteractionOnController(controller);\n }\n if (_this._teleportationRequested && !controller._teleportationEnabled) {\n _this._enableTeleportationOnController(controller);\n }\n };\n this._onNewGamepadDisconnected = function (gamepad) {\n if (gamepad instanceof BABYLON.WebVRController) {\n if (gamepad.hand === \"left\" && _this.leftController != null) {\n _this.leftController.dispose();\n _this.leftController = null;\n }\n if (gamepad.hand === \"right\" && _this.rightController != null) {\n _this.rightController.dispose();\n _this.rightController = null;\n }\n }\n };\n this._workingVector = BABYLON.Vector3.Zero();\n this._workingQuaternion = BABYLON.Quaternion.Identity();\n this._workingMatrix = BABYLON.Matrix.Identity();\n this._scene = scene;\n this._canvas = scene.getEngine().getRenderingCanvas();\n // Parse options\n if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {\n webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;\n }\n if (webVROptions.createDeviceOrientationCamera === undefined) {\n webVROptions.createDeviceOrientationCamera = true;\n }\n if (webVROptions.laserToggle === undefined) {\n webVROptions.laserToggle = true;\n }\n if (webVROptions.defaultHeight === undefined) {\n webVROptions.defaultHeight = 1.7;\n }\n if (webVROptions.useCustomVRButton) {\n this._useCustomVRButton = true;\n if (webVROptions.customVRButton) {\n this._btnVR = webVROptions.customVRButton;\n }\n }\n if (webVROptions.rayLength) {\n this._rayLength = webVROptions.rayLength;\n }\n this._defaultHeight = webVROptions.defaultHeight;\n if (webVROptions.positionScale) {\n this._rayLength *= webVROptions.positionScale;\n this._defaultHeight *= webVROptions.positionScale;\n }\n // Set position\n if (this._scene.activeCamera) {\n this._position = this._scene.activeCamera.position.clone();\n }\n else {\n this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);\n }\n // Set non-vr camera\n if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {\n this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera(\"deviceOrientationVRHelper\", this._position.clone(), scene);\n // Copy data from existing camera\n if (this._scene.activeCamera) {\n this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;\n this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;\n // Set rotation from previous camera\n if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {\n var targetCamera = this._scene.activeCamera;\n if (targetCamera.rotationQuaternion) {\n this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);\n }\n else {\n this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));\n }\n this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();\n }\n }\n this._scene.activeCamera = this._deviceOrientationCamera;\n if (this._canvas) {\n this._scene.activeCamera.attachControl(this._canvas);\n }\n }\n else {\n this._existingCamera = this._scene.activeCamera;\n }\n // Create VR cameras\n if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {\n this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera(\"VRDeviceOrientationVRHelper\", this._position, this._scene);\n }\n this._webVRCamera = new BABYLON.WebVRFreeCamera(\"WebVRHelper\", this._position, this._scene, webVROptions);\n this._webVRCamera.useStandingMatrix();\n this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);\n // Create default button\n if (!this._useCustomVRButton) {\n this._btnVR = document.createElement(\"BUTTON\");\n this._btnVR.className = \"babylonVRicon\";\n this._btnVR.id = \"babylonVRiconbtn\";\n this._btnVR.title = \"Click to switch to VR\";\n var css = \".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }\";\n css += \".babylonVRicon.vrdisplaypresenting { display: none; }\";\n // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)\n // css += \".babylonVRicon.vrdisplaysupported { }\";\n // css += \".babylonVRicon.vrdisplayready { }\";\n // css += \".babylonVRicon.vrdisplayrequesting { }\";\n var style = document.createElement('style');\n style.appendChild(document.createTextNode(css));\n document.getElementsByTagName('head')[0].appendChild(style);\n this.moveButtonToBottomRight();\n }\n // VR button click event\n if (this._btnVR) {\n this._btnVR.addEventListener(\"click\", function () {\n if (!_this.isInVRMode) {\n _this.enterVR();\n }\n else {\n _this.exitVR();\n }\n });\n }\n // Window events\n window.addEventListener(\"resize\", this._onResize);\n document.addEventListener(\"fullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"mozfullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"webkitfullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"msfullscreenchange\", this._onFullscreenChange, false);\n document.onmsfullscreenchange = this._onFullscreenChange;\n // Display vr button when headset is connected\n if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {\n this.displayVRButton();\n }\n else {\n this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {\n if (e.vrDisplay) {\n _this.displayVRButton();\n }\n });\n }\n // Exiting VR mode using 'ESC' key on desktop\n this._onKeyDown = function (event) {\n if (event.keyCode === 27 && _this.isInVRMode) {\n _this.exitVR();\n }\n };\n document.addEventListener(\"keydown\", this._onKeyDown);\n // Exiting VR mode double tapping the touch screen\n this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {\n if (_this.isInVRMode) {\n _this.exitVR();\n if (_this._fullscreenVRpresenting) {\n _this._scene.getEngine().switchFullscreen(true);\n }\n }\n }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);\n // Listen for WebVR display changes\n this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };\n this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };\n this._onVRRequestPresentStart = function () {\n _this._webVRrequesting = true;\n _this.updateButtonVisibility();\n };\n this._onVRRequestPresentComplete = function (success) {\n _this._webVRrequesting = false;\n _this.updateButtonVisibility();\n };\n scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);\n scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);\n scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);\n window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);\n scene.onDisposeObservable.add(function () {\n _this.dispose();\n });\n // Gamepad connection events\n this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });\n this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);\n this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);\n this.updateButtonVisibility();\n //create easing functions\n this._circleEase = new BABYLON.CircleEase();\n this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);\n if (this.webVROptions.floorMeshes) {\n this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });\n }\n }\n Object.defineProperty(VRExperienceHelper.prototype, \"onEnteringVR\", {\n /** Return this.onEnteringVRObservable\n * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly\n */\n get: function () {\n return this.onEnteringVRObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"onExitingVR\", {\n /** Return this.onExitingVRObservable\n * Note: This one is for backward compatibility. Please use onExitingVRObservable directly\n */\n get: function () {\n return this.onExitingVRObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"onControllerMeshLoaded\", {\n /** Return this.onControllerMeshLoadedObservable\n * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly\n */\n get: function () {\n return this.onControllerMeshLoadedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"teleportationTarget\", {\n /**\n * The mesh used to display where the user is going to teleport.\n */\n get: function () {\n return this._teleportationTarget;\n },\n /**\n * Sets the mesh to be used to display where the user is going to teleport.\n */\n set: function (value) {\n if (value) {\n value.name = \"teleportationTarget\";\n this._isDefaultTeleportationTarget = false;\n this._teleportationTarget = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"gazeTrackerMesh\", {\n /**\n * The mesh used to display where the user is selecting,\n * when set bakeCurrentTransformIntoVertices will be called on the mesh.\n * See http://doc.babylonjs.com/resources/baking_transformations\n */\n get: function () {\n return this._cameraGazer._gazeTracker;\n },\n set: function (value) {\n if (value) {\n this._cameraGazer._gazeTracker = value;\n this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();\n this._cameraGazer._gazeTracker.isPickable = false;\n this._cameraGazer._gazeTracker.isVisible = false;\n this._cameraGazer._gazeTracker.name = \"gazeTracker\";\n if (this.leftController) {\n this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone(\"gazeTracker\");\n }\n if (this.rightController) {\n this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone(\"gazeTracker\");\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"displayGaze\", {\n /**\n * If the ray of the gaze should be displayed.\n */\n get: function () {\n return this._displayGaze;\n },\n /**\n * Sets if the ray of the gaze should be displayed.\n */\n set: function (value) {\n this._displayGaze = value;\n if (!value) {\n this._cameraGazer._gazeTracker.isVisible = false;\n if (this.leftController) {\n this.leftController._gazeTracker.isVisible = false;\n }\n if (this.rightController) {\n this.rightController._gazeTracker.isVisible = false;\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"displayLaserPointer\", {\n /**\n * If the ray of the LaserPointer should be displayed.\n */\n get: function () {\n return this._displayLaserPointer;\n },\n /**\n * Sets if the ray of the LaserPointer should be displayed.\n */\n set: function (value) {\n this._displayLaserPointer = value;\n if (!value) {\n if (this.rightController) {\n this.rightController._deactivatePointer();\n this.rightController._gazeTracker.isVisible = false;\n }\n if (this.leftController) {\n this.leftController._deactivatePointer();\n this.leftController._gazeTracker.isVisible = false;\n }\n }\n else {\n if (this.rightController) {\n this.rightController._activatePointer();\n }\n if (this.leftController) {\n this.leftController._activatePointer();\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"deviceOrientationCamera\", {\n /**\n * The deviceOrientationCamera used as the camera when not in VR.\n */\n get: function () {\n return this._deviceOrientationCamera;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"currentVRCamera\", {\n /**\n * Based on the current WebVR support, returns the current VR camera used.\n */\n get: function () {\n if (this._webVRready) {\n return this._webVRCamera;\n }\n else {\n return this._scene.activeCamera;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"webVRCamera\", {\n /**\n * The webVRCamera which is used when in VR.\n */\n get: function () {\n return this._webVRCamera;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"vrDeviceOrientationCamera\", {\n /**\n * The deviceOrientationCamera that is used as a fallback when vr device is not connected.\n */\n get: function () {\n return this._vrDeviceOrientationCamera;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"_teleportationRequestInitiated\", {\n get: function () {\n var result = this._cameraGazer._teleportationRequestInitiated\n || (this.leftController !== null && this.leftController._teleportationRequestInitiated)\n || (this.rightController !== null && this.rightController._teleportationRequestInitiated);\n return result;\n },\n enumerable: true,\n configurable: true\n });\n // Raised when one of the controller has loaded successfully its associated default mesh\n VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {\n if (this.leftController && this.leftController.webVRController == webVRController) {\n if (webVRController.mesh) {\n this.leftController._setLaserPointerParent(webVRController.mesh);\n }\n }\n if (this.rightController && this.rightController.webVRController == webVRController) {\n if (webVRController.mesh) {\n this.rightController._setLaserPointerParent(webVRController.mesh);\n }\n }\n try {\n this.onControllerMeshLoadedObservable.notifyObservers(webVRController);\n }\n catch (err) {\n BABYLON.Tools.Warn(\"Error in your custom logic onControllerMeshLoaded: \" + err);\n }\n };\n Object.defineProperty(VRExperienceHelper.prototype, \"isInVRMode\", {\n /**\n * Gets a value indicating if we are currently in VR mode.\n */\n get: function () {\n return this._webVRpresenting || this._fullscreenVRpresenting;\n },\n enumerable: true,\n configurable: true\n });\n VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {\n var vrDisplay = this._scene.getEngine().getVRDevice();\n if (vrDisplay) {\n var wasPresenting = this._webVRpresenting;\n // A VR display is connected\n this._webVRpresenting = vrDisplay.isPresenting;\n if (wasPresenting && !this._webVRpresenting)\n this.exitVR();\n }\n else {\n BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');\n }\n this.updateButtonVisibility();\n };\n VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {\n this._webVRsupported = eventArgs.vrSupported;\n this._webVRready = !!eventArgs.vrDisplay;\n this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;\n this.updateButtonVisibility();\n };\n VRExperienceHelper.prototype.moveButtonToBottomRight = function () {\n if (this._canvas && !this._useCustomVRButton) {\n this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + \"px\";\n this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + \"px\";\n }\n };\n VRExperienceHelper.prototype.displayVRButton = function () {\n if (!this._useCustomVRButton && !this._btnVRDisplayed) {\n document.body.appendChild(this._btnVR);\n this._btnVRDisplayed = true;\n }\n };\n VRExperienceHelper.prototype.updateButtonVisibility = function () {\n if (!this._btnVR || this._useCustomVRButton) {\n return;\n }\n this._btnVR.className = \"babylonVRicon\";\n if (this.isInVRMode) {\n this._btnVR.className += \" vrdisplaypresenting\";\n }\n else {\n if (this._webVRready)\n this._btnVR.className += \" vrdisplayready\";\n if (this._webVRsupported)\n this._btnVR.className += \" vrdisplaysupported\";\n if (this._webVRrequesting)\n this._btnVR.className += \" vrdisplayrequesting\";\n }\n };\n /**\n * Attempt to enter VR. If a headset is connected and ready, will request present on that.\n * Otherwise, will use the fullscreen API.\n */\n VRExperienceHelper.prototype.enterVR = function () {\n if (this.onEnteringVRObservable) {\n try {\n this.onEnteringVRObservable.notifyObservers(this);\n }\n catch (err) {\n BABYLON.Tools.Warn(\"Error in your custom logic onEnteringVR: \" + err);\n }\n }\n if (this._scene.activeCamera) {\n this._position = this._scene.activeCamera.position.clone();\n // make sure that we return to the last active camera\n this._existingCamera = this._scene.activeCamera;\n }\n if (this._webVRrequesting)\n return;\n // If WebVR is supported and a headset is connected\n if (this._webVRready) {\n if (!this._webVRpresenting) {\n this._webVRCamera.position = this._position;\n this._scene.activeCamera = this._webVRCamera;\n }\n }\n else if (this._vrDeviceOrientationCamera) {\n this._vrDeviceOrientationCamera.position = this._position;\n if (this._scene.activeCamera) {\n this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;\n }\n this._scene.activeCamera = this._vrDeviceOrientationCamera;\n this._scene.getEngine().switchFullscreen(true);\n this.updateButtonVisibility();\n }\n if (this._scene.activeCamera && this._canvas) {\n this._scene.activeCamera.attachControl(this._canvas);\n }\n if (this._interactionsEnabled) {\n this._scene.registerBeforeRender(this.beforeRender);\n }\n };\n /**\n * Attempt to exit VR, or fullscreen.\n */\n VRExperienceHelper.prototype.exitVR = function () {\n if (this.onExitingVRObservable) {\n try {\n this.onExitingVRObservable.notifyObservers(this);\n }\n catch (err) {\n BABYLON.Tools.Warn(\"Error in your custom logic onExitingVR: \" + err);\n }\n }\n if (this._webVRpresenting) {\n this._scene.getEngine().disableVR();\n }\n if (this._scene.activeCamera) {\n this._position = this._scene.activeCamera.position.clone();\n }\n if (this._deviceOrientationCamera) {\n this._deviceOrientationCamera.position = this._position;\n this._scene.activeCamera = this._deviceOrientationCamera;\n if (this._canvas) {\n this._scene.activeCamera.attachControl(this._canvas);\n }\n }\n else if (this._existingCamera) {\n this._existingCamera.position = this._position;\n this._scene.activeCamera = this._existingCamera;\n }\n this.updateButtonVisibility();\n if (this._interactionsEnabled) {\n this._scene.unregisterBeforeRender(this.beforeRender);\n }\n // resize to update width and height when exiting vr exits fullscreen\n this._scene.getEngine().resize();\n };\n Object.defineProperty(VRExperienceHelper.prototype, \"position\", {\n /**\n * The position of the vr experience helper.\n */\n get: function () {\n return this._position;\n },\n /**\n * Sets the position of the vr experience helper.\n */\n set: function (value) {\n this._position = value;\n if (this._scene.activeCamera) {\n this._scene.activeCamera.position = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Enables controllers and user interactions such as selecting and object or clicking on an object.\n */\n VRExperienceHelper.prototype.enableInteractions = function () {\n var _this = this;\n if (!this._interactionsEnabled) {\n this._interactionsRequested = true;\n if (this.leftController) {\n this._enableInteractionOnController(this.leftController);\n }\n if (this.rightController) {\n this._enableInteractionOnController(this.rightController);\n }\n this.raySelectionPredicate = function (mesh) {\n return mesh.isVisible && mesh.isPickable;\n };\n this.meshSelectionPredicate = function (mesh) {\n return true;\n };\n this._raySelectionPredicate = function (mesh) {\n if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf(\"gazeTracker\") === -1\n && mesh.name.indexOf(\"teleportationTarget\") === -1\n && mesh.name.indexOf(\"torusTeleportation\") === -1)) {\n return _this.raySelectionPredicate(mesh);\n }\n return false;\n };\n this._interactionsEnabled = true;\n }\n };\n Object.defineProperty(VRExperienceHelper.prototype, \"_noControllerIsActive\", {\n get: function () {\n return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);\n },\n enumerable: true,\n configurable: true\n });\n VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {\n for (var i = 0; i < this._floorMeshesCollection.length; i++) {\n if (this._floorMeshesCollection[i].id === mesh.id) {\n return true;\n }\n }\n if (this._floorMeshName && mesh.name === this._floorMeshName) {\n return true;\n }\n return false;\n };\n /**\n * Adds a floor mesh to be used for teleportation.\n * @param floorMesh the mesh to be used for teleportation.\n */\n VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {\n if (!this._floorMeshesCollection) {\n return;\n }\n if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {\n return;\n }\n this._floorMeshesCollection.push(floorMesh);\n };\n /**\n * Removes a floor mesh from being used for teleportation.\n * @param floorMesh the mesh to be removed.\n */\n VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {\n if (!this._floorMeshesCollection) {\n return;\n }\n var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);\n if (meshIndex !== -1) {\n this._floorMeshesCollection.splice(meshIndex, 1);\n }\n };\n /**\n * Enables interactions and teleportation using the VR controllers and gaze.\n * @param vrTeleportationOptions options to modify teleportation behavior.\n */\n VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {\n if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }\n if (!this._teleportationInitialized) {\n this._teleportationRequested = true;\n this.enableInteractions();\n if (vrTeleportationOptions.floorMeshName) {\n this._floorMeshName = vrTeleportationOptions.floorMeshName;\n }\n if (vrTeleportationOptions.floorMeshes) {\n this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;\n }\n if (this.leftController != null) {\n this._enableTeleportationOnController(this.leftController);\n }\n if (this.rightController != null) {\n this._enableTeleportationOnController(this.rightController);\n }\n // Creates an image processing post process for the vignette not relying\n // on the main scene configuration for image processing to reduce setup and spaces \n // (gamma/linear) conflicts.\n var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();\n imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);\n imageProcessingConfiguration.vignetteEnabled = true;\n this._postProcessMove = new BABYLON.ImageProcessingPostProcess(\"postProcessMove\", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);\n this._webVRCamera.detachPostProcess(this._postProcessMove);\n this._teleportationInitialized = true;\n if (this._isDefaultTeleportationTarget) {\n this._createTeleportationCircles();\n this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);\n }\n }\n };\n VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {\n var _this = this;\n var controllerMesh = controller.webVRController.mesh;\n if (controllerMesh) {\n controller._interactionsEnabled = true;\n controller._activatePointer();\n if (this.webVROptions.laserToggle) {\n controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {\n // Enabling / disabling laserPointer \n if (_this._displayLaserPointer && stateObject.value === 1) {\n if (controller._activePointer) {\n controller._deactivatePointer();\n }\n else {\n controller._activatePointer();\n }\n if (_this.displayGaze) {\n controller._gazeTracker.isVisible = controller._activePointer;\n }\n }\n });\n }\n controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {\n var gazer = controller;\n if (_this._noControllerIsActive) {\n gazer = _this._cameraGazer;\n }\n if (!gazer._pointerDownOnMeshAsked) {\n if (stateObject.value > _this._padSensibilityUp) {\n gazer._selectionPointerDown();\n }\n }\n else if (stateObject.value < _this._padSensibilityDown) {\n gazer._selectionPointerUp();\n }\n });\n }\n };\n VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {\n // Dont teleport if another gaze already requested teleportation\n if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {\n return;\n }\n if (!gazer._teleportationRequestInitiated) {\n if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {\n gazer._activatePointer();\n gazer._teleportationRequestInitiated = true;\n }\n }\n else {\n // Listening to the proper controller values changes to confirm teleportation\n if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {\n if (this._teleportActive) {\n this._teleportCamera(this._haloCenter);\n }\n gazer._teleportationRequestInitiated = false;\n }\n }\n };\n VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {\n // Only rotate when user is not currently selecting a teleportation location\n if (gazer._teleportationRequestInitiated) {\n return;\n }\n if (!gazer._rotationLeftAsked) {\n if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {\n gazer._rotationLeftAsked = true;\n if (this._rotationAllowed) {\n this._rotateCamera(false);\n }\n }\n }\n else {\n if (stateObject.x > -this._padSensibilityDown) {\n gazer._rotationLeftAsked = false;\n }\n }\n if (!gazer._rotationRightAsked) {\n if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {\n gazer._rotationRightAsked = true;\n if (this._rotationAllowed) {\n this._rotateCamera(true);\n }\n }\n }\n else {\n if (stateObject.x < this._padSensibilityDown) {\n gazer._rotationRightAsked = false;\n }\n }\n };\n VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {\n // Only teleport backwards when user is not currently selecting a teleportation location\n if (gazer._teleportationRequestInitiated) {\n return;\n }\n // Teleport backwards\n if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {\n if (!gazer._teleportationBackRequestInitiated) {\n if (!this.currentVRCamera) {\n return;\n }\n // Get rotation and position of the current camera\n var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());\n var position = this.currentVRCamera.position;\n // If the camera has device position, use that instead\n if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {\n rotation = this.currentVRCamera.deviceRotationQuaternion;\n position = this.currentVRCamera.devicePosition;\n }\n // Get matrix with only the y rotation of the device rotation\n rotation.toEulerAnglesToRef(this._workingVector);\n this._workingVector.z = 0;\n this._workingVector.x = 0;\n BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);\n this._workingQuaternion.toRotationMatrix(this._workingMatrix);\n // Rotate backwards ray by device rotation to cast at the ground behind the user\n BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);\n // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff\n var ray = new BABYLON.Ray(position, this._workingVector);\n var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);\n if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {\n this._teleportCamera(hit.pickedPoint);\n }\n gazer._teleportationBackRequestInitiated = true;\n }\n }\n else {\n gazer._teleportationBackRequestInitiated = false;\n }\n };\n VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {\n var _this = this;\n var controllerMesh = controller.webVRController.mesh;\n if (controllerMesh) {\n if (!controller._interactionsEnabled) {\n this._enableInteractionOnController(controller);\n }\n controller._interactionsEnabled = true;\n controller._teleportationEnabled = true;\n if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {\n controller._dpadPressed = false;\n controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {\n controller._dpadPressed = stateObject.pressed;\n if (!controller._dpadPressed) {\n controller._rotationLeftAsked = false;\n controller._rotationRightAsked = false;\n controller._teleportationBackRequestInitiated = false;\n }\n });\n }\n controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {\n if (_this.teleportationEnabled) {\n _this._checkTeleportBackwards(stateObject, controller);\n _this._checkTeleportWithRay(stateObject, controller);\n }\n _this._checkRotate(stateObject, controller);\n });\n }\n };\n VRExperienceHelper.prototype._createTeleportationCircles = function () {\n this._teleportationTarget = BABYLON.Mesh.CreateGround(\"teleportationTarget\", 2, 2, 2, this._scene);\n this._teleportationTarget.isPickable = false;\n var length = 512;\n var dynamicTexture = new BABYLON.DynamicTexture(\"DynamicTexture\", length, this._scene, true);\n dynamicTexture.hasAlpha = true;\n var context = dynamicTexture.getContext();\n var centerX = length / 2;\n var centerY = length / 2;\n var radius = 200;\n context.beginPath();\n context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);\n context.fillStyle = this._teleportationFillColor;\n context.fill();\n context.lineWidth = 10;\n context.strokeStyle = this._teleportationBorderColor;\n context.stroke();\n context.closePath();\n dynamicTexture.update();\n var teleportationCircleMaterial = new BABYLON.StandardMaterial(\"TextPlaneMaterial\", this._scene);\n teleportationCircleMaterial.diffuseTexture = dynamicTexture;\n this._teleportationTarget.material = teleportationCircleMaterial;\n var torus = BABYLON.Mesh.CreateTorus(\"torusTeleportation\", 0.75, 0.1, 25, this._scene, false);\n torus.isPickable = false;\n torus.parent = this._teleportationTarget;\n var animationInnerCircle = new BABYLON.Animation(\"animationInnerCircle\", \"position.y\", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);\n var keys = [];\n keys.push({\n frame: 0,\n value: 0\n });\n keys.push({\n frame: 30,\n value: 0.4\n });\n keys.push({\n frame: 60,\n value: 0\n });\n animationInnerCircle.setKeys(keys);\n var easingFunction = new BABYLON.SineEase();\n easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);\n animationInnerCircle.setEasingFunction(easingFunction);\n torus.animations = [];\n torus.animations.push(animationInnerCircle);\n this._scene.beginAnimation(torus, 0, 60, true);\n this._hideTeleportationTarget();\n };\n VRExperienceHelper.prototype._displayTeleportationTarget = function () {\n this._teleportActive = true;\n if (this._teleportationInitialized) {\n this._teleportationTarget.isVisible = true;\n if (this._isDefaultTeleportationTarget) {\n this._teleportationTarget.getChildren()[0].isVisible = true;\n }\n }\n };\n VRExperienceHelper.prototype._hideTeleportationTarget = function () {\n this._teleportActive = false;\n if (this._teleportationInitialized) {\n this._teleportationTarget.isVisible = false;\n if (this._isDefaultTeleportationTarget) {\n this._teleportationTarget.getChildren()[0].isVisible = false;\n }\n }\n };\n VRExperienceHelper.prototype._rotateCamera = function (right) {\n var _this = this;\n if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {\n return;\n }\n if (right) {\n this._rotationAngle++;\n }\n else {\n this._rotationAngle--;\n }\n this.currentVRCamera.animations = [];\n var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));\n var animationRotation = new BABYLON.Animation(\"animationRotation\", \"rotationQuaternion\", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n var animationRotationKeys = [];\n animationRotationKeys.push({\n frame: 0,\n value: this.currentVRCamera.rotationQuaternion\n });\n animationRotationKeys.push({\n frame: 6,\n value: target\n });\n animationRotation.setKeys(animationRotationKeys);\n animationRotation.setEasingFunction(this._circleEase);\n this.currentVRCamera.animations.push(animationRotation);\n this._postProcessMove.animations = [];\n var animationPP = new BABYLON.Animation(\"animationPP\", \"vignetteWeight\", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n var vignetteWeightKeys = [];\n vignetteWeightKeys.push({\n frame: 0,\n value: 0\n });\n vignetteWeightKeys.push({\n frame: 3,\n value: 4\n });\n vignetteWeightKeys.push({\n frame: 6,\n value: 0\n });\n animationPP.setKeys(vignetteWeightKeys);\n animationPP.setEasingFunction(this._circleEase);\n this._postProcessMove.animations.push(animationPP);\n var animationPP2 = new BABYLON.Animation(\"animationPP2\", \"vignetteStretch\", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n var vignetteStretchKeys = [];\n vignetteStretchKeys.push({\n frame: 0,\n value: 0\n });\n vignetteStretchKeys.push({\n frame: 3,\n value: 10\n });\n vignetteStretchKeys.push({\n frame: 6,\n value: 0\n });\n animationPP2.setKeys(vignetteStretchKeys);\n animationPP2.setEasingFunction(this._circleEase);\n this._postProcessMove.animations.push(animationPP2);\n this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;\n this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;\n this._postProcessMove.samples = 4;\n this._webVRCamera.attachPostProcess(this._postProcessMove);\n this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {\n _this._webVRCamera.detachPostProcess(_this._postProcessMove);\n });\n this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);\n };\n VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {\n if (hit.pickedPoint) {\n if (gazer._teleportationRequestInitiated) {\n this._displayTeleportationTarget();\n this._haloCenter.copyFrom(hit.pickedPoint);\n this._teleportationTarget.position.copyFrom(hit.pickedPoint);\n }\n var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);\n if (pickNormal) {\n var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);\n var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);\n BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);\n }\n this._teleportationTarget.position.y += 0.1;\n }\n };\n VRExperienceHelper.prototype._teleportCamera = function (location) {\n var _this = this;\n if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {\n return;\n }\n // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the\n // offset of the headset from the anchor.\n if (this.webVRCamera.leftCamera) {\n this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);\n this._workingVector.subtractInPlace(this.webVRCamera.position);\n location.subtractToRef(this._workingVector, this._workingVector);\n }\n else {\n this._workingVector.copyFrom(location);\n }\n // Add height to account for user's height offset\n if (this.isInVRMode) {\n this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;\n }\n else {\n this._workingVector.y += this._defaultHeight;\n }\n this.onBeforeCameraTeleport.notifyObservers(this._workingVector);\n // Create animation from the camera's position to the new location\n this.currentVRCamera.animations = [];\n var animationCameraTeleportation = new BABYLON.Animation(\"animationCameraTeleportation\", \"position\", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n var animationCameraTeleportationKeys = [{\n frame: 0,\n value: this.currentVRCamera.position\n },\n {\n frame: 11,\n value: this._workingVector\n }\n ];\n animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);\n animationCameraTeleportation.setEasingFunction(this._circleEase);\n this.currentVRCamera.animations.push(animationCameraTeleportation);\n this._postProcessMove.animations = [];\n var animationPP = new BABYLON.Animation(\"animationPP\", \"vignetteWeight\", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n var vignetteWeightKeys = [];\n vignetteWeightKeys.push({\n frame: 0,\n value: 0\n });\n vignetteWeightKeys.push({\n frame: 5,\n value: 8\n });\n vignetteWeightKeys.push({\n frame: 11,\n value: 0\n });\n animationPP.setKeys(vignetteWeightKeys);\n this._postProcessMove.animations.push(animationPP);\n var animationPP2 = new BABYLON.Animation(\"animationPP2\", \"vignetteStretch\", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n var vignetteStretchKeys = [];\n vignetteStretchKeys.push({\n frame: 0,\n value: 0\n });\n vignetteStretchKeys.push({\n frame: 5,\n value: 10\n });\n vignetteStretchKeys.push({\n frame: 11,\n value: 0\n });\n animationPP2.setKeys(vignetteStretchKeys);\n this._postProcessMove.animations.push(animationPP2);\n this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;\n this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;\n this._webVRCamera.attachPostProcess(this._postProcessMove);\n this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {\n _this._webVRCamera.detachPostProcess(_this._postProcessMove);\n });\n this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {\n _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);\n });\n this._hideTeleportationTarget();\n };\n VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {\n if (normal) {\n var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));\n if (angle < Math.PI / 2) {\n normal.scaleInPlace(-1);\n }\n }\n return normal;\n };\n VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {\n if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {\n return;\n }\n var ray = gazer._getForwardRay(this._rayLength);\n var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);\n if (hit) {\n // Populate the contrllers mesh that can be used for drag/drop\n if (gazer._laserPointer) {\n hit.originMesh = gazer._laserPointer.parent;\n }\n this._scene.simulatePointerMove(hit, { pointerId: gazer._id });\n }\n gazer._currentHit = hit;\n // Moving the gazeTracker on the mesh face targetted\n if (hit && hit.pickedPoint) {\n if (this._displayGaze) {\n var multiplier = 1;\n gazer._gazeTracker.isVisible = true;\n if (gazer._isActionableMesh) {\n multiplier = 3;\n }\n gazer._gazeTracker.scaling.x = hit.distance * multiplier;\n gazer._gazeTracker.scaling.y = hit.distance * multiplier;\n gazer._gazeTracker.scaling.z = hit.distance * multiplier;\n var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);\n // To avoid z-fighting\n var deltaFighting = 0.002;\n if (pickNormal) {\n var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);\n var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);\n BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);\n }\n gazer._gazeTracker.position.copyFrom(hit.pickedPoint);\n if (gazer._gazeTracker.position.x < 0) {\n gazer._gazeTracker.position.x += deltaFighting;\n }\n else {\n gazer._gazeTracker.position.x -= deltaFighting;\n }\n if (gazer._gazeTracker.position.y < 0) {\n gazer._gazeTracker.position.y += deltaFighting;\n }\n else {\n gazer._gazeTracker.position.y -= deltaFighting;\n }\n if (gazer._gazeTracker.position.z < 0) {\n gazer._gazeTracker.position.z += deltaFighting;\n }\n else {\n gazer._gazeTracker.position.z -= deltaFighting;\n }\n }\n // Changing the size of the laser pointer based on the distance from the targetted point\n gazer._updatePointerDistance(hit.distance);\n }\n else {\n gazer._updatePointerDistance();\n gazer._gazeTracker.isVisible = false;\n }\n if (hit && hit.pickedMesh) {\n // The object selected is the floor, we're in a teleportation scenario\n if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {\n // Moving the teleportation area to this targetted point\n //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected\n if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {\n this._notifySelectedMeshUnselected(gazer._currentMeshSelected);\n }\n gazer._currentMeshSelected = null;\n if (gazer._teleportationRequestInitiated) {\n this._moveTeleportationSelectorTo(hit, gazer, ray);\n }\n return;\n }\n // If not, we're in a selection scenario\n //this._teleportationAllowed = false;\n if (hit.pickedMesh !== gazer._currentMeshSelected) {\n if (this.meshSelectionPredicate(hit.pickedMesh)) {\n this.onNewMeshPicked.notifyObservers(hit);\n gazer._currentMeshSelected = hit.pickedMesh;\n if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {\n this.changeGazeColor(new BABYLON.Color3(0, 0, 1));\n this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));\n gazer._isActionableMesh = true;\n }\n else {\n this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));\n this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));\n gazer._isActionableMesh = false;\n }\n try {\n this.onNewMeshSelected.notifyObservers(hit.pickedMesh);\n }\n catch (err) {\n BABYLON.Tools.Warn(\"Error in your custom logic onNewMeshSelected: \" + err);\n }\n }\n else {\n this._notifySelectedMeshUnselected(gazer._currentMeshSelected);\n gazer._currentMeshSelected = null;\n this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));\n this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));\n }\n }\n }\n else {\n this._notifySelectedMeshUnselected(gazer._currentMeshSelected);\n gazer._currentMeshSelected = null;\n //this._teleportationAllowed = false;\n this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));\n this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));\n }\n };\n VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {\n if (mesh) {\n this.onSelectedMeshUnselected.notifyObservers(mesh);\n }\n };\n /**\n * Sets the color of the laser ray from the vr controllers.\n * @param color new color for the ray.\n */\n VRExperienceHelper.prototype.changeLaserColor = function (color) {\n if (this.leftController) {\n this.leftController._setLaserPointerColor(color);\n }\n if (this.rightController) {\n this.rightController._setLaserPointerColor(color);\n }\n };\n /**\n * Sets the color of the ray from the vr headsets gaze.\n * @param color new color for the ray.\n */\n VRExperienceHelper.prototype.changeGazeColor = function (color) {\n if (!this._cameraGazer._gazeTracker.material) {\n return;\n }\n this._cameraGazer._gazeTracker.material.emissiveColor = color;\n if (this.leftController) {\n this.leftController._gazeTracker.material.emissiveColor = color;\n }\n if (this.rightController) {\n this.rightController._gazeTracker.material.emissiveColor = color;\n }\n };\n /**\n * Exits VR and disposes of the vr experience helper\n */\n VRExperienceHelper.prototype.dispose = function () {\n if (this.isInVRMode) {\n this.exitVR();\n }\n if (this._postProcessMove) {\n this._postProcessMove.dispose();\n }\n if (this._webVRCamera) {\n this._webVRCamera.dispose();\n }\n if (this._vrDeviceOrientationCamera) {\n this._vrDeviceOrientationCamera.dispose();\n }\n if (!this._useCustomVRButton && this._btnVR.parentNode) {\n document.body.removeChild(this._btnVR);\n }\n if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {\n this._deviceOrientationCamera.dispose();\n }\n if (this._cameraGazer) {\n this._cameraGazer.dispose();\n }\n if (this.leftController) {\n this.leftController.dispose();\n }\n if (this.rightController) {\n this.rightController.dispose();\n }\n if (this._teleportationTarget) {\n this._teleportationTarget.dispose();\n }\n this._floorMeshesCollection = [];\n document.removeEventListener(\"keydown\", this._onKeyDown);\n window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);\n window.removeEventListener(\"resize\", this._onResize);\n document.removeEventListener(\"fullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"mozfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"webkitfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"msfullscreenchange\", this._onFullscreenChange);\n document.onmsfullscreenchange = null;\n this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);\n this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);\n this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);\n window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);\n this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);\n this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);\n this._scene.unregisterBeforeRender(this.beforeRender);\n };\n /**\n * Gets the name of the VRExperienceHelper class\n * @returns \"VRExperienceHelper\"\n */\n VRExperienceHelper.prototype.getClassName = function () {\n return \"VRExperienceHelper\";\n };\n return VRExperienceHelper;\n }());\n BABYLON.VRExperienceHelper = VRExperienceHelper;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vrExperienceHelper.js.map\n\n// Mainly based on these 2 articles : \n// Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx\n// & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/ \nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the potential axis of a Joystick\n */\n var JoystickAxis;\n (function (JoystickAxis) {\n /** X axis */\n JoystickAxis[JoystickAxis[\"X\"] = 0] = \"X\";\n /** Y axis */\n JoystickAxis[JoystickAxis[\"Y\"] = 1] = \"Y\";\n /** Z axis */\n JoystickAxis[JoystickAxis[\"Z\"] = 2] = \"Z\";\n })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));\n /**\n * Class used to define virtual joystick (used in touch mode)\n */\n var VirtualJoystick = /** @class */ (function () {\n /**\n * Creates a new virtual joystick\n * @param leftJoystick defines that the joystick is for left hand (false by default)\n */\n function VirtualJoystick(leftJoystick) {\n var _this = this;\n if (leftJoystick) {\n this._leftJoystick = true;\n }\n else {\n this._leftJoystick = false;\n }\n VirtualJoystick._globalJoystickIndex++;\n // By default left & right arrow keys are moving the X\n // and up & down keys are moving the Y\n this._axisTargetedByLeftAndRight = JoystickAxis.X;\n this._axisTargetedByUpAndDown = JoystickAxis.Y;\n this.reverseLeftRight = false;\n this.reverseUpDown = false;\n // collections of pointers\n this._touches = new BABYLON.StringDictionary();\n this.deltaPosition = BABYLON.Vector3.Zero();\n this._joystickSensibility = 25;\n this._inversedSensibility = 1 / (this._joystickSensibility / 1000);\n this._onResize = function (evt) {\n VirtualJoystick.vjCanvasWidth = window.innerWidth;\n VirtualJoystick.vjCanvasHeight = window.innerHeight;\n if (VirtualJoystick.vjCanvas) {\n VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;\n VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;\n }\n VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;\n };\n // injecting a canvas element on top of the canvas 3D game\n if (!VirtualJoystick.vjCanvas) {\n window.addEventListener(\"resize\", this._onResize, false);\n VirtualJoystick.vjCanvas = document.createElement(\"canvas\");\n VirtualJoystick.vjCanvasWidth = window.innerWidth;\n VirtualJoystick.vjCanvasHeight = window.innerHeight;\n VirtualJoystick.vjCanvas.width = window.innerWidth;\n VirtualJoystick.vjCanvas.height = window.innerHeight;\n VirtualJoystick.vjCanvas.style.width = \"100%\";\n VirtualJoystick.vjCanvas.style.height = \"100%\";\n VirtualJoystick.vjCanvas.style.position = \"absolute\";\n VirtualJoystick.vjCanvas.style.backgroundColor = \"transparent\";\n VirtualJoystick.vjCanvas.style.top = \"0px\";\n VirtualJoystick.vjCanvas.style.left = \"0px\";\n VirtualJoystick.vjCanvas.style.zIndex = \"5\";\n VirtualJoystick.vjCanvas.style.msTouchAction = \"none\";\n // Support for jQuery PEP polyfill\n VirtualJoystick.vjCanvas.setAttribute(\"touch-action\", \"none\");\n var context = VirtualJoystick.vjCanvas.getContext('2d');\n if (!context) {\n throw new Error(\"Unable to create canvas for virtual joystick\");\n }\n VirtualJoystick.vjCanvasContext = context;\n VirtualJoystick.vjCanvasContext.strokeStyle = \"#ffffff\";\n VirtualJoystick.vjCanvasContext.lineWidth = 2;\n document.body.appendChild(VirtualJoystick.vjCanvas);\n }\n VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;\n this.pressed = false;\n // default joystick color\n this._joystickColor = \"cyan\";\n this._joystickPointerID = -1;\n // current joystick position\n this._joystickPointerPos = new BABYLON.Vector2(0, 0);\n this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);\n // origin joystick position\n this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);\n this._deltaJoystickVector = new BABYLON.Vector2(0, 0);\n this._onPointerDownHandlerRef = function (evt) {\n _this._onPointerDown(evt);\n };\n this._onPointerMoveHandlerRef = function (evt) {\n _this._onPointerMove(evt);\n };\n this._onPointerUpHandlerRef = function (evt) {\n _this._onPointerUp(evt);\n };\n VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);\n VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);\n VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);\n VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);\n VirtualJoystick.vjCanvas.addEventListener(\"contextmenu\", function (evt) {\n evt.preventDefault(); // Disables system menu\n }, false);\n requestAnimationFrame(function () { _this._drawVirtualJoystick(); });\n }\n /**\n * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)\n * @param newJoystickSensibility defines the new sensibility\n */\n VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {\n this._joystickSensibility = newJoystickSensibility;\n this._inversedSensibility = 1 / (this._joystickSensibility / 1000);\n };\n VirtualJoystick.prototype._onPointerDown = function (e) {\n var positionOnScreenCondition;\n e.preventDefault();\n if (this._leftJoystick === true) {\n positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);\n }\n else {\n positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);\n }\n if (positionOnScreenCondition && this._joystickPointerID < 0) {\n // First contact will be dedicated to the virtual joystick\n this._joystickPointerID = e.pointerId;\n this._joystickPointerStartPos.x = e.clientX;\n this._joystickPointerStartPos.y = e.clientY;\n this._joystickPointerPos = this._joystickPointerStartPos.clone();\n this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();\n this._deltaJoystickVector.x = 0;\n this._deltaJoystickVector.y = 0;\n this.pressed = true;\n this._touches.add(e.pointerId.toString(), e);\n }\n else {\n // You can only trigger the action buttons with a joystick declared\n if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {\n this._action();\n this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });\n }\n }\n };\n VirtualJoystick.prototype._onPointerMove = function (e) {\n // If the current pointer is the one associated to the joystick (first touch contact)\n if (this._joystickPointerID == e.pointerId) {\n this._joystickPointerPos.x = e.clientX;\n this._joystickPointerPos.y = e.clientY;\n this._deltaJoystickVector = this._joystickPointerPos.clone();\n this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);\n var directionLeftRight = this.reverseLeftRight ? -1 : 1;\n var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;\n switch (this._axisTargetedByLeftAndRight) {\n case JoystickAxis.X:\n this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));\n break;\n case JoystickAxis.Y:\n this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));\n break;\n case JoystickAxis.Z:\n this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));\n break;\n }\n var directionUpDown = this.reverseUpDown ? 1 : -1;\n var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;\n switch (this._axisTargetedByUpAndDown) {\n case JoystickAxis.X:\n this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));\n break;\n case JoystickAxis.Y:\n this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));\n break;\n case JoystickAxis.Z:\n this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));\n break;\n }\n }\n else {\n var data = this._touches.get(e.pointerId.toString());\n if (data) {\n data.x = e.clientX;\n data.y = e.clientY;\n }\n }\n };\n VirtualJoystick.prototype._onPointerUp = function (e) {\n if (this._joystickPointerID == e.pointerId) {\n VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);\n VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);\n this._joystickPointerID = -1;\n this.pressed = false;\n }\n else {\n var touch = this._touches.get(e.pointerId.toString());\n if (touch) {\n VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);\n }\n }\n this._deltaJoystickVector.x = 0;\n this._deltaJoystickVector.y = 0;\n this._touches.remove(e.pointerId.toString());\n };\n /**\n * Change the color of the virtual joystick\n * @param newColor a string that must be a CSS color value (like \"red\") or the hexa value (like \"#FF0000\")\n */\n VirtualJoystick.prototype.setJoystickColor = function (newColor) {\n this._joystickColor = newColor;\n };\n /**\n * Defines a callback to call when the joystick is touched\n * @param action defines the callback\n */\n VirtualJoystick.prototype.setActionOnTouch = function (action) {\n this._action = action;\n };\n /**\n * Defines which axis you'd like to control for left & right\n * @param axis defines the axis to use\n */\n VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {\n switch (axis) {\n case JoystickAxis.X:\n case JoystickAxis.Y:\n case JoystickAxis.Z:\n this._axisTargetedByLeftAndRight = axis;\n break;\n default:\n this._axisTargetedByLeftAndRight = JoystickAxis.X;\n break;\n }\n };\n /**\n * Defines which axis you'd like to control for up & down\n * @param axis defines the axis to use\n */\n VirtualJoystick.prototype.setAxisForUpDown = function (axis) {\n switch (axis) {\n case JoystickAxis.X:\n case JoystickAxis.Y:\n case JoystickAxis.Z:\n this._axisTargetedByUpAndDown = axis;\n break;\n default:\n this._axisTargetedByUpAndDown = JoystickAxis.Y;\n break;\n }\n };\n VirtualJoystick.prototype._drawVirtualJoystick = function () {\n var _this = this;\n if (this.pressed) {\n this._touches.forEach(function (key, touch) {\n if (touch.pointerId === _this._joystickPointerID) {\n VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);\n VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);\n VirtualJoystick.vjCanvasContext.beginPath();\n VirtualJoystick.vjCanvasContext.lineWidth = 6;\n VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;\n VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);\n VirtualJoystick.vjCanvasContext.stroke();\n VirtualJoystick.vjCanvasContext.closePath();\n VirtualJoystick.vjCanvasContext.beginPath();\n VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;\n VirtualJoystick.vjCanvasContext.lineWidth = 2;\n VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);\n VirtualJoystick.vjCanvasContext.stroke();\n VirtualJoystick.vjCanvasContext.closePath();\n VirtualJoystick.vjCanvasContext.beginPath();\n VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;\n VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);\n VirtualJoystick.vjCanvasContext.stroke();\n VirtualJoystick.vjCanvasContext.closePath();\n _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();\n }\n else {\n VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);\n VirtualJoystick.vjCanvasContext.beginPath();\n VirtualJoystick.vjCanvasContext.fillStyle = \"white\";\n VirtualJoystick.vjCanvasContext.beginPath();\n VirtualJoystick.vjCanvasContext.strokeStyle = \"red\";\n VirtualJoystick.vjCanvasContext.lineWidth = 6;\n VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);\n VirtualJoystick.vjCanvasContext.stroke();\n VirtualJoystick.vjCanvasContext.closePath();\n touch.prevX = touch.x;\n touch.prevY = touch.y;\n }\n ;\n });\n }\n requestAnimationFrame(function () { _this._drawVirtualJoystick(); });\n };\n /**\n * Release internal HTML canvas\n */\n VirtualJoystick.prototype.releaseCanvas = function () {\n if (VirtualJoystick.vjCanvas) {\n VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);\n VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);\n VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);\n VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);\n window.removeEventListener(\"resize\", this._onResize);\n document.body.removeChild(VirtualJoystick.vjCanvas);\n VirtualJoystick.vjCanvas = null;\n }\n };\n // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas\n VirtualJoystick._globalJoystickIndex = 0;\n return VirtualJoystick;\n }());\n BABYLON.VirtualJoystick = VirtualJoystick;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.virtualJoystick.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"VirtualJoysticksCamera\", function (name, scene) {\n return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n // We're mainly based on the logic defined into the FreeCamera code\n var VirtualJoysticksCamera = /** @class */ (function (_super) {\n __extends(VirtualJoysticksCamera, _super);\n function VirtualJoysticksCamera(name, position, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.inputs.addVirtualJoystick();\n return _this;\n }\n VirtualJoysticksCamera.prototype.getClassName = function () {\n return \"VirtualJoysticksCamera\";\n };\n return VirtualJoysticksCamera;\n }(BABYLON.FreeCamera));\n BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.virtualJoysticksCamera.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var FreeCameraVirtualJoystickInput = /** @class */ (function () {\n function FreeCameraVirtualJoystickInput() {\n }\n FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {\n return this._leftjoystick;\n };\n FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {\n return this._rightjoystick;\n };\n FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {\n if (this._leftjoystick) {\n var camera = this.camera;\n var speed = camera._computeLocalCameraSpeed() * 50;\n var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);\n var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);\n camera.cameraDirection = camera.cameraDirection.add(deltaTransform);\n camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);\n if (!this._leftjoystick.pressed) {\n this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);\n }\n if (!this._rightjoystick.pressed) {\n this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);\n }\n }\n };\n FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {\n this._leftjoystick = new BABYLON.VirtualJoystick(true);\n this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);\n this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);\n this._leftjoystick.setJoystickSensibility(0.15);\n this._rightjoystick = new BABYLON.VirtualJoystick(false);\n this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);\n this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);\n this._rightjoystick.reverseUpDown = true;\n this._rightjoystick.setJoystickSensibility(0.05);\n this._rightjoystick.setJoystickColor(\"yellow\");\n };\n FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {\n this._leftjoystick.releaseCanvas();\n this._rightjoystick.releaseCanvas();\n };\n FreeCameraVirtualJoystickInput.prototype.getClassName = function () {\n return \"FreeCameraVirtualJoystickInput\";\n };\n FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {\n return \"virtualJoystick\";\n };\n return FreeCameraVirtualJoystickInput;\n }());\n BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;\n BABYLON.CameraInputTypes[\"FreeCameraVirtualJoystickInput\"] = FreeCameraVirtualJoystickInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var SimplificationSettings = /** @class */ (function () {\n function SimplificationSettings(quality, distance, optimizeMesh) {\n this.quality = quality;\n this.distance = distance;\n this.optimizeMesh = optimizeMesh;\n }\n return SimplificationSettings;\n }());\n BABYLON.SimplificationSettings = SimplificationSettings;\n var SimplificationQueue = /** @class */ (function () {\n function SimplificationQueue() {\n this.running = false;\n this._simplificationArray = [];\n }\n SimplificationQueue.prototype.addTask = function (task) {\n this._simplificationArray.push(task);\n };\n SimplificationQueue.prototype.executeNext = function () {\n var task = this._simplificationArray.pop();\n if (task) {\n this.running = true;\n this.runSimplification(task);\n }\n else {\n this.running = false;\n }\n };\n SimplificationQueue.prototype.runSimplification = function (task) {\n var _this = this;\n if (task.parallelProcessing) {\n //parallel simplifier\n task.settings.forEach(function (setting) {\n var simplifier = _this.getSimplifier(task);\n simplifier.simplify(setting, function (newMesh) {\n task.mesh.addLODLevel(setting.distance, newMesh);\n newMesh.isVisible = true;\n //check if it is the last\n if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {\n //all done, run the success callback.\n task.successCallback();\n }\n _this.executeNext();\n });\n });\n }\n else {\n //single simplifier.\n var simplifier = this.getSimplifier(task);\n var runDecimation = function (setting, callback) {\n simplifier.simplify(setting, function (newMesh) {\n task.mesh.addLODLevel(setting.distance, newMesh);\n newMesh.isVisible = true;\n //run the next quality level\n callback();\n });\n };\n BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {\n runDecimation(task.settings[loop.index], function () {\n loop.executeNext();\n });\n }, function () {\n //execution ended, run the success callback.\n if (task.successCallback) {\n task.successCallback();\n }\n _this.executeNext();\n });\n }\n };\n SimplificationQueue.prototype.getSimplifier = function (task) {\n switch (task.simplificationType) {\n case SimplificationType.QUADRATIC:\n default:\n return new QuadraticErrorSimplification(task.mesh);\n }\n };\n return SimplificationQueue;\n }());\n BABYLON.SimplificationQueue = SimplificationQueue;\n /**\n * The implemented types of simplification\n * At the moment only Quadratic Error Decimation is implemented\n */\n var SimplificationType;\n (function (SimplificationType) {\n /** Quadratic error decimation */\n SimplificationType[SimplificationType[\"QUADRATIC\"] = 0] = \"QUADRATIC\";\n })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));\n var DecimationTriangle = /** @class */ (function () {\n function DecimationTriangle(vertices) {\n this.vertices = vertices;\n this.error = new Array(4);\n this.deleted = false;\n this.isDirty = false;\n this.deletePending = false;\n this.borderFactor = 0;\n }\n return DecimationTriangle;\n }());\n BABYLON.DecimationTriangle = DecimationTriangle;\n var DecimationVertex = /** @class */ (function () {\n function DecimationVertex(position, id) {\n this.position = position;\n this.id = id;\n this.isBorder = true;\n this.q = new QuadraticMatrix();\n this.triangleCount = 0;\n this.triangleStart = 0;\n this.originalOffsets = [];\n }\n DecimationVertex.prototype.updatePosition = function (newPosition) {\n this.position.copyFrom(newPosition);\n };\n return DecimationVertex;\n }());\n BABYLON.DecimationVertex = DecimationVertex;\n var QuadraticMatrix = /** @class */ (function () {\n function QuadraticMatrix(data) {\n this.data = new Array(10);\n for (var i = 0; i < 10; ++i) {\n if (data && data[i]) {\n this.data[i] = data[i];\n }\n else {\n this.data[i] = 0;\n }\n }\n }\n QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {\n var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +\n this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -\n this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];\n return det;\n };\n QuadraticMatrix.prototype.addInPlace = function (matrix) {\n for (var i = 0; i < 10; ++i) {\n this.data[i] += matrix.data[i];\n }\n };\n QuadraticMatrix.prototype.addArrayInPlace = function (data) {\n for (var i = 0; i < 10; ++i) {\n this.data[i] += data[i];\n }\n };\n QuadraticMatrix.prototype.add = function (matrix) {\n var m = new QuadraticMatrix();\n for (var i = 0; i < 10; ++i) {\n m.data[i] = this.data[i] + matrix.data[i];\n }\n return m;\n };\n QuadraticMatrix.FromData = function (a, b, c, d) {\n return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));\n };\n //returning an array to avoid garbage collection\n QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {\n return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];\n };\n return QuadraticMatrix;\n }());\n BABYLON.QuadraticMatrix = QuadraticMatrix;\n var Reference = /** @class */ (function () {\n function Reference(vertexId, triangleId) {\n this.vertexId = vertexId;\n this.triangleId = triangleId;\n }\n return Reference;\n }());\n BABYLON.Reference = Reference;\n /**\n * An implementation of the Quadratic Error simplification algorithm.\n * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf\n * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS\n * @author RaananW\n */\n var QuadraticErrorSimplification = /** @class */ (function () {\n function QuadraticErrorSimplification(_mesh) {\n this._mesh = _mesh;\n this.syncIterations = 5000;\n this.aggressiveness = 7;\n this.decimationIterations = 100;\n this.boundingBoxEpsilon = BABYLON.Epsilon;\n }\n QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {\n var _this = this;\n this.initDecimatedMesh();\n //iterating through the submeshes array, one after the other.\n BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {\n _this.initWithMesh(loop.index, function () {\n _this.runDecimation(settings, loop.index, function () {\n loop.executeNext();\n });\n }, settings.optimizeMesh);\n }, function () {\n setTimeout(function () {\n successCallback(_this._reconstructedMesh);\n }, 0);\n });\n };\n QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {\n var _this = this;\n var targetCount = ~~(this.triangles.length * settings.quality);\n var deletedTriangles = 0;\n var triangleCount = this.triangles.length;\n var iterationFunction = function (iteration, callback) {\n setTimeout(function () {\n if (iteration % 5 === 0) {\n _this.updateMesh(iteration === 0);\n }\n for (var i = 0; i < _this.triangles.length; ++i) {\n _this.triangles[i].isDirty = false;\n }\n var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);\n var trianglesIterator = function (i) {\n var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);\n var t = _this.triangles[tIdx];\n if (!t)\n return;\n if (t.error[3] > threshold || t.deleted || t.isDirty) {\n return;\n }\n for (var j = 0; j < 3; ++j) {\n if (t.error[j] < threshold) {\n var deleted0 = [];\n var deleted1 = [];\n var v0 = t.vertices[j];\n var v1 = t.vertices[(j + 1) % 3];\n if (v0.isBorder || v1.isBorder)\n continue;\n var p = BABYLON.Vector3.Zero();\n var n = BABYLON.Vector3.Zero();\n var uv = BABYLON.Vector2.Zero();\n var color = new BABYLON.Color4(0, 0, 0, 1);\n _this.calculateError(v0, v1, p, n, uv, color);\n var delTr = new Array();\n if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))\n continue;\n if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))\n continue;\n if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)\n continue;\n var uniqueArray = new Array();\n delTr.forEach(function (deletedT) {\n if (uniqueArray.indexOf(deletedT) === -1) {\n deletedT.deletePending = true;\n uniqueArray.push(deletedT);\n }\n });\n if (uniqueArray.length % 2 !== 0) {\n continue;\n }\n v0.q = v1.q.add(v0.q);\n v0.updatePosition(p);\n var tStart = _this.references.length;\n deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);\n deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);\n var tCount = _this.references.length - tStart;\n if (tCount <= v0.triangleCount) {\n if (tCount) {\n for (var c = 0; c < tCount; c++) {\n _this.references[v0.triangleStart + c] = _this.references[tStart + c];\n }\n }\n }\n else {\n v0.triangleStart = tStart;\n }\n v0.triangleCount = tCount;\n break;\n }\n }\n };\n BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });\n }, 0);\n };\n BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {\n if (triangleCount - deletedTriangles <= targetCount)\n loop.breakLoop();\n else {\n iterationFunction(loop.index, function () {\n loop.executeNext();\n });\n }\n }, function () {\n setTimeout(function () {\n //reconstruct this part of the mesh\n _this.reconstructMesh(submeshIndex);\n successCallback();\n }, 0);\n });\n };\n QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {\n var _this = this;\n this.vertices = [];\n this.triangles = [];\n var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var indices = this._mesh.getIndices();\n var submesh = this._mesh.subMeshes[submeshIndex];\n var findInVertices = function (positionToSearch) {\n if (optimizeMesh) {\n for (var ii = 0; ii < _this.vertices.length; ++ii) {\n if (_this.vertices[ii].position.equals(positionToSearch)) {\n return _this.vertices[ii];\n }\n }\n }\n return null;\n };\n var vertexReferences = [];\n var vertexInit = function (i) {\n if (!positionData) {\n return;\n }\n var offset = i + submesh.verticesStart;\n var position = BABYLON.Vector3.FromArray(positionData, offset * 3);\n var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);\n vertex.originalOffsets.push(offset);\n if (vertex.id === _this.vertices.length) {\n _this.vertices.push(vertex);\n }\n vertexReferences.push(vertex.id);\n };\n //var totalVertices = mesh.getTotalVertices();\n var totalVertices = submesh.verticesCount;\n BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {\n var indicesInit = function (i) {\n if (!indices) {\n return;\n }\n var offset = (submesh.indexStart / 3) + i;\n var pos = (offset * 3);\n var i0 = indices[pos + 0];\n var i1 = indices[pos + 1];\n var i2 = indices[pos + 2];\n var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];\n var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];\n var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];\n var triangle = new DecimationTriangle([v0, v1, v2]);\n triangle.originalOffset = pos;\n _this.triangles.push(triangle);\n };\n BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {\n _this.init(callback);\n });\n });\n };\n QuadraticErrorSimplification.prototype.init = function (callback) {\n var _this = this;\n var triangleInit1 = function (i) {\n var t = _this.triangles[i];\n t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();\n for (var j = 0; j < 3; j++) {\n t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));\n }\n };\n BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {\n var triangleInit2 = function (i) {\n var t = _this.triangles[i];\n for (var j = 0; j < 3; ++j) {\n t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);\n }\n t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);\n };\n BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {\n callback();\n });\n });\n };\n QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {\n var newTriangles = [];\n var i;\n for (i = 0; i < this.vertices.length; ++i) {\n this.vertices[i].triangleCount = 0;\n }\n var t;\n var j;\n for (i = 0; i < this.triangles.length; ++i) {\n if (!this.triangles[i].deleted) {\n t = this.triangles[i];\n for (j = 0; j < 3; ++j) {\n t.vertices[j].triangleCount = 1;\n }\n newTriangles.push(t);\n }\n }\n var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);\n var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);\n var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);\n var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);\n var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);\n var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);\n var vertexCount = 0;\n for (i = 0; i < this.vertices.length; ++i) {\n var vertex = this.vertices[i];\n vertex.id = vertexCount;\n if (vertex.triangleCount) {\n vertex.originalOffsets.forEach(function (originalOffset) {\n if (!normalData) {\n return;\n }\n newPositionData.push(vertex.position.x);\n newPositionData.push(vertex.position.y);\n newPositionData.push(vertex.position.z);\n newNormalData.push(normalData[originalOffset * 3]);\n newNormalData.push(normalData[(originalOffset * 3) + 1]);\n newNormalData.push(normalData[(originalOffset * 3) + 2]);\n if (uvs && uvs.length) {\n newUVsData.push(uvs[(originalOffset * 2)]);\n newUVsData.push(uvs[(originalOffset * 2) + 1]);\n }\n else if (colorsData && colorsData.length) {\n newColorsData.push(colorsData[(originalOffset * 4)]);\n newColorsData.push(colorsData[(originalOffset * 4) + 1]);\n newColorsData.push(colorsData[(originalOffset * 4) + 2]);\n newColorsData.push(colorsData[(originalOffset * 4) + 3]);\n }\n ++vertexCount;\n });\n }\n }\n var startingIndex = this._reconstructedMesh.getTotalIndices();\n var startingVertex = this._reconstructedMesh.getTotalVertices();\n var submeshesArray = this._reconstructedMesh.subMeshes;\n this._reconstructedMesh.subMeshes = [];\n var newIndicesArray = this._reconstructedMesh.getIndices(); //[];\n var originalIndices = this._mesh.getIndices();\n for (i = 0; i < newTriangles.length; ++i) {\n t = newTriangles[i]; //now get the new referencing point for each vertex\n [0, 1, 2].forEach(function (idx) {\n var id = originalIndices[t.originalOffset + idx];\n var offset = t.vertices[idx].originalOffsets.indexOf(id);\n if (offset < 0)\n offset = 0;\n newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);\n });\n }\n //overwriting the old vertex buffers and indices.\n this._reconstructedMesh.setIndices(newIndicesArray);\n this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);\n this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);\n if (newUVsData.length > 0)\n this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);\n if (newColorsData.length > 0)\n this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);\n //create submesh\n var originalSubmesh = this._mesh.subMeshes[submeshIndex];\n if (submeshIndex > 0) {\n this._reconstructedMesh.subMeshes = [];\n submeshesArray.forEach(function (submesh) {\n BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());\n });\n BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);\n }\n };\n QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {\n this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + \"Decimated\", this._mesh.getScene());\n this._reconstructedMesh.material = this._mesh.material;\n this._reconstructedMesh.parent = this._mesh.parent;\n this._reconstructedMesh.isVisible = false;\n this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;\n };\n QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {\n for (var i = 0; i < vertex1.triangleCount; ++i) {\n var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];\n if (t.deleted)\n continue;\n var s = this.references[vertex1.triangleStart + i].vertexId;\n var v1 = t.vertices[(s + 1) % 3];\n var v2 = t.vertices[(s + 2) % 3];\n if ((v1 === vertex2 || v2 === vertex2)) {\n deletedArray[i] = true;\n delTr.push(t);\n continue;\n }\n var d1 = v1.position.subtract(point);\n d1 = d1.normalize();\n var d2 = v2.position.subtract(point);\n d2 = d2.normalize();\n if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)\n return true;\n var normal = BABYLON.Vector3.Cross(d1, d2).normalize();\n deletedArray[i] = false;\n if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)\n return true;\n }\n return false;\n };\n QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {\n var newDeleted = deletedTriangles;\n for (var i = 0; i < vertex.triangleCount; ++i) {\n var ref = this.references[vertex.triangleStart + i];\n var t = this.triangles[ref.triangleId];\n if (t.deleted)\n continue;\n if (deletedArray[i] && t.deletePending) {\n t.deleted = true;\n newDeleted++;\n continue;\n }\n t.vertices[ref.vertexId] = origVertex;\n t.isDirty = true;\n t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);\n t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);\n t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);\n t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);\n this.references.push(ref);\n }\n return newDeleted;\n };\n QuadraticErrorSimplification.prototype.identifyBorder = function () {\n for (var i = 0; i < this.vertices.length; ++i) {\n var vCount = [];\n var vId = [];\n var v = this.vertices[i];\n var j;\n for (j = 0; j < v.triangleCount; ++j) {\n var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];\n for (var ii = 0; ii < 3; ii++) {\n var ofs = 0;\n var vv = triangle.vertices[ii];\n while (ofs < vCount.length) {\n if (vId[ofs] === vv.id)\n break;\n ++ofs;\n }\n if (ofs === vCount.length) {\n vCount.push(1);\n vId.push(vv.id);\n }\n else {\n vCount[ofs]++;\n }\n }\n }\n for (j = 0; j < vCount.length; ++j) {\n if (vCount[j] === 1) {\n this.vertices[vId[j]].isBorder = true;\n }\n else {\n this.vertices[vId[j]].isBorder = false;\n }\n }\n }\n };\n QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {\n if (identifyBorders === void 0) { identifyBorders = false; }\n var i;\n if (!identifyBorders) {\n var newTrianglesVector = [];\n for (i = 0; i < this.triangles.length; ++i) {\n if (!this.triangles[i].deleted) {\n newTrianglesVector.push(this.triangles[i]);\n }\n }\n this.triangles = newTrianglesVector;\n }\n for (i = 0; i < this.vertices.length; ++i) {\n this.vertices[i].triangleCount = 0;\n this.vertices[i].triangleStart = 0;\n }\n var t;\n var j;\n var v;\n for (i = 0; i < this.triangles.length; ++i) {\n t = this.triangles[i];\n for (j = 0; j < 3; ++j) {\n v = t.vertices[j];\n v.triangleCount++;\n }\n }\n var tStart = 0;\n for (i = 0; i < this.vertices.length; ++i) {\n this.vertices[i].triangleStart = tStart;\n tStart += this.vertices[i].triangleCount;\n this.vertices[i].triangleCount = 0;\n }\n var newReferences = new Array(this.triangles.length * 3);\n for (i = 0; i < this.triangles.length; ++i) {\n t = this.triangles[i];\n for (j = 0; j < 3; ++j) {\n v = t.vertices[j];\n newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);\n v.triangleCount++;\n }\n }\n this.references = newReferences;\n if (identifyBorders) {\n this.identifyBorder();\n }\n };\n QuadraticErrorSimplification.prototype.vertexError = function (q, point) {\n var x = point.x;\n var y = point.y;\n var z = point.z;\n return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y\n + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];\n };\n QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {\n var q = vertex1.q.add(vertex2.q);\n var border = vertex1.isBorder && vertex2.isBorder;\n var error = 0;\n var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);\n if (qDet !== 0 && !border) {\n if (!pointResult) {\n pointResult = BABYLON.Vector3.Zero();\n }\n pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));\n pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));\n pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));\n error = this.vertexError(q, pointResult);\n }\n else {\n var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));\n //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();\n var error1 = this.vertexError(q, vertex1.position);\n var error2 = this.vertexError(q, vertex2.position);\n var error3 = this.vertexError(q, p3);\n error = Math.min(error1, error2, error3);\n if (error === error1) {\n if (pointResult) {\n pointResult.copyFrom(vertex1.position);\n }\n }\n else if (error === error2) {\n if (pointResult) {\n pointResult.copyFrom(vertex2.position);\n }\n }\n else {\n if (pointResult) {\n pointResult.copyFrom(p3);\n }\n }\n }\n return error;\n };\n return QuadraticErrorSimplification;\n }());\n BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.meshSimplification.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var MeshLODLevel = /** @class */ (function () {\n function MeshLODLevel(distance, mesh) {\n this.distance = distance;\n this.mesh = mesh;\n }\n return MeshLODLevel;\n }());\n BABYLON.MeshLODLevel = MeshLODLevel;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.meshLODLevel.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the root class used to create scene optimization to use with SceneOptimizer\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var SceneOptimization = /** @class */ (function () {\n /**\n * Creates the SceneOptimization object\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @param desc defines the description associated with the optimization\n */\n function SceneOptimization(\n /**\n * Defines the priority of this optimization (0 by default which means first in the list)\n */\n priority) {\n if (priority === void 0) { priority = 0; }\n this.priority = priority;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n SceneOptimization.prototype.getDescription = function () {\n return \"\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n SceneOptimization.prototype.apply = function (scene, optimizer) {\n return true;\n };\n ;\n return SceneOptimization;\n }());\n BABYLON.SceneOptimization = SceneOptimization;\n /**\n * Defines an optimization used to reduce the size of render target textures\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var TextureOptimization = /** @class */ (function (_super) {\n __extends(TextureOptimization, _super);\n /**\n * Creates the TextureOptimization object\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter\n * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.\n */\n function TextureOptimization(\n /**\n * Defines the priority of this optimization (0 by default which means first in the list)\n */\n priority, \n /**\n * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter\n */\n maximumSize, \n /**\n * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.\n */\n step) {\n if (priority === void 0) { priority = 0; }\n if (maximumSize === void 0) { maximumSize = 1024; }\n if (step === void 0) { step = 0.5; }\n var _this = _super.call(this, priority) || this;\n _this.priority = priority;\n _this.maximumSize = maximumSize;\n _this.step = step;\n return _this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n TextureOptimization.prototype.getDescription = function () {\n return \"Reducing render target texture size to \" + this.maximumSize;\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n TextureOptimization.prototype.apply = function (scene, optimizer) {\n var allDone = true;\n for (var index = 0; index < scene.textures.length; index++) {\n var texture = scene.textures[index];\n if (!texture.canRescale || texture.getContext) {\n continue;\n }\n var currentSize = texture.getSize();\n var maxDimension = Math.max(currentSize.width, currentSize.height);\n if (maxDimension > this.maximumSize) {\n texture.scale(this.step);\n allDone = false;\n }\n }\n return allDone;\n };\n return TextureOptimization;\n }(SceneOptimization));\n BABYLON.TextureOptimization = TextureOptimization;\n /**\n * Defines an optimization used to increase or decrease the rendering resolution\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var HardwareScalingOptimization = /** @class */ (function (_super) {\n __extends(HardwareScalingOptimization, _super);\n /**\n * Creates the HardwareScalingOptimization object\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @param maximumScale defines the maximum scale to use (2 by default)\n * @param step defines the step to use between two passes (0.5 by default)\n */\n function HardwareScalingOptimization(\n /**\n * Defines the priority of this optimization (0 by default which means first in the list)\n */\n priority, \n /**\n * Defines the maximum scale to use (2 by default)\n */\n maximumScale, \n /**\n * Defines the step to use between two passes (0.5 by default)\n */\n step) {\n if (priority === void 0) { priority = 0; }\n if (maximumScale === void 0) { maximumScale = 2; }\n if (step === void 0) { step = 0.25; }\n var _this = _super.call(this, priority) || this;\n _this.priority = priority;\n _this.maximumScale = maximumScale;\n _this.step = step;\n _this._currentScale = -1;\n _this._directionOffset = 1;\n return _this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n HardwareScalingOptimization.prototype.getDescription = function () {\n return \"Setting hardware scaling level to \" + this._currentScale;\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {\n if (this._currentScale === -1) {\n this._currentScale = scene.getEngine().getHardwareScalingLevel();\n if (this._currentScale > this.maximumScale) {\n this._directionOffset = -1;\n }\n }\n this._currentScale += this._directionOffset * this.step;\n scene.getEngine().setHardwareScalingLevel(this._currentScale);\n return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;\n };\n ;\n return HardwareScalingOptimization;\n }(SceneOptimization));\n BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;\n /**\n * Defines an optimization used to remove shadows\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var ShadowsOptimization = /** @class */ (function (_super) {\n __extends(ShadowsOptimization, _super);\n function ShadowsOptimization() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n ShadowsOptimization.prototype.getDescription = function () {\n return \"Turning shadows on/off\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n ShadowsOptimization.prototype.apply = function (scene, optimizer) {\n scene.shadowsEnabled = optimizer.isInImprovementMode;\n return true;\n };\n ;\n return ShadowsOptimization;\n }(SceneOptimization));\n BABYLON.ShadowsOptimization = ShadowsOptimization;\n /**\n * Defines an optimization used to turn post-processes off\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var PostProcessesOptimization = /** @class */ (function (_super) {\n __extends(PostProcessesOptimization, _super);\n function PostProcessesOptimization() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n PostProcessesOptimization.prototype.getDescription = function () {\n return \"Turning post-processes on/off\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n PostProcessesOptimization.prototype.apply = function (scene, optimizer) {\n scene.postProcessesEnabled = optimizer.isInImprovementMode;\n return true;\n };\n ;\n return PostProcessesOptimization;\n }(SceneOptimization));\n BABYLON.PostProcessesOptimization = PostProcessesOptimization;\n /**\n * Defines an optimization used to turn lens flares off\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var LensFlaresOptimization = /** @class */ (function (_super) {\n __extends(LensFlaresOptimization, _super);\n function LensFlaresOptimization() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n LensFlaresOptimization.prototype.getDescription = function () {\n return \"Turning lens flares on/off\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n LensFlaresOptimization.prototype.apply = function (scene, optimizer) {\n scene.lensFlaresEnabled = optimizer.isInImprovementMode;\n return true;\n };\n ;\n return LensFlaresOptimization;\n }(SceneOptimization));\n BABYLON.LensFlaresOptimization = LensFlaresOptimization;\n /**\n * Defines an optimization based on user defined callback.\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var CustomOptimization = /** @class */ (function (_super) {\n __extends(CustomOptimization, _super);\n function CustomOptimization() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n CustomOptimization.prototype.getDescription = function () {\n if (this.onGetDescription) {\n return this.onGetDescription();\n }\n return \"Running user defined callback\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n CustomOptimization.prototype.apply = function (scene, optimizer) {\n if (this.onApply) {\n return this.onApply(scene, optimizer);\n }\n return true;\n };\n ;\n return CustomOptimization;\n }(SceneOptimization));\n BABYLON.CustomOptimization = CustomOptimization;\n /**\n * Defines an optimization used to turn particles off\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var ParticlesOptimization = /** @class */ (function (_super) {\n __extends(ParticlesOptimization, _super);\n function ParticlesOptimization() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n ParticlesOptimization.prototype.getDescription = function () {\n return \"Turning particles on/off\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n ParticlesOptimization.prototype.apply = function (scene, optimizer) {\n scene.particlesEnabled = optimizer.isInImprovementMode;\n return true;\n };\n ;\n return ParticlesOptimization;\n }(SceneOptimization));\n BABYLON.ParticlesOptimization = ParticlesOptimization;\n /**\n * Defines an optimization used to turn render targets off\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var RenderTargetsOptimization = /** @class */ (function (_super) {\n __extends(RenderTargetsOptimization, _super);\n function RenderTargetsOptimization() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n RenderTargetsOptimization.prototype.getDescription = function () {\n return \"Turning render targets off\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {\n scene.renderTargetsEnabled = optimizer.isInImprovementMode;\n return true;\n };\n ;\n return RenderTargetsOptimization;\n }(SceneOptimization));\n BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;\n /**\n * Defines an optimization used to merge meshes with compatible materials\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var MergeMeshesOptimization = /** @class */ (function (_super) {\n __extends(MergeMeshesOptimization, _super);\n function MergeMeshesOptimization() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this._canBeMerged = function (abstractMesh) {\n if (!(abstractMesh instanceof BABYLON.Mesh)) {\n return false;\n }\n var mesh = abstractMesh;\n if (mesh.isDisposed()) {\n return false;\n }\n if (!mesh.isVisible || !mesh.isEnabled()) {\n return false;\n }\n if (mesh.instances.length > 0) {\n return false;\n }\n if (mesh.skeleton || mesh.hasLODLevels) {\n return false;\n }\n return true;\n };\n return _this;\n }\n Object.defineProperty(MergeMeshesOptimization, \"UpdateSelectionTree\", {\n /**\n * Gets or sets a boolean which defines if optimization octree has to be updated\n */\n get: function () {\n return MergeMeshesOptimization._UpdateSelectionTree;\n },\n /**\n * Gets or sets a boolean which defines if optimization octree has to be updated\n */\n set: function (value) {\n MergeMeshesOptimization._UpdateSelectionTree = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n MergeMeshesOptimization.prototype.getDescription = function () {\n return \"Merging similar meshes together\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @param updateSelectionTree defines that the selection octree has to be updated (false by default)\n * @returns true if everything that can be done was applied\n */\n MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {\n var globalPool = scene.meshes.slice(0);\n var globalLength = globalPool.length;\n for (var index = 0; index < globalLength; index++) {\n var currentPool = new Array();\n var current = globalPool[index];\n // Checks\n if (!this._canBeMerged(current)) {\n continue;\n }\n currentPool.push(current);\n // Find compatible meshes\n for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {\n var otherMesh = globalPool[subIndex];\n if (!this._canBeMerged(otherMesh)) {\n continue;\n }\n if (otherMesh.material !== current.material) {\n continue;\n }\n if (otherMesh.checkCollisions !== current.checkCollisions) {\n continue;\n }\n currentPool.push(otherMesh);\n globalLength--;\n globalPool.splice(subIndex, 1);\n subIndex--;\n }\n if (currentPool.length < 2) {\n continue;\n }\n // Merge meshes\n BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);\n }\n if (updateSelectionTree != undefined) {\n if (updateSelectionTree) {\n scene.createOrUpdateSelectionOctree();\n }\n }\n else if (MergeMeshesOptimization.UpdateSelectionTree) {\n scene.createOrUpdateSelectionOctree();\n }\n return true;\n };\n ;\n MergeMeshesOptimization._UpdateSelectionTree = false;\n return MergeMeshesOptimization;\n }(SceneOptimization));\n BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;\n /**\n * Defines a list of options used by SceneOptimizer\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var SceneOptimizerOptions = /** @class */ (function () {\n /**\n * Creates a new list of options used by SceneOptimizer\n * @param targetFrameRate defines the target frame rate to reach (60 by default)\n * @param trackerDuration defines the interval between two checkes (2000ms by default)\n */\n function SceneOptimizerOptions(\n /**\n * Defines the target frame rate to reach (60 by default)\n */\n targetFrameRate, \n /**\n * Defines the interval between two checkes (2000ms by default)\n */\n trackerDuration) {\n if (targetFrameRate === void 0) { targetFrameRate = 60; }\n if (trackerDuration === void 0) { trackerDuration = 2000; }\n this.targetFrameRate = targetFrameRate;\n this.trackerDuration = trackerDuration;\n /**\n * Gets the list of optimizations to apply\n */\n this.optimizations = new Array();\n }\n /**\n * Add a new optimization\n * @param optimization defines the SceneOptimization to add to the list of active optimizations\n * @returns the current SceneOptimizerOptions\n */\n SceneOptimizerOptions.prototype.addOptimization = function (optimization) {\n this.optimizations.push(optimization);\n return this;\n };\n /**\n * Add a new custom optimization\n * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)\n * @param onGetDescription defines the callback called to get the description attached with the optimization.\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @returns the current SceneOptimizerOptions\n */\n SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {\n if (priority === void 0) { priority = 0; }\n var optimization = new CustomOptimization(priority);\n optimization.onApply = onApply;\n optimization.onGetDescription = onGetDescription;\n this.optimizations.push(optimization);\n return this;\n };\n /**\n * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene\n * @param targetFrameRate defines the target frame rate (60 by default)\n * @returns a SceneOptimizerOptions object\n */\n SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {\n var result = new SceneOptimizerOptions(targetFrameRate);\n var priority = 0;\n result.addOptimization(new MergeMeshesOptimization(priority));\n result.addOptimization(new ShadowsOptimization(priority));\n result.addOptimization(new LensFlaresOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new PostProcessesOptimization(priority));\n result.addOptimization(new ParticlesOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new TextureOptimization(priority, 1024));\n return result;\n };\n /**\n * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual\n * @param targetFrameRate defines the target frame rate (60 by default)\n * @returns a SceneOptimizerOptions object\n */\n SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {\n var result = new SceneOptimizerOptions(targetFrameRate);\n var priority = 0;\n result.addOptimization(new MergeMeshesOptimization(priority));\n result.addOptimization(new ShadowsOptimization(priority));\n result.addOptimization(new LensFlaresOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new PostProcessesOptimization(priority));\n result.addOptimization(new ParticlesOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new TextureOptimization(priority, 512));\n // Next priority\n priority++;\n result.addOptimization(new RenderTargetsOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new HardwareScalingOptimization(priority, 2));\n return result;\n };\n /**\n * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual\n * @param targetFrameRate defines the target frame rate (60 by default)\n * @returns a SceneOptimizerOptions object\n */\n SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {\n var result = new SceneOptimizerOptions(targetFrameRate);\n var priority = 0;\n result.addOptimization(new MergeMeshesOptimization(priority));\n result.addOptimization(new ShadowsOptimization(priority));\n result.addOptimization(new LensFlaresOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new PostProcessesOptimization(priority));\n result.addOptimization(new ParticlesOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new TextureOptimization(priority, 256));\n // Next priority\n priority++;\n result.addOptimization(new RenderTargetsOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new HardwareScalingOptimization(priority, 4));\n return result;\n };\n return SceneOptimizerOptions;\n }());\n BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;\n /**\n * Class used to run optimizations in order to reach a target frame rate\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var SceneOptimizer = /** @class */ (function () {\n /**\n * Creates a new SceneOptimizer\n * @param scene defines the scene to work on\n * @param options defines the options to use with the SceneOptimizer\n * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)\n * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)\n */\n function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {\n if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }\n if (improvementMode === void 0) { improvementMode = false; }\n var _this = this;\n this._isRunning = false;\n this._currentPriorityLevel = 0;\n this._targetFrameRate = 60;\n this._trackerDuration = 2000;\n this._currentFrameRate = 0;\n this._improvementMode = false;\n /**\n * Defines an observable called when the optimizer reaches the target frame rate\n */\n this.onSuccessObservable = new BABYLON.Observable();\n /**\n * Defines an observable called when the optimizer enables an optimization\n */\n this.onNewOptimizationAppliedObservable = new BABYLON.Observable();\n /**\n * Defines an observable called when the optimizer is not able to reach the target frame rate\n */\n this.onFailureObservable = new BABYLON.Observable();\n if (!options) {\n this._options = new SceneOptimizerOptions();\n }\n else {\n this._options = options;\n }\n if (this._options.targetFrameRate) {\n this._targetFrameRate = this._options.targetFrameRate;\n }\n if (this._options.trackerDuration) {\n this._trackerDuration = this._options.trackerDuration;\n }\n if (autoGeneratePriorities) {\n var priority = 0;\n for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {\n var optim = _a[_i];\n optim.priority = priority++;\n }\n }\n this._improvementMode = improvementMode;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {\n _this._sceneDisposeObserver = null;\n _this.dispose();\n });\n }\n Object.defineProperty(SceneOptimizer.prototype, \"isInImprovementMode\", {\n /**\n * Gets a boolean indicating if the optimizer is in improvement mode\n */\n get: function () {\n return this._improvementMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneOptimizer.prototype, \"currentPriorityLevel\", {\n /**\n * Gets the current priority level (0 at start)\n */\n get: function () {\n return this._currentPriorityLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneOptimizer.prototype, \"currentFrameRate\", {\n /**\n * Gets the current frame rate checked by the SceneOptimizer\n */\n get: function () {\n return this._currentFrameRate;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneOptimizer.prototype, \"targetFrameRate\", {\n /**\n * Gets or sets the current target frame rate (60 by default)\n */\n get: function () {\n return this._targetFrameRate;\n },\n /**\n * Gets or sets the current target frame rate (60 by default)\n */\n set: function (value) {\n this._targetFrameRate = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneOptimizer.prototype, \"trackerDuration\", {\n /**\n * Gets or sets the current interval between two checks (every 2000ms by default)\n */\n get: function () {\n return this._trackerDuration;\n },\n /**\n * Gets or sets the current interval between two checks (every 2000ms by default)\n */\n set: function (value) {\n this._trackerDuration = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneOptimizer.prototype, \"optimizations\", {\n /**\n * Gets the list of active optimizations\n */\n get: function () {\n return this._options.optimizations;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Stops the current optimizer\n */\n SceneOptimizer.prototype.stop = function () {\n this._isRunning = false;\n };\n /**\n * Reset the optimizer to initial step (current priority level = 0)\n */\n SceneOptimizer.prototype.reset = function () {\n this._currentPriorityLevel = 0;\n };\n /**\n * Start the optimizer. By default it will try to reach a specific framerate\n * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate\n */\n SceneOptimizer.prototype.start = function () {\n var _this = this;\n if (this._isRunning) {\n return;\n }\n this._isRunning = true;\n // Let's wait for the scene to be ready before running our check\n this._scene.executeWhenReady(function () {\n setTimeout(function () {\n _this._checkCurrentState();\n }, _this._trackerDuration);\n });\n };\n SceneOptimizer.prototype._checkCurrentState = function () {\n var _this = this;\n if (!this._isRunning) {\n return;\n }\n var scene = this._scene;\n var options = this._options;\n this._currentFrameRate = Math.round(scene.getEngine().getFps());\n if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||\n !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {\n this._isRunning = false;\n this.onSuccessObservable.notifyObservers(this);\n return;\n }\n // Apply current level of optimizations\n var allDone = true;\n var noOptimizationApplied = true;\n for (var index = 0; index < options.optimizations.length; index++) {\n var optimization = options.optimizations[index];\n if (optimization.priority === this._currentPriorityLevel) {\n noOptimizationApplied = false;\n allDone = allDone && optimization.apply(scene, this);\n this.onNewOptimizationAppliedObservable.notifyObservers(optimization);\n }\n }\n // If no optimization was applied, this is a failure :(\n if (noOptimizationApplied) {\n this._isRunning = false;\n this.onFailureObservable.notifyObservers(this);\n return;\n }\n // If all optimizations were done, move to next level\n if (allDone) {\n this._currentPriorityLevel++;\n }\n // Let's the system running for a specific amount of time before checking FPS\n scene.executeWhenReady(function () {\n setTimeout(function () {\n _this._checkCurrentState();\n }, _this._trackerDuration);\n });\n };\n /**\n * Release all resources\n */\n SceneOptimizer.prototype.dispose = function () {\n this.stop();\n this.onSuccessObservable.clear();\n this.onFailureObservable.clear();\n this.onNewOptimizationAppliedObservable.clear();\n if (this._sceneDisposeObserver) {\n this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);\n }\n };\n /**\n * Helper function to create a SceneOptimizer with one single line of code\n * @param scene defines the scene to work on\n * @param options defines the options to use with the SceneOptimizer\n * @param onSuccess defines a callback to call on success\n * @param onFailure defines a callback to call on failure\n * @returns the new SceneOptimizer object\n */\n SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {\n var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);\n if (onSuccess) {\n optimizer.onSuccessObservable.add(function () {\n onSuccess();\n });\n }\n if (onFailure) {\n optimizer.onFailureObservable.add(function () {\n onFailure();\n });\n }\n optimizer.start();\n return optimizer;\n };\n return SceneOptimizer;\n }());\n BABYLON.SceneOptimizer = SceneOptimizer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sceneOptimizer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var OutlineRenderer = /** @class */ (function () {\n function OutlineRenderer(scene) {\n this.zOffset = 1;\n this._scene = scene;\n }\n OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {\n var _this = this;\n if (useOverlay === void 0) { useOverlay = false; }\n var scene = this._scene;\n var engine = this._scene.getEngine();\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);\n if (!this.isReady(subMesh, hardwareInstancedRendering)) {\n return;\n }\n var mesh = subMesh.getRenderingMesh();\n var material = subMesh.getMaterial();\n if (!material || !scene.activeCamera) {\n return;\n }\n engine.enableEffect(this._effect);\n // Logarithmic depth\n if (material.useLogarithmicDepth) {\n this._effect.setFloat(\"logarithmicDepthConstant\", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));\n }\n this._effect.setFloat(\"offset\", useOverlay ? 0 : mesh.outlineWidth);\n this._effect.setColor4(\"color\", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);\n this._effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n this._effect.setMatrices(\"mBones\", mesh.skeleton.getTransformMatrices(mesh));\n }\n mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n this._effect.setTexture(\"diffuseSampler\", alphaTexture);\n this._effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n engine.setZOffset(-this.zOffset);\n mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix(\"world\", world); });\n engine.setZOffset(0);\n };\n OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {\n var defines = [];\n var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];\n var mesh = subMesh.getMesh();\n var material = subMesh.getMaterial();\n if (material) {\n // Alpha test\n if (material.needAlphaTesting()) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n //Logarithmic depth\n if (material.useLogarithmicDepth) {\n defines.push(\"#define LOGARITHMICDEPTH\");\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n // Get correct effect \n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n this._effect = this._scene.getEngine().createEffect(\"outline\", attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\", \"offset\", \"color\", \"logarithmicDepthConstant\"], [\"diffuseSampler\"], join);\n }\n return this._effect.isReady();\n };\n return OutlineRenderer;\n }());\n BABYLON.OutlineRenderer = OutlineRenderer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.outlineRenderer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var FaceAdjacencies = /** @class */ (function () {\n function FaceAdjacencies() {\n this.edges = new Array();\n this.edgesConnectedCount = 0;\n }\n return FaceAdjacencies;\n }());\n var EdgesRenderer = /** @class */ (function () {\n // Beware when you use this class with complex objects as the adjacencies computation can be really long\n function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {\n if (epsilon === void 0) { epsilon = 0.95; }\n if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }\n this.edgesWidthScalerForOrthographic = 1000.0;\n this.edgesWidthScalerForPerspective = 50.0;\n this._linesPositions = new Array();\n this._linesNormals = new Array();\n this._linesIndices = new Array();\n this._buffers = {};\n this._checkVerticesInsteadOfIndices = false;\n /** Gets or sets a boolean indicating if the edgesRenderer is active */\n this.isEnabled = true;\n this._source = source;\n this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;\n this._epsilon = epsilon;\n this._prepareRessources();\n this._generateEdgesLines();\n }\n EdgesRenderer.prototype._prepareRessources = function () {\n if (this._lineShader) {\n return;\n }\n this._lineShader = new BABYLON.ShaderMaterial(\"lineShader\", this._source.getScene(), \"line\", {\n attributes: [\"position\", \"normal\"],\n uniforms: [\"worldViewProjection\", \"color\", \"width\", \"aspectRatio\"]\n });\n this._lineShader.disableDepthWrite = true;\n this._lineShader.backFaceCulling = false;\n };\n EdgesRenderer.prototype._rebuild = function () {\n var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];\n if (buffer) {\n buffer._rebuild();\n }\n buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];\n if (buffer) {\n buffer._rebuild();\n }\n var scene = this._source.getScene();\n var engine = scene.getEngine();\n this._ib = engine.createIndexBuffer(this._linesIndices);\n };\n EdgesRenderer.prototype.dispose = function () {\n var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];\n if (buffer) {\n buffer.dispose();\n this._buffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];\n if (buffer) {\n buffer.dispose();\n this._buffers[BABYLON.VertexBuffer.NormalKind] = null;\n }\n this._source.getScene().getEngine()._releaseBuffer(this._ib);\n this._lineShader.dispose();\n };\n EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {\n if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {\n return 0;\n }\n if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {\n return 1;\n }\n if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {\n return 2;\n }\n return -1;\n };\n EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {\n if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {\n return 0;\n }\n if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {\n return 1;\n }\n if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {\n return 2;\n }\n return -1;\n };\n EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {\n var needToCreateLine;\n if (edge === undefined) {\n needToCreateLine = true;\n }\n else {\n var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);\n needToCreateLine = dotProduct < this._epsilon;\n }\n if (needToCreateLine) {\n var offset = this._linesPositions.length / 3;\n var normal = p0.subtract(p1);\n normal.normalize();\n // Positions\n this._linesPositions.push(p0.x);\n this._linesPositions.push(p0.y);\n this._linesPositions.push(p0.z);\n this._linesPositions.push(p0.x);\n this._linesPositions.push(p0.y);\n this._linesPositions.push(p0.z);\n this._linesPositions.push(p1.x);\n this._linesPositions.push(p1.y);\n this._linesPositions.push(p1.z);\n this._linesPositions.push(p1.x);\n this._linesPositions.push(p1.y);\n this._linesPositions.push(p1.z);\n // Normals\n this._linesNormals.push(p1.x);\n this._linesNormals.push(p1.y);\n this._linesNormals.push(p1.z);\n this._linesNormals.push(-1);\n this._linesNormals.push(p1.x);\n this._linesNormals.push(p1.y);\n this._linesNormals.push(p1.z);\n this._linesNormals.push(1);\n this._linesNormals.push(p0.x);\n this._linesNormals.push(p0.y);\n this._linesNormals.push(p0.z);\n this._linesNormals.push(-1);\n this._linesNormals.push(p0.x);\n this._linesNormals.push(p0.y);\n this._linesNormals.push(p0.z);\n this._linesNormals.push(1);\n // Indices\n this._linesIndices.push(offset);\n this._linesIndices.push(offset + 1);\n this._linesIndices.push(offset + 2);\n this._linesIndices.push(offset);\n this._linesIndices.push(offset + 2);\n this._linesIndices.push(offset + 3);\n }\n };\n EdgesRenderer.prototype._generateEdgesLines = function () {\n var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var indices = this._source.getIndices();\n if (!indices || !positions) {\n return;\n }\n // First let's find adjacencies\n var adjacencies = new Array();\n var faceNormals = new Array();\n var index;\n var faceAdjacencies;\n // Prepare faces\n for (index = 0; index < indices.length; index += 3) {\n faceAdjacencies = new FaceAdjacencies();\n var p0Index = indices[index];\n var p1Index = indices[index + 1];\n var p2Index = indices[index + 2];\n faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);\n faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);\n faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);\n var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));\n faceNormal.normalize();\n faceNormals.push(faceNormal);\n adjacencies.push(faceAdjacencies);\n }\n // Scan\n for (index = 0; index < adjacencies.length; index++) {\n faceAdjacencies = adjacencies[index];\n for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {\n var otherFaceAdjacencies = adjacencies[otherIndex];\n if (faceAdjacencies.edgesConnectedCount === 3) { // Full\n break;\n }\n if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full\n continue;\n }\n var otherP0 = indices[otherIndex * 3];\n var otherP1 = indices[otherIndex * 3 + 1];\n var otherP2 = indices[otherIndex * 3 + 2];\n for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {\n var otherEdgeIndex = 0;\n if (faceAdjacencies.edges[edgeIndex] !== undefined) {\n continue;\n }\n switch (edgeIndex) {\n case 0:\n if (this._checkVerticesInsteadOfIndices) {\n otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);\n }\n else {\n otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);\n }\n break;\n case 1:\n if (this._checkVerticesInsteadOfIndices) {\n otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);\n }\n else {\n otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);\n }\n break;\n case 2:\n if (this._checkVerticesInsteadOfIndices) {\n otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);\n }\n else {\n otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);\n }\n break;\n }\n if (otherEdgeIndex === -1) {\n continue;\n }\n faceAdjacencies.edges[edgeIndex] = otherIndex;\n otherFaceAdjacencies.edges[otherEdgeIndex] = index;\n faceAdjacencies.edgesConnectedCount++;\n otherFaceAdjacencies.edgesConnectedCount++;\n if (faceAdjacencies.edgesConnectedCount === 3) {\n break;\n }\n }\n }\n }\n // Create lines\n for (index = 0; index < adjacencies.length; index++) {\n // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon\n var current = adjacencies[index];\n this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);\n this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);\n this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);\n }\n // Merge into a single mesh\n var engine = this._source.getScene().getEngine();\n this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);\n this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);\n this._ib = engine.createIndexBuffer(this._linesIndices);\n this._indicesCount = this._linesIndices.length;\n };\n EdgesRenderer.prototype.render = function () {\n var scene = this._source.getScene();\n if (!this._lineShader.isReady() || !scene.activeCamera) {\n return;\n }\n var engine = scene.getEngine();\n this._lineShader._preBind();\n // VBOs\n engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());\n scene.resetCachedMaterial();\n this._lineShader.setColor4(\"color\", this._source.edgesColor);\n if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {\n this._lineShader.setFloat(\"width\", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);\n }\n else {\n this._lineShader.setFloat(\"width\", this._source.edgesWidth / this.edgesWidthScalerForPerspective);\n }\n this._lineShader.setFloat(\"aspectRatio\", engine.getAspectRatio(scene.activeCamera));\n this._lineShader.bind(this._source.getWorldMatrix());\n // Draw order\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);\n this._lineShader.unbind();\n engine.setDepthWrite(true);\n };\n return EdgesRenderer;\n }());\n BABYLON.EdgesRenderer = EdgesRenderer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.edgesRenderer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n // Adds the parser to the scene parsers.\n BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {\n if (parsedData.effectLayers) {\n for (var index = 0; index < parsedData.effectLayers.length; index++) {\n var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);\n container.effectLayers.push(effectLayer);\n }\n }\n });\n BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {\n var index = this.effectLayers.indexOf(toRemove);\n if (index !== -1) {\n this.effectLayers.splice(index, 1);\n }\n return index;\n };\n BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {\n this.effectLayers.push(newEffectLayer);\n };\n /**\n * Defines the layer scene component responsible to manage any effect layers\n * in a given scene.\n */\n var EffectLayerSceneComponent = /** @class */ (function () {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n function EffectLayerSceneComponent(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;\n this._renderEffects = false;\n this._needStencil = false;\n this._previousStencilState = false;\n this.scene = scene;\n this._engine = scene.getEngine();\n scene.effectLayers = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n EffectLayerSceneComponent.prototype.register = function () {\n this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);\n this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);\n this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);\n this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);\n this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);\n this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);\n };\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n EffectLayerSceneComponent.prototype.rebuild = function () {\n var layers = this.scene.effectLayers;\n for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {\n var effectLayer = layers_1[_i];\n effectLayer._rebuild();\n }\n };\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {\n // Effect layers\n serializationObject.effectLayers = [];\n var layers = this.scene.effectLayers;\n for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {\n var effectLayer = layers_2[_i];\n if (effectLayer.serialize) {\n serializationObject.effectLayers.push(effectLayer.serialize());\n }\n }\n };\n /**\n * Adds all the element from the container to the scene\n * @param container the container holding the elements\n */\n EffectLayerSceneComponent.prototype.addFromContainer = function (container) {\n var _this = this;\n if (!container.effectLayers) {\n return;\n }\n container.effectLayers.forEach(function (o) {\n _this.scene.addEffectLayer(o);\n });\n };\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n */\n EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {\n var _this = this;\n if (!container.effectLayers) {\n return;\n }\n container.effectLayers.forEach(function (o) {\n _this.scene.removeEffectLayer(o);\n });\n };\n /**\n * Disposes the component and the associated ressources.\n */\n EffectLayerSceneComponent.prototype.dispose = function () {\n var layers = this.scene.effectLayers;\n while (layers.length) {\n layers[0].dispose();\n }\n };\n EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {\n var layers = this.scene.effectLayers;\n for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {\n var layer = layers_3[_i];\n if (!layer.hasMesh(mesh)) {\n continue;\n }\n for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {\n var subMesh = _b[_a];\n if (!layer.isReady(subMesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n return true;\n };\n EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {\n this._renderEffects = false;\n this._needStencil = false;\n var layers = this.scene.effectLayers;\n if (layers && layers.length > 0) {\n this._previousStencilState = this._engine.getStencilBuffer();\n for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {\n var effectLayer = layers_4[_i];\n if (effectLayer.shouldRender() &&\n (!effectLayer.camera ||\n (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||\n (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {\n this._renderEffects = true;\n this._needStencil = this._needStencil || effectLayer.needStencil();\n var renderTarget = effectLayer._mainTexture;\n if (renderTarget._shouldRender()) {\n this.scene.incrementRenderId();\n renderTarget.render(false, false);\n }\n }\n }\n this.scene.incrementRenderId();\n }\n };\n EffectLayerSceneComponent.prototype._setStencil = function (camera) {\n // Activate effect Layer stencil\n if (this._needStencil) {\n this._engine.setStencilBuffer(true);\n }\n };\n EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {\n // Restore effect Layer stencil\n if (this._needStencil) {\n this._engine.setStencilBuffer(this._previousStencilState);\n }\n };\n EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {\n if (this._renderEffects) {\n this._engine.setDepthBuffer(false);\n var layers = this.scene.effectLayers;\n for (var i = 0; i < layers.length; i++) {\n var effectLayer = layers[i];\n if (effectLayer.renderingGroupId === renderingGroupId) {\n if (effectLayer.shouldRender()) {\n effectLayer.render();\n }\n }\n }\n this._engine.setDepthBuffer(true);\n }\n };\n EffectLayerSceneComponent.prototype._drawCamera = function (camera) {\n if (this._renderEffects) {\n this._draw(-1);\n }\n };\n EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {\n if (!this.scene._isInIntermediateRendering() && this._renderEffects) {\n this._draw(index);\n }\n };\n return EffectLayerSceneComponent;\n }());\n BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.effectLayerSceneComponent.js.map\n\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The effect layer Helps adding post process effect blended with the main pass.\n *\n * This can be for instance use to generate glow or higlight effects on the scene.\n *\n * The effect layer class can not be used directly and is intented to inherited from to be\n * customized per effects.\n */\n var EffectLayer = /** @class */ (function () {\n /**\n * Instantiates a new effect Layer and references it in the scene.\n * @param name The name of the layer\n * @param scene The scene to use the layer in\n */\n function EffectLayer(\n /** The Friendly of the effect in the scene */\n name, scene) {\n this._vertexBuffers = {};\n this._maxSize = 0;\n this._mainTextureDesiredSize = { width: 0, height: 0 };\n this._shouldRender = true;\n this._postProcesses = [];\n this._textures = [];\n this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };\n /**\n * The clear color of the texture used to generate the glow map.\n */\n this.neutralColor = new BABYLON.Color4();\n /**\n * Specifies wether the highlight layer is enabled or not.\n */\n this.isEnabled = true;\n /**\n * An event triggered when the effect layer has been disposed.\n */\n this.onDisposeObservable = new BABYLON.Observable();\n /**\n * An event triggered when the effect layer is about rendering the main texture with the glowy parts.\n */\n this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();\n /**\n * An event triggered when the generated texture is being merged in the scene.\n */\n this.onBeforeComposeObservable = new BABYLON.Observable();\n /**\n * An event triggered when the generated texture has been merged in the scene.\n */\n this.onAfterComposeObservable = new BABYLON.Observable();\n /**\n * An event triggered when the efffect layer changes its size.\n */\n this.onSizeChangedObservable = new BABYLON.Observable();\n this.name = name;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);\n if (!component) {\n component = new BABYLON.EffectLayerSceneComponent(this._scene);\n this._scene._addComponent(component);\n }\n this._engine = this._scene.getEngine();\n this._maxSize = this._engine.getCaps().maxTextureSize;\n this._scene.effectLayers.push(this);\n // Generate Buffers\n this._generateIndexBuffer();\n this._genrateVertexBuffer();\n }\n Object.defineProperty(EffectLayer.prototype, \"camera\", {\n /**\n * Gets the camera attached to the layer.\n */\n get: function () {\n return this._effectLayerOptions.camera;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EffectLayer.prototype, \"renderingGroupId\", {\n /**\n * Gets the rendering group id the layer should render in.\n */\n get: function () {\n return this._effectLayerOptions.renderingGroupId;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Initializes the effect layer with the required options.\n * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)\n */\n EffectLayer.prototype._init = function (options) {\n // Adapt options\n this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);\n this._setMainTextureSize();\n this._createMainTexture();\n this._createTextureAndPostProcesses();\n this._mergeEffect = this._createMergeEffect();\n };\n /**\n * Generates the index buffer of the full screen quad blending to the main canvas.\n */\n EffectLayer.prototype._generateIndexBuffer = function () {\n // Indices\n var indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = this._engine.createIndexBuffer(indices);\n };\n /**\n * Generates the vertex buffer of the full screen quad blending to the main canvas.\n */\n EffectLayer.prototype._genrateVertexBuffer = function () {\n // VBO\n var vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;\n };\n /**\n * Sets the main texture desired size which is the closest power of two\n * of the engine canvas size.\n */\n EffectLayer.prototype._setMainTextureSize = function () {\n if (this._effectLayerOptions.mainTextureFixedSize) {\n this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;\n this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;\n }\n else {\n this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;\n this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;\n this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;\n this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;\n }\n this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);\n this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);\n };\n /**\n * Creates the main texture for the effect layer.\n */\n EffectLayer.prototype._createMainTexture = function () {\n var _this = this;\n this._mainTexture = new BABYLON.RenderTargetTexture(\"HighlightLayerMainRTT\", {\n width: this._mainTextureDesiredSize.width,\n height: this._mainTextureDesiredSize.height\n }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this._mainTexture.activeCamera = this._effectLayerOptions.camera;\n this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._mainTexture.anisotropicFilteringLevel = 1;\n this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n this._mainTexture.renderParticles = false;\n this._mainTexture.renderList = null;\n this._mainTexture.ignoreCameraViewport = true;\n // Custom render function\n this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {\n _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);\n var index;\n var engine = _this._scene.getEngine();\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n _this._renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n _this._renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n _this._renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n for (index = 0; index < transparentSubMeshes.length; index++) {\n _this._renderSubMesh(transparentSubMeshes.data[index]);\n }\n };\n this._mainTexture.onClearObservable.add(function (engine) {\n engine.clear(_this.neutralColor, true, true, true);\n });\n };\n /**\n * Checks for the readiness of the element composing the layer.\n * @param subMesh the mesh to check for\n * @param useInstances specify wether or not to use instances to render the mesh\n * @param emissiveTexture the associated emissive texture used to generate the glow\n * @return true if ready otherwise, false\n */\n EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {\n var material = subMesh.getMaterial();\n if (!material) {\n return false;\n }\n if (!material.isReady(subMesh.getMesh(), useInstances)) {\n return false;\n }\n var defines = [];\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n var mesh = subMesh.getMesh();\n var uv1 = false;\n var uv2 = false;\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&\n alphaTexture.coordinatesIndex === 1) {\n defines.push(\"#define DIFFUSEUV2\");\n uv2 = true;\n }\n else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n defines.push(\"#define DIFFUSEUV1\");\n uv1 = true;\n }\n }\n }\n // Emissive\n if (emissiveTexture) {\n defines.push(\"#define EMISSIVE\");\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&\n emissiveTexture.coordinatesIndex === 1) {\n defines.push(\"#define EMISSIVEUV2\");\n uv2 = true;\n }\n else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n defines.push(\"#define EMISSIVEUV1\");\n uv1 = true;\n }\n }\n if (uv1) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (uv2) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets \n var manager = mesh.morphTargetManager;\n var morphInfluencers = 0;\n if (manager) {\n if (manager.numInfluencers > 0) {\n defines.push(\"#define MORPHTARGETS\");\n morphInfluencers = manager.numInfluencers;\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + morphInfluencers);\n BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { \"NUM_MORPH_INFLUENCERS\": morphInfluencers });\n }\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n // Get correct effect\n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect(\"glowMapGeneration\", attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\", \"color\", \"emissiveMatrix\", \"morphTargetInfluences\"], [\"diffuseSampler\", \"emissiveSampler\"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });\n }\n return this._effectLayerMapGenerationEffect.isReady();\n };\n /**\n * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.\n */\n EffectLayer.prototype.render = function () {\n var currentEffect = this._mergeEffect;\n // Check\n if (!currentEffect.isReady())\n return;\n for (var i = 0; i < this._postProcesses.length; i++) {\n if (!this._postProcesses[i].isReady()) {\n return;\n }\n }\n var engine = this._scene.getEngine();\n this.onBeforeComposeObservable.notifyObservers(this);\n // Render\n engine.enableEffect(currentEffect);\n engine.setState(false);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);\n // Cache\n var previousAlphaMode = engine.getAlphaMode();\n // Go Blend.\n engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);\n // Blends the map on the main canvas.\n this._internalRender(currentEffect);\n // Restore Alpha\n engine.setAlphaMode(previousAlphaMode);\n this.onAfterComposeObservable.notifyObservers(this);\n // Handle size changes.\n var size = this._mainTexture.getSize();\n this._setMainTextureSize();\n if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {\n // Recreate RTT and post processes on size change.\n this.onSizeChangedObservable.notifyObservers(this);\n this._disposeTextureAndPostProcesses();\n this._createMainTexture();\n this._createTextureAndPostProcesses();\n }\n };\n /**\n * Determine if a given mesh will be used in the current effect.\n * @param mesh mesh to test\n * @returns true if the mesh will be used\n */\n EffectLayer.prototype.hasMesh = function (mesh) {\n if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {\n return true;\n }\n return false;\n };\n /**\n * Returns true if the layer contains information to display, otherwise false.\n * @returns true if the glow layer should be rendered\n */\n EffectLayer.prototype.shouldRender = function () {\n return this.isEnabled && this._shouldRender;\n };\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n EffectLayer.prototype._shouldRenderMesh = function (mesh) {\n return true;\n };\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {\n return true;\n };\n /**\n * Renders the submesh passed in parameter to the generation map.\n */\n EffectLayer.prototype._renderSubMesh = function (subMesh) {\n var _this = this;\n if (!this.shouldRender()) {\n return;\n }\n var material = subMesh.getMaterial();\n var mesh = subMesh.getRenderingMesh();\n var scene = this._scene;\n var engine = scene.getEngine();\n if (!material) {\n return;\n }\n // Do not block in blend mode.\n if (material.needAlphaBlendingForMesh(mesh)) {\n return;\n }\n // Culling\n engine.setState(material.backFaceCulling);\n // Managing instances\n var batch = mesh._getInstancesRenderList(subMesh._id);\n if (batch.mustReturn) {\n return;\n }\n // Early Exit per mesh\n if (!this._shouldRenderMesh(mesh)) {\n return;\n }\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);\n this._setEmissiveTextureAndColor(mesh, subMesh, material);\n if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {\n engine.enableEffect(this._effectLayerMapGenerationEffect);\n mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);\n this._effectLayerMapGenerationEffect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n this._effectLayerMapGenerationEffect.setFloat4(\"color\", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n this._effectLayerMapGenerationEffect.setTexture(\"diffuseSampler\", alphaTexture);\n var textureMatrix = alphaTexture.getTextureMatrix();\n if (textureMatrix) {\n this._effectLayerMapGenerationEffect.setMatrix(\"diffuseMatrix\", textureMatrix);\n }\n }\n }\n // Glow emissive only\n if (this._emissiveTextureAndColor.texture) {\n this._effectLayerMapGenerationEffect.setTexture(\"emissiveSampler\", this._emissiveTextureAndColor.texture);\n this._effectLayerMapGenerationEffect.setMatrix(\"emissiveMatrix\", this._emissiveTextureAndColor.texture.getTextureMatrix());\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n this._effectLayerMapGenerationEffect.setMatrices(\"mBones\", mesh.skeleton.getTransformMatrices(mesh));\n }\n // Morph targets\n BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);\n // Draw\n mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix(\"world\", world); });\n }\n else {\n // Need to reset refresh rate of the main map\n this._mainTexture.resetRefreshCounter();\n }\n };\n /**\n * Rebuild the required buffers.\n * @hidden Internal use only.\n */\n EffectLayer.prototype._rebuild = function () {\n var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._generateIndexBuffer();\n };\n /**\n * Dispose only the render target textures and post process.\n */\n EffectLayer.prototype._disposeTextureAndPostProcesses = function () {\n this._mainTexture.dispose();\n for (var i = 0; i < this._postProcesses.length; i++) {\n if (this._postProcesses[i]) {\n this._postProcesses[i].dispose();\n }\n }\n this._postProcesses = [];\n for (var i = 0; i < this._textures.length; i++) {\n if (this._textures[i]) {\n this._textures[i].dispose();\n }\n }\n this._textures = [];\n };\n /**\n * Dispose the highlight layer and free resources.\n */\n EffectLayer.prototype.dispose = function () {\n var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n // Clean textures and post processes\n this._disposeTextureAndPostProcesses();\n // Remove from scene\n var index = this._scene.effectLayers.indexOf(this, 0);\n if (index > -1) {\n this._scene.effectLayers.splice(index, 1);\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onBeforeRenderMainTextureObservable.clear();\n this.onBeforeComposeObservable.clear();\n this.onAfterComposeObservable.clear();\n this.onSizeChangedObservable.clear();\n };\n /**\n * Gets the class name of the effect layer\n * @returns the string with the class name of the effect layer\n */\n EffectLayer.prototype.getClassName = function () {\n return \"EffectLayer\";\n };\n /**\n * Creates an effect layer from parsed effect layer data\n * @param parsedEffectLayer defines effect layer data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing the effect layer information\n * @returns a parsed effect Layer\n */\n EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {\n var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);\n return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);\n };\n __decorate([\n BABYLON.serialize()\n ], EffectLayer.prototype, \"name\", void 0);\n __decorate([\n BABYLON.serializeAsColor4()\n ], EffectLayer.prototype, \"neutralColor\", void 0);\n __decorate([\n BABYLON.serialize()\n ], EffectLayer.prototype, \"isEnabled\", void 0);\n __decorate([\n BABYLON.serializeAsCameraReference()\n ], EffectLayer.prototype, \"camera\", null);\n __decorate([\n BABYLON.serialize()\n ], EffectLayer.prototype, \"renderingGroupId\", null);\n return EffectLayer;\n }());\n BABYLON.EffectLayer = EffectLayer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.effectLayer.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {\n for (var index = 0; index < this.effectLayers.length; index++) {\n if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {\n return this.effectLayers[index];\n }\n }\n return null;\n };\n /**\n * Special Glow Blur post process only blurring the alpha channel\n * It enforces keeping the most luminous color in the color channel.\n */\n var GlowBlurPostProcess = /** @class */ (function (_super) {\n __extends(GlowBlurPostProcess, _super);\n function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }\n var _this = _super.call(this, name, \"glowBlurPostProcess\", [\"screenSize\", \"direction\", \"blurWidth\"], null, options, camera, samplingMode, engine, reusable) || this;\n _this.direction = direction;\n _this.kernel = kernel;\n _this.onApplyObservable.add(function (effect) {\n effect.setFloat2(\"screenSize\", _this.width, _this.height);\n effect.setVector2(\"direction\", _this.direction);\n effect.setFloat(\"blurWidth\", _this.kernel);\n });\n return _this;\n }\n return GlowBlurPostProcess;\n }(BABYLON.PostProcess));\n /**\n * The highlight layer Helps adding a glow effect around a mesh.\n *\n * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove\n * glowy meshes to your scene.\n *\n * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!\n */\n var HighlightLayer = /** @class */ (function (_super) {\n __extends(HighlightLayer, _super);\n /**\n * Instantiates a new highlight Layer and references it to the scene..\n * @param name The name of the layer\n * @param scene The scene to use the layer in\n * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)\n */\n function HighlightLayer(name, scene, options) {\n var _this = _super.call(this, name, scene) || this;\n _this.name = name;\n /**\n * Specifies whether or not the inner glow is ACTIVE in the layer.\n */\n _this.innerGlow = true;\n /**\n * Specifies whether or not the outer glow is ACTIVE in the layer.\n */\n _this.outerGlow = true;\n /**\n * An event triggered when the highlight layer is being blurred.\n */\n _this.onBeforeBlurObservable = new BABYLON.Observable();\n /**\n * An event triggered when the highlight layer has been blurred.\n */\n _this.onAfterBlurObservable = new BABYLON.Observable();\n _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;\n _this._meshes = {};\n _this._excludedMeshes = {};\n _this.neutralColor = HighlightLayer.NeutralColor;\n // Warn on stencil\n if (!_this._engine.isStencilEnable) {\n BABYLON.Tools.Warn(\"Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }\");\n }\n // Adapt options\n _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);\n // Initialize the layer\n _this._init({\n alphaBlendingMode: _this._options.alphaBlendingMode,\n camera: _this._options.camera,\n mainTextureFixedSize: _this._options.mainTextureFixedSize,\n mainTextureRatio: _this._options.mainTextureRatio,\n renderingGroupId: _this._options.renderingGroupId\n });\n // Do not render as long as no meshes have been added\n _this._shouldRender = false;\n return _this;\n }\n Object.defineProperty(HighlightLayer.prototype, \"blurHorizontalSize\", {\n /**\n * Gets the horizontal size of the blur.\n */\n get: function () {\n return this._horizontalBlurPostprocess.kernel;\n },\n /**\n * Specifies the horizontal size of the blur.\n */\n set: function (value) {\n this._horizontalBlurPostprocess.kernel = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(HighlightLayer.prototype, \"blurVerticalSize\", {\n /**\n * Gets the vertical size of the blur.\n */\n get: function () {\n return this._verticalBlurPostprocess.kernel;\n },\n /**\n * Specifies the vertical size of the blur.\n */\n set: function (value) {\n this._verticalBlurPostprocess.kernel = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Get the effect name of the layer.\n * @return The effect name\n */\n HighlightLayer.prototype.getEffectName = function () {\n return HighlightLayer.EffectName;\n };\n /**\n * Create the merge effect. This is the shader use to blit the information back\n * to the main canvas at the end of the scene rendering.\n */\n HighlightLayer.prototype._createMergeEffect = function () {\n // Effect\n return this._engine.createEffect(\"glowMapMerge\", [BABYLON.VertexBuffer.PositionKind], [\"offset\"], [\"textureSampler\"], this._options.isStroke ? \"#define STROKE \\n\" : undefined);\n };\n /**\n * Creates the render target textures and post processes used in the highlight layer.\n */\n HighlightLayer.prototype._createTextureAndPostProcesses = function () {\n var _this = this;\n var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;\n var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;\n blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;\n blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;\n var textureType = 0;\n if (this._engine.getCaps().textureHalfFloatRender) {\n textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else {\n textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n this._blurTexture = new BABYLON.RenderTargetTexture(\"HighlightLayerBlurRTT\", {\n width: blurTextureWidth,\n height: blurTextureHeight\n }, this._scene, false, true, textureType);\n this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._blurTexture.anisotropicFilteringLevel = 16;\n this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);\n this._blurTexture.renderParticles = false;\n this._blurTexture.ignoreCameraViewport = true;\n this._textures = [this._blurTexture];\n if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {\n this._downSamplePostprocess = new BABYLON.PassPostProcess(\"HighlightLayerPPP\", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());\n this._downSamplePostprocess.onApplyObservable.add(function (effect) {\n effect.setTexture(\"textureSampler\", _this._mainTexture);\n });\n this._horizontalBlurPostprocess = new GlowBlurPostProcess(\"HighlightLayerHBP\", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());\n this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {\n effect.setFloat2(\"screenSize\", blurTextureWidth, blurTextureHeight);\n });\n this._verticalBlurPostprocess = new GlowBlurPostProcess(\"HighlightLayerVBP\", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());\n this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {\n effect.setFloat2(\"screenSize\", blurTextureWidth, blurTextureHeight);\n });\n this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];\n }\n else {\n this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess(\"HighlightLayerHBP\", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {\n width: blurTextureWidth,\n height: blurTextureHeight\n }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess.width = blurTextureWidth;\n this._horizontalBlurPostprocess.height = blurTextureHeight;\n this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {\n effect.setTexture(\"textureSampler\", _this._mainTexture);\n });\n this._verticalBlurPostprocess = new BABYLON.BlurPostProcess(\"HighlightLayerVBP\", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {\n width: blurTextureWidth,\n height: blurTextureHeight\n }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];\n }\n this._mainTexture.onAfterUnbindObservable.add(function () {\n _this.onBeforeBlurObservable.notifyObservers(_this);\n var internalTexture = _this._blurTexture.getInternalTexture();\n if (internalTexture) {\n _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);\n }\n _this.onAfterBlurObservable.notifyObservers(_this);\n });\n // Prevent autoClear.\n this._postProcesses.map(function (pp) { pp.autoClear = false; });\n };\n /**\n * Returns wether or nood the layer needs stencil enabled during the mesh rendering.\n */\n HighlightLayer.prototype.needStencil = function () {\n return true;\n };\n /**\n * Checks for the readiness of the element composing the layer.\n * @param subMesh the mesh to check for\n * @param useInstances specify wether or not to use instances to render the mesh\n * @param emissiveTexture the associated emissive texture used to generate the glow\n * @return true if ready otherwise, false\n */\n HighlightLayer.prototype.isReady = function (subMesh, useInstances) {\n var material = subMesh.getMaterial();\n var mesh = subMesh.getRenderingMesh();\n if (!material || !mesh || !this._meshes) {\n return false;\n }\n var emissiveTexture = null;\n var highlightLayerMesh = this._meshes[mesh.uniqueId];\n if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {\n emissiveTexture = material.emissiveTexture;\n }\n return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);\n };\n /**\n * Implementation specific of rendering the generating effect on the main canvas.\n * @param effect The effect used to render through\n */\n HighlightLayer.prototype._internalRender = function (effect) {\n // Texture\n effect.setTexture(\"textureSampler\", this._blurTexture);\n // Cache\n var engine = this._engine;\n var previousStencilBuffer = engine.getStencilBuffer();\n var previousStencilFunction = engine.getStencilFunction();\n var previousStencilMask = engine.getStencilMask();\n var previousStencilOperationPass = engine.getStencilOperationPass();\n var previousStencilOperationFail = engine.getStencilOperationFail();\n var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();\n var previousStencilReference = engine.getStencilFunctionReference();\n // Stencil operations\n engine.setStencilOperationPass(BABYLON.Engine.REPLACE);\n engine.setStencilOperationFail(BABYLON.Engine.KEEP);\n engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);\n // Draw order\n engine.setStencilMask(0x00);\n engine.setStencilBuffer(true);\n engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);\n // 2 passes inner outer\n if (this.outerGlow) {\n effect.setFloat(\"offset\", 0);\n engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n }\n if (this.innerGlow) {\n effect.setFloat(\"offset\", 1);\n engine.setStencilFunction(BABYLON.Engine.EQUAL);\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n }\n // Restore Cache\n engine.setStencilFunction(previousStencilFunction);\n engine.setStencilMask(previousStencilMask);\n engine.setStencilBuffer(previousStencilBuffer);\n engine.setStencilOperationPass(previousStencilOperationPass);\n engine.setStencilOperationFail(previousStencilOperationFail);\n engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);\n engine.setStencilFunctionReference(previousStencilReference);\n };\n /**\n * Returns true if the layer contains information to display, otherwise false.\n */\n HighlightLayer.prototype.shouldRender = function () {\n if (_super.prototype.shouldRender.call(this)) {\n return this._meshes ? true : false;\n }\n return false;\n };\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n HighlightLayer.prototype._shouldRenderMesh = function (mesh) {\n // Excluded Mesh\n if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {\n return false;\n }\n ;\n if (!_super.prototype.hasMesh.call(this, mesh)) {\n return false;\n }\n return true;\n };\n /**\n * Sets the required values for both the emissive texture and and the main color.\n */\n HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {\n var highlightLayerMesh = this._meshes[mesh.uniqueId];\n if (highlightLayerMesh) {\n this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);\n }\n else {\n this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);\n }\n if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {\n this._emissiveTextureAndColor.texture = material.emissiveTexture;\n this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);\n }\n else {\n this._emissiveTextureAndColor.texture = null;\n }\n };\n /**\n * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.\n * @param mesh The mesh to exclude from the highlight layer\n */\n HighlightLayer.prototype.addExcludedMesh = function (mesh) {\n if (!this._excludedMeshes) {\n return;\n }\n var meshExcluded = this._excludedMeshes[mesh.uniqueId];\n if (!meshExcluded) {\n this._excludedMeshes[mesh.uniqueId] = {\n mesh: mesh,\n beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {\n mesh.getEngine().setStencilBuffer(false);\n }),\n afterRender: mesh.onAfterRenderObservable.add(function (mesh) {\n mesh.getEngine().setStencilBuffer(true);\n }),\n };\n }\n };\n /**\n * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.\n * @param mesh The mesh to highlight\n */\n HighlightLayer.prototype.removeExcludedMesh = function (mesh) {\n if (!this._excludedMeshes) {\n return;\n }\n var meshExcluded = this._excludedMeshes[mesh.uniqueId];\n if (meshExcluded) {\n if (meshExcluded.beforeRender) {\n mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);\n }\n if (meshExcluded.afterRender) {\n mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);\n }\n }\n this._excludedMeshes[mesh.uniqueId] = null;\n };\n /**\n * Determine if a given mesh will be highlighted by the current HighlightLayer\n * @param mesh mesh to test\n * @returns true if the mesh will be highlighted by the current HighlightLayer\n */\n HighlightLayer.prototype.hasMesh = function (mesh) {\n if (!this._meshes) {\n return false;\n }\n if (!_super.prototype.hasMesh.call(this, mesh)) {\n return false;\n }\n return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;\n };\n /**\n * Add a mesh in the highlight layer in order to make it glow with the chosen color.\n * @param mesh The mesh to highlight\n * @param color The color of the highlight\n * @param glowEmissiveOnly Extract the glow from the emissive texture\n */\n HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {\n var _this = this;\n if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }\n if (!this._meshes) {\n return;\n }\n var meshHighlight = this._meshes[mesh.uniqueId];\n if (meshHighlight) {\n meshHighlight.color = color;\n }\n else {\n this._meshes[mesh.uniqueId] = {\n mesh: mesh,\n color: color,\n // Lambda required for capture due to Observable this context\n observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {\n if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {\n _this._defaultStencilReference(mesh);\n }\n else {\n mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);\n }\n }),\n observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),\n glowEmissiveOnly: glowEmissiveOnly\n };\n mesh.onDisposeObservable.add(function () {\n _this._disposeMesh(mesh);\n });\n }\n this._shouldRender = true;\n };\n /**\n * Remove a mesh from the highlight layer in order to make it stop glowing.\n * @param mesh The mesh to highlight\n */\n HighlightLayer.prototype.removeMesh = function (mesh) {\n if (!this._meshes) {\n return;\n }\n var meshHighlight = this._meshes[mesh.uniqueId];\n if (meshHighlight) {\n if (meshHighlight.observerHighlight) {\n mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);\n }\n if (meshHighlight.observerDefault) {\n mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);\n }\n delete this._meshes[mesh.uniqueId];\n }\n this._shouldRender = false;\n for (var meshHighlightToCheck in this._meshes) {\n if (this._meshes[meshHighlightToCheck]) {\n this._shouldRender = true;\n break;\n }\n }\n };\n /**\n * Force the stencil to the normal expected value for none glowing parts\n */\n HighlightLayer.prototype._defaultStencilReference = function (mesh) {\n mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);\n };\n /**\n * Free any resources and references associated to a mesh.\n * Internal use\n * @param mesh The mesh to free.\n */\n HighlightLayer.prototype._disposeMesh = function (mesh) {\n this.removeMesh(mesh);\n this.removeExcludedMesh(mesh);\n };\n /**\n * Dispose the highlight layer and free resources.\n */\n HighlightLayer.prototype.dispose = function () {\n if (this._meshes) {\n // Clean mesh references \n for (var id in this._meshes) {\n var meshHighlight = this._meshes[id];\n if (meshHighlight && meshHighlight.mesh) {\n if (meshHighlight.observerHighlight) {\n meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);\n }\n if (meshHighlight.observerDefault) {\n meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);\n }\n }\n }\n this._meshes = null;\n }\n if (this._excludedMeshes) {\n for (var id in this._excludedMeshes) {\n var meshHighlight = this._excludedMeshes[id];\n if (meshHighlight) {\n if (meshHighlight.beforeRender) {\n meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);\n }\n if (meshHighlight.afterRender) {\n meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);\n }\n }\n }\n this._excludedMeshes = null;\n }\n _super.prototype.dispose.call(this);\n };\n /**\n * Gets the class name of the effect layer\n * @returns the string with the class name of the effect layer\n */\n HighlightLayer.prototype.getClassName = function () {\n return \"HighlightLayer\";\n };\n /**\n * Serializes this Highlight layer\n * @returns a serialized Highlight layer object\n */\n HighlightLayer.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.HighlightLayer\";\n // Highlighted meshes\n serializationObject.meshes = [];\n if (this._meshes) {\n for (var m in this._meshes) {\n var mesh = this._meshes[m];\n if (mesh) {\n serializationObject.meshes.push({\n glowEmissiveOnly: mesh.glowEmissiveOnly,\n color: mesh.color.asArray(),\n meshId: mesh.mesh.id\n });\n }\n }\n }\n // Excluded meshes\n serializationObject.excludedMeshes = [];\n if (this._excludedMeshes) {\n for (var e in this._excludedMeshes) {\n var excludedMesh = this._excludedMeshes[e];\n if (excludedMesh) {\n serializationObject.excludedMeshes.push(excludedMesh.mesh.id);\n }\n }\n }\n return serializationObject;\n };\n /**\n * Creates a Highlight layer from parsed Highlight layer data\n * @param parsedHightlightLayer defines the Highlight layer data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing the Highlight layer information\n * @returns a parsed Highlight layer\n */\n HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {\n var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);\n var index;\n // Excluded meshes\n for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {\n var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);\n if (mesh) {\n hl.addExcludedMesh(mesh);\n }\n }\n // Included meshes\n for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {\n var highlightedMesh = parsedHightlightLayer.meshes[index];\n var mesh = scene.getMeshByID(highlightedMesh.meshId);\n if (mesh) {\n hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);\n }\n }\n return hl;\n };\n /**\n * Effect Name of the highlight layer.\n */\n HighlightLayer.EffectName = \"HighlightLayer\";\n /**\n * The neutral color used during the preparation of the glow effect.\n * This is black by default as the blend operation is a blend operation.\n */\n HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);\n /**\n * Stencil value used for glowing meshes.\n */\n HighlightLayer.GlowingMeshStencilReference = 0x02;\n /**\n * Stencil value used for the other meshes in the scene.\n */\n HighlightLayer.NormalMeshStencilReference = 0x01;\n __decorate([\n BABYLON.serialize()\n ], HighlightLayer.prototype, \"innerGlow\", void 0);\n __decorate([\n BABYLON.serialize()\n ], HighlightLayer.prototype, \"outerGlow\", void 0);\n __decorate([\n BABYLON.serialize()\n ], HighlightLayer.prototype, \"blurHorizontalSize\", null);\n __decorate([\n BABYLON.serialize()\n ], HighlightLayer.prototype, \"blurVerticalSize\", null);\n __decorate([\n BABYLON.serialize(\"options\")\n ], HighlightLayer.prototype, \"_options\", void 0);\n return HighlightLayer;\n }(BABYLON.EffectLayer));\n BABYLON.HighlightLayer = HighlightLayer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.highlightLayer.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {\n for (var index = 0; index < this.effectLayers.length; index++) {\n if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {\n return this.effectLayers[index];\n }\n }\n return null;\n };\n /**\n * The glow layer Helps adding a glow effect around the emissive parts of a mesh.\n *\n * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove\n * glowy meshes to your scene.\n *\n * Documentation: https://doc.babylonjs.com/how_to/glow_layer\n */\n var GlowLayer = /** @class */ (function (_super) {\n __extends(GlowLayer, _super);\n /**\n * Instantiates a new glow Layer and references it to the scene.\n * @param name The name of the layer\n * @param scene The scene to use the layer in\n * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)\n */\n function GlowLayer(name, scene, options) {\n var _this = _super.call(this, name, scene) || this;\n _this._intensity = 1.0;\n _this._includedOnlyMeshes = [];\n _this._excludedMeshes = [];\n _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);\n // Adapt options\n _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);\n // Initialize the layer\n _this._init({\n alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,\n camera: _this._options.camera,\n mainTextureFixedSize: _this._options.mainTextureFixedSize,\n mainTextureRatio: _this._options.mainTextureRatio,\n renderingGroupId: _this._options.renderingGroupId\n });\n return _this;\n }\n Object.defineProperty(GlowLayer.prototype, \"blurKernelSize\", {\n /**\n * Gets the kernel size of the blur.\n */\n get: function () {\n return this._horizontalBlurPostprocess1.kernel;\n },\n /**\n * Sets the kernel size of the blur.\n */\n set: function (value) {\n this._horizontalBlurPostprocess1.kernel = value;\n this._verticalBlurPostprocess1.kernel = value;\n this._horizontalBlurPostprocess2.kernel = value;\n this._verticalBlurPostprocess2.kernel = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GlowLayer.prototype, \"intensity\", {\n /**\n * Gets the glow intensity.\n */\n get: function () {\n return this._intensity;\n },\n /**\n * Sets the glow intensity.\n */\n set: function (value) {\n this._intensity = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Get the effect name of the layer.\n * @return The effect name\n */\n GlowLayer.prototype.getEffectName = function () {\n return GlowLayer.EffectName;\n };\n /**\n * Create the merge effect. This is the shader use to blit the information back\n * to the main canvas at the end of the scene rendering.\n */\n GlowLayer.prototype._createMergeEffect = function () {\n // Effect\n return this._engine.createEffect(\"glowMapMerge\", [BABYLON.VertexBuffer.PositionKind], [\"offset\"], [\"textureSampler\", \"textureSampler2\"], \"#define EMISSIVE \\n\");\n };\n /**\n * Creates the render target textures and post processes used in the glow layer.\n */\n GlowLayer.prototype._createTextureAndPostProcesses = function () {\n var _this = this;\n var blurTextureWidth = this._mainTextureDesiredSize.width;\n var blurTextureHeight = this._mainTextureDesiredSize.height;\n blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;\n blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;\n var textureType = 0;\n if (this._engine.getCaps().textureHalfFloatRender) {\n textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else {\n textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n this._blurTexture1 = new BABYLON.RenderTargetTexture(\"GlowLayerBlurRTT\", {\n width: blurTextureWidth,\n height: blurTextureHeight\n }, this._scene, false, true, textureType);\n this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n this._blurTexture1.renderParticles = false;\n this._blurTexture1.ignoreCameraViewport = true;\n var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);\n var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);\n this._blurTexture2 = new BABYLON.RenderTargetTexture(\"GlowLayerBlurRTT2\", {\n width: blurTextureWidth2,\n height: blurTextureHeight2\n }, this._scene, false, true, textureType);\n this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n this._blurTexture2.renderParticles = false;\n this._blurTexture2.ignoreCameraViewport = true;\n this._textures = [this._blurTexture1, this._blurTexture2];\n this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess(\"GlowLayerHBP1\", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {\n width: blurTextureWidth,\n height: blurTextureHeight\n }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess1.width = blurTextureWidth;\n this._horizontalBlurPostprocess1.height = blurTextureHeight;\n this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {\n effect.setTexture(\"textureSampler\", _this._mainTexture);\n });\n this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess(\"GlowLayerVBP1\", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {\n width: blurTextureWidth,\n height: blurTextureHeight\n }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess(\"GlowLayerHBP2\", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {\n width: blurTextureWidth2,\n height: blurTextureHeight2\n }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess2.width = blurTextureWidth2;\n this._horizontalBlurPostprocess2.height = blurTextureHeight2;\n this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {\n effect.setTexture(\"textureSampler\", _this._blurTexture1);\n });\n this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess(\"GlowLayerVBP2\", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {\n width: blurTextureWidth2,\n height: blurTextureHeight2\n }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];\n this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];\n this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];\n this._mainTexture.samples = this._options.mainTextureSamples;\n this._mainTexture.onAfterUnbindObservable.add(function () {\n var internalTexture = _this._blurTexture1.getInternalTexture();\n if (internalTexture) {\n _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);\n internalTexture = _this._blurTexture2.getInternalTexture();\n if (internalTexture) {\n _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);\n }\n }\n });\n // Prevent autoClear.\n this._postProcesses.map(function (pp) { pp.autoClear = false; });\n };\n /**\n * Checks for the readiness of the element composing the layer.\n * @param subMesh the mesh to check for\n * @param useInstances specify wether or not to use instances to render the mesh\n * @param emissiveTexture the associated emissive texture used to generate the glow\n * @return true if ready otherwise, false\n */\n GlowLayer.prototype.isReady = function (subMesh, useInstances) {\n var material = subMesh.getMaterial();\n var mesh = subMesh.getRenderingMesh();\n if (!material || !mesh) {\n return false;\n }\n var emissiveTexture = material.emissiveTexture;\n return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);\n };\n /**\n * Returns wether or nood the layer needs stencil enabled during the mesh rendering.\n */\n GlowLayer.prototype.needStencil = function () {\n return false;\n };\n /**\n * Implementation specific of rendering the generating effect on the main canvas.\n * @param effect The effect used to render through\n */\n GlowLayer.prototype._internalRender = function (effect) {\n // Texture\n effect.setTexture(\"textureSampler\", this._blurTexture1);\n effect.setTexture(\"textureSampler2\", this._blurTexture2);\n effect.setFloat(\"offset\", this._intensity);\n // Cache\n var engine = this._engine;\n var previousStencilBuffer = engine.getStencilBuffer();\n // Draw order\n engine.setStencilBuffer(false);\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n // Draw order\n engine.setStencilBuffer(previousStencilBuffer);\n };\n /**\n * Sets the required values for both the emissive texture and and the main color.\n */\n GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {\n var textureLevel = 1.0;\n if (this.customEmissiveTextureSelector) {\n this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);\n }\n else {\n if (material) {\n this._emissiveTextureAndColor.texture = material.emissiveTexture;\n if (this._emissiveTextureAndColor.texture) {\n textureLevel = this._emissiveTextureAndColor.texture.level;\n }\n }\n else {\n this._emissiveTextureAndColor.texture = null;\n }\n }\n if (this.customEmissiveColorSelector) {\n this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);\n }\n else {\n if (material.emissiveColor) {\n this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);\n }\n else {\n this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);\n }\n }\n };\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n GlowLayer.prototype._shouldRenderMesh = function (mesh) {\n return this.hasMesh(mesh);\n };\n /**\n * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.\n * @param mesh The mesh to exclude from the glow layer\n */\n GlowLayer.prototype.addExcludedMesh = function (mesh) {\n if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {\n this._excludedMeshes.push(mesh.uniqueId);\n }\n };\n /**\n * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.\n * @param mesh The mesh to remove\n */\n GlowLayer.prototype.removeExcludedMesh = function (mesh) {\n var index = this._excludedMeshes.indexOf(mesh.uniqueId);\n if (index !== -1) {\n this._excludedMeshes.splice(index, 1);\n }\n };\n /**\n * Add a mesh in the inclusion list to impact or being impacted by the glow layer.\n * @param mesh The mesh to include in the glow layer\n */\n GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {\n if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {\n this._includedOnlyMeshes.push(mesh.uniqueId);\n }\n };\n /**\n * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.\n * @param mesh The mesh to remove\n */\n GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {\n var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);\n if (index !== -1) {\n this._includedOnlyMeshes.splice(index, 1);\n }\n };\n /**\n * Determine if a given mesh will be used in the glow layer\n * @param mesh The mesh to test\n * @returns true if the mesh will be highlighted by the current glow layer\n */\n GlowLayer.prototype.hasMesh = function (mesh) {\n if (!_super.prototype.hasMesh.call(this, mesh)) {\n return false;\n }\n // Included Mesh\n if (this._includedOnlyMeshes.length) {\n return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;\n }\n ;\n // Excluded Mesh\n if (this._excludedMeshes.length) {\n return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;\n }\n ;\n return true;\n };\n /**\n * Free any resources and references associated to a mesh.\n * Internal use\n * @param mesh The mesh to free.\n */\n GlowLayer.prototype._disposeMesh = function (mesh) {\n this.removeIncludedOnlyMesh(mesh);\n this.removeExcludedMesh(mesh);\n };\n /**\n * Gets the class name of the effect layer\n * @returns the string with the class name of the effect layer\n */\n GlowLayer.prototype.getClassName = function () {\n return \"GlowLayer\";\n };\n /**\n * Serializes this glow layer\n * @returns a serialized glow layer object\n */\n GlowLayer.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.GlowLayer\";\n var index;\n // Included meshes\n serializationObject.includedMeshes = [];\n if (this._includedOnlyMeshes.length) {\n for (index = 0; index < this._includedOnlyMeshes.length; index++) {\n var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);\n if (mesh) {\n serializationObject.includedMeshes.push(mesh.id);\n }\n }\n }\n // Excluded meshes\n serializationObject.excludedMeshes = [];\n if (this._excludedMeshes.length) {\n for (index = 0; index < this._excludedMeshes.length; index++) {\n var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);\n if (mesh) {\n serializationObject.excludedMeshes.push(mesh.id);\n }\n }\n }\n return serializationObject;\n };\n /**\n * Creates a Glow Layer from parsed glow layer data\n * @param parsedGlowLayer defines glow layer data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing the glow layer information\n * @returns a parsed Glow Layer\n */\n GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {\n var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);\n var index;\n // Excluded meshes\n for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {\n var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);\n if (mesh) {\n gl.addExcludedMesh(mesh);\n }\n }\n // Included meshes\n for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {\n var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);\n if (mesh) {\n gl.addIncludedOnlyMesh(mesh);\n }\n }\n return gl;\n };\n /**\n * Effect Name of the layer.\n */\n GlowLayer.EffectName = \"GlowLayer\";\n /**\n * The default blur kernel size used for the glow.\n */\n GlowLayer.DefaultBlurKernelSize = 32;\n /**\n * The default texture size ratio used for the glow.\n */\n GlowLayer.DefaultTextureRatio = 0.5;\n __decorate([\n BABYLON.serialize()\n ], GlowLayer.prototype, \"blurKernelSize\", null);\n __decorate([\n BABYLON.serialize()\n ], GlowLayer.prototype, \"intensity\", null);\n __decorate([\n BABYLON.serialize(\"options\")\n ], GlowLayer.prototype, \"_options\", void 0);\n return GlowLayer;\n }(BABYLON.EffectLayer));\n BABYLON.GlowLayer = GlowLayer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glowLayer.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the list of states available for a task inside a {BABYLON.AssetsManager}\n */\n var AssetTaskState;\n (function (AssetTaskState) {\n /**\n * Initialization\n */\n AssetTaskState[AssetTaskState[\"INIT\"] = 0] = \"INIT\";\n /**\n * Running\n */\n AssetTaskState[AssetTaskState[\"RUNNING\"] = 1] = \"RUNNING\";\n /**\n * Done\n */\n AssetTaskState[AssetTaskState[\"DONE\"] = 2] = \"DONE\";\n /**\n * Error\n */\n AssetTaskState[AssetTaskState[\"ERROR\"] = 3] = \"ERROR\";\n })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));\n /**\n * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene\n */\n var AbstractAssetTask = /** @class */ (function () {\n /**\n * Creates a new {BABYLON.AssetsManager}\n * @param name defines the name of the task\n */\n function AbstractAssetTask(\n /**\n * Task name\n */ name) {\n this.name = name;\n this._isCompleted = false;\n this._taskState = AssetTaskState.INIT;\n }\n Object.defineProperty(AbstractAssetTask.prototype, \"isCompleted\", {\n /**\n * Get if the task is completed\n */\n get: function () {\n return this._isCompleted;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractAssetTask.prototype, \"taskState\", {\n /**\n * Gets the current state of the task\n */\n get: function () {\n return this._taskState;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractAssetTask.prototype, \"errorObject\", {\n /**\n * Gets the current error object (if task is in error)\n */\n get: function () {\n return this._errorObject;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Internal only\n * @hidden\n */\n AbstractAssetTask.prototype._setErrorObject = function (message, exception) {\n if (this._errorObject) {\n return;\n }\n this._errorObject = {\n message: message,\n exception: exception\n };\n };\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {\n var _this = this;\n this._taskState = AssetTaskState.RUNNING;\n this.runTask(scene, function () {\n _this.onDoneCallback(onSuccess, onError);\n }, function (msg, exception) {\n _this.onErrorCallback(onError, msg, exception);\n });\n };\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n throw new Error(\"runTask is not implemented\");\n };\n /**\n * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.\n * This can be used with failed tasks that have the reason for failure fixed.\n */\n AbstractAssetTask.prototype.reset = function () {\n this._taskState = AssetTaskState.INIT;\n };\n AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {\n this._taskState = AssetTaskState.ERROR;\n this._errorObject = {\n message: message,\n exception: exception\n };\n if (this.onError) {\n this.onError(this, message, exception);\n }\n onError();\n };\n AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {\n try {\n this._taskState = AssetTaskState.DONE;\n this._isCompleted = true;\n if (this.onSuccess) {\n this.onSuccess(this);\n }\n onSuccess();\n }\n catch (e) {\n this.onErrorCallback(onError, \"Task is done, error executing success callback(s)\", e);\n }\n };\n return AbstractAssetTask;\n }());\n BABYLON.AbstractAssetTask = AbstractAssetTask;\n /**\n * Class used to share progress information about assets loading\n */\n var AssetsProgressEvent = /** @class */ (function () {\n /**\n * Creates a {BABYLON.AssetsProgressEvent}\n * @param remainingCount defines the number of remaining tasks to process\n * @param totalCount defines the total number of tasks\n * @param task defines the task that was just processed\n */\n function AssetsProgressEvent(remainingCount, totalCount, task) {\n this.remainingCount = remainingCount;\n this.totalCount = totalCount;\n this.task = task;\n }\n return AssetsProgressEvent;\n }());\n BABYLON.AssetsProgressEvent = AssetsProgressEvent;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load meshes\n */\n var MeshAssetTask = /** @class */ (function (_super) {\n __extends(MeshAssetTask, _super);\n /**\n * Creates a new {BABYLON.MeshAssetTask}\n * @param name defines the name of the task\n * @param meshesNames defines the list of mesh's names you want to load\n * @param rootUrl defines the root url to use as a base to load your meshes and associated resources\n * @param sceneFilename defines the filename of the scene to load from\n */\n function MeshAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the list of mesh's names you want to load\n */\n meshesNames, \n /**\n * Defines the root url to use as a base to load your meshes and associated resources\n */\n rootUrl, \n /**\n * Defines the filename of the scene to load from\n */\n sceneFilename) {\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.meshesNames = meshesNames;\n _this.rootUrl = rootUrl;\n _this.sceneFilename = sceneFilename;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n var _this = this;\n BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {\n _this.loadedMeshes = meshes;\n _this.loadedParticleSystems = particleSystems;\n _this.loadedSkeletons = skeletons;\n onSuccess();\n }, null, function (scene, message, exception) {\n onError(message, exception);\n });\n };\n return MeshAssetTask;\n }(AbstractAssetTask));\n BABYLON.MeshAssetTask = MeshAssetTask;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load text content\n */\n var TextFileAssetTask = /** @class */ (function (_super) {\n __extends(TextFileAssetTask, _super);\n /**\n * Creates a new TextFileAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n */\n function TextFileAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url) {\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.url = url;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n var _this = this;\n scene._loadFile(this.url, function (data) {\n _this.text = data;\n onSuccess();\n }, undefined, false, false, function (request, exception) {\n if (request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n });\n };\n return TextFileAssetTask;\n }(AbstractAssetTask));\n BABYLON.TextFileAssetTask = TextFileAssetTask;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load binary data\n */\n var BinaryFileAssetTask = /** @class */ (function (_super) {\n __extends(BinaryFileAssetTask, _super);\n /**\n * Creates a new BinaryFileAssetTask object\n * @param name defines the name of the new task\n * @param url defines the location of the file to load\n */\n function BinaryFileAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url) {\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.url = url;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n var _this = this;\n scene._loadFile(this.url, function (data) {\n _this.data = data;\n onSuccess();\n }, undefined, true, true, function (request, exception) {\n if (request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n });\n };\n return BinaryFileAssetTask;\n }(AbstractAssetTask));\n BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load images\n */\n var ImageAssetTask = /** @class */ (function (_super) {\n __extends(ImageAssetTask, _super);\n /**\n * Creates a new ImageAssetTask\n * @param name defines the name of the task\n * @param url defines the location of the image to load\n */\n function ImageAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the image to load\n */\n url) {\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.url = url;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n var _this = this;\n var img = new Image();\n BABYLON.Tools.SetCorsBehavior(this.url, img);\n img.onload = function () {\n _this.image = img;\n onSuccess();\n };\n img.onerror = function (err) {\n onError(\"Error loading image\", err);\n };\n img.src = this.url;\n };\n return ImageAssetTask;\n }(AbstractAssetTask));\n BABYLON.ImageAssetTask = ImageAssetTask;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load 2D textures\n */\n var TextureAssetTask = /** @class */ (function (_super) {\n __extends(TextureAssetTask, _super);\n /**\n * Creates a new TextureAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n * @param noMipmap defines if mipmap should not be generated (default is false)\n * @param invertY defines if texture must be inverted on Y axis (default is false)\n * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)\n */\n function TextureAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url, \n /**\n * Defines if mipmap should not be generated (default is false)\n */\n noMipmap, \n /**\n * Defines if texture must be inverted on Y axis (default is false)\n */\n invertY, \n /**\n * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)\n */\n samplingMode) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.url = url;\n _this.noMipmap = noMipmap;\n _this.invertY = invertY;\n _this.samplingMode = samplingMode;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n var onload = function () {\n onSuccess();\n };\n var onerror = function (message, exception) {\n onError(message, exception);\n };\n this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);\n };\n return TextureAssetTask;\n }(AbstractAssetTask));\n BABYLON.TextureAssetTask = TextureAssetTask;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load cube textures\n */\n var CubeTextureAssetTask = /** @class */ (function (_super) {\n __extends(CubeTextureAssetTask, _super);\n /**\n * Creates a new CubeTextureAssetTask\n * @param name defines the name of the task\n * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)\n * @param extensions defines the extensions to use to load files ([\"_px\", \"_py\", \"_pz\", \"_nx\", \"_ny\", \"_nz\"] by default)\n * @param noMipmap defines if mipmaps should not be generated (default is false)\n * @param files defines the explicit list of files (undefined by default)\n */\n function CubeTextureAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)\n */\n url, \n /**\n * Defines the extensions to use to load files ([\"_px\", \"_py\", \"_pz\", \"_nx\", \"_ny\", \"_nz\"] by default)\n */\n extensions, \n /**\n * Defines if mipmaps should not be generated (default is false)\n */\n noMipmap, \n /**\n * Defines the explicit list of files (undefined by default)\n */\n files) {\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.url = url;\n _this.extensions = extensions;\n _this.noMipmap = noMipmap;\n _this.files = files;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n var onload = function () {\n onSuccess();\n };\n var onerror = function (message, exception) {\n onError(message, exception);\n };\n this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);\n };\n return CubeTextureAssetTask;\n }(AbstractAssetTask));\n BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures\n */\n var HDRCubeTextureAssetTask = /** @class */ (function (_super) {\n __extends(HDRCubeTextureAssetTask, _super);\n /**\n * Creates a new HDRCubeTextureAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.\n * @param noMipmap defines if mipmaps should not be generated (default is false)\n * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)\n * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)\n * @param reserved Internal use only\n */\n function HDRCubeTextureAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url, \n /**\n * Defines the desired size (the more it increases the longer the generation will be)\n */\n size, \n /**\n * Defines if mipmaps should not be generated (default is false)\n */\n noMipmap, \n /**\n * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)\n */\n generateHarmonics, \n /**\n * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)\n */\n gammaSpace, \n /**\n * Internal Use Only\n */\n reserved) {\n if (noMipmap === void 0) { noMipmap = false; }\n if (generateHarmonics === void 0) { generateHarmonics = true; }\n if (gammaSpace === void 0) { gammaSpace = false; }\n if (reserved === void 0) { reserved = false; }\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.url = url;\n _this.size = size;\n _this.noMipmap = noMipmap;\n _this.generateHarmonics = generateHarmonics;\n _this.gammaSpace = gammaSpace;\n _this.reserved = reserved;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {\n var onload = function () {\n onSuccess();\n };\n var onerror = function (message, exception) {\n onError(message, exception);\n };\n this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);\n };\n return HDRCubeTextureAssetTask;\n }(AbstractAssetTask));\n BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;\n /**\n * This class can be used to easily import assets into a scene\n * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager\n */\n var AssetsManager = /** @class */ (function () {\n /**\n * Creates a new AssetsManager\n * @param scene defines the scene to work on\n */\n function AssetsManager(scene) {\n this._isLoading = false;\n this._tasks = new Array();\n this._waitingTasksCount = 0;\n this._totalTasksCount = 0;\n /**\n * Observable called when all tasks are processed\n */\n this.onTaskSuccessObservable = new BABYLON.Observable();\n /**\n * Observable called when a task had an error\n */\n this.onTaskErrorObservable = new BABYLON.Observable();\n /**\n * Observable called when a task is successful\n */\n this.onTasksDoneObservable = new BABYLON.Observable();\n /**\n * Observable called when a task is done (whatever the result is)\n */\n this.onProgressObservable = new BABYLON.Observable();\n /**\n * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n this.useDefaultLoadingScreen = true;\n this._scene = scene;\n }\n /**\n * Add a {BABYLON.MeshAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param meshesNames defines the name of meshes to load\n * @param rootUrl defines the root url to use to locate files\n * @param sceneFilename defines the filename of the scene file\n * @returns a new {BABYLON.MeshAssetTask} object\n */\n AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {\n var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);\n this._tasks.push(task);\n return task;\n };\n /**\n * Add a {BABYLON.TextFileAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @returns a new {BABYLON.TextFileAssetTask} object\n */\n AssetsManager.prototype.addTextFileTask = function (taskName, url) {\n var task = new TextFileAssetTask(taskName, url);\n this._tasks.push(task);\n return task;\n };\n /**\n * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @returns a new {BABYLON.BinaryFileAssetTask} object\n */\n AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {\n var task = new BinaryFileAssetTask(taskName, url);\n this._tasks.push(task);\n return task;\n };\n /**\n * Add a {BABYLON.ImageAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @returns a new {BABYLON.ImageAssetTask} object\n */\n AssetsManager.prototype.addImageTask = function (taskName, url) {\n var task = new ImageAssetTask(taskName, url);\n this._tasks.push(task);\n return task;\n };\n /**\n * Add a {BABYLON.TextureAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)\n * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)\n * @returns a new {BABYLON.TextureAssetTask} object\n */\n AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);\n this._tasks.push(task);\n return task;\n };\n /**\n * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param extensions defines the extension to use to load the cube map (can be null)\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param files defines the list of files to load (can be null)\n * @returns a new {BABYLON.CubeTextureAssetTask} object\n */\n AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {\n var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);\n this._tasks.push(task);\n return task;\n };\n /**\n *\n * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param size defines the size you want for the cubemap (can be null)\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param generateHarmonics defines if you want to automatically generate (true by default)\n * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)\n * @param reserved Internal use only\n * @returns a new {BABYLON.HDRCubeTextureAssetTask} object\n */\n AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {\n if (noMipmap === void 0) { noMipmap = false; }\n if (generateHarmonics === void 0) { generateHarmonics = true; }\n if (gammaSpace === void 0) { gammaSpace = false; }\n if (reserved === void 0) { reserved = false; }\n var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);\n this._tasks.push(task);\n return task;\n };\n /**\n * Remove a task from the assets manager.\n * @param task the task to remove\n */\n AssetsManager.prototype.removeTask = function (task) {\n var index = this._tasks.indexOf(task);\n if (index > -1) {\n this._tasks.splice(index, 1);\n }\n };\n AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {\n this._waitingTasksCount--;\n try {\n if (this.onProgress) {\n this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);\n }\n this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));\n }\n catch (e) {\n BABYLON.Tools.Error(\"Error running progress callbacks.\");\n console.log(e);\n }\n if (this._waitingTasksCount === 0) {\n try {\n if (this.onFinish) {\n this.onFinish(this._tasks);\n }\n // Let's remove successfull tasks\n var currentTasks = this._tasks.slice();\n for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {\n var task = currentTasks_1[_i];\n if (task.taskState === AssetTaskState.DONE) {\n var index = this._tasks.indexOf(task);\n if (index > -1) {\n this._tasks.splice(index, 1);\n }\n }\n }\n this.onTasksDoneObservable.notifyObservers(this._tasks);\n }\n catch (e) {\n BABYLON.Tools.Error(\"Error running tasks-done callbacks.\");\n console.log(e);\n }\n this._isLoading = false;\n this._scene.getEngine().hideLoadingUI();\n }\n };\n AssetsManager.prototype._runTask = function (task) {\n var _this = this;\n var done = function () {\n try {\n if (_this.onTaskSuccess) {\n _this.onTaskSuccess(task);\n }\n _this.onTaskSuccessObservable.notifyObservers(task);\n _this._decreaseWaitingTasksCount(task);\n }\n catch (e) {\n error(\"Error executing task success callbacks\", e);\n }\n };\n var error = function (message, exception) {\n task._setErrorObject(message, exception);\n if (_this.onTaskError) {\n _this.onTaskError(task);\n }\n _this.onTaskErrorObservable.notifyObservers(task);\n _this._decreaseWaitingTasksCount(task);\n };\n task.run(this._scene, done, error);\n };\n /**\n * Reset the {BABYLON.AssetsManager} and remove all tasks\n * @return the current instance of the {BABYLON.AssetsManager}\n */\n AssetsManager.prototype.reset = function () {\n this._isLoading = false;\n this._tasks = new Array();\n return this;\n };\n /**\n * Start the loading process\n * @return the current instance of the {BABYLON.AssetsManager}\n */\n AssetsManager.prototype.load = function () {\n if (this._isLoading) {\n return this;\n }\n this._isLoading = true;\n this._waitingTasksCount = this._tasks.length;\n this._totalTasksCount = this._tasks.length;\n if (this._waitingTasksCount === 0) {\n this._isLoading = false;\n if (this.onFinish) {\n this.onFinish(this._tasks);\n }\n this.onTasksDoneObservable.notifyObservers(this._tasks);\n return this;\n }\n if (this.useDefaultLoadingScreen) {\n this._scene.getEngine().displayLoadingUI();\n }\n for (var index = 0; index < this._tasks.length; index++) {\n var task = this._tasks[index];\n if (task.taskState === AssetTaskState.INIT) {\n this._runTask(task);\n }\n }\n return this;\n };\n return AssetsManager;\n }());\n BABYLON.AssetsManager = AssetsManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.assetsManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var serializedGeometries = [];\n var serializeGeometry = function (geometry, serializationGeometries) {\n if (serializedGeometries[geometry.id]) {\n return;\n }\n if (geometry.doNotSerialize) {\n return;\n }\n if (geometry instanceof BABYLON.BoxGeometry) {\n serializationGeometries.boxes.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON.SphereGeometry) {\n serializationGeometries.spheres.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON.CylinderGeometry) {\n serializationGeometries.cylinders.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON.TorusGeometry) {\n serializationGeometries.toruses.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON.GroundGeometry) {\n serializationGeometries.grounds.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON.Plane) {\n serializationGeometries.planes.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON.TorusKnotGeometry) {\n serializationGeometries.torusKnots.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON._PrimitiveGeometry) {\n throw new Error(\"Unknown primitive type\");\n }\n else {\n serializationGeometries.vertexData.push(geometry.serializeVerticeData());\n }\n serializedGeometries[geometry.id] = true;\n };\n var serializeMesh = function (mesh, serializationScene) {\n var serializationObject = {};\n // Geometry \n var geometry = mesh._geometry;\n if (geometry) {\n if (!mesh.getScene().getGeometryByID(geometry.id)) {\n // Geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry\n serializeGeometry(geometry, serializationScene.geometries);\n }\n }\n // Custom\n if (mesh.serialize) {\n mesh.serialize(serializationObject);\n }\n return serializationObject;\n };\n var finalizeSingleMesh = function (mesh, serializationObject) {\n //only works if the mesh is already loaded\n if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {\n //serialize material\n if (mesh.material) {\n if (mesh.material instanceof BABYLON.MultiMaterial) {\n serializationObject.multiMaterials = serializationObject.multiMaterials || [];\n serializationObject.materials = serializationObject.materials || [];\n if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {\n serializationObject.multiMaterials.push(mesh.material.serialize());\n var _loop_1 = function (submaterial) {\n if (submaterial) {\n if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {\n serializationObject.materials.push(submaterial.serialize());\n }\n }\n };\n for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {\n var submaterial = _a[_i];\n _loop_1(submaterial);\n }\n }\n }\n else {\n serializationObject.materials = serializationObject.materials || [];\n if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {\n serializationObject.materials.push(mesh.material.serialize());\n }\n }\n }\n //serialize geometry\n var geometry = mesh._geometry;\n if (geometry) {\n if (!serializationObject.geometries) {\n serializationObject.geometries = {};\n serializationObject.geometries.boxes = [];\n serializationObject.geometries.spheres = [];\n serializationObject.geometries.cylinders = [];\n serializationObject.geometries.toruses = [];\n serializationObject.geometries.grounds = [];\n serializationObject.geometries.planes = [];\n serializationObject.geometries.torusKnots = [];\n serializationObject.geometries.vertexData = [];\n }\n serializeGeometry(geometry, serializationObject.geometries);\n }\n // Skeletons\n if (mesh.skeleton) {\n serializationObject.skeletons = serializationObject.skeletons || [];\n serializationObject.skeletons.push(mesh.skeleton.serialize());\n }\n //serialize the actual mesh\n serializationObject.meshes = serializationObject.meshes || [];\n serializationObject.meshes.push(serializeMesh(mesh, serializationObject));\n }\n };\n var SceneSerializer = /** @class */ (function () {\n function SceneSerializer() {\n }\n SceneSerializer.ClearCache = function () {\n serializedGeometries = [];\n };\n SceneSerializer.Serialize = function (scene) {\n var serializationObject = {};\n SceneSerializer.ClearCache();\n // Scene\n serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;\n serializationObject.autoClear = scene.autoClear;\n serializationObject.clearColor = scene.clearColor.asArray();\n serializationObject.ambientColor = scene.ambientColor.asArray();\n serializationObject.gravity = scene.gravity.asArray();\n serializationObject.collisionsEnabled = scene.collisionsEnabled;\n serializationObject.workerCollisions = scene.workerCollisions;\n // Fog\n if (scene.fogMode && scene.fogMode !== 0) {\n serializationObject.fogMode = scene.fogMode;\n serializationObject.fogColor = scene.fogColor.asArray();\n serializationObject.fogStart = scene.fogStart;\n serializationObject.fogEnd = scene.fogEnd;\n serializationObject.fogDensity = scene.fogDensity;\n }\n //Physics\n if (scene.isPhysicsEnabled()) {\n var physicEngine = scene.getPhysicsEngine();\n if (physicEngine) {\n serializationObject.physicsEnabled = true;\n serializationObject.physicsGravity = physicEngine.gravity.asArray();\n serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();\n }\n }\n // Metadata\n if (scene.metadata) {\n serializationObject.metadata = scene.metadata;\n }\n // Morph targets\n serializationObject.morphTargetManagers = [];\n for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {\n var abstractMesh = _a[_i];\n var manager = abstractMesh.morphTargetManager;\n if (manager) {\n serializationObject.morphTargetManagers.push(manager.serialize());\n }\n }\n // Lights\n serializationObject.lights = [];\n var index;\n var light;\n for (index = 0; index < scene.lights.length; index++) {\n light = scene.lights[index];\n if (!light.doNotSerialize) {\n serializationObject.lights.push(light.serialize());\n }\n }\n // Cameras\n serializationObject.cameras = [];\n for (index = 0; index < scene.cameras.length; index++) {\n var camera = scene.cameras[index];\n if (!camera.doNotSerialize) {\n serializationObject.cameras.push(camera.serialize());\n }\n }\n if (scene.activeCamera) {\n serializationObject.activeCameraID = scene.activeCamera.id;\n }\n // Animations\n BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);\n // Materials\n serializationObject.materials = [];\n serializationObject.multiMaterials = [];\n var material;\n for (index = 0; index < scene.materials.length; index++) {\n material = scene.materials[index];\n if (!material.doNotSerialize) {\n serializationObject.materials.push(material.serialize());\n }\n }\n // MultiMaterials\n serializationObject.multiMaterials = [];\n for (index = 0; index < scene.multiMaterials.length; index++) {\n var multiMaterial = scene.multiMaterials[index];\n serializationObject.multiMaterials.push(multiMaterial.serialize());\n }\n // Environment texture\n if (scene.environmentTexture) {\n serializationObject.environmentTexture = scene.environmentTexture.name;\n }\n // Skeletons\n serializationObject.skeletons = [];\n for (index = 0; index < scene.skeletons.length; index++) {\n var skeleton = scene.skeletons[index];\n if (!skeleton.doNotSerialize) {\n serializationObject.skeletons.push(skeleton.serialize());\n }\n }\n // Transform nodes\n serializationObject.transformNodes = [];\n for (index = 0; index < scene.transformNodes.length; index++) {\n serializationObject.transformNodes.push(scene.transformNodes[index].serialize());\n }\n // Geometries\n serializationObject.geometries = {};\n serializationObject.geometries.boxes = [];\n serializationObject.geometries.spheres = [];\n serializationObject.geometries.cylinders = [];\n serializationObject.geometries.toruses = [];\n serializationObject.geometries.grounds = [];\n serializationObject.geometries.planes = [];\n serializationObject.geometries.torusKnots = [];\n serializationObject.geometries.vertexData = [];\n serializedGeometries = [];\n var geometries = scene.getGeometries();\n for (index = 0; index < geometries.length; index++) {\n var geometry = geometries[index];\n if (geometry.isReady()) {\n serializeGeometry(geometry, serializationObject.geometries);\n }\n }\n // Meshes\n serializationObject.meshes = [];\n for (index = 0; index < scene.meshes.length; index++) {\n var abstractMesh = scene.meshes[index];\n if (abstractMesh instanceof BABYLON.Mesh) {\n var mesh = abstractMesh;\n if (!mesh.doNotSerialize) {\n if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {\n serializationObject.meshes.push(serializeMesh(mesh, serializationObject));\n }\n }\n }\n }\n // Particles Systems\n serializationObject.particleSystems = [];\n for (index = 0; index < scene.particleSystems.length; index++) {\n serializationObject.particleSystems.push(scene.particleSystems[index].serialize());\n }\n // Shadows\n serializationObject.shadowGenerators = [];\n for (index = 0; index < scene.lights.length; index++) {\n light = scene.lights[index];\n var shadowGenerator = light.getShadowGenerator();\n if (shadowGenerator) {\n serializationObject.shadowGenerators.push(shadowGenerator.serialize());\n }\n }\n // Action Manager\n if (scene.actionManager) {\n serializationObject.actions = scene.actionManager.serialize(\"scene\");\n }\n // Audio\n serializationObject.sounds = [];\n for (index = 0; index < scene.soundTracks.length; index++) {\n var soundtrack = scene.soundTracks[index];\n for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {\n serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());\n }\n }\n // Components\n for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {\n var component = _c[_b];\n component.serialize(serializationObject);\n }\n return serializationObject;\n };\n SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {\n if (withParents === void 0) { withParents = false; }\n if (withChildren === void 0) { withChildren = false; }\n var serializationObject = {};\n SceneSerializer.ClearCache();\n toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];\n if (withParents || withChildren) {\n //deliberate for loop! not for each, appended should be processed as well.\n for (var i = 0; i < toSerialize.length; ++i) {\n if (withChildren) {\n toSerialize[i].getDescendants().forEach(function (node) {\n if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {\n toSerialize.push(node);\n }\n });\n }\n //make sure the array doesn't contain the object already\n if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {\n toSerialize.push(toSerialize[i].parent);\n }\n }\n }\n toSerialize.forEach(function (mesh) {\n finalizeSingleMesh(mesh, serializationObject);\n });\n return serializationObject;\n };\n return SceneSerializer;\n }());\n BABYLON.SceneSerializer = SceneSerializer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sceneSerializer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var ReflectionProbe = /** @class */ (function () {\n function ReflectionProbe(name, size, scene, generateMipMaps) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n var _this = this;\n this.name = name;\n this._viewMatrix = BABYLON.Matrix.Identity();\n this._target = BABYLON.Vector3.Zero();\n this._add = BABYLON.Vector3.Zero();\n this._invertYAxis = false;\n this.position = BABYLON.Vector3.Zero();\n this._scene = scene;\n this._scene.reflectionProbes.push(this);\n this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);\n this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {\n switch (faceIndex) {\n case 0:\n _this._add.copyFromFloats(1, 0, 0);\n break;\n case 1:\n _this._add.copyFromFloats(-1, 0, 0);\n break;\n case 2:\n _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);\n break;\n case 3:\n _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);\n break;\n case 4:\n _this._add.copyFromFloats(0, 0, 1);\n break;\n case 5:\n _this._add.copyFromFloats(0, 0, -1);\n break;\n }\n if (_this._attachedMesh) {\n _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());\n }\n _this.position.addToRef(_this._add, _this._target);\n BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);\n scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);\n scene._forcedViewPosition = _this.position;\n });\n this._renderTargetTexture.onAfterUnbindObservable.add(function () {\n scene._forcedViewPosition = null;\n scene.updateTransformMatrix(true);\n });\n if (scene.activeCamera) {\n this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);\n }\n }\n Object.defineProperty(ReflectionProbe.prototype, \"samples\", {\n get: function () {\n return this._renderTargetTexture.samples;\n },\n set: function (value) {\n this._renderTargetTexture.samples = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ReflectionProbe.prototype, \"refreshRate\", {\n get: function () {\n return this._renderTargetTexture.refreshRate;\n },\n set: function (value) {\n this._renderTargetTexture.refreshRate = value;\n },\n enumerable: true,\n configurable: true\n });\n ReflectionProbe.prototype.getScene = function () {\n return this._scene;\n };\n Object.defineProperty(ReflectionProbe.prototype, \"cubeTexture\", {\n get: function () {\n return this._renderTargetTexture;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ReflectionProbe.prototype, \"renderList\", {\n get: function () {\n return this._renderTargetTexture.renderList;\n },\n enumerable: true,\n configurable: true\n });\n ReflectionProbe.prototype.attachToMesh = function (mesh) {\n this._attachedMesh = mesh;\n };\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n */\n ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {\n this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);\n };\n ReflectionProbe.prototype.dispose = function () {\n var index = this._scene.reflectionProbes.indexOf(this);\n if (index !== -1) {\n // Remove from the scene if found \n this._scene.reflectionProbes.splice(index, 1);\n }\n if (this._renderTargetTexture) {\n this._renderTargetTexture.dispose();\n this._renderTargetTexture = null;\n }\n };\n return ReflectionProbe;\n }());\n BABYLON.ReflectionProbe = ReflectionProbe;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.reflectionProbe.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the layer scene component responsible to manage any layers\n * in a given scene.\n */\n var LayerSceneComponent = /** @class */ (function () {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n function LayerSceneComponent(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = BABYLON.SceneComponentConstants.NAME_LAYER;\n this.scene = scene;\n this._engine = scene.getEngine();\n scene.layers = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n LayerSceneComponent.prototype.register = function () {\n this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);\n this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);\n };\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n LayerSceneComponent.prototype.rebuild = function () {\n var layers = this.scene.layers;\n for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {\n var layer = layers_1[_i];\n layer._rebuild();\n }\n };\n /**\n * Disposes the component and the associated ressources.\n */\n LayerSceneComponent.prototype.dispose = function () {\n var layers = this.scene.layers;\n while (layers.length) {\n layers[0].dispose();\n }\n };\n LayerSceneComponent.prototype._draw = function (camera, isBackground) {\n var layers = this.scene.layers;\n if (layers.length) {\n this._engine.setDepthBuffer(false);\n var cameraLayerMask = camera.layerMask;\n for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {\n var layer = layers_2[_i];\n if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {\n layer.render();\n }\n }\n this._engine.setDepthBuffer(true);\n }\n };\n LayerSceneComponent.prototype._drawBackground = function (camera) {\n this._draw(camera, true);\n };\n LayerSceneComponent.prototype._drawForeground = function (camera) {\n this._draw(camera, false);\n };\n return LayerSceneComponent;\n }());\n BABYLON.LayerSceneComponent = LayerSceneComponent;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.layerSceneComponent.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Layer = /** @class */ (function () {\n function Layer(name, imgUrl, scene, isBackground, color) {\n this.name = name;\n this.scale = new BABYLON.Vector2(1, 1);\n this.offset = new BABYLON.Vector2(0, 0);\n this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;\n this.layerMask = 0x0FFFFFFF;\n this._vertexBuffers = {};\n // Events\n /**\n * An event triggered when the layer is disposed.\n */\n this.onDisposeObservable = new BABYLON.Observable();\n /**\n * An event triggered before rendering the scene\n */\n this.onBeforeRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered after rendering the scene\n */\n this.onAfterRenderObservable = new BABYLON.Observable();\n this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;\n this.isBackground = isBackground === undefined ? true : isBackground;\n this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;\n this._scene = (scene || BABYLON.Engine.LastCreatedScene);\n var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);\n if (!layerComponent) {\n layerComponent = new BABYLON.LayerSceneComponent(this._scene);\n this._scene._addComponent(layerComponent);\n }\n this._scene.layers.push(this);\n var engine = this._scene.getEngine();\n // VBO\n var vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;\n this._createIndexBuffer();\n // Effects\n this._effect = engine.createEffect(\"layer\", [BABYLON.VertexBuffer.PositionKind], [\"textureMatrix\", \"color\", \"scale\", \"offset\"], [\"textureSampler\"], \"\");\n this._alphaTestEffect = engine.createEffect(\"layer\", [BABYLON.VertexBuffer.PositionKind], [\"textureMatrix\", \"color\", \"scale\", \"offset\"], [\"textureSampler\"], \"#define ALPHATEST\");\n }\n Object.defineProperty(Layer.prototype, \"onDispose\", {\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Layer.prototype, \"onBeforeRender\", {\n set: function (callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Layer.prototype, \"onAfterRender\", {\n set: function (callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Layer.prototype._createIndexBuffer = function () {\n var engine = this._scene.getEngine();\n // Indices\n var indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = engine.createIndexBuffer(indices);\n };\n Layer.prototype._rebuild = function () {\n var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._createIndexBuffer();\n };\n Layer.prototype.render = function () {\n var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;\n // Check\n if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())\n return;\n var engine = this._scene.getEngine();\n this.onBeforeRenderObservable.notifyObservers(this);\n // Render\n engine.enableEffect(currentEffect);\n engine.setState(false);\n // Texture\n currentEffect.setTexture(\"textureSampler\", this.texture);\n currentEffect.setMatrix(\"textureMatrix\", this.texture.getTextureMatrix());\n // Color\n currentEffect.setFloat4(\"color\", this.color.r, this.color.g, this.color.b, this.color.a);\n // Scale / offset\n currentEffect.setVector2(\"offset\", this.offset);\n currentEffect.setVector2(\"scale\", this.scale);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);\n // Draw order\n if (!this.alphaTest) {\n engine.setAlphaMode(this.alphaBlendingMode);\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n }\n else {\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n }\n this.onAfterRenderObservable.notifyObservers(this);\n };\n Layer.prototype.dispose = function () {\n var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n if (this.texture) {\n this.texture.dispose();\n this.texture = null;\n }\n // Remove from scene\n var index = this._scene.layers.indexOf(this);\n this._scene.layers.splice(index, 1);\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onAfterRenderObservable.clear();\n this.onBeforeRenderObservable.clear();\n };\n return Layer;\n }());\n BABYLON.Layer = Layer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.layer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var TextureTools = /** @class */ (function () {\n function TextureTools() {\n }\n /**\n * Uses the GPU to create a copy texture rescaled at a given size\n * @param texture Texture to copy from\n * @param width Desired width\n * @param height Desired height\n * @return Generated texture\n */\n TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {\n if (useBilinearMode === void 0) { useBilinearMode = true; }\n var scene = texture.getScene();\n var engine = scene.getEngine();\n var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);\n rtt.wrapU = texture.wrapU;\n rtt.wrapV = texture.wrapV;\n rtt.uOffset = texture.uOffset;\n rtt.vOffset = texture.vOffset;\n rtt.uScale = texture.uScale;\n rtt.vScale = texture.vScale;\n rtt.uAng = texture.uAng;\n rtt.vAng = texture.vAng;\n rtt.wAng = texture.wAng;\n rtt.coordinatesIndex = texture.coordinatesIndex;\n rtt.level = texture.level;\n rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;\n rtt._texture.isReady = false;\n texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n var passPostProcess = new BABYLON.PassPostProcess(\"pass\", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n passPostProcess.getEffect().executeWhenCompiled(function () {\n passPostProcess.onApply = function (effect) {\n effect.setTexture(\"textureSampler\", texture);\n };\n var internalTexture = rtt.getInternalTexture();\n if (internalTexture) {\n scene.postProcessManager.directRender([passPostProcess], internalTexture);\n engine.unBindFramebuffer(internalTexture);\n rtt.disposeFramebufferObjects();\n passPostProcess.dispose();\n internalTexture.isReady = true;\n }\n });\n return rtt;\n };\n TextureTools.GetEnvironmentBRDFTexture = function (scene) {\n if (!scene._environmentBRDFTexture) {\n var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, \"EnvironmentBRDFTexture\", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n scene._environmentBRDFTexture = texture;\n }\n return scene._environmentBRDFTexture;\n };\n TextureTools._environmentBRDFBase64Texture = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=\";\n return TextureTools;\n }());\n BABYLON.TextureTools = TextureTools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.textureTools.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var FramingBehavior = /** @class */ (function () {\n function FramingBehavior() {\n this._mode = FramingBehavior.FitFrustumSidesMode;\n this._radiusScale = 1.0;\n this._positionScale = 0.5;\n this._defaultElevation = 0.3;\n this._elevationReturnTime = 1500;\n this._elevationReturnWaitTime = 1000;\n this._zoomStopsAnimation = false;\n this._framingTime = 1500;\n this._isPointerDown = false;\n this._lastInteractionTime = -Infinity;\n // Framing control\n this._animatables = new Array();\n this._betaIsAnimating = false;\n }\n Object.defineProperty(FramingBehavior.prototype, \"name\", {\n get: function () {\n return \"Framing\";\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"mode\", {\n /**\n * Gets current mode used by the behavior.\n */\n get: function () {\n return this._mode;\n },\n /**\n * Sets the current mode used by the behavior\n */\n set: function (mode) {\n this._mode = mode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"radiusScale\", {\n /**\n * Gets the scale applied to the radius\n */\n get: function () {\n return this._radiusScale;\n },\n /**\n * Sets the scale applied to the radius (1 by default)\n */\n set: function (radius) {\n this._radiusScale = radius;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"positionScale\", {\n /**\n * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.\n */\n get: function () {\n return this._positionScale;\n },\n /**\n * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.\n */\n set: function (scale) {\n this._positionScale = scale;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"defaultElevation\", {\n /**\n * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle\n * behaviour is triggered, in radians.\n */\n get: function () {\n return this._defaultElevation;\n },\n /**\n * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle\n * behaviour is triggered, in radians.\n */\n set: function (elevation) {\n this._defaultElevation = elevation;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"elevationReturnTime\", {\n /**\n * Gets the time (in milliseconds) taken to return to the default beta position.\n * Negative value indicates camera should not return to default.\n */\n get: function () {\n return this._elevationReturnTime;\n },\n /**\n * Sets the time (in milliseconds) taken to return to the default beta position.\n * Negative value indicates camera should not return to default.\n */\n set: function (speed) {\n this._elevationReturnTime = speed;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"elevationReturnWaitTime\", {\n /**\n * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.\n */\n get: function () {\n return this._elevationReturnWaitTime;\n },\n /**\n * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.\n */\n set: function (time) {\n this._elevationReturnWaitTime = time;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"zoomStopsAnimation\", {\n /**\n * Gets the flag that indicates if user zooming should stop animation.\n */\n get: function () {\n return this._zoomStopsAnimation;\n },\n /**\n * Sets the flag that indicates if user zooming should stop animation.\n */\n set: function (flag) {\n this._zoomStopsAnimation = flag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"framingTime\", {\n /**\n * Gets the transition time when framing the mesh, in milliseconds\n */\n get: function () {\n return this._framingTime;\n },\n /**\n * Sets the transition time when framing the mesh, in milliseconds\n */\n set: function (time) {\n this._framingTime = time;\n },\n enumerable: true,\n configurable: true\n });\n FramingBehavior.prototype.init = function () {\n // Do notihng\n };\n FramingBehavior.prototype.attach = function (camera) {\n var _this = this;\n this._attachedCamera = camera;\n var scene = this._attachedCamera.getScene();\n FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);\n this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {\n if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {\n _this._isPointerDown = true;\n return;\n }\n if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {\n _this._isPointerDown = false;\n }\n });\n this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {\n if (mesh) {\n _this.zoomOnMesh(mesh);\n }\n });\n this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {\n // Stop the animation if there is user interaction and the animation should stop for this interaction\n _this._applyUserInteraction();\n // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it\n // back to the default position after a given timeout\n _this._maintainCameraAboveGround();\n });\n };\n FramingBehavior.prototype.detach = function () {\n if (!this._attachedCamera) {\n return;\n }\n var scene = this._attachedCamera.getScene();\n if (this._onPrePointerObservableObserver) {\n scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);\n }\n if (this._onAfterCheckInputsObserver) {\n this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);\n }\n if (this._onMeshTargetChangedObserver) {\n this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);\n }\n this._attachedCamera = null;\n };\n /**\n * Targets the given mesh and updates zoom level accordingly.\n * @param mesh The mesh to target.\n * @param radius Optional. If a cached radius position already exists, overrides default.\n * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {\n if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }\n if (onAnimationEnd === void 0) { onAnimationEnd = null; }\n mesh.computeWorldMatrix(true);\n var boundingBox = mesh.getBoundingInfo().boundingBox;\n this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);\n };\n /**\n * Targets the given mesh with its children and updates zoom level accordingly.\n * @param mesh The mesh to target.\n * @param radius Optional. If a cached radius position already exists, overrides default.\n * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {\n if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }\n if (onAnimationEnd === void 0) { onAnimationEnd = null; }\n mesh.computeWorldMatrix(true);\n var boundingBox = mesh.getHierarchyBoundingVectors(true);\n this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);\n };\n /**\n * Targets the given meshes with their children and updates zoom level accordingly.\n * @param meshes The mesh to target.\n * @param radius Optional. If a cached radius position already exists, overrides default.\n * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {\n if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }\n if (onAnimationEnd === void 0) { onAnimationEnd = null; }\n var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n for (var i = 0; i < meshes.length; i++) {\n var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);\n BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);\n BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);\n }\n this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);\n };\n /**\n * Targets the given mesh and updates zoom level accordingly.\n * @param mesh The mesh to target.\n * @param radius Optional. If a cached radius position already exists, overrides default.\n * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {\n var _this = this;\n if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }\n if (onAnimationEnd === void 0) { onAnimationEnd = null; }\n var zoomTarget;\n if (!this._attachedCamera) {\n return;\n }\n // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY\n var bottom = minimumWorld.y;\n var top = maximumWorld.y;\n var zoomTargetY = bottom + (top - bottom) * this._positionScale;\n var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);\n if (focusOnOriginXZ) {\n zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);\n }\n else {\n var centerWorld = minimumWorld.add(radiusWorld);\n zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);\n }\n if (!this._vectorTransition) {\n this._vectorTransition = BABYLON.Animation.CreateAnimation(\"target\", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);\n }\n this._betaIsAnimating = true;\n var animatable = BABYLON.Animation.TransitionTo(\"target\", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);\n if (animatable) {\n this._animatables.push(animatable);\n }\n // sets the radius and lower radius bounds\n // Small delta ensures camera is not always at lower zoom limit.\n var radius = 0;\n if (this._mode === FramingBehavior.FitFrustumSidesMode) {\n var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);\n this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;\n radius = position;\n }\n else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {\n radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);\n if (this._attachedCamera.lowerRadiusLimit === null) {\n this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;\n }\n }\n // Set sensibilities\n var extend = maximumWorld.subtract(minimumWorld).length();\n this._attachedCamera.panningSensibility = 5000 / extend;\n this._attachedCamera.wheelPrecision = 100 / radius;\n // transition to new radius\n if (!this._radiusTransition) {\n this._radiusTransition = BABYLON.Animation.CreateAnimation(\"radius\", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);\n }\n animatable = BABYLON.Animation.TransitionTo(\"radius\", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {\n _this.stopAllAnimations();\n if (onAnimationEnd) {\n onAnimationEnd();\n }\n if (_this._attachedCamera) {\n _this._attachedCamera.storeState();\n }\n });\n if (animatable) {\n this._animatables.push(animatable);\n }\n };\n /**\n * Calculates the lowest radius for the camera based on the bounding box of the mesh.\n * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary\n *\t\t\t frustum width.\n * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order\n *\t\t to fully enclose the mesh in the viewing frustum.\n */\n FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {\n var size = maximumWorld.subtract(minimumWorld);\n var boxVectorGlobalDiagonal = size.length();\n var frustumSlope = this._getFrustumSlope();\n // Formula for setting distance\n // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)\n var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;\n // Horizon distance\n var radius = radiusWithoutFraming * this._radiusScale;\n var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));\n var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));\n var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);\n var camera = this._attachedCamera;\n if (!camera) {\n return 0;\n }\n if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {\n // Don't exceed the requested limit\n distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;\n }\n // Don't exceed the upper radius limit\n if (camera.upperRadiusLimit) {\n distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;\n }\n return distance;\n };\n /**\n * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera\n * is automatically returned to its default position (expected to be above ground plane).\n */\n FramingBehavior.prototype._maintainCameraAboveGround = function () {\n var _this = this;\n if (this._elevationReturnTime < 0) {\n return;\n }\n var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;\n var defaultBeta = Math.PI * 0.5 - this._defaultElevation;\n var limitBeta = Math.PI * 0.5;\n // Bring the camera back up if below the ground plane\n if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {\n this._betaIsAnimating = true;\n //Transition to new position\n this.stopAllAnimations();\n if (!this._betaTransition) {\n this._betaTransition = BABYLON.Animation.CreateAnimation(\"beta\", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);\n }\n var animatabe = BABYLON.Animation.TransitionTo(\"beta\", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {\n _this._clearAnimationLocks();\n _this.stopAllAnimations();\n });\n if (animatabe) {\n this._animatables.push(animatabe);\n }\n }\n };\n /**\n * Returns the frustum slope based on the canvas ratio and camera FOV\n * @returns The frustum slope represented as a Vector2 with X and Y slopes\n */\n FramingBehavior.prototype._getFrustumSlope = function () {\n // Calculate the viewport ratio\n // Aspect Ratio is Height/Width.\n var camera = this._attachedCamera;\n if (!camera) {\n return BABYLON.Vector2.Zero();\n }\n var engine = camera.getScene().getEngine();\n var aspectRatio = engine.getAspectRatio(camera);\n // Camera FOV is the vertical field of view (top-bottom) in radians.\n // Slope of the frustum top/bottom planes in view space, relative to the forward vector.\n var frustumSlopeY = Math.tan(camera.fov / 2);\n // Slope of the frustum left/right planes in view space, relative to the forward vector.\n // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit\n // along the forward vector.\n var frustumSlopeX = frustumSlopeY * aspectRatio;\n return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);\n };\n /**\n * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.\n */\n FramingBehavior.prototype._clearAnimationLocks = function () {\n this._betaIsAnimating = false;\n };\n /**\n * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.\n */\n FramingBehavior.prototype._applyUserInteraction = function () {\n if (this.isUserIsMoving) {\n this._lastInteractionTime = BABYLON.Tools.Now;\n this.stopAllAnimations();\n this._clearAnimationLocks();\n }\n };\n /**\n * Stops and removes all animations that have been applied to the camera\n */\n FramingBehavior.prototype.stopAllAnimations = function () {\n if (this._attachedCamera) {\n this._attachedCamera.animations = [];\n }\n while (this._animatables.length) {\n if (this._animatables[0]) {\n this._animatables[0].onAnimationEnd = null;\n this._animatables[0].stop();\n }\n this._animatables.shift();\n }\n };\n Object.defineProperty(FramingBehavior.prototype, \"isUserIsMoving\", {\n /**\n * Gets a value indicating if the user is moving the camera\n */\n get: function () {\n if (!this._attachedCamera) {\n return false;\n }\n return this._attachedCamera.inertialAlphaOffset !== 0 ||\n this._attachedCamera.inertialBetaOffset !== 0 ||\n this._attachedCamera.inertialRadiusOffset !== 0 ||\n this._attachedCamera.inertialPanningX !== 0 ||\n this._attachedCamera.inertialPanningY !== 0 ||\n this._isPointerDown;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * The easing function used by animations\n */\n FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();\n /**\n * The easing mode used by animations\n */\n FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;\n // Statics\n /**\n * The camera can move all the way towards the mesh.\n */\n FramingBehavior.IgnoreBoundsSizeMode = 0;\n /**\n * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides\n */\n FramingBehavior.FitFrustumSidesMode = 1;\n return FramingBehavior;\n }());\n BABYLON.FramingBehavior = FramingBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.framingBehavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius\n */\n var BouncingBehavior = /** @class */ (function () {\n function BouncingBehavior() {\n /**\n * The duration of the animation, in milliseconds\n */\n this.transitionDuration = 450;\n /**\n * Length of the distance animated by the transition when lower radius is reached\n */\n this.lowerRadiusTransitionRange = 2;\n /**\n * Length of the distance animated by the transition when upper radius is reached\n */\n this.upperRadiusTransitionRange = -2;\n this._autoTransitionRange = false;\n // Animations\n this._radiusIsAnimating = false;\n this._radiusBounceTransition = null;\n this._animatables = new Array();\n }\n Object.defineProperty(BouncingBehavior.prototype, \"name\", {\n get: function () {\n return \"Bouncing\";\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BouncingBehavior.prototype, \"autoTransitionRange\", {\n /**\n * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically\n */\n get: function () {\n return this._autoTransitionRange;\n },\n /**\n * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically\n * Transition ranges will be set to 5% of the bounding box diagonal in world space\n */\n set: function (value) {\n var _this = this;\n if (this._autoTransitionRange === value) {\n return;\n }\n this._autoTransitionRange = value;\n var camera = this._attachedCamera;\n if (!camera) {\n return;\n }\n if (value) {\n this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {\n if (!mesh) {\n return;\n }\n mesh.computeWorldMatrix(true);\n var diagonal = mesh.getBoundingInfo().diagonalLength;\n _this.lowerRadiusTransitionRange = diagonal * 0.05;\n _this.upperRadiusTransitionRange = diagonal * 0.05;\n });\n }\n else if (this._onMeshTargetChangedObserver) {\n camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);\n }\n },\n enumerable: true,\n configurable: true\n });\n BouncingBehavior.prototype.init = function () {\n // Do notihng\n };\n BouncingBehavior.prototype.attach = function (camera) {\n var _this = this;\n this._attachedCamera = camera;\n this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {\n if (!_this._attachedCamera) {\n return;\n }\n // Add the bounce animation to the lower radius limit\n if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {\n _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);\n }\n // Add the bounce animation to the upper radius limit\n if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {\n _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);\n }\n });\n };\n BouncingBehavior.prototype.detach = function () {\n if (!this._attachedCamera) {\n return;\n }\n if (this._onAfterCheckInputsObserver) {\n this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);\n }\n if (this._onMeshTargetChangedObserver) {\n this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);\n }\n this._attachedCamera = null;\n };\n /**\n * Checks if the camera radius is at the specified limit. Takes into account animation locks.\n * @param radiusLimit The limit to check against.\n * @return Bool to indicate if at limit.\n */\n BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {\n if (!this._attachedCamera) {\n return false;\n }\n if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {\n return true;\n }\n return false;\n };\n /**\n * Applies an animation to the radius of the camera, extending by the radiusDelta.\n * @param radiusDelta The delta by which to animate to. Can be negative.\n */\n BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {\n var _this = this;\n if (!this._attachedCamera) {\n return;\n }\n if (!this._radiusBounceTransition) {\n BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);\n this._radiusBounceTransition = BABYLON.Animation.CreateAnimation(\"radius\", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);\n }\n // Prevent zoom until bounce has completed\n this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;\n this._attachedCamera.wheelPrecision = Infinity;\n this._attachedCamera.inertialRadiusOffset = 0;\n // Animate to the radius limit\n this.stopAllAnimations();\n this._radiusIsAnimating = true;\n var animatable = BABYLON.Animation.TransitionTo(\"radius\", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });\n if (animatable) {\n this._animatables.push(animatable);\n }\n };\n /**\n * Removes all animation locks. Allows new animations to be added to any of the camera properties.\n */\n BouncingBehavior.prototype._clearAnimationLocks = function () {\n this._radiusIsAnimating = false;\n if (this._attachedCamera) {\n this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;\n }\n };\n /**\n * Stops and removes all animations that have been applied to the camera\n */\n BouncingBehavior.prototype.stopAllAnimations = function () {\n if (this._attachedCamera) {\n this._attachedCamera.animations = [];\n }\n while (this._animatables.length) {\n this._animatables[0].onAnimationEnd = null;\n this._animatables[0].stop();\n this._animatables.shift();\n }\n };\n /**\n * The easing function used by animations\n */\n BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);\n /**\n * The easing mode used by animations\n */\n BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;\n return BouncingBehavior;\n }());\n BABYLON.BouncingBehavior = BouncingBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.bouncingBehavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var AutoRotationBehavior = /** @class */ (function () {\n function AutoRotationBehavior() {\n this._zoomStopsAnimation = false;\n this._idleRotationSpeed = 0.05;\n this._idleRotationWaitTime = 2000;\n this._idleRotationSpinupTime = 2000;\n this._isPointerDown = false;\n this._lastFrameTime = null;\n this._lastInteractionTime = -Infinity;\n this._cameraRotationSpeed = 0;\n this._lastFrameRadius = 0;\n }\n Object.defineProperty(AutoRotationBehavior.prototype, \"name\", {\n get: function () {\n return \"AutoRotation\";\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AutoRotationBehavior.prototype, \"zoomStopsAnimation\", {\n /**\n * Gets the flag that indicates if user zooming should stop animation.\n */\n get: function () {\n return this._zoomStopsAnimation;\n },\n /**\n * Sets the flag that indicates if user zooming should stop animation.\n */\n set: function (flag) {\n this._zoomStopsAnimation = flag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AutoRotationBehavior.prototype, \"idleRotationSpeed\", {\n /**\n * Gets the default speed at which the camera rotates around the model.\n */\n get: function () {\n return this._idleRotationSpeed;\n },\n /**\n * Sets the default speed at which the camera rotates around the model.\n */\n set: function (speed) {\n this._idleRotationSpeed = speed;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AutoRotationBehavior.prototype, \"idleRotationWaitTime\", {\n /**\n * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.\n */\n get: function () {\n return this._idleRotationWaitTime;\n },\n /**\n * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.\n */\n set: function (time) {\n this._idleRotationWaitTime = time;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AutoRotationBehavior.prototype, \"idleRotationSpinupTime\", {\n /**\n * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.\n */\n get: function () {\n return this._idleRotationSpinupTime;\n },\n /**\n * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.\n */\n set: function (time) {\n this._idleRotationSpinupTime = time;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AutoRotationBehavior.prototype, \"rotationInProgress\", {\n /**\n * Gets a value indicating if the camera is currently rotating because of this behavior\n */\n get: function () {\n return Math.abs(this._cameraRotationSpeed) > 0;\n },\n enumerable: true,\n configurable: true\n });\n AutoRotationBehavior.prototype.init = function () {\n // Do notihng\n };\n AutoRotationBehavior.prototype.attach = function (camera) {\n var _this = this;\n this._attachedCamera = camera;\n var scene = this._attachedCamera.getScene();\n this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {\n if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {\n _this._isPointerDown = true;\n return;\n }\n if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {\n _this._isPointerDown = false;\n }\n });\n this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {\n var now = BABYLON.Tools.Now;\n var dt = 0;\n if (_this._lastFrameTime != null) {\n dt = now - _this._lastFrameTime;\n }\n _this._lastFrameTime = now;\n // Stop the animation if there is user interaction and the animation should stop for this interaction\n _this._applyUserInteraction();\n var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;\n var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);\n _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;\n // Step camera rotation by rotation speed\n if (_this._attachedCamera) {\n _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);\n }\n });\n };\n AutoRotationBehavior.prototype.detach = function () {\n if (!this._attachedCamera) {\n return;\n }\n var scene = this._attachedCamera.getScene();\n if (this._onPrePointerObservableObserver) {\n scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);\n }\n this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);\n this._attachedCamera = null;\n };\n /**\n * Returns true if user is scrolling.\n * @return true if user is scrolling.\n */\n AutoRotationBehavior.prototype._userIsZooming = function () {\n if (!this._attachedCamera) {\n return false;\n }\n return this._attachedCamera.inertialRadiusOffset !== 0;\n };\n AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {\n if (!this._attachedCamera) {\n return false;\n }\n var zoomHasHitLimit = false;\n if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {\n zoomHasHitLimit = true;\n }\n // Update the record of previous radius - works as an approx. indicator of hitting radius limits\n this._lastFrameRadius = this._attachedCamera.radius;\n return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();\n };\n /**\n * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.\n */\n AutoRotationBehavior.prototype._applyUserInteraction = function () {\n if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {\n this._lastInteractionTime = BABYLON.Tools.Now;\n }\n };\n // Tools\n AutoRotationBehavior.prototype._userIsMoving = function () {\n if (!this._attachedCamera) {\n return false;\n }\n return this._attachedCamera.inertialAlphaOffset !== 0 ||\n this._attachedCamera.inertialBetaOffset !== 0 ||\n this._attachedCamera.inertialRadiusOffset !== 0 ||\n this._attachedCamera.inertialPanningX !== 0 ||\n this._attachedCamera.inertialPanningY !== 0 ||\n this._isPointerDown;\n };\n return AutoRotationBehavior;\n }());\n BABYLON.AutoRotationBehavior = AutoRotationBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.autoRotationBehavior.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var NullEngineOptions = /** @class */ (function () {\n function NullEngineOptions() {\n this.renderWidth = 512;\n this.renderHeight = 256;\n this.textureSize = 512;\n this.deterministicLockstep = false;\n this.lockstepMaxSteps = 4;\n }\n return NullEngineOptions;\n }());\n BABYLON.NullEngineOptions = NullEngineOptions;\n /**\n * The null engine class provides support for headless version of babylon.js.\n * This can be used in server side scenario or for testing purposes\n */\n var NullEngine = /** @class */ (function (_super) {\n __extends(NullEngine, _super);\n function NullEngine(options) {\n if (options === void 0) { options = new NullEngineOptions(); }\n var _this = _super.call(this, null) || this;\n if (options.deterministicLockstep === undefined) {\n options.deterministicLockstep = false;\n }\n if (options.lockstepMaxSteps === undefined) {\n options.lockstepMaxSteps = 4;\n }\n _this._options = options;\n // Init caps\n // We consider we are on a webgl1 capable device\n _this._caps = new BABYLON.EngineCapabilities();\n _this._caps.maxTexturesImageUnits = 16;\n _this._caps.maxVertexTextureImageUnits = 16;\n _this._caps.maxTextureSize = 512;\n _this._caps.maxCubemapTextureSize = 512;\n _this._caps.maxRenderTextureSize = 512;\n _this._caps.maxVertexAttribs = 16;\n _this._caps.maxVaryingVectors = 16;\n _this._caps.maxFragmentUniformVectors = 16;\n _this._caps.maxVertexUniformVectors = 16;\n // Extensions\n _this._caps.standardDerivatives = false;\n _this._caps.astc = null;\n _this._caps.s3tc = null;\n _this._caps.pvrtc = null;\n _this._caps.etc1 = null;\n _this._caps.etc2 = null;\n _this._caps.textureAnisotropicFilterExtension = null;\n _this._caps.maxAnisotropy = 0;\n _this._caps.uintIndices = false;\n _this._caps.fragmentDepthSupported = false;\n _this._caps.highPrecisionShaderSupported = true;\n _this._caps.colorBufferFloat = false;\n _this._caps.textureFloat = false;\n _this._caps.textureFloatLinearFiltering = false;\n _this._caps.textureFloatRender = false;\n _this._caps.textureHalfFloat = false;\n _this._caps.textureHalfFloatLinearFiltering = false;\n _this._caps.textureHalfFloatRender = false;\n _this._caps.textureLOD = false;\n _this._caps.drawBuffersExtension = false;\n _this._caps.depthTextureExtension = false;\n _this._caps.vertexArrayObject = false;\n _this._caps.instancedArrays = false;\n BABYLON.Tools.Log(\"Babylon.js null engine (v\" + BABYLON.Engine.Version + \") launched\");\n // Wrappers\n if (typeof URL === \"undefined\") {\n URL = {\n createObjectURL: function () { },\n revokeObjectURL: function () { }\n };\n }\n if (typeof Blob === \"undefined\") {\n Blob = function () { };\n }\n return _this;\n }\n NullEngine.prototype.isDeterministicLockStep = function () {\n return this._options.deterministicLockstep;\n };\n NullEngine.prototype.getLockstepMaxSteps = function () {\n return this._options.lockstepMaxSteps;\n };\n NullEngine.prototype.getHardwareScalingLevel = function () {\n return 1.0;\n };\n NullEngine.prototype.createVertexBuffer = function (vertices) {\n return {\n capacity: 0,\n references: 1,\n is32Bits: false\n };\n };\n NullEngine.prototype.createIndexBuffer = function (indices) {\n return {\n capacity: 0,\n references: 1,\n is32Bits: false\n };\n };\n NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {\n if (stencil === void 0) { stencil = false; }\n };\n NullEngine.prototype.getRenderWidth = function (useScreen) {\n if (useScreen === void 0) { useScreen = false; }\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.width;\n }\n return this._options.renderWidth;\n };\n NullEngine.prototype.getRenderHeight = function (useScreen) {\n if (useScreen === void 0) { useScreen = false; }\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.height;\n }\n return this._options.renderHeight;\n };\n NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {\n this._cachedViewport = viewport;\n };\n NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {\n return {\n transformFeedback: null,\n __SPECTOR_rebuildProgram: null\n };\n };\n NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {\n return [];\n };\n NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {\n return [];\n };\n NullEngine.prototype.bindSamplers = function (effect) {\n this._currentEffect = null;\n };\n NullEngine.prototype.enableEffect = function (effect) {\n this._currentEffect = effect;\n if (effect.onBind) {\n effect.onBind(effect);\n }\n effect.onBindObservable.notifyObservers(effect);\n };\n NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {\n if (zOffset === void 0) { zOffset = 0; }\n if (reverseSide === void 0) { reverseSide = false; }\n };\n NullEngine.prototype.setIntArray = function (uniform, array) {\n };\n NullEngine.prototype.setIntArray2 = function (uniform, array) {\n };\n NullEngine.prototype.setIntArray3 = function (uniform, array) {\n };\n NullEngine.prototype.setIntArray4 = function (uniform, array) {\n };\n NullEngine.prototype.setFloatArray = function (uniform, array) {\n };\n NullEngine.prototype.setFloatArray2 = function (uniform, array) {\n };\n NullEngine.prototype.setFloatArray3 = function (uniform, array) {\n };\n NullEngine.prototype.setFloatArray4 = function (uniform, array) {\n };\n NullEngine.prototype.setArray = function (uniform, array) {\n };\n NullEngine.prototype.setArray2 = function (uniform, array) {\n };\n NullEngine.prototype.setArray3 = function (uniform, array) {\n };\n NullEngine.prototype.setArray4 = function (uniform, array) {\n };\n NullEngine.prototype.setMatrices = function (uniform, matrices) {\n };\n NullEngine.prototype.setMatrix = function (uniform, matrix) {\n };\n NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {\n };\n NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {\n };\n NullEngine.prototype.setFloat = function (uniform, value) {\n };\n NullEngine.prototype.setFloat2 = function (uniform, x, y) {\n };\n NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {\n };\n NullEngine.prototype.setBool = function (uniform, bool) {\n };\n NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {\n };\n NullEngine.prototype.setColor3 = function (uniform, color3) {\n };\n NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {\n };\n NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {\n if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }\n if (this._alphaMode === mode) {\n return;\n }\n this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);\n if (!noDepthWriteChange) {\n this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);\n }\n this._alphaMode = mode;\n };\n NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {\n };\n NullEngine.prototype.wipeCaches = function (bruteForce) {\n if (this.preventCacheWipeBetweenFrames) {\n return;\n }\n this.resetTextureCache();\n this._currentEffect = null;\n if (bruteForce) {\n this._currentProgram = null;\n this._stencilState.reset();\n this._depthCullingState.reset();\n this._alphaState.reset();\n }\n this._cachedVertexBuffers = null;\n this._cachedIndexBuffer = null;\n this._cachedEffectForVertexBuffers = null;\n };\n NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {\n };\n NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {\n };\n NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {\n };\n NullEngine.prototype._createTexture = function () {\n return {};\n };\n NullEngine.prototype._releaseTexture = function (texture) {\n };\n NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (buffer === void 0) { buffer = null; }\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);\n var url = String(urlArg);\n texture.url = url;\n texture.generateMipMaps = !noMipmap;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture.baseWidth = this._options.textureSize;\n texture.baseHeight = this._options.textureSize;\n texture.width = this._options.textureSize;\n texture.height = this._options.textureSize;\n if (format) {\n texture.format = format;\n }\n texture.isReady = true;\n if (onLoad) {\n onLoad();\n }\n this._internalTexturesCache.push(texture);\n return texture;\n };\n NullEngine.prototype.createRenderTargetTexture = function (size, options) {\n var fullOptions = new BABYLON.RenderTargetCreationOptions();\n if (options !== undefined && typeof options === \"object\") {\n fullOptions.generateMipMaps = options.generateMipMaps;\n fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;\n fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;\n fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;\n }\n else {\n fullOptions.generateMipMaps = options;\n fullOptions.generateDepthBuffer = true;\n fullOptions.generateStencilBuffer = false;\n fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;\n }\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);\n var width = size.width || size;\n var height = size.height || size;\n texture._depthStencilBuffer = {};\n texture._framebuffer = {};\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n texture.samples = 1;\n texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n texture._generateDepthBuffer = fullOptions.generateDepthBuffer;\n texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;\n this._internalTexturesCache.push(texture);\n return texture;\n };\n NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {\n texture.samplingMode = samplingMode;\n };\n NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n this._currentRenderTarget = texture;\n this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;\n if (this._cachedViewport && !forceFullscreenViewport) {\n this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);\n }\n };\n NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {\n if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }\n this._currentRenderTarget = null;\n if (onBeforeUnbind) {\n if (texture._MSAAFramebuffer) {\n this._currentFramebuffer = texture._framebuffer;\n }\n onBeforeUnbind();\n }\n this._currentFramebuffer = null;\n };\n NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {\n var vbo = {\n capacity: 1,\n references: 1,\n is32Bits: false\n };\n return vbo;\n };\n NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {\n if (premulAlpha === void 0) { premulAlpha = false; }\n };\n /**\n * Get the current error code of the webGL context\n * @returns the error code\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError\n */\n NullEngine.prototype.getError = function () {\n return 0;\n };\n /** @hidden */\n NullEngine.prototype._getUnpackAlignement = function () {\n return 1;\n };\n /** @hidden */\n NullEngine.prototype._unpackFlipY = function (value) {\n };\n NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {\n if (offset === void 0) { offset = 0; }\n };\n /**\n * Updates a dynamic vertex buffer.\n * @param vertexBuffer the vertex buffer to update\n * @param data the data used to update the vertex buffer\n * @param byteOffset the byte offset of the data (optional)\n * @param byteLength the byte length of the data (optional)\n */\n NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {\n };\n NullEngine.prototype._bindTextureDirectly = function (target, texture) {\n if (this._boundTexturesCache[this._activeChannel] !== texture) {\n this._boundTexturesCache[this._activeChannel] = texture;\n return true;\n }\n return false;\n };\n NullEngine.prototype._bindTexture = function (channel, texture) {\n if (channel < 0) {\n return;\n }\n this._bindTextureDirectly(0, texture);\n };\n NullEngine.prototype._releaseBuffer = function (buffer) {\n buffer.references--;\n if (buffer.references === 0) {\n return true;\n }\n return false;\n };\n NullEngine.prototype.releaseEffects = function () {\n };\n NullEngine.prototype.displayLoadingUI = function () {\n };\n NullEngine.prototype.hideLoadingUI = function () {\n };\n /** @hidden */\n NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n };\n /** @hidden */\n NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n };\n /** @hidden */\n NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n };\n /** @hidden */\n NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n };\n return NullEngine;\n }(BABYLON.Engine));\n BABYLON.NullEngine = NullEngine;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.nullEngine.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class can be used to get instrumentation data from a Babylon engine\n */\n var EngineInstrumentation = /** @class */ (function () {\n function EngineInstrumentation(engine) {\n this.engine = engine;\n this._captureGPUFrameTime = false;\n this._gpuFrameTime = new BABYLON.PerfCounter();\n this._captureShaderCompilationTime = false;\n this._shaderCompilationTime = new BABYLON.PerfCounter();\n // Observers\n this._onBeginFrameObserver = null;\n this._onEndFrameObserver = null;\n this._onBeforeShaderCompilationObserver = null;\n this._onAfterShaderCompilationObserver = null;\n }\n Object.defineProperty(EngineInstrumentation.prototype, \"gpuFrameTimeCounter\", {\n // Properties\n /**\n * Gets the perf counter used for GPU frame time\n */\n get: function () {\n return this._gpuFrameTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EngineInstrumentation.prototype, \"captureGPUFrameTime\", {\n /**\n * Gets the GPU frame time capture status\n */\n get: function () {\n return this._captureGPUFrameTime;\n },\n /**\n * Enable or disable the GPU frame time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureGPUFrameTime) {\n return;\n }\n this._captureGPUFrameTime = value;\n if (value) {\n this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {\n if (!_this._gpuFrameTimeToken) {\n _this._gpuFrameTimeToken = _this.engine.startTimeQuery();\n }\n });\n this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {\n if (!_this._gpuFrameTimeToken) {\n return;\n }\n var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);\n if (time > -1) {\n _this._gpuFrameTimeToken = null;\n _this._gpuFrameTime.fetchNewFrame();\n _this._gpuFrameTime.addCount(time, true);\n }\n });\n }\n else {\n this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);\n this._onBeginFrameObserver = null;\n this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);\n this._onEndFrameObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EngineInstrumentation.prototype, \"shaderCompilationTimeCounter\", {\n /**\n * Gets the perf counter used for shader compilation time\n */\n get: function () {\n return this._shaderCompilationTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EngineInstrumentation.prototype, \"captureShaderCompilationTime\", {\n /**\n * Gets the shader compilation time capture status\n */\n get: function () {\n return this._captureShaderCompilationTime;\n },\n /**\n * Enable or disable the shader compilation time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureShaderCompilationTime) {\n return;\n }\n this._captureShaderCompilationTime = value;\n if (value) {\n this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {\n _this._shaderCompilationTime.fetchNewFrame();\n _this._shaderCompilationTime.beginMonitoring();\n });\n this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {\n _this._shaderCompilationTime.endMonitoring();\n });\n }\n else {\n this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);\n this._onBeforeShaderCompilationObserver = null;\n this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);\n this._onAfterShaderCompilationObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n EngineInstrumentation.prototype.dispose = function () {\n this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);\n this._onBeginFrameObserver = null;\n this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);\n this._onEndFrameObserver = null;\n this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);\n this._onBeforeShaderCompilationObserver = null;\n this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);\n this._onAfterShaderCompilationObserver = null;\n this.engine = null;\n };\n return EngineInstrumentation;\n }());\n BABYLON.EngineInstrumentation = EngineInstrumentation;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.engineInstrumentation.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class can be used to get instrumentation data from a Babylon engine\n */\n var SceneInstrumentation = /** @class */ (function () {\n function SceneInstrumentation(scene) {\n var _this = this;\n this.scene = scene;\n this._captureActiveMeshesEvaluationTime = false;\n this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();\n this._captureRenderTargetsRenderTime = false;\n this._renderTargetsRenderTime = new BABYLON.PerfCounter();\n this._captureFrameTime = false;\n this._frameTime = new BABYLON.PerfCounter();\n this._captureRenderTime = false;\n this._renderTime = new BABYLON.PerfCounter();\n this._captureInterFrameTime = false;\n this._interFrameTime = new BABYLON.PerfCounter();\n this._captureParticlesRenderTime = false;\n this._particlesRenderTime = new BABYLON.PerfCounter();\n this._captureSpritesRenderTime = false;\n this._spritesRenderTime = new BABYLON.PerfCounter();\n this._capturePhysicsTime = false;\n this._physicsTime = new BABYLON.PerfCounter();\n this._captureAnimationsTime = false;\n this._animationsTime = new BABYLON.PerfCounter();\n this._captureCameraRenderTime = false;\n this._cameraRenderTime = new BABYLON.PerfCounter();\n // Observers\n this._onBeforeActiveMeshesEvaluationObserver = null;\n this._onAfterActiveMeshesEvaluationObserver = null;\n this._onBeforeRenderTargetsRenderObserver = null;\n this._onAfterRenderTargetsRenderObserver = null;\n this._onAfterRenderObserver = null;\n this._onBeforeDrawPhaseObserver = null;\n this._onAfterDrawPhaseObserver = null;\n this._onBeforeAnimationsObserver = null;\n this._onBeforeParticlesRenderingObserver = null;\n this._onAfterParticlesRenderingObserver = null;\n this._onBeforeSpritesRenderingObserver = null;\n this._onAfterSpritesRenderingObserver = null;\n this._onBeforePhysicsObserver = null;\n this._onAfterPhysicsObserver = null;\n this._onAfterAnimationsObserver = null;\n this._onBeforeCameraRenderObserver = null;\n this._onAfterCameraRenderObserver = null;\n // Before render\n this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {\n if (_this._captureActiveMeshesEvaluationTime) {\n _this._activeMeshesEvaluationTime.fetchNewFrame();\n }\n if (_this._captureRenderTargetsRenderTime) {\n _this._renderTargetsRenderTime.fetchNewFrame();\n }\n if (_this._captureFrameTime) {\n BABYLON.Tools.StartPerformanceCounter(\"Scene rendering\");\n _this._frameTime.beginMonitoring();\n }\n if (_this._captureInterFrameTime) {\n _this._interFrameTime.endMonitoring();\n }\n if (_this._captureParticlesRenderTime) {\n _this._particlesRenderTime.fetchNewFrame();\n }\n if (_this._captureSpritesRenderTime) {\n _this._spritesRenderTime.fetchNewFrame();\n }\n if (_this._captureAnimationsTime) {\n _this._animationsTime.beginMonitoring();\n }\n _this.scene.getEngine()._drawCalls.fetchNewFrame();\n _this.scene.getEngine()._textureCollisions.fetchNewFrame();\n });\n // After render\n this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {\n if (_this._captureFrameTime) {\n BABYLON.Tools.EndPerformanceCounter(\"Scene rendering\");\n _this._frameTime.endMonitoring();\n }\n if (_this._captureRenderTime) {\n _this._renderTime.endMonitoring(false);\n }\n if (_this._captureInterFrameTime) {\n _this._interFrameTime.beginMonitoring();\n }\n });\n }\n Object.defineProperty(SceneInstrumentation.prototype, \"activeMeshesEvaluationTimeCounter\", {\n // Properties\n /**\n * Gets the perf counter used for active meshes evaluation time\n */\n get: function () {\n return this._activeMeshesEvaluationTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureActiveMeshesEvaluationTime\", {\n /**\n * Gets the active meshes evaluation time capture status\n */\n get: function () {\n return this._captureActiveMeshesEvaluationTime;\n },\n /**\n * Enable or disable the active meshes evaluation time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureActiveMeshesEvaluationTime) {\n return;\n }\n this._captureActiveMeshesEvaluationTime = value;\n if (value) {\n this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {\n BABYLON.Tools.StartPerformanceCounter(\"Active meshes evaluation\");\n _this._activeMeshesEvaluationTime.beginMonitoring();\n });\n this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {\n BABYLON.Tools.EndPerformanceCounter(\"Active meshes evaluation\");\n _this._activeMeshesEvaluationTime.endMonitoring();\n });\n }\n else {\n this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);\n this._onBeforeActiveMeshesEvaluationObserver = null;\n this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);\n this._onAfterActiveMeshesEvaluationObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"renderTargetsRenderTimeCounter\", {\n /**\n * Gets the perf counter used for render targets render time\n */\n get: function () {\n return this._renderTargetsRenderTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureRenderTargetsRenderTime\", {\n /**\n * Gets the render targets render time capture status\n */\n get: function () {\n return this._captureRenderTargetsRenderTime;\n },\n /**\n * Enable or disable the render targets render time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureRenderTargetsRenderTime) {\n return;\n }\n this._captureRenderTargetsRenderTime = value;\n if (value) {\n this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {\n BABYLON.Tools.StartPerformanceCounter(\"Render targets rendering\");\n _this._renderTargetsRenderTime.beginMonitoring();\n });\n this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {\n BABYLON.Tools.EndPerformanceCounter(\"Render targets rendering\");\n _this._renderTargetsRenderTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);\n this._onBeforeRenderTargetsRenderObserver = null;\n this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);\n this._onAfterRenderTargetsRenderObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"particlesRenderTimeCounter\", {\n /**\n * Gets the perf counter used for particles render time\n */\n get: function () {\n return this._particlesRenderTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureParticlesRenderTime\", {\n /**\n * Gets the particles render time capture status\n */\n get: function () {\n return this._captureParticlesRenderTime;\n },\n /**\n * Enable or disable the particles render time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureParticlesRenderTime) {\n return;\n }\n this._captureParticlesRenderTime = value;\n if (value) {\n this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {\n BABYLON.Tools.StartPerformanceCounter(\"Particles\");\n _this._particlesRenderTime.beginMonitoring();\n });\n this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {\n BABYLON.Tools.EndPerformanceCounter(\"Particles\");\n _this._particlesRenderTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);\n this._onBeforeParticlesRenderingObserver = null;\n this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);\n this._onAfterParticlesRenderingObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"spritesRenderTimeCounter\", {\n /**\n * Gets the perf counter used for sprites render time\n */\n get: function () {\n return this._spritesRenderTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureSpritesRenderTime\", {\n /**\n * Gets the sprites render time capture status\n */\n get: function () {\n return this._captureSpritesRenderTime;\n },\n /**\n * Enable or disable the sprites render time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureSpritesRenderTime) {\n return;\n }\n this._captureSpritesRenderTime = value;\n if (value) {\n this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {\n BABYLON.Tools.StartPerformanceCounter(\"Sprites\");\n _this._spritesRenderTime.beginMonitoring();\n });\n this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {\n BABYLON.Tools.EndPerformanceCounter(\"Sprites\");\n _this._spritesRenderTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);\n this._onBeforeSpritesRenderingObserver = null;\n this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);\n this._onAfterSpritesRenderingObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"physicsTimeCounter\", {\n /**\n * Gets the perf counter used for physics time\n */\n get: function () {\n return this._physicsTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"capturePhysicsTime\", {\n /**\n * Gets the physics time capture status\n */\n get: function () {\n return this._capturePhysicsTime;\n },\n /**\n * Enable or disable the physics time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._capturePhysicsTime) {\n return;\n }\n this._capturePhysicsTime = value;\n if (value) {\n this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {\n BABYLON.Tools.StartPerformanceCounter(\"Physics\");\n _this._physicsTime.beginMonitoring();\n });\n this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {\n BABYLON.Tools.EndPerformanceCounter(\"Physics\");\n _this._physicsTime.endMonitoring();\n });\n }\n else {\n this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);\n this._onBeforePhysicsObserver = null;\n this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);\n this._onAfterPhysicsObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"animationsTimeCounter\", {\n /**\n * Gets the perf counter used for animations time\n */\n get: function () {\n return this._animationsTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureAnimationsTime\", {\n /**\n * Gets the animations time capture status\n */\n get: function () {\n return this._captureAnimationsTime;\n },\n /**\n * Enable or disable the animations time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureAnimationsTime) {\n return;\n }\n this._captureAnimationsTime = value;\n if (value) {\n this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {\n _this._animationsTime.endMonitoring();\n });\n }\n else {\n this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);\n this._onAfterAnimationsObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"frameTimeCounter\", {\n /**\n * Gets the perf counter used for frame time capture\n */\n get: function () {\n return this._frameTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureFrameTime\", {\n /**\n * Gets the frame time capture status\n */\n get: function () {\n return this._captureFrameTime;\n },\n /**\n * Enable or disable the frame time capture\n */\n set: function (value) {\n this._captureFrameTime = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"interFrameTimeCounter\", {\n /**\n * Gets the perf counter used for inter-frames time capture\n */\n get: function () {\n return this._interFrameTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureInterFrameTime\", {\n /**\n * Gets the inter-frames time capture status\n */\n get: function () {\n return this._captureInterFrameTime;\n },\n /**\n * Enable or disable the inter-frames time capture\n */\n set: function (value) {\n this._captureInterFrameTime = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"renderTimeCounter\", {\n /**\n * Gets the perf counter used for render time capture\n */\n get: function () {\n return this._renderTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureRenderTime\", {\n /**\n * Gets the render time capture status\n */\n get: function () {\n return this._captureRenderTime;\n },\n /**\n * Enable or disable the render time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureRenderTime) {\n return;\n }\n this._captureRenderTime = value;\n if (value) {\n this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {\n _this._renderTime.beginMonitoring();\n BABYLON.Tools.StartPerformanceCounter(\"Main render\");\n });\n this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {\n _this._renderTime.endMonitoring(false);\n BABYLON.Tools.EndPerformanceCounter(\"Main render\");\n });\n }\n else {\n this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);\n this._onBeforeDrawPhaseObserver = null;\n this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);\n this._onAfterDrawPhaseObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"cameraRenderTimeCounter\", {\n /**\n * Gets the perf counter used for camera render time capture\n */\n get: function () {\n return this._cameraRenderTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureCameraRenderTime\", {\n /**\n * Gets the camera render time capture status\n */\n get: function () {\n return this._captureCameraRenderTime;\n },\n /**\n * Enable or disable the camera render time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureCameraRenderTime) {\n return;\n }\n this._captureCameraRenderTime = value;\n if (value) {\n this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {\n _this._cameraRenderTime.beginMonitoring();\n BABYLON.Tools.StartPerformanceCounter(\"Rendering camera \" + camera.name);\n });\n this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {\n _this._cameraRenderTime.endMonitoring(false);\n BABYLON.Tools.EndPerformanceCounter(\"Rendering camera \" + camera.name);\n });\n }\n else {\n this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n this._onBeforeCameraRenderObserver = null;\n this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);\n this._onAfterCameraRenderObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"drawCallsCounter\", {\n /**\n * Gets the perf counter used for draw calls\n */\n get: function () {\n return this.scene.getEngine()._drawCalls;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"textureCollisionsCounter\", {\n /**\n * Gets the perf counter used for texture collisions\n */\n get: function () {\n return this.scene.getEngine()._textureCollisions;\n },\n enumerable: true,\n configurable: true\n });\n SceneInstrumentation.prototype.dispose = function () {\n this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n this._onAfterRenderObserver = null;\n this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);\n this._onBeforeActiveMeshesEvaluationObserver = null;\n this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);\n this._onAfterActiveMeshesEvaluationObserver = null;\n this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);\n this._onBeforeRenderTargetsRenderObserver = null;\n this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);\n this._onAfterRenderTargetsRenderObserver = null;\n this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);\n this._onBeforeAnimationsObserver = null;\n this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);\n this._onBeforeParticlesRenderingObserver = null;\n this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);\n this._onAfterParticlesRenderingObserver = null;\n this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);\n this._onBeforeSpritesRenderingObserver = null;\n this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);\n this._onAfterSpritesRenderingObserver = null;\n this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);\n this._onBeforeDrawPhaseObserver = null;\n this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);\n this._onAfterDrawPhaseObserver = null;\n this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);\n this._onBeforePhysicsObserver = null;\n this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);\n this._onAfterPhysicsObserver = null;\n this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);\n this._onAfterAnimationsObserver = null;\n this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n this._onBeforeCameraRenderObserver = null;\n this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);\n this._onAfterCameraRenderObserver = null;\n this.scene = null;\n };\n return SceneInstrumentation;\n }());\n BABYLON.SceneInstrumentation = SceneInstrumentation;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sceneInstrumentation.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * @hidden\n **/\n var _TimeToken = /** @class */ (function () {\n function _TimeToken() {\n this._timeElapsedQueryEnded = false;\n }\n return _TimeToken;\n }());\n BABYLON._TimeToken = _TimeToken;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.timeToken.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Background material defines definition.\n * @hidden Mainly internal Use\n */\n var BackgroundMaterialDefines = /** @class */ (function (_super) {\n __extends(BackgroundMaterialDefines, _super);\n /**\n * Constructor of the defines.\n */\n function BackgroundMaterialDefines() {\n var _this = _super.call(this) || this;\n /**\n * True if the diffuse texture is in use.\n */\n _this.DIFFUSE = false;\n /**\n * The direct UV channel to use.\n */\n _this.DIFFUSEDIRECTUV = 0;\n /**\n * True if the diffuse texture is in gamma space.\n */\n _this.GAMMADIFFUSE = false;\n /**\n * True if the diffuse texture has opacity in the alpha channel.\n */\n _this.DIFFUSEHASALPHA = false;\n /**\n * True if you want the material to fade to transparent at grazing angle.\n */\n _this.OPACITYFRESNEL = false;\n /**\n * True if an extra blur needs to be added in the reflection.\n */\n _this.REFLECTIONBLUR = false;\n /**\n * True if you want the material to fade to reflection at grazing angle.\n */\n _this.REFLECTIONFRESNEL = false;\n /**\n * True if you want the material to falloff as far as you move away from the scene center.\n */\n _this.REFLECTIONFALLOFF = false;\n /**\n * False if the current Webgl implementation does not support the texture lod extension.\n */\n _this.TEXTURELODSUPPORT = false;\n /**\n * True to ensure the data are premultiplied.\n */\n _this.PREMULTIPLYALPHA = false;\n /**\n * True if the texture contains cooked RGB values and not gray scaled multipliers.\n */\n _this.USERGBCOLOR = false;\n /**\n * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color\n * stays aligned with the desired configuration.\n */\n _this.USEHIGHLIGHTANDSHADOWCOLORS = false;\n /**\n * True to add noise in order to reduce the banding effect.\n */\n _this.NOISE = false;\n /**\n * is the reflection texture in BGR color scheme?\n * Mainly used to solve a bug in ios10 video tag\n */\n _this.REFLECTIONBGR = false;\n _this.IMAGEPROCESSING = false;\n _this.VIGNETTE = false;\n _this.VIGNETTEBLENDMODEMULTIPLY = false;\n _this.VIGNETTEBLENDMODEOPAQUE = false;\n _this.TONEMAPPING = false;\n _this.CONTRAST = false;\n _this.COLORCURVES = false;\n _this.COLORGRADING = false;\n _this.COLORGRADING3D = false;\n _this.SAMPLER3DGREENDEPTH = false;\n _this.SAMPLER3DBGRMAP = false;\n _this.IMAGEPROCESSINGPOSTPROCESS = false;\n _this.EXPOSURE = false;\n // Reflection.\n _this.REFLECTION = false;\n _this.REFLECTIONMAP_3D = false;\n _this.REFLECTIONMAP_SPHERICAL = false;\n _this.REFLECTIONMAP_PLANAR = false;\n _this.REFLECTIONMAP_CUBIC = false;\n _this.REFLECTIONMAP_PROJECTION = false;\n _this.REFLECTIONMAP_SKYBOX = false;\n _this.REFLECTIONMAP_EXPLICIT = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n _this.INVERTCUBICMAP = false;\n _this.REFLECTIONMAP_OPPOSITEZ = false;\n _this.LODINREFLECTIONALPHA = false;\n _this.GAMMAREFLECTION = false;\n _this.RGBDREFLECTION = false;\n _this.EQUIRECTANGULAR_RELFECTION_FOV = false;\n // Default BJS.\n _this.MAINUV1 = false;\n _this.MAINUV2 = false;\n _this.UV1 = false;\n _this.UV2 = false;\n _this.CLIPPLANE = false;\n _this.POINTSIZE = false;\n _this.FOG = false;\n _this.NORMAL = false;\n _this.NUM_BONE_INFLUENCERS = 0;\n _this.BonesPerMesh = 0;\n _this.INSTANCES = false;\n _this.SHADOWFLOAT = false;\n _this.rebuild();\n return _this;\n }\n return BackgroundMaterialDefines;\n }(BABYLON.MaterialDefines));\n /**\n * Background material used to create an efficient environement around your scene.\n */\n var BackgroundMaterial = /** @class */ (function (_super) {\n __extends(BackgroundMaterial, _super);\n /**\n * Instantiates a Background Material in the given scene\n * @param name The friendly name of the material\n * @param scene The scene to add the material to\n */\n function BackgroundMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n /**\n * Key light Color (multiply against the environement texture)\n */\n _this.primaryColor = BABYLON.Color3.White();\n _this._primaryColorShadowLevel = 0;\n _this._primaryColorHighlightLevel = 0;\n /**\n * Reflection Texture used in the material.\n * Should be author in a specific way for the best result (refer to the documentation).\n */\n _this.reflectionTexture = null;\n /**\n * Reflection Texture level of blur.\n *\n * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the\n * texture twice.\n */\n _this.reflectionBlur = 0;\n /**\n * Diffuse Texture used in the material.\n * Should be author in a specific way for the best result (refer to the documentation).\n */\n _this.diffuseTexture = null;\n _this._shadowLights = null;\n /**\n * Specify the list of lights casting shadow on the material.\n * All scene shadow lights will be included if null.\n */\n _this.shadowLights = null;\n /**\n * Helps adjusting the shadow to a softer level if required.\n * 0 means black shadows and 1 means no shadows.\n */\n _this.shadowLevel = 0;\n /**\n * In case of opacity Fresnel or reflection falloff, this is use as a scene center.\n * It is usually zero but might be interesting to modify according to your setup.\n */\n _this.sceneCenter = BABYLON.Vector3.Zero();\n /**\n * This helps specifying that the material is falling off to the sky box at grazing angle.\n * This helps ensuring a nice transition when the camera goes under the ground.\n */\n _this.opacityFresnel = true;\n /**\n * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.\n * This helps adding a mirror texture on the ground.\n */\n _this.reflectionFresnel = false;\n /**\n * This helps specifying the falloff radius off the reflection texture from the sceneCenter.\n * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.\n */\n _this.reflectionFalloffDistance = 0.0;\n /**\n * This specifies the weight of the reflection against the background in case of reflection Fresnel.\n */\n _this.reflectionAmount = 1.0;\n /**\n * This specifies the weight of the reflection at grazing angle.\n */\n _this.reflectionReflectance0 = 0.05;\n /**\n * This specifies the weight of the reflection at a perpendicular point of view.\n */\n _this.reflectionReflectance90 = 0.5;\n /**\n * Helps to directly use the maps channels instead of their level.\n */\n _this.useRGBColor = true;\n /**\n * This helps reducing the banding effect that could occur on the background.\n */\n _this.enableNoise = false;\n _this._fovMultiplier = 1.0;\n /**\n * Enable the FOV adjustment feature controlled by fovMultiplier.\n */\n _this.useEquirectangularFOV = false;\n _this._maxSimultaneousLights = 4;\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n _this.maxSimultaneousLights = 4;\n /**\n * Keep track of the image processing observer to allow dispose and replace.\n */\n _this._imageProcessingObserver = null;\n /**\n * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.\n * Setting this flag to true (not done automatically!) will convert it back to RGB.\n */\n _this.switchToBGR = false;\n // Temp values kept as cache in the material.\n _this._renderTargets = new BABYLON.SmartArray(16);\n _this._reflectionControls = BABYLON.Vector4.Zero();\n _this._white = BABYLON.Color3.White();\n _this._primaryShadowColor = BABYLON.Color3.Black();\n _this._primaryHighlightColor = BABYLON.Color3.Black();\n // Setup the default processing configuration to the scene.\n _this._attachImageProcessingConfiguration(null);\n _this.getRenderTargetTextures = function () {\n _this._renderTargets.reset();\n if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {\n _this._renderTargets.push(_this._diffuseTexture);\n }\n if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {\n _this._renderTargets.push(_this._reflectionTexture);\n }\n return _this._renderTargets;\n };\n return _this;\n }\n Object.defineProperty(BackgroundMaterial.prototype, \"_perceptualColor\", {\n /**\n * Experimental Internal Use Only.\n *\n * Key light Color in \"perceptual value\" meaning the color you would like to see on screen.\n * This acts as a helper to set the primary color to a more \"human friendly\" value.\n * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the\n * output color as close as possible from the chosen value.\n * (This does not account for contrast color grading and color curves as they are considered post effect and not directly\n * part of lighting setup.)\n */\n get: function () {\n return this.__perceptualColor;\n },\n set: function (value) {\n this.__perceptualColor = value;\n this._computePrimaryColorFromPerceptualColor();\n this._markAllSubMeshesAsLightsDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"primaryColorShadowLevel\", {\n /**\n * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.\n * The color opposite to the primary color is used at the level chosen to define what the black area would look.\n */\n get: function () {\n return this._primaryColorShadowLevel;\n },\n set: function (value) {\n this._primaryColorShadowLevel = value;\n this._computePrimaryColors();\n this._markAllSubMeshesAsLightsDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"primaryColorHighlightLevel\", {\n /**\n * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.\n * The primary color is used at the level chosen to define what the white area would look.\n */\n get: function () {\n return this._primaryColorHighlightLevel;\n },\n set: function (value) {\n this._primaryColorHighlightLevel = value;\n this._computePrimaryColors();\n this._markAllSubMeshesAsLightsDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"reflectionStandardFresnelWeight\", {\n /**\n * Sets the reflection reflectance fresnel values according to the default standard\n * empirically know to work well :-)\n */\n set: function (value) {\n var reflectionWeight = value;\n if (reflectionWeight < 0.5) {\n reflectionWeight = reflectionWeight * 2.0;\n this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;\n this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;\n }\n else {\n reflectionWeight = reflectionWeight * 2.0 - 1.0;\n this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;\n this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"fovMultiplier\", {\n /**\n * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values \"zoom in\" and higher values \"zoom out\".\n * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.\n * Recommended to be keep at 1.0 except for special cases.\n */\n get: function () {\n return this._fovMultiplier;\n },\n set: function (value) {\n if (isNaN(value)) {\n value = 1.0;\n }\n this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Attaches a new image processing configuration to the PBR Material.\n * @param configuration (if null the scene configuration will be use)\n */\n BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {\n var _this = this;\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {\n _this._computePrimaryColorFromPerceptualColor();\n _this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n };\n Object.defineProperty(BackgroundMaterial.prototype, \"imageProcessingConfiguration\", {\n /**\n * Gets the image processing configuration used either in this material.\n */\n get: function () {\n return this._imageProcessingConfiguration;\n },\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set: function (value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraColorCurvesEnabled\", {\n /**\n * Gets wether the color curves effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n },\n /**\n * Sets wether the color curves effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraColorGradingEnabled\", {\n /**\n * Gets wether the color grading effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n },\n /**\n * Gets wether the color grading effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraToneMappingEnabled\", {\n /**\n * Gets wether tonemapping is enabled or not.\n */\n get: function () {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n },\n /**\n * Sets wether tonemapping is enabled or not\n */\n set: function (value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraExposure\", {\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n get: function () {\n return this._imageProcessingConfiguration.exposure;\n },\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n set: function (value) {\n this._imageProcessingConfiguration.exposure = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraContrast\", {\n /**\n * Gets The camera contrast used on this material.\n */\n get: function () {\n return this._imageProcessingConfiguration.contrast;\n },\n /**\n * Sets The camera contrast used on this material.\n */\n set: function (value) {\n this._imageProcessingConfiguration.contrast = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraColorGradingTexture\", {\n /**\n * Gets the Color Grading 2D Lookup Texture.\n */\n get: function () {\n return this._imageProcessingConfiguration.colorGradingTexture;\n },\n /**\n * Sets the Color Grading 2D Lookup Texture.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorGradingTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraColorCurves\", {\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorCurves;\n },\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorCurves = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * The entire material has been created in order to prevent overdraw.\n * @returns false\n */\n BackgroundMaterial.prototype.needAlphaTesting = function () {\n return true;\n };\n /**\n * The entire material has been created in order to prevent overdraw.\n * @returns true if blending is enable\n */\n BackgroundMaterial.prototype.needAlphaBlending = function () {\n return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));\n };\n /**\n * Checks wether the material is ready to be rendered for a given mesh.\n * @param mesh The mesh to render\n * @param subMesh The submesh to check against\n * @param useInstances Specify wether or not the material is used with instances\n * @returns true if all the dependencies are ready (Textures, Effects...)\n */\n BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {\n var _this = this;\n if (useInstances === void 0) { useInstances = false; }\n if (subMesh.effect && this.isFrozen) {\n if (this._wasPreviouslyReady) {\n return true;\n }\n }\n if (!subMesh._materialDefines) {\n subMesh._materialDefines = new BackgroundMaterialDefines();\n }\n var scene = this.getScene();\n var defines = subMesh._materialDefines;\n if (!this.checkReadyOnEveryCall && subMesh.effect) {\n if (defines._renderId === scene.getRenderId()) {\n return true;\n }\n }\n var engine = scene.getEngine();\n // Lights\n BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);\n defines._needNormals = true;\n // Textures\n if (defines._areTexturesDirty) {\n defines._needUVs = false;\n if (scene.texturesEnabled) {\n if (scene.getEngine().getCaps().textureLOD) {\n defines.TEXTURELODSUPPORT = true;\n }\n if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n if (!this._diffuseTexture.isReadyOrNotBlocking()) {\n return false;\n }\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, \"DIFFUSE\");\n defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;\n defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;\n defines.OPACITYFRESNEL = this._opacityFresnel;\n }\n else {\n defines.DIFFUSE = false;\n defines.DIFFUSEHASALPHA = false;\n defines.GAMMADIFFUSE = false;\n defines.OPACITYFRESNEL = false;\n }\n var reflectionTexture = this._reflectionTexture;\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n if (!reflectionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n defines.REFLECTION = true;\n defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;\n defines.RGBDREFLECTION = reflectionTexture.isRGBD;\n defines.REFLECTIONBLUR = this._reflectionBlur > 0;\n defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;\n defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;\n defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;\n defines.REFLECTIONBGR = this.switchToBGR;\n if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {\n defines.INVERTCUBICMAP = true;\n }\n defines.REFLECTIONMAP_3D = reflectionTexture.isCube;\n switch (reflectionTexture.coordinatesMode) {\n case BABYLON.Texture.EXPLICIT_MODE:\n defines.REFLECTIONMAP_EXPLICIT = true;\n break;\n case BABYLON.Texture.PLANAR_MODE:\n defines.REFLECTIONMAP_PLANAR = true;\n break;\n case BABYLON.Texture.PROJECTION_MODE:\n defines.REFLECTIONMAP_PROJECTION = true;\n break;\n case BABYLON.Texture.SKYBOX_MODE:\n defines.REFLECTIONMAP_SKYBOX = true;\n break;\n case BABYLON.Texture.SPHERICAL_MODE:\n defines.REFLECTIONMAP_SPHERICAL = true;\n break;\n case BABYLON.Texture.EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR = true;\n break;\n case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;\n break;\n case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;\n break;\n case BABYLON.Texture.CUBIC_MODE:\n case BABYLON.Texture.INVCUBIC_MODE:\n default:\n defines.REFLECTIONMAP_CUBIC = true;\n break;\n }\n if (this.reflectionFresnel) {\n defines.REFLECTIONFRESNEL = true;\n defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;\n this._reflectionControls.x = this.reflectionAmount;\n this._reflectionControls.y = this.reflectionReflectance0;\n this._reflectionControls.z = this.reflectionReflectance90;\n this._reflectionControls.w = 1 / this.reflectionFalloffDistance;\n }\n else {\n defines.REFLECTIONFRESNEL = false;\n defines.REFLECTIONFALLOFF = false;\n }\n }\n else {\n defines.REFLECTION = false;\n defines.REFLECTIONFRESNEL = false;\n defines.REFLECTIONFALLOFF = false;\n defines.REFLECTIONBLUR = false;\n defines.REFLECTIONMAP_3D = false;\n defines.REFLECTIONMAP_SPHERICAL = false;\n defines.REFLECTIONMAP_PLANAR = false;\n defines.REFLECTIONMAP_CUBIC = false;\n defines.REFLECTIONMAP_PROJECTION = false;\n defines.REFLECTIONMAP_SKYBOX = false;\n defines.REFLECTIONMAP_EXPLICIT = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n defines.INVERTCUBICMAP = false;\n defines.REFLECTIONMAP_OPPOSITEZ = false;\n defines.LODINREFLECTIONALPHA = false;\n defines.GAMMAREFLECTION = false;\n defines.RGBDREFLECTION = false;\n }\n }\n defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);\n defines.USERGBCOLOR = this._useRGBColor;\n defines.NOISE = this._enableNoise;\n }\n if (defines._areLightsDirty) {\n defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n if (!this._imageProcessingConfiguration.isReady()) {\n return false;\n }\n this._imageProcessingConfiguration.prepareDefines(defines);\n }\n // Misc.\n BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);\n // Values that need to be evaluated on every frame\n BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);\n // Attribs\n if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {\n if (mesh) {\n if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n mesh.createNormals(true);\n BABYLON.Tools.Warn(\"BackgroundMaterial: Normals have been created for the mesh: \" + mesh.name);\n }\n }\n }\n // Get correct effect\n if (defines.isDirty) {\n defines.markAsProcessed();\n scene.resetCachedMaterial();\n // Fallbacks\n var fallbacks = new BABYLON.EffectFallbacks();\n if (defines.FOG) {\n fallbacks.addFallback(0, \"FOG\");\n }\n if (defines.POINTSIZE) {\n fallbacks.addFallback(1, \"POINTSIZE\");\n }\n BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);\n if (defines.NUM_BONE_INFLUENCERS > 0) {\n fallbacks.addCPUSkinningFallback(0, mesh);\n }\n //Attributes\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n if (defines.NORMAL) {\n attribs.push(BABYLON.VertexBuffer.NormalKind);\n }\n if (defines.UV1) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n }\n if (defines.UV2) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n }\n BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);\n BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);\n var uniforms = [\"world\", \"view\", \"viewProjection\", \"vEyePosition\", \"vLightsType\",\n \"vFogInfos\", \"vFogColor\", \"pointSize\",\n \"vClipPlane\", \"mBones\",\n \"vPrimaryColor\", \"vPrimaryColorShadow\",\n \"vReflectionInfos\", \"reflectionMatrix\", \"vReflectionMicrosurfaceInfos\", \"fFovMultiplier\",\n \"shadowLevel\", \"alpha\",\n \"vBackgroundCenter\", \"vReflectionControl\",\n \"vDiffuseInfos\", \"diffuseMatrix\",\n ];\n var samplers = [\"diffuseSampler\", \"reflectionSampler\", \"reflectionSamplerLow\", \"reflectionSamplerHigh\"];\n var uniformBuffers = [\"Material\", \"Scene\"];\n if (BABYLON.ImageProcessingConfiguration) {\n BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);\n BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);\n }\n BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: defines,\n maxSimultaneousLights: this._maxSimultaneousLights\n });\n var onCompiled = function (effect) {\n if (_this.onCompiled) {\n _this.onCompiled(effect);\n }\n _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());\n };\n var join = defines.toString();\n subMesh.setEffect(scene.getEngine().createEffect(\"background\", {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: onCompiled,\n onError: this.onError,\n indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }\n }, engine), defines);\n this.buildUniformLayout();\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n this._wasPreviouslyReady = true;\n return true;\n };\n /**\n * Compute the primary color according to the chosen perceptual color.\n */\n BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {\n if (!this.__perceptualColor) {\n return;\n }\n this._primaryColor.copyFrom(this.__perceptualColor);\n // Revert gamma space.\n this._primaryColor.toLinearSpaceToRef(this._primaryColor);\n // Revert image processing configuration.\n if (this._imageProcessingConfiguration) {\n // Revert Exposure.\n this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);\n }\n this._computePrimaryColors();\n };\n /**\n * Compute the highlights and shadow colors according to their chosen levels.\n */\n BackgroundMaterial.prototype._computePrimaryColors = function () {\n if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {\n return;\n }\n // Find the highlight color based on the configuration.\n this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);\n this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);\n // Find the shadow color based on the configuration.\n this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);\n this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);\n this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);\n };\n /**\n * Build the uniform buffer used in the material.\n */\n BackgroundMaterial.prototype.buildUniformLayout = function () {\n // Order is important !\n this._uniformBuffer.addUniform(\"vPrimaryColor\", 4);\n this._uniformBuffer.addUniform(\"vPrimaryColorShadow\", 4);\n this._uniformBuffer.addUniform(\"vDiffuseInfos\", 2);\n this._uniformBuffer.addUniform(\"vReflectionInfos\", 2);\n this._uniformBuffer.addUniform(\"diffuseMatrix\", 16);\n this._uniformBuffer.addUniform(\"reflectionMatrix\", 16);\n this._uniformBuffer.addUniform(\"vReflectionMicrosurfaceInfos\", 3);\n this._uniformBuffer.addUniform(\"fFovMultiplier\", 1);\n this._uniformBuffer.addUniform(\"pointSize\", 1);\n this._uniformBuffer.addUniform(\"shadowLevel\", 1);\n this._uniformBuffer.addUniform(\"alpha\", 1);\n this._uniformBuffer.addUniform(\"vBackgroundCenter\", 3);\n this._uniformBuffer.addUniform(\"vReflectionControl\", 4);\n this._uniformBuffer.create();\n };\n /**\n * Unbind the material.\n */\n BackgroundMaterial.prototype.unbind = function () {\n if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {\n this._uniformBuffer.setTexture(\"diffuseSampler\", null);\n }\n if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", null);\n }\n _super.prototype.unbind.call(this);\n };\n /**\n * Bind only the world matrix to the material.\n * @param world The world matrix to bind.\n */\n BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {\n this._activeEffect.setMatrix(\"world\", world);\n };\n /**\n * Bind the material for a dedicated submeh (every used meshes will be considered opaque).\n * @param world The world matrix to bind.\n * @param subMesh The submesh to bind for.\n */\n BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {\n var scene = this.getScene();\n var defines = subMesh._materialDefines;\n if (!defines) {\n return;\n }\n var effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices\n this.bindOnlyWorldMatrix(world);\n // Bones\n BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);\n var mustRebind = this._mustRebind(scene, effect, mesh.visibility);\n if (mustRebind) {\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this.bindViewProjection(effect);\n var reflectionTexture = this._reflectionTexture;\n if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {\n // Texture uniforms\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vDiffuseInfos\", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, \"diffuse\");\n }\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n this._uniformBuffer.updateMatrix(\"reflectionMatrix\", reflectionTexture.getReflectionTextureMatrix());\n this._uniformBuffer.updateFloat2(\"vReflectionInfos\", reflectionTexture.level, this._reflectionBlur);\n this._uniformBuffer.updateFloat3(\"vReflectionMicrosurfaceInfos\", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);\n }\n }\n if (this.shadowLevel > 0) {\n this._uniformBuffer.updateFloat(\"shadowLevel\", this.shadowLevel);\n }\n this._uniformBuffer.updateFloat(\"alpha\", this.alpha);\n // Point size\n if (this.pointsCloud) {\n this._uniformBuffer.updateFloat(\"pointSize\", this.pointSize);\n }\n if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {\n this._uniformBuffer.updateColor4(\"vPrimaryColor\", this._primaryHighlightColor, 1.0);\n this._uniformBuffer.updateColor4(\"vPrimaryColorShadow\", this._primaryShadowColor, 1.0);\n }\n else {\n this._uniformBuffer.updateColor4(\"vPrimaryColor\", this._primaryColor, 1.0);\n }\n }\n this._uniformBuffer.updateFloat(\"fFovMultiplier\", this._fovMultiplier);\n // Textures\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n this._uniformBuffer.setTexture(\"diffuseSampler\", this._diffuseTexture);\n }\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture);\n }\n else if (!defines.REFLECTIONBLUR) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture);\n }\n else {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture._lodTextureMid || reflectionTexture);\n this._uniformBuffer.setTexture(\"reflectionSamplerLow\", reflectionTexture._lodTextureLow || reflectionTexture);\n this._uniformBuffer.setTexture(\"reflectionSamplerHigh\", reflectionTexture._lodTextureHigh || reflectionTexture);\n }\n if (defines.REFLECTIONFRESNEL) {\n this._uniformBuffer.updateFloat3(\"vBackgroundCenter\", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);\n this._uniformBuffer.updateFloat4(\"vReflectionControl\", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);\n }\n }\n }\n // Clip plane\n BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);\n BABYLON.MaterialHelper.BindEyePosition(effect, scene);\n }\n if (mustRebind || !this.isFrozen) {\n if (scene.lightsEnabled) {\n BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);\n }\n // View\n this.bindView(effect);\n // Fog\n BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);\n // image processing\n if (this._imageProcessingConfiguration) {\n this._imageProcessingConfiguration.bind(this._activeEffect);\n }\n }\n this._uniformBuffer.update();\n this._afterBind(mesh, this._activeEffect);\n };\n /**\n * Dispose the material.\n * @param forceDisposeEffect Force disposal of the associated effect.\n * @param forceDisposeTextures Force disposal of the associated textures.\n */\n BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {\n if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }\n if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }\n if (forceDisposeTextures) {\n if (this.diffuseTexture) {\n this.diffuseTexture.dispose();\n }\n if (this.reflectionTexture) {\n this.reflectionTexture.dispose();\n }\n }\n this._renderTargets.dispose();\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n _super.prototype.dispose.call(this, forceDisposeEffect);\n };\n /**\n * Clones the material.\n * @param name The cloned name.\n * @returns The cloned material.\n */\n BackgroundMaterial.prototype.clone = function (name) {\n var _this = this;\n return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);\n };\n /**\n * Serializes the current material to its JSON representation.\n * @returns The JSON representation.\n */\n BackgroundMaterial.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.BackgroundMaterial\";\n return serializationObject;\n };\n /**\n * Gets the class name of the material\n * @returns \"BackgroundMaterial\"\n */\n BackgroundMaterial.prototype.getClassName = function () {\n return \"BackgroundMaterial\";\n };\n /**\n * Parse a JSON input to create back a background material.\n * @param source The JSON data to parse\n * @param scene The scene to create the parsed material in\n * @param rootUrl The root url of the assets the material depends upon\n * @returns the instantiated BackgroundMaterial.\n */\n BackgroundMaterial.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);\n };\n /**\n * Standard reflectance value at parallel view angle.\n */\n BackgroundMaterial.StandardReflectance0 = 0.05;\n /**\n * Standard reflectance value at grazing angle.\n */\n BackgroundMaterial.StandardReflectance90 = 0.5;\n __decorate([\n BABYLON.serializeAsColor3()\n ], BackgroundMaterial.prototype, \"_primaryColor\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], BackgroundMaterial.prototype, \"primaryColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3()\n ], BackgroundMaterial.prototype, \"__perceptualColor\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_primaryColorShadowLevel\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_primaryColorHighlightLevel\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], BackgroundMaterial.prototype, \"primaryColorHighlightLevel\", null);\n __decorate([\n BABYLON.serializeAsTexture()\n ], BackgroundMaterial.prototype, \"_reflectionTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionTexture\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_reflectionBlur\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionBlur\", void 0);\n __decorate([\n BABYLON.serializeAsTexture()\n ], BackgroundMaterial.prototype, \"_diffuseTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"diffuseTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"shadowLights\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_shadowLevel\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"shadowLevel\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], BackgroundMaterial.prototype, \"_sceneCenter\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"sceneCenter\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_opacityFresnel\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"opacityFresnel\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_reflectionFresnel\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionFresnel\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_reflectionFalloffDistance\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionFalloffDistance\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_reflectionAmount\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionAmount\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_reflectionReflectance0\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionReflectance0\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_reflectionReflectance90\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionReflectance90\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_useRGBColor\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"useRGBColor\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_enableNoise\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"enableNoise\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_maxSimultaneousLights\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"maxSimultaneousLights\", void 0);\n __decorate([\n BABYLON.serializeAsImageProcessingConfiguration()\n ], BackgroundMaterial.prototype, \"_imageProcessingConfiguration\", void 0);\n return BackgroundMaterial;\n }(BABYLON.PushMaterial));\n BABYLON.BackgroundMaterial = BackgroundMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.backgroundMaterial.js.map\n\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The Environment helper class can be used to add a fully featuread none expensive background to your scene.\n * It includes by default a skybox and a ground relying on the BackgroundMaterial.\n * It also helps with the default setup of your imageProcessing configuration.\n */\n var EnvironmentHelper = /** @class */ (function () {\n /**\n * constructor\n * @param options\n * @param scene The scene to add the material to\n */\n function EnvironmentHelper(options, scene) {\n var _this = this;\n this._errorHandler = function (message, exception) {\n _this.onErrorObservable.notifyObservers({ message: message, exception: exception });\n };\n this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);\n this._scene = scene;\n this.onErrorObservable = new BABYLON.Observable();\n this._setupBackground();\n this._setupImageProcessing();\n }\n /**\n * Creates the default options for the helper.\n */\n EnvironmentHelper._getDefaultOptions = function () {\n return {\n createGround: true,\n groundSize: 15,\n groundTexture: this._groundTextureCDNUrl,\n groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),\n groundOpacity: 0.9,\n enableGroundShadow: true,\n groundShadowLevel: 0.5,\n enableGroundMirror: false,\n groundMirrorSizeRatio: 0.3,\n groundMirrorBlurKernel: 64,\n groundMirrorAmount: 1,\n groundMirrorFresnelWeight: 1,\n groundMirrorFallOffDistance: 0,\n groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,\n groundYBias: 0.00001,\n createSkybox: true,\n skyboxSize: 20,\n skyboxTexture: this._skyboxTextureCDNUrl,\n skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),\n backgroundYRotation: 0,\n sizeAuto: true,\n rootPosition: BABYLON.Vector3.Zero(),\n setupImageProcessing: true,\n environmentTexture: this._environmentTextureCDNUrl,\n cameraExposure: 0.8,\n cameraContrast: 1.2,\n toneMappingEnabled: true,\n };\n };\n Object.defineProperty(EnvironmentHelper.prototype, \"rootMesh\", {\n /**\n * Gets the root mesh created by the helper.\n */\n get: function () {\n return this._rootMesh;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"skybox\", {\n /**\n * Gets the skybox created by the helper.\n */\n get: function () {\n return this._skybox;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"skyboxTexture\", {\n /**\n * Gets the skybox texture created by the helper.\n */\n get: function () {\n return this._skyboxTexture;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"skyboxMaterial\", {\n /**\n * Gets the skybox material created by the helper.\n */\n get: function () {\n return this._skyboxMaterial;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"ground\", {\n /**\n * Gets the ground mesh created by the helper.\n */\n get: function () {\n return this._ground;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"groundTexture\", {\n /**\n * Gets the ground texture created by the helper.\n */\n get: function () {\n return this._groundTexture;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"groundMirror\", {\n /**\n * Gets the ground mirror created by the helper.\n */\n get: function () {\n return this._groundMirror;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"groundMirrorRenderList\", {\n /**\n * Gets the ground mirror render list to helps pushing the meshes\n * you wish in the ground reflection.\n */\n get: function () {\n if (this._groundMirror) {\n return this._groundMirror.renderList;\n }\n return null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"groundMaterial\", {\n /**\n * Gets the ground material created by the helper.\n */\n get: function () {\n return this._groundMaterial;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Updates the background according to the new options\n * @param options\n */\n EnvironmentHelper.prototype.updateOptions = function (options) {\n var newOptions = __assign({}, this._options, options);\n if (this._ground && !newOptions.createGround) {\n this._ground.dispose();\n this._ground = null;\n }\n if (this._groundMaterial && !newOptions.createGround) {\n this._groundMaterial.dispose();\n this._groundMaterial = null;\n }\n if (this._groundTexture) {\n if (this._options.groundTexture != newOptions.groundTexture) {\n this._groundTexture.dispose();\n this._groundTexture = null;\n }\n }\n if (this._skybox && !newOptions.createSkybox) {\n this._skybox.dispose();\n this._skybox = null;\n }\n if (this._skyboxMaterial && !newOptions.createSkybox) {\n this._skyboxMaterial.dispose();\n this._skyboxMaterial = null;\n }\n if (this._skyboxTexture) {\n if (this._options.skyboxTexture != newOptions.skyboxTexture) {\n this._skyboxTexture.dispose();\n this._skyboxTexture = null;\n }\n }\n if (this._groundMirror && !newOptions.enableGroundMirror) {\n this._groundMirror.dispose();\n this._groundMirror = null;\n }\n if (this._scene.environmentTexture) {\n if (this._options.environmentTexture != newOptions.environmentTexture) {\n this._scene.environmentTexture.dispose();\n }\n }\n this._options = newOptions;\n this._setupBackground();\n this._setupImageProcessing();\n };\n /**\n * Sets the primary color of all the available elements.\n * @param color the main color to affect to the ground and the background\n */\n EnvironmentHelper.prototype.setMainColor = function (color) {\n if (this.groundMaterial) {\n this.groundMaterial.primaryColor = color;\n }\n if (this.skyboxMaterial) {\n this.skyboxMaterial.primaryColor = color;\n }\n if (this.groundMirror) {\n this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);\n }\n };\n /**\n * Setup the image processing according to the specified options.\n */\n EnvironmentHelper.prototype._setupImageProcessing = function () {\n if (this._options.setupImageProcessing) {\n this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;\n this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;\n this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;\n this._setupEnvironmentTexture();\n }\n };\n /**\n * Setup the environment texture according to the specified options.\n */\n EnvironmentHelper.prototype._setupEnvironmentTexture = function () {\n if (this._scene.environmentTexture) {\n return;\n }\n if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {\n this._scene.environmentTexture = this._options.environmentTexture;\n return;\n }\n var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);\n this._scene.environmentTexture = environmentTexture;\n };\n /**\n * Setup the background according to the specified options.\n */\n EnvironmentHelper.prototype._setupBackground = function () {\n if (!this._rootMesh) {\n this._rootMesh = new BABYLON.Mesh(\"BackgroundHelper\", this._scene);\n }\n this._rootMesh.rotation.y = this._options.backgroundYRotation;\n var sceneSize = this._getSceneSize();\n if (this._options.createGround) {\n this._setupGround(sceneSize);\n this._setupGroundMaterial();\n this._setupGroundDiffuseTexture();\n if (this._options.enableGroundMirror) {\n this._setupGroundMirrorTexture(sceneSize);\n }\n this._setupMirrorInGroundMaterial();\n }\n if (this._options.createSkybox) {\n this._setupSkybox(sceneSize);\n this._setupSkyboxMaterial();\n this._setupSkyboxReflectionTexture();\n }\n this._rootMesh.position.x = sceneSize.rootPosition.x;\n this._rootMesh.position.z = sceneSize.rootPosition.z;\n this._rootMesh.position.y = sceneSize.rootPosition.y;\n };\n /**\n * Get the scene sizes according to the setup.\n */\n EnvironmentHelper.prototype._getSceneSize = function () {\n var _this = this;\n var groundSize = this._options.groundSize;\n var skyboxSize = this._options.skyboxSize;\n var rootPosition = this._options.rootPosition;\n if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.\n return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };\n }\n var sceneExtends = this._scene.getWorldExtends(function (mesh) {\n return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);\n });\n var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);\n if (this._options.sizeAuto) {\n if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&\n this._scene.activeCamera.upperRadiusLimit) {\n groundSize = this._scene.activeCamera.upperRadiusLimit * 2;\n skyboxSize = groundSize;\n }\n var sceneDiagonalLenght = sceneDiagonal.length();\n if (sceneDiagonalLenght > groundSize) {\n groundSize = sceneDiagonalLenght * 2;\n skyboxSize = groundSize;\n }\n // 10 % bigger.\n groundSize *= 1.1;\n skyboxSize *= 1.5;\n rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));\n rootPosition.y = sceneExtends.min.y - this._options.groundYBias;\n }\n return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };\n };\n /**\n * Setup the ground according to the specified options.\n */\n EnvironmentHelper.prototype._setupGround = function (sceneSize) {\n var _this = this;\n if (!this._ground || this._ground.isDisposed()) {\n this._ground = BABYLON.Mesh.CreatePlane(\"BackgroundPlane\", sceneSize.groundSize, this._scene);\n this._ground.rotation.x = Math.PI / 2; // Face up by default.\n this._ground.parent = this._rootMesh;\n this._ground.onDisposeObservable.add(function () { _this._ground = null; });\n }\n this._ground.receiveShadows = this._options.enableGroundShadow;\n };\n /**\n * Setup the ground material according to the specified options.\n */\n EnvironmentHelper.prototype._setupGroundMaterial = function () {\n if (!this._groundMaterial) {\n this._groundMaterial = new BABYLON.BackgroundMaterial(\"BackgroundPlaneMaterial\", this._scene);\n }\n this._groundMaterial.alpha = this._options.groundOpacity;\n this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;\n this._groundMaterial.shadowLevel = this._options.groundShadowLevel;\n this._groundMaterial.primaryColor = this._options.groundColor;\n this._groundMaterial.useRGBColor = false;\n this._groundMaterial.enableNoise = true;\n if (this._ground) {\n this._ground.material = this._groundMaterial;\n }\n };\n /**\n * Setup the ground diffuse texture according to the specified options.\n */\n EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {\n if (!this._groundMaterial) {\n return;\n }\n if (this._groundTexture) {\n return;\n }\n if (this._options.groundTexture instanceof BABYLON.BaseTexture) {\n this._groundMaterial.diffuseTexture = this._options.groundTexture;\n return;\n }\n var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);\n diffuseTexture.gammaSpace = false;\n diffuseTexture.hasAlpha = true;\n this._groundMaterial.diffuseTexture = diffuseTexture;\n };\n /**\n * Setup the ground mirror texture according to the specified options.\n */\n EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {\n var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;\n if (!this._groundMirror) {\n this._groundMirror = new BABYLON.MirrorTexture(\"BackgroundPlaneMirrorTexture\", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);\n this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);\n this._groundMirror.anisotropicFilteringLevel = 1;\n this._groundMirror.wrapU = wrapping;\n this._groundMirror.wrapV = wrapping;\n this._groundMirror.gammaSpace = false;\n if (this._groundMirror.renderList) {\n for (var i = 0; i < this._scene.meshes.length; i++) {\n var mesh = this._scene.meshes[i];\n if (mesh !== this._ground &&\n mesh !== this._skybox &&\n mesh !== this._rootMesh) {\n this._groundMirror.renderList.push(mesh);\n }\n }\n }\n }\n this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);\n this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;\n };\n /**\n * Setup the ground to receive the mirror texture.\n */\n EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {\n if (this._groundMaterial) {\n this._groundMaterial.reflectionTexture = this._groundMirror;\n this._groundMaterial.reflectionFresnel = true;\n this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;\n this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;\n this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;\n }\n };\n /**\n * Setup the skybox according to the specified options.\n */\n EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {\n var _this = this;\n if (!this._skybox || this._skybox.isDisposed()) {\n this._skybox = BABYLON.Mesh.CreateBox(\"BackgroundSkybox\", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);\n this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });\n }\n this._skybox.parent = this._rootMesh;\n };\n /**\n * Setup the skybox material according to the specified options.\n */\n EnvironmentHelper.prototype._setupSkyboxMaterial = function () {\n if (!this._skybox) {\n return;\n }\n if (!this._skyboxMaterial) {\n this._skyboxMaterial = new BABYLON.BackgroundMaterial(\"BackgroundSkyboxMaterial\", this._scene);\n }\n this._skyboxMaterial.useRGBColor = false;\n this._skyboxMaterial.primaryColor = this._options.skyboxColor;\n this._skyboxMaterial.enableNoise = true;\n this._skybox.material = this._skyboxMaterial;\n };\n /**\n * Setup the skybox reflection texture according to the specified options.\n */\n EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {\n if (!this._skyboxMaterial) {\n return;\n }\n if (this._skyboxTexture) {\n return;\n }\n if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {\n this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;\n return;\n }\n this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);\n this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;\n this._skyboxTexture.gammaSpace = false;\n this._skyboxMaterial.reflectionTexture = this._skyboxTexture;\n };\n /**\n * Dispose all the elements created by the Helper.\n */\n EnvironmentHelper.prototype.dispose = function () {\n if (this._groundMaterial) {\n this._groundMaterial.dispose(true, true);\n }\n if (this._skyboxMaterial) {\n this._skyboxMaterial.dispose(true, true);\n }\n this._rootMesh.dispose(false);\n };\n /**\n * Default ground texture URL.\n */\n EnvironmentHelper._groundTextureCDNUrl = \"https://assets.babylonjs.com/environments/backgroundGround.png\";\n /**\n * Default skybox texture URL.\n */\n EnvironmentHelper._skyboxTextureCDNUrl = \"https://assets.babylonjs.com/environments/backgroundSkybox.dds\";\n /**\n * Default environment texture URL.\n */\n EnvironmentHelper._environmentTextureCDNUrl = \"https://assets.babylonjs.com/environments/environmentSpecular.env\";\n return EnvironmentHelper;\n }());\n BABYLON.EnvironmentHelper = EnvironmentHelper;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.environmentHelper.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /** Internal class used to store shapes for emitters */\n var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {\n function ParticleSystemSetEmitterCreationOptions() {\n }\n return ParticleSystemSetEmitterCreationOptions;\n }());\n /**\n * Represents a set of particle systems working together to create a specific effect\n */\n var ParticleSystemSet = /** @class */ (function () {\n function ParticleSystemSet() {\n /**\n * Gets the particle system list\n */\n this.systems = new Array();\n }\n Object.defineProperty(ParticleSystemSet.prototype, \"emitterNode\", {\n /**\n * Gets the emitter node used with this set\n */\n get: function () {\n return this._emitterNode;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Creates a new emitter mesh as a sphere\n * @param options defines the options used to create the sphere\n * @param renderingGroupId defines the renderingGroupId to use for the sphere\n * @param scene defines the hosting scene\n */\n ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {\n if (this._emitterNode) {\n this._emitterNode.dispose();\n }\n this._emitterCreationOptions = {\n kind: \"Sphere\",\n options: options,\n renderingGroupId: renderingGroupId\n };\n var emitterMesh = BABYLON.MeshBuilder.CreateSphere(\"emitterSphere\", { diameter: options.diameter, segments: options.segments }, scene);\n emitterMesh.renderingGroupId = renderingGroupId;\n var material = new BABYLON.StandardMaterial(\"emitterSphereMaterial\", scene);\n material.emissiveColor = options.color;\n emitterMesh.material = material;\n for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {\n var system = _a[_i];\n system.emitter = emitterMesh;\n }\n this._emitterNode = emitterMesh;\n };\n /**\n * Starts all particle systems of the set\n * @param emitter defines an optional mesh to use as emitter for the particle systems\n */\n ParticleSystemSet.prototype.start = function (emitter) {\n for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {\n var system = _a[_i];\n if (emitter) {\n system.emitter = emitter;\n }\n system.start();\n }\n };\n /**\n * Release all associated resources\n */\n ParticleSystemSet.prototype.dispose = function () {\n for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {\n var system = _a[_i];\n system.dispose();\n }\n this.systems = [];\n if (this._emitterNode) {\n this._emitterNode.dispose();\n this._emitterNode = null;\n }\n };\n /**\n * Serialize the set into a JSON compatible object\n * @returns a JSON compatible representation of the set\n */\n ParticleSystemSet.prototype.serialize = function () {\n var result = {};\n result.systems = [];\n for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {\n var system = _a[_i];\n result.systems.push(system.serialize());\n }\n if (this._emitterNode) {\n result.emitter = this._emitterCreationOptions;\n }\n return result;\n };\n /**\n * Parse a new ParticleSystemSet from a serialized source\n * @param data defines a JSON compatible representation of the set\n * @param scene defines the hosting scene\n * @param gpu defines if we want GPU particles or CPU particles\n * @returns a new ParticleSystemSet\n */\n ParticleSystemSet.Parse = function (data, scene, gpu) {\n if (gpu === void 0) { gpu = false; }\n var result = new ParticleSystemSet();\n var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + \"/textures/\";\n scene = scene || BABYLON.Engine.LastCreatedScene;\n for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {\n var system = _a[_i];\n result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));\n }\n if (data.emitter) {\n var options = data.emitter.options;\n switch (data.emitter.kind) {\n case \"Sphere\":\n result.setEmitterAsSphere({\n diameter: options.diameter,\n segments: options.segments,\n color: BABYLON.Color3.FromArray(options.color)\n }, data.emitter.renderingGroupId, scene);\n break;\n }\n }\n return result;\n };\n return ParticleSystemSet;\n }());\n BABYLON.ParticleSystemSet = ParticleSystemSet;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.particleSystemSet.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class is made for on one-liner static method to help creating particle system set.\n */\n var ParticleHelper = /** @class */ (function () {\n function ParticleHelper() {\n }\n /**\n * Create a default particle system that you can tweak\n * @param emitter defines the emitter to use\n * @param capacity defines the system capacity (default is 500 particles)\n * @param scene defines the hosting scene\n * @returns the new Particle system\n */\n ParticleHelper.CreateDefault = function (emitter, capacity, scene) {\n if (capacity === void 0) { capacity = 500; }\n var system = new BABYLON.ParticleSystem(\"default system\", capacity, scene);\n system.emitter = emitter;\n system.particleTexture = new BABYLON.Texture(\"https://www.babylonjs.com/assets/Flare.png\", system.getScene());\n system.createConeEmitter(0.1, Math.PI / 4);\n // Particle color\n system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);\n // Particle Size\n system.minSize = 0.1;\n system.maxSize = 0.1;\n // Emission speed\n system.minEmitPower = 2;\n system.maxEmitPower = 2;\n system.emitRate = 30;\n return system;\n };\n /**\n * This is the main static method (one-liner) of this helper to create different particle systems\n * @param type This string represents the type to the particle system to create\n * @param scene The scene where the particle system should live\n * @param gpu If the system will use gpu\n * @returns the ParticleSystemSet created\n */\n ParticleHelper.CreateAsync = function (type, scene, gpu) {\n if (gpu === void 0) { gpu = false; }\n if (!scene) {\n scene = BABYLON.Engine.LastCreatedScene;\n ;\n }\n var token = {};\n scene._addPendingData(token);\n return new Promise(function (resolve, reject) {\n if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {\n scene._removePendingData(token);\n return reject(\"Particle system with GPU is not supported.\");\n }\n BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + \"/systems/\" + type + \".json\", function (data, response) {\n scene._removePendingData(token);\n var newData = JSON.parse(data.toString());\n return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));\n }, undefined, undefined, undefined, function (req, exception) {\n scene._removePendingData(token);\n return reject(\"An error occured while the creation of your particle system. Check if your type '\" + type + \"' exists.\");\n });\n });\n };\n /**\n * Static function used to export a particle system to a ParticleSystemSet variable.\n * Please note that the emitter shape is not exported\n * @param system defines the particle systems to export\n */\n ParticleHelper.ExportSet = function (systems) {\n var set = new BABYLON.ParticleSystemSet();\n for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {\n var system = systems_1[_i];\n set.systems.push(system);\n }\n return set;\n };\n /**\n * Gets or sets base Assets URL\n */\n ParticleHelper.BaseAssetsUrl = \"https://assets.babylonjs.com/particles\";\n return ParticleHelper;\n }());\n BABYLON.ParticleHelper = ParticleHelper;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.particleHelper.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.\n * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.\n * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.\n * Potential additions to this helper include zoom and and non-infinite distance rendering effects.\n */\n var VideoDome = /** @class */ (function (_super) {\n __extends(VideoDome, _super);\n /**\n * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.\n * @param name Element's name, child elements will append suffixes for their own names.\n * @param urlsOrVideo defines the url(s) or the video element to use\n * @param options An object containing optional or exposed sub element properties\n */\n function VideoDome(name, urlsOrVideo, options, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._useDirectMapping = false;\n // set defaults and manage values\n name = name || \"videoDome\";\n options.resolution = (Math.abs(options.resolution) | 0) || 32;\n options.clickToPlay = Boolean(options.clickToPlay);\n options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);\n options.loop = options.loop === undefined ? true : Boolean(options.loop);\n options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);\n if (options.useDirectMapping === undefined) {\n _this._useDirectMapping = true;\n }\n else {\n _this._useDirectMapping = options.useDirectMapping;\n }\n _this._setReady(false);\n // create\n var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };\n var material = _this._material = new BABYLON.BackgroundMaterial(name + \"_material\", scene);\n var texture = _this._videoTexture = new BABYLON.VideoTexture(name + \"_texture\", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);\n _this._mesh = BABYLON.Mesh.CreateSphere(name + \"_mesh\", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);\n texture.onLoadObservable.addOnce(function () {\n _this._setReady(true);\n });\n // configure material\n material.useEquirectangularFOV = true;\n material.fovMultiplier = 1.0;\n material.opacityFresnel = false;\n if (_this._useDirectMapping) {\n texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n material.diffuseTexture = texture;\n }\n else {\n texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation\n texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n material.reflectionTexture = texture;\n }\n // configure mesh\n _this._mesh.material = material;\n _this._mesh.parent = _this;\n // optional configuration\n if (options.clickToPlay) {\n scene.onPointerUp = function () {\n _this._videoTexture.video.play();\n };\n }\n return _this;\n }\n Object.defineProperty(VideoDome.prototype, \"videoTexture\", {\n /**\n * Gets the video texture being displayed on the sphere\n */\n get: function () {\n return this._videoTexture;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VideoDome.prototype, \"fovMultiplier\", {\n /**\n * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values \"zoom in\" and higher values \"zoom out\".\n * Also see the options.resolution property.\n */\n get: function () {\n return this._material.fovMultiplier;\n },\n set: function (value) {\n this._material.fovMultiplier = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n this._videoTexture.dispose();\n this._mesh.dispose();\n this._material.dispose();\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n return VideoDome;\n }(BABYLON.Node));\n BABYLON.VideoDome = VideoDome;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.videoDome.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.\n * As a subclass of Node, this allow parenting to the camera with different locations in the scene.\n * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.\n * Potential additions to this helper include zoom and and non-infinite distance rendering effects.\n */\n var PhotoDome = /** @class */ (function (_super) {\n __extends(PhotoDome, _super);\n /**\n * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.\n * @param name Element's name, child elements will append suffixes for their own names.\n * @param urlsOfPhoto define the url of the photo to display\n * @param options An object containing optional or exposed sub element properties\n */\n function PhotoDome(name, urlOfPhoto, options, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._useDirectMapping = false;\n // set defaults and manage values\n name = name || \"photoDome\";\n options.resolution = (Math.abs(options.resolution) | 0) || 32;\n options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);\n if (options.useDirectMapping === undefined) {\n _this._useDirectMapping = true;\n }\n else {\n _this._useDirectMapping = options.useDirectMapping;\n }\n _this._setReady(false);\n // create\n var material = _this._material = new BABYLON.BackgroundMaterial(name + \"_material\", scene);\n _this._mesh = BABYLON.Mesh.CreateSphere(name + \"_mesh\", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);\n // configure material\n material.opacityFresnel = false;\n material.useEquirectangularFOV = true;\n material.fovMultiplier = 1.0;\n _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);\n _this.photoTexture.onLoadObservable.addOnce(function () {\n _this._setReady(true);\n });\n // configure mesh\n _this._mesh.material = material;\n _this._mesh.parent = _this;\n return _this;\n }\n Object.defineProperty(PhotoDome.prototype, \"photoTexture\", {\n /**\n * Gets or sets the texture being displayed on the sphere\n */\n get: function () {\n return this._photoTexture;\n },\n set: function (value) {\n if (this._photoTexture === value) {\n return;\n }\n this._photoTexture = value;\n if (this._useDirectMapping) {\n this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._material.diffuseTexture = this._photoTexture;\n }\n else {\n this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation\n this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._material.reflectionTexture = this._photoTexture;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PhotoDome.prototype, \"fovMultiplier\", {\n /**\n * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values \"zoom in\" and higher values \"zoom out\".\n * Also see the options.resolution property.\n */\n get: function () {\n return this._material.fovMultiplier;\n },\n set: function (value) {\n this._material.fovMultiplier = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n this._photoTexture.dispose();\n this._mesh.dispose();\n this._material.dispose();\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n return PhotoDome;\n }(BABYLON.Node));\n BABYLON.PhotoDome = PhotoDome;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.photoDome.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Engine.prototype.createQuery = function () {\n return this._gl.createQuery();\n };\n BABYLON.Engine.prototype.deleteQuery = function (query) {\n this._gl.deleteQuery(query);\n return this;\n };\n BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {\n return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);\n };\n BABYLON.Engine.prototype.getQueryResult = function (query) {\n return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);\n };\n BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {\n var glAlgorithm = this._getGlAlgorithmType(algorithmType);\n this._gl.beginQuery(glAlgorithm, query);\n return this;\n };\n BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {\n var glAlgorithm = this._getGlAlgorithmType(algorithmType);\n this._gl.endQuery(glAlgorithm);\n return this;\n };\n BABYLON.Engine.prototype._createTimeQuery = function () {\n var timerQuery = this.getCaps().timerQuery;\n if (timerQuery.createQueryEXT) {\n return timerQuery.createQueryEXT();\n }\n return this.createQuery();\n };\n BABYLON.Engine.prototype._deleteTimeQuery = function (query) {\n var timerQuery = this.getCaps().timerQuery;\n if (timerQuery.deleteQueryEXT) {\n timerQuery.deleteQueryEXT(query);\n return;\n }\n this.deleteQuery(query);\n };\n BABYLON.Engine.prototype._getTimeQueryResult = function (query) {\n var timerQuery = this.getCaps().timerQuery;\n if (timerQuery.getQueryObjectEXT) {\n return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);\n }\n return this.getQueryResult(query);\n };\n BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {\n var timerQuery = this.getCaps().timerQuery;\n if (timerQuery.getQueryObjectEXT) {\n return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);\n }\n return this.isQueryResultAvailable(query);\n };\n BABYLON.Engine.prototype.startTimeQuery = function () {\n var caps = this.getCaps();\n var timerQuery = caps.timerQuery;\n if (!timerQuery) {\n return null;\n }\n var token = new BABYLON._TimeToken();\n this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);\n if (caps.canUseTimestampForTimerQuery) {\n token._startTimeQuery = this._createTimeQuery();\n timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);\n }\n else {\n if (this._currentNonTimestampToken) {\n return this._currentNonTimestampToken;\n }\n token._timeElapsedQuery = this._createTimeQuery();\n if (timerQuery.beginQueryEXT) {\n timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);\n }\n else {\n this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);\n }\n this._currentNonTimestampToken = token;\n }\n return token;\n };\n BABYLON.Engine.prototype.endTimeQuery = function (token) {\n var caps = this.getCaps();\n var timerQuery = caps.timerQuery;\n if (!timerQuery || !token) {\n return -1;\n }\n if (caps.canUseTimestampForTimerQuery) {\n if (!token._startTimeQuery) {\n return -1;\n }\n if (!token._endTimeQuery) {\n token._endTimeQuery = this._createTimeQuery();\n timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);\n }\n }\n else if (!token._timeElapsedQueryEnded) {\n if (!token._timeElapsedQuery) {\n return -1;\n }\n if (timerQuery.endQueryEXT) {\n timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);\n }\n else {\n this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);\n }\n token._timeElapsedQueryEnded = true;\n }\n var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);\n var available = false;\n if (token._endTimeQuery) {\n available = this._getTimeQueryAvailability(token._endTimeQuery);\n }\n else if (token._timeElapsedQuery) {\n available = this._getTimeQueryAvailability(token._timeElapsedQuery);\n }\n if (available && !disjoint) {\n var result = 0;\n if (caps.canUseTimestampForTimerQuery) {\n if (!token._startTimeQuery || !token._endTimeQuery) {\n return -1;\n }\n var timeStart = this._getTimeQueryResult(token._startTimeQuery);\n var timeEnd = this._getTimeQueryResult(token._endTimeQuery);\n result = timeEnd - timeStart;\n this._deleteTimeQuery(token._startTimeQuery);\n this._deleteTimeQuery(token._endTimeQuery);\n token._startTimeQuery = null;\n token._endTimeQuery = null;\n }\n else {\n if (!token._timeElapsedQuery) {\n return -1;\n }\n result = this._getTimeQueryResult(token._timeElapsedQuery);\n this._deleteTimeQuery(token._timeElapsedQuery);\n token._timeElapsedQuery = null;\n token._timeElapsedQueryEnded = false;\n this._currentNonTimestampToken = null;\n }\n return result;\n }\n return -1;\n };\n BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {\n return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;\n };\n // We also need to update AbstractMesh as there is a portion of the code there\n BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {\n var engine = this.getEngine();\n if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced\n this._isOccluded = false;\n return;\n }\n if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {\n this._isOccluded = false;\n return;\n }\n if (this.isOcclusionQueryInProgress && this._occlusionQuery) {\n var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);\n if (isOcclusionQueryAvailable) {\n var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);\n this._isOcclusionQueryInProgress = false;\n this._occlusionInternalRetryCounter = 0;\n this._isOccluded = occlusionQueryResult === 1 ? false : true;\n }\n else {\n this._occlusionInternalRetryCounter++;\n if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {\n this._isOcclusionQueryInProgress = false;\n this._occlusionInternalRetryCounter = 0;\n // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)\n // if strict continue the last state of the object.\n this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;\n }\n else {\n return;\n }\n }\n }\n var scene = this.getScene();\n if (scene.getBoundingBoxRenderer) {\n var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();\n if (!this._occlusionQuery) {\n this._occlusionQuery = engine.createQuery();\n }\n engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);\n occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);\n engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);\n this._isOcclusionQueryInProgress = true;\n }\n };\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.engine.occlusionQuery.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to generate noise procedural textures\n */\n var NoiseProceduralTexture = /** @class */ (function (_super) {\n __extends(NoiseProceduralTexture, _super);\n /**\n * Creates a new NoiseProceduralTexture\n * @param name defines the name fo the texture\n * @param size defines the size of the texture (default is 256)\n * @param scene defines the hosting scene\n * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created\n * @param generateMipMaps defines if mipmaps must be generated (true by default)\n */\n function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {\n if (size === void 0) { size = 256; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n var _this = _super.call(this, name, size, \"noise\", scene, fallbackTexture, generateMipMaps) || this;\n _this._time = 0;\n /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */\n _this.brightness = 0.2;\n /** Defines the number of octaves to process */\n _this.octaves = 3;\n /** Defines the level of persistence (0.8 by default) */\n _this.persistence = 0.8;\n /** Gets or sets animation speed factor (default is 1) */\n _this.animationSpeedFactor = 1;\n _this._updateShaderUniforms();\n return _this;\n }\n NoiseProceduralTexture.prototype._updateShaderUniforms = function () {\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;\n this.setFloat(\"brightness\", this.brightness);\n this.setInt(\"octaves\", this.octaves);\n this.setFloat(\"persistence\", this.persistence);\n this.setFloat(\"timeScale\", this._time);\n };\n /** Generate the current state of the procedural texture */\n NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {\n this._updateShaderUniforms();\n _super.prototype.render.call(this, useCameraPostProcess);\n };\n /**\n * Serializes this noise procedural texture\n * @returns a serialized noise procedural texture object\n */\n NoiseProceduralTexture.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));\n serializationObject.customType = \"BABYLON.NoiseProceduralTexture\";\n return serializationObject;\n };\n /**\n * Creates a NoiseProceduralTexture from parsed noise procedural texture data\n * @param parsedTexture defines parsed texture data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing noise procedural texture information\n * @returns a parsed NoiseProceduralTexture\n */\n NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {\n var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);\n return texture;\n };\n return NoiseProceduralTexture;\n }(BABYLON.ProceduralTexture));\n BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.noiseProceduralTexture.js.map\n\nBABYLON.Effect.ShadersStore={\"defaultVertexShader\":\"#include<__decl__defaultVertex>\\n\\n#define CUSTOM_VERTEX_BEGIN\\nattribute vec3 position;\\n#ifdef NORMAL\\nattribute vec3 normal;\\n#endif\\n#ifdef TANGENT\\nattribute vec4 tangent;\\n#endif\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#ifdef VERTEXCOLOR\\nattribute vec4 color;\\n#endif\\n#include\\n#include\\n\\n#include\\n#ifdef MAINUV1\\nvarying vec2 vMainUV1;\\n#endif\\n#ifdef MAINUV2\\nvarying vec2 vMainUV2;\\n#endif\\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\\nvarying vec2 vDiffuseUV;\\n#endif\\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\\nvarying vec2 vAmbientUV;\\n#endif\\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\\nvarying vec2 vOpacityUV;\\n#endif\\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\\nvarying vec2 vEmissiveUV;\\n#endif\\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\\nvarying vec2 vLightmapUV;\\n#endif\\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\\nvarying vec2 vSpecularUV;\\n#endif\\n#if defined(BUMP) && BUMPDIRECTUV == 0\\nvarying vec2 vBumpUV;\\n#endif\\n\\nvarying vec3 vPositionW;\\n#ifdef NORMAL\\nvarying vec3 vNormalW;\\n#endif\\n#ifdef VERTEXCOLOR\\nvarying vec4 vColor;\\n#endif\\n#include\\n#include\\n#include\\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\\n#include\\n#include[0..maxSimultaneousMorphTargets]\\n#ifdef REFLECTIONMAP_SKYBOX\\nvarying vec3 vPositionUVW;\\n#endif\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvarying vec3 vDirectionW;\\n#endif\\n#include\\n#define CUSTOM_VERTEX_DEFINITIONS\\nvoid main(void) {\\n#define CUSTOM_VERTEX_MAIN_BEGIN\\nvec3 positionUpdated=position;\\n#ifdef NORMAL \\nvec3 normalUpdated=normal;\\n#endif\\n#ifdef TANGENT\\nvec4 tangentUpdated=tangent;\\n#endif\\n#include[0..maxSimultaneousMorphTargets]\\n#ifdef REFLECTIONMAP_SKYBOX\\nvPositionUVW=positionUpdated;\\n#endif \\n#define CUSTOM_VERTEX_UPDATE_POSITION\\n#define CUSTOM_VERTEX_UPDATE_NORMAL\\n#include\\n#include\\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\\nvPositionW=vec3(worldPos);\\n#ifdef NORMAL\\nmat3 normalWorld=mat3(finalWorld);\\n#ifdef NONUNIFORMSCALING\\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\\n#endif\\nvNormalW=normalize(normalWorld*normalUpdated);\\n#endif\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\\n#endif\\n\\n#ifndef UV1\\nvec2 uv=vec2(0.,0.);\\n#endif\\n#ifndef UV2\\nvec2 uv2=vec2(0.,0.);\\n#endif\\n#ifdef MAINUV1\\nvMainUV1=uv;\\n#endif\\n#ifdef MAINUV2\\nvMainUV2=uv2;\\n#endif\\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\\nif (vDiffuseInfos.x == 0.)\\n{\\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\\nif (vAmbientInfos.x == 0.)\\n{\\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\\nif (vOpacityInfos.x == 0.)\\n{\\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\\nif (vEmissiveInfos.x == 0.)\\n{\\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\\nif (vLightmapInfos.x == 0.)\\n{\\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\\nif (vSpecularInfos.x == 0.)\\n{\\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(BUMP) && BUMPDIRECTUV == 0\\nif (vBumpInfos.x == 0.)\\n{\\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#include\\n#include\\n#include\\n#include[0..maxSimultaneousLights]\\n#ifdef VERTEXCOLOR\\n\\nvColor=color;\\n#endif\\n#include\\n#include\\n#define CUSTOM_VERTEX_MAIN_END\\n}\\n\",\"defaultPixelShader\":\"#include<__decl__defaultFragment>\\n#if defined(BUMP) || !defined(NORMAL)\\n#extension GL_OES_standard_derivatives : enable\\n#endif\\n#define CUSTOM_FRAGMENT_BEGIN\\n#ifdef LOGARITHMICDEPTH\\n#extension GL_EXT_frag_depth : enable\\n#endif\\n\\n#define RECIPROCAL_PI2 0.15915494\\nuniform vec3 vEyePosition;\\nuniform vec3 vAmbientColor;\\n\\nvarying vec3 vPositionW;\\n#ifdef NORMAL\\nvarying vec3 vNormalW;\\n#endif\\n#ifdef VERTEXCOLOR\\nvarying vec4 vColor;\\n#endif\\n#ifdef MAINUV1\\nvarying vec2 vMainUV1;\\n#endif\\n#ifdef MAINUV2\\nvarying vec2 vMainUV2;\\n#endif\\n\\n#include\\n\\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\\n#include\\n#include\\n\\n#ifdef DIFFUSE\\n#if DIFFUSEDIRECTUV == 1\\n#define vDiffuseUV vMainUV1\\n#elif DIFFUSEDIRECTUV == 2\\n#define vDiffuseUV vMainUV2\\n#else\\nvarying vec2 vDiffuseUV;\\n#endif\\nuniform sampler2D diffuseSampler;\\n#endif\\n#ifdef AMBIENT\\n#if AMBIENTDIRECTUV == 1\\n#define vAmbientUV vMainUV1\\n#elif AMBIENTDIRECTUV == 2\\n#define vAmbientUV vMainUV2\\n#else\\nvarying vec2 vAmbientUV;\\n#endif\\nuniform sampler2D ambientSampler;\\n#endif\\n#ifdef OPACITY \\n#if OPACITYDIRECTUV == 1\\n#define vOpacityUV vMainUV1\\n#elif OPACITYDIRECTUV == 2\\n#define vOpacityUV vMainUV2\\n#else\\nvarying vec2 vOpacityUV;\\n#endif\\nuniform sampler2D opacitySampler;\\n#endif\\n#ifdef EMISSIVE\\n#if EMISSIVEDIRECTUV == 1\\n#define vEmissiveUV vMainUV1\\n#elif EMISSIVEDIRECTUV == 2\\n#define vEmissiveUV vMainUV2\\n#else\\nvarying vec2 vEmissiveUV;\\n#endif\\nuniform sampler2D emissiveSampler;\\n#endif\\n#ifdef LIGHTMAP\\n#if LIGHTMAPDIRECTUV == 1\\n#define vLightmapUV vMainUV1\\n#elif LIGHTMAPDIRECTUV == 2\\n#define vLightmapUV vMainUV2\\n#else\\nvarying vec2 vLightmapUV;\\n#endif\\nuniform sampler2D lightmapSampler;\\n#endif\\n#ifdef REFRACTION\\n#ifdef REFRACTIONMAP_3D\\nuniform samplerCube refractionCubeSampler;\\n#else\\nuniform sampler2D refraction2DSampler;\\n#endif\\n#endif\\n#if defined(SPECULAR) && defined(SPECULARTERM)\\n#if SPECULARDIRECTUV == 1\\n#define vSpecularUV vMainUV1\\n#elif SPECULARDIRECTUV == 2\\n#define vSpecularUV vMainUV2\\n#else\\nvarying vec2 vSpecularUV;\\n#endif\\nuniform sampler2D specularSampler;\\n#endif\\n#ifdef ALPHATEST\\nuniform float alphaCutOff;\\n#endif\\n\\n#include\\n\\n#ifdef REFLECTION\\n#ifdef REFLECTIONMAP_3D\\nuniform samplerCube reflectionCubeSampler;\\n#else\\nuniform sampler2D reflection2DSampler;\\n#endif\\n#ifdef REFLECTIONMAP_SKYBOX\\nvarying vec3 vPositionUVW;\\n#else\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvarying vec3 vDirectionW;\\n#endif\\n#endif\\n#include\\n#endif\\n#include\\n#include\\n#include\\n#include\\n#include\\n#include\\n#define CUSTOM_FRAGMENT_DEFINITIONS\\nvoid main(void) {\\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\\n#include\\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\\n\\nvec4 baseColor=vec4(1.,1.,1.,1.);\\nvec3 diffuseColor=vDiffuseColor.rgb;\\n\\nfloat alpha=vDiffuseColor.a;\\n\\n#ifdef NORMAL\\nvec3 normalW=normalize(vNormalW);\\n#else\\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\\n#endif\\n#include\\n#ifdef TWOSIDEDLIGHTING\\nnormalW=gl_FrontFacing ? normalW : -normalW;\\n#endif\\n#ifdef DIFFUSE\\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\\n#ifdef ALPHATEST\\nif (baseColor.a\\n#ifdef VERTEXCOLOR\\nbaseColor.rgb*=vColor.rgb;\\n#endif\\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\\n\\nvec3 baseAmbientColor=vec3(1.,1.,1.);\\n#ifdef AMBIENT\\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\\n#endif\\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\\n\\n#ifdef SPECULARTERM\\nfloat glossiness=vSpecularColor.a;\\nvec3 specularColor=vSpecularColor.rgb;\\n#ifdef SPECULAR\\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\\nspecularColor=specularMapColor.rgb;\\n#ifdef GLOSSINESS\\nglossiness=glossiness*specularMapColor.a;\\n#endif\\n#endif\\n#else\\nfloat glossiness=0.;\\n#endif\\n\\nvec3 diffuseBase=vec3(0.,0.,0.);\\nlightingInfo info;\\n#ifdef SPECULARTERM\\nvec3 specularBase=vec3(0.,0.,0.);\\n#endif\\nfloat shadow=1.;\\n#ifdef LIGHTMAP\\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\\n#endif\\n#include[0..maxSimultaneousLights]\\n\\nvec3 refractionColor=vec3(0.,0.,0.);\\n#ifdef REFRACTION\\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\\n#ifdef REFRACTIONMAP_3D\\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\\nif (dot(refractionVector,viewDirectionW)<1.0) {\\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\\n}\\n#else\\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\\nrefractionCoords.y=1.0-refractionCoords.y;\\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\\n#endif\\n#ifdef IS_REFRACTION_LINEAR\\nrefractionColor=toGammaSpace(refractionColor);\\n#endif\\nrefractionColor*=vRefractionInfos.x;\\n#endif\\n\\nvec3 reflectionColor=vec3(0.,0.,0.);\\n#ifdef REFLECTION\\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\\n#ifdef REFLECTIONMAP_3D\\n#ifdef ROUGHNESS\\nfloat bias=vReflectionInfos.y;\\n#ifdef SPECULARTERM\\n#ifdef SPECULAR\\n#ifdef GLOSSINESS\\nbias*=(1.0-specularMapColor.a);\\n#endif\\n#endif\\n#endif\\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\\n#else\\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\\n#endif\\n#else\\nvec2 coords=vReflectionUVW.xy;\\n#ifdef REFLECTIONMAP_PROJECTION\\ncoords/=vReflectionUVW.z;\\n#endif\\ncoords.y=1.0-coords.y;\\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\\n#endif\\n#ifdef IS_REFLECTION_LINEAR\\nreflectionColor=toGammaSpace(reflectionColor);\\n#endif\\nreflectionColor*=vReflectionInfos.x;\\n#ifdef REFLECTIONFRESNEL\\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\\n#ifdef REFLECTIONFRESNELFROMSPECULAR\\n#ifdef SPECULARTERM\\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\\n#else\\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\\n#endif\\n#else\\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\\n#endif\\n#endif\\n#endif\\n#ifdef REFRACTIONFRESNEL\\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\\n#endif\\n#ifdef OPACITY\\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\\n#ifdef OPACITYRGB\\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\\n#else\\nalpha*=opacityMap.a*vOpacityInfos.y;\\n#endif\\n#endif\\n#ifdef VERTEXALPHA\\nalpha*=vColor.a;\\n#endif\\n#ifdef OPACITYFRESNEL\\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\\n#endif\\n\\nvec3 emissiveColor=vEmissiveColor;\\n#ifdef EMISSIVE\\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\\n#endif\\n#ifdef EMISSIVEFRESNEL\\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\\n#endif\\n\\n#ifdef DIFFUSEFRESNEL\\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\\n#endif\\n\\n#ifdef EMISSIVEASILLUMINATION\\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\\n#else\\n#ifdef LINKEMISSIVEWITHDIFFUSE\\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\\n#else\\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\\n#endif\\n#endif\\n#ifdef SPECULARTERM\\nvec3 finalSpecular=specularBase*specularColor;\\n#ifdef SPECULAROVERALPHA\\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\\n#endif\\n#else\\nvec3 finalSpecular=vec3(0.0);\\n#endif\\n#ifdef REFLECTIONOVERALPHA\\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\\n#endif\\n\\n#ifdef EMISSIVEASILLUMINATION\\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\\n#else\\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\\n#endif\\n\\n#ifdef LIGHTMAP\\n#ifndef LIGHTMAPEXCLUDED\\n#ifdef USELIGHTMAPASSHADOWMAP\\ncolor.rgb*=lightmapColor;\\n#else\\ncolor.rgb+=lightmapColor;\\n#endif\\n#endif\\n#endif\\n#define CUSTOM_FRAGMENT_BEFORE_FOG\\ncolor.rgb=max(color.rgb,0.);\\n#include\\n#include\\n\\n\\n#ifdef IMAGEPROCESSINGPOSTPROCESS\\ncolor.rgb=toLinearSpace(color.rgb);\\n#else\\n#ifdef IMAGEPROCESSING\\ncolor.rgb=toLinearSpace(color.rgb);\\ncolor=applyImageProcessing(color);\\n#endif\\n#endif\\n#ifdef PREMULTIPLYALPHA\\n\\ncolor.rgb*=color.a;\\n#endif\\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\\ngl_FragColor=color;\\n}\\n\",\"pbrVertexShader\":\"precision highp float;\\n#include<__decl__pbrVertex>\\n\\nattribute vec3 position;\\n#ifdef NORMAL\\nattribute vec3 normal;\\n#endif\\n#ifdef TANGENT\\nattribute vec4 tangent;\\n#endif\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#ifdef MAINUV1\\nvarying vec2 vMainUV1;\\n#endif\\n#ifdef MAINUV2\\nvarying vec2 vMainUV2; \\n#endif \\n#ifdef VERTEXCOLOR\\nattribute vec4 color;\\n#endif\\n#include\\n#include\\n\\n#include\\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\\nvarying vec2 vAlbedoUV;\\n#endif\\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\\nvarying vec2 vAmbientUV;\\n#endif\\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\\nvarying vec2 vOpacityUV;\\n#endif\\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\\nvarying vec2 vEmissiveUV;\\n#endif\\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\\nvarying vec2 vLightmapUV;\\n#endif\\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\\nvarying vec2 vReflectivityUV;\\n#endif\\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\\nvarying vec2 vMicroSurfaceSamplerUV;\\n#endif\\n#if defined(BUMP) && BUMPDIRECTUV == 0\\nvarying vec2 vBumpUV;\\n#endif\\n\\nvarying vec3 vPositionW;\\n#ifdef NORMAL\\nvarying vec3 vNormalW;\\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\\nvarying vec3 vEnvironmentIrradiance;\\n#include\\n#endif\\n#endif\\n#ifdef VERTEXCOLOR\\nvarying vec4 vColor;\\n#endif\\n#include\\n#include\\n#include\\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\\n#include\\n#include[0..maxSimultaneousMorphTargets]\\n#ifdef REFLECTIONMAP_SKYBOX\\nvarying vec3 vPositionUVW;\\n#endif\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvarying vec3 vDirectionW;\\n#endif\\n#include\\nvoid main(void) {\\nvec3 positionUpdated=position;\\n#ifdef NORMAL\\nvec3 normalUpdated=normal;\\n#endif\\n#ifdef TANGENT\\nvec4 tangentUpdated=tangent;\\n#endif\\n#include[0..maxSimultaneousMorphTargets]\\n#ifdef REFLECTIONMAP_SKYBOX\\nvPositionUVW=positionUpdated;\\n#endif \\n#include\\n#include\\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\\nvPositionW=vec3(worldPos);\\n#ifdef NORMAL\\nmat3 normalWorld=mat3(finalWorld);\\n#ifdef NONUNIFORMSCALING\\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\\n#endif\\nvNormalW=normalize(normalWorld*normalUpdated);\\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\\n#ifdef REFLECTIONMAP_OPPOSITEZ\\nreflectionVector.z*=-1.0;\\n#endif\\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\\n#endif\\n#endif\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\\n#endif\\n\\n#ifndef UV1\\nvec2 uv=vec2(0.,0.);\\n#endif\\n#ifndef UV2\\nvec2 uv2=vec2(0.,0.);\\n#endif\\n#ifdef MAINUV1\\nvMainUV1=uv;\\n#endif \\n#ifdef MAINUV2\\nvMainUV2=uv2;\\n#endif \\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \\nif (vAlbedoInfos.x == 0.)\\n{\\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \\nif (vAmbientInfos.x == 0.)\\n{\\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \\nif (vOpacityInfos.x == 0.)\\n{\\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \\nif (vEmissiveInfos.x == 0.)\\n{\\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \\nif (vLightmapInfos.x == 0.)\\n{\\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \\nif (vReflectivityInfos.x == 0.)\\n{\\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \\nif (vMicroSurfaceSamplerInfos.x == 0.)\\n{\\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(BUMP) && BUMPDIRECTUV == 0 \\nif (vBumpInfos.x == 0.)\\n{\\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n\\n#include\\n\\n#include\\n\\n#include\\n\\n#include[0..maxSimultaneousLights]\\n\\n#ifdef VERTEXCOLOR\\nvColor=color;\\n#endif\\n\\n#ifdef POINTSIZE\\ngl_PointSize=pointSize;\\n#endif\\n\\n#include\\n}\",\"pbrPixelShader\":\"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\\n#extension GL_OES_standard_derivatives : enable\\n#endif\\n#ifdef LODBASEDMICROSFURACE\\n#extension GL_EXT_shader_texture_lod : enable\\n#endif\\n#ifdef LOGARITHMICDEPTH\\n#extension GL_EXT_frag_depth : enable\\n#endif\\nprecision highp float;\\n#include<__decl__pbrFragment>\\nuniform vec4 vEyePosition;\\nuniform vec3 vAmbientColor;\\nuniform vec4 vCameraInfos;\\n\\nvarying vec3 vPositionW;\\n#ifdef MAINUV1\\nvarying vec2 vMainUV1;\\n#endif \\n#ifdef MAINUV2 \\nvarying vec2 vMainUV2;\\n#endif \\n#ifdef NORMAL\\nvarying vec3 vNormalW;\\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\\nvarying vec3 vEnvironmentIrradiance;\\n#endif\\n#endif\\n#ifdef VERTEXCOLOR\\nvarying vec4 vColor;\\n#endif\\n\\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\\n\\n#ifdef ALBEDO\\n#if ALBEDODIRECTUV == 1\\n#define vAlbedoUV vMainUV1\\n#elif ALBEDODIRECTUV == 2\\n#define vAlbedoUV vMainUV2\\n#else\\nvarying vec2 vAlbedoUV;\\n#endif\\nuniform sampler2D albedoSampler;\\n#endif\\n#ifdef AMBIENT\\n#if AMBIENTDIRECTUV == 1\\n#define vAmbientUV vMainUV1\\n#elif AMBIENTDIRECTUV == 2\\n#define vAmbientUV vMainUV2\\n#else\\nvarying vec2 vAmbientUV;\\n#endif\\nuniform sampler2D ambientSampler;\\n#endif\\n#ifdef OPACITY\\n#if OPACITYDIRECTUV == 1\\n#define vOpacityUV vMainUV1\\n#elif OPACITYDIRECTUV == 2\\n#define vOpacityUV vMainUV2\\n#else\\nvarying vec2 vOpacityUV;\\n#endif\\nuniform sampler2D opacitySampler;\\n#endif\\n#ifdef EMISSIVE\\n#if EMISSIVEDIRECTUV == 1\\n#define vEmissiveUV vMainUV1\\n#elif EMISSIVEDIRECTUV == 2\\n#define vEmissiveUV vMainUV2\\n#else\\nvarying vec2 vEmissiveUV;\\n#endif\\nuniform sampler2D emissiveSampler;\\n#endif\\n#ifdef LIGHTMAP\\n#if LIGHTMAPDIRECTUV == 1\\n#define vLightmapUV vMainUV1\\n#elif LIGHTMAPDIRECTUV == 2\\n#define vLightmapUV vMainUV2\\n#else\\nvarying vec2 vLightmapUV;\\n#endif\\nuniform sampler2D lightmapSampler;\\n#endif\\n#ifdef REFLECTIVITY\\n#if REFLECTIVITYDIRECTUV == 1\\n#define vReflectivityUV vMainUV1\\n#elif REFLECTIVITYDIRECTUV == 2\\n#define vReflectivityUV vMainUV2\\n#else\\nvarying vec2 vReflectivityUV;\\n#endif\\nuniform sampler2D reflectivitySampler;\\n#endif\\n#ifdef MICROSURFACEMAP\\n#if MICROSURFACEMAPDIRECTUV == 1\\n#define vMicroSurfaceSamplerUV vMainUV1\\n#elif MICROSURFACEMAPDIRECTUV == 2\\n#define vMicroSurfaceSamplerUV vMainUV2\\n#else\\nvarying vec2 vMicroSurfaceSamplerUV;\\n#endif\\nuniform sampler2D microSurfaceSampler;\\n#endif\\n\\n#ifdef REFRACTION\\n#ifdef REFRACTIONMAP_3D\\n#define sampleRefraction(s,c) textureCube(s,c)\\nuniform samplerCube refractionSampler;\\n#ifdef LODBASEDMICROSFURACE\\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\\n#else\\nuniform samplerCube refractionSamplerLow;\\nuniform samplerCube refractionSamplerHigh;\\n#endif\\n#else\\n#define sampleRefraction(s,c) texture2D(s,c)\\nuniform sampler2D refractionSampler;\\n#ifdef LODBASEDMICROSFURACE\\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\\n#else\\nuniform samplerCube refractionSamplerLow;\\nuniform samplerCube refractionSamplerHigh;\\n#endif\\n#endif\\n#endif\\n\\n#ifdef REFLECTION\\n#ifdef REFLECTIONMAP_3D\\n#define sampleReflection(s,c) textureCube(s,c)\\nuniform samplerCube reflectionSampler;\\n#ifdef LODBASEDMICROSFURACE\\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\\n#else\\nuniform samplerCube reflectionSamplerLow;\\nuniform samplerCube reflectionSamplerHigh;\\n#endif\\n#else\\n#define sampleReflection(s,c) texture2D(s,c)\\nuniform sampler2D reflectionSampler;\\n#ifdef LODBASEDMICROSFURACE\\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\\n#else\\nuniform samplerCube reflectionSamplerLow;\\nuniform samplerCube reflectionSamplerHigh;\\n#endif\\n#endif\\n#ifdef REFLECTIONMAP_SKYBOX\\nvarying vec3 vPositionUVW;\\n#else\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvarying vec3 vDirectionW;\\n#endif\\n#endif\\n#include\\n#endif\\n#ifdef ENVIRONMENTBRDF\\nuniform sampler2D environmentBrdfSampler;\\n#endif\\n\\n#ifndef FROMLINEARSPACE\\n#define FROMLINEARSPACE;\\n#endif\\n#include\\n#include\\n#include\\n\\n#include\\n#include\\n#include\\n#include\\n#include\\n#include\\n#include\\n\\n#include\\nvoid main(void) {\\n#include\\n\\n\\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\\n#ifdef NORMAL\\nvec3 normalW=normalize(vNormalW);\\n#else\\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\\n#endif\\n#include\\n#ifdef SPECULARAA\\nvec3 nDfdx=dFdx(normalW.xyz);\\nvec3 nDfdy=dFdy(normalW.xyz);\\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\\n\\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\\n\\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\\n#else\\nfloat geometricRoughnessFactor=0.;\\n#endif\\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\\n#if defined(TWOSIDEDLIGHTING)\\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\\n#endif\\nnormalW*=sign(dot(normalW,faceNormal));\\n#endif\\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\\nnormalW=gl_FrontFacing ? normalW : -normalW;\\n#endif\\n\\n\\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\\n\\nfloat alpha=vAlbedoColor.a;\\n#ifdef ALBEDO\\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\\nalpha*=albedoTexture.a;\\n#endif\\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\\nsurfaceAlbedo*=vAlbedoInfos.y;\\n#endif\\n\\n#ifdef OPACITY\\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\\n#ifdef OPACITYRGB\\nalpha=getLuminance(opacityMap.rgb);\\n#else\\nalpha*=opacityMap.a;\\n#endif\\nalpha*=vOpacityInfos.y;\\n#endif\\n#ifdef VERTEXALPHA\\nalpha*=vColor.a;\\n#endif\\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\\n#ifdef ALPHATEST\\nif (alpha\\n#ifdef VERTEXCOLOR\\nsurfaceAlbedo*=vColor.rgb;\\n#endif\\n\\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\\n#ifdef AMBIENT\\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\\n#ifdef AMBIENTINGRAYSCALE\\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\\n#endif\\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\\n#endif\\n#ifdef UNLIT\\nvec3 diffuseBase=vec3(1.,1.,1.);\\n#else\\n\\nfloat microSurface=vReflectivityColor.a;\\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\\n#ifdef METALLICWORKFLOW\\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\\n#ifdef REFLECTIVITY\\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\\n#ifdef AOSTOREINMETALMAPRED\\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\\n#endif\\n#ifdef METALLNESSSTOREINMETALMAPBLUE\\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\\n#else\\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\\n#endif\\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\\n#else\\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\\n#endif\\n#endif\\n#endif\\n#ifdef MICROSURFACEMAP\\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\\nmetallicRoughness.g*=microSurfaceTexel.r;\\n#endif\\n\\nmicroSurface=1.0-metallicRoughness.g;\\n\\nvec3 baseColor=surfaceAlbedo;\\n\\n\\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\\n\\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\\n\\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\\n#else\\n#ifdef REFLECTIVITY\\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\\nsurfaceReflectivityColor*=vReflectivityInfos.y;\\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\\nmicroSurface*=surfaceReflectivityColorMap.a;\\nmicroSurface*=vReflectivityInfos.z;\\n#else\\n#ifdef MICROSURFACEAUTOMATIC\\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\\n#endif\\n#ifdef MICROSURFACEMAP\\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\\nmicroSurface*=microSurfaceTexel.r;\\n#endif\\n#endif\\n#endif\\n#endif\\n\\nmicroSurface=clamp(microSurface,0.,1.);\\n\\nfloat roughness=1.-microSurface;\\n\\n#ifdef ALPHAFRESNEL\\n#if defined(ALPHATEST) || defined(ALPHABLEND)\\n\\n\\n\\nfloat opacityPerceptual=alpha;\\n#ifdef LINEARALPHAFRESNEL\\nfloat opacity0=opacityPerceptual;\\n#else\\nfloat opacity0=opacityPerceptual*opacityPerceptual;\\n#endif\\nfloat opacity90=fresnelGrazingReflectance(opacity0);\\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\\n\\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\\n#ifdef ALPHATEST\\nif (alpha[0..maxSimultaneousLights]\\n\\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\\n\\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\\n\\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\\n#ifdef RADIANCEOCCLUSION\\n#ifdef AMBIENTINGRAYSCALE\\nfloat ambientMonochrome=ambientOcclusionColor.r;\\n#else\\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\\n#endif\\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\\nspecularEnvironmentReflectance*=seo;\\n#endif\\n#ifdef HORIZONOCCLUSION\\n#ifdef BUMP\\n#ifdef REFLECTIONMAP_3D\\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\\nspecularEnvironmentReflectance*=eho;\\n#endif\\n#endif\\n#endif\\n#else\\n\\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\\n#endif\\n\\n#ifdef REFRACTION\\nvec3 refractance=vec3(0.0,0.0,0.0);\\nvec3 transmission=vec3(1.0,1.0,1.0);\\n#ifdef LINKREFRACTIONTOTRANSPARENCY\\n\\ntransmission*=(1.0-alpha);\\n\\n\\nvec3 mixedAlbedo=surfaceAlbedo;\\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\\n\\nsurfaceAlbedo*=alpha;\\n\\nenvironmentIrradiance*=alpha;\\n\\nenvironmentRefraction.rgb*=tint;\\n\\nalpha=1.0;\\n#endif\\n\\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\\n\\ntransmission*=1.0-specularEnvironmentReflectance;\\n\\nrefractance=transmission;\\n#endif\\n\\n\\n\\n\\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\\n\\n#ifdef REFLECTION\\nvec3 finalIrradiance=environmentIrradiance;\\nfinalIrradiance*=surfaceAlbedo.rgb;\\n#endif\\n\\n#ifdef SPECULARTERM\\nvec3 finalSpecular=specularBase;\\nfinalSpecular=max(finalSpecular,0.0);\\n\\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\\n#endif\\n\\n#ifdef REFLECTION\\nvec3 finalRadiance=environmentRadiance.rgb;\\nfinalRadiance*=specularEnvironmentReflectance;\\n\\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\\n#endif\\n\\n#ifdef REFRACTION\\nvec3 finalRefraction=environmentRefraction.rgb;\\nfinalRefraction*=refractance;\\n#endif\\n\\n#ifdef ALPHABLEND\\nfloat luminanceOverAlpha=0.0;\\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\\n#endif\\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\\n#endif\\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\\n#endif\\n#endif\\n#endif\\n\\nvec3 finalDiffuse=diffuseBase;\\nfinalDiffuse.rgb+=vAmbientColor;\\nfinalDiffuse*=surfaceAlbedo.rgb;\\nfinalDiffuse=max(finalDiffuse,0.0);\\n\\nvec3 finalEmissive=vEmissiveColor;\\n#ifdef EMISSIVE\\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\\nfinalEmissive*=vEmissiveInfos.y;\\n#endif\\n\\n\\n\\nvec4 finalColor=vec4(\\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\\n#ifndef UNLIT\\n#ifdef REFLECTION\\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\\n#endif\\n#ifdef SPECULARTERM\\n\\n\\nfinalSpecularScaled +\\n#endif\\n#ifdef REFLECTION\\n\\n\\nfinalRadianceScaled +\\n#endif\\n#ifdef REFRACTION\\nfinalRefraction*vLightingIntensity.z +\\n#endif\\n#endif\\nfinalEmissive*vLightingIntensity.y,\\nalpha);\\n\\n#ifdef LIGHTMAP\\n#ifndef LIGHTMAPEXCLUDED\\n#ifdef USELIGHTMAPASSHADOWMAP\\nfinalColor.rgb*=lightmapColor;\\n#else\\nfinalColor.rgb+=lightmapColor;\\n#endif\\n#endif\\n#endif\\n\\nfinalColor=max(finalColor,0.0);\\n#include\\n#include(color,finalColor)\\n#ifdef IMAGEPROCESSINGPOSTPROCESS\\n\\n\\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\\n#else\\n\\nfinalColor=applyImageProcessing(finalColor);\\n#endif\\n#ifdef PREMULTIPLYALPHA\\n\\nfinalColor.rgb*=finalColor.a;\\n#endif\\ngl_FragColor=finalColor;\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n}\",\"rgbdEncodePixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n#include\\nvoid main(void) \\n{\\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\\n}\",\"rgbdDecodePixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n#include\\nvoid main(void) \\n{\\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\\n}\",\"spritesVertexShader\":\"\\nattribute vec4 position;\\nattribute vec4 options;\\nattribute vec4 cellInfo;\\nattribute vec4 color;\\n\\nuniform vec2 textureInfos;\\nuniform mat4 view;\\nuniform mat4 projection;\\n\\nvarying vec2 vUV;\\nvarying vec4 vColor;\\n#include\\nvoid main(void) { \\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \\nvec2 cornerPos;\\nfloat angle=position.w;\\nvec2 size=vec2(options.x,options.y);\\nvec2 offset=options.zw;\\nvec2 uvScale=textureInfos.xy;\\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\\n\\nvec3 rotatedCorner;\\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nrotatedCorner.z=0.;\\n\\nviewPos+=rotatedCorner;\\ngl_Position=projection*vec4(viewPos,1.0); \\n\\nvColor=color;\\n\\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\\nvUV=(uvOffset+cellInfo.zw)*uvScale;\\n\\n#ifdef FOG\\nvFogDistance=viewPos;\\n#endif\\n}\",\"spritesPixelShader\":\"uniform bool alphaTest;\\nvarying vec4 vColor;\\n\\nvarying vec2 vUV;\\nuniform sampler2D diffuseSampler;\\n\\n#include\\nvoid main(void) {\\nvec4 color=texture2D(diffuseSampler,vUV);\\nif (alphaTest) \\n{\\nif (color.a<0.95)\\ndiscard;\\n}\\ncolor*=vColor;\\n#include\\ngl_FragColor=color;\\n}\",\"particlesVertexShader\":\"\\nattribute vec3 position;\\nattribute vec4 color;\\nattribute float angle;\\nattribute vec2 size;\\n#ifdef ANIMATESHEET \\nattribute float cellIndex;\\n#endif\\n#ifndef BILLBOARD \\nattribute vec3 direction;\\n#endif\\nattribute vec2 offset;\\n\\nuniform mat4 view;\\nuniform mat4 projection;\\nuniform vec2 translationPivot;\\n#ifdef ANIMATESHEET \\nuniform vec3 particlesInfos; \\n#endif\\n\\nvarying vec2 vUV;\\nvarying vec4 vColor;\\n#ifdef CLIPPLANE\\nuniform vec4 vClipPlane;\\nuniform mat4 invView;\\nvarying float fClipDistance;\\n#endif\\n#ifdef BILLBOARD\\nuniform vec3 eyePosition; \\n#endif\\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\\nvec3 zaxis=normalize(cross(yaxis,xaxis));\\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\\nmat3 rotMatrix=mat3(row0,row1,row2);\\nvec3 alignedCorner=rotMatrix*rotatedCorner;\\nreturn position+alignedCorner; \\n}\\nvoid main(void) { \\nvec2 cornerPos;\\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\\n#ifdef BILLBOARD \\n\\nvec3 rotatedCorner;\\n#ifdef BILLBOARDY \\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nrotatedCorner.y=0.;\\nvec3 yaxis=position-eyePosition;\\nyaxis.y=0.;\\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \\n#else\\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nrotatedCorner.z=0.;\\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \\n#endif\\n\\ngl_Position=projection*vec4(viewPos,1.0); \\n#else\\n\\nvec3 rotatedCorner;\\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nrotatedCorner.y=0.;\\nvec3 yaxis=normalize(direction);\\nvec3 worldPos=rotate(yaxis,rotatedCorner);\\ngl_Position=projection*view*vec4(worldPos,1.0); \\n#endif \\nvColor=color;\\n#ifdef ANIMATESHEET\\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\\nvec2 uvScale=particlesInfos.xy;\\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\\n#else\\nvUV=offset;\\n#endif\\n\\n#ifdef CLIPPLANE\\nvec4 worldPos=invView*vec4(viewPos,1.0);\\nfClipDistance=dot(worldPos,vClipPlane);\\n#endif\\n}\",\"particlesPixelShader\":\"\\nvarying vec2 vUV;\\nvarying vec4 vColor;\\nuniform vec4 textureMask;\\nuniform sampler2D diffuseSampler;\\n#ifdef CLIPPLANE\\nvarying float fClipDistance;\\n#endif\\nvoid main(void) {\\n#ifdef CLIPPLANE\\nif (fClipDistance>0.0)\\ndiscard;\\n#endif\\nvec4 baseColor=texture2D(diffuseSampler,vUV);\\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\\n}\",\"colorVertexShader\":\"\\nattribute vec3 position;\\n#ifdef VERTEXCOLOR\\nattribute vec4 color;\\n#endif\\n#include\\n\\nuniform mat4 viewProjection;\\nuniform mat4 world;\\n\\n#ifdef VERTEXCOLOR\\nvarying vec4 vColor;\\n#endif\\nvoid main(void) {\\nmat4 finalWorld=world;\\n#include\\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\\n#ifdef VERTEXCOLOR\\n\\nvColor=color;\\n#endif\\n}\",\"colorPixelShader\":\"#ifdef VERTEXCOLOR\\nvarying vec4 vColor;\\n#else\\nuniform vec4 color;\\n#endif\\nvoid main(void) {\\n#ifdef VERTEXCOLOR\\ngl_FragColor=vColor;\\n#else\\ngl_FragColor=color;\\n#endif\\n}\",\"gpuRenderParticlesVertexShader\":\"#version 300 es\\nuniform mat4 view;\\nuniform mat4 projection;\\nuniform vec2 translationPivot;\\n\\nin vec3 position;\\nin float age;\\nin float life;\\nin vec3 size;\\n#ifndef BILLBOARD\\nin vec3 initialDirection;\\n#endif\\nin float angle;\\n#ifdef ANIMATESHEET\\nin float cellIndex;\\n#endif\\nin vec2 offset;\\nin vec2 uv;\\nout vec2 vUV;\\nout vec4 vColor;\\n#ifdef CLIPPLANE\\nuniform vec4 vClipPlane;\\nuniform mat4 invView;\\nout float fClipDistance;\\n#endif\\n#ifdef COLORGRADIENTS\\nuniform sampler2D colorGradientSampler;\\n#else\\nuniform vec4 colorDead;\\nin vec4 color;\\n#endif\\n#ifdef ANIMATESHEET\\nuniform vec3 sheetInfos;\\n#endif\\n#ifdef BILLBOARD\\nuniform vec3 eyePosition; \\n#endif\\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\\nvec3 zaxis=normalize(cross(yaxis,xaxis));\\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\\nmat3 rotMatrix=mat3(row0,row1,row2);\\nvec3 alignedCorner=rotMatrix*rotatedCorner;\\nreturn position+alignedCorner;\\n}\\nvoid main() {\\n#ifdef ANIMATESHEET\\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\\nvec2 uvScale=sheetInfos.xy;\\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\\n#else \\nvUV=uv;\\n#endif\\nfloat ratio=age/life;\\n#ifdef COLORGRADIENTS\\nvColor=texture(colorGradientSampler,vec2(ratio,0));\\n#else\\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\\n#endif\\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\\n#ifdef BILLBOARD\\nvec4 rotatedCorner;\\nrotatedCorner.w=0.;\\n#ifdef BILLBOARDY \\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nrotatedCorner.y=0.;\\nvec3 yaxis=position-eyePosition;\\nyaxis.y=0.;\\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \\n#else\\n\\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nrotatedCorner.z=0.;\\n\\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\\n#endif\\n#else\\n\\nvec3 rotatedCorner;\\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.y=0.;\\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nvec3 yaxis=normalize(initialDirection);\\nvec3 worldPos=rotate(yaxis,rotatedCorner);\\n\\nvec4 viewPosition=view*vec4(worldPos,1.0); \\n#endif\\ngl_Position=projection*viewPosition;\\n\\n#ifdef CLIPPLANE\\nvec4 worldPos=invView*viewPosition;\\nfClipDistance=dot(worldPos,vClipPlane);\\n#endif \\n}\",\"gpuRenderParticlesPixelShader\":\"#version 300 es\\nuniform sampler2D textureSampler;\\nin vec2 vUV;\\nin vec4 vColor;\\nout vec4 outFragColor;\\n#ifdef CLIPPLANE\\nin float fClipDistance;\\n#endif\\nvoid main() {\\n#ifdef CLIPPLANE\\nif (fClipDistance>0.0)\\ndiscard;\\n#endif \\noutFragColor=texture(textureSampler,vUV)*vColor;\\n}\\n\",\"gpuUpdateParticlesVertexShader\":\"#version 300 es\\n#define PI 3.14159\\nuniform float currentCount;\\nuniform float timeDelta;\\nuniform float stopFactor;\\nuniform mat4 emitterWM;\\nuniform vec2 lifeTime;\\nuniform vec2 emitPower;\\nuniform vec2 sizeRange;\\nuniform vec4 scaleRange;\\n#ifndef COLORGRADIENTS\\nuniform vec4 color1;\\nuniform vec4 color2;\\n#endif\\nuniform vec3 gravity;\\nuniform sampler2D randomSampler;\\nuniform sampler2D randomSampler2;\\nuniform vec4 angleRange;\\n#ifdef BOXEMITTER\\nuniform vec3 direction1;\\nuniform vec3 direction2;\\nuniform vec3 minEmitBox;\\nuniform vec3 maxEmitBox;\\n#endif\\n#ifdef POINTEMITTER\\nuniform vec3 direction1;\\nuniform vec3 direction2;\\n#endif\\n#ifdef SPHEREEMITTER\\nuniform float radius;\\nuniform float radiusRange;\\n#ifdef DIRECTEDSPHEREEMITTER\\nuniform vec3 direction1;\\nuniform vec3 direction2;\\n#else\\nuniform float directionRandomizer;\\n#endif\\n#endif\\n#ifdef CONEEMITTER\\nuniform vec2 radius;\\nuniform float coneAngle;\\nuniform vec2 height;\\nuniform float directionRandomizer;\\n#endif\\n\\nin vec3 position;\\nin float age;\\nin float life;\\nin vec4 seed;\\nin vec3 size;\\n#ifndef COLORGRADIENTS\\nin vec4 color;\\n#endif\\nin vec3 direction;\\n#ifndef BILLBOARD\\nin vec3 initialDirection;\\n#endif\\n#ifdef ANGULARSPEEDGRADIENTS\\nin float angle;\\n#else\\nin vec2 angle;\\n#endif\\n#ifdef ANIMATESHEET\\nin float cellIndex;\\n#endif\\n\\nout vec3 outPosition;\\nout float outAge;\\nout float outLife;\\nout vec4 outSeed;\\nout vec3 outSize;\\n#ifndef COLORGRADIENTS\\nout vec4 outColor;\\n#endif\\nout vec3 outDirection;\\n#ifndef BILLBOARD\\nout vec3 outInitialDirection;\\n#endif\\n#ifdef ANGULARSPEEDGRADIENTS\\nout float outAngle;\\n#else\\nout vec2 outAngle;\\n#endif\\n#ifdef ANIMATESHEET\\nout float outCellIndex;\\n#endif\\n#ifdef SIZEGRADIENTS\\nuniform sampler2D sizeGradientSampler;\\n#endif \\n#ifdef ANGULARSPEEDGRADIENTS\\nuniform sampler2D angularSpeedGradientSampler;\\n#endif \\n#ifdef VELOCITYGRADIENTS\\nuniform sampler2D velocityGradientSampler;\\n#endif\\n#ifdef NOISE\\nuniform vec3 noiseStrength;\\nuniform sampler2D noiseSampler;\\n#endif\\n#ifdef ANIMATESHEET\\nuniform vec3 cellInfos;\\n#endif\\nvec3 getRandomVec3(float offset) {\\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\\n}\\nvec4 getRandomVec4(float offset) {\\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\\n}\\nvoid main() {\\nif (age>=life) {\\nif (stopFactor == 0.) {\\noutPosition=position;\\noutAge=life;\\noutLife=life;\\noutSeed=seed;\\n#ifndef COLORGRADIENTS \\noutColor=vec4(0.,0.,0.,0.);\\n#endif\\noutSize=vec3(0.,0.,0.);\\n#ifndef BILLBOARD \\noutInitialDirection=initialDirection;\\n#endif \\noutDirection=direction;\\noutAngle=angle;\\n#ifdef ANIMATESHEET \\noutCellIndex=cellIndex;\\n#endif\\nreturn;\\n}\\nvec3 position;\\nvec3 direction;\\n\\nvec4 randoms=getRandomVec4(seed.x);\\n\\noutAge=0.0;\\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\\n\\noutSeed=seed;\\n\\n#ifdef SIZEGRADIENTS \\noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\\n#else\\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\\n#endif\\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \\n#ifndef COLORGRADIENTS\\n\\noutColor=color1+(color2-color1)*randoms.b;\\n#endif\\n\\n#ifndef ANGULARSPEEDGRADIENTS \\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\\n#else\\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\\n#endif \\n\\n#ifdef POINTEMITTER\\nvec3 randoms2=getRandomVec3(seed.y);\\nvec3 randoms3=getRandomVec3(seed.z);\\nposition=vec3(0,0,0);\\ndirection=direction1+(direction2-direction1)*randoms3;\\n#elif defined(BOXEMITTER)\\nvec3 randoms2=getRandomVec3(seed.y);\\nvec3 randoms3=getRandomVec3(seed.z);\\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\\ndirection=direction1+(direction2-direction1)*randoms3; \\n#elif defined(SPHEREEMITTER)\\nvec3 randoms2=getRandomVec3(seed.y);\\nvec3 randoms3=getRandomVec3(seed.z);\\n\\nfloat phi=2.0*PI*randoms2.x;\\nfloat theta=acos(2.0*randoms2.y-1.0);\\nfloat randX=cos(phi)*sin(theta);\\nfloat randY=cos(theta);\\nfloat randZ=sin(phi)*sin(theta);\\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\\n#ifdef DIRECTEDSPHEREEMITTER\\ndirection=direction1+(direction2-direction1)*randoms3;\\n#else\\n\\ndirection=position+directionRandomizer*randoms3;\\n#endif\\n#elif defined(CONEEMITTER)\\nvec3 randoms2=getRandomVec3(seed.y);\\nfloat s=2.0*PI*randoms2.x;\\n#ifdef CONEEMITTERSPAWNPOINT\\nfloat h=0.00001;\\n#else\\nfloat h=randoms2.y*height.y;\\n\\nh=1.-h*h; \\n#endif\\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\\nlRadius=lRadius*h;\\nfloat randX=lRadius*sin(s);\\nfloat randZ=lRadius*cos(s);\\nfloat randY=h*height.x;\\nposition=vec3(randX,randY,randZ); \\n\\nif (abs(cos(coneAngle)) == 1.0) {\\ndirection=vec3(0.,1.0,0.);\\n} else {\\nvec3 randoms3=getRandomVec3(seed.z);\\ndirection=position+directionRandomizer*randoms3;\\n}\\n#else \\n\\nposition=vec3(0.,0.,0.);\\n\\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\\n#endif\\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\\noutPosition=(emitterWM*vec4(position,1.)).xyz;\\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\\noutDirection=initial*power;\\n#ifndef BILLBOARD \\noutInitialDirection=initial;\\n#endif\\n#ifdef ANIMATESHEET \\noutCellIndex=cellInfos.x;\\n#endif\\n} else { \\nfloat directionScale=timeDelta;\\nfloat ageGradient=age/life;\\n#ifdef VELOCITYGRADIENTS\\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\\n#endif\\noutPosition=position+direction*directionScale;\\noutAge=age+timeDelta;\\noutLife=life;\\noutSeed=seed;\\n#ifndef COLORGRADIENTS \\noutColor=color;\\n#endif\\n#ifdef SIZEGRADIENTS\\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\\noutSize.yz=size.yz;\\n#else\\noutSize=size;\\n#endif \\n#ifndef BILLBOARD \\noutInitialDirection=initialDirection;\\n#endif\\noutDirection=direction+gravity*timeDelta;\\n#ifdef NOISE\\nvec3 localPosition=outPosition-emitterWM[3].xyz;\\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\\noutDirection=outDirection+force*timeDelta;\\n#endif \\n#ifdef ANGULARSPEEDGRADIENTS\\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\\noutAngle=angle+angularSpeed*timeDelta;\\n#else\\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\\n#endif\\n#ifdef ANIMATESHEET \\nfloat dist=cellInfos.y-cellInfos.x;\\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\\noutCellIndex=float(int(cellInfos.x+ratio*dist));\\n#endif\\n}\\n}\",\"gpuUpdateParticlesPixelShader\":\"#version 300 es\\nvoid main() {\\ndiscard;\\n}\\n\",\"postprocessVertexShader\":\"\\nattribute vec2 position;\\nuniform vec2 scale;\\n\\nvarying vec2 vUV;\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) { \\nvUV=(position*madd+madd)*scale;\\ngl_Position=vec4(position,0.0,1.0);\\n}\",\"passPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nvoid main(void) \\n{\\ngl_FragColor=texture2D(textureSampler,vUV);\\n}\",\"shadowMapVertexShader\":\"\\nattribute vec3 position;\\n#ifdef NORMAL\\nattribute vec3 normal;\\nuniform vec3 lightData;\\n#endif\\n#include\\n#include\\n#include[0..maxSimultaneousMorphTargets]\\n\\n#include\\n#include\\nuniform mat4 viewProjection;\\nuniform vec3 biasAndScale;\\nuniform vec2 depthValues;\\nvarying float vDepthMetric;\\n#ifdef ALPHATEST\\nvarying vec2 vUV;\\nuniform mat4 diffuseMatrix;\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#endif\\nvoid main(void)\\n{\\nvec3 positionUpdated=position;\\n#include[0..maxSimultaneousMorphTargets]\\n#include\\n#include\\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\\n\\n#ifdef NORMAL\\nmat3 normalWorld=mat3(finalWorld);\\n#ifdef NONUNIFORMSCALING\\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\\n#endif\\nvec3 worldNor=normalize(normalWorld*normal);\\n#ifdef DIRECTIONINLIGHTDATA\\nvec3 worldLightDir=normalize(-lightData.xyz);\\n#else\\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\\nvec3 worldLightDir=normalize(directionToLight);\\n#endif\\nfloat ndl=dot(worldNor,worldLightDir);\\nfloat sinNL=sqrt(1.0-ndl*ndl);\\nfloat normalBias=biasAndScale.y*sinNL;\\nworldPos.xyz-=worldNor*normalBias;\\n#endif\\n\\ngl_Position=viewProjection*worldPos;\\n#ifdef DEPTHTEXTURE\\n\\ngl_Position.z+=biasAndScale.x*gl_Position.w;\\n#endif\\n\\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\\n#ifdef ALPHATEST\\n#ifdef UV1\\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n#endif\\n#ifdef UV2\\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n#endif\\n#endif\\n}\",\"shadowMapPixelShader\":\"#ifndef FLOAT\\nvec4 pack(float depth)\\n{\\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\\nvec4 res=fract(depth*bit_shift);\\nres-=res.xxyz*bit_mask;\\nreturn res;\\n}\\n#endif\\nvarying float vDepthMetric;\\n#ifdef ALPHATEST\\nvarying vec2 vUV;\\nuniform sampler2D diffuseSampler;\\n#endif\\nuniform vec3 biasAndScale;\\nuniform vec2 depthValues;\\nvoid main(void)\\n{\\n#ifdef ALPHATEST\\nif (texture2D(diffuseSampler,vUV).a<0.4)\\ndiscard;\\n#endif\\nfloat depth=vDepthMetric;\\n#ifdef ESM\\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\\n#endif\\n#ifdef FLOAT\\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\\n#else\\ngl_FragColor=pack(depth);\\n#endif\\n}\",\"depthBoxBlurPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n\\nuniform vec2 screenSize;\\nvoid main(void)\\n{\\nvec4 colorDepth=vec4(0.0);\\nfor (int x=-OFFSET; x<=OFFSET; x++)\\nfor (int y=-OFFSET; y<=OFFSET; y++)\\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\\n}\",\"proceduralVertexShader\":\"\\nattribute vec2 position;\\n\\nvarying vec2 vPosition;\\nvarying vec2 vUV;\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) { \\nvPosition=position;\\nvUV=position*madd+madd;\\ngl_Position=vec4(position,0.0,1.0);\\n}\",\"depthVertexShader\":\"\\nattribute vec3 position;\\n#include\\n\\n#include\\nuniform mat4 viewProjection;\\nuniform vec2 depthValues;\\n#if defined(ALPHATEST) || defined(NEED_UV)\\nvarying vec2 vUV;\\nuniform mat4 diffuseMatrix;\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#endif\\nvarying float vDepthMetric;\\nvoid main(void)\\n{\\n#include\\n#include\\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\\n#ifdef UV1\\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n#endif\\n#ifdef UV2\\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n#endif\\n#endif\\n}\",\"depthPixelShader\":\"#ifdef ALPHATEST\\nvarying vec2 vUV;\\nuniform sampler2D diffuseSampler;\\n#endif\\nvarying float vDepthMetric;\\nvoid main(void)\\n{\\n#ifdef ALPHATEST\\nif (texture2D(diffuseSampler,vUV).a<0.4)\\ndiscard;\\n#endif\\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\\n}\",\"ssaoPixelShader\":\"\\nuniform sampler2D textureSampler;\\nvarying vec2 vUV;\\n#ifdef SSAO\\nuniform sampler2D randomSampler;\\nuniform float randTextureTiles;\\nuniform float samplesFactor;\\nuniform vec3 sampleSphere[SAMPLES];\\nuniform float totalStrength;\\nuniform float radius;\\nuniform float area;\\nuniform float fallOff;\\nuniform float base;\\nvec3 normalFromDepth(float depth,vec2 coords)\\n{\\nvec2 offset1=vec2(0.0,radius);\\nvec2 offset2=vec2(radius,0.0);\\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\\nvec3 p1=vec3(offset1,depth1-depth);\\nvec3 p2=vec3(offset2,depth2-depth);\\nvec3 normal=cross(p1,p2);\\nnormal.z=-normal.z;\\nreturn normalize(normal);\\n}\\nvoid main()\\n{\\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\\nfloat depth=texture2D(textureSampler,vUV).r;\\nvec3 position=vec3(vUV,depth);\\nvec3 normal=normalFromDepth(depth,vUV);\\nfloat radiusDepth=radius/depth;\\nfloat occlusion=0.0;\\nvec3 ray;\\nvec3 hemiRay;\\nfloat occlusionDepth;\\nfloat difference;\\nfor (int i=0; imaxZ) {\\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\\nreturn;\\n}\\nfor (int i=0; i1.0 || offset.y>1.0) {\\ncontinue;\\n}\\n\\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\\n\\nfloat rangeCheck=abs(depth-sampleDepth)=1e-5 ? 1.0 : 0.0)*rangeCheck;\\n}\\n\\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\\nfloat result=clamp(ao+base,0.0,1.0);\\ngl_FragColor=vec4(vec3(result),1.0);\\n}\\n#endif\\n#ifdef BILATERAL_BLUR\\nuniform sampler2D depthSampler;\\nuniform float outSize;\\nuniform float samplerOffsets[SAMPLES];\\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\\nvec4 color=vec4(0.0);\\nvec2 off1=vec2(1.3846153846)*direction;\\nvec2 off2=vec2(3.2307692308)*direction;\\ncolor+=texture2D(image,uv)*0.2270270270;\\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\\nreturn color;\\n}\\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\\nvec4 color=vec4(0.0);\\nvec2 off1=vec2(1.411764705882353)*direction;\\nvec2 off2=vec2(3.2941176470588234)*direction;\\nvec2 off3=vec2(5.176470588235294)*direction;\\ncolor+=texture2D(image,uv)*0.1964825501511404;\\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\\nreturn color;\\n}\\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\\nvec4 color=vec4(0.0);\\nvec2 off1=vec2(1.411764705882353)*direction;\\nvec2 off2=vec2(3.2941176470588234)*direction;\\nvec2 off3=vec2(5.176470588235294)*direction;\\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\\nfloat sampleDepth;\\nfloat weight;\\nfloat weightSum=30.0;\\ncolor+=texture2D(image,uv)*30.0;\\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\\nweightSum+=weight;\\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\\nweightSum+=weight;\\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\\nweightSum+=weight;\\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\\nweightSum+=weight;\\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\\nweightSum+=weight;\\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\\nweightSum+=weight;\\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\\nreturn color/weightSum;\\n}\\nvoid main()\\n{\\n#if EXPENSIVE\\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\\nfloat texelsize=1.0/outSize;\\nfloat result=0.0;\\nfloat weightSum=0.0;\\nfor (int i=0; i1.0) { lum_threshold=0.94+0.01*threshold; }\\nelse { lum_threshold=0.5+0.44*threshold; }\\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\\nhighlight*=luminance*gain;\\nhighlight.a=1.0;\\nreturn highlight;\\n}\\nvoid main(void)\\n{\\nvec4 original=texture2D(textureSampler,vUV);\\n\\nif (gain == -1.0) {\\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\\nreturn;\\n}\\nfloat w=2.0/screen_width;\\nfloat h=2.0/screen_height;\\nfloat weight=1.0;\\n\\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\\n#ifdef PENTAGON\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\\n#else\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\\n#endif\\nblurred/=39.0;\\ngl_FragColor=blurred;\\n\\n}\",\"depthOfFieldPixelShader\":\"\\n\\n\\n\\n\\nuniform sampler2D textureSampler;\\nuniform sampler2D highlightsSampler;\\nuniform sampler2D depthSampler;\\nuniform sampler2D grainSampler;\\n\\nuniform float grain_amount;\\nuniform bool blur_noise;\\nuniform float screen_width;\\nuniform float screen_height;\\nuniform float distortion;\\nuniform bool dof_enabled;\\n\\nuniform float screen_distance; \\nuniform float aperture;\\nuniform float darken;\\nuniform float edge_blur;\\nuniform bool highlights;\\n\\nuniform float near;\\nuniform float far;\\n\\nvarying vec2 vUV;\\n\\n#define PI 3.14159265\\n#define TWOPI 6.28318530\\n#define inverse_focal_length 0.1 \\n\\nvec2 centered_screen_pos;\\nvec2 distorted_coords;\\nfloat radius2;\\nfloat radius;\\n\\nvec2 rand(vec2 co)\\n{\\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\\n}\\n\\nvec2 getDistortedCoords(vec2 coords) {\\nif (distortion == 0.0) { return coords; }\\nvec2 direction=1.0*normalize(centered_screen_pos);\\nvec2 dist_coords=vec2(0.5,0.5);\\ndist_coords.x=0.5+direction.x*radius2*1.0;\\ndist_coords.y=0.5+direction.y*radius2*1.0;\\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\\ndist_coords=mix(coords,dist_coords,dist_amount);\\nreturn dist_coords;\\n}\\n\\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\\n\\nvec2 coords=distorted_coords;\\nfloat angle=rand(coords*100.0).x*TWOPI;\\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\\ncolor+=texture2D(textureSampler,coords)*weight;\\nreturn weight;\\n}\\n\\nfloat getBlurLevel(float size) {\\nreturn min(3.0,ceil(size/1.0));\\n}\\n\\nvec4 getBlurColor(float size) {\\nvec4 col=texture2D(textureSampler,distorted_coords);\\nif (size == 0.0) { return col; }\\n\\n\\nfloat blur_level=getBlurLevel(size);\\nfloat w=(size/screen_width);\\nfloat h=(size/screen_height);\\nfloat total_weight=1.0;\\nvec2 sample_coords;\\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\\nif (blur_level>1.0) {\\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\\n}\\nif (blur_level>2.0) {\\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\\n}\\ncol/=total_weight; \\n\\nif (darken>0.0) {\\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\\n}\\n\\n\\n\\n\\nreturn col;\\n}\\nvoid main(void)\\n{\\n\\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\\nradius=sqrt(radius2);\\ndistorted_coords=getDistortedCoords(vUV); \\nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \\nfloat depth=texture2D(depthSampler,distorted_coords).r; \\nfloat distance=near+(far-near)*depth; \\nvec4 color=texture2D(textureSampler,vUV); \\n\\n\\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\\n\\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\\n\\nfloat edge_blur_amount=0.0;\\nif (edge_blur>0.0) {\\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\\n}\\n\\nfloat blur_amount=max(edge_blur_amount,coc);\\n\\nif (blur_amount == 0.0) {\\ngl_FragColor=texture2D(textureSampler,distorted_coords);\\n}\\nelse {\\n\\ngl_FragColor=getBlurColor(blur_amount*1.7);\\n\\nif (highlights) {\\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\\n}\\nif (blur_noise) {\\n\\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\\n}\\n}\\n\\nif (grain_amount>0.0) {\\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\\n}\\n}\\n\",\"standardPixelShader\":\"uniform sampler2D textureSampler;\\nvarying vec2 vUV;\\n#if defined(PASS_POST_PROCESS)\\nvoid main(void)\\n{\\nvec4 color=texture2D(textureSampler,vUV);\\ngl_FragColor=color;\\n}\\n#endif\\n#if defined(DOWN_SAMPLE_X4)\\nuniform vec2 dsOffsets[16];\\nvoid main(void)\\n{\\nvec4 average=vec4(0.0,0.0,0.0,0.0);\\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\\naverage/=16.0;\\ngl_FragColor=average;\\n}\\n#endif\\n#if defined(BRIGHT_PASS)\\nuniform vec2 dsOffsets[4];\\nuniform float brightThreshold;\\nvoid main(void)\\n{\\nvec4 average=vec4(0.0,0.0,0.0,0.0);\\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\\naverage*=0.25;\\nfloat luminance=length(average.rgb);\\nif (luminanceshadowPixelDepth)\\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\\ncurrentPosition+=stepL;\\n}\\naccumFog/=NB_STEPS;\\nvec3 color=accumFog*scatteringPower;\\ngl_FragColor=vec4(color*exp(color) ,1.0);\\n}\\n#endif\\n#if defined(VLSMERGE)\\nuniform sampler2D originalSampler;\\nvoid main(void)\\n{\\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\\n}\\n#endif\\n#if defined(LUMINANCE)\\nuniform vec2 lumOffsets[4];\\nvoid main()\\n{\\nfloat average=0.0;\\nvec4 color=vec4(0.0);\\nfloat maximum=-1e20;\\nvec3 weight=vec3(0.299,0.587,0.114);\\nfor (int i=0; i<4; i++)\\n{\\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\\n\\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\\n\\n#ifdef WEIGHTED_AVERAGE\\nfloat GreyValue=dot(color.rgb,weight);\\n#endif\\n#ifdef BRIGHTNESS\\nfloat GreyValue=max(color.r,max(color.g,color.b));\\n#endif\\n#ifdef HSL_COMPONENT\\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\\n#endif\\n#ifdef MAGNITUDE\\nfloat GreyValue=length(color.rgb);\\n#endif\\nmaximum=max(maximum,GreyValue);\\naverage+=(0.25*log(1e-5+GreyValue));\\n}\\naverage=exp(average);\\ngl_FragColor=vec4(average,maximum,0.0,1.0);\\n}\\n#endif\\n#if defined(LUMINANCE_DOWN_SAMPLE)\\nuniform vec2 dsOffsets[9];\\nuniform float halfDestPixelSize;\\n#ifdef FINAL_DOWN_SAMPLER\\nvec4 pack(float value) {\\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\\nvec4 res=fract(value*bit_shift);\\nres-=res.xxyz*bit_mask;\\nreturn res;\\n}\\n#endif\\nvoid main()\\n{\\nvec4 color=vec4(0.0);\\nfloat average=0.0;\\nfor (int i=0; i<9; i++)\\n{\\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\\naverage+=color.r;\\n}\\naverage/=9.0;\\n#ifdef FINAL_DOWN_SAMPLER\\ngl_FragColor=pack(average);\\n#else\\ngl_FragColor=vec4(average,average,0.0,1.0);\\n#endif\\n}\\n#endif\\n#if defined(HDR)\\nuniform sampler2D textureAdderSampler;\\nuniform float averageLuminance;\\nvoid main()\\n{\\nvec4 color=texture2D(textureAdderSampler,vUV);\\nvec4 adjustedColor=color/averageLuminance;\\ncolor=adjustedColor;\\ncolor.a=1.0;\\ngl_FragColor=color;\\n}\\n#endif\\n#if defined(LENS_FLARE)\\n#define GHOSTS 3\\nuniform sampler2D lensColorSampler;\\nuniform float strength;\\nuniform float ghostDispersal;\\nuniform float haloWidth;\\nuniform vec2 resolution;\\nuniform float distortionStrength;\\nfloat hash(vec2 p)\\n{\\nfloat h=dot(p,vec2(127.1,311.7));\\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\\n}\\nfloat noise(in vec2 p)\\n{\\nvec2 i=floor(p);\\nvec2 f=fract(p);\\nvec2 u=f*f*(3.0-2.0*f);\\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\\nhash(i+vec2(1.0,0.0)),u.x),\\nmix(hash(i+vec2(0.0,1.0)),\\nhash(i+vec2(1.0,1.0)),u.x),u.y);\\n}\\nfloat fbm(vec2 p)\\n{\\nfloat f=0.0;\\nf+=0.5000*noise(p); p*=2.02;\\nf+=0.2500*noise(p); p*=2.03;\\nf+=0.1250*noise(p); p*=2.01;\\nf+=0.0625*noise(p); p*=2.04;\\nf/=0.9375;\\nreturn f;\\n}\\nvec3 pattern(vec2 uv)\\n{\\nvec2 p=-1.0+2.0*uv;\\nfloat p2=dot(p,p);\\nfloat f=fbm(vec2(15.0*p2))/2.0;\\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\\nreturn (1.0-f)*vec3(r,g,b);\\n}\\nfloat luminance(vec3 color)\\n{\\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\\n}\\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\\n{\\nreturn vec4(\\ntexture2D(tex,texcoord+direction*distortion.r).r,\\ntexture2D(tex,texcoord+direction*distortion.g).g,\\ntexture2D(tex,texcoord+direction*distortion.b).b,\\n1.0\\n);\\n}\\nvoid main(void)\\n{\\nvec2 uv=-vUV+vec2(1.0);\\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\\nvec2 texelSize=1.0/resolution;\\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\\nvec4 result=vec4(0.0);\\nfloat ghostIndice=1.0;\\nfor (int i=0; i=nSamples)\\nbreak;\\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\\nresult+=texture2D(textureSampler,offset1);\\n}\\ngl_FragColor=result/float(nSamples);\\n}\\n#endif\\n\",\"fxaaVertexShader\":\"\\nattribute vec2 position;\\nuniform vec2 texelSize;\\n\\nvarying vec2 vUV;\\nvarying vec2 sampleCoordS;\\nvarying vec2 sampleCoordE;\\nvarying vec2 sampleCoordN;\\nvarying vec2 sampleCoordW;\\nvarying vec2 sampleCoordNW;\\nvarying vec2 sampleCoordSE;\\nvarying vec2 sampleCoordNE;\\nvarying vec2 sampleCoordSW;\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) { \\nvUV=(position*madd+madd);\\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\\ngl_Position=vec4(position,0.0,1.0);\\n}\",\"fxaaPixelShader\":\"uniform sampler2D textureSampler;\\nuniform vec2 texelSize;\\nvarying vec2 vUV;\\nvarying vec2 sampleCoordS;\\nvarying vec2 sampleCoordE;\\nvarying vec2 sampleCoordN;\\nvarying vec2 sampleCoordW;\\nvarying vec2 sampleCoordNW;\\nvarying vec2 sampleCoordSE;\\nvarying vec2 sampleCoordNE;\\nvarying vec2 sampleCoordSW;\\nconst float fxaaQualitySubpix=1.0;\\nconst float fxaaQualityEdgeThreshold=0.166;\\nconst float fxaaQualityEdgeThresholdMin=0.0833;\\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\\nvoid main(){\\nvec2 posM;\\nposM.x=vUV.x;\\nposM.y=vUV.y;\\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\\nfloat lumaM=FxaaLuma(rgbyM);\\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\\nfloat maxSM=max(lumaS,lumaM);\\nfloat minSM=min(lumaS,lumaM);\\nfloat maxESM=max(lumaE,maxSM);\\nfloat minESM=min(lumaE,minSM);\\nfloat maxWN=max(lumaN,lumaW);\\nfloat minWN=min(lumaN,lumaW);\\nfloat rangeMax=max(maxWN,maxESM);\\nfloat rangeMin=min(minWN,minESM);\\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\\nfloat range=rangeMax-rangeMin;\\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\\n#ifndef MALI\\nif(range=edgeVert;\\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\\nif (!horzSpan)\\n{\\nlumaN=lumaW;\\n}\\nif (!horzSpan) \\n{\\nlumaS=lumaE;\\n}\\nif (horzSpan) \\n{\\nlengthSign=texelSize.y;\\n}\\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\\nfloat gradientN=lumaN-lumaM;\\nfloat gradientS=lumaS-lumaM;\\nfloat lumaNN=lumaN+lumaM;\\nfloat lumaSS=lumaS+lumaM;\\nbool pairN=abs(gradientN)>=abs(gradientS);\\nfloat gradient=max(abs(gradientN),abs(gradientS));\\nif (pairN)\\n{\\nlengthSign=-lengthSign;\\n}\\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\\nvec2 posB;\\nposB.x=posM.x;\\nposB.y=posM.y;\\nvec2 offNP;\\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\\nif (!horzSpan) \\n{\\nposB.x+=lengthSign*0.5;\\n}\\nif (horzSpan)\\n{\\nposB.y+=lengthSign*0.5;\\n}\\nvec2 posN;\\nposN.x=posB.x-offNP.x*1.5;\\nposN.y=posB.y-offNP.y*1.5;\\nvec2 posP;\\nposP.x=posB.x+offNP.x*1.5;\\nposP.y=posB.y+offNP.y*1.5;\\nfloat subpixD=((-2.0)*subpixC)+3.0;\\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\\nfloat subpixE=subpixC*subpixC;\\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\\nif (!pairN) \\n{\\nlumaNN=lumaSS;\\n}\\nfloat gradientScaled=gradient*1.0/4.0;\\nfloat lumaMM=lumaM-lumaNN*0.5;\\nfloat subpixF=subpixD*subpixE;\\nbool lumaMLTZero=lumaMM<0.0;\\nlumaEndN-=lumaNN*0.5;\\nlumaEndP-=lumaNN*0.5;\\nbool doneN=abs(lumaEndN)>=gradientScaled;\\nbool doneP=abs(lumaEndP)>=gradientScaled;\\nif (!doneN) \\n{\\nposN.x-=offNP.x*3.0;\\n}\\nif (!doneN) \\n{\\nposN.y-=offNP.y*3.0;\\n}\\nbool doneNP=(!doneN) || (!doneP);\\nif (!doneP) \\n{\\nposP.x+=offNP.x*3.0;\\n}\\nif (!doneP)\\n{\\nposP.y+=offNP.y*3.0;\\n}\\nif (doneNP)\\n{\\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\\ndoneN=abs(lumaEndN)>=gradientScaled;\\ndoneP=abs(lumaEndP)>=gradientScaled;\\nif (!doneN) posN.x-=offNP.x*12.0;\\nif (!doneN) posN.y-=offNP.y*12.0;\\ndoneNP=(!doneN) || (!doneP);\\nif (!doneP) posP.x+=offNP.x*12.0;\\nif (!doneP) posP.y+=offNP.y*12.0;\\n}\\nfloat dstN=posM.x-posN.x;\\nfloat dstP=posP.x-posM.x;\\nif (!horzSpan)\\n{\\ndstN=posM.y-posN.y;\\n}\\nif (!horzSpan) \\n{\\ndstP=posP.y-posM.y;\\n}\\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\\nfloat spanLength=(dstP+dstN);\\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\\nfloat spanLengthRcp=1.0/spanLength;\\nbool directionN=dstN\\n\\nuniform sampler2D textureSampler; \\n\\nuniform float intensity;\\nuniform float animatedSeed;\\n\\nvarying vec2 vUV;\\nvoid main(void)\\n{\\ngl_FragColor=texture2D(textureSampler,vUV);\\nvec2 seed=vUV*(animatedSeed);\\nfloat grain=dither(seed,intensity);\\n\\nfloat lum=getLuminance(gl_FragColor.rgb);\\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\\ngl_FragColor.rgb+=grain*grainAmount;\\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\\n}\",\"sharpenPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform vec2 screenSize;\\nuniform vec2 sharpnessAmounts;\\nvoid main(void)\\n{\\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\\nvec4 color=texture2D(textureSampler,vUV);\\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\\ncolor*4.0;\\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\\n}\",\"kernelBlurVertexShader\":\"\\nattribute vec2 position;\\n\\nuniform vec2 delta;\\n\\nvarying vec2 sampleCenter;\\n#include[0..varyingCount]\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) { \\nsampleCenter=(position*madd+madd);\\n#include[0..varyingCount]\\ngl_Position=vec4(position,0.0,1.0);\\n}\",\"kernelBlurPixelShader\":\"\\nuniform sampler2D textureSampler;\\nuniform vec2 delta;\\n\\nvarying vec2 sampleCenter;\\n#ifdef DOF\\nuniform sampler2D circleOfConfusionSampler;\\nuniform vec2 cameraMinMaxZ;\\nfloat sampleDistance(const in vec2 offset) {\\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \\nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \\n}\\nfloat sampleCoC(const in vec2 offset) {\\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \\nreturn coc; \\n}\\n#endif\\n#include[0..varyingCount]\\n#ifdef PACKEDFLOAT\\nvec4 pack(float depth)\\n{\\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\\nvec4 res=fract(depth*bit_shift);\\nres-=res.xxyz*bit_mask;\\nreturn res;\\n}\\nfloat unpack(vec4 color)\\n{\\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\\nreturn dot(color,bit_shift);\\n}\\n#endif\\nvoid main(void)\\n{\\nfloat computedWeight=0.0;\\n#ifdef PACKEDFLOAT \\nfloat blend=0.;\\n#else\\nvec4 blend=vec4(0.);\\n#endif\\n#ifdef DOF\\nfloat sumOfWeights=CENTER_WEIGHT; \\nfloat factor=0.0;\\n\\n#ifdef PACKEDFLOAT\\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\\n#else\\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\\n#endif\\n#endif\\n#include[0..varyingCount]\\n#include[0..depCount]\\n#ifdef PACKEDFLOAT\\ngl_FragColor=pack(blend);\\n#else\\ngl_FragColor=blend;\\n#endif\\n#ifdef DOF\\ngl_FragColor/=sumOfWeights;\\n#endif\\n}\",\"depthOfFieldMergePixelShader\":\"uniform sampler2D textureSampler;\\nvarying vec2 vUV;\\nuniform sampler2D circleOfConfusionSampler;\\nuniform sampler2D blurStep0;\\n#if BLUR_LEVEL>0\\nuniform sampler2D blurStep1;\\n#endif\\n#if BLUR_LEVEL>1\\nuniform sampler2D blurStep2;\\n#endif\\nvoid main(void)\\n{\\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\\n#if BLUR_LEVEL == 0\\nvec4 original=texture2D(textureSampler,vUV);\\nvec4 blurred0=texture2D(blurStep0,vUV);\\ngl_FragColor=mix(original,blurred0,coc);\\n#endif\\n#if BLUR_LEVEL == 1\\nif(coc<0.5){\\nvec4 original=texture2D(textureSampler,vUV);\\nvec4 blurred1=texture2D(blurStep1,vUV);\\ngl_FragColor=mix(original,blurred1,coc/0.5);\\n}else{\\nvec4 blurred0=texture2D(blurStep0,vUV); \\nvec4 blurred1=texture2D(blurStep1,vUV);\\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\\n}\\n#endif\\n#if BLUR_LEVEL == 2\\nif(coc<0.33){\\nvec4 original=texture2D(textureSampler,vUV);\\nvec4 blurred2=texture2D(blurStep2,vUV);\\ngl_FragColor=mix(original,blurred2,coc/0.33);\\n}else if(coc<0.66){\\nvec4 blurred1=texture2D(blurStep1,vUV);\\nvec4 blurred2=texture2D(blurStep2,vUV);\\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\\n}else{\\nvec4 blurred0=texture2D(blurStep0,vUV);\\nvec4 blurred1=texture2D(blurStep1,vUV);\\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\\n}\\n#endif\\n}\\n\",\"circleOfConfusionPixelShader\":\"\\nuniform sampler2D depthSampler;\\n\\nvarying vec2 vUV;\\n\\nuniform vec2 cameraMinMaxZ;\\n\\nuniform float focusDistance;\\nuniform float cocPrecalculation;\\nvoid main(void)\\n{\\nfloat depth=texture2D(depthSampler,vUV).r;\\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\\ncoc=clamp(coc,0.0,1.0);\\ngl_FragColor=vec4(coc,depth,coc,1.0);\\n}\\n\",\"bloomMergePixelShader\":\"uniform sampler2D textureSampler;\\nuniform sampler2D bloomBlur;\\nvarying vec2 vUV;\\nuniform float bloomWeight;\\nvoid main(void)\\n{\\ngl_FragColor=texture2D(textureSampler,vUV);\\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \\n}\\n\",\"extractHighlightsPixelShader\":\"#include\\n\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform float threshold;\\nuniform float exposure;\\nvoid main(void) \\n{\\ngl_FragColor=texture2D(textureSampler,vUV);\\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\\n}\",\"geometryVertexShader\":\"precision highp float;\\nprecision highp int;\\n#include\\n#include\\nattribute vec3 position;\\nattribute vec3 normal;\\n#if defined(ALPHATEST) || defined(NEED_UV)\\nvarying vec2 vUV;\\nuniform mat4 diffuseMatrix;\\n#ifdef UV1\\nvarying vec2 uv;\\n#endif\\n#ifdef UV2\\nvarying vec2 uv2;\\n#endif\\n#endif\\n\\nuniform mat4 viewProjection;\\nuniform mat4 view;\\nvarying vec3 vNormalV;\\nvarying vec4 vViewPos;\\n#ifdef POSITION\\nvarying vec3 vPosition;\\n#endif\\nvoid main(void)\\n{\\n#include\\n#include\\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\\nvViewPos=view*pos;\\n#ifdef POSITION\\nvPosition=pos.xyz/pos.w;\\n#endif\\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\\n#ifdef UV1\\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n#endif\\n#ifdef UV2\\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n#endif\\n#endif\\n}\",\"geometryPixelShader\":\"#extension GL_EXT_draw_buffers : require\\nprecision highp float;\\nprecision highp int;\\nvarying vec3 vNormalV;\\nvarying vec4 vViewPos;\\n#ifdef POSITION\\nvarying vec3 vPosition;\\n#endif\\n#ifdef ALPHATEST\\nvarying vec2 vUV;\\nuniform sampler2D diffuseSampler;\\n#endif\\n#ifdef POSITION\\n#include[3]\\n#else\\n#include[2]\\n#endif\\nvoid main() {\\n#ifdef ALPHATEST\\nif (texture2D(diffuseSampler,vUV).a<0.4)\\ndiscard;\\n#endif\\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\\n\\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\\n\\n#ifdef POSITION\\ngl_FragData[2]=vec4(vPosition,1.0);\\n#endif\\n}\",\"refractionPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform sampler2D refractionSampler;\\n\\nuniform vec3 baseColor;\\nuniform float depth;\\nuniform float colorLevel;\\nvoid main() {\\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\\nvec2 uv=vUV-vec2(0.5);\\nvec2 offset=uv*depth*ref;\\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\\n}\",\"blackAndWhitePixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform float degree;\\nvoid main(void) \\n{\\nvec3 color=texture2D(textureSampler,vUV).rgb;\\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \\nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\\n}\",\"convolutionPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform vec2 screenSize;\\nuniform float kernel[9];\\nvoid main(void)\\n{\\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\\nvec4 colorSum =\\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\\nfloat kernelWeight =\\nkernel[0] +\\nkernel[1] +\\nkernel[2] +\\nkernel[3] +\\nkernel[4] +\\nkernel[5] +\\nkernel[6] +\\nkernel[7] +\\nkernel[8];\\nif (kernelWeight<=0.0) {\\nkernelWeight=1.0;\\n}\\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\\n}\",\"filterPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform mat4 kernelMatrix;\\nvoid main(void)\\n{\\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\\ngl_FragColor=vec4(updatedColor,1.0);\\n}\",\"volumetricLightScatteringPixelShader\":\"uniform sampler2D textureSampler;\\nuniform sampler2D lightScatteringSampler;\\nuniform float decay;\\nuniform float exposure;\\nuniform float weight;\\nuniform float density;\\nuniform vec2 meshPositionOnScreen;\\nvarying vec2 vUV;\\nvoid main(void) {\\nvec2 tc=vUV;\\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\\nfloat illuminationDecay=1.0;\\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\\nfor(int i=0; i\\n#include\\n#include\\nvoid main(void)\\n{\\nvec4 result=texture2D(textureSampler,vUV);\\n#ifdef IMAGEPROCESSING\\n#ifndef FROMLINEARSPACE\\n\\nresult.rgb=toLinearSpace(result.rgb);\\n#endif\\nresult=applyImageProcessing(result);\\n#else\\n\\n#ifdef FROMLINEARSPACE\\nresult=applyImageProcessing(result);\\n#endif\\n#endif\\ngl_FragColor=result;\\n}\",\"lensFlareVertexShader\":\"\\nattribute vec2 position;\\n\\nuniform mat4 viewportMatrix;\\n\\nvarying vec2 vUV;\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) { \\nvUV=position*madd+madd;\\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\\n}\",\"lensFlarePixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n\\nuniform vec4 color;\\nvoid main(void) {\\nvec4 baseColor=texture2D(textureSampler,vUV);\\ngl_FragColor=baseColor*color;\\n}\",\"anaglyphPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform sampler2D leftSampler;\\nvoid main(void)\\n{\\nvec4 leftFrag=texture2D(leftSampler,vUV);\\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\\nvec4 rightFrag=texture2D(textureSampler,vUV);\\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\\n}\",\"stereoscopicInterlacePixelShader\":\"const vec3 TWO=vec3(2.0,2.0,2.0);\\nvarying vec2 vUV;\\nuniform sampler2D camASampler;\\nuniform sampler2D textureSampler;\\nuniform vec2 stepSize;\\nvoid main(void)\\n{\\nbool useCamB;\\nvec2 texCoord1;\\nvec2 texCoord2;\\nvec3 frag1;\\nvec3 frag2;\\n#ifdef IS_STEREOSCOPIC_HORIZ\\nuseCamB=vUV.x>0.5;\\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\\n#else\\nuseCamB=vUV.y>0.5;\\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\\n#endif\\n\\nif (useCamB){\\nfrag1=texture2D(textureSampler,texCoord1).rgb;\\nfrag2=texture2D(textureSampler,texCoord2).rgb;\\n}else{\\nfrag1=texture2D(camASampler ,texCoord1).rgb;\\nfrag2=texture2D(camASampler ,texCoord2).rgb;\\n}\\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\\n}\",\"vrDistortionCorrectionPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform vec2 LensCenter;\\nuniform vec2 Scale;\\nuniform vec2 ScaleIn;\\nuniform vec4 HmdWarpParam;\\nvec2 HmdWarp(vec2 in01) {\\nvec2 theta=(in01-LensCenter)*ScaleIn; \\nfloat rSq=theta.x*theta.x+theta.y*theta.y;\\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\\nreturn LensCenter+Scale*rvector;\\n}\\nvoid main(void)\\n{\\nvec2 tc=HmdWarp(vUV);\\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\\nelse{\\ngl_FragColor=texture2D(textureSampler,tc);\\n}\\n}\",\"glowBlurPostProcessPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n\\nuniform vec2 screenSize;\\nuniform vec2 direction;\\nuniform float blurWidth;\\n\\nfloat getLuminance(vec3 color)\\n{\\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\\n}\\nvoid main(void)\\n{\\nfloat weights[7];\\nweights[0]=0.05;\\nweights[1]=0.1;\\nweights[2]=0.2;\\nweights[3]=0.3;\\nweights[4]=0.2;\\nweights[5]=0.1;\\nweights[6]=0.05;\\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\\nvec2 texelStep=texelSize*direction*blurWidth;\\nvec2 start=vUV-3.0*texelStep;\\nvec4 baseColor=vec4(0.,0.,0.,0.);\\nvec2 texelOffset=vec2(0.,0.);\\nfor (int i=0; i<7; i++)\\n{\\n\\nvec4 texel=texture2D(textureSampler,start+texelOffset);\\nbaseColor.a+=texel.a*weights[i];\\n\\nfloat luminance=getLuminance(baseColor.rgb);\\nfloat luminanceTexel=getLuminance(texel.rgb);\\nfloat choice=step(luminanceTexel,luminance);\\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\\ntexelOffset+=texelStep;\\n}\\ngl_FragColor=baseColor;\\n}\",\"glowMapGenerationPixelShader\":\"#ifdef ALPHATEST\\nvarying vec2 vUVDiffuse;\\nuniform sampler2D diffuseSampler;\\n#endif\\n#ifdef EMISSIVE\\nvarying vec2 vUVEmissive;\\nuniform sampler2D emissiveSampler;\\n#endif\\nuniform vec4 color;\\nvoid main(void)\\n{\\n#ifdef ALPHATEST\\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\\ndiscard;\\n#endif\\n#ifdef EMISSIVE\\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\\n#else\\ngl_FragColor=color;\\n#endif\\n}\",\"glowMapGenerationVertexShader\":\"\\nattribute vec3 position;\\n#include\\n#include\\n#include[0..maxSimultaneousMorphTargets]\\n\\n#include\\nuniform mat4 viewProjection;\\nvarying vec4 vPosition;\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#ifdef ALPHATEST\\nvarying vec2 vUVDiffuse;\\nuniform mat4 diffuseMatrix;\\n#endif\\n#ifdef EMISSIVE\\nvarying vec2 vUVEmissive;\\nuniform mat4 emissiveMatrix;\\n#endif\\nvoid main(void)\\n{\\nvec3 positionUpdated=position;\\n#include[0..maxSimultaneousMorphTargets]\\n#include\\n#include\\n#ifdef CUBEMAP\\nvPosition=finalWorld*vec4(positionUpdated,1.0);\\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\\n#else\\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\\ngl_Position=vPosition;\\n#endif\\n#ifdef ALPHATEST\\n#ifdef DIFFUSEUV1\\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n#endif\\n#ifdef DIFFUSEUV2\\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n#endif\\n#endif\\n#ifdef EMISSIVE\\n#ifdef EMISSIVEUV1\\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\\n#endif\\n#ifdef EMISSIVEUV2\\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\\n#endif\\n#endif\\n}\",\"glowMapMergePixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n#ifdef EMISSIVE\\nuniform sampler2D textureSampler2;\\n#endif\\n\\nuniform float offset;\\nvoid main(void) {\\nvec4 baseColor=texture2D(textureSampler,vUV);\\n#ifdef EMISSIVE\\nbaseColor+=texture2D(textureSampler2,vUV);\\nbaseColor*=offset;\\n#else\\nbaseColor.a=abs(offset-baseColor.a);\\n#ifdef STROKE\\nfloat alpha=smoothstep(.0,.1,baseColor.a);\\nbaseColor.a=alpha;\\nbaseColor.rgb=baseColor.rgb*alpha;\\n#endif\\n#endif\\ngl_FragColor=baseColor;\\n}\",\"glowMapMergeVertexShader\":\"\\nattribute vec2 position;\\n\\nvarying vec2 vUV;\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) {\\nvUV=position*madd+madd;\\ngl_Position=vec4(position,0.0,1.0);\\n}\",\"lineVertexShader\":\"\\nattribute vec3 position;\\nattribute vec4 normal;\\n\\nuniform mat4 worldViewProjection;\\nuniform float width;\\nuniform float aspectRatio;\\nvoid main(void) {\\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\\ncurrentScreen.x*=aspectRatio;\\nnextScreen.x*=aspectRatio;\\nvec2 dir=normalize(nextScreen-currentScreen);\\nvec2 normalDir=vec2(-dir.y,dir.x);\\nnormalDir*=width/2.0;\\nnormalDir.x/=aspectRatio;\\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\\ngl_Position=viewPosition+offset;\\n}\",\"linePixelShader\":\"uniform vec4 color;\\nvoid main(void) {\\ngl_FragColor=color;\\n}\",\"outlineVertexShader\":\"\\nattribute vec3 position;\\nattribute vec3 normal;\\n#include\\n\\nuniform float offset;\\n#include\\nuniform mat4 viewProjection;\\n#ifdef ALPHATEST\\nvarying vec2 vUV;\\nuniform mat4 diffuseMatrix;\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#endif\\n#include\\nvoid main(void)\\n{\\nvec3 offsetPosition=position+normal*offset;\\n#include\\n#include\\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\\n#ifdef ALPHATEST\\n#ifdef UV1\\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n#endif\\n#ifdef UV2\\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n#endif\\n#endif\\n#include\\n}\\n\",\"outlinePixelShader\":\"#ifdef LOGARITHMICDEPTH\\n#extension GL_EXT_frag_depth : enable\\n#endif\\nuniform vec4 color;\\n#ifdef ALPHATEST\\nvarying vec2 vUV;\\nuniform sampler2D diffuseSampler;\\n#endif\\n#include\\nvoid main(void) {\\n#ifdef ALPHATEST\\nif (texture2D(diffuseSampler,vUV).a<0.4)\\ndiscard;\\n#endif\\n#include\\ngl_FragColor=color;\\n}\",\"layerVertexShader\":\"\\nattribute vec2 position;\\n\\nuniform vec2 scale;\\nuniform vec2 offset;\\nuniform mat4 textureMatrix;\\n\\nvarying vec2 vUV;\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) { \\nvec2 shiftedPosition=position*scale+offset;\\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\\ngl_Position=vec4(shiftedPosition,0.0,1.0);\\n}\",\"layerPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n\\nuniform vec4 color;\\nvoid main(void) {\\nvec4 baseColor=texture2D(textureSampler,vUV);\\n#ifdef ALPHATEST\\nif (baseColor.a<0.4)\\ndiscard;\\n#endif\\ngl_FragColor=baseColor*color;\\n}\",\"backgroundVertexShader\":\"precision highp float;\\n#include<__decl__backgroundVertex>\\n#include\\n\\nattribute vec3 position;\\n#ifdef NORMAL\\nattribute vec3 normal;\\n#endif\\n#include\\n\\n#include\\n#ifdef POINTSIZE\\nuniform float pointSize;\\n#endif\\n\\nvarying vec3 vPositionW;\\n#ifdef NORMAL\\nvarying vec3 vNormalW;\\n#endif\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#ifdef MAINUV1\\nvarying vec2 vMainUV1;\\n#endif\\n#ifdef MAINUV2\\nvarying vec2 vMainUV2; \\n#endif\\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\\nvarying vec2 vDiffuseUV;\\n#endif\\n#include\\n#include\\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\\n#ifdef REFLECTIONMAP_SKYBOX\\nvarying vec3 vPositionUVW;\\n#endif\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvarying vec3 vDirectionW;\\n#endif\\nvoid main(void) {\\n#ifdef REFLECTIONMAP_SKYBOX\\nvPositionUVW=position;\\n#endif \\n#include\\n#include\\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\\nvec4 worldPos=finalWorld*vec4(position,1.0);\\nvPositionW=vec3(worldPos);\\n#ifdef NORMAL\\nmat3 normalWorld=mat3(finalWorld);\\n#ifdef NONUNIFORMSCALING\\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\\n#endif\\nvNormalW=normalize(normalWorld*normal);\\n#endif\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\\nif (fFovMultiplier<=1.0) {\\nvDirectionW=normalize(segment);\\n} else {\\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\\n}\\n#endif\\n#endif\\n#ifndef UV1\\nvec2 uv=vec2(0.,0.);\\n#endif\\n#ifndef UV2\\nvec2 uv2=vec2(0.,0.);\\n#endif\\n#ifdef MAINUV1\\nvMainUV1=uv;\\n#endif \\n#ifdef MAINUV2\\nvMainUV2=uv2;\\n#endif\\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \\nif (vDiffuseInfos.x == 0.)\\n{\\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n\\n#include\\n\\n#include\\n\\n#include[0..maxSimultaneousLights]\\n\\n#ifdef VERTEXCOLOR\\nvColor=color;\\n#endif\\n\\n#ifdef POINTSIZE\\ngl_PointSize=pointSize;\\n#endif\\n}\\n\",\"backgroundPixelShader\":\"#ifdef TEXTURELODSUPPORT\\n#extension GL_EXT_shader_texture_lod : enable\\n#endif\\nprecision highp float;\\n#include<__decl__backgroundFragment>\\n#define RECIPROCAL_PI2 0.15915494\\n\\nuniform vec3 vEyePosition;\\n\\nvarying vec3 vPositionW;\\n#ifdef MAINUV1\\nvarying vec2 vMainUV1;\\n#endif \\n#ifdef MAINUV2 \\nvarying vec2 vMainUV2; \\n#endif \\n#ifdef NORMAL\\nvarying vec3 vNormalW;\\n#endif\\n#ifdef DIFFUSE\\n#if DIFFUSEDIRECTUV == 1\\n#define vDiffuseUV vMainUV1\\n#elif DIFFUSEDIRECTUV == 2\\n#define vDiffuseUV vMainUV2\\n#else\\nvarying vec2 vDiffuseUV;\\n#endif\\nuniform sampler2D diffuseSampler;\\n#endif\\n\\n#ifdef REFLECTION\\n#ifdef REFLECTIONMAP_3D\\n#define sampleReflection(s,c) textureCube(s,c)\\nuniform samplerCube reflectionSampler;\\n#ifdef TEXTURELODSUPPORT\\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\\n#else\\nuniform samplerCube reflectionSamplerLow;\\nuniform samplerCube reflectionSamplerHigh;\\n#endif\\n#else\\n#define sampleReflection(s,c) texture2D(s,c)\\nuniform sampler2D reflectionSampler;\\n#ifdef TEXTURELODSUPPORT\\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\\n#else\\nuniform samplerCube reflectionSamplerLow;\\nuniform samplerCube reflectionSamplerHigh;\\n#endif\\n#endif\\n#ifdef REFLECTIONMAP_SKYBOX\\nvarying vec3 vPositionUVW;\\n#else\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvarying vec3 vDirectionW;\\n#endif\\n#endif\\n#include\\n#endif\\n\\n#ifndef FROMLINEARSPACE\\n#define FROMLINEARSPACE;\\n#endif\\n\\n#ifndef SHADOWONLY\\n#define SHADOWONLY;\\n#endif\\n#include\\n\\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\\n#include\\n#include\\n#include\\n#include\\n#include\\n\\n#include\\n#ifdef REFLECTIONFRESNEL\\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\\n{\\n\\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\\n}\\n#endif\\nvoid main(void) {\\n#include\\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\\n\\n#ifdef NORMAL\\nvec3 normalW=normalize(vNormalW);\\n#else\\nvec3 normalW=vec3(0.0,1.0,0.0);\\n#endif\\n\\nfloat shadow=1.;\\nfloat globalShadow=0.;\\nfloat shadowLightCount=0.;\\n#include[0..maxSimultaneousLights]\\n#ifdef SHADOWINUSE\\nglobalShadow/=shadowLightCount;\\n#else\\nglobalShadow=1.0;\\n#endif\\n\\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\\n#ifdef REFLECTION\\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\\n#ifdef REFLECTIONMAP_OPPOSITEZ\\nreflectionVector.z*=-1.0;\\n#endif\\n\\n#ifdef REFLECTIONMAP_3D\\nvec3 reflectionCoords=reflectionVector;\\n#else\\nvec2 reflectionCoords=reflectionVector.xy;\\n#ifdef REFLECTIONMAP_PROJECTION\\nreflectionCoords/=reflectionVector.z;\\n#endif\\nreflectionCoords.y=1.0-reflectionCoords.y;\\n#endif\\n#ifdef REFLECTIONBLUR\\nfloat reflectionLOD=vReflectionInfos.y;\\n#ifdef TEXTURELODSUPPORT\\n\\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\\n#else\\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\\nif(lodReflectionNormalizedDoubled<1.0){\\nreflectionColor=mix(\\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\\nreflectionSpecularMid,\\nlodReflectionNormalizedDoubled\\n);\\n} else {\\nreflectionColor=mix(\\nreflectionSpecularMid,\\nsampleReflection(reflectionSamplerLow,reflectionCoords),\\nlodReflectionNormalizedDoubled-1.0\\n);\\n}\\n#endif\\n#else\\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\\nreflectionColor=reflectionSample;\\n#endif\\n#ifdef RGBDREFLECTION\\nreflectionColor.rgb=fromRGBD(reflectionColor);\\n#endif\\n#ifdef GAMMAREFLECTION\\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\\n#endif\\n#ifdef REFLECTIONBGR\\nreflectionColor.rgb=reflectionColor.bgr;\\n#endif\\n\\nreflectionColor.rgb*=vReflectionInfos.x;\\n#endif\\n\\nvec3 diffuseColor=vec3(1.,1.,1.);\\nfloat finalAlpha=alpha;\\n#ifdef DIFFUSE\\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\\n#ifdef GAMMADIFFUSE\\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\\n#endif\\n\\ndiffuseMap.rgb*=vDiffuseInfos.y;\\n#ifdef DIFFUSEHASALPHA\\nfinalAlpha*=diffuseMap.a;\\n#endif\\ndiffuseColor=diffuseMap.rgb;\\n#endif\\n\\n#ifdef REFLECTIONFRESNEL\\nvec3 colorBase=diffuseColor;\\n#else\\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\\n#endif\\ncolorBase=max(colorBase,0.0);\\n\\n#ifdef USERGBCOLOR\\nvec3 finalColor=colorBase;\\n#else\\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\\n#else\\nvec3 mainColor=vPrimaryColor.rgb;\\n#endif\\nvec3 finalColor=colorBase*mainColor;\\n#endif\\n\\n#ifdef REFLECTIONFRESNEL\\nvec3 reflectionAmount=vReflectionControl.xxx;\\nvec3 reflectionReflectance0=vReflectionControl.yyy;\\nvec3 reflectionReflectance90=vReflectionControl.zzz;\\nfloat VdotN=dot(normalize(vEyePosition),normalW);\\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\\nreflectionAmount*=planarReflectionFresnel;\\n#ifdef REFLECTIONFALLOFF\\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\\nreflectionAmount*=reflectionDistanceFalloff;\\n#endif\\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\\n#endif\\n#ifdef OPACITYFRESNEL\\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\\n\\nconst float startAngle=0.1;\\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\\nfinalAlpha*=fadeFactor*fadeFactor;\\n#endif\\n\\n#ifdef SHADOWINUSE\\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\\n#endif\\n\\nvec4 color=vec4(finalColor,finalAlpha);\\n#include\\n#ifdef IMAGEPROCESSINGPOSTPROCESS\\n\\n\\ncolor.rgb=clamp(color.rgb,0.,30.0);\\n#else\\n\\ncolor=applyImageProcessing(color);\\n#endif\\n#ifdef PREMULTIPLYALPHA\\n\\ncolor.rgb*=color.a;\\n#endif\\n#ifdef NOISE\\ncolor.rgb+=dither(vPositionW.xy,0.5);\\ncolor=max(color,0.0);\\n#endif\\ngl_FragColor=color;\\n}\\n\",\"noisePixelShader\":\"\\n\\nuniform float brightness;\\nuniform int octaves;\\nuniform float persistence;\\nuniform float timeScale;\\n\\nvarying vec2 vUV;\\n\\nvec2 hash22(vec2 p)\\n{\\np=p*mat2(127.1,311.7,269.5,183.3);\\np=-1.0+2.0*fract(sin(p)*43758.5453123);\\nreturn sin(p*6.283+timeScale);\\n}\\nfloat interpolationNoise(vec2 p)\\n{\\nvec2 pi=floor(p);\\nvec2 pf=p-pi;\\nvec2 w=pf*pf*(3.-2.*pf);\\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\\nfloat xm1=mix(f00,f10,w.x);\\nfloat xm2=mix(f01,f11,w.x);\\nfloat ym=mix(xm1,xm2,w.y); \\nreturn ym;\\n}\\nfloat perlinNoise2D(float x,float y)\\n{\\nfloat sum=0.0;\\nfloat frequency=0.0;\\nfloat amplitude=0.0;\\nfor(int i=0; i0\\nuniform mat4 mBones[BonesPerMesh];\\nattribute vec4 matricesIndices;\\nattribute vec4 matricesWeights;\\n#if NUM_BONE_INFLUENCERS>4\\nattribute vec4 matricesIndicesExtra;\\nattribute vec4 matricesWeightsExtra;\\n#endif\\n#endif\",\"instancesDeclaration\":\"#ifdef INSTANCES\\nattribute vec4 world0;\\nattribute vec4 world1;\\nattribute vec4 world2;\\nattribute vec4 world3;\\n#else\\nuniform mat4 world;\\n#endif\",\"pointCloudVertexDeclaration\":\"#ifdef POINTSIZE\\nuniform float pointSize;\\n#endif\",\"bumpVertexDeclaration\":\"#if defined(BUMP) || defined(PARALLAX)\\n#if defined(TANGENT) && defined(NORMAL) \\nvarying mat3 vTBN;\\n#endif\\n#endif\\n\",\"clipPlaneVertexDeclaration\":\"#ifdef CLIPPLANE\\nuniform vec4 vClipPlane;\\nvarying float fClipDistance;\\n#endif\",\"fogVertexDeclaration\":\"#ifdef FOG\\nvarying vec3 vFogDistance;\\n#endif\",\"morphTargetsVertexGlobalDeclaration\":\"#ifdef MORPHTARGETS\\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\\n#endif\",\"morphTargetsVertexDeclaration\":\"#ifdef MORPHTARGETS\\nattribute vec3 position{X};\\n#ifdef MORPHTARGETS_NORMAL\\nattribute vec3 normal{X};\\n#endif\\n#ifdef MORPHTARGETS_TANGENT\\nattribute vec3 tangent{X};\\n#endif\\n#endif\",\"logDepthDeclaration\":\"#ifdef LOGARITHMICDEPTH\\nuniform float logarithmicDepthConstant;\\nvarying float vFragmentDepth;\\n#endif\",\"morphTargetsVertex\":\"#ifdef MORPHTARGETS\\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\\n#ifdef MORPHTARGETS_NORMAL\\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\\n#endif\\n#ifdef MORPHTARGETS_TANGENT\\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\\n#endif\\n#endif\",\"instancesVertex\":\"#ifdef INSTANCES\\nmat4 finalWorld=mat4(world0,world1,world2,world3);\\n#else\\nmat4 finalWorld=world;\\n#endif\",\"bonesVertex\":\"#if NUM_BONE_INFLUENCERS>0\\nmat4 influence;\\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\\n#if NUM_BONE_INFLUENCERS>1\\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\\n#endif \\n#if NUM_BONE_INFLUENCERS>2\\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\\n#endif \\n#if NUM_BONE_INFLUENCERS>3\\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\\n#endif \\n#if NUM_BONE_INFLUENCERS>4\\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\\n#endif \\n#if NUM_BONE_INFLUENCERS>5\\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\\n#endif \\n#if NUM_BONE_INFLUENCERS>6\\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\\n#endif \\n#if NUM_BONE_INFLUENCERS>7\\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\\n#endif \\nfinalWorld=finalWorld*influence;\\n#endif\",\"bumpVertex\":\"#if defined(BUMP) || defined(PARALLAX)\\n#if defined(TANGENT) && defined(NORMAL)\\nvec3 tbnNormal=normalize(normalUpdated);\\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\\n#endif\\n#endif\",\"clipPlaneVertex\":\"#ifdef CLIPPLANE\\nfClipDistance=dot(worldPos,vClipPlane);\\n#endif\",\"fogVertex\":\"#ifdef FOG\\nvFogDistance=(view*worldPos).xyz;\\n#endif\",\"shadowsVertex\":\"#ifdef SHADOWS\\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\\n#endif\\n#endif\",\"pointCloudVertex\":\"#ifdef POINTSIZE\\ngl_PointSize=pointSize;\\n#endif\",\"logDepthVertex\":\"#ifdef LOGARITHMICDEPTH\\nvFragmentDepth=1.0+gl_Position.w;\\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\\n#endif\",\"helperFunctions\":\"const float PI=3.1415926535897932384626433832795;\\nconst float LinearEncodePowerApprox=2.2;\\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\\nmat3 transposeMat3(mat3 inMatrix) {\\nvec3 i0=inMatrix[0];\\nvec3 i1=inMatrix[1];\\nvec3 i2=inMatrix[2];\\nmat3 outMatrix=mat3(\\nvec3(i0.x,i1.x,i2.x),\\nvec3(i0.y,i1.y,i2.y),\\nvec3(i0.z,i1.z,i2.z)\\n);\\nreturn outMatrix;\\n}\\n\\nmat3 inverseMat3(mat3 inMatrix) {\\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\\nfloat b01=a22*a11-a12*a21;\\nfloat b11=-a22*a10+a12*a20;\\nfloat b21=a21*a10-a11*a20;\\nfloat det=a00*b01+a01*b11+a02*b21;\\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\\n}\\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\\n{\\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\\nreturn mix(value,1.0,mask);\\n}\\nvec3 applyEaseInOut(vec3 x){\\nreturn x*x*(3.0-2.0*x);\\n}\\nvec3 toLinearSpace(vec3 color)\\n{\\nreturn pow(color,vec3(LinearEncodePowerApprox));\\n}\\nvec3 toGammaSpace(vec3 color)\\n{\\nreturn pow(color,vec3(GammaEncodePowerApprox));\\n}\\nfloat square(float value)\\n{\\nreturn value*value;\\n}\\nfloat getLuminance(vec3 color)\\n{\\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\\n}\\n\\nfloat getRand(vec2 seed) {\\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\\n}\\nfloat dither(vec2 seed,float varianceAmount) {\\nfloat rand=getRand(seed);\\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\\nreturn dither;\\n}\\n\\nconst float rgbdMaxRange=255.0;\\nvec4 toRGBD(vec3 color) {\\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\\nfloat D=max(rgbdMaxRange/maxRGB,1.);\\nD=clamp(floor(D)/255.0,0.,1.);\\n\\nvec3 rgb=color.rgb*D;\\n\\nrgb=toGammaSpace(rgb);\\nreturn vec4(rgb,D); \\n}\\nvec3 fromRGBD(vec4 rgbd) {\\n\\nrgbd.rgb=toLinearSpace(rgbd.rgb);\\n\\nreturn rgbd.rgb/rgbd.a;\\n}\",\"lightFragmentDeclaration\":\"#ifdef LIGHT{X}\\nuniform vec4 vLightData{X};\\nuniform vec4 vLightDiffuse{X};\\n#ifdef SPECULARTERM\\nuniform vec3 vLightSpecular{X};\\n#else\\nvec3 vLightSpecular{X}=vec3(0.);\\n#endif\\n#ifdef SHADOW{X}\\n#if defined(SHADOWCUBE{X})\\nuniform samplerCube shadowSampler{X};\\n#else\\nvarying vec4 vPositionFromLight{X};\\nvarying float vDepthMetric{X};\\n#if defined(SHADOWPCSS{X})\\nuniform highp sampler2DShadow shadowSampler{X};\\nuniform highp sampler2D depthSampler{X};\\n#elif defined(SHADOWPCF{X})\\nuniform highp sampler2DShadow shadowSampler{X};\\n#else\\nuniform sampler2D shadowSampler{X};\\n#endif\\nuniform mat4 lightMatrix{X};\\n#endif\\nuniform vec4 shadowsInfo{X};\\nuniform vec2 depthValues{X};\\n#endif\\n#ifdef SPOTLIGHT{X}\\nuniform vec4 vLightDirection{X};\\n#endif\\n#ifdef HEMILIGHT{X}\\nuniform vec3 vLightGround{X};\\n#endif\\n#ifdef PROJECTEDLIGHTTEXTURE{X}\\nuniform mat4 textureProjectionMatrix{X};\\nuniform sampler2D projectionLightSampler{X};\\n#endif\\n#endif\",\"lightsFragmentFunctions\":\"\\nstruct lightingInfo\\n{\\nvec3 diffuse;\\n#ifdef SPECULARTERM\\nvec3 specular;\\n#endif\\n#ifdef NDOTL\\nfloat ndl;\\n#endif\\n};\\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\\nlightingInfo result;\\nvec3 lightVectorW;\\nfloat attenuation=1.0;\\nif (lightData.w == 0.)\\n{\\nvec3 direction=lightData.xyz-vPositionW;\\nattenuation=max(0.,1.0-length(direction)/range);\\nlightVectorW=normalize(direction);\\n}\\nelse\\n{\\nlightVectorW=normalize(-lightData.xyz);\\n}\\n\\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\\n#ifdef NDOTL\\nresult.ndl=ndl;\\n#endif\\nresult.diffuse=ndl*diffuseColor*attenuation;\\n#ifdef SPECULARTERM\\n\\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\\nfloat specComp=max(0.,dot(vNormal,angleW));\\nspecComp=pow(specComp,max(1.,glossiness));\\nresult.specular=specComp*specularColor*attenuation;\\n#endif\\nreturn result;\\n}\\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\\nlightingInfo result;\\nvec3 direction=lightData.xyz-vPositionW;\\nvec3 lightVectorW=normalize(direction);\\nfloat attenuation=max(0.,1.0-length(direction)/range);\\n\\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\\nif (cosAngle>=lightDirection.w)\\n{\\ncosAngle=max(0.,pow(cosAngle,lightData.w));\\nattenuation*=cosAngle;\\n\\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\\n#ifdef NDOTL\\nresult.ndl=ndl;\\n#endif\\nresult.diffuse=ndl*diffuseColor*attenuation;\\n#ifdef SPECULARTERM\\n\\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\\nfloat specComp=max(0.,dot(vNormal,angleW));\\nspecComp=pow(specComp,max(1.,glossiness));\\nresult.specular=specComp*specularColor*attenuation;\\n#endif\\nreturn result;\\n}\\nresult.diffuse=vec3(0.);\\n#ifdef SPECULARTERM\\nresult.specular=vec3(0.);\\n#endif\\n#ifdef NDOTL\\nresult.ndl=0.;\\n#endif\\nreturn result;\\n}\\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\\nlightingInfo result;\\n\\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\\n#ifdef NDOTL\\nresult.ndl=ndl;\\n#endif\\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\\n#ifdef SPECULARTERM\\n\\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\\nfloat specComp=max(0.,dot(vNormal,angleW));\\nspecComp=pow(specComp,max(1.,glossiness));\\nresult.specular=specComp*specularColor;\\n#endif\\nreturn result;\\n}\\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\\nstrq/=strq.w;\\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\\nreturn textureColor;\\n}\",\"lightUboDeclaration\":\"#ifdef LIGHT{X}\\nuniform Light{X}\\n{\\nvec4 vLightData;\\nvec4 vLightDiffuse;\\nvec3 vLightSpecular;\\n#ifdef SPOTLIGHT{X}\\nvec4 vLightDirection;\\n#endif\\n#ifdef HEMILIGHT{X}\\nvec3 vLightGround;\\n#endif\\nvec4 shadowsInfo;\\nvec2 depthValues;\\n} light{X};\\n#ifdef PROJECTEDLIGHTTEXTURE{X}\\nuniform mat4 textureProjectionMatrix{X};\\nuniform sampler2D projectionLightSampler{X};\\n#endif\\n#ifdef SHADOW{X}\\n#if defined(SHADOWCUBE{X})\\nuniform samplerCube shadowSampler{X}; \\n#else\\nvarying vec4 vPositionFromLight{X};\\nvarying float vDepthMetric{X};\\n#if defined(SHADOWPCSS{X})\\nuniform highp sampler2DShadow shadowSampler{X};\\nuniform highp sampler2D depthSampler{X};\\n#elif defined(SHADOWPCF{X})\\nuniform highp sampler2DShadow shadowSampler{X};\\n#else\\nuniform sampler2D shadowSampler{X};\\n#endif\\nuniform mat4 lightMatrix{X};\\n#endif\\n#endif\\n#endif\",\"defaultVertexDeclaration\":\"\\nuniform mat4 viewProjection;\\nuniform mat4 view;\\n#ifdef DIFFUSE\\nuniform mat4 diffuseMatrix;\\nuniform vec2 vDiffuseInfos;\\n#endif\\n#ifdef AMBIENT\\nuniform mat4 ambientMatrix;\\nuniform vec2 vAmbientInfos;\\n#endif\\n#ifdef OPACITY\\nuniform mat4 opacityMatrix;\\nuniform vec2 vOpacityInfos;\\n#endif\\n#ifdef EMISSIVE\\nuniform vec2 vEmissiveInfos;\\nuniform mat4 emissiveMatrix;\\n#endif\\n#ifdef LIGHTMAP\\nuniform vec2 vLightmapInfos;\\nuniform mat4 lightmapMatrix;\\n#endif\\n#if defined(SPECULAR) && defined(SPECULARTERM)\\nuniform vec2 vSpecularInfos;\\nuniform mat4 specularMatrix;\\n#endif\\n#ifdef BUMP\\nuniform vec3 vBumpInfos;\\nuniform mat4 bumpMatrix;\\n#endif\\n#ifdef POINTSIZE\\nuniform float pointSize;\\n#endif\\n\",\"defaultFragmentDeclaration\":\"uniform vec4 vDiffuseColor;\\n#ifdef SPECULARTERM\\nuniform vec4 vSpecularColor;\\n#endif\\nuniform vec3 vEmissiveColor;\\n\\n#ifdef DIFFUSE\\nuniform vec2 vDiffuseInfos;\\n#endif\\n#ifdef AMBIENT\\nuniform vec2 vAmbientInfos;\\n#endif\\n#ifdef OPACITY \\nuniform vec2 vOpacityInfos;\\n#endif\\n#ifdef EMISSIVE\\nuniform vec2 vEmissiveInfos;\\n#endif\\n#ifdef LIGHTMAP\\nuniform vec2 vLightmapInfos;\\n#endif\\n#ifdef BUMP\\nuniform vec3 vBumpInfos;\\nuniform vec2 vTangentSpaceParams;\\n#endif\\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\\nuniform mat4 view;\\n#endif\\n#ifdef REFRACTION\\nuniform vec4 vRefractionInfos;\\n#ifndef REFRACTIONMAP_3D\\nuniform mat4 refractionMatrix;\\n#endif\\n#ifdef REFRACTIONFRESNEL\\nuniform vec4 refractionLeftColor;\\nuniform vec4 refractionRightColor;\\n#endif\\n#endif\\n#if defined(SPECULAR) && defined(SPECULARTERM)\\nuniform vec2 vSpecularInfos;\\n#endif\\n#ifdef DIFFUSEFRESNEL\\nuniform vec4 diffuseLeftColor;\\nuniform vec4 diffuseRightColor;\\n#endif\\n#ifdef OPACITYFRESNEL\\nuniform vec4 opacityParts;\\n#endif\\n#ifdef EMISSIVEFRESNEL\\nuniform vec4 emissiveLeftColor;\\nuniform vec4 emissiveRightColor;\\n#endif\\n\\n#ifdef REFLECTION\\nuniform vec2 vReflectionInfos;\\n#ifdef REFLECTIONMAP_SKYBOX\\n#else\\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\\nuniform mat4 reflectionMatrix;\\n#endif\\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\\nuniform vec3 vReflectionPosition;\\nuniform vec3 vReflectionSize; \\n#endif\\n#endif\\n#ifdef REFLECTIONFRESNEL\\nuniform vec4 reflectionLeftColor;\\nuniform vec4 reflectionRightColor;\\n#endif\\n#endif\",\"defaultUboDeclaration\":\"layout(std140,column_major) uniform;\\nuniform Material\\n{\\nvec4 diffuseLeftColor;\\nvec4 diffuseRightColor;\\nvec4 opacityParts;\\nvec4 reflectionLeftColor;\\nvec4 reflectionRightColor;\\nvec4 refractionLeftColor;\\nvec4 refractionRightColor;\\nvec4 emissiveLeftColor; \\nvec4 emissiveRightColor;\\nvec2 vDiffuseInfos;\\nvec2 vAmbientInfos;\\nvec2 vOpacityInfos;\\nvec2 vReflectionInfos;\\nvec3 vReflectionPosition;\\nvec3 vReflectionSize;\\nvec2 vEmissiveInfos;\\nvec2 vLightmapInfos;\\nvec2 vSpecularInfos;\\nvec3 vBumpInfos;\\nmat4 diffuseMatrix;\\nmat4 ambientMatrix;\\nmat4 opacityMatrix;\\nmat4 reflectionMatrix;\\nmat4 emissiveMatrix;\\nmat4 lightmapMatrix;\\nmat4 specularMatrix;\\nmat4 bumpMatrix; \\nvec4 vTangentSpaceParams;\\nmat4 refractionMatrix;\\nvec4 vRefractionInfos;\\nvec4 vSpecularColor;\\nvec3 vEmissiveColor;\\nvec4 vDiffuseColor;\\nfloat pointSize; \\n};\\nuniform Scene {\\nmat4 viewProjection;\\nmat4 view;\\n};\",\"shadowsFragmentFunctions\":\"#ifdef SHADOWS\\n#ifndef SHADOWFLOAT\\nfloat unpack(vec4 color)\\n{\\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\\nreturn dot(color,bit_shift);\\n}\\n#endif\\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\\n{\\nvec3 directionToLight=vPositionW-lightPosition;\\nfloat depth=length(directionToLight);\\ndepth=(depth+depthValues.x)/(depthValues.y);\\ndepth=clamp(depth,0.,1.0);\\ndirectionToLight=normalize(directionToLight);\\ndirectionToLight.y=-directionToLight.y;\\n#ifndef SHADOWFLOAT\\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\\n#else\\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\\n#endif\\nif (depth>shadow)\\n{\\nreturn darkness;\\n}\\nreturn 1.0;\\n}\\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\\n{\\nvec3 directionToLight=vPositionW-lightPosition;\\nfloat depth=length(directionToLight);\\ndepth=(depth+depthValues.x)/(depthValues.y);\\ndepth=clamp(depth,0.,1.0);\\ndirectionToLight=normalize(directionToLight);\\ndirectionToLight.y=-directionToLight.y;\\nfloat visibility=1.;\\nvec3 poissonDisk[4];\\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\\n\\n#ifndef SHADOWFLOAT\\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\\n{\\nreturn 1.0;\\n}\\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\\n#ifndef SHADOWFLOAT\\nfloat shadow=unpack(texture2D(shadowSampler,uv));\\n#else\\nfloat shadow=texture2D(shadowSampler,uv).x;\\n#endif\\nif (shadowPixelDepth>shadow)\\n{\\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\\n}\\nreturn 1.;\\n}\\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\\n{\\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\\n{\\nreturn 1.0;\\n}\\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\\nfloat visibility=1.;\\nvec2 poissonDisk[4];\\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\\npoissonDisk[3]=vec2(0.34495938,0.29387760);\\n\\n#ifndef SHADOWFLOAT\\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\\n{\\nreturn 1.0;\\n}\\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\\n#ifndef SHADOWFLOAT\\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\\n#else\\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\\n#endif\\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\\n}\\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\\n{\\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\\n{\\nreturn 1.0;\\n}\\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \\n#ifndef SHADOWFLOAT\\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\\n#else\\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\\n#endif\\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\\n}\\n#ifdef WEBGL2\\n\\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\\n{\\nif (depthMetric>1.0 || depthMetric<0.0) {\\nreturn 1.0;\\n}\\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\\nfloat shadow=texture2D(shadowSampler,uvDepth);\\nshadow=mix(darkness,1.,shadow);\\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\\n}\\n\\n\\n\\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\\n{\\nif (depthMetric>1.0 || depthMetric<0.0) {\\nreturn 1.0;\\n}\\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \\nuv+=0.5; \\nvec2 st=fract(uv); \\nvec2 base_uv=floor(uv)-0.5; \\nbase_uv*=shadowMapSizeAndInverse.y; \\n\\n\\n\\n\\nvec2 uvw0=3.-2.*st;\\nvec2 uvw1=1.+2.*st;\\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\\nfloat shadow=0.;\\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\\nshadow=shadow/16.;\\nshadow=mix(darkness,1.,shadow);\\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\\n}\\n\\n\\n\\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\\n{\\nif (depthMetric>1.0 || depthMetric<0.0) {\\nreturn 1.0;\\n}\\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \\nuv+=0.5; \\nvec2 st=fract(uv); \\nvec2 base_uv=floor(uv)-0.5; \\nbase_uv*=shadowMapSizeAndInverse.y; \\n\\n\\nvec2 uvw0=4.-3.*st;\\nvec2 uvw1=vec2(7.);\\nvec2 uvw2=1.+3.*st;\\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\\nfloat shadow=0.;\\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\\nshadow=shadow/144.;\\nshadow=mix(darkness,1.,shadow);\\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\\n}\\nconst vec3 PoissonSamplers32[64]=vec3[64](\\nvec3(0.06407013,0.05409927,0.),\\nvec3(0.7366577,0.5789394,0.),\\nvec3(-0.6270542,-0.5320278,0.),\\nvec3(-0.4096107,0.8411095,0.),\\nvec3(0.6849564,-0.4990818,0.),\\nvec3(-0.874181,-0.04579735,0.),\\nvec3(0.9989998,0.0009880066,0.),\\nvec3(-0.004920578,-0.9151649,0.),\\nvec3(0.1805763,0.9747483,0.),\\nvec3(-0.2138451,0.2635818,0.),\\nvec3(0.109845,0.3884785,0.),\\nvec3(0.06876755,-0.3581074,0.),\\nvec3(0.374073,-0.7661266,0.),\\nvec3(0.3079132,-0.1216763,0.),\\nvec3(-0.3794335,-0.8271583,0.),\\nvec3(-0.203878,-0.07715034,0.),\\nvec3(0.5912697,0.1469799,0.),\\nvec3(-0.88069,0.3031784,0.),\\nvec3(0.5040108,0.8283722,0.),\\nvec3(-0.5844124,0.5494877,0.),\\nvec3(0.6017799,-0.1726654,0.),\\nvec3(-0.5554981,0.1559997,0.),\\nvec3(-0.3016369,-0.3900928,0.),\\nvec3(-0.5550632,-0.1723762,0.),\\nvec3(0.925029,0.2995041,0.),\\nvec3(-0.2473137,0.5538505,0.),\\nvec3(0.9183037,-0.2862392,0.),\\nvec3(0.2469421,0.6718712,0.),\\nvec3(0.3916397,-0.4328209,0.),\\nvec3(-0.03576927,-0.6220032,0.),\\nvec3(-0.04661255,0.7995201,0.),\\nvec3(0.4402924,0.3640312,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.)\\n);\\nconst vec3 PoissonSamplers64[64]=vec3[64](\\nvec3(-0.613392,0.617481,0.),\\nvec3(0.170019,-0.040254,0.),\\nvec3(-0.299417,0.791925,0.),\\nvec3(0.645680,0.493210,0.),\\nvec3(-0.651784,0.717887,0.),\\nvec3(0.421003,0.027070,0.),\\nvec3(-0.817194,-0.271096,0.),\\nvec3(-0.705374,-0.668203,0.),\\nvec3(0.977050,-0.108615,0.),\\nvec3(0.063326,0.142369,0.),\\nvec3(0.203528,0.214331,0.),\\nvec3(-0.667531,0.326090,0.),\\nvec3(-0.098422,-0.295755,0.),\\nvec3(-0.885922,0.215369,0.),\\nvec3(0.566637,0.605213,0.),\\nvec3(0.039766,-0.396100,0.),\\nvec3(0.751946,0.453352,0.),\\nvec3(0.078707,-0.715323,0.),\\nvec3(-0.075838,-0.529344,0.),\\nvec3(0.724479,-0.580798,0.),\\nvec3(0.222999,-0.215125,0.),\\nvec3(-0.467574,-0.405438,0.),\\nvec3(-0.248268,-0.814753,0.),\\nvec3(0.354411,-0.887570,0.),\\nvec3(0.175817,0.382366,0.),\\nvec3(0.487472,-0.063082,0.),\\nvec3(-0.084078,0.898312,0.),\\nvec3(0.488876,-0.783441,0.),\\nvec3(0.470016,0.217933,0.),\\nvec3(-0.696890,-0.549791,0.),\\nvec3(-0.149693,0.605762,0.),\\nvec3(0.034211,0.979980,0.),\\nvec3(0.503098,-0.308878,0.),\\nvec3(-0.016205,-0.872921,0.),\\nvec3(0.385784,-0.393902,0.),\\nvec3(-0.146886,-0.859249,0.),\\nvec3(0.643361,0.164098,0.),\\nvec3(0.634388,-0.049471,0.),\\nvec3(-0.688894,0.007843,0.),\\nvec3(0.464034,-0.188818,0.),\\nvec3(-0.440840,0.137486,0.),\\nvec3(0.364483,0.511704,0.),\\nvec3(0.034028,0.325968,0.),\\nvec3(0.099094,-0.308023,0.),\\nvec3(0.693960,-0.366253,0.),\\nvec3(0.678884,-0.204688,0.),\\nvec3(0.001801,0.780328,0.),\\nvec3(0.145177,-0.898984,0.),\\nvec3(0.062655,-0.611866,0.),\\nvec3(0.315226,-0.604297,0.),\\nvec3(-0.780145,0.486251,0.),\\nvec3(-0.371868,0.882138,0.),\\nvec3(0.200476,0.494430,0.),\\nvec3(-0.494552,-0.711051,0.),\\nvec3(0.612476,0.705252,0.),\\nvec3(-0.578845,-0.768792,0.),\\nvec3(-0.772454,-0.090976,0.),\\nvec3(0.504440,0.372295,0.),\\nvec3(0.155736,0.065157,0.),\\nvec3(0.391522,0.849605,0.),\\nvec3(-0.620106,-0.328104,0.),\\nvec3(0.789239,-0.419965,0.),\\nvec3(-0.545396,0.538133,0.),\\nvec3(-0.178564,-0.596057,0.)\\n);\\n\\n\\n\\n\\n\\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\\n{\\nif (depthMetric>1.0 || depthMetric<0.0) {\\nreturn 1.0;\\n}\\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\\nfloat blockerDepth=0.0;\\nfloat sumBlockerDepth=0.0;\\nfloat numBlocker=0.0;\\nfor (int i=0; icurrRayHeight)\\n{\\nfloat delta1=currSampledHeight-currRayHeight;\\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\\nfloat ratio=delta1/(delta1+delta2);\\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\\n\\nbreak;\\n}\\nelse\\n{\\ncurrRayHeight-=stepSize;\\nvLastOffset=vCurrOffset;\\nvCurrOffset+=stepSize*vMaxOffset;\\nlastSampledHeight=currSampledHeight;\\n}\\n}\\nreturn vCurrOffset;\\n}\\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\\n{\\n\\nfloat height=texture2D(bumpSampler,vBumpUV).w;\\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\\nreturn -texCoordOffset;\\n}\\n#endif\\n#endif\",\"clipPlaneFragmentDeclaration\":\"#ifdef CLIPPLANE\\nvarying float fClipDistance;\\n#endif\",\"fogFragmentDeclaration\":\"#ifdef FOG\\n#define FOGMODE_NONE 0.\\n#define FOGMODE_EXP 1.\\n#define FOGMODE_EXP2 2.\\n#define FOGMODE_LINEAR 3.\\n#define E 2.71828\\nuniform vec4 vFogInfos;\\nuniform vec3 vFogColor;\\nvarying vec3 vFogDistance;\\nfloat CalcFogFactor()\\n{\\nfloat fogCoeff=1.0;\\nfloat fogStart=vFogInfos.y;\\nfloat fogEnd=vFogInfos.z;\\nfloat fogDensity=vFogInfos.w;\\nfloat fogDistance=length(vFogDistance);\\nif (FOGMODE_LINEAR == vFogInfos.x)\\n{\\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\\n}\\nelse if (FOGMODE_EXP == vFogInfos.x)\\n{\\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\\n}\\nelse if (FOGMODE_EXP2 == vFogInfos.x)\\n{\\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\\n}\\nreturn clamp(fogCoeff,0.0,1.0);\\n}\\n#endif\",\"clipPlaneFragment\":\"#ifdef CLIPPLANE\\nif (fClipDistance>0.0)\\n{\\ndiscard;\\n}\\n#endif\",\"bumpFragment\":\"vec2 uvOffset=vec2(0.0,0.0);\\n#if defined(BUMP) || defined(PARALLAX)\\n#ifdef NORMALXYSCALE\\nfloat normalScale=1.0;\\n#else \\nfloat normalScale=vBumpInfos.y;\\n#endif\\n#if defined(TANGENT) && defined(NORMAL)\\nmat3 TBN=vTBN;\\n#else\\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\\n#endif\\n#endif\\n#ifdef PARALLAX\\nmat3 invTBN=transposeMat3(TBN);\\n#ifdef PARALLAXOCCLUSION\\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\\n#else\\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\\n#endif\\n#endif\\n#ifdef BUMP\\n#ifdef OBJECTSPACE_NORMALMAP\\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\\nnormalW=normalize(mat3(normalMatrix)*normalW); \\n#else\\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\\n#endif\\n#endif\",\"lightFragment\":\"#ifdef LIGHT{X}\\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\\n\\n#else\\n#ifdef PBR\\n#ifdef SPOTLIGHT{X}\\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\\n#endif\\n#ifdef HEMILIGHT{X}\\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\\n#endif\\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\\n#endif\\n#else\\n#ifdef SPOTLIGHT{X}\\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\\n#endif\\n#ifdef HEMILIGHT{X}\\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\\n#endif\\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\\n#endif\\n#endif\\n#ifdef PROJECTEDLIGHTTEXTURE{X}\\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\\n#endif\\n#endif\\n#ifdef SHADOW{X}\\n#ifdef SHADOWCLOSEESM{X}\\n#if defined(SHADOWCUBE{X})\\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\\n#else\\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\\n#endif\\n#elif defined(SHADOWESM{X})\\n#if defined(SHADOWCUBE{X})\\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\\n#else\\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\\n#endif\\n#elif defined(SHADOWPOISSON{X})\\n#if defined(SHADOWCUBE{X})\\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\\n#else\\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#endif\\n#elif defined(SHADOWPCF{X})\\n#if defined(SHADOWLOWQUALITY{X})\\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#elif defined(SHADOWMEDIUMQUALITY{X})\\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#else\\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#endif\\n#elif defined(SHADOWPCSS{X})\\n#if defined(SHADOWLOWQUALITY{X})\\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#elif defined(SHADOWMEDIUMQUALITY{X})\\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#else\\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#endif\\n#else\\n#if defined(SHADOWCUBE{X})\\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\\n#else\\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#endif\\n#endif\\n#ifdef SHADOWONLY\\n#ifndef SHADOWINUSE\\n#define SHADOWINUSE\\n#endif\\nglobalShadow+=shadow;\\nshadowLightCount+=1.0;\\n#endif\\n#else\\nshadow=1.;\\n#endif\\n#ifndef SHADOWONLY\\n#ifdef CUSTOMUSERLIGHTING\\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\\n#ifdef SPECULARTERM\\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\\n#endif\\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\\ndiffuseBase+=lightmapColor*shadow;\\n#ifdef SPECULARTERM\\n#ifndef LIGHTMAPNOSPECULAR{X}\\nspecularBase+=info.specular*shadow*lightmapColor;\\n#endif\\n#endif\\n#else\\ndiffuseBase+=info.diffuse*shadow;\\n#ifdef SPECULARTERM\\nspecularBase+=info.specular*shadow;\\n#endif\\n#endif\\n#endif\\n#endif\",\"logDepthFragment\":\"#ifdef LOGARITHMICDEPTH\\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\\n#endif\",\"fogFragment\":\"#ifdef FOG\\nfloat fog=CalcFogFactor();\\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\\n#endif\",\"pbrVertexDeclaration\":\"uniform mat4 view;\\nuniform mat4 viewProjection;\\n#ifdef ALBEDO\\nuniform mat4 albedoMatrix;\\nuniform vec2 vAlbedoInfos;\\n#endif\\n#ifdef AMBIENT\\nuniform mat4 ambientMatrix;\\nuniform vec3 vAmbientInfos;\\n#endif\\n#ifdef OPACITY\\nuniform mat4 opacityMatrix;\\nuniform vec2 vOpacityInfos;\\n#endif\\n#ifdef EMISSIVE\\nuniform vec2 vEmissiveInfos;\\nuniform mat4 emissiveMatrix;\\n#endif\\n#ifdef LIGHTMAP\\nuniform vec2 vLightmapInfos;\\nuniform mat4 lightmapMatrix;\\n#endif\\n#ifdef REFLECTIVITY \\nuniform vec3 vReflectivityInfos;\\nuniform mat4 reflectivityMatrix;\\n#endif\\n#ifdef MICROSURFACEMAP\\nuniform vec2 vMicroSurfaceSamplerInfos;\\nuniform mat4 microSurfaceSamplerMatrix;\\n#endif\\n#ifdef BUMP\\nuniform vec3 vBumpInfos;\\nuniform mat4 bumpMatrix;\\n#endif\\n#ifdef POINTSIZE\\nuniform float pointSize;\\n#endif\\n\\n#ifdef REFRACTION\\nuniform vec4 vRefractionInfos;\\nuniform mat4 refractionMatrix;\\nuniform vec3 vRefractionMicrosurfaceInfos;\\n#endif\\n\\n#ifdef REFLECTION\\nuniform vec2 vReflectionInfos;\\nuniform mat4 reflectionMatrix;\\nuniform vec3 vReflectionMicrosurfaceInfos;\\n#endif\\n\",\"pbrFragmentDeclaration\":\"uniform vec3 vReflectionColor;\\nuniform vec4 vAlbedoColor;\\n\\nuniform vec4 vLightingIntensity;\\nuniform vec4 vReflectivityColor;\\nuniform vec3 vEmissiveColor;\\n\\n#ifdef ALBEDO\\nuniform vec2 vAlbedoInfos;\\n#endif\\n#ifdef AMBIENT\\nuniform vec3 vAmbientInfos;\\n#endif\\n#ifdef BUMP\\nuniform vec3 vBumpInfos;\\nuniform vec2 vTangentSpaceParams;\\n#endif\\n#ifdef OPACITY \\nuniform vec2 vOpacityInfos;\\n#endif\\n#ifdef EMISSIVE\\nuniform vec2 vEmissiveInfos;\\n#endif\\n#ifdef LIGHTMAP\\nuniform vec2 vLightmapInfos;\\n#endif\\n#ifdef REFLECTIVITY\\nuniform vec3 vReflectivityInfos;\\n#endif\\n#ifdef MICROSURFACEMAP\\nuniform vec2 vMicroSurfaceSamplerInfos;\\n#endif\\n\\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\\nuniform mat4 view;\\n#endif\\n\\n#ifdef REFRACTION\\nuniform vec4 vRefractionInfos;\\nuniform mat4 refractionMatrix;\\nuniform vec3 vRefractionMicrosurfaceInfos;\\n#endif\\n\\n#ifdef REFLECTION\\nuniform vec2 vReflectionInfos;\\nuniform mat4 reflectionMatrix;\\nuniform vec3 vReflectionMicrosurfaceInfos;\\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\\nuniform vec3 vReflectionPosition;\\nuniform vec3 vReflectionSize; \\n#endif\\n#endif\",\"pbrUboDeclaration\":\"layout(std140,column_major) uniform;\\nuniform Material\\n{\\nuniform vec2 vAlbedoInfos;\\nuniform vec3 vAmbientInfos;\\nuniform vec2 vOpacityInfos;\\nuniform vec2 vEmissiveInfos;\\nuniform vec2 vLightmapInfos;\\nuniform vec3 vReflectivityInfos;\\nuniform vec2 vMicroSurfaceSamplerInfos;\\nuniform vec4 vRefractionInfos;\\nuniform vec2 vReflectionInfos;\\nuniform vec3 vReflectionPosition;\\nuniform vec3 vReflectionSize; \\nuniform vec3 vBumpInfos;\\nuniform mat4 albedoMatrix;\\nuniform mat4 ambientMatrix;\\nuniform mat4 opacityMatrix;\\nuniform mat4 emissiveMatrix;\\nuniform mat4 lightmapMatrix;\\nuniform mat4 reflectivityMatrix;\\nuniform mat4 microSurfaceSamplerMatrix;\\nuniform mat4 bumpMatrix;\\nuniform vec2 vTangentSpaceParams;\\nuniform mat4 refractionMatrix;\\nuniform mat4 reflectionMatrix;\\nuniform vec3 vReflectionColor;\\nuniform vec4 vAlbedoColor;\\nuniform vec4 vLightingIntensity;\\nuniform vec3 vRefractionMicrosurfaceInfos;\\nuniform vec3 vReflectionMicrosurfaceInfos;\\nuniform vec4 vReflectivityColor;\\nuniform vec3 vEmissiveColor;\\nuniform float pointSize;\\n};\\nuniform Scene {\\nmat4 viewProjection;\\nmat4 view;\\n};\",\"pbrFunctions\":\"\\n#define RECIPROCAL_PI2 0.15915494\\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\\n\\nconst float kRougnhessToAlphaScale=0.1;\\nconst float kRougnhessToAlphaOffset=0.29248125;\\nfloat convertRoughnessToAverageSlope(float roughness)\\n{\\n\\nconst float kMinimumVariance=0.0005;\\nfloat alphaG=square(roughness)+kMinimumVariance;\\nreturn alphaG;\\n}\\n\\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\\n{\\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\\n}\\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\\n{\\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\\n}\\n\\n\\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\\n{\\n\\n\\n\\nfloat a2=square(alphaG);\\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\\nreturn a2/(PI*d*d);\\n}\\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\\n{\\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\\n}\\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\\n{\\n\\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\\n}\\n\\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\\n{\\nroughness=max(roughness,geometricRoughnessFactor);\\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\\nvisibility/=(4.0*NdotL*NdotV); \\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\\nreturn fresnel*specTerm;\\n}\\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\\n{\\n\\n\\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\\nfloat fresnel =\\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\\nreturn fresnel*NdotL/PI;\\n}\\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\\n{\\n#ifdef USEPHYSICALLIGHTFALLOFF\\n\\nfloat lightRoughness=lightRadius/lightDistance;\\n\\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\\nreturn totalRoughness;\\n#else\\nreturn roughness;\\n#endif\\n}\\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\\n{\\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\\nreturn microSurface;\\n}\\n\\n\\nfloat fresnelGrazingReflectance(float reflectance0) {\\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\\nreturn reflectance90;\\n}\\n\\n\\n#define UNPACK_LOD(x) (1.0-x)*255.0\\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\\nfloat microsurfaceAverageSlope=alphaG;\\n\\n\\n\\n\\n\\n\\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\\nfloat lod=log2(microsurfaceAverageSlopeTexels);\\nreturn lod;\\n}\\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\\n\\n\\nfloat temp=NdotVUnclamped+ambientOcclusion;\\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\\n}\\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\\n\\nvec3 reflection=reflect(view,normal);\\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\\nreturn square(temp);\\n}\",\"harmonicsFunctions\":\"#ifdef USESPHERICALFROMREFLECTIONMAP\\nuniform vec3 vSphericalX;\\nuniform vec3 vSphericalY;\\nuniform vec3 vSphericalZ;\\nuniform vec3 vSphericalXX_ZZ;\\nuniform vec3 vSphericalYY_ZZ;\\nuniform vec3 vSphericalZZ;\\nuniform vec3 vSphericalXY;\\nuniform vec3 vSphericalYZ;\\nuniform vec3 vSphericalZX;\\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\\nvec3 T=cross(Q.xyz,V);\\nT+=Q.www*V;\\nreturn cross(Q.xyz,T)+V;\\n}\\nvec3 environmentIrradianceJones(vec3 normal)\\n{\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nfloat Nx=normal.x;\\nfloat Ny=normal.y;\\nfloat Nz=normal.z;\\nvec3 C1=vSphericalZZ.rgb;\\nvec3 Cx=vSphericalX.rgb;\\nvec3 Cy=vSphericalY.rgb;\\nvec3 Cz=vSphericalZ.rgb;\\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\\nvec3 Cxy=vSphericalXY.rgb;\\nvec3 Cyz=vSphericalYZ.rgb;\\nvec3 Czx=vSphericalZX.rgb;\\nvec3 a1=Cyy_zz*Ny+Cy;\\nvec3 a2=Cyz*Nz+a1;\\nvec3 b1=Czx*Nz+Cx;\\nvec3 b2=Cxy*Ny+b1;\\nvec3 b3=Cxx_zz*Nx+b2;\\nvec3 t1=Cz*Nz+C1;\\nvec3 t2=a2*Ny+t1;\\nvec3 t3=b3*Nx+t2;\\nreturn t3;\\n}\\n#endif\",\"pbrLightFunctions\":\"\\nstruct lightingInfo\\n{\\nvec3 diffuse;\\n#ifdef SPECULARTERM\\nvec3 specular;\\n#endif\\n};\\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\\n{ \\n#ifdef USEPHYSICALLIGHTFALLOFF\\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\\n#else\\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\\n#endif\\nreturn lightDistanceFalloff;\\n}\\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\\n{\\nfloat falloff=0.0;\\n#ifdef USEPHYSICALLIGHTFALLOFF\\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \\n\\n\\n\\n\\n\\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\\n\\n\\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\\n#else\\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\\nif (cosAngle>=cosHalfAngle)\\n{\\nfalloff=max(0.,pow(cosAngle,exponent));\\n}\\n#endif\\nreturn falloff;\\n}\\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\\nlightingInfo result;\\nvec3 lightDirection;\\nfloat attenuation=1.0;\\nfloat lightDistance;\\n\\nif (lightData.w == 0.)\\n{\\nvec3 lightOffset=lightData.xyz-vPositionW;\\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\\nlightDistance=sqrt(lightDistanceSquared);\\nlightDirection=normalize(lightOffset);\\n}\\n\\nelse\\n{\\nlightDistance=length(-lightData.xyz);\\nlightDirection=normalize(-lightData.xyz);\\n}\\n\\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\\n\\nvec3 H=normalize(viewDirectionW+lightDirection);\\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\\n#ifdef SPECULARTERM\\n\\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\\nresult.specular=specTerm*diffuseColor*attenuation;\\n#endif\\nreturn result;\\n}\\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\\nlightingInfo result;\\nvec3 lightOffset=lightData.xyz-vPositionW;\\nvec3 directionToLightCenterW=normalize(lightOffset);\\n\\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\\n\\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\\nattenuation*=directionalAttenuation;\\n\\nfloat lightDistance=sqrt(lightDistanceSquared);\\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\\n\\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\\n#ifdef SPECULARTERM\\n\\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\\nresult.specular=specTerm*diffuseColor*attenuation;\\n#endif\\nreturn result;\\n}\\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\\nlightingInfo result;\\n\\n\\n\\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\\n#ifdef SPECULARTERM\\n\\nvec3 lightVectorW=normalize(lightData.xyz);\\nvec3 H=normalize(viewDirectionW+lightVectorW);\\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\\nNdotL=clamp(NdotL,0.000000000001,1.0);\\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\\nresult.specular=specTerm*diffuseColor;\\n#endif\\nreturn result;\\n}\\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\\nstrq/=strq.w;\\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\\nreturn toLinearSpace(textureColor);\\n}\",\"kernelBlurFragment\":\"#ifdef DOF\\nfactor=sampleCoC(sampleCoord{X}); \\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\\nsumOfWeights+=computedWeight;\\n#else\\ncomputedWeight=KERNEL_WEIGHT{X};\\n#endif\\n#ifdef PACKEDFLOAT\\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\\n#else\\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\\n#endif\",\"kernelBlurFragment2\":\"#ifdef DOF\\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\\nsumOfWeights+=computedWeight;\\n#else\\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\\n#endif\\n#ifdef PACKEDFLOAT\\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\\n#else\\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\\n#endif\",\"kernelBlurVaryingDeclaration\":\"varying vec2 sampleCoord{X};\",\"kernelBlurVertex\":\"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};\",\"mrtFragmentDeclaration\":\"#if __VERSION__>=200\\nlayout(location=0) out vec4 glFragData[{X}];\\n#endif\\n\",\"bones300Declaration\":\"#if NUM_BONE_INFLUENCERS>0\\nuniform mat4 mBones[BonesPerMesh];\\nin vec4 matricesIndices;\\nin vec4 matricesWeights;\\n#if NUM_BONE_INFLUENCERS>4\\nin vec4 matricesIndicesExtra;\\nin vec4 matricesWeightsExtra;\\n#endif\\n#endif\",\"instances300Declaration\":\"#ifdef INSTANCES\\nin vec4 world0;\\nin vec4 world1;\\nin vec4 world2;\\nin vec4 world3;\\n#else\\nuniform mat4 world;\\n#endif\",\"backgroundVertexDeclaration\":\"uniform mat4 view;\\nuniform mat4 viewProjection;\\nuniform float shadowLevel;\\n#ifdef DIFFUSE\\nuniform mat4 diffuseMatrix;\\nuniform vec2 vDiffuseInfos;\\n#endif\\n#ifdef REFLECTION\\nuniform vec2 vReflectionInfos;\\nuniform mat4 reflectionMatrix;\\nuniform vec3 vReflectionMicrosurfaceInfos;\\nuniform float fFovMultiplier;\\n#endif\\n#ifdef POINTSIZE\\nuniform float pointSize;\\n#endif\",\"backgroundFragmentDeclaration\":\" uniform vec4 vPrimaryColor;\\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\\nuniform vec4 vPrimaryColorShadow;\\n#endif\\nuniform float shadowLevel;\\nuniform float alpha;\\n#ifdef DIFFUSE\\nuniform vec2 vDiffuseInfos;\\n#endif\\n#ifdef REFLECTION\\nuniform vec2 vReflectionInfos;\\nuniform mat4 reflectionMatrix;\\nuniform vec3 vReflectionMicrosurfaceInfos;\\n#endif\\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\\nuniform vec3 vBackgroundCenter;\\n#endif\\n#ifdef REFLECTIONFRESNEL\\nuniform vec4 vReflectionControl;\\n#endif\\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\\nuniform mat4 view;\\n#endif\",\"backgroundUboDeclaration\":\"layout(std140,column_major) uniform;\\nuniform Material\\n{\\nuniform vec4 vPrimaryColor;\\nuniform vec4 vPrimaryColorShadow;\\nuniform vec2 vDiffuseInfos;\\nuniform vec2 vReflectionInfos;\\nuniform mat4 diffuseMatrix;\\nuniform mat4 reflectionMatrix;\\nuniform vec3 vReflectionMicrosurfaceInfos;\\nuniform float fFovMultiplier;\\nuniform float pointSize;\\nuniform float shadowLevel;\\nuniform float alpha;\\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\\nuniform vec3 vBackgroundCenter;\\n#endif\\n#ifdef REFLECTIONFRESNEL\\nuniform vec4 vReflectionControl;\\n#endif\\n};\\nuniform Scene {\\nmat4 viewProjection;\\nmat4 view;\\n};\"};\n \nvar globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);\nglobalObject[\"BABYLON\"] = BABYLON;\n//backwards compatibility\nif(typeof earcut !== 'undefined') {\n globalObject[\"Earcut\"] = {\n earcut: earcut\n };\n}\n\n return BABYLON;\n});\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../Tools/Gulp/node_modules/webpack/buildin/global.js */ \"../Tools/Gulp/node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack://BabylonViewer/../dist/preview_release/babylon.max.js?"); +eval("/* WEBPACK VAR INJECTION */(function(global) {\n\n(function universalModuleDefinition(root, factory) {\n var amdDependencies = [];\n var CANNON = root.CANNON || this.CANNON;\n var OIMO = root.OIMO || this.OIMO;\n var earcut = root.earcut || this.earcut;\n if(true) {\n try { CANNON = CANNON || __webpack_require__(/*! cannon */ \"cannon\"); } catch(e) {} \n try { OIMO = OIMO || __webpack_require__(/*! oimo */ \"oimo\"); } catch(e) {} \n try { earcut = earcut || __webpack_require__(/*! earcut */ \"earcut\"); } catch(e) {} \n\n module.exports = factory(CANNON,OIMO,earcut);\n } else {}\n})(this, function(CANNON,OIMO,earcut) {\n CANNON = CANNON || this.CANNON;\n OIMO = OIMO || this.OIMO;\n earcut = earcut || this.earcut;\n\nvar __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if(\"object\"==typeof Reflect&&\"function\"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};\nvar __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();\nvar BABYLON;\n(function (BABYLON) {\n /**\n * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.\n * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)\n */\n var EffectFallbacks = /** @class */ (function () {\n function EffectFallbacks() {\n this._defines = {};\n this._currentRank = 32;\n this._maxRank = -1;\n }\n /**\n * Removes the fallback from the bound mesh.\n */\n EffectFallbacks.prototype.unBindMesh = function () {\n this._mesh = null;\n };\n /**\n * Adds a fallback on the specified property.\n * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)\n * @param define The name of the define in the shader\n */\n EffectFallbacks.prototype.addFallback = function (rank, define) {\n if (!this._defines[rank]) {\n if (rank < this._currentRank) {\n this._currentRank = rank;\n }\n if (rank > this._maxRank) {\n this._maxRank = rank;\n }\n this._defines[rank] = new Array();\n }\n this._defines[rank].push(define);\n };\n /**\n * Sets the mesh to use CPU skinning when needing to fallback.\n * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)\n * @param mesh The mesh to use the fallbacks.\n */\n EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {\n this._mesh = mesh;\n if (rank < this._currentRank) {\n this._currentRank = rank;\n }\n if (rank > this._maxRank) {\n this._maxRank = rank;\n }\n };\n Object.defineProperty(EffectFallbacks.prototype, \"isMoreFallbacks\", {\n /**\n * Checks to see if more fallbacks are still availible.\n */\n get: function () {\n return this._currentRank <= this._maxRank;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Removes the defines that shoould be removed when falling back.\n * @param currentDefines defines the current define statements for the shader.\n * @param effect defines the current effect we try to compile\n * @returns The resulting defines with defines of the current rank removed.\n */\n EffectFallbacks.prototype.reduce = function (currentDefines, effect) {\n // First we try to switch to CPU skinning\n if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {\n this._mesh.computeBonesUsingShaders = false;\n currentDefines = currentDefines.replace(\"#define NUM_BONE_INFLUENCERS \" + this._mesh.numBoneInfluencers, \"#define NUM_BONE_INFLUENCERS 0\");\n effect._bonesComputationForcedToCPU = true;\n var scene = this._mesh.getScene();\n for (var index = 0; index < scene.meshes.length; index++) {\n var otherMesh = scene.meshes[index];\n if (!otherMesh.material) {\n continue;\n }\n if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {\n continue;\n }\n if (otherMesh.material.getEffect() === effect) {\n otherMesh.computeBonesUsingShaders = false;\n }\n else if (otherMesh.subMeshes) {\n for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n var subMeshEffect = subMesh.effect;\n if (subMeshEffect === effect) {\n otherMesh.computeBonesUsingShaders = false;\n break;\n }\n }\n }\n }\n }\n else {\n var currentFallbacks = this._defines[this._currentRank];\n if (currentFallbacks) {\n for (var index = 0; index < currentFallbacks.length; index++) {\n currentDefines = currentDefines.replace(\"#define \" + currentFallbacks[index], \"\");\n }\n }\n this._currentRank++;\n }\n return currentDefines;\n };\n return EffectFallbacks;\n }());\n BABYLON.EffectFallbacks = EffectFallbacks;\n /**\n * Options to be used when creating an effect.\n */\n var EffectCreationOptions = /** @class */ (function () {\n function EffectCreationOptions() {\n }\n return EffectCreationOptions;\n }());\n BABYLON.EffectCreationOptions = EffectCreationOptions;\n /**\n * Effect containing vertex and fragment shader that can be executed on an object.\n */\n var Effect = /** @class */ (function () {\n /**\n * Instantiates an effect.\n * An effect can be used to create/manage/execute vertex and fragment shaders.\n * @param baseName Name of the effect.\n * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.\n * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.\n * @param samplers List of sampler variables that will be passed to the shader.\n * @param engine Engine to be used to render the effect\n * @param defines Define statements to be added to the shader.\n * @param fallbacks Possible fallbacks for this effect to improve performance when needed.\n * @param onCompiled Callback that will be called when the shader is compiled.\n * @param onError Callback that will be called if an error occurs during shader compilation.\n * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})\n */\n function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {\n if (samplers === void 0) { samplers = null; }\n if (defines === void 0) { defines = null; }\n if (fallbacks === void 0) { fallbacks = null; }\n if (onCompiled === void 0) { onCompiled = null; }\n if (onError === void 0) { onError = null; }\n var _this = this;\n /**\n * Unique ID of the effect.\n */\n this.uniqueId = 0;\n /**\n * Observable that will be called when the shader is compiled.\n */\n this.onCompileObservable = new BABYLON.Observable();\n /**\n * Observable that will be called if an error occurs during shader compilation.\n */\n this.onErrorObservable = new BABYLON.Observable();\n /** @hidden */\n this._bonesComputationForcedToCPU = false;\n this._uniformBuffersNames = {};\n this._isReady = false;\n this._compilationError = \"\";\n this.name = baseName;\n if (attributesNamesOrOptions.attributes) {\n var options = attributesNamesOrOptions;\n this._engine = uniformsNamesOrEngine;\n this._attributesNames = options.attributes;\n this._uniformsNames = options.uniformsNames.concat(options.samplers);\n this._samplers = options.samplers.slice();\n this.defines = options.defines;\n this.onError = options.onError;\n this.onCompiled = options.onCompiled;\n this._fallbacks = options.fallbacks;\n this._indexParameters = options.indexParameters;\n this._transformFeedbackVaryings = options.transformFeedbackVaryings;\n if (options.uniformBuffersNames) {\n for (var i = 0; i < options.uniformBuffersNames.length; i++) {\n this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;\n }\n }\n }\n else {\n this._engine = engine;\n this.defines = defines;\n this._uniformsNames = uniformsNamesOrEngine.concat(samplers);\n this._samplers = samplers ? samplers.slice() : [];\n this._attributesNames = attributesNamesOrOptions;\n this.onError = onError;\n this.onCompiled = onCompiled;\n this._indexParameters = indexParameters;\n this._fallbacks = fallbacks;\n }\n this.uniqueId = Effect._uniqueIdSeed++;\n var vertexSource;\n var fragmentSource;\n if (baseName.vertexElement) {\n vertexSource = document.getElementById(baseName.vertexElement);\n if (!vertexSource) {\n vertexSource = baseName.vertexElement;\n }\n }\n else {\n vertexSource = baseName.vertex || baseName;\n }\n if (baseName.fragmentElement) {\n fragmentSource = document.getElementById(baseName.fragmentElement);\n if (!fragmentSource) {\n fragmentSource = baseName.fragmentElement;\n }\n }\n else {\n fragmentSource = baseName.fragment || baseName;\n }\n this._loadVertexShader(vertexSource, function (vertexCode) {\n _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {\n _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {\n _this._loadFragmentShader(fragmentSource, function (fragmentCode) {\n _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {\n _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {\n if (baseName) {\n var vertex = baseName.vertexElement || baseName.vertex || baseName;\n var fragment = baseName.fragmentElement || baseName.fragment || baseName;\n _this._vertexSourceCode = \"#define SHADER_NAME vertex:\" + vertex + \"\\n\" + migratedVertexCode;\n _this._fragmentSourceCode = \"#define SHADER_NAME fragment:\" + fragment + \"\\n\" + migratedFragmentCode;\n }\n else {\n _this._vertexSourceCode = migratedVertexCode;\n _this._fragmentSourceCode = migratedFragmentCode;\n }\n _this._prepareEffect();\n });\n });\n });\n });\n });\n });\n }\n Object.defineProperty(Effect.prototype, \"onBindObservable\", {\n /**\n * Observable that will be called when effect is bound.\n */\n get: function () {\n if (!this._onBindObservable) {\n this._onBindObservable = new BABYLON.Observable();\n }\n return this._onBindObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Effect.prototype, \"key\", {\n /**\n * Unique key for this effect\n */\n get: function () {\n return this._key;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * If the effect has been compiled and prepared.\n * @returns if the effect is compiled and prepared.\n */\n Effect.prototype.isReady = function () {\n return this._isReady;\n };\n /**\n * The engine the effect was initialized with.\n * @returns the engine.\n */\n Effect.prototype.getEngine = function () {\n return this._engine;\n };\n /**\n * The compiled webGL program for the effect\n * @returns the webGL program.\n */\n Effect.prototype.getProgram = function () {\n return this._program;\n };\n /**\n * The set of names of attribute variables for the shader.\n * @returns An array of attribute names.\n */\n Effect.prototype.getAttributesNames = function () {\n return this._attributesNames;\n };\n /**\n * Returns the attribute at the given index.\n * @param index The index of the attribute.\n * @returns The location of the attribute.\n */\n Effect.prototype.getAttributeLocation = function (index) {\n return this._attributes[index];\n };\n /**\n * Returns the attribute based on the name of the variable.\n * @param name of the attribute to look up.\n * @returns the attribute location.\n */\n Effect.prototype.getAttributeLocationByName = function (name) {\n var index = this._attributesNames.indexOf(name);\n return this._attributes[index];\n };\n /**\n * The number of attributes.\n * @returns the numnber of attributes.\n */\n Effect.prototype.getAttributesCount = function () {\n return this._attributes.length;\n };\n /**\n * Gets the index of a uniform variable.\n * @param uniformName of the uniform to look up.\n * @returns the index.\n */\n Effect.prototype.getUniformIndex = function (uniformName) {\n return this._uniformsNames.indexOf(uniformName);\n };\n /**\n * Returns the attribute based on the name of the variable.\n * @param uniformName of the uniform to look up.\n * @returns the location of the uniform.\n */\n Effect.prototype.getUniform = function (uniformName) {\n return this._uniforms[this._uniformsNames.indexOf(uniformName)];\n };\n /**\n * Returns an array of sampler variable names\n * @returns The array of sampler variable neames.\n */\n Effect.prototype.getSamplers = function () {\n return this._samplers;\n };\n /**\n * The error from the last compilation.\n * @returns the error string.\n */\n Effect.prototype.getCompilationError = function () {\n return this._compilationError;\n };\n /**\n * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.\n * @param func The callback to be used.\n */\n Effect.prototype.executeWhenCompiled = function (func) {\n if (this.isReady()) {\n func(this);\n return;\n }\n this.onCompileObservable.add(function (effect) {\n func(effect);\n });\n };\n /** @hidden */\n Effect.prototype._loadVertexShader = function (vertex, callback) {\n if (BABYLON.Tools.IsWindowObjectExist()) {\n // DOM element ?\n if (vertex instanceof HTMLElement) {\n var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);\n callback(vertexCode);\n return;\n }\n }\n // Base64 encoded ?\n if (vertex.substr(0, 7) === \"base64:\") {\n var vertexBinary = window.atob(vertex.substr(7));\n callback(vertexBinary);\n return;\n }\n // Is in local store ?\n if (Effect.ShadersStore[vertex + \"VertexShader\"]) {\n callback(Effect.ShadersStore[vertex + \"VertexShader\"]);\n return;\n }\n var vertexShaderUrl;\n if (vertex[0] === \".\" || vertex[0] === \"/\" || vertex.indexOf(\"http\") > -1) {\n vertexShaderUrl = vertex;\n }\n else {\n vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;\n }\n // Vertex shader\n this._engine._loadFile(vertexShaderUrl + \".vertex.fx\", callback);\n };\n /** @hidden */\n Effect.prototype._loadFragmentShader = function (fragment, callback) {\n if (BABYLON.Tools.IsWindowObjectExist()) {\n // DOM element ?\n if (fragment instanceof HTMLElement) {\n var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);\n callback(fragmentCode);\n return;\n }\n }\n // Base64 encoded ?\n if (fragment.substr(0, 7) === \"base64:\") {\n var fragmentBinary = window.atob(fragment.substr(7));\n callback(fragmentBinary);\n return;\n }\n // Is in local store ?\n if (Effect.ShadersStore[fragment + \"PixelShader\"]) {\n callback(Effect.ShadersStore[fragment + \"PixelShader\"]);\n return;\n }\n if (Effect.ShadersStore[fragment + \"FragmentShader\"]) {\n callback(Effect.ShadersStore[fragment + \"FragmentShader\"]);\n return;\n }\n var fragmentShaderUrl;\n if (fragment[0] === \".\" || fragment[0] === \"/\" || fragment.indexOf(\"http\") > -1) {\n fragmentShaderUrl = fragment;\n }\n else {\n fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;\n }\n // Fragment shader\n this._engine._loadFile(fragmentShaderUrl + \".fragment.fx\", callback);\n };\n /** @hidden */\n Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {\n // Rebuild shaders source code\n var shaderVersion = (this._engine.webGLVersion > 1) ? \"#version 300 es\\n#define WEBGL2 \\n\" : \"\";\n var prefix = shaderVersion + (defines ? defines + \"\\n\" : \"\");\n vertexCode = prefix + vertexCode;\n fragmentCode = prefix + fragmentCode;\n // Number lines of shaders source code\n var i = 2;\n var regex = /\\n/gm;\n var formattedVertexCode = \"\\n1\\t\" + vertexCode.replace(regex, function () { return \"\\n\" + (i++) + \"\\t\"; });\n i = 2;\n var formattedFragmentCode = \"\\n1\\t\" + fragmentCode.replace(regex, function () { return \"\\n\" + (i++) + \"\\t\"; });\n // Dump shaders name and formatted source code\n if (this.name.vertexElement) {\n BABYLON.Tools.Error(\"Vertex shader: \" + this.name.vertexElement + formattedVertexCode);\n BABYLON.Tools.Error(\"Fragment shader: \" + this.name.fragmentElement + formattedFragmentCode);\n }\n else if (this.name.vertex) {\n BABYLON.Tools.Error(\"Vertex shader: \" + this.name.vertex + formattedVertexCode);\n BABYLON.Tools.Error(\"Fragment shader: \" + this.name.fragment + formattedFragmentCode);\n }\n else {\n BABYLON.Tools.Error(\"Vertex shader: \" + this.name + formattedVertexCode);\n BABYLON.Tools.Error(\"Fragment shader: \" + this.name + formattedFragmentCode);\n }\n };\n ;\n Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {\n var preparedSourceCode = this._processPrecision(sourceCode);\n if (this._engine.webGLVersion == 1) {\n callback(preparedSourceCode);\n return;\n }\n // Already converted\n if (preparedSourceCode.indexOf(\"#version 3\") !== -1) {\n callback(preparedSourceCode.replace(\"#version 300 es\", \"\"));\n return;\n }\n var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;\n // Remove extensions \n // #extension GL_OES_standard_derivatives : enable\n // #extension GL_EXT_shader_texture_lod : enable\n // #extension GL_EXT_frag_depth : enable\n // #extension GL_EXT_draw_buffers : require\n var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;\n var result = preparedSourceCode.replace(regex, \"\");\n // Migrate to GLSL v300\n result = result.replace(/varying(?![\\n\\r])\\s/g, isFragment ? \"in \" : \"out \");\n result = result.replace(/attribute[ \\t]/g, \"in \");\n result = result.replace(/[ \\t]attribute/g, \" in\");\n if (isFragment) {\n result = result.replace(/texture2DLodEXT\\s*\\(/g, \"textureLod(\");\n result = result.replace(/textureCubeLodEXT\\s*\\(/g, \"textureLod(\");\n result = result.replace(/texture2D\\s*\\(/g, \"texture(\");\n result = result.replace(/textureCube\\s*\\(/g, \"texture(\");\n result = result.replace(/gl_FragDepthEXT/g, \"gl_FragDepth\");\n result = result.replace(/gl_FragColor/g, \"glFragColor\");\n result = result.replace(/gl_FragData/g, \"glFragData\");\n result = result.replace(/void\\s+?main\\s*\\(/g, (hasDrawBuffersExtension ? \"\" : \"out vec4 glFragColor;\\n\") + \"void main(\");\n }\n callback(result);\n };\n Effect.prototype._processIncludes = function (sourceCode, callback) {\n var _this = this;\n var regex = /#include<(.+)>(\\((.*)\\))*(\\[(.*)\\])*/g;\n var match = regex.exec(sourceCode);\n var returnValue = new String(sourceCode);\n while (match != null) {\n var includeFile = match[1];\n // Uniform declaration\n if (includeFile.indexOf(\"__decl__\") !== -1) {\n includeFile = includeFile.replace(/__decl__/, \"\");\n if (this._engine.supportsUniformBuffers) {\n includeFile = includeFile.replace(/Vertex/, \"Ubo\");\n includeFile = includeFile.replace(/Fragment/, \"Ubo\");\n }\n includeFile = includeFile + \"Declaration\";\n }\n if (Effect.IncludesShadersStore[includeFile]) {\n // Substitution\n var includeContent = Effect.IncludesShadersStore[includeFile];\n if (match[2]) {\n var splits = match[3].split(\",\");\n for (var index = 0; index < splits.length; index += 2) {\n var source = new RegExp(splits[index], \"g\");\n var dest = splits[index + 1];\n includeContent = includeContent.replace(source, dest);\n }\n }\n if (match[4]) {\n var indexString = match[5];\n if (indexString.indexOf(\"..\") !== -1) {\n var indexSplits = indexString.split(\"..\");\n var minIndex = parseInt(indexSplits[0]);\n var maxIndex = parseInt(indexSplits[1]);\n var sourceIncludeContent = includeContent.slice(0);\n includeContent = \"\";\n if (isNaN(maxIndex)) {\n maxIndex = this._indexParameters[indexSplits[1]];\n }\n for (var i = minIndex; i < maxIndex; i++) {\n if (!this._engine.supportsUniformBuffers) {\n // Ubo replacement\n sourceIncludeContent = sourceIncludeContent.replace(/light\\{X\\}.(\\w*)/g, function (str, p1) {\n return p1 + \"{X}\";\n });\n }\n includeContent += sourceIncludeContent.replace(/\\{X\\}/g, i.toString()) + \"\\n\";\n }\n }\n else {\n if (!this._engine.supportsUniformBuffers) {\n // Ubo replacement\n includeContent = includeContent.replace(/light\\{X\\}.(\\w*)/g, function (str, p1) {\n return p1 + \"{X}\";\n });\n }\n includeContent = includeContent.replace(/\\{X\\}/g, indexString);\n }\n }\n // Replace\n returnValue = returnValue.replace(match[0], includeContent);\n }\n else {\n var includeShaderUrl = BABYLON.Engine.ShadersRepository + \"ShadersInclude/\" + includeFile + \".fx\";\n this._engine._loadFile(includeShaderUrl, function (fileContent) {\n Effect.IncludesShadersStore[includeFile] = fileContent;\n _this._processIncludes(returnValue, callback);\n });\n return;\n }\n match = regex.exec(sourceCode);\n }\n callback(returnValue);\n };\n Effect.prototype._processPrecision = function (source) {\n if (source.indexOf(\"precision highp float\") === -1) {\n if (!this._engine.getCaps().highPrecisionShaderSupported) {\n source = \"precision mediump float;\\n\" + source;\n }\n else {\n source = \"precision highp float;\\n\" + source;\n }\n }\n else {\n if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump\n source = source.replace(\"precision highp float\", \"precision mediump float\");\n }\n }\n return source;\n };\n /**\n * Recompiles the webGL program\n * @param vertexSourceCode The source code for the vertex shader.\n * @param fragmentSourceCode The source code for the fragment shader.\n * @param onCompiled Callback called when completed.\n * @param onError Callback called on error.\n */\n Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {\n var _this = this;\n this._isReady = false;\n this._vertexSourceCodeOverride = vertexSourceCode;\n this._fragmentSourceCodeOverride = fragmentSourceCode;\n this.onError = function (effect, error) {\n if (onError) {\n onError(error);\n }\n };\n this.onCompiled = function () {\n var scenes = _this.getEngine().scenes;\n for (var i = 0; i < scenes.length; i++) {\n scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n }\n if (onCompiled) {\n onCompiled(_this._program);\n }\n };\n this._fallbacks = null;\n this._prepareEffect();\n };\n /**\n * Gets the uniform locations of the the specified variable names\n * @param names THe names of the variables to lookup.\n * @returns Array of locations in the same order as variable names.\n */\n Effect.prototype.getSpecificUniformLocations = function (names) {\n var engine = this._engine;\n return engine.getUniforms(this._program, names);\n };\n /**\n * Prepares the effect\n */\n Effect.prototype._prepareEffect = function () {\n var attributesNames = this._attributesNames;\n var defines = this.defines;\n var fallbacks = this._fallbacks;\n this._valueCache = {};\n var previousProgram = this._program;\n try {\n var engine = this._engine;\n if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {\n this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);\n }\n else {\n this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);\n }\n this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);\n if (engine.supportsUniformBuffers) {\n for (var name in this._uniformBuffersNames) {\n this.bindUniformBlock(name, this._uniformBuffersNames[name]);\n }\n }\n this._uniforms = engine.getUniforms(this._program, this._uniformsNames);\n this._attributes = engine.getAttributes(this._program, attributesNames);\n var index;\n for (index = 0; index < this._samplers.length; index++) {\n var sampler = this.getUniform(this._samplers[index]);\n if (sampler == null) {\n this._samplers.splice(index, 1);\n index--;\n }\n }\n engine.bindSamplers(this);\n this._compilationError = \"\";\n this._isReady = true;\n if (this.onCompiled) {\n this.onCompiled(this);\n }\n this.onCompileObservable.notifyObservers(this);\n this.onCompileObservable.clear();\n // Unbind mesh reference in fallbacks\n if (this._fallbacks) {\n this._fallbacks.unBindMesh();\n }\n if (previousProgram) {\n this.getEngine()._deleteProgram(previousProgram);\n }\n }\n catch (e) {\n this._compilationError = e.message;\n // Let's go through fallbacks then\n BABYLON.Tools.Error(\"Unable to compile effect:\");\n BABYLON.Tools.Error(\"Uniforms: \" + this._uniformsNames.map(function (uniform) {\n return \" \" + uniform;\n }));\n BABYLON.Tools.Error(\"Attributes: \" + attributesNames.map(function (attribute) {\n return \" \" + attribute;\n }));\n BABYLON.Tools.Error(\"Error: \" + this._compilationError);\n if (previousProgram) {\n this._program = previousProgram;\n this._isReady = true;\n if (this.onError) {\n this.onError(this, this._compilationError);\n }\n this.onErrorObservable.notifyObservers(this);\n }\n if (fallbacks && fallbacks.isMoreFallbacks) {\n BABYLON.Tools.Error(\"Trying next fallback.\");\n this.defines = fallbacks.reduce(this.defines, this);\n this._prepareEffect();\n }\n else { // Sorry we did everything we can\n if (this.onError) {\n this.onError(this, this._compilationError);\n }\n this.onErrorObservable.notifyObservers(this);\n this.onErrorObservable.clear();\n // Unbind mesh reference in fallbacks\n if (this._fallbacks) {\n this._fallbacks.unBindMesh();\n }\n }\n }\n };\n Object.defineProperty(Effect.prototype, \"isSupported\", {\n /**\n * Checks if the effect is supported. (Must be called after compilation)\n */\n get: function () {\n return this._compilationError === \"\";\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Binds a texture to the engine to be used as output of the shader.\n * @param channel Name of the output variable.\n * @param texture Texture to bind.\n */\n Effect.prototype._bindTexture = function (channel, texture) {\n this._engine._bindTexture(this._samplers.indexOf(channel), texture);\n };\n /**\n * Sets a texture on the engine to be used in the shader.\n * @param channel Name of the sampler variable.\n * @param texture Texture to set.\n */\n Effect.prototype.setTexture = function (channel, texture) {\n this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);\n };\n /**\n * Sets a depth stencil texture from a render target on the engine to be used in the shader.\n * @param channel Name of the sampler variable.\n * @param texture Texture to set.\n */\n Effect.prototype.setDepthStencilTexture = function (channel, texture) {\n this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);\n };\n /**\n * Sets an array of textures on the engine to be used in the shader.\n * @param channel Name of the variable.\n * @param textures Textures to set.\n */\n Effect.prototype.setTextureArray = function (channel, textures) {\n if (this._samplers.indexOf(channel + \"Ex\") === -1) {\n var initialPos = this._samplers.indexOf(channel);\n for (var index = 1; index < textures.length; index++) {\n this._samplers.splice(initialPos + index, 0, channel + \"Ex\");\n }\n }\n this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);\n };\n /**\n * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)\n * @param channel Name of the sampler variable.\n * @param postProcess Post process to get the input texture from.\n */\n Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {\n this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);\n };\n /**\n * (Warning! setTextureFromPostProcessOutput may be desired instead)\n * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)\n * @param channel Name of the sampler variable.\n * @param postProcess Post process to get the output texture from.\n */\n Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {\n this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);\n };\n /** @hidden */\n Effect.prototype._cacheMatrix = function (uniformName, matrix) {\n var cache = this._valueCache[uniformName];\n var flag = matrix.updateFlag;\n if (cache !== undefined && cache === flag) {\n return false;\n }\n this._valueCache[uniformName] = flag;\n return true;\n };\n /** @hidden */\n Effect.prototype._cacheFloat2 = function (uniformName, x, y) {\n var cache = this._valueCache[uniformName];\n if (!cache) {\n cache = [x, y];\n this._valueCache[uniformName] = cache;\n return true;\n }\n var changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n return changed;\n };\n /** @hidden */\n Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {\n var cache = this._valueCache[uniformName];\n if (!cache) {\n cache = [x, y, z];\n this._valueCache[uniformName] = cache;\n return true;\n }\n var changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n if (cache[2] !== z) {\n cache[2] = z;\n changed = true;\n }\n return changed;\n };\n /** @hidden */\n Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {\n var cache = this._valueCache[uniformName];\n if (!cache) {\n cache = [x, y, z, w];\n this._valueCache[uniformName] = cache;\n return true;\n }\n var changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n if (cache[2] !== z) {\n cache[2] = z;\n changed = true;\n }\n if (cache[3] !== w) {\n cache[3] = w;\n changed = true;\n }\n return changed;\n };\n /**\n * Binds a buffer to a uniform.\n * @param buffer Buffer to bind.\n * @param name Name of the uniform variable to bind to.\n */\n Effect.prototype.bindUniformBuffer = function (buffer, name) {\n var bufferName = this._uniformBuffersNames[name];\n if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {\n return;\n }\n Effect._baseCache[bufferName] = buffer;\n this._engine.bindUniformBufferBase(buffer, bufferName);\n };\n /**\n * Binds block to a uniform.\n * @param blockName Name of the block to bind.\n * @param index Index to bind.\n */\n Effect.prototype.bindUniformBlock = function (blockName, index) {\n this._engine.bindUniformBlock(this._program, blockName, index);\n };\n /**\n * Sets an interger value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n * @returns this effect.\n */\n Effect.prototype.setInt = function (uniformName, value) {\n var cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value)\n return this;\n this._valueCache[uniformName] = value;\n this._engine.setInt(this.getUniform(uniformName), value);\n return this;\n };\n /**\n * Sets an int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setIntArray = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setIntArray2 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray2(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setIntArray3 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray3(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setIntArray4 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray4(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an float array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setFloatArray = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setFloatArray2 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray2(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setFloatArray3 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray3(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setFloatArray4 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray4(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setArray = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setArray2 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray2(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setArray3 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray3(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n Effect.prototype.setArray4 = function (uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray4(this.getUniform(uniformName), array);\n return this;\n };\n /**\n * Sets matrices on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrices matrices to be set.\n * @returns this effect.\n */\n Effect.prototype.setMatrices = function (uniformName, matrices) {\n if (!matrices) {\n return this;\n }\n this._valueCache[uniformName] = null;\n this._engine.setMatrices(this.getUniform(uniformName), matrices);\n return this;\n };\n /**\n * Sets matrix on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n * @returns this effect.\n */\n Effect.prototype.setMatrix = function (uniformName, matrix) {\n if (this._cacheMatrix(uniformName, matrix)) {\n this._engine.setMatrix(this.getUniform(uniformName), matrix);\n }\n return this;\n };\n /**\n * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n * @returns this effect.\n */\n Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {\n this._valueCache[uniformName] = null;\n this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);\n return this;\n };\n /**\n * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n * @returns this effect.\n */\n Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {\n this._valueCache[uniformName] = null;\n this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);\n return this;\n };\n /**\n * Sets a float on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value value to be set.\n * @returns this effect.\n */\n Effect.prototype.setFloat = function (uniformName, value) {\n var cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value)\n return this;\n this._valueCache[uniformName] = value;\n this._engine.setFloat(this.getUniform(uniformName), value);\n return this;\n };\n /**\n * Sets a boolean on a uniform variable.\n * @param uniformName Name of the variable.\n * @param bool value to be set.\n * @returns this effect.\n */\n Effect.prototype.setBool = function (uniformName, bool) {\n var cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === bool)\n return this;\n this._valueCache[uniformName] = bool;\n this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);\n return this;\n };\n /**\n * Sets a Vector2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector2 vector2 to be set.\n * @returns this effect.\n */\n Effect.prototype.setVector2 = function (uniformName, vector2) {\n if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {\n this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);\n }\n return this;\n };\n /**\n * Sets a float2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float2.\n * @param y Second float in float2.\n * @returns this effect.\n */\n Effect.prototype.setFloat2 = function (uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n this._engine.setFloat2(this.getUniform(uniformName), x, y);\n }\n return this;\n };\n /**\n * Sets a Vector3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector3 Value to be set.\n * @returns this effect.\n */\n Effect.prototype.setVector3 = function (uniformName, vector3) {\n if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {\n this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);\n }\n return this;\n };\n /**\n * Sets a float3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float3.\n * @param y Second float in float3.\n * @param z Third float in float3.\n * @returns this effect.\n */\n Effect.prototype.setFloat3 = function (uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n this._engine.setFloat3(this.getUniform(uniformName), x, y, z);\n }\n return this;\n };\n /**\n * Sets a Vector4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector4 Value to be set.\n * @returns this effect.\n */\n Effect.prototype.setVector4 = function (uniformName, vector4) {\n if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {\n this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);\n }\n return this;\n };\n /**\n * Sets a float4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float4.\n * @param y Second float in float4.\n * @param z Third float in float4.\n * @param w Fourth float in float4.\n * @returns this effect.\n */\n Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);\n }\n return this;\n };\n /**\n * Sets a Color3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @returns this effect.\n */\n Effect.prototype.setColor3 = function (uniformName, color3) {\n if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {\n this._engine.setColor3(this.getUniform(uniformName), color3);\n }\n return this;\n };\n /**\n * Sets a Color4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @param alpha Alpha value to be set.\n * @returns this effect.\n */\n Effect.prototype.setColor4 = function (uniformName, color3, alpha) {\n if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {\n this._engine.setColor4(this.getUniform(uniformName), color3, alpha);\n }\n return this;\n };\n /**\n * Sets a Color4 on a uniform variable\n * @param uniformName defines the name of the variable\n * @param color4 defines the value to be set\n * @returns this effect.\n */\n Effect.prototype.setDirectColor4 = function (uniformName, color4) {\n if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {\n this._engine.setDirectColor4(this.getUniform(uniformName), color4);\n }\n return this;\n };\n /**\n * This function will add a new shader to the shader store\n * @param name the name of the shader\n * @param pixelShader optional pixel shader content\n * @param vertexShader optional vertex shader content\n */\n Effect.RegisterShader = function (name, pixelShader, vertexShader) {\n if (pixelShader) {\n Effect.ShadersStore[name + \"PixelShader\"] = pixelShader;\n }\n if (vertexShader) {\n Effect.ShadersStore[name + \"VertexShader\"] = vertexShader;\n }\n };\n /**\n * Resets the cache of effects.\n */\n Effect.ResetCache = function () {\n Effect._baseCache = {};\n };\n Effect._uniqueIdSeed = 0;\n Effect._baseCache = {};\n /**\n * Store of each shader (The can be looked up using effect.key)\n */\n Effect.ShadersStore = {};\n /**\n * Store of each included file for a shader (The can be looked up using effect.key)\n */\n Effect.IncludesShadersStore = {};\n return Effect;\n }());\n BABYLON.Effect = Effect;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.effect.js.map\n\n\n\n//# sourceMappingURL=babylon.types.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var KeyboardEventTypes = /** @class */ (function () {\n function KeyboardEventTypes() {\n }\n Object.defineProperty(KeyboardEventTypes, \"KEYDOWN\", {\n get: function () {\n return KeyboardEventTypes._KEYDOWN;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(KeyboardEventTypes, \"KEYUP\", {\n get: function () {\n return KeyboardEventTypes._KEYUP;\n },\n enumerable: true,\n configurable: true\n });\n KeyboardEventTypes._KEYDOWN = 0x01;\n KeyboardEventTypes._KEYUP = 0x02;\n return KeyboardEventTypes;\n }());\n BABYLON.KeyboardEventTypes = KeyboardEventTypes;\n var KeyboardInfo = /** @class */ (function () {\n function KeyboardInfo(type, event) {\n this.type = type;\n this.event = event;\n }\n return KeyboardInfo;\n }());\n BABYLON.KeyboardInfo = KeyboardInfo;\n /**\n * This class is used to store keyboard related info for the onPreKeyboardObservable event.\n * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable\n */\n var KeyboardInfoPre = /** @class */ (function (_super) {\n __extends(KeyboardInfoPre, _super);\n function KeyboardInfoPre(type, event) {\n var _this = _super.call(this, type, event) || this;\n _this.skipOnPointerObservable = false;\n return _this;\n }\n return KeyboardInfoPre;\n }(KeyboardInfo));\n BABYLON.KeyboardInfoPre = KeyboardInfoPre;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.keyboardEvents.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var PointerEventTypes = /** @class */ (function () {\n function PointerEventTypes() {\n }\n Object.defineProperty(PointerEventTypes, \"POINTERDOWN\", {\n get: function () {\n return PointerEventTypes._POINTERDOWN;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointerEventTypes, \"POINTERUP\", {\n get: function () {\n return PointerEventTypes._POINTERUP;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointerEventTypes, \"POINTERMOVE\", {\n get: function () {\n return PointerEventTypes._POINTERMOVE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointerEventTypes, \"POINTERWHEEL\", {\n get: function () {\n return PointerEventTypes._POINTERWHEEL;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointerEventTypes, \"POINTERPICK\", {\n get: function () {\n return PointerEventTypes._POINTERPICK;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointerEventTypes, \"POINTERTAP\", {\n get: function () {\n return PointerEventTypes._POINTERTAP;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointerEventTypes, \"POINTERDOUBLETAP\", {\n get: function () {\n return PointerEventTypes._POINTERDOUBLETAP;\n },\n enumerable: true,\n configurable: true\n });\n PointerEventTypes._POINTERDOWN = 0x01;\n PointerEventTypes._POINTERUP = 0x02;\n PointerEventTypes._POINTERMOVE = 0x04;\n PointerEventTypes._POINTERWHEEL = 0x08;\n PointerEventTypes._POINTERPICK = 0x10;\n PointerEventTypes._POINTERTAP = 0x20;\n PointerEventTypes._POINTERDOUBLETAP = 0x40;\n return PointerEventTypes;\n }());\n BABYLON.PointerEventTypes = PointerEventTypes;\n var PointerInfoBase = /** @class */ (function () {\n function PointerInfoBase(type, event) {\n this.type = type;\n this.event = event;\n }\n return PointerInfoBase;\n }());\n BABYLON.PointerInfoBase = PointerInfoBase;\n /**\n * This class is used to store pointer related info for the onPrePointerObservable event.\n * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable\n */\n var PointerInfoPre = /** @class */ (function (_super) {\n __extends(PointerInfoPre, _super);\n function PointerInfoPre(type, event, localX, localY) {\n var _this = _super.call(this, type, event) || this;\n /**\n * Ray from a pointer if availible (eg. 6dof controller)\n */\n _this.ray = null;\n _this.skipOnPointerObservable = false;\n _this.localPosition = new BABYLON.Vector2(localX, localY);\n return _this;\n }\n return PointerInfoPre;\n }(PointerInfoBase));\n BABYLON.PointerInfoPre = PointerInfoPre;\n /**\n * This type contains all the data related to a pointer event in Babylon.js.\n * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.\n */\n var PointerInfo = /** @class */ (function (_super) {\n __extends(PointerInfo, _super);\n function PointerInfo(type, event, pickInfo) {\n var _this = _super.call(this, type, event) || this;\n _this.pickInfo = pickInfo;\n return _this;\n }\n return PointerInfo;\n }(PointerInfoBase));\n BABYLON.PointerInfo = PointerInfo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pointerEvents.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.ToGammaSpace = 1 / 2.2;\n BABYLON.ToLinearSpace = 2.2;\n BABYLON.Epsilon = 0.001;\n /**\n * Class used to hold a RBG color\n */\n var Color3 = /** @class */ (function () {\n /**\n * Creates a new Color3 object from red, green, blue values, all between 0 and 1\n * @param r defines the red component (between 0 and 1, default is 0)\n * @param g defines the green component (between 0 and 1, default is 0)\n * @param b defines the blue component (between 0 and 1, default is 0)\n */\n function Color3(\n /**\n * Defines the red component (between 0 and 1, default is 0)\n */\n r, \n /**\n * Defines the green component (between 0 and 1, default is 0)\n */\n g, \n /**\n * Defines the blue component (between 0 and 1, default is 0)\n */\n b) {\n if (r === void 0) { r = 0; }\n if (g === void 0) { g = 0; }\n if (b === void 0) { b = 0; }\n this.r = r;\n this.g = g;\n this.b = b;\n }\n /**\n * Creates a string with the Color3 current values\n * @returns the string representation of the Color3 object\n */\n Color3.prototype.toString = function () {\n return \"{R: \" + this.r + \" G:\" + this.g + \" B:\" + this.b + \"}\";\n };\n /**\n * Returns the string \"Color3\"\n * @returns \"Color3\"\n */\n Color3.prototype.getClassName = function () {\n return \"Color3\";\n };\n /**\n * Compute the Color3 hash code\n * @returns an unique number that can be used to hash Color3 objects\n */\n Color3.prototype.getHashCode = function () {\n var hash = this.r || 0;\n hash = (hash * 397) ^ (this.g || 0);\n hash = (hash * 397) ^ (this.b || 0);\n return hash;\n };\n // Operators\n /**\n * Stores in the given array from the given starting index the red, green, blue values as successive elements\n * @param array defines the array where to store the r,g,b components\n * @param index defines an optional index in the target array to define where to start storing values\n * @returns the current Color3 object\n */\n Color3.prototype.toArray = function (array, index) {\n if (index === undefined) {\n index = 0;\n }\n array[index] = this.r;\n array[index + 1] = this.g;\n array[index + 2] = this.b;\n return this;\n };\n /**\n * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha\n * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)\n * @returns a new {BABYLON.Color4} object\n */\n Color3.prototype.toColor4 = function (alpha) {\n if (alpha === void 0) { alpha = 1; }\n return new Color4(this.r, this.g, this.b, alpha);\n };\n /**\n * Returns a new array populated with 3 numeric elements : red, green and blue values\n * @returns the new array\n */\n Color3.prototype.asArray = function () {\n var result = new Array();\n this.toArray(result, 0);\n return result;\n };\n /**\n * Returns the luminance value\n * @returns a float value\n */\n Color3.prototype.toLuminance = function () {\n return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;\n };\n /**\n * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object\n * @param otherColor defines the second operand\n * @returns the new Color3 object\n */\n Color3.prototype.multiply = function (otherColor) {\n return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);\n };\n /**\n * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object \"result\"\n * @param otherColor defines the second operand\n * @param result defines the Color3 object where to store the result\n * @returns the current Color3\n */\n Color3.prototype.multiplyToRef = function (otherColor, result) {\n result.r = this.r * otherColor.r;\n result.g = this.g * otherColor.g;\n result.b = this.b * otherColor.b;\n return this;\n };\n /**\n * Determines equality between Color3 objects\n * @param otherColor defines the second operand\n * @returns true if the rgb values are equal to the given ones\n */\n Color3.prototype.equals = function (otherColor) {\n return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;\n };\n /**\n * Determines equality between the current Color3 object and a set of r,b,g values\n * @param r defines the red component to check\n * @param g defines the green component to check\n * @param b defines the blue component to check\n * @returns true if the rgb values are equal to the given ones\n */\n Color3.prototype.equalsFloats = function (r, g, b) {\n return this.r === r && this.g === g && this.b === b;\n };\n /**\n * Multiplies in place each rgb value by scale\n * @param scale defines the scaling factor\n * @returns the updated Color3\n */\n Color3.prototype.scale = function (scale) {\n return new Color3(this.r * scale, this.g * scale, this.b * scale);\n };\n /**\n * Multiplies the rgb values by scale and stores the result into \"result\"\n * @param scale defines the scaling factor\n * @param result defines the Color3 object where to store the result\n * @returns the unmodified current Color3\n */\n Color3.prototype.scaleToRef = function (scale, result) {\n result.r = this.r * scale;\n result.g = this.g * scale;\n result.b = this.b * scale;\n return this;\n };\n /**\n * Scale the current Color3 values by a factor and add the result to a given Color3\n * @param scale defines the scale factor\n * @param result defines color to store the result into\n * @returns the unmodified current Color3\n */\n Color3.prototype.scaleAndAddToRef = function (scale, result) {\n result.r += this.r * scale;\n result.g += this.g * scale;\n result.b += this.b * scale;\n return this;\n };\n /**\n * Clamps the rgb values by the min and max values and stores the result into \"result\"\n * @param min defines minimum clamping value (default is 0)\n * @param max defines maximum clamping value (default is 1)\n * @param result defines color to store the result into\n * @returns the original Color3\n */\n Color3.prototype.clampToRef = function (min, max, result) {\n if (min === void 0) { min = 0; }\n if (max === void 0) { max = 1; }\n result.r = BABYLON.Scalar.Clamp(this.r, min, max);\n result.g = BABYLON.Scalar.Clamp(this.g, min, max);\n result.b = BABYLON.Scalar.Clamp(this.b, min, max);\n return this;\n };\n /**\n * Creates a new Color3 set with the added values of the current Color3 and of the given one\n * @param otherColor defines the second operand\n * @returns the new Color3\n */\n Color3.prototype.add = function (otherColor) {\n return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);\n };\n /**\n * Stores the result of the addition of the current Color3 and given one rgb values into \"result\"\n * @param otherColor defines the second operand\n * @param result defines Color3 object to store the result into\n * @returns the unmodified current Color3\n */\n Color3.prototype.addToRef = function (otherColor, result) {\n result.r = this.r + otherColor.r;\n result.g = this.g + otherColor.g;\n result.b = this.b + otherColor.b;\n return this;\n };\n /**\n * Returns a new Color3 set with the subtracted values of the given one from the current Color3\n * @param otherColor defines the second operand\n * @returns the new Color3\n */\n Color3.prototype.subtract = function (otherColor) {\n return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);\n };\n /**\n * Stores the result of the subtraction of given one from the current Color3 rgb values into \"result\"\n * @param otherColor defines the second operand\n * @param result defines Color3 object to store the result into\n * @returns the unmodified current Color3\n */\n Color3.prototype.subtractToRef = function (otherColor, result) {\n result.r = this.r - otherColor.r;\n result.g = this.g - otherColor.g;\n result.b = this.b - otherColor.b;\n return this;\n };\n /**\n * Copy the current object\n * @returns a new Color3 copied the current one\n */\n Color3.prototype.clone = function () {\n return new Color3(this.r, this.g, this.b);\n };\n /**\n * Copies the rgb values from the source in the current Color3\n * @param source defines the source Color3 object\n * @returns the updated Color3 object\n */\n Color3.prototype.copyFrom = function (source) {\n this.r = source.r;\n this.g = source.g;\n this.b = source.b;\n return this;\n };\n /**\n * Updates the Color3 rgb values from the given floats\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @returns the current Color3 object\n */\n Color3.prototype.copyFromFloats = function (r, g, b) {\n this.r = r;\n this.g = g;\n this.b = b;\n return this;\n };\n /**\n * Updates the Color3 rgb values from the given floats\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @returns the current Color3 object\n */\n Color3.prototype.set = function (r, g, b) {\n return this.copyFromFloats(r, g, b);\n };\n /**\n * Compute the Color3 hexadecimal code as a string\n * @returns a string containing the hexadecimal representation of the Color3 object\n */\n Color3.prototype.toHexString = function () {\n var intR = (this.r * 255) | 0;\n var intG = (this.g * 255) | 0;\n var intB = (this.b * 255) | 0;\n return \"#\" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);\n };\n /**\n * Computes a new Color3 converted from the current one to linear space\n * @returns a new Color3 object\n */\n Color3.prototype.toLinearSpace = function () {\n var convertedColor = new Color3();\n this.toLinearSpaceToRef(convertedColor);\n return convertedColor;\n };\n /**\n * Converts the Color3 values to linear space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color3 object where to store the linear space version\n * @returns the unmodified Color3\n */\n Color3.prototype.toLinearSpaceToRef = function (convertedColor) {\n convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);\n convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);\n convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);\n return this;\n };\n /**\n * Computes a new Color3 converted from the current one to gamma space\n * @returns a new Color3 object\n */\n Color3.prototype.toGammaSpace = function () {\n var convertedColor = new Color3();\n this.toGammaSpaceToRef(convertedColor);\n return convertedColor;\n };\n /**\n * Converts the Color3 values to gamma space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color3 object where to store the gamma space version\n * @returns the unmodified Color3\n */\n Color3.prototype.toGammaSpaceToRef = function (convertedColor) {\n convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);\n convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);\n convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);\n return this;\n };\n // Statics\n /**\n * Creates a new Color3 from the string containing valid hexadecimal values\n * @param hex defines a string containing valid hexadecimal values\n * @returns a new Color3 object\n */\n Color3.FromHexString = function (hex) {\n if (hex.substring(0, 1) !== \"#\" || hex.length !== 7) {\n return new Color3(0, 0, 0);\n }\n var r = parseInt(hex.substring(1, 3), 16);\n var g = parseInt(hex.substring(3, 5), 16);\n var b = parseInt(hex.substring(5, 7), 16);\n return Color3.FromInts(r, g, b);\n };\n /**\n * Creates a new Vector3 from the starting index of the given array\n * @param array defines the source array\n * @param offset defines an offset in the source array\n * @returns a new Color3 object\n */\n Color3.FromArray = function (array, offset) {\n if (offset === void 0) { offset = 0; }\n return new Color3(array[offset], array[offset + 1], array[offset + 2]);\n };\n /**\n * Creates a new Color3 from integer values (< 256)\n * @param r defines the red component to read from (value between 0 and 255)\n * @param g defines the green component to read from (value between 0 and 255)\n * @param b defines the blue component to read from (value between 0 and 255)\n * @returns a new Color3 object\n */\n Color3.FromInts = function (r, g, b) {\n return new Color3(r / 255.0, g / 255.0, b / 255.0);\n };\n /**\n * Creates a new Color3 with values linearly interpolated of \"amount\" between the start Color3 and the end Color3\n * @param start defines the start Color3 value\n * @param end defines the end Color3 value\n * @param amount defines the gradient value between start and end\n * @returns a new Color3 object\n */\n Color3.Lerp = function (start, end, amount) {\n var r = start.r + ((end.r - start.r) * amount);\n var g = start.g + ((end.g - start.g) * amount);\n var b = start.b + ((end.b - start.b) * amount);\n return new Color3(r, g, b);\n };\n /**\n * Returns a Color3 value containing a red color\n * @returns a new Color3 object\n */\n Color3.Red = function () { return new Color3(1, 0, 0); };\n /**\n * Returns a Color3 value containing a green color\n * @returns a new Color3 object\n */\n Color3.Green = function () { return new Color3(0, 1, 0); };\n /**\n * Returns a Color3 value containing a blue color\n * @returns a new Color3 object\n */\n Color3.Blue = function () { return new Color3(0, 0, 1); };\n /**\n * Returns a Color3 value containing a black color\n * @returns a new Color3 object\n */\n Color3.Black = function () { return new Color3(0, 0, 0); };\n /**\n * Returns a Color3 value containing a white color\n * @returns a new Color3 object\n */\n Color3.White = function () { return new Color3(1, 1, 1); };\n /**\n * Returns a Color3 value containing a purple color\n * @returns a new Color3 object\n */\n Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };\n /**\n * Returns a Color3 value containing a magenta color\n * @returns a new Color3 object\n */\n Color3.Magenta = function () { return new Color3(1, 0, 1); };\n /**\n * Returns a Color3 value containing a yellow color\n * @returns a new Color3 object\n */\n Color3.Yellow = function () { return new Color3(1, 1, 0); };\n /**\n * Returns a Color3 value containing a gray color\n * @returns a new Color3 object\n */\n Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };\n /**\n * Returns a Color3 value containing a teal color\n * @returns a new Color3 object\n */\n Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };\n /**\n * Returns a Color3 value containing a random color\n * @returns a new Color3 object\n */\n Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };\n return Color3;\n }());\n BABYLON.Color3 = Color3;\n /**\n * Class used to hold a RBGA color\n */\n var Color4 = /** @class */ (function () {\n /**\n * Creates a new Color4 object from red, green, blue values, all between 0 and 1\n * @param r defines the red component (between 0 and 1, default is 0)\n * @param g defines the green component (between 0 and 1, default is 0)\n * @param b defines the blue component (between 0 and 1, default is 0)\n * @param a defines the alpha component (between 0 and 1, default is 1)\n */\n function Color4(\n /**\n * Defines the red component (between 0 and 1, default is 0)\n */\n r, \n /**\n * Defines the green component (between 0 and 1, default is 0)\n */\n g, \n /**\n * Defines the blue component (between 0 and 1, default is 0)\n */\n b, \n /**\n * Defines the alpha component (between 0 and 1, default is 1)\n */\n a) {\n if (r === void 0) { r = 0; }\n if (g === void 0) { g = 0; }\n if (b === void 0) { b = 0; }\n if (a === void 0) { a = 1; }\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n }\n // Operators\n /**\n * Adds in place the given Color4 values to the current Color4 object\n * @param right defines the second operand\n * @returns the current updated Color4 object\n */\n Color4.prototype.addInPlace = function (right) {\n this.r += right.r;\n this.g += right.g;\n this.b += right.b;\n this.a += right.a;\n return this;\n };\n /**\n * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values\n * @returns the new array\n */\n Color4.prototype.asArray = function () {\n var result = new Array();\n this.toArray(result, 0);\n return result;\n };\n /**\n * Stores from the starting index in the given array the Color4 successive values\n * @param array defines the array where to store the r,g,b components\n * @param index defines an optional index in the target array to define where to start storing values\n * @returns the current Color4 object\n */\n Color4.prototype.toArray = function (array, index) {\n if (index === undefined) {\n index = 0;\n }\n array[index] = this.r;\n array[index + 1] = this.g;\n array[index + 2] = this.b;\n array[index + 3] = this.a;\n return this;\n };\n /**\n * Creates a new Color4 set with the added values of the current Color4 and of the given one\n * @param right defines the second operand\n * @returns a new Color4 object\n */\n Color4.prototype.add = function (right) {\n return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);\n };\n /**\n * Creates a new Color4 set with the subtracted values of the given one from the current Color4\n * @param right defines the second operand\n * @returns a new Color4 object\n */\n Color4.prototype.subtract = function (right) {\n return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);\n };\n /**\n * Subtracts the given ones from the current Color4 values and stores the results in \"result\"\n * @param right defines the second operand\n * @param result defines the Color4 object where to store the result\n * @returns the current Color4 object\n */\n Color4.prototype.subtractToRef = function (right, result) {\n result.r = this.r - right.r;\n result.g = this.g - right.g;\n result.b = this.b - right.b;\n result.a = this.a - right.a;\n return this;\n };\n /**\n * Creates a new Color4 with the current Color4 values multiplied by scale\n * @param scale defines the scaling factor to apply\n * @returns a new Color4 object\n */\n Color4.prototype.scale = function (scale) {\n return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);\n };\n /**\n * Multiplies the current Color4 values by scale and stores the result in \"result\"\n * @param scale defines the scaling factor to apply\n * @param result defines the Color4 object where to store the result\n * @returns the current unmodified Color4\n */\n Color4.prototype.scaleToRef = function (scale, result) {\n result.r = this.r * scale;\n result.g = this.g * scale;\n result.b = this.b * scale;\n result.a = this.a * scale;\n return this;\n };\n /**\n * Scale the current Color4 values by a factor and add the result to a given Color4\n * @param scale defines the scale factor\n * @param result defines the Color4 object where to store the result\n * @returns the unmodified current Color4\n */\n Color4.prototype.scaleAndAddToRef = function (scale, result) {\n result.r += this.r * scale;\n result.g += this.g * scale;\n result.b += this.b * scale;\n result.a += this.a * scale;\n return this;\n };\n /**\n * Clamps the rgb values by the min and max values and stores the result into \"result\"\n * @param min defines minimum clamping value (default is 0)\n * @param max defines maximum clamping value (default is 1)\n * @param result defines color to store the result into.\n * @returns the cuurent Color4\n */\n Color4.prototype.clampToRef = function (min, max, result) {\n if (min === void 0) { min = 0; }\n if (max === void 0) { max = 1; }\n result.r = BABYLON.Scalar.Clamp(this.r, min, max);\n result.g = BABYLON.Scalar.Clamp(this.g, min, max);\n result.b = BABYLON.Scalar.Clamp(this.b, min, max);\n result.a = BABYLON.Scalar.Clamp(this.a, min, max);\n return this;\n };\n /**\n * Multipy an Color4 value by another and return a new Color4 object\n * @param color defines the Color4 value to multiply by\n * @returns a new Color4 object\n */\n Color4.prototype.multiply = function (color) {\n return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);\n };\n /**\n * Multipy a Color4 value by another and push the result in a reference value\n * @param color defines the Color4 value to multiply by\n * @param result defines the Color4 to fill the result in\n * @returns the result Color4\n */\n Color4.prototype.multiplyToRef = function (color, result) {\n result.r = this.r * color.r;\n result.g = this.g * color.g;\n result.b = this.b * color.b;\n result.a = this.a * color.a;\n return result;\n };\n /**\n * Creates a string with the Color4 current values\n * @returns the string representation of the Color4 object\n */\n Color4.prototype.toString = function () {\n return \"{R: \" + this.r + \" G:\" + this.g + \" B:\" + this.b + \" A:\" + this.a + \"}\";\n };\n /**\n * Returns the string \"Color4\"\n * @returns \"Color4\"\n */\n Color4.prototype.getClassName = function () {\n return \"Color4\";\n };\n /**\n * Compute the Color4 hash code\n * @returns an unique number that can be used to hash Color4 objects\n */\n Color4.prototype.getHashCode = function () {\n var hash = this.r || 0;\n hash = (hash * 397) ^ (this.g || 0);\n hash = (hash * 397) ^ (this.b || 0);\n hash = (hash * 397) ^ (this.a || 0);\n return hash;\n };\n /**\n * Creates a new Color4 copied from the current one\n * @returns a new Color4 object\n */\n Color4.prototype.clone = function () {\n return new Color4(this.r, this.g, this.b, this.a);\n };\n /**\n * Copies the given Color4 values into the current one\n * @param source defines the source Color4 object\n * @returns the current updated Color4 object\n */\n Color4.prototype.copyFrom = function (source) {\n this.r = source.r;\n this.g = source.g;\n this.b = source.b;\n this.a = source.a;\n return this;\n };\n /**\n * Copies the given float values into the current one\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @param a defines the alpha component to read from\n * @returns the current updated Color4 object\n */\n Color4.prototype.copyFromFloats = function (r, g, b, a) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n return this;\n };\n /**\n * Copies the given float values into the current one\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @param a defines the alpha component to read from\n * @returns the current updated Color4 object\n */\n Color4.prototype.set = function (r, g, b, a) {\n return this.copyFromFloats(r, g, b, a);\n };\n /**\n * Compute the Color4 hexadecimal code as a string\n * @returns a string containing the hexadecimal representation of the Color4 object\n */\n Color4.prototype.toHexString = function () {\n var intR = (this.r * 255) | 0;\n var intG = (this.g * 255) | 0;\n var intB = (this.b * 255) | 0;\n var intA = (this.a * 255) | 0;\n return \"#\" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);\n };\n /**\n * Computes a new Color4 converted from the current one to linear space\n * @returns a new Color4 object\n */\n Color4.prototype.toLinearSpace = function () {\n var convertedColor = new Color4();\n this.toLinearSpaceToRef(convertedColor);\n return convertedColor;\n };\n /**\n * Converts the Color4 values to linear space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color4 object where to store the linear space version\n * @returns the unmodified Color4\n */\n Color4.prototype.toLinearSpaceToRef = function (convertedColor) {\n convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);\n convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);\n convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);\n convertedColor.a = this.a;\n return this;\n };\n /**\n * Computes a new Color4 converted from the current one to gamma space\n * @returns a new Color4 object\n */\n Color4.prototype.toGammaSpace = function () {\n var convertedColor = new Color4();\n this.toGammaSpaceToRef(convertedColor);\n return convertedColor;\n };\n /**\n * Converts the Color4 values to gamma space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color4 object where to store the gamma space version\n * @returns the unmodified Color4\n */\n Color4.prototype.toGammaSpaceToRef = function (convertedColor) {\n convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);\n convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);\n convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);\n convertedColor.a = this.a;\n return this;\n };\n // Statics\n /**\n * Creates a new Color4 from the string containing valid hexadecimal values\n * @param hex defines a string containing valid hexadecimal values\n * @returns a new Color4 object\n */\n Color4.FromHexString = function (hex) {\n if (hex.substring(0, 1) !== \"#\" || hex.length !== 9) {\n return new Color4(0.0, 0.0, 0.0, 0.0);\n }\n var r = parseInt(hex.substring(1, 3), 16);\n var g = parseInt(hex.substring(3, 5), 16);\n var b = parseInt(hex.substring(5, 7), 16);\n var a = parseInt(hex.substring(7, 9), 16);\n return Color4.FromInts(r, g, b, a);\n };\n /**\n * Creates a new Color4 object set with the linearly interpolated values of \"amount\" between the left Color4 object and the right Color4 object\n * @param left defines the start value\n * @param right defines the end value\n * @param amount defines the gradient factor\n * @returns a new Color4 object\n */\n Color4.Lerp = function (left, right, amount) {\n var result = new Color4(0.0, 0.0, 0.0, 0.0);\n Color4.LerpToRef(left, right, amount, result);\n return result;\n };\n /**\n * Set the given \"result\" with the linearly interpolated values of \"amount\" between the left Color4 object and the right Color4 object\n * @param left defines the start value\n * @param right defines the end value\n * @param amount defines the gradient factor\n * @param result defines the Color4 object where to store data\n */\n Color4.LerpToRef = function (left, right, amount, result) {\n result.r = left.r + (right.r - left.r) * amount;\n result.g = left.g + (right.g - left.g) * amount;\n result.b = left.b + (right.b - left.b) * amount;\n result.a = left.a + (right.a - left.a) * amount;\n };\n /**\n * Creates a new Color4 from the starting index element of the given array\n * @param array defines the source array to read from\n * @param offset defines the offset in the source array\n * @returns a new Color4 object\n */\n Color4.FromArray = function (array, offset) {\n if (offset === void 0) { offset = 0; }\n return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n };\n /**\n * Creates a new Color3 from integer values (< 256)\n * @param r defines the red component to read from (value between 0 and 255)\n * @param g defines the green component to read from (value between 0 and 255)\n * @param b defines the blue component to read from (value between 0 and 255)\n * @param a defines the alpha component to read from (value between 0 and 255)\n * @returns a new Color3 object\n */\n Color4.FromInts = function (r, g, b, a) {\n return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);\n };\n /**\n * Check the content of a given array and convert it to an array containing RGBA data\n * If the original array was already containing count * 4 values then it is returned directly\n * @param colors defines the array to check\n * @param count defines the number of RGBA data to expect\n * @returns an array containing count * 4 values (RGBA)\n */\n Color4.CheckColors4 = function (colors, count) {\n // Check if color3 was used\n if (colors.length === count * 3) {\n var colors4 = [];\n for (var index = 0; index < colors.length; index += 3) {\n var newIndex = (index / 3) * 4;\n colors4[newIndex] = colors[index];\n colors4[newIndex + 1] = colors[index + 1];\n colors4[newIndex + 2] = colors[index + 2];\n colors4[newIndex + 3] = 1.0;\n }\n return colors4;\n }\n return colors;\n };\n return Color4;\n }());\n BABYLON.Color4 = Color4;\n /**\n * Class representing a vector containing 2 coordinates\n */\n var Vector2 = /** @class */ (function () {\n /**\n * Creates a new Vector2 from the given x and y coordinates\n * @param x defines the first coordinate\n * @param y defines the second coordinate\n */\n function Vector2(\n /** defines the first coordinate */\n x, \n /** defines the second coordinate */\n y) {\n if (x === void 0) { x = 0; }\n if (y === void 0) { y = 0; }\n this.x = x;\n this.y = y;\n }\n /**\n * Gets a string with the Vector2 coordinates\n * @returns a string with the Vector2 coordinates\n */\n Vector2.prototype.toString = function () {\n return \"{X: \" + this.x + \" Y:\" + this.y + \"}\";\n };\n /**\n * Gets class name\n * @returns the string \"Vector2\"\n */\n Vector2.prototype.getClassName = function () {\n return \"Vector2\";\n };\n /**\n * Gets current vector hash code\n * @returns the Vector2 hash code as a number\n */\n Vector2.prototype.getHashCode = function () {\n var hash = this.x || 0;\n hash = (hash * 397) ^ (this.y || 0);\n return hash;\n };\n // Operators\n /**\n * Sets the Vector2 coordinates in the given array or Float32Array from the given index.\n * @param array defines the source array\n * @param index defines the offset in source array\n * @returns the current Vector2\n */\n Vector2.prototype.toArray = function (array, index) {\n if (index === void 0) { index = 0; }\n array[index] = this.x;\n array[index + 1] = this.y;\n return this;\n };\n /**\n * Copy the current vector to an array\n * @returns a new array with 2 elements: the Vector2 coordinates.\n */\n Vector2.prototype.asArray = function () {\n var result = new Array();\n this.toArray(result, 0);\n return result;\n };\n /**\n * Sets the Vector2 coordinates with the given Vector2 coordinates\n * @param source defines the source Vector2\n * @returns the current updated Vector2\n */\n Vector2.prototype.copyFrom = function (source) {\n this.x = source.x;\n this.y = source.y;\n return this;\n };\n /**\n * Sets the Vector2 coordinates with the given floats\n * @param x defines the first coordinate\n * @param y defines the second coordinate\n * @returns the current updated Vector2\n */\n Vector2.prototype.copyFromFloats = function (x, y) {\n this.x = x;\n this.y = y;\n return this;\n };\n /**\n * Sets the Vector2 coordinates with the given floats\n * @param x defines the first coordinate\n * @param y defines the second coordinate\n * @returns the current updated Vector2\n */\n Vector2.prototype.set = function (x, y) {\n return this.copyFromFloats(x, y);\n };\n /**\n * Add another vector with the current one\n * @param otherVector defines the other vector\n * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates\n */\n Vector2.prototype.add = function (otherVector) {\n return new Vector2(this.x + otherVector.x, this.y + otherVector.y);\n };\n /**\n * Sets the \"result\" coordinates with the addition of the current Vector2 and the given one coordinates\n * @param otherVector defines the other vector\n * @param result defines the target vector\n * @returns the unmodified current Vector2\n */\n Vector2.prototype.addToRef = function (otherVector, result) {\n result.x = this.x + otherVector.x;\n result.y = this.y + otherVector.y;\n return this;\n };\n /**\n * Set the Vector2 coordinates by adding the given Vector2 coordinates\n * @param otherVector defines the other vector\n * @returns the current updated Vector2\n */\n Vector2.prototype.addInPlace = function (otherVector) {\n this.x += otherVector.x;\n this.y += otherVector.y;\n return this;\n };\n /**\n * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates\n * @param otherVector defines the other vector\n * @returns a new Vector2\n */\n Vector2.prototype.addVector3 = function (otherVector) {\n return new Vector2(this.x + otherVector.x, this.y + otherVector.y);\n };\n /**\n * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2\n * @param otherVector defines the other vector\n * @returns a new Vector2\n */\n Vector2.prototype.subtract = function (otherVector) {\n return new Vector2(this.x - otherVector.x, this.y - otherVector.y);\n };\n /**\n * Sets the \"result\" coordinates with the subtraction of the given one from the current Vector2 coordinates.\n * @param otherVector defines the other vector\n * @param result defines the target vector\n * @returns the unmodified current Vector2\n */\n Vector2.prototype.subtractToRef = function (otherVector, result) {\n result.x = this.x - otherVector.x;\n result.y = this.y - otherVector.y;\n return this;\n };\n /**\n * Sets the current Vector2 coordinates by subtracting from it the given one coordinates\n * @param otherVector defines the other vector\n * @returns the current updated Vector2\n */\n Vector2.prototype.subtractInPlace = function (otherVector) {\n this.x -= otherVector.x;\n this.y -= otherVector.y;\n return this;\n };\n /**\n * Multiplies in place the current Vector2 coordinates by the given ones\n * @param otherVector defines the other vector\n * @returns the current updated Vector2\n */\n Vector2.prototype.multiplyInPlace = function (otherVector) {\n this.x *= otherVector.x;\n this.y *= otherVector.y;\n return this;\n };\n /**\n * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates\n * @param otherVector defines the other vector\n * @returns a new Vector2\n */\n Vector2.prototype.multiply = function (otherVector) {\n return new Vector2(this.x * otherVector.x, this.y * otherVector.y);\n };\n /**\n * Sets \"result\" coordinates with the multiplication of the current Vector2 and the given one coordinates\n * @param otherVector defines the other vector\n * @param result defines the target vector\n * @returns the unmodified current Vector2\n */\n Vector2.prototype.multiplyToRef = function (otherVector, result) {\n result.x = this.x * otherVector.x;\n result.y = this.y * otherVector.y;\n return this;\n };\n /**\n * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats\n * @param x defines the first coordinate\n * @param y defines the second coordinate\n * @returns a new Vector2\n */\n Vector2.prototype.multiplyByFloats = function (x, y) {\n return new Vector2(this.x * x, this.y * y);\n };\n /**\n * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates\n * @param otherVector defines the other vector\n * @returns a new Vector2\n */\n Vector2.prototype.divide = function (otherVector) {\n return new Vector2(this.x / otherVector.x, this.y / otherVector.y);\n };\n /**\n * Sets the \"result\" coordinates with the Vector2 divided by the given one coordinates\n * @param otherVector defines the other vector\n * @param result defines the target vector\n * @returns the unmodified current Vector2\n */\n Vector2.prototype.divideToRef = function (otherVector, result) {\n result.x = this.x / otherVector.x;\n result.y = this.y / otherVector.y;\n return this;\n };\n /**\n * Divides the current Vector2 coordinates by the given ones\n * @param otherVector defines the other vector\n * @returns the current updated Vector2\n */\n Vector2.prototype.divideInPlace = function (otherVector) {\n return this.divideToRef(otherVector, this);\n };\n /**\n * Gets a new Vector2 with current Vector2 negated coordinates\n * @returns a new Vector2\n */\n Vector2.prototype.negate = function () {\n return new Vector2(-this.x, -this.y);\n };\n /**\n * Multiply the Vector2 coordinates by scale\n * @param scale defines the scaling factor\n * @returns the current updated Vector2\n */\n Vector2.prototype.scaleInPlace = function (scale) {\n this.x *= scale;\n this.y *= scale;\n return this;\n };\n /**\n * Returns a new Vector2 scaled by \"scale\" from the current Vector2\n * @param scale defines the scaling factor\n * @returns a new Vector2\n */\n Vector2.prototype.scale = function (scale) {\n var result = new Vector2(0, 0);\n this.scaleToRef(scale, result);\n return result;\n };\n /**\n * Scale the current Vector2 values by a factor to a given Vector2\n * @param scale defines the scale factor\n * @param result defines the Vector2 object where to store the result\n * @returns the unmodified current Vector2\n */\n Vector2.prototype.scaleToRef = function (scale, result) {\n result.x = this.x * scale;\n result.y = this.y * scale;\n return this;\n };\n /**\n * Scale the current Vector2 values by a factor and add the result to a given Vector2\n * @param scale defines the scale factor\n * @param result defines the Vector2 object where to store the result\n * @returns the unmodified current Vector2\n */\n Vector2.prototype.scaleAndAddToRef = function (scale, result) {\n result.x += this.x * scale;\n result.y += this.y * scale;\n return this;\n };\n /**\n * Gets a boolean if two vectors are equals\n * @param otherVector defines the other vector\n * @returns true if the given vector coordinates strictly equal the current Vector2 ones\n */\n Vector2.prototype.equals = function (otherVector) {\n return otherVector && this.x === otherVector.x && this.y === otherVector.y;\n };\n /**\n * Gets a boolean if two vectors are equals (using an epsilon value)\n * @param otherVector defines the other vector\n * @param epsilon defines the minimal distance to consider equality\n * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.\n */\n Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {\n if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }\n return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);\n };\n /**\n * Gets a new Vector2 from current Vector2 floored values\n * @returns a new Vector2\n */\n Vector2.prototype.floor = function () {\n return new Vector2(Math.floor(this.x), Math.floor(this.y));\n };\n /**\n * Gets a new Vector2 from current Vector2 floored values\n * @returns a new Vector2\n */\n Vector2.prototype.fract = function () {\n return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));\n };\n // Properties\n /**\n * Gets the length of the vector\n * @returns the vector length (float)\n */\n Vector2.prototype.length = function () {\n return Math.sqrt(this.x * this.x + this.y * this.y);\n };\n /**\n * Gets the vector squared length\n * @returns the vector squared length (float)\n */\n Vector2.prototype.lengthSquared = function () {\n return (this.x * this.x + this.y * this.y);\n };\n // Methods\n /**\n * Normalize the vector\n * @returns the current updated Vector2\n */\n Vector2.prototype.normalize = function () {\n var len = this.length();\n if (len === 0)\n return this;\n var num = 1.0 / len;\n this.x *= num;\n this.y *= num;\n return this;\n };\n /**\n * Gets a new Vector2 copied from the Vector2\n * @returns a new Vector2\n */\n Vector2.prototype.clone = function () {\n return new Vector2(this.x, this.y);\n };\n // Statics\n /**\n * Gets a new Vector2(0, 0)\n * @returns a new Vector2\n */\n Vector2.Zero = function () {\n return new Vector2(0, 0);\n };\n /**\n * Gets a new Vector2(1, 1)\n * @returns a new Vector2\n */\n Vector2.One = function () {\n return new Vector2(1, 1);\n };\n /**\n * Gets a new Vector2 set from the given index element of the given array\n * @param array defines the data source\n * @param offset defines the offset in the data source\n * @returns a new Vector2\n */\n Vector2.FromArray = function (array, offset) {\n if (offset === void 0) { offset = 0; }\n return new Vector2(array[offset], array[offset + 1]);\n };\n /**\n * Sets \"result\" from the given index element of the given array\n * @param array defines the data source\n * @param offset defines the offset in the data source\n * @param result defines the target vector\n */\n Vector2.FromArrayToRef = function (array, offset, result) {\n result.x = array[offset];\n result.y = array[offset + 1];\n };\n /**\n * Gets a new Vector2 located for \"amount\" (float) on the CatmullRom spline defined by the given four Vector2\n * @param value1 defines 1st point of control\n * @param value2 defines 2nd point of control\n * @param value3 defines 3rd point of control\n * @param value4 defines 4th point of control\n * @param amount defines the interpolation factor\n * @returns a new Vector2\n */\n Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {\n var squared = amount * amount;\n var cubed = amount * squared;\n var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +\n (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +\n ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));\n var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +\n (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +\n ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));\n return new Vector2(x, y);\n };\n /**\n * Returns a new Vector2 set with same the coordinates than \"value\" ones if the vector \"value\" is in the square defined by \"min\" and \"max\".\n * If a coordinate of \"value\" is lower than \"min\" coordinates, the returned Vector2 is given this \"min\" coordinate.\n * If a coordinate of \"value\" is greater than \"max\" coordinates, the returned Vector2 is given this \"max\" coordinate\n * @param value defines the value to clamp\n * @param min defines the lower limit\n * @param max defines the upper limit\n * @returns a new Vector2\n */\n Vector2.Clamp = function (value, min, max) {\n var x = value.x;\n x = (x > max.x) ? max.x : x;\n x = (x < min.x) ? min.x : x;\n var y = value.y;\n y = (y > max.y) ? max.y : y;\n y = (y < min.y) ? min.y : y;\n return new Vector2(x, y);\n };\n /**\n * Returns a new Vector2 located for \"amount\" (float) on the Hermite spline defined by the vectors \"value1\", \"value3\", \"tangent1\", \"tangent2\"\n * @param value1 defines the 1st control point\n * @param tangent1 defines the outgoing tangent\n * @param value2 defines the 2nd control point\n * @param tangent2 defines the incoming tangent\n * @param amount defines the interpolation factor\n * @returns a new Vector2\n */\n Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {\n var squared = amount * amount;\n var cubed = amount * squared;\n var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;\n var part2 = (-2.0 * cubed) + (3.0 * squared);\n var part3 = (cubed - (2.0 * squared)) + amount;\n var part4 = cubed - squared;\n var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);\n var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);\n return new Vector2(x, y);\n };\n /**\n * Returns a new Vector2 located for \"amount\" (float) on the linear interpolation between the vector \"start\" adn the vector \"end\".\n * @param start defines the start vector\n * @param end defines the end vector\n * @param amount defines the interpolation factor\n * @returns a new Vector2\n */\n Vector2.Lerp = function (start, end, amount) {\n var x = start.x + ((end.x - start.x) * amount);\n var y = start.y + ((end.y - start.y) * amount);\n return new Vector2(x, y);\n };\n /**\n * Gets the dot product of the vector \"left\" and the vector \"right\"\n * @param left defines first vector\n * @param right defines second vector\n * @returns the dot product (float)\n */\n Vector2.Dot = function (left, right) {\n return left.x * right.x + left.y * right.y;\n };\n /**\n * Returns a new Vector2 equal to the normalized given vector\n * @param vector defines the vector to normalize\n * @returns a new Vector2\n */\n Vector2.Normalize = function (vector) {\n var newVector = vector.clone();\n newVector.normalize();\n return newVector;\n };\n /**\n * Gets a new Vector2 set with the minimal coordinate values from the \"left\" and \"right\" vectors\n * @param left defines 1st vector\n * @param right defines 2nd vector\n * @returns a new Vector2\n */\n Vector2.Minimize = function (left, right) {\n var x = (left.x < right.x) ? left.x : right.x;\n var y = (left.y < right.y) ? left.y : right.y;\n return new Vector2(x, y);\n };\n /**\n * Gets a new Vecto2 set with the maximal coordinate values from the \"left\" and \"right\" vectors\n * @param left defines 1st vector\n * @param right defines 2nd vector\n * @returns a new Vector2\n */\n Vector2.Maximize = function (left, right) {\n var x = (left.x > right.x) ? left.x : right.x;\n var y = (left.y > right.y) ? left.y : right.y;\n return new Vector2(x, y);\n };\n /**\n * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix\n * @param vector defines the vector to transform\n * @param transformation defines the matrix to apply\n * @returns a new Vector2\n */\n Vector2.Transform = function (vector, transformation) {\n var r = Vector2.Zero();\n Vector2.TransformToRef(vector, transformation, r);\n return r;\n };\n /**\n * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector \"result\" coordinates\n * @param vector defines the vector to transform\n * @param transformation defines the matrix to apply\n * @param result defines the target vector\n */\n Vector2.TransformToRef = function (vector, transformation, result) {\n var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];\n var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];\n result.x = x;\n result.y = y;\n };\n /**\n * Determines if a given vector is included in a triangle\n * @param p defines the vector to test\n * @param p0 defines 1st triangle point\n * @param p1 defines 2nd triangle point\n * @param p2 defines 3rd triangle point\n * @returns true if the point \"p\" is in the triangle defined by the vertors \"p0\", \"p1\", \"p2\"\n */\n Vector2.PointInTriangle = function (p, p0, p1, p2) {\n var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);\n var sign = a < 0 ? -1 : 1;\n var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;\n var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;\n return s > 0 && t > 0 && (s + t) < 2 * a * sign;\n };\n /**\n * Gets the distance between the vectors \"value1\" and \"value2\"\n * @param value1 defines first vector\n * @param value2 defines second vector\n * @returns the distance between vectors\n */\n Vector2.Distance = function (value1, value2) {\n return Math.sqrt(Vector2.DistanceSquared(value1, value2));\n };\n /**\n * Returns the squared distance between the vectors \"value1\" and \"value2\"\n * @param value1 defines first vector\n * @param value2 defines second vector\n * @returns the squared distance between vectors\n */\n Vector2.DistanceSquared = function (value1, value2) {\n var x = value1.x - value2.x;\n var y = value1.y - value2.y;\n return (x * x) + (y * y);\n };\n /**\n * Gets a new Vector2 located at the center of the vectors \"value1\" and \"value2\"\n * @param value1 defines first vector\n * @param value2 defines second vector\n * @returns a new Vector2\n */\n Vector2.Center = function (value1, value2) {\n var center = value1.add(value2);\n center.scaleInPlace(0.5);\n return center;\n };\n /**\n * Gets the shortest distance (float) between the point \"p\" and the segment defined by the two points \"segA\" and \"segB\".\n * @param p defines the middle point\n * @param segA defines one point of the segment\n * @param segB defines the other point of the segment\n * @returns the shortest distance\n */\n Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {\n var l2 = Vector2.DistanceSquared(segA, segB);\n if (l2 === 0.0) {\n return Vector2.Distance(p, segA);\n }\n var v = segB.subtract(segA);\n var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));\n var proj = segA.add(v.multiplyByFloats(t, t));\n return Vector2.Distance(p, proj);\n };\n return Vector2;\n }());\n BABYLON.Vector2 = Vector2;\n /**\n * Classed used to store (x,y,z) vector representation\n * A Vector3 is the main object used in 3D geometry\n * It can represent etiher the coordinates of a point the space, either a direction\n * Reminder: Babylon.js uses a left handed forward facing system\n */\n var Vector3 = /** @class */ (function () {\n /**\n * Creates a new Vector3 object from the given x, y, z (floats) coordinates.\n * @param x defines the first coordinates (on X axis)\n * @param y defines the second coordinates (on Y axis)\n * @param z defines the third coordinates (on Z axis)\n */\n function Vector3(\n /**\n * Defines the first coordinates (on X axis)\n */\n x, \n /**\n * Defines the second coordinates (on Y axis)\n */\n y, \n /**\n * Defines the third coordinates (on Z axis)\n */\n z) {\n if (x === void 0) { x = 0; }\n if (y === void 0) { y = 0; }\n if (z === void 0) { z = 0; }\n this.x = x;\n this.y = y;\n this.z = z;\n }\n /**\n * Creates a string representation of the Vector3\n * @returns a string with the Vector3 coordinates.\n */\n Vector3.prototype.toString = function () {\n return \"{X: \" + this.x + \" Y:\" + this.y + \" Z:\" + this.z + \"}\";\n };\n /**\n * Gets the class name\n * @returns the string \"Vector3\"\n */\n Vector3.prototype.getClassName = function () {\n return \"Vector3\";\n };\n /**\n * Creates the Vector3 hash code\n * @returns a number which tends to be unique between Vector3 instances\n */\n Vector3.prototype.getHashCode = function () {\n var hash = this.x || 0;\n hash = (hash * 397) ^ (this.y || 0);\n hash = (hash * 397) ^ (this.z || 0);\n return hash;\n };\n // Operators\n /**\n * Creates an array containing three elements : the coordinates of the Vector3\n * @returns a new array of numbers\n */\n Vector3.prototype.asArray = function () {\n var result = [];\n this.toArray(result, 0);\n return result;\n };\n /**\n * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3\n * @param array defines the destination array\n * @param index defines the offset in the destination array\n * @returns the current Vector3\n */\n Vector3.prototype.toArray = function (array, index) {\n if (index === void 0) { index = 0; }\n array[index] = this.x;\n array[index + 1] = this.y;\n array[index + 2] = this.z;\n return this;\n };\n /**\n * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)\n * @returns a new Quaternion object, computed from the Vector3 coordinates\n */\n Vector3.prototype.toQuaternion = function () {\n return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);\n };\n /**\n * Adds the given vector to the current Vector3\n * @param otherVector defines the second operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.addInPlace = function (otherVector) {\n this.x += otherVector.x;\n this.y += otherVector.y;\n this.z += otherVector.z;\n return this;\n };\n /**\n * Gets a new Vector3, result of the addition the current Vector3 and the given vector\n * @param otherVector defines the second operand\n * @returns the resulting Vector3\n */\n Vector3.prototype.add = function (otherVector) {\n return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);\n };\n /**\n * Adds the current Vector3 to the given one and stores the result in the vector \"result\"\n * @param otherVector defines the second operand\n * @param result defines the Vector3 object where to store the result\n * @returns the current Vector3\n */\n Vector3.prototype.addToRef = function (otherVector, result) {\n result.x = this.x + otherVector.x;\n result.y = this.y + otherVector.y;\n result.z = this.z + otherVector.z;\n return this;\n };\n /**\n * Subtract the given vector from the current Vector3\n * @param otherVector defines the second operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.subtractInPlace = function (otherVector) {\n this.x -= otherVector.x;\n this.y -= otherVector.y;\n this.z -= otherVector.z;\n return this;\n };\n /**\n * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3\n * @param otherVector defines the second operand\n * @returns the resulting Vector3\n */\n Vector3.prototype.subtract = function (otherVector) {\n return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);\n };\n /**\n * Subtracts the given vector from the current Vector3 and stores the result in the vector \"result\".\n * @param otherVector defines the second operand\n * @param result defines the Vector3 object where to store the result\n * @returns the current Vector3\n */\n Vector3.prototype.subtractToRef = function (otherVector, result) {\n result.x = this.x - otherVector.x;\n result.y = this.y - otherVector.y;\n result.z = this.z - otherVector.z;\n return this;\n };\n /**\n * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates\n * @param x defines the x coordinate of the operand\n * @param y defines the y coordinate of the operand\n * @param z defines the z coordinate of the operand\n * @returns the resulting Vector3\n */\n Vector3.prototype.subtractFromFloats = function (x, y, z) {\n return new Vector3(this.x - x, this.y - y, this.z - z);\n };\n /**\n * Subtracts the given floats from the current Vector3 coordinates and set the given vector \"result\" with this result\n * @param x defines the x coordinate of the operand\n * @param y defines the y coordinate of the operand\n * @param z defines the z coordinate of the operand\n * @param result defines the Vector3 object where to store the result\n * @returns the current Vector3\n */\n Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {\n result.x = this.x - x;\n result.y = this.y - y;\n result.z = this.z - z;\n return this;\n };\n /**\n * Gets a new Vector3 set with the current Vector3 negated coordinates\n * @returns a new Vector3\n */\n Vector3.prototype.negate = function () {\n return new Vector3(-this.x, -this.y, -this.z);\n };\n /**\n * Multiplies the Vector3 coordinates by the float \"scale\"\n * @param scale defines the multiplier factor\n * @returns the current updated Vector3\n */\n Vector3.prototype.scaleInPlace = function (scale) {\n this.x *= scale;\n this.y *= scale;\n this.z *= scale;\n return this;\n };\n /**\n * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float \"scale\"\n * @param scale defines the multiplier factor\n * @returns a new Vector3\n */\n Vector3.prototype.scale = function (scale) {\n return new Vector3(this.x * scale, this.y * scale, this.z * scale);\n };\n /**\n * Multiplies the current Vector3 coordinates by the float \"scale\" and stores the result in the given vector \"result\" coordinates\n * @param scale defines the multiplier factor\n * @param result defines the Vector3 object where to store the result\n * @returns the current Vector3\n */\n Vector3.prototype.scaleToRef = function (scale, result) {\n result.x = this.x * scale;\n result.y = this.y * scale;\n result.z = this.z * scale;\n return this;\n };\n /**\n * Scale the current Vector3 values by a factor and add the result to a given Vector3\n * @param scale defines the scale factor\n * @param result defines the Vector3 object where to store the result\n * @returns the unmodified current Vector3\n */\n Vector3.prototype.scaleAndAddToRef = function (scale, result) {\n result.x += this.x * scale;\n result.y += this.y * scale;\n result.z += this.z * scale;\n return this;\n };\n /**\n * Returns true if the current Vector3 and the given vector coordinates are strictly equal\n * @param otherVector defines the second operand\n * @returns true if both vectors are equals\n */\n Vector3.prototype.equals = function (otherVector) {\n return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;\n };\n /**\n * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon\n * @param otherVector defines the second operand\n * @param epsilon defines the minimal distance to define values as equals\n * @returns true if both vectors are distant less than epsilon\n */\n Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {\n if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }\n return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);\n };\n /**\n * Returns true if the current Vector3 coordinates equals the given floats\n * @param x defines the x coordinate of the operand\n * @param y defines the y coordinate of the operand\n * @param z defines the z coordinate of the operand\n * @returns true if both vectors are equals\n */\n Vector3.prototype.equalsToFloats = function (x, y, z) {\n return this.x === x && this.y === y && this.z === z;\n };\n /**\n * Multiplies the current Vector3 coordinates by the given ones\n * @param otherVector defines the second operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.multiplyInPlace = function (otherVector) {\n this.x *= otherVector.x;\n this.y *= otherVector.y;\n this.z *= otherVector.z;\n return this;\n };\n /**\n * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector\n * @param otherVector defines the second operand\n * @returns the new Vector3\n */\n Vector3.prototype.multiply = function (otherVector) {\n return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);\n };\n /**\n * Multiplies the current Vector3 by the given one and stores the result in the given vector \"result\"\n * @param otherVector defines the second operand\n * @param result defines the Vector3 object where to store the result\n * @returns the current Vector3\n */\n Vector3.prototype.multiplyToRef = function (otherVector, result) {\n result.x = this.x * otherVector.x;\n result.y = this.y * otherVector.y;\n result.z = this.z * otherVector.z;\n return this;\n };\n /**\n * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats\n * @param x defines the x coordinate of the operand\n * @param y defines the y coordinate of the operand\n * @param z defines the z coordinate of the operand\n * @returns the new Vector3\n */\n Vector3.prototype.multiplyByFloats = function (x, y, z) {\n return new Vector3(this.x * x, this.y * y, this.z * z);\n };\n /**\n * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones\n * @param otherVector defines the second operand\n * @returns the new Vector3\n */\n Vector3.prototype.divide = function (otherVector) {\n return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);\n };\n /**\n * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector \"result\"\n * @param otherVector defines the second operand\n * @param result defines the Vector3 object where to store the result\n * @returns the current Vector3\n */\n Vector3.prototype.divideToRef = function (otherVector, result) {\n result.x = this.x / otherVector.x;\n result.y = this.y / otherVector.y;\n result.z = this.z / otherVector.z;\n return this;\n };\n /**\n * Divides the current Vector3 coordinates by the given ones.\n * @param otherVector defines the second operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.divideInPlace = function (otherVector) {\n return this.divideToRef(otherVector, this);\n };\n /**\n * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones\n * @param other defines the second operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.minimizeInPlace = function (other) {\n if (other.x < this.x)\n this.x = other.x;\n if (other.y < this.y)\n this.y = other.y;\n if (other.z < this.z)\n this.z = other.z;\n return this;\n };\n /**\n * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.\n * @param other defines the second operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.maximizeInPlace = function (other) {\n if (other.x > this.x)\n this.x = other.x;\n if (other.y > this.y)\n this.y = other.y;\n if (other.z > this.z)\n this.z = other.z;\n return this;\n };\n Object.defineProperty(Vector3.prototype, \"isNonUniform\", {\n /**\n * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same\n */\n get: function () {\n var absX = Math.abs(this.x);\n var absY = Math.abs(this.y);\n if (absX !== absY) {\n return true;\n }\n var absZ = Math.abs(this.z);\n if (absX !== absZ) {\n return true;\n }\n if (absY !== absZ) {\n return true;\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets a new Vector3 from current Vector3 floored values\n * @returns a new Vector3\n */\n Vector3.prototype.floor = function () {\n return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));\n };\n /**\n * Gets a new Vector3 from current Vector3 floored values\n * @returns a new Vector3\n */\n Vector3.prototype.fract = function () {\n return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));\n };\n // Properties\n /**\n * Gets the length of the Vector3\n * @returns the length of the Vecto3\n */\n Vector3.prototype.length = function () {\n return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);\n };\n /**\n * Gets the squared length of the Vector3\n * @returns squared length of the Vector3\n */\n Vector3.prototype.lengthSquared = function () {\n return (this.x * this.x + this.y * this.y + this.z * this.z);\n };\n /**\n * Normalize the current Vector3.\n * Please note that this is an in place operation.\n * @returns the current updated Vector3\n */\n Vector3.prototype.normalize = function () {\n var len = this.length();\n if (len === 0 || len === 1.0)\n return this;\n var num = 1.0 / len;\n this.x *= num;\n this.y *= num;\n this.z *= num;\n return this;\n };\n /**\n * Normalize the current Vector3 to a new vector\n * @returns the new Vector3\n */\n Vector3.prototype.normalizeToNew = function () {\n var normalized = new Vector3(0, 0, 0);\n this.normalizeToRef(normalized);\n return normalized;\n };\n /**\n * Normalize the current Vector3 to the reference\n * @param reference define the Vector3 to update\n * @returns the updated Vector3\n */\n Vector3.prototype.normalizeToRef = function (reference) {\n var len = this.length();\n if (len === 0 || len === 1.0) {\n reference.set(this.x, this.y, this.z);\n return reference;\n }\n var scale = 1.0 / len;\n this.scaleToRef(scale, reference);\n return reference;\n };\n /**\n * Creates a new Vector3 copied from the current Vector3\n * @returns the new Vector3\n */\n Vector3.prototype.clone = function () {\n return new Vector3(this.x, this.y, this.z);\n };\n /**\n * Copies the given vector coordinates to the current Vector3 ones\n * @param source defines the source Vector3\n * @returns the current updated Vector3\n */\n Vector3.prototype.copyFrom = function (source) {\n this.x = source.x;\n this.y = source.y;\n this.z = source.z;\n return this;\n };\n /**\n * Copies the given floats to the current Vector3 coordinates\n * @param x defines the x coordinate of the operand\n * @param y defines the y coordinate of the operand\n * @param z defines the z coordinate of the operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.copyFromFloats = function (x, y, z) {\n this.x = x;\n this.y = y;\n this.z = z;\n return this;\n };\n /**\n * Copies the given floats to the current Vector3 coordinates\n * @param x defines the x coordinate of the operand\n * @param y defines the y coordinate of the operand\n * @param z defines the z coordinate of the operand\n * @returns the current updated Vector3\n */\n Vector3.prototype.set = function (x, y, z) {\n return this.copyFromFloats(x, y, z);\n };\n // Statics\n /**\n * Get the clip factor between two vectors\n * @param vector0 defines the first operand\n * @param vector1 defines the second operand\n * @param axis defines the axis to use\n * @param size defines the size along the axis\n * @returns the clip factor\n */\n Vector3.GetClipFactor = function (vector0, vector1, axis, size) {\n var d0 = Vector3.Dot(vector0, axis) - size;\n var d1 = Vector3.Dot(vector1, axis) - size;\n var s = d0 / (d0 - d1);\n return s;\n };\n /**\n * Get angle between two vectors\n * @param vector0 angle between vector0 and vector1\n * @param vector1 angle between vector0 and vector1\n * @param normal direction of the normal\n * @return the angle between vector0 and vector1\n */\n Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {\n var v0 = vector0.clone().normalize();\n var v1 = vector1.clone().normalize();\n var dot = Vector3.Dot(v0, v1);\n var n = Vector3.Cross(v0, v1);\n if (Vector3.Dot(n, normal) > 0) {\n return Math.acos(dot);\n }\n return -Math.acos(dot);\n };\n /**\n * Returns a new Vector3 set from the index \"offset\" of the given array\n * @param array defines the source array\n * @param offset defines the offset in the source array\n * @returns the new Vector3\n */\n Vector3.FromArray = function (array, offset) {\n if (!offset) {\n offset = 0;\n }\n return new Vector3(array[offset], array[offset + 1], array[offset + 2]);\n };\n /**\n * Returns a new Vector3 set from the index \"offset\" of the given Float32Array\n * This function is deprecated. Use FromArray instead\n * @param array defines the source array\n * @param offset defines the offset in the source array\n * @returns the new Vector3\n */\n Vector3.FromFloatArray = function (array, offset) {\n return Vector3.FromArray(array, offset);\n };\n /**\n * Sets the given vector \"result\" with the element values from the index \"offset\" of the given array\n * @param array defines the source array\n * @param offset defines the offset in the source array\n * @param result defines the Vector3 where to store the result\n */\n Vector3.FromArrayToRef = function (array, offset, result) {\n result.x = array[offset];\n result.y = array[offset + 1];\n result.z = array[offset + 2];\n };\n /**\n * Sets the given vector \"result\" with the element values from the index \"offset\" of the given Float32Array\n * This function is deprecated. Use FromArrayToRef instead.\n * @param array defines the source array\n * @param offset defines the offset in the source array\n * @param result defines the Vector3 where to store the result\n */\n Vector3.FromFloatArrayToRef = function (array, offset, result) {\n return Vector3.FromArrayToRef(array, offset, result);\n };\n /**\n * Sets the given vector \"result\" with the given floats.\n * @param x defines the x coordinate of the source\n * @param y defines the y coordinate of the source\n * @param z defines the z coordinate of the source\n * @param result defines the Vector3 where to store the result\n */\n Vector3.FromFloatsToRef = function (x, y, z, result) {\n result.x = x;\n result.y = y;\n result.z = z;\n };\n /**\n * Returns a new Vector3 set to (0.0, 0.0, 0.0)\n * @returns a new empty Vector3\n */\n Vector3.Zero = function () {\n return new Vector3(0.0, 0.0, 0.0);\n };\n /**\n * Returns a new Vector3 set to (1.0, 1.0, 1.0)\n * @returns a new unit Vector3\n */\n Vector3.One = function () {\n return new Vector3(1.0, 1.0, 1.0);\n };\n /**\n * Returns a new Vector3 set to (0.0, 1.0, 0.0)\n * @returns a new up Vector3\n */\n Vector3.Up = function () {\n return new Vector3(0.0, 1.0, 0.0);\n };\n /**\n * Returns a new Vector3 set to (0.0, -1.0, 0.0)\n * @returns a new down Vector3\n */\n Vector3.Down = function () {\n return new Vector3(0.0, -1.0, 0.0);\n };\n /**\n * Returns a new Vector3 set to (0.0, 0.0, 1.0)\n * @returns a new forward Vector3\n */\n Vector3.Forward = function () {\n return new Vector3(0.0, 0.0, 1.0);\n };\n /**\n * Returns a new Vector3 set to (1.0, 0.0, 0.0)\n * @returns a new right Vector3\n */\n Vector3.Right = function () {\n return new Vector3(1.0, 0.0, 0.0);\n };\n /**\n * Returns a new Vector3 set to (-1.0, 0.0, 0.0)\n * @returns a new left Vector3\n */\n Vector3.Left = function () {\n return new Vector3(-1.0, 0.0, 0.0);\n };\n /**\n * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.\n * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)\n * @param vector defines the Vector3 to transform\n * @param transformation defines the transformation matrix\n * @returns the transformed Vector3\n */\n Vector3.TransformCoordinates = function (vector, transformation) {\n var result = Vector3.Zero();\n Vector3.TransformCoordinatesToRef(vector, transformation, result);\n return result;\n };\n /**\n * Sets the given vector \"result\" coordinates with the result of the transformation by the given matrix of the given vector\n * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)\n * @param vector defines the Vector3 to transform\n * @param transformation defines the transformation matrix\n * @param result defines the Vector3 where to store the result\n */\n Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {\n var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];\n var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];\n var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];\n var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];\n result.x = x / w;\n result.y = y / w;\n result.z = z / w;\n };\n /**\n * Sets the given vector \"result\" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)\n * This method computes tranformed coordinates only, not transformed direction vectors\n * @param x define the x coordinate of the source vector\n * @param y define the y coordinate of the source vector\n * @param z define the z coordinate of the source vector\n * @param transformation defines the transformation matrix\n * @param result defines the Vector3 where to store the result\n */\n Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {\n var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];\n var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];\n var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];\n var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];\n result.x = rx / rw;\n result.y = ry / rw;\n result.z = rz / rw;\n };\n /**\n * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector\n * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)\n * @param vector defines the Vector3 to transform\n * @param transformation defines the transformation matrix\n * @returns the new Vector3\n */\n Vector3.TransformNormal = function (vector, transformation) {\n var result = Vector3.Zero();\n Vector3.TransformNormalToRef(vector, transformation, result);\n return result;\n };\n /**\n * Sets the given vector \"result\" with the result of the normal transformation by the given matrix of the given vector\n * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)\n * @param vector defines the Vector3 to transform\n * @param transformation defines the transformation matrix\n * @param result defines the Vector3 where to store the result\n */\n Vector3.TransformNormalToRef = function (vector, transformation, result) {\n var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);\n var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);\n var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);\n result.x = x;\n result.y = y;\n result.z = z;\n };\n /**\n * Sets the given vector \"result\" with the result of the normal transformation by the given matrix of the given floats (x, y, z)\n * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)\n * @param x define the x coordinate of the source vector\n * @param y define the y coordinate of the source vector\n * @param z define the z coordinate of the source vector\n * @param transformation defines the transformation matrix\n * @param result defines the Vector3 where to store the result\n */\n Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {\n result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);\n result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);\n result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);\n };\n /**\n * Returns a new Vector3 located for \"amount\" on the CatmullRom interpolation spline defined by the vectors \"value1\", \"value2\", \"value3\", \"value4\"\n * @param value1 defines the first control point\n * @param value2 defines the second control point\n * @param value3 defines the third control point\n * @param value4 defines the fourth control point\n * @param amount defines the amount on the spline to use\n * @returns the new Vector3\n */\n Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {\n var squared = amount * amount;\n var cubed = amount * squared;\n var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +\n (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +\n ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));\n var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +\n (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +\n ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));\n var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +\n (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +\n ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));\n return new Vector3(x, y, z);\n };\n /**\n * Returns a new Vector3 set with the coordinates of \"value\", if the vector \"value\" is in the cube defined by the vectors \"min\" and \"max\"\n * If a coordinate value of \"value\" is lower than one of the \"min\" coordinate, then this \"value\" coordinate is set with the \"min\" one\n * If a coordinate value of \"value\" is greater than one of the \"max\" coordinate, then this \"value\" coordinate is set with the \"max\" one\n * @param value defines the current value\n * @param min defines the lower range value\n * @param max defines the upper range value\n * @returns the new Vector3\n */\n Vector3.Clamp = function (value, min, max) {\n var x = value.x;\n x = (x > max.x) ? max.x : x;\n x = (x < min.x) ? min.x : x;\n var y = value.y;\n y = (y > max.y) ? max.y : y;\n y = (y < min.y) ? min.y : y;\n var z = value.z;\n z = (z > max.z) ? max.z : z;\n z = (z < min.z) ? min.z : z;\n return new Vector3(x, y, z);\n };\n /**\n * Returns a new Vector3 located for \"amount\" (float) on the Hermite interpolation spline defined by the vectors \"value1\", \"tangent1\", \"value2\", \"tangent2\"\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent vector\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent vector\n * @param amount defines the amount on the interpolation spline (between 0 and 1)\n * @returns the new Vector3\n */\n Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {\n var squared = amount * amount;\n var cubed = amount * squared;\n var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;\n var part2 = (-2.0 * cubed) + (3.0 * squared);\n var part3 = (cubed - (2.0 * squared)) + amount;\n var part4 = cubed - squared;\n var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);\n var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);\n var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);\n return new Vector3(x, y, z);\n };\n /**\n * Returns a new Vector3 located for \"amount\" (float) on the linear interpolation between the vectors \"start\" and \"end\"\n * @param start defines the start value\n * @param end defines the end value\n * @param amount max defines amount between both (between 0 and 1)\n * @returns the new Vector3\n */\n Vector3.Lerp = function (start, end, amount) {\n var result = new Vector3(0, 0, 0);\n Vector3.LerpToRef(start, end, amount, result);\n return result;\n };\n /**\n * Sets the given vector \"result\" with the result of the linear interpolation from the vector \"start\" for \"amount\" to the vector \"end\"\n * @param start defines the start value\n * @param end defines the end value\n * @param amount max defines amount between both (between 0 and 1)\n * @param result defines the Vector3 where to store the result\n */\n Vector3.LerpToRef = function (start, end, amount, result) {\n result.x = start.x + ((end.x - start.x) * amount);\n result.y = start.y + ((end.y - start.y) * amount);\n result.z = start.z + ((end.z - start.z) * amount);\n };\n /**\n * Returns the dot product (float) between the vectors \"left\" and \"right\"\n * @param left defines the left operand\n * @param right defines the right operand\n * @returns the dot product\n */\n Vector3.Dot = function (left, right) {\n return (left.x * right.x + left.y * right.y + left.z * right.z);\n };\n /**\n * Returns a new Vector3 as the cross product of the vectors \"left\" and \"right\"\n * The cross product is then orthogonal to both \"left\" and \"right\"\n * @param left defines the left operand\n * @param right defines the right operand\n * @returns the cross product\n */\n Vector3.Cross = function (left, right) {\n var result = Vector3.Zero();\n Vector3.CrossToRef(left, right, result);\n return result;\n };\n /**\n * Sets the given vector \"result\" with the cross product of \"left\" and \"right\"\n * The cross product is then orthogonal to both \"left\" and \"right\"\n * @param left defines the left operand\n * @param right defines the right operand\n * @param result defines the Vector3 where to store the result\n */\n Vector3.CrossToRef = function (left, right, result) {\n MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;\n MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;\n MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;\n result.copyFrom(MathTmp.Vector3[0]);\n };\n /**\n * Returns a new Vector3 as the normalization of the given vector\n * @param vector defines the Vector3 to normalize\n * @returns the new Vector3\n */\n Vector3.Normalize = function (vector) {\n var result = Vector3.Zero();\n Vector3.NormalizeToRef(vector, result);\n return result;\n };\n /**\n * Sets the given vector \"result\" with the normalization of the given first vector\n * @param vector defines the Vector3 to normalize\n * @param result defines the Vector3 where to store the result\n */\n Vector3.NormalizeToRef = function (vector, result) {\n result.copyFrom(vector);\n result.normalize();\n };\n /**\n * Project a Vector3 onto screen space\n * @param vector defines the Vector3 to project\n * @param world defines the world matrix to use\n * @param transform defines the transform (view x projection) matrix to use\n * @param viewport defines the screen viewport to use\n * @returns the new Vector3\n */\n Vector3.Project = function (vector, world, transform, viewport) {\n var cw = viewport.width;\n var ch = viewport.height;\n var cx = viewport.x;\n var cy = viewport.y;\n var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());\n Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);\n var matrix = MathTmp.Matrix[0];\n world.multiplyToRef(transform, matrix);\n matrix.multiplyToRef(viewportMatrix, matrix);\n return Vector3.TransformCoordinates(vector, matrix);\n };\n /**\n * Unproject from screen space to object space\n * @param source defines the screen space Vector3 to use\n * @param viewportWidth defines the current width of the viewport\n * @param viewportHeight defines the current height of the viewport\n * @param world defines the world matrix to use (can be set to Identity to go to world space)\n * @param transform defines the transform (view x projection) matrix to use\n * @returns the new Vector3\n */\n Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {\n var matrix = MathTmp.Matrix[0];\n world.multiplyToRef(transform, matrix);\n matrix.invert();\n source.x = source.x / viewportWidth * 2 - 1;\n source.y = -(source.y / viewportHeight * 2 - 1);\n var vector = Vector3.TransformCoordinates(source, matrix);\n var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];\n if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {\n vector = vector.scale(1.0 / num);\n }\n return vector;\n };\n /**\n * Unproject from screen space to object space\n * @param source defines the screen space Vector3 to use\n * @param viewportWidth defines the current width of the viewport\n * @param viewportHeight defines the current height of the viewport\n * @param world defines the world matrix to use (can be set to Identity to go to world space)\n * @param view defines the view matrix to use\n * @param projection defines the projection matrix to use\n * @returns the new Vector3\n */\n Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {\n var result = Vector3.Zero();\n Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);\n return result;\n };\n /**\n * Unproject from screen space to object space\n * @param source defines the screen space Vector3 to use\n * @param viewportWidth defines the current width of the viewport\n * @param viewportHeight defines the current height of the viewport\n * @param world defines the world matrix to use (can be set to Identity to go to world space)\n * @param view defines the view matrix to use\n * @param projection defines the projection matrix to use\n * @param result defines the Vector3 where to store the result\n */\n Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {\n Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);\n };\n /**\n * Unproject from screen space to object space\n * @param sourceX defines the screen space x coordinate to use\n * @param sourceY defines the screen space y coordinate to use\n * @param sourceZ defines the screen space z coordinate to use\n * @param viewportWidth defines the current width of the viewport\n * @param viewportHeight defines the current height of the viewport\n * @param world defines the world matrix to use (can be set to Identity to go to world space)\n * @param view defines the view matrix to use\n * @param projection defines the projection matrix to use\n * @param result defines the Vector3 where to store the result\n */\n Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {\n var matrix = MathTmp.Matrix[0];\n world.multiplyToRef(view, matrix);\n matrix.multiplyToRef(projection, matrix);\n matrix.invert();\n var screenSource = MathTmp.Vector3[0];\n screenSource.x = sourceX / viewportWidth * 2 - 1;\n screenSource.y = -(sourceY / viewportHeight * 2 - 1);\n screenSource.z = 2 * sourceZ - 1.0;\n Vector3.TransformCoordinatesToRef(screenSource, matrix, result);\n var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];\n if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {\n result.scaleInPlace(1.0 / num);\n }\n };\n /**\n * Gets the minimal coordinate values between two Vector3\n * @param left defines the first operand\n * @param right defines the second operand\n * @returns the new Vector3\n */\n Vector3.Minimize = function (left, right) {\n var min = left.clone();\n min.minimizeInPlace(right);\n return min;\n };\n /**\n * Gets the maximal coordinate values between two Vector3\n * @param left defines the first operand\n * @param right defines the second operand\n * @returns the new Vector3\n */\n Vector3.Maximize = function (left, right) {\n var max = left.clone();\n max.maximizeInPlace(right);\n return max;\n };\n /**\n * Returns the distance between the vectors \"value1\" and \"value2\"\n * @param value1 defines the first operand\n * @param value2 defines the second operand\n * @returns the distance\n */\n Vector3.Distance = function (value1, value2) {\n return Math.sqrt(Vector3.DistanceSquared(value1, value2));\n };\n /**\n * Returns the squared distance between the vectors \"value1\" and \"value2\"\n * @param value1 defines the first operand\n * @param value2 defines the second operand\n * @returns the squared distance\n */\n Vector3.DistanceSquared = function (value1, value2) {\n var x = value1.x - value2.x;\n var y = value1.y - value2.y;\n var z = value1.z - value2.z;\n return (x * x) + (y * y) + (z * z);\n };\n /**\n * Returns a new Vector3 located at the center between \"value1\" and \"value2\"\n * @param value1 defines the first operand\n * @param value2 defines the second operand\n * @returns the new Vector3\n */\n Vector3.Center = function (value1, value2) {\n var center = value1.add(value2);\n center.scaleInPlace(0.5);\n return center;\n };\n /**\n * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),\n * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply\n * to something in order to rotate it from its local system to the given target system\n * Note: axis1, axis2 and axis3 are normalized during this operation\n * @param axis1 defines the first axis\n * @param axis2 defines the second axis\n * @param axis3 defines the third axis\n * @returns a new Vector3\n */\n Vector3.RotationFromAxis = function (axis1, axis2, axis3) {\n var rotation = Vector3.Zero();\n Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);\n return rotation;\n };\n /**\n * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3\n * @param axis1 defines the first axis\n * @param axis2 defines the second axis\n * @param axis3 defines the third axis\n * @param ref defines the Vector3 where to store the result\n */\n Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {\n var quat = MathTmp.Quaternion[0];\n Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);\n quat.toEulerAnglesToRef(ref);\n };\n return Vector3;\n }());\n BABYLON.Vector3 = Vector3;\n //Vector4 class created for EulerAngle class conversion to Quaternion\n var Vector4 = /** @class */ (function () {\n /**\n * Creates a Vector4 object from the given floats.\n */\n function Vector4(x, y, z, w) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n }\n /**\n * Returns the string with the Vector4 coordinates.\n */\n Vector4.prototype.toString = function () {\n return \"{X: \" + this.x + \" Y:\" + this.y + \" Z:\" + this.z + \" W:\" + this.w + \"}\";\n };\n /**\n * Returns the string \"Vector4\".\n */\n Vector4.prototype.getClassName = function () {\n return \"Vector4\";\n };\n /**\n * Returns the Vector4 hash code.\n */\n Vector4.prototype.getHashCode = function () {\n var hash = this.x || 0;\n hash = (hash * 397) ^ (this.y || 0);\n hash = (hash * 397) ^ (this.z || 0);\n hash = (hash * 397) ^ (this.w || 0);\n return hash;\n };\n // Operators\n /**\n * Returns a new array populated with 4 elements : the Vector4 coordinates.\n */\n Vector4.prototype.asArray = function () {\n var result = new Array();\n this.toArray(result, 0);\n return result;\n };\n /**\n * Populates the given array from the given index with the Vector4 coordinates.\n * Returns the Vector4.\n */\n Vector4.prototype.toArray = function (array, index) {\n if (index === undefined) {\n index = 0;\n }\n array[index] = this.x;\n array[index + 1] = this.y;\n array[index + 2] = this.z;\n array[index + 3] = this.w;\n return this;\n };\n /**\n * Adds the given vector to the current Vector4.\n * Returns the updated Vector4.\n */\n Vector4.prototype.addInPlace = function (otherVector) {\n this.x += otherVector.x;\n this.y += otherVector.y;\n this.z += otherVector.z;\n this.w += otherVector.w;\n return this;\n };\n /**\n * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.\n */\n Vector4.prototype.add = function (otherVector) {\n return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);\n };\n /**\n * Updates the given vector \"result\" with the result of the addition of the current Vector4 and the given one.\n * Returns the current Vector4.\n */\n Vector4.prototype.addToRef = function (otherVector, result) {\n result.x = this.x + otherVector.x;\n result.y = this.y + otherVector.y;\n result.z = this.z + otherVector.z;\n result.w = this.w + otherVector.w;\n return this;\n };\n /**\n * Subtract in place the given vector from the current Vector4.\n * Returns the updated Vector4.\n */\n Vector4.prototype.subtractInPlace = function (otherVector) {\n this.x -= otherVector.x;\n this.y -= otherVector.y;\n this.z -= otherVector.z;\n this.w -= otherVector.w;\n return this;\n };\n /**\n * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.\n */\n Vector4.prototype.subtract = function (otherVector) {\n return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);\n };\n /**\n * Sets the given vector \"result\" with the result of the subtraction of the given vector from the current Vector4.\n * Returns the current Vector4.\n */\n Vector4.prototype.subtractToRef = function (otherVector, result) {\n result.x = this.x - otherVector.x;\n result.y = this.y - otherVector.y;\n result.z = this.z - otherVector.z;\n result.w = this.w - otherVector.w;\n return this;\n };\n /**\n * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.\n */\n Vector4.prototype.subtractFromFloats = function (x, y, z, w) {\n return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);\n };\n /**\n * Sets the given vector \"result\" set with the result of the subtraction of the given floats from the current Vector4 coordinates.\n * Returns the current Vector4.\n */\n Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {\n result.x = this.x - x;\n result.y = this.y - y;\n result.z = this.z - z;\n result.w = this.w - w;\n return this;\n };\n /**\n * Returns a new Vector4 set with the current Vector4 negated coordinates.\n */\n Vector4.prototype.negate = function () {\n return new Vector4(-this.x, -this.y, -this.z, -this.w);\n };\n /**\n * Multiplies the current Vector4 coordinates by scale (float).\n * Returns the updated Vector4.\n */\n Vector4.prototype.scaleInPlace = function (scale) {\n this.x *= scale;\n this.y *= scale;\n this.z *= scale;\n this.w *= scale;\n return this;\n };\n /**\n * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).\n */\n Vector4.prototype.scale = function (scale) {\n return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);\n };\n /**\n * Sets the given vector \"result\" with the current Vector4 coordinates multiplied by scale (float).\n * Returns the current Vector4.\n */\n Vector4.prototype.scaleToRef = function (scale, result) {\n result.x = this.x * scale;\n result.y = this.y * scale;\n result.z = this.z * scale;\n result.w = this.w * scale;\n return this;\n };\n /**\n * Scale the current Vector4 values by a factor and add the result to a given Vector4\n * @param scale defines the scale factor\n * @param result defines the Vector4 object where to store the result\n * @returns the unmodified current Vector4\n */\n Vector4.prototype.scaleAndAddToRef = function (scale, result) {\n result.x += this.x * scale;\n result.y += this.y * scale;\n result.z += this.z * scale;\n result.w += this.w * scale;\n return this;\n };\n /**\n * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.\n */\n Vector4.prototype.equals = function (otherVector) {\n return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;\n };\n /**\n * Boolean : True if the current Vector4 coordinates are each beneath the distance \"epsilon\" from the given vector ones.\n */\n Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {\n if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }\n return otherVector\n && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)\n && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)\n && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)\n && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);\n };\n /**\n * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.\n */\n Vector4.prototype.equalsToFloats = function (x, y, z, w) {\n return this.x === x && this.y === y && this.z === z && this.w === w;\n };\n /**\n * Multiplies in place the current Vector4 by the given one.\n * Returns the updated Vector4.\n */\n Vector4.prototype.multiplyInPlace = function (otherVector) {\n this.x *= otherVector.x;\n this.y *= otherVector.y;\n this.z *= otherVector.z;\n this.w *= otherVector.w;\n return this;\n };\n /**\n * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.\n */\n Vector4.prototype.multiply = function (otherVector) {\n return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);\n };\n /**\n * Updates the given vector \"result\" with the multiplication result of the current Vector4 and the given one.\n * Returns the current Vector4.\n */\n Vector4.prototype.multiplyToRef = function (otherVector, result) {\n result.x = this.x * otherVector.x;\n result.y = this.y * otherVector.y;\n result.z = this.z * otherVector.z;\n result.w = this.w * otherVector.w;\n return this;\n };\n /**\n * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.\n */\n Vector4.prototype.multiplyByFloats = function (x, y, z, w) {\n return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);\n };\n /**\n * Returns a new Vector4 set with the division result of the current Vector4 by the given one.\n */\n Vector4.prototype.divide = function (otherVector) {\n return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);\n };\n /**\n * Updates the given vector \"result\" with the division result of the current Vector4 by the given one.\n * Returns the current Vector4.\n */\n Vector4.prototype.divideToRef = function (otherVector, result) {\n result.x = this.x / otherVector.x;\n result.y = this.y / otherVector.y;\n result.z = this.z / otherVector.z;\n result.w = this.w / otherVector.w;\n return this;\n };\n /**\n * Divides the current Vector3 coordinates by the given ones.\n * @returns the updated Vector3.\n */\n Vector4.prototype.divideInPlace = function (otherVector) {\n return this.divideToRef(otherVector, this);\n };\n /**\n * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones\n * @param other defines the second operand\n * @returns the current updated Vector4\n */\n Vector4.prototype.minimizeInPlace = function (other) {\n if (other.x < this.x)\n this.x = other.x;\n if (other.y < this.y)\n this.y = other.y;\n if (other.z < this.z)\n this.z = other.z;\n if (other.w < this.w)\n this.w = other.w;\n return this;\n };\n /**\n * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones\n * @param other defines the second operand\n * @returns the current updated Vector4\n */\n Vector4.prototype.maximizeInPlace = function (other) {\n if (other.x > this.x)\n this.x = other.x;\n if (other.y > this.y)\n this.y = other.y;\n if (other.z > this.z)\n this.z = other.z;\n if (other.w > this.w)\n this.w = other.w;\n return this;\n };\n /**\n * Gets a new Vector4 from current Vector4 floored values\n * @returns a new Vector4\n */\n Vector4.prototype.floor = function () {\n return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));\n };\n /**\n * Gets a new Vector4 from current Vector3 floored values\n * @returns a new Vector4\n */\n Vector4.prototype.fract = function () {\n return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));\n };\n // Properties\n /**\n * Returns the Vector4 length (float).\n */\n Vector4.prototype.length = function () {\n return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);\n };\n /**\n * Returns the Vector4 squared length (float).\n */\n Vector4.prototype.lengthSquared = function () {\n return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);\n };\n // Methods\n /**\n * Normalizes in place the Vector4.\n * Returns the updated Vector4.\n */\n Vector4.prototype.normalize = function () {\n var len = this.length();\n if (len === 0)\n return this;\n var num = 1.0 / len;\n this.x *= num;\n this.y *= num;\n this.z *= num;\n this.w *= num;\n return this;\n };\n /**\n * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.\n */\n Vector4.prototype.toVector3 = function () {\n return new Vector3(this.x, this.y, this.z);\n };\n /**\n * Returns a new Vector4 copied from the current one.\n */\n Vector4.prototype.clone = function () {\n return new Vector4(this.x, this.y, this.z, this.w);\n };\n /**\n * Updates the current Vector4 with the given one coordinates.\n * Returns the updated Vector4.\n */\n Vector4.prototype.copyFrom = function (source) {\n this.x = source.x;\n this.y = source.y;\n this.z = source.z;\n this.w = source.w;\n return this;\n };\n /**\n * Updates the current Vector4 coordinates with the given floats.\n * Returns the updated Vector4.\n */\n Vector4.prototype.copyFromFloats = function (x, y, z, w) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n return this;\n };\n /**\n * Updates the current Vector4 coordinates with the given floats.\n * Returns the updated Vector4.\n */\n Vector4.prototype.set = function (x, y, z, w) {\n return this.copyFromFloats(x, y, z, w);\n };\n // Statics\n /**\n * Returns a new Vector4 set from the starting index of the given array.\n */\n Vector4.FromArray = function (array, offset) {\n if (!offset) {\n offset = 0;\n }\n return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n };\n /**\n * Updates the given vector \"result\" from the starting index of the given array.\n */\n Vector4.FromArrayToRef = function (array, offset, result) {\n result.x = array[offset];\n result.y = array[offset + 1];\n result.z = array[offset + 2];\n result.w = array[offset + 3];\n };\n /**\n * Updates the given vector \"result\" from the starting index of the given Float32Array.\n */\n Vector4.FromFloatArrayToRef = function (array, offset, result) {\n Vector4.FromArrayToRef(array, offset, result);\n };\n /**\n * Updates the given vector \"result\" coordinates from the given floats.\n */\n Vector4.FromFloatsToRef = function (x, y, z, w, result) {\n result.x = x;\n result.y = y;\n result.z = z;\n result.w = w;\n };\n /**\n * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)\n */\n Vector4.Zero = function () {\n return new Vector4(0.0, 0.0, 0.0, 0.0);\n };\n /**\n * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)\n */\n Vector4.One = function () {\n return new Vector4(1.0, 1.0, 1.0, 1.0);\n };\n /**\n * Returns a new normalized Vector4 from the given one.\n */\n Vector4.Normalize = function (vector) {\n var result = Vector4.Zero();\n Vector4.NormalizeToRef(vector, result);\n return result;\n };\n /**\n * Updates the given vector \"result\" from the normalization of the given one.\n */\n Vector4.NormalizeToRef = function (vector, result) {\n result.copyFrom(vector);\n result.normalize();\n };\n Vector4.Minimize = function (left, right) {\n var min = left.clone();\n min.minimizeInPlace(right);\n return min;\n };\n Vector4.Maximize = function (left, right) {\n var max = left.clone();\n max.maximizeInPlace(right);\n return max;\n };\n /**\n * Returns the distance (float) between the vectors \"value1\" and \"value2\".\n */\n Vector4.Distance = function (value1, value2) {\n return Math.sqrt(Vector4.DistanceSquared(value1, value2));\n };\n /**\n * Returns the squared distance (float) between the vectors \"value1\" and \"value2\".\n */\n Vector4.DistanceSquared = function (value1, value2) {\n var x = value1.x - value2.x;\n var y = value1.y - value2.y;\n var z = value1.z - value2.z;\n var w = value1.w - value2.w;\n return (x * x) + (y * y) + (z * z) + (w * w);\n };\n /**\n * Returns a new Vector4 located at the center between the vectors \"value1\" and \"value2\".\n */\n Vector4.Center = function (value1, value2) {\n var center = value1.add(value2);\n center.scaleInPlace(0.5);\n return center;\n };\n /**\n * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.\n * This methods computes transformed normalized direction vectors only.\n */\n Vector4.TransformNormal = function (vector, transformation) {\n var result = Vector4.Zero();\n Vector4.TransformNormalToRef(vector, transformation, result);\n return result;\n };\n /**\n * Sets the given vector \"result\" with the result of the normal transformation by the given matrix of the given vector.\n * This methods computes transformed normalized direction vectors only.\n */\n Vector4.TransformNormalToRef = function (vector, transformation, result) {\n var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);\n var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);\n var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);\n result.x = x;\n result.y = y;\n result.z = z;\n result.w = vector.w;\n };\n /**\n * Sets the given vector \"result\" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).\n * This methods computes transformed normalized direction vectors only.\n */\n Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {\n result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);\n result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);\n result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);\n result.w = w;\n };\n return Vector4;\n }());\n BABYLON.Vector4 = Vector4;\n var Size = /** @class */ (function () {\n /**\n * Creates a Size object from the given width and height (floats).\n */\n function Size(width, height) {\n this.width = width;\n this.height = height;\n }\n // Returns a string with the Size width and height. \n Size.prototype.toString = function () {\n return \"{W: \" + this.width + \", H: \" + this.height + \"}\";\n };\n /**\n * Returns the string \"Size\"\n */\n Size.prototype.getClassName = function () {\n return \"Size\";\n };\n /**\n * Returns the Size hash code.\n */\n Size.prototype.getHashCode = function () {\n var hash = this.width || 0;\n hash = (hash * 397) ^ (this.height || 0);\n return hash;\n };\n /**\n * Updates the current size from the given one.\n * Returns the updated Size.\n */\n Size.prototype.copyFrom = function (src) {\n this.width = src.width;\n this.height = src.height;\n };\n /**\n * Updates in place the current Size from the given floats.\n * Returns the updated Size.\n */\n Size.prototype.copyFromFloats = function (width, height) {\n this.width = width;\n this.height = height;\n return this;\n };\n /**\n * Updates in place the current Size from the given floats.\n * Returns the updated Size.\n */\n Size.prototype.set = function (width, height) {\n return this.copyFromFloats(width, height);\n };\n /**\n * Returns a new Size set with the multiplication result of the current Size and the given floats.\n */\n Size.prototype.multiplyByFloats = function (w, h) {\n return new Size(this.width * w, this.height * h);\n };\n /**\n * Returns a new Size copied from the given one.\n */\n Size.prototype.clone = function () {\n return new Size(this.width, this.height);\n };\n /**\n * Boolean : True if the current Size and the given one width and height are strictly equal.\n */\n Size.prototype.equals = function (other) {\n if (!other) {\n return false;\n }\n return (this.width === other.width) && (this.height === other.height);\n };\n Object.defineProperty(Size.prototype, \"surface\", {\n /**\n * Returns the surface of the Size : width * height (float).\n */\n get: function () {\n return this.width * this.height;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a new Size set to (0.0, 0.0)\n */\n Size.Zero = function () {\n return new Size(0.0, 0.0);\n };\n /**\n * Returns a new Size set as the addition result of the current Size and the given one.\n */\n Size.prototype.add = function (otherSize) {\n var r = new Size(this.width + otherSize.width, this.height + otherSize.height);\n return r;\n };\n /**\n * Returns a new Size set as the subtraction result of the given one from the current Size.\n */\n Size.prototype.subtract = function (otherSize) {\n var r = new Size(this.width - otherSize.width, this.height - otherSize.height);\n return r;\n };\n /**\n * Returns a new Size set at the linear interpolation \"amount\" between \"start\" and \"end\".\n */\n Size.Lerp = function (start, end, amount) {\n var w = start.width + ((end.width - start.width) * amount);\n var h = start.height + ((end.height - start.height) * amount);\n return new Size(w, h);\n };\n return Size;\n }());\n BABYLON.Size = Size;\n /**\n * Class used to store quaternion data\n * @see https://en.wikipedia.org/wiki/Quaternion\n * @see http://doc.babylonjs.com/features/position,_rotation,_scaling\n */\n var Quaternion = /** @class */ (function () {\n /**\n * Creates a new Quaternion from the given floats\n * @param x defines the first component (0 by default)\n * @param y defines the second component (0 by default)\n * @param z defines the third component (0 by default)\n * @param w defines the fourth component (1.0 by default)\n */\n function Quaternion(\n /** defines the first component (0 by default) */\n x, \n /** defines the second component (0 by default) */\n y, \n /** defines the third component (0 by default) */\n z, \n /** defines the fourth component (1.0 by default) */\n w) {\n if (x === void 0) { x = 0.0; }\n if (y === void 0) { y = 0.0; }\n if (z === void 0) { z = 0.0; }\n if (w === void 0) { w = 1.0; }\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n }\n /**\n * Gets a string representation for the current quaternion\n * @returns a string with the Quaternion coordinates\n */\n Quaternion.prototype.toString = function () {\n return \"{X: \" + this.x + \" Y:\" + this.y + \" Z:\" + this.z + \" W:\" + this.w + \"}\";\n };\n /**\n * Gets the class name of the quaternion\n * @returns the string \"Quaternion\"\n */\n Quaternion.prototype.getClassName = function () {\n return \"Quaternion\";\n };\n /**\n * Gets a hash code for this quaternion\n * @returns the quaternion hash code\n */\n Quaternion.prototype.getHashCode = function () {\n var hash = this.x || 0;\n hash = (hash * 397) ^ (this.y || 0);\n hash = (hash * 397) ^ (this.z || 0);\n hash = (hash * 397) ^ (this.w || 0);\n return hash;\n };\n /**\n * Copy the quaternion to an array\n * @returns a new array populated with 4 elements from the quaternion coordinates\n */\n Quaternion.prototype.asArray = function () {\n return [this.x, this.y, this.z, this.w];\n };\n /**\n * Check if two quaternions are equals\n * @param otherQuaternion defines the second operand\n * @return true if the current quaternion and the given one coordinates are strictly equals\n */\n Quaternion.prototype.equals = function (otherQuaternion) {\n return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;\n };\n /**\n * Clone the current quaternion\n * @returns a new quaternion copied from the current one\n */\n Quaternion.prototype.clone = function () {\n return new Quaternion(this.x, this.y, this.z, this.w);\n };\n /**\n * Copy a quaternion to the current one\n * @param other defines the other quaternion\n * @returns the updated current quaternion\n */\n Quaternion.prototype.copyFrom = function (other) {\n this.x = other.x;\n this.y = other.y;\n this.z = other.z;\n this.w = other.w;\n return this;\n };\n /**\n * Updates the current quaternion with the given float coordinates\n * @param x defines the x coordinate\n * @param y defines the y coordinate\n * @param z defines the z coordinate\n * @param w defines the w coordinate\n * @returns the updated current quaternion\n */\n Quaternion.prototype.copyFromFloats = function (x, y, z, w) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n return this;\n };\n /**\n * Updates the current quaternion from the given float coordinates\n * @param x defines the x coordinate\n * @param y defines the y coordinate\n * @param z defines the z coordinate\n * @param w defines the w coordinate\n * @returns the updated current quaternion\n */\n Quaternion.prototype.set = function (x, y, z, w) {\n return this.copyFromFloats(x, y, z, w);\n };\n /**\n * Adds two quaternions\n * @param other defines the second operand\n * @returns a new quaternion as the addition result of the given one and the current quaternion\n */\n Quaternion.prototype.add = function (other) {\n return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);\n };\n /**\n * Add a quaternion to the current one\n * @param other defines the quaternion to add\n * @returns the current quaternion\n */\n Quaternion.prototype.addInPlace = function (other) {\n this.x += other.x;\n this.y += other.y;\n this.z += other.z;\n this.w += other.w;\n return this;\n };\n /**\n * Subtract two quaternions\n * @param other defines the second operand\n * @returns a new quaternion as the subtraction result of the given one from the current one\n */\n Quaternion.prototype.subtract = function (other) {\n return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);\n };\n /**\n * Multiplies the current quaternion by a scale factor\n * @param value defines the scale factor\n * @returns a new quaternion set by multiplying the current quaternion coordinates by the float \"scale\"\n */\n Quaternion.prototype.scale = function (value) {\n return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);\n };\n /**\n * Scale the current quaternion values by a factor and stores the result to a given quaternion\n * @param scale defines the scale factor\n * @param result defines the Quaternion object where to store the result\n * @returns the unmodified current quaternion\n */\n Quaternion.prototype.scaleToRef = function (scale, result) {\n result.x = this.x * scale;\n result.y = this.y * scale;\n result.z = this.z * scale;\n result.w = this.w * scale;\n return this;\n };\n /**\n * Multiplies in place the current quaternion by a scale factor\n * @param value defines the scale factor\n * @returns the current modified quaternion\n */\n Quaternion.prototype.scaleInPlace = function (value) {\n this.x *= value;\n this.y *= value;\n this.z *= value;\n this.w *= value;\n return this;\n };\n /**\n * Scale the current quaternion values by a factor and add the result to a given quaternion\n * @param scale defines the scale factor\n * @param result defines the Quaternion object where to store the result\n * @returns the unmodified current quaternion\n */\n Quaternion.prototype.scaleAndAddToRef = function (scale, result) {\n result.x += this.x * scale;\n result.y += this.y * scale;\n result.z += this.z * scale;\n result.w += this.w * scale;\n return this;\n };\n /**\n * Multiplies two quaternions\n * @param q1 defines the second operand\n * @returns a new quaternion set as the multiplication result of the current one with the given one \"q1\"\n */\n Quaternion.prototype.multiply = function (q1) {\n var result = new Quaternion(0, 0, 0, 1.0);\n this.multiplyToRef(q1, result);\n return result;\n };\n /**\n * Sets the given \"result\" as the the multiplication result of the current one with the given one \"q1\"\n * @param q1 defines the second operand\n * @param result defines the target quaternion\n * @returns the current quaternion\n */\n Quaternion.prototype.multiplyToRef = function (q1, result) {\n var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;\n var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;\n var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;\n var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;\n result.copyFromFloats(x, y, z, w);\n return this;\n };\n /**\n * Updates the current quaternion with the multiplication of itself with the given one \"q1\"\n * @param q1 defines the second operand\n * @returns the currentupdated quaternion\n */\n Quaternion.prototype.multiplyInPlace = function (q1) {\n this.multiplyToRef(q1, this);\n return this;\n };\n /**\n * Conjugates (1-q) the current quaternion and stores the result in the given quaternion\n * @param ref defines the target quaternion\n * @returns the current quaternion\n */\n Quaternion.prototype.conjugateToRef = function (ref) {\n ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);\n return this;\n };\n /**\n * Conjugates in place (1-q) the current quaternion\n * @returns the current updated quaternion\n */\n Quaternion.prototype.conjugateInPlace = function () {\n this.x *= -1;\n this.y *= -1;\n this.z *= -1;\n return this;\n };\n /**\n * Conjugates in place (1-q) the current quaternion\n * @returns a new quaternion\n */\n Quaternion.prototype.conjugate = function () {\n var result = new Quaternion(-this.x, -this.y, -this.z, this.w);\n return result;\n };\n /**\n * Gets length of current quaternion\n * @returns the quaternion length (float)\n */\n Quaternion.prototype.length = function () {\n return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));\n };\n /**\n * Normalize in place the current quaternion\n * @returns the current updated quaternion\n */\n Quaternion.prototype.normalize = function () {\n var length = 1.0 / this.length();\n this.x *= length;\n this.y *= length;\n this.z *= length;\n this.w *= length;\n return this;\n };\n /**\n * Returns a new Vector3 set with the Euler angles translated from the current quaternion\n * @param order is a reserved parameter and is ignore for now\n * @returns a new Vector3 containing the Euler angles\n */\n Quaternion.prototype.toEulerAngles = function (order) {\n if (order === void 0) { order = \"YZX\"; }\n var result = Vector3.Zero();\n this.toEulerAnglesToRef(result, order);\n return result;\n };\n /**\n * Sets the given vector3 \"result\" with the Euler angles translated from the current quaternion\n * @param result defines the vector which will be filled with the Euler angles\n * @param order is a reserved parameter and is ignore for now\n * @returns the current unchanged quaternion\n */\n Quaternion.prototype.toEulerAnglesToRef = function (result, order) {\n if (order === void 0) { order = \"YZX\"; }\n var qz = this.z;\n var qx = this.x;\n var qy = this.y;\n var qw = this.w;\n var sqw = qw * qw;\n var sqz = qz * qz;\n var sqx = qx * qx;\n var sqy = qy * qy;\n var zAxisY = qy * qz - qx * qw;\n var limit = .4999999;\n if (zAxisY < -limit) {\n result.y = 2 * Math.atan2(qy, qw);\n result.x = Math.PI / 2;\n result.z = 0;\n }\n else if (zAxisY > limit) {\n result.y = 2 * Math.atan2(qy, qw);\n result.x = -Math.PI / 2;\n result.z = 0;\n }\n else {\n result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));\n result.x = Math.asin(-2.0 * (qz * qy - qx * qw));\n result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));\n }\n return this;\n };\n /**\n * Updates the given rotation matrix with the current quaternion values\n * @param result defines the target matrix\n * @returns the current unchanged quaternion\n */\n Quaternion.prototype.toRotationMatrix = function (result) {\n var xx = this.x * this.x;\n var yy = this.y * this.y;\n var zz = this.z * this.z;\n var xy = this.x * this.y;\n var zw = this.z * this.w;\n var zx = this.z * this.x;\n var yw = this.y * this.w;\n var yz = this.y * this.z;\n var xw = this.x * this.w;\n result.m[0] = 1.0 - (2.0 * (yy + zz));\n result.m[1] = 2.0 * (xy + zw);\n result.m[2] = 2.0 * (zx - yw);\n result.m[3] = 0;\n result.m[4] = 2.0 * (xy - zw);\n result.m[5] = 1.0 - (2.0 * (zz + xx));\n result.m[6] = 2.0 * (yz + xw);\n result.m[7] = 0;\n result.m[8] = 2.0 * (zx + yw);\n result.m[9] = 2.0 * (yz - xw);\n result.m[10] = 1.0 - (2.0 * (yy + xx));\n result.m[11] = 0;\n result.m[12] = 0;\n result.m[13] = 0;\n result.m[14] = 0;\n result.m[15] = 1.0;\n result._markAsUpdated();\n return this;\n };\n /**\n * Updates the current quaternion from the given rotation matrix values\n * @param matrix defines the source matrix\n * @returns the current updated quaternion\n */\n Quaternion.prototype.fromRotationMatrix = function (matrix) {\n Quaternion.FromRotationMatrixToRef(matrix, this);\n return this;\n };\n // Statics\n /**\n * Creates a new quaternion from a rotation matrix\n * @param matrix defines the source matrix\n * @returns a new quaternion created from the given rotation matrix values\n */\n Quaternion.FromRotationMatrix = function (matrix) {\n var result = new Quaternion();\n Quaternion.FromRotationMatrixToRef(matrix, result);\n return result;\n };\n /**\n * Updates the given quaternion with the given rotation matrix values\n * @param matrix defines the source matrix\n * @param result defines the target quaternion\n */\n Quaternion.FromRotationMatrixToRef = function (matrix, result) {\n var data = matrix.m;\n var m11 = data[0], m12 = data[4], m13 = data[8];\n var m21 = data[1], m22 = data[5], m23 = data[9];\n var m31 = data[2], m32 = data[6], m33 = data[10];\n var trace = m11 + m22 + m33;\n var s;\n if (trace > 0) {\n s = 0.5 / Math.sqrt(trace + 1.0);\n result.w = 0.25 / s;\n result.x = (m32 - m23) * s;\n result.y = (m13 - m31) * s;\n result.z = (m21 - m12) * s;\n }\n else if (m11 > m22 && m11 > m33) {\n s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);\n result.w = (m32 - m23) / s;\n result.x = 0.25 * s;\n result.y = (m12 + m21) / s;\n result.z = (m13 + m31) / s;\n }\n else if (m22 > m33) {\n s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);\n result.w = (m13 - m31) / s;\n result.x = (m12 + m21) / s;\n result.y = 0.25 * s;\n result.z = (m23 + m32) / s;\n }\n else {\n s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);\n result.w = (m21 - m12) / s;\n result.x = (m13 + m31) / s;\n result.y = (m23 + m32) / s;\n result.z = 0.25 * s;\n }\n };\n /**\n * Returns the dot product (float) between the quaternions \"left\" and \"right\"\n * @param left defines the left operand\n * @param right defines the right operand\n * @returns the dot product\n */\n Quaternion.Dot = function (left, right) {\n return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);\n };\n /**\n * Checks if the two quaternions are close to each other\n * @param quat0 defines the first quaternion to check\n * @param quat1 defines the second quaternion to check\n * @returns true if the two quaternions are close to each other\n */\n Quaternion.AreClose = function (quat0, quat1) {\n var dot = Quaternion.Dot(quat0, quat1);\n return dot >= 0;\n };\n /**\n * Creates an empty quaternion\n * @returns a new quaternion set to (0.0, 0.0, 0.0)\n */\n Quaternion.Zero = function () {\n return new Quaternion(0.0, 0.0, 0.0, 0.0);\n };\n /**\n * Inverse a given quaternion\n * @param q defines the source quaternion\n * @returns a new quaternion as the inverted current quaternion\n */\n Quaternion.Inverse = function (q) {\n return new Quaternion(-q.x, -q.y, -q.z, q.w);\n };\n /**\n * Creates an identity quaternion\n * @returns the identity quaternion\n */\n Quaternion.Identity = function () {\n return new Quaternion(0.0, 0.0, 0.0, 1.0);\n };\n /**\n * Gets a boolean indicating if the given quaternion is identity\n * @param quaternion defines the quaternion to check\n * @returns true if the quaternion is identity\n */\n Quaternion.IsIdentity = function (quaternion) {\n return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;\n };\n /**\n * Creates a quaternion from a rotation around an axis\n * @param axis defines the axis to use\n * @param angle defines the angle to use\n * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)\n */\n Quaternion.RotationAxis = function (axis, angle) {\n return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());\n };\n /**\n * Creates a rotation around an axis and stores it into the given quaternion\n * @param axis defines the axis to use\n * @param angle defines the angle to use\n * @param result defines the target quaternion\n * @returns the target quaternion\n */\n Quaternion.RotationAxisToRef = function (axis, angle, result) {\n var sin = Math.sin(angle / 2);\n axis.normalize();\n result.w = Math.cos(angle / 2);\n result.x = axis.x * sin;\n result.y = axis.y * sin;\n result.z = axis.z * sin;\n return result;\n };\n /**\n * Creates a new quaternion from data stored into an array\n * @param array defines the data source\n * @param offset defines the offset in the source array where the data starts\n * @returns a new quaternion\n */\n Quaternion.FromArray = function (array, offset) {\n if (!offset) {\n offset = 0;\n }\n return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n };\n /**\n * Creates a new quaternion from the given Euler float angles (y, x, z)\n * @param yaw defines the rotation around Y axis\n * @param pitch defines the rotation around X axis\n * @param roll defines the rotation around Z axis\n * @returns the new quaternion\n */\n Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {\n var q = new Quaternion();\n Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);\n return q;\n };\n /**\n * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion\n * @param yaw defines the rotation around Y axis\n * @param pitch defines the rotation around X axis\n * @param roll defines the rotation around Z axis\n * @param result defines the target quaternion\n */\n Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {\n // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)\n var halfRoll = roll * 0.5;\n var halfPitch = pitch * 0.5;\n var halfYaw = yaw * 0.5;\n var sinRoll = Math.sin(halfRoll);\n var cosRoll = Math.cos(halfRoll);\n var sinPitch = Math.sin(halfPitch);\n var cosPitch = Math.cos(halfPitch);\n var sinYaw = Math.sin(halfYaw);\n var cosYaw = Math.cos(halfYaw);\n result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);\n result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);\n result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);\n result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);\n };\n /**\n * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation\n * @param alpha defines the rotation around first axis\n * @param beta defines the rotation around second axis\n * @param gamma defines the rotation around third axis\n * @returns the new quaternion\n */\n Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {\n var result = new Quaternion();\n Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);\n return result;\n };\n /**\n * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion\n * @param alpha defines the rotation around first axis\n * @param beta defines the rotation around second axis\n * @param gamma defines the rotation around third axis\n * @param result defines the target quaternion\n */\n Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {\n // Produces a quaternion from Euler angles in the z-x-z orientation\n var halfGammaPlusAlpha = (gamma + alpha) * 0.5;\n var halfGammaMinusAlpha = (gamma - alpha) * 0.5;\n var halfBeta = beta * 0.5;\n result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);\n result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);\n result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);\n result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);\n };\n /**\n * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)\n * @param axis1 defines the first axis\n * @param axis2 defines the second axis\n * @param axis3 defines the third axis\n * @returns the new quaternion\n */\n Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {\n var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);\n Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);\n return quat;\n };\n /**\n * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion\n * @param axis1 defines the first axis\n * @param axis2 defines the second axis\n * @param axis3 defines the third axis\n * @param ref defines the target quaternion\n */\n Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {\n var rotMat = MathTmp.Matrix[0];\n Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);\n Quaternion.FromRotationMatrixToRef(rotMat, ref);\n };\n /**\n * Interpolates between two quaternions\n * @param left defines first quaternion\n * @param right defines second quaternion\n * @param amount defines the gradient to use\n * @returns the new interpolated quaternion\n */\n Quaternion.Slerp = function (left, right, amount) {\n var result = Quaternion.Identity();\n Quaternion.SlerpToRef(left, right, amount, result);\n return result;\n };\n /**\n * Interpolates between two quaternions and stores it into a target quaternion\n * @param left defines first quaternion\n * @param right defines second quaternion\n * @param amount defines the gradient to use\n * @param result defines the target quaternion\n */\n Quaternion.SlerpToRef = function (left, right, amount, result) {\n var num2;\n var num3;\n var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);\n var flag = false;\n if (num4 < 0) {\n flag = true;\n num4 = -num4;\n }\n if (num4 > 0.999999) {\n num3 = 1 - amount;\n num2 = flag ? -amount : amount;\n }\n else {\n var num5 = Math.acos(num4);\n var num6 = (1.0 / Math.sin(num5));\n num3 = (Math.sin((1.0 - amount) * num5)) * num6;\n num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);\n }\n result.x = (num3 * left.x) + (num2 * right.x);\n result.y = (num3 * left.y) + (num2 * right.y);\n result.z = (num3 * left.z) + (num2 * right.z);\n result.w = (num3 * left.w) + (num2 * right.w);\n };\n /**\n * Interpolate between two quaternions using Hermite interpolation\n * @param value1 defines first quaternion\n * @param tangent1 defines the incoming tangent\n * @param value2 defines second quaternion\n * @param tangent2 defines the outgoing tangent\n * @param amount defines the target quaternion\n * @returns the new interpolated quaternion\n */\n Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {\n var squared = amount * amount;\n var cubed = amount * squared;\n var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;\n var part2 = (-2.0 * cubed) + (3.0 * squared);\n var part3 = (cubed - (2.0 * squared)) + amount;\n var part4 = cubed - squared;\n var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);\n var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);\n var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);\n var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);\n return new Quaternion(x, y, z, w);\n };\n return Quaternion;\n }());\n BABYLON.Quaternion = Quaternion;\n /**\n * Class used to store matrix data (4x4)\n */\n var Matrix = /** @class */ (function () {\n /**\n * Creates an empty matrix (filled with zeros)\n */\n function Matrix() {\n this._isIdentity = false;\n this._isIdentityDirty = true;\n /**\n * Gets or sets the internal data of the matrix\n */\n this.m = new Float32Array(16);\n this._markAsUpdated();\n }\n /** @hidden */\n Matrix.prototype._markAsUpdated = function () {\n this.updateFlag = Matrix._updateFlagSeed++;\n this._isIdentityDirty = true;\n };\n // Properties\n /**\n * Check if the current matrix is indentity\n * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)\n * @returns true is the matrix is the identity matrix\n */\n Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {\n if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }\n if (this._isIdentityDirty) {\n this._isIdentityDirty = false;\n if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {\n this._isIdentity = false;\n }\n else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||\n this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||\n this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||\n this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {\n this._isIdentity = false;\n }\n else {\n this._isIdentity = true;\n }\n if (!considerAsTextureMatrix && this.m[10] !== 1.0) {\n this._isIdentity = false;\n }\n }\n return this._isIdentity;\n };\n /**\n * Gets the determinant of the matrix\n * @returns the matrix determinant\n */\n Matrix.prototype.determinant = function () {\n var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);\n var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);\n var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);\n var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);\n var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);\n var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);\n return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -\n (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -\n (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));\n };\n // Methods\n /**\n * Returns the matrix as a Float32Array\n * @returns the matrix underlying array\n */\n Matrix.prototype.toArray = function () {\n return this.m;\n };\n /**\n * Returns the matrix as a Float32Array\n * @returns the matrix underlying array.\n */\n Matrix.prototype.asArray = function () {\n return this.toArray();\n };\n /**\n * Inverts the current matrix in place\n * @returns the current inverted matrix\n */\n Matrix.prototype.invert = function () {\n this.invertToRef(this);\n return this;\n };\n /**\n * Sets all the matrix elements to zero\n * @returns the current matrix\n */\n Matrix.prototype.reset = function () {\n for (var index = 0; index < 16; index++) {\n this.m[index] = 0.0;\n }\n this._markAsUpdated();\n return this;\n };\n /**\n * Adds the current matrix with a second one\n * @param other defines the matrix to add\n * @returns a new matrix as the addition of the current matrix and the given one\n */\n Matrix.prototype.add = function (other) {\n var result = new Matrix();\n this.addToRef(other, result);\n return result;\n };\n /**\n * Sets the given matrix \"result\" to the addition of the current matrix and the given one\n * @param other defines the matrix to add\n * @param result defines the target matrix\n * @returns the current matrix\n */\n Matrix.prototype.addToRef = function (other, result) {\n for (var index = 0; index < 16; index++) {\n result.m[index] = this.m[index] + other.m[index];\n }\n result._markAsUpdated();\n return this;\n };\n /**\n * Adds in place the given matrix to the current matrix\n * @param other defines the second operand\n * @returns the current updated matrix\n */\n Matrix.prototype.addToSelf = function (other) {\n for (var index = 0; index < 16; index++) {\n this.m[index] += other.m[index];\n }\n this._markAsUpdated();\n return this;\n };\n /**\n * Sets the given matrix to the current inverted Matrix\n * @param other defines the target matrix\n * @returns the unmodified current matrix\n */\n Matrix.prototype.invertToRef = function (other) {\n var l1 = this.m[0];\n var l2 = this.m[1];\n var l3 = this.m[2];\n var l4 = this.m[3];\n var l5 = this.m[4];\n var l6 = this.m[5];\n var l7 = this.m[6];\n var l8 = this.m[7];\n var l9 = this.m[8];\n var l10 = this.m[9];\n var l11 = this.m[10];\n var l12 = this.m[11];\n var l13 = this.m[12];\n var l14 = this.m[13];\n var l15 = this.m[14];\n var l16 = this.m[15];\n var l17 = (l11 * l16) - (l12 * l15);\n var l18 = (l10 * l16) - (l12 * l14);\n var l19 = (l10 * l15) - (l11 * l14);\n var l20 = (l9 * l16) - (l12 * l13);\n var l21 = (l9 * l15) - (l11 * l13);\n var l22 = (l9 * l14) - (l10 * l13);\n var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);\n var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));\n var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);\n var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));\n var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));\n var l28 = (l7 * l16) - (l8 * l15);\n var l29 = (l6 * l16) - (l8 * l14);\n var l30 = (l6 * l15) - (l7 * l14);\n var l31 = (l5 * l16) - (l8 * l13);\n var l32 = (l5 * l15) - (l7 * l13);\n var l33 = (l5 * l14) - (l6 * l13);\n var l34 = (l7 * l12) - (l8 * l11);\n var l35 = (l6 * l12) - (l8 * l10);\n var l36 = (l6 * l11) - (l7 * l10);\n var l37 = (l5 * l12) - (l8 * l9);\n var l38 = (l5 * l11) - (l7 * l9);\n var l39 = (l5 * l10) - (l6 * l9);\n other.m[0] = l23 * l27;\n other.m[4] = l24 * l27;\n other.m[8] = l25 * l27;\n other.m[12] = l26 * l27;\n other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;\n other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;\n other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;\n other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;\n other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;\n other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;\n other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;\n other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;\n other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;\n other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;\n other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;\n other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;\n other._markAsUpdated();\n return this;\n };\n /**\n * Inserts the translation vector (using 3 floats) in the current matrix\n * @param x defines the 1st component of the translation\n * @param y defines the 2nd component of the translation\n * @param z defines the 3rd component of the translation\n * @returns the current updated matrix\n */\n Matrix.prototype.setTranslationFromFloats = function (x, y, z) {\n this.m[12] = x;\n this.m[13] = y;\n this.m[14] = z;\n this._markAsUpdated();\n return this;\n };\n /**\n * Inserts the translation vector in the current matrix\n * @param vector3 defines the translation to insert\n * @returns the current updated matrix\n */\n Matrix.prototype.setTranslation = function (vector3) {\n this.m[12] = vector3.x;\n this.m[13] = vector3.y;\n this.m[14] = vector3.z;\n this._markAsUpdated();\n return this;\n };\n /**\n * Gets the translation value of the current matrix\n * @returns a new Vector3 as the extracted translation from the matrix\n */\n Matrix.prototype.getTranslation = function () {\n return new Vector3(this.m[12], this.m[13], this.m[14]);\n };\n /**\n * Fill a Vector3 with the extracted translation from the matrix\n * @param result defines the Vector3 where to store the translation\n * @returns the current matrix\n */\n Matrix.prototype.getTranslationToRef = function (result) {\n result.x = this.m[12];\n result.y = this.m[13];\n result.z = this.m[14];\n return this;\n };\n /**\n * Remove rotation and scaling part from the matrix\n * @returns the updated matrix\n */\n Matrix.prototype.removeRotationAndScaling = function () {\n this.setRowFromFloats(0, 1, 0, 0, 0);\n this.setRowFromFloats(1, 0, 1, 0, 0);\n this.setRowFromFloats(2, 0, 0, 1, 0);\n return this;\n };\n /**\n * Multiply two matrices\n * @param other defines the second operand\n * @returns a new matrix set with the multiplication result of the current Matrix and the given one\n */\n Matrix.prototype.multiply = function (other) {\n var result = new Matrix();\n this.multiplyToRef(other, result);\n return result;\n };\n /**\n * Copy the current matrix from the given one\n * @param other defines the source matrix\n * @returns the current updated matrix\n */\n Matrix.prototype.copyFrom = function (other) {\n for (var index = 0; index < 16; index++) {\n this.m[index] = other.m[index];\n }\n this._markAsUpdated();\n return this;\n };\n /**\n * Populates the given array from the starting index with the current matrix values\n * @param array defines the target array\n * @param offset defines the offset in the target array where to start storing values\n * @returns the current matrix\n */\n Matrix.prototype.copyToArray = function (array, offset) {\n if (offset === void 0) { offset = 0; }\n for (var index = 0; index < 16; index++) {\n array[offset + index] = this.m[index];\n }\n return this;\n };\n /**\n * Sets the given matrix \"result\" with the multiplication result of the current Matrix and the given one\n * @param other defines the second operand\n * @param result defines the matrix where to store the multiplication\n * @returns the current matrix\n */\n Matrix.prototype.multiplyToRef = function (other, result) {\n this.multiplyToArray(other, result.m, 0);\n result._markAsUpdated();\n return this;\n };\n /**\n * Sets the Float32Array \"result\" from the given index \"offset\" with the multiplication of the current matrix and the given one\n * @param other defines the second operand\n * @param result defines the array where to store the multiplication\n * @param offset defines the offset in the target array where to start storing values\n * @returns the current matrix\n */\n Matrix.prototype.multiplyToArray = function (other, result, offset) {\n var tm0 = this.m[0];\n var tm1 = this.m[1];\n var tm2 = this.m[2];\n var tm3 = this.m[3];\n var tm4 = this.m[4];\n var tm5 = this.m[5];\n var tm6 = this.m[6];\n var tm7 = this.m[7];\n var tm8 = this.m[8];\n var tm9 = this.m[9];\n var tm10 = this.m[10];\n var tm11 = this.m[11];\n var tm12 = this.m[12];\n var tm13 = this.m[13];\n var tm14 = this.m[14];\n var tm15 = this.m[15];\n var om0 = other.m[0];\n var om1 = other.m[1];\n var om2 = other.m[2];\n var om3 = other.m[3];\n var om4 = other.m[4];\n var om5 = other.m[5];\n var om6 = other.m[6];\n var om7 = other.m[7];\n var om8 = other.m[8];\n var om9 = other.m[9];\n var om10 = other.m[10];\n var om11 = other.m[11];\n var om12 = other.m[12];\n var om13 = other.m[13];\n var om14 = other.m[14];\n var om15 = other.m[15];\n result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;\n result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;\n result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;\n result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;\n result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;\n result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;\n result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;\n result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;\n result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;\n result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;\n result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;\n result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;\n result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;\n result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;\n result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;\n result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;\n return this;\n };\n /**\n * Check equality between this matrix and a second one\n * @param value defines the second matrix to compare\n * @returns true is the current matrix and the given one values are strictly equal\n */\n Matrix.prototype.equals = function (value) {\n return value &&\n (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&\n this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&\n this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&\n this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);\n };\n /**\n * Clone the current matrix\n * @returns a new matrix from the current matrix\n */\n Matrix.prototype.clone = function () {\n return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);\n };\n /**\n * Returns the name of the current matrix class\n * @returns the string \"Matrix\"\n */\n Matrix.prototype.getClassName = function () {\n return \"Matrix\";\n };\n /**\n * Gets the hash code of the current matrix\n * @returns the hash code\n */\n Matrix.prototype.getHashCode = function () {\n var hash = this.m[0] || 0;\n for (var i = 1; i < 16; i++) {\n hash = (hash * 397) ^ (this.m[i] || 0);\n }\n return hash;\n };\n /**\n * Decomposes the current Matrix into a translation, rotation and scaling components\n * @param scale defines the scale vector3 given as a reference to update\n * @param rotation defines the rotation quaternion given as a reference to update\n * @param translation defines the translation vector3 given as a reference to update\n * @returns true if operation was successful\n */\n Matrix.prototype.decompose = function (scale, rotation, translation) {\n if (translation) {\n translation.x = this.m[12];\n translation.y = this.m[13];\n translation.z = this.m[14];\n }\n scale = scale || MathTmp.Vector3[0];\n scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);\n scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);\n scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);\n if (this.determinant() <= 0) {\n scale.y *= -1;\n }\n if (scale.x === 0 || scale.y === 0 || scale.z === 0) {\n if (rotation) {\n rotation.x = 0;\n rotation.y = 0;\n rotation.z = 0;\n rotation.w = 1;\n }\n return false;\n }\n if (rotation) {\n Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);\n Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);\n }\n return true;\n };\n /**\n * Gets specific row of the matrix\n * @param index defines the number of the row to get\n * @returns the index-th row of the current matrix as a new Vector4\n */\n Matrix.prototype.getRow = function (index) {\n if (index < 0 || index > 3) {\n return null;\n }\n var i = index * 4;\n return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);\n };\n /**\n * Sets the index-th row of the current matrix to the vector4 values\n * @param index defines the number of the row to set\n * @param row defines the target vector4\n * @returns the updated current matrix\n */\n Matrix.prototype.setRow = function (index, row) {\n if (index < 0 || index > 3) {\n return this;\n }\n var i = index * 4;\n this.m[i + 0] = row.x;\n this.m[i + 1] = row.y;\n this.m[i + 2] = row.z;\n this.m[i + 3] = row.w;\n this._markAsUpdated();\n return this;\n };\n /**\n * Compute the transpose of the matrix\n * @returns the new transposed matrix\n */\n Matrix.prototype.transpose = function () {\n return Matrix.Transpose(this);\n };\n /**\n * Compute the transpose of the matrix and store it in a given matrix\n * @param result defines the target matrix\n * @returns the current matrix\n */\n Matrix.prototype.transposeToRef = function (result) {\n Matrix.TransposeToRef(this, result);\n return this;\n };\n /**\n * Sets the index-th row of the current matrix with the given 4 x float values\n * @param index defines the row index\n * @param x defines the x component to set\n * @param y defines the y component to set\n * @param z defines the z component to set\n * @param w defines the w component to set\n * @returns the updated current matrix\n */\n Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {\n if (index < 0 || index > 3) {\n return this;\n }\n var i = index * 4;\n this.m[i + 0] = x;\n this.m[i + 1] = y;\n this.m[i + 2] = z;\n this.m[i + 3] = w;\n this._markAsUpdated();\n return this;\n };\n /**\n * Compute a new matrix set with the current matrix values multiplied by scale (float)\n * @param scale defines the scale factor\n * @returns a new matrix\n */\n Matrix.prototype.scale = function (scale) {\n var result = new Matrix();\n this.scaleToRef(scale, result);\n return result;\n };\n /**\n * Scale the current matrix values by a factor to a given result matrix\n * @param scale defines the scale factor\n * @param result defines the matrix to store the result\n * @returns the current matrix\n */\n Matrix.prototype.scaleToRef = function (scale, result) {\n for (var index = 0; index < 16; index++) {\n result.m[index] = this.m[index] * scale;\n }\n result._markAsUpdated();\n return this;\n };\n /**\n * Scale the current matrix values by a factor and add the result to a given matrix\n * @param scale defines the scale factor\n * @param result defines the Matrix to store the result\n * @returns the current matrix\n */\n Matrix.prototype.scaleAndAddToRef = function (scale, result) {\n for (var index = 0; index < 16; index++) {\n result.m[index] += this.m[index] * scale;\n }\n result._markAsUpdated();\n return this;\n };\n /**\n * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).\n * @param ref matrix to store the result\n */\n Matrix.prototype.toNormalMatrix = function (ref) {\n this.invertToRef(ref);\n ref.transpose();\n var m = ref.m;\n Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);\n };\n /**\n * Gets only rotation part of the current matrix\n * @returns a new matrix sets to the extracted rotation matrix from the current one\n */\n Matrix.prototype.getRotationMatrix = function () {\n var result = Matrix.Identity();\n this.getRotationMatrixToRef(result);\n return result;\n };\n /**\n * Extracts the rotation matrix from the current one and sets it as the given \"result\"\n * @param result defines the target matrix to store data to\n * @returns the current matrix\n */\n Matrix.prototype.getRotationMatrixToRef = function (result) {\n var m = this.m;\n var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);\n var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);\n var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);\n if (this.determinant() <= 0) {\n sy *= -1;\n }\n if (sx === 0 || sy === 0 || sz === 0) {\n Matrix.IdentityToRef(result);\n }\n else {\n Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);\n }\n return this;\n };\n // Statics\n /**\n * Creates a matrix from an array\n * @param array defines the source array\n * @param offset defines an offset in the source array\n * @returns a new Matrix set from the starting index of the given array\n */\n Matrix.FromArray = function (array, offset) {\n var result = new Matrix();\n if (!offset) {\n offset = 0;\n }\n Matrix.FromArrayToRef(array, offset, result);\n return result;\n };\n /**\n * Copy the content of an array into a given matrix\n * @param array defines the source array\n * @param offset defines an offset in the source array\n * @param result defines the target matrix\n */\n Matrix.FromArrayToRef = function (array, offset, result) {\n for (var index = 0; index < 16; index++) {\n result.m[index] = array[index + offset];\n }\n result._markAsUpdated();\n };\n /**\n * Stores an array into a matrix after having multiplied each component by a given factor\n * @param array defines the source array\n * @param offset defines the offset in the source array\n * @param scale defines the scaling factor\n * @param result defines the target matrix\n */\n Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {\n for (var index = 0; index < 16; index++) {\n result.m[index] = array[index + offset] * scale;\n }\n result._markAsUpdated();\n };\n /**\n * Stores a list of values (16) inside a given matrix\n * @param initialM11 defines 1st value of 1st row\n * @param initialM12 defines 2nd value of 1st row\n * @param initialM13 defines 3rd value of 1st row\n * @param initialM14 defines 4th value of 1st row\n * @param initialM21 defines 1st value of 2nd row\n * @param initialM22 defines 2nd value of 2nd row\n * @param initialM23 defines 3rd value of 2nd row\n * @param initialM24 defines 4th value of 2nd row\n * @param initialM31 defines 1st value of 3rd row\n * @param initialM32 defines 2nd value of 3rd row\n * @param initialM33 defines 3rd value of 3rd row\n * @param initialM34 defines 4th value of 3rd row\n * @param initialM41 defines 1st value of 4th row\n * @param initialM42 defines 2nd value of 4th row\n * @param initialM43 defines 3rd value of 4th row\n * @param initialM44 defines 4th value of 4th row\n * @param result defines the target matrix\n */\n Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {\n result.m[0] = initialM11;\n result.m[1] = initialM12;\n result.m[2] = initialM13;\n result.m[3] = initialM14;\n result.m[4] = initialM21;\n result.m[5] = initialM22;\n result.m[6] = initialM23;\n result.m[7] = initialM24;\n result.m[8] = initialM31;\n result.m[9] = initialM32;\n result.m[10] = initialM33;\n result.m[11] = initialM34;\n result.m[12] = initialM41;\n result.m[13] = initialM42;\n result.m[14] = initialM43;\n result.m[15] = initialM44;\n result._markAsUpdated();\n };\n Object.defineProperty(Matrix, \"IdentityReadOnly\", {\n /**\n * Gets an identity matrix that must not be updated\n */\n get: function () {\n return Matrix._identityReadOnly;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Creates new matrix from a list of values (16)\n * @param initialM11 defines 1st value of 1st row\n * @param initialM12 defines 2nd value of 1st row\n * @param initialM13 defines 3rd value of 1st row\n * @param initialM14 defines 4th value of 1st row\n * @param initialM21 defines 1st value of 2nd row\n * @param initialM22 defines 2nd value of 2nd row\n * @param initialM23 defines 3rd value of 2nd row\n * @param initialM24 defines 4th value of 2nd row\n * @param initialM31 defines 1st value of 3rd row\n * @param initialM32 defines 2nd value of 3rd row\n * @param initialM33 defines 3rd value of 3rd row\n * @param initialM34 defines 4th value of 3rd row\n * @param initialM41 defines 1st value of 4th row\n * @param initialM42 defines 2nd value of 4th row\n * @param initialM43 defines 3rd value of 4th row\n * @param initialM44 defines 4th value of 4th row\n * @returns the new matrix\n */\n Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {\n var result = new Matrix();\n result.m[0] = initialM11;\n result.m[1] = initialM12;\n result.m[2] = initialM13;\n result.m[3] = initialM14;\n result.m[4] = initialM21;\n result.m[5] = initialM22;\n result.m[6] = initialM23;\n result.m[7] = initialM24;\n result.m[8] = initialM31;\n result.m[9] = initialM32;\n result.m[10] = initialM33;\n result.m[11] = initialM34;\n result.m[12] = initialM41;\n result.m[13] = initialM42;\n result.m[14] = initialM43;\n result.m[15] = initialM44;\n return result;\n };\n /**\n * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)\n * @param scale defines the scale vector3\n * @param rotation defines the rotation quaternion\n * @param translation defines the translation vector3\n * @returns a new matrix\n */\n Matrix.Compose = function (scale, rotation, translation) {\n var result = Matrix.Identity();\n Matrix.ComposeToRef(scale, rotation, translation, result);\n return result;\n };\n /**\n * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)\n * @param scale defines the scale vector3\n * @param rotation defines the rotation quaternion\n * @param translation defines the translation vector3\n * @param result defines the target matrix\n */\n Matrix.ComposeToRef = function (scale, rotation, translation, result) {\n Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);\n rotation.toRotationMatrix(MathTmp.Matrix[0]);\n MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);\n result.setTranslation(translation);\n };\n /**\n * Creates a new identity matrix\n * @returns a new identity matrix\n */\n Matrix.Identity = function () {\n return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n };\n /**\n * Creates a new identity matrix and stores the result in a given matrix\n * @param result defines the target matrix\n */\n Matrix.IdentityToRef = function (result) {\n Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);\n };\n /**\n * Creates a new zero matrix\n * @returns a new zero matrix\n */\n Matrix.Zero = function () {\n return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the X axis\n * @param angle defines the angle (in radians) to use\n * @return the new matrix\n */\n Matrix.RotationX = function (angle) {\n var result = new Matrix();\n Matrix.RotationXToRef(angle, result);\n return result;\n };\n /**\n * Creates a new matrix as the invert of a given matrix\n * @param source defines the source matrix\n * @returns the new matrix\n */\n Matrix.Invert = function (source) {\n var result = new Matrix();\n source.invertToRef(result);\n return result;\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the X axis and stores it in a given matrix\n * @param angle defines the angle (in radians) to use\n * @param result defines the target matrix\n */\n Matrix.RotationXToRef = function (angle, result) {\n var s = Math.sin(angle);\n var c = Math.cos(angle);\n result.m[0] = 1.0;\n result.m[15] = 1.0;\n result.m[5] = c;\n result.m[10] = c;\n result.m[9] = -s;\n result.m[6] = s;\n result.m[1] = 0.0;\n result.m[2] = 0.0;\n result.m[3] = 0.0;\n result.m[4] = 0.0;\n result.m[7] = 0.0;\n result.m[8] = 0.0;\n result.m[11] = 0.0;\n result.m[12] = 0.0;\n result.m[13] = 0.0;\n result.m[14] = 0.0;\n result._markAsUpdated();\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the Y axis\n * @param angle defines the angle (in radians) to use\n * @return the new matrix\n */\n Matrix.RotationY = function (angle) {\n var result = new Matrix();\n Matrix.RotationYToRef(angle, result);\n return result;\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the Y axis and stores it in a given matrix\n * @param angle defines the angle (in radians) to use\n * @param result defines the target matrix\n */\n Matrix.RotationYToRef = function (angle, result) {\n var s = Math.sin(angle);\n var c = Math.cos(angle);\n result.m[5] = 1.0;\n result.m[15] = 1.0;\n result.m[0] = c;\n result.m[2] = -s;\n result.m[8] = s;\n result.m[10] = c;\n result.m[1] = 0.0;\n result.m[3] = 0.0;\n result.m[4] = 0.0;\n result.m[6] = 0.0;\n result.m[7] = 0.0;\n result.m[9] = 0.0;\n result.m[11] = 0.0;\n result.m[12] = 0.0;\n result.m[13] = 0.0;\n result.m[14] = 0.0;\n result._markAsUpdated();\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the Z axis\n * @param angle defines the angle (in radians) to use\n * @return the new matrix\n */\n Matrix.RotationZ = function (angle) {\n var result = new Matrix();\n Matrix.RotationZToRef(angle, result);\n return result;\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the Z axis and stores it in a given matrix\n * @param angle defines the angle (in radians) to use\n * @param result defines the target matrix\n */\n Matrix.RotationZToRef = function (angle, result) {\n var s = Math.sin(angle);\n var c = Math.cos(angle);\n result.m[10] = 1.0;\n result.m[15] = 1.0;\n result.m[0] = c;\n result.m[1] = s;\n result.m[4] = -s;\n result.m[5] = c;\n result.m[2] = 0.0;\n result.m[3] = 0.0;\n result.m[6] = 0.0;\n result.m[7] = 0.0;\n result.m[8] = 0.0;\n result.m[9] = 0.0;\n result.m[11] = 0.0;\n result.m[12] = 0.0;\n result.m[13] = 0.0;\n result.m[14] = 0.0;\n result._markAsUpdated();\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the given axis\n * @param axis defines the axis to use\n * @param angle defines the angle (in radians) to use\n * @return the new matrix\n */\n Matrix.RotationAxis = function (axis, angle) {\n var result = Matrix.Zero();\n Matrix.RotationAxisToRef(axis, angle, result);\n return result;\n };\n /**\n * Creates a new rotation matrix for \"angle\" radians around the given axis and stores it in a given matrix\n * @param axis defines the axis to use\n * @param angle defines the angle (in radians) to use\n * @param result defines the target matrix\n */\n Matrix.RotationAxisToRef = function (axis, angle, result) {\n var s = Math.sin(-angle);\n var c = Math.cos(-angle);\n var c1 = 1 - c;\n axis.normalize();\n result.m[0] = (axis.x * axis.x) * c1 + c;\n result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);\n result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);\n result.m[3] = 0.0;\n result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);\n result.m[5] = (axis.y * axis.y) * c1 + c;\n result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);\n result.m[7] = 0.0;\n result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);\n result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);\n result.m[10] = (axis.z * axis.z) * c1 + c;\n result.m[11] = 0.0;\n result.m[15] = 1.0;\n result._markAsUpdated();\n };\n /**\n * Creates a rotation matrix\n * @param yaw defines the yaw angle in radians (Y axis)\n * @param pitch defines the pitch angle in radians (X axis)\n * @param roll defines the roll angle in radians (X axis)\n * @returns the new rotation matrix\n */\n Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {\n var result = new Matrix();\n Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);\n return result;\n };\n /**\n * Creates a rotation matrix and stores it in a given matrix\n * @param yaw defines the yaw angle in radians (Y axis)\n * @param pitch defines the pitch angle in radians (X axis)\n * @param roll defines the roll angle in radians (X axis)\n * @param result defines the target matrix\n */\n Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {\n Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);\n this._tempQuaternion.toRotationMatrix(result);\n };\n /**\n * Creates a scaling matrix\n * @param x defines the scale factor on X axis\n * @param y defines the scale factor on Y axis\n * @param z defines the scale factor on Z axis\n * @returns the new matrix\n */\n Matrix.Scaling = function (x, y, z) {\n var result = Matrix.Zero();\n Matrix.ScalingToRef(x, y, z, result);\n return result;\n };\n /**\n * Creates a scaling matrix and stores it in a given matrix\n * @param x defines the scale factor on X axis\n * @param y defines the scale factor on Y axis\n * @param z defines the scale factor on Z axis\n * @param result defines the target matrix\n */\n Matrix.ScalingToRef = function (x, y, z, result) {\n result.m[0] = x;\n result.m[1] = 0.0;\n result.m[2] = 0.0;\n result.m[3] = 0.0;\n result.m[4] = 0.0;\n result.m[5] = y;\n result.m[6] = 0.0;\n result.m[7] = 0.0;\n result.m[8] = 0.0;\n result.m[9] = 0.0;\n result.m[10] = z;\n result.m[11] = 0.0;\n result.m[12] = 0.0;\n result.m[13] = 0.0;\n result.m[14] = 0.0;\n result.m[15] = 1.0;\n result._markAsUpdated();\n };\n /**\n * Creates a translation matrix\n * @param x defines the translation on X axis\n * @param y defines the translation on Y axis\n * @param z defines the translationon Z axis\n * @returns the new matrix\n */\n Matrix.Translation = function (x, y, z) {\n var result = Matrix.Identity();\n Matrix.TranslationToRef(x, y, z, result);\n return result;\n };\n /**\n * Creates a translation matrix and stores it in a given matrix\n * @param x defines the translation on X axis\n * @param y defines the translation on Y axis\n * @param z defines the translationon Z axis\n * @param result defines the target matrix\n */\n Matrix.TranslationToRef = function (x, y, z, result) {\n Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);\n };\n /**\n * Returns a new Matrix whose values are the interpolated values for \"gradient\" (float) between the ones of the matrices \"startValue\" and \"endValue\".\n * @param startValue defines the start value\n * @param endValue defines the end value\n * @param gradient defines the gradient factor\n * @returns the new matrix\n */\n Matrix.Lerp = function (startValue, endValue, gradient) {\n var result = Matrix.Zero();\n Matrix.LerpToRef(startValue, endValue, gradient, result);\n return result;\n };\n /**\n * Set the given matrix \"result\" as the interpolated values for \"gradient\" (float) between the ones of the matrices \"startValue\" and \"endValue\".\n * @param startValue defines the start value\n * @param endValue defines the end value\n * @param gradient defines the gradient factor\n * @param result defines the Matrix object where to store data\n */\n Matrix.LerpToRef = function (startValue, endValue, gradient, result) {\n for (var index = 0; index < 16; index++) {\n result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;\n }\n result._markAsUpdated();\n };\n /**\n * Builds a new matrix whose values are computed by:\n * * decomposing the the \"startValue\" and \"endValue\" matrices into their respective scale, rotation and translation matrices\n * * interpolating for \"gradient\" (float) the values between each of these decomposed matrices between the start and the end\n * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices\n * @param startValue defines the first matrix\n * @param endValue defines the second matrix\n * @param gradient defines the gradient between the two matrices\n * @returns the new matrix\n */\n Matrix.DecomposeLerp = function (startValue, endValue, gradient) {\n var result = Matrix.Zero();\n Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);\n return result;\n };\n /**\n * Update a matrix to values which are computed by:\n * * decomposing the the \"startValue\" and \"endValue\" matrices into their respective scale, rotation and translation matrices\n * * interpolating for \"gradient\" (float) the values between each of these decomposed matrices between the start and the end\n * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices\n * @param startValue defines the first matrix\n * @param endValue defines the second matrix\n * @param gradient defines the gradient between the two matrices\n * @param result defines the target matrix\n */\n Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {\n var startScale = MathTmp.Vector3[0];\n var startRotation = MathTmp.Quaternion[0];\n var startTranslation = MathTmp.Vector3[1];\n startValue.decompose(startScale, startRotation, startTranslation);\n var endScale = MathTmp.Vector3[2];\n var endRotation = MathTmp.Quaternion[1];\n var endTranslation = MathTmp.Vector3[3];\n endValue.decompose(endScale, endRotation, endTranslation);\n var resultScale = MathTmp.Vector3[4];\n Vector3.LerpToRef(startScale, endScale, gradient, resultScale);\n var resultRotation = MathTmp.Quaternion[2];\n Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);\n var resultTranslation = MathTmp.Vector3[5];\n Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);\n Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);\n };\n /**\n * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like \"up\"\n * This function works in left handed mode\n * @param eye defines the final position of the entity\n * @param target defines where the entity should look at\n * @param up defines the up vector for the entity\n * @returns the new matrix\n */\n Matrix.LookAtLH = function (eye, target, up) {\n var result = Matrix.Zero();\n Matrix.LookAtLHToRef(eye, target, up, result);\n return result;\n };\n /**\n * Sets the given \"result\" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like \"up\".\n * This function works in left handed mode\n * @param eye defines the final position of the entity\n * @param target defines where the entity should look at\n * @param up defines the up vector for the entity\n * @param result defines the target matrix\n */\n Matrix.LookAtLHToRef = function (eye, target, up, result) {\n // Z axis\n target.subtractToRef(eye, this._zAxis);\n this._zAxis.normalize();\n // X axis\n Vector3.CrossToRef(up, this._zAxis, this._xAxis);\n if (this._xAxis.lengthSquared() === 0) {\n this._xAxis.x = 1.0;\n }\n else {\n this._xAxis.normalize();\n }\n // Y axis\n Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);\n this._yAxis.normalize();\n // Eye angles\n var ex = -Vector3.Dot(this._xAxis, eye);\n var ey = -Vector3.Dot(this._yAxis, eye);\n var ez = -Vector3.Dot(this._zAxis, eye);\n return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);\n };\n /**\n * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like \"up\"\n * This function works in right handed mode\n * @param eye defines the final position of the entity\n * @param target defines where the entity should look at\n * @param up defines the up vector for the entity\n * @returns the new matrix\n */\n Matrix.LookAtRH = function (eye, target, up) {\n var result = Matrix.Zero();\n Matrix.LookAtRHToRef(eye, target, up, result);\n return result;\n };\n /**\n * Sets the given \"result\" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like \"up\".\n * This function works in right handed mode\n * @param eye defines the final position of the entity\n * @param target defines where the entity should look at\n * @param up defines the up vector for the entity\n * @param result defines the target matrix\n */\n Matrix.LookAtRHToRef = function (eye, target, up, result) {\n // Z axis\n eye.subtractToRef(target, this._zAxis);\n this._zAxis.normalize();\n // X axis\n Vector3.CrossToRef(up, this._zAxis, this._xAxis);\n if (this._xAxis.lengthSquared() === 0) {\n this._xAxis.x = 1.0;\n }\n else {\n this._xAxis.normalize();\n }\n // Y axis\n Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);\n this._yAxis.normalize();\n // Eye angles\n var ex = -Vector3.Dot(this._xAxis, eye);\n var ey = -Vector3.Dot(this._yAxis, eye);\n var ez = -Vector3.Dot(this._zAxis, eye);\n return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);\n };\n /**\n * Create a left-handed orthographic projection matrix\n * @param width defines the viewport width\n * @param height defines the viewport height\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @returns a new matrix as a left-handed orthographic projection matrix\n */\n Matrix.OrthoLH = function (width, height, znear, zfar) {\n var matrix = Matrix.Zero();\n Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);\n return matrix;\n };\n /**\n * Store a left-handed orthographic projection to a given matrix\n * @param width defines the viewport width\n * @param height defines the viewport height\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @param result defines the target matrix\n */\n Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {\n var n = znear;\n var f = zfar;\n var a = 2.0 / width;\n var b = 2.0 / height;\n var c = 2.0 / (f - n);\n var d = -(f + n) / (f - n);\n Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);\n };\n /**\n * Create a left-handed orthographic projection matrix\n * @param left defines the viewport left coordinate\n * @param right defines the viewport right coordinate\n * @param bottom defines the viewport bottom coordinate\n * @param top defines the viewport top coordinate\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @returns a new matrix as a left-handed orthographic projection matrix\n */\n Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {\n var matrix = Matrix.Zero();\n Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);\n return matrix;\n };\n /**\n * Stores a left-handed orthographic projection into a given matrix\n * @param left defines the viewport left coordinate\n * @param right defines the viewport right coordinate\n * @param bottom defines the viewport bottom coordinate\n * @param top defines the viewport top coordinate\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @param result defines the target matrix\n */\n Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {\n var n = znear;\n var f = zfar;\n var a = 2.0 / (right - left);\n var b = 2.0 / (top - bottom);\n var c = 2.0 / (f - n);\n var d = -(f + n) / (f - n);\n var i0 = (left + right) / (left - right);\n var i1 = (top + bottom) / (bottom - top);\n Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);\n };\n /**\n * Creates a right-handed orthographic projection matrix\n * @param left defines the viewport left coordinate\n * @param right defines the viewport right coordinate\n * @param bottom defines the viewport bottom coordinate\n * @param top defines the viewport top coordinate\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @returns a new matrix as a right-handed orthographic projection matrix\n */\n Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {\n var matrix = Matrix.Zero();\n Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);\n return matrix;\n };\n /**\n * Stores a right-handed orthographic projection into a given matrix\n * @param left defines the viewport left coordinate\n * @param right defines the viewport right coordinate\n * @param bottom defines the viewport bottom coordinate\n * @param top defines the viewport top coordinate\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @param result defines the target matrix\n */\n Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {\n Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);\n result.m[10] *= -1.0;\n };\n /**\n * Creates a left-handed perspective projection matrix\n * @param width defines the viewport width\n * @param height defines the viewport height\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @returns a new matrix as a left-handed perspective projection matrix\n */\n Matrix.PerspectiveLH = function (width, height, znear, zfar) {\n var matrix = Matrix.Zero();\n var n = znear;\n var f = zfar;\n var a = 2.0 * n / width;\n var b = 2.0 * n / height;\n var c = (f + n) / (f - n);\n var d = -2.0 * f * n / (f - n);\n Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);\n return matrix;\n };\n /**\n * Creates a left-handed perspective projection matrix\n * @param fov defines the horizontal field of view\n * @param aspect defines the aspect ratio\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @returns a new matrix as a left-handed perspective projection matrix\n */\n Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {\n var matrix = Matrix.Zero();\n Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);\n return matrix;\n };\n /**\n * Stores a left-handed perspective projection into a given matrix\n * @param fov defines the horizontal field of view\n * @param aspect defines the aspect ratio\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @param result defines the target matrix\n * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally\n */\n Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {\n if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }\n var n = znear;\n var f = zfar;\n var t = 1.0 / (Math.tan(fov * 0.5));\n var a = isVerticalFovFixed ? (t / aspect) : t;\n var b = isVerticalFovFixed ? t : (t * aspect);\n var c = (f + n) / (f - n);\n var d = -2.0 * f * n / (f - n);\n Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);\n };\n /**\n * Creates a right-handed perspective projection matrix\n * @param fov defines the horizontal field of view\n * @param aspect defines the aspect ratio\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @returns a new matrix as a right-handed perspective projection matrix\n */\n Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {\n var matrix = Matrix.Zero();\n Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);\n return matrix;\n };\n /**\n * Stores a right-handed perspective projection into a given matrix\n * @param fov defines the horizontal field of view\n * @param aspect defines the aspect ratio\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @param result defines the target matrix\n * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally\n */\n Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {\n //alternatively this could be expressed as:\n // m = PerspectiveFovLHToRef\n // m[10] *= -1.0;\n // m[11] *= -1.0;\n if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }\n var n = znear;\n var f = zfar;\n var t = 1.0 / (Math.tan(fov * 0.5));\n var a = isVerticalFovFixed ? (t / aspect) : t;\n var b = isVerticalFovFixed ? t : (t * aspect);\n var c = -(f + n) / (f - n);\n var d = -2 * f * n / (f - n);\n Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);\n };\n /**\n * Stores a perspective projection for WebVR info a given matrix\n * @param fov defines the field of view\n * @param znear defines the near clip plane\n * @param zfar defines the far clip plane\n * @param result defines the target matrix\n * @param rightHanded defines if the matrix must be in right-handed mode (false by default)\n */\n Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {\n if (rightHanded === void 0) { rightHanded = false; }\n var rightHandedFactor = rightHanded ? -1 : 1;\n var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);\n var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);\n var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);\n var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);\n var xScale = 2.0 / (leftTan + rightTan);\n var yScale = 2.0 / (upTan + downTan);\n result.m[0] = xScale;\n result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;\n result.m[5] = yScale;\n result.m[6] = result.m[7] = 0.0;\n result.m[8] = ((leftTan - rightTan) * xScale * 0.5);\n result.m[9] = -((upTan - downTan) * yScale * 0.5);\n result.m[10] = -zfar / (znear - zfar);\n result.m[11] = 1.0 * rightHandedFactor;\n result.m[12] = result.m[13] = result.m[15] = 0.0;\n result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);\n result._markAsUpdated();\n };\n /**\n * Computes a complete transformation matrix\n * @param viewport defines the viewport to use\n * @param world defines the world matrix\n * @param view defines the view matrix\n * @param projection defines the projection matrix\n * @param zmin defines the near clip plane\n * @param zmax defines the far clip plane\n * @returns the transformation matrix\n */\n Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {\n var cw = viewport.width;\n var ch = viewport.height;\n var cx = viewport.x;\n var cy = viewport.y;\n var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);\n return world.multiply(view).multiply(projection).multiply(viewportMatrix);\n };\n /**\n * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array\n * @param matrix defines the matrix to use\n * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix\n */\n Matrix.GetAsMatrix2x2 = function (matrix) {\n return new Float32Array([\n matrix.m[0], matrix.m[1],\n matrix.m[4], matrix.m[5]\n ]);\n };\n /**\n * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array\n * @param matrix defines the matrix to use\n * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix\n */\n Matrix.GetAsMatrix3x3 = function (matrix) {\n return new Float32Array([\n matrix.m[0], matrix.m[1], matrix.m[2],\n matrix.m[4], matrix.m[5], matrix.m[6],\n matrix.m[8], matrix.m[9], matrix.m[10]\n ]);\n };\n /**\n * Compute the transpose of a given matrix\n * @param matrix defines the matrix to transpose\n * @returns the new matrix\n */\n Matrix.Transpose = function (matrix) {\n var result = new Matrix();\n Matrix.TransposeToRef(matrix, result);\n return result;\n };\n /**\n * Compute the transpose of a matrix and store it in a target matrix\n * @param matrix defines the matrix to transpose\n * @param result defines the target matrix\n */\n Matrix.TransposeToRef = function (matrix, result) {\n result.m[0] = matrix.m[0];\n result.m[1] = matrix.m[4];\n result.m[2] = matrix.m[8];\n result.m[3] = matrix.m[12];\n result.m[4] = matrix.m[1];\n result.m[5] = matrix.m[5];\n result.m[6] = matrix.m[9];\n result.m[7] = matrix.m[13];\n result.m[8] = matrix.m[2];\n result.m[9] = matrix.m[6];\n result.m[10] = matrix.m[10];\n result.m[11] = matrix.m[14];\n result.m[12] = matrix.m[3];\n result.m[13] = matrix.m[7];\n result.m[14] = matrix.m[11];\n result.m[15] = matrix.m[15];\n };\n /**\n * Computes a reflection matrix from a plane\n * @param plane defines the reflection plane\n * @returns a new matrix\n */\n Matrix.Reflection = function (plane) {\n var matrix = new Matrix();\n Matrix.ReflectionToRef(plane, matrix);\n return matrix;\n };\n /**\n * Computes a reflection matrix from a plane\n * @param plane defines the reflection plane\n * @param result defines the target matrix\n */\n Matrix.ReflectionToRef = function (plane, result) {\n plane.normalize();\n var x = plane.normal.x;\n var y = plane.normal.y;\n var z = plane.normal.z;\n var temp = -2 * x;\n var temp2 = -2 * y;\n var temp3 = -2 * z;\n result.m[0] = (temp * x) + 1;\n result.m[1] = temp2 * x;\n result.m[2] = temp3 * x;\n result.m[3] = 0.0;\n result.m[4] = temp * y;\n result.m[5] = (temp2 * y) + 1;\n result.m[6] = temp3 * y;\n result.m[7] = 0.0;\n result.m[8] = temp * z;\n result.m[9] = temp2 * z;\n result.m[10] = (temp3 * z) + 1;\n result.m[11] = 0.0;\n result.m[12] = temp * plane.d;\n result.m[13] = temp2 * plane.d;\n result.m[14] = temp3 * plane.d;\n result.m[15] = 1.0;\n result._markAsUpdated();\n };\n /**\n * Sets the given matrix as a rotation matrix composed from the 3 left handed axes\n * @param xaxis defines the value of the 1st axis\n * @param yaxis defines the value of the 2nd axis\n * @param zaxis defines the value of the 3rd axis\n * @param result defines the target matrix\n */\n Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {\n result.m[0] = xaxis.x;\n result.m[1] = xaxis.y;\n result.m[2] = xaxis.z;\n result.m[3] = 0.0;\n result.m[4] = yaxis.x;\n result.m[5] = yaxis.y;\n result.m[6] = yaxis.z;\n result.m[7] = 0.0;\n result.m[8] = zaxis.x;\n result.m[9] = zaxis.y;\n result.m[10] = zaxis.z;\n result.m[11] = 0.0;\n result.m[12] = 0.0;\n result.m[13] = 0.0;\n result.m[14] = 0.0;\n result.m[15] = 1.0;\n result._markAsUpdated();\n };\n /**\n * Creates a rotation matrix from a quaternion and stores it in a target matrix\n * @param quat defines the quaternion to use\n * @param result defines the target matrix\n */\n Matrix.FromQuaternionToRef = function (quat, result) {\n var xx = quat.x * quat.x;\n var yy = quat.y * quat.y;\n var zz = quat.z * quat.z;\n var xy = quat.x * quat.y;\n var zw = quat.z * quat.w;\n var zx = quat.z * quat.x;\n var yw = quat.y * quat.w;\n var yz = quat.y * quat.z;\n var xw = quat.x * quat.w;\n result.m[0] = 1.0 - (2.0 * (yy + zz));\n result.m[1] = 2.0 * (xy + zw);\n result.m[2] = 2.0 * (zx - yw);\n result.m[3] = 0.0;\n result.m[4] = 2.0 * (xy - zw);\n result.m[5] = 1.0 - (2.0 * (zz + xx));\n result.m[6] = 2.0 * (yz + xw);\n result.m[7] = 0.0;\n result.m[8] = 2.0 * (zx + yw);\n result.m[9] = 2.0 * (yz - xw);\n result.m[10] = 1.0 - (2.0 * (yy + xx));\n result.m[11] = 0.0;\n result.m[12] = 0.0;\n result.m[13] = 0.0;\n result.m[14] = 0.0;\n result.m[15] = 1.0;\n result._markAsUpdated();\n };\n Matrix._tempQuaternion = new Quaternion();\n Matrix._xAxis = Vector3.Zero();\n Matrix._yAxis = Vector3.Zero();\n Matrix._zAxis = Vector3.Zero();\n Matrix._updateFlagSeed = 0;\n Matrix._identityReadOnly = Matrix.Identity();\n return Matrix;\n }());\n BABYLON.Matrix = Matrix;\n var Plane = /** @class */ (function () {\n /**\n * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0\n */\n function Plane(a, b, c, d) {\n this.normal = new Vector3(a, b, c);\n this.d = d;\n }\n /**\n * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].\n */\n Plane.prototype.asArray = function () {\n return [this.normal.x, this.normal.y, this.normal.z, this.d];\n };\n // Methods\n /**\n * Returns a new plane copied from the current Plane.\n */\n Plane.prototype.clone = function () {\n return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);\n };\n /**\n * Returns the string \"Plane\".\n */\n Plane.prototype.getClassName = function () {\n return \"Plane\";\n };\n /**\n * Returns the Plane hash code.\n */\n Plane.prototype.getHashCode = function () {\n var hash = this.normal.getHashCode();\n hash = (hash * 397) ^ (this.d || 0);\n return hash;\n };\n /**\n * Normalize the current Plane in place.\n * Returns the updated Plane.\n */\n Plane.prototype.normalize = function () {\n var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));\n var magnitude = 0.0;\n if (norm !== 0) {\n magnitude = 1.0 / norm;\n }\n this.normal.x *= magnitude;\n this.normal.y *= magnitude;\n this.normal.z *= magnitude;\n this.d *= magnitude;\n return this;\n };\n /**\n * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.\n */\n Plane.prototype.transform = function (transformation) {\n var transposedMatrix = Matrix.Transpose(transformation);\n var x = this.normal.x;\n var y = this.normal.y;\n var z = this.normal.z;\n var d = this.d;\n var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);\n var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);\n var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);\n var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);\n return new Plane(normalX, normalY, normalZ, finalD);\n };\n /**\n * Returns the dot product (float) of the point coordinates and the plane normal.\n */\n Plane.prototype.dotCoordinate = function (point) {\n return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);\n };\n /**\n * Updates the current Plane from the plane defined by the three given points.\n * Returns the updated Plane.\n */\n Plane.prototype.copyFromPoints = function (point1, point2, point3) {\n var x1 = point2.x - point1.x;\n var y1 = point2.y - point1.y;\n var z1 = point2.z - point1.z;\n var x2 = point3.x - point1.x;\n var y2 = point3.y - point1.y;\n var z2 = point3.z - point1.z;\n var yz = (y1 * z2) - (z1 * y2);\n var xz = (z1 * x2) - (x1 * z2);\n var xy = (x1 * y2) - (y1 * x2);\n var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));\n var invPyth;\n if (pyth !== 0) {\n invPyth = 1.0 / pyth;\n }\n else {\n invPyth = 0.0;\n }\n this.normal.x = yz * invPyth;\n this.normal.y = xz * invPyth;\n this.normal.z = xy * invPyth;\n this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));\n return this;\n };\n /**\n * Boolean : True is the vector \"direction\" is the same side than the plane normal.\n */\n Plane.prototype.isFrontFacingTo = function (direction, epsilon) {\n var dot = Vector3.Dot(this.normal, direction);\n return (dot <= epsilon);\n };\n /**\n * Returns the signed distance (float) from the given point to the Plane.\n */\n Plane.prototype.signedDistanceTo = function (point) {\n return Vector3.Dot(point, this.normal) + this.d;\n };\n // Statics\n /**\n * Returns a new Plane from the given array.\n */\n Plane.FromArray = function (array) {\n return new Plane(array[0], array[1], array[2], array[3]);\n };\n /**\n * Returns a new Plane defined by the three given points.\n */\n Plane.FromPoints = function (point1, point2, point3) {\n var result = new Plane(0.0, 0.0, 0.0, 0.0);\n result.copyFromPoints(point1, point2, point3);\n return result;\n };\n /**\n * Returns a new Plane the normal vector to this plane at the given origin point.\n * Note : the vector \"normal\" is updated because normalized.\n */\n Plane.FromPositionAndNormal = function (origin, normal) {\n var result = new Plane(0.0, 0.0, 0.0, 0.0);\n normal.normalize();\n result.normal = normal;\n result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);\n return result;\n };\n /**\n * Returns the signed distance between the plane defined by the normal vector at the \"origin\"\" point and the given other point.\n */\n Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {\n var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);\n return Vector3.Dot(point, normal) + d;\n };\n return Plane;\n }());\n BABYLON.Plane = Plane;\n var Viewport = /** @class */ (function () {\n /**\n * Creates a Viewport object located at (x, y) and sized (width, height).\n */\n function Viewport(x, y, width, height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {\n if (renderWidthOrEngine.getRenderWidth) {\n var engine = renderWidthOrEngine;\n return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n }\n var renderWidth = renderWidthOrEngine;\n return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);\n };\n /**\n * Returns a new Viewport copied from the current one.\n */\n Viewport.prototype.clone = function () {\n return new Viewport(this.x, this.y, this.width, this.height);\n };\n return Viewport;\n }());\n BABYLON.Viewport = Viewport;\n var Frustum = /** @class */ (function () {\n function Frustum() {\n }\n /**\n * Returns a new array of 6 Frustum planes computed by the given transformation matrix.\n */\n Frustum.GetPlanes = function (transform) {\n var frustumPlanes = [];\n for (var index = 0; index < 6; index++) {\n frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));\n }\n Frustum.GetPlanesToRef(transform, frustumPlanes);\n return frustumPlanes;\n };\n Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {\n frustumPlane.normal.x = transform.m[3] + transform.m[2];\n frustumPlane.normal.y = transform.m[7] + transform.m[6];\n frustumPlane.normal.z = transform.m[11] + transform.m[10];\n frustumPlane.d = transform.m[15] + transform.m[14];\n frustumPlane.normalize();\n };\n Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {\n frustumPlane.normal.x = transform.m[3] - transform.m[2];\n frustumPlane.normal.y = transform.m[7] - transform.m[6];\n frustumPlane.normal.z = transform.m[11] - transform.m[10];\n frustumPlane.d = transform.m[15] - transform.m[14];\n frustumPlane.normalize();\n };\n Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {\n frustumPlane.normal.x = transform.m[3] + transform.m[0];\n frustumPlane.normal.y = transform.m[7] + transform.m[4];\n frustumPlane.normal.z = transform.m[11] + transform.m[8];\n frustumPlane.d = transform.m[15] + transform.m[12];\n frustumPlane.normalize();\n };\n Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {\n frustumPlane.normal.x = transform.m[3] - transform.m[0];\n frustumPlane.normal.y = transform.m[7] - transform.m[4];\n frustumPlane.normal.z = transform.m[11] - transform.m[8];\n frustumPlane.d = transform.m[15] - transform.m[12];\n frustumPlane.normalize();\n };\n Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {\n frustumPlane.normal.x = transform.m[3] - transform.m[1];\n frustumPlane.normal.y = transform.m[7] - transform.m[5];\n frustumPlane.normal.z = transform.m[11] - transform.m[9];\n frustumPlane.d = transform.m[15] - transform.m[13];\n frustumPlane.normalize();\n };\n Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {\n frustumPlane.normal.x = transform.m[3] + transform.m[1];\n frustumPlane.normal.y = transform.m[7] + transform.m[5];\n frustumPlane.normal.z = transform.m[11] + transform.m[9];\n frustumPlane.d = transform.m[15] + transform.m[13];\n frustumPlane.normalize();\n };\n /**\n * Sets the given array \"frustumPlanes\" with the 6 Frustum planes computed by the given transformation matrix.\n */\n Frustum.GetPlanesToRef = function (transform, frustumPlanes) {\n // Near\n Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);\n // Far\n Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);\n // Left\n Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);\n // Right\n Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);\n // Top\n Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);\n // Bottom\n Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);\n };\n return Frustum;\n }());\n BABYLON.Frustum = Frustum;\n /** Defines supported spaces */\n var Space;\n (function (Space) {\n /** Local (object) space */\n Space[Space[\"LOCAL\"] = 0] = \"LOCAL\";\n /** World space */\n Space[Space[\"WORLD\"] = 1] = \"WORLD\";\n /** Bone space */\n Space[Space[\"BONE\"] = 2] = \"BONE\";\n })(Space = BABYLON.Space || (BABYLON.Space = {}));\n /** Defines the 3 main axes */\n var Axis = /** @class */ (function () {\n function Axis() {\n }\n /** X axis */\n Axis.X = new Vector3(1.0, 0.0, 0.0);\n /** Y axis */\n Axis.Y = new Vector3(0.0, 1.0, 0.0);\n /** Z axis */\n Axis.Z = new Vector3(0.0, 0.0, 1.0);\n return Axis;\n }());\n BABYLON.Axis = Axis;\n ;\n var BezierCurve = /** @class */ (function () {\n function BezierCurve() {\n }\n /**\n * Returns the cubic Bezier interpolated value (float) at \"t\" (float) from the given x1, y1, x2, y2 floats.\n */\n BezierCurve.interpolate = function (t, x1, y1, x2, y2) {\n // Extract X (which is equal to time here)\n var f0 = 1 - 3 * x2 + 3 * x1;\n var f1 = 3 * x2 - 6 * x1;\n var f2 = 3 * x1;\n var refinedT = t;\n for (var i = 0; i < 5; i++) {\n var refinedT2 = refinedT * refinedT;\n var refinedT3 = refinedT2 * refinedT;\n var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;\n var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);\n refinedT -= (x - t) * slope;\n refinedT = Math.min(1, Math.max(0, refinedT));\n }\n // Resolve cubic bezier for the given x\n return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +\n 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +\n Math.pow(refinedT, 3);\n };\n return BezierCurve;\n }());\n BABYLON.BezierCurve = BezierCurve;\n /**\n * Defines potential orientation for back face culling\n */\n var Orientation;\n (function (Orientation) {\n /**\n * Clockwise\n */\n Orientation[Orientation[\"CW\"] = 0] = \"CW\";\n /** Counter clockwise */\n Orientation[Orientation[\"CCW\"] = 1] = \"CCW\";\n })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));\n /**\n * Defines angle representation\n */\n var Angle = /** @class */ (function () {\n /**\n * Creates an Angle object of \"radians\" radians (float).\n */\n function Angle(radians) {\n this._radians = radians;\n if (this._radians < 0.0)\n this._radians += (2.0 * Math.PI);\n }\n /**\n * Get value in degrees\n * @returns the Angle value in degrees (float)\n */\n Angle.prototype.degrees = function () {\n return this._radians * 180.0 / Math.PI;\n };\n /**\n * Get value in radians\n * @returns the Angle value in radians (float)\n */\n Angle.prototype.radians = function () {\n return this._radians;\n };\n /**\n * Gets a new Angle object valued with the angle value in radians between the two given vectors\n * @param a defines first vector\n * @param b defines second vector\n * @returns a new Angle\n */\n Angle.BetweenTwoPoints = function (a, b) {\n var delta = b.subtract(a);\n var theta = Math.atan2(delta.y, delta.x);\n return new Angle(theta);\n };\n /**\n * Gets a new Angle object from the given float in radians\n * @param radians defines the angle value in radians\n * @returns a new Angle\n */\n Angle.FromRadians = function (radians) {\n return new Angle(radians);\n };\n /**\n * Gets a new Angle object from the given float in degrees\n * @param degrees defines the angle value in degrees\n * @returns a new Angle\n */\n Angle.FromDegrees = function (degrees) {\n return new Angle(degrees * Math.PI / 180.0);\n };\n return Angle;\n }());\n BABYLON.Angle = Angle;\n var Arc2 = /** @class */ (function () {\n /**\n * Creates an Arc object from the three given points : start, middle and end.\n */\n function Arc2(startPoint, midPoint, endPoint) {\n this.startPoint = startPoint;\n this.midPoint = midPoint;\n this.endPoint = endPoint;\n var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);\n var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;\n var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;\n var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);\n this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);\n this.radius = this.centerPoint.subtract(this.startPoint).length();\n this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);\n var a1 = this.startAngle.degrees();\n var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();\n var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();\n // angles correction\n if (a2 - a1 > +180.0)\n a2 -= 360.0;\n if (a2 - a1 < -180.0)\n a2 += 360.0;\n if (a3 - a2 > +180.0)\n a3 -= 360.0;\n if (a3 - a2 < -180.0)\n a3 += 360.0;\n this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;\n this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);\n }\n return Arc2;\n }());\n BABYLON.Arc2 = Arc2;\n var Path2 = /** @class */ (function () {\n /**\n * Creates a Path2 object from the starting 2D coordinates x and y.\n */\n function Path2(x, y) {\n this._points = new Array();\n this._length = 0.0;\n this.closed = false;\n this._points.push(new Vector2(x, y));\n }\n /**\n * Adds a new segment until the given coordinates (x, y) to the current Path2.\n * Returns the updated Path2.\n */\n Path2.prototype.addLineTo = function (x, y) {\n if (this.closed) {\n return this;\n }\n var newPoint = new Vector2(x, y);\n var previousPoint = this._points[this._points.length - 1];\n this._points.push(newPoint);\n this._length += newPoint.subtract(previousPoint).length();\n return this;\n };\n /**\n * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.\n * Returns the updated Path2.\n */\n Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {\n if (numberOfSegments === void 0) { numberOfSegments = 36; }\n if (this.closed) {\n return this;\n }\n var startPoint = this._points[this._points.length - 1];\n var midPoint = new Vector2(midX, midY);\n var endPoint = new Vector2(endX, endY);\n var arc = new Arc2(startPoint, midPoint, endPoint);\n var increment = arc.angle.radians() / numberOfSegments;\n if (arc.orientation === Orientation.CW)\n increment *= -1;\n var currentAngle = arc.startAngle.radians() + increment;\n for (var i = 0; i < numberOfSegments; i++) {\n var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;\n var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;\n this.addLineTo(x, y);\n currentAngle += increment;\n }\n return this;\n };\n /**\n * Closes the Path2.\n * Returns the Path2.\n */\n Path2.prototype.close = function () {\n this.closed = true;\n return this;\n };\n /**\n * Returns the Path2 total length (float).\n */\n Path2.prototype.length = function () {\n var result = this._length;\n if (!this.closed) {\n var lastPoint = this._points[this._points.length - 1];\n var firstPoint = this._points[0];\n result += (firstPoint.subtract(lastPoint).length());\n }\n return result;\n };\n /**\n * Returns the Path2 internal array of points.\n */\n Path2.prototype.getPoints = function () {\n return this._points;\n };\n /**\n * Returns a new Vector2 located at a percentage of the Path2 total length on this path.\n */\n Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {\n if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {\n return Vector2.Zero();\n }\n var lengthPosition = normalizedLengthPosition * this.length();\n var previousOffset = 0;\n for (var i = 0; i < this._points.length; i++) {\n var j = (i + 1) % this._points.length;\n var a = this._points[i];\n var b = this._points[j];\n var bToA = b.subtract(a);\n var nextOffset = (bToA.length() + previousOffset);\n if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {\n var dir = bToA.normalize();\n var localOffset = lengthPosition - previousOffset;\n return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));\n }\n previousOffset = nextOffset;\n }\n return Vector2.Zero();\n };\n /**\n * Returns a new Path2 starting at the coordinates (x, y).\n */\n Path2.StartingAt = function (x, y) {\n return new Path2(x, y);\n };\n return Path2;\n }());\n BABYLON.Path2 = Path2;\n var Path3D = /** @class */ (function () {\n /**\n * new Path3D(path, normal, raw)\n * Creates a Path3D. A Path3D is a logical math object, so not a mesh.\n * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D\n * path : an array of Vector3, the curve axis of the Path3D\n * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.\n * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.\n */\n function Path3D(path, firstNormal, raw) {\n if (firstNormal === void 0) { firstNormal = null; }\n this.path = path;\n this._curve = new Array();\n this._distances = new Array();\n this._tangents = new Array();\n this._normals = new Array();\n this._binormals = new Array();\n for (var p = 0; p < path.length; p++) {\n this._curve[p] = path[p].clone(); // hard copy\n }\n this._raw = raw || false;\n this._compute(firstNormal);\n }\n /**\n * Returns the Path3D array of successive Vector3 designing its curve.\n */\n Path3D.prototype.getCurve = function () {\n return this._curve;\n };\n /**\n * Returns an array populated with tangent vectors on each Path3D curve point.\n */\n Path3D.prototype.getTangents = function () {\n return this._tangents;\n };\n /**\n * Returns an array populated with normal vectors on each Path3D curve point.\n */\n Path3D.prototype.getNormals = function () {\n return this._normals;\n };\n /**\n * Returns an array populated with binormal vectors on each Path3D curve point.\n */\n Path3D.prototype.getBinormals = function () {\n return this._binormals;\n };\n /**\n * Returns an array populated with distances (float) of the i-th point from the first curve point.\n */\n Path3D.prototype.getDistances = function () {\n return this._distances;\n };\n /**\n * Forces the Path3D tangent, normal, binormal and distance recomputation.\n * Returns the same object updated.\n */\n Path3D.prototype.update = function (path, firstNormal) {\n if (firstNormal === void 0) { firstNormal = null; }\n for (var p = 0; p < path.length; p++) {\n this._curve[p].x = path[p].x;\n this._curve[p].y = path[p].y;\n this._curve[p].z = path[p].z;\n }\n this._compute(firstNormal);\n return this;\n };\n // private function compute() : computes tangents, normals and binormals\n Path3D.prototype._compute = function (firstNormal) {\n var l = this._curve.length;\n // first and last tangents\n this._tangents[0] = this._getFirstNonNullVector(0);\n if (!this._raw) {\n this._tangents[0].normalize();\n }\n this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);\n if (!this._raw) {\n this._tangents[l - 1].normalize();\n }\n // normals and binormals at first point : arbitrary vector with _normalVector()\n var tg0 = this._tangents[0];\n var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);\n this._normals[0] = pp0;\n if (!this._raw) {\n this._normals[0].normalize();\n }\n this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);\n if (!this._raw) {\n this._binormals[0].normalize();\n }\n this._distances[0] = 0.0;\n // normals and binormals : next points\n var prev; // previous vector (segment)\n var cur; // current vector (segment)\n var curTang; // current tangent\n // previous normal\n var prevBinor; // previous binormal\n for (var i = 1; i < l; i++) {\n // tangents\n prev = this._getLastNonNullVector(i);\n if (i < l - 1) {\n cur = this._getFirstNonNullVector(i);\n this._tangents[i] = prev.add(cur);\n this._tangents[i].normalize();\n }\n this._distances[i] = this._distances[i - 1] + prev.length();\n // normals and binormals\n // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html\n curTang = this._tangents[i];\n prevBinor = this._binormals[i - 1];\n this._normals[i] = Vector3.Cross(prevBinor, curTang);\n if (!this._raw) {\n this._normals[i].normalize();\n }\n this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);\n if (!this._raw) {\n this._binormals[i].normalize();\n }\n }\n };\n // private function getFirstNonNullVector(index)\n // returns the first non null vector from index : curve[index + N].subtract(curve[index])\n Path3D.prototype._getFirstNonNullVector = function (index) {\n var i = 1;\n var nNVector = this._curve[index + i].subtract(this._curve[index]);\n while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {\n i++;\n nNVector = this._curve[index + i].subtract(this._curve[index]);\n }\n return nNVector;\n };\n // private function getLastNonNullVector(index)\n // returns the last non null vector from index : curve[index].subtract(curve[index - N])\n Path3D.prototype._getLastNonNullVector = function (index) {\n var i = 1;\n var nLVector = this._curve[index].subtract(this._curve[index - i]);\n while (nLVector.length() === 0 && index > i + 1) {\n i++;\n nLVector = this._curve[index].subtract(this._curve[index - i]);\n }\n return nLVector;\n };\n // private function normalVector(v0, vt, va) :\n // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane\n // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0\n Path3D.prototype._normalVector = function (v0, vt, va) {\n var normal0;\n var tgl = vt.length();\n if (tgl === 0.0) {\n tgl = 1.0;\n }\n if (va === undefined || va === null) {\n var point;\n if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane\n point = new Vector3(0.0, -1.0, 0.0);\n }\n else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {\n point = new Vector3(1.0, 0.0, 0.0);\n }\n else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {\n point = new Vector3(0.0, 0.0, 1.0);\n }\n else {\n point = Vector3.Zero();\n }\n normal0 = Vector3.Cross(vt, point);\n }\n else {\n normal0 = Vector3.Cross(vt, va);\n Vector3.CrossToRef(normal0, vt, normal0);\n }\n normal0.normalize();\n return normal0;\n };\n return Path3D;\n }());\n BABYLON.Path3D = Path3D;\n var Curve3 = /** @class */ (function () {\n /**\n * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.\n * A Curve3 is designed from a series of successive Vector3.\n * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object\n */\n function Curve3(points) {\n this._length = 0.0;\n this._points = points;\n this._length = this._computeLength(points);\n }\n /**\n * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve\n * @param v0 (Vector3) the origin point of the Quadratic Bezier\n * @param v1 (Vector3) the control point\n * @param v2 (Vector3) the end point of the Quadratic Bezier\n * @param nbPoints (integer) the wanted number of points in the curve\n */\n Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {\n nbPoints = nbPoints > 2 ? nbPoints : 3;\n var bez = new Array();\n var equation = function (t, val0, val1, val2) {\n var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;\n return res;\n };\n for (var i = 0; i <= nbPoints; i++) {\n bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));\n }\n return new Curve3(bez);\n };\n /**\n * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve\n * @param v0 (Vector3) the origin point of the Cubic Bezier\n * @param v1 (Vector3) the first control point\n * @param v2 (Vector3) the second control point\n * @param v3 (Vector3) the end point of the Cubic Bezier\n * @param nbPoints (integer) the wanted number of points in the curve\n */\n Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {\n nbPoints = nbPoints > 3 ? nbPoints : 4;\n var bez = new Array();\n var equation = function (t, val0, val1, val2, val3) {\n var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;\n return res;\n };\n for (var i = 0; i <= nbPoints; i++) {\n bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));\n }\n return new Curve3(bez);\n };\n /**\n * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline\n * @param p1 (Vector3) the origin point of the Hermite Spline\n * @param t1 (Vector3) the tangent vector at the origin point\n * @param p2 (Vector3) the end point of the Hermite Spline\n * @param t2 (Vector3) the tangent vector at the end point\n * @param nbPoints (integer) the wanted number of points in the curve\n */\n Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {\n var hermite = new Array();\n var step = 1.0 / nbPoints;\n for (var i = 0; i <= nbPoints; i++) {\n hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));\n }\n return new Curve3(hermite);\n };\n /**\n * Returns a Curve3 object along a CatmullRom Spline curve :\n * @param points (array of Vector3) the points the spline must pass through. At least, four points required\n * @param nbPoints (integer) the wanted number of points between each curve control points\n * @param closed (boolean) optional with default false, when true forms a closed loop from the points\n */\n Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {\n var catmullRom = new Array();\n var step = 1.0 / nbPoints;\n var amount = 0.0;\n if (closed) {\n var pointsCount = points.length;\n for (var i = 0; i < pointsCount; i++) {\n amount = 0;\n for (var c = 0; c < nbPoints; c++) {\n catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));\n amount += step;\n }\n }\n catmullRom.push(catmullRom[0]);\n }\n else {\n var totalPoints = new Array();\n totalPoints.push(points[0].clone());\n Array.prototype.push.apply(totalPoints, points);\n totalPoints.push(points[points.length - 1].clone());\n for (var i = 0; i < totalPoints.length - 3; i++) {\n amount = 0;\n for (var c = 0; c < nbPoints; c++) {\n catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));\n amount += step;\n }\n }\n i--;\n catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));\n }\n return new Curve3(catmullRom);\n };\n /**\n * Returns the Curve3 stored array of successive Vector3\n */\n Curve3.prototype.getPoints = function () {\n return this._points;\n };\n /**\n * Returns the computed length (float) of the curve.\n */\n Curve3.prototype.length = function () {\n return this._length;\n };\n /**\n * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);\n * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.\n * curveA and curveB keep unchanged.\n */\n Curve3.prototype.continue = function (curve) {\n var lastPoint = this._points[this._points.length - 1];\n var continuedPoints = this._points.slice();\n var curvePoints = curve.getPoints();\n for (var i = 1; i < curvePoints.length; i++) {\n continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));\n }\n var continuedCurve = new Curve3(continuedPoints);\n return continuedCurve;\n };\n Curve3.prototype._computeLength = function (path) {\n var l = 0;\n for (var i = 1; i < path.length; i++) {\n l += (path[i].subtract(path[i - 1])).length();\n }\n return l;\n };\n return Curve3;\n }());\n BABYLON.Curve3 = Curve3;\n // Vertex formats\n var PositionNormalVertex = /** @class */ (function () {\n function PositionNormalVertex(position, normal) {\n if (position === void 0) { position = Vector3.Zero(); }\n if (normal === void 0) { normal = Vector3.Up(); }\n this.position = position;\n this.normal = normal;\n }\n PositionNormalVertex.prototype.clone = function () {\n return new PositionNormalVertex(this.position.clone(), this.normal.clone());\n };\n return PositionNormalVertex;\n }());\n BABYLON.PositionNormalVertex = PositionNormalVertex;\n var PositionNormalTextureVertex = /** @class */ (function () {\n function PositionNormalTextureVertex(position, normal, uv) {\n if (position === void 0) { position = Vector3.Zero(); }\n if (normal === void 0) { normal = Vector3.Up(); }\n if (uv === void 0) { uv = Vector2.Zero(); }\n this.position = position;\n this.normal = normal;\n this.uv = uv;\n }\n PositionNormalTextureVertex.prototype.clone = function () {\n return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());\n };\n return PositionNormalTextureVertex;\n }());\n BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;\n // Temporary pre-allocated objects for engine internal use\n // usage in any internal function :\n // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3\n // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix\n var Tmp = /** @class */ (function () {\n function Tmp() {\n }\n Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];\n Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];\n Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough\n Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),\n Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough\n Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough\n Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough\n Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),\n Matrix.Zero(), Matrix.Zero(),\n Matrix.Zero(), Matrix.Zero(),\n Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough\n return Tmp;\n }());\n BABYLON.Tmp = Tmp;\n // Same as Tmp but not exported to keep it only for math functions to avoid conflicts\n var MathTmp = /** @class */ (function () {\n function MathTmp() {\n }\n MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];\n MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];\n MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];\n return MathTmp;\n }());\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.math.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Scalar = /** @class */ (function () {\n function Scalar() {\n }\n /**\n * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)\n */\n Scalar.WithinEpsilon = function (a, b, epsilon) {\n if (epsilon === void 0) { epsilon = 1.401298E-45; }\n var num = a - b;\n return -epsilon <= num && num <= epsilon;\n };\n /**\n * Returns a string : the upper case translation of the number i to hexadecimal.\n */\n Scalar.ToHex = function (i) {\n var str = i.toString(16);\n if (i <= 15) {\n return (\"0\" + str).toUpperCase();\n }\n return str.toUpperCase();\n };\n /**\n * Returns -1 if value is negative and +1 is value is positive.\n * Returns the value itself if it's equal to zero.\n */\n Scalar.Sign = function (value) {\n value = +value; // convert to a number\n if (value === 0 || isNaN(value))\n return value;\n return value > 0 ? 1 : -1;\n };\n /**\n * Returns the value itself if it's between min and max.\n * Returns min if the value is lower than min.\n * Returns max if the value is greater than max.\n */\n Scalar.Clamp = function (value, min, max) {\n if (min === void 0) { min = 0; }\n if (max === void 0) { max = 1; }\n return Math.min(max, Math.max(min, value));\n };\n /**\n * Returns the log2 of value.\n */\n Scalar.Log2 = function (value) {\n return Math.log(value) * Math.LOG2E;\n };\n /**\n * Loops the value, so that it is never larger than length and never smaller than 0.\n *\n * This is similar to the modulo operator but it works with floating point numbers.\n * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.\n * With t = 5 and length = 2.5, the result would be 0.0.\n * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator\n */\n Scalar.Repeat = function (value, length) {\n return value - Math.floor(value / length) * length;\n };\n /**\n * Normalize the value between 0.0 and 1.0 using min and max values\n */\n Scalar.Normalize = function (value, min, max) {\n return (value - min) / (max - min);\n };\n /**\n * Denormalize the value from 0.0 and 1.0 using min and max values\n */\n Scalar.Denormalize = function (normalized, min, max) {\n return (normalized * (max - min) + min);\n };\n /**\n * Calculates the shortest difference between two given angles given in degrees.\n */\n Scalar.DeltaAngle = function (current, target) {\n var num = Scalar.Repeat(target - current, 360.0);\n if (num > 180.0) {\n num -= 360.0;\n }\n return num;\n };\n /**\n * PingPongs the value t, so that it is never larger than length and never smaller than 0.\n *\n * The returned value will move back and forth between 0 and length\n */\n Scalar.PingPong = function (tx, length) {\n var t = Scalar.Repeat(tx, length * 2.0);\n return length - Math.abs(t - length);\n };\n /**\n * Interpolates between min and max with smoothing at the limits.\n *\n * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up\n * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.\n */\n Scalar.SmoothStep = function (from, to, tx) {\n var t = Scalar.Clamp(tx);\n t = -2.0 * t * t * t + 3.0 * t * t;\n return to * t + from * (1.0 - t);\n };\n /**\n * Moves a value current towards target.\n *\n * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.\n * Negative values of maxDelta pushes the value away from target.\n */\n Scalar.MoveTowards = function (current, target, maxDelta) {\n var result = 0;\n if (Math.abs(target - current) <= maxDelta) {\n result = target;\n }\n else {\n result = current + Scalar.Sign(target - current) * maxDelta;\n }\n return result;\n };\n /**\n * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.\n *\n * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta\n * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.\n */\n Scalar.MoveTowardsAngle = function (current, target, maxDelta) {\n var num = Scalar.DeltaAngle(current, target);\n var result = 0;\n if (-maxDelta < num && num < maxDelta) {\n result = target;\n }\n else {\n target = current + num;\n result = Scalar.MoveTowards(current, target, maxDelta);\n }\n return result;\n };\n /**\n * Creates a new scalar with values linearly interpolated of \"amount\" between the start scalar and the end scalar.\n */\n Scalar.Lerp = function (start, end, amount) {\n return start + ((end - start) * amount);\n };\n /**\n * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.\n * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.\n */\n Scalar.LerpAngle = function (start, end, amount) {\n var num = Scalar.Repeat(end - start, 360.0);\n if (num > 180.0) {\n num -= 360.0;\n }\n return start + num * Scalar.Clamp(amount);\n };\n /**\n * Calculates the linear parameter t that produces the interpolant value within the range [a, b].\n */\n Scalar.InverseLerp = function (a, b, value) {\n var result = 0;\n if (a != b) {\n result = Scalar.Clamp((value - a) / (b - a));\n }\n else {\n result = 0.0;\n }\n return result;\n };\n /**\n * Returns a new scalar located for \"amount\" (float) on the Hermite spline defined by the scalars \"value1\", \"value3\", \"tangent1\", \"tangent2\".\n */\n Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {\n var squared = amount * amount;\n var cubed = amount * squared;\n var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;\n var part2 = (-2.0 * cubed) + (3.0 * squared);\n var part3 = (cubed - (2.0 * squared)) + amount;\n var part4 = cubed - squared;\n return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);\n };\n /**\n * Returns a random float number between and min and max values\n */\n Scalar.RandomRange = function (min, max) {\n if (min === max)\n return min;\n return ((Math.random() * (max - min)) + min);\n };\n /**\n * This function returns percentage of a number in a given range.\n *\n * RangeToPercent(40,20,60) will return 0.5 (50%)\n * RangeToPercent(34,0,100) will return 0.34 (34%)\n */\n Scalar.RangeToPercent = function (number, min, max) {\n return ((number - min) / (max - min));\n };\n /**\n * This function returns number that corresponds to the percentage in a given range.\n *\n * PercentToRange(0.34,0,100) will return 34.\n */\n Scalar.PercentToRange = function (percent, min, max) {\n return ((max - min) * percent + min);\n };\n /**\n * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.\n * @param angle The angle to normalize in radian.\n * @return The converted angle.\n */\n Scalar.NormalizeRadians = function (angle) {\n // More precise but slower version kept for reference.\n // angle = angle % Tools.TwoPi;\n // angle = (angle + Tools.TwoPi) % Tools.TwoPi;\n //if (angle > Math.PI) {\n //\tangle -= Tools.TwoPi;\n //}\n angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));\n return angle;\n };\n /**\n * Two pi constants convenient for computation.\n */\n Scalar.TwoPi = Math.PI * 2;\n return Scalar;\n }());\n BABYLON.Scalar = Scalar;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.math.scalar.js.map\n\n\n\n//# sourceMappingURL=babylon.mixins.js.map\n\n// Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800\n// Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/\n// Definitions by: Nico Kemnitz \n// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n\n//# sourceMappingURL=babylon.webgl2.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var __decoratorInitialStore = {};\n var __mergedStore = {};\n var _copySource = function (creationFunction, source, instanciate) {\n var destination = creationFunction();\n // Tags\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(destination, source.tags);\n }\n var classStore = getMergedStore(destination);\n // Properties\n for (var property in classStore) {\n var propertyDescriptor = classStore[property];\n var sourceProperty = source[property];\n var propertyType = propertyDescriptor.type;\n if (sourceProperty !== undefined && sourceProperty !== null) {\n switch (propertyType) {\n case 0: // Value\n case 6: // Mesh reference\n case 11: // Camera reference\n destination[property] = sourceProperty;\n break;\n case 1: // Texture\n destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();\n break;\n case 2: // Color3\n case 3: // FresnelParameters\n case 4: // Vector2\n case 5: // Vector3\n case 7: // Color Curves\n case 10: // Quaternion\n destination[property] = instanciate ? sourceProperty : sourceProperty.clone();\n break;\n }\n }\n }\n return destination;\n };\n function getDirectStore(target) {\n var classKey = target.getClassName();\n if (!__decoratorInitialStore[classKey]) {\n __decoratorInitialStore[classKey] = {};\n }\n return __decoratorInitialStore[classKey];\n }\n /**\n * Return the list of properties flagged as serializable\n * @param target: host object\n */\n function getMergedStore(target) {\n var classKey = target.getClassName();\n if (__mergedStore[classKey]) {\n return __mergedStore[classKey];\n }\n __mergedStore[classKey] = {};\n var store = __mergedStore[classKey];\n var currentTarget = target;\n var currentKey = classKey;\n while (currentKey) {\n var initialStore = __decoratorInitialStore[currentKey];\n for (var property in initialStore) {\n store[property] = initialStore[property];\n }\n var parent_1 = void 0;\n var done = false;\n do {\n parent_1 = Object.getPrototypeOf(currentTarget);\n if (!parent_1.getClassName) {\n done = true;\n break;\n }\n if (parent_1.getClassName() !== currentKey) {\n break;\n }\n currentTarget = parent_1;\n } while (parent_1);\n if (done) {\n break;\n }\n currentKey = parent_1.getClassName();\n currentTarget = parent_1;\n }\n return store;\n }\n function generateSerializableMember(type, sourceName) {\n return function (target, propertyKey) {\n var classStore = getDirectStore(target);\n if (!classStore[propertyKey]) {\n classStore[propertyKey] = { type: type, sourceName: sourceName };\n }\n };\n }\n function generateExpandMember(setCallback, targetKey) {\n if (targetKey === void 0) { targetKey = null; }\n return function (target, propertyKey) {\n var key = targetKey || (\"_\" + propertyKey);\n Object.defineProperty(target, propertyKey, {\n get: function () {\n return this[key];\n },\n set: function (value) {\n if (this[key] === value) {\n return;\n }\n this[key] = value;\n target[setCallback].apply(this);\n },\n enumerable: true,\n configurable: true\n });\n };\n }\n function expandToProperty(callback, targetKey) {\n if (targetKey === void 0) { targetKey = null; }\n return generateExpandMember(callback, targetKey);\n }\n BABYLON.expandToProperty = expandToProperty;\n function serialize(sourceName) {\n return generateSerializableMember(0, sourceName); // value member\n }\n BABYLON.serialize = serialize;\n function serializeAsTexture(sourceName) {\n return generateSerializableMember(1, sourceName); // texture member\n }\n BABYLON.serializeAsTexture = serializeAsTexture;\n function serializeAsColor3(sourceName) {\n return generateSerializableMember(2, sourceName); // color3 member\n }\n BABYLON.serializeAsColor3 = serializeAsColor3;\n function serializeAsFresnelParameters(sourceName) {\n return generateSerializableMember(3, sourceName); // fresnel parameters member\n }\n BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;\n function serializeAsVector2(sourceName) {\n return generateSerializableMember(4, sourceName); // vector2 member\n }\n BABYLON.serializeAsVector2 = serializeAsVector2;\n function serializeAsVector3(sourceName) {\n return generateSerializableMember(5, sourceName); // vector3 member\n }\n BABYLON.serializeAsVector3 = serializeAsVector3;\n function serializeAsMeshReference(sourceName) {\n return generateSerializableMember(6, sourceName); // mesh reference member\n }\n BABYLON.serializeAsMeshReference = serializeAsMeshReference;\n function serializeAsColorCurves(sourceName) {\n return generateSerializableMember(7, sourceName); // color curves\n }\n BABYLON.serializeAsColorCurves = serializeAsColorCurves;\n function serializeAsColor4(sourceName) {\n return generateSerializableMember(8, sourceName); // color 4\n }\n BABYLON.serializeAsColor4 = serializeAsColor4;\n function serializeAsImageProcessingConfiguration(sourceName) {\n return generateSerializableMember(9, sourceName); // image processing\n }\n BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;\n function serializeAsQuaternion(sourceName) {\n return generateSerializableMember(10, sourceName); // quaternion member\n }\n BABYLON.serializeAsQuaternion = serializeAsQuaternion;\n /**\n * Decorator used to define property that can be serialized as reference to a camera\n * @param sourceName defines the name of the property to decorate\n */\n function serializeAsCameraReference(sourceName) {\n return generateSerializableMember(11, sourceName); // camera reference member\n }\n BABYLON.serializeAsCameraReference = serializeAsCameraReference;\n var SerializationHelper = /** @class */ (function () {\n function SerializationHelper() {\n }\n SerializationHelper.Serialize = function (entity, serializationObject) {\n if (!serializationObject) {\n serializationObject = {};\n }\n // Tags\n if (BABYLON.Tags) {\n serializationObject.tags = BABYLON.Tags.GetTags(entity);\n }\n var serializedProperties = getMergedStore(entity);\n // Properties\n for (var property in serializedProperties) {\n var propertyDescriptor = serializedProperties[property];\n var targetPropertyName = propertyDescriptor.sourceName || property;\n var propertyType = propertyDescriptor.type;\n var sourceProperty = entity[property];\n if (sourceProperty !== undefined && sourceProperty !== null) {\n switch (propertyType) {\n case 0: // Value\n serializationObject[targetPropertyName] = sourceProperty;\n break;\n case 1: // Texture\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 2: // Color3\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 3: // FresnelParameters\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 4: // Vector2\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 5: // Vector3\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 6: // Mesh reference\n serializationObject[targetPropertyName] = sourceProperty.id;\n break;\n case 7: // Color Curves\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 8: // Color 4\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 9: // Image Processing\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 10: // Quaternion\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 11: // Camera reference\n serializationObject[targetPropertyName] = sourceProperty.id;\n break;\n }\n }\n }\n return serializationObject;\n };\n SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {\n if (rootUrl === void 0) { rootUrl = null; }\n var destination = creationFunction();\n if (!rootUrl) {\n rootUrl = \"\";\n }\n // Tags\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(destination, source.tags);\n }\n var classStore = getMergedStore(destination);\n // Properties\n for (var property in classStore) {\n var propertyDescriptor = classStore[property];\n var sourceProperty = source[propertyDescriptor.sourceName || property];\n var propertyType = propertyDescriptor.type;\n if (sourceProperty !== undefined && sourceProperty !== null) {\n var dest = destination;\n switch (propertyType) {\n case 0: // Value\n dest[property] = sourceProperty;\n break;\n case 1: // Texture\n if (scene) {\n dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);\n }\n break;\n case 2: // Color3\n dest[property] = BABYLON.Color3.FromArray(sourceProperty);\n break;\n case 3: // FresnelParameters\n dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);\n break;\n case 4: // Vector2\n dest[property] = BABYLON.Vector2.FromArray(sourceProperty);\n break;\n case 5: // Vector3\n dest[property] = BABYLON.Vector3.FromArray(sourceProperty);\n break;\n case 6: // Mesh reference\n if (scene) {\n dest[property] = scene.getLastMeshByID(sourceProperty);\n }\n break;\n case 7: // Color Curves\n dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);\n break;\n case 8: // Color 4\n dest[property] = BABYLON.Color4.FromArray(sourceProperty);\n break;\n case 9: // Image Processing\n dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);\n break;\n case 10: // Quaternion\n dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);\n break;\n case 11: // Camera reference\n if (scene) {\n dest[property] = scene.getCameraByID(sourceProperty);\n }\n break;\n }\n }\n }\n return destination;\n };\n SerializationHelper.Clone = function (creationFunction, source) {\n return _copySource(creationFunction, source, false);\n };\n SerializationHelper.Instanciate = function (creationFunction, source) {\n return _copySource(creationFunction, source, true);\n };\n return SerializationHelper;\n }());\n BABYLON.SerializationHelper = SerializationHelper;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.decorators.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Wrapper class for promise with external resolve and reject.\n */\n var Deferred = /** @class */ (function () {\n /**\n * Constructor for this deferred object.\n */\n function Deferred() {\n var _this = this;\n this.promise = new Promise(function (resolve, reject) {\n _this._resolve = resolve;\n _this._reject = reject;\n });\n }\n Object.defineProperty(Deferred.prototype, \"resolve\", {\n /**\n * The resolve method of the promise associated with this deferred object.\n */\n get: function () {\n return this._resolve;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Deferred.prototype, \"reject\", {\n /**\n * The reject method of the promise associated with this deferred object.\n */\n get: function () {\n return this._reject;\n },\n enumerable: true,\n configurable: true\n });\n return Deferred;\n }());\n BABYLON.Deferred = Deferred;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.deferred.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A class serves as a medium between the observable and its observers\n */\n var EventState = /** @class */ (function () {\n /**\n * Create a new EventState\n * @param mask defines the mask associated with this state\n * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true\n * @param target defines the original target of the state\n * @param currentTarget defines the current target of the state\n */\n function EventState(mask, skipNextObservers, target, currentTarget) {\n if (skipNextObservers === void 0) { skipNextObservers = false; }\n this.initalize(mask, skipNextObservers, target, currentTarget);\n }\n /**\n * Initialize the current event state\n * @param mask defines the mask associated with this state\n * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true\n * @param target defines the original target of the state\n * @param currentTarget defines the current target of the state\n * @returns the current event state\n */\n EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {\n if (skipNextObservers === void 0) { skipNextObservers = false; }\n this.mask = mask;\n this.skipNextObservers = skipNextObservers;\n this.target = target;\n this.currentTarget = currentTarget;\n return this;\n };\n return EventState;\n }());\n BABYLON.EventState = EventState;\n /**\n * Represent an Observer registered to a given Observable object.\n */\n var Observer = /** @class */ (function () {\n /**\n * Creates a new observer\n * @param callback defines the callback to call when the observer is notified\n * @param mask defines the mask of the observer (used to filter notifications)\n * @param scope defines the current scope used to restore the JS context\n */\n function Observer(\n /**\n * Defines the callback to call when the observer is notified\n */\n callback, \n /**\n * Defines the mask of the observer (used to filter notifications)\n */\n mask, \n /**\n * Defines the current scope used to restore the JS context\n */\n scope) {\n if (scope === void 0) { scope = null; }\n this.callback = callback;\n this.mask = mask;\n this.scope = scope;\n /** @hidden */\n this._willBeUnregistered = false;\n /**\n * Gets or sets a property defining that the observer as to be unregistered after the next notification\n */\n this.unregisterOnNextCall = false;\n }\n return Observer;\n }());\n BABYLON.Observer = Observer;\n /**\n * Represent a list of observers registered to multiple Observables object.\n */\n var MultiObserver = /** @class */ (function () {\n function MultiObserver() {\n }\n /**\n * Release associated resources\n */\n MultiObserver.prototype.dispose = function () {\n if (this._observers && this._observables) {\n for (var index = 0; index < this._observers.length; index++) {\n this._observables[index].remove(this._observers[index]);\n }\n }\n this._observers = null;\n this._observables = null;\n };\n /**\n * Raise a callback when one of the observable will notify\n * @param observables defines a list of observables to watch\n * @param callback defines the callback to call on notification\n * @param mask defines the mask used to filter notifications\n * @param scope defines the current scope used to restore the JS context\n * @returns the new MultiObserver\n */\n MultiObserver.Watch = function (observables, callback, mask, scope) {\n if (mask === void 0) { mask = -1; }\n if (scope === void 0) { scope = null; }\n var result = new MultiObserver();\n result._observers = new Array();\n result._observables = observables;\n for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {\n var observable = observables_1[_i];\n var observer = observable.add(callback, mask, false, scope);\n if (observer) {\n result._observers.push(observer);\n }\n }\n return result;\n };\n return MultiObserver;\n }());\n BABYLON.MultiObserver = MultiObserver;\n /**\n * The Observable class is a simple implementation of the Observable pattern.\n *\n * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.\n * This enable a more fine grained execution without having to rely on multiple different Observable objects.\n * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).\n * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.\n */\n var Observable = /** @class */ (function () {\n /**\n * Creates a new observable\n * @param onObserverAdded defines a callback to call when a new observer is added\n */\n function Observable(onObserverAdded) {\n this._observers = new Array();\n this._eventState = new EventState(0);\n if (onObserverAdded) {\n this._onObserverAdded = onObserverAdded;\n }\n }\n /**\n * Create a new Observer with the specified callback\n * @param callback the callback that will be executed for that Observer\n * @param mask the mask used to filter observers\n * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.\n * @param scope optional scope for the callback to be called from\n * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification\n * @returns the new observer created for the callback\n */\n Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {\n if (mask === void 0) { mask = -1; }\n if (insertFirst === void 0) { insertFirst = false; }\n if (scope === void 0) { scope = null; }\n if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }\n if (!callback) {\n return null;\n }\n var observer = new Observer(callback, mask, scope);\n observer.unregisterOnNextCall = unregisterOnFirstCall;\n if (insertFirst) {\n this._observers.unshift(observer);\n }\n else {\n this._observers.push(observer);\n }\n if (this._onObserverAdded) {\n this._onObserverAdded(observer);\n }\n return observer;\n };\n /**\n * Create a new Observer with the specified callback and unregisters after the next notification\n * @param callback the callback that will be executed for that Observer\n * @returns the new observer created for the callback\n */\n Observable.prototype.addOnce = function (callback) {\n return this.add(callback, undefined, undefined, undefined, true);\n };\n /**\n * Remove an Observer from the Observable object\n * @param observer the instance of the Observer to remove\n * @returns false if it doesn't belong to this Observable\n */\n Observable.prototype.remove = function (observer) {\n if (!observer) {\n return false;\n }\n var index = this._observers.indexOf(observer);\n if (index !== -1) {\n this._deferUnregister(observer);\n return true;\n }\n return false;\n };\n /**\n * Remove a callback from the Observable object\n * @param callback the callback to remove\n * @param scope optional scope. If used only the callbacks with this scope will be removed\n * @returns false if it doesn't belong to this Observable\n */\n Observable.prototype.removeCallback = function (callback, scope) {\n for (var index = 0; index < this._observers.length; index++) {\n if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {\n this._deferUnregister(this._observers[index]);\n return true;\n }\n }\n return false;\n };\n Observable.prototype._deferUnregister = function (observer) {\n var _this = this;\n observer.unregisterOnNextCall = false;\n observer._willBeUnregistered = true;\n BABYLON.Tools.SetImmediate(function () {\n _this._remove(observer);\n });\n };\n // This should only be called when not iterating over _observers to avoid callback skipping.\n // Removes an observer from the _observer Array.\n Observable.prototype._remove = function (observer) {\n if (!observer) {\n return false;\n }\n var index = this._observers.indexOf(observer);\n if (index !== -1) {\n this._observers.splice(index, 1);\n return true;\n }\n return false;\n };\n /**\n * Notify all Observers by calling their respective callback with the given data\n * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute\n * @param eventData defines the data to send to all observers\n * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)\n * @param target defines the original target of the state\n * @param currentTarget defines the current target of the state\n * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)\n */\n Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {\n if (mask === void 0) { mask = -1; }\n if (!this._observers.length) {\n return true;\n }\n var state = this._eventState;\n state.mask = mask;\n state.target = target;\n state.currentTarget = currentTarget;\n state.skipNextObservers = false;\n state.lastReturnValue = eventData;\n for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {\n var obs = _a[_i];\n if (obs._willBeUnregistered) {\n continue;\n }\n if (obs.mask & mask) {\n if (obs.scope) {\n state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);\n }\n else {\n state.lastReturnValue = obs.callback(eventData, state);\n }\n if (obs.unregisterOnNextCall) {\n this._deferUnregister(obs);\n }\n }\n if (state.skipNextObservers) {\n return false;\n }\n }\n return true;\n };\n /**\n * Calling this will execute each callback, expecting it to be a promise or return a value.\n * If at any point in the chain one function fails, the promise will fail and the execution will not continue.\n * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object\n * and it is crucial that all callbacks will be executed.\n * The order of the callbacks is kept, callbacks are not executed parallel.\n *\n * @param eventData The data to be sent to each callback\n * @param mask is used to filter observers defaults to -1\n * @param target defines the callback target (see EventState)\n * @param currentTarget defines he current object in the bubbling phase\n * @returns {Promise} will return a Promise than resolves when all callbacks executed successfully.\n */\n Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {\n var _this = this;\n if (mask === void 0) { mask = -1; }\n // create an empty promise\n var p = Promise.resolve(eventData);\n // no observers? return this promise.\n if (!this._observers.length) {\n return p;\n }\n var state = this._eventState;\n state.mask = mask;\n state.target = target;\n state.currentTarget = currentTarget;\n state.skipNextObservers = false;\n // execute one callback after another (not using Promise.all, the order is important)\n this._observers.forEach(function (obs) {\n if (state.skipNextObservers) {\n return;\n }\n if (obs._willBeUnregistered) {\n return;\n }\n if (obs.mask & mask) {\n if (obs.scope) {\n p = p.then(function (lastReturnedValue) {\n state.lastReturnValue = lastReturnedValue;\n return obs.callback.apply(obs.scope, [eventData, state]);\n });\n }\n else {\n p = p.then(function (lastReturnedValue) {\n state.lastReturnValue = lastReturnedValue;\n return obs.callback(eventData, state);\n });\n }\n if (obs.unregisterOnNextCall) {\n _this._deferUnregister(obs);\n }\n }\n });\n // return the eventData\n return p.then(function () { return eventData; });\n };\n /**\n * Notify a specific observer\n * @param observer defines the observer to notify\n * @param eventData defines the data to be sent to each callback\n * @param mask is used to filter observers defaults to -1\n */\n Observable.prototype.notifyObserver = function (observer, eventData, mask) {\n if (mask === void 0) { mask = -1; }\n var state = this._eventState;\n state.mask = mask;\n state.skipNextObservers = false;\n observer.callback(eventData, state);\n };\n /**\n * Gets a boolean indicating if the observable has at least one observer\n * @returns true is the Observable has at least one Observer registered\n */\n Observable.prototype.hasObservers = function () {\n return this._observers.length > 0;\n };\n /**\n * Clear the list of observers\n */\n Observable.prototype.clear = function () {\n this._observers = new Array();\n this._onObserverAdded = null;\n };\n /**\n * Clone the current observable\n * @returns a new observable\n */\n Observable.prototype.clone = function () {\n var result = new Observable();\n result._observers = this._observers.slice(0);\n return result;\n };\n /**\n * Does this observable handles observer registered with a given mask\n * @param mask defines the mask to be tested\n * @return whether or not one observer registered with the given mask is handeled\n **/\n Observable.prototype.hasSpecificMask = function (mask) {\n if (mask === void 0) { mask = -1; }\n for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {\n var obs = _a[_i];\n if (obs.mask & mask || obs.mask === mask) {\n return true;\n }\n }\n return false;\n };\n return Observable;\n }());\n BABYLON.Observable = Observable;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.observable.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var SmartArray = /** @class */ (function () {\n function SmartArray(capacity) {\n this.length = 0;\n this.data = new Array(capacity);\n this._id = SmartArray._GlobalId++;\n }\n SmartArray.prototype.push = function (value) {\n this.data[this.length++] = value;\n if (this.length > this.data.length) {\n this.data.length *= 2;\n }\n };\n SmartArray.prototype.forEach = function (func) {\n for (var index = 0; index < this.length; index++) {\n func(this.data[index]);\n }\n };\n SmartArray.prototype.sort = function (compareFn) {\n this.data.sort(compareFn);\n };\n SmartArray.prototype.reset = function () {\n this.length = 0;\n };\n SmartArray.prototype.dispose = function () {\n this.reset();\n if (this.data) {\n this.data.length = 0;\n this.data = [];\n }\n };\n SmartArray.prototype.concat = function (array) {\n if (array.length === 0) {\n return;\n }\n if (this.length + array.length > this.data.length) {\n this.data.length = (this.length + array.length) * 2;\n }\n for (var index = 0; index < array.length; index++) {\n this.data[this.length++] = (array.data || array)[index];\n }\n };\n SmartArray.prototype.indexOf = function (value) {\n var position = this.data.indexOf(value);\n if (position >= this.length) {\n return -1;\n }\n return position;\n };\n SmartArray.prototype.contains = function (value) {\n return this.data.indexOf(value) !== -1;\n };\n // Statics\n SmartArray._GlobalId = 0;\n return SmartArray;\n }());\n BABYLON.SmartArray = SmartArray;\n var SmartArrayNoDuplicate = /** @class */ (function (_super) {\n __extends(SmartArrayNoDuplicate, _super);\n function SmartArrayNoDuplicate() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this._duplicateId = 0;\n return _this;\n }\n SmartArrayNoDuplicate.prototype.push = function (value) {\n _super.prototype.push.call(this, value);\n if (!value.__smartArrayFlags) {\n value.__smartArrayFlags = {};\n }\n value.__smartArrayFlags[this._id] = this._duplicateId;\n };\n SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {\n if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {\n return false;\n }\n this.push(value);\n return true;\n };\n SmartArrayNoDuplicate.prototype.reset = function () {\n _super.prototype.reset.call(this);\n this._duplicateId++;\n };\n SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {\n if (array.length === 0) {\n return;\n }\n if (this.length + array.length > this.data.length) {\n this.data.length = (this.length + array.length) * 2;\n }\n for (var index = 0; index < array.length; index++) {\n var item = (array.data || array)[index];\n this.pushNoDuplicate(item);\n }\n };\n return SmartArrayNoDuplicate;\n }(SmartArray));\n BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.smartArray.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /** Class used to store color gradient */\n var ColorGradient = /** @class */ (function () {\n function ColorGradient() {\n }\n /**\n * Will get a color picked randomly between color1 and color2.\n * If color2 is undefined then color1 will be used\n * @param result defines the target Color4 to store the result in\n */\n ColorGradient.prototype.getColorToRef = function (result) {\n if (!this.color2) {\n result.copyFrom(this.color1);\n return;\n }\n BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);\n };\n return ColorGradient;\n }());\n BABYLON.ColorGradient = ColorGradient;\n /** Class used to store factor gradient */\n var FactorGradient = /** @class */ (function () {\n function FactorGradient() {\n }\n /**\n * Will get a number picked randomly between factor1 and factor2.\n * If factor2 is undefined then factor1 will be used\n * @returns the picked number\n */\n FactorGradient.prototype.getFactor = function () {\n if (this.factor2 === undefined) {\n return this.factor1;\n }\n return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());\n };\n return FactorGradient;\n }());\n BABYLON.FactorGradient = FactorGradient;\n // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript\n // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work\n var LoadFileError = /** @class */ (function (_super) {\n __extends(LoadFileError, _super);\n function LoadFileError(message, request) {\n var _this = _super.call(this, message) || this;\n _this.request = request;\n _this.name = \"LoadFileError\";\n LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);\n return _this;\n }\n // Polyfill for Object.setPrototypeOf if necessary.\n LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });\n return LoadFileError;\n }(Error));\n BABYLON.LoadFileError = LoadFileError;\n var RetryStrategy = /** @class */ (function () {\n function RetryStrategy() {\n }\n RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {\n if (maxRetries === void 0) { maxRetries = 3; }\n if (baseInterval === void 0) { baseInterval = 500; }\n return function (url, request, retryIndex) {\n if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf(\"file:\") !== -1) {\n return -1;\n }\n return Math.pow(2, retryIndex) * baseInterval;\n };\n };\n return RetryStrategy;\n }());\n BABYLON.RetryStrategy = RetryStrategy;\n // Screenshots\n var screenshotCanvas;\n var cloneValue = function (source, destinationObject) {\n if (!source)\n return null;\n if (source instanceof BABYLON.Mesh) {\n return null;\n }\n if (source instanceof BABYLON.SubMesh) {\n return source.clone(destinationObject);\n }\n else if (source.clone) {\n return source.clone();\n }\n return null;\n };\n var Tools = /** @class */ (function () {\n function Tools() {\n }\n /**\n * Read the content of a byte array at a specified coordinates (taking in account wrapping)\n * @param u defines the coordinate on X axis\n * @param v defines the coordinate on Y axis\n * @param width defines the width of the source data\n * @param height defines the height of the source data\n * @param pixels defines the source byte array\n * @param color defines the output color\n */\n Tools.FetchToRef = function (u, v, width, height, pixels, color) {\n var wrappedU = ((Math.abs(u) * width) % width) | 0;\n var wrappedV = ((Math.abs(v) * height) % height) | 0;\n var position = (wrappedU + wrappedV * width) * 4;\n color.r = pixels[position] / 255;\n color.g = pixels[position + 1] / 255;\n color.b = pixels[position + 2] / 255;\n color.a = pixels[position + 3] / 255;\n };\n /**\n * Interpolates between a and b via alpha\n * @param a The lower value (returned when alpha = 0)\n * @param b The upper value (returned when alpha = 1)\n * @param alpha The interpolation-factor\n * @return The mixed value\n */\n Tools.Mix = function (a, b, alpha) {\n return a * (1 - alpha) + b * alpha;\n };\n Tools.Instantiate = function (className) {\n if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {\n return Tools.RegisteredExternalClasses[className];\n }\n var arr = className.split(\".\");\n var fn = (window || this);\n for (var i = 0, len = arr.length; i < len; i++) {\n fn = fn[arr[i]];\n }\n if (typeof fn !== \"function\") {\n return null;\n }\n return fn;\n };\n /**\n * Provides a slice function that will work even on IE\n * @param data defines the array to slice\n * @param start defines the start of the data (optional)\n * @param end defines the end of the data (optional)\n * @returns the new sliced array\n */\n Tools.Slice = function (data, start, end) {\n if (data.slice) {\n return data.slice(start, end);\n }\n return Array.prototype.slice.call(data, start, end);\n };\n Tools.SetImmediate = function (action) {\n if (Tools.IsWindowObjectExist() && window.setImmediate) {\n window.setImmediate(action);\n }\n else {\n setTimeout(action, 1);\n }\n };\n Tools.IsExponentOfTwo = function (value) {\n var count = 1;\n do {\n count *= 2;\n } while (count < value);\n return count === value;\n };\n /**\n * Returns the nearest 32-bit single precision float representation of a Number\n * @param value A Number. If the parameter is of a different type, it will get converted\n * to a number or to NaN if it cannot be converted\n * @returns number\n */\n Tools.FloatRound = function (value) {\n if (Math.fround) {\n return Math.fround(value);\n }\n return (Tools._tmpFloatArray[0] = value);\n };\n /**\n * Find the next highest power of two.\n * @param x Number to start search from.\n * @return Next highest power of two.\n */\n Tools.CeilingPOT = function (x) {\n x--;\n x |= x >> 1;\n x |= x >> 2;\n x |= x >> 4;\n x |= x >> 8;\n x |= x >> 16;\n x++;\n return x;\n };\n /**\n * Find the next lowest power of two.\n * @param x Number to start search from.\n * @return Next lowest power of two.\n */\n Tools.FloorPOT = function (x) {\n x = x | (x >> 1);\n x = x | (x >> 2);\n x = x | (x >> 4);\n x = x | (x >> 8);\n x = x | (x >> 16);\n return x - (x >> 1);\n };\n /**\n * Find the nearest power of two.\n * @param x Number to start search from.\n * @return Next nearest power of two.\n */\n Tools.NearestPOT = function (x) {\n var c = Tools.CeilingPOT(x);\n var f = Tools.FloorPOT(x);\n return (c - x) > (x - f) ? f : c;\n };\n Tools.GetExponentOfTwo = function (value, max, mode) {\n if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }\n var pot;\n switch (mode) {\n case BABYLON.Engine.SCALEMODE_FLOOR:\n pot = Tools.FloorPOT(value);\n break;\n case BABYLON.Engine.SCALEMODE_NEAREST:\n pot = Tools.NearestPOT(value);\n break;\n case BABYLON.Engine.SCALEMODE_CEILING:\n default:\n pot = Tools.CeilingPOT(value);\n break;\n }\n return Math.min(pot, max);\n };\n Tools.GetFilename = function (path) {\n var index = path.lastIndexOf(\"/\");\n if (index < 0)\n return path;\n return path.substring(index + 1);\n };\n /**\n * Extracts the \"folder\" part of a path (everything before the filename).\n * @param uri The URI to extract the info from\n * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present\n * @returns The \"folder\" part of the path\n */\n Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {\n if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }\n var index = uri.lastIndexOf(\"/\");\n if (index < 0) {\n if (returnUnchangedIfNoSlash) {\n return uri;\n }\n return \"\";\n }\n return uri.substring(0, index + 1);\n };\n Tools.GetDOMTextContent = function (element) {\n var result = \"\";\n var child = element.firstChild;\n while (child) {\n if (child.nodeType === 3) {\n result += child.textContent;\n }\n child = child.nextSibling;\n }\n return result;\n };\n Tools.ToDegrees = function (angle) {\n return angle * 180 / Math.PI;\n };\n Tools.ToRadians = function (angle) {\n return angle * Math.PI / 180;\n };\n Tools.EncodeArrayBufferTobase64 = function (buffer) {\n var keyStr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n var output = \"\";\n var chr1, chr2, chr3, enc1, enc2, enc3, enc4;\n var i = 0;\n var bytes = new Uint8Array(buffer);\n while (i < bytes.length) {\n chr1 = bytes[i++];\n chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index \n chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here\n enc1 = chr1 >> 2;\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\n enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);\n enc4 = chr3 & 63;\n if (isNaN(chr2)) {\n enc3 = enc4 = 64;\n }\n else if (isNaN(chr3)) {\n enc4 = 64;\n }\n output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +\n keyStr.charAt(enc3) + keyStr.charAt(enc4);\n }\n return \"data:image/png;base64,\" + output;\n };\n Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {\n if (bias === void 0) { bias = null; }\n var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n for (var index = indexStart; index < indexStart + indexCount; index++) {\n var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);\n minimum = BABYLON.Vector3.Minimize(current, minimum);\n maximum = BABYLON.Vector3.Maximize(current, maximum);\n }\n if (bias) {\n minimum.x -= minimum.x * bias.x + bias.y;\n minimum.y -= minimum.y * bias.x + bias.y;\n minimum.z -= minimum.z * bias.x + bias.y;\n maximum.x += maximum.x * bias.x + bias.y;\n maximum.y += maximum.y * bias.x + bias.y;\n maximum.z += maximum.z * bias.x + bias.y;\n }\n return {\n minimum: minimum,\n maximum: maximum\n };\n };\n Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {\n if (bias === void 0) { bias = null; }\n var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n if (!stride) {\n stride = 3;\n }\n for (var index = start; index < start + count; index++) {\n var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);\n minimum = BABYLON.Vector3.Minimize(current, minimum);\n maximum = BABYLON.Vector3.Maximize(current, maximum);\n }\n if (bias) {\n minimum.x -= minimum.x * bias.x + bias.y;\n minimum.y -= minimum.y * bias.x + bias.y;\n minimum.z -= minimum.z * bias.x + bias.y;\n maximum.x += maximum.x * bias.x + bias.y;\n maximum.y += maximum.y * bias.x + bias.y;\n maximum.z += maximum.z * bias.x + bias.y;\n }\n return {\n minimum: minimum,\n maximum: maximum\n };\n };\n Tools.Vector2ArrayFeeder = function (array) {\n return function (index) {\n var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);\n var length = isFloatArray ? array.length / 2 : array.length;\n if (index >= length) {\n return null;\n }\n if (isFloatArray) {\n var fa = array;\n return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);\n }\n var a = array;\n return a[index];\n };\n };\n Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {\n if (bias === void 0) { bias = null; }\n var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);\n var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);\n var i = 0;\n var cur = feeder(i++);\n while (cur) {\n minimum = BABYLON.Vector2.Minimize(cur, minimum);\n maximum = BABYLON.Vector2.Maximize(cur, maximum);\n cur = feeder(i++);\n }\n if (bias) {\n minimum.x -= minimum.x * bias.x + bias.y;\n minimum.y -= minimum.y * bias.x + bias.y;\n maximum.x += maximum.x * bias.x + bias.y;\n maximum.y += maximum.y * bias.x + bias.y;\n }\n return {\n minimum: minimum,\n maximum: maximum\n };\n };\n Tools.MakeArray = function (obj, allowsNullUndefined) {\n if (allowsNullUndefined !== true && (obj === undefined || obj == null))\n return null;\n return Array.isArray(obj) ? obj : [obj];\n };\n // Misc.\n Tools.GetPointerPrefix = function () {\n var eventPrefix = \"pointer\";\n // Check if pointer events are supported\n if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {\n eventPrefix = \"mouse\";\n }\n return eventPrefix;\n };\n /**\n * @param func - the function to be called\n * @param requester - the object that will request the next frame. Falls back to window.\n */\n Tools.QueueNewFrame = function (func, requester) {\n if (!Tools.IsWindowObjectExist()) {\n return setTimeout(func, 16);\n }\n if (!requester) {\n requester = window;\n }\n if (requester.requestAnimationFrame) {\n return requester.requestAnimationFrame(func);\n }\n else if (requester.msRequestAnimationFrame) {\n return requester.msRequestAnimationFrame(func);\n }\n else if (requester.webkitRequestAnimationFrame) {\n return requester.webkitRequestAnimationFrame(func);\n }\n else if (requester.mozRequestAnimationFrame) {\n return requester.mozRequestAnimationFrame(func);\n }\n else if (requester.oRequestAnimationFrame) {\n return requester.oRequestAnimationFrame(func);\n }\n else {\n return window.setTimeout(func, 16);\n }\n };\n Tools.RequestFullscreen = function (element) {\n var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;\n if (!requestFunction)\n return;\n requestFunction.call(element);\n };\n Tools.ExitFullscreen = function () {\n if (document.exitFullscreen) {\n document.exitFullscreen();\n }\n else if (document.mozCancelFullScreen) {\n document.mozCancelFullScreen();\n }\n else if (document.webkitCancelFullScreen) {\n document.webkitCancelFullScreen();\n }\n else if (document.msCancelFullScreen) {\n document.msCancelFullScreen();\n }\n };\n Tools.SetCorsBehavior = function (url, element) {\n if (url && url.indexOf(\"data:\") === 0) {\n return;\n }\n if (Tools.CorsBehavior) {\n if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {\n element.crossOrigin = Tools.CorsBehavior;\n }\n else {\n var result = Tools.CorsBehavior(url);\n if (result) {\n element.crossOrigin = result;\n }\n }\n }\n };\n // External files\n Tools.CleanUrl = function (url) {\n url = url.replace(/#/mg, \"%23\");\n return url;\n };\n /**\n * Loads an image as an HTMLImageElement.\n * @param input url string, ArrayBuffer, or Blob to load\n * @param onLoad callback called when the image successfully loads\n * @param onError callback called when the image fails to load\n * @param database database for caching\n * @returns the HTMLImageElement of the loaded image\n */\n Tools.LoadImage = function (input, onLoad, onError, database) {\n var url;\n var usingObjectURL = false;\n if (input instanceof ArrayBuffer) {\n url = URL.createObjectURL(new Blob([input]));\n usingObjectURL = true;\n }\n else if (input instanceof Blob) {\n url = URL.createObjectURL(input);\n usingObjectURL = true;\n }\n else {\n url = Tools.CleanUrl(input);\n url = Tools.PreprocessUrl(input);\n }\n var img = new Image();\n Tools.SetCorsBehavior(url, img);\n var loadHandler = function () {\n if (usingObjectURL && img.src) {\n URL.revokeObjectURL(img.src);\n }\n img.removeEventListener(\"load\", loadHandler);\n img.removeEventListener(\"error\", errorHandler);\n onLoad(img);\n };\n var errorHandler = function (err) {\n if (usingObjectURL && img.src) {\n URL.revokeObjectURL(img.src);\n }\n img.removeEventListener(\"load\", loadHandler);\n img.removeEventListener(\"error\", errorHandler);\n Tools.Error(\"Error while trying to load image: \" + input);\n if (onError) {\n onError(\"Error while trying to load image: \" + input, err);\n }\n };\n img.addEventListener(\"load\", loadHandler);\n img.addEventListener(\"error\", errorHandler);\n var noIndexedDB = function () {\n img.src = url;\n };\n var loadFromIndexedDB = function () {\n if (database) {\n database.loadImageFromDB(url, img);\n }\n };\n //ANY database to do!\n if (url.substr(0, 5) !== \"data:\" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {\n database.openAsync(loadFromIndexedDB, noIndexedDB);\n }\n else {\n if (url.indexOf(\"file:\") !== -1) {\n var textureName = decodeURIComponent(url.substring(5).toLowerCase());\n if (BABYLON.FilesInput.FilesToLoad[textureName]) {\n try {\n var blobURL;\n try {\n blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });\n }\n catch (ex) {\n // Chrome doesn't support oneTimeOnly parameter\n blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);\n }\n img.src = blobURL;\n usingObjectURL = true;\n }\n catch (e) {\n img.src = \"\";\n }\n return img;\n }\n }\n noIndexedDB();\n }\n return img;\n };\n Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {\n url = Tools.CleanUrl(url);\n url = Tools.PreprocessUrl(url);\n // If file and file input are set\n if (url.indexOf(\"file:\") !== -1) {\n var fileName = decodeURIComponent(url.substring(5).toLowerCase());\n if (BABYLON.FilesInput.FilesToLoad[fileName]) {\n return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);\n }\n }\n var loadUrl = Tools.BaseUrl + url;\n var aborted = false;\n var fileRequest = {\n onCompleteObservable: new BABYLON.Observable(),\n abort: function () { return aborted = true; },\n };\n var requestFile = function () {\n var request = new XMLHttpRequest();\n var retryHandle = null;\n fileRequest.abort = function () {\n aborted = true;\n if (request.readyState !== (XMLHttpRequest.DONE || 4)) {\n request.abort();\n }\n if (retryHandle !== null) {\n clearTimeout(retryHandle);\n retryHandle = null;\n }\n };\n var retryLoop = function (retryIndex) {\n request.open('GET', loadUrl, true);\n if (useArrayBuffer) {\n request.responseType = \"arraybuffer\";\n }\n if (onProgress) {\n request.addEventListener(\"progress\", onProgress);\n }\n var onLoadEnd = function () {\n request.removeEventListener(\"loadend\", onLoadEnd);\n fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n fileRequest.onCompleteObservable.clear();\n };\n request.addEventListener(\"loadend\", onLoadEnd);\n var onReadyStateChange = function () {\n if (aborted) {\n return;\n }\n // In case of undefined state in some browsers.\n if (request.readyState === (XMLHttpRequest.DONE || 4)) {\n // Some browsers have issues where onreadystatechange can be called multiple times with the same value.\n request.removeEventListener(\"readystatechange\", onReadyStateChange);\n if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {\n onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);\n return;\n }\n var retryStrategy = Tools.DefaultRetryStrategy;\n if (retryStrategy) {\n var waitTime = retryStrategy(loadUrl, request, retryIndex);\n if (waitTime !== -1) {\n // Prevent the request from completing for retry.\n request.removeEventListener(\"loadend\", onLoadEnd);\n request = new XMLHttpRequest();\n retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);\n return;\n }\n }\n var e = new LoadFileError(\"Error status: \" + request.status + \" \" + request.statusText + \" - Unable to load \" + loadUrl, request);\n if (onError) {\n onError(request, e);\n }\n else {\n throw e;\n }\n }\n };\n request.addEventListener(\"readystatechange\", onReadyStateChange);\n request.send();\n };\n retryLoop(0);\n };\n // Caching all files\n if (database && database.enableSceneOffline) {\n var noIndexedDB_1 = function (request) {\n if (request && request.status > 400) {\n if (onError) {\n onError(request);\n }\n }\n else {\n if (!aborted) {\n requestFile();\n }\n }\n };\n var loadFromIndexedDB = function () {\n // TODO: database needs to support aborting and should return a IFileRequest\n if (aborted) {\n return;\n }\n if (database) {\n database.loadFileFromDB(url, function (data) {\n if (!aborted) {\n onSuccess(data);\n }\n fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n }, onProgress ? function (event) {\n if (!aborted) {\n onProgress(event);\n }\n } : undefined, noIndexedDB_1, useArrayBuffer);\n }\n };\n database.openAsync(loadFromIndexedDB, noIndexedDB_1);\n }\n else {\n requestFile();\n }\n return fileRequest;\n };\n /**\n * Load a script (identified by an url). When the url returns, the\n * content of this file is added into a new script element, attached to the DOM (body element)\n */\n Tools.LoadScript = function (scriptUrl, onSuccess, onError) {\n var head = document.getElementsByTagName('head')[0];\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.src = scriptUrl;\n script.onload = function () {\n if (onSuccess) {\n onSuccess();\n }\n };\n script.onerror = function (e) {\n if (onError) {\n onError(\"Unable to load script '\" + scriptUrl + \"'\", e);\n }\n };\n head.appendChild(script);\n };\n Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {\n var reader = new FileReader();\n var request = {\n onCompleteObservable: new BABYLON.Observable(),\n abort: function () { return reader.abort(); },\n };\n reader.onloadend = function (e) {\n request.onCompleteObservable.notifyObservers(request);\n };\n reader.onload = function (e) {\n //target doesn't have result from ts 1.3\n callback(e.target['result']);\n };\n reader.onprogress = progressCallback;\n reader.readAsDataURL(fileToLoad);\n return request;\n };\n Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {\n var reader = new FileReader();\n var request = {\n onCompleteObservable: new BABYLON.Observable(),\n abort: function () { return reader.abort(); },\n };\n reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };\n reader.onerror = function (e) {\n Tools.Log(\"Error while reading file: \" + fileToLoad.name);\n callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));\n };\n reader.onload = function (e) {\n //target doesn't have result from ts 1.3\n callback(e.target['result']);\n };\n if (progressCallBack) {\n reader.onprogress = progressCallBack;\n }\n if (!useArrayBuffer) {\n // Asynchronous read\n reader.readAsText(fileToLoad);\n }\n else {\n reader.readAsArrayBuffer(fileToLoad);\n }\n return request;\n };\n //returns a downloadable url to a file content.\n Tools.FileAsURL = function (content) {\n var fileBlob = new Blob([content]);\n var url = window.URL || window.webkitURL;\n var link = url.createObjectURL(fileBlob);\n return link;\n };\n // Misc.\n Tools.Format = function (value, decimals) {\n if (decimals === void 0) { decimals = 2; }\n return value.toFixed(decimals);\n };\n Tools.CheckExtends = function (v, min, max) {\n if (v.x < min.x)\n min.x = v.x;\n if (v.y < min.y)\n min.y = v.y;\n if (v.z < min.z)\n min.z = v.z;\n if (v.x > max.x)\n max.x = v.x;\n if (v.y > max.y)\n max.y = v.y;\n if (v.z > max.z)\n max.z = v.z;\n };\n Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {\n for (var prop in source) {\n if (prop[0] === \"_\" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {\n continue;\n }\n if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {\n continue;\n }\n var sourceValue = source[prop];\n var typeOfSourceValue = typeof sourceValue;\n if (typeOfSourceValue === \"function\") {\n continue;\n }\n try {\n if (typeOfSourceValue === \"object\") {\n if (sourceValue instanceof Array) {\n destination[prop] = [];\n if (sourceValue.length > 0) {\n if (typeof sourceValue[0] == \"object\") {\n for (var index = 0; index < sourceValue.length; index++) {\n var clonedValue = cloneValue(sourceValue[index], destination);\n if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done\n destination[prop].push(clonedValue);\n }\n }\n }\n else {\n destination[prop] = sourceValue.slice(0);\n }\n }\n }\n else {\n destination[prop] = cloneValue(sourceValue, destination);\n }\n }\n else {\n destination[prop] = sourceValue;\n }\n }\n catch (e) {\n // Just ignore error (it could be because of a read-only property)\n }\n }\n };\n Tools.IsEmpty = function (obj) {\n for (var i in obj) {\n if (obj.hasOwnProperty(i)) {\n return false;\n }\n }\n return true;\n };\n Tools.RegisterTopRootEvents = function (events) {\n for (var index = 0; index < events.length; index++) {\n var event = events[index];\n window.addEventListener(event.name, event.handler, false);\n try {\n if (window.parent) {\n window.parent.addEventListener(event.name, event.handler, false);\n }\n }\n catch (e) {\n // Silently fails...\n }\n }\n };\n Tools.UnregisterTopRootEvents = function (events) {\n for (var index = 0; index < events.length; index++) {\n var event = events[index];\n window.removeEventListener(event.name, event.handler);\n try {\n if (window.parent) {\n window.parent.removeEventListener(event.name, event.handler);\n }\n }\n catch (e) {\n // Silently fails...\n }\n }\n };\n Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {\n if (mimeType === void 0) { mimeType = \"image/png\"; }\n // Read the contents of the framebuffer\n var numberOfChannelsByLine = width * 4;\n var halfHeight = height / 2;\n //Reading datas from WebGL\n var data = engine.readPixels(0, 0, width, height);\n //To flip image on Y axis.\n for (var i = 0; i < halfHeight; i++) {\n for (var j = 0; j < numberOfChannelsByLine; j++) {\n var currentCell = j + i * numberOfChannelsByLine;\n var targetLine = height - i - 1;\n var targetCell = j + targetLine * numberOfChannelsByLine;\n var temp = data[currentCell];\n data[currentCell] = data[targetCell];\n data[targetCell] = temp;\n }\n }\n // Create a 2D canvas to store the result\n if (!screenshotCanvas) {\n screenshotCanvas = document.createElement('canvas');\n }\n screenshotCanvas.width = width;\n screenshotCanvas.height = height;\n var context = screenshotCanvas.getContext('2d');\n if (context) {\n // Copy the pixels to a 2D canvas\n var imageData = context.createImageData(width, height);\n var castData = (imageData.data);\n castData.set(data);\n context.putImageData(imageData, 0, 0);\n Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);\n }\n };\n /**\n * Converts the canvas data to blob.\n * This acts as a polyfill for browsers not supporting the to blob function.\n * @param canvas Defines the canvas to extract the data from\n * @param successCallback Defines the callback triggered once the data are available\n * @param mimeType Defines the mime type of the result\n */\n Tools.ToBlob = function (canvas, successCallback, mimeType) {\n if (mimeType === void 0) { mimeType = \"image/png\"; }\n // We need HTMLCanvasElement.toBlob for HD screenshots\n if (!canvas.toBlob) {\n // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)\n canvas.toBlob = function (callback, type, quality) {\n var _this = this;\n setTimeout(function () {\n var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);\n for (var i = 0; i < len; i++) {\n arr[i] = binStr.charCodeAt(i);\n }\n callback(new Blob([arr]));\n });\n };\n }\n canvas.toBlob(function (blob) {\n successCallback(blob);\n }, mimeType);\n };\n /**\n * Encodes the canvas data to base 64 or automatically download the result if filename is defined\n * @param successCallback Defines the callback triggered once the data are available\n * @param mimeType Defines the mime type of the result\n * @param fileName The filename to download. If present, the result will automatically be downloaded\n */\n Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {\n if (mimeType === void 0) { mimeType = \"image/png\"; }\n if (successCallback) {\n var base64Image = screenshotCanvas.toDataURL(mimeType);\n successCallback(base64Image);\n }\n else {\n this.ToBlob(screenshotCanvas, function (blob) {\n //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.\n if ((\"download\" in document.createElement(\"a\"))) {\n if (!fileName) {\n var date = new Date();\n var stringDate = (date.getFullYear() + \"-\" + (date.getMonth() + 1)).slice(2) + \"-\" + date.getDate() + \"_\" + date.getHours() + \"-\" + ('0' + date.getMinutes()).slice(-2);\n fileName = \"screenshot_\" + stringDate + \".png\";\n }\n Tools.Download(blob, fileName);\n }\n else {\n var url = URL.createObjectURL(blob);\n var newWindow = window.open(\"\");\n if (!newWindow)\n return;\n var img = newWindow.document.createElement(\"img\");\n img.onload = function () {\n // no longer need to read the blob so it's revoked\n URL.revokeObjectURL(url);\n };\n img.src = url;\n newWindow.document.body.appendChild(img);\n }\n }, mimeType);\n }\n };\n /**\n * Downloads a blob in the browser\n * @param blob defines the blob to download\n * @param fileName defines the name of the downloaded file\n */\n Tools.Download = function (blob, fileName) {\n if (navigator && navigator.msSaveBlob) {\n navigator.msSaveBlob(blob, fileName);\n return;\n }\n var url = window.URL.createObjectURL(blob);\n var a = document.createElement(\"a\");\n document.body.appendChild(a);\n a.style.display = \"none\";\n a.href = url;\n a.download = fileName;\n a.addEventListener(\"click\", function () {\n if (a.parentElement) {\n a.parentElement.removeChild(a);\n }\n });\n a.click();\n window.URL.revokeObjectURL(url);\n };\n Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {\n if (mimeType === void 0) { mimeType = \"image/png\"; }\n var width;\n var height;\n // If a precision value is specified\n if (size.precision) {\n width = Math.round(engine.getRenderWidth() * size.precision);\n height = Math.round(width / engine.getAspectRatio(camera));\n }\n else if (size.width && size.height) {\n width = size.width;\n height = size.height;\n }\n //If passing only width, computing height to keep display canvas ratio.\n else if (size.width && !size.height) {\n width = size.width;\n height = Math.round(width / engine.getAspectRatio(camera));\n }\n //If passing only height, computing width to keep display canvas ratio.\n else if (size.height && !size.width) {\n height = size.height;\n width = Math.round(height * engine.getAspectRatio(camera));\n }\n //Assuming here that \"size\" parameter is a number\n else if (!isNaN(size)) {\n height = size;\n width = size;\n }\n else {\n Tools.Error(\"Invalid 'size' parameter !\");\n return;\n }\n if (!screenshotCanvas) {\n screenshotCanvas = document.createElement('canvas');\n }\n screenshotCanvas.width = width;\n screenshotCanvas.height = height;\n var renderContext = screenshotCanvas.getContext(\"2d\");\n var ratio = engine.getRenderWidth() / engine.getRenderHeight();\n var newWidth = width;\n var newHeight = newWidth / ratio;\n if (newHeight > height) {\n newHeight = height;\n newWidth = newHeight * ratio;\n }\n var offsetX = Math.max(0, width - newWidth) / 2;\n var offsetY = Math.max(0, height - newHeight) / 2;\n var renderingCanvas = engine.getRenderingCanvas();\n if (renderContext && renderingCanvas) {\n renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);\n }\n Tools.EncodeScreenshotCanvasData(successCallback, mimeType);\n };\n /**\n * Generates an image screenshot from the specified camera.\n *\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution.\n * @param successCallback The callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it.\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types.\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @constructor\n */\n Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {\n if (mimeType === void 0) { mimeType = \"image/png\"; }\n if (samples === void 0) { samples = 1; }\n if (antialiasing === void 0) { antialiasing = false; }\n var width;\n var height;\n //If a precision value is specified\n if (size.precision) {\n width = Math.round(engine.getRenderWidth() * size.precision);\n height = Math.round(width / engine.getAspectRatio(camera));\n size = { width: width, height: height };\n }\n else if (size.width && size.height) {\n width = size.width;\n height = size.height;\n }\n //If passing only width, computing height to keep display canvas ratio.\n else if (size.width && !size.height) {\n width = size.width;\n height = Math.round(width / engine.getAspectRatio(camera));\n size = { width: width, height: height };\n }\n //If passing only height, computing width to keep display canvas ratio.\n else if (size.height && !size.width) {\n height = size.height;\n width = Math.round(height * engine.getAspectRatio(camera));\n size = { width: width, height: height };\n }\n //Assuming here that \"size\" parameter is a number\n else if (!isNaN(size)) {\n height = size;\n width = size;\n }\n else {\n Tools.Error(\"Invalid 'size' parameter !\");\n return;\n }\n var scene = camera.getScene();\n var previousCamera = null;\n if (scene.activeCamera !== camera) {\n previousCamera = scene.activeCamera;\n scene.activeCamera = camera;\n }\n //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)\n var texture = new BABYLON.RenderTargetTexture(\"screenShot\", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);\n texture.renderList = null;\n texture.samples = samples;\n if (antialiasing) {\n texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));\n }\n texture.onAfterRenderObservable.add(function () {\n Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);\n });\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n texture.render(true);\n texture.dispose();\n if (previousCamera) {\n scene.activeCamera = previousCamera;\n }\n camera.getProjectionMatrix(true); // Force cache refresh;\n };\n // XHR response validator for local file scenario\n Tools.ValidateXHRData = function (xhr, dataType) {\n // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all\n if (dataType === void 0) { dataType = 7; }\n try {\n if (dataType & 1) {\n if (xhr.responseText && xhr.responseText.length > 0) {\n return true;\n }\n else if (dataType === 1) {\n return false;\n }\n }\n if (dataType & 2) {\n // Check header width and height since there is no \"TGA\" magic number\n var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);\n if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {\n return true;\n }\n else if (dataType === 2) {\n return false;\n }\n }\n if (dataType & 4) {\n // Check for the \"DDS\" magic number\n var ddsHeader = new Uint8Array(xhr.response, 0, 3);\n if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {\n return true;\n }\n else {\n return false;\n }\n }\n }\n catch (e) {\n // Global protection\n }\n return false;\n };\n /**\n * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523\n * Be aware Math.random() could cause collisions, but:\n * \"All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide\"\n */\n Tools.RandomId = function () {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n };\n /**\n * Test if the given uri is a base64 string.\n * @param uri The uri to test\n * @return True if the uri is a base64 string or false otherwise.\n */\n Tools.IsBase64 = function (uri) {\n return uri.length < 5 ? false : uri.substr(0, 5) === \"data:\";\n };\n /**\n * Decode the given base64 uri.\n * @param uri The uri to decode\n * @return The decoded base64 data.\n */\n Tools.DecodeBase64 = function (uri) {\n var decodedString = atob(uri.split(\",\")[1]);\n var bufferLength = decodedString.length;\n var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));\n for (var i = 0; i < bufferLength; i++) {\n bufferView[i] = decodedString.charCodeAt(i);\n }\n return bufferView.buffer;\n };\n Object.defineProperty(Tools, \"NoneLogLevel\", {\n get: function () {\n return Tools._NoneLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"MessageLogLevel\", {\n get: function () {\n return Tools._MessageLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"WarningLogLevel\", {\n get: function () {\n return Tools._WarningLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"ErrorLogLevel\", {\n get: function () {\n return Tools._ErrorLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"AllLogLevel\", {\n get: function () {\n return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Tools._AddLogEntry = function (entry) {\n Tools._LogCache = entry + Tools._LogCache;\n if (Tools.OnNewCacheEntry) {\n Tools.OnNewCacheEntry(entry);\n }\n };\n Tools._FormatMessage = function (message) {\n var padStr = function (i) { return (i < 10) ? \"0\" + i : \"\" + i; };\n var date = new Date();\n return \"[\" + padStr(date.getHours()) + \":\" + padStr(date.getMinutes()) + \":\" + padStr(date.getSeconds()) + \"]: \" + message;\n };\n Tools._LogDisabled = function (message) {\n // nothing to do\n };\n Tools._LogEnabled = function (message) {\n var formattedMessage = Tools._FormatMessage(message);\n console.log(\"BJS - \" + formattedMessage);\n var entry = \"
\" + formattedMessage + \"

\";\n Tools._AddLogEntry(entry);\n };\n Tools._WarnDisabled = function (message) {\n // nothing to do\n };\n Tools._WarnEnabled = function (message) {\n var formattedMessage = Tools._FormatMessage(message);\n console.warn(\"BJS - \" + formattedMessage);\n var entry = \"
\" + formattedMessage + \"

\";\n Tools._AddLogEntry(entry);\n };\n Tools._ErrorDisabled = function (message) {\n // nothing to do\n };\n Tools._ErrorEnabled = function (message) {\n Tools.errorsCount++;\n var formattedMessage = Tools._FormatMessage(message);\n console.error(\"BJS - \" + formattedMessage);\n var entry = \"
\" + formattedMessage + \"

\";\n Tools._AddLogEntry(entry);\n };\n Object.defineProperty(Tools, \"LogCache\", {\n get: function () {\n return Tools._LogCache;\n },\n enumerable: true,\n configurable: true\n });\n Tools.ClearLogCache = function () {\n Tools._LogCache = \"\";\n Tools.errorsCount = 0;\n };\n Object.defineProperty(Tools, \"LogLevels\", {\n set: function (level) {\n if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {\n Tools.Log = Tools._LogEnabled;\n }\n else {\n Tools.Log = Tools._LogDisabled;\n }\n if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {\n Tools.Warn = Tools._WarnEnabled;\n }\n else {\n Tools.Warn = Tools._WarnDisabled;\n }\n if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {\n Tools.Error = Tools._ErrorEnabled;\n }\n else {\n Tools.Error = Tools._ErrorDisabled;\n }\n },\n enumerable: true,\n configurable: true\n });\n Tools.IsWindowObjectExist = function () {\n return (typeof window) !== \"undefined\";\n };\n Object.defineProperty(Tools, \"PerformanceNoneLogLevel\", {\n get: function () {\n return Tools._PerformanceNoneLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"PerformanceUserMarkLogLevel\", {\n get: function () {\n return Tools._PerformanceUserMarkLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"PerformanceConsoleLogLevel\", {\n get: function () {\n return Tools._PerformanceConsoleLogLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tools, \"PerformanceLogLevel\", {\n set: function (level) {\n if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {\n Tools.StartPerformanceCounter = Tools._StartUserMark;\n Tools.EndPerformanceCounter = Tools._EndUserMark;\n return;\n }\n if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {\n Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;\n Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;\n return;\n }\n Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;\n Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;\n },\n enumerable: true,\n configurable: true\n });\n Tools._StartPerformanceCounterDisabled = function (counterName, condition) {\n };\n Tools._EndPerformanceCounterDisabled = function (counterName, condition) {\n };\n Tools._StartUserMark = function (counterName, condition) {\n if (condition === void 0) { condition = true; }\n if (!Tools._performance) {\n if (!Tools.IsWindowObjectExist()) {\n return;\n }\n Tools._performance = window.performance;\n }\n if (!condition || !Tools._performance.mark) {\n return;\n }\n Tools._performance.mark(counterName + \"-Begin\");\n };\n Tools._EndUserMark = function (counterName, condition) {\n if (condition === void 0) { condition = true; }\n if (!condition || !Tools._performance.mark) {\n return;\n }\n Tools._performance.mark(counterName + \"-End\");\n Tools._performance.measure(counterName, counterName + \"-Begin\", counterName + \"-End\");\n };\n Tools._StartPerformanceConsole = function (counterName, condition) {\n if (condition === void 0) { condition = true; }\n if (!condition) {\n return;\n }\n Tools._StartUserMark(counterName, condition);\n if (console.time) {\n console.time(counterName);\n }\n };\n Tools._EndPerformanceConsole = function (counterName, condition) {\n if (condition === void 0) { condition = true; }\n if (!condition) {\n return;\n }\n Tools._EndUserMark(counterName, condition);\n if (console.time) {\n console.timeEnd(counterName);\n }\n };\n Object.defineProperty(Tools, \"Now\", {\n get: function () {\n if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {\n return window.performance.now();\n }\n return Date.now();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * This method will return the name of the class used to create the instance of the given object.\n * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.\n * @param object the object to get the class name from\n * @return the name of the class, will be \"object\" for a custom data type not using the @className decorator\n */\n Tools.GetClassName = function (object, isType) {\n if (isType === void 0) { isType = false; }\n var name = null;\n if (!isType && object.getClassName) {\n name = object.getClassName();\n }\n else {\n if (object instanceof Object) {\n var classObj = isType ? object : Object.getPrototypeOf(object);\n name = classObj.constructor[\"__bjsclassName__\"];\n }\n if (!name) {\n name = typeof object;\n }\n }\n return name;\n };\n Tools.First = function (array, predicate) {\n for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {\n var el = array_1[_i];\n if (predicate(el)) {\n return el;\n }\n }\n return null;\n };\n /**\n * This method will return the name of the full name of the class, including its owning module (if any).\n * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).\n * @param object the object to get the class name from\n * @return a string that can have two forms: \"moduleName.className\" if module was specified when the class' Name was registered or \"className\" if there was not module specified.\n */\n Tools.getFullClassName = function (object, isType) {\n if (isType === void 0) { isType = false; }\n var className = null;\n var moduleName = null;\n if (!isType && object.getClassName) {\n className = object.getClassName();\n }\n else {\n if (object instanceof Object) {\n var classObj = isType ? object : Object.getPrototypeOf(object);\n className = classObj.constructor[\"__bjsclassName__\"];\n moduleName = classObj.constructor[\"__bjsmoduleName__\"];\n }\n if (!className) {\n className = typeof object;\n }\n }\n if (!className) {\n return null;\n }\n return ((moduleName != null) ? (moduleName + \".\") : \"\") + className;\n };\n /**\n * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.\n * @param array\n */\n Tools.arrayOrStringFeeder = function (array) {\n return function (index) {\n if (index >= array.length) {\n return null;\n }\n var val = array.charCodeAt ? array.charCodeAt(index) : array[index];\n if (val && val.getHashCode) {\n val = val.getHashCode();\n }\n if (typeof val === \"string\") {\n return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));\n }\n return val;\n };\n };\n /**\n * Compute the hashCode of a stream of number\n * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.\n * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.\n * @return the hash code computed\n */\n Tools.hashCodeFromStream = function (feeder) {\n // Based from here: http://stackoverflow.com/a/7616484/802124\n var hash = 0;\n var index = 0;\n var chr = feeder(index++);\n while (chr != null) {\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n chr = feeder(index++);\n }\n return hash;\n };\n /**\n * Returns a promise that resolves after the given amount of time.\n * @param delay Number of milliseconds to delay\n * @returns Promise that resolves after the given amount of time\n */\n Tools.DelayAsync = function (delay) {\n return new Promise(function (resolve) {\n setTimeout(function () {\n resolve();\n }, delay);\n });\n };\n /**\n * Gets the current gradient from an array of IValueGradient\n * @param ratio defines the current ratio to get\n * @param gradients defines the array of IValueGradient\n * @param updateFunc defines the callback function used to get the final value from the selected gradients\n */\n Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {\n for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {\n var currentGradient = gradients[gradientIndex];\n var nextGradient = gradients[gradientIndex + 1];\n if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {\n var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);\n updateFunc(currentGradient, nextGradient, scale);\n }\n }\n };\n Tools.BaseUrl = \"\";\n Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();\n /**\n * Default behaviour for cors in the application.\n * It can be a string if the expected behavior is identical in the entire app.\n * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)\n */\n Tools.CorsBehavior = \"anonymous\";\n Tools.UseFallbackTexture = true;\n /**\n * Use this object to register external classes like custom textures or material\n * to allow the laoders to instantiate them\n */\n Tools.RegisteredExternalClasses = {};\n // Used in case of a texture loading problem \n Tools.fallbackTexture = \"data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z\";\n Tools._tmpFloatArray = new Float32Array(1);\n Tools.PreprocessUrl = function (url) {\n return url;\n };\n // Logs\n Tools._NoneLogLevel = 0;\n Tools._MessageLogLevel = 1;\n Tools._WarningLogLevel = 2;\n Tools._ErrorLogLevel = 4;\n Tools._LogCache = \"\";\n Tools.errorsCount = 0;\n Tools.Log = Tools._LogEnabled;\n Tools.Warn = Tools._WarnEnabled;\n Tools.Error = Tools._ErrorEnabled;\n // Performances\n Tools._PerformanceNoneLogLevel = 0;\n Tools._PerformanceUserMarkLogLevel = 1;\n Tools._PerformanceConsoleLogLevel = 2;\n Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;\n Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;\n return Tools;\n }());\n BABYLON.Tools = Tools;\n /**\n * This class is used to track a performance counter which is number based.\n * The user has access to many properties which give statistics of different nature\n *\n * The implementer can track two kinds of Performance Counter: time and count\n * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.\n * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.\n */\n var PerfCounter = /** @class */ (function () {\n function PerfCounter() {\n this._startMonitoringTime = 0;\n this._min = 0;\n this._max = 0;\n this._average = 0;\n this._lastSecAverage = 0;\n this._current = 0;\n this._totalValueCount = 0;\n this._totalAccumulated = 0;\n this._lastSecAccumulated = 0;\n this._lastSecTime = 0;\n this._lastSecValueCount = 0;\n }\n Object.defineProperty(PerfCounter.prototype, \"min\", {\n /**\n * Returns the smallest value ever\n */\n get: function () {\n return this._min;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerfCounter.prototype, \"max\", {\n /**\n * Returns the biggest value ever\n */\n get: function () {\n return this._max;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerfCounter.prototype, \"average\", {\n /**\n * Returns the average value since the performance counter is running\n */\n get: function () {\n return this._average;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerfCounter.prototype, \"lastSecAverage\", {\n /**\n * Returns the average value of the last second the counter was monitored\n */\n get: function () {\n return this._lastSecAverage;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerfCounter.prototype, \"current\", {\n /**\n * Returns the current value\n */\n get: function () {\n return this._current;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerfCounter.prototype, \"total\", {\n get: function () {\n return this._totalAccumulated;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerfCounter.prototype, \"count\", {\n get: function () {\n return this._totalValueCount;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Call this method to start monitoring a new frame.\n * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.\n */\n PerfCounter.prototype.fetchNewFrame = function () {\n this._totalValueCount++;\n this._current = 0;\n this._lastSecValueCount++;\n };\n /**\n * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)\n * @param newCount the count value to add to the monitored count\n * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.\n */\n PerfCounter.prototype.addCount = function (newCount, fetchResult) {\n if (!PerfCounter.Enabled) {\n return;\n }\n this._current += newCount;\n if (fetchResult) {\n this._fetchResult();\n }\n };\n /**\n * Start monitoring this performance counter\n */\n PerfCounter.prototype.beginMonitoring = function () {\n if (!PerfCounter.Enabled) {\n return;\n }\n this._startMonitoringTime = Tools.Now;\n };\n /**\n * Compute the time lapsed since the previous beginMonitoring() call.\n * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter\n */\n PerfCounter.prototype.endMonitoring = function (newFrame) {\n if (newFrame === void 0) { newFrame = true; }\n if (!PerfCounter.Enabled) {\n return;\n }\n if (newFrame) {\n this.fetchNewFrame();\n }\n var currentTime = Tools.Now;\n this._current = currentTime - this._startMonitoringTime;\n if (newFrame) {\n this._fetchResult();\n }\n };\n PerfCounter.prototype._fetchResult = function () {\n this._totalAccumulated += this._current;\n this._lastSecAccumulated += this._current;\n // Min/Max update\n this._min = Math.min(this._min, this._current);\n this._max = Math.max(this._max, this._current);\n this._average = this._totalAccumulated / this._totalValueCount;\n // Reset last sec?\n var now = Tools.Now;\n if ((now - this._lastSecTime) > 1000) {\n this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;\n this._lastSecTime = now;\n this._lastSecAccumulated = 0;\n this._lastSecValueCount = 0;\n }\n };\n PerfCounter.Enabled = true;\n return PerfCounter;\n }());\n BABYLON.PerfCounter = PerfCounter;\n /**\n * Use this className as a decorator on a given class definition to add it a name and optionally its module.\n * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.\n * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified\n * @param name The name of the class, case should be preserved\n * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.\n */\n function className(name, module) {\n return function (target) {\n target[\"__bjsclassName__\"] = name;\n target[\"__bjsmoduleName__\"] = (module != null) ? module : null;\n };\n }\n BABYLON.className = className;\n /**\n * An implementation of a loop for asynchronous functions.\n */\n var AsyncLoop = /** @class */ (function () {\n /**\n * Constroctor.\n * @param iterations the number of iterations.\n * @param _fn the function to run each iteration\n * @param _successCallback the callback that will be called upon succesful execution\n * @param offset starting offset.\n */\n function AsyncLoop(iterations, _fn, _successCallback, offset) {\n if (offset === void 0) { offset = 0; }\n this.iterations = iterations;\n this._fn = _fn;\n this._successCallback = _successCallback;\n this.index = offset - 1;\n this._done = false;\n }\n /**\n * Execute the next iteration. Must be called after the last iteration was finished.\n */\n AsyncLoop.prototype.executeNext = function () {\n if (!this._done) {\n if (this.index + 1 < this.iterations) {\n ++this.index;\n this._fn(this);\n }\n else {\n this.breakLoop();\n }\n }\n };\n /**\n * Break the loop and run the success callback.\n */\n AsyncLoop.prototype.breakLoop = function () {\n this._done = true;\n this._successCallback();\n };\n /**\n * Helper function\n */\n AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {\n if (offset === void 0) { offset = 0; }\n var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);\n loop.executeNext();\n return loop;\n };\n /**\n * A for-loop that will run a given number of iterations synchronous and the rest async.\n * @param iterations total number of iterations\n * @param syncedIterations number of synchronous iterations in each async iteration.\n * @param fn the function to call each iteration.\n * @param callback a success call back that will be called when iterating stops.\n * @param breakFunction a break condition (optional)\n * @param timeout timeout settings for the setTimeout function. default - 0.\n * @constructor\n */\n AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {\n if (timeout === void 0) { timeout = 0; }\n AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {\n if (breakFunction && breakFunction())\n loop.breakLoop();\n else {\n setTimeout(function () {\n for (var i = 0; i < syncedIterations; ++i) {\n var iteration = (loop.index * syncedIterations) + i;\n if (iteration >= iterations)\n break;\n fn(iteration);\n if (breakFunction && breakFunction()) {\n loop.breakLoop();\n break;\n }\n }\n loop.executeNext();\n }, timeout);\n }\n }, callback);\n };\n return AsyncLoop;\n }());\n BABYLON.AsyncLoop = AsyncLoop;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.tools.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var PromiseStates;\n (function (PromiseStates) {\n PromiseStates[PromiseStates[\"Pending\"] = 0] = \"Pending\";\n PromiseStates[PromiseStates[\"Fulfilled\"] = 1] = \"Fulfilled\";\n PromiseStates[PromiseStates[\"Rejected\"] = 2] = \"Rejected\";\n })(PromiseStates || (PromiseStates = {}));\n var FulFillmentAgregator = /** @class */ (function () {\n function FulFillmentAgregator() {\n this.count = 0;\n this.target = 0;\n this.results = [];\n }\n return FulFillmentAgregator;\n }());\n var InternalPromise = /** @class */ (function () {\n function InternalPromise(resolver) {\n var _this = this;\n this._state = PromiseStates.Pending;\n this._children = new Array();\n this._rejectWasConsumed = false;\n if (!resolver) {\n return;\n }\n try {\n resolver(function (value) {\n _this._resolve(value);\n }, function (reason) {\n _this._reject(reason);\n });\n }\n catch (e) {\n this._reject(e);\n }\n }\n Object.defineProperty(InternalPromise.prototype, \"_result\", {\n get: function () {\n return this._resultValue;\n },\n set: function (value) {\n this._resultValue = value;\n if (this._parent && this._parent._result === undefined) {\n this._parent._result = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n InternalPromise.prototype.catch = function (onRejected) {\n return this.then(undefined, onRejected);\n };\n InternalPromise.prototype.then = function (onFulfilled, onRejected) {\n var _this = this;\n var newPromise = new InternalPromise();\n newPromise._onFulfilled = onFulfilled;\n newPromise._onRejected = onRejected;\n // Composition\n this._children.push(newPromise);\n newPromise._parent = this;\n if (this._state !== PromiseStates.Pending) {\n BABYLON.Tools.SetImmediate(function () {\n if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {\n var returnedValue = newPromise._resolve(_this._result);\n if (returnedValue !== undefined && returnedValue !== null) {\n if (returnedValue._state !== undefined) {\n var returnedPromise = returnedValue;\n newPromise._children.push(returnedPromise);\n returnedPromise._parent = newPromise;\n newPromise = returnedPromise;\n }\n else {\n newPromise._result = returnedValue;\n }\n }\n }\n else {\n newPromise._reject(_this._reason);\n }\n });\n }\n return newPromise;\n };\n InternalPromise.prototype._moveChildren = function (children) {\n var _this = this;\n var _a;\n (_a = this._children).push.apply(_a, children.splice(0, children.length));\n this._children.forEach(function (child) {\n child._parent = _this;\n });\n if (this._state === PromiseStates.Fulfilled) {\n for (var _i = 0, _b = this._children; _i < _b.length; _i++) {\n var child = _b[_i];\n child._resolve(this._result);\n }\n }\n else if (this._state === PromiseStates.Rejected) {\n for (var _c = 0, _d = this._children; _c < _d.length; _c++) {\n var child = _d[_c];\n child._reject(this._reason);\n }\n }\n };\n InternalPromise.prototype._resolve = function (value) {\n try {\n this._state = PromiseStates.Fulfilled;\n var returnedValue = null;\n if (this._onFulfilled) {\n returnedValue = this._onFulfilled(value);\n }\n if (returnedValue !== undefined && returnedValue !== null) {\n if (returnedValue._state !== undefined) {\n // Transmit children\n var returnedPromise = returnedValue;\n returnedPromise._parent = this;\n returnedPromise._moveChildren(this._children);\n value = returnedPromise._result;\n }\n else {\n value = returnedValue;\n }\n }\n this._result = value;\n for (var _i = 0, _a = this._children; _i < _a.length; _i++) {\n var child = _a[_i];\n child._resolve(value);\n }\n this._children.length = 0;\n delete this._onFulfilled;\n delete this._onRejected;\n }\n catch (e) {\n this._reject(e, true);\n }\n };\n InternalPromise.prototype._reject = function (reason, onLocalThrow) {\n if (onLocalThrow === void 0) { onLocalThrow = false; }\n this._state = PromiseStates.Rejected;\n this._reason = reason;\n if (this._onRejected && !onLocalThrow) {\n try {\n this._onRejected(reason);\n this._rejectWasConsumed = true;\n }\n catch (e) {\n reason = e;\n }\n }\n for (var _i = 0, _a = this._children; _i < _a.length; _i++) {\n var child = _a[_i];\n if (this._rejectWasConsumed) {\n child._resolve(null);\n }\n else {\n child._reject(reason);\n }\n }\n this._children.length = 0;\n delete this._onFulfilled;\n delete this._onRejected;\n };\n InternalPromise.resolve = function (value) {\n var newPromise = new InternalPromise();\n newPromise._resolve(value);\n return newPromise;\n };\n InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {\n promise.then(function (value) {\n agregator.results[index] = value;\n agregator.count++;\n if (agregator.count === agregator.target) {\n agregator.rootPromise._resolve(agregator.results);\n }\n return null;\n }, function (reason) {\n if (agregator.rootPromise._state !== PromiseStates.Rejected) {\n agregator.rootPromise._reject(reason);\n }\n });\n };\n InternalPromise.all = function (promises) {\n var newPromise = new InternalPromise();\n var agregator = new FulFillmentAgregator();\n agregator.target = promises.length;\n agregator.rootPromise = newPromise;\n if (promises.length) {\n for (var index = 0; index < promises.length; index++) {\n InternalPromise._RegisterForFulfillment(promises[index], agregator, index);\n }\n }\n else {\n newPromise._resolve([]);\n }\n return newPromise;\n };\n InternalPromise.race = function (promises) {\n var newPromise = new InternalPromise();\n if (promises.length) {\n for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {\n var promise = promises_1[_i];\n promise.then(function (value) {\n if (newPromise) {\n newPromise._resolve(value);\n newPromise = null;\n }\n return null;\n }, function (reason) {\n if (newPromise) {\n newPromise._reject(reason);\n newPromise = null;\n }\n });\n }\n }\n return newPromise;\n };\n return InternalPromise;\n }());\n /**\n * Helper class that provides a small promise polyfill\n */\n var PromisePolyfill = /** @class */ (function () {\n function PromisePolyfill() {\n }\n /**\n * Static function used to check if the polyfill is required\n * If this is the case then the function will inject the polyfill to window.Promise\n * @param force defines a boolean used to force the injection (mostly for testing purposes)\n */\n PromisePolyfill.Apply = function (force) {\n if (force === void 0) { force = false; }\n if (force || typeof Promise === 'undefined') {\n var root = window;\n root.Promise = InternalPromise;\n }\n };\n return PromisePolyfill;\n }());\n BABYLON.PromisePolyfill = PromisePolyfill;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.promise.js.map\n\n/// \nvar BABYLON;\n(function (BABYLON) {\n /**\n * Helper class to push actions to a pool of workers.\n */\n var WorkerPool = /** @class */ (function () {\n /**\n * Constructor\n * @param workers Array of workers to use for actions\n */\n function WorkerPool(workers) {\n this._pendingActions = new Array();\n this._workerInfos = workers.map(function (worker) { return ({\n worker: worker,\n active: false\n }); });\n }\n /**\n * Terminates all workers and clears any pending actions.\n */\n WorkerPool.prototype.dispose = function () {\n for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {\n var workerInfo = _a[_i];\n workerInfo.worker.terminate();\n }\n delete this._workerInfos;\n delete this._pendingActions;\n };\n /**\n * Pushes an action to the worker pool. If all the workers are active, the action will be\n * pended until a worker has completed its action.\n * @param action The action to perform. Call onComplete when the action is complete.\n */\n WorkerPool.prototype.push = function (action) {\n for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {\n var workerInfo = _a[_i];\n if (!workerInfo.active) {\n this._execute(workerInfo, action);\n return;\n }\n }\n this._pendingActions.push(action);\n };\n WorkerPool.prototype._execute = function (workerInfo, action) {\n var _this = this;\n workerInfo.active = true;\n action(workerInfo.worker, function () {\n workerInfo.active = false;\n var nextAction = _this._pendingActions.shift();\n if (nextAction) {\n _this._execute(workerInfo, nextAction);\n }\n });\n };\n return WorkerPool;\n }());\n BABYLON.WorkerPool = WorkerPool;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.workerPool.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * @hidden\n **/\n var _AlphaState = /** @class */ (function () {\n /**\n * Initializes the state.\n */\n function _AlphaState() {\n this._isAlphaBlendDirty = false;\n this._isBlendFunctionParametersDirty = false;\n this._isBlendEquationParametersDirty = false;\n this._isBlendConstantsDirty = false;\n this._alphaBlend = false;\n this._blendFunctionParameters = new Array(4);\n this._blendEquationParameters = new Array(2);\n this._blendConstants = new Array(4);\n this.reset();\n }\n Object.defineProperty(_AlphaState.prototype, \"isDirty\", {\n get: function () {\n return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_AlphaState.prototype, \"alphaBlend\", {\n get: function () {\n return this._alphaBlend;\n },\n set: function (value) {\n if (this._alphaBlend === value) {\n return;\n }\n this._alphaBlend = value;\n this._isAlphaBlendDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {\n if (this._blendConstants[0] === r &&\n this._blendConstants[1] === g &&\n this._blendConstants[2] === b &&\n this._blendConstants[3] === a) {\n return;\n }\n this._blendConstants[0] = r;\n this._blendConstants[1] = g;\n this._blendConstants[2] = b;\n this._blendConstants[3] = a;\n this._isBlendConstantsDirty = true;\n };\n _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {\n if (this._blendFunctionParameters[0] === value0 &&\n this._blendFunctionParameters[1] === value1 &&\n this._blendFunctionParameters[2] === value2 &&\n this._blendFunctionParameters[3] === value3) {\n return;\n }\n this._blendFunctionParameters[0] = value0;\n this._blendFunctionParameters[1] = value1;\n this._blendFunctionParameters[2] = value2;\n this._blendFunctionParameters[3] = value3;\n this._isBlendFunctionParametersDirty = true;\n };\n _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {\n if (this._blendEquationParameters[0] === rgb &&\n this._blendEquationParameters[1] === alpha) {\n return;\n }\n this._blendEquationParameters[0] = rgb;\n this._blendEquationParameters[1] = alpha;\n this._isBlendEquationParametersDirty = true;\n };\n _AlphaState.prototype.reset = function () {\n this._alphaBlend = false;\n this._blendFunctionParameters[0] = null;\n this._blendFunctionParameters[1] = null;\n this._blendFunctionParameters[2] = null;\n this._blendFunctionParameters[3] = null;\n this._blendEquationParameters[0] = null;\n this._blendEquationParameters[1] = null;\n this._blendConstants[0] = null;\n this._blendConstants[1] = null;\n this._blendConstants[2] = null;\n this._blendConstants[3] = null;\n this._isAlphaBlendDirty = true;\n this._isBlendFunctionParametersDirty = false;\n this._isBlendEquationParametersDirty = false;\n this._isBlendConstantsDirty = false;\n };\n _AlphaState.prototype.apply = function (gl) {\n if (!this.isDirty) {\n return;\n }\n // Alpha blend\n if (this._isAlphaBlendDirty) {\n if (this._alphaBlend) {\n gl.enable(gl.BLEND);\n }\n else {\n gl.disable(gl.BLEND);\n }\n this._isAlphaBlendDirty = false;\n }\n // Alpha function\n if (this._isBlendFunctionParametersDirty) {\n gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);\n this._isBlendFunctionParametersDirty = false;\n }\n // Alpha equation\n if (this._isBlendEquationParametersDirty) {\n gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);\n this._isBlendEquationParametersDirty = false;\n }\n // Constants\n if (this._isBlendConstantsDirty) {\n gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);\n this._isBlendConstantsDirty = false;\n }\n };\n return _AlphaState;\n }());\n BABYLON._AlphaState = _AlphaState;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.alphaCullingState.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * @hidden\n **/\n var _DepthCullingState = /** @class */ (function () {\n /**\n * Initializes the state.\n */\n function _DepthCullingState() {\n this._isDepthTestDirty = false;\n this._isDepthMaskDirty = false;\n this._isDepthFuncDirty = false;\n this._isCullFaceDirty = false;\n this._isCullDirty = false;\n this._isZOffsetDirty = false;\n this._isFrontFaceDirty = false;\n this.reset();\n }\n Object.defineProperty(_DepthCullingState.prototype, \"isDirty\", {\n get: function () {\n return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"zOffset\", {\n get: function () {\n return this._zOffset;\n },\n set: function (value) {\n if (this._zOffset === value) {\n return;\n }\n this._zOffset = value;\n this._isZOffsetDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"cullFace\", {\n get: function () {\n return this._cullFace;\n },\n set: function (value) {\n if (this._cullFace === value) {\n return;\n }\n this._cullFace = value;\n this._isCullFaceDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"cull\", {\n get: function () {\n return this._cull;\n },\n set: function (value) {\n if (this._cull === value) {\n return;\n }\n this._cull = value;\n this._isCullDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"depthFunc\", {\n get: function () {\n return this._depthFunc;\n },\n set: function (value) {\n if (this._depthFunc === value) {\n return;\n }\n this._depthFunc = value;\n this._isDepthFuncDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"depthMask\", {\n get: function () {\n return this._depthMask;\n },\n set: function (value) {\n if (this._depthMask === value) {\n return;\n }\n this._depthMask = value;\n this._isDepthMaskDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"depthTest\", {\n get: function () {\n return this._depthTest;\n },\n set: function (value) {\n if (this._depthTest === value) {\n return;\n }\n this._depthTest = value;\n this._isDepthTestDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_DepthCullingState.prototype, \"frontFace\", {\n get: function () {\n return this._frontFace;\n },\n set: function (value) {\n if (this._frontFace === value) {\n return;\n }\n this._frontFace = value;\n this._isFrontFaceDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n _DepthCullingState.prototype.reset = function () {\n this._depthMask = true;\n this._depthTest = true;\n this._depthFunc = null;\n this._cullFace = null;\n this._cull = null;\n this._zOffset = 0;\n this._frontFace = null;\n this._isDepthTestDirty = true;\n this._isDepthMaskDirty = true;\n this._isDepthFuncDirty = false;\n this._isCullFaceDirty = false;\n this._isCullDirty = false;\n this._isZOffsetDirty = false;\n this._isFrontFaceDirty = false;\n };\n _DepthCullingState.prototype.apply = function (gl) {\n if (!this.isDirty) {\n return;\n }\n // Cull\n if (this._isCullDirty) {\n if (this.cull) {\n gl.enable(gl.CULL_FACE);\n }\n else {\n gl.disable(gl.CULL_FACE);\n }\n this._isCullDirty = false;\n }\n // Cull face\n if (this._isCullFaceDirty) {\n gl.cullFace(this.cullFace);\n this._isCullFaceDirty = false;\n }\n // Depth mask\n if (this._isDepthMaskDirty) {\n gl.depthMask(this.depthMask);\n this._isDepthMaskDirty = false;\n }\n // Depth test\n if (this._isDepthTestDirty) {\n if (this.depthTest) {\n gl.enable(gl.DEPTH_TEST);\n }\n else {\n gl.disable(gl.DEPTH_TEST);\n }\n this._isDepthTestDirty = false;\n }\n // Depth func\n if (this._isDepthFuncDirty) {\n gl.depthFunc(this.depthFunc);\n this._isDepthFuncDirty = false;\n }\n // zOffset\n if (this._isZOffsetDirty) {\n if (this.zOffset) {\n gl.enable(gl.POLYGON_OFFSET_FILL);\n gl.polygonOffset(this.zOffset, 0);\n }\n else {\n gl.disable(gl.POLYGON_OFFSET_FILL);\n }\n this._isZOffsetDirty = false;\n }\n // Front face\n if (this._isFrontFaceDirty) {\n gl.frontFace(this.frontFace);\n this._isFrontFaceDirty = false;\n }\n };\n return _DepthCullingState;\n }());\n BABYLON._DepthCullingState = _DepthCullingState;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.depthCullingState.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * @hidden\n **/\n var _StencilState = /** @class */ (function () {\n function _StencilState() {\n this._isStencilTestDirty = false;\n this._isStencilMaskDirty = false;\n this._isStencilFuncDirty = false;\n this._isStencilOpDirty = false;\n this.reset();\n }\n Object.defineProperty(_StencilState.prototype, \"isDirty\", {\n get: function () {\n return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilFunc\", {\n get: function () {\n return this._stencilFunc;\n },\n set: function (value) {\n if (this._stencilFunc === value) {\n return;\n }\n this._stencilFunc = value;\n this._isStencilFuncDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilFuncRef\", {\n get: function () {\n return this._stencilFuncRef;\n },\n set: function (value) {\n if (this._stencilFuncRef === value) {\n return;\n }\n this._stencilFuncRef = value;\n this._isStencilFuncDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilFuncMask\", {\n get: function () {\n return this._stencilFuncMask;\n },\n set: function (value) {\n if (this._stencilFuncMask === value) {\n return;\n }\n this._stencilFuncMask = value;\n this._isStencilFuncDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilOpStencilFail\", {\n get: function () {\n return this._stencilOpStencilFail;\n },\n set: function (value) {\n if (this._stencilOpStencilFail === value) {\n return;\n }\n this._stencilOpStencilFail = value;\n this._isStencilOpDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilOpDepthFail\", {\n get: function () {\n return this._stencilOpDepthFail;\n },\n set: function (value) {\n if (this._stencilOpDepthFail === value) {\n return;\n }\n this._stencilOpDepthFail = value;\n this._isStencilOpDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilOpStencilDepthPass\", {\n get: function () {\n return this._stencilOpStencilDepthPass;\n },\n set: function (value) {\n if (this._stencilOpStencilDepthPass === value) {\n return;\n }\n this._stencilOpStencilDepthPass = value;\n this._isStencilOpDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilMask\", {\n get: function () {\n return this._stencilMask;\n },\n set: function (value) {\n if (this._stencilMask === value) {\n return;\n }\n this._stencilMask = value;\n this._isStencilMaskDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(_StencilState.prototype, \"stencilTest\", {\n get: function () {\n return this._stencilTest;\n },\n set: function (value) {\n if (this._stencilTest === value) {\n return;\n }\n this._stencilTest = value;\n this._isStencilTestDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n _StencilState.prototype.reset = function () {\n this._stencilTest = false;\n this._stencilMask = 0xFF;\n this._stencilFunc = BABYLON.Engine.ALWAYS;\n this._stencilFuncRef = 1;\n this._stencilFuncMask = 0xFF;\n this._stencilOpStencilFail = BABYLON.Engine.KEEP;\n this._stencilOpDepthFail = BABYLON.Engine.KEEP;\n this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;\n this._isStencilTestDirty = true;\n this._isStencilMaskDirty = true;\n this._isStencilFuncDirty = true;\n this._isStencilOpDirty = true;\n };\n _StencilState.prototype.apply = function (gl) {\n if (!this.isDirty) {\n return;\n }\n // Stencil test\n if (this._isStencilTestDirty) {\n if (this.stencilTest) {\n gl.enable(gl.STENCIL_TEST);\n }\n else {\n gl.disable(gl.STENCIL_TEST);\n }\n this._isStencilTestDirty = false;\n }\n // Stencil mask\n if (this._isStencilMaskDirty) {\n gl.stencilMask(this.stencilMask);\n this._isStencilMaskDirty = false;\n }\n // Stencil func\n if (this._isStencilFuncDirty) {\n gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);\n this._isStencilFuncDirty = false;\n }\n // Stencil op\n if (this._isStencilOpDirty) {\n gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);\n this._isStencilOpDirty = false;\n }\n };\n return _StencilState;\n }());\n BABYLON._StencilState = _StencilState;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stencilState.js.map\n\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Keeps track of all the buffer info used in engine.\n */\n var BufferPointer = /** @class */ (function () {\n function BufferPointer() {\n }\n return BufferPointer;\n }());\n /**\n * Interface for attribute information associated with buffer instanciation\n */\n var InstancingAttributeInfo = /** @class */ (function () {\n function InstancingAttributeInfo() {\n }\n return InstancingAttributeInfo;\n }());\n BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;\n /**\n * Define options used to create a render target texture\n */\n var RenderTargetCreationOptions = /** @class */ (function () {\n function RenderTargetCreationOptions() {\n }\n return RenderTargetCreationOptions;\n }());\n BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;\n /**\n * Define options used to create a depth texture\n */\n var DepthTextureCreationOptions = /** @class */ (function () {\n function DepthTextureCreationOptions() {\n }\n return DepthTextureCreationOptions;\n }());\n BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;\n /**\n * Class used to describe the capabilities of the engine relatively to the current browser\n */\n var EngineCapabilities = /** @class */ (function () {\n function EngineCapabilities() {\n }\n return EngineCapabilities;\n }());\n BABYLON.EngineCapabilities = EngineCapabilities;\n /**\n * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio\n */\n var Engine = /** @class */ (function () {\n /**\n * Creates a new engine\n * @param canvasOrContext defines the canvas or WebGL context to use for rendering\n * @param antialias defines enable antialiasing (default: false)\n * @param options defines further options to be sent to the getContext() function\n * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)\n */\n function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {\n if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }\n var _this = this;\n // Public members\n /**\n * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required\n */\n this.forcePOTTextures = false;\n /**\n * Gets a boolean indicating if the engine is currently rendering in fullscreen mode\n */\n this.isFullscreen = false;\n /**\n * Gets a boolean indicating if the pointer is currently locked\n */\n this.isPointerLock = false;\n /**\n * Gets or sets a boolean indicating if back faces must be culled (true by default)\n */\n this.cullBackFaces = true;\n /**\n * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun\n */\n this.renderEvenInBackground = true;\n /**\n * Gets or sets a boolean indicating that cache can be kept between frames\n */\n this.preventCacheWipeBetweenFrames = false;\n /**\n * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest\n **/\n this.enableOfflineSupport = false;\n /**\n * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)\n **/\n this.disableManifestCheck = false;\n /**\n * Gets the list of created scenes\n */\n this.scenes = new Array();\n /**\n * Gets the list of created postprocesses\n */\n this.postProcesses = new Array();\n /** Gets or sets a boolean indicating if the engine should validate programs after compilation */\n this.validateShaderPrograms = false;\n // Observables\n /**\n * Observable event triggered each time the rendering canvas is resized\n */\n this.onResizeObservable = new BABYLON.Observable();\n /**\n * Observable event triggered each time the canvas loses focus\n */\n this.onCanvasBlurObservable = new BABYLON.Observable();\n /**\n * Observable event triggered each time the canvas gains focus\n */\n this.onCanvasFocusObservable = new BABYLON.Observable();\n /**\n * Observable event triggered each time the canvas receives pointerout event\n */\n this.onCanvasPointerOutObservable = new BABYLON.Observable();\n /**\n * Observable event triggered before each texture is initialized\n */\n this.onBeforeTextureInitObservable = new BABYLON.Observable();\n //WebVR\n this._vrDisplay = undefined;\n this._vrSupported = false;\n this._vrExclusivePointerMode = false;\n // Uniform buffers list\n /**\n * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported\n */\n this.disableUniformBuffers = false;\n /** @hidden */\n this._uniformBuffers = new Array();\n // Observables\n /**\n * Observable raised when the engine begins a new frame\n */\n this.onBeginFrameObservable = new BABYLON.Observable();\n /**\n * Observable raised when the engine ends the current frame\n */\n this.onEndFrameObservable = new BABYLON.Observable();\n /**\n * Observable raised when the engine is about to compile a shader\n */\n this.onBeforeShaderCompilationObservable = new BABYLON.Observable();\n /**\n * Observable raised when the engine has jsut compiled a shader\n */\n this.onAfterShaderCompilationObservable = new BABYLON.Observable();\n this._windowIsBackground = false;\n this._webGLVersion = 1.0;\n /** @hidden */\n this._badOS = false;\n /** @hidden */\n this._badDesktopOS = false;\n /**\n * Gets or sets a value indicating if we want to disable texture binding optmization.\n * This could be required on some buggy drivers which wants to have textures bound in a progressive order.\n * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is\n */\n this.disableTextureBindingOptimization = false;\n /**\n * Observable signaled when VR display mode changes\n */\n this.onVRDisplayChangedObservable = new BABYLON.Observable();\n /**\n * Observable signaled when VR request present is complete\n */\n this.onVRRequestPresentComplete = new BABYLON.Observable();\n /**\n * Observable signaled when VR request present starts\n */\n this.onVRRequestPresentStart = new BABYLON.Observable();\n this._colorWrite = true;\n /** @hidden */\n this._drawCalls = new BABYLON.PerfCounter();\n /** @hidden */\n this._textureCollisions = new BABYLON.PerfCounter();\n this._renderingQueueLaunched = false;\n this._activeRenderLoops = new Array();\n // Deterministic lockstepMaxSteps\n this._deterministicLockstep = false;\n this._lockstepMaxSteps = 4;\n // Lost context\n /**\n * Observable signaled when a context lost event is raised\n */\n this.onContextLostObservable = new BABYLON.Observable();\n /**\n * Observable signaled when a context restored event is raised\n */\n this.onContextRestoredObservable = new BABYLON.Observable();\n this._contextWasLost = false;\n this._doNotHandleContextLost = false;\n // FPS\n this._performanceMonitor = new BABYLON.PerformanceMonitor();\n this._fps = 60;\n this._deltaTime = 0;\n /**\n * Turn this value on if you want to pause FPS computation when in background\n */\n this.disablePerformanceMonitorInBackground = false;\n // States\n /** @hidden */\n this._depthCullingState = new BABYLON._DepthCullingState();\n /** @hidden */\n this._stencilState = new BABYLON._StencilState();\n /** @hidden */\n this._alphaState = new BABYLON._AlphaState();\n /** @hidden */\n this._alphaMode = Engine.ALPHA_DISABLE;\n // Cache\n this._internalTexturesCache = new Array();\n /** @hidden */\n this._activeChannel = 0;\n this._currentTextureChannel = -1;\n /** @hidden */\n this._boundTexturesCache = {};\n this._compiledEffects = {};\n this._vertexAttribArraysEnabled = [];\n this._uintIndicesCurrentlySet = false;\n this._currentBoundBuffer = new Array();\n /** @hidden */\n this._currentFramebuffer = null;\n this._currentBufferPointers = new Array();\n this._currentInstanceLocations = new Array();\n this._currentInstanceBuffers = new Array();\n this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();\n this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();\n this._vaoRecordInProgress = false;\n this._mustWipeVertexAttributes = false;\n this._nextFreeTextureSlots = new Array();\n this._maxSimultaneousTextures = 0;\n this._activeRequests = new Array();\n // Hardware supported Compressed Textures\n this._texturesSupported = new Array();\n /**\n * Defines whether the engine has been created with the premultipliedAlpha option on or not.\n */\n this.premultipliedAlpha = true;\n this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);\n this._onVRFullScreenTriggered = function () {\n if (_this._vrDisplay && _this._vrDisplay.isPresenting) {\n //get the old size before we change\n _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());\n _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();\n //get the width and height, change the render size\n var leftEye = _this._vrDisplay.getEyeParameters('left');\n _this.setHardwareScalingLevel(1);\n _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);\n }\n else {\n _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);\n _this.setSize(_this._oldSize.width, _this._oldSize.height);\n }\n };\n this._unpackFlipYCached = null;\n this._boundUniforms = {};\n // Register promises\n BABYLON.PromisePolyfill.Apply();\n var canvas = null;\n Engine.Instances.push(this);\n if (!canvasOrContext) {\n return;\n }\n options = options || {};\n if (canvasOrContext.getContext) {\n canvas = canvasOrContext;\n this._renderingCanvas = canvas;\n if (antialias != null) {\n options.antialias = antialias;\n }\n if (options.deterministicLockstep === undefined) {\n options.deterministicLockstep = false;\n }\n if (options.lockstepMaxSteps === undefined) {\n options.lockstepMaxSteps = 4;\n }\n if (options.preserveDrawingBuffer === undefined) {\n options.preserveDrawingBuffer = false;\n }\n if (options.audioEngine === undefined) {\n options.audioEngine = true;\n }\n if (options.stencil === undefined) {\n options.stencil = true;\n }\n if (options.premultipliedAlpha === false) {\n this.premultipliedAlpha = false;\n }\n this._deterministicLockstep = options.deterministicLockstep;\n this._lockstepMaxSteps = options.lockstepMaxSteps;\n this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;\n // Exceptions\n if (navigator && navigator.userAgent) {\n var ua = navigator.userAgent;\n for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {\n var exception = _a[_i];\n var key = exception.key;\n var targets = exception.targets;\n if (ua.indexOf(key) > -1) {\n if (exception.capture && exception.captureConstraint) {\n var capture = exception.capture;\n var constraint = exception.captureConstraint;\n var regex = new RegExp(capture);\n var matches = regex.exec(ua);\n if (matches && matches.length > 0) {\n var capturedValue = parseInt(matches[matches.length - 1]);\n if (capturedValue >= constraint) {\n continue;\n }\n }\n }\n for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {\n var target = targets_1[_b];\n switch (target) {\n case \"uniformBuffer\":\n this.disableUniformBuffers = true;\n break;\n case \"textureBindingOptimization\":\n this.disableTextureBindingOptimization = true;\n break;\n }\n }\n }\n }\n }\n // GL\n if (!options.disableWebGL2Support) {\n try {\n this._gl = (canvas.getContext(\"webgl2\", options) || canvas.getContext(\"experimental-webgl2\", options));\n if (this._gl) {\n this._webGLVersion = 2.0;\n }\n }\n catch (e) {\n // Do nothing\n }\n }\n if (!this._gl) {\n if (!canvas) {\n throw new Error(\"The provided canvas is null or undefined.\");\n }\n try {\n this._gl = (canvas.getContext(\"webgl\", options) || canvas.getContext(\"experimental-webgl\", options));\n }\n catch (e) {\n throw new Error(\"WebGL not supported\");\n }\n }\n if (!this._gl) {\n throw new Error(\"WebGL not supported\");\n }\n this._onCanvasFocus = function () {\n _this.onCanvasFocusObservable.notifyObservers(_this);\n };\n this._onCanvasBlur = function () {\n _this.onCanvasBlurObservable.notifyObservers(_this);\n };\n canvas.addEventListener(\"focus\", this._onCanvasFocus);\n canvas.addEventListener(\"blur\", this._onCanvasBlur);\n this._onBlur = function () {\n if (_this.disablePerformanceMonitorInBackground) {\n _this._performanceMonitor.disable();\n }\n _this._windowIsBackground = true;\n };\n this._onFocus = function () {\n if (_this.disablePerformanceMonitorInBackground) {\n _this._performanceMonitor.enable();\n }\n _this._windowIsBackground = false;\n };\n this._onCanvasPointerOut = function (ev) {\n _this.onCanvasPointerOutObservable.notifyObservers(ev);\n };\n window.addEventListener(\"blur\", this._onBlur);\n window.addEventListener(\"focus\", this._onFocus);\n canvas.addEventListener(\"pointerout\", this._onCanvasPointerOut);\n // Context lost\n if (!this._doNotHandleContextLost) {\n this._onContextLost = function (evt) {\n evt.preventDefault();\n _this._contextWasLost = true;\n BABYLON.Tools.Warn(\"WebGL context lost.\");\n _this.onContextLostObservable.notifyObservers(_this);\n };\n this._onContextRestored = function (evt) {\n // Adding a timeout to avoid race condition at browser level\n setTimeout(function () {\n // Rebuild gl context\n _this._initGLContext();\n // Rebuild effects\n _this._rebuildEffects();\n // Rebuild textures\n _this._rebuildInternalTextures();\n // Rebuild buffers\n _this._rebuildBuffers();\n // Cache\n _this.wipeCaches(true);\n BABYLON.Tools.Warn(\"WebGL context successfully restored.\");\n _this.onContextRestoredObservable.notifyObservers(_this);\n _this._contextWasLost = false;\n }, 0);\n };\n canvas.addEventListener(\"webglcontextlost\", this._onContextLost, false);\n canvas.addEventListener(\"webglcontextrestored\", this._onContextRestored, false);\n }\n }\n else {\n this._gl = canvasOrContext;\n this._renderingCanvas = this._gl.canvas;\n if (this._gl.renderbufferStorageMultisample) {\n this._webGLVersion = 2.0;\n }\n options.stencil = this._gl.getContextAttributes().stencil;\n }\n // Viewport\n var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;\n this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;\n this.resize();\n this._isStencilEnable = options.stencil ? true : false;\n this._initGLContext();\n if (canvas) {\n // Fullscreen\n this._onFullscreenChange = function () {\n if (document.fullscreen !== undefined) {\n _this.isFullscreen = document.fullscreen;\n }\n else if (document.mozFullScreen !== undefined) {\n _this.isFullscreen = document.mozFullScreen;\n }\n else if (document.webkitIsFullScreen !== undefined) {\n _this.isFullscreen = document.webkitIsFullScreen;\n }\n else if (document.msIsFullScreen !== undefined) {\n _this.isFullscreen = document.msIsFullScreen;\n }\n // Pointer lock\n if (_this.isFullscreen && _this._pointerLockRequested && canvas) {\n canvas.requestPointerLock = canvas.requestPointerLock ||\n canvas.msRequestPointerLock ||\n canvas.mozRequestPointerLock ||\n canvas.webkitRequestPointerLock;\n if (canvas.requestPointerLock) {\n canvas.requestPointerLock();\n }\n }\n };\n document.addEventListener(\"fullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"mozfullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"webkitfullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"msfullscreenchange\", this._onFullscreenChange, false);\n // Pointer lock\n this._onPointerLockChange = function () {\n _this.isPointerLock = (document.mozPointerLockElement === canvas ||\n document.webkitPointerLockElement === canvas ||\n document.msPointerLockElement === canvas ||\n document.pointerLockElement === canvas);\n };\n document.addEventListener(\"pointerlockchange\", this._onPointerLockChange, false);\n document.addEventListener(\"mspointerlockchange\", this._onPointerLockChange, false);\n document.addEventListener(\"mozpointerlockchange\", this._onPointerLockChange, false);\n document.addEventListener(\"webkitpointerlockchange\", this._onPointerLockChange, false);\n this._onVRDisplayPointerRestricted = function () {\n if (canvas) {\n canvas.requestPointerLock();\n }\n };\n this._onVRDisplayPointerUnrestricted = function () {\n document.exitPointerLock();\n };\n window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);\n window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);\n }\n if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {\n Engine.audioEngine = new BABYLON.AudioEngine();\n }\n // Prepare buffer pointers\n for (var i = 0; i < this._caps.maxVertexAttribs; i++) {\n this._currentBufferPointers[i] = new BufferPointer();\n }\n this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);\n // Load WebVR Devices\n if (options.autoEnableWebVR) {\n this.initWebVR();\n }\n // Detect if we are running on a faulty buggy OS.\n this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);\n // Detect if we are running on a faulty buggy desktop OS.\n this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n console.log(\"Babylon.js engine (v\" + Engine.Version + \") launched\");\n this.enableOfflineSupport = (BABYLON.Database !== undefined);\n }\n Object.defineProperty(Engine, \"LastCreatedEngine\", {\n /**\n * Gets the latest created engine\n */\n get: function () {\n if (Engine.Instances.length === 0) {\n return null;\n }\n return Engine.Instances[Engine.Instances.length - 1];\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine, \"LastCreatedScene\", {\n /**\n * Gets the latest created scene\n */\n get: function () {\n var lastCreatedEngine = Engine.LastCreatedEngine;\n if (!lastCreatedEngine) {\n return null;\n }\n if (lastCreatedEngine.scenes.length === 0) {\n return null;\n }\n return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation\n * @param flag defines which part of the materials must be marked as dirty\n * @param predicate defines a predicate used to filter which materials should be affected\n */\n Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {\n for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {\n var engine = Engine.Instances[engineIndex];\n for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {\n engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);\n }\n }\n };\n Object.defineProperty(Engine, \"Version\", {\n /**\n * Returns the current version of the framework\n */\n get: function () {\n return \"3.3.0-alpha.13\";\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"isInVRExclusivePointerMode\", {\n /**\n * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers\n * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input\n */\n get: function () {\n return this._vrExclusivePointerMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"supportsUniformBuffers\", {\n /**\n * Gets a boolean indicating that the engine supports uniform buffers\n * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets\n */\n get: function () {\n return this.webGLVersion > 1 && !this.disableUniformBuffers;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"needPOTTextures\", {\n /**\n * Gets a boolean indicating that only power of 2 textures are supported\n * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them\n */\n get: function () {\n return this._webGLVersion < 2 || this.forcePOTTextures;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"doNotHandleContextLost\", {\n /**\n * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost\n */\n get: function () {\n return this._doNotHandleContextLost;\n },\n set: function (value) {\n this._doNotHandleContextLost = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"performanceMonitor\", {\n /**\n * Gets the performance monitor attached to this engine\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation\n */\n get: function () {\n return this._performanceMonitor;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"texturesSupported\", {\n /**\n * Gets the list of texture formats supported\n */\n get: function () {\n return this._texturesSupported;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"textureFormatInUse\", {\n /**\n * Gets the list of texture formats in use\n */\n get: function () {\n return this._textureFormatInUse;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"currentViewport\", {\n /**\n * Gets the current viewport\n */\n get: function () {\n return this._cachedViewport;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"emptyTexture\", {\n /**\n * Gets the default empty texture\n */\n get: function () {\n if (!this._emptyTexture) {\n this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);\n }\n return this._emptyTexture;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"emptyTexture3D\", {\n /**\n * Gets the default empty 3D texture\n */\n get: function () {\n if (!this._emptyTexture3D) {\n this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);\n }\n return this._emptyTexture3D;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"emptyCubeTexture\", {\n /**\n * Gets the default empty cube texture\n */\n get: function () {\n if (!this._emptyCubeTexture) {\n var faceData = new Uint8Array(4);\n var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];\n this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);\n }\n return this._emptyCubeTexture;\n },\n enumerable: true,\n configurable: true\n });\n Engine.prototype._rebuildInternalTextures = function () {\n var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies\n for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {\n var internalTexture = currentState_1[_i];\n internalTexture._rebuild();\n }\n };\n Engine.prototype._rebuildEffects = function () {\n for (var key in this._compiledEffects) {\n var effect = this._compiledEffects[key];\n effect._prepareEffect();\n }\n BABYLON.Effect.ResetCache();\n };\n Engine.prototype._rebuildBuffers = function () {\n // Index / Vertex\n for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {\n var scene = _a[_i];\n scene.resetCachedMaterial();\n scene._rebuildGeometries();\n scene._rebuildTextures();\n }\n // Uniforms\n for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {\n var uniformBuffer = _c[_b];\n uniformBuffer._rebuild();\n }\n };\n Engine.prototype._initGLContext = function () {\n // Caps\n this._caps = new EngineCapabilities();\n this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);\n this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);\n this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);\n this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);\n this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);\n this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);\n this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);\n this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);\n this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);\n this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);\n // Infos\n this._glVersion = this._gl.getParameter(this._gl.VERSION);\n var rendererInfo = this._gl.getExtension(\"WEBGL_debug_renderer_info\");\n if (rendererInfo != null) {\n this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);\n this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);\n }\n if (!this._glVendor) {\n this._glVendor = \"Unknown vendor\";\n }\n if (!this._glRenderer) {\n this._glRenderer = \"Unknown renderer\";\n }\n // Constants\n this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).\n if (this._gl.RGBA16F !== 0x881A) {\n this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.\n }\n if (this._gl.RGBA32F !== 0x8814) {\n this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.\n }\n if (this._gl.DEPTH24_STENCIL8 !== 35056) {\n this._gl.DEPTH24_STENCIL8 = 35056;\n }\n // Extensions\n this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);\n this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');\n this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');\n this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');\n this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');\n this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||\n this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3\n this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');\n this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;\n this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;\n this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;\n this._caps.highPrecisionShaderSupported = true;\n this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension(\"EXT_disjoint_timer_query\");\n if (this._caps.timerQuery) {\n if (this._webGLVersion === 1) {\n this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);\n }\n this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;\n }\n // Checks if some of the format renders first to allow the use of webgl inspector.\n this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');\n this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;\n this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;\n this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;\n this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;\n this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;\n if (this._webGLVersion > 1) {\n this._gl.HALF_FLOAT_OES = 0x140B;\n }\n this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();\n this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;\n // Draw buffers\n if (this._webGLVersion > 1) {\n this._caps.drawBuffersExtension = true;\n }\n else {\n var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');\n if (drawBuffersExtension !== null) {\n this._caps.drawBuffersExtension = true;\n this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);\n this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;\n for (var i = 0; i < 16; i++) {\n this._gl[\"COLOR_ATTACHMENT\" + i + \"_WEBGL\"] = drawBuffersExtension[\"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n }\n }\n else {\n this._caps.drawBuffersExtension = false;\n }\n }\n // Depth Texture\n if (this._webGLVersion > 1) {\n this._caps.depthTextureExtension = true;\n }\n else {\n var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');\n if (depthTextureExtension != null) {\n this._caps.depthTextureExtension = true;\n this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;\n }\n }\n // Vertex array object\n if (this._webGLVersion > 1) {\n this._caps.vertexArrayObject = true;\n }\n else {\n var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');\n if (vertexArrayObjectExtension != null) {\n this._caps.vertexArrayObject = true;\n this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);\n this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);\n this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);\n }\n else {\n this._caps.vertexArrayObject = false;\n }\n }\n // Instances count\n if (this._webGLVersion > 1) {\n this._caps.instancedArrays = true;\n }\n else {\n var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');\n if (instanceExtension != null) {\n this._caps.instancedArrays = true;\n this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);\n this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);\n this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);\n }\n else {\n this._caps.instancedArrays = false;\n }\n }\n // Intelligently add supported compressed formats in order to check for.\n // Check for ASTC support first as it is most powerful and to be very cross platform.\n // Next PVRTC & DXT, which are probably superior to ETC1/2.\n // Likely no hardware which supports both PVR & DXT, so order matters little.\n // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.\n if (this._caps.astc)\n this.texturesSupported.push('-astc.ktx');\n if (this._caps.s3tc)\n this.texturesSupported.push('-dxt.ktx');\n if (this._caps.pvrtc)\n this.texturesSupported.push('-pvrtc.ktx');\n if (this._caps.etc2)\n this.texturesSupported.push('-etc2.ktx');\n if (this._caps.etc1)\n this.texturesSupported.push('-etc1.ktx');\n if (this._gl.getShaderPrecisionFormat) {\n var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);\n if (highp) {\n this._caps.highPrecisionShaderSupported = highp.precision !== 0;\n }\n }\n // Depth buffer\n this.setDepthBuffer(true);\n this.setDepthFunctionToLessOrEqual();\n this.setDepthWrite(true);\n // Texture maps\n this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;\n for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {\n this._nextFreeTextureSlots.push(slot);\n }\n };\n Object.defineProperty(Engine.prototype, \"webGLVersion\", {\n /**\n * Gets version of the current webGL context\n */\n get: function () {\n return this._webGLVersion;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"isStencilEnable\", {\n /**\n * Returns true if the stencil buffer has been enabled through the creation option of the context.\n */\n get: function () {\n return this._isStencilEnable;\n },\n enumerable: true,\n configurable: true\n });\n Engine.prototype._prepareWorkingCanvas = function () {\n if (this._workingCanvas) {\n return;\n }\n this._workingCanvas = document.createElement(\"canvas\");\n var context = this._workingCanvas.getContext(\"2d\");\n if (context) {\n this._workingContext = context;\n }\n };\n /**\n * Reset the texture cache to empty state\n */\n Engine.prototype.resetTextureCache = function () {\n for (var key in this._boundTexturesCache) {\n if (!this._boundTexturesCache.hasOwnProperty(key)) {\n continue;\n }\n var boundTexture = this._boundTexturesCache[key];\n if (boundTexture) {\n this._removeDesignatedSlot(boundTexture);\n }\n this._boundTexturesCache[key] = null;\n }\n if (!this.disableTextureBindingOptimization) {\n this._nextFreeTextureSlots = [];\n for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {\n this._nextFreeTextureSlots.push(slot);\n }\n }\n this._currentTextureChannel = -1;\n };\n /**\n * Gets a boolean indicating that the engine is running in deterministic lock step mode\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n * @returns true if engine is in deterministic lock step mode\n */\n Engine.prototype.isDeterministicLockStep = function () {\n return this._deterministicLockstep;\n };\n /**\n * Gets the max steps when engine is running in deterministic lock step\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n * @returns the max steps\n */\n Engine.prototype.getLockstepMaxSteps = function () {\n return this._lockstepMaxSteps;\n };\n /**\n * Gets an object containing information about the current webGL context\n * @returns an object containing the vender, the renderer and the version of the current webGL context\n */\n Engine.prototype.getGlInfo = function () {\n return {\n vendor: this._glVendor,\n renderer: this._glRenderer,\n version: this._glVersion\n };\n };\n /**\n * Gets current aspect ratio\n * @param camera defines the camera to use to get the aspect ratio\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the aspect ratio\n */\n Engine.prototype.getAspectRatio = function (camera, useScreen) {\n if (useScreen === void 0) { useScreen = false; }\n var viewport = camera.viewport;\n return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);\n };\n /**\n * Gets current screen aspect ratio\n * @returns a number defining the aspect ratio\n */\n Engine.prototype.getScreenAspectRatio = function () {\n return (this.getRenderWidth(true)) / (this.getRenderHeight(true));\n };\n /**\n * Gets the current render width\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the current render width\n */\n Engine.prototype.getRenderWidth = function (useScreen) {\n if (useScreen === void 0) { useScreen = false; }\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.width;\n }\n return this._gl.drawingBufferWidth;\n };\n /**\n * Gets the current render height\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the current render height\n */\n Engine.prototype.getRenderHeight = function (useScreen) {\n if (useScreen === void 0) { useScreen = false; }\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.height;\n }\n return this._gl.drawingBufferHeight;\n };\n /**\n * Gets the HTML canvas attached with the current webGL context\n * @returns a HTML canvas\n */\n Engine.prototype.getRenderingCanvas = function () {\n return this._renderingCanvas;\n };\n /**\n * Gets the client rect of the HTML canvas attached with the current webGL context\n * @returns a client rectanglee\n */\n Engine.prototype.getRenderingCanvasClientRect = function () {\n if (!this._renderingCanvas) {\n return null;\n }\n return this._renderingCanvas.getBoundingClientRect();\n };\n /**\n * Defines the hardware scaling level.\n * By default the hardware scaling level is computed from the window device ratio.\n * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.\n * @param level defines the level to use\n */\n Engine.prototype.setHardwareScalingLevel = function (level) {\n this._hardwareScalingLevel = level;\n this.resize();\n };\n /**\n * Gets the current hardware scaling level.\n * By default the hardware scaling level is computed from the window device ratio.\n * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.\n * @returns a number indicating the current hardware scaling level\n */\n Engine.prototype.getHardwareScalingLevel = function () {\n return this._hardwareScalingLevel;\n };\n /**\n * Gets the list of loaded textures\n * @returns an array containing all loaded textures\n */\n Engine.prototype.getLoadedTexturesCache = function () {\n return this._internalTexturesCache;\n };\n /**\n * Gets the object containing all engine capabilities\n * @returns the EngineCapabilities object\n */\n Engine.prototype.getCaps = function () {\n return this._caps;\n };\n Object.defineProperty(Engine.prototype, \"drawCalls\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"drawCalls is deprecated. Please use SceneInstrumentation class\");\n return 0;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"drawCallsPerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the current depth function\n * @returns a number defining the depth function\n */\n Engine.prototype.getDepthFunction = function () {\n return this._depthCullingState.depthFunc;\n };\n /**\n * Sets the current depth function\n * @param depthFunc defines the function to use\n */\n Engine.prototype.setDepthFunction = function (depthFunc) {\n this._depthCullingState.depthFunc = depthFunc;\n };\n /**\n * Sets the current depth function to GREATER\n */\n Engine.prototype.setDepthFunctionToGreater = function () {\n this._depthCullingState.depthFunc = this._gl.GREATER;\n };\n /**\n * Sets the current depth function to GEQUAL\n */\n Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {\n this._depthCullingState.depthFunc = this._gl.GEQUAL;\n };\n /**\n * Sets the current depth function to LESS\n */\n Engine.prototype.setDepthFunctionToLess = function () {\n this._depthCullingState.depthFunc = this._gl.LESS;\n };\n /**\n * Sets the current depth function to LEQUAL\n */\n Engine.prototype.setDepthFunctionToLessOrEqual = function () {\n this._depthCullingState.depthFunc = this._gl.LEQUAL;\n };\n /**\n * Gets a boolean indicating if stencil buffer is enabled\n * @returns the current stencil buffer state\n */\n Engine.prototype.getStencilBuffer = function () {\n return this._stencilState.stencilTest;\n };\n /**\n * Enable or disable the stencil buffer\n * @param enable defines if the stencil buffer must be enabled or disabled\n */\n Engine.prototype.setStencilBuffer = function (enable) {\n this._stencilState.stencilTest = enable;\n };\n /**\n * Gets the current stencil mask\n * @returns a number defining the new stencil mask to use\n */\n Engine.prototype.getStencilMask = function () {\n return this._stencilState.stencilMask;\n };\n /**\n * Sets the current stencil mask\n * @param mask defines the new stencil mask to use\n */\n Engine.prototype.setStencilMask = function (mask) {\n this._stencilState.stencilMask = mask;\n };\n /**\n * Gets the current stencil function\n * @returns a number defining the stencil function to use\n */\n Engine.prototype.getStencilFunction = function () {\n return this._stencilState.stencilFunc;\n };\n /**\n * Gets the current stencil reference value\n * @returns a number defining the stencil reference value to use\n */\n Engine.prototype.getStencilFunctionReference = function () {\n return this._stencilState.stencilFuncRef;\n };\n /**\n * Gets the current stencil mask\n * @returns a number defining the stencil mask to use\n */\n Engine.prototype.getStencilFunctionMask = function () {\n return this._stencilState.stencilFuncMask;\n };\n /**\n * Sets the current stencil function\n * @param stencilFunc defines the new stencil function to use\n */\n Engine.prototype.setStencilFunction = function (stencilFunc) {\n this._stencilState.stencilFunc = stencilFunc;\n };\n /**\n * Sets the current stencil reference\n * @param reference defines the new stencil reference to use\n */\n Engine.prototype.setStencilFunctionReference = function (reference) {\n this._stencilState.stencilFuncRef = reference;\n };\n /**\n * Sets the current stencil mask\n * @param mask defines the new stencil mask to use\n */\n Engine.prototype.setStencilFunctionMask = function (mask) {\n this._stencilState.stencilFuncMask = mask;\n };\n /**\n * Gets the current stencil operation when stencil fails\n * @returns a number defining stencil operation to use when stencil fails\n */\n Engine.prototype.getStencilOperationFail = function () {\n return this._stencilState.stencilOpStencilFail;\n };\n /**\n * Gets the current stencil operation when depth fails\n * @returns a number defining stencil operation to use when depth fails\n */\n Engine.prototype.getStencilOperationDepthFail = function () {\n return this._stencilState.stencilOpDepthFail;\n };\n /**\n * Gets the current stencil operation when stencil passes\n * @returns a number defining stencil operation to use when stencil passes\n */\n Engine.prototype.getStencilOperationPass = function () {\n return this._stencilState.stencilOpStencilDepthPass;\n };\n /**\n * Sets the stencil operation to use when stencil fails\n * @param operation defines the stencil operation to use when stencil fails\n */\n Engine.prototype.setStencilOperationFail = function (operation) {\n this._stencilState.stencilOpStencilFail = operation;\n };\n /**\n * Sets the stencil operation to use when depth fails\n * @param operation defines the stencil operation to use when depth fails\n */\n Engine.prototype.setStencilOperationDepthFail = function (operation) {\n this._stencilState.stencilOpDepthFail = operation;\n };\n /**\n * Sets the stencil operation to use when stencil passes\n * @param operation defines the stencil operation to use when stencil passes\n */\n Engine.prototype.setStencilOperationPass = function (operation) {\n this._stencilState.stencilOpStencilDepthPass = operation;\n };\n /**\n * Sets a boolean indicating if the dithering state is enabled or disabled\n * @param value defines the dithering state\n */\n Engine.prototype.setDitheringState = function (value) {\n if (value) {\n this._gl.enable(this._gl.DITHER);\n }\n else {\n this._gl.disable(this._gl.DITHER);\n }\n };\n /**\n * Sets a boolean indicating if the rasterizer state is enabled or disabled\n * @param value defines the rasterizer state\n */\n Engine.prototype.setRasterizerState = function (value) {\n if (value) {\n this._gl.disable(this._gl.RASTERIZER_DISCARD);\n }\n else {\n this._gl.enable(this._gl.RASTERIZER_DISCARD);\n }\n };\n /**\n * stop executing a render loop function and remove it from the execution array\n * @param renderFunction defines the function to be removed. If not provided all functions will be removed.\n */\n Engine.prototype.stopRenderLoop = function (renderFunction) {\n if (!renderFunction) {\n this._activeRenderLoops = [];\n return;\n }\n var index = this._activeRenderLoops.indexOf(renderFunction);\n if (index >= 0) {\n this._activeRenderLoops.splice(index, 1);\n }\n };\n /** @hidden */\n Engine.prototype._renderLoop = function () {\n if (!this._contextWasLost) {\n var shouldRender = true;\n if (!this.renderEvenInBackground && this._windowIsBackground) {\n shouldRender = false;\n }\n if (shouldRender) {\n // Start new frame\n this.beginFrame();\n for (var index = 0; index < this._activeRenderLoops.length; index++) {\n var renderFunction = this._activeRenderLoops[index];\n renderFunction();\n }\n // Present\n this.endFrame();\n }\n }\n if (this._activeRenderLoops.length > 0) {\n // Register new frame\n var requester = null;\n if (this._vrDisplay && this._vrDisplay.isPresenting)\n requester = this._vrDisplay;\n this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);\n }\n else {\n this._renderingQueueLaunched = false;\n }\n };\n /**\n * Register and execute a render loop. The engine can have more than one render function\n * @param renderFunction defines the function to continuously execute\n */\n Engine.prototype.runRenderLoop = function (renderFunction) {\n if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {\n return;\n }\n this._activeRenderLoops.push(renderFunction);\n if (!this._renderingQueueLaunched) {\n this._renderingQueueLaunched = true;\n this._bindedRenderFunction = this._renderLoop.bind(this);\n this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);\n }\n };\n /**\n * Toggle full screen mode\n * @param requestPointerLock defines if a pointer lock should be requested from the user\n * @param options defines an option object to be sent to the requestFullscreen function\n */\n Engine.prototype.switchFullscreen = function (requestPointerLock) {\n if (this.isFullscreen) {\n BABYLON.Tools.ExitFullscreen();\n }\n else {\n this._pointerLockRequested = requestPointerLock;\n if (this._renderingCanvas) {\n BABYLON.Tools.RequestFullscreen(this._renderingCanvas);\n }\n }\n };\n /**\n * Clear the current render buffer or the current render target (if any is set up)\n * @param color defines the color to use\n * @param backBuffer defines if the back buffer must be cleared\n * @param depth defines if the depth buffer must be cleared\n * @param stencil defines if the stencil buffer must be cleared\n */\n Engine.prototype.clear = function (color, backBuffer, depth, stencil) {\n if (stencil === void 0) { stencil = false; }\n this.applyStates();\n var mode = 0;\n if (backBuffer && color) {\n this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);\n mode |= this._gl.COLOR_BUFFER_BIT;\n }\n if (depth) {\n this._gl.clearDepth(1.0);\n mode |= this._gl.DEPTH_BUFFER_BIT;\n }\n if (stencil) {\n this._gl.clearStencil(0);\n mode |= this._gl.STENCIL_BUFFER_BIT;\n }\n this._gl.clear(mode);\n };\n /**\n * Executes a scissor clear (ie. a clear on a specific portion of the screen)\n * @param x defines the x-coordinate of the top left corner of the clear rectangle\n * @param y defines the y-coordinate of the corner of the clear rectangle\n * @param width defines the width of the clear rectangle\n * @param height defines the height of the clear rectangle\n * @param clearColor defines the clear color\n */\n Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {\n var gl = this._gl;\n // Save state\n var curScissor = gl.getParameter(gl.SCISSOR_TEST);\n var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);\n // Change state\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(x, y, width, height);\n // Clear\n this.clear(clearColor, true, true, true);\n // Restore state\n gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);\n if (curScissor === true) {\n gl.enable(gl.SCISSOR_TEST);\n }\n else {\n gl.disable(gl.SCISSOR_TEST);\n }\n };\n /** @hidden */\n Engine.prototype._viewport = function (x, y, width, height) {\n if (x !== this._viewportCached.x ||\n y !== this._viewportCached.y ||\n width !== this._viewportCached.z ||\n height !== this._viewportCached.w) {\n this._viewportCached.x = x;\n this._viewportCached.y = y;\n this._viewportCached.z = width;\n this._viewportCached.w = height;\n this._gl.viewport(x, y, width, height);\n }\n };\n /**\n * Set the WebGL's viewport\n * @param viewport defines the viewport element to be used\n * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used\n * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used\n */\n Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {\n var width = requiredWidth || this.getRenderWidth();\n var height = requiredHeight || this.getRenderHeight();\n var x = viewport.x || 0;\n var y = viewport.y || 0;\n this._cachedViewport = viewport;\n this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);\n };\n /**\n * Directly set the WebGL Viewport\n * @param x defines the x coordinate of the viewport (in screen space)\n * @param y defines the y coordinate of the viewport (in screen space)\n * @param width defines the width of the viewport (in screen space)\n * @param height defines the height of the viewport (in screen space)\n * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state\n */\n Engine.prototype.setDirectViewport = function (x, y, width, height) {\n var currentViewport = this._cachedViewport;\n this._cachedViewport = null;\n this._viewport(x, y, width, height);\n return currentViewport;\n };\n /**\n * Begin a new frame\n */\n Engine.prototype.beginFrame = function () {\n this.onBeginFrameObservable.notifyObservers(this);\n this._measureFps();\n };\n /**\n * Enf the current frame\n */\n Engine.prototype.endFrame = function () {\n // Force a flush in case we are using a bad OS.\n if (this._badOS) {\n this.flushFramebuffer();\n }\n // Submit frame to the vr device, if enabled\n if (this._vrDisplay && this._vrDisplay.isPresenting) {\n // TODO: We should only submit the frame if we read frameData successfully.\n this._vrDisplay.submitFrame();\n }\n this.onEndFrameObservable.notifyObservers(this);\n };\n /**\n * Resize the view according to the canvas' size\n */\n Engine.prototype.resize = function () {\n // We're not resizing the size of the canvas while in VR mode & presenting\n if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {\n var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;\n var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;\n this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);\n }\n };\n /**\n * Force a specific size of the canvas\n * @param width defines the new canvas' width\n * @param height defines the new canvas' height\n */\n Engine.prototype.setSize = function (width, height) {\n if (!this._renderingCanvas) {\n return;\n }\n if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {\n return;\n }\n this._renderingCanvas.width = width;\n this._renderingCanvas.height = height;\n for (var index = 0; index < this.scenes.length; index++) {\n var scene = this.scenes[index];\n for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {\n var cam = scene.cameras[camIndex];\n cam._currentRenderId = 0;\n }\n }\n if (this.onResizeObservable.hasObservers) {\n this.onResizeObservable.notifyObservers(this);\n }\n };\n // WebVR functions\n /**\n * Gets a boolean indicating if a webVR device was detected\n * @returns true if a webVR device was detected\n */\n Engine.prototype.isVRDevicePresent = function () {\n return !!this._vrDisplay;\n };\n /**\n * Gets the current webVR device\n * @returns the current webVR device (or null)\n */\n Engine.prototype.getVRDevice = function () {\n return this._vrDisplay;\n };\n /**\n * Initializes a webVR display and starts listening to display change events\n * The onVRDisplayChangedObservable will be notified upon these changes\n * @returns The onVRDisplayChangedObservable\n */\n Engine.prototype.initWebVR = function () {\n this.initWebVRAsync();\n return this.onVRDisplayChangedObservable;\n };\n /**\n * Initializes a webVR display and starts listening to display change events\n * The onVRDisplayChangedObservable will be notified upon these changes\n * @returns A promise containing a VRDisplay and if vr is supported\n */\n Engine.prototype.initWebVRAsync = function () {\n var _this = this;\n var notifyObservers = function () {\n var eventArgs = {\n vrDisplay: _this._vrDisplay,\n vrSupported: _this._vrSupported\n };\n _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);\n _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });\n };\n if (!this._onVrDisplayConnect) {\n this._onVrDisplayConnect = function (event) {\n _this._vrDisplay = event.display;\n notifyObservers();\n };\n this._onVrDisplayDisconnect = function () {\n _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);\n _this._vrDisplay = undefined;\n _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);\n notifyObservers();\n };\n this._onVrDisplayPresentChange = function () {\n _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;\n };\n window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);\n window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);\n window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);\n }\n this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();\n this._webVRInitPromise.then(notifyObservers);\n return this._webVRInitPromise;\n };\n /**\n * Call this function to switch to webVR mode\n * Will do nothing if webVR is not supported or if there is no webVR device\n * @see http://doc.babylonjs.com/how_to/webvr_camera\n */\n Engine.prototype.enableVR = function () {\n var _this = this;\n if (this._vrDisplay && !this._vrDisplay.isPresenting) {\n var onResolved = function () {\n _this.onVRRequestPresentComplete.notifyObservers(true);\n _this._onVRFullScreenTriggered();\n };\n var onRejected = function () {\n _this.onVRRequestPresentComplete.notifyObservers(false);\n };\n this.onVRRequestPresentStart.notifyObservers(this);\n this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);\n }\n };\n /**\n * Call this function to leave webVR mode\n * Will do nothing if webVR is not supported or if there is no webVR device\n * @see http://doc.babylonjs.com/how_to/webvr_camera\n */\n Engine.prototype.disableVR = function () {\n if (this._vrDisplay && this._vrDisplay.isPresenting) {\n this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);\n }\n };\n Engine.prototype._getVRDisplaysAsync = function () {\n var _this = this;\n return new Promise(function (res, rej) {\n if (navigator.getVRDisplays) {\n navigator.getVRDisplays().then(function (devices) {\n _this._vrSupported = true;\n // note that devices may actually be an empty array. This is fine;\n // we expect this._vrDisplay to be undefined in this case.\n _this._vrDisplay = devices[0];\n res({\n vrDisplay: _this._vrDisplay,\n vrSupported: _this._vrSupported\n });\n });\n }\n else {\n _this._vrDisplay = undefined;\n _this._vrSupported = false;\n res({\n vrDisplay: _this._vrDisplay,\n vrSupported: _this._vrSupported\n });\n }\n });\n };\n /**\n * Binds the frame buffer to the specified texture.\n * @param texture The texture to render to or null for the default canvas\n * @param faceIndex The face of the texture to render to in case of cube texture\n * @param requiredWidth The width of the target to render to\n * @param requiredHeight The height of the target to render to\n * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true\n * @param depthStencilTexture The depth stencil texture to use to render\n * @param lodLevel defines le lod level to bind to the frame buffer\n */\n Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {\n if (lodLevel === void 0) { lodLevel = 0; }\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n this._currentRenderTarget = texture;\n this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);\n var gl = this._gl;\n if (texture.isCube) {\n if (faceIndex === undefined) {\n faceIndex = 0;\n }\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);\n if (depthStencilTexture) {\n if (depthStencilTexture._generateStencilBuffer) {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);\n }\n else {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);\n }\n }\n }\n if (this._cachedViewport && !forceFullscreenViewport) {\n this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);\n }\n else {\n if (!requiredWidth) {\n requiredWidth = texture.width;\n if (lodLevel) {\n requiredWidth = requiredWidth / Math.pow(2, lodLevel);\n }\n }\n if (!requiredHeight) {\n requiredHeight = texture.height;\n if (lodLevel) {\n requiredHeight = requiredHeight / Math.pow(2, lodLevel);\n }\n }\n this._viewport(0, 0, requiredWidth, requiredHeight);\n }\n this.wipeCaches();\n };\n Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {\n if (this._currentFramebuffer !== framebuffer) {\n this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);\n this._currentFramebuffer = framebuffer;\n }\n };\n /**\n * Unbind the current render target texture from the webGL context\n * @param texture defines the render target texture to unbind\n * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated\n * @param onBeforeUnbind defines a function which will be called before the effective unbind\n */\n Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {\n if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }\n this._currentRenderTarget = null;\n // If MSAA, we need to bitblt back to main texture\n var gl = this._gl;\n if (texture._MSAAFramebuffer) {\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);\n gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);\n }\n if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {\n this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);\n gl.generateMipmap(gl.TEXTURE_2D);\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n }\n if (onBeforeUnbind) {\n if (texture._MSAAFramebuffer) {\n // Bind the correct framebuffer\n this.bindUnboundFramebuffer(texture._framebuffer);\n }\n onBeforeUnbind();\n }\n this.bindUnboundFramebuffer(null);\n };\n /**\n * Unbind a list of render target textures from the webGL context\n * This is used only when drawBuffer extension or webGL2 are active\n * @param textures defines the render target textures to unbind\n * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated\n * @param onBeforeUnbind defines a function which will be called before the effective unbind\n */\n Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {\n if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }\n this._currentRenderTarget = null;\n // If MSAA, we need to bitblt back to main texture\n var gl = this._gl;\n if (textures[0]._MSAAFramebuffer) {\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);\n var attachments = textures[0]._attachments;\n if (!attachments) {\n attachments = new Array(textures.length);\n textures[0]._attachments = attachments;\n }\n for (var i = 0; i < textures.length; i++) {\n var texture = textures[i];\n for (var j = 0; j < attachments.length; j++) {\n attachments[j] = gl.NONE;\n }\n attachments[i] = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n gl.readBuffer(attachments[i]);\n gl.drawBuffers(attachments);\n gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);\n }\n for (var i = 0; i < attachments.length; i++) {\n attachments[i] = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n }\n gl.drawBuffers(attachments);\n }\n for (var i = 0; i < textures.length; i++) {\n var texture = textures[i];\n if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {\n this._bindTextureDirectly(gl.TEXTURE_2D, texture);\n gl.generateMipmap(gl.TEXTURE_2D);\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n }\n }\n if (onBeforeUnbind) {\n if (textures[0]._MSAAFramebuffer) {\n // Bind the correct framebuffer\n this.bindUnboundFramebuffer(textures[0]._framebuffer);\n }\n onBeforeUnbind();\n }\n this.bindUnboundFramebuffer(null);\n };\n /**\n * Force the mipmap generation for the given render target texture\n * @param texture defines the render target texture to use\n */\n Engine.prototype.generateMipMapsForCubemap = function (texture) {\n if (texture.generateMipMaps) {\n var gl = this._gl;\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n gl.generateMipmap(gl.TEXTURE_CUBE_MAP);\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n }\n };\n /**\n * Force a webGL flush (ie. a flush of all waiting webGL commands)\n */\n Engine.prototype.flushFramebuffer = function () {\n this._gl.flush();\n };\n /**\n * Unbind the current render target and bind the default framebuffer\n */\n Engine.prototype.restoreDefaultFramebuffer = function () {\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n else {\n this.bindUnboundFramebuffer(null);\n }\n if (this._cachedViewport) {\n this.setViewport(this._cachedViewport);\n }\n this.wipeCaches();\n };\n // UBOs\n /**\n * Create an uniform buffer\n * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets\n * @param elements defines the content of the uniform buffer\n * @returns the webGL uniform buffer\n */\n Engine.prototype.createUniformBuffer = function (elements) {\n var ubo = this._gl.createBuffer();\n if (!ubo) {\n throw new Error(\"Unable to create uniform buffer\");\n }\n this.bindUniformBuffer(ubo);\n if (elements instanceof Float32Array) {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);\n }\n else {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);\n }\n this.bindUniformBuffer(null);\n ubo.references = 1;\n return ubo;\n };\n /**\n * Create a dynamic uniform buffer\n * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets\n * @param elements defines the content of the uniform buffer\n * @returns the webGL uniform buffer\n */\n Engine.prototype.createDynamicUniformBuffer = function (elements) {\n var ubo = this._gl.createBuffer();\n if (!ubo) {\n throw new Error(\"Unable to create dynamic uniform buffer\");\n }\n this.bindUniformBuffer(ubo);\n if (elements instanceof Float32Array) {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);\n }\n else {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);\n }\n this.bindUniformBuffer(null);\n ubo.references = 1;\n return ubo;\n };\n /**\n * Update an existing uniform buffer\n * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets\n * @param uniformBuffer defines the target uniform buffer\n * @param elements defines the content to update\n * @param offset defines the offset in the uniform buffer where update should start\n * @param count defines the size of the data to update\n */\n Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {\n this.bindUniformBuffer(uniformBuffer);\n if (offset === undefined) {\n offset = 0;\n }\n if (count === undefined) {\n if (elements instanceof Float32Array) {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);\n }\n else {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));\n }\n }\n else {\n if (elements instanceof Float32Array) {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));\n }\n else {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));\n }\n }\n this.bindUniformBuffer(null);\n };\n // VBOs\n Engine.prototype._resetVertexBufferBinding = function () {\n this.bindArrayBuffer(null);\n this._cachedVertexBuffers = null;\n };\n /**\n * Creates a vertex buffer\n * @param data the data for the vertex buffer\n * @returns the new WebGL static buffer\n */\n Engine.prototype.createVertexBuffer = function (data) {\n var vbo = this._gl.createBuffer();\n if (!vbo) {\n throw new Error(\"Unable to create vertex buffer\");\n }\n this.bindArrayBuffer(vbo);\n if (data instanceof Array) {\n this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);\n }\n else {\n this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);\n }\n this._resetVertexBufferBinding();\n vbo.references = 1;\n return vbo;\n };\n /**\n * Creates a dynamic vertex buffer\n * @param data the data for the dynamic vertex buffer\n * @returns the new WebGL dynamic buffer\n */\n Engine.prototype.createDynamicVertexBuffer = function (data) {\n var vbo = this._gl.createBuffer();\n if (!vbo) {\n throw new Error(\"Unable to create dynamic vertex buffer\");\n }\n this.bindArrayBuffer(vbo);\n if (data instanceof Array) {\n this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);\n }\n else {\n this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);\n }\n this._resetVertexBufferBinding();\n vbo.references = 1;\n return vbo;\n };\n /**\n * Update a dynamic index buffer\n * @param indexBuffer defines the target index buffer\n * @param indices defines the data to update\n * @param offset defines the offset in the target index buffer where update should start\n */\n Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {\n if (offset === void 0) { offset = 0; }\n // Force cache update\n this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;\n this.bindIndexBuffer(indexBuffer);\n var arrayBuffer;\n if (indices instanceof Uint16Array || indices instanceof Uint32Array) {\n arrayBuffer = indices;\n }\n else {\n arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);\n }\n this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);\n this._resetIndexBufferBinding();\n };\n /**\n * Updates a dynamic vertex buffer.\n * @param vertexBuffer the vertex buffer to update\n * @param data the data used to update the vertex buffer\n * @param byteOffset the byte offset of the data\n * @param byteLength the byte length of the data\n */\n Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {\n this.bindArrayBuffer(vertexBuffer);\n if (byteOffset === undefined) {\n byteOffset = 0;\n }\n if (byteLength === undefined) {\n if (data instanceof Array) {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));\n }\n else {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);\n }\n }\n else {\n if (data instanceof Array) {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));\n }\n else {\n if (data instanceof ArrayBuffer) {\n data = new Uint8Array(data, byteOffset, byteLength);\n }\n else {\n data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);\n }\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);\n }\n }\n this._resetVertexBufferBinding();\n };\n Engine.prototype._resetIndexBufferBinding = function () {\n this.bindIndexBuffer(null);\n this._cachedIndexBuffer = null;\n };\n /**\n * Creates a new index buffer\n * @param indices defines the content of the index buffer\n * @param updatable defines if the index buffer must be updatable\n * @returns a new webGL buffer\n */\n Engine.prototype.createIndexBuffer = function (indices, updatable) {\n var vbo = this._gl.createBuffer();\n if (!vbo) {\n throw new Error(\"Unable to create index buffer\");\n }\n this.bindIndexBuffer(vbo);\n // Check for 32 bits indices\n var arrayBuffer;\n var need32Bits = false;\n if (indices instanceof Uint16Array) {\n arrayBuffer = indices;\n }\n else {\n //check 32 bit support\n if (this._caps.uintIndices) {\n if (indices instanceof Uint32Array) {\n arrayBuffer = indices;\n need32Bits = true;\n }\n else {\n //number[] or Int32Array, check if 32 bit is necessary\n for (var index = 0; index < indices.length; index++) {\n if (indices[index] > 65535) {\n need32Bits = true;\n break;\n }\n }\n arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);\n }\n }\n else {\n //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)\n arrayBuffer = new Uint16Array(indices);\n }\n }\n this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);\n this._resetIndexBufferBinding();\n vbo.references = 1;\n vbo.is32Bits = need32Bits;\n return vbo;\n };\n /**\n * Bind a webGL buffer to the webGL context\n * @param buffer defines the buffer to bind\n */\n Engine.prototype.bindArrayBuffer = function (buffer) {\n if (!this._vaoRecordInProgress) {\n this._unbindVertexArrayObject();\n }\n this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);\n };\n /**\n * Bind an uniform buffer to the current webGL context\n * @param buffer defines the buffer to bind\n */\n Engine.prototype.bindUniformBuffer = function (buffer) {\n this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);\n };\n /**\n * Bind a buffer to the current webGL context at a given location\n * @param buffer defines the buffer to bind\n * @param location defines the index where to bind the buffer\n */\n Engine.prototype.bindUniformBufferBase = function (buffer, location) {\n this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);\n };\n /**\n * Bind a specific block at a given index in a specific shader program\n * @param shaderProgram defines the shader program\n * @param blockName defines the block name\n * @param index defines the index where to bind the block\n */\n Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {\n var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);\n this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);\n };\n ;\n Engine.prototype.bindIndexBuffer = function (buffer) {\n if (!this._vaoRecordInProgress) {\n this._unbindVertexArrayObject();\n }\n this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);\n };\n Engine.prototype.bindBuffer = function (buffer, target) {\n if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {\n this._gl.bindBuffer(target, buffer);\n this._currentBoundBuffer[target] = buffer;\n }\n };\n /**\n * update the bound buffer with the given data\n * @param data defines the data to update\n */\n Engine.prototype.updateArrayBuffer = function (data) {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);\n };\n Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {\n var pointer = this._currentBufferPointers[indx];\n var changed = false;\n if (!pointer.active) {\n changed = true;\n pointer.active = true;\n pointer.index = indx;\n pointer.size = size;\n pointer.type = type;\n pointer.normalized = normalized;\n pointer.stride = stride;\n pointer.offset = offset;\n pointer.buffer = buffer;\n }\n else {\n if (pointer.buffer !== buffer) {\n pointer.buffer = buffer;\n changed = true;\n }\n if (pointer.size !== size) {\n pointer.size = size;\n changed = true;\n }\n if (pointer.type !== type) {\n pointer.type = type;\n changed = true;\n }\n if (pointer.normalized !== normalized) {\n pointer.normalized = normalized;\n changed = true;\n }\n if (pointer.stride !== stride) {\n pointer.stride = stride;\n changed = true;\n }\n if (pointer.offset !== offset) {\n pointer.offset = offset;\n changed = true;\n }\n }\n if (changed || this._vaoRecordInProgress) {\n this.bindArrayBuffer(buffer);\n this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);\n }\n };\n Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {\n if (indexBuffer == null) {\n return;\n }\n if (this._cachedIndexBuffer !== indexBuffer) {\n this._cachedIndexBuffer = indexBuffer;\n this.bindIndexBuffer(indexBuffer);\n this._uintIndicesCurrentlySet = indexBuffer.is32Bits;\n }\n };\n Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {\n var attributes = effect.getAttributesNames();\n if (!this._vaoRecordInProgress) {\n this._unbindVertexArrayObject();\n }\n this.unbindAllAttributes();\n for (var index = 0; index < attributes.length; index++) {\n var order = effect.getAttributeLocation(index);\n if (order >= 0) {\n var vertexBuffer = vertexBuffers[attributes[index]];\n if (!vertexBuffer) {\n continue;\n }\n this._gl.enableVertexAttribArray(order);\n if (!this._vaoRecordInProgress) {\n this._vertexAttribArraysEnabled[order] = true;\n }\n var buffer = vertexBuffer.getBuffer();\n if (buffer) {\n this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);\n if (vertexBuffer.getIsInstanced()) {\n this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());\n if (!this._vaoRecordInProgress) {\n this._currentInstanceLocations.push(order);\n this._currentInstanceBuffers.push(buffer);\n }\n }\n }\n }\n }\n };\n /**\n * Records a vertex array object\n * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects\n * @param vertexBuffers defines the list of vertex buffers to store\n * @param indexBuffer defines the index buffer to store\n * @param effect defines the effect to store\n * @returns the new vertex array object\n */\n Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {\n var vao = this._gl.createVertexArray();\n this._vaoRecordInProgress = true;\n this._gl.bindVertexArray(vao);\n this._mustWipeVertexAttributes = true;\n this._bindVertexBuffersAttributes(vertexBuffers, effect);\n this.bindIndexBuffer(indexBuffer);\n this._vaoRecordInProgress = false;\n this._gl.bindVertexArray(null);\n return vao;\n };\n /**\n * Bind a specific vertex array object\n * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects\n * @param vertexArrayObject defines the vertex array object to bind\n * @param indexBuffer defines the index buffer to bind\n */\n Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {\n if (this._cachedVertexArrayObject !== vertexArrayObject) {\n this._cachedVertexArrayObject = vertexArrayObject;\n this._gl.bindVertexArray(vertexArrayObject);\n this._cachedVertexBuffers = null;\n this._cachedIndexBuffer = null;\n this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;\n this._mustWipeVertexAttributes = true;\n }\n };\n /**\n * Bind webGl buffers directly to the webGL context\n * @param vertexBuffer defines the vertex buffer to bind\n * @param indexBuffer defines the index buffer to bind\n * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer\n * @param vertexStrideSize defines the vertex stride of the vertex buffer\n * @param effect defines the effect associated with the vertex buffer\n */\n Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {\n if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {\n this._cachedVertexBuffers = vertexBuffer;\n this._cachedEffectForVertexBuffers = effect;\n var attributesCount = effect.getAttributesCount();\n this._unbindVertexArrayObject();\n this.unbindAllAttributes();\n var offset = 0;\n for (var index = 0; index < attributesCount; index++) {\n if (index < vertexDeclaration.length) {\n var order = effect.getAttributeLocation(index);\n if (order >= 0) {\n this._gl.enableVertexAttribArray(order);\n this._vertexAttribArraysEnabled[order] = true;\n this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);\n }\n offset += vertexDeclaration[index] * 4;\n }\n }\n }\n this._bindIndexBufferWithCache(indexBuffer);\n };\n Engine.prototype._unbindVertexArrayObject = function () {\n if (!this._cachedVertexArrayObject) {\n return;\n }\n this._cachedVertexArrayObject = null;\n this._gl.bindVertexArray(null);\n };\n /**\n * Bind a list of vertex buffers to the webGL context\n * @param vertexBuffers defines the list of vertex buffers to bind\n * @param indexBuffer defines the index buffer to bind\n * @param effect defines the effect associated with the vertex buffers\n */\n Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {\n if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {\n this._cachedVertexBuffers = vertexBuffers;\n this._cachedEffectForVertexBuffers = effect;\n this._bindVertexBuffersAttributes(vertexBuffers, effect);\n }\n this._bindIndexBufferWithCache(indexBuffer);\n };\n /**\n * Unbind all instance attributes\n */\n Engine.prototype.unbindInstanceAttributes = function () {\n var boundBuffer;\n for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {\n var instancesBuffer = this._currentInstanceBuffers[i];\n if (boundBuffer != instancesBuffer && instancesBuffer.references) {\n boundBuffer = instancesBuffer;\n this.bindArrayBuffer(instancesBuffer);\n }\n var offsetLocation = this._currentInstanceLocations[i];\n this._gl.vertexAttribDivisor(offsetLocation, 0);\n }\n this._currentInstanceBuffers.length = 0;\n this._currentInstanceLocations.length = 0;\n };\n /**\n * Release and free the memory of a vertex array object\n * @param vao defines the vertex array object to delete\n */\n Engine.prototype.releaseVertexArrayObject = function (vao) {\n this._gl.deleteVertexArray(vao);\n };\n /** @hidden */\n Engine.prototype._releaseBuffer = function (buffer) {\n buffer.references--;\n if (buffer.references === 0) {\n this._gl.deleteBuffer(buffer);\n return true;\n }\n return false;\n };\n /**\n * Creates a webGL buffer to use with instanciation\n * @param capacity defines the size of the buffer\n * @returns the webGL buffer\n */\n Engine.prototype.createInstancesBuffer = function (capacity) {\n var buffer = this._gl.createBuffer();\n if (!buffer) {\n throw new Error(\"Unable to create instance buffer\");\n }\n buffer.capacity = capacity;\n this.bindArrayBuffer(buffer);\n this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);\n return buffer;\n };\n /**\n * Delete a webGL buffer used with instanciation\n * @param buffer defines the webGL buffer to delete\n */\n Engine.prototype.deleteInstancesBuffer = function (buffer) {\n this._gl.deleteBuffer(buffer);\n };\n /**\n * Update the content of a webGL buffer used with instanciation and bind it to the webGL context\n * @param instancesBuffer defines the webGL buffer to update and bind\n * @param data defines the data to store in the buffer\n * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer\n */\n Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {\n this.bindArrayBuffer(instancesBuffer);\n if (data) {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);\n }\n if (offsetLocations[0].index !== undefined) {\n var stride = 0;\n for (var i = 0; i < offsetLocations.length; i++) {\n var ai = offsetLocations[i];\n stride += ai.attributeSize * 4;\n }\n for (var i = 0; i < offsetLocations.length; i++) {\n var ai = offsetLocations[i];\n if (!this._vertexAttribArraysEnabled[ai.index]) {\n this._gl.enableVertexAttribArray(ai.index);\n this._vertexAttribArraysEnabled[ai.index] = true;\n }\n this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);\n this._gl.vertexAttribDivisor(ai.index, 1);\n this._currentInstanceLocations.push(ai.index);\n this._currentInstanceBuffers.push(instancesBuffer);\n }\n }\n else {\n for (var index = 0; index < 4; index++) {\n var offsetLocation = offsetLocations[index];\n if (!this._vertexAttribArraysEnabled[offsetLocation]) {\n this._gl.enableVertexAttribArray(offsetLocation);\n this._vertexAttribArraysEnabled[offsetLocation] = true;\n }\n this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);\n this._gl.vertexAttribDivisor(offsetLocation, 1);\n this._currentInstanceLocations.push(offsetLocation);\n this._currentInstanceBuffers.push(instancesBuffer);\n }\n }\n };\n /**\n * Apply all cached states (depth, culling, stencil and alpha)\n */\n Engine.prototype.applyStates = function () {\n this._depthCullingState.apply(this._gl);\n this._stencilState.apply(this._gl);\n this._alphaState.apply(this._gl);\n };\n /**\n * Send a draw order\n * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)\n * @param indexStart defines the starting index\n * @param indexCount defines the number of index to draw\n * @param instancesCount defines the number of instances to draw (if instanciation is enabled)\n */\n Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {\n this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);\n };\n /**\n * Draw a list of points\n * @param verticesStart defines the index of first vertex to draw\n * @param verticesCount defines the count of vertices to draw\n * @param instancesCount defines the number of instances to draw (if instanciation is enabled)\n */\n Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {\n this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);\n };\n /**\n * Draw a list of unindexed primitives\n * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)\n * @param verticesStart defines the index of first vertex to draw\n * @param verticesCount defines the count of vertices to draw\n * @param instancesCount defines the number of instances to draw (if instanciation is enabled)\n */\n Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {\n this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);\n };\n /**\n * Draw a list of indexed primitives\n * @param fillMode defines the primitive to use\n * @param indexStart defines the starting index\n * @param indexCount defines the number of index to draw\n * @param instancesCount defines the number of instances to draw (if instanciation is enabled)\n */\n Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {\n // Apply states\n this.applyStates();\n this._drawCalls.addCount(1, false);\n // Render\n var drawMode = this._drawMode(fillMode);\n var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;\n var mult = this._uintIndicesCurrentlySet ? 4 : 2;\n if (instancesCount) {\n this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);\n }\n else {\n this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);\n }\n };\n /**\n * Draw a list of unindexed primitives\n * @param fillMode defines the primitive to use\n * @param verticesStart defines the index of first vertex to draw\n * @param verticesCount defines the count of vertices to draw\n * @param instancesCount defines the number of instances to draw (if instanciation is enabled)\n */\n Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {\n // Apply states\n this.applyStates();\n this._drawCalls.addCount(1, false);\n var drawMode = this._drawMode(fillMode);\n if (instancesCount) {\n this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);\n }\n else {\n this._gl.drawArrays(drawMode, verticesStart, verticesCount);\n }\n };\n Engine.prototype._drawMode = function (fillMode) {\n switch (fillMode) {\n // Triangle views\n case BABYLON.Material.TriangleFillMode:\n return this._gl.TRIANGLES;\n case BABYLON.Material.PointFillMode:\n return this._gl.POINTS;\n case BABYLON.Material.WireFrameFillMode:\n return this._gl.LINES;\n // Draw modes\n case BABYLON.Material.PointListDrawMode:\n return this._gl.POINTS;\n case BABYLON.Material.LineListDrawMode:\n return this._gl.LINES;\n case BABYLON.Material.LineLoopDrawMode:\n return this._gl.LINE_LOOP;\n case BABYLON.Material.LineStripDrawMode:\n return this._gl.LINE_STRIP;\n case BABYLON.Material.TriangleStripDrawMode:\n return this._gl.TRIANGLE_STRIP;\n case BABYLON.Material.TriangleFanDrawMode:\n return this._gl.TRIANGLE_FAN;\n default:\n return this._gl.TRIANGLES;\n }\n };\n // Shaders\n /** @hidden */\n Engine.prototype._releaseEffect = function (effect) {\n if (this._compiledEffects[effect._key]) {\n delete this._compiledEffects[effect._key];\n this._deleteProgram(effect.getProgram());\n }\n };\n /** @hidden */\n Engine.prototype._deleteProgram = function (program) {\n if (program) {\n program.__SPECTOR_rebuildProgram = null;\n if (program.transformFeedback) {\n this.deleteTransformFeedback(program.transformFeedback);\n program.transformFeedback = null;\n }\n this._gl.deleteProgram(program);\n }\n };\n /**\n * Create a new effect (used to store vertex/fragment shaders)\n * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)\n * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object\n * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use\n * @param samplers defines an array of string used to represent textures\n * @param defines defines the string containing the defines to use to compile the shaders\n * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails\n * @param onCompiled defines a function to call when the effect creation is successful\n * @param onError defines a function to call when the effect creation has failed\n * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)\n * @returns the new Effect\n */\n Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {\n var vertex = baseName.vertexElement || baseName.vertex || baseName;\n var fragment = baseName.fragmentElement || baseName.fragment || baseName;\n var name = vertex + \"+\" + fragment + \"@\" + (defines ? defines : attributesNamesOrOptions.defines);\n if (this._compiledEffects[name]) {\n var compiledEffect = this._compiledEffects[name];\n if (onCompiled && compiledEffect.isReady()) {\n onCompiled(compiledEffect);\n }\n return compiledEffect;\n }\n var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);\n effect._key = name;\n this._compiledEffects[name] = effect;\n return effect;\n };\n Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {\n return this._compileRawShader(shaderVersion + (defines ? defines + \"\\n\" : \"\") + source, type);\n };\n ;\n Engine.prototype._compileRawShader = function (source, type) {\n var gl = this._gl;\n var shader = gl.createShader(type === \"vertex\" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n var log = gl.getShaderInfoLog(shader);\n if (log) {\n throw new Error(log);\n }\n }\n if (!shader) {\n throw new Error(\"Something went wrong while compile the shader.\");\n }\n return shader;\n };\n ;\n /**\n * Directly creates a webGL program\n * @param vertexCode defines the vertex shader code to use\n * @param fragmentCode defines the fragment shader code to use\n * @param context defines the webGL context to use (if not set, the current one will be used)\n * @param transformFeedbackVaryings defines the list of transform feedback varyings to use\n * @returns the new webGL program\n */\n Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {\n if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }\n context = context || this._gl;\n var vertexShader = this._compileRawShader(vertexCode, \"vertex\");\n var fragmentShader = this._compileRawShader(fragmentCode, \"fragment\");\n return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);\n };\n /**\n * Creates a webGL program\n * @param vertexCode defines the vertex shader code to use\n * @param fragmentCode defines the fragment shader code to use\n * @param defines defines the string containing the defines to use to compile the shaders\n * @param context defines the webGL context to use (if not set, the current one will be used)\n * @param transformFeedbackVaryings defines the list of transform feedback varyings to use\n * @returns the new webGL program\n */\n Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {\n if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }\n context = context || this._gl;\n this.onBeforeShaderCompilationObservable.notifyObservers(this);\n var shaderVersion = (this._webGLVersion > 1) ? \"#version 300 es\\n#define WEBGL2 \\n\" : \"\";\n var vertexShader = this._compileShader(vertexCode, \"vertex\", defines, shaderVersion);\n var fragmentShader = this._compileShader(fragmentCode, \"fragment\", defines, shaderVersion);\n var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);\n this.onAfterShaderCompilationObservable.notifyObservers(this);\n return program;\n };\n Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {\n if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }\n var shaderProgram = context.createProgram();\n if (!shaderProgram) {\n throw new Error(\"Unable to create program\");\n }\n context.attachShader(shaderProgram, vertexShader);\n context.attachShader(shaderProgram, fragmentShader);\n if (this.webGLVersion > 1 && transformFeedbackVaryings) {\n var transformFeedback = this.createTransformFeedback();\n this.bindTransformFeedback(transformFeedback);\n this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);\n shaderProgram.transformFeedback = transformFeedback;\n }\n context.linkProgram(shaderProgram);\n if (this.webGLVersion > 1 && transformFeedbackVaryings) {\n this.bindTransformFeedback(null);\n }\n var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);\n if (!linked) {\n var error = context.getProgramInfoLog(shaderProgram);\n if (error) {\n throw new Error(error);\n }\n }\n if (this.validateShaderPrograms) {\n context.validateProgram(shaderProgram);\n var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);\n if (!validated) {\n var error = context.getProgramInfoLog(shaderProgram);\n if (error) {\n throw new Error(error);\n }\n }\n }\n context.deleteShader(vertexShader);\n context.deleteShader(fragmentShader);\n return shaderProgram;\n };\n /**\n * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names\n * @param shaderProgram defines the webGL program to use\n * @param uniformsNames defines the list of uniform names\n * @returns an array of webGL uniform locations\n */\n Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {\n var results = new Array();\n for (var index = 0; index < uniformsNames.length; index++) {\n results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));\n }\n return results;\n };\n /**\n * Gets the lsit of active attributes for a given webGL program\n * @param shaderProgram defines the webGL program to use\n * @param attributesNames defines the list of attribute names to get\n * @returns an array of indices indicating the offset of each attribute\n */\n Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {\n var results = [];\n for (var index = 0; index < attributesNames.length; index++) {\n try {\n results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));\n }\n catch (e) {\n results.push(-1);\n }\n }\n return results;\n };\n /**\n * Activates an effect, mkaing it the current one (ie. the one used for rendering)\n * @param effect defines the effect to activate\n */\n Engine.prototype.enableEffect = function (effect) {\n if (!effect || effect === this._currentEffect) {\n return;\n }\n // Use program\n this.bindSamplers(effect);\n this._currentEffect = effect;\n if (effect.onBind) {\n effect.onBind(effect);\n }\n if (effect._onBindObservable) {\n effect._onBindObservable.notifyObservers(effect);\n }\n };\n /**\n * Set the value of an uniform to an array of int32\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n */\n Engine.prototype.setIntArray = function (uniform, array) {\n if (!uniform)\n return;\n this._gl.uniform1iv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of int32 (stored as vec2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n */\n Engine.prototype.setIntArray2 = function (uniform, array) {\n if (!uniform || array.length % 2 !== 0)\n return;\n this._gl.uniform2iv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of int32 (stored as vec3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n */\n Engine.prototype.setIntArray3 = function (uniform, array) {\n if (!uniform || array.length % 3 !== 0)\n return;\n this._gl.uniform3iv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of int32 (stored as vec4)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n */\n Engine.prototype.setIntArray4 = function (uniform, array) {\n if (!uniform || array.length % 4 !== 0)\n return;\n this._gl.uniform4iv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of float32\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n */\n Engine.prototype.setFloatArray = function (uniform, array) {\n if (!uniform)\n return;\n this._gl.uniform1fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of float32 (stored as vec2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n */\n Engine.prototype.setFloatArray2 = function (uniform, array) {\n if (!uniform || array.length % 2 !== 0)\n return;\n this._gl.uniform2fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of float32 (stored as vec3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n */\n Engine.prototype.setFloatArray3 = function (uniform, array) {\n if (!uniform || array.length % 3 !== 0)\n return;\n this._gl.uniform3fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of float32 (stored as vec4)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n */\n Engine.prototype.setFloatArray4 = function (uniform, array) {\n if (!uniform || array.length % 4 !== 0)\n return;\n this._gl.uniform4fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of number\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n */\n Engine.prototype.setArray = function (uniform, array) {\n if (!uniform)\n return;\n this._gl.uniform1fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of number (stored as vec2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n */\n Engine.prototype.setArray2 = function (uniform, array) {\n if (!uniform || array.length % 2 !== 0)\n return;\n this._gl.uniform2fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of number (stored as vec3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n */\n Engine.prototype.setArray3 = function (uniform, array) {\n if (!uniform || array.length % 3 !== 0)\n return;\n this._gl.uniform3fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of number (stored as vec4)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n */\n Engine.prototype.setArray4 = function (uniform, array) {\n if (!uniform || array.length % 4 !== 0)\n return;\n this._gl.uniform4fv(uniform, array);\n };\n /**\n * Set the value of an uniform to an array of float32 (stored as matrices)\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrices defines the array of float32 to store\n */\n Engine.prototype.setMatrices = function (uniform, matrices) {\n if (!uniform)\n return;\n this._gl.uniformMatrix4fv(uniform, false, matrices);\n };\n /**\n * Set the value of an uniform to a matrix\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrix defines the matrix to store\n */\n Engine.prototype.setMatrix = function (uniform, matrix) {\n if (!uniform)\n return;\n this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());\n };\n /**\n * Set the value of an uniform to a matrix (3x3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrix defines the Float32Array representing the 3x3 matrix to store\n */\n Engine.prototype.setMatrix3x3 = function (uniform, matrix) {\n if (!uniform)\n return;\n this._gl.uniformMatrix3fv(uniform, false, matrix);\n };\n /**\n * Set the value of an uniform to a matrix (2x2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrix defines the Float32Array representing the 2x2 matrix to store\n */\n Engine.prototype.setMatrix2x2 = function (uniform, matrix) {\n if (!uniform)\n return;\n this._gl.uniformMatrix2fv(uniform, false, matrix);\n };\n /**\n * Set the value of an uniform to a number (int)\n * @param uniform defines the webGL uniform location where to store the value\n * @param value defines the int number to store\n */\n Engine.prototype.setInt = function (uniform, value) {\n if (!uniform)\n return;\n this._gl.uniform1i(uniform, value);\n };\n /**\n * Set the value of an uniform to a number (float)\n * @param uniform defines the webGL uniform location where to store the value\n * @param value defines the float number to store\n */\n Engine.prototype.setFloat = function (uniform, value) {\n if (!uniform)\n return;\n this._gl.uniform1f(uniform, value);\n };\n /**\n * Set the value of an uniform to a vec2\n * @param uniform defines the webGL uniform location where to store the value\n * @param x defines the 1st component of the value\n * @param y defines the 2nd component of the value\n */\n Engine.prototype.setFloat2 = function (uniform, x, y) {\n if (!uniform)\n return;\n this._gl.uniform2f(uniform, x, y);\n };\n /**\n * Set the value of an uniform to a vec3\n * @param uniform defines the webGL uniform location where to store the value\n * @param x defines the 1st component of the value\n * @param y defines the 2nd component of the value\n * @param z defines the 3rd component of the value\n */\n Engine.prototype.setFloat3 = function (uniform, x, y, z) {\n if (!uniform)\n return;\n this._gl.uniform3f(uniform, x, y, z);\n };\n /**\n * Set the value of an uniform to a boolean\n * @param uniform defines the webGL uniform location where to store the value\n * @param bool defines the boolean to store\n */\n Engine.prototype.setBool = function (uniform, bool) {\n if (!uniform)\n return;\n this._gl.uniform1i(uniform, bool);\n };\n /**\n * Set the value of an uniform to a vec4\n * @param uniform defines the webGL uniform location where to store the value\n * @param x defines the 1st component of the value\n * @param y defines the 2nd component of the value\n * @param z defines the 3rd component of the value\n * @param w defines the 4th component of the value\n */\n Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {\n if (!uniform)\n return;\n this._gl.uniform4f(uniform, x, y, z, w);\n };\n /**\n * Set the value of an uniform to a Color3\n * @param uniform defines the webGL uniform location where to store the value\n * @param color3 defines the color to store\n */\n Engine.prototype.setColor3 = function (uniform, color3) {\n if (!uniform)\n return;\n this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);\n };\n /**\n * Set the value of an uniform to a Color3 and an alpha value\n * @param uniform defines the webGL uniform location where to store the value\n * @param color3 defines the color to store\n * @param alpha defines the alpha component to store\n */\n Engine.prototype.setColor4 = function (uniform, color3, alpha) {\n if (!uniform)\n return;\n this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);\n };\n /**\n * Sets a Color4 on a uniform variable\n * @param uniform defines the uniform location\n * @param color4 defines the value to be set\n */\n Engine.prototype.setDirectColor4 = function (uniform, color4) {\n if (!uniform)\n return;\n this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);\n };\n // States\n /**\n * Set various states to the webGL context\n * @param culling defines backface culling state\n * @param zOffset defines the value to apply to zOffset (0 by default)\n * @param force defines if states must be applied even if cache is up to date\n * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)\n */\n Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {\n if (zOffset === void 0) { zOffset = 0; }\n if (reverseSide === void 0) { reverseSide = false; }\n // Culling\n if (this._depthCullingState.cull !== culling || force) {\n this._depthCullingState.cull = culling;\n }\n // Cull face\n var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;\n if (this._depthCullingState.cullFace !== cullFace || force) {\n this._depthCullingState.cullFace = cullFace;\n }\n // Z offset\n this.setZOffset(zOffset);\n // Front face\n var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;\n if (this._depthCullingState.frontFace !== frontFace || force) {\n this._depthCullingState.frontFace = frontFace;\n }\n };\n /**\n * Set the z offset to apply to current rendering\n * @param value defines the offset to apply\n */\n Engine.prototype.setZOffset = function (value) {\n this._depthCullingState.zOffset = value;\n };\n /**\n * Gets the current value of the zOffset\n * @returns the current zOffset state\n */\n Engine.prototype.getZOffset = function () {\n return this._depthCullingState.zOffset;\n };\n /**\n * Enable or disable depth buffering\n * @param enable defines the state to set\n */\n Engine.prototype.setDepthBuffer = function (enable) {\n this._depthCullingState.depthTest = enable;\n };\n /**\n * Gets a boolean indicating if depth writing is enabled\n * @returns the current depth writing state\n */\n Engine.prototype.getDepthWrite = function () {\n return this._depthCullingState.depthMask;\n };\n /**\n * Enable or disable depth writing\n * @param enable defines the state to set\n */\n Engine.prototype.setDepthWrite = function (enable) {\n this._depthCullingState.depthMask = enable;\n };\n /**\n * Enable or disable color writing\n * @param enable defines the state to set\n */\n Engine.prototype.setColorWrite = function (enable) {\n this._gl.colorMask(enable, enable, enable, enable);\n this._colorWrite = enable;\n };\n /**\n * Gets a boolean indicating if color writing is enabled\n * @returns the current color writing state\n */\n Engine.prototype.getColorWrite = function () {\n return this._colorWrite;\n };\n /**\n * Sets alpha constants used by some alpha blending modes\n * @param r defines the red component\n * @param g defines the green component\n * @param b defines the blue component\n * @param a defines the alpha component\n */\n Engine.prototype.setAlphaConstants = function (r, g, b, a) {\n this._alphaState.setAlphaBlendConstants(r, g, b, a);\n };\n /**\n * Sets the current alpha mode\n * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)\n * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)\n * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered\n */\n Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {\n if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }\n if (this._alphaMode === mode) {\n return;\n }\n switch (mode) {\n case Engine.ALPHA_DISABLE:\n this._alphaState.alphaBlend = false;\n break;\n case Engine.ALPHA_PREMULTIPLIED:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_COMBINE:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_ONEONE:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_ADD:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_SUBTRACT:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_MULTIPLY:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_MAXIMIZED:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_INTERPOLATE:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n case Engine.ALPHA_SCREENMODE:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n }\n if (!noDepthWriteChange) {\n this.setDepthWrite(mode === Engine.ALPHA_DISABLE);\n }\n this._alphaMode = mode;\n };\n /**\n * Gets the current alpha mode\n * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered\n * @returns the current alpha mode\n */\n Engine.prototype.getAlphaMode = function () {\n return this._alphaMode;\n };\n // Textures\n /**\n * Clears the list of texture accessible through engine.\n * This can help preventing texture load conflict due to name collision.\n */\n Engine.prototype.clearInternalTexturesCache = function () {\n this._internalTexturesCache = [];\n };\n /**\n * Force the entire cache to be cleared\n * You should not have to use this function unless your engine needs to share the webGL context with another engine\n * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)\n */\n Engine.prototype.wipeCaches = function (bruteForce) {\n if (this.preventCacheWipeBetweenFrames && !bruteForce) {\n return;\n }\n this._currentEffect = null;\n this._unpackFlipYCached = null;\n this._viewportCached.x = 0;\n this._viewportCached.y = 0;\n this._viewportCached.z = 0;\n this._viewportCached.w = 0;\n if (bruteForce) {\n this.resetTextureCache();\n this._currentProgram = null;\n this._stencilState.reset();\n this._depthCullingState.reset();\n this.setDepthFunctionToLessOrEqual();\n this._alphaState.reset();\n }\n this._resetVertexBufferBinding();\n this._cachedIndexBuffer = null;\n this._cachedEffectForVertexBuffers = null;\n this._unbindVertexArrayObject();\n this.bindIndexBuffer(null);\n };\n /**\n * Set the compressed texture format to use, based on the formats you have, and the formats\n * supported by the hardware / browser.\n *\n * Khronos Texture Container (.ktx) files are used to support this. This format has the\n * advantage of being specifically designed for OpenGL. Header elements directly correspond\n * to API arguments needed to compressed textures. This puts the burden on the container\n * generator to house the arcane code for determining these for current & future formats.\n *\n * for description see https://www.khronos.org/opengles/sdk/tools/KTX/\n * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/\n *\n * Note: The result of this call is not taken into account when a texture is base64.\n *\n * @param formatsAvailable defines the list of those format families you have created\n * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)\n *\n * Current families are astc, dxt, pvrtc, etc2, & etc1.\n * @returns The extension selected.\n */\n Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {\n for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {\n for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {\n if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {\n return this._textureFormatInUse = this._texturesSupported[i];\n }\n }\n }\n // actively set format to nothing, to allow this to be called more than once\n // and possibly fail the 2nd time\n this._textureFormatInUse = null;\n return null;\n };\n Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {\n var gl = this._gl;\n var magFilter = gl.NEAREST;\n var minFilter = gl.NEAREST;\n switch (samplingMode) {\n case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:\n magFilter = gl.LINEAR;\n if (generateMipMaps) {\n minFilter = gl.LINEAR_MIPMAP_NEAREST;\n }\n else {\n minFilter = gl.LINEAR;\n }\n break;\n case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:\n magFilter = gl.LINEAR;\n if (generateMipMaps) {\n minFilter = gl.LINEAR_MIPMAP_LINEAR;\n }\n else {\n minFilter = gl.LINEAR;\n }\n break;\n case Engine.TEXTURE_NEAREST_SAMPLINGMODE:\n magFilter = gl.NEAREST;\n if (generateMipMaps) {\n minFilter = gl.NEAREST_MIPMAP_LINEAR;\n }\n else {\n minFilter = gl.NEAREST;\n }\n break;\n case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:\n magFilter = gl.NEAREST;\n if (generateMipMaps) {\n minFilter = gl.NEAREST_MIPMAP_NEAREST;\n }\n else {\n minFilter = gl.NEAREST;\n }\n break;\n case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:\n magFilter = gl.NEAREST;\n if (generateMipMaps) {\n minFilter = gl.LINEAR_MIPMAP_NEAREST;\n }\n else {\n minFilter = gl.LINEAR;\n }\n break;\n case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:\n magFilter = gl.NEAREST;\n if (generateMipMaps) {\n minFilter = gl.LINEAR_MIPMAP_LINEAR;\n }\n else {\n minFilter = gl.LINEAR;\n }\n break;\n case Engine.TEXTURE_NEAREST_LINEAR:\n magFilter = gl.NEAREST;\n minFilter = gl.LINEAR;\n break;\n case Engine.TEXTURE_NEAREST_NEAREST:\n magFilter = gl.NEAREST;\n minFilter = gl.NEAREST;\n break;\n case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:\n magFilter = gl.LINEAR;\n if (generateMipMaps) {\n minFilter = gl.NEAREST_MIPMAP_NEAREST;\n }\n else {\n minFilter = gl.NEAREST;\n }\n break;\n case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:\n magFilter = gl.LINEAR;\n if (generateMipMaps) {\n minFilter = gl.NEAREST_MIPMAP_LINEAR;\n }\n else {\n minFilter = gl.NEAREST;\n }\n break;\n case Engine.TEXTURE_LINEAR_LINEAR:\n magFilter = gl.LINEAR;\n minFilter = gl.LINEAR;\n break;\n case Engine.TEXTURE_LINEAR_NEAREST:\n magFilter = gl.LINEAR;\n minFilter = gl.NEAREST;\n break;\n }\n return {\n min: minFilter,\n mag: magFilter\n };\n };\n Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {\n if (onErrorCallBack === void 0) { onErrorCallBack = null; }\n var img;\n var onload = function () {\n loadedImages[index] = img;\n loadedImages._internalCount++;\n if (scene) {\n scene._removePendingData(img);\n }\n if (loadedImages._internalCount === 6) {\n onfinish(loadedImages);\n }\n };\n var onerror = function (message, exception) {\n if (scene) {\n scene._removePendingData(img);\n }\n if (onErrorCallBack) {\n onErrorCallBack(message, exception);\n }\n };\n img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);\n if (scene) {\n scene._addPendingData(img);\n }\n };\n Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {\n if (onError === void 0) { onError = null; }\n var loadedImages = [];\n loadedImages._internalCount = 0;\n for (var index = 0; index < 6; index++) {\n this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);\n }\n };\n ;\n /** @hidden */\n Engine.prototype._createTexture = function () {\n var texture = this._gl.createTexture();\n if (!texture) {\n throw new Error(\"Unable to create texture\");\n }\n return texture;\n };\n /**\n * Usually called from BABYLON.Texture.ts.\n * Passed information to create a WebGLTexture\n * @param urlArg defines a value which contains one of the following:\n * * A conventional http URL, e.g. 'http://...' or 'file://...'\n * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'\n * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'\n * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file\n * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file\n * @param scene needed for loading to the correct scene\n * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)\n * @param onLoad optional callback to be called upon successful completion\n * @param onError optional callback to be called upon failure\n * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob\n * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities\n * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures\n * @param forcedExtension defines the extension to use to pick the right loader\n * @returns a InternalTexture for assignment back into BABYLON.Texture\n */\n Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {\n var _this = this;\n if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (buffer === void 0) { buffer = null; }\n if (fallback === void 0) { fallback = null; }\n if (format === void 0) { format = null; }\n if (forcedExtension === void 0) { forcedExtension = null; }\n var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback\n var fromData = url.substr(0, 5) === \"data:\";\n var fromBlob = url.substr(0, 5) === \"blob:\";\n var isBase64 = fromData && url.indexOf(\"base64\") !== -1;\n var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);\n // establish the file extension, if possible\n var lastDot = url.lastIndexOf('.');\n var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : \"\");\n var loader = null;\n for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {\n var availableLoader = _a[_i];\n if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {\n loader = availableLoader;\n break;\n }\n }\n if (loader) {\n url = loader.transformUrl(url, this._textureFormatInUse);\n }\n if (scene) {\n scene._addPendingData(texture);\n }\n texture.url = url;\n texture.generateMipMaps = !noMipmap;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n if (!this._doNotHandleContextLost) {\n // Keep a link to the buffer only if we plan to handle context lost\n texture._buffer = buffer;\n }\n var onLoadObserver = null;\n if (onLoad && !fallback) {\n onLoadObserver = texture.onLoadedObservable.add(onLoad);\n }\n if (!fallback)\n this._internalTexturesCache.push(texture);\n var onInternalError = function (message, exception) {\n if (scene) {\n scene._removePendingData(texture);\n }\n var customFallback = false;\n if (loader) {\n var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);\n if (fallbackUrl) {\n // Add Back\n customFallback = true;\n _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);\n }\n }\n if (!customFallback) {\n if (onLoadObserver) {\n texture.onLoadedObservable.remove(onLoadObserver);\n }\n if (BABYLON.Tools.UseFallbackTexture) {\n _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);\n }\n }\n if (onError) {\n onError(message || \"Unknown error\", exception);\n }\n };\n // processing for non-image formats\n if (loader) {\n var callback = function (data) {\n loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {\n _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {\n done();\n return false;\n }, samplingMode);\n });\n };\n if (!buffer) {\n this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {\n onInternalError(\"Unable to load \" + (request ? request.responseURL : url, exception));\n });\n }\n else {\n callback(buffer);\n }\n }\n else {\n var onload = function (img) {\n if (fromBlob && !_this._doNotHandleContextLost) {\n // We need to store the image if we need to rebuild the texture\n // in case of a webgl context lost\n texture._buffer = img;\n }\n _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {\n var gl = _this._gl;\n var isPot = (img.width === potWidth && img.height === potHeight);\n var internalFormat = format ? _this._getInternalFormat(format) : ((extension === \".jpg\") ? gl.RGB : gl.RGBA);\n if (isPot) {\n gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);\n return false;\n }\n var maxTextureSize = _this._caps.maxTextureSize;\n if (img.width > maxTextureSize || img.height > maxTextureSize) {\n _this._prepareWorkingCanvas();\n if (!_this._workingCanvas || !_this._workingContext) {\n return false;\n }\n _this._workingCanvas.width = potWidth;\n _this._workingCanvas.height = potHeight;\n _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);\n gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);\n texture.width = potWidth;\n texture.height = potHeight;\n return false;\n }\n else {\n // Using shaders when possible to rescale because canvas.drawImage is lossy\n var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);\n _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);\n gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {\n _this._releaseTexture(source_1);\n _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);\n continuationCallback();\n });\n }\n return true;\n }, samplingMode);\n };\n if (!fromData || isBase64) {\n if (buffer instanceof HTMLImageElement) {\n onload(buffer);\n }\n else {\n BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);\n }\n }\n else if (typeof buffer === \"string\" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {\n BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);\n }\n else {\n onload(buffer);\n }\n }\n return texture;\n };\n Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {\n var _this = this;\n var rtt = this.createRenderTargetTexture({\n width: destination.width,\n height: destination.height,\n }, {\n generateMipMaps: false,\n type: Engine.TEXTURETYPE_UNSIGNED_INT,\n samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,\n generateDepthBuffer: false,\n generateStencilBuffer: false\n });\n if (!this._rescalePostProcess) {\n this._rescalePostProcess = new BABYLON.PassPostProcess(\"rescale\", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);\n }\n this._rescalePostProcess.getEffect().executeWhenCompiled(function () {\n _this._rescalePostProcess.onApply = function (effect) {\n effect._bindTexture(\"textureSampler\", source);\n };\n var hostingScene = scene;\n if (!hostingScene) {\n hostingScene = _this.scenes[_this.scenes.length - 1];\n }\n hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);\n _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);\n _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);\n _this.unBindFramebuffer(rtt);\n _this._releaseTexture(rtt);\n if (onComplete) {\n onComplete();\n }\n });\n };\n /**\n * Update a raw texture\n * @param texture defines the texture to update\n * @param data defines the data to store in the texture\n * @param format defines the format of the data\n * @param invertY defines if data must be stored with Y axis inverted\n * @param compression defines the compression used (null by default)\n * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)\n */\n Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {\n if (compression === void 0) { compression = null; }\n if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (!texture) {\n return;\n }\n // babylon's internalSizedFomat but gl's texImage2D internalFormat\n var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);\n // babylon's internalFormat but gl's texImage2D format\n var internalFormat = this._getInternalFormat(format);\n var textureType = this._getWebGLTextureType(type);\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n texture.format = format;\n texture.type = type;\n texture.invertY = invertY;\n texture._compression = compression;\n }\n if (texture.width % 4 !== 0) {\n this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);\n }\n if (compression && data) {\n this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);\n }\n else {\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);\n }\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n // this.resetTextureCache();\n texture.isReady = true;\n };\n /**\n * Creates a raw texture\n * @param data defines the data to store in the texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param format defines the format of the data\n * @param generateMipMaps defines if the engine should generate the mip levels\n * @param invertY defines if data must be stored with Y axis inverted\n * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)\n * @param compression defines the compression used (null by default)\n * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)\n * @returns the raw texture inside an InternalTexture\n */\n Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {\n if (compression === void 0) { compression = null; }\n if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.format = format;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture._compression = compression;\n texture.type = type;\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n this.updateRawTexture(texture, data, format, invertY, compression, type);\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n // Filters\n var filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);\n if (generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n this._internalTexturesCache.push(texture);\n return texture;\n };\n /** @hidden */\n Engine.prototype._unpackFlipY = function (value) {\n if (this._unpackFlipYCached !== value) {\n this._unpackFlipYCached = value;\n this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);\n }\n };\n /** @hidden */\n Engine.prototype._getUnpackAlignement = function () {\n return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);\n };\n /**\n * Creates a dynamic texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param generateMipMaps defines if the engine should generate the mip levels\n * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)\n * @returns the dynamic texture inside an InternalTexture\n */\n Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);\n texture.baseWidth = width;\n texture.baseHeight = height;\n if (generateMipMaps) {\n width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;\n height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;\n }\n // this.resetTextureCache();\n texture.width = width;\n texture.height = height;\n texture.isReady = false;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n this.updateTextureSamplingMode(samplingMode, texture);\n this._internalTexturesCache.push(texture);\n return texture;\n };\n /**\n * Update the sampling mode of a given texture\n * @param samplingMode defines the required sampling mode\n * @param texture defines the texture to update\n */\n Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {\n var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);\n if (texture.isCube) {\n this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);\n this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n }\n else if (texture.is3D) {\n this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);\n this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);\n this._bindTextureDirectly(this._gl.TEXTURE_3D, null);\n }\n else {\n this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);\n this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n }\n texture.samplingMode = samplingMode;\n };\n /**\n * Update the content of a dynamic texture\n * @param texture defines the texture to update\n * @param canvas defines the canvas containing the source\n * @param invertY defines if data must be stored with Y axis inverted\n * @param premulAlpha defines if alpha is stored as premultiplied\n * @param format defines the format of the data\n */\n Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {\n if (premulAlpha === void 0) { premulAlpha = false; }\n if (!texture) {\n return;\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n this._unpackFlipY(invertY);\n if (premulAlpha) {\n this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);\n }\n var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n if (premulAlpha) {\n this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);\n }\n texture.isReady = true;\n };\n /**\n * Update a video texture\n * @param texture defines the texture to update\n * @param video defines the video element to use\n * @param invertY defines if data must be stored with Y axis inverted\n */\n Engine.prototype.updateVideoTexture = function (texture, video, invertY) {\n if (!texture || texture._isDisabled) {\n return;\n }\n var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n this._unpackFlipY(!invertY); // Video are upside down by default\n try {\n // Testing video texture support\n if (this._videoTextureSupported === undefined) {\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);\n if (this._gl.getError() !== 0) {\n this._videoTextureSupported = false;\n }\n else {\n this._videoTextureSupported = true;\n }\n }\n // Copy video through the current working canvas if video texture is not supported\n if (!this._videoTextureSupported) {\n if (!texture._workingCanvas) {\n texture._workingCanvas = document.createElement(\"canvas\");\n var context = texture._workingCanvas.getContext(\"2d\");\n if (!context) {\n throw new Error(\"Unable to get 2d context\");\n }\n texture._workingContext = context;\n texture._workingCanvas.width = texture.width;\n texture._workingCanvas.height = texture.height;\n }\n texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);\n }\n else {\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);\n }\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n if (!wasPreviouslyBound) {\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n }\n // this.resetTextureCache();\n texture.isReady = true;\n }\n catch (ex) {\n // Something unexpected\n // Let's disable the texture\n texture._isDisabled = true;\n }\n };\n /**\n * Updates a depth texture Comparison Mode and Function.\n * If the comparison Function is equal to 0, the mode will be set to none.\n * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.\n * @param texture The texture to set the comparison function for\n * @param comparisonFunction The comparison function to set, 0 if no comparison required\n */\n Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {\n if (this.webGLVersion === 1) {\n BABYLON.Tools.Error(\"WebGL 1 does not support texture comparison.\");\n return;\n }\n var gl = this._gl;\n if (texture.isCube) {\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);\n if (comparisonFunction === 0) {\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);\n }\n else {\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n }\n else {\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n if (comparisonFunction === 0) {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);\n }\n else {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n }\n texture._comparisonFunction = comparisonFunction;\n };\n Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {\n var width = size.width || size;\n var height = size.height || size;\n internalTexture.baseWidth = width;\n internalTexture.baseHeight = height;\n internalTexture.width = width;\n internalTexture.height = height;\n internalTexture.isReady = true;\n internalTexture.samples = 1;\n internalTexture.generateMipMaps = false;\n internalTexture._generateDepthBuffer = true;\n internalTexture._generateStencilBuffer = generateStencil;\n internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;\n internalTexture._comparisonFunction = comparisonFunction;\n var gl = this._gl;\n var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;\n var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);\n gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);\n gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);\n gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n if (comparisonFunction === 0) {\n gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);\n gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);\n }\n else {\n gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);\n gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);\n }\n };\n /**\n * Creates a depth stencil texture.\n * This is only available in WebGL 2 or with the depth texture extension available.\n * @param size The size of face edge in the texture.\n * @param options The options defining the texture.\n * @returns The texture\n */\n Engine.prototype.createDepthStencilTexture = function (size, options) {\n if (options.isCube) {\n var width = size.width || size;\n return this._createDepthStencilCubeTexture(width, options);\n }\n else {\n return this._createDepthStencilTexture(size, options);\n }\n };\n /**\n * Creates a depth stencil texture.\n * This is only available in WebGL 2 or with the depth texture extension available.\n * @param size The size of face edge in the texture.\n * @param options The options defining the texture.\n * @returns The texture\n */\n Engine.prototype._createDepthStencilTexture = function (size, options) {\n var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);\n if (!this._caps.depthTextureExtension) {\n BABYLON.Tools.Error(\"Depth texture is not supported by your browser or hardware.\");\n return internalTexture;\n }\n var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);\n var gl = this._gl;\n this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);\n this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);\n if (this.webGLVersion > 1) {\n if (internalOptions.generateStencil) {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);\n }\n else {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);\n }\n }\n else {\n if (internalOptions.generateStencil) {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);\n }\n else {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);\n }\n }\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n return internalTexture;\n };\n /**\n * Creates a depth stencil cube texture.\n * This is only available in WebGL 2.\n * @param size The size of face edge in the cube texture.\n * @param options The options defining the cube texture.\n * @returns The cube texture\n */\n Engine.prototype._createDepthStencilCubeTexture = function (size, options) {\n var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);\n internalTexture.isCube = true;\n if (this.webGLVersion === 1) {\n BABYLON.Tools.Error(\"Depth cube texture is not supported by WebGL 1.\");\n return internalTexture;\n }\n var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);\n var gl = this._gl;\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);\n this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);\n // Create the depth/stencil buffer\n for (var face = 0; face < 6; face++) {\n if (internalOptions.generateStencil) {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);\n }\n else {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);\n }\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n return internalTexture;\n };\n /**\n * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.\n * @param renderTarget The render target to set the frame buffer for\n */\n Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {\n // Create the framebuffer\n var internalTexture = renderTarget.getInternalTexture();\n if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {\n return;\n }\n var gl = this._gl;\n var depthStencilTexture = renderTarget.depthStencilTexture;\n this.bindUnboundFramebuffer(internalTexture._framebuffer);\n if (depthStencilTexture.isCube) {\n if (depthStencilTexture._generateStencilBuffer) {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);\n }\n else {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);\n }\n }\n else {\n if (depthStencilTexture._generateStencilBuffer) {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);\n }\n else {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);\n }\n }\n this.bindUnboundFramebuffer(null);\n };\n /**\n * Creates a new render target texture\n * @param size defines the size of the texture\n * @param options defines the options used to create the texture\n * @returns a new render target texture stored in an InternalTexture\n */\n Engine.prototype.createRenderTargetTexture = function (size, options) {\n var fullOptions = new RenderTargetCreationOptions();\n if (options !== undefined && typeof options === \"object\") {\n fullOptions.generateMipMaps = options.generateMipMaps;\n fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;\n fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;\n fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;\n fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;\n }\n else {\n fullOptions.generateMipMaps = options;\n fullOptions.generateDepthBuffer = true;\n fullOptions.generateStencilBuffer = false;\n fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;\n fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;\n fullOptions.format = Engine.TEXTUREFORMAT_RGBA;\n }\n if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n }\n else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n }\n var gl = this._gl;\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);\n this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);\n var width = size.width || size;\n var height = size.height || size;\n var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);\n if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {\n fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;\n BABYLON.Tools.Warn(\"Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type\");\n }\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);\n // Create the framebuffer\n var currentFrameBuffer = this._currentFramebuffer;\n var framebuffer = gl.createFramebuffer();\n this.bindUnboundFramebuffer(framebuffer);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);\n texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);\n if (fullOptions.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n // Unbind\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n gl.bindRenderbuffer(gl.RENDERBUFFER, null);\n this.bindUnboundFramebuffer(currentFrameBuffer);\n texture._framebuffer = framebuffer;\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n texture.samples = 1;\n texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n texture._generateDepthBuffer = fullOptions.generateDepthBuffer;\n texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;\n // this.resetTextureCache();\n this._internalTexturesCache.push(texture);\n return texture;\n };\n /**\n * Create a multi render target texture\n * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target\n * @param size defines the size of the texture\n * @param options defines the creation options\n * @returns the cube texture as an InternalTexture\n */\n Engine.prototype.createMultipleRenderTarget = function (size, options) {\n var generateMipMaps = false;\n var generateDepthBuffer = true;\n var generateStencilBuffer = false;\n var generateDepthTexture = false;\n var textureCount = 1;\n var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;\n var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;\n var types = new Array();\n var samplingModes = new Array();\n if (options !== undefined) {\n generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;\n generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;\n generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;\n textureCount = options.textureCount || 1;\n if (options.types) {\n types = options.types;\n }\n if (options.samplingModes) {\n samplingModes = options.samplingModes;\n }\n }\n var gl = this._gl;\n // Create the framebuffer\n var framebuffer = gl.createFramebuffer();\n this.bindUnboundFramebuffer(framebuffer);\n var width = size.width || size;\n var height = size.height || size;\n var textures = [];\n var attachments = [];\n var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);\n for (var i = 0; i < textureCount; i++) {\n var samplingMode = samplingModes[i] || defaultSamplingMode;\n var type = types[i] || defaultType;\n if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n }\n else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n }\n var filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {\n type = Engine.TEXTURETYPE_UNSIGNED_INT;\n BABYLON.Tools.Warn(\"Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type\");\n }\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);\n var attachment = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n textures.push(texture);\n attachments.push(attachment);\n gl.activeTexture(gl[\"TEXTURE\" + i]);\n gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);\n gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);\n if (generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n // Unbind\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n texture._framebuffer = framebuffer;\n texture._depthStencilBuffer = depthStencilBuffer;\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n texture.samples = 1;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.type = type;\n texture._generateDepthBuffer = generateDepthBuffer;\n texture._generateStencilBuffer = generateStencilBuffer;\n texture._attachments = attachments;\n this._internalTexturesCache.push(texture);\n }\n if (generateDepthTexture && this._caps.depthTextureExtension) {\n // Depth texture\n var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);\n depthTexture._framebuffer = framebuffer;\n depthTexture.baseWidth = width;\n depthTexture.baseHeight = height;\n depthTexture.width = width;\n depthTexture.height = height;\n depthTexture.isReady = true;\n depthTexture.samples = 1;\n depthTexture.generateMipMaps = generateMipMaps;\n depthTexture.samplingMode = gl.NEAREST;\n depthTexture._generateDepthBuffer = generateDepthBuffer;\n depthTexture._generateStencilBuffer = generateStencilBuffer;\n textures.push(depthTexture);\n this._internalTexturesCache.push(depthTexture);\n }\n gl.drawBuffers(attachments);\n gl.bindRenderbuffer(gl.RENDERBUFFER, null);\n this.bindUnboundFramebuffer(null);\n this.resetTextureCache();\n return textures;\n };\n Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {\n if (samples === void 0) { samples = 1; }\n var depthStencilBuffer = null;\n var gl = this._gl;\n // Create the depth/stencil buffer\n if (generateStencilBuffer) {\n depthStencilBuffer = gl.createRenderbuffer();\n gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);\n if (samples > 1) {\n gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);\n }\n else {\n gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);\n }\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);\n }\n else if (generateDepthBuffer) {\n depthStencilBuffer = gl.createRenderbuffer();\n gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);\n if (samples > 1) {\n gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);\n }\n else {\n gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);\n }\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);\n }\n return depthStencilBuffer;\n };\n /**\n * Updates the sample count of a render target texture\n * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets\n * @param texture defines the texture to update\n * @param samples defines the sample count to set\n * @returns the effective sample count (could be 0 if multisample render targets are not supported)\n */\n Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {\n if (this.webGLVersion < 2 || !texture) {\n return 1;\n }\n if (texture.samples === samples) {\n return samples;\n }\n var gl = this._gl;\n samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));\n // Dispose previous render buffers\n if (texture._depthStencilBuffer) {\n gl.deleteRenderbuffer(texture._depthStencilBuffer);\n texture._depthStencilBuffer = null;\n }\n if (texture._MSAAFramebuffer) {\n gl.deleteFramebuffer(texture._MSAAFramebuffer);\n texture._MSAAFramebuffer = null;\n }\n if (texture._MSAARenderBuffer) {\n gl.deleteRenderbuffer(texture._MSAARenderBuffer);\n texture._MSAARenderBuffer = null;\n }\n if (samples > 1) {\n var framebuffer = gl.createFramebuffer();\n if (!framebuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n texture._MSAAFramebuffer = framebuffer;\n this.bindUnboundFramebuffer(texture._MSAAFramebuffer);\n var colorRenderbuffer = gl.createRenderbuffer();\n if (!colorRenderbuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);\n gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);\n texture._MSAARenderBuffer = colorRenderbuffer;\n }\n else {\n this.bindUnboundFramebuffer(texture._framebuffer);\n }\n texture.samples = samples;\n texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);\n gl.bindRenderbuffer(gl.RENDERBUFFER, null);\n this.bindUnboundFramebuffer(null);\n return samples;\n };\n /**\n * Update the sample count for a given multiple render target texture\n * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets\n * @param textures defines the textures to update\n * @param samples defines the sample count to set\n * @returns the effective sample count (could be 0 if multisample render targets are not supported)\n */\n Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {\n if (this.webGLVersion < 2 || !textures || textures.length == 0) {\n return 1;\n }\n if (textures[0].samples === samples) {\n return samples;\n }\n var gl = this._gl;\n samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));\n // Dispose previous render buffers\n if (textures[0]._depthStencilBuffer) {\n gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);\n textures[0]._depthStencilBuffer = null;\n }\n if (textures[0]._MSAAFramebuffer) {\n gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);\n textures[0]._MSAAFramebuffer = null;\n }\n for (var i = 0; i < textures.length; i++) {\n if (textures[i]._MSAARenderBuffer) {\n gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);\n textures[i]._MSAARenderBuffer = null;\n }\n }\n if (samples > 1) {\n var framebuffer = gl.createFramebuffer();\n if (!framebuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n this.bindUnboundFramebuffer(framebuffer);\n var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);\n var attachments = [];\n for (var i = 0; i < textures.length; i++) {\n var texture = textures[i];\n var attachment = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n var colorRenderbuffer = gl.createRenderbuffer();\n if (!colorRenderbuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);\n gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);\n texture._MSAAFramebuffer = framebuffer;\n texture._MSAARenderBuffer = colorRenderbuffer;\n texture.samples = samples;\n texture._depthStencilBuffer = depthStencilBuffer;\n gl.bindRenderbuffer(gl.RENDERBUFFER, null);\n attachments.push(attachment);\n }\n gl.drawBuffers(attachments);\n }\n else {\n this.bindUnboundFramebuffer(textures[0]._framebuffer);\n }\n this.bindUnboundFramebuffer(null);\n return samples;\n };\n /** @hidden */\n Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n var gl = this._gl;\n var target = gl.TEXTURE_2D;\n if (texture.isCube) {\n target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;\n }\n this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);\n };\n /** @hidden */\n Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n var gl = this._gl;\n var textureType = this._getWebGLTextureType(texture.type);\n var format = this._getInternalFormat(texture.format);\n var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);\n this._unpackFlipY(texture.invertY);\n var target = gl.TEXTURE_2D;\n if (texture.isCube) {\n target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;\n }\n var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));\n var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));\n var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));\n var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));\n gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);\n };\n /** @hidden */\n Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n var gl = this._gl;\n var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;\n this._bindTextureDirectly(bindTarget, texture, true);\n this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);\n this._bindTextureDirectly(bindTarget, null, true);\n };\n /** @hidden */\n Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n var gl = this._gl;\n var textureType = this._getWebGLTextureType(texture.type);\n var format = this._getInternalFormat(texture.format);\n var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);\n var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;\n this._bindTextureDirectly(bindTarget, texture, true);\n this._unpackFlipY(texture.invertY);\n var target = gl.TEXTURE_2D;\n if (texture.isCube) {\n target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;\n }\n gl.texImage2D(target, lod, internalFormat, format, textureType, image);\n this._bindTextureDirectly(bindTarget, null, true);\n };\n /**\n * Creates a new render target cube texture\n * @param size defines the size of the texture\n * @param options defines the options used to create the texture\n * @returns a new render target cube texture stored in an InternalTexture\n */\n Engine.prototype.createRenderTargetCubeTexture = function (size, options) {\n var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;\n if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n }\n else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n }\n var gl = this._gl;\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);\n if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {\n fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;\n BABYLON.Tools.Warn(\"Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type\");\n }\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n for (var face = 0; face < 6; face++) {\n gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);\n }\n // Create the framebuffer\n var framebuffer = gl.createFramebuffer();\n this.bindUnboundFramebuffer(framebuffer);\n texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);\n // MipMaps\n if (fullOptions.generateMipMaps) {\n gl.generateMipmap(gl.TEXTURE_CUBE_MAP);\n }\n // Unbind\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n gl.bindRenderbuffer(gl.RENDERBUFFER, null);\n this.bindUnboundFramebuffer(null);\n texture._framebuffer = framebuffer;\n texture.width = size;\n texture.height = size;\n texture.isReady = true;\n texture.isCube = true;\n texture.samples = 1;\n texture.generateMipMaps = fullOptions.generateMipMaps;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n texture._generateDepthBuffer = fullOptions.generateDepthBuffer;\n texture._generateStencilBuffer = fullOptions.generateStencilBuffer;\n this._internalTexturesCache.push(texture);\n return texture;\n };\n /**\n * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)\n * @param rootUrl defines the url where the file to load is located\n * @param scene defines the current scene\n * @param lodScale defines scale to apply to the mip map selection\n * @param lodOffset defines offset to apply to the mip map selection\n * @param onLoad defines an optional callback raised when the texture is loaded\n * @param onError defines an optional callback raised if there is an issue to load the texture\n * @param format defines the format of the data\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture\n * @returns the cube texture as an InternalTexture\n */\n Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {\n var _this = this;\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (forcedExtension === void 0) { forcedExtension = null; }\n if (createPolynomials === void 0) { createPolynomials = true; }\n var callback = function (loadData) {\n if (!loadData) {\n if (onLoad) {\n onLoad(null);\n }\n return;\n }\n var texture = loadData.texture;\n if (!createPolynomials) {\n texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();\n }\n else if (loadData.info.sphericalPolynomial) {\n texture._sphericalPolynomial = loadData.info.sphericalPolynomial;\n }\n texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;\n if (_this._caps.textureLOD) {\n // Do not add extra process if texture lod is supported.\n if (onLoad) {\n onLoad(texture);\n }\n return;\n }\n var mipSlices = 3;\n var gl = _this._gl;\n var width = loadData.width;\n if (!width) {\n return;\n }\n var textures = [];\n for (var i = 0; i < mipSlices; i++) {\n //compute LOD from even spacing in smoothness (matching shader calculation)\n var smoothness = i / (mipSlices - 1);\n var roughness = 1 - smoothness;\n var minLODIndex = lodOffset; // roughness = 0\n var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1\n var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;\n var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));\n var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);\n glTextureFromLod.type = texture.type;\n glTextureFromLod.format = texture.format;\n glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));\n glTextureFromLod.height = glTextureFromLod.width;\n glTextureFromLod.isCube = true;\n _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n if (loadData.isDDS) {\n var info = loadData.info;\n var data = loadData.data;\n _this._unpackFlipY(info.isCompressed);\n BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);\n }\n else {\n BABYLON.Tools.Warn(\"DDS is the only prefiltered cube map supported so far.\");\n }\n _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n // Wrap in a base texture for easy binding.\n var lodTexture = new BABYLON.BaseTexture(scene);\n lodTexture.isCube = true;\n lodTexture._texture = glTextureFromLod;\n glTextureFromLod.isReady = true;\n textures.push(lodTexture);\n }\n texture._lodTextureHigh = textures[2];\n texture._lodTextureMid = textures[1];\n texture._lodTextureLow = textures[0];\n if (onLoad) {\n onLoad(texture);\n }\n };\n return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);\n };\n /**\n * Creates a cube texture\n * @param rootUrl defines the url where the files to load is located\n * @param scene defines the current scene\n * @param files defines the list of files to load (1 per face)\n * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)\n * @param onLoad defines an optional callback raised when the texture is loaded\n * @param onError defines an optional callback raised if there is an issue to load the texture\n * @param format defines the format of the data\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param createPolynomials if a polynomial sphere should be created for the cube texture\n * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness\n * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness\n * @param fallback defines texture to use while falling back when (compressed) texture file not found.\n * @returns the cube texture as an InternalTexture\n */\n Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {\n var _this = this;\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (forcedExtension === void 0) { forcedExtension = null; }\n if (createPolynomials === void 0) { createPolynomials = false; }\n if (lodScale === void 0) { lodScale = 0; }\n if (lodOffset === void 0) { lodOffset = 0; }\n if (fallback === void 0) { fallback = null; }\n var gl = this._gl;\n var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);\n texture.isCube = true;\n texture.url = rootUrl;\n texture.generateMipMaps = !noMipmap;\n texture._lodGenerationScale = lodScale;\n texture._lodGenerationOffset = lodOffset;\n if (!this._doNotHandleContextLost) {\n texture._extension = forcedExtension;\n texture._files = files;\n }\n var lastDot = rootUrl.lastIndexOf('.');\n var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : \"\");\n var loader = null;\n for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {\n var availableLoader = _a[_i];\n if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {\n loader = availableLoader;\n break;\n }\n }\n var onInternalError = function (request, exception) {\n if (loader) {\n var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);\n if (fallbackUrl) {\n _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);\n }\n }\n if (onError && request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n };\n if (loader) {\n rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);\n var onloaddata = function (data) {\n _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);\n };\n if (files && files.length === 6) {\n if (loader.supportCascades) {\n this._cascadeLoadFiles(scene, onloaddata, files, onError);\n }\n else if (onError) {\n onError(\"Textures type does not support cascades.\");\n }\n }\n else {\n this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);\n }\n }\n else {\n if (!files) {\n throw new Error(\"Cannot load cubemap because files were not defined\");\n }\n this._cascadeLoadImgs(rootUrl, scene, function (imgs) {\n var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;\n var height = width;\n _this._prepareWorkingCanvas();\n if (!_this._workingCanvas || !_this._workingContext) {\n return;\n }\n _this._workingCanvas.width = width;\n _this._workingCanvas.height = height;\n var faces = [\n gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z\n ];\n _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n _this._unpackFlipY(false);\n var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;\n for (var index = 0; index < faces.length; index++) {\n _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);\n gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);\n }\n if (!noMipmap) {\n gl.generateMipmap(gl.TEXTURE_CUBE_MAP);\n }\n _this._setCubeMapTextureParams(!noMipmap);\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n if (format) {\n texture.format = format;\n }\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n }, files, onError);\n }\n this._internalTexturesCache.push(texture);\n return texture;\n };\n /**\n * @hidden\n */\n Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {\n var gl = this._gl;\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n // this.resetTextureCache();\n };\n /**\n * Update a raw cube texture\n * @param texture defines the texture to udpdate\n * @param data defines the data to store\n * @param format defines the data format\n * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)\n * @param invertY defines if data must be stored with Y axis inverted\n * @param compression defines the compression used (null by default)\n * @param level defines which level of the texture to update\n */\n Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {\n if (compression === void 0) { compression = null; }\n if (level === void 0) { level = 0; }\n texture._bufferViewArray = data;\n texture.format = format;\n texture.type = type;\n texture.invertY = invertY;\n texture._compression = compression;\n var gl = this._gl;\n var textureType = this._getWebGLTextureType(type);\n var internalFormat = this._getInternalFormat(format);\n var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);\n var needConversion = false;\n if (internalFormat === gl.RGB) {\n internalFormat = gl.RGBA;\n needConversion = true;\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));\n if (texture.width % 4 !== 0) {\n gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);\n }\n // Data are known to be in +X +Y +Z -X -Y -Z\n for (var faceIndex = 0; faceIndex < 6; faceIndex++) {\n var faceData = data[faceIndex];\n if (compression) {\n gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);\n }\n else {\n if (needConversion) {\n faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);\n }\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);\n }\n }\n var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));\n if (isPot && texture.generateMipMaps && level === 0) {\n this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n // this.resetTextureCache();\n texture.isReady = true;\n };\n /**\n * Creates a new raw cube texture\n * @param data defines the array of data to use to create each face\n * @param size defines the size of the textures\n * @param format defines the format of the data\n * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)\n * @param generateMipMaps defines if the engine should generate the mip levels\n * @param invertY defines if data must be stored with Y axis inverted\n * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)\n * @param compression defines the compression used (null by default)\n * @returns the cube texture as an InternalTexture\n */\n Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {\n if (compression === void 0) { compression = null; }\n var gl = this._gl;\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);\n texture.isCube = true;\n texture.format = format;\n texture.type = type;\n if (!this._doNotHandleContextLost) {\n texture._bufferViewArray = data;\n }\n var textureType = this._getWebGLTextureType(type);\n var internalFormat = this._getInternalFormat(format);\n if (internalFormat === gl.RGB) {\n internalFormat = gl.RGBA;\n }\n // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable\n if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {\n generateMipMaps = false;\n samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n BABYLON.Tools.Warn(\"Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.\");\n }\n else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {\n generateMipMaps = false;\n samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n BABYLON.Tools.Warn(\"Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.\");\n }\n else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {\n generateMipMaps = false;\n BABYLON.Tools.Warn(\"Render to float textures is not supported. Mipmap generation forced to false.\");\n }\n else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {\n generateMipMaps = false;\n BABYLON.Tools.Warn(\"Render to half float textures is not supported. Mipmap generation forced to false.\");\n }\n var width = size;\n var height = width;\n texture.width = width;\n texture.height = height;\n // Double check on POT to generate Mips.\n var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));\n if (!isPot) {\n generateMipMaps = false;\n }\n // Upload data if needed. The texture won't be ready until then.\n if (data) {\n this.updateRawCubeTexture(texture, data, format, type, invertY, compression);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);\n // Filters\n if (data && generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);\n }\n var filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n texture.generateMipMaps = generateMipMaps;\n return texture;\n };\n /**\n * Creates a new raw cube texture from a specified url\n * @param url defines the url where the data is located\n * @param scene defines the current scene\n * @param size defines the size of the textures\n * @param format defines the format of the data\n * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)\n * @param noMipmap defines if the engine should avoid generating the mip levels\n * @param callback defines a callback used to extract texture data from loaded data\n * @param mipmapGenerator defines to provide an optional tool to generate mip levels\n * @param onLoad defines a callback called when texture is loaded\n * @param onError defines a callback called if there is an error\n * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)\n * @param invertY defines if data must be stored with Y axis inverted\n * @returns the cube texture as an InternalTexture\n */\n Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {\n var _this = this;\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }\n if (invertY === void 0) { invertY = false; }\n var gl = this._gl;\n var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);\n scene._addPendingData(texture);\n texture.url = url;\n this._internalTexturesCache.push(texture);\n var onerror = function (request, exception) {\n scene._removePendingData(texture);\n if (onError && request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n };\n var internalCallback = function (data) {\n var width = texture.width;\n var faceDataArrays = callback(data);\n if (!faceDataArrays) {\n return;\n }\n if (mipmapGenerator) {\n var textureType = _this._getWebGLTextureType(type);\n var internalFormat = _this._getInternalFormat(format);\n var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);\n var needConversion = false;\n if (internalFormat === gl.RGB) {\n internalFormat = gl.RGBA;\n needConversion = true;\n }\n _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n _this._unpackFlipY(false);\n var mipData = mipmapGenerator(faceDataArrays);\n for (var level = 0; level < mipData.length; level++) {\n var mipSize = width >> level;\n for (var faceIndex = 0; faceIndex < 6; faceIndex++) {\n var mipFaceData = mipData[level][faceIndex];\n if (needConversion) {\n mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);\n }\n gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);\n }\n }\n _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n }\n else {\n _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);\n }\n texture.isReady = true;\n // this.resetTextureCache();\n scene._removePendingData(texture);\n if (onLoad) {\n onLoad();\n }\n };\n this._loadFile(url, function (data) {\n internalCallback(data);\n }, undefined, scene.database, true, onerror);\n return texture;\n };\n ;\n /**\n * Update a raw 3D texture\n * @param texture defines the texture to update\n * @param data defines the data to store\n * @param format defines the data format\n * @param invertY defines if data must be stored with Y axis inverted\n * @param compression defines the used compression (can be null)\n * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)\n */\n Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {\n if (compression === void 0) { compression = null; }\n if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }\n var internalType = this._getWebGLTextureType(textureType);\n var internalFormat = this._getInternalFormat(format);\n var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);\n this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);\n this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n texture.format = format;\n texture.invertY = invertY;\n texture._compression = compression;\n }\n if (texture.width % 4 !== 0) {\n this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);\n }\n if (compression && data) {\n this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);\n }\n else {\n this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);\n }\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_3D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_3D, null);\n // this.resetTextureCache();\n texture.isReady = true;\n };\n /**\n * Creates a new raw 3D texture\n * @param data defines the data used to create the texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param depth defines the depth of the texture\n * @param format defines the format of the texture\n * @param generateMipMaps defines if the engine must generate mip levels\n * @param invertY defines if data must be stored with Y axis inverted\n * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)\n * @param compression defines the compressed used (can be null)\n * @param textureType defines the compressed used (can be null)\n * @returns a new raw 3D texture (stored in an InternalTexture)\n */\n Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {\n if (compression === void 0) { compression = null; }\n if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.baseDepth = depth;\n texture.width = width;\n texture.height = height;\n texture.depth = depth;\n texture.format = format;\n texture.type = textureType;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.is3D = true;\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);\n this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);\n // Filters\n var filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);\n this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);\n if (generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_3D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_3D, null);\n this._internalTexturesCache.push(texture);\n return texture;\n };\n Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {\n var gl = this._gl;\n if (!gl) {\n return;\n }\n var filters = this._getSamplingParameters(samplingMode, !noMipmap);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);\n if (!noMipmap && !isCompressed) {\n gl.generateMipmap(gl.TEXTURE_2D);\n }\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n // this.resetTextureCache();\n if (scene) {\n scene._removePendingData(texture);\n }\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n };\n Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {\n var _this = this;\n if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }\n var maxTextureSize = this.getCaps().maxTextureSize;\n var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);\n var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);\n var gl = this._gl;\n if (!gl) {\n return;\n }\n if (!texture._webGLTexture) {\n // this.resetTextureCache();\n if (scene) {\n scene._removePendingData(texture);\n }\n return;\n }\n this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);\n this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = potWidth;\n texture.height = potHeight;\n texture.isReady = true;\n if (processFunction(potWidth, potHeight, function () {\n _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);\n })) {\n // Returning as texture needs extra async steps\n return;\n }\n this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);\n };\n Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {\n // Create new RGBA data container.\n var rgbaData;\n if (textureType === Engine.TEXTURETYPE_FLOAT) {\n rgbaData = new Float32Array(width * height * 4);\n }\n else {\n rgbaData = new Uint32Array(width * height * 4);\n }\n // Convert each pixel.\n for (var x = 0; x < width; x++) {\n for (var y = 0; y < height; y++) {\n var index = (y * width + x) * 3;\n var newIndex = (y * width + x) * 4;\n // Map Old Value to new value.\n rgbaData[newIndex + 0] = rgbData[index + 0];\n rgbaData[newIndex + 1] = rgbData[index + 1];\n rgbaData[newIndex + 2] = rgbData[index + 2];\n // Add fully opaque alpha channel.\n rgbaData[newIndex + 3] = 1;\n }\n }\n return rgbaData;\n };\n /** @hidden */\n Engine.prototype._releaseFramebufferObjects = function (texture) {\n var gl = this._gl;\n if (texture._framebuffer) {\n gl.deleteFramebuffer(texture._framebuffer);\n texture._framebuffer = null;\n }\n if (texture._depthStencilBuffer) {\n gl.deleteRenderbuffer(texture._depthStencilBuffer);\n texture._depthStencilBuffer = null;\n }\n if (texture._MSAAFramebuffer) {\n gl.deleteFramebuffer(texture._MSAAFramebuffer);\n texture._MSAAFramebuffer = null;\n }\n if (texture._MSAARenderBuffer) {\n gl.deleteRenderbuffer(texture._MSAARenderBuffer);\n texture._MSAARenderBuffer = null;\n }\n };\n /** @hidden */\n Engine.prototype._releaseTexture = function (texture) {\n var gl = this._gl;\n this._releaseFramebufferObjects(texture);\n gl.deleteTexture(texture._webGLTexture);\n // Unbind channels\n this.unbindAllTextures();\n var index = this._internalTexturesCache.indexOf(texture);\n if (index !== -1) {\n this._internalTexturesCache.splice(index, 1);\n }\n // Integrated fixed lod samplers.\n if (texture._lodTextureHigh) {\n texture._lodTextureHigh.dispose();\n }\n if (texture._lodTextureMid) {\n texture._lodTextureMid.dispose();\n }\n if (texture._lodTextureLow) {\n texture._lodTextureLow.dispose();\n }\n // Set output texture of post process to null if the texture has been released/disposed\n this.scenes.forEach(function (scene) {\n scene.postProcesses.forEach(function (postProcess) {\n if (postProcess._outputTexture == texture) {\n postProcess._outputTexture = null;\n }\n });\n scene.cameras.forEach(function (camera) {\n camera._postProcesses.forEach(function (postProcess) {\n if (postProcess) {\n if (postProcess._outputTexture == texture) {\n postProcess._outputTexture = null;\n }\n }\n });\n });\n });\n };\n Engine.prototype.setProgram = function (program) {\n if (this._currentProgram !== program) {\n this._gl.useProgram(program);\n this._currentProgram = program;\n }\n };\n /**\n * Binds an effect to the webGL context\n * @param effect defines the effect to bind\n */\n Engine.prototype.bindSamplers = function (effect) {\n this.setProgram(effect.getProgram());\n var samplers = effect.getSamplers();\n for (var index = 0; index < samplers.length; index++) {\n var uniform = effect.getUniform(samplers[index]);\n if (uniform) {\n this._boundUniforms[index] = uniform;\n }\n }\n this._currentEffect = null;\n };\n Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {\n if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {\n return;\n }\n // Remove\n this._linkTrackers(internalTexture.previous, internalTexture.next);\n // Bind last to it\n this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);\n // Bind to dummy\n this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);\n };\n Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {\n if (!internalTexture) {\n return -1;\n }\n internalTexture._initialSlot = channel;\n if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel\n if (channel !== internalTexture._designatedSlot) {\n this._textureCollisions.addCount(1, false);\n }\n }\n else {\n if (channel !== internalTexture._designatedSlot) {\n if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot\n return internalTexture._designatedSlot;\n }\n else {\n // No slot for this texture, let's pick a new one (if we find a free slot)\n if (this._nextFreeTextureSlots.length) {\n return this._nextFreeTextureSlots[0];\n }\n // We need to recycle the oldest bound texture, sorry.\n this._textureCollisions.addCount(1, false);\n return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);\n }\n }\n }\n return channel;\n };\n Engine.prototype._linkTrackers = function (previous, next) {\n previous.next = next;\n next.previous = previous;\n };\n Engine.prototype._removeDesignatedSlot = function (internalTexture) {\n var currentSlot = internalTexture._designatedSlot;\n if (currentSlot === -1) {\n return -1;\n }\n internalTexture._designatedSlot = -1;\n if (this.disableTextureBindingOptimization) {\n return -1;\n }\n // Remove from bound list\n this._linkTrackers(internalTexture.previous, internalTexture.next);\n // Free the slot\n this._boundTexturesCache[currentSlot] = null;\n this._nextFreeTextureSlots.push(currentSlot);\n return currentSlot;\n };\n Engine.prototype._activateCurrentTexture = function () {\n if (this._currentTextureChannel !== this._activeChannel) {\n this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);\n this._currentTextureChannel = this._activeChannel;\n }\n };\n /** @hidden */\n Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {\n if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }\n if (force === void 0) { force = false; }\n var wasPreviouslyBound = false;\n if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {\n this._activeChannel = texture._designatedSlot;\n }\n var currentTextureBound = this._boundTexturesCache[this._activeChannel];\n var isTextureForRendering = texture && texture._initialSlot > -1;\n if (currentTextureBound !== texture || force) {\n if (currentTextureBound) {\n this._removeDesignatedSlot(currentTextureBound);\n }\n this._activateCurrentTexture();\n this._gl.bindTexture(target, texture ? texture._webGLTexture : null);\n this._boundTexturesCache[this._activeChannel] = texture;\n if (texture) {\n if (!this.disableTextureBindingOptimization) {\n var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);\n if (slotIndex > -1) {\n this._nextFreeTextureSlots.splice(slotIndex, 1);\n }\n this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);\n this._linkTrackers(texture, this._lastBoundInternalTextureTracker);\n }\n texture._designatedSlot = this._activeChannel;\n }\n }\n else if (forTextureDataUpdate) {\n wasPreviouslyBound = true;\n this._activateCurrentTexture();\n }\n if (isTextureForRendering && !forTextureDataUpdate) {\n this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);\n }\n return wasPreviouslyBound;\n };\n /** @hidden */\n Engine.prototype._bindTexture = function (channel, texture) {\n if (channel < 0) {\n return;\n }\n if (texture) {\n channel = this._getCorrectTextureChannel(channel, texture);\n }\n this._activeChannel = channel;\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);\n };\n /**\n * Sets a texture to the webGL context from a postprocess\n * @param channel defines the channel to use\n * @param postProcess defines the source postprocess\n */\n Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {\n this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);\n };\n /**\n * Binds the output of the passed in post process to the texture channel specified\n * @param channel The channel the texture should be bound to\n * @param postProcess The post process which's output should be bound\n */\n Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {\n this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);\n };\n /**\n * Unbind all textures from the webGL context\n */\n Engine.prototype.unbindAllTextures = function () {\n for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {\n this._activeChannel = channel;\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n if (this.webGLVersion > 1) {\n this._bindTextureDirectly(this._gl.TEXTURE_3D, null);\n }\n }\n };\n /**\n * Sets a texture to the according uniform.\n * @param channel The texture channel\n * @param uniform The uniform to set\n * @param texture The texture to apply\n */\n Engine.prototype.setTexture = function (channel, uniform, texture) {\n if (channel < 0) {\n return;\n }\n if (uniform) {\n this._boundUniforms[channel] = uniform;\n }\n this._setTexture(channel, texture);\n };\n /**\n * Sets a depth stencil texture from a render target to the according uniform.\n * @param channel The texture channel\n * @param uniform The uniform to set\n * @param texture The render target texture containing the depth stencil texture to apply\n */\n Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {\n if (channel < 0) {\n return;\n }\n if (uniform) {\n this._boundUniforms[channel] = uniform;\n }\n if (!texture || !texture.depthStencilTexture) {\n this._setTexture(channel, null);\n }\n else {\n this._setTexture(channel, texture, false, true);\n }\n };\n Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {\n var uniform = this._boundUniforms[sourceSlot];\n if (uniform._currentState === destination) {\n return;\n }\n this._gl.uniform1i(uniform, destination);\n uniform._currentState = destination;\n };\n Engine.prototype._getTextureWrapMode = function (mode) {\n switch (mode) {\n case Engine.TEXTURE_WRAP_ADDRESSMODE:\n return this._gl.REPEAT;\n case Engine.TEXTURE_CLAMP_ADDRESSMODE:\n return this._gl.CLAMP_TO_EDGE;\n case Engine.TEXTURE_MIRROR_ADDRESSMODE:\n return this._gl.MIRRORED_REPEAT;\n }\n return this._gl.REPEAT;\n };\n Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {\n if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }\n if (depthStencilTexture === void 0) { depthStencilTexture = false; }\n // Not ready?\n if (!texture) {\n if (this._boundTexturesCache[channel] != null) {\n this._activeChannel = channel;\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n if (this.webGLVersion > 1) {\n this._bindTextureDirectly(this._gl.TEXTURE_3D, null);\n }\n }\n return false;\n }\n // Video\n if (texture.video) {\n this._activeChannel = channel;\n texture.update();\n }\n else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading\n texture.delayLoad();\n return false;\n }\n var internalTexture;\n if (depthStencilTexture) {\n internalTexture = texture.depthStencilTexture;\n }\n else if (texture.isReady()) {\n internalTexture = texture.getInternalTexture();\n }\n else if (texture.isCube) {\n internalTexture = this.emptyCubeTexture;\n }\n else if (texture.is3D) {\n internalTexture = this.emptyTexture3D;\n }\n else {\n internalTexture = this.emptyTexture;\n }\n if (!isPartOfTextureArray) {\n channel = this._getCorrectTextureChannel(channel, internalTexture);\n }\n var needToBind = true;\n if (this._boundTexturesCache[channel] === internalTexture) {\n this._moveBoundTextureOnTop(internalTexture);\n if (!isPartOfTextureArray) {\n this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);\n }\n needToBind = false;\n }\n this._activeChannel = channel;\n if (internalTexture && internalTexture.is3D) {\n if (needToBind) {\n this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);\n }\n if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {\n internalTexture._cachedWrapU = texture.wrapU;\n this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);\n }\n if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {\n internalTexture._cachedWrapV = texture.wrapV;\n this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);\n }\n if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {\n internalTexture._cachedWrapR = texture.wrapR;\n this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);\n }\n this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);\n }\n else if (internalTexture && internalTexture.isCube) {\n if (needToBind) {\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);\n }\n if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {\n internalTexture._cachedCoordinatesMode = texture.coordinatesMode;\n // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.\n var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;\n this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);\n this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);\n }\n this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);\n }\n else {\n if (needToBind) {\n this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);\n }\n if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {\n internalTexture._cachedWrapU = texture.wrapU;\n this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);\n }\n if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {\n internalTexture._cachedWrapV = texture.wrapV;\n this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);\n }\n this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);\n }\n return true;\n };\n /**\n * Sets an array of texture to the webGL context\n * @param channel defines the channel where the texture array must be set\n * @param uniform defines the associated uniform location\n * @param textures defines the array of textures to bind\n */\n Engine.prototype.setTextureArray = function (channel, uniform, textures) {\n if (channel < 0 || !uniform) {\n return;\n }\n if (!this._textureUnits || this._textureUnits.length !== textures.length) {\n this._textureUnits = new Int32Array(textures.length);\n }\n for (var i = 0; i < textures.length; i++) {\n this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());\n }\n this._gl.uniform1iv(uniform, this._textureUnits);\n for (var index = 0; index < textures.length; index++) {\n this._setTexture(this._textureUnits[index], textures[index], true);\n }\n };\n /** @hidden */\n Engine.prototype._setAnisotropicLevel = function (target, texture) {\n var internalTexture = texture.getInternalTexture();\n if (!internalTexture) {\n return;\n }\n var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;\n var value = texture.anisotropicFilteringLevel;\n if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST\n && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR\n && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {\n value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear\n }\n if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {\n this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);\n internalTexture._cachedAnisotropicFilteringLevel = value;\n }\n };\n Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {\n this._bindTextureDirectly(target, texture, true, true);\n this._gl.texParameterf(target, parameter, value);\n };\n Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {\n if (texture) {\n this._bindTextureDirectly(target, texture, true, true);\n }\n this._gl.texParameteri(target, parameter, value);\n };\n /**\n * Reads pixels from the current frame buffer. Please note that this function can be slow\n * @param x defines the x coordinate of the rectangle where pixels must be read\n * @param y defines the y coordinate of the rectangle where pixels must be read\n * @param width defines the width of the rectangle where pixels must be read\n * @param height defines the height of the rectangle where pixels must be read\n * @returns a Uint8Array containing RGBA colors\n */\n Engine.prototype.readPixels = function (x, y, width, height) {\n var data = new Uint8Array(height * width * 4);\n this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);\n return data;\n };\n /**\n * Add an externaly attached data from its key.\n * This method call will fail and return false, if such key already exists.\n * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.\n * @param key the unique key that identifies the data\n * @param data the data object to associate to the key for this Engine instance\n * @return true if no such key were already present and the data was added successfully, false otherwise\n */\n Engine.prototype.addExternalData = function (key, data) {\n if (!this._externalData) {\n this._externalData = new BABYLON.StringDictionary();\n }\n return this._externalData.add(key, data);\n };\n /**\n * Get an externaly attached data from its key\n * @param key the unique key that identifies the data\n * @return the associated data, if present (can be null), or undefined if not present\n */\n Engine.prototype.getExternalData = function (key) {\n if (!this._externalData) {\n this._externalData = new BABYLON.StringDictionary();\n }\n return this._externalData.get(key);\n };\n /**\n * Get an externaly attached data from its key, create it using a factory if it's not already present\n * @param key the unique key that identifies the data\n * @param factory the factory that will be called to create the instance if and only if it doesn't exists\n * @return the associated data, can be null if the factory returned null.\n */\n Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {\n if (!this._externalData) {\n this._externalData = new BABYLON.StringDictionary();\n }\n return this._externalData.getOrAddWithFactory(key, factory);\n };\n /**\n * Remove an externaly attached data from the Engine instance\n * @param key the unique key that identifies the data\n * @return true if the data was successfully removed, false if it doesn't exist\n */\n Engine.prototype.removeExternalData = function (key) {\n if (!this._externalData) {\n this._externalData = new BABYLON.StringDictionary();\n }\n return this._externalData.remove(key);\n };\n /**\n * Unbind all vertex attributes from the webGL context\n */\n Engine.prototype.unbindAllAttributes = function () {\n if (this._mustWipeVertexAttributes) {\n this._mustWipeVertexAttributes = false;\n for (var i = 0; i < this._caps.maxVertexAttribs; i++) {\n this._gl.disableVertexAttribArray(i);\n this._vertexAttribArraysEnabled[i] = false;\n this._currentBufferPointers[i].active = false;\n }\n return;\n }\n for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {\n if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {\n continue;\n }\n this._gl.disableVertexAttribArray(i);\n this._vertexAttribArraysEnabled[i] = false;\n this._currentBufferPointers[i].active = false;\n }\n };\n /**\n * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled\n */\n Engine.prototype.releaseEffects = function () {\n for (var name in this._compiledEffects) {\n this._deleteProgram(this._compiledEffects[name]._program);\n }\n this._compiledEffects = {};\n };\n /**\n * Dispose and release all associated resources\n */\n Engine.prototype.dispose = function () {\n this.hideLoadingUI();\n this.stopRenderLoop();\n // Release postProcesses\n while (this.postProcesses.length) {\n this.postProcesses[0].dispose();\n }\n // Empty texture\n if (this._emptyTexture) {\n this._releaseTexture(this._emptyTexture);\n this._emptyTexture = null;\n }\n if (this._emptyCubeTexture) {\n this._releaseTexture(this._emptyCubeTexture);\n this._emptyCubeTexture = null;\n }\n // Rescale PP\n if (this._rescalePostProcess) {\n this._rescalePostProcess.dispose();\n }\n // Release scenes\n while (this.scenes.length) {\n this.scenes[0].dispose();\n }\n // Release audio engine\n if (Engine.audioEngine) {\n Engine.audioEngine.dispose();\n }\n // Release effects\n this.releaseEffects();\n // Unbind\n this.unbindAllAttributes();\n this._boundUniforms = [];\n if (this._dummyFramebuffer) {\n this._gl.deleteFramebuffer(this._dummyFramebuffer);\n }\n //WebVR\n this.disableVR();\n // Events\n if (BABYLON.Tools.IsWindowObjectExist()) {\n window.removeEventListener(\"blur\", this._onBlur);\n window.removeEventListener(\"focus\", this._onFocus);\n window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);\n window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);\n if (this._renderingCanvas) {\n this._renderingCanvas.removeEventListener(\"focus\", this._onCanvasFocus);\n this._renderingCanvas.removeEventListener(\"blur\", this._onCanvasBlur);\n this._renderingCanvas.removeEventListener(\"pointerout\", this._onCanvasPointerOut);\n if (!this._doNotHandleContextLost) {\n this._renderingCanvas.removeEventListener(\"webglcontextlost\", this._onContextLost);\n this._renderingCanvas.removeEventListener(\"webglcontextrestored\", this._onContextRestored);\n }\n }\n document.removeEventListener(\"fullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"mozfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"webkitfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"msfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"pointerlockchange\", this._onPointerLockChange);\n document.removeEventListener(\"mspointerlockchange\", this._onPointerLockChange);\n document.removeEventListener(\"mozpointerlockchange\", this._onPointerLockChange);\n document.removeEventListener(\"webkitpointerlockchange\", this._onPointerLockChange);\n if (this._onVrDisplayConnect) {\n window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);\n if (this._onVrDisplayDisconnect) {\n window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);\n }\n if (this._onVrDisplayPresentChange) {\n window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);\n }\n this._onVrDisplayConnect = null;\n this._onVrDisplayDisconnect = null;\n }\n }\n // Remove from Instances\n var index = Engine.Instances.indexOf(this);\n if (index >= 0) {\n Engine.Instances.splice(index, 1);\n }\n this._workingCanvas = null;\n this._workingContext = null;\n this._currentBufferPointers = [];\n this._renderingCanvas = null;\n this._currentProgram = null;\n this._bindedRenderFunction = null;\n this.onResizeObservable.clear();\n this.onCanvasBlurObservable.clear();\n this.onCanvasFocusObservable.clear();\n this.onCanvasPointerOutObservable.clear();\n this.onBeginFrameObservable.clear();\n this.onEndFrameObservable.clear();\n BABYLON.Effect.ResetCache();\n // Abort active requests\n for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {\n var request = _a[_i];\n request.abort();\n }\n };\n // Loading screen\n /**\n * Display the loading screen\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n Engine.prototype.displayLoadingUI = function () {\n if (!BABYLON.Tools.IsWindowObjectExist()) {\n return;\n }\n var loadingScreen = this.loadingScreen;\n if (loadingScreen) {\n loadingScreen.displayLoadingUI();\n }\n };\n /**\n * Hide the loading screen\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n Engine.prototype.hideLoadingUI = function () {\n if (!BABYLON.Tools.IsWindowObjectExist()) {\n return;\n }\n var loadingScreen = this.loadingScreen;\n if (loadingScreen) {\n loadingScreen.hideLoadingUI();\n }\n };\n Object.defineProperty(Engine.prototype, \"loadingScreen\", {\n /**\n * Gets the current loading screen object\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n get: function () {\n if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)\n this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);\n return this._loadingScreen;\n },\n /**\n * Sets the current loading screen object\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n set: function (loadingScreen) {\n this._loadingScreen = loadingScreen;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"loadingUIText\", {\n /**\n * Sets the current loading screen text\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n set: function (text) {\n this.loadingScreen.loadingUIText = text;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Engine.prototype, \"loadingUIBackgroundColor\", {\n /**\n * Sets the current loading screen background color\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n set: function (color) {\n this.loadingScreen.loadingUIBackgroundColor = color;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Attach a new callback raised when context lost event is fired\n * @param callback defines the callback to call\n */\n Engine.prototype.attachContextLostEvent = function (callback) {\n if (this._renderingCanvas) {\n this._renderingCanvas.addEventListener(\"webglcontextlost\", callback, false);\n }\n };\n /**\n * Attach a new callback raised when context restored event is fired\n * @param callback defines the callback to call\n */\n Engine.prototype.attachContextRestoredEvent = function (callback) {\n if (this._renderingCanvas) {\n this._renderingCanvas.addEventListener(\"webglcontextrestored\", callback, false);\n }\n };\n /**\n * Gets the source code of the vertex shader associated with a specific webGL program\n * @param program defines the program to use\n * @returns a string containing the source code of the vertex shader associated with the program\n */\n Engine.prototype.getVertexShaderSource = function (program) {\n var shaders = this._gl.getAttachedShaders(program);\n if (!shaders) {\n return null;\n }\n return this._gl.getShaderSource(shaders[0]);\n };\n /**\n * Gets the source code of the fragment shader associated with a specific webGL program\n * @param program defines the program to use\n * @returns a string containing the source code of the fragment shader associated with the program\n */\n Engine.prototype.getFragmentShaderSource = function (program) {\n var shaders = this._gl.getAttachedShaders(program);\n if (!shaders) {\n return null;\n }\n return this._gl.getShaderSource(shaders[1]);\n };\n /**\n * Get the current error code of the webGL context\n * @returns the error code\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError\n */\n Engine.prototype.getError = function () {\n return this._gl.getError();\n };\n // FPS\n /**\n * Gets the current framerate\n * @returns a number representing the framerate\n */\n Engine.prototype.getFps = function () {\n return this._fps;\n };\n /**\n * Gets the time spent between current and previous frame\n * @returns a number representing the delta time in ms\n */\n Engine.prototype.getDeltaTime = function () {\n return this._deltaTime;\n };\n Engine.prototype._measureFps = function () {\n this._performanceMonitor.sampleFrame();\n this._fps = this._performanceMonitor.averageFPS;\n this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;\n };\n /** @hidden */\n Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {\n if (faceIndex === void 0) { faceIndex = -1; }\n if (level === void 0) { level = 0; }\n var gl = this._gl;\n if (!this._dummyFramebuffer) {\n var dummy = gl.createFramebuffer();\n if (!dummy) {\n throw new Error(\"Unable to create dummy framebuffer\");\n }\n this._dummyFramebuffer = dummy;\n }\n gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);\n if (faceIndex > -1) {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);\n }\n else {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);\n }\n var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;\n var buffer;\n switch (readType) {\n case gl.UNSIGNED_BYTE:\n buffer = new Uint8Array(4 * width * height);\n readType = gl.UNSIGNED_BYTE;\n break;\n default:\n buffer = new Float32Array(4 * width * height);\n readType = gl.FLOAT;\n break;\n }\n gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);\n gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);\n return buffer;\n };\n Engine.prototype._canRenderToFloatFramebuffer = function () {\n if (this._webGLVersion > 1) {\n return this._caps.colorBufferFloat;\n }\n return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);\n };\n Engine.prototype._canRenderToHalfFloatFramebuffer = function () {\n if (this._webGLVersion > 1) {\n return this._caps.colorBufferFloat;\n }\n return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);\n };\n // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture\n Engine.prototype._canRenderToFramebuffer = function (type) {\n var gl = this._gl;\n //clear existing errors\n while (gl.getError() !== gl.NO_ERROR) { }\n var successful = true;\n var texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n var fb = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, fb);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);\n successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);\n successful = successful && (gl.getError() === gl.NO_ERROR);\n //try render by clearing frame buffer's color buffer\n if (successful) {\n gl.clear(gl.COLOR_BUFFER_BIT);\n successful = successful && (gl.getError() === gl.NO_ERROR);\n }\n //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)\n if (successful) {\n //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n var readFormat = gl.RGBA;\n var readType = gl.UNSIGNED_BYTE;\n var buffer = new Uint8Array(4);\n gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);\n successful = successful && (gl.getError() === gl.NO_ERROR);\n }\n //clean up\n gl.deleteTexture(texture);\n gl.deleteFramebuffer(fb);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n //clear accumulated errors\n while (!successful && (gl.getError() !== gl.NO_ERROR)) { }\n return successful;\n };\n /** @hidden */\n Engine.prototype._getWebGLTextureType = function (type) {\n if (type === Engine.TEXTURETYPE_FLOAT) {\n return this._gl.FLOAT;\n }\n else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {\n // Add Half Float Constant.\n return this._gl.HALF_FLOAT_OES;\n }\n return this._gl.UNSIGNED_BYTE;\n };\n ;\n Engine.prototype._getInternalFormat = function (format) {\n var internalFormat = this._gl.RGBA;\n switch (format) {\n case Engine.TEXTUREFORMAT_ALPHA:\n internalFormat = this._gl.ALPHA;\n break;\n case Engine.TEXTUREFORMAT_LUMINANCE:\n internalFormat = this._gl.LUMINANCE;\n break;\n case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:\n internalFormat = this._gl.LUMINANCE_ALPHA;\n break;\n case Engine.TEXTUREFORMAT_RGB:\n internalFormat = this._gl.RGB;\n break;\n case Engine.TEXTUREFORMAT_RGBA:\n internalFormat = this._gl.RGBA;\n break;\n case Engine.TEXTUREFORMAT_R:\n internalFormat = this._gl.RED;\n break;\n case Engine.TEXTUREFORMAT_RG:\n internalFormat = this._gl.RG;\n break;\n }\n return internalFormat;\n };\n /** @hidden */\n Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {\n if (this._webGLVersion === 1) {\n if (format !== undefined) {\n switch (format) {\n case Engine.TEXTUREFORMAT_LUMINANCE:\n return this._gl.LUMINANCE;\n case Engine.TEXTUREFORMAT_ALPHA:\n return this._gl.ALPHA;\n }\n }\n return this._gl.RGBA;\n }\n if (type === Engine.TEXTURETYPE_FLOAT) {\n if (format !== undefined) {\n switch (format) {\n case Engine.TEXTUREFORMAT_R:\n return this._gl.R32F;\n case Engine.TEXTUREFORMAT_RG:\n return this._gl.RG32F;\n case Engine.TEXTUREFORMAT_RGB:\n return this._gl.RGB32F;\n }\n }\n return this._gl.RGBA32F;\n }\n if (type === Engine.TEXTURETYPE_HALF_FLOAT) {\n if (format) {\n switch (format) {\n case Engine.TEXTUREFORMAT_R:\n return this._gl.R16F;\n case Engine.TEXTUREFORMAT_RG:\n return this._gl.RG16F;\n case Engine.TEXTUREFORMAT_RGB:\n return this._gl.RGB16F;\n }\n }\n return this._gl.RGBA16F;\n }\n if (format !== undefined) {\n switch (format) {\n case Engine.TEXTUREFORMAT_LUMINANCE:\n return this._gl.LUMINANCE;\n case Engine.TEXTUREFORMAT_RGB:\n return this._gl.RGB;\n case Engine.TEXTUREFORMAT_R:\n return this._gl.R8;\n case Engine.TEXTUREFORMAT_RG:\n return this._gl.RG8;\n case Engine.TEXTUREFORMAT_ALPHA:\n return this._gl.ALPHA;\n }\n }\n return this._gl.RGBA;\n };\n ;\n /** @hidden */\n Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {\n if (type === Engine.TEXTURETYPE_FLOAT) {\n return this._gl.RGBA32F;\n }\n else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {\n return this._gl.RGBA16F;\n }\n return this._gl.RGBA8;\n };\n ;\n /** @hidden */\n Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {\n var _this = this;\n var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);\n this._activeRequests.push(request);\n request.onCompleteObservable.add(function (request) {\n _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);\n });\n return request;\n };\n /** @hidden */\n Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this._loadFile(url, function (data) {\n resolve(data);\n }, undefined, database, useArrayBuffer, function (request, exception) {\n reject(exception);\n });\n });\n };\n Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {\n if (onErrorCallBack === void 0) { onErrorCallBack = null; }\n var onload = function (data) {\n loadedFiles[index] = data;\n loadedFiles._internalCount++;\n if (loadedFiles._internalCount === 6) {\n onfinish(loadedFiles);\n }\n };\n var onerror = function (request, exception) {\n if (onErrorCallBack && request) {\n onErrorCallBack(request.status + \" \" + request.statusText, exception);\n }\n };\n this._loadFile(url, onload, undefined, undefined, true, onerror);\n };\n Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {\n if (onError === void 0) { onError = null; }\n var loadedFiles = [];\n loadedFiles._internalCount = 0;\n for (var index = 0; index < 6; index++) {\n this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);\n }\n };\n // Statics\n /**\n * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)\n * @returns true if the engine can be created\n * @ignorenaming\n */\n Engine.isSupported = function () {\n try {\n var tempcanvas = document.createElement(\"canvas\");\n var gl = tempcanvas.getContext(\"webgl\") || tempcanvas.getContext(\"experimental-webgl\");\n return gl != null && !!window.WebGLRenderingContext;\n }\n catch (e) {\n return false;\n }\n };\n /** Use this array to turn off some WebGL2 features on known buggy browsers version */\n Engine.ExceptionList = [\n { key: \"Chrome/63.0\", capture: \"63\\\\.0\\\\.3239\\\\.(\\\\d+)\", captureConstraint: 108, targets: [\"uniformBuffer\"] },\n { key: \"Firefox/58\", capture: null, captureConstraint: null, targets: [\"uniformBuffer\"] },\n { key: \"Firefox/59\", capture: null, captureConstraint: null, targets: [\"uniformBuffer\"] },\n { key: \"Macintosh\", capture: null, captureConstraint: null, targets: [\"textureBindingOptimization\"] },\n { key: \"iPhone\", capture: null, captureConstraint: null, targets: [\"textureBindingOptimization\"] },\n { key: \"iPad\", capture: null, captureConstraint: null, targets: [\"textureBindingOptimization\"] }\n ];\n /** Gets the list of created engines */\n Engine.Instances = new Array();\n /**\n * Hidden\n */\n Engine._TextureLoaders = [];\n // Const statics\n /** Defines that alpha blending is disabled */\n Engine.ALPHA_DISABLE = 0;\n /** Defines that alpha blending to SRC ALPHA * SRC + DEST */\n Engine.ALPHA_ADD = 1;\n /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */\n Engine.ALPHA_COMBINE = 2;\n /** Defines that alpha blending to DEST - SRC * DEST */\n Engine.ALPHA_SUBTRACT = 3;\n /** Defines that alpha blending to SRC * DEST */\n Engine.ALPHA_MULTIPLY = 4;\n /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */\n Engine.ALPHA_MAXIMIZED = 5;\n /** Defines that alpha blending to SRC + DEST */\n Engine.ALPHA_ONEONE = 6;\n /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */\n Engine.ALPHA_PREMULTIPLIED = 7;\n /**\n * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST\n * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA\n */\n Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;\n /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */\n Engine.ALPHA_INTERPOLATE = 9;\n /**\n * Defines that alpha blending to SRC + (1 - SRC) * DEST\n * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA\n */\n Engine.ALPHA_SCREENMODE = 10;\n /** Defines that the ressource is not delayed*/\n Engine.DELAYLOADSTATE_NONE = 0;\n /** Defines that the ressource was successfully delay loaded */\n Engine.DELAYLOADSTATE_LOADED = 1;\n /** Defines that the ressource is currently delay loading */\n Engine.DELAYLOADSTATE_LOADING = 2;\n /** Defines that the ressource is delayed and has not started loading */\n Engine.DELAYLOADSTATE_NOTLOADED = 4;\n // Depht or Stencil test Constants.\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */\n Engine.NEVER = 0x0200;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */\n Engine.ALWAYS = 0x0207;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */\n Engine.LESS = 0x0201;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */\n Engine.EQUAL = 0x0202;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */\n Engine.LEQUAL = 0x0203;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */\n Engine.GREATER = 0x0204;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */\n Engine.GEQUAL = 0x0206;\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */\n Engine.NOTEQUAL = 0x0205;\n // Stencil Actions Constants.\n /** Passed to stencilOperation to specify that stencil value must be kept */\n Engine.KEEP = 0x1E00;\n /** Passed to stencilOperation to specify that stencil value must be replaced */\n Engine.REPLACE = 0x1E01;\n /** Passed to stencilOperation to specify that stencil value must be incremented */\n Engine.INCR = 0x1E02;\n /** Passed to stencilOperation to specify that stencil value must be decremented */\n Engine.DECR = 0x1E03;\n /** Passed to stencilOperation to specify that stencil value must be inverted */\n Engine.INVERT = 0x150A;\n /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */\n Engine.INCR_WRAP = 0x8507;\n /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */\n Engine.DECR_WRAP = 0x8508;\n /** Texture is not repeating outside of 0..1 UVs */\n Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;\n /** Texture is repeating outside of 0..1 UVs */\n Engine.TEXTURE_WRAP_ADDRESSMODE = 1;\n /** Texture is repeating and mirrored */\n Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;\n /** ALPHA */\n Engine.TEXTUREFORMAT_ALPHA = 0;\n /** LUMINANCE */\n Engine.TEXTUREFORMAT_LUMINANCE = 1;\n /** LUMINANCE_ALPHA */\n Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;\n /** RGB */\n Engine.TEXTUREFORMAT_RGB = 4;\n /** RGBA */\n Engine.TEXTUREFORMAT_RGBA = 5;\n /** R */\n Engine.TEXTUREFORMAT_R = 6;\n /** RG */\n Engine.TEXTUREFORMAT_RG = 7;\n /** UNSIGNED_INT */\n Engine.TEXTURETYPE_UNSIGNED_INT = 0;\n /** FLOAT */\n Engine.TEXTURETYPE_FLOAT = 1;\n /** HALF_FLOAT */\n Engine.TEXTURETYPE_HALF_FLOAT = 2;\n /** nearest is mag = nearest and min = nearest and mip = linear */\n Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;\n /** Bilinear is mag = linear and min = linear and mip = nearest */\n Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;\n /** Trilinear is mag = linear and min = linear and mip = linear */\n Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;\n /** nearest is mag = nearest and min = nearest and mip = linear */\n Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;\n /** Bilinear is mag = linear and min = linear and mip = nearest */\n Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;\n /** Trilinear is mag = linear and min = linear and mip = linear */\n Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;\n /** mag = nearest and min = nearest and mip = nearest */\n Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;\n /** mag = nearest and min = linear and mip = nearest */\n Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;\n /** mag = nearest and min = linear and mip = linear */\n Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;\n /** mag = nearest and min = linear and mip = none */\n Engine.TEXTURE_NEAREST_LINEAR = 7;\n /** mag = nearest and min = nearest and mip = none */\n Engine.TEXTURE_NEAREST_NEAREST = 8;\n /** mag = linear and min = nearest and mip = nearest */\n Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;\n /** mag = linear and min = nearest and mip = linear */\n Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;\n /** mag = linear and min = linear and mip = none */\n Engine.TEXTURE_LINEAR_LINEAR = 11;\n /** mag = linear and min = nearest and mip = none */\n Engine.TEXTURE_LINEAR_NEAREST = 12;\n /** Explicit coordinates mode */\n Engine.TEXTURE_EXPLICIT_MODE = 0;\n /** Spherical coordinates mode */\n Engine.TEXTURE_SPHERICAL_MODE = 1;\n /** Planar coordinates mode */\n Engine.TEXTURE_PLANAR_MODE = 2;\n /** Cubic coordinates mode */\n Engine.TEXTURE_CUBIC_MODE = 3;\n /** Projection coordinates mode */\n Engine.TEXTURE_PROJECTION_MODE = 4;\n /** Skybox coordinates mode */\n Engine.TEXTURE_SKYBOX_MODE = 5;\n /** Inverse Cubic coordinates mode */\n Engine.TEXTURE_INVCUBIC_MODE = 6;\n /** Equirectangular coordinates mode */\n Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;\n /** Equirectangular Fixed coordinates mode */\n Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;\n /** Equirectangular Fixed Mirrored coordinates mode */\n Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;\n // Texture rescaling mode\n /** Defines that texture rescaling will use a floor to find the closer power of 2 size */\n Engine.SCALEMODE_FLOOR = 1;\n /** Defines that texture rescaling will look for the nearest power of 2 size */\n Engine.SCALEMODE_NEAREST = 2;\n /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */\n Engine.SCALEMODE_CEILING = 3;\n // Updatable statics so stick with vars here\n /**\n * Gets or sets the epsilon value used by collision engine\n */\n Engine.CollisionsEpsilon = 0.001;\n /**\n * Gets or sets the relative url used to load code if using the engine in non-minified mode\n */\n Engine.CodeRepository = \"src/\";\n /**\n * Gets or sets the relative url used to load shaders if using the engine in non-minified mode\n */\n Engine.ShadersRepository = \"src/Shaders/\";\n return Engine;\n }());\n BABYLON.Engine = Engine;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.engine.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Node is the basic class for all scene objects (Mesh, Light Camera).\n */\n var Node = /** @class */ (function () {\n /**\n * Creates a new Node\n * @param {string} name - the name and id to be given to this node\n * @param {BABYLON.Scene} the scene this node will be added to\n */\n function Node(name, scene) {\n if (scene === void 0) { scene = null; }\n /**\n * Gets or sets a string used to store user defined state for the node\n */\n this.state = \"\";\n /**\n * Gets or sets an object used to store user defined information for the node\n */\n this.metadata = null;\n /**\n * Gets or sets a boolean used to define if the node must be serialized\n */\n this.doNotSerialize = false;\n /** @hidden */\n this._isDisposed = false;\n /**\n * Gets a list of Animations associated with the node\n */\n this.animations = new Array();\n this._ranges = {};\n this._isEnabled = true;\n this._isReady = true;\n /** @hidden */\n this._currentRenderId = -1;\n this._parentRenderId = -1;\n this._childRenderId = -1;\n this._animationPropertiesOverride = null;\n /**\n * An event triggered when the mesh is disposed\n */\n this.onDisposeObservable = new BABYLON.Observable();\n // Behaviors\n this._behaviors = new Array();\n this.name = name;\n this.id = name;\n this._scene = (scene || BABYLON.Engine.LastCreatedScene);\n this.uniqueId = this._scene.getUniqueId();\n this._initCache();\n }\n /**\n * Add a new node constructor\n * @param type defines the type name of the node to construct\n * @param constructorFunc defines the constructor function\n */\n Node.AddNodeConstructor = function (type, constructorFunc) {\n this._NodeConstructors[type] = constructorFunc;\n };\n /**\n * Returns a node constructor based on type name\n * @param type defines the type name\n * @param name defines the new node name\n * @param scene defines the hosting scene\n * @param options defines optional options to transmit to constructors\n * @returns the new constructor or null\n */\n Node.Construct = function (type, name, scene, options) {\n var constructorFunc = this._NodeConstructors[type];\n if (!constructorFunc) {\n return null;\n }\n return constructorFunc(name, scene, options);\n };\n /**\n * Gets a boolean indicating if the node has been disposed\n * @returns true if the node was disposed\n */\n Node.prototype.isDisposed = function () {\n return this._isDisposed;\n };\n Object.defineProperty(Node.prototype, \"parent\", {\n get: function () {\n return this._parentNode;\n },\n /**\n * Gets or sets the parent of the node\n */\n set: function (parent) {\n if (this._parentNode === parent) {\n return;\n }\n // Remove self from list of children of parent\n if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {\n var index = this._parentNode._children.indexOf(this);\n if (index !== -1) {\n this._parentNode._children.splice(index, 1);\n }\n }\n // Store new parent\n this._parentNode = parent;\n // Add as child to new parent\n if (this._parentNode) {\n if (this._parentNode._children === undefined || this._parentNode._children === null) {\n this._parentNode._children = new Array();\n }\n this._parentNode._children.push(this);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Node.prototype, \"animationPropertiesOverride\", {\n /**\n * Gets or sets the animation properties override\n */\n get: function () {\n if (!this._animationPropertiesOverride) {\n return this._scene.animationPropertiesOverride;\n }\n return this._animationPropertiesOverride;\n },\n set: function (value) {\n this._animationPropertiesOverride = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets a string idenfifying the name of the class\n * @returns \"Node\" string\n */\n Node.prototype.getClassName = function () {\n return \"Node\";\n };\n Object.defineProperty(Node.prototype, \"onDispose\", {\n /**\n * Sets a callback that will be raised when the node will be disposed\n */\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the scene of the node\n * @returns a {BABYLON.Scene}\n */\n Node.prototype.getScene = function () {\n return this._scene;\n };\n /**\n * Gets the engine of the node\n * @returns a {BABYLON.Engine}\n */\n Node.prototype.getEngine = function () {\n return this._scene.getEngine();\n };\n /**\n * Attach a behavior to the node\n * @see http://doc.babylonjs.com/features/behaviour\n * @param behavior defines the behavior to attach\n * @returns the current Node\n */\n Node.prototype.addBehavior = function (behavior) {\n var _this = this;\n var index = this._behaviors.indexOf(behavior);\n if (index !== -1) {\n return this;\n }\n behavior.init();\n if (this._scene.isLoading) {\n // We defer the attach when the scene will be loaded\n this._scene.onDataLoadedObservable.addOnce(function () {\n behavior.attach(_this);\n });\n }\n else {\n behavior.attach(this);\n }\n this._behaviors.push(behavior);\n return this;\n };\n /**\n * Remove an attached behavior\n * @see http://doc.babylonjs.com/features/behaviour\n * @param behavior defines the behavior to attach\n * @returns the current Node\n */\n Node.prototype.removeBehavior = function (behavior) {\n var index = this._behaviors.indexOf(behavior);\n if (index === -1) {\n return this;\n }\n this._behaviors[index].detach();\n this._behaviors.splice(index, 1);\n return this;\n };\n Object.defineProperty(Node.prototype, \"behaviors\", {\n /**\n * Gets the list of attached behaviors\n * @see http://doc.babylonjs.com/features/behaviour\n */\n get: function () {\n return this._behaviors;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets an attached behavior by name\n * @param name defines the name of the behavior to look for\n * @see http://doc.babylonjs.com/features/behaviour\n * @returns null if behavior was not found else the requested behavior\n */\n Node.prototype.getBehaviorByName = function (name) {\n for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {\n var behavior = _a[_i];\n if (behavior.name === name) {\n return behavior;\n }\n }\n return null;\n };\n /**\n * Returns the world matrix of the node\n * @returns a matrix containing the node's world matrix\n */\n Node.prototype.getWorldMatrix = function () {\n return BABYLON.Matrix.Identity();\n };\n /** @hidden */\n Node.prototype._getWorldMatrixDeterminant = function () {\n return 1;\n };\n // override it in derived class if you add new variables to the cache\n // and call the parent class method\n /** @hidden */\n Node.prototype._initCache = function () {\n this._cache = {};\n this._cache.parent = undefined;\n };\n /** @hidden */\n Node.prototype.updateCache = function (force) {\n if (!force && this.isSynchronized())\n return;\n this._cache.parent = this.parent;\n this._updateCache();\n };\n // override it in derived class if you add new variables to the cache\n // and call the parent class method if !ignoreParentClass\n /** @hidden */\n Node.prototype._updateCache = function (ignoreParentClass) {\n };\n // override it in derived class if you add new variables to the cache\n /** @hidden */\n Node.prototype._isSynchronized = function () {\n return true;\n };\n /** @hidden */\n Node.prototype._markSyncedWithParent = function () {\n if (this.parent) {\n this._parentRenderId = this.parent._childRenderId;\n }\n };\n /** @hidden */\n Node.prototype.isSynchronizedWithParent = function () {\n if (!this.parent) {\n return true;\n }\n if (this._parentRenderId !== this.parent._childRenderId) {\n return false;\n }\n return this.parent.isSynchronized();\n };\n /** @hidden */\n Node.prototype.isSynchronized = function (updateCache) {\n var check = this.hasNewParent();\n check = check || !this.isSynchronizedWithParent();\n check = check || !this._isSynchronized();\n if (updateCache)\n this.updateCache(true);\n return !check;\n };\n /** @hidden */\n Node.prototype.hasNewParent = function (update) {\n if (this._cache.parent === this.parent)\n return false;\n if (update)\n this._cache.parent = this.parent;\n return true;\n };\n /**\n * Is this node ready to be used/rendered\n * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)\n * @return true if the node is ready\n */\n Node.prototype.isReady = function (completeCheck) {\n if (completeCheck === void 0) { completeCheck = false; }\n return this._isReady;\n };\n /**\n * Is this node enabled?\n * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true\n * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors\n * @return whether this node (and its parent) is enabled\n */\n Node.prototype.isEnabled = function (checkAncestors) {\n if (checkAncestors === void 0) { checkAncestors = true; }\n if (checkAncestors === false) {\n return this._isEnabled;\n }\n if (this._isEnabled === false) {\n return false;\n }\n if (this.parent !== undefined && this.parent !== null) {\n return this.parent.isEnabled(checkAncestors);\n }\n return true;\n };\n /**\n * Set the enabled state of this node\n * @param value defines the new enabled state\n */\n Node.prototype.setEnabled = function (value) {\n this._isEnabled = value;\n };\n /**\n * Is this node a descendant of the given node?\n * The function will iterate up the hierarchy until the ancestor was found or no more parents defined\n * @param ancestor defines the parent node to inspect\n * @returns a boolean indicating if this node is a descendant of the given node\n */\n Node.prototype.isDescendantOf = function (ancestor) {\n if (this.parent) {\n if (this.parent === ancestor) {\n return true;\n }\n return this.parent.isDescendantOf(ancestor);\n }\n return false;\n };\n /** @hidden */\n Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {\n if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }\n if (!this._children) {\n return;\n }\n for (var index = 0; index < this._children.length; index++) {\n var item = this._children[index];\n if (!predicate || predicate(item)) {\n results.push(item);\n }\n if (!directDescendantsOnly) {\n item._getDescendants(results, false, predicate);\n }\n }\n };\n /**\n * Will return all nodes that have this node as ascendant\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @return all children nodes of all types\n */\n Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {\n var results = new Array();\n this._getDescendants(results, directDescendantsOnly, predicate);\n return results;\n };\n /**\n * Get all child-meshes of this node\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @returns an array of {BABYLON.AbstractMesh}\n */\n Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {\n var results = [];\n this._getDescendants(results, directDescendantsOnly, function (node) {\n return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));\n });\n return results;\n };\n /**\n * Get all child-transformNodes of this node\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @returns an array of {BABYLON.TransformNode}\n */\n Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {\n var results = [];\n this._getDescendants(results, directDescendantsOnly, function (node) {\n return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));\n });\n return results;\n };\n /**\n * Get all direct children of this node\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @returns an array of {BABYLON.Node}\n */\n Node.prototype.getChildren = function (predicate) {\n return this.getDescendants(true, predicate);\n };\n /** @hidden */\n Node.prototype._setReady = function (state) {\n if (state === this._isReady) {\n return;\n }\n if (!state) {\n this._isReady = false;\n return;\n }\n if (this.onReady) {\n this.onReady(this);\n }\n this._isReady = true;\n };\n /**\n * Get an animation by name\n * @param name defines the name of the animation to look for\n * @returns null if not found else the requested animation\n */\n Node.prototype.getAnimationByName = function (name) {\n for (var i = 0; i < this.animations.length; i++) {\n var animation = this.animations[i];\n if (animation.name === name) {\n return animation;\n }\n }\n return null;\n };\n /**\n * Creates an animation range for this node\n * @param name defines the name of the range\n * @param from defines the starting key\n * @param to defines the end key\n */\n Node.prototype.createAnimationRange = function (name, from, to) {\n // check name not already in use\n if (!this._ranges[name]) {\n this._ranges[name] = new BABYLON.AnimationRange(name, from, to);\n for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {\n if (this.animations[i]) {\n this.animations[i].createRange(name, from, to);\n }\n }\n }\n };\n /**\n * Delete a specific animation range\n * @param name defines the name of the range to delete\n * @param deleteFrames defines if animation frames from the range must be deleted as well\n */\n Node.prototype.deleteAnimationRange = function (name, deleteFrames) {\n if (deleteFrames === void 0) { deleteFrames = true; }\n for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {\n if (this.animations[i]) {\n this.animations[i].deleteRange(name, deleteFrames);\n }\n }\n this._ranges[name] = null; // said much faster than 'delete this._range[name]' \n };\n /**\n * Get an animation range by name\n * @param name defines the name of the animation range to look for\n * @returns null if not found else the requested animation range\n */\n Node.prototype.getAnimationRange = function (name) {\n return this._ranges[name];\n };\n /**\n * Will start the animation sequence\n * @param name defines the range frames for animation sequence\n * @param loop defines if the animation should loop (false by default)\n * @param speedRatio defines the speed factor in which to run the animation (1 by default)\n * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)\n * @returns the object created for this animation. If range does not exist, it will return null\n */\n Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {\n var range = this.getAnimationRange(name);\n if (!range) {\n return null;\n }\n return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);\n };\n /**\n * Serialize animation ranges into a JSON compatible object\n * @returns serialization object\n */\n Node.prototype.serializeAnimationRanges = function () {\n var serializationRanges = [];\n for (var name in this._ranges) {\n var localRange = this._ranges[name];\n if (!localRange) {\n continue;\n }\n var range = {};\n range.name = name;\n range.from = localRange.from;\n range.to = localRange.to;\n serializationRanges.push(range);\n }\n return serializationRanges;\n };\n /**\n * Computes the world matrix of the node\n * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch\n * @returns the world matrix\n */\n Node.prototype.computeWorldMatrix = function (force) {\n return BABYLON.Matrix.Identity();\n };\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n if (!doNotRecurse) {\n var nodes = this.getDescendants(true);\n for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {\n var node = nodes_1[_i];\n node.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n }\n else {\n var transformNodes = this.getChildTransformNodes(true);\n for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {\n var transformNode = transformNodes_1[_a];\n transformNode.parent = null;\n transformNode.computeWorldMatrix(true);\n }\n }\n this.parent = null;\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n // Behaviors\n for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {\n var behavior = _c[_b];\n behavior.detach();\n }\n this._behaviors = [];\n this._isDisposed = true;\n };\n /**\n * Parse animation range data from a serialization object and store them into a given node\n * @param node defines where to store the animation ranges\n * @param parsedNode defines the serialization object to read data from\n * @param scene defines the hosting scene\n */\n Node.ParseAnimationRanges = function (node, parsedNode, scene) {\n if (parsedNode.ranges) {\n for (var index = 0; index < parsedNode.ranges.length; index++) {\n var data = parsedNode.ranges[index];\n node.createAnimationRange(data.name, data.from, data.to);\n }\n }\n };\n Node._NodeConstructors = {};\n __decorate([\n BABYLON.serialize()\n ], Node.prototype, \"name\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Node.prototype, \"id\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Node.prototype, \"uniqueId\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Node.prototype, \"state\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Node.prototype, \"metadata\", void 0);\n return Node;\n }());\n BABYLON.Node = Node;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.node.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var BoundingSphere = /** @class */ (function () {\n /**\n * Creates a new bounding sphere\n * @param min defines the minimum vector (in local space)\n * @param max defines the maximum vector (in local space)\n */\n function BoundingSphere(min, max) {\n this._tempRadiusVector = BABYLON.Vector3.Zero();\n this.reConstruct(min, max);\n }\n /**\n * Recreates the entire bounding sphere from scratch\n * @param min defines the new minimum vector (in local space)\n * @param max defines the new maximum vector (in local space)\n */\n BoundingSphere.prototype.reConstruct = function (min, max) {\n this.minimum = min.clone();\n this.maximum = max.clone();\n var distance = BABYLON.Vector3.Distance(min, max);\n this.center = BABYLON.Vector3.Lerp(min, max, 0.5);\n this.radius = distance * 0.5;\n this.centerWorld = BABYLON.Vector3.Zero();\n this._update(BABYLON.Matrix.Identity());\n };\n /**\n * Scale the current bounding sphere by applying a scale factor\n * @param factor defines the scale factor to apply\n * @returns the current bounding box\n */\n BoundingSphere.prototype.scale = function (factor) {\n var newRadius = this.radius * factor;\n var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);\n var min = this.center.subtract(newRadiusVector);\n var max = this.center.add(newRadiusVector);\n this.reConstruct(min, max);\n return this;\n };\n // Methods\n BoundingSphere.prototype._update = function (world) {\n BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);\n this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;\n };\n BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {\n for (var i = 0; i < 6; i++) {\n if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)\n return false;\n }\n return true;\n };\n BoundingSphere.prototype.intersectsPoint = function (point) {\n var x = this.centerWorld.x - point.x;\n var y = this.centerWorld.y - point.y;\n var z = this.centerWorld.z - point.z;\n var distance = Math.sqrt((x * x) + (y * y) + (z * z));\n if (this.radiusWorld < distance)\n return false;\n return true;\n };\n // Statics\n BoundingSphere.Intersects = function (sphere0, sphere1) {\n var x = sphere0.centerWorld.x - sphere1.centerWorld.x;\n var y = sphere0.centerWorld.y - sphere1.centerWorld.y;\n var z = sphere0.centerWorld.z - sphere1.centerWorld.z;\n var distance = Math.sqrt((x * x) + (y * y) + (z * z));\n if (sphere0.radiusWorld + sphere1.radiusWorld < distance)\n return false;\n return true;\n };\n return BoundingSphere;\n }());\n BABYLON.BoundingSphere = BoundingSphere;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boundingSphere.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var BoundingBox = /** @class */ (function () {\n /**\n * Creates a new bounding box\n * @param min defines the minimum vector (in local space)\n * @param max defines the maximum vector (in local space)\n */\n function BoundingBox(min, max) {\n this.vectorsWorld = new Array();\n this.reConstruct(min, max);\n }\n // Methods\n /**\n * Recreates the entire bounding box from scratch\n * @param min defines the new minimum vector (in local space)\n * @param max defines the new maximum vector (in local space)\n */\n BoundingBox.prototype.reConstruct = function (min, max) {\n this.minimum = min.clone();\n this.maximum = max.clone();\n // Bounding vectors\n this.vectors = new Array();\n this.vectors.push(this.minimum.clone());\n this.vectors.push(this.maximum.clone());\n this.vectors.push(this.minimum.clone());\n this.vectors[2].x = this.maximum.x;\n this.vectors.push(this.minimum.clone());\n this.vectors[3].y = this.maximum.y;\n this.vectors.push(this.minimum.clone());\n this.vectors[4].z = this.maximum.z;\n this.vectors.push(this.maximum.clone());\n this.vectors[5].z = this.minimum.z;\n this.vectors.push(this.maximum.clone());\n this.vectors[6].x = this.minimum.x;\n this.vectors.push(this.maximum.clone());\n this.vectors[7].y = this.minimum.y;\n // OBB\n this.center = this.maximum.add(this.minimum).scale(0.5);\n this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);\n this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n // World\n for (var index = 0; index < this.vectors.length; index++) {\n this.vectorsWorld[index] = BABYLON.Vector3.Zero();\n }\n this.minimumWorld = BABYLON.Vector3.Zero();\n this.maximumWorld = BABYLON.Vector3.Zero();\n this.centerWorld = BABYLON.Vector3.Zero();\n this.extendSizeWorld = BABYLON.Vector3.Zero();\n this._update(this._worldMatrix || BABYLON.Matrix.Identity());\n };\n /**\n * Scale the current bounding box by applying a scale factor\n * @param factor defines the scale factor to apply\n * @returns the current bounding box\n */\n BoundingBox.prototype.scale = function (factor) {\n var diff = this.maximum.subtract(this.minimum);\n var distance = diff.length() * factor;\n diff.normalize();\n var newRadius = diff.scale(distance / 2);\n var min = this.center.subtract(newRadius);\n var max = this.center.add(newRadius);\n this.reConstruct(min, max);\n return this;\n };\n BoundingBox.prototype.getWorldMatrix = function () {\n return this._worldMatrix;\n };\n BoundingBox.prototype.setWorldMatrix = function (matrix) {\n this._worldMatrix.copyFrom(matrix);\n return this;\n };\n BoundingBox.prototype._update = function (world) {\n BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);\n BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);\n for (var index = 0; index < this.vectors.length; index++) {\n var v = this.vectorsWorld[index];\n BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);\n if (v.x < this.minimumWorld.x)\n this.minimumWorld.x = v.x;\n if (v.y < this.minimumWorld.y)\n this.minimumWorld.y = v.y;\n if (v.z < this.minimumWorld.z)\n this.minimumWorld.z = v.z;\n if (v.x > this.maximumWorld.x)\n this.maximumWorld.x = v.x;\n if (v.y > this.maximumWorld.y)\n this.maximumWorld.y = v.y;\n if (v.z > this.maximumWorld.z)\n this.maximumWorld.z = v.z;\n }\n // Extend\n this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);\n this.extendSizeWorld.scaleInPlace(0.5);\n // OBB\n this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);\n this.centerWorld.scaleInPlace(0.5);\n BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);\n BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);\n BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);\n this._worldMatrix = world;\n };\n BoundingBox.prototype.isInFrustum = function (frustumPlanes) {\n return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);\n };\n BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {\n return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);\n };\n BoundingBox.prototype.intersectsPoint = function (point) {\n var delta = -BABYLON.Epsilon;\n if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)\n return false;\n if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)\n return false;\n if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)\n return false;\n return true;\n };\n BoundingBox.prototype.intersectsSphere = function (sphere) {\n return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);\n };\n BoundingBox.prototype.intersectsMinMax = function (min, max) {\n if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)\n return false;\n if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)\n return false;\n if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)\n return false;\n return true;\n };\n // Statics\n BoundingBox.Intersects = function (box0, box1) {\n if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)\n return false;\n if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)\n return false;\n if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)\n return false;\n return true;\n };\n BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {\n var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);\n var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);\n return (num <= (sphereRadius * sphereRadius));\n };\n BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {\n for (var p = 0; p < 6; p++) {\n for (var i = 0; i < 8; i++) {\n if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {\n return false;\n }\n }\n }\n return true;\n };\n BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {\n for (var p = 0; p < 6; p++) {\n var inCount = 8;\n for (var i = 0; i < 8; i++) {\n if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {\n --inCount;\n }\n else {\n break;\n }\n }\n if (inCount === 0)\n return false;\n }\n return true;\n };\n return BoundingBox;\n }());\n BABYLON.BoundingBox = BoundingBox;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boundingBox.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var computeBoxExtents = function (axis, box) {\n var p = BABYLON.Vector3.Dot(box.centerWorld, axis);\n var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;\n var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;\n var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;\n var r = r0 + r1 + r2;\n return {\n min: p - r,\n max: p + r\n };\n };\n var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };\n var axisOverlap = function (axis, box0, box1) {\n var result0 = computeBoxExtents(axis, box0);\n var result1 = computeBoxExtents(axis, box1);\n return extentsOverlap(result0.min, result0.max, result1.min, result1.max);\n };\n var BoundingInfo = /** @class */ (function () {\n function BoundingInfo(minimum, maximum) {\n this.minimum = minimum;\n this.maximum = maximum;\n this._isLocked = false;\n this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);\n this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);\n }\n Object.defineProperty(BoundingInfo.prototype, \"isLocked\", {\n get: function () {\n return this._isLocked;\n },\n set: function (value) {\n this._isLocked = value;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n BoundingInfo.prototype.update = function (world) {\n if (this._isLocked) {\n return;\n }\n this.boundingBox._update(world);\n this.boundingSphere._update(world);\n };\n /**\n * Recreate the bounding info to be centered around a specific point given a specific extend.\n * @param center New center of the bounding info\n * @param extend New extend of the bounding info\n */\n BoundingInfo.prototype.centerOn = function (center, extend) {\n this.minimum = center.subtract(extend);\n this.maximum = center.add(extend);\n this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);\n this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);\n return this;\n };\n /**\n * Scale the current bounding info by applying a scale factor\n * @param factor defines the scale factor to apply\n * @returns the current bounding info\n */\n BoundingInfo.prototype.scale = function (factor) {\n this.boundingBox.scale(factor);\n this.boundingSphere.scale(factor);\n return this;\n };\n BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {\n if (!this.boundingSphere.isInFrustum(frustumPlanes))\n return false;\n return this.boundingBox.isInFrustum(frustumPlanes);\n };\n Object.defineProperty(BoundingInfo.prototype, \"diagonalLength\", {\n /**\n * Gets the world distance between the min and max points of the bounding box\n */\n get: function () {\n var boundingBox = this.boundingBox;\n var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);\n return size.length();\n },\n enumerable: true,\n configurable: true\n });\n BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {\n return this.boundingBox.isCompletelyInFrustum(frustumPlanes);\n };\n BoundingInfo.prototype._checkCollision = function (collider) {\n return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);\n };\n BoundingInfo.prototype.intersectsPoint = function (point) {\n if (!this.boundingSphere.centerWorld) {\n return false;\n }\n if (!this.boundingSphere.intersectsPoint(point)) {\n return false;\n }\n if (!this.boundingBox.intersectsPoint(point)) {\n return false;\n }\n return true;\n };\n BoundingInfo.prototype.intersects = function (boundingInfo, precise) {\n if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {\n return false;\n }\n if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {\n return false;\n }\n if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {\n return false;\n }\n if (!precise) {\n return true;\n }\n var box0 = this.boundingBox;\n var box1 = boundingInfo.boundingBox;\n if (!axisOverlap(box0.directions[0], box0, box1))\n return false;\n if (!axisOverlap(box0.directions[1], box0, box1))\n return false;\n if (!axisOverlap(box0.directions[2], box0, box1))\n return false;\n if (!axisOverlap(box1.directions[0], box0, box1))\n return false;\n if (!axisOverlap(box1.directions[1], box0, box1))\n return false;\n if (!axisOverlap(box1.directions[2], box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))\n return false;\n if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))\n return false;\n return true;\n };\n return BoundingInfo;\n }());\n BABYLON.BoundingInfo = BoundingInfo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boundingInfo.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var TransformNode = /** @class */ (function (_super) {\n __extends(TransformNode, _super);\n function TransformNode(name, scene, isPure) {\n if (scene === void 0) { scene = null; }\n if (isPure === void 0) { isPure = true; }\n var _this = _super.call(this, name, scene) || this;\n _this._forward = new BABYLON.Vector3(0, 0, 1);\n _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);\n _this._up = new BABYLON.Vector3(0, 1, 0);\n _this._right = new BABYLON.Vector3(1, 0, 0);\n _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);\n // Properties\n _this._rotation = BABYLON.Vector3.Zero();\n _this._scaling = BABYLON.Vector3.One();\n _this._isDirty = false;\n /**\n * Set the billboard mode. Default is 0.\n *\n * | Value | Type | Description |\n * | --- | --- | --- |\n * | 0 | BILLBOARDMODE_NONE | |\n * | 1 | BILLBOARDMODE_X | |\n * | 2 | BILLBOARDMODE_Y | |\n * | 4 | BILLBOARDMODE_Z | |\n * | 7 | BILLBOARDMODE_ALL | |\n *\n */\n _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;\n _this.scalingDeterminant = 1;\n _this.infiniteDistance = false;\n /**\n * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.\n * By default the system will update normals to compensate\n */\n _this.ignoreNonUniformScaling = false;\n _this.position = BABYLON.Vector3.Zero();\n _this._localWorld = BABYLON.Matrix.Zero();\n _this._worldMatrix = BABYLON.Matrix.Zero();\n _this._worldMatrixDeterminant = 0;\n _this._absolutePosition = BABYLON.Vector3.Zero();\n _this._pivotMatrix = BABYLON.Matrix.Identity();\n _this._postMultiplyPivotMatrix = false;\n _this._isWorldMatrixFrozen = false;\n /**\n * An event triggered after the world matrix is updated\n */\n _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();\n _this._nonUniformScaling = false;\n if (isPure) {\n _this.getScene().addTransformNode(_this);\n }\n return _this;\n }\n /**\n * Gets a string idenfifying the name of the class\n * @returns \"TransformNode\" string\n */\n TransformNode.prototype.getClassName = function () {\n return \"TransformNode\";\n };\n Object.defineProperty(TransformNode.prototype, \"rotation\", {\n /**\n * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.\n * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!\n * Default : (0.0, 0.0, 0.0)\n */\n get: function () {\n return this._rotation;\n },\n set: function (newRotation) {\n this._rotation = newRotation;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TransformNode.prototype, \"scaling\", {\n /**\n * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.\n * Default : (1.0, 1.0, 1.0)\n */\n get: function () {\n return this._scaling;\n },\n /**\n * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.\n * Default : (1.0, 1.0, 1.0)\n */\n set: function (newScaling) {\n this._scaling = newScaling;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TransformNode.prototype, \"rotationQuaternion\", {\n /**\n * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.\n * It's null by default.\n * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\\ is then ignored and set to (0.0, 0.0, 0.0)\n */\n get: function () {\n return this._rotationQuaternion;\n },\n set: function (quaternion) {\n this._rotationQuaternion = quaternion;\n //reset the rotation vector. \n if (quaternion && this.rotation.length()) {\n this.rotation.copyFromFloats(0.0, 0.0, 0.0);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TransformNode.prototype, \"forward\", {\n /**\n * The forward direction of that transform in world space.\n */\n get: function () {\n return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TransformNode.prototype, \"up\", {\n /**\n * The up direction of that transform in world space.\n */\n get: function () {\n return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TransformNode.prototype, \"right\", {\n /**\n * The right direction of that transform in world space.\n */\n get: function () {\n return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the latest update of the World matrix\n * Returns a Matrix.\n */\n TransformNode.prototype.getWorldMatrix = function () {\n if (this._currentRenderId !== this.getScene().getRenderId()) {\n this.computeWorldMatrix();\n }\n return this._worldMatrix;\n };\n /** @hidden */\n TransformNode.prototype._getWorldMatrixDeterminant = function () {\n return this._worldMatrixDeterminant;\n };\n Object.defineProperty(TransformNode.prototype, \"worldMatrixFromCache\", {\n /**\n * Returns directly the latest state of the mesh World matrix.\n * A Matrix is returned.\n */\n get: function () {\n return this._worldMatrix;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Copies the paramater passed Matrix into the mesh Pose matrix.\n * Returns the TransformNode.\n */\n TransformNode.prototype.updatePoseMatrix = function (matrix) {\n this._poseMatrix.copyFrom(matrix);\n return this;\n };\n /**\n * Returns the mesh Pose matrix.\n * Returned object : Matrix\n */\n TransformNode.prototype.getPoseMatrix = function () {\n return this._poseMatrix;\n };\n TransformNode.prototype._isSynchronized = function () {\n if (this._isDirty) {\n return false;\n }\n if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)\n return false;\n if (this._cache.pivotMatrixUpdated) {\n return false;\n }\n if (this.infiniteDistance) {\n return false;\n }\n if (!this._cache.position.equals(this.position))\n return false;\n if (this.rotationQuaternion) {\n if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))\n return false;\n }\n if (!this._cache.rotation.equals(this.rotation))\n return false;\n if (!this._cache.scaling.equals(this.scaling))\n return false;\n return true;\n };\n TransformNode.prototype._initCache = function () {\n _super.prototype._initCache.call(this);\n this._cache.localMatrixUpdated = false;\n this._cache.position = BABYLON.Vector3.Zero();\n this._cache.scaling = BABYLON.Vector3.Zero();\n this._cache.rotation = BABYLON.Vector3.Zero();\n this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);\n this._cache.billboardMode = -1;\n };\n TransformNode.prototype.markAsDirty = function (property) {\n if (property === \"rotation\") {\n this.rotationQuaternion = null;\n }\n this._currentRenderId = Number.MAX_VALUE;\n this._isDirty = true;\n return this;\n };\n Object.defineProperty(TransformNode.prototype, \"absolutePosition\", {\n /**\n * Returns the current mesh absolute position.\n * Retuns a Vector3.\n */\n get: function () {\n return this._absolutePosition;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Sets a new matrix to apply before all other transformation\n * @param matrix defines the transform matrix\n * @returns the current TransformNode\n */\n TransformNode.prototype.setPreTransformMatrix = function (matrix) {\n return this.setPivotMatrix(matrix, false);\n };\n /**\n * Sets a new pivot matrix to the current node\n * @param matrix defines the new pivot matrix to use\n * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect\n * @returns the current TransformNode\n */\n TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {\n if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }\n this._pivotMatrix = matrix.clone();\n this._cache.pivotMatrixUpdated = true;\n this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;\n if (this._postMultiplyPivotMatrix) {\n if (!this._pivotMatrixInverse) {\n this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);\n }\n else {\n this._pivotMatrix.invertToRef(this._pivotMatrixInverse);\n }\n }\n return this;\n };\n /**\n * Returns the mesh pivot matrix.\n * Default : Identity.\n * A Matrix is returned.\n */\n TransformNode.prototype.getPivotMatrix = function () {\n return this._pivotMatrix;\n };\n /**\n * Prevents the World matrix to be computed any longer.\n * Returns the TransformNode.\n */\n TransformNode.prototype.freezeWorldMatrix = function () {\n this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily\n this.computeWorldMatrix(true);\n this._isWorldMatrixFrozen = true;\n return this;\n };\n /**\n * Allows back the World matrix computation.\n * Returns the TransformNode.\n */\n TransformNode.prototype.unfreezeWorldMatrix = function () {\n this._isWorldMatrixFrozen = false;\n this.computeWorldMatrix(true);\n return this;\n };\n Object.defineProperty(TransformNode.prototype, \"isWorldMatrixFrozen\", {\n /**\n * True if the World matrix has been frozen.\n * Returns a boolean.\n */\n get: function () {\n return this._isWorldMatrixFrozen;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Retuns the mesh absolute position in the World.\n * Returns a Vector3.\n */\n TransformNode.prototype.getAbsolutePosition = function () {\n this.computeWorldMatrix();\n return this._absolutePosition;\n };\n /**\n * Sets the mesh absolute position in the World from a Vector3 or an Array(3).\n * Returns the TransformNode.\n */\n TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {\n if (!absolutePosition) {\n return this;\n }\n var absolutePositionX;\n var absolutePositionY;\n var absolutePositionZ;\n if (absolutePosition.x === undefined) {\n if (arguments.length < 3) {\n return this;\n }\n absolutePositionX = arguments[0];\n absolutePositionY = arguments[1];\n absolutePositionZ = arguments[2];\n }\n else {\n absolutePositionX = absolutePosition.x;\n absolutePositionY = absolutePosition.y;\n absolutePositionZ = absolutePosition.z;\n }\n if (this.parent) {\n var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();\n invertParentWorldMatrix.invert();\n var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);\n this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);\n }\n else {\n this.position.x = absolutePositionX;\n this.position.y = absolutePositionY;\n this.position.z = absolutePositionZ;\n }\n return this;\n };\n /**\n * Sets the mesh position in its local space.\n * Returns the TransformNode.\n */\n TransformNode.prototype.setPositionWithLocalVector = function (vector3) {\n this.computeWorldMatrix();\n this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);\n return this;\n };\n /**\n * Returns the mesh position in the local space from the current World matrix values.\n * Returns a new Vector3.\n */\n TransformNode.prototype.getPositionExpressedInLocalSpace = function () {\n this.computeWorldMatrix();\n var invLocalWorldMatrix = this._localWorld.clone();\n invLocalWorldMatrix.invert();\n return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);\n };\n /**\n * Translates the mesh along the passed Vector3 in its local space.\n * Returns the TransformNode.\n */\n TransformNode.prototype.locallyTranslate = function (vector3) {\n this.computeWorldMatrix(true);\n this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);\n return this;\n };\n /**\n * Orients a mesh towards a target point. Mesh must be drawn facing user.\n * @param targetPoint the position (must be in same space as current mesh) to look at\n * @param yawCor optional yaw (y-axis) correction in radians\n * @param pitchCor optional pitch (x-axis) correction in radians\n * @param rollCor optional roll (z-axis) correction in radians\n * @param space the choosen space of the target\n * @returns the TransformNode.\n */\n TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {\n if (yawCor === void 0) { yawCor = 0; }\n if (pitchCor === void 0) { pitchCor = 0; }\n if (rollCor === void 0) { rollCor = 0; }\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n var dv = TransformNode._lookAtVectorCache;\n var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();\n targetPoint.subtractToRef(pos, dv);\n var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;\n var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);\n var pitch = Math.atan2(dv.y, len);\n if (this.rotationQuaternion) {\n BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);\n }\n else {\n this.rotation.x = pitch + pitchCor;\n this.rotation.y = yaw + yawCor;\n this.rotation.z = rollCor;\n }\n return this;\n };\n /**\n * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.\n * This Vector3 is expressed in the World space.\n */\n TransformNode.prototype.getDirection = function (localAxis) {\n var result = BABYLON.Vector3.Zero();\n this.getDirectionToRef(localAxis, result);\n return result;\n };\n /**\n * Sets the Vector3 \"result\" as the rotated Vector3 \"localAxis\" in the same rotation than the mesh.\n * localAxis is expressed in the mesh local space.\n * result is computed in the Wordl space from the mesh World matrix.\n * Returns the TransformNode.\n */\n TransformNode.prototype.getDirectionToRef = function (localAxis, result) {\n BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);\n return this;\n };\n /**\n * Sets a new pivot point to the current node\n * @param point defines the new pivot point to use\n * @param space defines if the point is in world or local space (local by default)\n * @returns the current TransformNode\n */\n TransformNode.prototype.setPivotPoint = function (point, space) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (this.getScene().getRenderId() == 0) {\n this.computeWorldMatrix(true);\n }\n var wm = this.getWorldMatrix();\n if (space == BABYLON.Space.WORLD) {\n var tmat = BABYLON.Tmp.Matrix[0];\n wm.invertToRef(tmat);\n point = BABYLON.Vector3.TransformCoordinates(point, tmat);\n }\n return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);\n };\n /**\n * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.\n */\n TransformNode.prototype.getPivotPoint = function () {\n var point = BABYLON.Vector3.Zero();\n this.getPivotPointToRef(point);\n return point;\n };\n /**\n * Sets the passed Vector3 \"result\" with the coordinates of the mesh pivot point in the local space.\n * Returns the TransformNode.\n */\n TransformNode.prototype.getPivotPointToRef = function (result) {\n result.x = -this._pivotMatrix.m[12];\n result.y = -this._pivotMatrix.m[13];\n result.z = -this._pivotMatrix.m[14];\n return this;\n };\n /**\n * Returns a new Vector3 set with the mesh pivot point World coordinates.\n */\n TransformNode.prototype.getAbsolutePivotPoint = function () {\n var point = BABYLON.Vector3.Zero();\n this.getAbsolutePivotPointToRef(point);\n return point;\n };\n /**\n * Sets the Vector3 \"result\" coordinates with the mesh pivot point World coordinates.\n * Returns the TransformNode.\n */\n TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {\n result.x = this._pivotMatrix.m[12];\n result.y = this._pivotMatrix.m[13];\n result.z = this._pivotMatrix.m[14];\n this.getPivotPointToRef(result);\n BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);\n return this;\n };\n /**\n * Defines the passed node as the parent of the current node.\n * The node will remain exactly where it is and its position / rotation will be updated accordingly\n * Returns the TransformNode.\n */\n TransformNode.prototype.setParent = function (node) {\n if (!node && !this.parent) {\n return this;\n }\n if (!node) {\n var rotation = BABYLON.Tmp.Quaternion[0];\n var position = BABYLON.Tmp.Vector3[0];\n var scale = BABYLON.Tmp.Vector3[1];\n if (this.parent && this.parent.computeWorldMatrix) {\n this.parent.computeWorldMatrix(true);\n }\n this.computeWorldMatrix(true);\n this.getWorldMatrix().decompose(scale, rotation, position);\n if (this.rotationQuaternion) {\n this.rotationQuaternion.copyFrom(rotation);\n }\n else {\n rotation.toEulerAnglesToRef(this.rotation);\n }\n this.scaling.x = scale.x;\n this.scaling.y = scale.y;\n this.scaling.z = scale.z;\n this.position.x = position.x;\n this.position.y = position.y;\n this.position.z = position.z;\n }\n else {\n var rotation = BABYLON.Tmp.Quaternion[0];\n var position = BABYLON.Tmp.Vector3[0];\n var scale = BABYLON.Tmp.Vector3[1];\n var diffMatrix = BABYLON.Tmp.Matrix[0];\n var invParentMatrix = BABYLON.Tmp.Matrix[1];\n this.computeWorldMatrix(true);\n node.computeWorldMatrix(true);\n node.getWorldMatrix().invertToRef(invParentMatrix);\n this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);\n diffMatrix.decompose(scale, rotation, position);\n if (this.rotationQuaternion) {\n this.rotationQuaternion.copyFrom(rotation);\n }\n else {\n rotation.toEulerAnglesToRef(this.rotation);\n }\n this.position.x = position.x;\n this.position.y = position.y;\n this.position.z = position.z;\n this.scaling.x = scale.x;\n this.scaling.y = scale.y;\n this.scaling.z = scale.z;\n }\n this.parent = node;\n return this;\n };\n Object.defineProperty(TransformNode.prototype, \"nonUniformScaling\", {\n get: function () {\n return this._nonUniformScaling;\n },\n enumerable: true,\n configurable: true\n });\n TransformNode.prototype._updateNonUniformScalingState = function (value) {\n if (this._nonUniformScaling === value) {\n return false;\n }\n this._nonUniformScaling = value;\n return true;\n };\n /**\n * Attach the current TransformNode to another TransformNode associated with a bone\n * @param bone Bone affecting the TransformNode\n * @param affectedTransformNode TransformNode associated with the bone\n */\n TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {\n this._transformToBoneReferal = affectedTransformNode;\n this.parent = bone;\n if (bone.getWorldMatrix().determinant() < 0) {\n this.scalingDeterminant *= -1;\n }\n return this;\n };\n TransformNode.prototype.detachFromBone = function () {\n if (!this.parent) {\n return this;\n }\n if (this.parent.getWorldMatrix().determinant() < 0) {\n this.scalingDeterminant *= -1;\n }\n this._transformToBoneReferal = null;\n this.parent = null;\n return this;\n };\n /**\n * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.\n * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.\n * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.\n * The passed axis is also normalized.\n * Returns the TransformNode.\n */\n TransformNode.prototype.rotate = function (axis, amount, space) {\n axis.normalize();\n if (!this.rotationQuaternion) {\n this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);\n this.rotation = BABYLON.Vector3.Zero();\n }\n var rotationQuaternion;\n if (!space || space === BABYLON.Space.LOCAL) {\n rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);\n this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);\n }\n else {\n if (this.parent) {\n var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();\n invertParentWorldMatrix.invert();\n axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);\n }\n rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);\n rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n }\n return this;\n };\n /**\n * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.\n * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.\n * The passed axis is also normalized.\n * Returns the TransformNode.\n * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm\n */\n TransformNode.prototype.rotateAround = function (point, axis, amount) {\n axis.normalize();\n if (!this.rotationQuaternion) {\n this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);\n this.rotation.copyFromFloats(0, 0, 0);\n }\n point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);\n BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);\n BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);\n BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);\n BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);\n BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);\n BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);\n this.position.addInPlace(BABYLON.Tmp.Vector3[1]);\n BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n return this;\n };\n /**\n * Translates the mesh along the axis vector for the passed distance in the given space.\n * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.\n * Returns the TransformNode.\n */\n TransformNode.prototype.translate = function (axis, distance, space) {\n var displacementVector = axis.scale(distance);\n if (!space || space === BABYLON.Space.LOCAL) {\n var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);\n this.setPositionWithLocalVector(tempV3);\n }\n else {\n this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));\n }\n return this;\n };\n /**\n * Adds a rotation step to the mesh current rotation.\n * x, y, z are Euler angles expressed in radians.\n * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.\n * This means this rotation is made in the mesh local space only.\n * It's useful to set a custom rotation order different from the BJS standard one YXZ.\n * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.\n * ```javascript\n * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);\n * ```\n * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.\n * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.\n * Returns the TransformNode.\n */\n TransformNode.prototype.addRotation = function (x, y, z) {\n var rotationQuaternion;\n if (this.rotationQuaternion) {\n rotationQuaternion = this.rotationQuaternion;\n }\n else {\n rotationQuaternion = BABYLON.Tmp.Quaternion[1];\n BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);\n }\n var accumulation = BABYLON.Tmp.Quaternion[0];\n BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);\n rotationQuaternion.multiplyInPlace(accumulation);\n if (!this.rotationQuaternion) {\n rotationQuaternion.toEulerAnglesToRef(this.rotation);\n }\n return this;\n };\n /**\n * Computes the mesh World matrix and returns it.\n * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.\n * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.\n * If the parameter `force`is set to `true`, the actual computation is done.\n * Returns the mesh World Matrix.\n */\n TransformNode.prototype.computeWorldMatrix = function (force) {\n if (this._isWorldMatrixFrozen) {\n return this._worldMatrix;\n }\n if (!force && this.isSynchronized(true)) {\n this._currentRenderId = this.getScene().getRenderId();\n return this._worldMatrix;\n }\n this._cache.position.copyFrom(this.position);\n this._cache.scaling.copyFrom(this.scaling);\n this._cache.pivotMatrixUpdated = false;\n this._cache.billboardMode = this.billboardMode;\n this._currentRenderId = this.getScene().getRenderId();\n this._childRenderId = this.getScene().getRenderId();\n this._isDirty = false;\n // Scaling\n BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);\n // Rotation\n //rotate, if quaternion is set and rotation was used\n if (this.rotationQuaternion) {\n var len = this.rotation.length();\n if (len) {\n this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));\n this.rotation.copyFromFloats(0, 0, 0);\n }\n }\n if (this.rotationQuaternion) {\n this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);\n this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);\n }\n else {\n BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);\n this._cache.rotation.copyFrom(this.rotation);\n }\n // Translation\n var camera = this.getScene().activeCamera;\n if (this.infiniteDistance && !this.parent && camera) {\n var cameraWorldMatrix = camera.getWorldMatrix();\n var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);\n BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);\n }\n else {\n BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);\n }\n // Composing transformations\n this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);\n BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);\n // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)\n if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {\n // Need to decompose each rotation here\n var currentPosition = BABYLON.Tmp.Vector3[3];\n if (this.parent && this.parent.getWorldMatrix) {\n if (this._transformToBoneReferal) {\n this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);\n BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);\n }\n else {\n BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);\n }\n }\n else {\n currentPosition.copyFrom(this.position);\n }\n currentPosition.subtractInPlace(camera.globalPosition);\n var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {\n finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);\n }\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {\n finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);\n }\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {\n finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);\n }\n BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);\n }\n else {\n BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());\n BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);\n BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);\n }\n BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);\n BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);\n }\n // Post multiply inverse of pivotMatrix\n if (this._postMultiplyPivotMatrix) {\n BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);\n }\n // Local world\n BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);\n // Parent\n if (this.parent && this.parent.getWorldMatrix) {\n if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {\n if (this._transformToBoneReferal) {\n this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);\n BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);\n }\n else {\n BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());\n }\n this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);\n BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);\n this._worldMatrix.copyFrom(this._localWorld);\n this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);\n }\n else {\n if (this._transformToBoneReferal) {\n this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);\n BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);\n }\n else {\n this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);\n }\n }\n this._markSyncedWithParent();\n }\n else {\n this._worldMatrix.copyFrom(this._localWorld);\n }\n // Normal matrix\n if (!this.ignoreNonUniformScaling) {\n if (this.scaling.isNonUniform) {\n this._updateNonUniformScalingState(true);\n }\n else if (this.parent && this.parent._nonUniformScaling) {\n this._updateNonUniformScalingState(this.parent._nonUniformScaling);\n }\n else {\n this._updateNonUniformScalingState(false);\n }\n }\n else {\n this._updateNonUniformScalingState(false);\n }\n this._afterComputeWorldMatrix();\n // Absolute position\n this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);\n // Callbacks\n this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);\n if (!this._poseMatrix) {\n this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);\n }\n // Cache the determinant\n this._worldMatrixDeterminant = this._worldMatrix.determinant();\n return this._worldMatrix;\n };\n TransformNode.prototype._afterComputeWorldMatrix = function () {\n };\n /**\n * If you'd like to be called back after the mesh position, rotation or scaling has been updated.\n * @param func: callback function to add\n *\n * Returns the TransformNode.\n */\n TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {\n this.onAfterWorldMatrixUpdateObservable.add(func);\n return this;\n };\n /**\n * Removes a registered callback function.\n * Returns the TransformNode.\n */\n TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {\n this.onAfterWorldMatrixUpdateObservable.removeCallback(func);\n return this;\n };\n /**\n * Clone the current transform node\n * Returns the new transform node\n * @param name Name of the new clone\n * @param newParent New parent for the clone\n * @param doNotCloneChildren Do not clone children hierarchy\n */\n TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {\n var _this = this;\n var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);\n result.name = name;\n result.id = name;\n if (newParent) {\n result.parent = newParent;\n }\n if (!doNotCloneChildren) {\n // Children\n var directDescendants = this.getDescendants(true);\n for (var index = 0; index < directDescendants.length; index++) {\n var child = directDescendants[index];\n if (child.clone) {\n child.clone(name + \".\" + child.name, result);\n }\n }\n }\n return result;\n };\n TransformNode.prototype.serialize = function (currentSerializationObject) {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);\n serializationObject.type = this.getClassName();\n // Parent\n if (this.parent) {\n serializationObject.parentId = this.parent.id;\n }\n if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {\n serializationObject.tags = BABYLON.Tags.GetTags(this);\n }\n serializationObject.localMatrix = this.getPivotMatrix().asArray();\n serializationObject.isEnabled = this.isEnabled();\n // Parent\n if (this.parent) {\n serializationObject.parentId = this.parent.id;\n }\n return serializationObject;\n };\n // Statics\n /**\n * Returns a new TransformNode object parsed from the source provided.\n * The parameter `parsedMesh` is the source.\n * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with\n */\n TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {\n var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);\n }\n if (parsedTransformNode.localMatrix) {\n transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));\n }\n else if (parsedTransformNode.pivotMatrix) {\n transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));\n }\n transformNode.setEnabled(parsedTransformNode.isEnabled);\n // Parent\n if (parsedTransformNode.parentId) {\n transformNode._waitingParentId = parsedTransformNode.parentId;\n }\n return transformNode;\n };\n /**\n * Releases resources associated with this transform node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from scene\n this.getScene().removeTransformNode(this);\n this.onAfterWorldMatrixUpdateObservable.clear();\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n // Statics\n TransformNode.BILLBOARDMODE_NONE = 0;\n TransformNode.BILLBOARDMODE_X = 1;\n TransformNode.BILLBOARDMODE_Y = 2;\n TransformNode.BILLBOARDMODE_Z = 4;\n TransformNode.BILLBOARDMODE_ALL = 7;\n TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);\n TransformNode._rotationAxisCache = new BABYLON.Quaternion();\n __decorate([\n BABYLON.serializeAsVector3()\n ], TransformNode.prototype, \"_rotation\", void 0);\n __decorate([\n BABYLON.serializeAsQuaternion()\n ], TransformNode.prototype, \"_rotationQuaternion\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], TransformNode.prototype, \"_scaling\", void 0);\n __decorate([\n BABYLON.serialize()\n ], TransformNode.prototype, \"billboardMode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], TransformNode.prototype, \"scalingDeterminant\", void 0);\n __decorate([\n BABYLON.serialize()\n ], TransformNode.prototype, \"infiniteDistance\", void 0);\n __decorate([\n BABYLON.serialize()\n ], TransformNode.prototype, \"ignoreNonUniformScaling\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], TransformNode.prototype, \"position\", void 0);\n return TransformNode;\n }(BABYLON.Node));\n BABYLON.TransformNode = TransformNode;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.transformNode.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to store all common mesh properties\n */\n var AbstractMesh = /** @class */ (function (_super) {\n __extends(AbstractMesh, _super);\n // Constructor\n /**\n * Creates a new AbstractMesh\n * @param name defines the name of the mesh\n * @param scene defines the hosting scene\n */\n function AbstractMesh(name, scene) {\n if (scene === void 0) { scene = null; }\n var _this = _super.call(this, name, scene, false) || this;\n _this._facetNb = 0; // facet number\n _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space \n _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box\n _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?\n _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation\n _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data\n _this._subDiv = {\n max: 1,\n X: 1,\n Y: 1,\n Z: 1\n };\n _this._facetDepthSort = false; // is the facet depth sort to be computed\n _this._facetDepthSortEnabled = false; // is the facet depth sort initialized\n // Events\n /**\n * An event triggered when this mesh collides with another one\n */\n _this.onCollideObservable = new BABYLON.Observable();\n /**\n * An event triggered when the collision's position changes\n */\n _this.onCollisionPositionChangeObservable = new BABYLON.Observable();\n /**\n * An event triggered when material is changed\n */\n _this.onMaterialChangedObservable = new BABYLON.Observable();\n // Properties\n /**\n * Gets or sets the orientation for POV movement & rotation\n */\n _this.definedFacingForward = true;\n /**\n * This property determines the type of occlusion query algorithm to run in WebGl, you can use:\n * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.\n * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.\n * @see http://doc.babylonjs.com/features/occlusionquery\n */\n _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;\n /**\n * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:\n * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.\n * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.\n * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.\n * @see http://doc.babylonjs.com/features/occlusionquery\n */\n _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;\n /**\n * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.\n * The default value is -1 which means don't break the query and wait till the result\n * @see http://doc.babylonjs.com/features/occlusionquery\n */\n _this.occlusionRetryCount = -1;\n /** @hidden */\n _this._occlusionInternalRetryCounter = 0;\n /** @hidden */\n _this._isOccluded = false;\n /** @hidden */\n _this._isOcclusionQueryInProgress = false;\n _this._visibility = 1.0;\n /** Gets or sets the alpha index used to sort transparent meshes\n * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index\n */\n _this.alphaIndex = Number.MAX_VALUE;\n /**\n * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true\n */\n _this.isVisible = true;\n /**\n * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true\n */\n _this.isPickable = true;\n /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */\n _this.showSubMeshesBoundingBox = false;\n /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)\n * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares\n */\n _this.isBlocker = false;\n /**\n * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)\n */\n _this.enablePointerMoveEvents = false;\n /**\n * Specifies the rendering group id for this mesh (0 by default)\n * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups\n */\n _this.renderingGroupId = 0;\n _this._receiveShadows = false;\n /**\n * Gets or sets a boolean indicating if the outline must be rendered as well\n * @see https://www.babylonjs-playground.com/#10WJ5S#3\n */\n _this.renderOutline = false;\n /** Defines color to use when rendering outline */\n _this.outlineColor = BABYLON.Color3.Red();\n /** Define width to use when rendering outline */\n _this.outlineWidth = 0.02;\n /**\n * Gets or sets a boolean indicating if the overlay must be rendered as well\n * @see https://www.babylonjs-playground.com/#10WJ5S#2\n */\n _this.renderOverlay = false;\n /** Defines color to use when rendering overlay */\n _this.overlayColor = BABYLON.Color3.Red();\n /** Defines alpha to use when rendering overlay */\n _this.overlayAlpha = 0.5;\n _this._hasVertexAlpha = false;\n _this._useVertexColors = true;\n _this._computeBonesUsingShaders = true;\n _this._numBoneInfluencers = 4;\n _this._applyFog = true;\n /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */\n _this.useOctreeForRenderingSelection = true;\n /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */\n _this.useOctreeForPicking = true;\n /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */\n _this.useOctreeForCollisions = true;\n _this._layerMask = 0x0FFFFFFF;\n /**\n * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)\n */\n _this.alwaysSelectAsActiveMesh = false;\n /**\n * Gets or sets the current action manager\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions\n */\n _this.actionManager = null;\n /**\n * Gets or sets impostor used for physic simulation\n * @see http://doc.babylonjs.com/features/physics_engine\n */\n _this.physicsImpostor = null;\n // Collisions\n _this._checkCollisions = false;\n _this._collisionMask = -1;\n _this._collisionGroup = -1;\n /**\n * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */\n _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);\n /**\n * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */\n _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);\n _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);\n _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);\n // Edges\n /**\n * Defines edge width used when edgesRenderer is enabled\n * @see https://www.babylonjs-playground.com/#10OJSG#13\n */\n _this.edgesWidth = 1;\n /**\n * Defines edge color used when edgesRenderer is enabled\n * @see https://www.babylonjs-playground.com/#10OJSG#13\n */\n _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);\n // Cache\n _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();\n _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();\n /** @hidden */\n _this._renderId = 0;\n /** @hidden */\n _this._intersectionsInProgress = new Array();\n /** @hidden */\n _this._unIndexed = false;\n /** @hidden */\n _this._lightSources = new Array();\n _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {\n if (collidedMesh === void 0) { collidedMesh = null; }\n //TODO move this to the collision coordinator!\n if (_this.getScene().workerCollisions)\n newPosition.multiplyInPlace(_this._collider._radius);\n newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);\n if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {\n _this.position.addInPlace(_this._diffPositionForCollisions);\n }\n if (collidedMesh) {\n _this.onCollideObservable.notifyObservers(collidedMesh);\n }\n _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);\n };\n _this.getScene().addMesh(_this);\n _this._resyncLightSources();\n return _this;\n }\n Object.defineProperty(AbstractMesh, \"BILLBOARDMODE_NONE\", {\n /**\n * No billboard\n */\n get: function () {\n return BABYLON.TransformNode.BILLBOARDMODE_NONE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh, \"BILLBOARDMODE_X\", {\n /** Billboard on X axis */\n get: function () {\n return BABYLON.TransformNode.BILLBOARDMODE_X;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh, \"BILLBOARDMODE_Y\", {\n /** Billboard on Y axis */\n get: function () {\n return BABYLON.TransformNode.BILLBOARDMODE_Y;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh, \"BILLBOARDMODE_Z\", {\n /** Billboard on Z axis */\n get: function () {\n return BABYLON.TransformNode.BILLBOARDMODE_Z;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh, \"BILLBOARDMODE_ALL\", {\n /** Billboard on all axes */\n get: function () {\n return BABYLON.TransformNode.BILLBOARDMODE_ALL;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"facetNb\", {\n /**\n * Gets the number of facets in the mesh\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet\n */\n get: function () {\n return this._facetNb;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"partitioningSubdivisions\", {\n /**\n * Gets or set the number (integer) of subdivisions per axis in the partioning space\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning\n */\n get: function () {\n return this._partitioningSubdivisions;\n },\n set: function (nb) {\n this._partitioningSubdivisions = nb;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"partitioningBBoxRatio\", {\n /**\n * The ratio (float) to apply to the bouding box size to set to the partioning space.\n * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning\n */\n get: function () {\n return this._partitioningBBoxRatio;\n },\n set: function (ratio) {\n this._partitioningBBoxRatio = ratio;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"mustDepthSortFacets\", {\n /**\n * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.\n * Works only for updatable meshes.\n * Doesn't work with multi-materials\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort\n */\n get: function () {\n return this._facetDepthSort;\n },\n set: function (sort) {\n this._facetDepthSort = sort;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"facetDepthSortFrom\", {\n /**\n * The location (Vector3) where the facet depth sort must be computed from.\n * By default, the active camera position.\n * Used only when facet depth sort is enabled\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort\n */\n get: function () {\n return this._facetDepthSortFrom;\n },\n set: function (location) {\n this._facetDepthSortFrom = location;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"isFacetDataEnabled\", {\n /**\n * gets a boolean indicating if facetData is enabled\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet\n */\n get: function () {\n return this._facetDataEnabled;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n AbstractMesh.prototype._updateNonUniformScalingState = function (value) {\n if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {\n return false;\n }\n this._markSubMeshesAsMiscDirty();\n return true;\n };\n Object.defineProperty(AbstractMesh.prototype, \"onCollide\", {\n /** Set a function to call when this mesh collides with another one */\n set: function (callback) {\n if (this._onCollideObserver) {\n this.onCollideObservable.remove(this._onCollideObserver);\n }\n this._onCollideObserver = this.onCollideObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"onCollisionPositionChange\", {\n /** Set a function to call when the collision's position changes */\n set: function (callback) {\n if (this._onCollisionPositionChangeObserver) {\n this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);\n }\n this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"isOccluded\", {\n /**\n * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not\n * @see http://doc.babylonjs.com/features/occlusionquery\n */\n get: function () {\n return this._isOccluded;\n },\n set: function (value) {\n this._isOccluded = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"isOcclusionQueryInProgress\", {\n /**\n * Flag to check the progress status of the query\n * @see http://doc.babylonjs.com/features/occlusionquery\n */\n get: function () {\n return this._isOcclusionQueryInProgress;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"visibility\", {\n /**\n * Gets or sets mesh visibility between 0 and 1 (default is 1)\n */\n get: function () {\n return this._visibility;\n },\n /**\n * Gets or sets mesh visibility between 0 and 1 (default is 1)\n */\n set: function (value) {\n if (this._visibility === value) {\n return;\n }\n this._visibility = value;\n this._markSubMeshesAsMiscDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"material\", {\n /** Gets or sets current material */\n get: function () {\n return this._material;\n },\n set: function (value) {\n if (this._material === value) {\n return;\n }\n this._material = value;\n if (this.onMaterialChangedObservable.hasObservers) {\n this.onMaterialChangedObservable.notifyObservers(this);\n }\n if (!this.subMeshes) {\n return;\n }\n this._unBindEffect();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"receiveShadows\", {\n /**\n * Gets or sets a boolean indicating that this mesh can receive realtime shadows\n * @see http://doc.babylonjs.com/babylon101/shadows\n */\n get: function () {\n return this._receiveShadows;\n },\n set: function (value) {\n if (this._receiveShadows === value) {\n return;\n }\n this._receiveShadows = value;\n this._markSubMeshesAsLightDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"hasVertexAlpha\", {\n /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */\n get: function () {\n return this._hasVertexAlpha;\n },\n set: function (value) {\n if (this._hasVertexAlpha === value) {\n return;\n }\n this._hasVertexAlpha = value;\n this._markSubMeshesAsAttributesDirty();\n this._markSubMeshesAsMiscDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"useVertexColors\", {\n /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */\n get: function () {\n return this._useVertexColors;\n },\n set: function (value) {\n if (this._useVertexColors === value) {\n return;\n }\n this._useVertexColors = value;\n this._markSubMeshesAsAttributesDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"computeBonesUsingShaders\", {\n /**\n * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)\n */\n get: function () {\n return this._computeBonesUsingShaders;\n },\n set: function (value) {\n if (this._computeBonesUsingShaders === value) {\n return;\n }\n this._computeBonesUsingShaders = value;\n this._markSubMeshesAsAttributesDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"numBoneInfluencers\", {\n /** Gets or sets the number of allowed bone influences per vertex (4 by default) */\n get: function () {\n return this._numBoneInfluencers;\n },\n set: function (value) {\n if (this._numBoneInfluencers === value) {\n return;\n }\n this._numBoneInfluencers = value;\n this._markSubMeshesAsAttributesDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"applyFog\", {\n /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */\n get: function () {\n return this._applyFog;\n },\n set: function (value) {\n if (this._applyFog === value) {\n return;\n }\n this._applyFog = value;\n this._markSubMeshesAsMiscDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"layerMask\", {\n /**\n * Gets or sets the current layer mask (default is 0x0FFFFFFF)\n * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures\n */\n get: function () {\n return this._layerMask;\n },\n set: function (value) {\n if (value === this._layerMask) {\n return;\n }\n this._layerMask = value;\n this._resyncLightSources();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"collisionMask\", {\n /**\n * Gets or sets a collision mask used to mask collisions (default is -1).\n * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0\n */\n get: function () {\n return this._collisionMask;\n },\n set: function (mask) {\n this._collisionMask = !isNaN(mask) ? mask : -1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"collisionGroup\", {\n /**\n * Gets or sets the current collision group mask (-1 by default).\n * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0\n */\n get: function () {\n return this._collisionGroup;\n },\n set: function (mask) {\n this._collisionGroup = !isNaN(mask) ? mask : -1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"_positions\", {\n /** @hidden */\n get: function () {\n return null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"skeleton\", {\n get: function () {\n return this._skeleton;\n },\n /**\n * Gets or sets a skeleton to apply skining transformations\n * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons\n */\n set: function (value) {\n if (this._skeleton && this._skeleton.needInitialSkinMatrix) {\n this._skeleton._unregisterMeshWithPoseMatrix(this);\n }\n if (value && value.needInitialSkinMatrix) {\n value._registerMeshWithPoseMatrix(this);\n }\n this._skeleton = value;\n if (!this._skeleton) {\n this._bonesTransformMatrices = null;\n }\n this._markSubMeshesAsAttributesDirty();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"AbstractMesh\"\n * @returns \"AbstractMesh\"\n */\n AbstractMesh.prototype.getClassName = function () {\n return \"AbstractMesh\";\n };\n /**\n * Gets a string representation of the current mesh\n * @param fullDetails defines a boolean indicating if full details must be included\n * @returns a string representation of the current mesh\n */\n AbstractMesh.prototype.toString = function (fullDetails) {\n var ret = \"Name: \" + this.name + \", isInstance: \" + (this instanceof BABYLON.InstancedMesh ? \"YES\" : \"NO\");\n ret += \", # of submeshes: \" + (this.subMeshes ? this.subMeshes.length : 0);\n if (this._skeleton) {\n ret += \", skeleton: \" + this._skeleton.name;\n }\n if (fullDetails) {\n ret += \", billboard mode: \" + ([\"NONE\", \"X\", \"Y\", null, \"Z\", null, null, \"ALL\"])[this.billboardMode];\n ret += \", freeze wrld mat: \" + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? \"YES\" : \"NO\");\n }\n return ret;\n };\n /** @hidden */\n AbstractMesh.prototype._rebuild = function () {\n if (this._occlusionQuery) {\n this._occlusionQuery = null;\n }\n if (this._edgesRenderer) {\n this._edgesRenderer._rebuild();\n }\n if (!this.subMeshes) {\n return;\n }\n for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n subMesh._rebuild();\n }\n };\n /** @hidden */\n AbstractMesh.prototype._resyncLightSources = function () {\n this._lightSources.length = 0;\n for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {\n var light = _a[_i];\n if (!light.isEnabled()) {\n continue;\n }\n if (light.canAffectMesh(this)) {\n this._lightSources.push(light);\n }\n }\n this._markSubMeshesAsLightDirty();\n };\n /** @hidden */\n AbstractMesh.prototype._resyncLighSource = function (light) {\n var isIn = light.isEnabled() && light.canAffectMesh(this);\n var index = this._lightSources.indexOf(light);\n if (index === -1) {\n if (!isIn) {\n return;\n }\n this._lightSources.push(light);\n }\n else {\n if (isIn) {\n return;\n }\n this._lightSources.splice(index, 1);\n }\n this._markSubMeshesAsLightDirty();\n };\n /** @hidden */\n AbstractMesh.prototype._unBindEffect = function () {\n for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n subMesh.setEffect(null);\n }\n };\n /** @hidden */\n AbstractMesh.prototype._removeLightSource = function (light) {\n var index = this._lightSources.indexOf(light);\n if (index === -1) {\n return;\n }\n this._lightSources.splice(index, 1);\n this._markSubMeshesAsLightDirty();\n };\n AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {\n if (!this.subMeshes) {\n return;\n }\n for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n if (subMesh._materialDefines) {\n func(subMesh._materialDefines);\n }\n }\n };\n /** @hidden */\n AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {\n this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });\n };\n /** @hidden */\n AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {\n this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });\n };\n /** @hidden */\n AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {\n if (!this.subMeshes) {\n return;\n }\n for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n var material = subMesh.getMaterial();\n if (material) {\n material.markAsDirty(BABYLON.Material.MiscDirtyFlag);\n }\n }\n };\n Object.defineProperty(AbstractMesh.prototype, \"scaling\", {\n /**\n * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)\n */\n get: function () {\n return this._scaling;\n },\n set: function (newScaling) {\n this._scaling = newScaling;\n if (this.physicsImpostor) {\n this.physicsImpostor.forceUpdate();\n }\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n /**\n * Disables the mesh edge rendering mode\n * @returns the currentAbstractMesh\n */\n AbstractMesh.prototype.disableEdgesRendering = function () {\n if (this._edgesRenderer) {\n this._edgesRenderer.dispose();\n this._edgesRenderer = null;\n }\n return this;\n };\n /**\n * Enables the edge rendering mode on the mesh.\n * This mode makes the mesh edges visible\n * @param epsilon defines the maximal distance between two angles to detect a face\n * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces\n * @returns the currentAbstractMesh\n * @see https://www.babylonjs-playground.com/#19O9TU#0\n */\n AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {\n if (epsilon === void 0) { epsilon = 0.95; }\n if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }\n this.disableEdgesRendering();\n this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);\n return this;\n };\n Object.defineProperty(AbstractMesh.prototype, \"edgesRenderer\", {\n /**\n * Gets the edgesRenderer associated with the mesh\n */\n get: function () {\n return this._edgesRenderer;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"isBlocked\", {\n /**\n * Returns true if the mesh is blocked. Implemented by child classes\n */\n get: function () {\n return false;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the mesh itself by default. Implemented by child classes\n * @param camera defines the camera to use to pick the right LOD level\n * @returns the currentAbstractMesh\n */\n AbstractMesh.prototype.getLOD = function (camera) {\n return this;\n };\n /**\n * Returns 0 by default. Implemented by child classes\n * @returns an integer\n */\n AbstractMesh.prototype.getTotalVertices = function () {\n return 0;\n };\n /**\n * Returns null by default. Implemented by child classes\n * @returns null\n */\n AbstractMesh.prototype.getIndices = function () {\n return null;\n };\n /**\n * Returns the array of the requested vertex data kind. Implemented by child classes\n * @param kind defines the vertex data kind to use\n * @returns null\n */\n AbstractMesh.prototype.getVerticesData = function (kind) {\n return null;\n };\n /**\n * Sets the vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.\n * Note that a new underlying VertexBuffer object is created each call.\n * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.\n * @param kind defines vertex data kind:\n * * BABYLON.VertexBuffer.PositionKind\n * * BABYLON.VertexBuffer.UVKind\n * * BABYLON.VertexBuffer.UV2Kind\n * * BABYLON.VertexBuffer.UV3Kind\n * * BABYLON.VertexBuffer.UV4Kind\n * * BABYLON.VertexBuffer.UV5Kind\n * * BABYLON.VertexBuffer.UV6Kind\n * * BABYLON.VertexBuffer.ColorKind\n * * BABYLON.VertexBuffer.MatricesIndicesKind\n * * BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * * BABYLON.VertexBuffer.MatricesWeightsKind\n * * BABYLON.VertexBuffer.MatricesWeightsExtraKind\n * @param data defines the data source\n * @param updatable defines if the data must be flagged as updatable (or static)\n * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind\n * @returns the current mesh\n */\n AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {\n return this;\n };\n /**\n * Updates the existing vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, it is simply returned as it is.\n * @param kind defines vertex data kind:\n * * BABYLON.VertexBuffer.PositionKind\n * * BABYLON.VertexBuffer.UVKind\n * * BABYLON.VertexBuffer.UV2Kind\n * * BABYLON.VertexBuffer.UV3Kind\n * * BABYLON.VertexBuffer.UV4Kind\n * * BABYLON.VertexBuffer.UV5Kind\n * * BABYLON.VertexBuffer.UV6Kind\n * * BABYLON.VertexBuffer.ColorKind\n * * BABYLON.VertexBuffer.MatricesIndicesKind\n * * BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * * BABYLON.VertexBuffer.MatricesWeightsKind\n * * BABYLON.VertexBuffer.MatricesWeightsExtraKind\n * @param data defines the data source\n * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed\n * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh\n * @returns the current mesh\n */\n AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {\n return this;\n };\n /**\n * Sets the mesh indices,\n * If the mesh has no geometry, a new Geometry object is created and set to the mesh.\n * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)\n * @param totalVertices Defines the total number of vertices\n * @returns the current mesh\n */\n AbstractMesh.prototype.setIndices = function (indices, totalVertices) {\n return this;\n };\n /**\n * Gets a boolean indicating if specific vertex data is present\n * @param kind defines the vertex data kind to use\n * @returns true is data kind is present\n */\n AbstractMesh.prototype.isVerticesDataPresent = function (kind) {\n return false;\n };\n /**\n * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined\n * @returns a BoundingInfo\n */\n AbstractMesh.prototype.getBoundingInfo = function () {\n if (this._masterMesh) {\n return this._masterMesh.getBoundingInfo();\n }\n if (!this._boundingInfo) {\n // this._boundingInfo is being created here\n this._updateBoundingInfo();\n }\n // cannot be null.\n return this._boundingInfo;\n };\n /**\n * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)\n * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box\n * @returns the current mesh\n */\n AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {\n if (includeDescendants === void 0) { includeDescendants = true; }\n var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);\n var sizeVec = boundingVectors.max.subtract(boundingVectors.min);\n var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);\n if (maxDimension === 0) {\n return this;\n }\n var scale = 1 / maxDimension;\n this.scaling.scaleInPlace(scale);\n return this;\n };\n /**\n * Overwrite the current bounding info\n * @param boundingInfo defines the new bounding info\n * @returns the current mesh\n */\n AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {\n this._boundingInfo = boundingInfo;\n return this;\n };\n Object.defineProperty(AbstractMesh.prototype, \"useBones\", {\n /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */\n get: function () {\n return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n AbstractMesh.prototype._preActivate = function () {\n };\n /** @hidden */\n AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {\n };\n /** @hidden */\n AbstractMesh.prototype._activate = function (renderId) {\n this._renderId = renderId;\n };\n /**\n * Gets the current world matrix\n * @returns a Matrix\n */\n AbstractMesh.prototype.getWorldMatrix = function () {\n if (this._masterMesh) {\n return this._masterMesh.getWorldMatrix();\n }\n return _super.prototype.getWorldMatrix.call(this);\n };\n /** @hidden */\n AbstractMesh.prototype._getWorldMatrixDeterminant = function () {\n if (this._masterMesh) {\n return this._masterMesh._getWorldMatrixDeterminant();\n }\n return _super.prototype._getWorldMatrixDeterminant.call(this);\n };\n // ================================== Point of View Movement =================================\n /**\n * Perform relative position change from the point of view of behind the front of the mesh.\n * This is performed taking into account the meshes current rotation, so you do not have to care.\n * Supports definition of mesh facing forward or backward\n * @param amountRight defines the distance on the right axis\n * @param amountUp defines the distance on the up axis\n * @param amountForward defines the distance on the forward axis\n * @returns the current mesh\n */\n AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {\n this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));\n return this;\n };\n /**\n * Calculate relative position change from the point of view of behind the front of the mesh.\n * This is performed taking into account the meshes current rotation, so you do not have to care.\n * Supports definition of mesh facing forward or backward\n * @param amountRight defines the distance on the right axis\n * @param amountUp defines the distance on the up axis\n * @param amountForward defines the distance on the forward axis\n * @returns the new displacement vector\n */\n AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {\n var rotMatrix = new BABYLON.Matrix();\n var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);\n rotQuaternion.toRotationMatrix(rotMatrix);\n var translationDelta = BABYLON.Vector3.Zero();\n var defForwardMult = this.definedFacingForward ? -1 : 1;\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);\n return translationDelta;\n };\n // ================================== Point of View Rotation =================================\n /**\n * Perform relative rotation change from the point of view of behind the front of the mesh.\n * Supports definition of mesh facing forward or backward\n * @param flipBack defines the flip\n * @param twirlClockwise defines the twirl\n * @param tiltRight defines the tilt\n * @returns the current mesh\n */\n AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {\n this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));\n return this;\n };\n /**\n * Calculate relative rotation change from the point of view of behind the front of the mesh.\n * Supports definition of mesh facing forward or backward.\n * @param flipBack defines the flip\n * @param twirlClockwise defines the twirl\n * @param tiltRight defines the tilt\n * @returns the new rotation vector\n */\n AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {\n var defForwardMult = this.definedFacingForward ? 1 : -1;\n return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);\n };\n /**\n * Return the minimum and maximum world vectors of the entire hierarchy under current mesh\n * @param includeDescendants Include bounding info from descendants as well (true by default)\n * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors\n * @returns the new bounding vectors\n */\n AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {\n if (includeDescendants === void 0) { includeDescendants = true; }\n if (predicate === void 0) { predicate = null; }\n // Ensures that all world matrix will be recomputed.\n this.getScene().incrementRenderId();\n this.computeWorldMatrix(true);\n var min;\n var max;\n var boundingInfo = this.getBoundingInfo();\n if (!this.subMeshes) {\n min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n }\n else {\n min = boundingInfo.boundingBox.minimumWorld;\n max = boundingInfo.boundingBox.maximumWorld;\n }\n if (includeDescendants) {\n var descendants = this.getDescendants(false);\n for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {\n var descendant = descendants_1[_i];\n var childMesh = descendant;\n childMesh.computeWorldMatrix(true);\n // Filters meshes based on custom predicate function.\n if (predicate && !predicate(childMesh)) {\n continue;\n }\n //make sure we have the needed params to get mix and max\n if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {\n continue;\n }\n var childBoundingInfo = childMesh.getBoundingInfo();\n var boundingBox = childBoundingInfo.boundingBox;\n var minBox = boundingBox.minimumWorld;\n var maxBox = boundingBox.maximumWorld;\n BABYLON.Tools.CheckExtends(minBox, min, max);\n BABYLON.Tools.CheckExtends(maxBox, min, max);\n }\n }\n return {\n min: min,\n max: max\n };\n };\n /** @hidden */\n AbstractMesh.prototype._updateBoundingInfo = function () {\n this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);\n this._boundingInfo.update(this.worldMatrixFromCache);\n this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);\n return this;\n };\n /** @hidden */\n AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {\n if (!this.subMeshes) {\n return this;\n }\n for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {\n var subMesh = this.subMeshes[subIndex];\n if (!subMesh.IsGlobal) {\n subMesh.updateBoundingInfo(matrix);\n }\n }\n return this;\n };\n /** @hidden */\n AbstractMesh.prototype._afterComputeWorldMatrix = function () {\n // Bounding info\n this._updateBoundingInfo();\n };\n /**\n * Returns `true` if the mesh is within the frustum defined by the passed array of planes.\n * A mesh is in the frustum if its bounding box intersects the frustum\n * @param frustumPlanes defines the frustum to test\n * @returns true if the mesh is in the frustum planes\n */\n AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {\n return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);\n };\n /**\n * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.\n * A mesh is completely in the frustum if its bounding box it completely inside the frustum.\n * @param frustumPlanes defines the frustum to test\n * @returns true if the mesh is completely in the frustum planes\n */\n AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {\n return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);\n };\n /**\n * True if the mesh intersects another mesh or a SolidParticle object\n * @param mesh defines a target mesh or SolidParticle to test\n * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)\n * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes\n * @returns true if there is an intersection\n */\n AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {\n if (precise === void 0) { precise = false; }\n if (!this._boundingInfo || !mesh._boundingInfo) {\n return false;\n }\n if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {\n return true;\n }\n if (includeDescendants) {\n for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {\n var child = _a[_i];\n if (child.intersectsMesh(mesh, precise, true)) {\n return true;\n }\n }\n }\n return false;\n };\n /**\n * Returns true if the passed point (Vector3) is inside the mesh bounding box\n * @param point defines the point to test\n * @returns true if there is an intersection\n */\n AbstractMesh.prototype.intersectsPoint = function (point) {\n if (!this._boundingInfo) {\n return false;\n }\n return this._boundingInfo.intersectsPoint(point);\n };\n /**\n * Gets the current physics impostor\n * @see http://doc.babylonjs.com/features/physics_engine\n * @returns a physics impostor or null\n */\n AbstractMesh.prototype.getPhysicsImpostor = function () {\n return this.physicsImpostor;\n };\n /**\n * Gets the position of the current mesh in camera space\n * @param camera defines the camera to use\n * @returns a position\n */\n AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {\n if (camera === void 0) { camera = null; }\n if (!camera) {\n camera = this.getScene().activeCamera;\n }\n return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());\n };\n /**\n * Returns the distance from the mesh to the active camera\n * @param camera defines the camera to use\n * @returns the distance\n */\n AbstractMesh.prototype.getDistanceToCamera = function (camera) {\n if (camera === void 0) { camera = null; }\n if (!camera) {\n camera = this.getScene().activeCamera;\n }\n return this.absolutePosition.subtract(camera.position).length();\n };\n /**\n * Apply a physic impulse to the mesh\n * @param force defines the force to apply\n * @param contactPoint defines where to apply the force\n * @returns the current mesh\n * @see http://doc.babylonjs.com/how_to/using_the_physics_engine\n */\n AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {\n if (!this.physicsImpostor) {\n return this;\n }\n this.physicsImpostor.applyImpulse(force, contactPoint);\n return this;\n };\n /**\n * Creates a physic joint between two meshes\n * @param otherMesh defines the other mesh to use\n * @param pivot1 defines the pivot to use on this mesh\n * @param pivot2 defines the pivot to use on the other mesh\n * @param options defines additional options (can be plugin dependent)\n * @returns the current mesh\n * @see https://www.babylonjs-playground.com/#0BS5U0#0\n */\n AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {\n if (!this.physicsImpostor || !otherMesh.physicsImpostor) {\n return this;\n }\n this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {\n mainPivot: pivot1,\n connectedPivot: pivot2,\n nativeParams: options\n });\n return this;\n };\n Object.defineProperty(AbstractMesh.prototype, \"checkCollisions\", {\n // Collisions\n /**\n * Gets or sets a boolean indicating that this mesh can be used in the collision engine\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */\n get: function () {\n return this._checkCollisions;\n },\n set: function (collisionEnabled) {\n this._checkCollisions = collisionEnabled;\n if (this.getScene().workerCollisions) {\n this.getScene().collisionCoordinator.onMeshUpdated(this);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractMesh.prototype, \"collider\", {\n /**\n * Gets Collider object used to compute collisions (not physics)\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */\n get: function () {\n return this._collider;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Move the mesh using collision engine\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n * @param displacement defines the requested displacement vector\n * @returns the current mesh\n */\n AbstractMesh.prototype.moveWithCollisions = function (displacement) {\n var globalPosition = this.getAbsolutePosition();\n globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);\n if (!this._collider) {\n this._collider = new BABYLON.Collider();\n }\n this._collider._radius = this.ellipsoid;\n this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);\n return this;\n };\n // Submeshes octree\n /**\n * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.\n * Please note that you must have a decent number of submeshes to get performance improvements when using an octree\n * @param maxCapacity defines the maximum size of each block (64 by default)\n * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)\n * @returns the new octree\n * @see https://www.babylonjs-playground.com/#NA4OQ#12\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees\n */\n AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {\n if (maxCapacity === void 0) { maxCapacity = 64; }\n if (maxDepth === void 0) { maxDepth = 2; }\n if (!this._submeshesOctree) {\n this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);\n }\n this.computeWorldMatrix(true);\n var boundingInfo = this.getBoundingInfo();\n // Update octree\n var bbox = boundingInfo.boundingBox;\n this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);\n return this._submeshesOctree;\n };\n // Collisions\n /** @hidden */\n AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {\n this._generatePointsArray();\n if (!this._positions) {\n return this;\n }\n // Transformation\n if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {\n subMesh._lastColliderTransformMatrix = transformMatrix.clone();\n subMesh._lastColliderWorldVertices = [];\n subMesh._trianglePlanes = [];\n var start = subMesh.verticesStart;\n var end = (subMesh.verticesStart + subMesh.verticesCount);\n for (var i = start; i < end; i++) {\n subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));\n }\n }\n // Collide\n collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());\n if (collider.collisionFound) {\n collider.collidedMesh = this;\n }\n return this;\n };\n /** @hidden */\n AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {\n var subMeshes;\n var len;\n // Octrees\n if (this._submeshesOctree && this.useOctreeForCollisions) {\n var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);\n var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);\n len = intersections.length;\n subMeshes = intersections.data;\n }\n else {\n subMeshes = this.subMeshes;\n len = subMeshes.length;\n }\n for (var index = 0; index < len; index++) {\n var subMesh = subMeshes[index];\n // Bounding test\n if (len > 1 && !subMesh._checkCollision(collider))\n continue;\n this._collideForSubMesh(subMesh, transformMatrix, collider);\n }\n return this;\n };\n /** @hidden */\n AbstractMesh.prototype._checkCollision = function (collider) {\n // Bounding box test\n if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))\n return this;\n // Transformation matrix\n BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);\n this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);\n this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);\n return this;\n };\n // Picking\n /** @hidden */\n AbstractMesh.prototype._generatePointsArray = function () {\n return false;\n };\n /**\n * Checks if the passed Ray intersects with the mesh\n * @param ray defines the ray to use\n * @param fastCheck defines if fast mode (but less precise) must be used (false by default)\n * @returns the picking info\n * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh\n */\n AbstractMesh.prototype.intersects = function (ray, fastCheck) {\n var pickingInfo = new BABYLON.PickingInfo();\n if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {\n return pickingInfo;\n }\n if (!this._generatePointsArray()) {\n return pickingInfo;\n }\n var intersectInfo = null;\n // Octrees\n var subMeshes;\n var len;\n if (this._submeshesOctree && this.useOctreeForPicking) {\n var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());\n var intersections = this._submeshesOctree.intersectsRay(worldRay);\n len = intersections.length;\n subMeshes = intersections.data;\n }\n else {\n subMeshes = this.subMeshes;\n len = subMeshes.length;\n }\n for (var index = 0; index < len; index++) {\n var subMesh = subMeshes[index];\n // Bounding test\n if (len > 1 && !subMesh.canIntersects(ray))\n continue;\n var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);\n if (currentIntersectInfo) {\n if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {\n intersectInfo = currentIntersectInfo;\n intersectInfo.subMeshId = index;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n if (intersectInfo) {\n // Get picked point\n var world = this.getWorldMatrix();\n var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);\n var direction = ray.direction.clone();\n direction = direction.scale(intersectInfo.distance);\n var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);\n var pickedPoint = worldOrigin.add(worldDirection);\n // Return result\n pickingInfo.hit = true;\n pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);\n pickingInfo.pickedPoint = pickedPoint;\n pickingInfo.pickedMesh = this;\n pickingInfo.bu = intersectInfo.bu || 0;\n pickingInfo.bv = intersectInfo.bv || 0;\n pickingInfo.faceId = intersectInfo.faceId;\n pickingInfo.subMeshId = intersectInfo.subMeshId;\n return pickingInfo;\n }\n return pickingInfo;\n };\n /**\n * Clones the current mesh\n * @param name defines the mesh name\n * @param newParent defines the new mesh parent\n * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)\n * @returns the new mesh\n */\n AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {\n return null;\n };\n /**\n * Disposes all the submeshes of the current meshnp\n * @returns the current mesh\n */\n AbstractMesh.prototype.releaseSubMeshes = function () {\n if (this.subMeshes) {\n while (this.subMeshes.length) {\n this.subMeshes[0].dispose();\n }\n }\n else {\n this.subMeshes = new Array();\n }\n return this;\n };\n /**\n * Releases resources associated with this abstract mesh.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n var _this = this;\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n var index;\n // Smart Array Retainers.\n this.getScene().freeActiveMeshes();\n this.getScene().freeRenderingGroups();\n // Action manager\n if (this.actionManager !== undefined && this.actionManager !== null) {\n this.actionManager.dispose();\n this.actionManager = null;\n }\n // Skeleton\n this._skeleton = null;\n // Physics\n if (this.physicsImpostor) {\n this.physicsImpostor.dispose( /*!doNotRecurse*/);\n }\n // Intersections in progress\n for (index = 0; index < this._intersectionsInProgress.length; index++) {\n var other = this._intersectionsInProgress[index];\n var pos = other._intersectionsInProgress.indexOf(this);\n other._intersectionsInProgress.splice(pos, 1);\n }\n this._intersectionsInProgress = [];\n // Lights\n var lights = this.getScene().lights;\n lights.forEach(function (light) {\n var meshIndex = light.includedOnlyMeshes.indexOf(_this);\n if (meshIndex !== -1) {\n light.includedOnlyMeshes.splice(meshIndex, 1);\n }\n meshIndex = light.excludedMeshes.indexOf(_this);\n if (meshIndex !== -1) {\n light.excludedMeshes.splice(meshIndex, 1);\n }\n // Shadow generators\n var generator = light.getShadowGenerator();\n if (generator) {\n var shadowMap = generator.getShadowMap();\n if (shadowMap && shadowMap.renderList) {\n meshIndex = shadowMap.renderList.indexOf(_this);\n if (meshIndex !== -1) {\n shadowMap.renderList.splice(meshIndex, 1);\n }\n }\n }\n });\n // Edges\n if (this._edgesRenderer) {\n this._edgesRenderer.dispose();\n this._edgesRenderer = null;\n }\n // SubMeshes\n if (this.getClassName() !== \"InstancedMesh\") {\n this.releaseSubMeshes();\n }\n // Octree\n var sceneOctree = this.getScene().selectionOctree;\n if (sceneOctree !== undefined && sceneOctree !== null) {\n var index = sceneOctree.dynamicContent.indexOf(this);\n if (index !== -1) {\n sceneOctree.dynamicContent.splice(index, 1);\n }\n }\n // Query\n var engine = this.getScene().getEngine();\n if (this._occlusionQuery) {\n this._isOcclusionQueryInProgress = false;\n engine.deleteQuery(this._occlusionQuery);\n this._occlusionQuery = null;\n }\n // Engine\n engine.wipeCaches();\n // Remove from scene\n this.getScene().removeMesh(this);\n if (disposeMaterialAndTextures) {\n if (this.material) {\n this.material.dispose(false, true);\n }\n }\n if (!doNotRecurse) {\n // Particles\n for (index = 0; index < this.getScene().particleSystems.length; index++) {\n if (this.getScene().particleSystems[index].emitter === this) {\n this.getScene().particleSystems[index].dispose();\n index--;\n }\n }\n }\n // facet data\n if (this._facetDataEnabled) {\n this.disableFacetData();\n }\n this.onAfterWorldMatrixUpdateObservable.clear();\n this.onCollideObservable.clear();\n this.onCollisionPositionChangeObservable.clear();\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n /**\n * Adds the passed mesh as a child to the current mesh\n * @param mesh defines the child mesh\n * @returns the current mesh\n */\n AbstractMesh.prototype.addChild = function (mesh) {\n mesh.setParent(this);\n return this;\n };\n /**\n * Removes the passed mesh from the current mesh children list\n * @param mesh defines the child mesh\n * @returns the current mesh\n */\n AbstractMesh.prototype.removeChild = function (mesh) {\n mesh.setParent(null);\n return this;\n };\n // Facet data\n /** @hidden */\n AbstractMesh.prototype._initFacetData = function () {\n if (!this._facetNormals) {\n this._facetNormals = new Array();\n }\n if (!this._facetPositions) {\n this._facetPositions = new Array();\n }\n if (!this._facetPartitioning) {\n this._facetPartitioning = new Array();\n }\n this._facetNb = (this.getIndices().length / 3) | 0;\n this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10\n this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box\n for (var f = 0; f < this._facetNb; f++) {\n this._facetNormals[f] = BABYLON.Vector3.Zero();\n this._facetPositions[f] = BABYLON.Vector3.Zero();\n }\n this._facetDataEnabled = true;\n return this;\n };\n /**\n * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.\n * This method can be called within the render loop.\n * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation\n * @returns the current mesh\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.updateFacetData = function () {\n if (!this._facetDataEnabled) {\n this._initFacetData();\n }\n var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var indices = this.getIndices();\n var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var bInfo = this.getBoundingInfo();\n if (this._facetDepthSort && !this._facetDepthSortEnabled) {\n // init arrays, matrix and sort function on first call\n this._facetDepthSortEnabled = true;\n if (indices instanceof Uint16Array) {\n this._depthSortedIndices = new Uint16Array(indices);\n }\n else if (indices instanceof Uint32Array) {\n this._depthSortedIndices = new Uint32Array(indices);\n }\n else {\n var needs32bits = false;\n for (var i = 0; i < indices.length; i++) {\n if (indices[i] > 65535) {\n needs32bits = true;\n break;\n }\n }\n if (needs32bits) {\n this._depthSortedIndices = new Uint32Array(indices);\n }\n else {\n this._depthSortedIndices = new Uint16Array(indices);\n }\n }\n this._facetDepthSortFunction = function (f1, f2) {\n return (f2.sqDistance - f1.sqDistance);\n };\n if (!this._facetDepthSortFrom) {\n var camera = this.getScene().activeCamera;\n this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();\n }\n this._depthSortedFacets = [];\n for (var f = 0; f < this._facetNb; f++) {\n var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };\n this._depthSortedFacets.push(depthSortedFacet);\n }\n this._invertedMatrix = BABYLON.Matrix.Identity();\n this._facetDepthSortOrigin = BABYLON.Vector3.Zero();\n }\n this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;\n this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;\n this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;\n var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;\n bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;\n this._subDiv.max = this._partitioningSubdivisions;\n this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis\n this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis\n this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);\n this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision\n this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;\n this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;\n // set the parameters for ComputeNormals()\n this._facetParameters.facetNormals = this.getFacetLocalNormals();\n this._facetParameters.facetPositions = this.getFacetLocalPositions();\n this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();\n this._facetParameters.bInfo = bInfo;\n this._facetParameters.bbSize = this._bbSize;\n this._facetParameters.subDiv = this._subDiv;\n this._facetParameters.ratio = this.partitioningBBoxRatio;\n this._facetParameters.depthSort = this._facetDepthSort;\n if (this._facetDepthSort && this._facetDepthSortEnabled) {\n this.computeWorldMatrix(true);\n this._worldMatrix.invertToRef(this._invertedMatrix);\n BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);\n this._facetParameters.distanceTo = this._facetDepthSortOrigin;\n }\n this._facetParameters.depthSortedFacets = this._depthSortedFacets;\n BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);\n if (this._facetDepthSort && this._facetDepthSortEnabled) {\n this._depthSortedFacets.sort(this._facetDepthSortFunction);\n var l = (this._depthSortedIndices.length / 3) | 0;\n for (var f = 0; f < l; f++) {\n var sind = this._depthSortedFacets[f].ind;\n this._depthSortedIndices[f * 3] = indices[sind];\n this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];\n this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];\n }\n this.updateIndices(this._depthSortedIndices);\n }\n return this;\n };\n /**\n * Returns the facetLocalNormals array.\n * The normals are expressed in the mesh local spac\n * @returns an array of Vector3\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetLocalNormals = function () {\n if (!this._facetNormals) {\n this.updateFacetData();\n }\n return this._facetNormals;\n };\n /**\n * Returns the facetLocalPositions array.\n * The facet positions are expressed in the mesh local space\n * @returns an array of Vector3\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetLocalPositions = function () {\n if (!this._facetPositions) {\n this.updateFacetData();\n }\n return this._facetPositions;\n };\n /**\n * Returns the facetLocalPartioning array\n * @returns an array of array of numbers\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetLocalPartitioning = function () {\n if (!this._facetPartitioning) {\n this.updateFacetData();\n }\n return this._facetPartitioning;\n };\n /**\n * Returns the i-th facet position in the world system.\n * This method allocates a new Vector3 per call\n * @param i defines the facet index\n * @returns a new Vector3\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetPosition = function (i) {\n var pos = BABYLON.Vector3.Zero();\n this.getFacetPositionToRef(i, pos);\n return pos;\n };\n /**\n * Sets the reference Vector3 with the i-th facet position in the world system\n * @param i defines the facet index\n * @param ref defines the target vector\n * @returns the current mesh\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {\n var localPos = (this.getFacetLocalPositions())[i];\n var world = this.getWorldMatrix();\n BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);\n return this;\n };\n /**\n * Returns the i-th facet normal in the world system.\n * This method allocates a new Vector3 per call\n * @param i defines the facet index\n * @returns a new Vector3\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetNormal = function (i) {\n var norm = BABYLON.Vector3.Zero();\n this.getFacetNormalToRef(i, norm);\n return norm;\n };\n /**\n * Sets the reference Vector3 with the i-th facet normal in the world system\n * @param i defines the facet index\n * @param ref defines the target vector\n * @returns the current mesh\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {\n var localNorm = (this.getFacetLocalNormals())[i];\n BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);\n return this;\n };\n /**\n * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system)\n * @param x defines x coordinate\n * @param y defines y coordinate\n * @param z defines z coordinate\n * @returns the array of facet indexes\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {\n var bInfo = this.getBoundingInfo();\n var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);\n var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);\n var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);\n if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {\n return null;\n }\n return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];\n };\n /**\n * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found\n * @param projected sets as the (x,y,z) world projection on the facet\n * @param checkFace if true (default false), only the facet \"facing\" to (x,y,z) or only the ones \"turning their backs\", according to the parameter \"facing\" are returned\n * @param facing if facing and checkFace are true, only the facet \"facing\" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet \"turning their backs\" to (x, y, z) are returned : negative dot (x, y, z) * facet position\n * @param x defines x coordinate\n * @param y defines y coordinate\n * @param z defines z coordinate\n * @returns the face index if found (or null instead)\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {\n if (checkFace === void 0) { checkFace = false; }\n if (facing === void 0) { facing = true; }\n var world = this.getWorldMatrix();\n var invMat = BABYLON.Tmp.Matrix[5];\n world.invertToRef(invMat);\n var invVect = BABYLON.Tmp.Vector3[8];\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space\n var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);\n if (projected) {\n // tranform the local computed projected vector to world coordinates\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);\n }\n return closest;\n };\n /**\n * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found\n * @param projected sets as the (x,y,z) local projection on the facet\n * @param checkFace if true (default false), only the facet \"facing\" to (x,y,z) or only the ones \"turning their backs\", according to the parameter \"facing\" are returned\n * @param facing if facing and checkFace are true, only the facet \"facing\" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet \"turning their backs\" to (x, y, z) are returned : negative dot (x, y, z) * facet position\n * @param x defines x coordinate\n * @param y defines y coordinate\n * @param z defines z coordinate\n * @returns the face index if found (or null instead)\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {\n if (checkFace === void 0) { checkFace = false; }\n if (facing === void 0) { facing = true; }\n var closest = null;\n var tmpx = 0.0;\n var tmpy = 0.0;\n var tmpz = 0.0;\n var d = 0.0; // tmp dot facet normal * facet position\n var t0 = 0.0;\n var projx = 0.0;\n var projy = 0.0;\n var projz = 0.0;\n // Get all the facets in the same partitioning block than (x, y, z)\n var facetPositions = this.getFacetLocalPositions();\n var facetNormals = this.getFacetLocalNormals();\n var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);\n if (!facetsInBlock) {\n return null;\n }\n // Get the closest facet to (x, y, z)\n var shortest = Number.MAX_VALUE; // init distance vars\n var tmpDistance = shortest;\n var fib; // current facet in the block\n var norm; // current facet normal\n var p0; // current facet barycenter position\n // loop on all the facets in the current partitioning block\n for (var idx = 0; idx < facetsInBlock.length; idx++) {\n fib = facetsInBlock[idx];\n norm = facetNormals[fib];\n p0 = facetPositions[fib];\n d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;\n if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {\n // compute (x,y,z) projection on the facet = (projx, projy, projz)\n d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;\n t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);\n projx = x + norm.x * t0;\n projy = y + norm.y * t0;\n projz = z + norm.z * t0;\n tmpx = projx - x;\n tmpy = projy - y;\n tmpz = projz - z;\n tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet\n if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)\n shortest = tmpDistance;\n closest = fib;\n if (projected) {\n projected.x = projx;\n projected.y = projy;\n projected.z = projz;\n }\n }\n }\n }\n return closest;\n };\n /**\n * Returns the object \"parameter\" set with all the expected parameters for facetData computation by ComputeNormals()\n * @returns the parameters\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.getFacetDataParameters = function () {\n return this._facetParameters;\n };\n /**\n * Disables the feature FacetData and frees the related memory\n * @returns the current mesh\n * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata\n */\n AbstractMesh.prototype.disableFacetData = function () {\n if (this._facetDataEnabled) {\n this._facetDataEnabled = false;\n this._facetPositions = new Array();\n this._facetNormals = new Array();\n this._facetPartitioning = new Array();\n this._facetParameters = null;\n this._depthSortedIndices = new Uint32Array(0);\n }\n return this;\n };\n /**\n * Updates the AbstractMesh indices array\n * @param indices defines the data source\n * @returns the current mesh\n */\n AbstractMesh.prototype.updateIndices = function (indices) {\n return this;\n };\n /**\n * Creates new normals data for the mesh\n * @param updatable defines if the normal vertex buffer must be flagged as updatable\n * @returns the current mesh\n */\n AbstractMesh.prototype.createNormals = function (updatable) {\n var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var indices = this.getIndices();\n var normals;\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n }\n else {\n normals = [];\n }\n BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });\n this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);\n return this;\n };\n /**\n * Align the mesh with a normal\n * @param normal defines the normal to use\n * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)\n * @returns the current mesh\n */\n AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {\n if (!upDirection) {\n upDirection = BABYLON.Axis.Y;\n }\n var axisX = BABYLON.Tmp.Vector3[0];\n var axisZ = BABYLON.Tmp.Vector3[1];\n BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);\n BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);\n if (this.rotationQuaternion) {\n BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);\n }\n else {\n BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);\n }\n return this;\n };\n /** @hidden */\n AbstractMesh.prototype._checkOcclusionQuery = function () {\n this._isOccluded = false;\n };\n /** No occlusion */\n AbstractMesh.OCCLUSION_TYPE_NONE = 0;\n /** Occlusion set to optimisitic */\n AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;\n /** Occlusion set to strict */\n AbstractMesh.OCCLUSION_TYPE_STRICT = 2;\n /** Use an accurante occlusion algorithm */\n AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;\n /** Use a conservative occlusion algorithm */\n AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;\n return AbstractMesh;\n }(BABYLON.TransformNode));\n BABYLON.AbstractMesh = AbstractMesh;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.abstractMesh.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Base class of all the lights in Babylon. It groups all the generic information about lights.\n * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.\n * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.\n */\n var Light = /** @class */ (function (_super) {\n __extends(Light, _super);\n /**\n * Creates a Light object in the scene.\n * Documentation : http://doc.babylonjs.com/tutorials/lights\n * @param name The firendly name of the light\n * @param scene The scene the light belongs too\n */\n function Light(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n /**\n * Diffuse gives the basic color to an object.\n */\n _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);\n /**\n * Specular produces a highlight color on an object.\n * Note: This is note affecting PBR materials.\n */\n _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);\n /**\n * Strength of the light.\n * Note: By default it is define in the framework own unit.\n * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.\n */\n _this.intensity = 1.0;\n /**\n * Defines how far from the source the light is impacting in scene units.\n * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.\n */\n _this.range = Number.MAX_VALUE;\n /**\n * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type\n * of light.\n */\n _this._photometricScale = 1.0;\n _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;\n _this._radius = 0.00001;\n /**\n * Defines the rendering priority of the lights. It can help in case of fallback or number of lights\n * exceeding the number allowed of the materials.\n */\n _this.renderPriority = 0;\n _this._shadowEnabled = true;\n _this._excludeWithLayerMask = 0;\n _this._includeOnlyWithLayerMask = 0;\n _this._lightmapMode = 0;\n /**\n * @hidden Internal use only.\n */\n _this._excludedMeshesIds = new Array();\n /**\n * @hidden Internal use only.\n */\n _this._includedOnlyMeshesIds = new Array();\n _this.getScene().addLight(_this);\n _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());\n _this._buildUniformLayout();\n _this.includedOnlyMeshes = new Array();\n _this.excludedMeshes = new Array();\n _this._resyncMeshes();\n return _this;\n }\n Object.defineProperty(Light.prototype, \"intensityMode\", {\n /**\n * Gets the photometric scale used to interpret the intensity.\n * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.\n */\n get: function () {\n return this._intensityMode;\n },\n /**\n * Sets the photometric scale used to interpret the intensity.\n * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.\n */\n set: function (value) {\n this._intensityMode = value;\n this._computePhotometricScale();\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(Light.prototype, \"radius\", {\n /**\n * Gets the light radius used by PBR Materials to simulate soft area lights.\n */\n get: function () {\n return this._radius;\n },\n /**\n * sets the light radius used by PBR Materials to simulate soft area lights.\n */\n set: function (value) {\n this._radius = value;\n this._computePhotometricScale();\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(Light.prototype, \"shadowEnabled\", {\n /**\n * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching\n * the current shadow generator.\n */\n get: function () {\n return this._shadowEnabled;\n },\n /**\n * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching\n * the current shadow generator.\n */\n set: function (value) {\n if (this._shadowEnabled === value) {\n return;\n }\n this._shadowEnabled = value;\n this._markMeshesAsLightDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Light.prototype, \"includedOnlyMeshes\", {\n /**\n * Gets the only meshes impacted by this light.\n */\n get: function () {\n return this._includedOnlyMeshes;\n },\n /**\n * Sets the only meshes impacted by this light.\n */\n set: function (value) {\n this._includedOnlyMeshes = value;\n this._hookArrayForIncludedOnly(value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Light.prototype, \"excludedMeshes\", {\n /**\n * Gets the meshes not impacted by this light.\n */\n get: function () {\n return this._excludedMeshes;\n },\n /**\n * Sets the meshes not impacted by this light.\n */\n set: function (value) {\n this._excludedMeshes = value;\n this._hookArrayForExcluded(value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Light.prototype, \"excludeWithLayerMask\", {\n /**\n * Gets the layer id use to find what meshes are not impacted by the light.\n * Inactive if 0\n */\n get: function () {\n return this._excludeWithLayerMask;\n },\n /**\n * Sets the layer id use to find what meshes are not impacted by the light.\n * Inactive if 0\n */\n set: function (value) {\n this._excludeWithLayerMask = value;\n this._resyncMeshes();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Light.prototype, \"includeOnlyWithLayerMask\", {\n /**\n * Gets the layer id use to find what meshes are impacted by the light.\n * Inactive if 0\n */\n get: function () {\n return this._includeOnlyWithLayerMask;\n },\n /**\n * Sets the layer id use to find what meshes are impacted by the light.\n * Inactive if 0\n */\n set: function (value) {\n this._includeOnlyWithLayerMask = value;\n this._resyncMeshes();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Light.prototype, \"lightmapMode\", {\n /**\n * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)\n */\n get: function () {\n return this._lightmapMode;\n },\n /**\n * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)\n */\n set: function (value) {\n if (this._lightmapMode === value) {\n return;\n }\n this._lightmapMode = value;\n this._markMeshesAsLightDirty();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"Light\".\n * @returns the class name\n */\n Light.prototype.getClassName = function () {\n return \"Light\";\n };\n /**\n * Converts the light information to a readable string for debug purpose.\n * @param fullDetails Supports for multiple levels of logging within scene loading\n * @returns the human readable light info\n */\n Light.prototype.toString = function (fullDetails) {\n var ret = \"Name: \" + this.name;\n ret += \", type: \" + ([\"Point\", \"Directional\", \"Spot\", \"Hemispheric\"])[this.getTypeID()];\n if (this.animations) {\n for (var i = 0; i < this.animations.length; i++) {\n ret += \", animation[0]: \" + this.animations[i].toString(fullDetails);\n }\n }\n if (fullDetails) {\n }\n return ret;\n };\n /**\n * Set the enabled state of this node.\n * @param value - the new enabled state\n */\n Light.prototype.setEnabled = function (value) {\n _super.prototype.setEnabled.call(this, value);\n this._resyncMeshes();\n };\n /**\n * Returns the Light associated shadow generator if any.\n * @return the associated shadow generator.\n */\n Light.prototype.getShadowGenerator = function () {\n return this._shadowGenerator;\n };\n /**\n * Returns a Vector3, the absolute light position in the World.\n * @returns the world space position of the light\n */\n Light.prototype.getAbsolutePosition = function () {\n return BABYLON.Vector3.Zero();\n };\n /**\n * Specifies if the light will affect the passed mesh.\n * @param mesh The mesh to test against the light\n * @return true the mesh is affected otherwise, false.\n */\n Light.prototype.canAffectMesh = function (mesh) {\n if (!mesh) {\n return true;\n }\n if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {\n return false;\n }\n if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {\n return false;\n }\n if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {\n return false;\n }\n if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {\n return false;\n }\n return true;\n };\n /**\n * Computes and Returns the light World matrix.\n * @returns the world matrix\n */\n Light.prototype.getWorldMatrix = function () {\n this._currentRenderId = this.getScene().getRenderId();\n this._childRenderId = this._currentRenderId;\n var worldMatrix = this._getWorldMatrix();\n if (this.parent && this.parent.getWorldMatrix) {\n if (!this._parentedWorldMatrix) {\n this._parentedWorldMatrix = BABYLON.Matrix.Identity();\n }\n worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);\n this._markSyncedWithParent();\n return this._parentedWorldMatrix;\n }\n return worldMatrix;\n };\n /**\n * Sort function to order lights for rendering.\n * @param a First Light object to compare to second.\n * @param b Second Light object to compare first.\n * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.\n */\n Light.CompareLightsPriority = function (a, b) {\n //shadow-casting lights have priority over non-shadow-casting lights\n //the renderPrioirty is a secondary sort criterion\n if (a.shadowEnabled !== b.shadowEnabled) {\n return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);\n }\n return b.renderPriority - a.renderPriority;\n };\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n if (this._shadowGenerator) {\n this._shadowGenerator.dispose();\n this._shadowGenerator = null;\n }\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from meshes\n for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n mesh._removeLightSource(this);\n }\n this._uniformBuffer.dispose();\n // Remove from scene\n this.getScene().removeLight(this);\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n /**\n * Returns the light type ID (integer).\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n Light.prototype.getTypeID = function () {\n return 0;\n };\n /**\n * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.\n * @returns the scaled intensity in intensity mode unit\n */\n Light.prototype.getScaledIntensity = function () {\n return this._photometricScale * this.intensity;\n };\n /**\n * Returns a new Light object, named \"name\", from the current one.\n * @param name The name of the cloned light\n * @returns the new created light\n */\n Light.prototype.clone = function (name) {\n var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());\n if (!constructor) {\n return null;\n }\n return BABYLON.SerializationHelper.Clone(constructor, this);\n };\n /**\n * Serializes the current light into a Serialization object.\n * @returns the serialized object.\n */\n Light.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n // Type\n serializationObject.type = this.getTypeID();\n // Parent\n if (this.parent) {\n serializationObject.parentId = this.parent.id;\n }\n // Inclusion / exclusions\n if (this.excludedMeshes.length > 0) {\n serializationObject.excludedMeshesIds = [];\n this.excludedMeshes.forEach(function (mesh) {\n serializationObject.excludedMeshesIds.push(mesh.id);\n });\n }\n if (this.includedOnlyMeshes.length > 0) {\n serializationObject.includedOnlyMeshesIds = [];\n this.includedOnlyMeshes.forEach(function (mesh) {\n serializationObject.includedOnlyMeshesIds.push(mesh.id);\n });\n }\n // Animations \n BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);\n serializationObject.ranges = this.serializeAnimationRanges();\n return serializationObject;\n };\n /**\n * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.\n * This new light is named \"name\" and added to the passed scene.\n * @param type Type according to the types available in Light.LIGHTTYPEID_x\n * @param name The friendly name of the light\n * @param scene The scene the new light will belong to\n * @returns the constructor function\n */\n Light.GetConstructorFromName = function (type, name, scene) {\n var constructorFunc = BABYLON.Node.Construct(\"Light_Type_\" + type, name, scene);\n if (constructorFunc) {\n return constructorFunc;\n }\n // Default to no light for none present once.\n return null;\n };\n /**\n * Parses the passed \"parsedLight\" and returns a new instanced Light from this parsing.\n * @param parsedLight The JSON representation of the light\n * @param scene The scene to create the parsed light in\n * @returns the created light after parsing\n */\n Light.Parse = function (parsedLight, scene) {\n var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);\n if (!constructor) {\n return null;\n }\n var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);\n // Inclusion / exclusions\n if (parsedLight.excludedMeshesIds) {\n light._excludedMeshesIds = parsedLight.excludedMeshesIds;\n }\n if (parsedLight.includedOnlyMeshesIds) {\n light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;\n }\n // Parent\n if (parsedLight.parentId) {\n light._waitingParentId = parsedLight.parentId;\n }\n // Animations\n if (parsedLight.animations) {\n for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {\n var parsedAnimation = parsedLight.animations[animationIndex];\n light.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);\n }\n if (parsedLight.autoAnimate) {\n scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);\n }\n return light;\n };\n Light.prototype._hookArrayForExcluded = function (array) {\n var _this = this;\n var oldPush = array.push;\n array.push = function () {\n var items = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n items[_i] = arguments[_i];\n }\n var result = oldPush.apply(array, items);\n for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {\n var item = items_1[_a];\n item._resyncLighSource(_this);\n }\n return result;\n };\n var oldSplice = array.splice;\n array.splice = function (index, deleteCount) {\n var deleted = oldSplice.apply(array, [index, deleteCount]);\n for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {\n var item = deleted_1[_i];\n item._resyncLighSource(_this);\n }\n return deleted;\n };\n for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {\n var item = array_1[_i];\n item._resyncLighSource(this);\n }\n };\n Light.prototype._hookArrayForIncludedOnly = function (array) {\n var _this = this;\n var oldPush = array.push;\n array.push = function () {\n var items = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n items[_i] = arguments[_i];\n }\n var result = oldPush.apply(array, items);\n _this._resyncMeshes();\n return result;\n };\n var oldSplice = array.splice;\n array.splice = function (index, deleteCount) {\n var deleted = oldSplice.apply(array, [index, deleteCount]);\n _this._resyncMeshes();\n return deleted;\n };\n this._resyncMeshes();\n };\n Light.prototype._resyncMeshes = function () {\n for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n mesh._resyncLighSource(this);\n }\n };\n /**\n * Forces the meshes to update their light related information in their rendering used effects\n * @hidden Internal Use Only\n */\n Light.prototype._markMeshesAsLightDirty = function () {\n for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n if (mesh._lightSources.indexOf(this) !== -1) {\n mesh._markSubMeshesAsLightDirty();\n }\n }\n };\n /**\n * Recomputes the cached photometric scale if needed.\n */\n Light.prototype._computePhotometricScale = function () {\n this._photometricScale = this._getPhotometricScale();\n this.getScene().resetCachedMaterial();\n };\n /**\n * Returns the Photometric Scale according to the light type and intensity mode.\n */\n Light.prototype._getPhotometricScale = function () {\n var photometricScale = 0.0;\n var lightTypeID = this.getTypeID();\n //get photometric mode\n var photometricMode = this.intensityMode;\n if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {\n if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {\n photometricMode = Light.INTENSITYMODE_ILLUMINANCE;\n }\n else {\n photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;\n }\n }\n //compute photometric scale\n switch (lightTypeID) {\n case Light.LIGHTTYPEID_POINTLIGHT:\n case Light.LIGHTTYPEID_SPOTLIGHT:\n switch (photometricMode) {\n case Light.INTENSITYMODE_LUMINOUSPOWER:\n photometricScale = 1.0 / (4.0 * Math.PI);\n break;\n case Light.INTENSITYMODE_LUMINOUSINTENSITY:\n photometricScale = 1.0;\n break;\n case Light.INTENSITYMODE_LUMINANCE:\n photometricScale = this.radius * this.radius;\n break;\n }\n break;\n case Light.LIGHTTYPEID_DIRECTIONALLIGHT:\n switch (photometricMode) {\n case Light.INTENSITYMODE_ILLUMINANCE:\n photometricScale = 1.0;\n break;\n case Light.INTENSITYMODE_LUMINANCE:\n // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.\n // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).\n var apexAngleRadians = this.radius;\n // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).\n apexAngleRadians = Math.max(apexAngleRadians, 0.001);\n var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));\n photometricScale = solidAngle;\n break;\n }\n break;\n case Light.LIGHTTYPEID_HEMISPHERICLIGHT:\n // No fall off in hemisperic light.\n photometricScale = 1.0;\n break;\n }\n return photometricScale;\n };\n /**\n * Reorder the light in the scene according to their defined priority.\n * @hidden Internal Use Only\n */\n Light.prototype._reorderLightsInScene = function () {\n var scene = this.getScene();\n if (this._renderPriority != 0) {\n scene.requireLightSorting = true;\n }\n this.getScene().sortLightsByPriority();\n };\n //lightmapMode Consts\n /**\n * If every light affecting the material is in this lightmapMode,\n * material.lightmapTexture adds or multiplies\n * (depends on material.useLightmapAsShadowmap)\n * after every other light calculations.\n */\n Light.LIGHTMAP_DEFAULT = 0;\n /**\n * material.lightmapTexture as only diffuse lighting from this light\n * adds only specular lighting from this light\n * adds dynamic shadows\n */\n Light.LIGHTMAP_SPECULAR = 1;\n /**\n * material.lightmapTexture as only lighting\n * no light calculation from this light\n * only adds dynamic shadows from this light\n */\n Light.LIGHTMAP_SHADOWSONLY = 2;\n // Intensity Mode Consts\n /**\n * Each light type uses the default quantity according to its type:\n * point/spot lights use luminous intensity\n * directional lights use illuminance\n */\n Light.INTENSITYMODE_AUTOMATIC = 0;\n /**\n * lumen (lm)\n */\n Light.INTENSITYMODE_LUMINOUSPOWER = 1;\n /**\n * candela (lm/sr)\n */\n Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;\n /**\n * lux (lm/m^2)\n */\n Light.INTENSITYMODE_ILLUMINANCE = 3;\n /**\n * nit (cd/m^2)\n */\n Light.INTENSITYMODE_LUMINANCE = 4;\n // Light types ids const.\n /**\n * Light type const id of the point light.\n */\n Light.LIGHTTYPEID_POINTLIGHT = 0;\n /**\n * Light type const id of the directional light.\n */\n Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;\n /**\n * Light type const id of the spot light.\n */\n Light.LIGHTTYPEID_SPOTLIGHT = 2;\n /**\n * Light type const id of the hemispheric light.\n */\n Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;\n __decorate([\n BABYLON.serializeAsColor3()\n ], Light.prototype, \"diffuse\", void 0);\n __decorate([\n BABYLON.serializeAsColor3()\n ], Light.prototype, \"specular\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Light.prototype, \"intensity\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Light.prototype, \"range\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Light.prototype, \"intensityMode\", null);\n __decorate([\n BABYLON.serialize()\n ], Light.prototype, \"radius\", null);\n __decorate([\n BABYLON.serialize()\n ], Light.prototype, \"_renderPriority\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_reorderLightsInScene\")\n ], Light.prototype, \"renderPriority\", void 0);\n __decorate([\n BABYLON.serialize(\"shadowEnabled\")\n ], Light.prototype, \"_shadowEnabled\", void 0);\n __decorate([\n BABYLON.serialize(\"excludeWithLayerMask\")\n ], Light.prototype, \"_excludeWithLayerMask\", void 0);\n __decorate([\n BABYLON.serialize(\"includeOnlyWithLayerMask\")\n ], Light.prototype, \"_includeOnlyWithLayerMask\", void 0);\n __decorate([\n BABYLON.serialize(\"lightmapMode\")\n ], Light.prototype, \"_lightmapMode\", void 0);\n return Light;\n }(BABYLON.Node));\n BABYLON.Light = Light;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.light.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var Camera = /** @class */ (function (_super) {\n __extends(Camera, _super);\n function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {\n if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }\n var _this = _super.call(this, name, scene) || this;\n /**\n * The vector the camera should consider as up.\n * (default is Vector3(0, 1, 0) aka Vector3.Up())\n */\n _this.upVector = BABYLON.Vector3.Up();\n _this.orthoLeft = null;\n _this.orthoRight = null;\n _this.orthoBottom = null;\n _this.orthoTop = null;\n /**\n * FOV is set in Radians. (default is 0.8)\n */\n _this.fov = 0.8;\n _this.minZ = 1;\n _this.maxZ = 10000.0;\n _this.inertia = 0.9;\n _this.mode = Camera.PERSPECTIVE_CAMERA;\n _this.isIntermediate = false;\n _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);\n /**\n * Restricts the camera to viewing objects with the same layerMask.\n * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0\n */\n _this.layerMask = 0x0FFFFFFF;\n /**\n * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)\n */\n _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;\n // Camera rig members\n _this.cameraRigMode = Camera.RIG_MODE_NONE;\n _this._rigCameras = new Array();\n _this._webvrViewMatrix = BABYLON.Matrix.Identity();\n _this._skipRendering = false;\n _this.customRenderTargets = new Array();\n // Observables\n _this.onViewMatrixChangedObservable = new BABYLON.Observable();\n _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();\n _this.onAfterCheckInputsObservable = new BABYLON.Observable();\n _this.onRestoreStateObservable = new BABYLON.Observable();\n // Cache\n _this._computedViewMatrix = BABYLON.Matrix.Identity();\n _this._projectionMatrix = new BABYLON.Matrix();\n _this._doNotComputeProjectionMatrix = false;\n _this._worldMatrix = BABYLON.Matrix.Identity();\n _this._postProcesses = new Array();\n _this._transformMatrix = BABYLON.Matrix.Zero();\n _this._activeMeshes = new BABYLON.SmartArray(256);\n _this._globalPosition = BABYLON.Vector3.Zero();\n _this._refreshFrustumPlanes = true;\n _this.getScene().addCamera(_this);\n if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {\n _this.getScene().activeCamera = _this;\n }\n _this.position = position;\n return _this;\n }\n Object.defineProperty(Camera, \"PERSPECTIVE_CAMERA\", {\n get: function () {\n return Camera._PERSPECTIVE_CAMERA;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"ORTHOGRAPHIC_CAMERA\", {\n get: function () {\n return Camera._ORTHOGRAPHIC_CAMERA;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"FOVMODE_VERTICAL_FIXED\", {\n /**\n * This is the default FOV mode for perspective cameras.\n * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.\n *\n */\n get: function () {\n return Camera._FOVMODE_VERTICAL_FIXED;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"FOVMODE_HORIZONTAL_FIXED\", {\n /**\n * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.\n *\n */\n get: function () {\n return Camera._FOVMODE_HORIZONTAL_FIXED;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_NONE\", {\n get: function () {\n return Camera._RIG_MODE_NONE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_STEREOSCOPIC_ANAGLYPH\", {\n get: function () {\n return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL\", {\n get: function () {\n return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED\", {\n get: function () {\n return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_STEREOSCOPIC_OVERUNDER\", {\n get: function () {\n return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_VR\", {\n get: function () {\n return Camera._RIG_MODE_VR;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera, \"RIG_MODE_WEBVR\", {\n get: function () {\n return Camera._RIG_MODE_WEBVR;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Store current camera state (fov, position, etc..)\n */\n Camera.prototype.storeState = function () {\n this._stateStored = true;\n this._storedFov = this.fov;\n return this;\n };\n /**\n * Restores the camera state values if it has been stored. You must call storeState() first\n */\n Camera.prototype._restoreStateValues = function () {\n if (!this._stateStored) {\n return false;\n }\n this.fov = this._storedFov;\n return true;\n };\n /**\n * Restored camera state. You must call storeState() first\n */\n Camera.prototype.restoreState = function () {\n if (this._restoreStateValues()) {\n this.onRestoreStateObservable.notifyObservers(this);\n return true;\n }\n return false;\n };\n Camera.prototype.getClassName = function () {\n return \"Camera\";\n };\n /**\n * @param {boolean} fullDetails - support for multiple levels of logging within scene loading\n */\n Camera.prototype.toString = function (fullDetails) {\n var ret = \"Name: \" + this.name;\n ret += \", type: \" + this.getClassName();\n if (this.animations) {\n for (var i = 0; i < this.animations.length; i++) {\n ret += \", animation[0]: \" + this.animations[i].toString(fullDetails);\n }\n }\n if (fullDetails) {\n }\n return ret;\n };\n Object.defineProperty(Camera.prototype, \"globalPosition\", {\n get: function () {\n return this._globalPosition;\n },\n enumerable: true,\n configurable: true\n });\n Camera.prototype.getActiveMeshes = function () {\n return this._activeMeshes;\n };\n Camera.prototype.isActiveMesh = function (mesh) {\n return (this._activeMeshes.indexOf(mesh) !== -1);\n };\n /**\n * Is this camera ready to be used/rendered\n * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)\n * @return true if the camera is ready\n */\n Camera.prototype.isReady = function (completeCheck) {\n if (completeCheck === void 0) { completeCheck = false; }\n if (completeCheck) {\n for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {\n var pp = _a[_i];\n if (pp && !pp.isReady()) {\n return false;\n }\n }\n }\n return _super.prototype.isReady.call(this, completeCheck);\n };\n //Cache\n Camera.prototype._initCache = function () {\n _super.prototype._initCache.call(this);\n this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.mode = undefined;\n this._cache.minZ = undefined;\n this._cache.maxZ = undefined;\n this._cache.fov = undefined;\n this._cache.fovMode = undefined;\n this._cache.aspectRatio = undefined;\n this._cache.orthoLeft = undefined;\n this._cache.orthoRight = undefined;\n this._cache.orthoBottom = undefined;\n this._cache.orthoTop = undefined;\n this._cache.renderWidth = undefined;\n this._cache.renderHeight = undefined;\n };\n Camera.prototype._updateCache = function (ignoreParentClass) {\n if (!ignoreParentClass) {\n _super.prototype._updateCache.call(this);\n }\n this._cache.position.copyFrom(this.position);\n this._cache.upVector.copyFrom(this.upVector);\n };\n // Synchronized\n Camera.prototype._isSynchronized = function () {\n return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();\n };\n Camera.prototype._isSynchronizedViewMatrix = function () {\n if (!_super.prototype._isSynchronized.call(this))\n return false;\n return this._cache.position.equals(this.position)\n && this._cache.upVector.equals(this.upVector)\n && this.isSynchronizedWithParent();\n };\n Camera.prototype._isSynchronizedProjectionMatrix = function () {\n var check = this._cache.mode === this.mode\n && this._cache.minZ === this.minZ\n && this._cache.maxZ === this.maxZ;\n if (!check) {\n return false;\n }\n var engine = this.getEngine();\n if (this.mode === Camera.PERSPECTIVE_CAMERA) {\n check = this._cache.fov === this.fov\n && this._cache.fovMode === this.fovMode\n && this._cache.aspectRatio === engine.getAspectRatio(this);\n }\n else {\n check = this._cache.orthoLeft === this.orthoLeft\n && this._cache.orthoRight === this.orthoRight\n && this._cache.orthoBottom === this.orthoBottom\n && this._cache.orthoTop === this.orthoTop\n && this._cache.renderWidth === engine.getRenderWidth()\n && this._cache.renderHeight === engine.getRenderHeight();\n }\n return check;\n };\n // Controls\n Camera.prototype.attachControl = function (element, noPreventDefault) {\n };\n Camera.prototype.detachControl = function (element) {\n };\n Camera.prototype.update = function () {\n this._checkInputs();\n if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n this._updateRigCameras();\n }\n };\n Camera.prototype._checkInputs = function () {\n this.onAfterCheckInputsObservable.notifyObservers(this);\n };\n Object.defineProperty(Camera.prototype, \"rigCameras\", {\n get: function () {\n return this._rigCameras;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera.prototype, \"rigPostProcess\", {\n get: function () {\n return this._rigPostProcess;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Internal, gets the first post proces.\n * @returns the first post process to be run on this camera.\n */\n Camera.prototype._getFirstPostProcess = function () {\n for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {\n if (this._postProcesses[ppIndex] !== null) {\n return this._postProcesses[ppIndex];\n }\n }\n return null;\n };\n Camera.prototype._cascadePostProcessesToRigCams = function () {\n // invalidate framebuffer\n var firstPostProcess = this._getFirstPostProcess();\n if (firstPostProcess) {\n firstPostProcess.markTextureDirty();\n }\n // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera\n for (var i = 0, len = this._rigCameras.length; i < len; i++) {\n var cam = this._rigCameras[i];\n var rigPostProcess = cam._rigPostProcess;\n // for VR rig, there does not have to be a post process\n if (rigPostProcess) {\n var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;\n if (isPass) {\n // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses\n cam.isIntermediate = this._postProcesses.length === 0;\n }\n cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);\n rigPostProcess.markTextureDirty();\n }\n else {\n cam._postProcesses = this._postProcesses.slice(0);\n }\n }\n };\n Camera.prototype.attachPostProcess = function (postProcess, insertAt) {\n if (insertAt === void 0) { insertAt = null; }\n if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {\n BABYLON.Tools.Error(\"You're trying to reuse a post process not defined as reusable.\");\n return 0;\n }\n if (insertAt == null || insertAt < 0) {\n this._postProcesses.push(postProcess);\n }\n else if (this._postProcesses[insertAt] === null) {\n this._postProcesses[insertAt] = postProcess;\n }\n else {\n this._postProcesses.splice(insertAt, 0, postProcess);\n }\n this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated\n return this._postProcesses.indexOf(postProcess);\n };\n Camera.prototype.detachPostProcess = function (postProcess) {\n var idx = this._postProcesses.indexOf(postProcess);\n if (idx !== -1) {\n this._postProcesses[idx] = null;\n }\n this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated\n };\n Camera.prototype.getWorldMatrix = function () {\n if (this._isSynchronizedViewMatrix()) {\n return this._worldMatrix;\n }\n // Getting the the view matrix will also compute the world matrix.\n this.getViewMatrix();\n return this._worldMatrix;\n };\n Camera.prototype._getViewMatrix = function () {\n return BABYLON.Matrix.Identity();\n };\n Camera.prototype.getViewMatrix = function (force) {\n if (!force && this._isSynchronizedViewMatrix()) {\n return this._computedViewMatrix;\n }\n this.updateCache();\n this._computedViewMatrix = this._getViewMatrix();\n this._currentRenderId = this.getScene().getRenderId();\n this._childRenderId = this._currentRenderId;\n this._refreshFrustumPlanes = true;\n if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {\n this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);\n }\n this.onViewMatrixChangedObservable.notifyObservers(this);\n this._computedViewMatrix.invertToRef(this._worldMatrix);\n return this._computedViewMatrix;\n };\n Camera.prototype.freezeProjectionMatrix = function (projection) {\n this._doNotComputeProjectionMatrix = true;\n if (projection !== undefined) {\n this._projectionMatrix = projection;\n }\n };\n ;\n Camera.prototype.unfreezeProjectionMatrix = function () {\n this._doNotComputeProjectionMatrix = false;\n };\n ;\n Camera.prototype.getProjectionMatrix = function (force) {\n if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {\n return this._projectionMatrix;\n }\n // Cache\n this._cache.mode = this.mode;\n this._cache.minZ = this.minZ;\n this._cache.maxZ = this.maxZ;\n // Matrix\n this._refreshFrustumPlanes = true;\n var engine = this.getEngine();\n var scene = this.getScene();\n if (this.mode === Camera.PERSPECTIVE_CAMERA) {\n this._cache.fov = this.fov;\n this._cache.fovMode = this.fovMode;\n this._cache.aspectRatio = engine.getAspectRatio(this);\n if (this.minZ <= 0) {\n this.minZ = 0.1;\n }\n if (scene.useRightHandedSystem) {\n BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);\n }\n else {\n BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);\n }\n }\n else {\n var halfWidth = engine.getRenderWidth() / 2.0;\n var halfHeight = engine.getRenderHeight() / 2.0;\n if (scene.useRightHandedSystem) {\n BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);\n }\n else {\n BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);\n }\n this._cache.orthoLeft = this.orthoLeft;\n this._cache.orthoRight = this.orthoRight;\n this._cache.orthoBottom = this.orthoBottom;\n this._cache.orthoTop = this.orthoTop;\n this._cache.renderWidth = engine.getRenderWidth();\n this._cache.renderHeight = engine.getRenderHeight();\n }\n this.onProjectionMatrixChangedObservable.notifyObservers(this);\n return this._projectionMatrix;\n };\n /**\n * Gets the transformation matrix (ie. the multiplication of view by projection matrices)\n * @returns a Matrix\n */\n Camera.prototype.getTransformationMatrix = function () {\n this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);\n return this._transformMatrix;\n };\n Camera.prototype.updateFrustumPlanes = function () {\n if (!this._refreshFrustumPlanes) {\n return;\n }\n this.getTransformationMatrix();\n if (!this._frustumPlanes) {\n this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);\n }\n else {\n BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);\n }\n this._refreshFrustumPlanes = false;\n };\n Camera.prototype.isInFrustum = function (target) {\n this.updateFrustumPlanes();\n return target.isInFrustum(this._frustumPlanes);\n };\n Camera.prototype.isCompletelyInFrustum = function (target) {\n this.updateFrustumPlanes();\n return target.isCompletelyInFrustum(this._frustumPlanes);\n };\n Camera.prototype.getForwardRay = function (length, transform, origin) {\n if (length === void 0) { length = 100; }\n if (!transform) {\n transform = this.getWorldMatrix();\n }\n if (!origin) {\n origin = this.position;\n }\n var forward = new BABYLON.Vector3(0, 0, 1);\n var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);\n var direction = BABYLON.Vector3.Normalize(forwardWorld);\n return new BABYLON.Ray(origin, direction, length);\n };\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n // Observables\n this.onViewMatrixChangedObservable.clear();\n this.onProjectionMatrixChangedObservable.clear();\n this.onAfterCheckInputsObservable.clear();\n this.onRestoreStateObservable.clear();\n // Inputs\n if (this.inputs) {\n this.inputs.clear();\n }\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from scene\n this.getScene().removeCamera(this);\n while (this._rigCameras.length > 0) {\n var camera = this._rigCameras.pop();\n if (camera) {\n camera.dispose();\n }\n }\n // Postprocesses\n if (this._rigPostProcess) {\n this._rigPostProcess.dispose(this);\n this._rigPostProcess = null;\n this._postProcesses = [];\n }\n else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n this._rigPostProcess = null;\n this._postProcesses = [];\n }\n else {\n var i = this._postProcesses.length;\n while (--i >= 0) {\n var postProcess = this._postProcesses[i];\n if (postProcess) {\n postProcess.dispose(this);\n }\n }\n }\n // Render targets\n var i = this.customRenderTargets.length;\n while (--i >= 0) {\n this.customRenderTargets[i].dispose();\n }\n this.customRenderTargets = [];\n // Active Meshes\n this._activeMeshes.dispose();\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n Object.defineProperty(Camera.prototype, \"leftCamera\", {\n // ---- Camera rigs section ----\n get: function () {\n if (this._rigCameras.length < 1) {\n return null;\n }\n return this._rigCameras[0];\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Camera.prototype, \"rightCamera\", {\n get: function () {\n if (this._rigCameras.length < 2) {\n return null;\n }\n return this._rigCameras[1];\n },\n enumerable: true,\n configurable: true\n });\n Camera.prototype.getLeftTarget = function () {\n if (this._rigCameras.length < 1) {\n return null;\n }\n return this._rigCameras[0].getTarget();\n };\n Camera.prototype.getRightTarget = function () {\n if (this._rigCameras.length < 2) {\n return null;\n }\n return this._rigCameras[1].getTarget();\n };\n Camera.prototype.setCameraRigMode = function (mode, rigParams) {\n if (this.cameraRigMode === mode) {\n return;\n }\n while (this._rigCameras.length > 0) {\n var camera = this._rigCameras.pop();\n if (camera) {\n camera.dispose();\n }\n }\n this.cameraRigMode = mode;\n this._cameraRigParams = {};\n //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,\n //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced\n this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;\n this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);\n // create the rig cameras, unless none\n if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n var leftCamera = this.createRigCamera(this.name + \"_L\", 0);\n var rightCamera = this.createRigCamera(this.name + \"_R\", 1);\n if (leftCamera && rightCamera) {\n this._rigCameras.push(leftCamera);\n this._rigCameras.push(rightCamera);\n }\n }\n switch (this.cameraRigMode) {\n case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + \"_passthru\", 1.0, this._rigCameras[0]);\n this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + \"_anaglyph\", 1.0, this._rigCameras);\n break;\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;\n this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + \"_passthru\", 1.0, this._rigCameras[0]);\n this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + \"_stereoInterlace\", this._rigCameras, isStereoscopicHoriz);\n break;\n case Camera.RIG_MODE_VR:\n var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();\n this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;\n this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);\n this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();\n this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;\n this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;\n this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;\n this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;\n this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);\n this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();\n this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;\n this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;\n this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;\n if (metrics.compensateDistortion) {\n this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess(\"VR_Distort_Compensation_Left\", this._rigCameras[0], false, metrics);\n this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess(\"VR_Distort_Compensation_Right\", this._rigCameras[1], true, metrics);\n }\n break;\n case Camera.RIG_MODE_WEBVR:\n if (rigParams.vrDisplay) {\n var leftEye = rigParams.vrDisplay.getEyeParameters('left');\n var rightEye = rigParams.vrDisplay.getEyeParameters('right');\n //Left eye\n this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);\n this._rigCameras[0].setCameraRigParameter(\"left\", true);\n //leaving this for future reference\n this._rigCameras[0].setCameraRigParameter(\"specs\", rigParams.specs);\n this._rigCameras[0].setCameraRigParameter(\"eyeParameters\", leftEye);\n this._rigCameras[0].setCameraRigParameter(\"frameData\", rigParams.frameData);\n this._rigCameras[0].setCameraRigParameter(\"parentCamera\", rigParams.parentCamera);\n this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();\n this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;\n this._rigCameras[0].parent = this;\n this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;\n //Right eye\n this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);\n this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);\n this._rigCameras[1].setCameraRigParameter(\"specs\", rigParams.specs);\n this._rigCameras[1].setCameraRigParameter(\"frameData\", rigParams.frameData);\n this._rigCameras[1].setCameraRigParameter(\"parentCamera\", rigParams.parentCamera);\n this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();\n this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;\n this._rigCameras[1].parent = this;\n this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;\n if (Camera.UseAlternateWebVRRendering) {\n this._rigCameras[1]._skipRendering = true;\n this._rigCameras[0]._alternateCamera = this._rigCameras[1];\n }\n }\n break;\n }\n this._cascadePostProcessesToRigCams();\n this.update();\n };\n Camera.prototype._getVRProjectionMatrix = function () {\n BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);\n this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);\n return this._projectionMatrix;\n };\n Camera.prototype._updateCameraRotationMatrix = function () {\n //Here for WebVR\n };\n Camera.prototype._updateWebVRCameraRotationMatrix = function () {\n //Here for WebVR\n };\n /**\n * This function MUST be overwritten by the different WebVR cameras available.\n * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.\n */\n Camera.prototype._getWebVRProjectionMatrix = function () {\n return BABYLON.Matrix.Identity();\n };\n /**\n * This function MUST be overwritten by the different WebVR cameras available.\n * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.\n */\n Camera.prototype._getWebVRViewMatrix = function () {\n return BABYLON.Matrix.Identity();\n };\n Camera.prototype.setCameraRigParameter = function (name, value) {\n if (!this._cameraRigParams) {\n this._cameraRigParams = {};\n }\n this._cameraRigParams[name] = value;\n //provisionnally:\n if (name === \"interaxialDistance\") {\n this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);\n }\n };\n /**\n * needs to be overridden by children so sub has required properties to be copied\n */\n Camera.prototype.createRigCamera = function (name, cameraIndex) {\n return null;\n };\n /**\n * May need to be overridden by children\n */\n Camera.prototype._updateRigCameras = function () {\n for (var i = 0; i < this._rigCameras.length; i++) {\n this._rigCameras[i].minZ = this.minZ;\n this._rigCameras[i].maxZ = this.maxZ;\n this._rigCameras[i].fov = this.fov;\n }\n // only update viewport when ANAGLYPH\n if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {\n this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;\n }\n };\n Camera.prototype._setupInputs = function () {\n };\n Camera.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n // Type\n serializationObject.type = this.getClassName();\n // Parent\n if (this.parent) {\n serializationObject.parentId = this.parent.id;\n }\n if (this.inputs) {\n this.inputs.serialize(serializationObject);\n }\n // Animations\n BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);\n serializationObject.ranges = this.serializeAnimationRanges();\n return serializationObject;\n };\n Camera.prototype.clone = function (name) {\n return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);\n };\n Camera.prototype.getDirection = function (localAxis) {\n var result = BABYLON.Vector3.Zero();\n this.getDirectionToRef(localAxis, result);\n return result;\n };\n Camera.prototype.getDirectionToRef = function (localAxis, result) {\n BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);\n };\n Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {\n if (interaxial_distance === void 0) { interaxial_distance = 0; }\n if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }\n var constructorFunc = BABYLON.Node.Construct(type, name, scene, {\n interaxial_distance: interaxial_distance,\n isStereoscopicSideBySide: isStereoscopicSideBySide\n });\n if (constructorFunc) {\n return constructorFunc;\n }\n // Default to universal camera\n return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };\n };\n Camera.prototype.computeWorldMatrix = function () {\n return this.getWorldMatrix();\n };\n Camera.Parse = function (parsedCamera, scene) {\n var type = parsedCamera.type;\n var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);\n var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);\n // Parent\n if (parsedCamera.parentId) {\n camera._waitingParentId = parsedCamera.parentId;\n }\n //If camera has an input manager, let it parse inputs settings\n if (camera.inputs) {\n camera.inputs.parse(parsedCamera);\n camera._setupInputs();\n }\n if (camera.setPosition) { // need to force position\n camera.position.copyFromFloats(0, 0, 0);\n camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));\n }\n // Target\n if (parsedCamera.target) {\n if (camera.setTarget) {\n camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));\n }\n }\n // Apply 3d rig, when found\n if (parsedCamera.cameraRigMode) {\n var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};\n camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);\n }\n // Animations\n if (parsedCamera.animations) {\n for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {\n var parsedAnimation = parsedCamera.animations[animationIndex];\n camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);\n }\n if (parsedCamera.autoAnimate) {\n scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);\n }\n return camera;\n };\n // Statics\n Camera._PERSPECTIVE_CAMERA = 0;\n Camera._ORTHOGRAPHIC_CAMERA = 1;\n Camera._FOVMODE_VERTICAL_FIXED = 0;\n Camera._FOVMODE_HORIZONTAL_FIXED = 1;\n Camera._RIG_MODE_NONE = 0;\n Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;\n Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;\n Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;\n Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;\n Camera._RIG_MODE_VR = 20;\n Camera._RIG_MODE_WEBVR = 21;\n Camera.ForceAttachControlToAlwaysPreventDefault = false;\n Camera.UseAlternateWebVRRendering = false;\n __decorate([\n BABYLON.serializeAsVector3()\n ], Camera.prototype, \"position\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], Camera.prototype, \"upVector\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"orthoLeft\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"orthoRight\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"orthoBottom\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"orthoTop\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"fov\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"minZ\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"maxZ\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"inertia\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"mode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"layerMask\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"fovMode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"cameraRigMode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"interaxialDistance\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Camera.prototype, \"isStereoscopicSideBySide\", void 0);\n return Camera;\n }(BABYLON.Node));\n BABYLON.Camera = Camera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.camera.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var RenderingManager = /** @class */ (function () {\n function RenderingManager(scene) {\n /**\n * Hidden\n */\n this._useSceneAutoClearSetup = false;\n this._renderingGroups = new Array();\n this._autoClearDepthStencil = {};\n this._customOpaqueSortCompareFn = {};\n this._customAlphaTestSortCompareFn = {};\n this._customTransparentSortCompareFn = {};\n this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();\n this._scene = scene;\n for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {\n this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };\n }\n }\n RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {\n if (depth === void 0) { depth = true; }\n if (stencil === void 0) { stencil = true; }\n if (this._depthStencilBufferAlreadyCleaned) {\n return;\n }\n this._scene.getEngine().clear(null, false, depth, stencil);\n this._depthStencilBufferAlreadyCleaned = true;\n };\n RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {\n // Update the observable context (not null as it only goes away on dispose)\n var info = this._renderingGroupInfo;\n info.scene = this._scene;\n info.camera = this._scene.activeCamera;\n // Dispatch sprites\n if (renderSprites) {\n for (var index = 0; index < this._scene.spriteManagers.length; index++) {\n var manager = this._scene.spriteManagers[index];\n this.dispatchSprites(manager);\n }\n }\n // Render\n for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;\n var renderingGroup = this._renderingGroups[index];\n if (!renderingGroup)\n continue;\n var renderingGroupMask = Math.pow(2, index);\n info.renderingGroupId = index;\n // Before Observable\n this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);\n // Clear depth/stencil if needed\n if (RenderingManager.AUTOCLEAR) {\n var autoClear = this._useSceneAutoClearSetup ?\n this._scene.getAutoClearDepthStencilSetup(index) :\n this._autoClearDepthStencil[index];\n if (autoClear && autoClear.autoClear) {\n this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);\n }\n }\n // Render\n for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {\n var step = _a[_i];\n step.action(index);\n }\n renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);\n for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {\n var step = _c[_b];\n step.action(index);\n }\n // After Observable\n this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);\n }\n };\n RenderingManager.prototype.reset = function () {\n for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n var renderingGroup = this._renderingGroups[index];\n if (renderingGroup) {\n renderingGroup.prepare();\n }\n }\n };\n RenderingManager.prototype.dispose = function () {\n this.freeRenderingGroups();\n this._renderingGroups.length = 0;\n this._renderingGroupInfo = null;\n };\n /**\n * Clear the info related to rendering groups preventing retention points during dispose.\n */\n RenderingManager.prototype.freeRenderingGroups = function () {\n for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n var renderingGroup = this._renderingGroups[index];\n if (renderingGroup) {\n renderingGroup.dispose();\n }\n }\n };\n RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {\n if (this._renderingGroups[renderingGroupId] === undefined) {\n this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);\n }\n };\n RenderingManager.prototype.dispatchSprites = function (spriteManager) {\n var renderingGroupId = spriteManager.renderingGroupId || 0;\n this._prepareRenderingGroup(renderingGroupId);\n this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);\n };\n RenderingManager.prototype.dispatchParticles = function (particleSystem) {\n var renderingGroupId = particleSystem.renderingGroupId || 0;\n this._prepareRenderingGroup(renderingGroupId);\n this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);\n };\n /**\n * @param subMesh The submesh to dispatch\n * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.\n * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.\n */\n RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {\n if (mesh === undefined) {\n mesh = subMesh.getMesh();\n }\n var renderingGroupId = mesh.renderingGroupId || 0;\n this._prepareRenderingGroup(renderingGroupId);\n this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);\n };\n /**\n * Overrides the default sort function applied in the renderging group to prepare the meshes.\n * This allowed control for front to back rendering or reversly depending of the special needs.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param opaqueSortCompareFn The opaque queue comparison function use to sort.\n * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.\n * @param transparentSortCompareFn The transparent queue comparison function use to sort.\n */\n RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {\n if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }\n if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }\n if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }\n this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;\n this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;\n this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;\n if (this._renderingGroups[renderingGroupId]) {\n var group = this._renderingGroups[renderingGroupId];\n group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];\n group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];\n group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];\n }\n };\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n * @param depth Automatically clears depth between groups if true and autoClear is true.\n * @param stencil Automatically clears stencil between groups if true and autoClear is true.\n */\n RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {\n if (depth === void 0) { depth = true; }\n if (stencil === void 0) { stencil = true; }\n this._autoClearDepthStencil[renderingGroupId] = {\n autoClear: autoClearDepthStencil,\n depth: depth,\n stencil: stencil\n };\n };\n /**\n * Gets the current auto clear configuration for one rendering group of the rendering\n * manager.\n * @param index the rendering group index to get the information for\n * @returns The auto clear setup for the requested rendering group\n */\n RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {\n return this._autoClearDepthStencil[index];\n };\n /**\n * The max id used for rendering groups (not included)\n */\n RenderingManager.MAX_RENDERINGGROUPS = 4;\n /**\n * The min id used for rendering groups (included)\n */\n RenderingManager.MIN_RENDERINGGROUPS = 0;\n /**\n * Used to globally prevent autoclearing scenes.\n */\n RenderingManager.AUTOCLEAR = true;\n return RenderingManager;\n }());\n BABYLON.RenderingManager = RenderingManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.renderingManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var RenderingGroup = /** @class */ (function () {\n /**\n * Creates a new rendering group.\n * @param index The rendering group index\n * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied\n * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied\n * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied\n */\n function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {\n if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }\n if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }\n if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }\n this.index = index;\n this._opaqueSubMeshes = new BABYLON.SmartArray(256);\n this._transparentSubMeshes = new BABYLON.SmartArray(256);\n this._alphaTestSubMeshes = new BABYLON.SmartArray(256);\n this._depthOnlySubMeshes = new BABYLON.SmartArray(256);\n this._particleSystems = new BABYLON.SmartArray(256);\n this._spriteManagers = new BABYLON.SmartArray(256);\n this._edgesRenderers = new BABYLON.SmartArray(16);\n this._scene = scene;\n this.opaqueSortCompareFn = opaqueSortCompareFn;\n this.alphaTestSortCompareFn = alphaTestSortCompareFn;\n this.transparentSortCompareFn = transparentSortCompareFn;\n }\n Object.defineProperty(RenderingGroup.prototype, \"opaqueSortCompareFn\", {\n /**\n * Set the opaque sort comparison function.\n * If null the sub meshes will be render in the order they were created\n */\n set: function (value) {\n this._opaqueSortCompareFn = value;\n if (value) {\n this._renderOpaque = this.renderOpaqueSorted;\n }\n else {\n this._renderOpaque = RenderingGroup.renderUnsorted;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderingGroup.prototype, \"alphaTestSortCompareFn\", {\n /**\n * Set the alpha test sort comparison function.\n * If null the sub meshes will be render in the order they were created\n */\n set: function (value) {\n this._alphaTestSortCompareFn = value;\n if (value) {\n this._renderAlphaTest = this.renderAlphaTestSorted;\n }\n else {\n this._renderAlphaTest = RenderingGroup.renderUnsorted;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderingGroup.prototype, \"transparentSortCompareFn\", {\n /**\n * Set the transparent sort comparison function.\n * If null the sub meshes will be render in the order they were created\n */\n set: function (value) {\n if (value) {\n this._transparentSortCompareFn = value;\n }\n else {\n this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;\n }\n this._renderTransparent = this.renderTransparentSorted;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Render all the sub meshes contained in the group.\n * @param customRenderFunction Used to override the default render behaviour of the group.\n * @returns true if rendered some submeshes.\n */\n RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {\n if (customRenderFunction) {\n customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);\n return;\n }\n var engine = this._scene.getEngine();\n // Depth only\n if (this._depthOnlySubMeshes.length !== 0) {\n engine.setColorWrite(false);\n this._renderAlphaTest(this._depthOnlySubMeshes);\n engine.setColorWrite(true);\n }\n // Opaque\n if (this._opaqueSubMeshes.length !== 0) {\n this._renderOpaque(this._opaqueSubMeshes);\n }\n // Alpha test\n if (this._alphaTestSubMeshes.length !== 0) {\n this._renderAlphaTest(this._alphaTestSubMeshes);\n }\n var stencilState = engine.getStencilBuffer();\n engine.setStencilBuffer(false);\n // Sprites\n if (renderSprites) {\n this._renderSprites();\n }\n // Particles\n if (renderParticles) {\n this._renderParticles(activeMeshes);\n }\n if (this.onBeforeTransparentRendering) {\n this.onBeforeTransparentRendering();\n }\n // Transparent\n if (this._transparentSubMeshes.length !== 0) {\n this._renderTransparent(this._transparentSubMeshes);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n }\n // Set back stencil to false in case it changes before the edge renderer.\n engine.setStencilBuffer(false);\n // Edges\n for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {\n this._edgesRenderers.data[edgesRendererIndex].render();\n }\n // Restore Stencil state.\n engine.setStencilBuffer(stencilState);\n };\n /**\n * Renders the opaque submeshes in the order from the opaqueSortCompareFn.\n * @param subMeshes The submeshes to render\n */\n RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {\n return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);\n };\n /**\n * Renders the opaque submeshes in the order from the alphatestSortCompareFn.\n * @param subMeshes The submeshes to render\n */\n RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {\n return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);\n };\n /**\n * Renders the opaque submeshes in the order from the transparentSortCompareFn.\n * @param subMeshes The submeshes to render\n */\n RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {\n return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);\n };\n /**\n * Renders the submeshes in a specified order.\n * @param subMeshes The submeshes to sort before render\n * @param sortCompareFn The comparison function use to sort\n * @param cameraPosition The camera position use to preprocess the submeshes to help sorting\n * @param transparent Specifies to activate blending if true\n */\n RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {\n var subIndex = 0;\n var subMesh;\n var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();\n for (; subIndex < subMeshes.length; subIndex++) {\n subMesh = subMeshes.data[subIndex];\n subMesh._alphaIndex = subMesh.getMesh().alphaIndex;\n subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();\n }\n var sortedArray = subMeshes.data.slice(0, subMeshes.length);\n if (sortCompareFn) {\n sortedArray.sort(sortCompareFn);\n }\n for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {\n subMesh = sortedArray[subIndex];\n if (transparent) {\n var material = subMesh.getMaterial();\n if (material && material.needDepthPrePass) {\n var engine = material.getScene().getEngine();\n engine.setColorWrite(false);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n subMesh.render(false);\n engine.setColorWrite(true);\n }\n }\n subMesh.render(transparent);\n }\n };\n /**\n * Renders the submeshes in the order they were dispatched (no sort applied).\n * @param subMeshes The submeshes to render\n */\n RenderingGroup.renderUnsorted = function (subMeshes) {\n for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {\n var submesh = subMeshes.data[subIndex];\n submesh.render(false);\n }\n };\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are rendered back to front if in the same alpha index.\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n RenderingGroup.defaultTransparentSortCompare = function (a, b) {\n // Alpha index first\n if (a._alphaIndex > b._alphaIndex) {\n return 1;\n }\n if (a._alphaIndex < b._alphaIndex) {\n return -1;\n }\n // Then distance to camera\n return RenderingGroup.backToFrontSortCompare(a, b);\n };\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are rendered back to front.\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n RenderingGroup.backToFrontSortCompare = function (a, b) {\n // Then distance to camera\n if (a._distanceToCamera < b._distanceToCamera) {\n return 1;\n }\n if (a._distanceToCamera > b._distanceToCamera) {\n return -1;\n }\n return 0;\n };\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are rendered front to back (prevent overdraw).\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n RenderingGroup.frontToBackSortCompare = function (a, b) {\n // Then distance to camera\n if (a._distanceToCamera < b._distanceToCamera) {\n return -1;\n }\n if (a._distanceToCamera > b._distanceToCamera) {\n return 1;\n }\n return 0;\n };\n /**\n * Resets the different lists of submeshes to prepare a new frame.\n */\n RenderingGroup.prototype.prepare = function () {\n this._opaqueSubMeshes.reset();\n this._transparentSubMeshes.reset();\n this._alphaTestSubMeshes.reset();\n this._depthOnlySubMeshes.reset();\n this._particleSystems.reset();\n this._spriteManagers.reset();\n this._edgesRenderers.reset();\n };\n RenderingGroup.prototype.dispose = function () {\n this._opaqueSubMeshes.dispose();\n this._transparentSubMeshes.dispose();\n this._alphaTestSubMeshes.dispose();\n this._depthOnlySubMeshes.dispose();\n this._particleSystems.dispose();\n this._spriteManagers.dispose();\n this._edgesRenderers.dispose();\n };\n /**\n * Inserts the submesh in its correct queue depending on its material.\n * @param subMesh The submesh to dispatch\n * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.\n * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.\n */\n RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {\n // Get mesh and materials if not provided\n if (mesh === undefined) {\n mesh = subMesh.getMesh();\n }\n if (material === undefined) {\n material = subMesh.getMaterial();\n }\n if (material === null || material === undefined) {\n return;\n }\n if (material.needAlphaBlendingForMesh(mesh)) { // Transparent\n this._transparentSubMeshes.push(subMesh);\n }\n else if (material.needAlphaTesting()) { // Alpha test\n if (material.needDepthPrePass) {\n this._depthOnlySubMeshes.push(subMesh);\n }\n this._alphaTestSubMeshes.push(subMesh);\n }\n else {\n if (material.needDepthPrePass) {\n this._depthOnlySubMeshes.push(subMesh);\n }\n this._opaqueSubMeshes.push(subMesh); // Opaque\n }\n if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {\n this._edgesRenderers.push(mesh._edgesRenderer);\n }\n };\n RenderingGroup.prototype.dispatchSprites = function (spriteManager) {\n this._spriteManagers.push(spriteManager);\n };\n RenderingGroup.prototype.dispatchParticles = function (particleSystem) {\n this._particleSystems.push(particleSystem);\n };\n RenderingGroup.prototype._renderParticles = function (activeMeshes) {\n if (this._particleSystems.length === 0) {\n return;\n }\n // Particles\n var activeCamera = this._scene.activeCamera;\n this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);\n for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {\n var particleSystem = this._particleSystems.data[particleIndex];\n if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {\n continue;\n }\n var emitter = particleSystem.emitter;\n if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {\n this._scene._activeParticles.addCount(particleSystem.render(), false);\n }\n }\n this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);\n };\n RenderingGroup.prototype._renderSprites = function () {\n if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {\n return;\n }\n // Sprites \n var activeCamera = this._scene.activeCamera;\n this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);\n for (var id = 0; id < this._spriteManagers.length; id++) {\n var spriteManager = this._spriteManagers.data[id];\n if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {\n spriteManager.render();\n }\n }\n this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);\n };\n return RenderingGroup;\n }());\n BABYLON.RenderingGroup = RenderingGroup;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.renderingGroup.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Groups all the scene component constants in one place to ease maintenance.\n * @hidden\n */\n var SceneComponentConstants = /** @class */ (function () {\n function SceneComponentConstants() {\n }\n SceneComponentConstants.NAME_EFFECTLAYER = \"EffectLayer\";\n SceneComponentConstants.NAME_LAYER = \"Layer\";\n SceneComponentConstants.NAME_LENSFLARESYSTEM = \"LensFlareSystem\";\n SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = \"BoundingBoxRenderer\";\n SceneComponentConstants.NAME_PARTICLESYSTEM = \"ParticleSystem\";\n SceneComponentConstants.NAME_GAMEPAD = \"Gamepad\";\n SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;\n SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;\n SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;\n SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;\n SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;\n SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;\n SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;\n SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;\n SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;\n SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;\n SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;\n SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;\n SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;\n SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;\n return SceneComponentConstants;\n }());\n BABYLON.SceneComponentConstants = SceneComponentConstants;\n /**\n * Repressentation of a stage in the scene (Basically a list of ordered steps)\n * @hidden\n */\n var Stage = /** @class */ (function (_super) {\n __extends(Stage, _super);\n /**\n * Hide ctor from the rest of the world.\n * @param items The items to add.\n */\n function Stage(items) {\n return _super.apply(this, items) || this;\n }\n /**\n * Creates a new Stage.\n * @returns A new instance of a Stage\n */\n Stage.Create = function () {\n return Object.create(Stage.prototype);\n };\n /**\n * Registers a step in an ordered way in the targeted stage.\n * @param index Defines the position to register the step in\n * @param component Defines the component attached to the step\n * @param action Defines the action to launch during the step\n */\n Stage.prototype.registerStep = function (index, component, action) {\n var i = 0;\n var maxIndex = Number.MAX_VALUE;\n for (; i < this.length && i < maxIndex; i++) {\n var step = this[i];\n maxIndex = step.index;\n }\n this.splice(i, 0, { index: index, component: component, action: action.bind(component) });\n };\n /**\n * Clears all the steps from the stage.\n */\n Stage.prototype.clear = function () {\n this.length = 0;\n };\n return Stage;\n }(Array));\n BABYLON.Stage = Stage;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sceneComponent.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Base class of the scene acting as a container for the different elements composing a scene.\n * This class is dynamically extended by the different components of the scene increasing\n * flexibility and reducing coupling\n */\n var AbstractScene = /** @class */ (function () {\n function AbstractScene() {\n /** All of the cameras added to this scene\n * @see http://doc.babylonjs.com/babylon101/cameras\n */\n this.cameras = new Array();\n /**\n * All of the lights added to this scene\n * @see http://doc.babylonjs.com/babylon101/lights\n */\n this.lights = new Array();\n /**\n * All of the (abstract) meshes added to this scene\n */\n this.meshes = new Array();\n /**\n * The list of skeletons added to the scene\n * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons\n */\n this.skeletons = new Array();\n /**\n * All of the particle systems added to this scene\n * @see http://doc.babylonjs.com/babylon101/particles\n */\n this.particleSystems = new Array();\n /**\n * Gets a list of Animations associated with the scene\n */\n this.animations = [];\n /**\n * All of the animation groups added to this scene\n * @see http://doc.babylonjs.com/how_to/group\n */\n this.animationGroups = new Array();\n /**\n * All of the multi-materials added to this scene\n * @see http://doc.babylonjs.com/how_to/multi_materials\n */\n this.multiMaterials = new Array();\n /**\n * All of the materials added to this scene\n * @see http://doc.babylonjs.com/babylon101/materials\n */\n this.materials = new Array();\n /**\n * The list of morph target managers added to the scene\n * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh\n */\n this.morphTargetManagers = new Array();\n /**\n * The list of geometries used in the scene.\n */\n this.geometries = new Array();\n /**\n * All of the tranform nodes added to this scene\n * @see http://doc.babylonjs.com/how_to/transformnode\n */\n this.transformNodes = new Array();\n /**\n * ActionManagers available on the scene.\n */\n this.actionManagers = new Array();\n /**\n * Sounds to keep.\n */\n this.sounds = new Array();\n /**\n * Textures to keep.\n */\n this.textures = new Array();\n }\n /**\n * Adds a parser in the list of available ones\n * @param name Defines the name of the parser\n * @param parser Defines the parser to add\n */\n AbstractScene.AddParser = function (name, parser) {\n this._BabylonFileParsers[name] = parser;\n };\n /**\n * Gets a general parser from the list of avaialble ones\n * @param name Defines the name of the parser\n * @returns the requested parser or null\n */\n AbstractScene.GetParser = function (name) {\n if (this._BabylonFileParsers[name]) {\n return this._BabylonFileParsers[name];\n }\n return null;\n };\n /**\n * Adds n individual parser in the list of available ones\n * @param name Defines the name of the parser\n * @param parser Defines the parser to add\n */\n AbstractScene.AddIndividualParser = function (name, parser) {\n this._IndividualBabylonFileParsers[name] = parser;\n };\n /**\n * Gets an individual parser from the list of avaialble ones\n * @param name Defines the name of the parser\n * @returns the requested parser or null\n */\n AbstractScene.GetIndividualParser = function (name) {\n if (this._IndividualBabylonFileParsers[name]) {\n return this._IndividualBabylonFileParsers[name];\n }\n return null;\n };\n /**\n * Parser json data and populate both a scene and its associated container object\n * @param jsonData Defines the data to parse\n * @param scene Defines the scene to parse the data for\n * @param container Defines the container attached to the parsing sequence\n * @param rootUrl Defines the root url of the data\n */\n AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {\n for (var parserName in this._BabylonFileParsers) {\n if (this._BabylonFileParsers.hasOwnProperty(parserName)) {\n this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);\n }\n }\n };\n /**\n * Stores the list of available parsers in the application.\n */\n AbstractScene._BabylonFileParsers = {};\n /**\n * Stores the list of available individual parsers in the application.\n */\n AbstractScene._IndividualBabylonFileParsers = {};\n return AbstractScene;\n }());\n BABYLON.AbstractScene = AbstractScene;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.abstractScene.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /** @hidden */\n var ClickInfo = /** @class */ (function () {\n function ClickInfo() {\n this._singleClick = false;\n this._doubleClick = false;\n this._hasSwiped = false;\n this._ignore = false;\n }\n Object.defineProperty(ClickInfo.prototype, \"singleClick\", {\n get: function () {\n return this._singleClick;\n },\n set: function (b) {\n this._singleClick = b;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ClickInfo.prototype, \"doubleClick\", {\n get: function () {\n return this._doubleClick;\n },\n set: function (b) {\n this._doubleClick = b;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ClickInfo.prototype, \"hasSwiped\", {\n get: function () {\n return this._hasSwiped;\n },\n set: function (b) {\n this._hasSwiped = b;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ClickInfo.prototype, \"ignore\", {\n get: function () {\n return this._ignore;\n },\n set: function (b) {\n this._ignore = b;\n },\n enumerable: true,\n configurable: true\n });\n return ClickInfo;\n }());\n /**\n * This class is used by the onRenderingGroupObservable\n */\n var RenderingGroupInfo = /** @class */ (function () {\n function RenderingGroupInfo() {\n }\n return RenderingGroupInfo;\n }());\n BABYLON.RenderingGroupInfo = RenderingGroupInfo;\n /**\n * Represents a scene to be rendered by the engine.\n * @see http://doc.babylonjs.com/features/scene\n */\n var Scene = /** @class */ (function (_super) {\n __extends(Scene, _super);\n /**\n * Creates a new Scene\n * @param engine defines the engine to use to render this scene\n */\n function Scene(engine) {\n var _this = _super.call(this) || this;\n // Members\n /**\n * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame\n */\n _this.autoClear = true;\n /**\n * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame\n */\n _this.autoClearDepthAndStencil = true;\n /**\n * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))\n */\n _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);\n /**\n * Defines the color used to simulate the ambient color (Default is (0, 0, 0))\n */\n _this.ambientColor = new BABYLON.Color3(0, 0, 0);\n _this._forceWireframe = false;\n _this._forcePointsCloud = false;\n /**\n * Gets or sets a boolean indicating if animations are enabled\n */\n _this.animationsEnabled = true;\n _this._animationPropertiesOverride = null;\n /**\n * Gets or sets a boolean indicating if a constant deltatime has to be used\n * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate\n */\n _this.useConstantAnimationDeltaTime = false;\n /**\n * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated\n * Please note that it requires to run a ray cast through the scene on every frame\n */\n _this.constantlyUpdateMeshUnderPointer = false;\n /**\n * Defines the HTML cursor to use when hovering over interactive elements\n */\n _this.hoverCursor = \"pointer\";\n /**\n * Defines the HTML default cursor to use (empty by default)\n */\n _this.defaultCursor = \"\";\n /**\n * This is used to call preventDefault() on pointer down\n * in order to block unwanted artifacts like system double clicks\n */\n _this.preventDefaultOnPointerDown = true;\n // Metadata\n /**\n * Gets or sets user defined metadata\n */\n _this.metadata = null;\n /**\n * Use this array to add regular expressions used to disable offline support for specific urls\n */\n _this.disableOfflineSupportExceptionRules = new Array();\n /**\n * An event triggered when the scene is disposed.\n */\n _this.onDisposeObservable = new BABYLON.Observable();\n _this._onDisposeObserver = null;\n /**\n * An event triggered before rendering the scene (right after animations and physics)\n */\n _this.onBeforeRenderObservable = new BABYLON.Observable();\n _this._onBeforeRenderObserver = null;\n /**\n * An event triggered after rendering the scene\n */\n _this.onAfterRenderObservable = new BABYLON.Observable();\n _this._onAfterRenderObserver = null;\n /**\n * An event triggered before animating the scene\n */\n _this.onBeforeAnimationsObservable = new BABYLON.Observable();\n /**\n * An event triggered after animations processing\n */\n _this.onAfterAnimationsObservable = new BABYLON.Observable();\n /**\n * An event triggered before draw calls are ready to be sent\n */\n _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();\n /**\n * An event triggered after draw calls have been sent\n */\n _this.onAfterDrawPhaseObservable = new BABYLON.Observable();\n /**\n * An event triggered when physic simulation is about to be run\n */\n _this.onBeforePhysicsObservable = new BABYLON.Observable();\n /**\n * An event triggered when physic simulation has been done\n */\n _this.onAfterPhysicsObservable = new BABYLON.Observable();\n /**\n * An event triggered when the scene is ready\n */\n _this.onReadyObservable = new BABYLON.Observable();\n /**\n * An event triggered before rendering a camera\n */\n _this.onBeforeCameraRenderObservable = new BABYLON.Observable();\n _this._onBeforeCameraRenderObserver = null;\n /**\n * An event triggered after rendering a camera\n */\n _this.onAfterCameraRenderObservable = new BABYLON.Observable();\n _this._onAfterCameraRenderObserver = null;\n /**\n * An event triggered when active meshes evaluation is about to start\n */\n _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();\n /**\n * An event triggered when active meshes evaluation is done\n */\n _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();\n /**\n * An event triggered when particles rendering is about to start\n * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)\n */\n _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();\n /**\n * An event triggered when particles rendering is done\n * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)\n */\n _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();\n /**\n * An event triggered when sprites rendering is about to start\n * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)\n */\n _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();\n /**\n * An event triggered when sprites rendering is done\n * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)\n */\n _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();\n /**\n * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed\n */\n _this.onDataLoadedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a camera is created\n */\n _this.onNewCameraAddedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a camera is removed\n */\n _this.onCameraRemovedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a light is created\n */\n _this.onNewLightAddedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a light is removed\n */\n _this.onLightRemovedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a geometry is created\n */\n _this.onNewGeometryAddedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a geometry is removed\n */\n _this.onGeometryRemovedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a transform node is created\n */\n _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a transform node is removed\n */\n _this.onTransformNodeRemovedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a mesh is created\n */\n _this.onNewMeshAddedObservable = new BABYLON.Observable();\n /**\n * An event triggered when a mesh is removed\n */\n _this.onMeshRemovedObservable = new BABYLON.Observable();\n /**\n * An event triggered when render targets are about to be rendered\n * Can happen multiple times per frame.\n */\n _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered when render targets were rendered.\n * Can happen multiple times per frame.\n */\n _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered before calculating deterministic simulation step\n */\n _this.onBeforeStepObservable = new BABYLON.Observable();\n /**\n * An event triggered after calculating deterministic simulation step\n */\n _this.onAfterStepObservable = new BABYLON.Observable();\n /**\n * This Observable will be triggered before rendering each renderingGroup of each rendered camera.\n * The RenderinGroupInfo class contains all the information about the context in which the observable is called\n * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)\n */\n _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();\n /**\n * This Observable will be triggered after rendering each renderingGroup of each rendered camera.\n * The RenderinGroupInfo class contains all the information about the context in which the observable is called\n * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)\n */\n _this.onAfterRenderingGroupObservable = new BABYLON.Observable();\n // Animations\n _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);\n /**\n * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).\n * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true\n */\n _this.onPrePointerObservable = new BABYLON.Observable();\n /**\n * Observable event triggered each time an input event is received from the rendering canvas\n */\n _this.onPointerObservable = new BABYLON.Observable();\n _this._meshPickProceed = false;\n _this._currentPickResult = null;\n _this._previousPickResult = null;\n _this._totalPointersPressed = 0;\n _this._doubleClickOccured = false;\n /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */\n _this.cameraToUseForPointers = null;\n _this._pointerX = 0;\n _this._pointerY = 0;\n _this._startingPointerPosition = new BABYLON.Vector2(0, 0);\n _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);\n _this._startingPointerTime = 0;\n _this._previousStartingPointerTime = 0;\n _this._pointerCaptures = {};\n // Deterministic lockstep\n _this._timeAccumulator = 0;\n _this._currentStepId = 0;\n _this._currentInternalStep = 0;\n // Keyboard\n /**\n * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()\n * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true\n */\n _this.onPreKeyboardObservable = new BABYLON.Observable();\n /**\n * Observable event triggered each time an keyboard event is received from the hosting window\n */\n _this.onKeyboardObservable = new BABYLON.Observable();\n // Coordinates system\n _this._useRightHandedSystem = false;\n // Fog\n _this._fogEnabled = true;\n _this._fogMode = Scene.FOGMODE_NONE;\n /**\n * Gets or sets the fog color to use\n * @see http://doc.babylonjs.com/babylon101/environment#fog\n */\n _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);\n /**\n * Gets or sets the fog density to use\n * @see http://doc.babylonjs.com/babylon101/environment#fog\n */\n _this.fogDensity = 0.1;\n /**\n * Gets or sets the fog start distance to use\n * @see http://doc.babylonjs.com/babylon101/environment#fog\n */\n _this.fogStart = 0;\n /**\n * Gets or sets the fog end distance to use\n * @see http://doc.babylonjs.com/babylon101/environment#fog\n */\n _this.fogEnd = 1000.0;\n // Lights\n _this._shadowsEnabled = true;\n _this._lightsEnabled = true;\n /** All of the active cameras added to this scene. */\n _this.activeCameras = new Array();\n // Textures\n _this._texturesEnabled = true;\n // Particles\n /**\n * Gets or sets a boolean indicating if particles are enabled on this scene\n */\n _this.particlesEnabled = true;\n // Sprites\n /**\n * Gets or sets a boolean indicating if sprites are enabled on this scene\n */\n _this.spritesEnabled = true;\n /**\n * All of the sprite managers added to this scene\n * @see http://doc.babylonjs.com/babylon101/sprites\n */\n _this.spriteManagers = new Array();\n // Skeletons\n _this._skeletonsEnabled = true;\n // Lens flares\n /**\n * Gets or sets a boolean indicating if lens flares are enabled on this scene\n */\n _this.lensFlaresEnabled = true;\n // Collisions\n /**\n * Gets or sets a boolean indicating if collisions are enabled on this scene\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */\n _this.collisionsEnabled = true;\n /**\n * Defines the gravity applied to this scene (used only for collisions)\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */\n _this.gravity = new BABYLON.Vector3(0, -9.807, 0);\n // Postprocesses\n /**\n * Gets or sets a boolean indicating if postprocesses are enabled on this scene\n */\n _this.postProcessesEnabled = true;\n /**\n * The list of postprocesses added to the scene\n */\n _this.postProcesses = new Array();\n // Customs render targets\n /**\n * Gets or sets a boolean indicating if render targets are enabled on this scene\n */\n _this.renderTargetsEnabled = true;\n /**\n * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes\n * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com\n */\n _this.dumpNextRenderTargets = false;\n /**\n * The list of user defined render targets added to the scene\n */\n _this.customRenderTargets = new Array();\n /**\n * Gets the list of meshes imported to the scene through SceneLoader\n */\n _this.importedMeshesFiles = new Array();\n // Probes\n /**\n * Gets or sets a boolean indicating if probes are enabled on this scene\n */\n _this.probesEnabled = true;\n /**\n * The list of reflection probes added to the scene\n * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes\n */\n _this.reflectionProbes = new Array();\n _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);\n // Procedural textures\n /**\n * Gets or sets a boolean indicating if procedural textures are enabled on this scene\n */\n _this.proceduralTexturesEnabled = true;\n /**\n * The list of procedural textures added to the scene\n * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures\n */\n _this.proceduralTextures = new Array();\n /**\n * The list of sound tracks added to the scene\n * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music\n */\n _this.soundTracks = new Array();\n _this._audioEnabled = true;\n _this._headphone = false;\n // Performance counters\n _this._totalVertices = new BABYLON.PerfCounter();\n /** @hidden */\n _this._activeIndices = new BABYLON.PerfCounter();\n /** @hidden */\n _this._activeParticles = new BABYLON.PerfCounter();\n /** @hidden */\n _this._activeBones = new BABYLON.PerfCounter();\n _this._animationTime = 0;\n /**\n * Gets or sets a general scale for animation speed\n * @see https://www.babylonjs-playground.com/#IBU2W7#3\n */\n _this.animationTimeScale = 1;\n _this._renderId = 0;\n _this._executeWhenReadyTimeoutId = -1;\n _this._intermediateRendering = false;\n _this._viewUpdateFlag = -1;\n _this._projectionUpdateFlag = -1;\n _this._alternateViewUpdateFlag = -1;\n _this._alternateProjectionUpdateFlag = -1;\n /** @hidden */\n _this._toBeDisposed = new BABYLON.SmartArray(256);\n _this._activeRequests = new Array();\n _this._pendingData = new Array();\n _this._isDisposed = false;\n /**\n * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered\n * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)\n */\n _this.dispatchAllSubMeshesOfActiveMeshes = false;\n _this._activeMeshes = new BABYLON.SmartArray(256);\n _this._processedMaterials = new BABYLON.SmartArray(256);\n _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);\n /** @hidden */\n _this._activeParticleSystems = new BABYLON.SmartArray(256);\n _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);\n _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);\n /** @hidden */\n _this._activeAnimatables = new Array();\n _this._transformMatrix = BABYLON.Matrix.Zero();\n _this._useAlternateCameraConfiguration = false;\n _this._alternateRendering = false;\n /**\n * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)\n * This is useful if there are more lights that the maximum simulteanous authorized\n */\n _this.requireLightSorting = false;\n _this._depthRenderer = {};\n /**\n * Backing store of defined scene components.\n */\n _this._components = [];\n /**\n * Backing store of defined scene components.\n */\n _this._serializableComponents = [];\n /**\n * List of components to register on the next registration step.\n */\n _this._transientComponents = [];\n /**\n * Defines the actions happening before camera updates.\n */\n _this._beforeCameraUpdateStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening during the per mesh ready checks.\n */\n _this._isReadyForMeshStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening before evaluate active mesh checks.\n */\n _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening during the evaluate sub mesh checks.\n */\n _this._evaluateSubMeshStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening during the active mesh stage.\n */\n _this._activeMeshStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening during the per camera render target step.\n */\n _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening just before the active camera is drawing.\n */\n _this._beforeCameraDrawStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening just before a rendering group is drawing.\n */\n _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening just after a rendering group has been drawn.\n */\n _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();\n /**\n * Defines the actions happening just after the active camera has been drawn.\n */\n _this._afterCameraDrawStage = BABYLON.Stage.Create();\n _this._activeMeshesFrozen = false;\n /** @hidden */\n _this._allowPostProcessClear = true;\n _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;\n _this._engine = engine || BABYLON.Engine.LastCreatedEngine;\n _this._engine.scenes.push(_this);\n _this._uid = null;\n _this._renderingManager = new BABYLON.RenderingManager(_this);\n if (BABYLON.PostProcessManager) {\n _this.postProcessManager = new BABYLON.PostProcessManager(_this);\n }\n if (BABYLON.OutlineRenderer) {\n _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);\n }\n if (BABYLON.Tools.IsWindowObjectExist()) {\n _this.attachControl();\n }\n //simplification queue\n if (BABYLON.SimplificationQueue) {\n _this.simplificationQueue = new BABYLON.SimplificationQueue();\n }\n //collision coordinator initialization. For now legacy per default.\n _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));\n // Uniform Buffer\n _this._createUbo();\n // Default Image processing definition\n if (BABYLON.ImageProcessingConfiguration) {\n _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();\n }\n return _this;\n }\n Object.defineProperty(Scene, \"FOGMODE_NONE\", {\n /** The fog is deactivated */\n get: function () {\n return Scene._FOGMODE_NONE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene, \"FOGMODE_EXP\", {\n /** The fog density is following an exponential function */\n get: function () {\n return Scene._FOGMODE_EXP;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene, \"FOGMODE_EXP2\", {\n /** The fog density is following an exponential function faster than FOGMODE_EXP */\n get: function () {\n return Scene._FOGMODE_EXP2;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene, \"FOGMODE_LINEAR\", {\n /** The fog density is following a linear function. */\n get: function () {\n return Scene._FOGMODE_LINEAR;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"environmentTexture\", {\n /**\n * Texture used in all pbr material as the reflection texture.\n * As in the majority of the scene they are the same (exception for multi room and so on),\n * this is easier to reference from here than from all the materials.\n */\n get: function () {\n return this._environmentTexture;\n },\n /**\n * Texture used in all pbr material as the reflection texture.\n * As in the majority of the scene they are the same (exception for multi room and so on),\n * this is easier to set here than in all the materials.\n */\n set: function (value) {\n if (this._environmentTexture === value) {\n return;\n }\n this._environmentTexture = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"imageProcessingConfiguration\", {\n /**\n * Default image processing configuration used either in the rendering\n * Forward main pass or through the imageProcessingPostProcess if present.\n * As in the majority of the scene they are the same (exception for multi camera),\n * this is easier to reference from here than from all the materials and post process.\n *\n * No setter as we it is a shared configuration, you can set the values instead.\n */\n get: function () {\n return this._imageProcessingConfiguration;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"forceWireframe\", {\n get: function () {\n return this._forceWireframe;\n },\n /**\n * Gets or sets a boolean indicating if all rendering must be done in wireframe\n */\n set: function (value) {\n if (this._forceWireframe === value) {\n return;\n }\n this._forceWireframe = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"forcePointsCloud\", {\n get: function () {\n return this._forcePointsCloud;\n },\n /**\n * Gets or sets a boolean indicating if all rendering must be done in point cloud\n */\n set: function (value) {\n if (this._forcePointsCloud === value) {\n return;\n }\n this._forcePointsCloud = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"animationPropertiesOverride\", {\n /**\n * Gets or sets the animation properties override\n */\n get: function () {\n return this._animationPropertiesOverride;\n },\n set: function (value) {\n this._animationPropertiesOverride = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"onDispose\", {\n /** Sets a function to be executed when this scene is disposed. */\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"beforeRender\", {\n /** Sets a function to be executed before rendering this scene */\n set: function (callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n if (callback) {\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"afterRender\", {\n /** Sets a function to be executed after rendering this scene */\n set: function (callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n if (callback) {\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"beforeCameraRender\", {\n /** Sets a function to be executed before rendering a camera*/\n set: function (callback) {\n if (this._onBeforeCameraRenderObserver) {\n this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n }\n this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"afterCameraRender\", {\n /** Sets a function to be executed after rendering a camera*/\n set: function (callback) {\n if (this._onAfterCameraRenderObserver) {\n this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);\n }\n this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"unTranslatedPointer\", {\n /**\n * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)\n */\n get: function () {\n return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"useRightHandedSystem\", {\n get: function () {\n return this._useRightHandedSystem;\n },\n /**\n * Gets or sets a boolean indicating if the scene must use right-handed coordinates system\n */\n set: function (value) {\n if (this._useRightHandedSystem === value) {\n return;\n }\n this._useRightHandedSystem = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Sets the step Id used by deterministic lock step\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n * @param newStepId defines the step Id\n */\n Scene.prototype.setStepId = function (newStepId) {\n this._currentStepId = newStepId;\n };\n ;\n /**\n * Gets the step Id used by deterministic lock step\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n * @returns the step Id\n */\n Scene.prototype.getStepId = function () {\n return this._currentStepId;\n };\n ;\n /**\n * Gets the internal step used by deterministic lock step\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n * @returns the internal step\n */\n Scene.prototype.getInternalStep = function () {\n return this._currentInternalStep;\n };\n ;\n Object.defineProperty(Scene.prototype, \"fogEnabled\", {\n get: function () {\n return this._fogEnabled;\n },\n /**\n * Gets or sets a boolean indicating if fog is enabled on this scene\n * @see http://doc.babylonjs.com/babylon101/environment#fog\n */\n set: function (value) {\n if (this._fogEnabled === value) {\n return;\n }\n this._fogEnabled = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"fogMode\", {\n get: function () {\n return this._fogMode;\n },\n /**\n * Gets or sets the fog mode to use\n * @see http://doc.babylonjs.com/babylon101/environment#fog\n */\n set: function (value) {\n if (this._fogMode === value) {\n return;\n }\n this._fogMode = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"shadowsEnabled\", {\n get: function () {\n return this._shadowsEnabled;\n },\n /**\n * Gets or sets a boolean indicating if shadows are enabled on this scene\n */\n set: function (value) {\n if (this._shadowsEnabled === value) {\n return;\n }\n this._shadowsEnabled = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"lightsEnabled\", {\n get: function () {\n return this._lightsEnabled;\n },\n /**\n * Gets or sets a boolean indicating if lights are enabled on this scene\n */\n set: function (value) {\n if (this._lightsEnabled === value) {\n return;\n }\n this._lightsEnabled = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"defaultMaterial\", {\n /** The default material used on meshes when no material is affected */\n get: function () {\n if (!this._defaultMaterial) {\n this._defaultMaterial = new BABYLON.StandardMaterial(\"default material\", this);\n }\n return this._defaultMaterial;\n },\n /** The default material used on meshes when no material is affected */\n set: function (value) {\n this._defaultMaterial = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"texturesEnabled\", {\n get: function () {\n return this._texturesEnabled;\n },\n /**\n * Gets or sets a boolean indicating if textures are enabled on this scene\n */\n set: function (value) {\n if (this._texturesEnabled === value) {\n return;\n }\n this._texturesEnabled = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"skeletonsEnabled\", {\n get: function () {\n return this._skeletonsEnabled;\n },\n /**\n * Gets or sets a boolean indicating if skeletons are enabled on this scene\n */\n set: function (value) {\n if (this._skeletonsEnabled === value) {\n return;\n }\n this._skeletonsEnabled = value;\n this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"postProcessRenderPipelineManager\", {\n /**\n * Gets the postprocess render pipeline manager\n * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline\n * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline\n */\n get: function () {\n if (!this._postProcessRenderPipelineManager) {\n this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();\n }\n return this._postProcessRenderPipelineManager;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"mainSoundTrack\", {\n /**\n * Gets the main soundtrack associated with the scene\n */\n get: function () {\n if (!this._mainSoundTrack) {\n this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });\n }\n return this._mainSoundTrack;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"_isAlternateRenderingEnabled\", {\n /** @hidden */\n get: function () {\n return this._alternateRendering;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"frustumPlanes\", {\n /**\n * Gets the list of frustum planes (built from the active camera)\n */\n get: function () {\n return this._frustumPlanes;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"geometryBufferRenderer\", {\n /**\n * Gets the current geometry buffer associated to the scene.\n */\n get: function () {\n return this._geometryBufferRenderer;\n },\n /**\n * Sets the current geometry buffer for the scene.\n */\n set: function (geometryBufferRenderer) {\n if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {\n this._geometryBufferRenderer = geometryBufferRenderer;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Registers the transient components if needed.\n */\n Scene.prototype._registerTransientComponents = function () {\n // Register components that have been associated lately to the scene.\n if (this._transientComponents.length > 0) {\n for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {\n var component = _a[_i];\n component.register();\n }\n this._transientComponents = [];\n }\n };\n /**\n * Add a component to the scene.\n * Note that the ccomponent could be registered on th next frame if this is called after\n * the register component stage.\n * @param component Defines the component to add to the scene\n */\n Scene.prototype._addComponent = function (component) {\n this._components.push(component);\n this._transientComponents.push(component);\n var serializableComponent = component;\n if (serializableComponent.addFromContainer) {\n this._serializableComponents.push(serializableComponent);\n }\n };\n /**\n * Gets a component from the scene.\n * @param name defines the name of the component to retrieve\n * @returns the component or null if not present\n */\n Scene.prototype._getComponent = function (name) {\n for (var _i = 0, _a = this._components; _i < _a.length; _i++) {\n var component = _a[_i];\n if (component.name === name) {\n return component;\n }\n }\n return null;\n };\n Object.defineProperty(Scene.prototype, \"debugLayer\", {\n /**\n * Gets the debug layer (aka Inspector) associated with the scene\n * @see http://doc.babylonjs.com/features/playground_debuglayer\n */\n get: function () {\n if (!this._debugLayer) {\n this._debugLayer = new BABYLON.DebugLayer(this);\n }\n return this._debugLayer;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"workerCollisions\", {\n /**\n * Gets a boolean indicating if collisions are processed on a web worker\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21\n */\n get: function () {\n return this._workerCollisions;\n },\n set: function (enabled) {\n if (!BABYLON.CollisionCoordinatorLegacy) {\n return;\n }\n enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);\n this._workerCollisions = enabled;\n if (this.collisionCoordinator) {\n this.collisionCoordinator.destroy();\n }\n this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();\n this.collisionCoordinator.init(this);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"selectionOctree\", {\n /**\n * Gets the octree used to boost mesh selection (picking)\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees\n */\n get: function () {\n return this._selectionOctree;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"meshUnderPointer\", {\n /**\n * Gets the mesh that is currently under the pointer\n */\n get: function () {\n return this._pointerOverMesh;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"pointerX\", {\n /**\n * Gets the current on-screen X position of the pointer\n */\n get: function () {\n return this._pointerX;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Scene.prototype, \"pointerY\", {\n /**\n * Gets the current on-screen Y position of the pointer\n */\n get: function () {\n return this._pointerY;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the cached material (ie. the latest rendered one)\n * @returns the cached material\n */\n Scene.prototype.getCachedMaterial = function () {\n return this._cachedMaterial;\n };\n /**\n * Gets the cached effect (ie. the latest rendered one)\n * @returns the cached effect\n */\n Scene.prototype.getCachedEffect = function () {\n return this._cachedEffect;\n };\n /**\n * Gets the cached visibility state (ie. the latest rendered one)\n * @returns the cached visibility state\n */\n Scene.prototype.getCachedVisibility = function () {\n return this._cachedVisibility;\n };\n /**\n * Gets a boolean indicating if the current material / effect / visibility must be bind again\n * @param material defines the current material\n * @param effect defines the current effect\n * @param visibility defines the current visibility state\n * @returns true if one parameter is not cached\n */\n Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {\n if (visibility === void 0) { visibility = 1; }\n return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;\n };\n /**\n * Gets the outline renderer associated with the scene\n * @returns a OutlineRenderer\n */\n Scene.prototype.getOutlineRenderer = function () {\n return this._outlineRenderer;\n };\n /**\n * Gets the engine associated with the scene\n * @returns an Engine\n */\n Scene.prototype.getEngine = function () {\n return this._engine;\n };\n /**\n * Gets the total number of vertices rendered per frame\n * @returns the total number of vertices rendered per frame\n */\n Scene.prototype.getTotalVertices = function () {\n return this._totalVertices.current;\n };\n Object.defineProperty(Scene.prototype, \"totalVerticesPerfCounter\", {\n /**\n * Gets the performance counter for total vertices\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation\n */\n get: function () {\n return this._totalVertices;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)\n * @returns the total number of active indices rendered per frame\n */\n Scene.prototype.getActiveIndices = function () {\n return this._activeIndices.current;\n };\n Object.defineProperty(Scene.prototype, \"totalActiveIndicesPerfCounter\", {\n /**\n * Gets the performance counter for active indices\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation\n */\n get: function () {\n return this._activeIndices;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the total number of active particles rendered per frame\n * @returns the total number of active particles rendered per frame\n */\n Scene.prototype.getActiveParticles = function () {\n return this._activeParticles.current;\n };\n Object.defineProperty(Scene.prototype, \"activeParticlesPerfCounter\", {\n /**\n * Gets the performance counter for active particles\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation\n */\n get: function () {\n return this._activeParticles;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the total number of active bones rendered per frame\n * @returns the total number of active bones rendered per frame\n */\n Scene.prototype.getActiveBones = function () {\n return this._activeBones.current;\n };\n Object.defineProperty(Scene.prototype, \"activeBonesPerfCounter\", {\n /**\n * Gets the performance counter for active bones\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation\n */\n get: function () {\n return this._activeBones;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Scene.prototype.getInterFramePerfCounter = function () {\n BABYLON.Tools.Warn(\"getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n Object.defineProperty(Scene.prototype, \"interFramePerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"interFramePerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Scene.prototype.getLastFrameDuration = function () {\n BABYLON.Tools.Warn(\"getLastFrameDuration is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n Object.defineProperty(Scene.prototype, \"lastFramePerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"lastFramePerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Scene.prototype.getEvaluateActiveMeshesDuration = function () {\n BABYLON.Tools.Warn(\"getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n Object.defineProperty(Scene.prototype, \"evaluateActiveMeshesDurationPerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the array of active meshes\n * @returns an array of AbstractMesh\n */\n Scene.prototype.getActiveMeshes = function () {\n return this._activeMeshes;\n };\n /** @hidden */\n Scene.prototype.getRenderTargetsDuration = function () {\n BABYLON.Tools.Warn(\"getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n /** @hidden */\n Scene.prototype.getRenderDuration = function () {\n BABYLON.Tools.Warn(\"getRenderDuration is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n Object.defineProperty(Scene.prototype, \"renderDurationPerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Scene.prototype.getParticlesDuration = function () {\n BABYLON.Tools.Warn(\"getParticlesDuration is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n Object.defineProperty(Scene.prototype, \"particlesDurationPerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Scene.prototype.getSpritesDuration = function () {\n BABYLON.Tools.Warn(\"getSpritesDuration is deprecated. Please use SceneInstrumentation class\");\n return 0;\n };\n Object.defineProperty(Scene.prototype, \"spriteDuractionPerfCounter\", {\n /** @hidden */\n get: function () {\n BABYLON.Tools.Warn(\"spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class\");\n return null;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)\n * @returns a number\n */\n Scene.prototype.getAnimationRatio = function () {\n return this._animationRatio !== undefined ? this._animationRatio : 1;\n };\n /**\n * Gets an unique Id for the current frame\n * @returns a number\n */\n Scene.prototype.getRenderId = function () {\n return this._renderId;\n };\n /** Call this function if you want to manually increment the render Id*/\n Scene.prototype.incrementRenderId = function () {\n this._renderId++;\n };\n Scene.prototype._updatePointerPosition = function (evt) {\n var canvasRect = this._engine.getRenderingCanvasClientRect();\n if (!canvasRect) {\n return;\n }\n this._pointerX = evt.clientX - canvasRect.left;\n this._pointerY = evt.clientY - canvasRect.top;\n this._unTranslatedPointerX = this._pointerX;\n this._unTranslatedPointerY = this._pointerY;\n };\n Scene.prototype._createUbo = function () {\n this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);\n this._sceneUbo.addUniform(\"viewProjection\", 16);\n this._sceneUbo.addUniform(\"view\", 16);\n };\n Scene.prototype._createAlternateUbo = function () {\n this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);\n this._alternateSceneUbo.addUniform(\"viewProjection\", 16);\n this._alternateSceneUbo.addUniform(\"view\", 16);\n };\n // Pointers handling\n Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {\n var result = this.pickSprite(x, y, predicate, fastCheck, camera);\n if (result) {\n result.ray = originalPointerInfo ? originalPointerInfo.ray : null;\n }\n return result;\n };\n Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {\n if (pointerInfo.pickInfo) {\n if (!pointerInfo.pickInfo.ray) {\n pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);\n }\n }\n };\n /**\n * Use this method to simulate a pointer move on a mesh\n * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay\n * @param pickResult pickingInfo of the object wished to simulate pointer event on\n * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)\n * @returns the current scene\n */\n Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {\n var evt = new PointerEvent(\"pointermove\", pointerEventInit);\n if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {\n return this;\n }\n return this._processPointerMove(pickResult, evt);\n };\n Scene.prototype._processPointerMove = function (pickResult, evt) {\n var canvas = this._engine.getRenderingCanvas();\n if (!canvas) {\n return this;\n }\n if (pickResult && pickResult.hit && pickResult.pickedMesh) {\n this.setPointerOverSprite(null);\n this.setPointerOverMesh(pickResult.pickedMesh);\n if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {\n if (this._pointerOverMesh.actionManager.hoverCursor) {\n canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;\n }\n else {\n canvas.style.cursor = this.hoverCursor;\n }\n }\n else {\n canvas.style.cursor = this.defaultCursor;\n }\n }\n else {\n this.setPointerOverMesh(null);\n // Sprites\n pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);\n if (pickResult && pickResult.hit && pickResult.pickedSprite) {\n this.setPointerOverSprite(pickResult.pickedSprite);\n if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {\n canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;\n }\n else {\n canvas.style.cursor = this.hoverCursor;\n }\n }\n else {\n this.setPointerOverSprite(null);\n // Restore pointer\n canvas.style.cursor = this.defaultCursor;\n }\n }\n if (pickResult) {\n var type = evt.type === \"mousewheel\" || evt.type === \"DOMMouseScroll\" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;\n if (this.onPointerMove) {\n this.onPointerMove(evt, pickResult, type);\n }\n if (this.onPointerObservable.hasObservers()) {\n var pi = new BABYLON.PointerInfo(type, evt, pickResult);\n this._setRayOnPointerInfo(pi);\n this.onPointerObservable.notifyObservers(pi, type);\n }\n }\n return this;\n };\n Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {\n var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);\n if (pickResult) {\n pi.ray = pickResult.ray;\n }\n this.onPrePointerObservable.notifyObservers(pi, type);\n if (pi.skipOnPointerObservable) {\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Use this method to simulate a pointer down on a mesh\n * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay\n * @param pickResult pickingInfo of the object wished to simulate pointer event on\n * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)\n * @returns the current scene\n */\n Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {\n var evt = new PointerEvent(\"pointerdown\", pointerEventInit);\n if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {\n return this;\n }\n return this._processPointerDown(pickResult, evt);\n };\n Scene.prototype._processPointerDown = function (pickResult, evt) {\n var _this = this;\n if (pickResult && pickResult.hit && pickResult.pickedMesh) {\n this._pickedDownMesh = pickResult.pickedMesh;\n var actionManager = pickResult.pickedMesh.actionManager;\n if (actionManager) {\n if (actionManager.hasPickTriggers) {\n actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n switch (evt.button) {\n case 0:\n actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n break;\n case 1:\n actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n break;\n case 2:\n actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n break;\n }\n }\n if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {\n window.setTimeout(function () {\n var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, _this.cameraToUseForPointers);\n if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {\n if (_this._totalPointersPressed !== 0 &&\n ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&\n (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&\n Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {\n _this._startingPointerTime = 0;\n actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n }\n }\n }, Scene.LongPressDelay);\n }\n }\n }\n if (pickResult) {\n var type = BABYLON.PointerEventTypes.POINTERDOWN;\n if (this.onPointerDown) {\n this.onPointerDown(evt, pickResult, type);\n }\n if (this.onPointerObservable.hasObservers()) {\n var pi = new BABYLON.PointerInfo(type, evt, pickResult);\n this._setRayOnPointerInfo(pi);\n this.onPointerObservable.notifyObservers(pi, type);\n }\n }\n return this;\n };\n /**\n * Use this method to simulate a pointer up on a mesh\n * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay\n * @param pickResult pickingInfo of the object wished to simulate pointer event on\n * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)\n * @returns the current scene\n */\n Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {\n var evt = new PointerEvent(\"pointerup\", pointerEventInit);\n var clickInfo = new ClickInfo();\n clickInfo.singleClick = true;\n clickInfo.ignore = true;\n if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {\n return this;\n }\n return this._processPointerUp(pickResult, evt, clickInfo);\n };\n Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {\n if (pickResult && pickResult && pickResult.pickedMesh) {\n this._pickedUpMesh = pickResult.pickedMesh;\n if (this._pickedDownMesh === this._pickedUpMesh) {\n if (this.onPointerPick) {\n this.onPointerPick(evt, pickResult);\n }\n if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {\n var type_1 = BABYLON.PointerEventTypes.POINTERPICK;\n var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);\n this._setRayOnPointerInfo(pi);\n this.onPointerObservable.notifyObservers(pi, type_1);\n }\n }\n if (pickResult.pickedMesh.actionManager) {\n if (clickInfo.ignore) {\n pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n }\n if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {\n pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n }\n if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {\n pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n }\n }\n }\n if (this._pickedDownMesh &&\n this._pickedDownMesh.actionManager &&\n this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&\n this._pickedDownMesh !== this._pickedUpMesh) {\n this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));\n }\n var type = BABYLON.PointerEventTypes.POINTERUP;\n if (this.onPointerObservable.hasObservers()) {\n if (!clickInfo.ignore) {\n if (!clickInfo.hasSwiped) {\n if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {\n var type_2 = BABYLON.PointerEventTypes.POINTERTAP;\n var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);\n this._setRayOnPointerInfo(pi);\n this.onPointerObservable.notifyObservers(pi, type_2);\n }\n if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {\n var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;\n var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);\n this._setRayOnPointerInfo(pi);\n this.onPointerObservable.notifyObservers(pi, type_3);\n }\n }\n }\n else {\n var pi = new BABYLON.PointerInfo(type, evt, pickResult);\n this._setRayOnPointerInfo(pi);\n this.onPointerObservable.notifyObservers(pi, type);\n }\n }\n if (this.onPointerUp) {\n this.onPointerUp(evt, pickResult, type);\n }\n return this;\n };\n /**\n * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)\n * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)\n * @returns true if the pointer was captured\n */\n Scene.prototype.isPointerCaptured = function (pointerId) {\n if (pointerId === void 0) { pointerId = 0; }\n return this._pointerCaptures[pointerId];\n };\n /**\n * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp\n * @param attachUp defines if you want to attach events to pointerup\n * @param attachDown defines if you want to attach events to pointerdown\n * @param attachMove defines if you want to attach events to pointermove\n */\n Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {\n var _this = this;\n if (attachUp === void 0) { attachUp = true; }\n if (attachDown === void 0) { attachDown = true; }\n if (attachMove === void 0) { attachMove = true; }\n this._initActionManager = function (act, clickInfo) {\n if (!_this._meshPickProceed) {\n var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);\n _this._currentPickResult = pickResult;\n if (pickResult) {\n act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;\n }\n _this._meshPickProceed = true;\n }\n return act;\n };\n this._delayedSimpleClick = function (btn, clickInfo, cb) {\n // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different\n if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||\n btn !== _this._previousButtonPressed) {\n _this._doubleClickOccured = false;\n clickInfo.singleClick = true;\n clickInfo.ignore = false;\n cb(clickInfo, _this._currentPickResult);\n }\n };\n this._initClickEvent = function (obs1, obs2, evt, cb) {\n var clickInfo = new ClickInfo();\n _this._currentPickResult = null;\n var act = null;\n var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)\n || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)\n || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);\n if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {\n act = _this._initActionManager(act, clickInfo);\n if (act)\n checkPicking = act.hasPickTriggers;\n }\n if (checkPicking) {\n var btn = evt.button;\n clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||\n Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;\n if (!clickInfo.hasSwiped) {\n var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;\n if (!checkSingleClickImmediately) {\n checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&\n !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);\n if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {\n act = _this._initActionManager(act, clickInfo);\n if (act)\n checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);\n }\n }\n if (checkSingleClickImmediately) {\n // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required\n if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||\n btn !== _this._previousButtonPressed) {\n clickInfo.singleClick = true;\n cb(clickInfo, _this._currentPickResult);\n }\n }\n // at least one double click is required to be check and exclusive double click is enabled\n else {\n // wait that no double click has been raised during the double click delay\n _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;\n _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);\n }\n var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||\n obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);\n if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {\n act = _this._initActionManager(act, clickInfo);\n if (act)\n checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);\n }\n if (checkDoubleClick) {\n // two successive keys pressed are equal, double click delay is not over and double click has not just occurred\n if (btn === _this._previousButtonPressed &&\n Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&\n !_this._doubleClickOccured) {\n // pointer has not moved for 2 clicks, it's a double click\n if (!clickInfo.hasSwiped &&\n Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&\n Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {\n _this._previousStartingPointerTime = 0;\n _this._doubleClickOccured = true;\n clickInfo.doubleClick = true;\n clickInfo.ignore = false;\n if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {\n clearTimeout(_this._previousDelayedSimpleClickTimeout);\n }\n _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;\n cb(clickInfo, _this._currentPickResult);\n }\n // if the two successive clicks are too far, it's just two simple clicks\n else {\n _this._doubleClickOccured = false;\n _this._previousStartingPointerTime = _this._startingPointerTime;\n _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;\n _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;\n _this._previousButtonPressed = btn;\n if (Scene.ExclusiveDoubleClickMode) {\n if (_this._previousDelayedSimpleClickTimeout) {\n clearTimeout(_this._previousDelayedSimpleClickTimeout);\n }\n _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;\n cb(clickInfo, _this._previousPickResult);\n }\n else {\n cb(clickInfo, _this._currentPickResult);\n }\n }\n }\n // just the first click of the double has been raised\n else {\n _this._doubleClickOccured = false;\n _this._previousStartingPointerTime = _this._startingPointerTime;\n _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;\n _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;\n _this._previousButtonPressed = btn;\n }\n }\n }\n }\n clickInfo.ignore = true;\n cb(clickInfo, _this._currentPickResult);\n };\n this._spritePredicate = function (sprite) {\n return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;\n };\n this._onPointerMove = function (evt) {\n _this._updatePointerPosition(evt);\n // PreObservable support\n if (_this._checkPrePointerObservable(null, evt, evt.type === \"mousewheel\" || evt.type === \"DOMMouseScroll\" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {\n return;\n }\n if (!_this.cameraToUseForPointers && !_this.activeCamera) {\n return;\n }\n if (!_this.pointerMovePredicate) {\n _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };\n }\n // Meshes\n var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);\n _this._processPointerMove(pickResult, evt);\n };\n this._onPointerDown = function (evt) {\n _this._totalPointersPressed++;\n _this._pickedDownMesh = null;\n _this._meshPickProceed = false;\n _this._updatePointerPosition(evt);\n if (_this.preventDefaultOnPointerDown && canvas) {\n evt.preventDefault();\n canvas.focus();\n }\n // PreObservable support\n if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {\n return;\n }\n if (!_this.cameraToUseForPointers && !_this.activeCamera) {\n return;\n }\n _this._pointerCaptures[evt.pointerId] = true;\n _this._startingPointerPosition.x = _this._pointerX;\n _this._startingPointerPosition.y = _this._pointerY;\n _this._startingPointerTime = Date.now();\n if (!_this.pointerDownPredicate) {\n _this.pointerDownPredicate = function (mesh) {\n return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();\n };\n }\n // Meshes\n _this._pickedDownMesh = null;\n var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);\n _this._processPointerDown(pickResult, evt);\n // Sprites\n _this._pickedDownSprite = null;\n if (_this.spriteManagers.length > 0) {\n pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);\n if (pickResult && pickResult.hit && pickResult.pickedSprite) {\n if (pickResult.pickedSprite.actionManager) {\n _this._pickedDownSprite = pickResult.pickedSprite;\n switch (evt.button) {\n case 0:\n pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));\n break;\n case 1:\n pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));\n break;\n case 2:\n pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));\n break;\n }\n if (pickResult.pickedSprite.actionManager) {\n pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));\n }\n }\n }\n }\n };\n this._onPointerUp = function (evt) {\n if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF \n return; // So we need to test it the pointer down was pressed before.\n }\n _this._totalPointersPressed--;\n _this._pickedUpMesh = null;\n _this._meshPickProceed = false;\n _this._updatePointerPosition(evt);\n _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {\n // PreObservable support\n if (_this.onPrePointerObservable.hasObservers()) {\n if (!clickInfo.ignore) {\n if (!clickInfo.hasSwiped) {\n if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {\n if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {\n return;\n }\n }\n if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {\n if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {\n return;\n }\n }\n }\n }\n else {\n if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {\n return;\n }\n }\n }\n if (!_this.cameraToUseForPointers && !_this.activeCamera) {\n return;\n }\n _this._pointerCaptures[evt.pointerId] = false;\n if (!_this.pointerUpPredicate) {\n _this.pointerUpPredicate = function (mesh) {\n return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();\n };\n }\n // Meshes\n if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {\n _this._initActionManager(null, clickInfo);\n }\n if (!pickResult) {\n pickResult = _this._currentPickResult;\n }\n _this._processPointerUp(pickResult, evt, clickInfo);\n // Sprites\n if (!clickInfo.ignore) {\n if (_this.spriteManagers.length > 0) {\n var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);\n if (spritePickResult) {\n if (spritePickResult.hit && spritePickResult.pickedSprite) {\n if (spritePickResult.pickedSprite.actionManager) {\n spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));\n if (spritePickResult.pickedSprite.actionManager) {\n if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {\n spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));\n }\n }\n }\n }\n if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {\n _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));\n }\n }\n }\n }\n _this._previousPickResult = _this._currentPickResult;\n });\n };\n this._onKeyDown = function (evt) {\n var type = BABYLON.KeyboardEventTypes.KEYDOWN;\n if (_this.onPreKeyboardObservable.hasObservers()) {\n var pi = new BABYLON.KeyboardInfoPre(type, evt);\n _this.onPreKeyboardObservable.notifyObservers(pi, type);\n if (pi.skipOnPointerObservable) {\n return;\n }\n }\n if (_this.onKeyboardObservable.hasObservers()) {\n var pi = new BABYLON.KeyboardInfo(type, evt);\n _this.onKeyboardObservable.notifyObservers(pi, type);\n }\n if (_this.actionManager) {\n _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));\n }\n };\n this._onKeyUp = function (evt) {\n var type = BABYLON.KeyboardEventTypes.KEYUP;\n if (_this.onPreKeyboardObservable.hasObservers()) {\n var pi = new BABYLON.KeyboardInfoPre(type, evt);\n _this.onPreKeyboardObservable.notifyObservers(pi, type);\n if (pi.skipOnPointerObservable) {\n return;\n }\n }\n if (_this.onKeyboardObservable.hasObservers()) {\n var pi = new BABYLON.KeyboardInfo(type, evt);\n _this.onKeyboardObservable.notifyObservers(pi, type);\n }\n if (_this.actionManager) {\n _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));\n }\n };\n var engine = this.getEngine();\n this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {\n if (!canvas) {\n return;\n }\n canvas.addEventListener(\"keydown\", _this._onKeyDown, false);\n canvas.addEventListener(\"keyup\", _this._onKeyUp, false);\n });\n this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {\n if (!canvas) {\n return;\n }\n canvas.removeEventListener(\"keydown\", _this._onKeyDown);\n canvas.removeEventListener(\"keyup\", _this._onKeyUp);\n });\n var eventPrefix = BABYLON.Tools.GetPointerPrefix();\n var canvas = this._engine.getRenderingCanvas();\n if (!canvas) {\n return;\n }\n if (attachMove) {\n canvas.addEventListener(eventPrefix + \"move\", this._onPointerMove, false);\n // Wheel\n canvas.addEventListener('mousewheel', this._onPointerMove, false);\n canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);\n }\n if (attachDown) {\n canvas.addEventListener(eventPrefix + \"down\", this._onPointerDown, false);\n }\n if (attachUp) {\n window.addEventListener(eventPrefix + \"up\", this._onPointerUp, false);\n }\n canvas.tabIndex = 1;\n };\n /** Detaches all event handlers*/\n Scene.prototype.detachControl = function () {\n var engine = this.getEngine();\n var eventPrefix = BABYLON.Tools.GetPointerPrefix();\n var canvas = engine.getRenderingCanvas();\n if (!canvas) {\n return;\n }\n canvas.removeEventListener(eventPrefix + \"move\", this._onPointerMove);\n canvas.removeEventListener(eventPrefix + \"down\", this._onPointerDown);\n window.removeEventListener(eventPrefix + \"up\", this._onPointerUp);\n if (this._onCanvasBlurObserver) {\n engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n if (this._onCanvasFocusObserver) {\n engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);\n }\n // Wheel\n canvas.removeEventListener('mousewheel', this._onPointerMove);\n canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);\n // Keyboard\n canvas.removeEventListener(\"keydown\", this._onKeyDown);\n canvas.removeEventListener(\"keyup\", this._onKeyUp);\n // Observables\n this.onKeyboardObservable.clear();\n this.onPreKeyboardObservable.clear();\n this.onPointerObservable.clear();\n this.onPrePointerObservable.clear();\n };\n /**\n * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)\n * Delay loaded resources are not taking in account\n * @return true if all required resources are ready\n */\n Scene.prototype.isReady = function () {\n if (this._isDisposed) {\n return false;\n }\n if (this._pendingData.length > 0) {\n return false;\n }\n var index;\n var engine = this.getEngine();\n // Geometries\n for (index = 0; index < this.geometries.length; index++) {\n var geometry = this.geometries[index];\n if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {\n return false;\n }\n }\n // Meshes\n for (index = 0; index < this.meshes.length; index++) {\n var mesh = this.meshes[index];\n if (!mesh.isEnabled()) {\n continue;\n }\n if (!mesh.subMeshes || mesh.subMeshes.length === 0) {\n continue;\n }\n if (!mesh.isReady(true)) {\n return false;\n }\n var hardwareInstancedRendering = mesh.getClassName() === \"InstancedMesh\" || engine.getCaps().instancedArrays && mesh.instances.length > 0;\n // Is Ready For Mesh\n for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {\n var step = _a[_i];\n if (!step.action(mesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n // Post-processes\n if (this.activeCameras && this.activeCameras.length > 0) {\n for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {\n var camera = _c[_b];\n if (!camera.isReady(true)) {\n return false;\n }\n }\n }\n else if (this.activeCamera) {\n if (!this.activeCamera.isReady(true)) {\n return false;\n }\n }\n // Particles\n for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {\n var particleSystem = _e[_d];\n if (!particleSystem.isReady()) {\n return false;\n }\n }\n return true;\n };\n /** Resets all cached information relative to material (including effect and visibility) */\n Scene.prototype.resetCachedMaterial = function () {\n this._cachedMaterial = null;\n this._cachedEffect = null;\n this._cachedVisibility = null;\n };\n /**\n * Registers a function to be called before every frame render\n * @param func defines the function to register\n */\n Scene.prototype.registerBeforeRender = function (func) {\n this.onBeforeRenderObservable.add(func);\n };\n /**\n * Unregisters a function called before every frame render\n * @param func defines the function to unregister\n */\n Scene.prototype.unregisterBeforeRender = function (func) {\n this.onBeforeRenderObservable.removeCallback(func);\n };\n /**\n * Registers a function to be called after every frame render\n * @param func defines the function to register\n */\n Scene.prototype.registerAfterRender = function (func) {\n this.onAfterRenderObservable.add(func);\n };\n /**\n * Unregisters a function called after every frame render\n * @param func defines the function to unregister\n */\n Scene.prototype.unregisterAfterRender = function (func) {\n this.onAfterRenderObservable.removeCallback(func);\n };\n Scene.prototype._executeOnceBeforeRender = function (func) {\n var _this = this;\n var execFunc = function () {\n func();\n setTimeout(function () {\n _this.unregisterBeforeRender(execFunc);\n });\n };\n this.registerBeforeRender(execFunc);\n };\n /**\n * The provided function will run before render once and will be disposed afterwards.\n * A timeout delay can be provided so that the function will be executed in N ms.\n * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.\n * @param func The function to be executed.\n * @param timeout optional delay in ms\n */\n Scene.prototype.executeOnceBeforeRender = function (func, timeout) {\n var _this = this;\n if (timeout !== undefined) {\n setTimeout(function () {\n _this._executeOnceBeforeRender(func);\n }, timeout);\n }\n else {\n this._executeOnceBeforeRender(func);\n }\n };\n /** @hidden */\n Scene.prototype._addPendingData = function (data) {\n this._pendingData.push(data);\n };\n /** @hidden */\n Scene.prototype._removePendingData = function (data) {\n var wasLoading = this.isLoading;\n var index = this._pendingData.indexOf(data);\n if (index !== -1) {\n this._pendingData.splice(index, 1);\n }\n if (wasLoading && !this.isLoading) {\n this.onDataLoadedObservable.notifyObservers(this);\n }\n };\n /**\n * Returns the number of items waiting to be loaded\n * @returns the number of items waiting to be loaded\n */\n Scene.prototype.getWaitingItemsCount = function () {\n return this._pendingData.length;\n };\n Object.defineProperty(Scene.prototype, \"isLoading\", {\n /**\n * Returns a boolean indicating if the scene is still loading data\n */\n get: function () {\n return this._pendingData.length > 0;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Registers a function to be executed when the scene is ready\n * @param {Function} func - the function to be executed\n */\n Scene.prototype.executeWhenReady = function (func) {\n var _this = this;\n this.onReadyObservable.add(func);\n if (this._executeWhenReadyTimeoutId !== -1) {\n return;\n }\n this._executeWhenReadyTimeoutId = setTimeout(function () {\n _this._checkIsReady();\n }, 150);\n };\n /**\n * Returns a promise that resolves when the scene is ready\n * @returns A promise that resolves when the scene is ready\n */\n Scene.prototype.whenReadyAsync = function () {\n var _this = this;\n return new Promise(function (resolve) {\n _this.executeWhenReady(function () {\n resolve();\n });\n });\n };\n /** @hidden */\n Scene.prototype._checkIsReady = function () {\n var _this = this;\n this._registerTransientComponents();\n if (this.isReady()) {\n this.onReadyObservable.notifyObservers(this);\n this.onReadyObservable.clear();\n this._executeWhenReadyTimeoutId = -1;\n return;\n }\n this._executeWhenReadyTimeoutId = setTimeout(function () {\n _this._checkIsReady();\n }, 150);\n };\n // Animations\n /**\n * Will start the animation sequence of a given target\n * @param target defines the target\n * @param from defines from which frame should animation start\n * @param to defines until which frame should animation run.\n * @param weight defines the weight to apply to the animation (1.0 by default)\n * @param loop defines if the animation loops\n * @param speedRatio defines the speed in which to run the animation (1.0 by default)\n * @param onAnimationEnd defines the function to be executed when the animation ends\n * @param animatable defines an animatable object. If not provided a new one will be created from the given params\n * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)\n * @returns the animatable object created for this animation\n */\n Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {\n if (weight === void 0) { weight = 1.0; }\n if (speedRatio === void 0) { speedRatio = 1.0; }\n var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);\n returnedAnimatable.weight = weight;\n return returnedAnimatable;\n };\n /**\n * Will start the animation sequence of a given target\n * @param target defines the target\n * @param from defines from which frame should animation start\n * @param to defines until which frame should animation run.\n * @param loop defines if the animation loops\n * @param speedRatio defines the speed in which to run the animation (1.0 by default)\n * @param onAnimationEnd defines the function to be executed when the animation ends\n * @param animatable defines an animatable object. If not provided a new one will be created from the given params\n * @param stopCurrent defines if the current animations must be stopped first (true by default)\n * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)\n * @returns the animatable object created for this animation\n */\n Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {\n if (speedRatio === void 0) { speedRatio = 1.0; }\n if (stopCurrent === void 0) { stopCurrent = true; }\n if (from > to && speedRatio > 0) {\n speedRatio *= -1;\n }\n if (stopCurrent) {\n this.stopAnimation(target, undefined, targetMask);\n }\n if (!animatable) {\n animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);\n }\n var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;\n // Local animations\n if (target.animations && shouldRunTargetAnimations) {\n animatable.appendAnimations(target, target.animations);\n }\n // Children animations\n if (target.getAnimatables) {\n var animatables = target.getAnimatables();\n for (var index = 0; index < animatables.length; index++) {\n this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);\n }\n }\n animatable.reset();\n return animatable;\n };\n /**\n * Begin a new animation on a given node\n * @param target defines the target where the animation will take place\n * @param animations defines the list of animations to start\n * @param from defines the initial value\n * @param to defines the final value\n * @param loop defines if you want animation to loop (off by default)\n * @param speedRatio defines the speed ratio to apply to all animations\n * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)\n * @returns the list of created animatables\n */\n Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {\n if (speedRatio === undefined) {\n speedRatio = 1.0;\n }\n var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);\n return animatable;\n };\n /**\n * Begin a new animation on a given node and its hierarchy\n * @param target defines the root node where the animation will take place\n * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.\n * @param animations defines the list of animations to start\n * @param from defines the initial value\n * @param to defines the final value\n * @param loop defines if you want animation to loop (off by default)\n * @param speedRatio defines the speed ratio to apply to all animations\n * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)\n * @returns the list of animatables created for all nodes\n */\n Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {\n var children = target.getDescendants(directDescendantsOnly);\n var result = [];\n result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));\n for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {\n var child = children_1[_i];\n result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));\n }\n return result;\n };\n /**\n * Gets the animatable associated with a specific target\n * @param target defines the target of the animatable\n * @returns the required animatable if found\n */\n Scene.prototype.getAnimatableByTarget = function (target) {\n for (var index = 0; index < this._activeAnimatables.length; index++) {\n if (this._activeAnimatables[index].target === target) {\n return this._activeAnimatables[index];\n }\n }\n return null;\n };\n /**\n * Gets all animatables associated with a given target\n * @param target defines the target to look animatables for\n * @returns an array of Animatables\n */\n Scene.prototype.getAllAnimatablesByTarget = function (target) {\n var result = [];\n for (var index = 0; index < this._activeAnimatables.length; index++) {\n if (this._activeAnimatables[index].target === target) {\n result.push(this._activeAnimatables[index]);\n }\n }\n return result;\n };\n Object.defineProperty(Scene.prototype, \"animatables\", {\n /**\n * Gets all animatable attached to the scene\n */\n get: function () {\n return this._activeAnimatables;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Will stop the animation of the given target\n * @param target - the target\n * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)\n * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)\n */\n Scene.prototype.stopAnimation = function (target, animationName, targetMask) {\n var animatables = this.getAllAnimatablesByTarget(target);\n for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {\n var animatable = animatables_1[_i];\n animatable.stop(animationName, targetMask);\n }\n };\n /**\n * Stops and removes all animations that have been applied to the scene\n */\n Scene.prototype.stopAllAnimations = function () {\n if (this._activeAnimatables) {\n for (var i = 0; i < this._activeAnimatables.length; i++) {\n this._activeAnimatables[i].stop();\n }\n this._activeAnimatables = [];\n }\n for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {\n var group = _a[_i];\n group.stop();\n }\n };\n Scene.prototype._animate = function () {\n if (!this.animationsEnabled || this._activeAnimatables.length === 0) {\n return;\n }\n // Getting time\n var now = BABYLON.Tools.Now;\n if (!this._animationTimeLast) {\n if (this._pendingData.length > 0) {\n return;\n }\n this._animationTimeLast = now;\n }\n var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;\n this._animationTime += deltaTime;\n this._animationTimeLast = now;\n for (var index = 0; index < this._activeAnimatables.length; index++) {\n this._activeAnimatables[index]._animate(this._animationTime);\n }\n // Late animation bindings\n this._processLateAnimationBindings();\n };\n /** @hidden */\n Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {\n var target = runtimeAnimation.target;\n this._registeredForLateAnimationBindings.pushNoDuplicate(target);\n if (!target._lateAnimationHolders) {\n target._lateAnimationHolders = {};\n }\n if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {\n target._lateAnimationHolders[runtimeAnimation.targetPath] = {\n totalWeight: 0,\n animations: [],\n originalValue: originalValue\n };\n }\n target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);\n target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;\n };\n Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {\n var normalizer = 1.0;\n var finalPosition = BABYLON.Tmp.Vector3[0];\n var finalScaling = BABYLON.Tmp.Vector3[1];\n var finalQuaternion = BABYLON.Tmp.Quaternion[0];\n var startIndex = 0;\n var originalAnimation = holder.animations[0];\n var originalValue = holder.originalValue;\n var scale = 1;\n if (holder.totalWeight < 1.0) {\n // We need to mix the original value in \n originalValue.decompose(finalScaling, finalQuaternion, finalPosition);\n scale = 1.0 - holder.totalWeight;\n }\n else {\n startIndex = 1;\n // We need to normalize the weights\n normalizer = holder.totalWeight;\n originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);\n scale = originalAnimation.weight / normalizer;\n if (scale == 1) {\n return originalAnimation.currentValue;\n }\n }\n finalScaling.scaleInPlace(scale);\n finalPosition.scaleInPlace(scale);\n finalQuaternion.scaleInPlace(scale);\n for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {\n var runtimeAnimation = holder.animations[animIndex];\n var scale = runtimeAnimation.weight / normalizer;\n var currentPosition = BABYLON.Tmp.Vector3[2];\n var currentScaling = BABYLON.Tmp.Vector3[3];\n var currentQuaternion = BABYLON.Tmp.Quaternion[1];\n runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);\n currentScaling.scaleAndAddToRef(scale, finalScaling);\n currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);\n currentPosition.scaleAndAddToRef(scale, finalPosition);\n }\n BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);\n return originalAnimation._workValue;\n };\n Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {\n var originalAnimation = holder.animations[0];\n var originalValue = holder.originalValue;\n if (holder.animations.length === 1) {\n return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));\n }\n var normalizer = 1.0;\n var quaternions;\n var weights;\n if (holder.totalWeight < 1.0) {\n var scale = 1.0 - holder.totalWeight;\n quaternions = [];\n weights = [];\n quaternions.push(originalValue);\n weights.push(scale);\n }\n else {\n if (holder.animations.length === 2) { // Slerp as soon as we can\n return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);\n }\n quaternions = [];\n weights = [];\n normalizer = holder.totalWeight;\n }\n for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {\n var runtimeAnimation = holder.animations[animIndex];\n quaternions.push(runtimeAnimation.currentValue);\n weights.push(runtimeAnimation.weight / normalizer);\n }\n // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions\n var cumulativeAmount = 0;\n var cumulativeQuaternion = null;\n for (var index = 0; index < quaternions.length;) {\n if (!cumulativeQuaternion) {\n cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));\n cumulativeAmount = weights[index] + weights[index + 1];\n index += 2;\n continue;\n }\n cumulativeAmount += weights[index];\n BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);\n index++;\n }\n return cumulativeQuaternion;\n };\n Scene.prototype._processLateAnimationBindings = function () {\n if (!this._registeredForLateAnimationBindings.length) {\n return;\n }\n for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {\n var target = this._registeredForLateAnimationBindings.data[index];\n for (var path in target._lateAnimationHolders) {\n var holder = target._lateAnimationHolders[path];\n var originalAnimation = holder.animations[0];\n var originalValue = holder.originalValue;\n var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix\n var finalValue = void 0;\n if (matrixDecomposeMode) {\n finalValue = this._processLateAnimationBindingsForMatrices(holder);\n }\n else {\n var quaternionMode = originalValue.w !== undefined;\n if (quaternionMode) {\n finalValue = this._processLateAnimationBindingsForQuaternions(holder);\n }\n else {\n var startIndex = 0;\n var normalizer = 1.0;\n if (holder.totalWeight < 1.0) {\n // We need to mix the original value in \n if (originalValue.scale) {\n finalValue = originalValue.scale(1.0 - holder.totalWeight);\n }\n else {\n finalValue = originalValue * (1.0 - holder.totalWeight);\n }\n }\n else {\n // We need to normalize the weights\n normalizer = holder.totalWeight;\n var scale_1 = originalAnimation.weight / normalizer;\n if (scale_1 !== 1) {\n if (originalAnimation.currentValue.scale) {\n finalValue = originalAnimation.currentValue.scale(scale_1);\n }\n else {\n finalValue = originalAnimation.currentValue * scale_1;\n }\n }\n else {\n finalValue = originalAnimation.currentValue;\n }\n startIndex = 1;\n }\n for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {\n var runtimeAnimation = holder.animations[animIndex];\n var scale = runtimeAnimation.weight / normalizer;\n if (runtimeAnimation.currentValue.scaleAndAddToRef) {\n runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);\n }\n else {\n finalValue += runtimeAnimation.currentValue * scale;\n }\n }\n }\n }\n target[path] = finalValue;\n }\n target._lateAnimationHolders = {};\n }\n this._registeredForLateAnimationBindings.reset();\n };\n // Matrix\n /** @hidden */\n Scene.prototype._switchToAlternateCameraConfiguration = function (active) {\n this._useAlternateCameraConfiguration = active;\n };\n /**\n * Gets the current view matrix\n * @returns a Matrix\n */\n Scene.prototype.getViewMatrix = function () {\n return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;\n };\n /**\n * Gets the current projection matrix\n * @returns a Matrix\n */\n Scene.prototype.getProjectionMatrix = function () {\n return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;\n };\n /**\n * Gets the current transform matrix\n * @returns a Matrix made of View * Projection\n */\n Scene.prototype.getTransformMatrix = function () {\n return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;\n };\n /**\n * Sets the current transform matrix\n * @param view defines the View matrix to use\n * @param projection defines the Projection matrix to use\n */\n Scene.prototype.setTransformMatrix = function (view, projection) {\n if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {\n return;\n }\n this._viewUpdateFlag = view.updateFlag;\n this._projectionUpdateFlag = projection.updateFlag;\n this._viewMatrix = view;\n this._projectionMatrix = projection;\n this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);\n // Update frustum\n if (!this._frustumPlanes) {\n this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);\n }\n else {\n BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);\n }\n if (this.activeCamera && this.activeCamera._alternateCamera) {\n var otherCamera = this.activeCamera._alternateCamera;\n otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);\n BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane\n }\n if (this._sceneUbo.useUbo) {\n this._sceneUbo.updateMatrix(\"viewProjection\", this._transformMatrix);\n this._sceneUbo.updateMatrix(\"view\", this._viewMatrix);\n this._sceneUbo.update();\n }\n };\n /** @hidden */\n Scene.prototype._setAlternateTransformMatrix = function (view, projection) {\n if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {\n return;\n }\n this._alternateViewUpdateFlag = view.updateFlag;\n this._alternateProjectionUpdateFlag = projection.updateFlag;\n this._alternateViewMatrix = view;\n this._alternateProjectionMatrix = projection;\n if (!this._alternateTransformMatrix) {\n this._alternateTransformMatrix = BABYLON.Matrix.Zero();\n }\n this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);\n if (!this._alternateSceneUbo) {\n this._createAlternateUbo();\n }\n if (this._alternateSceneUbo.useUbo) {\n this._alternateSceneUbo.updateMatrix(\"viewProjection\", this._alternateTransformMatrix);\n this._alternateSceneUbo.updateMatrix(\"view\", this._alternateViewMatrix);\n this._alternateSceneUbo.update();\n }\n };\n /**\n * Gets the uniform buffer used to store scene data\n * @returns a UniformBuffer\n */\n Scene.prototype.getSceneUniformBuffer = function () {\n return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;\n };\n /**\n * Gets an unique (relatively to the current scene) Id\n * @returns an unique number for the scene\n */\n Scene.prototype.getUniqueId = function () {\n var result = Scene._uniqueIdCounter;\n Scene._uniqueIdCounter++;\n return result;\n };\n /**\n * Add a mesh to the list of scene's meshes\n * @param newMesh defines the mesh to add\n * @param recursive if all child meshes should also be added to the scene\n */\n Scene.prototype.addMesh = function (newMesh, recursive) {\n var _this = this;\n if (recursive === void 0) { recursive = false; }\n this.meshes.push(newMesh);\n //notify the collision coordinator\n if (this.collisionCoordinator) {\n this.collisionCoordinator.onMeshAdded(newMesh);\n }\n newMesh._resyncLightSources();\n this.onNewMeshAddedObservable.notifyObservers(newMesh);\n if (recursive) {\n newMesh.getChildMeshes().forEach(function (m) {\n _this.addMesh(m);\n });\n }\n };\n /**\n * Remove a mesh for the list of scene's meshes\n * @param toRemove defines the mesh to remove\n * @param recursive if all child meshes should also be removed from the scene\n * @returns the index where the mesh was in the mesh list\n */\n Scene.prototype.removeMesh = function (toRemove, recursive) {\n var _this = this;\n if (recursive === void 0) { recursive = false; }\n var index = this.meshes.indexOf(toRemove);\n if (index !== -1) {\n // Remove from the scene if mesh found\n this.meshes.splice(index, 1);\n }\n this.onMeshRemovedObservable.notifyObservers(toRemove);\n if (recursive) {\n toRemove.getChildMeshes().forEach(function (m) {\n _this.removeMesh(m);\n });\n }\n return index;\n };\n /**\n * Add a transform node to the list of scene's transform nodes\n * @param newTransformNode defines the transform node to add\n */\n Scene.prototype.addTransformNode = function (newTransformNode) {\n this.transformNodes.push(newTransformNode);\n this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);\n };\n /**\n * Remove a transform node for the list of scene's transform nodes\n * @param toRemove defines the transform node to remove\n * @returns the index where the transform node was in the transform node list\n */\n Scene.prototype.removeTransformNode = function (toRemove) {\n var index = this.transformNodes.indexOf(toRemove);\n if (index !== -1) {\n // Remove from the scene if found\n this.transformNodes.splice(index, 1);\n }\n this.onTransformNodeRemovedObservable.notifyObservers(toRemove);\n return index;\n };\n /**\n * Remove a skeleton for the list of scene's skeletons\n * @param toRemove defines the skeleton to remove\n * @returns the index where the skeleton was in the skeleton list\n */\n Scene.prototype.removeSkeleton = function (toRemove) {\n var index = this.skeletons.indexOf(toRemove);\n if (index !== -1) {\n // Remove from the scene if found\n this.skeletons.splice(index, 1);\n }\n return index;\n };\n /**\n * Remove a morph target for the list of scene's morph targets\n * @param toRemove defines the morph target to remove\n * @returns the index where the morph target was in the morph target list\n */\n Scene.prototype.removeMorphTargetManager = function (toRemove) {\n var index = this.morphTargetManagers.indexOf(toRemove);\n if (index !== -1) {\n // Remove from the scene if found\n this.morphTargetManagers.splice(index, 1);\n }\n return index;\n };\n /**\n * Remove a light for the list of scene's lights\n * @param toRemove defines the light to remove\n * @returns the index where the light was in the light list\n */\n Scene.prototype.removeLight = function (toRemove) {\n var index = this.lights.indexOf(toRemove);\n if (index !== -1) {\n // Remove from meshes\n for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n mesh._removeLightSource(toRemove);\n }\n // Remove from the scene if mesh found\n this.lights.splice(index, 1);\n this.sortLightsByPriority();\n }\n this.onLightRemovedObservable.notifyObservers(toRemove);\n return index;\n };\n /**\n * Remove a camera for the list of scene's cameras\n * @param toRemove defines the camera to remove\n * @returns the index where the camera was in the camera list\n */\n Scene.prototype.removeCamera = function (toRemove) {\n var index = this.cameras.indexOf(toRemove);\n if (index !== -1) {\n // Remove from the scene if mesh found\n this.cameras.splice(index, 1);\n }\n // Remove from activeCameras\n var index2 = this.activeCameras.indexOf(toRemove);\n if (index2 !== -1) {\n // Remove from the scene if mesh found\n this.activeCameras.splice(index2, 1);\n }\n // Reset the activeCamera\n if (this.activeCamera === toRemove) {\n if (this.cameras.length > 0) {\n this.activeCamera = this.cameras[0];\n }\n else {\n this.activeCamera = null;\n }\n }\n this.onCameraRemovedObservable.notifyObservers(toRemove);\n return index;\n };\n /**\n * Remove a particle system for the list of scene's particle systems\n * @param toRemove defines the particle system to remove\n * @returns the index where the particle system was in the particle system list\n */\n Scene.prototype.removeParticleSystem = function (toRemove) {\n var index = this.particleSystems.indexOf(toRemove);\n if (index !== -1) {\n this.particleSystems.splice(index, 1);\n }\n return index;\n };\n /**\n * Remove a animation for the list of scene's animations\n * @param toRemove defines the animation to remove\n * @returns the index where the animation was in the animation list\n */\n Scene.prototype.removeAnimation = function (toRemove) {\n var index = this.animations.indexOf(toRemove);\n if (index !== -1) {\n this.animations.splice(index, 1);\n }\n return index;\n };\n /**\n * Removes the given animation group from this scene.\n * @param toRemove The animation group to remove\n * @returns The index of the removed animation group\n */\n Scene.prototype.removeAnimationGroup = function (toRemove) {\n var index = this.animationGroups.indexOf(toRemove);\n if (index !== -1) {\n this.animationGroups.splice(index, 1);\n }\n return index;\n };\n /**\n * Removes the given multi-material from this scene.\n * @param toRemove The multi-material to remove\n * @returns The index of the removed multi-material\n */\n Scene.prototype.removeMultiMaterial = function (toRemove) {\n var index = this.multiMaterials.indexOf(toRemove);\n if (index !== -1) {\n this.multiMaterials.splice(index, 1);\n }\n return index;\n };\n /**\n * Removes the given material from this scene.\n * @param toRemove The material to remove\n * @returns The index of the removed material\n */\n Scene.prototype.removeMaterial = function (toRemove) {\n var index = this.materials.indexOf(toRemove);\n if (index !== -1) {\n this.materials.splice(index, 1);\n }\n return index;\n };\n /**\n * Removes the given action manager from this scene.\n * @param toRemove The action manager to remove\n * @returns The index of the removed action manager\n */\n Scene.prototype.removeActionManager = function (toRemove) {\n var index = this.actionManagers.indexOf(toRemove);\n if (index !== -1) {\n this.actionManagers.splice(index, 1);\n }\n return index;\n };\n /**\n * Removes the given texture from this scene.\n * @param toRemove The texture to remove\n * @returns The index of the removed texture\n */\n Scene.prototype.removeTexture = function (toRemove) {\n var index = this.textures.indexOf(toRemove);\n if (index !== -1) {\n this.textures.splice(index, 1);\n }\n return index;\n };\n /**\n * Adds the given light to this scene\n * @param newLight The light to add\n */\n Scene.prototype.addLight = function (newLight) {\n this.lights.push(newLight);\n this.sortLightsByPriority();\n // Add light to all meshes (To support if the light is removed and then readded)\n for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n if (mesh._lightSources.indexOf(newLight) === -1) {\n mesh._lightSources.push(newLight);\n mesh._resyncLightSources();\n }\n }\n this.onNewLightAddedObservable.notifyObservers(newLight);\n };\n /**\n * Sorts the list list based on light priorities\n */\n Scene.prototype.sortLightsByPriority = function () {\n if (this.requireLightSorting) {\n this.lights.sort(BABYLON.Light.CompareLightsPriority);\n }\n };\n /**\n * Adds the given camera to this scene\n * @param newCamera The camera to add\n */\n Scene.prototype.addCamera = function (newCamera) {\n this.cameras.push(newCamera);\n this.onNewCameraAddedObservable.notifyObservers(newCamera);\n };\n /**\n * Adds the given skeleton to this scene\n * @param newSkeleton The skeleton to add\n */\n Scene.prototype.addSkeleton = function (newSkeleton) {\n this.skeletons.push(newSkeleton);\n };\n /**\n * Adds the given particle system to this scene\n * @param newParticleSystem The particle system to add\n */\n Scene.prototype.addParticleSystem = function (newParticleSystem) {\n this.particleSystems.push(newParticleSystem);\n };\n /**\n * Adds the given animation to this scene\n * @param newAnimation The animation to add\n */\n Scene.prototype.addAnimation = function (newAnimation) {\n this.animations.push(newAnimation);\n };\n /**\n * Adds the given animation group to this scene.\n * @param newAnimationGroup The animation group to add\n */\n Scene.prototype.addAnimationGroup = function (newAnimationGroup) {\n this.animationGroups.push(newAnimationGroup);\n };\n /**\n * Adds the given multi-material to this scene\n * @param newMultiMaterial The multi-material to add\n */\n Scene.prototype.addMultiMaterial = function (newMultiMaterial) {\n this.multiMaterials.push(newMultiMaterial);\n };\n /**\n * Adds the given material to this scene\n * @param newMaterial The material to add\n */\n Scene.prototype.addMaterial = function (newMaterial) {\n this.materials.push(newMaterial);\n };\n /**\n * Adds the given morph target to this scene\n * @param newMorphTargetManager The morph target to add\n */\n Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {\n this.morphTargetManagers.push(newMorphTargetManager);\n };\n /**\n * Adds the given geometry to this scene\n * @param newGeometry The geometry to add\n */\n Scene.prototype.addGeometry = function (newGeometry) {\n this.geometries.push(newGeometry);\n };\n /**\n * Adds the given action manager to this scene\n * @param newActionManager The action manager to add\n */\n Scene.prototype.addActionManager = function (newActionManager) {\n this.actionManagers.push(newActionManager);\n };\n /**\n * Adds the given texture to this scene.\n * @param newTexture The texture to add\n */\n Scene.prototype.addTexture = function (newTexture) {\n this.textures.push(newTexture);\n };\n /**\n * Switch active camera\n * @param newCamera defines the new active camera\n * @param attachControl defines if attachControl must be called for the new active camera (default: true)\n */\n Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {\n if (attachControl === void 0) { attachControl = true; }\n var canvas = this._engine.getRenderingCanvas();\n if (!canvas) {\n return;\n }\n if (this.activeCamera) {\n this.activeCamera.detachControl(canvas);\n }\n this.activeCamera = newCamera;\n if (attachControl) {\n newCamera.attachControl(canvas);\n }\n };\n /**\n * sets the active camera of the scene using its ID\n * @param id defines the camera's ID\n * @return the new active camera or null if none found.\n */\n Scene.prototype.setActiveCameraByID = function (id) {\n var camera = this.getCameraByID(id);\n if (camera) {\n this.activeCamera = camera;\n return camera;\n }\n return null;\n };\n /**\n * sets the active camera of the scene using its name\n * @param name defines the camera's name\n * @returns the new active camera or null if none found.\n */\n Scene.prototype.setActiveCameraByName = function (name) {\n var camera = this.getCameraByName(name);\n if (camera) {\n this.activeCamera = camera;\n return camera;\n }\n return null;\n };\n /**\n * get an animation group using its name\n * @param name defines the material's name\n * @return the animation group or null if none found.\n */\n Scene.prototype.getAnimationGroupByName = function (name) {\n for (var index = 0; index < this.animationGroups.length; index++) {\n if (this.animationGroups[index].name === name) {\n return this.animationGroups[index];\n }\n }\n return null;\n };\n /**\n * get a material using its id\n * @param id defines the material's ID\n * @return the material or null if none found.\n */\n Scene.prototype.getMaterialByID = function (id) {\n for (var index = 0; index < this.materials.length; index++) {\n if (this.materials[index].id === id) {\n return this.materials[index];\n }\n }\n return null;\n };\n /**\n * Gets a material using its name\n * @param name defines the material's name\n * @return the material or null if none found.\n */\n Scene.prototype.getMaterialByName = function (name) {\n for (var index = 0; index < this.materials.length; index++) {\n if (this.materials[index].name === name) {\n return this.materials[index];\n }\n }\n return null;\n };\n /**\n * Gets a camera using its id\n * @param id defines the id to look for\n * @returns the camera or null if not found\n */\n Scene.prototype.getCameraByID = function (id) {\n for (var index = 0; index < this.cameras.length; index++) {\n if (this.cameras[index].id === id) {\n return this.cameras[index];\n }\n }\n return null;\n };\n /**\n * Gets a camera using its unique id\n * @param uniqueId defines the unique id to look for\n * @returns the camera or null if not found\n */\n Scene.prototype.getCameraByUniqueID = function (uniqueId) {\n for (var index = 0; index < this.cameras.length; index++) {\n if (this.cameras[index].uniqueId === uniqueId) {\n return this.cameras[index];\n }\n }\n return null;\n };\n /**\n * Gets a camera using its name\n * @param name defines the camera's name\n * @return the camera or null if none found.\n */\n Scene.prototype.getCameraByName = function (name) {\n for (var index = 0; index < this.cameras.length; index++) {\n if (this.cameras[index].name === name) {\n return this.cameras[index];\n }\n }\n return null;\n };\n /**\n * Gets a bone using its id\n * @param id defines the bone's id\n * @return the bone or null if not found\n */\n Scene.prototype.getBoneByID = function (id) {\n for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {\n var skeleton = this.skeletons[skeletonIndex];\n for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {\n if (skeleton.bones[boneIndex].id === id) {\n return skeleton.bones[boneIndex];\n }\n }\n }\n return null;\n };\n /**\n * Gets a bone using its id\n * @param name defines the bone's name\n * @return the bone or null if not found\n */\n Scene.prototype.getBoneByName = function (name) {\n for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {\n var skeleton = this.skeletons[skeletonIndex];\n for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {\n if (skeleton.bones[boneIndex].name === name) {\n return skeleton.bones[boneIndex];\n }\n }\n }\n return null;\n };\n /**\n * Gets a light node using its name\n * @param name defines the the light's name\n * @return the light or null if none found.\n */\n Scene.prototype.getLightByName = function (name) {\n for (var index = 0; index < this.lights.length; index++) {\n if (this.lights[index].name === name) {\n return this.lights[index];\n }\n }\n return null;\n };\n /**\n * Gets a light node using its id\n * @param id defines the light's id\n * @return the light or null if none found.\n */\n Scene.prototype.getLightByID = function (id) {\n for (var index = 0; index < this.lights.length; index++) {\n if (this.lights[index].id === id) {\n return this.lights[index];\n }\n }\n return null;\n };\n /**\n * Gets a light node using its scene-generated unique ID\n * @param uniqueId defines the light's unique id\n * @return the light or null if none found.\n */\n Scene.prototype.getLightByUniqueID = function (uniqueId) {\n for (var index = 0; index < this.lights.length; index++) {\n if (this.lights[index].uniqueId === uniqueId) {\n return this.lights[index];\n }\n }\n return null;\n };\n /**\n * Gets a particle system by id\n * @param id defines the particle system id\n * @return the corresponding system or null if none found\n */\n Scene.prototype.getParticleSystemByID = function (id) {\n for (var index = 0; index < this.particleSystems.length; index++) {\n if (this.particleSystems[index].id === id) {\n return this.particleSystems[index];\n }\n }\n return null;\n };\n /**\n * Gets a geometry using its ID\n * @param id defines the geometry's id\n * @return the geometry or null if none found.\n */\n Scene.prototype.getGeometryByID = function (id) {\n for (var index = 0; index < this.geometries.length; index++) {\n if (this.geometries[index].id === id) {\n return this.geometries[index];\n }\n }\n return null;\n };\n /**\n * Add a new geometry to this scene\n * @param geometry defines the geometry to be added to the scene.\n * @param force defines if the geometry must be pushed even if a geometry with this id already exists\n * @return a boolean defining if the geometry was added or not\n */\n Scene.prototype.pushGeometry = function (geometry, force) {\n if (!force && this.getGeometryByID(geometry.id)) {\n return false;\n }\n this.geometries.push(geometry);\n //notify the collision coordinator\n if (this.collisionCoordinator) {\n this.collisionCoordinator.onGeometryAdded(geometry);\n }\n this.onNewGeometryAddedObservable.notifyObservers(geometry);\n return true;\n };\n /**\n * Removes an existing geometry\n * @param geometry defines the geometry to be removed from the scene\n * @return a boolean defining if the geometry was removed or not\n */\n Scene.prototype.removeGeometry = function (geometry) {\n var index = this.geometries.indexOf(geometry);\n if (index > -1) {\n this.geometries.splice(index, 1);\n //notify the collision coordinator\n if (this.collisionCoordinator) {\n this.collisionCoordinator.onGeometryDeleted(geometry);\n }\n this.onGeometryRemovedObservable.notifyObservers(geometry);\n return true;\n }\n return false;\n };\n /**\n * Gets the list of geometries attached to the scene\n * @returns an array of Geometry\n */\n Scene.prototype.getGeometries = function () {\n return this.geometries;\n };\n /**\n * Gets the first added mesh found of a given ID\n * @param id defines the id to search for\n * @return the mesh found or null if not found at all\n */\n Scene.prototype.getMeshByID = function (id) {\n for (var index = 0; index < this.meshes.length; index++) {\n if (this.meshes[index].id === id) {\n return this.meshes[index];\n }\n }\n return null;\n };\n /**\n * Gets a list of meshes using their id\n * @param id defines the id to search for\n * @returns a list of meshes\n */\n Scene.prototype.getMeshesByID = function (id) {\n return this.meshes.filter(function (m) {\n return m.id === id;\n });\n };\n /**\n * Gets the first added transform node found of a given ID\n * @param id defines the id to search for\n * @return the found transform node or null if not found at all.\n */\n Scene.prototype.getTransformNodeByID = function (id) {\n for (var index = 0; index < this.transformNodes.length; index++) {\n if (this.transformNodes[index].id === id) {\n return this.transformNodes[index];\n }\n }\n return null;\n };\n /**\n * Gets a list of transform nodes using their id\n * @param id defines the id to search for\n * @returns a list of transform nodes\n */\n Scene.prototype.getTransformNodesByID = function (id) {\n return this.transformNodes.filter(function (m) {\n return m.id === id;\n });\n };\n /**\n * Gets a mesh with its auto-generated unique id\n * @param uniqueId defines the unique id to search for\n * @return the found mesh or null if not found at all.\n */\n Scene.prototype.getMeshByUniqueID = function (uniqueId) {\n for (var index = 0; index < this.meshes.length; index++) {\n if (this.meshes[index].uniqueId === uniqueId) {\n return this.meshes[index];\n }\n }\n return null;\n };\n /**\n * Gets a the last added mesh using a given id\n * @param id defines the id to search for\n * @return the found mesh or null if not found at all.\n */\n Scene.prototype.getLastMeshByID = function (id) {\n for (var index = this.meshes.length - 1; index >= 0; index--) {\n if (this.meshes[index].id === id) {\n return this.meshes[index];\n }\n }\n return null;\n };\n /**\n * Gets a the last added node (Mesh, Camera, Light) using a given id\n * @param id defines the id to search for\n * @return the found node or null if not found at all\n */\n Scene.prototype.getLastEntryByID = function (id) {\n var index;\n for (index = this.meshes.length - 1; index >= 0; index--) {\n if (this.meshes[index].id === id) {\n return this.meshes[index];\n }\n }\n for (index = this.transformNodes.length - 1; index >= 0; index--) {\n if (this.transformNodes[index].id === id) {\n return this.transformNodes[index];\n }\n }\n for (index = this.cameras.length - 1; index >= 0; index--) {\n if (this.cameras[index].id === id) {\n return this.cameras[index];\n }\n }\n for (index = this.lights.length - 1; index >= 0; index--) {\n if (this.lights[index].id === id) {\n return this.lights[index];\n }\n }\n return null;\n };\n /**\n * Gets a node (Mesh, Camera, Light) using a given id\n * @param id defines the id to search for\n * @return the found node or null if not found at all\n */\n Scene.prototype.getNodeByID = function (id) {\n var mesh = this.getMeshByID(id);\n if (mesh) {\n return mesh;\n }\n var light = this.getLightByID(id);\n if (light) {\n return light;\n }\n var camera = this.getCameraByID(id);\n if (camera) {\n return camera;\n }\n var bone = this.getBoneByID(id);\n return bone;\n };\n /**\n * Gets a node (Mesh, Camera, Light) using a given name\n * @param name defines the name to search for\n * @return the found node or null if not found at all.\n */\n Scene.prototype.getNodeByName = function (name) {\n var mesh = this.getMeshByName(name);\n if (mesh) {\n return mesh;\n }\n var light = this.getLightByName(name);\n if (light) {\n return light;\n }\n var camera = this.getCameraByName(name);\n if (camera) {\n return camera;\n }\n var bone = this.getBoneByName(name);\n return bone;\n };\n /**\n * Gets a mesh using a given name\n * @param name defines the name to search for\n * @return the found mesh or null if not found at all.\n */\n Scene.prototype.getMeshByName = function (name) {\n for (var index = 0; index < this.meshes.length; index++) {\n if (this.meshes[index].name === name) {\n return this.meshes[index];\n }\n }\n return null;\n };\n /**\n * Gets a transform node using a given name\n * @param name defines the name to search for\n * @return the found transform node or null if not found at all.\n */\n Scene.prototype.getTransformNodeByName = function (name) {\n for (var index = 0; index < this.transformNodes.length; index++) {\n if (this.transformNodes[index].name === name) {\n return this.transformNodes[index];\n }\n }\n return null;\n };\n /**\n * Gets a sound using a given name\n * @param name defines the name to search for\n * @return the found sound or null if not found at all.\n */\n Scene.prototype.getSoundByName = function (name) {\n var index;\n if (BABYLON.AudioEngine) {\n for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {\n if (this.mainSoundTrack.soundCollection[index].name === name) {\n return this.mainSoundTrack.soundCollection[index];\n }\n }\n for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {\n for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {\n if (this.soundTracks[sdIndex].soundCollection[index].name === name) {\n return this.soundTracks[sdIndex].soundCollection[index];\n }\n }\n }\n }\n return null;\n };\n /**\n * Gets a skeleton using a given id (if many are found, this function will pick the last one)\n * @param id defines the id to search for\n * @return the found skeleton or null if not found at all.\n */\n Scene.prototype.getLastSkeletonByID = function (id) {\n for (var index = this.skeletons.length - 1; index >= 0; index--) {\n if (this.skeletons[index].id === id) {\n return this.skeletons[index];\n }\n }\n return null;\n };\n /**\n * Gets a skeleton using a given id (if many are found, this function will pick the first one)\n * @param id defines the id to search for\n * @return the found skeleton or null if not found at all.\n */\n Scene.prototype.getSkeletonById = function (id) {\n for (var index = 0; index < this.skeletons.length; index++) {\n if (this.skeletons[index].id === id) {\n return this.skeletons[index];\n }\n }\n return null;\n };\n /**\n * Gets a skeleton using a given name\n * @param name defines the name to search for\n * @return the found skeleton or null if not found at all.\n */\n Scene.prototype.getSkeletonByName = function (name) {\n for (var index = 0; index < this.skeletons.length; index++) {\n if (this.skeletons[index].name === name) {\n return this.skeletons[index];\n }\n }\n return null;\n };\n /**\n * Gets a morph target manager using a given id (if many are found, this function will pick the last one)\n * @param id defines the id to search for\n * @return the found morph target manager or null if not found at all.\n */\n Scene.prototype.getMorphTargetManagerById = function (id) {\n for (var index = 0; index < this.morphTargetManagers.length; index++) {\n if (this.morphTargetManagers[index].uniqueId === id) {\n return this.morphTargetManagers[index];\n }\n }\n return null;\n };\n /**\n * Gets a boolean indicating if the given mesh is active\n * @param mesh defines the mesh to look for\n * @returns true if the mesh is in the active list\n */\n Scene.prototype.isActiveMesh = function (mesh) {\n return (this._activeMeshes.indexOf(mesh) !== -1);\n };\n Object.defineProperty(Scene.prototype, \"uid\", {\n /**\n * Return a unique id as a string which can serve as an identifier for the scene\n */\n get: function () {\n if (!this._uid) {\n this._uid = BABYLON.Tools.RandomId();\n }\n return this._uid;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Add an externaly attached data from its key.\n * This method call will fail and return false, if such key already exists.\n * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.\n * @param key the unique key that identifies the data\n * @param data the data object to associate to the key for this Engine instance\n * @return true if no such key were already present and the data was added successfully, false otherwise\n */\n Scene.prototype.addExternalData = function (key, data) {\n if (!this._externalData) {\n this._externalData = new BABYLON.StringDictionary();\n }\n return this._externalData.add(key, data);\n };\n /**\n * Get an externaly attached data from its key\n * @param key the unique key that identifies the data\n * @return the associated data, if present (can be null), or undefined if not present\n */\n Scene.prototype.getExternalData = function (key) {\n if (!this._externalData) {\n return null;\n }\n return this._externalData.get(key);\n };\n /**\n * Get an externaly attached data from its key, create it using a factory if it's not already present\n * @param key the unique key that identifies the data\n * @param factory the factory that will be called to create the instance if and only if it doesn't exists\n * @return the associated data, can be null if the factory returned null.\n */\n Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {\n if (!this._externalData) {\n this._externalData = new BABYLON.StringDictionary();\n }\n return this._externalData.getOrAddWithFactory(key, factory);\n };\n /**\n * Remove an externaly attached data from the Engine instance\n * @param key the unique key that identifies the data\n * @return true if the data was successfully removed, false if it doesn't exist\n */\n Scene.prototype.removeExternalData = function (key) {\n return this._externalData.remove(key);\n };\n Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {\n if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {\n for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {\n var step = _a[_i];\n step.action(mesh, subMesh);\n }\n var material = subMesh.getMaterial();\n if (material !== null && material !== undefined) {\n // Render targets\n if (material.getRenderTargetTextures !== undefined) {\n if (this._processedMaterials.indexOf(material) === -1) {\n this._processedMaterials.push(material);\n this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());\n }\n }\n // Dispatch\n this._activeIndices.addCount(subMesh.indexCount, false);\n this._renderingManager.dispatch(subMesh, mesh, material);\n }\n }\n };\n /**\n * Clear the processed materials smart array preventing retention point in material dispose.\n */\n Scene.prototype.freeProcessedMaterials = function () {\n this._processedMaterials.dispose();\n };\n /**\n * Clear the active meshes smart array preventing retention point in mesh dispose.\n */\n Scene.prototype.freeActiveMeshes = function () {\n this._activeMeshes.dispose();\n if (this.activeCamera && this.activeCamera._activeMeshes) {\n this.activeCamera._activeMeshes.dispose();\n }\n if (this.activeCameras) {\n for (var i = 0; i < this.activeCameras.length; i++) {\n var activeCamera = this.activeCameras[i];\n if (activeCamera && activeCamera._activeMeshes) {\n activeCamera._activeMeshes.dispose();\n }\n }\n }\n };\n /**\n * Clear the info related to rendering groups preventing retention points during dispose.\n */\n Scene.prototype.freeRenderingGroups = function () {\n if (this._renderingManager) {\n this._renderingManager.freeRenderingGroups();\n }\n if (this.textures) {\n for (var i = 0; i < this.textures.length; i++) {\n var texture = this.textures[i];\n if (texture && texture.renderList) {\n texture.freeRenderingGroups();\n }\n }\n }\n };\n /** @hidden */\n Scene.prototype._isInIntermediateRendering = function () {\n return this._intermediateRendering;\n };\n /**\n * Defines the current active mesh candidate provider\n * @param provider defines the provider to use\n */\n Scene.prototype.setActiveMeshCandidateProvider = function (provider) {\n this._activeMeshCandidateProvider = provider;\n };\n /**\n * Gets the current active mesh candidate provider\n * @returns the current active mesh candidate provider\n */\n Scene.prototype.getActiveMeshCandidateProvider = function () {\n return this._activeMeshCandidateProvider;\n };\n /**\n * Use this function to stop evaluating active meshes. The current list will be keep alive between frames\n * @returns the current scene\n */\n Scene.prototype.freezeActiveMeshes = function () {\n if (!this.activeCamera) {\n return this;\n }\n if (!this._frustumPlanes) {\n this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());\n }\n this._evaluateActiveMeshes();\n this._activeMeshesFrozen = true;\n return this;\n };\n /**\n * Use this function to restart evaluating active meshes on every frame\n * @returns the current scene\n */\n Scene.prototype.unfreezeActiveMeshes = function () {\n this._activeMeshesFrozen = false;\n return this;\n };\n Scene.prototype._evaluateActiveMeshes = function () {\n if (this._activeMeshesFrozen && this._activeMeshes.length) {\n return;\n }\n if (!this.activeCamera) {\n return;\n }\n this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);\n this.activeCamera._activeMeshes.reset();\n this._activeMeshes.reset();\n this._renderingManager.reset();\n this._processedMaterials.reset();\n this._activeParticleSystems.reset();\n this._activeSkeletons.reset();\n this._softwareSkinnedMeshes.reset();\n for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {\n var step = _a[_i];\n step.action();\n }\n // Meshes\n var meshes;\n var len;\n var checkIsEnabled = true;\n // Determine mesh candidates\n if (this._activeMeshCandidateProvider !== undefined) {\n // Use _activeMeshCandidateProvider\n meshes = this._activeMeshCandidateProvider.getMeshes(this);\n checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;\n if (meshes !== undefined) {\n len = meshes.length;\n }\n else {\n len = 0;\n }\n }\n else if (this._selectionOctree !== undefined) {\n // Octree\n var selection = this._selectionOctree.select(this._frustumPlanes);\n meshes = selection.data;\n len = selection.length;\n }\n else {\n // Full scene traversal\n len = this.meshes.length;\n meshes = this.meshes;\n }\n // Check each mesh\n for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {\n mesh = meshes[meshIndex];\n if (mesh.isBlocked) {\n continue;\n }\n this._totalVertices.addCount(mesh.getTotalVertices(), false);\n if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {\n continue;\n }\n mesh.computeWorldMatrix();\n // Intersections\n if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {\n this._meshesForIntersections.pushNoDuplicate(mesh);\n }\n // Switch to current LOD\n meshLOD = mesh.getLOD(this.activeCamera);\n if (meshLOD === undefined || meshLOD === null) {\n continue;\n }\n mesh._preActivate();\n if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {\n this._activeMeshes.push(mesh);\n this.activeCamera._activeMeshes.push(mesh);\n mesh._activate(this._renderId);\n if (meshLOD !== mesh) {\n meshLOD._activate(this._renderId);\n }\n this._activeMesh(mesh, meshLOD);\n }\n }\n this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);\n // Particle systems\n if (this.particlesEnabled) {\n this.onBeforeParticlesRenderingObservable.notifyObservers(this);\n for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {\n var particleSystem = this.particleSystems[particleIndex];\n if (!particleSystem.isStarted() || !particleSystem.emitter) {\n continue;\n }\n var emitter = particleSystem.emitter;\n if (!emitter.position || emitter.isEnabled()) {\n this._activeParticleSystems.push(particleSystem);\n particleSystem.animate();\n this._renderingManager.dispatchParticles(particleSystem);\n }\n }\n this.onAfterParticlesRenderingObservable.notifyObservers(this);\n }\n };\n Scene.prototype._activeMesh = function (sourceMesh, mesh) {\n if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {\n if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {\n mesh.skeleton.prepare();\n }\n if (!mesh.computeBonesUsingShaders) {\n this._softwareSkinnedMeshes.pushNoDuplicate(mesh);\n }\n }\n for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {\n var step = _a[_i];\n step.action(sourceMesh, mesh);\n }\n if (mesh !== undefined && mesh !== null\n && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {\n // Submeshes Octrees\n var len;\n var subMeshes;\n if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {\n var intersections = mesh._submeshesOctree.select(this._frustumPlanes);\n len = intersections.length;\n subMeshes = intersections.data;\n }\n else {\n subMeshes = mesh.subMeshes;\n len = subMeshes.length;\n }\n for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {\n subMesh = subMeshes[subIndex];\n this._evaluateSubMesh(subMesh, mesh);\n }\n }\n };\n /**\n * Update the transform matrix to update from the current active camera\n * @param force defines a boolean used to force the update even if cache is up to date\n */\n Scene.prototype.updateTransformMatrix = function (force) {\n if (!this.activeCamera) {\n return;\n }\n this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));\n };\n /**\n * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)\n * @param alternateCamera defines the camera to use\n */\n Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {\n this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());\n };\n Scene.prototype._renderForCamera = function (camera, rigParent) {\n if (camera && camera._skipRendering) {\n return;\n }\n var engine = this._engine;\n this.activeCamera = camera;\n if (!this.activeCamera)\n throw new Error(\"Active camera not set\");\n // Viewport\n engine.setViewport(this.activeCamera.viewport);\n // Camera\n this.resetCachedMaterial();\n this._renderId++;\n this.updateTransformMatrix();\n if (camera._alternateCamera) {\n this.updateAlternateTransformMatrix(camera._alternateCamera);\n this._alternateRendering = true;\n }\n this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);\n // Meshes\n this._evaluateActiveMeshes();\n // Software skinning\n for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {\n var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];\n mesh.applySkeleton(mesh.skeleton);\n }\n // Render targets\n this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);\n if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {\n this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);\n }\n if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {\n this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);\n }\n if (this.renderTargetsEnabled) {\n this._intermediateRendering = true;\n if (this._renderTargets.length > 0) {\n BABYLON.Tools.StartPerformanceCounter(\"Render targets\", this._renderTargets.length > 0);\n for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {\n var renderTarget = this._renderTargets.data[renderIndex];\n if (renderTarget._shouldRender()) {\n this._renderId++;\n var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;\n renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);\n }\n }\n BABYLON.Tools.EndPerformanceCounter(\"Render targets\", this._renderTargets.length > 0);\n this._renderId++;\n }\n for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {\n var step = _a[_i];\n step.action(this.activeCamera);\n }\n this._intermediateRendering = false;\n engine.restoreDefaultFramebuffer(); // Restore back buffer if needed\n }\n this.onAfterRenderTargetsRenderObservable.notifyObservers(this);\n // Prepare Frame\n if (this.postProcessManager) {\n this.postProcessManager._prepareFrame();\n }\n // Before Camera Draw\n for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {\n var step = _c[_b];\n step.action(this.activeCamera);\n }\n // Render\n this.onBeforeDrawPhaseObservable.notifyObservers(this);\n this._renderingManager.render(null, null, true, true);\n this.onAfterDrawPhaseObservable.notifyObservers(this);\n // After Camera Draw\n for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {\n var step = _e[_d];\n step.action(this.activeCamera);\n }\n // Finalize frame\n if (this.postProcessManager) {\n this.postProcessManager._finalizeFrame(camera.isIntermediate);\n }\n // Reset some special arrays\n this._renderTargets.reset();\n this._alternateRendering = false;\n this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);\n };\n Scene.prototype._processSubCameras = function (camera) {\n if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {\n this._renderForCamera(camera);\n return;\n }\n // rig cameras\n for (var index = 0; index < camera._rigCameras.length; index++) {\n this._renderForCamera(camera._rigCameras[index], camera);\n }\n this.activeCamera = camera;\n this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());\n };\n Scene.prototype._checkIntersections = function () {\n for (var index = 0; index < this._meshesForIntersections.length; index++) {\n var sourceMesh = this._meshesForIntersections.data[index];\n if (!sourceMesh.actionManager) {\n continue;\n }\n for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {\n var action = sourceMesh.actionManager.actions[actionIndex];\n if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {\n var parameters = action.getTriggerParameter();\n var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;\n var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);\n var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);\n if (areIntersecting && currentIntersectionInProgress === -1) {\n if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {\n action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));\n sourceMesh._intersectionsInProgress.push(otherMesh);\n }\n else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {\n sourceMesh._intersectionsInProgress.push(otherMesh);\n }\n }\n else if (!areIntersecting && currentIntersectionInProgress > -1) {\n //They intersected, and now they don't.\n //is this trigger an exit trigger? execute an event.\n if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {\n action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));\n }\n //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.\n if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {\n var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;\n return otherMesh === parameterMesh;\n }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {\n sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);\n }\n }\n }\n }\n }\n };\n /**\n * Render the scene\n * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)\n */\n Scene.prototype.render = function (updateCameras) {\n if (updateCameras === void 0) { updateCameras = true; }\n if (this.isDisposed) {\n return;\n }\n // Register components that have been associated lately to the scene.\n this._registerTransientComponents();\n this._activeParticles.fetchNewFrame();\n this._totalVertices.fetchNewFrame();\n this._activeIndices.fetchNewFrame();\n this._activeBones.fetchNewFrame();\n this._meshesForIntersections.reset();\n this.resetCachedMaterial();\n this.onBeforeAnimationsObservable.notifyObservers(this);\n // Actions\n if (this.actionManager) {\n this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);\n }\n //Simplification Queue\n if (this.simplificationQueue && !this.simplificationQueue.running) {\n this.simplificationQueue.executeNext();\n }\n if (this._engine.isDeterministicLockStep()) {\n var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;\n var defaultFPS = (60.0 / 1000.0);\n var defaultFrameTime = 1000 / 60; // frame time in MS\n if (this._physicsEngine) {\n defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;\n }\n var stepsTaken = 0;\n var maxSubSteps = this._engine.getLockstepMaxSteps();\n var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));\n internalSteps = Math.min(internalSteps, maxSubSteps);\n do {\n this.onBeforeStepObservable.notifyObservers(this);\n // Animations\n this._animationRatio = defaultFrameTime * defaultFPS;\n this._animate();\n this.onAfterAnimationsObservable.notifyObservers(this);\n // Physics\n if (this._physicsEngine) {\n this.onBeforePhysicsObservable.notifyObservers(this);\n this._physicsEngine._step(defaultFrameTime / 1000);\n this.onAfterPhysicsObservable.notifyObservers(this);\n }\n this.onAfterStepObservable.notifyObservers(this);\n this._currentStepId++;\n stepsTaken++;\n deltaTime -= defaultFrameTime;\n } while (deltaTime > 0 && stepsTaken < internalSteps);\n this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;\n }\n else {\n // Animations\n var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));\n this._animationRatio = deltaTime * (60.0 / 1000.0);\n this._animate();\n this.onAfterAnimationsObservable.notifyObservers(this);\n // Physics\n if (this._physicsEngine) {\n this.onBeforePhysicsObservable.notifyObservers(this);\n this._physicsEngine._step(deltaTime / 1000.0);\n this.onAfterPhysicsObservable.notifyObservers(this);\n }\n }\n // Before camera update steps\n for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {\n var step = _a[_i];\n step.action();\n }\n // Update Cameras\n if (updateCameras) {\n if (this.activeCameras.length > 0) {\n for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {\n var camera = this.activeCameras[cameraIndex];\n camera.update();\n if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {\n // rig cameras\n for (var index = 0; index < camera._rigCameras.length; index++) {\n camera._rigCameras[index].update();\n }\n }\n }\n }\n else if (this.activeCamera) {\n this.activeCamera.update();\n if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {\n // rig cameras\n for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {\n this.activeCamera._rigCameras[index].update();\n }\n }\n }\n }\n // Before render\n this.onBeforeRenderObservable.notifyObservers(this);\n // Customs render targets\n this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);\n var engine = this.getEngine();\n var currentActiveCamera = this.activeCamera;\n if (this.renderTargetsEnabled) {\n BABYLON.Tools.StartPerformanceCounter(\"Custom render targets\", this.customRenderTargets.length > 0);\n this._intermediateRendering = true;\n for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {\n var renderTarget = this.customRenderTargets[customIndex];\n if (renderTarget._shouldRender()) {\n this._renderId++;\n this.activeCamera = renderTarget.activeCamera || this.activeCamera;\n if (!this.activeCamera)\n throw new Error(\"Active camera not set\");\n // Viewport\n engine.setViewport(this.activeCamera.viewport);\n // Camera\n this.updateTransformMatrix();\n renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);\n }\n }\n BABYLON.Tools.EndPerformanceCounter(\"Custom render targets\", this.customRenderTargets.length > 0);\n this._intermediateRendering = false;\n this._renderId++;\n }\n // Restore back buffer\n if (this.customRenderTargets.length > 0) {\n engine.restoreDefaultFramebuffer();\n }\n this.onAfterRenderTargetsRenderObservable.notifyObservers(this);\n this.activeCamera = currentActiveCamera;\n // Procedural textures\n if (this.proceduralTexturesEnabled) {\n BABYLON.Tools.StartPerformanceCounter(\"Procedural textures\", this.proceduralTextures.length > 0);\n for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {\n var proceduralTexture = this.proceduralTextures[proceduralIndex];\n if (proceduralTexture._shouldRender()) {\n proceduralTexture.render();\n }\n }\n BABYLON.Tools.EndPerformanceCounter(\"Procedural textures\", this.proceduralTextures.length > 0);\n }\n // Clear\n if (this.autoClearDepthAndStencil || this.autoClear) {\n this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);\n }\n // Shadows\n if (this.shadowsEnabled) {\n for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {\n var light = this.lights[lightIndex];\n var shadowGenerator = light.getShadowGenerator();\n if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {\n var shadowMap = (shadowGenerator.getShadowMap());\n if (this.textures.indexOf(shadowMap) !== -1) {\n this._renderTargets.push(shadowMap);\n }\n }\n }\n }\n // Depth renderer\n for (var key in this._depthRenderer) {\n this._renderTargets.push(this._depthRenderer[key].getDepthMap());\n }\n // Geometry renderer\n if (this._geometryBufferRenderer) {\n this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());\n }\n // RenderPipeline\n if (this._postProcessRenderPipelineManager) {\n this._postProcessRenderPipelineManager.update();\n }\n // Multi-cameras?\n if (this.activeCameras.length > 0) {\n for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {\n if (cameraIndex > 0) {\n this._engine.clear(null, false, true, true);\n }\n this._processSubCameras(this.activeCameras[cameraIndex]);\n }\n }\n else {\n if (!this.activeCamera) {\n throw new Error(\"No camera defined\");\n }\n this._processSubCameras(this.activeCamera);\n }\n // Intersection checks\n this._checkIntersections();\n // Update the audio listener attached to the camera\n if (BABYLON.AudioEngine) {\n this._updateAudioParameters();\n }\n // After render\n if (this.afterRender) {\n this.afterRender();\n }\n this.onAfterRenderObservable.notifyObservers(this);\n // Cleaning\n for (var index = 0; index < this._toBeDisposed.length; index++) {\n var data = this._toBeDisposed.data[index];\n if (data) {\n data.dispose();\n }\n this._toBeDisposed[index] = null;\n }\n this._toBeDisposed.reset();\n if (this.dumpNextRenderTargets) {\n this.dumpNextRenderTargets = false;\n }\n this._activeBones.addCount(0, true);\n this._activeIndices.addCount(0, true);\n this._activeParticles.addCount(0, true);\n };\n Scene.prototype._updateAudioParameters = function () {\n if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {\n return;\n }\n var listeningCamera;\n var audioEngine = BABYLON.Engine.audioEngine;\n if (this.activeCameras.length > 0) {\n listeningCamera = this.activeCameras[0];\n }\n else {\n listeningCamera = this.activeCamera;\n }\n if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {\n audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);\n // for VR cameras\n if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {\n listeningCamera = listeningCamera.rigCameras[0];\n }\n var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());\n var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);\n cameraDirection.normalize();\n // To avoid some errors on GearVR\n if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {\n audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);\n }\n var i;\n for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {\n var sound = this.mainSoundTrack.soundCollection[i];\n if (sound.useCustomAttenuation) {\n sound.updateDistanceFromListener();\n }\n }\n for (i = 0; i < this.soundTracks.length; i++) {\n for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {\n sound = this.soundTracks[i].soundCollection[j];\n if (sound.useCustomAttenuation) {\n sound.updateDistanceFromListener();\n }\n }\n }\n }\n };\n Object.defineProperty(Scene.prototype, \"audioEnabled\", {\n // Audio\n /**\n * Gets or sets if audio support is enabled\n * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music\n */\n get: function () {\n return this._audioEnabled;\n },\n set: function (value) {\n this._audioEnabled = value;\n if (BABYLON.AudioEngine) {\n if (this._audioEnabled) {\n this._enableAudio();\n }\n else {\n this._disableAudio();\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Scene.prototype._disableAudio = function () {\n var i;\n for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {\n this.mainSoundTrack.soundCollection[i].pause();\n }\n for (i = 0; i < this.soundTracks.length; i++) {\n for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {\n this.soundTracks[i].soundCollection[j].pause();\n }\n }\n };\n Scene.prototype._enableAudio = function () {\n var i;\n for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {\n if (this.mainSoundTrack.soundCollection[i].isPaused) {\n this.mainSoundTrack.soundCollection[i].play();\n }\n }\n for (i = 0; i < this.soundTracks.length; i++) {\n for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {\n if (this.soundTracks[i].soundCollection[j].isPaused) {\n this.soundTracks[i].soundCollection[j].play();\n }\n }\n }\n };\n Object.defineProperty(Scene.prototype, \"headphone\", {\n /**\n * Gets or sets if audio will be output to headphones\n * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music\n */\n get: function () {\n return this._headphone;\n },\n set: function (value) {\n this._headphone = value;\n if (BABYLON.AudioEngine) {\n if (this._headphone) {\n this._switchAudioModeForHeadphones();\n }\n else {\n this._switchAudioModeForNormalSpeakers();\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Scene.prototype._switchAudioModeForHeadphones = function () {\n this.mainSoundTrack.switchPanningModelToHRTF();\n for (var i = 0; i < this.soundTracks.length; i++) {\n this.soundTracks[i].switchPanningModelToHRTF();\n }\n };\n Scene.prototype._switchAudioModeForNormalSpeakers = function () {\n this.mainSoundTrack.switchPanningModelToEqualPower();\n for (var i = 0; i < this.soundTracks.length; i++) {\n this.soundTracks[i].switchPanningModelToEqualPower();\n }\n };\n /**\n * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.\n * @param camera The camera to create the depth renderer on (default: scene's active camera)\n * @returns the created depth renderer\n */\n Scene.prototype.enableDepthRenderer = function (camera) {\n camera = camera || this.activeCamera;\n if (!camera) {\n throw \"No camera available to enable depth renderer\";\n }\n if (!this._depthRenderer[camera.id]) {\n var textureType = 0;\n if (this._engine.getCaps().textureHalfFloatRender) {\n textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else if (this._engine.getCaps().textureFloatRender) {\n textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n else {\n throw \"Depth renderer does not support int texture type\";\n }\n this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);\n }\n return this._depthRenderer[camera.id];\n };\n /**\n * Disables a depth renderer for a given camera\n * @param camera The camera to disable the depth renderer on (default: scene's active camera)\n */\n Scene.prototype.disableDepthRenderer = function (camera) {\n camera = camera || this.activeCamera;\n if (!camera || !this._depthRenderer[camera.id]) {\n return;\n }\n this._depthRenderer[camera.id].dispose();\n delete this._depthRenderer[camera.id];\n };\n /**\n * Enables a GeometryBufferRender and associates it with the scene\n * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)\n * @returns the GeometryBufferRenderer\n */\n Scene.prototype.enableGeometryBufferRenderer = function (ratio) {\n if (ratio === void 0) { ratio = 1; }\n if (this._geometryBufferRenderer) {\n return this._geometryBufferRenderer;\n }\n this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);\n if (!this._geometryBufferRenderer.isSupported) {\n this._geometryBufferRenderer = null;\n }\n return this._geometryBufferRenderer;\n };\n /**\n * Disables the GeometryBufferRender associated with the scene\n */\n Scene.prototype.disableGeometryBufferRenderer = function () {\n if (!this._geometryBufferRenderer) {\n return;\n }\n this._geometryBufferRenderer.dispose();\n this._geometryBufferRenderer = null;\n };\n /**\n * Freeze all materials\n * A frozen material will not be updatable but should be faster to render\n */\n Scene.prototype.freezeMaterials = function () {\n for (var i = 0; i < this.materials.length; i++) {\n this.materials[i].freeze();\n }\n };\n /**\n * Unfreeze all materials\n * A frozen material will not be updatable but should be faster to render\n */\n Scene.prototype.unfreezeMaterials = function () {\n for (var i = 0; i < this.materials.length; i++) {\n this.materials[i].unfreeze();\n }\n };\n /**\n * Releases all held ressources\n */\n Scene.prototype.dispose = function () {\n this.beforeRender = null;\n this.afterRender = null;\n this.skeletons = [];\n this.morphTargetManagers = [];\n this._transientComponents = [];\n this._isReadyForMeshStage.clear();\n this._beforeEvaluateActiveMeshStage.clear();\n this._evaluateSubMeshStage.clear();\n this._activeMeshStage.clear();\n this._cameraDrawRenderTargetStage.clear();\n this._beforeCameraDrawStage.clear();\n this._beforeRenderingGroupDrawStage.clear();\n this._afterRenderingGroupDrawStage.clear();\n this._afterCameraDrawStage.clear();\n this._beforeCameraUpdateStage.clear();\n for (var _i = 0, _a = this._components; _i < _a.length; _i++) {\n var component = _a[_i];\n component.dispose();\n }\n this.importedMeshesFiles = new Array();\n this.stopAllAnimations();\n this.resetCachedMaterial();\n for (var key in this._depthRenderer) {\n this._depthRenderer[key].dispose();\n }\n // Smart arrays\n if (this.activeCamera) {\n this.activeCamera._activeMeshes.dispose();\n this.activeCamera = null;\n }\n this._activeMeshes.dispose();\n this._renderingManager.dispose();\n this._processedMaterials.dispose();\n this._activeParticleSystems.dispose();\n this._activeSkeletons.dispose();\n this._softwareSkinnedMeshes.dispose();\n this._renderTargets.dispose();\n this._registeredForLateAnimationBindings.dispose();\n this._meshesForIntersections.dispose();\n this._toBeDisposed.dispose();\n // Abort active requests\n for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {\n var request = _c[_b];\n request.abort();\n }\n // Debug layer\n if (this._debugLayer) {\n this._debugLayer.hide();\n }\n // Events\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onBeforeRenderObservable.clear();\n this.onAfterRenderObservable.clear();\n this.onBeforeRenderTargetsRenderObservable.clear();\n this.onAfterRenderTargetsRenderObservable.clear();\n this.onAfterStepObservable.clear();\n this.onBeforeStepObservable.clear();\n this.onBeforeActiveMeshesEvaluationObservable.clear();\n this.onAfterActiveMeshesEvaluationObservable.clear();\n this.onBeforeParticlesRenderingObservable.clear();\n this.onAfterParticlesRenderingObservable.clear();\n this.onBeforeSpritesRenderingObservable.clear();\n this.onAfterSpritesRenderingObservable.clear();\n this.onBeforeDrawPhaseObservable.clear();\n this.onAfterDrawPhaseObservable.clear();\n this.onBeforePhysicsObservable.clear();\n this.onAfterPhysicsObservable.clear();\n this.onBeforeAnimationsObservable.clear();\n this.onAfterAnimationsObservable.clear();\n this.onDataLoadedObservable.clear();\n this.onBeforeRenderingGroupObservable.clear();\n this.onAfterRenderingGroupObservable.clear();\n this.detachControl();\n // Release sounds & sounds tracks\n if (BABYLON.AudioEngine) {\n this.disposeSounds();\n }\n // VR Helper\n if (this.VRHelper) {\n this.VRHelper.dispose();\n }\n // Detach cameras\n var canvas = this._engine.getRenderingCanvas();\n if (canvas) {\n var index;\n for (index = 0; index < this.cameras.length; index++) {\n this.cameras[index].detachControl(canvas);\n }\n }\n // Release animation groups\n while (this.animationGroups.length) {\n this.animationGroups[0].dispose();\n }\n // Release lights\n while (this.lights.length) {\n this.lights[0].dispose();\n }\n // Release meshes\n while (this.meshes.length) {\n this.meshes[0].dispose(true);\n }\n while (this.transformNodes.length) {\n this.removeTransformNode(this.transformNodes[0]);\n }\n // Release cameras\n while (this.cameras.length) {\n this.cameras[0].dispose();\n }\n // Release materials\n if (this.defaultMaterial) {\n this.defaultMaterial.dispose();\n }\n while (this.multiMaterials.length) {\n this.multiMaterials[0].dispose();\n }\n while (this.materials.length) {\n this.materials[0].dispose();\n }\n // Release particles\n while (this.particleSystems.length) {\n this.particleSystems[0].dispose();\n }\n // Release sprites\n while (this.spriteManagers.length) {\n this.spriteManagers[0].dispose();\n }\n // Release postProcesses\n while (this.postProcesses.length) {\n this.postProcesses[0].dispose();\n }\n // Release textures\n while (this.textures.length) {\n this.textures[0].dispose();\n }\n // Release UBO\n this._sceneUbo.dispose();\n if (this._alternateSceneUbo) {\n this._alternateSceneUbo.dispose();\n }\n // Post-processes\n this.postProcessManager.dispose();\n if (this._postProcessRenderPipelineManager) {\n this._postProcessRenderPipelineManager.dispose();\n }\n // Physics\n if (this._physicsEngine) {\n this.disablePhysicsEngine();\n }\n // Remove from engine\n index = this._engine.scenes.indexOf(this);\n if (index > -1) {\n this._engine.scenes.splice(index, 1);\n }\n this._engine.wipeCaches(true);\n this._isDisposed = true;\n };\n Object.defineProperty(Scene.prototype, \"isDisposed\", {\n /**\n * Gets if the scene is already disposed\n */\n get: function () {\n return this._isDisposed;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Releases sounds & soundtracks\n */\n Scene.prototype.disposeSounds = function () {\n if (!this._mainSoundTrack) {\n return;\n }\n this.mainSoundTrack.dispose();\n for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {\n this.soundTracks[scIndex].dispose();\n }\n };\n /**\n * Call this function to reduce memory footprint of the scene.\n * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)\n */\n Scene.prototype.clearCachedVertexData = function () {\n for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {\n var mesh = this.meshes[meshIndex];\n var geometry = mesh.geometry;\n if (geometry) {\n geometry._indices = [];\n for (var vbName in geometry._vertexBuffers) {\n if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {\n continue;\n }\n geometry._vertexBuffers[vbName]._buffer._data = null;\n }\n }\n }\n };\n /**\n * This function will remove the local cached buffer data from texture.\n * It will save memory but will prevent the texture from being rebuilt\n */\n Scene.prototype.cleanCachedTextureBuffer = function () {\n for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {\n var baseTexture = _a[_i];\n var buffer = baseTexture._buffer;\n if (buffer) {\n baseTexture._buffer = null;\n }\n }\n };\n // Octrees\n /**\n * Get the world extend vectors with an optional filter\n *\n * @param filterPredicate the predicate - which meshes should be included when calculating the world size\n * @returns {{ min: Vector3; max: Vector3 }} min and max vectors\n */\n Scene.prototype.getWorldExtends = function (filterPredicate) {\n var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n filterPredicate = filterPredicate || (function () { return true; });\n this.meshes.filter(filterPredicate).forEach(function (mesh) {\n mesh.computeWorldMatrix(true);\n if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {\n return;\n }\n var boundingInfo = mesh.getBoundingInfo();\n var minBox = boundingInfo.boundingBox.minimumWorld;\n var maxBox = boundingInfo.boundingBox.maximumWorld;\n BABYLON.Tools.CheckExtends(minBox, min, max);\n BABYLON.Tools.CheckExtends(maxBox, min, max);\n });\n return {\n min: min,\n max: max\n };\n };\n /**\n * Creates or updates the octree used to boost selection (picking)\n * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees\n * @param maxCapacity defines the maximum capacity per leaf\n * @param maxDepth defines the maximum depth of the octree\n * @returns an octree of AbstractMesh\n */\n Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {\n if (maxCapacity === void 0) { maxCapacity = 64; }\n if (maxDepth === void 0) { maxDepth = 2; }\n if (!this._selectionOctree) {\n this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);\n }\n var worldExtends = this.getWorldExtends();\n // Update octree\n this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);\n return this._selectionOctree;\n };\n // Picking\n /**\n * Creates a ray that can be used to pick in the scene\n * @param x defines the x coordinate of the origin (on-screen)\n * @param y defines the y coordinate of the origin (on-screen)\n * @param world defines the world matrix to use if you want to pick in object space (instead of world space)\n * @param camera defines the camera to use for the picking\n * @param cameraViewSpace defines if picking will be done in view space (false by default)\n * @returns a Ray\n */\n Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {\n if (cameraViewSpace === void 0) { cameraViewSpace = false; }\n var result = BABYLON.Ray.Zero();\n this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);\n return result;\n };\n /**\n * Creates a ray that can be used to pick in the scene\n * @param x defines the x coordinate of the origin (on-screen)\n * @param y defines the y coordinate of the origin (on-screen)\n * @param world defines the world matrix to use if you want to pick in object space (instead of world space)\n * @param result defines the ray where to store the picking ray\n * @param camera defines the camera to use for the picking\n * @param cameraViewSpace defines if picking will be done in view space (false by default)\n * @returns the current scene\n */\n Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {\n if (cameraViewSpace === void 0) { cameraViewSpace = false; }\n var engine = this._engine;\n if (!camera) {\n if (!this.activeCamera)\n throw new Error(\"Active camera not set\");\n camera = this.activeCamera;\n }\n var cameraViewport = camera.viewport;\n var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n // Moving coordinates to local viewport world\n x = x / this._engine.getHardwareScalingLevel() - viewport.x;\n y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);\n result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());\n return this;\n };\n /**\n * Creates a ray that can be used to pick in the scene\n * @param x defines the x coordinate of the origin (on-screen)\n * @param y defines the y coordinate of the origin (on-screen)\n * @param camera defines the camera to use for the picking\n * @returns a Ray\n */\n Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {\n var result = BABYLON.Ray.Zero();\n this.createPickingRayInCameraSpaceToRef(x, y, result, camera);\n return result;\n };\n /**\n * Creates a ray that can be used to pick in the scene\n * @param x defines the x coordinate of the origin (on-screen)\n * @param y defines the y coordinate of the origin (on-screen)\n * @param result defines the ray where to store the picking ray\n * @param camera defines the camera to use for the picking\n * @returns the current scene\n */\n Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {\n if (!BABYLON.PickingInfo) {\n return this;\n }\n var engine = this._engine;\n if (!camera) {\n if (!this.activeCamera)\n throw new Error(\"Active camera not set\");\n camera = this.activeCamera;\n }\n var cameraViewport = camera.viewport;\n var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n var identity = BABYLON.Matrix.Identity();\n // Moving coordinates to local viewport world\n x = x / this._engine.getHardwareScalingLevel() - viewport.x;\n y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);\n result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());\n return this;\n };\n Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {\n if (!BABYLON.PickingInfo) {\n return null;\n }\n var pickingInfo = null;\n for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {\n var mesh = this.meshes[meshIndex];\n if (predicate) {\n if (!predicate(mesh)) {\n continue;\n }\n }\n else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {\n continue;\n }\n var world = mesh.getWorldMatrix();\n var ray = rayFunction(world);\n var result = mesh.intersects(ray, fastCheck);\n if (!result || !result.hit)\n continue;\n if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)\n continue;\n pickingInfo = result;\n if (fastCheck) {\n break;\n }\n }\n return pickingInfo || new BABYLON.PickingInfo();\n };\n Scene.prototype._internalMultiPick = function (rayFunction, predicate) {\n if (!BABYLON.PickingInfo) {\n return null;\n }\n var pickingInfos = new Array();\n for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {\n var mesh = this.meshes[meshIndex];\n if (predicate) {\n if (!predicate(mesh)) {\n continue;\n }\n }\n else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {\n continue;\n }\n var world = mesh.getWorldMatrix();\n var ray = rayFunction(world);\n var result = mesh.intersects(ray, false);\n if (!result || !result.hit)\n continue;\n pickingInfos.push(result);\n }\n return pickingInfos;\n };\n Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {\n if (!BABYLON.PickingInfo) {\n return null;\n }\n var pickingInfo = null;\n if (!camera) {\n if (!this.activeCamera) {\n return null;\n }\n camera = this.activeCamera;\n }\n if (this.spriteManagers.length > 0) {\n for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {\n var spriteManager = this.spriteManagers[spriteIndex];\n if (!spriteManager.isPickable) {\n continue;\n }\n var result = spriteManager.intersects(ray, camera, predicate, fastCheck);\n if (!result || !result.hit)\n continue;\n if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)\n continue;\n pickingInfo = result;\n if (fastCheck) {\n break;\n }\n }\n }\n return pickingInfo || new BABYLON.PickingInfo();\n };\n /** Launch a ray to try to pick a mesh in the scene\n * @param x position on screen\n * @param y position on screen\n * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true\n * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.\n * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used\n * @returns a PickingInfo\n */\n Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {\n var _this = this;\n if (!BABYLON.PickingInfo) {\n return null;\n }\n var result = this._internalPick(function (world) {\n _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);\n return _this._tempPickingRay;\n }, predicate, fastCheck);\n if (result) {\n result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);\n }\n return result;\n };\n /** Launch a ray to try to pick a sprite in the scene\n * @param x position on screen\n * @param y position on screen\n * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true\n * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.\n * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used\n * @returns a PickingInfo\n */\n Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {\n this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);\n return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);\n };\n /** Use the given ray to pick a mesh in the scene\n * @param ray The ray to use to pick meshes\n * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true\n * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null\n * @returns a PickingInfo\n */\n Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {\n var _this = this;\n var result = this._internalPick(function (world) {\n if (!_this._pickWithRayInverseMatrix) {\n _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();\n }\n world.invertToRef(_this._pickWithRayInverseMatrix);\n if (!_this._cachedRayForTransform) {\n _this._cachedRayForTransform = BABYLON.Ray.Zero();\n }\n BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);\n return _this._cachedRayForTransform;\n }, predicate, fastCheck);\n if (result) {\n result.ray = ray;\n }\n return result;\n };\n /**\n * Launch a ray to try to pick a mesh in the scene\n * @param x X position on screen\n * @param y Y position on screen\n * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true\n * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used\n * @returns an array of PickingInfo\n */\n Scene.prototype.multiPick = function (x, y, predicate, camera) {\n var _this = this;\n return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);\n };\n /**\n * Launch a ray to try to pick a mesh in the scene\n * @param ray Ray to use\n * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true\n * @returns an array of PickingInfo\n */\n Scene.prototype.multiPickWithRay = function (ray, predicate) {\n var _this = this;\n return this._internalMultiPick(function (world) {\n if (!_this._pickWithRayInverseMatrix) {\n _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();\n }\n world.invertToRef(_this._pickWithRayInverseMatrix);\n if (!_this._cachedRayForTransform) {\n _this._cachedRayForTransform = BABYLON.Ray.Zero();\n }\n BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);\n return _this._cachedRayForTransform;\n }, predicate);\n };\n /**\n * Force the value of meshUnderPointer\n * @param mesh defines the mesh to use\n */\n Scene.prototype.setPointerOverMesh = function (mesh) {\n if (this._pointerOverMesh === mesh) {\n return;\n }\n if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {\n this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));\n }\n this._pointerOverMesh = mesh;\n if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {\n this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));\n }\n };\n /**\n * Gets the mesh under the pointer\n * @returns a Mesh or null if no mesh is under the pointer\n */\n Scene.prototype.getPointerOverMesh = function () {\n return this._pointerOverMesh;\n };\n /**\n * Force the sprite under the pointer\n * @param sprite defines the sprite to use\n */\n Scene.prototype.setPointerOverSprite = function (sprite) {\n if (this._pointerOverSprite === sprite) {\n return;\n }\n if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {\n this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));\n }\n this._pointerOverSprite = sprite;\n if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {\n this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));\n }\n };\n /**\n * Gets the sprite under the pointer\n * @returns a Sprite or null if no sprite is under the pointer\n */\n Scene.prototype.getPointerOverSprite = function () {\n return this._pointerOverSprite;\n };\n // Physics\n /**\n * Gets the current physics engine\n * @returns a PhysicsEngine or null if none attached\n */\n Scene.prototype.getPhysicsEngine = function () {\n return this._physicsEngine;\n };\n /**\n * Enables physics to the current scene\n * @param gravity defines the scene's gravity for the physics engine\n * @param plugin defines the physics engine to be used. defaults to OimoJS.\n * @return a boolean indicating if the physics engine was initialized\n */\n Scene.prototype.enablePhysics = function (gravity, plugin) {\n if (gravity === void 0) { gravity = null; }\n if (this._physicsEngine) {\n return true;\n }\n try {\n this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);\n return true;\n }\n catch (e) {\n BABYLON.Tools.Error(e.message);\n return false;\n }\n };\n /**\n * Disables and disposes the physics engine associated with the scene\n */\n Scene.prototype.disablePhysicsEngine = function () {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.dispose();\n this._physicsEngine = null;\n };\n /**\n * Gets a boolean indicating if there is an active physics engine\n * @returns a boolean indicating if there is an active physics engine\n */\n Scene.prototype.isPhysicsEnabled = function () {\n return this._physicsEngine !== undefined;\n };\n /**\n * Deletes a physics compound impostor\n * @param compound defines the compound to delete\n */\n Scene.prototype.deleteCompoundImpostor = function (compound) {\n var mesh = compound.parts[0].mesh;\n if (mesh.physicsImpostor) {\n mesh.physicsImpostor.dispose( /*true*/);\n mesh.physicsImpostor = null;\n }\n };\n // Misc.\n /** @hidden */\n Scene.prototype._rebuildGeometries = function () {\n for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {\n var geometry = _a[_i];\n geometry._rebuild();\n }\n for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {\n var mesh = _c[_b];\n mesh._rebuild();\n }\n if (this.postProcessManager) {\n this.postProcessManager._rebuild();\n }\n for (var _d = 0, _e = this._components; _d < _e.length; _d++) {\n var component = _e[_d];\n component.rebuild();\n }\n for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {\n var system = _g[_f];\n system.rebuild();\n }\n if (this._postProcessRenderPipelineManager) {\n this._postProcessRenderPipelineManager._rebuild();\n }\n };\n /** @hidden */\n Scene.prototype._rebuildTextures = function () {\n for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {\n var texture = _a[_i];\n texture._rebuild();\n }\n this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n };\n /**\n * Creates a default light for the scene.\n * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light\n * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light\n */\n Scene.prototype.createDefaultLight = function (replace) {\n if (replace === void 0) { replace = false; }\n // Dispose existing light in replace mode.\n if (replace) {\n if (this.lights) {\n for (var i = 0; i < this.lights.length; i++) {\n this.lights[i].dispose();\n }\n }\n }\n // Light\n if (this.lights.length === 0) {\n new BABYLON.HemisphericLight(\"default light\", BABYLON.Vector3.Up(), this);\n }\n };\n /**\n * Creates a default camera for the scene.\n * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera\n * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera\n * @param replace has default false, when true replaces the active camera in the scene\n * @param attachCameraControls has default false, when true attaches camera controls to the canvas.\n */\n Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {\n if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }\n if (replace === void 0) { replace = false; }\n if (attachCameraControls === void 0) { attachCameraControls = false; }\n // Dispose existing camera in replace mode.\n if (replace) {\n if (this.activeCamera) {\n this.activeCamera.dispose();\n this.activeCamera = null;\n }\n }\n // Camera\n if (!this.activeCamera) {\n var worldExtends = this.getWorldExtends();\n var worldSize = worldExtends.max.subtract(worldExtends.min);\n var worldCenter = worldExtends.min.add(worldSize.scale(0.5));\n var camera;\n var radius = worldSize.length() * 1.5;\n // empty scene scenario!\n if (!isFinite(radius)) {\n radius = 1;\n worldCenter.copyFromFloats(0, 0, 0);\n }\n if (createArcRotateCamera) {\n var arcRotateCamera = new BABYLON.ArcRotateCamera(\"default camera\", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);\n arcRotateCamera.lowerRadiusLimit = radius * 0.01;\n arcRotateCamera.wheelPrecision = 100 / radius;\n camera = arcRotateCamera;\n }\n else {\n var freeCamera = new BABYLON.FreeCamera(\"default camera\", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);\n freeCamera.setTarget(worldCenter);\n camera = freeCamera;\n }\n camera.minZ = radius * 0.01;\n camera.maxZ = radius * 1000;\n camera.speed = radius * 0.2;\n this.activeCamera = camera;\n var canvas = this.getEngine().getRenderingCanvas();\n if (attachCameraControls && canvas) {\n camera.attachControl(canvas);\n }\n }\n };\n /**\n * Creates a default camera and a default light.\n * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light\n * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera\n * @param replace has the default false, when true replaces the active camera/light in the scene\n * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.\n */\n Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {\n if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }\n if (replace === void 0) { replace = false; }\n if (attachCameraControls === void 0) { attachCameraControls = false; }\n this.createDefaultLight(replace);\n this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);\n };\n /**\n * Creates a new sky box\n * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox\n * @param environmentTexture defines the texture to use as environment texture\n * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used\n * @param scale defines the overall scale of the skybox\n * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1\n * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture\n * @returns a new mesh holding the sky box\n */\n Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {\n if (pbr === void 0) { pbr = false; }\n if (scale === void 0) { scale = 1000; }\n if (blur === void 0) { blur = 0; }\n if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }\n if (!environmentTexture) {\n BABYLON.Tools.Warn(\"Can not create default skybox without environment texture.\");\n return null;\n }\n if (setGlobalEnvTexture) {\n if (environmentTexture) {\n this.environmentTexture = environmentTexture;\n }\n }\n // Skybox\n var hdrSkybox = BABYLON.Mesh.CreateBox(\"hdrSkyBox\", scale, this);\n if (pbr) {\n var hdrSkyboxMaterial = new BABYLON.PBRMaterial(\"skyBox\", this);\n hdrSkyboxMaterial.backFaceCulling = false;\n hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();\n if (hdrSkyboxMaterial.reflectionTexture) {\n hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;\n }\n hdrSkyboxMaterial.microSurface = 1.0 - blur;\n hdrSkyboxMaterial.disableLighting = true;\n hdrSkyboxMaterial.twoSidedLighting = true;\n hdrSkybox.infiniteDistance = true;\n hdrSkybox.material = hdrSkyboxMaterial;\n }\n else {\n var skyboxMaterial = new BABYLON.StandardMaterial(\"skyBox\", this);\n skyboxMaterial.backFaceCulling = false;\n skyboxMaterial.reflectionTexture = environmentTexture.clone();\n if (skyboxMaterial.reflectionTexture) {\n skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;\n }\n skyboxMaterial.disableLighting = true;\n hdrSkybox.infiniteDistance = true;\n hdrSkybox.material = skyboxMaterial;\n }\n return hdrSkybox;\n };\n /**\n * Creates a new environment\n * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment\n * @param options defines the options you can use to configure the environment\n * @returns the new EnvironmentHelper\n */\n Scene.prototype.createDefaultEnvironment = function (options) {\n if (BABYLON.EnvironmentHelper) {\n return new BABYLON.EnvironmentHelper(options, this);\n }\n return null;\n };\n /**\n * Creates a new VREXperienceHelper\n * @see http://doc.babylonjs.com/how_to/webvr_helper\n * @param webVROptions defines the options used to create the new VREXperienceHelper\n * @returns a new VREXperienceHelper\n */\n Scene.prototype.createDefaultVRExperience = function (webVROptions) {\n if (webVROptions === void 0) { webVROptions = {}; }\n return new BABYLON.VRExperienceHelper(this, webVROptions);\n };\n // Tags\n Scene.prototype._getByTags = function (list, tagsQuery, forEach) {\n if (tagsQuery === undefined) {\n // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)\n return list;\n }\n var listByTags = [];\n forEach = forEach || (function (item) { return; });\n for (var i in list) {\n var item = list[i];\n if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {\n listByTags.push(item);\n forEach(item);\n }\n }\n return listByTags;\n };\n /**\n * Get a list of meshes by tags\n * @param tagsQuery defines the tags query to use\n * @param forEach defines a predicate used to filter results\n * @returns an array of Mesh\n */\n Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {\n return this._getByTags(this.meshes, tagsQuery, forEach);\n };\n /**\n * Get a list of cameras by tags\n * @param tagsQuery defines the tags query to use\n * @param forEach defines a predicate used to filter results\n * @returns an array of Camera\n */\n Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {\n return this._getByTags(this.cameras, tagsQuery, forEach);\n };\n /**\n * Get a list of lights by tags\n * @param tagsQuery defines the tags query to use\n * @param forEach defines a predicate used to filter results\n * @returns an array of Light\n */\n Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {\n return this._getByTags(this.lights, tagsQuery, forEach);\n };\n /**\n * Get a list of materials by tags\n * @param tagsQuery defines the tags query to use\n * @param forEach defines a predicate used to filter results\n * @returns an array of Material\n */\n Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {\n return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));\n };\n /**\n * Overrides the default sort function applied in the renderging group to prepare the meshes.\n * This allowed control for front to back rendering or reversly depending of the special needs.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param opaqueSortCompareFn The opaque queue comparison function use to sort.\n * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.\n * @param transparentSortCompareFn The transparent queue comparison function use to sort.\n */\n Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {\n if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }\n if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }\n if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }\n this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);\n };\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n * @param depth Automatically clears depth between groups if true and autoClear is true.\n * @param stencil Automatically clears stencil between groups if true and autoClear is true.\n */\n Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {\n if (depth === void 0) { depth = true; }\n if (stencil === void 0) { stencil = true; }\n this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);\n };\n /**\n * Gets the current auto clear configuration for one rendering group of the rendering\n * manager.\n * @param index the rendering group index to get the information for\n * @returns The auto clear setup for the requested rendering group\n */\n Scene.prototype.getAutoClearDepthStencilSetup = function (index) {\n return this._renderingManager.getAutoClearDepthStencilSetup(index);\n };\n /**\n * Will flag all materials as dirty to trigger new shader compilation\n * @param flag defines the flag used to specify which material part must be marked as dirty\n * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty\n */\n Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {\n for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {\n var material = _a[_i];\n if (predicate && !predicate(material)) {\n continue;\n }\n material.markAsDirty(flag);\n }\n };\n /** @hidden */\n Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {\n var _this = this;\n var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);\n this._activeRequests.push(request);\n request.onCompleteObservable.add(function (request) {\n _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);\n });\n return request;\n };\n /** @hidden */\n Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this._loadFile(url, function (data) {\n resolve(data);\n }, undefined, useDatabase, useArrayBuffer, function (request, exception) {\n reject(exception);\n });\n });\n };\n // Statics\n Scene._FOGMODE_NONE = 0;\n Scene._FOGMODE_EXP = 1;\n Scene._FOGMODE_EXP2 = 2;\n Scene._FOGMODE_LINEAR = 3;\n Scene._uniqueIdCounter = 0;\n /**\n * Gets or sets the minimum deltatime when deterministic lock step is enabled\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n */\n Scene.MinDeltaTime = 1.0;\n /**\n * Gets or sets the maximum deltatime when deterministic lock step is enabled\n * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep\n */\n Scene.MaxDeltaTime = 1000.0;\n /** The distance in pixel that you have to move to prevent some events */\n Scene.DragMovementThreshold = 10; // in pixels\n /** Time in milliseconds to wait to raise long press events if button is still pressed */\n Scene.LongPressDelay = 500; // in milliseconds\n /** Time in milliseconds with two consecutive clicks will be considered as a double click */\n Scene.DoubleClickDelay = 300; // in milliseconds\n /** If you need to check double click without raising a single click at first click, enable this flag */\n Scene.ExclusiveDoubleClickMode = false;\n return Scene;\n }(BABYLON.AbstractScene));\n BABYLON.Scene = Scene;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.scene.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Set of assets to keep when moving a scene into an asset container.\n */\n var KeepAssets = /** @class */ (function (_super) {\n __extends(KeepAssets, _super);\n function KeepAssets() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n return KeepAssets;\n }(BABYLON.AbstractScene));\n BABYLON.KeepAssets = KeepAssets;\n /**\n * Container with a set of assets that can be added or removed from a scene.\n */\n var AssetContainer = /** @class */ (function (_super) {\n __extends(AssetContainer, _super);\n /**\n * Instantiates an AssetContainer.\n * @param scene The scene the AssetContainer belongs to.\n */\n function AssetContainer(scene) {\n var _this = _super.call(this) || this;\n _this.scene = scene;\n return _this;\n }\n /**\n * Adds all the assets from the container to the scene.\n */\n AssetContainer.prototype.addAllToScene = function () {\n var _this = this;\n this.cameras.forEach(function (o) {\n _this.scene.addCamera(o);\n });\n this.lights.forEach(function (o) {\n _this.scene.addLight(o);\n });\n this.meshes.forEach(function (o) {\n _this.scene.addMesh(o);\n });\n this.skeletons.forEach(function (o) {\n _this.scene.addSkeleton(o);\n });\n this.animations.forEach(function (o) {\n _this.scene.addAnimation(o);\n });\n this.animationGroups.forEach(function (o) {\n _this.scene.addAnimationGroup(o);\n });\n this.multiMaterials.forEach(function (o) {\n _this.scene.addMultiMaterial(o);\n });\n this.materials.forEach(function (o) {\n _this.scene.addMaterial(o);\n });\n this.morphTargetManagers.forEach(function (o) {\n _this.scene.addMorphTargetManager(o);\n });\n this.geometries.forEach(function (o) {\n _this.scene.addGeometry(o);\n });\n this.transformNodes.forEach(function (o) {\n _this.scene.addTransformNode(o);\n });\n this.actionManagers.forEach(function (o) {\n _this.scene.addActionManager(o);\n });\n this.sounds.forEach(function (o) {\n o.play();\n o.autoplay = true;\n _this.scene.mainSoundTrack.AddSound(o);\n });\n this.textures.forEach(function (o) {\n _this.scene.addTexture(o);\n });\n for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {\n var component = _a[_i];\n component.addFromContainer(this.scene);\n }\n };\n /**\n * Removes all the assets in the container from the scene\n */\n AssetContainer.prototype.removeAllFromScene = function () {\n var _this = this;\n this.cameras.forEach(function (o) {\n _this.scene.removeCamera(o);\n });\n this.lights.forEach(function (o) {\n _this.scene.removeLight(o);\n });\n this.meshes.forEach(function (o) {\n _this.scene.removeMesh(o);\n });\n this.skeletons.forEach(function (o) {\n _this.scene.removeSkeleton(o);\n });\n this.animations.forEach(function (o) {\n _this.scene.removeAnimation(o);\n });\n this.animationGroups.forEach(function (o) {\n _this.scene.removeAnimationGroup(o);\n });\n this.multiMaterials.forEach(function (o) {\n _this.scene.removeMultiMaterial(o);\n });\n this.materials.forEach(function (o) {\n _this.scene.removeMaterial(o);\n });\n this.morphTargetManagers.forEach(function (o) {\n _this.scene.removeMorphTargetManager(o);\n });\n this.geometries.forEach(function (o) {\n _this.scene.removeGeometry(o);\n });\n this.transformNodes.forEach(function (o) {\n _this.scene.removeTransformNode(o);\n });\n this.actionManagers.forEach(function (o) {\n _this.scene.removeActionManager(o);\n });\n this.sounds.forEach(function (o) {\n o.stop();\n o.autoplay = false;\n _this.scene.mainSoundTrack.RemoveSound(o);\n });\n this.textures.forEach(function (o) {\n _this.scene.removeTexture(o);\n });\n for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {\n var component = _a[_i];\n component.removeFromContainer(this.scene);\n }\n };\n AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {\n if (!sourceAssets) {\n return;\n }\n for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {\n var asset = sourceAssets_1[_i];\n var move = true;\n if (keepAssets) {\n for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {\n var keepAsset = keepAssets_1[_a];\n if (asset === keepAsset) {\n move = false;\n break;\n }\n }\n }\n if (move) {\n targetAssets.push(asset);\n }\n }\n };\n /**\n * Removes all the assets contained in the scene and adds them to the container.\n * @param keepAssets Set of assets to keep in the scene. (default: empty)\n */\n AssetContainer.prototype.moveAllFromScene = function (keepAssets) {\n if (keepAssets === undefined) {\n keepAssets = new KeepAssets();\n }\n for (var key in this) {\n if (this.hasOwnProperty(key)) {\n this[key] = this[key] || [];\n this._moveAssets(this.scene[key], this[key], keepAssets[key]);\n }\n }\n this.removeAllFromScene();\n };\n /**\n * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.\n * @returns the root mesh\n */\n AssetContainer.prototype.createRootMesh = function () {\n var rootMesh = new BABYLON.Mesh(\"assetContainerRootMesh\", this.scene);\n this.meshes.forEach(function (m) {\n if (!m.parent) {\n rootMesh.addChild(m);\n }\n });\n this.meshes.unshift(rootMesh);\n return rootMesh;\n };\n return AssetContainer;\n }(BABYLON.AbstractScene));\n BABYLON.AssetContainer = AssetContainer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.assetContainer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Buffer = /** @class */ (function () {\n /**\n * Constructor\n * @param engine the engine\n * @param data the data to use for this buffer\n * @param updatable whether the data is updatable\n * @param stride the stride (optional)\n * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)\n * @param instanced whether the buffer is instanced (optional)\n * @param useBytes set to true if the stride in in bytes (optional)\n */\n function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {\n if (stride === void 0) { stride = 0; }\n if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }\n if (instanced === void 0) { instanced = false; }\n if (useBytes === void 0) { useBytes = false; }\n if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'\n this._engine = engine.getScene().getEngine();\n }\n else {\n this._engine = engine;\n }\n this._updatable = updatable;\n this._instanced = instanced;\n this._data = data;\n this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;\n if (!postponeInternalCreation) { // by default\n this.create();\n }\n }\n /**\n * Create a new {BABYLON.VertexBuffer} based on the current buffer\n * @param kind defines the vertex buffer kind (position, normal, etc.)\n * @param offset defines offset in the buffer (0 by default)\n * @param size defines the size in floats of attributes (position is 3 for instance)\n * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)\n * @param instanced defines if the vertex buffer contains indexed data\n * @param useBytes defines if the offset and stride are in bytes\n * @returns the new vertex buffer\n */\n Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {\n if (useBytes === void 0) { useBytes = false; }\n var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;\n var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;\n // a lot of these parameters are ignored as they are overriden by the buffer\n return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);\n };\n // Properties\n Buffer.prototype.isUpdatable = function () {\n return this._updatable;\n };\n Buffer.prototype.getData = function () {\n return this._data;\n };\n Buffer.prototype.getBuffer = function () {\n return this._buffer;\n };\n /**\n * Gets the stride in float32 units (i.e. byte stride / 4).\n * May not be an integer if the byte stride is not divisible by 4.\n * DEPRECATED. Use byteStride instead.\n * @returns the stride in float32 units\n */\n Buffer.prototype.getStrideSize = function () {\n return this.byteStride / Float32Array.BYTES_PER_ELEMENT;\n };\n // Methods\n Buffer.prototype.create = function (data) {\n if (data === void 0) { data = null; }\n if (!data && this._buffer) {\n return; // nothing to do\n }\n data = data || this._data;\n if (!data) {\n return;\n }\n if (!this._buffer) { // create buffer\n if (this._updatable) {\n this._buffer = this._engine.createDynamicVertexBuffer(data);\n this._data = data;\n }\n else {\n this._buffer = this._engine.createVertexBuffer(data);\n }\n }\n else if (this._updatable) { // update buffer\n this._engine.updateDynamicVertexBuffer(this._buffer, data);\n this._data = data;\n }\n };\n Buffer.prototype._rebuild = function () {\n this._buffer = null;\n this.create(this._data);\n };\n Buffer.prototype.update = function (data) {\n this.create(data);\n };\n /**\n * Updates the data directly.\n * @param data the new data\n * @param offset the new offset\n * @param vertexCount the vertex count (optional)\n * @param useBytes set to true if the offset is in bytes\n */\n Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {\n if (useBytes === void 0) { useBytes = false; }\n if (!this._buffer) {\n return;\n }\n if (this._updatable) { // update buffer\n this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));\n this._data = null;\n }\n };\n Buffer.prototype.dispose = function () {\n if (!this._buffer) {\n return;\n }\n if (this._engine._releaseBuffer(this._buffer)) {\n this._buffer = null;\n }\n };\n return Buffer;\n }());\n BABYLON.Buffer = Buffer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.buffer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var VertexBuffer = /** @class */ (function () {\n /**\n * Constructor\n * @param engine the engine\n * @param data the data to use for this vertex buffer\n * @param kind the vertex buffer kind\n * @param updatable whether the data is updatable\n * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)\n * @param stride the stride (optional)\n * @param instanced whether the buffer is instanced (optional)\n * @param offset the offset of the data (optional)\n * @param size the number of components (optional)\n * @param type the type of the component (optional)\n * @param normalized whether the data contains normalized data (optional)\n * @param useBytes set to true if stride and offset are in bytes (optional)\n */\n function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {\n if (normalized === void 0) { normalized = false; }\n if (useBytes === void 0) { useBytes = false; }\n if (data instanceof BABYLON.Buffer) {\n this._buffer = data;\n this._ownsBuffer = false;\n }\n else {\n this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);\n this._ownsBuffer = true;\n }\n this._kind = kind;\n if (type == undefined) {\n var data_1 = this.getData();\n this.type = VertexBuffer.FLOAT;\n if (data_1 instanceof Int8Array)\n this.type = VertexBuffer.BYTE;\n else if (data_1 instanceof Uint8Array)\n this.type = VertexBuffer.UNSIGNED_BYTE;\n else if (data_1 instanceof Int16Array)\n this.type = VertexBuffer.SHORT;\n else if (data_1 instanceof Uint16Array)\n this.type = VertexBuffer.UNSIGNED_SHORT;\n else if (data_1 instanceof Int32Array)\n this.type = VertexBuffer.INT;\n else if (data_1 instanceof Uint32Array)\n this.type = VertexBuffer.UNSIGNED_INT;\n }\n else {\n this.type = type;\n }\n var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);\n if (useBytes) {\n this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));\n this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);\n this.byteOffset = offset || 0;\n }\n else {\n this._size = size || stride || VertexBuffer.DeduceStride(kind);\n this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));\n this.byteOffset = (offset || 0) * typeByteLength;\n }\n this.normalized = normalized;\n this._instanced = instanced !== undefined ? instanced : false;\n this._instanceDivisor = instanced ? 1 : 0;\n }\n Object.defineProperty(VertexBuffer.prototype, \"instanceDivisor\", {\n /**\n * Gets or sets the instance divisor when in instanced mode\n */\n get: function () {\n return this._instanceDivisor;\n },\n set: function (value) {\n this._instanceDivisor = value;\n if (value == 0) {\n this._instanced = false;\n }\n else {\n this._instanced = true;\n }\n },\n enumerable: true,\n configurable: true\n });\n VertexBuffer.prototype._rebuild = function () {\n if (!this._buffer) {\n return;\n }\n this._buffer._rebuild();\n };\n /**\n * Returns the kind of the VertexBuffer (string).\n */\n VertexBuffer.prototype.getKind = function () {\n return this._kind;\n };\n // Properties\n /**\n * Boolean : is the VertexBuffer updatable ?\n */\n VertexBuffer.prototype.isUpdatable = function () {\n return this._buffer.isUpdatable();\n };\n /**\n * Returns an array of numbers or a typed array containing the VertexBuffer data.\n */\n VertexBuffer.prototype.getData = function () {\n return this._buffer.getData();\n };\n /**\n * Returns the WebGLBuffer associated to the VertexBuffer.\n */\n VertexBuffer.prototype.getBuffer = function () {\n return this._buffer.getBuffer();\n };\n /**\n * Returns the stride as a multiple of the type byte length.\n * DEPRECATED. Use byteStride instead.\n */\n VertexBuffer.prototype.getStrideSize = function () {\n return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);\n };\n /**\n * Returns the offset as a multiple of the type byte length.\n * DEPRECATED. Use byteOffset instead.\n */\n VertexBuffer.prototype.getOffset = function () {\n return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);\n };\n /**\n * Returns the number of components per vertex attribute (integer).\n */\n VertexBuffer.prototype.getSize = function () {\n return this._size;\n };\n /**\n * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?\n */\n VertexBuffer.prototype.getIsInstanced = function () {\n return this._instanced;\n };\n /**\n * Returns the instancing divisor, zero for non-instanced (integer).\n */\n VertexBuffer.prototype.getInstanceDivisor = function () {\n return this._instanceDivisor;\n };\n // Methods\n /**\n * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.\n * Returns the created WebGLBuffer.\n */\n VertexBuffer.prototype.create = function (data) {\n return this._buffer.create(data);\n };\n /**\n * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.\n * This function will create a new buffer if the current one is not updatable\n * Returns the updated WebGLBuffer.\n */\n VertexBuffer.prototype.update = function (data) {\n return this._buffer.update(data);\n };\n /**\n * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.\n * Returns the directly updated WebGLBuffer.\n * @param data the new data\n * @param offset the new offset\n * @param useBytes set to true if the offset is in bytes\n */\n VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {\n if (useBytes === void 0) { useBytes = false; }\n this._buffer.updateDirectly(data, offset, undefined, useBytes);\n };\n /**\n * Disposes the VertexBuffer and the underlying WebGLBuffer.\n */\n VertexBuffer.prototype.dispose = function () {\n if (this._ownsBuffer) {\n this._buffer.dispose();\n }\n };\n /**\n * Enumerates each value of this vertex buffer as numbers.\n * @param count the number of values to enumerate\n * @param callback the callback function called for each value\n */\n VertexBuffer.prototype.forEach = function (count, callback) {\n VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);\n };\n Object.defineProperty(VertexBuffer, \"PositionKind\", {\n get: function () {\n return VertexBuffer._PositionKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"NormalKind\", {\n get: function () {\n return VertexBuffer._NormalKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"TangentKind\", {\n get: function () {\n return VertexBuffer._TangentKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"UVKind\", {\n get: function () {\n return VertexBuffer._UVKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"UV2Kind\", {\n get: function () {\n return VertexBuffer._UV2Kind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"UV3Kind\", {\n get: function () {\n return VertexBuffer._UV3Kind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"UV4Kind\", {\n get: function () {\n return VertexBuffer._UV4Kind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"UV5Kind\", {\n get: function () {\n return VertexBuffer._UV5Kind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"UV6Kind\", {\n get: function () {\n return VertexBuffer._UV6Kind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"ColorKind\", {\n get: function () {\n return VertexBuffer._ColorKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"MatricesIndicesKind\", {\n get: function () {\n return VertexBuffer._MatricesIndicesKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"MatricesWeightsKind\", {\n get: function () {\n return VertexBuffer._MatricesWeightsKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"MatricesIndicesExtraKind\", {\n get: function () {\n return VertexBuffer._MatricesIndicesExtraKind;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VertexBuffer, \"MatricesWeightsExtraKind\", {\n get: function () {\n return VertexBuffer._MatricesWeightsExtraKind;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Deduces the stride given a kind.\n * @param kind The kind string to deduce\n * @returns The deduced stride\n */\n VertexBuffer.DeduceStride = function (kind) {\n switch (kind) {\n case VertexBuffer.UVKind:\n case VertexBuffer.UV2Kind:\n case VertexBuffer.UV3Kind:\n case VertexBuffer.UV4Kind:\n case VertexBuffer.UV5Kind:\n case VertexBuffer.UV6Kind:\n return 2;\n case VertexBuffer.NormalKind:\n case VertexBuffer.PositionKind:\n return 3;\n case VertexBuffer.ColorKind:\n case VertexBuffer.MatricesIndicesKind:\n case VertexBuffer.MatricesIndicesExtraKind:\n case VertexBuffer.MatricesWeightsKind:\n case VertexBuffer.MatricesWeightsExtraKind:\n case VertexBuffer.TangentKind:\n return 4;\n default:\n throw new Error(\"Invalid kind '\" + kind + \"'\");\n }\n };\n /**\n * Gets the byte length of the given type.\n * @param type the type\n * @returns the number of bytes\n */\n VertexBuffer.GetTypeByteLength = function (type) {\n switch (type) {\n case VertexBuffer.BYTE:\n case VertexBuffer.UNSIGNED_BYTE:\n return 1;\n case VertexBuffer.SHORT:\n case VertexBuffer.UNSIGNED_SHORT:\n return 2;\n case VertexBuffer.INT:\n case VertexBuffer.FLOAT:\n return 4;\n default:\n throw new Error(\"Invalid type '\" + type + \"'\");\n }\n };\n /**\n * Enumerates each value of the given parameters as numbers.\n * @param data the data to enumerate\n * @param byteOffset the byte offset of the data\n * @param byteStride the byte stride of the data\n * @param componentCount the number of components per element\n * @param componentType the type of the component\n * @param count the total number of components\n * @param normalized whether the data is normalized\n * @param callback the callback function called for each value\n */\n VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {\n if (data instanceof Array) {\n var offset = byteOffset / 4;\n var stride = byteStride / 4;\n for (var index = 0; index < count; index += componentCount) {\n for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {\n callback(data[offset + componentIndex], index + componentIndex);\n }\n offset += stride;\n }\n }\n else {\n var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);\n var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);\n for (var index = 0; index < count; index += componentCount) {\n var componentByteOffset = byteOffset;\n for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {\n var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);\n callback(value, index + componentIndex);\n componentByteOffset += componentByteLength;\n }\n byteOffset += byteStride;\n }\n }\n };\n VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {\n switch (type) {\n case VertexBuffer.BYTE: {\n var value = dataView.getInt8(byteOffset);\n if (normalized) {\n value = Math.max(value / 127, -1);\n }\n return value;\n }\n case VertexBuffer.UNSIGNED_BYTE: {\n var value = dataView.getUint8(byteOffset);\n if (normalized) {\n value = value / 255;\n }\n return value;\n }\n case VertexBuffer.SHORT: {\n var value = dataView.getInt16(byteOffset, true);\n if (normalized) {\n value = Math.max(value / 16383, -1);\n }\n return value;\n }\n case VertexBuffer.UNSIGNED_SHORT: {\n var value = dataView.getUint16(byteOffset, true);\n if (normalized) {\n value = value / 65535;\n }\n return value;\n }\n case VertexBuffer.FLOAT: {\n return dataView.getFloat32(byteOffset, true);\n }\n default: {\n throw new Error(\"Invalid component type \" + type);\n }\n }\n };\n /**\n * The byte type.\n */\n VertexBuffer.BYTE = 5120;\n /**\n * The unsigned byte type.\n */\n VertexBuffer.UNSIGNED_BYTE = 5121;\n /**\n * The short type.\n */\n VertexBuffer.SHORT = 5122;\n /**\n * The unsigned short type.\n */\n VertexBuffer.UNSIGNED_SHORT = 5123;\n /**\n * The integer type.\n */\n VertexBuffer.INT = 5124;\n /**\n * The unsigned integer type.\n */\n VertexBuffer.UNSIGNED_INT = 5125;\n /**\n * The float type.\n */\n VertexBuffer.FLOAT = 5126;\n // Enums\n VertexBuffer._PositionKind = \"position\";\n VertexBuffer._NormalKind = \"normal\";\n VertexBuffer._TangentKind = \"tangent\";\n VertexBuffer._UVKind = \"uv\";\n VertexBuffer._UV2Kind = \"uv2\";\n VertexBuffer._UV3Kind = \"uv3\";\n VertexBuffer._UV4Kind = \"uv4\";\n VertexBuffer._UV5Kind = \"uv5\";\n VertexBuffer._UV6Kind = \"uv6\";\n VertexBuffer._ColorKind = \"color\";\n VertexBuffer._MatricesIndicesKind = \"matricesIndices\";\n VertexBuffer._MatricesWeightsKind = \"matricesWeights\";\n VertexBuffer._MatricesIndicesExtraKind = \"matricesIndicesExtra\";\n VertexBuffer._MatricesWeightsExtraKind = \"matricesWeightsExtra\";\n return VertexBuffer;\n }());\n BABYLON.VertexBuffer = VertexBuffer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vertexBuffer.js.map\n\n\n\n//# sourceMappingURL=babylon.internalTextureLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context\n */\n var DummyInternalTextureTracker = /** @class */ (function () {\n function DummyInternalTextureTracker() {\n /**\n * Gets or set the previous tracker in the list\n */\n this.previous = null;\n /**\n * Gets or set the next tracker in the list\n */\n this.next = null;\n }\n return DummyInternalTextureTracker;\n }());\n BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.internalTextureTracker.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to store data associated with WebGL texture data for the engine\n * This class should not be used directly\n */\n var InternalTexture = /** @class */ (function () {\n /**\n * Creates a new InternalTexture\n * @param engine defines the engine to use\n * @param dataSource defines the type of data that will be used\n */\n function InternalTexture(engine, dataSource) {\n /**\n * Observable called when the texture is loaded\n */\n this.onLoadedObservable = new BABYLON.Observable();\n /**\n * Gets or set the previous tracker in the list\n */\n this.previous = null;\n /**\n * Gets or set the next tracker in the list\n */\n this.next = null;\n // Private\n /** @hidden */\n this._initialSlot = -1;\n /** @hidden */\n this._designatedSlot = -1;\n /** @hidden */\n this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;\n /** @hidden */\n this._comparisonFunction = 0;\n /** @hidden */\n this._sphericalPolynomial = null;\n /** @hidden */\n this._lodGenerationScale = 0;\n /** @hidden */\n this._lodGenerationOffset = 0;\n /** @hidden */\n this._isRGBD = false;\n /** @hidden */\n this._references = 1;\n this._engine = engine;\n this._dataSource = dataSource;\n this._webGLTexture = engine._createTexture();\n }\n /**\n * Gets the Engine the texture belongs to.\n * @returns The babylon engine\n */\n InternalTexture.prototype.getEngine = function () {\n return this._engine;\n };\n Object.defineProperty(InternalTexture.prototype, \"dataSource\", {\n /**\n * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)\n */\n get: function () {\n return this._dataSource;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)\n */\n InternalTexture.prototype.incrementReferences = function () {\n this._references++;\n };\n /**\n * Change the size of the texture (not the size of the content)\n * @param width defines the new width\n * @param height defines the new height\n * @param depth defines the new depth (1 by default)\n */\n InternalTexture.prototype.updateSize = function (width, height, depth) {\n if (depth === void 0) { depth = 1; }\n this.width = width;\n this.height = height;\n this.depth = depth;\n this.baseWidth = width;\n this.baseHeight = height;\n this.baseDepth = depth;\n this._size = width * height * depth;\n };\n /** @hidden */\n InternalTexture.prototype._rebuild = function () {\n var _this = this;\n var proxy;\n this.isReady = false;\n this._cachedCoordinatesMode = null;\n this._cachedWrapU = null;\n this._cachedWrapV = null;\n this._cachedAnisotropicFilteringLevel = null;\n switch (this._dataSource) {\n case InternalTexture.DATASOURCE_TEMP:\n return;\n case InternalTexture.DATASOURCE_URL:\n proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {\n _this.isReady = true;\n }, null, this._buffer, undefined, this.format);\n proxy._swapAndDie(this);\n return;\n case InternalTexture.DATASOURCE_RAW:\n proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);\n proxy._swapAndDie(this);\n this.isReady = true;\n return;\n case InternalTexture.DATASOURCE_RAW3D:\n proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);\n proxy._swapAndDie(this);\n this.isReady = true;\n return;\n case InternalTexture.DATASOURCE_DYNAMIC:\n proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);\n proxy._swapAndDie(this);\n // The engine will make sure to update content so no need to flag it as isReady = true\n return;\n case InternalTexture.DATASOURCE_RENDERTARGET:\n var options = new BABYLON.RenderTargetCreationOptions();\n options.generateDepthBuffer = this._generateDepthBuffer;\n options.generateMipMaps = this.generateMipMaps;\n options.generateStencilBuffer = this._generateStencilBuffer;\n options.samplingMode = this.samplingMode;\n options.type = this.type;\n if (this.isCube) {\n proxy = this._engine.createRenderTargetCubeTexture(this.width, options);\n }\n else {\n var size = {\n width: this.width,\n height: this.height\n };\n proxy = this._engine.createRenderTargetTexture(size, options);\n }\n proxy._swapAndDie(this);\n this.isReady = true;\n return;\n case InternalTexture.DATASOURCE_DEPTHTEXTURE:\n var depthTextureOptions = {\n bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,\n comparisonFunction: this._comparisonFunction,\n generateStencil: this._generateStencilBuffer,\n isCube: this.isCube\n };\n proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);\n proxy._swapAndDie(this);\n this.isReady = true;\n return;\n case InternalTexture.DATASOURCE_CUBE:\n proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {\n _this.isReady = true;\n }, null, this.format, this._extension);\n proxy._swapAndDie(this);\n return;\n case InternalTexture.DATASOURCE_CUBERAW:\n proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);\n proxy._swapAndDie(this);\n this.isReady = true;\n return;\n case InternalTexture.DATASOURCE_CUBERAW_RGBD:\n proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);\n BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {\n _this.isReady = true;\n });\n proxy._swapAndDie(this);\n return;\n case InternalTexture.DATASOURCE_CUBEPREFILTERED:\n proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {\n if (proxy) {\n proxy._swapAndDie(_this);\n }\n _this.isReady = true;\n }, null, this.format, this._extension);\n proxy._sphericalPolynomial = this._sphericalPolynomial;\n return;\n }\n };\n InternalTexture.prototype._swapAndDie = function (target) {\n target._webGLTexture = this._webGLTexture;\n if (this._framebuffer) {\n target._framebuffer = this._framebuffer;\n }\n if (this._depthStencilBuffer) {\n target._depthStencilBuffer = this._depthStencilBuffer;\n }\n if (this._lodTextureHigh) {\n if (target._lodTextureHigh) {\n target._lodTextureHigh.dispose();\n }\n target._lodTextureHigh = this._lodTextureHigh;\n }\n if (this._lodTextureMid) {\n if (target._lodTextureMid) {\n target._lodTextureMid.dispose();\n }\n target._lodTextureMid = this._lodTextureMid;\n }\n if (this._lodTextureLow) {\n if (target._lodTextureLow) {\n target._lodTextureLow.dispose();\n }\n target._lodTextureLow = this._lodTextureLow;\n }\n var cache = this._engine.getLoadedTexturesCache();\n var index = cache.indexOf(this);\n if (index !== -1) {\n cache.splice(index, 1);\n }\n };\n /**\n * Dispose the current allocated resources\n */\n InternalTexture.prototype.dispose = function () {\n if (!this._webGLTexture) {\n return;\n }\n this._references--;\n if (this._references === 0) {\n this._engine._releaseTexture(this);\n this._webGLTexture = null;\n this.previous = null;\n this.next = null;\n }\n };\n /**\n * The source of the texture data is unknown\n */\n InternalTexture.DATASOURCE_UNKNOWN = 0;\n /**\n * Texture data comes from an URL\n */\n InternalTexture.DATASOURCE_URL = 1;\n /**\n * Texture data is only used for temporary storage\n */\n InternalTexture.DATASOURCE_TEMP = 2;\n /**\n * Texture data comes from raw data (ArrayBuffer)\n */\n InternalTexture.DATASOURCE_RAW = 3;\n /**\n * Texture content is dynamic (video or dynamic texture)\n */\n InternalTexture.DATASOURCE_DYNAMIC = 4;\n /**\n * Texture content is generated by rendering to it\n */\n InternalTexture.DATASOURCE_RENDERTARGET = 5;\n /**\n * Texture content is part of a multi render target process\n */\n InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;\n /**\n * Texture data comes from a cube data file\n */\n InternalTexture.DATASOURCE_CUBE = 7;\n /**\n * Texture data comes from a raw cube data\n */\n InternalTexture.DATASOURCE_CUBERAW = 8;\n /**\n * Texture data come from a prefiltered cube data file\n */\n InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;\n /**\n * Texture content is raw 3D data\n */\n InternalTexture.DATASOURCE_RAW3D = 10;\n /**\n * Texture content is a depth texture\n */\n InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;\n /**\n * Texture data comes from a raw cube data encoded with RGBD\n */\n InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;\n return InternalTexture;\n }());\n BABYLON.InternalTexture = InternalTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.internalTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var BaseTexture = /** @class */ (function () {\n function BaseTexture(scene) {\n this._hasAlpha = false;\n this.getAlphaFromRGB = false;\n this.level = 1;\n this.coordinatesIndex = 0;\n this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;\n this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;\n this.isCube = false;\n this.is3D = false;\n this.gammaSpace = true;\n this.invertZ = false;\n this.lodLevelInAlpha = false;\n this.isRenderTarget = false;\n this.animations = new Array();\n /**\n * An event triggered when the texture is disposed.\n */\n this.onDisposeObservable = new BABYLON.Observable();\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;\n this._cachedSize = BABYLON.Size.Zero();\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n if (this._scene) {\n this._scene.textures.push(this);\n }\n this._uid = null;\n }\n Object.defineProperty(BaseTexture.prototype, \"hasAlpha\", {\n get: function () {\n return this._hasAlpha;\n },\n set: function (value) {\n if (this._hasAlpha === value) {\n return;\n }\n this._hasAlpha = value;\n if (this._scene) {\n this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"coordinatesMode\", {\n get: function () {\n return this._coordinatesMode;\n },\n /**\n * How a texture is mapped.\n *\n * | Value | Type | Description |\n * | ----- | ----------------------------------- | ----------- |\n * | 0 | EXPLICIT_MODE | |\n * | 1 | SPHERICAL_MODE | |\n * | 2 | PLANAR_MODE | |\n * | 3 | CUBIC_MODE | |\n * | 4 | PROJECTION_MODE | |\n * | 5 | SKYBOX_MODE | |\n * | 6 | INVCUBIC_MODE | |\n * | 7 | EQUIRECTANGULAR_MODE | |\n * | 8 | FIXED_EQUIRECTANGULAR_MODE | |\n * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |\n */\n set: function (value) {\n if (this._coordinatesMode === value) {\n return;\n }\n this._coordinatesMode = value;\n if (this._scene) {\n this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"isRGBD\", {\n /**\n * Gets whether or not the texture contains RGBD data.\n */\n get: function () {\n return this._texture != null && this._texture._isRGBD;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"lodGenerationOffset\", {\n get: function () {\n if (this._texture)\n return this._texture._lodGenerationOffset;\n return 0.0;\n },\n set: function (value) {\n if (this._texture)\n this._texture._lodGenerationOffset = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"lodGenerationScale\", {\n get: function () {\n if (this._texture)\n return this._texture._lodGenerationScale;\n return 0.0;\n },\n set: function (value) {\n if (this._texture)\n this._texture._lodGenerationScale = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"uid\", {\n get: function () {\n if (!this._uid) {\n this._uid = BABYLON.Tools.RandomId();\n }\n return this._uid;\n },\n enumerable: true,\n configurable: true\n });\n BaseTexture.prototype.toString = function () {\n return this.name;\n };\n BaseTexture.prototype.getClassName = function () {\n return \"BaseTexture\";\n };\n Object.defineProperty(BaseTexture.prototype, \"onDispose\", {\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"isBlocking\", {\n get: function () {\n return true;\n },\n enumerable: true,\n configurable: true\n });\n BaseTexture.prototype.getScene = function () {\n return this._scene;\n };\n BaseTexture.prototype.getTextureMatrix = function () {\n return BABYLON.Matrix.IdentityReadOnly;\n };\n BaseTexture.prototype.getReflectionTextureMatrix = function () {\n return BABYLON.Matrix.IdentityReadOnly;\n };\n BaseTexture.prototype.getInternalTexture = function () {\n return this._texture;\n };\n BaseTexture.prototype.isReadyOrNotBlocking = function () {\n return !this.isBlocking || this.isReady();\n };\n BaseTexture.prototype.isReady = function () {\n if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {\n this.delayLoad();\n return false;\n }\n if (this._texture) {\n return this._texture.isReady;\n }\n return false;\n };\n BaseTexture.prototype.getSize = function () {\n if (this._texture) {\n if (this._texture.width) {\n this._cachedSize.width = this._texture.width;\n this._cachedSize.height = this._texture.height;\n return this._cachedSize;\n }\n if (this._texture._size) {\n this._cachedSize.width = this._texture._size;\n this._cachedSize.height = this._texture._size;\n return this._cachedSize;\n }\n }\n return this._cachedSize;\n };\n BaseTexture.prototype.getBaseSize = function () {\n if (!this.isReady() || !this._texture)\n return BABYLON.Size.Zero();\n if (this._texture._size) {\n return new BABYLON.Size(this._texture._size, this._texture._size);\n }\n return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);\n };\n BaseTexture.prototype.scale = function (ratio) {\n };\n Object.defineProperty(BaseTexture.prototype, \"canRescale\", {\n get: function () {\n return false;\n },\n enumerable: true,\n configurable: true\n });\n BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {\n if (!this._scene) {\n return null;\n }\n var texturesCache = this._scene.getEngine().getLoadedTexturesCache();\n for (var index = 0; index < texturesCache.length; index++) {\n var texturesCacheEntry = texturesCache[index];\n if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {\n if (!sampling || sampling === texturesCacheEntry.samplingMode) {\n texturesCacheEntry.incrementReferences();\n return texturesCacheEntry;\n }\n }\n }\n return null;\n };\n BaseTexture.prototype._rebuild = function () {\n };\n BaseTexture.prototype.delayLoad = function () {\n };\n BaseTexture.prototype.clone = function () {\n return null;\n };\n Object.defineProperty(BaseTexture.prototype, \"textureType\", {\n get: function () {\n if (!this._texture) {\n return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"textureFormat\", {\n get: function () {\n if (!this._texture) {\n return BABYLON.Engine.TEXTUREFORMAT_RGBA;\n }\n return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.\n * This will returns an RGBA array buffer containing either in values (0-255) or\n * float values (0-1) depending of the underlying buffer type.\n * @param faceIndex The face of the texture to read (in case of cube texture)\n * @param level The LOD level of the texture to read (in case of Mip Maps)\n * @returns The Array buffer containing the pixels data.\n */\n BaseTexture.prototype.readPixels = function (faceIndex, level) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (level === void 0) { level = 0; }\n if (!this._texture) {\n return null;\n }\n var size = this.getSize();\n var width = size.width;\n var height = size.height;\n var scene = this.getScene();\n if (!scene) {\n return null;\n }\n var engine = scene.getEngine();\n if (level != 0) {\n width = width / Math.pow(2, level);\n height = height / Math.pow(2, level);\n width = Math.round(width);\n height = Math.round(height);\n }\n if (this._texture.isCube) {\n return engine._readTexturePixels(this._texture, width, height, faceIndex, level);\n }\n return engine._readTexturePixels(this._texture, width, height, -1, level);\n };\n BaseTexture.prototype.releaseInternalTexture = function () {\n if (this._texture) {\n this._texture.dispose();\n this._texture = null;\n }\n };\n Object.defineProperty(BaseTexture.prototype, \"sphericalPolynomial\", {\n get: function () {\n if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {\n return null;\n }\n if (!this._texture._sphericalPolynomial) {\n this._texture._sphericalPolynomial =\n BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);\n }\n return this._texture._sphericalPolynomial;\n },\n set: function (value) {\n if (this._texture) {\n this._texture._sphericalPolynomial = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"_lodTextureHigh\", {\n get: function () {\n if (this._texture) {\n return this._texture._lodTextureHigh;\n }\n return null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"_lodTextureMid\", {\n get: function () {\n if (this._texture) {\n return this._texture._lodTextureMid;\n }\n return null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseTexture.prototype, \"_lodTextureLow\", {\n get: function () {\n if (this._texture) {\n return this._texture._lodTextureLow;\n }\n return null;\n },\n enumerable: true,\n configurable: true\n });\n BaseTexture.prototype.dispose = function () {\n if (!this._scene) {\n return;\n }\n // Animations\n this._scene.stopAnimation(this);\n // Remove from scene\n this._scene._removePendingData(this);\n var index = this._scene.textures.indexOf(this);\n if (index >= 0) {\n this._scene.textures.splice(index, 1);\n }\n if (this._texture === undefined) {\n return;\n }\n // Release\n this.releaseInternalTexture();\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n };\n BaseTexture.prototype.serialize = function () {\n if (!this.name) {\n return null;\n }\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n // Animations\n BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);\n return serializationObject;\n };\n BaseTexture.WhenAllReady = function (textures, callback) {\n var numRemaining = textures.length;\n if (numRemaining === 0) {\n callback();\n return;\n }\n var _loop_1 = function () {\n texture = textures[i];\n if (texture.isReady()) {\n if (--numRemaining === 0) {\n callback();\n }\n }\n else {\n onLoadObservable = texture.onLoadObservable;\n var onLoadCallback_1 = function () {\n onLoadObservable.removeCallback(onLoadCallback_1);\n if (--numRemaining === 0) {\n callback();\n }\n };\n onLoadObservable.add(onLoadCallback_1);\n }\n };\n var texture, onLoadObservable;\n for (var i = 0; i < textures.length; i++) {\n _loop_1();\n }\n };\n BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"name\", void 0);\n __decorate([\n BABYLON.serialize(\"hasAlpha\")\n ], BaseTexture.prototype, \"_hasAlpha\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"getAlphaFromRGB\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"level\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"coordinatesIndex\", void 0);\n __decorate([\n BABYLON.serialize(\"coordinatesMode\")\n ], BaseTexture.prototype, \"_coordinatesMode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"wrapU\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"wrapV\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"wrapR\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"anisotropicFilteringLevel\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"isCube\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"is3D\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"gammaSpace\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"invertZ\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"lodLevelInAlpha\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"lodGenerationOffset\", null);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"lodGenerationScale\", null);\n __decorate([\n BABYLON.serialize()\n ], BaseTexture.prototype, \"isRenderTarget\", void 0);\n return BaseTexture;\n }());\n BABYLON.BaseTexture = BaseTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.baseTexture.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var Texture = /** @class */ (function (_super) {\n __extends(Texture, _super);\n function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {\n if (noMipmap === void 0) { noMipmap = false; }\n if (invertY === void 0) { invertY = true; }\n if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (buffer === void 0) { buffer = null; }\n if (deleteBuffer === void 0) { deleteBuffer = false; }\n var _this = _super.call(this, scene) || this;\n _this.uOffset = 0;\n _this.vOffset = 0;\n _this.uScale = 1.0;\n _this.vScale = 1.0;\n _this.uAng = 0;\n _this.vAng = 0;\n _this.wAng = 0;\n /**\n * Defines the center of rotation (U)\n */\n _this.uRotationCenter = 0.5;\n /**\n * Defines the center of rotation (V)\n */\n _this.vRotationCenter = 0.5;\n /**\n * Defines the center of rotation (W)\n */\n _this.wRotationCenter = 0.5;\n _this._isBlocking = true;\n _this.name = url || \"\";\n _this.url = url;\n _this._noMipmap = noMipmap;\n _this._invertY = invertY;\n _this._samplingMode = samplingMode;\n _this._buffer = buffer;\n _this._deleteBuffer = deleteBuffer;\n if (format) {\n _this._format = format;\n }\n scene = _this.getScene();\n if (!scene) {\n return _this;\n }\n scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);\n var load = function () {\n if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {\n _this.onLoadObservable.notifyObservers(_this);\n }\n if (onLoad) {\n onLoad();\n }\n if (!_this.isBlocking && scene) {\n scene.resetCachedMaterial();\n }\n };\n if (!_this.url) {\n _this._delayedOnLoad = load;\n _this._delayedOnError = onError;\n return _this;\n }\n _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);\n if (!_this._texture) {\n if (!scene.useDelayedTextureLoading) {\n _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);\n if (deleteBuffer) {\n delete _this._buffer;\n }\n }\n else {\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n _this._delayedOnLoad = load;\n _this._delayedOnError = onError;\n }\n }\n else {\n if (_this._texture.isReady) {\n BABYLON.Tools.SetImmediate(function () { return load(); });\n }\n else {\n _this._texture.onLoadedObservable.add(load);\n }\n }\n return _this;\n }\n Object.defineProperty(Texture.prototype, \"noMipmap\", {\n get: function () {\n return this._noMipmap;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Texture.prototype, \"isBlocking\", {\n get: function () {\n return this._isBlocking;\n },\n set: function (value) {\n this._isBlocking = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Texture.prototype, \"samplingMode\", {\n get: function () {\n return this._samplingMode;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Update the url (and optional buffer) of this texture if url was null during construction.\n * @param url the url of the texture\n * @param buffer the buffer of the texture (defaults to null)\n */\n Texture.prototype.updateURL = function (url, buffer) {\n if (buffer === void 0) { buffer = null; }\n if (this.url) {\n throw new Error(\"URL is already set\");\n }\n this.url = url;\n this._buffer = buffer;\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n this.delayLoad();\n };\n Texture.prototype.delayLoad = function () {\n if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {\n return;\n }\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;\n this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);\n if (!this._texture) {\n this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);\n if (this._deleteBuffer) {\n delete this._buffer;\n }\n }\n else {\n if (this._delayedOnLoad) {\n if (this._texture.isReady) {\n BABYLON.Tools.SetImmediate(this._delayedOnLoad);\n }\n else {\n this._texture.onLoadedObservable.add(this._delayedOnLoad);\n }\n }\n }\n this._delayedOnLoad = null;\n this._delayedOnError = null;\n };\n Texture.prototype.updateSamplingMode = function (samplingMode) {\n if (!this._texture) {\n return;\n }\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this._samplingMode = samplingMode;\n scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);\n };\n Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {\n x *= this.uScale;\n y *= this.vScale;\n x -= this.uRotationCenter * this.uScale;\n y -= this.vRotationCenter * this.vScale;\n z -= this.wRotationCenter;\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);\n t.x += this.uRotationCenter * this.uScale + this.uOffset;\n t.y += this.vRotationCenter * this.vScale + this.vOffset;\n t.z += this.wRotationCenter;\n };\n Texture.prototype.getTextureMatrix = function () {\n var _this = this;\n if (this.uOffset === this._cachedUOffset &&\n this.vOffset === this._cachedVOffset &&\n this.uScale === this._cachedUScale &&\n this.vScale === this._cachedVScale &&\n this.uAng === this._cachedUAng &&\n this.vAng === this._cachedVAng &&\n this.wAng === this._cachedWAng) {\n return this._cachedTextureMatrix;\n }\n this._cachedUOffset = this.uOffset;\n this._cachedVOffset = this.vOffset;\n this._cachedUScale = this.uScale;\n this._cachedVScale = this.vScale;\n this._cachedUAng = this.uAng;\n this._cachedVAng = this.vAng;\n this._cachedWAng = this.wAng;\n if (!this._cachedTextureMatrix) {\n this._cachedTextureMatrix = BABYLON.Matrix.Zero();\n this._rowGenerationMatrix = new BABYLON.Matrix();\n this._t0 = BABYLON.Vector3.Zero();\n this._t1 = BABYLON.Vector3.Zero();\n this._t2 = BABYLON.Vector3.Zero();\n }\n BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);\n this._prepareRowForTextureGeneration(0, 0, 0, this._t0);\n this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);\n this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);\n this._t1.subtractInPlace(this._t0);\n this._t2.subtractInPlace(this._t0);\n BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);\n this._cachedTextureMatrix.m[0] = this._t1.x;\n this._cachedTextureMatrix.m[1] = this._t1.y;\n this._cachedTextureMatrix.m[2] = this._t1.z;\n this._cachedTextureMatrix.m[4] = this._t2.x;\n this._cachedTextureMatrix.m[5] = this._t2.y;\n this._cachedTextureMatrix.m[6] = this._t2.z;\n this._cachedTextureMatrix.m[8] = this._t0.x;\n this._cachedTextureMatrix.m[9] = this._t0.y;\n this._cachedTextureMatrix.m[10] = this._t0.z;\n var scene = this.getScene();\n if (!scene) {\n return this._cachedTextureMatrix;\n }\n scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {\n return mat.hasTexture(_this);\n });\n return this._cachedTextureMatrix;\n };\n Texture.prototype.getReflectionTextureMatrix = function () {\n var _this = this;\n var scene = this.getScene();\n if (!scene) {\n return this._cachedTextureMatrix;\n }\n if (this.uOffset === this._cachedUOffset &&\n this.vOffset === this._cachedVOffset &&\n this.uScale === this._cachedUScale &&\n this.vScale === this._cachedVScale &&\n this.coordinatesMode === this._cachedCoordinatesMode) {\n if (this.coordinatesMode === Texture.PROJECTION_MODE) {\n if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {\n return this._cachedTextureMatrix;\n }\n }\n else {\n return this._cachedTextureMatrix;\n }\n }\n if (!this._cachedTextureMatrix) {\n this._cachedTextureMatrix = BABYLON.Matrix.Zero();\n }\n if (!this._projectionModeMatrix) {\n this._projectionModeMatrix = BABYLON.Matrix.Zero();\n }\n this._cachedUOffset = this.uOffset;\n this._cachedVOffset = this.vOffset;\n this._cachedUScale = this.uScale;\n this._cachedVScale = this.vScale;\n this._cachedCoordinatesMode = this.coordinatesMode;\n switch (this.coordinatesMode) {\n case Texture.PLANAR_MODE:\n BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);\n this._cachedTextureMatrix[0] = this.uScale;\n this._cachedTextureMatrix[5] = this.vScale;\n this._cachedTextureMatrix[12] = this.uOffset;\n this._cachedTextureMatrix[13] = this.vOffset;\n break;\n case Texture.PROJECTION_MODE:\n BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);\n this._projectionModeMatrix.m[0] = 0.5;\n this._projectionModeMatrix.m[5] = -0.5;\n this._projectionModeMatrix.m[10] = 0.0;\n this._projectionModeMatrix.m[12] = 0.5;\n this._projectionModeMatrix.m[13] = 0.5;\n this._projectionModeMatrix.m[14] = 1.0;\n this._projectionModeMatrix.m[15] = 1.0;\n var projectionMatrix = scene.getProjectionMatrix();\n this._cachedProjectionMatrixId = projectionMatrix.updateFlag;\n projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);\n break;\n default:\n BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);\n break;\n }\n scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {\n return (mat.getActiveTextures().indexOf(_this) !== -1);\n });\n return this._cachedTextureMatrix;\n };\n Texture.prototype.clone = function () {\n var _this = this;\n return BABYLON.SerializationHelper.Clone(function () {\n return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);\n }, this);\n };\n Object.defineProperty(Texture.prototype, \"onLoadObservable\", {\n get: function () {\n if (!this._onLoadObservable) {\n this._onLoadObservable = new BABYLON.Observable();\n }\n return this._onLoadObservable;\n },\n enumerable: true,\n configurable: true\n });\n Texture.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n if (typeof this._buffer === \"string\" && this._buffer.substr(0, 5) === \"data:\") {\n serializationObject.base64String = this._buffer;\n serializationObject.name = serializationObject.name.replace(\"data:\", \"\");\n }\n serializationObject.invertY = this._invertY;\n serializationObject.samplingMode = this.samplingMode;\n return serializationObject;\n };\n Texture.prototype.getClassName = function () {\n return \"Texture\";\n };\n Texture.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n if (this._onLoadObservable) {\n this._onLoadObservable.clear();\n this._onLoadObservable = null;\n }\n this._delayedOnLoad = null;\n this._delayedOnError = null;\n };\n // Statics\n Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {\n if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }\n return new Texture(\"data:\" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);\n };\n Texture.Parse = function (parsedTexture, scene, rootUrl) {\n if (parsedTexture.customType) {\n var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);\n // Update Sampling Mode\n var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);\n if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {\n if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {\n parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);\n }\n }\n return parsedCustomTexture;\n }\n if (parsedTexture.isCube) {\n return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);\n }\n if (!parsedTexture.name && !parsedTexture.isRenderTarget) {\n return null;\n }\n var texture = BABYLON.SerializationHelper.Parse(function () {\n var generateMipMaps = true;\n if (parsedTexture.noMipmap) {\n generateMipMaps = false;\n }\n if (parsedTexture.mirrorPlane) {\n var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);\n mirrorTexture._waitingRenderList = parsedTexture.renderList;\n mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);\n return mirrorTexture;\n }\n else if (parsedTexture.isRenderTarget) {\n var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);\n renderTargetTexture._waitingRenderList = parsedTexture.renderList;\n return renderTargetTexture;\n }\n else {\n var texture;\n if (parsedTexture.base64String) {\n texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);\n }\n else {\n var url = rootUrl + parsedTexture.name;\n if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {\n url = parsedTexture.url;\n }\n texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);\n }\n return texture;\n }\n }, parsedTexture, scene);\n // Update Sampling Mode\n if (parsedTexture.samplingMode) {\n var sampling = parsedTexture.samplingMode;\n if (texture._samplingMode !== sampling) {\n texture.updateSamplingMode(sampling);\n }\n }\n // Animations\n if (parsedTexture.animations) {\n for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {\n var parsedAnimation = parsedTexture.animations[animationIndex];\n texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n }\n return texture;\n };\n Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {\n if (deleteBuffer === void 0) { deleteBuffer = false; }\n if (noMipmap === void 0) { noMipmap = false; }\n if (invertY === void 0) { invertY = true; }\n if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }\n if (name.substr(0, 5) !== \"data:\") {\n name = \"data:\" + name;\n }\n return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);\n };\n // Constants\n Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;\n Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear\n Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;\n Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest\n Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;\n Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear\n Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;\n Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;\n Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;\n Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;\n Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;\n Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;\n Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;\n Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;\n Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;\n Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;\n Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;\n Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;\n Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;\n Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;\n Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;\n Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;\n Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;\n Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;\n Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;\n Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;\n Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;\n Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;\n /**\n * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file\n */\n Texture.UseSerializedUrlIfAny = false;\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"url\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"uOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"vOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"uScale\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"vScale\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"uAng\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"vAng\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"wAng\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"uRotationCenter\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"vRotationCenter\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"wRotationCenter\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Texture.prototype, \"isBlocking\", null);\n return Texture;\n }(BABYLON.BaseTexture));\n BABYLON.Texture = Texture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.texture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * @hidden\n **/\n var _InstancesBatch = /** @class */ (function () {\n function _InstancesBatch() {\n this.mustReturn = false;\n this.visibleInstances = new Array();\n this.renderSelf = new Array();\n }\n return _InstancesBatch;\n }());\n BABYLON._InstancesBatch = _InstancesBatch;\n var Mesh = /** @class */ (function (_super) {\n __extends(Mesh, _super);\n /**\n * @constructor\n * @param {string} name The value used by scene.getMeshByName() to do a lookup.\n * @param {Scene} scene The scene to add this mesh to.\n * @param {Node} parent The parent of this mesh, if it has one\n * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.\n * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.\n * When false, achieved by calling a clone(), also passing False.\n * This will make creation of children, recursive.\n * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.\n */\n function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {\n if (scene === void 0) { scene = null; }\n if (parent === void 0) { parent = null; }\n if (source === void 0) { source = null; }\n if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }\n var _this = _super.call(this, name, scene) || this;\n // Members\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;\n _this.instances = new Array();\n _this._LODLevels = new Array();\n _this._visibleInstances = {};\n _this._renderIdForInstances = new Array();\n _this._batchCache = new _InstancesBatch();\n _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances\n // Use by builder only to know what orientation were the mesh build in.\n _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;\n _this.overrideMaterialSideOrientation = null;\n _this._areNormalsFrozen = false; // Will be used by ribbons mainly\n // Will be used to save a source mesh reference, If any\n _this._source = null;\n scene = _this.getScene();\n if (source) {\n // Geometry\n if (source._geometry) {\n source._geometry.applyToMesh(_this);\n }\n // Deep copy\n BABYLON.Tools.DeepCopy(source, _this, [\"name\", \"material\", \"skeleton\", \"instances\", \"parent\", \"uniqueId\",\n \"source\", \"metadata\", \"hasLODLevels\", \"geometry\", \"isBlocked\", \"areNormalsFrozen\",\n \"onBeforeDrawObservable\", \"onBeforeRenderObservable\", \"onAfterRenderObservable\", \"onBeforeDraw\"\n ], [\"_poseMatrix\"]);\n // Source mesh\n _this._source = source;\n // Metadata\n if (source.metadata && source.metadata.clone) {\n _this.metadata = source.metadata.clone();\n }\n else {\n _this.metadata = source.metadata;\n }\n // Tags\n if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {\n BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));\n }\n // Parent\n _this.parent = source.parent;\n // Pivot\n _this.setPivotMatrix(source.getPivotMatrix());\n _this.id = name + \".\" + source.id;\n // Material\n _this.material = source.material;\n var index;\n if (!doNotCloneChildren) {\n // Children\n var directDescendants = source.getDescendants(true);\n for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {\n var child = directDescendants[index_1];\n if (child.clone) {\n child.clone(name + \".\" + child.name, _this);\n }\n }\n }\n // Physics clone \n var physicsEngine = _this.getScene().getPhysicsEngine();\n if (clonePhysicsImpostor && physicsEngine) {\n var impostor = physicsEngine.getImpostorForPhysicsObject(source);\n if (impostor) {\n _this.physicsImpostor = impostor.clone(_this);\n }\n }\n // Particles\n for (index = 0; index < scene.particleSystems.length; index++) {\n var system = scene.particleSystems[index];\n if (system.emitter === source) {\n system.clone(system.name, _this);\n }\n }\n _this.refreshBoundingInfo();\n _this.computeWorldMatrix(true);\n }\n // Parent\n if (parent !== null) {\n _this.parent = parent;\n }\n return _this;\n }\n Object.defineProperty(Mesh, \"FRONTSIDE\", {\n /**\n * Mesh side orientation : usually the external or front surface\n */\n get: function () {\n return Mesh._FRONTSIDE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"BACKSIDE\", {\n /**\n * Mesh side orientation : usually the internal or back surface\n */\n get: function () {\n return Mesh._BACKSIDE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"DOUBLESIDE\", {\n /**\n * Mesh side orientation : both internal and external or front and back surfaces\n */\n get: function () {\n return Mesh._DOUBLESIDE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"DEFAULTSIDE\", {\n /**\n * Mesh side orientation : by default, `FRONTSIDE`\n */\n get: function () {\n return Mesh._DEFAULTSIDE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"NO_CAP\", {\n /**\n * Mesh cap setting : no cap\n */\n get: function () {\n return Mesh._NO_CAP;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"CAP_START\", {\n /**\n * Mesh cap setting : one cap at the beginning of the mesh\n */\n get: function () {\n return Mesh._CAP_START;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"CAP_END\", {\n /**\n * Mesh cap setting : one cap at the end of the mesh\n */\n get: function () {\n return Mesh._CAP_END;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh, \"CAP_ALL\", {\n /**\n * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh\n */\n get: function () {\n return Mesh._CAP_ALL;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh.prototype, \"onBeforeRenderObservable\", {\n /**\n * An event triggered before rendering the mesh\n */\n get: function () {\n if (!this._onBeforeRenderObservable) {\n this._onBeforeRenderObservable = new BABYLON.Observable();\n }\n return this._onBeforeRenderObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh.prototype, \"onAfterRenderObservable\", {\n /**\n * An event triggered after rendering the mesh\n */\n get: function () {\n if (!this._onAfterRenderObservable) {\n this._onAfterRenderObservable = new BABYLON.Observable();\n }\n return this._onAfterRenderObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh.prototype, \"onBeforeDrawObservable\", {\n /**\n * An event triggered before drawing the mesh\n */\n get: function () {\n if (!this._onBeforeDrawObservable) {\n this._onBeforeDrawObservable = new BABYLON.Observable();\n }\n return this._onBeforeDrawObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh.prototype, \"onBeforeDraw\", {\n set: function (callback) {\n if (this._onBeforeDrawObserver) {\n this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);\n }\n this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh.prototype, \"morphTargetManager\", {\n get: function () {\n return this._morphTargetManager;\n },\n set: function (value) {\n if (this._morphTargetManager === value) {\n return;\n }\n this._morphTargetManager = value;\n this._syncGeometryWithMorphTargetManager();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh.prototype, \"source\", {\n get: function () {\n return this._source;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Mesh.prototype, \"isUnIndexed\", {\n get: function () {\n return this._unIndexed;\n },\n set: function (value) {\n if (this._unIndexed !== value) {\n this._unIndexed = value;\n this._markSubMeshesAsAttributesDirty();\n }\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n /**\n * Returns the string \"Mesh\".\n */\n Mesh.prototype.getClassName = function () {\n return \"Mesh\";\n };\n /**\n * Returns a string.\n * @param {boolean} fullDetails - support for multiple levels of logging within scene loading\n */\n Mesh.prototype.toString = function (fullDetails) {\n var ret = _super.prototype.toString.call(this, fullDetails);\n ret += \", n vertices: \" + this.getTotalVertices();\n ret += \", parent: \" + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : \"NONE\"));\n if (this.animations) {\n for (var i = 0; i < this.animations.length; i++) {\n ret += \", animation[0]: \" + this.animations[i].toString(fullDetails);\n }\n }\n if (fullDetails) {\n if (this._geometry) {\n var ib = this.getIndices();\n var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (vb && ib) {\n ret += \", flat shading: \" + (vb.length / 3 === ib.length ? \"YES\" : \"NO\");\n }\n }\n else {\n ret += \", flat shading: UNKNOWN\";\n }\n }\n return ret;\n };\n Mesh.prototype._unBindEffect = function () {\n _super.prototype._unBindEffect.call(this);\n for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {\n var instance = _a[_i];\n instance._unBindEffect();\n }\n };\n Object.defineProperty(Mesh.prototype, \"hasLODLevels\", {\n /**\n * True if the mesh has some Levels Of Details (LOD).\n * Returns a boolean.\n */\n get: function () {\n return this._LODLevels.length > 0;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh\n * @returns an array of {BABYLON.MeshLODLevel}\n */\n Mesh.prototype.getLODLevels = function () {\n return this._LODLevels;\n };\n Mesh.prototype._sortLODLevels = function () {\n this._LODLevels.sort(function (a, b) {\n if (a.distance < b.distance) {\n return 1;\n }\n if (a.distance > b.distance) {\n return -1;\n }\n return 0;\n });\n };\n /**\n * Add a mesh as LOD level triggered at the given distance.\n * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD\n * @param distance The distance from the center of the object to show this level\n * @param mesh The mesh to be added as LOD level (can be null)\n * @return This mesh (for chaining)\n */\n Mesh.prototype.addLODLevel = function (distance, mesh) {\n if (mesh && mesh._masterMesh) {\n BABYLON.Tools.Warn(\"You cannot use a mesh as LOD level twice\");\n return this;\n }\n var level = new BABYLON.MeshLODLevel(distance, mesh);\n this._LODLevels.push(level);\n if (mesh) {\n mesh._masterMesh = this;\n }\n this._sortLODLevels();\n return this;\n };\n /**\n * Returns the LOD level mesh at the passed distance or null if not found.\n * It is related to the method `addLODLevel(distance, mesh)`.\n * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD\n * Returns an object Mesh or `null`.\n */\n Mesh.prototype.getLODLevelAtDistance = function (distance) {\n for (var index = 0; index < this._LODLevels.length; index++) {\n var level = this._LODLevels[index];\n if (level.distance === distance) {\n return level.mesh;\n }\n }\n return null;\n };\n /**\n * Remove a mesh from the LOD array\n * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD\n * @param {Mesh} mesh The mesh to be removed.\n * @return {Mesh} This mesh (for chaining)\n */\n Mesh.prototype.removeLODLevel = function (mesh) {\n for (var index = 0; index < this._LODLevels.length; index++) {\n if (this._LODLevels[index].mesh === mesh) {\n this._LODLevels.splice(index, 1);\n if (mesh) {\n mesh._masterMesh = null;\n }\n }\n }\n this._sortLODLevels();\n return this;\n };\n /**\n * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.\n * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod\n */\n Mesh.prototype.getLOD = function (camera, boundingSphere) {\n if (!this._LODLevels || this._LODLevels.length === 0) {\n return this;\n }\n var bSphere;\n if (boundingSphere) {\n bSphere = boundingSphere;\n }\n else {\n var boundingInfo = this.getBoundingInfo();\n bSphere = boundingInfo.boundingSphere;\n }\n var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();\n if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {\n if (this.onLODLevelSelection) {\n this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);\n }\n return this;\n }\n for (var index = 0; index < this._LODLevels.length; index++) {\n var level = this._LODLevels[index];\n if (level.distance < distanceToCamera) {\n if (level.mesh) {\n level.mesh._preActivate();\n level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);\n }\n if (this.onLODLevelSelection) {\n this.onLODLevelSelection(distanceToCamera, this, level.mesh);\n }\n return level.mesh;\n }\n }\n if (this.onLODLevelSelection) {\n this.onLODLevelSelection(distanceToCamera, this, this);\n }\n return this;\n };\n Object.defineProperty(Mesh.prototype, \"geometry\", {\n /**\n * Returns the mesh internal Geometry object.\n */\n get: function () {\n return this._geometry;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.\n */\n Mesh.prototype.getTotalVertices = function () {\n if (this._geometry === null || this._geometry === undefined) {\n return 0;\n }\n return this._geometry.getTotalVertices();\n };\n /**\n * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).\n * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.\n * You can force the copy with forceCopy === true\n * Returns null if the mesh has no geometry or no vertex buffer.\n * Possible `kind` values :\n * - BABYLON.VertexBuffer.PositionKind\n * - BABYLON.VertexBuffer.UVKind\n * - BABYLON.VertexBuffer.UV2Kind\n * - BABYLON.VertexBuffer.UV3Kind\n * - BABYLON.VertexBuffer.UV4Kind\n * - BABYLON.VertexBuffer.UV5Kind\n * - BABYLON.VertexBuffer.UV6Kind\n * - BABYLON.VertexBuffer.ColorKind\n * - BABYLON.VertexBuffer.MatricesIndicesKind\n * - BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * - BABYLON.VertexBuffer.MatricesWeightsKind\n * - BABYLON.VertexBuffer.MatricesWeightsExtraKind\n */\n Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {\n if (!this._geometry) {\n return null;\n }\n return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);\n };\n /**\n * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.\n * Returns `null` if the mesh has no geometry.\n * Possible `kind` values :\n * - BABYLON.VertexBuffer.PositionKind\n * - BABYLON.VertexBuffer.UVKind\n * - BABYLON.VertexBuffer.UV2Kind\n * - BABYLON.VertexBuffer.UV3Kind\n * - BABYLON.VertexBuffer.UV4Kind\n * - BABYLON.VertexBuffer.UV5Kind\n * - BABYLON.VertexBuffer.UV6Kind\n * - BABYLON.VertexBuffer.ColorKind\n * - BABYLON.VertexBuffer.MatricesIndicesKind\n * - BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * - BABYLON.VertexBuffer.MatricesWeightsKind\n * - BABYLON.VertexBuffer.MatricesWeightsExtraKind\n */\n Mesh.prototype.getVertexBuffer = function (kind) {\n if (!this._geometry) {\n return null;\n }\n return this._geometry.getVertexBuffer(kind);\n };\n Mesh.prototype.isVerticesDataPresent = function (kind) {\n if (!this._geometry) {\n if (this._delayInfo) {\n return this._delayInfo.indexOf(kind) !== -1;\n }\n return false;\n }\n return this._geometry.isVerticesDataPresent(kind);\n };\n /**\n * Returns a boolean defining if the vertex data for the requested `kind` is updatable.\n * Possible `kind` values :\n * - BABYLON.VertexBuffer.PositionKind\n * - BABYLON.VertexBuffer.UVKind\n * - BABYLON.VertexBuffer.UV2Kind\n * - BABYLON.VertexBuffer.UV3Kind\n * - BABYLON.VertexBuffer.UV4Kind\n * - BABYLON.VertexBuffer.UV5Kind\n * - BABYLON.VertexBuffer.UV6Kind\n * - BABYLON.VertexBuffer.ColorKind\n * - BABYLON.VertexBuffer.MatricesIndicesKind\n * - BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * - BABYLON.VertexBuffer.MatricesWeightsKind\n * - BABYLON.VertexBuffer.MatricesWeightsExtraKind\n */\n Mesh.prototype.isVertexBufferUpdatable = function (kind) {\n if (!this._geometry) {\n if (this._delayInfo) {\n return this._delayInfo.indexOf(kind) !== -1;\n }\n return false;\n }\n return this._geometry.isVertexBufferUpdatable(kind);\n };\n /**\n * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.\n * Possible `kind` values :\n * - BABYLON.VertexBuffer.PositionKind\n * - BABYLON.VertexBuffer.UVKind\n * - BABYLON.VertexBuffer.UV2Kind\n * - BABYLON.VertexBuffer.UV3Kind\n * - BABYLON.VertexBuffer.UV4Kind\n * - BABYLON.VertexBuffer.UV5Kind\n * - BABYLON.VertexBuffer.UV6Kind\n * - BABYLON.VertexBuffer.ColorKind\n * - BABYLON.VertexBuffer.MatricesIndicesKind\n * - BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * - BABYLON.VertexBuffer.MatricesWeightsKind\n * - BABYLON.VertexBuffer.MatricesWeightsExtraKind\n */\n Mesh.prototype.getVerticesDataKinds = function () {\n if (!this._geometry) {\n var result = new Array();\n if (this._delayInfo) {\n this._delayInfo.forEach(function (kind, index, array) {\n result.push(kind);\n });\n }\n return result;\n }\n return this._geometry.getVerticesDataKinds();\n };\n /**\n * Returns a positive integer : the total number of indices in this mesh geometry.\n * Returns zero if the mesh has no geometry.\n */\n Mesh.prototype.getTotalIndices = function () {\n if (!this._geometry) {\n return 0;\n }\n return this._geometry.getTotalIndices();\n };\n /**\n * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.\n * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.\n * Returns an empty array if the mesh has no geometry.\n */\n Mesh.prototype.getIndices = function (copyWhenShared) {\n if (!this._geometry) {\n return [];\n }\n return this._geometry.getIndices(copyWhenShared);\n };\n Object.defineProperty(Mesh.prototype, \"isBlocked\", {\n get: function () {\n return this._masterMesh !== null && this._masterMesh !== undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Determine if the current mesh is ready to be rendered\n * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)\n * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)\n * @returns true if all associated assets are ready (material, textures, shaders)\n */\n Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {\n if (completeCheck === void 0) { completeCheck = false; }\n if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }\n if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {\n return false;\n }\n if (!_super.prototype.isReady.call(this, completeCheck)) {\n return false;\n }\n if (!this.subMeshes || this.subMeshes.length === 0) {\n return true;\n }\n if (!completeCheck) {\n return true;\n }\n var engine = this.getEngine();\n var scene = this.getScene();\n var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;\n this.computeWorldMatrix();\n var mat = this.material || scene.defaultMaterial;\n if (mat) {\n if (mat.storeEffectOnSubMeshes) {\n for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n var effectiveMaterial = subMesh.getMaterial();\n if (effectiveMaterial) {\n if (effectiveMaterial.storeEffectOnSubMeshes) {\n if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n else {\n if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n }\n }\n else {\n if (!mat.isReady(this, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n // Shadows\n for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {\n var light = _c[_b];\n var generator = light.getShadowGenerator();\n if (generator) {\n for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {\n var subMesh = _e[_d];\n if (!generator.isReady(subMesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n }\n // LOD\n for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {\n var lod = _g[_f];\n if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {\n return false;\n }\n }\n return true;\n };\n Object.defineProperty(Mesh.prototype, \"areNormalsFrozen\", {\n /**\n * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.\n * This property is pertinent only for updatable parametric shapes.\n */\n get: function () {\n return this._areNormalsFrozen;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.\n * It has no effect at all on other shapes.\n * It prevents the mesh normals from being recomputed on next `positions` array update.\n * Returns the Mesh.\n */\n Mesh.prototype.freezeNormals = function () {\n this._areNormalsFrozen = true;\n return this;\n };\n /**\n * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.\n * It has no effect at all on other shapes.\n * It reactivates the mesh normals computation if it was previously frozen.\n * Returns the Mesh.\n */\n Mesh.prototype.unfreezeNormals = function () {\n this._areNormalsFrozen = false;\n return this;\n };\n Object.defineProperty(Mesh.prototype, \"overridenInstanceCount\", {\n /**\n * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs\n */\n set: function (count) {\n this._overridenInstanceCount = count;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n Mesh.prototype._preActivate = function () {\n var sceneRenderId = this.getScene().getRenderId();\n if (this._preActivateId === sceneRenderId) {\n return this;\n }\n this._preActivateId = sceneRenderId;\n this._visibleInstances = null;\n return this;\n };\n Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {\n if (this._visibleInstances) {\n this._visibleInstances.intermediateDefaultRenderId = renderId;\n }\n return this;\n };\n Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {\n if (!this._visibleInstances) {\n this._visibleInstances = {};\n this._visibleInstances.defaultRenderId = renderId;\n this._visibleInstances.selfDefaultRenderId = this._renderId;\n }\n if (!this._visibleInstances[renderId]) {\n this._visibleInstances[renderId] = new Array();\n }\n this._visibleInstances[renderId].push(instance);\n return this;\n };\n /**\n * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.\n * This means the mesh underlying bounding box and sphere are recomputed.\n * Returns the Mesh.\n */\n Mesh.prototype.refreshBoundingInfo = function () {\n return this._refreshBoundingInfo(false);\n };\n Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {\n if (this._boundingInfo && this._boundingInfo.isLocked) {\n return this;\n }\n var data = this._getPositionData(applySkeleton);\n if (data) {\n var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());\n this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);\n }\n if (this.subMeshes) {\n for (var index = 0; index < this.subMeshes.length; index++) {\n this.subMeshes[index].refreshBoundingInfo();\n }\n }\n this._updateBoundingInfo();\n return this;\n };\n Mesh.prototype._getPositionData = function (applySkeleton) {\n var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (data && applySkeleton && this.skeleton) {\n data = BABYLON.Tools.Slice(data);\n var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);\n var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (matricesWeightsData && matricesIndicesData) {\n var needExtras = this.numBoneInfluencers > 4;\n var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;\n var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;\n var skeletonMatrices = this.skeleton.getTransformMatrices(this);\n var tempVector = BABYLON.Tmp.Vector3[0];\n var finalMatrix = BABYLON.Tmp.Matrix[0];\n var tempMatrix = BABYLON.Tmp.Matrix[1];\n var matWeightIdx = 0;\n for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {\n finalMatrix.reset();\n var inf;\n var weight;\n for (inf = 0; inf < 4; inf++) {\n weight = matricesWeightsData[matWeightIdx + inf];\n if (weight > 0) {\n BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);\n finalMatrix.addToSelf(tempMatrix);\n }\n }\n if (needExtras) {\n for (inf = 0; inf < 4; inf++) {\n weight = matricesWeightsExtraData[matWeightIdx + inf];\n if (weight > 0) {\n BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);\n finalMatrix.addToSelf(tempMatrix);\n }\n }\n }\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);\n tempVector.toArray(data, index);\n }\n }\n }\n return data;\n };\n Mesh.prototype._createGlobalSubMesh = function (force) {\n var totalVertices = this.getTotalVertices();\n if (!totalVertices || !this.getIndices()) {\n return null;\n }\n // Check if we need to recreate the submeshes\n if (this.subMeshes && this.subMeshes.length > 0) {\n var ib = this.getIndices();\n if (!ib) {\n return null;\n }\n var totalIndices = ib.length;\n var needToRecreate = false;\n if (force) {\n needToRecreate = true;\n }\n else {\n for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {\n var submesh = _a[_i];\n if (submesh.indexStart + submesh.indexCount >= totalIndices) {\n needToRecreate = true;\n break;\n }\n if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {\n needToRecreate = true;\n break;\n }\n }\n }\n if (!needToRecreate) {\n return this.subMeshes[0];\n }\n }\n this.releaseSubMeshes();\n return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);\n };\n Mesh.prototype.subdivide = function (count) {\n if (count < 1) {\n return;\n }\n var totalIndices = this.getTotalIndices();\n var subdivisionSize = (totalIndices / count) | 0;\n var offset = 0;\n // Ensure that subdivisionSize is a multiple of 3\n while (subdivisionSize % 3 !== 0) {\n subdivisionSize++;\n }\n this.releaseSubMeshes();\n for (var index = 0; index < count; index++) {\n if (offset >= totalIndices) {\n break;\n }\n BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);\n offset += subdivisionSize;\n }\n this.synchronizeInstances();\n };\n Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {\n if (updatable === void 0) { updatable = false; }\n if (!this._geometry) {\n var vertexData = new BABYLON.VertexData();\n vertexData.set(data, kind);\n var scene = this.getScene();\n new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);\n }\n else {\n this._geometry.setVerticesData(kind, data, updatable, stride);\n }\n return this;\n };\n Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {\n if (updatable === void 0) { updatable = true; }\n var vb = this.getVertexBuffer(kind);\n if (!vb || vb.isUpdatable() === updatable) {\n return;\n }\n this.setVerticesData(kind, this.getVerticesData(kind), updatable);\n };\n /**\n * Sets the mesh VertexBuffer.\n * Returns the Mesh.\n */\n Mesh.prototype.setVerticesBuffer = function (buffer) {\n if (!this._geometry) {\n this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);\n }\n this._geometry.setVerticesBuffer(buffer);\n return this;\n };\n Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {\n if (!this._geometry) {\n return this;\n }\n if (!makeItUnique) {\n this._geometry.updateVerticesData(kind, data, updateExtends);\n }\n else {\n this.makeGeometryUnique();\n this.updateVerticesData(kind, data, updateExtends, false);\n }\n return this;\n };\n /**\n * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.\n * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions\n * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.\n * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.\n * Returns the Mesh.\n */\n Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {\n if (computeNormals === void 0) { computeNormals = true; }\n var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!positions) {\n return this;\n }\n positionFunction(positions);\n this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);\n if (computeNormals) {\n var indices = this.getIndices();\n var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n if (!normals) {\n return this;\n }\n BABYLON.VertexData.ComputeNormals(positions, indices, normals);\n this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);\n }\n return this;\n };\n /**\n * Creates a un-shared specific occurence of the geometry for the mesh.\n * Returns the Mesh.\n */\n Mesh.prototype.makeGeometryUnique = function () {\n if (!this._geometry) {\n return this;\n }\n var oldGeometry = this._geometry;\n var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());\n oldGeometry.releaseForMesh(this, true);\n geometry.applyToMesh(this);\n return this;\n };\n Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {\n if (totalVertices === void 0) { totalVertices = null; }\n if (updatable === void 0) { updatable = false; }\n if (!this._geometry) {\n var vertexData = new BABYLON.VertexData();\n vertexData.indices = indices;\n var scene = this.getScene();\n new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);\n }\n else {\n this._geometry.setIndices(indices, totalVertices, updatable);\n }\n return this;\n };\n /**\n * Update the current index buffer\n * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)\n * Returns the Mesh.\n */\n Mesh.prototype.updateIndices = function (indices, offset) {\n if (!this._geometry) {\n return this;\n }\n this._geometry.updateIndices(indices, offset);\n return this;\n };\n /**\n * Invert the geometry to move from a right handed system to a left handed one.\n * Returns the Mesh.\n */\n Mesh.prototype.toLeftHanded = function () {\n if (!this._geometry) {\n return this;\n }\n this._geometry.toLeftHanded();\n return this;\n };\n Mesh.prototype._bind = function (subMesh, effect, fillMode) {\n if (!this._geometry) {\n return this;\n }\n var engine = this.getScene().getEngine();\n // Wireframe\n var indexToBind;\n if (this._unIndexed) {\n indexToBind = null;\n }\n else {\n switch (fillMode) {\n case BABYLON.Material.PointFillMode:\n indexToBind = null;\n break;\n case BABYLON.Material.WireFrameFillMode:\n indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);\n break;\n default:\n case BABYLON.Material.TriangleFillMode:\n indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();\n break;\n }\n }\n // VBOs\n this._geometry._bind(effect, indexToBind);\n return this;\n };\n Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {\n if (alternate === void 0) { alternate = false; }\n if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {\n return this;\n }\n if (this._onBeforeDrawObservable) {\n this._onBeforeDrawObservable.notifyObservers(this);\n }\n var scene = this.getScene();\n var engine = scene.getEngine();\n if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {\n // or triangles as points\n engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);\n }\n else if (fillMode == BABYLON.Material.WireFrameFillMode) {\n // Triangles as wireframe\n engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);\n }\n else {\n engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);\n }\n if (scene._isAlternateRenderingEnabled && !alternate) {\n var effect = subMesh.effect || this._effectiveMaterial.getEffect();\n if (!effect || !scene.activeCamera) {\n return this;\n }\n scene._switchToAlternateCameraConfiguration(true);\n this._effectiveMaterial.bindView(effect);\n this._effectiveMaterial.bindViewProjection(effect);\n engine.setViewport(scene.activeCamera._alternateCamera.viewport);\n this._draw(subMesh, fillMode, instancesCount, true);\n engine.setViewport(scene.activeCamera.viewport);\n scene._switchToAlternateCameraConfiguration(false);\n this._effectiveMaterial.bindView(effect);\n this._effectiveMaterial.bindViewProjection(effect);\n }\n return this;\n };\n /**\n * Registers for this mesh a javascript function called just before the rendering process.\n * This function is passed the current mesh.\n * Return the Mesh.\n */\n Mesh.prototype.registerBeforeRender = function (func) {\n this.onBeforeRenderObservable.add(func);\n return this;\n };\n /**\n * Disposes a previously registered javascript function called before the rendering.\n * This function is passed the current mesh.\n * Returns the Mesh.\n */\n Mesh.prototype.unregisterBeforeRender = function (func) {\n this.onBeforeRenderObservable.removeCallback(func);\n return this;\n };\n /**\n * Registers for this mesh a javascript function called just after the rendering is complete.\n * This function is passed the current mesh.\n * Returns the Mesh.\n */\n Mesh.prototype.registerAfterRender = function (func) {\n this.onAfterRenderObservable.add(func);\n return this;\n };\n /**\n * Disposes a previously registered javascript function called after the rendering.\n * This function is passed the current mesh.\n * Return the Mesh.\n */\n Mesh.prototype.unregisterAfterRender = function (func) {\n this.onAfterRenderObservable.removeCallback(func);\n return this;\n };\n Mesh.prototype._getInstancesRenderList = function (subMeshId) {\n var scene = this.getScene();\n this._batchCache.mustReturn = false;\n this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;\n this._batchCache.visibleInstances[subMeshId] = null;\n if (this._visibleInstances) {\n var currentRenderId = scene.getRenderId();\n var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);\n this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];\n var selfRenderId = this._renderId;\n if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {\n this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];\n currentRenderId = Math.max(defaultRenderId, currentRenderId);\n selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);\n }\n var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];\n if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {\n if (this._renderIdForInstances[subMeshId] === currentRenderId) {\n this._batchCache.mustReturn = true;\n return this._batchCache;\n }\n if (currentRenderId !== selfRenderId) {\n this._batchCache.renderSelf[subMeshId] = false;\n }\n }\n this._renderIdForInstances[subMeshId] = currentRenderId;\n }\n return this._batchCache;\n };\n Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {\n var visibleInstances = batch.visibleInstances[subMesh._id];\n if (!visibleInstances) {\n return this;\n }\n var matricesCount = visibleInstances.length + 1;\n var bufferSize = matricesCount * 16 * 4;\n var currentInstancesBufferSize = this._instancesBufferSize;\n var instancesBuffer = this._instancesBuffer;\n while (this._instancesBufferSize < bufferSize) {\n this._instancesBufferSize *= 2;\n }\n if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {\n this._instancesData = new Float32Array(this._instancesBufferSize / 4);\n }\n var offset = 0;\n var instancesCount = 0;\n var world = this.getWorldMatrix();\n if (batch.renderSelf[subMesh._id]) {\n world.copyToArray(this._instancesData, offset);\n offset += 16;\n instancesCount++;\n }\n if (visibleInstances) {\n for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {\n var instance = visibleInstances[instanceIndex];\n instance.getWorldMatrix().copyToArray(this._instancesData, offset);\n offset += 16;\n instancesCount++;\n }\n }\n if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {\n if (instancesBuffer) {\n instancesBuffer.dispose();\n }\n instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);\n this._instancesBuffer = instancesBuffer;\n this.setVerticesBuffer(instancesBuffer.createVertexBuffer(\"world0\", 0, 4));\n this.setVerticesBuffer(instancesBuffer.createVertexBuffer(\"world1\", 4, 4));\n this.setVerticesBuffer(instancesBuffer.createVertexBuffer(\"world2\", 8, 4));\n this.setVerticesBuffer(instancesBuffer.createVertexBuffer(\"world3\", 12, 4));\n }\n else {\n instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);\n }\n this._bind(subMesh, effect, fillMode);\n this._draw(subMesh, fillMode, instancesCount);\n engine.unbindInstanceAttributes();\n return this;\n };\n Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {\n var scene = this.getScene();\n var engine = scene.getEngine();\n if (hardwareInstancedRendering) {\n this._renderWithInstances(subMesh, fillMode, batch, effect, engine);\n }\n else {\n if (batch.renderSelf[subMesh._id]) {\n // Draw\n if (onBeforeDraw) {\n onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);\n }\n this._draw(subMesh, fillMode, this._overridenInstanceCount);\n }\n var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];\n if (visibleInstancesForSubMesh) {\n for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {\n var instance = visibleInstancesForSubMesh[instanceIndex];\n // World\n var world = instance.getWorldMatrix();\n if (onBeforeDraw) {\n onBeforeDraw(true, world, effectiveMaterial);\n }\n // Draw\n this._draw(subMesh, fillMode);\n }\n }\n }\n return this;\n };\n /**\n * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager\n * @param subMesh defines the subMesh to render\n * @param enableAlphaMode defines if alpha mode can be changed\n * @returns the current mesh\n */\n Mesh.prototype.render = function (subMesh, enableAlphaMode) {\n // this._checkOcclusionQuery();\n // if (this._isOccluded) {\n // return this;\n // }\n var scene = this.getScene();\n // Managing instances\n var batch = this._getInstancesRenderList(subMesh._id);\n if (batch.mustReturn) {\n return this;\n }\n // Checking geometry state\n if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {\n return this;\n }\n if (this._onBeforeRenderObservable) {\n this._onBeforeRenderObservable.notifyObservers(this);\n }\n var engine = scene.getEngine();\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);\n // Material\n var material = subMesh.getMaterial();\n if (!material) {\n return this;\n }\n this._effectiveMaterial = material;\n if (this._effectiveMaterial.storeEffectOnSubMeshes) {\n if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {\n return this;\n }\n }\n else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {\n return this;\n }\n // Alpha mode\n if (enableAlphaMode) {\n engine.setAlphaMode(this._effectiveMaterial.alphaMode);\n }\n // Outline - step 1\n var savedDepthWrite = engine.getDepthWrite();\n if (this.renderOutline) {\n engine.setDepthWrite(false);\n scene.getOutlineRenderer().render(subMesh, batch);\n engine.setDepthWrite(savedDepthWrite);\n }\n var effect;\n if (this._effectiveMaterial.storeEffectOnSubMeshes) {\n effect = subMesh.effect;\n }\n else {\n effect = this._effectiveMaterial.getEffect();\n }\n if (!effect) {\n return this;\n }\n var sideOrientation = this.overrideMaterialSideOrientation;\n if (sideOrientation == null) {\n sideOrientation = this._effectiveMaterial.sideOrientation;\n if (this._getWorldMatrixDeterminant() < 0) {\n sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);\n }\n }\n var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);\n if (this._effectiveMaterial.forceDepthWrite) {\n engine.setDepthWrite(true);\n }\n // Bind\n var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);\n if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB\n this._bind(subMesh, effect, fillMode);\n }\n var world = this.getWorldMatrix();\n if (this._effectiveMaterial.storeEffectOnSubMeshes) {\n this._effectiveMaterial.bindForSubMesh(world, this, subMesh);\n }\n else {\n this._effectiveMaterial.bind(world, this);\n }\n if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {\n engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);\n this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);\n engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);\n }\n // Draw\n this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);\n // Unbind\n this._effectiveMaterial.unbind();\n // Outline - step 2\n if (this.renderOutline && savedDepthWrite) {\n engine.setDepthWrite(true);\n engine.setColorWrite(false);\n scene.getOutlineRenderer().render(subMesh, batch);\n engine.setColorWrite(true);\n }\n // Overlay\n if (this.renderOverlay) {\n var currentMode = engine.getAlphaMode();\n engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);\n scene.getOutlineRenderer().render(subMesh, batch, true);\n engine.setAlphaMode(currentMode);\n }\n if (this._onAfterRenderObservable) {\n this._onAfterRenderObservable.notifyObservers(this);\n }\n return this;\n };\n Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {\n if (isInstance && effectiveMaterial) {\n effectiveMaterial.bindOnlyWorldMatrix(world);\n }\n };\n /**\n * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.\n */\n Mesh.prototype.getEmittedParticleSystems = function () {\n var results = new Array();\n for (var index = 0; index < this.getScene().particleSystems.length; index++) {\n var particleSystem = this.getScene().particleSystems[index];\n if (particleSystem.emitter === this) {\n results.push(particleSystem);\n }\n }\n return results;\n };\n /**\n * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.\n */\n Mesh.prototype.getHierarchyEmittedParticleSystems = function () {\n var results = new Array();\n var descendants = this.getDescendants();\n descendants.push(this);\n for (var index = 0; index < this.getScene().particleSystems.length; index++) {\n var particleSystem = this.getScene().particleSystems[index];\n var emitter = particleSystem.emitter;\n if (emitter.position && descendants.indexOf(emitter) !== -1) {\n results.push(particleSystem);\n }\n }\n return results;\n };\n /**\n * Normalize matrix weights so that all vertices have a total weight set to 1\n */\n Mesh.prototype.cleanMatrixWeights = function () {\n var epsilon = 1e-3;\n var noInfluenceBoneIndex = 0.0;\n if (this.skeleton) {\n noInfluenceBoneIndex = this.skeleton.bones.length;\n }\n else {\n return;\n }\n var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);\n var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);\n var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n var influencers = this.numBoneInfluencers;\n var size = matricesWeights.length;\n for (var i = 0; i < size; i += 4) {\n var weight = 0.0;\n var firstZeroWeight = -1;\n for (var j = 0; j < 4; j++) {\n var w = matricesWeights[i + j];\n weight += w;\n if (w < epsilon && firstZeroWeight < 0) {\n firstZeroWeight = j;\n }\n }\n if (matricesWeightsExtra) {\n for (var j = 0; j < 4; j++) {\n var w = matricesWeightsExtra[i + j];\n weight += w;\n if (w < epsilon && firstZeroWeight < 0) {\n firstZeroWeight = j + 4;\n }\n }\n }\n if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {\n firstZeroWeight = influencers - 1;\n }\n if (weight > epsilon) {\n var mweight = 1.0 / weight;\n for (var j = 0; j < 4; j++) {\n matricesWeights[i + j] *= mweight;\n }\n if (matricesWeightsExtra) {\n for (var j = 0; j < 4; j++) {\n matricesWeightsExtra[i + j] *= mweight;\n }\n }\n }\n else {\n if (firstZeroWeight >= 4) {\n matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;\n matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;\n }\n else {\n matricesWeights[i + firstZeroWeight] = 1.0 - weight;\n matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;\n }\n }\n }\n this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);\n if (matricesIndicesExtra) {\n this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);\n }\n this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);\n if (matricesWeightsExtra) {\n this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);\n }\n };\n Mesh.prototype._checkDelayState = function () {\n var scene = this.getScene();\n if (this._geometry) {\n this._geometry.load(scene);\n }\n else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;\n this._queueLoad(scene);\n }\n return this;\n };\n Mesh.prototype._queueLoad = function (scene) {\n var _this = this;\n scene._addPendingData(this);\n var getBinaryData = (this.delayLoadingFile.indexOf(\".babylonbinarymeshdata\") !== -1);\n BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {\n if (data instanceof ArrayBuffer) {\n _this._delayLoadingFunction(data, _this);\n }\n else {\n _this._delayLoadingFunction(JSON.parse(data), _this);\n }\n _this.instances.forEach(function (instance) {\n instance._syncSubMeshes();\n });\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;\n scene._removePendingData(_this);\n }, function () { }, scene.database, getBinaryData);\n return this;\n };\n /**\n * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.\n */\n Mesh.prototype.isInFrustum = function (frustumPlanes) {\n if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {\n return false;\n }\n if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {\n return false;\n }\n this._checkDelayState();\n return true;\n };\n /**\n * Sets the mesh material by the material or multiMaterial `id` property.\n * The material `id` is a string identifying the material or the multiMaterial.\n * This method returns the Mesh.\n */\n Mesh.prototype.setMaterialByID = function (id) {\n var materials = this.getScene().materials;\n var index;\n for (index = materials.length - 1; index > -1; index--) {\n if (materials[index].id === id) {\n this.material = materials[index];\n return this;\n }\n }\n // Multi\n var multiMaterials = this.getScene().multiMaterials;\n for (index = multiMaterials.length - 1; index > -1; index--) {\n if (multiMaterials[index].id === id) {\n this.material = multiMaterials[index];\n return this;\n }\n }\n return this;\n };\n /**\n * Returns as a new array populated with the mesh material and/or skeleton, if any.\n */\n Mesh.prototype.getAnimatables = function () {\n var results = new Array();\n if (this.material) {\n results.push(this.material);\n }\n if (this.skeleton) {\n results.push(this.skeleton);\n }\n return results;\n };\n /**\n * Modifies the mesh geometry according to the passed transformation matrix.\n * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.\n * The mesh normals are modified accordingly the same transformation.\n * tuto : http://doc.babylonjs.com/resources/baking_transformations\n * Note that, under the hood, this method sets a new VertexBuffer each call.\n * Returns the Mesh.\n */\n Mesh.prototype.bakeTransformIntoVertices = function (transform) {\n // Position\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {\n return this;\n }\n var submeshes = this.subMeshes.splice(0);\n this._resetPointsArrayCache();\n var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var temp = new Array();\n var index;\n for (index = 0; index < data.length; index += 3) {\n BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);\n }\n this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());\n // Normals\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n return this;\n }\n data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n temp = [];\n for (index = 0; index < data.length; index += 3) {\n BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);\n }\n this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());\n // flip faces?\n if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {\n this.flipFaces();\n }\n // Restore submeshes\n this.releaseSubMeshes();\n this.subMeshes = submeshes;\n return this;\n };\n /**\n * Modifies the mesh geometry according to its own current World Matrix.\n * The mesh World Matrix is then reset.\n * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.\n * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations\n * Note that, under the hood, this method sets a new VertexBuffer each call.\n * Returns the Mesh.\n */\n Mesh.prototype.bakeCurrentTransformIntoVertices = function () {\n this.bakeTransformIntoVertices(this.computeWorldMatrix(true));\n this.scaling.copyFromFloats(1, 1, 1);\n this.position.copyFromFloats(0, 0, 0);\n this.rotation.copyFromFloats(0, 0, 0);\n //only if quaternion is already set\n if (this.rotationQuaternion) {\n this.rotationQuaternion = BABYLON.Quaternion.Identity();\n }\n this._worldMatrix = BABYLON.Matrix.Identity();\n return this;\n };\n Object.defineProperty(Mesh.prototype, \"_positions\", {\n // Cache\n get: function () {\n if (this._geometry) {\n return this._geometry._positions;\n }\n return null;\n },\n enumerable: true,\n configurable: true\n });\n Mesh.prototype._resetPointsArrayCache = function () {\n if (this._geometry) {\n this._geometry._resetPointsArrayCache();\n }\n return this;\n };\n Mesh.prototype._generatePointsArray = function () {\n if (this._geometry) {\n return this._geometry._generatePointsArray();\n }\n return false;\n };\n /**\n * Returns a new Mesh object generated from the current mesh properties.\n * This method must not get confused with createInstance().\n * The parameter `name` is a string, the name given to the new mesh.\n * The optional parameter `newParent` can be any Node object (default `null`).\n * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.\n * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.\n */\n Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {\n if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }\n return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);\n };\n /**\n * Releases resources associated with this mesh.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n var _this = this;\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n this.morphTargetManager = null;\n if (this._geometry) {\n this._geometry.releaseForMesh(this, true);\n }\n if (this._onBeforeDrawObservable) {\n this._onBeforeDrawObservable.clear();\n }\n if (this._onBeforeRenderObservable) {\n this._onBeforeRenderObservable.clear();\n }\n if (this._onAfterRenderObservable) {\n this._onAfterRenderObservable.clear();\n }\n // Sources\n var meshes = this.getScene().meshes;\n meshes.forEach(function (abstractMesh) {\n var mesh = abstractMesh;\n if (mesh._source && mesh._source === _this) {\n mesh._source = null;\n }\n });\n this._source = null;\n // Instances\n if (this._instancesBuffer) {\n this._instancesBuffer.dispose();\n this._instancesBuffer = null;\n }\n while (this.instances.length) {\n this.instances[0].dispose();\n }\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n /**\n * Modifies the mesh geometry according to a displacement map.\n * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.\n * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.\n * This method returns nothing.\n * The parameter `url` is a string, the URL from the image file is to be downloaded.\n * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.\n * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.\n * The parameter `uvOffset` is an optional vector2 used to offset UV.\n * The parameter `uvScale` is an optional vector2 used to scale UV.\n *\n * Returns the Mesh.\n */\n Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {\n var _this = this;\n var scene = this.getScene();\n var onload = function (img) {\n // Getting height map data\n var canvas = document.createElement(\"canvas\");\n var context = canvas.getContext(\"2d\");\n var heightMapWidth = img.width;\n var heightMapHeight = img.height;\n canvas.width = heightMapWidth;\n canvas.height = heightMapHeight;\n context.drawImage(img, 0, 0);\n // Create VertexData from map data\n //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949\n var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;\n _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);\n //execute success callback, if set\n if (onSuccess) {\n onSuccess(_this);\n }\n };\n BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);\n return this;\n };\n /**\n * Modifies the mesh geometry according to a displacementMap buffer.\n * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.\n * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.\n * This method returns nothing.\n * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.\n * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.\n * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.\n * The parameter `uvOffset` is an optional vector2 used to offset UV.\n * The parameter `uvScale` is an optional vector2 used to scale UV.\n *\n * Returns the Mesh.\n */\n Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)\n || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)\n || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n BABYLON.Tools.Warn(\"Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing\");\n return this;\n }\n var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);\n var position = BABYLON.Vector3.Zero();\n var normal = BABYLON.Vector3.Zero();\n var uv = BABYLON.Vector2.Zero();\n uvOffset = uvOffset || BABYLON.Vector2.Zero();\n uvScale = uvScale || new BABYLON.Vector2(1, 1);\n for (var index = 0; index < positions.length; index += 3) {\n BABYLON.Vector3.FromArrayToRef(positions, index, position);\n BABYLON.Vector3.FromArrayToRef(normals, index, normal);\n BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);\n // Compute height\n var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;\n var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;\n var pos = (u + v * heightMapWidth) * 4;\n var r = buffer[pos] / 255.0;\n var g = buffer[pos + 1] / 255.0;\n var b = buffer[pos + 2] / 255.0;\n var gradient = r * 0.3 + g * 0.59 + b * 0.11;\n normal.normalize();\n normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);\n position = position.add(normal);\n position.toArray(positions, index);\n }\n BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);\n this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);\n this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);\n return this;\n };\n /**\n * Modify the mesh to get a flat shading rendering.\n * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.\n * This method returns the Mesh.\n * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.\n */\n Mesh.prototype.convertToFlatShadedMesh = function () {\n /// Update normals and vertices to get a flat shading rendering.\n /// Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face\n var kinds = this.getVerticesDataKinds();\n var vbs = {};\n var data = {};\n var newdata = {};\n var updatableNormals = false;\n var kindIndex;\n var kind;\n for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {\n kind = kinds[kindIndex];\n var vertexBuffer = this.getVertexBuffer(kind);\n if (kind === BABYLON.VertexBuffer.NormalKind) {\n updatableNormals = vertexBuffer.isUpdatable();\n kinds.splice(kindIndex, 1);\n kindIndex--;\n continue;\n }\n vbs[kind] = vertexBuffer;\n data[kind] = vbs[kind].getData();\n newdata[kind] = [];\n }\n // Save previous submeshes\n var previousSubmeshes = this.subMeshes.slice(0);\n var indices = this.getIndices();\n var totalIndices = this.getTotalIndices();\n // Generating unique vertices per face\n var index;\n for (index = 0; index < totalIndices; index++) {\n var vertexIndex = indices[index];\n for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {\n kind = kinds[kindIndex];\n var stride = vbs[kind].getStrideSize();\n for (var offset = 0; offset < stride; offset++) {\n newdata[kind].push(data[kind][vertexIndex * stride + offset]);\n }\n }\n }\n // Updating faces & normal\n var normals = [];\n var positions = newdata[BABYLON.VertexBuffer.PositionKind];\n for (index = 0; index < totalIndices; index += 3) {\n indices[index] = index;\n indices[index + 1] = index + 1;\n indices[index + 2] = index + 2;\n var p1 = BABYLON.Vector3.FromArray(positions, index * 3);\n var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);\n var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);\n var p1p2 = p1.subtract(p2);\n var p3p2 = p3.subtract(p2);\n var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));\n // Store same normals for every vertex\n for (var localIndex = 0; localIndex < 3; localIndex++) {\n normals.push(normal.x);\n normals.push(normal.y);\n normals.push(normal.z);\n }\n }\n this.setIndices(indices);\n this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);\n // Updating vertex buffers\n for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {\n kind = kinds[kindIndex];\n this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());\n }\n // Updating submeshes\n this.releaseSubMeshes();\n for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {\n var previousOne = previousSubmeshes[submeshIndex];\n BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);\n }\n this.synchronizeInstances();\n return this;\n };\n /**\n * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.\n * In other words, more vertices, no more indices and a single bigger VBO.\n * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.\n * Returns the Mesh.\n */\n Mesh.prototype.convertToUnIndexedMesh = function () {\n /// Remove indices by unfolding faces into buffers\n /// Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face\n var kinds = this.getVerticesDataKinds();\n var vbs = {};\n var data = {};\n var newdata = {};\n var kindIndex;\n var kind;\n for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {\n kind = kinds[kindIndex];\n var vertexBuffer = this.getVertexBuffer(kind);\n vbs[kind] = vertexBuffer;\n data[kind] = vbs[kind].getData();\n newdata[kind] = [];\n }\n // Save previous submeshes\n var previousSubmeshes = this.subMeshes.slice(0);\n var indices = this.getIndices();\n var totalIndices = this.getTotalIndices();\n // Generating unique vertices per face\n var index;\n for (index = 0; index < totalIndices; index++) {\n var vertexIndex = indices[index];\n for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {\n kind = kinds[kindIndex];\n var stride = vbs[kind].getStrideSize();\n for (var offset = 0; offset < stride; offset++) {\n newdata[kind].push(data[kind][vertexIndex * stride + offset]);\n }\n }\n }\n // Updating indices\n for (index = 0; index < totalIndices; index += 3) {\n indices[index] = index;\n indices[index + 1] = index + 1;\n indices[index + 2] = index + 2;\n }\n this.setIndices(indices);\n // Updating vertex buffers\n for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {\n kind = kinds[kindIndex];\n this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());\n }\n // Updating submeshes\n this.releaseSubMeshes();\n for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {\n var previousOne = previousSubmeshes[submeshIndex];\n BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);\n }\n this._unIndexed = true;\n this.synchronizeInstances();\n return this;\n };\n /**\n * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.\n * This method returns the Mesh.\n * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.\n */\n Mesh.prototype.flipFaces = function (flipNormals) {\n if (flipNormals === void 0) { flipNormals = false; }\n var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);\n var i;\n if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {\n for (i = 0; i < vertex_data.normals.length; i++) {\n vertex_data.normals[i] *= -1;\n }\n }\n if (vertex_data.indices) {\n var temp;\n for (i = 0; i < vertex_data.indices.length; i += 3) {\n // reassign indices\n temp = vertex_data.indices[i + 1];\n vertex_data.indices[i + 1] = vertex_data.indices[i + 2];\n vertex_data.indices[i + 2] = temp;\n }\n }\n vertex_data.applyToMesh(this);\n return this;\n };\n // Instances\n /**\n * Creates a new InstancedMesh object from the mesh model.\n * An instance shares the same properties and the same material than its model.\n * Only these properties of each instance can then be set individually :\n * - position\n * - rotation\n * - rotationQuaternion\n * - setPivotMatrix\n * - scaling\n * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances\n * Warning : this method is not supported for Line mesh and LineSystem\n */\n Mesh.prototype.createInstance = function (name) {\n return new BABYLON.InstancedMesh(name, this);\n };\n /**\n * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.\n * After this call, all the mesh instances have the same submeshes than the current mesh.\n * This method returns the Mesh.\n */\n Mesh.prototype.synchronizeInstances = function () {\n for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {\n var instance = this.instances[instanceIndex];\n instance._syncSubMeshes();\n }\n return this;\n };\n /**\n * Simplify the mesh according to the given array of settings.\n * Function will return immediately and will simplify async. It returns the Mesh.\n * @param settings a collection of simplification settings.\n * @param parallelProcessing should all levels calculate parallel or one after the other.\n * @param type the type of simplification to run.\n * @param successCallback optional success callback to be called after the simplification finished processing all settings.\n */\n Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {\n if (parallelProcessing === void 0) { parallelProcessing = true; }\n if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }\n this.getScene().simplificationQueue.addTask({\n settings: settings,\n parallelProcessing: parallelProcessing,\n mesh: this,\n simplificationType: simplificationType,\n successCallback: successCallback\n });\n return this;\n };\n /**\n * Optimization of the mesh's indices, in case a mesh has duplicated vertices.\n * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.\n * This should be used together with the simplification to avoid disappearing triangles.\n * Returns the Mesh.\n * @param successCallback an optional success callback to be called after the optimization finished.\n */\n Mesh.prototype.optimizeIndices = function (successCallback) {\n var _this = this;\n var indices = this.getIndices();\n var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!positions || !indices) {\n return this;\n }\n var vectorPositions = new Array();\n for (var pos = 0; pos < positions.length; pos = pos + 3) {\n vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));\n }\n var dupes = new Array();\n BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {\n var realPos = vectorPositions.length - 1 - iteration;\n var testedPosition = vectorPositions[realPos];\n for (var j = 0; j < realPos; ++j) {\n var againstPosition = vectorPositions[j];\n if (testedPosition.equals(againstPosition)) {\n dupes[realPos] = j;\n break;\n }\n }\n }, function () {\n for (var i = 0; i < indices.length; ++i) {\n indices[i] = dupes[indices[i]] || indices[i];\n }\n //indices are now reordered\n var originalSubMeshes = _this.subMeshes.slice(0);\n _this.setIndices(indices);\n _this.subMeshes = originalSubMeshes;\n if (successCallback) {\n successCallback(_this);\n }\n });\n return this;\n };\n Mesh.prototype.serialize = function (serializationObject) {\n serializationObject.name = this.name;\n serializationObject.id = this.id;\n serializationObject.type = this.getClassName();\n if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {\n serializationObject.tags = BABYLON.Tags.GetTags(this);\n }\n serializationObject.position = this.position.asArray();\n if (this.rotationQuaternion) {\n serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();\n }\n else if (this.rotation) {\n serializationObject.rotation = this.rotation.asArray();\n }\n serializationObject.scaling = this.scaling.asArray();\n serializationObject.localMatrix = this.getPivotMatrix().asArray();\n serializationObject.isEnabled = this.isEnabled(false);\n serializationObject.isVisible = this.isVisible;\n serializationObject.infiniteDistance = this.infiniteDistance;\n serializationObject.pickable = this.isPickable;\n serializationObject.receiveShadows = this.receiveShadows;\n serializationObject.billboardMode = this.billboardMode;\n serializationObject.visibility = this.visibility;\n serializationObject.checkCollisions = this.checkCollisions;\n serializationObject.isBlocker = this.isBlocker;\n // Parent\n if (this.parent) {\n serializationObject.parentId = this.parent.id;\n }\n // Geometry\n serializationObject.isUnIndexed = this.isUnIndexed;\n var geometry = this._geometry;\n if (geometry) {\n var geometryId = geometry.id;\n serializationObject.geometryId = geometryId;\n // SubMeshes\n serializationObject.subMeshes = [];\n for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {\n var subMesh = this.subMeshes[subIndex];\n serializationObject.subMeshes.push({\n materialIndex: subMesh.materialIndex,\n verticesStart: subMesh.verticesStart,\n verticesCount: subMesh.verticesCount,\n indexStart: subMesh.indexStart,\n indexCount: subMesh.indexCount\n });\n }\n }\n // Material\n if (this.material) {\n serializationObject.materialId = this.material.id;\n }\n else {\n this.material = null;\n }\n // Morph targets\n if (this.morphTargetManager) {\n serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;\n }\n // Skeleton\n if (this.skeleton) {\n serializationObject.skeletonId = this.skeleton.id;\n }\n // Physics\n //TODO implement correct serialization for physics impostors.\n var impostor = this.getPhysicsImpostor();\n if (impostor) {\n serializationObject.physicsMass = impostor.getParam(\"mass\");\n serializationObject.physicsFriction = impostor.getParam(\"friction\");\n serializationObject.physicsRestitution = impostor.getParam(\"mass\");\n serializationObject.physicsImpostor = impostor.type;\n }\n // Metadata\n if (this.metadata) {\n serializationObject.metadata = this.metadata;\n }\n // Instances\n serializationObject.instances = [];\n for (var index = 0; index < this.instances.length; index++) {\n var instance = this.instances[index];\n var serializationInstance = {\n name: instance.name,\n id: instance.id,\n position: instance.position.asArray(),\n scaling: instance.scaling.asArray()\n };\n if (instance.rotationQuaternion) {\n serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();\n }\n else if (instance.rotation) {\n serializationInstance.rotation = instance.rotation.asArray();\n }\n serializationObject.instances.push(serializationInstance);\n // Animations\n BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);\n serializationInstance.ranges = instance.serializeAnimationRanges();\n }\n // \n // Animations\n BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);\n serializationObject.ranges = this.serializeAnimationRanges();\n // Layer mask\n serializationObject.layerMask = this.layerMask;\n // Alpha\n serializationObject.alphaIndex = this.alphaIndex;\n serializationObject.hasVertexAlpha = this.hasVertexAlpha;\n // Overlay\n serializationObject.overlayAlpha = this.overlayAlpha;\n serializationObject.overlayColor = this.overlayColor.asArray();\n serializationObject.renderOverlay = this.renderOverlay;\n // Fog\n serializationObject.applyFog = this.applyFog;\n // Action Manager\n if (this.actionManager) {\n serializationObject.actions = this.actionManager.serialize(this.name);\n }\n };\n Mesh.prototype._syncGeometryWithMorphTargetManager = function () {\n if (!this.geometry) {\n return;\n }\n this._markSubMeshesAsAttributesDirty();\n var morphTargetManager = this._morphTargetManager;\n if (morphTargetManager && morphTargetManager.vertexCount) {\n if (morphTargetManager.vertexCount !== this.getTotalVertices()) {\n BABYLON.Tools.Error(\"Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.\");\n this.morphTargetManager = null;\n return;\n }\n for (var index = 0; index < morphTargetManager.numInfluencers; index++) {\n var morphTarget = morphTargetManager.getActiveTarget(index);\n var positions = morphTarget.getPositions();\n if (!positions) {\n BABYLON.Tools.Error(\"Invalid morph target. Target must have positions.\");\n return;\n }\n this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);\n var normals = morphTarget.getNormals();\n if (normals) {\n this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);\n }\n var tangents = morphTarget.getTangents();\n if (tangents) {\n this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);\n }\n }\n }\n else {\n var index = 0;\n // Positions\n while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {\n this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);\n if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {\n this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);\n }\n if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {\n this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);\n }\n index++;\n }\n }\n };\n // Statics\n /**\n * Returns a new Mesh object parsed from the source provided.\n * The parameter `parsedMesh` is the source.\n * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with\n */\n Mesh.Parse = function (parsedMesh, scene, rootUrl) {\n var mesh;\n if (parsedMesh.type && parsedMesh.type === \"GroundMesh\") {\n mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);\n }\n else {\n mesh = new Mesh(parsedMesh.name, scene);\n }\n mesh.id = parsedMesh.id;\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);\n }\n mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);\n if (parsedMesh.metadata !== undefined) {\n mesh.metadata = parsedMesh.metadata;\n }\n if (parsedMesh.rotationQuaternion) {\n mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);\n }\n else if (parsedMesh.rotation) {\n mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);\n }\n mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);\n if (parsedMesh.localMatrix) {\n mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));\n }\n else if (parsedMesh.pivotMatrix) {\n mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));\n }\n mesh.setEnabled(parsedMesh.isEnabled);\n mesh.isVisible = parsedMesh.isVisible;\n mesh.infiniteDistance = parsedMesh.infiniteDistance;\n mesh.showBoundingBox = parsedMesh.showBoundingBox;\n mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;\n if (parsedMesh.applyFog !== undefined) {\n mesh.applyFog = parsedMesh.applyFog;\n }\n if (parsedMesh.pickable !== undefined) {\n mesh.isPickable = parsedMesh.pickable;\n }\n if (parsedMesh.alphaIndex !== undefined) {\n mesh.alphaIndex = parsedMesh.alphaIndex;\n }\n mesh.receiveShadows = parsedMesh.receiveShadows;\n mesh.billboardMode = parsedMesh.billboardMode;\n if (parsedMesh.visibility !== undefined) {\n mesh.visibility = parsedMesh.visibility;\n }\n mesh.checkCollisions = parsedMesh.checkCollisions;\n if (parsedMesh.isBlocker !== undefined) {\n mesh.isBlocker = parsedMesh.isBlocker;\n }\n mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;\n // freezeWorldMatrix\n if (parsedMesh.freezeWorldMatrix) {\n mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;\n }\n // Parent\n if (parsedMesh.parentId) {\n mesh._waitingParentId = parsedMesh.parentId;\n }\n // Actions\n if (parsedMesh.actions !== undefined) {\n mesh._waitingActions = parsedMesh.actions;\n }\n // Overlay\n if (parsedMesh.overlayAlpha !== undefined) {\n mesh.overlayAlpha = parsedMesh.overlayAlpha;\n }\n if (parsedMesh.overlayColor !== undefined) {\n mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);\n }\n if (parsedMesh.renderOverlay !== undefined) {\n mesh.renderOverlay = parsedMesh.renderOverlay;\n }\n // Geometry\n mesh.isUnIndexed = !!parsedMesh.isUnIndexed;\n mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;\n if (parsedMesh.delayLoadingFile) {\n mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;\n mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));\n if (parsedMesh._binaryInfo) {\n mesh._binaryInfo = parsedMesh._binaryInfo;\n }\n mesh._delayInfo = [];\n if (parsedMesh.hasUVs) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);\n }\n if (parsedMesh.hasUVs2) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);\n }\n if (parsedMesh.hasUVs3) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);\n }\n if (parsedMesh.hasUVs4) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);\n }\n if (parsedMesh.hasUVs5) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);\n }\n if (parsedMesh.hasUVs6) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);\n }\n if (parsedMesh.hasColors) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);\n }\n if (parsedMesh.hasMatricesIndices) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n }\n if (parsedMesh.hasMatricesWeights) {\n mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n }\n mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;\n if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {\n mesh._checkDelayState();\n }\n }\n else {\n BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);\n }\n // Material\n if (parsedMesh.materialId) {\n mesh.setMaterialByID(parsedMesh.materialId);\n }\n else {\n mesh.material = null;\n }\n // Morph targets\n if (parsedMesh.morphTargetManagerId > -1) {\n mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);\n }\n // Skeleton\n if (parsedMesh.skeletonId > -1) {\n mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);\n if (parsedMesh.numBoneInfluencers) {\n mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;\n }\n }\n // Animations\n if (parsedMesh.animations) {\n for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {\n var parsedAnimation = parsedMesh.animations[animationIndex];\n mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);\n }\n if (parsedMesh.autoAnimate) {\n scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);\n }\n // Layer Mask\n if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {\n mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));\n }\n else {\n mesh.layerMask = 0x0FFFFFFF;\n }\n // Physics\n if (parsedMesh.physicsImpostor) {\n mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {\n mass: parsedMesh.physicsMass,\n friction: parsedMesh.physicsFriction,\n restitution: parsedMesh.physicsRestitution\n }, scene);\n }\n // Instances\n if (parsedMesh.instances) {\n for (var index = 0; index < parsedMesh.instances.length; index++) {\n var parsedInstance = parsedMesh.instances[index];\n var instance = mesh.createInstance(parsedInstance.name);\n if (parsedInstance.id) {\n instance.id = parsedInstance.id;\n }\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);\n }\n instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);\n if (parsedInstance.parentId) {\n instance._waitingParentId = parsedInstance.parentId;\n }\n if (parsedInstance.rotationQuaternion) {\n instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);\n }\n else if (parsedInstance.rotation) {\n instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);\n }\n instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);\n instance.checkCollisions = mesh.checkCollisions;\n if (parsedMesh.animations) {\n for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {\n parsedAnimation = parsedMesh.animations[animationIndex];\n instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);\n if (parsedMesh.autoAnimate) {\n scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);\n }\n }\n }\n }\n return mesh;\n };\n /**\n * Creates a ribbon mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.\n *\n * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial\n * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.\n * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.\n * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.\n * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.\n * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.\n * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {\n if (closeArray === void 0) { closeArray = false; }\n if (updatable === void 0) { updatable = false; }\n return BABYLON.MeshBuilder.CreateRibbon(name, {\n pathArray: pathArray,\n closeArray: closeArray,\n closePath: closePath,\n offset: offset,\n updatable: updatable,\n sideOrientation: sideOrientation,\n instance: instance\n }, scene);\n };\n /**\n * Creates a plane polygonal mesh. By default, this is a disc.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).\n * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {\n if (scene === void 0) { scene = null; }\n var options = {\n radius: radius,\n tessellation: tessellation,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateDisc(name, options, scene);\n };\n /**\n * Creates a box mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `size` sets the size (float) of each box side (default 1).\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {\n if (scene === void 0) { scene = null; }\n var options = {\n size: size,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateBox(name, options, scene);\n };\n /**\n * Creates a sphere mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).\n * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {\n var options = {\n segments: segments,\n diameterX: diameter,\n diameterY: diameter,\n diameterZ: diameter,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateSphere(name, options, scene);\n };\n /**\n * Creates a cylinder or a cone mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).\n * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).\n * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter \"diameterBottom\" can't be zero.\n * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.\n * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {\n if (scene === undefined || !(scene instanceof BABYLON.Scene)) {\n if (scene !== undefined) {\n sideOrientation = updatable || Mesh.DEFAULTSIDE;\n updatable = scene;\n }\n scene = subdivisions;\n subdivisions = 1;\n }\n var options = {\n height: height,\n diameterTop: diameterTop,\n diameterBottom: diameterBottom,\n tessellation: tessellation,\n subdivisions: subdivisions,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);\n };\n // Torus (Code from SharpDX.org)\n /**\n * Creates a torus mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `diameter` sets the diameter size (float) of the torus (default 1).\n * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).\n * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {\n var options = {\n diameter: diameter,\n thickness: thickness,\n tessellation: tessellation,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateTorus(name, options, scene);\n };\n /**\n * Creates a torus knot mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).\n * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).\n * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).\n * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {\n var options = {\n radius: radius,\n tube: tube,\n radialSegments: radialSegments,\n tubularSegments: tubularSegments,\n p: p,\n q: q,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);\n };\n /**\n * Creates a line mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.\n * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.\n * The parameter `points` is an array successive Vector3.\n * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines\n * When updating an instance, remember that only point positions can change, not the number of points.\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateLines = function (name, points, scene, updatable, instance) {\n if (scene === void 0) { scene = null; }\n if (updatable === void 0) { updatable = false; }\n if (instance === void 0) { instance = null; }\n var options = {\n points: points,\n updatable: updatable,\n instance: instance\n };\n return BABYLON.MeshBuilder.CreateLines(name, options, scene);\n };\n /**\n * Creates a dashed line mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.\n * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.\n * The parameter `points` is an array successive Vector3.\n * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).\n * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).\n * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).\n * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines\n * When updating an instance, remember that only point positions can change, not the number of points.\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {\n if (scene === void 0) { scene = null; }\n var options = {\n points: points,\n dashSize: dashSize,\n gapSize: gapSize,\n dashNb: dashNb,\n updatable: updatable,\n instance: instance\n };\n return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);\n };\n /**\n * Creates a polygon mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.\n * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.\n * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * Remember you can only change the shape positions, not their number when updating a polygon.\n */\n Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {\n var options = {\n shape: shape,\n holes: holes,\n updatable: updatable,\n sideOrientation: sideOrientation\n };\n return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);\n };\n /**\n * Creates an extruded polygon mesh, with depth in the Y direction.\n * Please consider using the same method from the MeshBuilder class instead.\n */\n Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {\n var options = {\n shape: shape,\n holes: holes,\n depth: depth,\n updatable: updatable,\n sideOrientation: sideOrientation\n };\n return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);\n };\n /**\n * Creates an extruded shape mesh.\n * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.\n * Please consider using the same method from the MeshBuilder class instead.\n *\n * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes\n * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be\n * extruded along the Z axis.\n * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.\n * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.\n * The parameter `scale` (float, default 1) is the value to scale the shape.\n * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape\n * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {\n if (scene === void 0) { scene = null; }\n var options = {\n shape: shape,\n path: path,\n scale: scale,\n rotation: rotation,\n cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,\n sideOrientation: sideOrientation,\n instance: instance,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);\n };\n /**\n * Creates an custom extruded shape mesh.\n * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.\n * Please consider using the same method from the MeshBuilder class instead.\n *\n * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes\n * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be\n * extruded along the Z axis.\n * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.\n * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path\n * and the distance of this point from the begining of the path :\n * ```javascript\n * var rotationFunction = function(i, distance) {\n * // do things\n * return rotationValue; }\n * ```\n * It must returns a float value that will be the rotation in radians applied to the shape on each path point.\n * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path\n * and the distance of this point from the begining of the path :\n * ```javascript\n * var scaleFunction = function(i, distance) {\n * // do things\n * return scaleValue;}\n * ```\n * It must returns a float value that will be the scale value applied to the shape on each path point.\n * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.\n * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.\n * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape\n * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {\n var options = {\n shape: shape,\n path: path,\n scaleFunction: scaleFunction,\n rotationFunction: rotationFunction,\n ribbonCloseArray: ribbonCloseArray,\n ribbonClosePath: ribbonClosePath,\n cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,\n sideOrientation: sideOrientation,\n instance: instance,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);\n };\n /**\n * Creates lathe mesh.\n * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be\n * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.\n * The parameter `radius` (positive float, default 1) is the radius value of the lathe.\n * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {\n var options = {\n shape: shape,\n radius: radius,\n tessellation: tessellation,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateLathe(name, options, scene);\n };\n /**\n * Creates a plane mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {\n var options = {\n size: size,\n width: size,\n height: size,\n sideOrientation: sideOrientation,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreatePlane(name, options, scene);\n };\n /**\n * Creates a ground mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.\n * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {\n var options = {\n width: width,\n height: height,\n subdivisions: subdivisions,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateGround(name, options, scene);\n };\n /**\n * Creates a tiled ground mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.\n * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.\n * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the\n * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.\n * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the\n * numbers of subdivisions on the ground width and height of each tile.\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {\n var options = {\n xmin: xmin,\n zmin: zmin,\n xmax: xmax,\n zmax: zmax,\n subdivisions: subdivisions,\n precision: precision,\n updatable: updatable\n };\n return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);\n };\n /**\n * Creates a ground mesh from a height map.\n * tuto : http://doc.babylonjs.com/babylon101/height_map\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `url` sets the URL of the height map image resource.\n * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.\n * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.\n * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.\n * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.\n * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).\n * This function is passed the newly built mesh :\n * ```javascript\n * function(mesh) { // do things\n * return; }\n * ```\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {\n var options = {\n width: width,\n height: height,\n subdivisions: subdivisions,\n minHeight: minHeight,\n maxHeight: maxHeight,\n updatable: updatable,\n onReady: onReady\n };\n return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);\n };\n /**\n * Creates a tube mesh.\n * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.\n * The parameter `radius` (positive float, default 1) sets the tube radius size.\n * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.\n * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.\n * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.\n * It must return a radius value (positive float) :\n * ```javascript\n * var radiusFunction = function(i, distance) {\n * // do things\n * return radius; }\n * ```\n * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {\n var options = {\n path: path,\n radius: radius,\n tessellation: tessellation,\n radiusFunction: radiusFunction,\n arc: 1,\n cap: cap,\n updatable: updatable,\n sideOrientation: sideOrientation,\n instance: instance\n };\n return BABYLON.MeshBuilder.CreateTube(name, options, scene);\n };\n /**\n * Creates a polyhedron mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial\n * to choose the wanted type.\n * The parameter `size` (positive float, default 1) sets the polygon size.\n * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).\n * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.\n * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron\n * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).\n * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors\n * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreatePolyhedron = function (name, options, scene) {\n return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);\n };\n /**\n * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.\n * Please consider using the same method from the MeshBuilder class instead.\n * The parameter `radius` sets the radius size (float) of the icosphere (default 1).\n * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).\n * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.\n * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.\n * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n */\n Mesh.CreateIcoSphere = function (name, options, scene) {\n return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);\n };\n /**\n * Creates a decal mesh.\n * Please consider using the same method from the MeshBuilder class instead.\n * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.\n * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.\n * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.\n * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.\n * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.\n */\n Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {\n var options = {\n position: position,\n normal: normal,\n size: size,\n angle: angle\n };\n return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);\n };\n // Skeletons\n /**\n * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.\n */\n Mesh.prototype.setPositionsForCPUSkinning = function () {\n if (!this._sourcePositions) {\n var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!source) {\n return this._sourcePositions;\n }\n this._sourcePositions = new Float32Array(source);\n if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {\n this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);\n }\n }\n return this._sourcePositions;\n };\n /**\n * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.\n */\n Mesh.prototype.setNormalsForCPUSkinning = function () {\n if (!this._sourceNormals) {\n var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n if (!source) {\n return this._sourceNormals;\n }\n this._sourceNormals = new Float32Array(source);\n if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {\n this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);\n }\n }\n return this._sourceNormals;\n };\n /**\n * Updates the vertex buffer by applying transformation from the bones.\n * Returns the Mesh.\n *\n * @param {skeleton} skeleton to apply\n */\n Mesh.prototype.applySkeleton = function (skeleton) {\n if (!this.geometry) {\n return this;\n }\n if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {\n return this;\n }\n this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {\n return this;\n }\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n return this;\n }\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {\n return this;\n }\n if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {\n return this;\n }\n if (!this._sourcePositions) {\n var submeshes = this.subMeshes.slice();\n this.setPositionsForCPUSkinning();\n this.subMeshes = submeshes;\n }\n if (!this._sourceNormals) {\n this.setNormalsForCPUSkinning();\n }\n // positionsData checks for not being Float32Array will only pass at most once\n var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!positionsData) {\n return this;\n }\n if (!(positionsData instanceof Float32Array)) {\n positionsData = new Float32Array(positionsData);\n }\n // normalsData checks for not being Float32Array will only pass at most once\n var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n if (!normalsData) {\n return this;\n }\n if (!(normalsData instanceof Float32Array)) {\n normalsData = new Float32Array(normalsData);\n }\n var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);\n var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (!matricesWeightsData || !matricesIndicesData) {\n return this;\n }\n var needExtras = this.numBoneInfluencers > 4;\n var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;\n var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;\n var skeletonMatrices = skeleton.getTransformMatrices(this);\n var tempVector3 = BABYLON.Vector3.Zero();\n var finalMatrix = new BABYLON.Matrix();\n var tempMatrix = new BABYLON.Matrix();\n var matWeightIdx = 0;\n var inf;\n for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {\n var weight;\n for (inf = 0; inf < 4; inf++) {\n weight = matricesWeightsData[matWeightIdx + inf];\n if (weight > 0) {\n BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);\n finalMatrix.addToSelf(tempMatrix);\n }\n }\n if (needExtras) {\n for (inf = 0; inf < 4; inf++) {\n weight = matricesWeightsExtraData[matWeightIdx + inf];\n if (weight > 0) {\n BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);\n finalMatrix.addToSelf(tempMatrix);\n }\n }\n }\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);\n tempVector3.toArray(positionsData, index);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);\n tempVector3.toArray(normalsData, index);\n finalMatrix.reset();\n }\n this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);\n this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);\n return this;\n };\n // Tools\n /**\n * Returns an object `{min:` Vector3`, max:` Vector3`}`\n * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system\n */\n Mesh.MinMax = function (meshes) {\n var minVector = null;\n var maxVector = null;\n meshes.forEach(function (mesh, index, array) {\n var boundingInfo = mesh.getBoundingInfo();\n var boundingBox = boundingInfo.boundingBox;\n if (!minVector || !maxVector) {\n minVector = boundingBox.minimumWorld;\n maxVector = boundingBox.maximumWorld;\n }\n else {\n minVector.minimizeInPlace(boundingBox.minimumWorld);\n maxVector.maximizeInPlace(boundingBox.maximumWorld);\n }\n });\n if (!minVector || !maxVector) {\n return {\n min: BABYLON.Vector3.Zero(),\n max: BABYLON.Vector3.Zero()\n };\n }\n return {\n min: minVector,\n max: maxVector\n };\n };\n /**\n * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.\n */\n Mesh.Center = function (meshesOrMinMaxVector) {\n var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;\n return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);\n };\n /**\n * Merge the array of meshes into a single mesh for performance reasons.\n * @param {Array} meshes - The vertices source. They should all be of the same material. Entries can empty\n * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes\n * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.\n * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.\n * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.\n */\n Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {\n if (disposeSource === void 0) { disposeSource = true; }\n var index;\n if (!allow32BitsIndices) {\n var totalVertices = 0;\n // Counting vertices\n for (index = 0; index < meshes.length; index++) {\n if (meshes[index]) {\n totalVertices += meshes[index].getTotalVertices();\n if (totalVertices > 65536) {\n BABYLON.Tools.Warn(\"Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices\");\n return null;\n }\n }\n }\n }\n // Merge\n var vertexData = null;\n var otherVertexData;\n var indiceArray = new Array();\n var source = null;\n for (index = 0; index < meshes.length; index++) {\n if (meshes[index]) {\n meshes[index].computeWorldMatrix(true);\n otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);\n otherVertexData.transform(meshes[index].getWorldMatrix());\n if (vertexData) {\n vertexData.merge(otherVertexData);\n }\n else {\n vertexData = otherVertexData;\n source = meshes[index];\n }\n if (subdivideWithSubMeshes) {\n indiceArray.push(meshes[index].getTotalIndices());\n }\n }\n }\n source = source;\n if (!meshSubclass) {\n meshSubclass = new Mesh(source.name + \"_merged\", source.getScene());\n }\n vertexData.applyToMesh(meshSubclass);\n // Setting properties\n meshSubclass.material = source.material;\n meshSubclass.checkCollisions = source.checkCollisions;\n // Cleaning\n if (disposeSource) {\n for (index = 0; index < meshes.length; index++) {\n if (meshes[index]) {\n meshes[index].dispose();\n }\n }\n }\n // Subdivide\n if (subdivideWithSubMeshes) {\n //-- removal of global submesh\n meshSubclass.releaseSubMeshes();\n index = 0;\n var offset = 0;\n //-- apply subdivision according to index table\n while (index < indiceArray.length) {\n BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);\n offset += indiceArray[index];\n index++;\n }\n }\n return meshSubclass;\n };\n // Consts\n Mesh._FRONTSIDE = 0;\n Mesh._BACKSIDE = 1;\n Mesh._DOUBLESIDE = 2;\n Mesh._DEFAULTSIDE = 0;\n Mesh._NO_CAP = 0;\n Mesh._CAP_START = 1;\n Mesh._CAP_END = 2;\n Mesh._CAP_ALL = 3;\n return Mesh;\n }(BABYLON.AbstractMesh));\n BABYLON.Mesh = Mesh;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.mesh.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var BaseSubMesh = /** @class */ (function () {\n function BaseSubMesh() {\n }\n Object.defineProperty(BaseSubMesh.prototype, \"effect\", {\n get: function () {\n return this._materialEffect;\n },\n enumerable: true,\n configurable: true\n });\n BaseSubMesh.prototype.setEffect = function (effect, defines) {\n if (defines === void 0) { defines = null; }\n if (this._materialEffect === effect) {\n if (!effect) {\n this._materialDefines = null;\n }\n return;\n }\n this._materialDefines = defines;\n this._materialEffect = effect;\n };\n return BaseSubMesh;\n }());\n BABYLON.BaseSubMesh = BaseSubMesh;\n var SubMesh = /** @class */ (function (_super) {\n __extends(SubMesh, _super);\n function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {\n if (createBoundingBox === void 0) { createBoundingBox = true; }\n var _this = _super.call(this) || this;\n _this.materialIndex = materialIndex;\n _this.verticesStart = verticesStart;\n _this.verticesCount = verticesCount;\n _this.indexStart = indexStart;\n _this.indexCount = indexCount;\n _this._renderId = 0;\n _this._mesh = mesh;\n _this._renderingMesh = renderingMesh || mesh;\n mesh.subMeshes.push(_this);\n _this._trianglePlanes = [];\n _this._id = mesh.subMeshes.length - 1;\n if (createBoundingBox) {\n _this.refreshBoundingInfo();\n mesh.computeWorldMatrix(true);\n }\n return _this;\n }\n SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {\n if (createBoundingBox === void 0) { createBoundingBox = true; }\n return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);\n };\n Object.defineProperty(SubMesh.prototype, \"IsGlobal\", {\n get: function () {\n return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the submesh BoudingInfo object.\n */\n SubMesh.prototype.getBoundingInfo = function () {\n if (this.IsGlobal) {\n return this._mesh.getBoundingInfo();\n }\n return this._boundingInfo;\n };\n /**\n * Sets the submesh BoundingInfo.\n * Return the SubMesh.\n */\n SubMesh.prototype.setBoundingInfo = function (boundingInfo) {\n this._boundingInfo = boundingInfo;\n return this;\n };\n /**\n * Returns the mesh of the current submesh.\n */\n SubMesh.prototype.getMesh = function () {\n return this._mesh;\n };\n /**\n * Returns the rendering mesh of the submesh.\n */\n SubMesh.prototype.getRenderingMesh = function () {\n return this._renderingMesh;\n };\n /**\n * Returns the submesh material.\n */\n SubMesh.prototype.getMaterial = function () {\n var rootMaterial = this._renderingMesh.material;\n if (rootMaterial === null || rootMaterial === undefined) {\n return this._mesh.getScene().defaultMaterial;\n }\n else if (rootMaterial.getSubMaterial) {\n var multiMaterial = rootMaterial;\n var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);\n if (this._currentMaterial !== effectiveMaterial) {\n this._currentMaterial = effectiveMaterial;\n this._materialDefines = null;\n }\n return effectiveMaterial;\n }\n return rootMaterial;\n };\n // Methods\n /**\n * Sets a new updated BoundingInfo object to the submesh.\n * Returns the SubMesh.\n */\n SubMesh.prototype.refreshBoundingInfo = function () {\n this._lastColliderWorldVertices = null;\n if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {\n return this;\n }\n var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!data) {\n this._boundingInfo = this._mesh.getBoundingInfo();\n return this;\n }\n var indices = this._renderingMesh.getIndices();\n var extend;\n //is this the only submesh?\n if (this.indexStart === 0 && this.indexCount === indices.length) {\n var boundingInfo = this._renderingMesh.getBoundingInfo();\n //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.\n extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };\n }\n else {\n extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);\n }\n this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);\n return this;\n };\n SubMesh.prototype._checkCollision = function (collider) {\n var boundingInfo = this.getBoundingInfo();\n return boundingInfo._checkCollision(collider);\n };\n /**\n * Updates the submesh BoundingInfo.\n * Returns the Submesh.\n */\n SubMesh.prototype.updateBoundingInfo = function (world) {\n var boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n this.refreshBoundingInfo();\n boundingInfo = this.getBoundingInfo();\n }\n boundingInfo.update(world);\n return this;\n };\n /**\n * True is the submesh bounding box intersects the frustum defined by the passed array of planes.\n * Boolean returned.\n */\n SubMesh.prototype.isInFrustum = function (frustumPlanes) {\n var boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return false;\n }\n return boundingInfo.isInFrustum(frustumPlanes);\n };\n /**\n * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.\n * Boolean returned.\n */\n SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {\n var boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return false;\n }\n return boundingInfo.isCompletelyInFrustum(frustumPlanes);\n };\n /**\n * Renders the submesh.\n * Returns it.\n */\n SubMesh.prototype.render = function (enableAlphaMode) {\n this._renderingMesh.render(this, enableAlphaMode);\n return this;\n };\n /**\n * Returns a new Index Buffer.\n * Type returned : WebGLBuffer.\n */\n SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {\n if (!this._linesIndexBuffer) {\n var linesIndices = [];\n for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {\n linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);\n }\n this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);\n this.linesIndexCount = linesIndices.length;\n }\n return this._linesIndexBuffer;\n };\n /**\n * True is the passed Ray intersects the submesh bounding box.\n * Boolean returned.\n */\n SubMesh.prototype.canIntersects = function (ray) {\n var boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return false;\n }\n return ray.intersectsBox(boundingInfo.boundingBox);\n };\n /**\n * Returns an object IntersectionInfo.\n */\n SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {\n var intersectInfo = null;\n var material = this.getMaterial();\n if (!material) {\n return null;\n }\n switch (material.fillMode) {\n case BABYLON.Material.PointListDrawMode:\n case BABYLON.Material.LineListDrawMode:\n case BABYLON.Material.LineLoopDrawMode:\n case BABYLON.Material.LineStripDrawMode:\n case BABYLON.Material.TriangleFanDrawMode:\n case BABYLON.Material.TriangleStripDrawMode:\n return null;\n }\n // LineMesh first as it's also a Mesh...\n if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {\n var lineMesh = this._mesh;\n // Line test\n for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {\n var p0 = positions[indices[index]];\n var p1 = positions[indices[index + 1]];\n var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);\n if (length < 0) {\n continue;\n }\n if (fastCheck || !intersectInfo || length < intersectInfo.distance) {\n intersectInfo = new BABYLON.IntersectionInfo(null, null, length);\n if (fastCheck) {\n break;\n }\n }\n }\n }\n else {\n // Triangles test\n for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {\n var p0 = positions[indices[index]];\n var p1 = positions[indices[index + 1]];\n var p2 = positions[indices[index + 2]];\n var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);\n if (currentIntersectInfo) {\n if (currentIntersectInfo.distance < 0) {\n continue;\n }\n if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {\n intersectInfo = currentIntersectInfo;\n intersectInfo.faceId = index / 3;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n }\n return intersectInfo;\n };\n SubMesh.prototype._rebuild = function () {\n if (this._linesIndexBuffer) {\n this._linesIndexBuffer = null;\n }\n };\n // Clone \n /**\n * Creates a new Submesh from the passed Mesh.\n */\n SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {\n var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);\n if (!this.IsGlobal) {\n var boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return result;\n }\n result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);\n }\n return result;\n };\n // Dispose\n /**\n * Disposes the Submesh.\n * Returns nothing.\n */\n SubMesh.prototype.dispose = function () {\n if (this._linesIndexBuffer) {\n this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);\n this._linesIndexBuffer = null;\n }\n // Remove from mesh\n var index = this._mesh.subMeshes.indexOf(this);\n this._mesh.subMeshes.splice(index, 1);\n };\n // Statics\n /**\n * Creates a new Submesh from the passed parameters :\n * - materialIndex (integer) : the index of the main mesh material.\n * - startIndex (integer) : the index where to start the copy in the mesh indices array.\n * - indexCount (integer) : the number of indices to copy then from the startIndex.\n * - mesh (Mesh) : the main mesh to create the submesh from.\n * - renderingMesh (optional Mesh) : rendering mesh.\n */\n SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {\n var minVertexIndex = Number.MAX_VALUE;\n var maxVertexIndex = -Number.MAX_VALUE;\n renderingMesh = (renderingMesh || mesh);\n var indices = renderingMesh.getIndices();\n for (var index = startIndex; index < startIndex + indexCount; index++) {\n var vertexIndex = indices[index];\n if (vertexIndex < minVertexIndex)\n minVertexIndex = vertexIndex;\n if (vertexIndex > maxVertexIndex)\n maxVertexIndex = vertexIndex;\n }\n return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);\n };\n return SubMesh;\n }(BaseSubMesh));\n BABYLON.SubMesh = SubMesh;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.subMesh.js.map\n\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Manages the defines for the Material\n */\n var MaterialDefines = /** @class */ (function () {\n function MaterialDefines() {\n this._isDirty = true;\n /** @hidden */\n this._areLightsDirty = true;\n /** @hidden */\n this._areAttributesDirty = true;\n /** @hidden */\n this._areTexturesDirty = true;\n /** @hidden */\n this._areFresnelDirty = true;\n /** @hidden */\n this._areMiscDirty = true;\n /** @hidden */\n this._areImageProcessingDirty = true;\n /** @hidden */\n this._normals = false;\n /** @hidden */\n this._uvs = false;\n /** @hidden */\n this._needNormals = false;\n /** @hidden */\n this._needUVs = false;\n }\n Object.defineProperty(MaterialDefines.prototype, \"isDirty\", {\n /**\n * Specifies if the material needs to be re-calculated\n */\n get: function () {\n return this._isDirty;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Marks the material to indicate that it has been re-calculated\n */\n MaterialDefines.prototype.markAsProcessed = function () {\n this._isDirty = false;\n this._areAttributesDirty = false;\n this._areTexturesDirty = false;\n this._areFresnelDirty = false;\n this._areLightsDirty = false;\n this._areMiscDirty = false;\n this._areImageProcessingDirty = false;\n };\n /**\n * Marks the material to indicate that it needs to be re-calculated\n */\n MaterialDefines.prototype.markAsUnprocessed = function () {\n this._isDirty = true;\n };\n /**\n * Marks the material to indicate all of its defines need to be re-calculated\n */\n MaterialDefines.prototype.markAllAsDirty = function () {\n this._areTexturesDirty = true;\n this._areAttributesDirty = true;\n this._areLightsDirty = true;\n this._areFresnelDirty = true;\n this._areMiscDirty = true;\n this._areImageProcessingDirty = true;\n this._isDirty = true;\n };\n /**\n * Marks the material to indicate that image processing needs to be re-calculated\n */\n MaterialDefines.prototype.markAsImageProcessingDirty = function () {\n this._areImageProcessingDirty = true;\n this._isDirty = true;\n };\n /**\n * Marks the material to indicate the lights need to be re-calculated\n */\n MaterialDefines.prototype.markAsLightDirty = function () {\n this._areLightsDirty = true;\n this._isDirty = true;\n };\n /**\n * Marks the attribute state as changed\n */\n MaterialDefines.prototype.markAsAttributesDirty = function () {\n this._areAttributesDirty = true;\n this._isDirty = true;\n };\n /**\n * Marks the texture state as changed\n */\n MaterialDefines.prototype.markAsTexturesDirty = function () {\n this._areTexturesDirty = true;\n this._isDirty = true;\n };\n /**\n * Marks the fresnel state as changed\n */\n MaterialDefines.prototype.markAsFresnelDirty = function () {\n this._areFresnelDirty = true;\n this._isDirty = true;\n };\n /**\n * Marks the misc state as changed\n */\n MaterialDefines.prototype.markAsMiscDirty = function () {\n this._areMiscDirty = true;\n this._isDirty = true;\n };\n /**\n * Rebuilds the material defines\n */\n MaterialDefines.prototype.rebuild = function () {\n if (this._keys) {\n delete this._keys;\n }\n this._keys = [];\n for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {\n var key = _a[_i];\n if (key[0] === \"_\") {\n continue;\n }\n this._keys.push(key);\n }\n };\n /**\n * Specifies if two material defines are equal\n * @param other - A material define instance to compare to\n * @returns - Boolean indicating if the material defines are equal (true) or not (false)\n */\n MaterialDefines.prototype.isEqual = function (other) {\n if (this._keys.length !== other._keys.length) {\n return false;\n }\n for (var index = 0; index < this._keys.length; index++) {\n var prop = this._keys[index];\n if (this[prop] !== other[prop]) {\n return false;\n }\n }\n return true;\n };\n /**\n * Clones this instance's defines to another instance\n * @param other - material defines to clone values to\n */\n MaterialDefines.prototype.cloneTo = function (other) {\n if (this._keys.length !== other._keys.length) {\n other._keys = this._keys.slice(0);\n }\n for (var index = 0; index < this._keys.length; index++) {\n var prop = this._keys[index];\n other[prop] = this[prop];\n }\n };\n /**\n * Resets the material define values\n */\n MaterialDefines.prototype.reset = function () {\n for (var index = 0; index < this._keys.length; index++) {\n var prop = this._keys[index];\n var type = typeof this[prop];\n switch (type) {\n case \"number\":\n this[prop] = 0;\n break;\n case \"string\":\n this[prop] = \"\";\n break;\n default:\n this[prop] = false;\n break;\n }\n }\n };\n /**\n * Converts the material define values to a string\n * @returns - String of material define information\n */\n MaterialDefines.prototype.toString = function () {\n var result = \"\";\n for (var index = 0; index < this._keys.length; index++) {\n var prop = this._keys[index];\n var value = this[prop];\n var type = typeof value;\n switch (type) {\n case \"number\":\n case \"string\":\n result += \"#define \" + prop + \" \" + value + \"\\n\";\n break;\n default:\n if (value) {\n result += \"#define \" + prop + \"\\n\";\n }\n break;\n }\n }\n return result;\n };\n return MaterialDefines;\n }());\n BABYLON.MaterialDefines = MaterialDefines;\n /**\n * Base class for the main features of a material in Babylon.js\n */\n var Material = /** @class */ (function () {\n /**\n * Creates a material instance\n * @param name defines the name of the material\n * @param scene defines the scene to reference\n * @param doNotAdd specifies if the material should be added to the scene\n */\n function Material(name, scene, doNotAdd) {\n /**\n * Specifies if the ready state should be checked on each call\n */\n this.checkReadyOnEveryCall = false;\n /**\n * Specifies if the ready state should be checked once\n */\n this.checkReadyOnlyOnce = false;\n /**\n * The state of the material\n */\n this.state = \"\";\n /**\n * The alpha value of the material\n */\n this._alpha = 1.0;\n /**\n * Specifies if back face culling is enabled\n */\n this._backFaceCulling = true;\n /**\n * Specifies if the material should be serialized\n */\n this.doNotSerialize = false;\n /**\n * Specifies if the effect should be stored on sub meshes\n */\n this.storeEffectOnSubMeshes = false;\n /**\n * An event triggered when the material is disposed\n */\n this.onDisposeObservable = new BABYLON.Observable();\n /**\n * Stores the value of the alpha mode\n */\n this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;\n /**\n * Stores the state of the need depth pre-pass value\n */\n this._needDepthPrePass = false;\n /**\n * Specifies if depth writing should be disabled\n */\n this.disableDepthWrite = false;\n /**\n * Specifies if depth writing should be forced\n */\n this.forceDepthWrite = false;\n /**\n * Specifies if there should be a separate pass for culling\n */\n this.separateCullingPass = false;\n /**\n * Stores the state specifing if fog should be enabled\n */\n this._fogEnabled = true;\n /**\n * Stores the size of points\n */\n this.pointSize = 1.0;\n /**\n * Stores the z offset value\n */\n this.zOffset = 0;\n /**\n * Specifies if the material was previously ready\n */\n this._wasPreviouslyReady = false;\n /**\n * Stores the fill mode state\n */\n this._fillMode = Material.TriangleFillMode;\n this.name = name;\n this.id = name || BABYLON.Tools.RandomId();\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this.uniqueId = this._scene.getUniqueId();\n if (this._scene.useRightHandedSystem) {\n this.sideOrientation = Material.ClockWiseSideOrientation;\n }\n else {\n this.sideOrientation = Material.CounterClockWiseSideOrientation;\n }\n this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());\n this._useUBO = this.getScene().getEngine().supportsUniformBuffers;\n if (!doNotAdd) {\n this._scene.materials.push(this);\n }\n }\n Object.defineProperty(Material, \"TriangleFillMode\", {\n /**\n * Returns the triangle fill mode\n */\n get: function () {\n return Material._TriangleFillMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"WireFrameFillMode\", {\n /**\n * Returns the wireframe mode\n */\n get: function () {\n return Material._WireFrameFillMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"PointFillMode\", {\n /**\n * Returns the point fill mode\n */\n get: function () {\n return Material._PointFillMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"PointListDrawMode\", {\n /**\n * Returns the point list draw mode\n */\n get: function () {\n return Material._PointListDrawMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"LineListDrawMode\", {\n /**\n * Returns the line list draw mode\n */\n get: function () {\n return Material._LineListDrawMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"LineLoopDrawMode\", {\n /**\n * Returns the line loop draw mode\n */\n get: function () {\n return Material._LineLoopDrawMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"LineStripDrawMode\", {\n /**\n * Returns the line strip draw mode\n */\n get: function () {\n return Material._LineStripDrawMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"TriangleStripDrawMode\", {\n /**\n * Returns the triangle strip draw mode\n */\n get: function () {\n return Material._TriangleStripDrawMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"TriangleFanDrawMode\", {\n /**\n * Returns the triangle fan draw mode\n */\n get: function () {\n return Material._TriangleFanDrawMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"ClockWiseSideOrientation\", {\n /**\n * Returns the clock-wise side orientation\n */\n get: function () {\n return Material._ClockWiseSideOrientation;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"CounterClockWiseSideOrientation\", {\n /**\n * Returns the counter clock-wise side orientation\n */\n get: function () {\n return Material._CounterClockWiseSideOrientation;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"TextureDirtyFlag\", {\n /**\n * Returns the dirty texture flag value\n */\n get: function () {\n return Material._TextureDirtyFlag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"LightDirtyFlag\", {\n /**\n * Returns the dirty light flag value\n */\n get: function () {\n return Material._LightDirtyFlag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"FresnelDirtyFlag\", {\n /**\n * Returns the dirty fresnel flag value\n */\n get: function () {\n return Material._FresnelDirtyFlag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"AttributesDirtyFlag\", {\n /**\n * Returns the dirty attributes flag value\n */\n get: function () {\n return Material._AttributesDirtyFlag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material, \"MiscDirtyFlag\", {\n /**\n * Returns the dirty misc flag value\n */\n get: function () {\n return Material._MiscDirtyFlag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"alpha\", {\n /**\n * Gets the alpha value of the material\n */\n get: function () {\n return this._alpha;\n },\n /**\n * Sets the alpha value of the material\n */\n set: function (value) {\n if (this._alpha === value) {\n return;\n }\n this._alpha = value;\n this.markAsDirty(Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"backFaceCulling\", {\n /**\n * Gets the back-face culling state\n */\n get: function () {\n return this._backFaceCulling;\n },\n /**\n * Sets the back-face culling state\n */\n set: function (value) {\n if (this._backFaceCulling === value) {\n return;\n }\n this._backFaceCulling = value;\n this.markAsDirty(Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"onDispose\", {\n /**\n * Called during a dispose event\n */\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"onBindObservable\", {\n /**\n * An event triggered when the material is bound\n */\n get: function () {\n if (!this._onBindObservable) {\n this._onBindObservable = new BABYLON.Observable();\n }\n return this._onBindObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"onBind\", {\n /**\n * Called during a bind event\n */\n set: function (callback) {\n if (this._onBindObserver) {\n this.onBindObservable.remove(this._onBindObserver);\n }\n this._onBindObserver = this.onBindObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"onUnBindObservable\", {\n /**\n * An event triggered when the material is unbound\n */\n get: function () {\n if (!this._onUnBindObservable) {\n this._onUnBindObservable = new BABYLON.Observable();\n }\n return this._onUnBindObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"alphaMode\", {\n /**\n * Gets the value of the alpha mode\n */\n get: function () {\n return this._alphaMode;\n },\n /**\n * Sets the value of the alpha mode.\n *\n * | Value | Type | Description |\n * | --- | --- | --- |\n * | 0 | ALPHA_DISABLE | |\n * | 1 | ALPHA_ADD | |\n * | 2 | ALPHA_COMBINE | |\n * | 3 | ALPHA_SUBTRACT | |\n * | 4 | ALPHA_MULTIPLY | |\n * | 5 | ALPHA_MAXIMIZED | |\n * | 6 | ALPHA_ONEONE | |\n * | 7 | ALPHA_PREMULTIPLIED | |\n * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |\n * | 9 | ALPHA_INTERPOLATE | |\n * | 10 | ALPHA_SCREENMODE | |\n *\n */\n set: function (value) {\n if (this._alphaMode === value) {\n return;\n }\n this._alphaMode = value;\n this.markAsDirty(Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"needDepthPrePass\", {\n /**\n * Gets the depth pre-pass value\n */\n get: function () {\n return this._needDepthPrePass;\n },\n /**\n * Sets the need depth pre-pass value\n */\n set: function (value) {\n if (this._needDepthPrePass === value) {\n return;\n }\n this._needDepthPrePass = value;\n if (this._needDepthPrePass) {\n this.checkReadyOnEveryCall = true;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"fogEnabled\", {\n /**\n * Gets the value of the fog enabled state\n */\n get: function () {\n return this._fogEnabled;\n },\n /**\n * Sets the state for enabling fog\n */\n set: function (value) {\n if (this._fogEnabled === value) {\n return;\n }\n this._fogEnabled = value;\n this.markAsDirty(Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"wireframe\", {\n /**\n * Gets a value specifying if wireframe mode is enabled\n */\n get: function () {\n switch (this._fillMode) {\n case Material.WireFrameFillMode:\n case Material.LineListDrawMode:\n case Material.LineLoopDrawMode:\n case Material.LineStripDrawMode:\n return true;\n }\n return this._scene.forceWireframe;\n },\n /**\n * Sets the state of wireframe mode\n */\n set: function (value) {\n this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"pointsCloud\", {\n /**\n * Gets the value specifying if point clouds are enabled\n */\n get: function () {\n switch (this._fillMode) {\n case Material.PointFillMode:\n case Material.PointListDrawMode:\n return true;\n }\n return this._scene.forcePointsCloud;\n },\n /**\n * Sets the state of point cloud mode\n */\n set: function (value) {\n this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Material.prototype, \"fillMode\", {\n /**\n * Gets the material fill mode\n */\n get: function () {\n return this._fillMode;\n },\n /**\n * Sets the material fill mode\n */\n set: function (value) {\n if (this._fillMode === value) {\n return;\n }\n this._fillMode = value;\n this.markAsDirty(Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a string representation of the current material\n * @param fullDetails defines a boolean indicating which levels of logging is desired\n * @returns a string with material information\n */\n Material.prototype.toString = function (fullDetails) {\n var ret = \"Name: \" + this.name;\n if (fullDetails) {\n }\n return ret;\n };\n /**\n * Gets the class name of the material\n * @returns a string with the class name of the material\n */\n Material.prototype.getClassName = function () {\n return \"Material\";\n };\n Object.defineProperty(Material.prototype, \"isFrozen\", {\n /**\n * Specifies if updates for the material been locked\n */\n get: function () {\n return this.checkReadyOnlyOnce;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Locks updates for the material\n */\n Material.prototype.freeze = function () {\n this.checkReadyOnlyOnce = true;\n };\n /**\n * Unlocks updates for the material\n */\n Material.prototype.unfreeze = function () {\n this.checkReadyOnlyOnce = false;\n };\n /**\n * Specifies if the material is ready to be used\n * @param mesh defines the mesh to check\n * @param useInstances specifies if instances should be used\n * @returns a boolean indicating if the material is ready to be used\n */\n Material.prototype.isReady = function (mesh, useInstances) {\n return true;\n };\n /**\n * Specifies that the submesh is ready to be used\n * @param mesh defines the mesh to check\n * @param subMesh defines which submesh to check\n * @param useInstances specifies that instances should be used\n * @returns a boolean indicating that the submesh is ready or not\n */\n Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {\n return false;\n };\n /**\n * Returns the material effect\n * @returns the effect associated with the material\n */\n Material.prototype.getEffect = function () {\n return this._effect;\n };\n /**\n * Returns the current scene\n * @returns a Scene\n */\n Material.prototype.getScene = function () {\n return this._scene;\n };\n /**\n * Specifies if the material will require alpha blending\n * @returns a boolean specifying if alpha blending is needed\n */\n Material.prototype.needAlphaBlending = function () {\n return (this.alpha < 1.0);\n };\n /**\n * Specifies if the mesh will require alpha blending\n * @param mesh defines the mesh to check\n * @returns a boolean specifying if alpha blending is needed for the mesh\n */\n Material.prototype.needAlphaBlendingForMesh = function (mesh) {\n return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;\n };\n /**\n * Specifies if this material should be rendered in alpha test mode\n * @returns a boolean specifying if an alpha test is needed.\n */\n Material.prototype.needAlphaTesting = function () {\n return false;\n };\n /**\n * Gets the texture used for the alpha test\n * @returns the texture to use for alpha testing\n */\n Material.prototype.getAlphaTestTexture = function () {\n return null;\n };\n /**\n * Marks the material to indicate that it needs to be re-calculated\n */\n Material.prototype.markDirty = function () {\n this._wasPreviouslyReady = false;\n };\n /** @hidden */\n Material.prototype._preBind = function (effect, overrideOrientation) {\n if (overrideOrientation === void 0) { overrideOrientation = null; }\n var engine = this._scene.getEngine();\n var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;\n var reverse = orientation === Material.ClockWiseSideOrientation;\n engine.enableEffect(effect ? effect : this._effect);\n engine.setState(this.backFaceCulling, this.zOffset, false, reverse);\n return reverse;\n };\n /**\n * Binds the material to the mesh\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh to bind the material to\n */\n Material.prototype.bind = function (world, mesh) {\n };\n /**\n * Binds the submesh to the material\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh containing the submesh\n * @param subMesh defines the submesh to bind the material to\n */\n Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {\n };\n /**\n * Binds the world matrix to the material\n * @param world defines the world transformation matrix\n */\n Material.prototype.bindOnlyWorldMatrix = function (world) {\n };\n /**\n * Binds the scene's uniform buffer to the effect.\n * @param effect defines the effect to bind to the scene uniform buffer\n * @param sceneUbo defines the uniform buffer storing scene data\n */\n Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {\n sceneUbo.bindToEffect(effect, \"Scene\");\n };\n /**\n * Binds the view matrix to the effect\n * @param effect defines the effect to bind the view matrix to\n */\n Material.prototype.bindView = function (effect) {\n if (!this._useUBO) {\n effect.setMatrix(\"view\", this.getScene().getViewMatrix());\n }\n else {\n this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());\n }\n };\n /**\n * Binds the view projection matrix to the effect\n * @param effect defines the effect to bind the view projection matrix to\n */\n Material.prototype.bindViewProjection = function (effect) {\n if (!this._useUBO) {\n effect.setMatrix(\"viewProjection\", this.getScene().getTransformMatrix());\n }\n else {\n this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());\n }\n };\n /**\n * Specifies if material alpha testing should be turned on for the mesh\n * @param mesh defines the mesh to check\n */\n Material.prototype._shouldTurnAlphaTestOn = function (mesh) {\n return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());\n };\n /**\n * Processes to execute after binding the material to a mesh\n * @param mesh defines the rendered mesh\n */\n Material.prototype._afterBind = function (mesh) {\n this._scene._cachedMaterial = this;\n if (mesh) {\n this._scene._cachedVisibility = mesh.visibility;\n }\n else {\n this._scene._cachedVisibility = 1;\n }\n if (this._onBindObservable && mesh) {\n this._onBindObservable.notifyObservers(mesh);\n }\n if (this.disableDepthWrite) {\n var engine = this._scene.getEngine();\n this._cachedDepthWriteState = engine.getDepthWrite();\n engine.setDepthWrite(false);\n }\n };\n /**\n * Unbinds the material from the mesh\n */\n Material.prototype.unbind = function () {\n if (this._onUnBindObservable) {\n this._onUnBindObservable.notifyObservers(this);\n }\n if (this.disableDepthWrite) {\n var engine = this._scene.getEngine();\n engine.setDepthWrite(this._cachedDepthWriteState);\n }\n };\n /**\n * Gets the active textures from the material\n * @returns an array of textures\n */\n Material.prototype.getActiveTextures = function () {\n return [];\n };\n /**\n * Specifies if the material uses a texture\n * @param texture defines the texture to check against the material\n * @returns a boolean specifying if the material uses the texture\n */\n Material.prototype.hasTexture = function (texture) {\n return false;\n };\n /**\n * Makes a duplicate of the material, and gives it a new name\n * @param name defines the new name for the duplicated material\n * @returns the cloned material\n */\n Material.prototype.clone = function (name) {\n return null;\n };\n /**\n * Gets the meshes bound to the material\n * @returns an array of meshes bound to the material\n */\n Material.prototype.getBindedMeshes = function () {\n var result = new Array();\n for (var index = 0; index < this._scene.meshes.length; index++) {\n var mesh = this._scene.meshes[index];\n if (mesh.material === this) {\n result.push(mesh);\n }\n }\n return result;\n };\n /**\n * Force shader compilation\n * @param mesh defines the mesh associated with this material\n * @param onCompiled defines a function to execute once the material is compiled\n * @param options defines the options to configure the compilation\n */\n Material.prototype.forceCompilation = function (mesh, onCompiled, options) {\n var _this = this;\n var localOptions = __assign({ clipPlane: false }, options);\n var subMesh = new BABYLON.BaseSubMesh();\n var scene = this.getScene();\n var checkReady = function () {\n if (!_this._scene || !_this._scene.getEngine()) {\n return;\n }\n if (subMesh._materialDefines) {\n subMesh._materialDefines._renderId = -1;\n }\n var clipPlaneState = scene.clipPlane;\n if (localOptions.clipPlane) {\n scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);\n }\n if (_this.storeEffectOnSubMeshes) {\n if (_this.isReadyForSubMesh(mesh, subMesh)) {\n if (onCompiled) {\n onCompiled(_this);\n }\n }\n else {\n setTimeout(checkReady, 16);\n }\n }\n else {\n if (_this.isReady(mesh)) {\n if (onCompiled) {\n onCompiled(_this);\n }\n }\n else {\n setTimeout(checkReady, 16);\n }\n }\n if (localOptions.clipPlane) {\n scene.clipPlane = clipPlaneState;\n }\n };\n checkReady();\n };\n /**\n * Force shader compilation\n * @param mesh defines the mesh that will use this material\n * @param options defines additional options for compiling the shaders\n * @returns a promise that resolves when the compilation completes\n */\n Material.prototype.forceCompilationAsync = function (mesh, options) {\n var _this = this;\n return new Promise(function (resolve) {\n _this.forceCompilation(mesh, function () {\n resolve();\n }, options);\n });\n };\n /**\n * Marks a define in the material to indicate that it needs to be re-computed\n * @param flag defines a flag used to determine which parts of the material have to be marked as dirty\n */\n Material.prototype.markAsDirty = function (flag) {\n if (flag & Material.TextureDirtyFlag) {\n this._markAllSubMeshesAsTexturesDirty();\n }\n if (flag & Material.LightDirtyFlag) {\n this._markAllSubMeshesAsLightsDirty();\n }\n if (flag & Material.FresnelDirtyFlag) {\n this._markAllSubMeshesAsFresnelDirty();\n }\n if (flag & Material.AttributesDirtyFlag) {\n this._markAllSubMeshesAsAttributesDirty();\n }\n if (flag & Material.MiscDirtyFlag) {\n this._markAllSubMeshesAsMiscDirty();\n }\n this.getScene().resetCachedMaterial();\n };\n /**\n * Marks all submeshes of a material to indicate that their material defines need to be re-calculated\n * @param func defines a function which checks material defines against the submeshes\n */\n Material.prototype._markAllSubMeshesAsDirty = function (func) {\n for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n if (!mesh.subMeshes) {\n continue;\n }\n for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {\n var subMesh = _c[_b];\n if (subMesh.getMaterial() !== this) {\n continue;\n }\n if (!subMesh._materialDefines) {\n continue;\n }\n func(subMesh._materialDefines);\n }\n }\n };\n /**\n * Indicates that image processing needs to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });\n };\n /**\n * Indicates that textures need to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsTexturesDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });\n };\n /**\n * Indicates that fresnel needs to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsFresnelDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });\n };\n /**\n * Indicates that fresnel and misc need to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) {\n defines.markAsFresnelDirty();\n defines.markAsMiscDirty();\n });\n };\n /**\n * Indicates that lights need to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsLightsDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });\n };\n /**\n * Indicates that attributes need to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsAttributesDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });\n };\n /**\n * Indicates that misc needs to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsMiscDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });\n };\n /**\n * Indicates that textures and misc need to be re-calculated for all submeshes\n */\n Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {\n this._markAllSubMeshesAsDirty(function (defines) {\n defines.markAsTexturesDirty();\n defines.markAsMiscDirty();\n });\n };\n /**\n * Disposes the material\n * @param forceDisposeEffect specifies if effects should be forcefully disposed\n * @param forceDisposeTextures specifies if textures should be forcefully disposed\n */\n Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {\n // Animations\n this.getScene().stopAnimation(this);\n this.getScene().freeProcessedMaterials();\n // Remove from scene\n var index = this._scene.materials.indexOf(this);\n if (index >= 0) {\n this._scene.materials.splice(index, 1);\n }\n // Remove from meshes\n for (index = 0; index < this._scene.meshes.length; index++) {\n var mesh = this._scene.meshes[index];\n if (mesh.material === this) {\n mesh.material = null;\n if (mesh.geometry) {\n var geometry = (mesh.geometry);\n if (this.storeEffectOnSubMeshes) {\n for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {\n var subMesh = _a[_i];\n geometry._releaseVertexArrayObject(subMesh._materialEffect);\n if (forceDisposeEffect && subMesh._materialEffect) {\n this._scene.getEngine()._releaseEffect(subMesh._materialEffect);\n }\n }\n }\n else {\n geometry._releaseVertexArrayObject(this._effect);\n }\n }\n }\n }\n this._uniformBuffer.dispose();\n // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect\n if (forceDisposeEffect && this._effect) {\n if (!this.storeEffectOnSubMeshes) {\n this._scene.getEngine()._releaseEffect(this._effect);\n }\n this._effect = null;\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n if (this._onBindObservable) {\n this._onBindObservable.clear();\n }\n if (this._onUnBindObservable) {\n this._onUnBindObservable.clear();\n }\n };\n /**\n * Serializes this material\n * @returns the serialized material object\n */\n Material.prototype.serialize = function () {\n return BABYLON.SerializationHelper.Serialize(this);\n };\n /**\n * Creates a MultiMaterial from parsed MultiMaterial data.\n * @param parsedMultiMaterial defines parsed MultiMaterial data.\n * @param scene defines the hosting scene\n * @returns a new MultiMaterial\n */\n Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {\n var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);\n multiMaterial.id = parsedMultiMaterial.id;\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);\n }\n for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {\n var subMatId = parsedMultiMaterial.materials[matIndex];\n if (subMatId) {\n multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));\n }\n else {\n multiMaterial.subMaterials.push(null);\n }\n }\n return multiMaterial;\n };\n /**\n * Creates a material from parsed material data\n * @param parsedMaterial defines parsed material data\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures\n * @returns a new material\n */\n Material.Parse = function (parsedMaterial, scene, rootUrl) {\n if (!parsedMaterial.customType || parsedMaterial.customType === \"BABYLON.StandardMaterial\") {\n return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);\n }\n if (parsedMaterial.customType === \"BABYLON.PBRMaterial\" && parsedMaterial.overloadedAlbedo) {\n parsedMaterial.customType = \"BABYLON.LegacyPBRMaterial\";\n if (!BABYLON.LegacyPBRMaterial) {\n BABYLON.Tools.Error(\"Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.\");\n return;\n }\n }\n var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);\n return materialType.Parse(parsedMaterial, scene, rootUrl);\n };\n // Triangle views\n Material._TriangleFillMode = 0;\n Material._WireFrameFillMode = 1;\n Material._PointFillMode = 2;\n // Draw modes\n Material._PointListDrawMode = 3;\n Material._LineListDrawMode = 4;\n Material._LineLoopDrawMode = 5;\n Material._LineStripDrawMode = 6;\n Material._TriangleStripDrawMode = 7;\n Material._TriangleFanDrawMode = 8;\n /**\n * Stores the clock-wise side orientation\n */\n Material._ClockWiseSideOrientation = 0;\n /**\n * Stores the counter clock-wise side orientation\n */\n Material._CounterClockWiseSideOrientation = 1;\n /**\n * The dirty texture flag value\n */\n Material._TextureDirtyFlag = 1;\n /**\n * The dirty light flag value\n */\n Material._LightDirtyFlag = 2;\n /**\n * The dirty fresnel flag value\n */\n Material._FresnelDirtyFlag = 4;\n /**\n * The dirty attribute flag value\n */\n Material._AttributesDirtyFlag = 8;\n /**\n * The dirty misc flag value\n */\n Material._MiscDirtyFlag = 16;\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"id\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"uniqueId\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"name\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"checkReadyOnEveryCall\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"checkReadyOnlyOnce\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"state\", void 0);\n __decorate([\n BABYLON.serialize(\"alpha\")\n ], Material.prototype, \"_alpha\", void 0);\n __decorate([\n BABYLON.serialize(\"backFaceCulling\")\n ], Material.prototype, \"_backFaceCulling\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"sideOrientation\", void 0);\n __decorate([\n BABYLON.serialize(\"alphaMode\")\n ], Material.prototype, \"_alphaMode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"_needDepthPrePass\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"disableDepthWrite\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"forceDepthWrite\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"separateCullingPass\", void 0);\n __decorate([\n BABYLON.serialize(\"fogEnabled\")\n ], Material.prototype, \"_fogEnabled\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"pointSize\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"zOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"wireframe\", null);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"pointsCloud\", null);\n __decorate([\n BABYLON.serialize()\n ], Material.prototype, \"fillMode\", null);\n return Material;\n }());\n BABYLON.Material = Material;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.material.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var UniformBuffer = /** @class */ (function () {\n /**\n * Uniform buffer objects.\n *\n * Handles blocks of uniform on the GPU.\n *\n * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.\n *\n * For more information, please refer to :\n * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object\n */\n function UniformBuffer(engine, data, dynamic) {\n this._engine = engine;\n this._noUBO = !engine.supportsUniformBuffers;\n this._dynamic = dynamic;\n this._data = data || [];\n this._uniformLocations = {};\n this._uniformSizes = {};\n this._uniformLocationPointer = 0;\n this._needSync = false;\n if (this._noUBO) {\n this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;\n this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;\n this.updateFloat = this._updateFloatForEffect;\n this.updateFloat2 = this._updateFloat2ForEffect;\n this.updateFloat3 = this._updateFloat3ForEffect;\n this.updateFloat4 = this._updateFloat4ForEffect;\n this.updateMatrix = this._updateMatrixForEffect;\n this.updateVector3 = this._updateVector3ForEffect;\n this.updateVector4 = this._updateVector4ForEffect;\n this.updateColor3 = this._updateColor3ForEffect;\n this.updateColor4 = this._updateColor4ForEffect;\n }\n else {\n this._engine._uniformBuffers.push(this);\n this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;\n this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;\n this.updateFloat = this._updateFloatForUniform;\n this.updateFloat2 = this._updateFloat2ForUniform;\n this.updateFloat3 = this._updateFloat3ForUniform;\n this.updateFloat4 = this._updateFloat4ForUniform;\n this.updateMatrix = this._updateMatrixForUniform;\n this.updateVector3 = this._updateVector3ForUniform;\n this.updateVector4 = this._updateVector4ForUniform;\n this.updateColor3 = this._updateColor3ForUniform;\n this.updateColor4 = this._updateColor4ForUniform;\n }\n }\n Object.defineProperty(UniformBuffer.prototype, \"useUbo\", {\n // Properties\n /**\n * Indicates if the buffer is using the WebGL2 UBO implementation,\n * or just falling back on setUniformXXX calls.\n */\n get: function () {\n return !this._noUBO;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(UniformBuffer.prototype, \"isSync\", {\n /**\n * Indicates if the WebGL underlying uniform buffer is in sync\n * with the javascript cache data.\n */\n get: function () {\n return !this._needSync;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Indicates if the WebGL underlying uniform buffer is dynamic.\n * Also, a dynamic UniformBuffer will disable cache verification and always\n * update the underlying WebGL uniform buffer to the GPU.\n */\n UniformBuffer.prototype.isDynamic = function () {\n return this._dynamic !== undefined;\n };\n /**\n * The data cache on JS side.\n */\n UniformBuffer.prototype.getData = function () {\n return this._bufferData;\n };\n /**\n * The underlying WebGL Uniform buffer.\n */\n UniformBuffer.prototype.getBuffer = function () {\n return this._buffer;\n };\n /**\n * std140 layout specifies how to align data within an UBO structure.\n * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159\n * for specs.\n */\n UniformBuffer.prototype._fillAlignment = function (size) {\n // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components\n // and 4x4 matrices\n // TODO : change if other types are used\n var alignment;\n if (size <= 2) {\n alignment = size;\n }\n else {\n alignment = 4;\n }\n if ((this._uniformLocationPointer % alignment) !== 0) {\n var oldPointer = this._uniformLocationPointer;\n this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);\n var diff = this._uniformLocationPointer - oldPointer;\n for (var i = 0; i < diff; i++) {\n this._data.push(0);\n }\n }\n };\n /**\n * Adds an uniform in the buffer.\n * Warning : the subsequents calls of this function must be in the same order as declared in the shader\n * for the layout to be correct !\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {number|number[]} size Data size, or data directly.\n */\n UniformBuffer.prototype.addUniform = function (name, size) {\n if (this._noUBO) {\n return;\n }\n if (this._uniformLocations[name] !== undefined) {\n // Already existing uniform\n return;\n }\n // This function must be called in the order of the shader layout !\n // size can be the size of the uniform, or data directly\n var data;\n if (size instanceof Array) {\n data = size;\n size = data.length;\n }\n else {\n size = size;\n data = [];\n // Fill with zeros\n for (var i = 0; i < size; i++) {\n data.push(0);\n }\n }\n this._fillAlignment(size);\n this._uniformSizes[name] = size;\n this._uniformLocations[name] = this._uniformLocationPointer;\n this._uniformLocationPointer += size;\n for (var i = 0; i < size; i++) {\n this._data.push(data[i]);\n }\n this._needSync = true;\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {Matrix} mat A 4x4 matrix.\n */\n UniformBuffer.prototype.addMatrix = function (name, mat) {\n this.addUniform(name, Array.prototype.slice.call(mat.toArray()));\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {number} x\n * @param {number} y\n */\n UniformBuffer.prototype.addFloat2 = function (name, x, y) {\n var temp = [x, y];\n this.addUniform(name, temp);\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {number} x\n * @param {number} y\n * @param {number} z\n */\n UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {\n var temp = [x, y, z];\n this.addUniform(name, temp);\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {Color3} color\n */\n UniformBuffer.prototype.addColor3 = function (name, color) {\n var temp = new Array();\n color.toArray(temp);\n this.addUniform(name, temp);\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {Color3} color\n * @param {number} alpha\n */\n UniformBuffer.prototype.addColor4 = function (name, color, alpha) {\n var temp = new Array();\n color.toArray(temp);\n temp.push(alpha);\n this.addUniform(name, temp);\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n * @param {Vector3} vector\n */\n UniformBuffer.prototype.addVector3 = function (name, vector) {\n var temp = new Array();\n vector.toArray(temp);\n this.addUniform(name, temp);\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n */\n UniformBuffer.prototype.addMatrix3x3 = function (name) {\n this.addUniform(name, 12);\n };\n /**\n * Wrapper for addUniform.\n * @param {string} name Name of the uniform, as used in the uniform block in the shader.\n */\n UniformBuffer.prototype.addMatrix2x2 = function (name) {\n this.addUniform(name, 8);\n };\n /**\n * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.\n */\n UniformBuffer.prototype.create = function () {\n if (this._noUBO) {\n return;\n }\n if (this._buffer) {\n return; // nothing to do\n }\n // See spec, alignment must be filled as a vec4\n this._fillAlignment(4);\n this._bufferData = new Float32Array(this._data);\n this._rebuild();\n this._needSync = true;\n };\n UniformBuffer.prototype._rebuild = function () {\n if (this._noUBO) {\n return;\n }\n if (this._dynamic) {\n this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);\n }\n else {\n this._buffer = this._engine.createUniformBuffer(this._bufferData);\n }\n };\n /**\n * Updates the WebGL Uniform Buffer on the GPU.\n * If the `dynamic` flag is set to true, no cache comparison is done.\n * Otherwise, the buffer will be updated only if the cache differs.\n */\n UniformBuffer.prototype.update = function () {\n if (!this._buffer) {\n this.create();\n return;\n }\n if (!this._dynamic && !this._needSync) {\n return;\n }\n this._engine.updateUniformBuffer(this._buffer, this._bufferData);\n this._needSync = false;\n };\n /**\n * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.\n * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.\n * @param {number[]|Float32Array} data Flattened data\n * @param {number} size Size of the data.\n */\n UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {\n var location = this._uniformLocations[uniformName];\n if (location === undefined) {\n if (this._buffer) {\n // Cannot add an uniform if the buffer is already created\n BABYLON.Tools.Error(\"Cannot add an uniform after UBO has been created.\");\n return;\n }\n this.addUniform(uniformName, size);\n location = this._uniformLocations[uniformName];\n }\n if (!this._buffer) {\n this.create();\n }\n if (!this._dynamic) {\n // Cache for static uniform buffers\n var changed = false;\n for (var i = 0; i < size; i++) {\n if (this._bufferData[location + i] !== data[i]) {\n changed = true;\n this._bufferData[location + i] = data[i];\n }\n }\n this._needSync = this._needSync || changed;\n }\n else {\n // No cache for dynamic\n for (var i = 0; i < size; i++) {\n this._bufferData[location + i] = data[i];\n }\n }\n };\n // Update methods\n UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {\n // To match std140, matrix must be realigned\n for (var i = 0; i < 3; i++) {\n UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];\n UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];\n UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];\n UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;\n }\n this.updateUniform(name, UniformBuffer._tempBuffer, 12);\n };\n UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {\n this._currentEffect.setMatrix3x3(name, matrix);\n };\n UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {\n this._currentEffect.setMatrix2x2(name, matrix);\n };\n UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {\n // To match std140, matrix must be realigned\n for (var i = 0; i < 2; i++) {\n UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];\n UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];\n UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;\n UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;\n }\n this.updateUniform(name, UniformBuffer._tempBuffer, 8);\n };\n UniformBuffer.prototype._updateFloatForEffect = function (name, x) {\n this._currentEffect.setFloat(name, x);\n };\n UniformBuffer.prototype._updateFloatForUniform = function (name, x) {\n UniformBuffer._tempBuffer[0] = x;\n this.updateUniform(name, UniformBuffer._tempBuffer, 1);\n };\n UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n this._currentEffect.setFloat2(name + suffix, x, y);\n };\n UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n UniformBuffer._tempBuffer[0] = x;\n UniformBuffer._tempBuffer[1] = y;\n this.updateUniform(name, UniformBuffer._tempBuffer, 2);\n };\n UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n this._currentEffect.setFloat3(name + suffix, x, y, z);\n };\n UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n UniformBuffer._tempBuffer[0] = x;\n UniformBuffer._tempBuffer[1] = y;\n UniformBuffer._tempBuffer[2] = z;\n this.updateUniform(name, UniformBuffer._tempBuffer, 3);\n };\n UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n this._currentEffect.setFloat4(name + suffix, x, y, z, w);\n };\n UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n UniformBuffer._tempBuffer[0] = x;\n UniformBuffer._tempBuffer[1] = y;\n UniformBuffer._tempBuffer[2] = z;\n UniformBuffer._tempBuffer[3] = w;\n this.updateUniform(name, UniformBuffer._tempBuffer, 4);\n };\n UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {\n this._currentEffect.setMatrix(name, mat);\n };\n UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {\n this.updateUniform(name, mat.toArray(), 16);\n };\n UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {\n this._currentEffect.setVector3(name, vector);\n };\n UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {\n vector.toArray(UniformBuffer._tempBuffer);\n this.updateUniform(name, UniformBuffer._tempBuffer, 3);\n };\n UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {\n this._currentEffect.setVector4(name, vector);\n };\n UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {\n vector.toArray(UniformBuffer._tempBuffer);\n this.updateUniform(name, UniformBuffer._tempBuffer, 4);\n };\n UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n this._currentEffect.setColor3(name + suffix, color);\n };\n UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n color.toArray(UniformBuffer._tempBuffer);\n this.updateUniform(name, UniformBuffer._tempBuffer, 3);\n };\n UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n this._currentEffect.setColor4(name + suffix, color, alpha);\n };\n UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {\n if (suffix === void 0) { suffix = \"\"; }\n color.toArray(UniformBuffer._tempBuffer);\n UniformBuffer._tempBuffer[3] = alpha;\n this.updateUniform(name, UniformBuffer._tempBuffer, 4);\n };\n /**\n * Sets a sampler uniform on the effect.\n * @param {string} name Name of the sampler.\n * @param {Texture} texture\n */\n UniformBuffer.prototype.setTexture = function (name, texture) {\n this._currentEffect.setTexture(name, texture);\n };\n /**\n * Directly updates the value of the uniform in the cache AND on the GPU.\n * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.\n * @param {number[]|Float32Array} data Flattened data\n */\n UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {\n this.updateUniform(uniformName, data, data.length);\n this.update();\n };\n /**\n * Binds this uniform buffer to an effect.\n * @param {Effect} effect\n * @param {string} name Name of the uniform block in the shader.\n */\n UniformBuffer.prototype.bindToEffect = function (effect, name) {\n this._currentEffect = effect;\n if (this._noUBO || !this._buffer) {\n return;\n }\n effect.bindUniformBuffer(this._buffer, name);\n };\n /**\n * Disposes the uniform buffer.\n */\n UniformBuffer.prototype.dispose = function () {\n if (this._noUBO) {\n return;\n }\n var index = this._engine._uniformBuffers.indexOf(this);\n if (index !== -1) {\n this._engine._uniformBuffers.splice(index, 1);\n }\n if (!this._buffer) {\n return;\n }\n if (this._engine._releaseBuffer(this._buffer)) {\n this._buffer = null;\n }\n };\n // Pool for avoiding memory leaks\n UniformBuffer._MAX_UNIFORM_SIZE = 256;\n UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);\n return UniformBuffer;\n }());\n BABYLON.UniformBuffer = UniformBuffer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.uniformBuffer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance\n */\n var VertexData = /** @class */ (function () {\n function VertexData() {\n }\n /**\n * Uses the passed data array to set the set the values for the specified kind of data\n * @param data a linear array of floating numbers\n * @param kind the type of data that is being set, eg positions, colors etc\n */\n VertexData.prototype.set = function (data, kind) {\n switch (kind) {\n case BABYLON.VertexBuffer.PositionKind:\n this.positions = data;\n break;\n case BABYLON.VertexBuffer.NormalKind:\n this.normals = data;\n break;\n case BABYLON.VertexBuffer.TangentKind:\n this.tangents = data;\n break;\n case BABYLON.VertexBuffer.UVKind:\n this.uvs = data;\n break;\n case BABYLON.VertexBuffer.UV2Kind:\n this.uvs2 = data;\n break;\n case BABYLON.VertexBuffer.UV3Kind:\n this.uvs3 = data;\n break;\n case BABYLON.VertexBuffer.UV4Kind:\n this.uvs4 = data;\n break;\n case BABYLON.VertexBuffer.UV5Kind:\n this.uvs5 = data;\n break;\n case BABYLON.VertexBuffer.UV6Kind:\n this.uvs6 = data;\n break;\n case BABYLON.VertexBuffer.ColorKind:\n this.colors = data;\n break;\n case BABYLON.VertexBuffer.MatricesIndicesKind:\n this.matricesIndices = data;\n break;\n case BABYLON.VertexBuffer.MatricesWeightsKind:\n this.matricesWeights = data;\n break;\n case BABYLON.VertexBuffer.MatricesIndicesExtraKind:\n this.matricesIndicesExtra = data;\n break;\n case BABYLON.VertexBuffer.MatricesWeightsExtraKind:\n this.matricesWeightsExtra = data;\n break;\n }\n };\n /**\n * Associates the vertexData to the passed Mesh.\n * Sets it as updatable or not (default `false`)\n * @param mesh the mesh the vertexData is applied to\n * @param updatable when used and having the value true allows new data to update the vertexData\n * @returns the VertexData\n */\n VertexData.prototype.applyToMesh = function (mesh, updatable) {\n this._applyTo(mesh, updatable);\n return this;\n };\n /**\n * Associates the vertexData to the passed Geometry.\n * Sets it as updatable or not (default `false`)\n * @param geometry the geometry the vertexData is applied to\n * @param updatable when used and having the value true allows new data to update the vertexData\n * @returns VertexData\n */\n VertexData.prototype.applyToGeometry = function (geometry, updatable) {\n this._applyTo(geometry, updatable);\n return this;\n };\n /**\n * Updates the associated mesh\n * @param mesh the mesh to be updated\n * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false\n * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false\n * @returns VertexData\n */\n VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {\n this._update(mesh);\n return this;\n };\n /**\n * Updates the associated geometry\n * @param geometry the geometry to be updated\n * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false\n * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false\n * @returns VertexData.\n */\n VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {\n this._update(geometry);\n return this;\n };\n VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {\n if (updatable === void 0) { updatable = false; }\n if (this.positions) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);\n }\n if (this.normals) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);\n }\n if (this.tangents) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);\n }\n if (this.uvs) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);\n }\n if (this.uvs2) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);\n }\n if (this.uvs3) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);\n }\n if (this.uvs4) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);\n }\n if (this.uvs5) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);\n }\n if (this.uvs6) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);\n }\n if (this.colors) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);\n }\n if (this.matricesIndices) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);\n }\n if (this.matricesWeights) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);\n }\n if (this.matricesIndicesExtra) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);\n }\n if (this.matricesWeightsExtra) {\n meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);\n }\n if (this.indices) {\n meshOrGeometry.setIndices(this.indices, null, updatable);\n }\n else {\n meshOrGeometry.setIndices([], null);\n }\n return this;\n };\n VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {\n if (this.positions) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);\n }\n if (this.normals) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);\n }\n if (this.tangents) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);\n }\n if (this.uvs) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);\n }\n if (this.uvs2) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);\n }\n if (this.uvs3) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);\n }\n if (this.uvs4) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);\n }\n if (this.uvs5) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);\n }\n if (this.uvs6) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);\n }\n if (this.colors) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);\n }\n if (this.matricesIndices) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);\n }\n if (this.matricesWeights) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);\n }\n if (this.matricesIndicesExtra) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);\n }\n if (this.matricesWeightsExtra) {\n meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);\n }\n if (this.indices) {\n meshOrGeometry.setIndices(this.indices, null);\n }\n return this;\n };\n /**\n * Transforms each position and each normal of the vertexData according to the passed Matrix\n * @param matrix the transforming matrix\n * @returns the VertexData\n */\n VertexData.prototype.transform = function (matrix) {\n var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;\n var transformed = BABYLON.Vector3.Zero();\n var index;\n if (this.positions) {\n var position = BABYLON.Vector3.Zero();\n for (index = 0; index < this.positions.length; index += 3) {\n BABYLON.Vector3.FromArrayToRef(this.positions, index, position);\n BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);\n this.positions[index] = transformed.x;\n this.positions[index + 1] = transformed.y;\n this.positions[index + 2] = transformed.z;\n }\n }\n if (this.normals) {\n var normal = BABYLON.Vector3.Zero();\n for (index = 0; index < this.normals.length; index += 3) {\n BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);\n BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);\n this.normals[index] = transformed.x;\n this.normals[index + 1] = transformed.y;\n this.normals[index + 2] = transformed.z;\n }\n }\n if (this.tangents) {\n var tangent = BABYLON.Vector4.Zero();\n var tangentTransformed = BABYLON.Vector4.Zero();\n for (index = 0; index < this.tangents.length; index += 4) {\n BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);\n BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);\n this.tangents[index] = tangentTransformed.x;\n this.tangents[index + 1] = tangentTransformed.y;\n this.tangents[index + 2] = tangentTransformed.z;\n this.tangents[index + 3] = tangentTransformed.w;\n }\n }\n if (flip && this.indices) {\n for (index = 0; index < this.indices.length; index += 3) {\n var tmp = this.indices[index + 1];\n this.indices[index + 1] = this.indices[index + 2];\n this.indices[index + 2] = tmp;\n }\n }\n return this;\n };\n /**\n * Merges the passed VertexData into the current one\n * @param other the VertexData to be merged into the current one\n * @returns the modified VertexData\n */\n VertexData.prototype.merge = function (other) {\n this._validate();\n other._validate();\n if (!this.normals !== !other.normals ||\n !this.tangents !== !other.tangents ||\n !this.uvs !== !other.uvs ||\n !this.uvs2 !== !other.uvs2 ||\n !this.uvs3 !== !other.uvs3 ||\n !this.uvs4 !== !other.uvs4 ||\n !this.uvs5 !== !other.uvs5 ||\n !this.uvs6 !== !other.uvs6 ||\n !this.colors !== !other.colors ||\n !this.matricesIndices !== !other.matricesIndices ||\n !this.matricesWeights !== !other.matricesWeights ||\n !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||\n !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {\n throw new Error(\"Cannot merge vertex data that do not have the same set of attributes\");\n }\n if (other.indices) {\n if (!this.indices) {\n this.indices = [];\n }\n var offset = this.positions ? this.positions.length / 3 : 0;\n for (var index = 0; index < other.indices.length; index++) {\n //TODO check type - if Int32Array | Uint32Array | Uint16Array!\n this.indices.push(other.indices[index] + offset);\n }\n }\n this.positions = this._mergeElement(this.positions, other.positions);\n this.normals = this._mergeElement(this.normals, other.normals);\n this.tangents = this._mergeElement(this.tangents, other.tangents);\n this.uvs = this._mergeElement(this.uvs, other.uvs);\n this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);\n this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);\n this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);\n this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);\n this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);\n this.colors = this._mergeElement(this.colors, other.colors);\n this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);\n this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);\n this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);\n this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);\n return this;\n };\n VertexData.prototype._mergeElement = function (source, other) {\n if (!source) {\n return other;\n }\n if (!other) {\n return source;\n }\n var len = other.length + source.length;\n var isSrcTypedArray = source instanceof Float32Array;\n var isOthTypedArray = other instanceof Float32Array;\n // use non-loop method when the source is Float32Array\n if (isSrcTypedArray) {\n var ret32 = new Float32Array(len);\n ret32.set(source);\n ret32.set(other, source.length);\n return ret32;\n // source is number[], when other is also use concat\n }\n else if (!isOthTypedArray) {\n return source.concat(other);\n // source is a number[], but other is a Float32Array, loop required\n }\n else {\n var ret = source.slice(0); // copy source to a separate array\n for (var i = 0, len = other.length; i < len; i++) {\n ret.push(other[i]);\n }\n return ret;\n }\n };\n VertexData.prototype._validate = function () {\n if (!this.positions) {\n throw new Error(\"Positions are required\");\n }\n var getElementCount = function (kind, values) {\n var stride = BABYLON.VertexBuffer.DeduceStride(kind);\n if ((values.length % stride) !== 0) {\n throw new Error(\"The \" + kind + \"s array count must be a multiple of \" + stride);\n }\n return values.length / stride;\n };\n var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);\n var validateElementCount = function (kind, values) {\n var elementCount = getElementCount(kind, values);\n if (elementCount !== positionsElementCount) {\n throw new Error(\"The \" + kind + \"s element count (\" + elementCount + \") does not match the positions count (\" + positionsElementCount + \")\");\n }\n };\n if (this.normals)\n validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);\n if (this.tangents)\n validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);\n if (this.uvs)\n validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);\n if (this.uvs2)\n validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);\n if (this.uvs3)\n validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);\n if (this.uvs4)\n validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);\n if (this.uvs5)\n validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);\n if (this.uvs6)\n validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);\n if (this.colors)\n validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);\n if (this.matricesIndices)\n validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);\n if (this.matricesWeights)\n validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);\n if (this.matricesIndicesExtra)\n validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);\n if (this.matricesWeightsExtra)\n validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);\n };\n /**\n * Serializes the VertexData\n * @returns a serialized object\n */\n VertexData.prototype.serialize = function () {\n var serializationObject = this.serialize();\n if (this.positions) {\n serializationObject.positions = this.positions;\n }\n if (this.normals) {\n serializationObject.normals = this.normals;\n }\n if (this.tangents) {\n serializationObject.tangents = this.tangents;\n }\n if (this.uvs) {\n serializationObject.uvs = this.uvs;\n }\n if (this.uvs2) {\n serializationObject.uvs2 = this.uvs2;\n }\n if (this.uvs3) {\n serializationObject.uvs3 = this.uvs3;\n }\n if (this.uvs4) {\n serializationObject.uvs4 = this.uvs4;\n }\n if (this.uvs5) {\n serializationObject.uvs5 = this.uvs5;\n }\n if (this.uvs6) {\n serializationObject.uvs6 = this.uvs6;\n }\n if (this.colors) {\n serializationObject.colors = this.colors;\n }\n if (this.matricesIndices) {\n serializationObject.matricesIndices = this.matricesIndices;\n serializationObject.matricesIndices._isExpanded = true;\n }\n if (this.matricesWeights) {\n serializationObject.matricesWeights = this.matricesWeights;\n }\n if (this.matricesIndicesExtra) {\n serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;\n serializationObject.matricesIndicesExtra._isExpanded = true;\n }\n if (this.matricesWeightsExtra) {\n serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;\n }\n serializationObject.indices = this.indices;\n return serializationObject;\n };\n // Statics\n /**\n * Extracts the vertexData from a mesh\n * @param mesh the mesh from which to extract the VertexData\n * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false\n * @param forceCopy indicating that the VertexData must be cloned, optional, default false\n * @returns the object VertexData associated to the passed mesh\n */\n VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {\n return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);\n };\n /**\n * Extracts the vertexData from the geometry\n * @param geometry the geometry from which to extract the VertexData\n * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false\n * @param forceCopy indicating that the VertexData must be cloned, optional, default false\n * @returns the object VertexData associated to the passed mesh\n */\n VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {\n return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);\n };\n VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {\n var result = new VertexData();\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {\n result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {\n result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {\n result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {\n result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {\n result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {\n result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {\n result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {\n result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {\n result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {\n result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {\n result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);\n }\n result.indices = meshOrGeometry.getIndices(copyWhenShared);\n return result;\n };\n /**\n * Creates the VertexData for a Ribbon\n * @param options an object used to set the following optional parameters for the ribbon, required but can be empty\n * * pathArray array of paths, each of which an array of successive Vector3\n * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false\n * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false\n * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false\n * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional\n * * colors a linear array, of length 4 * number of vertices, of custom color values, optional\n * @returns the VertexData of the ribbon\n */\n VertexData.CreateRibbon = function (options) {\n var pathArray = options.pathArray;\n var closeArray = options.closeArray || false;\n var closePath = options.closePath || false;\n var invertUV = options.invertUV || false;\n var defaultOffset = Math.floor(pathArray[0].length / 2);\n var offset = options.offset || defaultOffset;\n offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var customUV = options.uvs;\n var customColors = options.colors;\n var positions = [];\n var indices = [];\n var normals = [];\n var uvs = [];\n var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id\n var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray\n var uTotalDistance = []; // uTotalDistance[p] : total distance of path p\n var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray\n var minlg; // minimal length among all paths from pathArray\n var lg = []; // array of path lengths : nb of vertex per path\n var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number\n var p; // path iterator\n var i; // point iterator\n var j; // point iterator\n // if single path in pathArray\n if (pathArray.length < 2) {\n var ar1 = [];\n var ar2 = [];\n for (i = 0; i < pathArray[0].length - offset; i++) {\n ar1.push(pathArray[0][i]);\n ar2.push(pathArray[0][i + offset]);\n }\n pathArray = [ar1, ar2];\n }\n // positions and horizontal distances (u)\n var idc = 0;\n var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath\n var path;\n var l;\n minlg = pathArray[0].length;\n var vectlg;\n var dist;\n for (p = 0; p < pathArray.length; p++) {\n uTotalDistance[p] = 0;\n us[p] = [0];\n path = pathArray[p];\n l = path.length;\n minlg = (minlg < l) ? minlg : l;\n j = 0;\n while (j < l) {\n positions.push(path[j].x, path[j].y, path[j].z);\n if (j > 0) {\n vectlg = path[j].subtract(path[j - 1]).length();\n dist = vectlg + uTotalDistance[p];\n us[p].push(dist);\n uTotalDistance[p] = dist;\n }\n j++;\n }\n if (closePath) { // an extra hidden vertex is added in the \"positions\" array\n j--;\n positions.push(path[0].x, path[0].y, path[0].z);\n vectlg = path[j].subtract(path[0]).length();\n dist = vectlg + uTotalDistance[p];\n us[p].push(dist);\n uTotalDistance[p] = dist;\n }\n lg[p] = l + closePathCorr;\n idx[p] = idc;\n idc += (l + closePathCorr);\n }\n // vertical distances (v)\n var path1;\n var path2;\n var vertex1 = null;\n var vertex2 = null;\n for (i = 0; i < minlg + closePathCorr; i++) {\n vTotalDistance[i] = 0;\n vs[i] = [0];\n for (p = 0; p < pathArray.length - 1; p++) {\n path1 = pathArray[p];\n path2 = pathArray[p + 1];\n if (i === minlg) { // closePath\n vertex1 = path1[0];\n vertex2 = path2[0];\n }\n else {\n vertex1 = path1[i];\n vertex2 = path2[i];\n }\n vectlg = vertex2.subtract(vertex1).length();\n dist = vectlg + vTotalDistance[i];\n vs[i].push(dist);\n vTotalDistance[i] = dist;\n }\n if (closeArray && vertex2 && vertex1) {\n path1 = pathArray[p];\n path2 = pathArray[0];\n if (i === minlg) { // closePath\n vertex2 = path2[0];\n }\n vectlg = vertex2.subtract(vertex1).length();\n dist = vectlg + vTotalDistance[i];\n vTotalDistance[i] = dist;\n }\n }\n // uvs\n var u;\n var v;\n if (customUV) {\n for (p = 0; p < customUV.length; p++) {\n uvs.push(customUV[p].x, customUV[p].y);\n }\n }\n else {\n for (p = 0; p < pathArray.length; p++) {\n for (i = 0; i < minlg + closePathCorr; i++) {\n u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;\n v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;\n if (invertUV) {\n uvs.push(v, u);\n }\n else {\n uvs.push(u, v);\n }\n }\n }\n }\n // indices\n p = 0; // path index\n var pi = 0; // positions array index\n var l1 = lg[p] - 1; // path1 length\n var l2 = lg[p + 1] - 1; // path2 length\n var min = (l1 < l2) ? l1 : l2; // current path stop index\n var shft = idx[1] - idx[0]; // shift\n var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate\ton\n while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path\n // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise\n indices.push(pi, pi + shft, pi + 1);\n indices.push(pi + shft + 1, pi + 1, pi + shft);\n pi += 1;\n if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path\n p++;\n if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true\n shft = idx[0] - idx[p];\n l1 = lg[p] - 1;\n l2 = lg[0] - 1;\n }\n else {\n shft = idx[p + 1] - idx[p];\n l1 = lg[p] - 1;\n l2 = lg[p + 1] - 1;\n }\n pi = idx[p];\n min = (l1 < l2) ? l1 + pi : l2 + pi;\n }\n }\n // normals\n VertexData.ComputeNormals(positions, indices, normals);\n if (closePath) { // update both the first and last vertex normals to their average value\n var indexFirst = 0;\n var indexLast = 0;\n for (p = 0; p < pathArray.length; p++) {\n indexFirst = idx[p] * 3;\n if (p + 1 < pathArray.length) {\n indexLast = (idx[p + 1] - 1) * 3;\n }\n else {\n indexLast = normals.length - 3;\n }\n normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;\n normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;\n normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;\n normals[indexLast] = normals[indexFirst];\n normals[indexLast + 1] = normals[indexFirst + 1];\n normals[indexLast + 2] = normals[indexFirst + 2];\n }\n }\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Colors\n var colors = null;\n if (customColors) {\n colors = new Float32Array(customColors.length * 4);\n for (var c = 0; c < customColors.length; c++) {\n colors[c * 4] = customColors[c].r;\n colors[c * 4 + 1] = customColors[c].g;\n colors[c * 4 + 2] = customColors[c].b;\n colors[c * 4 + 3] = customColors[c].a;\n }\n }\n // Result\n var vertexData = new VertexData();\n var positions32 = new Float32Array(positions);\n var normals32 = new Float32Array(normals);\n var uvs32 = new Float32Array(uvs);\n vertexData.indices = indices;\n vertexData.positions = positions32;\n vertexData.normals = normals32;\n vertexData.uvs = uvs32;\n if (colors) {\n vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);\n }\n if (closePath) {\n vertexData._idx = idx;\n }\n return vertexData;\n };\n /**\n * Creates the VertexData for a box\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * size sets the width, height and depth of the box to the value of size, optional default 1\n * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size\n * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size\n * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size\n * * faceUV an array of 6 Vector4 elements used to set different images to each box side\n * * faceColors an array of 6 Color3 elements used to set different colors to each box side\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the box\n */\n VertexData.CreateBox = function (options) {\n var normalsSource = [\n new BABYLON.Vector3(0, 0, 1),\n new BABYLON.Vector3(0, 0, -1),\n new BABYLON.Vector3(1, 0, 0),\n new BABYLON.Vector3(-1, 0, 0),\n new BABYLON.Vector3(0, 1, 0),\n new BABYLON.Vector3(0, -1, 0)\n ];\n var indices = [];\n var positions = [];\n var normals = [];\n var uvs = [];\n var width = options.width || options.size || 1;\n var height = options.height || options.size || 1;\n var depth = options.depth || options.size || 1;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var faceUV = options.faceUV || new Array(6);\n var faceColors = options.faceColors;\n var colors = [];\n // default face colors and UV if undefined\n for (var f = 0; f < 6; f++) {\n if (faceUV[f] === undefined) {\n faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);\n }\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);\n }\n }\n var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);\n // Create each face in turn.\n for (var index = 0; index < normalsSource.length; index++) {\n var normal = normalsSource[index];\n // Get two vectors perpendicular to the face normal and to each other.\n var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);\n var side2 = BABYLON.Vector3.Cross(normal, side1);\n // Six indices (two triangles) per face.\n var verticesLength = positions.length / 3;\n indices.push(verticesLength);\n indices.push(verticesLength + 1);\n indices.push(verticesLength + 2);\n indices.push(verticesLength);\n indices.push(verticesLength + 2);\n indices.push(verticesLength + 3);\n // Four vertices per face.\n var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);\n positions.push(vertex.x, vertex.y, vertex.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(faceUV[index].z, faceUV[index].w);\n if (faceColors) {\n colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);\n }\n vertex = normal.subtract(side1).add(side2).multiply(scaleVector);\n positions.push(vertex.x, vertex.y, vertex.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(faceUV[index].x, faceUV[index].w);\n if (faceColors) {\n colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);\n }\n vertex = normal.add(side1).add(side2).multiply(scaleVector);\n positions.push(vertex.x, vertex.y, vertex.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(faceUV[index].x, faceUV[index].y);\n if (faceColors) {\n colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);\n }\n vertex = normal.add(side1).subtract(side2).multiply(scaleVector);\n positions.push(vertex.x, vertex.y, vertex.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(faceUV[index].z, faceUV[index].y);\n if (faceColors) {\n colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);\n }\n }\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors) {\n var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;\n vertexData.colors = totalColors;\n }\n return vertexData;\n };\n /**\n * Creates the VertexData for an ellipsoid, defaults to a sphere\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * segments sets the number of horizontal strips optional, default 32\n * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1\n * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter\n * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter\n * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter\n * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1\n * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the ellipsoid\n */\n VertexData.CreateSphere = function (options) {\n var segments = options.segments || 32;\n var diameterX = options.diameterX || options.diameter || 1;\n var diameterY = options.diameterY || options.diameter || 1;\n var diameterZ = options.diameterZ || options.diameter || 1;\n var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;\n var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);\n var totalZRotationSteps = 2 + segments;\n var totalYRotationSteps = 2 * totalZRotationSteps;\n var indices = [];\n var positions = [];\n var normals = [];\n var uvs = [];\n for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {\n var normalizedZ = zRotationStep / totalZRotationSteps;\n var angleZ = normalizedZ * Math.PI * slice;\n for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {\n var normalizedY = yRotationStep / totalYRotationSteps;\n var angleY = normalizedY * Math.PI * 2 * arc;\n var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);\n var rotationY = BABYLON.Matrix.RotationY(angleY);\n var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);\n var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);\n var vertex = complete.multiply(radius);\n var normal = complete.divide(radius).normalize();\n positions.push(vertex.x, vertex.y, vertex.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(normalizedY, normalizedZ);\n }\n if (zRotationStep > 0) {\n var verticesCount = positions.length / 3;\n for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {\n indices.push((firstIndex));\n indices.push((firstIndex + 1));\n indices.push(firstIndex + totalYRotationSteps + 1);\n indices.push((firstIndex + totalYRotationSteps + 1));\n indices.push((firstIndex + 1));\n indices.push((firstIndex + totalYRotationSteps + 2));\n }\n }\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData for a cylinder, cone or prism\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * height sets the height (y direction) of the cylinder, optional, default 2\n * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter\n * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter\n * * diameter sets the diameter of the top and bottom of the cone, optional default 1\n * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24\n * * subdivisions` the number of rings along the cylinder height, optional, default 1\n * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false\n * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the cylinder, cone or prism\n */\n VertexData.CreateCylinder = function (options) {\n var height = options.height || 2;\n var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;\n var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;\n var tessellation = options.tessellation || 24;\n var subdivisions = options.subdivisions || 1;\n var hasRings = options.hasRings ? true : false;\n var enclose = options.enclose ? true : false;\n var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var faceUV = options.faceUV || new Array(3);\n var faceColors = options.faceColors;\n // default face colors and UV if undefined\n var quadNb = (arc !== 1 && enclose) ? 2 : 0;\n var ringNb = (hasRings) ? subdivisions : 1;\n var surfaceNb = 2 + (1 + quadNb) * ringNb;\n var f;\n for (f = 0; f < surfaceNb; f++) {\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);\n }\n }\n for (f = 0; f < surfaceNb; f++) {\n if (faceUV && faceUV[f] === undefined) {\n faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);\n }\n }\n var indices = new Array();\n var positions = new Array();\n var normals = new Array();\n var uvs = new Array();\n var colors = new Array();\n var angle_step = Math.PI * 2 * arc / tessellation;\n var angle;\n var h;\n var radius;\n var tan = (diameterBottom - diameterTop) / 2 / height;\n var ringVertex = BABYLON.Vector3.Zero();\n var ringNormal = BABYLON.Vector3.Zero();\n var ringFirstVertex = BABYLON.Vector3.Zero();\n var ringFirstNormal = BABYLON.Vector3.Zero();\n var quadNormal = BABYLON.Vector3.Zero();\n var Y = BABYLON.Axis.Y;\n // positions, normals, uvs\n var i;\n var j;\n var r;\n var ringIdx = 1;\n var s = 1; // surface index\n var cs = 0;\n var v = 0;\n for (i = 0; i <= subdivisions; i++) {\n h = i / subdivisions;\n radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;\n ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;\n for (r = 0; r < ringIdx; r++) {\n if (hasRings) {\n s += r;\n }\n if (enclose) {\n s += 2 * r;\n }\n for (j = 0; j <= tessellation; j++) {\n angle = j * angle_step;\n // position\n ringVertex.x = Math.cos(-angle) * radius;\n ringVertex.y = -height / 2 + h * height;\n ringVertex.z = Math.sin(-angle) * radius;\n // normal\n if (diameterTop === 0 && i === subdivisions) {\n // if no top cap, reuse former normals\n ringNormal.x = normals[normals.length - (tessellation + 1) * 3];\n ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];\n ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];\n }\n else {\n ringNormal.x = ringVertex.x;\n ringNormal.z = ringVertex.z;\n ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;\n ringNormal.normalize();\n }\n // keep first ring vertex values for enclose\n if (j === 0) {\n ringFirstVertex.copyFrom(ringVertex);\n ringFirstNormal.copyFrom(ringNormal);\n }\n positions.push(ringVertex.x, ringVertex.y, ringVertex.z);\n normals.push(ringNormal.x, ringNormal.y, ringNormal.z);\n if (hasRings) {\n v = (cs !== s) ? faceUV[s].y : faceUV[s].w;\n }\n else {\n v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;\n }\n uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);\n if (faceColors) {\n colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);\n }\n }\n // if enclose, add four vertices and their dedicated normals\n if (arc !== 1 && enclose) {\n positions.push(ringVertex.x, ringVertex.y, ringVertex.z);\n positions.push(0, ringVertex.y, 0);\n positions.push(0, ringVertex.y, 0);\n positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);\n BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);\n quadNormal.normalize();\n normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);\n BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);\n quadNormal.normalize();\n normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);\n if (hasRings) {\n v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;\n }\n else {\n v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;\n }\n uvs.push(faceUV[s + 1].x, v);\n uvs.push(faceUV[s + 1].z, v);\n if (hasRings) {\n v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;\n }\n else {\n v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;\n }\n uvs.push(faceUV[s + 2].x, v);\n uvs.push(faceUV[s + 2].z, v);\n if (faceColors) {\n colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);\n colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);\n colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);\n colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);\n }\n }\n if (cs !== s) {\n cs = s;\n }\n }\n }\n // indices\n var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose\n var s;\n i = 0;\n for (s = 0; s < subdivisions; s++) {\n var i0 = 0;\n var i1 = 0;\n var i2 = 0;\n var i3 = 0;\n for (j = 0; j < tessellation; j++) {\n i0 = i * (e + 1) + j;\n i1 = (i + 1) * (e + 1) + j;\n i2 = i * (e + 1) + (j + 1);\n i3 = (i + 1) * (e + 1) + (j + 1);\n indices.push(i0, i1, i2);\n indices.push(i3, i2, i1);\n }\n if (arc !== 1 && enclose) { // if enclose, add two quads\n indices.push(i0 + 2, i1 + 2, i2 + 2);\n indices.push(i3 + 2, i2 + 2, i1 + 2);\n indices.push(i0 + 4, i1 + 4, i2 + 4);\n indices.push(i3 + 4, i2 + 4, i1 + 4);\n }\n i = (hasRings) ? (i + 2) : (i + 1);\n }\n // Caps\n var createCylinderCap = function (isTop) {\n var radius = isTop ? diameterTop / 2 : diameterBottom / 2;\n if (radius === 0) {\n return;\n }\n // Cap positions, normals & uvs\n var angle;\n var circleVector;\n var i;\n var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];\n var c = null;\n if (faceColors) {\n c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];\n }\n // cap center\n var vbase = positions.length / 3;\n var offset = isTop ? height / 2 : -height / 2;\n var center = new BABYLON.Vector3(0, offset, 0);\n positions.push(center.x, center.y, center.z);\n normals.push(0, isTop ? 1 : -1, 0);\n uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);\n if (c) {\n colors.push(c.r, c.g, c.b, c.a);\n }\n var textureScale = new BABYLON.Vector2(0.5, 0.5);\n for (i = 0; i <= tessellation; i++) {\n angle = Math.PI * 2 * i * arc / tessellation;\n var cos = Math.cos(-angle);\n var sin = Math.sin(-angle);\n circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);\n var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);\n positions.push(circleVector.x, circleVector.y, circleVector.z);\n normals.push(0, isTop ? 1 : -1, 0);\n uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);\n if (c) {\n colors.push(c.r, c.g, c.b, c.a);\n }\n }\n // Cap indices\n for (i = 0; i < tessellation; i++) {\n if (!isTop) {\n indices.push(vbase);\n indices.push(vbase + (i + 1));\n indices.push(vbase + (i + 2));\n }\n else {\n indices.push(vbase);\n indices.push(vbase + (i + 2));\n indices.push(vbase + (i + 1));\n }\n }\n };\n // add caps to geometry\n createCylinderCap(false);\n createCylinderCap(true);\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors) {\n vertexData.colors = colors;\n }\n return vertexData;\n };\n /**\n * Creates the VertexData for a torus\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * diameter the diameter of the torus, optional default 1\n * * thickness the diameter of the tube forming the torus, optional default 0.5\n * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the torus\n */\n VertexData.CreateTorus = function (options) {\n var indices = [];\n var positions = [];\n var normals = [];\n var uvs = [];\n var diameter = options.diameter || 1;\n var thickness = options.thickness || 0.5;\n var tessellation = options.tessellation || 16;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var stride = tessellation + 1;\n for (var i = 0; i <= tessellation; i++) {\n var u = i / tessellation;\n var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;\n var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));\n for (var j = 0; j <= tessellation; j++) {\n var v = 1 - j / tessellation;\n var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;\n var dx = Math.cos(innerAngle);\n var dy = Math.sin(innerAngle);\n // Create a vertex.\n var normal = new BABYLON.Vector3(dx, dy, 0);\n var position = normal.scale(thickness / 2);\n var textureCoordinate = new BABYLON.Vector2(u, v);\n position = BABYLON.Vector3.TransformCoordinates(position, transform);\n normal = BABYLON.Vector3.TransformNormal(normal, transform);\n positions.push(position.x, position.y, position.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(textureCoordinate.x, textureCoordinate.y);\n // And create indices for two triangles.\n var nextI = (i + 1) % stride;\n var nextJ = (j + 1) % stride;\n indices.push(i * stride + j);\n indices.push(i * stride + nextJ);\n indices.push(nextI * stride + j);\n indices.push(i * stride + nextJ);\n indices.push(nextI * stride + nextJ);\n indices.push(nextI * stride + j);\n }\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData of the LineSystem\n * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty\n * - lines an array of lines, each line being an array of successive Vector3\n * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point\n * @returns the VertexData of the LineSystem\n */\n VertexData.CreateLineSystem = function (options) {\n var indices = [];\n var positions = [];\n var lines = options.lines;\n var colors = options.colors;\n var vertexColors = [];\n var idx = 0;\n for (var l = 0; l < lines.length; l++) {\n var points = lines[l];\n for (var index = 0; index < points.length; index++) {\n positions.push(points[index].x, points[index].y, points[index].z);\n if (colors) {\n var color = colors[l];\n vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);\n }\n if (index > 0) {\n indices.push(idx - 1);\n indices.push(idx);\n }\n idx++;\n }\n }\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n if (colors) {\n vertexData.colors = vertexColors;\n }\n return vertexData;\n };\n /**\n * Create the VertexData for a DashedLines\n * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty\n * - points an array successive Vector3\n * - dashSize the size of the dashes relative to the dash number, optional, default 3\n * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1\n * - dashNb the intended total number of dashes, optional, default 200\n * @returns the VertexData for the DashedLines\n */\n VertexData.CreateDashedLines = function (options) {\n var dashSize = options.dashSize || 3;\n var gapSize = options.gapSize || 1;\n var dashNb = options.dashNb || 200;\n var points = options.points;\n var positions = new Array();\n var indices = new Array();\n var curvect = BABYLON.Vector3.Zero();\n var lg = 0;\n var nb = 0;\n var shft = 0;\n var dashshft = 0;\n var curshft = 0;\n var idx = 0;\n var i = 0;\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n lg += curvect.length();\n }\n shft = lg / dashNb;\n dashshft = dashSize * shft / (dashSize + gapSize);\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n nb = Math.floor(curvect.length() / shft);\n curvect.normalize();\n for (var j = 0; j < nb; j++) {\n curshft = shft * j;\n positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);\n positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);\n indices.push(idx, idx + 1);\n idx += 2;\n }\n }\n // Result\n var vertexData = new VertexData();\n vertexData.positions = positions;\n vertexData.indices = indices;\n return vertexData;\n };\n /**\n * Creates the VertexData for a Ground\n * @param options an object used to set the following optional parameters for the Ground, required but can be empty\n * - width the width (x direction) of the ground, optional, default 1\n * - height the height (z direction) of the ground, optional, default 1\n * - subdivisions the number of subdivisions per side, optional, default 1\n * @returns the VertexData of the Ground\n */\n VertexData.CreateGround = function (options) {\n var indices = [];\n var positions = [];\n var normals = [];\n var uvs = [];\n var row, col;\n var width = options.width || 1;\n var height = options.height || 1;\n var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;\n var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;\n for (row = 0; row <= subdivisionsY; row++) {\n for (col = 0; col <= subdivisionsX; col++) {\n var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));\n var normal = new BABYLON.Vector3(0, 1.0, 0);\n positions.push(position.x, position.y, position.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);\n }\n }\n for (row = 0; row < subdivisionsY; row++) {\n for (col = 0; col < subdivisionsX; col++) {\n indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));\n indices.push(col + 1 + row * (subdivisionsX + 1));\n indices.push(col + row * (subdivisionsX + 1));\n indices.push(col + (row + 1) * (subdivisionsX + 1));\n indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));\n indices.push(col + row * (subdivisionsX + 1));\n }\n }\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData for a TiledGround by subdividing the ground into tiles\n * @param options an object used to set the following optional parameters for the Ground, required but can be empty\n * * xmin the ground minimum X coordinate, optional, default -1\n * * zmin the ground minimum Z coordinate, optional, default -1\n * * xmax the ground maximum X coordinate, optional, default 1\n * * zmax the ground maximum Z coordinate, optional, default 1\n * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}\n * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}\n * @returns the VertexData of the TiledGround\n */\n VertexData.CreateTiledGround = function (options) {\n var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;\n var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;\n var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;\n var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;\n var subdivisions = options.subdivisions || { w: 1, h: 1 };\n var precision = options.precision || { w: 1, h: 1 };\n var indices = new Array();\n var positions = new Array();\n var normals = new Array();\n var uvs = new Array();\n var row, col, tileRow, tileCol;\n subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;\n subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;\n precision.w = (precision.w < 1) ? 1 : precision.w;\n precision.h = (precision.h < 1) ? 1 : precision.h;\n var tileSize = {\n 'w': (xmax - xmin) / subdivisions.w,\n 'h': (zmax - zmin) / subdivisions.h\n };\n function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {\n // Indices\n var base = positions.length / 3;\n var rowLength = precision.w + 1;\n for (row = 0; row < precision.h; row++) {\n for (col = 0; col < precision.w; col++) {\n var square = [\n base + col + row * rowLength,\n base + (col + 1) + row * rowLength,\n base + (col + 1) + (row + 1) * rowLength,\n base + col + (row + 1) * rowLength\n ];\n indices.push(square[1]);\n indices.push(square[2]);\n indices.push(square[3]);\n indices.push(square[0]);\n indices.push(square[1]);\n indices.push(square[3]);\n }\n }\n // Position, normals and uvs\n var position = BABYLON.Vector3.Zero();\n var normal = new BABYLON.Vector3(0, 1.0, 0);\n for (row = 0; row <= precision.h; row++) {\n position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;\n for (col = 0; col <= precision.w; col++) {\n position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;\n position.y = 0;\n positions.push(position.x, position.y, position.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(col / precision.w, row / precision.h);\n }\n }\n }\n for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {\n for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {\n applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);\n }\n }\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData of the Ground designed from a heightmap\n * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap\n * * width the width (x direction) of the ground\n * * height the height (z direction) of the ground\n * * subdivisions the number of subdivisions per side\n * * minHeight the minimum altitude on the ground, optional, default 0\n * * maxHeight the maximum altitude on the ground, optional default 1\n * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)\n * * buffer the array holding the image color data\n * * bufferWidth the width of image\n * * bufferHeight the height of image\n * @returns the VertexData of the Ground designed from a heightmap\n */\n VertexData.CreateGroundFromHeightMap = function (options) {\n var indices = [];\n var positions = [];\n var normals = [];\n var uvs = [];\n var row, col;\n var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);\n // Vertices\n for (row = 0; row <= options.subdivisions; row++) {\n for (col = 0; col <= options.subdivisions; col++) {\n var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));\n // Compute height\n var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;\n var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;\n var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;\n var r = options.buffer[pos] / 255.0;\n var g = options.buffer[pos + 1] / 255.0;\n var b = options.buffer[pos + 2] / 255.0;\n var gradient = r * filter.r + g * filter.g + b * filter.b;\n position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;\n // Add vertex\n positions.push(position.x, position.y, position.z);\n normals.push(0, 0, 0);\n uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);\n }\n }\n // Indices\n for (row = 0; row < options.subdivisions; row++) {\n for (col = 0; col < options.subdivisions; col++) {\n indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));\n indices.push(col + 1 + row * (options.subdivisions + 1));\n indices.push(col + row * (options.subdivisions + 1));\n indices.push(col + (row + 1) * (options.subdivisions + 1));\n indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));\n indices.push(col + row * (options.subdivisions + 1));\n }\n }\n // Normals\n VertexData.ComputeNormals(positions, indices, normals);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData for a Plane\n * @param options an object used to set the following optional parameters for the plane, required but can be empty\n * * size sets the width and height of the plane to the value of size, optional default 1\n * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size\n * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the box\n */\n VertexData.CreatePlane = function (options) {\n var indices = [];\n var positions = [];\n var normals = [];\n var uvs = [];\n var width = options.width || options.size || 1;\n var height = options.height || options.size || 1;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n // Vertices\n var halfWidth = width / 2.0;\n var halfHeight = height / 2.0;\n positions.push(-halfWidth, -halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(0.0, 0.0);\n positions.push(halfWidth, -halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(1.0, 0.0);\n positions.push(halfWidth, halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(1.0, 1.0);\n positions.push(-halfWidth, halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(0.0, 1.0);\n // Indices\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData of the Disc or regular Polygon\n * @param options an object used to set the following optional parameters for the disc, required but can be empty\n * * radius the radius of the disc, optional default 0.5\n * * tessellation the number of polygon sides, optional, default 64\n * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the box\n */\n VertexData.CreateDisc = function (options) {\n var positions = new Array();\n var indices = new Array();\n var normals = new Array();\n var uvs = new Array();\n var radius = options.radius || 0.5;\n var tessellation = options.tessellation || 64;\n var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n // positions and uvs\n positions.push(0, 0, 0); // disc center first\n uvs.push(0.5, 0.5);\n var theta = Math.PI * 2 * arc;\n var step = theta / tessellation;\n for (var a = 0; a < theta; a += step) {\n var x = Math.cos(a);\n var y = Math.sin(a);\n var u = (x + 1) / 2;\n var v = (1 - y) / 2;\n positions.push(radius * x, radius * y, 0);\n uvs.push(u, v);\n }\n if (arc === 1) {\n positions.push(positions[3], positions[4], positions[5]); // close the circle\n uvs.push(uvs[2], uvs[3]);\n }\n //indices\n var vertexNb = positions.length / 3;\n for (var i = 1; i < vertexNb - 1; i++) {\n indices.push(i + 1, 0, i);\n }\n // result\n VertexData.ComputeNormals(positions, indices, normals);\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n /**\n * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()\n * All parameters are provided by MeshBuilder.CreatePolygon as needed\n * @param polygon a mesh built from polygonTriangulation.build()\n * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the Polygon\n */\n VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {\n var faceUV = fUV || new Array(3);\n var faceColors = fColors;\n var colors = [];\n // default face colors and UV if undefined\n for (var f = 0; f < 3; f++) {\n if (faceUV[f] === undefined) {\n faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);\n }\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);\n }\n }\n var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);\n var indices = polygon.getIndices();\n // set face colours and textures\n var idx = 0;\n var face = 0;\n for (var index = 0; index < normals.length; index += 3) {\n //Edge Face no. 1\n if (Math.abs(normals[index + 1]) < 0.001) {\n face = 1;\n }\n //Top Face no. 0\n if (Math.abs(normals[index + 1] - 1) < 0.001) {\n face = 0;\n }\n //Bottom Face no. 2\n if (Math.abs(normals[index + 1] + 1) < 0.001) {\n face = 2;\n }\n idx = index / 3;\n uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;\n uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;\n if (faceColors) {\n colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);\n }\n }\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors) {\n var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;\n vertexData.colors = totalColors;\n }\n return vertexData;\n };\n /**\n * Creates the VertexData of the IcoSphere\n * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty\n * * radius the radius of the IcoSphere, optional default 1\n * * radiusX allows stretching in the x direction, optional, default radius\n * * radiusY allows stretching in the y direction, optional, default radius\n * * radiusZ allows stretching in the z direction, optional, default radius\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the IcoSphere\n */\n VertexData.CreateIcoSphere = function (options) {\n var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var radius = options.radius || 1;\n var flat = (options.flat === undefined) ? true : options.flat;\n var subdivisions = options.subdivisions || 4;\n var radiusX = options.radiusX || radius;\n var radiusY = options.radiusY || radius;\n var radiusZ = options.radiusZ || radius;\n var t = (1 + Math.sqrt(5)) / 2;\n // 12 vertex x,y,z\n var ico_vertices = [\n -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,\n 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,\n t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11\n ];\n // index of 3 vertex makes a face of icopshere\n var ico_indices = [\n 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,\n 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,\n 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,\n 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1\n ];\n // vertex for uv have aliased position, not for UV\n var vertices_unalias_id = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,\n // vertex alias\n 0,\n 2,\n 3,\n 3,\n 3,\n 4,\n 7,\n 8,\n 9,\n 9,\n 10,\n 11 // 23: B + 12\n ];\n // uv as integer step (not pixels !)\n var ico_vertexuv = [\n 5, 1, 3, 1, 6, 4, 0, 0,\n 5, 3, 4, 2, 2, 2, 4, 0,\n 2, 0, 1, 1, 6, 0, 6, 2,\n // vertex alias (for same vertex on different faces)\n 0, 4,\n 3, 3,\n 4, 4,\n 3, 1,\n 4, 2,\n 4, 4,\n 0, 2,\n 1, 1,\n 2, 2,\n 3, 3,\n 1, 3,\n 2, 4 // 23: B + 12\n ];\n // Vertices[0, 1, ...9, A, B] : position on UV plane\n // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)\n // First island of uv mapping\n // v = 4h 3+ 2\n // v = 3h 9+ 4\n // v = 2h 9+ 5 B\n // v = 1h 9 1 0\n // v = 0h 3 8 7 A\n // u = 0 1 2 3 4 5 6 *a\n // Second island of uv mapping\n // v = 4h 0+ B+ 4+\n // v = 3h A+ 2+\n // v = 2h 7+ 6 3+\n // v = 1h 8+ 3+\n // v = 0h\n // u = 0 1 2 3 4 5 6 *a\n // Face layout on texture UV mapping\n // ============\n // \\ 4 /\\ 16 / ======\n // \\ / \\ / /\\ 11 /\n // \\/ 7 \\/ / \\ /\n // ======= / 10 \\/\n // /\\ 17 /\\ =======\n // / \\ / \\ \\ 15 /\\\n // / 8 \\/ 12 \\ \\ / \\\n // ============ \\/ 6 \\\n // \\ 18 /\\ ============\n // \\ / \\ \\ 5 /\\ 0 /\n // \\/ 13 \\ \\ / \\ /\n // ======= \\/ 1 \\/\n // =============\n // /\\ 19 /\\ 2 /\\\n // / \\ / \\ / \\\n // / 14 \\/ 9 \\/ 3 \\\n // ===================\n // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97\n var ustep = 138 / 1024;\n var vstep = 239 / 1024;\n var uoffset = 60 / 1024;\n var voffset = 26 / 1024;\n // Second island should have margin, not to touch the first island\n // avoid any borderline artefact in pixel rounding\n var island_u_offset = -40 / 1024;\n var island_v_offset = +20 / 1024;\n // face is either island 0 or 1 :\n // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]\n var island = [\n 0, 0, 0, 0, 1,\n 0, 0, 1, 1, 0,\n 0, 0, 1, 1, 0,\n 0, 1, 1, 1, 0 // 15 - 19\n ];\n var indices = new Array();\n var positions = new Array();\n var normals = new Array();\n var uvs = new Array();\n var current_indice = 0;\n // prepare array of 3 vector (empty) (to be worked in place, shared for each face)\n var face_vertex_pos = new Array(3);\n var face_vertex_uv = new Array(3);\n var v012;\n for (v012 = 0; v012 < 3; v012++) {\n face_vertex_pos[v012] = BABYLON.Vector3.Zero();\n face_vertex_uv[v012] = BABYLON.Vector2.Zero();\n }\n // create all with normals\n for (var face = 0; face < 20; face++) {\n // 3 vertex per face\n for (v012 = 0; v012 < 3; v012++) {\n // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)\n var v_id = ico_indices[3 * face + v012];\n // vertex have 3D position (x,y,z)\n face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);\n // Normalize to get normal, then scale to radius\n face_vertex_pos[v012].normalize().scaleInPlace(radius);\n // uv Coordinates from vertex ID\n face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);\n }\n // Subdivide the face (interpolate pos, norm, uv)\n // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)\n // - norm is linear interpolation of vertex corner normal\n // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )\n // - uv is linear interpolation\n //\n // Topology is as below for sub-divide by 2\n // vertex shown as v0,v1,v2\n // interp index is i1 to progress in range [v0,v1[\n // interp index is i2 to progress in range [v0,v2[\n // face index as (i1,i2) for /\\ : (i1,i2),(i1+1,i2),(i1,i2+1)\n // and (i1,i2)' for \\/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)\n //\n //\n // i2 v2\n // ^ ^\n // / / \\\n // / / \\\n // / / \\\n // / / (0,1) \\\n // / #---------\\\n // / / \\ (0,0)'/ \\\n // / / \\ / \\\n // / / \\ / \\\n // / / (0,0) \\ / (1,0) \\\n // / #---------#---------\\\n // v0 v1\n //\n // --------------------> i1\n //\n // interp of (i1,i2):\n // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)\n // along i1 : lerp(x0,x1, i1/(S-i2))\n //\n // centroid of triangle is needed to get help normal computation\n // (c1,c2) are used for centroid location\n var interp_vertex = function (i1, i2, c1, c2) {\n // vertex is interpolated from\n // - face_vertex_pos[0..2]\n // - face_vertex_uv[0..2]\n var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);\n var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);\n var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));\n pos_interp.normalize();\n var vertex_normal;\n if (flat) {\n // in flat mode, recalculate normal as face centroid normal\n var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);\n var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);\n vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));\n }\n else {\n // in smooth mode, recalculate normal from each single vertex position\n vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);\n }\n // Vertex normal need correction due to X,Y,Z radius scaling\n vertex_normal.x /= radiusX;\n vertex_normal.y /= radiusY;\n vertex_normal.z /= radiusZ;\n vertex_normal.normalize();\n var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);\n var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);\n var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));\n positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);\n normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);\n uvs.push(uv_interp.x, uv_interp.y);\n // push each vertex has member of a face\n // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)\n indices.push(current_indice);\n current_indice++;\n };\n for (var i2 = 0; i2 < subdivisions; i2++) {\n for (var i1 = 0; i1 + i2 < subdivisions; i1++) {\n // face : (i1,i2) for /\\ :\n // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)\n interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);\n interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);\n interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);\n if (i1 + i2 + 1 < subdivisions) {\n // face : (i1,i2)' for \\/ :\n // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)\n interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);\n interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);\n interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);\n }\n }\n }\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html\n /**\n * Creates the VertexData for a Polyhedron\n * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty\n * * type provided types are:\n * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)\n * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)\n * * size the size of the IcoSphere, optional default 1\n * * sizeX allows stretching in the x direction, optional, default size\n * * sizeY allows stretching in the y direction, optional, default size\n * * sizeZ allows stretching in the z direction, optional, default size\n * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the Polyhedron\n */\n VertexData.CreatePolyhedron = function (options) {\n // provided polyhedron types :\n // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)\n // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)\n var polyhedra = [];\n polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };\n polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };\n polyhedra[2] = {\n vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],\n face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]\n };\n polyhedra[3] = {\n vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],\n face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]\n };\n polyhedra[4] = {\n vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],\n face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]\n };\n polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };\n polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };\n polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };\n polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };\n polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };\n polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };\n polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };\n polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };\n polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };\n polyhedra[14] = {\n vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],\n face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]\n };\n var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;\n var size = options.size;\n var sizeX = options.sizeX || size || 1;\n var sizeY = options.sizeY || size || 1;\n var sizeZ = options.sizeZ || size || 1;\n var data = options.custom || polyhedra[type];\n var nbfaces = data.face.length;\n var faceUV = options.faceUV || new Array(nbfaces);\n var faceColors = options.faceColors;\n var flat = (options.flat === undefined) ? true : options.flat;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n var positions = new Array();\n var indices = new Array();\n var normals = new Array();\n var uvs = new Array();\n var colors = new Array();\n var index = 0;\n var faceIdx = 0; // face cursor in the array \"indexes\"\n var indexes = new Array();\n var i = 0;\n var f = 0;\n var u, v, ang, x, y, tmp;\n // default face colors and UV if undefined\n if (flat) {\n for (f = 0; f < nbfaces; f++) {\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);\n }\n if (faceUV && faceUV[f] === undefined) {\n faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);\n }\n }\n }\n if (!flat) {\n for (i = 0; i < data.vertex.length; i++) {\n positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);\n uvs.push(0, 0);\n }\n for (f = 0; f < nbfaces; f++) {\n for (i = 0; i < data.face[f].length - 2; i++) {\n indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);\n }\n }\n }\n else {\n for (f = 0; f < nbfaces; f++) {\n var fl = data.face[f].length; // number of vertices of the current face\n ang = 2 * Math.PI / fl;\n x = 0.5 * Math.tan(ang / 2);\n y = 0.5;\n // positions, uvs, colors\n for (i = 0; i < fl; i++) {\n // positions\n positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);\n indexes.push(index);\n index++;\n // uvs\n u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);\n v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);\n uvs.push(u, v);\n tmp = x * Math.cos(ang) - y * Math.sin(ang);\n y = x * Math.sin(ang) + y * Math.cos(ang);\n x = tmp;\n // colors\n if (faceColors) {\n colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);\n }\n }\n // indices from indexes\n for (i = 0; i < fl - 2; i++) {\n indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);\n }\n faceIdx += fl;\n }\n }\n VertexData.ComputeNormals(positions, indices, normals);\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n var vertexData = new VertexData();\n vertexData.positions = positions;\n vertexData.indices = indices;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors && flat) {\n vertexData.colors = colors;\n }\n return vertexData;\n };\n // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473\n /**\n * Creates the VertexData for a TorusKnot\n * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty\n * * radius the radius of the torus knot, optional, default 2\n * * tube the thickness of the tube, optional, default 0.5\n * * radialSegments the number of sides on each tube segments, optional, default 32\n * * tubularSegments the number of tubes to decompose the knot into, optional, default 32\n * * p the number of windings around the z axis, optional, default 2\n * * q the number of windings around the x axis, optional, default 3\n * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the Torus Knot\n */\n VertexData.CreateTorusKnot = function (options) {\n var indices = new Array();\n var positions = new Array();\n var normals = new Array();\n var uvs = new Array();\n var radius = options.radius || 2;\n var tube = options.tube || 0.5;\n var radialSegments = options.radialSegments || 32;\n var tubularSegments = options.tubularSegments || 32;\n var p = options.p || 2;\n var q = options.q || 3;\n var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n // Helper\n var getPos = function (angle) {\n var cu = Math.cos(angle);\n var su = Math.sin(angle);\n var quOverP = q / p * angle;\n var cs = Math.cos(quOverP);\n var tx = radius * (2 + cs) * 0.5 * cu;\n var ty = radius * (2 + cs) * su * 0.5;\n var tz = radius * Math.sin(quOverP) * 0.5;\n return new BABYLON.Vector3(tx, ty, tz);\n };\n // Vertices\n var i;\n var j;\n for (i = 0; i <= radialSegments; i++) {\n var modI = i % radialSegments;\n var u = modI / radialSegments * 2 * p * Math.PI;\n var p1 = getPos(u);\n var p2 = getPos(u + 0.01);\n var tang = p2.subtract(p1);\n var n = p2.add(p1);\n var bitan = BABYLON.Vector3.Cross(tang, n);\n n = BABYLON.Vector3.Cross(bitan, tang);\n bitan.normalize();\n n.normalize();\n for (j = 0; j < tubularSegments; j++) {\n var modJ = j % tubularSegments;\n var v = modJ / tubularSegments * 2 * Math.PI;\n var cx = -tube * Math.cos(v);\n var cy = tube * Math.sin(v);\n positions.push(p1.x + cx * n.x + cy * bitan.x);\n positions.push(p1.y + cx * n.y + cy * bitan.y);\n positions.push(p1.z + cx * n.z + cy * bitan.z);\n uvs.push(i / radialSegments);\n uvs.push(j / tubularSegments);\n }\n }\n for (i = 0; i < radialSegments; i++) {\n for (j = 0; j < tubularSegments; j++) {\n var jNext = (j + 1) % tubularSegments;\n var a = i * tubularSegments + j;\n var b = (i + 1) * tubularSegments + j;\n var c = (i + 1) * tubularSegments + jNext;\n var d = i * tubularSegments + jNext;\n indices.push(d);\n indices.push(b);\n indices.push(a);\n indices.push(d);\n indices.push(c);\n indices.push(b);\n }\n }\n // Normals\n VertexData.ComputeNormals(positions, indices, normals);\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n var vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n };\n // Tools\n /**\n * Compute normals for given positions and indices\n * @param positions an array of vertex positions, [...., x, y, z, ......]\n * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]\n * @param normals an array of vertex normals, [...., x, y, z, ......]\n * @param options an object used to set the following optional parameters for the TorusKnot, optional\n * * facetNormals : optional array of facet normals (vector3)\n * * facetPositions : optional array of facet positions (vector3)\n * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation\n * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation\n * * bInfo : optional bounding info, required for facetPartitioning computation\n * * bbSize : optional bounding box size data, required for facetPartitioning computation\n * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation\n * * useRightHandedSystem: optional boolean to for right handed system computation\n * * depthSort : optional boolean to enable the facet depth sort computation\n * * distanceTo : optional Vector3 to compute the facet depth from this location\n * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location\n */\n VertexData.ComputeNormals = function (positions, indices, normals, options) {\n // temporary scalar variables\n var index = 0; // facet index \n var p1p2x = 0.0; // p1p2 vector x coordinate\n var p1p2y = 0.0; // p1p2 vector y coordinate\n var p1p2z = 0.0; // p1p2 vector z coordinate\n var p3p2x = 0.0; // p3p2 vector x coordinate\n var p3p2y = 0.0; // p3p2 vector y coordinate\n var p3p2z = 0.0; // p3p2 vector z coordinate\n var faceNormalx = 0.0; // facet normal x coordinate\n var faceNormaly = 0.0; // facet normal y coordinate\n var faceNormalz = 0.0; // facet normal z coordinate\n var length = 0.0; // facet normal length before normalization\n var v1x = 0; // vector1 x index in the positions array\n var v1y = 0; // vector1 y index in the positions array\n var v1z = 0; // vector1 z index in the positions array\n var v2x = 0; // vector2 x index in the positions array\n var v2y = 0; // vector2 y index in the positions array\n var v2z = 0; // vector2 z index in the positions array\n var v3x = 0; // vector3 x index in the positions array\n var v3y = 0; // vector3 y index in the positions array\n var v3z = 0; // vector3 z index in the positions array\n var computeFacetNormals = false;\n var computeFacetPositions = false;\n var computeFacetPartitioning = false;\n var computeDepthSort = false;\n var faceNormalSign = 1;\n var ratio = 0;\n var distanceTo = null;\n if (options) {\n computeFacetNormals = (options.facetNormals) ? true : false;\n computeFacetPositions = (options.facetPositions) ? true : false;\n computeFacetPartitioning = (options.facetPartitioning) ? true : false;\n faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;\n ratio = options.ratio || 0;\n computeDepthSort = (options.depthSort) ? true : false;\n distanceTo = (options.distanceTo);\n if (computeDepthSort) {\n if (distanceTo === undefined) {\n distanceTo = BABYLON.Vector3.Zero();\n }\n var depthSortedFacets = options.depthSortedFacets;\n }\n }\n // facetPartitioning reinit if needed\n var xSubRatio = 0;\n var ySubRatio = 0;\n var zSubRatio = 0;\n var subSq = 0;\n if (computeFacetPartitioning && options && options.bbSize) {\n var ox = 0; // X partitioning index for facet position\n var oy = 0; // Y partinioning index for facet position\n var oz = 0; // Z partinioning index for facet position\n var b1x = 0; // X partitioning index for facet v1 vertex\n var b1y = 0; // Y partitioning index for facet v1 vertex\n var b1z = 0; // z partitioning index for facet v1 vertex\n var b2x = 0; // X partitioning index for facet v2 vertex\n var b2y = 0; // Y partitioning index for facet v2 vertex\n var b2z = 0; // Z partitioning index for facet v2 vertex\n var b3x = 0; // X partitioning index for facet v3 vertex\n var b3y = 0; // Y partitioning index for facet v3 vertex\n var b3z = 0; // Z partitioning index for facet v3 vertex\n var block_idx_o = 0; // facet barycenter block index\n var block_idx_v1 = 0; // v1 vertex block index\n var block_idx_v2 = 0; // v2 vertex block index\n var block_idx_v3 = 0; // v3 vertex block index \n var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;\n bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;\n xSubRatio = options.subDiv.X * ratio / options.bbSize.x;\n ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;\n zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;\n subSq = options.subDiv.max * options.subDiv.max;\n options.facetPartitioning.length = 0;\n }\n // reset the normals\n for (index = 0; index < positions.length; index++) {\n normals[index] = 0.0;\n }\n // Loop : 1 indice triplet = 1 facet\n var nbFaces = (indices.length / 3) | 0;\n for (index = 0; index < nbFaces; index++) {\n // get the indexes of the coordinates of each vertex of the facet\n v1x = indices[index * 3] * 3;\n v1y = v1x + 1;\n v1z = v1x + 2;\n v2x = indices[index * 3 + 1] * 3;\n v2y = v2x + 1;\n v2z = v2x + 2;\n v3x = indices[index * 3 + 2] * 3;\n v3y = v3x + 1;\n v3z = v3x + 2;\n p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2\n p1p2y = positions[v1y] - positions[v2y];\n p1p2z = positions[v1z] - positions[v2z];\n p3p2x = positions[v3x] - positions[v2x];\n p3p2y = positions[v3y] - positions[v2y];\n p3p2z = positions[v3z] - positions[v2z];\n // compute the face normal with the cross product\n faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);\n faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);\n faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);\n // normalize this normal and store it in the array facetData\n length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);\n length = (length === 0) ? 1.0 : length;\n faceNormalx /= length;\n faceNormaly /= length;\n faceNormalz /= length;\n if (computeFacetNormals && options) {\n options.facetNormals[index].x = faceNormalx;\n options.facetNormals[index].y = faceNormaly;\n options.facetNormals[index].z = faceNormalz;\n }\n if (computeFacetPositions && options) {\n // compute and the facet barycenter coordinates in the array facetPositions \n options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;\n options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;\n options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;\n }\n if (computeFacetPartitioning && options) {\n // store the facet indexes in arrays in the main facetPartitioning array :\n // compute each facet vertex (+ facet barycenter) index in the partiniong array\n ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);\n oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);\n oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);\n b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);\n b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);\n b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);\n b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);\n b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);\n b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);\n b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);\n b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);\n b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);\n block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;\n block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;\n block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;\n block_idx_o = ox + options.subDiv.max * oy + subSq * oz;\n options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();\n options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();\n options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();\n options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();\n // push each facet index in each block containing the vertex\n options.facetPartitioning[block_idx_v1].push(index);\n if (block_idx_v2 != block_idx_v1) {\n options.facetPartitioning[block_idx_v2].push(index);\n }\n if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {\n options.facetPartitioning[block_idx_v3].push(index);\n }\n if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {\n options.facetPartitioning[block_idx_o].push(index);\n }\n }\n if (computeDepthSort && options && options.facetPositions) {\n var dsf = depthSortedFacets[index];\n dsf.ind = index * 3;\n dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);\n }\n // compute the normals anyway\n normals[v1x] += faceNormalx; // accumulate all the normals per face\n normals[v1y] += faceNormaly;\n normals[v1z] += faceNormalz;\n normals[v2x] += faceNormalx;\n normals[v2y] += faceNormaly;\n normals[v2z] += faceNormalz;\n normals[v3x] += faceNormalx;\n normals[v3y] += faceNormaly;\n normals[v3z] += faceNormalz;\n }\n // last normalization of each normal\n for (index = 0; index < normals.length / 3; index++) {\n faceNormalx = normals[index * 3];\n faceNormaly = normals[index * 3 + 1];\n faceNormalz = normals[index * 3 + 2];\n length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);\n length = (length === 0) ? 1.0 : length;\n faceNormalx /= length;\n faceNormaly /= length;\n faceNormalz /= length;\n normals[index * 3] = faceNormalx;\n normals[index * 3 + 1] = faceNormaly;\n normals[index * 3 + 2] = faceNormalz;\n }\n };\n VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {\n var li = indices.length;\n var ln = normals.length;\n var i;\n var n;\n sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;\n switch (sideOrientation) {\n case BABYLON.Mesh.FRONTSIDE:\n // nothing changed\n break;\n case BABYLON.Mesh.BACKSIDE:\n var tmp;\n // indices\n for (i = 0; i < li; i += 3) {\n tmp = indices[i];\n indices[i] = indices[i + 2];\n indices[i + 2] = tmp;\n }\n // normals\n for (n = 0; n < ln; n++) {\n normals[n] = -normals[n];\n }\n break;\n case BABYLON.Mesh.DOUBLESIDE:\n // positions\n var lp = positions.length;\n var l = lp / 3;\n for (var p = 0; p < lp; p++) {\n positions[lp + p] = positions[p];\n }\n // indices\n for (i = 0; i < li; i += 3) {\n indices[i + li] = indices[i + 2] + l;\n indices[i + 1 + li] = indices[i + 1] + l;\n indices[i + 2 + li] = indices[i] + l;\n }\n // normals\n for (n = 0; n < ln; n++) {\n normals[ln + n] = -normals[n];\n }\n // uvs\n var lu = uvs.length;\n var u = 0;\n for (u = 0; u < lu; u++) {\n uvs[u + lu] = uvs[u];\n }\n frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);\n backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);\n u = 0;\n for (i = 0; i < lu / 2; i++) {\n uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];\n uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];\n uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];\n uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];\n u += 2;\n }\n break;\n }\n };\n /**\n * Applies VertexData created from the imported parameters to the geometry\n * @param parsedVertexData the parsed data from an imported file\n * @param geometry the geometry to apply the VertexData to\n */\n VertexData.ImportVertexData = function (parsedVertexData, geometry) {\n var vertexData = new VertexData();\n // positions\n var positions = parsedVertexData.positions;\n if (positions) {\n vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);\n }\n // normals\n var normals = parsedVertexData.normals;\n if (normals) {\n vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);\n }\n // tangents\n var tangents = parsedVertexData.tangents;\n if (tangents) {\n vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);\n }\n // uvs\n var uvs = parsedVertexData.uvs;\n if (uvs) {\n vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);\n }\n // uv2s\n var uv2s = parsedVertexData.uv2s;\n if (uv2s) {\n vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);\n }\n // uv3s\n var uv3s = parsedVertexData.uv3s;\n if (uv3s) {\n vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);\n }\n // uv4s\n var uv4s = parsedVertexData.uv4s;\n if (uv4s) {\n vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);\n }\n // uv5s\n var uv5s = parsedVertexData.uv5s;\n if (uv5s) {\n vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);\n }\n // uv6s\n var uv6s = parsedVertexData.uv6s;\n if (uv6s) {\n vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);\n }\n // colors\n var colors = parsedVertexData.colors;\n if (colors) {\n vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);\n }\n // matricesIndices\n var matricesIndices = parsedVertexData.matricesIndices;\n if (matricesIndices) {\n vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);\n }\n // matricesWeights\n var matricesWeights = parsedVertexData.matricesWeights;\n if (matricesWeights) {\n vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);\n }\n // indices\n var indices = parsedVertexData.indices;\n if (indices) {\n vertexData.indices = indices;\n }\n geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);\n };\n return VertexData;\n }());\n BABYLON.VertexData = VertexData;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.mesh.vertexData.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to store geometry data (vertex buffers + index buffer)\n */\n var Geometry = /** @class */ (function () {\n /**\n * Creates a new geometry\n * @param id defines the unique ID\n * @param scene defines the hosting scene\n * @param vertexData defines the {BABYLON.VertexData} used to get geometry data\n * @param updatable defines if geometry must be updatable (false by default)\n * @param mesh defines the mesh that will be associated with the geometry\n */\n function Geometry(id, scene, vertexData, updatable, mesh) {\n if (updatable === void 0) { updatable = false; }\n if (mesh === void 0) { mesh = null; }\n /**\n * Gets the delay loading state of the geometry (none by default which means not delayed)\n */\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;\n this._totalVertices = 0;\n this._isDisposed = false;\n this._indexBufferIsUpdatable = false;\n this.id = id;\n this._engine = scene.getEngine();\n this._meshes = [];\n this._scene = scene;\n //Init vertex buffer cache\n this._vertexBuffers = {};\n this._indices = [];\n this._updatable = updatable;\n // vertexData\n if (vertexData) {\n this.setAllVerticesData(vertexData, updatable);\n }\n else {\n this._totalVertices = 0;\n this._indices = [];\n }\n if (this._engine.getCaps().vertexArrayObject) {\n this._vertexArrayObjects = {};\n }\n // applyToMesh\n if (mesh) {\n if (mesh.getClassName() === \"LinesMesh\") {\n this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);\n this._updateExtend();\n }\n this.applyToMesh(mesh);\n mesh.computeWorldMatrix(true);\n }\n }\n Object.defineProperty(Geometry.prototype, \"boundingBias\", {\n /**\n * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y\n */\n get: function () {\n return this._boundingBias;\n },\n /**\n * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y\n */\n set: function (value) {\n if (this._boundingBias && this._boundingBias.equals(value)) {\n return;\n }\n this._boundingBias = value.clone();\n this._updateBoundingInfo(true, null);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Static function used to attach a new empty geometry to a mesh\n * @param mesh defines the mesh to attach the geometry to\n * @returns the new {BABYLON.Geometry}\n */\n Geometry.CreateGeometryForMesh = function (mesh) {\n var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());\n geometry.applyToMesh(mesh);\n return geometry;\n };\n Object.defineProperty(Geometry.prototype, \"extend\", {\n /**\n * Gets the current extend of the geometry\n */\n get: function () {\n return this._extend;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the hosting scene\n * @returns the hosting {BABYLON.Scene}\n */\n Geometry.prototype.getScene = function () {\n return this._scene;\n };\n /**\n * Gets the hosting engine\n * @returns the hosting {BABYLON.Engine}\n */\n Geometry.prototype.getEngine = function () {\n return this._engine;\n };\n /**\n * Defines if the geometry is ready to use\n * @returns true if the geometry is ready to be used\n */\n Geometry.prototype.isReady = function () {\n return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;\n };\n Object.defineProperty(Geometry.prototype, \"doNotSerialize\", {\n /**\n * Gets a value indicating that the geometry should not be serialized\n */\n get: function () {\n for (var index = 0; index < this._meshes.length; index++) {\n if (!this._meshes[index].doNotSerialize) {\n return false;\n }\n }\n return true;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Geometry.prototype._rebuild = function () {\n if (this._vertexArrayObjects) {\n this._vertexArrayObjects = {};\n }\n // Index buffer\n if (this._meshes.length !== 0 && this._indices) {\n this._indexBuffer = this._engine.createIndexBuffer(this._indices);\n }\n // Vertex buffers\n for (var key in this._vertexBuffers) {\n var vertexBuffer = this._vertexBuffers[key];\n vertexBuffer._rebuild();\n }\n };\n /**\n * Affects all geometry data in one call\n * @param vertexData defines the geometry data\n * @param updatable defines if the geometry must be flagged as updatable (false as default)\n */\n Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {\n vertexData.applyToGeometry(this, updatable);\n this.notifyUpdate();\n };\n /**\n * Set specific vertex data\n * @param kind defines the data kind (Position, normal, etc...)\n * @param data defines the vertex data to use\n * @param updatable defines if the vertex must be flagged as updatable (false as default)\n * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified\n */\n Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {\n if (updatable === void 0) { updatable = false; }\n var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);\n this.setVerticesBuffer(buffer);\n };\n /**\n * Removes a specific vertex data\n * @param kind defines the data kind (Position, normal, etc...)\n */\n Geometry.prototype.removeVerticesData = function (kind) {\n if (this._vertexBuffers[kind]) {\n this._vertexBuffers[kind].dispose();\n delete this._vertexBuffers[kind];\n }\n };\n /**\n * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data\n * @param buffer defines the vertex buffer to use\n * @param totalVertices defines the total number of vertices for position kind (could be null)\n */\n Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {\n if (totalVertices === void 0) { totalVertices = null; }\n var kind = buffer.getKind();\n if (this._vertexBuffers[kind]) {\n this._vertexBuffers[kind].dispose();\n }\n this._vertexBuffers[kind] = buffer;\n if (kind === BABYLON.VertexBuffer.PositionKind) {\n var data = buffer.getData();\n if (totalVertices != null) {\n this._totalVertices = totalVertices;\n }\n else {\n if (data != null) {\n this._totalVertices = data.length / (buffer.byteStride / 4);\n }\n }\n this._updateExtend(data);\n this._resetPointsArrayCache();\n var meshes = this._meshes;\n var numOfMeshes = meshes.length;\n for (var index = 0; index < numOfMeshes; index++) {\n var mesh = meshes[index];\n mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);\n mesh._createGlobalSubMesh(false);\n mesh.computeWorldMatrix(true);\n }\n }\n this.notifyUpdate(kind);\n if (this._vertexArrayObjects) {\n this._disposeVertexArrayObjects();\n this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported\n }\n };\n /**\n * Update a specific vertex buffer\n * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array\n * It will do nothing if the buffer is not updatable\n * @param kind defines the data kind (Position, normal, etc...)\n * @param data defines the data to use\n * @param offset defines the offset in the target buffer where to store the data\n * @param useBytes set to true if the offset is in bytes\n */\n Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {\n if (useBytes === void 0) { useBytes = false; }\n var vertexBuffer = this.getVertexBuffer(kind);\n if (!vertexBuffer) {\n return;\n }\n vertexBuffer.updateDirectly(data, offset, useBytes);\n this.notifyUpdate(kind);\n };\n /**\n * Update a specific vertex buffer\n * This function will create a new buffer if the current one is not updatable\n * @param kind defines the data kind (Position, normal, etc...)\n * @param data defines the data to use\n * @param updateExtends defines if the geometry extends must be recomputed (false by default)\n */\n Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {\n if (updateExtends === void 0) { updateExtends = false; }\n var vertexBuffer = this.getVertexBuffer(kind);\n if (!vertexBuffer) {\n return;\n }\n vertexBuffer.update(data);\n if (kind === BABYLON.VertexBuffer.PositionKind) {\n this._updateBoundingInfo(updateExtends, data);\n }\n this.notifyUpdate(kind);\n };\n Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {\n if (updateExtends) {\n this._updateExtend(data);\n }\n var meshes = this._meshes;\n var numOfMeshes = meshes.length;\n this._resetPointsArrayCache();\n for (var index = 0; index < numOfMeshes; index++) {\n var mesh = meshes[index];\n if (updateExtends) {\n mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);\n for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {\n var subMesh = mesh.subMeshes[subIndex];\n subMesh.refreshBoundingInfo();\n }\n }\n }\n };\n /** @hidden */\n Geometry.prototype._bind = function (effect, indexToBind) {\n if (!effect) {\n return;\n }\n if (indexToBind === undefined) {\n indexToBind = this._indexBuffer;\n }\n var vbs = this.getVertexBuffers();\n if (!vbs) {\n return;\n }\n if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {\n this._engine.bindBuffers(vbs, indexToBind, effect);\n return;\n }\n // Using VAO\n if (!this._vertexArrayObjects[effect.key]) {\n this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);\n }\n this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);\n };\n /**\n * Gets total number of vertices\n * @returns the total number of vertices\n */\n Geometry.prototype.getTotalVertices = function () {\n if (!this.isReady()) {\n return 0;\n }\n return this._totalVertices;\n };\n /**\n * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.\n * @param kind defines the data kind (Position, normal, etc...)\n * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes\n * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it\n * @returns a float array containing vertex data\n */\n Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {\n var vertexBuffer = this.getVertexBuffer(kind);\n if (!vertexBuffer) {\n return null;\n }\n var data = vertexBuffer.getData();\n if (!data) {\n return null;\n }\n var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);\n var count = this._totalVertices * vertexBuffer.getSize();\n if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {\n var copy_1 = new Array(count);\n vertexBuffer.forEach(count, function (value, index) {\n copy_1[index] = value;\n });\n return copy_1;\n }\n if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {\n if (data instanceof Array) {\n var offset = vertexBuffer.byteOffset / 4;\n return BABYLON.Tools.Slice(data, offset, offset + count);\n }\n else if (data instanceof ArrayBuffer) {\n return new Float32Array(data, vertexBuffer.byteOffset, count);\n }\n else {\n return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);\n }\n }\n if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {\n return BABYLON.Tools.Slice(data);\n }\n return data;\n };\n /**\n * Returns a boolean defining if the vertex data for the requested `kind` is updatable\n * @param kind defines the data kind (Position, normal, etc...)\n * @returns true if the vertex buffer with the specified kind is updatable\n */\n Geometry.prototype.isVertexBufferUpdatable = function (kind) {\n var vb = this._vertexBuffers[kind];\n if (!vb) {\n return false;\n }\n return vb.isUpdatable();\n };\n /**\n * Gets a specific vertex buffer\n * @param kind defines the data kind (Position, normal, etc...)\n * @returns a {BABYLON.VertexBuffer}\n */\n Geometry.prototype.getVertexBuffer = function (kind) {\n if (!this.isReady()) {\n return null;\n }\n return this._vertexBuffers[kind];\n };\n /**\n * Returns all vertex buffers\n * @return an object holding all vertex buffers indexed by kind\n */\n Geometry.prototype.getVertexBuffers = function () {\n if (!this.isReady()) {\n return null;\n }\n return this._vertexBuffers;\n };\n /**\n * Gets a boolean indicating if specific vertex buffer is present\n * @param kind defines the data kind (Position, normal, etc...)\n * @returns true if data is present\n */\n Geometry.prototype.isVerticesDataPresent = function (kind) {\n if (!this._vertexBuffers) {\n if (this._delayInfo) {\n return this._delayInfo.indexOf(kind) !== -1;\n }\n return false;\n }\n return this._vertexBuffers[kind] !== undefined;\n };\n /**\n * Gets a list of all attached data kinds (Position, normal, etc...)\n * @returns a list of string containing all kinds\n */\n Geometry.prototype.getVerticesDataKinds = function () {\n var result = [];\n var kind;\n if (!this._vertexBuffers && this._delayInfo) {\n for (kind in this._delayInfo) {\n result.push(kind);\n }\n }\n else {\n for (kind in this._vertexBuffers) {\n result.push(kind);\n }\n }\n return result;\n };\n /**\n * Update index buffer\n * @param indices defines the indices to store in the index buffer\n * @param offset defines the offset in the target buffer where to store the data\n */\n Geometry.prototype.updateIndices = function (indices, offset) {\n if (!this._indexBuffer) {\n return;\n }\n if (!this._indexBufferIsUpdatable) {\n this.setIndices(indices, null, true);\n }\n else {\n this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);\n }\n };\n /**\n * Creates a new index buffer\n * @param indices defines the indices to store in the index buffer\n * @param totalVertices defines the total number of vertices (could be null)\n * @param updatable defines if the index buffer must be flagged as updatable (false by default)\n */\n Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {\n if (totalVertices === void 0) { totalVertices = null; }\n if (updatable === void 0) { updatable = false; }\n if (this._indexBuffer) {\n this._engine._releaseBuffer(this._indexBuffer);\n }\n this._disposeVertexArrayObjects();\n this._indices = indices;\n this._indexBufferIsUpdatable = updatable;\n if (this._meshes.length !== 0 && this._indices) {\n this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);\n }\n if (totalVertices != undefined) { // including null and undefined\n this._totalVertices = totalVertices;\n }\n var meshes = this._meshes;\n var numOfMeshes = meshes.length;\n for (var index = 0; index < numOfMeshes; index++) {\n meshes[index]._createGlobalSubMesh(true);\n }\n this.notifyUpdate();\n };\n /**\n * Return the total number of indices\n * @returns the total number of indices\n */\n Geometry.prototype.getTotalIndices = function () {\n if (!this.isReady()) {\n return 0;\n }\n return this._indices.length;\n };\n /**\n * Gets the index buffer array\n * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes\n * @returns the index buffer array\n */\n Geometry.prototype.getIndices = function (copyWhenShared) {\n if (!this.isReady()) {\n return null;\n }\n var orig = this._indices;\n if (!copyWhenShared || this._meshes.length === 1) {\n return orig;\n }\n else {\n var len = orig.length;\n var copy = [];\n for (var i = 0; i < len; i++) {\n copy.push(orig[i]);\n }\n return copy;\n }\n };\n /**\n * Gets the index buffer\n * @return the index buffer\n */\n Geometry.prototype.getIndexBuffer = function () {\n if (!this.isReady()) {\n return null;\n }\n return this._indexBuffer;\n };\n /** @hidden */\n Geometry.prototype._releaseVertexArrayObject = function (effect) {\n if (effect === void 0) { effect = null; }\n if (!effect || !this._vertexArrayObjects) {\n return;\n }\n if (this._vertexArrayObjects[effect.key]) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);\n delete this._vertexArrayObjects[effect.key];\n }\n };\n /**\n * Release the associated resources for a specific mesh\n * @param mesh defines the source mesh\n * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it\n */\n Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {\n var meshes = this._meshes;\n var index = meshes.indexOf(mesh);\n if (index === -1) {\n return;\n }\n meshes.splice(index, 1);\n mesh._geometry = null;\n if (meshes.length === 0 && shouldDispose) {\n this.dispose();\n }\n };\n /**\n * Apply current geometry to a given mesh\n * @param mesh defines the mesh to apply geometry to\n */\n Geometry.prototype.applyToMesh = function (mesh) {\n if (mesh._geometry === this) {\n return;\n }\n var previousGeometry = mesh._geometry;\n if (previousGeometry) {\n previousGeometry.releaseForMesh(mesh);\n }\n var meshes = this._meshes;\n // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()\n mesh._geometry = this;\n this._scene.pushGeometry(this);\n meshes.push(mesh);\n if (this.isReady()) {\n this._applyToMesh(mesh);\n }\n else {\n mesh._boundingInfo = this._boundingInfo;\n }\n };\n Geometry.prototype._updateExtend = function (data) {\n if (data === void 0) { data = null; }\n if (!data) {\n data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n }\n this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);\n };\n Geometry.prototype._applyToMesh = function (mesh) {\n var numOfMeshes = this._meshes.length;\n // vertexBuffers\n for (var kind in this._vertexBuffers) {\n if (numOfMeshes === 1) {\n this._vertexBuffers[kind].create();\n }\n var buffer = this._vertexBuffers[kind].getBuffer();\n if (buffer)\n buffer.references = numOfMeshes;\n if (kind === BABYLON.VertexBuffer.PositionKind) {\n if (!this._extend) {\n this._updateExtend();\n }\n mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);\n mesh._createGlobalSubMesh(false);\n //bounding info was just created again, world matrix should be applied again.\n mesh._updateBoundingInfo();\n }\n }\n // indexBuffer\n if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {\n this._indexBuffer = this._engine.createIndexBuffer(this._indices);\n }\n if (this._indexBuffer) {\n this._indexBuffer.references = numOfMeshes;\n }\n };\n Geometry.prototype.notifyUpdate = function (kind) {\n if (this.onGeometryUpdated) {\n this.onGeometryUpdated(this, kind);\n }\n for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n mesh._markSubMeshesAsAttributesDirty();\n }\n };\n /**\n * Load the geometry if it was flagged as delay loaded\n * @param scene defines the hosting scene\n * @param onLoaded defines a callback called when the geometry is loaded\n */\n Geometry.prototype.load = function (scene, onLoaded) {\n if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {\n return;\n }\n if (this.isReady()) {\n if (onLoaded) {\n onLoaded();\n }\n return;\n }\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;\n this._queueLoad(scene, onLoaded);\n };\n Geometry.prototype._queueLoad = function (scene, onLoaded) {\n var _this = this;\n if (!this.delayLoadingFile) {\n return;\n }\n scene._addPendingData(this);\n scene._loadFile(this.delayLoadingFile, function (data) {\n if (!_this._delayLoadingFunction) {\n return;\n }\n _this._delayLoadingFunction(JSON.parse(data), _this);\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;\n _this._delayInfo = [];\n scene._removePendingData(_this);\n var meshes = _this._meshes;\n var numOfMeshes = meshes.length;\n for (var index = 0; index < numOfMeshes; index++) {\n _this._applyToMesh(meshes[index]);\n }\n if (onLoaded) {\n onLoaded();\n }\n }, undefined, true);\n };\n /**\n * Invert the geometry to move from a right handed system to a left handed one.\n */\n Geometry.prototype.toLeftHanded = function () {\n // Flip faces\n var tIndices = this.getIndices(false);\n if (tIndices != null && tIndices.length > 0) {\n for (var i = 0; i < tIndices.length; i += 3) {\n var tTemp = tIndices[i + 0];\n tIndices[i + 0] = tIndices[i + 2];\n tIndices[i + 2] = tTemp;\n }\n this.setIndices(tIndices);\n }\n // Negate position.z\n var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);\n if (tPositions != null && tPositions.length > 0) {\n for (var i = 0; i < tPositions.length; i += 3) {\n tPositions[i + 2] = -tPositions[i + 2];\n }\n this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);\n }\n // Negate normal.z\n var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);\n if (tNormals != null && tNormals.length > 0) {\n for (var i = 0; i < tNormals.length; i += 3) {\n tNormals[i + 2] = -tNormals[i + 2];\n }\n this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);\n }\n };\n // Cache\n /** @hidden */\n Geometry.prototype._resetPointsArrayCache = function () {\n this._positions = null;\n };\n /** @hidden */\n Geometry.prototype._generatePointsArray = function () {\n if (this._positions)\n return true;\n var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!data || data.length === 0) {\n return false;\n }\n this._positions = [];\n for (var index = 0; index < data.length; index += 3) {\n this._positions.push(BABYLON.Vector3.FromArray(data, index));\n }\n return true;\n };\n /**\n * Gets a value indicating if the geometry is disposed\n * @returns true if the geometry was disposed\n */\n Geometry.prototype.isDisposed = function () {\n return this._isDisposed;\n };\n Geometry.prototype._disposeVertexArrayObjects = function () {\n if (this._vertexArrayObjects) {\n for (var kind in this._vertexArrayObjects) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);\n }\n this._vertexArrayObjects = {};\n }\n };\n /**\n * Free all associated resources\n */\n Geometry.prototype.dispose = function () {\n var meshes = this._meshes;\n var numOfMeshes = meshes.length;\n var index;\n for (index = 0; index < numOfMeshes; index++) {\n this.releaseForMesh(meshes[index]);\n }\n this._meshes = [];\n this._disposeVertexArrayObjects();\n for (var kind in this._vertexBuffers) {\n this._vertexBuffers[kind].dispose();\n }\n this._vertexBuffers = {};\n this._totalVertices = 0;\n if (this._indexBuffer) {\n this._engine._releaseBuffer(this._indexBuffer);\n }\n this._indexBuffer = null;\n this._indices = [];\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;\n this.delayLoadingFile = null;\n this._delayLoadingFunction = null;\n this._delayInfo = [];\n this._boundingInfo = null;\n this._scene.removeGeometry(this);\n this._isDisposed = true;\n };\n /**\n * Clone the current geometry into a new geometry\n * @param id defines the unique ID of the new geometry\n * @returns a new geometry object\n */\n Geometry.prototype.copy = function (id) {\n var vertexData = new BABYLON.VertexData();\n vertexData.indices = [];\n var indices = this.getIndices();\n if (indices) {\n for (var index = 0; index < indices.length; index++) {\n vertexData.indices.push(indices[index]);\n }\n }\n var updatable = false;\n var stopChecking = false;\n var kind;\n for (kind in this._vertexBuffers) {\n // using slice() to make a copy of the array and not just reference it\n var data = this.getVerticesData(kind);\n if (data instanceof Float32Array) {\n vertexData.set(new Float32Array(data), kind);\n }\n else {\n vertexData.set(data.slice(0), kind);\n }\n if (!stopChecking) {\n var vb = this.getVertexBuffer(kind);\n if (vb) {\n updatable = vb.isUpdatable();\n stopChecking = !updatable;\n }\n }\n }\n var geometry = new Geometry(id, this._scene, vertexData, updatable);\n geometry.delayLoadState = this.delayLoadState;\n geometry.delayLoadingFile = this.delayLoadingFile;\n geometry._delayLoadingFunction = this._delayLoadingFunction;\n for (kind in this._delayInfo) {\n geometry._delayInfo = geometry._delayInfo || [];\n geometry._delayInfo.push(kind);\n }\n // Bounding info\n geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);\n return geometry;\n };\n /**\n * Serialize the current geometry info (and not the vertices data) into a JSON object\n * @return a JSON representation of the current geometry data (without the vertices data)\n */\n Geometry.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.id = this.id;\n serializationObject.updatable = this._updatable;\n if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {\n serializationObject.tags = BABYLON.Tags.GetTags(this);\n }\n return serializationObject;\n };\n Geometry.prototype.toNumberArray = function (origin) {\n if (Array.isArray(origin)) {\n return origin;\n }\n else {\n return Array.prototype.slice.call(origin);\n }\n };\n /**\n * Serialize all vertices data into a JSON oject\n * @returns a JSON representation of the current geometry data\n */\n Geometry.prototype.serializeVerticeData = function () {\n var serializationObject = this.serialize();\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {\n serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {\n serializationObject.positions._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {\n serializationObject.normals._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {\n serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {\n serializationObject.tangets._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {\n serializationObject.uvs._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {\n serializationObject.uv2s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {\n serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {\n serializationObject.uv3s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {\n serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {\n serializationObject.uv4s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {\n serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {\n serializationObject.uv5s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {\n serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {\n serializationObject.uv6s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {\n serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {\n serializationObject.colors._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {\n serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));\n serializationObject.matricesIndices._isExpanded = true;\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {\n serializationObject.matricesIndices._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {\n serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));\n if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {\n serializationObject.matricesWeights._updatable = true;\n }\n }\n serializationObject.indices = this.toNumberArray(this.getIndices());\n return serializationObject;\n };\n // Statics\n /**\n * Extracts a clone of a mesh geometry\n * @param mesh defines the source mesh\n * @param id defines the unique ID of the new geometry object\n * @returns the new geometry object\n */\n Geometry.ExtractFromMesh = function (mesh, id) {\n var geometry = mesh._geometry;\n if (!geometry) {\n return null;\n }\n return geometry.copy(id);\n };\n /**\n * You should now use Tools.RandomId(), this method is still here for legacy reasons.\n * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523\n * Be aware Math.random() could cause collisions, but:\n * \"All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide\"\n * @returns a string containing a new GUID\n */\n Geometry.RandomId = function () {\n return BABYLON.Tools.RandomId();\n };\n /** @hidden */\n Geometry._ImportGeometry = function (parsedGeometry, mesh) {\n var scene = mesh.getScene();\n // Geometry\n var geometryId = parsedGeometry.geometryId;\n if (geometryId) {\n var geometry = scene.getGeometryByID(geometryId);\n if (geometry) {\n geometry.applyToMesh(mesh);\n }\n }\n else if (parsedGeometry instanceof ArrayBuffer) {\n var binaryInfo = mesh._binaryInfo;\n if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {\n var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);\n }\n if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {\n var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);\n }\n if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {\n var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);\n }\n if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {\n var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);\n }\n if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {\n var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);\n }\n if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {\n var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);\n }\n if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {\n var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);\n }\n if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {\n var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);\n }\n if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {\n var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);\n }\n if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {\n var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);\n }\n if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {\n var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);\n var floatIndices = [];\n for (var i = 0; i < matricesIndicesData.length; i++) {\n var index = matricesIndicesData[i];\n floatIndices.push(index & 0x000000FF);\n floatIndices.push((index & 0x0000FF00) >> 8);\n floatIndices.push((index & 0x00FF0000) >> 16);\n floatIndices.push(index >> 24);\n }\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);\n }\n if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {\n var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);\n }\n if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {\n var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);\n mesh.setIndices(indicesData, null);\n }\n if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {\n var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);\n mesh.subMeshes = [];\n for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {\n var materialIndex = subMeshesData[(i * 5) + 0];\n var verticesStart = subMeshesData[(i * 5) + 1];\n var verticesCount = subMeshesData[(i * 5) + 2];\n var indexStart = subMeshesData[(i * 5) + 3];\n var indexCount = subMeshesData[(i * 5) + 4];\n BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);\n }\n }\n }\n else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {\n mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);\n mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);\n if (parsedGeometry.tangents) {\n mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);\n }\n if (parsedGeometry.uvs) {\n mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);\n }\n if (parsedGeometry.uvs2) {\n mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);\n }\n if (parsedGeometry.uvs3) {\n mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);\n }\n if (parsedGeometry.uvs4) {\n mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);\n }\n if (parsedGeometry.uvs5) {\n mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);\n }\n if (parsedGeometry.uvs6) {\n mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);\n }\n if (parsedGeometry.colors) {\n mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);\n }\n if (parsedGeometry.matricesIndices) {\n if (!parsedGeometry.matricesIndices._isExpanded) {\n var floatIndices = [];\n for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {\n var matricesIndex = parsedGeometry.matricesIndices[i];\n floatIndices.push(matricesIndex & 0x000000FF);\n floatIndices.push((matricesIndex & 0x0000FF00) >> 8);\n floatIndices.push((matricesIndex & 0x00FF0000) >> 16);\n floatIndices.push(matricesIndex >> 24);\n }\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);\n }\n else {\n delete parsedGeometry.matricesIndices._isExpanded;\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);\n }\n }\n if (parsedGeometry.matricesIndicesExtra) {\n if (!parsedGeometry.matricesIndicesExtra._isExpanded) {\n var floatIndices = [];\n for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {\n var matricesIndex = parsedGeometry.matricesIndicesExtra[i];\n floatIndices.push(matricesIndex & 0x000000FF);\n floatIndices.push((matricesIndex & 0x0000FF00) >> 8);\n floatIndices.push((matricesIndex & 0x00FF0000) >> 16);\n floatIndices.push(matricesIndex >> 24);\n }\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);\n }\n else {\n delete parsedGeometry.matricesIndices._isExpanded;\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);\n }\n }\n if (parsedGeometry.matricesWeights) {\n Geometry._CleanMatricesWeights(parsedGeometry, mesh);\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);\n }\n if (parsedGeometry.matricesWeightsExtra) {\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);\n }\n mesh.setIndices(parsedGeometry.indices, null);\n }\n // SubMeshes\n if (parsedGeometry.subMeshes) {\n mesh.subMeshes = [];\n for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {\n var parsedSubMesh = parsedGeometry.subMeshes[subIndex];\n BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);\n }\n }\n // Flat shading\n if (mesh._shouldGenerateFlatShading) {\n mesh.convertToFlatShadedMesh();\n delete mesh._shouldGenerateFlatShading;\n }\n // Update\n mesh.computeWorldMatrix(true);\n // Octree\n var sceneOctree = scene.selectionOctree;\n if (sceneOctree !== undefined && sceneOctree !== null) {\n sceneOctree.addMesh(mesh);\n }\n };\n Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {\n var epsilon = 1e-3;\n if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {\n return;\n }\n var noInfluenceBoneIndex = 0.0;\n if (parsedGeometry.skeletonId > -1) {\n var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);\n if (!skeleton) {\n return;\n }\n noInfluenceBoneIndex = skeleton.bones.length;\n }\n else {\n return;\n }\n var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);\n var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n var matricesWeights = parsedGeometry.matricesWeights;\n var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;\n var influencers = parsedGeometry.numBoneInfluencer;\n var size = matricesWeights.length;\n for (var i = 0; i < size; i += 4) {\n var weight = 0.0;\n var firstZeroWeight = -1;\n for (var j = 0; j < 4; j++) {\n var w = matricesWeights[i + j];\n weight += w;\n if (w < epsilon && firstZeroWeight < 0) {\n firstZeroWeight = j;\n }\n }\n if (matricesWeightsExtra) {\n for (var j = 0; j < 4; j++) {\n var w = matricesWeightsExtra[i + j];\n weight += w;\n if (w < epsilon && firstZeroWeight < 0) {\n firstZeroWeight = j + 4;\n }\n }\n }\n if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {\n firstZeroWeight = influencers - 1;\n }\n if (weight > epsilon) {\n var mweight = 1.0 / weight;\n for (var j = 0; j < 4; j++) {\n matricesWeights[i + j] *= mweight;\n }\n if (matricesWeightsExtra) {\n for (var j = 0; j < 4; j++) {\n matricesWeightsExtra[i + j] *= mweight;\n }\n }\n }\n else {\n if (firstZeroWeight >= 4) {\n matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;\n matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;\n }\n else {\n matricesWeights[i + firstZeroWeight] = 1.0 - weight;\n matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;\n }\n }\n }\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);\n if (parsedGeometry.matricesWeightsExtra) {\n mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);\n }\n };\n /**\n * Create a new geometry from persisted data (Using .babylon file format)\n * @param parsedVertexData defines the persisted data\n * @param scene defines the hosting scene\n * @param rootUrl defines the root url to use to load assets (like delayed data)\n * @returns the new geometry object\n */\n Geometry.Parse = function (parsedVertexData, scene, rootUrl) {\n if (scene.getGeometryByID(parsedVertexData.id)) {\n return null; // null since geometry could be something else than a box...\n }\n var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);\n }\n if (parsedVertexData.delayLoadingFile) {\n geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;\n geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));\n geometry._delayInfo = [];\n if (parsedVertexData.hasUVs) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);\n }\n if (parsedVertexData.hasUVs2) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);\n }\n if (parsedVertexData.hasUVs3) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);\n }\n if (parsedVertexData.hasUVs4) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);\n }\n if (parsedVertexData.hasUVs5) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);\n }\n if (parsedVertexData.hasUVs6) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);\n }\n if (parsedVertexData.hasColors) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);\n }\n if (parsedVertexData.hasMatricesIndices) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n }\n if (parsedVertexData.hasMatricesWeights) {\n geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n }\n geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;\n }\n else {\n BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);\n }\n scene.pushGeometry(geometry, true);\n return geometry;\n };\n return Geometry;\n }());\n BABYLON.Geometry = Geometry;\n // Primitives\n /// Abstract class\n /**\n * Abstract class used to provide common services for all typed geometries\n * @hidden\n */\n var _PrimitiveGeometry = /** @class */ (function (_super) {\n __extends(_PrimitiveGeometry, _super);\n /**\n * Creates a new typed geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n */\n function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {\n if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }\n if (mesh === void 0) { mesh = null; }\n var _this = _super.call(this, id, scene, undefined, false, mesh) || this;\n _this._canBeRegenerated = _canBeRegenerated;\n _this._beingRegenerated = true;\n _this.regenerate();\n _this._beingRegenerated = false;\n return _this;\n }\n /**\n * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)\n * @returns true if the geometry can be regenerated\n */\n _PrimitiveGeometry.prototype.canBeRegenerated = function () {\n return this._canBeRegenerated;\n };\n /**\n * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values\n */\n _PrimitiveGeometry.prototype.regenerate = function () {\n if (!this._canBeRegenerated) {\n return;\n }\n this._beingRegenerated = true;\n this.setAllVerticesData(this._regenerateVertexData(), false);\n this._beingRegenerated = false;\n };\n /**\n * Clone the geometry\n * @param id defines the unique ID of the new geometry\n * @returns the new geometry\n */\n _PrimitiveGeometry.prototype.asNewGeometry = function (id) {\n return _super.prototype.copy.call(this, id);\n };\n // overrides\n _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {\n if (!this._beingRegenerated) {\n return;\n }\n _super.prototype.setAllVerticesData.call(this, vertexData, false);\n };\n _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {\n if (!this._beingRegenerated) {\n return;\n }\n _super.prototype.setVerticesData.call(this, kind, data, false);\n };\n // to override\n /** @hidden */\n _PrimitiveGeometry.prototype._regenerateVertexData = function () {\n throw new Error(\"Abstract method\");\n };\n _PrimitiveGeometry.prototype.copy = function (id) {\n throw new Error(\"Must be overriden in sub-classes.\");\n };\n _PrimitiveGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.canBeRegenerated = this.canBeRegenerated();\n return serializationObject;\n };\n return _PrimitiveGeometry;\n }(Geometry));\n BABYLON._PrimitiveGeometry = _PrimitiveGeometry;\n /**\n * Creates a ribbon geometry\n * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons\n */\n var RibbonGeometry = /** @class */ (function (_super) {\n __extends(RibbonGeometry, _super);\n /**\n * Creates a ribbon geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param pathArray defines the array of paths to use\n * @param closeArray defines if the last path and the first path must be joined\n * @param closePath defines if the last and first points of each path in your pathArray must be joined\n * @param offset defines the offset between points\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function RibbonGeometry(id, scene, \n /**\n * Defines the array of paths to use\n */\n pathArray, \n /**\n * Defines if the last and first points of each path in your pathArray must be joined\n */\n closeArray, \n /**\n * Defines if the last and first points of each path in your pathArray must be joined\n */\n closePath, \n /**\n * Defines the offset between points\n */\n offset, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.pathArray = pathArray;\n _this.closeArray = closeArray;\n _this.closePath = closePath;\n _this.offset = offset;\n _this.side = side;\n return _this;\n }\n /** @hidden */\n RibbonGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });\n };\n RibbonGeometry.prototype.copy = function (id) {\n return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);\n };\n return RibbonGeometry;\n }(_PrimitiveGeometry));\n BABYLON.RibbonGeometry = RibbonGeometry;\n /**\n * Creates a box geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#box\n */\n var BoxGeometry = /** @class */ (function (_super) {\n __extends(BoxGeometry, _super);\n /**\n * Creates a box geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param size defines the zise of the box (width, height and depth are the same)\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function BoxGeometry(id, scene, \n /**\n * Defines the zise of the box (width, height and depth are the same)\n */\n size, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.size = size;\n _this.side = side;\n return _this;\n }\n BoxGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });\n };\n BoxGeometry.prototype.copy = function (id) {\n return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);\n };\n BoxGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.size = this.size;\n return serializationObject;\n };\n BoxGeometry.Parse = function (parsedBox, scene) {\n if (scene.getGeometryByID(parsedBox.id)) {\n return null; // null since geometry could be something else than a box...\n }\n var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(box, parsedBox.tags);\n }\n scene.pushGeometry(box, true);\n return box;\n };\n return BoxGeometry;\n }(_PrimitiveGeometry));\n BABYLON.BoxGeometry = BoxGeometry;\n /**\n * Creates a sphere geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere\n */\n var SphereGeometry = /** @class */ (function (_super) {\n __extends(SphereGeometry, _super);\n /**\n * Create a new sphere geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param segments defines the number of segments to use to create the sphere\n * @param diameter defines the diameter of the sphere\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function SphereGeometry(id, scene, \n /**\n * Defines the number of segments to use to create the sphere\n */\n segments, \n /**\n * Defines the diameter of the sphere\n */\n diameter, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.segments = segments;\n _this.diameter = diameter;\n _this.side = side;\n return _this;\n }\n SphereGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });\n };\n SphereGeometry.prototype.copy = function (id) {\n return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);\n };\n SphereGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.segments = this.segments;\n serializationObject.diameter = this.diameter;\n return serializationObject;\n };\n SphereGeometry.Parse = function (parsedSphere, scene) {\n if (scene.getGeometryByID(parsedSphere.id)) {\n return null; // null since geometry could be something else than a sphere...\n }\n var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);\n }\n scene.pushGeometry(sphere, true);\n return sphere;\n };\n return SphereGeometry;\n }(_PrimitiveGeometry));\n BABYLON.SphereGeometry = SphereGeometry;\n /**\n * Creates a disc geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon\n */\n var DiscGeometry = /** @class */ (function (_super) {\n __extends(DiscGeometry, _super);\n /**\n * Creates a new disc geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param radius defines the radius of the disc\n * @param tessellation defines the tesselation factor to apply to the disc\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function DiscGeometry(id, scene, \n /**\n * Defines the radius of the disc\n */\n radius, \n /**\n * Defines the tesselation factor to apply to the disc\n */\n tessellation, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.radius = radius;\n _this.tessellation = tessellation;\n _this.side = side;\n return _this;\n }\n DiscGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });\n };\n DiscGeometry.prototype.copy = function (id) {\n return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);\n };\n return DiscGeometry;\n }(_PrimitiveGeometry));\n BABYLON.DiscGeometry = DiscGeometry;\n /**\n * Creates a new cylinder geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone\n */\n var CylinderGeometry = /** @class */ (function (_super) {\n __extends(CylinderGeometry, _super);\n /**\n * Creates a new cylinder geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param height defines the height of the cylinder\n * @param diameterTop defines the diameter of the cylinder's top cap\n * @param diameterBottom defines the diameter of the cylinder's bottom cap\n * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)\n * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function CylinderGeometry(id, scene, \n /**\n * Defines the height of the cylinder\n */\n height, \n /**\n * Defines the diameter of the cylinder's top cap\n */\n diameterTop, \n /**\n * Defines the diameter of the cylinder's bottom cap\n */\n diameterBottom, \n /**\n * Defines the tessellation factor to apply to the cylinder\n */\n tessellation, \n /**\n * Defines the number of subdivisions to apply to the cylinder (1 by default)\n */\n subdivisions, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (subdivisions === void 0) { subdivisions = 1; }\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.height = height;\n _this.diameterTop = diameterTop;\n _this.diameterBottom = diameterBottom;\n _this.tessellation = tessellation;\n _this.subdivisions = subdivisions;\n _this.side = side;\n return _this;\n }\n CylinderGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });\n };\n CylinderGeometry.prototype.copy = function (id) {\n return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);\n };\n CylinderGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.height = this.height;\n serializationObject.diameterTop = this.diameterTop;\n serializationObject.diameterBottom = this.diameterBottom;\n serializationObject.tessellation = this.tessellation;\n return serializationObject;\n };\n CylinderGeometry.Parse = function (parsedCylinder, scene) {\n if (scene.getGeometryByID(parsedCylinder.id)) {\n return null; // null since geometry could be something else than a cylinder...\n }\n var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);\n }\n scene.pushGeometry(cylinder, true);\n return cylinder;\n };\n return CylinderGeometry;\n }(_PrimitiveGeometry));\n BABYLON.CylinderGeometry = CylinderGeometry;\n /**\n * Creates a new torus geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#torus\n */\n var TorusGeometry = /** @class */ (function (_super) {\n __extends(TorusGeometry, _super);\n /**\n * Creates a new torus geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param diameter defines the diameter of the torus\n * @param thickness defines the thickness of the torus (ie. internal diameter)\n * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function TorusGeometry(id, scene, \n /**\n * Defines the diameter of the torus\n */\n diameter, \n /**\n * Defines the thickness of the torus (ie. internal diameter)\n */\n thickness, \n /**\n * Defines the tesselation factor to apply to the torus\n */\n tessellation, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.diameter = diameter;\n _this.thickness = thickness;\n _this.tessellation = tessellation;\n _this.side = side;\n return _this;\n }\n TorusGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });\n };\n TorusGeometry.prototype.copy = function (id) {\n return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);\n };\n TorusGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.diameter = this.diameter;\n serializationObject.thickness = this.thickness;\n serializationObject.tessellation = this.tessellation;\n return serializationObject;\n };\n TorusGeometry.Parse = function (parsedTorus, scene) {\n if (scene.getGeometryByID(parsedTorus.id)) {\n return null; // null since geometry could be something else than a torus...\n }\n var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);\n }\n scene.pushGeometry(torus, true);\n return torus;\n };\n return TorusGeometry;\n }(_PrimitiveGeometry));\n BABYLON.TorusGeometry = TorusGeometry;\n /**\n * Creates a new ground geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#ground\n */\n var GroundGeometry = /** @class */ (function (_super) {\n __extends(GroundGeometry, _super);\n /**\n * Creates a new ground geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param width defines the width of the ground\n * @param height defines the height of the ground\n * @param subdivisions defines the subdivisions to apply to the ground\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n */\n function GroundGeometry(id, scene, \n /**\n * Defines the width of the ground\n */\n width, \n /**\n * Defines the height of the ground\n */\n height, \n /**\n * Defines the subdivisions to apply to the ground\n */\n subdivisions, canBeRegenerated, mesh) {\n if (mesh === void 0) { mesh = null; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.width = width;\n _this.height = height;\n _this.subdivisions = subdivisions;\n return _this;\n }\n GroundGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });\n };\n GroundGeometry.prototype.copy = function (id) {\n return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);\n };\n GroundGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.width = this.width;\n serializationObject.height = this.height;\n serializationObject.subdivisions = this.subdivisions;\n return serializationObject;\n };\n GroundGeometry.Parse = function (parsedGround, scene) {\n if (scene.getGeometryByID(parsedGround.id)) {\n return null; // null since geometry could be something else than a ground...\n }\n var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);\n }\n scene.pushGeometry(ground, true);\n return ground;\n };\n return GroundGeometry;\n }(_PrimitiveGeometry));\n BABYLON.GroundGeometry = GroundGeometry;\n /**\n * Creates a tiled ground geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground\n */\n var TiledGroundGeometry = /** @class */ (function (_super) {\n __extends(TiledGroundGeometry, _super);\n /**\n * Creates a tiled ground geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param xmin defines the minimum value on X axis\n * @param zmin defines the minimum value on Z axis\n * @param xmax defines the maximum value on X axis\n * @param zmax defines the maximum value on Z axis\n * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)\n * @param precision defines the precision to use when computing the tiles\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n */\n function TiledGroundGeometry(id, scene, \n /**\n * Defines the minimum value on X axis\n */\n xmin, \n /**\n * Defines the minimum value on Z axis\n */\n zmin, \n /**\n * Defines the maximum value on X axis\n */\n xmax, \n /**\n * Defines the maximum value on Z axis\n */\n zmax, \n /**\n * Defines the subdivisions to apply to the ground\n */\n subdivisions, \n /**\n * Defines the precision to use when computing the tiles\n */\n precision, canBeRegenerated, mesh) {\n if (mesh === void 0) { mesh = null; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.xmin = xmin;\n _this.zmin = zmin;\n _this.xmax = xmax;\n _this.zmax = zmax;\n _this.subdivisions = subdivisions;\n _this.precision = precision;\n return _this;\n }\n TiledGroundGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });\n };\n TiledGroundGeometry.prototype.copy = function (id) {\n return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);\n };\n return TiledGroundGeometry;\n }(_PrimitiveGeometry));\n BABYLON.TiledGroundGeometry = TiledGroundGeometry;\n /**\n * Creates a plane geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#plane\n */\n var PlaneGeometry = /** @class */ (function (_super) {\n __extends(PlaneGeometry, _super);\n /**\n * Creates a plane geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param size defines the size of the plane (width === height)\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function PlaneGeometry(id, scene, \n /**\n * Defines the size of the plane (width === height)\n */\n size, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.size = size;\n _this.side = side;\n return _this;\n }\n PlaneGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });\n };\n PlaneGeometry.prototype.copy = function (id) {\n return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);\n };\n PlaneGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.size = this.size;\n return serializationObject;\n };\n PlaneGeometry.Parse = function (parsedPlane, scene) {\n if (scene.getGeometryByID(parsedPlane.id)) {\n return null; // null since geometry could be something else than a ground...\n }\n var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);\n }\n scene.pushGeometry(plane, true);\n return plane;\n };\n return PlaneGeometry;\n }(_PrimitiveGeometry));\n BABYLON.PlaneGeometry = PlaneGeometry;\n /**\n * Creates a torus knot geometry\n * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot\n */\n var TorusKnotGeometry = /** @class */ (function (_super) {\n __extends(TorusKnotGeometry, _super);\n /**\n * Creates a torus knot geometry\n * @param id defines the unique ID of the geometry\n * @param scene defines the hosting scene\n * @param radius defines the radius of the torus knot\n * @param tube defines the thickness of the torus knot tube\n * @param radialSegments defines the number of radial segments\n * @param tubularSegments defines the number of tubular segments\n * @param p defines the first number of windings\n * @param q defines the second number of windings\n * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)\n * @param mesh defines the hosting mesh (can be null)\n * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n function TorusKnotGeometry(id, scene, \n /**\n * Defines the radius of the torus knot\n */\n radius, \n /**\n * Defines the thickness of the torus knot tube\n */\n tube, \n /**\n * Defines the number of radial segments\n */\n radialSegments, \n /**\n * Defines the number of tubular segments\n */\n tubularSegments, \n /**\n * Defines the first number of windings\n */\n p, \n /**\n * Defines the second number of windings\n */\n q, canBeRegenerated, mesh, \n /**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */\n side) {\n if (mesh === void 0) { mesh = null; }\n if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }\n var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;\n _this.radius = radius;\n _this.tube = tube;\n _this.radialSegments = radialSegments;\n _this.tubularSegments = tubularSegments;\n _this.p = p;\n _this.q = q;\n _this.side = side;\n return _this;\n }\n TorusKnotGeometry.prototype._regenerateVertexData = function () {\n return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });\n };\n TorusKnotGeometry.prototype.copy = function (id) {\n return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);\n };\n TorusKnotGeometry.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.radius = this.radius;\n serializationObject.tube = this.tube;\n serializationObject.radialSegments = this.radialSegments;\n serializationObject.tubularSegments = this.tubularSegments;\n serializationObject.p = this.p;\n serializationObject.q = this.q;\n return serializationObject;\n };\n ;\n TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {\n if (scene.getGeometryByID(parsedTorusKnot.id)) {\n return null; // null since geometry could be something else than a ground...\n }\n var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);\n if (BABYLON.Tags) {\n BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);\n }\n scene.pushGeometry(torusKnot, true);\n return torusKnot;\n };\n return TorusKnotGeometry;\n }(_PrimitiveGeometry));\n BABYLON.TorusKnotGeometry = TorusKnotGeometry;\n //}\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.geometry.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window\n */\n var PerformanceMonitor = /** @class */ (function () {\n /**\n * constructor\n * @param frameSampleSize The number of samples required to saturate the sliding window\n */\n function PerformanceMonitor(frameSampleSize) {\n if (frameSampleSize === void 0) { frameSampleSize = 30; }\n this._enabled = true;\n this._rollingFrameTime = new RollingAverage(frameSampleSize);\n }\n /**\n * Samples current frame\n * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames\n */\n PerformanceMonitor.prototype.sampleFrame = function (timeMs) {\n if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }\n if (!this._enabled)\n return;\n if (this._lastFrameTimeMs != null) {\n var dt = timeMs - this._lastFrameTimeMs;\n this._rollingFrameTime.add(dt);\n }\n this._lastFrameTimeMs = timeMs;\n };\n Object.defineProperty(PerformanceMonitor.prototype, \"averageFrameTime\", {\n /**\n * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)\n * @return Average frame time in milliseconds\n */\n get: function () {\n return this._rollingFrameTime.average;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerformanceMonitor.prototype, \"averageFrameTimeVariance\", {\n /**\n * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)\n * @return Frame time variance in milliseconds squared\n */\n get: function () {\n return this._rollingFrameTime.variance;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerformanceMonitor.prototype, \"instantaneousFrameTime\", {\n /**\n * Returns the frame time of the most recent frame\n * @return Frame time in milliseconds\n */\n get: function () {\n return this._rollingFrameTime.history(0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerformanceMonitor.prototype, \"averageFPS\", {\n /**\n * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)\n * @return Framerate in frames per second\n */\n get: function () {\n return 1000.0 / this._rollingFrameTime.average;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerformanceMonitor.prototype, \"instantaneousFPS\", {\n /**\n * Returns the average framerate in frames per second using the most recent frame time\n * @return Framerate in frames per second\n */\n get: function () {\n var history = this._rollingFrameTime.history(0);\n if (history === 0) {\n return 0;\n }\n return 1000.0 / history;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PerformanceMonitor.prototype, \"isSaturated\", {\n /**\n * Returns true if enough samples have been taken to completely fill the sliding window\n * @return true if saturated\n */\n get: function () {\n return this._rollingFrameTime.isSaturated();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Enables contributions to the sliding window sample set\n */\n PerformanceMonitor.prototype.enable = function () {\n this._enabled = true;\n };\n /**\n * Disables contributions to the sliding window sample set\n * Samples will not be interpolated over the disabled period\n */\n PerformanceMonitor.prototype.disable = function () {\n this._enabled = false;\n //clear last sample to avoid interpolating over the disabled period when next enabled\n this._lastFrameTimeMs = null;\n };\n Object.defineProperty(PerformanceMonitor.prototype, \"isEnabled\", {\n /**\n * Returns true if sampling is enabled\n * @return true if enabled\n */\n get: function () {\n return this._enabled;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Resets performance monitor\n */\n PerformanceMonitor.prototype.reset = function () {\n //clear last sample to avoid interpolating over the disabled period when next enabled\n this._lastFrameTimeMs = null;\n //wipe record\n this._rollingFrameTime.reset();\n };\n return PerformanceMonitor;\n }());\n BABYLON.PerformanceMonitor = PerformanceMonitor;\n /**\n * RollingAverage\n *\n * Utility to efficiently compute the rolling average and variance over a sliding window of samples\n */\n var RollingAverage = /** @class */ (function () {\n /**\n * constructor\n * @param length The number of samples required to saturate the sliding window\n */\n function RollingAverage(length) {\n this._samples = new Array(length);\n this.reset();\n }\n /**\n * Adds a sample to the sample set\n * @param v The sample value\n */\n RollingAverage.prototype.add = function (v) {\n //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance\n var delta;\n //we need to check if we've already wrapped round\n if (this.isSaturated()) {\n //remove bottom of stack from mean\n var bottomValue = this._samples[this._pos];\n delta = bottomValue - this.average;\n this.average -= delta / (this._sampleCount - 1);\n this._m2 -= delta * (bottomValue - this.average);\n }\n else {\n this._sampleCount++;\n }\n //add new value to mean\n delta = v - this.average;\n this.average += delta / (this._sampleCount);\n this._m2 += delta * (v - this.average);\n //set the new variance\n this.variance = this._m2 / (this._sampleCount - 1);\n this._samples[this._pos] = v;\n this._pos++;\n this._pos %= this._samples.length; //positive wrap around\n };\n /**\n * Returns previously added values or null if outside of history or outside the sliding window domain\n * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that\n * @return Value previously recorded with add() or null if outside of range\n */\n RollingAverage.prototype.history = function (i) {\n if ((i >= this._sampleCount) || (i >= this._samples.length)) {\n return 0;\n }\n var i0 = this._wrapPosition(this._pos - 1.0);\n return this._samples[this._wrapPosition(i0 - i)];\n };\n /**\n * Returns true if enough samples have been taken to completely fill the sliding window\n * @return true if sample-set saturated\n */\n RollingAverage.prototype.isSaturated = function () {\n return this._sampleCount >= this._samples.length;\n };\n /**\n * Resets the rolling average (equivalent to 0 samples taken so far)\n */\n RollingAverage.prototype.reset = function () {\n this.average = 0;\n this.variance = 0;\n this._sampleCount = 0;\n this._pos = 0;\n this._m2 = 0;\n };\n /**\n * Wraps a value around the sample range boundaries\n * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.\n * @return Wrapped position in sample range\n */\n RollingAverage.prototype._wrapPosition = function (i) {\n var max = this._samples.length;\n return ((i % max) + max) % max;\n };\n return RollingAverage;\n }());\n BABYLON.RollingAverage = RollingAverage;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.performanceMonitor.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * \"Static Class\" containing the most commonly used helper while dealing with material for\n * rendering purpose.\n *\n * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.\n *\n * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.\n */\n var MaterialHelper = /** @class */ (function () {\n function MaterialHelper() {\n }\n /**\n * Bind the current view position to an effect.\n * @param effect The effect to be bound\n * @param scene The scene the eyes position is used from\n */\n MaterialHelper.BindEyePosition = function (effect, scene) {\n if (scene._forcedViewPosition) {\n effect.setVector3(\"vEyePosition\", scene._forcedViewPosition);\n return;\n }\n effect.setVector3(\"vEyePosition\", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);\n };\n /**\n * Helps preparing the defines values about the UVs in used in the effect.\n * UVs are shared as much as we can accross chanels in the shaders.\n * @param texture The texture we are preparing the UVs for\n * @param defines The defines to update\n * @param key The chanel key \"diffuse\", \"specular\"... used in the shader\n */\n MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {\n defines._needUVs = true;\n defines[key] = true;\n if (texture.getTextureMatrix().isIdentity(true)) {\n defines[key + \"DIRECTUV\"] = texture.coordinatesIndex + 1;\n if (texture.coordinatesIndex === 0) {\n defines[\"MAINUV1\"] = true;\n }\n else {\n defines[\"MAINUV2\"] = true;\n }\n }\n else {\n defines[key + \"DIRECTUV\"] = 0;\n }\n };\n /**\n * Binds a texture matrix value to its corrsponding uniform\n * @param texture The texture to bind the matrix for\n * @param uniformBuffer The uniform buffer receivin the data\n * @param key The chanel key \"diffuse\", \"specular\"... used in the shader\n */\n MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {\n var matrix = texture.getTextureMatrix();\n if (!matrix.isIdentity(true)) {\n uniformBuffer.updateMatrix(key + \"Matrix\", matrix);\n }\n };\n /**\n * Helper used to prepare the list of defines associated with misc. values for shader compilation\n * @param mesh defines the current mesh\n * @param scene defines the current scene\n * @param useLogarithmicDepth defines if logarithmic depth has to be turned on\n * @param pointsCloud defines if point cloud rendering has to be turned on\n * @param fogEnabled defines if fog has to be turned on\n * @param alphaTest defines if alpha testing has to be turned on\n * @param defines defines the current list of defines\n */\n MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {\n if (defines._areMiscDirty) {\n defines[\"LOGARITHMICDEPTH\"] = useLogarithmicDepth;\n defines[\"POINTSIZE\"] = pointsCloud;\n defines[\"FOG\"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);\n defines[\"NONUNIFORMSCALING\"] = mesh.nonUniformScaling;\n defines[\"ALPHATEST\"] = alphaTest;\n }\n };\n /**\n * Helper used to prepare the list of defines associated with frame values for shader compilation\n * @param scene defines the current scene\n * @param engine defines the current engine\n * @param defines specifies the list of active defines\n * @param useInstances defines if instances have to be turned on\n * @param useClipPlane defines if clip plane have to be turned on\n */\n MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {\n if (useClipPlane === void 0) { useClipPlane = null; }\n var changed = false;\n if (useClipPlane == null) {\n useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);\n }\n if (defines[\"CLIPPLANE\"] !== useClipPlane) {\n defines[\"CLIPPLANE\"] = useClipPlane;\n changed = true;\n }\n if (defines[\"DEPTHPREPASS\"] !== !engine.getColorWrite()) {\n defines[\"DEPTHPREPASS\"] = !defines[\"DEPTHPREPASS\"];\n changed = true;\n }\n if (defines[\"INSTANCES\"] !== useInstances) {\n defines[\"INSTANCES\"] = useInstances;\n changed = true;\n }\n if (changed) {\n defines.markAsUnprocessed();\n }\n };\n /**\n * Prepares the defines used in the shader depending on the attributes data available in the mesh\n * @param mesh The mesh containing the geometry data we will draw\n * @param defines The defines to update\n * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)\n * @param useBones Precise whether bones should be used or not (override mesh info)\n * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)\n * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)\n * @returns false if defines are considered not dirty and have not been checked\n */\n MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {\n if (useMorphTargets === void 0) { useMorphTargets = false; }\n if (useVertexAlpha === void 0) { useVertexAlpha = true; }\n if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {\n return false;\n }\n defines._normals = defines._needNormals;\n defines._uvs = defines._needUVs;\n defines[\"NORMAL\"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));\n if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {\n defines[\"TANGENT\"] = true;\n }\n if (defines._needUVs) {\n defines[\"UV1\"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);\n defines[\"UV2\"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);\n }\n else {\n defines[\"UV1\"] = false;\n defines[\"UV2\"] = false;\n }\n if (useVertexColor) {\n var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);\n defines[\"VERTEXCOLOR\"] = hasVertexColors;\n defines[\"VERTEXALPHA\"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;\n }\n if (useBones) {\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n defines[\"NUM_BONE_INFLUENCERS\"] = mesh.numBoneInfluencers;\n defines[\"BonesPerMesh\"] = (mesh.skeleton.bones.length + 1);\n }\n else {\n defines[\"NUM_BONE_INFLUENCERS\"] = 0;\n defines[\"BonesPerMesh\"] = 0;\n }\n }\n if (useMorphTargets) {\n var manager = mesh.morphTargetManager;\n if (manager) {\n defines[\"MORPHTARGETS_TANGENT\"] = manager.supportsTangents && defines[\"TANGENT\"];\n defines[\"MORPHTARGETS_NORMAL\"] = manager.supportsNormals && defines[\"NORMAL\"];\n defines[\"MORPHTARGETS\"] = (manager.numInfluencers > 0);\n defines[\"NUM_MORPH_INFLUENCERS\"] = manager.numInfluencers;\n }\n else {\n defines[\"MORPHTARGETS_TANGENT\"] = false;\n defines[\"MORPHTARGETS_NORMAL\"] = false;\n defines[\"MORPHTARGETS\"] = false;\n defines[\"NUM_MORPH_INFLUENCERS\"] = 0;\n }\n }\n return true;\n };\n /**\n * Prepares the defines related to the light information passed in parameter\n * @param scene The scene we are intending to draw\n * @param mesh The mesh the effect is compiling for\n * @param defines The defines to update\n * @param specularSupported Specifies whether specular is supported or not (override lights data)\n * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max\n * @param disableLighting Specifies whether the lighting is disabled (override scene and light)\n * @returns true if normals will be required for the rest of the effect\n */\n MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {\n if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }\n if (disableLighting === void 0) { disableLighting = false; }\n if (!defines._areLightsDirty) {\n return defines._needNormals;\n }\n var lightIndex = 0;\n var needNormals = false;\n var needRebuild = false;\n var lightmapMode = false;\n var shadowEnabled = false;\n var specularEnabled = false;\n if (scene.lightsEnabled && !disableLighting) {\n for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {\n var light = _a[_i];\n needNormals = true;\n if (defines[\"LIGHT\" + lightIndex] === undefined) {\n needRebuild = true;\n }\n defines[\"LIGHT\" + lightIndex] = true;\n defines[\"SPOTLIGHT\" + lightIndex] = false;\n defines[\"HEMILIGHT\" + lightIndex] = false;\n defines[\"POINTLIGHT\" + lightIndex] = false;\n defines[\"DIRLIGHT\" + lightIndex] = false;\n light.prepareLightSpecificDefines(defines, lightIndex);\n // Specular\n if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {\n specularEnabled = true;\n }\n // Shadows\n defines[\"SHADOW\" + lightIndex] = false;\n defines[\"SHADOWPCF\" + lightIndex] = false;\n defines[\"SHADOWPCSS\" + lightIndex] = false;\n defines[\"SHADOWPOISSON\" + lightIndex] = false;\n defines[\"SHADOWESM\" + lightIndex] = false;\n defines[\"SHADOWCUBE\" + lightIndex] = false;\n defines[\"SHADOWLOWQUALITY\" + lightIndex] = false;\n defines[\"SHADOWMEDIUMQUALITY\" + lightIndex] = false;\n if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {\n var shadowGenerator = light.getShadowGenerator();\n if (shadowGenerator) {\n var shadowMap = shadowGenerator.getShadowMap();\n if (shadowMap) {\n if (shadowMap.renderList && shadowMap.renderList.length > 0) {\n shadowEnabled = true;\n shadowGenerator.prepareDefines(defines, lightIndex);\n }\n }\n }\n }\n if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {\n lightmapMode = true;\n defines[\"LIGHTMAPEXCLUDED\" + lightIndex] = true;\n defines[\"LIGHTMAPNOSPECULAR\" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);\n }\n else {\n defines[\"LIGHTMAPEXCLUDED\" + lightIndex] = false;\n defines[\"LIGHTMAPNOSPECULAR\" + lightIndex] = false;\n }\n lightIndex++;\n if (lightIndex === maxSimultaneousLights)\n break;\n }\n }\n defines[\"SPECULARTERM\"] = specularEnabled;\n defines[\"SHADOWS\"] = shadowEnabled;\n // Resetting all other lights if any\n for (var index = lightIndex; index < maxSimultaneousLights; index++) {\n if (defines[\"LIGHT\" + index] !== undefined) {\n defines[\"LIGHT\" + index] = false;\n defines[\"HEMILIGHT\" + lightIndex] = false;\n defines[\"POINTLIGHT\" + lightIndex] = false;\n defines[\"DIRLIGHT\" + lightIndex] = false;\n defines[\"SPOTLIGHT\" + lightIndex] = false;\n defines[\"SHADOW\" + lightIndex] = false;\n }\n }\n var caps = scene.getEngine().getCaps();\n if (defines[\"SHADOWFLOAT\"] === undefined) {\n needRebuild = true;\n }\n defines[\"SHADOWFLOAT\"] = shadowEnabled &&\n ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||\n (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));\n defines[\"LIGHTMAPEXCLUDED\"] = lightmapMode;\n if (needRebuild) {\n defines.rebuild();\n }\n return needNormals;\n };\n /**\n * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms\n * that won t be acctive due to defines being turned off.\n * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information\n * @param samplersList The samplers list\n * @param defines The defines helping in the list generation\n * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect\n */\n MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {\n if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }\n var uniformsList;\n var uniformBuffersList = null;\n if (uniformsListOrOptions.uniformsNames) {\n var options = uniformsListOrOptions;\n uniformsList = options.uniformsNames;\n uniformBuffersList = options.uniformBuffersNames;\n samplersList = options.samplers;\n defines = options.defines;\n maxSimultaneousLights = options.maxSimultaneousLights;\n }\n else {\n uniformsList = uniformsListOrOptions;\n if (!samplersList) {\n samplersList = [];\n }\n }\n for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {\n if (!defines[\"LIGHT\" + lightIndex]) {\n break;\n }\n uniformsList.push(\"vLightData\" + lightIndex, \"vLightDiffuse\" + lightIndex, \"vLightSpecular\" + lightIndex, \"vLightDirection\" + lightIndex, \"vLightGround\" + lightIndex, \"lightMatrix\" + lightIndex, \"shadowsInfo\" + lightIndex, \"depthValues\" + lightIndex);\n if (uniformBuffersList) {\n uniformBuffersList.push(\"Light\" + lightIndex);\n }\n samplersList.push(\"shadowSampler\" + lightIndex);\n samplersList.push(\"depthSampler\" + lightIndex);\n if (defines[\"PROJECTEDLIGHTTEXTURE\" + lightIndex]) {\n samplersList.push(\"projectionLightSampler\" + lightIndex);\n uniformsList.push(\"textureProjectionMatrix\" + lightIndex);\n }\n }\n if (defines[\"NUM_MORPH_INFLUENCERS\"]) {\n uniformsList.push(\"morphTargetInfluences\");\n }\n };\n /**\n * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)\n * @param defines The defines to update while falling back\n * @param fallbacks The authorized effect fallbacks\n * @param maxSimultaneousLights The maximum number of lights allowed\n * @param rank the current rank of the Effect\n * @returns The newly affected rank\n */\n MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {\n if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }\n if (rank === void 0) { rank = 0; }\n var lightFallbackRank = 0;\n for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {\n if (!defines[\"LIGHT\" + lightIndex]) {\n break;\n }\n if (lightIndex > 0) {\n lightFallbackRank = rank + lightIndex;\n fallbacks.addFallback(lightFallbackRank, \"LIGHT\" + lightIndex);\n }\n if (!defines[\"SHADOWS\"]) {\n if (defines[\"SHADOW\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOW\" + lightIndex);\n }\n if (defines[\"SHADOWPCF\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWPCF\" + lightIndex);\n }\n if (defines[\"SHADOWPCSS\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWPCSS\" + lightIndex);\n }\n if (defines[\"SHADOWPOISSON\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWPOISSON\" + lightIndex);\n }\n if (defines[\"SHADOWESM\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWESM\" + lightIndex);\n }\n }\n }\n return lightFallbackRank++;\n };\n /**\n * Prepares the list of attributes required for morph targets according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param mesh The mesh to prepare the morph targets attributes for\n * @param defines The current Defines of the effect\n */\n MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {\n var influencers = defines[\"NUM_MORPH_INFLUENCERS\"];\n if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {\n var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;\n var manager = mesh.morphTargetManager;\n var normal = manager && manager.supportsNormals && defines[\"NORMAL\"];\n var tangent = manager && manager.supportsTangents && defines[\"TANGENT\"];\n for (var index = 0; index < influencers; index++) {\n attribs.push(BABYLON.VertexBuffer.PositionKind + index);\n if (normal) {\n attribs.push(BABYLON.VertexBuffer.NormalKind + index);\n }\n if (tangent) {\n attribs.push(BABYLON.VertexBuffer.TangentKind + index);\n }\n if (attribs.length > maxAttributesCount) {\n BABYLON.Tools.Error(\"Cannot add more vertex attributes for mesh \" + mesh.name);\n }\n }\n }\n };\n /**\n * Prepares the list of attributes required for bones according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param mesh The mesh to prepare the bones attributes for\n * @param defines The current Defines of the effect\n * @param fallbacks The current efffect fallback strategy\n */\n MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {\n if (defines[\"NUM_BONE_INFLUENCERS\"] > 0) {\n fallbacks.addCPUSkinningFallback(0, mesh);\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (defines[\"NUM_BONE_INFLUENCERS\"] > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n }\n };\n /**\n * Prepares the list of attributes required for instances according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param defines The current Defines of the effect\n */\n MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {\n if (defines[\"INSTANCES\"]) {\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n };\n /**\n * Binds the light shadow information to the effect for the given mesh.\n * @param light The light containing the generator\n * @param scene The scene the lights belongs to\n * @param mesh The mesh we are binding the information to render\n * @param lightIndex The light index in the effect used to render the mesh\n * @param effect The effect we are binding the data to\n */\n MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {\n if (light.shadowEnabled && mesh.receiveShadows) {\n var shadowGenerator = light.getShadowGenerator();\n if (shadowGenerator) {\n shadowGenerator.bindShadowLight(lightIndex, effect);\n }\n }\n };\n /**\n * Binds the light information to the effect.\n * @param light The light containing the generator\n * @param effect The effect we are binding the data to\n * @param lightIndex The light index in the effect used to render\n */\n MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {\n light.transferToEffect(effect, lightIndex + \"\");\n };\n /**\n * Binds the lights information from the scene to the effect for the given mesh.\n * @param scene The scene the lights belongs to\n * @param mesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n * @param defines The generated defines for the effect\n * @param maxSimultaneousLights The maximum number of light that can be bound to the effect\n * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not\n */\n MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {\n if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }\n if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }\n var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);\n for (var i = 0; i < len; i++) {\n var light = mesh._lightSources[i];\n var iAsString = i.toString();\n var scaledIntensity = light.getScaledIntensity();\n light._uniformBuffer.bindToEffect(effect, \"Light\" + i);\n MaterialHelper.BindLightProperties(light, effect, i);\n light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);\n light._uniformBuffer.updateColor4(\"vLightDiffuse\", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);\n if (defines[\"SPECULARTERM\"]) {\n light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);\n light._uniformBuffer.updateColor3(\"vLightSpecular\", BABYLON.Tmp.Color3[1], iAsString);\n }\n // Shadows\n if (scene.shadowsEnabled) {\n this.BindLightShadow(light, scene, mesh, iAsString, effect);\n }\n light._uniformBuffer.update();\n }\n };\n /**\n * Binds the fog information from the scene to the effect for the given mesh.\n * @param scene The scene the lights belongs to\n * @param mesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n */\n MaterialHelper.BindFogParameters = function (scene, mesh, effect) {\n if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {\n effect.setFloat4(\"vFogInfos\", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);\n effect.setColor3(\"vFogColor\", scene.fogColor);\n }\n };\n /**\n * Binds the bones information from the mesh to the effect.\n * @param mesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n */\n MaterialHelper.BindBonesParameters = function (mesh, effect) {\n if (!effect || !mesh) {\n return;\n }\n if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {\n mesh.computeBonesUsingShaders = false;\n }\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n var matrices = mesh.skeleton.getTransformMatrices(mesh);\n if (matrices) {\n effect.setMatrices(\"mBones\", matrices);\n }\n }\n };\n /**\n * Binds the morph targets information from the mesh to the effect.\n * @param abstractMesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n */\n MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {\n var manager = abstractMesh.morphTargetManager;\n if (!abstractMesh || !manager) {\n return;\n }\n effect.setFloatArray(\"morphTargetInfluences\", manager.influences);\n };\n /**\n * Binds the logarithmic depth information from the scene to the effect for the given defines.\n * @param defines The generated defines used in the effect\n * @param effect The effect we are binding the data to\n * @param scene The scene we are willing to render with logarithmic scale for\n */\n MaterialHelper.BindLogDepth = function (defines, effect, scene) {\n if (defines[\"LOGARITHMICDEPTH\"]) {\n effect.setFloat(\"logarithmicDepthConstant\", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));\n }\n };\n /**\n * Binds the clip plane information from the scene to the effect.\n * @param scene The scene the clip plane information are extracted from\n * @param effect The effect we are binding the data to\n */\n MaterialHelper.BindClipPlane = function (effect, scene) {\n if (scene.clipPlane) {\n var clipPlane = scene.clipPlane;\n effect.setFloat4(\"vClipPlane\", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);\n }\n };\n return MaterialHelper;\n }());\n BABYLON.MaterialHelper = MaterialHelper;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.materialHelper.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var PushMaterial = /** @class */ (function (_super) {\n __extends(PushMaterial, _super);\n function PushMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._normalMatrix = new BABYLON.Matrix();\n _this.storeEffectOnSubMeshes = true;\n return _this;\n }\n PushMaterial.prototype.getEffect = function () {\n return this._activeEffect;\n };\n PushMaterial.prototype.isReady = function (mesh, useInstances) {\n if (!mesh) {\n return false;\n }\n if (!mesh.subMeshes || mesh.subMeshes.length === 0) {\n return true;\n }\n return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);\n };\n /**\n * Binds the given world matrix to the active effect\n *\n * @param world the matrix to bind\n */\n PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {\n this._activeEffect.setMatrix(\"world\", world);\n };\n /**\n * Binds the given normal matrix to the active effect\n *\n * @param normalMatrix the matrix to bind\n */\n PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {\n this._activeEffect.setMatrix(\"normalMatrix\", normalMatrix);\n };\n PushMaterial.prototype.bind = function (world, mesh) {\n if (!mesh) {\n return;\n }\n this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);\n };\n PushMaterial.prototype._afterBind = function (mesh, effect) {\n if (effect === void 0) { effect = null; }\n _super.prototype._afterBind.call(this, mesh);\n this.getScene()._cachedEffect = effect;\n };\n PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {\n if (visibility === void 0) { visibility = 1; }\n return scene.isCachedMaterialInvalid(this, effect, visibility);\n };\n return PushMaterial;\n }(BABYLON.Material));\n BABYLON.PushMaterial = PushMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pushMaterial.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /** @hidden */\n var StandardMaterialDefines = /** @class */ (function (_super) {\n __extends(StandardMaterialDefines, _super);\n function StandardMaterialDefines() {\n var _this = _super.call(this) || this;\n _this.MAINUV1 = false;\n _this.MAINUV2 = false;\n _this.DIFFUSE = false;\n _this.DIFFUSEDIRECTUV = 0;\n _this.AMBIENT = false;\n _this.AMBIENTDIRECTUV = 0;\n _this.OPACITY = false;\n _this.OPACITYDIRECTUV = 0;\n _this.OPACITYRGB = false;\n _this.REFLECTION = false;\n _this.EMISSIVE = false;\n _this.EMISSIVEDIRECTUV = 0;\n _this.SPECULAR = false;\n _this.SPECULARDIRECTUV = 0;\n _this.BUMP = false;\n _this.BUMPDIRECTUV = 0;\n _this.PARALLAX = false;\n _this.PARALLAXOCCLUSION = false;\n _this.SPECULAROVERALPHA = false;\n _this.CLIPPLANE = false;\n _this.ALPHATEST = false;\n _this.DEPTHPREPASS = false;\n _this.ALPHAFROMDIFFUSE = false;\n _this.POINTSIZE = false;\n _this.FOG = false;\n _this.SPECULARTERM = false;\n _this.DIFFUSEFRESNEL = false;\n _this.OPACITYFRESNEL = false;\n _this.REFLECTIONFRESNEL = false;\n _this.REFRACTIONFRESNEL = false;\n _this.EMISSIVEFRESNEL = false;\n _this.FRESNEL = false;\n _this.NORMAL = false;\n _this.UV1 = false;\n _this.UV2 = false;\n _this.VERTEXCOLOR = false;\n _this.VERTEXALPHA = false;\n _this.NUM_BONE_INFLUENCERS = 0;\n _this.BonesPerMesh = 0;\n _this.INSTANCES = false;\n _this.GLOSSINESS = false;\n _this.ROUGHNESS = false;\n _this.EMISSIVEASILLUMINATION = false;\n _this.LINKEMISSIVEWITHDIFFUSE = false;\n _this.REFLECTIONFRESNELFROMSPECULAR = false;\n _this.LIGHTMAP = false;\n _this.LIGHTMAPDIRECTUV = 0;\n _this.OBJECTSPACE_NORMALMAP = false;\n _this.USELIGHTMAPASSHADOWMAP = false;\n _this.REFLECTIONMAP_3D = false;\n _this.REFLECTIONMAP_SPHERICAL = false;\n _this.REFLECTIONMAP_PLANAR = false;\n _this.REFLECTIONMAP_CUBIC = false;\n _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\n _this.REFLECTIONMAP_PROJECTION = false;\n _this.REFLECTIONMAP_SKYBOX = false;\n _this.REFLECTIONMAP_EXPLICIT = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n _this.INVERTCUBICMAP = false;\n _this.LOGARITHMICDEPTH = false;\n _this.REFRACTION = false;\n _this.REFRACTIONMAP_3D = false;\n _this.REFLECTIONOVERALPHA = false;\n _this.TWOSIDEDLIGHTING = false;\n _this.SHADOWFLOAT = false;\n _this.MORPHTARGETS = false;\n _this.MORPHTARGETS_NORMAL = false;\n _this.MORPHTARGETS_TANGENT = false;\n _this.NUM_MORPH_INFLUENCERS = 0;\n _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH\n _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7\n _this.IMAGEPROCESSING = false;\n _this.VIGNETTE = false;\n _this.VIGNETTEBLENDMODEMULTIPLY = false;\n _this.VIGNETTEBLENDMODEOPAQUE = false;\n _this.TONEMAPPING = false;\n _this.CONTRAST = false;\n _this.COLORCURVES = false;\n _this.COLORGRADING = false;\n _this.COLORGRADING3D = false;\n _this.SAMPLER3DGREENDEPTH = false;\n _this.SAMPLER3DBGRMAP = false;\n _this.IMAGEPROCESSINGPOSTPROCESS = false;\n /**\n * If the reflection texture on this material is in linear color space\n * @hidden\n */\n _this.IS_REFLECTION_LINEAR = false;\n /**\n * If the refraction texture on this material is in linear color space\n * @hidden\n */\n _this.IS_REFRACTION_LINEAR = false;\n _this.EXPOSURE = false;\n _this.rebuild();\n return _this;\n }\n StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {\n var modes = [\n \"REFLECTIONMAP_CUBIC\", \"REFLECTIONMAP_EXPLICIT\", \"REFLECTIONMAP_PLANAR\",\n \"REFLECTIONMAP_PROJECTION\", \"REFLECTIONMAP_PROJECTION\", \"REFLECTIONMAP_SKYBOX\",\n \"REFLECTIONMAP_SPHERICAL\", \"REFLECTIONMAP_EQUIRECTANGULAR\", \"REFLECTIONMAP_EQUIRECTANGULAR_FIXED\",\n \"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\"\n ];\n for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {\n var mode = modes_1[_i];\n this[mode] = (mode === modeToEnable);\n }\n };\n return StandardMaterialDefines;\n }(BABYLON.MaterialDefines));\n BABYLON.StandardMaterialDefines = StandardMaterialDefines;\n var StandardMaterial = /** @class */ (function (_super) {\n __extends(StandardMaterial, _super);\n function StandardMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this.ambientColor = new BABYLON.Color3(0, 0, 0);\n _this.diffuseColor = new BABYLON.Color3(1, 1, 1);\n _this.specularColor = new BABYLON.Color3(1, 1, 1);\n _this.emissiveColor = new BABYLON.Color3(0, 0, 0);\n _this.specularPower = 64;\n _this._useAlphaFromDiffuseTexture = false;\n _this._useEmissiveAsIllumination = false;\n _this._linkEmissiveWithDiffuse = false;\n _this._useSpecularOverAlpha = false;\n _this._useReflectionOverAlpha = false;\n _this._disableLighting = false;\n _this._useObjectSpaceNormalMap = false;\n _this._useParallax = false;\n _this._useParallaxOcclusion = false;\n _this.parallaxScaleBias = 0.05;\n _this._roughness = 0;\n _this.indexOfRefraction = 0.98;\n _this.invertRefractionY = true;\n /**\n * Defines the alpha limits in alpha test mode\n */\n _this.alphaCutOff = 0.4;\n _this._useLightmapAsShadowmap = false;\n _this._useReflectionFresnelFromSpecular = false;\n _this._useGlossinessFromSpecularMapAlpha = false;\n _this._maxSimultaneousLights = 4;\n /**\n * If sets to true, x component of normal map value will invert (x = 1.0 - x).\n */\n _this._invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will invert (y = 1.0 - y).\n */\n _this._invertNormalMapY = false;\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n */\n _this._twoSidedLighting = false;\n _this._renderTargets = new BABYLON.SmartArray(16);\n _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();\n _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);\n // Setup the default processing configuration to the scene.\n _this._attachImageProcessingConfiguration(null);\n _this.getRenderTargetTextures = function () {\n _this._renderTargets.reset();\n if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {\n _this._renderTargets.push(_this._reflectionTexture);\n }\n if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {\n _this._renderTargets.push(_this._refractionTexture);\n }\n return _this._renderTargets;\n };\n return _this;\n }\n Object.defineProperty(StandardMaterial.prototype, \"imageProcessingConfiguration\", {\n /**\n * Gets the image processing configuration used either in this material.\n */\n get: function () {\n return this._imageProcessingConfiguration;\n },\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set: function (value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Attaches a new image processing configuration to the Standard Material.\n * @param configuration\n */\n StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {\n var _this = this;\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {\n _this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n };\n Object.defineProperty(StandardMaterial.prototype, \"cameraColorCurvesEnabled\", {\n /**\n * Gets wether the color curves effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n },\n /**\n * Sets wether the color curves effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial.prototype, \"cameraColorGradingEnabled\", {\n /**\n * Gets wether the color grading effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n },\n /**\n * Gets wether the color grading effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial.prototype, \"cameraToneMappingEnabled\", {\n /**\n * Gets wether tonemapping is enabled or not.\n */\n get: function () {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n },\n /**\n * Sets wether tonemapping is enabled or not\n */\n set: function (value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(StandardMaterial.prototype, \"cameraExposure\", {\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n get: function () {\n return this._imageProcessingConfiguration.exposure;\n },\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n set: function (value) {\n this._imageProcessingConfiguration.exposure = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(StandardMaterial.prototype, \"cameraContrast\", {\n /**\n * Gets The camera contrast used on this material.\n */\n get: function () {\n return this._imageProcessingConfiguration.contrast;\n },\n /**\n * Sets The camera contrast used on this material.\n */\n set: function (value) {\n this._imageProcessingConfiguration.contrast = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial.prototype, \"cameraColorGradingTexture\", {\n /**\n * Gets the Color Grading 2D Lookup Texture.\n */\n get: function () {\n return this._imageProcessingConfiguration.colorGradingTexture;\n },\n /**\n * Sets the Color Grading 2D Lookup Texture.\n */\n set: function (value) {\n this._imageProcessingConfiguration.colorGradingTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial.prototype, \"cameraColorCurves\", {\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n get: function () {\n return this._imageProcessingConfiguration.colorCurves;\n },\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n set: function (value) {\n this._imageProcessingConfiguration.colorCurves = value;\n },\n enumerable: true,\n configurable: true\n });\n StandardMaterial.prototype.getClassName = function () {\n return \"StandardMaterial\";\n };\n Object.defineProperty(StandardMaterial.prototype, \"useLogarithmicDepth\", {\n get: function () {\n return this._useLogarithmicDepth;\n },\n set: function (value) {\n this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;\n this._markAllSubMeshesAsMiscDirty();\n },\n enumerable: true,\n configurable: true\n });\n StandardMaterial.prototype.needAlphaBlending = function () {\n return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;\n };\n StandardMaterial.prototype.needAlphaTesting = function () {\n return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;\n };\n StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {\n return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;\n };\n StandardMaterial.prototype.getAlphaTestTexture = function () {\n return this._diffuseTexture;\n };\n /**\n * Child classes can use it to update shaders\n */\n StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {\n if (useInstances === void 0) { useInstances = false; }\n if (subMesh.effect && this.isFrozen) {\n if (this._wasPreviouslyReady) {\n return true;\n }\n }\n if (!subMesh._materialDefines) {\n subMesh._materialDefines = new StandardMaterialDefines();\n }\n var scene = this.getScene();\n var defines = subMesh._materialDefines;\n if (!this.checkReadyOnEveryCall && subMesh.effect) {\n if (defines._renderId === scene.getRenderId()) {\n return true;\n }\n }\n var engine = scene.getEngine();\n // Lights\n defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);\n // Textures\n if (defines._areTexturesDirty) {\n defines._needUVs = false;\n defines.MAINUV1 = false;\n defines.MAINUV2 = false;\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {\n if (!this._diffuseTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, \"DIFFUSE\");\n }\n }\n else {\n defines.DIFFUSE = false;\n }\n if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {\n if (!this._ambientTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, \"AMBIENT\");\n }\n }\n else {\n defines.AMBIENT = false;\n }\n if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {\n if (!this._opacityTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, \"OPACITY\");\n defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;\n }\n }\n else {\n defines.OPACITY = false;\n }\n if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {\n if (!this._reflectionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n defines._needNormals = true;\n defines.REFLECTION = true;\n defines.ROUGHNESS = (this._roughness > 0);\n defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;\n defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);\n defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;\n switch (this._reflectionTexture.coordinatesMode) {\n case BABYLON.Texture.EXPLICIT_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_EXPLICIT\");\n break;\n case BABYLON.Texture.PLANAR_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_PLANAR\");\n break;\n case BABYLON.Texture.PROJECTION_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_PROJECTION\");\n break;\n case BABYLON.Texture.SKYBOX_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_SKYBOX\");\n break;\n case BABYLON.Texture.SPHERICAL_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_SPHERICAL\");\n break;\n case BABYLON.Texture.EQUIRECTANGULAR_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_EQUIRECTANGULAR\");\n break;\n case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_EQUIRECTANGULAR_FIXED\");\n break;\n case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\");\n break;\n case BABYLON.Texture.CUBIC_MODE:\n case BABYLON.Texture.INVCUBIC_MODE:\n default:\n defines.setReflectionMode(\"REFLECTIONMAP_CUBIC\");\n break;\n }\n defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;\n }\n }\n else {\n defines.REFLECTION = false;\n }\n if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {\n if (!this._emissiveTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, \"EMISSIVE\");\n }\n }\n else {\n defines.EMISSIVE = false;\n }\n if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {\n if (!this._lightmapTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, \"LIGHTMAP\");\n defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;\n }\n }\n else {\n defines.LIGHTMAP = false;\n }\n if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {\n if (!this._specularTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, \"SPECULAR\");\n defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;\n }\n }\n else {\n defines.SPECULAR = false;\n }\n if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {\n // Bump texure can not be not blocking.\n if (!this._bumpTexture.isReady()) {\n return false;\n }\n else {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, \"BUMP\");\n defines.PARALLAX = this._useParallax;\n defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;\n }\n defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;\n }\n else {\n defines.BUMP = false;\n }\n if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {\n if (!this._refractionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n defines._needUVs = true;\n defines.REFRACTION = true;\n defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;\n }\n }\n else {\n defines.REFRACTION = false;\n }\n defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;\n }\n else {\n defines.DIFFUSE = false;\n defines.AMBIENT = false;\n defines.OPACITY = false;\n defines.REFLECTION = false;\n defines.EMISSIVE = false;\n defines.LIGHTMAP = false;\n defines.BUMP = false;\n defines.REFRACTION = false;\n }\n defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();\n defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;\n defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;\n defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;\n defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n if (!this._imageProcessingConfiguration.isReady()) {\n return false;\n }\n this._imageProcessingConfiguration.prepareDefines(defines);\n defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);\n defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);\n }\n if (defines._areFresnelDirty) {\n if (StandardMaterial.FresnelEnabled) {\n // Fresnel\n if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||\n this._emissiveFresnelParameters || this._refractionFresnelParameters ||\n this._reflectionFresnelParameters) {\n defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);\n defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);\n defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);\n defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;\n defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);\n defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);\n defines._needNormals = true;\n defines.FRESNEL = true;\n }\n }\n else {\n defines.FRESNEL = false;\n }\n }\n // Misc.\n BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);\n // Attribs\n BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);\n // Values that need to be evaluated on every frame\n BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);\n // Get correct effect \n if (defines.isDirty) {\n defines.markAsProcessed();\n scene.resetCachedMaterial();\n // Fallbacks\n var fallbacks = new BABYLON.EffectFallbacks();\n if (defines.REFLECTION) {\n fallbacks.addFallback(0, \"REFLECTION\");\n }\n if (defines.SPECULAR) {\n fallbacks.addFallback(0, \"SPECULAR\");\n }\n if (defines.BUMP) {\n fallbacks.addFallback(0, \"BUMP\");\n }\n if (defines.PARALLAX) {\n fallbacks.addFallback(1, \"PARALLAX\");\n }\n if (defines.PARALLAXOCCLUSION) {\n fallbacks.addFallback(0, \"PARALLAXOCCLUSION\");\n }\n if (defines.SPECULAROVERALPHA) {\n fallbacks.addFallback(0, \"SPECULAROVERALPHA\");\n }\n if (defines.FOG) {\n fallbacks.addFallback(1, \"FOG\");\n }\n if (defines.POINTSIZE) {\n fallbacks.addFallback(0, \"POINTSIZE\");\n }\n if (defines.LOGARITHMICDEPTH) {\n fallbacks.addFallback(0, \"LOGARITHMICDEPTH\");\n }\n BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);\n if (defines.SPECULARTERM) {\n fallbacks.addFallback(0, \"SPECULARTERM\");\n }\n if (defines.DIFFUSEFRESNEL) {\n fallbacks.addFallback(1, \"DIFFUSEFRESNEL\");\n }\n if (defines.OPACITYFRESNEL) {\n fallbacks.addFallback(2, \"OPACITYFRESNEL\");\n }\n if (defines.REFLECTIONFRESNEL) {\n fallbacks.addFallback(3, \"REFLECTIONFRESNEL\");\n }\n if (defines.EMISSIVEFRESNEL) {\n fallbacks.addFallback(4, \"EMISSIVEFRESNEL\");\n }\n if (defines.FRESNEL) {\n fallbacks.addFallback(4, \"FRESNEL\");\n }\n //Attributes\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n if (defines.NORMAL) {\n attribs.push(BABYLON.VertexBuffer.NormalKind);\n }\n if (defines.UV1) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n }\n if (defines.UV2) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n }\n if (defines.VERTEXCOLOR) {\n attribs.push(BABYLON.VertexBuffer.ColorKind);\n }\n BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);\n BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);\n BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);\n var shaderName = \"default\";\n var uniforms = [\"world\", \"view\", \"viewProjection\", \"vEyePosition\", \"vLightsType\", \"vAmbientColor\", \"vDiffuseColor\", \"vSpecularColor\", \"vEmissiveColor\",\n \"vFogInfos\", \"vFogColor\", \"pointSize\",\n \"vDiffuseInfos\", \"vAmbientInfos\", \"vOpacityInfos\", \"vReflectionInfos\", \"vEmissiveInfos\", \"vSpecularInfos\", \"vBumpInfos\", \"vLightmapInfos\", \"vRefractionInfos\",\n \"mBones\",\n \"vClipPlane\", \"diffuseMatrix\", \"ambientMatrix\", \"opacityMatrix\", \"reflectionMatrix\", \"emissiveMatrix\", \"specularMatrix\", \"bumpMatrix\", \"normalMatrix\", \"lightmapMatrix\", \"refractionMatrix\",\n \"diffuseLeftColor\", \"diffuseRightColor\", \"opacityParts\", \"reflectionLeftColor\", \"reflectionRightColor\", \"emissiveLeftColor\", \"emissiveRightColor\", \"refractionLeftColor\", \"refractionRightColor\",\n \"vReflectionPosition\", \"vReflectionSize\",\n \"logarithmicDepthConstant\", \"vTangentSpaceParams\", \"alphaCutOff\"\n ];\n var samplers = [\"diffuseSampler\", \"ambientSampler\", \"opacitySampler\", \"reflectionCubeSampler\", \"reflection2DSampler\", \"emissiveSampler\", \"specularSampler\", \"bumpSampler\", \"lightmapSampler\", \"refractionCubeSampler\", \"refraction2DSampler\"];\n var uniformBuffers = [\"Material\", \"Scene\"];\n if (BABYLON.ImageProcessingConfiguration) {\n BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);\n BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);\n }\n BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: defines,\n maxSimultaneousLights: this._maxSimultaneousLights\n });\n if (this.customShaderNameResolve) {\n shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);\n }\n var join = defines.toString();\n subMesh.setEffect(scene.getEngine().createEffect(shaderName, {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: this.onCompiled,\n onError: this.onError,\n indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }\n }, engine), defines);\n this.buildUniformLayout();\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n this._wasPreviouslyReady = true;\n return true;\n };\n StandardMaterial.prototype.buildUniformLayout = function () {\n // Order is important !\n this._uniformBuffer.addUniform(\"diffuseLeftColor\", 4);\n this._uniformBuffer.addUniform(\"diffuseRightColor\", 4);\n this._uniformBuffer.addUniform(\"opacityParts\", 4);\n this._uniformBuffer.addUniform(\"reflectionLeftColor\", 4);\n this._uniformBuffer.addUniform(\"reflectionRightColor\", 4);\n this._uniformBuffer.addUniform(\"refractionLeftColor\", 4);\n this._uniformBuffer.addUniform(\"refractionRightColor\", 4);\n this._uniformBuffer.addUniform(\"emissiveLeftColor\", 4);\n this._uniformBuffer.addUniform(\"emissiveRightColor\", 4);\n this._uniformBuffer.addUniform(\"vDiffuseInfos\", 2);\n this._uniformBuffer.addUniform(\"vAmbientInfos\", 2);\n this._uniformBuffer.addUniform(\"vOpacityInfos\", 2);\n this._uniformBuffer.addUniform(\"vReflectionInfos\", 2);\n this._uniformBuffer.addUniform(\"vReflectionPosition\", 3);\n this._uniformBuffer.addUniform(\"vReflectionSize\", 3);\n this._uniformBuffer.addUniform(\"vEmissiveInfos\", 2);\n this._uniformBuffer.addUniform(\"vLightmapInfos\", 2);\n this._uniformBuffer.addUniform(\"vSpecularInfos\", 2);\n this._uniformBuffer.addUniform(\"vBumpInfos\", 3);\n this._uniformBuffer.addUniform(\"diffuseMatrix\", 16);\n this._uniformBuffer.addUniform(\"ambientMatrix\", 16);\n this._uniformBuffer.addUniform(\"opacityMatrix\", 16);\n this._uniformBuffer.addUniform(\"reflectionMatrix\", 16);\n this._uniformBuffer.addUniform(\"emissiveMatrix\", 16);\n this._uniformBuffer.addUniform(\"lightmapMatrix\", 16);\n this._uniformBuffer.addUniform(\"specularMatrix\", 16);\n this._uniformBuffer.addUniform(\"bumpMatrix\", 16);\n this._uniformBuffer.addUniform(\"vTangentSpaceParams\", 2);\n this._uniformBuffer.addUniform(\"refractionMatrix\", 16);\n this._uniformBuffer.addUniform(\"vRefractionInfos\", 4);\n this._uniformBuffer.addUniform(\"vSpecularColor\", 4);\n this._uniformBuffer.addUniform(\"vEmissiveColor\", 3);\n this._uniformBuffer.addUniform(\"vDiffuseColor\", 4);\n this._uniformBuffer.addUniform(\"pointSize\", 1);\n this._uniformBuffer.create();\n };\n StandardMaterial.prototype.unbind = function () {\n if (this._activeEffect) {\n var needFlag = false;\n if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._activeEffect.setTexture(\"reflection2DSampler\", null);\n needFlag = true;\n }\n if (this._refractionTexture && this._refractionTexture.isRenderTarget) {\n this._activeEffect.setTexture(\"refraction2DSampler\", null);\n needFlag = true;\n }\n if (needFlag) {\n this._markAllSubMeshesAsTexturesDirty();\n }\n }\n _super.prototype.unbind.call(this);\n };\n StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {\n var scene = this.getScene();\n var defines = subMesh._materialDefines;\n if (!defines) {\n return;\n }\n var effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices \n this.bindOnlyWorldMatrix(world);\n // Normal Matrix\n if (defines.OBJECTSPACE_NORMALMAP) {\n world.toNormalMatrix(this._normalMatrix);\n this.bindOnlyNormalMatrix(this._normalMatrix);\n }\n var mustRebind = this._mustRebind(scene, effect, mesh.visibility);\n // Bones\n BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);\n if (mustRebind) {\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this.bindViewProjection(effect);\n if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {\n if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {\n // Fresnel\n if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {\n this._uniformBuffer.updateColor4(\"diffuseLeftColor\", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);\n this._uniformBuffer.updateColor4(\"diffuseRightColor\", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);\n }\n if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {\n this._uniformBuffer.updateColor4(\"opacityParts\", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);\n }\n if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {\n this._uniformBuffer.updateColor4(\"reflectionLeftColor\", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);\n this._uniformBuffer.updateColor4(\"reflectionRightColor\", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);\n }\n if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {\n this._uniformBuffer.updateColor4(\"refractionLeftColor\", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);\n this._uniformBuffer.updateColor4(\"refractionRightColor\", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);\n }\n if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {\n this._uniformBuffer.updateColor4(\"emissiveLeftColor\", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);\n this._uniformBuffer.updateColor4(\"emissiveRightColor\", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);\n }\n }\n // Textures \n if (scene.texturesEnabled) {\n if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vDiffuseInfos\", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, \"diffuse\");\n if (this._diffuseTexture.hasAlpha) {\n effect.setFloat(\"alphaCutOff\", this.alphaCutOff);\n }\n }\n if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vAmbientInfos\", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, \"ambient\");\n }\n if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vOpacityInfos\", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, \"opacity\");\n }\n if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vReflectionInfos\", this._reflectionTexture.level, this.roughness);\n this._uniformBuffer.updateMatrix(\"reflectionMatrix\", this._reflectionTexture.getReflectionTextureMatrix());\n if (this._reflectionTexture.boundingBoxSize) {\n var cubeTexture = this._reflectionTexture;\n this._uniformBuffer.updateVector3(\"vReflectionPosition\", cubeTexture.boundingBoxPosition);\n this._uniformBuffer.updateVector3(\"vReflectionSize\", cubeTexture.boundingBoxSize);\n }\n }\n if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vEmissiveInfos\", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, \"emissive\");\n }\n if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vLightmapInfos\", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, \"lightmap\");\n }\n if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vSpecularInfos\", this._specularTexture.coordinatesIndex, this._specularTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, \"specular\");\n }\n if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {\n this._uniformBuffer.updateFloat3(\"vBumpInfos\", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);\n BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, \"bump\");\n if (scene._mirroredCameraPosition) {\n this._uniformBuffer.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);\n }\n else {\n this._uniformBuffer.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);\n }\n }\n if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {\n var depth = 1.0;\n if (!this._refractionTexture.isCube) {\n this._uniformBuffer.updateMatrix(\"refractionMatrix\", this._refractionTexture.getReflectionTextureMatrix());\n if (this._refractionTexture.depth) {\n depth = this._refractionTexture.depth;\n }\n }\n this._uniformBuffer.updateFloat4(\"vRefractionInfos\", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);\n }\n }\n // Point size\n if (this.pointsCloud) {\n this._uniformBuffer.updateFloat(\"pointSize\", this.pointSize);\n }\n if (defines.SPECULARTERM) {\n this._uniformBuffer.updateColor4(\"vSpecularColor\", this.specularColor, this.specularPower);\n }\n this._uniformBuffer.updateColor3(\"vEmissiveColor\", this.emissiveColor);\n // Diffuse\n this._uniformBuffer.updateColor4(\"vDiffuseColor\", this.diffuseColor, this.alpha * mesh.visibility);\n }\n // Textures \n if (scene.texturesEnabled) {\n if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {\n effect.setTexture(\"diffuseSampler\", this._diffuseTexture);\n }\n if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {\n effect.setTexture(\"ambientSampler\", this._ambientTexture);\n }\n if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {\n effect.setTexture(\"opacitySampler\", this._opacityTexture);\n }\n if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {\n if (this._reflectionTexture.isCube) {\n effect.setTexture(\"reflectionCubeSampler\", this._reflectionTexture);\n }\n else {\n effect.setTexture(\"reflection2DSampler\", this._reflectionTexture);\n }\n }\n if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {\n effect.setTexture(\"emissiveSampler\", this._emissiveTexture);\n }\n if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {\n effect.setTexture(\"lightmapSampler\", this._lightmapTexture);\n }\n if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {\n effect.setTexture(\"specularSampler\", this._specularTexture);\n }\n if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {\n effect.setTexture(\"bumpSampler\", this._bumpTexture);\n }\n if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {\n var depth = 1.0;\n if (this._refractionTexture.isCube) {\n effect.setTexture(\"refractionCubeSampler\", this._refractionTexture);\n }\n else {\n effect.setTexture(\"refraction2DSampler\", this._refractionTexture);\n }\n }\n }\n // Clip plane\n BABYLON.MaterialHelper.BindClipPlane(effect, scene);\n // Colors\n scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);\n BABYLON.MaterialHelper.BindEyePosition(effect, scene);\n effect.setColor3(\"vAmbientColor\", this._globalAmbientColor);\n }\n if (mustRebind || !this.isFrozen) {\n // Lights\n if (scene.lightsEnabled && !this._disableLighting) {\n BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);\n }\n // View\n if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {\n this.bindView(effect);\n }\n // Fog\n BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);\n // Morph targets\n if (defines.NUM_MORPH_INFLUENCERS) {\n BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);\n }\n // Log. depth\n BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);\n // image processing\n if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {\n this._imageProcessingConfiguration.bind(this._activeEffect);\n }\n }\n this._uniformBuffer.update();\n this._afterBind(mesh, this._activeEffect);\n };\n StandardMaterial.prototype.getAnimatables = function () {\n var results = [];\n if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {\n results.push(this._diffuseTexture);\n }\n if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {\n results.push(this._ambientTexture);\n }\n if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {\n results.push(this._opacityTexture);\n }\n if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {\n results.push(this._reflectionTexture);\n }\n if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {\n results.push(this._emissiveTexture);\n }\n if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {\n results.push(this._specularTexture);\n }\n if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {\n results.push(this._bumpTexture);\n }\n if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {\n results.push(this._lightmapTexture);\n }\n if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {\n results.push(this._refractionTexture);\n }\n return results;\n };\n StandardMaterial.prototype.getActiveTextures = function () {\n var activeTextures = _super.prototype.getActiveTextures.call(this);\n if (this._diffuseTexture) {\n activeTextures.push(this._diffuseTexture);\n }\n if (this._ambientTexture) {\n activeTextures.push(this._ambientTexture);\n }\n if (this._opacityTexture) {\n activeTextures.push(this._opacityTexture);\n }\n if (this._reflectionTexture) {\n activeTextures.push(this._reflectionTexture);\n }\n if (this._emissiveTexture) {\n activeTextures.push(this._emissiveTexture);\n }\n if (this._specularTexture) {\n activeTextures.push(this._specularTexture);\n }\n if (this._bumpTexture) {\n activeTextures.push(this._bumpTexture);\n }\n if (this._lightmapTexture) {\n activeTextures.push(this._lightmapTexture);\n }\n if (this._refractionTexture) {\n activeTextures.push(this._refractionTexture);\n }\n return activeTextures;\n };\n StandardMaterial.prototype.hasTexture = function (texture) {\n if (_super.prototype.hasTexture.call(this, texture)) {\n return true;\n }\n if (this._diffuseTexture === texture) {\n return true;\n }\n if (this._ambientTexture === texture) {\n return true;\n }\n if (this._opacityTexture === texture) {\n return true;\n }\n if (this._reflectionTexture === texture) {\n return true;\n }\n if (this._emissiveTexture === texture) {\n return true;\n }\n if (this._specularTexture === texture) {\n return true;\n }\n if (this._bumpTexture === texture) {\n return true;\n }\n if (this._lightmapTexture === texture) {\n return true;\n }\n if (this._refractionTexture === texture) {\n return true;\n }\n return false;\n };\n StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {\n if (forceDisposeTextures) {\n if (this._diffuseTexture) {\n this._diffuseTexture.dispose();\n }\n if (this._ambientTexture) {\n this._ambientTexture.dispose();\n }\n if (this._opacityTexture) {\n this._opacityTexture.dispose();\n }\n if (this._reflectionTexture) {\n this._reflectionTexture.dispose();\n }\n if (this._emissiveTexture) {\n this._emissiveTexture.dispose();\n }\n if (this._specularTexture) {\n this._specularTexture.dispose();\n }\n if (this._bumpTexture) {\n this._bumpTexture.dispose();\n }\n if (this._lightmapTexture) {\n this._lightmapTexture.dispose();\n }\n if (this._refractionTexture) {\n this._refractionTexture.dispose();\n }\n }\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);\n };\n StandardMaterial.prototype.clone = function (name) {\n var _this = this;\n var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);\n result.name = name;\n result.id = name;\n return result;\n };\n StandardMaterial.prototype.serialize = function () {\n return BABYLON.SerializationHelper.Serialize(this);\n };\n // Statics\n StandardMaterial.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);\n };\n Object.defineProperty(StandardMaterial, \"DiffuseTextureEnabled\", {\n get: function () {\n return StandardMaterial._DiffuseTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._DiffuseTextureEnabled === value) {\n return;\n }\n StandardMaterial._DiffuseTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"AmbientTextureEnabled\", {\n get: function () {\n return StandardMaterial._AmbientTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._AmbientTextureEnabled === value) {\n return;\n }\n StandardMaterial._AmbientTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"OpacityTextureEnabled\", {\n get: function () {\n return StandardMaterial._OpacityTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._OpacityTextureEnabled === value) {\n return;\n }\n StandardMaterial._OpacityTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"ReflectionTextureEnabled\", {\n get: function () {\n return StandardMaterial._ReflectionTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._ReflectionTextureEnabled === value) {\n return;\n }\n StandardMaterial._ReflectionTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"EmissiveTextureEnabled\", {\n get: function () {\n return StandardMaterial._EmissiveTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._EmissiveTextureEnabled === value) {\n return;\n }\n StandardMaterial._EmissiveTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"SpecularTextureEnabled\", {\n get: function () {\n return StandardMaterial._SpecularTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._SpecularTextureEnabled === value) {\n return;\n }\n StandardMaterial._SpecularTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"BumpTextureEnabled\", {\n get: function () {\n return StandardMaterial._BumpTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._BumpTextureEnabled === value) {\n return;\n }\n StandardMaterial._BumpTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"LightmapTextureEnabled\", {\n get: function () {\n return StandardMaterial._LightmapTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._LightmapTextureEnabled === value) {\n return;\n }\n StandardMaterial._LightmapTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"RefractionTextureEnabled\", {\n get: function () {\n return StandardMaterial._RefractionTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._RefractionTextureEnabled === value) {\n return;\n }\n StandardMaterial._RefractionTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"ColorGradingTextureEnabled\", {\n get: function () {\n return StandardMaterial._ColorGradingTextureEnabled;\n },\n set: function (value) {\n if (StandardMaterial._ColorGradingTextureEnabled === value) {\n return;\n }\n StandardMaterial._ColorGradingTextureEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardMaterial, \"FresnelEnabled\", {\n get: function () {\n return StandardMaterial._FresnelEnabled;\n },\n set: function (value) {\n if (StandardMaterial._FresnelEnabled === value) {\n return;\n }\n StandardMaterial._FresnelEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n // Flags used to enable or disable a type of texture for all Standard Materials\n StandardMaterial._DiffuseTextureEnabled = true;\n StandardMaterial._AmbientTextureEnabled = true;\n StandardMaterial._OpacityTextureEnabled = true;\n StandardMaterial._ReflectionTextureEnabled = true;\n StandardMaterial._EmissiveTextureEnabled = true;\n StandardMaterial._SpecularTextureEnabled = true;\n StandardMaterial._BumpTextureEnabled = true;\n StandardMaterial._LightmapTextureEnabled = true;\n StandardMaterial._RefractionTextureEnabled = true;\n StandardMaterial._ColorGradingTextureEnabled = true;\n StandardMaterial._FresnelEnabled = true;\n __decorate([\n BABYLON.serializeAsTexture(\"diffuseTexture\")\n ], StandardMaterial.prototype, \"_diffuseTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n ], StandardMaterial.prototype, \"diffuseTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"ambientTexture\")\n ], StandardMaterial.prototype, \"_ambientTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"ambientTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"opacityTexture\")\n ], StandardMaterial.prototype, \"_opacityTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n ], StandardMaterial.prototype, \"opacityTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"reflectionTexture\")\n ], StandardMaterial.prototype, \"_reflectionTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"reflectionTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"emissiveTexture\")\n ], StandardMaterial.prototype, \"_emissiveTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"emissiveTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"specularTexture\")\n ], StandardMaterial.prototype, \"_specularTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"specularTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"bumpTexture\")\n ], StandardMaterial.prototype, \"_bumpTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"bumpTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"lightmapTexture\")\n ], StandardMaterial.prototype, \"_lightmapTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"lightmapTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"refractionTexture\")\n ], StandardMaterial.prototype, \"_refractionTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"refractionTexture\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"ambient\")\n ], StandardMaterial.prototype, \"ambientColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"diffuse\")\n ], StandardMaterial.prototype, \"diffuseColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"specular\")\n ], StandardMaterial.prototype, \"specularColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"emissive\")\n ], StandardMaterial.prototype, \"emissiveColor\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardMaterial.prototype, \"specularPower\", void 0);\n __decorate([\n BABYLON.serialize(\"useAlphaFromDiffuseTexture\")\n ], StandardMaterial.prototype, \"_useAlphaFromDiffuseTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useAlphaFromDiffuseTexture\", void 0);\n __decorate([\n BABYLON.serialize(\"useEmissiveAsIllumination\")\n ], StandardMaterial.prototype, \"_useEmissiveAsIllumination\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useEmissiveAsIllumination\", void 0);\n __decorate([\n BABYLON.serialize(\"linkEmissiveWithDiffuse\")\n ], StandardMaterial.prototype, \"_linkEmissiveWithDiffuse\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"linkEmissiveWithDiffuse\", void 0);\n __decorate([\n BABYLON.serialize(\"useSpecularOverAlpha\")\n ], StandardMaterial.prototype, \"_useSpecularOverAlpha\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useSpecularOverAlpha\", void 0);\n __decorate([\n BABYLON.serialize(\"useReflectionOverAlpha\")\n ], StandardMaterial.prototype, \"_useReflectionOverAlpha\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useReflectionOverAlpha\", void 0);\n __decorate([\n BABYLON.serialize(\"disableLighting\")\n ], StandardMaterial.prototype, \"_disableLighting\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], StandardMaterial.prototype, \"disableLighting\", void 0);\n __decorate([\n BABYLON.serialize(\"useObjectSpaceNormalMap\")\n ], StandardMaterial.prototype, \"_useObjectSpaceNormalMap\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useObjectSpaceNormalMap\", void 0);\n __decorate([\n BABYLON.serialize(\"useParallax\")\n ], StandardMaterial.prototype, \"_useParallax\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useParallax\", void 0);\n __decorate([\n BABYLON.serialize(\"useParallaxOcclusion\")\n ], StandardMaterial.prototype, \"_useParallaxOcclusion\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useParallaxOcclusion\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardMaterial.prototype, \"parallaxScaleBias\", void 0);\n __decorate([\n BABYLON.serialize(\"roughness\")\n ], StandardMaterial.prototype, \"_roughness\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"roughness\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardMaterial.prototype, \"indexOfRefraction\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardMaterial.prototype, \"invertRefractionY\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardMaterial.prototype, \"alphaCutOff\", void 0);\n __decorate([\n BABYLON.serialize(\"useLightmapAsShadowmap\")\n ], StandardMaterial.prototype, \"_useLightmapAsShadowmap\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useLightmapAsShadowmap\", void 0);\n __decorate([\n BABYLON.serializeAsFresnelParameters(\"diffuseFresnelParameters\")\n ], StandardMaterial.prototype, \"_diffuseFresnelParameters\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n ], StandardMaterial.prototype, \"diffuseFresnelParameters\", void 0);\n __decorate([\n BABYLON.serializeAsFresnelParameters(\"opacityFresnelParameters\")\n ], StandardMaterial.prototype, \"_opacityFresnelParameters\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsFresnelAndMiscDirty\")\n ], StandardMaterial.prototype, \"opacityFresnelParameters\", void 0);\n __decorate([\n BABYLON.serializeAsFresnelParameters(\"reflectionFresnelParameters\")\n ], StandardMaterial.prototype, \"_reflectionFresnelParameters\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n ], StandardMaterial.prototype, \"reflectionFresnelParameters\", void 0);\n __decorate([\n BABYLON.serializeAsFresnelParameters(\"refractionFresnelParameters\")\n ], StandardMaterial.prototype, \"_refractionFresnelParameters\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n ], StandardMaterial.prototype, \"refractionFresnelParameters\", void 0);\n __decorate([\n BABYLON.serializeAsFresnelParameters(\"emissiveFresnelParameters\")\n ], StandardMaterial.prototype, \"_emissiveFresnelParameters\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n ], StandardMaterial.prototype, \"emissiveFresnelParameters\", void 0);\n __decorate([\n BABYLON.serialize(\"useReflectionFresnelFromSpecular\")\n ], StandardMaterial.prototype, \"_useReflectionFresnelFromSpecular\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n ], StandardMaterial.prototype, \"useReflectionFresnelFromSpecular\", void 0);\n __decorate([\n BABYLON.serialize(\"useGlossinessFromSpecularMapAlpha\")\n ], StandardMaterial.prototype, \"_useGlossinessFromSpecularMapAlpha\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"useGlossinessFromSpecularMapAlpha\", void 0);\n __decorate([\n BABYLON.serialize(\"maxSimultaneousLights\")\n ], StandardMaterial.prototype, \"_maxSimultaneousLights\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], StandardMaterial.prototype, \"maxSimultaneousLights\", void 0);\n __decorate([\n BABYLON.serialize(\"invertNormalMapX\")\n ], StandardMaterial.prototype, \"_invertNormalMapX\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"invertNormalMapX\", void 0);\n __decorate([\n BABYLON.serialize(\"invertNormalMapY\")\n ], StandardMaterial.prototype, \"_invertNormalMapY\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"invertNormalMapY\", void 0);\n __decorate([\n BABYLON.serialize(\"twoSidedLighting\")\n ], StandardMaterial.prototype, \"_twoSidedLighting\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], StandardMaterial.prototype, \"twoSidedLighting\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardMaterial.prototype, \"useLogarithmicDepth\", null);\n return StandardMaterial;\n }(BABYLON.PushMaterial));\n BABYLON.StandardMaterial = StandardMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.standardMaterial.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class representing spherical polynomial coefficients to the 3rd degree\n */\n var SphericalPolynomial = /** @class */ (function () {\n function SphericalPolynomial() {\n /**\n * The x coefficients of the spherical polynomial\n */\n this.x = BABYLON.Vector3.Zero();\n /**\n * The y coefficients of the spherical polynomial\n */\n this.y = BABYLON.Vector3.Zero();\n /**\n * The z coefficients of the spherical polynomial\n */\n this.z = BABYLON.Vector3.Zero();\n /**\n * The xx coefficients of the spherical polynomial\n */\n this.xx = BABYLON.Vector3.Zero();\n /**\n * The yy coefficients of the spherical polynomial\n */\n this.yy = BABYLON.Vector3.Zero();\n /**\n * The zz coefficients of the spherical polynomial\n */\n this.zz = BABYLON.Vector3.Zero();\n /**\n * The xy coefficients of the spherical polynomial\n */\n this.xy = BABYLON.Vector3.Zero();\n /**\n * The yz coefficients of the spherical polynomial\n */\n this.yz = BABYLON.Vector3.Zero();\n /**\n * The zx coefficients of the spherical polynomial\n */\n this.zx = BABYLON.Vector3.Zero();\n }\n /**\n * Adds an ambient color to the spherical polynomial\n * @param color the color to add\n */\n SphericalPolynomial.prototype.addAmbient = function (color) {\n var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);\n this.xx = this.xx.add(colorVector);\n this.yy = this.yy.add(colorVector);\n this.zz = this.zz.add(colorVector);\n };\n /**\n * Scales the spherical polynomial by the given amount\n * @param scale the amount to scale\n */\n SphericalPolynomial.prototype.scale = function (scale) {\n this.x = this.x.scale(scale);\n this.y = this.y.scale(scale);\n this.z = this.z.scale(scale);\n this.xx = this.xx.scale(scale);\n this.yy = this.yy.scale(scale);\n this.zz = this.zz.scale(scale);\n this.yz = this.yz.scale(scale);\n this.zx = this.zx.scale(scale);\n this.xy = this.xy.scale(scale);\n };\n /**\n * Gets the spherical polynomial from harmonics\n * @param harmonics the spherical harmonics\n * @returns the spherical polynomial\n */\n SphericalPolynomial.FromHarmonics = function (harmonics) {\n var result = new SphericalPolynomial();\n result.x = harmonics.l11.scale(1.02333);\n result.y = harmonics.l1_1.scale(1.02333);\n result.z = harmonics.l10.scale(1.02333);\n result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));\n result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));\n result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));\n result.yz = harmonics.l2_1.scale(0.858086);\n result.zx = harmonics.l21.scale(0.858086);\n result.xy = harmonics.l2_2.scale(0.858086);\n result.scale(1.0 / Math.PI);\n return result;\n };\n /**\n * Constructs a spherical polynomial from an array.\n * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)\n * @returns the spherical polynomial\n */\n SphericalPolynomial.FromArray = function (data) {\n var sp = new SphericalPolynomial();\n BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);\n BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);\n BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);\n BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);\n BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);\n BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);\n BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);\n BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);\n BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);\n return sp;\n };\n return SphericalPolynomial;\n }());\n BABYLON.SphericalPolynomial = SphericalPolynomial;\n /**\n * Class representing spherical harmonics coefficients to the 3rd degree\n */\n var SphericalHarmonics = /** @class */ (function () {\n function SphericalHarmonics() {\n /**\n * The l0,0 coefficients of the spherical harmonics\n */\n this.l00 = BABYLON.Vector3.Zero();\n /**\n * The l1,-1 coefficients of the spherical harmonics\n */\n this.l1_1 = BABYLON.Vector3.Zero();\n /**\n * The l1,0 coefficients of the spherical harmonics\n */\n this.l10 = BABYLON.Vector3.Zero();\n /**\n * The l1,1 coefficients of the spherical harmonics\n */\n this.l11 = BABYLON.Vector3.Zero();\n /**\n * The l2,-2 coefficients of the spherical harmonics\n */\n this.l2_2 = BABYLON.Vector3.Zero();\n /**\n * The l2,-1 coefficients of the spherical harmonics\n */\n this.l2_1 = BABYLON.Vector3.Zero();\n /**\n * The l2,0 coefficients of the spherical harmonics\n */\n this.l20 = BABYLON.Vector3.Zero();\n /**\n * The l2,1 coefficients of the spherical harmonics\n */\n this.l21 = BABYLON.Vector3.Zero();\n /**\n * The l2,2 coefficients of the spherical harmonics\n */\n this.lL22 = BABYLON.Vector3.Zero();\n }\n /**\n * Adds a light to the spherical harmonics\n * @param direction the direction of the light\n * @param color the color of the light\n * @param deltaSolidAngle the delta solid angle of the light\n */\n SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {\n var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);\n var c = colorVector.scale(deltaSolidAngle);\n this.l00 = this.l00.add(c.scale(0.282095));\n this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));\n this.l10 = this.l10.add(c.scale(0.488603 * direction.z));\n this.l11 = this.l11.add(c.scale(0.488603 * direction.x));\n this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));\n this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));\n this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));\n this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));\n this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));\n };\n /**\n * Scales the spherical harmonics by the given amount\n * @param scale the amount to scale\n */\n SphericalHarmonics.prototype.scale = function (scale) {\n this.l00 = this.l00.scale(scale);\n this.l1_1 = this.l1_1.scale(scale);\n this.l10 = this.l10.scale(scale);\n this.l11 = this.l11.scale(scale);\n this.l2_2 = this.l2_2.scale(scale);\n this.l2_1 = this.l2_1.scale(scale);\n this.l20 = this.l20.scale(scale);\n this.l21 = this.l21.scale(scale);\n this.lL22 = this.lL22.scale(scale);\n };\n /**\n * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.\n *\n * ```\n * E_lm = A_l * L_lm\n * ```\n *\n * In spherical harmonics this convolution amounts to scaling factors for each frequency band.\n * This corresponds to equation 5 in \"An Efficient Representation for Irradiance Environment Maps\", where\n * the scaling factors are given in equation 9.\n */\n SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {\n // Constant (Band 0)\n this.l00 = this.l00.scale(3.141593);\n // Linear (Band 1)\n this.l1_1 = this.l1_1.scale(2.094395);\n this.l10 = this.l10.scale(2.094395);\n this.l11 = this.l11.scale(2.094395);\n // Quadratic (Band 2)\n this.l2_2 = this.l2_2.scale(0.785398);\n this.l2_1 = this.l2_1.scale(0.785398);\n this.l20 = this.l20.scale(0.785398);\n this.l21 = this.l21.scale(0.785398);\n this.lL22 = this.lL22.scale(0.785398);\n };\n /**\n * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.\n *\n * ```\n * L = (1/pi) * E * rho\n * ```\n *\n * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.\n */\n SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {\n this.scale(1.0 / Math.PI);\n // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied\n // (The pixel shader must apply albedo after texture fetches, etc).\n };\n /**\n * Gets the spherical harmonics from polynomial\n * @param polynomial the spherical polynomial\n * @returns the spherical harmonics\n */\n SphericalHarmonics.FromPolynomial = function (polynomial) {\n var result = new SphericalHarmonics();\n result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));\n result.l1_1 = polynomial.y.scale(0.977204);\n result.l10 = polynomial.z.scale(0.977204);\n result.l11 = polynomial.x.scale(0.977204);\n result.l2_2 = polynomial.xy.scale(1.16538);\n result.l2_1 = polynomial.yz.scale(1.16538);\n result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));\n result.l21 = polynomial.zx.scale(1.16538);\n result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));\n result.scale(Math.PI);\n return result;\n };\n /**\n * Constructs a spherical harmonics from an array.\n * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)\n * @returns the spherical harmonics\n */\n SphericalHarmonics.FromArray = function (data) {\n var sh = new SphericalHarmonics();\n BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);\n BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);\n BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);\n BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);\n BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);\n BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);\n BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);\n BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);\n BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);\n return sh;\n };\n return SphericalHarmonics;\n }());\n BABYLON.SphericalHarmonics = SphericalHarmonics;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sphericalPolynomial.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var FileFaceOrientation = /** @class */ (function () {\n function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {\n this.name = name;\n this.worldAxisForNormal = worldAxisForNormal;\n this.worldAxisForFileX = worldAxisForFileX;\n this.worldAxisForFileY = worldAxisForFileY;\n }\n return FileFaceOrientation;\n }());\n ;\n /**\n * Helper class dealing with the extraction of spherical polynomial dataArray\n * from a cube map.\n */\n var CubeMapToSphericalPolynomialTools = /** @class */ (function () {\n function CubeMapToSphericalPolynomialTools() {\n }\n /**\n * Converts a texture to the according Spherical Polynomial data.\n * This extracts the first 3 orders only as they are the only one used in the lighting.\n *\n * @param texture The texture to extract the information from.\n * @return The Spherical Polynomial data.\n */\n CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {\n if (!texture.isCube) {\n // Only supports cube Textures currently.\n return null;\n }\n var size = texture.getSize().width;\n var right = texture.readPixels(0);\n var left = texture.readPixels(1);\n var up;\n var down;\n if (texture.isRenderTarget) {\n up = texture.readPixels(3);\n down = texture.readPixels(2);\n }\n else {\n up = texture.readPixels(2);\n down = texture.readPixels(3);\n }\n var front = texture.readPixels(4);\n var back = texture.readPixels(5);\n var gammaSpace = texture.gammaSpace;\n // Always read as RGBA.\n var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;\n var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {\n type = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n var cubeInfo = {\n size: size,\n right: right,\n left: left,\n up: up,\n down: down,\n front: front,\n back: back,\n format: format,\n type: type,\n gammaSpace: gammaSpace,\n };\n return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);\n };\n /**\n * Converts a cubemap to the according Spherical Polynomial data.\n * This extracts the first 3 orders only as they are the only one used in the lighting.\n *\n * @param cubeInfo The Cube map to extract the information from.\n * @return The Spherical Polynomial data.\n */\n CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {\n var sphericalHarmonics = new BABYLON.SphericalHarmonics();\n var totalSolidAngle = 0.0;\n // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.\n var du = 2.0 / cubeInfo.size;\n var dv = du;\n // The (u,v) of the first texel is half a texel from the corner (-1,-1).\n var minUV = du * 0.5 - 1.0;\n for (var faceIndex = 0; faceIndex < 6; faceIndex++) {\n var fileFace = this.FileFaces[faceIndex];\n var dataArray = cubeInfo[fileFace.name];\n var v = minUV;\n // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).\n // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.\n // Because SP is still linear, so summation is fine in that basis.\n var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;\n for (var y = 0; y < cubeInfo.size; y++) {\n var u = minUV;\n for (var x = 0; x < cubeInfo.size; x++) {\n // World direction (not normalised)\n var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);\n worldDirection.normalize();\n var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);\n var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];\n var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];\n var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];\n // Handle Integer types.\n if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {\n r /= 255;\n g /= 255;\n b /= 255;\n }\n // Handle Gamma space textures.\n if (cubeInfo.gammaSpace) {\n r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);\n g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);\n b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);\n }\n var color = new BABYLON.Color3(r, g, b);\n sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);\n totalSolidAngle += deltaSolidAngle;\n u += du;\n }\n v += dv;\n }\n }\n // Solid angle for entire sphere is 4*pi\n var sphereSolidAngle = 4.0 * Math.PI;\n // Adjust the solid angle to allow for how many faces we processed.\n var facesProcessed = 6.0;\n var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;\n // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle. \n // This is needed because the numerical integration over the cube uses a \n // small angle approximation of solid angle for each texel (see deltaSolidAngle),\n // and also to compensate for accumulative error due to float precision in the summation.\n var correctionFactor = expectedSolidAngle / totalSolidAngle;\n sphericalHarmonics.scale(correctionFactor);\n sphericalHarmonics.convertIncidentRadianceToIrradiance();\n sphericalHarmonics.convertIrradianceToLambertianRadiance();\n return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);\n };\n CubeMapToSphericalPolynomialTools.FileFaces = [\n new FileFaceOrientation(\"right\", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),\n new FileFaceOrientation(\"left\", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),\n new FileFaceOrientation(\"up\", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),\n new FileFaceOrientation(\"down\", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),\n new FileFaceOrientation(\"front\", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),\n new FileFaceOrientation(\"back\", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom\n ];\n return CubeMapToSphericalPolynomialTools;\n }());\n BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Manages the defines for the PBR Material.\n * @hiddenChildren\n */\n var PBRMaterialDefines = /** @class */ (function (_super) {\n __extends(PBRMaterialDefines, _super);\n /**\n * Initializes the PBR Material defines.\n */\n function PBRMaterialDefines() {\n var _this = _super.call(this) || this;\n _this.PBR = true;\n _this.MAINUV1 = false;\n _this.MAINUV2 = false;\n _this.UV1 = false;\n _this.UV2 = false;\n _this.ALBEDO = false;\n _this.ALBEDODIRECTUV = 0;\n _this.VERTEXCOLOR = false;\n _this.AMBIENT = false;\n _this.AMBIENTDIRECTUV = 0;\n _this.AMBIENTINGRAYSCALE = false;\n _this.OPACITY = false;\n _this.VERTEXALPHA = false;\n _this.OPACITYDIRECTUV = 0;\n _this.OPACITYRGB = false;\n _this.ALPHATEST = false;\n _this.DEPTHPREPASS = false;\n _this.ALPHABLEND = false;\n _this.ALPHAFROMALBEDO = false;\n _this.ALPHATESTVALUE = \"0.5\";\n _this.SPECULAROVERALPHA = false;\n _this.RADIANCEOVERALPHA = false;\n _this.ALPHAFRESNEL = false;\n _this.LINEARALPHAFRESNEL = false;\n _this.PREMULTIPLYALPHA = false;\n _this.EMISSIVE = false;\n _this.EMISSIVEDIRECTUV = 0;\n _this.REFLECTIVITY = false;\n _this.REFLECTIVITYDIRECTUV = 0;\n _this.SPECULARTERM = false;\n _this.MICROSURFACEFROMREFLECTIVITYMAP = false;\n _this.MICROSURFACEAUTOMATIC = false;\n _this.LODBASEDMICROSFURACE = false;\n _this.MICROSURFACEMAP = false;\n _this.MICROSURFACEMAPDIRECTUV = 0;\n _this.METALLICWORKFLOW = false;\n _this.ROUGHNESSSTOREINMETALMAPALPHA = false;\n _this.ROUGHNESSSTOREINMETALMAPGREEN = false;\n _this.METALLNESSSTOREINMETALMAPBLUE = false;\n _this.AOSTOREINMETALMAPRED = false;\n _this.ENVIRONMENTBRDF = false;\n _this.NORMAL = false;\n _this.TANGENT = false;\n _this.BUMP = false;\n _this.BUMPDIRECTUV = 0;\n _this.OBJECTSPACE_NORMALMAP = false;\n _this.PARALLAX = false;\n _this.PARALLAXOCCLUSION = false;\n _this.NORMALXYSCALE = true;\n _this.LIGHTMAP = false;\n _this.LIGHTMAPDIRECTUV = 0;\n _this.USELIGHTMAPASSHADOWMAP = false;\n _this.GAMMALIGHTMAP = false;\n _this.REFLECTION = false;\n _this.REFLECTIONMAP_3D = false;\n _this.REFLECTIONMAP_SPHERICAL = false;\n _this.REFLECTIONMAP_PLANAR = false;\n _this.REFLECTIONMAP_CUBIC = false;\n _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\n _this.REFLECTIONMAP_PROJECTION = false;\n _this.REFLECTIONMAP_SKYBOX = false;\n _this.REFLECTIONMAP_EXPLICIT = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n _this.INVERTCUBICMAP = false;\n _this.USESPHERICALFROMREFLECTIONMAP = false;\n _this.USESPHERICALINVERTEX = false;\n _this.REFLECTIONMAP_OPPOSITEZ = false;\n _this.LODINREFLECTIONALPHA = false;\n _this.GAMMAREFLECTION = false;\n _this.RGBDREFLECTION = false;\n _this.RADIANCEOCCLUSION = false;\n _this.HORIZONOCCLUSION = false;\n _this.REFRACTION = false;\n _this.REFRACTIONMAP_3D = false;\n _this.REFRACTIONMAP_OPPOSITEZ = false;\n _this.LODINREFRACTIONALPHA = false;\n _this.GAMMAREFRACTION = false;\n _this.RGBDREFRACTION = false;\n _this.LINKREFRACTIONTOTRANSPARENCY = false;\n _this.INSTANCES = false;\n _this.NUM_BONE_INFLUENCERS = 0;\n _this.BonesPerMesh = 0;\n _this.NONUNIFORMSCALING = false;\n _this.MORPHTARGETS = false;\n _this.MORPHTARGETS_NORMAL = false;\n _this.MORPHTARGETS_TANGENT = false;\n _this.NUM_MORPH_INFLUENCERS = 0;\n _this.IMAGEPROCESSING = false;\n _this.VIGNETTE = false;\n _this.VIGNETTEBLENDMODEMULTIPLY = false;\n _this.VIGNETTEBLENDMODEOPAQUE = false;\n _this.TONEMAPPING = false;\n _this.CONTRAST = false;\n _this.COLORCURVES = false;\n _this.COLORGRADING = false;\n _this.COLORGRADING3D = false;\n _this.SAMPLER3DGREENDEPTH = false;\n _this.SAMPLER3DBGRMAP = false;\n _this.IMAGEPROCESSINGPOSTPROCESS = false;\n _this.EXPOSURE = false;\n _this.USEPHYSICALLIGHTFALLOFF = false;\n _this.TWOSIDEDLIGHTING = false;\n _this.SHADOWFLOAT = false;\n _this.CLIPPLANE = false;\n _this.POINTSIZE = false;\n _this.FOG = false;\n _this.LOGARITHMICDEPTH = false;\n _this.FORCENORMALFORWARD = false;\n _this.SPECULARAA = false;\n _this.UNLIT = false;\n _this.rebuild();\n return _this;\n }\n /**\n * Resets the PBR Material defines.\n */\n PBRMaterialDefines.prototype.reset = function () {\n _super.prototype.reset.call(this);\n this.ALPHATESTVALUE = \"0.5\";\n this.PBR = true;\n };\n return PBRMaterialDefines;\n }(BABYLON.MaterialDefines));\n /**\n * The Physically based material base class of BJS.\n *\n * This offers the main features of a standard PBR material.\n * For more information, please refer to the documentation :\n * http://doc.babylonjs.com/extensions/Physically_Based_Rendering\n */\n var PBRBaseMaterial = /** @class */ (function (_super) {\n __extends(PBRBaseMaterial, _super);\n /**\n * Instantiates a new PBRMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n function PBRBaseMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n /**\n * Intensity of the direct lights e.g. the four lights available in your scene.\n * This impacts both the direct diffuse and specular highlights.\n */\n _this._directIntensity = 1.0;\n /**\n * Intensity of the emissive part of the material.\n * This helps controlling the emissive effect without modifying the emissive color.\n */\n _this._emissiveIntensity = 1.0;\n /**\n * Intensity of the environment e.g. how much the environment will light the object\n * either through harmonics for rough material or through the refelction for shiny ones.\n */\n _this._environmentIntensity = 1.0;\n /**\n * This is a special control allowing the reduction of the specular highlights coming from the\n * four lights of the scene. Those highlights may not be needed in full environment lighting.\n */\n _this._specularIntensity = 1.0;\n /**\n * This stores the direct, emissive, environment, and specular light intensities into a Vector4.\n */\n _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);\n /**\n * Debug Control allowing disabling the bump map on this material.\n */\n _this._disableBumpMap = false;\n /**\n * AKA Occlusion Texture Intensity in other nomenclature.\n */\n _this._ambientTextureStrength = 1.0;\n /**\n * The color of a material in ambient lighting.\n */\n _this._ambientColor = new BABYLON.Color3(0, 0, 0);\n /**\n * AKA Diffuse Color in other nomenclature.\n */\n _this._albedoColor = new BABYLON.Color3(1, 1, 1);\n /**\n * AKA Specular Color in other nomenclature.\n */\n _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);\n /**\n * The color applied when light is reflected from a material.\n */\n _this._reflectionColor = new BABYLON.Color3(1, 1, 1);\n /**\n * The color applied when light is emitted from a material.\n */\n _this._emissiveColor = new BABYLON.Color3(0, 0, 0);\n /**\n * AKA Glossiness in other nomenclature.\n */\n _this._microSurface = 0.9;\n /**\n * source material index of refraction (IOR)' / 'destination material IOR.\n */\n _this._indexOfRefraction = 0.66;\n /**\n * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.\n */\n _this._invertRefractionY = false;\n /**\n * This parameters will make the material used its opacity to control how much it is refracting aginst not.\n * Materials half opaque for instance using refraction could benefit from this control.\n */\n _this._linkRefractionWithTransparency = false;\n /**\n * Specifies that the material will use the light map as a show map.\n */\n _this._useLightmapAsShadowmap = false;\n /**\n * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal\n * makes the reflect vector face the model (under horizon).\n */\n _this._useHorizonOcclusion = true;\n /**\n * This parameters will enable/disable radiance occlusion by preventing the radiance to lit\n * too much the area relying on ambient texture to define their ambient occlusion.\n */\n _this._useRadianceOcclusion = true;\n /**\n * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.\n */\n _this._useAlphaFromAlbedoTexture = false;\n /**\n * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).\n * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.\n */\n _this._useSpecularOverAlpha = true;\n /**\n * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.\n */\n _this._useMicroSurfaceFromReflectivityMapAlpha = false;\n /**\n * Specifies if the metallic texture contains the roughness information in its alpha channel.\n */\n _this._useRoughnessFromMetallicTextureAlpha = true;\n /**\n * Specifies if the metallic texture contains the roughness information in its green channel.\n */\n _this._useRoughnessFromMetallicTextureGreen = false;\n /**\n * Specifies if the metallic texture contains the metallness information in its blue channel.\n */\n _this._useMetallnessFromMetallicTextureBlue = false;\n /**\n * Specifies if the metallic texture contains the ambient occlusion information in its red channel.\n */\n _this._useAmbientOcclusionFromMetallicTextureRed = false;\n /**\n * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.\n */\n _this._useAmbientInGrayScale = false;\n /**\n * In case the reflectivity map does not contain the microsurface information in its alpha channel,\n * The material will try to infer what glossiness each pixel should be.\n */\n _this._useAutoMicroSurfaceFromReflectivityMap = false;\n /**\n * BJS is using an harcoded light falloff based on a manually sets up range.\n * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.\n * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.\n */\n _this._usePhysicalLightFalloff = true;\n /**\n * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).\n * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.\n */\n _this._useRadianceOverAlpha = true;\n /**\n * Allows using an object space normal map (instead of tangent space).\n */\n _this._useObjectSpaceNormalMap = false;\n /**\n * Allows using the bump map in parallax mode.\n */\n _this._useParallax = false;\n /**\n * Allows using the bump map in parallax occlusion mode.\n */\n _this._useParallaxOcclusion = false;\n /**\n * Controls the scale bias of the parallax mode.\n */\n _this._parallaxScaleBias = 0.05;\n /**\n * If sets to true, disables all the lights affecting the material.\n */\n _this._disableLighting = false;\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n _this._maxSimultaneousLights = 4;\n /**\n * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).\n */\n _this._invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).\n */\n _this._invertNormalMapY = false;\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n */\n _this._twoSidedLighting = false;\n /**\n * Defines the alpha limits in alpha test mode.\n */\n _this._alphaCutOff = 0.4;\n /**\n * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.\n */\n _this._forceAlphaTest = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)\n */\n _this._useAlphaFresnel = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)\n */\n _this._useLinearAlphaFresnel = false;\n /**\n * The transparency mode of the material.\n */\n _this._transparencyMode = null;\n /**\n * Specifies the environment BRDF texture used to comput the scale and offset roughness values\n * from cos thetav and roughness:\n * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf\n */\n _this._environmentBRDFTexture = null;\n /**\n * Force the shader to compute irradiance in the fragment shader in order to take bump in account.\n */\n _this._forceIrradianceInFragment = false;\n /**\n * Force normal to face away from face.\n */\n _this._forceNormalForward = false;\n /**\n * Enables specular anti aliasing in the PBR shader.\n * It will both interacts on the Geometry for analytical and IBL lighting.\n * It also prefilter the roughness map based on the bump values.\n */\n _this._enableSpecularAntiAliasing = false;\n /**\n * Stores the available render targets.\n */\n _this._renderTargets = new BABYLON.SmartArray(16);\n /**\n * Sets the global ambient color for the material used in lighting calculations.\n */\n _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);\n /**\n * If set to true, no lighting calculations will be applied.\n */\n _this._unlit = false;\n // Setup the default processing configuration to the scene.\n _this._attachImageProcessingConfiguration(null);\n _this.getRenderTargetTextures = function () {\n _this._renderTargets.reset();\n if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {\n _this._renderTargets.push(_this._reflectionTexture);\n }\n if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {\n _this._renderTargets.push(_this._refractionTexture);\n }\n return _this._renderTargets;\n };\n _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);\n return _this;\n }\n /**\n * Attaches a new image processing configuration to the PBR Material.\n * @param configuration\n */\n PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {\n var _this = this;\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {\n _this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n };\n /**\n * Gets the name of the material class.\n */\n PBRBaseMaterial.prototype.getClassName = function () {\n return \"PBRBaseMaterial\";\n };\n Object.defineProperty(PBRBaseMaterial.prototype, \"useLogarithmicDepth\", {\n /**\n * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.\n */\n get: function () {\n return this._useLogarithmicDepth;\n },\n /**\n * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.\n */\n set: function (value) {\n this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRBaseMaterial.prototype, \"transparencyMode\", {\n /**\n * Gets the current transparency mode.\n */\n get: function () {\n return this._transparencyMode;\n },\n /**\n * Sets the transparency mode of the material.\n *\n * | Value | Type | Description |\n * | ----- | ----------------------------------- | ----------- |\n * | 0 | OPAQUE | |\n * | 1 | ALPHATEST | |\n * | 2 | ALPHABLEND | |\n * | 3 | ALPHATESTANDBLEND | |\n *\n */\n set: function (value) {\n if (this._transparencyMode === value) {\n return;\n }\n this._transparencyMode = value;\n this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);\n this._markAllSubMeshesAsTexturesAndMiscDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRBaseMaterial.prototype, \"_disableAlphaBlending\", {\n /**\n * Returns true if alpha blending should be disabled.\n */\n get: function () {\n return (this._linkRefractionWithTransparency ||\n this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||\n this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Specifies whether or not this material should be rendered in alpha blend mode.\n */\n PBRBaseMaterial.prototype.needAlphaBlending = function () {\n if (this._disableAlphaBlending) {\n return false;\n }\n return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();\n };\n /**\n * Specifies if the mesh will require alpha blending.\n * @param mesh - BJS mesh.\n */\n PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {\n if (this._disableAlphaBlending) {\n return false;\n }\n return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);\n };\n /**\n * Specifies whether or not this material should be rendered in alpha test mode.\n */\n PBRBaseMaterial.prototype.needAlphaTesting = function () {\n if (this._forceAlphaTest) {\n return true;\n }\n if (this._linkRefractionWithTransparency) {\n return false;\n }\n return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);\n };\n /**\n * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.\n */\n PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {\n return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;\n };\n /**\n * Gets the texture used for the alpha test.\n */\n PBRBaseMaterial.prototype.getAlphaTestTexture = function () {\n return this._albedoTexture;\n };\n /**\n * Specifies that the submesh is ready to be used.\n * @param mesh - BJS mesh.\n * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.\n * @param useInstances - Specifies that instances should be used.\n * @returns - boolean indicating that the submesh is ready or not.\n */\n PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {\n if (subMesh.effect && this.isFrozen) {\n if (this._wasPreviouslyReady) {\n return true;\n }\n }\n if (!subMesh._materialDefines) {\n subMesh._materialDefines = new PBRMaterialDefines();\n }\n var defines = subMesh._materialDefines;\n if (!this.checkReadyOnEveryCall && subMesh.effect) {\n if (defines._renderId === this.getScene().getRenderId()) {\n return true;\n }\n }\n var scene = this.getScene();\n var engine = scene.getEngine();\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n if (!this._albedoTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {\n if (!this._ambientTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {\n if (!this._opacityTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n var reflectionTexture = this._getReflectionTexture();\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n if (!reflectionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {\n if (!this._lightmapTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {\n if (!this._emissiveTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (BABYLON.StandardMaterial.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n if (!this._metallicTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n else if (this._reflectivityTexture) {\n if (!this._reflectivityTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._microSurfaceTexture) {\n if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {\n // Bump texture cannot be not blocking.\n if (!this._bumpTexture.isReady()) {\n return false;\n }\n }\n var refractionTexture = this._getRefractionTexture();\n if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {\n if (!refractionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n // This is blocking.\n if (!this._environmentBRDFTexture.isReady()) {\n return false;\n }\n }\n }\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n if (!this._imageProcessingConfiguration.isReady()) {\n return false;\n }\n }\n if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n mesh.createNormals(true);\n BABYLON.Tools.Warn(\"PBRMaterial: Normals have been created for the mesh: \" + mesh.name);\n }\n var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);\n if (effect) {\n scene.resetCachedMaterial();\n subMesh.setEffect(effect, defines);\n this.buildUniformLayout();\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n this._wasPreviouslyReady = true;\n return true;\n };\n /**\n * Specifies if the material uses metallic roughness workflow.\n * @returns boolean specifiying if the material uses metallic roughness workflow.\n */\n PBRBaseMaterial.prototype.isMetallicWorkflow = function () {\n if (this._metallic != null || this._roughness != null || this._metallicTexture) {\n return true;\n }\n return false;\n };\n PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {\n if (onCompiled === void 0) { onCompiled = null; }\n if (onError === void 0) { onError = null; }\n if (useInstances === void 0) { useInstances = null; }\n if (useClipPlane === void 0) { useClipPlane = null; }\n this._prepareDefines(mesh, defines, useInstances, useClipPlane);\n if (!defines.isDirty) {\n return null;\n }\n defines.markAsProcessed();\n var scene = this.getScene();\n var engine = scene.getEngine();\n // Fallbacks\n var fallbacks = new BABYLON.EffectFallbacks();\n var fallbackRank = 0;\n if (defines.USESPHERICALINVERTEX) {\n fallbacks.addFallback(fallbackRank++, \"USESPHERICALINVERTEX\");\n }\n if (defines.FOG) {\n fallbacks.addFallback(fallbackRank, \"FOG\");\n }\n if (defines.SPECULARAA) {\n fallbacks.addFallback(fallbackRank, \"SPECULARAA\");\n }\n if (defines.POINTSIZE) {\n fallbacks.addFallback(fallbackRank, \"POINTSIZE\");\n }\n if (defines.LOGARITHMICDEPTH) {\n fallbacks.addFallback(fallbackRank, \"LOGARITHMICDEPTH\");\n }\n if (defines.PARALLAX) {\n fallbacks.addFallback(fallbackRank, \"PARALLAX\");\n }\n if (defines.PARALLAXOCCLUSION) {\n fallbacks.addFallback(fallbackRank++, \"PARALLAXOCCLUSION\");\n }\n if (defines.ENVIRONMENTBRDF) {\n fallbacks.addFallback(fallbackRank++, \"ENVIRONMENTBRDF\");\n }\n if (defines.TANGENT) {\n fallbacks.addFallback(fallbackRank++, \"TANGENT\");\n }\n if (defines.BUMP) {\n fallbacks.addFallback(fallbackRank++, \"BUMP\");\n }\n fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);\n if (defines.SPECULARTERM) {\n fallbacks.addFallback(fallbackRank++, \"SPECULARTERM\");\n }\n if (defines.USESPHERICALFROMREFLECTIONMAP) {\n fallbacks.addFallback(fallbackRank++, \"USESPHERICALFROMREFLECTIONMAP\");\n }\n if (defines.LIGHTMAP) {\n fallbacks.addFallback(fallbackRank++, \"LIGHTMAP\");\n }\n if (defines.NORMAL) {\n fallbacks.addFallback(fallbackRank++, \"NORMAL\");\n }\n if (defines.AMBIENT) {\n fallbacks.addFallback(fallbackRank++, \"AMBIENT\");\n }\n if (defines.EMISSIVE) {\n fallbacks.addFallback(fallbackRank++, \"EMISSIVE\");\n }\n if (defines.VERTEXCOLOR) {\n fallbacks.addFallback(fallbackRank++, \"VERTEXCOLOR\");\n }\n if (defines.NUM_BONE_INFLUENCERS > 0) {\n fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);\n }\n if (defines.MORPHTARGETS) {\n fallbacks.addFallback(fallbackRank++, \"MORPHTARGETS\");\n }\n //Attributes\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n if (defines.NORMAL) {\n attribs.push(BABYLON.VertexBuffer.NormalKind);\n }\n if (defines.TANGENT) {\n attribs.push(BABYLON.VertexBuffer.TangentKind);\n }\n if (defines.UV1) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n }\n if (defines.UV2) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n }\n if (defines.VERTEXCOLOR) {\n attribs.push(BABYLON.VertexBuffer.ColorKind);\n }\n BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);\n BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);\n BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);\n var uniforms = [\"world\", \"view\", \"viewProjection\", \"vEyePosition\", \"vLightsType\", \"vAmbientColor\", \"vAlbedoColor\", \"vReflectivityColor\", \"vEmissiveColor\", \"vReflectionColor\",\n \"vFogInfos\", \"vFogColor\", \"pointSize\",\n \"vAlbedoInfos\", \"vAmbientInfos\", \"vOpacityInfos\", \"vReflectionInfos\", \"vReflectionPosition\", \"vReflectionSize\", \"vEmissiveInfos\", \"vReflectivityInfos\",\n \"vMicroSurfaceSamplerInfos\", \"vBumpInfos\", \"vLightmapInfos\", \"vRefractionInfos\",\n \"mBones\",\n \"vClipPlane\", \"albedoMatrix\", \"ambientMatrix\", \"opacityMatrix\", \"reflectionMatrix\", \"emissiveMatrix\", \"reflectivityMatrix\", \"normalMatrix\", \"microSurfaceSamplerMatrix\", \"bumpMatrix\", \"lightmapMatrix\", \"refractionMatrix\",\n \"vLightingIntensity\",\n \"logarithmicDepthConstant\",\n \"vSphericalX\", \"vSphericalY\", \"vSphericalZ\",\n \"vSphericalXX\", \"vSphericalYY\", \"vSphericalZZ\",\n \"vSphericalXY\", \"vSphericalYZ\", \"vSphericalZX\",\n \"vReflectionMicrosurfaceInfos\", \"vRefractionMicrosurfaceInfos\",\n \"vTangentSpaceParams\"\n ];\n var samplers = [\"albedoSampler\", \"reflectivitySampler\", \"ambientSampler\", \"emissiveSampler\",\n \"bumpSampler\", \"lightmapSampler\", \"opacitySampler\",\n \"refractionSampler\", \"refractionSamplerLow\", \"refractionSamplerHigh\",\n \"reflectionSampler\", \"reflectionSamplerLow\", \"reflectionSamplerHigh\",\n \"microSurfaceSampler\", \"environmentBrdfSampler\"];\n var uniformBuffers = [\"Material\", \"Scene\"];\n if (BABYLON.ImageProcessingConfiguration) {\n BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);\n BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);\n }\n BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: defines,\n maxSimultaneousLights: this._maxSimultaneousLights\n });\n var join = defines.toString();\n return engine.createEffect(\"pbr\", {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: onCompiled,\n onError: onError,\n indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }\n }, engine);\n };\n PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {\n if (useInstances === void 0) { useInstances = null; }\n if (useClipPlane === void 0) { useClipPlane = null; }\n var scene = this.getScene();\n var engine = scene.getEngine();\n // Lights\n BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);\n defines._needNormals = true;\n // Textures\n defines.METALLICWORKFLOW = this.isMetallicWorkflow();\n if (defines._areTexturesDirty) {\n defines._needUVs = false;\n if (scene.texturesEnabled) {\n if (scene.getEngine().getCaps().textureLOD) {\n defines.LODBASEDMICROSFURACE = true;\n }\n if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, \"ALBEDO\");\n }\n else {\n defines.ALBEDO = false;\n }\n if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, \"AMBIENT\");\n defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;\n }\n else {\n defines.AMBIENT = false;\n }\n if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, \"OPACITY\");\n defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;\n }\n else {\n defines.OPACITY = false;\n }\n var reflectionTexture = this._getReflectionTexture();\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n defines.REFLECTION = true;\n defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;\n defines.RGBDREFLECTION = reflectionTexture.isRGBD;\n defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;\n defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;\n if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {\n defines.INVERTCUBICMAP = true;\n }\n defines.REFLECTIONMAP_3D = reflectionTexture.isCube;\n switch (reflectionTexture.coordinatesMode) {\n case BABYLON.Texture.EXPLICIT_MODE:\n defines.REFLECTIONMAP_EXPLICIT = true;\n break;\n case BABYLON.Texture.PLANAR_MODE:\n defines.REFLECTIONMAP_PLANAR = true;\n break;\n case BABYLON.Texture.PROJECTION_MODE:\n defines.REFLECTIONMAP_PROJECTION = true;\n break;\n case BABYLON.Texture.SKYBOX_MODE:\n defines.REFLECTIONMAP_SKYBOX = true;\n break;\n case BABYLON.Texture.SPHERICAL_MODE:\n defines.REFLECTIONMAP_SPHERICAL = true;\n break;\n case BABYLON.Texture.EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR = true;\n break;\n case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;\n break;\n case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;\n break;\n case BABYLON.Texture.CUBIC_MODE:\n case BABYLON.Texture.INVCUBIC_MODE:\n default:\n defines.REFLECTIONMAP_CUBIC = true;\n defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;\n break;\n }\n if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {\n if (reflectionTexture.sphericalPolynomial) {\n defines.USESPHERICALFROMREFLECTIONMAP = true;\n if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {\n defines.USESPHERICALINVERTEX = false;\n }\n else {\n defines.USESPHERICALINVERTEX = true;\n }\n }\n }\n }\n else {\n defines.REFLECTION = false;\n defines.REFLECTIONMAP_3D = false;\n defines.REFLECTIONMAP_SPHERICAL = false;\n defines.REFLECTIONMAP_PLANAR = false;\n defines.REFLECTIONMAP_CUBIC = false;\n defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\n defines.REFLECTIONMAP_PROJECTION = false;\n defines.REFLECTIONMAP_SKYBOX = false;\n defines.REFLECTIONMAP_EXPLICIT = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n defines.INVERTCUBICMAP = false;\n defines.USESPHERICALFROMREFLECTIONMAP = false;\n defines.USESPHERICALINVERTEX = false;\n defines.REFLECTIONMAP_OPPOSITEZ = false;\n defines.LODINREFLECTIONALPHA = false;\n defines.GAMMAREFLECTION = false;\n defines.RGBDREFLECTION = false;\n }\n if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, \"LIGHTMAP\");\n defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;\n defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;\n }\n else {\n defines.LIGHTMAP = false;\n }\n if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, \"EMISSIVE\");\n }\n else {\n defines.EMISSIVE = false;\n }\n if (BABYLON.StandardMaterial.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, \"REFLECTIVITY\");\n defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;\n defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;\n defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;\n defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;\n }\n else if (this._reflectivityTexture) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, \"REFLECTIVITY\");\n defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;\n defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;\n }\n else {\n defines.REFLECTIVITY = false;\n }\n if (this._microSurfaceTexture) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, \"MICROSURFACEMAP\");\n }\n else {\n defines.MICROSURFACEMAP = false;\n }\n }\n else {\n defines.REFLECTIVITY = false;\n defines.MICROSURFACEMAP = false;\n }\n if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, \"BUMP\");\n if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n defines.PARALLAX = true;\n defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;\n }\n else {\n defines.PARALLAX = false;\n }\n defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;\n }\n else {\n defines.BUMP = false;\n }\n var refractionTexture = this._getRefractionTexture();\n if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {\n defines.REFRACTION = true;\n defines.REFRACTIONMAP_3D = refractionTexture.isCube;\n defines.GAMMAREFRACTION = refractionTexture.gammaSpace;\n defines.RGBDREFRACTION = refractionTexture.isRGBD;\n defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;\n defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;\n if (this._linkRefractionWithTransparency) {\n defines.LINKREFRACTIONTOTRANSPARENCY = true;\n }\n }\n else {\n defines.REFRACTION = false;\n }\n if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n defines.ENVIRONMENTBRDF = true;\n }\n else {\n defines.ENVIRONMENTBRDF = false;\n }\n if (this._shouldUseAlphaFromAlbedoTexture()) {\n defines.ALPHAFROMALBEDO = true;\n }\n else {\n defines.ALPHAFROMALBEDO = false;\n }\n }\n defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;\n defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;\n defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;\n if (!this.backFaceCulling && this._twoSidedLighting) {\n defines.TWOSIDEDLIGHTING = true;\n }\n else {\n defines.TWOSIDEDLIGHTING = false;\n }\n defines.ALPHATESTVALUE = \"\" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? \".\" : \"\");\n defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);\n defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);\n defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;\n defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;\n defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n this._imageProcessingConfiguration.prepareDefines(defines);\n }\n defines.FORCENORMALFORWARD = this._forceNormalForward;\n defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;\n defines.HORIZONOCCLUSION = this._useHorizonOcclusion;\n // Misc.\n if (defines._areMiscDirty) {\n BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);\n defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));\n }\n // Values that need to be evaluated on every frame\n BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);\n // Attribs\n BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);\n };\n /**\n * Force shader compilation\n */\n PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {\n var _this = this;\n var localOptions = __assign({ clipPlane: false }, options);\n var defines = new PBRMaterialDefines();\n var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);\n if (effect.isReady()) {\n if (onCompiled) {\n onCompiled(this);\n }\n }\n else {\n effect.onCompileObservable.add(function () {\n if (onCompiled) {\n onCompiled(_this);\n }\n });\n }\n };\n /**\n * Initializes the uniform buffer layout for the shader.\n */\n PBRBaseMaterial.prototype.buildUniformLayout = function () {\n // Order is important !\n this._uniformBuffer.addUniform(\"vAlbedoInfos\", 2);\n this._uniformBuffer.addUniform(\"vAmbientInfos\", 3);\n this._uniformBuffer.addUniform(\"vOpacityInfos\", 2);\n this._uniformBuffer.addUniform(\"vEmissiveInfos\", 2);\n this._uniformBuffer.addUniform(\"vLightmapInfos\", 2);\n this._uniformBuffer.addUniform(\"vReflectivityInfos\", 3);\n this._uniformBuffer.addUniform(\"vMicroSurfaceSamplerInfos\", 2);\n this._uniformBuffer.addUniform(\"vRefractionInfos\", 4);\n this._uniformBuffer.addUniform(\"vReflectionInfos\", 2);\n this._uniformBuffer.addUniform(\"vReflectionPosition\", 3);\n this._uniformBuffer.addUniform(\"vReflectionSize\", 3);\n this._uniformBuffer.addUniform(\"vBumpInfos\", 3);\n this._uniformBuffer.addUniform(\"albedoMatrix\", 16);\n this._uniformBuffer.addUniform(\"ambientMatrix\", 16);\n this._uniformBuffer.addUniform(\"opacityMatrix\", 16);\n this._uniformBuffer.addUniform(\"emissiveMatrix\", 16);\n this._uniformBuffer.addUniform(\"lightmapMatrix\", 16);\n this._uniformBuffer.addUniform(\"reflectivityMatrix\", 16);\n this._uniformBuffer.addUniform(\"microSurfaceSamplerMatrix\", 16);\n this._uniformBuffer.addUniform(\"bumpMatrix\", 16);\n this._uniformBuffer.addUniform(\"vTangentSpaceParams\", 2);\n this._uniformBuffer.addUniform(\"refractionMatrix\", 16);\n this._uniformBuffer.addUniform(\"reflectionMatrix\", 16);\n this._uniformBuffer.addUniform(\"vReflectionColor\", 3);\n this._uniformBuffer.addUniform(\"vAlbedoColor\", 4);\n this._uniformBuffer.addUniform(\"vLightingIntensity\", 4);\n this._uniformBuffer.addUniform(\"vRefractionMicrosurfaceInfos\", 3);\n this._uniformBuffer.addUniform(\"vReflectionMicrosurfaceInfos\", 3);\n this._uniformBuffer.addUniform(\"vReflectivityColor\", 4);\n this._uniformBuffer.addUniform(\"vEmissiveColor\", 3);\n this._uniformBuffer.addUniform(\"pointSize\", 1);\n this._uniformBuffer.create();\n };\n /**\n * Unbinds the textures.\n */\n PBRBaseMaterial.prototype.unbind = function () {\n if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", null);\n }\n if (this._refractionTexture && this._refractionTexture.isRenderTarget) {\n this._uniformBuffer.setTexture(\"refractionSampler\", null);\n }\n _super.prototype.unbind.call(this);\n };\n /**\n * Binds the submesh data.\n * @param world - The world matrix.\n * @param mesh - The BJS mesh.\n * @param subMesh - A submesh of the BJS mesh.\n */\n PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {\n var scene = this.getScene();\n var defines = subMesh._materialDefines;\n if (!defines) {\n return;\n }\n var effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices\n this.bindOnlyWorldMatrix(world);\n // Normal Matrix\n if (defines.OBJECTSPACE_NORMALMAP) {\n world.toNormalMatrix(this._normalMatrix);\n this.bindOnlyNormalMatrix(this._normalMatrix);\n }\n var mustRebind = this._mustRebind(scene, effect, mesh.visibility);\n // Bones\n BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);\n var reflectionTexture = null;\n if (mustRebind) {\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this.bindViewProjection(effect);\n reflectionTexture = this._getReflectionTexture();\n var refractionTexture = this._getRefractionTexture();\n if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {\n // Texture uniforms\n if (scene.texturesEnabled) {\n if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vAlbedoInfos\", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, \"albedo\");\n }\n if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {\n this._uniformBuffer.updateFloat3(\"vAmbientInfos\", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);\n BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, \"ambient\");\n }\n if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vOpacityInfos\", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, \"opacity\");\n }\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n this._uniformBuffer.updateMatrix(\"reflectionMatrix\", reflectionTexture.getReflectionTextureMatrix());\n this._uniformBuffer.updateFloat2(\"vReflectionInfos\", reflectionTexture.level, 0);\n if (reflectionTexture.boundingBoxSize) {\n var cubeTexture = reflectionTexture;\n this._uniformBuffer.updateVector3(\"vReflectionPosition\", cubeTexture.boundingBoxPosition);\n this._uniformBuffer.updateVector3(\"vReflectionSize\", cubeTexture.boundingBoxSize);\n }\n var polynomials = reflectionTexture.sphericalPolynomial;\n if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {\n this._activeEffect.setFloat3(\"vSphericalX\", polynomials.x.x, polynomials.x.y, polynomials.x.z);\n this._activeEffect.setFloat3(\"vSphericalY\", polynomials.y.x, polynomials.y.y, polynomials.y.z);\n this._activeEffect.setFloat3(\"vSphericalZ\", polynomials.z.x, polynomials.z.y, polynomials.z.z);\n this._activeEffect.setFloat3(\"vSphericalXX_ZZ\", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);\n this._activeEffect.setFloat3(\"vSphericalYY_ZZ\", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);\n this._activeEffect.setFloat3(\"vSphericalZZ\", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);\n this._activeEffect.setFloat3(\"vSphericalXY\", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);\n this._activeEffect.setFloat3(\"vSphericalYZ\", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);\n this._activeEffect.setFloat3(\"vSphericalZX\", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);\n }\n this._uniformBuffer.updateFloat3(\"vReflectionMicrosurfaceInfos\", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);\n }\n if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vEmissiveInfos\", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, \"emissive\");\n }\n if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vLightmapInfos\", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, \"lightmap\");\n }\n if (BABYLON.StandardMaterial.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n this._uniformBuffer.updateFloat3(\"vReflectivityInfos\", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);\n BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, \"reflectivity\");\n }\n else if (this._reflectivityTexture) {\n this._uniformBuffer.updateFloat3(\"vReflectivityInfos\", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);\n BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, \"reflectivity\");\n }\n if (this._microSurfaceTexture) {\n this._uniformBuffer.updateFloat2(\"vMicroSurfaceSamplerInfos\", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, \"microSurfaceSampler\");\n }\n }\n if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {\n this._uniformBuffer.updateFloat3(\"vBumpInfos\", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);\n BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, \"bump\");\n if (scene._mirroredCameraPosition) {\n this._uniformBuffer.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);\n }\n else {\n this._uniformBuffer.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);\n }\n }\n if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {\n this._uniformBuffer.updateMatrix(\"refractionMatrix\", refractionTexture.getReflectionTextureMatrix());\n var depth = 1.0;\n if (!refractionTexture.isCube) {\n if (refractionTexture.depth) {\n depth = refractionTexture.depth;\n }\n }\n this._uniformBuffer.updateFloat4(\"vRefractionInfos\", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);\n this._uniformBuffer.updateFloat3(\"vRefractionMicrosurfaceInfos\", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);\n }\n }\n // Point size\n if (this.pointsCloud) {\n this._uniformBuffer.updateFloat(\"pointSize\", this.pointSize);\n }\n // Colors\n if (defines.METALLICWORKFLOW) {\n BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;\n BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;\n this._uniformBuffer.updateColor4(\"vReflectivityColor\", BABYLON.PBRMaterial._scaledReflectivity, 0);\n }\n else {\n this._uniformBuffer.updateColor4(\"vReflectivityColor\", this._reflectivityColor, this._microSurface);\n }\n this._uniformBuffer.updateColor3(\"vEmissiveColor\", this._emissiveColor);\n this._uniformBuffer.updateColor3(\"vReflectionColor\", this._reflectionColor);\n this._uniformBuffer.updateColor4(\"vAlbedoColor\", this._albedoColor, this.alpha * mesh.visibility);\n // Misc\n this._lightingInfos.x = this._directIntensity;\n this._lightingInfos.y = this._emissiveIntensity;\n this._lightingInfos.z = this._environmentIntensity;\n this._lightingInfos.w = this._specularIntensity;\n this._uniformBuffer.updateVector4(\"vLightingIntensity\", this._lightingInfos);\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n this._uniformBuffer.setTexture(\"albedoSampler\", this._albedoTexture);\n }\n if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {\n this._uniformBuffer.setTexture(\"ambientSampler\", this._ambientTexture);\n }\n if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {\n this._uniformBuffer.setTexture(\"opacitySampler\", this._opacityTexture);\n }\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n if (defines.LODBASEDMICROSFURACE) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture);\n }\n else {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture._lodTextureMid || reflectionTexture);\n this._uniformBuffer.setTexture(\"reflectionSamplerLow\", reflectionTexture._lodTextureLow || reflectionTexture);\n this._uniformBuffer.setTexture(\"reflectionSamplerHigh\", reflectionTexture._lodTextureHigh || reflectionTexture);\n }\n }\n if (defines.ENVIRONMENTBRDF) {\n this._uniformBuffer.setTexture(\"environmentBrdfSampler\", this._environmentBRDFTexture);\n }\n if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {\n if (defines.LODBASEDMICROSFURACE) {\n this._uniformBuffer.setTexture(\"refractionSampler\", refractionTexture);\n }\n else {\n this._uniformBuffer.setTexture(\"refractionSampler\", refractionTexture._lodTextureMid || refractionTexture);\n this._uniformBuffer.setTexture(\"refractionSamplerLow\", refractionTexture._lodTextureLow || refractionTexture);\n this._uniformBuffer.setTexture(\"refractionSamplerHigh\", refractionTexture._lodTextureHigh || refractionTexture);\n }\n }\n if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {\n this._uniformBuffer.setTexture(\"emissiveSampler\", this._emissiveTexture);\n }\n if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {\n this._uniformBuffer.setTexture(\"lightmapSampler\", this._lightmapTexture);\n }\n if (BABYLON.StandardMaterial.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n this._uniformBuffer.setTexture(\"reflectivitySampler\", this._metallicTexture);\n }\n else if (this._reflectivityTexture) {\n this._uniformBuffer.setTexture(\"reflectivitySampler\", this._reflectivityTexture);\n }\n if (this._microSurfaceTexture) {\n this._uniformBuffer.setTexture(\"microSurfaceSampler\", this._microSurfaceTexture);\n }\n }\n if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {\n this._uniformBuffer.setTexture(\"bumpSampler\", this._bumpTexture);\n }\n }\n // Clip plane\n BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);\n // Colors\n scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);\n var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);\n var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));\n effect.setFloat4(\"vEyePosition\", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);\n effect.setColor3(\"vAmbientColor\", this._globalAmbientColor);\n }\n if (mustRebind || !this.isFrozen) {\n // Lights\n if (scene.lightsEnabled && !this._disableLighting) {\n BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);\n }\n // View\n if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {\n this.bindView(effect);\n }\n // Fog\n BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);\n // Morph targets\n if (defines.NUM_MORPH_INFLUENCERS) {\n BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);\n }\n // image processing\n this._imageProcessingConfiguration.bind(this._activeEffect);\n // Log. depth\n BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);\n }\n this._uniformBuffer.update();\n this._afterBind(mesh, this._activeEffect);\n };\n /**\n * Returns the animatable textures.\n * @returns - Array of animatable textures.\n */\n PBRBaseMaterial.prototype.getAnimatables = function () {\n var results = [];\n if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {\n results.push(this._albedoTexture);\n }\n if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {\n results.push(this._ambientTexture);\n }\n if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {\n results.push(this._opacityTexture);\n }\n if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {\n results.push(this._reflectionTexture);\n }\n if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {\n results.push(this._emissiveTexture);\n }\n if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {\n results.push(this._metallicTexture);\n }\n else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {\n results.push(this._reflectivityTexture);\n }\n if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {\n results.push(this._bumpTexture);\n }\n if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {\n results.push(this._lightmapTexture);\n }\n if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {\n results.push(this._refractionTexture);\n }\n return results;\n };\n /**\n * Returns the texture used for reflections.\n * @returns - Reflection texture if present. Otherwise, returns the environment texture.\n */\n PBRBaseMaterial.prototype._getReflectionTexture = function () {\n if (this._reflectionTexture) {\n return this._reflectionTexture;\n }\n return this.getScene().environmentTexture;\n };\n /**\n * Returns the texture used for refraction or null if none is used.\n * @returns - Refection texture if present. If no refraction texture and refraction\n * is linked with transparency, returns environment texture. Otherwise, returns null.\n */\n PBRBaseMaterial.prototype._getRefractionTexture = function () {\n if (this._refractionTexture) {\n return this._refractionTexture;\n }\n if (this._linkRefractionWithTransparency) {\n return this.getScene().environmentTexture;\n }\n return null;\n };\n /**\n * Disposes the resources of the material.\n * @param forceDisposeEffect - Forces the disposal of effects.\n * @param forceDisposeTextures - Forces the disposal of all textures.\n */\n PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {\n if (forceDisposeTextures) {\n if (this._albedoTexture) {\n this._albedoTexture.dispose();\n }\n if (this._ambientTexture) {\n this._ambientTexture.dispose();\n }\n if (this._opacityTexture) {\n this._opacityTexture.dispose();\n }\n if (this._reflectionTexture) {\n this._reflectionTexture.dispose();\n }\n if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {\n this._environmentBRDFTexture.dispose();\n }\n if (this._emissiveTexture) {\n this._emissiveTexture.dispose();\n }\n if (this._metallicTexture) {\n this._metallicTexture.dispose();\n }\n if (this._reflectivityTexture) {\n this._reflectivityTexture.dispose();\n }\n if (this._bumpTexture) {\n this._bumpTexture.dispose();\n }\n if (this._lightmapTexture) {\n this._lightmapTexture.dispose();\n }\n if (this._refractionTexture) {\n this._refractionTexture.dispose();\n }\n }\n this._renderTargets.dispose();\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);\n };\n /**\n * Stores the reflectivity values based on metallic roughness workflow.\n */\n PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();\n __decorate([\n BABYLON.serializeAsImageProcessingConfiguration()\n ], PBRBaseMaterial.prototype, \"_imageProcessingConfiguration\", void 0);\n __decorate([\n BABYLON.serialize()\n ], PBRBaseMaterial.prototype, \"useLogarithmicDepth\", null);\n __decorate([\n BABYLON.serialize()\n ], PBRBaseMaterial.prototype, \"transparencyMode\", null);\n return PBRBaseMaterial;\n }(BABYLON.PushMaterial));\n BABYLON.PBRBaseMaterial = PBRBaseMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pbrBaseMaterial.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The Physically based simple base material of BJS.\n *\n * This enables better naming and convention enforcements on top of the pbrMaterial.\n * It is used as the base class for both the specGloss and metalRough conventions.\n */\n var PBRBaseSimpleMaterial = /** @class */ (function (_super) {\n __extends(PBRBaseSimpleMaterial, _super);\n /**\n * Instantiates a new PBRMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n function PBRBaseSimpleMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n _this.maxSimultaneousLights = 4;\n /**\n * If sets to true, disables all the lights affecting the material.\n */\n _this.disableLighting = false;\n /**\n * If sets to true, x component of normal map value will invert (x = 1.0 - x).\n */\n _this.invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will invert (y = 1.0 - y).\n */\n _this.invertNormalMapY = false;\n /**\n * Emissivie color used to self-illuminate the model.\n */\n _this.emissiveColor = new BABYLON.Color3(0, 0, 0);\n /**\n * Occlusion Channel Strenght.\n */\n _this.occlusionStrength = 1.0;\n _this.useLightmapAsShadowmap = false;\n _this._useAlphaFromAlbedoTexture = true;\n _this._useAmbientInGrayScale = true;\n return _this;\n }\n Object.defineProperty(PBRBaseSimpleMaterial.prototype, \"doubleSided\", {\n /**\n * Gets the current double sided mode.\n */\n get: function () {\n return this._twoSidedLighting;\n },\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n */\n set: function (value) {\n if (this._twoSidedLighting === value) {\n return;\n }\n this._twoSidedLighting = value;\n this.backFaceCulling = !value;\n this._markAllSubMeshesAsTexturesDirty();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Return the active textures of the material.\n */\n PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {\n var activeTextures = _super.prototype.getActiveTextures.call(this);\n if (this.environmentTexture) {\n activeTextures.push(this.environmentTexture);\n }\n if (this.normalTexture) {\n activeTextures.push(this.normalTexture);\n }\n if (this.emissiveTexture) {\n activeTextures.push(this.emissiveTexture);\n }\n if (this.occlusionTexture) {\n activeTextures.push(this.occlusionTexture);\n }\n if (this.lightmapTexture) {\n activeTextures.push(this.lightmapTexture);\n }\n return activeTextures;\n };\n PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {\n if (_super.prototype.hasTexture.call(this, texture)) {\n return true;\n }\n if (this.lightmapTexture === texture) {\n return true;\n }\n return false;\n };\n PBRBaseSimpleMaterial.prototype.getClassName = function () {\n return \"PBRBaseSimpleMaterial\";\n };\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"maxSimultaneousLights\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"disableLighting\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_reflectionTexture\")\n ], PBRBaseSimpleMaterial.prototype, \"environmentTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"invertNormalMapX\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"invertNormalMapY\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_bumpTexture\")\n ], PBRBaseSimpleMaterial.prototype, \"normalTexture\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"emissive\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"emissiveColor\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"emissiveTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_ambientTextureStrength\")\n ], PBRBaseSimpleMaterial.prototype, \"occlusionStrength\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_ambientTexture\")\n ], PBRBaseSimpleMaterial.prototype, \"occlusionTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_alphaCutOff\")\n ], PBRBaseSimpleMaterial.prototype, \"alphaCutOff\", void 0);\n __decorate([\n BABYLON.serialize()\n ], PBRBaseSimpleMaterial.prototype, \"doubleSided\", null);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", null)\n ], PBRBaseSimpleMaterial.prototype, \"lightmapTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRBaseSimpleMaterial.prototype, \"useLightmapAsShadowmap\", void 0);\n return PBRBaseSimpleMaterial;\n }(BABYLON.PBRBaseMaterial));\n BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The Physically based material of BJS.\n *\n * This offers the main features of a standard PBR material.\n * For more information, please refer to the documentation :\n * http://doc.babylonjs.com/extensions/Physically_Based_Rendering\n */\n var PBRMaterial = /** @class */ (function (_super) {\n __extends(PBRMaterial, _super);\n /**\n * Instantiates a new PBRMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n function PBRMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n /**\n * Intensity of the direct lights e.g. the four lights available in your scene.\n * This impacts both the direct diffuse and specular highlights.\n */\n _this.directIntensity = 1.0;\n /**\n * Intensity of the emissive part of the material.\n * This helps controlling the emissive effect without modifying the emissive color.\n */\n _this.emissiveIntensity = 1.0;\n /**\n * Intensity of the environment e.g. how much the environment will light the object\n * either through harmonics for rough material or through the refelction for shiny ones.\n */\n _this.environmentIntensity = 1.0;\n /**\n * This is a special control allowing the reduction of the specular highlights coming from the\n * four lights of the scene. Those highlights may not be needed in full environment lighting.\n */\n _this.specularIntensity = 1.0;\n /**\n * Debug Control allowing disabling the bump map on this material.\n */\n _this.disableBumpMap = false;\n /**\n * AKA Occlusion Texture Intensity in other nomenclature.\n */\n _this.ambientTextureStrength = 1.0;\n /**\n * The color of a material in ambient lighting.\n */\n _this.ambientColor = new BABYLON.Color3(0, 0, 0);\n /**\n * AKA Diffuse Color in other nomenclature.\n */\n _this.albedoColor = new BABYLON.Color3(1, 1, 1);\n /**\n * AKA Specular Color in other nomenclature.\n */\n _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);\n /**\n * The color reflected from the material.\n */\n _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);\n /**\n * The color emitted from the material.\n */\n _this.emissiveColor = new BABYLON.Color3(0, 0, 0);\n /**\n * AKA Glossiness in other nomenclature.\n */\n _this.microSurface = 1.0;\n /**\n * source material index of refraction (IOR)' / 'destination material IOR.\n */\n _this.indexOfRefraction = 0.66;\n /**\n * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.\n */\n _this.invertRefractionY = false;\n /**\n * This parameters will make the material used its opacity to control how much it is refracting aginst not.\n * Materials half opaque for instance using refraction could benefit from this control.\n */\n _this.linkRefractionWithTransparency = false;\n _this.useLightmapAsShadowmap = false;\n /**\n * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.\n */\n _this.useAlphaFromAlbedoTexture = false;\n /**\n * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.\n */\n _this.forceAlphaTest = false;\n /**\n * Defines the alpha limits in alpha test mode.\n */\n _this.alphaCutOff = 0.4;\n /**\n * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).\n * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.\n */\n _this.useSpecularOverAlpha = true;\n /**\n * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.\n */\n _this.useMicroSurfaceFromReflectivityMapAlpha = false;\n /**\n * Specifies if the metallic texture contains the roughness information in its alpha channel.\n */\n _this.useRoughnessFromMetallicTextureAlpha = true;\n /**\n * Specifies if the metallic texture contains the roughness information in its green channel.\n */\n _this.useRoughnessFromMetallicTextureGreen = false;\n /**\n * Specifies if the metallic texture contains the metallness information in its blue channel.\n */\n _this.useMetallnessFromMetallicTextureBlue = false;\n /**\n * Specifies if the metallic texture contains the ambient occlusion information in its red channel.\n */\n _this.useAmbientOcclusionFromMetallicTextureRed = false;\n /**\n * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.\n */\n _this.useAmbientInGrayScale = false;\n /**\n * In case the reflectivity map does not contain the microsurface information in its alpha channel,\n * The material will try to infer what glossiness each pixel should be.\n */\n _this.useAutoMicroSurfaceFromReflectivityMap = false;\n /**\n * BJS is using an harcoded light falloff based on a manually sets up range.\n * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.\n * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.\n */\n _this.usePhysicalLightFalloff = true;\n /**\n * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).\n * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.\n */\n _this.useRadianceOverAlpha = true;\n /**\n * Allows using an object space normal map (instead of tangent space).\n */\n _this.useObjectSpaceNormalMap = false;\n /**\n * Allows using the bump map in parallax mode.\n */\n _this.useParallax = false;\n /**\n * Allows using the bump map in parallax occlusion mode.\n */\n _this.useParallaxOcclusion = false;\n /**\n * Controls the scale bias of the parallax mode.\n */\n _this.parallaxScaleBias = 0.05;\n /**\n * If sets to true, disables all the lights affecting the material.\n */\n _this.disableLighting = false;\n /**\n * Force the shader to compute irradiance in the fragment shader in order to take bump in account.\n */\n _this.forceIrradianceInFragment = false;\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n _this.maxSimultaneousLights = 4;\n /**\n * If sets to true, x component of normal map value will invert (x = 1.0 - x).\n */\n _this.invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will invert (y = 1.0 - y).\n */\n _this.invertNormalMapY = false;\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n */\n _this.twoSidedLighting = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)\n */\n _this.useAlphaFresnel = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)\n */\n _this.useLinearAlphaFresnel = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part.\n */\n _this.environmentBRDFTexture = null;\n /**\n * Force normal to face away from face.\n */\n _this.forceNormalForward = false;\n /**\n * Enables specular anti aliasing in the PBR shader.\n * It will both interacts on the Geometry for analytical and IBL lighting.\n * It also prefilter the roughness map based on the bump values.\n */\n _this.enableSpecularAntiAliasing = false;\n /**\n * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal\n * makes the reflect vector face the model (under horizon).\n */\n _this.useHorizonOcclusion = true;\n /**\n * This parameters will enable/disable radiance occlusion by preventing the radiance to lit\n * too much the area relying on ambient texture to define their ambient occlusion.\n */\n _this.useRadianceOcclusion = true;\n /**\n * If set to true, no lighting calculations will be applied.\n */\n _this.unlit = false;\n _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);\n return _this;\n }\n Object.defineProperty(PBRMaterial, \"PBRMATERIAL_OPAQUE\", {\n /**\n * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.\n */\n get: function () {\n return this._PBRMATERIAL_OPAQUE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial, \"PBRMATERIAL_ALPHATEST\", {\n /**\n * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.\n */\n get: function () {\n return this._PBRMATERIAL_ALPHATEST;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial, \"PBRMATERIAL_ALPHABLEND\", {\n /**\n * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n */\n get: function () {\n return this._PBRMATERIAL_ALPHABLEND;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial, \"PBRMATERIAL_ALPHATESTANDBLEND\", {\n /**\n * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n * They are also discarded below the alpha cutoff threshold to improve performances.\n */\n get: function () {\n return this._PBRMATERIAL_ALPHATESTANDBLEND;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial.prototype, \"imageProcessingConfiguration\", {\n /**\n * Gets the image processing configuration used either in this material.\n */\n get: function () {\n return this._imageProcessingConfiguration;\n },\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set: function (value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial.prototype, \"cameraColorCurvesEnabled\", {\n /**\n * Gets wether the color curves effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n },\n /**\n * Sets wether the color curves effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial.prototype, \"cameraColorGradingEnabled\", {\n /**\n * Gets wether the color grading effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n },\n /**\n * Gets wether the color grading effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial.prototype, \"cameraToneMappingEnabled\", {\n /**\n * Gets wether tonemapping is enabled or not.\n */\n get: function () {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n },\n /**\n * Sets wether tonemapping is enabled or not\n */\n set: function (value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(PBRMaterial.prototype, \"cameraExposure\", {\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n get: function () {\n return this._imageProcessingConfiguration.exposure;\n },\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n set: function (value) {\n this._imageProcessingConfiguration.exposure = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(PBRMaterial.prototype, \"cameraContrast\", {\n /**\n * Gets The camera contrast used on this material.\n */\n get: function () {\n return this._imageProcessingConfiguration.contrast;\n },\n /**\n * Sets The camera contrast used on this material.\n */\n set: function (value) {\n this._imageProcessingConfiguration.contrast = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial.prototype, \"cameraColorGradingTexture\", {\n /**\n * Gets the Color Grading 2D Lookup Texture.\n */\n get: function () {\n return this._imageProcessingConfiguration.colorGradingTexture;\n },\n /**\n * Sets the Color Grading 2D Lookup Texture.\n */\n set: function (value) {\n this._imageProcessingConfiguration.colorGradingTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PBRMaterial.prototype, \"cameraColorCurves\", {\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n get: function () {\n return this._imageProcessingConfiguration.colorCurves;\n },\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n set: function (value) {\n this._imageProcessingConfiguration.colorCurves = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the name of this material class.\n */\n PBRMaterial.prototype.getClassName = function () {\n return \"PBRMaterial\";\n };\n /**\n * Returns an array of the actively used textures.\n * @returns - Array of BaseTextures\n */\n PBRMaterial.prototype.getActiveTextures = function () {\n var activeTextures = _super.prototype.getActiveTextures.call(this);\n if (this._albedoTexture) {\n activeTextures.push(this._albedoTexture);\n }\n if (this._ambientTexture) {\n activeTextures.push(this._ambientTexture);\n }\n if (this._opacityTexture) {\n activeTextures.push(this._opacityTexture);\n }\n if (this._reflectionTexture) {\n activeTextures.push(this._reflectionTexture);\n }\n if (this._emissiveTexture) {\n activeTextures.push(this._emissiveTexture);\n }\n if (this._reflectivityTexture) {\n activeTextures.push(this._reflectivityTexture);\n }\n if (this._metallicTexture) {\n activeTextures.push(this._metallicTexture);\n }\n if (this._microSurfaceTexture) {\n activeTextures.push(this._microSurfaceTexture);\n }\n if (this._bumpTexture) {\n activeTextures.push(this._bumpTexture);\n }\n if (this._lightmapTexture) {\n activeTextures.push(this._lightmapTexture);\n }\n if (this._refractionTexture) {\n activeTextures.push(this._refractionTexture);\n }\n return activeTextures;\n };\n /**\n * Checks to see if a texture is used in the material.\n * @param texture - Base texture to use.\n * @returns - Boolean specifying if a texture is used in the material.\n */\n PBRMaterial.prototype.hasTexture = function (texture) {\n if (_super.prototype.hasTexture.call(this, texture)) {\n return true;\n }\n if (this._albedoTexture === texture) {\n return true;\n }\n if (this._ambientTexture === texture) {\n return true;\n }\n if (this._opacityTexture === texture) {\n return true;\n }\n if (this._reflectionTexture === texture) {\n return true;\n }\n if (this._reflectivityTexture === texture) {\n return true;\n }\n if (this._metallicTexture === texture) {\n return true;\n }\n if (this._microSurfaceTexture === texture) {\n return true;\n }\n if (this._bumpTexture === texture) {\n return true;\n }\n if (this._lightmapTexture === texture) {\n return true;\n }\n if (this._refractionTexture === texture) {\n return true;\n }\n return false;\n };\n /**\n * Makes a duplicate of the current material.\n * @param name - name to use for the new material.\n */\n PBRMaterial.prototype.clone = function (name) {\n var _this = this;\n var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);\n clone.id = name;\n clone.name = name;\n return clone;\n };\n /**\n * Serializes this PBR Material.\n * @returns - An object with the serialized material.\n */\n PBRMaterial.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.PBRMaterial\";\n return serializationObject;\n };\n // Statics\n /**\n * Parses a PBR Material from a serialized object.\n * @param source - Serialized object.\n * @param scene - BJS scene instance.\n * @param rootUrl - url for the scene object\n * @returns - PBRMaterial\n */\n PBRMaterial.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);\n };\n PBRMaterial._PBRMATERIAL_OPAQUE = 0;\n /**\n * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.\n */\n PBRMaterial._PBRMATERIAL_ALPHATEST = 1;\n /**\n * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n */\n PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;\n /**\n * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n * They are also discarded below the alpha cutoff threshold to improve performances.\n */\n PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"directIntensity\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"emissiveIntensity\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"environmentIntensity\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"specularIntensity\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"disableBumpMap\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"albedoTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"ambientTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"ambientTextureStrength\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n ], PBRMaterial.prototype, \"opacityTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"reflectionTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"emissiveTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"reflectivityTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"metallicTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"metallic\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"roughness\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"microSurfaceTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"bumpTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", null)\n ], PBRMaterial.prototype, \"lightmapTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"refractionTexture\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"ambient\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"ambientColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"albedo\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"albedoColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"reflectivity\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"reflectivityColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"reflection\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"reflectionColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"emissive\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"emissiveColor\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"microSurface\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"indexOfRefraction\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"invertRefractionY\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"linkRefractionWithTransparency\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useLightmapAsShadowmap\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n ], PBRMaterial.prototype, \"useAlphaFromAlbedoTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n ], PBRMaterial.prototype, \"forceAlphaTest\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n ], PBRMaterial.prototype, \"alphaCutOff\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useSpecularOverAlpha\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useMicroSurfaceFromReflectivityMapAlpha\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useRoughnessFromMetallicTextureAlpha\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useRoughnessFromMetallicTextureGreen\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useMetallnessFromMetallicTextureBlue\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useAmbientOcclusionFromMetallicTextureRed\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useAmbientInGrayScale\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useAutoMicroSurfaceFromReflectivityMap\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"usePhysicalLightFalloff\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useRadianceOverAlpha\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useObjectSpaceNormalMap\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useParallax\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useParallaxOcclusion\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"parallaxScaleBias\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], PBRMaterial.prototype, \"disableLighting\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"forceIrradianceInFragment\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], PBRMaterial.prototype, \"maxSimultaneousLights\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"invertNormalMapX\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"invertNormalMapY\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"twoSidedLighting\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useAlphaFresnel\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useLinearAlphaFresnel\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"environmentBRDFTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"forceNormalForward\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"enableSpecularAntiAliasing\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useHorizonOcclusion\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMaterial.prototype, \"useRadianceOcclusion\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n ], PBRMaterial.prototype, \"unlit\", void 0);\n return PBRMaterial;\n }(BABYLON.PBRBaseMaterial));\n BABYLON.PBRMaterial = PBRMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pbrMaterial.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The PBR material of BJS following the metal roughness convention.\n *\n * This fits to the PBR convention in the GLTF definition:\n * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0\n */\n var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {\n __extends(PBRMetallicRoughnessMaterial, _super);\n /**\n * Instantiates a new PBRMetalRoughnessMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n function PBRMetallicRoughnessMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._useRoughnessFromMetallicTextureAlpha = false;\n _this._useRoughnessFromMetallicTextureGreen = true;\n _this._useMetallnessFromMetallicTextureBlue = true;\n _this.metallic = 1.0;\n _this.roughness = 1.0;\n return _this;\n }\n /**\n * Return the currrent class name of the material.\n */\n PBRMetallicRoughnessMaterial.prototype.getClassName = function () {\n return \"PBRMetallicRoughnessMaterial\";\n };\n /**\n * Return the active textures of the material.\n */\n PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {\n var activeTextures = _super.prototype.getActiveTextures.call(this);\n if (this.baseTexture) {\n activeTextures.push(this.baseTexture);\n }\n if (this.metallicRoughnessTexture) {\n activeTextures.push(this.metallicRoughnessTexture);\n }\n return activeTextures;\n };\n /**\n * Checks to see if a texture is used in the material.\n * @param texture - Base texture to use.\n * @returns - Boolean specifying if a texture is used in the material.\n */\n PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {\n if (_super.prototype.hasTexture.call(this, texture)) {\n return true;\n }\n if (this.baseTexture === texture) {\n return true;\n }\n if (this.metallicRoughnessTexture === texture) {\n return true;\n }\n return false;\n };\n /**\n * Makes a duplicate of the current material.\n * @param name - name to use for the new material.\n */\n PBRMetallicRoughnessMaterial.prototype.clone = function (name) {\n var _this = this;\n var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);\n clone.id = name;\n clone.name = name;\n return clone;\n };\n /**\n * Serialize the material to a parsable JSON object.\n */\n PBRMetallicRoughnessMaterial.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.PBRMetallicRoughnessMaterial\";\n return serializationObject;\n };\n /**\n * Parses a JSON object correponding to the serialize function.\n */\n PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);\n };\n __decorate([\n BABYLON.serializeAsColor3(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoColor\")\n ], PBRMetallicRoughnessMaterial.prototype, \"baseColor\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoTexture\")\n ], PBRMetallicRoughnessMaterial.prototype, \"baseTexture\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMetallicRoughnessMaterial.prototype, \"metallic\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], PBRMetallicRoughnessMaterial.prototype, \"roughness\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_metallicTexture\")\n ], PBRMetallicRoughnessMaterial.prototype, \"metallicRoughnessTexture\", void 0);\n return PBRMetallicRoughnessMaterial;\n }(BABYLON.PBRBaseSimpleMaterial));\n BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The PBR material of BJS following the specular glossiness convention.\n *\n * This fits to the PBR convention in the GLTF definition:\n * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness\n */\n var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {\n __extends(PBRSpecularGlossinessMaterial, _super);\n /**\n * Instantiates a new PBRSpecularGlossinessMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n function PBRSpecularGlossinessMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._useMicroSurfaceFromReflectivityMapAlpha = true;\n return _this;\n }\n /**\n * Return the currrent class name of the material.\n */\n PBRSpecularGlossinessMaterial.prototype.getClassName = function () {\n return \"PBRSpecularGlossinessMaterial\";\n };\n /**\n * Return the active textures of the material.\n */\n PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {\n var activeTextures = _super.prototype.getActiveTextures.call(this);\n if (this.diffuseTexture) {\n activeTextures.push(this.diffuseTexture);\n }\n if (this.specularGlossinessTexture) {\n activeTextures.push(this.specularGlossinessTexture);\n }\n return activeTextures;\n };\n /**\n * Checks to see if a texture is used in the material.\n * @param texture - Base texture to use.\n * @returns - Boolean specifying if a texture is used in the material.\n */\n PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {\n if (_super.prototype.hasTexture.call(this, texture)) {\n return true;\n }\n if (this.diffuseTexture === texture) {\n return true;\n }\n if (this.specularGlossinessTexture === texture) {\n return true;\n }\n return false;\n };\n /**\n * Makes a duplicate of the current material.\n * @param name - name to use for the new material.\n */\n PBRSpecularGlossinessMaterial.prototype.clone = function (name) {\n var _this = this;\n var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);\n clone.id = name;\n clone.name = name;\n return clone;\n };\n /**\n * Serialize the material to a parsable JSON object.\n */\n PBRSpecularGlossinessMaterial.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.PBRSpecularGlossinessMaterial\";\n return serializationObject;\n };\n /**\n * Parses a JSON object correponding to the serialize function.\n */\n PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);\n };\n __decorate([\n BABYLON.serializeAsColor3(\"diffuse\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoColor\")\n ], PBRSpecularGlossinessMaterial.prototype, \"diffuseColor\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoTexture\")\n ], PBRSpecularGlossinessMaterial.prototype, \"diffuseTexture\", void 0);\n __decorate([\n BABYLON.serializeAsColor3(\"specular\"),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_reflectivityColor\")\n ], PBRSpecularGlossinessMaterial.prototype, \"specularColor\", void 0);\n __decorate([\n BABYLON.serialize(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_microSurface\")\n ], PBRSpecularGlossinessMaterial.prototype, \"glossiness\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(),\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_reflectivityTexture\")\n ], PBRSpecularGlossinessMaterial.prototype, \"specularGlossinessTexture\", void 0);\n return PBRSpecularGlossinessMaterial;\n }(BABYLON.PBRBaseSimpleMaterial));\n BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.CameraInputTypes = {};\n var CameraInputsManager = /** @class */ (function () {\n function CameraInputsManager(camera) {\n this.attached = {};\n this.camera = camera;\n this.checkInputs = function () { };\n }\n /**\n * Add an input method to a camera\n * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs\n * @param input camera input method\n */\n CameraInputsManager.prototype.add = function (input) {\n var type = input.getSimpleName();\n if (this.attached[type]) {\n BABYLON.Tools.Warn(\"camera input of type \" + type + \" already exists on camera\");\n return;\n }\n this.attached[type] = input;\n input.camera = this.camera;\n //for checkInputs, we are dynamically creating a function\n //the goal is to avoid the performance penalty of looping for inputs in the render loop\n if (input.checkInputs) {\n this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));\n }\n if (this.attachedElement) {\n input.attachControl(this.attachedElement);\n }\n };\n /**\n * Remove a specific input method from a camera\n * example: camera.inputs.remove(camera.inputs.attached.mouse);\n * @param inputToRemove camera input method\n */\n CameraInputsManager.prototype.remove = function (inputToRemove) {\n for (var cam in this.attached) {\n var input = this.attached[cam];\n if (input === inputToRemove) {\n input.detachControl(this.attachedElement);\n input.camera = null;\n delete this.attached[cam];\n this.rebuildInputCheck();\n }\n }\n };\n CameraInputsManager.prototype.removeByType = function (inputType) {\n for (var cam in this.attached) {\n var input = this.attached[cam];\n if (input.getClassName() === inputType) {\n input.detachControl(this.attachedElement);\n input.camera = null;\n delete this.attached[cam];\n this.rebuildInputCheck();\n }\n }\n };\n CameraInputsManager.prototype._addCheckInputs = function (fn) {\n var current = this.checkInputs;\n return function () {\n current();\n fn();\n };\n };\n CameraInputsManager.prototype.attachInput = function (input) {\n if (this.attachedElement) {\n input.attachControl(this.attachedElement, this.noPreventDefault);\n }\n };\n CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {\n if (noPreventDefault === void 0) { noPreventDefault = false; }\n if (this.attachedElement) {\n return;\n }\n noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;\n this.attachedElement = element;\n this.noPreventDefault = noPreventDefault;\n for (var cam in this.attached) {\n this.attached[cam].attachControl(element, noPreventDefault);\n }\n };\n CameraInputsManager.prototype.detachElement = function (element, disconnect) {\n if (disconnect === void 0) { disconnect = false; }\n if (this.attachedElement !== element) {\n return;\n }\n for (var cam in this.attached) {\n this.attached[cam].detachControl(element);\n if (disconnect) {\n this.attached[cam].camera = null;\n }\n }\n this.attachedElement = null;\n };\n CameraInputsManager.prototype.rebuildInputCheck = function () {\n this.checkInputs = function () { };\n for (var cam in this.attached) {\n var input = this.attached[cam];\n if (input.checkInputs) {\n this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));\n }\n }\n };\n /**\n * Remove all attached input methods from a camera\n */\n CameraInputsManager.prototype.clear = function () {\n if (this.attachedElement) {\n this.detachElement(this.attachedElement, true);\n }\n this.attached = {};\n this.attachedElement = null;\n this.checkInputs = function () { };\n };\n CameraInputsManager.prototype.serialize = function (serializedCamera) {\n var inputs = {};\n for (var cam in this.attached) {\n var input = this.attached[cam];\n var res = BABYLON.SerializationHelper.Serialize(input);\n inputs[input.getClassName()] = res;\n }\n serializedCamera.inputsmgr = inputs;\n };\n CameraInputsManager.prototype.parse = function (parsedCamera) {\n var parsedInputs = parsedCamera.inputsmgr;\n if (parsedInputs) {\n this.clear();\n for (var n in parsedInputs) {\n var construct = BABYLON.CameraInputTypes[n];\n if (construct) {\n var parsedinput = parsedInputs[n];\n var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);\n this.add(input);\n }\n }\n }\n else {\n //2016-03-08 this part is for managing backward compatibility\n for (var n in this.attached) {\n var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];\n if (construct) {\n var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);\n this.remove(this.attached[n]);\n this.add(input);\n }\n }\n }\n };\n return CameraInputsManager;\n }());\n BABYLON.CameraInputsManager = CameraInputsManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.cameraInputsManager.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var TargetCamera = /** @class */ (function (_super) {\n __extends(TargetCamera, _super);\n function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {\n if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }\n var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;\n _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);\n _this.cameraRotation = new BABYLON.Vector2(0, 0);\n _this.rotation = new BABYLON.Vector3(0, 0, 0);\n _this.speed = 2.0;\n _this.noRotationConstraint = false;\n _this.lockedTarget = null;\n _this._currentTarget = BABYLON.Vector3.Zero();\n _this._viewMatrix = BABYLON.Matrix.Zero();\n _this._camMatrix = BABYLON.Matrix.Zero();\n _this._cameraTransformMatrix = BABYLON.Matrix.Zero();\n _this._cameraRotationMatrix = BABYLON.Matrix.Zero();\n _this._referencePoint = new BABYLON.Vector3(0, 0, 1);\n _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);\n _this._transformedReferencePoint = BABYLON.Vector3.Zero();\n _this._globalCurrentTarget = BABYLON.Vector3.Zero();\n _this._globalCurrentUpVector = BABYLON.Vector3.Zero();\n return _this;\n }\n TargetCamera.prototype.getFrontPosition = function (distance) {\n this.getWorldMatrix();\n var direction = this.getTarget().subtract(this.position);\n direction.normalize();\n direction.scaleInPlace(distance);\n return this.globalPosition.add(direction);\n };\n TargetCamera.prototype._getLockedTargetPosition = function () {\n if (!this.lockedTarget) {\n return null;\n }\n if (this.lockedTarget.absolutePosition) {\n this.lockedTarget.computeWorldMatrix();\n }\n return this.lockedTarget.absolutePosition || this.lockedTarget;\n };\n TargetCamera.prototype.storeState = function () {\n this._storedPosition = this.position.clone();\n this._storedRotation = this.rotation.clone();\n if (this.rotationQuaternion) {\n this._storedRotationQuaternion = this.rotationQuaternion.clone();\n }\n return _super.prototype.storeState.call(this);\n };\n /**\n * Restored camera state. You must call storeState() first\n */\n TargetCamera.prototype._restoreStateValues = function () {\n if (!_super.prototype._restoreStateValues.call(this)) {\n return false;\n }\n this.position = this._storedPosition.clone();\n this.rotation = this._storedRotation.clone();\n if (this.rotationQuaternion) {\n this.rotationQuaternion = this._storedRotationQuaternion.clone();\n }\n this.cameraDirection.copyFromFloats(0, 0, 0);\n this.cameraRotation.copyFromFloats(0, 0);\n return true;\n };\n // Cache\n TargetCamera.prototype._initCache = function () {\n _super.prototype._initCache.call(this);\n this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n };\n TargetCamera.prototype._updateCache = function (ignoreParentClass) {\n if (!ignoreParentClass) {\n _super.prototype._updateCache.call(this);\n }\n var lockedTargetPosition = this._getLockedTargetPosition();\n if (!lockedTargetPosition) {\n this._cache.lockedTarget = null;\n }\n else {\n if (!this._cache.lockedTarget) {\n this._cache.lockedTarget = lockedTargetPosition.clone();\n }\n else {\n this._cache.lockedTarget.copyFrom(lockedTargetPosition);\n }\n }\n this._cache.rotation.copyFrom(this.rotation);\n if (this.rotationQuaternion)\n this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);\n };\n // Synchronized\n TargetCamera.prototype._isSynchronizedViewMatrix = function () {\n if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {\n return false;\n }\n var lockedTargetPosition = this._getLockedTargetPosition();\n return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)\n && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));\n };\n // Methods\n TargetCamera.prototype._computeLocalCameraSpeed = function () {\n var engine = this.getEngine();\n return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));\n };\n // Target\n TargetCamera.prototype.setTarget = function (target) {\n this.upVector.normalize();\n BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);\n this._camMatrix.invert();\n this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);\n var vDir = target.subtract(this.position);\n if (vDir.x >= 0.0) {\n this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);\n }\n else {\n this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);\n }\n this.rotation.z = 0;\n if (isNaN(this.rotation.x)) {\n this.rotation.x = 0;\n }\n if (isNaN(this.rotation.y)) {\n this.rotation.y = 0;\n }\n if (isNaN(this.rotation.z)) {\n this.rotation.z = 0;\n }\n if (this.rotationQuaternion) {\n BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);\n }\n };\n /**\n * Return the current target position of the camera. This value is expressed in local space.\n */\n TargetCamera.prototype.getTarget = function () {\n return this._currentTarget;\n };\n TargetCamera.prototype._decideIfNeedsToMove = function () {\n return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;\n };\n TargetCamera.prototype._updatePosition = function () {\n if (this.parent) {\n this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);\n BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);\n this.position.addInPlace(BABYLON.Tmp.Vector3[0]);\n return;\n }\n this.position.addInPlace(this.cameraDirection);\n };\n TargetCamera.prototype._checkInputs = function () {\n var needToMove = this._decideIfNeedsToMove();\n var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;\n // Move\n if (needToMove) {\n this._updatePosition();\n }\n // Rotate\n if (needToRotate) {\n this.rotation.x += this.cameraRotation.x;\n this.rotation.y += this.cameraRotation.y;\n //rotate, if quaternion is set and rotation was used\n if (this.rotationQuaternion) {\n var len = this.rotation.lengthSquared();\n if (len) {\n BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);\n }\n }\n if (!this.noRotationConstraint) {\n var limit = (Math.PI / 2) * 0.95;\n if (this.rotation.x > limit)\n this.rotation.x = limit;\n if (this.rotation.x < -limit)\n this.rotation.x = -limit;\n }\n }\n // Inertia\n if (needToMove) {\n if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {\n this.cameraDirection.x = 0;\n }\n if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {\n this.cameraDirection.y = 0;\n }\n if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {\n this.cameraDirection.z = 0;\n }\n this.cameraDirection.scaleInPlace(this.inertia);\n }\n if (needToRotate) {\n if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {\n this.cameraRotation.x = 0;\n }\n if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {\n this.cameraRotation.y = 0;\n }\n this.cameraRotation.scaleInPlace(this.inertia);\n }\n _super.prototype._checkInputs.call(this);\n };\n TargetCamera.prototype._updateCameraRotationMatrix = function () {\n if (this.rotationQuaternion) {\n this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);\n }\n else {\n BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);\n }\n //update the up vector!\n BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);\n };\n TargetCamera.prototype._getViewMatrix = function () {\n if (this.lockedTarget) {\n this.setTarget(this._getLockedTargetPosition());\n }\n // Compute\n this._updateCameraRotationMatrix();\n BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);\n // Computing target and final matrix\n this.position.addToRef(this._transformedReferencePoint, this._currentTarget);\n this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);\n return this._viewMatrix;\n };\n TargetCamera.prototype._computeViewMatrix = function (position, target, up) {\n if (this.parent) {\n var parentWorldMatrix = this.parent.getWorldMatrix();\n BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);\n BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);\n BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);\n this._markSyncedWithParent();\n }\n else {\n this._globalPosition.copyFrom(this.position);\n this._globalCurrentTarget.copyFrom(target);\n this._globalCurrentUpVector.copyFrom(up);\n }\n if (this.getScene().useRightHandedSystem) {\n BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);\n }\n else {\n BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);\n }\n };\n /**\n * @override\n * Override Camera.createRigCamera\n */\n TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {\n if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {\n var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());\n if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {\n if (!this.rotationQuaternion) {\n this.rotationQuaternion = new BABYLON.Quaternion();\n }\n rigCamera._cameraRigParams = {};\n rigCamera.rotationQuaternion = new BABYLON.Quaternion();\n }\n return rigCamera;\n }\n return null;\n };\n /**\n * @override\n * Override Camera._updateRigCameras\n */\n TargetCamera.prototype._updateRigCameras = function () {\n var camLeft = this._rigCameras[0];\n var camRight = this._rigCameras[1];\n switch (this.cameraRigMode) {\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:\n var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;\n var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;\n this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);\n this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);\n camLeft.setTarget(this.getTarget());\n camRight.setTarget(this.getTarget());\n break;\n case BABYLON.Camera.RIG_MODE_VR:\n if (camLeft.rotationQuaternion) {\n camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);\n camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);\n }\n else {\n camLeft.rotation.copyFrom(this.rotation);\n camRight.rotation.copyFrom(this.rotation);\n }\n camLeft.position.copyFrom(this.position);\n camRight.position.copyFrom(this.position);\n break;\n }\n _super.prototype._updateRigCameras.call(this);\n };\n TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {\n if (!this._rigCamTransformMatrix) {\n this._rigCamTransformMatrix = new BABYLON.Matrix();\n }\n var target = this.getTarget();\n BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);\n this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));\n BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);\n };\n TargetCamera.prototype.getClassName = function () {\n return \"TargetCamera\";\n };\n __decorate([\n BABYLON.serializeAsVector3()\n ], TargetCamera.prototype, \"rotation\", void 0);\n __decorate([\n BABYLON.serialize()\n ], TargetCamera.prototype, \"speed\", void 0);\n __decorate([\n BABYLON.serializeAsMeshReference(\"lockedTargetId\")\n ], TargetCamera.prototype, \"lockedTarget\", void 0);\n return TargetCamera;\n }(BABYLON.Camera));\n BABYLON.TargetCamera = TargetCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.targetCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FreeCameraMouseInput = /** @class */ (function () {\n function FreeCameraMouseInput(touchEnabled) {\n if (touchEnabled === void 0) { touchEnabled = true; }\n this.touchEnabled = touchEnabled;\n this.buttons = [0, 1, 2];\n this.angularSensibility = 2000.0;\n this.previousPosition = null;\n }\n FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n var engine = this.camera.getEngine();\n if (!this._pointerInput) {\n this._pointerInput = function (p, s) {\n var evt = p.event;\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n if (!_this.touchEnabled && evt.pointerType === \"touch\") {\n return;\n }\n if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {\n return;\n }\n var srcElement = (evt.srcElement || evt.target);\n if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {\n try {\n srcElement.setPointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error. Execution will continue.\n }\n _this.previousPosition = {\n x: evt.clientX,\n y: evt.clientY\n };\n if (!noPreventDefault) {\n evt.preventDefault();\n element.focus();\n }\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {\n try {\n srcElement.releasePointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error.\n }\n _this.previousPosition = null;\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {\n if (!_this.previousPosition || engine.isPointerLock) {\n return;\n }\n var offsetX = evt.clientX - _this.previousPosition.x;\n if (_this.camera.getScene().useRightHandedSystem)\n offsetX *= -1;\n if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)\n offsetX *= -1;\n _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;\n var offsetY = evt.clientY - _this.previousPosition.y;\n _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;\n _this.previousPosition = {\n x: evt.clientX,\n y: evt.clientY\n };\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n };\n }\n this._onMouseMove = function (evt) {\n if (!engine.isPointerLock) {\n return;\n }\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;\n if (_this.camera.getScene().useRightHandedSystem)\n offsetX *= -1;\n if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)\n offsetX *= -1;\n _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;\n var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;\n _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;\n _this.previousPosition = null;\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n };\n this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);\n element.addEventListener(\"mousemove\", this._onMouseMove, false);\n };\n FreeCameraMouseInput.prototype.detachControl = function (element) {\n if (this._observer && element) {\n this.camera.getScene().onPointerObservable.remove(this._observer);\n if (this._onMouseMove) {\n element.removeEventListener(\"mousemove\", this._onMouseMove);\n }\n this._observer = null;\n this._onMouseMove = null;\n this.previousPosition = null;\n }\n };\n FreeCameraMouseInput.prototype.getClassName = function () {\n return \"FreeCameraMouseInput\";\n };\n FreeCameraMouseInput.prototype.getSimpleName = function () {\n return \"mouse\";\n };\n __decorate([\n BABYLON.serialize()\n ], FreeCameraMouseInput.prototype, \"buttons\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCameraMouseInput.prototype, \"angularSensibility\", void 0);\n return FreeCameraMouseInput;\n }());\n BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;\n BABYLON.CameraInputTypes[\"FreeCameraMouseInput\"] = FreeCameraMouseInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraMouseInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FreeCameraKeyboardMoveInput = /** @class */ (function () {\n function FreeCameraKeyboardMoveInput() {\n this._keys = new Array();\n this.keysUp = [38];\n this.keysDown = [40];\n this.keysLeft = [37];\n this.keysRight = [39];\n }\n FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n if (this._onCanvasBlurObserver) {\n return;\n }\n this._scene = this.camera.getScene();\n this._engine = this._scene.getEngine();\n this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {\n _this._keys = [];\n });\n this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {\n var evt = info.event;\n if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {\n if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||\n _this.keysDown.indexOf(evt.keyCode) !== -1 ||\n _this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n _this.keysRight.indexOf(evt.keyCode) !== -1) {\n var index = _this._keys.indexOf(evt.keyCode);\n if (index === -1) {\n _this._keys.push(evt.keyCode);\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n else {\n if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||\n _this.keysDown.indexOf(evt.keyCode) !== -1 ||\n _this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n _this.keysRight.indexOf(evt.keyCode) !== -1) {\n var index = _this._keys.indexOf(evt.keyCode);\n if (index >= 0) {\n _this._keys.splice(index, 1);\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n });\n };\n FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {\n if (this._scene) {\n if (this._onKeyboardObserver) {\n this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);\n }\n if (this._onCanvasBlurObserver) {\n this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n this._onKeyboardObserver = null;\n this._onCanvasBlurObserver = null;\n }\n this._keys = [];\n };\n FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {\n if (this._onKeyboardObserver) {\n var camera = this.camera;\n // Keyboard\n for (var index = 0; index < this._keys.length; index++) {\n var keyCode = this._keys[index];\n var speed = camera._computeLocalCameraSpeed();\n if (this.keysLeft.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(-speed, 0, 0);\n }\n else if (this.keysUp.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, speed);\n }\n else if (this.keysRight.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(speed, 0, 0);\n }\n else if (this.keysDown.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, -speed);\n }\n if (camera.getScene().useRightHandedSystem) {\n camera._localDirection.z *= -1;\n }\n camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);\n BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);\n camera.cameraDirection.addInPlace(camera._transformedDirection);\n }\n }\n };\n FreeCameraKeyboardMoveInput.prototype.getClassName = function () {\n return \"FreeCameraKeyboardMoveInput\";\n };\n FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {\n this._keys = [];\n };\n FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {\n return \"keyboard\";\n };\n __decorate([\n BABYLON.serialize()\n ], FreeCameraKeyboardMoveInput.prototype, \"keysUp\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCameraKeyboardMoveInput.prototype, \"keysDown\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCameraKeyboardMoveInput.prototype, \"keysLeft\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCameraKeyboardMoveInput.prototype, \"keysRight\", void 0);\n return FreeCameraKeyboardMoveInput;\n }());\n BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;\n BABYLON.CameraInputTypes[\"FreeCameraKeyboardMoveInput\"] = FreeCameraKeyboardMoveInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FreeCameraInputsManager = /** @class */ (function (_super) {\n __extends(FreeCameraInputsManager, _super);\n function FreeCameraInputsManager(camera) {\n return _super.call(this, camera) || this;\n }\n FreeCameraInputsManager.prototype.addKeyboard = function () {\n this.add(new BABYLON.FreeCameraKeyboardMoveInput());\n return this;\n };\n FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {\n if (touchEnabled === void 0) { touchEnabled = true; }\n this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));\n return this;\n };\n FreeCameraInputsManager.prototype.addDeviceOrientation = function () {\n this.add(new BABYLON.FreeCameraDeviceOrientationInput());\n return this;\n };\n FreeCameraInputsManager.prototype.addTouch = function () {\n this.add(new BABYLON.FreeCameraTouchInput());\n return this;\n };\n FreeCameraInputsManager.prototype.addVirtualJoystick = function () {\n this.add(new BABYLON.FreeCameraVirtualJoystickInput());\n return this;\n };\n return FreeCameraInputsManager;\n }(BABYLON.CameraInputsManager));\n BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraInputsManager.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"FreeCamera\", function (name, scene) {\n // Forcing to use the Universal camera\n return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n var FreeCamera = /** @class */ (function (_super) {\n __extends(FreeCamera, _super);\n function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {\n if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }\n var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;\n _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);\n _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);\n _this.checkCollisions = false;\n _this.applyGravity = false;\n _this._needMoveForGravity = false;\n _this._oldPosition = BABYLON.Vector3.Zero();\n _this._diffPosition = BABYLON.Vector3.Zero();\n _this._newPosition = BABYLON.Vector3.Zero();\n // Collisions\n _this._collisionMask = -1;\n _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {\n if (collidedMesh === void 0) { collidedMesh = null; }\n //TODO move this to the collision coordinator!\n if (_this.getScene().workerCollisions)\n newPosition.multiplyInPlace(_this._collider._radius);\n var updatePosition = function (newPos) {\n _this._newPosition.copyFrom(newPos);\n _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);\n if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {\n _this.position.addInPlace(_this._diffPosition);\n if (_this.onCollide && collidedMesh) {\n _this.onCollide(collidedMesh);\n }\n }\n };\n updatePosition(newPosition);\n };\n _this.inputs = new BABYLON.FreeCameraInputsManager(_this);\n _this.inputs.addKeyboard().addMouse();\n return _this;\n }\n Object.defineProperty(FreeCamera.prototype, \"angularSensibility\", {\n //-- begin properties for backward compatibility for inputs\n /**\n * Gets the input sensibility for a mouse input. (default is 2000.0)\n * Higher values reduce sensitivity.\n */\n get: function () {\n var mouse = this.inputs.attached[\"mouse\"];\n if (mouse)\n return mouse.angularSensibility;\n return 0;\n },\n /**\n * Sets the input sensibility for a mouse input. (default is 2000.0)\n * Higher values reduce sensitivity.\n */\n set: function (value) {\n var mouse = this.inputs.attached[\"mouse\"];\n if (mouse)\n mouse.angularSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FreeCamera.prototype, \"keysUp\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysUp;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysUp = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FreeCamera.prototype, \"keysDown\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysDown;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysDown = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FreeCamera.prototype, \"keysLeft\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysLeft;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysLeft = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FreeCamera.prototype, \"keysRight\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysRight;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysRight = value;\n },\n enumerable: true,\n configurable: true\n });\n // Controls\n FreeCamera.prototype.attachControl = function (element, noPreventDefault) {\n this.inputs.attachElement(element, noPreventDefault);\n };\n FreeCamera.prototype.detachControl = function (element) {\n this.inputs.detachElement(element);\n this.cameraDirection = new BABYLON.Vector3(0, 0, 0);\n this.cameraRotation = new BABYLON.Vector2(0, 0);\n };\n Object.defineProperty(FreeCamera.prototype, \"collisionMask\", {\n get: function () {\n return this._collisionMask;\n },\n set: function (mask) {\n this._collisionMask = !isNaN(mask) ? mask : -1;\n },\n enumerable: true,\n configurable: true\n });\n FreeCamera.prototype._collideWithWorld = function (displacement) {\n var globalPosition;\n if (this.parent) {\n globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());\n }\n else {\n globalPosition = this.position;\n }\n globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);\n this._oldPosition.addInPlace(this.ellipsoidOffset);\n if (!this._collider) {\n this._collider = new BABYLON.Collider();\n }\n this._collider._radius = this.ellipsoid;\n this._collider.collisionMask = this._collisionMask;\n //no need for clone, as long as gravity is not on.\n var actualDisplacement = displacement;\n //add gravity to the direction to prevent the dual-collision checking\n if (this.applyGravity) {\n //this prevents mending with cameraDirection, a global variable of the free camera class.\n actualDisplacement = displacement.add(this.getScene().gravity);\n }\n this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);\n };\n FreeCamera.prototype._checkInputs = function () {\n if (!this._localDirection) {\n this._localDirection = BABYLON.Vector3.Zero();\n this._transformedDirection = BABYLON.Vector3.Zero();\n }\n this.inputs.checkInputs();\n _super.prototype._checkInputs.call(this);\n };\n FreeCamera.prototype._decideIfNeedsToMove = function () {\n return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;\n };\n FreeCamera.prototype._updatePosition = function () {\n if (this.checkCollisions && this.getScene().collisionsEnabled) {\n this._collideWithWorld(this.cameraDirection);\n }\n else {\n _super.prototype._updatePosition.call(this);\n }\n };\n FreeCamera.prototype.dispose = function () {\n this.inputs.clear();\n _super.prototype.dispose.call(this);\n };\n FreeCamera.prototype.getClassName = function () {\n return \"FreeCamera\";\n };\n __decorate([\n BABYLON.serializeAsVector3()\n ], FreeCamera.prototype, \"ellipsoid\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], FreeCamera.prototype, \"ellipsoidOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCamera.prototype, \"checkCollisions\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCamera.prototype, \"applyGravity\", void 0);\n return FreeCamera;\n }(BABYLON.TargetCamera));\n BABYLON.FreeCamera = FreeCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {\n function ArcRotateCameraKeyboardMoveInput() {\n this._keys = new Array();\n this.keysUp = [38];\n this.keysDown = [40];\n this.keysLeft = [37];\n this.keysRight = [39];\n this.keysReset = [220];\n this.panningSensibility = 50.0;\n this.zoomingSensibility = 25.0;\n this.useAltToZoom = true;\n }\n ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n if (this._onCanvasBlurObserver) {\n return;\n }\n this._scene = this.camera.getScene();\n this._engine = this._scene.getEngine();\n this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {\n _this._keys = [];\n });\n this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {\n var evt = info.event;\n if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {\n _this._ctrlPressed = evt.ctrlKey;\n _this._altPressed = evt.altKey;\n if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||\n _this.keysDown.indexOf(evt.keyCode) !== -1 ||\n _this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n _this.keysRight.indexOf(evt.keyCode) !== -1 ||\n _this.keysReset.indexOf(evt.keyCode) !== -1) {\n var index = _this._keys.indexOf(evt.keyCode);\n if (index === -1) {\n _this._keys.push(evt.keyCode);\n }\n if (evt.preventDefault) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n else {\n if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||\n _this.keysDown.indexOf(evt.keyCode) !== -1 ||\n _this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n _this.keysRight.indexOf(evt.keyCode) !== -1 ||\n _this.keysReset.indexOf(evt.keyCode) !== -1) {\n var index = _this._keys.indexOf(evt.keyCode);\n if (index >= 0) {\n _this._keys.splice(index, 1);\n }\n if (evt.preventDefault) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n });\n };\n ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {\n if (this._scene) {\n if (this._onKeyboardObserver) {\n this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);\n }\n if (this._onCanvasBlurObserver) {\n this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n this._onKeyboardObserver = null;\n this._onCanvasBlurObserver = null;\n }\n this._keys = [];\n };\n ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {\n if (this._onKeyboardObserver) {\n var camera = this.camera;\n for (var index = 0; index < this._keys.length; index++) {\n var keyCode = this._keys[index];\n if (this.keysLeft.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningX -= 1 / this.panningSensibility;\n }\n else {\n camera.inertialAlphaOffset -= 0.01;\n }\n }\n else if (this.keysUp.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningY += 1 / this.panningSensibility;\n }\n else if (this._altPressed && this.useAltToZoom) {\n camera.inertialRadiusOffset += 1 / this.zoomingSensibility;\n }\n else {\n camera.inertialBetaOffset -= 0.01;\n }\n }\n else if (this.keysRight.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningX += 1 / this.panningSensibility;\n }\n else {\n camera.inertialAlphaOffset += 0.01;\n }\n }\n else if (this.keysDown.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningY -= 1 / this.panningSensibility;\n }\n else if (this._altPressed && this.useAltToZoom) {\n camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;\n }\n else {\n camera.inertialBetaOffset += 0.01;\n }\n }\n else if (this.keysReset.indexOf(keyCode) !== -1) {\n camera.restoreState();\n }\n }\n }\n };\n ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {\n return \"ArcRotateCameraKeyboardMoveInput\";\n };\n ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {\n return \"keyboard\";\n };\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"keysUp\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"keysDown\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"keysLeft\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"keysRight\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"keysReset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"panningSensibility\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"zoomingSensibility\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraKeyboardMoveInput.prototype, \"useAltToZoom\", void 0);\n return ArcRotateCameraKeyboardMoveInput;\n }());\n BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;\n BABYLON.CameraInputTypes[\"ArcRotateCameraKeyboardMoveInput\"] = ArcRotateCameraKeyboardMoveInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ArcRotateCameraMouseWheelInput = /** @class */ (function () {\n function ArcRotateCameraMouseWheelInput() {\n this.wheelPrecision = 3.0;\n /**\n * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.\n * It defines the percentage of current camera.radius to use as delta when wheel is used.\n */\n this.wheelDeltaPercentage = 0;\n }\n ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n this._wheel = function (p, s) {\n //sanity check - this should be a PointerWheel event.\n if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)\n return;\n var event = p.event;\n var delta = 0;\n if (event.wheelDelta) {\n if (_this.wheelDeltaPercentage) {\n var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;\n if (event.wheelDelta > 0) {\n delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);\n }\n else {\n delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);\n }\n }\n else {\n delta = event.wheelDelta / (_this.wheelPrecision * 40);\n }\n }\n else if (event.detail) {\n delta = -event.detail / _this.wheelPrecision;\n }\n if (delta)\n _this.camera.inertialRadiusOffset += delta;\n if (event.preventDefault) {\n if (!noPreventDefault) {\n event.preventDefault();\n }\n }\n };\n this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);\n };\n ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {\n if (this._observer && element) {\n this.camera.getScene().onPointerObservable.remove(this._observer);\n this._observer = null;\n this._wheel = null;\n }\n };\n ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {\n return \"ArcRotateCameraMouseWheelInput\";\n };\n ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {\n return \"mousewheel\";\n };\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraMouseWheelInput.prototype, \"wheelPrecision\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraMouseWheelInput.prototype, \"wheelDeltaPercentage\", void 0);\n return ArcRotateCameraMouseWheelInput;\n }());\n BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;\n BABYLON.CameraInputTypes[\"ArcRotateCameraMouseWheelInput\"] = ArcRotateCameraMouseWheelInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ArcRotateCameraPointersInput = /** @class */ (function () {\n function ArcRotateCameraPointersInput() {\n this.buttons = [0, 1, 2];\n this.angularSensibilityX = 1000.0;\n this.angularSensibilityY = 1000.0;\n this.pinchPrecision = 12.0;\n /**\n * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.\n * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.\n */\n this.pinchDeltaPercentage = 0;\n this.panningSensibility = 1000.0;\n this.multiTouchPanning = true;\n this.multiTouchPanAndZoom = true;\n this._isPanClick = false;\n this.pinchInwards = true;\n }\n ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n var engine = this.camera.getEngine();\n var cacheSoloPointer; // cache pointer object for better perf on camera rotation\n var pointA = null;\n var pointB = null;\n var previousPinchSquaredDistance = 0;\n var initialDistance = 0;\n var twoFingerActivityCount = 0;\n var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };\n this._pointerInput = function (p, s) {\n var evt = p.event;\n var isTouch = p.event.pointerType === \"touch\";\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {\n return;\n }\n var srcElement = (evt.srcElement || evt.target);\n if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {\n try {\n srcElement.setPointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error. Execution will continue.\n }\n // Manage panning with pan button click\n _this._isPanClick = evt.button === _this.camera._panningMouseButton;\n // manage pointers\n cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };\n if (pointA === null) {\n pointA = cacheSoloPointer;\n }\n else if (pointB === null) {\n pointB = cacheSoloPointer;\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n element.focus();\n }\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {\n _this.camera.restoreState();\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {\n try {\n srcElement.releasePointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error.\n }\n cacheSoloPointer = null;\n previousPinchSquaredDistance = 0;\n previousMultiTouchPanPosition.isPaning = false;\n previousMultiTouchPanPosition.isPinching = false;\n twoFingerActivityCount = 0;\n initialDistance = 0;\n if (!isTouch) {\n pointB = null; // Mouse and pen are mono pointer\n }\n //would be better to use pointers.remove(evt.pointerId) for multitouch gestures, \n //but emptying completly pointers collection is required to fix a bug on iPhone : \n //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers \n //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected\n if (engine._badOS) {\n pointA = pointB = null;\n }\n else {\n //only remove the impacted pointer in case of multitouch allowing on most \n //platforms switching from rotate to zoom and pan seamlessly.\n if (pointB && pointA && pointA.pointerId == evt.pointerId) {\n pointA = pointB;\n pointB = null;\n cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };\n }\n else if (pointA && pointB && pointB.pointerId == evt.pointerId) {\n pointB = null;\n cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };\n }\n else {\n pointA = pointB = null;\n }\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n // One button down\n if (pointA && pointB === null && cacheSoloPointer) {\n if (_this.panningSensibility !== 0 &&\n ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {\n _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;\n _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;\n }\n else {\n var offsetX = evt.clientX - cacheSoloPointer.x;\n var offsetY = evt.clientY - cacheSoloPointer.y;\n _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;\n _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;\n }\n cacheSoloPointer.x = evt.clientX;\n cacheSoloPointer.y = evt.clientY;\n }\n // Two buttons down: pinch/pan\n else if (pointA && pointB) {\n //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers\n var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;\n ed.x = evt.clientX;\n ed.y = evt.clientY;\n var direction = _this.pinchInwards ? 1 : -1;\n var distX = pointA.x - pointB.x;\n var distY = pointA.y - pointB.y;\n var pinchSquaredDistance = (distX * distX) + (distY * distY);\n var pinchDistance = Math.sqrt(pinchSquaredDistance);\n if (previousPinchSquaredDistance === 0) {\n initialDistance = pinchDistance;\n previousPinchSquaredDistance = pinchSquaredDistance;\n previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;\n previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;\n return;\n }\n if (_this.multiTouchPanAndZoom) {\n if (_this.pinchDeltaPercentage) {\n _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;\n }\n else {\n _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /\n (_this.pinchPrecision *\n ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *\n direction);\n }\n if (_this.panningSensibility !== 0) {\n var pointersCenterX = (pointA.x + pointB.x) / 2;\n var pointersCenterY = (pointA.y + pointB.y) / 2;\n var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;\n var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;\n previousMultiTouchPanPosition.x = pointersCenterX;\n previousMultiTouchPanPosition.y = pointersCenterY;\n _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);\n _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);\n }\n }\n else {\n twoFingerActivityCount++;\n if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {\n if (_this.pinchDeltaPercentage) {\n _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;\n }\n else {\n _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /\n (_this.pinchPrecision *\n ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *\n direction);\n }\n previousMultiTouchPanPosition.isPaning = false;\n previousMultiTouchPanPosition.isPinching = true;\n }\n else {\n if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {\n if (!previousMultiTouchPanPosition.isPaning) {\n previousMultiTouchPanPosition.isPaning = true;\n previousMultiTouchPanPosition.isPinching = false;\n previousMultiTouchPanPosition.x = ed.x;\n previousMultiTouchPanPosition.y = ed.y;\n return;\n }\n _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);\n _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);\n }\n }\n if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {\n previousMultiTouchPanPosition.x = ed.x;\n previousMultiTouchPanPosition.y = ed.y;\n }\n }\n previousPinchSquaredDistance = pinchSquaredDistance;\n }\n }\n };\n this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);\n this._onContextMenu = function (evt) {\n evt.preventDefault();\n };\n if (!this.camera._useCtrlForPanning) {\n element.addEventListener(\"contextmenu\", this._onContextMenu, false);\n }\n this._onLostFocus = function () {\n //this._keys = [];\n pointA = pointB = null;\n previousPinchSquaredDistance = 0;\n previousMultiTouchPanPosition.isPaning = false;\n previousMultiTouchPanPosition.isPinching = false;\n twoFingerActivityCount = 0;\n cacheSoloPointer = null;\n initialDistance = 0;\n };\n this._onMouseMove = function (evt) {\n if (!engine.isPointerLock) {\n return;\n }\n var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;\n var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;\n _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;\n _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n };\n this._onGestureStart = function (e) {\n if (window.MSGesture === undefined) {\n return;\n }\n if (!_this._MSGestureHandler) {\n _this._MSGestureHandler = new MSGesture();\n _this._MSGestureHandler.target = element;\n }\n _this._MSGestureHandler.addPointer(e.pointerId);\n };\n this._onGesture = function (e) {\n _this.camera.radius *= e.scale;\n if (e.preventDefault) {\n if (!noPreventDefault) {\n e.stopPropagation();\n e.preventDefault();\n }\n }\n };\n element.addEventListener(\"mousemove\", this._onMouseMove, false);\n element.addEventListener(\"MSPointerDown\", this._onGestureStart, false);\n element.addEventListener(\"MSGestureChange\", this._onGesture, false);\n BABYLON.Tools.RegisterTopRootEvents([\n { name: \"blur\", handler: this._onLostFocus }\n ]);\n };\n ArcRotateCameraPointersInput.prototype.detachControl = function (element) {\n if (this._onLostFocus) {\n BABYLON.Tools.UnregisterTopRootEvents([\n { name: \"blur\", handler: this._onLostFocus }\n ]);\n }\n if (element && this._observer) {\n this.camera.getScene().onPointerObservable.remove(this._observer);\n this._observer = null;\n if (this._onContextMenu) {\n element.removeEventListener(\"contextmenu\", this._onContextMenu);\n }\n if (this._onMouseMove) {\n element.removeEventListener(\"mousemove\", this._onMouseMove);\n }\n if (this._onGestureStart) {\n element.removeEventListener(\"MSPointerDown\", this._onGestureStart);\n }\n if (this._onGesture) {\n element.removeEventListener(\"MSGestureChange\", this._onGesture);\n }\n this._isPanClick = false;\n this.pinchInwards = true;\n this._onMouseMove = null;\n this._onGestureStart = null;\n this._onGesture = null;\n this._MSGestureHandler = null;\n this._onLostFocus = null;\n this._onContextMenu = null;\n }\n };\n ArcRotateCameraPointersInput.prototype.getClassName = function () {\n return \"ArcRotateCameraPointersInput\";\n };\n ArcRotateCameraPointersInput.prototype.getSimpleName = function () {\n return \"pointers\";\n };\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"buttons\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"angularSensibilityX\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"angularSensibilityY\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"pinchPrecision\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"pinchDeltaPercentage\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"panningSensibility\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"multiTouchPanning\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraPointersInput.prototype, \"multiTouchPanAndZoom\", void 0);\n return ArcRotateCameraPointersInput;\n }());\n BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;\n BABYLON.CameraInputTypes[\"ArcRotateCameraPointersInput\"] = ArcRotateCameraPointersInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ArcRotateCameraInputsManager = /** @class */ (function (_super) {\n __extends(ArcRotateCameraInputsManager, _super);\n function ArcRotateCameraInputsManager(camera) {\n return _super.call(this, camera) || this;\n }\n ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {\n this.add(new BABYLON.ArcRotateCameraMouseWheelInput());\n return this;\n };\n ArcRotateCameraInputsManager.prototype.addPointers = function () {\n this.add(new BABYLON.ArcRotateCameraPointersInput());\n return this;\n };\n ArcRotateCameraInputsManager.prototype.addKeyboard = function () {\n this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());\n return this;\n };\n ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {\n this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());\n return this;\n };\n return ArcRotateCameraInputsManager;\n }(BABYLON.CameraInputsManager));\n BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"ArcRotateCamera\", function (name, scene) {\n return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };\n });\n var ArcRotateCamera = /** @class */ (function (_super) {\n __extends(ArcRotateCamera, _super);\n function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {\n if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }\n var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;\n _this.inertialAlphaOffset = 0;\n _this.inertialBetaOffset = 0;\n _this.inertialRadiusOffset = 0;\n _this.lowerAlphaLimit = null;\n _this.upperAlphaLimit = null;\n _this.lowerBetaLimit = 0.01;\n _this.upperBetaLimit = Math.PI;\n _this.lowerRadiusLimit = null;\n _this.upperRadiusLimit = null;\n _this.inertialPanningX = 0;\n _this.inertialPanningY = 0;\n _this.pinchToPanMaxDistance = 20;\n _this.panningDistanceLimit = null;\n _this.panningOriginTarget = BABYLON.Vector3.Zero();\n _this.panningInertia = 0.9;\n //-- end properties for backward compatibility for inputs\n _this.zoomOnFactor = 1;\n _this.targetScreenOffset = BABYLON.Vector2.Zero();\n _this.allowUpsideDown = true;\n _this._viewMatrix = new BABYLON.Matrix();\n // Panning\n _this.panningAxis = new BABYLON.Vector3(1, 1, 0);\n _this.onMeshTargetChangedObservable = new BABYLON.Observable();\n _this.checkCollisions = false;\n _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);\n _this._previousPosition = BABYLON.Vector3.Zero();\n _this._collisionVelocity = BABYLON.Vector3.Zero();\n _this._newPosition = BABYLON.Vector3.Zero();\n _this._computationVector = BABYLON.Vector3.Zero();\n _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {\n if (collidedMesh === void 0) { collidedMesh = null; }\n if (_this.getScene().workerCollisions && _this.checkCollisions) {\n newPosition.multiplyInPlace(_this._collider._radius);\n }\n if (!collidedMesh) {\n _this._previousPosition.copyFrom(_this.position);\n }\n else {\n _this.setPosition(newPosition);\n if (_this.onCollide) {\n _this.onCollide(collidedMesh);\n }\n }\n // Recompute because of constraints\n var cosa = Math.cos(_this.alpha);\n var sina = Math.sin(_this.alpha);\n var cosb = Math.cos(_this.beta);\n var sinb = Math.sin(_this.beta);\n if (sinb === 0) {\n sinb = 0.0001;\n }\n var target = _this._getTargetPosition();\n _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);\n target.addToRef(_this._computationVector, _this._newPosition);\n _this.position.copyFrom(_this._newPosition);\n var up = _this.upVector;\n if (_this.allowUpsideDown && _this.beta < 0) {\n up = up.clone();\n up = up.negate();\n }\n _this._computeViewMatrix(_this.position, target, up);\n _this._viewMatrix.m[12] += _this.targetScreenOffset.x;\n _this._viewMatrix.m[13] += _this.targetScreenOffset.y;\n _this._collisionTriggered = false;\n };\n _this._target = BABYLON.Vector3.Zero();\n if (target) {\n _this.setTarget(target);\n }\n _this.alpha = alpha;\n _this.beta = beta;\n _this.radius = radius;\n _this.getViewMatrix();\n _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);\n _this.inputs.addKeyboard().addMouseWheel().addPointers();\n return _this;\n }\n Object.defineProperty(ArcRotateCamera.prototype, \"target\", {\n get: function () {\n return this._target;\n },\n set: function (value) {\n this.setTarget(value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"angularSensibilityX\", {\n //-- begin properties for backward compatibility for inputs\n get: function () {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers)\n return pointers.angularSensibilityX;\n return 0;\n },\n set: function (value) {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.angularSensibilityX = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"angularSensibilityY\", {\n get: function () {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers)\n return pointers.angularSensibilityY;\n return 0;\n },\n set: function (value) {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.angularSensibilityY = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"pinchPrecision\", {\n get: function () {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers)\n return pointers.pinchPrecision;\n return 0;\n },\n set: function (value) {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.pinchPrecision = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"pinchDeltaPercentage\", {\n get: function () {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers)\n return pointers.pinchDeltaPercentage;\n return 0;\n },\n set: function (value) {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.pinchDeltaPercentage = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"panningSensibility\", {\n get: function () {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers)\n return pointers.panningSensibility;\n return 0;\n },\n set: function (value) {\n var pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.panningSensibility = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"keysUp\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysUp;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysUp = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"keysDown\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysDown;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysDown = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"keysLeft\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysLeft;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysLeft = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"keysRight\", {\n get: function () {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n return keyboard.keysRight;\n return [];\n },\n set: function (value) {\n var keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard)\n keyboard.keysRight = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"wheelPrecision\", {\n get: function () {\n var mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel)\n return mousewheel.wheelPrecision;\n return 0;\n },\n set: function (value) {\n var mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel)\n mousewheel.wheelPrecision = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"wheelDeltaPercentage\", {\n get: function () {\n var mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel)\n return mousewheel.wheelDeltaPercentage;\n return 0;\n },\n set: function (value) {\n var mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel)\n mousewheel.wheelDeltaPercentage = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"bouncingBehavior\", {\n get: function () {\n return this._bouncingBehavior;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"useBouncingBehavior\", {\n get: function () {\n return this._bouncingBehavior != null;\n },\n set: function (value) {\n if (value === this.useBouncingBehavior) {\n return;\n }\n if (value) {\n this._bouncingBehavior = new BABYLON.BouncingBehavior();\n this.addBehavior(this._bouncingBehavior);\n }\n else if (this._bouncingBehavior) {\n this.removeBehavior(this._bouncingBehavior);\n this._bouncingBehavior = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"framingBehavior\", {\n get: function () {\n return this._framingBehavior;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"useFramingBehavior\", {\n get: function () {\n return this._framingBehavior != null;\n },\n set: function (value) {\n if (value === this.useFramingBehavior) {\n return;\n }\n if (value) {\n this._framingBehavior = new BABYLON.FramingBehavior();\n this.addBehavior(this._framingBehavior);\n }\n else if (this._framingBehavior) {\n this.removeBehavior(this._framingBehavior);\n this._framingBehavior = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"autoRotationBehavior\", {\n get: function () {\n return this._autoRotationBehavior;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ArcRotateCamera.prototype, \"useAutoRotationBehavior\", {\n get: function () {\n return this._autoRotationBehavior != null;\n },\n set: function (value) {\n if (value === this.useAutoRotationBehavior) {\n return;\n }\n if (value) {\n this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();\n this.addBehavior(this._autoRotationBehavior);\n }\n else if (this._autoRotationBehavior) {\n this.removeBehavior(this._autoRotationBehavior);\n this._autoRotationBehavior = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n // Cache\n ArcRotateCamera.prototype._initCache = function () {\n _super.prototype._initCache.call(this);\n this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.alpha = undefined;\n this._cache.beta = undefined;\n this._cache.radius = undefined;\n this._cache.targetScreenOffset = BABYLON.Vector2.Zero();\n };\n ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {\n if (!ignoreParentClass) {\n _super.prototype._updateCache.call(this);\n }\n this._cache._target.copyFrom(this._getTargetPosition());\n this._cache.alpha = this.alpha;\n this._cache.beta = this.beta;\n this._cache.radius = this.radius;\n this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);\n };\n ArcRotateCamera.prototype._getTargetPosition = function () {\n if (this._targetHost && this._targetHost.getAbsolutePosition) {\n var pos = this._targetHost.getAbsolutePosition();\n if (this._targetBoundingCenter) {\n pos.addToRef(this._targetBoundingCenter, this._target);\n }\n else {\n this._target.copyFrom(pos);\n }\n }\n var lockedTargetPosition = this._getLockedTargetPosition();\n if (lockedTargetPosition) {\n return lockedTargetPosition;\n }\n return this._target;\n };\n ArcRotateCamera.prototype.storeState = function () {\n this._storedAlpha = this.alpha;\n this._storedBeta = this.beta;\n this._storedRadius = this.radius;\n this._storedTarget = this._getTargetPosition().clone();\n return _super.prototype.storeState.call(this);\n };\n /**\n * Restored camera state. You must call storeState() first\n */\n ArcRotateCamera.prototype._restoreStateValues = function () {\n if (!_super.prototype._restoreStateValues.call(this)) {\n return false;\n }\n this.alpha = this._storedAlpha;\n this.beta = this._storedBeta;\n this.radius = this._storedRadius;\n this.setTarget(this._storedTarget.clone());\n this.inertialAlphaOffset = 0;\n this.inertialBetaOffset = 0;\n this.inertialRadiusOffset = 0;\n this.inertialPanningX = 0;\n this.inertialPanningY = 0;\n return true;\n };\n // Synchronized\n ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {\n if (!_super.prototype._isSynchronizedViewMatrix.call(this))\n return false;\n return this._cache._target.equals(this._getTargetPosition())\n && this._cache.alpha === this.alpha\n && this._cache.beta === this.beta\n && this._cache.radius === this.radius\n && this._cache.targetScreenOffset.equals(this.targetScreenOffset);\n };\n // Methods\n ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {\n var _this = this;\n if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }\n if (panningMouseButton === void 0) { panningMouseButton = 2; }\n this._useCtrlForPanning = useCtrlForPanning;\n this._panningMouseButton = panningMouseButton;\n this.inputs.attachElement(element, noPreventDefault);\n this._reset = function () {\n _this.inertialAlphaOffset = 0;\n _this.inertialBetaOffset = 0;\n _this.inertialRadiusOffset = 0;\n _this.inertialPanningX = 0;\n _this.inertialPanningY = 0;\n };\n };\n ArcRotateCamera.prototype.detachControl = function (element) {\n this.inputs.detachElement(element);\n if (this._reset) {\n this._reset();\n }\n };\n ArcRotateCamera.prototype._checkInputs = function () {\n //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.\n if (this._collisionTriggered) {\n return;\n }\n this.inputs.checkInputs();\n // Inertia\n if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {\n var inertialAlphaOffset = this.inertialAlphaOffset;\n if (this.beta <= 0)\n inertialAlphaOffset *= -1;\n if (this.getScene().useRightHandedSystem)\n inertialAlphaOffset *= -1;\n if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)\n inertialAlphaOffset *= -1;\n this.alpha += inertialAlphaOffset;\n this.beta += this.inertialBetaOffset;\n this.radius -= this.inertialRadiusOffset;\n this.inertialAlphaOffset *= this.inertia;\n this.inertialBetaOffset *= this.inertia;\n this.inertialRadiusOffset *= this.inertia;\n if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)\n this.inertialAlphaOffset = 0;\n if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)\n this.inertialBetaOffset = 0;\n if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)\n this.inertialRadiusOffset = 0;\n }\n // Panning inertia\n if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {\n if (!this._localDirection) {\n this._localDirection = BABYLON.Vector3.Zero();\n this._transformedDirection = BABYLON.Vector3.Zero();\n }\n this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);\n this._localDirection.multiplyInPlace(this.panningAxis);\n this._viewMatrix.invertToRef(this._cameraTransformMatrix);\n BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);\n //Eliminate y if map panning is enabled (panningAxis == 1,0,1)\n if (!this.panningAxis.y) {\n this._transformedDirection.y = 0;\n }\n if (!this._targetHost) {\n if (this.panningDistanceLimit) {\n this._transformedDirection.addInPlace(this._target);\n var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);\n if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {\n this._target.copyFrom(this._transformedDirection);\n }\n }\n else {\n this._target.addInPlace(this._transformedDirection);\n }\n }\n this.inertialPanningX *= this.panningInertia;\n this.inertialPanningY *= this.panningInertia;\n if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)\n this.inertialPanningX = 0;\n if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)\n this.inertialPanningY = 0;\n }\n // Limits\n this._checkLimits();\n _super.prototype._checkInputs.call(this);\n };\n ArcRotateCamera.prototype._checkLimits = function () {\n if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {\n if (this.allowUpsideDown && this.beta > Math.PI) {\n this.beta = this.beta - (2 * Math.PI);\n }\n }\n else {\n if (this.beta < this.lowerBetaLimit) {\n this.beta = this.lowerBetaLimit;\n }\n }\n if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {\n if (this.allowUpsideDown && this.beta < -Math.PI) {\n this.beta = this.beta + (2 * Math.PI);\n }\n }\n else {\n if (this.beta > this.upperBetaLimit) {\n this.beta = this.upperBetaLimit;\n }\n }\n if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {\n this.alpha = this.lowerAlphaLimit;\n }\n if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {\n this.alpha = this.upperAlphaLimit;\n }\n if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {\n this.radius = this.lowerRadiusLimit;\n }\n if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {\n this.radius = this.upperRadiusLimit;\n }\n };\n ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {\n this.position.subtractToRef(this._getTargetPosition(), this._computationVector);\n this.radius = this._computationVector.length();\n if (this.radius === 0) {\n this.radius = 0.0001; // Just to avoid division by zero\n }\n // Alpha\n this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));\n if (this._computationVector.z < 0) {\n this.alpha = 2 * Math.PI - this.alpha;\n }\n // Beta\n this.beta = Math.acos(this._computationVector.y / this.radius);\n this._checkLimits();\n };\n ArcRotateCamera.prototype.setPosition = function (position) {\n if (this.position.equals(position)) {\n return;\n }\n this.position.copyFrom(position);\n this.rebuildAnglesAndRadius();\n };\n ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {\n if (toBoundingCenter === void 0) { toBoundingCenter = false; }\n if (allowSamePosition === void 0) { allowSamePosition = false; }\n if (target.getBoundingInfo) {\n if (toBoundingCenter) {\n this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();\n }\n else {\n this._targetBoundingCenter = null;\n }\n this._targetHost = target;\n this._target = this._getTargetPosition();\n this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);\n }\n else {\n var newTarget = target;\n var currentTarget = this._getTargetPosition();\n if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {\n return;\n }\n this._targetHost = null;\n this._target = newTarget;\n this._targetBoundingCenter = null;\n this.onMeshTargetChangedObservable.notifyObservers(null);\n }\n this.rebuildAnglesAndRadius();\n };\n ArcRotateCamera.prototype._getViewMatrix = function () {\n // Compute\n var cosa = Math.cos(this.alpha);\n var sina = Math.sin(this.alpha);\n var cosb = Math.cos(this.beta);\n var sinb = Math.sin(this.beta);\n if (sinb === 0) {\n sinb = 0.0001;\n }\n var target = this._getTargetPosition();\n this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);\n target.addToRef(this._computationVector, this._newPosition);\n if (this.getScene().collisionsEnabled && this.checkCollisions) {\n if (!this._collider) {\n this._collider = new BABYLON.Collider();\n }\n this._collider._radius = this.collisionRadius;\n this._newPosition.subtractToRef(this.position, this._collisionVelocity);\n this._collisionTriggered = true;\n this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);\n }\n else {\n this.position.copyFrom(this._newPosition);\n var up = this.upVector;\n if (this.allowUpsideDown && sinb < 0) {\n up = up.clone();\n up = up.negate();\n }\n this._computeViewMatrix(this.position, target, up);\n this._viewMatrix.m[12] += this.targetScreenOffset.x;\n this._viewMatrix.m[13] += this.targetScreenOffset.y;\n }\n this._currentTarget = target;\n return this._viewMatrix;\n };\n ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {\n if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }\n meshes = meshes || this.getScene().meshes;\n var minMaxVector = BABYLON.Mesh.MinMax(meshes);\n var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);\n this.radius = distance * this.zoomOnFactor;\n this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);\n };\n ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {\n if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }\n var meshesOrMinMaxVector;\n var distance;\n if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes\n var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;\n meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);\n distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);\n }\n else { //minMaxVector and distance\n var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;\n meshesOrMinMaxVector = minMaxVectorAndDistance;\n distance = minMaxVectorAndDistance.distance;\n }\n this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);\n if (!doNotUpdateMaxZ) {\n this.maxZ = distance * 2;\n }\n };\n /**\n * @override\n * Override Camera.createRigCamera\n */\n ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {\n var alphaShift = 0;\n switch (this.cameraRigMode) {\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n case BABYLON.Camera.RIG_MODE_VR:\n alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);\n break;\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);\n break;\n }\n var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());\n rigCam._cameraRigParams = {};\n return rigCam;\n };\n /**\n * @override\n * Override Camera._updateRigCameras\n */\n ArcRotateCamera.prototype._updateRigCameras = function () {\n var camLeft = this._rigCameras[0];\n var camRight = this._rigCameras[1];\n camLeft.beta = camRight.beta = this.beta;\n camLeft.radius = camRight.radius = this.radius;\n switch (this.cameraRigMode) {\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n case BABYLON.Camera.RIG_MODE_VR:\n camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;\n camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;\n break;\n case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;\n camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;\n break;\n }\n _super.prototype._updateRigCameras.call(this);\n };\n ArcRotateCamera.prototype.dispose = function () {\n this.inputs.clear();\n _super.prototype.dispose.call(this);\n };\n ArcRotateCamera.prototype.getClassName = function () {\n return \"ArcRotateCamera\";\n };\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"alpha\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"beta\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"radius\", void 0);\n __decorate([\n BABYLON.serializeAsVector3(\"target\")\n ], ArcRotateCamera.prototype, \"_target\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"inertialAlphaOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"inertialBetaOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"inertialRadiusOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"lowerAlphaLimit\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"upperAlphaLimit\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"lowerBetaLimit\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"upperBetaLimit\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"lowerRadiusLimit\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"upperRadiusLimit\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"inertialPanningX\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"inertialPanningY\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"pinchToPanMaxDistance\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"panningDistanceLimit\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], ArcRotateCamera.prototype, \"panningOriginTarget\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"panningInertia\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"zoomOnFactor\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCamera.prototype, \"allowUpsideDown\", void 0);\n return ArcRotateCamera;\n }(BABYLON.TargetCamera));\n BABYLON.ArcRotateCamera = ArcRotateCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCamera.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"Light_Type_3\", function (name, scene) {\n return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };\n });\n /**\n * The HemisphericLight simulates the ambient environment light,\n * so the passed direction is the light reflection direction, not the incoming direction.\n */\n var HemisphericLight = /** @class */ (function (_super) {\n __extends(HemisphericLight, _super);\n /**\n * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).\n * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.\n * The HemisphericLight can't cast shadows.\n * Documentation : http://doc.babylonjs.com/tutorials/lights\n * @param name The friendly name of the light\n * @param direction The direction of the light reflection\n * @param scene The scene the light belongs to\n */\n function HemisphericLight(name, direction, scene) {\n var _this = _super.call(this, name, scene) || this;\n /**\n * The groundColor is the light in the opposite direction to the one specified during creation.\n * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.\n */\n _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);\n _this.direction = direction || BABYLON.Vector3.Up();\n return _this;\n }\n HemisphericLight.prototype._buildUniformLayout = function () {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 3);\n this._uniformBuffer.addUniform(\"vLightGround\", 3);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n };\n /**\n * Returns the string \"HemisphericLight\".\n * @return The class name\n */\n HemisphericLight.prototype.getClassName = function () {\n return \"HemisphericLight\";\n };\n /**\n * Sets the HemisphericLight direction towards the passed target (Vector3).\n * Returns the updated direction.\n * @param target The target the direction should point to\n * @return The computed direction\n */\n HemisphericLight.prototype.setDirectionToTarget = function (target) {\n this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));\n return this.direction;\n };\n /**\n * Returns the shadow generator associated to the light.\n * @returns Always null for hemispheric lights because it does not support shadows.\n */\n HemisphericLight.prototype.getShadowGenerator = function () {\n return null;\n };\n /**\n * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The hemispheric light\n */\n HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {\n var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);\n this._uniformBuffer.updateFloat4(\"vLightData\", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);\n this._uniformBuffer.updateColor3(\"vLightGround\", this.groundColor.scale(this.intensity), lightIndex);\n return this;\n };\n /**\n * @hidden internal use only.\n */\n HemisphericLight.prototype._getWorldMatrix = function () {\n if (!this._worldMatrix) {\n this._worldMatrix = BABYLON.Matrix.Identity();\n }\n return this._worldMatrix;\n };\n /**\n * Returns the integer 3.\n * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n HemisphericLight.prototype.getTypeID = function () {\n return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;\n };\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {\n defines[\"HEMILIGHT\" + lightIndex] = true;\n };\n __decorate([\n BABYLON.serializeAsColor3()\n ], HemisphericLight.prototype, \"groundColor\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], HemisphericLight.prototype, \"direction\", void 0);\n return HemisphericLight;\n }(BABYLON.Light));\n BABYLON.HemisphericLight = HemisphericLight;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.hemisphericLight.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Base implementation IShadowLight\n * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.\n */\n var ShadowLight = /** @class */ (function (_super) {\n __extends(ShadowLight, _super);\n function ShadowLight() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this._needProjectionMatrixCompute = true;\n return _this;\n }\n ShadowLight.prototype._setPosition = function (value) {\n this._position = value;\n };\n Object.defineProperty(ShadowLight.prototype, \"position\", {\n /**\n * Sets the position the shadow will be casted from. Also use as the light position for both\n * point and spot lights.\n */\n get: function () {\n return this._position;\n },\n /**\n * Sets the position the shadow will be casted from. Also use as the light position for both\n * point and spot lights.\n */\n set: function (value) {\n this._setPosition(value);\n },\n enumerable: true,\n configurable: true\n });\n ShadowLight.prototype._setDirection = function (value) {\n this._direction = value;\n };\n Object.defineProperty(ShadowLight.prototype, \"direction\", {\n /**\n * In 2d mode (needCube being false), gets the direction used to cast the shadow.\n * Also use as the light direction on spot and directional lights.\n */\n get: function () {\n return this._direction;\n },\n /**\n * In 2d mode (needCube being false), sets the direction used to cast the shadow.\n * Also use as the light direction on spot and directional lights.\n */\n set: function (value) {\n this._setDirection(value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowLight.prototype, \"shadowMinZ\", {\n /**\n * Gets the shadow projection clipping minimum z value.\n */\n get: function () {\n return this._shadowMinZ;\n },\n /**\n * Sets the shadow projection clipping minimum z value.\n */\n set: function (value) {\n this._shadowMinZ = value;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowLight.prototype, \"shadowMaxZ\", {\n /**\n * Sets the shadow projection clipping maximum z value.\n */\n get: function () {\n return this._shadowMaxZ;\n },\n /**\n * Gets the shadow projection clipping maximum z value.\n */\n set: function (value) {\n this._shadowMaxZ = value;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light\n * @returns true if the information has been computed, false if it does not need to (no parenting)\n */\n ShadowLight.prototype.computeTransformedInformation = function () {\n if (this.parent && this.parent.getWorldMatrix) {\n if (!this.transformedPosition) {\n this.transformedPosition = BABYLON.Vector3.Zero();\n }\n BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);\n // In case the direction is present.\n if (this.direction) {\n if (!this.transformedDirection) {\n this.transformedDirection = BABYLON.Vector3.Zero();\n }\n BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);\n }\n return true;\n }\n return false;\n };\n /**\n * Return the depth scale used for the shadow map.\n * @returns the depth scale.\n */\n ShadowLight.prototype.getDepthScale = function () {\n return 50.0;\n };\n /**\n * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.\n * @param faceIndex The index of the face we are computed the direction to generate shadow\n * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true\n */\n ShadowLight.prototype.getShadowDirection = function (faceIndex) {\n return this.transformedDirection ? this.transformedDirection : this.direction;\n };\n /**\n * Returns the ShadowLight absolute position in the World.\n * @returns the position vector in world space\n */\n ShadowLight.prototype.getAbsolutePosition = function () {\n return this.transformedPosition ? this.transformedPosition : this.position;\n };\n /**\n * Sets the ShadowLight direction toward the passed target.\n * @param target The point tot target in local space\n * @returns the updated ShadowLight direction\n */\n ShadowLight.prototype.setDirectionToTarget = function (target) {\n this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));\n return this.direction;\n };\n /**\n * Returns the light rotation in euler definition.\n * @returns the x y z rotation in local space.\n */\n ShadowLight.prototype.getRotation = function () {\n this.direction.normalize();\n var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);\n var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);\n return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);\n };\n /**\n * Returns whether or not the shadow generation require a cube texture or a 2d texture.\n * @returns true if a cube texture needs to be use\n */\n ShadowLight.prototype.needCube = function () {\n return false;\n };\n /**\n * Detects if the projection matrix requires to be recomputed this frame.\n * @returns true if it requires to be recomputed otherwise, false.\n */\n ShadowLight.prototype.needProjectionMatrixCompute = function () {\n return this._needProjectionMatrixCompute;\n };\n /**\n * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.\n */\n ShadowLight.prototype.forceProjectionMatrixCompute = function () {\n this._needProjectionMatrixCompute = true;\n };\n /**\n * Get the world matrix of the sahdow lights.\n * @hidden Internal Use Only\n */\n ShadowLight.prototype._getWorldMatrix = function () {\n if (!this._worldMatrix) {\n this._worldMatrix = BABYLON.Matrix.Identity();\n }\n BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);\n return this._worldMatrix;\n };\n /**\n * Gets the minZ used for shadow according to both the scene and the light.\n * @param activeCamera The camera we are returning the min for\n * @returns the depth min z\n */\n ShadowLight.prototype.getDepthMinZ = function (activeCamera) {\n return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;\n };\n /**\n * Gets the maxZ used for shadow according to both the scene and the light.\n * @param activeCamera The camera we are returning the max for\n * @returns the depth max z\n */\n ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {\n return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;\n };\n /**\n * Sets the shadow projection matrix in parameter to the generated projection matrix.\n * @param matrix The materix to updated with the projection information\n * @param viewMatrix The transform matrix of the light\n * @param renderList The list of mesh to render in the map\n * @returns The current light\n */\n ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {\n if (this.customProjectionMatrixBuilder) {\n this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);\n }\n else {\n this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);\n }\n return this;\n };\n __decorate([\n BABYLON.serializeAsVector3()\n ], ShadowLight.prototype, \"position\", null);\n __decorate([\n BABYLON.serializeAsVector3()\n ], ShadowLight.prototype, \"direction\", null);\n __decorate([\n BABYLON.serialize()\n ], ShadowLight.prototype, \"shadowMinZ\", null);\n __decorate([\n BABYLON.serialize()\n ], ShadowLight.prototype, \"shadowMaxZ\", null);\n return ShadowLight;\n }(BABYLON.Light));\n BABYLON.ShadowLight = ShadowLight;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.shadowLight.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"Light_Type_0\", function (name, scene) {\n return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };\n });\n /**\n * A point light is a light defined by an unique point in world space.\n * The light is emitted in every direction from this point.\n * A good example of a point light is a standard light bulb.\n * Documentation: https://doc.babylonjs.com/babylon101/lights\n */\n var PointLight = /** @class */ (function (_super) {\n __extends(PointLight, _super);\n /**\n * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.\n * A PointLight emits the light in every direction.\n * It can cast shadows.\n * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :\n * ```javascript\n * var pointLight = new BABYLON.PointLight(\"pl\", camera.position, scene);\n * ```\n * Documentation : http://doc.babylonjs.com/tutorials/lights\n * @param name The light friendly name\n * @param position The position of the point light in the scene\n * @param scene The scene the lights belongs to\n */\n function PointLight(name, position, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._shadowAngle = Math.PI / 2;\n _this.position = position;\n return _this;\n }\n Object.defineProperty(PointLight.prototype, \"shadowAngle\", {\n /**\n * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n * This specifies what angle the shadow will use to be created.\n *\n * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.\n */\n get: function () {\n return this._shadowAngle;\n },\n /**\n * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n * This specifies what angle the shadow will use to be created.\n *\n * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.\n */\n set: function (value) {\n this._shadowAngle = value;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PointLight.prototype, \"direction\", {\n /**\n * Gets the direction if it has been set.\n * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n */\n get: function () {\n return this._direction;\n },\n /**\n * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n */\n set: function (value) {\n var previousNeedCube = this.needCube();\n this._direction = value;\n if (this.needCube() !== previousNeedCube && this._shadowGenerator) {\n this._shadowGenerator.recreateShadowMap();\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"PointLight\"\n * @returns the class name\n */\n PointLight.prototype.getClassName = function () {\n return \"PointLight\";\n };\n /**\n * Returns the integer 0.\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n PointLight.prototype.getTypeID = function () {\n return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;\n };\n /**\n * Specifies wether or not the shadowmap should be a cube texture.\n * @returns true if the shadowmap needs to be a cube texture.\n */\n PointLight.prototype.needCube = function () {\n return !this.direction;\n };\n /**\n * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).\n * @param faceIndex The index of the face we are computed the direction to generate shadow\n * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true\n */\n PointLight.prototype.getShadowDirection = function (faceIndex) {\n if (this.direction) {\n return _super.prototype.getShadowDirection.call(this, faceIndex);\n }\n else {\n switch (faceIndex) {\n case 0:\n return new BABYLON.Vector3(1.0, 0.0, 0.0);\n case 1:\n return new BABYLON.Vector3(-1.0, 0.0, 0.0);\n case 2:\n return new BABYLON.Vector3(0.0, -1.0, 0.0);\n case 3:\n return new BABYLON.Vector3(0.0, 1.0, 0.0);\n case 4:\n return new BABYLON.Vector3(0.0, 0.0, 1.0);\n case 5:\n return new BABYLON.Vector3(0.0, 0.0, -1.0);\n }\n }\n return BABYLON.Vector3.Zero();\n };\n /**\n * Sets the passed matrix \"matrix\" as a left-handed perspective projection matrix with the following settings :\n * - fov = PI / 2\n * - aspect ratio : 1.0\n * - z-near and far equal to the active camera minZ and maxZ.\n * Returns the PointLight.\n */\n PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {\n var activeCamera = this.getScene().activeCamera;\n if (!activeCamera) {\n return;\n }\n BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);\n };\n PointLight.prototype._buildUniformLayout = function () {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 3);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n };\n /**\n * Sets the passed Effect \"effect\" with the PointLight transformed position (or position, if none) and passed name (string).\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The point light\n */\n PointLight.prototype.transferToEffect = function (effect, lightIndex) {\n if (this.computeTransformedInformation()) {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);\n return this;\n }\n this._uniformBuffer.updateFloat4(\"vLightData\", this.position.x, this.position.y, this.position.z, 0, lightIndex);\n return this;\n };\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {\n defines[\"POINTLIGHT\" + lightIndex] = true;\n };\n __decorate([\n BABYLON.serialize()\n ], PointLight.prototype, \"shadowAngle\", null);\n return PointLight;\n }(BABYLON.ShadowLight));\n BABYLON.PointLight = PointLight;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pointLight.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"Light_Type_1\", function (name, scene) {\n return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };\n });\n /**\n * A directional light is defined by a direction (what a surprise!).\n * The light is emitted from everywhere in the specified direction, and has an infinite range.\n * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.\n * Documentation: https://doc.babylonjs.com/babylon101/lights\n */\n var DirectionalLight = /** @class */ (function (_super) {\n __extends(DirectionalLight, _super);\n /**\n * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).\n * The directional light is emitted from everywhere in the given direction.\n * It can cast shawdows.\n * Documentation : http://doc.babylonjs.com/tutorials/lights\n * @param name The friendly name of the light\n * @param direction The direction of the light\n * @param scene The scene the light belongs to\n */\n function DirectionalLight(name, direction, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._shadowFrustumSize = 0;\n _this._shadowOrthoScale = 0.1;\n /**\n * Automatically compute the projection matrix to best fit (including all the casters)\n * on each frame.\n */\n _this.autoUpdateExtends = true;\n // Cache\n _this._orthoLeft = Number.MAX_VALUE;\n _this._orthoRight = Number.MIN_VALUE;\n _this._orthoTop = Number.MIN_VALUE;\n _this._orthoBottom = Number.MAX_VALUE;\n _this.position = direction.scale(-1.0);\n _this.direction = direction;\n return _this;\n }\n Object.defineProperty(DirectionalLight.prototype, \"shadowFrustumSize\", {\n /**\n * Fix frustum size for the shadow generation. This is disabled if the value is 0.\n */\n get: function () {\n return this._shadowFrustumSize;\n },\n /**\n * Specifies a fix frustum size for the shadow generation.\n */\n set: function (value) {\n this._shadowFrustumSize = value;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DirectionalLight.prototype, \"shadowOrthoScale\", {\n /**\n * Gets the shadow projection scale against the optimal computed one.\n * 0.1 by default which means that the projection window is increase by 10% from the optimal size.\n * This does not impact in fixed frustum size (shadowFrustumSize being set)\n */\n get: function () {\n return this._shadowOrthoScale;\n },\n /**\n * Sets the shadow projection scale against the optimal computed one.\n * 0.1 by default which means that the projection window is increase by 10% from the optimal size.\n * This does not impact in fixed frustum size (shadowFrustumSize being set)\n */\n set: function (value) {\n this._shadowOrthoScale = value;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"DirectionalLight\".\n * @return The class name\n */\n DirectionalLight.prototype.getClassName = function () {\n return \"DirectionalLight\";\n };\n /**\n * Returns the integer 1.\n * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n DirectionalLight.prototype.getTypeID = function () {\n return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;\n };\n /**\n * Sets the passed matrix \"matrix\" as projection matrix for the shadows cast by the light according to the passed view matrix.\n * Returns the DirectionalLight Shadow projection matrix.\n */\n DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {\n if (this.shadowFrustumSize > 0) {\n this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);\n }\n else {\n this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);\n }\n };\n /**\n * Sets the passed matrix \"matrix\" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.\n * Returns the DirectionalLight Shadow projection matrix.\n */\n DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {\n var activeCamera = this.getScene().activeCamera;\n if (!activeCamera) {\n return;\n }\n BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);\n };\n /**\n * Sets the passed matrix \"matrix\" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.\n * Returns the DirectionalLight Shadow projection matrix.\n */\n DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {\n var activeCamera = this.getScene().activeCamera;\n if (!activeCamera) {\n return;\n }\n // Check extends\n if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {\n var tempVector3 = BABYLON.Vector3.Zero();\n this._orthoLeft = Number.MAX_VALUE;\n this._orthoRight = Number.MIN_VALUE;\n this._orthoTop = Number.MIN_VALUE;\n this._orthoBottom = Number.MAX_VALUE;\n for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {\n var mesh = renderList[meshIndex];\n if (!mesh) {\n continue;\n }\n var boundingInfo = mesh.getBoundingInfo();\n var boundingBox = boundingInfo.boundingBox;\n for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {\n BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);\n if (tempVector3.x < this._orthoLeft)\n this._orthoLeft = tempVector3.x;\n if (tempVector3.y < this._orthoBottom)\n this._orthoBottom = tempVector3.y;\n if (tempVector3.x > this._orthoRight)\n this._orthoRight = tempVector3.x;\n if (tempVector3.y > this._orthoTop)\n this._orthoTop = tempVector3.y;\n }\n }\n }\n var xOffset = this._orthoRight - this._orthoLeft;\n var yOffset = this._orthoTop - this._orthoBottom;\n BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);\n };\n DirectionalLight.prototype._buildUniformLayout = function () {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 3);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n };\n /**\n * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The directional light\n */\n DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {\n if (this.computeTransformedInformation()) {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);\n return this;\n }\n this._uniformBuffer.updateFloat4(\"vLightData\", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);\n return this;\n };\n /**\n * Gets the minZ used for shadow according to both the scene and the light.\n *\n * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being\n * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.\n * @param activeCamera The camera we are returning the min for\n * @returns the depth min z\n */\n DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {\n return 1;\n };\n /**\n * Gets the maxZ used for shadow according to both the scene and the light.\n *\n * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being\n * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.\n * @param activeCamera The camera we are returning the max for\n * @returns the depth max z\n */\n DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {\n return 1;\n };\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {\n defines[\"DIRLIGHT\" + lightIndex] = true;\n };\n __decorate([\n BABYLON.serialize()\n ], DirectionalLight.prototype, \"shadowFrustumSize\", null);\n __decorate([\n BABYLON.serialize()\n ], DirectionalLight.prototype, \"shadowOrthoScale\", null);\n __decorate([\n BABYLON.serialize()\n ], DirectionalLight.prototype, \"autoUpdateExtends\", void 0);\n return DirectionalLight;\n }(BABYLON.ShadowLight));\n BABYLON.DirectionalLight = DirectionalLight;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.directionalLight.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"Light_Type_2\", function (name, scene) {\n return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };\n });\n /**\n * A spot light is defined by a position, a direction, an angle, and an exponent.\n * These values define a cone of light starting from the position, emitting toward the direction.\n * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,\n * and the exponent defines the speed of the decay of the light with distance (reach).\n * Documentation: https://doc.babylonjs.com/babylon101/lights\n */\n var SpotLight = /** @class */ (function (_super) {\n __extends(SpotLight, _super);\n /**\n * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.\n * It can cast shadows.\n * Documentation : http://doc.babylonjs.com/tutorials/lights\n * @param name The light friendly name\n * @param position The position of the spot light in the scene\n * @param direction The direction of the light in the scene\n * @param angle The cone angle of the light in Radians\n * @param exponent The light decay speed with the distance from the emission spot\n * @param scene The scene the lights belongs to\n */\n function SpotLight(name, position, direction, angle, exponent, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._projectionTextureMatrix = BABYLON.Matrix.Zero();\n _this._projectionTextureLightNear = 1e-6;\n _this._projectionTextureLightFar = 1000.0;\n _this._projectionTextureUpDirection = BABYLON.Vector3.Up();\n _this._projectionTextureViewLightDirty = true;\n _this._projectionTextureProjectionLightDirty = true;\n _this._projectionTextureDirty = true;\n _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();\n _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();\n _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();\n _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);\n _this.position = position;\n _this.direction = direction;\n _this.angle = angle;\n _this.exponent = exponent;\n return _this;\n }\n Object.defineProperty(SpotLight.prototype, \"angle\", {\n /**\n * Gets the cone angle of the spot light in Radians.\n */\n get: function () {\n return this._angle;\n },\n /**\n * Sets the cone angle of the spot light in Radians.\n */\n set: function (value) {\n this._angle = value;\n this._projectionTextureProjectionLightDirty = true;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpotLight.prototype, \"shadowAngleScale\", {\n /**\n * Allows scaling the angle of the light for shadow generation only.\n */\n get: function () {\n return this._shadowAngleScale;\n },\n /**\n * Allows scaling the angle of the light for shadow generation only.\n */\n set: function (value) {\n this._shadowAngleScale = value;\n this.forceProjectionMatrixCompute();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpotLight.prototype, \"projectionTextureMatrix\", {\n /**\n * Allows reading the projecton texture\n */\n get: function () {\n return this._projectionTextureMatrix;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpotLight.prototype, \"projectionTextureLightNear\", {\n /**\n * Gets the near clip of the Spotlight for texture projection.\n */\n get: function () {\n return this._projectionTextureLightNear;\n },\n /**\n * Sets the near clip of the Spotlight for texture projection.\n */\n set: function (value) {\n this._projectionTextureLightNear = value;\n this._projectionTextureProjectionLightDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpotLight.prototype, \"projectionTextureLightFar\", {\n /**\n * Gets the far clip of the Spotlight for texture projection.\n */\n get: function () {\n return this._projectionTextureLightFar;\n },\n /**\n * Sets the far clip of the Spotlight for texture projection.\n */\n set: function (value) {\n this._projectionTextureLightFar = value;\n this._projectionTextureProjectionLightDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpotLight.prototype, \"projectionTextureUpDirection\", {\n /**\n * Gets the Up vector of the Spotlight for texture projection.\n */\n get: function () {\n return this._projectionTextureUpDirection;\n },\n /**\n * Sets the Up vector of the Spotlight for texture projection.\n */\n set: function (value) {\n this._projectionTextureUpDirection = value;\n this._projectionTextureProjectionLightDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpotLight.prototype, \"projectionTexture\", {\n /**\n * Gets the projection texture of the light.\n */\n get: function () {\n return this._projectionTexture;\n },\n /**\n * Sets the projection texture of the light.\n */\n set: function (value) {\n this._projectionTexture = value;\n this._projectionTextureDirty = true;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"SpotLight\".\n * @returns the class name\n */\n SpotLight.prototype.getClassName = function () {\n return \"SpotLight\";\n };\n /**\n * Returns the integer 2.\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n SpotLight.prototype.getTypeID = function () {\n return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;\n };\n /**\n * Overrides the direction setter to recompute the projection texture view light Matrix.\n */\n SpotLight.prototype._setDirection = function (value) {\n _super.prototype._setDirection.call(this, value);\n this._projectionTextureViewLightDirty = true;\n };\n /**\n * Overrides the position setter to recompute the projection texture view light Matrix.\n */\n SpotLight.prototype._setPosition = function (value) {\n _super.prototype._setPosition.call(this, value);\n this._projectionTextureViewLightDirty = true;\n };\n /**\n * Sets the passed matrix \"matrix\" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.\n * Returns the SpotLight.\n */\n SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {\n var activeCamera = this.getScene().activeCamera;\n if (!activeCamera) {\n return;\n }\n this._shadowAngleScale = this._shadowAngleScale || 1;\n var angle = this._shadowAngleScale * this._angle;\n BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);\n };\n SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {\n this._projectionTextureViewLightDirty = false;\n this._projectionTextureDirty = true;\n this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);\n BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);\n };\n SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {\n this._projectionTextureProjectionLightDirty = false;\n this._projectionTextureDirty = true;\n var light_far = this.projectionTextureLightFar;\n var light_near = this.projectionTextureLightNear;\n var P = light_far / (light_far - light_near);\n var Q = -P * light_near;\n var S = 1.0 / Math.tan(this._angle / 2.0);\n var A = 1.0;\n BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);\n };\n /**\n * Main function for light texture projection matrix computing.\n */\n SpotLight.prototype._computeProjectionTextureMatrix = function () {\n this._projectionTextureDirty = false;\n this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);\n this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);\n };\n SpotLight.prototype._buildUniformLayout = function () {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 3);\n this._uniformBuffer.addUniform(\"vLightDirection\", 3);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n };\n /**\n * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The spot light\n */\n SpotLight.prototype.transferToEffect = function (effect, lightIndex) {\n var normalizeDirection;\n if (this.computeTransformedInformation()) {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);\n normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);\n }\n else {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);\n normalizeDirection = BABYLON.Vector3.Normalize(this.direction);\n }\n this._uniformBuffer.updateFloat4(\"vLightDirection\", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);\n if (this.projectionTexture && this.projectionTexture.isReady()) {\n if (this._projectionTextureViewLightDirty) {\n this._computeProjectionTextureViewLightMatrix();\n }\n if (this._projectionTextureProjectionLightDirty) {\n this._computeProjectionTextureProjectionLightMatrix();\n }\n if (this._projectionTextureDirty) {\n this._computeProjectionTextureMatrix();\n }\n effect.setMatrix(\"textureProjectionMatrix\" + lightIndex, this._projectionTextureMatrix);\n effect.setTexture(\"projectionLightSampler\" + lightIndex, this.projectionTexture);\n }\n return this;\n };\n /**\n * Disposes the light and the associated resources.\n */\n SpotLight.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n if (this._projectionTexture) {\n this._projectionTexture.dispose();\n }\n };\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {\n defines[\"SPOTLIGHT\" + lightIndex] = true;\n defines[\"PROJECTEDLIGHTTEXTURE\" + lightIndex] = this.projectionTexture ? true : false;\n };\n __decorate([\n BABYLON.serialize()\n ], SpotLight.prototype, \"angle\", null);\n __decorate([\n BABYLON.serialize()\n ], SpotLight.prototype, \"shadowAngleScale\", null);\n __decorate([\n BABYLON.serialize()\n ], SpotLight.prototype, \"exponent\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SpotLight.prototype, \"projectionTextureLightNear\", null);\n __decorate([\n BABYLON.serialize()\n ], SpotLight.prototype, \"projectionTextureLightFar\", null);\n __decorate([\n BABYLON.serialize()\n ], SpotLight.prototype, \"projectionTextureUpDirection\", null);\n __decorate([\n BABYLON.serializeAsTexture(\"projectedLightTexture\")\n ], SpotLight.prototype, \"_projectionTexture\", void 0);\n return SpotLight;\n }(BABYLON.ShadowLight));\n BABYLON.SpotLight = SpotLight;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.spotLight.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to override all child animations of a given target\n */\n var AnimationPropertiesOverride = /** @class */ (function () {\n function AnimationPropertiesOverride() {\n /**\n * Gets or sets a value indicating if animation blending must be used\n */\n this.enableBlending = false;\n /**\n * Gets or sets the blending speed to use when enableBlending is true\n */\n this.blendingSpeed = 0.01;\n /**\n * Gets or sets the default loop mode to use\n */\n this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;\n }\n return AnimationPropertiesOverride;\n }());\n BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.animationPropertiesOverride.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Represents the range of an animation\n */\n var AnimationRange = /** @class */ (function () {\n /**\n * Initializes the range of an animation\n * @param name The name of the animation range\n * @param from The starting frame of the animation\n * @param to The ending frame of the animation\n */\n function AnimationRange(\n /**The name of the animation range**/\n name, \n /**The starting frame of the animation */\n from, \n /**The ending frame of the animation*/\n to) {\n this.name = name;\n this.from = from;\n this.to = to;\n }\n /**\n * Makes a copy of the animation range\n * @returns A copy of the animation range\n */\n AnimationRange.prototype.clone = function () {\n return new AnimationRange(this.name, this.from, this.to);\n };\n return AnimationRange;\n }());\n BABYLON.AnimationRange = AnimationRange;\n /**\n * Composed of a frame, and an action function\n */\n var AnimationEvent = /** @class */ (function () {\n /**\n * Initializes the animation event\n * @param frame The frame for which the event is triggered\n * @param action The event to perform when triggered\n * @param onlyOnce Specifies if the event should be triggered only once\n */\n function AnimationEvent(\n /** The frame for which the event is triggered **/\n frame, \n /** The event to perform when triggered **/\n action, \n /** Specifies if the event should be triggered only once**/\n onlyOnce) {\n this.frame = frame;\n this.action = action;\n this.onlyOnce = onlyOnce;\n /**\n * Specifies if the animation event is done\n */\n this.isDone = false;\n }\n /** @hidden */\n AnimationEvent.prototype._clone = function () {\n return new AnimationEvent(this.frame, this.action, this.onlyOnce);\n };\n return AnimationEvent;\n }());\n BABYLON.AnimationEvent = AnimationEvent;\n /**\n * A cursor which tracks a point on a path\n */\n var PathCursor = /** @class */ (function () {\n /**\n * Initializes the path cursor\n * @param path The path to track\n */\n function PathCursor(path) {\n this.path = path;\n /**\n * Stores path cursor callbacks for when an onchange event is triggered\n */\n this._onchange = new Array();\n /**\n * The value of the path cursor\n */\n this.value = 0;\n /**\n * The animation array of the path cursor\n */\n this.animations = new Array();\n }\n /**\n * Gets the cursor point on the path\n * @returns A point on the path cursor at the cursor location\n */\n PathCursor.prototype.getPoint = function () {\n var point = this.path.getPointAtLengthPosition(this.value);\n return new BABYLON.Vector3(point.x, 0, point.y);\n };\n /**\n * Moves the cursor ahead by the step amount\n * @param step The amount to move the cursor forward\n * @returns This path cursor\n */\n PathCursor.prototype.moveAhead = function (step) {\n if (step === void 0) { step = 0.002; }\n this.move(step);\n return this;\n };\n /**\n * Moves the cursor behind by the step amount\n * @param step The amount to move the cursor back\n * @returns This path cursor\n */\n PathCursor.prototype.moveBack = function (step) {\n if (step === void 0) { step = 0.002; }\n this.move(-step);\n return this;\n };\n /**\n * Moves the cursor by the step amount\n * If the step amount is greater than one, an exception is thrown\n * @param step The amount to move the cursor\n * @returns This path cursor\n */\n PathCursor.prototype.move = function (step) {\n if (Math.abs(step) > 1) {\n throw \"step size should be less than 1.\";\n }\n this.value += step;\n this.ensureLimits();\n this.raiseOnChange();\n return this;\n };\n /**\n * Ensures that the value is limited between zero and one\n * @returns This path cursor\n */\n PathCursor.prototype.ensureLimits = function () {\n while (this.value > 1) {\n this.value -= 1;\n }\n while (this.value < 0) {\n this.value += 1;\n }\n return this;\n };\n /**\n * Runs onchange callbacks on change (used by the animation engine)\n * @returns This path cursor\n */\n PathCursor.prototype.raiseOnChange = function () {\n var _this = this;\n this._onchange.forEach(function (f) { return f(_this); });\n return this;\n };\n /**\n * Executes a function on change\n * @param f A path cursor onchange callback\n * @returns This path cursor\n */\n PathCursor.prototype.onchange = function (f) {\n this._onchange.push(f);\n return this;\n };\n return PathCursor;\n }());\n BABYLON.PathCursor = PathCursor;\n /**\n * Enum for the animation key frame interpolation type\n */\n var AnimationKeyInterpolation;\n (function (AnimationKeyInterpolation) {\n /**\n * Do not interpolate between keys and use the start key value only. Tangents are ignored\n */\n AnimationKeyInterpolation[AnimationKeyInterpolation[\"STEP\"] = 1] = \"STEP\";\n })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));\n /**\n * Class used to store any kind of animation\n */\n var Animation = /** @class */ (function () {\n /**\n * Initializes the animation\n * @param name Name of the animation\n * @param targetProperty Property to animate\n * @param framePerSecond The frames per second of the animation\n * @param dataType The data type of the animation\n * @param loopMode The loop mode of the animation\n * @param enableBlendings Specifies if blending should be enabled\n */\n function Animation(\n /**Name of the animation */\n name, \n /**Property to animate */\n targetProperty, \n /**The frames per second of the animation */\n framePerSecond, \n /**The data type of the animation */\n dataType, \n /**The loop mode of the animation */\n loopMode, \n /**Specifies if blending should be enabled */\n enableBlending) {\n this.name = name;\n this.targetProperty = targetProperty;\n this.framePerSecond = framePerSecond;\n this.dataType = dataType;\n this.loopMode = loopMode;\n this.enableBlending = enableBlending;\n /**\n * @hidden Internal use only\n */\n this._runtimeAnimations = new Array();\n /**\n * The set of event that will be linked to this animation\n */\n this._events = new Array();\n /**\n * Stores the blending speed of the animation\n */\n this.blendingSpeed = 0.01;\n /**\n * Stores the animation ranges for the animation\n */\n this._ranges = {};\n this.targetPropertyPath = targetProperty.split(\".\");\n this.dataType = dataType;\n this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;\n }\n /**\n * @hidden Internal use\n */\n Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {\n var dataType = undefined;\n if (!isNaN(parseFloat(from)) && isFinite(from)) {\n dataType = Animation.ANIMATIONTYPE_FLOAT;\n }\n else if (from instanceof BABYLON.Quaternion) {\n dataType = Animation.ANIMATIONTYPE_QUATERNION;\n }\n else if (from instanceof BABYLON.Vector3) {\n dataType = Animation.ANIMATIONTYPE_VECTOR3;\n }\n else if (from instanceof BABYLON.Vector2) {\n dataType = Animation.ANIMATIONTYPE_VECTOR2;\n }\n else if (from instanceof BABYLON.Color3) {\n dataType = Animation.ANIMATIONTYPE_COLOR3;\n }\n else if (from instanceof BABYLON.Size) {\n dataType = Animation.ANIMATIONTYPE_SIZE;\n }\n if (dataType == undefined) {\n return null;\n }\n var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);\n var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];\n animation.setKeys(keys);\n if (easingFunction !== undefined) {\n animation.setEasingFunction(easingFunction);\n }\n return animation;\n };\n /**\n * Sets up an animation\n * @param property The property to animate\n * @param animationType The animation type to apply\n * @param framePerSecond The frames per second of the animation\n * @param easingFunction The easing function used in the animation\n * @returns The created animation\n */\n Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {\n var animation = new Animation(property + \"Animation\", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);\n animation.setEasingFunction(easingFunction);\n return animation;\n };\n /**\n * Create and start an animation on a node\n * @param name defines the name of the global animation that will be run on all nodes\n * @param node defines the root node where the animation will take place\n * @param targetProperty defines property to animate\n * @param framePerSecond defines the number of frame per second yo use\n * @param totalFrame defines the number of frames in total\n * @param from defines the initial value\n * @param to defines the final value\n * @param loopMode defines which loop mode you want to use (off by default)\n * @param easingFunction defines the easing function to use (linear by default)\n * @param onAnimationEnd defines the callback to call when animation end\n * @returns the animatable created for this animation\n */\n Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {\n var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);\n if (!animation) {\n return null;\n }\n return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);\n };\n /**\n * Create and start an animation on a node and its descendants\n * @param name defines the name of the global animation that will be run on all nodes\n * @param node defines the root node where the animation will take place\n * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used\n * @param targetProperty defines property to animate\n * @param framePerSecond defines the number of frame per second to use\n * @param totalFrame defines the number of frames in total\n * @param from defines the initial value\n * @param to defines the final value\n * @param loopMode defines which loop mode you want to use (off by default)\n * @param easingFunction defines the easing function to use (linear by default)\n * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)\n * @returns the list of animatables created for all nodes\n * @example https://www.babylonjs-playground.com/#MH0VLI\n */\n Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {\n var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);\n if (!animation) {\n return null;\n }\n var scene = node.getScene();\n return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);\n };\n /**\n * Creates a new animation, merges it with the existing animations and starts it\n * @param name Name of the animation\n * @param node Node which contains the scene that begins the animations\n * @param targetProperty Specifies which property to animate\n * @param framePerSecond The frames per second of the animation\n * @param totalFrame The total number of frames\n * @param from The frame at the beginning of the animation\n * @param to The frame at the end of the animation\n * @param loopMode Specifies the loop mode of the animation\n * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations\n * @param onAnimationEnd Callback to run once the animation is complete\n * @returns Nullable animation\n */\n Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {\n var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);\n if (!animation) {\n return null;\n }\n node.animations.push(animation);\n return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);\n };\n /**\n * Transition property of an host to the target Value\n * @param property The property to transition\n * @param targetValue The target Value of the property\n * @param host The object where the property to animate belongs\n * @param scene Scene used to run the animation\n * @param frameRate Framerate (in frame/s) to use\n * @param transition The transition type we want to use\n * @param duration The duration of the animation, in milliseconds\n * @param onAnimationEnd Callback trigger at the end of the animation\n * @returns Nullable animation\n */\n Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {\n if (onAnimationEnd === void 0) { onAnimationEnd = null; }\n if (duration <= 0) {\n host[property] = targetValue;\n if (onAnimationEnd) {\n onAnimationEnd();\n }\n return null;\n }\n var endFrame = frameRate * (duration / 1000);\n transition.setKeys([{\n frame: 0,\n value: host[property].clone ? host[property].clone() : host[property]\n },\n {\n frame: endFrame,\n value: targetValue\n }]);\n if (!host.animations) {\n host.animations = [];\n }\n host.animations.push(transition);\n var animation = scene.beginAnimation(host, 0, endFrame, false);\n animation.onAnimationEnd = onAnimationEnd;\n return animation;\n };\n Object.defineProperty(Animation.prototype, \"runtimeAnimations\", {\n /**\n * Return the array of runtime animations currently using this animation\n */\n get: function () {\n return this._runtimeAnimations;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation.prototype, \"hasRunningRuntimeAnimations\", {\n /**\n * Specifies if any of the runtime animations are currently running\n */\n get: function () {\n for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {\n var runtimeAnimation = _a[_i];\n if (!runtimeAnimation.isStopped) {\n return true;\n }\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n /**\n * Converts the animation to a string\n * @param fullDetails support for multiple levels of logging within scene loading\n * @returns String form of the animation\n */\n Animation.prototype.toString = function (fullDetails) {\n var ret = \"Name: \" + this.name + \", property: \" + this.targetProperty;\n ret += \", datatype: \" + ([\"Float\", \"Vector3\", \"Quaternion\", \"Matrix\", \"Color3\", \"Vector2\"])[this.dataType];\n ret += \", nKeys: \" + (this._keys ? this._keys.length : \"none\");\n ret += \", nRanges: \" + (this._ranges ? Object.keys(this._ranges).length : \"none\");\n if (fullDetails) {\n ret += \", Ranges: {\";\n var first = true;\n for (var name in this._ranges) {\n if (first) {\n ret += \", \";\n first = false;\n }\n ret += name;\n }\n ret += \"}\";\n }\n return ret;\n };\n /**\n * Add an event to this animation\n * @param event Event to add\n */\n Animation.prototype.addEvent = function (event) {\n this._events.push(event);\n };\n /**\n * Remove all events found at the given frame\n * @param frame The frame to remove events from\n */\n Animation.prototype.removeEvents = function (frame) {\n for (var index = 0; index < this._events.length; index++) {\n if (this._events[index].frame === frame) {\n this._events.splice(index, 1);\n index--;\n }\n }\n };\n /**\n * Retrieves all the events from the animation\n * @returns Events from the animation\n */\n Animation.prototype.getEvents = function () {\n return this._events;\n };\n /**\n * Creates an animation range\n * @param name Name of the animation range\n * @param from Starting frame of the animation range\n * @param to Ending frame of the animation\n */\n Animation.prototype.createRange = function (name, from, to) {\n // check name not already in use; could happen for bones after serialized\n if (!this._ranges[name]) {\n this._ranges[name] = new AnimationRange(name, from, to);\n }\n };\n /**\n * Deletes an animation range by name\n * @param name Name of the animation range to delete\n * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)\n */\n Animation.prototype.deleteRange = function (name, deleteFrames) {\n if (deleteFrames === void 0) { deleteFrames = true; }\n var range = this._ranges[name];\n if (!range) {\n return;\n }\n if (deleteFrames) {\n var from = range.from;\n var to = range.to;\n // this loop MUST go high to low for multiple splices to work\n for (var key = this._keys.length - 1; key >= 0; key--) {\n if (this._keys[key].frame >= from && this._keys[key].frame <= to) {\n this._keys.splice(key, 1);\n }\n }\n }\n this._ranges[name] = null; // said much faster than 'delete this._range[name]' \n };\n /**\n * Gets the animation range by name, or null if not defined\n * @param name Name of the animation range\n * @returns Nullable animation range\n */\n Animation.prototype.getRange = function (name) {\n return this._ranges[name];\n };\n /**\n * Gets the key frames from the animation\n * @returns The key frames of the animation\n */\n Animation.prototype.getKeys = function () {\n return this._keys;\n };\n /**\n * Gets the highest frame rate of the animation\n * @returns Highest frame rate of the animation\n */\n Animation.prototype.getHighestFrame = function () {\n var ret = 0;\n for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {\n if (ret < this._keys[key].frame) {\n ret = this._keys[key].frame;\n }\n }\n return ret;\n };\n /**\n * Gets the easing function of the animation\n * @returns Easing function of the animation\n */\n Animation.prototype.getEasingFunction = function () {\n return this._easingFunction;\n };\n /**\n * Sets the easing function of the animation\n * @param easingFunction A custom mathematical formula for animation\n */\n Animation.prototype.setEasingFunction = function (easingFunction) {\n this._easingFunction = easingFunction;\n };\n /**\n * Interpolates a scalar linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated scalar value\n */\n Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {\n return BABYLON.Scalar.Lerp(startValue, endValue, gradient);\n };\n /**\n * Interpolates a scalar cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated scalar value\n */\n Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {\n return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n };\n /**\n * Interpolates a quaternion using a spherical linear interpolation\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated quaternion value\n */\n Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {\n return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);\n };\n /**\n * Interpolates a quaternion cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation curve\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated quaternion value\n */\n Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {\n return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();\n };\n /**\n * Interpolates a Vector3 linearl\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated scalar value\n */\n Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {\n return BABYLON.Vector3.Lerp(startValue, endValue, gradient);\n };\n /**\n * Interpolates a Vector3 cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns InterpolatedVector3 value\n */\n Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {\n return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n };\n /**\n * Interpolates a Vector2 linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Vector2 value\n */\n Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {\n return BABYLON.Vector2.Lerp(startValue, endValue, gradient);\n };\n /**\n * Interpolates a Vector2 cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Vector2 value\n */\n Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {\n return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n };\n /**\n * Interpolates a size linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Size value\n */\n Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {\n return BABYLON.Size.Lerp(startValue, endValue, gradient);\n };\n /**\n * Interpolates a Color3 linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Color3 value\n */\n Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {\n return BABYLON.Color3.Lerp(startValue, endValue, gradient);\n };\n /**\n * @hidden Internal use only\n */\n Animation.prototype._getKeyValue = function (value) {\n if (typeof value === \"function\") {\n return value();\n }\n return value;\n };\n /**\n * @hidden Internal use only\n */\n Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {\n if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {\n return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;\n }\n var keys = this.getKeys();\n // Try to get a hash to find the right key\n var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));\n if (keys[startKeyIndex].frame >= currentFrame) {\n while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {\n startKeyIndex--;\n }\n }\n for (var key = startKeyIndex; key < keys.length; key++) {\n var endKey = keys[key + 1];\n if (endKey.frame >= currentFrame) {\n var startKey = keys[key];\n var startValue = this._getKeyValue(startKey.value);\n if (startKey.interpolation === AnimationKeyInterpolation.STEP) {\n return startValue;\n }\n var endValue = this._getKeyValue(endKey.value);\n var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;\n var frameDelta = endKey.frame - startKey.frame;\n // gradient : percent of currentFrame between the frame inf and the frame sup\n var gradient = (currentFrame - startKey.frame) / frameDelta;\n // check for easingFunction and correction of gradient\n var easingFunction = this.getEasingFunction();\n if (easingFunction != null) {\n gradient = easingFunction.ease(gradient);\n }\n switch (this.dataType) {\n // Float\n case Animation.ANIMATIONTYPE_FLOAT:\n var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n return floatValue;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return offsetValue * repeatCount + floatValue;\n }\n break;\n // Quaternion\n case Animation.ANIMATIONTYPE_QUATERNION:\n var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n return quatValue;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return quatValue.addInPlace(offsetValue.scale(repeatCount));\n }\n return quatValue;\n // Vector3\n case Animation.ANIMATIONTYPE_VECTOR3:\n var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n return vec3Value;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return vec3Value.add(offsetValue.scale(repeatCount));\n }\n // Vector2\n case Animation.ANIMATIONTYPE_VECTOR2:\n var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n return vec2Value;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return vec2Value.add(offsetValue.scale(repeatCount));\n }\n // Size\n case Animation.ANIMATIONTYPE_SIZE:\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n return this.sizeInterpolateFunction(startValue, endValue, gradient);\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));\n }\n // Color3\n case Animation.ANIMATIONTYPE_COLOR3:\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n return this.color3InterpolateFunction(startValue, endValue, gradient);\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));\n }\n // Matrix\n case Animation.ANIMATIONTYPE_MATRIX:\n switch (loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n if (Animation.AllowMatricesInterpolation) {\n return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);\n }\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return startValue;\n }\n default:\n break;\n }\n break;\n }\n }\n return this._getKeyValue(keys[keys.length - 1].value);\n };\n /**\n * Defines the function to use to interpolate matrices\n * @param startValue defines the start matrix\n * @param endValue defines the end matrix\n * @param gradient defines the gradient between both matrices\n * @param result defines an optional target matrix where to store the interpolation\n * @returns the interpolated matrix\n */\n Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {\n if (Animation.AllowMatrixDecomposeForInterpolation) {\n if (result) {\n BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);\n return result;\n }\n return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);\n }\n if (result) {\n BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);\n return result;\n }\n return BABYLON.Matrix.Lerp(startValue, endValue, gradient);\n };\n /**\n * Makes a copy of the animation\n * @returns Cloned animation\n */\n Animation.prototype.clone = function () {\n var clone = new Animation(this.name, this.targetPropertyPath.join(\".\"), this.framePerSecond, this.dataType, this.loopMode);\n clone.enableBlending = this.enableBlending;\n clone.blendingSpeed = this.blendingSpeed;\n if (this._keys) {\n clone.setKeys(this._keys);\n }\n if (this._ranges) {\n clone._ranges = {};\n for (var name in this._ranges) {\n var range = this._ranges[name];\n if (!range) {\n continue;\n }\n clone._ranges[name] = range.clone();\n }\n }\n return clone;\n };\n /**\n * Sets the key frames of the animation\n * @param values The animation key frames to set\n */\n Animation.prototype.setKeys = function (values) {\n this._keys = values.slice(0);\n };\n /**\n * Serializes the animation to an object\n * @returns Serialized object\n */\n Animation.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.property = this.targetProperty;\n serializationObject.framePerSecond = this.framePerSecond;\n serializationObject.dataType = this.dataType;\n serializationObject.loopBehavior = this.loopMode;\n serializationObject.enableBlending = this.enableBlending;\n serializationObject.blendingSpeed = this.blendingSpeed;\n var dataType = this.dataType;\n serializationObject.keys = [];\n var keys = this.getKeys();\n for (var index = 0; index < keys.length; index++) {\n var animationKey = keys[index];\n var key = {};\n key.frame = animationKey.frame;\n switch (dataType) {\n case Animation.ANIMATIONTYPE_FLOAT:\n key.values = [animationKey.value];\n break;\n case Animation.ANIMATIONTYPE_QUATERNION:\n case Animation.ANIMATIONTYPE_MATRIX:\n case Animation.ANIMATIONTYPE_VECTOR3:\n case Animation.ANIMATIONTYPE_COLOR3:\n key.values = animationKey.value.asArray();\n break;\n }\n serializationObject.keys.push(key);\n }\n serializationObject.ranges = [];\n for (var name in this._ranges) {\n var source = this._ranges[name];\n if (!source) {\n continue;\n }\n var range = {};\n range.name = name;\n range.from = source.from;\n range.to = source.to;\n serializationObject.ranges.push(range);\n }\n return serializationObject;\n };\n Object.defineProperty(Animation, \"ANIMATIONTYPE_FLOAT\", {\n /**\n * Get the float animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_FLOAT;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONTYPE_VECTOR3\", {\n /**\n * Get the Vector3 animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_VECTOR3;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONTYPE_VECTOR2\", {\n /**\n * Get the Vectpr2 animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_VECTOR2;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONTYPE_SIZE\", {\n /**\n * Get the Size animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_SIZE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONTYPE_QUATERNION\", {\n /**\n * Get the Quaternion animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_QUATERNION;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONTYPE_MATRIX\", {\n /**\n * Get the Matrix animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_MATRIX;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONTYPE_COLOR3\", {\n /**\n * Get the Color3 animation type\n */\n get: function () {\n return Animation._ANIMATIONTYPE_COLOR3;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONLOOPMODE_RELATIVE\", {\n /**\n * Get the Relative Loop Mode\n */\n get: function () {\n return Animation._ANIMATIONLOOPMODE_RELATIVE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONLOOPMODE_CYCLE\", {\n /**\n * Get the Cycle Loop Mode\n */\n get: function () {\n return Animation._ANIMATIONLOOPMODE_CYCLE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animation, \"ANIMATIONLOOPMODE_CONSTANT\", {\n /**\n * Get the Constant Loop Mode\n */\n get: function () {\n return Animation._ANIMATIONLOOPMODE_CONSTANT;\n },\n enumerable: true,\n configurable: true\n });\n /** @hidden */\n Animation._UniversalLerp = function (left, right, amount) {\n var constructor = left.constructor;\n if (constructor.Lerp) { // Lerp supported\n return constructor.Lerp(left, right, amount);\n }\n else if (constructor.Slerp) { // Slerp supported\n return constructor.Slerp(left, right, amount);\n }\n else if (left.toFixed) { // Number\n return left * (1.0 - amount) + amount * right;\n }\n else { // Blending not supported\n return right;\n }\n };\n /**\n * Parses an animation object and creates an animation\n * @param parsedAnimation Parsed animation object\n * @returns Animation object\n */\n Animation.Parse = function (parsedAnimation) {\n var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);\n var dataType = parsedAnimation.dataType;\n var keys = [];\n var data;\n var index;\n if (parsedAnimation.enableBlending) {\n animation.enableBlending = parsedAnimation.enableBlending;\n }\n if (parsedAnimation.blendingSpeed) {\n animation.blendingSpeed = parsedAnimation.blendingSpeed;\n }\n for (index = 0; index < parsedAnimation.keys.length; index++) {\n var key = parsedAnimation.keys[index];\n var inTangent;\n var outTangent;\n switch (dataType) {\n case Animation.ANIMATIONTYPE_FLOAT:\n data = key.values[0];\n if (key.values.length >= 1) {\n inTangent = key.values[1];\n }\n if (key.values.length >= 2) {\n outTangent = key.values[2];\n }\n break;\n case Animation.ANIMATIONTYPE_QUATERNION:\n data = BABYLON.Quaternion.FromArray(key.values);\n if (key.values.length >= 8) {\n var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));\n if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {\n inTangent = _inTangent;\n }\n }\n if (key.values.length >= 12) {\n var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));\n if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {\n outTangent = _outTangent;\n }\n }\n break;\n case Animation.ANIMATIONTYPE_MATRIX:\n data = BABYLON.Matrix.FromArray(key.values);\n break;\n case Animation.ANIMATIONTYPE_COLOR3:\n data = BABYLON.Color3.FromArray(key.values);\n break;\n case Animation.ANIMATIONTYPE_VECTOR3:\n default:\n data = BABYLON.Vector3.FromArray(key.values);\n break;\n }\n var keyData = {};\n keyData.frame = key.frame;\n keyData.value = data;\n if (inTangent != undefined) {\n keyData.inTangent = inTangent;\n }\n if (outTangent != undefined) {\n keyData.outTangent = outTangent;\n }\n keys.push(keyData);\n }\n animation.setKeys(keys);\n if (parsedAnimation.ranges) {\n for (index = 0; index < parsedAnimation.ranges.length; index++) {\n data = parsedAnimation.ranges[index];\n animation.createRange(data.name, data.from, data.to);\n }\n }\n return animation;\n };\n /**\n * Appends the serialized animations from the source animations\n * @param source Source containing the animations\n * @param destination Target to store the animations\n */\n Animation.AppendSerializedAnimations = function (source, destination) {\n if (source.animations) {\n destination.animations = [];\n for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {\n var animation = source.animations[animationIndex];\n destination.animations.push(animation.serialize());\n }\n }\n };\n /**\n * Use matrix interpolation instead of using direct key value when animating matrices\n */\n Animation.AllowMatricesInterpolation = false;\n /**\n * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower\n */\n Animation.AllowMatrixDecomposeForInterpolation = true;\n // Statics\n /**\n * Float animation type\n */\n Animation._ANIMATIONTYPE_FLOAT = 0;\n /**\n * Vector3 animation type\n */\n Animation._ANIMATIONTYPE_VECTOR3 = 1;\n /**\n * Quaternion animation type\n */\n Animation._ANIMATIONTYPE_QUATERNION = 2;\n /**\n * Matrix animation type\n */\n Animation._ANIMATIONTYPE_MATRIX = 3;\n /**\n * Color3 animation type\n */\n Animation._ANIMATIONTYPE_COLOR3 = 4;\n /**\n * Vector2 animation type\n */\n Animation._ANIMATIONTYPE_VECTOR2 = 5;\n /**\n * Size animation type\n */\n Animation._ANIMATIONTYPE_SIZE = 6;\n /**\n * Relative Loop Mode\n */\n Animation._ANIMATIONLOOPMODE_RELATIVE = 0;\n /**\n * Cycle Loop Mode\n */\n Animation._ANIMATIONLOOPMODE_CYCLE = 1;\n /**\n * Constant Loop Mode\n */\n Animation._ANIMATIONLOOPMODE_CONSTANT = 2;\n return Animation;\n }());\n BABYLON.Animation = Animation;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.animation.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class defines the direct association between an animation and a target\n */\n var TargetedAnimation = /** @class */ (function () {\n function TargetedAnimation() {\n }\n return TargetedAnimation;\n }());\n BABYLON.TargetedAnimation = TargetedAnimation;\n /**\n * Use this class to create coordinated animations on multiple targets\n */\n var AnimationGroup = /** @class */ (function () {\n function AnimationGroup(name, scene) {\n if (scene === void 0) { scene = null; }\n this.name = name;\n this._targetedAnimations = new Array();\n this._animatables = new Array();\n this._from = Number.MAX_VALUE;\n this._to = -Number.MAX_VALUE;\n this._speedRatio = 1;\n this.onAnimationEndObservable = new BABYLON.Observable();\n /**\n * This observable will notify when all animations have ended.\n */\n this.onAnimationGroupEndObservable = new BABYLON.Observable();\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this._scene.animationGroups.push(this);\n }\n Object.defineProperty(AnimationGroup.prototype, \"from\", {\n /**\n * Gets the first frame\n */\n get: function () {\n return this._from;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AnimationGroup.prototype, \"to\", {\n /**\n * Gets the last frame\n */\n get: function () {\n return this._to;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AnimationGroup.prototype, \"isStarted\", {\n /**\n * Define if the animations are started\n */\n get: function () {\n return this._isStarted;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AnimationGroup.prototype, \"speedRatio\", {\n /**\n * Gets or sets the speed ratio to use for all animations\n */\n get: function () {\n return this._speedRatio;\n },\n /**\n * Gets or sets the speed ratio to use for all animations\n */\n set: function (value) {\n if (this._speedRatio === value) {\n return;\n }\n this._speedRatio = value;\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.speedRatio = this._speedRatio;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AnimationGroup.prototype, \"targetedAnimations\", {\n /**\n * Gets the targeted animations for this animation group\n */\n get: function () {\n return this._targetedAnimations;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AnimationGroup.prototype, \"animatables\", {\n /**\n * returning the list of animatables controlled by this animation group.\n */\n get: function () {\n return this._animatables;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Add an animation (with its target) in the group\n * @param animation defines the animation we want to add\n * @param target defines the target of the animation\n * @returns the {BABYLON.TargetedAnimation} object\n */\n AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {\n var targetedAnimation = {\n animation: animation,\n target: target\n };\n var keys = animation.getKeys();\n if (this._from > keys[0].frame) {\n this._from = keys[0].frame;\n }\n if (this._to < keys[keys.length - 1].frame) {\n this._to = keys[keys.length - 1].frame;\n }\n this._targetedAnimations.push(targetedAnimation);\n return targetedAnimation;\n };\n /**\n * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame\n * It can add constant keys at begin or end\n * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)\n * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)\n */\n AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {\n if (beginFrame === void 0) { beginFrame = null; }\n if (endFrame === void 0) { endFrame = null; }\n if (beginFrame == null)\n beginFrame = this._from;\n if (endFrame == null)\n endFrame = this._to;\n for (var index = 0; index < this._targetedAnimations.length; index++) {\n var targetedAnimation = this._targetedAnimations[index];\n var keys = targetedAnimation.animation.getKeys();\n var startKey = keys[0];\n var endKey = keys[keys.length - 1];\n if (startKey.frame > beginFrame) {\n var newKey = {\n frame: beginFrame,\n value: startKey.value,\n inTangent: startKey.inTangent,\n outTangent: startKey.outTangent,\n interpolation: startKey.interpolation\n };\n keys.splice(0, 0, newKey);\n }\n if (endKey.frame < endFrame) {\n var newKey = {\n frame: endFrame,\n value: endKey.value,\n inTangent: endKey.outTangent,\n outTangent: endKey.outTangent,\n interpolation: endKey.interpolation\n };\n keys.push(newKey);\n }\n }\n this._from = beginFrame;\n this._to = endFrame;\n return this;\n };\n /**\n * Start all animations on given targets\n * @param loop defines if animations must loop\n * @param speedRatio defines the ratio to apply to animation speed (1 by default)\n * @param from defines the from key (optional)\n * @param to defines the to key (optional)\n * @returns the current animation group\n */\n AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {\n var _this = this;\n if (loop === void 0) { loop = false; }\n if (speedRatio === void 0) { speedRatio = 1; }\n if (this._isStarted || this._targetedAnimations.length === 0) {\n return this;\n }\n var _loop_1 = function (targetedAnimation) {\n var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);\n animatable.onAnimationEnd = function () {\n _this.onAnimationEndObservable.notifyObservers(targetedAnimation);\n _this._checkAnimationGroupEnded(animatable);\n };\n this_1._animatables.push(animatable);\n };\n var this_1 = this;\n for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {\n var targetedAnimation = _a[_i];\n _loop_1(targetedAnimation);\n }\n this._speedRatio = speedRatio;\n this._isStarted = true;\n return this;\n };\n /**\n * Pause all animations\n */\n AnimationGroup.prototype.pause = function () {\n if (!this._isStarted) {\n return this;\n }\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.pause();\n }\n return this;\n };\n /**\n * Play all animations to initial state\n * This function will start() the animations if they were not started or will restart() them if they were paused\n * @param loop defines if animations must loop\n */\n AnimationGroup.prototype.play = function (loop) {\n // only if all animatables are ready and exist\n if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {\n if (loop !== undefined) {\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.loopAnimation = loop;\n }\n }\n this.restart();\n }\n else {\n this.stop();\n this.start(loop, this._speedRatio);\n }\n return this;\n };\n /**\n * Reset all animations to initial state\n */\n AnimationGroup.prototype.reset = function () {\n if (!this._isStarted) {\n return this;\n }\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.reset();\n }\n return this;\n };\n /**\n * Restart animations from key 0\n */\n AnimationGroup.prototype.restart = function () {\n if (!this._isStarted) {\n return this;\n }\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.restart();\n }\n return this;\n };\n /**\n * Stop all animations\n */\n AnimationGroup.prototype.stop = function () {\n if (!this._isStarted) {\n return this;\n }\n var list = this._animatables.slice();\n for (var index = 0; index < list.length; index++) {\n list[index].stop();\n }\n this._isStarted = false;\n return this;\n };\n /**\n * Set animation weight for all animatables\n * @param weight defines the weight to use\n * @return the animationGroup\n * @see http://doc.babylonjs.com/babylon101/animations#animation-weights\n */\n AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.weight = weight;\n }\n return this;\n };\n /**\n * Synchronize and normalize all animatables with a source animatable\n * @param root defines the root animatable to synchronize with\n * @return the animationGroup\n * @see http://doc.babylonjs.com/babylon101/animations#animation-weights\n */\n AnimationGroup.prototype.syncAllAnimationsWith = function (root) {\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.syncWith(root);\n }\n return this;\n };\n /**\n * Goes to a specific frame in this animation group\n * @param frame the frame number to go to\n * @return the animationGroup\n */\n AnimationGroup.prototype.goToFrame = function (frame) {\n if (!this._isStarted) {\n return this;\n }\n for (var index = 0; index < this._animatables.length; index++) {\n var animatable = this._animatables[index];\n animatable.goToFrame(frame);\n }\n return this;\n };\n /**\n * Dispose all associated resources\n */\n AnimationGroup.prototype.dispose = function () {\n this._targetedAnimations = [];\n this._animatables = [];\n var index = this._scene.animationGroups.indexOf(this);\n if (index > -1) {\n this._scene.animationGroups.splice(index, 1);\n }\n };\n AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {\n // animatable should be taken out of the array\n var idx = this._animatables.indexOf(animatable);\n if (idx > -1) {\n this._animatables.splice(idx, 1);\n }\n // all animatables were removed? animation group ended!\n if (this._animatables.length === 0) {\n this._isStarted = false;\n this.onAnimationGroupEndObservable.notifyObservers(this);\n }\n };\n return AnimationGroup;\n }());\n BABYLON.AnimationGroup = AnimationGroup;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.animationGroup.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines a runtime animation\n */\n var RuntimeAnimation = /** @class */ (function () {\n /**\n * Create a new RuntimeAnimation object\n * @param target defines the target of the animation\n * @param animation defines the source animation object\n * @param scene defines the hosting scene\n * @param host defines the initiating Animatable\n */\n function RuntimeAnimation(target, animation, scene, host) {\n var _this = this;\n this._events = new Array();\n /**\n * The current frame of the runtime animation\n */\n this._currentFrame = 0;\n /**\n * The original value of the runtime animation\n */\n this._originalValue = new Array();\n /**\n * The offsets cache of the runtime animation\n */\n this._offsetsCache = {};\n /**\n * The high limits cache of the runtime animation\n */\n this._highLimitsCache = {};\n /**\n * Specifies if the runtime animation has been stopped\n */\n this._stopped = false;\n /**\n * The blending factor of the runtime animation\n */\n this._blendingFactor = 0;\n /**\n * The target path of the runtime animation\n */\n this._targetPath = \"\";\n /**\n * The weight of the runtime animation\n */\n this._weight = 1.0;\n /**\n * The ratio offset of the runtime animation\n */\n this._ratioOffset = 0;\n /**\n * The previous delay of the runtime animation\n */\n this._previousDelay = 0;\n /**\n * The previous ratio of the runtime animation\n */\n this._previousRatio = 0;\n this._animation = animation;\n this._target = target;\n this._scene = scene;\n this._host = host;\n animation._runtimeAnimations.push(this);\n // Cloning events locally\n var events = animation.getEvents();\n if (events && events.length > 0) {\n events.forEach(function (e) {\n _this._events.push(e._clone());\n });\n }\n }\n Object.defineProperty(RuntimeAnimation.prototype, \"currentFrame\", {\n /**\n * Gets the current frame of the runtime animation\n */\n get: function () {\n return this._currentFrame;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RuntimeAnimation.prototype, \"weight\", {\n /**\n * Gets the weight of the runtime animation\n */\n get: function () {\n return this._weight;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RuntimeAnimation.prototype, \"currentValue\", {\n /**\n * Gets the current value of the runtime animation\n */\n get: function () {\n return this._currentValue;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RuntimeAnimation.prototype, \"targetPath\", {\n /**\n * Gets the target path of the runtime animation\n */\n get: function () {\n return this._targetPath;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RuntimeAnimation.prototype, \"target\", {\n /**\n * Gets the actual target of the runtime animation\n */\n get: function () {\n return this._activeTarget;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RuntimeAnimation.prototype, \"animation\", {\n /**\n * Gets the animation from the runtime animation\n */\n get: function () {\n return this._animation;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Resets the runtime animation to the beginning\n * @param restoreOriginal defines whether to restore the target property to the original value\n */\n RuntimeAnimation.prototype.reset = function (restoreOriginal) {\n if (restoreOriginal === void 0) { restoreOriginal = false; }\n if (restoreOriginal) {\n if (this._target instanceof Array) {\n var index = 0;\n for (var _i = 0, _a = this._target; _i < _a.length; _i++) {\n var target = _a[_i];\n if (this._originalValue[index] !== undefined) {\n this._setValue(target, this._originalValue[index], -1);\n }\n index++;\n }\n }\n else {\n if (this._originalValue[0] !== undefined) {\n this._setValue(this._target, this._originalValue[0], -1);\n }\n }\n }\n this._offsetsCache = {};\n this._highLimitsCache = {};\n this._currentFrame = 0;\n this._blendingFactor = 0;\n this._originalValue = new Array();\n // Events\n for (var index = 0; index < this._events.length; index++) {\n this._events[index].isDone = false;\n }\n };\n /**\n * Specifies if the runtime animation is stopped\n * @returns Boolean specifying if the runtime animation is stopped\n */\n RuntimeAnimation.prototype.isStopped = function () {\n return this._stopped;\n };\n /**\n * Disposes of the runtime animation\n */\n RuntimeAnimation.prototype.dispose = function () {\n var index = this._animation.runtimeAnimations.indexOf(this);\n if (index > -1) {\n this._animation.runtimeAnimations.splice(index, 1);\n }\n };\n /**\n * Interpolates the animation from the current frame\n * @param currentFrame The frame to interpolate the animation to\n * @param repeatCount The number of times that the animation should loop\n * @param loopMode The type of looping mode to use\n * @param offsetValue Animation offset value\n * @param highLimitValue The high limit value\n * @returns The interpolated value\n */\n RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {\n this._currentFrame = currentFrame;\n if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {\n this._workValue = BABYLON.Matrix.Zero();\n }\n return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);\n };\n /**\n * Apply the interpolated value to the target\n * @param currentValue defines the value computed by the animation\n * @param weight defines the weight to apply to this value (Defaults to 1.0)\n */\n RuntimeAnimation.prototype.setValue = function (currentValue, weight) {\n if (weight === void 0) { weight = 1.0; }\n if (this._target instanceof Array) {\n var index = 0;\n for (var _i = 0, _a = this._target; _i < _a.length; _i++) {\n var target = _a[_i];\n this._setValue(target, currentValue, weight, index);\n index++;\n }\n }\n else {\n this._setValue(this._target, currentValue, weight);\n }\n };\n RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {\n if (targetIndex === void 0) { targetIndex = 0; }\n // Set value\n var path;\n var destination;\n var targetPropertyPath = this._animation.targetPropertyPath;\n if (targetPropertyPath.length > 1) {\n var property = target[targetPropertyPath[0]];\n for (var index = 1; index < targetPropertyPath.length - 1; index++) {\n property = property[targetPropertyPath[index]];\n }\n path = targetPropertyPath[targetPropertyPath.length - 1];\n destination = property;\n }\n else {\n path = targetPropertyPath[0];\n destination = target;\n }\n this._targetPath = path;\n this._activeTarget = destination;\n this._weight = weight;\n if (this._originalValue[targetIndex] === undefined) {\n var originalValue = void 0;\n if (destination.getRestPose && path === \"_matrix\") { // For bones\n originalValue = destination.getRestPose();\n }\n else {\n originalValue = destination[path];\n }\n if (originalValue && originalValue.clone) {\n this._originalValue[targetIndex] = originalValue.clone();\n }\n else {\n this._originalValue[targetIndex] = originalValue;\n }\n }\n // Blending\n var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;\n if (enableBlending && this._blendingFactor <= 1.0) {\n if (!this._originalBlendValue) {\n var originalValue = destination[path];\n if (originalValue.clone) {\n this._originalBlendValue = originalValue.clone();\n }\n else {\n this._originalBlendValue = originalValue;\n }\n }\n if (this._originalBlendValue.m) { // Matrix\n if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {\n if (this._currentValue) {\n BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);\n }\n else {\n this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);\n }\n }\n else {\n if (this._currentValue) {\n BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);\n }\n else {\n this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);\n }\n }\n }\n else {\n this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);\n }\n var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;\n this._blendingFactor += blendingSpeed;\n }\n else {\n this._currentValue = currentValue;\n }\n if (weight !== -1.0) {\n this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);\n }\n else {\n destination[path] = this._currentValue;\n }\n if (target.markAsDirty) {\n target.markAsDirty(this._animation.targetProperty);\n }\n };\n /**\n * Gets the loop pmode of the runtime animation\n * @returns Loop Mode\n */\n RuntimeAnimation.prototype._getCorrectLoopMode = function () {\n if (this._target && this._target.animationPropertiesOverride) {\n return this._target.animationPropertiesOverride.loopMode;\n }\n return this._animation.loopMode;\n };\n /**\n * Move the current animation to a given frame\n * @param frame defines the frame to move to\n */\n RuntimeAnimation.prototype.goToFrame = function (frame) {\n var keys = this._animation.getKeys();\n if (frame < keys[0].frame) {\n frame = keys[0].frame;\n }\n else if (frame > keys[keys.length - 1].frame) {\n frame = keys[keys.length - 1].frame;\n }\n var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());\n this.setValue(currentValue, -1);\n };\n /**\n * @hidden Internal use only\n */\n RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {\n var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;\n this._ratioOffset = this._previousRatio - newRatio;\n };\n /**\n * Execute the current animation\n * @param delay defines the delay to add to the current frame\n * @param from defines the lower bound of the animation range\n * @param to defines the upper bound of the animation range\n * @param loop defines if the current animation must loop\n * @param speedRatio defines the current speed ratio\n * @param weight defines the weight of the animation (default is -1 so no weight)\n * @returns a boolean indicating if the animation is running\n */\n RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {\n if (weight === void 0) { weight = -1.0; }\n var targetPropertyPath = this._animation.targetPropertyPath;\n if (!targetPropertyPath || targetPropertyPath.length < 1) {\n this._stopped = true;\n return false;\n }\n var returnValue = true;\n var keys = this._animation.getKeys();\n // Adding a start key at frame 0 if missing\n if (keys[0].frame !== 0) {\n var newKey = { frame: 0, value: keys[0].value };\n keys.splice(0, 0, newKey);\n }\n // Adding a duplicate key when there is only one key at frame zero\n else if (keys.length === 1) {\n var newKey = { frame: 0.001, value: keys[0].value };\n keys.push(newKey);\n }\n // Check limits\n if (from < keys[0].frame || from > keys[keys.length - 1].frame) {\n from = keys[0].frame;\n }\n if (to < keys[0].frame || to > keys[keys.length - 1].frame) {\n to = keys[keys.length - 1].frame;\n }\n //to and from cannot be the same key\n if (from === to) {\n if (from > keys[0].frame) {\n from--;\n }\n else if (to < keys[keys.length - 1].frame) {\n to++;\n }\n }\n // Compute ratio\n var range = to - from;\n var offsetValue;\n // ratio represents the frame delta between from and to\n var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;\n var highLimitValue = 0;\n this._previousDelay = delay;\n this._previousRatio = ratio;\n if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller\n returnValue = false;\n highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);\n }\n else {\n // Get max value if required\n if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {\n var keyOffset = to.toString() + from.toString();\n if (!this._offsetsCache[keyOffset]) {\n var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);\n var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);\n switch (this._animation.dataType) {\n // Float\n case BABYLON.Animation.ANIMATIONTYPE_FLOAT:\n this._offsetsCache[keyOffset] = toValue - fromValue;\n break;\n // Quaternion\n case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n break;\n // Vector3\n case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n // Vector2\n case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n // Size\n case BABYLON.Animation.ANIMATIONTYPE_SIZE:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n // Color3\n case BABYLON.Animation.ANIMATIONTYPE_COLOR3:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n default:\n break;\n }\n this._highLimitsCache[keyOffset] = toValue;\n }\n highLimitValue = this._highLimitsCache[keyOffset];\n offsetValue = this._offsetsCache[keyOffset];\n }\n }\n if (offsetValue === undefined) {\n switch (this._animation.dataType) {\n // Float\n case BABYLON.Animation.ANIMATIONTYPE_FLOAT:\n offsetValue = 0;\n break;\n // Quaternion\n case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:\n offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);\n break;\n // Vector3\n case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:\n offsetValue = BABYLON.Vector3.Zero();\n break;\n // Vector2\n case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:\n offsetValue = BABYLON.Vector2.Zero();\n break;\n // Size\n case BABYLON.Animation.ANIMATIONTYPE_SIZE:\n offsetValue = BABYLON.Size.Zero();\n break;\n // Color3\n case BABYLON.Animation.ANIMATIONTYPE_COLOR3:\n offsetValue = BABYLON.Color3.Black();\n }\n }\n // Compute value\n var repeatCount = (ratio / range) >> 0;\n var currentFrame = returnValue ? from + ratio % range : to;\n // Need to normalize?\n if (this._host && this._host.syncRoot) {\n var syncRoot = this._host.syncRoot;\n var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);\n currentFrame = from + (to - from) * hostNormalizedFrame;\n }\n // Reset events if looping\n var events = this._events;\n if (range > 0 && this.currentFrame > currentFrame ||\n range < 0 && this.currentFrame < currentFrame) {\n // Need to reset animation events\n for (var index = 0; index < events.length; index++) {\n if (!events[index].onlyOnce) {\n // reset event, the animation is looping\n events[index].isDone = false;\n }\n }\n }\n var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);\n // Set value\n this.setValue(currentValue, weight);\n // Check events\n for (var index = 0; index < events.length; index++) {\n // Make sure current frame has passed event frame and that event frame is within the current range\n // Also, handle both forward and reverse animations\n if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||\n (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {\n var event = events[index];\n if (!event.isDone) {\n // If event should be done only once, remove it.\n if (event.onlyOnce) {\n events.splice(index, 1);\n index--;\n }\n event.isDone = true;\n event.action();\n } // Don't do anything if the event has already be done.\n }\n }\n if (!returnValue) {\n this._stopped = true;\n }\n return returnValue;\n };\n return RuntimeAnimation;\n }());\n BABYLON.RuntimeAnimation = RuntimeAnimation;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.runtimeAnimation.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to store an actual running animation\n */\n var Animatable = /** @class */ (function () {\n /**\n * Creates a new Animatable\n * @param scene defines the hosting scene\n * @param target defines the target object\n * @param fromFrame defines the starting frame number (default is 0)\n * @param toFrame defines the ending frame number (default is 100)\n * @param loopAnimation defines if the animation must loop (default is false)\n * @param speedRatio defines the factor to apply to animation speed (default is 1)\n * @param onAnimationEnd defines a callback to call when animation ends if it is not looping\n * @param animations defines a group of animation to add to the new Animatable\n */\n function Animatable(scene, \n /** defines the target object */\n target, \n /** defines the starting frame number (default is 0) */\n fromFrame, \n /** defines the ending frame number (default is 100) */\n toFrame, \n /** defines if the animation must loop (default is false) */\n loopAnimation, speedRatio, \n /** defines a callback to call when animation ends if it is not looping */\n onAnimationEnd, animations) {\n if (fromFrame === void 0) { fromFrame = 0; }\n if (toFrame === void 0) { toFrame = 100; }\n if (loopAnimation === void 0) { loopAnimation = false; }\n if (speedRatio === void 0) { speedRatio = 1.0; }\n this.target = target;\n this.fromFrame = fromFrame;\n this.toFrame = toFrame;\n this.loopAnimation = loopAnimation;\n this.onAnimationEnd = onAnimationEnd;\n this._localDelayOffset = null;\n this._pausedDelay = null;\n this._runtimeAnimations = new Array();\n this._paused = false;\n this._speedRatio = 1;\n this._weight = -1.0;\n /**\n * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.\n * This will only apply for non looping animation (default is true)\n */\n this.disposeOnEnd = true;\n /**\n * Gets a boolean indicating if the animation has started\n */\n this.animationStarted = false;\n /**\n * Observer raised when the animation ends\n */\n this.onAnimationEndObservable = new BABYLON.Observable();\n this._scene = scene;\n if (animations) {\n this.appendAnimations(target, animations);\n }\n this._speedRatio = speedRatio;\n scene._activeAnimatables.push(this);\n }\n Object.defineProperty(Animatable.prototype, \"syncRoot\", {\n /**\n * Gets the root Animatable used to synchronize and normalize animations\n */\n get: function () {\n return this._syncRoot;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animatable.prototype, \"masterFrame\", {\n /**\n * Gets the current frame of the first RuntimeAnimation\n * Used to synchronize Animatables\n */\n get: function () {\n if (this._runtimeAnimations.length === 0) {\n return 0;\n }\n return this._runtimeAnimations[0].currentFrame;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animatable.prototype, \"weight\", {\n /**\n * Gets or sets the animatable weight (-1.0 by default meaning not weighted)\n */\n get: function () {\n return this._weight;\n },\n set: function (value) {\n if (value === -1) { // -1 is ok and means no weight\n this._weight = -1;\n return;\n }\n // Else weight must be in [0, 1] range\n this._weight = Math.min(Math.max(value, 0), 1.0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Animatable.prototype, \"speedRatio\", {\n /**\n * Gets or sets the speed ratio to apply to the animatable (1.0 by default)\n */\n get: function () {\n return this._speedRatio;\n },\n set: function (value) {\n for (var index = 0; index < this._runtimeAnimations.length; index++) {\n var animation = this._runtimeAnimations[index];\n animation._prepareForSpeedRatioChange(value);\n }\n this._speedRatio = value;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n /**\n * Synchronize and normalize current Animatable with a source Animatable\n * This is useful when using animation weights and when animations are not of the same length\n * @param root defines the root Animatable to synchronize with\n * @returns the current Animatable\n */\n Animatable.prototype.syncWith = function (root) {\n this._syncRoot = root;\n if (root) {\n // Make sure this animatable will animate after the root\n var index = this._scene._activeAnimatables.indexOf(this);\n if (index > -1) {\n this._scene._activeAnimatables.splice(index, 1);\n this._scene._activeAnimatables.push(this);\n }\n }\n return this;\n };\n /**\n * Gets the list of runtime animations\n * @returns an array of RuntimeAnimation\n */\n Animatable.prototype.getAnimations = function () {\n return this._runtimeAnimations;\n };\n /**\n * Adds more animations to the current animatable\n * @param target defines the target of the animations\n * @param animations defines the new animations to add\n */\n Animatable.prototype.appendAnimations = function (target, animations) {\n for (var index = 0; index < animations.length; index++) {\n var animation = animations[index];\n this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));\n }\n };\n /**\n * Gets the source animation for a specific property\n * @param property defines the propertyu to look for\n * @returns null or the source animation for the given property\n */\n Animatable.prototype.getAnimationByTargetProperty = function (property) {\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = 0; index < runtimeAnimations.length; index++) {\n if (runtimeAnimations[index].animation.targetProperty === property) {\n return runtimeAnimations[index].animation;\n }\n }\n return null;\n };\n /**\n * Gets the runtime animation for a specific property\n * @param property defines the propertyu to look for\n * @returns null or the runtime animation for the given property\n */\n Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = 0; index < runtimeAnimations.length; index++) {\n if (runtimeAnimations[index].animation.targetProperty === property) {\n return runtimeAnimations[index];\n }\n }\n return null;\n };\n /**\n * Resets the animatable to its original state\n */\n Animatable.prototype.reset = function () {\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].reset(true);\n }\n this._localDelayOffset = null;\n this._pausedDelay = null;\n };\n /**\n * Allows the animatable to blend with current running animations\n * @see http://doc.babylonjs.com/babylon101/animations#animation-blending\n * @param blendingSpeed defines the blending speed to use\n */\n Animatable.prototype.enableBlending = function (blendingSpeed) {\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].animation.enableBlending = true;\n runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;\n }\n };\n /**\n * Disable animation blending\n * @see http://doc.babylonjs.com/babylon101/animations#animation-blending\n */\n Animatable.prototype.disableBlending = function () {\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].animation.enableBlending = false;\n }\n };\n /**\n * Jump directly to a given frame\n * @param frame defines the frame to jump to\n */\n Animatable.prototype.goToFrame = function (frame) {\n var runtimeAnimations = this._runtimeAnimations;\n if (runtimeAnimations[0]) {\n var fps = runtimeAnimations[0].animation.framePerSecond;\n var currentFrame = runtimeAnimations[0].currentFrame;\n var adjustTime = frame - currentFrame;\n var delay = adjustTime * 1000 / (fps * this.speedRatio);\n if (this._localDelayOffset === null) {\n this._localDelayOffset = 0;\n }\n this._localDelayOffset -= delay;\n }\n for (var index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].goToFrame(frame);\n }\n };\n /**\n * Pause the animation\n */\n Animatable.prototype.pause = function () {\n if (this._paused) {\n return;\n }\n this._paused = true;\n };\n /**\n * Restart the animation\n */\n Animatable.prototype.restart = function () {\n this._paused = false;\n };\n Animatable.prototype._raiseOnAnimationEnd = function () {\n if (this.onAnimationEnd) {\n this.onAnimationEnd();\n }\n this.onAnimationEndObservable.notifyObservers(this);\n };\n /**\n * Stop and delete the current animation\n * @param animationName defines a string used to only stop some of the runtime animations instead of all\n * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)\n */\n Animatable.prototype.stop = function (animationName, targetMask) {\n if (animationName || targetMask) {\n var idx = this._scene._activeAnimatables.indexOf(this);\n if (idx > -1) {\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = runtimeAnimations.length - 1; index >= 0; index--) {\n var runtimeAnimation = runtimeAnimations[index];\n if (animationName && runtimeAnimation.animation.name != animationName) {\n continue;\n }\n if (targetMask && !targetMask(runtimeAnimation.target)) {\n continue;\n }\n runtimeAnimation.dispose();\n runtimeAnimations.splice(index, 1);\n }\n if (runtimeAnimations.length == 0) {\n this._scene._activeAnimatables.splice(idx, 1);\n this._raiseOnAnimationEnd();\n }\n }\n }\n else {\n var index = this._scene._activeAnimatables.indexOf(this);\n if (index > -1) {\n this._scene._activeAnimatables.splice(index, 1);\n var runtimeAnimations = this._runtimeAnimations;\n for (var index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].dispose();\n }\n this._raiseOnAnimationEnd();\n }\n }\n };\n /**\n * Wait asynchronously for the animation to end\n * @returns a promise which will be fullfilled when the animation ends\n */\n Animatable.prototype.waitAsync = function () {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this.onAnimationEndObservable.add(function () {\n resolve(_this);\n }, undefined, undefined, _this, true);\n });\n };\n /** @hidden */\n Animatable.prototype._animate = function (delay) {\n if (this._paused) {\n this.animationStarted = false;\n if (this._pausedDelay === null) {\n this._pausedDelay = delay;\n }\n return true;\n }\n if (this._localDelayOffset === null) {\n this._localDelayOffset = delay;\n this._pausedDelay = null;\n }\n else if (this._pausedDelay !== null) {\n this._localDelayOffset += delay - this._pausedDelay;\n this._pausedDelay = null;\n }\n if (this._weight === 0) { // We consider that an animation with a weight === 0 is \"actively\" paused\n return true;\n }\n // Animating\n var running = false;\n var runtimeAnimations = this._runtimeAnimations;\n var index;\n for (index = 0; index < runtimeAnimations.length; index++) {\n var animation = runtimeAnimations[index];\n var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);\n running = running || isRunning;\n }\n this.animationStarted = running;\n if (!running) {\n if (this.disposeOnEnd) {\n // Remove from active animatables\n index = this._scene._activeAnimatables.indexOf(this);\n this._scene._activeAnimatables.splice(index, 1);\n // Dispose all runtime animations\n for (index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].dispose();\n }\n }\n this._raiseOnAnimationEnd();\n if (this.disposeOnEnd) {\n this.onAnimationEnd = null;\n this.onAnimationEndObservable.clear();\n }\n }\n return running;\n };\n return Animatable;\n }());\n BABYLON.Animatable = Animatable;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.animatable.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var EasingFunction = /** @class */ (function () {\n function EasingFunction() {\n // Properties\n this._easingMode = EasingFunction.EASINGMODE_EASEIN;\n }\n Object.defineProperty(EasingFunction, \"EASINGMODE_EASEIN\", {\n get: function () {\n return EasingFunction._EASINGMODE_EASEIN;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EasingFunction, \"EASINGMODE_EASEOUT\", {\n get: function () {\n return EasingFunction._EASINGMODE_EASEOUT;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EasingFunction, \"EASINGMODE_EASEINOUT\", {\n get: function () {\n return EasingFunction._EASINGMODE_EASEINOUT;\n },\n enumerable: true,\n configurable: true\n });\n EasingFunction.prototype.setEasingMode = function (easingMode) {\n var n = Math.min(Math.max(easingMode, 0), 2);\n this._easingMode = n;\n };\n EasingFunction.prototype.getEasingMode = function () {\n return this._easingMode;\n };\n EasingFunction.prototype.easeInCore = function (gradient) {\n throw new Error('You must implement this method');\n };\n EasingFunction.prototype.ease = function (gradient) {\n switch (this._easingMode) {\n case EasingFunction.EASINGMODE_EASEIN:\n return this.easeInCore(gradient);\n case EasingFunction.EASINGMODE_EASEOUT:\n return (1 - this.easeInCore(1 - gradient));\n }\n if (gradient >= 0.5) {\n return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);\n }\n return (this.easeInCore(gradient * 2) * 0.5);\n };\n //Statics\n EasingFunction._EASINGMODE_EASEIN = 0;\n EasingFunction._EASINGMODE_EASEOUT = 1;\n EasingFunction._EASINGMODE_EASEINOUT = 2;\n return EasingFunction;\n }());\n BABYLON.EasingFunction = EasingFunction;\n var CircleEase = /** @class */ (function (_super) {\n __extends(CircleEase, _super);\n function CircleEase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n CircleEase.prototype.easeInCore = function (gradient) {\n gradient = Math.max(0, Math.min(1, gradient));\n return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));\n };\n return CircleEase;\n }(EasingFunction));\n BABYLON.CircleEase = CircleEase;\n var BackEase = /** @class */ (function (_super) {\n __extends(BackEase, _super);\n function BackEase(amplitude) {\n if (amplitude === void 0) { amplitude = 1; }\n var _this = _super.call(this) || this;\n _this.amplitude = amplitude;\n return _this;\n }\n BackEase.prototype.easeInCore = function (gradient) {\n var num = Math.max(0, this.amplitude);\n return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));\n };\n return BackEase;\n }(EasingFunction));\n BABYLON.BackEase = BackEase;\n var BounceEase = /** @class */ (function (_super) {\n __extends(BounceEase, _super);\n function BounceEase(bounces, bounciness) {\n if (bounces === void 0) { bounces = 3; }\n if (bounciness === void 0) { bounciness = 2; }\n var _this = _super.call(this) || this;\n _this.bounces = bounces;\n _this.bounciness = bounciness;\n return _this;\n }\n BounceEase.prototype.easeInCore = function (gradient) {\n var y = Math.max(0.0, this.bounces);\n var bounciness = this.bounciness;\n if (bounciness <= 1.0) {\n bounciness = 1.001;\n }\n var num9 = Math.pow(bounciness, y);\n var num5 = 1.0 - bounciness;\n var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);\n var num15 = gradient * num4;\n var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);\n var num3 = Math.floor(num65);\n var num13 = num3 + 1.0;\n var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);\n var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);\n var num7 = (num8 + num12) * 0.5;\n var num6 = gradient - num7;\n var num2 = num7 - num8;\n return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));\n };\n return BounceEase;\n }(EasingFunction));\n BABYLON.BounceEase = BounceEase;\n var CubicEase = /** @class */ (function (_super) {\n __extends(CubicEase, _super);\n function CubicEase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n CubicEase.prototype.easeInCore = function (gradient) {\n return (gradient * gradient * gradient);\n };\n return CubicEase;\n }(EasingFunction));\n BABYLON.CubicEase = CubicEase;\n var ElasticEase = /** @class */ (function (_super) {\n __extends(ElasticEase, _super);\n function ElasticEase(oscillations, springiness) {\n if (oscillations === void 0) { oscillations = 3; }\n if (springiness === void 0) { springiness = 3; }\n var _this = _super.call(this) || this;\n _this.oscillations = oscillations;\n _this.springiness = springiness;\n return _this;\n }\n ElasticEase.prototype.easeInCore = function (gradient) {\n var num2;\n var num3 = Math.max(0.0, this.oscillations);\n var num = Math.max(0.0, this.springiness);\n if (num == 0) {\n num2 = gradient;\n }\n else {\n num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);\n }\n return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));\n };\n return ElasticEase;\n }(EasingFunction));\n BABYLON.ElasticEase = ElasticEase;\n var ExponentialEase = /** @class */ (function (_super) {\n __extends(ExponentialEase, _super);\n function ExponentialEase(exponent) {\n if (exponent === void 0) { exponent = 2; }\n var _this = _super.call(this) || this;\n _this.exponent = exponent;\n return _this;\n }\n ExponentialEase.prototype.easeInCore = function (gradient) {\n if (this.exponent <= 0) {\n return gradient;\n }\n return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));\n };\n return ExponentialEase;\n }(EasingFunction));\n BABYLON.ExponentialEase = ExponentialEase;\n var PowerEase = /** @class */ (function (_super) {\n __extends(PowerEase, _super);\n function PowerEase(power) {\n if (power === void 0) { power = 2; }\n var _this = _super.call(this) || this;\n _this.power = power;\n return _this;\n }\n PowerEase.prototype.easeInCore = function (gradient) {\n var y = Math.max(0.0, this.power);\n return Math.pow(gradient, y);\n };\n return PowerEase;\n }(EasingFunction));\n BABYLON.PowerEase = PowerEase;\n var QuadraticEase = /** @class */ (function (_super) {\n __extends(QuadraticEase, _super);\n function QuadraticEase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n QuadraticEase.prototype.easeInCore = function (gradient) {\n return (gradient * gradient);\n };\n return QuadraticEase;\n }(EasingFunction));\n BABYLON.QuadraticEase = QuadraticEase;\n var QuarticEase = /** @class */ (function (_super) {\n __extends(QuarticEase, _super);\n function QuarticEase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n QuarticEase.prototype.easeInCore = function (gradient) {\n return (gradient * gradient * gradient * gradient);\n };\n return QuarticEase;\n }(EasingFunction));\n BABYLON.QuarticEase = QuarticEase;\n var QuinticEase = /** @class */ (function (_super) {\n __extends(QuinticEase, _super);\n function QuinticEase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n QuinticEase.prototype.easeInCore = function (gradient) {\n return (gradient * gradient * gradient * gradient * gradient);\n };\n return QuinticEase;\n }(EasingFunction));\n BABYLON.QuinticEase = QuinticEase;\n var SineEase = /** @class */ (function (_super) {\n __extends(SineEase, _super);\n function SineEase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n SineEase.prototype.easeInCore = function (gradient) {\n return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));\n };\n return SineEase;\n }(EasingFunction));\n BABYLON.SineEase = SineEase;\n var BezierCurveEase = /** @class */ (function (_super) {\n __extends(BezierCurveEase, _super);\n function BezierCurveEase(x1, y1, x2, y2) {\n if (x1 === void 0) { x1 = 0; }\n if (y1 === void 0) { y1 = 0; }\n if (x2 === void 0) { x2 = 1; }\n if (y2 === void 0) { y2 = 1; }\n var _this = _super.call(this) || this;\n _this.x1 = x1;\n _this.y1 = y1;\n _this.x2 = x2;\n _this.y2 = y2;\n return _this;\n }\n BezierCurveEase.prototype.easeInCore = function (gradient) {\n return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);\n };\n return BezierCurveEase;\n }(EasingFunction));\n BABYLON.BezierCurveEase = BezierCurveEase;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.easing.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A Condition applied to an Action\n */\n var Condition = /** @class */ (function () {\n /**\n * Creates a new Condition\n * @param actionManager the manager of the action the condition is applied to\n */\n function Condition(actionManager) {\n this._actionManager = actionManager;\n }\n /**\n * Check if the current condition is valid\n * @returns a boolean\n */\n Condition.prototype.isValid = function () {\n return true;\n };\n /**\n * Internal only\n * @hidden\n */\n Condition.prototype._getProperty = function (propertyPath) {\n return this._actionManager._getProperty(propertyPath);\n };\n /**\n * Internal only\n * @hidden\n */\n Condition.prototype._getEffectiveTarget = function (target, propertyPath) {\n return this._actionManager._getEffectiveTarget(target, propertyPath);\n };\n /**\n * Serialize placeholder for child classes\n * @returns the serialized object\n */\n Condition.prototype.serialize = function () {\n };\n /**\n * Internal only\n * @hidden\n */\n Condition.prototype._serialize = function (serializedCondition) {\n return {\n type: 2,\n children: [],\n name: serializedCondition.name,\n properties: serializedCondition.properties\n };\n };\n return Condition;\n }());\n BABYLON.Condition = Condition;\n /**\n * Defines specific conditional operators as extensions of Condition\n */\n var ValueCondition = /** @class */ (function (_super) {\n __extends(ValueCondition, _super);\n /**\n * Creates a new ValueCondition\n * @param actionManager manager for the action the condition applies to\n * @param target for the action\n * @param propertyPath path to specify the property of the target the conditional operator uses\n * @param value the value compared by the conditional operator against the current value of the property\n * @param operator the conditional operator, default ValueCondition.IsEqual\n */\n function ValueCondition(actionManager, target, \n /** path to specify the property of the target the conditional operator uses */\n propertyPath, \n /** the value compared by the conditional operator against the current value of the property */\n value, \n /** the conditional operator, default ValueCondition.IsEqual */\n operator) {\n if (operator === void 0) { operator = ValueCondition.IsEqual; }\n var _this = _super.call(this, actionManager) || this;\n _this.propertyPath = propertyPath;\n _this.value = value;\n _this.operator = operator;\n _this._target = target;\n _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);\n _this._property = _this._getProperty(_this.propertyPath);\n return _this;\n }\n Object.defineProperty(ValueCondition, \"IsEqual\", {\n /**\n * returns the number for IsEqual\n */\n get: function () {\n return ValueCondition._IsEqual;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValueCondition, \"IsDifferent\", {\n /**\n * Returns the number for IsDifferent\n */\n get: function () {\n return ValueCondition._IsDifferent;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValueCondition, \"IsGreater\", {\n /**\n * Returns the number for IsGreater\n */\n get: function () {\n return ValueCondition._IsGreater;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValueCondition, \"IsLesser\", {\n /**\n * Returns the number for IsLesser\n */\n get: function () {\n return ValueCondition._IsLesser;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Compares the given value with the property value for the specified conditional operator\n * @returns the result of the comparison\n */\n ValueCondition.prototype.isValid = function () {\n switch (this.operator) {\n case ValueCondition.IsGreater:\n return this._effectiveTarget[this._property] > this.value;\n case ValueCondition.IsLesser:\n return this._effectiveTarget[this._property] < this.value;\n case ValueCondition.IsEqual:\n case ValueCondition.IsDifferent:\n var check;\n if (this.value.equals) {\n check = this.value.equals(this._effectiveTarget[this._property]);\n }\n else {\n check = this.value === this._effectiveTarget[this._property];\n }\n return this.operator === ValueCondition.IsEqual ? check : !check;\n }\n return false;\n };\n /**\n * Serialize the ValueCondition into a JSON compatible object\n * @returns serialization object\n */\n ValueCondition.prototype.serialize = function () {\n return this._serialize({\n name: \"ValueCondition\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: BABYLON.Action._SerializeValueAsString(this.value) },\n { name: \"operator\", value: ValueCondition.GetOperatorName(this.operator) }\n ]\n });\n };\n /**\n * Gets the name of the conditional operator for the ValueCondition\n * @param operator the conditional operator\n * @returns the name\n */\n ValueCondition.GetOperatorName = function (operator) {\n switch (operator) {\n case ValueCondition._IsEqual: return \"IsEqual\";\n case ValueCondition._IsDifferent: return \"IsDifferent\";\n case ValueCondition._IsGreater: return \"IsGreater\";\n case ValueCondition._IsLesser: return \"IsLesser\";\n default: return \"\";\n }\n };\n /**\n * Internal only\n * @hidden\n */\n ValueCondition._IsEqual = 0;\n /**\n * Internal only\n * @hidden\n */\n ValueCondition._IsDifferent = 1;\n /**\n * Internal only\n * @hidden\n */\n ValueCondition._IsGreater = 2;\n /**\n * Internal only\n * @hidden\n */\n ValueCondition._IsLesser = 3;\n return ValueCondition;\n }(Condition));\n BABYLON.ValueCondition = ValueCondition;\n /**\n * Defines a predicate condition as an extension of Condition\n */\n var PredicateCondition = /** @class */ (function (_super) {\n __extends(PredicateCondition, _super);\n /**\n * Creates a new PredicateCondition\n * @param actionManager manager for the action the condition applies to\n * @param predicate defines the predicate function used to validate the condition\n */\n function PredicateCondition(actionManager, \n /** defines the predicate function used to validate the condition */\n predicate) {\n var _this = _super.call(this, actionManager) || this;\n _this.predicate = predicate;\n return _this;\n }\n /**\n * @returns the validity of the predicate condition\n */\n PredicateCondition.prototype.isValid = function () {\n return this.predicate();\n };\n return PredicateCondition;\n }(Condition));\n BABYLON.PredicateCondition = PredicateCondition;\n /**\n * Defines a state condition as an extension of Condition\n */\n var StateCondition = /** @class */ (function (_super) {\n __extends(StateCondition, _super);\n /**\n * Creates a new StateCondition\n * @param actionManager manager for the action the condition applies to\n * @param target of the condition\n * @param value to compare with target state\n */\n function StateCondition(actionManager, target, value) {\n var _this = _super.call(this, actionManager) || this;\n _this.value = value;\n _this._target = target;\n return _this;\n }\n /**\n * @returns the validity of the state\n */\n StateCondition.prototype.isValid = function () {\n return this._target.state === this.value;\n };\n /**\n * Serialize the StateCondition into a JSON compatible object\n * @returns serialization object\n */\n StateCondition.prototype.serialize = function () {\n return this._serialize({\n name: \"StateCondition\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"value\", value: this.value }\n ]\n });\n };\n return StateCondition;\n }(Condition));\n BABYLON.StateCondition = StateCondition;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.condition.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The action to be carried out following a trigger\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions\n */\n var Action = /** @class */ (function () {\n /**\n * Creates a new Action\n * @param triggerOptions the trigger, with or without parameters, for the action\n * @param condition an optional determinant of action\n */\n function Action(\n /** the trigger, with or without parameters, for the action */\n triggerOptions, condition) {\n this.triggerOptions = triggerOptions;\n /**\n * An event triggered prior to action being executed.\n */\n this.onBeforeExecuteObservable = new BABYLON.Observable();\n if (triggerOptions.parameter) {\n this.trigger = triggerOptions.trigger;\n this._triggerParameter = triggerOptions.parameter;\n }\n else {\n this.trigger = triggerOptions;\n }\n this._nextActiveAction = this;\n this._condition = condition;\n }\n /**\n * Internal only\n * @hidden\n */\n Action.prototype._prepare = function () {\n };\n /**\n * Gets the trigger parameters\n * @returns the trigger parameters\n */\n Action.prototype.getTriggerParameter = function () {\n return this._triggerParameter;\n };\n /**\n * Internal only - executes current action event\n * @hidden\n */\n Action.prototype._executeCurrent = function (evt) {\n if (this._nextActiveAction._condition) {\n var condition = this._nextActiveAction._condition;\n var currentRenderId = this._actionManager.getScene().getRenderId();\n // We cache the current evaluation for the current frame\n if (condition._evaluationId === currentRenderId) {\n if (!condition._currentResult) {\n return;\n }\n }\n else {\n condition._evaluationId = currentRenderId;\n if (!condition.isValid()) {\n condition._currentResult = false;\n return;\n }\n condition._currentResult = true;\n }\n }\n this.onBeforeExecuteObservable.notifyObservers(this);\n this._nextActiveAction.execute(evt);\n this.skipToNextActiveAction();\n };\n /**\n * Execute placeholder for child classes\n * @param evt optional action event\n */\n Action.prototype.execute = function (evt) {\n };\n /**\n * Skips to next active action\n */\n Action.prototype.skipToNextActiveAction = function () {\n if (this._nextActiveAction._child) {\n if (!this._nextActiveAction._child._actionManager) {\n this._nextActiveAction._child._actionManager = this._actionManager;\n }\n this._nextActiveAction = this._nextActiveAction._child;\n }\n else {\n this._nextActiveAction = this;\n }\n };\n /**\n * Adds action to chain of actions, may be a DoNothingAction\n * @param action defines the next action to execute\n * @returns The action passed in\n * @see https://www.babylonjs-playground.com/#1T30HR#0\n */\n Action.prototype.then = function (action) {\n this._child = action;\n action._actionManager = this._actionManager;\n action._prepare();\n return action;\n };\n /**\n * Internal only\n * @hidden\n */\n Action.prototype._getProperty = function (propertyPath) {\n return this._actionManager._getProperty(propertyPath);\n };\n /**\n * Internal only\n * @hidden\n */\n Action.prototype._getEffectiveTarget = function (target, propertyPath) {\n return this._actionManager._getEffectiveTarget(target, propertyPath);\n };\n /**\n * Serialize placeholder for child classes\n * @param parent of child\n * @returns the serialized object\n */\n Action.prototype.serialize = function (parent) {\n };\n /**\n * Internal only called by serialize\n * @hidden\n */\n Action.prototype._serialize = function (serializedAction, parent) {\n var serializationObject = {\n type: 1,\n children: [],\n name: serializedAction.name,\n properties: serializedAction.properties || []\n };\n // Serialize child\n if (this._child) {\n this._child.serialize(serializationObject);\n }\n // Check if \"this\" has a condition\n if (this._condition) {\n var serializedCondition = this._condition.serialize();\n serializedCondition.children.push(serializationObject);\n if (parent) {\n parent.children.push(serializedCondition);\n }\n return serializedCondition;\n }\n if (parent) {\n parent.children.push(serializationObject);\n }\n return serializationObject;\n };\n /**\n * Internal only\n * @hidden\n */\n Action._SerializeValueAsString = function (value) {\n if (typeof value === \"number\") {\n return value.toString();\n }\n if (typeof value === \"boolean\") {\n return value ? \"true\" : \"false\";\n }\n if (value instanceof BABYLON.Vector2) {\n return value.x + \", \" + value.y;\n }\n if (value instanceof BABYLON.Vector3) {\n return value.x + \", \" + value.y + \", \" + value.z;\n }\n if (value instanceof BABYLON.Color3) {\n return value.r + \", \" + value.g + \", \" + value.b;\n }\n if (value instanceof BABYLON.Color4) {\n return value.r + \", \" + value.g + \", \" + value.b + \", \" + value.a;\n }\n return value; // string\n };\n /**\n * Internal only\n * @hidden\n */\n Action._GetTargetProperty = function (target) {\n return {\n name: \"target\",\n targetType: target instanceof BABYLON.Mesh ? \"MeshProperties\"\n : target instanceof BABYLON.Light ? \"LightProperties\"\n : target instanceof BABYLON.Camera ? \"CameraProperties\"\n : \"SceneProperties\",\n value: target instanceof BABYLON.Scene ? \"Scene\" : target.name\n };\n };\n return Action;\n }());\n BABYLON.Action = Action;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.action.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * ActionEvent is the event being sent when an action is triggered.\n */\n var ActionEvent = /** @class */ (function () {\n /**\n * Creates a new ActionEvent\n * @param source The mesh or sprite that triggered the action\n * @param pointerX The X mouse cursor position at the time of the event\n * @param pointerY The Y mouse cursor position at the time of the event\n * @param meshUnderPointer The mesh that is currently pointed at (can be null)\n * @param sourceEvent the original (browser) event that triggered the ActionEvent\n * @param additionalData additional data for the event\n */\n function ActionEvent(\n /** The mesh or sprite that triggered the action */\n source, \n /** The X mouse cursor position at the time of the event */\n pointerX, \n /** The Y mouse cursor position at the time of the event */\n pointerY, \n /** The mesh that is currently pointed at (can be null) */\n meshUnderPointer, \n /** the original (browser) event that triggered the ActionEvent */\n sourceEvent, \n /** additional data for the event */\n additionalData) {\n this.source = source;\n this.pointerX = pointerX;\n this.pointerY = pointerY;\n this.meshUnderPointer = meshUnderPointer;\n this.sourceEvent = sourceEvent;\n this.additionalData = additionalData;\n }\n /**\n * Helper function to auto-create an ActionEvent from a source mesh.\n * @param source The source mesh that triggered the event\n * @param evt The original (browser) event\n * @param additionalData additional data for the event\n * @returns the new ActionEvent\n */\n ActionEvent.CreateNew = function (source, evt, additionalData) {\n var scene = source.getScene();\n return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);\n };\n /**\n * Helper function to auto-create an ActionEvent from a source sprite\n * @param source The source sprite that triggered the event\n * @param scene Scene associated with the sprite\n * @param evt The original (browser) event\n * @param additionalData additional data for the event\n * @returns the new ActionEvent\n */\n ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {\n return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);\n };\n /**\n * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew\n * @param scene the scene where the event occurred\n * @param evt The original (browser) event\n * @returns the new ActionEvent\n */\n ActionEvent.CreateNewFromScene = function (scene, evt) {\n return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);\n };\n /**\n * Helper function to auto-create an ActionEvent from a primitive\n * @param prim defines the target primitive\n * @param pointerPos defines the pointer position\n * @param evt The original (browser) event\n * @param additionalData additional data for the event\n * @returns the new ActionEvent\n */\n ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {\n return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);\n };\n return ActionEvent;\n }());\n BABYLON.ActionEvent = ActionEvent;\n /**\n * Action Manager manages all events to be triggered on a given mesh or the global scene.\n * A single scene can have many Action Managers to handle predefined actions on specific meshes.\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions\n */\n var ActionManager = /** @class */ (function () {\n /**\n * Creates a new action manager\n * @param scene defines the hosting scene\n */\n function ActionManager(scene) {\n // Members\n /** Gets the list of actions */\n this.actions = new Array();\n /** Gets the cursor to use when hovering items */\n this.hoverCursor = '';\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n scene.actionManagers.push(this);\n }\n Object.defineProperty(ActionManager, \"NothingTrigger\", {\n /**\n * Nothing\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._NothingTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnPickTrigger\", {\n /**\n * On pick\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnPickTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnLeftPickTrigger\", {\n /**\n * On left pick\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnLeftPickTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnRightPickTrigger\", {\n /**\n * On right pick\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnRightPickTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnCenterPickTrigger\", {\n /**\n * On center pick\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnCenterPickTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnPickDownTrigger\", {\n /**\n * On pick down\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnPickDownTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnDoublePickTrigger\", {\n /**\n * On double pick\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnDoublePickTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnPickUpTrigger\", {\n /**\n * On pick up\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnPickUpTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnPickOutTrigger\", {\n /**\n * On pick out.\n * This trigger will only be raised if you also declared a OnPickDown\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnPickOutTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnLongPressTrigger\", {\n /**\n * On long press\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnLongPressTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnPointerOverTrigger\", {\n /**\n * On pointer over\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnPointerOverTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnPointerOutTrigger\", {\n /**\n * On pointer out\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnPointerOutTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnEveryFrameTrigger\", {\n /**\n * On every frame\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnEveryFrameTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnIntersectionEnterTrigger\", {\n /**\n * On intersection enter\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnIntersectionEnterTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnIntersectionExitTrigger\", {\n /**\n * On intersection exit\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnIntersectionExitTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnKeyDownTrigger\", {\n /**\n * On key down\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnKeyDownTrigger;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"OnKeyUpTrigger\", {\n /**\n * On key up\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers\n */\n get: function () {\n return ActionManager._OnKeyUpTrigger;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n /**\n * Releases all associated resources\n */\n ActionManager.prototype.dispose = function () {\n var index = this._scene.actionManagers.indexOf(this);\n for (var i = 0; i < this.actions.length; i++) {\n var action = this.actions[i];\n ActionManager.Triggers[action.trigger]--;\n if (ActionManager.Triggers[action.trigger] === 0) {\n delete ActionManager.Triggers[action.trigger];\n }\n }\n if (index > -1) {\n this._scene.actionManagers.splice(index, 1);\n }\n };\n /**\n * Gets hosting scene\n * @returns the hosting scene\n */\n ActionManager.prototype.getScene = function () {\n return this._scene;\n };\n /**\n * Does this action manager handles actions of any of the given triggers\n * @param triggers defines the triggers to be tested\n * @return a boolean indicating whether one (or more) of the triggers is handled\n */\n ActionManager.prototype.hasSpecificTriggers = function (triggers) {\n for (var index = 0; index < this.actions.length; index++) {\n var action = this.actions[index];\n if (triggers.indexOf(action.trigger) > -1) {\n return true;\n }\n }\n return false;\n };\n /**\n * Does this action manager handles actions of a given trigger\n * @param trigger defines the trigger to be tested\n * @param parameterPredicate defines an optional predicate to filter triggers by parameter\n * @return whether the trigger is handled\n */\n ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {\n for (var index = 0; index < this.actions.length; index++) {\n var action = this.actions[index];\n if (action.trigger === trigger) {\n if (parameterPredicate) {\n if (parameterPredicate(action.getTriggerParameter())) {\n return true;\n }\n }\n else {\n return true;\n }\n }\n }\n return false;\n };\n Object.defineProperty(ActionManager.prototype, \"hasPointerTriggers\", {\n /**\n * Does this action manager has pointer triggers\n */\n get: function () {\n for (var index = 0; index < this.actions.length; index++) {\n var action = this.actions[index];\n if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {\n return true;\n }\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager.prototype, \"hasPickTriggers\", {\n /**\n * Does this action manager has pick triggers\n */\n get: function () {\n for (var index = 0; index < this.actions.length; index++) {\n var action = this.actions[index];\n if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {\n return true;\n }\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"HasTriggers\", {\n /**\n * Does exist one action manager with at least one trigger\n **/\n get: function () {\n for (var t in ActionManager.Triggers) {\n if (ActionManager.Triggers.hasOwnProperty(t)) {\n return true;\n }\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ActionManager, \"HasPickTriggers\", {\n /**\n * Does exist one action manager with at least one pick trigger\n **/\n get: function () {\n for (var t in ActionManager.Triggers) {\n if (ActionManager.Triggers.hasOwnProperty(t)) {\n var t_int = parseInt(t);\n if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {\n return true;\n }\n }\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Does exist one action manager that handles actions of a given trigger\n * @param trigger defines the trigger to be tested\n * @return a boolean indicating whether the trigger is handeled by at least one action manager\n **/\n ActionManager.HasSpecificTrigger = function (trigger) {\n for (var t in ActionManager.Triggers) {\n if (ActionManager.Triggers.hasOwnProperty(t)) {\n var t_int = parseInt(t);\n if (t_int === trigger) {\n return true;\n }\n }\n }\n return false;\n };\n /**\n * Registers an action to this action manager\n * @param action defines the action to be registered\n * @return the action amended (prepared) after registration\n */\n ActionManager.prototype.registerAction = function (action) {\n if (action.trigger === ActionManager.OnEveryFrameTrigger) {\n if (this.getScene().actionManager !== this) {\n BABYLON.Tools.Warn(\"OnEveryFrameTrigger can only be used with scene.actionManager\");\n return null;\n }\n }\n this.actions.push(action);\n if (ActionManager.Triggers[action.trigger]) {\n ActionManager.Triggers[action.trigger]++;\n }\n else {\n ActionManager.Triggers[action.trigger] = 1;\n }\n action._actionManager = this;\n action._prepare();\n return action;\n };\n /**\n * Unregisters an action to this action manager\n * @param action defines the action to be unregistered\n * @return a boolean indicating whether the action has been unregistered\n */\n ActionManager.prototype.unregisterAction = function (action) {\n var index = this.actions.indexOf(action);\n if (index !== -1) {\n this.actions.splice(index, 1);\n ActionManager.Triggers[action.trigger] -= 1;\n if (ActionManager.Triggers[action.trigger] === 0) {\n delete ActionManager.Triggers[action.trigger];\n }\n delete action._actionManager;\n return true;\n }\n return false;\n };\n /**\n * Process a specific trigger\n * @param trigger defines the trigger to process\n * @param evt defines the event details to be processed\n */\n ActionManager.prototype.processTrigger = function (trigger, evt) {\n for (var index = 0; index < this.actions.length; index++) {\n var action = this.actions[index];\n if (action.trigger === trigger) {\n if (evt) {\n if (trigger === ActionManager.OnKeyUpTrigger\n || trigger === ActionManager.OnKeyDownTrigger) {\n var parameter = action.getTriggerParameter();\n if (parameter && parameter !== evt.sourceEvent.keyCode) {\n if (!parameter.toLowerCase) {\n continue;\n }\n var lowerCase = parameter.toLowerCase();\n if (lowerCase !== evt.sourceEvent.key) {\n var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;\n var actualkey = String.fromCharCode(unicode).toLowerCase();\n if (actualkey !== lowerCase) {\n continue;\n }\n }\n }\n }\n }\n action._executeCurrent(evt);\n }\n }\n };\n /** @hidden */\n ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {\n var properties = propertyPath.split(\".\");\n for (var index = 0; index < properties.length - 1; index++) {\n target = target[properties[index]];\n }\n return target;\n };\n /** @hidden */\n ActionManager.prototype._getProperty = function (propertyPath) {\n var properties = propertyPath.split(\".\");\n return properties[properties.length - 1];\n };\n /**\n * Serialize this manager to a JSON object\n * @param name defines the property name to store this manager\n * @returns a JSON representation of this manager\n */\n ActionManager.prototype.serialize = function (name) {\n var root = {\n children: new Array(),\n name: name,\n type: 3,\n properties: new Array() // Empty for root but required\n };\n for (var i = 0; i < this.actions.length; i++) {\n var triggerObject = {\n type: 0,\n children: new Array(),\n name: ActionManager.GetTriggerName(this.actions[i].trigger),\n properties: new Array()\n };\n var triggerOptions = this.actions[i].triggerOptions;\n if (triggerOptions && typeof triggerOptions !== \"number\") {\n if (triggerOptions.parameter instanceof BABYLON.Node) {\n triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));\n }\n else {\n var parameter = {};\n BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, [\"mesh\"]);\n if (triggerOptions.parameter.mesh) {\n parameter._meshId = triggerOptions.parameter.mesh.id;\n }\n triggerObject.properties.push({ name: \"parameter\", targetType: null, value: parameter });\n }\n }\n // Serialize child action, recursively\n this.actions[i].serialize(triggerObject);\n // Add serialized trigger\n root.children.push(triggerObject);\n }\n return root;\n };\n /**\n * Creates a new ActionManager from a JSON data\n * @param parsedActions defines the JSON data to read from\n * @param object defines the hosting mesh\n * @param scene defines the hosting scene\n */\n ActionManager.Parse = function (parsedActions, object, scene) {\n var actionManager = new ActionManager(scene);\n if (object === null)\n scene.actionManager = actionManager;\n else\n object.actionManager = actionManager;\n // instanciate a new object\n var instanciate = function (name, params) {\n // TODO: We will need to find a solution for the next line when using commonjs / es6 .\n var newInstance = Object.create(BABYLON.Tools.Instantiate(\"BABYLON.\" + name).prototype);\n newInstance.constructor.apply(newInstance, params);\n return newInstance;\n };\n var parseParameter = function (name, value, target, propertyPath) {\n if (propertyPath === null) {\n // String, boolean or float\n var floatValue = parseFloat(value);\n if (value === \"true\" || value === \"false\")\n return value === \"true\";\n else\n return isNaN(floatValue) ? value : floatValue;\n }\n var effectiveTarget = propertyPath.split(\".\");\n var values = value.split(\",\");\n // Get effective Target\n for (var i = 0; i < effectiveTarget.length; i++) {\n target = target[effectiveTarget[i]];\n }\n // Return appropriate value with its type\n if (typeof (target) === \"boolean\")\n return values[0] === \"true\";\n if (typeof (target) === \"string\")\n return values[0];\n // Parameters with multiple values such as Vector3 etc.\n var split = new Array();\n for (var i = 0; i < values.length; i++)\n split.push(parseFloat(values[i]));\n if (target instanceof BABYLON.Vector3)\n return BABYLON.Vector3.FromArray(split);\n if (target instanceof BABYLON.Vector4)\n return BABYLON.Vector4.FromArray(split);\n if (target instanceof BABYLON.Color3)\n return BABYLON.Color3.FromArray(split);\n if (target instanceof BABYLON.Color4)\n return BABYLON.Color4.FromArray(split);\n return parseFloat(values[0]);\n };\n // traverse graph per trigger\n var traverse = function (parsedAction, trigger, condition, action, combineArray) {\n if (combineArray === void 0) { combineArray = null; }\n if (parsedAction.detached)\n return;\n var parameters = new Array();\n var target = null;\n var propertyPath = null;\n var combine = parsedAction.combine && parsedAction.combine.length > 0;\n // Parameters\n if (parsedAction.type === 2)\n parameters.push(actionManager);\n else\n parameters.push(trigger);\n if (combine) {\n var actions = new Array();\n for (var j = 0; j < parsedAction.combine.length; j++) {\n traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);\n }\n parameters.push(actions);\n }\n else {\n for (var i = 0; i < parsedAction.properties.length; i++) {\n var value = parsedAction.properties[i].value;\n var name = parsedAction.properties[i].name;\n var targetType = parsedAction.properties[i].targetType;\n if (name === \"target\")\n if (targetType !== null && targetType === \"SceneProperties\")\n value = target = scene;\n else\n value = target = scene.getNodeByName(value);\n else if (name === \"parent\")\n value = scene.getNodeByName(value);\n else if (name === \"sound\")\n value = scene.getSoundByName(value);\n else if (name !== \"propertyPath\") {\n if (parsedAction.type === 2 && name === \"operator\")\n value = BABYLON.ValueCondition[value];\n else\n value = parseParameter(name, value, target, name === \"value\" ? propertyPath : null);\n }\n else {\n propertyPath = value;\n }\n parameters.push(value);\n }\n }\n if (combineArray === null) {\n parameters.push(condition);\n }\n else {\n parameters.push(null);\n }\n // If interpolate value action\n if (parsedAction.name === \"InterpolateValueAction\") {\n var param = parameters[parameters.length - 2];\n parameters[parameters.length - 1] = param;\n parameters[parameters.length - 2] = condition;\n }\n // Action or condition(s) and not CombineAction\n var newAction = instanciate(parsedAction.name, parameters);\n if (newAction instanceof BABYLON.Condition && condition !== null) {\n var nothing = new BABYLON.DoNothingAction(trigger, condition);\n if (action)\n action.then(nothing);\n else\n actionManager.registerAction(nothing);\n action = nothing;\n }\n if (combineArray === null) {\n if (newAction instanceof BABYLON.Condition) {\n condition = newAction;\n newAction = action;\n }\n else {\n condition = null;\n if (action)\n action.then(newAction);\n else\n actionManager.registerAction(newAction);\n }\n }\n else {\n combineArray.push(newAction);\n }\n for (var i = 0; i < parsedAction.children.length; i++)\n traverse(parsedAction.children[i], trigger, condition, newAction, null);\n };\n // triggers\n for (var i = 0; i < parsedActions.children.length; i++) {\n var triggerParams;\n var trigger = parsedActions.children[i];\n if (trigger.properties.length > 0) {\n var param = trigger.properties[0].value;\n var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);\n if (value._meshId) {\n value.mesh = scene.getMeshByID(value._meshId);\n }\n triggerParams = { trigger: ActionManager[trigger.name], parameter: value };\n }\n else\n triggerParams = ActionManager[trigger.name];\n for (var j = 0; j < trigger.children.length; j++) {\n if (!trigger.detached)\n traverse(trigger.children[j], triggerParams, null, null);\n }\n }\n };\n /**\n * Get a trigger name by index\n * @param trigger defines the trigger index\n * @returns a trigger name\n */\n ActionManager.GetTriggerName = function (trigger) {\n switch (trigger) {\n case 0: return \"NothingTrigger\";\n case 1: return \"OnPickTrigger\";\n case 2: return \"OnLeftPickTrigger\";\n case 3: return \"OnRightPickTrigger\";\n case 4: return \"OnCenterPickTrigger\";\n case 5: return \"OnPickDownTrigger\";\n case 6: return \"OnPickUpTrigger\";\n case 7: return \"OnLongPressTrigger\";\n case 8: return \"OnPointerOverTrigger\";\n case 9: return \"OnPointerOutTrigger\";\n case 10: return \"OnEveryFrameTrigger\";\n case 11: return \"OnIntersectionEnterTrigger\";\n case 12: return \"OnIntersectionExitTrigger\";\n case 13: return \"OnKeyDownTrigger\";\n case 14: return \"OnKeyUpTrigger\";\n case 15: return \"OnPickOutTrigger\";\n default: return \"\";\n }\n };\n // Statics\n ActionManager._NothingTrigger = 0;\n ActionManager._OnPickTrigger = 1;\n ActionManager._OnLeftPickTrigger = 2;\n ActionManager._OnRightPickTrigger = 3;\n ActionManager._OnCenterPickTrigger = 4;\n ActionManager._OnPickDownTrigger = 5;\n ActionManager._OnDoublePickTrigger = 6;\n ActionManager._OnPickUpTrigger = 7;\n ActionManager._OnLongPressTrigger = 8;\n ActionManager._OnPointerOverTrigger = 9;\n ActionManager._OnPointerOutTrigger = 10;\n ActionManager._OnEveryFrameTrigger = 11;\n ActionManager._OnIntersectionEnterTrigger = 12;\n ActionManager._OnIntersectionExitTrigger = 13;\n ActionManager._OnKeyDownTrigger = 14;\n ActionManager._OnKeyUpTrigger = 15;\n ActionManager._OnPickOutTrigger = 16;\n /** Gets the list of active triggers */\n ActionManager.Triggers = {};\n return ActionManager;\n }());\n BABYLON.ActionManager = ActionManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.actionManager.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var InterpolateValueAction = /** @class */ (function (_super) {\n __extends(InterpolateValueAction, _super);\n function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {\n if (duration === void 0) { duration = 1000; }\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.propertyPath = propertyPath;\n _this.value = value;\n _this.duration = duration;\n _this.stopOtherAnimations = stopOtherAnimations;\n _this.onInterpolationDone = onInterpolationDone;\n _this.onInterpolationDoneObservable = new BABYLON.Observable();\n _this._target = _this._effectiveTarget = target;\n return _this;\n }\n InterpolateValueAction.prototype._prepare = function () {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n };\n InterpolateValueAction.prototype.execute = function () {\n var _this = this;\n var scene = this._actionManager.getScene();\n var keys = [\n {\n frame: 0,\n value: this._effectiveTarget[this._property]\n }, {\n frame: 100,\n value: this.value\n }\n ];\n var dataType;\n if (typeof this.value === \"number\") {\n dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;\n }\n else if (this.value instanceof BABYLON.Color3) {\n dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;\n }\n else if (this.value instanceof BABYLON.Vector3) {\n dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;\n }\n else if (this.value instanceof BABYLON.Matrix) {\n dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;\n }\n else if (this.value instanceof BABYLON.Quaternion) {\n dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;\n }\n else {\n BABYLON.Tools.Warn(\"InterpolateValueAction: Unsupported type (\" + typeof this.value + \")\");\n return;\n }\n var animation = new BABYLON.Animation(\"InterpolateValueAction\", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n animation.setKeys(keys);\n if (this.stopOtherAnimations) {\n scene.stopAnimation(this._effectiveTarget);\n }\n var wrapper = function () {\n _this.onInterpolationDoneObservable.notifyObservers(_this);\n if (_this.onInterpolationDone) {\n _this.onInterpolationDone();\n }\n };\n scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);\n };\n InterpolateValueAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"InterpolateValueAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: BABYLON.Action._SerializeValueAsString(this.value) },\n { name: \"duration\", value: BABYLON.Action._SerializeValueAsString(this.duration) },\n { name: \"stopOtherAnimations\", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }\n ]\n }, parent);\n };\n return InterpolateValueAction;\n }(BABYLON.Action));\n BABYLON.InterpolateValueAction = InterpolateValueAction;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.interpolateValueAction.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var SwitchBooleanAction = /** @class */ (function (_super) {\n __extends(SwitchBooleanAction, _super);\n function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.propertyPath = propertyPath;\n _this._target = _this._effectiveTarget = target;\n return _this;\n }\n SwitchBooleanAction.prototype._prepare = function () {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n };\n SwitchBooleanAction.prototype.execute = function () {\n this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];\n };\n SwitchBooleanAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"SwitchBooleanAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath }\n ]\n }, parent);\n };\n return SwitchBooleanAction;\n }(BABYLON.Action));\n BABYLON.SwitchBooleanAction = SwitchBooleanAction;\n var SetStateAction = /** @class */ (function (_super) {\n __extends(SetStateAction, _super);\n function SetStateAction(triggerOptions, target, value, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.value = value;\n _this._target = target;\n return _this;\n }\n SetStateAction.prototype.execute = function () {\n this._target.state = this.value;\n };\n SetStateAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"SetStateAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"value\", value: this.value }\n ]\n }, parent);\n };\n return SetStateAction;\n }(BABYLON.Action));\n BABYLON.SetStateAction = SetStateAction;\n var SetValueAction = /** @class */ (function (_super) {\n __extends(SetValueAction, _super);\n function SetValueAction(triggerOptions, target, propertyPath, value, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.propertyPath = propertyPath;\n _this.value = value;\n _this._target = _this._effectiveTarget = target;\n return _this;\n }\n SetValueAction.prototype._prepare = function () {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n };\n SetValueAction.prototype.execute = function () {\n this._effectiveTarget[this._property] = this.value;\n if (this._target.markAsDirty) {\n this._target.markAsDirty(this._property);\n }\n };\n SetValueAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"SetValueAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: BABYLON.Action._SerializeValueAsString(this.value) }\n ]\n }, parent);\n };\n return SetValueAction;\n }(BABYLON.Action));\n BABYLON.SetValueAction = SetValueAction;\n var IncrementValueAction = /** @class */ (function (_super) {\n __extends(IncrementValueAction, _super);\n function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.propertyPath = propertyPath;\n _this.value = value;\n _this._target = _this._effectiveTarget = target;\n return _this;\n }\n IncrementValueAction.prototype._prepare = function () {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n if (typeof this._effectiveTarget[this._property] !== \"number\") {\n BABYLON.Tools.Warn(\"Warning: IncrementValueAction can only be used with number values\");\n }\n };\n IncrementValueAction.prototype.execute = function () {\n this._effectiveTarget[this._property] += this.value;\n if (this._target.markAsDirty) {\n this._target.markAsDirty(this._property);\n }\n };\n IncrementValueAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"IncrementValueAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: BABYLON.Action._SerializeValueAsString(this.value) }\n ]\n }, parent);\n };\n return IncrementValueAction;\n }(BABYLON.Action));\n BABYLON.IncrementValueAction = IncrementValueAction;\n var PlayAnimationAction = /** @class */ (function (_super) {\n __extends(PlayAnimationAction, _super);\n function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.from = from;\n _this.to = to;\n _this.loop = loop;\n _this._target = target;\n return _this;\n }\n PlayAnimationAction.prototype._prepare = function () {\n };\n PlayAnimationAction.prototype.execute = function () {\n var scene = this._actionManager.getScene();\n scene.beginAnimation(this._target, this.from, this.to, this.loop);\n };\n PlayAnimationAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"PlayAnimationAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n { name: \"from\", value: String(this.from) },\n { name: \"to\", value: String(this.to) },\n { name: \"loop\", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }\n ]\n }, parent);\n };\n return PlayAnimationAction;\n }(BABYLON.Action));\n BABYLON.PlayAnimationAction = PlayAnimationAction;\n var StopAnimationAction = /** @class */ (function (_super) {\n __extends(StopAnimationAction, _super);\n function StopAnimationAction(triggerOptions, target, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this._target = target;\n return _this;\n }\n StopAnimationAction.prototype._prepare = function () {\n };\n StopAnimationAction.prototype.execute = function () {\n var scene = this._actionManager.getScene();\n scene.stopAnimation(this._target);\n };\n StopAnimationAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"StopAnimationAction\",\n properties: [BABYLON.Action._GetTargetProperty(this._target)]\n }, parent);\n };\n return StopAnimationAction;\n }(BABYLON.Action));\n BABYLON.StopAnimationAction = StopAnimationAction;\n var DoNothingAction = /** @class */ (function (_super) {\n __extends(DoNothingAction, _super);\n function DoNothingAction(triggerOptions, condition) {\n if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }\n return _super.call(this, triggerOptions, condition) || this;\n }\n DoNothingAction.prototype.execute = function () {\n };\n DoNothingAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"DoNothingAction\",\n properties: []\n }, parent);\n };\n return DoNothingAction;\n }(BABYLON.Action));\n BABYLON.DoNothingAction = DoNothingAction;\n var CombineAction = /** @class */ (function (_super) {\n __extends(CombineAction, _super);\n function CombineAction(triggerOptions, children, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.children = children;\n return _this;\n }\n CombineAction.prototype._prepare = function () {\n for (var index = 0; index < this.children.length; index++) {\n this.children[index]._actionManager = this._actionManager;\n this.children[index]._prepare();\n }\n };\n CombineAction.prototype.execute = function (evt) {\n for (var index = 0; index < this.children.length; index++) {\n this.children[index].execute(evt);\n }\n };\n CombineAction.prototype.serialize = function (parent) {\n var serializationObject = _super.prototype._serialize.call(this, {\n name: \"CombineAction\",\n properties: [],\n combine: []\n }, parent);\n for (var i = 0; i < this.children.length; i++) {\n serializationObject.combine.push(this.children[i].serialize(null));\n }\n return serializationObject;\n };\n return CombineAction;\n }(BABYLON.Action));\n BABYLON.CombineAction = CombineAction;\n var ExecuteCodeAction = /** @class */ (function (_super) {\n __extends(ExecuteCodeAction, _super);\n function ExecuteCodeAction(triggerOptions, func, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this.func = func;\n return _this;\n }\n ExecuteCodeAction.prototype.execute = function (evt) {\n this.func(evt);\n };\n return ExecuteCodeAction;\n }(BABYLON.Action));\n BABYLON.ExecuteCodeAction = ExecuteCodeAction;\n var SetParentAction = /** @class */ (function (_super) {\n __extends(SetParentAction, _super);\n function SetParentAction(triggerOptions, target, parent, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this._target = target;\n _this._parent = parent;\n return _this;\n }\n SetParentAction.prototype._prepare = function () {\n };\n SetParentAction.prototype.execute = function () {\n if (this._target.parent === this._parent) {\n return;\n }\n var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();\n invertParentWorldMatrix.invert();\n this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);\n this._target.parent = this._parent;\n };\n SetParentAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"SetParentAction\",\n properties: [\n BABYLON.Action._GetTargetProperty(this._target),\n BABYLON.Action._GetTargetProperty(this._parent),\n ]\n }, parent);\n };\n return SetParentAction;\n }(BABYLON.Action));\n BABYLON.SetParentAction = SetParentAction;\n var PlaySoundAction = /** @class */ (function (_super) {\n __extends(PlaySoundAction, _super);\n function PlaySoundAction(triggerOptions, sound, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this._sound = sound;\n return _this;\n }\n PlaySoundAction.prototype._prepare = function () {\n };\n PlaySoundAction.prototype.execute = function () {\n if (this._sound !== undefined)\n this._sound.play();\n };\n PlaySoundAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"PlaySoundAction\",\n properties: [{ name: \"sound\", value: this._sound.name }]\n }, parent);\n };\n return PlaySoundAction;\n }(BABYLON.Action));\n BABYLON.PlaySoundAction = PlaySoundAction;\n var StopSoundAction = /** @class */ (function (_super) {\n __extends(StopSoundAction, _super);\n function StopSoundAction(triggerOptions, sound, condition) {\n var _this = _super.call(this, triggerOptions, condition) || this;\n _this._sound = sound;\n return _this;\n }\n StopSoundAction.prototype._prepare = function () {\n };\n StopSoundAction.prototype.execute = function () {\n if (this._sound !== undefined)\n this._sound.stop();\n };\n StopSoundAction.prototype.serialize = function (parent) {\n return _super.prototype._serialize.call(this, {\n name: \"StopSoundAction\",\n properties: [{ name: \"sound\", value: this._sound.name }]\n }, parent);\n };\n return StopSoundAction;\n }(BABYLON.Action));\n BABYLON.StopSoundAction = StopSoundAction;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.directActions.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var SpriteManager = /** @class */ (function () {\n function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {\n if (epsilon === void 0) { epsilon = 0.01; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n this.name = name;\n this.sprites = new Array();\n this.renderingGroupId = 0;\n this.layerMask = 0x0FFFFFFF;\n this.fogEnabled = true;\n this.isPickable = false;\n /**\n * An event triggered when the manager is disposed.\n */\n this.onDisposeObservable = new BABYLON.Observable();\n this._vertexBuffers = {};\n this._capacity = capacity;\n this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);\n this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n if (cellSize.width && cellSize.height) {\n this.cellWidth = cellSize.width;\n this.cellHeight = cellSize.height;\n }\n else if (cellSize !== undefined) {\n this.cellWidth = cellSize;\n this.cellHeight = cellSize;\n }\n else {\n return;\n }\n this._epsilon = epsilon;\n this._scene = scene;\n this._scene.spriteManagers.push(this);\n var indices = [];\n var index = 0;\n for (var count = 0; count < capacity; count++) {\n indices.push(index);\n indices.push(index + 1);\n indices.push(index + 2);\n indices.push(index);\n indices.push(index + 2);\n indices.push(index + 3);\n index += 4;\n }\n this._indexBuffer = scene.getEngine().createIndexBuffer(indices);\n // VBO\n // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)\n this._vertexData = new Float32Array(capacity * 16 * 4);\n this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);\n var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);\n var options = this._buffer.createVertexBuffer(\"options\", 4, 4);\n var cellInfo = this._buffer.createVertexBuffer(\"cellInfo\", 8, 4);\n var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;\n this._vertexBuffers[\"options\"] = options;\n this._vertexBuffers[\"cellInfo\"] = cellInfo;\n this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;\n // Effects\n this._effectBase = this._scene.getEngine().createEffect(\"sprites\", [BABYLON.VertexBuffer.PositionKind, \"options\", \"cellInfo\", BABYLON.VertexBuffer.ColorKind], [\"view\", \"projection\", \"textureInfos\", \"alphaTest\"], [\"diffuseSampler\"], \"\");\n this._effectFog = this._scene.getEngine().createEffect(\"sprites\", [BABYLON.VertexBuffer.PositionKind, \"options\", \"cellInfo\", BABYLON.VertexBuffer.ColorKind], [\"view\", \"projection\", \"textureInfos\", \"alphaTest\", \"vFogInfos\", \"vFogColor\"], [\"diffuseSampler\"], \"#define FOG\");\n }\n Object.defineProperty(SpriteManager.prototype, \"onDispose\", {\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SpriteManager.prototype, \"texture\", {\n get: function () {\n return this._spriteTexture;\n },\n set: function (value) {\n this._spriteTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {\n var arrayOffset = index * 16;\n if (offsetX === 0)\n offsetX = this._epsilon;\n else if (offsetX === 1)\n offsetX = 1 - this._epsilon;\n if (offsetY === 0)\n offsetY = this._epsilon;\n else if (offsetY === 1)\n offsetY = 1 - this._epsilon;\n this._vertexData[arrayOffset] = sprite.position.x;\n this._vertexData[arrayOffset + 1] = sprite.position.y;\n this._vertexData[arrayOffset + 2] = sprite.position.z;\n this._vertexData[arrayOffset + 3] = sprite.angle;\n this._vertexData[arrayOffset + 4] = sprite.width;\n this._vertexData[arrayOffset + 5] = sprite.height;\n this._vertexData[arrayOffset + 6] = offsetX;\n this._vertexData[arrayOffset + 7] = offsetY;\n this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;\n this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;\n var offset = (sprite.cellIndex / rowSize) >> 0;\n this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;\n this._vertexData[arrayOffset + 11] = offset;\n // Color\n this._vertexData[arrayOffset + 12] = sprite.color.r;\n this._vertexData[arrayOffset + 13] = sprite.color.g;\n this._vertexData[arrayOffset + 14] = sprite.color.b;\n this._vertexData[arrayOffset + 15] = sprite.color.a;\n };\n SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {\n var count = Math.min(this._capacity, this.sprites.length);\n var min = BABYLON.Vector3.Zero();\n var max = BABYLON.Vector3.Zero();\n var distance = Number.MAX_VALUE;\n var currentSprite = null;\n var cameraSpacePosition = BABYLON.Vector3.Zero();\n var cameraView = camera.getViewMatrix();\n for (var index = 0; index < count; index++) {\n var sprite = this.sprites[index];\n if (!sprite) {\n continue;\n }\n if (predicate) {\n if (!predicate(sprite)) {\n continue;\n }\n }\n else if (!sprite.isPickable) {\n continue;\n }\n BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);\n min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);\n max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);\n if (ray.intersectsBoxMinMax(min, max)) {\n var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);\n if (distance > currentDistance) {\n distance = currentDistance;\n currentSprite = sprite;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n if (currentSprite) {\n var result = new BABYLON.PickingInfo();\n result.hit = true;\n result.pickedSprite = currentSprite;\n result.distance = distance;\n return result;\n }\n return null;\n };\n SpriteManager.prototype.render = function () {\n // Check\n if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())\n return;\n var engine = this._scene.getEngine();\n var baseSize = this._spriteTexture.getBaseSize();\n // Sprites\n var deltaTime = engine.getDeltaTime();\n var max = Math.min(this._capacity, this.sprites.length);\n var rowSize = baseSize.width / this.cellWidth;\n var offset = 0;\n for (var index = 0; index < max; index++) {\n var sprite = this.sprites[index];\n if (!sprite || !sprite.isVisible) {\n continue;\n }\n sprite._animate(deltaTime);\n this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);\n this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);\n this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);\n this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);\n }\n this._buffer.update(this._vertexData);\n // Render\n var effect = this._effectBase;\n if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {\n effect = this._effectFog;\n }\n engine.enableEffect(effect);\n var viewMatrix = this._scene.getViewMatrix();\n effect.setTexture(\"diffuseSampler\", this._spriteTexture);\n effect.setMatrix(\"view\", viewMatrix);\n effect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n effect.setFloat2(\"textureInfos\", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);\n // Fog\n if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {\n effect.setFloat4(\"vFogInfos\", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);\n effect.setColor3(\"vFogColor\", this._scene.fogColor);\n }\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n // Draw order\n engine.setDepthFunctionToLessOrEqual();\n effect.setBool(\"alphaTest\", true);\n engine.setColorWrite(false);\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);\n engine.setColorWrite(true);\n effect.setBool(\"alphaTest\", false);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n };\n SpriteManager.prototype.dispose = function () {\n if (this._buffer) {\n this._buffer.dispose();\n this._buffer = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n if (this._spriteTexture) {\n this._spriteTexture.dispose();\n this._spriteTexture = null;\n }\n // Remove from scene\n var index = this._scene.spriteManagers.indexOf(this);\n this._scene.spriteManagers.splice(index, 1);\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n };\n return SpriteManager;\n }());\n BABYLON.SpriteManager = SpriteManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.spriteManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Sprite = /** @class */ (function () {\n function Sprite(name, manager) {\n this.name = name;\n this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n this.width = 1.0;\n this.height = 1.0;\n this.angle = 0;\n this.cellIndex = 0;\n this.invertU = 0;\n this.invertV = 0;\n this.animations = new Array();\n this.isPickable = false;\n this._animationStarted = false;\n this._loopAnimation = false;\n this._fromIndex = 0;\n this._toIndex = 0;\n this._delay = 0;\n this._direction = 1;\n this._time = 0;\n /**\n * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true\n */\n this.isVisible = true;\n this._manager = manager;\n this._manager.sprites.push(this);\n this.position = BABYLON.Vector3.Zero();\n }\n Object.defineProperty(Sprite.prototype, \"size\", {\n get: function () {\n return this.width;\n },\n set: function (value) {\n this.width = value;\n this.height = value;\n },\n enumerable: true,\n configurable: true\n });\n Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {\n this._fromIndex = from;\n this._toIndex = to;\n this._loopAnimation = loop;\n this._delay = delay;\n this._animationStarted = true;\n this._direction = from < to ? 1 : -1;\n this.cellIndex = from;\n this._time = 0;\n this._onAnimationEnd = onAnimationEnd;\n };\n Sprite.prototype.stopAnimation = function () {\n this._animationStarted = false;\n };\n Sprite.prototype._animate = function (deltaTime) {\n if (!this._animationStarted)\n return;\n this._time += deltaTime;\n if (this._time > this._delay) {\n this._time = this._time % this._delay;\n this.cellIndex += this._direction;\n if (this.cellIndex > this._toIndex) {\n if (this._loopAnimation) {\n this.cellIndex = this._fromIndex;\n }\n else {\n this.cellIndex = this._toIndex;\n this._animationStarted = false;\n if (this._onAnimationEnd) {\n this._onAnimationEnd();\n }\n if (this.disposeWhenFinishedAnimating) {\n this.dispose();\n }\n }\n }\n }\n };\n Sprite.prototype.dispose = function () {\n for (var i = 0; i < this._manager.sprites.length; i++) {\n if (this._manager.sprites[i] == this) {\n this._manager.sprites.splice(i, 1);\n }\n }\n };\n return Sprite;\n }());\n BABYLON.Sprite = Sprite;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sprite.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var IntersectionInfo = /** @class */ (function () {\n function IntersectionInfo(bu, bv, distance) {\n this.bu = bu;\n this.bv = bv;\n this.distance = distance;\n this.faceId = 0;\n this.subMeshId = 0;\n }\n return IntersectionInfo;\n }());\n BABYLON.IntersectionInfo = IntersectionInfo;\n /**\n * Information about the result of picking within a scene\n * See https://doc.babylonjs.com/babylon101/picking_collisions\n */\n var PickingInfo = /** @class */ (function () {\n function PickingInfo() {\n /**\n * If the pick collided with an object\n */\n this.hit = false;\n /**\n * Distance away where the pick collided\n */\n this.distance = 0;\n /**\n * The location of pick collision\n */\n this.pickedPoint = null;\n /**\n * The mesh corrisponding the the pick collision\n */\n this.pickedMesh = null;\n /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/\n this.bu = 0;\n /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/\n this.bv = 0;\n /** The id of the face on the mesh that was picked */\n this.faceId = -1;\n /** Id of the the submesh that was picked */\n this.subMeshId = 0;\n /** If a sprite was picked, this will be the sprite the pick collided with */\n this.pickedSprite = null;\n /**\n * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.\n */\n this.originMesh = null;\n /**\n * The ray that was used to perform the picking.\n */\n this.ray = null;\n }\n /**\n * Gets the normal corrispodning to the face the pick collided with\n * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)\n * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map\n * @returns The normal corrispodning to the face the pick collided with\n */\n PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {\n if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }\n if (useVerticesNormals === void 0) { useVerticesNormals = true; }\n if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n return null;\n }\n var indices = this.pickedMesh.getIndices();\n if (!indices) {\n return null;\n }\n var result;\n if (useVerticesNormals) {\n var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);\n var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);\n var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);\n normal0 = normal0.scale(this.bu);\n normal1 = normal1.scale(this.bv);\n normal2 = normal2.scale(1.0 - this.bu - this.bv);\n result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);\n }\n else {\n var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);\n var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);\n var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);\n var p1p2 = vertex1.subtract(vertex2);\n var p3p2 = vertex3.subtract(vertex2);\n result = BABYLON.Vector3.Cross(p1p2, p3p2);\n }\n if (useWorldCoordinates) {\n var wm = this.pickedMesh.getWorldMatrix();\n if (this.pickedMesh.nonUniformScaling) {\n BABYLON.Tmp.Matrix[0].copyFrom(wm);\n wm = BABYLON.Tmp.Matrix[0];\n wm.setTranslationFromFloats(0, 0, 0);\n wm.invert();\n wm.transposeToRef(BABYLON.Tmp.Matrix[1]);\n wm = BABYLON.Tmp.Matrix[1];\n }\n result = BABYLON.Vector3.TransformNormal(result, wm);\n }\n result.normalize();\n return result;\n };\n /**\n * Gets the texture coordinates of where the pick occured\n * @returns the vector containing the coordnates of the texture\n */\n PickingInfo.prototype.getTextureCoordinates = function () {\n if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n return null;\n }\n var indices = this.pickedMesh.getIndices();\n if (!indices) {\n return null;\n }\n var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);\n if (!uvs) {\n return null;\n }\n var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);\n var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);\n var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);\n uv0 = uv0.scale(1.0 - this.bu - this.bv);\n uv1 = uv1.scale(this.bu);\n uv2 = uv2.scale(this.bv);\n return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);\n };\n return PickingInfo;\n }());\n BABYLON.PickingInfo = PickingInfo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pickingInfo.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Ray = /** @class */ (function () {\n function Ray(origin, direction, length) {\n if (length === void 0) { length = Number.MAX_VALUE; }\n this.origin = origin;\n this.direction = direction;\n this.length = length;\n }\n // Methods\n Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {\n var d = 0.0;\n var maxValue = Number.MAX_VALUE;\n var inv;\n var min;\n var max;\n var temp;\n if (Math.abs(this.direction.x) < 0.0000001) {\n if (this.origin.x < minimum.x || this.origin.x > maximum.x) {\n return false;\n }\n }\n else {\n inv = 1.0 / this.direction.x;\n min = (minimum.x - this.origin.x) * inv;\n max = (maximum.x - this.origin.x) * inv;\n if (max === -Infinity) {\n max = Infinity;\n }\n if (min > max) {\n temp = min;\n min = max;\n max = temp;\n }\n d = Math.max(min, d);\n maxValue = Math.min(max, maxValue);\n if (d > maxValue) {\n return false;\n }\n }\n if (Math.abs(this.direction.y) < 0.0000001) {\n if (this.origin.y < minimum.y || this.origin.y > maximum.y) {\n return false;\n }\n }\n else {\n inv = 1.0 / this.direction.y;\n min = (minimum.y - this.origin.y) * inv;\n max = (maximum.y - this.origin.y) * inv;\n if (max === -Infinity) {\n max = Infinity;\n }\n if (min > max) {\n temp = min;\n min = max;\n max = temp;\n }\n d = Math.max(min, d);\n maxValue = Math.min(max, maxValue);\n if (d > maxValue) {\n return false;\n }\n }\n if (Math.abs(this.direction.z) < 0.0000001) {\n if (this.origin.z < minimum.z || this.origin.z > maximum.z) {\n return false;\n }\n }\n else {\n inv = 1.0 / this.direction.z;\n min = (minimum.z - this.origin.z) * inv;\n max = (maximum.z - this.origin.z) * inv;\n if (max === -Infinity) {\n max = Infinity;\n }\n if (min > max) {\n temp = min;\n min = max;\n max = temp;\n }\n d = Math.max(min, d);\n maxValue = Math.min(max, maxValue);\n if (d > maxValue) {\n return false;\n }\n }\n return true;\n };\n Ray.prototype.intersectsBox = function (box) {\n return this.intersectsBoxMinMax(box.minimum, box.maximum);\n };\n Ray.prototype.intersectsSphere = function (sphere) {\n var x = sphere.center.x - this.origin.x;\n var y = sphere.center.y - this.origin.y;\n var z = sphere.center.z - this.origin.z;\n var pyth = (x * x) + (y * y) + (z * z);\n var rr = sphere.radius * sphere.radius;\n if (pyth <= rr) {\n return true;\n }\n var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);\n if (dot < 0.0) {\n return false;\n }\n var temp = pyth - (dot * dot);\n return temp <= rr;\n };\n Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {\n if (!this._edge1) {\n this._edge1 = BABYLON.Vector3.Zero();\n this._edge2 = BABYLON.Vector3.Zero();\n this._pvec = BABYLON.Vector3.Zero();\n this._tvec = BABYLON.Vector3.Zero();\n this._qvec = BABYLON.Vector3.Zero();\n }\n vertex1.subtractToRef(vertex0, this._edge1);\n vertex2.subtractToRef(vertex0, this._edge2);\n BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);\n var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);\n if (det === 0) {\n return null;\n }\n var invdet = 1 / det;\n this.origin.subtractToRef(vertex0, this._tvec);\n var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;\n if (bu < 0 || bu > 1.0) {\n return null;\n }\n BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);\n var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;\n if (bv < 0 || bu + bv > 1.0) {\n return null;\n }\n //check if the distance is longer than the predefined length.\n var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;\n if (distance > this.length) {\n return null;\n }\n return new BABYLON.IntersectionInfo(bu, bv, distance);\n };\n Ray.prototype.intersectsPlane = function (plane) {\n var distance;\n var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);\n if (Math.abs(result1) < 9.99999997475243E-07) {\n return null;\n }\n else {\n var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);\n distance = (-plane.d - result2) / result1;\n if (distance < 0.0) {\n if (distance < -9.99999997475243E-07) {\n return null;\n }\n else {\n return 0;\n }\n }\n return distance;\n }\n };\n Ray.prototype.intersectsMesh = function (mesh, fastCheck) {\n var tm = BABYLON.Tmp.Matrix[0];\n mesh.getWorldMatrix().invertToRef(tm);\n if (this._tmpRay) {\n Ray.TransformToRef(this, tm, this._tmpRay);\n }\n else {\n this._tmpRay = Ray.Transform(this, tm);\n }\n return mesh.intersects(this._tmpRay, fastCheck);\n };\n Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {\n if (results) {\n results.length = 0;\n }\n else {\n results = [];\n }\n for (var i = 0; i < meshes.length; i++) {\n var pickInfo = this.intersectsMesh(meshes[i], fastCheck);\n if (pickInfo.hit) {\n results.push(pickInfo);\n }\n }\n results.sort(this._comparePickingInfo);\n return results;\n };\n Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {\n if (pickingInfoA.distance < pickingInfoB.distance) {\n return -1;\n }\n else if (pickingInfoA.distance > pickingInfoB.distance) {\n return 1;\n }\n else {\n return 0;\n }\n };\n /**\n * Intersection test between the ray and a given segment whithin a given tolerance (threshold)\n * @param sega the first point of the segment to test the intersection against\n * @param segb the second point of the segment to test the intersection against\n * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful\n * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection\n */\n Ray.prototype.intersectionSegment = function (sega, segb, threshold) {\n var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));\n var u = segb.subtract(sega);\n var v = rsegb.subtract(this.origin);\n var w = sega.subtract(this.origin);\n var a = BABYLON.Vector3.Dot(u, u); // always >= 0\n var b = BABYLON.Vector3.Dot(u, v);\n var c = BABYLON.Vector3.Dot(v, v); // always >= 0\n var d = BABYLON.Vector3.Dot(u, w);\n var e = BABYLON.Vector3.Dot(v, w);\n var D = a * c - b * b; // always >= 0\n var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0\n var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0\n // compute the line parameters of the two closest points\n if (D < Ray.smallnum) { // the lines are almost parallel\n sN = 0.0; // force using point P0 on segment S1\n sD = 1.0; // to prevent possible division by 0.0 later\n tN = e;\n tD = c;\n }\n else { // get the closest points on the infinite lines\n sN = (b * e - c * d);\n tN = (a * e - b * d);\n if (sN < 0.0) { // sc < 0 => the s=0 edge is visible\n sN = 0.0;\n tN = e;\n tD = c;\n }\n else if (sN > sD) { // sc > 1 => the s=1 edge is visible\n sN = sD;\n tN = e + b;\n tD = c;\n }\n }\n if (tN < 0.0) { // tc < 0 => the t=0 edge is visible\n tN = 0.0;\n // recompute sc for this edge\n if (-d < 0.0) {\n sN = 0.0;\n }\n else if (-d > a)\n sN = sD;\n else {\n sN = -d;\n sD = a;\n }\n }\n else if (tN > tD) { // tc > 1 => the t=1 edge is visible\n tN = tD;\n // recompute sc for this edge\n if ((-d + b) < 0.0) {\n sN = 0;\n }\n else if ((-d + b) > a) {\n sN = sD;\n }\n else {\n sN = (-d + b);\n sD = a;\n }\n }\n // finally do the division to get sc and tc\n sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);\n tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);\n // get the difference of the two closest points\n var qtc = v.multiplyByFloats(tc, tc, tc);\n var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)\n var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result\n if (isIntersected) {\n return qtc.length();\n }\n return -1;\n };\n Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {\n BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);\n BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);\n BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);\n this.direction.normalize();\n return this;\n };\n // Statics\n Ray.Zero = function () {\n return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());\n };\n Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {\n var result = Ray.Zero();\n return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);\n };\n /**\n * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be\n * transformed to the given world matrix.\n * @param origin The origin point\n * @param end The end point\n * @param world a matrix to transform the ray to. Default is the identity matrix.\n */\n Ray.CreateNewFromTo = function (origin, end, world) {\n if (world === void 0) { world = BABYLON.Matrix.Identity(); }\n var direction = end.subtract(origin);\n var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));\n direction.normalize();\n return Ray.Transform(new Ray(origin, direction, length), world);\n };\n Ray.Transform = function (ray, matrix) {\n var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));\n Ray.TransformToRef(ray, matrix, result);\n return result;\n };\n Ray.TransformToRef = function (ray, matrix, result) {\n BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);\n BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);\n result.length = ray.length;\n var dir = result.direction;\n var len = dir.length();\n if (!(len === 0 || len === 1)) {\n var num = 1.0 / len;\n dir.x *= num;\n dir.y *= num;\n dir.z *= num;\n result.length *= len;\n }\n };\n Ray.smallnum = 0.00000001;\n Ray.rayl = 10e8;\n return Ray;\n }());\n BABYLON.Ray = Ray;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.ray.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {\n if (boxMin.x > sphereCenter.x + sphereRadius)\n return false;\n if (sphereCenter.x - sphereRadius > boxMax.x)\n return false;\n if (boxMin.y > sphereCenter.y + sphereRadius)\n return false;\n if (sphereCenter.y - sphereRadius > boxMax.y)\n return false;\n if (boxMin.z > sphereCenter.z + sphereRadius)\n return false;\n if (sphereCenter.z - sphereRadius > boxMax.z)\n return false;\n return true;\n };\n var getLowestRoot = (function () {\n var result = { root: 0, found: false };\n return function (a, b, c, maxR) {\n result.root = 0;\n result.found = false;\n var determinant = b * b - 4.0 * a * c;\n if (determinant < 0)\n return result;\n var sqrtD = Math.sqrt(determinant);\n var r1 = (-b - sqrtD) / (2.0 * a);\n var r2 = (-b + sqrtD) / (2.0 * a);\n if (r1 > r2) {\n var temp = r2;\n r2 = r1;\n r1 = temp;\n }\n if (r1 > 0 && r1 < maxR) {\n result.root = r1;\n result.found = true;\n return result;\n }\n if (r2 > 0 && r2 < maxR) {\n result.root = r2;\n result.found = true;\n return result;\n }\n return result;\n };\n })();\n var Collider = /** @class */ (function () {\n function Collider() {\n this._collisionPoint = BABYLON.Vector3.Zero();\n this._planeIntersectionPoint = BABYLON.Vector3.Zero();\n this._tempVector = BABYLON.Vector3.Zero();\n this._tempVector2 = BABYLON.Vector3.Zero();\n this._tempVector3 = BABYLON.Vector3.Zero();\n this._tempVector4 = BABYLON.Vector3.Zero();\n this._edge = BABYLON.Vector3.Zero();\n this._baseToVertex = BABYLON.Vector3.Zero();\n this._destinationPoint = BABYLON.Vector3.Zero();\n this._slidePlaneNormal = BABYLON.Vector3.Zero();\n this._displacementVector = BABYLON.Vector3.Zero();\n this._radius = BABYLON.Vector3.One();\n this._retry = 0;\n this._basePointWorld = BABYLON.Vector3.Zero();\n this._velocityWorld = BABYLON.Vector3.Zero();\n this._normalizedVelocity = BABYLON.Vector3.Zero();\n this._collisionMask = -1;\n }\n Object.defineProperty(Collider.prototype, \"collisionMask\", {\n get: function () {\n return this._collisionMask;\n },\n set: function (mask) {\n this._collisionMask = !isNaN(mask) ? mask : -1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Collider.prototype, \"slidePlaneNormal\", {\n /**\n * Gets the plane normal used to compute the sliding response (in local space)\n */\n get: function () {\n return this._slidePlaneNormal;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n Collider.prototype._initialize = function (source, dir, e) {\n this._velocity = dir;\n BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);\n this._basePoint = source;\n source.multiplyToRef(this._radius, this._basePointWorld);\n dir.multiplyToRef(this._radius, this._velocityWorld);\n this._velocityWorldLength = this._velocityWorld.length();\n this._epsilon = e;\n this.collisionFound = false;\n };\n Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {\n pa.subtractToRef(point, this._tempVector);\n pb.subtractToRef(point, this._tempVector2);\n BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);\n var d = BABYLON.Vector3.Dot(this._tempVector4, n);\n if (d < 0)\n return false;\n pc.subtractToRef(point, this._tempVector3);\n BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);\n d = BABYLON.Vector3.Dot(this._tempVector4, n);\n if (d < 0)\n return false;\n BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);\n d = BABYLON.Vector3.Dot(this._tempVector4, n);\n return d >= 0;\n };\n Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {\n var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);\n var max = Math.max(this._radius.x, this._radius.y, this._radius.z);\n if (distance > this._velocityWorldLength + max + sphereRadius) {\n return false;\n }\n if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))\n return false;\n return true;\n };\n Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {\n var t0;\n var embeddedInPlane = false;\n //defensive programming, actually not needed.\n if (!trianglePlaneArray) {\n trianglePlaneArray = [];\n }\n if (!trianglePlaneArray[faceIndex]) {\n trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);\n trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);\n }\n var trianglePlane = trianglePlaneArray[faceIndex];\n if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))\n return;\n var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);\n var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);\n if (normalDotVelocity == 0) {\n if (Math.abs(signedDistToTrianglePlane) >= 1.0)\n return;\n embeddedInPlane = true;\n t0 = 0;\n }\n else {\n t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;\n var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;\n if (t0 > t1) {\n var temp = t1;\n t1 = t0;\n t0 = temp;\n }\n if (t0 > 1.0 || t1 < 0.0)\n return;\n if (t0 < 0)\n t0 = 0;\n if (t0 > 1.0)\n t0 = 1.0;\n }\n this._collisionPoint.copyFromFloats(0, 0, 0);\n var found = false;\n var t = 1.0;\n if (!embeddedInPlane) {\n this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);\n this._velocity.scaleToRef(t0, this._tempVector);\n this._planeIntersectionPoint.addInPlace(this._tempVector);\n if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {\n found = true;\n t = t0;\n this._collisionPoint.copyFrom(this._planeIntersectionPoint);\n }\n }\n if (!found) {\n var velocitySquaredLength = this._velocity.lengthSquared();\n var a = velocitySquaredLength;\n this._basePoint.subtractToRef(p1, this._tempVector);\n var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));\n var c = this._tempVector.lengthSquared() - 1.0;\n var lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n t = lowestRoot.root;\n found = true;\n this._collisionPoint.copyFrom(p1);\n }\n this._basePoint.subtractToRef(p2, this._tempVector);\n b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));\n c = this._tempVector.lengthSquared() - 1.0;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n t = lowestRoot.root;\n found = true;\n this._collisionPoint.copyFrom(p2);\n }\n this._basePoint.subtractToRef(p3, this._tempVector);\n b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));\n c = this._tempVector.lengthSquared() - 1.0;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n t = lowestRoot.root;\n found = true;\n this._collisionPoint.copyFrom(p3);\n }\n p2.subtractToRef(p1, this._edge);\n p1.subtractToRef(this._basePoint, this._baseToVertex);\n var edgeSquaredLength = this._edge.lengthSquared();\n var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);\n var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);\n a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;\n b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;\n c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;\n if (f >= 0.0 && f <= 1.0) {\n t = lowestRoot.root;\n found = true;\n this._edge.scaleInPlace(f);\n p1.addToRef(this._edge, this._collisionPoint);\n }\n }\n p3.subtractToRef(p2, this._edge);\n p2.subtractToRef(this._basePoint, this._baseToVertex);\n edgeSquaredLength = this._edge.lengthSquared();\n edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);\n edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);\n a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;\n b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;\n c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;\n if (f >= 0.0 && f <= 1.0) {\n t = lowestRoot.root;\n found = true;\n this._edge.scaleInPlace(f);\n p2.addToRef(this._edge, this._collisionPoint);\n }\n }\n p1.subtractToRef(p3, this._edge);\n p3.subtractToRef(this._basePoint, this._baseToVertex);\n edgeSquaredLength = this._edge.lengthSquared();\n edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);\n edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);\n a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;\n b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;\n c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;\n if (f >= 0.0 && f <= 1.0) {\n t = lowestRoot.root;\n found = true;\n this._edge.scaleInPlace(f);\n p3.addToRef(this._edge, this._collisionPoint);\n }\n }\n }\n if (found) {\n var distToCollision = t * this._velocity.length();\n if (!this.collisionFound || distToCollision < this._nearestDistance) {\n if (!this.intersectionPoint) {\n this.intersectionPoint = this._collisionPoint.clone();\n }\n else {\n this.intersectionPoint.copyFrom(this._collisionPoint);\n }\n this._nearestDistance = distToCollision;\n this.collisionFound = true;\n }\n }\n };\n Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {\n for (var i = indexStart; i < indexEnd; i += 3) {\n var p1 = pts[indices[i] - decal];\n var p2 = pts[indices[i + 1] - decal];\n var p3 = pts[indices[i + 2] - decal];\n this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);\n }\n };\n Collider.prototype._getResponse = function (pos, vel) {\n pos.addToRef(vel, this._destinationPoint);\n vel.scaleInPlace((this._nearestDistance / vel.length()));\n this._basePoint.addToRef(vel, pos);\n pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);\n this._slidePlaneNormal.normalize();\n this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);\n pos.addInPlace(this._displacementVector);\n this.intersectionPoint.addInPlace(this._displacementVector);\n this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));\n this._destinationPoint.subtractInPlace(this._slidePlaneNormal);\n this._destinationPoint.subtractToRef(this.intersectionPoint, vel);\n };\n return Collider;\n }());\n BABYLON.Collider = Collider;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.collider.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n //WebWorker code will be inserted to this variable.\n BABYLON.CollisionWorker = \"\";\n /** Defines supported task for worker process */\n var WorkerTaskType;\n (function (WorkerTaskType) {\n /** Initialization */\n WorkerTaskType[WorkerTaskType[\"INIT\"] = 0] = \"INIT\";\n /** Update of geometry */\n WorkerTaskType[WorkerTaskType[\"UPDATE\"] = 1] = \"UPDATE\";\n /** Evaluate collision */\n WorkerTaskType[WorkerTaskType[\"COLLIDE\"] = 2] = \"COLLIDE\";\n })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));\n /** Defines kind of replies returned by worker */\n var WorkerReplyType;\n (function (WorkerReplyType) {\n /** Success */\n WorkerReplyType[WorkerReplyType[\"SUCCESS\"] = 0] = \"SUCCESS\";\n /** Unkown error */\n WorkerReplyType[WorkerReplyType[\"UNKNOWN_ERROR\"] = 1] = \"UNKNOWN_ERROR\";\n })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));\n var CollisionCoordinatorWorker = /** @class */ (function () {\n function CollisionCoordinatorWorker() {\n var _this = this;\n this._scaledPosition = BABYLON.Vector3.Zero();\n this._scaledVelocity = BABYLON.Vector3.Zero();\n this.onMeshUpdated = function (transformNode) {\n _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);\n };\n this.onGeometryUpdated = function (geometry) {\n _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);\n };\n this._afterRender = function () {\n if (!_this._init)\n return;\n if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {\n return;\n }\n //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.\n //TODO make sure update runs as fast as possible to be able to update 60 FPS.\n if (_this._runningUpdated > 4) {\n return;\n }\n ++_this._runningUpdated;\n var payload = {\n updatedMeshes: _this._addUpdateMeshesList,\n updatedGeometries: _this._addUpdateGeometriesList,\n removedGeometries: _this._toRemoveGeometryArray,\n removedMeshes: _this._toRemoveMeshesArray\n };\n var message = {\n payload: payload,\n taskType: WorkerTaskType.UPDATE\n };\n var serializable = [];\n for (var id in payload.updatedGeometries) {\n if (payload.updatedGeometries.hasOwnProperty(id)) {\n //prepare transferables\n serializable.push(message.payload.updatedGeometries[id].indices.buffer);\n serializable.push(message.payload.updatedGeometries[id].normals.buffer);\n serializable.push(message.payload.updatedGeometries[id].positions.buffer);\n }\n }\n _this._worker.postMessage(message, serializable);\n _this._addUpdateMeshesList = {};\n _this._addUpdateGeometriesList = {};\n _this._toRemoveGeometryArray = [];\n _this._toRemoveMeshesArray = [];\n };\n this._onMessageFromWorker = function (e) {\n var returnData = e.data;\n if (returnData.error != WorkerReplyType.SUCCESS) {\n //TODO what errors can be returned from the worker?\n BABYLON.Tools.Warn(\"error returned from worker!\");\n return;\n }\n switch (returnData.taskType) {\n case WorkerTaskType.INIT:\n _this._init = true;\n //Update the worked with ALL of the scene's current state\n _this._scene.meshes.forEach(function (mesh) {\n _this.onMeshAdded(mesh);\n });\n _this._scene.getGeometries().forEach(function (geometry) {\n _this.onGeometryAdded(geometry);\n });\n break;\n case WorkerTaskType.UPDATE:\n _this._runningUpdated--;\n break;\n case WorkerTaskType.COLLIDE:\n var returnPayload = returnData.payload;\n if (!_this._collisionsCallbackArray[returnPayload.collisionId])\n return;\n var callback = _this._collisionsCallbackArray[returnPayload.collisionId];\n if (callback) {\n var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);\n if (mesh) {\n callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);\n }\n }\n //cleanup\n _this._collisionsCallbackArray[returnPayload.collisionId] = null;\n break;\n }\n };\n this._collisionsCallbackArray = [];\n this._init = false;\n this._runningUpdated = 0;\n this._addUpdateMeshesList = {};\n this._addUpdateGeometriesList = {};\n this._toRemoveGeometryArray = [];\n this._toRemoveMeshesArray = [];\n }\n CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {\n if (!this._init)\n return;\n if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])\n return;\n position.divideToRef(collider._radius, this._scaledPosition);\n displacement.divideToRef(collider._radius, this._scaledVelocity);\n this._collisionsCallbackArray[collisionIndex] = onNewPosition;\n var payload = {\n collider: {\n position: this._scaledPosition.asArray(),\n velocity: this._scaledVelocity.asArray(),\n radius: collider._radius.asArray()\n },\n collisionId: collisionIndex,\n excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,\n maximumRetry: maximumRetry\n };\n var message = {\n payload: payload,\n taskType: WorkerTaskType.COLLIDE\n };\n this._worker.postMessage(message);\n };\n CollisionCoordinatorWorker.prototype.init = function (scene) {\n this._scene = scene;\n this._scene.registerAfterRender(this._afterRender);\n var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + \"Collisions/babylon.collisionWorker.js\" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));\n this._worker = new Worker(workerUrl);\n this._worker.onmessage = this._onMessageFromWorker;\n var message = {\n payload: {},\n taskType: WorkerTaskType.INIT\n };\n this._worker.postMessage(message);\n };\n CollisionCoordinatorWorker.prototype.destroy = function () {\n this._scene.unregisterAfterRender(this._afterRender);\n this._worker.terminate();\n };\n CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {\n mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);\n this.onMeshUpdated(mesh);\n };\n CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {\n this._toRemoveMeshesArray.push(mesh.uniqueId);\n };\n CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {\n //TODO this will break if the user uses his own function. This should be an array of callbacks!\n geometry.onGeometryUpdated = this.onGeometryUpdated;\n this.onGeometryUpdated(geometry);\n };\n CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {\n this._toRemoveGeometryArray.push(geometry.id);\n };\n CollisionCoordinatorWorker.SerializeMesh = function (mesh) {\n var submeshes = [];\n if (mesh.subMeshes) {\n submeshes = mesh.subMeshes.map(function (sm, idx) {\n var boundingInfo = sm.getBoundingInfo();\n return {\n position: idx,\n verticesStart: sm.verticesStart,\n verticesCount: sm.verticesCount,\n indexStart: sm.indexStart,\n indexCount: sm.indexCount,\n hasMaterial: !!sm.getMaterial(),\n sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),\n sphereRadius: boundingInfo.boundingSphere.radiusWorld,\n boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),\n boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()\n };\n });\n }\n var geometryId = null;\n if (mesh instanceof BABYLON.Mesh) {\n var geometry = mesh.geometry;\n geometryId = geometry ? geometry.id : null;\n }\n else if (mesh instanceof BABYLON.InstancedMesh) {\n var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;\n geometryId = geometry ? geometry.id : null;\n }\n var boundingInfo = mesh.getBoundingInfo();\n return {\n uniqueId: mesh.uniqueId,\n id: mesh.id,\n name: mesh.name,\n geometryId: geometryId,\n sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),\n sphereRadius: boundingInfo.boundingSphere.radiusWorld,\n boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),\n boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),\n worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),\n subMeshes: submeshes,\n checkCollisions: mesh.checkCollisions\n };\n };\n CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {\n return {\n id: geometry.id,\n positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),\n normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),\n indices: new Uint32Array(geometry.getIndices() || []),\n };\n };\n return CollisionCoordinatorWorker;\n }());\n BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;\n var CollisionCoordinatorLegacy = /** @class */ (function () {\n function CollisionCoordinatorLegacy() {\n this._scaledPosition = BABYLON.Vector3.Zero();\n this._scaledVelocity = BABYLON.Vector3.Zero();\n this._finalPosition = BABYLON.Vector3.Zero();\n }\n CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {\n position.divideToRef(collider._radius, this._scaledPosition);\n displacement.divideToRef(collider._radius, this._scaledVelocity);\n collider.collidedMesh = null;\n collider._retry = 0;\n collider._initialVelocity = this._scaledVelocity;\n collider._initialPosition = this._scaledPosition;\n this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);\n this._finalPosition.multiplyInPlace(collider._radius);\n //run the callback\n onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);\n };\n CollisionCoordinatorLegacy.prototype.init = function (scene) {\n this._scene = scene;\n };\n CollisionCoordinatorLegacy.prototype.destroy = function () {\n //Legacy need no destruction method.\n };\n //No update in legacy mode\n CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };\n CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };\n CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };\n CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };\n CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };\n CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };\n CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {\n if (excludedMesh === void 0) { excludedMesh = null; }\n var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;\n if (collider._retry >= maximumRetry) {\n finalPosition.copyFrom(position);\n return;\n }\n // Check if this is a mesh else camera or -1\n var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);\n collider._initialize(position, velocity, closeDistance);\n // Check all meshes\n for (var index = 0; index < this._scene.meshes.length; index++) {\n var mesh = this._scene.meshes[index];\n if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {\n mesh._checkCollision(collider);\n }\n }\n if (!collider.collisionFound) {\n position.addToRef(velocity, finalPosition);\n return;\n }\n if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {\n collider._getResponse(position, velocity);\n }\n if (velocity.length() <= closeDistance) {\n finalPosition.copyFrom(position);\n return;\n }\n collider._retry++;\n this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);\n };\n return CollisionCoordinatorLegacy;\n }());\n BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.collisionCoordinator.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A particle represents one of the element emitted by a particle system.\n * This is mainly define by its coordinates, direction, velocity and age.\n */\n var Particle = /** @class */ (function () {\n /**\n * Creates a new instance Particle\n * @param particleSystem the particle system the particle belongs to\n */\n function Particle(\n /**\n * particleSystem the particle system the particle belongs to.\n */\n particleSystem) {\n this.particleSystem = particleSystem;\n /**\n * The world position of the particle in the scene.\n */\n this.position = BABYLON.Vector3.Zero();\n /**\n * The world direction of the particle in the scene.\n */\n this.direction = BABYLON.Vector3.Zero();\n /**\n * The color of the particle.\n */\n this.color = new BABYLON.Color4(0, 0, 0, 0);\n /**\n * The color change of the particle per step.\n */\n this.colorStep = new BABYLON.Color4(0, 0, 0, 0);\n /**\n * Defines how long will the life of the particle be.\n */\n this.lifeTime = 1.0;\n /**\n * The current age of the particle.\n */\n this.age = 0;\n /**\n * The current size of the particle.\n */\n this.size = 0;\n /**\n * The current scale of the particle.\n */\n this.scale = new BABYLON.Vector2(1, 1);\n /**\n * The current angle of the particle.\n */\n this.angle = 0;\n /**\n * Defines how fast is the angle changing.\n */\n this.angularSpeed = 0;\n /**\n * Defines the cell index used by the particle to be rendered from a sprite.\n */\n this.cellIndex = 0;\n /** @hidden */\n this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);\n /** @hidden */\n this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);\n /** @hidden */\n this._currentSize1 = 0;\n /** @hidden */\n this._currentSize2 = 0;\n /** @hidden */\n this._currentAngularSpeed1 = 0;\n /** @hidden */\n this._currentAngularSpeed2 = 0;\n /** @hidden */\n this._currentVelocity1 = 0;\n /** @hidden */\n this._currentVelocity2 = 0;\n if (!this.particleSystem.isAnimationSheetEnabled) {\n return;\n }\n this.updateCellInfoFromSystem();\n }\n Particle.prototype.updateCellInfoFromSystem = function () {\n this.cellIndex = this.particleSystem.startSpriteCellID;\n };\n /**\n * Defines how the sprite cell index is updated for the particle\n */\n Particle.prototype.updateCellIndex = function () {\n var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);\n var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);\n this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;\n };\n /**\n * Copy the properties of particle to another one.\n * @param other the particle to copy the information to.\n */\n Particle.prototype.copyTo = function (other) {\n other.position.copyFrom(this.position);\n if (this._initialDirection) {\n if (other._initialDirection) {\n other._initialDirection.copyFrom(this._initialDirection);\n }\n else {\n other._initialDirection = this._initialDirection.clone();\n }\n }\n else {\n other._initialDirection = null;\n }\n other.direction.copyFrom(this.direction);\n other.color.copyFrom(this.color);\n other.colorStep.copyFrom(this.colorStep);\n other.lifeTime = this.lifeTime;\n other.age = this.age;\n other.size = this.size;\n other.scale.copyFrom(this.scale);\n other.angle = this.angle;\n other.angularSpeed = this.angularSpeed;\n other.particleSystem = this.particleSystem;\n other.cellIndex = this.cellIndex;\n if (this._currentColorGradient) {\n other._currentColorGradient = this._currentColorGradient;\n other._currentColor1.copyFrom(this._currentColor1);\n other._currentColor2.copyFrom(this._currentColor2);\n }\n if (this._currentSizeGradient) {\n other._currentSizeGradient = this._currentSizeGradient;\n other._currentSize1 = this._currentSize1;\n other._currentSize2 = this._currentSize2;\n }\n if (this._currentAngularSpeedGradient) {\n other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;\n other._currentAngularSpeed1 = this._currentAngularSpeed1;\n other._currentAngularSpeed2 = this._currentAngularSpeed2;\n }\n if (this._currentVelocityGradient) {\n other._currentVelocityGradient = this._currentVelocityGradient;\n other._currentVelocity1 = this._currentVelocity1;\n other._currentVelocity2 = this._currentVelocity2;\n }\n if (this.particleSystem.isAnimationSheetEnabled) {\n other._initialStartSpriteCellID = this._initialStartSpriteCellID;\n other._initialEndSpriteCellID = this._initialEndSpriteCellID;\n }\n };\n return Particle;\n }());\n BABYLON.Particle = Particle;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.particle.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This represents a particle system in Babylon.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.\n * @example https://doc.babylonjs.com/babylon101/particles\n */\n var ParticleSystem = /** @class */ (function () {\n /**\n * Instantiates a particle system.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * @param name The name of the particle system\n * @param capacity The max number of particles alive at the same time\n * @param scene The scene the particle system belongs to\n * @param customEffect a custom effect used to change the way particles are rendered by default\n * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture\n * @param epsilon Offset used to render the particles\n */\n function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {\n if (customEffect === void 0) { customEffect = null; }\n if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }\n if (epsilon === void 0) { epsilon = 0.01; }\n var _this = this;\n /**\n * List of animations used by the particle system.\n */\n this.animations = [];\n /**\n * The rendering group used by the Particle system to chose when to render.\n */\n this.renderingGroupId = 0;\n /**\n * The emitter represents the Mesh or position we are attaching the particle system to.\n */\n this.emitter = null;\n /**\n * The maximum number of particles to emit per frame\n */\n this.emitRate = 10;\n /**\n * If you want to launch only a few particles at once, that can be done, as well.\n */\n this.manualEmitCount = -1;\n /**\n * The overall motion speed (0.01 is default update speed, faster updates = faster animation)\n */\n this.updateSpeed = 0.01;\n /**\n * The amount of time the particle system is running (depends of the overall update speed).\n */\n this.targetStopDuration = 0;\n /**\n * Specifies whether the particle system will be disposed once it reaches the end of the animation.\n */\n this.disposeOnStop = false;\n /**\n * Minimum power of emitting particles.\n */\n this.minEmitPower = 1;\n /**\n * Maximum power of emitting particles.\n */\n this.maxEmitPower = 1;\n /**\n * Minimum life time of emitting particles.\n */\n this.minLifeTime = 1;\n /**\n * Maximum life time of emitting particles.\n */\n this.maxLifeTime = 1;\n /**\n * Minimum Size of emitting particles.\n */\n this.minSize = 1;\n /**\n * Maximum Size of emitting particles.\n */\n this.maxSize = 1;\n /**\n * Minimum scale of emitting particles on X axis.\n */\n this.minScaleX = 1;\n /**\n * Maximum scale of emitting particles on X axis.\n */\n this.maxScaleX = 1;\n /**\n * Minimum scale of emitting particles on Y axis.\n */\n this.minScaleY = 1;\n /**\n * Maximum scale of emitting particles on Y axis.\n */\n this.maxScaleY = 1;\n /**\n * Gets or sets the minimal initial rotation in radians.\n */\n this.minInitialRotation = 0;\n /**\n * Gets or sets the maximal initial rotation in radians.\n */\n this.maxInitialRotation = 0;\n /**\n * Minimum angular speed of emitting particles (Z-axis rotation for each particle).\n */\n this.minAngularSpeed = 0;\n /**\n * Maximum angular speed of emitting particles (Z-axis rotation for each particle).\n */\n this.maxAngularSpeed = 0;\n /**\n * The layer mask we are rendering the particles through.\n */\n this.layerMask = 0x0FFFFFFF;\n /**\n * This can help using your own shader to render the particle system.\n * The according effect will be created\n */\n this.customShader = null;\n /**\n * By default particle system starts as soon as they are created. This prevents the\n * automatic start to happen and let you decide when to start emitting particles.\n */\n this.preventAutoStart = false;\n /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */\n this.noiseStrength = new BABYLON.Vector3(10, 10, 10);\n /**\n * Callback triggered when the particle animation is ending.\n */\n this.onAnimationEnd = null;\n /**\n * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.\n */\n this.blendMode = ParticleSystem.BLENDMODE_ONEONE;\n /**\n * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls\n * to override the particles.\n */\n this.forceDepthWrite = false;\n /**\n * You can use gravity if you want to give an orientation to your particles.\n */\n this.gravity = BABYLON.Vector3.Zero();\n this._colorGradients = null;\n this._sizeGradients = null;\n this._lifeTimeGradients = null;\n this._angularSpeedGradients = null;\n this._velocityGradients = null;\n /**\n * Random color of each particle after it has been emitted, between color1 and color2 vectors\n */\n this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * Random color of each particle after it has been emitted, between color1 and color2 vectors\n */\n this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * Color the particle will have at the end of its lifetime\n */\n this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);\n /**\n * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel\n */\n this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)\n */\n this.spriteCellChangeSpeed = 1;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display\n */\n this.startSpriteCellID = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display\n */\n this.endSpriteCellID = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use\n */\n this.spriteCellWidth = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use\n */\n this.spriteCellHeight = 0;\n /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */\n this.preWarmCycles = 0;\n /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */\n this.preWarmStepOffset = 1;\n /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */\n this.translationPivot = new BABYLON.Vector2(0, 0);\n /**\n * An event triggered when the system is disposed\n */\n this.onDisposeObservable = new BABYLON.Observable();\n /**\n * Gets or sets the billboard mode to use when isBillboardBased = true.\n * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far\n */\n this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;\n this._particles = new Array();\n this._stockParticles = new Array();\n this._newPartsExcess = 0;\n this._vertexBuffers = {};\n this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);\n this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);\n this._scaledDirection = BABYLON.Vector3.Zero();\n this._scaledGravity = BABYLON.Vector3.Zero();\n this._currentRenderId = -1;\n this._useInstancing = false;\n this._started = false;\n this._stopped = false;\n this._actualFrame = 0;\n this._isBillboardBased = true;\n // start of sub system methods\n /**\n * \"Recycles\" one of the particle by copying it back to the \"stock\" of particles and removing it from the active list.\n * Its lifetime will start back at 0.\n */\n this.recycleParticle = function (particle) {\n var lastParticle = _this._particles.pop();\n if (lastParticle !== particle) {\n lastParticle.copyTo(particle);\n }\n _this._stockParticles.push(lastParticle);\n };\n this._createParticle = function () {\n var particle;\n if (_this._stockParticles.length !== 0) {\n particle = _this._stockParticles.pop();\n particle.age = 0;\n particle._currentColorGradient = null;\n particle.cellIndex = _this.startSpriteCellID;\n }\n else {\n particle = new BABYLON.Particle(_this);\n }\n return particle;\n };\n this._emitFromParticle = function (particle) {\n if (!_this.subEmitters || _this.subEmitters.length === 0) {\n return;\n }\n var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);\n var subSystem = _this.subEmitters[templateIndex].clone(_this.name + \"_sub\", particle.position.clone());\n subSystem._rootParticleSystem = _this;\n _this.activeSubSystems.push(subSystem);\n subSystem.start();\n };\n this.id = name;\n this.name = name;\n this._capacity = capacity;\n this._epsilon = epsilon;\n this._isAnimationSheetEnabled = isAnimationSheetEnabled;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this._customEffect = customEffect;\n this._scene.particleSystems.push(this);\n this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;\n this._createIndexBuffer();\n this._createVertexBuffers();\n // Default emitter type\n this.particleEmitterType = new BABYLON.BoxParticleEmitter();\n this.updateFunction = function (particles) {\n var noiseTextureData = null;\n var noiseTextureSize = null;\n if (_this.noiseTexture) { // We need to get texture data back to CPU\n noiseTextureData = (_this.noiseTexture.readPixels());\n noiseTextureSize = _this.noiseTexture.getSize();\n }\n var _loop_1 = function () {\n particle = particles[index];\n particle.age += _this._scaledUpdateSpeed;\n if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle\n _this._emitFromParticle(particle);\n _this.recycleParticle(particle);\n index--;\n return \"continue\";\n }\n else {\n var ratio = particle.age / particle.lifeTime;\n // Color\n if (_this._colorGradients && _this._colorGradients.length > 0) {\n BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {\n if (currentGradient !== particle._currentColorGradient) {\n particle._currentColor1.copyFrom(particle._currentColor2);\n nextGradient.getColorToRef(particle._currentColor2);\n particle._currentColorGradient = currentGradient;\n }\n BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);\n });\n }\n else {\n particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);\n particle.color.addInPlace(_this._scaledColorStep);\n if (particle.color.a < 0) {\n particle.color.a = 0;\n }\n }\n // Angular speed\n if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {\n BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {\n if (currentGradient !== particle._currentAngularSpeedGradient) {\n particle._currentAngularSpeed1 = particle._currentAngularSpeed2;\n particle._currentAngularSpeed2 = nextGradient.getFactor();\n particle._currentAngularSpeedGradient = currentGradient;\n }\n particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);\n });\n }\n particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;\n // Direction\n var directionScale_1 = _this._scaledUpdateSpeed;\n if (_this._velocityGradients && _this._velocityGradients.length > 0) {\n BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {\n if (currentGradient !== particle._currentVelocityGradient) {\n particle._currentVelocity1 = particle._currentVelocity2;\n particle._currentVelocity2 = nextGradient.getFactor();\n particle._currentVelocityGradient = currentGradient;\n }\n directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);\n });\n }\n particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);\n particle.position.addInPlace(_this._scaledDirection);\n // Noise\n if (noiseTextureData && noiseTextureSize) {\n var localPosition = BABYLON.Tmp.Vector3[0];\n var emitterPosition = BABYLON.Tmp.Vector3[1];\n _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);\n particle.position.subtractToRef(emitterPosition, localPosition);\n var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);\n var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);\n var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);\n var force = BABYLON.Tmp.Vector3[0];\n var scaledForce = BABYLON.Tmp.Vector3[1];\n force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);\n force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);\n particle.direction.addInPlace(scaledForce);\n }\n // Gravity\n _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);\n particle.direction.addInPlace(_this._scaledGravity);\n // Size\n if (_this._sizeGradients && _this._sizeGradients.length > 0) {\n BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {\n if (currentGradient !== particle._currentSizeGradient) {\n particle._currentSize1 = particle._currentSize2;\n particle._currentSize2 = nextGradient.getFactor();\n particle._currentSizeGradient = currentGradient;\n }\n particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);\n });\n }\n if (_this._isAnimationSheetEnabled) {\n particle.updateCellIndex();\n }\n }\n };\n var particle;\n for (var index = 0; index < particles.length; index++) {\n _loop_1();\n }\n };\n }\n /**\n * Gets the current list of color gradients.\n * You must use addColorGradient and removeColorGradient to udpate this list\n * @returns the list of color gradients\n */\n ParticleSystem.prototype.getColorGradients = function () {\n return this._colorGradients;\n };\n /**\n * Gets the current list of size gradients.\n * You must use addSizeGradient and removeSizeGradient to udpate this list\n * @returns the list of size gradients\n */\n ParticleSystem.prototype.getSizeGradients = function () {\n return this._sizeGradients;\n };\n /**\n * Gets the current list of life time gradients.\n * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list\n * @returns the list of life time gradients\n */\n ParticleSystem.prototype.getLifeTimeGradients = function () {\n return this._lifeTimeGradients;\n };\n /**\n * Gets the current list of angular speed gradients.\n * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list\n * @returns the list of angular speed gradients\n */\n ParticleSystem.prototype.getAngularSpeedGradients = function () {\n return this._angularSpeedGradients;\n };\n /**\n * Gets the current list of velocity gradients.\n * You must use addVelocityGradient and removeVelocityGradient to udpate this list\n * @returns the list of velocity gradients\n */\n ParticleSystem.prototype.getVelocityGradients = function () {\n return this._velocityGradients;\n };\n Object.defineProperty(ParticleSystem.prototype, \"direction1\", {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.direction1) {\n return this.particleEmitterType.direction1;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.direction1) {\n this.particleEmitterType.direction1 = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ParticleSystem.prototype, \"direction2\", {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.direction2) {\n return this.particleEmitterType.direction2;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.direction2) {\n this.particleEmitterType.direction2 = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ParticleSystem.prototype, \"minEmitBox\", {\n /**\n * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.minEmitBox) {\n return this.particleEmitterType.minEmitBox;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.minEmitBox) {\n this.particleEmitterType.minEmitBox = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ParticleSystem.prototype, \"maxEmitBox\", {\n /**\n * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.maxEmitBox) {\n return this.particleEmitterType.maxEmitBox;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.maxEmitBox) {\n this.particleEmitterType.maxEmitBox = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ParticleSystem.prototype, \"onDispose\", {\n /**\n * Sets a callback that will be triggered when the system is disposed\n */\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ParticleSystem.prototype, \"isAnimationSheetEnabled\", {\n /**\n * Gets or sets whether an animation sprite sheet is enabled or not on the particle system\n */\n get: function () {\n return this._isAnimationSheetEnabled;\n },\n set: function (value) {\n if (this._isAnimationSheetEnabled == value) {\n return;\n }\n this._isAnimationSheetEnabled = value;\n this._resetEffect();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ParticleSystem.prototype, \"isBillboardBased\", {\n /**\n * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction\n */\n get: function () {\n return this._isBillboardBased;\n },\n set: function (value) {\n if (this._isBillboardBased === value) {\n return;\n }\n this._isBillboardBased = value;\n this._resetEffect();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Get hosting scene\n * @returns the scene\n */\n ParticleSystem.prototype.getScene = function () {\n return this._scene;\n };\n Object.defineProperty(ParticleSystem.prototype, \"particles\", {\n //end of Sub-emitter\n /**\n * Gets the current list of active particles\n */\n get: function () {\n return this._particles;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"ParticleSystem\"\n * @returns a string containing the class name\n */\n ParticleSystem.prototype.getClassName = function () {\n return \"ParticleSystem\";\n };\n ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {\n u = Math.abs(u) * 0.5 + 0.5;\n v = Math.abs(v) * 0.5 + 0.5;\n var wrappedU = ((u * width) % width) | 0;\n var wrappedV = ((v * height) % height) | 0;\n var position = (wrappedU + wrappedV * width) * 4;\n return pixels[position] / 255;\n };\n ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {\n var newGradient = new BABYLON.FactorGradient();\n newGradient.gradient = gradient;\n newGradient.factor1 = factor;\n newGradient.factor2 = factor2;\n factorGradients.push(newGradient);\n factorGradients.sort(function (a, b) {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n };\n ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {\n if (!factorGradients) {\n return;\n }\n var index = 0;\n for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {\n var factorGradient = factorGradients_1[_i];\n if (factorGradient.gradient === gradient) {\n factorGradients.splice(index, 1);\n break;\n }\n index++;\n }\n };\n /**\n * Adds a new life time gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the life time factor to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {\n if (!this._lifeTimeGradients) {\n this._lifeTimeGradients = [];\n }\n this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);\n return this;\n };\n /**\n * Remove a specific life time gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {\n this._removeFactorGradient(this._lifeTimeGradients, gradient);\n return this;\n };\n /**\n * Adds a new size gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {\n if (!this._sizeGradients) {\n this._sizeGradients = [];\n }\n this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);\n return this;\n };\n /**\n * Remove a specific size gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n ParticleSystem.prototype.removeSizeGradient = function (gradient) {\n this._removeFactorGradient(this._sizeGradients, gradient);\n return this;\n };\n /**\n * Adds a new angular speed gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {\n if (!this._angularSpeedGradients) {\n this._angularSpeedGradients = [];\n }\n this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);\n return this;\n };\n /**\n * Remove a specific angular speed gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {\n this._removeFactorGradient(this._angularSpeedGradients, gradient);\n return this;\n };\n /**\n * Adds a new velocity gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {\n if (!this._velocityGradients) {\n this._velocityGradients = [];\n }\n this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);\n return this;\n };\n /**\n * Remove a specific velocity gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n ParticleSystem.prototype.removeVelocityGradient = function (gradient) {\n this._removeFactorGradient(this._velocityGradients, gradient);\n return this;\n };\n /**\n * Adds a new color gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param color defines the color to affect to the specified gradient\n * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from\n */\n ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {\n if (!this._colorGradients) {\n this._colorGradients = [];\n }\n var colorGradient = new BABYLON.ColorGradient();\n colorGradient.gradient = gradient;\n colorGradient.color1 = color;\n colorGradient.color2 = color2;\n this._colorGradients.push(colorGradient);\n this._colorGradients.sort(function (a, b) {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n return this;\n };\n /**\n * Remove a specific color gradient\n * @param gradient defines the gradient to remove\n */\n ParticleSystem.prototype.removeColorGradient = function (gradient) {\n if (!this._colorGradients) {\n return this;\n }\n var index = 0;\n for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {\n var colorGradient = _a[_i];\n if (colorGradient.gradient === gradient) {\n this._colorGradients.splice(index, 1);\n break;\n }\n index++;\n }\n return this;\n };\n ParticleSystem.prototype._resetEffect = function () {\n if (this._vertexBuffer) {\n this._vertexBuffer.dispose();\n this._vertexBuffer = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n this._createVertexBuffers();\n };\n ParticleSystem.prototype._createVertexBuffers = function () {\n this._vertexBufferSize = this._useInstancing ? 10 : 12;\n if (this._isAnimationSheetEnabled) {\n this._vertexBufferSize += 1;\n }\n if (!this._isBillboardBased) {\n this._vertexBufferSize += 3;\n }\n var engine = this._scene.getEngine();\n this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));\n this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);\n var dataOffset = 0;\n var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;\n dataOffset += 3;\n var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;\n dataOffset += 4;\n var options = this._vertexBuffer.createVertexBuffer(\"angle\", dataOffset, 1, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"angle\"] = options;\n dataOffset += 1;\n var size = this._vertexBuffer.createVertexBuffer(\"size\", dataOffset, 2, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"size\"] = size;\n dataOffset += 2;\n if (this._isAnimationSheetEnabled) {\n var cellIndexBuffer = this._vertexBuffer.createVertexBuffer(\"cellIndex\", dataOffset, 1, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"cellIndex\"] = cellIndexBuffer;\n dataOffset += 1;\n }\n if (!this._isBillboardBased) {\n var directionBuffer = this._vertexBuffer.createVertexBuffer(\"direction\", dataOffset, 3, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"direction\"] = directionBuffer;\n dataOffset += 3;\n }\n var offsets;\n if (this._useInstancing) {\n var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);\n this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);\n offsets = this._spriteBuffer.createVertexBuffer(\"offset\", 0, 2);\n }\n else {\n offsets = this._vertexBuffer.createVertexBuffer(\"offset\", dataOffset, 2, this._vertexBufferSize, this._useInstancing);\n dataOffset += 2;\n }\n this._vertexBuffers[\"offset\"] = offsets;\n };\n ParticleSystem.prototype._createIndexBuffer = function () {\n if (this._useInstancing) {\n return;\n }\n var indices = [];\n var index = 0;\n for (var count = 0; count < this._capacity; count++) {\n indices.push(index);\n indices.push(index + 1);\n indices.push(index + 2);\n indices.push(index);\n indices.push(index + 2);\n indices.push(index + 3);\n index += 4;\n }\n this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);\n };\n /**\n * Gets the maximum number of particles active at the same time.\n * @returns The max number of active particles.\n */\n ParticleSystem.prototype.getCapacity = function () {\n return this._capacity;\n };\n /**\n * Gets Wether there are still active particles in the system.\n * @returns True if it is alive, otherwise false.\n */\n ParticleSystem.prototype.isAlive = function () {\n return this._alive;\n };\n /**\n * Gets Wether the system has been started.\n * @returns True if it has been started, otherwise false.\n */\n ParticleSystem.prototype.isStarted = function () {\n return this._started;\n };\n /**\n * Starts the particle system and begins to emit\n * @param delay defines the delay in milliseconds before starting the system (0 by default)\n */\n ParticleSystem.prototype.start = function (delay) {\n var _this = this;\n if (delay === void 0) { delay = 0; }\n if (delay) {\n setTimeout(function () {\n _this.start(0);\n }, delay);\n return;\n }\n this._started = true;\n this._stopped = false;\n this._actualFrame = 0;\n if (this.subEmitters && this.subEmitters.length != 0) {\n this.activeSubSystems = new Array();\n }\n if (this.preWarmCycles) {\n for (var index = 0; index < this.preWarmCycles; index++) {\n this.animate(true);\n }\n }\n };\n /**\n * Stops the particle system.\n * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.\n */\n ParticleSystem.prototype.stop = function (stopSubEmitters) {\n if (stopSubEmitters === void 0) { stopSubEmitters = true; }\n this._stopped = true;\n if (stopSubEmitters) {\n this._stopSubEmitters();\n }\n };\n // animation sheet\n /**\n * Remove all active particles\n */\n ParticleSystem.prototype.reset = function () {\n this._stockParticles = [];\n this._particles = [];\n };\n /**\n * @hidden (for internal use only)\n */\n ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {\n var offset = index * this._vertexBufferSize;\n this._vertexData[offset++] = particle.position.x;\n this._vertexData[offset++] = particle.position.y;\n this._vertexData[offset++] = particle.position.z;\n this._vertexData[offset++] = particle.color.r;\n this._vertexData[offset++] = particle.color.g;\n this._vertexData[offset++] = particle.color.b;\n this._vertexData[offset++] = particle.color.a;\n this._vertexData[offset++] = particle.angle;\n this._vertexData[offset++] = particle.scale.x * particle.size;\n this._vertexData[offset++] = particle.scale.y * particle.size;\n if (this._isAnimationSheetEnabled) {\n this._vertexData[offset++] = particle.cellIndex;\n }\n if (!this._isBillboardBased) {\n if (particle._initialDirection) {\n this._vertexData[offset++] = particle._initialDirection.x;\n this._vertexData[offset++] = particle._initialDirection.y;\n this._vertexData[offset++] = particle._initialDirection.z;\n }\n else {\n this._vertexData[offset++] = particle.direction.x;\n this._vertexData[offset++] = particle.direction.y;\n this._vertexData[offset++] = particle.direction.z;\n }\n }\n if (!this._useInstancing) {\n if (this._isAnimationSheetEnabled) {\n if (offsetX === 0)\n offsetX = this._epsilon;\n else if (offsetX === 1)\n offsetX = 1 - this._epsilon;\n if (offsetY === 0)\n offsetY = this._epsilon;\n else if (offsetY === 1)\n offsetY = 1 - this._epsilon;\n }\n this._vertexData[offset++] = offsetX;\n this._vertexData[offset++] = offsetY;\n }\n };\n ParticleSystem.prototype._stopSubEmitters = function () {\n if (!this.activeSubSystems) {\n return;\n }\n this.activeSubSystems.forEach(function (subSystem) {\n subSystem.stop(true);\n });\n this.activeSubSystems = new Array();\n };\n ParticleSystem.prototype._removeFromRoot = function () {\n if (!this._rootParticleSystem) {\n return;\n }\n var index = this._rootParticleSystem.activeSubSystems.indexOf(this);\n if (index !== -1) {\n this._rootParticleSystem.activeSubSystems.splice(index, 1);\n }\n };\n // End of sub system methods\n ParticleSystem.prototype._update = function (newParticles) {\n // Update current\n this._alive = this._particles.length > 0;\n if (this.emitter.position) {\n var emitterMesh = this.emitter;\n this._emitterWorldMatrix = emitterMesh.getWorldMatrix();\n }\n else {\n var emitterPosition = this.emitter;\n this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);\n }\n this.updateFunction(this._particles);\n // Add new ones\n var particle;\n var _loop_2 = function () {\n if (this_1._particles.length === this_1._capacity) {\n return \"break\";\n }\n particle = this_1._createParticle();\n this_1._particles.push(particle);\n // Emitter\n var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);\n if (this_1.startPositionFunction) {\n this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);\n }\n else {\n this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);\n }\n if (this_1.startDirectionFunction) {\n this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);\n }\n else {\n this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);\n }\n if (emitPower === 0) {\n if (!particle._initialDirection) {\n particle._initialDirection = particle.direction.clone();\n }\n else {\n particle._initialDirection.copyFrom(particle.direction);\n }\n }\n else {\n particle._initialDirection = null;\n }\n particle.direction.scaleInPlace(emitPower);\n // Life time\n if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {\n var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);\n BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {\n var factorGradient1 = currentGradient;\n var factorGradient2 = nextGradient;\n var lifeTime1 = factorGradient1.getFactor();\n var lifeTime2 = factorGradient2.getFactor();\n var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);\n particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);\n });\n }\n else {\n particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);\n }\n // Size\n if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {\n particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);\n }\n else {\n particle._currentSizeGradient = this_1._sizeGradients[0];\n particle._currentSize1 = particle._currentSizeGradient.getFactor();\n particle.size = particle._currentSize1;\n if (this_1._sizeGradients.length > 1) {\n particle._currentSize2 = this_1._sizeGradients[1].getFactor();\n }\n else {\n particle._currentSize2 = particle._currentSize1;\n }\n }\n // Size and scale\n particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));\n // Angle\n if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {\n particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);\n }\n else {\n particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];\n particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();\n particle._currentAngularSpeed1 = particle.angularSpeed;\n if (this_1._angularSpeedGradients.length > 1) {\n particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();\n }\n else {\n particle._currentAngularSpeed2 = particle._currentAngularSpeed1;\n }\n }\n particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);\n // Velocity\n if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {\n particle._currentVelocityGradient = this_1._velocityGradients[0];\n particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();\n if (this_1._velocityGradients.length > 1) {\n particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();\n }\n else {\n particle._currentVelocity2 = particle._currentVelocity1;\n }\n }\n // Color\n if (!this_1._colorGradients || this_1._colorGradients.length === 0) {\n step = BABYLON.Scalar.RandomRange(0, 1.0);\n BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);\n this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);\n this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);\n }\n else {\n particle._currentColorGradient = this_1._colorGradients[0];\n particle._currentColorGradient.getColorToRef(particle.color);\n particle._currentColor1.copyFrom(particle.color);\n if (this_1._colorGradients.length > 1) {\n this_1._colorGradients[1].getColorToRef(particle._currentColor2);\n }\n else {\n particle._currentColor2.copyFrom(particle.color);\n }\n }\n // Sheet\n if (this_1._isAnimationSheetEnabled) {\n particle._initialStartSpriteCellID = this_1.startSpriteCellID;\n particle._initialEndSpriteCellID = this_1.endSpriteCellID;\n }\n };\n var this_1 = this, step;\n for (var index = 0; index < newParticles; index++) {\n var state_1 = _loop_2();\n if (state_1 === \"break\")\n break;\n }\n };\n /** @hidden */\n ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {\n if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }\n if (isBillboardBased === void 0) { isBillboardBased = false; }\n var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, \"angle\", \"offset\", \"size\"];\n if (isAnimationSheetEnabled) {\n attributeNamesOrOptions.push(\"cellIndex\");\n }\n if (!isBillboardBased) {\n attributeNamesOrOptions.push(\"direction\");\n }\n return attributeNamesOrOptions;\n };\n ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {\n if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }\n var effectCreationOption = [\"invView\", \"view\", \"projection\", \"vClipPlane\", \"textureMask\", \"translationPivot\", \"eyePosition\"];\n if (isAnimationSheetEnabled) {\n effectCreationOption.push(\"particlesInfos\");\n }\n return effectCreationOption;\n };\n ParticleSystem.prototype._getEffect = function () {\n if (this._customEffect) {\n return this._customEffect;\n }\n ;\n var defines = [];\n if (this._scene.clipPlane) {\n defines.push(\"#define CLIPPLANE\");\n }\n if (this._isAnimationSheetEnabled) {\n defines.push(\"#define ANIMATESHEET\");\n }\n if (this._isBillboardBased) {\n defines.push(\"#define BILLBOARD\");\n switch (this.billboardMode) {\n case BABYLON.AbstractMesh.BILLBOARDMODE_Y:\n defines.push(\"#define BILLBOARDY\");\n break;\n case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:\n default:\n break;\n }\n }\n // Effect\n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);\n var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);\n this._effect = this._scene.getEngine().createEffect(\"particles\", attributesNamesOrOptions, effectCreationOption, [\"diffuseSampler\"], join);\n }\n return this._effect;\n };\n /**\n * Animates the particle system for the current frame by emitting new particles and or animating the living ones.\n * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)\n */\n ParticleSystem.prototype.animate = function (preWarmOnly) {\n if (preWarmOnly === void 0) { preWarmOnly = false; }\n if (!this._started)\n return;\n if (!preWarmOnly) {\n var effect = this._getEffect();\n // Check\n if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())\n return;\n if (this._currentRenderId === this._scene.getRenderId()) {\n return;\n }\n this._currentRenderId = this._scene.getRenderId();\n }\n this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());\n // determine the number of particles we need to create\n var newParticles;\n if (this.manualEmitCount > -1) {\n newParticles = this.manualEmitCount;\n this._newPartsExcess = 0;\n this.manualEmitCount = 0;\n }\n else {\n newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);\n this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;\n }\n if (this._newPartsExcess > 1.0) {\n newParticles += this._newPartsExcess >> 0;\n this._newPartsExcess -= this._newPartsExcess >> 0;\n }\n this._alive = false;\n if (!this._stopped) {\n this._actualFrame += this._scaledUpdateSpeed;\n if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)\n this.stop();\n }\n else {\n newParticles = 0;\n }\n this._update(newParticles);\n // Stopped?\n if (this._stopped) {\n if (!this._alive) {\n this._started = false;\n if (this.onAnimationEnd) {\n this.onAnimationEnd();\n }\n if (this.disposeOnStop) {\n this._scene._toBeDisposed.push(this);\n }\n }\n }\n if (!preWarmOnly) {\n // Update VBO\n var offset = 0;\n for (var index = 0; index < this._particles.length; index++) {\n var particle = this._particles[index];\n this._appendParticleVertices(offset, particle);\n offset += this._useInstancing ? 1 : 4;\n }\n if (this._vertexBuffer) {\n this._vertexBuffer.update(this._vertexData);\n }\n }\n if (this.manualEmitCount === 0 && this.disposeOnStop) {\n this.stop();\n }\n };\n ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {\n this._appendParticleVertex(offset++, particle, 0, 0);\n if (!this._useInstancing) {\n this._appendParticleVertex(offset++, particle, 1, 0);\n this._appendParticleVertex(offset++, particle, 1, 1);\n this._appendParticleVertex(offset++, particle, 0, 1);\n }\n };\n /**\n * Rebuilds the particle system.\n */\n ParticleSystem.prototype.rebuild = function () {\n this._createIndexBuffer();\n if (this._vertexBuffer) {\n this._vertexBuffer._rebuild();\n }\n };\n /**\n * Is this system ready to be used/rendered\n * @return true if the system is ready\n */\n ParticleSystem.prototype.isReady = function () {\n var effect = this._getEffect();\n if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {\n return false;\n }\n return true;\n };\n /**\n * Renders the particle system in its current state.\n * @returns the current number of particles\n */\n ParticleSystem.prototype.render = function () {\n var effect = this._getEffect();\n // Check\n if (!this.isReady() || !this._particles.length) {\n return 0;\n }\n var engine = this._scene.getEngine();\n // Render\n engine.enableEffect(effect);\n engine.setState(false);\n var viewMatrix = this._scene.getViewMatrix();\n effect.setTexture(\"diffuseSampler\", this.particleTexture);\n effect.setMatrix(\"view\", viewMatrix);\n effect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n if (this._isAnimationSheetEnabled && this.particleTexture) {\n var baseSize = this.particleTexture.getBaseSize();\n effect.setFloat3(\"particlesInfos\", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);\n }\n effect.setVector2(\"translationPivot\", this.translationPivot);\n effect.setFloat4(\"textureMask\", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);\n if (this._isBillboardBased) {\n var camera = this._scene.activeCamera;\n effect.setVector3(\"eyePosition\", camera.globalPosition);\n }\n if (this._scene.clipPlane) {\n var clipPlane = this._scene.clipPlane;\n var invView = viewMatrix.clone();\n invView.invert();\n effect.setMatrix(\"invView\", invView);\n effect.setFloat4(\"vClipPlane\", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);\n }\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n // Draw order\n switch (this.blendMode) {\n case ParticleSystem.BLENDMODE_ADD:\n engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);\n break;\n case ParticleSystem.BLENDMODE_ONEONE:\n engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);\n break;\n case ParticleSystem.BLENDMODE_STANDARD:\n engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);\n break;\n }\n if (this.forceDepthWrite) {\n engine.setDepthWrite(true);\n }\n if (this._useInstancing) {\n engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);\n engine.unbindInstanceAttributes();\n }\n else {\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);\n }\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n return this._particles.length;\n };\n /**\n * Disposes the particle system and free the associated resources\n * @param disposeTexture defines if the particule texture must be disposed as well (true by default)\n */\n ParticleSystem.prototype.dispose = function (disposeTexture) {\n if (disposeTexture === void 0) { disposeTexture = true; }\n if (this._vertexBuffer) {\n this._vertexBuffer.dispose();\n this._vertexBuffer = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n if (disposeTexture && this.particleTexture) {\n this.particleTexture.dispose();\n this.particleTexture = null;\n }\n if (disposeTexture && this.noiseTexture) {\n this.noiseTexture.dispose();\n this.noiseTexture = null;\n }\n this._removeFromRoot();\n // Remove from scene\n var index = this._scene.particleSystems.indexOf(this);\n if (index > -1) {\n this._scene.particleSystems.splice(index, 1);\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n };\n /**\n * Creates a Point Emitter for the particle system (emits directly from the emitter position)\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the box\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the box\n * @returns the emitter\n */\n ParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {\n var particleEmitter = new BABYLON.PointParticleEmitter();\n particleEmitter.direction1 = direction1;\n particleEmitter.direction2 = direction2;\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n };\n /**\n * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)\n * @param radius The radius of the hemisphere to emit from\n * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius\n * @returns the emitter\n */\n ParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {\n if (radius === void 0) { radius = 1; }\n if (radiusRange === void 0) { radiusRange = 1; }\n var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n };\n /**\n * Creates a Sphere Emitter for the particle system (emits along the sphere radius)\n * @param radius The radius of the sphere to emit from\n * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius\n * @returns the emitter\n */\n ParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {\n if (radius === void 0) { radius = 1; }\n if (radiusRange === void 0) { radiusRange = 1; }\n var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n };\n /**\n * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)\n * @param radius The radius of the sphere to emit from\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere\n * @returns the emitter\n */\n ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {\n if (radius === void 0) { radius = 1; }\n if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }\n if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }\n var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n };\n /**\n * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)\n * @param radius The radius of the cone to emit from\n * @param angle The base angle of the cone\n * @returns the emitter\n */\n ParticleSystem.prototype.createConeEmitter = function (radius, angle) {\n if (radius === void 0) { radius = 1; }\n if (angle === void 0) { angle = Math.PI / 4; }\n var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n };\n /**\n * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the box\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the box\n * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox\n * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox\n * @returns the emitter\n */\n ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {\n var particleEmitter = new BABYLON.BoxParticleEmitter();\n this.particleEmitterType = particleEmitter;\n this.direction1 = direction1;\n this.direction2 = direction2;\n this.minEmitBox = minEmitBox;\n this.maxEmitBox = maxEmitBox;\n return particleEmitter;\n };\n // Clone\n /**\n * Clones the particle system.\n * @param name The name of the cloned object\n * @param newEmitter The new emitter to use\n * @returns the cloned particle system\n */\n ParticleSystem.prototype.clone = function (name, newEmitter) {\n var custom = null;\n var program = null;\n if (this.customShader != null) {\n program = this.customShader;\n var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join(\"\\n\") : \"\";\n custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);\n }\n else if (this._customEffect) {\n custom = this._customEffect;\n }\n var result = new ParticleSystem(name, this._capacity, this._scene, custom);\n result.customShader = program;\n BABYLON.Tools.DeepCopy(this, result, [\"particles\", \"customShader\"]);\n if (newEmitter === undefined) {\n newEmitter = this.emitter;\n }\n result.emitter = newEmitter;\n if (this.particleTexture) {\n result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);\n }\n if (!this.preventAutoStart) {\n result.start();\n }\n return result;\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n ParticleSystem.prototype.serialize = function () {\n var serializationObject = {};\n ParticleSystem._Serialize(serializationObject, this);\n serializationObject.textureMask = this.textureMask.asArray();\n serializationObject.customShader = this.customShader;\n serializationObject.preventAutoStart = this.preventAutoStart;\n serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;\n return serializationObject;\n };\n /** @hidden */\n ParticleSystem._Serialize = function (serializationObject, particleSystem) {\n serializationObject.name = particleSystem.name;\n serializationObject.id = particleSystem.id;\n serializationObject.capacity = particleSystem.getCapacity();\n // Emitter\n if (particleSystem.emitter.position) {\n var emitterMesh = particleSystem.emitter;\n serializationObject.emitterId = emitterMesh.id;\n }\n else {\n var emitterPosition = particleSystem.emitter;\n serializationObject.emitter = emitterPosition.asArray();\n }\n // Emitter\n if (particleSystem.particleEmitterType) {\n serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();\n }\n if (particleSystem.particleTexture) {\n serializationObject.textureName = particleSystem.particleTexture.name;\n }\n // Animations\n BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);\n // Particle system\n serializationObject.renderingGroupId = particleSystem.renderingGroupId;\n serializationObject.isBillboardBased = particleSystem.isBillboardBased;\n serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;\n serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;\n serializationObject.minSize = particleSystem.minSize;\n serializationObject.maxSize = particleSystem.maxSize;\n serializationObject.minScaleX = particleSystem.minScaleX;\n serializationObject.maxScaleX = particleSystem.maxScaleX;\n serializationObject.minScaleY = particleSystem.minScaleY;\n serializationObject.maxScaleY = particleSystem.maxScaleY;\n serializationObject.minEmitPower = particleSystem.minEmitPower;\n serializationObject.maxEmitPower = particleSystem.maxEmitPower;\n serializationObject.minLifeTime = particleSystem.minLifeTime;\n serializationObject.maxLifeTime = particleSystem.maxLifeTime;\n serializationObject.emitRate = particleSystem.emitRate;\n serializationObject.gravity = particleSystem.gravity.asArray();\n serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();\n serializationObject.color1 = particleSystem.color1.asArray();\n serializationObject.color2 = particleSystem.color2.asArray();\n serializationObject.colorDead = particleSystem.colorDead.asArray();\n serializationObject.updateSpeed = particleSystem.updateSpeed;\n serializationObject.targetStopDuration = particleSystem.targetStopDuration;\n serializationObject.blendMode = particleSystem.blendMode;\n serializationObject.preWarmCycles = particleSystem.preWarmCycles;\n serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;\n serializationObject.minInitialRotation = particleSystem.minInitialRotation;\n serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;\n serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;\n serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;\n serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;\n serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;\n serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;\n var colorGradients = particleSystem.getColorGradients();\n if (colorGradients) {\n serializationObject.colorGradients = [];\n for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {\n var colorGradient = colorGradients_1[_i];\n var serializedGradient = {\n gradient: colorGradient.gradient,\n color1: colorGradient.color1.asArray()\n };\n if (colorGradient.color2) {\n serializedGradient.color2 = colorGradient.color2.asArray();\n }\n serializationObject.colorGradients.push(serializedGradient);\n }\n }\n var sizeGradients = particleSystem.getSizeGradients();\n if (sizeGradients) {\n serializationObject.sizeGradients = [];\n for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {\n var sizeGradient = sizeGradients_1[_a];\n var serializedGradient = {\n gradient: sizeGradient.gradient,\n factor1: sizeGradient.factor1\n };\n if (sizeGradient.factor2 !== undefined) {\n serializedGradient.factor2 = sizeGradient.factor2;\n }\n serializationObject.sizeGradients.push(serializedGradient);\n }\n }\n var angularSpeedGradients = particleSystem.getAngularSpeedGradients();\n if (angularSpeedGradients) {\n serializationObject.angularSpeedGradients = [];\n for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {\n var angularSpeedGradient = angularSpeedGradients_1[_b];\n var serializedGradient = {\n gradient: angularSpeedGradient.gradient,\n factor1: angularSpeedGradient.factor1\n };\n if (angularSpeedGradient.factor2 !== undefined) {\n serializedGradient.factor2 = angularSpeedGradient.factor2;\n }\n serializationObject.angularSpeedGradients.push(serializedGradient);\n }\n }\n var velocityGradients = particleSystem.getVelocityGradients();\n if (velocityGradients) {\n serializationObject.velocityGradients = [];\n for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {\n var velocityGradient = velocityGradients_1[_c];\n var serializedGradient = {\n gradient: velocityGradient.gradient,\n factor1: velocityGradient.factor1\n };\n if (velocityGradient.factor2 !== undefined) {\n serializedGradient.factor2 = velocityGradient.factor2;\n }\n serializationObject.velocityGradients.push(serializedGradient);\n }\n }\n if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {\n var noiseTexture = particleSystem.noiseTexture;\n serializationObject.noiseTexture = noiseTexture.serialize();\n }\n };\n /** @hidden */\n ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {\n // Texture\n if (parsedParticleSystem.textureName) {\n particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);\n particleSystem.particleTexture.name = parsedParticleSystem.textureName;\n }\n // Emitter\n if (parsedParticleSystem.emitterId === undefined) {\n particleSystem.emitter = BABYLON.Vector3.Zero();\n }\n else if (parsedParticleSystem.emitterId) {\n particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);\n }\n else {\n particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);\n }\n // Misc.\n if (parsedParticleSystem.renderingGroupId !== undefined) {\n particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;\n }\n if (parsedParticleSystem.isBillboardBased !== undefined) {\n particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;\n }\n // Animations\n if (parsedParticleSystem.animations) {\n for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {\n var parsedAnimation = parsedParticleSystem.animations[animationIndex];\n particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n }\n if (parsedParticleSystem.autoAnimate) {\n scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);\n }\n // Particle system\n particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;\n particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;\n particleSystem.minSize = parsedParticleSystem.minSize;\n particleSystem.maxSize = parsedParticleSystem.maxSize;\n if (parsedParticleSystem.minScaleX) {\n particleSystem.minScaleX = parsedParticleSystem.minScaleX;\n particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;\n particleSystem.minScaleY = parsedParticleSystem.minScaleY;\n particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;\n }\n if (parsedParticleSystem.preWarmCycles !== undefined) {\n particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;\n particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;\n }\n if (parsedParticleSystem.minInitialRotation !== undefined) {\n particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;\n particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;\n }\n particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;\n particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;\n particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;\n particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;\n particleSystem.emitRate = parsedParticleSystem.emitRate;\n particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);\n if (parsedParticleSystem.noiseStrength) {\n particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);\n }\n particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);\n particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);\n particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);\n particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;\n particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;\n particleSystem.blendMode = parsedParticleSystem.blendMode;\n if (parsedParticleSystem.colorGradients) {\n for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {\n var colorGradient = _a[_i];\n particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);\n }\n }\n if (parsedParticleSystem.sizeGradients) {\n for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {\n var sizeGradient = _c[_b];\n particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);\n }\n }\n if (parsedParticleSystem.angularSpeedGradients) {\n for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {\n var angularSpeedGradient = _e[_d];\n particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);\n }\n }\n if (parsedParticleSystem.velocityGradients) {\n for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {\n var velocityGradient = _g[_f];\n particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);\n }\n }\n if (parsedParticleSystem.noiseTexture) {\n particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);\n }\n // Emitter\n var emitterType;\n if (parsedParticleSystem.particleEmitterType) {\n switch (parsedParticleSystem.particleEmitterType.type) {\n case \"SphereParticleEmitter\":\n emitterType = new BABYLON.SphereParticleEmitter();\n break;\n case \"SphereDirectedParticleEmitter\":\n emitterType = new BABYLON.SphereDirectedParticleEmitter();\n break;\n case \"ConeEmitter\":\n case \"ConeParticleEmitter\":\n emitterType = new BABYLON.ConeParticleEmitter();\n break;\n case \"BoxEmitter\":\n case \"BoxParticleEmitter\":\n default:\n emitterType = new BABYLON.BoxParticleEmitter();\n break;\n }\n emitterType.parse(parsedParticleSystem.particleEmitterType);\n }\n else {\n emitterType = new BABYLON.BoxParticleEmitter();\n emitterType.parse(parsedParticleSystem);\n }\n particleSystem.particleEmitterType = emitterType;\n // Animation sheet\n particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;\n particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;\n particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;\n particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;\n particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;\n };\n /**\n * Parses a JSON object to create a particle system.\n * @param parsedParticleSystem The JSON object to parse\n * @param scene The scene to create the particle system in\n * @param rootUrl The root url to use to load external dependencies like texture\n * @returns the Parsed particle system\n */\n ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {\n var name = parsedParticleSystem.name;\n var custom = null;\n var program = null;\n if (parsedParticleSystem.customShader) {\n program = parsedParticleSystem.customShader;\n var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join(\"\\n\") : \"\";\n custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);\n }\n var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);\n particleSystem.customShader = program;\n if (parsedParticleSystem.id) {\n particleSystem.id = parsedParticleSystem.id;\n }\n // Auto start\n if (parsedParticleSystem.preventAutoStart) {\n particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;\n }\n ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);\n particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);\n if (!particleSystem.preventAutoStart) {\n particleSystem.start();\n }\n return particleSystem;\n };\n /**\n * Source color is added to the destination color without alpha affecting the result.\n */\n ParticleSystem.BLENDMODE_ONEONE = 0;\n /**\n * Blend current color and particle color using particle’s alpha.\n */\n ParticleSystem.BLENDMODE_STANDARD = 1;\n /**\n * Add current color and particle color multiplied by particle’s alpha.\n */\n ParticleSystem.BLENDMODE_ADD = 2;\n return ParticleSystem;\n }());\n BABYLON.ParticleSystem = ParticleSystem;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.particleSystem.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Particle emitter emitting particles from the inside of a box.\n * It emits the particles randomly between 2 given directions.\n */\n var BoxParticleEmitter = /** @class */ (function () {\n /**\n * Creates a new instance BoxParticleEmitter\n */\n function BoxParticleEmitter() {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction1 = new BABYLON.Vector3(0, 1.0, 0);\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction2 = new BABYLON.Vector3(0, 1.0, 0);\n /**\n * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n */\n this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);\n /**\n * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n */\n this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n */\n BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {\n var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);\n var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);\n var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n };\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n */\n BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {\n var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);\n var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);\n var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);\n };\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n BoxParticleEmitter.prototype.clone = function () {\n var newOne = new BoxParticleEmitter();\n BABYLON.Tools.DeepCopy(this, newOne);\n return newOne;\n };\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param effect defines the update shader\n */\n BoxParticleEmitter.prototype.applyToShader = function (effect) {\n effect.setVector3(\"direction1\", this.direction1);\n effect.setVector3(\"direction2\", this.direction2);\n effect.setVector3(\"minEmitBox\", this.minEmitBox);\n effect.setVector3(\"maxEmitBox\", this.maxEmitBox);\n };\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containng the defines string\n */\n BoxParticleEmitter.prototype.getEffectDefines = function () {\n return \"#define BOXEMITTER\";\n };\n /**\n * Returns the string \"BoxParticleEmitter\"\n * @returns a string containing the class name\n */\n BoxParticleEmitter.prototype.getClassName = function () {\n return \"BoxParticleEmitter\";\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n BoxParticleEmitter.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n serializationObject.minEmitBox = this.minEmitBox.asArray();\n serializationObject.maxEmitBox = this.maxEmitBox.asArray();\n return serializationObject;\n };\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n BoxParticleEmitter.prototype.parse = function (serializationObject) {\n BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);\n BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);\n BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);\n BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);\n };\n return BoxParticleEmitter;\n }());\n BABYLON.BoxParticleEmitter = BoxParticleEmitter;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boxParticleEmitter.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Particle emitter emitting particles from the inside of a cone.\n * It emits the particles alongside the cone volume from the base to the particle.\n * The emission direction might be randomized.\n */\n var ConeParticleEmitter = /** @class */ (function () {\n /**\n * Creates a new instance ConeParticleEmitter\n * @param radius the radius of the emission cone (1 by default)\n * @param angles the cone base angle (PI by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)\n */\n function ConeParticleEmitter(radius, angle, \n /** defines how much to randomize the particle direction [0-1] (default is 0) */\n directionRandomizer) {\n if (radius === void 0) { radius = 1; }\n if (angle === void 0) { angle = Math.PI; }\n if (directionRandomizer === void 0) { directionRandomizer = 0; }\n this.directionRandomizer = directionRandomizer;\n /**\n * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)\n */\n this.radiusRange = 1;\n /**\n * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)\n */\n this.heightRange = 1;\n /**\n * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)\n */\n this.emitFromSpawnPointOnly = false;\n this.angle = angle;\n this.radius = radius;\n }\n Object.defineProperty(ConeParticleEmitter.prototype, \"radius\", {\n /**\n * Gets or sets the radius of the emission cone\n */\n get: function () {\n return this._radius;\n },\n set: function (value) {\n this._radius = value;\n this._buildHeight();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ConeParticleEmitter.prototype, \"angle\", {\n /**\n * Gets or sets the angle of the emission cone\n */\n get: function () {\n return this._angle;\n },\n set: function (value) {\n this._angle = value;\n this._buildHeight();\n },\n enumerable: true,\n configurable: true\n });\n ConeParticleEmitter.prototype._buildHeight = function () {\n if (this._angle !== 0) {\n this._height = this._radius / Math.tan(this._angle / 2);\n }\n else {\n this._height = 1;\n }\n };\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n */\n ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {\n if (Math.abs(Math.cos(this._angle)) === 1.0) {\n BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);\n }\n else {\n // measure the direction Vector from the emitter to the particle.\n var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();\n var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n direction.x += randX;\n direction.y += randY;\n direction.z += randZ;\n direction.normalize();\n BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);\n }\n };\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n */\n ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {\n var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);\n var h;\n if (!this.emitFromSpawnPointOnly) {\n h = BABYLON.Scalar.RandomRange(0, this.heightRange);\n // Better distribution in a cone at normal angles.\n h = 1 - h * h;\n }\n else {\n h = 0.0001;\n }\n var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);\n radius = radius * h;\n var randX = radius * Math.sin(s);\n var randZ = radius * Math.cos(s);\n var randY = h * this._height;\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);\n };\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n ConeParticleEmitter.prototype.clone = function () {\n var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);\n BABYLON.Tools.DeepCopy(this, newOne);\n return newOne;\n };\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param effect defines the update shader\n */\n ConeParticleEmitter.prototype.applyToShader = function (effect) {\n effect.setFloat2(\"radius\", this._radius, this.radiusRange);\n effect.setFloat(\"coneAngle\", this._angle);\n effect.setFloat2(\"height\", this._height, this.heightRange);\n effect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n };\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containng the defines string\n */\n ConeParticleEmitter.prototype.getEffectDefines = function () {\n var defines = \"#define CONEEMITTER\";\n if (this.emitFromSpawnPointOnly) {\n defines += \"\\n#define CONEEMITTERSPAWNPOINT\";\n }\n return defines;\n };\n /**\n * Returns the string \"ConeParticleEmitter\"\n * @returns a string containing the class name\n */\n ConeParticleEmitter.prototype.getClassName = function () {\n return \"ConeParticleEmitter\";\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n ConeParticleEmitter.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this._radius;\n serializationObject.angle = this._angle;\n serializationObject.directionRandomizer = this.directionRandomizer;\n return serializationObject;\n };\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n ConeParticleEmitter.prototype.parse = function (serializationObject) {\n this.radius = serializationObject.radius;\n this.angle = serializationObject.angle;\n this.directionRandomizer = serializationObject.directionRandomizer;\n };\n return ConeParticleEmitter;\n }());\n BABYLON.ConeParticleEmitter = ConeParticleEmitter;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.coneParticleEmitter.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Particle emitter emitting particles from the inside of a sphere.\n * It emits the particles alongside the sphere radius. The emission direction might be randomized.\n */\n var SphereParticleEmitter = /** @class */ (function () {\n /**\n * Creates a new instance SphereParticleEmitter\n * @param radius the radius of the emission sphere (1 by default)\n * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1]\n */\n function SphereParticleEmitter(\n /**\n * The radius of the emission sphere.\n */\n radius, \n /**\n * The range of emission [0-1] 0 Surface only, 1 Entire Radius.\n */\n radiusRange, \n /**\n * How much to randomize the particle direction [0-1].\n */\n directionRandomizer) {\n if (radius === void 0) { radius = 1; }\n if (radiusRange === void 0) { radiusRange = 1; }\n if (directionRandomizer === void 0) { directionRandomizer = 0; }\n this.radius = radius;\n this.radiusRange = radiusRange;\n this.directionRandomizer = directionRandomizer;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n */\n SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {\n var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();\n var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n direction.x += randX;\n direction.y += randY;\n direction.z += randZ;\n direction.normalize();\n BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);\n };\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n */\n SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {\n var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);\n var v = BABYLON.Scalar.RandomRange(0, 1.0);\n var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);\n var theta = Math.acos(2 * v - 1);\n var randX = randRadius * Math.cos(phi) * Math.sin(theta);\n var randY = randRadius * Math.cos(theta);\n var randZ = randRadius * Math.sin(phi) * Math.sin(theta);\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);\n };\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n SphereParticleEmitter.prototype.clone = function () {\n var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);\n BABYLON.Tools.DeepCopy(this, newOne);\n return newOne;\n };\n /**\n * Called by the {BABYLON.GPUParticleSystem} to setup the update shader\n * @param effect defines the update shader\n */\n SphereParticleEmitter.prototype.applyToShader = function (effect) {\n effect.setFloat(\"radius\", this.radius);\n effect.setFloat(\"radiusRange\", this.radiusRange);\n effect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n };\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containng the defines string\n */\n SphereParticleEmitter.prototype.getEffectDefines = function () {\n return \"#define SPHEREEMITTER\";\n };\n /**\n * Returns the string \"SphereParticleEmitter\"\n * @returns a string containing the class name\n */\n SphereParticleEmitter.prototype.getClassName = function () {\n return \"SphereParticleEmitter\";\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n SphereParticleEmitter.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this.radius;\n serializationObject.radiusRange = this.radiusRange;\n serializationObject.directionRandomizer = this.directionRandomizer;\n return serializationObject;\n };\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n SphereParticleEmitter.prototype.parse = function (serializationObject) {\n this.radius = serializationObject.radius;\n this.radiusRange = serializationObject.radiusRange;\n this.directionRandomizer = serializationObject.directionRandomizer;\n };\n return SphereParticleEmitter;\n }());\n BABYLON.SphereParticleEmitter = SphereParticleEmitter;\n /**\n * Particle emitter emitting particles from the inside of a sphere.\n * It emits the particles randomly between two vectors.\n */\n var SphereDirectedParticleEmitter = /** @class */ (function (_super) {\n __extends(SphereDirectedParticleEmitter, _super);\n /**\n * Creates a new instance SphereDirectedParticleEmitter\n * @param radius the radius of the emission sphere (1 by default)\n * @param direction1 the min limit of the emission direction (up vector by default)\n * @param direction2 the max limit of the emission direction (up vector by default)\n */\n function SphereDirectedParticleEmitter(radius, \n /**\n * The min limit of the emission direction.\n */\n direction1, \n /**\n * The max limit of the emission direction.\n */\n direction2) {\n if (radius === void 0) { radius = 1; }\n if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }\n if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }\n var _this = _super.call(this, radius) || this;\n _this.direction1 = direction1;\n _this.direction2 = direction2;\n return _this;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n */\n SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {\n var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);\n var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);\n var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n };\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n SphereDirectedParticleEmitter.prototype.clone = function () {\n var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);\n BABYLON.Tools.DeepCopy(this, newOne);\n return newOne;\n };\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param effect defines the update shader\n */\n SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {\n effect.setFloat(\"radius\", this.radius);\n effect.setFloat(\"radiusRange\", this.radiusRange);\n effect.setVector3(\"direction1\", this.direction1);\n effect.setVector3(\"direction2\", this.direction2);\n };\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containng the defines string\n */\n SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {\n return \"#define SPHEREEMITTER\\n#define DIRECTEDSPHEREEMITTER\";\n };\n /**\n * Returns the string \"SphereDirectedParticleEmitter\"\n * @returns a string containing the class name\n */\n SphereDirectedParticleEmitter.prototype.getClassName = function () {\n return \"SphereDirectedParticleEmitter\";\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n SphereDirectedParticleEmitter.prototype.serialize = function () {\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n return serializationObject;\n };\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {\n _super.prototype.parse.call(this, serializationObject);\n this.direction1.copyFrom(serializationObject.direction1);\n this.direction2.copyFrom(serializationObject.direction2);\n };\n return SphereDirectedParticleEmitter;\n }(SphereParticleEmitter));\n BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sphereParticleEmitter.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Particle emitter emitting particles from the inside of a hemisphere.\n * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.\n */\n var HemisphericParticleEmitter = /** @class */ (function () {\n /**\n * Creates a new instance HemisphericParticleEmitter\n * @param radius the radius of the emission hemisphere (1 by default)\n * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1]\n */\n function HemisphericParticleEmitter(\n /**\n * The radius of the emission hemisphere.\n */\n radius, \n /**\n * The range of emission [0-1] 0 Surface only, 1 Entire Radius.\n */\n radiusRange, \n /**\n * How much to randomize the particle direction [0-1].\n */\n directionRandomizer) {\n if (radius === void 0) { radius = 1; }\n if (radiusRange === void 0) { radiusRange = 1; }\n if (directionRandomizer === void 0) { directionRandomizer = 0; }\n this.radius = radius;\n this.radiusRange = radiusRange;\n this.directionRandomizer = directionRandomizer;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n */\n HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {\n var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();\n var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);\n direction.x += randX;\n direction.y += randY;\n direction.z += randZ;\n direction.normalize();\n BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);\n };\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n */\n HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {\n var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);\n var v = BABYLON.Scalar.RandomRange(0, 1.0);\n var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);\n var theta = Math.acos(2 * v - 1);\n var randX = randRadius * Math.cos(phi) * Math.sin(theta);\n var randY = randRadius * Math.cos(theta);\n var randZ = randRadius * Math.sin(phi) * Math.sin(theta);\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);\n };\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n HemisphericParticleEmitter.prototype.clone = function () {\n var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);\n BABYLON.Tools.DeepCopy(this, newOne);\n return newOne;\n };\n /**\n * Called by the {BABYLON.GPUParticleSystem} to setup the update shader\n * @param effect defines the update shader\n */\n HemisphericParticleEmitter.prototype.applyToShader = function (effect) {\n effect.setFloat(\"radius\", this.radius);\n effect.setFloat(\"radiusRange\", this.radiusRange);\n effect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n };\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containng the defines string\n */\n HemisphericParticleEmitter.prototype.getEffectDefines = function () {\n return \"#define HEMISPHERICEMITTER\";\n };\n /**\n * Returns the string \"HemisphericParticleEmitter\"\n * @returns a string containing the class name\n */\n HemisphericParticleEmitter.prototype.getClassName = function () {\n return \"HemisphericParticleEmitter\";\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n HemisphericParticleEmitter.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this.radius;\n serializationObject.radiusRange = this.radiusRange;\n serializationObject.directionRandomizer = this.directionRandomizer;\n return serializationObject;\n };\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n HemisphericParticleEmitter.prototype.parse = function (serializationObject) {\n this.radius = serializationObject.radius;\n this.radiusRange = serializationObject.radiusRange;\n this.directionRandomizer = serializationObject.directionRandomizer;\n };\n return HemisphericParticleEmitter;\n }());\n BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Particle emitter emitting particles from a point.\n * It emits the particles randomly between 2 given directions.\n */\n var PointParticleEmitter = /** @class */ (function () {\n /**\n * Creates a new instance PointParticleEmitter\n */\n function PointParticleEmitter() {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction1 = new BABYLON.Vector3(0, 1.0, 0);\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction2 = new BABYLON.Vector3(0, 1.0, 0);\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n */\n PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {\n var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);\n var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);\n var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n };\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n */\n PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);\n };\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n PointParticleEmitter.prototype.clone = function () {\n var newOne = new PointParticleEmitter();\n BABYLON.Tools.DeepCopy(this, newOne);\n return newOne;\n };\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param effect defines the update shader\n */\n PointParticleEmitter.prototype.applyToShader = function (effect) {\n effect.setVector3(\"direction1\", this.direction1);\n effect.setVector3(\"direction2\", this.direction2);\n };\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containng the defines string\n */\n PointParticleEmitter.prototype.getEffectDefines = function () {\n return \"#define POINTEMITTER\";\n };\n /**\n * Returns the string \"PointParticleEmitter\"\n * @returns a string containing the class name\n */\n PointParticleEmitter.prototype.getClassName = function () {\n return \"PointParticleEmitter\";\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n PointParticleEmitter.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n return serializationObject;\n };\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n PointParticleEmitter.prototype.parse = function (serializationObject) {\n BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);\n BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);\n };\n return PointParticleEmitter;\n }());\n BABYLON.PointParticleEmitter = PointParticleEmitter;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pointParticleEmitter.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n // Adds the parsers to the scene parsers.\n BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {\n var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);\n if (!individualParser) {\n return;\n }\n // Particles Systems\n if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {\n for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {\n var parsedParticleSystem = parsedData.particleSystems[index];\n container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));\n }\n }\n });\n BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {\n if (parsedParticleSystem.activeParticleCount) {\n var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);\n return ps;\n }\n else {\n var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);\n return ps;\n }\n });\n BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {\n if (uniformsNames === void 0) { uniformsNames = []; }\n if (samplers === void 0) { samplers = []; }\n if (defines === void 0) { defines = \"\"; }\n var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();\n var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();\n if (defines.indexOf(\" BILLBOARD\") === -1) {\n defines += \"\\n#define BILLBOARD\\n\";\n }\n if (samplers.indexOf(\"diffuseSampler\") === -1) {\n samplers.push(\"diffuseSampler\");\n }\n return this.createEffect({\n vertex: \"particles\",\n fragmentElement: fragmentName\n }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);\n };\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.particleSystemComponent.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ShaderMaterial = /** @class */ (function (_super) {\n __extends(ShaderMaterial, _super);\n function ShaderMaterial(name, scene, shaderPath, options) {\n var _this = _super.call(this, name, scene) || this;\n _this._textures = {};\n _this._textureArrays = {};\n _this._floats = {};\n _this._ints = {};\n _this._floatsArrays = {};\n _this._colors3 = {};\n _this._colors3Arrays = {};\n _this._colors4 = {};\n _this._vectors2 = {};\n _this._vectors3 = {};\n _this._vectors4 = {};\n _this._matrices = {};\n _this._matrices3x3 = {};\n _this._matrices2x2 = {};\n _this._vectors2Arrays = {};\n _this._vectors3Arrays = {};\n _this._cachedWorldViewMatrix = new BABYLON.Matrix();\n _this._shaderPath = shaderPath;\n options.needAlphaBlending = options.needAlphaBlending || false;\n options.needAlphaTesting = options.needAlphaTesting || false;\n options.attributes = options.attributes || [\"position\", \"normal\", \"uv\"];\n options.uniforms = options.uniforms || [\"worldViewProjection\"];\n options.uniformBuffers = options.uniformBuffers || [];\n options.samplers = options.samplers || [];\n options.defines = options.defines || [];\n _this._options = options;\n return _this;\n }\n ShaderMaterial.prototype.getClassName = function () {\n return \"ShaderMaterial\";\n };\n ShaderMaterial.prototype.needAlphaBlending = function () {\n return this._options.needAlphaBlending;\n };\n ShaderMaterial.prototype.needAlphaTesting = function () {\n return this._options.needAlphaTesting;\n };\n ShaderMaterial.prototype._checkUniform = function (uniformName) {\n if (this._options.uniforms.indexOf(uniformName) === -1) {\n this._options.uniforms.push(uniformName);\n }\n };\n ShaderMaterial.prototype.setTexture = function (name, texture) {\n if (this._options.samplers.indexOf(name) === -1) {\n this._options.samplers.push(name);\n }\n this._textures[name] = texture;\n return this;\n };\n ShaderMaterial.prototype.setTextureArray = function (name, textures) {\n if (this._options.samplers.indexOf(name) === -1) {\n this._options.samplers.push(name);\n }\n this._checkUniform(name);\n this._textureArrays[name] = textures;\n return this;\n };\n ShaderMaterial.prototype.setFloat = function (name, value) {\n this._checkUniform(name);\n this._floats[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setInt = function (name, value) {\n this._checkUniform(name);\n this._ints[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setFloats = function (name, value) {\n this._checkUniform(name);\n this._floatsArrays[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setColor3 = function (name, value) {\n this._checkUniform(name);\n this._colors3[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setColor3Array = function (name, value) {\n this._checkUniform(name);\n this._colors3Arrays[name] = value.reduce(function (arr, color) {\n color.toArray(arr, arr.length);\n return arr;\n }, []);\n return this;\n };\n ShaderMaterial.prototype.setColor4 = function (name, value) {\n this._checkUniform(name);\n this._colors4[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setVector2 = function (name, value) {\n this._checkUniform(name);\n this._vectors2[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setVector3 = function (name, value) {\n this._checkUniform(name);\n this._vectors3[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setVector4 = function (name, value) {\n this._checkUniform(name);\n this._vectors4[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setMatrix = function (name, value) {\n this._checkUniform(name);\n this._matrices[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {\n this._checkUniform(name);\n this._matrices3x3[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {\n this._checkUniform(name);\n this._matrices2x2[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setArray2 = function (name, value) {\n this._checkUniform(name);\n this._vectors2Arrays[name] = value;\n return this;\n };\n ShaderMaterial.prototype.setArray3 = function (name, value) {\n this._checkUniform(name);\n this._vectors3Arrays[name] = value;\n return this;\n };\n ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {\n if (!mesh) {\n return true;\n }\n if (this._effect && (this._effect.defines.indexOf(\"#define INSTANCES\") !== -1) !== useInstances) {\n return false;\n }\n return false;\n };\n ShaderMaterial.prototype.isReady = function (mesh, useInstances) {\n var scene = this.getScene();\n var engine = scene.getEngine();\n if (!this.checkReadyOnEveryCall) {\n if (this._renderId === scene.getRenderId()) {\n if (this._checkCache(scene, mesh, useInstances)) {\n return true;\n }\n }\n }\n // Instances\n var defines = [];\n var attribs = [];\n var fallbacks = new BABYLON.EffectFallbacks();\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n }\n for (var index = 0; index < this._options.defines.length; index++) {\n defines.push(this._options.defines[index]);\n }\n for (var index = 0; index < this._options.attributes.length; index++) {\n attribs.push(this._options.attributes[index]);\n }\n if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {\n attribs.push(BABYLON.VertexBuffer.ColorKind);\n defines.push(\"#define VERTEXCOLOR\");\n }\n // Bones\n if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton.bones.length + 1));\n fallbacks.addCPUSkinningFallback(0, mesh);\n if (this._options.uniforms.indexOf(\"mBones\") === -1) {\n this._options.uniforms.push(\"mBones\");\n }\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Textures\n for (var name in this._textures) {\n if (!this._textures[name].isReady()) {\n return false;\n }\n }\n // Alpha test\n if (mesh && this._shouldTurnAlphaTestOn(mesh)) {\n defines.push(\"#define ALPHATEST\");\n }\n var previousEffect = this._effect;\n var join = defines.join(\"\\n\");\n this._effect = engine.createEffect(this._shaderPath, {\n attributes: attribs,\n uniformsNames: this._options.uniforms,\n uniformBuffersNames: this._options.uniformBuffers,\n samplers: this._options.samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: this.onCompiled,\n onError: this.onError\n }, engine);\n if (!this._effect.isReady()) {\n return false;\n }\n if (previousEffect !== this._effect) {\n scene.resetCachedMaterial();\n }\n this._renderId = scene.getRenderId();\n return true;\n };\n ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {\n var scene = this.getScene();\n if (!this._effect) {\n return;\n }\n if (this._options.uniforms.indexOf(\"world\") !== -1) {\n this._effect.setMatrix(\"world\", world);\n }\n if (this._options.uniforms.indexOf(\"worldView\") !== -1) {\n world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);\n this._effect.setMatrix(\"worldView\", this._cachedWorldViewMatrix);\n }\n if (this._options.uniforms.indexOf(\"worldViewProjection\") !== -1) {\n this._effect.setMatrix(\"worldViewProjection\", world.multiply(scene.getTransformMatrix()));\n }\n };\n ShaderMaterial.prototype.bind = function (world, mesh) {\n // Std values\n this.bindOnlyWorldMatrix(world);\n if (this._effect && this.getScene().getCachedMaterial() !== this) {\n if (this._options.uniforms.indexOf(\"view\") !== -1) {\n this._effect.setMatrix(\"view\", this.getScene().getViewMatrix());\n }\n if (this._options.uniforms.indexOf(\"projection\") !== -1) {\n this._effect.setMatrix(\"projection\", this.getScene().getProjectionMatrix());\n }\n if (this._options.uniforms.indexOf(\"viewProjection\") !== -1) {\n this._effect.setMatrix(\"viewProjection\", this.getScene().getTransformMatrix());\n }\n // Bones\n BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);\n var name;\n // Texture\n for (name in this._textures) {\n this._effect.setTexture(name, this._textures[name]);\n }\n // Texture arrays\n for (name in this._textureArrays) {\n this._effect.setTextureArray(name, this._textureArrays[name]);\n }\n // Int \n for (name in this._ints) {\n this._effect.setInt(name, this._ints[name]);\n }\n // Float \n for (name in this._floats) {\n this._effect.setFloat(name, this._floats[name]);\n }\n // Floats \n for (name in this._floatsArrays) {\n this._effect.setArray(name, this._floatsArrays[name]);\n }\n // Color3 \n for (name in this._colors3) {\n this._effect.setColor3(name, this._colors3[name]);\n }\n for (name in this._colors3Arrays) {\n this._effect.setArray3(name, this._colors3Arrays[name]);\n }\n // Color4 \n for (name in this._colors4) {\n var color = this._colors4[name];\n this._effect.setFloat4(name, color.r, color.g, color.b, color.a);\n }\n // Vector2 \n for (name in this._vectors2) {\n this._effect.setVector2(name, this._vectors2[name]);\n }\n // Vector3 \n for (name in this._vectors3) {\n this._effect.setVector3(name, this._vectors3[name]);\n }\n // Vector4 \n for (name in this._vectors4) {\n this._effect.setVector4(name, this._vectors4[name]);\n }\n // Matrix \n for (name in this._matrices) {\n this._effect.setMatrix(name, this._matrices[name]);\n }\n // Matrix 3x3\n for (name in this._matrices3x3) {\n this._effect.setMatrix3x3(name, this._matrices3x3[name]);\n }\n // Matrix 2x2\n for (name in this._matrices2x2) {\n this._effect.setMatrix2x2(name, this._matrices2x2[name]);\n }\n // Vector2Array \n for (name in this._vectors2Arrays) {\n this._effect.setArray2(name, this._vectors2Arrays[name]);\n }\n // Vector3Array \n for (name in this._vectors3Arrays) {\n this._effect.setArray3(name, this._vectors3Arrays[name]);\n }\n }\n this._afterBind(mesh);\n };\n ShaderMaterial.prototype.getActiveTextures = function () {\n var activeTextures = _super.prototype.getActiveTextures.call(this);\n for (var name in this._textures) {\n activeTextures.push(this._textures[name]);\n }\n for (var name in this._textureArrays) {\n var array = this._textureArrays[name];\n for (var index = 0; index < array.length; index++) {\n activeTextures.push(array[index]);\n }\n }\n return activeTextures;\n };\n ShaderMaterial.prototype.hasTexture = function (texture) {\n if (_super.prototype.hasTexture.call(this, texture)) {\n return true;\n }\n for (var name in this._textures) {\n if (this._textures[name] === texture) {\n return true;\n }\n }\n for (var name in this._textureArrays) {\n var array = this._textureArrays[name];\n for (var index = 0; index < array.length; index++) {\n if (array[index] === texture) {\n return true;\n }\n }\n }\n return false;\n };\n ShaderMaterial.prototype.clone = function (name) {\n var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);\n return newShaderMaterial;\n };\n ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {\n if (forceDisposeTextures) {\n var name;\n for (name in this._textures) {\n this._textures[name].dispose();\n }\n for (name in this._textureArrays) {\n var array = this._textureArrays[name];\n for (var index = 0; index < array.length; index++) {\n array[index].dispose();\n }\n }\n }\n this._textures = {};\n _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);\n };\n ShaderMaterial.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.ShaderMaterial\";\n serializationObject.options = this._options;\n serializationObject.shaderPath = this._shaderPath;\n var name;\n // Texture\n serializationObject.textures = {};\n for (name in this._textures) {\n serializationObject.textures[name] = this._textures[name].serialize();\n }\n // Texture arrays\n serializationObject.textureArrays = {};\n for (name in this._textureArrays) {\n serializationObject.textureArrays[name] = [];\n var array = this._textureArrays[name];\n for (var index = 0; index < array.length; index++) {\n serializationObject.textureArrays[name].push(array[index].serialize());\n }\n }\n // Float \n serializationObject.floats = {};\n for (name in this._floats) {\n serializationObject.floats[name] = this._floats[name];\n }\n // Float s \n serializationObject.FloatArrays = {};\n for (name in this._floatsArrays) {\n serializationObject.FloatArrays[name] = this._floatsArrays[name];\n }\n // Color3 \n serializationObject.colors3 = {};\n for (name in this._colors3) {\n serializationObject.colors3[name] = this._colors3[name].asArray();\n }\n // Color3 array\n serializationObject.colors3Arrays = {};\n for (name in this._colors3Arrays) {\n serializationObject.colors3Arrays[name] = this._colors3Arrays[name];\n }\n // Color4 \n serializationObject.colors4 = {};\n for (name in this._colors4) {\n serializationObject.colors4[name] = this._colors4[name].asArray();\n }\n // Vector2 \n serializationObject.vectors2 = {};\n for (name in this._vectors2) {\n serializationObject.vectors2[name] = this._vectors2[name].asArray();\n }\n // Vector3 \n serializationObject.vectors3 = {};\n for (name in this._vectors3) {\n serializationObject.vectors3[name] = this._vectors3[name].asArray();\n }\n // Vector4 \n serializationObject.vectors4 = {};\n for (name in this._vectors4) {\n serializationObject.vectors4[name] = this._vectors4[name].asArray();\n }\n // Matrix \n serializationObject.matrices = {};\n for (name in this._matrices) {\n serializationObject.matrices[name] = this._matrices[name].asArray();\n }\n // Matrix 3x3\n serializationObject.matrices3x3 = {};\n for (name in this._matrices3x3) {\n serializationObject.matrices3x3[name] = this._matrices3x3[name];\n }\n // Matrix 2x2\n serializationObject.matrices2x2 = {};\n for (name in this._matrices2x2) {\n serializationObject.matrices2x2[name] = this._matrices2x2[name];\n }\n // Vector2Array\n serializationObject.vectors2Arrays = {};\n for (name in this._vectors2Arrays) {\n serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];\n }\n // Vector3Array\n serializationObject.vectors3Arrays = {};\n for (name in this._vectors3Arrays) {\n serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];\n }\n return serializationObject;\n };\n ShaderMaterial.Parse = function (source, scene, rootUrl) {\n var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);\n var name;\n // Texture\n for (name in source.textures) {\n material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));\n }\n // Texture arrays\n for (name in source.textureArrays) {\n var array = source.textureArrays[name];\n var textureArray = new Array();\n for (var index = 0; index < array.length; index++) {\n textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));\n }\n material.setTextureArray(name, textureArray);\n }\n // Float \n for (name in source.floats) {\n material.setFloat(name, source.floats[name]);\n }\n // Float s \n for (name in source.floatsArrays) {\n material.setFloats(name, source.floatsArrays[name]);\n }\n // Color3 \n for (name in source.colors3) {\n material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));\n }\n // Color3 arrays\n for (name in source.colors3Arrays) {\n var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {\n if (i % 3 === 0) {\n arr.push([num]);\n }\n else {\n arr[arr.length - 1].push(num);\n }\n return arr;\n }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });\n material.setColor3Array(name, colors);\n }\n // Color4 \n for (name in source.colors4) {\n material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));\n }\n // Vector2 \n for (name in source.vectors2) {\n material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));\n }\n // Vector3 \n for (name in source.vectors3) {\n material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));\n }\n // Vector4 \n for (name in source.vectors4) {\n material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));\n }\n // Matrix \n for (name in source.matrices) {\n material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));\n }\n // Matrix 3x3\n for (name in source.matrices3x3) {\n material.setMatrix3x3(name, source.matrices3x3[name]);\n }\n // Matrix 2x2\n for (name in source.matrices2x2) {\n material.setMatrix2x2(name, source.matrices2x2[name]);\n }\n // Vector2Array\n for (name in source.vectors2Arrays) {\n material.setArray2(name, source.vectors2Arrays[name]);\n }\n // Vector3Array\n for (name in source.vectors3Arrays) {\n material.setArray3(name, source.vectors3Arrays[name]);\n }\n return material;\n };\n return ShaderMaterial;\n }(BABYLON.Material));\n BABYLON.ShaderMaterial = ShaderMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.shaderMaterial.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GroundMesh = /** @class */ (function (_super) {\n __extends(GroundMesh, _super);\n function GroundMesh(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this.generateOctree = false;\n return _this;\n }\n GroundMesh.prototype.getClassName = function () {\n return \"GroundMesh\";\n };\n Object.defineProperty(GroundMesh.prototype, \"subdivisions\", {\n get: function () {\n return Math.min(this._subdivisionsX, this._subdivisionsY);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GroundMesh.prototype, \"subdivisionsX\", {\n get: function () {\n return this._subdivisionsX;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GroundMesh.prototype, \"subdivisionsY\", {\n get: function () {\n return this._subdivisionsY;\n },\n enumerable: true,\n configurable: true\n });\n GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {\n if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }\n this._subdivisionsX = chunksCount;\n this._subdivisionsY = chunksCount;\n this.subdivide(chunksCount);\n this.createOrUpdateSubmeshesOctree(octreeBlocksSize);\n };\n /**\n * Returns a height (y) value in the Worl system :\n * the ground altitude at the coordinates (x, z) expressed in the World system.\n * Returns the ground y position if (x, z) are outside the ground surface.\n */\n GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {\n var world = this.getWorldMatrix();\n var invMat = BABYLON.Tmp.Matrix[5];\n world.invertToRef(invMat);\n var tmpVect = BABYLON.Tmp.Vector3[8];\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space\n x = tmpVect.x;\n z = tmpVect.z;\n if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {\n return this.position.y;\n }\n if (!this._heightQuads || this._heightQuads.length == 0) {\n this._initHeightQuads();\n this._computeHeightQuads();\n }\n var facet = this._getFacetAt(x, z);\n var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;\n // return y in the World system\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);\n return tmpVect.y;\n };\n /**\n * Returns a normalized vector (Vector3) orthogonal to the ground\n * at the ground coordinates (x, z) expressed in the World system.\n * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.\n */\n GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {\n var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);\n this.getNormalAtCoordinatesToRef(x, z, normal);\n return normal;\n };\n /**\n * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground\n * at the ground coordinates (x, z) expressed in the World system.\n * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.\n * Returns the GroundMesh.\n */\n GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {\n var world = this.getWorldMatrix();\n var tmpMat = BABYLON.Tmp.Matrix[5];\n world.invertToRef(tmpMat);\n var tmpVect = BABYLON.Tmp.Vector3[8];\n BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space\n x = tmpVect.x;\n z = tmpVect.z;\n if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {\n return this;\n }\n if (!this._heightQuads || this._heightQuads.length == 0) {\n this._initHeightQuads();\n this._computeHeightQuads();\n }\n var facet = this._getFacetAt(x, z);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);\n return this;\n };\n /**\n * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()\n * if the ground has been updated.\n * This can be used in the render loop.\n * Returns the GroundMesh.\n */\n GroundMesh.prototype.updateCoordinateHeights = function () {\n if (!this._heightQuads || this._heightQuads.length == 0) {\n this._initHeightQuads();\n }\n this._computeHeightQuads();\n return this;\n };\n // Returns the element \"facet\" from the heightQuads array relative to (x, z) local coordinates\n GroundMesh.prototype._getFacetAt = function (x, z) {\n // retrieve col and row from x, z coordinates in the ground local system\n var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);\n var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);\n var quad = this._heightQuads[row * this._subdivisionsX + col];\n var facet;\n if (z < quad.slope.x * x + quad.slope.y) {\n facet = quad.facet1;\n }\n else {\n facet = quad.facet2;\n }\n return facet;\n };\n // Creates and populates the heightMap array with \"facet\" elements :\n // a quad is two triangular facets separated by a slope, so a \"facet\" element is 1 slope + 2 facets\n // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h\n // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0\n // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0 \n // Returns the GroundMesh. \n GroundMesh.prototype._initHeightQuads = function () {\n var subdivisionsX = this._subdivisionsX;\n var subdivisionsY = this._subdivisionsY;\n this._heightQuads = new Array();\n for (var row = 0; row < subdivisionsY; row++) {\n for (var col = 0; col < subdivisionsX; col++) {\n var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };\n this._heightQuads[row * subdivisionsX + col] = quad;\n }\n }\n return this;\n };\n // Compute each quad element values and update the the heightMap array :\n // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h\n // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0\n // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0 \n // Returns the GroundMesh. \n GroundMesh.prototype._computeHeightQuads = function () {\n var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n if (!positions) {\n return this;\n }\n var v1 = BABYLON.Tmp.Vector3[3];\n var v2 = BABYLON.Tmp.Vector3[2];\n var v3 = BABYLON.Tmp.Vector3[1];\n var v4 = BABYLON.Tmp.Vector3[0];\n var v1v2 = BABYLON.Tmp.Vector3[4];\n var v1v3 = BABYLON.Tmp.Vector3[5];\n var v1v4 = BABYLON.Tmp.Vector3[6];\n var norm1 = BABYLON.Tmp.Vector3[7];\n var norm2 = BABYLON.Tmp.Vector3[8];\n var i = 0;\n var j = 0;\n var k = 0;\n var cd = 0; // 2D slope coefficient : z = cd * x + h\n var h = 0;\n var d1 = 0; // facet plane equation : ax + by + cz + d = 0\n var d2 = 0;\n var subdivisionsX = this._subdivisionsX;\n var subdivisionsY = this._subdivisionsY;\n for (var row = 0; row < subdivisionsY; row++) {\n for (var col = 0; col < subdivisionsX; col++) {\n i = col * 3;\n j = row * (subdivisionsX + 1) * 3;\n k = (row + 1) * (subdivisionsX + 1) * 3;\n v1.x = positions[j + i];\n v1.y = positions[j + i + 1];\n v1.z = positions[j + i + 2];\n v2.x = positions[j + i + 3];\n v2.y = positions[j + i + 4];\n v2.z = positions[j + i + 5];\n v3.x = positions[k + i];\n v3.y = positions[k + i + 1];\n v3.z = positions[k + i + 2];\n v4.x = positions[k + i + 3];\n v4.y = positions[k + i + 4];\n v4.z = positions[k + i + 5];\n // 2D slope V1V4\n cd = (v4.z - v1.z) / (v4.x - v1.x);\n h = v1.z - cd * v1.x; // v1 belongs to the slope\n // facet equations :\n // we compute each facet normal vector\n // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0\n // we compute the value d by applying the equation to v1 which belongs to the plane\n // then we store the facet equation in a Vector4\n v2.subtractToRef(v1, v1v2);\n v3.subtractToRef(v1, v1v3);\n v4.subtractToRef(v1, v1v4);\n BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class\n BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);\n norm1.normalize();\n norm2.normalize();\n d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);\n d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);\n var quad = this._heightQuads[row * subdivisionsX + col];\n quad.slope.copyFromFloats(cd, h);\n quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);\n quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);\n }\n }\n return this;\n };\n GroundMesh.prototype.serialize = function (serializationObject) {\n _super.prototype.serialize.call(this, serializationObject);\n serializationObject.subdivisionsX = this._subdivisionsX;\n serializationObject.subdivisionsY = this._subdivisionsY;\n serializationObject.minX = this._minX;\n serializationObject.maxX = this._maxX;\n serializationObject.minZ = this._minZ;\n serializationObject.maxZ = this._maxZ;\n serializationObject.width = this._width;\n serializationObject.height = this._height;\n };\n GroundMesh.Parse = function (parsedMesh, scene) {\n var result = new GroundMesh(parsedMesh.name, scene);\n result._subdivisionsX = parsedMesh.subdivisionsX || 1;\n result._subdivisionsY = parsedMesh.subdivisionsY || 1;\n result._minX = parsedMesh.minX;\n result._maxX = parsedMesh.maxX;\n result._minZ = parsedMesh.minZ;\n result._maxZ = parsedMesh.maxZ;\n result._width = parsedMesh.width;\n result._height = parsedMesh.height;\n return result;\n };\n return GroundMesh;\n }(BABYLON.Mesh));\n BABYLON.GroundMesh = GroundMesh;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.groundMesh.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Creates an instance based on a source mesh.\n */\n var InstancedMesh = /** @class */ (function (_super) {\n __extends(InstancedMesh, _super);\n function InstancedMesh(name, source) {\n var _this = _super.call(this, name, source.getScene()) || this;\n source.instances.push(_this);\n _this._sourceMesh = source;\n _this.position.copyFrom(source.position);\n _this.rotation.copyFrom(source.rotation);\n _this.scaling.copyFrom(source.scaling);\n if (source.rotationQuaternion) {\n _this.rotationQuaternion = source.rotationQuaternion.clone();\n }\n _this.infiniteDistance = source.infiniteDistance;\n _this.setPivotMatrix(source.getPivotMatrix());\n _this.refreshBoundingInfo();\n _this._syncSubMeshes();\n return _this;\n }\n /**\n * Returns the string \"InstancedMesh\".\n */\n InstancedMesh.prototype.getClassName = function () {\n return \"InstancedMesh\";\n };\n Object.defineProperty(InstancedMesh.prototype, \"receiveShadows\", {\n // Methods \n get: function () {\n return this._sourceMesh.receiveShadows;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(InstancedMesh.prototype, \"material\", {\n get: function () {\n return this._sourceMesh.material;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(InstancedMesh.prototype, \"visibility\", {\n get: function () {\n return this._sourceMesh.visibility;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(InstancedMesh.prototype, \"skeleton\", {\n get: function () {\n return this._sourceMesh.skeleton;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(InstancedMesh.prototype, \"renderingGroupId\", {\n get: function () {\n return this._sourceMesh.renderingGroupId;\n },\n set: function (value) {\n if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {\n return;\n }\n //no-op with warning\n BABYLON.Tools.Warn(\"Note - setting renderingGroupId of an instanced mesh has no effect on the scene\");\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the total number of vertices (integer).\n */\n InstancedMesh.prototype.getTotalVertices = function () {\n return this._sourceMesh.getTotalVertices();\n };\n Object.defineProperty(InstancedMesh.prototype, \"sourceMesh\", {\n get: function () {\n return this._sourceMesh;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Is this node ready to be used/rendered\n * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)\n * @return {boolean} is it ready\n */\n InstancedMesh.prototype.isReady = function (completeCheck) {\n if (completeCheck === void 0) { completeCheck = false; }\n return this._sourceMesh.isReady(completeCheck, true);\n };\n /**\n * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.\n */\n InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {\n return this._sourceMesh.getVerticesData(kind, copyWhenShared);\n };\n /**\n * Sets the vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.\n * The `data` are either a numeric array either a Float32Array.\n * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.\n * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).\n * Note that a new underlying VertexBuffer object is created each call.\n * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.\n *\n * Possible `kind` values :\n * - BABYLON.VertexBuffer.PositionKind\n * - BABYLON.VertexBuffer.UVKind\n * - BABYLON.VertexBuffer.UV2Kind\n * - BABYLON.VertexBuffer.UV3Kind\n * - BABYLON.VertexBuffer.UV4Kind\n * - BABYLON.VertexBuffer.UV5Kind\n * - BABYLON.VertexBuffer.UV6Kind\n * - BABYLON.VertexBuffer.ColorKind\n * - BABYLON.VertexBuffer.MatricesIndicesKind\n * - BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * - BABYLON.VertexBuffer.MatricesWeightsKind\n * - BABYLON.VertexBuffer.MatricesWeightsExtraKind\n *\n * Returns the Mesh.\n */\n InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {\n if (this.sourceMesh) {\n this.sourceMesh.setVerticesData(kind, data, updatable, stride);\n }\n return this.sourceMesh;\n };\n /**\n * Updates the existing vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, it is simply returned as it is.\n * The `data` are either a numeric array either a Float32Array.\n * No new underlying VertexBuffer object is created.\n * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.\n * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.\n *\n * Possible `kind` values :\n * - BABYLON.VertexBuffer.PositionKind\n * - BABYLON.VertexBuffer.UVKind\n * - BABYLON.VertexBuffer.UV2Kind\n * - BABYLON.VertexBuffer.UV3Kind\n * - BABYLON.VertexBuffer.UV4Kind\n * - BABYLON.VertexBuffer.UV5Kind\n * - BABYLON.VertexBuffer.UV6Kind\n * - BABYLON.VertexBuffer.ColorKind\n * - BABYLON.VertexBuffer.MatricesIndicesKind\n * - BABYLON.VertexBuffer.MatricesIndicesExtraKind\n * - BABYLON.VertexBuffer.MatricesWeightsKind\n * - BABYLON.VertexBuffer.MatricesWeightsExtraKind\n *\n * Returns the Mesh.\n */\n InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {\n if (this.sourceMesh) {\n this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);\n }\n return this.sourceMesh;\n };\n /**\n * Sets the mesh indices.\n * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).\n * If the mesh has no geometry, a new Geometry object is created and set to the mesh.\n * This method creates a new index buffer each call.\n * Returns the Mesh.\n */\n InstancedMesh.prototype.setIndices = function (indices, totalVertices) {\n if (totalVertices === void 0) { totalVertices = null; }\n if (this.sourceMesh) {\n this.sourceMesh.setIndices(indices, totalVertices);\n }\n return this.sourceMesh;\n };\n /**\n * Boolean : True if the mesh owns the requested kind of data.\n */\n InstancedMesh.prototype.isVerticesDataPresent = function (kind) {\n return this._sourceMesh.isVerticesDataPresent(kind);\n };\n /**\n * Returns an array of indices (IndicesArray).\n */\n InstancedMesh.prototype.getIndices = function () {\n return this._sourceMesh.getIndices();\n };\n Object.defineProperty(InstancedMesh.prototype, \"_positions\", {\n get: function () {\n return this._sourceMesh._positions;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Sets a new updated BoundingInfo to the mesh.\n * Returns the mesh.\n */\n InstancedMesh.prototype.refreshBoundingInfo = function () {\n var meshBB = this._sourceMesh.getBoundingInfo();\n this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());\n this._updateBoundingInfo();\n return this;\n };\n InstancedMesh.prototype._preActivate = function () {\n if (this._currentLOD) {\n this._currentLOD._preActivate();\n }\n return this;\n };\n InstancedMesh.prototype._activate = function (renderId) {\n if (this._currentLOD) {\n this._currentLOD._registerInstanceForRenderId(this, renderId);\n }\n return this;\n };\n /**\n * Returns the current associated LOD AbstractMesh.\n */\n InstancedMesh.prototype.getLOD = function (camera) {\n if (!camera) {\n return this;\n }\n var boundingInfo = this.getBoundingInfo();\n this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);\n if (this._currentLOD === this.sourceMesh) {\n return this;\n }\n return this._currentLOD;\n };\n InstancedMesh.prototype._syncSubMeshes = function () {\n this.releaseSubMeshes();\n if (this._sourceMesh.subMeshes) {\n for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {\n this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);\n }\n }\n return this;\n };\n InstancedMesh.prototype._generatePointsArray = function () {\n return this._sourceMesh._generatePointsArray();\n };\n /**\n * Creates a new InstancedMesh from the current mesh.\n * - name (string) : the cloned mesh name\n * - newParent (optional Node) : the optional Node to parent the clone to.\n * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.\n *\n * Returns the clone.\n */\n InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {\n var result = this._sourceMesh.createInstance(name);\n // Deep copy\n BABYLON.Tools.DeepCopy(this, result, [\"name\", \"subMeshes\", \"uniqueId\"], []);\n // Bounding info\n this.refreshBoundingInfo();\n // Parent\n if (newParent) {\n result.parent = newParent;\n }\n if (!doNotCloneChildren) {\n // Children\n for (var index = 0; index < this.getScene().meshes.length; index++) {\n var mesh = this.getScene().meshes[index];\n if (mesh.parent === this) {\n mesh.clone(mesh.name, result);\n }\n }\n }\n result.computeWorldMatrix(true);\n return result;\n };\n /**\n * Disposes the InstancedMesh.\n * Returns nothing.\n */\n InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n // Remove from mesh\n var index = this._sourceMesh.instances.indexOf(this);\n this._sourceMesh.instances.splice(index, 1);\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n return InstancedMesh;\n }(BABYLON.AbstractMesh));\n BABYLON.InstancedMesh = InstancedMesh;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.instancedMesh.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var LinesMesh = /** @class */ (function (_super) {\n __extends(LinesMesh, _super);\n function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {\n if (scene === void 0) { scene = null; }\n if (parent === void 0) { parent = null; }\n var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;\n _this.useVertexColor = useVertexColor;\n _this.useVertexAlpha = useVertexAlpha;\n _this.color = new BABYLON.Color3(1, 1, 1);\n _this.alpha = 1;\n if (source) {\n _this.color = source.color.clone();\n _this.alpha = source.alpha;\n _this.useVertexColor = source.useVertexColor;\n _this.useVertexAlpha = source.useVertexAlpha;\n }\n _this._intersectionThreshold = 0.1;\n var defines = [];\n var options = {\n attributes: [BABYLON.VertexBuffer.PositionKind],\n uniforms: [\"world\", \"viewProjection\"],\n needAlphaBlending: true,\n defines: defines\n };\n if (useVertexAlpha === false) {\n options.needAlphaBlending = false;\n }\n if (!useVertexColor) {\n options.uniforms.push(\"color\");\n }\n else {\n options.defines.push(\"#define VERTEXCOLOR\");\n options.attributes.push(BABYLON.VertexBuffer.ColorKind);\n }\n _this._colorShader = new BABYLON.ShaderMaterial(\"colorShader\", _this.getScene(), \"color\", options);\n return _this;\n }\n Object.defineProperty(LinesMesh.prototype, \"intersectionThreshold\", {\n /**\n * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.\n * This margin is expressed in world space coordinates, so its value may vary.\n * Default value is 0.1\n * @returns the intersection Threshold value.\n */\n get: function () {\n return this._intersectionThreshold;\n },\n /**\n * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.\n * This margin is expressed in world space coordinates, so its value may vary.\n * @param value the new threshold to apply\n */\n set: function (value) {\n if (this._intersectionThreshold === value) {\n return;\n }\n this._intersectionThreshold = value;\n if (this.geometry) {\n this.geometry.boundingBias = new BABYLON.Vector2(0, value);\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the string \"LineMesh\"\n */\n LinesMesh.prototype.getClassName = function () {\n return \"LinesMesh\";\n };\n Object.defineProperty(LinesMesh.prototype, \"material\", {\n /**\n * @hidden\n */\n get: function () {\n return this._colorShader;\n },\n /**\n * @hidden\n */\n set: function (value) {\n // Do nothing\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LinesMesh.prototype, \"checkCollisions\", {\n /**\n * @hidden\n */\n get: function () {\n return false;\n },\n enumerable: true,\n configurable: true\n });\n LinesMesh.prototype.createInstance = function (name) {\n throw new Error(\"LinesMeshes do not support createInstance.\");\n };\n LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {\n if (!this._geometry) {\n return this;\n }\n // VBOs\n this._geometry._bind(this._colorShader.getEffect());\n // Color\n if (!this.useVertexColor) {\n this._colorShader.setColor4(\"color\", this.color.toColor4(this.alpha));\n }\n return this;\n };\n LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {\n if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {\n return this;\n }\n var engine = this.getScene().getEngine();\n // Draw order\n engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);\n return this;\n };\n LinesMesh.prototype.dispose = function (doNotRecurse) {\n this._colorShader.dispose();\n _super.prototype.dispose.call(this, doNotRecurse);\n };\n /**\n * Returns a new LineMesh object cloned from the current one.\n */\n LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {\n return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);\n };\n return LinesMesh;\n }(BABYLON.Mesh));\n BABYLON.LinesMesh = LinesMesh;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.linesMesh.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class implement a typical dictionary using a string as key and the generic type T as value.\n * The underlying implementation relies on an associative array to ensure the best performances.\n * The value can be anything including 'null' but except 'undefined'\n */\n var StringDictionary = /** @class */ (function () {\n function StringDictionary() {\n this._count = 0;\n this._data = {};\n }\n /**\n * This will clear this dictionary and copy the content from the 'source' one.\n * If the T value is a custom object, it won't be copied/cloned, the same object will be used\n * @param source the dictionary to take the content from and copy to this dictionary\n */\n StringDictionary.prototype.copyFrom = function (source) {\n var _this = this;\n this.clear();\n source.forEach(function (t, v) { return _this.add(t, v); });\n };\n /**\n * Get a value based from its key\n * @param key the given key to get the matching value from\n * @return the value if found, otherwise undefined is returned\n */\n StringDictionary.prototype.get = function (key) {\n var val = this._data[key];\n if (val !== undefined) {\n return val;\n }\n return undefined;\n };\n /**\n * Get a value from its key or add it if it doesn't exist.\n * This method will ensure you that a given key/data will be present in the dictionary.\n * @param key the given key to get the matching value from\n * @param factory the factory that will create the value if the key is not present in the dictionary.\n * The factory will only be invoked if there's no data for the given key.\n * @return the value corresponding to the key.\n */\n StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {\n var val = this.get(key);\n if (val !== undefined) {\n return val;\n }\n val = factory(key);\n if (val) {\n this.add(key, val);\n }\n return val;\n };\n /**\n * Get a value from its key if present in the dictionary otherwise add it\n * @param key the key to get the value from\n * @param val if there's no such key/value pair in the dictionary add it with this value\n * @return the value corresponding to the key\n */\n StringDictionary.prototype.getOrAdd = function (key, val) {\n var curVal = this.get(key);\n if (curVal !== undefined) {\n return curVal;\n }\n this.add(key, val);\n return val;\n };\n /**\n * Check if there's a given key in the dictionary\n * @param key the key to check for\n * @return true if the key is present, false otherwise\n */\n StringDictionary.prototype.contains = function (key) {\n return this._data[key] !== undefined;\n };\n /**\n * Add a new key and its corresponding value\n * @param key the key to add\n * @param value the value corresponding to the key\n * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary\n */\n StringDictionary.prototype.add = function (key, value) {\n if (this._data[key] !== undefined) {\n return false;\n }\n this._data[key] = value;\n ++this._count;\n return true;\n };\n StringDictionary.prototype.set = function (key, value) {\n if (this._data[key] === undefined) {\n return false;\n }\n this._data[key] = value;\n return true;\n };\n /**\n * Get the element of the given key and remove it from the dictionary\n * @param key\n */\n StringDictionary.prototype.getAndRemove = function (key) {\n var val = this.get(key);\n if (val !== undefined) {\n delete this._data[key];\n --this._count;\n return val;\n }\n return null;\n };\n /**\n * Remove a key/value from the dictionary.\n * @param key the key to remove\n * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary\n */\n StringDictionary.prototype.remove = function (key) {\n if (this.contains(key)) {\n delete this._data[key];\n --this._count;\n return true;\n }\n return false;\n };\n /**\n * Clear the whole content of the dictionary\n */\n StringDictionary.prototype.clear = function () {\n this._data = {};\n this._count = 0;\n };\n Object.defineProperty(StringDictionary.prototype, \"count\", {\n get: function () {\n return this._count;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Execute a callback on each key/val of the dictionary.\n * Note that you can remove any element in this dictionary in the callback implementation\n * @param callback the callback to execute on a given key/value pair\n */\n StringDictionary.prototype.forEach = function (callback) {\n for (var cur in this._data) {\n var val = this._data[cur];\n callback(cur, val);\n }\n };\n /**\n * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.\n * If the callback returns null or undefined the method will iterate to the next key/value pair\n * Note that you can remove any element in this dictionary in the callback implementation\n * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned\n */\n StringDictionary.prototype.first = function (callback) {\n for (var cur in this._data) {\n var val = this._data[cur];\n var res = callback(cur, val);\n if (res) {\n return res;\n }\n }\n return null;\n };\n return StringDictionary;\n }());\n BABYLON.StringDictionary = StringDictionary;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stringDictionary.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Debug;\n (function (Debug) {\n /**\n * Class used to render a debug view of a given skeleton\n * @see http://www.babylonjs-playground.com/#1BZJVJ#8\n */\n var SkeletonViewer = /** @class */ (function () {\n /**\n * Creates a new SkeletonViewer\n * @param skeleton defines the skeleton to render\n * @param mesh defines the mesh attached to the skeleton\n * @param scene defines the hosting scene\n * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)\n * @param renderingGroupId defines the rendering group id to use with the viewer\n */\n function SkeletonViewer(\n /** defines the skeleton to render */\n skeleton, \n /** defines the mesh attached to the skeleton */\n mesh, scene, \n /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */\n autoUpdateBonesMatrices, \n /** defines the rendering group id to use with the viewer */\n renderingGroupId) {\n if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }\n if (renderingGroupId === void 0) { renderingGroupId = 1; }\n this.skeleton = skeleton;\n this.mesh = mesh;\n this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;\n this.renderingGroupId = renderingGroupId;\n /** Gets or sets the color used to render the skeleton */\n this.color = BABYLON.Color3.White();\n this._debugLines = new Array();\n this._isEnabled = false;\n this._scene = scene;\n this.update();\n this._renderFunction = this.update.bind(this);\n }\n Object.defineProperty(SkeletonViewer.prototype, \"isEnabled\", {\n get: function () {\n return this._isEnabled;\n },\n /** Gets or sets a boolean indicating if the viewer is enabled */\n set: function (value) {\n if (this._isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n if (value) {\n this._scene.registerBeforeRender(this._renderFunction);\n }\n else {\n this._scene.unregisterBeforeRender(this._renderFunction);\n }\n },\n enumerable: true,\n configurable: true\n });\n SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {\n if (x === void 0) { x = 0; }\n if (y === void 0) { y = 0; }\n if (z === void 0) { z = 0; }\n var tmat = BABYLON.Tmp.Matrix[0];\n var parentBone = bone.getParent();\n tmat.copyFrom(bone.getLocalMatrix());\n if (x !== 0 || y !== 0 || z !== 0) {\n var tmat2 = BABYLON.Tmp.Matrix[1];\n BABYLON.Matrix.IdentityToRef(tmat2);\n tmat2.m[12] = x;\n tmat2.m[13] = y;\n tmat2.m[14] = z;\n tmat2.multiplyToRef(tmat, tmat);\n }\n if (parentBone) {\n tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);\n }\n tmat.multiplyToRef(meshMat, tmat);\n position.x = tmat.m[12];\n position.y = tmat.m[13];\n position.z = tmat.m[14];\n };\n SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {\n var len = bones.length;\n var meshPos = this.mesh.position;\n for (var i = 0; i < len; i++) {\n var bone = bones[i];\n var points = this._debugLines[i];\n if (!points) {\n points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n this._debugLines[i] = points;\n }\n this._getBonePosition(points[0], bone, meshMat);\n this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);\n points[0].subtractInPlace(meshPos);\n points[1].subtractInPlace(meshPos);\n }\n };\n SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {\n var len = bones.length;\n var boneNum = 0;\n var meshPos = this.mesh.position;\n for (var i = len - 1; i >= 0; i--) {\n var childBone = bones[i];\n var parentBone = childBone.getParent();\n if (!parentBone) {\n continue;\n }\n var points = this._debugLines[boneNum];\n if (!points) {\n points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n this._debugLines[boneNum] = points;\n }\n childBone.getAbsolutePositionToRef(this.mesh, points[0]);\n parentBone.getAbsolutePositionToRef(this.mesh, points[1]);\n points[0].subtractInPlace(meshPos);\n points[1].subtractInPlace(meshPos);\n boneNum++;\n }\n };\n /** Update the viewer to sync with current skeleton state */\n SkeletonViewer.prototype.update = function () {\n if (this.autoUpdateBonesMatrices) {\n this.skeleton.computeAbsoluteTransforms();\n }\n if (this.skeleton.bones[0].length === undefined) {\n this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());\n }\n else {\n this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());\n }\n if (!this._debugMesh) {\n this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(\"\", { lines: this._debugLines, updatable: true, instance: null }, this._scene);\n this._debugMesh.renderingGroupId = this.renderingGroupId;\n }\n else {\n BABYLON.MeshBuilder.CreateLineSystem(\"\", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);\n }\n this._debugMesh.position.copyFrom(this.mesh.position);\n this._debugMesh.color = this.color;\n };\n /** Release associated resources */\n SkeletonViewer.prototype.dispose = function () {\n if (this._debugMesh) {\n this.isEnabled = false;\n this._debugMesh.dispose();\n this._debugMesh = null;\n }\n };\n return SkeletonViewer;\n }());\n Debug.SkeletonViewer = SkeletonViewer;\n })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.skeletonViewer.js.map\n\n/**\n * Module Debug contains the (visual) components to debug a scene correctly\n */\nvar BABYLON;\n(function (BABYLON) {\n var Debug;\n (function (Debug) {\n /**\n * The Axes viewer will show 3 axes in a specific point in space\n */\n var AxesViewer = /** @class */ (function () {\n /**\n * Creates a new AxesViewer\n * @param scene defines the hosting scene\n * @param scaleLines defines a number used to scale line length (1 by default)\n */\n function AxesViewer(scene, scaleLines) {\n if (scaleLines === void 0) { scaleLines = 1; }\n this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n /**\n * Gets or sets a number used to scale line length\n */\n this.scaleLines = 1;\n this.scaleLines = scaleLines;\n this._xmesh = BABYLON.Mesh.CreateLines(\"xline\", this._xline, scene, true);\n this._ymesh = BABYLON.Mesh.CreateLines(\"yline\", this._yline, scene, true);\n this._zmesh = BABYLON.Mesh.CreateLines(\"zline\", this._zline, scene, true);\n this._xmesh.renderingGroupId = 2;\n this._ymesh.renderingGroupId = 2;\n this._zmesh.renderingGroupId = 2;\n this._xmesh.material.checkReadyOnlyOnce = true;\n this._xmesh.color = new BABYLON.Color3(1, 0, 0);\n this._ymesh.material.checkReadyOnlyOnce = true;\n this._ymesh.color = new BABYLON.Color3(0, 1, 0);\n this._zmesh.material.checkReadyOnlyOnce = true;\n this._zmesh.color = new BABYLON.Color3(0, 0, 1);\n this.scene = scene;\n }\n /**\n * Force the viewer to update\n * @param position defines the position of the viewer\n * @param xaxis defines the x axis of the viewer\n * @param yaxis defines the y axis of the viewer\n * @param zaxis defines the z axis of the viewer\n */\n AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {\n var scaleLines = this.scaleLines;\n if (this._xmesh) {\n this._xmesh.position.copyFrom(position);\n }\n if (this._ymesh) {\n this._ymesh.position.copyFrom(position);\n }\n if (this._zmesh) {\n this._zmesh.position.copyFrom(position);\n }\n var point2 = this._xline[1];\n point2.x = xaxis.x * scaleLines;\n point2.y = xaxis.y * scaleLines;\n point2.z = xaxis.z * scaleLines;\n BABYLON.Mesh.CreateLines(\"\", this._xline, null, false, this._xmesh);\n point2 = this._yline[1];\n point2.x = yaxis.x * scaleLines;\n point2.y = yaxis.y * scaleLines;\n point2.z = yaxis.z * scaleLines;\n BABYLON.Mesh.CreateLines(\"\", this._yline, null, false, this._ymesh);\n point2 = this._zline[1];\n point2.x = zaxis.x * scaleLines;\n point2.y = zaxis.y * scaleLines;\n point2.z = zaxis.z * scaleLines;\n BABYLON.Mesh.CreateLines(\"\", this._zline, null, false, this._zmesh);\n };\n /** Releases resources */\n AxesViewer.prototype.dispose = function () {\n if (this._xmesh) {\n this._xmesh.dispose();\n }\n if (this._ymesh) {\n this._ymesh.dispose();\n }\n if (this._zmesh) {\n this._zmesh.dispose();\n }\n this._xmesh = null;\n this._ymesh = null;\n this._zmesh = null;\n this.scene = null;\n };\n return AxesViewer;\n }());\n Debug.AxesViewer = AxesViewer;\n })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.axesViewer.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var Debug;\n (function (Debug) {\n /**\n * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh\n * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8\n */\n var BoneAxesViewer = /** @class */ (function (_super) {\n __extends(BoneAxesViewer, _super);\n /**\n * Creates a new BoneAxesViewer\n * @param scene defines the hosting scene\n * @param bone defines the target bone\n * @param mesh defines the target mesh\n * @param scaleLines defines a scaling factor for line length (1 by default)\n */\n function BoneAxesViewer(scene, bone, mesh, scaleLines) {\n if (scaleLines === void 0) { scaleLines = 1; }\n var _this = _super.call(this, scene, scaleLines) || this;\n /** Gets current position */\n _this.pos = BABYLON.Vector3.Zero();\n /** Gets direction of X axis */\n _this.xaxis = BABYLON.Vector3.Zero();\n /** Gets direction of Y axis */\n _this.yaxis = BABYLON.Vector3.Zero();\n /** Gets direction of Z axis */\n _this.zaxis = BABYLON.Vector3.Zero();\n _this.mesh = mesh;\n _this.bone = bone;\n return _this;\n }\n /**\n * Force the viewer to update\n */\n BoneAxesViewer.prototype.update = function () {\n if (!this.mesh || !this.bone) {\n return;\n }\n var bone = this.bone;\n bone.getAbsolutePositionToRef(this.mesh, this.pos);\n bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);\n bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);\n bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);\n _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);\n };\n /** Releases resources */\n BoneAxesViewer.prototype.dispose = function () {\n if (this.mesh) {\n this.mesh = null;\n this.bone = null;\n _super.prototype.dispose.call(this);\n }\n };\n return BoneAxesViewer;\n }(Debug.AxesViewer));\n Debug.BoneAxesViewer = BoneAxesViewer;\n })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boneAxesViewer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var RayHelper = /** @class */ (function () {\n function RayHelper(ray) {\n this.ray = ray;\n }\n RayHelper.CreateAndShow = function (ray, scene, color) {\n var helper = new RayHelper(ray);\n helper.show(scene, color);\n return helper;\n };\n RayHelper.prototype.show = function (scene, color) {\n if (!this._renderFunction && this.ray) {\n var ray = this.ray;\n this._renderFunction = this._render.bind(this);\n this._scene = scene;\n this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];\n this._renderLine = BABYLON.Mesh.CreateLines(\"ray\", this._renderPoints, scene, true);\n if (this._renderFunction) {\n this._scene.registerBeforeRender(this._renderFunction);\n }\n }\n if (color && this._renderLine) {\n this._renderLine.color.copyFrom(color);\n }\n };\n RayHelper.prototype.hide = function () {\n if (this._renderFunction && this._scene) {\n this._scene.unregisterBeforeRender(this._renderFunction);\n this._scene = null;\n this._renderFunction = null;\n if (this._renderLine) {\n this._renderLine.dispose();\n this._renderLine = null;\n }\n this._renderPoints = [];\n }\n };\n RayHelper.prototype._render = function () {\n var ray = this.ray;\n if (!ray) {\n return;\n }\n var point = this._renderPoints[1];\n var len = Math.min(ray.length, 1000000);\n point.copyFrom(ray.direction);\n point.scaleInPlace(len);\n point.addInPlace(ray.origin);\n BABYLON.Mesh.CreateLines(\"ray\", this._renderPoints, this._scene, true, this._renderLine);\n };\n RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {\n this._attachedToMesh = mesh;\n var ray = this.ray;\n if (!ray) {\n return;\n }\n if (!ray.direction) {\n ray.direction = BABYLON.Vector3.Zero();\n }\n if (!ray.origin) {\n ray.origin = BABYLON.Vector3.Zero();\n }\n if (length) {\n ray.length = length;\n }\n if (!meshSpaceOrigin) {\n meshSpaceOrigin = BABYLON.Vector3.Zero();\n }\n if (!meshSpaceDirection) {\n // -1 so that this will work with Mesh.lookAt\n meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);\n }\n if (!this._meshSpaceDirection) {\n this._meshSpaceDirection = meshSpaceDirection.clone();\n this._meshSpaceOrigin = meshSpaceOrigin.clone();\n }\n else {\n this._meshSpaceDirection.copyFrom(meshSpaceDirection);\n this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);\n }\n if (!this._updateToMeshFunction) {\n this._updateToMeshFunction = this._updateToMesh.bind(this);\n this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);\n }\n this._updateToMesh();\n };\n RayHelper.prototype.detachFromMesh = function () {\n if (this._attachedToMesh) {\n if (this._updateToMeshFunction) {\n this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);\n }\n this._attachedToMesh = null;\n this._updateToMeshFunction = null;\n }\n };\n RayHelper.prototype._updateToMesh = function () {\n var ray = this.ray;\n if (!this._attachedToMesh || !ray) {\n return;\n }\n if (this._attachedToMesh._isDisposed) {\n this.detachFromMesh();\n return;\n }\n this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);\n BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);\n };\n RayHelper.prototype.dispose = function () {\n this.hide();\n this.detachFromMesh();\n this.ray = null;\n };\n return RayHelper;\n }());\n BABYLON.RayHelper = RayHelper;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.rayHelper.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n // load the inspector using require, if not present in the global namespace.\n var DebugLayer = /** @class */ (function () {\n function DebugLayer(scene) {\n this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;\n this.onPropertyChangedObservable = new BABYLON.Observable();\n this._scene = scene;\n }\n /** Creates the inspector window. */\n DebugLayer.prototype._createInspector = function (config) {\n if (config === void 0) { config = {}; }\n var popup = config.popup || false;\n var initialTab = config.initialTab || 0;\n var parentElement = config.parentElement || null;\n if (!this._inspector) {\n this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;\n this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);\n } // else nothing to do as instance is already created\n };\n DebugLayer.prototype.isVisible = function () {\n if (!this._inspector) {\n return false;\n }\n return true;\n };\n DebugLayer.prototype.hide = function () {\n if (this._inspector) {\n try {\n this._inspector.dispose();\n }\n catch (e) {\n // If the inspector has been removed directly from the inspector tool\n }\n this.onPropertyChangedObservable.clear();\n this._inspector = null;\n }\n };\n /**\n *\n * Launch the debugLayer.\n *\n * initialTab:\n * | Value | Tab Name |\n * | --- | --- |\n * | 0 | Scene |\n * | 1 | Console |\n * | 2 | Stats |\n * | 3 | Textures |\n * | 4 | Mesh |\n * | 5 | Light |\n * | 6 | Material |\n * | 7 | GLTF |\n * | 8 | GUI |\n * | 9 | Physics |\n * | 10 | Camera |\n * | 11 | Audio |\n *\n */\n DebugLayer.prototype.show = function (config) {\n if (config === void 0) { config = {}; }\n if (typeof this.BJSINSPECTOR == 'undefined') {\n // Load inspector and add it to the DOM\n BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));\n }\n else {\n // Otherwise creates the inspector\n this._createInspector(config);\n }\n };\n /**\n * Gets the active tab\n * @return the index of the active tab or -1 if the inspector is hidden\n */\n DebugLayer.prototype.getActiveTab = function () {\n return this._inspector ? this._inspector.getActiveTabIndex() : -1;\n };\n DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';\n return DebugLayer;\n }());\n BABYLON.DebugLayer = DebugLayer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.debugLayer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Debug;\n (function (Debug) {\n /**\n * Used to show the physics impostor around the specific mesh\n */\n var PhysicsViewer = /** @class */ (function () {\n /**\n * Creates a new PhysicsViewer\n * @param scene defines the hosting scene\n */\n function PhysicsViewer(scene) {\n /** @hidden */\n this._impostors = [];\n /** @hidden */\n this._meshes = [];\n /** @hidden */\n this._numMeshes = 0;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n var physicEngine = this._scene.getPhysicsEngine();\n if (physicEngine) {\n this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();\n }\n }\n /** @hidden */\n PhysicsViewer.prototype._updateDebugMeshes = function () {\n var plugin = this._physicsEnginePlugin;\n for (var i = 0; i < this._numMeshes; i++) {\n var impostor = this._impostors[i];\n if (!impostor) {\n continue;\n }\n if (impostor.isDisposed) {\n this.hideImpostor(this._impostors[i--]);\n }\n else {\n var mesh = this._meshes[i];\n if (mesh && plugin) {\n plugin.syncMeshWithImpostor(mesh, impostor);\n }\n }\n }\n };\n /**\n * Renders a specified physic impostor\n * @param impostor defines the impostor to render\n */\n PhysicsViewer.prototype.showImpostor = function (impostor) {\n if (!this._scene) {\n return;\n }\n for (var i = 0; i < this._numMeshes; i++) {\n if (this._impostors[i] == impostor) {\n return;\n }\n }\n var debugMesh = this._getDebugMesh(impostor, this._scene);\n if (debugMesh) {\n this._impostors[this._numMeshes] = impostor;\n this._meshes[this._numMeshes] = debugMesh;\n if (this._numMeshes === 0) {\n this._renderFunction = this._updateDebugMeshes.bind(this);\n this._scene.registerBeforeRender(this._renderFunction);\n }\n this._numMeshes++;\n }\n };\n /**\n * Hides a specified physic impostor\n * @param impostor defines the impostor to hide\n */\n PhysicsViewer.prototype.hideImpostor = function (impostor) {\n if (!impostor || !this._scene) {\n return;\n }\n var removed = false;\n for (var i = 0; i < this._numMeshes; i++) {\n if (this._impostors[i] == impostor) {\n var mesh = this._meshes[i];\n if (!mesh) {\n continue;\n }\n this._scene.removeMesh(mesh);\n mesh.dispose();\n this._numMeshes--;\n if (this._numMeshes > 0) {\n this._meshes[i] = this._meshes[this._numMeshes];\n this._impostors[i] = this._impostors[this._numMeshes];\n this._meshes[this._numMeshes] = null;\n this._impostors[this._numMeshes] = null;\n }\n else {\n this._meshes[0] = null;\n this._impostors[0] = null;\n }\n removed = true;\n break;\n }\n }\n if (removed && this._numMeshes === 0) {\n this._scene.unregisterBeforeRender(this._renderFunction);\n }\n };\n PhysicsViewer.prototype._getDebugMaterial = function (scene) {\n if (!this._debugMaterial) {\n this._debugMaterial = new BABYLON.StandardMaterial('', scene);\n this._debugMaterial.wireframe = true;\n }\n return this._debugMaterial;\n };\n PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {\n if (!this._debugBoxMesh) {\n this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);\n this._debugBoxMesh.renderingGroupId = 1;\n this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();\n this._debugBoxMesh.material = this._getDebugMaterial(scene);\n scene.removeMesh(this._debugBoxMesh);\n }\n return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');\n };\n PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {\n if (!this._debugSphereMesh) {\n this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);\n this._debugSphereMesh.renderingGroupId = 1;\n this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();\n this._debugSphereMesh.material = this._getDebugMaterial(scene);\n scene.removeMesh(this._debugSphereMesh);\n }\n return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');\n };\n PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {\n var mesh = null;\n if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {\n mesh = this._getDebugBoxMesh(scene);\n impostor.getBoxSizeToRef(mesh.scaling);\n }\n else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {\n mesh = this._getDebugSphereMesh(scene);\n var radius = impostor.getRadius();\n mesh.scaling.x = radius * 2;\n mesh.scaling.y = radius * 2;\n mesh.scaling.z = radius * 2;\n }\n return mesh;\n };\n /** Releases all resources */\n PhysicsViewer.prototype.dispose = function () {\n for (var i = 0; i < this._numMeshes; i++) {\n this.hideImpostor(this._impostors[i]);\n }\n if (this._debugBoxMesh) {\n this._debugBoxMesh.dispose();\n }\n if (this._debugSphereMesh) {\n this._debugSphereMesh.dispose();\n }\n if (this._debugMaterial) {\n this._debugMaterial.dispose();\n }\n this._impostors.length = 0;\n this._scene = null;\n this._physicsEnginePlugin = null;\n };\n return PhysicsViewer;\n }());\n Debug.PhysicsViewer = PhysicsViewer;\n })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.physicsViewer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n Object.defineProperty(BABYLON.Scene.prototype, \"forceShowBoundingBoxes\", {\n get: function () {\n return this._forceShowBoundingBoxes || false;\n },\n set: function (value) {\n this._forceShowBoundingBoxes = value;\n // Lazyly creates a BB renderer if needed.\n if (value) {\n this.getBoundingBoxRenderer();\n }\n },\n enumerable: true,\n configurable: true\n });\n BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {\n if (!this._boundingBoxRenderer) {\n this._boundingBoxRenderer = new BoundingBoxRenderer(this);\n }\n return this._boundingBoxRenderer;\n };\n Object.defineProperty(BABYLON.AbstractMesh.prototype, \"showBoundingBox\", {\n get: function () {\n return this._showBoundingBox || false;\n },\n set: function (value) {\n this._showBoundingBox = value;\n // Lazyly creates a BB renderer if needed.\n if (value) {\n this.getScene().getBoundingBoxRenderer();\n }\n },\n enumerable: true,\n configurable: true\n });\n var BoundingBoxRenderer = /** @class */ (function () {\n function BoundingBoxRenderer(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;\n this.frontColor = new BABYLON.Color3(1, 1, 1);\n this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);\n this.showBackLines = true;\n this.renderList = new BABYLON.SmartArray(32);\n this._vertexBuffers = {};\n this.scene = scene;\n scene._addComponent(this);\n }\n /**\n * Registers the component in a given scene\n */\n BoundingBoxRenderer.prototype.register = function () {\n this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);\n this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);\n this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);\n this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);\n };\n BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {\n if (mesh.showSubMeshesBoundingBox) {\n var boundingInfo = subMesh.getBoundingInfo();\n if (boundingInfo !== null && boundingInfo !== undefined) {\n this.renderList.push(boundingInfo.boundingBox);\n }\n }\n };\n BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {\n if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {\n var boundingInfo = sourceMesh.getBoundingInfo();\n this.renderList.push(boundingInfo.boundingBox);\n }\n };\n BoundingBoxRenderer.prototype._prepareRessources = function () {\n if (this._colorShader) {\n return;\n }\n this._colorShader = new BABYLON.ShaderMaterial(\"colorShader\", this.scene, \"color\", {\n attributes: [BABYLON.VertexBuffer.PositionKind],\n uniforms: [\"world\", \"viewProjection\", \"color\"]\n });\n var engine = this.scene.getEngine();\n var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);\n this._createIndexBuffer();\n };\n BoundingBoxRenderer.prototype._createIndexBuffer = function () {\n var engine = this.scene.getEngine();\n this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);\n };\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n BoundingBoxRenderer.prototype.rebuild = function () {\n var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._createIndexBuffer();\n };\n BoundingBoxRenderer.prototype.reset = function () {\n this.renderList.reset();\n };\n BoundingBoxRenderer.prototype.render = function () {\n if (this.renderList.length === 0) {\n return;\n }\n this._prepareRessources();\n if (!this._colorShader.isReady()) {\n return;\n }\n var engine = this.scene.getEngine();\n engine.setDepthWrite(false);\n this._colorShader._preBind();\n for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {\n var boundingBox = this.renderList.data[boundingBoxIndex];\n var min = boundingBox.minimum;\n var max = boundingBox.maximum;\n var diff = max.subtract(min);\n var median = min.add(diff.scale(0.5));\n var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)\n .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))\n .multiply(boundingBox.getWorldMatrix());\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());\n if (this.showBackLines) {\n // Back\n engine.setDepthFunctionToGreaterOrEqual();\n this.scene.resetCachedMaterial();\n this._colorShader.setColor4(\"color\", this.backColor.toColor4());\n this._colorShader.bind(worldMatrix);\n // Draw order\n engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);\n }\n // Front\n engine.setDepthFunctionToLess();\n this.scene.resetCachedMaterial();\n this._colorShader.setColor4(\"color\", this.frontColor.toColor4());\n this._colorShader.bind(worldMatrix);\n // Draw order\n engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);\n }\n this._colorShader.unbind();\n engine.setDepthFunctionToLessOrEqual();\n engine.setDepthWrite(true);\n };\n BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {\n this._prepareRessources();\n if (!this._colorShader.isReady() || !mesh._boundingInfo) {\n return;\n }\n var engine = this.scene.getEngine();\n engine.setDepthWrite(false);\n engine.setColorWrite(false);\n this._colorShader._preBind();\n var boundingBox = mesh._boundingInfo.boundingBox;\n var min = boundingBox.minimum;\n var max = boundingBox.maximum;\n var diff = max.subtract(min);\n var median = min.add(diff.scale(0.5));\n var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)\n .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))\n .multiply(boundingBox.getWorldMatrix());\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());\n engine.setDepthFunctionToLess();\n this.scene.resetCachedMaterial();\n this._colorShader.bind(worldMatrix);\n engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);\n this._colorShader.unbind();\n engine.setDepthFunctionToLessOrEqual();\n engine.setDepthWrite(true);\n engine.setColorWrite(true);\n };\n BoundingBoxRenderer.prototype.dispose = function () {\n if (!this._colorShader) {\n return;\n }\n this.renderList.dispose();\n this._colorShader.dispose();\n var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (buffer) {\n buffer.dispose();\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n this.scene.getEngine()._releaseBuffer(this._indexBuffer);\n };\n return BoundingBoxRenderer;\n }());\n BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boundingBoxRenderer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Engine.prototype.createTransformFeedback = function () {\n return this._gl.createTransformFeedback();\n };\n BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {\n this._gl.deleteTransformFeedback(value);\n };\n BABYLON.Engine.prototype.bindTransformFeedback = function (value) {\n this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);\n };\n BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {\n if (usePoints === void 0) { usePoints = true; }\n this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);\n };\n BABYLON.Engine.prototype.endTransformFeedback = function () {\n this._gl.endTransformFeedback();\n };\n BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {\n this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);\n };\n BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {\n this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);\n };\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.engine.transformFeedback.js.map\n\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This represents a GPU particle system in Babylon\n * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data\n * @see https://www.babylonjs-playground.com/#PU4WYI#4\n */\n var GPUParticleSystem = /** @class */ (function () {\n /**\n * Instantiates a GPU particle system.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * @param name The name of the particle system\n * @param options The options used to create the system\n * @param scene The scene the particle system belongs to\n * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture\n */\n function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {\n if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }\n /**\n * The emitter represents the Mesh or position we are attaching the particle system to.\n */\n this.emitter = null;\n /**\n * The rendering group used by the Particle system to chose when to render.\n */\n this.renderingGroupId = 0;\n /**\n * The layer mask we are rendering the particles through.\n */\n this.layerMask = 0x0FFFFFFF;\n this._accumulatedCount = 0;\n this._targetIndex = 0;\n this._currentRenderId = -1;\n this._started = false;\n this._stopped = false;\n this._timeDelta = 0;\n this._attributesStrideSize = 21;\n this._actualFrame = 0;\n this._rawTextureWidth = 256;\n /**\n * List of animations used by the particle system.\n */\n this.animations = [];\n /**\n * An event triggered when the system is disposed.\n */\n this.onDisposeObservable = new BABYLON.Observable();\n /**\n * The overall motion speed (0.01 is default update speed, faster updates = faster animation)\n */\n this.updateSpeed = 0.01;\n /**\n * The amount of time the particle system is running (depends of the overall update speed).\n */\n this.targetStopDuration = 0;\n /**\n * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.\n */\n this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;\n /**\n * Minimum life time of emitting particles.\n */\n this.minLifeTime = 1;\n /**\n * Maximum life time of emitting particles.\n */\n this.maxLifeTime = 1;\n /**\n * Minimum Size of emitting particles.\n */\n this.minSize = 1;\n /**\n * Maximum Size of emitting particles.\n */\n this.maxSize = 1;\n /**\n * Minimum scale of emitting particles on X axis.\n */\n this.minScaleX = 1;\n /**\n * Maximum scale of emitting particles on X axis.\n */\n this.maxScaleX = 1;\n /**\n * Minimum scale of emitting particles on Y axis.\n */\n this.minScaleY = 1;\n /**\n * Maximum scale of emitting particles on Y axis.\n */\n this.maxScaleY = 1;\n /**\n * Random color of each particle after it has been emitted, between color1 and color2 vectors.\n */\n this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * Random color of each particle after it has been emitted, between color1 and color2 vectors.\n */\n this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * Color the particle will have at the end of its lifetime.\n */\n this.colorDead = new BABYLON.Color4(0, 0, 0, 0);\n /**\n * The maximum number of particles to emit per frame until we reach the activeParticleCount value\n */\n this.emitRate = 100;\n /**\n * You can use gravity if you want to give an orientation to your particles.\n */\n this.gravity = BABYLON.Vector3.Zero();\n /**\n * Minimum power of emitting particles.\n */\n this.minEmitPower = 1;\n /**\n * Maximum power of emitting particles.\n */\n this.maxEmitPower = 1;\n /**\n * Minimum angular speed of emitting particles (Z-axis rotation for each particle).\n */\n this.minAngularSpeed = 0;\n /**\n * Maximum angular speed of emitting particles (Z-axis rotation for each particle).\n */\n this.maxAngularSpeed = 0;\n /**\n * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls\n * to override the particles.\n */\n this.forceDepthWrite = false;\n this._preWarmDone = false;\n /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */\n this.preWarmCycles = 0;\n /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */\n this.preWarmStepOffset = 1;\n /**\n * Gets or sets the minimal initial rotation in radians.\n */\n this.minInitialRotation = 0;\n /**\n * Gets or sets the maximal initial rotation in radians.\n */\n this.maxInitialRotation = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)\n */\n this.spriteCellChangeSpeed = 1;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display\n */\n this.startSpriteCellID = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display\n */\n this.endSpriteCellID = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use\n */\n this.spriteCellWidth = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use\n */\n this.spriteCellHeight = 0;\n /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */\n this.translationPivot = new BABYLON.Vector2(0, 0);\n /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */\n this.noiseStrength = new BABYLON.Vector3(10, 10, 10);\n /**\n * Gets or sets the billboard mode to use when isBillboardBased = true.\n * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far\n */\n this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;\n this._isBillboardBased = true;\n this._colorGradients = null;\n this._angularSpeedGradients = null;\n this._sizeGradients = null;\n this._velocityGradients = null;\n this.id = name;\n this.name = name;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this._engine = this._scene.getEngine();\n if (!options.randomTextureSize) {\n delete options.randomTextureSize;\n }\n var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);\n var optionsAsNumber = options;\n if (isFinite(optionsAsNumber)) {\n fullOptions.capacity = optionsAsNumber;\n }\n this._capacity = fullOptions.capacity;\n this._activeCount = fullOptions.capacity;\n this._currentActiveCount = 0;\n this._isAnimationSheetEnabled = isAnimationSheetEnabled;\n this._scene.particleSystems.push(this);\n this._updateEffectOptions = {\n attributes: [\"position\", \"age\", \"life\", \"seed\", \"size\", \"color\", \"direction\", \"initialDirection\", \"angle\", \"cellIndex\"],\n uniformsNames: [\"currentCount\", \"timeDelta\", \"emitterWM\", \"lifeTime\", \"color1\", \"color2\", \"sizeRange\", \"scaleRange\", \"gravity\", \"emitPower\",\n \"direction1\", \"direction2\", \"minEmitBox\", \"maxEmitBox\", \"radius\", \"directionRandomizer\", \"height\", \"coneAngle\", \"stopFactor\",\n \"angleRange\", \"radiusRange\", \"cellInfos\", \"noiseStrength\"],\n uniformBuffersNames: [],\n samplers: [\"randomSampler\", \"randomSampler2\", \"sizeGradientSampler\", \"angularSpeedGradientSampler\", \"velocityGradientSampler\", \"noiseSampler\"],\n defines: \"\",\n fallbacks: null,\n onCompiled: null,\n onError: null,\n indexParameters: null,\n maxSimultaneousLights: 0,\n transformFeedbackVaryings: []\n };\n this.particleEmitterType = new BABYLON.BoxParticleEmitter();\n // Random data\n var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);\n var d = [];\n for (var i = 0; i < maxTextureSize; ++i) {\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n }\n this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);\n this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n d = [];\n for (var i = 0; i < maxTextureSize; ++i) {\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n }\n this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);\n this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n this._randomTextureSize = maxTextureSize;\n }\n Object.defineProperty(GPUParticleSystem, \"IsSupported\", {\n /**\n * Gets a boolean indicating if the GPU particles can be rendered on current browser\n */\n get: function () {\n if (!BABYLON.Engine.LastCreatedEngine) {\n return false;\n }\n return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GPUParticleSystem.prototype, \"direction1\", {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.direction1) {\n return this.particleEmitterType.direction1;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.direction1) {\n this.particleEmitterType.direction1 = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GPUParticleSystem.prototype, \"direction2\", {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.direction2) {\n return this.particleEmitterType.direction2;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.direction2) {\n this.particleEmitterType.direction2 = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GPUParticleSystem.prototype, \"minEmitBox\", {\n /**\n * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.minEmitBox) {\n return this.particleEmitterType.minEmitBox;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.minEmitBox) {\n this.particleEmitterType.minEmitBox = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GPUParticleSystem.prototype, \"maxEmitBox\", {\n /**\n * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get: function () {\n if (this.particleEmitterType.maxEmitBox) {\n return this.particleEmitterType.maxEmitBox;\n }\n return BABYLON.Vector3.Zero();\n },\n set: function (value) {\n if (this.particleEmitterType.maxEmitBox) {\n this.particleEmitterType.maxEmitBox = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the maximum number of particles active at the same time.\n * @returns The max number of active particles.\n */\n GPUParticleSystem.prototype.getCapacity = function () {\n return this._capacity;\n };\n Object.defineProperty(GPUParticleSystem.prototype, \"activeParticleCount\", {\n /**\n * Gets or set the number of active particles\n */\n get: function () {\n return this._activeCount;\n },\n set: function (value) {\n this._activeCount = Math.min(value, this._capacity);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GPUParticleSystem.prototype, \"isAnimationSheetEnabled\", {\n /**\n * Gets whether an animation sprite sheet is enabled or not on the particle system\n */\n get: function () {\n return this._isAnimationSheetEnabled;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Is this system ready to be used/rendered\n * @return true if the system is ready\n */\n GPUParticleSystem.prototype.isReady = function () {\n if (!this._updateEffect) {\n this._recreateUpdateEffect();\n this._recreateRenderEffect();\n return false;\n }\n if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {\n return false;\n }\n return true;\n };\n /**\n * Gets Wether the system has been started.\n * @returns True if it has been started, otherwise false.\n */\n GPUParticleSystem.prototype.isStarted = function () {\n return this._started;\n };\n /**\n * Starts the particle system and begins to emit\n * @param delay defines the delay in milliseconds before starting the system (0 by default)\n */\n GPUParticleSystem.prototype.start = function (delay) {\n var _this = this;\n if (delay === void 0) { delay = 0; }\n if (delay) {\n setTimeout(function () {\n _this.start(0);\n }, delay);\n return;\n }\n this._started = true;\n this._stopped = false;\n this._preWarmDone = false;\n };\n /**\n * Stops the particle system.\n */\n GPUParticleSystem.prototype.stop = function () {\n this._stopped = true;\n };\n /**\n * Remove all active particles\n */\n GPUParticleSystem.prototype.reset = function () {\n this._releaseBuffers();\n this._releaseVAOs();\n this._currentActiveCount = 0;\n this._targetIndex = 0;\n };\n /**\n * Returns the string \"GPUParticleSystem\"\n * @returns a string containing the class name\n */\n GPUParticleSystem.prototype.getClassName = function () {\n return \"GPUParticleSystem\";\n };\n Object.defineProperty(GPUParticleSystem.prototype, \"isBillboardBased\", {\n /**\n * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction\n */\n get: function () {\n return this._isBillboardBased;\n },\n set: function (value) {\n if (this._isBillboardBased === value) {\n return;\n }\n this._isBillboardBased = value;\n this._releaseBuffers();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the current list of color gradients.\n * You must use addColorGradient and removeColorGradient to udpate this list\n * @returns the list of color gradients\n */\n GPUParticleSystem.prototype.getColorGradients = function () {\n return this._colorGradients;\n };\n /**\n * Gets the current list of size gradients.\n * You must use addSizeGradient and removeSizeGradient to udpate this list\n * @returns the list of size gradients\n */\n GPUParticleSystem.prototype.getSizeGradients = function () {\n return this._sizeGradients;\n };\n /**\n * Gets the current list of angular speed gradients.\n * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list\n * @returns the list of angular speed gradients\n */\n GPUParticleSystem.prototype.getAngularSpeedGradients = function () {\n return this._angularSpeedGradients;\n };\n /**\n * Gets the current list of velocity gradients.\n * You must use addVelocityGradient and removeVelocityGradient to udpate this list\n * @returns the list of angular speed gradients\n */\n GPUParticleSystem.prototype.getVelocityGradients = function () {\n return this._velocityGradients;\n };\n GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {\n if (!gradients) {\n return this;\n }\n var index = 0;\n for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {\n var valueGradient = gradients_1[_i];\n if (valueGradient.gradient === gradient) {\n gradients.splice(index, 1);\n break;\n }\n index++;\n }\n if (texture) {\n texture.dispose();\n }\n this._releaseBuffers();\n return this;\n };\n /**\n * Adds a new color gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param color defines the color to affect to the specified gradient\n * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {\n if (!this._colorGradients) {\n this._colorGradients = [];\n }\n var colorGradient = new BABYLON.ColorGradient();\n colorGradient.gradient = gradient;\n colorGradient.color1 = color1;\n this._colorGradients.push(colorGradient);\n this._colorGradients.sort(function (a, b) {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n if (this._colorGradientsTexture) {\n this._colorGradientsTexture.dispose();\n this._colorGradientsTexture = null;\n }\n this._releaseBuffers();\n return this;\n };\n /**\n * Remove a specific color gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.removeColorGradient = function (gradient) {\n this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);\n this._colorGradientsTexture = null;\n return this;\n };\n GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {\n var valueGradient = new BABYLON.FactorGradient();\n valueGradient.gradient = gradient;\n valueGradient.factor1 = factor;\n factorGradients.push(valueGradient);\n factorGradients.sort(function (a, b) {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n this._releaseBuffers();\n };\n /**\n * Adds a new size gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {\n if (!this._sizeGradients) {\n this._sizeGradients = [];\n }\n this._addFactorGradient(this._sizeGradients, gradient, factor);\n if (this._sizeGradientsTexture) {\n this._sizeGradientsTexture.dispose();\n this._sizeGradientsTexture = null;\n }\n this._releaseBuffers();\n return this;\n };\n /**\n * Remove a specific size gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {\n this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);\n this._sizeGradientsTexture = null;\n return this;\n };\n /**\n * Adds a new angular speed gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {\n if (!this._angularSpeedGradients) {\n this._angularSpeedGradients = [];\n }\n this._addFactorGradient(this._angularSpeedGradients, gradient, factor);\n if (this._angularSpeedGradientsTexture) {\n this._angularSpeedGradientsTexture.dispose();\n this._angularSpeedGradientsTexture = null;\n }\n this._releaseBuffers();\n return this;\n };\n /**\n * Remove a specific angular speed gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {\n this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);\n this._angularSpeedGradientsTexture = null;\n return this;\n };\n /**\n * Adds a new velocity gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {\n if (!this._velocityGradients) {\n this._velocityGradients = [];\n }\n this._addFactorGradient(this._velocityGradients, gradient, factor);\n if (this._velocityGradientsTexture) {\n this._velocityGradientsTexture.dispose();\n this._velocityGradientsTexture = null;\n }\n this._releaseBuffers();\n return this;\n };\n /**\n * Remove a specific velocity gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {\n this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);\n this._velocityGradientsTexture = null;\n return this;\n };\n GPUParticleSystem.prototype._createUpdateVAO = function (source) {\n var updateVertexBuffers = {};\n updateVertexBuffers[\"position\"] = source.createVertexBuffer(\"position\", 0, 3);\n updateVertexBuffers[\"age\"] = source.createVertexBuffer(\"age\", 3, 1);\n updateVertexBuffers[\"life\"] = source.createVertexBuffer(\"life\", 4, 1);\n updateVertexBuffers[\"seed\"] = source.createVertexBuffer(\"seed\", 5, 4);\n updateVertexBuffers[\"size\"] = source.createVertexBuffer(\"size\", 9, 3);\n var offset = 12;\n if (!this._colorGradientsTexture) {\n updateVertexBuffers[\"color\"] = source.createVertexBuffer(\"color\", offset, 4);\n offset += 4;\n }\n updateVertexBuffers[\"direction\"] = source.createVertexBuffer(\"direction\", offset, 3);\n offset += 3;\n if (!this._isBillboardBased) {\n updateVertexBuffers[\"initialDirection\"] = source.createVertexBuffer(\"initialDirection\", offset, 3);\n offset += 3;\n }\n if (this._angularSpeedGradientsTexture) {\n updateVertexBuffers[\"angle\"] = source.createVertexBuffer(\"angle\", offset, 1);\n offset += 1;\n }\n else {\n updateVertexBuffers[\"angle\"] = source.createVertexBuffer(\"angle\", offset, 2);\n offset += 2;\n }\n if (this._isAnimationSheetEnabled) {\n updateVertexBuffers[\"cellIndex\"] = source.createVertexBuffer(\"cellIndex\", offset, 1);\n offset += 1;\n }\n var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);\n this._engine.bindArrayBuffer(null);\n return vao;\n };\n GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {\n var renderVertexBuffers = {};\n renderVertexBuffers[\"position\"] = source.createVertexBuffer(\"position\", 0, 3, this._attributesStrideSize, true);\n renderVertexBuffers[\"age\"] = source.createVertexBuffer(\"age\", 3, 1, this._attributesStrideSize, true);\n renderVertexBuffers[\"life\"] = source.createVertexBuffer(\"life\", 4, 1, this._attributesStrideSize, true);\n renderVertexBuffers[\"size\"] = source.createVertexBuffer(\"size\", 9, 3, this._attributesStrideSize, true);\n var offset = 12;\n if (!this._colorGradientsTexture) {\n renderVertexBuffers[\"color\"] = source.createVertexBuffer(\"color\", offset, 4, this._attributesStrideSize, true);\n offset += 4;\n }\n offset += 3; // Direction\n if (!this._isBillboardBased) {\n renderVertexBuffers[\"initialDirection\"] = source.createVertexBuffer(\"initialDirection\", offset, 3, this._attributesStrideSize, true);\n offset += 3;\n }\n renderVertexBuffers[\"angle\"] = source.createVertexBuffer(\"angle\", offset, 1, this._attributesStrideSize, true);\n if (this._angularSpeedGradientsTexture) {\n offset++;\n }\n else {\n offset += 2;\n }\n if (this._isAnimationSheetEnabled) {\n renderVertexBuffers[\"cellIndex\"] = source.createVertexBuffer(\"cellIndex\", offset, 1, this._attributesStrideSize, true);\n offset += 1;\n }\n renderVertexBuffers[\"offset\"] = spriteSource.createVertexBuffer(\"offset\", 0, 2);\n renderVertexBuffers[\"uv\"] = spriteSource.createVertexBuffer(\"uv\", 2, 2);\n var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);\n this._engine.bindArrayBuffer(null);\n return vao;\n };\n GPUParticleSystem.prototype._initialize = function (force) {\n if (force === void 0) { force = false; }\n if (this._buffer0 && !force) {\n return;\n }\n var engine = this._scene.getEngine();\n var data = new Array();\n if (!this.isBillboardBased) {\n this._attributesStrideSize += 3;\n }\n if (this._colorGradientsTexture) {\n this._attributesStrideSize -= 4;\n }\n if (this._angularSpeedGradientsTexture) {\n this._attributesStrideSize -= 1;\n }\n if (this._isAnimationSheetEnabled) {\n this._attributesStrideSize += 1;\n }\n for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {\n // position\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n // Age and life\n data.push(0.0); // create the particle as a dead one to create a new one at start\n data.push(0.0);\n // Seed\n data.push(Math.random());\n data.push(Math.random());\n data.push(Math.random());\n data.push(Math.random());\n // Size\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n if (!this._colorGradientsTexture) {\n // color\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n }\n // direction\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n if (!this.isBillboardBased) {\n // initialDirection\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n }\n // angle\n data.push(0.0);\n if (!this._angularSpeedGradientsTexture) {\n data.push(0.0);\n }\n if (this._isAnimationSheetEnabled) {\n data.push(0.0);\n }\n }\n // Sprite data\n var spriteData = new Float32Array([0.5, 0.5, 1, 1,\n -0.5, 0.5, 0, 1,\n -0.5, -0.5, 0, 0,\n 0.5, -0.5, 1, 0]);\n // Buffers\n this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);\n this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);\n this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);\n // Update VAO\n this._updateVAO = [];\n this._updateVAO.push(this._createUpdateVAO(this._buffer0));\n this._updateVAO.push(this._createUpdateVAO(this._buffer1));\n // Render VAO\n this._renderVAO = [];\n this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));\n this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));\n // Links\n this._sourceBuffer = this._buffer0;\n this._targetBuffer = this._buffer1;\n };\n /** @hidden */\n GPUParticleSystem.prototype._recreateUpdateEffect = function () {\n var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : \"\";\n if (this._isBillboardBased) {\n defines += \"\\n#define BILLBOARD\";\n }\n if (this._colorGradientsTexture) {\n defines += \"\\n#define COLORGRADIENTS\";\n }\n if (this._sizeGradientsTexture) {\n defines += \"\\n#define SIZEGRADIENTS\";\n }\n if (this._angularSpeedGradientsTexture) {\n defines += \"\\n#define ANGULARSPEEDGRADIENTS\";\n }\n if (this._velocityGradientsTexture) {\n defines += \"\\n#define VELOCITYGRADIENTS\";\n }\n if (this.isAnimationSheetEnabled) {\n defines += \"\\n#define ANIMATESHEET\";\n }\n if (this.noiseTexture) {\n defines += \"\\n#define NOISE\";\n }\n if (this._updateEffect && this._updateEffectOptions.defines === defines) {\n return;\n }\n this._updateEffectOptions.transformFeedbackVaryings = [\"outPosition\", \"outAge\", \"outLife\", \"outSeed\", \"outSize\"];\n if (!this._colorGradientsTexture) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outColor\");\n }\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outDirection\");\n if (!this._isBillboardBased) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outInitialDirection\");\n }\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outAngle\");\n if (this.isAnimationSheetEnabled) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outCellIndex\");\n }\n this._updateEffectOptions.defines = defines;\n this._updateEffect = new BABYLON.Effect(\"gpuUpdateParticles\", this._updateEffectOptions, this._scene.getEngine());\n };\n /** @hidden */\n GPUParticleSystem.prototype._recreateRenderEffect = function () {\n var defines = \"\";\n if (this._scene.clipPlane) {\n defines = \"\\n#define CLIPPLANE\";\n }\n if (this._isBillboardBased) {\n defines += \"\\n#define BILLBOARD\";\n switch (this.billboardMode) {\n case BABYLON.AbstractMesh.BILLBOARDMODE_Y:\n defines += \"\\n#define BILLBOARDY\";\n break;\n case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:\n default:\n break;\n }\n }\n if (this._colorGradientsTexture) {\n defines += \"\\n#define COLORGRADIENTS\";\n }\n if (this.isAnimationSheetEnabled) {\n defines += \"\\n#define ANIMATESHEET\";\n }\n if (this._renderEffect && this._renderEffect.defines === defines) {\n return;\n }\n this._renderEffect = new BABYLON.Effect(\"gpuRenderParticles\", [\"position\", \"age\", \"life\", \"size\", \"color\", \"offset\", \"uv\", \"initialDirection\", \"angle\", \"cellIndex\"], [\"view\", \"projection\", \"colorDead\", \"invView\", \"vClipPlane\", \"sheetInfos\", \"translationPivot\", \"eyePosition\"], [\"textureSampler\", \"colorGradientSampler\"], this._scene.getEngine(), defines);\n };\n /**\n * Animates the particle system for the current frame by emitting new particles and or animating the living ones.\n * @param preWarm defines if we are in the pre-warmimg phase\n */\n GPUParticleSystem.prototype.animate = function (preWarm) {\n if (preWarm === void 0) { preWarm = false; }\n this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());\n this._actualFrame += this._timeDelta;\n if (!this._stopped) {\n if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {\n this.stop();\n }\n }\n };\n GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {\n var texture = this[textureName];\n if (!factorGradients || !factorGradients.length || texture) {\n return;\n }\n var data = new Float32Array(this._rawTextureWidth);\n for (var x = 0; x < this._rawTextureWidth; x++) {\n var ratio = x / this._rawTextureWidth;\n BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {\n data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);\n });\n }\n this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);\n };\n GPUParticleSystem.prototype._createSizeGradientTexture = function () {\n this._createFactorGradientTexture(this._sizeGradients, \"_sizeGradientsTexture\");\n };\n GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {\n this._createFactorGradientTexture(this._angularSpeedGradients, \"_angularSpeedGradientsTexture\");\n };\n GPUParticleSystem.prototype._createVelocityGradientTexture = function () {\n this._createFactorGradientTexture(this._velocityGradients, \"_velocityGradientsTexture\");\n };\n GPUParticleSystem.prototype._createColorGradientTexture = function () {\n if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {\n return;\n }\n var data = new Uint8Array(this._rawTextureWidth * 4);\n var tmpColor = BABYLON.Tmp.Color4[0];\n for (var x = 0; x < this._rawTextureWidth; x++) {\n var ratio = x / this._rawTextureWidth;\n BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {\n BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);\n data[x * 4] = tmpColor.r * 255;\n data[x * 4 + 1] = tmpColor.g * 255;\n data[x * 4 + 2] = tmpColor.b * 255;\n data[x * 4 + 3] = tmpColor.a * 255;\n });\n }\n this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);\n };\n /**\n * Renders the particle system in its current state\n * @param preWarm defines if the system should only update the particles but not render them\n * @returns the current number of particles\n */\n GPUParticleSystem.prototype.render = function (preWarm) {\n if (preWarm === void 0) { preWarm = false; }\n if (!this._started) {\n return 0;\n }\n this._createColorGradientTexture();\n this._createSizeGradientTexture();\n this._createAngularSpeedGradientTexture();\n this._createVelocityGradientTexture();\n this._recreateUpdateEffect();\n this._recreateRenderEffect();\n if (!this.isReady()) {\n return 0;\n }\n if (!preWarm) {\n if (!this._preWarmDone && this.preWarmCycles) {\n for (var index = 0; index < this.preWarmCycles; index++) {\n this.animate(true);\n this.render(true);\n }\n this._preWarmDone = true;\n }\n if (this._currentRenderId === this._scene.getRenderId()) {\n return 0;\n }\n this._currentRenderId = this._scene.getRenderId();\n }\n // Get everything ready to render\n this._initialize();\n this._accumulatedCount += this.emitRate * this._timeDelta;\n if (this._accumulatedCount > 1) {\n var intPart = this._accumulatedCount | 0;\n this._accumulatedCount -= intPart;\n this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);\n }\n if (!this._currentActiveCount) {\n return 0;\n }\n // Enable update effect\n this._engine.enableEffect(this._updateEffect);\n this._engine.setState(false);\n this._updateEffect.setFloat(\"currentCount\", this._currentActiveCount);\n this._updateEffect.setFloat(\"timeDelta\", this._timeDelta);\n this._updateEffect.setFloat(\"stopFactor\", this._stopped ? 0 : 1);\n this._updateEffect.setTexture(\"randomSampler\", this._randomTexture);\n this._updateEffect.setTexture(\"randomSampler2\", this._randomTexture2);\n this._updateEffect.setFloat2(\"lifeTime\", this.minLifeTime, this.maxLifeTime);\n this._updateEffect.setFloat2(\"emitPower\", this.minEmitPower, this.maxEmitPower);\n if (!this._colorGradientsTexture) {\n this._updateEffect.setDirectColor4(\"color1\", this.color1);\n this._updateEffect.setDirectColor4(\"color2\", this.color2);\n }\n this._updateEffect.setFloat2(\"sizeRange\", this.minSize, this.maxSize);\n this._updateEffect.setFloat4(\"scaleRange\", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);\n this._updateEffect.setFloat4(\"angleRange\", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);\n this._updateEffect.setVector3(\"gravity\", this.gravity);\n if (this._sizeGradientsTexture) {\n this._updateEffect.setTexture(\"sizeGradientSampler\", this._sizeGradientsTexture);\n }\n if (this._angularSpeedGradientsTexture) {\n this._updateEffect.setTexture(\"angularSpeedGradientSampler\", this._angularSpeedGradientsTexture);\n }\n if (this._velocityGradientsTexture) {\n this._updateEffect.setTexture(\"velocityGradientSampler\", this._velocityGradientsTexture);\n }\n if (this.particleEmitterType) {\n this.particleEmitterType.applyToShader(this._updateEffect);\n }\n if (this._isAnimationSheetEnabled) {\n this._updateEffect.setFloat3(\"cellInfos\", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);\n }\n if (this.noiseTexture) {\n this._updateEffect.setTexture(\"noiseSampler\", this.noiseTexture);\n this._updateEffect.setVector3(\"noiseStrength\", this.noiseStrength);\n }\n var emitterWM;\n if (this.emitter.position) {\n var emitterMesh = this.emitter;\n emitterWM = emitterMesh.getWorldMatrix();\n }\n else {\n var emitterPosition = this.emitter;\n emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);\n }\n this._updateEffect.setMatrix(\"emitterWM\", emitterWM);\n // Bind source VAO\n this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);\n // Update\n this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());\n this._engine.setRasterizerState(false);\n this._engine.beginTransformFeedback(true);\n this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);\n this._engine.endTransformFeedback();\n this._engine.setRasterizerState(true);\n this._engine.bindTransformFeedbackBuffer(null);\n if (!preWarm) {\n // Enable render effect\n this._engine.enableEffect(this._renderEffect);\n var viewMatrix = this._scene.getViewMatrix();\n this._renderEffect.setMatrix(\"view\", viewMatrix);\n this._renderEffect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n this._renderEffect.setTexture(\"textureSampler\", this.particleTexture);\n this._renderEffect.setVector2(\"translationPivot\", this.translationPivot);\n if (this._colorGradientsTexture) {\n this._renderEffect.setTexture(\"colorGradientSampler\", this._colorGradientsTexture);\n }\n else {\n this._renderEffect.setDirectColor4(\"colorDead\", this.colorDead);\n }\n if (this._isAnimationSheetEnabled && this.particleTexture) {\n var baseSize = this.particleTexture.getBaseSize();\n this._renderEffect.setFloat3(\"sheetInfos\", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);\n }\n if (this._isBillboardBased) {\n var camera = this._scene.activeCamera;\n this._renderEffect.setVector3(\"eyePosition\", camera.globalPosition);\n }\n if (this._scene.clipPlane) {\n var clipPlane = this._scene.clipPlane;\n var invView = viewMatrix.clone();\n invView.invert();\n this._renderEffect.setMatrix(\"invView\", invView);\n this._renderEffect.setFloat4(\"vClipPlane\", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);\n }\n // Draw order\n switch (this.blendMode) {\n case BABYLON.ParticleSystem.BLENDMODE_ADD:\n this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);\n break;\n case BABYLON.ParticleSystem.BLENDMODE_ONEONE:\n this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);\n break;\n case BABYLON.ParticleSystem.BLENDMODE_STANDARD:\n this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);\n break;\n }\n if (this.forceDepthWrite) {\n this._engine.setDepthWrite(true);\n }\n // Bind source VAO\n this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);\n // Render\n this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);\n this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n }\n // Switch VAOs\n this._targetIndex++;\n if (this._targetIndex === 2) {\n this._targetIndex = 0;\n }\n // Switch buffers\n var tmpBuffer = this._sourceBuffer;\n this._sourceBuffer = this._targetBuffer;\n this._targetBuffer = tmpBuffer;\n return this._currentActiveCount;\n };\n /**\n * Rebuilds the particle system\n */\n GPUParticleSystem.prototype.rebuild = function () {\n this._initialize(true);\n };\n GPUParticleSystem.prototype._releaseBuffers = function () {\n if (this._buffer0) {\n this._buffer0.dispose();\n this._buffer0 = null;\n }\n if (this._buffer1) {\n this._buffer1.dispose();\n this._buffer1 = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n };\n GPUParticleSystem.prototype._releaseVAOs = function () {\n if (!this._updateVAO) {\n return;\n }\n for (var index = 0; index < this._updateVAO.length; index++) {\n this._engine.releaseVertexArrayObject(this._updateVAO[index]);\n }\n this._updateVAO = [];\n for (var index = 0; index < this._renderVAO.length; index++) {\n this._engine.releaseVertexArrayObject(this._renderVAO[index]);\n }\n this._renderVAO = [];\n };\n /**\n * Disposes the particle system and free the associated resources\n * @param disposeTexture defines if the particule texture must be disposed as well (true by default)\n */\n GPUParticleSystem.prototype.dispose = function (disposeTexture) {\n if (disposeTexture === void 0) { disposeTexture = true; }\n var index = this._scene.particleSystems.indexOf(this);\n if (index > -1) {\n this._scene.particleSystems.splice(index, 1);\n }\n this._releaseBuffers();\n this._releaseVAOs();\n if (this._colorGradientsTexture) {\n this._colorGradientsTexture.dispose();\n this._colorGradientsTexture = null;\n }\n if (this._sizeGradientsTexture) {\n this._sizeGradientsTexture.dispose();\n this._sizeGradientsTexture = null;\n }\n if (this._angularSpeedGradientsTexture) {\n this._angularSpeedGradientsTexture.dispose();\n this._angularSpeedGradientsTexture = null;\n }\n if (this._velocityGradientsTexture) {\n this._velocityGradientsTexture.dispose();\n this._velocityGradientsTexture = null;\n }\n if (this._randomTexture) {\n this._randomTexture.dispose();\n this._randomTexture = null;\n }\n if (this._randomTexture2) {\n this._randomTexture2.dispose();\n this._randomTexture2 = null;\n }\n if (disposeTexture && this.particleTexture) {\n this.particleTexture.dispose();\n this.particleTexture = null;\n }\n if (disposeTexture && this.noiseTexture) {\n this.noiseTexture.dispose();\n this.noiseTexture = null;\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n };\n /**\n * Clones the particle system.\n * @param name The name of the cloned object\n * @param newEmitter The new emitter to use\n * @returns the cloned particle system\n */\n GPUParticleSystem.prototype.clone = function (name, newEmitter) {\n var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);\n BABYLON.Tools.DeepCopy(this, result);\n if (newEmitter === undefined) {\n newEmitter = this.emitter;\n }\n result.emitter = newEmitter;\n if (this.particleTexture) {\n result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);\n }\n return result;\n };\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n GPUParticleSystem.prototype.serialize = function () {\n var serializationObject = {};\n BABYLON.ParticleSystem._Serialize(serializationObject, this);\n serializationObject.activeParticleCount = this.activeParticleCount;\n return serializationObject;\n };\n /**\n * Parses a JSON object to create a GPU particle system.\n * @param parsedParticleSystem The JSON object to parse\n * @param scene The scene to create the particle system in\n * @param rootUrl The root url to use to load external dependencies like texture\n * @returns the parsed GPU particle system\n */\n GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {\n var name = parsedParticleSystem.name;\n var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);\n if (parsedParticleSystem.activeParticleCount) {\n particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;\n }\n BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);\n return particleSystem;\n };\n return GPUParticleSystem;\n }());\n BABYLON.GPUParticleSystem = GPUParticleSystem;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gpuParticleSystem.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Represents one particle of a solid particle system.\n */\n var SolidParticle = /** @class */ (function () {\n /**\n * Creates a Solid Particle object.\n * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()\n * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.\n * @param positionIndex (integer) is the starting index of the particle vertices in the SPS \"positions\" array.\n * @param indiceIndex (integer) is the starting index of the particle indices in the SPS \"indices\" array.\n * @param model (ModelShape) is a reference to the model shape on what the particle is designed.\n * @param shapeId (integer) is the model shape identifier in the SPS.\n * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))\n * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.\n */\n function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {\n if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }\n /**\n * particle global index\n */\n this.idx = 0;\n /**\n * The color of the particle\n */\n this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * The world space position of the particle.\n */\n this.position = BABYLON.Vector3.Zero();\n /**\n * The world space rotation of the particle. (Not use if rotationQuaternion is set)\n */\n this.rotation = BABYLON.Vector3.Zero();\n /**\n * The scaling of the particle.\n */\n this.scaling = BABYLON.Vector3.One();\n /**\n * The uvs of the particle.\n */\n this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);\n /**\n * The current speed of the particle.\n */\n this.velocity = BABYLON.Vector3.Zero();\n /**\n * The pivot point in the particle local space.\n */\n this.pivot = BABYLON.Vector3.Zero();\n /**\n * Must the particle be translated from its pivot point in its local space ?\n * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.\n * Default : false\n */\n this.translateFromPivot = false;\n /**\n * Is the particle active or not ?\n */\n this.alive = true;\n /**\n * Is the particle visible or not ?\n */\n this.isVisible = true;\n /**\n * Index of this particle in the global \"positions\" array (Internal use)\n */\n this._pos = 0;\n /**\n * Index of this particle in the global \"indices\" array (Internal use)\n */\n this._ind = 0;\n /**\n * ModelShape id of this particle\n */\n this.shapeId = 0;\n /**\n * Index of the particle in its shape id (Internal use)\n */\n this.idxInShape = 0;\n /**\n * Still set as invisible in order to skip useless computations (Internal use)\n */\n this._stillInvisible = false;\n /**\n * Last computed particle rotation matrix\n */\n this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];\n /**\n * Parent particle Id, if any.\n * Default null.\n */\n this.parentId = null;\n /**\n * Internal global position in the SPS.\n */\n this._globalPosition = BABYLON.Vector3.Zero();\n this.idx = particleIndex;\n this._pos = positionIndex;\n this._ind = indiceIndex;\n this._model = model;\n this.shapeId = shapeId;\n this.idxInShape = idxInShape;\n this._sps = sps;\n if (modelBoundingInfo) {\n this._modelBoundingInfo = modelBoundingInfo;\n this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);\n }\n }\n Object.defineProperty(SolidParticle.prototype, \"scale\", {\n /**\n * Legacy support, changed scale to scaling\n */\n get: function () {\n return this.scaling;\n },\n /**\n * Legacy support, changed scale to scaling\n */\n set: function (scale) {\n this.scaling = scale;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticle.prototype, \"quaternion\", {\n /**\n * Legacy support, changed quaternion to rotationQuaternion\n */\n get: function () {\n return this.rotationQuaternion;\n },\n /**\n * Legacy support, changed quaternion to rotationQuaternion\n */\n set: function (q) {\n this.rotationQuaternion = q;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a boolean. True if the particle intersects another particle or another mesh, else false.\n * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)\n * @param target is the object (solid particle or mesh) what the intersection is computed against.\n * @returns true if it intersects\n */\n SolidParticle.prototype.intersectsMesh = function (target) {\n if (!this._boundingInfo || !target._boundingInfo) {\n return false;\n }\n if (this._sps._bSphereOnly) {\n return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);\n }\n return this._boundingInfo.intersects(target._boundingInfo, false);\n };\n return SolidParticle;\n }());\n BABYLON.SolidParticle = SolidParticle;\n /**\n * Represents the shape of the model used by one particle of a solid particle system.\n * SPS internal tool, don't use it manually.\n */\n var ModelShape = /** @class */ (function () {\n /**\n * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.\n * SPS internal tool, don't use it manually.\n * @hidden\n */\n function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {\n /**\n * length of the shape in the model indices array (internal use)\n */\n this._indicesLength = 0;\n this.shapeID = id;\n this._shape = shape;\n this._indicesLength = indicesLength;\n this._shapeUV = shapeUV;\n this._positionFunction = posFunction;\n this._vertexFunction = vtxFunction;\n }\n return ModelShape;\n }());\n BABYLON.ModelShape = ModelShape;\n /**\n * Represents a Depth Sorted Particle in the solid particle system.\n */\n var DepthSortedParticle = /** @class */ (function () {\n function DepthSortedParticle() {\n /**\n * Index of the particle in the \"indices\" array\n */\n this.ind = 0;\n /**\n * Length of the particle shape in the \"indices\" array\n */\n this.indicesLength = 0;\n /**\n * Squared distance from the particle to the camera\n */\n this.sqDistance = 0.0;\n }\n return DepthSortedParticle;\n }());\n BABYLON.DepthSortedParticle = DepthSortedParticle;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.solidParticle.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.\n *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.\n\r\n * The SPS is also a particle system. It provides some methods to manage the particles.\n * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.\n *\n * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System\n */\n var SolidParticleSystem = /** @class */ (function () {\n /**\n * Creates a SPS (Solid Particle System) object.\n * @param name (String) is the SPS name, this will be the underlying mesh name.\n * @param scene (Scene) is the scene in which the SPS is added.\n * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.\n * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.\n * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.\n * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.\n * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).\n * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.\n * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.\n */\n function SolidParticleSystem(name, scene, options) {\n /**\n * The SPS array of Solid Particle objects. Just access each particle as with any classic array.\n * Example : var p = SPS.particles[i];\n */\n this.particles = new Array();\n /**\n * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.\n */\n this.nbParticles = 0;\n /**\n * If the particles must ever face the camera (default false). Useful for planar particles.\n */\n this.billboard = false;\n /**\n * Recompute normals when adding a shape\n */\n this.recomputeNormals = true;\n /**\n * This a counter ofr your own usage. It's not set by any SPS functions.\n */\n this.counter = 0;\n /**\n * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.\n * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns\n */\n this.vars = {};\n /**\n * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)\n */\n this._bSphereOnly = false;\n /**\n * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)\n */\n this._bSphereRadiusFactor = 1.0;\n this._positions = new Array();\n this._indices = new Array();\n this._normals = new Array();\n this._colors = new Array();\n this._uvs = new Array();\n this._index = 0; // indices index\n this._updatable = true;\n this._pickable = false;\n this._isVisibilityBoxLocked = false;\n this._alwaysVisible = false;\n this._depthSort = false;\n this._shapeCounter = 0;\n this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);\n this._color = new BABYLON.Color4(0, 0, 0, 0);\n this._computeParticleColor = true;\n this._computeParticleTexture = true;\n this._computeParticleRotation = true;\n this._computeParticleVertex = false;\n this._computeBoundingBox = false;\n this._depthSortParticles = true;\n this._cam_axisZ = BABYLON.Vector3.Zero();\n this._cam_axisY = BABYLON.Vector3.Zero();\n this._cam_axisX = BABYLON.Vector3.Zero();\n this._axisZ = BABYLON.Axis.Z;\n this._camDir = BABYLON.Vector3.Zero();\n this._camInvertedPosition = BABYLON.Vector3.Zero();\n this._rotMatrix = new BABYLON.Matrix();\n this._invertMatrix = new BABYLON.Matrix();\n this._rotated = BABYLON.Vector3.Zero();\n this._quaternion = new BABYLON.Quaternion();\n this._vertex = BABYLON.Vector3.Zero();\n this._normal = BABYLON.Vector3.Zero();\n this._yaw = 0.0;\n this._pitch = 0.0;\n this._roll = 0.0;\n this._halfroll = 0.0;\n this._halfpitch = 0.0;\n this._halfyaw = 0.0;\n this._sinRoll = 0.0;\n this._cosRoll = 0.0;\n this._sinPitch = 0.0;\n this._cosPitch = 0.0;\n this._sinYaw = 0.0;\n this._cosYaw = 0.0;\n this._mustUnrotateFixedNormals = false;\n this._minimum = BABYLON.Vector3.Zero();\n this._maximum = BABYLON.Vector3.Zero();\n this._minBbox = BABYLON.Vector3.Zero();\n this._maxBbox = BABYLON.Vector3.Zero();\n this._particlesIntersect = false;\n this._depthSortFunction = function (p1, p2) {\n return (p2.sqDistance - p1.sqDistance);\n };\n this._needs32Bits = false;\n this._pivotBackTranslation = BABYLON.Vector3.Zero();\n this._scaledPivot = BABYLON.Vector3.Zero();\n this._particleHasParent = false;\n this.name = name;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this._camera = scene.activeCamera;\n this._pickable = options ? options.isPickable : false;\n this._depthSort = options ? options.enableDepthSort : false;\n this._particlesIntersect = options ? options.particleIntersection : false;\n this._bSphereOnly = options ? options.boundingSphereOnly : false;\n this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;\n if (options && options.updatable !== undefined) {\n this._updatable = options.updatable;\n }\n else {\n this._updatable = true;\n }\n if (this._pickable) {\n this.pickedParticles = [];\n }\n if (this._depthSort) {\n this.depthSortedParticles = [];\n }\n }\n /**\n * Builds the SPS underlying mesh. Returns a standard Mesh.\n * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.\n * @returns the created mesh\n */\n SolidParticleSystem.prototype.buildMesh = function () {\n if (this.nbParticles === 0) {\n var triangle = BABYLON.MeshBuilder.CreateDisc(\"\", { radius: 1, tessellation: 3 }, this._scene);\n this.addShape(triangle, 1);\n triangle.dispose();\n }\n this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);\n this._positions32 = new Float32Array(this._positions);\n this._uvs32 = new Float32Array(this._uvs);\n this._colors32 = new Float32Array(this._colors);\n if (this.recomputeNormals) {\n BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);\n }\n this._normals32 = new Float32Array(this._normals);\n this._fixedNormal32 = new Float32Array(this._normals);\n if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction\n this._unrotateFixedNormals();\n }\n var vertexData = new BABYLON.VertexData();\n vertexData.indices = (this._depthSort) ? this._indices : this._indices32;\n vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);\n vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);\n if (this._uvs32.length > 0) {\n vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);\n }\n if (this._colors32.length > 0) {\n vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);\n }\n var mesh = new BABYLON.Mesh(this.name, this._scene);\n vertexData.applyToMesh(mesh, this._updatable);\n this.mesh = mesh;\n this.mesh.isPickable = this._pickable;\n // free memory\n if (!this._depthSort) {\n this._indices = null;\n }\n this._positions = null;\n this._normals = null;\n this._uvs = null;\n this._colors = null;\n if (!this._updatable) {\n this.particles.length = 0;\n }\n return mesh;\n };\n /**\n * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.\n * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.\n * Thus the particles generated from `digest()` have their property `position` set yet.\n * @param mesh ( Mesh ) is the mesh to be digested\n * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any\n * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets\n * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets\n * @returns the current SPS\n */\n SolidParticleSystem.prototype.digest = function (mesh, options) {\n var size = (options && options.facetNb) || 1;\n var number = (options && options.number) || 0;\n var delta = (options && options.delta) || 0;\n var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var meshInd = mesh.getIndices();\n var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);\n var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);\n var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var f = 0; // facet counter\n var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices\n // compute size from number\n if (number) {\n number = (number > totalFacets) ? totalFacets : number;\n size = Math.round(totalFacets / number);\n delta = 0;\n }\n else {\n size = (size > totalFacets) ? totalFacets : size;\n }\n var facetPos = []; // submesh positions\n var facetInd = []; // submesh indices\n var facetUV = []; // submesh UV\n var facetCol = []; // submesh colors\n var barycenter = BABYLON.Vector3.Zero();\n var sizeO = size;\n while (f < totalFacets) {\n size = sizeO + Math.floor((1 + delta) * Math.random());\n if (f > totalFacets - size) {\n size = totalFacets - f;\n }\n // reset temp arrays\n facetPos.length = 0;\n facetInd.length = 0;\n facetUV.length = 0;\n facetCol.length = 0;\n // iterate over \"size\" facets\n var fi = 0;\n for (var j = f * 3; j < (f + size) * 3; j++) {\n facetInd.push(fi);\n var i = meshInd[j];\n facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);\n if (meshUV) {\n facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);\n }\n if (meshCol) {\n facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);\n }\n fi++;\n }\n // create a model shape for each single particle\n var idx = this.nbParticles;\n var shape = this._posToShape(facetPos);\n var shapeUV = this._uvsToShapeUV(facetUV);\n // compute the barycenter of the shape\n var v;\n for (v = 0; v < shape.length; v++) {\n barycenter.addInPlace(shape[v]);\n }\n barycenter.scaleInPlace(1 / shape.length);\n // shift the shape from its barycenter to the origin\n for (v = 0; v < shape.length; v++) {\n shape[v].subtractInPlace(barycenter);\n }\n var bInfo;\n if (this._particlesIntersect) {\n bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);\n }\n var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);\n // add the particle in the SPS\n var currentPos = this._positions.length;\n var currentInd = this._indices.length;\n this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);\n this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);\n // initialize the particle position\n this.particles[this.nbParticles].position.addInPlace(barycenter);\n this._index += shape.length;\n idx++;\n this.nbParticles++;\n this._shapeCounter++;\n f += size;\n }\n return this;\n };\n // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()\n SolidParticleSystem.prototype._unrotateFixedNormals = function () {\n var index = 0;\n var idx = 0;\n for (var p = 0; p < this.particles.length; p++) {\n this._particle = this.particles[p];\n this._shape = this._particle._model._shape;\n if (this._particle.rotationQuaternion) {\n this._quaternion.copyFrom(this._particle.rotationQuaternion);\n }\n else {\n this._yaw = this._particle.rotation.y;\n this._pitch = this._particle.rotation.x;\n this._roll = this._particle.rotation.z;\n this._quaternionRotationYPR();\n }\n this._quaternionToRotationMatrix();\n this._rotMatrix.invertToRef(this._invertMatrix);\n for (var pt = 0; pt < this._shape.length; pt++) {\n idx = index + pt * 3;\n BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);\n this._fixedNormal32[idx] = this._normal.x;\n this._fixedNormal32[idx + 1] = this._normal.y;\n this._fixedNormal32[idx + 2] = this._normal.z;\n }\n index = idx + 3;\n }\n };\n //reset copy\n SolidParticleSystem.prototype._resetCopy = function () {\n this._copy.position.x = 0;\n this._copy.position.y = 0;\n this._copy.position.z = 0;\n this._copy.rotation.x = 0;\n this._copy.rotation.y = 0;\n this._copy.rotation.z = 0;\n this._copy.rotationQuaternion = null;\n this._copy.scaling.x = 1.0;\n this._copy.scaling.y = 1.0;\n this._copy.scaling.z = 1.0;\n this._copy.uvs.x = 0;\n this._copy.uvs.y = 0;\n this._copy.uvs.z = 1.0;\n this._copy.uvs.w = 1.0;\n this._copy.color = null;\n this._copy.translateFromPivot = false;\n };\n // _meshBuilder : inserts the shape model in the global SPS mesh\n SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {\n var i;\n var u = 0;\n var c = 0;\n var n = 0;\n this._resetCopy();\n if (options && options.positionFunction) { // call to custom positionFunction\n options.positionFunction(this._copy, idx, idxInShape);\n this._mustUnrotateFixedNormals = true;\n }\n if (this._copy.rotationQuaternion) {\n this._quaternion.copyFrom(this._copy.rotationQuaternion);\n }\n else {\n this._yaw = this._copy.rotation.y;\n this._pitch = this._copy.rotation.x;\n this._roll = this._copy.rotation.z;\n this._quaternionRotationYPR();\n }\n this._quaternionToRotationMatrix();\n this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;\n this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;\n this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;\n if (this._copy.translateFromPivot) {\n this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);\n }\n else {\n this._pivotBackTranslation.copyFrom(this._scaledPivot);\n }\n for (i = 0; i < shape.length; i++) {\n this._vertex.x = shape[i].x;\n this._vertex.y = shape[i].y;\n this._vertex.z = shape[i].z;\n if (options && options.vertexFunction) {\n options.vertexFunction(this._copy, this._vertex, i);\n }\n this._vertex.x *= this._copy.scaling.x;\n this._vertex.y *= this._copy.scaling.y;\n this._vertex.z *= this._copy.scaling.z;\n this._vertex.x -= this._scaledPivot.x;\n this._vertex.y -= this._scaledPivot.y;\n this._vertex.z -= this._scaledPivot.z;\n BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);\n this._rotated.addInPlace(this._pivotBackTranslation);\n positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);\n if (meshUV) {\n uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);\n u += 2;\n }\n if (this._copy.color) {\n this._color = this._copy.color;\n }\n else if (meshCol && meshCol[c] !== undefined) {\n this._color.r = meshCol[c];\n this._color.g = meshCol[c + 1];\n this._color.b = meshCol[c + 2];\n this._color.a = meshCol[c + 3];\n }\n else {\n this._color.r = 1.0;\n this._color.g = 1.0;\n this._color.b = 1.0;\n this._color.a = 1.0;\n }\n colors.push(this._color.r, this._color.g, this._color.b, this._color.a);\n c += 4;\n if (!this.recomputeNormals && meshNor) {\n this._normal.x = meshNor[n];\n this._normal.y = meshNor[n + 1];\n this._normal.z = meshNor[n + 2];\n BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);\n normals.push(this._normal.x, this._normal.y, this._normal.z);\n n += 3;\n }\n }\n for (i = 0; i < meshInd.length; i++) {\n var current_ind = p + meshInd[i];\n indices.push(current_ind);\n if (current_ind > 65535) {\n this._needs32Bits = true;\n }\n }\n if (this._pickable) {\n var nbfaces = meshInd.length / 3;\n for (i = 0; i < nbfaces; i++) {\n this.pickedParticles.push({ idx: idx, faceId: i });\n }\n }\n if (this._depthSort) {\n this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());\n }\n return this._copy;\n };\n // returns a shape array from positions array\n SolidParticleSystem.prototype._posToShape = function (positions) {\n var shape = [];\n for (var i = 0; i < positions.length; i += 3) {\n shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));\n }\n return shape;\n };\n // returns a shapeUV array from a Vector4 uvs\n SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {\n var shapeUV = [];\n if (uvs) {\n for (var i = 0; i < uvs.length; i++)\n shapeUV.push(uvs[i]);\n }\n return shapeUV;\n };\n // adds a new particle object in the particles array\n SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {\n if (bInfo === void 0) { bInfo = null; }\n var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);\n this.particles.push(sp);\n return sp;\n };\n /**\n * Adds some particles to the SPS from the model shape. Returns the shape id.\n * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps\n * @param mesh is any Mesh object that will be used as a model for the solid particles.\n * @param nb (positive integer) the number of particles to be created from this model\n * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.\n * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation\n * @returns the number of shapes in the system\n */\n SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {\n var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var meshInd = mesh.getIndices();\n var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);\n var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);\n var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var bbInfo;\n if (this._particlesIntersect) {\n bbInfo = mesh.getBoundingInfo();\n }\n var shape = this._posToShape(meshPos);\n var shapeUV = this._uvsToShapeUV(meshUV);\n var posfunc = options ? options.positionFunction : null;\n var vtxfunc = options ? options.vertexFunction : null;\n var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);\n // particles\n var sp;\n var currentCopy;\n var idx = this.nbParticles;\n for (var i = 0; i < nb; i++) {\n var currentPos = this._positions.length;\n var currentInd = this._indices.length;\n currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);\n if (this._updatable) {\n sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);\n sp.position.copyFrom(currentCopy.position);\n sp.rotation.copyFrom(currentCopy.rotation);\n if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {\n sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);\n }\n if (currentCopy.color && sp.color) {\n sp.color.copyFrom(currentCopy.color);\n }\n sp.scaling.copyFrom(currentCopy.scaling);\n sp.uvs.copyFrom(currentCopy.uvs);\n }\n this._index += shape.length;\n idx++;\n }\n this.nbParticles += nb;\n this._shapeCounter++;\n return this._shapeCounter - 1;\n };\n // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices\n SolidParticleSystem.prototype._rebuildParticle = function (particle) {\n this._resetCopy();\n if (particle._model._positionFunction) { // recall to stored custom positionFunction\n particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);\n }\n if (this._copy.rotationQuaternion) {\n this._quaternion.copyFrom(this._copy.rotationQuaternion);\n }\n else {\n this._yaw = this._copy.rotation.y;\n this._pitch = this._copy.rotation.x;\n this._roll = this._copy.rotation.z;\n this._quaternionRotationYPR();\n }\n this._quaternionToRotationMatrix();\n this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;\n this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;\n this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;\n if (this._copy.translateFromPivot) {\n this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);\n }\n else {\n this._pivotBackTranslation.copyFrom(this._scaledPivot);\n }\n this._shape = particle._model._shape;\n for (var pt = 0; pt < this._shape.length; pt++) {\n this._vertex.x = this._shape[pt].x;\n this._vertex.y = this._shape[pt].y;\n this._vertex.z = this._shape[pt].z;\n if (particle._model._vertexFunction) {\n particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction\n }\n this._vertex.x *= this._copy.scaling.x;\n this._vertex.y *= this._copy.scaling.y;\n this._vertex.z *= this._copy.scaling.z;\n this._vertex.x -= this._scaledPivot.x;\n this._vertex.y -= this._scaledPivot.y;\n this._vertex.z -= this._scaledPivot.z;\n BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);\n this._rotated.addInPlace(this._pivotBackTranslation);\n this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;\n this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;\n this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;\n }\n particle.position.x = 0.0;\n particle.position.y = 0.0;\n particle.position.z = 0.0;\n particle.rotation.x = 0.0;\n particle.rotation.y = 0.0;\n particle.rotation.z = 0.0;\n particle.rotationQuaternion = null;\n particle.scaling.x = 1.0;\n particle.scaling.y = 1.0;\n particle.scaling.z = 1.0;\n particle.uvs.x = 0.0;\n particle.uvs.y = 0.0;\n particle.uvs.z = 1.0;\n particle.uvs.w = 1.0;\n particle.pivot.x = 0.0;\n particle.pivot.y = 0.0;\n particle.pivot.z = 0.0;\n particle.translateFromPivot = false;\n particle.parentId = null;\n };\n /**\n * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.\n * @returns the SPS.\n */\n SolidParticleSystem.prototype.rebuildMesh = function () {\n for (var p = 0; p < this.particles.length; p++) {\n this._rebuildParticle(this.particles[p]);\n }\n this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);\n return this;\n };\n /**\n * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.\n * This method calls `updateParticle()` for each particle of the SPS.\n * For an animated SPS, it is usually called within the render loop.\n * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_\n * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_\n * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_\n * @returns the SPS.\n */\n SolidParticleSystem.prototype.setParticles = function (start, end, update) {\n if (start === void 0) { start = 0; }\n if (end === void 0) { end = this.nbParticles - 1; }\n if (update === void 0) { update = true; }\n if (!this._updatable) {\n return this;\n }\n // custom beforeUpdate\n this.beforeUpdateParticles(start, end, update);\n this._cam_axisX.x = 1.0;\n this._cam_axisX.y = 0.0;\n this._cam_axisX.z = 0.0;\n this._cam_axisY.x = 0.0;\n this._cam_axisY.y = 1.0;\n this._cam_axisY.z = 0.0;\n this._cam_axisZ.x = 0.0;\n this._cam_axisZ.y = 0.0;\n this._cam_axisZ.z = 1.0;\n // cases when the World Matrix is to be computed first\n if (this.billboard || this._depthSort) {\n this.mesh.computeWorldMatrix(true);\n this.mesh._worldMatrix.invertToRef(this._invertMatrix);\n }\n // if the particles will always face the camera\n if (this.billboard) {\n // compute the camera position and un-rotate it by the current mesh rotation\n this._camera.getDirectionToRef(this._axisZ, this._camDir);\n BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);\n this._cam_axisZ.normalize();\n // same for camera up vector extracted from the cam view matrix\n var view = this._camera.getViewMatrix(true);\n BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);\n BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);\n this._cam_axisY.normalize();\n this._cam_axisX.normalize();\n }\n // if depthSort, compute the camera global position in the mesh local system\n if (this._depthSort) {\n BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera\n }\n BABYLON.Matrix.IdentityToRef(this._rotMatrix);\n var idx = 0; // current position index in the global array positions32\n var index = 0; // position start index in the global array positions32 of the current particle\n var colidx = 0; // current color index in the global array colors32\n var colorIndex = 0; // color start index in the global array colors32 of the current particle\n var uvidx = 0; // current uv index in the global array uvs32\n var uvIndex = 0; // uv start index in the global array uvs32 of the current particle\n var pt = 0; // current index in the particle model shape\n if (this.mesh.isFacetDataEnabled) {\n this._computeBoundingBox = true;\n }\n end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;\n if (this._computeBoundingBox) {\n if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch\n BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);\n BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);\n }\n else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.\n if (this.mesh._boundingInfo) {\n this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);\n this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);\n }\n }\n }\n // particle loop\n index = this.particles[start]._pos;\n var vpos = (index / 3) | 0;\n colorIndex = vpos * 4;\n uvIndex = vpos * 2;\n for (var p = start; p <= end; p++) {\n this._particle = this.particles[p];\n this._shape = this._particle._model._shape;\n this._shapeUV = this._particle._model._shapeUV;\n // call to custom user function to update the particle properties\n this.updateParticle(this._particle);\n // camera-particle distance for depth sorting\n if (this._depthSort && this._depthSortParticles) {\n var dsp = this.depthSortedParticles[p];\n dsp.ind = this._particle._ind;\n dsp.indicesLength = this._particle._model._indicesLength;\n dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);\n }\n // skip the computations for inactive or already invisible particles\n if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {\n // increment indexes for the next particle\n pt = this._shape.length;\n index += pt * 3;\n colorIndex += pt * 4;\n uvIndex += pt * 2;\n continue;\n }\n if (this._particle.isVisible) {\n this._particle._stillInvisible = false; // un-mark permanent invisibility\n this._particleHasParent = (this._particle.parentId !== null);\n this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;\n this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;\n this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;\n // particle rotation matrix\n if (this.billboard) {\n this._particle.rotation.x = 0.0;\n this._particle.rotation.y = 0.0;\n }\n if (this._computeParticleRotation || this.billboard) {\n if (this._particle.rotationQuaternion) {\n this._quaternion.copyFrom(this._particle.rotationQuaternion);\n }\n else {\n this._yaw = this._particle.rotation.y;\n this._pitch = this._particle.rotation.x;\n this._roll = this._particle.rotation.z;\n this._quaternionRotationYPR();\n }\n this._quaternionToRotationMatrix();\n }\n if (this._particleHasParent) {\n this._parent = this.particles[this._particle.parentId];\n this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];\n this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];\n this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];\n this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;\n this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;\n this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;\n if (this._computeParticleRotation || this.billboard) {\n this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];\n this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];\n this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];\n this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];\n this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];\n this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];\n this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];\n this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];\n this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];\n }\n }\n else {\n this._particle._globalPosition.x = this._particle.position.x;\n this._particle._globalPosition.y = this._particle.position.y;\n this._particle._globalPosition.z = this._particle.position.z;\n if (this._computeParticleRotation || this.billboard) {\n this._particle._rotationMatrix[0] = this._rotMatrix.m[0];\n this._particle._rotationMatrix[1] = this._rotMatrix.m[1];\n this._particle._rotationMatrix[2] = this._rotMatrix.m[2];\n this._particle._rotationMatrix[3] = this._rotMatrix.m[4];\n this._particle._rotationMatrix[4] = this._rotMatrix.m[5];\n this._particle._rotationMatrix[5] = this._rotMatrix.m[6];\n this._particle._rotationMatrix[6] = this._rotMatrix.m[8];\n this._particle._rotationMatrix[7] = this._rotMatrix.m[9];\n this._particle._rotationMatrix[8] = this._rotMatrix.m[10];\n }\n }\n if (this._particle.translateFromPivot) {\n this._pivotBackTranslation.x = 0.0;\n this._pivotBackTranslation.y = 0.0;\n this._pivotBackTranslation.z = 0.0;\n }\n else {\n this._pivotBackTranslation.x = this._scaledPivot.x;\n this._pivotBackTranslation.y = this._scaledPivot.y;\n this._pivotBackTranslation.z = this._scaledPivot.z;\n }\n // particle vertex loop\n for (pt = 0; pt < this._shape.length; pt++) {\n idx = index + pt * 3;\n colidx = colorIndex + pt * 4;\n uvidx = uvIndex + pt * 2;\n this._vertex.x = this._shape[pt].x;\n this._vertex.y = this._shape[pt].y;\n this._vertex.z = this._shape[pt].z;\n if (this._computeParticleVertex) {\n this.updateParticleVertex(this._particle, this._vertex, pt);\n }\n // positions\n this._vertex.x *= this._particle.scaling.x;\n this._vertex.y *= this._particle.scaling.y;\n this._vertex.z *= this._particle.scaling.z;\n this._vertex.x -= this._scaledPivot.x;\n this._vertex.y -= this._scaledPivot.y;\n this._vertex.z -= this._scaledPivot.z;\n this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];\n this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];\n this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];\n this._rotated.x += this._pivotBackTranslation.x;\n this._rotated.y += this._pivotBackTranslation.y;\n this._rotated.z += this._pivotBackTranslation.z;\n this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;\n this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;\n this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;\n if (this._computeBoundingBox) {\n if (this._positions32[idx] < this._minimum.x) {\n this._minimum.x = this._positions32[idx];\n }\n if (this._positions32[idx] > this._maximum.x) {\n this._maximum.x = this._positions32[idx];\n }\n if (this._positions32[idx + 1] < this._minimum.y) {\n this._minimum.y = this._positions32[idx + 1];\n }\n if (this._positions32[idx + 1] > this._maximum.y) {\n this._maximum.y = this._positions32[idx + 1];\n }\n if (this._positions32[idx + 2] < this._minimum.z) {\n this._minimum.z = this._positions32[idx + 2];\n }\n if (this._positions32[idx + 2] > this._maximum.z) {\n this._maximum.z = this._positions32[idx + 2];\n }\n }\n // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()\n if (!this._computeParticleVertex) {\n this._normal.x = this._fixedNormal32[idx];\n this._normal.y = this._fixedNormal32[idx + 1];\n this._normal.z = this._fixedNormal32[idx + 2];\n this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];\n this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];\n this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];\n this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;\n this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;\n this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;\n }\n if (this._computeParticleColor && this._particle.color) {\n this._colors32[colidx] = this._particle.color.r;\n this._colors32[colidx + 1] = this._particle.color.g;\n this._colors32[colidx + 2] = this._particle.color.b;\n this._colors32[colidx + 3] = this._particle.color.a;\n }\n if (this._computeParticleTexture) {\n this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;\n this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;\n }\n }\n }\n // particle just set invisible : scaled to zero and positioned at the origin\n else {\n this._particle._stillInvisible = true; // mark the particle as invisible\n for (pt = 0; pt < this._shape.length; pt++) {\n idx = index + pt * 3;\n colidx = colorIndex + pt * 4;\n uvidx = uvIndex + pt * 2;\n this._positions32[idx] = 0.0;\n this._positions32[idx + 1] = 0.0;\n this._positions32[idx + 2] = 0.0;\n this._normals32[idx] = 0.0;\n this._normals32[idx + 1] = 0.0;\n this._normals32[idx + 2] = 0.0;\n if (this._computeParticleColor && this._particle.color) {\n this._colors32[colidx] = this._particle.color.r;\n this._colors32[colidx + 1] = this._particle.color.g;\n this._colors32[colidx + 2] = this._particle.color.b;\n this._colors32[colidx + 3] = this._particle.color.a;\n }\n if (this._computeParticleTexture) {\n this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;\n this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;\n }\n }\n }\n // if the particle intersections must be computed : update the bbInfo\n if (this._particlesIntersect) {\n var bInfo = this._particle._boundingInfo;\n var bBox = bInfo.boundingBox;\n var bSphere = bInfo.boundingSphere;\n if (!this._bSphereOnly) {\n // place, scale and rotate the particle bbox within the SPS local system, then update it\n for (var b = 0; b < bBox.vectors.length; b++) {\n this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;\n this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;\n this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;\n this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];\n this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];\n this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];\n bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;\n bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;\n bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;\n }\n bBox._update(this.mesh._worldMatrix);\n }\n // place and scale the particle bouding sphere in the SPS local system, then update it\n this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;\n this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;\n this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;\n this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;\n this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;\n this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;\n bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;\n bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;\n bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;\n bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));\n bSphere._update(this.mesh._worldMatrix);\n }\n // increment indexes for the next particle\n index = idx + 3;\n colorIndex = colidx + 4;\n uvIndex = uvidx + 2;\n }\n // if the VBO must be updated\n if (update) {\n if (this._computeParticleColor) {\n this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);\n }\n if (this._computeParticleTexture) {\n this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);\n }\n this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);\n if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {\n if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {\n // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]\n var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;\n BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);\n for (var i = 0; i < this._normals32.length; i++) {\n this._fixedNormal32[i] = this._normals32[i];\n }\n }\n if (!this.mesh.areNormalsFrozen) {\n this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);\n }\n }\n if (this._depthSort && this._depthSortParticles) {\n this.depthSortedParticles.sort(this._depthSortFunction);\n var dspl = this.depthSortedParticles.length;\n var sorted = 0;\n var lind = 0;\n var sind = 0;\n var sid = 0;\n for (sorted = 0; sorted < dspl; sorted++) {\n lind = this.depthSortedParticles[sorted].indicesLength;\n sind = this.depthSortedParticles[sorted].ind;\n for (var i = 0; i < lind; i++) {\n this._indices32[sid] = this._indices[sind + i];\n sid++;\n }\n }\n this.mesh.updateIndices(this._indices32);\n }\n }\n if (this._computeBoundingBox) {\n this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);\n this.mesh._boundingInfo.update(this.mesh._worldMatrix);\n }\n this.afterUpdateParticles(start, end, update);\n return this;\n };\n SolidParticleSystem.prototype._quaternionRotationYPR = function () {\n this._halfroll = this._roll * 0.5;\n this._halfpitch = this._pitch * 0.5;\n this._halfyaw = this._yaw * 0.5;\n this._sinRoll = Math.sin(this._halfroll);\n this._cosRoll = Math.cos(this._halfroll);\n this._sinPitch = Math.sin(this._halfpitch);\n this._cosPitch = Math.cos(this._halfpitch);\n this._sinYaw = Math.sin(this._halfyaw);\n this._cosYaw = Math.cos(this._halfyaw);\n this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;\n this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;\n this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;\n this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;\n };\n SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {\n this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));\n this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);\n this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);\n this._rotMatrix.m[3] = 0;\n this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);\n this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));\n this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);\n this._rotMatrix.m[7] = 0;\n this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);\n this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);\n this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));\n this._rotMatrix.m[11] = 0;\n this._rotMatrix.m[12] = 0;\n this._rotMatrix.m[13] = 0;\n this._rotMatrix.m[14] = 0;\n this._rotMatrix.m[15] = 1.0;\n };\n /**\n * Disposes the SPS.\n */\n SolidParticleSystem.prototype.dispose = function () {\n this.mesh.dispose();\n this.vars = null;\n // drop references to internal big arrays for the GC\n this._positions = null;\n this._indices = null;\n this._normals = null;\n this._uvs = null;\n this._colors = null;\n this._indices32 = null;\n this._positions32 = null;\n this._normals32 = null;\n this._fixedNormal32 = null;\n this._uvs32 = null;\n this._colors32 = null;\n this.pickedParticles = null;\n };\n /**\n * Visibilty helper : Recomputes the visible size according to the mesh bounding box\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility\n * @returns the SPS.\n */\n SolidParticleSystem.prototype.refreshVisibleSize = function () {\n if (!this._isVisibilityBoxLocked) {\n this.mesh.refreshBoundingInfo();\n }\n return this;\n };\n /**\n * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.\n * @param size the size (float) of the visibility box\n * note : this doesn't lock the SPS mesh bounding box.\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility\n */\n SolidParticleSystem.prototype.setVisibilityBox = function (size) {\n var vis = size / 2;\n this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));\n };\n Object.defineProperty(SolidParticleSystem.prototype, \"isAlwaysVisible\", {\n /**\n * Gets whether the SPS as always visible or not\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility\n */\n get: function () {\n return this._alwaysVisible;\n },\n /**\n * Sets the SPS as always visible or not\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility\n */\n set: function (val) {\n this._alwaysVisible = val;\n this.mesh.alwaysSelectAsActiveMesh = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"isVisibilityBoxLocked\", {\n /**\n * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility\n */\n get: function () {\n return this._isVisibilityBoxLocked;\n },\n /**\n * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility\n */\n set: function (val) {\n this._isVisibilityBoxLocked = val;\n var boundingInfo = this.mesh.getBoundingInfo();\n boundingInfo.isLocked = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"computeParticleRotation\", {\n /**\n * Gets if `setParticles()` computes the particle rotations or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.\n */\n get: function () {\n return this._computeParticleRotation;\n },\n /**\n * Tells to `setParticles()` to compute the particle rotations or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.\n */\n set: function (val) {\n this._computeParticleRotation = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"computeParticleColor\", {\n /**\n * Gets if `setParticles()` computes the particle colors or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.\n */\n get: function () {\n return this._computeParticleColor;\n },\n /**\n * Tells to `setParticles()` to compute the particle colors or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.\n */\n set: function (val) {\n this._computeParticleColor = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"computeParticleTexture\", {\n /**\n * Gets if `setParticles()` computes the particle textures or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.\n */\n get: function () {\n return this._computeParticleTexture;\n },\n set: function (val) {\n this._computeParticleTexture = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"computeParticleVertex\", {\n /**\n * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.\n * Default value : false. The SPS is faster when it's set to false.\n * Note : the particle custom vertex positions aren't stored values.\n */\n get: function () {\n return this._computeParticleVertex;\n },\n /**\n * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.\n * Default value : false. The SPS is faster when it's set to false.\n * Note : the particle custom vertex positions aren't stored values.\n */\n set: function (val) {\n this._computeParticleVertex = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"computeBoundingBox\", {\n /**\n * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.\n */\n get: function () {\n return this._computeBoundingBox;\n },\n /**\n * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.\n */\n set: function (val) {\n this._computeBoundingBox = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SolidParticleSystem.prototype, \"depthSortParticles\", {\n /**\n * Gets if `setParticles()` sorts or not the distance between each particle and the camera.\n * Skipped when `enableDepthSort` is set to `false` (default) at construction time.\n * Default : `true`\n */\n get: function () {\n return this._depthSortParticles;\n },\n /**\n * Tells to `setParticles()` to sort or not the distance between each particle and the camera.\n * Skipped when `enableDepthSort` is set to `false` (default) at construction time.\n * Default : `true`\n */\n set: function (val) {\n this._depthSortParticles = val;\n },\n enumerable: true,\n configurable: true\n });\n // =======================================================================\n // Particle behavior logic\n // these following methods may be overwritten by the user to fit his needs \n /**\n * This function does nothing. It may be overwritten to set all the particle first values.\n * The SPS doesn't call this function, you may have to call it by your own.\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management\n */\n SolidParticleSystem.prototype.initParticles = function () {\n };\n /**\n * This function does nothing. It may be overwritten to recycle a particle.\n * The SPS doesn't call this function, you may have to call it by your own.\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management\n * @param particle The particle to recycle\n * @returns the recycled particle\n */\n SolidParticleSystem.prototype.recycleParticle = function (particle) {\n return particle;\n };\n /**\n * Updates a particle : this function should be overwritten by the user.\n * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management\n * @example : just set a particle position or velocity and recycle conditions\n * @param particle The particle to update\n * @returns the updated particle\n */\n SolidParticleSystem.prototype.updateParticle = function (particle) {\n return particle;\n };\n /**\n * Updates a vertex of a particle : it can be overwritten by the user.\n * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.\n * @param particle the current particle\n * @param vertex the current index of the current particle\n * @param pt the index of the current vertex in the particle shape\n * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape\n * @example : just set a vertex particle position\n * @returns the updated vertex\n */\n SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {\n return vertex;\n };\n /**\n * This will be called before any other treatment by `setParticles()` and will be passed three parameters.\n * This does nothing and may be overwritten by the user.\n * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param update the boolean update value actually passed to setParticles()\n */\n SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {\n };\n /**\n * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.\n * This will be passed three parameters.\n * This does nothing and may be overwritten by the user.\n * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param update the boolean update value actually passed to setParticles()\n */\n SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {\n };\n return SolidParticleSystem;\n }());\n BABYLON.SolidParticleSystem = SolidParticleSystem;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.solidParticleSystem.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class containing static functions to help procedurally build meshes\n */\n var MeshBuilder = /** @class */ (function () {\n function MeshBuilder() {\n }\n MeshBuilder.updateSideOrientation = function (orientation) {\n if (orientation == BABYLON.Mesh.DOUBLESIDE) {\n return BABYLON.Mesh.DOUBLESIDE;\n }\n if (orientation === undefined || orientation === null) {\n return BABYLON.Mesh.FRONTSIDE;\n }\n return orientation;\n };\n /**\n * Creates a box mesh\n * * The parameter `size` sets the size (float) of each box side (default 1)\n * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)\n * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements)\n * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the box mesh\n */\n MeshBuilder.CreateBox = function (name, options, scene) {\n if (scene === void 0) { scene = null; }\n var box = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n box._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateBox(options);\n vertexData.applyToMesh(box, options.updatable);\n return box;\n };\n /**\n * Creates a sphere mesh\n * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)\n * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)\n * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)\n * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio\n * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude)\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the sphere mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere\n */\n MeshBuilder.CreateSphere = function (name, options, scene) {\n var sphere = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n sphere._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateSphere(options);\n vertexData.applyToMesh(sphere, options.updatable);\n return sphere;\n };\n /**\n * Creates a plane polygonal mesh. By default, this is a disc\n * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)\n * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc\n * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the plane polygonal mesh\n * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon\n */\n MeshBuilder.CreateDisc = function (name, options, scene) {\n if (scene === void 0) { scene = null; }\n var disc = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n disc._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateDisc(options);\n vertexData.applyToMesh(disc, options.updatable);\n return disc;\n };\n /**\n * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided\n * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)\n * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`)\n * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size\n * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the icosahedron mesh\n * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere\n */\n MeshBuilder.CreateIcoSphere = function (name, options, scene) {\n var sphere = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n sphere._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateIcoSphere(options);\n vertexData.applyToMesh(sphere, options.updatable);\n return sphere;\n };\n ;\n /**\n * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters\n * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry\n * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array\n * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array\n * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path\n * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11\n * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones\n * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values\n * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry\n * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the ribbon mesh\n * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial\n * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes\n */\n MeshBuilder.CreateRibbon = function (name, options, scene) {\n if (scene === void 0) { scene = null; }\n var pathArray = options.pathArray;\n var closeArray = options.closeArray;\n var closePath = options.closePath;\n var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n var instance = options.instance;\n var updatable = options.updatable;\n if (instance) { // existing ribbon instance update\n // positionFunction : ribbon case\n // only pathArray and sideOrientation parameters are taken into account for positions update\n BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum\n BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);\n var positionFunction = function (positions) {\n var minlg = pathArray[0].length;\n var i = 0;\n var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;\n for (var si = 1; si <= ns; si++) {\n for (var p = 0; p < pathArray.length; p++) {\n var path = pathArray[p];\n var l = path.length;\n minlg = (minlg < l) ? minlg : l;\n var j = 0;\n while (j < minlg) {\n positions[i] = path[j].x;\n positions[i + 1] = path[j].y;\n positions[i + 2] = path[j].z;\n if (path[j].x < BABYLON.Tmp.Vector3[0].x) {\n BABYLON.Tmp.Vector3[0].x = path[j].x;\n }\n if (path[j].x > BABYLON.Tmp.Vector3[1].x) {\n BABYLON.Tmp.Vector3[1].x = path[j].x;\n }\n if (path[j].y < BABYLON.Tmp.Vector3[0].y) {\n BABYLON.Tmp.Vector3[0].y = path[j].y;\n }\n if (path[j].y > BABYLON.Tmp.Vector3[1].y) {\n BABYLON.Tmp.Vector3[1].y = path[j].y;\n }\n if (path[j].z < BABYLON.Tmp.Vector3[0].z) {\n BABYLON.Tmp.Vector3[0].z = path[j].z;\n }\n if (path[j].z > BABYLON.Tmp.Vector3[1].z) {\n BABYLON.Tmp.Vector3[1].z = path[j].z;\n }\n j++;\n i += 3;\n }\n if (instance._closePath) {\n positions[i] = path[0].x;\n positions[i + 1] = path[0].y;\n positions[i + 2] = path[0].z;\n i += 3;\n }\n }\n }\n };\n var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n positionFunction(positions);\n instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);\n instance._boundingInfo.update(instance._worldMatrix);\n instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);\n if (options.colors) {\n var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);\n for (var c = 0; c < options.colors.length; c++) {\n colors[c * 4] = options.colors[c].r;\n colors[c * 4 + 1] = options.colors[c].g;\n colors[c * 4 + 2] = options.colors[c].b;\n colors[c * 4 + 3] = options.colors[c].a;\n }\n instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);\n }\n if (options.uvs) {\n var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);\n for (var i = 0; i < options.uvs.length; i++) {\n uvs[i * 2] = options.uvs[i].x;\n uvs[i * 2 + 1] = options.uvs[i].y;\n }\n instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);\n }\n if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {\n var indices = instance.getIndices();\n var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;\n BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);\n if (instance._closePath) {\n var indexFirst = 0;\n var indexLast = 0;\n for (var p = 0; p < pathArray.length; p++) {\n indexFirst = instance._idx[p] * 3;\n if (p + 1 < pathArray.length) {\n indexLast = (instance._idx[p + 1] - 1) * 3;\n }\n else {\n indexLast = normals.length - 3;\n }\n normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;\n normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;\n normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;\n normals[indexLast] = normals[indexFirst];\n normals[indexLast + 1] = normals[indexFirst + 1];\n normals[indexLast + 2] = normals[indexFirst + 2];\n }\n }\n if (!(instance.areNormalsFrozen)) {\n instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);\n }\n }\n return instance;\n }\n else { // new ribbon creation\n var ribbon = new BABYLON.Mesh(name, scene);\n ribbon._originalBuilderSideOrientation = sideOrientation;\n var vertexData = BABYLON.VertexData.CreateRibbon(options);\n if (closePath) {\n ribbon._idx = vertexData._idx;\n }\n ribbon._closePath = closePath;\n ribbon._closeArray = closeArray;\n vertexData.applyToMesh(ribbon, updatable);\n return ribbon;\n }\n };\n /**\n * Creates a cylinder or a cone mesh\n * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).\n * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).\n * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter \"diameterBottom\" can't be zero.\n * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.\n * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).\n * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.\n * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.\n * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.\n * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).\n * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3\n * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7\n * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17\n * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.\n * * If `enclose` is false, a ring surface is one element.\n * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.\n * * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the cylinder mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone\n */\n MeshBuilder.CreateCylinder = function (name, options, scene) {\n var cylinder = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n cylinder._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateCylinder(options);\n vertexData.applyToMesh(cylinder, options.updatable);\n return cylinder;\n };\n /**\n * Creates a torus mesh\n * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)\n * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)\n * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the torus mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus\n */\n MeshBuilder.CreateTorus = function (name, options, scene) {\n var torus = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n torus._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateTorus(options);\n vertexData.applyToMesh(torus, options.updatable);\n return torus;\n };\n /**\n * Creates a torus knot mesh\n * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)\n * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)\n * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)\n * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the torus knot mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot\n */\n MeshBuilder.CreateTorusKnot = function (name, options, scene) {\n var torusKnot = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n torusKnot._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreateTorusKnot(options);\n vertexData.applyToMesh(torusKnot, options.updatable);\n return torusKnot;\n };\n /**\n * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh\n * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter\n * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function\n * * The parameter `lines` is an array of lines, each line being an array of successive Vector3\n * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter\n * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point\n * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)\n * * Updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines\n * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system\n * @param name defines the name of the new line system\n * @param options defines the options used to create the line system\n * @param scene defines the hosting scene\n * @returns a new line system mesh\n */\n MeshBuilder.CreateLineSystem = function (name, options, scene) {\n var instance = options.instance;\n var lines = options.lines;\n var colors = options.colors;\n if (instance) { // lines update\n var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var vertexColor;\n var lineColors;\n if (colors) {\n vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);\n }\n var i = 0;\n var c = 0;\n for (var l = 0; l < lines.length; l++) {\n var points = lines[l];\n for (var p = 0; p < points.length; p++) {\n positions[i] = points[p].x;\n positions[i + 1] = points[p].y;\n positions[i + 2] = points[p].z;\n if (colors && vertexColor) {\n lineColors = colors[l];\n vertexColor[c] = lineColors[p].r;\n vertexColor[c + 1] = lineColors[p].g;\n vertexColor[c + 2] = lineColors[p].b;\n vertexColor[c + 3] = lineColors[p].a;\n c += 4;\n }\n i += 3;\n }\n }\n instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);\n if (colors && vertexColor) {\n instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);\n }\n return instance;\n }\n // line system creation\n var useVertexColor = (colors) ? true : false;\n var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);\n var vertexData = BABYLON.VertexData.CreateLineSystem(options);\n vertexData.applyToMesh(lineSystem, options.updatable);\n return lineSystem;\n };\n /**\n * Creates a line mesh\n * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter\n * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function\n * * The parameter `points` is an array successive Vector3\n * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines\n * * The optional parameter `colors` is an array of successive Color4, one per line point\n * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)\n * * When updating an instance, remember that only point positions can change, not the number of points\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines\n * @param name defines the name of the new line system\n * @param options defines the options used to create the line system\n * @param scene defines the hosting scene\n * @returns a new line mesh\n */\n MeshBuilder.CreateLines = function (name, options, scene) {\n if (scene === void 0) { scene = null; }\n var colors = (options.colors) ? [options.colors] : null;\n var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);\n return lines;\n };\n /**\n * Creates a dashed line mesh\n * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter\n * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function\n * * The parameter `points` is an array successive Vector3\n * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)\n * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)\n * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)\n * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines\n * * When updating an instance, remember that only point positions can change, not the number of points\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the dashed line mesh\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines\n */\n MeshBuilder.CreateDashedLines = function (name, options, scene) {\n if (scene === void 0) { scene = null; }\n var points = options.points;\n var instance = options.instance;\n var gapSize = options.gapSize || 1;\n var dashSize = options.dashSize || 3;\n if (instance) { // dashed lines update\n var positionFunction = function (positions) {\n var curvect = BABYLON.Vector3.Zero();\n var nbSeg = positions.length / 6;\n var lg = 0;\n var nb = 0;\n var shft = 0;\n var dashshft = 0;\n var curshft = 0;\n var p = 0;\n var i = 0;\n var j = 0;\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n lg += curvect.length();\n }\n shft = lg / nbSeg;\n dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n nb = Math.floor(curvect.length() / shft);\n curvect.normalize();\n j = 0;\n while (j < nb && p < positions.length) {\n curshft = shft * j;\n positions[p] = points[i].x + curshft * curvect.x;\n positions[p + 1] = points[i].y + curshft * curvect.y;\n positions[p + 2] = points[i].z + curshft * curvect.z;\n positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;\n positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;\n positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;\n p += 6;\n j++;\n }\n }\n while (p < positions.length) {\n positions[p] = points[i].x;\n positions[p + 1] = points[i].y;\n positions[p + 2] = points[i].z;\n p += 3;\n }\n };\n instance.updateMeshPositions(positionFunction, false);\n return instance;\n }\n // dashed lines creation\n var dashedLines = new BABYLON.LinesMesh(name, scene);\n var vertexData = BABYLON.VertexData.CreateDashedLines(options);\n vertexData.applyToMesh(dashedLines, options.updatable);\n dashedLines.dashSize = dashSize;\n dashedLines.gapSize = gapSize;\n return dashedLines;\n };\n /**\n * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.\n * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.\n * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.\n * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.\n * * The parameter `scale` (float, default 1) is the value to scale the shape.\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape\n * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the extruded shape mesh\n * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes\n */\n MeshBuilder.ExtrudeShape = function (name, options, scene) {\n if (scene === void 0) { scene = null; }\n var path = options.path;\n var shape = options.shape;\n var scale = options.scale || 1;\n var rotation = options.rotation || 0;\n var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;\n var updatable = options.updatable;\n var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n var instance = options.instance || null;\n var invertUV = options.invertUV || false;\n return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null);\n };\n /**\n * Creates an custom extruded shape mesh.\n * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.\n * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.\n * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.\n * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path\n * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.\n * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path\n * * It must returns a float value that will be the scale value applied to the shape on each path point\n * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`\n * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape\n * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the custom extruded shape mesh\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes\n * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes\n */\n MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {\n var path = options.path;\n var shape = options.shape;\n var scaleFunction = options.scaleFunction || (function () { return 1; });\n var rotationFunction = options.rotationFunction || (function () { return 0; });\n var ribbonCloseArray = options.ribbonCloseArray || false;\n var ribbonClosePath = options.ribbonClosePath || false;\n var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;\n var updatable = options.updatable;\n var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n var instance = options.instance;\n var invertUV = options.invertUV || false;\n return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null);\n };\n /**\n * Creates lathe mesh.\n * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe\n * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero\n * * The parameter `radius` (positive float, default 1) is the radius value of the lathe\n * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe\n * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides\n * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape\n * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter \"arc\"\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the lathe mesh\n * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe\n */\n MeshBuilder.CreateLathe = function (name, options, scene) {\n var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;\n var closed = (options.closed === undefined) ? true : options.closed;\n var shape = options.shape;\n var radius = options.radius || 1;\n var tessellation = options.tessellation || 64;\n var clip = options.clip || 0;\n var updatable = options.updatable;\n var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n var cap = options.cap || BABYLON.Mesh.NO_CAP;\n var pi2 = Math.PI * 2;\n var paths = new Array();\n var invertUV = options.invertUV || false;\n var i = 0;\n var p = 0;\n var step = pi2 / tessellation * arc;\n var rotated;\n var path = new Array();\n for (i = 0; i <= tessellation - clip; i++) {\n var path = [];\n if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {\n path.push(new BABYLON.Vector3(0, shape[0].y, 0));\n path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));\n }\n for (p = 0; p < shape.length; p++) {\n rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);\n path.push(rotated);\n }\n if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {\n path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));\n path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));\n }\n paths.push(path);\n }\n // lathe ribbon\n var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);\n return lathe;\n };\n /**\n * Creates a plane mesh\n * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)\n * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)\n * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the plane mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane\n */\n MeshBuilder.CreatePlane = function (name, options, scene) {\n var plane = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n plane._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreatePlane(options);\n vertexData.applyToMesh(plane, options.updatable);\n if (options.sourcePlane) {\n plane.translate(options.sourcePlane.normal, options.sourcePlane.d);\n var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));\n var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);\n plane.rotate(vectorProduct, product);\n }\n return plane;\n };\n /**\n * Creates a ground mesh\n * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground\n * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the ground mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane\n */\n MeshBuilder.CreateGround = function (name, options, scene) {\n var ground = new BABYLON.GroundMesh(name, scene);\n ground._setReady(false);\n ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;\n ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;\n ground._width = options.width || 1;\n ground._height = options.height || 1;\n ground._maxX = ground._width / 2;\n ground._maxZ = ground._height / 2;\n ground._minX = -ground._maxX;\n ground._minZ = -ground._maxZ;\n var vertexData = BABYLON.VertexData.CreateGround(options);\n vertexData.applyToMesh(ground, options.updatable);\n ground._setReady(true);\n return ground;\n };\n /**\n * Creates a tiled ground mesh\n * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates\n * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates\n * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile\n * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the tiled ground mesh\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground\n */\n MeshBuilder.CreateTiledGround = function (name, options, scene) {\n var tiledGround = new BABYLON.Mesh(name, scene);\n var vertexData = BABYLON.VertexData.CreateTiledGround(options);\n vertexData.applyToMesh(tiledGround, options.updatable);\n return tiledGround;\n };\n /**\n * Creates a ground mesh from a height map\n * * The parameter `url` sets the URL of the height map image resource.\n * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.\n * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.\n * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.\n * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.\n * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.\n * * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param url defines the url to the height map\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the ground mesh\n * @see http://doc.babylonjs.com/babylon101/height_map\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map\n */\n MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {\n var width = options.width || 10.0;\n var height = options.height || 10.0;\n var subdivisions = options.subdivisions || 1 | 0;\n var minHeight = options.minHeight || 0.0;\n var maxHeight = options.maxHeight || 1.0;\n var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);\n var updatable = options.updatable;\n var onReady = options.onReady;\n var ground = new BABYLON.GroundMesh(name, scene);\n ground._subdivisionsX = subdivisions;\n ground._subdivisionsY = subdivisions;\n ground._width = width;\n ground._height = height;\n ground._maxX = ground._width / 2.0;\n ground._maxZ = ground._height / 2.0;\n ground._minX = -ground._maxX;\n ground._minZ = -ground._maxZ;\n ground._setReady(false);\n var onload = function (img) {\n // Getting height map data\n var canvas = document.createElement(\"canvas\");\n var context = canvas.getContext(\"2d\");\n if (!context) {\n throw new Error(\"Unable to get 2d context for CreateGroundFromHeightMap\");\n }\n if (scene.isDisposed) {\n return;\n }\n var bufferWidth = img.width;\n var bufferHeight = img.height;\n canvas.width = bufferWidth;\n canvas.height = bufferHeight;\n context.drawImage(img, 0, 0);\n // Create VertexData from map data\n // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949\n var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;\n var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({\n width: width, height: height,\n subdivisions: subdivisions,\n minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,\n buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight\n });\n vertexData.applyToMesh(ground, updatable);\n //execute ready callback, if set\n if (onReady) {\n onReady(ground);\n }\n ground._setReady(true);\n };\n BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);\n return ground;\n };\n /**\n * Creates a polygon mesh\n * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh\n * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors\n * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4)\n * * Remember you can only change the shape positions, not their number when updating a polygon\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the polygon mesh\n */\n MeshBuilder.CreatePolygon = function (name, options, scene) {\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n var shape = options.shape;\n var holes = options.holes || [];\n var depth = options.depth || 0;\n var contours = [];\n var hole = [];\n for (var i = 0; i < shape.length; i++) {\n contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);\n }\n var epsilon = 0.00000001;\n if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {\n contours.pop();\n }\n var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);\n for (var hNb = 0; hNb < holes.length; hNb++) {\n hole = [];\n for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {\n hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));\n }\n polygonTriangulation.addHole(hole);\n }\n var polygon = polygonTriangulation.build(options.updatable, depth);\n polygon._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);\n vertexData.applyToMesh(polygon, options.updatable);\n return polygon;\n };\n ;\n /**\n * Creates an extruded polygon mesh, with depth in the Y direction.\n * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements)\n * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the polygon mesh\n */\n MeshBuilder.ExtrudePolygon = function (name, options, scene) {\n return MeshBuilder.CreatePolygon(name, options, scene);\n };\n ;\n /**\n * Creates a tube mesh.\n * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters\n * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube\n * * The parameter `radius` (positive float, default 1) sets the tube radius size\n * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface\n * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`\n * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)\n * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the tube mesh\n * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes\n * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube\n */\n MeshBuilder.CreateTube = function (name, options, scene) {\n var path = options.path;\n var instance = options.instance;\n var radius = 1.0;\n if (instance) {\n radius = instance.radius;\n }\n if (options.radius !== undefined) {\n radius = options.radius;\n }\n ;\n var tessellation = options.tessellation || 64 | 0;\n var radiusFunction = options.radiusFunction || null;\n var cap = options.cap || BABYLON.Mesh.NO_CAP;\n var invertUV = options.invertUV || false;\n var updatable = options.updatable;\n var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;\n // tube geometry\n var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {\n var tangents = path3D.getTangents();\n var normals = path3D.getNormals();\n var distances = path3D.getDistances();\n var pi2 = Math.PI * 2;\n var step = pi2 / tessellation * arc;\n var returnRadius = function () { return radius; };\n var radiusFunctionFinal = radiusFunction || returnRadius;\n var circlePath;\n var rad;\n var normal;\n var rotated;\n var rotationMatrix = BABYLON.Tmp.Matrix[0];\n var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;\n for (var i = 0; i < path.length; i++) {\n rad = radiusFunctionFinal(i, distances[i]); // current radius\n circlePath = Array(); // current circle array\n normal = normals[i]; // current normal\n for (var t = 0; t < tessellation; t++) {\n BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);\n rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();\n BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);\n rotated.scaleInPlace(rad).addInPlace(path[i]);\n circlePath[t] = rotated;\n }\n circlePaths[index] = circlePath;\n index++;\n }\n // cap\n var capPath = function (nbPoints, pathIndex) {\n var pointCap = Array();\n for (var i = 0; i < nbPoints; i++) {\n pointCap.push(path[pathIndex]);\n }\n return pointCap;\n };\n switch (cap) {\n case BABYLON.Mesh.NO_CAP:\n break;\n case BABYLON.Mesh.CAP_START:\n circlePaths[0] = capPath(tessellation, 0);\n circlePaths[1] = circlePaths[2].slice(0);\n break;\n case BABYLON.Mesh.CAP_END:\n circlePaths[index] = circlePaths[index - 1].slice(0);\n circlePaths[index + 1] = capPath(tessellation, path.length - 1);\n break;\n case BABYLON.Mesh.CAP_ALL:\n circlePaths[0] = capPath(tessellation, 0);\n circlePaths[1] = circlePaths[2].slice(0);\n circlePaths[index] = circlePaths[index - 1].slice(0);\n circlePaths[index + 1] = capPath(tessellation, path.length - 1);\n break;\n default:\n break;\n }\n return circlePaths;\n };\n var path3D;\n var pathArray;\n if (instance) { // tube update\n var arc = options.arc || instance.arc;\n path3D = (instance.path3D).update(path);\n pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);\n instance = MeshBuilder.CreateRibbon(\"\", { pathArray: pathArray, instance: instance });\n instance.path3D = path3D;\n instance.pathArray = pathArray;\n instance.arc = arc;\n instance.radius = radius;\n return instance;\n }\n // tube creation\n path3D = new BABYLON.Path3D(path);\n var newPathArray = new Array();\n cap = (cap < 0 || cap > 3) ? 0 : cap;\n pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);\n var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);\n tube.pathArray = pathArray;\n tube.path3D = path3D;\n tube.tessellation = tessellation;\n tube.cap = cap;\n tube.arc = options.arc;\n tube.radius = radius;\n return tube;\n };\n /**\n * Creates a polyhedron mesh\n * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type\n * * The parameter `size` (positive float, default 1) sets the polygon size\n * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)\n * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`\n * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron\n * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`)\n * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors\n * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the polyhedron mesh\n * @see http://doc.babylonjs.com/how_to/polyhedra_shapes\n */\n MeshBuilder.CreatePolyhedron = function (name, options, scene) {\n var polyhedron = new BABYLON.Mesh(name, scene);\n options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);\n polyhedron._originalBuilderSideOrientation = options.sideOrientation;\n var vertexData = BABYLON.VertexData.CreatePolyhedron(options);\n vertexData.applyToMesh(polyhedron, options.updatable);\n return polyhedron;\n };\n /**\n * Creates a decal mesh.\n * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal\n * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates\n * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates\n * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling\n * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal\n * @param name defines the name of the mesh\n * @param sourceMesh defines the mesh where the decal must be applied\n * @param options defines the options used to create the mesh\n * @param scene defines the hosting scene\n * @returns the decal mesh\n * @see http://doc.babylonjs.com/how_to/decals\n */\n MeshBuilder.CreateDecal = function (name, sourceMesh, options) {\n var indices = sourceMesh.getIndices();\n var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var position = options.position || BABYLON.Vector3.Zero();\n var normal = options.normal || BABYLON.Vector3.Up();\n var size = options.size || BABYLON.Vector3.One();\n var angle = options.angle || 0;\n // Getting correct rotation\n if (!normal) {\n var target = new BABYLON.Vector3(0, 0, 1);\n var camera = sourceMesh.getScene().activeCamera;\n var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());\n normal = camera.globalPosition.subtract(cameraWorldTarget);\n }\n var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;\n var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);\n var pitch = Math.atan2(normal.y, len);\n // Matrix\n var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));\n var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);\n var meshWorldMatrix = sourceMesh.getWorldMatrix();\n var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);\n var vertexData = new BABYLON.VertexData();\n vertexData.indices = [];\n vertexData.positions = [];\n vertexData.normals = [];\n vertexData.uvs = [];\n var currentVertexDataIndex = 0;\n var extractDecalVector3 = function (indexId) {\n var result = new BABYLON.PositionNormalVertex();\n if (!indices || !positions || !normals) {\n return result;\n }\n var vertexId = indices[indexId];\n result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);\n // Send vector to decal local world\n result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);\n // Get normal\n result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);\n result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);\n return result;\n }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js\n var clip = function (vertices, axis) {\n if (vertices.length === 0) {\n return vertices;\n }\n var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));\n var clipVertices = function (v0, v1) {\n var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);\n return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));\n };\n var result = new Array();\n for (var index = 0; index < vertices.length; index += 3) {\n var v1Out;\n var v2Out;\n var v3Out;\n var total = 0;\n var nV1 = null;\n var nV2 = null;\n var nV3 = null;\n var nV4 = null;\n var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;\n var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;\n var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;\n v1Out = d1 > 0;\n v2Out = d2 > 0;\n v3Out = d3 > 0;\n total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);\n switch (total) {\n case 0:\n result.push(vertices[index]);\n result.push(vertices[index + 1]);\n result.push(vertices[index + 2]);\n break;\n case 1:\n if (v1Out) {\n nV1 = vertices[index + 1];\n nV2 = vertices[index + 2];\n nV3 = clipVertices(vertices[index], nV1);\n nV4 = clipVertices(vertices[index], nV2);\n }\n if (v2Out) {\n nV1 = vertices[index];\n nV2 = vertices[index + 2];\n nV3 = clipVertices(vertices[index + 1], nV1);\n nV4 = clipVertices(vertices[index + 1], nV2);\n result.push(nV3);\n result.push(nV2.clone());\n result.push(nV1.clone());\n result.push(nV2.clone());\n result.push(nV3.clone());\n result.push(nV4);\n break;\n }\n if (v3Out) {\n nV1 = vertices[index];\n nV2 = vertices[index + 1];\n nV3 = clipVertices(vertices[index + 2], nV1);\n nV4 = clipVertices(vertices[index + 2], nV2);\n }\n if (nV1 && nV2 && nV3 && nV4) {\n result.push(nV1.clone());\n result.push(nV2.clone());\n result.push(nV3);\n result.push(nV4);\n result.push(nV3.clone());\n result.push(nV2.clone());\n }\n break;\n case 2:\n if (!v1Out) {\n nV1 = vertices[index].clone();\n nV2 = clipVertices(nV1, vertices[index + 1]);\n nV3 = clipVertices(nV1, vertices[index + 2]);\n result.push(nV1);\n result.push(nV2);\n result.push(nV3);\n }\n if (!v2Out) {\n nV1 = vertices[index + 1].clone();\n nV2 = clipVertices(nV1, vertices[index + 2]);\n nV3 = clipVertices(nV1, vertices[index]);\n result.push(nV1);\n result.push(nV2);\n result.push(nV3);\n }\n if (!v3Out) {\n nV1 = vertices[index + 2].clone();\n nV2 = clipVertices(nV1, vertices[index]);\n nV3 = clipVertices(nV1, vertices[index + 1]);\n result.push(nV1);\n result.push(nV2);\n result.push(nV3);\n }\n break;\n case 3:\n break;\n }\n }\n return result;\n };\n for (var index = 0; index < indices.length; index += 3) {\n var faceVertices = new Array();\n faceVertices.push(extractDecalVector3(index));\n faceVertices.push(extractDecalVector3(index + 1));\n faceVertices.push(extractDecalVector3(index + 2));\n // Clip\n faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));\n faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));\n faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));\n faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));\n faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));\n faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));\n if (faceVertices.length === 0) {\n continue;\n }\n // Add UVs and get back to world\n for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {\n var vertex = faceVertices[vIndex];\n //TODO check for Int32Array | Uint32Array | Uint16Array\n vertexData.indices.push(currentVertexDataIndex);\n vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);\n vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);\n vertexData.uvs.push(0.5 + vertex.position.x / size.x);\n vertexData.uvs.push(0.5 + vertex.position.y / size.y);\n currentVertexDataIndex++;\n }\n }\n // Return mesh\n var decal = new BABYLON.Mesh(name, sourceMesh.getScene());\n vertexData.applyToMesh(decal);\n decal.position = position.clone();\n decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);\n return decal;\n };\n // Privates\n MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {\n // extrusion geometry\n var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {\n var tangents = path3D.getTangents();\n var normals = path3D.getNormals();\n var binormals = path3D.getBinormals();\n var distances = path3D.getDistances();\n var angle = 0;\n var returnScale = function () { return scale !== null ? scale : 1; };\n var returnRotation = function () { return rotation !== null ? rotation : 0; };\n var rotate = custom && rotateFunction ? rotateFunction : returnRotation;\n var scl = custom && scaleFunction ? scaleFunction : returnScale;\n var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;\n var rotationMatrix = BABYLON.Tmp.Matrix[0];\n for (var i = 0; i < curve.length; i++) {\n var shapePath = new Array();\n var angleStep = rotate(i, distances[i]);\n var scaleRatio = scl(i, distances[i]);\n for (var p = 0; p < shape.length; p++) {\n BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);\n var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));\n var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();\n BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);\n rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);\n shapePath[p] = rotated;\n }\n shapePaths[index] = shapePath;\n angle += angleStep;\n index++;\n }\n // cap\n var capPath = function (shapePath) {\n var pointCap = Array();\n var barycenter = BABYLON.Vector3.Zero();\n var i;\n for (i = 0; i < shapePath.length; i++) {\n barycenter.addInPlace(shapePath[i]);\n }\n barycenter.scaleInPlace(1.0 / shapePath.length);\n for (i = 0; i < shapePath.length; i++) {\n pointCap.push(barycenter);\n }\n return pointCap;\n };\n switch (cap) {\n case BABYLON.Mesh.NO_CAP:\n break;\n case BABYLON.Mesh.CAP_START:\n shapePaths[0] = capPath(shapePaths[2]);\n shapePaths[1] = shapePaths[2];\n break;\n case BABYLON.Mesh.CAP_END:\n shapePaths[index] = shapePaths[index - 1];\n shapePaths[index + 1] = capPath(shapePaths[index - 1]);\n break;\n case BABYLON.Mesh.CAP_ALL:\n shapePaths[0] = capPath(shapePaths[2]);\n shapePaths[1] = shapePaths[2];\n shapePaths[index] = shapePaths[index - 1];\n shapePaths[index + 1] = capPath(shapePaths[index - 1]);\n break;\n default:\n break;\n }\n return shapePaths;\n };\n var path3D;\n var pathArray;\n if (instance) { // instance update\n path3D = (instance.path3D).update(curve);\n pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);\n instance = BABYLON.Mesh.CreateRibbon(\"\", pathArray, false, false, 0, scene || undefined, false, 0, instance);\n return instance;\n }\n // extruded shape creation\n path3D = new BABYLON.Path3D(curve);\n var newShapePaths = new Array();\n cap = (cap < 0 || cap > 3) ? 0 : cap;\n pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);\n var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);\n extrudedGeneric.pathArray = pathArray;\n extrudedGeneric.path3D = path3D;\n extrudedGeneric.cap = cap;\n return extrudedGeneric;\n };\n return MeshBuilder;\n }());\n BABYLON.MeshBuilder = MeshBuilder;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.meshBuilder.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Draco compression (https://google.github.io/draco/)\n *\n * This class wraps the Draco module.\n *\n * **Encoder**\n *\n * The encoder is not currently implemented.\n *\n * **Decoder**\n *\n * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.\n *\n * To update the configuration, use the following code:\n * ```javascript\n * BABYLON.DracoCompression.Configuration = {\n * decoder: {\n * wasmUrl: \"\",\n * wasmBinaryUrl: \"\",\n * fallbackUrl: \"\",\n * }\n * };\n * ```\n *\n * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.\n * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.\n * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.\n *\n * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:\n * ```javascript\n * var dracoCompression = new BABYLON.DracoCompression();\n * var vertexData = await dracoCompression.decodeMeshAsync(data, {\n * [BABYLON.VertexBuffer.PositionKind]: 0\n * });\n * ```\n *\n * @see https://www.babylonjs-playground.com/#N3EK4B#0\n */\n var DracoCompression = /** @class */ (function () {\n /**\n * Constructor\n */\n function DracoCompression() {\n }\n Object.defineProperty(DracoCompression, \"DecoderAvailable\", {\n /**\n * Returns true if the decoder is available.\n */\n get: function () {\n if (typeof DracoDecoderModule !== \"undefined\") {\n return true;\n }\n var decoder = DracoCompression.Configuration.decoder;\n if (decoder) {\n if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === \"object\") {\n return true;\n }\n if (decoder.fallbackUrl) {\n return true;\n }\n }\n return false;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Stop all async operations and release resources.\n */\n DracoCompression.prototype.dispose = function () {\n };\n /**\n * Decode Draco compressed mesh data to vertex data.\n * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data\n * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids\n * @returns A promise that resolves with the decoded vertex data\n */\n DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {\n var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;\n return DracoCompression._GetDecoderModule().then(function (wrappedModule) {\n var module = wrappedModule.module;\n var vertexData = new BABYLON.VertexData();\n var buffer = new module.DecoderBuffer();\n buffer.Init(dataView, dataView.byteLength);\n var decoder = new module.Decoder();\n var geometry;\n var status;\n try {\n var type = decoder.GetEncodedGeometryType(buffer);\n switch (type) {\n case module.TRIANGULAR_MESH:\n geometry = new module.Mesh();\n status = decoder.DecodeBufferToMesh(buffer, geometry);\n break;\n case module.POINT_CLOUD:\n geometry = new module.PointCloud();\n status = decoder.DecodeBufferToPointCloud(buffer, geometry);\n break;\n default:\n throw new Error(\"Invalid geometry type \" + type);\n }\n if (!status.ok() || !geometry.ptr) {\n throw new Error(status.error_msg());\n }\n var numPoints = geometry.num_points();\n if (type === module.TRIANGULAR_MESH) {\n var numFaces = geometry.num_faces();\n var faceIndices = new module.DracoInt32Array();\n try {\n var indices = new Uint32Array(numFaces * 3);\n for (var i = 0; i < numFaces; i++) {\n decoder.GetFaceFromMesh(geometry, i, faceIndices);\n var offset = i * 3;\n indices[offset + 0] = faceIndices.GetValue(0);\n indices[offset + 1] = faceIndices.GetValue(1);\n indices[offset + 2] = faceIndices.GetValue(2);\n }\n vertexData.indices = indices;\n }\n finally {\n module.destroy(faceIndices);\n }\n }\n for (var kind in attributes) {\n var uniqueId = attributes[kind];\n var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);\n var dracoData = new module.DracoFloat32Array();\n try {\n decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);\n var babylonData = new Float32Array(numPoints * attribute.num_components());\n for (var i = 0; i < babylonData.length; i++) {\n babylonData[i] = dracoData.GetValue(i);\n }\n vertexData.set(babylonData, kind);\n }\n finally {\n module.destroy(dracoData);\n }\n }\n }\n finally {\n if (geometry) {\n module.destroy(geometry);\n }\n module.destroy(decoder);\n module.destroy(buffer);\n }\n return vertexData;\n });\n };\n DracoCompression._GetDecoderModule = function () {\n if (!DracoCompression._DecoderModulePromise) {\n var promise = null;\n var config_1 = {};\n if (typeof DracoDecoderModule !== \"undefined\") {\n promise = Promise.resolve();\n }\n else {\n var decoder = DracoCompression.Configuration.decoder;\n if (decoder) {\n if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === \"object\") {\n promise = Promise.all([\n DracoCompression._LoadScriptAsync(decoder.wasmUrl),\n DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {\n config_1.wasmBinary = data;\n })\n ]);\n }\n else if (decoder.fallbackUrl) {\n promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);\n }\n }\n }\n if (!promise) {\n throw new Error(\"Draco decoder module is not available\");\n }\n DracoCompression._DecoderModulePromise = promise.then(function () {\n return new Promise(function (resolve) {\n config_1.onModuleLoaded = function (decoderModule) {\n // decoderModule is Promise-like. Wrap before resolving to avoid loop.\n resolve({ module: decoderModule });\n };\n DracoDecoderModule(config_1);\n });\n });\n }\n return DracoCompression._DecoderModulePromise;\n };\n DracoCompression._LoadScriptAsync = function (url) {\n return new Promise(function (resolve, reject) {\n BABYLON.Tools.LoadScript(url, function () {\n resolve();\n }, function (message) {\n reject(new Error(message));\n });\n });\n };\n DracoCompression._LoadFileAsync = function (url) {\n return new Promise(function (resolve, reject) {\n BABYLON.Tools.LoadFile(url, function (data) {\n resolve(data);\n }, undefined, undefined, true, function (request, exception) {\n reject(exception);\n });\n });\n };\n /**\n * The configuration. Defaults to the following urls:\n * - wasmUrl: \"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js\"\n * - wasmBinaryUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.wasm\"\n * - fallbackUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.js\"\n */\n DracoCompression.Configuration = {\n decoder: {\n wasmUrl: \"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js\",\n wasmBinaryUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.wasm\",\n fallbackUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.js\"\n }\n };\n return DracoCompression;\n }());\n BABYLON.DracoCompression = DracoCompression;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.dracoCompression.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var AudioEngine = /** @class */ (function () {\n function AudioEngine() {\n this._audioContext = null;\n this._audioContextInitialized = false;\n this.canUseWebAudio = false;\n this.WarnedWebAudioUnsupported = false;\n this.unlocked = false;\n this.isMP3supported = false;\n this.isOGGsupported = false;\n if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {\n window.AudioContext = window.AudioContext || window.webkitAudioContext;\n this.canUseWebAudio = true;\n }\n var audioElem = document.createElement('audio');\n try {\n if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs=\"mp3\"').replace(/^no$/, '')) {\n this.isMP3supported = true;\n }\n }\n catch (e) {\n // protect error during capability check.\n }\n try {\n if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs=\"vorbis\"').replace(/^no$/, '')) {\n this.isOGGsupported = true;\n }\n }\n catch (e) {\n // protect error during capability check.\n }\n if (/iPad|iPhone|iPod/.test(navigator.platform)) {\n this._unlockiOSaudio();\n }\n else {\n this.unlocked = true;\n }\n }\n Object.defineProperty(AudioEngine.prototype, \"audioContext\", {\n get: function () {\n if (!this._audioContextInitialized) {\n this._initializeAudioContext();\n }\n return this._audioContext;\n },\n enumerable: true,\n configurable: true\n });\n AudioEngine.prototype._unlockiOSaudio = function () {\n var _this = this;\n var unlockaudio = function () {\n if (!_this.audioContext) {\n return;\n }\n var buffer = _this.audioContext.createBuffer(1, 1, 22050);\n var source = _this.audioContext.createBufferSource();\n source.buffer = buffer;\n source.connect(_this.audioContext.destination);\n source.start(0);\n setTimeout(function () {\n if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {\n _this.unlocked = true;\n window.removeEventListener('touchend', unlockaudio, false);\n if (_this.onAudioUnlocked) {\n _this.onAudioUnlocked();\n }\n }\n }, 0);\n };\n window.addEventListener('touchend', unlockaudio, false);\n };\n AudioEngine.prototype._initializeAudioContext = function () {\n try {\n if (this.canUseWebAudio) {\n this._audioContext = new AudioContext();\n // create a global volume gain node \n this.masterGain = this._audioContext.createGain();\n this.masterGain.gain.value = 1;\n this.masterGain.connect(this._audioContext.destination);\n this._audioContextInitialized = true;\n }\n }\n catch (e) {\n this.canUseWebAudio = false;\n BABYLON.Tools.Error(\"Web Audio: \" + e.message);\n }\n };\n AudioEngine.prototype.dispose = function () {\n if (this.canUseWebAudio && this._audioContextInitialized) {\n if (this._connectedAnalyser && this._audioContext) {\n this._connectedAnalyser.stopDebugCanvas();\n this._connectedAnalyser.dispose();\n this.masterGain.disconnect();\n this.masterGain.connect(this._audioContext.destination);\n this._connectedAnalyser = null;\n }\n this.masterGain.gain.value = 1;\n }\n this.WarnedWebAudioUnsupported = false;\n };\n AudioEngine.prototype.getGlobalVolume = function () {\n if (this.canUseWebAudio && this._audioContextInitialized) {\n return this.masterGain.gain.value;\n }\n else {\n return -1;\n }\n };\n AudioEngine.prototype.setGlobalVolume = function (newVolume) {\n if (this.canUseWebAudio && this._audioContextInitialized) {\n this.masterGain.gain.value = newVolume;\n }\n };\n AudioEngine.prototype.connectToAnalyser = function (analyser) {\n if (this._connectedAnalyser) {\n this._connectedAnalyser.stopDebugCanvas();\n }\n if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {\n this._connectedAnalyser = analyser;\n this.masterGain.disconnect();\n this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);\n }\n };\n return AudioEngine;\n }());\n BABYLON.AudioEngine = AudioEngine;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.audioEngine.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Sound = /** @class */ (function () {\n /**\n * Create a sound and attach it to a scene\n * @param name Name of your sound\n * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams\n * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played\n * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming\n */\n function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {\n if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }\n var _this = this;\n this.autoplay = false;\n this.loop = false;\n this.useCustomAttenuation = false;\n this.spatialSound = false;\n this.refDistance = 1;\n this.rolloffFactor = 1;\n this.maxDistance = 100;\n this.distanceModel = \"linear\";\n this._panningModel = \"equalpower\";\n this._playbackRate = 1;\n this._streaming = false;\n this._startTime = 0;\n this._startOffset = 0;\n this._position = BABYLON.Vector3.Zero();\n this._localDirection = new BABYLON.Vector3(1, 0, 0);\n this._volume = 1;\n this._isReadyToPlay = false;\n this.isPlaying = false;\n this.isPaused = false;\n this._isDirectional = false;\n // Used if you'd like to create a directional sound.\n // If not set, the sound will be omnidirectional\n this._coneInnerAngle = 360;\n this._coneOuterAngle = 360;\n this._coneOuterGain = 0;\n this._isOutputConnected = false;\n this._urlType = \"Unknown\";\n this.name = name;\n this._scene = scene;\n this._readyToPlayCallback = readyToPlayCallback;\n // Default custom attenuation function is a linear attenuation\n this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {\n if (currentDistance < maxDistance) {\n return currentVolume * (1 - currentDistance / maxDistance);\n }\n else {\n return 0;\n }\n };\n if (options) {\n this.autoplay = options.autoplay || false;\n this.loop = options.loop || false;\n // if volume === 0, we need another way to check this option\n if (options.volume !== undefined) {\n this._volume = options.volume;\n }\n this.spatialSound = options.spatialSound || false;\n this.maxDistance = options.maxDistance || 100;\n this.useCustomAttenuation = options.useCustomAttenuation || false;\n this.rolloffFactor = options.rolloffFactor || 1;\n this.refDistance = options.refDistance || 1;\n this.distanceModel = options.distanceModel || \"linear\";\n this._playbackRate = options.playbackRate || 1;\n this._streaming = options.streaming || false;\n }\n if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {\n this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();\n this._soundGain.gain.value = this._volume;\n this._inputAudioNode = this._soundGain;\n this._ouputAudioNode = this._soundGain;\n if (this.spatialSound) {\n this._createSpatialParameters();\n }\n this._scene.mainSoundTrack.AddSound(this);\n var validParameter = true;\n // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound\n if (urlOrArrayBuffer) {\n try {\n if (typeof (urlOrArrayBuffer) === \"string\") {\n this._urlType = \"String\";\n }\n else if (urlOrArrayBuffer instanceof ArrayBuffer) {\n this._urlType = \"ArrayBuffer\";\n }\n else if (urlOrArrayBuffer instanceof MediaStream) {\n this._urlType = \"MediaStream\";\n }\n else if (Array.isArray(urlOrArrayBuffer)) {\n this._urlType = \"Array\";\n }\n var urls = [];\n var codecSupportedFound = false;\n switch (this._urlType) {\n case \"MediaStream\":\n this._streaming = true;\n this._isReadyToPlay = true;\n this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);\n if (this.autoplay) {\n this.play();\n }\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n break;\n case \"ArrayBuffer\":\n if (urlOrArrayBuffer.byteLength > 0) {\n codecSupportedFound = true;\n this._soundLoaded(urlOrArrayBuffer);\n }\n break;\n case \"String\":\n urls.push(urlOrArrayBuffer);\n case \"Array\":\n if (urls.length === 0)\n urls = urlOrArrayBuffer;\n // If we found a supported format, we load it immediately and stop the loop\n for (var i = 0; i < urls.length; i++) {\n var url = urls[i];\n if (url.indexOf(\".mp3\", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {\n codecSupportedFound = true;\n }\n if (url.indexOf(\".ogg\", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {\n codecSupportedFound = true;\n }\n if (url.indexOf(\".wav\", url.length - 4) !== -1) {\n codecSupportedFound = true;\n }\n if (url.indexOf(\"blob:\") !== -1) {\n codecSupportedFound = true;\n }\n if (codecSupportedFound) {\n // Loading sound using XHR2\n if (!this._streaming) {\n this._scene._loadFile(url, function (data) {\n _this._soundLoaded(data);\n }, undefined, true, true, function (exception) {\n if (exception) {\n BABYLON.Tools.Error(\"XHR \" + exception.status + \" error on: \" + url + \".\");\n }\n BABYLON.Tools.Error(\"Sound creation aborted.\");\n _this._scene.mainSoundTrack.RemoveSound(_this);\n });\n }\n // Streaming sound using HTML5 Audio tag\n else {\n this._htmlAudioElement = new Audio(url);\n this._htmlAudioElement.controls = false;\n this._htmlAudioElement.loop = this.loop;\n BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);\n this._htmlAudioElement.preload = \"auto\";\n this._htmlAudioElement.addEventListener(\"canplaythrough\", function () {\n _this._isReadyToPlay = true;\n if (_this.autoplay) {\n _this.play();\n }\n if (_this._readyToPlayCallback) {\n _this._readyToPlayCallback();\n }\n });\n document.body.appendChild(this._htmlAudioElement);\n }\n break;\n }\n }\n break;\n default:\n validParameter = false;\n break;\n }\n if (!validParameter) {\n BABYLON.Tools.Error(\"Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.\");\n }\n else {\n if (!codecSupportedFound) {\n this._isReadyToPlay = true;\n // Simulating a ready to play event to avoid breaking code path\n if (this._readyToPlayCallback) {\n window.setTimeout(function () {\n if (_this._readyToPlayCallback) {\n _this._readyToPlayCallback();\n }\n }, 1000);\n }\n }\n }\n }\n catch (ex) {\n BABYLON.Tools.Error(\"Unexpected error. Sound creation aborted.\");\n this._scene.mainSoundTrack.RemoveSound(this);\n }\n }\n }\n else {\n // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers\n this._scene.mainSoundTrack.AddSound(this);\n if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {\n BABYLON.Tools.Error(\"Web Audio is not supported by your browser.\");\n BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;\n }\n // Simulating a ready to play event to avoid breaking code for non web audio browsers\n if (this._readyToPlayCallback) {\n window.setTimeout(function () {\n if (_this._readyToPlayCallback) {\n _this._readyToPlayCallback();\n }\n }, 1000);\n }\n }\n }\n Sound.prototype.dispose = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio) {\n if (this.isPlaying) {\n this.stop();\n }\n this._isReadyToPlay = false;\n if (this.soundTrackId === -1) {\n this._scene.mainSoundTrack.RemoveSound(this);\n }\n else {\n this._scene.soundTracks[this.soundTrackId].RemoveSound(this);\n }\n if (this._soundGain) {\n this._soundGain.disconnect();\n this._soundGain = null;\n }\n if (this._soundPanner) {\n this._soundPanner.disconnect();\n this._soundPanner = null;\n }\n if (this._soundSource) {\n this._soundSource.disconnect();\n this._soundSource = null;\n }\n this._audioBuffer = null;\n if (this._htmlAudioElement) {\n this._htmlAudioElement.pause();\n this._htmlAudioElement.src = \"\";\n document.body.removeChild(this._htmlAudioElement);\n }\n if (this._streamingSource) {\n this._streamingSource.disconnect();\n }\n if (this._connectedMesh && this._registerFunc) {\n this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);\n this._connectedMesh = null;\n }\n }\n };\n Sound.prototype.isReady = function () {\n return this._isReadyToPlay;\n };\n Sound.prototype._soundLoaded = function (audioData) {\n var _this = this;\n if (!BABYLON.Engine.audioEngine.audioContext) {\n return;\n }\n BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {\n _this._audioBuffer = buffer;\n _this._isReadyToPlay = true;\n if (_this.autoplay) {\n _this.play();\n }\n if (_this._readyToPlayCallback) {\n _this._readyToPlayCallback();\n }\n }, function (err) { BABYLON.Tools.Error(\"Error while decoding audio data for: \" + _this.name + \" / Error: \" + err); });\n };\n Sound.prototype.setAudioBuffer = function (audioBuffer) {\n if (BABYLON.Engine.audioEngine.canUseWebAudio) {\n this._audioBuffer = audioBuffer;\n this._isReadyToPlay = true;\n }\n };\n Sound.prototype.updateOptions = function (options) {\n if (options) {\n this.loop = options.loop || this.loop;\n this.maxDistance = options.maxDistance || this.maxDistance;\n this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;\n this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;\n this.refDistance = options.refDistance || this.refDistance;\n this.distanceModel = options.distanceModel || this.distanceModel;\n this._playbackRate = options.playbackRate || this._playbackRate;\n this._updateSpatialParameters();\n if (this.isPlaying) {\n if (this._streaming && this._htmlAudioElement) {\n this._htmlAudioElement.playbackRate = this._playbackRate;\n }\n else {\n if (this._soundSource) {\n this._soundSource.playbackRate.value = this._playbackRate;\n }\n }\n }\n }\n };\n Sound.prototype._createSpatialParameters = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {\n if (this._scene.headphone) {\n this._panningModel = \"HRTF\";\n }\n this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();\n this._updateSpatialParameters();\n this._soundPanner.connect(this._ouputAudioNode);\n this._inputAudioNode = this._soundPanner;\n }\n };\n Sound.prototype._updateSpatialParameters = function () {\n if (this.spatialSound && this._soundPanner) {\n if (this.useCustomAttenuation) {\n // Tricks to disable in a way embedded Web Audio attenuation \n this._soundPanner.distanceModel = \"linear\";\n this._soundPanner.maxDistance = Number.MAX_VALUE;\n this._soundPanner.refDistance = 1;\n this._soundPanner.rolloffFactor = 1;\n this._soundPanner.panningModel = this._panningModel;\n }\n else {\n this._soundPanner.distanceModel = this.distanceModel;\n this._soundPanner.maxDistance = this.maxDistance;\n this._soundPanner.refDistance = this.refDistance;\n this._soundPanner.rolloffFactor = this.rolloffFactor;\n this._soundPanner.panningModel = this._panningModel;\n }\n }\n };\n Sound.prototype.switchPanningModelToHRTF = function () {\n this._panningModel = \"HRTF\";\n this._switchPanningModel();\n };\n Sound.prototype.switchPanningModelToEqualPower = function () {\n this._panningModel = \"equalpower\";\n this._switchPanningModel();\n };\n Sound.prototype._switchPanningModel = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {\n this._soundPanner.panningModel = this._panningModel;\n }\n };\n Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {\n if (BABYLON.Engine.audioEngine.canUseWebAudio) {\n if (this._isOutputConnected) {\n this._ouputAudioNode.disconnect();\n }\n this._ouputAudioNode.connect(soundTrackAudioNode);\n this._isOutputConnected = true;\n }\n };\n /**\n * Transform this sound into a directional source\n * @param coneInnerAngle Size of the inner cone in degree\n * @param coneOuterAngle Size of the outer cone in degree\n * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)\n */\n Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {\n if (coneOuterAngle < coneInnerAngle) {\n BABYLON.Tools.Error(\"setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.\");\n return;\n }\n this._coneInnerAngle = coneInnerAngle;\n this._coneOuterAngle = coneOuterAngle;\n this._coneOuterGain = coneOuterGain;\n this._isDirectional = true;\n if (this.isPlaying && this.loop) {\n this.stop();\n this.play();\n }\n };\n Sound.prototype.setPosition = function (newPosition) {\n this._position = newPosition;\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {\n this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);\n }\n };\n Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {\n this._localDirection = newLocalDirection;\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {\n this._updateDirection();\n }\n };\n Sound.prototype._updateDirection = function () {\n if (!this._connectedMesh || !this._soundPanner) {\n return;\n }\n var mat = this._connectedMesh.getWorldMatrix();\n var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);\n direction.normalize();\n this._soundPanner.setOrientation(direction.x, direction.y, direction.z);\n };\n Sound.prototype.updateDistanceFromListener = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {\n var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);\n this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);\n }\n };\n Sound.prototype.setAttenuationFunction = function (callback) {\n this._customAttenuationFunction = callback;\n };\n /**\n * Play the sound\n * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.\n * @param offset (optional) Start the sound setting it at a specific time\n */\n Sound.prototype.play = function (time, offset) {\n var _this = this;\n if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {\n try {\n if (this._startOffset < 0) {\n time = -this._startOffset;\n this._startOffset = 0;\n }\n var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;\n if (!this._soundSource || !this._streamingSource) {\n if (this.spatialSound && this._soundPanner) {\n this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);\n if (this._isDirectional) {\n this._soundPanner.coneInnerAngle = this._coneInnerAngle;\n this._soundPanner.coneOuterAngle = this._coneOuterAngle;\n this._soundPanner.coneOuterGain = this._coneOuterGain;\n if (this._connectedMesh) {\n this._updateDirection();\n }\n else {\n this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);\n }\n }\n }\n }\n if (this._streaming) {\n if (!this._streamingSource) {\n this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);\n this._htmlAudioElement.onended = function () { _this._onended(); };\n this._htmlAudioElement.playbackRate = this._playbackRate;\n }\n this._streamingSource.disconnect();\n this._streamingSource.connect(this._inputAudioNode);\n if (this._htmlAudioElement) {\n this._htmlAudioElement.play();\n }\n }\n else {\n this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();\n this._soundSource.buffer = this._audioBuffer;\n this._soundSource.connect(this._inputAudioNode);\n this._soundSource.loop = this.loop;\n this._soundSource.playbackRate.value = this._playbackRate;\n this._soundSource.onended = function () { _this._onended(); };\n if (this._soundSource.buffer) {\n this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);\n }\n }\n this._startTime = startTime;\n this.isPlaying = true;\n this.isPaused = false;\n }\n catch (ex) {\n BABYLON.Tools.Error(\"Error while trying to play audio: \" + this.name + \", \" + ex.message);\n }\n }\n };\n Sound.prototype._onended = function () {\n this.isPlaying = false;\n if (this.onended) {\n this.onended();\n }\n };\n /**\n * Stop the sound\n * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.\n */\n Sound.prototype.stop = function (time) {\n if (this.isPlaying) {\n if (this._streaming) {\n if (this._htmlAudioElement) {\n this._htmlAudioElement.pause();\n // Test needed for Firefox or it will generate an Invalid State Error\n if (this._htmlAudioElement.currentTime > 0) {\n this._htmlAudioElement.currentTime = 0;\n }\n }\n else {\n this._streamingSource.disconnect();\n }\n }\n else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {\n var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;\n this._soundSource.stop(stopTime);\n this._soundSource.onended = function () { };\n if (!this.isPaused) {\n this._startOffset = 0;\n }\n }\n this.isPlaying = false;\n }\n };\n Sound.prototype.pause = function () {\n if (this.isPlaying) {\n this.isPaused = true;\n if (this._streaming) {\n if (this._htmlAudioElement) {\n this._htmlAudioElement.pause();\n }\n else {\n this._streamingSource.disconnect();\n }\n }\n else if (BABYLON.Engine.audioEngine.audioContext) {\n this.stop(0);\n this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;\n }\n }\n };\n Sound.prototype.setVolume = function (newVolume, time) {\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {\n if (time && BABYLON.Engine.audioEngine.audioContext) {\n this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);\n this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);\n this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);\n }\n else {\n this._soundGain.gain.value = newVolume;\n }\n }\n this._volume = newVolume;\n };\n Sound.prototype.setPlaybackRate = function (newPlaybackRate) {\n this._playbackRate = newPlaybackRate;\n if (this.isPlaying) {\n if (this._streaming && this._htmlAudioElement) {\n this._htmlAudioElement.playbackRate = this._playbackRate;\n }\n else if (this._soundSource) {\n this._soundSource.playbackRate.value = this._playbackRate;\n }\n }\n };\n Sound.prototype.getVolume = function () {\n return this._volume;\n };\n Sound.prototype.attachToMesh = function (meshToConnectTo) {\n var _this = this;\n if (this._connectedMesh && this._registerFunc) {\n this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);\n this._registerFunc = null;\n }\n this._connectedMesh = meshToConnectTo;\n if (!this.spatialSound) {\n this.spatialSound = true;\n this._createSpatialParameters();\n if (this.isPlaying && this.loop) {\n this.stop();\n this.play();\n }\n }\n this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);\n this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };\n meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);\n };\n Sound.prototype.detachFromMesh = function () {\n if (this._connectedMesh && this._registerFunc) {\n this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);\n this._registerFunc = null;\n this._connectedMesh = null;\n }\n };\n Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {\n if (!node.getBoundingInfo) {\n return;\n }\n var mesh = node;\n var boundingInfo = mesh.getBoundingInfo();\n this.setPosition(boundingInfo.boundingSphere.centerWorld);\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {\n this._updateDirection();\n }\n };\n Sound.prototype.clone = function () {\n var _this = this;\n if (!this._streaming) {\n var setBufferAndRun = function () {\n if (_this._isReadyToPlay) {\n clonedSound._audioBuffer = _this.getAudioBuffer();\n clonedSound._isReadyToPlay = true;\n if (clonedSound.autoplay) {\n clonedSound.play();\n }\n }\n else {\n window.setTimeout(setBufferAndRun, 300);\n }\n };\n var currentOptions = {\n autoplay: this.autoplay, loop: this.loop,\n volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,\n useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,\n refDistance: this.refDistance, distanceModel: this.distanceModel\n };\n var clonedSound = new Sound(this.name + \"_cloned\", new ArrayBuffer(0), this._scene, null, currentOptions);\n if (this.useCustomAttenuation) {\n clonedSound.setAttenuationFunction(this._customAttenuationFunction);\n }\n clonedSound.setPosition(this._position);\n clonedSound.setPlaybackRate(this._playbackRate);\n setBufferAndRun();\n return clonedSound;\n }\n // Can't clone a streaming sound\n else {\n return null;\n }\n };\n Sound.prototype.getAudioBuffer = function () {\n return this._audioBuffer;\n };\n Sound.prototype.serialize = function () {\n var serializationObject = {\n name: this.name,\n url: this.name,\n autoplay: this.autoplay,\n loop: this.loop,\n volume: this._volume,\n spatialSound: this.spatialSound,\n maxDistance: this.maxDistance,\n rolloffFactor: this.rolloffFactor,\n refDistance: this.refDistance,\n distanceModel: this.distanceModel,\n playbackRate: this._playbackRate,\n panningModel: this._panningModel,\n soundTrackId: this.soundTrackId\n };\n if (this.spatialSound) {\n if (this._connectedMesh)\n serializationObject.connectedMeshId = this._connectedMesh.id;\n serializationObject.position = this._position.asArray();\n serializationObject.refDistance = this.refDistance;\n serializationObject.distanceModel = this.distanceModel;\n serializationObject.isDirectional = this._isDirectional;\n serializationObject.localDirectionToMesh = this._localDirection.asArray();\n serializationObject.coneInnerAngle = this._coneInnerAngle;\n serializationObject.coneOuterAngle = this._coneOuterAngle;\n serializationObject.coneOuterGain = this._coneOuterGain;\n }\n return serializationObject;\n };\n Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {\n var soundName = parsedSound.name;\n var soundUrl;\n if (parsedSound.url) {\n soundUrl = rootUrl + parsedSound.url;\n }\n else {\n soundUrl = rootUrl + soundName;\n }\n var options = {\n autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,\n spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,\n rolloffFactor: parsedSound.rolloffFactor,\n refDistance: parsedSound.refDistance,\n distanceModel: parsedSound.distanceModel,\n playbackRate: parsedSound.playbackRate\n };\n var newSound;\n if (!sourceSound) {\n newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);\n scene._addPendingData(newSound);\n }\n else {\n var setBufferAndRun = function () {\n if (sourceSound._isReadyToPlay) {\n newSound._audioBuffer = sourceSound.getAudioBuffer();\n newSound._isReadyToPlay = true;\n if (newSound.autoplay) {\n newSound.play();\n }\n }\n else {\n window.setTimeout(setBufferAndRun, 300);\n }\n };\n newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);\n setBufferAndRun();\n }\n if (parsedSound.position) {\n var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);\n newSound.setPosition(soundPosition);\n }\n if (parsedSound.isDirectional) {\n newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);\n if (parsedSound.localDirectionToMesh) {\n var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);\n newSound.setLocalDirectionToMesh(localDirectionToMesh);\n }\n }\n if (parsedSound.connectedMeshId) {\n var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);\n if (connectedMesh) {\n newSound.attachToMesh(connectedMesh);\n }\n }\n return newSound;\n };\n return Sound;\n }());\n BABYLON.Sound = Sound;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sound.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var SoundTrack = /** @class */ (function () {\n function SoundTrack(scene, options) {\n this.id = -1;\n this._isMainTrack = false;\n this._isInitialized = false;\n this._scene = scene;\n this.soundCollection = new Array();\n this._options = options;\n if (!this._isMainTrack) {\n this._scene.soundTracks.push(this);\n this.id = this._scene.soundTracks.length - 1;\n }\n }\n SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {\n this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();\n this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);\n if (this._options) {\n if (this._options.volume) {\n this._outputAudioNode.gain.value = this._options.volume;\n }\n if (this._options.mainTrack) {\n this._isMainTrack = this._options.mainTrack;\n }\n }\n this._isInitialized = true;\n }\n };\n SoundTrack.prototype.dispose = function () {\n if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {\n if (this._connectedAnalyser) {\n this._connectedAnalyser.stopDebugCanvas();\n }\n while (this.soundCollection.length) {\n this.soundCollection[0].dispose();\n }\n if (this._outputAudioNode) {\n this._outputAudioNode.disconnect();\n }\n this._outputAudioNode = null;\n }\n };\n SoundTrack.prototype.AddSound = function (sound) {\n if (!this._isInitialized) {\n this._initializeSoundTrackAudioGraph();\n }\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {\n sound.connectToSoundTrackAudioNode(this._outputAudioNode);\n }\n if (sound.soundTrackId) {\n if (sound.soundTrackId === -1) {\n this._scene.mainSoundTrack.RemoveSound(sound);\n }\n else {\n this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);\n }\n }\n this.soundCollection.push(sound);\n sound.soundTrackId = this.id;\n };\n SoundTrack.prototype.RemoveSound = function (sound) {\n var index = this.soundCollection.indexOf(sound);\n if (index !== -1) {\n this.soundCollection.splice(index, 1);\n }\n };\n SoundTrack.prototype.setVolume = function (newVolume) {\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {\n this._outputAudioNode.gain.value = newVolume;\n }\n };\n SoundTrack.prototype.switchPanningModelToHRTF = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio) {\n for (var i = 0; i < this.soundCollection.length; i++) {\n this.soundCollection[i].switchPanningModelToHRTF();\n }\n }\n };\n SoundTrack.prototype.switchPanningModelToEqualPower = function () {\n if (BABYLON.Engine.audioEngine.canUseWebAudio) {\n for (var i = 0; i < this.soundCollection.length; i++) {\n this.soundCollection[i].switchPanningModelToEqualPower();\n }\n }\n };\n SoundTrack.prototype.connectToAnalyser = function (analyser) {\n if (this._connectedAnalyser) {\n this._connectedAnalyser.stopDebugCanvas();\n }\n this._connectedAnalyser = analyser;\n if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {\n this._outputAudioNode.disconnect();\n this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);\n }\n };\n return SoundTrack;\n }());\n BABYLON.SoundTrack = SoundTrack;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.soundtrack.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to work with sound analyzer using fast fourier transform (FFT)\n * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music\n */\n var Analyser = /** @class */ (function () {\n /**\n * Creates a new analyser\n * @param scene defines hosting scene\n */\n function Analyser(scene) {\n /**\n * Gets or sets the smoothing\n * @ignorenaming\n */\n this.SMOOTHING = 0.75;\n /**\n * Gets or sets the FFT table size\n * @ignorenaming\n */\n this.FFT_SIZE = 512;\n /**\n * Gets or sets the bar graph amplitude\n * @ignorenaming\n */\n this.BARGRAPHAMPLITUDE = 256;\n /**\n * Gets or sets the position of the debug canvas\n * @ignorenaming\n */\n this.DEBUGCANVASPOS = { x: 20, y: 20 };\n /**\n * Gets or sets the debug canvas size\n * @ignorenaming\n */\n this.DEBUGCANVASSIZE = { width: 320, height: 200 };\n this._scene = scene;\n this._audioEngine = BABYLON.Engine.audioEngine;\n if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {\n this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();\n this._webAudioAnalyser.minDecibels = -140;\n this._webAudioAnalyser.maxDecibels = 0;\n this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);\n this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);\n this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);\n }\n }\n /**\n * Get the number of data values you will have to play with for the visualization\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount\n * @returns a number\n */\n Analyser.prototype.getFrequencyBinCount = function () {\n if (this._audioEngine.canUseWebAudio) {\n return this._webAudioAnalyser.frequencyBinCount;\n }\n else {\n return 0;\n }\n };\n /**\n * Gets the current frequency data as a byte array\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData\n * @returns a Uint8Array\n */\n Analyser.prototype.getByteFrequencyData = function () {\n if (this._audioEngine.canUseWebAudio) {\n this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;\n this._webAudioAnalyser.fftSize = this.FFT_SIZE;\n this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);\n }\n return this._byteFreqs;\n };\n /**\n * Gets the current waveform as a byte array\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData\n * @returns a Uint8Array\n */\n Analyser.prototype.getByteTimeDomainData = function () {\n if (this._audioEngine.canUseWebAudio) {\n this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;\n this._webAudioAnalyser.fftSize = this.FFT_SIZE;\n this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);\n }\n return this._byteTime;\n };\n /**\n * Gets the current frequency data as a float array\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData\n * @returns a Float32Array\n */\n Analyser.prototype.getFloatFrequencyData = function () {\n if (this._audioEngine.canUseWebAudio) {\n this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;\n this._webAudioAnalyser.fftSize = this.FFT_SIZE;\n this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);\n }\n return this._floatFreqs;\n };\n /**\n * Renders the debug canvas\n */\n Analyser.prototype.drawDebugCanvas = function () {\n var _this = this;\n if (this._audioEngine.canUseWebAudio) {\n if (!this._debugCanvas) {\n this._debugCanvas = document.createElement(\"canvas\");\n this._debugCanvas.width = this.DEBUGCANVASSIZE.width;\n this._debugCanvas.height = this.DEBUGCANVASSIZE.height;\n this._debugCanvas.style.position = \"absolute\";\n this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + \"px\";\n this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + \"px\";\n this._debugCanvasContext = this._debugCanvas.getContext(\"2d\");\n document.body.appendChild(this._debugCanvas);\n this._registerFunc = function () {\n _this.drawDebugCanvas();\n };\n this._scene.registerBeforeRender(this._registerFunc);\n }\n if (this._registerFunc && this._debugCanvasContext) {\n var workingArray = this.getByteFrequencyData();\n this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';\n this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);\n // Draw the frequency domain chart.\n for (var i = 0; i < this.getFrequencyBinCount(); i++) {\n var value = workingArray[i];\n var percent = value / this.BARGRAPHAMPLITUDE;\n var height = this.DEBUGCANVASSIZE.height * percent;\n var offset = this.DEBUGCANVASSIZE.height - height - 1;\n var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();\n var hue = i / this.getFrequencyBinCount() * 360;\n this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';\n this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);\n }\n }\n }\n };\n /**\n * Stops rendering the debug canvas and removes it\n */\n Analyser.prototype.stopDebugCanvas = function () {\n if (this._debugCanvas) {\n if (this._registerFunc) {\n this._scene.unregisterBeforeRender(this._registerFunc);\n this._registerFunc = null;\n }\n document.body.removeChild(this._debugCanvas);\n this._debugCanvas = null;\n this._debugCanvasContext = null;\n }\n };\n /**\n * Connects two audio nodes\n * @param inputAudioNode defines first node to connect\n * @param outputAudioNode defines second node to connect\n */\n Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {\n if (this._audioEngine.canUseWebAudio) {\n inputAudioNode.connect(this._webAudioAnalyser);\n this._webAudioAnalyser.connect(outputAudioNode);\n }\n };\n /**\n * Releases all associated resources\n */\n Analyser.prototype.dispose = function () {\n if (this._audioEngine.canUseWebAudio) {\n this._webAudioAnalyser.disconnect();\n }\n };\n return Analyser;\n }());\n BABYLON.Analyser = Analyser;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.analyser.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var CubeTexture = /** @class */ (function (_super) {\n __extends(CubeTexture, _super);\n /**\n * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well\n * as prefiltered data.\n * @param rootUrl defines the url of the texture or the root name of the six images\n * @param scene defines the scene the texture is attached to\n * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...\n * @param noMipmap defines if mipmaps should be created or not\n * @param files defines the six files to load for the different faces\n * @param onLoad defines a callback triggered at the end of the file load if no errors occured\n * @param onError defines a callback triggered in case of error during load\n * @param format defines the internal format to use for the texture once loaded\n * @param prefiltered defines whether or not the texture is created from prefiltered data\n * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name\n * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary\n * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness\n * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness\n * @return the cube texture\n */\n function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {\n if (extensions === void 0) { extensions = null; }\n if (noMipmap === void 0) { noMipmap = false; }\n if (files === void 0) { files = null; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }\n if (prefiltered === void 0) { prefiltered = false; }\n if (forcedExtension === void 0) { forcedExtension = null; }\n if (createPolynomials === void 0) { createPolynomials = false; }\n if (lodScale === void 0) { lodScale = 0.8; }\n if (lodOffset === void 0) { lodOffset = 0; }\n var _this = _super.call(this, scene) || this;\n /**\n * Gets or sets the center of the bounding box associated with the cube texture\n * It must define where the camera used to render the texture was set\n */\n _this.boundingBoxPosition = BABYLON.Vector3.Zero();\n _this._rotationY = 0;\n /** @hidden */\n _this._prefiltered = false;\n _this.name = rootUrl;\n _this.url = rootUrl;\n _this._noMipmap = noMipmap;\n _this.hasAlpha = false;\n _this._format = format;\n _this.isCube = true;\n _this._textureMatrix = BABYLON.Matrix.Identity();\n _this._createPolynomials = createPolynomials;\n _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;\n if (!rootUrl && !files) {\n return _this;\n }\n var lastDot = rootUrl.lastIndexOf(\".\");\n var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : \"\");\n var isDDS = (extension === \".dds\");\n var isEnv = (extension === \".env\");\n if (isEnv) {\n _this.gammaSpace = false;\n _this._prefiltered = false;\n }\n else {\n _this._prefiltered = prefiltered;\n if (prefiltered) {\n _this.gammaSpace = false;\n }\n }\n _this._texture = _this._getFromCache(rootUrl, noMipmap);\n if (!files) {\n if (!isEnv && !isDDS && !extensions) {\n extensions = [\"_px.jpg\", \"_py.jpg\", \"_pz.jpg\", \"_nx.jpg\", \"_ny.jpg\", \"_nz.jpg\"];\n }\n files = [];\n if (extensions) {\n for (var index = 0; index < extensions.length; index++) {\n files.push(rootUrl + extensions[index]);\n }\n }\n }\n _this._files = files;\n if (!_this._texture) {\n if (!scene.useDelayedTextureLoading) {\n if (prefiltered) {\n _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);\n }\n else {\n _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);\n }\n }\n else {\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n }\n }\n else if (onLoad) {\n if (_this._texture.isReady) {\n BABYLON.Tools.SetImmediate(function () { return onLoad(); });\n }\n else {\n _this._texture.onLoadedObservable.add(onLoad);\n }\n }\n return _this;\n }\n Object.defineProperty(CubeTexture.prototype, \"boundingBoxSize\", {\n get: function () {\n return this._boundingBoxSize;\n },\n /**\n * Gets or sets the size of the bounding box associated with the cube texture\n * When defined, the cubemap will switch to local mode\n * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity\n * @example https://www.babylonjs-playground.com/#RNASML\n */\n set: function (value) {\n if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {\n return;\n }\n this._boundingBoxSize = value;\n var scene = this.getScene();\n if (scene) {\n scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CubeTexture.prototype, \"rotationY\", {\n /**\n * Gets texture matrix rotation angle around Y axis radians.\n */\n get: function () {\n return this._rotationY;\n },\n /**\n * Sets texture matrix rotation angle around Y axis in radians.\n */\n set: function (value) {\n this._rotationY = value;\n this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));\n },\n enumerable: true,\n configurable: true\n });\n CubeTexture.CreateFromImages = function (files, scene, noMipmap) {\n var rootUrlKey = \"\";\n files.forEach(function (url) { return rootUrlKey += url; });\n return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);\n };\n /**\n * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.\n * @param url defines the url of the prefiltered texture\n * @param scene defines the scene the texture is attached to\n * @param forcedExtension defines the extension of the file if different from the url\n * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary\n * @return the prefiltered texture\n */\n CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {\n if (forcedExtension === void 0) { forcedExtension = null; }\n if (createPolynomials === void 0) { createPolynomials = true; }\n return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);\n };\n // Methods\n CubeTexture.prototype.delayLoad = function () {\n if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {\n return;\n }\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;\n this._texture = this._getFromCache(this.url, this._noMipmap);\n if (!this._texture) {\n if (this._prefiltered) {\n this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);\n }\n else {\n this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);\n }\n }\n };\n CubeTexture.prototype.getReflectionTextureMatrix = function () {\n return this._textureMatrix;\n };\n CubeTexture.prototype.setReflectionTextureMatrix = function (value) {\n this._textureMatrix = value;\n };\n CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {\n var texture = BABYLON.SerializationHelper.Parse(function () {\n var prefiltered = false;\n if (parsedTexture.prefiltered) {\n prefiltered = parsedTexture.prefiltered;\n }\n return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);\n }, parsedTexture, scene);\n // Local Cubemaps\n if (parsedTexture.boundingBoxPosition) {\n texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);\n }\n if (parsedTexture.boundingBoxSize) {\n texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);\n }\n // Animations\n if (parsedTexture.animations) {\n for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {\n var parsedAnimation = parsedTexture.animations[animationIndex];\n texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n }\n return texture;\n };\n CubeTexture.prototype.clone = function () {\n var _this = this;\n return BABYLON.SerializationHelper.Clone(function () {\n var scene = _this.getScene();\n if (!scene) {\n return _this;\n }\n return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);\n }, this);\n };\n __decorate([\n BABYLON.serialize(\"rotationY\")\n ], CubeTexture.prototype, \"_rotationY\", void 0);\n return CubeTexture;\n }(BABYLON.BaseTexture));\n BABYLON.CubeTexture = CubeTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.cubeTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Raw cube texture where the raw buffers are passed in\n */\n var RawCubeTexture = /** @class */ (function (_super) {\n __extends(RawCubeTexture, _super);\n /**\n * Creates a cube texture where the raw buffers are passed in.\n * @param scene defines the scene the texture is attached to\n * @param data defines the array of data to use to create each face\n * @param size defines the size of the textures\n * @param format defines the format of the data\n * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)\n * @param generateMipMaps defines if the engine should generate the mip levels\n * @param invertY defines if data must be stored with Y axis inverted\n * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)\n * @param compression defines the compression used (null by default)\n */\n function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {\n if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (generateMipMaps === void 0) { generateMipMaps = false; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (compression === void 0) { compression = null; }\n var _this = _super.call(this, \"\", scene) || this;\n _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);\n return _this;\n }\n /**\n * Updates the raw cube texture.\n * @param data defines the data to store\n * @param format defines the data format\n * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)\n * @param invertY defines if data must be stored with Y axis inverted\n * @param compression defines the compression used (null by default)\n * @param level defines which level of the texture to update\n */\n RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {\n if (compression === void 0) { compression = null; }\n if (level === void 0) { level = 0; }\n this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);\n };\n /**\n * Updates a raw cube texture with RGBD encoded data.\n * @param data defines the array of data [mipmap][face] to use to create each face\n * @param sphericalPolynomial defines the spherical polynomial for irradiance\n * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness\n * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness\n * @returns a promsie that resolves when the operation is complete\n */\n RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {\n if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }\n if (lodScale === void 0) { lodScale = 0.8; }\n if (lodOffset === void 0) { lodOffset = 0; }\n return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);\n };\n /**\n * Clones the raw cube texture.\n * @return a new cube texture\n */\n RawCubeTexture.prototype.clone = function () {\n var _this = this;\n return BABYLON.SerializationHelper.Clone(function () {\n var scene = _this.getScene();\n var internalTexture = _this._texture;\n var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);\n if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {\n texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);\n }\n return texture;\n }, this);\n };\n /** @hidden */\n RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {\n internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;\n internalTexture._bufferViewArrayArray = data;\n internalTexture._lodGenerationScale = lodScale;\n internalTexture._lodGenerationOffset = lodOffset;\n internalTexture._sphericalPolynomial = sphericalPolynomial;\n return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {\n internalTexture.isReady = true;\n });\n };\n return RawCubeTexture;\n }(BABYLON.CubeTexture));\n BABYLON.RawCubeTexture = RawCubeTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.rawCubeTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var RenderTargetTexture = /** @class */ (function (_super) {\n __extends(RenderTargetTexture, _super);\n /**\n * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse\n * or used a shadow, depth texture...\n * @param name The friendly name of the texture\n * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)\n * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.\n * @param generateMipMaps True if mip maps need to be generated after render.\n * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT\n * @param type The type of the buffer in the RTT (int, half float, float...)\n * @param isCube True if a cube texture needs to be created\n * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)\n * @param generateDepthBuffer True to generate a depth buffer\n * @param generateStencilBuffer True to generate a stencil buffer\n * @param isMulti True if multiple textures need to be created (Draw Buffers)\n * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)\n */\n function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {\n if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (isCube === void 0) { isCube = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }\n if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }\n if (isMulti === void 0) { isMulti = false; }\n if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }\n var _this = _super.call(this, null, scene, !generateMipMaps) || this;\n _this.isCube = isCube;\n _this.renderParticles = true;\n _this.renderSprites = false;\n _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;\n _this.ignoreCameraViewport = false;\n // Events\n /**\n * An event triggered when the texture is unbind.\n */\n _this.onBeforeBindObservable = new BABYLON.Observable();\n /**\n * An event triggered when the texture is unbind.\n */\n _this.onAfterUnbindObservable = new BABYLON.Observable();\n /**\n * An event triggered before rendering the texture\n */\n _this.onBeforeRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered after rendering the texture\n */\n _this.onAfterRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered after the texture clear\n */\n _this.onClearObservable = new BABYLON.Observable();\n _this._currentRefreshId = -1;\n _this._refreshRate = 1;\n _this._samples = 1;\n /**\n * Gets or sets the center of the bounding box associated with the texture (when in cube mode)\n * It must define where the camera used to render the texture is set\n */\n _this.boundingBoxPosition = BABYLON.Vector3.Zero();\n scene = _this.getScene();\n if (!scene) {\n return _this;\n }\n _this.renderList = new Array();\n _this._engine = scene.getEngine();\n _this.name = name;\n _this.isRenderTarget = true;\n _this._initialSizeParameter = size;\n _this._processSizeParameter(size);\n _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {\n });\n _this._generateMipMaps = generateMipMaps ? true : false;\n _this._doNotChangeAspectRatio = doNotChangeAspectRatio;\n // Rendering groups\n _this._renderingManager = new BABYLON.RenderingManager(scene);\n _this._renderingManager._useSceneAutoClearSetup = true;\n if (isMulti) {\n return _this;\n }\n _this._renderTargetOptions = {\n generateMipMaps: generateMipMaps,\n type: type,\n format: format,\n samplingMode: samplingMode,\n generateDepthBuffer: generateDepthBuffer,\n generateStencilBuffer: generateStencilBuffer\n };\n if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {\n _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n }\n if (isCube) {\n _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);\n _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;\n _this._textureMatrix = BABYLON.Matrix.Identity();\n }\n else {\n _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);\n }\n return _this;\n }\n Object.defineProperty(RenderTargetTexture, \"REFRESHRATE_RENDER_ONCE\", {\n get: function () {\n return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture, \"REFRESHRATE_RENDER_ONEVERYFRAME\", {\n get: function () {\n return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture, \"REFRESHRATE_RENDER_ONEVERYTWOFRAMES\", {\n get: function () {\n return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture.prototype, \"renderList\", {\n /**\n * Use this list to define the list of mesh you want to render.\n */\n get: function () {\n return this._renderList;\n },\n set: function (value) {\n this._renderList = value;\n if (this._renderList) {\n this._hookArray(this._renderList);\n }\n },\n enumerable: true,\n configurable: true\n });\n RenderTargetTexture.prototype._hookArray = function (array) {\n var _this = this;\n var oldPush = array.push;\n array.push = function () {\n var items = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n items[_i] = arguments[_i];\n }\n var result = oldPush.apply(array, items);\n _this.getScene().meshes.forEach(function (mesh) {\n mesh._markSubMeshesAsLightDirty();\n });\n return result;\n };\n var oldSplice = array.splice;\n array.splice = function (index, deleteCount) {\n var deleted = oldSplice.apply(array, [index, deleteCount]);\n _this.getScene().meshes.forEach(function (mesh) {\n mesh._markSubMeshesAsLightDirty();\n });\n return deleted;\n };\n };\n Object.defineProperty(RenderTargetTexture.prototype, \"onAfterUnbind\", {\n set: function (callback) {\n if (this._onAfterUnbindObserver) {\n this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);\n }\n this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture.prototype, \"onBeforeRender\", {\n set: function (callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture.prototype, \"onAfterRender\", {\n set: function (callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture.prototype, \"onClear\", {\n set: function (callback) {\n if (this._onClearObserver) {\n this.onClearObservable.remove(this._onClearObserver);\n }\n this._onClearObserver = this.onClearObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RenderTargetTexture.prototype, \"renderTargetOptions\", {\n get: function () {\n return this._renderTargetOptions;\n },\n enumerable: true,\n configurable: true\n });\n RenderTargetTexture.prototype._onRatioRescale = function () {\n if (this._sizeRatio) {\n this.resize(this._initialSizeParameter);\n }\n };\n Object.defineProperty(RenderTargetTexture.prototype, \"boundingBoxSize\", {\n get: function () {\n return this._boundingBoxSize;\n },\n /**\n * Gets or sets the size of the bounding box associated with the texture (when in cube mode)\n * When defined, the cubemap will switch to local mode\n * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity\n * @example https://www.babylonjs-playground.com/#RNASML\n */\n set: function (value) {\n if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {\n return;\n }\n this._boundingBoxSize = value;\n var scene = this.getScene();\n if (scene) {\n scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Creates a depth stencil texture.\n * This is only available in WebGL 2 or with the depth texture extension available.\n * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode\n * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture\n * @param generateStencil Specifies whether or not a stencil should be allocated in the texture\n */\n RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {\n if (comparisonFunction === void 0) { comparisonFunction = 0; }\n if (bilinearFiltering === void 0) { bilinearFiltering = true; }\n if (generateStencil === void 0) { generateStencil = false; }\n if (!this.getScene()) {\n return;\n }\n var engine = this.getScene().getEngine();\n this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {\n bilinearFiltering: bilinearFiltering,\n comparisonFunction: comparisonFunction,\n generateStencil: generateStencil,\n isCube: this.isCube\n });\n engine.setFrameBufferDepthStencilTexture(this);\n };\n RenderTargetTexture.prototype._processSizeParameter = function (size) {\n if (size.ratio) {\n this._sizeRatio = size.ratio;\n this._size = {\n width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),\n height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)\n };\n }\n else {\n this._size = size;\n }\n };\n Object.defineProperty(RenderTargetTexture.prototype, \"samples\", {\n get: function () {\n return this._samples;\n },\n set: function (value) {\n if (this._samples === value) {\n return;\n }\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);\n },\n enumerable: true,\n configurable: true\n });\n RenderTargetTexture.prototype.resetRefreshCounter = function () {\n this._currentRefreshId = -1;\n };\n Object.defineProperty(RenderTargetTexture.prototype, \"refreshRate\", {\n get: function () {\n return this._refreshRate;\n },\n // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...\n set: function (value) {\n this._refreshRate = value;\n this.resetRefreshCounter();\n },\n enumerable: true,\n configurable: true\n });\n RenderTargetTexture.prototype.addPostProcess = function (postProcess) {\n if (!this._postProcessManager) {\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this._postProcessManager = new BABYLON.PostProcessManager(scene);\n this._postProcesses = new Array();\n }\n this._postProcesses.push(postProcess);\n this._postProcesses[0].autoClear = false;\n };\n RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {\n if (!this._postProcesses) {\n return;\n }\n if (dispose) {\n for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {\n var postProcess = _a[_i];\n postProcess.dispose();\n }\n }\n this._postProcesses = [];\n };\n RenderTargetTexture.prototype.removePostProcess = function (postProcess) {\n if (!this._postProcesses) {\n return;\n }\n var index = this._postProcesses.indexOf(postProcess);\n if (index === -1) {\n return;\n }\n this._postProcesses.splice(index, 1);\n if (this._postProcesses.length > 0) {\n this._postProcesses[0].autoClear = false;\n }\n };\n RenderTargetTexture.prototype._shouldRender = function () {\n if (this._currentRefreshId === -1) { // At least render once\n this._currentRefreshId = 1;\n return true;\n }\n if (this.refreshRate === this._currentRefreshId) {\n this._currentRefreshId = 1;\n return true;\n }\n this._currentRefreshId++;\n return false;\n };\n RenderTargetTexture.prototype.getRenderSize = function () {\n if (this._size.width) {\n return this._size.width;\n }\n return this._size;\n };\n RenderTargetTexture.prototype.getRenderWidth = function () {\n if (this._size.width) {\n return this._size.width;\n }\n return this._size;\n };\n RenderTargetTexture.prototype.getRenderHeight = function () {\n if (this._size.width) {\n return this._size.height;\n }\n return this._size;\n };\n Object.defineProperty(RenderTargetTexture.prototype, \"canRescale\", {\n get: function () {\n return true;\n },\n enumerable: true,\n configurable: true\n });\n RenderTargetTexture.prototype.scale = function (ratio) {\n var newSize = this.getRenderSize() * ratio;\n this.resize(newSize);\n };\n RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {\n if (this.isCube) {\n return this._textureMatrix;\n }\n return _super.prototype.getReflectionTextureMatrix.call(this);\n };\n RenderTargetTexture.prototype.resize = function (size) {\n this.releaseInternalTexture();\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this._processSizeParameter(size);\n if (this.isCube) {\n this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);\n }\n else {\n this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);\n }\n };\n RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {\n if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }\n if (dumpForDebug === void 0) { dumpForDebug = false; }\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var engine = scene.getEngine();\n if (this.useCameraPostProcesses !== undefined) {\n useCameraPostProcess = this.useCameraPostProcesses;\n }\n if (this._waitingRenderList) {\n this.renderList = [];\n for (var index = 0; index < this._waitingRenderList.length; index++) {\n var id = this._waitingRenderList[index];\n var mesh_1 = scene.getMeshByID(id);\n if (mesh_1) {\n this.renderList.push(mesh_1);\n }\n }\n delete this._waitingRenderList;\n }\n // Is predicate defined?\n if (this.renderListPredicate) {\n if (this.renderList) {\n this.renderList.splice(0); // Clear previous renderList\n }\n else {\n this.renderList = [];\n }\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var sceneMeshes = scene.meshes;\n for (var index = 0; index < sceneMeshes.length; index++) {\n var mesh = sceneMeshes[index];\n if (this.renderListPredicate(mesh)) {\n this.renderList.push(mesh);\n }\n }\n }\n this.onBeforeBindObservable.notifyObservers(this);\n // Set custom projection.\n // Needs to be before binding to prevent changing the aspect ratio.\n var camera;\n if (this.activeCamera) {\n camera = this.activeCamera;\n engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());\n if (this.activeCamera !== scene.activeCamera) {\n scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));\n }\n }\n else {\n camera = scene.activeCamera;\n if (camera) {\n engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());\n }\n }\n // Prepare renderingManager\n this._renderingManager.reset();\n var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;\n var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;\n var sceneRenderId = scene.getRenderId();\n for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {\n var mesh = currentRenderList[meshIndex];\n if (mesh) {\n if (!mesh.isReady(this.refreshRate === 0)) {\n this.resetRefreshCounter();\n continue;\n }\n mesh._preActivateForIntermediateRendering(sceneRenderId);\n var isMasked = void 0;\n if (!this.renderList && camera) {\n isMasked = ((mesh.layerMask & camera.layerMask) === 0);\n }\n else {\n isMasked = false;\n }\n if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {\n mesh._activate(sceneRenderId);\n for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {\n var subMesh = mesh.subMeshes[subIndex];\n scene._activeIndices.addCount(subMesh.indexCount, false);\n this._renderingManager.dispatch(subMesh, mesh);\n }\n }\n }\n }\n for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {\n var particleSystem = scene.particleSystems[particleIndex];\n var emitter = particleSystem.emitter;\n if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {\n continue;\n }\n if (currentRenderList.indexOf(emitter) >= 0) {\n this._renderingManager.dispatchParticles(particleSystem);\n }\n }\n if (this.isCube) {\n for (var face = 0; face < 6; face++) {\n this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n }\n }\n else {\n this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);\n }\n this.onAfterUnbindObservable.notifyObservers(this);\n if (scene.activeCamera) {\n if (this.activeCamera && this.activeCamera !== scene.activeCamera) {\n scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));\n }\n engine.setViewport(scene.activeCamera.viewport);\n }\n scene.resetCachedMaterial();\n };\n RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {\n var minimum = 128;\n var x = renderDimension * scale;\n var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));\n // Ensure we don't exceed the render dimension (while staying POT)\n return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);\n };\n RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {\n var _this = this;\n if (!this._texture) {\n return;\n }\n engine.unBindFramebuffer(this._texture, this.isCube, function () {\n _this.onAfterRenderObservable.notifyObservers(faceIndex);\n });\n };\n RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var engine = scene.getEngine();\n if (!this._texture) {\n return;\n }\n // Bind\n if (this._postProcessManager) {\n this._postProcessManager._prepareFrame(this._texture, this._postProcesses);\n }\n else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {\n if (this._texture) {\n engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);\n }\n }\n this.onBeforeRenderObservable.notifyObservers(faceIndex);\n // Clear\n if (this.onClearObservable.hasObservers()) {\n this.onClearObservable.notifyObservers(engine);\n }\n else {\n engine.clear(this.clearColor || scene.clearColor, true, true, true);\n }\n if (!this._doNotChangeAspectRatio) {\n scene.updateTransformMatrix(true);\n }\n // Render\n this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);\n if (this._postProcessManager) {\n this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);\n }\n else if (useCameraPostProcess) {\n scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);\n }\n if (!this._doNotChangeAspectRatio) {\n scene.updateTransformMatrix(true);\n }\n // Dump ?\n if (dumpForDebug) {\n BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);\n }\n // Unbind\n if (!this.isCube || faceIndex === 5) {\n if (this.isCube) {\n if (faceIndex === 5) {\n engine.generateMipMapsForCubemap(this._texture);\n }\n }\n this.unbindFrameBuffer(engine, faceIndex);\n }\n else {\n this.onAfterRenderObservable.notifyObservers(faceIndex);\n }\n };\n /**\n * Overrides the default sort function applied in the renderging group to prepare the meshes.\n * This allowed control for front to back rendering or reversly depending of the special needs.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param opaqueSortCompareFn The opaque queue comparison function use to sort.\n * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.\n * @param transparentSortCompareFn The transparent queue comparison function use to sort.\n */\n RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {\n if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }\n if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }\n if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }\n this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);\n };\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n */\n RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {\n this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);\n this._renderingManager._useSceneAutoClearSetup = false;\n };\n RenderTargetTexture.prototype.clone = function () {\n var textureSize = this.getSize();\n var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // RenderTarget Texture\n newTexture.coordinatesMode = this.coordinatesMode;\n if (this.renderList) {\n newTexture.renderList = this.renderList.slice(0);\n }\n return newTexture;\n };\n RenderTargetTexture.prototype.serialize = function () {\n if (!this.name) {\n return null;\n }\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.renderTargetSize = this.getRenderSize();\n serializationObject.renderList = [];\n if (this.renderList) {\n for (var index = 0; index < this.renderList.length; index++) {\n serializationObject.renderList.push(this.renderList[index].id);\n }\n }\n return serializationObject;\n };\n // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore\n RenderTargetTexture.prototype.disposeFramebufferObjects = function () {\n var objBuffer = this.getInternalTexture();\n var scene = this.getScene();\n if (objBuffer && scene) {\n scene.getEngine()._releaseFramebufferObjects(objBuffer);\n }\n };\n RenderTargetTexture.prototype.dispose = function () {\n if (this._postProcessManager) {\n this._postProcessManager.dispose();\n this._postProcessManager = null;\n }\n this.clearPostProcesses(true);\n if (this._resizeObserver) {\n this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);\n this._resizeObserver = null;\n }\n this.renderList = null;\n // Remove from custom render targets\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var index = scene.customRenderTargets.indexOf(this);\n if (index >= 0) {\n scene.customRenderTargets.splice(index, 1);\n }\n for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {\n var camera = _a[_i];\n index = camera.customRenderTargets.indexOf(this);\n if (index >= 0) {\n camera.customRenderTargets.splice(index, 1);\n }\n }\n _super.prototype.dispose.call(this);\n };\n RenderTargetTexture.prototype._rebuild = function () {\n if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {\n this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;\n }\n if (this._postProcessManager) {\n this._postProcessManager._rebuild();\n }\n };\n /**\n * Clear the info related to rendering groups preventing retention point in material dispose.\n */\n RenderTargetTexture.prototype.freeRenderingGroups = function () {\n if (this._renderingManager) {\n this._renderingManager.freeRenderingGroups();\n }\n };\n RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;\n RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;\n RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;\n return RenderTargetTexture;\n }(BABYLON.Texture));\n BABYLON.RenderTargetTexture = RenderTargetTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.renderTargetTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n ;\n var MultiRenderTarget = /** @class */ (function (_super) {\n __extends(MultiRenderTarget, _super);\n function MultiRenderTarget(name, size, count, scene, options) {\n var _this = this;\n var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;\n var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;\n var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;\n _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;\n _this._engine = scene.getEngine();\n if (!_this.isSupported) {\n _this.dispose();\n return;\n }\n var types = [];\n var samplingModes = [];\n for (var i = 0; i < count; i++) {\n if (options && options.types && options.types[i] !== undefined) {\n types.push(options.types[i]);\n }\n else {\n types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n }\n if (options && options.samplingModes && options.samplingModes[i] !== undefined) {\n samplingModes.push(options.samplingModes[i]);\n }\n else {\n samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n }\n }\n var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;\n _this._size = size;\n _this._multiRenderTargetOptions = {\n samplingModes: samplingModes,\n generateMipMaps: generateMipMaps,\n generateDepthBuffer: generateDepthBuffer,\n generateStencilBuffer: generateStencilBuffer,\n generateDepthTexture: generateDepthTexture,\n types: types,\n textureCount: count\n };\n _this._createInternalTextures();\n _this._createTextures();\n return _this;\n }\n Object.defineProperty(MultiRenderTarget.prototype, \"isSupported\", {\n get: function () {\n return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MultiRenderTarget.prototype, \"textures\", {\n get: function () {\n return this._textures;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MultiRenderTarget.prototype, \"depthTexture\", {\n get: function () {\n return this._textures[this._textures.length - 1];\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MultiRenderTarget.prototype, \"wrapU\", {\n set: function (wrap) {\n if (this._textures) {\n for (var i = 0; i < this._textures.length; i++) {\n this._textures[i].wrapU = wrap;\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MultiRenderTarget.prototype, \"wrapV\", {\n set: function (wrap) {\n if (this._textures) {\n for (var i = 0; i < this._textures.length; i++) {\n this._textures[i].wrapV = wrap;\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n MultiRenderTarget.prototype._rebuild = function () {\n this.releaseInternalTextures();\n this._createInternalTextures();\n for (var i = 0; i < this._internalTextures.length; i++) {\n var texture = this._textures[i];\n texture._texture = this._internalTextures[i];\n }\n // Keeps references to frame buffer and stencil/depth buffer\n this._texture = this._internalTextures[0];\n };\n MultiRenderTarget.prototype._createInternalTextures = function () {\n this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);\n };\n MultiRenderTarget.prototype._createTextures = function () {\n this._textures = [];\n for (var i = 0; i < this._internalTextures.length; i++) {\n var texture = new BABYLON.Texture(null, this.getScene());\n texture._texture = this._internalTextures[i];\n this._textures.push(texture);\n }\n // Keeps references to frame buffer and stencil/depth buffer\n this._texture = this._internalTextures[0];\n };\n Object.defineProperty(MultiRenderTarget.prototype, \"samples\", {\n get: function () {\n return this._samples;\n },\n set: function (value) {\n if (this._samples === value) {\n return;\n }\n this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);\n },\n enumerable: true,\n configurable: true\n });\n MultiRenderTarget.prototype.resize = function (size) {\n this.releaseInternalTextures();\n this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);\n this._createInternalTextures();\n };\n MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {\n var _this = this;\n engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {\n _this.onAfterRenderObservable.notifyObservers(faceIndex);\n });\n };\n MultiRenderTarget.prototype.dispose = function () {\n this.releaseInternalTextures();\n _super.prototype.dispose.call(this);\n };\n MultiRenderTarget.prototype.releaseInternalTextures = function () {\n if (!this._internalTextures) {\n return;\n }\n for (var i = this._internalTextures.length - 1; i >= 0; i--) {\n if (this._internalTextures[i] !== undefined) {\n this._internalTextures[i].dispose();\n this._internalTextures.splice(i, 1);\n }\n }\n };\n return MultiRenderTarget;\n }(BABYLON.RenderTargetTexture));\n BABYLON.MultiRenderTarget = MultiRenderTarget;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.multiRenderTarget.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var MirrorTexture = /** @class */ (function (_super) {\n __extends(MirrorTexture, _super);\n function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }\n if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }\n var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;\n _this.scene = scene;\n _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);\n _this._transformMatrix = BABYLON.Matrix.Zero();\n _this._mirrorMatrix = BABYLON.Matrix.Zero();\n _this._adaptiveBlurKernel = 0;\n _this._blurKernelX = 0;\n _this._blurKernelY = 0;\n _this._blurRatio = 1.0;\n _this.ignoreCameraViewport = true;\n _this._updateGammaSpace();\n _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {\n _this._updateGammaSpace;\n });\n _this.onBeforeRenderObservable.add(function () {\n BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);\n _this._savedViewMatrix = scene.getViewMatrix();\n _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);\n scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());\n scene.clipPlane = _this.mirrorPlane;\n scene.getEngine().cullBackFaces = false;\n scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);\n });\n _this.onAfterRenderObservable.add(function () {\n scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());\n scene.getEngine().cullBackFaces = true;\n scene._mirroredCameraPosition = null;\n delete scene.clipPlane;\n });\n return _this;\n }\n Object.defineProperty(MirrorTexture.prototype, \"blurRatio\", {\n get: function () {\n return this._blurRatio;\n },\n set: function (value) {\n if (this._blurRatio === value) {\n return;\n }\n this._blurRatio = value;\n this._preparePostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MirrorTexture.prototype, \"adaptiveBlurKernel\", {\n set: function (value) {\n this._adaptiveBlurKernel = value;\n this._autoComputeBlurKernel();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MirrorTexture.prototype, \"blurKernel\", {\n set: function (value) {\n this.blurKernelX = value;\n this.blurKernelY = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MirrorTexture.prototype, \"blurKernelX\", {\n get: function () {\n return this._blurKernelX;\n },\n set: function (value) {\n if (this._blurKernelX === value) {\n return;\n }\n this._blurKernelX = value;\n this._preparePostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MirrorTexture.prototype, \"blurKernelY\", {\n get: function () {\n return this._blurKernelY;\n },\n set: function (value) {\n if (this._blurKernelY === value) {\n return;\n }\n this._blurKernelY = value;\n this._preparePostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n MirrorTexture.prototype._autoComputeBlurKernel = function () {\n var engine = this.getScene().getEngine();\n var dw = this.getRenderWidth() / engine.getRenderWidth();\n var dh = this.getRenderHeight() / engine.getRenderHeight();\n this.blurKernelX = this._adaptiveBlurKernel * dw;\n this.blurKernelY = this._adaptiveBlurKernel * dh;\n };\n MirrorTexture.prototype._onRatioRescale = function () {\n if (this._sizeRatio) {\n this.resize(this._initialSizeParameter);\n if (!this._adaptiveBlurKernel) {\n this._preparePostProcesses();\n }\n }\n if (this._adaptiveBlurKernel) {\n this._autoComputeBlurKernel();\n }\n };\n MirrorTexture.prototype._updateGammaSpace = function () {\n this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;\n };\n MirrorTexture.prototype._preparePostProcesses = function () {\n this.clearPostProcesses(true);\n if (this._blurKernelX && this._blurKernelY) {\n var engine = this.getScene().getEngine();\n var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n this._blurX = new BABYLON.BlurPostProcess(\"horizontal blur\", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);\n this._blurX.autoClear = false;\n if (this._blurRatio === 1 && this.samples < 2 && this._texture) {\n this._blurX.inputTexture = this._texture;\n }\n else {\n this._blurX.alwaysForcePOT = true;\n }\n this._blurY = new BABYLON.BlurPostProcess(\"vertical blur\", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);\n this._blurY.autoClear = false;\n this._blurY.alwaysForcePOT = this._blurRatio !== 1;\n this.addPostProcess(this._blurX);\n this.addPostProcess(this._blurY);\n }\n else {\n if (this._blurY) {\n this.removePostProcess(this._blurY);\n this._blurY.dispose();\n this._blurY = null;\n }\n if (this._blurX) {\n this.removePostProcess(this._blurX);\n this._blurX.dispose();\n this._blurX = null;\n }\n }\n };\n MirrorTexture.prototype.clone = function () {\n var scene = this.getScene();\n if (!scene) {\n return this;\n }\n var textureSize = this.getSize();\n var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // Mirror Texture\n newTexture.mirrorPlane = this.mirrorPlane.clone();\n if (this.renderList) {\n newTexture.renderList = this.renderList.slice(0);\n }\n return newTexture;\n };\n MirrorTexture.prototype.serialize = function () {\n if (!this.name) {\n return null;\n }\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.mirrorPlane = this.mirrorPlane.asArray();\n return serializationObject;\n };\n MirrorTexture.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);\n };\n return MirrorTexture;\n }(BABYLON.RenderTargetTexture));\n BABYLON.MirrorTexture = MirrorTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.mirrorTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Creates a refraction texture used by refraction channel of the standard material.\n * @param name the texture name\n * @param size size of the underlying texture\n * @param scene root scene\n */\n var RefractionTexture = /** @class */ (function (_super) {\n __extends(RefractionTexture, _super);\n function RefractionTexture(name, size, scene, generateMipMaps) {\n var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;\n _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);\n _this.depth = 2.0;\n _this.onBeforeRenderObservable.add(function () {\n scene.clipPlane = _this.refractionPlane;\n });\n _this.onAfterRenderObservable.add(function () {\n delete scene.clipPlane;\n });\n return _this;\n }\n RefractionTexture.prototype.clone = function () {\n var scene = this.getScene();\n if (!scene) {\n return this;\n }\n var textureSize = this.getSize();\n var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // Refraction Texture\n newTexture.refractionPlane = this.refractionPlane.clone();\n if (this.renderList) {\n newTexture.renderList = this.renderList.slice(0);\n }\n newTexture.depth = this.depth;\n return newTexture;\n };\n RefractionTexture.prototype.serialize = function () {\n if (!this.name) {\n return null;\n }\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.mirrorPlane = this.refractionPlane.asArray();\n serializationObject.depth = this.depth;\n return serializationObject;\n };\n return RefractionTexture;\n }(BABYLON.RenderTargetTexture));\n BABYLON.RefractionTexture = RefractionTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.refractionTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A class extending {BABYLON.Texture} allowing drawing on a texture\n * @see http://doc.babylonjs.com/how_to/dynamictexture\n */\n var DynamicTexture = /** @class */ (function (_super) {\n __extends(DynamicTexture, _super);\n /**\n * Creates a {BABYLON.DynamicTexture}\n * @param name defines the name of the texture\n * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height\n * @param scene defines the scene where you want the texture\n * @param generateMipMaps defines the use of MinMaps or not (default is false)\n * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)\n * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)\n */\n function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {\n if (scene === void 0) { scene = null; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }\n var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;\n _this.name = name;\n _this._engine = _this.getScene().getEngine();\n _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this._generateMipMaps = generateMipMaps;\n if (options.getContext) {\n _this._canvas = options;\n _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);\n }\n else {\n _this._canvas = document.createElement(\"canvas\");\n if (options.width || options.width === 0) {\n _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);\n }\n else {\n _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);\n }\n }\n var textureSize = _this.getSize();\n _this._canvas.width = textureSize.width;\n _this._canvas.height = textureSize.height;\n _this._context = _this._canvas.getContext(\"2d\");\n return _this;\n }\n Object.defineProperty(DynamicTexture.prototype, \"canRescale\", {\n /**\n * Gets the current state of canRescale\n */\n get: function () {\n return true;\n },\n enumerable: true,\n configurable: true\n });\n DynamicTexture.prototype._recreate = function (textureSize) {\n this._canvas.width = textureSize.width;\n this._canvas.height = textureSize.height;\n this.releaseInternalTexture();\n this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);\n };\n /**\n * Scales the texture\n * @param ratio the scale factor to apply to both width and height\n */\n DynamicTexture.prototype.scale = function (ratio) {\n var textureSize = this.getSize();\n textureSize.width *= ratio;\n textureSize.height *= ratio;\n this._recreate(textureSize);\n };\n /**\n * Resizes the texture\n * @param width the new width\n * @param height the new height\n */\n DynamicTexture.prototype.scaleTo = function (width, height) {\n var textureSize = this.getSize();\n textureSize.width = width;\n textureSize.height = height;\n this._recreate(textureSize);\n };\n /**\n * Gets the context of the canvas used by the texture\n * @returns the canvas context of the dynamic texture\n */\n DynamicTexture.prototype.getContext = function () {\n return this._context;\n };\n /**\n * Clears the texture\n */\n DynamicTexture.prototype.clear = function () {\n var size = this.getSize();\n this._context.fillRect(0, 0, size.width, size.height);\n };\n /**\n * Updates the texture\n * @param invertY defines the direction for the Y axis (default is true - y increases downwards)\n * @param premulAlpha defines if alpha is stored as premultiplied (default is false)\n */\n DynamicTexture.prototype.update = function (invertY, premulAlpha) {\n if (premulAlpha === void 0) { premulAlpha = false; }\n this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);\n };\n /**\n * Draws text onto the texture\n * @param text defines the text to be drawn\n * @param x defines the placement of the text from the left\n * @param y defines the placement of the text from the top when invertY is true and from the bottom when false\n * @param font defines the font to be used with font-style, font-size, font-name\n * @param color defines the color used for the text\n * @param clearColor defines the color for the canvas, use null to not overwrite canvas\n * @param invertY defines the direction for the Y axis (default is true - y increases downwards)\n * @param update defines whether texture is immediately update (default is true)\n */\n DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {\n if (update === void 0) { update = true; }\n var size = this.getSize();\n if (clearColor) {\n this._context.fillStyle = clearColor;\n this._context.fillRect(0, 0, size.width, size.height);\n }\n this._context.font = font;\n if (x === null || x === undefined) {\n var textSize = this._context.measureText(text);\n x = (size.width - textSize.width) / 2;\n }\n if (y === null || y === undefined) {\n var fontSize = parseInt((font.replace(/\\D/g, '')));\n y = (size.height / 2) + (fontSize / 3.65);\n }\n this._context.fillStyle = color;\n this._context.fillText(text, x, y);\n if (update) {\n this.update(invertY);\n }\n };\n /**\n * Clones the texture\n * @returns the clone of the texture.\n */\n DynamicTexture.prototype.clone = function () {\n var scene = this.getScene();\n if (!scene) {\n return this;\n }\n var textureSize = this.getSize();\n var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // Dynamic Texture\n newTexture.wrapU = this.wrapU;\n newTexture.wrapV = this.wrapV;\n return newTexture;\n };\n /**\n * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized\n * @returns a serialized dynamic texture object\n */\n DynamicTexture.prototype.serialize = function () {\n var scene = this.getScene();\n if (scene && !scene.isReady()) {\n BABYLON.Tools.Warn(\"The scene must be ready before serializing the dynamic texture\");\n }\n var serializationObject = _super.prototype.serialize.call(this);\n serializationObject.base64String = this._canvas.toDataURL();\n serializationObject.invertY = this._invertY;\n serializationObject.samplingMode = this.samplingMode;\n return serializationObject;\n };\n /** @hidden */\n DynamicTexture.prototype._rebuild = function () {\n this.update();\n };\n return DynamicTexture;\n }(BABYLON.Texture));\n BABYLON.DynamicTexture = DynamicTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.dynamicTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var VideoTexture = /** @class */ (function (_super) {\n __extends(VideoTexture, _super);\n /**\n * Creates a video texture.\n * Sample : https://doc.babylonjs.com/how_to/video_texture\n * @param {string | null} name optional name, will detect from video source, if not defined\n * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.\n * @param {BABYLON.Scene} scene is obviously the current scene.\n * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).\n * @param {boolean} invertY is false by default but can be used to invert video on Y axis\n * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default\n * @param {VideoTextureSettings} [settings] allows finer control over video usage\n */\n function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {\n if (generateMipMaps === void 0) { generateMipMaps = false; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (settings === void 0) { settings = {\n autoPlay: true,\n loop: true,\n autoUpdateTexture: true,\n }; }\n var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;\n _this._onUserActionRequestedObservable = null;\n _this._stillImageCaptured = false;\n _this._poster = false;\n _this._createInternalTexture = function () {\n if (_this._texture != null) {\n if (_this._poster) {\n _this._texture.dispose();\n _this._poster = false;\n }\n else {\n return;\n }\n }\n if (!_this._engine.needPOTTextures ||\n (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {\n _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n }\n else {\n _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this._generateMipMaps = false;\n }\n _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);\n if (!_this.video.autoplay) {\n var oldHandler_1 = _this.video.onplaying;\n var error_1 = false;\n _this.video.onplaying = function () {\n _this.video.onplaying = oldHandler_1;\n _this._texture.isReady = true;\n _this._updateInternalTexture();\n if (!error_1) {\n _this.video.pause();\n }\n if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {\n _this.onLoadObservable.notifyObservers(_this);\n }\n };\n var playing = _this.video.play();\n if (playing) {\n playing.then(function () {\n // Everything is good.\n })\n .catch(function () {\n error_1 = true;\n // On Chrome for instance, new policies might prevent playing without user interaction.\n if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {\n _this._onUserActionRequestedObservable.notifyObservers(_this);\n }\n });\n }\n else {\n _this.video.onplaying = oldHandler_1;\n _this._texture.isReady = true;\n _this._updateInternalTexture();\n if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {\n _this.onLoadObservable.notifyObservers(_this);\n }\n }\n }\n else {\n _this._texture.isReady = true;\n _this._updateInternalTexture();\n if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {\n _this.onLoadObservable.notifyObservers(_this);\n }\n }\n };\n _this.reset = function () {\n if (_this._texture == null) {\n return;\n }\n if (!_this._poster) {\n _this._texture.dispose();\n _this._texture = null;\n }\n };\n _this._updateInternalTexture = function (e) {\n if (_this._texture == null || !_this._texture.isReady) {\n return;\n }\n if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {\n return;\n }\n _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);\n };\n _this._engine = _this.getScene().getEngine();\n _this._generateMipMaps = generateMipMaps;\n _this._samplingMode = samplingMode;\n _this.autoUpdateTexture = settings.autoUpdateTexture;\n _this.name = name || _this._getName(src);\n _this.video = _this._getVideo(src);\n if (settings.poster) {\n _this.video.poster = settings.poster;\n }\n if (settings.autoPlay !== undefined) {\n _this.video.autoplay = settings.autoPlay;\n }\n if (settings.loop !== undefined) {\n _this.video.loop = settings.loop;\n }\n _this.video.setAttribute(\"playsinline\", \"\");\n _this.video.addEventListener(\"canplay\", _this._createInternalTexture);\n _this.video.addEventListener(\"paused\", _this._updateInternalTexture);\n _this.video.addEventListener(\"seeked\", _this._updateInternalTexture);\n _this.video.addEventListener(\"emptied\", _this.reset);\n if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {\n _this._createInternalTexture();\n }\n if (settings.poster) {\n _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);\n _this._poster = true;\n }\n return _this;\n }\n Object.defineProperty(VideoTexture.prototype, \"onUserActionRequestedObservable\", {\n get: function () {\n if (!this._onUserActionRequestedObservable) {\n this._onUserActionRequestedObservable = new BABYLON.Observable();\n }\n return this._onUserActionRequestedObservable;\n },\n enumerable: true,\n configurable: true\n });\n VideoTexture.prototype._getName = function (src) {\n if (src instanceof HTMLVideoElement) {\n return src.currentSrc;\n }\n if (typeof src === \"object\") {\n return src.toString();\n }\n return src;\n };\n ;\n VideoTexture.prototype._getVideo = function (src) {\n if (src instanceof HTMLVideoElement) {\n BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);\n return src;\n }\n var video = document.createElement(\"video\");\n if (typeof src === \"string\") {\n BABYLON.Tools.SetCorsBehavior(src, video);\n video.src = src;\n }\n else {\n BABYLON.Tools.SetCorsBehavior(src[0], video);\n src.forEach(function (url) {\n var source = document.createElement(\"source\");\n source.src = url;\n video.appendChild(source);\n });\n }\n return video;\n };\n ;\n /**\n * Internal method to initiate `update`.\n */\n VideoTexture.prototype._rebuild = function () {\n this.update();\n };\n /**\n * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.\n */\n VideoTexture.prototype.update = function () {\n if (!this.autoUpdateTexture) {\n // Expecting user to call `updateTexture` manually\n return;\n }\n this.updateTexture(true);\n };\n /**\n * Update Texture in `manual` mode. Does not do anything if not visible or paused.\n * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.\n */\n VideoTexture.prototype.updateTexture = function (isVisible) {\n if (!isVisible) {\n return;\n }\n if (this.video.paused && this._stillImageCaptured) {\n return;\n }\n this._stillImageCaptured = true;\n this._updateInternalTexture();\n };\n /**\n * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.\n * @param url New url.\n */\n VideoTexture.prototype.updateURL = function (url) {\n this.video.src = url;\n };\n VideoTexture.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n if (this._onUserActionRequestedObservable) {\n this._onUserActionRequestedObservable.clear();\n this._onUserActionRequestedObservable = null;\n }\n this.video.removeEventListener(\"canplay\", this._createInternalTexture);\n this.video.removeEventListener(\"paused\", this._updateInternalTexture);\n this.video.removeEventListener(\"seeked\", this._updateInternalTexture);\n this.video.removeEventListener(\"emptied\", this.reset);\n this.video.pause();\n };\n VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {\n var video = document.createElement(\"video\");\n video.setAttribute('autoplay', '');\n video.setAttribute('muted', '');\n video.setAttribute('playsinline', '');\n var constraintsDeviceId;\n if (constraints && constraints.deviceId) {\n constraintsDeviceId = {\n exact: constraints.deviceId,\n };\n }\n window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;\n if (navigator.mediaDevices) {\n navigator.mediaDevices.getUserMedia({ video: constraints })\n .then(function (stream) {\n if (video.mozSrcObject !== undefined) {\n // hack for Firefox < 19\n video.mozSrcObject = stream;\n }\n else {\n video.srcObject = stream;\n }\n var onPlaying = function () {\n if (onReady) {\n onReady(new VideoTexture(\"video\", video, scene, true, true));\n }\n video.removeEventListener(\"playing\", onPlaying);\n };\n video.addEventListener(\"playing\", onPlaying);\n video.play();\n })\n .catch(function (err) {\n BABYLON.Tools.Error(err.name);\n });\n }\n else {\n navigator.getUserMedia =\n navigator.getUserMedia ||\n navigator.webkitGetUserMedia ||\n navigator.mozGetUserMedia ||\n navigator.msGetUserMedia;\n if (navigator.getUserMedia) {\n navigator.getUserMedia({\n video: {\n deviceId: constraintsDeviceId,\n width: {\n min: (constraints && constraints.minWidth) || 256,\n max: (constraints && constraints.maxWidth) || 640,\n },\n height: {\n min: (constraints && constraints.minHeight) || 256,\n max: (constraints && constraints.maxHeight) || 480,\n },\n },\n }, function (stream) {\n if (video.mozSrcObject !== undefined) {\n // hack for Firefox < 19\n video.mozSrcObject = stream;\n }\n else {\n video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;\n }\n video.play();\n if (onReady) {\n onReady(new VideoTexture(\"video\", video, scene, true, true));\n }\n }, function (e) {\n BABYLON.Tools.Error(e.name);\n });\n }\n }\n };\n return VideoTexture;\n }(BABYLON.Texture));\n BABYLON.VideoTexture = VideoTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.videoTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var RawTexture = /** @class */ (function (_super) {\n __extends(RawTexture, _super);\n function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;\n _this.format = format;\n _this._engine = scene.getEngine();\n _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);\n _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n return _this;\n }\n RawTexture.prototype.update = function (data) {\n this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);\n };\n // Statics\n RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);\n };\n RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);\n };\n RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);\n };\n RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);\n };\n RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);\n };\n RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }\n return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);\n };\n return RawTexture;\n }(BABYLON.Texture));\n BABYLON.RawTexture = RawTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.rawTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to store 3D textures containing user data\n */\n var RawTexture3D = /** @class */ (function (_super) {\n __extends(RawTexture3D, _super);\n /**\n * Create a new RawTexture3D\n * @param data defines the data of the texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param depth defines the depth of the texture\n * @param format defines the texture format to use\n * @param scene defines the hosting scene\n * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)\n * @param invertY defines if texture must be stored with Y axis inverted\n * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)\n * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)\n */\n function RawTexture3D(data, width, height, depth, \n /** Gets or sets the texture format to use */\n format, scene, generateMipMaps, invertY, samplingMode, textureType) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (invertY === void 0) { invertY = false; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;\n _this.format = format;\n _this._engine = scene.getEngine();\n _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);\n _this.is3D = true;\n return _this;\n }\n /**\n * Update the texture with new data\n * @param data defines the data to store in the texture\n */\n RawTexture3D.prototype.update = function (data) {\n if (!this._texture) {\n return;\n }\n this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);\n };\n return RawTexture3D;\n }(BABYLON.Texture));\n BABYLON.RawTexture3D = RawTexture3D;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.rawTexture3D.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * PostProcessManager is used to manage one or more post processes or post process pipelines\n * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses\n */\n var PostProcessManager = /** @class */ (function () {\n /**\n * Creates a new instance PostProcess\n * @param scene The scene that the post process is associated with.\n */\n function PostProcessManager(scene) {\n this._vertexBuffers = {};\n this._scene = scene;\n }\n PostProcessManager.prototype._prepareBuffers = function () {\n if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {\n return;\n }\n // VBO\n var vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);\n this._buildIndexBuffer();\n };\n PostProcessManager.prototype._buildIndexBuffer = function () {\n // Indices\n var indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);\n };\n /**\n * Rebuilds the vertex buffers of the manager.\n */\n PostProcessManager.prototype._rebuild = function () {\n var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (!vb) {\n return;\n }\n vb._rebuild();\n this._buildIndexBuffer();\n };\n // Methods\n /**\n * Prepares a frame to be run through a post process.\n * @param sourceTexture The input texture to the post procesess. (default: null)\n * @param postProcesses An array of post processes to be run. (default: null)\n * @returns True if the post processes were able to be run.\n */\n PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {\n if (sourceTexture === void 0) { sourceTexture = null; }\n if (postProcesses === void 0) { postProcesses = null; }\n var camera = this._scene.activeCamera;\n if (!camera) {\n return false;\n }\n var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });\n if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {\n return false;\n }\n postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);\n return true;\n };\n /**\n * Manually render a set of post processes to a texture.\n * @param postProcesses An array of post processes to be run.\n * @param targetTexture The target texture to render to.\n * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight\n * @param faceIndex defines the face to render to if a cubemap is defined as the target\n * @param lodLevel defines which lod of the texture to render to\n */\n PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {\n if (targetTexture === void 0) { targetTexture = null; }\n if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lodLevel === void 0) { lodLevel = 0; }\n var engine = this._scene.getEngine();\n for (var index = 0; index < postProcesses.length; index++) {\n if (index < postProcesses.length - 1) {\n postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);\n }\n else {\n if (targetTexture) {\n engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);\n }\n else {\n engine.restoreDefaultFramebuffer();\n }\n }\n var pp = postProcesses[index];\n var effect = pp.apply();\n if (effect) {\n pp.onBeforeRenderObservable.notifyObservers(effect);\n // VBOs\n this._prepareBuffers();\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n // Draw order\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n pp.onAfterRenderObservable.notifyObservers(effect);\n }\n }\n // Restore depth buffer\n engine.setDepthBuffer(true);\n engine.setDepthWrite(true);\n };\n /**\n * Finalize the result of the output of the postprocesses.\n * @param doNotPresent If true the result will not be displayed to the screen.\n * @param targetTexture The target texture to render to.\n * @param faceIndex The index of the face to bind the target texture to.\n * @param postProcesses The array of post processes to render.\n * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)\n */\n PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {\n if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }\n var camera = this._scene.activeCamera;\n if (!camera) {\n return;\n }\n postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });\n if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {\n return;\n }\n var engine = this._scene.getEngine();\n for (var index = 0, len = postProcesses.length; index < len; index++) {\n var pp = postProcesses[index];\n if (index < len - 1) {\n pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);\n }\n else {\n if (targetTexture) {\n engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);\n pp._outputTexture = targetTexture;\n }\n else {\n engine.restoreDefaultFramebuffer();\n pp._outputTexture = null;\n }\n }\n if (doNotPresent) {\n break;\n }\n var effect = pp.apply();\n if (effect) {\n pp.onBeforeRenderObservable.notifyObservers(effect);\n // VBOs\n this._prepareBuffers();\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n // Draw order\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n pp.onAfterRenderObservable.notifyObservers(effect);\n }\n }\n // Restore states\n engine.setDepthBuffer(true);\n engine.setDepthWrite(true);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n };\n /**\n * Disposes of the post process manager.\n */\n PostProcessManager.prototype.dispose = function () {\n var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (buffer) {\n buffer.dispose();\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n };\n return PostProcessManager;\n }());\n BABYLON.PostProcessManager = PostProcessManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.postProcessManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * PostProcess can be used to apply a shader to a texture after it has been rendered\n * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses\n */\n var PostProcess = /** @class */ (function () {\n /**\n * Creates a new instance PostProcess\n * @param name The name of the PostProcess.\n * @param fragmentUrl The url of the fragment shader to be used.\n * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.\n * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.\n * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param defines String of defines that will be set when running the fragment shader. (default: null)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param vertexUrl The url of the vertex shader to be used. (default: \"postprocess\")\n * @param indexParameters The index parameters to be used for babylons include syntax \"#include[0..varyingCount]\". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx\n * @param blockCompilation If the shader should not be compiled imediatly. (default: false)\n */\n function PostProcess(\n /** Name of the PostProcess. */\n name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }\n if (defines === void 0) { defines = null; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (vertexUrl === void 0) { vertexUrl = \"postprocess\"; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n this.name = name;\n /**\n * Width of the texture to apply the post process on\n */\n this.width = -1;\n /**\n * Height of the texture to apply the post process on\n */\n this.height = -1;\n /**\n * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)\n */\n this._outputTexture = null;\n /**\n * If the buffer needs to be cleared before applying the post process. (default: true)\n * Should be set to false if shader will overwrite all previous pixels.\n */\n this.autoClear = true;\n /**\n * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)\n */\n this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;\n /**\n * Animations to be used for the post processing\n */\n this.animations = new Array();\n /**\n * Enable Pixel Perfect mode where texture is not scaled to be power of 2.\n * Can only be used on a single postprocess or on the last one of a chain. (default: false)\n */\n this.enablePixelPerfectMode = false;\n /**\n * Force the postprocess to be applied without taking in account viewport\n */\n this.forceFullscreenViewport = true;\n /**\n * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)\n *\n * | Value | Type | Description |\n * | ----- | ----------------------------------- | ----------- |\n * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |\n * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |\n * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |\n *\n */\n this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;\n /**\n * Force textures to be a power of two (default: false)\n */\n this.alwaysForcePOT = false;\n /**\n * Number of sample textures (default: 1)\n */\n this.samples = 1;\n /**\n * Modify the scale of the post process to be the same as the viewport (default: false)\n */\n this.adaptScaleToCurrentViewport = false;\n this._reusable = false;\n /**\n * Smart array of input and output textures for the post process.\n */\n this._textures = new BABYLON.SmartArray(2);\n /**\n * The index in _textures that corresponds to the output texture.\n */\n this._currentRenderTextureInd = 0;\n this._scaleRatio = new BABYLON.Vector2(1, 1);\n this._texelSize = BABYLON.Vector2.Zero();\n // Events\n /**\n * An event triggered when the postprocess is activated.\n */\n this.onActivateObservable = new BABYLON.Observable();\n /**\n * An event triggered when the postprocess changes its size.\n */\n this.onSizeChangedObservable = new BABYLON.Observable();\n /**\n * An event triggered when the postprocess applies its effect.\n */\n this.onApplyObservable = new BABYLON.Observable();\n /**\n * An event triggered before rendering the postprocess\n */\n this.onBeforeRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered after rendering the postprocess\n */\n this.onAfterRenderObservable = new BABYLON.Observable();\n if (camera != null) {\n this._camera = camera;\n this._scene = camera.getScene();\n camera.attachPostProcess(this);\n this._engine = this._scene.getEngine();\n this._scene.postProcesses.push(this);\n }\n else if (engine) {\n this._engine = engine;\n this._engine.postProcesses.push(this);\n }\n this._options = options;\n this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;\n this._reusable = reusable || false;\n this._textureType = textureType;\n this._samplers = samplers || [];\n this._samplers.push(\"textureSampler\");\n this._fragmentUrl = fragmentUrl;\n this._vertexUrl = vertexUrl;\n this._parameters = parameters || [];\n this._parameters.push(\"scale\");\n this._indexParameters = indexParameters;\n if (!blockCompilation) {\n this.updateEffect(defines);\n }\n }\n Object.defineProperty(PostProcess.prototype, \"onActivate\", {\n /**\n * A function that is added to the onActivateObservable\n */\n set: function (callback) {\n if (this._onActivateObserver) {\n this.onActivateObservable.remove(this._onActivateObserver);\n }\n if (callback) {\n this._onActivateObserver = this.onActivateObservable.add(callback);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PostProcess.prototype, \"onSizeChanged\", {\n /**\n * A function that is added to the onSizeChangedObservable\n */\n set: function (callback) {\n if (this._onSizeChangedObserver) {\n this.onSizeChangedObservable.remove(this._onSizeChangedObserver);\n }\n this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PostProcess.prototype, \"onApply\", {\n /**\n * A function that is added to the onApplyObservable\n */\n set: function (callback) {\n if (this._onApplyObserver) {\n this.onApplyObservable.remove(this._onApplyObserver);\n }\n this._onApplyObserver = this.onApplyObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PostProcess.prototype, \"onBeforeRender\", {\n /**\n * A function that is added to the onBeforeRenderObservable\n */\n set: function (callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PostProcess.prototype, \"onAfterRender\", {\n /**\n * A function that is added to the onAfterRenderObservable\n */\n set: function (callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PostProcess.prototype, \"inputTexture\", {\n /**\n * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will\n * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.\n */\n get: function () {\n return this._textures.data[this._currentRenderTextureInd];\n },\n set: function (value) {\n this._forcedOutputTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the camera which post process is applied to.\n * @returns The camera the post process is applied to.\n */\n PostProcess.prototype.getCamera = function () {\n return this._camera;\n };\n Object.defineProperty(PostProcess.prototype, \"texelSize\", {\n /**\n * Gets the texel size of the postprocess.\n * See https://en.wikipedia.org/wiki/Texel_(graphics)\n */\n get: function () {\n if (this._shareOutputWithPostProcess) {\n return this._shareOutputWithPostProcess.texelSize;\n }\n if (this._forcedOutputTexture) {\n this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);\n }\n return this._texelSize;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the engine which this post process belongs to.\n * @returns The engine the post process was enabled with.\n */\n PostProcess.prototype.getEngine = function () {\n return this._engine;\n };\n /**\n * The effect that is created when initializing the post process.\n * @returns The created effect corrisponding the the postprocess.\n */\n PostProcess.prototype.getEffect = function () {\n return this._effect;\n };\n /**\n * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.\n * @param postProcess The post process to share the output with.\n * @returns This post process.\n */\n PostProcess.prototype.shareOutputWith = function (postProcess) {\n this._disposeTextures();\n this._shareOutputWithPostProcess = postProcess;\n return this;\n };\n /**\n * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.\n * This should be called if the post process that shares output with this post process is disabled/disposed.\n */\n PostProcess.prototype.useOwnOutput = function () {\n if (this._textures.length == 0) {\n this._textures = new BABYLON.SmartArray(2);\n }\n this._shareOutputWithPostProcess = null;\n };\n /**\n * Updates the effect with the current post process compile time values and recompiles the shader.\n * @param defines Define statements that should be added at the beginning of the shader. (default: null)\n * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)\n * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)\n * @param indexParameters The index parameters to be used for babylons include syntax \"#include[0..varyingCount]\". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx\n * @param onCompiled Called when the shader has been compiled.\n * @param onError Called if there is an error when compiling a shader.\n */\n PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {\n if (defines === void 0) { defines = null; }\n if (uniforms === void 0) { uniforms = null; }\n if (samplers === void 0) { samplers = null; }\n this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, [\"position\"], uniforms || this._parameters, samplers || this._samplers, defines !== null ? defines : \"\", undefined, onCompiled, onError, indexParameters || this._indexParameters);\n };\n /**\n * The post process is reusable if it can be used multiple times within one frame.\n * @returns If the post process is reusable\n */\n PostProcess.prototype.isReusable = function () {\n return this._reusable;\n };\n /** invalidate frameBuffer to hint the postprocess to create a depth buffer */\n PostProcess.prototype.markTextureDirty = function () {\n this.width = -1;\n };\n /**\n * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.\n * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.\n * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.\n * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)\n * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)\n * @returns The target texture that was bound to be written to.\n */\n PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {\n var _this = this;\n if (sourceTexture === void 0) { sourceTexture = null; }\n camera = camera || this._camera;\n var scene = camera.getScene();\n var engine = scene.getEngine();\n var maxSize = engine.getCaps().maxTextureSize;\n var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;\n var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;\n // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen\n var webVRCamera = camera.parent;\n if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {\n requiredWidth /= 2;\n }\n var desiredWidth = (this._options.width || requiredWidth);\n var desiredHeight = this._options.height || requiredHeight;\n if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {\n if (this.adaptScaleToCurrentViewport) {\n var currentViewport = engine.currentViewport;\n if (currentViewport) {\n desiredWidth *= currentViewport.width;\n desiredHeight *= currentViewport.height;\n }\n }\n if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {\n if (!this._options.width) {\n desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;\n }\n if (!this._options.height) {\n desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;\n }\n }\n if (this.width !== desiredWidth || this.height !== desiredHeight) {\n if (this._textures.length > 0) {\n for (var i = 0; i < this._textures.length; i++) {\n this._engine._releaseTexture(this._textures.data[i]);\n }\n this._textures.reset();\n }\n this.width = desiredWidth;\n this.height = desiredHeight;\n var textureSize = { width: this.width, height: this.height };\n var textureOptions = {\n generateMipMaps: false,\n generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,\n generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,\n samplingMode: this.renderTargetSamplingMode,\n type: this._textureType\n };\n this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));\n if (this._reusable) {\n this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));\n }\n this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);\n this.onSizeChangedObservable.notifyObservers(this);\n }\n this._textures.forEach(function (texture) {\n if (texture.samples !== _this.samples) {\n _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);\n }\n });\n }\n var target;\n if (this._shareOutputWithPostProcess) {\n target = this._shareOutputWithPostProcess.inputTexture;\n }\n else if (this._forcedOutputTexture) {\n target = this._forcedOutputTexture;\n this.width = this._forcedOutputTexture.width;\n this.height = this._forcedOutputTexture.height;\n }\n else {\n target = this.inputTexture;\n }\n // Bind the input of this post process to be used as the output of the previous post process.\n if (this.enablePixelPerfectMode) {\n this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);\n this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);\n }\n else {\n this._scaleRatio.copyFromFloats(1, 1);\n this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);\n }\n this.onActivateObservable.notifyObservers(camera);\n // Clear\n if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {\n this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);\n }\n if (this._reusable) {\n this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;\n }\n return target;\n };\n Object.defineProperty(PostProcess.prototype, \"isSupported\", {\n /**\n * If the post process is supported.\n */\n get: function () {\n return this._effect.isSupported;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PostProcess.prototype, \"aspectRatio\", {\n /**\n * The aspect ratio of the output texture.\n */\n get: function () {\n if (this._shareOutputWithPostProcess) {\n return this._shareOutputWithPostProcess.aspectRatio;\n }\n if (this._forcedOutputTexture) {\n return this._forcedOutputTexture.width / this._forcedOutputTexture.height;\n }\n return this.width / this.height;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Get a value indicating if the post-process is ready to be used\n * @returns true if the post-process is ready (shader is compiled)\n */\n PostProcess.prototype.isReady = function () {\n return this._effect && this._effect.isReady();\n };\n /**\n * Binds all textures and uniforms to the shader, this will be run on every pass.\n * @returns the effect corrisponding to this post process. Null if not compiled or not ready.\n */\n PostProcess.prototype.apply = function () {\n // Check\n if (!this._effect || !this._effect.isReady())\n return null;\n // States\n this._engine.enableEffect(this._effect);\n this._engine.setState(false);\n this._engine.setDepthBuffer(false);\n this._engine.setDepthWrite(false);\n // Alpha\n this._engine.setAlphaMode(this.alphaMode);\n if (this.alphaConstants) {\n this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);\n }\n // Bind the output texture of the preivous post process as the input to this post process. \n var source;\n if (this._shareOutputWithPostProcess) {\n source = this._shareOutputWithPostProcess.inputTexture;\n }\n else if (this._forcedOutputTexture) {\n source = this._forcedOutputTexture;\n }\n else {\n source = this.inputTexture;\n }\n this._effect._bindTexture(\"textureSampler\", source);\n // Parameters\n this._effect.setVector2(\"scale\", this._scaleRatio);\n this.onApplyObservable.notifyObservers(this._effect);\n return this._effect;\n };\n PostProcess.prototype._disposeTextures = function () {\n if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {\n return;\n }\n if (this._textures.length > 0) {\n for (var i = 0; i < this._textures.length; i++) {\n this._engine._releaseTexture(this._textures.data[i]);\n }\n }\n this._textures.dispose();\n };\n /**\n * Disposes the post process.\n * @param camera The camera to dispose the post process on.\n */\n PostProcess.prototype.dispose = function (camera) {\n camera = camera || this._camera;\n this._disposeTextures();\n if (this._scene) {\n var index_1 = this._scene.postProcesses.indexOf(this);\n if (index_1 !== -1) {\n this._scene.postProcesses.splice(index_1, 1);\n }\n }\n else {\n var index_2 = this._engine.postProcesses.indexOf(this);\n if (index_2 !== -1) {\n this._engine.postProcesses.splice(index_2, 1);\n }\n }\n if (!camera) {\n return;\n }\n camera.detachPostProcess(this);\n var index = camera._postProcesses.indexOf(this);\n if (index === 0 && camera._postProcesses.length > 0) {\n var firstPostProcess = this._camera._getFirstPostProcess();\n if (firstPostProcess) {\n firstPostProcess.markTextureDirty();\n }\n }\n this.onActivateObservable.clear();\n this.onAfterRenderObservable.clear();\n this.onApplyObservable.clear();\n this.onBeforeRenderObservable.clear();\n this.onSizeChangedObservable.clear();\n };\n return PostProcess;\n }());\n BABYLON.PostProcess = PostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.postProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var PassPostProcess = /** @class */ (function (_super) {\n __extends(PassPostProcess, _super);\n function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (camera === void 0) { camera = null; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n return _super.call(this, name, \"pass\", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;\n }\n return PassPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.PassPostProcess = PassPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.passPostProcess.js.map\n\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Default implementation IShadowGenerator.\n * This is the main object responsible of generating shadows in the framework.\n * Documentation: https://doc.babylonjs.com/babylon101/shadows\n */\n var ShadowGenerator = /** @class */ (function () {\n /**\n * Creates a ShadowGenerator object.\n * A ShadowGenerator is the required tool to use the shadows.\n * Each light casting shadows needs to use its own ShadowGenerator.\n * Documentation : http://doc.babylonjs.com/tutorials/shadows\n * @param mapSize The size of the texture what stores the shadows. Example : 1024.\n * @param light The light object generating the shadows.\n * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.\n */\n function ShadowGenerator(mapSize, light, useFullFloatFirst) {\n this._bias = 0.00005;\n this._normalBias = 0;\n this._blurBoxOffset = 1;\n this._blurScale = 2;\n this._blurKernel = 1;\n this._useKernelBlur = false;\n this._filter = ShadowGenerator.FILTER_NONE;\n this._filteringQuality = ShadowGenerator.QUALITY_HIGH;\n this._contactHardeningLightSizeUVRatio = 0.1;\n this._darkness = 0;\n this._transparencyShadow = false;\n /**\n * Controls the extent to which the shadows fade out at the edge of the frustum\n * Used only by directionals and spots\n */\n this.frustumEdgeFalloff = 0;\n /**\n * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.\n * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.\n * It might on the other hand introduce peter panning.\n */\n this.forceBackFacesOnly = false;\n this._lightDirection = BABYLON.Vector3.Zero();\n this._viewMatrix = BABYLON.Matrix.Zero();\n this._projectionMatrix = BABYLON.Matrix.Zero();\n this._transformMatrix = BABYLON.Matrix.Zero();\n this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._currentFaceIndex = 0;\n this._currentFaceIndexCache = 0;\n this._defaultTextureMatrix = BABYLON.Matrix.Identity();\n this._mapSize = mapSize;\n this._light = light;\n this._scene = light.getScene();\n light._shadowGenerator = this;\n // Texture type fallback from float to int if not supported.\n var caps = this._scene.getEngine().getCaps();\n if (!useFullFloatFirst) {\n if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n else {\n this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n }\n else {\n if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else {\n this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n }\n this._initializeGenerator();\n this._applyFilterValues();\n }\n Object.defineProperty(ShadowGenerator.prototype, \"bias\", {\n /**\n * Gets the bias: offset applied on the depth preventing acnea (in light direction).\n */\n get: function () {\n return this._bias;\n },\n /**\n * Sets the bias: offset applied on the depth preventing acnea (in light direction).\n */\n set: function (bias) {\n this._bias = bias;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"normalBias\", {\n /**\n * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).\n */\n get: function () {\n return this._normalBias;\n },\n /**\n * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).\n */\n set: function (normalBias) {\n this._normalBias = normalBias;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"blurBoxOffset\", {\n /**\n * Gets the blur box offset: offset applied during the blur pass.\n * Only usefull if useKernelBlur = false\n */\n get: function () {\n return this._blurBoxOffset;\n },\n /**\n * Sets the blur box offset: offset applied during the blur pass.\n * Only usefull if useKernelBlur = false\n */\n set: function (value) {\n if (this._blurBoxOffset === value) {\n return;\n }\n this._blurBoxOffset = value;\n this._disposeBlurPostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"blurScale\", {\n /**\n * Gets the blur scale: scale of the blurred texture compared to the main shadow map.\n * 2 means half of the size.\n */\n get: function () {\n return this._blurScale;\n },\n /**\n * Sets the blur scale: scale of the blurred texture compared to the main shadow map.\n * 2 means half of the size.\n */\n set: function (value) {\n if (this._blurScale === value) {\n return;\n }\n this._blurScale = value;\n this._disposeBlurPostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"blurKernel\", {\n /**\n * Gets the blur kernel: kernel size of the blur pass.\n * Only usefull if useKernelBlur = true\n */\n get: function () {\n return this._blurKernel;\n },\n /**\n * Sets the blur kernel: kernel size of the blur pass.\n * Only usefull if useKernelBlur = true\n */\n set: function (value) {\n if (this._blurKernel === value) {\n return;\n }\n this._blurKernel = value;\n this._disposeBlurPostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useKernelBlur\", {\n /**\n * Gets whether the blur pass is a kernel blur (if true) or box blur.\n * Only usefull in filtered mode (useBlurExponentialShadowMap...)\n */\n get: function () {\n return this._useKernelBlur;\n },\n /**\n * Sets whether the blur pass is a kernel blur (if true) or box blur.\n * Only usefull in filtered mode (useBlurExponentialShadowMap...)\n */\n set: function (value) {\n if (this._useKernelBlur === value) {\n return;\n }\n this._useKernelBlur = value;\n this._disposeBlurPostProcesses();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"depthScale\", {\n /**\n * Gets the depth scale used in ESM mode.\n */\n get: function () {\n return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();\n },\n /**\n * Sets the depth scale used in ESM mode.\n * This can override the scale stored on the light.\n */\n set: function (value) {\n this._depthScale = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"filter\", {\n /**\n * Gets the current mode of the shadow generator (normal, PCF, ESM...).\n * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE\n */\n get: function () {\n return this._filter;\n },\n /**\n * Sets the current mode of the shadow generator (normal, PCF, ESM...).\n * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE\n */\n set: function (value) {\n // Blurring the cubemap is going to be too expensive. Reverting to unblurred version\n if (this._light.needCube()) {\n if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {\n this.useExponentialShadowMap = true;\n return;\n }\n else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {\n this.useCloseExponentialShadowMap = true;\n return;\n }\n // PCF on cubemap would also be expensive\n else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {\n this.usePoissonSampling = true;\n return;\n }\n }\n // Weblg1 fallback for PCF.\n if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {\n if (this._scene.getEngine().webGLVersion === 1) {\n this.usePoissonSampling = true;\n return;\n }\n }\n if (this._filter === value) {\n return;\n }\n this._filter = value;\n this._disposeBlurPostProcesses();\n this._applyFilterValues();\n this._light._markMeshesAsLightDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"usePoissonSampling\", {\n /**\n * Gets if the current filter is set to Poisson Sampling.\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;\n },\n /**\n * Sets the current filter to Poisson Sampling.\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useVarianceShadowMap\", {\n /**\n * Gets if the current filter is set to VSM.\n * DEPRECATED. Should use useExponentialShadowMap instead.\n */\n get: function () {\n BABYLON.Tools.Warn(\"VSM are now replaced by ESM. Please use useExponentialShadowMap instead.\");\n return this.useExponentialShadowMap;\n },\n /**\n * Sets the current filter is to VSM.\n * DEPRECATED. Should use useExponentialShadowMap instead.\n */\n set: function (value) {\n BABYLON.Tools.Warn(\"VSM are now replaced by ESM. Please use useExponentialShadowMap instead.\");\n this.useExponentialShadowMap = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useBlurVarianceShadowMap\", {\n /**\n * Gets if the current filter is set to blurred VSM.\n * DEPRECATED. Should use useBlurExponentialShadowMap instead.\n */\n get: function () {\n BABYLON.Tools.Warn(\"VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.\");\n return this.useBlurExponentialShadowMap;\n },\n /**\n * Sets the current filter is to blurred VSM.\n * DEPRECATED. Should use useBlurExponentialShadowMap instead.\n */\n set: function (value) {\n BABYLON.Tools.Warn(\"VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.\");\n this.useBlurExponentialShadowMap = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useExponentialShadowMap\", {\n /**\n * Gets if the current filter is set to ESM.\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;\n },\n /**\n * Sets the current filter is to ESM.\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useBlurExponentialShadowMap\", {\n /**\n * Gets if the current filter is set to filtered ESM.\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;\n },\n /**\n * Gets if the current filter is set to filtered ESM.\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useCloseExponentialShadowMap\", {\n /**\n * Gets if the current filter is set to \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;\n },\n /**\n * Sets the current filter to \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useBlurCloseExponentialShadowMap\", {\n /**\n * Gets if the current filter is set to filtered \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;\n },\n /**\n * Sets the current filter to filtered \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"usePercentageCloserFiltering\", {\n /**\n * Gets if the current filter is set to \"PCF\" (percentage closer filtering).\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_PCF;\n },\n /**\n * Sets the current filter to \"PCF\" (percentage closer filtering).\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"filteringQuality\", {\n /**\n * Gets the PCF or PCSS Quality.\n * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.\n */\n get: function () {\n return this._filteringQuality;\n },\n /**\n * Sets the PCF or PCSS Quality.\n * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.\n */\n set: function (filteringQuality) {\n this._filteringQuality = filteringQuality;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"useContactHardeningShadow\", {\n /**\n * Gets if the current filter is set to \"PCSS\" (contact hardening).\n */\n get: function () {\n return this.filter === ShadowGenerator.FILTER_PCSS;\n },\n /**\n * Sets the current filter to \"PCSS\" (contact hardening).\n */\n set: function (value) {\n if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {\n return;\n }\n this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ShadowGenerator.prototype, \"contactHardeningLightSizeUVRatio\", {\n /**\n * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.\n * Using a ratio helps keeping shape stability independently of the map size.\n *\n * It does not account for the light projection as it was having too much\n * instability during the light setup or during light position changes.\n *\n * Only valid if useContactHardeningShadow is true.\n */\n get: function () {\n return this._contactHardeningLightSizeUVRatio;\n },\n /**\n * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.\n * Using a ratio helps keeping shape stability independently of the map size.\n *\n * It does not account for the light projection as it was having too much\n * instability during the light setup or during light position changes.\n *\n * Only valid if useContactHardeningShadow is true.\n */\n set: function (contactHardeningLightSizeUVRatio) {\n this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.\n * 0 means strongest and 1 would means no shadow.\n * @returns the darkness.\n */\n ShadowGenerator.prototype.getDarkness = function () {\n return this._darkness;\n };\n /**\n * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.\n * @param darkness The darkness value 0 means strongest and 1 would means no shadow.\n * @returns the shadow generator allowing fluent coding.\n */\n ShadowGenerator.prototype.setDarkness = function (darkness) {\n if (darkness >= 1.0)\n this._darkness = 1.0;\n else if (darkness <= 0.0)\n this._darkness = 0.0;\n else\n this._darkness = darkness;\n return this;\n };\n /**\n * Sets the ability to have transparent shadow (boolean).\n * @param transparent True if transparent else False\n * @returns the shadow generator allowing fluent coding\n */\n ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {\n this._transparencyShadow = transparent;\n return this;\n };\n /**\n * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).\n * @returns The render target texture if present otherwise, null\n */\n ShadowGenerator.prototype.getShadowMap = function () {\n return this._shadowMap;\n };\n /**\n * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).\n * @returns The render target texture if the shadow map is present otherwise, null\n */\n ShadowGenerator.prototype.getShadowMapForRendering = function () {\n if (this._shadowMap2) {\n return this._shadowMap2;\n }\n return this._shadowMap;\n };\n /**\n * Helper function to add a mesh and its descendants to the list of shadow casters.\n * @param mesh Mesh to add\n * @param includeDescendants boolean indicating if the descendants should be added. Default to true\n * @returns the Shadow Generator itself\n */\n ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {\n if (includeDescendants === void 0) { includeDescendants = true; }\n var _a;\n if (!this._shadowMap) {\n return this;\n }\n if (!this._shadowMap.renderList) {\n this._shadowMap.renderList = [];\n }\n this._shadowMap.renderList.push(mesh);\n if (includeDescendants) {\n (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());\n }\n return this;\n };\n /**\n * Helper function to remove a mesh and its descendants from the list of shadow casters\n * @param mesh Mesh to remove\n * @param includeDescendants boolean indicating if the descendants should be removed. Default to true\n * @returns the Shadow Generator itself\n */\n ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {\n if (includeDescendants === void 0) { includeDescendants = true; }\n if (!this._shadowMap || !this._shadowMap.renderList) {\n return this;\n }\n var index = this._shadowMap.renderList.indexOf(mesh);\n if (index !== -1) {\n this._shadowMap.renderList.splice(index, 1);\n }\n if (includeDescendants) {\n for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {\n var child = _a[_i];\n this.removeShadowCaster(child);\n }\n }\n return this;\n };\n /**\n * Returns the associated light object.\n * @returns the light generating the shadow\n */\n ShadowGenerator.prototype.getLight = function () {\n return this._light;\n };\n ShadowGenerator.prototype._initializeGenerator = function () {\n this._light._markMeshesAsLightDirty();\n this._initializeShadowMap();\n };\n ShadowGenerator.prototype._initializeShadowMap = function () {\n var _this = this;\n // Render target\n var engine = this._scene.getEngine();\n if (engine.webGLVersion > 1) {\n this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + \"_shadowMap\", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);\n this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);\n }\n else {\n this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + \"_shadowMap\", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());\n }\n this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._shadowMap.anisotropicFilteringLevel = 1;\n this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n this._shadowMap.renderParticles = false;\n this._shadowMap.ignoreCameraViewport = true;\n // Record Face Index before render.\n this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {\n _this._currentFaceIndex = faceIndex;\n if (_this._filter === ShadowGenerator.FILTER_PCF) {\n engine.setColorWrite(false);\n }\n });\n // Custom render function.\n this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);\n // Blur if required afer render.\n this._shadowMap.onAfterUnbindObservable.add(function () {\n if (_this._filter === ShadowGenerator.FILTER_PCF) {\n engine.setColorWrite(true);\n }\n if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {\n return;\n }\n var shadowMap = _this.getShadowMapForRendering();\n if (shadowMap) {\n _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);\n }\n });\n // Clear according to the chosen filter.\n var clearZero = new BABYLON.Color4(0, 0, 0, 0);\n var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n this._shadowMap.onClearObservable.add(function (engine) {\n if (_this._filter === ShadowGenerator.FILTER_PCF) {\n engine.clear(clearOne, false, true, false);\n }\n else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {\n engine.clear(clearZero, true, true, false);\n }\n else {\n engine.clear(clearOne, true, true, false);\n }\n });\n };\n ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {\n var _this = this;\n var engine = this._scene.getEngine();\n var targetSize = this._mapSize / this.blurScale;\n if (!this.useKernelBlur || this.blurScale !== 1.0) {\n this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + \"_shadowMap2\", targetSize, this._scene, false, true, this._textureType);\n this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n }\n if (this.useKernelBlur) {\n this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + \"KernelBlurX\", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);\n this._kernelBlurXPostprocess.width = targetSize;\n this._kernelBlurXPostprocess.height = targetSize;\n this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {\n effect.setTexture(\"textureSampler\", _this._shadowMap);\n });\n this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + \"KernelBlurY\", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);\n this._kernelBlurXPostprocess.autoClear = false;\n this._kernelBlurYPostprocess.autoClear = false;\n if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {\n this._kernelBlurXPostprocess.packedFloat = true;\n this._kernelBlurYPostprocess.packedFloat = true;\n }\n this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];\n }\n else {\n this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + \"DepthBoxBlur\", \"depthBoxBlur\", [\"screenSize\", \"boxOffset\"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, \"#define OFFSET \" + this._blurBoxOffset, this._textureType);\n this._boxBlurPostprocess.onApplyObservable.add(function (effect) {\n effect.setFloat2(\"screenSize\", targetSize, targetSize);\n effect.setTexture(\"textureSampler\", _this._shadowMap);\n });\n this._boxBlurPostprocess.autoClear = false;\n this._blurPostProcesses = [this._boxBlurPostprocess];\n }\n };\n ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {\n var index;\n var engine = this._scene.getEngine();\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);\n }\n if (this._transparencyShadow) {\n for (index = 0; index < transparentSubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);\n }\n }\n };\n ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {\n var _this = this;\n var mesh = subMesh.getRenderingMesh();\n var scene = this._scene;\n var engine = scene.getEngine();\n var material = subMesh.getMaterial();\n if (!material) {\n return;\n }\n // Culling\n engine.setState(material.backFaceCulling);\n // Managing instances\n var batch = mesh._getInstancesRenderList(subMesh._id);\n if (batch.mustReturn) {\n return;\n }\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);\n if (this.isReady(subMesh, hardwareInstancedRendering)) {\n engine.enableEffect(this._effect);\n mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);\n this._effect.setFloat3(\"biasAndScale\", this.bias, this.normalBias, this.depthScale);\n this._effect.setMatrix(\"viewProjection\", this.getTransformMatrix());\n if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {\n this._effect.setVector3(\"lightData\", this._cachedDirection);\n }\n else {\n this._effect.setVector3(\"lightData\", this._cachedPosition);\n }\n if (scene.activeCamera) {\n this._effect.setFloat2(\"depthValues\", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));\n }\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n this._effect.setTexture(\"diffuseSampler\", alphaTexture);\n this._effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n this._effect.setMatrices(\"mBones\", mesh.skeleton.getTransformMatrices((mesh)));\n }\n // Morph targets\n BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);\n if (this.forceBackFacesOnly) {\n engine.setState(true, 0, false, true);\n }\n // Draw\n mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix(\"world\", world); });\n if (this.forceBackFacesOnly) {\n engine.setState(true, 0, false, false);\n }\n }\n else {\n // Need to reset refresh rate of the shadowMap\n if (this._shadowMap) {\n this._shadowMap.resetRefreshCounter();\n }\n }\n };\n ShadowGenerator.prototype._applyFilterValues = function () {\n if (!this._shadowMap) {\n return;\n }\n if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {\n this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);\n }\n else {\n this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n }\n };\n /**\n * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.\n * @param onCompiled Callback triggered at the and of the effects compilation\n * @param options Sets of optional options forcing the compilation with different modes\n */\n ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {\n var _this = this;\n var localOptions = __assign({ useInstances: false }, options);\n var shadowMap = this.getShadowMap();\n if (!shadowMap) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n var renderList = shadowMap.renderList;\n if (!renderList) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n var subMeshes = new Array();\n for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {\n var mesh = renderList_1[_i];\n subMeshes.push.apply(subMeshes, mesh.subMeshes);\n }\n if (subMeshes.length === 0) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n var currentIndex = 0;\n var checkReady = function () {\n if (!_this._scene || !_this._scene.getEngine()) {\n return;\n }\n while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {\n currentIndex++;\n if (currentIndex >= subMeshes.length) {\n if (onCompiled) {\n onCompiled(_this);\n }\n return;\n }\n }\n setTimeout(checkReady, 16);\n };\n checkReady();\n };\n /**\n * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.\n * @param options Sets of optional options forcing the compilation with different modes\n * @returns A promise that resolves when the compilation completes\n */\n ShadowGenerator.prototype.forceCompilationAsync = function (options) {\n var _this = this;\n return new Promise(function (resolve) {\n _this.forceCompilation(function () {\n resolve();\n }, options);\n });\n };\n /**\n * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).\n * @param subMesh The submesh we want to render in the shadow map\n * @param useInstances Defines wether will draw in the map using instances\n * @returns true if ready otherwise, false\n */\n ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {\n var defines = [];\n if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {\n defines.push(\"#define FLOAT\");\n }\n if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {\n defines.push(\"#define ESM\");\n }\n else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {\n defines.push(\"#define DEPTHTEXTURE\");\n }\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n var mesh = subMesh.getMesh();\n var material = subMesh.getMaterial();\n // Normal bias.\n if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n attribs.push(BABYLON.VertexBuffer.NormalKind);\n defines.push(\"#define NORMAL\");\n if (mesh.nonUniformScaling) {\n defines.push(\"#define NONUNIFORMSCALING\");\n }\n if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {\n defines.push(\"#define DIRECTIONINLIGHTDATA\");\n }\n }\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n if (alphaTexture.coordinatesIndex === 1) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton.bones.length + 1));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets \n var manager = mesh.morphTargetManager;\n var morphInfluencers = 0;\n if (manager) {\n if (manager.numInfluencers > 0) {\n defines.push(\"#define MORPHTARGETS\");\n morphInfluencers = manager.numInfluencers;\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + morphInfluencers);\n BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { \"NUM_MORPH_INFLUENCERS\": morphInfluencers });\n }\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n // Get correct effect\n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n this._effect = this._scene.getEngine().createEffect(\"shadowMap\", attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\", \"lightData\", \"depthValues\", \"biasAndScale\", \"morphTargetInfluences\"], [\"diffuseSampler\"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });\n }\n if (!this._effect.isReady()) {\n return false;\n }\n if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {\n if (!this._blurPostProcesses || !this._blurPostProcesses.length) {\n this._initializeBlurRTTAndPostProcesses();\n }\n }\n if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {\n return false;\n }\n if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {\n return false;\n }\n if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {\n return false;\n }\n return true;\n };\n /**\n * Prepare all the defines in a material relying on a shadow map at the specified light index.\n * @param defines Defines of the material we want to update\n * @param lightIndex Index of the light in the enabled light list of the material\n */\n ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {\n var scene = this._scene;\n var light = this._light;\n if (!scene.shadowsEnabled || !light.shadowEnabled) {\n return;\n }\n defines[\"SHADOW\" + lightIndex] = true;\n if (this.useContactHardeningShadow) {\n defines[\"SHADOWPCSS\" + lightIndex] = true;\n if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {\n defines[\"SHADOWLOWQUALITY\" + lightIndex] = true;\n }\n else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {\n defines[\"SHADOWMEDIUMQUALITY\" + lightIndex] = true;\n }\n // else default to high.\n }\n if (this.usePercentageCloserFiltering) {\n defines[\"SHADOWPCF\" + lightIndex] = true;\n if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {\n defines[\"SHADOWLOWQUALITY\" + lightIndex] = true;\n }\n else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {\n defines[\"SHADOWMEDIUMQUALITY\" + lightIndex] = true;\n }\n // else default to high.\n }\n else if (this.usePoissonSampling) {\n defines[\"SHADOWPOISSON\" + lightIndex] = true;\n }\n else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {\n defines[\"SHADOWESM\" + lightIndex] = true;\n }\n else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {\n defines[\"SHADOWCLOSEESM\" + lightIndex] = true;\n }\n if (light.needCube()) {\n defines[\"SHADOWCUBE\" + lightIndex] = true;\n }\n };\n /**\n * Binds the shadow related information inside of an effect (information like near, far, darkness...\n * defined in the generator but impacting the effect).\n * @param lightIndex Index of the light in the enabled light list of the material owning the effect\n * @param effect The effect we are binfing the information for\n */\n ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {\n var light = this._light;\n var scene = this._scene;\n if (!scene.shadowsEnabled || !light.shadowEnabled) {\n return;\n }\n var camera = scene.activeCamera;\n if (!camera) {\n return;\n }\n var shadowMap = this.getShadowMap();\n if (!shadowMap) {\n return;\n }\n if (!light.needCube()) {\n effect.setMatrix(\"lightMatrix\" + lightIndex, this.getTransformMatrix());\n }\n // Only PCF uses depth stencil texture.\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n effect.setDepthStencilTexture(\"shadowSampler\" + lightIndex, this.getShadowMapForRendering());\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);\n }\n else if (this._filter === ShadowGenerator.FILTER_PCSS) {\n effect.setDepthStencilTexture(\"shadowSampler\" + lightIndex, this.getShadowMapForRendering());\n effect.setTexture(\"depthSampler\" + lightIndex, this.getShadowMapForRendering());\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);\n }\n else {\n effect.setTexture(\"shadowSampler\" + lightIndex, this.getShadowMapForRendering());\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);\n }\n light._uniformBuffer.updateFloat2(\"depthValues\", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);\n };\n /**\n * Gets the transformation matrix used to project the meshes into the map from the light point of view.\n * (eq to shadow prjection matrix * light transform matrix)\n * @returns The transform matrix used to create the shadow map\n */\n ShadowGenerator.prototype.getTransformMatrix = function () {\n var scene = this._scene;\n if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {\n return this._transformMatrix;\n }\n this._currentRenderID = scene.getRenderId();\n this._currentFaceIndexCache = this._currentFaceIndex;\n var lightPosition = this._light.position;\n if (this._light.computeTransformedInformation()) {\n lightPosition = this._light.transformedPosition;\n }\n BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);\n if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {\n this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light\n }\n if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {\n this._cachedPosition.copyFrom(lightPosition);\n this._cachedDirection.copyFrom(this._lightDirection);\n BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);\n var shadowMap = this.getShadowMap();\n if (shadowMap) {\n var renderList = shadowMap.renderList;\n if (renderList) {\n this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);\n }\n }\n this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);\n }\n return this._transformMatrix;\n };\n /**\n * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between\n * Cube and 2D textures for instance.\n */\n ShadowGenerator.prototype.recreateShadowMap = function () {\n var shadowMap = this._shadowMap;\n if (!shadowMap) {\n return;\n }\n // Track render list.\n var renderList = shadowMap.renderList;\n // Clean up existing data.\n this._disposeRTTandPostProcesses();\n // Reinitializes.\n this._initializeGenerator();\n // Reaffect the filter to ensure a correct fallback if necessary.\n this.filter = this.filter;\n // Reaffect the filter.\n this._applyFilterValues();\n // Reaffect Render List.\n this._shadowMap.renderList = renderList;\n };\n ShadowGenerator.prototype._disposeBlurPostProcesses = function () {\n if (this._shadowMap2) {\n this._shadowMap2.dispose();\n this._shadowMap2 = null;\n }\n if (this._boxBlurPostprocess) {\n this._boxBlurPostprocess.dispose();\n this._boxBlurPostprocess = null;\n }\n if (this._kernelBlurXPostprocess) {\n this._kernelBlurXPostprocess.dispose();\n this._kernelBlurXPostprocess = null;\n }\n if (this._kernelBlurYPostprocess) {\n this._kernelBlurYPostprocess.dispose();\n this._kernelBlurYPostprocess = null;\n }\n this._blurPostProcesses = [];\n };\n ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {\n if (this._shadowMap) {\n this._shadowMap.dispose();\n this._shadowMap = null;\n }\n this._disposeBlurPostProcesses();\n };\n /**\n * Disposes the ShadowGenerator.\n * Returns nothing.\n */\n ShadowGenerator.prototype.dispose = function () {\n this._disposeRTTandPostProcesses();\n if (this._light) {\n this._light._shadowGenerator = null;\n this._light._markMeshesAsLightDirty();\n }\n };\n /**\n * Serializes the shadow generator setup to a json object.\n * @returns The serialized JSON object\n */\n ShadowGenerator.prototype.serialize = function () {\n var serializationObject = {};\n var shadowMap = this.getShadowMap();\n if (!shadowMap) {\n return serializationObject;\n }\n serializationObject.lightId = this._light.id;\n serializationObject.mapSize = shadowMap.getRenderSize();\n serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;\n serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;\n serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;\n serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;\n serializationObject.usePoissonSampling = this.usePoissonSampling;\n serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;\n serializationObject.depthScale = this.depthScale;\n serializationObject.darkness = this.getDarkness();\n serializationObject.blurBoxOffset = this.blurBoxOffset;\n serializationObject.blurKernel = this.blurKernel;\n serializationObject.blurScale = this.blurScale;\n serializationObject.useKernelBlur = this.useKernelBlur;\n serializationObject.transparencyShadow = this._transparencyShadow;\n serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;\n serializationObject.bias = this.bias;\n serializationObject.normalBias = this.normalBias;\n serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;\n serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;\n serializationObject.filteringQuality = this.filteringQuality;\n serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;\n serializationObject.renderList = [];\n if (shadowMap.renderList) {\n for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {\n var mesh = shadowMap.renderList[meshIndex];\n serializationObject.renderList.push(mesh.id);\n }\n }\n return serializationObject;\n };\n /**\n * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.\n * @param parsedShadowGenerator The JSON object to parse\n * @param scene The scene to create the shadow map for\n * @returns The parsed shadow generator\n */\n ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {\n var light = scene.getLightByID(parsedShadowGenerator.lightId);\n var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);\n var shadowMap = shadowGenerator.getShadowMap();\n for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {\n var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);\n meshes.forEach(function (mesh) {\n if (!shadowMap) {\n return;\n }\n if (!shadowMap.renderList) {\n shadowMap.renderList = [];\n }\n shadowMap.renderList.push(mesh);\n });\n }\n if (parsedShadowGenerator.usePoissonSampling) {\n shadowGenerator.usePoissonSampling = true;\n }\n else if (parsedShadowGenerator.useExponentialShadowMap) {\n shadowGenerator.useExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useBlurExponentialShadowMap) {\n shadowGenerator.useBlurExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useCloseExponentialShadowMap) {\n shadowGenerator.useCloseExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {\n shadowGenerator.useBlurCloseExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.usePercentageCloserFiltering) {\n shadowGenerator.usePercentageCloserFiltering = true;\n }\n else if (parsedShadowGenerator.useContactHardeningShadow) {\n shadowGenerator.useContactHardeningShadow = true;\n }\n if (parsedShadowGenerator.filteringQuality) {\n shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;\n }\n if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {\n shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;\n }\n // Backward compat\n else if (parsedShadowGenerator.useVarianceShadowMap) {\n shadowGenerator.useExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useBlurVarianceShadowMap) {\n shadowGenerator.useBlurExponentialShadowMap = true;\n }\n if (parsedShadowGenerator.depthScale) {\n shadowGenerator.depthScale = parsedShadowGenerator.depthScale;\n }\n if (parsedShadowGenerator.blurScale) {\n shadowGenerator.blurScale = parsedShadowGenerator.blurScale;\n }\n if (parsedShadowGenerator.blurBoxOffset) {\n shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;\n }\n if (parsedShadowGenerator.useKernelBlur) {\n shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;\n }\n if (parsedShadowGenerator.blurKernel) {\n shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;\n }\n if (parsedShadowGenerator.bias !== undefined) {\n shadowGenerator.bias = parsedShadowGenerator.bias;\n }\n if (parsedShadowGenerator.normalBias !== undefined) {\n shadowGenerator.normalBias = parsedShadowGenerator.normalBias;\n }\n if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {\n shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;\n }\n if (parsedShadowGenerator.darkness) {\n shadowGenerator.setDarkness(parsedShadowGenerator.darkness);\n }\n if (parsedShadowGenerator.transparencyShadow) {\n shadowGenerator.setTransparencyShadow(true);\n }\n shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;\n return shadowGenerator;\n };\n /**\n * Shadow generator mode None: no filtering applied.\n */\n ShadowGenerator.FILTER_NONE = 0;\n /**\n * Shadow generator mode ESM: Exponential Shadow Mapping.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\n ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;\n /**\n * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.\n * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)\n */\n ShadowGenerator.FILTER_POISSONSAMPLING = 2;\n /**\n * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\n ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;\n /**\n * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing\n * edge artifacts on steep falloff.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\n ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;\n /**\n * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing\n * edge artifacts on steep falloff.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\n ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;\n /**\n * Shadow generator mode PCF: Percentage Closer Filtering\n * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1\n * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)\n */\n ShadowGenerator.FILTER_PCF = 6;\n /**\n * Shadow generator mode PCSS: Percentage Closering Soft Shadow.\n * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1\n * Contact Hardening\n */\n ShadowGenerator.FILTER_PCSS = 7;\n /**\n * Reserved for PCF and PCSS\n * Highest Quality.\n *\n * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.\n *\n * Execute PCSS with 32 taps blocker search and 64 taps PCF.\n */\n ShadowGenerator.QUALITY_HIGH = 0;\n /**\n * Reserved for PCF and PCSS\n * Good tradeoff for quality/perf cross devices\n *\n * Execute PCF on a 3*3 kernel.\n *\n * Execute PCSS with 16 taps blocker search and 32 taps PCF.\n */\n ShadowGenerator.QUALITY_MEDIUM = 1;\n /**\n * Reserved for PCF and PCSS\n * The lowest quality but the fastest.\n *\n * Execute PCF on a 1*1 kernel.\n *\n * Execute PCSS with 16 taps blocker search and 16 taps PCF.\n */\n ShadowGenerator.QUALITY_LOW = 2;\n return ShadowGenerator;\n }());\n BABYLON.ShadowGenerator = ShadowGenerator;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.shadowGenerator.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var DefaultLoadingScreen = /** @class */ (function () {\n function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {\n if (_loadingText === void 0) { _loadingText = \"\"; }\n if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = \"black\"; }\n var _this = this;\n this._renderingCanvas = _renderingCanvas;\n this._loadingText = _loadingText;\n this._loadingDivBackgroundColor = _loadingDivBackgroundColor;\n // Resize\n this._resizeLoadingUI = function () {\n var canvasRect = _this._renderingCanvas.getBoundingClientRect();\n var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;\n if (!_this._loadingDiv) {\n return;\n }\n _this._loadingDiv.style.position = (canvasPositioning === \"fixed\") ? \"fixed\" : \"absolute\";\n _this._loadingDiv.style.left = canvasRect.left + \"px\";\n _this._loadingDiv.style.top = canvasRect.top + \"px\";\n _this._loadingDiv.style.width = canvasRect.width + \"px\";\n _this._loadingDiv.style.height = canvasRect.height + \"px\";\n };\n }\n DefaultLoadingScreen.prototype.displayLoadingUI = function () {\n if (this._loadingDiv) {\n // Do not add a loading screen if there is already one \n return;\n }\n this._loadingDiv = document.createElement(\"div\");\n this._loadingDiv.id = \"babylonjsLoadingDiv\";\n this._loadingDiv.style.opacity = \"0\";\n this._loadingDiv.style.transition = \"opacity 1.5s ease\";\n this._loadingDiv.style.pointerEvents = \"none\";\n // Loading text\n this._loadingTextDiv = document.createElement(\"div\");\n this._loadingTextDiv.style.position = \"absolute\";\n this._loadingTextDiv.style.left = \"0\";\n this._loadingTextDiv.style.top = \"50%\";\n this._loadingTextDiv.style.marginTop = \"80px\";\n this._loadingTextDiv.style.width = \"100%\";\n this._loadingTextDiv.style.height = \"20px\";\n this._loadingTextDiv.style.fontFamily = \"Arial\";\n this._loadingTextDiv.style.fontSize = \"14px\";\n this._loadingTextDiv.style.color = \"white\";\n this._loadingTextDiv.style.textAlign = \"center\";\n this._loadingTextDiv.innerHTML = \"Loading\";\n this._loadingDiv.appendChild(this._loadingTextDiv);\n //set the predefined text\n this._loadingTextDiv.innerHTML = this._loadingText;\n // Generating keyframes\n var style = document.createElement('style');\n style.type = 'text/css';\n var keyFrames = \"@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\\n 100% { -webkit-transform: rotate(360deg);}\\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\\n 100% { transform: rotate(360deg);}\\n }\";\n style.innerHTML = keyFrames;\n document.getElementsByTagName('head')[0].appendChild(style);\n // Loading img\n var imgBack = new Image();\n imgBack.src = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC\";\n imgBack.style.position = \"absolute\";\n imgBack.style.left = \"50%\";\n imgBack.style.top = \"50%\";\n imgBack.style.marginLeft = \"-60px\";\n imgBack.style.marginTop = \"-60px\";\n imgBack.style.animation = \"spin1 2s infinite ease-in-out\";\n imgBack.style.webkitAnimation = \"spin1 2s infinite ease-in-out\";\n imgBack.style.transformOrigin = \"50% 50%\";\n imgBack.style.webkitTransformOrigin = \"50% 50%\";\n this._loadingDiv.appendChild(imgBack);\n this._resizeLoadingUI();\n window.addEventListener(\"resize\", this._resizeLoadingUI);\n this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;\n document.body.appendChild(this._loadingDiv);\n this._loadingDiv.style.opacity = \"1\";\n };\n DefaultLoadingScreen.prototype.hideLoadingUI = function () {\n var _this = this;\n if (!this._loadingDiv) {\n return;\n }\n var onTransitionEnd = function () {\n if (!_this._loadingDiv) {\n return;\n }\n document.body.removeChild(_this._loadingDiv);\n window.removeEventListener(\"resize\", _this._resizeLoadingUI);\n _this._loadingDiv = null;\n };\n this._loadingDiv.style.opacity = \"0\";\n this._loadingDiv.addEventListener(\"transitionend\", onTransitionEnd);\n };\n Object.defineProperty(DefaultLoadingScreen.prototype, \"loadingUIText\", {\n set: function (text) {\n this._loadingText = text;\n if (this._loadingTextDiv) {\n this._loadingTextDiv.innerHTML = this._loadingText;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultLoadingScreen.prototype, \"loadingUIBackgroundColor\", {\n get: function () {\n return this._loadingDivBackgroundColor;\n },\n set: function (color) {\n this._loadingDivBackgroundColor = color;\n if (!this._loadingDiv) {\n return;\n }\n this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;\n },\n enumerable: true,\n configurable: true\n });\n return DefaultLoadingScreen;\n }());\n BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.loadingScreen.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var SceneLoaderProgressEvent = /** @class */ (function () {\n function SceneLoaderProgressEvent(lengthComputable, loaded, total) {\n this.lengthComputable = lengthComputable;\n this.loaded = loaded;\n this.total = total;\n }\n SceneLoaderProgressEvent.FromProgressEvent = function (event) {\n return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);\n };\n return SceneLoaderProgressEvent;\n }());\n BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;\n var SceneLoader = /** @class */ (function () {\n function SceneLoader() {\n }\n Object.defineProperty(SceneLoader, \"NO_LOGGING\", {\n get: function () {\n return 0;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"MINIMAL_LOGGING\", {\n get: function () {\n return 1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"SUMMARY_LOGGING\", {\n get: function () {\n return 2;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"DETAILED_LOGGING\", {\n get: function () {\n return 3;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"ForceFullSceneLoadingForIncremental\", {\n get: function () {\n return SceneLoader._ForceFullSceneLoadingForIncremental;\n },\n set: function (value) {\n SceneLoader._ForceFullSceneLoadingForIncremental = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"ShowLoadingScreen\", {\n get: function () {\n return SceneLoader._ShowLoadingScreen;\n },\n set: function (value) {\n SceneLoader._ShowLoadingScreen = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"loggingLevel\", {\n get: function () {\n return SceneLoader._loggingLevel;\n },\n set: function (value) {\n SceneLoader._loggingLevel = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneLoader, \"CleanBoneMatrixWeights\", {\n get: function () {\n return SceneLoader._CleanBoneMatrixWeights;\n },\n set: function (value) {\n SceneLoader._CleanBoneMatrixWeights = value;\n },\n enumerable: true,\n configurable: true\n });\n SceneLoader._getDefaultPlugin = function () {\n return SceneLoader._registeredPlugins[\".babylon\"];\n };\n SceneLoader._getPluginForExtension = function (extension) {\n var registeredPlugin = SceneLoader._registeredPlugins[extension];\n if (registeredPlugin) {\n return registeredPlugin;\n }\n BABYLON.Tools.Warn(\"Unable to find a plugin to load \" + extension + \" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type\");\n return SceneLoader._getDefaultPlugin();\n };\n SceneLoader._getPluginForDirectLoad = function (data) {\n for (var extension in SceneLoader._registeredPlugins) {\n var plugin = SceneLoader._registeredPlugins[extension].plugin;\n if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {\n return SceneLoader._registeredPlugins[extension];\n }\n }\n return SceneLoader._getDefaultPlugin();\n };\n SceneLoader._getPluginForFilename = function (sceneFilename) {\n if (sceneFilename.name) {\n sceneFilename = sceneFilename.name;\n }\n var queryStringPosition = sceneFilename.indexOf(\"?\");\n if (queryStringPosition !== -1) {\n sceneFilename = sceneFilename.substring(0, queryStringPosition);\n }\n var dotPosition = sceneFilename.lastIndexOf(\".\");\n var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();\n return SceneLoader._getPluginForExtension(extension);\n };\n // use babylon file loader directly if sceneFilename is prefixed with \"data:\"\n SceneLoader._getDirectLoad = function (sceneFilename) {\n if (sceneFilename.substr && sceneFilename.substr(0, 5) === \"data:\") {\n return sceneFilename.substr(5);\n }\n return null;\n };\n SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {\n var directLoad = SceneLoader._getDirectLoad(sceneFilename);\n var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));\n var plugin;\n if (registeredPlugin.plugin.createPlugin) {\n plugin = registeredPlugin.plugin.createPlugin();\n }\n else {\n plugin = registeredPlugin.plugin;\n }\n var useArrayBuffer = registeredPlugin.isBinary;\n var database;\n SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);\n var dataCallback = function (data, responseURL) {\n if (scene.isDisposed) {\n onError(\"Scene has been disposed\");\n return;\n }\n scene.database = database;\n onSuccess(plugin, data, responseURL);\n };\n var request = null;\n var pluginDisposed = false;\n var onDisposeObservable = plugin.onDisposeObservable;\n if (onDisposeObservable) {\n onDisposeObservable.add(function () {\n pluginDisposed = true;\n if (request) {\n request.abort();\n request = null;\n }\n onDispose();\n });\n }\n var manifestChecked = function () {\n if (pluginDisposed) {\n return;\n }\n var url = rootUrl + sceneFilename;\n request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {\n onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));\n } : undefined, database, useArrayBuffer, function (request, exception) {\n onError(\"Failed to load scene.\" + (exception ? \"\" : \" \" + exception.message), exception);\n });\n };\n if (directLoad) {\n dataCallback(directLoad);\n return plugin;\n }\n if (rootUrl.indexOf(\"file:\") === -1) {\n var engine = scene.getEngine();\n var canUseOfflineSupport = engine.enableOfflineSupport;\n if (canUseOfflineSupport) {\n // Also check for exceptions\n var exceptionFound = false;\n for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {\n var regex = _a[_i];\n if (regex.test(rootUrl + sceneFilename)) {\n exceptionFound = true;\n break;\n }\n }\n canUseOfflineSupport = !exceptionFound;\n }\n if (canUseOfflineSupport) {\n // Checking if a manifest file has been set for this scene and if offline mode has been requested\n database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);\n }\n else {\n manifestChecked();\n }\n }\n // Loading file from disk via input file or drag'n'drop\n else {\n var fileOrString = sceneFilename;\n if (fileOrString.name) { // File\n request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);\n }\n else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {\n request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);\n }\n else {\n onError(\"Unable to find file named \" + sceneFilename);\n }\n }\n return plugin;\n };\n // Public functions\n SceneLoader.GetPluginForExtension = function (extension) {\n return SceneLoader._getPluginForExtension(extension).plugin;\n };\n SceneLoader.IsPluginForExtensionAvailable = function (extension) {\n return !!SceneLoader._registeredPlugins[extension];\n };\n SceneLoader.RegisterPlugin = function (plugin) {\n if (typeof plugin.extensions === \"string\") {\n var extension = plugin.extensions;\n SceneLoader._registeredPlugins[extension.toLowerCase()] = {\n plugin: plugin,\n isBinary: false\n };\n }\n else {\n var extensions = plugin.extensions;\n Object.keys(extensions).forEach(function (extension) {\n SceneLoader._registeredPlugins[extension.toLowerCase()] = {\n plugin: plugin,\n isBinary: extensions[extension].isBinary\n };\n });\n }\n };\n /**\n * Import meshes into a scene\n * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene the instance of BABYLON.Scene to append to\n * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {\n if (sceneFilename === void 0) { sceneFilename = \"\"; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (onSuccess === void 0) { onSuccess = null; }\n if (onProgress === void 0) { onProgress = null; }\n if (onError === void 0) { onError = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n if (!scene) {\n BABYLON.Tools.Error(\"No scene available to import mesh to\");\n return null;\n }\n if (!sceneFilename) {\n sceneFilename = BABYLON.Tools.GetFilename(rootUrl);\n rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);\n }\n if (sceneFilename.substr && sceneFilename.substr(0, 1) === \"/\") {\n BABYLON.Tools.Error(\"Wrong sceneFilename parameter\");\n return null;\n }\n var loadingToken = {};\n scene._addPendingData(loadingToken);\n var disposeHandler = function () {\n scene._removePendingData(loadingToken);\n };\n var errorHandler = function (message, exception) {\n var errorMessage = \"Unable to import meshes from \" + rootUrl + sceneFilename + \": \" + message;\n if (onError) {\n onError(scene, errorMessage, exception);\n }\n else {\n BABYLON.Tools.Error(errorMessage);\n // should the exception be thrown?\n }\n disposeHandler();\n };\n var progressHandler = onProgress ? function (event) {\n try {\n onProgress(event);\n }\n catch (e) {\n errorHandler(\"Error in onProgress callback\", e);\n }\n } : undefined;\n var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {\n scene.importedMeshesFiles.push(rootUrl + sceneFilename);\n if (onSuccess) {\n try {\n onSuccess(meshes, particleSystems, skeletons, animationGroups);\n }\n catch (e) {\n errorHandler(\"Error in onSuccess callback\", e);\n }\n }\n scene._removePendingData(loadingToken);\n };\n return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {\n if (plugin.rewriteRootURL) {\n rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);\n }\n if (sceneFilename === \"\") {\n if (sceneFilename === \"\") {\n rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);\n }\n }\n if (plugin.importMesh) {\n var syncedPlugin = plugin;\n var meshes = new Array();\n var particleSystems = new Array();\n var skeletons = new Array();\n if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {\n return;\n }\n scene.loadingPluginName = plugin.name;\n successHandler(meshes, particleSystems, skeletons, []);\n }\n else {\n var asyncedPlugin = plugin;\n asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {\n scene.loadingPluginName = plugin.name;\n successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);\n }).catch(function (error) {\n errorHandler(error.message, error);\n });\n }\n }, progressHandler, errorHandler, disposeHandler, pluginExtension);\n };\n /**\n * Import meshes into a scene\n * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene the instance of BABYLON.Scene to append to\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups\n */\n SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {\n if (sceneFilename === void 0) { sceneFilename = \"\"; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (onProgress === void 0) { onProgress = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n return new Promise(function (resolve, reject) {\n SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {\n resolve({\n meshes: meshes,\n particleSystems: particleSystems,\n skeletons: skeletons,\n animationGroups: animationGroups\n });\n }, onProgress, function (scene, message, exception) {\n reject(exception || new Error(message));\n }, pluginExtension);\n });\n };\n /**\n * Load a scene\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param engine is the instance of BABYLON.Engine to use to create the scene\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {\n if (onSuccess === void 0) { onSuccess = null; }\n if (onProgress === void 0) { onProgress = null; }\n if (onError === void 0) { onError = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);\n };\n /**\n * Load a scene\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param engine is the instance of BABYLON.Engine to use to create the scene\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded scene\n */\n SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {\n if (onProgress === void 0) { onProgress = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n return new Promise(function (resolve, reject) {\n SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {\n resolve(scene);\n }, onProgress, function (scene, message, exception) {\n reject(exception || new Error(message));\n }, pluginExtension);\n });\n };\n /**\n * Append a scene\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {\n if (sceneFilename === void 0) { sceneFilename = \"\"; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (onSuccess === void 0) { onSuccess = null; }\n if (onProgress === void 0) { onProgress = null; }\n if (onError === void 0) { onError = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n if (!scene) {\n BABYLON.Tools.Error(\"No scene available to append to\");\n return null;\n }\n if (!sceneFilename) {\n sceneFilename = BABYLON.Tools.GetFilename(rootUrl);\n rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);\n }\n if (sceneFilename.substr && sceneFilename.substr(0, 1) === \"/\") {\n BABYLON.Tools.Error(\"Wrong sceneFilename parameter\");\n return null;\n }\n if (SceneLoader.ShowLoadingScreen) {\n scene.getEngine().displayLoadingUI();\n }\n var loadingToken = {};\n scene._addPendingData(loadingToken);\n var disposeHandler = function () {\n scene._removePendingData(loadingToken);\n scene.getEngine().hideLoadingUI();\n };\n var errorHandler = function (message, exception) {\n var errorMessage = \"Unable to load from \" + rootUrl + sceneFilename + (message ? \": \" + message : \"\");\n if (onError) {\n onError(scene, errorMessage, exception);\n }\n else {\n BABYLON.Tools.Error(errorMessage);\n // should the exception be thrown?\n }\n disposeHandler();\n };\n var progressHandler = onProgress ? function (event) {\n try {\n onProgress(event);\n }\n catch (e) {\n errorHandler(\"Error in onProgress callback\", e);\n }\n } : undefined;\n var successHandler = function () {\n if (onSuccess) {\n try {\n onSuccess(scene);\n }\n catch (e) {\n errorHandler(\"Error in onSuccess callback\", e);\n }\n }\n scene._removePendingData(loadingToken);\n };\n return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {\n if (sceneFilename === \"\") {\n rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);\n }\n if (plugin.load) {\n var syncedPlugin = plugin;\n if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {\n return;\n }\n scene.loadingPluginName = plugin.name;\n successHandler();\n }\n else {\n var asyncedPlugin = plugin;\n asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {\n scene.loadingPluginName = plugin.name;\n successHandler();\n }).catch(function (error) {\n errorHandler(error.message, error);\n });\n }\n if (SceneLoader.ShowLoadingScreen) {\n scene.executeWhenReady(function () {\n scene.getEngine().hideLoadingUI();\n });\n }\n }, progressHandler, errorHandler, disposeHandler, pluginExtension);\n };\n /**\n * Append a scene\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The given scene\n */\n SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {\n if (sceneFilename === void 0) { sceneFilename = \"\"; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (onProgress === void 0) { onProgress = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n return new Promise(function (resolve, reject) {\n SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {\n resolve(scene);\n }, onProgress, function (scene, message, exception) {\n reject(exception || new Error(message));\n }, pluginExtension);\n });\n };\n /**\n * Load a scene into an asset container\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {\n if (sceneFilename === void 0) { sceneFilename = \"\"; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (onSuccess === void 0) { onSuccess = null; }\n if (onProgress === void 0) { onProgress = null; }\n if (onError === void 0) { onError = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n if (!scene) {\n BABYLON.Tools.Error(\"No scene available to load asset container to\");\n return null;\n }\n if (!sceneFilename) {\n sceneFilename = BABYLON.Tools.GetFilename(rootUrl);\n rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);\n }\n if (sceneFilename.substr && sceneFilename.substr(0, 1) === \"/\") {\n BABYLON.Tools.Error(\"Wrong sceneFilename parameter\");\n return null;\n }\n var loadingToken = {};\n scene._addPendingData(loadingToken);\n var disposeHandler = function () {\n scene._removePendingData(loadingToken);\n };\n var errorHandler = function (message, exception) {\n var errorMessage = \"Unable to load assets from \" + rootUrl + sceneFilename + (message ? \": \" + message : \"\");\n if (onError) {\n onError(scene, errorMessage, exception);\n }\n else {\n BABYLON.Tools.Error(errorMessage);\n // should the exception be thrown?\n }\n disposeHandler();\n };\n var progressHandler = onProgress ? function (event) {\n try {\n onProgress(event);\n }\n catch (e) {\n errorHandler(\"Error in onProgress callback\", e);\n }\n } : undefined;\n var successHandler = function (assets) {\n if (onSuccess) {\n try {\n onSuccess(assets);\n }\n catch (e) {\n errorHandler(\"Error in onSuccess callback\", e);\n }\n }\n scene._removePendingData(loadingToken);\n };\n return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {\n if (plugin.loadAssetContainer) {\n var syncedPlugin = plugin;\n var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);\n if (!assetContainer) {\n return;\n }\n scene.loadingPluginName = plugin.name;\n successHandler(assetContainer);\n }\n else if (plugin.loadAssetContainerAsync) {\n var asyncedPlugin = plugin;\n asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {\n scene.loadingPluginName = plugin.name;\n successHandler(assetContainer);\n }).catch(function (error) {\n errorHandler(error.message, error);\n });\n }\n else {\n errorHandler(\"LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.\");\n }\n if (SceneLoader.ShowLoadingScreen) {\n scene.executeWhenReady(function () {\n scene.getEngine().hideLoadingUI();\n });\n }\n }, progressHandler, errorHandler, disposeHandler, pluginExtension);\n };\n /**\n * Load a scene into an asset container\n * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file. can start with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded asset container\n */\n SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {\n if (sceneFilename === void 0) { sceneFilename = \"\"; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (onProgress === void 0) { onProgress = null; }\n if (pluginExtension === void 0) { pluginExtension = null; }\n return new Promise(function (resolve, reject) {\n SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {\n resolve(assetContainer);\n }, onProgress, function (scene, message, exception) {\n reject(exception || new Error(message));\n }, pluginExtension);\n });\n };\n // Flags\n SceneLoader._ForceFullSceneLoadingForIncremental = false;\n SceneLoader._ShowLoadingScreen = true;\n SceneLoader._CleanBoneMatrixWeights = false;\n SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;\n // Members\n SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();\n SceneLoader._registeredPlugins = {};\n return SceneLoader;\n }());\n BABYLON.SceneLoader = SceneLoader;\n ;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sceneLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var parseMaterialById = function (id, parsedData, scene, rootUrl) {\n for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {\n var parsedMaterial = parsedData.materials[index];\n if (parsedMaterial.id === id) {\n return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);\n }\n }\n return null;\n };\n var isDescendantOf = function (mesh, names, hierarchyIds) {\n for (var i in names) {\n if (mesh.name === names[i]) {\n hierarchyIds.push(mesh.id);\n return true;\n }\n }\n if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {\n hierarchyIds.push(mesh.id);\n return true;\n }\n return false;\n };\n var logOperation = function (operation, producer) {\n return operation + \" of \" + (producer ? producer.file + \" from \" + producer.name + \" version: \" + producer.version + \", exporter version: \" + producer.exporter_version : \"unknown\");\n };\n var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {\n if (addToScene === void 0) { addToScene = false; }\n var container = new BABYLON.AssetContainer(scene);\n // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details\n // when SceneLoader.debugLogging = true (default), or exception encountered.\n // Everything stored in var log instead of writing separate lines to support only writing in exception,\n // and avoid problems with multiple concurrent .babylon loads.\n var log = \"importScene has failed JSON parse\";\n try {\n var parsedData = JSON.parse(data);\n log = \"\";\n var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;\n var index;\n var cache;\n // Lights\n if (parsedData.lights !== undefined && parsedData.lights !== null) {\n for (index = 0, cache = parsedData.lights.length; index < cache; index++) {\n var parsedLight = parsedData.lights[index];\n var light = BABYLON.Light.Parse(parsedLight, scene);\n if (light) {\n container.lights.push(light);\n log += (index === 0 ? \"\\n\\tLights:\" : \"\");\n log += \"\\n\\t\\t\" + light.toString(fullDetails);\n }\n }\n }\n // Animations\n if (parsedData.animations !== undefined && parsedData.animations !== null) {\n for (index = 0, cache = parsedData.animations.length; index < cache; index++) {\n var parsedAnimation = parsedData.animations[index];\n var animation = BABYLON.Animation.Parse(parsedAnimation);\n scene.animations.push(animation);\n container.animations.push(animation);\n log += (index === 0 ? \"\\n\\tAnimations:\" : \"\");\n log += \"\\n\\t\\t\" + animation.toString(fullDetails);\n }\n }\n // Materials\n if (parsedData.materials !== undefined && parsedData.materials !== null) {\n for (index = 0, cache = parsedData.materials.length; index < cache; index++) {\n var parsedMaterial = parsedData.materials[index];\n var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);\n container.materials.push(mat);\n log += (index === 0 ? \"\\n\\tMaterials:\" : \"\");\n log += \"\\n\\t\\t\" + mat.toString(fullDetails);\n }\n }\n if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {\n for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {\n var parsedMultiMaterial = parsedData.multiMaterials[index];\n var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);\n container.multiMaterials.push(mmat);\n log += (index === 0 ? \"\\n\\tMultiMaterials:\" : \"\");\n log += \"\\n\\t\\t\" + mmat.toString(fullDetails);\n }\n }\n // Morph targets\n if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {\n for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {\n var managerData = _a[_i];\n container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));\n }\n }\n // Skeletons\n if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {\n for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {\n var parsedSkeleton = parsedData.skeletons[index];\n var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);\n container.skeletons.push(skeleton);\n log += (index === 0 ? \"\\n\\tSkeletons:\" : \"\");\n log += \"\\n\\t\\t\" + skeleton.toString(fullDetails);\n }\n }\n // Geometries\n var geometries = parsedData.geometries;\n if (geometries !== undefined && geometries !== null) {\n var addedGeometry = new Array();\n // Boxes\n var boxes = geometries.boxes;\n if (boxes !== undefined && boxes !== null) {\n for (index = 0, cache = boxes.length; index < cache; index++) {\n var parsedBox = boxes[index];\n addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));\n }\n }\n // Spheres\n var spheres = geometries.spheres;\n if (spheres !== undefined && spheres !== null) {\n for (index = 0, cache = spheres.length; index < cache; index++) {\n var parsedSphere = spheres[index];\n addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));\n }\n }\n // Cylinders\n var cylinders = geometries.cylinders;\n if (cylinders !== undefined && cylinders !== null) {\n for (index = 0, cache = cylinders.length; index < cache; index++) {\n var parsedCylinder = cylinders[index];\n addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));\n }\n }\n // Toruses\n var toruses = geometries.toruses;\n if (toruses !== undefined && toruses !== null) {\n for (index = 0, cache = toruses.length; index < cache; index++) {\n var parsedTorus = toruses[index];\n addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));\n }\n }\n // Grounds\n var grounds = geometries.grounds;\n if (grounds !== undefined && grounds !== null) {\n for (index = 0, cache = grounds.length; index < cache; index++) {\n var parsedGround = grounds[index];\n addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));\n }\n }\n // Planes\n var planes = geometries.planes;\n if (planes !== undefined && planes !== null) {\n for (index = 0, cache = planes.length; index < cache; index++) {\n var parsedPlane = planes[index];\n addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));\n }\n }\n // TorusKnots\n var torusKnots = geometries.torusKnots;\n if (torusKnots !== undefined && torusKnots !== null) {\n for (index = 0, cache = torusKnots.length; index < cache; index++) {\n var parsedTorusKnot = torusKnots[index];\n addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));\n }\n }\n // VertexData\n var vertexData = geometries.vertexData;\n if (vertexData !== undefined && vertexData !== null) {\n for (index = 0, cache = vertexData.length; index < cache; index++) {\n var parsedVertexData = vertexData[index];\n addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));\n }\n }\n addedGeometry.forEach(function (g) {\n if (g) {\n container.geometries.push(g);\n }\n });\n }\n // Transform nodes\n if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {\n for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {\n var parsedTransformNode = parsedData.transformNodes[index];\n var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);\n container.transformNodes.push(node);\n }\n }\n // Meshes\n if (parsedData.meshes !== undefined && parsedData.meshes !== null) {\n for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {\n var parsedMesh = parsedData.meshes[index];\n var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);\n container.meshes.push(mesh);\n log += (index === 0 ? \"\\n\\tMeshes:\" : \"\");\n log += \"\\n\\t\\t\" + mesh.toString(fullDetails);\n }\n }\n // Cameras\n if (parsedData.cameras !== undefined && parsedData.cameras !== null) {\n for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {\n var parsedCamera = parsedData.cameras[index];\n var camera = BABYLON.Camera.Parse(parsedCamera, scene);\n container.cameras.push(camera);\n log += (index === 0 ? \"\\n\\tCameras:\" : \"\");\n log += \"\\n\\t\\t\" + camera.toString(fullDetails);\n }\n }\n // Browsing all the graph to connect the dots\n for (index = 0, cache = scene.cameras.length; index < cache; index++) {\n var camera = scene.cameras[index];\n if (camera._waitingParentId) {\n camera.parent = scene.getLastEntryByID(camera._waitingParentId);\n camera._waitingParentId = null;\n }\n }\n for (index = 0, cache = scene.lights.length; index < cache; index++) {\n var light_1 = scene.lights[index];\n if (light_1 && light_1._waitingParentId) {\n light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);\n light_1._waitingParentId = null;\n }\n }\n // Sounds\n // TODO: add sound\n var loadedSounds = [];\n var loadedSound;\n if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {\n for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {\n var parsedSound = parsedData.sounds[index];\n if (BABYLON.Engine.audioEngine.canUseWebAudio) {\n if (!parsedSound.url)\n parsedSound.url = parsedSound.name;\n if (!loadedSounds[parsedSound.url]) {\n loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);\n loadedSounds[parsedSound.url] = loadedSound;\n container.sounds.push(loadedSound);\n }\n else {\n container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));\n }\n }\n else {\n container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));\n }\n }\n }\n loadedSounds = [];\n // Connect parents & children and parse actions\n for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {\n var transformNode = scene.transformNodes[index];\n if (transformNode._waitingParentId) {\n transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);\n transformNode._waitingParentId = null;\n }\n }\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n var mesh = scene.meshes[index];\n if (mesh._waitingParentId) {\n mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);\n mesh._waitingParentId = null;\n }\n if (mesh._waitingActions) {\n BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);\n mesh._waitingActions = null;\n }\n }\n // freeze world matrix application\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n var currentMesh = scene.meshes[index];\n if (currentMesh._waitingFreezeWorldMatrix) {\n currentMesh.freezeWorldMatrix();\n currentMesh._waitingFreezeWorldMatrix = null;\n }\n else {\n currentMesh.computeWorldMatrix(true);\n }\n }\n // Shadows\n if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {\n for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {\n var parsedShadowGenerator = parsedData.shadowGenerators[index];\n BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);\n // SG would be available on their associated lights\n }\n }\n // Lights exclusions / inclusions\n for (index = 0, cache = scene.lights.length; index < cache; index++) {\n var light_2 = scene.lights[index];\n // Excluded check\n if (light_2._excludedMeshesIds.length > 0) {\n for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {\n var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);\n if (excludedMesh) {\n light_2.excludedMeshes.push(excludedMesh);\n }\n }\n light_2._excludedMeshesIds = [];\n }\n // Included check\n if (light_2._includedOnlyMeshesIds.length > 0) {\n for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {\n var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);\n if (includedOnlyMesh) {\n light_2.includedOnlyMeshes.push(includedOnlyMesh);\n }\n }\n light_2._includedOnlyMeshesIds = [];\n }\n }\n BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);\n // Actions (scene)\n if (parsedData.actions !== undefined && parsedData.actions !== null) {\n BABYLON.ActionManager.Parse(parsedData.actions, null, scene);\n }\n if (!addToScene) {\n container.removeAllFromScene();\n }\n }\n catch (err) {\n var msg = logOperation(\"loadAssts\", parsedData ? parsedData.producer : \"Unknown\") + log;\n if (onError) {\n onError(msg, err);\n }\n else {\n BABYLON.Tools.Log(msg);\n throw err;\n }\n }\n finally {\n if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {\n BABYLON.Tools.Log(logOperation(\"loadAssts\", parsedData ? parsedData.producer : \"Unknown\") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : \"\"));\n }\n }\n return container;\n };\n BABYLON.SceneLoader.RegisterPlugin({\n name: \"babylon.js\",\n extensions: \".babylon\",\n canDirectLoad: function (data) {\n if (data.indexOf(\"babylon\") !== -1) { // We consider that the producer string is filled\n return true;\n }\n return false;\n },\n importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {\n // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details\n // when SceneLoader.debugLogging = true (default), or exception encountered.\n // Everything stored in var log instead of writing separate lines to support only writing in exception,\n // and avoid problems with multiple concurrent .babylon loads.\n var log = \"importMesh has failed JSON parse\";\n try {\n var parsedData = JSON.parse(data);\n log = \"\";\n var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;\n if (!meshesNames) {\n meshesNames = null;\n }\n else if (!Array.isArray(meshesNames)) {\n meshesNames = [meshesNames];\n }\n var hierarchyIds = new Array();\n if (parsedData.meshes !== undefined && parsedData.meshes !== null) {\n var loadedSkeletonsIds = [];\n var loadedMaterialsIds = [];\n var index;\n var cache;\n for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {\n var parsedMesh = parsedData.meshes[index];\n if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {\n if (meshesNames !== null) {\n // Remove found mesh name from list.\n delete meshesNames[meshesNames.indexOf(parsedMesh.name)];\n }\n //Geometry?\n if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {\n //does the file contain geometries?\n if (parsedData.geometries !== undefined && parsedData.geometries !== null) {\n //find the correct geometry and add it to the scene\n var found = false;\n [\"boxes\", \"spheres\", \"cylinders\", \"toruses\", \"grounds\", \"planes\", \"torusKnots\", \"vertexData\"].forEach(function (geometryType) {\n if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {\n return;\n }\n else {\n parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {\n if (parsedGeometryData.id === parsedMesh.geometryId) {\n switch (geometryType) {\n case \"boxes\":\n BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"spheres\":\n BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"cylinders\":\n BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"toruses\":\n BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"grounds\":\n BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"planes\":\n BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"torusKnots\":\n BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);\n break;\n case \"vertexData\":\n BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);\n break;\n }\n found = true;\n }\n });\n }\n });\n if (found === false) {\n BABYLON.Tools.Warn(\"Geometry not found for mesh \" + parsedMesh.id);\n }\n }\n }\n // Material ?\n if (parsedMesh.materialId) {\n var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);\n if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {\n for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {\n var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];\n if (parsedMultiMaterial.id === parsedMesh.materialId) {\n for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {\n var subMatId = parsedMultiMaterial.materials[matIndex];\n loadedMaterialsIds.push(subMatId);\n var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);\n if (mat) {\n log += \"\\n\\tMaterial \" + mat.toString(fullDetails);\n }\n }\n loadedMaterialsIds.push(parsedMultiMaterial.id);\n var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);\n if (mmat) {\n materialFound = true;\n log += \"\\n\\tMulti-Material \" + mmat.toString(fullDetails);\n }\n break;\n }\n }\n }\n if (materialFound === false) {\n loadedMaterialsIds.push(parsedMesh.materialId);\n var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);\n if (!mat) {\n BABYLON.Tools.Warn(\"Material not found for mesh \" + parsedMesh.id);\n }\n else {\n log += \"\\n\\tMaterial \" + mat.toString(fullDetails);\n }\n }\n }\n // Skeleton ?\n if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {\n var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);\n if (skeletonAlreadyLoaded === false) {\n for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {\n var parsedSkeleton = parsedData.skeletons[skeletonIndex];\n if (parsedSkeleton.id === parsedMesh.skeletonId) {\n var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);\n skeletons.push(skeleton);\n loadedSkeletonsIds.push(parsedSkeleton.id);\n log += \"\\n\\tSkeleton \" + skeleton.toString(fullDetails);\n }\n }\n }\n }\n // Morph targets ?\n if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {\n for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {\n var managerData = _a[_i];\n BABYLON.MorphTargetManager.Parse(managerData, scene);\n }\n }\n var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);\n meshes.push(mesh);\n log += \"\\n\\tMesh \" + mesh.toString(fullDetails);\n }\n }\n // Connecting parents\n var currentMesh;\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n currentMesh = scene.meshes[index];\n if (currentMesh._waitingParentId) {\n currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);\n currentMesh._waitingParentId = null;\n }\n }\n // freeze and compute world matrix application\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n currentMesh = scene.meshes[index];\n if (currentMesh._waitingFreezeWorldMatrix) {\n currentMesh.freezeWorldMatrix();\n currentMesh._waitingFreezeWorldMatrix = null;\n }\n else {\n currentMesh.computeWorldMatrix(true);\n }\n }\n }\n // Particles\n if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {\n var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);\n if (parser) {\n for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {\n var parsedParticleSystem = parsedData.particleSystems[index];\n if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {\n particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));\n }\n }\n }\n }\n return true;\n }\n catch (err) {\n var msg = logOperation(\"importMesh\", parsedData ? parsedData.producer : \"Unknown\") + log;\n if (onError) {\n onError(msg, err);\n }\n else {\n BABYLON.Tools.Log(msg);\n throw err;\n }\n }\n finally {\n if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {\n BABYLON.Tools.Log(logOperation(\"importMesh\", parsedData ? parsedData.producer : \"Unknown\") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : \"\"));\n }\n }\n return false;\n },\n load: function (scene, data, rootUrl, onError) {\n // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details\n // when SceneLoader.debugLogging = true (default), or exception encountered.\n // Everything stored in var log instead of writing separate lines to support only writing in exception,\n // and avoid problems with multiple concurrent .babylon loads.\n var log = \"importScene has failed JSON parse\";\n try {\n var parsedData = JSON.parse(data);\n log = \"\";\n // Scene\n if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {\n scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;\n }\n if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {\n scene.autoClear = parsedData.autoClear;\n }\n if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {\n scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);\n }\n if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {\n scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);\n }\n if (parsedData.gravity !== undefined && parsedData.gravity !== null) {\n scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);\n }\n // Fog\n if (parsedData.fogMode && parsedData.fogMode !== 0) {\n scene.fogMode = parsedData.fogMode;\n scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);\n scene.fogStart = parsedData.fogStart;\n scene.fogEnd = parsedData.fogEnd;\n scene.fogDensity = parsedData.fogDensity;\n log += \"\\tFog mode for scene: \";\n switch (scene.fogMode) {\n // getters not compiling, so using hardcoded\n case 1:\n log += \"exp\\n\";\n break;\n case 2:\n log += \"exp2\\n\";\n break;\n case 3:\n log += \"linear\\n\";\n break;\n }\n }\n //Physics\n if (parsedData.physicsEnabled) {\n var physicsPlugin;\n if (parsedData.physicsEngine === \"cannon\") {\n physicsPlugin = new BABYLON.CannonJSPlugin();\n }\n else if (parsedData.physicsEngine === \"oimo\") {\n physicsPlugin = new BABYLON.OimoJSPlugin();\n }\n log = \"\\tPhysics engine \" + (parsedData.physicsEngine ? parsedData.physicsEngine : \"oimo\") + \" enabled\\n\";\n //else - default engine, which is currently oimo\n var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;\n scene.enablePhysics(physicsGravity, physicsPlugin);\n }\n // Metadata\n if (parsedData.metadata !== undefined && parsedData.metadata !== null) {\n scene.metadata = parsedData.metadata;\n }\n //collisions, if defined. otherwise, default is true\n if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {\n scene.collisionsEnabled = parsedData.collisionsEnabled;\n }\n scene.workerCollisions = !!parsedData.workerCollisions;\n var container = loadAssetContainer(scene, data, rootUrl, onError, true);\n if (!container) {\n return false;\n }\n if (parsedData.autoAnimate) {\n scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);\n }\n if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {\n scene.setActiveCameraByID(parsedData.activeCameraID);\n }\n // Environment texture\t\t\n if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {\n if (parsedData.environmentTextureType && parsedData.environmentTextureType === \"BABYLON.HDRCubeTexture\") {\n var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;\n var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);\n if (parsedData.environmentTextureRotationY) {\n hdrTexture.rotationY = parsedData.environmentTextureRotationY;\n }\n scene.environmentTexture = hdrTexture;\n }\n else {\n var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);\n if (parsedData.environmentTextureRotationY) {\n cubeTexture.rotationY = parsedData.environmentTextureRotationY;\n }\n scene.environmentTexture = cubeTexture;\n }\n if (parsedData.createDefaultSkybox === true) {\n var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;\n var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;\n scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);\n }\n }\n // Finish\n return true;\n }\n catch (err) {\n var msg = logOperation(\"importScene\", parsedData ? parsedData.producer : \"Unknown\") + log;\n if (onError) {\n onError(msg, err);\n }\n else {\n BABYLON.Tools.Log(msg);\n throw err;\n }\n }\n finally {\n if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {\n BABYLON.Tools.Log(logOperation(\"importScene\", parsedData ? parsedData.producer : \"Unknown\") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : \"\"));\n }\n }\n return false;\n },\n loadAssetContainer: function (scene, data, rootUrl, onError) {\n var container = loadAssetContainer(scene, data, rootUrl, onError);\n return container;\n }\n });\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.babylonFileLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var FilesInput = /** @class */ (function () {\n function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {\n this.onProcessFileCallback = function () { return true; };\n this._engine = engine;\n this._currentScene = scene;\n this._sceneLoadedCallback = sceneLoadedCallback;\n this._progressCallback = progressCallback;\n this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;\n this._textureLoadingCallback = textureLoadingCallback;\n this._startingProcessingFilesCallback = startingProcessingFilesCallback;\n this._onReloadCallback = onReloadCallback;\n this._errorCallback = errorCallback;\n }\n FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {\n var _this = this;\n if (elementToMonitor) {\n this._elementToMonitor = elementToMonitor;\n this._dragEnterHandler = function (e) { _this.drag(e); };\n this._dragOverHandler = function (e) { _this.drag(e); };\n this._dropHandler = function (e) { _this.drop(e); };\n this._elementToMonitor.addEventListener(\"dragenter\", this._dragEnterHandler, false);\n this._elementToMonitor.addEventListener(\"dragover\", this._dragOverHandler, false);\n this._elementToMonitor.addEventListener(\"drop\", this._dropHandler, false);\n }\n };\n FilesInput.prototype.dispose = function () {\n if (!this._elementToMonitor) {\n return;\n }\n this._elementToMonitor.removeEventListener(\"dragenter\", this._dragEnterHandler);\n this._elementToMonitor.removeEventListener(\"dragover\", this._dragOverHandler);\n this._elementToMonitor.removeEventListener(\"drop\", this._dropHandler);\n };\n FilesInput.prototype.renderFunction = function () {\n if (this._additionalRenderLoopLogicCallback) {\n this._additionalRenderLoopLogicCallback();\n }\n if (this._currentScene) {\n if (this._textureLoadingCallback) {\n var remaining = this._currentScene.getWaitingItemsCount();\n if (remaining > 0) {\n this._textureLoadingCallback(remaining);\n }\n }\n this._currentScene.render();\n }\n };\n FilesInput.prototype.drag = function (e) {\n e.stopPropagation();\n e.preventDefault();\n };\n FilesInput.prototype.drop = function (eventDrop) {\n eventDrop.stopPropagation();\n eventDrop.preventDefault();\n this.loadFiles(eventDrop);\n };\n FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {\n var _this = this;\n var reader = folder.createReader();\n var relativePath = folder.fullPath.replace(/^\\//, \"\").replace(/(.+?)\\/?$/, \"$1/\");\n reader.readEntries(function (entries) {\n remaining.count += entries.length;\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n var entry = entries_1[_i];\n if (entry.isFile) {\n entry.file(function (file) {\n file.correctName = relativePath + file.name;\n files.push(file);\n if (--remaining.count === 0) {\n callback();\n }\n });\n }\n else if (entry.isDirectory) {\n _this._traverseFolder(entry, files, remaining, callback);\n }\n }\n if (--remaining.count) {\n callback();\n }\n });\n };\n FilesInput.prototype._processFiles = function (files) {\n for (var i = 0; i < files.length; i++) {\n var name = files[i].correctName.toLowerCase();\n var extension = name.split('.').pop();\n if (!this.onProcessFileCallback(files[i], name, extension)) {\n continue;\n }\n if ((extension === \"babylon\" || extension === \"stl\" || extension === \"obj\" || extension === \"gltf\" || extension === \"glb\")\n && name.indexOf(\".binary.babylon\") === -1 && name.indexOf(\".incremental.babylon\") === -1) {\n this._sceneFileToLoad = files[i];\n }\n else {\n FilesInput.FilesToLoad[name] = files[i];\n }\n }\n };\n FilesInput.prototype.loadFiles = function (event) {\n var _this = this;\n if (this._startingProcessingFilesCallback)\n this._startingProcessingFilesCallback();\n // Handling data transfer via drag'n'drop\n if (event && event.dataTransfer && event.dataTransfer.files) {\n this._filesToLoad = event.dataTransfer.files;\n }\n // Handling files from input files\n if (event && event.target && event.target.files) {\n this._filesToLoad = event.target.files;\n }\n if (this._filesToLoad && this._filesToLoad.length > 0) {\n var files_1 = new Array();\n var folders = [];\n var items = event.dataTransfer ? event.dataTransfer.items : null;\n for (var i = 0; i < this._filesToLoad.length; i++) {\n var fileToLoad = this._filesToLoad[i];\n var name_1 = fileToLoad.name.toLowerCase();\n var entry = void 0;\n fileToLoad.correctName = name_1;\n if (items) {\n var item = items[i];\n if (item.getAsEntry) {\n entry = item.getAsEntry();\n }\n else if (item.webkitGetAsEntry) {\n entry = item.webkitGetAsEntry();\n }\n }\n if (!entry) {\n files_1.push(fileToLoad);\n }\n else {\n if (entry.isDirectory) {\n folders.push(entry);\n }\n else {\n files_1.push(fileToLoad);\n }\n }\n }\n if (folders.length === 0) {\n this._processFiles(files_1);\n this._processReload();\n }\n else {\n var remaining = { count: folders.length };\n for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {\n var folder = folders_1[_i];\n this._traverseFolder(folder, files_1, remaining, function () {\n _this._processFiles(files_1);\n if (remaining.count === 0) {\n _this._processReload();\n }\n });\n }\n }\n }\n };\n FilesInput.prototype._processReload = function () {\n if (this._onReloadCallback) {\n this._onReloadCallback(this._sceneFileToLoad);\n }\n else {\n this.reload();\n }\n };\n FilesInput.prototype.reload = function () {\n var _this = this;\n // If a scene file has been provided\n if (this._sceneFileToLoad) {\n if (this._currentScene) {\n if (BABYLON.Tools.errorsCount > 0) {\n BABYLON.Tools.ClearLogCache();\n }\n this._engine.stopRenderLoop();\n }\n BABYLON.SceneLoader.LoadAsync(\"file:\", this._sceneFileToLoad, this._engine, function (progress) {\n if (_this._progressCallback) {\n _this._progressCallback(progress);\n }\n }).then(function (scene) {\n if (_this._currentScene) {\n _this._currentScene.dispose();\n }\n _this._currentScene = scene;\n if (_this._sceneLoadedCallback) {\n _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);\n }\n // Wait for textures and shaders to be ready\n _this._currentScene.executeWhenReady(function () {\n _this._engine.runRenderLoop(function () {\n _this.renderFunction();\n });\n });\n }).catch(function (error) {\n if (_this._errorCallback) {\n _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);\n }\n });\n }\n else {\n BABYLON.Tools.Error(\"Please provide a valid .babylon file.\");\n }\n };\n FilesInput.FilesToLoad = {};\n return FilesInput;\n }());\n BABYLON.FilesInput = FilesInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.filesInput.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Tags = /** @class */ (function () {\n function Tags() {\n }\n Tags.EnableFor = function (obj) {\n obj._tags = obj._tags || {};\n obj.hasTags = function () {\n return Tags.HasTags(obj);\n };\n obj.addTags = function (tagsString) {\n return Tags.AddTagsTo(obj, tagsString);\n };\n obj.removeTags = function (tagsString) {\n return Tags.RemoveTagsFrom(obj, tagsString);\n };\n obj.matchesTagsQuery = function (tagsQuery) {\n return Tags.MatchesQuery(obj, tagsQuery);\n };\n };\n Tags.DisableFor = function (obj) {\n delete obj._tags;\n delete obj.hasTags;\n delete obj.addTags;\n delete obj.removeTags;\n delete obj.matchesTagsQuery;\n };\n Tags.HasTags = function (obj) {\n if (!obj._tags) {\n return false;\n }\n return !BABYLON.Tools.IsEmpty(obj._tags);\n };\n Tags.GetTags = function (obj, asString) {\n if (asString === void 0) { asString = true; }\n if (!obj._tags) {\n return null;\n }\n if (asString) {\n var tagsArray = [];\n for (var tag in obj._tags) {\n if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {\n tagsArray.push(tag);\n }\n }\n return tagsArray.join(\" \");\n }\n else {\n return obj._tags;\n }\n };\n // the tags 'true' and 'false' are reserved and cannot be used as tags\n // a tag cannot start with '||', '&&', and '!'\n // it cannot contain whitespaces\n Tags.AddTagsTo = function (obj, tagsString) {\n if (!tagsString) {\n return;\n }\n if (typeof tagsString !== \"string\") {\n return;\n }\n var tags = tagsString.split(\" \");\n tags.forEach(function (tag, index, array) {\n Tags._AddTagTo(obj, tag);\n });\n };\n Tags._AddTagTo = function (obj, tag) {\n tag = tag.trim();\n if (tag === \"\" || tag === \"true\" || tag === \"false\") {\n return;\n }\n if (tag.match(/[\\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {\n return;\n }\n Tags.EnableFor(obj);\n obj._tags[tag] = true;\n };\n Tags.RemoveTagsFrom = function (obj, tagsString) {\n if (!Tags.HasTags(obj)) {\n return;\n }\n var tags = tagsString.split(\" \");\n for (var t in tags) {\n Tags._RemoveTagFrom(obj, tags[t]);\n }\n };\n Tags._RemoveTagFrom = function (obj, tag) {\n delete obj._tags[tag];\n };\n Tags.MatchesQuery = function (obj, tagsQuery) {\n if (tagsQuery === undefined) {\n return true;\n }\n if (tagsQuery === \"\") {\n return Tags.HasTags(obj);\n }\n return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });\n };\n return Tags;\n }());\n BABYLON.Tags = Tags;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.tags.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to evalaute queries containing `and` and `or` operators\n */\n var AndOrNotEvaluator = /** @class */ (function () {\n function AndOrNotEvaluator() {\n }\n /**\n * Evaluate a query\n * @param query defines the query to evaluate\n * @param evaluateCallback defines the callback used to filter result\n * @returns true if the query matches\n */\n AndOrNotEvaluator.Eval = function (query, evaluateCallback) {\n if (!query.match(/\\([^\\(\\)]*\\)/g)) {\n query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);\n }\n else {\n query = query.replace(/\\([^\\(\\)]*\\)/g, function (r) {\n // remove parenthesis\n r = r.slice(1, r.length - 1);\n return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);\n });\n }\n if (query === \"true\") {\n return true;\n }\n if (query === \"false\") {\n return false;\n }\n return AndOrNotEvaluator.Eval(query, evaluateCallback);\n };\n AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {\n evaluateCallback = evaluateCallback || (function (r) {\n return r === \"true\" ? true : false;\n });\n var result;\n var or = parenthesisContent.split(\"||\");\n for (var i in or) {\n if (or.hasOwnProperty(i)) {\n var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());\n var and = ori.split(\"&&\");\n if (and.length > 1) {\n for (var j = 0; j < and.length; ++j) {\n var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());\n if (andj !== \"true\" && andj !== \"false\") {\n if (andj[0] === \"!\") {\n result = !evaluateCallback(andj.substring(1));\n }\n else {\n result = evaluateCallback(andj);\n }\n }\n else {\n result = andj === \"true\" ? true : false;\n }\n if (!result) { // no need to continue since 'false && ... && ...' will always return false\n ori = \"false\";\n break;\n }\n }\n }\n if (result || ori === \"true\") { // no need to continue since 'true || ... || ...' will always return true\n result = true;\n break;\n }\n // result equals false (or undefined)\n if (ori !== \"true\" && ori !== \"false\") {\n if (ori[0] === \"!\") {\n result = !evaluateCallback(ori.substring(1));\n }\n else {\n result = evaluateCallback(ori);\n }\n }\n else {\n result = ori === \"true\" ? true : false;\n }\n }\n }\n // the whole parenthesis scope is replaced by 'true' or 'false'\n return result ? \"true\" : \"false\";\n };\n AndOrNotEvaluator._SimplifyNegation = function (booleanString) {\n booleanString = booleanString.replace(/^[\\s!]+/, function (r) {\n // remove whitespaces\n r = r.replace(/[\\s]/g, function () { return \"\"; });\n return r.length % 2 ? \"!\" : \"\";\n });\n booleanString = booleanString.trim();\n if (booleanString === \"!true\") {\n booleanString = \"false\";\n }\n else if (booleanString === \"!false\") {\n booleanString = \"true\";\n }\n return booleanString;\n };\n return AndOrNotEvaluator;\n }());\n BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.andOrNotEvaluator.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to enable access to IndexedDB\n * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API\n */\n var Database = /** @class */ (function () {\n /**\n * Creates a new Database\n * @param urlToScene defines the url to load the scene\n * @param callbackManifestChecked defines the callback to use when manifest is checked\n * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)\n */\n function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {\n if (disableManifestCheck === void 0) { disableManifestCheck = false; }\n var _this = this;\n // Handling various flavors of prefixed version of IndexedDB\n this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);\n this.callbackManifestChecked = callbackManifestChecked;\n this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);\n this.db = null;\n this._enableSceneOffline = false;\n this._enableTexturesOffline = false;\n this.manifestVersionFound = 0;\n this.mustUpdateRessources = false;\n this.hasReachedQuota = false;\n if (!Database.IDBStorageEnabled) {\n this.callbackManifestChecked(true);\n }\n else {\n if (disableManifestCheck) {\n this._enableSceneOffline = true;\n this._enableTexturesOffline = true;\n this.manifestVersionFound = 1;\n BABYLON.Tools.SetImmediate(function () {\n _this.callbackManifestChecked(true);\n });\n }\n else {\n this._checkManifestFile();\n }\n }\n }\n Object.defineProperty(Database.prototype, \"enableSceneOffline\", {\n /**\n * Gets a boolean indicating if scene must be saved in the database\n */\n get: function () {\n return this._enableSceneOffline;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Database.prototype, \"enableTexturesOffline\", {\n /**\n * Gets a boolean indicating if textures must be saved in the database\n */\n get: function () {\n return this._enableTexturesOffline;\n },\n enumerable: true,\n configurable: true\n });\n Database.prototype._checkManifestFile = function () {\n var _this = this;\n var noManifestFile = function () {\n _this._enableSceneOffline = false;\n _this._enableTexturesOffline = false;\n _this.callbackManifestChecked(false);\n };\n var timeStampUsed = false;\n var manifestURL = this.currentSceneUrl + \".manifest\";\n var xhr = new XMLHttpRequest();\n if (navigator.onLine) {\n // Adding a timestamp to by-pass browsers' cache\n timeStampUsed = true;\n manifestURL = manifestURL + (manifestURL.match(/\\?/) == null ? \"?\" : \"&\") + Date.now();\n }\n xhr.open(\"GET\", manifestURL, true);\n xhr.addEventListener(\"load\", function () {\n if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {\n try {\n var manifestFile = JSON.parse(xhr.response);\n _this._enableSceneOffline = manifestFile.enableSceneOffline;\n _this._enableTexturesOffline = manifestFile.enableTexturesOffline;\n if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {\n _this.manifestVersionFound = manifestFile.version;\n }\n if (_this.callbackManifestChecked) {\n _this.callbackManifestChecked(true);\n }\n }\n catch (ex) {\n noManifestFile();\n }\n }\n else {\n noManifestFile();\n }\n }, false);\n xhr.addEventListener(\"error\", function (event) {\n if (timeStampUsed) {\n timeStampUsed = false;\n // Let's retry without the timeStamp\n // It could fail when coupled with HTML5 Offline API\n var retryManifestURL = _this.currentSceneUrl + \".manifest\";\n xhr.open(\"GET\", retryManifestURL, true);\n xhr.send();\n }\n else {\n noManifestFile();\n }\n }, false);\n try {\n xhr.send();\n }\n catch (ex) {\n BABYLON.Tools.Error(\"Error on XHR send request.\");\n this.callbackManifestChecked(false);\n }\n };\n /**\n * Open the database and make it available\n * @param successCallback defines the callback to call on success\n * @param errorCallback defines the callback to call on error\n */\n Database.prototype.openAsync = function (successCallback, errorCallback) {\n var _this = this;\n var handleError = function () {\n _this.isSupported = false;\n if (errorCallback)\n errorCallback();\n };\n if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {\n // Your browser doesn't support IndexedDB\n this.isSupported = false;\n if (errorCallback)\n errorCallback();\n }\n else {\n // If the DB hasn't been opened or created yet\n if (!this.db) {\n this.hasReachedQuota = false;\n this.isSupported = true;\n var request = this.idbFactory.open(\"babylonjs\", 1);\n // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB\n request.onerror = function (event) {\n handleError();\n };\n // executes when a version change transaction cannot complete due to other active transactions\n request.onblocked = function (event) {\n BABYLON.Tools.Error(\"IDB request blocked. Please reload the page.\");\n handleError();\n };\n // DB has been opened successfully\n request.onsuccess = function (event) {\n _this.db = request.result;\n successCallback();\n };\n // Initialization of the DB. Creating Scenes & Textures stores\n request.onupgradeneeded = function (event) {\n _this.db = (event.target).result;\n if (_this.db) {\n try {\n _this.db.createObjectStore(\"scenes\", { keyPath: \"sceneUrl\" });\n _this.db.createObjectStore(\"versions\", { keyPath: \"sceneUrl\" });\n _this.db.createObjectStore(\"textures\", { keyPath: \"textureUrl\" });\n }\n catch (ex) {\n BABYLON.Tools.Error(\"Error while creating object stores. Exception: \" + ex.message);\n handleError();\n }\n }\n };\n }\n // DB has already been created and opened\n else {\n if (successCallback)\n successCallback();\n }\n }\n };\n /**\n * Loads an image from the database\n * @param url defines the url to load from\n * @param image defines the target DOM image\n */\n Database.prototype.loadImageFromDB = function (url, image) {\n var _this = this;\n var completeURL = Database._ReturnFullUrlLocation(url);\n var saveAndLoadImage = function () {\n if (!_this.hasReachedQuota && _this.db !== null) {\n // the texture is not yet in the DB, let's try to save it\n _this._saveImageIntoDBAsync(completeURL, image);\n }\n // If the texture is not in the DB and we've reached the DB quota limit\n // let's load it directly from the web\n else {\n image.src = url;\n }\n };\n if (!this.mustUpdateRessources) {\n this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);\n }\n // First time we're download the images or update requested in the manifest file by a version change\n else {\n saveAndLoadImage();\n }\n };\n Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {\n if (this.isSupported && this.db !== null) {\n var texture;\n var transaction = this.db.transaction([\"textures\"]);\n transaction.onabort = function (event) {\n image.src = url;\n };\n transaction.oncomplete = function (event) {\n var blobTextureURL;\n if (texture) {\n var URL = window.URL || window.webkitURL;\n blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });\n image.onerror = function () {\n BABYLON.Tools.Error(\"Error loading image from blob URL: \" + blobTextureURL + \" switching back to web url: \" + url);\n image.src = url;\n };\n image.src = blobTextureURL;\n }\n else {\n notInDBCallback();\n }\n };\n var getRequest = transaction.objectStore(\"textures\").get(url);\n getRequest.onsuccess = function (event) {\n texture = (event.target).result;\n };\n getRequest.onerror = function (event) {\n BABYLON.Tools.Error(\"Error loading texture \" + url + \" from DB.\");\n image.src = url;\n };\n }\n else {\n BABYLON.Tools.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n image.src = url;\n }\n };\n Database.prototype._saveImageIntoDBAsync = function (url, image) {\n var _this = this;\n if (this.isSupported) {\n // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on\n var generateBlobUrl = function () {\n var blobTextureURL;\n if (blob) {\n var URL = window.URL || window.webkitURL;\n try {\n blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });\n }\n // Chrome is raising a type error if we're setting the oneTimeOnly parameter\n catch (ex) {\n blobTextureURL = URL.createObjectURL(blob);\n }\n }\n if (blobTextureURL) {\n image.src = blobTextureURL;\n }\n };\n if (Database.IsUASupportingBlobStorage) { // Create XHR\n var xhr = new XMLHttpRequest(), blob;\n xhr.open(\"GET\", url, true);\n xhr.responseType = \"blob\";\n xhr.addEventListener(\"load\", function () {\n if (xhr.status === 200 && _this.db) {\n // Blob as response (XHR2)\n blob = xhr.response;\n var transaction = _this.db.transaction([\"textures\"], \"readwrite\");\n // the transaction could abort because of a QuotaExceededError error\n transaction.onabort = function (event) {\n try {\n //backwards compatibility with ts 1.0, srcElement doesn't have an \"error\" according to ts 1.3\n var srcElement = (event.srcElement || event.target);\n var error = srcElement.error;\n if (error && error.name === \"QuotaExceededError\") {\n _this.hasReachedQuota = true;\n }\n }\n catch (ex) { }\n generateBlobUrl();\n };\n transaction.oncomplete = function (event) {\n generateBlobUrl();\n };\n var newTexture = { textureUrl: url, data: blob };\n try {\n // Put the blob into the dabase\n var addRequest = transaction.objectStore(\"textures\").put(newTexture);\n addRequest.onsuccess = function (event) {\n };\n addRequest.onerror = function (event) {\n generateBlobUrl();\n };\n }\n catch (ex) {\n // \"DataCloneError\" generated by Chrome when you try to inject blob into IndexedDB\n if (ex.code === 25) {\n Database.IsUASupportingBlobStorage = false;\n }\n image.src = url;\n }\n }\n else {\n image.src = url;\n }\n }, false);\n xhr.addEventListener(\"error\", function (event) {\n BABYLON.Tools.Error(\"Error in XHR request in BABYLON.Database.\");\n image.src = url;\n }, false);\n xhr.send();\n }\n else {\n image.src = url;\n }\n }\n else {\n BABYLON.Tools.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n image.src = url;\n }\n };\n Database.prototype._checkVersionFromDB = function (url, versionLoaded) {\n var _this = this;\n var updateVersion = function () {\n // the version is not yet in the DB or we need to update it\n _this._saveVersionIntoDBAsync(url, versionLoaded);\n };\n this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);\n };\n Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {\n var _this = this;\n if (this.isSupported && this.db) {\n var version;\n try {\n var transaction = this.db.transaction([\"versions\"]);\n transaction.oncomplete = function (event) {\n if (version) {\n // If the version in the JSON file is different from the version in DB\n if (_this.manifestVersionFound !== version.data) {\n _this.mustUpdateRessources = true;\n updateInDBCallback();\n }\n else {\n callback(version.data);\n }\n }\n // version was not found in DB\n else {\n _this.mustUpdateRessources = true;\n updateInDBCallback();\n }\n };\n transaction.onabort = function (event) {\n callback(-1);\n };\n var getRequest = transaction.objectStore(\"versions\").get(url);\n getRequest.onsuccess = function (event) {\n version = (event.target).result;\n };\n getRequest.onerror = function (event) {\n BABYLON.Tools.Error(\"Error loading version for scene \" + url + \" from DB.\");\n callback(-1);\n };\n }\n catch (ex) {\n BABYLON.Tools.Error(\"Error while accessing 'versions' object store (READ OP). Exception: \" + ex.message);\n callback(-1);\n }\n }\n else {\n BABYLON.Tools.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n callback(-1);\n }\n };\n Database.prototype._saveVersionIntoDBAsync = function (url, callback) {\n var _this = this;\n if (this.isSupported && !this.hasReachedQuota && this.db) {\n try {\n // Open a transaction to the database\n var transaction = this.db.transaction([\"versions\"], \"readwrite\");\n // the transaction could abort because of a QuotaExceededError error\n transaction.onabort = function (event) {\n try { //backwards compatibility with ts 1.0, srcElement doesn't have an \"error\" according to ts 1.3\n var error = event.srcElement['error'];\n if (error && error.name === \"QuotaExceededError\") {\n _this.hasReachedQuota = true;\n }\n }\n catch (ex) { }\n callback(-1);\n };\n transaction.oncomplete = function (event) {\n callback(_this.manifestVersionFound);\n };\n var newVersion = { sceneUrl: url, data: this.manifestVersionFound };\n // Put the scene into the database\n var addRequest = transaction.objectStore(\"versions\").put(newVersion);\n addRequest.onsuccess = function (event) {\n };\n addRequest.onerror = function (event) {\n BABYLON.Tools.Error(\"Error in DB add version request in BABYLON.Database.\");\n };\n }\n catch (ex) {\n BABYLON.Tools.Error(\"Error while accessing 'versions' object store (WRITE OP). Exception: \" + ex.message);\n callback(-1);\n }\n }\n else {\n callback(-1);\n }\n };\n /**\n * Loads a file from database\n * @param url defines the URL to load from\n * @param sceneLoaded defines a callback to call on success\n * @param progressCallBack defines a callback to call when progress changed\n * @param errorCallback defines a callback to call on error\n * @param useArrayBuffer defines a boolean to use array buffer instead of text string\n */\n Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {\n var _this = this;\n var completeUrl = Database._ReturnFullUrlLocation(url);\n var saveAndLoadFile = function () {\n // the scene is not yet in the DB, let's try to save it\n _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);\n };\n this._checkVersionFromDB(completeUrl, function (version) {\n if (version !== -1) {\n if (!_this.mustUpdateRessources) {\n _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);\n }\n else {\n _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);\n }\n }\n else {\n if (errorCallback) {\n errorCallback();\n }\n }\n });\n };\n Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {\n if (this.isSupported && this.db) {\n var targetStore;\n if (url.indexOf(\".babylon\") !== -1) {\n targetStore = \"scenes\";\n }\n else {\n targetStore = \"textures\";\n }\n var file;\n var transaction = this.db.transaction([targetStore]);\n transaction.oncomplete = function (event) {\n if (file) {\n callback(file.data);\n }\n // file was not found in DB\n else {\n notInDBCallback();\n }\n };\n transaction.onabort = function (event) {\n notInDBCallback();\n };\n var getRequest = transaction.objectStore(targetStore).get(url);\n getRequest.onsuccess = function (event) {\n file = (event.target).result;\n };\n getRequest.onerror = function (event) {\n BABYLON.Tools.Error(\"Error loading file \" + url + \" from DB.\");\n notInDBCallback();\n };\n }\n else {\n BABYLON.Tools.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n callback();\n }\n };\n Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {\n var _this = this;\n if (this.isSupported) {\n var targetStore;\n if (url.indexOf(\".babylon\") !== -1) {\n targetStore = \"scenes\";\n }\n else {\n targetStore = \"textures\";\n }\n // Create XHR\n var xhr = new XMLHttpRequest();\n var fileData;\n xhr.open(\"GET\", url + \"?\" + Date.now(), true);\n if (useArrayBuffer) {\n xhr.responseType = \"arraybuffer\";\n }\n if (progressCallback) {\n xhr.onprogress = progressCallback;\n }\n xhr.addEventListener(\"load\", function () {\n if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {\n // Blob as response (XHR2)\n //fileData = xhr.responseText;\n fileData = !useArrayBuffer ? xhr.responseText : xhr.response;\n if (!_this.hasReachedQuota && _this.db) {\n // Open a transaction to the database\n var transaction = _this.db.transaction([targetStore], \"readwrite\");\n // the transaction could abort because of a QuotaExceededError error\n transaction.onabort = function (event) {\n try {\n //backwards compatibility with ts 1.0, srcElement doesn't have an \"error\" according to ts 1.3\n var error = event.srcElement['error'];\n if (error && error.name === \"QuotaExceededError\") {\n _this.hasReachedQuota = true;\n }\n }\n catch (ex) { }\n callback(fileData);\n };\n transaction.oncomplete = function (event) {\n callback(fileData);\n };\n var newFile;\n if (targetStore === \"scenes\") {\n newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };\n }\n else {\n newFile = { textureUrl: url, data: fileData };\n }\n try {\n // Put the scene into the database\n var addRequest = transaction.objectStore(targetStore).put(newFile);\n addRequest.onsuccess = function (event) {\n };\n addRequest.onerror = function (event) {\n BABYLON.Tools.Error(\"Error in DB add file request in BABYLON.Database.\");\n };\n }\n catch (ex) {\n callback(fileData);\n }\n }\n else {\n callback(fileData);\n }\n }\n else {\n if (xhr.status >= 400 && errorCallback) {\n errorCallback(xhr);\n }\n else {\n callback();\n }\n }\n }, false);\n xhr.addEventListener(\"error\", function (event) {\n BABYLON.Tools.Error(\"error on XHR request.\");\n callback();\n }, false);\n xhr.send();\n }\n else {\n BABYLON.Tools.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n callback();\n }\n };\n /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */\n Database.IsUASupportingBlobStorage = true;\n /** Gets a boolean indicating if Database storate is enabled */\n Database.IDBStorageEnabled = true;\n Database._ParseURL = function (url) {\n var a = document.createElement('a');\n a.href = url;\n var urlWithoutHash = url.substring(0, url.lastIndexOf(\"#\"));\n var fileName = url.substring(urlWithoutHash.lastIndexOf(\"/\") + 1, url.length);\n var absLocation = url.substring(0, url.indexOf(fileName, 0));\n return absLocation;\n };\n Database._ReturnFullUrlLocation = function (url) {\n if (url.indexOf(\"http:/\") === -1 && url.indexOf(\"https:/\") === -1) {\n return (Database._ParseURL(window.location.href) + url);\n }\n else {\n return url;\n }\n };\n return Database;\n }());\n BABYLON.Database = Database;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.database.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var FresnelParameters = /** @class */ (function () {\n function FresnelParameters() {\n this._isEnabled = true;\n this.leftColor = BABYLON.Color3.White();\n this.rightColor = BABYLON.Color3.Black();\n this.bias = 0;\n this.power = 1;\n }\n Object.defineProperty(FresnelParameters.prototype, \"isEnabled\", {\n get: function () {\n return this._isEnabled;\n },\n set: function (value) {\n if (this._isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);\n },\n enumerable: true,\n configurable: true\n });\n FresnelParameters.prototype.clone = function () {\n var newFresnelParameters = new FresnelParameters();\n BABYLON.Tools.DeepCopy(this, newFresnelParameters);\n return newFresnelParameters;\n };\n FresnelParameters.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.isEnabled = this.isEnabled;\n serializationObject.leftColor = this.leftColor.asArray();\n serializationObject.rightColor = this.rightColor.asArray();\n serializationObject.bias = this.bias;\n serializationObject.power = this.power;\n return serializationObject;\n };\n FresnelParameters.Parse = function (parsedFresnelParameters) {\n var fresnelParameters = new FresnelParameters();\n fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;\n fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);\n fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);\n fresnelParameters.bias = parsedFresnelParameters.bias;\n fresnelParameters.power = parsedFresnelParameters.power || 1.0;\n return fresnelParameters;\n };\n return FresnelParameters;\n }());\n BABYLON.FresnelParameters = FresnelParameters;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.fresnelParameters.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var MultiMaterial = /** @class */ (function (_super) {\n __extends(MultiMaterial, _super);\n function MultiMaterial(name, scene) {\n var _this = _super.call(this, name, scene, true) || this;\n scene.multiMaterials.push(_this);\n _this.subMaterials = new Array();\n _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material\n return _this;\n }\n Object.defineProperty(MultiMaterial.prototype, \"subMaterials\", {\n get: function () {\n return this._subMaterials;\n },\n set: function (value) {\n this._subMaterials = value;\n this._hookArray(value);\n },\n enumerable: true,\n configurable: true\n });\n MultiMaterial.prototype._hookArray = function (array) {\n var _this = this;\n var oldPush = array.push;\n array.push = function () {\n var items = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n items[_i] = arguments[_i];\n }\n var result = oldPush.apply(array, items);\n _this._markAllSubMeshesAsTexturesDirty();\n return result;\n };\n var oldSplice = array.splice;\n array.splice = function (index, deleteCount) {\n var deleted = oldSplice.apply(array, [index, deleteCount]);\n _this._markAllSubMeshesAsTexturesDirty();\n return deleted;\n };\n };\n // Properties\n MultiMaterial.prototype.getSubMaterial = function (index) {\n if (index < 0 || index >= this.subMaterials.length) {\n return this.getScene().defaultMaterial;\n }\n return this.subMaterials[index];\n };\n MultiMaterial.prototype.getActiveTextures = function () {\n var _a;\n return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {\n if (subMaterial) {\n return subMaterial.getActiveTextures();\n }\n else {\n return [];\n }\n }));\n };\n // Methods\n MultiMaterial.prototype.getClassName = function () {\n return \"MultiMaterial\";\n };\n MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {\n for (var index = 0; index < this.subMaterials.length; index++) {\n var subMaterial = this.subMaterials[index];\n if (subMaterial) {\n if (subMaterial.storeEffectOnSubMeshes) {\n if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {\n return false;\n }\n continue;\n }\n if (!subMaterial.isReady(mesh)) {\n return false;\n }\n }\n }\n return true;\n };\n MultiMaterial.prototype.clone = function (name, cloneChildren) {\n var newMultiMaterial = new MultiMaterial(name, this.getScene());\n for (var index = 0; index < this.subMaterials.length; index++) {\n var subMaterial = null;\n var current = this.subMaterials[index];\n if (cloneChildren && current) {\n subMaterial = current.clone(name + \"-\" + current.name);\n }\n else {\n subMaterial = this.subMaterials[index];\n }\n newMultiMaterial.subMaterials.push(subMaterial);\n }\n return newMultiMaterial;\n };\n MultiMaterial.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.id = this.id;\n if (BABYLON.Tags) {\n serializationObject.tags = BABYLON.Tags.GetTags(this);\n }\n serializationObject.materials = [];\n for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {\n var subMat = this.subMaterials[matIndex];\n if (subMat) {\n serializationObject.materials.push(subMat.id);\n }\n else {\n serializationObject.materials.push(null);\n }\n }\n return serializationObject;\n };\n MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var index = scene.multiMaterials.indexOf(this);\n if (index >= 0) {\n scene.multiMaterials.splice(index, 1);\n }\n _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);\n };\n return MultiMaterial;\n }(BABYLON.Material));\n BABYLON.MultiMaterial = MultiMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.multiMaterial.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FreeCameraTouchInput = /** @class */ (function () {\n function FreeCameraTouchInput() {\n this._offsetX = null;\n this._offsetY = null;\n this._pointerPressed = new Array();\n this.touchAngularSensibility = 200000.0;\n this.touchMoveSensibility = 250.0;\n }\n FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n var previousPosition = null;\n if (this._pointerInput === undefined) {\n this._onLostFocus = function (evt) {\n _this._offsetX = null;\n _this._offsetY = null;\n };\n this._pointerInput = function (p, s) {\n var evt = p.event;\n if (evt.pointerType === \"mouse\") {\n return;\n }\n if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n _this._pointerPressed.push(evt.pointerId);\n if (_this._pointerPressed.length !== 1) {\n return;\n }\n previousPosition = {\n x: evt.clientX,\n y: evt.clientY\n };\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n var index = _this._pointerPressed.indexOf(evt.pointerId);\n if (index === -1) {\n return;\n }\n _this._pointerPressed.splice(index, 1);\n if (index != 0) {\n return;\n }\n previousPosition = null;\n _this._offsetX = null;\n _this._offsetY = null;\n }\n else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n if (!previousPosition) {\n return;\n }\n var index = _this._pointerPressed.indexOf(evt.pointerId);\n if (index != 0) {\n return;\n }\n _this._offsetX = evt.clientX - previousPosition.x;\n _this._offsetY = -(evt.clientY - previousPosition.y);\n }\n };\n }\n this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);\n if (this._onLostFocus) {\n element.addEventListener(\"blur\", this._onLostFocus);\n }\n };\n FreeCameraTouchInput.prototype.detachControl = function (element) {\n if (this._pointerInput && element) {\n if (this._observer) {\n this.camera.getScene().onPointerObservable.remove(this._observer);\n this._observer = null;\n }\n if (this._onLostFocus) {\n element.removeEventListener(\"blur\", this._onLostFocus);\n this._onLostFocus = null;\n }\n this._pointerPressed = [];\n this._offsetX = null;\n this._offsetY = null;\n }\n };\n FreeCameraTouchInput.prototype.checkInputs = function () {\n if (this._offsetX && this._offsetY) {\n var camera = this.camera;\n camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;\n if (this._pointerPressed.length > 1) {\n camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;\n }\n else {\n var speed = camera._computeLocalCameraSpeed();\n var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);\n BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);\n camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));\n }\n }\n };\n FreeCameraTouchInput.prototype.getClassName = function () {\n return \"FreeCameraTouchInput\";\n };\n FreeCameraTouchInput.prototype.getSimpleName = function () {\n return \"touch\";\n };\n __decorate([\n BABYLON.serialize()\n ], FreeCameraTouchInput.prototype, \"touchAngularSensibility\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCameraTouchInput.prototype, \"touchMoveSensibility\", void 0);\n return FreeCameraTouchInput;\n }());\n BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;\n BABYLON.CameraInputTypes[\"FreeCameraTouchInput\"] = FreeCameraTouchInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraTouchInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"TouchCamera\", function (name, scene) {\n return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n // We're mainly based on the logic defined into the FreeCamera code\n var TouchCamera = /** @class */ (function (_super) {\n __extends(TouchCamera, _super);\n //-- end properties for backward compatibility for inputs\n function TouchCamera(name, position, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.inputs.addTouch();\n _this._setupInputs();\n return _this;\n }\n Object.defineProperty(TouchCamera.prototype, \"touchAngularSensibility\", {\n //-- Begin properties for backward compatibility for inputs\n get: function () {\n var touch = this.inputs.attached[\"touch\"];\n if (touch)\n return touch.touchAngularSensibility;\n return 0;\n },\n set: function (value) {\n var touch = this.inputs.attached[\"touch\"];\n if (touch)\n touch.touchAngularSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TouchCamera.prototype, \"touchMoveSensibility\", {\n get: function () {\n var touch = this.inputs.attached[\"touch\"];\n if (touch)\n return touch.touchMoveSensibility;\n return 0;\n },\n set: function (value) {\n var touch = this.inputs.attached[\"touch\"];\n if (touch)\n touch.touchMoveSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n TouchCamera.prototype.getClassName = function () {\n return \"TouchCamera\";\n };\n TouchCamera.prototype._setupInputs = function () {\n var mouse = this.inputs.attached[\"mouse\"];\n if (mouse) {\n mouse.touchEnabled = false;\n }\n };\n return TouchCamera;\n }(BABYLON.FreeCamera));\n BABYLON.TouchCamera = TouchCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.touchCamera.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ProceduralTexture = /** @class */ (function (_super) {\n __extends(ProceduralTexture, _super);\n function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {\n if (fallbackTexture === void 0) { fallbackTexture = null; }\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n if (isCube === void 0) { isCube = false; }\n var _this = _super.call(this, null, scene, !generateMipMaps) || this;\n _this.isCube = isCube;\n _this.isEnabled = true;\n _this._currentRefreshId = -1;\n _this._refreshRate = 1;\n _this._vertexBuffers = {};\n _this._uniforms = new Array();\n _this._samplers = new Array();\n _this._textures = {};\n _this._floats = {};\n _this._ints = {};\n _this._floatsArrays = {};\n _this._colors3 = {};\n _this._colors4 = {};\n _this._vectors2 = {};\n _this._vectors3 = {};\n _this._matrices = {};\n _this._fallbackTextureUsed = false;\n scene = _this.getScene();\n scene.proceduralTextures.push(_this);\n _this._engine = scene.getEngine();\n _this.name = name;\n _this.isRenderTarget = true;\n _this._size = size;\n _this._generateMipMaps = generateMipMaps;\n _this.setFragment(fragment);\n _this._fallbackTexture = fallbackTexture;\n if (isCube) {\n _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });\n _this.setFloat(\"face\", 0);\n }\n else {\n _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);\n }\n // VBO\n var vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);\n _this._createIndexBuffer();\n return _this;\n }\n ProceduralTexture.prototype._createIndexBuffer = function () {\n var engine = this._engine;\n // Indices\n var indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = engine.createIndexBuffer(indices);\n };\n ProceduralTexture.prototype._rebuild = function () {\n var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._createIndexBuffer();\n if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {\n this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;\n }\n };\n ProceduralTexture.prototype.reset = function () {\n if (this._effect === undefined) {\n return;\n }\n var engine = this._engine;\n engine._releaseEffect(this._effect);\n };\n ProceduralTexture.prototype.isReady = function () {\n var _this = this;\n var engine = this._engine;\n var shaders;\n if (!this._fragment) {\n return false;\n }\n if (this._fallbackTextureUsed) {\n return true;\n }\n if (this._fragment.fragmentElement !== undefined) {\n shaders = { vertex: \"procedural\", fragmentElement: this._fragment.fragmentElement };\n }\n else {\n shaders = { vertex: \"procedural\", fragment: this._fragment };\n }\n this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, \"\", undefined, undefined, function () {\n _this.releaseInternalTexture();\n if (_this._fallbackTexture) {\n _this._texture = _this._fallbackTexture._texture;\n if (_this._texture) {\n _this._texture.incrementReferences();\n }\n }\n _this._fallbackTextureUsed = true;\n });\n return this._effect.isReady();\n };\n ProceduralTexture.prototype.resetRefreshCounter = function () {\n this._currentRefreshId = -1;\n };\n ProceduralTexture.prototype.setFragment = function (fragment) {\n this._fragment = fragment;\n };\n Object.defineProperty(ProceduralTexture.prototype, \"refreshRate\", {\n get: function () {\n return this._refreshRate;\n },\n // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...\n set: function (value) {\n this._refreshRate = value;\n this.resetRefreshCounter();\n },\n enumerable: true,\n configurable: true\n });\n ProceduralTexture.prototype._shouldRender = function () {\n if (!this.isEnabled || !this.isReady() || !this._texture) {\n return false;\n }\n if (this._fallbackTextureUsed) {\n return false;\n }\n if (this._currentRefreshId === -1) { // At least render once\n this._currentRefreshId = 1;\n return true;\n }\n if (this.refreshRate === this._currentRefreshId) {\n this._currentRefreshId = 1;\n return true;\n }\n this._currentRefreshId++;\n return false;\n };\n ProceduralTexture.prototype.getRenderSize = function () {\n return this._size;\n };\n ProceduralTexture.prototype.resize = function (size, generateMipMaps) {\n if (this._fallbackTextureUsed) {\n return;\n }\n this.releaseInternalTexture();\n this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);\n // Update properties\n this._size = size;\n this._generateMipMaps = generateMipMaps;\n };\n ProceduralTexture.prototype._checkUniform = function (uniformName) {\n if (this._uniforms.indexOf(uniformName) === -1) {\n this._uniforms.push(uniformName);\n }\n };\n ProceduralTexture.prototype.setTexture = function (name, texture) {\n if (this._samplers.indexOf(name) === -1) {\n this._samplers.push(name);\n }\n this._textures[name] = texture;\n return this;\n };\n ProceduralTexture.prototype.setFloat = function (name, value) {\n this._checkUniform(name);\n this._floats[name] = value;\n return this;\n };\n /**\n * Set the value of an uniform to an integer value\n * @param name defines the name of the uniform\n * @param value defines the value to set\n * @returns the current procedural texture\n */\n ProceduralTexture.prototype.setInt = function (name, value) {\n this._checkUniform(name);\n this._ints[name] = value;\n return this;\n };\n ProceduralTexture.prototype.setFloats = function (name, value) {\n this._checkUniform(name);\n this._floatsArrays[name] = value;\n return this;\n };\n ProceduralTexture.prototype.setColor3 = function (name, value) {\n this._checkUniform(name);\n this._colors3[name] = value;\n return this;\n };\n ProceduralTexture.prototype.setColor4 = function (name, value) {\n this._checkUniform(name);\n this._colors4[name] = value;\n return this;\n };\n ProceduralTexture.prototype.setVector2 = function (name, value) {\n this._checkUniform(name);\n this._vectors2[name] = value;\n return this;\n };\n ProceduralTexture.prototype.setVector3 = function (name, value) {\n this._checkUniform(name);\n this._vectors3[name] = value;\n return this;\n };\n ProceduralTexture.prototype.setMatrix = function (name, value) {\n this._checkUniform(name);\n this._matrices[name] = value;\n return this;\n };\n ProceduralTexture.prototype.render = function (useCameraPostProcess) {\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var engine = this._engine;\n // Render\n engine.enableEffect(this._effect);\n engine.setState(false);\n // Texture\n for (var name in this._textures) {\n this._effect.setTexture(name, this._textures[name]);\n }\n // Float \n for (name in this._ints) {\n this._effect.setInt(name, this._ints[name]);\n }\n // Float \n for (name in this._floats) {\n this._effect.setFloat(name, this._floats[name]);\n }\n // Floats \n for (name in this._floatsArrays) {\n this._effect.setArray(name, this._floatsArrays[name]);\n }\n // Color3 \n for (name in this._colors3) {\n this._effect.setColor3(name, this._colors3[name]);\n }\n // Color4 \n for (name in this._colors4) {\n var color = this._colors4[name];\n this._effect.setFloat4(name, color.r, color.g, color.b, color.a);\n }\n // Vector2 \n for (name in this._vectors2) {\n this._effect.setVector2(name, this._vectors2[name]);\n }\n // Vector3 \n for (name in this._vectors3) {\n this._effect.setVector3(name, this._vectors3[name]);\n }\n // Matrix \n for (name in this._matrices) {\n this._effect.setMatrix(name, this._matrices[name]);\n }\n if (!this._texture) {\n return;\n }\n if (this.isCube) {\n for (var face = 0; face < 6; face++) {\n engine.bindFramebuffer(this._texture, face, undefined, undefined, true);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);\n this._effect.setFloat(\"face\", face);\n // Clear\n engine.clear(scene.clearColor, true, true, true);\n // Draw order\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n // Mipmaps\n if (face === 5) {\n engine.generateMipMapsForCubemap(this._texture);\n }\n }\n }\n else {\n engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);\n // Clear\n engine.clear(scene.clearColor, true, true, true);\n // Draw order\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n }\n // Unbind\n engine.unBindFramebuffer(this._texture, this.isCube);\n if (this.onGenerated) {\n this.onGenerated();\n }\n };\n ProceduralTexture.prototype.clone = function () {\n var textureSize = this.getSize();\n var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // RenderTarget Texture\n newTexture.coordinatesMode = this.coordinatesMode;\n return newTexture;\n };\n ProceduralTexture.prototype.dispose = function () {\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n var index = scene.proceduralTextures.indexOf(this);\n if (index >= 0) {\n scene.proceduralTextures.splice(index, 1);\n }\n var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {\n this._indexBuffer = null;\n }\n _super.prototype.dispose.call(this);\n };\n __decorate([\n BABYLON.serialize()\n ], ProceduralTexture.prototype, \"_size\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ProceduralTexture.prototype, \"_generateMipMaps\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ProceduralTexture.prototype, \"isEnabled\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ProceduralTexture.prototype, \"refreshRate\", null);\n return ProceduralTexture;\n }(BABYLON.Texture));\n BABYLON.ProceduralTexture = ProceduralTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.proceduralTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var CustomProceduralTexture = /** @class */ (function (_super) {\n __extends(CustomProceduralTexture, _super);\n function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {\n var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;\n _this._animate = true;\n _this._time = 0;\n _this._texturePath = texturePath;\n //Try to load json\n _this.loadJson(texturePath);\n _this.refreshRate = 1;\n return _this;\n }\n CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {\n var _this = this;\n var noConfigFile = function () {\n BABYLON.Tools.Log(\"No config file found in \" + jsonUrl + \" trying to use ShadersStore or DOM element\");\n try {\n _this.setFragment(_this._texturePath);\n }\n catch (ex) {\n BABYLON.Tools.Error(\"No json or ShaderStore or DOM element found for CustomProceduralTexture\");\n }\n };\n var configFileUrl = jsonUrl + \"/config.json\";\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", configFileUrl, true);\n xhr.addEventListener(\"load\", function () {\n if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {\n try {\n _this._config = JSON.parse(xhr.response);\n _this.updateShaderUniforms();\n _this.updateTextures();\n _this.setFragment(_this._texturePath + \"/custom\");\n _this._animate = _this._config.animate;\n _this.refreshRate = _this._config.refreshrate;\n }\n catch (ex) {\n noConfigFile();\n }\n }\n else {\n noConfigFile();\n }\n }, false);\n xhr.addEventListener(\"error\", function () {\n noConfigFile();\n }, false);\n try {\n xhr.send();\n }\n catch (ex) {\n BABYLON.Tools.Error(\"CustomProceduralTexture: Error on XHR send request.\");\n }\n };\n CustomProceduralTexture.prototype.isReady = function () {\n if (!_super.prototype.isReady.call(this)) {\n return false;\n }\n for (var name in this._textures) {\n var texture = this._textures[name];\n if (!texture.isReady()) {\n return false;\n }\n }\n return true;\n };\n CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {\n var scene = this.getScene();\n if (this._animate && scene) {\n this._time += scene.getAnimationRatio() * 0.03;\n this.updateShaderUniforms();\n }\n _super.prototype.render.call(this, useCameraPostProcess);\n };\n CustomProceduralTexture.prototype.updateTextures = function () {\n for (var i = 0; i < this._config.sampler2Ds.length; i++) {\n this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + \"/\" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));\n }\n };\n CustomProceduralTexture.prototype.updateShaderUniforms = function () {\n if (this._config) {\n for (var j = 0; j < this._config.uniforms.length; j++) {\n var uniform = this._config.uniforms[j];\n switch (uniform.type) {\n case \"float\":\n this.setFloat(uniform.name, uniform.value);\n break;\n case \"color3\":\n this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));\n break;\n case \"color4\":\n this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));\n break;\n case \"vector2\":\n this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));\n break;\n case \"vector3\":\n this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));\n break;\n }\n }\n }\n this.setFloat(\"time\", this._time);\n };\n Object.defineProperty(CustomProceduralTexture.prototype, \"animate\", {\n get: function () {\n return this._animate;\n },\n set: function (value) {\n this._animate = value;\n },\n enumerable: true,\n configurable: true\n });\n return CustomProceduralTexture;\n }(BABYLON.ProceduralTexture));\n BABYLON.CustomProceduralTexture = CustomProceduralTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.customProceduralTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FreeCameraGamepadInput = /** @class */ (function () {\n function FreeCameraGamepadInput() {\n this.gamepadAngularSensibility = 200;\n this.gamepadMoveSensibility = 40;\n // private members\n this._cameraTransform = BABYLON.Matrix.Identity();\n this._deltaTransform = BABYLON.Vector3.Zero();\n this._vector3 = BABYLON.Vector3.Zero();\n this._vector2 = BABYLON.Vector2.Zero();\n }\n FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n var manager = this.camera.getScene().gamepadManager;\n this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {\n if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {\n // prioritize XBOX gamepads.\n if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {\n _this.gamepad = gamepad;\n }\n }\n });\n this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {\n if (_this.gamepad === gamepad) {\n _this.gamepad = null;\n }\n });\n this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);\n };\n FreeCameraGamepadInput.prototype.detachControl = function (element) {\n this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);\n this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);\n this.gamepad = null;\n };\n FreeCameraGamepadInput.prototype.checkInputs = function () {\n if (this.gamepad && this.gamepad.leftStick) {\n var camera = this.camera;\n var LSValues = this.gamepad.leftStick;\n var normalizedLX = LSValues.x / this.gamepadMoveSensibility;\n var normalizedLY = LSValues.y / this.gamepadMoveSensibility;\n LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;\n LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;\n var RSValues = this.gamepad.rightStick;\n if (RSValues) {\n var normalizedRX = RSValues.x / this.gamepadAngularSensibility;\n var normalizedRY = RSValues.y / this.gamepadAngularSensibility;\n RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;\n RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;\n }\n else {\n RSValues = { x: 0, y: 0 };\n }\n if (!camera.rotationQuaternion) {\n BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);\n }\n else {\n camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);\n }\n var speed = camera._computeLocalCameraSpeed() * 50.0;\n this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);\n BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);\n camera.cameraDirection.addInPlace(this._deltaTransform);\n this._vector2.copyFromFloats(RSValues.y, RSValues.x);\n camera.cameraRotation.addInPlace(this._vector2);\n }\n };\n FreeCameraGamepadInput.prototype.getClassName = function () {\n return \"FreeCameraGamepadInput\";\n };\n FreeCameraGamepadInput.prototype.getSimpleName = function () {\n return \"gamepad\";\n };\n __decorate([\n BABYLON.serialize()\n ], FreeCameraGamepadInput.prototype, \"gamepadAngularSensibility\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FreeCameraGamepadInput.prototype, \"gamepadMoveSensibility\", void 0);\n return FreeCameraGamepadInput;\n }());\n BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;\n BABYLON.CameraInputTypes[\"FreeCameraGamepadInput\"] = FreeCameraGamepadInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraGamepadInput.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ArcRotateCameraGamepadInput = /** @class */ (function () {\n function ArcRotateCameraGamepadInput() {\n this.gamepadRotationSensibility = 80;\n this.gamepadMoveSensibility = 40;\n }\n ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {\n var _this = this;\n var manager = this.camera.getScene().gamepadManager;\n this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {\n if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {\n // prioritize XBOX gamepads.\n if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {\n _this.gamepad = gamepad;\n }\n }\n });\n this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {\n if (_this.gamepad === gamepad) {\n _this.gamepad = null;\n }\n });\n this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);\n };\n ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {\n this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);\n this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);\n this.gamepad = null;\n };\n ArcRotateCameraGamepadInput.prototype.checkInputs = function () {\n if (this.gamepad) {\n var camera = this.camera;\n var RSValues = this.gamepad.rightStick;\n if (RSValues) {\n if (RSValues.x != 0) {\n var normalizedRX = RSValues.x / this.gamepadRotationSensibility;\n if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {\n camera.inertialAlphaOffset += normalizedRX;\n }\n }\n if (RSValues.y != 0) {\n var normalizedRY = RSValues.y / this.gamepadRotationSensibility;\n if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {\n camera.inertialBetaOffset += normalizedRY;\n }\n }\n }\n var LSValues = this.gamepad.leftStick;\n if (LSValues && LSValues.y != 0) {\n var normalizedLY = LSValues.y / this.gamepadMoveSensibility;\n if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {\n this.camera.inertialRadiusOffset -= normalizedLY;\n }\n }\n }\n };\n ArcRotateCameraGamepadInput.prototype.getClassName = function () {\n return \"ArcRotateCameraGamepadInput\";\n };\n ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {\n return \"gamepad\";\n };\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraGamepadInput.prototype, \"gamepadRotationSensibility\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ArcRotateCameraGamepadInput.prototype, \"gamepadMoveSensibility\", void 0);\n return ArcRotateCameraGamepadInput;\n }());\n BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;\n BABYLON.CameraInputTypes[\"ArcRotateCameraGamepadInput\"] = ArcRotateCameraGamepadInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var GamepadManager = /** @class */ (function () {\n function GamepadManager(_scene) {\n var _this = this;\n this._scene = _scene;\n this._babylonGamepads = [];\n this._oneGamepadConnected = false;\n this._isMonitoring = false;\n this.onGamepadDisconnectedObservable = new BABYLON.Observable();\n if (!BABYLON.Tools.IsWindowObjectExist()) {\n this._gamepadEventSupported = false;\n }\n else {\n this._gamepadEventSupported = 'GamepadEvent' in window;\n this._gamepadSupport = (navigator.getGamepads ||\n navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);\n }\n this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {\n // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected\n for (var i in _this._babylonGamepads) {\n var gamepad = _this._babylonGamepads[i];\n if (gamepad && gamepad._isConnected) {\n _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);\n }\n }\n });\n this._onGamepadConnectedEvent = function (evt) {\n var gamepad = evt.gamepad;\n if (gamepad.index in _this._babylonGamepads) {\n if (_this._babylonGamepads[gamepad.index].isConnected) {\n return;\n }\n }\n var newGamepad;\n if (_this._babylonGamepads[gamepad.index]) {\n newGamepad = _this._babylonGamepads[gamepad.index];\n newGamepad.browserGamepad = gamepad;\n newGamepad._isConnected = true;\n }\n else {\n newGamepad = _this._addNewGamepad(gamepad);\n }\n _this.onGamepadConnectedObservable.notifyObservers(newGamepad);\n _this._startMonitoringGamepads();\n };\n this._onGamepadDisconnectedEvent = function (evt) {\n var gamepad = evt.gamepad;\n // Remove the gamepad from the list of gamepads to monitor.\n for (var i in _this._babylonGamepads) {\n if (_this._babylonGamepads[i].index === gamepad.index) {\n var disconnectedGamepad = _this._babylonGamepads[i];\n disconnectedGamepad._isConnected = false;\n _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);\n break;\n }\n }\n };\n if (this._gamepadSupport) {\n //first add already-connected gamepads\n this._updateGamepadObjects();\n if (this._babylonGamepads.length) {\n this._startMonitoringGamepads();\n }\n // Checking if the gamepad connected event is supported (like in Firefox)\n if (this._gamepadEventSupported) {\n window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);\n window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);\n }\n else {\n this._startMonitoringGamepads();\n }\n }\n }\n Object.defineProperty(GamepadManager.prototype, \"gamepads\", {\n get: function () {\n return this._babylonGamepads;\n },\n enumerable: true,\n configurable: true\n });\n GamepadManager.prototype.getGamepadByType = function (type) {\n if (type === void 0) { type = BABYLON.Gamepad.XBOX; }\n for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {\n var gamepad = _a[_i];\n if (gamepad && gamepad.type === type) {\n return gamepad;\n }\n }\n return null;\n };\n GamepadManager.prototype.dispose = function () {\n if (this._gamepadEventSupported) {\n if (this._onGamepadConnectedEvent) {\n window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);\n }\n if (this._onGamepadDisconnectedEvent) {\n window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);\n }\n this._onGamepadConnectedEvent = null;\n this._onGamepadDisconnectedEvent = null;\n }\n this._babylonGamepads.forEach(function (gamepad) {\n gamepad.dispose();\n });\n this.onGamepadConnectedObservable.clear();\n this.onGamepadDisconnectedObservable.clear();\n this._oneGamepadConnected = false;\n this._stopMonitoringGamepads();\n this._babylonGamepads = [];\n };\n GamepadManager.prototype._addNewGamepad = function (gamepad) {\n if (!this._oneGamepadConnected) {\n this._oneGamepadConnected = true;\n }\n var newGamepad;\n var xboxOne = (gamepad.id.search(\"Xbox One\") !== -1);\n if (xboxOne || gamepad.id.search(\"Xbox 360\") !== -1 || gamepad.id.search(\"xinput\") !== -1) {\n newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);\n }\n // if pose is supported, use the (WebVR) pose enabled controller\n else if (gamepad.pose) {\n newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);\n }\n else {\n newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);\n }\n this._babylonGamepads[newGamepad.index] = newGamepad;\n return newGamepad;\n };\n GamepadManager.prototype._startMonitoringGamepads = function () {\n if (!this._isMonitoring) {\n this._isMonitoring = true;\n //back-comp\n if (!this._scene) {\n this._checkGamepadsStatus();\n }\n }\n };\n GamepadManager.prototype._stopMonitoringGamepads = function () {\n this._isMonitoring = false;\n };\n GamepadManager.prototype._checkGamepadsStatus = function () {\n var _this = this;\n // Hack to be compatible Chrome\n this._updateGamepadObjects();\n for (var i in this._babylonGamepads) {\n var gamepad = this._babylonGamepads[i];\n if (!gamepad || !gamepad.isConnected) {\n continue;\n }\n gamepad.update();\n }\n if (this._isMonitoring && !this._scene) {\n BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });\n }\n };\n // This function is called only on Chrome, which does not properly support\n // connection/disconnection events and forces you to recopy again the gamepad object\n GamepadManager.prototype._updateGamepadObjects = function () {\n var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);\n for (var i = 0; i < gamepads.length; i++) {\n var gamepad = gamepads[i];\n if (gamepad) {\n if (!this._babylonGamepads[gamepad.index]) {\n var newGamepad = this._addNewGamepad(gamepad);\n this.onGamepadConnectedObservable.notifyObservers(newGamepad);\n }\n else {\n // Forced to copy again this object for Chrome for unknown reason\n this._babylonGamepads[i].browserGamepad = gamepad;\n if (!this._babylonGamepads[i].isConnected) {\n this._babylonGamepads[i]._isConnected = true;\n this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);\n }\n }\n }\n }\n };\n return GamepadManager;\n }());\n BABYLON.GamepadManager = GamepadManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gamepadManager.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var StickValues = /** @class */ (function () {\n function StickValues(x, y) {\n this.x = x;\n this.y = y;\n }\n return StickValues;\n }());\n BABYLON.StickValues = StickValues;\n var Gamepad = /** @class */ (function () {\n function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {\n if (leftStickX === void 0) { leftStickX = 0; }\n if (leftStickY === void 0) { leftStickY = 1; }\n if (rightStickX === void 0) { rightStickX = 2; }\n if (rightStickY === void 0) { rightStickY = 3; }\n this.id = id;\n this.index = index;\n this.browserGamepad = browserGamepad;\n this._isConnected = true;\n this._invertLeftStickY = false;\n this.type = Gamepad.GAMEPAD;\n this._leftStickAxisX = leftStickX;\n this._leftStickAxisY = leftStickY;\n this._rightStickAxisX = rightStickX;\n this._rightStickAxisY = rightStickY;\n if (this.browserGamepad.axes.length >= 2) {\n this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };\n }\n if (this.browserGamepad.axes.length >= 4) {\n this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };\n }\n }\n Object.defineProperty(Gamepad.prototype, \"isConnected\", {\n get: function () {\n return this._isConnected;\n },\n enumerable: true,\n configurable: true\n });\n Gamepad.prototype.onleftstickchanged = function (callback) {\n this._onleftstickchanged = callback;\n };\n Gamepad.prototype.onrightstickchanged = function (callback) {\n this._onrightstickchanged = callback;\n };\n Object.defineProperty(Gamepad.prototype, \"leftStick\", {\n get: function () {\n return this._leftStick;\n },\n set: function (newValues) {\n if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {\n this._onleftstickchanged(newValues);\n }\n this._leftStick = newValues;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Gamepad.prototype, \"rightStick\", {\n get: function () {\n return this._rightStick;\n },\n set: function (newValues) {\n if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {\n this._onrightstickchanged(newValues);\n }\n this._rightStick = newValues;\n },\n enumerable: true,\n configurable: true\n });\n Gamepad.prototype.update = function () {\n if (this._leftStick) {\n this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };\n if (this._invertLeftStickY) {\n this.leftStick.y *= -1;\n }\n }\n if (this._rightStick) {\n this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };\n }\n };\n Gamepad.prototype.dispose = function () {\n };\n Gamepad.GAMEPAD = 0;\n Gamepad.GENERIC = 1;\n Gamepad.XBOX = 2;\n Gamepad.POSE_ENABLED = 3;\n return Gamepad;\n }());\n BABYLON.Gamepad = Gamepad;\n var GenericPad = /** @class */ (function (_super) {\n __extends(GenericPad, _super);\n function GenericPad(id, index, browserGamepad) {\n var _this = _super.call(this, id, index, browserGamepad) || this;\n _this.onButtonDownObservable = new BABYLON.Observable();\n _this.onButtonUpObservable = new BABYLON.Observable();\n _this.type = Gamepad.GENERIC;\n _this._buttons = new Array(browserGamepad.buttons.length);\n return _this;\n }\n GenericPad.prototype.onbuttondown = function (callback) {\n this._onbuttondown = callback;\n };\n GenericPad.prototype.onbuttonup = function (callback) {\n this._onbuttonup = callback;\n };\n GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._onbuttondown) {\n this._onbuttondown(buttonIndex);\n }\n this.onButtonDownObservable.notifyObservers(buttonIndex);\n }\n if (newValue === 0) {\n if (this._onbuttonup) {\n this._onbuttonup(buttonIndex);\n }\n this.onButtonUpObservable.notifyObservers(buttonIndex);\n }\n }\n return newValue;\n };\n GenericPad.prototype.update = function () {\n _super.prototype.update.call(this);\n for (var index = 0; index < this._buttons.length; index++) {\n this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);\n }\n };\n GenericPad.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this.onButtonDownObservable.clear();\n this.onButtonUpObservable.clear();\n };\n return GenericPad;\n }(Gamepad));\n BABYLON.GenericPad = GenericPad;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gamepad.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines supported buttons for XBox360 compatible gamepads\n */\n var Xbox360Button;\n (function (Xbox360Button) {\n /** A */\n Xbox360Button[Xbox360Button[\"A\"] = 0] = \"A\";\n /** B */\n Xbox360Button[Xbox360Button[\"B\"] = 1] = \"B\";\n /** X */\n Xbox360Button[Xbox360Button[\"X\"] = 2] = \"X\";\n /** Y */\n Xbox360Button[Xbox360Button[\"Y\"] = 3] = \"Y\";\n /** Start */\n Xbox360Button[Xbox360Button[\"Start\"] = 4] = \"Start\";\n /** Back */\n Xbox360Button[Xbox360Button[\"Back\"] = 5] = \"Back\";\n /** Left button */\n Xbox360Button[Xbox360Button[\"LB\"] = 6] = \"LB\";\n /** Right button */\n Xbox360Button[Xbox360Button[\"RB\"] = 7] = \"RB\";\n /** Left stick */\n Xbox360Button[Xbox360Button[\"LeftStick\"] = 8] = \"LeftStick\";\n /** Right stick */\n Xbox360Button[Xbox360Button[\"RightStick\"] = 9] = \"RightStick\";\n })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));\n /** Defines values for XBox360 DPad */\n var Xbox360Dpad;\n (function (Xbox360Dpad) {\n /** Up */\n Xbox360Dpad[Xbox360Dpad[\"Up\"] = 0] = \"Up\";\n /** Down */\n Xbox360Dpad[Xbox360Dpad[\"Down\"] = 1] = \"Down\";\n /** Left */\n Xbox360Dpad[Xbox360Dpad[\"Left\"] = 2] = \"Left\";\n /** Right */\n Xbox360Dpad[Xbox360Dpad[\"Right\"] = 3] = \"Right\";\n })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));\n /**\n * Defines a XBox360 gamepad\n */\n var Xbox360Pad = /** @class */ (function (_super) {\n __extends(Xbox360Pad, _super);\n /**\n * Creates a new XBox360 gamepad object\n * @param id defines the id of this gamepad\n * @param index defines its index\n * @param gamepad defines the internal HTML gamepad object\n * @param xboxOne defines if it is a XBox One gamepad\n */\n function Xbox360Pad(id, index, gamepad, xboxOne) {\n if (xboxOne === void 0) { xboxOne = false; }\n var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;\n _this._leftTrigger = 0;\n _this._rightTrigger = 0;\n /** Observable raised when a button is pressed */\n _this.onButtonDownObservable = new BABYLON.Observable();\n /** Observable raised when a button is released */\n _this.onButtonUpObservable = new BABYLON.Observable();\n /** Observable raised when a pad is pressed */\n _this.onPadDownObservable = new BABYLON.Observable();\n /** Observable raised when a pad is released */\n _this.onPadUpObservable = new BABYLON.Observable();\n _this._buttonA = 0;\n _this._buttonB = 0;\n _this._buttonX = 0;\n _this._buttonY = 0;\n _this._buttonBack = 0;\n _this._buttonStart = 0;\n _this._buttonLB = 0;\n _this._buttonRB = 0;\n _this._buttonLeftStick = 0;\n _this._buttonRightStick = 0;\n _this._dPadUp = 0;\n _this._dPadDown = 0;\n _this._dPadLeft = 0;\n _this._dPadRight = 0;\n _this._isXboxOnePad = false;\n _this.type = BABYLON.Gamepad.XBOX;\n _this._isXboxOnePad = xboxOne;\n return _this;\n }\n /**\n * Defines the callback to call when left trigger is pressed\n * @param callback defines the callback to use\n */\n Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {\n this._onlefttriggerchanged = callback;\n };\n /**\n * Defines the callback to call when right trigger is pressed\n * @param callback defines the callback to use\n */\n Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {\n this._onrighttriggerchanged = callback;\n };\n Object.defineProperty(Xbox360Pad.prototype, \"leftTrigger\", {\n /**\n * Gets or sets left trigger value\n */\n get: function () {\n return this._leftTrigger;\n },\n set: function (newValue) {\n if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {\n this._onlefttriggerchanged(newValue);\n }\n this._leftTrigger = newValue;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"rightTrigger\", {\n /**\n * Gets or sets right trigger value\n */\n get: function () {\n return this._rightTrigger;\n },\n set: function (newValue) {\n if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {\n this._onrighttriggerchanged(newValue);\n }\n this._rightTrigger = newValue;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Defines the callback to call when a button is pressed\n * @param callback defines the callback to use\n */\n Xbox360Pad.prototype.onbuttondown = function (callback) {\n this._onbuttondown = callback;\n };\n /**\n * Defines the callback to call when a button is released\n * @param callback defines the callback to use\n */\n Xbox360Pad.prototype.onbuttonup = function (callback) {\n this._onbuttonup = callback;\n };\n /**\n * Defines the callback to call when a pad is pressed\n * @param callback defines the callback to use\n */\n Xbox360Pad.prototype.ondpaddown = function (callback) {\n this._ondpaddown = callback;\n };\n /**\n * Defines the callback to call when a pad is released\n * @param callback defines the callback to use\n */\n Xbox360Pad.prototype.ondpadup = function (callback) {\n this._ondpadup = callback;\n };\n Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._onbuttondown) {\n this._onbuttondown(buttonType);\n }\n this.onButtonDownObservable.notifyObservers(buttonType);\n }\n if (newValue === 0) {\n if (this._onbuttonup) {\n this._onbuttonup(buttonType);\n }\n this.onButtonUpObservable.notifyObservers(buttonType);\n }\n }\n return newValue;\n };\n Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._ondpaddown) {\n this._ondpaddown(buttonType);\n }\n this.onPadDownObservable.notifyObservers(buttonType);\n }\n if (newValue === 0) {\n if (this._ondpadup) {\n this._ondpadup(buttonType);\n }\n this.onPadUpObservable.notifyObservers(buttonType);\n }\n }\n return newValue;\n };\n Object.defineProperty(Xbox360Pad.prototype, \"buttonA\", {\n /** Gets or sets value of A button */\n get: function () {\n return this._buttonA;\n },\n set: function (value) {\n this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonB\", {\n /** Gets or sets value of B button */\n get: function () {\n return this._buttonB;\n },\n set: function (value) {\n this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonX\", {\n /** Gets or sets value of X button */\n get: function () {\n return this._buttonX;\n },\n set: function (value) {\n this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonY\", {\n /** Gets or sets value of Y button */\n get: function () {\n return this._buttonY;\n },\n set: function (value) {\n this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonStart\", {\n /** Gets or sets value of Start button */\n get: function () {\n return this._buttonStart;\n },\n set: function (value) {\n this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonBack\", {\n /** Gets or sets value of Back button */\n get: function () {\n return this._buttonBack;\n },\n set: function (value) {\n this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonLB\", {\n /** Gets or sets value of Left button */\n get: function () {\n return this._buttonLB;\n },\n set: function (value) {\n this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonRB\", {\n /** Gets or sets value of Right button */\n get: function () {\n return this._buttonRB;\n },\n set: function (value) {\n this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonLeftStick\", {\n /** Gets or sets value of left stick */\n get: function () {\n return this._buttonLeftStick;\n },\n set: function (value) {\n this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"buttonRightStick\", {\n /** Gets or sets value of right stick */\n get: function () {\n return this._buttonRightStick;\n },\n set: function (value) {\n this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"dPadUp\", {\n /** Gets or sets value of DPad up */\n get: function () {\n return this._dPadUp;\n },\n set: function (value) {\n this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"dPadDown\", {\n /** Gets or sets value of DPad down */\n get: function () {\n return this._dPadDown;\n },\n set: function (value) {\n this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"dPadLeft\", {\n /** Gets or sets value of DPad left */\n get: function () {\n return this._dPadLeft;\n },\n set: function (value) {\n this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Xbox360Pad.prototype, \"dPadRight\", {\n /** Gets or sets value of DPad right */\n get: function () {\n return this._dPadRight;\n },\n set: function (value) {\n this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Force the gamepad to synchronize with device values\n */\n Xbox360Pad.prototype.update = function () {\n _super.prototype.update.call(this);\n if (this._isXboxOnePad) {\n this.buttonA = this.browserGamepad.buttons[0].value;\n this.buttonB = this.browserGamepad.buttons[1].value;\n this.buttonX = this.browserGamepad.buttons[2].value;\n this.buttonY = this.browserGamepad.buttons[3].value;\n this.buttonLB = this.browserGamepad.buttons[4].value;\n this.buttonRB = this.browserGamepad.buttons[5].value;\n this.leftTrigger = this.browserGamepad.axes[2];\n this.rightTrigger = this.browserGamepad.axes[5];\n this.buttonBack = this.browserGamepad.buttons[9].value;\n this.buttonStart = this.browserGamepad.buttons[8].value;\n this.buttonLeftStick = this.browserGamepad.buttons[6].value;\n this.buttonRightStick = this.browserGamepad.buttons[7].value;\n this.dPadUp = this.browserGamepad.buttons[11].value;\n this.dPadDown = this.browserGamepad.buttons[12].value;\n this.dPadLeft = this.browserGamepad.buttons[13].value;\n this.dPadRight = this.browserGamepad.buttons[14].value;\n }\n else {\n this.buttonA = this.browserGamepad.buttons[0].value;\n this.buttonB = this.browserGamepad.buttons[1].value;\n this.buttonX = this.browserGamepad.buttons[2].value;\n this.buttonY = this.browserGamepad.buttons[3].value;\n this.buttonLB = this.browserGamepad.buttons[4].value;\n this.buttonRB = this.browserGamepad.buttons[5].value;\n this.leftTrigger = this.browserGamepad.buttons[6].value;\n this.rightTrigger = this.browserGamepad.buttons[7].value;\n this.buttonBack = this.browserGamepad.buttons[8].value;\n this.buttonStart = this.browserGamepad.buttons[9].value;\n this.buttonLeftStick = this.browserGamepad.buttons[10].value;\n this.buttonRightStick = this.browserGamepad.buttons[11].value;\n this.dPadUp = this.browserGamepad.buttons[12].value;\n this.dPadDown = this.browserGamepad.buttons[13].value;\n this.dPadLeft = this.browserGamepad.buttons[14].value;\n this.dPadRight = this.browserGamepad.buttons[15].value;\n }\n };\n Xbox360Pad.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this.onButtonDownObservable.clear();\n this.onButtonUpObservable.clear();\n this.onPadDownObservable.clear();\n this.onPadUpObservable.clear();\n };\n return Xbox360Pad;\n }(BABYLON.Gamepad));\n BABYLON.Xbox360Pad = Xbox360Pad;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.xboxGamepad.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the types of pose enabled controllers that are supported\n */\n var PoseEnabledControllerType;\n (function (PoseEnabledControllerType) {\n /**\n * HTC Vive\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"VIVE\"] = 0] = \"VIVE\";\n /**\n * Oculus Rift\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"OCULUS\"] = 1] = \"OCULUS\";\n /**\n * Windows mixed reality\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"WINDOWS\"] = 2] = \"WINDOWS\";\n /**\n * Samsung gear VR\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"GEAR_VR\"] = 3] = \"GEAR_VR\";\n /**\n * Google Daydream\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"DAYDREAM\"] = 4] = \"DAYDREAM\";\n /**\n * Generic\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"GENERIC\"] = 5] = \"GENERIC\";\n })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));\n /**\n * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)\n */\n var PoseEnabledControllerHelper = /** @class */ (function () {\n function PoseEnabledControllerHelper() {\n }\n /**\n * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)\n * @param vrGamepad the gamepad to initialized\n * @returns a vr controller of the type the gamepad identified as\n */\n PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {\n // Oculus Touch\n if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {\n return new BABYLON.OculusTouchController(vrGamepad);\n }\n // Windows Mixed Reality controllers \n else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {\n return new BABYLON.WindowsMotionController(vrGamepad);\n }\n // HTC Vive\n else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {\n return new BABYLON.ViveController(vrGamepad);\n }\n // Samsung/Oculus Gear VR or Oculus Go\n else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {\n return new BABYLON.GearVRController(vrGamepad);\n }\n // Google Daydream\n else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {\n return new BABYLON.DaydreamController(vrGamepad);\n }\n // Generic \n else {\n return new BABYLON.GenericController(vrGamepad);\n }\n };\n return PoseEnabledControllerHelper;\n }());\n BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;\n /**\n * Defines the PoseEnabledController object that contains state of a vr capable controller\n */\n var PoseEnabledController = /** @class */ (function (_super) {\n __extends(PoseEnabledController, _super);\n /**\n * Creates a new PoseEnabledController from a gamepad\n * @param browserGamepad the gamepad that the PoseEnabledController should be created from\n */\n function PoseEnabledController(browserGamepad) {\n var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;\n // Represents device position and rotation in room space. Should only be used to help calculate babylon space values\n _this._deviceRoomPosition = BABYLON.Vector3.Zero();\n _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();\n /**\n * The device position in babylon space\n */\n _this.devicePosition = BABYLON.Vector3.Zero();\n /**\n * The device rotation in babylon space\n */\n _this.deviceRotationQuaternion = new BABYLON.Quaternion();\n /**\n * The scale factor of the device in babylon space\n */\n _this.deviceScaleFactor = 1;\n _this._leftHandSystemQuaternion = new BABYLON.Quaternion();\n /**\n * Internal, matrix used to convert room space to babylon space\n */\n _this._deviceToWorld = BABYLON.Matrix.Identity();\n /**\n * Node to be used when casting a ray from the controller\n */\n _this._pointingPoseNode = null;\n _this._workingMatrix = BABYLON.Matrix.Identity();\n /**\n * @hidden\n */\n _this._meshAttachedObservable = new BABYLON.Observable();\n _this.type = BABYLON.Gamepad.POSE_ENABLED;\n _this.controllerType = PoseEnabledControllerType.GENERIC;\n _this.position = BABYLON.Vector3.Zero();\n _this.rotationQuaternion = new BABYLON.Quaternion();\n _this._calculatedPosition = BABYLON.Vector3.Zero();\n _this._calculatedRotation = new BABYLON.Quaternion();\n BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);\n return _this;\n }\n /**\n * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller\n */\n PoseEnabledController.prototype.update = function () {\n _super.prototype.update.call(this);\n this._updatePoseAndMesh();\n };\n /**\n * Updates only the pose device and mesh without doing any button event checking\n */\n PoseEnabledController.prototype._updatePoseAndMesh = function () {\n var pose = this.browserGamepad.pose;\n this.updateFromDevice(pose);\n BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);\n this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);\n BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);\n this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);\n if (this._mesh) {\n this._mesh.position.copyFrom(this.devicePosition);\n if (this._mesh.rotationQuaternion) {\n this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);\n }\n }\n };\n /**\n * Updates the state of the pose enbaled controller based on the raw pose data from the device\n * @param poseData raw pose fromthe device\n */\n PoseEnabledController.prototype.updateFromDevice = function (poseData) {\n if (poseData) {\n this.rawPose = poseData;\n if (poseData.position) {\n this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);\n if (this._mesh && this._mesh.getScene().useRightHandedSystem) {\n this._deviceRoomPosition.z *= -1;\n }\n this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);\n this._calculatedPosition.addInPlace(this.position);\n }\n var pose = this.rawPose;\n if (poseData.orientation && pose.orientation) {\n this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);\n if (this._mesh) {\n if (this._mesh.getScene().useRightHandedSystem) {\n this._deviceRoomRotationQuaternion.z *= -1;\n this._deviceRoomRotationQuaternion.w *= -1;\n }\n else {\n this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);\n }\n }\n // if the camera is set, rotate to the camera's rotation\n this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);\n }\n }\n };\n /**\n * Attaches a mesh to the controller\n * @param mesh the mesh to be attached\n */\n PoseEnabledController.prototype.attachToMesh = function (mesh) {\n if (this._mesh) {\n this._mesh.parent = null;\n }\n this._mesh = mesh;\n if (this._poseControlledCamera) {\n this._mesh.parent = this._poseControlledCamera;\n }\n if (!this._mesh.rotationQuaternion) {\n this._mesh.rotationQuaternion = new BABYLON.Quaternion();\n }\n // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh\n this._updatePoseAndMesh();\n if (this._pointingPoseNode) {\n var parents = [];\n var obj = this._pointingPoseNode;\n while (obj.parent) {\n parents.push(obj.parent);\n obj = obj.parent;\n }\n parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });\n }\n this._meshAttachedObservable.notifyObservers(mesh);\n };\n /**\n * Attaches the controllers mesh to a camera\n * @param camera the camera the mesh should be attached to\n */\n PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {\n this._poseControlledCamera = camera;\n if (this._mesh) {\n this._mesh.parent = this._poseControlledCamera;\n }\n };\n /**\n * Disposes of the controller\n */\n PoseEnabledController.prototype.dispose = function () {\n if (this._mesh) {\n this._mesh.dispose();\n }\n this._mesh = null;\n _super.prototype.dispose.call(this);\n };\n Object.defineProperty(PoseEnabledController.prototype, \"mesh\", {\n /**\n * The mesh that is attached to the controller\n */\n get: function () {\n return this._mesh;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the ray of the controller in the direction the controller is pointing\n * @param length the length the resulting ray should be\n * @returns a ray in the direction the controller is pointing\n */\n PoseEnabledController.prototype.getForwardRay = function (length) {\n if (length === void 0) { length = 100; }\n if (!this.mesh) {\n return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);\n }\n var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();\n var origin = m.getTranslation();\n var forward = new BABYLON.Vector3(0, 0, -1);\n var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);\n var direction = BABYLON.Vector3.Normalize(forwardWorld);\n return new BABYLON.Ray(origin, direction, length);\n };\n /**\n * Name of the child mesh that can be used to cast a ray from the controller\n */\n PoseEnabledController.POINTING_POSE = \"POINTING_POSE\";\n return PoseEnabledController;\n }(BABYLON.Gamepad));\n BABYLON.PoseEnabledController = PoseEnabledController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.poseEnabledController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the WebVRController object that represents controllers tracked in 3D space\n */\n var WebVRController = /** @class */ (function (_super) {\n __extends(WebVRController, _super);\n /**\n * Creates a new WebVRController from a gamepad\n * @param vrGamepad the gamepad that the WebVRController should be created from\n */\n function WebVRController(vrGamepad) {\n var _this = _super.call(this, vrGamepad) || this;\n // Observables\n /**\n * Fired when the trigger state has changed\n */\n _this.onTriggerStateChangedObservable = new BABYLON.Observable();\n /**\n * Fired when the main button state has changed\n */\n _this.onMainButtonStateChangedObservable = new BABYLON.Observable();\n /**\n * Fired when the secondary button state has changed\n */\n _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();\n /**\n * Fired when the pad state has changed\n */\n _this.onPadStateChangedObservable = new BABYLON.Observable();\n /**\n * Fired when controllers stick values have changed\n */\n _this.onPadValuesChangedObservable = new BABYLON.Observable();\n /**\n * X and Y axis corrisponding to the controllers joystick\n */\n _this.pad = { x: 0, y: 0 };\n // avoid GC, store state in a tmp object\n _this._changes = {\n pressChanged: false,\n touchChanged: false,\n valueChanged: false,\n changed: false\n };\n _this._buttons = new Array(vrGamepad.buttons.length);\n _this.hand = vrGamepad.hand;\n return _this;\n }\n /**\n * Fired when a controller button's state has changed\n * @param callback the callback containing the button that was modified\n */\n WebVRController.prototype.onButtonStateChange = function (callback) {\n this._onButtonStateChange = callback;\n };\n Object.defineProperty(WebVRController.prototype, \"defaultModel\", {\n /**\n * The default controller model for the controller\n */\n get: function () {\n return this._defaultModel;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Updates the state of the controller and mesh based on the current position and rotation of the controller\n */\n WebVRController.prototype.update = function () {\n _super.prototype.update.call(this);\n for (var index = 0; index < this._buttons.length; index++) {\n this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);\n }\n ;\n if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {\n this.pad.x = this.leftStick.x;\n this.pad.y = this.leftStick.y;\n this.onPadValuesChangedObservable.notifyObservers(this.pad);\n }\n };\n WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {\n if (!newState) {\n newState = {\n pressed: false,\n touched: false,\n value: 0\n };\n }\n if (!currentState) {\n this._buttons[buttonIndex] = {\n pressed: newState.pressed,\n touched: newState.touched,\n value: newState.value\n };\n return;\n }\n this._checkChanges(newState, currentState);\n if (this._changes.changed) {\n this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);\n this._handleButtonChange(buttonIndex, newState, this._changes);\n }\n this._buttons[buttonIndex].pressed = newState.pressed;\n this._buttons[buttonIndex].touched = newState.touched;\n // oculus triggers are never 0, thou not touched.\n this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;\n };\n WebVRController.prototype._checkChanges = function (newState, currentState) {\n this._changes.pressChanged = newState.pressed !== currentState.pressed;\n this._changes.touchChanged = newState.touched !== currentState.touched;\n this._changes.valueChanged = newState.value !== currentState.value;\n this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;\n return this._changes;\n };\n /**\n * Disposes of th webVRCOntroller\n */\n WebVRController.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this.onTriggerStateChangedObservable.clear();\n this.onMainButtonStateChangedObservable.clear();\n this.onSecondaryButtonStateChangedObservable.clear();\n this.onPadStateChangedObservable.clear();\n this.onPadValuesChangedObservable.clear();\n };\n return WebVRController;\n }(BABYLON.PoseEnabledController));\n BABYLON.WebVRController = WebVRController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.webVRController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Oculus Touch Controller\n */\n var OculusTouchController = /** @class */ (function (_super) {\n __extends(OculusTouchController, _super);\n /**\n * Creates a new OculusTouchController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n function OculusTouchController(vrGamepad) {\n var _this = _super.call(this, vrGamepad) || this;\n /**\n * Fired when the secondary trigger on this controller is modified\n */\n _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();\n /**\n * Fired when the thumb rest on this controller is modified\n */\n _this.onThumbRestChangedObservable = new BABYLON.Observable();\n _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;\n return _this;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {\n var _this = this;\n var meshName;\n // Hand\n if (this.hand === 'left') {\n meshName = OculusTouchController.MODEL_LEFT_FILENAME;\n }\n else { // Right is the default if no hand is specified\n meshName = OculusTouchController.MODEL_RIGHT_FILENAME;\n }\n BABYLON.SceneLoader.ImportMesh(\"\", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {\n /*\n Parent Mesh name: oculus_touch_left\n - body\n - trigger\n - thumbstick\n - grip\n - button_y\n - button_x\n - button_enter\n */\n _this._defaultModel = newMeshes[1];\n _this.attachToMesh(_this._defaultModel);\n if (meshLoaded) {\n meshLoaded(_this._defaultModel);\n }\n });\n };\n Object.defineProperty(OculusTouchController.prototype, \"onAButtonStateChangedObservable\", {\n /**\n * Fired when the A button on this controller is modified\n */\n get: function () {\n if (this.hand === 'right') {\n return this.onMainButtonStateChangedObservable;\n }\n else {\n throw new Error('No A button on left hand');\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(OculusTouchController.prototype, \"onBButtonStateChangedObservable\", {\n /**\n * Fired when the B button on this controller is modified\n */\n get: function () {\n if (this.hand === 'right') {\n return this.onSecondaryButtonStateChangedObservable;\n }\n else {\n throw new Error('No B button on left hand');\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(OculusTouchController.prototype, \"onXButtonStateChangedObservable\", {\n /**\n * Fired when the X button on this controller is modified\n */\n get: function () {\n if (this.hand === 'left') {\n return this.onMainButtonStateChangedObservable;\n }\n else {\n throw new Error('No X button on right hand');\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(OculusTouchController.prototype, \"onYButtonStateChangedObservable\", {\n /**\n * Fired when the Y button on this controller is modified\n */\n get: function () {\n if (this.hand === 'left') {\n return this.onSecondaryButtonStateChangedObservable;\n }\n else {\n throw new Error('No Y button on right hand');\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Called once for each button that changed state since the last frame\n * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick\n * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)\n * 2) secondary trigger (same)\n * 3) A (right) X (left), touch, pressed = value\n * 4) B / Y\n * 5) thumb rest\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n * @param changes Which properties on the state changed since last frame\n */\n OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {\n var notifyObject = state; //{ state: state, changes: changes };\n var triggerDirection = this.hand === 'right' ? -1 : 1;\n switch (buttonIdx) {\n case 0:\n this.onPadStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 1: // index trigger\n if (this._defaultModel) {\n (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;\n (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;\n (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;\n }\n this.onTriggerStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 2: // secondary trigger\n if (this._defaultModel) {\n (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;\n }\n this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 3:\n if (this._defaultModel) {\n if (notifyObject.pressed) {\n (this._defaultModel.getChildren()[1]).position.y = -0.001;\n }\n else {\n (this._defaultModel.getChildren()[1]).position.y = 0;\n }\n }\n this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 4:\n if (this._defaultModel) {\n if (notifyObject.pressed) {\n (this._defaultModel.getChildren()[2]).position.y = -0.001;\n }\n else {\n (this._defaultModel.getChildren()[2]).position.y = 0;\n }\n }\n this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 5:\n this.onThumbRestChangedObservable.notifyObservers(notifyObject);\n return;\n }\n };\n /**\n * Base Url for the controller model.\n */\n OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';\n /**\n * File name for the left controller model.\n */\n OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';\n /**\n * File name for the right controller model.\n */\n OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';\n return OculusTouchController;\n }(BABYLON.WebVRController));\n BABYLON.OculusTouchController = OculusTouchController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.oculusTouchController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Vive Controller\n */\n var ViveController = /** @class */ (function (_super) {\n __extends(ViveController, _super);\n /**\n * Creates a new ViveController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n function ViveController(vrGamepad) {\n var _this = _super.call(this, vrGamepad) || this;\n _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;\n _this._invertLeftStickY = true;\n return _this;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {\n var _this = this;\n BABYLON.SceneLoader.ImportMesh(\"\", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {\n /*\n Parent Mesh name: ViveWand\n - body\n - r_gripper\n - l_gripper\n - menu_button\n - system_button\n - trackpad\n - trigger\n - LED\n */\n _this._defaultModel = newMeshes[1];\n _this.attachToMesh(_this._defaultModel);\n if (meshLoaded) {\n meshLoaded(_this._defaultModel);\n }\n });\n };\n Object.defineProperty(ViveController.prototype, \"onLeftButtonStateChangedObservable\", {\n /**\n * Fired when the left button on this controller is modified\n */\n get: function () {\n return this.onMainButtonStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ViveController.prototype, \"onRightButtonStateChangedObservable\", {\n /**\n * Fired when the right button on this controller is modified\n */\n get: function () {\n return this.onMainButtonStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ViveController.prototype, \"onMenuButtonStateChangedObservable\", {\n /**\n * Fired when the menu button on this controller is modified\n */\n get: function () {\n return this.onSecondaryButtonStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Called once for each button that changed state since the last frame\n * Vive mapping:\n * 0: touchpad\n * 1: trigger\n * 2: left AND right buttons\n * 3: menu button\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n * @param changes Which properties on the state changed since last frame\n */\n ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {\n var notifyObject = state; //{ state: state, changes: changes };\n switch (buttonIdx) {\n case 0:\n this.onPadStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 1: // index trigger\n if (this._defaultModel) {\n (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;\n }\n this.onTriggerStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 2: // left AND right button\n this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 3:\n if (this._defaultModel) {\n if (notifyObject.pressed) {\n (this._defaultModel.getChildren()[2]).position.y = -0.001;\n }\n else {\n (this._defaultModel.getChildren()[2]).position.y = 0;\n }\n }\n this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n }\n };\n /**\n * Base Url for the controller model.\n */\n ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';\n /**\n * File name for the controller model.\n */\n ViveController.MODEL_FILENAME = 'wand.babylon';\n return ViveController;\n }(BABYLON.WebVRController));\n BABYLON.ViveController = ViveController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.viveController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Generic Controller\n */\n var GenericController = /** @class */ (function (_super) {\n __extends(GenericController, _super);\n /**\n * Creates a new GenericController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n function GenericController(vrGamepad) {\n return _super.call(this, vrGamepad) || this;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {\n var _this = this;\n BABYLON.SceneLoader.ImportMesh(\"\", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {\n _this._defaultModel = newMeshes[1];\n _this.attachToMesh(_this._defaultModel);\n if (meshLoaded) {\n meshLoaded(_this._defaultModel);\n }\n });\n };\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n * @param changes Which properties on the state changed since last frame\n */\n GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {\n console.log(\"Button id: \" + buttonIdx + \"state: \");\n console.dir(state);\n };\n /**\n * Base Url for the controller model.\n */\n GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';\n /**\n * File name for the controller model.\n */\n GenericController.MODEL_FILENAME = 'generic.babylon';\n return GenericController;\n }(BABYLON.WebVRController));\n BABYLON.GenericController = GenericController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.genericController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh\n */\n var LoadedMeshInfo = /** @class */ (function () {\n function LoadedMeshInfo() {\n /**\n * Map of the button meshes contained in the controller\n */\n this.buttonMeshes = {};\n /**\n * Map of the axis meshes contained in the controller\n */\n this.axisMeshes = {};\n }\n return LoadedMeshInfo;\n }());\n /**\n * Defines the WindowsMotionController object that the state of the windows motion controller\n */\n var WindowsMotionController = /** @class */ (function (_super) {\n __extends(WindowsMotionController, _super);\n /**\n * Creates a new WindowsMotionController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n function WindowsMotionController(vrGamepad) {\n var _this = _super.call(this, vrGamepad) || this;\n _this._mapping = {\n // Semantic button names\n buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],\n // A mapping of the button name to glTF model node name\n // that should be transformed by button value.\n buttonMeshNames: {\n 'trigger': 'SELECT',\n 'menu': 'MENU',\n 'grip': 'GRASP',\n 'thumbstick': 'THUMBSTICK_PRESS',\n 'trackpad': 'TOUCHPAD_PRESS'\n },\n // This mapping is used to translate from the Motion Controller to Babylon semantics\n buttonObservableNames: {\n 'trigger': 'onTriggerStateChangedObservable',\n 'menu': 'onSecondaryButtonStateChangedObservable',\n 'grip': 'onMainButtonStateChangedObservable',\n 'thumbstick': 'onPadStateChangedObservable',\n 'trackpad': 'onTrackpadChangedObservable'\n },\n // A mapping of the axis name to glTF model node name\n // that should be transformed by axis value.\n // This array mirrors the browserGamepad.axes array, such that \n // the mesh corresponding to axis 0 is in this array index 0.\n axisMeshNames: [\n 'THUMBSTICK_X',\n 'THUMBSTICK_Y',\n 'TOUCHPAD_TOUCH_X',\n 'TOUCHPAD_TOUCH_Y'\n ],\n pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE\n };\n /**\n * Fired when the trackpad on this controller is clicked\n */\n _this.onTrackpadChangedObservable = new BABYLON.Observable();\n /**\n * Fired when the trackpad on this controller is modified\n */\n _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();\n /**\n * The current x and y values of this controller's trackpad\n */\n _this.trackpad = { x: 0, y: 0 };\n _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;\n _this._loadedMeshInfo = null;\n return _this;\n }\n Object.defineProperty(WindowsMotionController.prototype, \"onTriggerButtonStateChangedObservable\", {\n /**\n * Fired when the trigger on this controller is modified\n */\n get: function () {\n return this.onTriggerStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WindowsMotionController.prototype, \"onMenuButtonStateChangedObservable\", {\n /**\n * Fired when the menu button on this controller is modified\n */\n get: function () {\n return this.onSecondaryButtonStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WindowsMotionController.prototype, \"onGripButtonStateChangedObservable\", {\n /**\n * Fired when the grip button on this controller is modified\n */\n get: function () {\n return this.onMainButtonStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WindowsMotionController.prototype, \"onThumbstickButtonStateChangedObservable\", {\n /**\n * Fired when the thumbstick button on this controller is modified\n */\n get: function () {\n return this.onPadStateChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WindowsMotionController.prototype, \"onTouchpadButtonStateChangedObservable\", {\n /**\n * Fired when the touchpad button on this controller is modified\n */\n get: function () {\n return this.onTrackpadChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WindowsMotionController.prototype, \"onTouchpadValuesChangedObservable\", {\n /**\n * Fired when the touchpad values on this controller are modified\n */\n get: function () {\n return this.onTrackpadValuesChangedObservable;\n },\n enumerable: true,\n configurable: true\n });\n WindowsMotionController.prototype._updateTrackpad = function () {\n if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {\n this.trackpad.x = this.browserGamepad[\"axes\"][2];\n this.trackpad.y = this.browserGamepad[\"axes\"][3];\n this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);\n }\n };\n /**\n * Called once per frame by the engine.\n */\n WindowsMotionController.prototype.update = function () {\n _super.prototype.update.call(this);\n if (this.browserGamepad.axes) {\n this._updateTrackpad();\n // Only need to animate axes if there is a loaded mesh\n if (this._loadedMeshInfo) {\n for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {\n this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);\n }\n }\n }\n };\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n * @param changes Which properties on the state changed since last frame\n */\n WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {\n var buttonName = this._mapping.buttons[buttonIdx];\n if (!buttonName) {\n return;\n }\n // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames\n this._updateTrackpad();\n // Only emit events for buttons that we know how to map from index to name\n var observable = this[(this._mapping.buttonObservableNames)[buttonName]];\n if (observable) {\n observable.notifyObservers(state);\n }\n this._lerpButtonTransform(buttonName, state.value);\n };\n /**\n * Moves the buttons on the controller mesh based on their current state\n * @param buttonName the name of the button to move\n * @param buttonValue the value of the button which determines the buttons new position\n */\n WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {\n // If there is no loaded mesh, there is nothing to transform.\n if (!this._loadedMeshInfo) {\n return;\n }\n var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];\n if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {\n return;\n }\n BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);\n BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);\n };\n /**\n * Moves the axis on the controller mesh based on its current state\n * @param axis the index of the axis\n * @param axisValue the value of the axis which determines the meshes new position\n * @hidden\n */\n WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {\n if (!this._loadedMeshInfo) {\n return;\n }\n var meshInfo = this._loadedMeshInfo.axisMeshes[axis];\n if (!meshInfo) {\n return;\n }\n if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {\n return;\n }\n // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)\n var lerpValue = axisValue * 0.5 + 0.5;\n BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);\n BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);\n };\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {\n var _this = this;\n if (forceDefault === void 0) { forceDefault = false; }\n var path;\n var filename;\n // Checking if GLB loader is present\n if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(\".glb\")) {\n // Determine the device specific folder based on the ID suffix\n var device = 'default';\n if (this.id && !forceDefault) {\n var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);\n device = ((match && match[0]) || device);\n }\n // Hand\n if (this.hand === 'left') {\n filename = WindowsMotionController.MODEL_LEFT_FILENAME;\n }\n else { // Right is the default if no hand is specified\n filename = WindowsMotionController.MODEL_RIGHT_FILENAME;\n }\n path = WindowsMotionController.MODEL_BASE_URL + device + '/';\n }\n else {\n BABYLON.Tools.Warn(\"You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models\");\n path = BABYLON.GenericController.MODEL_BASE_URL;\n filename = BABYLON.GenericController.MODEL_FILENAME;\n }\n BABYLON.SceneLoader.ImportMesh(\"\", path, filename, scene, function (meshes) {\n // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.\n _this._loadedMeshInfo = _this.processModel(scene, meshes);\n if (!_this._loadedMeshInfo) {\n return;\n }\n _this._defaultModel = _this._loadedMeshInfo.rootNode;\n _this.attachToMesh(_this._defaultModel);\n if (meshLoaded) {\n meshLoaded(_this._defaultModel);\n }\n }, null, function (scene, message) {\n BABYLON.Tools.Log(message);\n BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);\n if (!forceDefault) {\n _this.initControllerMesh(scene, meshLoaded, true);\n }\n });\n };\n /**\n * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that\n * can be transformed by button presses and axes values, based on this._mapping.\n *\n * @param scene scene in which the meshes exist\n * @param meshes list of meshes that make up the controller model to process\n * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.\n */\n WindowsMotionController.prototype.processModel = function (scene, meshes) {\n var loadedMeshInfo = null;\n // Create a new mesh to contain the glTF hierarchy\n var parentMesh = new BABYLON.Mesh(this.id + \" \" + this.hand, scene);\n // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'\n var childMesh = null;\n for (var i = 0; i < meshes.length; i++) {\n var mesh = meshes[i];\n if (!mesh.parent) {\n // Exclude controller meshes from picking results\n mesh.isPickable = false;\n // Handle root node, attach to the new parentMesh\n childMesh = mesh;\n break;\n }\n }\n if (childMesh) {\n childMesh.setParent(parentMesh);\n // Create our mesh info. Note that this method will always return non-null.\n loadedMeshInfo = this.createMeshInfo(parentMesh);\n }\n else {\n BABYLON.Tools.Warn('Could not find root node in model file.');\n }\n return loadedMeshInfo;\n };\n WindowsMotionController.prototype.createMeshInfo = function (rootNode) {\n var loadedMeshInfo = new LoadedMeshInfo();\n var i;\n loadedMeshInfo.rootNode = rootNode;\n // Reset the caches\n loadedMeshInfo.buttonMeshes = {};\n loadedMeshInfo.axisMeshes = {};\n // Button Meshes\n for (i = 0; i < this._mapping.buttons.length; i++) {\n var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];\n if (!buttonMeshName) {\n BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);\n continue;\n }\n var buttonMesh = getChildByName(rootNode, buttonMeshName);\n if (!buttonMesh) {\n BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);\n continue;\n }\n var buttonMeshInfo = {\n index: i,\n value: getImmediateChildByName(buttonMesh, 'VALUE'),\n pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),\n unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')\n };\n if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {\n loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;\n }\n else {\n // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.\n BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +\n '(VALUE: ' + !!buttonMeshInfo.value +\n ', PRESSED: ' + !!buttonMeshInfo.pressed +\n ', UNPRESSED:' + !!buttonMeshInfo.unpressed +\n ')');\n }\n }\n // Axis Meshes\n for (i = 0; i < this._mapping.axisMeshNames.length; i++) {\n var axisMeshName = this._mapping.axisMeshNames[i];\n if (!axisMeshName) {\n BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);\n continue;\n }\n var axisMesh = getChildByName(rootNode, axisMeshName);\n if (!axisMesh) {\n BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);\n continue;\n }\n var axisMeshInfo = {\n index: i,\n value: getImmediateChildByName(axisMesh, 'VALUE'),\n min: getImmediateChildByName(axisMesh, 'MIN'),\n max: getImmediateChildByName(axisMesh, 'MAX')\n };\n if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {\n loadedMeshInfo.axisMeshes[i] = axisMeshInfo;\n }\n else {\n // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.\n BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +\n '(VALUE: ' + !!axisMeshInfo.value +\n ', MIN: ' + !!axisMeshInfo.min +\n ', MAX:' + !!axisMeshInfo.max +\n ')');\n }\n }\n // Pointing Ray\n loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);\n if (!loadedMeshInfo.pointingPoseNode) {\n BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);\n }\n else {\n this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;\n }\n return loadedMeshInfo;\n // Look through all children recursively. This will return null if no mesh exists with the given name.\n function getChildByName(node, name) {\n return node.getChildMeshes(false, function (n) { return n.name === name; })[0];\n }\n // Look through only immediate children. This will return null if no mesh exists with the given name.\n function getImmediateChildByName(node, name) {\n return node.getChildMeshes(true, function (n) { return n.name == name; })[0];\n }\n };\n /**\n * Gets the ray of the controller in the direction the controller is pointing\n * @param length the length the resulting ray should be\n * @returns a ray in the direction the controller is pointing\n */\n WindowsMotionController.prototype.getForwardRay = function (length) {\n if (length === void 0) { length = 100; }\n if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {\n return _super.prototype.getForwardRay.call(this, length);\n }\n var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();\n var origin = m.getTranslation();\n var forward = new BABYLON.Vector3(0, 0, -1);\n var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);\n var direction = BABYLON.Vector3.Normalize(forwardWorld);\n return new BABYLON.Ray(origin, direction, length);\n };\n /**\n * Disposes of the controller\n */\n WindowsMotionController.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this.onTrackpadChangedObservable.clear();\n };\n /**\n * The base url used to load the left and right controller models\n */\n WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';\n /**\n * The name of the left controller model file\n */\n WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';\n /**\n * The name of the right controller model file\n */\n WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';\n /**\n * The controller name prefix for this controller type\n */\n WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';\n /**\n * The controller id pattern for this controller type\n */\n WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;\n return WindowsMotionController;\n }(BABYLON.WebVRController));\n BABYLON.WindowsMotionController = WindowsMotionController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.windowsMotionController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Gear VR Controller\n */\n var GearVRController = /** @class */ (function (_super) {\n __extends(GearVRController, _super);\n /**\n * Creates a new GearVRController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n function GearVRController(vrGamepad) {\n var _this = _super.call(this, vrGamepad) || this;\n _this._maxRotationDistFromHeadset = Math.PI / 5;\n _this._draggedRoomRotation = 0;\n _this._tmpVector = new BABYLON.Vector3();\n _this._buttonIndexToObservableNameMap = [\n 'onTrackpadChangedObservable',\n 'onTriggerStateChangedObservable' // Trigger\n ];\n _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;\n // Initial starting position defaults to where hand would be (incase of only 3dof controller)\n _this._calculatedPosition = new BABYLON.Vector3(_this.hand == \"left\" ? -0.15 : 0.15, -0.5, 0.25);\n return _this;\n }\n /**\n * Updates the state of the pose enbaled controller based on the raw pose data from the device\n * @param poseData raw pose fromthe device\n */\n GearVRController.prototype.updateFromDevice = function (poseData) {\n _super.prototype.updateFromDevice.call(this, poseData);\n if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {\n if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {\n var camera = BABYLON.Engine.LastCreatedScene.activeCamera;\n camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);\n // Find the radian distance away that the headset is from the controllers rotation\n var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));\n if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {\n // Only rotate enouph to be within the _maxRotationDistFromHeadset\n var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);\n this._draggedRoomRotation += rotationAmount;\n // Rotate controller around headset\n var sin = Math.sin(-rotationAmount);\n var cos = Math.cos(-rotationAmount);\n this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;\n this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;\n }\n }\n }\n };\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {\n var _this = this;\n BABYLON.SceneLoader.ImportMesh(\"\", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {\n // Offset the controller so it will rotate around the users wrist\n var mesh = new BABYLON.Mesh(\"\", scene);\n newMeshes[1].parent = mesh;\n newMeshes[1].position.z = -0.15;\n _this._defaultModel = mesh;\n _this.attachToMesh(_this._defaultModel);\n if (meshLoaded) {\n meshLoaded(_this._defaultModel);\n }\n });\n };\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n * @param changes Which properties on the state changed since last frame\n */\n GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {\n if (buttonIdx < this._buttonIndexToObservableNameMap.length) {\n var observableName = this._buttonIndexToObservableNameMap[buttonIdx];\n // Only emit events for buttons that we know how to map from index to observable\n var observable = this[observableName];\n if (observable) {\n observable.notifyObservers(state);\n }\n }\n };\n /**\n * Base Url for the controller model.\n */\n GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';\n /**\n * File name for the controller model.\n */\n GearVRController.MODEL_FILENAME = 'generic.babylon';\n /**\n * Gamepad Id prefix used to identify this controller.\n */\n GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'\n return GearVRController;\n }(BABYLON.WebVRController));\n BABYLON.GearVRController = GearVRController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gearVRController.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Google Daydream controller\n */\n var DaydreamController = /** @class */ (function (_super) {\n __extends(DaydreamController, _super);\n /**\n * Creates a new DaydreamController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n function DaydreamController(vrGamepad) {\n var _this = _super.call(this, vrGamepad) || this;\n _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;\n return _this;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {\n var _this = this;\n BABYLON.SceneLoader.ImportMesh(\"\", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {\n _this._defaultModel = newMeshes[1];\n _this.attachToMesh(_this._defaultModel);\n if (meshLoaded) {\n meshLoaded(_this._defaultModel);\n }\n });\n };\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n * @param changes Which properties on the state changed since last frame\n */\n DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {\n // Daydream controller only has 1 GamepadButton (on the trackpad).\n if (buttonIdx === 0) {\n var observable = this.onTriggerStateChangedObservable;\n if (observable) {\n observable.notifyObservers(state);\n }\n }\n else {\n // If the app or home buttons are ever made available\n BABYLON.Tools.Warn(\"Unrecognized Daydream button index: \" + buttonIdx);\n }\n };\n /**\n * Base Url for the controller model.\n */\n DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';\n /**\n * File name for the controller model.\n */\n DaydreamController.MODEL_FILENAME = 'generic.babylon';\n /**\n * Gamepad Id prefix used to identify Daydream Controller.\n */\n DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'\n return DaydreamController;\n }(BABYLON.WebVRController));\n BABYLON.DaydreamController = DaydreamController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.daydreamController.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n Object.defineProperty(BABYLON.Scene.prototype, \"gamepadManager\", {\n get: function () {\n if (!this._gamepadManager) {\n this._gamepadManager = new BABYLON.GamepadManager(this);\n var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);\n if (!component) {\n component = new GamepadSystemSceneComponent(this);\n this._addComponent(component);\n }\n }\n return this._gamepadManager;\n },\n enumerable: true,\n configurable: true\n });\n BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {\n this.add(new BABYLON.FreeCameraGamepadInput());\n return this;\n };\n BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {\n this.add(new BABYLON.ArcRotateCameraGamepadInput());\n return this;\n };\n /**\n * Defines the gamepad scene component responsible to manage gamepads in a given scene\n */\n var GamepadSystemSceneComponent = /** @class */ (function () {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n function GamepadSystemSceneComponent(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n GamepadSystemSceneComponent.prototype.register = function () {\n this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);\n };\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n GamepadSystemSceneComponent.prototype.rebuild = function () {\n // Nothing to do for gamepads\n };\n /**\n * Disposes the component and the associated ressources\n */\n GamepadSystemSceneComponent.prototype.dispose = function () {\n var gamepadManager = this.scene._gamepadManager;\n if (gamepadManager) {\n gamepadManager.dispose();\n this.scene._gamepadManager = null;\n }\n };\n GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {\n var gamepadManager = this.scene._gamepadManager;\n if (gamepadManager && gamepadManager._isMonitoring) {\n gamepadManager._checkGamepadsStatus();\n }\n };\n return GamepadSystemSceneComponent;\n }());\n BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gamepadSceneComponent.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"FollowCamera\", function (name, scene) {\n return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n BABYLON.Node.AddNodeConstructor(\"ArcFollowCamera\", function (name, scene) {\n return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };\n });\n var FollowCamera = /** @class */ (function (_super) {\n __extends(FollowCamera, _super);\n function FollowCamera(name, position, scene, lockedTarget) {\n if (lockedTarget === void 0) { lockedTarget = null; }\n var _this = _super.call(this, name, position, scene) || this;\n _this.radius = 12;\n _this.rotationOffset = 0;\n _this.heightOffset = 4;\n _this.cameraAcceleration = 0.05;\n _this.maxCameraSpeed = 20;\n _this.lockedTarget = lockedTarget;\n return _this;\n }\n FollowCamera.prototype.getRadians = function (degrees) {\n return degrees * Math.PI / 180;\n };\n FollowCamera.prototype.follow = function (cameraTarget) {\n if (!cameraTarget)\n return;\n var yRotation;\n if (cameraTarget.rotationQuaternion) {\n var rotMatrix = new BABYLON.Matrix();\n cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);\n yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);\n }\n else {\n yRotation = cameraTarget.rotation.y;\n }\n var radians = this.getRadians(this.rotationOffset) + yRotation;\n var targetPosition = cameraTarget.getAbsolutePosition();\n var targetX = targetPosition.x + Math.sin(radians) * this.radius;\n var targetZ = targetPosition.z + Math.cos(radians) * this.radius;\n var dx = targetX - this.position.x;\n var dy = (targetPosition.y + this.heightOffset) - this.position.y;\n var dz = (targetZ) - this.position.z;\n var vx = dx * this.cameraAcceleration * 2; //this is set to .05\n var vy = dy * this.cameraAcceleration;\n var vz = dz * this.cameraAcceleration * 2;\n if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {\n vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;\n }\n if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {\n vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;\n }\n if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {\n vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;\n }\n this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);\n this.setTarget(targetPosition);\n };\n FollowCamera.prototype._checkInputs = function () {\n _super.prototype._checkInputs.call(this);\n if (this.lockedTarget) {\n this.follow(this.lockedTarget);\n }\n };\n FollowCamera.prototype.getClassName = function () {\n return \"FollowCamera\";\n };\n __decorate([\n BABYLON.serialize()\n ], FollowCamera.prototype, \"radius\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FollowCamera.prototype, \"rotationOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FollowCamera.prototype, \"heightOffset\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FollowCamera.prototype, \"cameraAcceleration\", void 0);\n __decorate([\n BABYLON.serialize()\n ], FollowCamera.prototype, \"maxCameraSpeed\", void 0);\n __decorate([\n BABYLON.serializeAsMeshReference(\"lockedTargetId\")\n ], FollowCamera.prototype, \"lockedTarget\", void 0);\n return FollowCamera;\n }(BABYLON.TargetCamera));\n BABYLON.FollowCamera = FollowCamera;\n var ArcFollowCamera = /** @class */ (function (_super) {\n __extends(ArcFollowCamera, _super);\n function ArcFollowCamera(name, alpha, beta, radius, target, scene) {\n var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;\n _this.alpha = alpha;\n _this.beta = beta;\n _this.radius = radius;\n _this.target = target;\n _this._cartesianCoordinates = BABYLON.Vector3.Zero();\n _this.follow();\n return _this;\n }\n ArcFollowCamera.prototype.follow = function () {\n if (!this.target) {\n return;\n }\n this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);\n this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);\n this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);\n var targetPosition = this.target.getAbsolutePosition();\n this.position = targetPosition.add(this._cartesianCoordinates);\n this.setTarget(targetPosition);\n };\n ArcFollowCamera.prototype._checkInputs = function () {\n _super.prototype._checkInputs.call(this);\n this.follow();\n };\n ArcFollowCamera.prototype.getClassName = function () {\n return \"ArcFollowCamera\";\n };\n return ArcFollowCamera;\n }(BABYLON.TargetCamera));\n BABYLON.ArcFollowCamera = ArcFollowCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.followCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n // We're mainly based on the logic defined into the FreeCamera code\n var UniversalCamera = /** @class */ (function (_super) {\n __extends(UniversalCamera, _super);\n //-- end properties for backward compatibility for inputs\n function UniversalCamera(name, position, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.inputs.addGamepad();\n return _this;\n }\n Object.defineProperty(UniversalCamera.prototype, \"gamepadAngularSensibility\", {\n //-- Begin properties for backward compatibility for inputs\n get: function () {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n return gamepad.gamepadAngularSensibility;\n return 0;\n },\n set: function (value) {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n gamepad.gamepadAngularSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(UniversalCamera.prototype, \"gamepadMoveSensibility\", {\n get: function () {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n return gamepad.gamepadMoveSensibility;\n return 0;\n },\n set: function (value) {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n gamepad.gamepadMoveSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n UniversalCamera.prototype.getClassName = function () {\n return \"UniversalCamera\";\n };\n return UniversalCamera;\n }(BABYLON.TouchCamera));\n BABYLON.UniversalCamera = UniversalCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.universalCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"GamepadCamera\", function (name, scene) {\n return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n // We're mainly based on the logic defined into the FreeCamera code\n var GamepadCamera = /** @class */ (function (_super) {\n __extends(GamepadCamera, _super);\n //-- end properties for backward compatibility for inputs\n function GamepadCamera(name, position, scene) {\n return _super.call(this, name, position, scene) || this;\n }\n Object.defineProperty(GamepadCamera.prototype, \"gamepadAngularSensibility\", {\n //-- Begin properties for backward compatibility for inputs\n get: function () {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n return gamepad.gamepadAngularSensibility;\n return 0;\n },\n set: function (value) {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n gamepad.gamepadAngularSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GamepadCamera.prototype, \"gamepadMoveSensibility\", {\n get: function () {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n return gamepad.gamepadMoveSensibility;\n return 0;\n },\n set: function (value) {\n var gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad)\n gamepad.gamepadMoveSensibility = value;\n },\n enumerable: true,\n configurable: true\n });\n GamepadCamera.prototype.getClassName = function () {\n return \"GamepadCamera\";\n };\n return GamepadCamera;\n }(BABYLON.UniversalCamera));\n BABYLON.GamepadCamera = GamepadCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gamepadCamera.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var PostProcessRenderPipelineManager = /** @class */ (function () {\n function PostProcessRenderPipelineManager() {\n this._renderPipelines = {};\n }\n PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {\n this._renderPipelines[renderPipeline._name] = renderPipeline;\n };\n PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {\n if (unique === void 0) { unique = false; }\n var renderPipeline = this._renderPipelines[renderPipelineName];\n if (!renderPipeline) {\n return;\n }\n renderPipeline._attachCameras(cameras, unique);\n };\n PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {\n var renderPipeline = this._renderPipelines[renderPipelineName];\n if (!renderPipeline) {\n return;\n }\n renderPipeline._detachCameras(cameras);\n };\n PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {\n var renderPipeline = this._renderPipelines[renderPipelineName];\n if (!renderPipeline) {\n return;\n }\n renderPipeline._enableEffect(renderEffectName, cameras);\n };\n PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {\n var renderPipeline = this._renderPipelines[renderPipelineName];\n if (!renderPipeline) {\n return;\n }\n renderPipeline._disableEffect(renderEffectName, cameras);\n };\n PostProcessRenderPipelineManager.prototype.update = function () {\n for (var renderPipelineName in this._renderPipelines) {\n if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {\n var pipeline = this._renderPipelines[renderPipelineName];\n if (!pipeline.isSupported) {\n pipeline.dispose();\n delete this._renderPipelines[renderPipelineName];\n }\n else {\n pipeline._update();\n }\n }\n }\n };\n PostProcessRenderPipelineManager.prototype._rebuild = function () {\n for (var renderPipelineName in this._renderPipelines) {\n if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {\n var pipeline = this._renderPipelines[renderPipelineName];\n pipeline._rebuild();\n }\n }\n };\n PostProcessRenderPipelineManager.prototype.dispose = function () {\n for (var renderPipelineName in this._renderPipelines) {\n if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {\n var pipeline = this._renderPipelines[renderPipelineName];\n pipeline.dispose();\n }\n }\n };\n return PostProcessRenderPipelineManager;\n }());\n BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This represents a set of one or more post processes in Babylon.\n * A post process can be used to apply a shader to a texture after it is rendered.\n * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline\n */\n var PostProcessRenderEffect = /** @class */ (function () {\n /**\n * Instantiates a post process render effect.\n * A post process can be used to apply a shader to a texture after it is rendered.\n * @param engine The engine the effect is tied to\n * @param name The name of the effect\n * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.\n * @param singleInstance False if this post process can be run on multiple cameras. (default: true)\n */\n function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {\n this._name = name;\n this._singleInstance = singleInstance || true;\n this._getPostProcesses = getPostProcesses;\n this._cameras = {};\n this._indicesForCamera = {};\n this._postProcesses = {};\n }\n Object.defineProperty(PostProcessRenderEffect.prototype, \"isSupported\", {\n /**\n * Checks if all the post processes in the effect are supported.\n */\n get: function () {\n for (var index in this._postProcesses) {\n if (this._postProcesses.hasOwnProperty(index)) {\n var pps = this._postProcesses[index];\n for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {\n if (!pps[ppIndex].isSupported) {\n return false;\n }\n }\n }\n }\n return true;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Updates the current state of the effect\n */\n PostProcessRenderEffect.prototype._update = function () {\n };\n /**\n * Attaches the effect on cameras\n * @param cameras The camera to attach to.\n */\n PostProcessRenderEffect.prototype._attachCameras = function (cameras) {\n var _this = this;\n var cameraKey;\n var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (var i = 0; i < cams.length; i++) {\n var camera = cams[i];\n var cameraName = camera.name;\n if (this._singleInstance) {\n cameraKey = 0;\n }\n else {\n cameraKey = cameraName;\n }\n if (!this._postProcesses[cameraKey]) {\n var postProcess = this._getPostProcesses();\n if (postProcess) {\n this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];\n }\n }\n if (!this._indicesForCamera[cameraName]) {\n this._indicesForCamera[cameraName] = [];\n }\n this._postProcesses[cameraKey].forEach(function (postProcess) {\n var index = camera.attachPostProcess(postProcess);\n _this._indicesForCamera[cameraName].push(index);\n });\n if (!this._cameras[cameraName]) {\n this._cameras[cameraName] = camera;\n }\n }\n };\n /**\n * Detatches the effect on cameras\n * @param cameras The camera to detatch from.\n */\n PostProcessRenderEffect.prototype._detachCameras = function (cameras) {\n var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (var i = 0; i < cams.length; i++) {\n var camera = cams[i];\n var cameraName = camera.name;\n this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {\n camera.detachPostProcess(postProcess);\n });\n if (this._cameras[cameraName]) {\n //this._indicesForCamera.splice(index, 1);\n this._cameras[cameraName] = null;\n }\n }\n };\n /**\n * Enables the effect on given cameras\n * @param cameras The camera to enable.\n */\n PostProcessRenderEffect.prototype._enable = function (cameras) {\n var _this = this;\n var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (var i = 0; i < cams.length; i++) {\n var camera = cams[i];\n var cameraName = camera.name;\n for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {\n if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {\n this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {\n cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);\n });\n }\n }\n }\n };\n /**\n * Disables the effect on the given cameras\n * @param cameras The camera to disable.\n */\n PostProcessRenderEffect.prototype._disable = function (cameras) {\n var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (var i = 0; i < cams.length; i++) {\n var camera = cams[i];\n var cameraName = camera.name;\n this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {\n camera.detachPostProcess(postProcess);\n });\n }\n };\n /**\n * Gets a list of the post processes contained in the effect.\n * @param camera The camera to get the post processes on.\n * @returns The list of the post processes in the effect.\n */\n PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {\n if (this._singleInstance) {\n return this._postProcesses[0];\n }\n else {\n if (!camera) {\n return null;\n }\n return this._postProcesses[camera.name];\n }\n };\n return PostProcessRenderEffect;\n }());\n BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.postProcessRenderEffect.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var PostProcessRenderPipeline = /** @class */ (function () {\n function PostProcessRenderPipeline(engine, name) {\n this.engine = engine;\n this._name = name;\n this._renderEffects = {};\n this._renderEffectsForIsolatedPass = new Array();\n this._cameras = [];\n }\n PostProcessRenderPipeline.prototype.getClassName = function () {\n return \"PostProcessRenderPipeline\";\n };\n Object.defineProperty(PostProcessRenderPipeline.prototype, \"isSupported\", {\n get: function () {\n for (var renderEffectName in this._renderEffects) {\n if (this._renderEffects.hasOwnProperty(renderEffectName)) {\n if (!this._renderEffects[renderEffectName].isSupported) {\n return false;\n }\n }\n }\n return true;\n },\n enumerable: true,\n configurable: true\n });\n PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {\n this._renderEffects[renderEffect._name] = renderEffect;\n };\n // private\n PostProcessRenderPipeline.prototype._rebuild = function () {\n };\n PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {\n var renderEffects = this._renderEffects[renderEffectName];\n if (!renderEffects) {\n return;\n }\n renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));\n };\n PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {\n var renderEffects = this._renderEffects[renderEffectName];\n if (!renderEffects) {\n return;\n }\n renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));\n };\n PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {\n var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n var indicesToDelete = [];\n var i;\n for (i = 0; i < cams.length; i++) {\n var camera = cams[i];\n var cameraName = camera.name;\n if (this._cameras.indexOf(camera) === -1) {\n this._cameras[cameraName] = camera;\n }\n else if (unique) {\n indicesToDelete.push(i);\n }\n }\n for (i = 0; i < indicesToDelete.length; i++) {\n cameras.splice(indicesToDelete[i], 1);\n }\n for (var renderEffectName in this._renderEffects) {\n if (this._renderEffects.hasOwnProperty(renderEffectName)) {\n this._renderEffects[renderEffectName]._attachCameras(cams);\n }\n }\n };\n PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {\n var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (var renderEffectName in this._renderEffects) {\n if (this._renderEffects.hasOwnProperty(renderEffectName)) {\n this._renderEffects[renderEffectName]._detachCameras(cams);\n }\n }\n for (var i = 0; i < cams.length; i++) {\n this._cameras.splice(this._cameras.indexOf(cams[i]), 1);\n }\n };\n PostProcessRenderPipeline.prototype._update = function () {\n for (var renderEffectName in this._renderEffects) {\n if (this._renderEffects.hasOwnProperty(renderEffectName)) {\n this._renderEffects[renderEffectName]._update();\n }\n }\n for (var i = 0; i < this._cameras.length; i++) {\n var cameraName = this._cameras[i].name;\n if (this._renderEffectsForIsolatedPass[cameraName]) {\n this._renderEffectsForIsolatedPass[cameraName]._update();\n }\n }\n };\n PostProcessRenderPipeline.prototype._reset = function () {\n this._renderEffects = {};\n this._renderEffectsForIsolatedPass = new Array();\n };\n PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {\n // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)\n var effectKeys = Object.keys(this._renderEffects);\n if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {\n var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();\n if (postProcesses) {\n postProcesses[0].samples = sampleCount;\n return true;\n }\n }\n return false;\n };\n PostProcessRenderPipeline.prototype.dispose = function () {\n // Must be implemented by children \n };\n __decorate([\n BABYLON.serialize()\n ], PostProcessRenderPipeline.prototype, \"_name\", void 0);\n return PostProcessRenderPipeline;\n }());\n BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.postProcessRenderPipeline.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This represents a depth renderer in Babylon.\n * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing\n */\n var DepthRenderer = /** @class */ (function () {\n /**\n * Instantiates a depth renderer\n * @param scene The scene the renderer belongs to\n * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)\n * @param camera The camera to be used to render the depth map (default: scene's active camera)\n */\n function DepthRenderer(scene, type, camera) {\n if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }\n if (camera === void 0) { camera = null; }\n var _this = this;\n this._scene = scene;\n this._camera = camera;\n var engine = scene.getEngine();\n // Render target\n this._depthMap = new BABYLON.RenderTargetTexture(\"depthMap\", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);\n this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._depthMap.refreshRate = 1;\n this._depthMap.renderParticles = false;\n this._depthMap.renderList = null;\n // Camera to get depth map from to support multiple concurrent cameras\n this._depthMap.activeCamera = this._camera;\n this._depthMap.ignoreCameraViewport = true;\n this._depthMap.useCameraPostProcesses = false;\n // set default depth value to 1.0 (far away)\n this._depthMap.onClearObservable.add(function (engine) {\n engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);\n });\n // Custom render function\n var renderSubMesh = function (subMesh) {\n var mesh = subMesh.getRenderingMesh();\n var scene = _this._scene;\n var engine = scene.getEngine();\n var material = subMesh.getMaterial();\n if (!material) {\n return;\n }\n // Culling and reverse (right handed system)\n engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);\n // Managing instances\n var batch = mesh._getInstancesRenderList(subMesh._id);\n if (batch.mustReturn) {\n return;\n }\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);\n var camera = _this._camera || scene.activeCamera;\n if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {\n engine.enableEffect(_this._effect);\n mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);\n _this._effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n _this._effect.setFloat2(\"depthValues\", camera.minZ, camera.minZ + camera.maxZ);\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n _this._effect.setTexture(\"diffuseSampler\", alphaTexture);\n _this._effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n _this._effect.setMatrices(\"mBones\", mesh.skeleton.getTransformMatrices(mesh));\n }\n // Draw\n mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix(\"world\", world); });\n }\n };\n this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {\n var index;\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n };\n }\n /**\n * Creates the depth rendering effect and checks if the effect is ready.\n * @param subMesh The submesh to be used to render the depth map of\n * @param useInstances If multiple world instances should be used\n * @returns if the depth renderer is ready to render the depth map\n */\n DepthRenderer.prototype.isReady = function (subMesh, useInstances) {\n var material = subMesh.getMaterial();\n if (material.disableDepthWrite) {\n return false;\n }\n var defines = [];\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n var mesh = subMesh.getMesh();\n // Alpha test\n if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n // Get correct effect \n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n this._effect = this._scene.getEngine().createEffect(\"depth\", attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\", \"depthValues\"], [\"diffuseSampler\"], join);\n }\n return this._effect.isReady();\n };\n /**\n * Gets the texture which the depth map will be written to.\n * @returns The depth map texture\n */\n DepthRenderer.prototype.getDepthMap = function () {\n return this._depthMap;\n };\n /**\n * Disposes of the depth renderer.\n */\n DepthRenderer.prototype.dispose = function () {\n this._depthMap.dispose();\n };\n return DepthRenderer;\n }());\n BABYLON.DepthRenderer = DepthRenderer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.depthRenderer.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var SSAORenderingPipeline = /** @class */ (function (_super) {\n __extends(SSAORenderingPipeline, _super);\n /**\n * @constructor\n * @param {string} name - The rendering pipeline name\n * @param {BABYLON.Scene} scene - The scene linked to this pipeline\n * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }\n * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to\n */\n function SSAORenderingPipeline(name, scene, ratio, cameras) {\n var _this = _super.call(this, scene.getEngine(), name) || this;\n // Members\n /**\n * The PassPostProcess id in the pipeline that contains the original scene color\n */\n _this.SSAOOriginalSceneColorEffect = \"SSAOOriginalSceneColorEffect\";\n /**\n * The SSAO PostProcess id in the pipeline\n */\n _this.SSAORenderEffect = \"SSAORenderEffect\";\n /**\n * The horizontal blur PostProcess id in the pipeline\n */\n _this.SSAOBlurHRenderEffect = \"SSAOBlurHRenderEffect\";\n /**\n * The vertical blur PostProcess id in the pipeline\n */\n _this.SSAOBlurVRenderEffect = \"SSAOBlurVRenderEffect\";\n /**\n * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)\n */\n _this.SSAOCombineRenderEffect = \"SSAOCombineRenderEffect\";\n /**\n * The output strength of the SSAO post-process. Default value is 1.0.\n */\n _this.totalStrength = 1.0;\n /**\n * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006\n */\n _this.radius = 0.0001;\n /**\n * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel\n * Must not be equal to fallOff and superior to fallOff.\n * Default value is 0.975\n */\n _this.area = 0.0075;\n /**\n * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel\n * Must not be equal to area and inferior to area.\n * Default value is 0.0\n */\n _this.fallOff = 0.000001;\n /**\n * The base color of the SSAO post-process\n * The final result is \"base + ssao\" between [0, 1]\n */\n _this.base = 0.5;\n _this._firstUpdate = true;\n _this._scene = scene;\n // Set up assets\n _this._createRandomTexture();\n _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer \"on\"\n var ssaoRatio = ratio.ssaoRatio || ratio;\n var combineRatio = ratio.combineRatio || ratio;\n _this._originalColorPostProcess = new BABYLON.PassPostProcess(\"SSAOOriginalSceneColor\", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);\n _this._createSSAOPostProcess(ssaoRatio);\n _this._createBlurPostProcess(ssaoRatio);\n _this._createSSAOCombinePostProcess(combineRatio);\n // Set up pipeline\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(_this);\n if (cameras)\n scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);\n return _this;\n }\n // Public Methods\n /**\n * Removes the internal pipeline assets and detatches the pipeline from the scene cameras\n */\n SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {\n if (disableDepthRender === void 0) { disableDepthRender = false; }\n for (var i = 0; i < this._scene.cameras.length; i++) {\n var camera = this._scene.cameras[i];\n this._originalColorPostProcess.dispose(camera);\n this._ssaoPostProcess.dispose(camera);\n this._blurHPostProcess.dispose(camera);\n this._blurVPostProcess.dispose(camera);\n this._ssaoCombinePostProcess.dispose(camera);\n }\n this._randomTexture.dispose();\n if (disableDepthRender)\n this._scene.disableDepthRenderer();\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);\n _super.prototype.dispose.call(this);\n };\n // Private Methods\n SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {\n var _this = this;\n var size = 16;\n this._blurHPostProcess = new BABYLON.BlurPostProcess(\"BlurH\", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this._blurVPostProcess = new BABYLON.BlurPostProcess(\"BlurV\", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this._blurHPostProcess.onActivateObservable.add(function () {\n var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();\n _this._blurHPostProcess.kernel = size * dw;\n });\n this._blurVPostProcess.onActivateObservable.add(function () {\n var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();\n _this._blurVPostProcess.kernel = size * dw;\n });\n };\n SSAORenderingPipeline.prototype._rebuild = function () {\n this._firstUpdate = true;\n _super.prototype._rebuild.call(this);\n };\n SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {\n var _this = this;\n var numSamples = 16;\n var sampleSphere = [\n 0.5381, 0.1856, -0.4319,\n 0.1379, 0.2486, 0.4430,\n 0.3371, 0.5679, -0.0057,\n -0.6999, -0.0451, -0.0019,\n 0.0689, -0.1598, -0.8547,\n 0.0560, 0.0069, -0.1843,\n -0.0146, 0.1402, 0.0762,\n 0.0100, -0.1924, -0.0344,\n -0.3577, -0.5301, -0.4358,\n -0.3169, 0.1063, 0.0158,\n 0.0103, -0.5869, 0.0046,\n -0.0897, -0.4940, 0.3287,\n 0.7119, -0.0154, -0.0918,\n -0.0533, 0.0596, -0.5411,\n 0.0352, -0.0631, 0.5460,\n -0.4776, 0.2847, -0.0271\n ];\n var samplesFactor = 1.0 / numSamples;\n this._ssaoPostProcess = new BABYLON.PostProcess(\"ssao\", \"ssao\", [\n \"sampleSphere\", \"samplesFactor\", \"randTextureTiles\", \"totalStrength\", \"radius\",\n \"area\", \"fallOff\", \"base\", \"range\", \"viewport\"\n ], [\"randomSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, \"#define SAMPLES \" + numSamples + \"\\n#define SSAO\");\n this._ssaoPostProcess.onApply = function (effect) {\n if (_this._firstUpdate) {\n effect.setArray3(\"sampleSphere\", sampleSphere);\n effect.setFloat(\"samplesFactor\", samplesFactor);\n effect.setFloat(\"randTextureTiles\", 4.0);\n }\n effect.setFloat(\"totalStrength\", _this.totalStrength);\n effect.setFloat(\"radius\", _this.radius);\n effect.setFloat(\"area\", _this.area);\n effect.setFloat(\"fallOff\", _this.fallOff);\n effect.setFloat(\"base\", _this.base);\n effect.setTexture(\"textureSampler\", _this._depthTexture);\n effect.setTexture(\"randomSampler\", _this._randomTexture);\n };\n };\n SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {\n var _this = this;\n this._ssaoCombinePostProcess = new BABYLON.PostProcess(\"ssaoCombine\", \"ssaoCombine\", [], [\"originalColor\", \"viewport\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._ssaoCombinePostProcess.onApply = function (effect) {\n effect.setVector4(\"viewport\", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));\n effect.setTextureFromPostProcess(\"originalColor\", _this._originalColorPostProcess);\n };\n };\n SSAORenderingPipeline.prototype._createRandomTexture = function () {\n var size = 512;\n this._randomTexture = new BABYLON.DynamicTexture(\"SSAORandomTexture\", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);\n this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n var context = this._randomTexture.getContext();\n var rand = function (min, max) {\n return Math.random() * (max - min) + min;\n };\n var randVector = BABYLON.Vector3.Zero();\n for (var x = 0; x < size; x++) {\n for (var y = 0; y < size; y++) {\n randVector.x = Math.floor(rand(-1.0, 1.0) * 255);\n randVector.y = Math.floor(rand(-1.0, 1.0) * 255);\n randVector.z = Math.floor(rand(-1.0, 1.0) * 255);\n context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';\n context.fillRect(x, y, 1, 1);\n }\n }\n this._randomTexture.update(false);\n };\n __decorate([\n BABYLON.serialize()\n ], SSAORenderingPipeline.prototype, \"totalStrength\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAORenderingPipeline.prototype, \"radius\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAORenderingPipeline.prototype, \"area\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAORenderingPipeline.prototype, \"fallOff\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAORenderingPipeline.prototype, \"base\", void 0);\n return SSAORenderingPipeline;\n }(BABYLON.PostProcessRenderPipeline));\n BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var SSAO2RenderingPipeline = /** @class */ (function (_super) {\n __extends(SSAO2RenderingPipeline, _super);\n /**\n * @constructor\n * @param {string} name - The rendering pipeline name\n * @param {BABYLON.Scene} scene - The scene linked to this pipeline\n * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }\n * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to\n */\n function SSAO2RenderingPipeline(name, scene, ratio, cameras) {\n var _this = _super.call(this, scene.getEngine(), name) || this;\n // Members\n /**\n * The PassPostProcess id in the pipeline that contains the original scene color\n */\n _this.SSAOOriginalSceneColorEffect = \"SSAOOriginalSceneColorEffect\";\n /**\n * The SSAO PostProcess id in the pipeline\n */\n _this.SSAORenderEffect = \"SSAORenderEffect\";\n /**\n * The horizontal blur PostProcess id in the pipeline\n */\n _this.SSAOBlurHRenderEffect = \"SSAOBlurHRenderEffect\";\n /**\n * The vertical blur PostProcess id in the pipeline\n */\n _this.SSAOBlurVRenderEffect = \"SSAOBlurVRenderEffect\";\n /**\n * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)\n */\n _this.SSAOCombineRenderEffect = \"SSAOCombineRenderEffect\";\n /**\n * The output strength of the SSAO post-process. Default value is 1.0.\n */\n _this.totalStrength = 1.0;\n /**\n * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.\n */\n _this.maxZ = 100.0;\n /**\n * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much\n */\n _this.minZAspect = 0.2;\n /**\n * Number of samples used for the SSAO calculations. Default value is 8\n */\n _this._samples = 8;\n /**\n * Are we using bilateral blur ?\n */\n _this._expensiveBlur = true;\n /**\n * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0\n */\n _this.radius = 2.0;\n /**\n * The base color of the SSAO post-process\n * The final result is \"base + ssao\" between [0, 1]\n */\n _this.base = 0.1;\n _this._firstUpdate = true;\n _this._scene = scene;\n _this._ratio = ratio;\n if (!_this.isSupported) {\n BABYLON.Tools.Error(\"SSAO 2 needs WebGL 2 support.\");\n return _this;\n }\n var ssaoRatio = _this._ratio.ssaoRatio || ratio;\n var blurRatio = _this._ratio.blurRatio || ratio;\n // Set up assets\n var geometryBufferRenderer = scene.enableGeometryBufferRenderer();\n _this._createRandomTexture();\n _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];\n _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];\n _this._originalColorPostProcess = new BABYLON.PassPostProcess(\"SSAOOriginalSceneColor\", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);\n _this._createSSAOPostProcess(1.0);\n _this._createBlurPostProcess(ssaoRatio, blurRatio);\n _this._createSSAOCombinePostProcess(blurRatio);\n // Set up pipeline\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(_this);\n if (cameras)\n scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);\n return _this;\n }\n Object.defineProperty(SSAO2RenderingPipeline.prototype, \"samples\", {\n get: function () {\n return this._samples;\n },\n set: function (n) {\n this._ssaoPostProcess.updateEffect(\"#define SAMPLES \" + n + \"\\n#define SSAO\");\n this._samples = n;\n this._sampleSphere = this._generateHemisphere();\n this._firstUpdate = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SSAO2RenderingPipeline.prototype, \"expensiveBlur\", {\n get: function () {\n return this._expensiveBlur;\n },\n set: function (b) {\n this._blurHPostProcess.updateEffect(\"#define BILATERAL_BLUR\\n#define BILATERAL_BLUR_H\\n#define SAMPLES 16\\n#define EXPENSIVE \" + (b ? \"1\" : \"0\") + \"\\n\", null, [\"textureSampler\", \"depthSampler\"]);\n this._blurVPostProcess.updateEffect(\"#define BILATERAL_BLUR\\n#define SAMPLES 16\\n#define EXPENSIVE \" + (b ? \"1\" : \"0\") + \"\\n\", null, [\"textureSampler\", \"depthSampler\"]);\n this._expensiveBlur = b;\n this._firstUpdate = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SSAO2RenderingPipeline, \"IsSupported\", {\n /**\n * Support test.\n */\n get: function () {\n var engine = BABYLON.Engine.LastCreatedEngine;\n if (!engine) {\n return false;\n }\n return engine.getCaps().drawBuffersExtension;\n },\n enumerable: true,\n configurable: true\n });\n // Public Methods\n /**\n * Removes the internal pipeline assets and detatches the pipeline from the scene cameras\n */\n SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {\n if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }\n for (var i = 0; i < this._scene.cameras.length; i++) {\n var camera = this._scene.cameras[i];\n this._originalColorPostProcess.dispose(camera);\n this._ssaoPostProcess.dispose(camera);\n this._blurHPostProcess.dispose(camera);\n this._blurVPostProcess.dispose(camera);\n this._ssaoCombinePostProcess.dispose(camera);\n }\n this._randomTexture.dispose();\n if (disableGeometryBufferRenderer)\n this._scene.disableGeometryBufferRenderer();\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);\n _super.prototype.dispose.call(this);\n };\n // Private Methods\n SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {\n var _this = this;\n this._samplerOffsets = [];\n var expensive = this.expensiveBlur;\n for (var i = -8; i < 8; i++) {\n this._samplerOffsets.push(i * 2 + 0.5);\n }\n this._blurHPostProcess = new BABYLON.PostProcess(\"BlurH\", \"ssao2\", [\"outSize\", \"samplerOffsets\", \"near\", \"far\", \"radius\"], [\"depthSampler\"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, \"#define BILATERAL_BLUR\\n#define BILATERAL_BLUR_H\\n#define SAMPLES 16\\n#define EXPENSIVE \" + (expensive ? \"1\" : \"0\") + \"\\n\");\n this._blurHPostProcess.onApply = function (effect) {\n if (!_this._scene.activeCamera) {\n return;\n }\n effect.setFloat(\"outSize\", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);\n effect.setFloat(\"near\", _this._scene.activeCamera.minZ);\n effect.setFloat(\"far\", _this._scene.activeCamera.maxZ);\n effect.setFloat(\"radius\", _this.radius);\n effect.setTexture(\"depthSampler\", _this._depthTexture);\n if (_this._firstUpdate) {\n effect.setArray(\"samplerOffsets\", _this._samplerOffsets);\n }\n };\n this._blurVPostProcess = new BABYLON.PostProcess(\"BlurV\", \"ssao2\", [\"outSize\", \"samplerOffsets\", \"near\", \"far\", \"radius\"], [\"depthSampler\"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, \"#define BILATERAL_BLUR\\n#define BILATERAL_BLUR_V\\n#define SAMPLES 16\\n#define EXPENSIVE \" + (expensive ? \"1\" : \"0\") + \"\\n\");\n this._blurVPostProcess.onApply = function (effect) {\n if (!_this._scene.activeCamera) {\n return;\n }\n effect.setFloat(\"outSize\", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);\n effect.setFloat(\"near\", _this._scene.activeCamera.minZ);\n effect.setFloat(\"far\", _this._scene.activeCamera.maxZ);\n effect.setFloat(\"radius\", _this.radius);\n effect.setTexture(\"depthSampler\", _this._depthTexture);\n if (_this._firstUpdate) {\n effect.setArray(\"samplerOffsets\", _this._samplerOffsets);\n _this._firstUpdate = false;\n }\n };\n };\n SSAO2RenderingPipeline.prototype._rebuild = function () {\n this._firstUpdate = true;\n _super.prototype._rebuild.call(this);\n };\n SSAO2RenderingPipeline.prototype._generateHemisphere = function () {\n var numSamples = this.samples;\n var result = [];\n var vector, scale;\n var rand = function (min, max) {\n return Math.random() * (max - min) + min;\n };\n var i = 0;\n while (i < numSamples) {\n vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));\n vector.normalize();\n scale = i / numSamples;\n scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);\n vector.scaleInPlace(scale);\n result.push(vector.x, vector.y, vector.z);\n i++;\n }\n return result;\n };\n SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {\n var _this = this;\n var numSamples = this.samples;\n this._sampleSphere = this._generateHemisphere();\n this._ssaoPostProcess = new BABYLON.PostProcess(\"ssao2\", \"ssao2\", [\n \"sampleSphere\", \"samplesFactor\", \"randTextureTiles\", \"totalStrength\", \"radius\",\n \"base\", \"range\", \"projection\", \"near\", \"far\", \"texelSize\",\n \"xViewport\", \"yViewport\", \"maxZ\", \"minZAspect\"\n ], [\"randomSampler\", \"normalSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, \"#define SAMPLES \" + numSamples + \"\\n#define SSAO\");\n this._ssaoPostProcess.onApply = function (effect) {\n if (_this._firstUpdate) {\n effect.setArray3(\"sampleSphere\", _this._sampleSphere);\n effect.setFloat(\"randTextureTiles\", 4.0);\n }\n if (!_this._scene.activeCamera) {\n return;\n }\n effect.setFloat(\"samplesFactor\", 1 / _this.samples);\n effect.setFloat(\"totalStrength\", _this.totalStrength);\n effect.setFloat2(\"texelSize\", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);\n effect.setFloat(\"radius\", _this.radius);\n effect.setFloat(\"maxZ\", _this.maxZ);\n effect.setFloat(\"minZAspect\", _this.minZAspect);\n effect.setFloat(\"base\", _this.base);\n effect.setFloat(\"near\", _this._scene.activeCamera.minZ);\n effect.setFloat(\"far\", _this._scene.activeCamera.maxZ);\n effect.setFloat(\"xViewport\", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));\n effect.setFloat(\"yViewport\", Math.tan(_this._scene.activeCamera.fov / 2));\n effect.setMatrix(\"projection\", _this._scene.getProjectionMatrix());\n effect.setTexture(\"textureSampler\", _this._depthTexture);\n effect.setTexture(\"normalSampler\", _this._normalTexture);\n effect.setTexture(\"randomSampler\", _this._randomTexture);\n };\n };\n SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {\n var _this = this;\n this._ssaoCombinePostProcess = new BABYLON.PostProcess(\"ssaoCombine\", \"ssaoCombine\", [], [\"originalColor\", \"viewport\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._ssaoCombinePostProcess.onApply = function (effect) {\n var viewport = _this._scene.activeCamera.viewport;\n effect.setVector4(\"viewport\", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));\n effect.setTextureFromPostProcess(\"originalColor\", _this._originalColorPostProcess);\n };\n };\n SSAO2RenderingPipeline.prototype._createRandomTexture = function () {\n var size = 512;\n this._randomTexture = new BABYLON.DynamicTexture(\"SSAORandomTexture\", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);\n this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n var context = this._randomTexture.getContext();\n var rand = function (min, max) {\n return Math.random() * (max - min) + min;\n };\n var randVector = BABYLON.Vector3.Zero();\n for (var x = 0; x < size; x++) {\n for (var y = 0; y < size; y++) {\n randVector.x = rand(0.0, 1.0);\n randVector.y = rand(0.0, 1.0);\n randVector.z = 0.0;\n randVector.normalize();\n randVector.scaleInPlace(255);\n randVector.x = Math.floor(randVector.x);\n randVector.y = Math.floor(randVector.y);\n context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';\n context.fillRect(x, y, 1, 1);\n }\n }\n this._randomTexture.update(false);\n };\n /**\n * Serialize the rendering pipeline (Used when exporting)\n * @returns the serialized object\n */\n SSAO2RenderingPipeline.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"SSAO2RenderingPipeline\";\n return serializationObject;\n };\n /**\n * Parse the serialized pipeline\n * @param source Source pipeline.\n * @param scene The scene to load the pipeline to.\n * @param rootUrl The URL of the serialized pipeline.\n * @returns An instantiated pipeline from the serialized object.\n */\n SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);\n };\n __decorate([\n BABYLON.serialize()\n ], SSAO2RenderingPipeline.prototype, \"totalStrength\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAO2RenderingPipeline.prototype, \"maxZ\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAO2RenderingPipeline.prototype, \"minZAspect\", void 0);\n __decorate([\n BABYLON.serialize(\"samples\")\n ], SSAO2RenderingPipeline.prototype, \"_samples\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAO2RenderingPipeline.prototype, \"_ratio\", void 0);\n __decorate([\n BABYLON.serialize(\"expensiveBlur\")\n ], SSAO2RenderingPipeline.prototype, \"_expensiveBlur\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAO2RenderingPipeline.prototype, \"radius\", void 0);\n __decorate([\n BABYLON.serialize()\n ], SSAO2RenderingPipeline.prototype, \"base\", void 0);\n return SSAO2RenderingPipeline;\n }(BABYLON.PostProcessRenderPipeline));\n BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map\n\n// BABYLON.JS Chromatic Aberration GLSL Shader\n// Author: Olivier Guyot\n// Separates very slightly R, G and B colors on the edges of the screen\n// Inspired by Francois Tarlier & Martins Upitis\n\nvar BABYLON;\n(function (BABYLON) {\n var LensRenderingPipeline = /** @class */ (function (_super) {\n __extends(LensRenderingPipeline, _super);\n /**\n * @constructor\n *\n * Effect parameters are as follow:\n * {\n * chromatic_aberration: number; // from 0 to x (1 for realism)\n * edge_blur: number; // from 0 to x (1 for realism)\n * distortion: number; // from 0 to x (1 for realism)\n * grain_amount: number; // from 0 to 1\n * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise\n * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)\n * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)\n * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)\n * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like \"bokeh\" effect\n * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)\n * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)\n * blur_noise: boolean; // add a little bit of noise to the blur (default: true)\n * }\n * Note: if an effect parameter is unset, effect is disabled\n *\n * @param {string} name - The rendering pipeline name\n * @param {object} parameters - An object containing all parameters (see above)\n * @param {BABYLON.Scene} scene - The scene linked to this pipeline\n * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)\n * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to\n */\n function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {\n if (ratio === void 0) { ratio = 1.0; }\n var _this = _super.call(this, scene.getEngine(), name) || this;\n // Lens effects can be of the following:\n // - chromatic aberration (slight shift of RGB colors)\n // - blur on the edge of the lens\n // - lens distortion\n // - depth-of-field blur & highlights enhancing\n // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)\n // - grain effect (noise or custom texture)\n // Two additional texture samplers are needed:\n // - depth map (for depth-of-field)\n // - grain texture\n /**\n * The chromatic aberration PostProcess id in the pipeline\n */\n _this.LensChromaticAberrationEffect = \"LensChromaticAberrationEffect\";\n /**\n * The highlights enhancing PostProcess id in the pipeline\n */\n _this.HighlightsEnhancingEffect = \"HighlightsEnhancingEffect\";\n /**\n * The depth-of-field PostProcess id in the pipeline\n */\n _this.LensDepthOfFieldEffect = \"LensDepthOfFieldEffect\";\n _this._scene = scene;\n // Fetch texture samplers\n _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer \"on\"\n if (parameters.grain_texture) {\n _this._grainTexture = parameters.grain_texture;\n }\n else {\n _this._createGrainTexture();\n }\n // save parameters\n _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;\n _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;\n _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;\n _this._distortion = parameters.distortion ? parameters.distortion : 0;\n _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;\n _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;\n _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;\n _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;\n _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;\n _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;\n _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;\n // Create effects\n _this._createChromaticAberrationPostProcess(ratio);\n _this._createHighlightsPostProcess(ratio);\n _this._createDepthOfFieldPostProcess(ratio / 4);\n // Set up pipeline\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));\n if (_this._highlightsGain === -1) {\n _this._disableEffect(_this.HighlightsEnhancingEffect, null);\n }\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(_this);\n if (cameras) {\n scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);\n }\n return _this;\n }\n // public methods (self explanatory)\n LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };\n LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };\n LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };\n LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };\n LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };\n LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };\n LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };\n LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };\n LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };\n LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };\n LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };\n LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };\n LensRenderingPipeline.prototype.enablePentagonBokeh = function () {\n this._highlightsPostProcess.updateEffect(\"#define PENTAGON\\n\");\n };\n LensRenderingPipeline.prototype.disablePentagonBokeh = function () {\n this._highlightsPostProcess.updateEffect();\n };\n LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };\n LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };\n LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {\n this._highlightsGain = amount;\n };\n LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {\n if (this._highlightsGain === -1) {\n this._highlightsGain = 1.0;\n }\n this._highlightsThreshold = amount;\n };\n LensRenderingPipeline.prototype.disableHighlights = function () {\n this._highlightsGain = -1;\n };\n /**\n * Removes the internal pipeline assets and detaches the pipeline from the scene cameras\n */\n LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {\n if (disableDepthRender === void 0) { disableDepthRender = false; }\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);\n this._chromaticAberrationPostProcess = null;\n this._highlightsPostProcess = null;\n this._depthOfFieldPostProcess = null;\n this._grainTexture.dispose();\n if (disableDepthRender)\n this._scene.disableDepthRenderer();\n };\n // colors shifting and distortion\n LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {\n var _this = this;\n this._chromaticAberrationPostProcess = new BABYLON.PostProcess(\"LensChromaticAberration\", \"chromaticAberration\", [\"chromatic_aberration\", \"screen_width\", \"screen_height\", \"direction\", \"radialIntensity\", \"centerPosition\"], // uniforms\n [], // samplers\n ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._chromaticAberrationPostProcess.onApply = function (effect) {\n effect.setFloat('chromatic_aberration', _this._chromaticAberration);\n effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());\n effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());\n effect.setFloat('radialIntensity', 1);\n effect.setFloat2('direction', 17, 17);\n effect.setFloat2('centerPosition', 0.5, 0.5);\n };\n };\n // highlights enhancing\n LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {\n var _this = this;\n this._highlightsPostProcess = new BABYLON.PostProcess(\"LensHighlights\", \"lensHighlights\", [\"gain\", \"threshold\", \"screen_width\", \"screen_height\"], // uniforms\n [], // samplers\n ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? \"#define PENTAGON\\n\" : \"\");\n this._highlightsPostProcess.onApply = function (effect) {\n effect.setFloat('gain', _this._highlightsGain);\n effect.setFloat('threshold', _this._highlightsThreshold);\n effect.setTextureFromPostProcess(\"textureSampler\", _this._chromaticAberrationPostProcess);\n effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());\n effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());\n };\n };\n // colors shifting and distortion\n LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {\n var _this = this;\n this._depthOfFieldPostProcess = new BABYLON.PostProcess(\"LensDepthOfField\", \"depthOfField\", [\n \"grain_amount\", \"blur_noise\", \"screen_width\", \"screen_height\", \"distortion\", \"dof_enabled\",\n \"screen_distance\", \"aperture\", \"darken\", \"edge_blur\", \"highlights\", \"near\", \"far\"\n ], [\"depthSampler\", \"grainSampler\", \"highlightsSampler\"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._depthOfFieldPostProcess.onApply = function (effect) {\n effect.setTexture(\"depthSampler\", _this._depthTexture);\n effect.setTexture(\"grainSampler\", _this._grainTexture);\n effect.setTextureFromPostProcess(\"textureSampler\", _this._highlightsPostProcess);\n effect.setTextureFromPostProcess(\"highlightsSampler\", _this._depthOfFieldPostProcess);\n effect.setFloat('grain_amount', _this._grainAmount);\n effect.setBool('blur_noise', _this._blurNoise);\n effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());\n effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());\n effect.setFloat('distortion', _this._distortion);\n effect.setBool('dof_enabled', (_this._dofDistance !== -1));\n effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));\n effect.setFloat('aperture', _this._dofAperture);\n effect.setFloat('darken', _this._dofDarken);\n effect.setFloat('edge_blur', _this._edgeBlur);\n effect.setBool('highlights', (_this._highlightsGain !== -1));\n if (_this._scene.activeCamera) {\n effect.setFloat('near', _this._scene.activeCamera.minZ);\n effect.setFloat('far', _this._scene.activeCamera.maxZ);\n }\n };\n };\n // creates a black and white random noise texture, 512x512\n LensRenderingPipeline.prototype._createGrainTexture = function () {\n var size = 512;\n this._grainTexture = new BABYLON.DynamicTexture(\"LensNoiseTexture\", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;\n this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;\n var context = this._grainTexture.getContext();\n var rand = function (min, max) {\n return Math.random() * (max - min) + min;\n };\n var value;\n for (var x = 0; x < size; x++) {\n for (var y = 0; y < size; y++) {\n value = Math.floor(rand(0.42, 0.58) * 255);\n context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';\n context.fillRect(x, y, 1, 1);\n }\n }\n this._grainTexture.update(false);\n };\n return LensRenderingPipeline;\n }(BABYLON.PostProcessRenderPipeline));\n BABYLON.LensRenderingPipeline = LensRenderingPipeline;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.lensRenderingPipeline.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var StandardRenderingPipeline = /** @class */ (function (_super) {\n __extends(StandardRenderingPipeline, _super);\n /**\n * @constructor\n * @param {string} name - The rendering pipeline name\n * @param {BABYLON.Scene} scene - The scene linked to this pipeline\n * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)\n * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be \"reusable\". Can be null.\n * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to\n */\n function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {\n if (originalPostProcess === void 0) { originalPostProcess = null; }\n var _this = _super.call(this, scene.getEngine(), name) || this;\n _this.downSampleX4PostProcess = null;\n _this.brightPassPostProcess = null;\n _this.blurHPostProcesses = [];\n _this.blurVPostProcesses = [];\n _this.textureAdderPostProcess = null;\n _this.volumetricLightPostProcess = null;\n _this.volumetricLightSmoothXPostProcess = null;\n _this.volumetricLightSmoothYPostProcess = null;\n _this.volumetricLightMergePostProces = null;\n _this.volumetricLightFinalPostProcess = null;\n _this.luminancePostProcess = null;\n _this.luminanceDownSamplePostProcesses = [];\n _this.hdrPostProcess = null;\n _this.textureAdderFinalPostProcess = null;\n _this.lensFlareFinalPostProcess = null;\n _this.hdrFinalPostProcess = null;\n _this.lensFlarePostProcess = null;\n _this.lensFlareComposePostProcess = null;\n _this.motionBlurPostProcess = null;\n _this.depthOfFieldPostProcess = null;\n // Values\n _this.brightThreshold = 1.0;\n _this.blurWidth = 512.0;\n _this.horizontalBlur = false;\n _this.exposure = 1.0;\n _this.lensTexture = null;\n _this.volumetricLightCoefficient = 0.2;\n _this.volumetricLightPower = 4.0;\n _this.volumetricLightBlurScale = 64.0;\n _this.sourceLight = null;\n _this.hdrMinimumLuminance = 1.0;\n _this.hdrDecreaseRate = 0.5;\n _this.hdrIncreaseRate = 0.5;\n _this.lensColorTexture = null;\n _this.lensFlareStrength = 20.0;\n _this.lensFlareGhostDispersal = 1.4;\n _this.lensFlareHaloWidth = 0.7;\n _this.lensFlareDistortionStrength = 16.0;\n _this.lensStarTexture = null;\n _this.lensFlareDirtTexture = null;\n _this.depthOfFieldDistance = 10.0;\n _this.depthOfFieldBlurWidth = 64.0;\n _this.motionStrength = 1.0;\n // IAnimatable\n _this.animations = [];\n _this._currentDepthOfFieldSource = null;\n _this._hdrCurrentLuminance = 1.0;\n // Getters and setters\n _this._bloomEnabled = true;\n _this._depthOfFieldEnabled = false;\n _this._vlsEnabled = false;\n _this._lensFlareEnabled = false;\n _this._hdrEnabled = false;\n _this._motionBlurEnabled = false;\n _this._motionBlurSamples = 64.0;\n _this._volumetricLightStepsCount = 50.0;\n _this._cameras = cameras || [];\n // Initialize\n _this._scene = scene;\n _this._basePostProcess = originalPostProcess;\n _this._ratio = ratio;\n // Misc\n _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(_this);\n _this._buildPipeline();\n return _this;\n }\n Object.defineProperty(StandardRenderingPipeline.prototype, \"BloomEnabled\", {\n get: function () {\n return this._bloomEnabled;\n },\n set: function (enabled) {\n if (this._bloomEnabled === enabled) {\n return;\n }\n this._bloomEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"DepthOfFieldEnabled\", {\n get: function () {\n return this._depthOfFieldEnabled;\n },\n set: function (enabled) {\n if (this._depthOfFieldEnabled === enabled) {\n return;\n }\n this._depthOfFieldEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"LensFlareEnabled\", {\n get: function () {\n return this._lensFlareEnabled;\n },\n set: function (enabled) {\n if (this._lensFlareEnabled === enabled) {\n return;\n }\n this._lensFlareEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"HDREnabled\", {\n get: function () {\n return this._hdrEnabled;\n },\n set: function (enabled) {\n if (this._hdrEnabled === enabled) {\n return;\n }\n this._hdrEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"VLSEnabled\", {\n get: function () {\n return this._vlsEnabled;\n },\n set: function (enabled) {\n if (this._vlsEnabled === enabled) {\n return;\n }\n if (enabled) {\n var geometry = this._scene.enableGeometryBufferRenderer();\n if (!geometry) {\n BABYLON.Tools.Warn(\"Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline\");\n return;\n }\n }\n this._vlsEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"MotionBlurEnabled\", {\n get: function () {\n return this._motionBlurEnabled;\n },\n set: function (enabled) {\n if (this._motionBlurEnabled === enabled) {\n return;\n }\n this._motionBlurEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"volumetricLightStepsCount\", {\n get: function () {\n return this._volumetricLightStepsCount;\n },\n set: function (count) {\n if (this.volumetricLightPostProcess) {\n this.volumetricLightPostProcess.updateEffect(\"#define VLS\\n#define NB_STEPS \" + count.toFixed(1));\n }\n this._volumetricLightStepsCount = count;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandardRenderingPipeline.prototype, \"motionBlurSamples\", {\n get: function () {\n return this._motionBlurSamples;\n },\n set: function (samples) {\n if (this.motionBlurPostProcess) {\n this.motionBlurPostProcess.updateEffect(\"#define MOTION_BLUR\\n#define MAX_MOTION_SAMPLES \" + samples.toFixed(1));\n }\n this._motionBlurSamples = samples;\n },\n enumerable: true,\n configurable: true\n });\n StandardRenderingPipeline.prototype._buildPipeline = function () {\n var _this = this;\n var ratio = this._ratio;\n var scene = this._scene;\n this._disposePostProcesses();\n this._reset();\n // Create pass post-process\n if (!this._basePostProcess) {\n this.originalPostProcess = new BABYLON.PostProcess(\"HDRPass\", \"standard\", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", this._floatTextureType);\n this.originalPostProcess.onApply = function (effect) {\n _this._currentDepthOfFieldSource = _this.originalPostProcess;\n };\n }\n else {\n this.originalPostProcess = this._basePostProcess;\n }\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRPassPostProcess\", function () { return _this.originalPostProcess; }, true));\n this._currentDepthOfFieldSource = this.originalPostProcess;\n if (this._bloomEnabled) {\n // Create down sample X4 post-process\n this._createDownSampleX4PostProcess(scene, ratio / 2);\n // Create bright pass post-process\n this._createBrightPassPostProcess(scene, ratio / 2);\n // Create gaussian blur post-processes (down sampling blurs)\n this._createBlurPostProcesses(scene, ratio / 4, 1);\n // Create texture adder post-process\n this._createTextureAdderPostProcess(scene, ratio);\n // Create depth-of-field source post-process\n this.textureAdderFinalPostProcess = new BABYLON.PostProcess(\"HDRDepthOfFieldSource\", \"standard\", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRBaseDepthOfFieldSource\", function () { return _this.textureAdderFinalPostProcess; }, true));\n }\n if (this._vlsEnabled) {\n // Create volumetric light\n this._createVolumetricLightPostProcess(scene, ratio);\n // Create volumetric light final post-process\n this.volumetricLightFinalPostProcess = new BABYLON.PostProcess(\"HDRVLSFinal\", \"standard\", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRVLSFinal\", function () { return _this.volumetricLightFinalPostProcess; }, true));\n }\n if (this._lensFlareEnabled) {\n // Create lens flare post-process\n this._createLensFlarePostProcess(scene, ratio);\n // Create depth-of-field source post-process post lens-flare and disable it now\n this.lensFlareFinalPostProcess = new BABYLON.PostProcess(\"HDRPostLensFlareDepthOfFieldSource\", \"standard\", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRPostLensFlareDepthOfFieldSource\", function () { return _this.lensFlareFinalPostProcess; }, true));\n }\n if (this._hdrEnabled) {\n // Create luminance\n this._createLuminancePostProcesses(scene, this._floatTextureType);\n // Create HDR\n this._createHdrPostProcess(scene, ratio);\n // Create depth-of-field source post-process post hdr and disable it now\n this.hdrFinalPostProcess = new BABYLON.PostProcess(\"HDRPostHDReDepthOfFieldSource\", \"standard\", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRPostHDReDepthOfFieldSource\", function () { return _this.hdrFinalPostProcess; }, true));\n }\n if (this._depthOfFieldEnabled) {\n // Create gaussian blur used by depth-of-field\n this._createBlurPostProcesses(scene, ratio / 2, 3, \"depthOfFieldBlurWidth\");\n // Create depth-of-field post-process\n this._createDepthOfFieldPostProcess(scene, ratio);\n }\n if (this._motionBlurEnabled) {\n // Create motion blur post-process\n this._createMotionBlurPostProcess(scene, ratio);\n }\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);\n }\n };\n // Down Sample X4 Post-Processs\n StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {\n var _this = this;\n var downSampleX4Offsets = new Array(32);\n this.downSampleX4PostProcess = new BABYLON.PostProcess(\"HDRDownSampleX4\", \"standard\", [\"dsOffsets\"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define DOWN_SAMPLE_X4\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.downSampleX4PostProcess.onApply = function (effect) {\n var id = 0;\n var width = _this.downSampleX4PostProcess.width;\n var height = _this.downSampleX4PostProcess.height;\n for (var i = -2; i < 2; i++) {\n for (var j = -2; j < 2; j++) {\n downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);\n downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);\n id += 2;\n }\n }\n effect.setArray2(\"dsOffsets\", downSampleX4Offsets);\n };\n // Add to pipeline\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRDownSampleX4\", function () { return _this.downSampleX4PostProcess; }, true));\n };\n // Brightpass Post-Process\n StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {\n var _this = this;\n var brightOffsets = new Array(8);\n this.brightPassPostProcess = new BABYLON.PostProcess(\"HDRBrightPass\", \"standard\", [\"dsOffsets\", \"brightThreshold\"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define BRIGHT_PASS\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.brightPassPostProcess.onApply = function (effect) {\n var sU = (1.0 / _this.brightPassPostProcess.width);\n var sV = (1.0 / _this.brightPassPostProcess.height);\n brightOffsets[0] = -0.5 * sU;\n brightOffsets[1] = 0.5 * sV;\n brightOffsets[2] = 0.5 * sU;\n brightOffsets[3] = 0.5 * sV;\n brightOffsets[4] = -0.5 * sU;\n brightOffsets[5] = -0.5 * sV;\n brightOffsets[6] = 0.5 * sU;\n brightOffsets[7] = -0.5 * sV;\n effect.setArray2(\"dsOffsets\", brightOffsets);\n effect.setFloat(\"brightThreshold\", _this.brightThreshold);\n };\n // Add to pipeline\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRBrightPass\", function () { return _this.brightPassPostProcess; }, true));\n };\n // Create blur H&V post-processes\n StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {\n var _this = this;\n if (blurWidthKey === void 0) { blurWidthKey = \"blurWidth\"; }\n var engine = scene.getEngine();\n var blurX = new BABYLON.BlurPostProcess(\"HDRBlurH\" + \"_\" + indice, new BABYLON.Vector2(1, 0), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n var blurY = new BABYLON.BlurPostProcess(\"HDRBlurV\" + \"_\" + indice, new BABYLON.Vector2(0, 1), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n blurX.onActivateObservable.add(function () {\n var dw = blurX.width / engine.getRenderWidth();\n blurX.kernel = _this[blurWidthKey] * dw;\n });\n blurY.onActivateObservable.add(function () {\n var dw = blurY.height / engine.getRenderHeight();\n blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;\n });\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRBlurH\" + indice, function () { return blurX; }, true));\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRBlurV\" + indice, function () { return blurY; }, true));\n this.blurHPostProcesses.push(blurX);\n this.blurVPostProcesses.push(blurY);\n };\n // Create texture adder post-process\n StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {\n var _this = this;\n this.textureAdderPostProcess = new BABYLON.PostProcess(\"HDRTextureAdder\", \"standard\", [\"exposure\"], [\"otherSampler\", \"lensSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define TEXTURE_ADDER\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.textureAdderPostProcess.onApply = function (effect) {\n effect.setTextureFromPostProcess(\"otherSampler\", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);\n effect.setTexture(\"lensSampler\", _this.lensTexture);\n effect.setFloat(\"exposure\", _this.exposure);\n _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;\n };\n // Add to pipeline\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRTextureAdder\", function () { return _this.textureAdderPostProcess; }, true));\n };\n StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {\n var _this = this;\n var geometryRenderer = scene.enableGeometryBufferRenderer();\n geometryRenderer.enablePosition = true;\n var geometry = geometryRenderer.getGBuffer();\n // Base post-process\n this.volumetricLightPostProcess = new BABYLON.PostProcess(\"HDRVLS\", \"standard\", [\"shadowViewProjection\", \"cameraPosition\", \"sunDirection\", \"sunColor\", \"scatteringCoefficient\", \"scatteringPower\", \"depthValues\"], [\"shadowMapSampler\", \"positionSampler\"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define VLS\\n#define NB_STEPS \" + this._volumetricLightStepsCount.toFixed(1));\n var depthValues = BABYLON.Vector2.Zero();\n this.volumetricLightPostProcess.onApply = function (effect) {\n if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {\n var generator = _this.sourceLight.getShadowGenerator();\n effect.setTexture(\"shadowMapSampler\", generator.getShadowMap());\n effect.setTexture(\"positionSampler\", geometry.textures[2]);\n effect.setColor3(\"sunColor\", _this.sourceLight.diffuse);\n effect.setVector3(\"sunDirection\", _this.sourceLight.getShadowDirection());\n effect.setVector3(\"cameraPosition\", _this._scene.activeCamera.globalPosition);\n effect.setMatrix(\"shadowViewProjection\", generator.getTransformMatrix());\n effect.setFloat(\"scatteringCoefficient\", _this.volumetricLightCoefficient);\n effect.setFloat(\"scatteringPower\", _this.volumetricLightPower);\n depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);\n depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);\n effect.setVector2(\"depthValues\", depthValues);\n }\n };\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRVLS\", function () { return _this.volumetricLightPostProcess; }, true));\n // Smooth\n this._createBlurPostProcesses(scene, ratio / 4, 0, \"volumetricLightBlurScale\");\n // Merge\n this.volumetricLightMergePostProces = new BABYLON.PostProcess(\"HDRVLSMerge\", \"standard\", [], [\"originalSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define VLSMERGE\");\n this.volumetricLightMergePostProces.onApply = function (effect) {\n effect.setTextureFromPostProcess(\"originalSampler\", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);\n _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;\n };\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRVLSMerge\", function () { return _this.volumetricLightMergePostProces; }, true));\n };\n // Create luminance\n StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {\n var _this = this;\n // Create luminance\n var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);\n this.luminancePostProcess = new BABYLON.PostProcess(\"HDRLuminance\", \"standard\", [\"lumOffsets\"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define LUMINANCE\", textureType);\n var offsets = [];\n this.luminancePostProcess.onApply = function (effect) {\n var sU = (1.0 / _this.luminancePostProcess.width);\n var sV = (1.0 / _this.luminancePostProcess.height);\n offsets[0] = -0.5 * sU;\n offsets[1] = 0.5 * sV;\n offsets[2] = 0.5 * sU;\n offsets[3] = 0.5 * sV;\n offsets[4] = -0.5 * sU;\n offsets[5] = -0.5 * sV;\n offsets[6] = 0.5 * sU;\n offsets[7] = -0.5 * sV;\n effect.setArray2(\"lumOffsets\", offsets);\n };\n // Add to pipeline\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRLuminance\", function () { return _this.luminancePostProcess; }, true));\n // Create down sample luminance\n for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {\n var size = Math.pow(3, i);\n var defines = \"#define LUMINANCE_DOWN_SAMPLE\\n\";\n if (i === 0) {\n defines += \"#define FINAL_DOWN_SAMPLER\";\n }\n var postProcess = new BABYLON.PostProcess(\"HDRLuminanceDownSample\" + i, \"standard\", [\"dsOffsets\", \"halfDestPixelSize\"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);\n this.luminanceDownSamplePostProcesses.push(postProcess);\n }\n // Create callbacks and add effects\n var lastLuminance = this.luminancePostProcess;\n this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {\n var downSampleOffsets = new Array(18);\n pp.onApply = function (effect) {\n if (!lastLuminance) {\n return;\n }\n var id = 0;\n for (var x = -1; x < 2; x++) {\n for (var y = -1; y < 2; y++) {\n downSampleOffsets[id] = x / lastLuminance.width;\n downSampleOffsets[id + 1] = y / lastLuminance.height;\n id += 2;\n }\n }\n effect.setArray2(\"dsOffsets\", downSampleOffsets);\n effect.setFloat(\"halfDestPixelSize\", 0.5 / lastLuminance.width);\n if (index === _this.luminanceDownSamplePostProcesses.length - 1) {\n lastLuminance = _this.luminancePostProcess;\n }\n else {\n lastLuminance = pp;\n }\n };\n if (index === _this.luminanceDownSamplePostProcesses.length - 1) {\n pp.onAfterRender = function (effect) {\n var pixel = scene.getEngine().readPixels(0, 0, 1, 1);\n var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;\n };\n }\n _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRLuminanceDownSample\" + index, function () { return pp; }, true));\n });\n };\n // Create HDR post-process\n StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {\n var _this = this;\n this.hdrPostProcess = new BABYLON.PostProcess(\"HDR\", \"standard\", [\"averageLuminance\"], [\"textureAdderSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define HDR\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n var outputLiminance = 1;\n var time = 0;\n var lastTime = 0;\n this.hdrPostProcess.onApply = function (effect) {\n effect.setTextureFromPostProcess(\"textureAdderSampler\", _this._currentDepthOfFieldSource);\n time += scene.getEngine().getDeltaTime();\n if (outputLiminance < 0) {\n outputLiminance = _this._hdrCurrentLuminance;\n }\n else {\n var dt = (lastTime - time) / 1000.0;\n if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {\n outputLiminance += _this.hdrDecreaseRate * dt;\n }\n else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {\n outputLiminance -= _this.hdrIncreaseRate * dt;\n }\n else {\n outputLiminance = _this._hdrCurrentLuminance;\n }\n }\n outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);\n effect.setFloat(\"averageLuminance\", outputLiminance);\n lastTime = time;\n _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;\n };\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDR\", function () { return _this.hdrPostProcess; }, true));\n };\n // Create lens flare post-process\n StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {\n var _this = this;\n this.lensFlarePostProcess = new BABYLON.PostProcess(\"HDRLensFlare\", \"standard\", [\"strength\", \"ghostDispersal\", \"haloWidth\", \"resolution\", \"distortionStrength\"], [\"lensColorSampler\"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define LENS_FLARE\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRLensFlare\", function () { return _this.lensFlarePostProcess; }, true));\n this._createBlurPostProcesses(scene, ratio / 4, 2);\n this.lensFlareComposePostProcess = new BABYLON.PostProcess(\"HDRLensFlareCompose\", \"standard\", [\"lensStarMatrix\"], [\"otherSampler\", \"lensDirtSampler\", \"lensStarSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define LENS_FLARE_COMPOSE\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRLensFlareCompose\", function () { return _this.lensFlareComposePostProcess; }, true));\n var resolution = new BABYLON.Vector2(0, 0);\n // Lens flare\n this.lensFlarePostProcess.onApply = function (effect) {\n effect.setTextureFromPostProcess(\"textureSampler\", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);\n effect.setTexture(\"lensColorSampler\", _this.lensColorTexture);\n effect.setFloat(\"strength\", _this.lensFlareStrength);\n effect.setFloat(\"ghostDispersal\", _this.lensFlareGhostDispersal);\n effect.setFloat(\"haloWidth\", _this.lensFlareHaloWidth);\n // Shift\n resolution.x = _this.lensFlarePostProcess.width;\n resolution.y = _this.lensFlarePostProcess.height;\n effect.setVector2(\"resolution\", resolution);\n effect.setFloat(\"distortionStrength\", _this.lensFlareDistortionStrength);\n };\n // Compose\n var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n this.lensFlareComposePostProcess.onApply = function (effect) {\n if (!_this._scene.activeCamera) {\n return;\n }\n effect.setTextureFromPostProcess(\"otherSampler\", _this._currentDepthOfFieldSource);\n effect.setTexture(\"lensDirtSampler\", _this.lensFlareDirtTexture);\n effect.setTexture(\"lensStarSampler\", _this.lensStarTexture);\n // Lens start rotation matrix\n var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);\n var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);\n var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));\n camRot *= 4.0;\n var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);\n effect.setMatrix(\"lensStarMatrix\", lensStarMatrix);\n _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;\n };\n };\n // Create depth-of-field post-process\n StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {\n var _this = this;\n this.depthOfFieldPostProcess = new BABYLON.PostProcess(\"HDRDepthOfField\", \"standard\", [\"distance\"], [\"otherSampler\", \"depthSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define DEPTH_OF_FIELD\", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this.depthOfFieldPostProcess.onApply = function (effect) {\n effect.setTextureFromPostProcess(\"otherSampler\", _this._currentDepthOfFieldSource);\n effect.setTexture(\"depthSampler\", _this._getDepthTexture());\n effect.setFloat(\"distance\", _this.depthOfFieldDistance);\n };\n // Add to pipeline\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRDepthOfField\", function () { return _this.depthOfFieldPostProcess; }, true));\n };\n // Create motion blur post-process\n StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {\n var _this = this;\n this.motionBlurPostProcess = new BABYLON.PostProcess(\"HDRMotionBlur\", \"standard\", [\"inverseViewProjection\", \"prevViewProjection\", \"screenSize\", \"motionScale\", \"motionStrength\"], [\"depthSampler\"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define MOTION_BLUR\\n#define MAX_MOTION_SAMPLES \" + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n var motionScale = 0;\n var prevViewProjection = BABYLON.Matrix.Identity();\n var invViewProjection = BABYLON.Matrix.Identity();\n var viewProjection = BABYLON.Matrix.Identity();\n var screenSize = BABYLON.Vector2.Zero();\n this.motionBlurPostProcess.onApply = function (effect) {\n viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());\n viewProjection.invertToRef(invViewProjection);\n effect.setMatrix(\"inverseViewProjection\", invViewProjection);\n effect.setMatrix(\"prevViewProjection\", prevViewProjection);\n prevViewProjection = viewProjection;\n screenSize.x = _this.motionBlurPostProcess.width;\n screenSize.y = _this.motionBlurPostProcess.height;\n effect.setVector2(\"screenSize\", screenSize);\n motionScale = scene.getEngine().getFps() / 60.0;\n effect.setFloat(\"motionScale\", motionScale);\n effect.setFloat(\"motionStrength\", _this.motionStrength);\n effect.setTexture(\"depthSampler\", _this._getDepthTexture());\n };\n this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), \"HDRMotionBlur\", function () { return _this.motionBlurPostProcess; }, true));\n };\n StandardRenderingPipeline.prototype._getDepthTexture = function () {\n if (this._scene.getEngine().getCaps().drawBuffersExtension) {\n var renderer = this._scene.enableGeometryBufferRenderer();\n return renderer.getGBuffer().textures[0];\n }\n return this._scene.enableDepthRenderer().getDepthMap();\n };\n StandardRenderingPipeline.prototype._disposePostProcesses = function () {\n for (var i = 0; i < this._cameras.length; i++) {\n var camera = this._cameras[i];\n if (this.originalPostProcess) {\n this.originalPostProcess.dispose(camera);\n }\n if (this.downSampleX4PostProcess) {\n this.downSampleX4PostProcess.dispose(camera);\n }\n if (this.brightPassPostProcess) {\n this.brightPassPostProcess.dispose(camera);\n }\n if (this.textureAdderPostProcess) {\n this.textureAdderPostProcess.dispose(camera);\n }\n if (this.textureAdderFinalPostProcess) {\n this.textureAdderFinalPostProcess.dispose(camera);\n }\n if (this.volumetricLightPostProcess) {\n this.volumetricLightPostProcess.dispose(camera);\n }\n if (this.volumetricLightSmoothXPostProcess) {\n this.volumetricLightSmoothXPostProcess.dispose(camera);\n }\n if (this.volumetricLightSmoothYPostProcess) {\n this.volumetricLightSmoothYPostProcess.dispose(camera);\n }\n if (this.volumetricLightMergePostProces) {\n this.volumetricLightMergePostProces.dispose(camera);\n }\n if (this.volumetricLightFinalPostProcess) {\n this.volumetricLightFinalPostProcess.dispose(camera);\n }\n if (this.lensFlarePostProcess) {\n this.lensFlarePostProcess.dispose(camera);\n }\n if (this.lensFlareComposePostProcess) {\n this.lensFlareComposePostProcess.dispose(camera);\n }\n for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {\n this.luminanceDownSamplePostProcesses[j].dispose(camera);\n }\n if (this.luminancePostProcess) {\n this.luminancePostProcess.dispose(camera);\n }\n if (this.hdrPostProcess) {\n this.hdrPostProcess.dispose(camera);\n }\n if (this.hdrFinalPostProcess) {\n this.hdrFinalPostProcess.dispose(camera);\n }\n if (this.depthOfFieldPostProcess) {\n this.depthOfFieldPostProcess.dispose(camera);\n }\n if (this.motionBlurPostProcess) {\n this.motionBlurPostProcess.dispose(camera);\n }\n for (var j = 0; j < this.blurHPostProcesses.length; j++) {\n this.blurHPostProcesses[j].dispose(camera);\n }\n for (var j = 0; j < this.blurVPostProcesses.length; j++) {\n this.blurVPostProcesses[j].dispose(camera);\n }\n }\n this.originalPostProcess = null;\n this.downSampleX4PostProcess = null;\n this.brightPassPostProcess = null;\n this.textureAdderPostProcess = null;\n this.textureAdderFinalPostProcess = null;\n this.volumetricLightPostProcess = null;\n this.volumetricLightSmoothXPostProcess = null;\n this.volumetricLightSmoothYPostProcess = null;\n this.volumetricLightMergePostProces = null;\n this.volumetricLightFinalPostProcess = null;\n this.lensFlarePostProcess = null;\n this.lensFlareComposePostProcess = null;\n this.luminancePostProcess = null;\n this.hdrPostProcess = null;\n this.hdrFinalPostProcess = null;\n this.depthOfFieldPostProcess = null;\n this.motionBlurPostProcess = null;\n this.luminanceDownSamplePostProcesses = [];\n this.blurHPostProcesses = [];\n this.blurVPostProcesses = [];\n };\n /**\n * Dispose of the pipeline and stop all post processes\n */\n StandardRenderingPipeline.prototype.dispose = function () {\n this._disposePostProcesses();\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n _super.prototype.dispose.call(this);\n };\n /**\n * Serialize the rendering pipeline (Used when exporting)\n * @returns the serialized object\n */\n StandardRenderingPipeline.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n if (this.sourceLight) {\n serializationObject.sourceLightId = this.sourceLight.id;\n }\n serializationObject.customType = \"StandardRenderingPipeline\";\n return serializationObject;\n };\n /**\n * Parse the serialized pipeline\n * @param source Source pipeline.\n * @param scene The scene to load the pipeline to.\n * @param rootUrl The URL of the serialized pipeline.\n * @returns An instantiated pipeline from the serialized object.\n */\n StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {\n var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);\n if (source.sourceLightId) {\n p.sourceLight = scene.getLightByID(source.sourceLightId);\n }\n return p;\n };\n // Luminance steps\n StandardRenderingPipeline.LuminanceSteps = 6;\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"brightThreshold\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"blurWidth\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"horizontalBlur\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"exposure\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"lensTexture\")\n ], StandardRenderingPipeline.prototype, \"lensTexture\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"volumetricLightCoefficient\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"volumetricLightPower\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"volumetricLightBlurScale\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"hdrMinimumLuminance\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"hdrDecreaseRate\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"hdrIncreaseRate\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"lensColorTexture\")\n ], StandardRenderingPipeline.prototype, \"lensColorTexture\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"lensFlareStrength\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"lensFlareGhostDispersal\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"lensFlareHaloWidth\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"lensFlareDistortionStrength\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"lensStarTexture\")\n ], StandardRenderingPipeline.prototype, \"lensStarTexture\", void 0);\n __decorate([\n BABYLON.serializeAsTexture(\"lensFlareDirtTexture\")\n ], StandardRenderingPipeline.prototype, \"lensFlareDirtTexture\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"depthOfFieldDistance\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"depthOfFieldBlurWidth\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"motionStrength\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"_ratio\", void 0);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"BloomEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"DepthOfFieldEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"LensFlareEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"HDREnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"VLSEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"MotionBlurEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"volumetricLightStepsCount\", null);\n __decorate([\n BABYLON.serialize()\n ], StandardRenderingPipeline.prototype, \"motionBlurSamples\", null);\n return StandardRenderingPipeline;\n }(BABYLON.PostProcessRenderPipeline));\n BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.standardRenderingPipeline.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FxaaPostProcess = /** @class */ (function (_super) {\n __extends(FxaaPostProcess, _super);\n function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {\n if (camera === void 0) { camera = null; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n var _this = _super.call(this, name, \"fxaa\", [\"texelSize\"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, \"fxaa\", undefined, true) || this;\n var defines = _this._getDefines();\n _this.updateEffect(defines);\n _this.onApplyObservable.add(function (effect) {\n var texelSize = _this.texelSize;\n effect.setFloat2(\"texelSize\", texelSize.x, texelSize.y);\n });\n return _this;\n }\n FxaaPostProcess.prototype._getDefines = function () {\n var engine = this.getEngine();\n if (!engine) {\n return null;\n }\n var glInfo = engine.getGlInfo();\n if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf(\"mali\") > -1) {\n return \"#define MALI 1\\n\";\n }\n return null;\n };\n return FxaaPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.FxaaPostProcess = FxaaPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.fxaaPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen\n */\n var ChromaticAberrationPostProcess = /** @class */ (function (_super) {\n __extends(ChromaticAberrationPostProcess, _super);\n /**\n * Creates a new instance ChromaticAberrationPostProcess\n * @param name The name of the effect.\n * @param screenWidth The width of the screen to apply the effect on.\n * @param screenHeight The height of the screen to apply the effect on.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"chromaticAberration\", [\"chromatic_aberration\", \"screen_width\", \"screen_height\", \"direction\", \"radialIntensity\", \"centerPosition\"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;\n /**\n * The amount of seperation of rgb channels (default: 30)\n */\n _this.aberrationAmount = 30;\n /**\n * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)\n */\n _this.radialIntensity = 0;\n /**\n * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))\n */\n _this.direction = new BABYLON.Vector2(0.707, 0.707);\n /**\n * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))\n */\n _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);\n _this.onApplyObservable.add(function (effect) {\n effect.setFloat('chromatic_aberration', _this.aberrationAmount);\n effect.setFloat('screen_width', screenWidth);\n effect.setFloat('screen_height', screenHeight);\n effect.setFloat('radialIntensity', _this.radialIntensity);\n effect.setFloat2('direction', _this.direction.x, _this.direction.y);\n effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);\n });\n return _this;\n }\n return ChromaticAberrationPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The GrainPostProcess adds noise to the image at mid luminance levels\n */\n var GrainPostProcess = /** @class */ (function (_super) {\n __extends(GrainPostProcess, _super);\n /**\n * Creates a new instance of @see GrainPostProcess\n * @param name The name of the effect.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"grain\", [\"intensity\", \"animatedSeed\"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;\n /**\n * The intensity of the grain added (default: 30)\n */\n _this.intensity = 30;\n /**\n * If the grain should be randomized on every frame\n */\n _this.animated = false;\n _this.onApplyObservable.add(function (effect) {\n effect.setFloat('intensity', _this.intensity);\n effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);\n });\n return _this;\n }\n return GrainPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.GrainPostProcess = GrainPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.grainPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The SharpenPostProcess applies a sharpen kernel to every pixel\n * See http://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n var SharpenPostProcess = /** @class */ (function (_super) {\n __extends(SharpenPostProcess, _super);\n /**\n * Creates a new instance ConvolutionPostProcess\n * @param name The name of the effect.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"sharpen\", [\"sharpnessAmounts\", \"screenSize\"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;\n /**\n * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)\n */\n _this.colorAmount = 1.0;\n /**\n * How much sharpness should be applied (default: 0.3)\n */\n _this.edgeAmount = 0.3;\n _this.onApply = function (effect) {\n effect.setFloat2(\"screenSize\", _this.width, _this.height);\n effect.setFloat2(\"sharpnessAmounts\", _this.edgeAmount, _this.colorAmount);\n };\n return _this;\n }\n return SharpenPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.SharpenPostProcess = SharpenPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sharpenPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The Blur Post Process which blurs an image based on a kernel and direction.\n * Can be used twice in x and y directions to perform a guassian blur in two passes.\n */\n var BlurPostProcess = /** @class */ (function (_super) {\n __extends(BlurPostProcess, _super);\n /**\n * Creates a new instance BlurPostProcess\n * @param name The name of the effect.\n * @param direction The direction in which to blur the image.\n * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.\n * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function BlurPostProcess(name, \n /** The direction in which to blur the image. */\n direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (defines === void 0) { defines = \"\"; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"kernelBlur\", [\"delta\", \"direction\", \"cameraMinMaxZ\"], [\"circleOfConfusionSampler\"], options, camera, samplingMode, engine, reusable, null, textureType, \"kernelBlur\", { varyingCount: 0, depCount: 0 }, true) || this;\n _this.direction = direction;\n _this.blockCompilation = blockCompilation;\n _this._packedFloat = false;\n _this._staticDefines = \"\";\n _this._staticDefines = defines;\n _this.onApplyObservable.add(function (effect) {\n if (_this._outputTexture) {\n effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);\n }\n else {\n effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);\n }\n });\n _this.kernel = kernel;\n return _this;\n }\n Object.defineProperty(BlurPostProcess.prototype, \"kernel\", {\n /**\n * Gets the length in pixels of the blur sample region\n */\n get: function () {\n return this._idealKernel;\n },\n /**\n * Sets the length in pixels of the blur sample region\n */\n set: function (v) {\n if (this._idealKernel === v) {\n return;\n }\n v = Math.max(v, 1);\n this._idealKernel = v;\n this._kernel = this._nearestBestKernel(v);\n if (!this.blockCompilation) {\n this._updateParameters();\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BlurPostProcess.prototype, \"packedFloat\", {\n /**\n * Gets wether or not the blur is unpacking/repacking floats\n */\n get: function () {\n return this._packedFloat;\n },\n /**\n * Sets wether or not the blur needs to unpack/repack floats\n */\n set: function (v) {\n if (this._packedFloat === v) {\n return;\n }\n this._packedFloat = v;\n if (!this.blockCompilation) {\n this._updateParameters();\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Updates the effect with the current post process compile time values and recompiles the shader.\n * @param defines Define statements that should be added at the beginning of the shader. (default: null)\n * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)\n * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)\n * @param indexParameters The index parameters to be used for babylons include syntax \"#include[0..varyingCount]\". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx\n * @param onCompiled Called when the shader has been compiled.\n * @param onError Called if there is an error when compiling a shader.\n */\n BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {\n if (defines === void 0) { defines = null; }\n if (uniforms === void 0) { uniforms = null; }\n if (samplers === void 0) { samplers = null; }\n this._updateParameters(onCompiled, onError);\n };\n BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {\n // Generate sampling offsets and weights\n var N = this._kernel;\n var centerIndex = (N - 1) / 2;\n // Generate Gaussian sampling weights over kernel\n var offsets = [];\n var weights = [];\n var totalWeight = 0;\n for (var i = 0; i < N; i++) {\n var u = i / (N - 1);\n var w = this._gaussianWeight(u * 2.0 - 1);\n offsets[i] = (i - centerIndex);\n weights[i] = w;\n totalWeight += w;\n }\n // Normalize weights\n for (var i = 0; i < weights.length; i++) {\n weights[i] /= totalWeight;\n }\n // Optimize: combine samples to take advantage of hardware linear sampling\n // Walk from left to center, combining pairs (symmetrically)\n var linearSamplingWeights = [];\n var linearSamplingOffsets = [];\n var linearSamplingMap = [];\n for (var i = 0; i <= centerIndex; i += 2) {\n var j = Math.min(i + 1, Math.floor(centerIndex));\n var singleCenterSample = i === j;\n if (singleCenterSample) {\n linearSamplingMap.push({ o: offsets[i], w: weights[i] });\n }\n else {\n var sharedCell = j === centerIndex;\n var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));\n var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);\n if (offsetLinear === 0) {\n linearSamplingMap.push({ o: offsets[i], w: weights[i] });\n linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });\n }\n else {\n linearSamplingMap.push({ o: offsetLinear, w: weightLinear });\n linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });\n }\n }\n }\n for (var i = 0; i < linearSamplingMap.length; i++) {\n linearSamplingOffsets[i] = linearSamplingMap[i].o;\n linearSamplingWeights[i] = linearSamplingMap[i].w;\n }\n // Replace with optimized\n offsets = linearSamplingOffsets;\n weights = linearSamplingWeights;\n // Generate shaders\n var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;\n var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter\n var varyingCount = Math.min(offsets.length, freeVaryingVec2);\n var defines = \"\";\n defines += this._staticDefines;\n // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.\n if (this._staticDefines.indexOf(\"DOF\") != -1) {\n defines += \"#define CENTER_WEIGHT \" + this._glslFloat(weights[varyingCount - 1]) + \"\\r\\n\";\n varyingCount--;\n }\n for (var i = 0; i < varyingCount; i++) {\n defines += \"#define KERNEL_OFFSET\" + i + \" \" + this._glslFloat(offsets[i]) + \"\\r\\n\";\n defines += \"#define KERNEL_WEIGHT\" + i + \" \" + this._glslFloat(weights[i]) + \"\\r\\n\";\n }\n var depCount = 0;\n for (var i = freeVaryingVec2; i < offsets.length; i++) {\n defines += \"#define KERNEL_DEP_OFFSET\" + depCount + \" \" + this._glslFloat(offsets[i]) + \"\\r\\n\";\n defines += \"#define KERNEL_DEP_WEIGHT\" + depCount + \" \" + this._glslFloat(weights[i]) + \"\\r\\n\";\n depCount++;\n }\n if (this.packedFloat) {\n defines += \"#define PACKEDFLOAT 1\";\n }\n this.blockCompilation = false;\n _super.prototype.updateEffect.call(this, defines, null, null, {\n varyingCount: varyingCount,\n depCount: depCount\n }, onCompiled, onError);\n };\n /**\n * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.\n * Other odd kernels optimize correctly but require proportionally more samples, even kernels are\n * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we\n * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.\n * The gaps between physical kernels are compensated for in the weighting of the samples\n * @param idealKernel Ideal blur kernel.\n * @return Nearest best kernel.\n */\n BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {\n var v = Math.round(idealKernel);\n for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {\n var k = _a[_i];\n if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {\n return Math.max(k, 3);\n }\n }\n return Math.max(v, 3);\n };\n /**\n * Calculates the value of a Gaussian distribution with sigma 3 at a given point.\n * @param x The point on the Gaussian distribution to sample.\n * @return the value of the Gaussian function at x.\n */\n BlurPostProcess.prototype._gaussianWeight = function (x) {\n //reference: Engine/ImageProcessingBlur.cpp #dcc760\n // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],\n // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.\n // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is\n // truncated at around 1.3% of peak strength.\n //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size\n var sigma = (1 / 3);\n var denominator = Math.sqrt(2.0 * Math.PI) * sigma;\n var exponent = -((x * x) / (2.0 * sigma * sigma));\n var weight = (1.0 / denominator) * Math.exp(exponent);\n return weight;\n };\n /**\n * Generates a string that can be used as a floating point number in GLSL.\n * @param x Value to print.\n * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).\n * @return GLSL float string.\n */\n BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {\n if (decimalFigures === void 0) { decimalFigures = 8; }\n return x.toFixed(decimalFigures).replace(/0+$/, '');\n };\n return BlurPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.BlurPostProcess = BlurPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.blurPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The DepthOfFieldBlurPostProcess applied a blur in a give direction.\n * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels\n * based on samples that have a large difference in distance than the center pixel.\n * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf\n */\n var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {\n __extends(DepthOfFieldBlurPostProcess, _super);\n /**\n * Creates a new instance CircleOfConfusionPostProcess\n * @param name The name of the effect.\n * @param scene The scene the effect belongs to.\n * @param direction The direction the blur should be applied.\n * @param kernel The size of the kernel used to blur.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges\n * @param imageToBlur The image to apply the blur to (default: Current rendered frame)\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (imageToBlur === void 0) { imageToBlur = null; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, \"#define DOF 1\\r\\n\", blockCompilation) || this;\n _this.direction = direction;\n _this.onApplyObservable.add(function (effect) {\n if (imageToBlur != null) {\n effect.setTextureFromPostProcess(\"textureSampler\", imageToBlur);\n }\n effect.setTextureFromPostProcessOutput(\"circleOfConfusionSampler\", circleOfConfusion);\n if (scene.activeCamera) {\n effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);\n }\n });\n return _this;\n }\n return DepthOfFieldBlurPostProcess;\n }(BABYLON.BlurPostProcess));\n BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Options to be set when merging outputs from the default pipeline.\n */\n var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {\n function DepthOfFieldMergePostProcessOptions() {\n }\n return DepthOfFieldMergePostProcessOptions;\n }());\n BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;\n /**\n * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.\n */\n var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {\n __extends(DepthOfFieldMergePostProcess, _super);\n /**\n * Creates a new instance of DepthOfFieldMergePostProcess\n * @param name The name of the effect.\n * @param originalFromInput Post process which's input will be used for the merge.\n * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.\n * @param blurSteps Blur post processes from low to high which will be mixed with the original image.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"depthOfFieldMerge\", [], [\"circleOfConfusionSampler\", \"blurStep0\", \"blurStep1\", \"blurStep2\"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;\n _this.blurSteps = blurSteps;\n _this.onApplyObservable.add(function (effect) {\n effect.setTextureFromPostProcess(\"textureSampler\", originalFromInput);\n effect.setTextureFromPostProcessOutput(\"circleOfConfusionSampler\", circleOfConfusion);\n blurSteps.forEach(function (step, index) {\n effect.setTextureFromPostProcessOutput(\"blurStep\" + (blurSteps.length - index - 1), step);\n });\n });\n if (!blockCompilation) {\n _this.updateEffect();\n }\n return _this;\n }\n /**\n * Updates the effect with the current post process compile time values and recompiles the shader.\n * @param defines Define statements that should be added at the beginning of the shader. (default: null)\n * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)\n * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)\n * @param indexParameters The index parameters to be used for babylons include syntax \"#include[0..varyingCount]\". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx\n * @param onCompiled Called when the shader has been compiled.\n * @param onError Called if there is an error when compiling a shader.\n */\n DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {\n if (defines === void 0) { defines = null; }\n if (uniforms === void 0) { uniforms = null; }\n if (samplers === void 0) { samplers = null; }\n if (!defines) {\n defines = \"\";\n defines += \"#define BLUR_LEVEL \" + (this.blurSteps.length - 1) + \"\\n\";\n }\n _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);\n };\n return DepthOfFieldMergePostProcess;\n }(BABYLON.PostProcess));\n BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion\n */\n var CircleOfConfusionPostProcess = /** @class */ (function (_super) {\n __extends(CircleOfConfusionPostProcess, _super);\n /**\n * Creates a new instance CircleOfConfusionPostProcess\n * @param name The name of the effect.\n * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"circleOfConfusion\", [\"cameraMinMaxZ\", \"focusDistance\", \"cocPrecalculation\"], [\"depthSampler\"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;\n /**\n * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.\n */\n _this.lensSize = 50;\n /**\n * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)\n */\n _this.fStop = 1.4;\n /**\n * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)\n */\n _this.focusDistance = 2000;\n /**\n * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)\n */\n _this.focalLength = 50;\n _this._depthTexture = null;\n _this._depthTexture = depthTexture;\n _this.onApplyObservable.add(function (effect) {\n if (!_this._depthTexture) {\n BABYLON.Tools.Warn(\"No depth texture set on CircleOfConfusionPostProcess\");\n return;\n }\n effect.setTexture(\"depthSampler\", _this._depthTexture);\n // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html\n var aperture = _this.lensSize / _this.fStop;\n var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]\n effect.setFloat('focusDistance', _this.focusDistance);\n effect.setFloat('cocPrecalculation', cocPrecalculation);\n effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);\n });\n return _this;\n }\n Object.defineProperty(CircleOfConfusionPostProcess.prototype, \"depthTexture\", {\n /**\n * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.\n */\n set: function (value) {\n this._depthTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n return CircleOfConfusionPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Specifies the level of max blur that should be applied when using the depth of field effect\n */\n var DepthOfFieldEffectBlurLevel;\n (function (DepthOfFieldEffectBlurLevel) {\n /**\n * Subtle blur\n */\n DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel[\"Low\"] = 0] = \"Low\";\n /**\n * Medium blur\n */\n DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel[\"Medium\"] = 1] = \"Medium\";\n /**\n * Large blur\n */\n DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel[\"High\"] = 2] = \"High\";\n })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));\n ;\n /**\n * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.\n */\n var DepthOfFieldEffect = /** @class */ (function (_super) {\n __extends(DepthOfFieldEffect, _super);\n /**\n * Creates a new instance DepthOfFieldEffect\n * @param scene The scene the effect belongs to.\n * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.\n * @param pipelineTextureType The type of texture to be used when performing the post processing.\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {\n if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }\n if (pipelineTextureType === void 0) { pipelineTextureType = 0; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, scene.getEngine(), \"depth of field\", function () {\n return _this._effects;\n }, true) || this;\n /**\n * Internal post processes in depth of field effect\n */\n _this._effects = [];\n // Circle of confusion value for each pixel is used to determine how much to blur that pixel\n _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess(\"circleOfConfusion\", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);\n // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)\n // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts \n // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf\n _this._depthOfFieldBlurY = [];\n _this._depthOfFieldBlurX = [];\n var blurCount = 1;\n var kernelSize = 15;\n switch (blurLevel) {\n case DepthOfFieldEffectBlurLevel.High: {\n blurCount = 3;\n kernelSize = 51;\n break;\n }\n case DepthOfFieldEffectBlurLevel.Medium: {\n blurCount = 2;\n kernelSize = 31;\n break;\n }\n default: {\n kernelSize = 15;\n blurCount = 1;\n break;\n }\n }\n var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);\n var ratio = 1.0;\n for (var i = 0; i < blurCount; i++) {\n var blurY = new BABYLON.DepthOfFieldBlurPostProcess(\"verticle blur\", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);\n blurY.autoClear = false;\n ratio = 0.75 / Math.pow(2, i);\n var blurX = new BABYLON.DepthOfFieldBlurPostProcess(\"horizontal blur\", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);\n blurX.autoClear = false;\n _this._depthOfFieldBlurY.push(blurY);\n _this._depthOfFieldBlurX.push(blurX);\n }\n // Set all post processes on the effect.\n _this._effects = [_this._circleOfConfusion];\n for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {\n _this._effects.push(_this._depthOfFieldBlurY[i]);\n _this._effects.push(_this._depthOfFieldBlurX[i]);\n }\n // Merge blurred images with original image based on circleOfConfusion\n _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess(\"dofMerge\", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);\n _this._dofMerge.autoClear = false;\n _this._effects.push(_this._dofMerge);\n return _this;\n }\n Object.defineProperty(DepthOfFieldEffect.prototype, \"focalLength\", {\n get: function () {\n return this._circleOfConfusion.focalLength;\n },\n /**\n * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)\n */\n set: function (value) {\n this._circleOfConfusion.focalLength = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DepthOfFieldEffect.prototype, \"fStop\", {\n get: function () {\n return this._circleOfConfusion.fStop;\n },\n /**\n * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)\n */\n set: function (value) {\n this._circleOfConfusion.fStop = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DepthOfFieldEffect.prototype, \"focusDistance\", {\n get: function () {\n return this._circleOfConfusion.focusDistance;\n },\n /**\n * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)\n */\n set: function (value) {\n this._circleOfConfusion.focusDistance = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DepthOfFieldEffect.prototype, \"lensSize\", {\n get: function () {\n return this._circleOfConfusion.lensSize;\n },\n /**\n * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.\n */\n set: function (value) {\n this._circleOfConfusion.lensSize = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DepthOfFieldEffect.prototype, \"depthTexture\", {\n /**\n * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.\n */\n set: function (value) {\n this._circleOfConfusion.depthTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes each of the internal effects for a given camera.\n * @param camera The camera to dispose the effect on.\n */\n DepthOfFieldEffect.prototype.disposeEffects = function (camera) {\n for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {\n this._effects[effectIndex].dispose(camera);\n }\n };\n /**\n * Internal\n */\n DepthOfFieldEffect.prototype._updateEffects = function () {\n for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {\n this._effects[effectIndex].updateEffect();\n }\n };\n /**\n * Internal\n * @returns if all the contained post processes are ready.\n */\n DepthOfFieldEffect.prototype._isReady = function () {\n for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {\n if (!this._effects[effectIndex].isReady()) {\n return false;\n }\n }\n return true;\n };\n return DepthOfFieldEffect;\n }(BABYLON.PostProcessRenderEffect));\n BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.depthOfFieldEffect.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.\n */\n var BloomMergePostProcess = /** @class */ (function (_super) {\n __extends(BloomMergePostProcess, _super);\n /**\n * Creates a new instance of @see BloomMergePostProcess\n * @param name The name of the effect.\n * @param originalFromInput Post process which's input will be used for the merge.\n * @param blurred Blurred highlights post process which's output will be used.\n * @param weight Weight of the bloom to be added to the original input.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function BloomMergePostProcess(name, originalFromInput, blurred, \n /** Weight of the bloom to be added to the original input. */\n weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"bloomMerge\", [\"bloomWeight\"], [\"circleOfConfusionSampler\", \"blurStep0\", \"blurStep1\", \"blurStep2\", \"bloomBlur\"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;\n _this.weight = weight;\n _this.onApplyObservable.add(function (effect) {\n effect.setTextureFromPostProcess(\"textureSampler\", originalFromInput);\n effect.setTextureFromPostProcessOutput(\"bloomBlur\", blurred);\n effect.setFloat(\"bloomWeight\", _this.weight);\n });\n if (!blockCompilation) {\n _this.updateEffect();\n }\n return _this;\n }\n return BloomMergePostProcess;\n }(BABYLON.PostProcess));\n BABYLON.BloomMergePostProcess = BloomMergePostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.bloomMergePostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.\n */\n var ExtractHighlightsPostProcess = /** @class */ (function (_super) {\n __extends(ExtractHighlightsPostProcess, _super);\n function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, name, \"extractHighlights\", [\"threshold\", \"exposure\"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;\n /**\n * The luminance threshold, pixels below this value will be set to black.\n */\n _this.threshold = 0.9;\n /**\n * Internal\n */\n _this._exposure = 1;\n /**\n * Post process which has the input texture to be used when performing highlight extraction\n */\n _this._inputPostProcess = null;\n _this.onApplyObservable.add(function (effect) {\n if (_this._inputPostProcess) {\n effect.setTextureFromPostProcess(\"textureSampler\", _this._inputPostProcess);\n }\n effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));\n effect.setFloat('exposure', _this._exposure);\n });\n return _this;\n }\n return ExtractHighlightsPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras\n */\n var BloomEffect = /** @class */ (function (_super) {\n __extends(BloomEffect, _super);\n /**\n * Creates a new instance of @see BloomEffect\n * @param scene The scene the effect belongs to.\n * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.\n * @param bloomKernel The size of the kernel to be used when applying the blur.\n * @param bloomWeight The the strength of bloom.\n * @param pipelineTextureType The type of texture to be used when performing the post processing.\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {\n if (pipelineTextureType === void 0) { pipelineTextureType = 0; }\n if (blockCompilation === void 0) { blockCompilation = false; }\n var _this = _super.call(this, scene.getEngine(), \"bloom\", function () {\n return _this._effects;\n }, true) || this;\n _this.bloomScale = bloomScale;\n /**\n * Internal\n */\n _this._effects = [];\n _this._downscale = new BABYLON.ExtractHighlightsPostProcess(\"highlights\", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);\n _this._blurX = new BABYLON.BlurPostProcess(\"horizontal blur\", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);\n _this._blurX.alwaysForcePOT = true;\n _this._blurX.autoClear = false;\n _this._blurY = new BABYLON.BlurPostProcess(\"vertical blur\", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);\n _this._blurY.alwaysForcePOT = true;\n _this._blurY.autoClear = false;\n _this.kernel = bloomKernel;\n _this._effects = [_this._downscale, _this._blurX, _this._blurY];\n _this._merge = new BABYLON.BloomMergePostProcess(\"bloomMerge\", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);\n _this._merge.autoClear = false;\n _this._effects.push(_this._merge);\n return _this;\n }\n Object.defineProperty(BloomEffect.prototype, \"threshold\", {\n /**\n * The luminance threshold to find bright areas of the image to bloom.\n */\n get: function () {\n return this._downscale.threshold;\n },\n set: function (value) {\n this._downscale.threshold = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BloomEffect.prototype, \"weight\", {\n /**\n * The strength of the bloom.\n */\n get: function () {\n return this._merge.weight;\n },\n set: function (value) {\n this._merge.weight = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BloomEffect.prototype, \"kernel\", {\n /**\n * Specifies the size of the bloom blur kernel, relative to the final output size\n */\n get: function () {\n return this._blurX.kernel / this.bloomScale;\n },\n set: function (value) {\n this._blurX.kernel = value * this.bloomScale;\n this._blurY.kernel = value * this.bloomScale;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes each of the internal effects for a given camera.\n * @param camera The camera to dispose the effect on.\n */\n BloomEffect.prototype.disposeEffects = function (camera) {\n for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {\n this._effects[effectIndex].dispose(camera);\n }\n };\n /**\n * Internal\n */\n BloomEffect.prototype._updateEffects = function () {\n for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {\n this._effects[effectIndex].updateEffect();\n }\n };\n /**\n * Internal\n * @returns if all the contained post processes are ready.\n */\n BloomEffect.prototype._isReady = function () {\n for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {\n if (!this._effects[effectIndex].isReady()) {\n return false;\n }\n }\n return true;\n };\n return BloomEffect;\n }(BABYLON.PostProcessRenderEffect));\n BABYLON.BloomEffect = BloomEffect;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.bloomEffect.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.\n * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline\n */\n var DefaultRenderingPipeline = /** @class */ (function (_super) {\n __extends(DefaultRenderingPipeline, _super);\n /**\n * @constructor\n * @param {string} name - The rendering pipeline name (default: \"\")\n * @param {boolean} hdr - If high dynamic range textures should be used (default: true)\n * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)\n * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)\n * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)\n */\n function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {\n if (name === void 0) { name = \"\"; }\n if (hdr === void 0) { hdr = true; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n if (automaticBuild === void 0) { automaticBuild = true; }\n var _this = _super.call(this, scene.getEngine(), name) || this;\n _this._camerasToBeAttached = [];\n /**\n * ID of the sharpen post process,\n */\n _this.SharpenPostProcessId = \"SharpenPostProcessEffect\";\n /**\n * ID of the image processing post process;\n */\n _this.ImageProcessingPostProcessId = \"ImageProcessingPostProcessEffect\";\n /**\n * ID of the Fast Approximate Anti-Aliasing post process;\n */\n _this.FxaaPostProcessId = \"FxaaPostProcessEffect\";\n /**\n * ID of the chromatic aberration post process,\n */\n _this.ChromaticAberrationPostProcessId = \"ChromaticAberrationPostProcessEffect\";\n /**\n * ID of the grain post process\n */\n _this.GrainPostProcessId = \"GrainPostProcessEffect\";\n /**\n * Glow post process which adds a glow to emmisive areas of the image\n */\n _this._glowLayer = null;\n /**\n * Animations which can be used to tweak settings over a period of time\n */\n _this.animations = [];\n _this._imageProcessingConfigurationObserver = null;\n // Values \n _this._sharpenEnabled = false;\n _this._bloomEnabled = false;\n _this._depthOfFieldEnabled = false;\n _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;\n _this._fxaaEnabled = false;\n _this._imageProcessingEnabled = true;\n _this._bloomScale = 0.5;\n _this._chromaticAberrationEnabled = false;\n _this._grainEnabled = false;\n _this._buildAllowed = true;\n _this._resizeObserver = null;\n _this._hardwareScaleLevel = 1.0;\n _this._bloomKernel = 64;\n /**\n * Specifies the weight of the bloom in the final rendering\n */\n _this._bloomWeight = 0.15;\n /**\n * Specifies the luma threshold for the area that will be blurred by the bloom\n */\n _this._bloomThreshold = 0.9;\n _this._samples = 1;\n _this._hasCleared = false;\n _this._prevPostProcess = null;\n _this._prevPrevPostProcess = null;\n _this._cameras = cameras || scene.cameras;\n _this._camerasToBeAttached = _this._cameras.slice();\n _this._buildAllowed = automaticBuild;\n // Initialize\n _this._scene = scene;\n var caps = _this._scene.getEngine().getCaps();\n _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);\n // Misc\n if (_this._hdr) {\n if (caps.textureHalfFloatRender) {\n _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else if (caps.textureFloatRender) {\n _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n }\n else {\n _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n // Attach\n scene.postProcessRenderPipelineManager.addPipeline(_this);\n var engine = _this._scene.getEngine();\n // Create post processes before hand so they can be modified before enabled.\n // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.\n _this.sharpen = new BABYLON.SharpenPostProcess(\"sharpen\", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);\n _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);\n _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);\n _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);\n _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess(\"ChromaticAberration\", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);\n _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);\n _this.grain = new BABYLON.GrainPostProcess(\"Grain\", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);\n _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);\n _this._resizeObserver = engine.onResizeObservable.add(function () {\n _this._hardwareScaleLevel = engine.getHardwareScalingLevel();\n _this.bloomKernel = _this.bloomKernel;\n });\n _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {\n _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;\n });\n _this._buildPipeline();\n return _this;\n }\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"sharpenEnabled\", {\n get: function () {\n return this._sharpenEnabled;\n },\n /**\n * Enable or disable the sharpen process from the pipeline\n */\n set: function (enabled) {\n if (this._sharpenEnabled === enabled) {\n return;\n }\n this._sharpenEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"bloomKernel\", {\n /**\n * Specifies the size of the bloom blur kernel, relative to the final output size\n */\n get: function () {\n return this._bloomKernel;\n },\n set: function (value) {\n this._bloomKernel = value;\n this.bloom.kernel = value / this._hardwareScaleLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"bloomWeight\", {\n get: function () {\n return this._bloomWeight;\n },\n /**\n * The strength of the bloom.\n */\n set: function (value) {\n if (this._bloomWeight === value) {\n return;\n }\n this.bloom.weight = value;\n this._bloomWeight = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"bloomThreshold\", {\n get: function () {\n return this._bloomThreshold;\n },\n /**\n * The strength of the bloom.\n */\n set: function (value) {\n if (this._bloomThreshold === value) {\n return;\n }\n this.bloom.threshold = value;\n this._bloomThreshold = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"bloomScale\", {\n get: function () {\n return this._bloomScale;\n },\n /**\n * The scale of the bloom, lower value will provide better performance.\n */\n set: function (value) {\n if (this._bloomScale === value) {\n return;\n }\n this._bloomScale = value;\n // recreate bloom and dispose old as this setting is not dynamic\n this._rebuildBloom();\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"bloomEnabled\", {\n get: function () {\n return this._bloomEnabled;\n },\n /**\n * Enable or disable the bloom from the pipeline\n */\n set: function (enabled) {\n if (this._bloomEnabled === enabled) {\n return;\n }\n this._bloomEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n DefaultRenderingPipeline.prototype._rebuildBloom = function () {\n // recreate bloom and dispose old as this setting is not dynamic\n var oldBloom = this.bloom;\n this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);\n this.bloom.threshold = oldBloom.threshold;\n for (var i = 0; i < this._cameras.length; i++) {\n oldBloom.disposeEffects(this._cameras[i]);\n }\n };\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"depthOfFieldEnabled\", {\n /**\n * If the depth of field is enabled.\n */\n get: function () {\n return this._depthOfFieldEnabled;\n },\n set: function (enabled) {\n if (this._depthOfFieldEnabled === enabled) {\n return;\n }\n this._depthOfFieldEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"depthOfFieldBlurLevel\", {\n /**\n * Blur level of the depth of field effect. (Higher blur will effect performance)\n */\n get: function () {\n return this._depthOfFieldBlurLevel;\n },\n set: function (value) {\n if (this._depthOfFieldBlurLevel === value) {\n return;\n }\n this._depthOfFieldBlurLevel = value;\n // recreate dof and dispose old as this setting is not dynamic\n var oldDof = this.depthOfField;\n this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);\n this.depthOfField.focalLength = oldDof.focalLength;\n this.depthOfField.focusDistance = oldDof.focusDistance;\n this.depthOfField.fStop = oldDof.fStop;\n this.depthOfField.lensSize = oldDof.lensSize;\n for (var i = 0; i < this._cameras.length; i++) {\n oldDof.disposeEffects(this._cameras[i]);\n }\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"fxaaEnabled\", {\n get: function () {\n return this._fxaaEnabled;\n },\n /**\n * If the anti aliasing is enabled.\n */\n set: function (enabled) {\n if (this._fxaaEnabled === enabled) {\n return;\n }\n this._fxaaEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"samples\", {\n get: function () {\n return this._samples;\n },\n /**\n * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)\n */\n set: function (sampleCount) {\n if (this._samples === sampleCount) {\n return;\n }\n this._samples = sampleCount;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"imageProcessingEnabled\", {\n get: function () {\n return this._imageProcessingEnabled;\n },\n /**\n * If image processing is enabled.\n */\n set: function (enabled) {\n if (this._imageProcessingEnabled === enabled) {\n return;\n }\n this._imageProcessingEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"glowLayerEnabled\", {\n get: function () {\n return this._glowLayer == null;\n },\n /**\n * If glow layer is enabled. (Adds a glow effect to emmissive materials)\n */\n set: function (enabled) {\n if (enabled && !this._glowLayer) {\n this._glowLayer = new BABYLON.GlowLayer(\"\", this._scene);\n }\n else if (!enabled && this._glowLayer) {\n this._glowLayer.dispose();\n this._glowLayer = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"chromaticAberrationEnabled\", {\n get: function () {\n return this._chromaticAberrationEnabled;\n },\n /**\n * Enable or disable the chromaticAberration process from the pipeline\n */\n set: function (enabled) {\n if (this._chromaticAberrationEnabled === enabled) {\n return;\n }\n this._chromaticAberrationEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DefaultRenderingPipeline.prototype, \"grainEnabled\", {\n get: function () {\n return this._grainEnabled;\n },\n /**\n * Enable or disable the grain process from the pipeline\n */\n set: function (enabled) {\n if (this._grainEnabled === enabled) {\n return;\n }\n this._grainEnabled = enabled;\n this._buildPipeline();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Force the compilation of the entire pipeline.\n */\n DefaultRenderingPipeline.prototype.prepare = function () {\n var previousState = this._buildAllowed;\n this._buildAllowed = true;\n this._buildPipeline();\n this._buildAllowed = previousState;\n };\n DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {\n if (skipTextureSharing === void 0) { skipTextureSharing = false; }\n if (this._hasCleared) {\n postProcess.autoClear = false;\n }\n else {\n postProcess.autoClear = true;\n this._scene.autoClear = false;\n this._hasCleared = true;\n }\n if (!skipTextureSharing) {\n if (this._prevPrevPostProcess) {\n postProcess.shareOutputWith(this._prevPrevPostProcess);\n }\n else {\n postProcess.useOwnOutput();\n }\n if (this._prevPostProcess) {\n this._prevPrevPostProcess = this._prevPostProcess;\n }\n this._prevPostProcess = postProcess;\n }\n };\n DefaultRenderingPipeline.prototype._buildPipeline = function () {\n var _this = this;\n if (!this._buildAllowed) {\n return;\n }\n this._scene.autoClear = true;\n var engine = this._scene.getEngine();\n this._disposePostProcesses();\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n // get back cameras to be used to reattach pipeline\n this._cameras = this._camerasToBeAttached.slice();\n }\n this._reset();\n this._prevPostProcess = null;\n this._prevPrevPostProcess = null;\n this._hasCleared = false;\n if (this.depthOfFieldEnabled) {\n var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();\n this.depthOfField.depthTexture = depthTexture;\n if (!this.depthOfField._isReady()) {\n this.depthOfField._updateEffects();\n }\n this.addEffect(this.depthOfField);\n this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);\n }\n if (this.bloomEnabled) {\n if (!this.bloom._isReady()) {\n this.bloom._updateEffects();\n }\n this.addEffect(this.bloom);\n this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);\n }\n if (this._imageProcessingEnabled) {\n this.imageProcessing = new BABYLON.ImageProcessingPostProcess(\"imageProcessing\", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);\n if (this._hdr) {\n this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));\n this._setAutoClearAndTextureSharing(this.imageProcessing);\n }\n else {\n this._scene.imageProcessingConfiguration.applyByPostProcess = false;\n }\n }\n if (this.sharpenEnabled) {\n if (!this.sharpen.isReady()) {\n this.sharpen.updateEffect();\n }\n this.addEffect(this._sharpenEffect);\n this._setAutoClearAndTextureSharing(this.sharpen);\n }\n if (this.grainEnabled) {\n if (!this.grain.isReady()) {\n this.grain.updateEffect();\n }\n this.addEffect(this._grainEffect);\n this._setAutoClearAndTextureSharing(this.grain);\n }\n if (this.chromaticAberrationEnabled) {\n if (!this.chromaticAberration.isReady()) {\n this.chromaticAberration.updateEffect();\n }\n this.addEffect(this._chromaticAberrationEffect);\n this._setAutoClearAndTextureSharing(this.chromaticAberration);\n }\n if (this.fxaaEnabled) {\n this.fxaa = new BABYLON.FxaaPostProcess(\"fxaa\", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);\n this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));\n this._setAutoClearAndTextureSharing(this.fxaa, true);\n }\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);\n }\n if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {\n BABYLON.Tools.Warn(\"MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0\");\n }\n };\n DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {\n if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }\n for (var i = 0; i < this._cameras.length; i++) {\n var camera = this._cameras[i];\n if (this.imageProcessing) {\n this.imageProcessing.dispose(camera);\n }\n if (this.fxaa) {\n this.fxaa.dispose(camera);\n }\n // These are created in the constructor and should not be disposed on every pipeline change\n if (disposeNonRecreated) {\n if (this.sharpen) {\n this.sharpen.dispose(camera);\n }\n if (this.depthOfField) {\n this.depthOfField.disposeEffects(camera);\n }\n if (this.bloom) {\n this.bloom.disposeEffects(camera);\n }\n if (this.chromaticAberration) {\n this.chromaticAberration.dispose(camera);\n }\n if (this.grain) {\n this.grain.dispose(camera);\n }\n if (this._glowLayer) {\n this._glowLayer.dispose();\n }\n }\n }\n this.imageProcessing = null;\n this.fxaa = null;\n if (disposeNonRecreated) {\n this.sharpen = null;\n this._sharpenEffect = null;\n this.depthOfField = null;\n this.bloom = null;\n this.chromaticAberration = null;\n this._chromaticAberrationEffect = null;\n this.grain = null;\n this._grainEffect = null;\n this._glowLayer = null;\n }\n };\n /**\n * Adds a camera to the pipeline\n * @param camera the camera to be added\n */\n DefaultRenderingPipeline.prototype.addCamera = function (camera) {\n this._camerasToBeAttached.push(camera);\n this._buildPipeline();\n };\n /**\n * Removes a camera from the pipeline\n * @param camera the camera to remove\n */\n DefaultRenderingPipeline.prototype.removeCamera = function (camera) {\n var index = this._camerasToBeAttached.indexOf(camera);\n this._camerasToBeAttached.splice(index, 1);\n this._buildPipeline();\n };\n /**\n * Dispose of the pipeline and stop all post processes\n */\n DefaultRenderingPipeline.prototype.dispose = function () {\n this._disposePostProcesses(true);\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n this._scene.autoClear = true;\n if (this._resizeObserver) {\n this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);\n this._resizeObserver = null;\n }\n this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);\n _super.prototype.dispose.call(this);\n };\n /**\n * Serialize the rendering pipeline (Used when exporting)\n * @returns the serialized object\n */\n DefaultRenderingPipeline.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"DefaultRenderingPipeline\";\n return serializationObject;\n };\n /**\n * Parse the serialized pipeline\n * @param source Source pipeline.\n * @param scene The scene to load the pipeline to.\n * @param rootUrl The URL of the serialized pipeline.\n * @returns An instantiated pipeline from the serialized object.\n */\n DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);\n };\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"sharpenEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"bloomKernel\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"_bloomWeight\", void 0);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"_bloomThreshold\", void 0);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"_hdr\", void 0);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"bloomWeight\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"bloomThreshold\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"bloomScale\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"bloomEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"depthOfFieldEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"depthOfFieldBlurLevel\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"fxaaEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"samples\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"imageProcessingEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"glowLayerEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"chromaticAberrationEnabled\", null);\n __decorate([\n BABYLON.serialize()\n ], DefaultRenderingPipeline.prototype, \"grainEnabled\", null);\n return DefaultRenderingPipeline;\n }(BABYLON.PostProcessRenderPipeline));\n BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.defaultRenderingPipeline.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This renderer is helpfull to fill one of the render target with a geometry buffer.\n */\n var GeometryBufferRenderer = /** @class */ (function () {\n /**\n * Creates a new G Buffer for the scene\n * @param scene The scene the buffer belongs to\n * @param ratio How big is the buffer related to the main canvas.\n */\n function GeometryBufferRenderer(scene, ratio) {\n if (ratio === void 0) { ratio = 1; }\n this._enablePosition = false;\n this._scene = scene;\n this._ratio = ratio;\n // Render target\n this._createRenderTargets();\n }\n Object.defineProperty(GeometryBufferRenderer.prototype, \"renderList\", {\n /**\n * Set the render list (meshes to be rendered) used in the G buffer.\n */\n set: function (meshes) {\n this._multiRenderTarget.renderList = meshes;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeometryBufferRenderer.prototype, \"isSupported\", {\n /**\n * Gets wether or not G buffer are supported by the running hardware.\n * This requires draw buffer supports\n */\n get: function () {\n return this._multiRenderTarget.isSupported;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeometryBufferRenderer.prototype, \"enablePosition\", {\n /**\n * Gets wether or not position are enabled for the G buffer.\n */\n get: function () {\n return this._enablePosition;\n },\n /**\n * Sets wether or not position are enabled for the G buffer.\n */\n set: function (enable) {\n this._enablePosition = enable;\n this.dispose();\n this._createRenderTargets();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeometryBufferRenderer.prototype, \"scene\", {\n /**\n * Gets the scene associated with the buffer.\n */\n get: function () {\n return this._scene;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeometryBufferRenderer.prototype, \"ratio\", {\n /**\n * Gets the ratio used by the buffer during its creation.\n * How big is the buffer related to the main canvas.\n */\n get: function () {\n return this._ratio;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Checks wether everything is ready to render a submesh to the G buffer.\n * @param subMesh the submesh to check readiness for\n * @param useInstances is the mesh drawn using instance or not\n * @returns true if ready otherwise false\n */\n GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {\n var material = subMesh.getMaterial();\n if (material && material.disableDepthWrite) {\n return false;\n }\n var defines = [];\n var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];\n var mesh = subMesh.getMesh();\n // Alpha test\n if (material && material.needAlphaTesting()) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n // Buffers\n if (this._enablePosition) {\n defines.push(\"#define POSITION\");\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n // Get correct effect \n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n this._effect = this._scene.getEngine().createEffect(\"geometry\", attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\", \"view\"], [\"diffuseSampler\"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });\n }\n return this._effect.isReady();\n };\n /**\n * Gets the current underlying G Buffer.\n * @returns the buffer\n */\n GeometryBufferRenderer.prototype.getGBuffer = function () {\n return this._multiRenderTarget;\n };\n Object.defineProperty(GeometryBufferRenderer.prototype, \"samples\", {\n /**\n * Gets the number of samples used to render the buffer (anti aliasing).\n */\n get: function () {\n return this._multiRenderTarget.samples;\n },\n /**\n * Sets the number of samples used to render the buffer (anti aliasing).\n */\n set: function (value) {\n this._multiRenderTarget.samples = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes the renderer and frees up associated resources.\n */\n GeometryBufferRenderer.prototype.dispose = function () {\n this.getGBuffer().dispose();\n };\n GeometryBufferRenderer.prototype._createRenderTargets = function () {\n var _this = this;\n var engine = this._scene.getEngine();\n var count = this._enablePosition ? 3 : 2;\n this._multiRenderTarget = new BABYLON.MultiRenderTarget(\"gBuffer\", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });\n if (!this.isSupported) {\n return;\n }\n this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._multiRenderTarget.refreshRate = 1;\n this._multiRenderTarget.renderParticles = false;\n this._multiRenderTarget.renderList = null;\n // set default depth value to 1.0 (far away)\n this._multiRenderTarget.onClearObservable.add(function (engine) {\n engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);\n });\n // Custom render function\n var renderSubMesh = function (subMesh) {\n var mesh = subMesh.getRenderingMesh();\n var scene = _this._scene;\n var engine = scene.getEngine();\n var material = subMesh.getMaterial();\n if (!material) {\n return;\n }\n // Culling\n engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);\n // Managing instances\n var batch = mesh._getInstancesRenderList(subMesh._id);\n if (batch.mustReturn) {\n return;\n }\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);\n if (_this.isReady(subMesh, hardwareInstancedRendering)) {\n engine.enableEffect(_this._effect);\n mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);\n _this._effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n _this._effect.setMatrix(\"view\", scene.getViewMatrix());\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n _this._effect.setTexture(\"diffuseSampler\", alphaTexture);\n _this._effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n _this._effect.setMatrices(\"mBones\", mesh.skeleton.getTransformMatrices(mesh));\n }\n // Draw\n mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix(\"world\", world); });\n }\n };\n this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {\n var index;\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n };\n };\n return GeometryBufferRenderer;\n }());\n BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.geometryBufferRenderer.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This groups together the common properties used for image processing either in direct forward pass\n * or through post processing effect depending on the use of the image processing pipeline in your scene\n * or not.\n */\n var ImageProcessingConfiguration = /** @class */ (function () {\n function ImageProcessingConfiguration() {\n /**\n * Color curves setup used in the effect if colorCurvesEnabled is set to true\n */\n this.colorCurves = new BABYLON.ColorCurves();\n this._colorCurvesEnabled = false;\n this._colorGradingEnabled = false;\n this._colorGradingWithGreenDepth = true;\n this._colorGradingBGR = true;\n this._exposure = 1.0;\n this._toneMappingEnabled = false;\n this._contrast = 1.0;\n /**\n * Vignette stretch size.\n */\n this.vignetteStretch = 0;\n /**\n * Vignette centre X Offset.\n */\n this.vignetteCentreX = 0;\n /**\n * Vignette centre Y Offset.\n */\n this.vignetteCentreY = 0;\n /**\n * Vignette weight or intensity of the vignette effect.\n */\n this.vignetteWeight = 1.5;\n /**\n * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)\n * if vignetteEnabled is set to true.\n */\n this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);\n /**\n * Camera field of view used by the Vignette effect.\n */\n this.vignetteCameraFov = 0.5;\n this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;\n this._vignetteEnabled = false;\n this._applyByPostProcess = false;\n this._isEnabled = true;\n /**\n * An event triggered when the configuration changes and requires Shader to Update some parameters.\n */\n this.onUpdateParameters = new BABYLON.Observable();\n }\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"colorCurvesEnabled\", {\n /**\n * Gets wether the color curves effect is enabled.\n */\n get: function () {\n return this._colorCurvesEnabled;\n },\n /**\n * Sets wether the color curves effect is enabled.\n */\n set: function (value) {\n if (this._colorCurvesEnabled === value) {\n return;\n }\n this._colorCurvesEnabled = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"colorGradingEnabled\", {\n /**\n * Gets wether the color grading effect is enabled.\n */\n get: function () {\n return this._colorGradingEnabled;\n },\n /**\n * Sets wether the color grading effect is enabled.\n */\n set: function (value) {\n if (this._colorGradingEnabled === value) {\n return;\n }\n this._colorGradingEnabled = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"colorGradingWithGreenDepth\", {\n /**\n * Gets wether the color grading effect is using a green depth for the 3d Texture.\n */\n get: function () {\n return this._colorGradingWithGreenDepth;\n },\n /**\n * Sets wether the color grading effect is using a green depth for the 3d Texture.\n */\n set: function (value) {\n if (this._colorGradingWithGreenDepth === value) {\n return;\n }\n this._colorGradingWithGreenDepth = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"colorGradingBGR\", {\n /**\n * Gets wether the color grading texture contains BGR values.\n */\n get: function () {\n return this._colorGradingBGR;\n },\n /**\n * Sets wether the color grading texture contains BGR values.\n */\n set: function (value) {\n if (this._colorGradingBGR === value) {\n return;\n }\n this._colorGradingBGR = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"exposure\", {\n /**\n * Gets the Exposure used in the effect.\n */\n get: function () {\n return this._exposure;\n },\n /**\n * Sets the Exposure used in the effect.\n */\n set: function (value) {\n if (this._exposure === value) {\n return;\n }\n this._exposure = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"toneMappingEnabled\", {\n /**\n * Gets wether the tone mapping effect is enabled.\n */\n get: function () {\n return this._toneMappingEnabled;\n },\n /**\n * Sets wether the tone mapping effect is enabled.\n */\n set: function (value) {\n if (this._toneMappingEnabled === value) {\n return;\n }\n this._toneMappingEnabled = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"contrast\", {\n /**\n * Gets the contrast used in the effect.\n */\n get: function () {\n return this._contrast;\n },\n /**\n * Sets the contrast used in the effect.\n */\n set: function (value) {\n if (this._contrast === value) {\n return;\n }\n this._contrast = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"vignetteBlendMode\", {\n /**\n * Gets the vignette blend mode allowing different kind of effect.\n */\n get: function () {\n return this._vignetteBlendMode;\n },\n /**\n * Sets the vignette blend mode allowing different kind of effect.\n */\n set: function (value) {\n if (this._vignetteBlendMode === value) {\n return;\n }\n this._vignetteBlendMode = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"vignetteEnabled\", {\n /**\n * Gets wether the vignette effect is enabled.\n */\n get: function () {\n return this._vignetteEnabled;\n },\n /**\n * Sets wether the vignette effect is enabled.\n */\n set: function (value) {\n if (this._vignetteEnabled === value) {\n return;\n }\n this._vignetteEnabled = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"applyByPostProcess\", {\n /**\n * Gets wether the image processing is applied through a post process or not.\n */\n get: function () {\n return this._applyByPostProcess;\n },\n /**\n * Sets wether the image processing is applied through a post process or not.\n */\n set: function (value) {\n if (this._applyByPostProcess === value) {\n return;\n }\n this._applyByPostProcess = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration.prototype, \"isEnabled\", {\n /**\n * Gets wether the image processing is enabled or not.\n */\n get: function () {\n return this._isEnabled;\n },\n /**\n * Sets wether the image processing is enabled or not.\n */\n set: function (value) {\n if (this._isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Method called each time the image processing information changes requires to recompile the effect.\n */\n ImageProcessingConfiguration.prototype._updateParameters = function () {\n this.onUpdateParameters.notifyObservers(this);\n };\n ImageProcessingConfiguration.prototype.getClassName = function () {\n return \"ImageProcessingConfiguration\";\n };\n /**\n * Prepare the list of uniforms associated with the Image Processing effects.\n * @param uniformsList The list of uniforms used in the effect\n * @param defines the list of defines currently in use\n */\n ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {\n if (defines.EXPOSURE) {\n uniforms.push(\"exposureLinear\");\n }\n if (defines.CONTRAST) {\n uniforms.push(\"contrast\");\n }\n if (defines.COLORGRADING) {\n uniforms.push(\"colorTransformSettings\");\n }\n if (defines.VIGNETTE) {\n uniforms.push(\"vInverseScreenSize\");\n uniforms.push(\"vignetteSettings1\");\n uniforms.push(\"vignetteSettings2\");\n }\n if (defines.COLORCURVES) {\n BABYLON.ColorCurves.PrepareUniforms(uniforms);\n }\n };\n /**\n * Prepare the list of samplers associated with the Image Processing effects.\n * @param uniformsList The list of uniforms used in the effect\n * @param defines the list of defines currently in use\n */\n ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {\n if (defines.COLORGRADING) {\n samplersList.push(\"txColorTransform\");\n }\n };\n /**\n * Prepare the list of defines associated to the shader.\n * @param defines the list of defines to complete\n */\n ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {\n if (forPostProcess === void 0) { forPostProcess = false; }\n if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {\n defines.VIGNETTE = false;\n defines.TONEMAPPING = false;\n defines.CONTRAST = false;\n defines.EXPOSURE = false;\n defines.COLORCURVES = false;\n defines.COLORGRADING = false;\n defines.COLORGRADING3D = false;\n defines.IMAGEPROCESSING = false;\n defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;\n return;\n }\n defines.VIGNETTE = this.vignetteEnabled;\n defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);\n defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;\n defines.TONEMAPPING = this.toneMappingEnabled;\n defines.CONTRAST = (this.contrast !== 1.0);\n defines.EXPOSURE = (this.exposure !== 1.0);\n defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);\n defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);\n if (defines.COLORGRADING) {\n defines.COLORGRADING3D = this.colorGradingTexture.is3D;\n }\n else {\n defines.COLORGRADING3D = false;\n }\n defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;\n defines.SAMPLER3DBGRMAP = this.colorGradingBGR;\n defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;\n defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;\n };\n /**\n * Returns true if all the image processing information are ready.\n */\n ImageProcessingConfiguration.prototype.isReady = function () {\n // Color Grading texure can not be none blocking.\n return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();\n };\n /**\n * Binds the image processing to the shader.\n * @param effect The effect to bind to\n */\n ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {\n if (aspectRatio === void 0) { aspectRatio = 1; }\n // Color Curves\n if (this._colorCurvesEnabled && this.colorCurves) {\n BABYLON.ColorCurves.Bind(this.colorCurves, effect);\n }\n // Vignette\n if (this._vignetteEnabled) {\n var inverseWidth = 1 / effect.getEngine().getRenderWidth();\n var inverseHeight = 1 / effect.getEngine().getRenderHeight();\n effect.setFloat2(\"vInverseScreenSize\", inverseWidth, inverseHeight);\n var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);\n var vignetteScaleX = vignetteScaleY * aspectRatio;\n var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);\n vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);\n vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);\n effect.setFloat4(\"vignetteSettings1\", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);\n var vignettePower = -2.0 * this.vignetteWeight;\n effect.setFloat4(\"vignetteSettings2\", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);\n }\n // Exposure\n effect.setFloat(\"exposureLinear\", this.exposure);\n // Contrast\n effect.setFloat(\"contrast\", this.contrast);\n // Color transform settings\n if (this.colorGradingTexture) {\n effect.setTexture(\"txColorTransform\", this.colorGradingTexture);\n var textureSize = this.colorGradingTexture.getSize().height;\n effect.setFloat4(\"colorTransformSettings\", (textureSize - 1) / textureSize, // textureScale\n 0.5 / textureSize, // textureOffset\n textureSize, // textureSize\n this.colorGradingTexture.level // weight\n );\n }\n };\n /**\n * Clones the current image processing instance.\n * @return The cloned image processing\n */\n ImageProcessingConfiguration.prototype.clone = function () {\n return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);\n };\n /**\n * Serializes the current image processing instance to a json representation.\n * @return a JSON representation\n */\n ImageProcessingConfiguration.prototype.serialize = function () {\n return BABYLON.SerializationHelper.Serialize(this);\n };\n /**\n * Parses the image processing from a json representation.\n * @param source the JSON source to parse\n * @return The parsed image processing\n */\n ImageProcessingConfiguration.Parse = function (source) {\n return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);\n };\n Object.defineProperty(ImageProcessingConfiguration, \"VIGNETTEMODE_MULTIPLY\", {\n /**\n * Used to apply the vignette as a mix with the pixel color.\n */\n get: function () {\n return this._VIGNETTEMODE_MULTIPLY;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingConfiguration, \"VIGNETTEMODE_OPAQUE\", {\n /**\n * Used to apply the vignette as a replacement of the pixel color.\n */\n get: function () {\n return this._VIGNETTEMODE_OPAQUE;\n },\n enumerable: true,\n configurable: true\n });\n // Static constants associated to the image processing.\n ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;\n ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;\n __decorate([\n BABYLON.serializeAsColorCurves()\n ], ImageProcessingConfiguration.prototype, \"colorCurves\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_colorCurvesEnabled\", void 0);\n __decorate([\n BABYLON.serializeAsTexture()\n ], ImageProcessingConfiguration.prototype, \"colorGradingTexture\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_colorGradingEnabled\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_colorGradingWithGreenDepth\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_colorGradingBGR\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_exposure\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_toneMappingEnabled\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_contrast\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"vignetteStretch\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"vignetteCentreX\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"vignetteCentreY\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"vignetteWeight\", void 0);\n __decorate([\n BABYLON.serializeAsColor4()\n ], ImageProcessingConfiguration.prototype, \"vignetteColor\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"vignetteCameraFov\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_vignetteBlendMode\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_vignetteEnabled\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_applyByPostProcess\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingConfiguration.prototype, \"_isEnabled\", void 0);\n return ImageProcessingConfiguration;\n }());\n BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.imageProcessingConfiguration.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This represents a color grading texture. This acts as a lookup table LUT, useful during post process\n * It can help converting any input color in a desired output one. This can then be used to create effects\n * from sepia, black and white to sixties or futuristic rendering...\n *\n * The only supported format is currently 3dl.\n * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/\n */\n var ColorGradingTexture = /** @class */ (function (_super) {\n __extends(ColorGradingTexture, _super);\n /**\n * Instantiates a ColorGradingTexture from the following parameters.\n *\n * @param url The location of the color gradind data (currently only supporting 3dl)\n * @param scene The scene the texture will be used in\n */\n function ColorGradingTexture(url, scene) {\n var _this = _super.call(this, scene) || this;\n if (!url) {\n return _this;\n }\n _this._engine = scene.getEngine();\n _this._textureMatrix = BABYLON.Matrix.Identity();\n _this.name = url;\n _this.url = url;\n _this.hasAlpha = false;\n _this.isCube = false;\n _this.is3D = _this._engine.webGLVersion > 1;\n _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.anisotropicFilteringLevel = 1;\n _this._texture = _this._getFromCache(url, true);\n if (!_this._texture) {\n if (!scene.useDelayedTextureLoading) {\n _this.loadTexture();\n }\n else {\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n }\n }\n return _this;\n }\n /**\n * Returns the texture matrix used in most of the material.\n * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).\n */\n ColorGradingTexture.prototype.getTextureMatrix = function () {\n return this._textureMatrix;\n };\n /**\n * Occurs when the file being loaded is a .3dl LUT file.\n */\n ColorGradingTexture.prototype.load3dlTexture = function () {\n var engine = this._engine;\n var texture;\n if (engine.webGLVersion === 1) {\n texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n }\n else {\n texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n }\n this._texture = texture;\n var callback = function (text) {\n if (typeof text !== \"string\") {\n return;\n }\n var data = null;\n var tempData = null;\n var line;\n var lines = text.split('\\n');\n var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;\n var maxColor = 0;\n for (var i = 0; i < lines.length; i++) {\n line = lines[i];\n if (!ColorGradingTexture._noneEmptyLineRegex.test(line))\n continue;\n if (line.indexOf('#') === 0)\n continue;\n var words = line.split(\" \");\n if (size === 0) {\n // Number of space + one\n size = words.length;\n data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8\n tempData = new Float32Array(size * size * size * 4);\n continue;\n }\n if (size != 0) {\n var r = Math.max(parseInt(words[0]), 0);\n var g = Math.max(parseInt(words[1]), 0);\n var b = Math.max(parseInt(words[2]), 0);\n maxColor = Math.max(r, maxColor);\n maxColor = Math.max(g, maxColor);\n maxColor = Math.max(b, maxColor);\n var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;\n if (tempData) {\n tempData[pixelStorageIndex + 0] = r;\n tempData[pixelStorageIndex + 1] = g;\n tempData[pixelStorageIndex + 2] = b;\n }\n pixelIndexSlice++;\n if (pixelIndexSlice % size == 0) {\n pixelIndexH++;\n pixelIndexSlice = 0;\n if (pixelIndexH % size == 0) {\n pixelIndexW++;\n pixelIndexH = 0;\n }\n }\n }\n }\n if (tempData && data) {\n for (var i = 0; i < tempData.length; i++) {\n if (i > 0 && (i + 1) % 4 === 0) {\n data[i] = 255;\n }\n else {\n var value = tempData[i];\n data[i] = (value / maxColor * 255);\n }\n }\n }\n if (texture.is3D) {\n texture.updateSize(size, size, size);\n engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);\n }\n else {\n texture.updateSize(size * size, size);\n engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);\n }\n };\n var scene = this.getScene();\n if (scene) {\n scene._loadFile(this.url, callback);\n }\n else {\n this._engine._loadFile(this.url, callback);\n }\n return this._texture;\n };\n /**\n * Starts the loading process of the texture.\n */\n ColorGradingTexture.prototype.loadTexture = function () {\n if (this.url && this.url.toLocaleLowerCase().indexOf(\".3dl\") == (this.url.length - 4)) {\n this.load3dlTexture();\n }\n };\n /**\n * Clones the color gradind texture.\n */\n ColorGradingTexture.prototype.clone = function () {\n var newTexture = new ColorGradingTexture(this.url, this.getScene());\n // Base texture\n newTexture.level = this.level;\n return newTexture;\n };\n /**\n * Called during delayed load for textures.\n */\n ColorGradingTexture.prototype.delayLoad = function () {\n if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {\n return;\n }\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;\n this._texture = this._getFromCache(this.url, true);\n if (!this._texture) {\n this.loadTexture();\n }\n };\n /**\n * Parses a color grading texture serialized by Babylon.\n * @param parsedTexture The texture information being parsedTexture\n * @param scene The scene to load the texture in\n * @param rootUrl The root url of the data assets to load\n * @return A color gradind texture\n */\n ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {\n var texture = null;\n if (parsedTexture.name && !parsedTexture.isRenderTarget) {\n texture = new ColorGradingTexture(parsedTexture.name, scene);\n texture.name = parsedTexture.name;\n texture.level = parsedTexture.level;\n }\n return texture;\n };\n /**\n * Serializes the LUT texture to json format.\n */\n ColorGradingTexture.prototype.serialize = function () {\n if (!this.name) {\n return null;\n }\n var serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.level = this.level;\n serializationObject.customType = \"BABYLON.ColorGradingTexture\";\n return serializationObject;\n };\n /**\n * Empty line regex stored for GC.\n */\n ColorGradingTexture._noneEmptyLineRegex = /\\S+/;\n return ColorGradingTexture;\n }(BABYLON.BaseTexture));\n BABYLON.ColorGradingTexture = ColorGradingTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.colorGradingTexture.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n var ColorCurves = /** @class */ (function () {\n function ColorCurves() {\n this._dirty = true;\n this._tempColor = new BABYLON.Color4(0, 0, 0, 0);\n this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);\n this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);\n this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);\n this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);\n this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);\n this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);\n this._globalHue = 30;\n this._globalDensity = 0;\n this._globalSaturation = 0;\n this._globalExposure = 0;\n this._highlightsHue = 30;\n this._highlightsDensity = 0;\n this._highlightsSaturation = 0;\n this._highlightsExposure = 0;\n this._midtonesHue = 30;\n this._midtonesDensity = 0;\n this._midtonesSaturation = 0;\n this._midtonesExposure = 0;\n this._shadowsHue = 30;\n this._shadowsDensity = 0;\n this._shadowsSaturation = 0;\n this._shadowsExposure = 0;\n }\n Object.defineProperty(ColorCurves.prototype, \"globalHue\", {\n /**\n * Gets the global Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get: function () {\n return this._globalHue;\n },\n /**\n * Sets the global Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set: function (value) {\n this._globalHue = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"globalDensity\", {\n /**\n * Gets the global Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get: function () {\n return this._globalDensity;\n },\n /**\n * Sets the global Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set: function (value) {\n this._globalDensity = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"globalSaturation\", {\n /**\n * Gets the global Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get: function () {\n return this._globalSaturation;\n },\n /**\n * Sets the global Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set: function (value) {\n this._globalSaturation = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"globalExposure\", {\n /**\n * Gets the global Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get: function () {\n return this._globalExposure;\n },\n /**\n * Sets the global Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set: function (value) {\n this._globalExposure = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"highlightsHue\", {\n /**\n * Gets the highlights Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get: function () {\n return this._highlightsHue;\n },\n /**\n * Sets the highlights Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set: function (value) {\n this._highlightsHue = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"highlightsDensity\", {\n /**\n * Gets the highlights Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get: function () {\n return this._highlightsDensity;\n },\n /**\n * Sets the highlights Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set: function (value) {\n this._highlightsDensity = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"highlightsSaturation\", {\n /**\n * Gets the highlights Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get: function () {\n return this._highlightsSaturation;\n },\n /**\n * Sets the highlights Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set: function (value) {\n this._highlightsSaturation = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"highlightsExposure\", {\n /**\n * Gets the highlights Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get: function () {\n return this._highlightsExposure;\n },\n /**\n * Sets the highlights Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set: function (value) {\n this._highlightsExposure = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"midtonesHue\", {\n /**\n * Gets the midtones Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get: function () {\n return this._midtonesHue;\n },\n /**\n * Sets the midtones Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set: function (value) {\n this._midtonesHue = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"midtonesDensity\", {\n /**\n * Gets the midtones Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get: function () {\n return this._midtonesDensity;\n },\n /**\n * Sets the midtones Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set: function (value) {\n this._midtonesDensity = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"midtonesSaturation\", {\n /**\n * Gets the midtones Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get: function () {\n return this._midtonesSaturation;\n },\n /**\n * Sets the midtones Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set: function (value) {\n this._midtonesSaturation = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"midtonesExposure\", {\n /**\n * Gets the midtones Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get: function () {\n return this._midtonesExposure;\n },\n /**\n * Sets the midtones Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set: function (value) {\n this._midtonesExposure = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"shadowsHue\", {\n /**\n * Gets the shadows Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get: function () {\n return this._shadowsHue;\n },\n /**\n * Sets the shadows Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set: function (value) {\n this._shadowsHue = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"shadowsDensity\", {\n /**\n * Gets the shadows Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get: function () {\n return this._shadowsDensity;\n },\n /**\n * Sets the shadows Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set: function (value) {\n this._shadowsDensity = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"shadowsSaturation\", {\n /**\n * Gets the shadows Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get: function () {\n return this._shadowsSaturation;\n },\n /**\n * Sets the shadows Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set: function (value) {\n this._shadowsSaturation = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ColorCurves.prototype, \"shadowsExposure\", {\n /**\n * Gets the shadows Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get: function () {\n return this._shadowsExposure;\n },\n /**\n * Sets the shadows Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set: function (value) {\n this._shadowsExposure = value;\n this._dirty = true;\n },\n enumerable: true,\n configurable: true\n });\n ColorCurves.prototype.getClassName = function () {\n return \"ColorCurves\";\n };\n /**\n * Binds the color curves to the shader.\n * @param colorCurves The color curve to bind\n * @param effect The effect to bind to\n */\n ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {\n if (positiveUniform === void 0) { positiveUniform = \"vCameraColorCurvePositive\"; }\n if (neutralUniform === void 0) { neutralUniform = \"vCameraColorCurveNeutral\"; }\n if (negativeUniform === void 0) { negativeUniform = \"vCameraColorCurveNegative\"; }\n if (colorCurves._dirty) {\n colorCurves._dirty = false;\n // Fill in global info.\n colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);\n // Compute highlights info.\n colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);\n colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);\n // Compute midtones info.\n colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);\n colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);\n // Compute shadows info.\n colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);\n colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);\n // Compute deltas (neutral is midtones).\n colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);\n colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);\n }\n if (effect) {\n effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);\n effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);\n effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);\n }\n };\n /**\n * Prepare the list of uniforms associated with the ColorCurves effects.\n * @param uniformsList The list of uniforms used in the effect\n */\n ColorCurves.PrepareUniforms = function (uniformsList) {\n uniformsList.push(\"vCameraColorCurveNeutral\", \"vCameraColorCurvePositive\", \"vCameraColorCurveNegative\");\n };\n /**\n * Returns color grading data based on a hue, density, saturation and exposure value.\n * @param filterHue The hue of the color filter.\n * @param filterDensity The density of the color filter.\n * @param saturation The saturation.\n * @param exposure The exposure.\n * @param result The result data container.\n */\n ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {\n if (hue == null) {\n return;\n }\n hue = ColorCurves.clamp(hue, 0, 360);\n density = ColorCurves.clamp(density, -100, 100);\n saturation = ColorCurves.clamp(saturation, -100, 100);\n exposure = ColorCurves.clamp(exposure, -100, 100);\n // Remap the slider/config filter density with non-linear mapping and also scale by half\n // so that the maximum filter density is only 50% control. This provides fine control \n // for small values and reasonable range.\n density = ColorCurves.applyColorGradingSliderNonlinear(density);\n density *= 0.5;\n exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);\n if (density < 0) {\n density *= -1;\n hue = (hue + 180) % 360;\n }\n ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);\n result.scaleToRef(2, result);\n result.a = 1 + 0.01 * saturation;\n };\n /**\n * Takes an input slider value and returns an adjusted value that provides extra control near the centre.\n * @param value The input slider value in range [-100,100].\n * @returns Adjusted value.\n */\n ColorCurves.applyColorGradingSliderNonlinear = function (value) {\n value /= 100;\n var x = Math.abs(value);\n x = Math.pow(x, 2);\n if (value < 0) {\n x *= -1;\n }\n x *= 100;\n return x;\n };\n /**\n * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).\n * @param hue The hue (H) input.\n * @param saturation The saturation (S) input.\n * @param brightness The brightness (B) input.\n * @result An RGBA color represented as Vector4.\n */\n ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {\n var h = ColorCurves.clamp(hue, 0, 360);\n var s = ColorCurves.clamp(saturation / 100, 0, 1);\n var v = ColorCurves.clamp(brightness / 100, 0, 1);\n if (s === 0) {\n result.r = v;\n result.g = v;\n result.b = v;\n }\n else {\n // sector 0 to 5\n h /= 60;\n var i = Math.floor(h);\n // fractional part of h\n var f = h - i;\n var p = v * (1 - s);\n var q = v * (1 - s * f);\n var t = v * (1 - s * (1 - f));\n switch (i) {\n case 0:\n result.r = v;\n result.g = t;\n result.b = p;\n break;\n case 1:\n result.r = q;\n result.g = v;\n result.b = p;\n break;\n case 2:\n result.r = p;\n result.g = v;\n result.b = t;\n break;\n case 3:\n result.r = p;\n result.g = q;\n result.b = v;\n break;\n case 4:\n result.r = t;\n result.g = p;\n result.b = v;\n break;\n default: // case 5:\n result.r = v;\n result.g = p;\n result.b = q;\n break;\n }\n }\n result.a = 1;\n };\n /**\n * Returns a value clamped between min and max\n * @param value The value to clamp\n * @param min The minimum of value\n * @param max The maximum of value\n * @returns The clamped value.\n */\n ColorCurves.clamp = function (value, min, max) {\n return Math.min(Math.max(value, min), max);\n };\n /**\n * Clones the current color curve instance.\n * @return The cloned curves\n */\n ColorCurves.prototype.clone = function () {\n return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);\n };\n /**\n * Serializes the current color curve instance to a json representation.\n * @return a JSON representation\n */\n ColorCurves.prototype.serialize = function () {\n return BABYLON.SerializationHelper.Serialize(this);\n };\n /**\n * Parses the color curve from a json representation.\n * @param source the JSON source to parse\n * @return The parsed curves\n */\n ColorCurves.Parse = function (source) {\n return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);\n };\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_globalHue\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_globalDensity\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_globalSaturation\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_globalExposure\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_highlightsHue\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_highlightsDensity\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_highlightsSaturation\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_highlightsExposure\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_midtonesHue\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_midtonesDensity\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_midtonesSaturation\", void 0);\n __decorate([\n BABYLON.serialize()\n ], ColorCurves.prototype, \"_midtonesExposure\", void 0);\n return ColorCurves;\n }());\n BABYLON.ColorCurves = ColorCurves;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.colorCurves.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var RefractionPostProcess = /** @class */ (function (_super) {\n __extends(RefractionPostProcess, _super);\n function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {\n var _this = _super.call(this, name, \"refraction\", [\"baseColor\", \"depth\", \"colorLevel\"], [\"refractionSampler\"], options, camera, samplingMode, engine, reusable) || this;\n _this.color = color;\n _this.depth = depth;\n _this.colorLevel = colorLevel;\n _this._ownRefractionTexture = true;\n _this.onActivateObservable.add(function (cam) {\n _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());\n });\n _this.onApplyObservable.add(function (effect) {\n effect.setColor3(\"baseColor\", _this.color);\n effect.setFloat(\"depth\", _this.depth);\n effect.setFloat(\"colorLevel\", _this.colorLevel);\n effect.setTexture(\"refractionSampler\", _this._refTexture);\n });\n return _this;\n }\n Object.defineProperty(RefractionPostProcess.prototype, \"refractionTexture\", {\n /**\n * Gets or sets the refraction texture\n * Please note that you are responsible for disposing the texture if you set it manually\n */\n get: function () {\n return this._refTexture;\n },\n set: function (value) {\n if (this._refTexture && this._ownRefractionTexture) {\n this._refTexture.dispose();\n }\n this._refTexture = value;\n this._ownRefractionTexture = false;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n RefractionPostProcess.prototype.dispose = function (camera) {\n if (this._refTexture && this._ownRefractionTexture) {\n this._refTexture.dispose();\n this._refTexture = null;\n }\n _super.prototype.dispose.call(this, camera);\n };\n return RefractionPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.RefractionPostProcess = RefractionPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.refractionPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var BlackAndWhitePostProcess = /** @class */ (function (_super) {\n __extends(BlackAndWhitePostProcess, _super);\n function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {\n var _this = _super.call(this, name, \"blackAndWhite\", [\"degree\"], null, options, camera, samplingMode, engine, reusable) || this;\n _this.degree = 1;\n _this.onApplyObservable.add(function (effect) {\n effect.setFloat(\"degree\", _this.degree);\n });\n return _this;\n }\n return BlackAndWhitePostProcess;\n }(BABYLON.PostProcess));\n BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the\n * input texture to perform effects such as edge detection or sharpening\n * See http://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n var ConvolutionPostProcess = /** @class */ (function (_super) {\n __extends(ConvolutionPostProcess, _super);\n /**\n * Creates a new instance ConvolutionPostProcess\n * @param name The name of the effect.\n * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n */\n function ConvolutionPostProcess(name, \n /** Array of 9 values corrisponding to the 3x3 kernel to be applied */\n kernel, options, camera, samplingMode, engine, reusable, textureType) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n var _this = _super.call(this, name, \"convolution\", [\"kernel\", \"screenSize\"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;\n _this.kernel = kernel;\n _this.onApply = function (effect) {\n effect.setFloat2(\"screenSize\", _this.width, _this.height);\n effect.setArray(\"kernel\", _this.kernel);\n };\n return _this;\n }\n // Statics\n /**\n * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];\n /**\n * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];\n /**\n * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];\n /**\n * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];\n /**\n * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];\n /**\n * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)\n */\n ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];\n return ConvolutionPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.convolutionPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var FilterPostProcess = /** @class */ (function (_super) {\n __extends(FilterPostProcess, _super);\n function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {\n var _this = _super.call(this, name, \"filter\", [\"kernelMatrix\"], null, options, camera, samplingMode, engine, reusable) || this;\n _this.kernelMatrix = kernelMatrix;\n _this.onApply = function (effect) {\n effect.setMatrix(\"kernelMatrix\", _this.kernelMatrix);\n };\n return _this;\n }\n return FilterPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.FilterPostProcess = FilterPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.filterPostProcess.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html\n var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {\n __extends(VolumetricLightScatteringPostProcess, _super);\n /**\n * @constructor\n * @param {string} name - The post-process name\n * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)\n * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to\n * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering\n * @param {number} samples - The post-process quality, default 100\n * @param {number} samplingMode - The post-process filtering mode\n * @param {BABYLON.Engine} engine - The babylon engine\n * @param {boolean} reusable - If the post-process is reusable\n * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If \"camera\" is null (RenderPipelineà, \"scene\" must be provided\n */\n function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {\n if (samples === void 0) { samples = 100; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }\n var _this = _super.call(this, name, \"volumetricLightScattering\", [\"decay\", \"exposure\", \"weight\", \"meshPositionOnScreen\", \"density\"], [\"lightScatteringSampler\"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, \"#define NUM_SAMPLES \" + samples) || this;\n _this._screenCoordinates = BABYLON.Vector2.Zero();\n /**\n * Custom position of the mesh. Used if \"useCustomMeshPosition\" is set to \"true\"\n */\n _this.customMeshPosition = BABYLON.Vector3.Zero();\n /**\n * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)\n */\n _this.useCustomMeshPosition = false;\n /**\n * If the post-process should inverse the light scattering direction\n */\n _this.invert = true;\n /**\n * Array containing the excluded meshes not rendered in the internal pass\n */\n _this.excludedMeshes = new Array();\n /**\n * Controls the overall intensity of the post-process\n */\n _this.exposure = 0.3;\n /**\n * Dissipates each sample's contribution in range [0, 1]\n */\n _this.decay = 0.96815;\n /**\n * Controls the overall intensity of each sample\n */\n _this.weight = 0.58767;\n /**\n * Controls the density of each sample\n */\n _this.density = 0.926;\n scene = ((camera === null) ? scene : camera.getScene()); // parameter \"scene\" can be null.\n engine = scene.getEngine();\n _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n // Configure mesh\n _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh(\"VolumetricLightScatteringMesh\", scene));\n // Configure\n _this._createPass(scene, ratio.passRatio || ratio);\n _this.onActivate = function (camera) {\n if (!_this.isSupported) {\n _this.dispose(camera);\n }\n _this.onActivate = null;\n };\n _this.onApplyObservable.add(function (effect) {\n _this._updateMeshScreenCoordinates(scene);\n effect.setTexture(\"lightScatteringSampler\", _this._volumetricLightScatteringRTT);\n effect.setFloat(\"exposure\", _this.exposure);\n effect.setFloat(\"decay\", _this.decay);\n effect.setFloat(\"weight\", _this.weight);\n effect.setFloat(\"density\", _this.density);\n effect.setVector2(\"meshPositionOnScreen\", _this._screenCoordinates);\n });\n return _this;\n }\n Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, \"useDiffuseColor\", {\n get: function () {\n BABYLON.Tools.Warn(\"VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead\");\n return false;\n },\n set: function (useDiffuseColor) {\n BABYLON.Tools.Warn(\"VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead\");\n },\n enumerable: true,\n configurable: true\n });\n VolumetricLightScatteringPostProcess.prototype.getClassName = function () {\n return \"VolumetricLightScatteringPostProcess\";\n };\n VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {\n var mesh = subMesh.getMesh();\n // Render this.mesh as default\n if (mesh === this.mesh && mesh.material) {\n return mesh.material.isReady(mesh);\n }\n var defines = [];\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n var material = subMesh.getMaterial();\n // Alpha test\n if (material) {\n if (material.needAlphaTesting()) {\n defines.push(\"#define ALPHATEST\");\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n // Get correct effect \n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: \"depth\", fragmentElement: \"volumetricLightScatteringPass\" }, attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\"], [\"diffuseSampler\"], join);\n }\n return this._volumetricLightScatteringPass.isReady();\n };\n /**\n * Sets the new light position for light scattering effect\n * @param {BABYLON.Vector3} The new custom light position\n */\n VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {\n this.customMeshPosition = position;\n };\n /**\n * Returns the light position for light scattering effect\n * @return {BABYLON.Vector3} The custom light position\n */\n VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {\n return this.customMeshPosition;\n };\n /**\n * Disposes the internal assets and detaches the post-process from the camera\n */\n VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {\n var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);\n if (rttIndex !== -1) {\n camera.getScene().customRenderTargets.splice(rttIndex, 1);\n }\n this._volumetricLightScatteringRTT.dispose();\n _super.prototype.dispose.call(this, camera);\n };\n /**\n * Returns the render target texture used by the post-process\n * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process\n */\n VolumetricLightScatteringPostProcess.prototype.getPass = function () {\n return this._volumetricLightScatteringRTT;\n };\n // Private methods\n VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {\n if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {\n return true;\n }\n return false;\n };\n VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {\n var _this = this;\n var engine = scene.getEngine();\n this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture(\"volumetricLightScatteringMap\", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._volumetricLightScatteringRTT.renderList = null;\n this._volumetricLightScatteringRTT.renderParticles = false;\n this._volumetricLightScatteringRTT.ignoreCameraViewport = true;\n var camera = this.getCamera();\n if (camera) {\n camera.customRenderTargets.push(this._volumetricLightScatteringRTT);\n }\n else {\n scene.customRenderTargets.push(this._volumetricLightScatteringRTT);\n }\n // Custom render function for submeshes\n var renderSubMesh = function (subMesh) {\n var mesh = subMesh.getRenderingMesh();\n if (_this._meshExcluded(mesh)) {\n return;\n }\n var material = subMesh.getMaterial();\n if (!material) {\n return;\n }\n var scene = mesh.getScene();\n var engine = scene.getEngine();\n // Culling\n engine.setState(material.backFaceCulling);\n // Managing instances\n var batch = mesh._getInstancesRenderList(subMesh._id);\n if (batch.mustReturn) {\n return;\n }\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);\n if (_this._isReady(subMesh, hardwareInstancedRendering)) {\n var effect = _this._volumetricLightScatteringPass;\n if (mesh === _this.mesh) {\n if (subMesh.effect) {\n effect = subMesh.effect;\n }\n else {\n effect = material.getEffect();\n }\n }\n engine.enableEffect(effect);\n mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);\n if (mesh === _this.mesh) {\n material.bind(mesh.getWorldMatrix(), mesh);\n }\n else {\n _this._volumetricLightScatteringPass.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n _this._volumetricLightScatteringPass.setTexture(\"diffuseSampler\", alphaTexture);\n if (alphaTexture) {\n _this._volumetricLightScatteringPass.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n _this._volumetricLightScatteringPass.setMatrices(\"mBones\", mesh.skeleton.getTransformMatrices(mesh));\n }\n }\n // Draw\n mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix(\"world\", world); });\n }\n };\n // Render target texture callbacks\n var savedSceneClearColor;\n var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);\n this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {\n savedSceneClearColor = scene.clearColor;\n scene.clearColor = sceneClearColor;\n });\n this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {\n scene.clearColor = savedSceneClearColor;\n });\n this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {\n var engine = scene.getEngine();\n var index;\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n if (transparentSubMeshes.length) {\n // Sort sub meshes\n for (index = 0; index < transparentSubMeshes.length; index++) {\n var submesh = transparentSubMeshes.data[index];\n var boundingInfo = submesh.getBoundingInfo();\n if (boundingInfo && scene.activeCamera) {\n submesh._alphaIndex = submesh.getMesh().alphaIndex;\n submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();\n }\n }\n var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);\n sortedArray.sort(function (a, b) {\n // Alpha index first\n if (a._alphaIndex > b._alphaIndex) {\n return 1;\n }\n if (a._alphaIndex < b._alphaIndex) {\n return -1;\n }\n // Then distance to camera\n if (a._distanceToCamera < b._distanceToCamera) {\n return 1;\n }\n if (a._distanceToCamera > b._distanceToCamera) {\n return -1;\n }\n return 0;\n });\n // Render sub meshes\n engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);\n for (index = 0; index < sortedArray.length; index++) {\n renderSubMesh(sortedArray[index]);\n }\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n }\n };\n };\n VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {\n var transform = scene.getTransformMatrix();\n var meshPosition;\n if (this.useCustomMeshPosition) {\n meshPosition = this.customMeshPosition;\n }\n else if (this.attachedNode) {\n meshPosition = this.attachedNode.position;\n }\n else {\n meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;\n }\n var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);\n this._screenCoordinates.x = pos.x / this._viewPort.width;\n this._screenCoordinates.y = pos.y / this._viewPort.height;\n if (this.invert)\n this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;\n };\n // Static methods\n /**\n * Creates a default mesh for the Volumeric Light Scattering post-process\n * @param {string} The mesh name\n * @param {BABYLON.Scene} The scene where to create the mesh\n * @return {BABYLON.Mesh} the default mesh\n */\n VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {\n var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);\n mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;\n var material = new BABYLON.StandardMaterial(name + \"Material\", scene);\n material.emissiveColor = new BABYLON.Color3(1, 1, 1);\n mesh.material = material;\n return mesh;\n };\n __decorate([\n BABYLON.serializeAsVector3()\n ], VolumetricLightScatteringPostProcess.prototype, \"customMeshPosition\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"useCustomMeshPosition\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"invert\", void 0);\n __decorate([\n BABYLON.serializeAsMeshReference()\n ], VolumetricLightScatteringPostProcess.prototype, \"mesh\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"excludedMeshes\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"exposure\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"decay\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"weight\", void 0);\n __decorate([\n BABYLON.serialize()\n ], VolumetricLightScatteringPostProcess.prototype, \"density\", void 0);\n return VolumetricLightScatteringPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map\n\n//\n// This post-process allows the modification of rendered colors by using\n// a 'look-up table' (LUT). This effect is also called Color Grading.\n// \n// The object needs to be provided an url to a texture containing the color\n// look-up table: the texture must be 256 pixels wide and 16 pixels high.\n// Use an image editing software to tweak the LUT to match your needs.\n// \n// For an example of a color LUT, see here:\n// http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png\n// For explanations on color grading, see here:\n// http://udn.epicgames.com/Three/ColorGrading.html\n//\n\nvar BABYLON;\n(function (BABYLON) {\n var ColorCorrectionPostProcess = /** @class */ (function (_super) {\n __extends(ColorCorrectionPostProcess, _super);\n function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {\n var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;\n _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);\n _this._colorTableTexture.anisotropicFilteringLevel = 1;\n _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n _this.onApply = function (effect) {\n effect.setTexture(\"colorTable\", _this._colorTableTexture);\n };\n return _this;\n }\n return ColorCorrectionPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /** Defines operator used for tonemapping */\n var TonemappingOperator;\n (function (TonemappingOperator) {\n /** Hable */\n TonemappingOperator[TonemappingOperator[\"Hable\"] = 0] = \"Hable\";\n /** Reinhard */\n TonemappingOperator[TonemappingOperator[\"Reinhard\"] = 1] = \"Reinhard\";\n /** HejiDawson */\n TonemappingOperator[TonemappingOperator[\"HejiDawson\"] = 2] = \"HejiDawson\";\n /** Photographic */\n TonemappingOperator[TonemappingOperator[\"Photographic\"] = 3] = \"Photographic\";\n })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));\n ;\n /**\n * Defines a post process to apply tone mapping\n */\n var TonemapPostProcess = /** @class */ (function (_super) {\n __extends(TonemapPostProcess, _super);\n /**\n * Creates a new TonemapPostProcess\n * @param name defines the name of the postprocess\n * @param _operator defines the operator to use\n * @param exposureAdjustment defines the required exposure adjustement\n * @param camera defines the camera to use (can be null)\n * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)\n * @param engine defines the hosting engine (can be ignore if camera is set)\n * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)\n */\n function TonemapPostProcess(name, _operator, \n /** Defines the required exposure adjustement */\n exposureAdjustment, camera, samplingMode, engine, textureFormat) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }\n if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n var _this = _super.call(this, name, \"tonemap\", [\"_ExposureAdjustment\"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;\n _this._operator = _operator;\n _this.exposureAdjustment = exposureAdjustment;\n var defines = \"#define \";\n if (_this._operator === TonemappingOperator.Hable)\n defines += \"HABLE_TONEMAPPING\";\n else if (_this._operator === TonemappingOperator.Reinhard)\n defines += \"REINHARD_TONEMAPPING\";\n else if (_this._operator === TonemappingOperator.HejiDawson)\n defines += \"OPTIMIZED_HEJIDAWSON_TONEMAPPING\";\n else if (_this._operator === TonemappingOperator.Photographic)\n defines += \"PHOTOGRAPHIC_TONEMAPPING\";\n //sadly a second call to create the effect.\n _this.updateEffect(defines);\n _this.onApply = function (effect) {\n effect.setFloat(\"_ExposureAdjustment\", _this.exposureAdjustment);\n };\n return _this;\n }\n return TonemapPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.TonemapPostProcess = TonemapPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.tonemapPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var DisplayPassPostProcess = /** @class */ (function (_super) {\n __extends(DisplayPassPostProcess, _super);\n function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {\n return _super.call(this, name, \"displayPass\", [\"passSampler\"], [\"passSampler\"], options, camera, samplingMode, engine, reusable) || this;\n }\n return DisplayPassPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.displayPassPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var HighlightsPostProcess = /** @class */ (function (_super) {\n __extends(HighlightsPostProcess, _super);\n function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n return _super.call(this, name, \"highlights\", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;\n }\n return HighlightsPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.HighlightsPostProcess = HighlightsPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.highlightsPostProcess.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var ImageProcessingPostProcess = /** @class */ (function (_super) {\n __extends(ImageProcessingPostProcess, _super);\n function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {\n if (camera === void 0) { camera = null; }\n if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }\n var _this = _super.call(this, name, \"imageProcessing\", [], [], options, camera, samplingMode, engine, reusable, null, textureType, \"postprocess\", null, true) || this;\n _this._fromLinearSpace = true;\n /**\n * Defines cache preventing GC.\n */\n _this._defines = {\n IMAGEPROCESSING: false,\n VIGNETTE: false,\n VIGNETTEBLENDMODEMULTIPLY: false,\n VIGNETTEBLENDMODEOPAQUE: false,\n TONEMAPPING: false,\n CONTRAST: false,\n COLORCURVES: false,\n COLORGRADING: false,\n COLORGRADING3D: false,\n FROMLINEARSPACE: false,\n SAMPLER3DGREENDEPTH: false,\n SAMPLER3DBGRMAP: false,\n IMAGEPROCESSINGPOSTPROCESS: false,\n EXPOSURE: false,\n };\n // Setup the configuration as forced by the constructor. This would then not force the \n // scene materials output in linear space and let untouched the default forward pass.\n if (imageProcessingConfiguration) {\n imageProcessingConfiguration.applyByPostProcess = true;\n _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);\n // This will cause the shader to be compiled\n _this.fromLinearSpace = false;\n }\n // Setup the default processing configuration to the scene.\n else {\n _this._attachImageProcessingConfiguration(null, true);\n _this.imageProcessingConfiguration.applyByPostProcess = true;\n }\n _this.onApply = function (effect) {\n _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);\n };\n return _this;\n }\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"imageProcessingConfiguration\", {\n /**\n * Gets the image processing configuration used either in this material.\n */\n get: function () {\n return this._imageProcessingConfiguration;\n },\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set: function (value) {\n this._attachImageProcessingConfiguration(value);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Attaches a new image processing configuration to the PBR Material.\n * @param configuration\n */\n ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {\n var _this = this;\n if (doNotBuild === void 0) { doNotBuild = false; }\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n var scene = null;\n var engine = this.getEngine();\n var camera = this.getCamera();\n if (camera) {\n scene = camera.getScene();\n }\n else if (engine && engine.scenes) {\n var scenes = engine.scenes;\n scene = scenes[scenes.length - 1];\n }\n else {\n scene = BABYLON.Engine.LastCreatedScene;\n }\n this._imageProcessingConfiguration = scene.imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {\n _this._updateParameters();\n });\n }\n // Ensure the effect will be rebuilt.\n if (!doNotBuild) {\n this._updateParameters();\n }\n };\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"colorCurves\", {\n /**\n * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .\n */\n get: function () {\n return this.imageProcessingConfiguration.colorCurves;\n },\n /**\n * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorCurves = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"colorCurvesEnabled\", {\n /**\n * Gets wether the color curves effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n },\n /**\n * Sets wether the color curves effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"colorGradingTexture\", {\n /**\n * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorGradingTexture;\n },\n /**\n * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorGradingTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"colorGradingEnabled\", {\n /**\n * Gets wether the color grading effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n },\n /**\n * Gets wether the color grading effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"exposure\", {\n /**\n * Gets exposure used in the effect.\n */\n get: function () {\n return this.imageProcessingConfiguration.exposure;\n },\n /**\n * Sets exposure used in the effect.\n */\n set: function (value) {\n this.imageProcessingConfiguration.exposure = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"toneMappingEnabled\", {\n /**\n * Gets wether tonemapping is enabled or not.\n */\n get: function () {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n },\n /**\n * Sets wether tonemapping is enabled or not\n */\n set: function (value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"contrast\", {\n /**\n * Gets contrast used in the effect.\n */\n get: function () {\n return this.imageProcessingConfiguration.contrast;\n },\n /**\n * Sets contrast used in the effect.\n */\n set: function (value) {\n this.imageProcessingConfiguration.contrast = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteStretch\", {\n /**\n * Gets Vignette stretch size.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteStretch;\n },\n /**\n * Sets Vignette stretch size.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteStretch = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteCentreX\", {\n /**\n * Gets Vignette centre X Offset.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteCentreX;\n },\n /**\n * Sets Vignette centre X Offset.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteCentreX = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteCentreY\", {\n /**\n * Gets Vignette centre Y Offset.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteCentreY;\n },\n /**\n * Sets Vignette centre Y Offset.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteCentreY = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteWeight\", {\n /**\n * Gets Vignette weight or intensity of the vignette effect.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteWeight;\n },\n /**\n * Sets Vignette weight or intensity of the vignette effect.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteWeight = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteColor\", {\n /**\n * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)\n * if vignetteEnabled is set to true.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteColor;\n },\n /**\n * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)\n * if vignetteEnabled is set to true.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteColor = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteCameraFov\", {\n /**\n * Gets Camera field of view used by the Vignette effect.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteCameraFov;\n },\n /**\n * Sets Camera field of view used by the Vignette effect.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteCameraFov = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteBlendMode\", {\n /**\n * Gets the vignette blend mode allowing different kind of effect.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteBlendMode;\n },\n /**\n * Sets the vignette blend mode allowing different kind of effect.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteBlendMode = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"vignetteEnabled\", {\n /**\n * Gets wether the vignette effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.vignetteEnabled;\n },\n /**\n * Sets wether the vignette effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.vignetteEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageProcessingPostProcess.prototype, \"fromLinearSpace\", {\n /**\n * Gets wether the input of the processing is in Gamma or Linear Space.\n */\n get: function () {\n return this._fromLinearSpace;\n },\n /**\n * Sets wether the input of the processing is in Gamma or Linear Space.\n */\n set: function (value) {\n if (this._fromLinearSpace === value) {\n return;\n }\n this._fromLinearSpace = value;\n this._updateParameters();\n },\n enumerable: true,\n configurable: true\n });\n ImageProcessingPostProcess.prototype.getClassName = function () {\n return \"ImageProcessingPostProcess\";\n };\n ImageProcessingPostProcess.prototype._updateParameters = function () {\n this._defines.FROMLINEARSPACE = this._fromLinearSpace;\n this.imageProcessingConfiguration.prepareDefines(this._defines, true);\n var defines = \"\";\n for (var define in this._defines) {\n if (this._defines[define]) {\n defines += \"#define \" + define + \";\\r\\n\";\n }\n }\n var samplers = [\"textureSampler\"];\n var uniforms = [\"scale\"];\n if (BABYLON.ImageProcessingConfiguration) {\n BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);\n BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);\n }\n this.updateEffect(defines, uniforms, samplers);\n };\n ImageProcessingPostProcess.prototype.dispose = function (camera) {\n _super.prototype.dispose.call(this, camera);\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n if (this._imageProcessingConfiguration) {\n this.imageProcessingConfiguration.applyByPostProcess = false;\n }\n };\n __decorate([\n BABYLON.serialize()\n ], ImageProcessingPostProcess.prototype, \"_fromLinearSpace\", void 0);\n return ImageProcessingPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.imageProcessingPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to store bone information\n * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons\n */\n var Bone = /** @class */ (function (_super) {\n __extends(Bone, _super);\n /**\n * Create a new bone\n * @param name defines the bone name\n * @param skeleton defines the parent skeleton\n * @param parentBone defines the parent (can be null if the bone is the root)\n * @param localMatrix defines the local matrix\n * @param restPose defines the rest pose matrix\n * @param baseMatrix defines the base matrix\n * @param index defines index of the bone in the hiearchy\n */\n function Bone(\n /**\n * defines the bone name\n */\n name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {\n if (parentBone === void 0) { parentBone = null; }\n if (localMatrix === void 0) { localMatrix = null; }\n if (restPose === void 0) { restPose = null; }\n if (baseMatrix === void 0) { baseMatrix = null; }\n if (index === void 0) { index = null; }\n var _this = _super.call(this, name, skeleton.getScene()) || this;\n _this.name = name;\n /**\n * Gets the list of child bones\n */\n _this.children = new Array();\n /** Gets the animations associated with this bone */\n _this.animations = new Array();\n /**\n * @hidden Internal only\n * Set this value to map this bone to a different index in the transform matrices\n * Set this value to -1 to exclude the bone from the transform matrices\n */\n _this._index = null;\n _this._absoluteTransform = new BABYLON.Matrix();\n _this._invertedAbsoluteTransform = new BABYLON.Matrix();\n _this._scalingDeterminant = 1;\n _this._worldTransform = new BABYLON.Matrix();\n _this._needToDecompose = true;\n _this._needToCompose = false;\n _this._skeleton = skeleton;\n _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();\n _this._restPose = restPose ? restPose : _this._localMatrix.clone();\n _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();\n _this._index = index;\n skeleton.bones.push(_this);\n _this.setParent(parentBone, false);\n if (baseMatrix || localMatrix) {\n _this._updateDifferenceMatrix();\n }\n return _this;\n }\n Object.defineProperty(Bone.prototype, \"_matrix\", {\n /** @hidden */\n get: function () {\n this._compose();\n return this._localMatrix;\n },\n /** @hidden */\n set: function (value) {\n this._localMatrix.copyFrom(value);\n this._needToDecompose = true;\n },\n enumerable: true,\n configurable: true\n });\n // Members\n /**\n * Gets the parent skeleton\n * @returns a skeleton\n */\n Bone.prototype.getSkeleton = function () {\n return this._skeleton;\n };\n /**\n * Gets parent bone\n * @returns a bone or null if the bone is the root of the bone hierarchy\n */\n Bone.prototype.getParent = function () {\n return this._parent;\n };\n /**\n * Sets the parent bone\n * @param parent defines the parent (can be null if the bone is the root)\n * @param updateDifferenceMatrix defines if the difference matrix must be updated\n */\n Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {\n if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }\n if (this._parent === parent) {\n return;\n }\n if (this._parent) {\n var index = this._parent.children.indexOf(this);\n if (index !== -1) {\n this._parent.children.splice(index, 1);\n }\n }\n this._parent = parent;\n if (this._parent) {\n this._parent.children.push(this);\n }\n if (updateDifferenceMatrix) {\n this._updateDifferenceMatrix();\n }\n this.markAsDirty();\n };\n /**\n * Gets the local matrix\n * @returns a matrix\n */\n Bone.prototype.getLocalMatrix = function () {\n this._compose();\n return this._localMatrix;\n };\n /**\n * Gets the base matrix (initial matrix which remains unchanged)\n * @returns a matrix\n */\n Bone.prototype.getBaseMatrix = function () {\n return this._baseMatrix;\n };\n /**\n * Gets the rest pose matrix\n * @returns a matrix\n */\n Bone.prototype.getRestPose = function () {\n return this._restPose;\n };\n /**\n * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)\n */\n Bone.prototype.getWorldMatrix = function () {\n return this._worldTransform;\n };\n /**\n * Sets the local matrix to rest pose matrix\n */\n Bone.prototype.returnToRest = function () {\n this.updateMatrix(this._restPose.clone());\n };\n /**\n * Gets the inverse of the absolute transform matrix.\n * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)\n * @returns a matrix\n */\n Bone.prototype.getInvertedAbsoluteTransform = function () {\n return this._invertedAbsoluteTransform;\n };\n /**\n * Gets the absolute transform matrix (ie base matrix * parent world matrix)\n * @returns a matrix\n */\n Bone.prototype.getAbsoluteTransform = function () {\n return this._absoluteTransform;\n };\n Object.defineProperty(Bone.prototype, \"position\", {\n // Properties (matches AbstractMesh properties)\n /** Gets or sets current position (in local space) */\n get: function () {\n this._decompose();\n return this._localPosition;\n },\n set: function (newPosition) {\n this._decompose();\n this._localPosition.copyFrom(newPosition);\n this._markAsDirtyAndCompose();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Bone.prototype, \"rotation\", {\n /** Gets or sets current rotation (in local space) */\n get: function () {\n return this.getRotation();\n },\n set: function (newRotation) {\n this.setRotation(newRotation);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Bone.prototype, \"rotationQuaternion\", {\n /** Gets or sets current rotation quaternion (in local space) */\n get: function () {\n this._decompose();\n return this._localRotation;\n },\n set: function (newRotation) {\n this.setRotationQuaternion(newRotation);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Bone.prototype, \"scaling\", {\n /** Gets or sets current scaling (in local space) */\n get: function () {\n return this.getScale();\n },\n set: function (newScaling) {\n this.setScale(newScaling);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Bone.prototype, \"animationPropertiesOverride\", {\n /**\n * Gets the animation properties override\n */\n get: function () {\n return this._skeleton.animationPropertiesOverride;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n Bone.prototype._decompose = function () {\n if (!this._needToDecompose) {\n return;\n }\n this._needToDecompose = false;\n if (!this._localScaling) {\n this._localScaling = BABYLON.Vector3.Zero();\n this._localRotation = BABYLON.Quaternion.Zero();\n this._localPosition = BABYLON.Vector3.Zero();\n }\n this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);\n };\n Bone.prototype._compose = function () {\n if (!this._needToCompose) {\n return;\n }\n this._needToCompose = false;\n BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);\n };\n /**\n * Update the base and local matrices\n * @param matrix defines the new base or local matrix\n * @param updateDifferenceMatrix defines if the difference matrix must be updated\n * @param updateLocalMatrix defines if the local matrix should be updated\n */\n Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {\n if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }\n if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }\n this._baseMatrix.copyFrom(matrix);\n if (updateDifferenceMatrix) {\n this._updateDifferenceMatrix();\n }\n if (updateLocalMatrix) {\n this._localMatrix.copyFrom(matrix);\n this._markAsDirtyAndDecompose();\n }\n else {\n this.markAsDirty();\n }\n };\n /** @hidden */\n Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {\n if (updateChildren === void 0) { updateChildren = true; }\n if (!rootMatrix) {\n rootMatrix = this._baseMatrix;\n }\n if (this._parent) {\n rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);\n }\n else {\n this._absoluteTransform.copyFrom(rootMatrix);\n }\n this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);\n if (updateChildren) {\n for (var index = 0; index < this.children.length; index++) {\n this.children[index]._updateDifferenceMatrix();\n }\n }\n this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);\n };\n /**\n * Flag the bone as dirty (Forcing it to update everything)\n */\n Bone.prototype.markAsDirty = function () {\n this._currentRenderId++;\n this._childRenderId++;\n this._skeleton._markAsDirty();\n };\n Bone.prototype._markAsDirtyAndCompose = function () {\n this.markAsDirty();\n this._needToCompose = true;\n };\n Bone.prototype._markAsDirtyAndDecompose = function () {\n this.markAsDirty();\n this._needToDecompose = true;\n };\n /**\n * Copy an animation range from another bone\n * @param source defines the source bone\n * @param rangeName defines the range name to copy\n * @param frameOffset defines the frame offset\n * @param rescaleAsRequired defines if rescaling must be applied if required\n * @param skelDimensionsRatio defines the scaling ratio\n * @returns true if operation was successful\n */\n Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {\n if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }\n if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }\n // all animation may be coming from a library skeleton, so may need to create animation\n if (this.animations.length === 0) {\n this.animations.push(new BABYLON.Animation(this.name, \"_matrix\", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));\n this.animations[0].setKeys([]);\n }\n // get animation info / verify there is such a range from the source bone\n var sourceRange = source.animations[0].getRange(rangeName);\n if (!sourceRange) {\n return false;\n }\n var from = sourceRange.from;\n var to = sourceRange.to;\n var sourceKeys = source.animations[0].getKeys();\n // rescaling prep\n var sourceBoneLength = source.length;\n var sourceParent = source.getParent();\n var parent = this.getParent();\n var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;\n var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;\n var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);\n var destKeys = this.animations[0].getKeys();\n // loop vars declaration\n var orig;\n var origTranslation;\n var mat;\n for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {\n orig = sourceKeys[key];\n if (orig.frame >= from && orig.frame <= to) {\n if (rescaleAsRequired) {\n mat = orig.value.clone();\n // scale based on parent ratio, when bone has parent\n if (parentScalingReqd) {\n origTranslation = mat.getTranslation();\n mat.setTranslation(origTranslation.scaleInPlace(parentRatio));\n // scale based on skeleton dimension ratio when root bone, and value is passed\n }\n else if (dimensionsScalingReqd && skelDimensionsRatio) {\n origTranslation = mat.getTranslation();\n mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));\n // use original when root bone, and no data for skelDimensionsRatio\n }\n else {\n mat = orig.value;\n }\n }\n else {\n mat = orig.value;\n }\n destKeys.push({ frame: orig.frame + frameOffset, value: mat });\n }\n }\n this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);\n return true;\n };\n /**\n * Translate the bone in local or world space\n * @param vec The amount to translate the bone\n * @param space The space that the translation is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.translate = function (vec, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n var lm = this.getLocalMatrix();\n if (space == BABYLON.Space.LOCAL) {\n lm.m[12] += vec.x;\n lm.m[13] += vec.y;\n lm.m[14] += vec.z;\n }\n else {\n var wm = null;\n //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()\n if (mesh) {\n wm = mesh.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteTransforms();\n var tmat = Bone._tmpMats[0];\n var tvec = Bone._tmpVecs[0];\n if (this._parent) {\n if (mesh && wm) {\n tmat.copyFrom(this._parent.getAbsoluteTransform());\n tmat.multiplyToRef(wm, tmat);\n }\n else {\n tmat.copyFrom(this._parent.getAbsoluteTransform());\n }\n }\n tmat.m[12] = 0;\n tmat.m[13] = 0;\n tmat.m[14] = 0;\n tmat.invert();\n BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);\n lm.m[12] += tvec.x;\n lm.m[13] += tvec.y;\n lm.m[14] += tvec.z;\n }\n this._markAsDirtyAndDecompose();\n };\n /**\n * Set the postion of the bone in local or world space\n * @param position The position to set the bone\n * @param space The space that the position is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.setPosition = function (position, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n var lm = this.getLocalMatrix();\n if (space == BABYLON.Space.LOCAL) {\n lm.m[12] = position.x;\n lm.m[13] = position.y;\n lm.m[14] = position.z;\n }\n else {\n var wm = null;\n //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()\n if (mesh) {\n wm = mesh.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteTransforms();\n var tmat = Bone._tmpMats[0];\n var vec = Bone._tmpVecs[0];\n if (this._parent) {\n if (mesh && wm) {\n tmat.copyFrom(this._parent.getAbsoluteTransform());\n tmat.multiplyToRef(wm, tmat);\n }\n else {\n tmat.copyFrom(this._parent.getAbsoluteTransform());\n }\n }\n tmat.invert();\n BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);\n lm.m[12] = vec.x;\n lm.m[13] = vec.y;\n lm.m[14] = vec.z;\n }\n this._markAsDirtyAndDecompose();\n };\n /**\n * Set the absolute position of the bone (world space)\n * @param position The position to set the bone\n * @param mesh The mesh that this bone is attached to\n */\n Bone.prototype.setAbsolutePosition = function (position, mesh) {\n this.setPosition(position, BABYLON.Space.WORLD, mesh);\n };\n /**\n * Scale the bone on the x, y and z axes (in local space)\n * @param x The amount to scale the bone on the x axis\n * @param y The amount to scale the bone on the y axis\n * @param z The amount to scale the bone on the z axis\n * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)\n */\n Bone.prototype.scale = function (x, y, z, scaleChildren) {\n if (scaleChildren === void 0) { scaleChildren = false; }\n var locMat = this.getLocalMatrix();\n // Apply new scaling on top of current local matrix\n var scaleMat = Bone._tmpMats[0];\n BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);\n scaleMat.multiplyToRef(locMat, locMat);\n // Invert scaling matrix and apply the inverse to all children\n scaleMat.invert();\n for (var _i = 0, _a = this.children; _i < _a.length; _i++) {\n var child = _a[_i];\n var cm = child.getLocalMatrix();\n cm.multiplyToRef(scaleMat, cm);\n cm.m[12] *= x;\n cm.m[13] *= y;\n cm.m[14] *= z;\n child._markAsDirtyAndDecompose();\n }\n this._markAsDirtyAndDecompose();\n if (scaleChildren) {\n for (var _b = 0, _c = this.children; _b < _c.length; _b++) {\n var child = _c[_b];\n child.scale(x, y, z, scaleChildren);\n }\n }\n };\n /**\n * Set the bone scaling in local space\n * @param scale defines the scaling vector\n */\n Bone.prototype.setScale = function (scale) {\n this._decompose();\n this._localScaling.copyFrom(scale);\n this._markAsDirtyAndCompose();\n };\n /**\n * Gets the current scaling in local space\n * @returns the current scaling vector\n */\n Bone.prototype.getScale = function () {\n this._decompose();\n return this._localScaling;\n };\n /**\n * Gets the current scaling in local space and stores it in a target vector\n * @param result defines the target vector\n */\n Bone.prototype.getScaleToRef = function (result) {\n this._decompose();\n result.copyFrom(this._localScaling);\n };\n /**\n * Set the yaw, pitch, and roll of the bone in local or world space\n * @param yaw The rotation of the bone on the y axis\n * @param pitch The rotation of the bone on the x axis\n * @param roll The rotation of the bone on the z axis\n * @param space The space that the axes of rotation are in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (space === BABYLON.Space.LOCAL) {\n var quat = Bone._tmpQuat;\n BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);\n this.setRotationQuaternion(quat, space, mesh);\n return;\n }\n var rotMatInv = Bone._tmpMats[0];\n if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {\n return;\n }\n var rotMat = Bone._tmpMats[1];\n BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat);\n this._rotateWithMatrix(rotMat, space, mesh);\n };\n /**\n * Add a rotation to the bone on an axis in local or world space\n * @param axis The axis to rotate the bone on\n * @param amount The amount to rotate the bone\n * @param space The space that the axis is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.rotate = function (axis, amount, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n var rmat = Bone._tmpMats[0];\n rmat.m[12] = 0;\n rmat.m[13] = 0;\n rmat.m[14] = 0;\n BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);\n this._rotateWithMatrix(rmat, space, mesh);\n };\n /**\n * Set the rotation of the bone to a particular axis angle in local or world space\n * @param axis The axis to rotate the bone on\n * @param angle The angle that the bone should be rotated to\n * @param space The space that the axis is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (space === BABYLON.Space.LOCAL) {\n var quat = Bone._tmpQuat;\n BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);\n this.setRotationQuaternion(quat, space, mesh);\n return;\n }\n var rotMatInv = Bone._tmpMats[0];\n if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {\n return;\n }\n var rotMat = Bone._tmpMats[1];\n BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat);\n this._rotateWithMatrix(rotMat, space, mesh);\n };\n /**\n * Set the euler rotation of the bone in local of world space\n * @param rotation The euler rotation that the bone should be set to\n * @param space The space that the rotation is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.setRotation = function (rotation, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);\n };\n /**\n * Set the quaternion rotation of the bone in local of world space\n * @param quat The quaternion rotation that the bone should be set to\n * @param space The space that the rotation is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (space === BABYLON.Space.LOCAL) {\n this._decompose();\n this._localRotation.copyFrom(quat);\n this._markAsDirtyAndCompose();\n return;\n }\n var rotMatInv = Bone._tmpMats[0];\n if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {\n return;\n }\n var rotMat = Bone._tmpMats[1];\n BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat);\n this._rotateWithMatrix(rotMat, space, mesh);\n };\n /**\n * Set the rotation matrix of the bone in local of world space\n * @param rotMat The rotation matrix that the bone should be set to\n * @param space The space that the rotation is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n */\n Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (space === BABYLON.Space.LOCAL) {\n var quat = Bone._tmpQuat;\n BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);\n this.setRotationQuaternion(quat, space, mesh);\n return;\n }\n var rotMatInv = Bone._tmpMats[0];\n if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {\n return;\n }\n var rotMat2 = Bone._tmpMats[1];\n rotMat2.copyFrom(rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat2);\n this._rotateWithMatrix(rotMat2, space, mesh);\n };\n Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n var lmat = this.getLocalMatrix();\n var lx = lmat.m[12];\n var ly = lmat.m[13];\n var lz = lmat.m[14];\n var parent = this.getParent();\n var parentScale = Bone._tmpMats[3];\n var parentScaleInv = Bone._tmpMats[4];\n if (parent && space == BABYLON.Space.WORLD) {\n if (mesh) {\n parentScale.copyFrom(mesh.getWorldMatrix());\n parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);\n }\n else {\n parentScale.copyFrom(parent.getAbsoluteTransform());\n }\n parentScaleInv.copyFrom(parentScale);\n parentScaleInv.invert();\n lmat.multiplyToRef(parentScale, lmat);\n lmat.multiplyToRef(rmat, lmat);\n lmat.multiplyToRef(parentScaleInv, lmat);\n }\n else {\n if (space == BABYLON.Space.WORLD && mesh) {\n parentScale.copyFrom(mesh.getWorldMatrix());\n parentScaleInv.copyFrom(parentScale);\n parentScaleInv.invert();\n lmat.multiplyToRef(parentScale, lmat);\n lmat.multiplyToRef(rmat, lmat);\n lmat.multiplyToRef(parentScaleInv, lmat);\n }\n else {\n lmat.multiplyToRef(rmat, lmat);\n }\n }\n lmat.m[12] = lx;\n lmat.m[13] = ly;\n lmat.m[14] = lz;\n this.computeAbsoluteTransforms();\n this._markAsDirtyAndDecompose();\n };\n Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {\n var scaleMatrix = Bone._tmpMats[2];\n rotMatInv.copyFrom(this.getAbsoluteTransform());\n if (mesh) {\n rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);\n BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);\n }\n rotMatInv.invert();\n if (isNaN(rotMatInv.m[0])) {\n // Matrix failed to invert.\n // This can happen if scale is zero for example.\n return false;\n }\n scaleMatrix.m[0] *= this._scalingDeterminant;\n rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);\n return true;\n };\n /**\n * Get the position of the bone in local or world space\n * @param space The space that the returned position is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @returns The position of the bone\n */\n Bone.prototype.getPosition = function (space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (mesh === void 0) { mesh = null; }\n var pos = BABYLON.Vector3.Zero();\n this.getPositionToRef(space, mesh, pos);\n return pos;\n };\n /**\n * Copy the position of the bone to a vector3 in local or world space\n * @param space The space that the returned position is in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @param result The vector3 to copy the position to\n */\n Bone.prototype.getPositionToRef = function (space, mesh, result) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (space == BABYLON.Space.LOCAL) {\n var lm = this.getLocalMatrix();\n result.x = lm.m[12];\n result.y = lm.m[13];\n result.z = lm.m[14];\n }\n else {\n var wm = null;\n //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()\n if (mesh) {\n wm = mesh.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteTransforms();\n var tmat = Bone._tmpMats[0];\n if (mesh && wm) {\n tmat.copyFrom(this.getAbsoluteTransform());\n tmat.multiplyToRef(wm, tmat);\n }\n else {\n tmat = this.getAbsoluteTransform();\n }\n result.x = tmat.m[12];\n result.y = tmat.m[13];\n result.z = tmat.m[14];\n }\n };\n /**\n * Get the absolute position of the bone (world space)\n * @param mesh The mesh that this bone is attached to\n * @returns The absolute position of the bone\n */\n Bone.prototype.getAbsolutePosition = function (mesh) {\n if (mesh === void 0) { mesh = null; }\n var pos = BABYLON.Vector3.Zero();\n this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);\n return pos;\n };\n /**\n * Copy the absolute position of the bone (world space) to the result param\n * @param mesh The mesh that this bone is attached to\n * @param result The vector3 to copy the absolute position to\n */\n Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {\n this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);\n };\n /**\n * Compute the absolute transforms of this bone and its children\n */\n Bone.prototype.computeAbsoluteTransforms = function () {\n this._compose();\n if (this._parent) {\n this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);\n }\n else {\n this._absoluteTransform.copyFrom(this._localMatrix);\n var poseMatrix = this._skeleton.getPoseMatrix();\n if (poseMatrix) {\n this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);\n }\n }\n var children = this.children;\n var len = children.length;\n for (var i = 0; i < len; i++) {\n children[i].computeAbsoluteTransforms();\n }\n };\n /**\n * Get the world direction from an axis that is in the local space of the bone\n * @param localAxis The local direction that is used to compute the world direction\n * @param mesh The mesh that this bone is attached to\n * @returns The world direction\n */\n Bone.prototype.getDirection = function (localAxis, mesh) {\n if (mesh === void 0) { mesh = null; }\n var result = BABYLON.Vector3.Zero();\n this.getDirectionToRef(localAxis, mesh, result);\n return result;\n };\n /**\n * Copy the world direction to a vector3 from an axis that is in the local space of the bone\n * @param localAxis The local direction that is used to compute the world direction\n * @param mesh The mesh that this bone is attached to\n * @param result The vector3 that the world direction will be copied to\n */\n Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {\n if (mesh === void 0) { mesh = null; }\n var wm = null;\n //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()\n if (mesh) {\n wm = mesh.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteTransforms();\n var mat = Bone._tmpMats[0];\n mat.copyFrom(this.getAbsoluteTransform());\n if (mesh && wm) {\n mat.multiplyToRef(wm, mat);\n }\n BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);\n result.normalize();\n };\n /**\n * Get the euler rotation of the bone in local or world space\n * @param space The space that the rotation should be in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @returns The euler rotation\n */\n Bone.prototype.getRotation = function (space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (mesh === void 0) { mesh = null; }\n var result = BABYLON.Vector3.Zero();\n this.getRotationToRef(space, mesh, result);\n return result;\n };\n /**\n * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space\n * @param space The space that the rotation should be in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @param result The vector3 that the rotation should be copied to\n */\n Bone.prototype.getRotationToRef = function (space, mesh, result) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (mesh === void 0) { mesh = null; }\n var quat = Bone._tmpQuat;\n this.getRotationQuaternionToRef(space, mesh, quat);\n quat.toEulerAnglesToRef(result);\n };\n /**\n * Get the quaternion rotation of the bone in either local or world space\n * @param space The space that the rotation should be in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @returns The quaternion rotation\n */\n Bone.prototype.getRotationQuaternion = function (space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (mesh === void 0) { mesh = null; }\n var result = BABYLON.Quaternion.Identity();\n this.getRotationQuaternionToRef(space, mesh, result);\n return result;\n };\n /**\n * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space\n * @param space The space that the rotation should be in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @param result The quaternion that the rotation should be copied to\n */\n Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (mesh === void 0) { mesh = null; }\n if (space == BABYLON.Space.LOCAL) {\n this._decompose();\n result.copyFrom(this._localRotation);\n }\n else {\n var mat = Bone._tmpMats[0];\n var amat = this.getAbsoluteTransform();\n if (mesh) {\n amat.multiplyToRef(mesh.getWorldMatrix(), mat);\n }\n else {\n mat.copyFrom(amat);\n }\n mat.m[0] *= this._scalingDeterminant;\n mat.m[1] *= this._scalingDeterminant;\n mat.m[2] *= this._scalingDeterminant;\n mat.decompose(undefined, result, undefined);\n }\n };\n /**\n * Get the rotation matrix of the bone in local or world space\n * @param space The space that the rotation should be in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @returns The rotation matrix\n */\n Bone.prototype.getRotationMatrix = function (space, mesh) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n var result = BABYLON.Matrix.Identity();\n this.getRotationMatrixToRef(space, mesh, result);\n return result;\n };\n /**\n * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space\n * @param space The space that the rotation should be in\n * @param mesh The mesh that this bone is attached to. This is only used in world space\n * @param result The quaternion that the rotation should be copied to\n */\n Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {\n if (space === void 0) { space = BABYLON.Space.LOCAL; }\n if (space == BABYLON.Space.LOCAL) {\n this.getLocalMatrix().getRotationMatrixToRef(result);\n }\n else {\n var mat = Bone._tmpMats[0];\n var amat = this.getAbsoluteTransform();\n if (mesh) {\n amat.multiplyToRef(mesh.getWorldMatrix(), mat);\n }\n else {\n mat.copyFrom(amat);\n }\n mat.m[0] *= this._scalingDeterminant;\n mat.m[1] *= this._scalingDeterminant;\n mat.m[2] *= this._scalingDeterminant;\n mat.getRotationMatrixToRef(result);\n }\n };\n /**\n * Get the world position of a point that is in the local space of the bone\n * @param position The local position\n * @param mesh The mesh that this bone is attached to\n * @returns The world position\n */\n Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {\n if (mesh === void 0) { mesh = null; }\n var result = BABYLON.Vector3.Zero();\n this.getAbsolutePositionFromLocalToRef(position, mesh, result);\n return result;\n };\n /**\n * Get the world position of a point that is in the local space of the bone and copy it to the result param\n * @param position The local position\n * @param mesh The mesh that this bone is attached to\n * @param result The vector3 that the world position should be copied to\n */\n Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {\n if (mesh === void 0) { mesh = null; }\n var wm = null;\n //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()\n if (mesh) {\n wm = mesh.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteTransforms();\n var tmat = Bone._tmpMats[0];\n if (mesh && wm) {\n tmat.copyFrom(this.getAbsoluteTransform());\n tmat.multiplyToRef(wm, tmat);\n }\n else {\n tmat = this.getAbsoluteTransform();\n }\n BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);\n };\n /**\n * Get the local position of a point that is in world space\n * @param position The world position\n * @param mesh The mesh that this bone is attached to\n * @returns The local position\n */\n Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {\n if (mesh === void 0) { mesh = null; }\n var result = BABYLON.Vector3.Zero();\n this.getLocalPositionFromAbsoluteToRef(position, mesh, result);\n return result;\n };\n /**\n * Get the local position of a point that is in world space and copy it to the result param\n * @param position The world position\n * @param mesh The mesh that this bone is attached to\n * @param result The vector3 that the local position should be copied to\n */\n Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {\n if (mesh === void 0) { mesh = null; }\n var wm = null;\n //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()\n if (mesh) {\n wm = mesh.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteTransforms();\n var tmat = Bone._tmpMats[0];\n tmat.copyFrom(this.getAbsoluteTransform());\n if (mesh && wm) {\n tmat.multiplyToRef(wm, tmat);\n }\n tmat.invert();\n BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);\n };\n Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n Bone._tmpQuat = BABYLON.Quaternion.Identity();\n Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];\n return Bone;\n }(BABYLON.Node));\n BABYLON.Bone = Bone;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.bone.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to apply inverse kinematics to bones\n * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller\n */\n var BoneIKController = /** @class */ (function () {\n /**\n * Creates a new BoneIKController\n * @param mesh defines the mesh to control\n * @param bone defines the bone to control\n * @param options defines options to set up the controller\n */\n function BoneIKController(mesh, bone, options) {\n /**\n * Gets or sets the target position\n */\n this.targetPosition = BABYLON.Vector3.Zero();\n /**\n * Gets or sets the pole target position\n */\n this.poleTargetPosition = BABYLON.Vector3.Zero();\n /**\n * Gets or sets the pole target local offset\n */\n this.poleTargetLocalOffset = BABYLON.Vector3.Zero();\n /**\n * Gets or sets the pole angle\n */\n this.poleAngle = 0;\n /**\n * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)\n */\n this.slerpAmount = 1;\n this._bone1Quat = BABYLON.Quaternion.Identity();\n this._bone1Mat = BABYLON.Matrix.Identity();\n this._bone2Ang = Math.PI;\n this._maxAngle = Math.PI;\n this._rightHandedSystem = false;\n this._bendAxis = BABYLON.Vector3.Right();\n this._slerping = false;\n this._adjustRoll = 0;\n this._bone2 = bone;\n this._bone1 = bone.getParent();\n if (!this._bone1) {\n return;\n }\n this.mesh = mesh;\n var bonePos = bone.getPosition();\n if (bone.getAbsoluteTransform().determinant() > 0) {\n this._rightHandedSystem = true;\n this._bendAxis.x = 0;\n this._bendAxis.y = 0;\n this._bendAxis.z = -1;\n if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {\n this._adjustRoll = Math.PI * .5;\n this._bendAxis.z = 1;\n }\n }\n if (this._bone1.length) {\n var boneScale1 = this._bone1.getScale();\n var boneScale2 = this._bone2.getScale();\n this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;\n this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;\n }\n else if (this._bone1.children[0]) {\n mesh.computeWorldMatrix(true);\n var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);\n var pos2 = this._bone2.getAbsolutePosition(mesh);\n var pos3 = this._bone1.getAbsolutePosition(mesh);\n this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);\n this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);\n }\n this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);\n this.maxAngle = Math.PI;\n if (options) {\n if (options.targetMesh) {\n this.targetMesh = options.targetMesh;\n this.targetMesh.computeWorldMatrix(true);\n }\n if (options.poleTargetMesh) {\n this.poleTargetMesh = options.poleTargetMesh;\n this.poleTargetMesh.computeWorldMatrix(true);\n }\n else if (options.poleTargetBone) {\n this.poleTargetBone = options.poleTargetBone;\n }\n else if (this._bone1.getParent()) {\n this.poleTargetBone = this._bone1.getParent();\n }\n if (options.poleTargetLocalOffset) {\n this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);\n }\n if (options.poleAngle) {\n this.poleAngle = options.poleAngle;\n }\n if (options.bendAxis) {\n this._bendAxis.copyFrom(options.bendAxis);\n }\n if (options.maxAngle) {\n this.maxAngle = options.maxAngle;\n }\n if (options.slerpAmount) {\n this.slerpAmount = options.slerpAmount;\n }\n }\n }\n Object.defineProperty(BoneIKController.prototype, \"maxAngle\", {\n /**\n * Gets or sets maximum allowed angle\n */\n get: function () {\n return this._maxAngle;\n },\n set: function (value) {\n this._setMaxAngle(value);\n },\n enumerable: true,\n configurable: true\n });\n BoneIKController.prototype._setMaxAngle = function (ang) {\n if (ang < 0) {\n ang = 0;\n }\n if (ang > Math.PI || ang == undefined) {\n ang = Math.PI;\n }\n this._maxAngle = ang;\n var a = this._bone1Length;\n var b = this._bone2Length;\n this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));\n };\n /**\n * Force the controller to update the bones\n */\n BoneIKController.prototype.update = function () {\n var bone1 = this._bone1;\n if (!bone1) {\n return;\n }\n var target = this.targetPosition;\n var poleTarget = this.poleTargetPosition;\n var mat1 = BoneIKController._tmpMats[0];\n var mat2 = BoneIKController._tmpMats[1];\n if (this.targetMesh) {\n target.copyFrom(this.targetMesh.getAbsolutePosition());\n }\n if (this.poleTargetBone) {\n this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);\n }\n else if (this.poleTargetMesh) {\n BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);\n }\n var bonePos = BoneIKController._tmpVecs[0];\n var zaxis = BoneIKController._tmpVecs[1];\n var xaxis = BoneIKController._tmpVecs[2];\n var yaxis = BoneIKController._tmpVecs[3];\n var upAxis = BoneIKController._tmpVecs[4];\n var _tmpQuat = BoneIKController._tmpQuat;\n bone1.getAbsolutePositionToRef(this.mesh, bonePos);\n poleTarget.subtractToRef(bonePos, upAxis);\n if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {\n upAxis.y = 1;\n }\n else {\n upAxis.normalize();\n }\n target.subtractToRef(bonePos, yaxis);\n yaxis.normalize();\n BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);\n zaxis.normalize();\n BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);\n xaxis.normalize();\n BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);\n var a = this._bone1Length;\n var b = this._bone2Length;\n var c = BABYLON.Vector3.Distance(bonePos, target);\n if (this._maxReach > 0) {\n c = Math.min(this._maxReach, c);\n }\n var acosa = (b * b + c * c - a * a) / (2 * b * c);\n var acosb = (c * c + a * a - b * b) / (2 * c * a);\n if (acosa > 1) {\n acosa = 1;\n }\n if (acosb > 1) {\n acosb = 1;\n }\n if (acosa < -1) {\n acosa = -1;\n }\n if (acosb < -1) {\n acosb = -1;\n }\n var angA = Math.acos(acosa);\n var angB = Math.acos(acosb);\n var angC = -angA - angB;\n if (this._rightHandedSystem) {\n BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);\n mat2.multiplyToRef(mat1, mat1);\n BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);\n mat2.multiplyToRef(mat1, mat1);\n }\n else {\n var _tmpVec = BoneIKController._tmpVecs[5];\n _tmpVec.copyFrom(this._bendAxis);\n _tmpVec.x *= -1;\n BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);\n mat2.multiplyToRef(mat1, mat1);\n }\n if (this.poleAngle) {\n BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);\n mat1.multiplyToRef(mat2, mat1);\n }\n if (this._bone1) {\n if (this.slerpAmount < 1) {\n if (!this._slerping) {\n BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);\n }\n BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);\n BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);\n angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;\n this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);\n this._slerping = true;\n }\n else {\n this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);\n this._bone1Mat.copyFrom(mat1);\n this._slerping = false;\n }\n }\n this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);\n this._bone2Ang = angC;\n };\n BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();\n BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];\n return BoneIKController;\n }());\n BABYLON.BoneIKController = BoneIKController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boneIKController.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to make a bone look toward a point in space\n * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller\n */\n var BoneLookController = /** @class */ (function () {\n /**\n * Create a BoneLookController\n * @param mesh the mesh that the bone belongs to\n * @param bone the bone that will be looking to the target\n * @param target the target Vector3 to look at\n * @param settings optional settings:\n * * maxYaw: the maximum angle the bone will yaw to\n * * minYaw: the minimum angle the bone will yaw to\n * * maxPitch: the maximum angle the bone will pitch to\n * * minPitch: the minimum angle the bone will yaw to\n * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.\n * * upAxis: the up axis of the coordinate system\n * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.\n * * yawAxis: set yawAxis if the bone does not yaw on the y axis\n * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis\n * * adjustYaw: used to make an adjustment to the yaw of the bone\n * * adjustPitch: used to make an adjustment to the pitch of the bone\n * * adjustRoll: used to make an adjustment to the roll of the bone\n **/\n function BoneLookController(mesh, bone, target, options) {\n /**\n * The up axis of the coordinate system that is used when the bone is rotated\n */\n this.upAxis = BABYLON.Vector3.Up();\n /**\n * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD\n */\n this.upAxisSpace = BABYLON.Space.LOCAL;\n /**\n * Used to make an adjustment to the yaw of the bone\n */\n this.adjustYaw = 0;\n /**\n * Used to make an adjustment to the pitch of the bone\n */\n this.adjustPitch = 0;\n /**\n * Used to make an adjustment to the roll of the bone\n */\n this.adjustRoll = 0;\n /**\n * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)\n */\n this.slerpAmount = 1;\n this._boneQuat = BABYLON.Quaternion.Identity();\n this._slerping = false;\n this._firstFrameSkipped = false;\n this._fowardAxis = BABYLON.Vector3.Forward();\n this.mesh = mesh;\n this.bone = bone;\n this.target = target;\n if (options) {\n if (options.adjustYaw) {\n this.adjustYaw = options.adjustYaw;\n }\n if (options.adjustPitch) {\n this.adjustPitch = options.adjustPitch;\n }\n if (options.adjustRoll) {\n this.adjustRoll = options.adjustRoll;\n }\n if (options.maxYaw != null) {\n this.maxYaw = options.maxYaw;\n }\n else {\n this.maxYaw = Math.PI;\n }\n if (options.minYaw != null) {\n this.minYaw = options.minYaw;\n }\n else {\n this.minYaw = -Math.PI;\n }\n if (options.maxPitch != null) {\n this.maxPitch = options.maxPitch;\n }\n else {\n this.maxPitch = Math.PI;\n }\n if (options.minPitch != null) {\n this.minPitch = options.minPitch;\n }\n else {\n this.minPitch = -Math.PI;\n }\n if (options.slerpAmount != null) {\n this.slerpAmount = options.slerpAmount;\n }\n if (options.upAxis != null) {\n this.upAxis = options.upAxis;\n }\n if (options.upAxisSpace != null) {\n this.upAxisSpace = options.upAxisSpace;\n }\n if (options.yawAxis != null || options.pitchAxis != null) {\n var newYawAxis = BABYLON.Axis.Y;\n var newPitchAxis = BABYLON.Axis.X;\n if (options.yawAxis != null) {\n newYawAxis = options.yawAxis.clone();\n newYawAxis.normalize();\n }\n if (options.pitchAxis != null) {\n newPitchAxis = options.pitchAxis.clone();\n newPitchAxis.normalize();\n }\n var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);\n this._transformYawPitch = BABYLON.Matrix.Identity();\n BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);\n this._transformYawPitchInv = this._transformYawPitch.clone();\n this._transformYawPitch.invert();\n }\n }\n if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {\n this.upAxisSpace = BABYLON.Space.LOCAL;\n }\n }\n Object.defineProperty(BoneLookController.prototype, \"minYaw\", {\n /**\n * Gets or sets the minimum yaw angle that the bone can look to\n */\n get: function () {\n return this._minYaw;\n },\n set: function (value) {\n this._minYaw = value;\n this._minYawSin = Math.sin(value);\n this._minYawCos = Math.cos(value);\n if (this._maxYaw != null) {\n this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;\n this._yawRange = this._maxYaw - this._minYaw;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BoneLookController.prototype, \"maxYaw\", {\n /**\n * Gets or sets the maximum yaw angle that the bone can look to\n */\n get: function () {\n return this._maxYaw;\n },\n set: function (value) {\n this._maxYaw = value;\n this._maxYawSin = Math.sin(value);\n this._maxYawCos = Math.cos(value);\n if (this._minYaw != null) {\n this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;\n this._yawRange = this._maxYaw - this._minYaw;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BoneLookController.prototype, \"minPitch\", {\n /**\n * Gets or sets the minimum pitch angle that the bone can look to\n */\n get: function () {\n return this._minPitch;\n },\n set: function (value) {\n this._minPitch = value;\n this._minPitchTan = Math.tan(value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BoneLookController.prototype, \"maxPitch\", {\n /**\n * Gets or sets the maximum pitch angle that the bone can look to\n */\n get: function () {\n return this._maxPitch;\n },\n set: function (value) {\n this._maxPitch = value;\n this._maxPitchTan = Math.tan(value);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())\n */\n BoneLookController.prototype.update = function () {\n //skip the first frame when slerping so that the mesh rotation is correct\n if (this.slerpAmount < 1 && !this._firstFrameSkipped) {\n this._firstFrameSkipped = true;\n return;\n }\n var bone = this.bone;\n var bonePos = BoneLookController._tmpVecs[0];\n bone.getAbsolutePositionToRef(this.mesh, bonePos);\n var target = this.target;\n var _tmpMat1 = BoneLookController._tmpMats[0];\n var _tmpMat2 = BoneLookController._tmpMats[1];\n var mesh = this.mesh;\n var parentBone = bone.getParent();\n var upAxis = BoneLookController._tmpVecs[1];\n upAxis.copyFrom(this.upAxis);\n if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {\n if (this._transformYawPitch) {\n BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);\n }\n parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);\n }\n else if (this.upAxisSpace == BABYLON.Space.LOCAL) {\n mesh.getDirectionToRef(upAxis, upAxis);\n if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {\n upAxis.normalize();\n }\n }\n var checkYaw = false;\n var checkPitch = false;\n if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {\n checkYaw = true;\n }\n if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {\n checkPitch = true;\n }\n if (checkYaw || checkPitch) {\n var spaceMat = BoneLookController._tmpMats[2];\n var spaceMatInv = BoneLookController._tmpMats[3];\n if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {\n parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);\n }\n else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {\n spaceMat.copyFrom(mesh.getWorldMatrix());\n }\n else {\n var forwardAxis = BoneLookController._tmpVecs[2];\n forwardAxis.copyFrom(this._fowardAxis);\n if (this._transformYawPitch) {\n BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);\n }\n if (parentBone) {\n parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);\n }\n else {\n mesh.getDirectionToRef(forwardAxis, forwardAxis);\n }\n var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);\n rightAxis.normalize();\n var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);\n BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);\n }\n spaceMat.invertToRef(spaceMatInv);\n var xzlen = null;\n if (checkPitch) {\n var localTarget = BoneLookController._tmpVecs[3];\n target.subtractToRef(bonePos, localTarget);\n BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);\n xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);\n var pitch = Math.atan2(localTarget.y, xzlen);\n var newPitch = pitch;\n if (pitch > this._maxPitch) {\n localTarget.y = this._maxPitchTan * xzlen;\n newPitch = this._maxPitch;\n }\n else if (pitch < this._minPitch) {\n localTarget.y = this._minPitchTan * xzlen;\n newPitch = this._minPitch;\n }\n if (pitch != newPitch) {\n BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);\n localTarget.addInPlace(bonePos);\n target = localTarget;\n }\n }\n if (checkYaw) {\n var localTarget = BoneLookController._tmpVecs[4];\n target.subtractToRef(bonePos, localTarget);\n BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);\n var yaw = Math.atan2(localTarget.x, localTarget.z);\n var newYaw = yaw;\n if (yaw > this._maxYaw || yaw < this._minYaw) {\n if (xzlen == null) {\n xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);\n }\n if (this._yawRange > Math.PI) {\n if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {\n localTarget.z = this._maxYawCos * xzlen;\n localTarget.x = this._maxYawSin * xzlen;\n newYaw = this._maxYaw;\n }\n else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {\n localTarget.z = this._minYawCos * xzlen;\n localTarget.x = this._minYawSin * xzlen;\n newYaw = this._minYaw;\n }\n }\n else {\n if (yaw > this._maxYaw) {\n localTarget.z = this._maxYawCos * xzlen;\n localTarget.x = this._maxYawSin * xzlen;\n newYaw = this._maxYaw;\n }\n else if (yaw < this._minYaw) {\n localTarget.z = this._minYawCos * xzlen;\n localTarget.x = this._minYawSin * xzlen;\n newYaw = this._minYaw;\n }\n }\n }\n if (this._slerping && this._yawRange > Math.PI) {\n //are we going to be crossing into the min/max region?\n var boneFwd = BoneLookController._tmpVecs[8];\n boneFwd.copyFrom(BABYLON.Axis.Z);\n if (this._transformYawPitch) {\n BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);\n }\n var boneRotMat = BoneLookController._tmpMats[4];\n this._boneQuat.toRotationMatrix(boneRotMat);\n this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);\n BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);\n BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);\n var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);\n var angBtwTar = this._getAngleBetween(boneYaw, yaw);\n var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);\n if (angBtwTar > angBtwMidYaw) {\n if (xzlen == null) {\n xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);\n }\n var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);\n var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);\n if (angBtwMin < angBtwMax) {\n newYaw = boneYaw + Math.PI * .75;\n localTarget.z = Math.cos(newYaw) * xzlen;\n localTarget.x = Math.sin(newYaw) * xzlen;\n }\n else {\n newYaw = boneYaw - Math.PI * .75;\n localTarget.z = Math.cos(newYaw) * xzlen;\n localTarget.x = Math.sin(newYaw) * xzlen;\n }\n }\n }\n if (yaw != newYaw) {\n BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);\n localTarget.addInPlace(bonePos);\n target = localTarget;\n }\n }\n }\n var zaxis = BoneLookController._tmpVecs[5];\n var xaxis = BoneLookController._tmpVecs[6];\n var yaxis = BoneLookController._tmpVecs[7];\n var _tmpQuat = BoneLookController._tmpQuat;\n target.subtractToRef(bonePos, zaxis);\n zaxis.normalize();\n BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);\n xaxis.normalize();\n BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);\n yaxis.normalize();\n BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);\n if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {\n return;\n }\n if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {\n return;\n }\n if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {\n return;\n }\n if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {\n BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);\n _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);\n }\n if (this.slerpAmount < 1) {\n if (!this._slerping) {\n this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);\n }\n if (this._transformYawPitch) {\n this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);\n }\n BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);\n BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);\n this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);\n this._slerping = true;\n }\n else {\n if (this._transformYawPitch) {\n this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);\n }\n this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);\n this._slerping = false;\n }\n };\n BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {\n var angDiff = ang2 - ang1;\n angDiff %= Math.PI * 2;\n if (angDiff > Math.PI) {\n angDiff -= Math.PI * 2;\n }\n else if (angDiff < -Math.PI) {\n angDiff += Math.PI * 2;\n }\n return angDiff;\n };\n BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {\n ang1 %= (2 * Math.PI);\n ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;\n ang2 %= (2 * Math.PI);\n ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;\n var ab = 0;\n if (ang1 < ang2) {\n ab = ang2 - ang1;\n }\n else {\n ab = ang1 - ang2;\n }\n if (ab > Math.PI) {\n ab = Math.PI * 2 - ab;\n }\n return ab;\n };\n BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {\n ang %= (2 * Math.PI);\n ang = (ang < 0) ? ang + (2 * Math.PI) : ang;\n ang1 %= (2 * Math.PI);\n ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;\n ang2 %= (2 * Math.PI);\n ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;\n if (ang1 < ang2) {\n if (ang > ang1 && ang < ang2) {\n return true;\n }\n }\n else {\n if (ang > ang2 && ang < ang1) {\n return true;\n }\n }\n return false;\n };\n BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();\n BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];\n return BoneLookController;\n }());\n BABYLON.BoneLookController = BoneLookController;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boneLookController.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to handle skinning animations\n * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons\n */\n var Skeleton = /** @class */ (function () {\n /**\n * Creates a new skeleton\n * @param name defines the skeleton name\n * @param id defines the skeleton Id\n * @param scene defines the hosting scene\n */\n function Skeleton(\n /** defines the skeleton name */\n name, \n /** defines the skeleton Id */\n id, scene) {\n this.name = name;\n this.id = id;\n /**\n * Gets the list of child bones\n */\n this.bones = new Array();\n /**\n * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)\n */\n this.needInitialSkinMatrix = false;\n this._isDirty = true;\n this._meshesWithPoseMatrix = new Array();\n this._identity = BABYLON.Matrix.Identity();\n this._ranges = {};\n this._lastAbsoluteTransformsUpdateId = -1;\n /**\n * Specifies if the skeleton should be serialized\n */\n this.doNotSerialize = false;\n this._animationPropertiesOverride = null;\n // Events\n /**\n * An observable triggered before computing the skeleton's matrices\n */\n this.onBeforeComputeObservable = new BABYLON.Observable();\n this.bones = [];\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n scene.skeletons.push(this);\n //make sure it will recalculate the matrix next time prepare is called.\n this._isDirty = true;\n }\n Object.defineProperty(Skeleton.prototype, \"animationPropertiesOverride\", {\n /**\n * Gets or sets the animation properties override\n */\n get: function () {\n if (!this._animationPropertiesOverride) {\n return this._scene.animationPropertiesOverride;\n }\n return this._animationPropertiesOverride;\n },\n set: function (value) {\n this._animationPropertiesOverride = value;\n },\n enumerable: true,\n configurable: true\n });\n // Members\n /**\n * Gets the list of transform matrices to send to shaders (one matrix per bone)\n * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)\n * @returns a Float32Array containing matrices data\n */\n Skeleton.prototype.getTransformMatrices = function (mesh) {\n if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {\n return mesh._bonesTransformMatrices;\n }\n if (!this._transformMatrices) {\n this.prepare();\n }\n return this._transformMatrices;\n };\n /**\n * Gets the current hosting scene\n * @returns a scene object\n */\n Skeleton.prototype.getScene = function () {\n return this._scene;\n };\n // Methods\n /**\n * Gets a string representing the current skeleton data\n * @param fullDetails defines a boolean indicating if we want a verbose version\n * @returns a string representing the current skeleton data\n */\n Skeleton.prototype.toString = function (fullDetails) {\n var ret = \"Name: \" + this.name + \", nBones: \" + this.bones.length;\n ret += \", nAnimationRanges: \" + (this._ranges ? Object.keys(this._ranges).length : \"none\");\n if (fullDetails) {\n ret += \", Ranges: {\";\n var first = true;\n for (var name_1 in this._ranges) {\n if (first) {\n ret += \", \";\n first = false;\n }\n ret += name_1;\n }\n ret += \"}\";\n }\n return ret;\n };\n /**\n * Get bone's index searching by name\n * @param name defines bone's name to search for\n * @return the indice of the bone. Returns -1 if not found\n */\n Skeleton.prototype.getBoneIndexByName = function (name) {\n for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {\n if (this.bones[boneIndex].name === name) {\n return boneIndex;\n }\n }\n return -1;\n };\n /**\n * Creater a new animation range\n * @param name defines the name of the range\n * @param from defines the start key\n * @param to defines the end key\n */\n Skeleton.prototype.createAnimationRange = function (name, from, to) {\n // check name not already in use\n if (!this._ranges[name]) {\n this._ranges[name] = new BABYLON.AnimationRange(name, from, to);\n for (var i = 0, nBones = this.bones.length; i < nBones; i++) {\n if (this.bones[i].animations[0]) {\n this.bones[i].animations[0].createRange(name, from, to);\n }\n }\n }\n };\n /**\n * Delete a specific animation range\n * @param name defines the name of the range\n * @param deleteFrames defines if frames must be removed as well\n */\n Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {\n if (deleteFrames === void 0) { deleteFrames = true; }\n for (var i = 0, nBones = this.bones.length; i < nBones; i++) {\n if (this.bones[i].animations[0]) {\n this.bones[i].animations[0].deleteRange(name, deleteFrames);\n }\n }\n this._ranges[name] = null; // said much faster than 'delete this._range[name]' \n };\n /**\n * Gets a specific animation range\n * @param name defines the name of the range to look for\n * @returns the requested animation range or null if not found\n */\n Skeleton.prototype.getAnimationRange = function (name) {\n return this._ranges[name];\n };\n /**\n * Gets the list of all animation ranges defined on this skeleton\n * @returns an array\n */\n Skeleton.prototype.getAnimationRanges = function () {\n var animationRanges = [];\n var name;\n var i = 0;\n for (name in this._ranges) {\n animationRanges[i] = this._ranges[name];\n i++;\n }\n return animationRanges;\n };\n /**\n * Copy animation range from a source skeleton.\n * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences\n * @param source defines the source skeleton\n * @param name defines the name of the range to copy\n * @param rescaleAsRequired defines if rescaling must be applied if required\n * @returns true if operation was successful\n */\n Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {\n if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }\n if (this._ranges[name] || !source.getAnimationRange(name)) {\n return false;\n }\n var ret = true;\n var frameOffset = this._getHighestAnimationFrame() + 1;\n // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required\n var boneDict = {};\n var sourceBones = source.bones;\n var nBones;\n var i;\n for (i = 0, nBones = sourceBones.length; i < nBones; i++) {\n boneDict[sourceBones[i].name] = sourceBones[i];\n }\n if (this.bones.length !== sourceBones.length) {\n BABYLON.Tools.Warn(\"copyAnimationRange: this rig has \" + this.bones.length + \" bones, while source as \" + sourceBones.length);\n ret = false;\n }\n var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;\n for (i = 0, nBones = this.bones.length; i < nBones; i++) {\n var boneName = this.bones[i].name;\n var sourceBone = boneDict[boneName];\n if (sourceBone) {\n ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);\n }\n else {\n BABYLON.Tools.Warn(\"copyAnimationRange: not same rig, missing source bone \" + boneName);\n ret = false;\n }\n }\n // do not call createAnimationRange(), since it also is done to bones, which was already done\n var range = source.getAnimationRange(name);\n if (range) {\n this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);\n }\n return ret;\n };\n /**\n * Forces the skeleton to go to rest pose\n */\n Skeleton.prototype.returnToRest = function () {\n for (var index = 0; index < this.bones.length; index++) {\n this.bones[index].returnToRest();\n }\n };\n Skeleton.prototype._getHighestAnimationFrame = function () {\n var ret = 0;\n for (var i = 0, nBones = this.bones.length; i < nBones; i++) {\n if (this.bones[i].animations[0]) {\n var highest = this.bones[i].animations[0].getHighestFrame();\n if (ret < highest) {\n ret = highest;\n }\n }\n }\n return ret;\n };\n /**\n * Begin a specific animation range\n * @param name defines the name of the range to start\n * @param loop defines if looping must be turned on (false by default)\n * @param speedRatio defines the speed ratio to apply (1 by default)\n * @param onAnimationEnd defines a callback which will be called when animation will end\n * @returns a new animatable\n */\n Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {\n var range = this.getAnimationRange(name);\n if (!range) {\n return null;\n }\n return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);\n };\n /** @hidden */\n Skeleton.prototype._markAsDirty = function () {\n this._isDirty = true;\n };\n /** @hidden */\n Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {\n this._meshesWithPoseMatrix.push(mesh);\n };\n /** @hidden */\n Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {\n var index = this._meshesWithPoseMatrix.indexOf(mesh);\n if (index > -1) {\n this._meshesWithPoseMatrix.splice(index, 1);\n }\n };\n /** @hidden */\n Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {\n this.onBeforeComputeObservable.notifyObservers(this);\n for (var index = 0; index < this.bones.length; index++) {\n var bone = this.bones[index];\n var parentBone = bone.getParent();\n if (parentBone) {\n bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());\n }\n else {\n if (initialSkinMatrix) {\n bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());\n }\n else {\n bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());\n }\n }\n if (bone._index !== -1) {\n var mappedIndex = bone._index === null ? index : bone._index;\n bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);\n }\n }\n this._identity.copyToArray(targetMatrix, this.bones.length * 16);\n };\n /**\n * Build all resources required to render a skeleton\n */\n Skeleton.prototype.prepare = function () {\n if (!this._isDirty) {\n return;\n }\n if (this.needInitialSkinMatrix) {\n for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {\n var mesh = this._meshesWithPoseMatrix[index];\n var poseMatrix = mesh.getPoseMatrix();\n if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {\n mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));\n }\n if (this._synchronizedWithMesh !== mesh) {\n this._synchronizedWithMesh = mesh;\n // Prepare bones\n for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {\n var bone = this.bones[boneIndex];\n if (!bone.getParent()) {\n var matrix = bone.getBaseMatrix();\n matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);\n bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);\n }\n }\n }\n this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);\n }\n }\n else {\n if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {\n this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));\n }\n this._computeTransformMatrices(this._transformMatrices, null);\n }\n this._isDirty = false;\n this._scene._activeBones.addCount(this.bones.length, false);\n };\n /**\n * Gets the list of animatables currently running for this skeleton\n * @returns an array of animatables\n */\n Skeleton.prototype.getAnimatables = function () {\n if (!this._animatables || this._animatables.length !== this.bones.length) {\n this._animatables = [];\n for (var index = 0; index < this.bones.length; index++) {\n this._animatables.push(this.bones[index]);\n }\n }\n return this._animatables;\n };\n /**\n * Clone the current skeleton\n * @param name defines the name of the new skeleton\n * @param id defines the id of the enw skeleton\n * @returns the new skeleton\n */\n Skeleton.prototype.clone = function (name, id) {\n var result = new Skeleton(name, id || name, this._scene);\n result.needInitialSkinMatrix = this.needInitialSkinMatrix;\n for (var index = 0; index < this.bones.length; index++) {\n var source = this.bones[index];\n var parentBone = null;\n var parent_1 = source.getParent();\n if (parent_1) {\n var parentIndex = this.bones.indexOf(parent_1);\n parentBone = result.bones[parentIndex];\n }\n var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());\n BABYLON.Tools.DeepCopy(source.animations, bone.animations);\n }\n if (this._ranges) {\n result._ranges = {};\n for (var rangeName in this._ranges) {\n var range = this._ranges[rangeName];\n if (range) {\n result._ranges[rangeName] = range.clone();\n }\n }\n }\n this._isDirty = true;\n return result;\n };\n /**\n * Enable animation blending for this skeleton\n * @param blendingSpeed defines the blending speed to apply\n * @see http://doc.babylonjs.com/babylon101/animations#animation-blending\n */\n Skeleton.prototype.enableBlending = function (blendingSpeed) {\n if (blendingSpeed === void 0) { blendingSpeed = 0.01; }\n this.bones.forEach(function (bone) {\n bone.animations.forEach(function (animation) {\n animation.enableBlending = true;\n animation.blendingSpeed = blendingSpeed;\n });\n });\n };\n /**\n * Releases all resources associated with the current skeleton\n */\n Skeleton.prototype.dispose = function () {\n this._meshesWithPoseMatrix = [];\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from scene\n this.getScene().removeSkeleton(this);\n };\n /**\n * Serialize the skeleton in a JSON object\n * @returns a JSON object\n */\n Skeleton.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.id = this.id;\n if (this.dimensionsAtRest) {\n serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();\n }\n serializationObject.bones = [];\n serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;\n for (var index = 0; index < this.bones.length; index++) {\n var bone = this.bones[index];\n var parent_2 = bone.getParent();\n var serializedBone = {\n parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,\n name: bone.name,\n matrix: bone.getBaseMatrix().toArray(),\n rest: bone.getRestPose().toArray()\n };\n serializationObject.bones.push(serializedBone);\n if (bone.length) {\n serializedBone.length = bone.length;\n }\n if (bone.metadata) {\n serializedBone.metadata = bone.metadata;\n }\n if (bone.animations && bone.animations.length > 0) {\n serializedBone.animation = bone.animations[0].serialize();\n }\n serializationObject.ranges = [];\n for (var name in this._ranges) {\n var source = this._ranges[name];\n if (!source) {\n continue;\n }\n var range = {};\n range.name = name;\n range.from = source.from;\n range.to = source.to;\n serializationObject.ranges.push(range);\n }\n }\n return serializationObject;\n };\n /**\n * Creates a new skeleton from serialized data\n * @param parsedSkeleton defines the serialized data\n * @param scene defines the hosting scene\n * @returns a new skeleton\n */\n Skeleton.Parse = function (parsedSkeleton, scene) {\n var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);\n if (parsedSkeleton.dimensionsAtRest) {\n skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);\n }\n skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;\n var index;\n for (index = 0; index < parsedSkeleton.bones.length; index++) {\n var parsedBone = parsedSkeleton.bones[index];\n var parentBone = null;\n if (parsedBone.parentBoneIndex > -1) {\n parentBone = skeleton.bones[parsedBone.parentBoneIndex];\n }\n var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;\n var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);\n if (parsedBone.length) {\n bone.length = parsedBone.length;\n }\n if (parsedBone.metadata) {\n bone.metadata = parsedBone.metadata;\n }\n if (parsedBone.animation) {\n bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));\n }\n }\n // placed after bones, so createAnimationRange can cascade down\n if (parsedSkeleton.ranges) {\n for (index = 0; index < parsedSkeleton.ranges.length; index++) {\n var data = parsedSkeleton.ranges[index];\n skeleton.createAnimationRange(data.name, data.from, data.to);\n }\n }\n return skeleton;\n };\n /**\n * Compute all node absolute transforms\n * @param forceUpdate defines if computation must be done even if cache is up to date\n */\n Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {\n if (forceUpdate === void 0) { forceUpdate = false; }\n var renderId = this._scene.getRenderId();\n if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {\n this.bones[0].computeAbsoluteTransforms();\n this._lastAbsoluteTransformsUpdateId = renderId;\n }\n };\n /**\n * Gets the root pose matrix\n * @returns a matrix\n */\n Skeleton.prototype.getPoseMatrix = function () {\n var poseMatrix = null;\n if (this._meshesWithPoseMatrix.length > 0) {\n poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();\n }\n return poseMatrix;\n };\n /**\n * Sorts bones per internal index\n */\n Skeleton.prototype.sortBones = function () {\n var bones = new Array();\n var visited = new Array(this.bones.length);\n for (var index = 0; index < this.bones.length; index++) {\n this._sortBones(index, bones, visited);\n }\n this.bones = bones;\n };\n Skeleton.prototype._sortBones = function (index, bones, visited) {\n if (visited[index]) {\n return;\n }\n visited[index] = true;\n var bone = this.bones[index];\n if (bone._index === undefined) {\n bone._index = index;\n }\n var parentBone = bone.getParent();\n if (parentBone) {\n this._sortBones(this.bones.indexOf(parentBone), bones, visited);\n }\n bones.push(bone);\n };\n return Skeleton;\n }());\n BABYLON.Skeleton = Skeleton;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.skeleton.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n ;\n /**\n * This groups tools to convert HDR texture to native colors array.\n */\n var HDRTools = /** @class */ (function () {\n function HDRTools() {\n }\n HDRTools.Ldexp = function (mantissa, exponent) {\n if (exponent > 1023) {\n return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);\n }\n if (exponent < -1074) {\n return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);\n }\n return mantissa * Math.pow(2, exponent);\n };\n HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {\n if (exponent > 0) { /*nonzero pixel*/\n exponent = this.Ldexp(1.0, exponent - (128 + 8));\n float32array[index + 0] = red * exponent;\n float32array[index + 1] = green * exponent;\n float32array[index + 2] = blue * exponent;\n }\n else {\n float32array[index + 0] = 0;\n float32array[index + 1] = 0;\n float32array[index + 2] = 0;\n }\n };\n HDRTools.readStringLine = function (uint8array, startIndex) {\n var line = \"\";\n var character = \"\";\n for (var i = startIndex; i < uint8array.length - startIndex; i++) {\n character = String.fromCharCode(uint8array[i]);\n if (character == \"\\n\") {\n break;\n }\n line += character;\n }\n return line;\n };\n /**\n * Reads header information from an RGBE texture stored in a native array.\n * More information on this format are available here:\n * https://en.wikipedia.org/wiki/RGBE_image_format\n *\n * @param uint8array The binary file stored in native array.\n * @return The header information.\n */\n HDRTools.RGBE_ReadHeader = function (uint8array) {\n var height = 0;\n var width = 0;\n var line = this.readStringLine(uint8array, 0);\n if (line[0] != '#' || line[1] != '?') {\n throw \"Bad HDR Format.\";\n }\n var endOfHeader = false;\n var findFormat = false;\n var lineIndex = 0;\n do {\n lineIndex += (line.length + 1);\n line = this.readStringLine(uint8array, lineIndex);\n if (line == \"FORMAT=32-bit_rle_rgbe\") {\n findFormat = true;\n }\n else if (line.length == 0) {\n endOfHeader = true;\n }\n } while (!endOfHeader);\n if (!findFormat) {\n throw \"HDR Bad header format, unsupported FORMAT\";\n }\n lineIndex += (line.length + 1);\n line = this.readStringLine(uint8array, lineIndex);\n var sizeRegexp = /^\\-Y (.*) \\+X (.*)$/g;\n var match = sizeRegexp.exec(line);\n // TODO. Support +Y and -X if needed.\n if (!match || match.length < 3) {\n throw \"HDR Bad header format, no size\";\n }\n width = parseInt(match[2]);\n height = parseInt(match[1]);\n if (width < 8 || width > 0x7fff) {\n throw \"HDR Bad header format, unsupported size\";\n }\n lineIndex += (line.length + 1);\n return {\n height: height,\n width: width,\n dataPosition: lineIndex\n };\n };\n /**\n * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.\n * This RGBE texture needs to store the information as a panorama.\n *\n * More information on this format are available here:\n * https://en.wikipedia.org/wiki/RGBE_image_format\n *\n * @param buffer The binary file stored in an array buffer.\n * @param size The expected size of the extracted cubemap.\n * @return The Cube Map information.\n */\n HDRTools.GetCubeMapTextureData = function (buffer, size) {\n var uint8array = new Uint8Array(buffer);\n var hdrInfo = this.RGBE_ReadHeader(uint8array);\n var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);\n var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);\n return cubeMapData;\n };\n /**\n * Returns the pixels data extracted from an RGBE texture.\n * This pixels will be stored left to right up to down in the R G B order in one array.\n *\n * More information on this format are available here:\n * https://en.wikipedia.org/wiki/RGBE_image_format\n *\n * @param uint8array The binary file stored in an array buffer.\n * @param hdrInfo The header information of the file.\n * @return The pixels data in RGB right to left up to down order.\n */\n HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {\n // Keep for multi format supports.\n return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);\n };\n HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {\n var num_scanlines = hdrInfo.height;\n var scanline_width = hdrInfo.width;\n var a, b, c, d, count;\n var dataIndex = hdrInfo.dataPosition;\n var index = 0, endIndex = 0, i = 0;\n var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E\n var scanLineArray = new Uint8Array(scanLineArrayBuffer);\n // 3 channels of 4 bytes per pixel in float.\n var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);\n var resultArray = new Float32Array(resultBuffer);\n // read in each successive scanline\n while (num_scanlines > 0) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n c = uint8array[dataIndex++];\n d = uint8array[dataIndex++];\n if (a != 2 || b != 2 || (c & 0x80)) {\n // this file is not run length encoded\n throw \"HDR Bad header format, not RLE\";\n }\n if (((c << 8) | d) != scanline_width) {\n throw \"HDR Bad header format, wrong scan line width\";\n }\n index = 0;\n // read each of the four channels for the scanline into the buffer\n for (i = 0; i < 4; i++) {\n endIndex = (i + 1) * scanline_width;\n while (index < endIndex) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n if (a > 128) {\n // a run of the same value\n count = a - 128;\n if ((count == 0) || (count > endIndex - index)) {\n throw \"HDR Bad Format, bad scanline data (run)\";\n }\n while (count-- > 0) {\n scanLineArray[index++] = b;\n }\n }\n else {\n // a non-run\n count = a;\n if ((count == 0) || (count > endIndex - index)) {\n throw \"HDR Bad Format, bad scanline data (non-run)\";\n }\n scanLineArray[index++] = b;\n if (--count > 0) {\n for (var j = 0; j < count; j++) {\n scanLineArray[index++] = uint8array[dataIndex++];\n }\n }\n }\n }\n }\n // now convert data from buffer into floats\n for (i = 0; i < scanline_width; i++) {\n a = scanLineArray[i];\n b = scanLineArray[i + scanline_width];\n c = scanLineArray[i + 2 * scanline_width];\n d = scanLineArray[i + 3 * scanline_width];\n this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);\n }\n num_scanlines--;\n }\n return resultArray;\n };\n return HDRTools;\n }());\n BABYLON.HDRTools = HDRTools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.hdr.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This represents a texture coming from an HDR input.\n *\n * The only supported format is currently panorama picture stored in RGBE format.\n * Example of such files can be found on HDRLib: http://hdrlib.com/\n */\n var HDRCubeTexture = /** @class */ (function (_super) {\n __extends(HDRCubeTexture, _super);\n /**\n * Instantiates an HDRTexture from the following parameters.\n *\n * @param url The location of the HDR raw data (Panorama stored in RGBE format)\n * @param scene The scene the texture will be used in\n * @param size The cubemap desired size (the more it increases the longer the generation will be)\n * @param noMipmap Forces to not generate the mipmap if true\n * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process\n * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)\n * @param reserved Reserved flag for internal use.\n */\n function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {\n if (noMipmap === void 0) { noMipmap = false; }\n if (generateHarmonics === void 0) { generateHarmonics = true; }\n if (gammaSpace === void 0) { gammaSpace = false; }\n if (reserved === void 0) { reserved = false; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n var _this = _super.call(this, scene) || this;\n _this._generateHarmonics = true;\n _this._onLoad = null;\n _this._onError = null;\n /**\n * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.\n */\n _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;\n _this._isBlocking = true;\n _this._rotationY = 0;\n /**\n * Gets or sets the center of the bounding box associated with the cube texture\n * It must define where the camera used to render the texture was set\n */\n _this.boundingBoxPosition = BABYLON.Vector3.Zero();\n if (!url) {\n return _this;\n }\n _this.name = url;\n _this.url = url;\n _this.hasAlpha = false;\n _this.isCube = true;\n _this._textureMatrix = BABYLON.Matrix.Identity();\n _this._onLoad = onLoad;\n _this._onError = onError;\n _this.gammaSpace = gammaSpace;\n _this._noMipmap = noMipmap;\n _this._size = size;\n _this._texture = _this._getFromCache(url, _this._noMipmap);\n if (!_this._texture) {\n if (!scene.useDelayedTextureLoading) {\n _this.loadTexture();\n }\n else {\n _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;\n }\n }\n return _this;\n }\n Object.defineProperty(HDRCubeTexture.prototype, \"isBlocking\", {\n /**\n * Gets wether or not the texture is blocking during loading.\n */\n get: function () {\n return this._isBlocking;\n },\n /**\n * Sets wether or not the texture is blocking during loading.\n */\n set: function (value) {\n this._isBlocking = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(HDRCubeTexture.prototype, \"rotationY\", {\n /**\n * Gets texture matrix rotation angle around Y axis radians.\n */\n get: function () {\n return this._rotationY;\n },\n /**\n * Sets texture matrix rotation angle around Y axis in radians.\n */\n set: function (value) {\n this._rotationY = value;\n this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(HDRCubeTexture.prototype, \"boundingBoxSize\", {\n get: function () {\n return this._boundingBoxSize;\n },\n /**\n * Gets or sets the size of the bounding box associated with the cube texture\n * When defined, the cubemap will switch to local mode\n * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity\n * @example https://www.babylonjs-playground.com/#RNASML\n */\n set: function (value) {\n if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {\n return;\n }\n this._boundingBoxSize = value;\n var scene = this.getScene();\n if (scene) {\n scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Occurs when the file is raw .hdr file.\n */\n HDRCubeTexture.prototype.loadTexture = function () {\n var _this = this;\n var callback = function (buffer) {\n _this.lodGenerationOffset = 0.0;\n _this.lodGenerationScale = 0.8;\n var scene = _this.getScene();\n if (!scene) {\n return null;\n }\n // Extract the raw linear data.\n var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);\n // Generate harmonics if needed.\n if (_this._generateHarmonics) {\n var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);\n _this.sphericalPolynomial = sphericalPolynomial;\n }\n var results = [];\n var byteArray = null;\n // Push each faces.\n for (var j = 0; j < 6; j++) {\n // Create uintarray fallback.\n if (!scene.getEngine().getCaps().textureFloat) {\n // 3 channels of 1 bytes per pixel in bytes.\n var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);\n byteArray = new Uint8Array(byteBuffer);\n }\n var dataFace = (data[HDRCubeTexture._facesMapping[j]]);\n // If special cases.\n if (_this.gammaSpace || byteArray) {\n for (var i = 0; i < _this._size * _this._size; i++) {\n // Put in gamma space if requested.\n if (_this.gammaSpace) {\n dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);\n dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);\n dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);\n }\n // Convert to int texture for fallback.\n if (byteArray) {\n var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);\n var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);\n var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);\n // May use luminance instead if the result is not accurate.\n var max = Math.max(Math.max(r, g), b);\n if (max > 255) {\n var scale = 255 / max;\n r *= scale;\n g *= scale;\n b *= scale;\n }\n byteArray[(i * 3) + 0] = r;\n byteArray[(i * 3) + 1] = g;\n byteArray[(i * 3) + 2] = b;\n }\n }\n }\n if (byteArray) {\n results.push(byteArray);\n }\n else {\n results.push(dataFace);\n }\n }\n return results;\n };\n var scene = this.getScene();\n if (scene) {\n this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);\n }\n };\n HDRCubeTexture.prototype.clone = function () {\n var scene = this.getScene();\n if (!scene) {\n return this;\n }\n var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);\n // Base texture\n newTexture.level = this.level;\n newTexture.wrapU = this.wrapU;\n newTexture.wrapV = this.wrapV;\n newTexture.coordinatesIndex = this.coordinatesIndex;\n newTexture.coordinatesMode = this.coordinatesMode;\n return newTexture;\n };\n // Methods\n HDRCubeTexture.prototype.delayLoad = function () {\n if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {\n return;\n }\n this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;\n this._texture = this._getFromCache(this.url, this._noMipmap);\n if (!this._texture) {\n this.loadTexture();\n }\n };\n HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {\n return this._textureMatrix;\n };\n HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {\n this._textureMatrix = value;\n };\n HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {\n var texture = null;\n if (parsedTexture.name && !parsedTexture.isRenderTarget) {\n texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);\n texture.name = parsedTexture.name;\n texture.hasAlpha = parsedTexture.hasAlpha;\n texture.level = parsedTexture.level;\n texture.coordinatesMode = parsedTexture.coordinatesMode;\n texture.isBlocking = parsedTexture.isBlocking;\n }\n if (texture) {\n if (parsedTexture.boundingBoxPosition) {\n texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);\n }\n if (parsedTexture.boundingBoxSize) {\n texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);\n }\n if (parsedTexture.rotationY) {\n texture.rotationY = parsedTexture.rotationY;\n }\n }\n return texture;\n };\n HDRCubeTexture.prototype.serialize = function () {\n if (!this.name) {\n return null;\n }\n var serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.hasAlpha = this.hasAlpha;\n serializationObject.isCube = true;\n serializationObject.level = this.level;\n serializationObject.size = this._size;\n serializationObject.coordinatesMode = this.coordinatesMode;\n serializationObject.useInGammaSpace = this.gammaSpace;\n serializationObject.generateHarmonics = this._generateHarmonics;\n serializationObject.customType = \"BABYLON.HDRCubeTexture\";\n serializationObject.noMipmap = this._noMipmap;\n serializationObject.isBlocking = this._isBlocking;\n serializationObject.rotationY = this._rotationY;\n return serializationObject;\n };\n HDRCubeTexture._facesMapping = [\n \"right\",\n \"left\",\n \"up\",\n \"down\",\n \"front\",\n \"back\"\n ];\n return HDRCubeTexture;\n }(BABYLON.BaseTexture));\n BABYLON.HDRCubeTexture = HDRCubeTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.hdrCubeTexture.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.\n */\n var PanoramaToCubeMapTools = /** @class */ (function () {\n function PanoramaToCubeMapTools() {\n }\n /**\n * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).\n *\n * @param float32Array The source data.\n * @param inputWidth The width of the input panorama.\n * @param inputhHeight The height of the input panorama.\n * @param size The willing size of the generated cubemap (each faces will be size * size pixels)\n * @return The cubemap data\n */\n PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {\n if (!float32Array) {\n throw \"ConvertPanoramaToCubemap: input cannot be null\";\n }\n if (float32Array.length != inputWidth * inputHeight * 3) {\n throw \"ConvertPanoramaToCubemap: input size is wrong\";\n }\n var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);\n var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);\n var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);\n var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);\n var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);\n var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);\n return {\n front: textureFront,\n back: textureBack,\n left: textureLeft,\n right: textureRight,\n up: textureUp,\n down: textureDown,\n size: size,\n type: BABYLON.Engine.TEXTURETYPE_FLOAT,\n format: BABYLON.Engine.TEXTUREFORMAT_RGB,\n gammaSpace: false,\n };\n };\n PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {\n var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);\n var textureArray = new Float32Array(buffer);\n var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);\n var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);\n var dy = 1 / texSize;\n var fy = 0;\n for (var y = 0; y < texSize; y++) {\n var xv1 = faceData[0];\n var xv2 = faceData[2];\n for (var x = 0; x < texSize; x++) {\n var v = xv2.subtract(xv1).scale(fy).add(xv1);\n v.normalize();\n var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);\n // 3 channels per pixels\n textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;\n textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;\n textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;\n xv1 = xv1.add(rotDX1);\n xv2 = xv2.add(rotDX2);\n }\n fy += dy;\n }\n return textureArray;\n };\n PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {\n var theta = Math.atan2(vDir.z, vDir.x);\n var phi = Math.acos(vDir.y);\n while (theta < -Math.PI)\n theta += 2 * Math.PI;\n while (theta > Math.PI)\n theta -= 2 * Math.PI;\n var dx = theta / Math.PI;\n var dy = phi / Math.PI;\n // recenter.\n dx = dx * 0.5 + 0.5;\n var px = Math.round(dx * inputWidth);\n if (px < 0)\n px = 0;\n else if (px >= inputWidth)\n px = inputWidth - 1;\n var py = Math.round(dy * inputHeight);\n if (py < 0)\n py = 0;\n else if (py >= inputHeight)\n py = inputHeight - 1;\n var inputY = (inputHeight - py - 1);\n var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];\n var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];\n var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];\n return {\n r: r,\n g: g,\n b: b\n };\n };\n PanoramaToCubeMapTools.FACE_FRONT = [\n new BABYLON.Vector3(-1.0, -1.0, -1.0),\n new BABYLON.Vector3(1.0, -1.0, -1.0),\n new BABYLON.Vector3(-1.0, 1.0, -1.0),\n new BABYLON.Vector3(1.0, 1.0, -1.0)\n ];\n PanoramaToCubeMapTools.FACE_BACK = [\n new BABYLON.Vector3(1.0, -1.0, 1.0),\n new BABYLON.Vector3(-1.0, -1.0, 1.0),\n new BABYLON.Vector3(1.0, 1.0, 1.0),\n new BABYLON.Vector3(-1.0, 1.0, 1.0)\n ];\n PanoramaToCubeMapTools.FACE_RIGHT = [\n new BABYLON.Vector3(1.0, -1.0, -1.0),\n new BABYLON.Vector3(1.0, -1.0, 1.0),\n new BABYLON.Vector3(1.0, 1.0, -1.0),\n new BABYLON.Vector3(1.0, 1.0, 1.0)\n ];\n PanoramaToCubeMapTools.FACE_LEFT = [\n new BABYLON.Vector3(-1.0, -1.0, 1.0),\n new BABYLON.Vector3(-1.0, -1.0, -1.0),\n new BABYLON.Vector3(-1.0, 1.0, 1.0),\n new BABYLON.Vector3(-1.0, 1.0, -1.0)\n ];\n PanoramaToCubeMapTools.FACE_DOWN = [\n new BABYLON.Vector3(-1.0, 1.0, -1.0),\n new BABYLON.Vector3(1.0, 1.0, -1.0),\n new BABYLON.Vector3(-1.0, 1.0, 1.0),\n new BABYLON.Vector3(1.0, 1.0, 1.0)\n ];\n PanoramaToCubeMapTools.FACE_UP = [\n new BABYLON.Vector3(-1.0, -1.0, 1.0),\n new BABYLON.Vector3(1.0, -1.0, 1.0),\n new BABYLON.Vector3(-1.0, -1.0, -1.0),\n new BABYLON.Vector3(1.0, -1.0, -1.0)\n ];\n return PanoramaToCubeMapTools;\n }());\n BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.panoramaToCubemap.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var IndexedVector2 = /** @class */ (function (_super) {\n __extends(IndexedVector2, _super);\n function IndexedVector2(original, index) {\n var _this = _super.call(this, original.x, original.y) || this;\n _this.index = index;\n return _this;\n }\n return IndexedVector2;\n }(BABYLON.Vector2));\n var PolygonPoints = /** @class */ (function () {\n function PolygonPoints() {\n this.elements = new Array();\n }\n PolygonPoints.prototype.add = function (originalPoints) {\n var _this = this;\n var result = new Array();\n originalPoints.forEach(function (point) {\n if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {\n var newPoint = new IndexedVector2(point, _this.elements.length);\n result.push(newPoint);\n _this.elements.push(newPoint);\n }\n });\n return result;\n };\n PolygonPoints.prototype.computeBounds = function () {\n var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);\n var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);\n this.elements.forEach(function (point) {\n // x\n if (point.x < lmin.x) {\n lmin.x = point.x;\n }\n else if (point.x > lmax.x) {\n lmax.x = point.x;\n }\n // y\n if (point.y < lmin.y) {\n lmin.y = point.y;\n }\n else if (point.y > lmax.y) {\n lmax.y = point.y;\n }\n });\n return {\n min: lmin,\n max: lmax,\n width: lmax.x - lmin.x,\n height: lmax.y - lmin.y\n };\n };\n return PolygonPoints;\n }());\n var Polygon = /** @class */ (function () {\n function Polygon() {\n }\n Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {\n return [\n new BABYLON.Vector2(xmin, ymin),\n new BABYLON.Vector2(xmax, ymin),\n new BABYLON.Vector2(xmax, ymax),\n new BABYLON.Vector2(xmin, ymax)\n ];\n };\n Polygon.Circle = function (radius, cx, cy, numberOfSides) {\n if (cx === void 0) { cx = 0; }\n if (cy === void 0) { cy = 0; }\n if (numberOfSides === void 0) { numberOfSides = 32; }\n var result = new Array();\n var angle = 0;\n var increment = (Math.PI * 2) / numberOfSides;\n for (var i = 0; i < numberOfSides; i++) {\n result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));\n angle -= increment;\n }\n return result;\n };\n Polygon.Parse = function (input) {\n var floats = input.split(/[^-+eE\\.\\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });\n var i, result = [];\n for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {\n result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));\n }\n return result;\n };\n Polygon.StartingAt = function (x, y) {\n return BABYLON.Path2.StartingAt(x, y);\n };\n return Polygon;\n }());\n BABYLON.Polygon = Polygon;\n var PolygonMeshBuilder = /** @class */ (function () {\n function PolygonMeshBuilder(name, contours, scene) {\n this._points = new PolygonPoints();\n this._outlinepoints = new PolygonPoints();\n this._holes = new Array();\n this._epoints = new Array();\n this._eholes = new Array();\n this._name = name;\n this._scene = scene;\n var points;\n if (contours instanceof BABYLON.Path2) {\n points = contours.getPoints();\n }\n else {\n points = contours;\n }\n this._addToepoint(points);\n this._points.add(points);\n this._outlinepoints.add(points);\n if (typeof earcut === 'undefined') {\n BABYLON.Tools.Warn(\"Earcut was not found, the polygon will not be built.\");\n }\n }\n PolygonMeshBuilder.prototype._addToepoint = function (points) {\n for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {\n var p = points_1[_i];\n this._epoints.push(p.x, p.y);\n }\n };\n PolygonMeshBuilder.prototype.addHole = function (hole) {\n this._points.add(hole);\n var holepoints = new PolygonPoints();\n holepoints.add(hole);\n this._holes.push(holepoints);\n this._eholes.push(this._epoints.length / 2);\n this._addToepoint(hole);\n return this;\n };\n PolygonMeshBuilder.prototype.build = function (updatable, depth) {\n var _this = this;\n if (updatable === void 0) { updatable = false; }\n if (depth === void 0) { depth = 0; }\n var result = new BABYLON.Mesh(this._name, this._scene);\n var normals = new Array();\n var positions = new Array();\n var uvs = new Array();\n var bounds = this._points.computeBounds();\n this._points.elements.forEach(function (p) {\n normals.push(0, 1.0, 0);\n positions.push(p.x, 0, p.y);\n uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);\n });\n var indices = new Array();\n var res = earcut(this._epoints, this._eholes, 2);\n for (var i = 0; i < res.length; i++) {\n indices.push(res[i]);\n }\n if (depth > 0) {\n var positionscount = (positions.length / 3); //get the current pointcount\n this._points.elements.forEach(function (p) {\n normals.push(0, -1.0, 0);\n positions.push(p.x, -depth, p.y);\n uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);\n });\n var totalCount = indices.length;\n for (var i = 0; i < totalCount; i += 3) {\n var i0 = indices[i + 0];\n var i1 = indices[i + 1];\n var i2 = indices[i + 2];\n indices.push(i2 + positionscount);\n indices.push(i1 + positionscount);\n indices.push(i0 + positionscount);\n }\n //Add the sides\n this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);\n this._holes.forEach(function (hole) {\n _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);\n });\n }\n result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);\n result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);\n result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);\n result.setIndices(indices);\n return result;\n };\n PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {\n var StartIndex = positions.length / 3;\n var ulength = 0;\n for (var i = 0; i < points.elements.length; i++) {\n var p = points.elements[i];\n var p1;\n if ((i + 1) > points.elements.length - 1) {\n p1 = points.elements[0];\n }\n else {\n p1 = points.elements[i + 1];\n }\n positions.push(p.x, 0, p.y);\n positions.push(p.x, -depth, p.y);\n positions.push(p1.x, 0, p1.y);\n positions.push(p1.x, -depth, p1.y);\n var v1 = new BABYLON.Vector3(p.x, 0, p.y);\n var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);\n var v3 = v2.subtract(v1);\n var v4 = new BABYLON.Vector3(0, 1, 0);\n var vn = BABYLON.Vector3.Cross(v3, v4);\n vn = vn.normalize();\n uvs.push(ulength / bounds.width, 0);\n uvs.push(ulength / bounds.width, 1);\n ulength += v3.length();\n uvs.push((ulength / bounds.width), 0);\n uvs.push((ulength / bounds.width), 1);\n if (!flip) {\n normals.push(-vn.x, -vn.y, -vn.z);\n normals.push(-vn.x, -vn.y, -vn.z);\n normals.push(-vn.x, -vn.y, -vn.z);\n normals.push(-vn.x, -vn.y, -vn.z);\n indices.push(StartIndex);\n indices.push(StartIndex + 1);\n indices.push(StartIndex + 2);\n indices.push(StartIndex + 1);\n indices.push(StartIndex + 3);\n indices.push(StartIndex + 2);\n }\n else {\n normals.push(vn.x, vn.y, vn.z);\n normals.push(vn.x, vn.y, vn.z);\n normals.push(vn.x, vn.y, vn.z);\n normals.push(vn.x, vn.y, vn.z);\n indices.push(StartIndex);\n indices.push(StartIndex + 2);\n indices.push(StartIndex + 1);\n indices.push(StartIndex + 1);\n indices.push(StartIndex + 2);\n indices.push(StartIndex + 3);\n }\n StartIndex += 4;\n }\n ;\n };\n return PolygonMeshBuilder;\n }());\n BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.polygonMesh.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n // Unique ID when we import meshes from Babylon to CSG\n var currentCSGMeshId = 0;\n // # class Vertex\n // Represents a vertex of a polygon. Use your own vertex class instead of this\n // one to provide additional features like texture coordinates and vertex\n // colors. Custom vertex classes need to provide a `pos` property and `clone()`,\n // `flip()`, and `interpolate()` methods that behave analogous to the ones\n // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience\n // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`\n // is not used anywhere else. \n // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes\n var Vertex = /** @class */ (function () {\n function Vertex(pos, normal, uv) {\n this.pos = pos;\n this.normal = normal;\n this.uv = uv;\n }\n Vertex.prototype.clone = function () {\n return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());\n };\n // Invert all orientation-specific data (e.g. vertex normal). Called when the\n // orientation of a polygon is flipped.\n Vertex.prototype.flip = function () {\n this.normal = this.normal.scale(-1);\n };\n // Create a new vertex between this vertex and `other` by linearly\n // interpolating all properties using a parameter of `t`. Subclasses should\n // override this to interpolate additional properties.\n Vertex.prototype.interpolate = function (other, t) {\n return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));\n };\n return Vertex;\n }());\n // # class Plane\n // Represents a plane in 3D space.\n var Plane = /** @class */ (function () {\n function Plane(normal, w) {\n this.normal = normal;\n this.w = w;\n }\n Plane.FromPoints = function (a, b, c) {\n var v0 = c.subtract(a);\n var v1 = b.subtract(a);\n if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {\n return null;\n }\n var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));\n return new Plane(n, BABYLON.Vector3.Dot(n, a));\n };\n Plane.prototype.clone = function () {\n return new Plane(this.normal.clone(), this.w);\n };\n Plane.prototype.flip = function () {\n this.normal.scaleInPlace(-1);\n this.w = -this.w;\n };\n // Split `polygon` by this plane if needed, then put the polygon or polygon\n // fragments in the appropriate lists. Coplanar polygons go into either\n // `coplanarFront` or `coplanarBack` depending on their orientation with\n // respect to this plane. Polygons in front or in back of this plane go into\n // either `front` or `back`.\n Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {\n var COPLANAR = 0;\n var FRONT = 1;\n var BACK = 2;\n var SPANNING = 3;\n // Classify each point as well as the entire polygon into one of the above\n // four classes.\n var polygonType = 0;\n var types = [];\n var i;\n var t;\n for (i = 0; i < polygon.vertices.length; i++) {\n t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;\n var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;\n polygonType |= type;\n types.push(type);\n }\n // Put the polygon in the correct list, splitting it when necessary.\n switch (polygonType) {\n case COPLANAR:\n (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);\n break;\n case FRONT:\n front.push(polygon);\n break;\n case BACK:\n back.push(polygon);\n break;\n case SPANNING:\n var f = [], b = [];\n for (i = 0; i < polygon.vertices.length; i++) {\n var j = (i + 1) % polygon.vertices.length;\n var ti = types[i], tj = types[j];\n var vi = polygon.vertices[i], vj = polygon.vertices[j];\n if (ti !== BACK)\n f.push(vi);\n if (ti !== FRONT)\n b.push(ti !== BACK ? vi.clone() : vi);\n if ((ti | tj) === SPANNING) {\n t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));\n var v = vi.interpolate(vj, t);\n f.push(v);\n b.push(v.clone());\n }\n }\n var poly;\n if (f.length >= 3) {\n poly = new Polygon(f, polygon.shared);\n if (poly.plane)\n front.push(poly);\n }\n if (b.length >= 3) {\n poly = new Polygon(b, polygon.shared);\n if (poly.plane)\n back.push(poly);\n }\n break;\n }\n };\n // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a\n // point is on the plane.\n Plane.EPSILON = 1e-5;\n return Plane;\n }());\n // # class Polygon\n // Represents a convex polygon. The vertices used to initialize a polygon must\n // be coplanar and form a convex loop.\n // \n // Each convex polygon has a `shared` property, which is shared between all\n // polygons that are clones of each other or were split from the same polygon.\n // This can be used to define per-polygon properties (such as surface color).\n var Polygon = /** @class */ (function () {\n function Polygon(vertices, shared) {\n this.vertices = vertices;\n this.shared = shared;\n this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);\n }\n Polygon.prototype.clone = function () {\n var vertices = this.vertices.map(function (v) { return v.clone(); });\n return new Polygon(vertices, this.shared);\n };\n Polygon.prototype.flip = function () {\n this.vertices.reverse().map(function (v) { v.flip(); });\n this.plane.flip();\n };\n return Polygon;\n }());\n // # class Node\n // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons\n // by picking a polygon to split along. That polygon (and all other coplanar\n // polygons) are added directly to that node and the other polygons are added to\n // the front and/or back subtrees. This is not a leafy BSP tree since there is\n // no distinction between internal and leaf nodes.\n var Node = /** @class */ (function () {\n function Node(polygons) {\n this.plane = null;\n this.front = null;\n this.back = null;\n this.polygons = new Array();\n if (polygons) {\n this.build(polygons);\n }\n }\n Node.prototype.clone = function () {\n var node = new Node();\n node.plane = this.plane && this.plane.clone();\n node.front = this.front && this.front.clone();\n node.back = this.back && this.back.clone();\n node.polygons = this.polygons.map(function (p) { return p.clone(); });\n return node;\n };\n // Convert solid space to empty space and empty space to solid space.\n Node.prototype.invert = function () {\n for (var i = 0; i < this.polygons.length; i++) {\n this.polygons[i].flip();\n }\n if (this.plane) {\n this.plane.flip();\n }\n if (this.front) {\n this.front.invert();\n }\n if (this.back) {\n this.back.invert();\n }\n var temp = this.front;\n this.front = this.back;\n this.back = temp;\n };\n // Recursively remove all polygons in `polygons` that are inside this BSP\n // tree.\n Node.prototype.clipPolygons = function (polygons) {\n if (!this.plane)\n return polygons.slice();\n var front = new Array(), back = new Array();\n for (var i = 0; i < polygons.length; i++) {\n this.plane.splitPolygon(polygons[i], front, back, front, back);\n }\n if (this.front) {\n front = this.front.clipPolygons(front);\n }\n if (this.back) {\n back = this.back.clipPolygons(back);\n }\n else {\n back = [];\n }\n return front.concat(back);\n };\n // Remove all polygons in this BSP tree that are inside the other BSP tree\n // `bsp`.\n Node.prototype.clipTo = function (bsp) {\n this.polygons = bsp.clipPolygons(this.polygons);\n if (this.front)\n this.front.clipTo(bsp);\n if (this.back)\n this.back.clipTo(bsp);\n };\n // Return a list of all polygons in this BSP tree.\n Node.prototype.allPolygons = function () {\n var polygons = this.polygons.slice();\n if (this.front)\n polygons = polygons.concat(this.front.allPolygons());\n if (this.back)\n polygons = polygons.concat(this.back.allPolygons());\n return polygons;\n };\n // Build a BSP tree out of `polygons`. When called on an existing tree, the\n // new polygons are filtered down to the bottom of the tree and become new\n // nodes there. Each set of polygons is partitioned using the first polygon\n // (no heuristic is used to pick a good split).\n Node.prototype.build = function (polygons) {\n if (!polygons.length)\n return;\n if (!this.plane)\n this.plane = polygons[0].plane.clone();\n var front = new Array(), back = new Array();\n for (var i = 0; i < polygons.length; i++) {\n this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);\n }\n if (front.length) {\n if (!this.front)\n this.front = new Node();\n this.front.build(front);\n }\n if (back.length) {\n if (!this.back)\n this.back = new Node();\n this.back.build(back);\n }\n };\n return Node;\n }());\n var CSG = /** @class */ (function () {\n function CSG() {\n this.polygons = new Array();\n }\n // Convert BABYLON.Mesh to BABYLON.CSG\n CSG.FromMesh = function (mesh) {\n var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;\n var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;\n if (mesh instanceof BABYLON.Mesh) {\n mesh.computeWorldMatrix(true);\n matrix = mesh.getWorldMatrix();\n meshPosition = mesh.position.clone();\n meshRotation = mesh.rotation.clone();\n if (mesh.rotationQuaternion) {\n meshRotationQuaternion = mesh.rotationQuaternion.clone();\n }\n meshScaling = mesh.scaling.clone();\n }\n else {\n throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';\n }\n var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);\n var subMeshes = mesh.subMeshes;\n for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {\n for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {\n vertices = [];\n for (var j = 0; j < 3; j++) {\n var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);\n uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);\n var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);\n position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);\n normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);\n vertex = new Vertex(position, normal, uv);\n vertices.push(vertex);\n }\n polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });\n // To handle the case of degenerated triangle\n // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated\n if (polygon.plane)\n polygons.push(polygon);\n }\n }\n var csg = CSG.FromPolygons(polygons);\n csg.matrix = matrix;\n csg.position = meshPosition;\n csg.rotation = meshRotation;\n csg.scaling = meshScaling;\n csg.rotationQuaternion = meshRotationQuaternion;\n currentCSGMeshId++;\n return csg;\n };\n // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.\n CSG.FromPolygons = function (polygons) {\n var csg = new CSG();\n csg.polygons = polygons;\n return csg;\n };\n CSG.prototype.clone = function () {\n var csg = new CSG();\n csg.polygons = this.polygons.map(function (p) { return p.clone(); });\n csg.copyTransformAttributes(this);\n return csg;\n };\n CSG.prototype.union = function (csg) {\n var a = new Node(this.clone().polygons);\n var b = new Node(csg.clone().polygons);\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);\n };\n CSG.prototype.unionInPlace = function (csg) {\n var a = new Node(this.polygons);\n var b = new Node(csg.polygons);\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n this.polygons = a.allPolygons();\n };\n CSG.prototype.subtract = function (csg) {\n var a = new Node(this.clone().polygons);\n var b = new Node(csg.clone().polygons);\n a.invert();\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n a.invert();\n return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);\n };\n CSG.prototype.subtractInPlace = function (csg) {\n var a = new Node(this.polygons);\n var b = new Node(csg.polygons);\n a.invert();\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n a.invert();\n this.polygons = a.allPolygons();\n };\n CSG.prototype.intersect = function (csg) {\n var a = new Node(this.clone().polygons);\n var b = new Node(csg.clone().polygons);\n a.invert();\n b.clipTo(a);\n b.invert();\n a.clipTo(b);\n b.clipTo(a);\n a.build(b.allPolygons());\n a.invert();\n return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);\n };\n CSG.prototype.intersectInPlace = function (csg) {\n var a = new Node(this.polygons);\n var b = new Node(csg.polygons);\n a.invert();\n b.clipTo(a);\n b.invert();\n a.clipTo(b);\n b.clipTo(a);\n a.build(b.allPolygons());\n a.invert();\n this.polygons = a.allPolygons();\n };\n // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is\n // not modified.\n CSG.prototype.inverse = function () {\n var csg = this.clone();\n csg.inverseInPlace();\n return csg;\n };\n CSG.prototype.inverseInPlace = function () {\n this.polygons.map(function (p) { p.flip(); });\n };\n // This is used to keep meshes transformations so they can be restored\n // when we build back a Babylon Mesh\n // NB : All CSG operations are performed in world coordinates\n CSG.prototype.copyTransformAttributes = function (csg) {\n this.matrix = csg.matrix;\n this.position = csg.position;\n this.rotation = csg.rotation;\n this.scaling = csg.scaling;\n this.rotationQuaternion = csg.rotationQuaternion;\n return this;\n };\n // Build Raw mesh from CSG\n // Coordinates here are in world space\n CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {\n var matrix = this.matrix.clone();\n matrix.invert();\n var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;\n if (keepSubMeshes) {\n // Sort Polygons, since subMeshes are indices range\n polygons.sort(function (a, b) {\n if (a.shared.meshId === b.shared.meshId) {\n return a.shared.subMeshId - b.shared.subMeshId;\n }\n else {\n return a.shared.meshId - b.shared.meshId;\n }\n });\n }\n for (var i = 0, il = polygons.length; i < il; i++) {\n polygon = polygons[i];\n // Building SubMeshes\n if (!subMesh_dict[polygon.shared.meshId]) {\n subMesh_dict[polygon.shared.meshId] = {};\n }\n if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {\n subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {\n indexStart: +Infinity,\n indexEnd: -Infinity,\n materialIndex: polygon.shared.materialIndex\n };\n }\n subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];\n for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {\n polygonIndices[0] = 0;\n polygonIndices[1] = j - 1;\n polygonIndices[2] = j;\n for (var k = 0; k < 3; k++) {\n vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);\n normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);\n uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);\n var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);\n var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);\n vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];\n // Check if 2 points can be merged\n if (!(typeof vertex_idx !== 'undefined' &&\n normals[vertex_idx * 3] === localNormal.x &&\n normals[vertex_idx * 3 + 1] === localNormal.y &&\n normals[vertex_idx * 3 + 2] === localNormal.z &&\n uvs[vertex_idx * 2] === uv.x &&\n uvs[vertex_idx * 2 + 1] === uv.y)) {\n vertices.push(localVertex.x, localVertex.y, localVertex.z);\n uvs.push(uv.x, uv.y);\n normals.push(normal.x, normal.y, normal.z);\n vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;\n }\n indices.push(vertex_idx);\n subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);\n subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);\n currentIndex++;\n }\n }\n }\n mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);\n mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);\n mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);\n mesh.setIndices(indices, null);\n if (keepSubMeshes) {\n // We offset the materialIndex by the previous number of materials in the CSG mixed meshes\n var materialIndexOffset = 0, materialMaxIndex;\n mesh.subMeshes = new Array();\n for (var m in subMesh_dict) {\n materialMaxIndex = -1;\n for (var sm in subMesh_dict[m]) {\n subMesh_obj = subMesh_dict[m][sm];\n BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);\n materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);\n }\n materialIndexOffset += ++materialMaxIndex;\n }\n }\n return mesh;\n };\n // Build Mesh from CSG taking material and transforms into account\n CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {\n var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);\n mesh.material = material;\n mesh.position.copyFrom(this.position);\n mesh.rotation.copyFrom(this.rotation);\n if (this.rotationQuaternion) {\n mesh.rotationQuaternion = this.rotationQuaternion.clone();\n }\n mesh.scaling.copyFrom(this.scaling);\n mesh.computeWorldMatrix(true);\n return mesh;\n };\n return CSG;\n }());\n BABYLON.CSG = CSG;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.csg.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var LensFlare = /** @class */ (function () {\n function LensFlare(size, position, color, imgUrl, system) {\n this.size = size;\n this.position = position;\n this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;\n this.color = color || new BABYLON.Color3(1, 1, 1);\n this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;\n this._system = system;\n system.lensFlares.push(this);\n }\n LensFlare.AddFlare = function (size, position, color, imgUrl, system) {\n return new LensFlare(size, position, color, imgUrl, system);\n };\n LensFlare.prototype.dispose = function () {\n if (this.texture) {\n this.texture.dispose();\n }\n // Remove from scene\n var index = this._system.lensFlares.indexOf(this);\n this._system.lensFlares.splice(index, 1);\n };\n ;\n return LensFlare;\n }());\n BABYLON.LensFlare = LensFlare;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.lensFlare.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n // Adds the parser to the scene parsers.\n BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {\n // Lens flares\n if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {\n for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {\n var parsedLensFlareSystem = parsedData.lensFlareSystems[index];\n var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);\n container.lensFlareSystems.push(lf);\n }\n }\n });\n BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {\n for (var index = 0; index < this.lensFlareSystems.length; index++) {\n if (this.lensFlareSystems[index].name === name) {\n return this.lensFlareSystems[index];\n }\n }\n return null;\n };\n BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {\n for (var index = 0; index < this.lensFlareSystems.length; index++) {\n if (this.lensFlareSystems[index].id === id) {\n return this.lensFlareSystems[index];\n }\n }\n return null;\n };\n BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {\n var index = this.lensFlareSystems.indexOf(toRemove);\n if (index !== -1) {\n this.lensFlareSystems.splice(index, 1);\n }\n return index;\n };\n BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {\n this.lensFlareSystems.push(newLensFlareSystem);\n };\n /**\n * Defines the lens flare scene component responsible to manage any lens flares\n * in a given scene.\n */\n var LensFlareSystemSceneComponent = /** @class */ (function () {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n function LensFlareSystemSceneComponent(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;\n this.scene = scene;\n scene.lensFlareSystems = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n LensFlareSystemSceneComponent.prototype.register = function () {\n this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);\n };\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n LensFlareSystemSceneComponent.prototype.rebuild = function () {\n // Nothing to do for lens flare\n };\n /**\n * Adds all the element from the container to the scene\n * @param container the container holding the elements\n */\n LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {\n var _this = this;\n if (!container.lensFlareSystems) {\n return;\n }\n container.lensFlareSystems.forEach(function (o) {\n _this.scene.addLensFlareSystem(o);\n });\n };\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n */\n LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {\n var _this = this;\n if (!container.lensFlareSystems) {\n return;\n }\n container.lensFlareSystems.forEach(function (o) {\n _this.scene.removeLensFlareSystem(o);\n });\n };\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {\n // Lens flares\n serializationObject.lensFlareSystems = [];\n var lensFlareSystems = this.scene.lensFlareSystems;\n for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {\n var lensFlareSystem = lensFlareSystems_1[_i];\n serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());\n }\n };\n /**\n * Disposes the component and the associated ressources.\n */\n LensFlareSystemSceneComponent.prototype.dispose = function () {\n var lensFlareSystems = this.scene.lensFlareSystems;\n while (lensFlareSystems.length) {\n lensFlareSystems[0].dispose();\n }\n };\n LensFlareSystemSceneComponent.prototype._draw = function (camera) {\n // Lens flares\n if (this.scene.lensFlaresEnabled) {\n var lensFlareSystems = this.scene.lensFlareSystems;\n BABYLON.Tools.StartPerformanceCounter(\"Lens flares\", lensFlareSystems.length > 0);\n for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {\n var lensFlareSystem = lensFlareSystems_2[_i];\n if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {\n lensFlareSystem.render();\n }\n }\n BABYLON.Tools.EndPerformanceCounter(\"Lens flares\", lensFlareSystems.length > 0);\n }\n };\n return LensFlareSystemSceneComponent;\n }());\n BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var LensFlareSystem = /** @class */ (function () {\n function LensFlareSystem(name, emitter, scene) {\n this.name = name;\n this.lensFlares = new Array();\n this.borderLimit = 300;\n this.viewportBorder = 0;\n this.layerMask = 0x0FFFFFFF;\n this._vertexBuffers = {};\n this._isEnabled = true;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);\n if (!component) {\n component = new BABYLON.LensFlareSystemSceneComponent(this._scene);\n scene._addComponent(component);\n }\n this._emitter = emitter;\n this.id = name;\n scene.lensFlareSystems.push(this);\n this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };\n var engine = scene.getEngine();\n // VBO\n var vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);\n // Indices\n var indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = engine.createIndexBuffer(indices);\n // Effects\n this._effect = engine.createEffect(\"lensFlare\", [BABYLON.VertexBuffer.PositionKind], [\"color\", \"viewportMatrix\"], [\"textureSampler\"], \"\");\n }\n Object.defineProperty(LensFlareSystem.prototype, \"isEnabled\", {\n get: function () {\n return this._isEnabled;\n },\n set: function (value) {\n this._isEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n LensFlareSystem.prototype.getScene = function () {\n return this._scene;\n };\n LensFlareSystem.prototype.getEmitter = function () {\n return this._emitter;\n };\n LensFlareSystem.prototype.setEmitter = function (newEmitter) {\n this._emitter = newEmitter;\n };\n LensFlareSystem.prototype.getEmitterPosition = function () {\n return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;\n };\n LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {\n var position = this.getEmitterPosition();\n position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);\n this._positionX = position.x;\n this._positionY = position.y;\n position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());\n if (this.viewportBorder > 0) {\n globalViewport.x -= this.viewportBorder;\n globalViewport.y -= this.viewportBorder;\n globalViewport.width += this.viewportBorder * 2;\n globalViewport.height += this.viewportBorder * 2;\n position.x += this.viewportBorder;\n position.y += this.viewportBorder;\n this._positionX += this.viewportBorder;\n this._positionY += this.viewportBorder;\n }\n if (position.z > 0) {\n if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {\n if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))\n return true;\n }\n return true;\n }\n return false;\n };\n LensFlareSystem.prototype._isVisible = function () {\n if (!this._isEnabled || !this._scene.activeCamera) {\n return false;\n }\n var emitterPosition = this.getEmitterPosition();\n var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);\n var distance = direction.length();\n direction.normalize();\n var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);\n var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);\n return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;\n };\n LensFlareSystem.prototype.render = function () {\n if (!this._effect.isReady() || !this._scene.activeCamera)\n return false;\n var engine = this._scene.getEngine();\n var viewport = this._scene.activeCamera.viewport;\n var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));\n // Position\n if (!this.computeEffectivePosition(globalViewport)) {\n return false;\n }\n // Visibility\n if (!this._isVisible()) {\n return false;\n }\n // Intensity\n var awayX;\n var awayY;\n if (this._positionX < this.borderLimit + globalViewport.x) {\n awayX = this.borderLimit + globalViewport.x - this._positionX;\n }\n else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {\n awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;\n }\n else {\n awayX = 0;\n }\n if (this._positionY < this.borderLimit + globalViewport.y) {\n awayY = this.borderLimit + globalViewport.y - this._positionY;\n }\n else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {\n awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;\n }\n else {\n awayY = 0;\n }\n var away = (awayX > awayY) ? awayX : awayY;\n away -= this.viewportBorder;\n if (away > this.borderLimit) {\n away = this.borderLimit;\n }\n var intensity = 1.0 - (away / this.borderLimit);\n if (intensity < 0) {\n return false;\n }\n if (intensity > 1.0) {\n intensity = 1.0;\n }\n if (this.viewportBorder > 0) {\n globalViewport.x += this.viewportBorder;\n globalViewport.y += this.viewportBorder;\n globalViewport.width -= this.viewportBorder * 2;\n globalViewport.height -= this.viewportBorder * 2;\n this._positionX -= this.viewportBorder;\n this._positionY -= this.viewportBorder;\n }\n // Position\n var centerX = globalViewport.x + globalViewport.width / 2;\n var centerY = globalViewport.y + globalViewport.height / 2;\n var distX = centerX - this._positionX;\n var distY = centerY - this._positionY;\n // Effects\n engine.enableEffect(this._effect);\n engine.setState(false);\n engine.setDepthBuffer(false);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);\n // Flares\n for (var index = 0; index < this.lensFlares.length; index++) {\n var flare = this.lensFlares[index];\n engine.setAlphaMode(flare.alphaMode);\n var x = centerX - (distX * flare.position);\n var y = centerY - (distY * flare.position);\n var cw = flare.size;\n var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);\n var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;\n var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));\n var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);\n this._effect.setMatrix(\"viewportMatrix\", viewportMatrix);\n // Texture\n this._effect.setTexture(\"textureSampler\", flare.texture);\n // Color\n this._effect.setFloat4(\"color\", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);\n // Draw order\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n }\n engine.setDepthBuffer(true);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n return true;\n };\n LensFlareSystem.prototype.dispose = function () {\n var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n while (this.lensFlares.length) {\n this.lensFlares[0].dispose();\n }\n // Remove from scene\n var index = this._scene.lensFlareSystems.indexOf(this);\n this._scene.lensFlareSystems.splice(index, 1);\n };\n LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {\n var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);\n var name = parsedLensFlareSystem.name || \"lensFlareSystem#\" + parsedLensFlareSystem.emitterId;\n var lensFlareSystem = new LensFlareSystem(name, emitter, scene);\n lensFlareSystem.id = parsedLensFlareSystem.id || name;\n lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;\n for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {\n var parsedFlare = parsedLensFlareSystem.flares[index];\n BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : \"\", lensFlareSystem);\n }\n return lensFlareSystem;\n };\n LensFlareSystem.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.id = this.id;\n serializationObject.name = this.name;\n serializationObject.emitterId = this.getEmitter().id;\n serializationObject.borderLimit = this.borderLimit;\n serializationObject.flares = [];\n for (var index = 0; index < this.lensFlares.length; index++) {\n var flare = this.lensFlares[index];\n serializationObject.flares.push({\n size: flare.size,\n position: flare.position,\n color: flare.color.asArray(),\n textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : \"\")\n });\n }\n return serializationObject;\n };\n return LensFlareSystem;\n }());\n BABYLON.LensFlareSystem = LensFlareSystem;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.lensFlareSystem.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This is a holder class for the physics joint created by the physics plugin.\n * It holds a set of functions to control the underlying joint.\n */\n var PhysicsJoint = /** @class */ (function () {\n function PhysicsJoint(type, jointData) {\n this.type = type;\n this.jointData = jointData;\n jointData.nativeParams = jointData.nativeParams || {};\n }\n Object.defineProperty(PhysicsJoint.prototype, \"physicsJoint\", {\n get: function () {\n return this._physicsJoint;\n },\n set: function (newJoint) {\n if (this._physicsJoint) {\n //remove from the wolrd\n }\n this._physicsJoint = newJoint;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PhysicsJoint.prototype, \"physicsPlugin\", {\n set: function (physicsPlugin) {\n this._physicsPlugin = physicsPlugin;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Execute a function that is physics-plugin specific.\n * @param {Function} func the function that will be executed.\n * It accepts two parameters: the physics world and the physics joint.\n */\n PhysicsJoint.prototype.executeNativeFunction = function (func) {\n func(this._physicsPlugin.world, this._physicsJoint);\n };\n //TODO check if the native joints are the same\n //Joint Types\n PhysicsJoint.DistanceJoint = 0;\n PhysicsJoint.HingeJoint = 1;\n PhysicsJoint.BallAndSocketJoint = 2;\n PhysicsJoint.WheelJoint = 3;\n PhysicsJoint.SliderJoint = 4;\n //OIMO\n PhysicsJoint.PrismaticJoint = 5;\n //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)\n PhysicsJoint.UniversalJoint = 6;\n PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;\n //Cannon\n //Similar to a Ball-Joint. Different in params\n PhysicsJoint.PointToPointJoint = 8;\n //Cannon only at the moment\n PhysicsJoint.SpringJoint = 9;\n PhysicsJoint.LockJoint = 10;\n return PhysicsJoint;\n }());\n BABYLON.PhysicsJoint = PhysicsJoint;\n /**\n * A class representing a physics distance joint.\n */\n var DistanceJoint = /** @class */ (function (_super) {\n __extends(DistanceJoint, _super);\n function DistanceJoint(jointData) {\n return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;\n }\n /**\n * Update the predefined distance.\n */\n DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {\n this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);\n };\n return DistanceJoint;\n }(PhysicsJoint));\n BABYLON.DistanceJoint = DistanceJoint;\n var MotorEnabledJoint = /** @class */ (function (_super) {\n __extends(MotorEnabledJoint, _super);\n function MotorEnabledJoint(type, jointData) {\n return _super.call(this, type, jointData) || this;\n }\n /**\n * Set the motor values.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param {number} force the force to apply\n * @param {number} maxForce max force for this motor.\n */\n MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {\n this._physicsPlugin.setMotor(this, force || 0, maxForce);\n };\n /**\n * Set the motor's limits.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n */\n MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {\n this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);\n };\n return MotorEnabledJoint;\n }(PhysicsJoint));\n BABYLON.MotorEnabledJoint = MotorEnabledJoint;\n /**\n * This class represents a single hinge physics joint\n */\n var HingeJoint = /** @class */ (function (_super) {\n __extends(HingeJoint, _super);\n function HingeJoint(jointData) {\n return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;\n }\n /**\n * Set the motor values.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param {number} force the force to apply\n * @param {number} maxForce max force for this motor.\n */\n HingeJoint.prototype.setMotor = function (force, maxForce) {\n this._physicsPlugin.setMotor(this, force || 0, maxForce);\n };\n /**\n * Set the motor's limits.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n */\n HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {\n this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);\n };\n return HingeJoint;\n }(MotorEnabledJoint));\n BABYLON.HingeJoint = HingeJoint;\n /**\n * This class represents a dual hinge physics joint (same as wheel joint)\n */\n var Hinge2Joint = /** @class */ (function (_super) {\n __extends(Hinge2Joint, _super);\n function Hinge2Joint(jointData) {\n return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;\n }\n /**\n * Set the motor values.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param {number} force the force to apply\n * @param {number} maxForce max force for this motor.\n * @param {motorIndex} the motor's index, 0 or 1.\n */\n Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {\n if (motorIndex === void 0) { motorIndex = 0; }\n this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);\n };\n /**\n * Set the motor limits.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param {number} upperLimit the upper limit\n * @param {number} lowerLimit lower limit\n * @param {motorIndex} the motor's index, 0 or 1.\n */\n Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {\n if (motorIndex === void 0) { motorIndex = 0; }\n this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);\n };\n return Hinge2Joint;\n }(MotorEnabledJoint));\n BABYLON.Hinge2Joint = Hinge2Joint;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.physicsJoint.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var PhysicsImpostor = /** @class */ (function () {\n function PhysicsImpostor(object, type, _options, _scene) {\n if (_options === void 0) { _options = { mass: 0 }; }\n var _this = this;\n this.object = object;\n this.type = type;\n this._options = _options;\n this._scene = _scene;\n this._bodyUpdateRequired = false;\n this._onBeforePhysicsStepCallbacks = new Array();\n this._onAfterPhysicsStepCallbacks = new Array();\n this._onPhysicsCollideCallbacks = [];\n this._deltaPosition = BABYLON.Vector3.Zero();\n this._isDisposed = false;\n //temp variables for parent rotation calculations\n //private _mats: Array = [new Matrix(), new Matrix()];\n this._tmpQuat = new BABYLON.Quaternion();\n this._tmpQuat2 = new BABYLON.Quaternion();\n /**\n * this function is executed by the physics engine.\n */\n this.beforeStep = function () {\n if (!_this._physicsEngine) {\n return;\n }\n _this.object.translate(_this._deltaPosition, -1);\n _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);\n _this.object.computeWorldMatrix(false);\n if (_this.object.parent && _this.object.rotationQuaternion) {\n _this.getParentsRotation();\n _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);\n }\n else {\n _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());\n }\n if (!_this._options.disableBidirectionalTransformation) {\n _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);\n }\n _this._onBeforePhysicsStepCallbacks.forEach(function (func) {\n func(_this);\n });\n };\n /**\n * this function is executed by the physics engine.\n */\n this.afterStep = function () {\n if (!_this._physicsEngine) {\n return;\n }\n _this._onAfterPhysicsStepCallbacks.forEach(function (func) {\n func(_this);\n });\n _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);\n // object has now its world rotation. needs to be converted to local.\n if (_this.object.parent && _this.object.rotationQuaternion) {\n _this.getParentsRotation();\n _this._tmpQuat.conjugateInPlace();\n _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);\n }\n // take the position set and make it the absolute position of this object.\n _this.object.setAbsolutePosition(_this.object.position);\n _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);\n _this.object.translate(_this._deltaPosition, 1);\n };\n /**\n * Legacy collision detection event support\n */\n this.onCollideEvent = null;\n //event and body object due to cannon's event-based architecture.\n this.onCollide = function (e) {\n if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {\n return;\n }\n if (!_this._physicsEngine) {\n return;\n }\n var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);\n if (otherImpostor) {\n // Legacy collision detection event support\n if (_this.onCollideEvent) {\n _this.onCollideEvent(_this, otherImpostor);\n }\n _this._onPhysicsCollideCallbacks.filter(function (obj) {\n return obj.otherImpostors.indexOf(otherImpostor) !== -1;\n }).forEach(function (obj) {\n obj.callback(_this, otherImpostor);\n });\n }\n };\n //sanity check!\n if (!this.object) {\n BABYLON.Tools.Error(\"No object was provided. A physics object is obligatory\");\n return;\n }\n //legacy support for old syntax.\n if (!this._scene && object.getScene) {\n this._scene = object.getScene();\n }\n if (!this._scene) {\n return;\n }\n this._physicsEngine = this._scene.getPhysicsEngine();\n if (!this._physicsEngine) {\n BABYLON.Tools.Error(\"Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.\");\n }\n else {\n //set the object's quaternion, if not set\n if (!this.object.rotationQuaternion) {\n if (this.object.rotation) {\n this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);\n }\n else {\n this.object.rotationQuaternion = new BABYLON.Quaternion();\n }\n }\n //default options params\n this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;\n this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;\n this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;\n this._joints = [];\n //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.\n if (!this.object.parent || this._options.ignoreParent) {\n this._init();\n }\n else if (this.object.parent.physicsImpostor) {\n BABYLON.Tools.Warn(\"You must affect impostors to children before affecting impostor to parent.\");\n }\n }\n }\n Object.defineProperty(PhysicsImpostor.prototype, \"isDisposed\", {\n get: function () {\n return this._isDisposed;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PhysicsImpostor.prototype, \"mass\", {\n get: function () {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;\n },\n set: function (value) {\n this.setMass(value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PhysicsImpostor.prototype, \"friction\", {\n get: function () {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;\n },\n set: function (value) {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PhysicsImpostor.prototype, \"restitution\", {\n get: function () {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;\n },\n set: function (value) {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * This function will completly initialize this impostor.\n * It will create a new body - but only if this mesh has no parent.\n * If it has, this impostor will not be used other than to define the impostor\n * of the child mesh.\n */\n PhysicsImpostor.prototype._init = function () {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.removeImpostor(this);\n this.physicsBody = null;\n this._parent = this._parent || this._getPhysicsParent();\n if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {\n this._physicsEngine.addImpostor(this);\n }\n };\n PhysicsImpostor.prototype._getPhysicsParent = function () {\n if (this.object.parent instanceof BABYLON.AbstractMesh) {\n var parentMesh = this.object.parent;\n return parentMesh.physicsImpostor;\n }\n return null;\n };\n /**\n * Should a new body be generated.\n */\n PhysicsImpostor.prototype.isBodyInitRequired = function () {\n return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);\n };\n PhysicsImpostor.prototype.setScalingUpdated = function (updated) {\n this.forceUpdate();\n };\n /**\n * Force a regeneration of this or the parent's impostor's body.\n * Use under cautious - This will remove all joints already implemented.\n */\n PhysicsImpostor.prototype.forceUpdate = function () {\n this._init();\n if (this.parent && !this._options.ignoreParent) {\n this.parent.forceUpdate();\n }\n };\n Object.defineProperty(PhysicsImpostor.prototype, \"physicsBody\", {\n /*public get mesh(): AbstractMesh {\n return this._mesh;\n }*/\n /**\n * Gets the body that holds this impostor. Either its own, or its parent.\n */\n get: function () {\n return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;\n },\n /**\n * Set the physics body. Used mainly by the physics engine/plugin\n */\n set: function (physicsBody) {\n if (this._physicsBody && this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);\n }\n this._physicsBody = physicsBody;\n this.resetUpdateFlags();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PhysicsImpostor.prototype, \"parent\", {\n get: function () {\n return !this._options.ignoreParent && this._parent ? this._parent : null;\n },\n set: function (value) {\n this._parent = value;\n },\n enumerable: true,\n configurable: true\n });\n PhysicsImpostor.prototype.resetUpdateFlags = function () {\n this._bodyUpdateRequired = false;\n };\n PhysicsImpostor.prototype.getObjectExtendSize = function () {\n if (this.object.getBoundingInfo) {\n var q = this.object.rotationQuaternion;\n //reset rotation\n this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;\n //calculate the world matrix with no rotation\n this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);\n var boundingInfo = this.object.getBoundingInfo();\n var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);\n //bring back the rotation\n this.object.rotationQuaternion = q;\n //calculate the world matrix with the new rotation\n this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);\n return size;\n }\n else {\n return PhysicsImpostor.DEFAULT_OBJECT_SIZE;\n }\n };\n PhysicsImpostor.prototype.getObjectCenter = function () {\n if (this.object.getBoundingInfo) {\n var boundingInfo = this.object.getBoundingInfo();\n return boundingInfo.boundingBox.centerWorld;\n }\n else {\n return this.object.position;\n }\n };\n /**\n * Get a specific parametes from the options parameter.\n */\n PhysicsImpostor.prototype.getParam = function (paramName) {\n return this._options[paramName];\n };\n /**\n * Sets a specific parameter in the options given to the physics plugin\n */\n PhysicsImpostor.prototype.setParam = function (paramName, value) {\n this._options[paramName] = value;\n this._bodyUpdateRequired = true;\n };\n /**\n * Specifically change the body's mass option. Won't recreate the physics body object\n */\n PhysicsImpostor.prototype.setMass = function (mass) {\n if (this.getParam(\"mass\") !== mass) {\n this.setParam(\"mass\", mass);\n }\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);\n }\n };\n PhysicsImpostor.prototype.getLinearVelocity = function () {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();\n };\n PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);\n }\n };\n PhysicsImpostor.prototype.getAngularVelocity = function () {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();\n };\n PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);\n }\n };\n /**\n * Execute a function with the physics plugin native code.\n * Provide a function the will have two variables - the world object and the physics body object.\n */\n PhysicsImpostor.prototype.executeNativeFunction = function (func) {\n if (this._physicsEngine) {\n func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);\n }\n };\n /**\n * Register a function that will be executed before the physics world is stepping forward.\n */\n PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {\n this._onBeforePhysicsStepCallbacks.push(func);\n };\n PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {\n var index = this._onBeforePhysicsStepCallbacks.indexOf(func);\n if (index > -1) {\n this._onBeforePhysicsStepCallbacks.splice(index, 1);\n }\n else {\n BABYLON.Tools.Warn(\"Function to remove was not found\");\n }\n };\n /**\n * Register a function that will be executed after the physics step\n */\n PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {\n this._onAfterPhysicsStepCallbacks.push(func);\n };\n PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {\n var index = this._onAfterPhysicsStepCallbacks.indexOf(func);\n if (index > -1) {\n this._onAfterPhysicsStepCallbacks.splice(index, 1);\n }\n else {\n BABYLON.Tools.Warn(\"Function to remove was not found\");\n }\n };\n /**\n * register a function that will be executed when this impostor collides against a different body.\n */\n PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {\n var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];\n this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });\n };\n PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {\n var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];\n var index = -1;\n var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {\n if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {\n // chcek the arrays match\n var sameList = cbDef.otherImpostors.every(function (impostor) {\n return collidedAgainstList.indexOf(impostor) > -1;\n });\n if (sameList) {\n index = idx;\n }\n return sameList;\n }\n return false;\n });\n if (found) {\n this._onPhysicsCollideCallbacks.splice(index, 1);\n }\n else {\n BABYLON.Tools.Warn(\"Function to remove was not found\");\n }\n };\n PhysicsImpostor.prototype.getParentsRotation = function () {\n var parent = this.object.parent;\n this._tmpQuat.copyFromFloats(0, 0, 0, 1);\n while (parent) {\n if (parent.rotationQuaternion) {\n this._tmpQuat2.copyFrom(parent.rotationQuaternion);\n }\n else {\n BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);\n }\n this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);\n parent = parent.parent;\n }\n return this._tmpQuat;\n };\n /**\n * Apply a force\n */\n PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);\n }\n return this;\n };\n /**\n * Apply an impulse\n */\n PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);\n }\n return this;\n };\n /**\n * A help function to create a joint.\n */\n PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {\n var joint = new BABYLON.PhysicsJoint(jointType, jointData);\n this.addJoint(otherImpostor, joint);\n return this;\n };\n /**\n * Add a joint to this impostor with a different impostor.\n */\n PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {\n this._joints.push({\n otherImpostor: otherImpostor,\n joint: joint\n });\n if (this._physicsEngine) {\n this._physicsEngine.addJoint(this, otherImpostor, joint);\n }\n return this;\n };\n /**\n * Will keep this body still, in a sleep mode.\n */\n PhysicsImpostor.prototype.sleep = function () {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().sleepBody(this);\n }\n return this;\n };\n /**\n * Wake the body up.\n */\n PhysicsImpostor.prototype.wakeUp = function () {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);\n }\n return this;\n };\n PhysicsImpostor.prototype.clone = function (newObject) {\n if (!newObject)\n return null;\n return new PhysicsImpostor(newObject, this.type, this._options, this._scene);\n };\n PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {\n var _this = this;\n //no dispose if no physics engine is available.\n if (!this._physicsEngine) {\n return;\n }\n this._joints.forEach(function (j) {\n if (_this._physicsEngine) {\n _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);\n }\n });\n //dispose the physics body\n this._physicsEngine.removeImpostor(this);\n if (this.parent) {\n this.parent.forceUpdate();\n }\n else {\n /*this._object.getChildMeshes().forEach(function(mesh) {\n if (mesh.physicsImpostor) {\n if (disposeChildren) {\n mesh.physicsImpostor.dispose();\n mesh.physicsImpostor = null;\n }\n }\n })*/\n }\n this._isDisposed = true;\n };\n PhysicsImpostor.prototype.setDeltaPosition = function (position) {\n this._deltaPosition.copyFrom(position);\n };\n PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {\n if (!this._deltaRotation) {\n this._deltaRotation = new BABYLON.Quaternion();\n }\n this._deltaRotation.copyFrom(rotation);\n this._deltaRotationConjugated = this._deltaRotation.conjugate();\n };\n PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);\n }\n return this;\n };\n PhysicsImpostor.prototype.getRadius = function () {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;\n };\n /**\n * Sync a bone with this impostor\n * @param bone The bone to sync to the impostor.\n * @param boneMesh The mesh that the bone is influencing.\n * @param jointPivot The pivot of the joint / bone in local space.\n * @param distToJoint Optional distance from the impostor to the joint.\n * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.\n */\n PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {\n var tempVec = PhysicsImpostor._tmpVecs[0];\n var mesh = this.object;\n if (mesh.rotationQuaternion) {\n if (adjustRotation) {\n var tempQuat = PhysicsImpostor._tmpQuat;\n mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);\n bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);\n }\n else {\n bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);\n }\n }\n tempVec.x = 0;\n tempVec.y = 0;\n tempVec.z = 0;\n if (jointPivot) {\n tempVec.x = jointPivot.x;\n tempVec.y = jointPivot.y;\n tempVec.z = jointPivot.z;\n bone.getDirectionToRef(tempVec, boneMesh, tempVec);\n if (distToJoint === undefined || distToJoint === null) {\n distToJoint = jointPivot.length();\n }\n tempVec.x *= distToJoint;\n tempVec.y *= distToJoint;\n tempVec.z *= distToJoint;\n }\n if (bone.getParent()) {\n tempVec.addInPlace(mesh.getAbsolutePosition());\n bone.setAbsolutePosition(tempVec, boneMesh);\n }\n else {\n boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());\n boneMesh.position.x -= tempVec.x;\n boneMesh.position.y -= tempVec.y;\n boneMesh.position.z -= tempVec.z;\n }\n };\n /**\n * Sync impostor to a bone\n * @param bone The bone that the impostor will be synced to.\n * @param boneMesh The mesh that the bone is influencing.\n * @param jointPivot The pivot of the joint / bone in local space.\n * @param distToJoint Optional distance from the impostor to the joint.\n * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.\n * @param boneAxis Optional vector3 axis the bone is aligned with\n */\n PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {\n var mesh = this.object;\n if (mesh.rotationQuaternion) {\n if (adjustRotation) {\n var tempQuat = PhysicsImpostor._tmpQuat;\n bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);\n tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);\n }\n else {\n bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);\n }\n }\n var pos = PhysicsImpostor._tmpVecs[0];\n var boneDir = PhysicsImpostor._tmpVecs[1];\n if (!boneAxis) {\n boneAxis = PhysicsImpostor._tmpVecs[2];\n boneAxis.x = 0;\n boneAxis.y = 1;\n boneAxis.z = 0;\n }\n bone.getDirectionToRef(boneAxis, boneMesh, boneDir);\n bone.getAbsolutePositionToRef(boneMesh, pos);\n if ((distToJoint === undefined || distToJoint === null) && jointPivot) {\n distToJoint = jointPivot.length();\n }\n if (distToJoint !== undefined && distToJoint !== null) {\n pos.x += boneDir.x * distToJoint;\n pos.y += boneDir.y * distToJoint;\n pos.z += boneDir.z * distToJoint;\n }\n mesh.setAbsolutePosition(pos);\n };\n PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);\n PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();\n PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];\n PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();\n //Impostor types\n PhysicsImpostor.NoImpostor = 0;\n PhysicsImpostor.SphereImpostor = 1;\n PhysicsImpostor.BoxImpostor = 2;\n PhysicsImpostor.PlaneImpostor = 3;\n PhysicsImpostor.MeshImpostor = 4;\n PhysicsImpostor.CylinderImpostor = 7;\n PhysicsImpostor.ParticleImpostor = 8;\n PhysicsImpostor.HeightmapImpostor = 9;\n return PhysicsImpostor;\n }());\n BABYLON.PhysicsImpostor = PhysicsImpostor;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.physicsImpostor.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var PhysicsEngine = /** @class */ (function () {\n function PhysicsEngine(gravity, _physicsPlugin) {\n if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }\n this._physicsPlugin = _physicsPlugin;\n //new methods and parameters\n this._impostors = [];\n this._joints = [];\n if (!this._physicsPlugin.isSupported()) {\n throw new Error(\"Physics Engine \" + this._physicsPlugin.name + \" cannot be found. \"\n + \"Please make sure it is included.\");\n }\n gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);\n this.setGravity(gravity);\n this.setTimeStep();\n }\n PhysicsEngine.prototype.setGravity = function (gravity) {\n this.gravity = gravity;\n this._physicsPlugin.setGravity(this.gravity);\n };\n /**\n * Set the time step of the physics engine.\n * default is 1/60.\n * To slow it down, enter 1/600 for example.\n * To speed it up, 1/30\n * @param {number} newTimeStep the new timestep to apply to this world.\n */\n PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {\n if (newTimeStep === void 0) { newTimeStep = 1 / 60; }\n this._physicsPlugin.setTimeStep(newTimeStep);\n };\n /**\n * Get the time step of the physics engine.\n */\n PhysicsEngine.prototype.getTimeStep = function () {\n return this._physicsPlugin.getTimeStep();\n };\n PhysicsEngine.prototype.dispose = function () {\n this._impostors.forEach(function (impostor) {\n impostor.dispose();\n });\n this._physicsPlugin.dispose();\n };\n PhysicsEngine.prototype.getPhysicsPluginName = function () {\n return this._physicsPlugin.name;\n };\n /**\n * Adding a new impostor for the impostor tracking.\n * This will be done by the impostor itself.\n * @param {PhysicsImpostor} impostor the impostor to add\n */\n PhysicsEngine.prototype.addImpostor = function (impostor) {\n impostor.uniqueId = this._impostors.push(impostor);\n //if no parent, generate the body\n if (!impostor.parent) {\n this._physicsPlugin.generatePhysicsBody(impostor);\n }\n };\n /**\n * Remove an impostor from the engine.\n * This impostor and its mesh will not longer be updated by the physics engine.\n * @param {PhysicsImpostor} impostor the impostor to remove\n */\n PhysicsEngine.prototype.removeImpostor = function (impostor) {\n var index = this._impostors.indexOf(impostor);\n if (index > -1) {\n var removed = this._impostors.splice(index, 1);\n //Is it needed?\n if (removed.length) {\n //this will also remove it from the world.\n removed[0].physicsBody = null;\n }\n }\n };\n /**\n * Add a joint to the physics engine\n * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.\n * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint\n * @param {PhysicsJoint} the joint that will connect both impostors.\n */\n PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {\n var impostorJoint = {\n mainImpostor: mainImpostor,\n connectedImpostor: connectedImpostor,\n joint: joint\n };\n joint.physicsPlugin = this._physicsPlugin;\n this._joints.push(impostorJoint);\n this._physicsPlugin.generateJoint(impostorJoint);\n };\n PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {\n var matchingJoints = this._joints.filter(function (impostorJoint) {\n return (impostorJoint.connectedImpostor === connectedImpostor\n && impostorJoint.joint === joint\n && impostorJoint.mainImpostor === mainImpostor);\n });\n if (matchingJoints.length) {\n this._physicsPlugin.removeJoint(matchingJoints[0]);\n //TODO remove it from the list as well\n }\n };\n /**\n * Called by the scene. no need to call it.\n */\n PhysicsEngine.prototype._step = function (delta) {\n var _this = this;\n //check if any mesh has no body / requires an update\n this._impostors.forEach(function (impostor) {\n if (impostor.isBodyInitRequired()) {\n _this._physicsPlugin.generatePhysicsBody(impostor);\n }\n });\n if (delta > 0.1) {\n delta = 0.1;\n }\n else if (delta <= 0) {\n delta = 1.0 / 60.0;\n }\n this._physicsPlugin.executeStep(delta, this._impostors);\n };\n PhysicsEngine.prototype.getPhysicsPlugin = function () {\n return this._physicsPlugin;\n };\n PhysicsEngine.prototype.getImpostors = function () {\n return this._impostors;\n };\n PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {\n for (var i = 0; i < this._impostors.length; ++i) {\n if (this._impostors[i].object === object) {\n return this._impostors[i];\n }\n }\n return null;\n };\n PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {\n for (var i = 0; i < this._impostors.length; ++i) {\n if (this._impostors[i].physicsBody === body) {\n return this._impostors[i];\n }\n }\n return null;\n };\n // Statics\n PhysicsEngine.Epsilon = 0.001;\n return PhysicsEngine;\n }());\n BABYLON.PhysicsEngine = PhysicsEngine;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.physicsEngine.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var PhysicsHelper = /** @class */ (function () {\n function PhysicsHelper(scene) {\n this._scene = scene;\n this._physicsEngine = this._scene.getPhysicsEngine();\n if (!this._physicsEngine) {\n BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');\n }\n }\n /**\n * @param {Vector3} origin the origin of the explosion\n * @param {number} radius the explosion radius\n * @param {number} strength the explosion strength\n * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant\n */\n PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {\n if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }\n if (!this._physicsEngine) {\n BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');\n return null;\n }\n var impostors = this._physicsEngine.getImpostors();\n if (impostors.length === 0) {\n return null;\n }\n var event = new PhysicsRadialExplosionEvent(this._scene);\n impostors.forEach(function (impostor) {\n var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);\n if (!impostorForceAndContactPoint) {\n return;\n }\n impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);\n });\n event.dispose(false);\n return event;\n };\n /**\n * @param {Vector3} origin the origin of the explosion\n * @param {number} radius the explosion radius\n * @param {number} strength the explosion strength\n * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant\n */\n PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {\n if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }\n if (!this._physicsEngine) {\n BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');\n return null;\n }\n var impostors = this._physicsEngine.getImpostors();\n if (impostors.length === 0) {\n return null;\n }\n var event = new PhysicsRadialExplosionEvent(this._scene);\n impostors.forEach(function (impostor) {\n var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);\n if (!impostorForceAndContactPoint) {\n return;\n }\n impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);\n });\n event.dispose(false);\n return event;\n };\n /**\n * @param {Vector3} origin the origin of the explosion\n * @param {number} radius the explosion radius\n * @param {number} strength the explosion strength\n * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant\n */\n PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {\n if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }\n if (!this._physicsEngine) {\n BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');\n return null;\n }\n var impostors = this._physicsEngine.getImpostors();\n if (impostors.length === 0) {\n return null;\n }\n var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);\n event.dispose(false);\n return event;\n };\n /**\n * @param {Vector3} origin the origin of the updraft\n * @param {number} radius the radius of the updraft\n * @param {number} strength the strength of the updraft\n * @param {number} height the height of the updraft\n * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center\n */\n PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {\n if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }\n if (!this._physicsEngine) {\n BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');\n return null;\n }\n if (this._physicsEngine.getImpostors().length === 0) {\n return null;\n }\n var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);\n event.dispose(false);\n return event;\n };\n /**\n * @param {Vector3} origin the of the vortex\n * @param {number} radius the radius of the vortex\n * @param {number} strength the strength of the vortex\n * @param {number} height the height of the vortex\n */\n PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {\n if (!this._physicsEngine) {\n BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');\n return null;\n }\n if (this._physicsEngine.getImpostors().length === 0) {\n return null;\n }\n var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);\n event.dispose(false);\n return event;\n };\n return PhysicsHelper;\n }());\n BABYLON.PhysicsHelper = PhysicsHelper;\n /***** Radial explosion *****/\n var PhysicsRadialExplosionEvent = /** @class */ (function () {\n function PhysicsRadialExplosionEvent(scene) {\n this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable\n this._rays = [];\n this._dataFetched = false; // check if the data has been fetched. If not, do cleanup\n this._scene = scene;\n }\n /**\n * Returns the data related to the radial explosion event (sphere & rays).\n * @returns {PhysicsRadialExplosionEventData}\n */\n PhysicsRadialExplosionEvent.prototype.getData = function () {\n this._dataFetched = true;\n return {\n sphere: this._sphere,\n rays: this._rays,\n };\n };\n /**\n * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.\n * @param impostor\n * @param {Vector3} origin the origin of the explosion\n * @param {number} radius the explosion radius\n * @param {number} strength the explosion strength\n * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear\n * @returns {Nullable}\n */\n PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {\n if (impostor.mass === 0) {\n return null;\n }\n if (!this._intersectsWithSphere(impostor, origin, radius)) {\n return null;\n }\n if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {\n return null;\n }\n var impostorObjectCenter = impostor.getObjectCenter();\n var direction = impostorObjectCenter.subtract(origin);\n var ray = new BABYLON.Ray(origin, direction, radius);\n this._rays.push(ray);\n var hit = ray.intersectsMesh(impostor.object);\n var contactPoint = hit.pickedPoint;\n if (!contactPoint) {\n return null;\n }\n var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);\n if (distanceFromOrigin > radius) {\n return null;\n }\n var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant\n ? strength\n : strength * (1 - (distanceFromOrigin / radius));\n var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);\n return { force: force, contactPoint: contactPoint };\n };\n /**\n * Disposes the sphere.\n * @param {bolean} force\n */\n PhysicsRadialExplosionEvent.prototype.dispose = function (force) {\n var _this = this;\n if (force === void 0) { force = true; }\n if (force) {\n this._sphere.dispose();\n }\n else {\n setTimeout(function () {\n if (!_this._dataFetched) {\n _this._sphere.dispose();\n }\n }, 0);\n }\n };\n /*** Helpers ***/\n PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {\n if (!this._sphere) {\n this._sphere = BABYLON.MeshBuilder.CreateSphere(\"radialExplosionEventSphere\", this._sphereOptions, this._scene);\n this._sphere.isVisible = false;\n }\n };\n PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {\n var impostorObject = impostor.object;\n this._prepareSphere();\n this._sphere.position = origin;\n this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);\n this._sphere._updateBoundingInfo();\n this._sphere.computeWorldMatrix(true);\n return this._sphere.intersectsMesh(impostorObject, true);\n };\n return PhysicsRadialExplosionEvent;\n }());\n BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;\n /***** Gravitational Field *****/\n var PhysicsGravitationalFieldEvent = /** @class */ (function () {\n function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {\n if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }\n this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup\n this._physicsHelper = physicsHelper;\n this._scene = scene;\n this._origin = origin;\n this._radius = radius;\n this._strength = strength;\n this._falloff = falloff;\n this._tickCallback = this._tick.bind(this);\n }\n /**\n * Returns the data related to the gravitational field event (sphere).\n * @returns {PhysicsGravitationalFieldEventData}\n */\n PhysicsGravitationalFieldEvent.prototype.getData = function () {\n this._dataFetched = true;\n return {\n sphere: this._sphere,\n };\n };\n /**\n * Enables the gravitational field.\n */\n PhysicsGravitationalFieldEvent.prototype.enable = function () {\n this._tickCallback.call(this);\n this._scene.registerBeforeRender(this._tickCallback);\n };\n /**\n * Disables the gravitational field.\n */\n PhysicsGravitationalFieldEvent.prototype.disable = function () {\n this._scene.unregisterBeforeRender(this._tickCallback);\n };\n /**\n * Disposes the sphere.\n * @param {bolean} force\n */\n PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {\n var _this = this;\n if (force === void 0) { force = true; }\n if (force) {\n this._sphere.dispose();\n }\n else {\n setTimeout(function () {\n if (!_this._dataFetched) {\n _this._sphere.dispose();\n }\n }, 0);\n }\n };\n PhysicsGravitationalFieldEvent.prototype._tick = function () {\n // Since the params won't change, we fetch the event only once\n if (this._sphere) {\n this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);\n }\n else {\n var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);\n if (radialExplosionEvent) {\n this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');\n }\n }\n };\n return PhysicsGravitationalFieldEvent;\n }());\n BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;\n /***** Updraft *****/\n var PhysicsUpdraftEvent = /** @class */ (function () {\n function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {\n this._scene = _scene;\n this._origin = _origin;\n this._radius = _radius;\n this._strength = _strength;\n this._height = _height;\n this._updraftMode = _updraftMode;\n this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder\n this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular\n this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom\n this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup\n this._physicsEngine = this._scene.getPhysicsEngine();\n this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);\n this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);\n if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {\n this._originDirection = this._origin.subtract(this._originTop).normalize();\n }\n this._tickCallback = this._tick.bind(this);\n }\n /**\n * Returns the data related to the updraft event (cylinder).\n * @returns {PhysicsUpdraftEventData}\n */\n PhysicsUpdraftEvent.prototype.getData = function () {\n this._dataFetched = true;\n return {\n cylinder: this._cylinder,\n };\n };\n /**\n * Enables the updraft.\n */\n PhysicsUpdraftEvent.prototype.enable = function () {\n this._tickCallback.call(this);\n this._scene.registerBeforeRender(this._tickCallback);\n };\n /**\n * Disables the cortex.\n */\n PhysicsUpdraftEvent.prototype.disable = function () {\n this._scene.unregisterBeforeRender(this._tickCallback);\n };\n /**\n * Disposes the sphere.\n * @param {bolean} force\n */\n PhysicsUpdraftEvent.prototype.dispose = function (force) {\n var _this = this;\n if (force === void 0) { force = true; }\n if (force) {\n this._cylinder.dispose();\n }\n else {\n setTimeout(function () {\n if (!_this._dataFetched) {\n _this._cylinder.dispose();\n }\n }, 0);\n }\n };\n PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {\n if (impostor.mass === 0) {\n return null;\n }\n if (!this._intersectsWithCylinder(impostor)) {\n return null;\n }\n var impostorObjectCenter = impostor.getObjectCenter();\n if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {\n var direction = this._originDirection;\n }\n else {\n var direction = impostorObjectCenter.subtract(this._originTop);\n }\n var multiplier = this._strength * -1;\n var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);\n return { force: force, contactPoint: impostorObjectCenter };\n };\n PhysicsUpdraftEvent.prototype._tick = function () {\n var _this = this;\n this._physicsEngine.getImpostors().forEach(function (impostor) {\n var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);\n if (!impostorForceAndContactPoint) {\n return;\n }\n impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);\n });\n };\n /*** Helpers ***/\n PhysicsUpdraftEvent.prototype._prepareCylinder = function () {\n if (!this._cylinder) {\n this._cylinder = BABYLON.MeshBuilder.CreateCylinder(\"updraftEventCylinder\", {\n height: this._height,\n diameter: this._radius * 2,\n }, this._scene);\n this._cylinder.isVisible = false;\n }\n };\n PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {\n var impostorObject = impostor.object;\n this._prepareCylinder();\n this._cylinder.position = this._cylinderPosition;\n return this._cylinder.intersectsMesh(impostorObject, true);\n };\n return PhysicsUpdraftEvent;\n }());\n BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;\n /***** Vortex *****/\n var PhysicsVortexEvent = /** @class */ (function () {\n function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {\n this._scene = _scene;\n this._origin = _origin;\n this._radius = _radius;\n this._strength = _strength;\n this._height = _height;\n this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder\n this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in\n this._updraftMultiplier = 0.02;\n this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom\n this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup\n this._physicsEngine = this._scene.getPhysicsEngine();\n this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);\n this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);\n this._tickCallback = this._tick.bind(this);\n }\n /**\n * Returns the data related to the vortex event (cylinder).\n * @returns {PhysicsVortexEventData}\n */\n PhysicsVortexEvent.prototype.getData = function () {\n this._dataFetched = true;\n return {\n cylinder: this._cylinder,\n };\n };\n /**\n * Enables the vortex.\n */\n PhysicsVortexEvent.prototype.enable = function () {\n this._tickCallback.call(this);\n this._scene.registerBeforeRender(this._tickCallback);\n };\n /**\n * Disables the cortex.\n */\n PhysicsVortexEvent.prototype.disable = function () {\n this._scene.unregisterBeforeRender(this._tickCallback);\n };\n /**\n * Disposes the sphere.\n * @param {bolean} force\n */\n PhysicsVortexEvent.prototype.dispose = function (force) {\n var _this = this;\n if (force === void 0) { force = true; }\n if (force) {\n this._cylinder.dispose();\n }\n else {\n setTimeout(function () {\n if (!_this._dataFetched) {\n _this._cylinder.dispose();\n }\n }, 0);\n }\n };\n PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {\n if (impostor.mass === 0) {\n return null;\n }\n if (!this._intersectsWithCylinder(impostor)) {\n return null;\n }\n if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {\n return null;\n }\n var impostorObjectCenter = impostor.getObjectCenter();\n var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)\n var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);\n var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);\n var hit = ray.intersectsMesh(impostor.object);\n var contactPoint = hit.pickedPoint;\n if (!contactPoint) {\n return null;\n }\n var absoluteDistanceFromOrigin = hit.distance / this._radius;\n var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();\n var directionToOrigin = contactPoint.normalize();\n if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {\n directionToOrigin = directionToOrigin.negate();\n }\n // TODO: find a more physically based solution\n if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {\n var forceX = directionToOrigin.x * this._strength / 8;\n var forceY = directionToOrigin.y * this._updraftMultiplier;\n var forceZ = directionToOrigin.z * this._strength / 8;\n }\n else {\n var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;\n var forceY = this._originTop.y * this._updraftMultiplier;\n var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;\n }\n var force = new BABYLON.Vector3(forceX, forceY, forceZ);\n force = force.multiplyByFloats(this._strength, this._strength, this._strength);\n return { force: force, contactPoint: impostorObjectCenter };\n };\n PhysicsVortexEvent.prototype._tick = function () {\n var _this = this;\n this._physicsEngine.getImpostors().forEach(function (impostor) {\n var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);\n if (!impostorForceAndContactPoint) {\n return;\n }\n impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);\n });\n };\n /*** Helpers ***/\n PhysicsVortexEvent.prototype._prepareCylinder = function () {\n if (!this._cylinder) {\n this._cylinder = BABYLON.MeshBuilder.CreateCylinder(\"vortexEventCylinder\", {\n height: this._height,\n diameter: this._radius * 2,\n }, this._scene);\n this._cylinder.isVisible = false;\n }\n };\n PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {\n var impostorObject = impostor.object;\n this._prepareCylinder();\n this._cylinder.position = this._cylinderPosition;\n return this._cylinder.intersectsMesh(impostorObject, true);\n };\n return PhysicsVortexEvent;\n }());\n BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;\n /***** Enums *****/\n /**\n * The strenght of the force in correspondence to the distance of the affected object\n */\n var PhysicsRadialImpulseFalloff;\n (function (PhysicsRadialImpulseFalloff) {\n /** Defines that impulse is constant in strength across it's whole radius */\n PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff[\"Constant\"] = 0] = \"Constant\";\n /** DEfines that impulse gets weaker if it's further from the origin */\n PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff[\"Linear\"] = 1] = \"Linear\";\n })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));\n /**\n * The strenght of the force in correspondence to the distance of the affected object\n */\n var PhysicsUpdraftMode;\n (function (PhysicsUpdraftMode) {\n /** Defines that the upstream forces will pull towards the top center of the cylinder */\n PhysicsUpdraftMode[PhysicsUpdraftMode[\"Center\"] = 0] = \"Center\";\n /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */\n PhysicsUpdraftMode[PhysicsUpdraftMode[\"Perpendicular\"] = 1] = \"Perpendicular\";\n })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.physicsHelper.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var CannonJSPlugin = /** @class */ (function () {\n function CannonJSPlugin(_useDeltaForWorldStep, iterations) {\n if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }\n if (iterations === void 0) { iterations = 10; }\n this._useDeltaForWorldStep = _useDeltaForWorldStep;\n this.name = \"CannonJSPlugin\";\n this._physicsMaterials = new Array();\n this._fixedTimeStep = 1 / 60;\n //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html\n this.BJSCANNON = CANNON;\n this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);\n this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);\n this._tmpPosition = BABYLON.Vector3.Zero();\n this._tmpDeltaPosition = BABYLON.Vector3.Zero();\n this._tmpUnityRotation = new BABYLON.Quaternion();\n if (!this.isSupported()) {\n BABYLON.Tools.Error(\"CannonJS is not available. Please make sure you included the js file.\");\n return;\n }\n this._extendNamespace();\n this.world = new this.BJSCANNON.World();\n this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();\n this.world.solver.iterations = iterations;\n }\n CannonJSPlugin.prototype.setGravity = function (gravity) {\n this.world.gravity.copy(gravity);\n };\n CannonJSPlugin.prototype.setTimeStep = function (timeStep) {\n this._fixedTimeStep = timeStep;\n };\n CannonJSPlugin.prototype.getTimeStep = function () {\n return this._fixedTimeStep;\n };\n CannonJSPlugin.prototype.executeStep = function (delta, impostors) {\n this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);\n };\n CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {\n var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);\n var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);\n impostor.physicsBody.applyImpulse(impulse, worldPoint);\n };\n CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {\n var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);\n var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);\n impostor.physicsBody.applyForce(impulse, worldPoint);\n };\n CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {\n //parent-child relationship. Does this impostor has a parent impostor?\n if (impostor.parent) {\n if (impostor.physicsBody) {\n this.removePhysicsBody(impostor);\n //TODO is that needed?\n impostor.forceUpdate();\n }\n return;\n }\n //should a new body be created for this impostor?\n if (impostor.isBodyInitRequired()) {\n var shape = this._createShape(impostor);\n //unregister events, if body is being changed\n var oldBody = impostor.physicsBody;\n if (oldBody) {\n this.removePhysicsBody(impostor);\n }\n //create the body and material\n var material = this._addMaterial(\"mat-\" + impostor.uniqueId, impostor.getParam(\"friction\"), impostor.getParam(\"restitution\"));\n var bodyCreationObject = {\n mass: impostor.getParam(\"mass\"),\n material: material\n };\n // A simple extend, in case native options were used.\n var nativeOptions = impostor.getParam(\"nativeOptions\");\n for (var key in nativeOptions) {\n if (nativeOptions.hasOwnProperty(key)) {\n bodyCreationObject[key] = nativeOptions[key];\n }\n }\n impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);\n impostor.physicsBody.addEventListener(\"collide\", impostor.onCollide);\n this.world.addEventListener(\"preStep\", impostor.beforeStep);\n this.world.addEventListener(\"postStep\", impostor.afterStep);\n impostor.physicsBody.addShape(shape);\n this.world.add(impostor.physicsBody);\n //try to keep the body moving in the right direction by taking old properties.\n //Should be tested!\n if (oldBody) {\n ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {\n impostor.physicsBody[param].copy(oldBody[param]);\n });\n }\n this._processChildMeshes(impostor);\n }\n //now update the body's transformation\n this._updatePhysicsBodyTransformation(impostor);\n };\n CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {\n var _this = this;\n var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];\n var currentRotation = mainImpostor.object.rotationQuaternion;\n if (meshChildren.length) {\n var processMesh = function (localPosition, mesh) {\n if (!currentRotation || !mesh.rotationQuaternion) {\n return;\n }\n var childImpostor = mesh.getPhysicsImpostor();\n if (childImpostor) {\n var parent = childImpostor.parent;\n if (parent !== mainImpostor) {\n var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());\n var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));\n if (childImpostor.physicsBody) {\n _this.removePhysicsBody(childImpostor);\n childImpostor.physicsBody = null;\n }\n childImpostor.parent = mainImpostor;\n childImpostor.resetUpdateFlags();\n mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new _this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new _this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));\n //Add the mass of the children.\n mainImpostor.physicsBody.mass += childImpostor.getParam(\"mass\");\n }\n }\n currentRotation.multiplyInPlace(mesh.rotationQuaternion);\n mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));\n };\n meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));\n }\n };\n CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {\n impostor.physicsBody.removeEventListener(\"collide\", impostor.onCollide);\n this.world.removeEventListener(\"preStep\", impostor.beforeStep);\n this.world.removeEventListener(\"postStep\", impostor.afterStep);\n this.world.remove(impostor.physicsBody);\n };\n CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {\n var mainBody = impostorJoint.mainImpostor.physicsBody;\n var connectedBody = impostorJoint.connectedImpostor.physicsBody;\n if (!mainBody || !connectedBody) {\n return;\n }\n var constraint;\n var jointData = impostorJoint.joint.jointData;\n //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html\n var constraintData = {\n pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,\n pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,\n axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,\n axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,\n maxForce: jointData.nativeParams.maxForce,\n collideConnected: !!jointData.collision\n };\n switch (impostorJoint.joint.type) {\n case BABYLON.PhysicsJoint.HingeJoint:\n case BABYLON.PhysicsJoint.Hinge2Joint:\n constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);\n break;\n case BABYLON.PhysicsJoint.DistanceJoint:\n constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);\n break;\n case BABYLON.PhysicsJoint.SpringJoint:\n var springData = jointData;\n constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {\n restLength: springData.length,\n stiffness: springData.stiffness,\n damping: springData.damping,\n localAnchorA: constraintData.pivotA,\n localAnchorB: constraintData.pivotB\n });\n break;\n case BABYLON.PhysicsJoint.LockJoint:\n constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);\n break;\n case BABYLON.PhysicsJoint.PointToPointJoint:\n case BABYLON.PhysicsJoint.BallAndSocketJoint:\n default:\n constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);\n break;\n }\n //set the collideConnected flag after the creation, since DistanceJoint ignores it.\n constraint.collideConnected = !!jointData.collision;\n impostorJoint.joint.physicsJoint = constraint;\n //don't add spring as constraint, as it is not one.\n if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {\n this.world.addConstraint(constraint);\n }\n else {\n impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {\n constraint.applyForce();\n });\n }\n };\n CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {\n this.world.removeConstraint(impostorJoint.joint.physicsJoint);\n };\n CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {\n var index;\n var mat;\n for (index = 0; index < this._physicsMaterials.length; index++) {\n mat = this._physicsMaterials[index];\n if (mat.friction === friction && mat.restitution === restitution) {\n return mat;\n }\n }\n var currentMat = new this.BJSCANNON.Material(name);\n currentMat.friction = friction;\n currentMat.restitution = restitution;\n this._physicsMaterials.push(currentMat);\n return currentMat;\n };\n CannonJSPlugin.prototype._checkWithEpsilon = function (value) {\n return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;\n };\n CannonJSPlugin.prototype._createShape = function (impostor) {\n var object = impostor.object;\n var returnValue;\n var extendSize = impostor.getObjectExtendSize();\n switch (impostor.type) {\n case BABYLON.PhysicsImpostor.SphereImpostor:\n var radiusX = extendSize.x;\n var radiusY = extendSize.y;\n var radiusZ = extendSize.z;\n returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);\n break;\n //TMP also for cylinder - TODO Cannon supports cylinder natively.\n case BABYLON.PhysicsImpostor.CylinderImpostor:\n returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);\n break;\n case BABYLON.PhysicsImpostor.BoxImpostor:\n var box = extendSize.scale(0.5);\n returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));\n break;\n case BABYLON.PhysicsImpostor.PlaneImpostor:\n BABYLON.Tools.Warn(\"Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead\");\n returnValue = new this.BJSCANNON.Plane();\n break;\n case BABYLON.PhysicsImpostor.MeshImpostor:\n // should transform the vertex data to world coordinates!!\n var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];\n var rawFaces = object.getIndices ? object.getIndices() : [];\n if (!rawVerts)\n return;\n // get only scale! so the object could transform correctly.\n var oldPosition = object.position.clone();\n var oldRotation = object.rotation && object.rotation.clone();\n var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();\n object.position.copyFromFloats(0, 0, 0);\n object.rotation && object.rotation.copyFromFloats(0, 0, 0);\n object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());\n object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();\n var transform = object.computeWorldMatrix(true);\n // convert rawVerts to object space\n var temp = new Array();\n var index;\n for (index = 0; index < rawVerts.length; index += 3) {\n BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);\n }\n BABYLON.Tools.Warn(\"MeshImpostor only collides against spheres.\");\n returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);\n //now set back the transformation!\n object.position.copyFrom(oldPosition);\n oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);\n oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);\n break;\n case BABYLON.PhysicsImpostor.HeightmapImpostor:\n var oldPosition2 = object.position.clone();\n var oldRotation2 = object.rotation && object.rotation.clone();\n var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();\n object.position.copyFromFloats(0, 0, 0);\n object.rotation && object.rotation.copyFromFloats(0, 0, 0);\n object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());\n object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();\n object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);\n returnValue = this._createHeightmap(object);\n object.position.copyFrom(oldPosition2);\n oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);\n oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);\n object.computeWorldMatrix(true);\n break;\n case BABYLON.PhysicsImpostor.ParticleImpostor:\n returnValue = new this.BJSCANNON.Particle();\n break;\n }\n return returnValue;\n };\n CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {\n var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));\n var transform = object.computeWorldMatrix(true);\n // convert rawVerts to object space\n var temp = new Array();\n var index;\n for (index = 0; index < pos.length; index += 3) {\n BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);\n }\n pos = temp;\n var matrix = new Array();\n //For now pointDepth will not be used and will be automatically calculated.\n //Future reference - try and find the best place to add a reference to the pointDepth variable.\n var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);\n var boundingInfo = object.getBoundingInfo();\n var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);\n var minY = boundingInfo.boundingBox.extendSizeWorld.z;\n var elementSize = dim * 2 / arraySize;\n for (var i = 0; i < pos.length; i = i + 3) {\n var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);\n var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);\n var y = -pos[i + 2] + minY;\n if (!matrix[x]) {\n matrix[x] = [];\n }\n if (!matrix[x][z]) {\n matrix[x][z] = y;\n }\n matrix[x][z] = Math.max(y, matrix[x][z]);\n }\n for (var x = 0; x <= arraySize; ++x) {\n if (!matrix[x]) {\n var loc = 1;\n while (!matrix[(x + loc) % arraySize]) {\n loc++;\n }\n matrix[x] = matrix[(x + loc) % arraySize].slice();\n //console.log(\"missing x\", x);\n }\n for (var z = 0; z <= arraySize; ++z) {\n if (!matrix[x][z]) {\n var loc = 1;\n var newValue;\n while (newValue === undefined) {\n newValue = matrix[x][(z + loc++) % arraySize];\n }\n matrix[x][z] = newValue;\n }\n }\n }\n var shape = new this.BJSCANNON.Heightfield(matrix, {\n elementSize: elementSize\n });\n //For future reference, needed for body transformation\n shape.minY = minY;\n return shape;\n };\n CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {\n var object = impostor.object;\n //make sure it is updated...\n object.computeWorldMatrix && object.computeWorldMatrix(true);\n // The delta between the mesh position and the mesh bounding box center\n var bInfo = object.getBoundingInfo();\n if (!bInfo)\n return;\n var center = impostor.getObjectCenter();\n //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)\n this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));\n this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);\n this._tmpPosition.copyFrom(center);\n var quaternion = object.rotationQuaternion;\n if (!quaternion) {\n return;\n }\n //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.\n if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {\n //-90 DEG in X, precalculated\n quaternion = quaternion.multiply(this._minus90X);\n //Invert! (Precalculated, 90 deg in X)\n //No need to clone. this will never change.\n impostor.setDeltaRotation(this._plus90X);\n }\n //If it is a heightfield, if should be centered.\n if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {\n var mesh = object;\n var boundingInfo = mesh.getBoundingInfo();\n //calculate the correct body position:\n var rotationQuaternion = mesh.rotationQuaternion;\n mesh.rotationQuaternion = this._tmpUnityRotation;\n mesh.computeWorldMatrix(true);\n //get original center with no rotation\n var c = center.clone();\n var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);\n //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)\n var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);\n mesh.setPreTransformMatrix(p);\n mesh.computeWorldMatrix(true);\n //calculate the translation\n var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();\n this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);\n //add it inverted to the delta\n this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));\n this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;\n //rotation is back\n mesh.rotationQuaternion = rotationQuaternion;\n mesh.setPreTransformMatrix(oldPivot);\n mesh.computeWorldMatrix(true);\n }\n else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {\n this._tmpDeltaPosition.copyFromFloats(0, 0, 0);\n //this._tmpPosition.copyFrom(object.position);\n }\n impostor.setDeltaPosition(this._tmpDeltaPosition);\n //Now update the impostor object\n impostor.physicsBody.position.copy(this._tmpPosition);\n impostor.physicsBody.quaternion.copy(quaternion);\n };\n CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {\n impostor.object.position.copyFrom(impostor.physicsBody.position);\n if (impostor.object.rotationQuaternion) {\n impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);\n }\n };\n CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {\n impostor.physicsBody.position.copy(newPosition);\n impostor.physicsBody.quaternion.copy(newRotation);\n };\n CannonJSPlugin.prototype.isSupported = function () {\n return this.BJSCANNON !== undefined;\n };\n CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {\n impostor.physicsBody.velocity.copy(velocity);\n };\n CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {\n impostor.physicsBody.angularVelocity.copy(velocity);\n };\n CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {\n var v = impostor.physicsBody.velocity;\n if (!v) {\n return null;\n }\n return new BABYLON.Vector3(v.x, v.y, v.z);\n };\n CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {\n var v = impostor.physicsBody.angularVelocity;\n if (!v) {\n return null;\n }\n return new BABYLON.Vector3(v.x, v.y, v.z);\n };\n CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {\n impostor.physicsBody.mass = mass;\n impostor.physicsBody.updateMassProperties();\n };\n CannonJSPlugin.prototype.getBodyMass = function (impostor) {\n return impostor.physicsBody.mass;\n };\n CannonJSPlugin.prototype.getBodyFriction = function (impostor) {\n return impostor.physicsBody.material.friction;\n };\n CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {\n impostor.physicsBody.material.friction = friction;\n };\n CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {\n return impostor.physicsBody.material.restitution;\n };\n CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {\n impostor.physicsBody.material.restitution = restitution;\n };\n CannonJSPlugin.prototype.sleepBody = function (impostor) {\n impostor.physicsBody.sleep();\n };\n CannonJSPlugin.prototype.wakeUpBody = function (impostor) {\n impostor.physicsBody.wakeUp();\n };\n CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {\n joint.physicsJoint.distance = maxDistance;\n };\n // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {\n // if (!motorIndex) {\n // joint.physicsJoint.enableMotor();\n // }\n // }\n // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {\n // if (!motorIndex) {\n // joint.physicsJoint.disableMotor();\n // }\n // }\n CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {\n if (!motorIndex) {\n joint.physicsJoint.enableMotor();\n joint.physicsJoint.setMotorSpeed(speed);\n if (maxForce) {\n this.setLimit(joint, maxForce);\n }\n }\n };\n CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {\n joint.physicsJoint.motorEquation.maxForce = upperLimit;\n joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;\n };\n CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {\n var body = impostor.physicsBody;\n mesh.position.x = body.position.x;\n mesh.position.y = body.position.y;\n mesh.position.z = body.position.z;\n if (mesh.rotationQuaternion) {\n mesh.rotationQuaternion.x = body.quaternion.x;\n mesh.rotationQuaternion.y = body.quaternion.y;\n mesh.rotationQuaternion.z = body.quaternion.z;\n mesh.rotationQuaternion.w = body.quaternion.w;\n }\n };\n CannonJSPlugin.prototype.getRadius = function (impostor) {\n var shape = impostor.physicsBody.shapes[0];\n return shape.boundingSphereRadius;\n };\n CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {\n var shape = impostor.physicsBody.shapes[0];\n result.x = shape.halfExtents.x * 2;\n result.y = shape.halfExtents.y * 2;\n result.z = shape.halfExtents.z * 2;\n };\n CannonJSPlugin.prototype.dispose = function () {\n };\n CannonJSPlugin.prototype._extendNamespace = function () {\n //this will force cannon to execute at least one step when using interpolation\n var step_tmp1 = new this.BJSCANNON.Vec3();\n var Engine = this.BJSCANNON;\n this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {\n maxSubSteps = maxSubSteps || 10;\n timeSinceLastCalled = timeSinceLastCalled || 0;\n if (timeSinceLastCalled === 0) {\n this.internalStep(dt);\n this.time += dt;\n }\n else {\n var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);\n internalSteps = Math.min(internalSteps, maxSubSteps) || 1;\n var t0 = performance.now();\n for (var i = 0; i !== internalSteps; i++) {\n this.internalStep(dt);\n if (performance.now() - t0 > dt * 1000) {\n break;\n }\n }\n this.time += timeSinceLastCalled;\n var h = this.time % dt;\n var h_div_dt = h / dt;\n var interpvelo = step_tmp1;\n var bodies = this.bodies;\n for (var j = 0; j !== bodies.length; j++) {\n var b = bodies[j];\n if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {\n b.position.vsub(b.previousPosition, interpvelo);\n interpvelo.scale(h_div_dt, interpvelo);\n b.position.vadd(interpvelo, b.interpolatedPosition);\n }\n else {\n b.interpolatedPosition.copy(b.position);\n b.interpolatedQuaternion.copy(b.quaternion);\n }\n }\n }\n };\n };\n return CannonJSPlugin;\n }());\n BABYLON.CannonJSPlugin = CannonJSPlugin;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.cannonJSPlugin.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var OimoJSPlugin = /** @class */ (function () {\n function OimoJSPlugin(iterations) {\n this.name = \"OimoJSPlugin\";\n this._tmpImpostorsArray = [];\n this._tmpPositionVector = BABYLON.Vector3.Zero();\n this.BJSOIMO = OIMO;\n this.world = new this.BJSOIMO.World({\n iterations: iterations\n });\n this.world.clear();\n }\n OimoJSPlugin.prototype.setGravity = function (gravity) {\n this.world.gravity.copy(gravity);\n };\n OimoJSPlugin.prototype.setTimeStep = function (timeStep) {\n this.world.timeStep = timeStep;\n };\n OimoJSPlugin.prototype.getTimeStep = function () {\n return this.world.timeStep;\n };\n OimoJSPlugin.prototype.executeStep = function (delta, impostors) {\n var _this = this;\n impostors.forEach(function (impostor) {\n impostor.beforeStep();\n });\n this.world.step();\n impostors.forEach(function (impostor) {\n impostor.afterStep();\n //update the ordered impostors array\n _this._tmpImpostorsArray[impostor.uniqueId] = impostor;\n });\n //check for collisions\n var contact = this.world.contacts;\n while (contact !== null) {\n if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {\n contact = contact.next;\n continue;\n }\n //is this body colliding with any other? get the impostor\n var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];\n var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];\n if (!mainImpostor || !collidingImpostor) {\n contact = contact.next;\n continue;\n }\n mainImpostor.onCollide({ body: collidingImpostor.physicsBody });\n collidingImpostor.onCollide({ body: mainImpostor.physicsBody });\n contact = contact.next;\n }\n };\n OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {\n var mass = impostor.physicsBody.mass;\n impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));\n };\n OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {\n BABYLON.Tools.Warn(\"Oimo doesn't support applying force. Using impule instead.\");\n this.applyImpulse(impostor, force, contactPoint);\n };\n OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {\n var _this = this;\n //parent-child relationship. Does this impostor has a parent impostor?\n if (impostor.parent) {\n if (impostor.physicsBody) {\n this.removePhysicsBody(impostor);\n //TODO is that needed?\n impostor.forceUpdate();\n }\n return;\n }\n if (impostor.isBodyInitRequired()) {\n var bodyConfig = {\n name: impostor.uniqueId,\n //Oimo must have mass, also for static objects.\n config: [impostor.getParam(\"mass\") || 1, impostor.getParam(\"friction\"), impostor.getParam(\"restitution\")],\n size: [],\n type: [],\n pos: [],\n posShape: [],\n rot: [],\n rotShape: [],\n move: impostor.getParam(\"mass\") !== 0,\n density: impostor.getParam(\"mass\"),\n friction: impostor.getParam(\"friction\"),\n restitution: impostor.getParam(\"restitution\"),\n //Supporting older versions of Oimo\n world: this.world\n };\n var impostors = [impostor];\n var addToArray = function (parent) {\n if (!parent.getChildMeshes)\n return;\n parent.getChildMeshes().forEach(function (m) {\n if (m.physicsImpostor) {\n impostors.push(m.physicsImpostor);\n //m.physicsImpostor._init();\n }\n });\n };\n addToArray(impostor.object);\n var checkWithEpsilon_1 = function (value) {\n return Math.max(value, BABYLON.PhysicsEngine.Epsilon);\n };\n var globalQuaternion_1 = new BABYLON.Quaternion();\n impostors.forEach(function (i) {\n if (!i.object.rotationQuaternion) {\n return;\n }\n //get the correct bounding box\n var oldQuaternion = i.object.rotationQuaternion;\n globalQuaternion_1 = oldQuaternion.clone();\n var rot = oldQuaternion.toEulerAngles();\n var extendSize = i.getObjectExtendSize();\n var radToDeg = 57.295779513082320876;\n if (i === impostor) {\n var center = impostor.getObjectCenter();\n impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);\n _this._tmpPositionVector.divideInPlace(impostor.object.scaling);\n //Can also use Array.prototype.push.apply\n bodyConfig.pos.push(center.x);\n bodyConfig.pos.push(center.y);\n bodyConfig.pos.push(center.z);\n bodyConfig.posShape.push(0, 0, 0);\n //tmp solution\n bodyConfig.rot.push(0);\n bodyConfig.rot.push(0);\n bodyConfig.rot.push(0);\n bodyConfig.rotShape.push(0, 0, 0);\n }\n else {\n var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());\n bodyConfig.posShape.push(localPosition.x);\n bodyConfig.posShape.push(localPosition.y);\n bodyConfig.posShape.push(localPosition.z);\n bodyConfig.pos.push(0, 0, 0);\n //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged\n bodyConfig.rot.push(0);\n bodyConfig.rot.push(0);\n bodyConfig.rot.push(0);\n bodyConfig.rotShape.push(rot.x * radToDeg);\n bodyConfig.rotShape.push(rot.y * radToDeg);\n bodyConfig.rotShape.push(rot.z * radToDeg);\n }\n // register mesh\n switch (i.type) {\n case BABYLON.PhysicsImpostor.ParticleImpostor:\n BABYLON.Tools.Warn(\"No Particle support in OIMO.js. using SphereImpostor instead\");\n case BABYLON.PhysicsImpostor.SphereImpostor:\n var radiusX = extendSize.x;\n var radiusY = extendSize.y;\n var radiusZ = extendSize.z;\n var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;\n bodyConfig.type.push('sphere');\n //due to the way oimo works with compounds, add 3 times\n bodyConfig.size.push(size);\n bodyConfig.size.push(size);\n bodyConfig.size.push(size);\n break;\n case BABYLON.PhysicsImpostor.CylinderImpostor:\n var sizeX = checkWithEpsilon_1(extendSize.x) / 2;\n var sizeY = checkWithEpsilon_1(extendSize.y);\n bodyConfig.type.push('cylinder');\n bodyConfig.size.push(sizeX);\n bodyConfig.size.push(sizeY);\n //due to the way oimo works with compounds, add one more value.\n bodyConfig.size.push(sizeY);\n break;\n case BABYLON.PhysicsImpostor.PlaneImpostor:\n case BABYLON.PhysicsImpostor.BoxImpostor:\n default:\n var sizeX = checkWithEpsilon_1(extendSize.x);\n var sizeY = checkWithEpsilon_1(extendSize.y);\n var sizeZ = checkWithEpsilon_1(extendSize.z);\n bodyConfig.type.push('box');\n //if (i === impostor) {\n bodyConfig.size.push(sizeX);\n bodyConfig.size.push(sizeY);\n bodyConfig.size.push(sizeZ);\n //} else {\n // bodyConfig.size.push(0,0,0);\n //}\n break;\n }\n //actually not needed, but hey...\n i.object.rotationQuaternion = oldQuaternion;\n });\n impostor.physicsBody = this.world.add(bodyConfig);\n // set the quaternion, ignoring the previously defined (euler) rotation\n impostor.physicsBody.resetQuaternion(globalQuaternion_1);\n // update with delta 0, so the body will reveive the new rotation.\n impostor.physicsBody.updatePosition(0);\n }\n else {\n this._tmpPositionVector.copyFromFloats(0, 0, 0);\n }\n impostor.setDeltaPosition(this._tmpPositionVector);\n //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);\n //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);\n };\n OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {\n //impostor.physicsBody.dispose();\n //Same as : (older oimo versions)\n this.world.removeRigidBody(impostor.physicsBody);\n };\n OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {\n var mainBody = impostorJoint.mainImpostor.physicsBody;\n var connectedBody = impostorJoint.connectedImpostor.physicsBody;\n if (!mainBody || !connectedBody) {\n return;\n }\n var jointData = impostorJoint.joint.jointData;\n var options = jointData.nativeParams || {};\n var type;\n var nativeJointData = {\n body1: mainBody,\n body2: connectedBody,\n axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),\n axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),\n pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),\n pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),\n min: options.min,\n max: options.max,\n collision: options.collision || jointData.collision,\n spring: options.spring,\n //supporting older version of Oimo\n world: this.world\n };\n switch (impostorJoint.joint.type) {\n case BABYLON.PhysicsJoint.BallAndSocketJoint:\n type = \"jointBall\";\n break;\n case BABYLON.PhysicsJoint.SpringJoint:\n BABYLON.Tools.Warn(\"OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead\");\n var springData = jointData;\n nativeJointData.min = springData.length || nativeJointData.min;\n //Max should also be set, just make sure it is at least min\n nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);\n case BABYLON.PhysicsJoint.DistanceJoint:\n type = \"jointDistance\";\n nativeJointData.max = jointData.maxDistance;\n break;\n case BABYLON.PhysicsJoint.PrismaticJoint:\n type = \"jointPrisme\";\n break;\n case BABYLON.PhysicsJoint.SliderJoint:\n type = \"jointSlide\";\n break;\n case BABYLON.PhysicsJoint.WheelJoint:\n type = \"jointWheel\";\n break;\n case BABYLON.PhysicsJoint.HingeJoint:\n default:\n type = \"jointHinge\";\n break;\n }\n nativeJointData.type = type;\n impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);\n };\n OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {\n //Bug in Oimo prevents us from disposing a joint in the playground\n //joint.joint.physicsJoint.dispose();\n //So we will bruteforce it!\n try {\n this.world.removeJoint(impostorJoint.joint.physicsJoint);\n }\n catch (e) {\n BABYLON.Tools.Warn(e);\n }\n };\n OimoJSPlugin.prototype.isSupported = function () {\n return this.BJSOIMO !== undefined;\n };\n OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {\n if (!impostor.physicsBody.sleeping) {\n //TODO check that\n /*if (impostor.physicsBody.shapes.next) {\n var parentShape = this._getLastShape(impostor.physicsBody);\n impostor.object.position.copyFrom(parentShape.position);\n console.log(parentShape.position);\n } else {*/\n impostor.object.position.copyFrom(impostor.physicsBody.getPosition());\n //}\n if (impostor.object.rotationQuaternion) {\n impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());\n }\n }\n };\n OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {\n var body = impostor.physicsBody;\n body.position.copy(newPosition);\n body.orientation.copy(newRotation);\n body.syncShapes();\n body.awake();\n };\n /*private _getLastShape(body: any): any {\n var lastShape = body.shapes;\n while (lastShape.next) {\n lastShape = lastShape.next;\n }\n return lastShape;\n }*/\n OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {\n impostor.physicsBody.linearVelocity.copy(velocity);\n };\n OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {\n impostor.physicsBody.angularVelocity.copy(velocity);\n };\n OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {\n var v = impostor.physicsBody.linearVelocity;\n if (!v) {\n return null;\n }\n return new BABYLON.Vector3(v.x, v.y, v.z);\n };\n OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {\n var v = impostor.physicsBody.angularVelocity;\n if (!v) {\n return null;\n }\n return new BABYLON.Vector3(v.x, v.y, v.z);\n };\n OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {\n var staticBody = mass === 0;\n //this will actually set the body's density and not its mass.\n //But this is how oimo treats the mass variable.\n impostor.physicsBody.shapes.density = staticBody ? 1 : mass;\n impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);\n };\n OimoJSPlugin.prototype.getBodyMass = function (impostor) {\n return impostor.physicsBody.shapes.density;\n };\n OimoJSPlugin.prototype.getBodyFriction = function (impostor) {\n return impostor.physicsBody.shapes.friction;\n };\n OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {\n impostor.physicsBody.shapes.friction = friction;\n };\n OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {\n return impostor.physicsBody.shapes.restitution;\n };\n OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {\n impostor.physicsBody.shapes.restitution = restitution;\n };\n OimoJSPlugin.prototype.sleepBody = function (impostor) {\n impostor.physicsBody.sleep();\n };\n OimoJSPlugin.prototype.wakeUpBody = function (impostor) {\n impostor.physicsBody.awake();\n };\n OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {\n joint.physicsJoint.limitMotor.upperLimit = maxDistance;\n if (minDistance !== void 0) {\n joint.physicsJoint.limitMotor.lowerLimit = minDistance;\n }\n };\n OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {\n //TODO separate rotational and transational motors.\n var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;\n if (motor) {\n motor.setMotor(speed, maxForce);\n }\n };\n OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {\n //TODO separate rotational and transational motors.\n var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;\n if (motor) {\n motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);\n }\n };\n OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {\n var body = impostor.physicsBody;\n mesh.position.x = body.position.x;\n mesh.position.y = body.position.y;\n mesh.position.z = body.position.z;\n if (mesh.rotationQuaternion) {\n mesh.rotationQuaternion.x = body.orientation.x;\n mesh.rotationQuaternion.y = body.orientation.y;\n mesh.rotationQuaternion.z = body.orientation.z;\n mesh.rotationQuaternion.w = body.orientation.s;\n }\n };\n OimoJSPlugin.prototype.getRadius = function (impostor) {\n return impostor.physicsBody.shapes.radius;\n };\n OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {\n var shape = impostor.physicsBody.shapes;\n result.x = shape.halfWidth * 2;\n result.y = shape.halfHeight * 2;\n result.z = shape.halfDepth * 2;\n };\n OimoJSPlugin.prototype.dispose = function () {\n this.world.clear();\n };\n return OimoJSPlugin;\n }());\n BABYLON.OimoJSPlugin = OimoJSPlugin;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.oimoJSPlugin.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html\n // All values and structures referenced from:\n // http://msdn.microsoft.com/en-us/library/bb943991.aspx/\n var DDS_MAGIC = 0x20534444;\n var \n //DDSD_CAPS = 0x1,\n //DDSD_HEIGHT = 0x2,\n //DDSD_WIDTH = 0x4,\n //DDSD_PITCH = 0x8,\n //DDSD_PIXELFORMAT = 0x1000,\n DDSD_MIPMAPCOUNT = 0x20000;\n //DDSD_LINEARSIZE = 0x80000,\n //DDSD_DEPTH = 0x800000;\n // var DDSCAPS_COMPLEX = 0x8,\n // DDSCAPS_MIPMAP = 0x400000,\n // DDSCAPS_TEXTURE = 0x1000;\n var DDSCAPS2_CUBEMAP = 0x200;\n // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,\n // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,\n // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,\n // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,\n // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,\n // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,\n // DDSCAPS2_VOLUME = 0x200000;\n var \n //DDPF_ALPHAPIXELS = 0x1,\n //DDPF_ALPHA = 0x2,\n DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, \n //DDPF_YUV = 0x200,\n DDPF_LUMINANCE = 0x20000;\n function FourCCToInt32(value) {\n return value.charCodeAt(0) +\n (value.charCodeAt(1) << 8) +\n (value.charCodeAt(2) << 16) +\n (value.charCodeAt(3) << 24);\n }\n function Int32ToFourCC(value) {\n return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);\n }\n var FOURCC_DXT1 = FourCCToInt32(\"DXT1\");\n var FOURCC_DXT3 = FourCCToInt32(\"DXT3\");\n var FOURCC_DXT5 = FourCCToInt32(\"DXT5\");\n var FOURCC_DX10 = FourCCToInt32(\"DX10\");\n var FOURCC_D3DFMT_R16G16B16A16F = 113;\n var FOURCC_D3DFMT_R32G32B32A32F = 116;\n var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;\n var DXGI_FORMAT_B8G8R8X8_UNORM = 88;\n var headerLengthInt = 31; // The header length in 32 bit ints\n // Offsets into the header array\n var off_magic = 0;\n var off_size = 1;\n var off_flags = 2;\n var off_height = 3;\n var off_width = 4;\n var off_mipmapCount = 7;\n var off_pfFlags = 20;\n var off_pfFourCC = 21;\n var off_RGBbpp = 22;\n var off_RMask = 23;\n var off_GMask = 24;\n var off_BMask = 25;\n var off_AMask = 26;\n // var off_caps1 = 27;\n var off_caps2 = 28;\n // var off_caps3 = 29;\n // var off_caps4 = 30;\n var off_dxgiFormat = 32;\n ;\n var DDSTools = /** @class */ (function () {\n function DDSTools() {\n }\n DDSTools.GetDDSInfo = function (arrayBuffer) {\n var header = new Int32Array(arrayBuffer, 0, headerLengthInt);\n var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);\n var mipmapCount = 1;\n if (header[off_flags] & DDSD_MIPMAPCOUNT) {\n mipmapCount = Math.max(1, header[off_mipmapCount]);\n }\n var fourCC = header[off_pfFourCC];\n var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;\n var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n switch (fourCC) {\n case FOURCC_D3DFMT_R16G16B16A16F:\n textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n break;\n case FOURCC_D3DFMT_R32G32B32A32F:\n textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n break;\n case FOURCC_DX10:\n if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {\n textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n break;\n }\n }\n return {\n width: header[off_width],\n height: header[off_height],\n mipmapCount: mipmapCount,\n isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,\n isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,\n isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,\n isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,\n isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),\n dxgiFormat: dxgiFormat,\n textureType: textureType\n };\n };\n DDSTools._ToHalfFloat = function (value) {\n if (!DDSTools._FloatView) {\n DDSTools._FloatView = new Float32Array(1);\n DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);\n }\n DDSTools._FloatView[0] = value;\n var x = DDSTools._Int32View[0];\n var bits = (x >> 16) & 0x8000; /* Get the sign */\n var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */\n var e = (x >> 23) & 0xff; /* Using int is faster here */\n /* If zero, or denormal, or exponent underflows too much for a denormal\n * half, return signed zero. */\n if (e < 103) {\n return bits;\n }\n /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */\n if (e > 142) {\n bits |= 0x7c00;\n /* If exponent was 0xff and one mantissa bit was set, it means NaN,\n * not Inf, so make sure we set one mantissa bit too. */\n bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);\n return bits;\n }\n /* If exponent underflows but not too much, return a denormal */\n if (e < 113) {\n m |= 0x0800;\n /* Extra rounding may overflow and set mantissa to 0 and exponent\n * to 1, which is OK. */\n bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);\n return bits;\n }\n bits |= ((e - 112) << 10) | (m >> 1);\n bits += m & 1;\n return bits;\n };\n DDSTools._FromHalfFloat = function (value) {\n var s = (value & 0x8000) >> 15;\n var e = (value & 0x7C00) >> 10;\n var f = value & 0x03FF;\n if (e === 0) {\n return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));\n }\n else if (e == 0x1F) {\n return f ? NaN : ((s ? -1 : 1) * Infinity);\n }\n return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));\n };\n DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {\n var destArray = new Float32Array(dataLength);\n var srcData = new Uint16Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 4;\n destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);\n destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);\n destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = lod;\n }\n else {\n destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);\n }\n index += 4;\n }\n }\n return destArray;\n };\n DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {\n if (DDSTools.StoreLODInAlphaChannel) {\n var destArray = new Uint16Array(dataLength);\n var srcData = new Uint16Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 4;\n destArray[index] = srcData[srcPos];\n destArray[index + 1] = srcData[srcPos + 1];\n destArray[index + 2] = srcData[srcPos + 2];\n destArray[index + 3] = DDSTools._ToHalfFloat(lod);\n index += 4;\n }\n }\n return destArray;\n }\n return new Uint16Array(arrayBuffer, dataOffset, dataLength);\n };\n DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {\n if (DDSTools.StoreLODInAlphaChannel) {\n var destArray = new Float32Array(dataLength);\n var srcData = new Float32Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 4;\n destArray[index] = srcData[srcPos];\n destArray[index + 1] = srcData[srcPos + 1];\n destArray[index + 2] = srcData[srcPos + 2];\n destArray[index + 3] = lod;\n index += 4;\n }\n }\n return destArray;\n }\n return new Float32Array(arrayBuffer, dataOffset, dataLength);\n };\n DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {\n var destArray = new Uint8Array(dataLength);\n var srcData = new Float32Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 4;\n destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;\n destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;\n destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = lod;\n }\n else {\n destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;\n }\n index += 4;\n }\n }\n return destArray;\n };\n DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {\n var destArray = new Uint8Array(dataLength);\n var srcData = new Uint16Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 4;\n destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;\n destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;\n destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = lod;\n }\n else {\n destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;\n }\n index += 4;\n }\n }\n return destArray;\n };\n DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {\n var byteArray = new Uint8Array(dataLength);\n var srcData = new Uint8Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 4;\n byteArray[index] = srcData[srcPos + rOffset];\n byteArray[index + 1] = srcData[srcPos + gOffset];\n byteArray[index + 2] = srcData[srcPos + bOffset];\n byteArray[index + 3] = srcData[srcPos + aOffset];\n index += 4;\n }\n }\n return byteArray;\n };\n DDSTools._ExtractLongWordOrder = function (value) {\n if (value === 0 || value === 255 || value === -16777216) {\n return 0;\n }\n return 1 + DDSTools._ExtractLongWordOrder(value >> 8);\n };\n DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {\n var byteArray = new Uint8Array(dataLength);\n var srcData = new Uint8Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width) * 3;\n byteArray[index] = srcData[srcPos + rOffset];\n byteArray[index + 1] = srcData[srcPos + gOffset];\n byteArray[index + 2] = srcData[srcPos + bOffset];\n index += 3;\n }\n }\n return byteArray;\n };\n DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {\n var byteArray = new Uint8Array(dataLength);\n var srcData = new Uint8Array(arrayBuffer, dataOffset);\n var index = 0;\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var srcPos = (x + y * width);\n byteArray[index] = srcData[srcPos];\n index++;\n }\n }\n return byteArray;\n };\n /**\n * Uploads DDS Levels to a Babylon Texture\n * @hidden\n */\n DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {\n if (lodIndex === void 0) { lodIndex = -1; }\n var sphericalPolynomialFaces = null;\n if (info.sphericalPolynomial) {\n sphericalPolynomialFaces = new Array();\n }\n var ext = engine.getCaps().s3tc;\n var header = new Int32Array(arrayBuffer, 0, headerLengthInt);\n var fourCC, width, height, dataLength = 0, dataOffset;\n var byteArray, mipmapCount, mip;\n var internalCompressedFormat = 0;\n var blockBytes = 1;\n if (header[off_magic] !== DDS_MAGIC) {\n BABYLON.Tools.Error(\"Invalid magic number in DDS header\");\n return;\n }\n if (!info.isFourCC && !info.isRGB && !info.isLuminance) {\n BABYLON.Tools.Error(\"Unsupported format, must contain a FourCC, RGB or LUMINANCE code\");\n return;\n }\n if (info.isCompressed && !ext) {\n BABYLON.Tools.Error(\"Compressed textures are not supported on this platform.\");\n return;\n }\n var bpp = header[off_RGBbpp];\n dataOffset = header[off_size] + 4;\n var computeFormats = false;\n if (info.isFourCC) {\n fourCC = header[off_pfFourCC];\n switch (fourCC) {\n case FOURCC_DXT1:\n blockBytes = 8;\n internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;\n break;\n case FOURCC_DXT3:\n blockBytes = 16;\n internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;\n break;\n case FOURCC_DXT5:\n blockBytes = 16;\n internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;\n break;\n case FOURCC_D3DFMT_R16G16B16A16F:\n computeFormats = true;\n break;\n case FOURCC_D3DFMT_R32G32B32A32F:\n computeFormats = true;\n break;\n case FOURCC_DX10:\n // There is an additionnal header so dataOffset need to be changed\n dataOffset += 5 * 4; // 5 uints\n var supported = false;\n switch (info.dxgiFormat) {\n case DXGI_FORMAT_R16G16B16A16_FLOAT:\n computeFormats = true;\n supported = true;\n break;\n case DXGI_FORMAT_B8G8R8X8_UNORM:\n info.isRGB = true;\n info.isFourCC = false;\n bpp = 32;\n supported = true;\n break;\n }\n if (supported) {\n break;\n }\n default:\n console.error(\"Unsupported FourCC code:\", Int32ToFourCC(fourCC));\n return;\n }\n }\n var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);\n var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);\n var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);\n var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);\n if (computeFormats) {\n internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);\n }\n mipmapCount = 1;\n if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {\n mipmapCount = Math.max(1, header[off_mipmapCount]);\n }\n for (var face = 0; face < faces; face++) {\n width = header[off_width];\n height = header[off_height];\n for (mip = 0; mip < mipmapCount; ++mip) {\n if (lodIndex === -1 || lodIndex === mip) {\n // In case of fixed LOD, if the lod has just been uploaded, early exit.\n var i = (lodIndex === -1) ? mip : 0;\n if (!info.isCompressed && info.isFourCC) {\n texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;\n dataLength = width * height * 4;\n var floatArray = null;\n if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation\n if (bpp === 128) {\n floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));\n }\n }\n else if (bpp === 64) {\n floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));\n }\n }\n texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n else {\n if (bpp === 128) {\n texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;\n floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(floatArray);\n }\n }\n else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {\n texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;\n floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(floatArray);\n }\n }\n else { // 64\n texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));\n }\n }\n }\n if (floatArray) {\n engine._uploadDataToTextureDirectly(texture, floatArray, face, i);\n }\n }\n else if (info.isRGB) {\n texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n if (bpp === 24) {\n texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;\n dataLength = width * height * 3;\n byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);\n engine._uploadDataToTextureDirectly(texture, byteArray, face, i);\n }\n else { // 32\n texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;\n dataLength = width * height * 4;\n byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);\n engine._uploadDataToTextureDirectly(texture, byteArray, face, i);\n }\n }\n else if (info.isLuminance) {\n var unpackAlignment = engine._getUnpackAlignement();\n var unpaddedRowSize = width;\n var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;\n dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;\n byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);\n texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;\n texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n engine._uploadDataToTextureDirectly(texture, byteArray, face, i);\n }\n else {\n dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;\n byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);\n texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);\n }\n }\n dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;\n width *= 0.5;\n height *= 0.5;\n width = Math.max(1.0, width);\n height = Math.max(1.0, height);\n }\n if (currentFace !== undefined) {\n // Loading a single face\n break;\n }\n }\n if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {\n info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({\n size: header[off_width],\n right: sphericalPolynomialFaces[0],\n left: sphericalPolynomialFaces[1],\n up: sphericalPolynomialFaces[2],\n down: sphericalPolynomialFaces[3],\n front: sphericalPolynomialFaces[4],\n back: sphericalPolynomialFaces[5],\n format: BABYLON.Engine.TEXTUREFORMAT_RGBA,\n type: BABYLON.Engine.TEXTURETYPE_FLOAT,\n gammaSpace: false,\n });\n }\n else {\n info.sphericalPolynomial = undefined;\n }\n };\n DDSTools.StoreLODInAlphaChannel = false;\n return DDSTools;\n }());\n BABYLON.DDSTools = DDSTools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.dds.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Implementation of the DDS Texture Loader.\n */\n var DDSTextureLoader = /** @class */ (function () {\n function DDSTextureLoader() {\n /**\n * Defines wether the loader supports cascade loading the different faces.\n */\n this.supportCascades = true;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @param fallback defines the fallback internal texture if any\n * @param isBase64 defines whether the texture is encoded as a base64\n * @param isBuffer defines whether the texture data are stored as a buffer\n * @returns true if the loader can load the specified file\n */\n DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {\n return extension.indexOf(\".dds\") === 0;\n };\n /**\n * Transform the url before loading if required.\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the transformed texture\n */\n DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {\n return rootUrl;\n };\n /**\n * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the fallback texture\n */\n DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {\n return null;\n };\n /**\n * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n * @param onError defines the callback to trigger in case of error\n */\n DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {\n var engine = texture.getEngine();\n var info;\n var loadMipmap = false;\n if (Array.isArray(imgs)) {\n for (var index = 0; index < imgs.length; index++) {\n var data_1 = imgs[index];\n info = BABYLON.DDSTools.GetDDSInfo(data_1);\n texture.width = info.width;\n texture.height = info.height;\n loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;\n engine._unpackFlipY(info.isCompressed);\n BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);\n if (!info.isFourCC && info.mipmapCount === 1) {\n engine.generateMipMapsForCubemap(texture);\n }\n }\n }\n else {\n var data = imgs;\n info = BABYLON.DDSTools.GetDDSInfo(data);\n texture.width = info.width;\n texture.height = info.height;\n if (createPolynomials) {\n info.sphericalPolynomial = new BABYLON.SphericalPolynomial();\n }\n loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;\n engine._unpackFlipY(info.isCompressed);\n BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);\n if (!info.isFourCC && info.mipmapCount === 1) {\n engine.generateMipMapsForCubemap(texture);\n }\n }\n engine._setCubeMapTextureParams(loadMipmap);\n texture.isReady = true;\n if (onLoad) {\n onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });\n }\n };\n /**\n * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n DDSTextureLoader.prototype.loadData = function (data, texture, callback) {\n var info = BABYLON.DDSTools.GetDDSInfo(data);\n var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);\n callback(info.width, info.height, !loadMipmap, info.isFourCC, function () {\n BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);\n });\n };\n return DDSTextureLoader;\n }());\n // Register the loader.\n BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.ddsTextureLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /*\n * Based on jsTGALoader - Javascript loader for TGA file\n * By Vincent Thibault\n * @blog http://blog.robrowser.com/javascript-tga-loader.html\n */\n var TGATools = /** @class */ (function () {\n function TGATools() {\n }\n TGATools.GetTGAHeader = function (data) {\n var offset = 0;\n var header = {\n id_length: data[offset++],\n colormap_type: data[offset++],\n image_type: data[offset++],\n colormap_index: data[offset++] | data[offset++] << 8,\n colormap_length: data[offset++] | data[offset++] << 8,\n colormap_size: data[offset++],\n origin: [\n data[offset++] | data[offset++] << 8,\n data[offset++] | data[offset++] << 8\n ],\n width: data[offset++] | data[offset++] << 8,\n height: data[offset++] | data[offset++] << 8,\n pixel_size: data[offset++],\n flags: data[offset++]\n };\n return header;\n };\n /**\n * Uploads TGA content to a Babylon Texture\n * @hidden\n */\n TGATools.UploadContent = function (texture, data) {\n // Not enough data to contain header ?\n if (data.length < 19) {\n BABYLON.Tools.Error(\"Unable to load TGA file - Not enough data to contain header\");\n return;\n }\n // Read Header\n var offset = 18;\n var header = TGATools.GetTGAHeader(data);\n // Assume it's a valid Targa file.\n if (header.id_length + offset > data.length) {\n BABYLON.Tools.Error(\"Unable to load TGA file - Not enough data\");\n return;\n }\n // Skip not needed data\n offset += header.id_length;\n var use_rle = false;\n var use_pal = false;\n var use_grey = false;\n // Get some informations.\n switch (header.image_type) {\n case TGATools._TYPE_RLE_INDEXED:\n use_rle = true;\n case TGATools._TYPE_INDEXED:\n use_pal = true;\n break;\n case TGATools._TYPE_RLE_RGB:\n use_rle = true;\n case TGATools._TYPE_RGB:\n // use_rgb = true;\n break;\n case TGATools._TYPE_RLE_GREY:\n use_rle = true;\n case TGATools._TYPE_GREY:\n use_grey = true;\n break;\n }\n var pixel_data;\n // var numAlphaBits = header.flags & 0xf;\n var pixel_size = header.pixel_size >> 3;\n var pixel_total = header.width * header.height * pixel_size;\n // Read palettes\n var palettes;\n if (use_pal) {\n palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));\n }\n // Read LRE\n if (use_rle) {\n pixel_data = new Uint8Array(pixel_total);\n var c, count, i;\n var localOffset = 0;\n var pixels = new Uint8Array(pixel_size);\n while (offset < pixel_total && localOffset < pixel_total) {\n c = data[offset++];\n count = (c & 0x7f) + 1;\n // RLE pixels\n if (c & 0x80) {\n // Bind pixel tmp array\n for (i = 0; i < pixel_size; ++i) {\n pixels[i] = data[offset++];\n }\n // Copy pixel array\n for (i = 0; i < count; ++i) {\n pixel_data.set(pixels, localOffset + i * pixel_size);\n }\n localOffset += pixel_size * count;\n }\n // Raw pixels\n else {\n count *= pixel_size;\n for (i = 0; i < count; ++i) {\n pixel_data[localOffset + i] = data[offset++];\n }\n localOffset += count;\n }\n }\n }\n // RAW Pixels\n else {\n pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));\n }\n // Load to texture\n var x_start, y_start, x_step, y_step, y_end, x_end;\n switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {\n default:\n case TGATools._ORIGIN_UL:\n x_start = 0;\n x_step = 1;\n x_end = header.width;\n y_start = 0;\n y_step = 1;\n y_end = header.height;\n break;\n case TGATools._ORIGIN_BL:\n x_start = 0;\n x_step = 1;\n x_end = header.width;\n y_start = header.height - 1;\n y_step = -1;\n y_end = -1;\n break;\n case TGATools._ORIGIN_UR:\n x_start = header.width - 1;\n x_step = -1;\n x_end = -1;\n y_start = 0;\n y_step = 1;\n y_end = header.height;\n break;\n case TGATools._ORIGIN_BR:\n x_start = header.width - 1;\n x_step = -1;\n x_end = -1;\n y_start = header.height - 1;\n y_step = -1;\n y_end = -1;\n break;\n }\n // Load the specify method\n var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';\n var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);\n var engine = texture.getEngine();\n engine._uploadDataToTextureDirectly(texture, imageData);\n };\n TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n var image = pixel_data, colormap = palettes;\n var width = header.width, height = header.height;\n var color, i = 0, x, y;\n var imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i++) {\n color = image[i];\n imageData[(x + width * y) * 4 + 3] = 255;\n imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];\n imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];\n imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];\n }\n }\n return imageData;\n };\n TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n var image = pixel_data;\n var width = header.width, height = header.height;\n var color, i = 0, x, y;\n var imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 2) {\n color = image[i + 0] + (image[i + 1] << 8); // Inversed ?\n var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;\n var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;\n var b = ((color & 0x001F) * 255) / 0x1F | 0;\n imageData[(x + width * y) * 4 + 0] = r;\n imageData[(x + width * y) * 4 + 1] = g;\n imageData[(x + width * y) * 4 + 2] = b;\n imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;\n }\n }\n return imageData;\n };\n TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n var image = pixel_data;\n var width = header.width, height = header.height;\n var i = 0, x, y;\n var imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 3) {\n imageData[(x + width * y) * 4 + 3] = 255;\n imageData[(x + width * y) * 4 + 2] = image[i + 0];\n imageData[(x + width * y) * 4 + 1] = image[i + 1];\n imageData[(x + width * y) * 4 + 0] = image[i + 2];\n }\n }\n return imageData;\n };\n TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n var image = pixel_data;\n var width = header.width, height = header.height;\n var i = 0, x, y;\n var imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 4) {\n imageData[(x + width * y) * 4 + 2] = image[i + 0];\n imageData[(x + width * y) * 4 + 1] = image[i + 1];\n imageData[(x + width * y) * 4 + 0] = image[i + 2];\n imageData[(x + width * y) * 4 + 3] = image[i + 3];\n }\n }\n return imageData;\n };\n TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n var image = pixel_data;\n var width = header.width, height = header.height;\n var color, i = 0, x, y;\n var imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i++) {\n color = image[i];\n imageData[(x + width * y) * 4 + 0] = color;\n imageData[(x + width * y) * 4 + 1] = color;\n imageData[(x + width * y) * 4 + 2] = color;\n imageData[(x + width * y) * 4 + 3] = 255;\n }\n }\n return imageData;\n };\n TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n var image = pixel_data;\n var width = header.width, height = header.height;\n var i = 0, x, y;\n var imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 2) {\n imageData[(x + width * y) * 4 + 0] = image[i + 0];\n imageData[(x + width * y) * 4 + 1] = image[i + 0];\n imageData[(x + width * y) * 4 + 2] = image[i + 0];\n imageData[(x + width * y) * 4 + 3] = image[i + 1];\n }\n }\n return imageData;\n };\n //private static _TYPE_NO_DATA = 0;\n TGATools._TYPE_INDEXED = 1;\n TGATools._TYPE_RGB = 2;\n TGATools._TYPE_GREY = 3;\n TGATools._TYPE_RLE_INDEXED = 9;\n TGATools._TYPE_RLE_RGB = 10;\n TGATools._TYPE_RLE_GREY = 11;\n TGATools._ORIGIN_MASK = 0x30;\n TGATools._ORIGIN_SHIFT = 0x04;\n TGATools._ORIGIN_BL = 0x00;\n TGATools._ORIGIN_BR = 0x01;\n TGATools._ORIGIN_UL = 0x02;\n TGATools._ORIGIN_UR = 0x03;\n return TGATools;\n }());\n BABYLON.TGATools = TGATools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.tga.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Implementation of the TGA Texture Loader.\n */\n var TGATextureLoader = /** @class */ (function () {\n function TGATextureLoader() {\n /**\n * Defines wether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @param fallback defines the fallback internal texture if any\n * @param isBase64 defines whether the texture is encoded as a base64\n * @param isBuffer defines whether the texture data are stored as a buffer\n * @returns true if the loader can load the specified file\n */\n TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {\n return extension.indexOf(\".tga\") === 0;\n };\n /**\n * Transform the url before loading if required.\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the transformed texture\n */\n TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {\n return rootUrl;\n };\n /**\n * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the fallback texture\n */\n TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {\n return null;\n };\n /**\n * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n * @param onError defines the callback to trigger in case of error\n */\n TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {\n throw \".env not supported in Cube.\";\n };\n /**\n * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n TGATextureLoader.prototype.loadData = function (data, texture, callback) {\n var uintData = new Uint8Array(data);\n var header = BABYLON.TGATools.GetTGAHeader(uintData);\n callback(header.width, header.height, texture.generateMipMaps, false, function () {\n BABYLON.TGATools.UploadContent(texture, uintData);\n });\n };\n return TGATextureLoader;\n }());\n // Register the loader.\n BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.tgaTextureLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * for description see https://www.khronos.org/opengles/sdk/tools/KTX/\n * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/\n */\n var KhronosTextureContainer = /** @class */ (function () {\n /**\n * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file\n * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or\n * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented\n * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented\n */\n function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {\n this.arrayBuffer = arrayBuffer;\n // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:\n // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\\r', '\\n', '\\x1A', '\\n'\n // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A\n var identifier = new Uint8Array(this.arrayBuffer, 0, 12);\n if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||\n identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {\n BABYLON.Tools.Error(\"texture missing KTX identifier\");\n return;\n }\n // load the reset of the header in native 32 bit int\n var header = new Int32Array(this.arrayBuffer, 12, 13);\n // determine of the remaining header values are recorded in the opposite endianness & require conversion\n var oppositeEndianess = header[0] === 0x01020304;\n // read all the header elements in order they exist in the file, without modification (sans endainness)\n this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures\n this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures\n this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures\n this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)\n this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)\n this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)\n this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)\n this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)\n this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays\n this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6\n this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures\n this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data\n // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.\n if (this.glType !== 0) {\n BABYLON.Tools.Error(\"only compressed formats currently supported\");\n return;\n }\n else {\n // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.\n this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);\n }\n if (this.pixelHeight === 0 || this.pixelDepth !== 0) {\n BABYLON.Tools.Error(\"only 2D textures currently supported\");\n return;\n }\n if (this.numberOfArrayElements !== 0) {\n BABYLON.Tools.Error(\"texture arrays not currently supported\");\n return;\n }\n if (this.numberOfFaces !== facesExpected) {\n BABYLON.Tools.Error(\"number of faces expected\" + facesExpected + \", but found \" + this.numberOfFaces);\n return;\n }\n // we now have a completely validated file, so could use existence of loadType as success\n // would need to make this more elaborate & adjust checks above to support more than one load type\n this.loadType = KhronosTextureContainer.COMPRESSED_2D;\n }\n // not as fast hardware based, but will probably never need to use\n KhronosTextureContainer.prototype.switchEndainness = function (val) {\n return ((val & 0xFF) << 24)\n | ((val & 0xFF00) << 8)\n | ((val >> 8) & 0xFF00)\n | ((val >> 24) & 0xFF);\n };\n /**\n * Uploads KTX content to a Babylon Texture.\n * It is assumed that the texture has already been created & is currently bound\n * @hidden\n */\n KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {\n switch (this.loadType) {\n case KhronosTextureContainer.COMPRESSED_2D:\n this._upload2DCompressedLevels(texture, loadMipmaps);\n break;\n case KhronosTextureContainer.TEX_2D:\n case KhronosTextureContainer.COMPRESSED_3D:\n case KhronosTextureContainer.TEX_3D:\n }\n };\n KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {\n // initialize width & height for level 1\n var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;\n var width = this.pixelWidth;\n var height = this.pixelHeight;\n var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;\n for (var level = 0; level < mipmapCount; level++) {\n var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps\n dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.\n for (var face = 0; face < this.numberOfFaces; face++) {\n var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);\n var engine = texture.getEngine();\n engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);\n dataOffset += imageSize; // add size of the image for the next face/mipmap\n dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image\n }\n width = Math.max(1.0, width * 0.5);\n height = Math.max(1.0, height * 0.5);\n }\n };\n KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)\n // load types\n KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()\n KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()\n KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()\n KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()\n return KhronosTextureContainer;\n }());\n BABYLON.KhronosTextureContainer = KhronosTextureContainer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.khronosTextureContainer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Implementation of the KTX Texture Loader.\n */\n var KTXTextureLoader = /** @class */ (function () {\n function KTXTextureLoader() {\n /**\n * Defines wether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @param fallback defines the fallback internal texture if any\n * @param isBase64 defines whether the texture is encoded as a base64\n * @param isBuffer defines whether the texture data are stored as a buffer\n * @returns true if the loader can load the specified file\n */\n KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {\n if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {\n return true;\n }\n return false;\n };\n /**\n * Transform the url before loading if required.\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the transformed texture\n */\n KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {\n var lastDot = rootUrl.lastIndexOf('.');\n return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;\n };\n /**\n * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the fallback texture\n */\n KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {\n // remove the format appended to the rootUrl in the original createCubeTexture call.\n var exp = new RegExp(\"\" + textureFormatInUse + \"$\");\n return rootUrl.replace(exp, \"\");\n };\n /**\n * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n * @param onError defines the callback to trigger in case of error\n */\n KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {\n if (Array.isArray(data)) {\n return;\n }\n var engine = texture.getEngine();\n var ktx = new BABYLON.KhronosTextureContainer(data, 6);\n var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;\n engine._unpackFlipY(true);\n ktx.uploadLevels(texture, texture.generateMipMaps);\n texture.width = ktx.pixelWidth;\n texture.height = ktx.pixelHeight;\n engine._setCubeMapTextureParams(loadMipmap);\n texture.isReady = true;\n };\n /**\n * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n KTXTextureLoader.prototype.loadData = function (data, texture, callback) {\n var ktx = new BABYLON.KhronosTextureContainer(data, 1);\n callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {\n ktx.uploadLevels(texture, texture.generateMipMaps);\n });\n };\n return KTXTextureLoader;\n }());\n // Register the loader.\n BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.ktxTextureLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Sets of helpers addressing the serialization and deserialization of environment texture\n * stored in a BabylonJS env file.\n * Those files are usually stored as .env files.\n */\n var EnvironmentTextureTools = /** @class */ (function () {\n function EnvironmentTextureTools() {\n }\n /**\n * Gets the environment info from an env file.\n * @param data The array buffer containing the .env bytes.\n * @returns the environment file info (the json header) if successfully parsed.\n */\n EnvironmentTextureTools.GetEnvInfo = function (data) {\n var dataView = new DataView(data);\n var pos = 0;\n for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {\n if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {\n BABYLON.Tools.Error('Not a babylon environment map');\n return null;\n }\n }\n // Read json manifest - collect characters up to null terminator\n var manifestString = '';\n var charCode = 0x00;\n while ((charCode = dataView.getUint8(pos++))) {\n manifestString += String.fromCharCode(charCode);\n }\n var manifest = JSON.parse(manifestString);\n if (manifest.specular) {\n // Extend the header with the position of the payload.\n manifest.specular.specularDataPosition = pos;\n // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.\n manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;\n }\n return manifest;\n };\n /**\n * Creates an environment texture from a loaded cube texture.\n * @param texture defines the cube texture to convert in env file\n * @return a promise containing the environment data if succesfull.\n */\n EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {\n var _this = this;\n var internalTexture = texture.getInternalTexture();\n if (!internalTexture) {\n return Promise.reject(\"The cube texture is invalid.\");\n }\n if (!texture._prefiltered) {\n return Promise.reject(\"The cube texture is invalid (not prefiltered).\");\n }\n var engine = internalTexture.getEngine();\n if (engine && engine.premultipliedAlpha) {\n return Promise.reject(\"Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.\");\n }\n if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {\n return Promise.reject(\"The cube texture should allow HDR (Full Float or Half Float).\");\n }\n var canvas = engine.getRenderingCanvas();\n if (!canvas) {\n return Promise.reject(\"Env texture can only be created when the engine is associated to a canvas.\");\n }\n var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n if (!engine.getCaps().textureFloatRender) {\n textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n if (!engine.getCaps().textureHalfFloatRender) {\n return Promise.reject(\"Env texture can only be created when the browser supports half float or full float rendering.\");\n }\n }\n var cubeWidth = internalTexture.width;\n var hostingScene = new BABYLON.Scene(engine);\n var specularTextures = {};\n var promises = [];\n // Read and collect all mipmaps data from the cube.\n var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);\n mipmapsCount = Math.round(mipmapsCount);\n var _loop_1 = function (i) {\n var faceWidth = Math.pow(2, mipmapsCount - i);\n var _loop_2 = function (face) {\n var data = texture.readPixels(face, i);\n // Creates a temp texture with the face data.\n var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);\n // And rgbdEncode them. \n var promise = new Promise(function (resolve, reject) {\n var rgbdPostProcess = new BABYLON.PostProcess(\"rgbdEncode\", \"rgbdEncode\", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);\n rgbdPostProcess.getEffect().executeWhenCompiled(function () {\n rgbdPostProcess.onApply = function (effect) {\n effect._bindTexture(\"textureSampler\", tempTexture);\n };\n // As the process needs to happen on the main canvas, keep track of the current size\n var currentW = engine.getRenderWidth();\n var currentH = engine.getRenderHeight();\n // Set the desired size for the texture\n engine.setSize(faceWidth, faceWidth);\n hostingScene.postProcessManager.directRender([rgbdPostProcess], null);\n // Reading datas from WebGL\n BABYLON.Tools.ToBlob(canvas, function (blob) {\n var fileReader = new FileReader();\n fileReader.onload = function (event) {\n var arrayBuffer = event.target.result;\n specularTextures[i * 6 + face] = arrayBuffer;\n resolve();\n };\n fileReader.readAsArrayBuffer(blob);\n });\n // Reapply the previous canvas size\n engine.setSize(currentW, currentH);\n });\n });\n promises.push(promise);\n };\n // All faces of the cube.\n for (var face = 0; face < 6; face++) {\n _loop_2(face);\n }\n };\n for (var i = 0; i <= mipmapsCount; i++) {\n _loop_1(i);\n }\n // Once all the textures haves been collected as RGBD stored in PNGs\n return Promise.all(promises).then(function () {\n // We can delete the hosting scene keeping track of all the creation objects\n hostingScene.dispose();\n // Creates the json header for the env texture\n var info = {\n version: 1,\n width: cubeWidth,\n irradiance: _this._CreateEnvTextureIrradiance(texture),\n specular: {\n mipmaps: [],\n lodGenerationScale: texture.lodGenerationScale\n }\n };\n // Sets the specular image data information\n var position = 0;\n for (var i = 0; i <= mipmapsCount; i++) {\n for (var face = 0; face < 6; face++) {\n var byteLength = specularTextures[i * 6 + face].byteLength;\n info.specular.mipmaps.push({\n length: byteLength,\n position: position\n });\n position += byteLength;\n }\n }\n // Encode the JSON as an array buffer\n var infoString = JSON.stringify(info);\n var infoBuffer = new ArrayBuffer(infoString.length + 1);\n var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.\n for (var i = 0, strLen = infoString.length; i < strLen; i++) {\n infoView[i] = infoString.charCodeAt(i);\n }\n // Ends up with a null terminator for easier parsing\n infoView[infoString.length] = 0x00;\n // Computes the final required size and creates the storage\n var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;\n var finalBuffer = new ArrayBuffer(totalSize);\n var finalBufferView = new Uint8Array(finalBuffer);\n var dataView = new DataView(finalBuffer);\n // Copy the magic bytes identifying the file in\n var pos = 0;\n for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {\n dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);\n }\n // Add the json info\n finalBufferView.set(new Uint8Array(infoBuffer), pos);\n pos += infoBuffer.byteLength;\n // Finally inserts the texture data\n for (var i = 0; i <= mipmapsCount; i++) {\n for (var face = 0; face < 6; face++) {\n var dataBuffer = specularTextures[i * 6 + face];\n finalBufferView.set(new Uint8Array(dataBuffer), pos);\n pos += dataBuffer.byteLength;\n }\n }\n // Voila\n return finalBuffer;\n });\n };\n /**\n * Creates a JSON representation of the spherical data.\n * @param texture defines the texture containing the polynomials\n * @return the JSON representation of the spherical info\n */\n EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {\n var polynmials = texture.sphericalPolynomial;\n if (polynmials == null) {\n return null;\n }\n return {\n x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],\n y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],\n z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],\n xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],\n yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],\n zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],\n yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],\n zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],\n xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]\n };\n };\n /**\n * Uploads the texture info contained in the env file to the GPU.\n * @param texture defines the internal texture to upload to\n * @param arrayBuffer defines the buffer cotaining the data to load\n * @param info defines the texture info retrieved through the GetEnvInfo method\n * @returns a promise\n */\n EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {\n if (info.version !== 1) {\n throw new Error(\"Unsupported babylon environment map version \\\"\" + info.version + \"\\\"\");\n }\n var specularInfo = info.specular;\n if (!specularInfo) {\n // Nothing else parsed so far\n return Promise.resolve();\n }\n // Double checks the enclosed info\n var mipmapsCount = BABYLON.Scalar.Log2(info.width);\n mipmapsCount = Math.round(mipmapsCount) + 1;\n if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {\n throw new Error(\"Unsupported specular mipmaps number \\\"\" + specularInfo.mipmaps.length + \"\\\"\");\n }\n texture._lodGenerationScale = specularInfo.lodGenerationScale;\n var imageData = new Array(mipmapsCount);\n for (var i = 0; i < mipmapsCount; i++) {\n imageData[i] = new Array(6);\n for (var face = 0; face < 6; face++) {\n var imageInfo = specularInfo.mipmaps[i * 6 + face];\n imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);\n }\n }\n return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);\n };\n /**\n * Uploads the levels of image data to the GPU.\n * @param texture defines the internal texture to upload to\n * @param imageData defines the array buffer views of image data [mipmap][face]\n * @returns a promise\n */\n EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {\n if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {\n throw new Error(\"Texture size must be a power of two\");\n }\n var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;\n // Gets everything ready.\n var engine = texture.getEngine();\n var expandTexture = false;\n var generateNonLODTextures = false;\n var rgbdPostProcess = null;\n var cubeRtt = null;\n var lodTextures = null;\n var caps = engine.getCaps();\n texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;\n texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n texture.generateMipMaps = true;\n engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);\n // Add extra process if texture lod is not supported\n if (!caps.textureLOD) {\n expandTexture = false;\n generateNonLODTextures = true;\n lodTextures = {};\n }\n // in webgl 1 there are no ways to either render or copy lod level information for float textures.\n else if (engine.webGLVersion < 2) {\n expandTexture = false;\n }\n // If half float available we can uncompress the texture\n else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n expandTexture = true;\n texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n // If full float available we can uncompress the texture\n else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n expandTexture = true;\n texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n // Expand the texture if possible\n if (expandTexture) {\n // Simply run through the decode PP\n rgbdPostProcess = new BABYLON.PostProcess(\"rgbdDecode\", \"rgbdDecode\", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);\n texture._isRGBD = false;\n texture.invertY = false;\n cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {\n generateDepthBuffer: false,\n generateMipMaps: true,\n generateStencilBuffer: false,\n samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,\n type: texture.type,\n format: BABYLON.Engine.TEXTUREFORMAT_RGBA\n });\n }\n else {\n texture._isRGBD = true;\n texture.invertY = true;\n // In case of missing support, applies the same patch than DDS files.\n if (generateNonLODTextures) {\n var mipSlices = 3;\n var scale = texture._lodGenerationScale;\n var offset = texture._lodGenerationOffset;\n for (var i = 0; i < mipSlices; i++) {\n //compute LOD from even spacing in smoothness (matching shader calculation)\n var smoothness = i / (mipSlices - 1);\n var roughness = 1 - smoothness;\n var minLODIndex = offset; // roughness = 0\n var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)\n var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;\n var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));\n var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);\n glTextureFromLod.isCube = true;\n glTextureFromLod.invertY = true;\n glTextureFromLod.generateMipMaps = false;\n engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);\n // Wrap in a base texture for easy binding.\n var lodTexture = new BABYLON.BaseTexture(null);\n lodTexture.isCube = true;\n lodTexture._texture = glTextureFromLod;\n lodTextures[mipmapIndex] = lodTexture;\n switch (i) {\n case 0:\n texture._lodTextureLow = lodTexture;\n break;\n case 1:\n texture._lodTextureMid = lodTexture;\n break;\n case 2:\n texture._lodTextureHigh = lodTexture;\n break;\n }\n }\n }\n }\n var promises = [];\n var _loop_3 = function (i) {\n var _loop_4 = function (face) {\n // Constructs an image element from image data\n var bytes = imageData[i][face];\n var blob = new Blob([bytes], { type: 'image/png' });\n var url = URL.createObjectURL(blob);\n var image = new Image();\n image.src = url;\n // Enqueue promise to upload to the texture.\n var promise = new Promise(function (resolve, reject) {\n image.onload = function () {\n if (expandTexture) {\n var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {\n reject(message);\n }, image);\n rgbdPostProcess.getEffect().executeWhenCompiled(function () {\n // Uncompress the data to a RTT\n rgbdPostProcess.onApply = function (effect) {\n effect._bindTexture(\"textureSampler\", tempTexture_1);\n effect.setFloat2(\"scale\", 1, 1);\n };\n engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);\n // Cleanup\n engine.restoreDefaultFramebuffer();\n tempTexture_1.dispose();\n window.URL.revokeObjectURL(url);\n resolve();\n });\n }\n else {\n engine._uploadImageToTexture(texture, image, face, i);\n // Upload the face to the non lod texture support\n if (generateNonLODTextures) {\n var lodTexture = lodTextures[i];\n if (lodTexture) {\n engine._uploadImageToTexture(lodTexture._texture, image, face, 0);\n }\n }\n resolve();\n }\n };\n image.onerror = function (error) {\n reject(error);\n };\n });\n promises.push(promise);\n };\n // All faces\n for (var face = 0; face < 6; face++) {\n _loop_4(face);\n }\n };\n // All mipmaps up to provided number of images\n for (var i = 0; i < imageData.length; i++) {\n _loop_3(i);\n }\n // Fill remaining mipmaps with black textures.\n if (imageData.length < mipmapsCount) {\n var data = void 0;\n var size = Math.pow(2, mipmapsCount - 1 - imageData.length);\n var dataLength = size * size * 4;\n switch (texture.type) {\n case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {\n data = new Uint8Array(dataLength);\n break;\n }\n case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {\n data = new Uint16Array(dataLength);\n break;\n }\n case BABYLON.Engine.TEXTURETYPE_FLOAT: {\n data = new Float32Array(dataLength);\n break;\n }\n }\n for (var i = imageData.length; i < mipmapsCount; i++) {\n for (var face = 0; face < 6; face++) {\n engine._uploadArrayBufferViewToTexture(texture, data, face, i);\n }\n }\n }\n // Once all done, finishes the cleanup and return\n return Promise.all(promises).then(function () {\n // Release temp RTT.\n if (cubeRtt) {\n engine._releaseFramebufferObjects(cubeRtt);\n cubeRtt._swapAndDie(texture);\n }\n // Release temp Post Process.\n if (rgbdPostProcess) {\n rgbdPostProcess.dispose();\n }\n // Flag internal texture as ready in case they are in use.\n if (generateNonLODTextures) {\n if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {\n texture._lodTextureHigh._texture.isReady = true;\n }\n if (texture._lodTextureMid && texture._lodTextureMid._texture) {\n texture._lodTextureMid._texture.isReady = true;\n }\n if (texture._lodTextureLow && texture._lodTextureLow._texture) {\n texture._lodTextureLow._texture.isReady = true;\n }\n }\n });\n };\n /**\n * Uploads spherical polynomials information to the texture.\n * @param texture defines the texture we are trying to upload the information to\n * @param info defines the environment texture info retrieved through the GetEnvInfo method\n */\n EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {\n if (info.version !== 1) {\n BABYLON.Tools.Warn('Unsupported babylon environment map version \"' + info.version + '\"');\n }\n var irradianceInfo = info.irradiance;\n if (!irradianceInfo) {\n return;\n }\n var sp = new BABYLON.SphericalPolynomial();\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);\n BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);\n texture._sphericalPolynomial = sp;\n };\n /**\n * Magic number identifying the env file.\n */\n EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];\n return EnvironmentTextureTools;\n }());\n BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.environmentTextureTools.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Implementation of the ENV Texture Loader.\n */\n var ENVTextureLoader = /** @class */ (function () {\n function ENVTextureLoader() {\n /**\n * Defines wether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @param fallback defines the fallback internal texture if any\n * @param isBase64 defines whether the texture is encoded as a base64\n * @param isBuffer defines whether the texture data are stored as a buffer\n * @returns true if the loader can load the specified file\n */\n ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {\n return extension.indexOf(\".env\") === 0;\n };\n /**\n * Transform the url before loading if required.\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the transformed texture\n */\n ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {\n return rootUrl;\n };\n /**\n * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work\n * @param rootUrl the url of the texture\n * @param textureFormatInUse defines the current compressed format in use iun the engine\n * @returns the fallback texture\n */\n ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {\n return null;\n };\n /**\n * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n * @param onError defines the callback to trigger in case of error\n */\n ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {\n if (Array.isArray(data)) {\n return;\n }\n data = data;\n var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);\n if (info) {\n texture.width = info.width;\n texture.height = info.width;\n BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);\n BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {\n texture.isReady = true;\n if (onLoad) {\n onLoad();\n }\n });\n }\n else if (onError) {\n onError(\"Can not parse the environment file\", null);\n }\n };\n /**\n * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n ENVTextureLoader.prototype.loadData = function (data, texture, callback) {\n throw \".env not supported in 2d.\";\n };\n return ENVTextureLoader;\n }());\n // Register the loader.\n BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.envTextureLoader.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Renders a layer on top of an existing scene\n */\n var UtilityLayerRenderer = /** @class */ (function () {\n /**\n * Instantiates a UtilityLayerRenderer\n * @param originalScene the original scene that will be rendered on top of\n */\n function UtilityLayerRenderer(\n /** the original scene that will be rendered on top of */\n originalScene) {\n var _this = this;\n this.originalScene = originalScene;\n this._pointerCaptures = {};\n this._lastPointerEvents = {};\n /**\n * If the utility layer should automatically be rendered on top of existing scene\n */\n this.shouldRender = true;\n /**\n * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene\n */\n this.onlyCheckPointerDownEvents = true;\n /**\n * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)\n */\n this.processAllEvents = false;\n /**\n * Observable raised when the pointer move from the utility layer scene to the main scene\n */\n this.onPointerOutObservable = new BABYLON.Observable();\n // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app\n this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());\n this.utilityLayerScene._allowPostProcessClear = false;\n originalScene.getEngine().scenes.pop();\n // Detach controls on utility scene, events will be fired by logic below to handle picking priority\n this.utilityLayerScene.detachControl();\n this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {\n if (!_this.processAllEvents) {\n if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE\n && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP\n && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {\n return;\n }\n }\n var pointerEvent = (prePointerInfo.event);\n if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {\n _this._pointerCaptures[pointerEvent.pointerId] = false;\n return;\n }\n var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);\n if (!prePointerInfo.ray && utilityScenePick) {\n prePointerInfo.ray = utilityScenePick.ray;\n }\n // always fire the prepointer oversvable\n _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);\n // allow every non pointer down event to flow to the utility layer\n if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {\n if (!prePointerInfo.skipOnPointerObservable) {\n _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));\n }\n if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {\n _this._pointerCaptures[pointerEvent.pointerId] = false;\n }\n return;\n }\n if (_this.utilityLayerScene.autoClearDepthAndStencil) {\n // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene\n if (utilityScenePick && utilityScenePick.hit) {\n if (!prePointerInfo.skipOnPointerObservable) {\n _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));\n }\n prePointerInfo.skipOnPointerObservable = true;\n }\n }\n else {\n var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);\n var pointerEvent_1 = (prePointerInfo.event);\n // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray\n if (originalScenePick && utilityScenePick) {\n // No pick in utility scene\n if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {\n if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {\n // We touched an utility mesh present in the main scene\n _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);\n prePointerInfo.skipOnPointerObservable = true;\n }\n else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {\n _this._pointerCaptures[pointerEvent_1.pointerId] = true;\n }\n }\n else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {\n // We pick something in utility scene or the pick in utility is closer than the one in main scene\n _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);\n // If a previous utility layer set this, do not unset this\n if (!prePointerInfo.skipOnPointerObservable) {\n prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;\n }\n }\n else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {\n // We have a pick in both scenes but main is closer than utility\n // We touched an utility mesh present in the main scene\n if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {\n _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);\n prePointerInfo.skipOnPointerObservable = true;\n }\n else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {\n // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete\n _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);\n delete _this._lastPointerEvents[pointerEvent_1.pointerId];\n }\n }\n if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {\n _this._pointerCaptures[pointerEvent_1.pointerId] = false;\n }\n }\n }\n });\n // Render directly on top of existing scene without clearing\n this.utilityLayerScene.autoClear = false;\n this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {\n if (_this.shouldRender) {\n _this.render();\n }\n });\n this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {\n _this.dispose();\n });\n this._updateCamera();\n }\n Object.defineProperty(UtilityLayerRenderer, \"DefaultUtilityLayer\", {\n /**\n * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)\n */\n get: function () {\n if (UtilityLayerRenderer._DefaultUtilityLayer == null) {\n UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);\n UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {\n UtilityLayerRenderer._DefaultUtilityLayer = null;\n });\n }\n return UtilityLayerRenderer._DefaultUtilityLayer;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(UtilityLayerRenderer, \"DefaultKeepDepthUtilityLayer\", {\n /**\n * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)\n */\n get: function () {\n if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;\n });\n }\n return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;\n },\n enumerable: true,\n configurable: true\n });\n UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {\n if (!prePointerInfo.skipOnPointerObservable) {\n this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));\n this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;\n }\n };\n /**\n * Renders the utility layers scene on top of the original scene\n */\n UtilityLayerRenderer.prototype.render = function () {\n this._updateCamera();\n if (this.utilityLayerScene.activeCamera) {\n // Set the camera's scene to utility layers scene\n var oldScene = this.utilityLayerScene.activeCamera.getScene();\n var camera = this.utilityLayerScene.activeCamera;\n camera._scene = this.utilityLayerScene;\n if (camera.leftCamera) {\n camera.leftCamera._scene = this.utilityLayerScene;\n }\n if (camera.rightCamera) {\n camera.rightCamera._scene = this.utilityLayerScene;\n }\n this.utilityLayerScene.render(false);\n // Reset camera's scene back to original\n camera._scene = oldScene;\n if (camera.leftCamera) {\n camera.leftCamera._scene = oldScene;\n }\n if (camera.rightCamera) {\n camera.rightCamera._scene = oldScene;\n }\n }\n };\n /**\n * Disposes of the renderer\n */\n UtilityLayerRenderer.prototype.dispose = function () {\n this.onPointerOutObservable.clear();\n if (this._afterRenderObserver) {\n this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);\n }\n if (this._sceneDisposeObserver) {\n this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);\n }\n if (this._originalPointerObserver) {\n this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);\n }\n this.utilityLayerScene.dispose();\n };\n UtilityLayerRenderer.prototype._updateCamera = function () {\n this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;\n };\n UtilityLayerRenderer._DefaultUtilityLayer = null;\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;\n return UtilityLayerRenderer;\n }());\n BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.utilityLayerRenderer.js.map\n\n\n\n//# sourceMappingURL=babylon.behavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events\n */\n var PointerDragBehavior = /** @class */ (function () {\n /**\n * Creates a pointer drag behavior that can be attached to a mesh\n * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)\n */\n function PointerDragBehavior(options) {\n /**\n * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)\n */\n this.maxDragAngle = 0;\n /**\n * @hidden\n */\n this._useAlternatePickedPointAboveMaxDragAngle = false;\n /**\n * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)\n */\n this.currentDraggingPointerID = -1;\n /**\n * If the behavior is currently in a dragging state\n */\n this.dragging = false;\n /**\n * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)\n */\n this.dragDeltaRatio = 0.2;\n /**\n * If the drag plane orientation should be updated during the dragging (Default: true)\n */\n this.updateDragPlane = true;\n // Debug mode will display drag planes to help visualize behavior\n this._debugMode = false;\n this._moving = false;\n /**\n * Fires each time the attached mesh is dragged with the pointer\n * * delta between last drag position and current drag position in world space\n * * dragDistance along the drag axis\n * * dragPlaneNormal normal of the current drag plane used during the drag\n * * dragPlanePoint in world space where the drag intersects the drag plane\n */\n this.onDragObservable = new BABYLON.Observable();\n /**\n * Fires each time a drag begins (eg. mouse down on mesh)\n */\n this.onDragStartObservable = new BABYLON.Observable();\n /**\n * Fires each time a drag ends (eg. mouse release after drag)\n */\n this.onDragEndObservable = new BABYLON.Observable();\n /**\n * If the attached mesh should be moved when dragged\n */\n this.moveAttached = true;\n /**\n * If the drag behavior will react to drag events (Default: true)\n */\n this.enabled = true;\n /**\n * If camera controls should be detached during the drag\n */\n this.detachCameraControls = true;\n /**\n * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)\n */\n this.useObjectOrienationForDragging = true;\n this._tmpVector = new BABYLON.Vector3(0, 0, 0);\n this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);\n this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);\n // Variables to avoid instantiation in the below method\n this._pointA = new BABYLON.Vector3(0, 0, 0);\n this._pointB = new BABYLON.Vector3(0, 0, 0);\n this._pointC = new BABYLON.Vector3(0, 0, 0);\n this._lineA = new BABYLON.Vector3(0, 0, 0);\n this._lineB = new BABYLON.Vector3(0, 0, 0);\n this._localAxis = new BABYLON.Vector3(0, 0, 0);\n this._lookAt = new BABYLON.Vector3(0, 0, 0);\n this._options = options ? options : {};\n var optionCount = 0;\n if (this._options.dragAxis) {\n optionCount++;\n }\n if (this._options.dragPlaneNormal) {\n optionCount++;\n }\n if (optionCount > 1) {\n throw \"Multiple drag modes specified in dragBehavior options. Only one expected\";\n }\n }\n Object.defineProperty(PointerDragBehavior.prototype, \"name\", {\n /**\n * The name of the behavior\n */\n get: function () {\n return \"PointerDrag\";\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Initializes the behavior\n */\n PointerDragBehavior.prototype.init = function () { };\n /**\n * Attaches the drag behavior the passed in mesh\n * @param ownerNode The mesh that will be dragged around once attached\n */\n PointerDragBehavior.prototype.attach = function (ownerNode) {\n var _this = this;\n this._scene = ownerNode.getScene();\n this._attachedNode = ownerNode;\n // Initialize drag plane to not interfere with existing scene\n if (!PointerDragBehavior._planeScene) {\n if (this._debugMode) {\n PointerDragBehavior._planeScene = this._scene;\n }\n else {\n PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());\n PointerDragBehavior._planeScene.detachControl();\n this._scene.getEngine().scenes.pop();\n this._scene.onDisposeObservable.addOnce(function () {\n PointerDragBehavior._planeScene.dispose();\n PointerDragBehavior._planeScene = null;\n });\n }\n }\n this._dragPlane = BABYLON.Mesh.CreatePlane(\"pointerDragPlane\", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);\n // State of the drag\n this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);\n var delta = new BABYLON.Vector3(0, 0, 0);\n var dragLength = 0;\n var targetPosition = new BABYLON.Vector3(0, 0, 0);\n var pickPredicate = function (m) {\n return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);\n };\n var attachedElement = null;\n this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {\n if (!_this.enabled) {\n return;\n }\n if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {\n if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {\n _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);\n var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);\n if (pickedPoint) {\n _this.dragging = true;\n _this.currentDraggingPointerID = pointerInfo.event.pointerId;\n _this.lastDragPosition.copyFrom(pickedPoint);\n _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });\n targetPosition.copyFrom(_this._attachedNode.absolutePosition);\n // Detatch camera controls\n if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {\n if (_this._scene.activeCamera.inputs.attachedElement) {\n attachedElement = _this._scene.activeCamera.inputs.attachedElement;\n _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);\n }\n else {\n attachedElement = null;\n }\n }\n }\n }\n }\n else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {\n if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {\n _this.releaseDrag();\n // Reattach camera controls\n if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {\n _this._scene.activeCamera.attachControl(attachedElement, true);\n }\n }\n }\n else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {\n if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {\n _this._moving = true;\n var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);\n if (pickedPoint) {\n if (_this.updateDragPlane) {\n _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);\n }\n // depending on the drag mode option drag accordingly\n if (_this._options.dragAxis) {\n // Convert local drag axis to world\n BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);\n // Project delta drag from the drag plane onto the drag axis\n pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);\n dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);\n _this._worldDragAxis.scaleToRef(dragLength, delta);\n }\n else {\n dragLength = delta.length();\n pickedPoint.subtractToRef(_this.lastDragPosition, delta);\n }\n targetPosition.addInPlace(delta);\n _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });\n _this.lastDragPosition.copyFrom(pickedPoint);\n }\n }\n }\n });\n this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {\n if (_this._moving && _this.moveAttached) {\n // Slowly move mesh to avoid jitter\n targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);\n _this._tmpVector.scaleInPlace(0.2);\n _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);\n _this._attachedNode.setAbsolutePosition(_this._tmpVector);\n }\n });\n };\n PointerDragBehavior.prototype.releaseDrag = function () {\n this.dragging = false;\n this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });\n this.currentDraggingPointerID = -1;\n this._moving = false;\n };\n PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {\n var _this = this;\n if (!ray) {\n return null;\n }\n // Calculate angle between plane normal and ray\n var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));\n // Correct if ray is casted from oposite side\n if (angle > Math.PI / 2) {\n angle = Math.PI - angle;\n }\n // If the angle is too perpendicular to the plane pick another point on the plane where it is looking\n if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {\n if (this._useAlternatePickedPointAboveMaxDragAngle) {\n // Invert ray direction along the towards object axis\n this._tmpVector.copyFrom(ray.direction);\n this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);\n this._alternatePickedPoint.normalize();\n this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));\n this._tmpVector.addInPlace(this._alternatePickedPoint);\n // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point\n var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);\n this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);\n this._alternatePickedPoint.addInPlace(this._tmpVector);\n this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);\n return this._alternatePickedPoint;\n }\n else {\n return null;\n }\n }\n var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });\n if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {\n return pickResult.pickedPoint;\n }\n else {\n return null;\n }\n };\n // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera\n PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {\n this._pointA.copyFrom(dragPlanePosition);\n if (this._options.dragAxis) {\n this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);\n // Calculate plane normal in direction of camera but perpendicular to drag axis\n this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis\n ray.origin.subtractToRef(this._pointA, this._pointC);\n this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera\n // Get perpendicular line from direction to camera and drag axis\n this._pointB.subtractToRef(this._pointA, this._lineA);\n this._pointC.subtractToRef(this._pointA, this._lineB);\n BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);\n // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera\n BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);\n this._lookAt.normalize();\n this._dragPlane.position.copyFrom(this._pointA);\n this._pointA.subtractToRef(this._lookAt, this._lookAt);\n this._dragPlane.lookAt(this._lookAt);\n }\n else if (this._options.dragPlaneNormal) {\n this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);\n this._dragPlane.position.copyFrom(this._pointA);\n this._pointA.subtractToRef(this._localAxis, this._lookAt);\n this._dragPlane.lookAt(this._lookAt);\n }\n else {\n this._dragPlane.position.copyFrom(this._pointA);\n this._dragPlane.lookAt(ray.origin);\n }\n this._dragPlane.computeWorldMatrix(true);\n };\n /**\n * Detaches the behavior from the mesh\n */\n PointerDragBehavior.prototype.detach = function () {\n if (this._pointerObserver) {\n this._scene.onPointerObservable.remove(this._pointerObserver);\n }\n if (this._beforeRenderObserver) {\n this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);\n }\n };\n return PointerDragBehavior;\n }());\n BABYLON.PointerDragBehavior = PointerDragBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.pointerDragBehavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A behavior that when attached to a mesh will allow the mesh to be scaled\n */\n var MultiPointerScaleBehavior = /** @class */ (function () {\n function MultiPointerScaleBehavior() {\n this._startDistance = 0;\n this._initialScale = new BABYLON.Vector3(0, 0, 0);\n this._targetScale = new BABYLON.Vector3(0, 0, 0);\n this._sceneRenderObserver = null;\n this._dragBehaviorA = new BABYLON.PointerDragBehavior({});\n this._dragBehaviorA.moveAttached = false;\n this._dragBehaviorB = new BABYLON.PointerDragBehavior({});\n this._dragBehaviorB.moveAttached = false;\n }\n Object.defineProperty(MultiPointerScaleBehavior.prototype, \"name\", {\n /**\n * The name of the behavior\n */\n get: function () {\n return \"MultiPointerScale\";\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Initializes the behavior\n */\n MultiPointerScaleBehavior.prototype.init = function () { };\n MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {\n return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();\n };\n /**\n * Attaches the scale behavior the passed in mesh\n * @param ownerNode The mesh that will be scaled around once attached\n */\n MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {\n var _this = this;\n this._ownerNode = ownerNode;\n // Create 2 drag behaviors such that each will only be triggered by a separate pointer\n this._dragBehaviorA.onDragStartObservable.add(function (e) {\n if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {\n if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {\n _this._dragBehaviorA.releaseDrag();\n }\n else {\n _this._initialScale.copyFrom(ownerNode.scaling);\n _this._startDistance = _this._getCurrentDistance();\n }\n }\n });\n this._dragBehaviorB.onDragStartObservable.add(function (e) {\n if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {\n if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {\n _this._dragBehaviorB.releaseDrag();\n }\n else {\n _this._initialScale.copyFrom(ownerNode.scaling);\n _this._startDistance = _this._getCurrentDistance();\n }\n }\n });\n // Once both drag behaviors are active scale based on the distance between the two pointers\n [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {\n behavior.onDragObservable.add(function () {\n if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {\n var ratio = _this._getCurrentDistance() / _this._startDistance;\n _this._initialScale.scaleToRef(ratio, _this._targetScale);\n }\n });\n });\n ownerNode.addBehavior(this._dragBehaviorA);\n ownerNode.addBehavior(this._dragBehaviorB);\n // On every frame move towards target scaling to avoid jitter caused by vr controllers\n this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {\n if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {\n var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);\n if (change.length() > 0.01) {\n ownerNode.scaling.addInPlace(change);\n }\n }\n });\n };\n /**\n * Detaches the behavior from the mesh\n */\n MultiPointerScaleBehavior.prototype.detach = function () {\n var _this = this;\n this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);\n [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {\n behavior.onDragStartObservable.clear();\n behavior.onDragObservable.clear();\n _this._ownerNode.removeBehavior(behavior);\n });\n };\n return MultiPointerScaleBehavior;\n }());\n BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray\n */\n var SixDofDragBehavior = /** @class */ (function () {\n function SixDofDragBehavior() {\n this._sceneRenderObserver = null;\n this._targetPosition = new BABYLON.Vector3(0, 0, 0);\n this._moving = false;\n this._startingOrientation = new BABYLON.Quaternion();\n /**\n * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)\n */\n this.zDragFactor = 3;\n /**\n * If the behavior is currently in a dragging state\n */\n this.dragging = false;\n /**\n * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)\n */\n this.dragDeltaRatio = 0.2;\n /**\n * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)\n */\n this.currentDraggingPointerID = -1;\n /**\n * If camera controls should be detached during the drag\n */\n this.detachCameraControls = true;\n }\n Object.defineProperty(SixDofDragBehavior.prototype, \"name\", {\n /**\n * The name of the behavior\n */\n get: function () {\n return \"SixDofDrag\";\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Initializes the behavior\n */\n SixDofDragBehavior.prototype.init = function () { };\n /**\n * Attaches the scale behavior the passed in mesh\n * @param ownerNode The mesh that will be scaled around once attached\n */\n SixDofDragBehavior.prototype.attach = function (ownerNode) {\n var _this = this;\n this._ownerNode = ownerNode;\n this._scene = this._ownerNode.getScene();\n if (!SixDofDragBehavior._virtualScene) {\n SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());\n this._scene.getEngine().scenes.pop();\n }\n var pickedMesh = null;\n var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);\n // Setup virtual meshes to be used for dragging without dirtying the existing scene\n this._virtualOriginMesh = new BABYLON.AbstractMesh(\"\", SixDofDragBehavior._virtualScene);\n this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();\n this._virtualDragMesh = new BABYLON.AbstractMesh(\"\", SixDofDragBehavior._virtualScene);\n this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();\n var pickPredicate = function (m) {\n return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);\n };\n var attachedElement = null;\n this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {\n if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {\n if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {\n if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {\n pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);\n }\n pickedMesh = _this._ownerNode;\n lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);\n // Set position and orientation of the controller\n _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);\n _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));\n // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged\n _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);\n _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);\n if (!pickedMesh.rotationQuaternion) {\n pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);\n }\n var oldParent = pickedMesh.parent;\n pickedMesh.setParent(null);\n _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);\n pickedMesh.setParent(oldParent);\n _this._virtualOriginMesh.addChild(_this._virtualDragMesh);\n // Update state\n _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);\n _this.dragging = true;\n _this.currentDraggingPointerID = pointerInfo.event.pointerId;\n // Detatch camera controls\n if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {\n if (_this._scene.activeCamera.inputs.attachedElement) {\n attachedElement = _this._scene.activeCamera.inputs.attachedElement;\n _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);\n }\n else {\n attachedElement = null;\n }\n }\n }\n }\n else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {\n if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {\n _this.dragging = false;\n _this._moving = false;\n _this.currentDraggingPointerID = -1;\n pickedMesh = null;\n _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);\n // Reattach camera controls\n if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {\n _this._scene.activeCamera.attachControl(attachedElement, true);\n }\n }\n }\n else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {\n if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {\n var zDragFactor = _this.zDragFactor;\n if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {\n pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);\n zDragFactor = 0;\n }\n // Calculate controller drag distance in controller space\n var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);\n lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);\n var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);\n _this._virtualOriginMesh.addChild(_this._virtualDragMesh);\n // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away\n _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;\n if (_this._virtualDragMesh.position.z < 0) {\n _this._virtualDragMesh.position.z = 0;\n }\n // Update the controller position\n _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);\n _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));\n _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);\n // Move the virtualObjectsPosition into the picked mesh's space if needed\n _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);\n if (pickedMesh.parent) {\n BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);\n }\n if (!_this._moving) {\n _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);\n }\n _this._moving = true;\n }\n }\n });\n var tmpQuaternion = new BABYLON.Quaternion();\n // On every frame move towards target scaling to avoid jitter caused by vr controllers\n this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {\n if (_this.dragging && _this._moving && pickedMesh) {\n // Slowly move mesh to avoid jitter\n pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));\n // Get change in rotation\n tmpQuaternion.copyFrom(_this._startingOrientation);\n tmpQuaternion.x = -tmpQuaternion.x;\n tmpQuaternion.y = -tmpQuaternion.y;\n tmpQuaternion.z = -tmpQuaternion.z;\n _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);\n // Convert change in rotation to only y axis rotation\n BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles(\"xyz\").y, 0, 0, tmpQuaternion);\n tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);\n // Slowly move mesh to avoid jitter\n var oldParent = pickedMesh.parent;\n pickedMesh.setParent(null);\n BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);\n pickedMesh.setParent(oldParent);\n }\n });\n };\n /**\n * Detaches the behavior from the mesh\n */\n SixDofDragBehavior.prototype.detach = function () {\n if (this._scene) {\n this._scene.onPointerObservable.remove(this._pointerObserver);\n }\n if (this._ownerNode) {\n this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);\n }\n if (this._virtualOriginMesh) {\n this._virtualOriginMesh.dispose();\n }\n if (this._virtualDragMesh) {\n this._virtualDragMesh.dispose();\n }\n };\n return SixDofDragBehavior;\n }());\n BABYLON.SixDofDragBehavior = SixDofDragBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sixDofDragBehavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * @hidden\n */\n var FaceDirectionInfo = /** @class */ (function () {\n function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {\n if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }\n if (diff === void 0) { diff = 0; }\n if (ignore === void 0) { ignore = false; }\n this.direction = direction;\n this.rotatedDirection = rotatedDirection;\n this.diff = diff;\n this.ignore = ignore;\n }\n return FaceDirectionInfo;\n }());\n /**\n * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera\n */\n var AttachToBoxBehavior = /** @class */ (function () {\n /**\n * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera\n * @param ui The transform node that should be attched to the mesh\n */\n function AttachToBoxBehavior(ui) {\n this.ui = ui;\n /**\n * The name of the behavior\n */\n this.name = \"AttachToBoxBehavior\";\n /**\n * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)\n */\n this.distanceAwayFromFace = 0.15;\n /**\n * The distance from the bottom of the face that the UI should be attached to (default: 0.15)\n */\n this.distanceAwayFromBottomOfFace = 0.15;\n this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];\n this._tmpMatrix = new BABYLON.Matrix();\n this._tmpVector = new BABYLON.Vector3();\n this._zeroVector = BABYLON.Vector3.Zero();\n this._lookAtTmpMatrix = new BABYLON.Matrix();\n /* Does nothing */\n }\n /**\n * Initializes the behavior\n */\n AttachToBoxBehavior.prototype.init = function () {\n /* Does nothing */\n };\n AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {\n var _this = this;\n // Go over each face and calculate the angle between the face's normal and targetDirection\n this._faceVectors.forEach(function (v) {\n if (!_this._target.rotationQuaternion) {\n _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);\n }\n _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);\n BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);\n v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));\n });\n // Return the face information of the one with the normal closeset to target direction\n return this._faceVectors.reduce(function (min, p) {\n if (min.ignore) {\n return p;\n }\n else if (p.ignore) {\n return min;\n }\n else {\n return min.diff < p.diff ? min : p;\n }\n }, this._faceVectors[0]);\n };\n AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {\n if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }\n BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);\n this._lookAtTmpMatrix.invert();\n BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);\n };\n /**\n * Attaches the AttachToBoxBehavior to the passed in mesh\n * @param target The mesh that the specified node will be attached to\n */\n AttachToBoxBehavior.prototype.attach = function (target) {\n var _this = this;\n this._target = target;\n this._scene = this._target.getScene();\n // Every frame, update the app bars position\n this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {\n if (!_this._scene.activeCamera) {\n return;\n }\n // Find the face closest to the cameras position\n var cameraPos = _this._scene.activeCamera.position;\n if (_this._scene.activeCamera.devicePosition) {\n cameraPos = _this._scene.activeCamera.devicePosition;\n }\n var facing = _this._closestFace(cameraPos.subtract(target.position));\n if (_this._scene.activeCamera.leftCamera) {\n _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);\n }\n else {\n _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);\n }\n // Get camera up direction\n BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);\n // Ignore faces to not select a parrelel face for the up vector of the UI\n _this._faceVectors.forEach(function (v) {\n if (facing.direction.x && v.direction.x) {\n v.ignore = true;\n }\n if (facing.direction.y && v.direction.y) {\n v.ignore = true;\n }\n if (facing.direction.z && v.direction.z) {\n v.ignore = true;\n }\n });\n var facingUp = _this._closestFace(_this._tmpVector);\n // Unignore faces\n _this._faceVectors.forEach(function (v) {\n v.ignore = false;\n });\n // Position the app bar on that face\n _this.ui.position.copyFrom(target.position);\n if (facing.direction.x) {\n facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);\n _this.ui.position.addInPlace(_this._tmpVector);\n }\n if (facing.direction.y) {\n facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);\n _this.ui.position.addInPlace(_this._tmpVector);\n }\n if (facing.direction.z) {\n facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);\n _this.ui.position.addInPlace(_this._tmpVector);\n }\n // Rotate to be oriented properly to the camera\n if (!_this.ui.rotationQuaternion) {\n _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);\n }\n facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);\n _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);\n // Place ui the correct distance from the bottom of the mesh\n if (facingUp.direction.x) {\n _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);\n }\n if (facingUp.direction.y) {\n _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);\n }\n if (facingUp.direction.z) {\n _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);\n }\n _this.ui.position.addInPlace(_this._tmpVector);\n });\n };\n /**\n * Detaches the behavior from the mesh\n */\n AttachToBoxBehavior.prototype.detach = function () {\n this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);\n };\n return AttachToBoxBehavior;\n }());\n BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.attachToBoxBehavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.\n */\n var Gizmo = /** @class */ (function () {\n /**\n * Creates a gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n */\n function Gizmo(\n /** The utility layer the gizmo will be added to */\n gizmoLayer) {\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = this;\n this.gizmoLayer = gizmoLayer;\n this._scaleFactor = 3;\n this._tmpMatrix = new BABYLON.Matrix();\n /**\n * If a custom mesh has been set (Default: false)\n */\n this._customMeshSet = false;\n /**\n * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)\n */\n this.updateGizmoRotationToMatchAttachedMesh = true;\n /**\n * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)\n */\n this.updateGizmoPositionToMatchAttachedMesh = true;\n /**\n * When set, the gizmo will always appear the same size no matter where the camera is (default: false)\n */\n this._updateScale = true;\n this._interactionsEnabled = true;\n this._tempVector = new BABYLON.Vector3();\n this._rootMesh = new BABYLON.Mesh(\"gizmoRootNode\", gizmoLayer.utilityLayerScene);\n this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {\n _this._update();\n });\n this.attachedMesh = null;\n }\n Object.defineProperty(Gizmo.prototype, \"attachedMesh\", {\n /**\n * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)\n * * When set, interactions will be enabled\n */\n get: function () {\n return this._attachedMesh;\n },\n set: function (value) {\n this._attachedMesh = value;\n this._rootMesh.setEnabled(value ? true : false);\n this._attachedMeshChanged(value);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes and replaces the current meshes in the gizmo with the specified mesh\n * @param mesh The mesh to replace the default mesh of the gizmo\n */\n Gizmo.prototype.setCustomMesh = function (mesh) {\n if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {\n throw \"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)\";\n }\n this._rootMesh.getChildMeshes().forEach(function (c) {\n c.dispose();\n });\n mesh.parent = this._rootMesh;\n this._customMeshSet = true;\n };\n Gizmo.prototype._attachedMeshChanged = function (value) {\n };\n /**\n * @hidden\n * Updates the gizmo to match the attached mesh's position/rotation\n */\n Gizmo.prototype._update = function () {\n if (this.attachedMesh) {\n if (this.updateGizmoRotationToMatchAttachedMesh) {\n if (!this._rootMesh.rotationQuaternion) {\n this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);\n }\n // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale\n this._tempVector.copyFrom(this.attachedMesh.scaling);\n if (this.attachedMesh.scaling.x < 0) {\n this.attachedMesh.scaling.x *= -1;\n }\n if (this.attachedMesh.scaling.y < 0) {\n this.attachedMesh.scaling.y *= -1;\n }\n if (this.attachedMesh.scaling.z < 0) {\n this.attachedMesh.scaling.z *= -1;\n }\n this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);\n this.attachedMesh.scaling.copyFrom(this._tempVector);\n this.attachedMesh.computeWorldMatrix();\n BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);\n }\n if (this.updateGizmoPositionToMatchAttachedMesh) {\n this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);\n }\n if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {\n var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;\n if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {\n cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;\n }\n this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);\n var dist = this._tempVector.length() / this._scaleFactor;\n this._rootMesh.scaling.set(dist, dist, dist);\n }\n }\n };\n /**\n * Disposes of the gizmo\n */\n Gizmo.prototype.dispose = function () {\n this._rootMesh.dispose();\n if (this._beforeRenderObserver) {\n this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);\n }\n };\n return Gizmo;\n }());\n BABYLON.Gizmo = Gizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Single axis drag gizmo\n */\n var AxisDragGizmo = /** @class */ (function (_super) {\n __extends(AxisDragGizmo, _super);\n /**\n * Creates an AxisDragGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param dragAxis The axis which the gizmo will be able to drag on\n * @param color The color of the gizmo\n */\n function AxisDragGizmo(dragAxis, color, gizmoLayer) {\n if (color === void 0) { color = BABYLON.Color3.Gray(); }\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this._pointerObserver = null;\n /**\n * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n _this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n _this.onSnapObservable = new BABYLON.Observable();\n // Create Material\n var coloredMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n coloredMaterial.disableLighting = true;\n coloredMaterial.emissiveColor = color;\n var hoverMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n hoverMaterial.disableLighting = true;\n hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));\n // Build mesh on root node\n var arrow = new BABYLON.AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n var arrowMesh = BABYLON.MeshBuilder.CreateCylinder(\"yPosMesh\", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);\n var arrowTail = BABYLON.MeshBuilder.CreateLines(\"yPosMesh\", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);\n arrowTail.color = coloredMaterial.emissiveColor;\n arrow.addChild(arrowMesh);\n arrow.addChild(arrowTail);\n // Position arrow pointing in its drag axis\n arrowMesh.scaling.scaleInPlace(0.05);\n arrowMesh.material = coloredMaterial;\n arrowMesh.rotation.x = Math.PI / 2;\n arrowMesh.position.z += 0.3;\n arrowTail.scaling.scaleInPlace(0.2);\n arrowTail.rotation.x = Math.PI / 2;\n arrowTail.material = coloredMaterial;\n arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));\n _this._rootMesh.addChild(arrow);\n var currentSnapDragDistance = 0;\n var tmpVector = new BABYLON.Vector3();\n var tmpSnapEvent = { snapDistance: 0 };\n // Add drag behavior to handle events when the gizmo is dragged\n _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });\n _this.dragBehavior.moveAttached = false;\n _this._rootMesh.addBehavior(_this.dragBehavior);\n _this.dragBehavior.onDragObservable.add(function (event) {\n if (_this.attachedMesh) {\n // Snapping logic\n if (_this.snapDistance == 0) {\n _this.attachedMesh.position.addInPlace(event.delta);\n }\n else {\n currentSnapDragDistance += event.dragDistance;\n if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {\n var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);\n currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;\n event.delta.normalizeToRef(tmpVector);\n tmpVector.scaleInPlace(_this.snapDistance * dragSteps);\n _this.attachedMesh.position.addInPlace(tmpVector);\n tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;\n _this.onSnapObservable.notifyObservers(tmpSnapEvent);\n }\n }\n }\n });\n _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {\n if (_this._customMeshSet) {\n return;\n }\n var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);\n var material = isHovered ? hoverMaterial : coloredMaterial;\n _this._rootMesh.getChildMeshes().forEach(function (m) {\n m.material = material;\n if (m.color) {\n m.color = material.emissiveColor;\n }\n });\n });\n return _this;\n }\n AxisDragGizmo.prototype._attachedMeshChanged = function (value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n };\n /**\n * Disposes of the gizmo\n */\n AxisDragGizmo.prototype.dispose = function () {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n _super.prototype.dispose.call(this);\n };\n return AxisDragGizmo;\n }(BABYLON.Gizmo));\n BABYLON.AxisDragGizmo = AxisDragGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.axisDragGizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Single axis scale gizmo\n */\n var AxisScaleGizmo = /** @class */ (function (_super) {\n __extends(AxisScaleGizmo, _super);\n /**\n * Creates an AxisScaleGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param dragAxis The axis which the gizmo will be able to scale on\n * @param color The color of the gizmo\n */\n function AxisScaleGizmo(dragAxis, color, gizmoLayer) {\n if (color === void 0) { color = BABYLON.Color3.Gray(); }\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this._pointerObserver = null;\n /**\n * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n _this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n _this.onSnapObservable = new BABYLON.Observable();\n // Create Material\n var coloredMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n coloredMaterial.disableLighting = true;\n coloredMaterial.emissiveColor = color;\n var hoverMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n hoverMaterial.disableLighting = true;\n hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));\n // Build mesh on root node\n var arrow = new BABYLON.AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n var arrowMesh = BABYLON.MeshBuilder.CreateBox(\"yPosMesh\", { size: 0.4 }, gizmoLayer.utilityLayerScene);\n var arrowTail = BABYLON.MeshBuilder.CreateLines(\"yPosMesh\", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);\n arrowTail.color = coloredMaterial.emissiveColor;\n arrow.addChild(arrowMesh);\n arrow.addChild(arrowTail);\n // Position arrow pointing in its drag axis\n arrowMesh.scaling.scaleInPlace(0.1);\n arrowMesh.material = coloredMaterial;\n arrowMesh.rotation.x = Math.PI / 2;\n arrowMesh.position.z += 0.3;\n arrowTail.scaling.scaleInPlace(0.2);\n arrowTail.rotation.x = Math.PI / 2;\n arrowTail.material = coloredMaterial;\n arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));\n _this._rootMesh.addChild(arrow);\n // Add drag behavior to handle events when the gizmo is dragged\n _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });\n _this.dragBehavior.moveAttached = false;\n _this._rootMesh.addBehavior(_this.dragBehavior);\n var currentSnapDragDistance = 0;\n var tmpVector = new BABYLON.Vector3();\n var tmpSnapEvent = { snapDistance: 0 };\n _this.dragBehavior.onDragObservable.add(function (event) {\n if (_this.attachedMesh) {\n // Snapping logic\n var snapped = false;\n var dragSteps = 0;\n if (_this.snapDistance == 0) {\n dragAxis.scaleToRef(event.dragDistance, tmpVector);\n }\n else {\n currentSnapDragDistance += event.dragDistance;\n if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {\n dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);\n currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;\n dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);\n snapped = true;\n }\n else {\n tmpVector.scaleInPlace(0);\n }\n }\n _this.attachedMesh.scaling.addInPlace(tmpVector);\n if (snapped) {\n tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;\n _this.onSnapObservable.notifyObservers(tmpSnapEvent);\n }\n }\n });\n _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {\n if (_this._customMeshSet) {\n return;\n }\n var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);\n var material = isHovered ? hoverMaterial : coloredMaterial;\n _this._rootMesh.getChildMeshes().forEach(function (m) {\n m.material = material;\n if (m.color) {\n m.color = material.emissiveColor;\n }\n });\n });\n return _this;\n }\n AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n };\n /**\n * Disposes of the gizmo\n */\n AxisScaleGizmo.prototype.dispose = function () {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n _super.prototype.dispose.call(this);\n };\n return AxisScaleGizmo;\n }(BABYLON.Gizmo));\n BABYLON.AxisScaleGizmo = AxisScaleGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.axisScaleGizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Single plane rotation gizmo\n */\n var PlaneRotationGizmo = /** @class */ (function (_super) {\n __extends(PlaneRotationGizmo, _super);\n /**\n * Creates a PlaneRotationGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param planeNormal The normal of the plane which the gizmo will be able to rotate on\n * @param color The color of the gizmo\n */\n function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {\n if (color === void 0) { color = BABYLON.Color3.Gray(); }\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this._pointerObserver = null;\n /**\n * Rotation distance in radians that the gizmo will snap to (Default: 0)\n */\n _this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n _this.onSnapObservable = new BABYLON.Observable();\n // Create Material\n var coloredMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n coloredMaterial.disableLighting = true;\n coloredMaterial.emissiveColor = color;\n var hoverMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n hoverMaterial.disableLighting = true;\n hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));\n // Build mesh on root node\n var parentMesh = new BABYLON.AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n // Create circle out of lines\n var tessellation = 20;\n var radius = 2;\n var points = new Array();\n for (var i = 0; i < tessellation; i++) {\n var radian = (2 * Math.PI) * (i / (tessellation - 1));\n points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));\n }\n var rotationMesh = BABYLON.Mesh.CreateLines(\"\", points, gizmoLayer.utilityLayerScene);\n rotationMesh.color = coloredMaterial.emissiveColor;\n // Position arrow pointing in its drag axis\n rotationMesh.scaling.scaleInPlace(0.1);\n rotationMesh.material = coloredMaterial;\n rotationMesh.rotation.x = Math.PI / 2;\n parentMesh.addChild(rotationMesh);\n parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));\n _this._rootMesh.addChild(parentMesh);\n // Add drag behavior to handle events when the gizmo is dragged\n _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });\n _this.dragBehavior.moveAttached = false;\n _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;\n _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;\n _this._rootMesh.addBehavior(_this.dragBehavior);\n var lastDragPosition = new BABYLON.Vector3();\n _this.dragBehavior.onDragStartObservable.add(function (e) {\n if (_this.attachedMesh) {\n lastDragPosition.copyFrom(e.dragPlanePoint);\n }\n });\n var rotationMatrix = new BABYLON.Matrix();\n var planeNormalTowardsCamera = new BABYLON.Vector3();\n var localPlaneNormalTowardsCamera = new BABYLON.Vector3();\n var tmpSnapEvent = { snapDistance: 0 };\n var currentSnapDragDistance = 0;\n _this.dragBehavior.onDragObservable.add(function (event) {\n if (_this.attachedMesh) {\n if (!_this.attachedMesh.rotationQuaternion) {\n _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);\n }\n // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)\n var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();\n var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();\n var cross = BABYLON.Vector3.Cross(newVector, originalVector);\n var dot = BABYLON.Vector3.Dot(newVector, originalVector);\n var angle = Math.atan2(cross.length(), dot);\n planeNormalTowardsCamera.copyFrom(planeNormal);\n localPlaneNormalTowardsCamera.copyFrom(planeNormal);\n if (_this.updateGizmoRotationToMatchAttachedMesh) {\n _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);\n localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);\n }\n // Flip up vector depending on which side the camera is on\n if (gizmoLayer.utilityLayerScene.activeCamera) {\n var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);\n if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {\n planeNormalTowardsCamera.scaleInPlace(-1);\n localPlaneNormalTowardsCamera.scaleInPlace(-1);\n }\n }\n var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;\n if (halfCircleSide)\n angle = -angle;\n // Snapping logic\n var snapped = false;\n if (_this.snapDistance != 0) {\n currentSnapDragDistance += angle;\n if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {\n var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);\n currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;\n angle = _this.snapDistance * dragSteps;\n snapped = true;\n }\n else {\n angle = 0;\n }\n }\n // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)\n var quaternionCoefficient = Math.sin(angle / 2);\n var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));\n if (_this.updateGizmoRotationToMatchAttachedMesh) {\n // Rotate selected mesh quaternion over fixed axis\n _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);\n }\n else {\n // Rotate selected mesh quaternion over rotated axis\n amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);\n }\n lastDragPosition.copyFrom(event.dragPlanePoint);\n if (snapped) {\n tmpSnapEvent.snapDistance = angle;\n _this.onSnapObservable.notifyObservers(tmpSnapEvent);\n }\n }\n });\n _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {\n if (_this._customMeshSet) {\n return;\n }\n var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);\n var material = isHovered ? hoverMaterial : coloredMaterial;\n _this._rootMesh.getChildMeshes().forEach(function (m) {\n m.material = material;\n if (m.color) {\n m.color = material.emissiveColor;\n }\n });\n });\n return _this;\n }\n PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n };\n /**\n * Disposes of the gizmo\n */\n PlaneRotationGizmo.prototype.dispose = function () {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n _super.prototype.dispose.call(this);\n };\n return PlaneRotationGizmo;\n }(BABYLON.Gizmo));\n BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.planeRotationGizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Gizmo that enables dragging a mesh along 3 axis\n */\n var PositionGizmo = /** @class */ (function (_super) {\n __extends(PositionGizmo, _super);\n /**\n * Creates a PositionGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n */\n function PositionGizmo(gizmoLayer) {\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);\n _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);\n _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);\n _this.attachedMesh = null;\n return _this;\n }\n Object.defineProperty(PositionGizmo.prototype, \"attachedMesh\", {\n set: function (mesh) {\n if (this.xGizmo) {\n this.xGizmo.attachedMesh = mesh;\n this.yGizmo.attachedMesh = mesh;\n this.zGizmo.attachedMesh = mesh;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PositionGizmo.prototype, \"updateGizmoRotationToMatchAttachedMesh\", {\n get: function () {\n return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;\n },\n set: function (value) {\n if (this.xGizmo) {\n this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes of the gizmo\n */\n PositionGizmo.prototype.dispose = function () {\n this.xGizmo.dispose();\n this.yGizmo.dispose();\n this.zGizmo.dispose();\n };\n /**\n * CustomMeshes are not supported by this gizmo\n * @param mesh The mesh to replace the default mesh of the gizmo\n */\n PositionGizmo.prototype.setCustomMesh = function (mesh) {\n BABYLON.Tools.Error(\"Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)\");\n };\n return PositionGizmo;\n }(BABYLON.Gizmo));\n BABYLON.PositionGizmo = PositionGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.positionGizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Gizmo that enables rotating a mesh along 3 axis\n */\n var RotationGizmo = /** @class */ (function (_super) {\n __extends(RotationGizmo, _super);\n /**\n * Creates a RotationGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n */\n function RotationGizmo(gizmoLayer) {\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);\n _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);\n _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);\n _this.attachedMesh = null;\n return _this;\n }\n Object.defineProperty(RotationGizmo.prototype, \"attachedMesh\", {\n set: function (mesh) {\n if (this.xGizmo) {\n this.xGizmo.attachedMesh = mesh;\n this.yGizmo.attachedMesh = mesh;\n this.zGizmo.attachedMesh = mesh;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RotationGizmo.prototype, \"updateGizmoRotationToMatchAttachedMesh\", {\n get: function () {\n return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;\n },\n set: function (value) {\n if (this.xGizmo) {\n this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes of the gizmo\n */\n RotationGizmo.prototype.dispose = function () {\n this.xGizmo.dispose();\n this.yGizmo.dispose();\n this.zGizmo.dispose();\n };\n /**\n * CustomMeshes are not supported by this gizmo\n * @param mesh The mesh to replace the default mesh of the gizmo\n */\n RotationGizmo.prototype.setCustomMesh = function (mesh) {\n BABYLON.Tools.Error(\"Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)\");\n };\n return RotationGizmo;\n }(BABYLON.Gizmo));\n BABYLON.RotationGizmo = RotationGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.rotationGizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Gizmo that enables scaling a mesh along 3 axis\n */\n var ScaleGizmo = /** @class */ (function (_super) {\n __extends(ScaleGizmo, _super);\n /**\n * Creates a ScaleGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n */\n function ScaleGizmo(gizmoLayer) {\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);\n _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);\n _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);\n _this.attachedMesh = null;\n return _this;\n }\n Object.defineProperty(ScaleGizmo.prototype, \"attachedMesh\", {\n set: function (mesh) {\n if (this.xGizmo) {\n this.xGizmo.attachedMesh = mesh;\n this.yGizmo.attachedMesh = mesh;\n this.zGizmo.attachedMesh = mesh;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ScaleGizmo.prototype, \"updateGizmoRotationToMatchAttachedMesh\", {\n get: function () {\n return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;\n },\n set: function (value) {\n if (this.xGizmo) {\n this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes of the gizmo\n */\n ScaleGizmo.prototype.dispose = function () {\n this.xGizmo.dispose();\n this.yGizmo.dispose();\n this.zGizmo.dispose();\n };\n return ScaleGizmo;\n }(BABYLON.Gizmo));\n BABYLON.ScaleGizmo = ScaleGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.scaleGizmo.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Bounding box gizmo\n */\n var BoundingBoxGizmo = /** @class */ (function (_super) {\n __extends(BoundingBoxGizmo, _super);\n /**\n * Creates an BoundingBoxGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param color The color of the gizmo\n */\n function BoundingBoxGizmo(color, gizmoLayer) {\n if (color === void 0) { color = BABYLON.Color3.Gray(); }\n if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }\n var _this = _super.call(this, gizmoLayer) || this;\n _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);\n _this._renderObserver = null;\n _this._pointerObserver = null;\n _this._scaleDragSpeed = 0.2;\n _this._tmpQuaternion = new BABYLON.Quaternion();\n _this._tmpVector = new BABYLON.Vector3(0, 0, 0);\n /**\n * The size of the rotation spheres attached to the bounding box (Default: 0.1)\n */\n _this.rotationSphereSize = 0.1;\n /**\n * The size of the scale boxes attached to the bounding box (Default: 0.1)\n */\n _this.scaleBoxSize = 0.1;\n /**\n * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)\n */\n _this.fixedDragMeshScreenSize = false;\n /**\n * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)\n */\n _this.fixedDragMeshScreenSizeDistanceFactor = 10;\n /**\n * Fired when a rotation sphere or scale box is dragged\n */\n _this.onDragStartObservable = new BABYLON.Observable();\n /**\n * Fired when a rotation sphere or scale box drag is started\n */\n _this.onDragObservable = new BABYLON.Observable();\n /**\n * Fired when a rotation sphere or scale box drag is needed\n */\n _this.onDragEndObservable = new BABYLON.Observable();\n _this._existingMeshScale = new BABYLON.Vector3();\n // Do not update the gizmo's scale so it has a fixed size to the object its attached to\n _this._updateScale = false;\n _this._anchorMesh = new BABYLON.AbstractMesh(\"anchor\", gizmoLayer.utilityLayerScene);\n // Create Materials\n var coloredMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n coloredMaterial.disableLighting = true;\n coloredMaterial.emissiveColor = color;\n var hoverColoredMaterial = new BABYLON.StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n hoverColoredMaterial.disableLighting = true;\n hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));\n // Build bounding box out of lines\n _this._lineBoundingBox = new BABYLON.AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();\n var lines = [];\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(BABYLON.MeshBuilder.CreateLines(\"lines\", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.forEach(function (l) {\n l.color = color;\n l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));\n l.isPickable = false;\n _this._lineBoundingBox.addChild(l);\n });\n _this._rootMesh.addChild(_this._lineBoundingBox);\n // Create rotation spheres\n _this._rotateSpheresParent = new BABYLON.AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();\n var _loop_1 = function (i_1) {\n var sphere = BABYLON.MeshBuilder.CreateSphere(\"\", { diameter: 1 }, gizmoLayer.utilityLayerScene);\n sphere.rotationQuaternion = new BABYLON.Quaternion();\n sphere.material = coloredMaterial;\n // Drag behavior\n _dragBehavior = new BABYLON.PointerDragBehavior({});\n _dragBehavior.moveAttached = false;\n _dragBehavior.updateDragPlane = false;\n sphere.addBehavior(_dragBehavior);\n var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);\n var totalTurnAmountOfDrag = 0;\n _dragBehavior.onDragStartObservable.add(function (event) {\n startingTurnDirection.copyFrom(sphere.forward);\n totalTurnAmountOfDrag = 0;\n });\n _dragBehavior.onDragObservable.add(function (event) {\n _this.onDragObservable.notifyObservers({});\n if (_this.attachedMesh) {\n var worldDragDirection = startingTurnDirection;\n // Project the world right on to the drag plane\n var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));\n var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();\n // project drag delta on to the resulting drag axis and rotate based on that\n var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);\n // Make rotation relative to size of mesh.\n projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();\n // Rotate based on axis\n if (!_this.attachedMesh.rotationQuaternion) {\n _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);\n }\n if (!_this._anchorMesh.rotationQuaternion) {\n _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);\n }\n // Do not allow the object to turn more than a full circle\n totalTurnAmountOfDrag += projectDist;\n if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {\n if (i_1 >= 8) {\n BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);\n }\n else if (i_1 >= 4) {\n BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);\n }\n else {\n BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);\n }\n // Rotate around center of bounding box\n _this._anchorMesh.addChild(_this.attachedMesh);\n _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);\n _this._anchorMesh.removeChild(_this.attachedMesh);\n }\n _this.updateBoundingBox();\n }\n });\n // Selection/deselection\n _dragBehavior.onDragStartObservable.add(function () {\n _this.onDragStartObservable.notifyObservers({});\n _this._selectNode(sphere);\n });\n _dragBehavior.onDragEndObservable.add(function () {\n _this.onDragEndObservable.notifyObservers({});\n _this._selectNode(null);\n });\n this_1._rotateSpheresParent.addChild(sphere);\n };\n var this_1 = this, _dragBehavior;\n for (var i_1 = 0; i_1 < 12; i_1++) {\n _loop_1(i_1);\n }\n _this._rootMesh.addChild(_this._rotateSpheresParent);\n // Create scale cubes\n _this._scaleBoxesParent = new BABYLON.AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();\n for (var i = 0; i < 2; i++) {\n for (var j = 0; j < 2; j++) {\n var _loop_2 = function () {\n var box = BABYLON.MeshBuilder.CreateBox(\"\", { size: 1 }, gizmoLayer.utilityLayerScene);\n box.material = coloredMaterial;\n // Dragging logic\n var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);\n _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });\n _dragBehavior.moveAttached = false;\n box.addBehavior(_dragBehavior);\n _dragBehavior.onDragObservable.add(function (event) {\n _this.onDragObservable.notifyObservers({});\n if (_this.attachedMesh) {\n var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();\n var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);\n deltaScale.scaleInPlace(_this._scaleDragSpeed);\n _this.updateBoundingBox();\n // Scale from the position of the opposite corner \n box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);\n _this._anchorMesh.position.subtractInPlace(_this._tmpVector);\n _this._anchorMesh.addChild(_this.attachedMesh);\n _this._anchorMesh.scaling.addInPlace(deltaScale);\n if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {\n _this._anchorMesh.scaling.subtractInPlace(deltaScale);\n }\n _this._anchorMesh.removeChild(_this.attachedMesh);\n }\n });\n // Selection/deselection\n _dragBehavior.onDragStartObservable.add(function () {\n _this.onDragStartObservable.notifyObservers({});\n _this._selectNode(box);\n });\n _dragBehavior.onDragEndObservable.add(function () {\n _this.onDragEndObservable.notifyObservers({});\n _this._selectNode(null);\n });\n this_2._scaleBoxesParent.addChild(box);\n };\n var this_2 = this, _dragBehavior;\n for (var k = 0; k < 2; k++) {\n _loop_2();\n }\n }\n }\n _this._rootMesh.addChild(_this._scaleBoxesParent);\n // Hover color change\n var pointerIds = new Array();\n _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {\n if (!pointerIds[pointerInfo.event.pointerId]) {\n _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {\n pointerIds[pointerInfo.event.pointerId] = mesh;\n mesh.material = hoverColoredMaterial;\n }\n });\n }\n else {\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {\n pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;\n delete pointerIds[pointerInfo.event.pointerId];\n }\n }\n });\n // Update bounding box positions\n _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {\n // Only update the bouding box if scaling has changed\n if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {\n _this.updateBoundingBox();\n }\n });\n _this.updateBoundingBox();\n return _this;\n }\n BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {\n if (value) {\n // Reset anchor mesh to match attached mesh's scale\n // This is needed to avoid invalid box/sphere position on first drag\n this._anchorMesh.addChild(value);\n this._anchorMesh.removeChild(value);\n this.updateBoundingBox();\n }\n };\n BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {\n this._rotateSpheresParent.getChildMeshes()\n .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {\n m.isVisible = (!selectedMesh || m == selectedMesh);\n });\n };\n BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {\n var _this = this;\n mesh.computeWorldMatrix(true);\n mesh.getChildMeshes().forEach(function (m) {\n _this._recurseComputeWorld(m);\n });\n };\n /**\n * Updates the bounding box information for the Gizmo\n */\n BoundingBoxGizmo.prototype.updateBoundingBox = function () {\n this._update();\n if (this.attachedMesh) {\n // Rotate based on axis\n if (!this.attachedMesh.rotationQuaternion) {\n this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);\n }\n if (!this._anchorMesh.rotationQuaternion) {\n this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);\n }\n this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);\n // Store original position and reset mesh to origin before computing the bounding box\n this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);\n this._tmpVector.copyFrom(this.attachedMesh.position);\n this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);\n this.attachedMesh.position.set(0, 0, 0);\n // Update bounding dimensions/positions \n var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();\n boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);\n // Update gizmo to match bounding box scaling and rotation\n this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);\n this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);\n this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);\n this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);\n this._lineBoundingBox.computeWorldMatrix();\n this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);\n // restore position/rotation values\n this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);\n this.attachedMesh.position.copyFrom(this._tmpVector);\n this._recurseComputeWorld(this.attachedMesh);\n }\n // Update rotation sphere locations\n var rotateSpheres = this._rotateSpheresParent.getChildMeshes();\n for (var i = 0; i < 3; i++) {\n for (var j = 0; j < 2; j++) {\n for (var k = 0; k < 2; k++) {\n var index = ((i * 4) + (j * 2)) + k;\n if (i == 0) {\n rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);\n rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));\n }\n if (i == 1) {\n rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);\n rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));\n }\n if (i == 2) {\n rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);\n rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));\n }\n if (this.fixedDragMeshScreenSize) {\n this._rootMesh.computeWorldMatrix();\n this._rotateSpheresParent.computeWorldMatrix();\n rotateSpheres[index].computeWorldMatrix();\n rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);\n var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;\n rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);\n }\n else {\n rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);\n }\n }\n }\n }\n // Update scale box locations\n var scaleBoxes = this._scaleBoxesParent.getChildMeshes();\n for (var i = 0; i < 2; i++) {\n for (var j = 0; j < 2; j++) {\n for (var k = 0; k < 2; k++) {\n var index = ((i * 4) + (j * 2)) + k;\n if (scaleBoxes[index]) {\n scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);\n scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n if (this.fixedDragMeshScreenSize) {\n this._rootMesh.computeWorldMatrix();\n this._scaleBoxesParent.computeWorldMatrix();\n scaleBoxes[index].computeWorldMatrix();\n scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);\n var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;\n scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);\n }\n else {\n scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);\n }\n }\n }\n }\n }\n if (this.attachedMesh) {\n this._existingMeshScale.copyFrom(this.attachedMesh.scaling);\n }\n };\n /**\n * Enables rotation on the specified axis and disables rotation on the others\n * @param axis The list of axis that should be enabled (eg. \"xy\" or \"xyz\")\n */\n BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {\n this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {\n if (i < 4) {\n m.setEnabled(axis.indexOf(\"x\") != -1);\n }\n else if (i < 8) {\n m.setEnabled(axis.indexOf(\"y\") != -1);\n }\n else {\n m.setEnabled(axis.indexOf(\"z\") != -1);\n }\n });\n };\n /**\n * Disposes of the gizmo\n */\n BoundingBoxGizmo.prototype.dispose = function () {\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);\n this._lineBoundingBox.dispose();\n this._rotateSpheresParent.dispose();\n this._scaleBoxesParent.dispose();\n _super.prototype.dispose.call(this);\n };\n /**\n * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)\n * @param mesh the mesh to wrap in the bounding box mesh and make not pickable\n * @returns the bounding box mesh with the passed in mesh as a child\n */\n BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {\n var makeNotPickable = function (root) {\n root.isPickable = false;\n root.getChildMeshes().forEach(function (c) {\n makeNotPickable(c);\n });\n };\n makeNotPickable(mesh);\n // Reset position to get boudning box from origin with no rotation\n if (!mesh.rotationQuaternion) {\n mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);\n }\n var oldPos = mesh.position.clone();\n var oldRot = mesh.rotationQuaternion.clone();\n mesh.rotationQuaternion.set(0, 0, 0, 1);\n mesh.position.set(0, 0, 0);\n // Update bounding dimensions/positions \n var box = BABYLON.MeshBuilder.CreateBox(\"box\", { size: 1 }, mesh.getScene());\n var boundingMinMax = mesh.getHierarchyBoundingVectors();\n boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);\n box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);\n // Restore original positions\n mesh.addChild(box);\n mesh.rotationQuaternion.copyFrom(oldRot);\n mesh.position.copyFrom(oldPos);\n // Reverse parenting\n mesh.removeChild(box);\n box.addChild(mesh);\n box.visibility = 0;\n return box;\n };\n /**\n * CustomMeshes are not supported by this gizmo\n * @param mesh The mesh to replace the default mesh of the gizmo\n */\n BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {\n BABYLON.Tools.Error(\"Custom meshes are not supported on this gizmo\");\n };\n return BoundingBoxGizmo;\n }(BABYLON.Gizmo));\n BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.boundingBoxGizmo.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Helps setup gizmo's in the scene to rotate/scale/position meshes\n */\n var GizmoManager = /** @class */ (function () {\n /**\n * Instatiates a gizmo manager\n * @param scene the scene to overlay the gizmos on top of\n */\n function GizmoManager(scene) {\n var _this = this;\n this.scene = scene;\n this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };\n this._pointerObserver = null;\n this._attachedMesh = null;\n this._boundingBoxColor = BABYLON.Color3.FromHexString(\"#0984e3\");\n this._dragBehavior = new BABYLON.SixDofDragBehavior();\n /**\n * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)\n */\n this.attachableMeshes = null;\n /**\n * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)\n */\n this.usePointerToAttachGizmos = true;\n this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };\n // Instatiate/dispose gizmos based on pointer actions\n this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {\n if (!_this.usePointerToAttachGizmos) {\n return;\n }\n if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {\n var node = pointerInfo.pickInfo.pickedMesh;\n if (_this.attachableMeshes == null) {\n // Attach to the most parent node\n while (node && node.parent != null) {\n node = node.parent;\n }\n }\n else {\n // Attach to the parent node that is an attachableMesh\n var found = false;\n _this.attachableMeshes.forEach(function (mesh) {\n if (node && (node == mesh || node.isDescendantOf(mesh))) {\n node = mesh;\n found = true;\n }\n });\n if (!found) {\n node = null;\n }\n }\n if (node instanceof BABYLON.AbstractMesh) {\n _this.attachToMesh(node);\n }\n }\n else {\n _this.attachToMesh(null);\n }\n }\n });\n }\n /**\n * Attaches a set of gizmos to the specified mesh\n * @param mesh The mesh the gizmo's should be attached to\n */\n GizmoManager.prototype.attachToMesh = function (mesh) {\n if (this._attachedMesh) {\n this._attachedMesh.removeBehavior(this._dragBehavior);\n }\n this._attachedMesh = mesh;\n for (var key in this.gizmos) {\n var gizmo = (this.gizmos[key]);\n if (gizmo && this._gizmosEnabled[key]) {\n gizmo.attachedMesh = mesh;\n }\n }\n if (this.boundingBoxGizmoEnabled && this._attachedMesh) {\n this._attachedMesh.addBehavior(this._dragBehavior);\n }\n };\n Object.defineProperty(GizmoManager.prototype, \"positionGizmoEnabled\", {\n get: function () {\n return this._gizmosEnabled.positionGizmo;\n },\n /**\n * If the position gizmo is enabled\n */\n set: function (value) {\n if (value) {\n this.gizmos.positionGizmo = this.gizmos.positionGizmo || new BABYLON.PositionGizmo();\n this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;\n this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;\n }\n else if (this.gizmos.positionGizmo) {\n this.gizmos.positionGizmo.attachedMesh = null;\n }\n this._gizmosEnabled.positionGizmo = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GizmoManager.prototype, \"rotationGizmoEnabled\", {\n get: function () {\n return this._gizmosEnabled.rotationGizmo;\n },\n /**\n * If the rotation gizmo is enabled\n */\n set: function (value) {\n if (value) {\n this.gizmos.rotationGizmo = this.gizmos.rotationGizmo || new BABYLON.RotationGizmo();\n this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;\n this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;\n }\n else if (this.gizmos.rotationGizmo) {\n this.gizmos.rotationGizmo.attachedMesh = null;\n }\n this._gizmosEnabled.rotationGizmo = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GizmoManager.prototype, \"scaleGizmoEnabled\", {\n get: function () {\n return this._gizmosEnabled.scaleGizmo;\n },\n /**\n * If the scale gizmo is enabled\n */\n set: function (value) {\n if (value) {\n this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();\n this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;\n }\n else if (this.gizmos.scaleGizmo) {\n this.gizmos.scaleGizmo.attachedMesh = null;\n }\n this._gizmosEnabled.scaleGizmo = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GizmoManager.prototype, \"boundingBoxGizmoEnabled\", {\n get: function () {\n return this._gizmosEnabled.boundingBoxGizmo;\n },\n /**\n * If the boundingBox gizmo is enabled\n */\n set: function (value) {\n if (value) {\n this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);\n this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;\n if (this._attachedMesh) {\n this._attachedMesh.removeBehavior(this._dragBehavior);\n this._attachedMesh.addBehavior(this._dragBehavior);\n }\n }\n else if (this.gizmos.boundingBoxGizmo) {\n this.gizmos.boundingBoxGizmo.attachedMesh = null;\n }\n this._gizmosEnabled.boundingBoxGizmo = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes of the gizmo manager\n */\n GizmoManager.prototype.dispose = function () {\n this.scene.onPointerObservable.remove(this._pointerObserver);\n for (var key in this.gizmos) {\n var gizmo = (this.gizmos[key]);\n if (gizmo) {\n gizmo.dispose();\n }\n }\n this._dragBehavior.detach();\n this._gizmoLayer.dispose();\n };\n return GizmoManager;\n }());\n BABYLON.GizmoManager = GizmoManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.gizmoManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines a target to use with MorphTargetManager\n * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets\n */\n var MorphTarget = /** @class */ (function () {\n /**\n * Creates a new MorphTarget\n * @param name defines the name of the target\n * @param influence defines the influence to use\n */\n function MorphTarget(\n /** defines the name of the target */\n name, influence, scene) {\n if (influence === void 0) { influence = 0; }\n if (scene === void 0) { scene = null; }\n this.name = name;\n /**\n * Gets or sets the list of animations\n */\n this.animations = new Array();\n this._positions = null;\n this._normals = null;\n this._tangents = null;\n /**\n * Observable raised when the influence changes\n */\n this.onInfluenceChanged = new BABYLON.Observable();\n this._animationPropertiesOverride = null;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this.influence = influence;\n }\n Object.defineProperty(MorphTarget.prototype, \"influence\", {\n /**\n * Gets or sets the influence of this target (ie. its weight in the overall morphing)\n */\n get: function () {\n return this._influence;\n },\n set: function (influence) {\n if (this._influence === influence) {\n return;\n }\n var previous = this._influence;\n this._influence = influence;\n if (this.onInfluenceChanged.hasObservers) {\n this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTarget.prototype, \"animationPropertiesOverride\", {\n /**\n * Gets or sets the animation properties override\n */\n get: function () {\n if (!this._animationPropertiesOverride && this._scene) {\n return this._scene.animationPropertiesOverride;\n }\n return this._animationPropertiesOverride;\n },\n set: function (value) {\n this._animationPropertiesOverride = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTarget.prototype, \"hasPositions\", {\n /**\n * Gets a boolean defining if the target contains position data\n */\n get: function () {\n return !!this._positions;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTarget.prototype, \"hasNormals\", {\n /**\n * Gets a boolean defining if the target contains normal data\n */\n get: function () {\n return !!this._normals;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTarget.prototype, \"hasTangents\", {\n /**\n * Gets a boolean defining if the target contains tangent data\n */\n get: function () {\n return !!this._tangents;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Affects position data to this target\n * @param data defines the position data to use\n */\n MorphTarget.prototype.setPositions = function (data) {\n this._positions = data;\n };\n /**\n * Gets the position data stored in this target\n * @returns a FloatArray containing the position data (or null if not present)\n */\n MorphTarget.prototype.getPositions = function () {\n return this._positions;\n };\n /**\n * Affects normal data to this target\n * @param data defines the normal data to use\n */\n MorphTarget.prototype.setNormals = function (data) {\n this._normals = data;\n };\n /**\n * Gets the normal data stored in this target\n * @returns a FloatArray containing the normal data (or null if not present)\n */\n MorphTarget.prototype.getNormals = function () {\n return this._normals;\n };\n /**\n * Affects tangent data to this target\n * @param data defines the tangent data to use\n */\n MorphTarget.prototype.setTangents = function (data) {\n this._tangents = data;\n };\n /**\n * Gets the tangent data stored in this target\n * @returns a FloatArray containing the tangent data (or null if not present)\n */\n MorphTarget.prototype.getTangents = function () {\n return this._tangents;\n };\n /**\n * Serializes the current target into a Serialization object\n * @returns the serialized object\n */\n MorphTarget.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.influence = this.influence;\n serializationObject.positions = Array.prototype.slice.call(this.getPositions());\n if (this.hasNormals) {\n serializationObject.normals = Array.prototype.slice.call(this.getNormals());\n }\n if (this.hasTangents) {\n serializationObject.tangents = Array.prototype.slice.call(this.getTangents());\n }\n // Animations\n BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);\n return serializationObject;\n };\n // Statics\n /**\n * Creates a new target from serialized data\n * @param serializationObject defines the serialized data to use\n * @returns a new MorphTarget\n */\n MorphTarget.Parse = function (serializationObject) {\n var result = new MorphTarget(serializationObject.name, serializationObject.influence);\n result.setPositions(serializationObject.positions);\n if (serializationObject.normals) {\n result.setNormals(serializationObject.normals);\n }\n if (serializationObject.tangents) {\n result.setTangents(serializationObject.tangents);\n }\n // Animations\n if (serializationObject.animations) {\n for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {\n var parsedAnimation = serializationObject.animations[animationIndex];\n result.animations.push(BABYLON.Animation.Parse(parsedAnimation));\n }\n }\n return result;\n };\n /**\n * Creates a MorphTarget from mesh data\n * @param mesh defines the source mesh\n * @param name defines the name to use for the new target\n * @param influence defines the influence to attach to the target\n * @returns a new MorphTarget\n */\n MorphTarget.FromMesh = function (mesh, name, influence) {\n if (!name) {\n name = mesh.name;\n }\n var result = new MorphTarget(name, influence, mesh.getScene());\n result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {\n result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));\n }\n return result;\n };\n return MorphTarget;\n }());\n BABYLON.MorphTarget = MorphTarget;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.morphTarget.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class is used to deform meshes using morphing between different targets\n * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets\n */\n var MorphTargetManager = /** @class */ (function () {\n /**\n * Creates a new MorphTargetManager\n * @param scene defines the current scene\n */\n function MorphTargetManager(scene) {\n if (scene === void 0) { scene = null; }\n this._targets = new Array();\n this._targetObservable = new Array();\n this._activeTargets = new BABYLON.SmartArray(16);\n this._supportsNormals = false;\n this._supportsTangents = false;\n this._vertexCount = 0;\n this._uniqueId = 0;\n this._tempInfluences = new Array();\n if (!scene) {\n scene = BABYLON.Engine.LastCreatedScene;\n }\n this._scene = scene;\n if (this._scene) {\n this._scene.morphTargetManagers.push(this);\n this._uniqueId = this._scene.getUniqueId();\n }\n }\n Object.defineProperty(MorphTargetManager.prototype, \"uniqueId\", {\n /**\n * Gets the unique ID of this manager\n */\n get: function () {\n return this._uniqueId;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTargetManager.prototype, \"vertexCount\", {\n /**\n * Gets the number of vertices handled by this manager\n */\n get: function () {\n return this._vertexCount;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTargetManager.prototype, \"supportsNormals\", {\n /**\n * Gets a boolean indicating if this manager supports morphing of normals\n */\n get: function () {\n return this._supportsNormals;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTargetManager.prototype, \"supportsTangents\", {\n /**\n * Gets a boolean indicating if this manager supports morphing of tangents\n */\n get: function () {\n return this._supportsTangents;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTargetManager.prototype, \"numTargets\", {\n /**\n * Gets the number of targets stored in this manager\n */\n get: function () {\n return this._targets.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTargetManager.prototype, \"numInfluencers\", {\n /**\n * Gets the number of influencers (ie. the number of targets with influences > 0)\n */\n get: function () {\n return this._activeTargets.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(MorphTargetManager.prototype, \"influences\", {\n /**\n * Gets the list of influences (one per target)\n */\n get: function () {\n return this._influences;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the active target at specified index. An active target is a target with an influence > 0\n * @param index defines the index to check\n * @returns the requested target\n */\n MorphTargetManager.prototype.getActiveTarget = function (index) {\n return this._activeTargets.data[index];\n };\n /**\n * Gets the target at specified index\n * @param index defines the index to check\n * @returns the requested target\n */\n MorphTargetManager.prototype.getTarget = function (index) {\n return this._targets[index];\n };\n /**\n * Add a new target to this manager\n * @param target defines the target to add\n */\n MorphTargetManager.prototype.addTarget = function (target) {\n var _this = this;\n this._targets.push(target);\n this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {\n _this._syncActiveTargets(needUpdate);\n }));\n this._syncActiveTargets(true);\n };\n /**\n * Removes a target from the manager\n * @param target defines the target to remove\n */\n MorphTargetManager.prototype.removeTarget = function (target) {\n var index = this._targets.indexOf(target);\n if (index >= 0) {\n this._targets.splice(index, 1);\n target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);\n this._syncActiveTargets(true);\n }\n };\n /**\n * Serializes the current manager into a Serialization object\n * @returns the serialized object\n */\n MorphTargetManager.prototype.serialize = function () {\n var serializationObject = {};\n serializationObject.id = this.uniqueId;\n serializationObject.targets = [];\n for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {\n var target = _a[_i];\n serializationObject.targets.push(target.serialize());\n }\n return serializationObject;\n };\n MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {\n var influenceCount = 0;\n this._activeTargets.reset();\n this._supportsNormals = true;\n this._supportsTangents = true;\n this._vertexCount = 0;\n for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {\n var target = _a[_i];\n this._activeTargets.push(target);\n this._tempInfluences[influenceCount++] = target.influence;\n var positions = target.getPositions();\n if (positions) {\n this._supportsNormals = this._supportsNormals && target.hasNormals;\n this._supportsTangents = this._supportsTangents && target.hasTangents;\n var vertexCount = positions.length / 3;\n if (this._vertexCount === 0) {\n this._vertexCount = vertexCount;\n }\n else if (this._vertexCount !== vertexCount) {\n BABYLON.Tools.Error(\"Incompatible target. Targets must all have the same vertices count.\");\n return;\n }\n }\n }\n if (!this._influences || this._influences.length !== influenceCount) {\n this._influences = new Float32Array(influenceCount);\n }\n for (var index = 0; index < influenceCount; index++) {\n this._influences[index] = this._tempInfluences[index];\n }\n if (needUpdate) {\n this.synchronize();\n }\n };\n /**\n * Syncrhonize the targets with all the meshes using this morph target manager\n */\n MorphTargetManager.prototype.synchronize = function () {\n if (!this._scene) {\n return;\n }\n // Flag meshes as dirty to resync with the active targets\n for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {\n var mesh = _a[_i];\n if (mesh.morphTargetManager === this) {\n mesh._syncGeometryWithMorphTargetManager();\n }\n }\n };\n // Statics\n /**\n * Creates a new MorphTargetManager from serialized data\n * @param serializationObject defines the serialized data\n * @param scene defines the hosting scene\n * @returns the new MorphTargetManager\n */\n MorphTargetManager.Parse = function (serializationObject, scene) {\n var result = new MorphTargetManager(scene);\n result._uniqueId = serializationObject.id;\n for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {\n var targetData = _a[_i];\n result.addTarget(BABYLON.MorphTarget.Parse(targetData));\n }\n return result;\n };\n return MorphTargetManager;\n }());\n BABYLON.MorphTargetManager = MorphTargetManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.morphTargetManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Octree = /** @class */ (function () {\n function Octree(creationFunc, maxBlockCapacity, maxDepth) {\n if (maxDepth === void 0) { maxDepth = 2; }\n this.maxDepth = maxDepth;\n this.dynamicContent = new Array();\n this._maxBlockCapacity = maxBlockCapacity || 64;\n this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);\n this._creationFunc = creationFunc;\n }\n // Methods\n Octree.prototype.update = function (worldMin, worldMax, entries) {\n Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);\n };\n Octree.prototype.addMesh = function (entry) {\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.addEntry(entry);\n }\n };\n Octree.prototype.select = function (frustumPlanes, allowDuplicate) {\n this._selectionContent.reset();\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.select(frustumPlanes, this._selectionContent, allowDuplicate);\n }\n if (allowDuplicate) {\n this._selectionContent.concat(this.dynamicContent);\n }\n else {\n this._selectionContent.concatWithNoDuplicate(this.dynamicContent);\n }\n return this._selectionContent;\n };\n Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {\n this._selectionContent.reset();\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);\n }\n if (allowDuplicate) {\n this._selectionContent.concat(this.dynamicContent);\n }\n else {\n this._selectionContent.concatWithNoDuplicate(this.dynamicContent);\n }\n return this._selectionContent;\n };\n Octree.prototype.intersectsRay = function (ray) {\n this._selectionContent.reset();\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.intersectsRay(ray, this._selectionContent);\n }\n this._selectionContent.concatWithNoDuplicate(this.dynamicContent);\n return this._selectionContent;\n };\n Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {\n target.blocks = new Array();\n var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);\n // Segmenting space\n for (var x = 0; x < 2; x++) {\n for (var y = 0; y < 2; y++) {\n for (var z = 0; z < 2; z++) {\n var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));\n var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));\n var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);\n block.addEntries(entries);\n target.blocks.push(block);\n }\n }\n }\n };\n Octree.CreationFuncForMeshes = function (entry, block) {\n var boundingInfo = entry.getBoundingInfo();\n if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {\n block.entries.push(entry);\n }\n };\n Octree.CreationFuncForSubMeshes = function (entry, block) {\n var boundingInfo = entry.getBoundingInfo();\n if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {\n block.entries.push(entry);\n }\n };\n return Octree;\n }());\n BABYLON.Octree = Octree;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.octree.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var OctreeBlock = /** @class */ (function () {\n function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {\n this.entries = new Array();\n this._boundingVectors = new Array();\n this._capacity = capacity;\n this._depth = depth;\n this._maxDepth = maxDepth;\n this._creationFunc = creationFunc;\n this._minPoint = minPoint;\n this._maxPoint = maxPoint;\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors[2].x = maxPoint.x;\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors[3].y = maxPoint.y;\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors[4].z = maxPoint.z;\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors[5].z = minPoint.z;\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors[6].x = minPoint.x;\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors[7].y = minPoint.y;\n }\n Object.defineProperty(OctreeBlock.prototype, \"capacity\", {\n // Property\n get: function () {\n return this._capacity;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(OctreeBlock.prototype, \"minPoint\", {\n get: function () {\n return this._minPoint;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(OctreeBlock.prototype, \"maxPoint\", {\n get: function () {\n return this._maxPoint;\n },\n enumerable: true,\n configurable: true\n });\n // Methods\n OctreeBlock.prototype.addEntry = function (entry) {\n if (this.blocks) {\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.addEntry(entry);\n }\n return;\n }\n this._creationFunc(entry, this);\n if (this.entries.length > this.capacity && this._depth < this._maxDepth) {\n this.createInnerBlocks();\n }\n };\n OctreeBlock.prototype.addEntries = function (entries) {\n for (var index = 0; index < entries.length; index++) {\n var mesh = entries[index];\n this.addEntry(mesh);\n }\n };\n OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {\n if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {\n if (this.blocks) {\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.select(frustumPlanes, selection, allowDuplicate);\n }\n return;\n }\n if (allowDuplicate) {\n selection.concat(this.entries);\n }\n else {\n selection.concatWithNoDuplicate(this.entries);\n }\n }\n };\n OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {\n if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {\n if (this.blocks) {\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);\n }\n return;\n }\n if (allowDuplicate) {\n selection.concat(this.entries);\n }\n else {\n selection.concatWithNoDuplicate(this.entries);\n }\n }\n };\n OctreeBlock.prototype.intersectsRay = function (ray, selection) {\n if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {\n if (this.blocks) {\n for (var index = 0; index < this.blocks.length; index++) {\n var block = this.blocks[index];\n block.intersectsRay(ray, selection);\n }\n return;\n }\n selection.concatWithNoDuplicate(this.entries);\n }\n };\n OctreeBlock.prototype.createInnerBlocks = function () {\n BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);\n };\n return OctreeBlock;\n }());\n BABYLON.OctreeBlock = OctreeBlock;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.octreeBlock.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Postprocess used to generate anaglyphic rendering\n */\n var AnaglyphPostProcess = /** @class */ (function (_super) {\n __extends(AnaglyphPostProcess, _super);\n /**\n * Creates a new AnaglyphPostProcess\n * @param name defines postprocess name\n * @param options defines creation options or target ratio scale\n * @param rigCameras defines cameras using this postprocess\n * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)\n * @param engine defines hosting engine\n * @param reusable defines if the postprocess will be reused multiple times per frame\n */\n function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {\n var _this = _super.call(this, name, \"anaglyph\", null, [\"leftSampler\"], options, rigCameras[1], samplingMode, engine, reusable) || this;\n _this._passedProcess = rigCameras[0]._rigPostProcess;\n _this.onApplyObservable.add(function (effect) {\n effect.setTextureFromPostProcess(\"leftSampler\", _this._passedProcess);\n });\n return _this;\n }\n return AnaglyphPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.anaglyphPostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"AnaglyphArcRotateCamera\", function (name, scene, options) {\n return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };\n });\n /**\n * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)\n */\n var AnaglyphArcRotateCamera = /** @class */ (function (_super) {\n __extends(AnaglyphArcRotateCamera, _super);\n /**\n * Creates a new AnaglyphArcRotateCamera\n * @param name defines camera name\n * @param alpha defines alpha angle (in radians)\n * @param beta defines beta angle (in radians)\n * @param radius defines radius\n * @param target defines camera target\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {\n var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns AnaglyphArcRotateCamera\n */\n AnaglyphArcRotateCamera.prototype.getClassName = function () {\n return \"AnaglyphArcRotateCamera\";\n };\n return AnaglyphArcRotateCamera;\n }(BABYLON.ArcRotateCamera));\n BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"AnaglyphFreeCamera\", function (name, scene, options) {\n return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };\n });\n /**\n * Camera used to simulate anaglyphic rendering (based on FreeCamera)\n */\n var AnaglyphFreeCamera = /** @class */ (function (_super) {\n __extends(AnaglyphFreeCamera, _super);\n /**\n * Creates a new AnaglyphFreeCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns AnaglyphFreeCamera\n */\n AnaglyphFreeCamera.prototype.getClassName = function () {\n return \"AnaglyphFreeCamera\";\n };\n return AnaglyphFreeCamera;\n }(BABYLON.FreeCamera));\n BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.anaglyphFreeCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"AnaglyphGamepadCamera\", function (name, scene, options) {\n return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };\n });\n /**\n * Camera used to simulate anaglyphic rendering (based on GamepadCamera)\n */\n var AnaglyphGamepadCamera = /** @class */ (function (_super) {\n __extends(AnaglyphGamepadCamera, _super);\n /**\n * Creates a new AnaglyphGamepadCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns AnaglyphGamepadCamera\n */\n AnaglyphGamepadCamera.prototype.getClassName = function () {\n return \"AnaglyphGamepadCamera\";\n };\n return AnaglyphGamepadCamera;\n }(BABYLON.GamepadCamera));\n BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"AnaglyphUniversalCamera\", function (name, scene, options) {\n return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };\n });\n /**\n * Camera used to simulate anaglyphic rendering (based on UniversalCamera)\n */\n var AnaglyphUniversalCamera = /** @class */ (function (_super) {\n __extends(AnaglyphUniversalCamera, _super);\n /**\n * Creates a new AnaglyphUniversalCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns AnaglyphUniversalCamera\n */\n AnaglyphUniversalCamera.prototype.getClassName = function () {\n return \"AnaglyphUniversalCamera\";\n };\n return AnaglyphUniversalCamera;\n }(BABYLON.UniversalCamera));\n BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {\n __extends(StereoscopicInterlacePostProcess, _super);\n function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {\n var _this = _super.call(this, name, \"stereoscopicInterlace\", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? \"#define IS_STEREOSCOPIC_HORIZ 1\" : undefined) || this;\n _this._passedProcess = rigCameras[0]._rigPostProcess;\n _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);\n _this.onSizeChangedObservable.add(function () {\n _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);\n });\n _this.onApplyObservable.add(function (effect) {\n effect.setTextureFromPostProcess(\"camASampler\", _this._passedProcess);\n effect.setFloat2(\"stepSize\", _this._stepSize.x, _this._stepSize.y);\n });\n return _this;\n }\n return StereoscopicInterlacePostProcess;\n }(BABYLON.PostProcess));\n BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"StereoscopicArcRotateCamera\", function (name, scene, options) {\n return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };\n });\n /**\n * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)\n */\n var StereoscopicArcRotateCamera = /** @class */ (function (_super) {\n __extends(StereoscopicArcRotateCamera, _super);\n /**\n * Creates a new StereoscopicArcRotateCamera\n * @param name defines camera name\n * @param alpha defines alpha angle (in radians)\n * @param beta defines beta angle (in radians)\n * @param radius defines radius\n * @param target defines camera target\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {\n var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns StereoscopicArcRotateCamera\n */\n StereoscopicArcRotateCamera.prototype.getClassName = function () {\n return \"StereoscopicArcRotateCamera\";\n };\n return StereoscopicArcRotateCamera;\n }(BABYLON.ArcRotateCamera));\n BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"StereoscopicFreeCamera\", function (name, scene, options) {\n return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };\n });\n /**\n * Camera used to simulate stereoscopic rendering (based on FreeCamera)\n */\n var StereoscopicFreeCamera = /** @class */ (function (_super) {\n __extends(StereoscopicFreeCamera, _super);\n /**\n * Creates a new StereoscopicFreeCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns StereoscopicFreeCamera\n */\n StereoscopicFreeCamera.prototype.getClassName = function () {\n return \"StereoscopicFreeCamera\";\n };\n return StereoscopicFreeCamera;\n }(BABYLON.FreeCamera));\n BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"StereoscopicGamepadCamera\", function (name, scene, options) {\n return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };\n });\n /**\n * Camera used to simulate stereoscopic rendering (based on GamepadCamera)\n */\n var StereoscopicGamepadCamera = /** @class */ (function (_super) {\n __extends(StereoscopicGamepadCamera, _super);\n /**\n * Creates a new StereoscopicGamepadCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns StereoscopicGamepadCamera\n */\n StereoscopicGamepadCamera.prototype.getClassName = function () {\n return \"StereoscopicGamepadCamera\";\n };\n return StereoscopicGamepadCamera;\n }(BABYLON.GamepadCamera));\n BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"StereoscopicFreeCamera\", function (name, scene, options) {\n return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };\n });\n /**\n * Camera used to simulate stereoscopic rendering (based on UniversalCamera)\n */\n var StereoscopicUniversalCamera = /** @class */ (function (_super) {\n __extends(StereoscopicUniversalCamera, _super);\n /**\n * Creates a new StereoscopicUniversalCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.interaxialDistance = interaxialDistance;\n _this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });\n return _this;\n }\n /**\n * Gets camera class name\n * @returns StereoscopicUniversalCamera\n */\n StereoscopicUniversalCamera.prototype.getClassName = function () {\n return \"StereoscopicUniversalCamera\";\n };\n return StereoscopicUniversalCamera;\n }(BABYLON.UniversalCamera));\n BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {\n __extends(VRDistortionCorrectionPostProcess, _super);\n function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {\n var _this = _super.call(this, name, \"vrDistortionCorrection\", [\n 'LensCenter',\n 'Scale',\n 'ScaleIn',\n 'HmdWarpParam'\n ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;\n _this._isRightEye = isRightEye;\n _this._distortionFactors = vrMetrics.distortionK;\n _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;\n _this._lensCenterOffset = vrMetrics.lensCenterOffset;\n _this.adaptScaleToCurrentViewport = true;\n _this.onSizeChangedObservable.add(function () {\n _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);\n _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);\n _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);\n });\n _this.onApplyObservable.add(function (effect) {\n effect.setFloat2(\"LensCenter\", _this._lensCenter.x, _this._lensCenter.y);\n effect.setFloat2(\"Scale\", _this._scaleFactor.x, _this._scaleFactor.y);\n effect.setFloat2(\"ScaleIn\", _this._scaleIn.x, _this._scaleIn.y);\n effect.setFloat4(\"HmdWarpParam\", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);\n });\n return _this;\n }\n return VRDistortionCorrectionPostProcess;\n }(BABYLON.PostProcess));\n BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.\n * Screen rotation is taken into account.\n */\n var FreeCameraDeviceOrientationInput = /** @class */ (function () {\n function FreeCameraDeviceOrientationInput() {\n var _this = this;\n this._screenOrientationAngle = 0;\n this._screenQuaternion = new BABYLON.Quaternion();\n this._alpha = 0;\n this._beta = 0;\n this._gamma = 0;\n this._orientationChanged = function () {\n _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));\n _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);\n _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));\n };\n this._deviceOrientation = function (evt) {\n _this._alpha = evt.alpha !== null ? evt.alpha : 0;\n _this._beta = evt.beta !== null ? evt.beta : 0;\n _this._gamma = evt.gamma !== null ? evt.gamma : 0;\n };\n this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));\n this._orientationChanged();\n }\n Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, \"camera\", {\n get: function () {\n return this._camera;\n },\n set: function (camera) {\n this._camera = camera;\n if (this._camera != null && !this._camera.rotationQuaternion) {\n this._camera.rotationQuaternion = new BABYLON.Quaternion();\n }\n },\n enumerable: true,\n configurable: true\n });\n FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {\n window.addEventListener(\"orientationchange\", this._orientationChanged);\n window.addEventListener(\"deviceorientation\", this._deviceOrientation);\n //In certain cases, the attach control is called AFTER orientation was changed,\n //So this is needed.\n this._orientationChanged();\n };\n FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {\n window.removeEventListener(\"orientationchange\", this._orientationChanged);\n window.removeEventListener(\"deviceorientation\", this._deviceOrientation);\n };\n FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {\n //if no device orientation provided, don't update the rotation.\n //Only testing against alpha under the assumption thatnorientation will never be so exact when set.\n if (!this._alpha)\n return;\n BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);\n this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);\n this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);\n //Mirror on XY Plane\n this._camera.rotationQuaternion.z *= -1;\n this._camera.rotationQuaternion.w *= -1;\n };\n FreeCameraDeviceOrientationInput.prototype.getClassName = function () {\n return \"FreeCameraDeviceOrientationInput\";\n };\n FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {\n return \"deviceOrientation\";\n };\n return FreeCameraDeviceOrientationInput;\n }());\n BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;\n BABYLON.CameraInputTypes[\"FreeCameraDeviceOrientationInput\"] = FreeCameraDeviceOrientationInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {\n function ArcRotateCameraVRDeviceOrientationInput() {\n this.alphaCorrection = 1;\n this.betaCorrection = 1;\n this.gammaCorrection = 1;\n this._alpha = 0;\n this._gamma = 0;\n this._dirty = false;\n this._deviceOrientationHandler = this._onOrientationEvent.bind(this);\n }\n ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {\n this.camera.attachControl(element, noPreventDefault);\n window.addEventListener(\"deviceorientation\", this._deviceOrientationHandler);\n };\n ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {\n if (evt.alpha !== null) {\n this._alpha = +evt.alpha | 0;\n }\n if (evt.gamma !== null) {\n this._gamma = +evt.gamma | 0;\n }\n this._dirty = true;\n };\n ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {\n if (this._dirty) {\n this._dirty = false;\n if (this._gamma < 0) {\n this._gamma = 180 + this._gamma;\n }\n this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;\n this.camera.beta = (this._gamma / 180.0 * Math.PI);\n }\n };\n ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {\n window.removeEventListener(\"deviceorientation\", this._deviceOrientationHandler);\n };\n ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {\n return \"ArcRotateCameraVRDeviceOrientationInput\";\n };\n ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {\n return \"VRDeviceOrientation\";\n };\n return ArcRotateCameraVRDeviceOrientationInput;\n }());\n BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;\n BABYLON.CameraInputTypes[\"ArcRotateCameraVRDeviceOrientationInput\"] = ArcRotateCameraVRDeviceOrientationInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var VRCameraMetrics = /** @class */ (function () {\n function VRCameraMetrics() {\n this.compensateDistortion = true;\n }\n Object.defineProperty(VRCameraMetrics.prototype, \"aspectRatio\", {\n get: function () {\n return this.hResolution / (2 * this.vResolution);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRCameraMetrics.prototype, \"aspectRatioFov\", {\n get: function () {\n return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRCameraMetrics.prototype, \"leftHMatrix\", {\n get: function () {\n var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);\n var h = (4 * meters) / this.hScreenSize;\n return BABYLON.Matrix.Translation(h, 0, 0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRCameraMetrics.prototype, \"rightHMatrix\", {\n get: function () {\n var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);\n var h = (4 * meters) / this.hScreenSize;\n return BABYLON.Matrix.Translation(-h, 0, 0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRCameraMetrics.prototype, \"leftPreViewMatrix\", {\n get: function () {\n return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRCameraMetrics.prototype, \"rightPreViewMatrix\", {\n get: function () {\n return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);\n },\n enumerable: true,\n configurable: true\n });\n VRCameraMetrics.GetDefault = function () {\n var result = new VRCameraMetrics();\n result.hResolution = 1280;\n result.vResolution = 800;\n result.hScreenSize = 0.149759993;\n result.vScreenSize = 0.0935999975;\n result.vScreenCenter = 0.0467999987;\n result.eyeToScreenDistance = 0.0410000011;\n result.lensSeparationDistance = 0.0635000020;\n result.interpupillaryDistance = 0.0640000030;\n result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];\n result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];\n result.postProcessScaleFactor = 1.714605507808412;\n result.lensCenterOffset = 0.151976421;\n return result;\n };\n return VRCameraMetrics;\n }());\n BABYLON.VRCameraMetrics = VRCameraMetrics;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vrCameraMetrics.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"WebVRFreeCamera\", function (name, scene) {\n return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n BABYLON.Node.AddNodeConstructor(\"WebVRGamepadCamera\", function (name, scene) {\n return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n /**\n * This represents a WebVR camera.\n * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.\n * @example http://doc.babylonjs.com/how_to/webvr_camera\n */\n var WebVRFreeCamera = /** @class */ (function (_super) {\n __extends(WebVRFreeCamera, _super);\n /**\n * Instantiates a WebVRFreeCamera.\n * @param name The name of the WebVRFreeCamera\n * @param position The starting anchor position for the camera\n * @param scene The scene the camera belongs to\n * @param webVROptions a set of customizable options for the webVRCamera\n */\n function WebVRFreeCamera(name, position, scene, webVROptions) {\n if (webVROptions === void 0) { webVROptions = {}; }\n var _this = _super.call(this, name, position, scene) || this;\n _this.webVROptions = webVROptions;\n /**\n * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay\n */\n _this._vrDevice = null;\n /**\n * The rawPose of the vrDevice.\n */\n _this.rawPose = null;\n _this._specsVersion = \"1.1\";\n _this._attached = false;\n _this._descendants = [];\n // Represents device position and rotation in room space. Should only be used to help calculate babylon space values\n _this._deviceRoomPosition = BABYLON.Vector3.Zero();\n /** @hidden */\n _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();\n _this._standingMatrix = null;\n /**\n * Represents device position in babylon space.\n */\n _this.devicePosition = BABYLON.Vector3.Zero();\n /**\n * Represents device rotation in babylon space.\n */\n _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();\n /**\n * The scale of the device to be used when translating from device space to babylon space.\n */\n _this.deviceScaleFactor = 1;\n _this._deviceToWorld = BABYLON.Matrix.Identity();\n _this._worldToDevice = BABYLON.Matrix.Identity();\n /**\n * References to the webVR controllers for the vrDevice.\n */\n _this.controllers = [];\n /**\n * Emits an event when a controller is attached.\n */\n _this.onControllersAttachedObservable = new BABYLON.Observable();\n /**\n * Emits an event when a controller's mesh has been loaded;\n */\n _this.onControllerMeshLoadedObservable = new BABYLON.Observable();\n /**\n * Emits an event when the HMD's pose has been updated.\n */\n _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();\n _this._poseSet = false;\n /**\n * If the rig cameras be used as parent instead of this camera.\n */\n _this.rigParenting = true;\n _this._defaultHeight = undefined;\n _this._workingVector = BABYLON.Vector3.Zero();\n _this._oneVector = BABYLON.Vector3.One();\n _this._workingMatrix = BABYLON.Matrix.Identity();\n _this._cache.position = BABYLON.Vector3.Zero();\n if (webVROptions.defaultHeight) {\n _this._defaultHeight = webVROptions.defaultHeight;\n _this.position.y = _this._defaultHeight;\n }\n _this.minZ = 0.1;\n //legacy support - the compensation boolean was removed.\n if (arguments.length === 5) {\n _this.webVROptions = arguments[4];\n }\n // default webVR options\n if (_this.webVROptions.trackPosition == undefined) {\n _this.webVROptions.trackPosition = true;\n }\n if (_this.webVROptions.controllerMeshes == undefined) {\n _this.webVROptions.controllerMeshes = true;\n }\n if (_this.webVROptions.defaultLightingOnControllers == undefined) {\n _this.webVROptions.defaultLightingOnControllers = true;\n }\n _this.rotationQuaternion = new BABYLON.Quaternion();\n if (_this.webVROptions && _this.webVROptions.positionScale) {\n _this.deviceScaleFactor = _this.webVROptions.positionScale;\n }\n //enable VR\n var engine = _this.getEngine();\n _this._onVREnabled = function (success) { if (success) {\n _this.initControllers();\n } };\n engine.onVRRequestPresentComplete.add(_this._onVREnabled);\n engine.initWebVR().add(function (event) {\n if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {\n return;\n }\n _this._vrDevice = event.vrDisplay;\n //reset the rig parameters.\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });\n if (_this._attached) {\n _this.getEngine().enableVR();\n }\n });\n if (typeof (VRFrameData) !== \"undefined\")\n _this._frameData = new VRFrameData();\n /**\n * The idea behind the following lines:\n * objects that have the camera as parent should actually have the rig cameras as a parent.\n * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,\n * the second will not show it correctly.\n *\n * To solve this - each object that has the camera as parent will be added to a protected array.\n * When the rig camera renders, it will take this array and set all of those to be its children.\n * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.\n * Amazing!\n */\n scene.onBeforeCameraRenderObservable.add(function (camera) {\n if (camera.parent === _this && _this.rigParenting) {\n _this._descendants = _this.getDescendants(true, function (n) {\n // don't take the cameras or the controllers!\n var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });\n var isRigCamera = _this._rigCameras.indexOf(n) !== -1;\n return !isController && !isRigCamera;\n });\n _this._descendants.forEach(function (node) {\n node.parent = camera;\n });\n }\n });\n scene.onAfterCameraRenderObservable.add(function (camera) {\n if (camera.parent === _this && _this.rigParenting) {\n _this._descendants.forEach(function (node) {\n node.parent = _this;\n });\n }\n });\n return _this;\n }\n /**\n * Gets the device distance from the ground in meters.\n * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.\n */\n WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {\n if (this._standingMatrix) {\n // Add standing matrix offset to get real offset from ground in room\n this._standingMatrix.getTranslationToRef(this._workingVector);\n return this._deviceRoomPosition.y + this._workingVector.y;\n }\n //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.\n return this._defaultHeight || 0;\n };\n /**\n * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.\n * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.\n */\n WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {\n var _this = this;\n if (callback === void 0) { callback = function (bool) { }; }\n // Use standing matrix if available\n this.getEngine().initWebVRAsync().then(function (result) {\n if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {\n callback(false);\n }\n else {\n _this._standingMatrix = new BABYLON.Matrix();\n BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);\n if (!_this.getScene().useRightHandedSystem) {\n [2, 6, 8, 9, 14].forEach(function (num) {\n if (_this._standingMatrix) {\n _this._standingMatrix.m[num] *= -1;\n }\n });\n }\n callback(true);\n }\n });\n };\n /**\n * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.\n * @returns A promise with a boolean set to if the standing matrix is supported.\n */\n WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {\n var _this = this;\n return new Promise(function (res, rej) {\n _this.useStandingMatrix(function (supported) {\n res(supported);\n });\n });\n };\n /**\n * Disposes the camera\n */\n WebVRFreeCamera.prototype.dispose = function () {\n this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);\n _super.prototype.dispose.call(this);\n };\n /**\n * Gets a vrController by name.\n * @param name The name of the controller to retreive\n * @returns the controller matching the name specified or null if not found\n */\n WebVRFreeCamera.prototype.getControllerByName = function (name) {\n for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {\n var gp = _a[_i];\n if (gp.hand === name) {\n return gp;\n }\n }\n return null;\n };\n Object.defineProperty(WebVRFreeCamera.prototype, \"leftController\", {\n /**\n * The controller corrisponding to the users left hand.\n */\n get: function () {\n if (!this._leftController) {\n this._leftController = this.getControllerByName(\"left\");\n }\n return this._leftController;\n },\n enumerable: true,\n configurable: true\n });\n ;\n Object.defineProperty(WebVRFreeCamera.prototype, \"rightController\", {\n /**\n * The controller corrisponding to the users right hand.\n */\n get: function () {\n if (!this._rightController) {\n this._rightController = this.getControllerByName(\"right\");\n }\n return this._rightController;\n },\n enumerable: true,\n configurable: true\n });\n ;\n /**\n * Casts a ray forward from the vrCamera's gaze.\n * @param length Length of the ray (default: 100)\n * @returns the ray corrisponding to the gaze\n */\n WebVRFreeCamera.prototype.getForwardRay = function (length) {\n if (length === void 0) { length = 100; }\n if (this.leftCamera) {\n // Use left eye to avoid computation to compute center on every call\n return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera\n }\n else {\n return _super.prototype.getForwardRay.call(this, length);\n }\n };\n /**\n * Updates the camera based on device's frame data\n */\n WebVRFreeCamera.prototype._checkInputs = function () {\n if (this._vrDevice && this._vrDevice.isPresenting) {\n this._vrDevice.getFrameData(this._frameData);\n this.updateFromDevice(this._frameData.pose);\n }\n _super.prototype._checkInputs.call(this);\n };\n /**\n * Updates the poseControlled values based on the input device pose.\n * @param poseData Pose coming from the device\n */\n WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {\n if (poseData && poseData.orientation) {\n this.rawPose = poseData;\n this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);\n if (this.getScene().useRightHandedSystem) {\n this._deviceRoomRotationQuaternion.z *= -1;\n this._deviceRoomRotationQuaternion.w *= -1;\n }\n if (this.webVROptions.trackPosition && this.rawPose.position) {\n this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);\n if (this.getScene().useRightHandedSystem) {\n this._deviceRoomPosition.z *= -1;\n }\n }\n this._poseSet = true;\n }\n };\n /**\n * WebVR's attach control will start broadcasting frames to the device.\n * Note that in certain browsers (chrome for example) this function must be called\n * within a user-interaction callback. Example:\n *
 scene.onPointerDown = function() { camera.attachControl(canvas); }
\n *\n * @param element html element to attach the vrDevice to\n * @param noPreventDefault prevent the default html element operation when attaching the vrDevice\n */\n WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {\n _super.prototype.attachControl.call(this, element, noPreventDefault);\n this._attached = true;\n noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;\n if (this._vrDevice) {\n this.getEngine().enableVR();\n }\n };\n /**\n * Detaches the camera from the html element and disables VR\n *\n * @param element html element to detach from\n */\n WebVRFreeCamera.prototype.detachControl = function (element) {\n this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);\n this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);\n _super.prototype.detachControl.call(this, element);\n this._attached = false;\n this.getEngine().disableVR();\n };\n /**\n * @returns the name of this class\n */\n WebVRFreeCamera.prototype.getClassName = function () {\n return \"WebVRFreeCamera\";\n };\n /**\n * Calls resetPose on the vrDisplay\n * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose\n */\n WebVRFreeCamera.prototype.resetToCurrentRotation = function () {\n //uses the vrDisplay's \"resetPose()\".\n //pitch and roll won't be affected.\n this._vrDevice.resetPose();\n };\n /**\n * Updates the rig cameras (left and right eye)\n */\n WebVRFreeCamera.prototype._updateRigCameras = function () {\n var camLeft = this._rigCameras[0];\n var camRight = this._rigCameras[1];\n camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);\n camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);\n camLeft.position.copyFrom(this._deviceRoomPosition);\n camRight.position.copyFrom(this._deviceRoomPosition);\n };\n /**\n * Updates the cached values of the camera\n * @param ignoreParentClass ignores updating the parent class's cache (default: false)\n */\n WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {\n var _this = this;\n if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {\n // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition\n if (!this.updateCacheCalled) {\n // make sure it is only called once per loop. this.update() might cause an infinite loop.\n this.updateCacheCalled = true;\n this.update();\n }\n // Set working vector to the device position in room space rotated by the new rotation\n this.rotationQuaternion.toRotationMatrix(this._workingMatrix);\n BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);\n // Subtract this vector from the current device position in world to get the translation for the device world matrix\n this.devicePosition.subtractToRef(this._workingVector, this._workingVector);\n BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);\n // Add translation from anchor position\n this._deviceToWorld.getTranslationToRef(this._workingVector);\n this._workingVector.addInPlace(this.position);\n this._workingVector.subtractInPlace(this._cache.position);\n this._deviceToWorld.setTranslation(this._workingVector);\n // Set an inverted matrix to be used when updating the camera\n this._deviceToWorld.invertToRef(this._worldToDevice);\n // Update the gamepad to ensure the mesh is updated on the same frame as camera\n this.controllers.forEach(function (controller) {\n controller._deviceToWorld.copyFrom(_this._deviceToWorld);\n controller.update();\n });\n }\n if (!ignoreParentClass) {\n _super.prototype._updateCache.call(this);\n }\n this.updateCacheCalled = false;\n };\n /**\n * Updates the current device position and rotation in the babylon world\n */\n WebVRFreeCamera.prototype.update = function () {\n // Get current device position in babylon world\n BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);\n // Get current device rotation in babylon world\n BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);\n this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);\n BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);\n if (this._poseSet) {\n this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);\n }\n _super.prototype.update.call(this);\n };\n /**\n * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)\n * @returns an identity matrix\n */\n WebVRFreeCamera.prototype._getViewMatrix = function () {\n return BABYLON.Matrix.Identity();\n };\n /**\n * This function is called by the two RIG cameras.\n * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)\n */\n WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {\n var _this = this;\n // Update the parent camera prior to using a child camera to avoid desynchronization\n var parentCamera = this._cameraRigParams[\"parentCamera\"];\n parentCamera._updateCache();\n //WebVR 1.1\n var viewArray = this._cameraRigParams[\"left\"] ? this._cameraRigParams[\"frameData\"].leftViewMatrix : this._cameraRigParams[\"frameData\"].rightViewMatrix;\n BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);\n if (!this.getScene().useRightHandedSystem) {\n [2, 6, 8, 9, 14].forEach(function (num) {\n _this._webvrViewMatrix.m[num] *= -1;\n });\n }\n // update the camera rotation matrix\n this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);\n BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);\n // Computing target and final matrix\n this.position.addToRef(this._transformedReferencePoint, this._currentTarget);\n // should the view matrix be updated with scale and position offset?\n if (parentCamera.deviceScaleFactor !== 1) {\n this._webvrViewMatrix.invert();\n // scale the position, if set\n if (parentCamera.deviceScaleFactor) {\n this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;\n this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;\n this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;\n }\n this._webvrViewMatrix.invert();\n }\n parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);\n // Compute global position\n this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();\n this._webvrViewMatrix.invertToRef(this._workingMatrix);\n this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);\n this._workingMatrix.getTranslationToRef(this._globalPosition);\n this._markSyncedWithParent();\n return this._webvrViewMatrix;\n };\n WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {\n var _this = this;\n var parentCamera = this.parent;\n parentCamera._vrDevice.depthNear = parentCamera.minZ;\n parentCamera._vrDevice.depthFar = parentCamera.maxZ;\n var projectionArray = this._cameraRigParams[\"left\"] ? this._cameraRigParams[\"frameData\"].leftProjectionMatrix : this._cameraRigParams[\"frameData\"].rightProjectionMatrix;\n BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);\n //babylon compatible matrix\n if (!this.getScene().useRightHandedSystem) {\n [8, 9, 10, 11].forEach(function (num) {\n _this._projectionMatrix.m[num] *= -1;\n });\n }\n return this._projectionMatrix;\n };\n /**\n * Initializes the controllers and their meshes\n */\n WebVRFreeCamera.prototype.initControllers = function () {\n var _this = this;\n this.controllers = [];\n var manager = this.getScene().gamepadManager;\n this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {\n if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {\n var webVrController = gamepad;\n if (webVrController.defaultModel) {\n webVrController.defaultModel.setEnabled(false);\n }\n if (webVrController.hand === \"right\") {\n _this._rightController = null;\n }\n if (webVrController.hand === \"left\") {\n _this._leftController = null;\n }\n var controllerIndex = _this.controllers.indexOf(webVrController);\n if (controllerIndex !== -1) {\n _this.controllers.splice(controllerIndex, 1);\n }\n }\n });\n this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {\n if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {\n var webVrController_1 = gamepad;\n webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;\n webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);\n if (_this.webVROptions.controllerMeshes) {\n if (webVrController_1.defaultModel) {\n webVrController_1.defaultModel.setEnabled(true);\n }\n else {\n // Load the meshes\n webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {\n loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);\n _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);\n if (_this.webVROptions.defaultLightingOnControllers) {\n if (!_this._lightOnControllers) {\n _this._lightOnControllers = new BABYLON.HemisphericLight(\"vrControllersLight\", new BABYLON.Vector3(0, 1, 0), _this.getScene());\n }\n var activateLightOnSubMeshes_1 = function (mesh, light) {\n var children = mesh.getChildren();\n if (children.length !== 0) {\n children.forEach(function (mesh) {\n light.includedOnlyMeshes.push(mesh);\n activateLightOnSubMeshes_1(mesh, light);\n });\n }\n };\n _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);\n activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);\n }\n });\n }\n }\n webVrController_1.attachToPoseControlledCamera(_this);\n // since this is async - sanity check. Is the controller already stored?\n if (_this.controllers.indexOf(webVrController_1) === -1) {\n //add to the controllers array\n _this.controllers.push(webVrController_1);\n // Forced to add some control code for Vive as it doesn't always fill properly the \"hand\" property\n // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...\n // So we're overriding setting left & right manually to be sure\n var firstViveWandDetected = false;\n for (var i = 0; i < _this.controllers.length; i++) {\n if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {\n if (!firstViveWandDetected) {\n firstViveWandDetected = true;\n _this.controllers[i].hand = \"left\";\n }\n else {\n _this.controllers[i].hand = \"right\";\n }\n }\n }\n //did we find enough controllers? Great! let the developer know.\n if (_this.controllers.length >= 2) {\n _this.onControllersAttachedObservable.notifyObservers(_this.controllers);\n }\n }\n }\n });\n };\n return WebVRFreeCamera;\n }(BABYLON.FreeCamera));\n BABYLON.WebVRFreeCamera = WebVRFreeCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.webVRCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"DeviceOrientationCamera\", function (name, scene) {\n return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n // We're mainly based on the logic defined into the FreeCamera code\n /**\n * This is a camera specifically designed to react to device orientation events such as a modern mobile device\n * being tilted forward or back and left or right.\n */\n var DeviceOrientationCamera = /** @class */ (function (_super) {\n __extends(DeviceOrientationCamera, _super);\n /**\n * Creates a new device orientation camera\n * @param name The name of the camera\n * @param position The start position camera\n * @param scene The scene the camera belongs to\n */\n function DeviceOrientationCamera(name, position, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this._quaternionCache = new BABYLON.Quaternion();\n _this.inputs.addDeviceOrientation();\n return _this;\n }\n /**\n * Gets the current instance class name (\"DeviceOrientationCamera\").\n * This helps avoiding instanceof at run time.\n * @returns the class name\n */\n DeviceOrientationCamera.prototype.getClassName = function () {\n return \"DeviceOrientationCamera\";\n };\n /**\n * Checks and applies the current values of the inputs to the camera. (Internal use only)\n */\n DeviceOrientationCamera.prototype._checkInputs = function () {\n _super.prototype._checkInputs.call(this);\n this._quaternionCache.copyFrom(this.rotationQuaternion);\n if (this._initialQuaternion) {\n this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n }\n };\n /**\n * Reset the camera to its default orientation on the specified axis only.\n * @param axis The axis to reset\n */\n DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {\n var _this = this;\n if (axis === void 0) { axis = BABYLON.Axis.Y; }\n //can only work if this camera has a rotation quaternion already.\n if (!this.rotationQuaternion)\n return;\n if (!this._initialQuaternion) {\n this._initialQuaternion = new BABYLON.Quaternion();\n }\n this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);\n ['x', 'y', 'z'].forEach(function (axisName) {\n if (!axis[axisName]) {\n _this._initialQuaternion[axisName] = 0;\n }\n else {\n _this._initialQuaternion[axisName] *= -1;\n }\n });\n this._initialQuaternion.normalize();\n //force rotation update\n this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n };\n return DeviceOrientationCamera;\n }(BABYLON.FreeCamera));\n BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.deviceOrientationCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"VRDeviceOrientationFreeCamera\", function (name, scene) {\n return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {\n __extends(VRDeviceOrientationFreeCamera, _super);\n function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {\n if (compensateDistortion === void 0) { compensateDistortion = true; }\n if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }\n var _this = _super.call(this, name, position, scene) || this;\n vrCameraMetrics.compensateDistortion = compensateDistortion;\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });\n return _this;\n }\n VRDeviceOrientationFreeCamera.prototype.getClassName = function () {\n return \"VRDeviceOrientationFreeCamera\";\n };\n return VRDeviceOrientationFreeCamera;\n }(BABYLON.DeviceOrientationCamera));\n BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"VRDeviceOrientationFreeCamera\", function (name, scene) {\n return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };\n });\n var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {\n __extends(VRDeviceOrientationArcRotateCamera, _super);\n function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {\n if (compensateDistortion === void 0) { compensateDistortion = true; }\n if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }\n var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;\n vrCameraMetrics.compensateDistortion = compensateDistortion;\n _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });\n _this.inputs.addVRDeviceOrientation();\n return _this;\n }\n VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {\n return \"VRDeviceOrientationArcRotateCamera\";\n };\n return VRDeviceOrientationArcRotateCamera;\n }(BABYLON.ArcRotateCamera));\n BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"VRDeviceOrientationGamepadCamera\", function (name, scene) {\n return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {\n __extends(VRDeviceOrientationGamepadCamera, _super);\n function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {\n if (compensateDistortion === void 0) { compensateDistortion = true; }\n if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }\n var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;\n _this.inputs.addGamepad();\n return _this;\n }\n VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {\n return \"VRDeviceOrientationGamepadCamera\";\n };\n return VRDeviceOrientationGamepadCamera;\n }(BABYLON.VRDeviceOrientationFreeCamera));\n BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var VRExperienceHelperGazer = /** @class */ (function () {\n function VRExperienceHelperGazer(scene, gazeTrackerToClone) {\n if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }\n this.scene = scene;\n this._pointerDownOnMeshAsked = false;\n this._isActionableMesh = false;\n this._teleportationRequestInitiated = false;\n this._teleportationBackRequestInitiated = false;\n this._rotationRightAsked = false;\n this._rotationLeftAsked = false;\n this._dpadPressed = true;\n this._activePointer = false;\n this._id = VRExperienceHelperGazer._idCounter++;\n // Gaze tracker\n if (!gazeTrackerToClone) {\n this._gazeTracker = BABYLON.Mesh.CreateTorus(\"gazeTracker\", 0.0035, 0.0025, 20, scene, false);\n this._gazeTracker.bakeCurrentTransformIntoVertices();\n this._gazeTracker.isPickable = false;\n this._gazeTracker.isVisible = false;\n var targetMat = new BABYLON.StandardMaterial(\"targetMat\", scene);\n targetMat.specularColor = BABYLON.Color3.Black();\n targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);\n targetMat.backFaceCulling = false;\n this._gazeTracker.material = targetMat;\n }\n else {\n this._gazeTracker = gazeTrackerToClone.clone(\"gazeTracker\");\n }\n }\n VRExperienceHelperGazer.prototype._getForwardRay = function (length) {\n return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));\n };\n VRExperienceHelperGazer.prototype._selectionPointerDown = function () {\n this._pointerDownOnMeshAsked = true;\n if (this._currentHit) {\n this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });\n }\n };\n VRExperienceHelperGazer.prototype._selectionPointerUp = function () {\n if (this._currentHit) {\n this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });\n }\n this._pointerDownOnMeshAsked = false;\n };\n VRExperienceHelperGazer.prototype._activatePointer = function () {\n this._activePointer = true;\n };\n VRExperienceHelperGazer.prototype._deactivatePointer = function () {\n this._activePointer = false;\n };\n VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {\n if (distance === void 0) { distance = 100; }\n };\n VRExperienceHelperGazer.prototype.dispose = function () {\n this._interactionsEnabled = false;\n this._teleportationEnabled = false;\n if (this._gazeTracker) {\n this._gazeTracker.dispose();\n }\n };\n VRExperienceHelperGazer._idCounter = 0;\n return VRExperienceHelperGazer;\n }());\n var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {\n __extends(VRExperienceHelperControllerGazer, _super);\n function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {\n var _this = _super.call(this, scene, gazeTrackerToClone) || this;\n _this.webVRController = webVRController;\n // Laser pointer\n _this._laserPointer = BABYLON.Mesh.CreateCylinder(\"laserPointer\", 1, 0.004, 0.0002, 20, 1, scene, false);\n var laserPointerMaterial = new BABYLON.StandardMaterial(\"laserPointerMat\", scene);\n laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);\n laserPointerMaterial.alpha = 0.6;\n _this._laserPointer.material = laserPointerMaterial;\n _this._laserPointer.rotation.x = Math.PI / 2;\n _this._laserPointer.position.z = -0.5;\n _this._laserPointer.isVisible = false;\n _this._laserPointer.isPickable = false;\n if (!webVRController.mesh) {\n // Create an empty mesh that is used prior to loading the high quality model\n var preloadMesh = new BABYLON.Mesh(\"preloadControllerMesh\", scene);\n var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);\n preloadPointerPose.rotation.x = -0.7;\n preloadMesh.addChild(preloadPointerPose);\n webVRController.attachToMesh(preloadMesh);\n }\n _this._setLaserPointerParent(webVRController.mesh);\n _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {\n _this._setLaserPointerParent(mesh);\n });\n return _this;\n }\n VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {\n return this.webVRController.getForwardRay(length);\n };\n VRExperienceHelperControllerGazer.prototype._activatePointer = function () {\n _super.prototype._activatePointer.call(this);\n this._laserPointer.isVisible = true;\n };\n VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {\n _super.prototype._deactivatePointer.call(this);\n this._laserPointer.isVisible = false;\n };\n VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {\n this._laserPointer.material.emissiveColor = color;\n };\n VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {\n var makeNotPick = function (root) {\n root.isPickable = false;\n root.getChildMeshes().forEach(function (c) {\n makeNotPick(c);\n });\n };\n makeNotPick(mesh);\n var childMeshes = mesh.getChildMeshes();\n this.webVRController._pointingPoseNode = null;\n for (var i = 0; i < childMeshes.length; i++) {\n if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {\n mesh = childMeshes[i];\n this.webVRController._pointingPoseNode = mesh;\n break;\n }\n }\n this._laserPointer.parent = mesh;\n };\n VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {\n if (distance === void 0) { distance = 100; }\n this._laserPointer.scaling.y = distance;\n this._laserPointer.position.z = -distance / 2;\n };\n VRExperienceHelperControllerGazer.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this._laserPointer.dispose();\n if (this._meshAttachedObserver) {\n this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);\n }\n };\n return VRExperienceHelperControllerGazer;\n }(VRExperienceHelperGazer));\n var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {\n __extends(VRExperienceHelperCameraGazer, _super);\n function VRExperienceHelperCameraGazer(getCamera, scene) {\n var _this = _super.call(this, scene) || this;\n _this.getCamera = getCamera;\n return _this;\n }\n VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {\n var camera = this.getCamera();\n if (camera) {\n return camera.getForwardRay(length);\n }\n else {\n return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());\n }\n };\n return VRExperienceHelperCameraGazer;\n }(VRExperienceHelperGazer));\n /**\n * Helps to quickly add VR support to an existing scene.\n * See http://doc.babylonjs.com/how_to/webvr_helper\n */\n var VRExperienceHelper = /** @class */ (function () {\n /**\n * Instantiates a VRExperienceHelper.\n * Helps to quickly add VR support to an existing scene.\n * @param scene The scene the VRExperienceHelper belongs to.\n * @param webVROptions Options to modify the vr experience helper's behavior.\n */\n function VRExperienceHelper(scene, \n /** Options to modify the vr experience helper's behavior. */\n webVROptions) {\n if (webVROptions === void 0) { webVROptions = {}; }\n var _this = this;\n this.webVROptions = webVROptions;\n // Can the system support WebVR, even if a headset isn't plugged in?\n this._webVRsupported = false;\n // If WebVR is supported, is a headset plugged in and are we ready to present?\n this._webVRready = false;\n // Are we waiting for the requestPresent callback to complete?\n this._webVRrequesting = false;\n // Are we presenting to the headset right now?\n this._webVRpresenting = false;\n // Are we presenting in the fullscreen fallback?\n this._fullscreenVRpresenting = false;\n /**\n * Observable raised when entering VR.\n */\n this.onEnteringVRObservable = new BABYLON.Observable();\n /**\n * Observable raised when exiting VR.\n */\n this.onExitingVRObservable = new BABYLON.Observable();\n /**\n * Observable raised when controller mesh is loaded.\n */\n this.onControllerMeshLoadedObservable = new BABYLON.Observable();\n this._useCustomVRButton = false;\n this._teleportationRequested = false;\n this._teleportActive = false;\n this._floorMeshesCollection = [];\n this._rotationAllowed = true;\n this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);\n this._isDefaultTeleportationTarget = true;\n this._teleportationFillColor = \"#444444\";\n this._teleportationBorderColor = \"#FFFFFF\";\n this._rotationAngle = 0;\n this._haloCenter = new BABYLON.Vector3(0, 0, 0);\n this._padSensibilityUp = 0.65;\n this._padSensibilityDown = 0.35;\n this.leftController = null;\n this.rightController = null;\n /**\n * Observable raised when a new mesh is selected based on meshSelectionPredicate\n */\n this.onNewMeshSelected = new BABYLON.Observable();\n /**\n * Observable raised when a new mesh is picked based on meshSelectionPredicate\n */\n this.onNewMeshPicked = new BABYLON.Observable();\n /**\n * Observable raised before camera teleportation\n */\n this.onBeforeCameraTeleport = new BABYLON.Observable();\n /**\n * Observable raised after camera teleportation\n */\n this.onAfterCameraTeleport = new BABYLON.Observable();\n /**\n * Observable raised when current selected mesh gets unselected\n */\n this.onSelectedMeshUnselected = new BABYLON.Observable();\n /**\n * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.\n */\n this.teleportationEnabled = true;\n this._teleportationInitialized = false;\n this._interactionsEnabled = false;\n this._interactionsRequested = false;\n this._displayGaze = true;\n this._displayLaserPointer = true;\n this._onResize = function () {\n _this.moveButtonToBottomRight();\n if (_this._fullscreenVRpresenting && _this._webVRready) {\n _this.exitVR();\n }\n };\n this._onFullscreenChange = function () {\n if (document.fullscreen !== undefined) {\n _this._fullscreenVRpresenting = document.fullscreen;\n }\n else if (document.mozFullScreen !== undefined) {\n _this._fullscreenVRpresenting = document.mozFullScreen;\n }\n else if (document.webkitIsFullScreen !== undefined) {\n _this._fullscreenVRpresenting = document.webkitIsFullScreen;\n }\n else if (document.msIsFullScreen !== undefined) {\n _this._fullscreenVRpresenting = document.msIsFullScreen;\n }\n else if (document.msFullscreenElement !== undefined) {\n _this._fullscreenVRpresenting = document.msFullscreenElement;\n }\n if (!_this._fullscreenVRpresenting && _this._canvas) {\n _this.exitVR();\n if (!_this._useCustomVRButton) {\n _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + \"px\";\n _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + \"px\";\n }\n }\n };\n this.beforeRender = function () {\n if (_this.leftController && _this.leftController._activePointer) {\n _this._castRayAndSelectObject(_this.leftController);\n }\n if (_this.rightController && _this.rightController._activePointer) {\n _this._castRayAndSelectObject(_this.rightController);\n }\n if (_this._noControllerIsActive) {\n _this._castRayAndSelectObject(_this._cameraGazer);\n }\n else {\n _this._cameraGazer._gazeTracker.isVisible = false;\n }\n };\n this._onNewGamepadConnected = function (gamepad) {\n if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {\n if (gamepad.leftStick) {\n gamepad.onleftstickchanged(function (stickValues) {\n if (_this._teleportationInitialized && _this.teleportationEnabled) {\n // Listening to classic/xbox gamepad only if no VR controller is active\n if ((!_this.leftController && !_this.rightController) ||\n ((_this.leftController && !_this.leftController._activePointer) &&\n (_this.rightController && !_this.rightController._activePointer))) {\n _this._checkTeleportWithRay(stickValues, _this._cameraGazer);\n _this._checkTeleportBackwards(stickValues, _this._cameraGazer);\n }\n }\n });\n }\n if (gamepad.rightStick) {\n gamepad.onrightstickchanged(function (stickValues) {\n if (_this._teleportationInitialized) {\n _this._checkRotate(stickValues, _this._cameraGazer);\n }\n });\n }\n if (gamepad.type === BABYLON.Gamepad.XBOX) {\n gamepad.onbuttondown(function (buttonPressed) {\n if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {\n _this._cameraGazer._selectionPointerDown();\n }\n });\n gamepad.onbuttonup(function (buttonPressed) {\n if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {\n _this._cameraGazer._selectionPointerUp();\n }\n });\n }\n }\n else {\n var webVRController = gamepad;\n var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);\n if (webVRController.hand === \"right\" || (_this.leftController && _this.leftController.webVRController != webVRController)) {\n _this.rightController = controller;\n }\n else {\n _this.leftController = controller;\n }\n _this._tryEnableInteractionOnController(controller);\n }\n };\n // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded\n this._tryEnableInteractionOnController = function (controller) {\n if (_this._interactionsRequested && !controller._interactionsEnabled) {\n _this._enableInteractionOnController(controller);\n }\n if (_this._teleportationRequested && !controller._teleportationEnabled) {\n _this._enableTeleportationOnController(controller);\n }\n };\n this._onNewGamepadDisconnected = function (gamepad) {\n if (gamepad instanceof BABYLON.WebVRController) {\n if (gamepad.hand === \"left\" && _this.leftController != null) {\n _this.leftController.dispose();\n _this.leftController = null;\n }\n if (gamepad.hand === \"right\" && _this.rightController != null) {\n _this.rightController.dispose();\n _this.rightController = null;\n }\n }\n };\n this._workingVector = BABYLON.Vector3.Zero();\n this._workingQuaternion = BABYLON.Quaternion.Identity();\n this._workingMatrix = BABYLON.Matrix.Identity();\n this._scene = scene;\n this._canvas = scene.getEngine().getRenderingCanvas();\n // Parse options\n if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {\n webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;\n }\n if (webVROptions.createDeviceOrientationCamera === undefined) {\n webVROptions.createDeviceOrientationCamera = true;\n }\n if (webVROptions.laserToggle === undefined) {\n webVROptions.laserToggle = true;\n }\n if (webVROptions.defaultHeight === undefined) {\n webVROptions.defaultHeight = 1.7;\n }\n if (webVROptions.useCustomVRButton) {\n this._useCustomVRButton = true;\n if (webVROptions.customVRButton) {\n this._btnVR = webVROptions.customVRButton;\n }\n }\n if (webVROptions.rayLength) {\n this._rayLength = webVROptions.rayLength;\n }\n this._defaultHeight = webVROptions.defaultHeight;\n if (webVROptions.positionScale) {\n this._rayLength *= webVROptions.positionScale;\n this._defaultHeight *= webVROptions.positionScale;\n }\n // Set position\n if (this._scene.activeCamera) {\n this._position = this._scene.activeCamera.position.clone();\n }\n else {\n this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);\n }\n // Set non-vr camera\n if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {\n this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera(\"deviceOrientationVRHelper\", this._position.clone(), scene);\n // Copy data from existing camera\n if (this._scene.activeCamera) {\n this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;\n this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;\n // Set rotation from previous camera\n if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {\n var targetCamera = this._scene.activeCamera;\n if (targetCamera.rotationQuaternion) {\n this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);\n }\n else {\n this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));\n }\n this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();\n }\n }\n this._scene.activeCamera = this._deviceOrientationCamera;\n if (this._canvas) {\n this._scene.activeCamera.attachControl(this._canvas);\n }\n }\n else {\n this._existingCamera = this._scene.activeCamera;\n }\n // Create VR cameras\n if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {\n this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera(\"VRDeviceOrientationVRHelper\", this._position, this._scene);\n }\n this._webVRCamera = new BABYLON.WebVRFreeCamera(\"WebVRHelper\", this._position, this._scene, webVROptions);\n this._webVRCamera.useStandingMatrix();\n this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);\n // Create default button\n if (!this._useCustomVRButton) {\n this._btnVR = document.createElement(\"BUTTON\");\n this._btnVR.className = \"babylonVRicon\";\n this._btnVR.id = \"babylonVRiconbtn\";\n this._btnVR.title = \"Click to switch to VR\";\n var css = \".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }\";\n css += \".babylonVRicon.vrdisplaypresenting { display: none; }\";\n // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)\n // css += \".babylonVRicon.vrdisplaysupported { }\";\n // css += \".babylonVRicon.vrdisplayready { }\";\n // css += \".babylonVRicon.vrdisplayrequesting { }\";\n var style = document.createElement('style');\n style.appendChild(document.createTextNode(css));\n document.getElementsByTagName('head')[0].appendChild(style);\n this.moveButtonToBottomRight();\n }\n // VR button click event\n if (this._btnVR) {\n this._btnVR.addEventListener(\"click\", function () {\n if (!_this.isInVRMode) {\n _this.enterVR();\n }\n else {\n _this.exitVR();\n }\n });\n }\n // Window events\n window.addEventListener(\"resize\", this._onResize);\n document.addEventListener(\"fullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"mozfullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"webkitfullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"msfullscreenchange\", this._onFullscreenChange, false);\n document.onmsfullscreenchange = this._onFullscreenChange;\n // Display vr button when headset is connected\n if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {\n this.displayVRButton();\n }\n else {\n this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {\n if (e.vrDisplay) {\n _this.displayVRButton();\n }\n });\n }\n // Exiting VR mode using 'ESC' key on desktop\n this._onKeyDown = function (event) {\n if (event.keyCode === 27 && _this.isInVRMode) {\n _this.exitVR();\n }\n };\n document.addEventListener(\"keydown\", this._onKeyDown);\n // Exiting VR mode double tapping the touch screen\n this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {\n if (_this.isInVRMode) {\n _this.exitVR();\n if (_this._fullscreenVRpresenting) {\n _this._scene.getEngine().switchFullscreen(true);\n }\n }\n }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);\n // Listen for WebVR display changes\n this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };\n this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };\n this._onVRRequestPresentStart = function () {\n _this._webVRrequesting = true;\n _this.updateButtonVisibility();\n };\n this._onVRRequestPresentComplete = function (success) {\n _this._webVRrequesting = false;\n _this.updateButtonVisibility();\n };\n scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);\n scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);\n scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);\n window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);\n scene.onDisposeObservable.add(function () {\n _this.dispose();\n });\n // Gamepad connection events\n this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });\n this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);\n this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);\n this.updateButtonVisibility();\n //create easing functions\n this._circleEase = new BABYLON.CircleEase();\n this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);\n if (this.webVROptions.floorMeshes) {\n this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });\n }\n }\n Object.defineProperty(VRExperienceHelper.prototype, \"onEnteringVR\", {\n /** Return this.onEnteringVRObservable\n * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly\n */\n get: function () {\n return this.onEnteringVRObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"onExitingVR\", {\n /** Return this.onExitingVRObservable\n * Note: This one is for backward compatibility. Please use onExitingVRObservable directly\n */\n get: function () {\n return this.onExitingVRObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"onControllerMeshLoaded\", {\n /** Return this.onControllerMeshLoadedObservable\n * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly\n */\n get: function () {\n return this.onControllerMeshLoadedObservable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"teleportationTarget\", {\n /**\n * The mesh used to display where the user is going to teleport.\n */\n get: function () {\n return this._teleportationTarget;\n },\n /**\n * Sets the mesh to be used to display where the user is going to teleport.\n */\n set: function (value) {\n if (value) {\n value.name = \"teleportationTarget\";\n this._isDefaultTeleportationTarget = false;\n this._teleportationTarget = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"gazeTrackerMesh\", {\n /**\n * The mesh used to display where the user is selecting,\n * when set bakeCurrentTransformIntoVertices will be called on the mesh.\n * See http://doc.babylonjs.com/resources/baking_transformations\n */\n get: function () {\n return this._cameraGazer._gazeTracker;\n },\n set: function (value) {\n if (value) {\n this._cameraGazer._gazeTracker = value;\n this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();\n this._cameraGazer._gazeTracker.isPickable = false;\n this._cameraGazer._gazeTracker.isVisible = false;\n this._cameraGazer._gazeTracker.name = \"gazeTracker\";\n if (this.leftController) {\n this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone(\"gazeTracker\");\n }\n if (this.rightController) {\n this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone(\"gazeTracker\");\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"displayGaze\", {\n /**\n * If the ray of the gaze should be displayed.\n */\n get: function () {\n return this._displayGaze;\n },\n /**\n * Sets if the ray of the gaze should be displayed.\n */\n set: function (value) {\n this._displayGaze = value;\n if (!value) {\n this._cameraGazer._gazeTracker.isVisible = false;\n if (this.leftController) {\n this.leftController._gazeTracker.isVisible = false;\n }\n if (this.rightController) {\n this.rightController._gazeTracker.isVisible = false;\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"displayLaserPointer\", {\n /**\n * If the ray of the LaserPointer should be displayed.\n */\n get: function () {\n return this._displayLaserPointer;\n },\n /**\n * Sets if the ray of the LaserPointer should be displayed.\n */\n set: function (value) {\n this._displayLaserPointer = value;\n if (!value) {\n if (this.rightController) {\n this.rightController._deactivatePointer();\n this.rightController._gazeTracker.isVisible = false;\n }\n if (this.leftController) {\n this.leftController._deactivatePointer();\n this.leftController._gazeTracker.isVisible = false;\n }\n }\n else {\n if (this.rightController) {\n this.rightController._activatePointer();\n }\n if (this.leftController) {\n this.leftController._activatePointer();\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"deviceOrientationCamera\", {\n /**\n * The deviceOrientationCamera used as the camera when not in VR.\n */\n get: function () {\n return this._deviceOrientationCamera;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"currentVRCamera\", {\n /**\n * Based on the current WebVR support, returns the current VR camera used.\n */\n get: function () {\n if (this._webVRready) {\n return this._webVRCamera;\n }\n else {\n return this._scene.activeCamera;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"webVRCamera\", {\n /**\n * The webVRCamera which is used when in VR.\n */\n get: function () {\n return this._webVRCamera;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"vrDeviceOrientationCamera\", {\n /**\n * The deviceOrientationCamera that is used as a fallback when vr device is not connected.\n */\n get: function () {\n return this._vrDeviceOrientationCamera;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VRExperienceHelper.prototype, \"_teleportationRequestInitiated\", {\n get: function () {\n var result = this._cameraGazer._teleportationRequestInitiated\n || (this.leftController !== null && this.leftController._teleportationRequestInitiated)\n || (this.rightController !== null && this.rightController._teleportationRequestInitiated);\n return result;\n },\n enumerable: true,\n configurable: true\n });\n // Raised when one of the controller has loaded successfully its associated default mesh\n VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {\n if (this.leftController && this.leftController.webVRController == webVRController) {\n if (webVRController.mesh) {\n this.leftController._setLaserPointerParent(webVRController.mesh);\n }\n }\n if (this.rightController && this.rightController.webVRController == webVRController) {\n if (webVRController.mesh) {\n this.rightController._setLaserPointerParent(webVRController.mesh);\n }\n }\n try {\n this.onControllerMeshLoadedObservable.notifyObservers(webVRController);\n }\n catch (err) {\n BABYLON.Tools.Warn(\"Error in your custom logic onControllerMeshLoaded: \" + err);\n }\n };\n Object.defineProperty(VRExperienceHelper.prototype, \"isInVRMode\", {\n /**\n * Gets a value indicating if we are currently in VR mode.\n */\n get: function () {\n return this._webVRpresenting || this._fullscreenVRpresenting;\n },\n enumerable: true,\n configurable: true\n });\n VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {\n var vrDisplay = this._scene.getEngine().getVRDevice();\n if (vrDisplay) {\n var wasPresenting = this._webVRpresenting;\n // A VR display is connected\n this._webVRpresenting = vrDisplay.isPresenting;\n if (wasPresenting && !this._webVRpresenting)\n this.exitVR();\n }\n else {\n BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');\n }\n this.updateButtonVisibility();\n };\n VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {\n this._webVRsupported = eventArgs.vrSupported;\n this._webVRready = !!eventArgs.vrDisplay;\n this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;\n this.updateButtonVisibility();\n };\n VRExperienceHelper.prototype.moveButtonToBottomRight = function () {\n if (this._canvas && !this._useCustomVRButton) {\n this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + \"px\";\n this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + \"px\";\n }\n };\n VRExperienceHelper.prototype.displayVRButton = function () {\n if (!this._useCustomVRButton && !this._btnVRDisplayed) {\n document.body.appendChild(this._btnVR);\n this._btnVRDisplayed = true;\n }\n };\n VRExperienceHelper.prototype.updateButtonVisibility = function () {\n if (!this._btnVR || this._useCustomVRButton) {\n return;\n }\n this._btnVR.className = \"babylonVRicon\";\n if (this.isInVRMode) {\n this._btnVR.className += \" vrdisplaypresenting\";\n }\n else {\n if (this._webVRready)\n this._btnVR.className += \" vrdisplayready\";\n if (this._webVRsupported)\n this._btnVR.className += \" vrdisplaysupported\";\n if (this._webVRrequesting)\n this._btnVR.className += \" vrdisplayrequesting\";\n }\n };\n /**\n * Attempt to enter VR. If a headset is connected and ready, will request present on that.\n * Otherwise, will use the fullscreen API.\n */\n VRExperienceHelper.prototype.enterVR = function () {\n if (this.onEnteringVRObservable) {\n try {\n this.onEnteringVRObservable.notifyObservers(this);\n }\n catch (err) {\n BABYLON.Tools.Warn(\"Error in your custom logic onEnteringVR: \" + err);\n }\n }\n if (this._scene.activeCamera) {\n this._position = this._scene.activeCamera.position.clone();\n // make sure that we return to the last active camera\n this._existingCamera = this._scene.activeCamera;\n }\n if (this._webVRrequesting)\n return;\n // If WebVR is supported and a headset is connected\n if (this._webVRready) {\n if (!this._webVRpresenting) {\n this._webVRCamera.position = this._position;\n this._scene.activeCamera = this._webVRCamera;\n }\n }\n else if (this._vrDeviceOrientationCamera) {\n this._vrDeviceOrientationCamera.position = this._position;\n if (this._scene.activeCamera) {\n this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;\n }\n this._scene.activeCamera = this._vrDeviceOrientationCamera;\n this._scene.getEngine().switchFullscreen(true);\n this.updateButtonVisibility();\n }\n if (this._scene.activeCamera && this._canvas) {\n this._scene.activeCamera.attachControl(this._canvas);\n }\n if (this._interactionsEnabled) {\n this._scene.registerBeforeRender(this.beforeRender);\n }\n };\n /**\n * Attempt to exit VR, or fullscreen.\n */\n VRExperienceHelper.prototype.exitVR = function () {\n if (this.onExitingVRObservable) {\n try {\n this.onExitingVRObservable.notifyObservers(this);\n }\n catch (err) {\n BABYLON.Tools.Warn(\"Error in your custom logic onExitingVR: \" + err);\n }\n }\n if (this._webVRpresenting) {\n this._scene.getEngine().disableVR();\n }\n if (this._scene.activeCamera) {\n this._position = this._scene.activeCamera.position.clone();\n }\n if (this._deviceOrientationCamera) {\n this._deviceOrientationCamera.position = this._position;\n this._scene.activeCamera = this._deviceOrientationCamera;\n if (this._canvas) {\n this._scene.activeCamera.attachControl(this._canvas);\n }\n }\n else if (this._existingCamera) {\n this._existingCamera.position = this._position;\n this._scene.activeCamera = this._existingCamera;\n }\n this.updateButtonVisibility();\n if (this._interactionsEnabled) {\n this._scene.unregisterBeforeRender(this.beforeRender);\n }\n // resize to update width and height when exiting vr exits fullscreen\n this._scene.getEngine().resize();\n };\n Object.defineProperty(VRExperienceHelper.prototype, \"position\", {\n /**\n * The position of the vr experience helper.\n */\n get: function () {\n return this._position;\n },\n /**\n * Sets the position of the vr experience helper.\n */\n set: function (value) {\n this._position = value;\n if (this._scene.activeCamera) {\n this._scene.activeCamera.position = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Enables controllers and user interactions such as selecting and object or clicking on an object.\n */\n VRExperienceHelper.prototype.enableInteractions = function () {\n var _this = this;\n if (!this._interactionsEnabled) {\n this._interactionsRequested = true;\n if (this.leftController) {\n this._enableInteractionOnController(this.leftController);\n }\n if (this.rightController) {\n this._enableInteractionOnController(this.rightController);\n }\n this.raySelectionPredicate = function (mesh) {\n return mesh.isVisible && mesh.isPickable;\n };\n this.meshSelectionPredicate = function (mesh) {\n return true;\n };\n this._raySelectionPredicate = function (mesh) {\n if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf(\"gazeTracker\") === -1\n && mesh.name.indexOf(\"teleportationTarget\") === -1\n && mesh.name.indexOf(\"torusTeleportation\") === -1)) {\n return _this.raySelectionPredicate(mesh);\n }\n return false;\n };\n this._interactionsEnabled = true;\n }\n };\n Object.defineProperty(VRExperienceHelper.prototype, \"_noControllerIsActive\", {\n get: function () {\n return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);\n },\n enumerable: true,\n configurable: true\n });\n VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {\n for (var i = 0; i < this._floorMeshesCollection.length; i++) {\n if (this._floorMeshesCollection[i].id === mesh.id) {\n return true;\n }\n }\n if (this._floorMeshName && mesh.name === this._floorMeshName) {\n return true;\n }\n return false;\n };\n /**\n * Adds a floor mesh to be used for teleportation.\n * @param floorMesh the mesh to be used for teleportation.\n */\n VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {\n if (!this._floorMeshesCollection) {\n return;\n }\n if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {\n return;\n }\n this._floorMeshesCollection.push(floorMesh);\n };\n /**\n * Removes a floor mesh from being used for teleportation.\n * @param floorMesh the mesh to be removed.\n */\n VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {\n if (!this._floorMeshesCollection) {\n return;\n }\n var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);\n if (meshIndex !== -1) {\n this._floorMeshesCollection.splice(meshIndex, 1);\n }\n };\n /**\n * Enables interactions and teleportation using the VR controllers and gaze.\n * @param vrTeleportationOptions options to modify teleportation behavior.\n */\n VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {\n if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }\n if (!this._teleportationInitialized) {\n this._teleportationRequested = true;\n this.enableInteractions();\n if (vrTeleportationOptions.floorMeshName) {\n this._floorMeshName = vrTeleportationOptions.floorMeshName;\n }\n if (vrTeleportationOptions.floorMeshes) {\n this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;\n }\n if (this.leftController != null) {\n this._enableTeleportationOnController(this.leftController);\n }\n if (this.rightController != null) {\n this._enableTeleportationOnController(this.rightController);\n }\n // Creates an image processing post process for the vignette not relying\n // on the main scene configuration for image processing to reduce setup and spaces \n // (gamma/linear) conflicts.\n var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();\n imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);\n imageProcessingConfiguration.vignetteEnabled = true;\n this._postProcessMove = new BABYLON.ImageProcessingPostProcess(\"postProcessMove\", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);\n this._webVRCamera.detachPostProcess(this._postProcessMove);\n this._teleportationInitialized = true;\n if (this._isDefaultTeleportationTarget) {\n this._createTeleportationCircles();\n this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);\n }\n }\n };\n VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {\n var _this = this;\n var controllerMesh = controller.webVRController.mesh;\n if (controllerMesh) {\n controller._interactionsEnabled = true;\n controller._activatePointer();\n if (this.webVROptions.laserToggle) {\n controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {\n // Enabling / disabling laserPointer \n if (_this._displayLaserPointer && stateObject.value === 1) {\n if (controller._activePointer) {\n controller._deactivatePointer();\n }\n else {\n controller._activatePointer();\n }\n if (_this.displayGaze) {\n controller._gazeTracker.isVisible = controller._activePointer;\n }\n }\n });\n }\n controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {\n var gazer = controller;\n if (_this._noControllerIsActive) {\n gazer = _this._cameraGazer;\n }\n if (!gazer._pointerDownOnMeshAsked) {\n if (stateObject.value > _this._padSensibilityUp) {\n gazer._selectionPointerDown();\n }\n }\n else if (stateObject.value < _this._padSensibilityDown) {\n gazer._selectionPointerUp();\n }\n });\n }\n };\n VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {\n // Dont teleport if another gaze already requested teleportation\n if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {\n return;\n }\n if (!gazer._teleportationRequestInitiated) {\n if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {\n gazer._activatePointer();\n gazer._teleportationRequestInitiated = true;\n }\n }\n else {\n // Listening to the proper controller values changes to confirm teleportation\n if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {\n if (this._teleportActive) {\n this._teleportCamera(this._haloCenter);\n }\n gazer._teleportationRequestInitiated = false;\n }\n }\n };\n VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {\n // Only rotate when user is not currently selecting a teleportation location\n if (gazer._teleportationRequestInitiated) {\n return;\n }\n if (!gazer._rotationLeftAsked) {\n if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {\n gazer._rotationLeftAsked = true;\n if (this._rotationAllowed) {\n this._rotateCamera(false);\n }\n }\n }\n else {\n if (stateObject.x > -this._padSensibilityDown) {\n gazer._rotationLeftAsked = false;\n }\n }\n if (!gazer._rotationRightAsked) {\n if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {\n gazer._rotationRightAsked = true;\n if (this._rotationAllowed) {\n this._rotateCamera(true);\n }\n }\n }\n else {\n if (stateObject.x < this._padSensibilityDown) {\n gazer._rotationRightAsked = false;\n }\n }\n };\n VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {\n // Only teleport backwards when user is not currently selecting a teleportation location\n if (gazer._teleportationRequestInitiated) {\n return;\n }\n // Teleport backwards\n if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {\n if (!gazer._teleportationBackRequestInitiated) {\n if (!this.currentVRCamera) {\n return;\n }\n // Get rotation and position of the current camera\n var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());\n var position = this.currentVRCamera.position;\n // If the camera has device position, use that instead\n if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {\n rotation = this.currentVRCamera.deviceRotationQuaternion;\n position = this.currentVRCamera.devicePosition;\n }\n // Get matrix with only the y rotation of the device rotation\n rotation.toEulerAnglesToRef(this._workingVector);\n this._workingVector.z = 0;\n this._workingVector.x = 0;\n BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);\n this._workingQuaternion.toRotationMatrix(this._workingMatrix);\n // Rotate backwards ray by device rotation to cast at the ground behind the user\n BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);\n // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff\n var ray = new BABYLON.Ray(position, this._workingVector);\n var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);\n if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {\n this._teleportCamera(hit.pickedPoint);\n }\n gazer._teleportationBackRequestInitiated = true;\n }\n }\n else {\n gazer._teleportationBackRequestInitiated = false;\n }\n };\n VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {\n var _this = this;\n var controllerMesh = controller.webVRController.mesh;\n if (controllerMesh) {\n if (!controller._interactionsEnabled) {\n this._enableInteractionOnController(controller);\n }\n controller._interactionsEnabled = true;\n controller._teleportationEnabled = true;\n if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {\n controller._dpadPressed = false;\n controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {\n controller._dpadPressed = stateObject.pressed;\n if (!controller._dpadPressed) {\n controller._rotationLeftAsked = false;\n controller._rotationRightAsked = false;\n controller._teleportationBackRequestInitiated = false;\n }\n });\n }\n controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {\n if (_this.teleportationEnabled) {\n _this._checkTeleportBackwards(stateObject, controller);\n _this._checkTeleportWithRay(stateObject, controller);\n }\n _this._checkRotate(stateObject, controller);\n });\n }\n };\n VRExperienceHelper.prototype._createTeleportationCircles = function () {\n this._teleportationTarget = BABYLON.Mesh.CreateGround(\"teleportationTarget\", 2, 2, 2, this._scene);\n this._teleportationTarget.isPickable = false;\n var length = 512;\n var dynamicTexture = new BABYLON.DynamicTexture(\"DynamicTexture\", length, this._scene, true);\n dynamicTexture.hasAlpha = true;\n var context = dynamicTexture.getContext();\n var centerX = length / 2;\n var centerY = length / 2;\n var radius = 200;\n context.beginPath();\n context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);\n context.fillStyle = this._teleportationFillColor;\n context.fill();\n context.lineWidth = 10;\n context.strokeStyle = this._teleportationBorderColor;\n context.stroke();\n context.closePath();\n dynamicTexture.update();\n var teleportationCircleMaterial = new BABYLON.StandardMaterial(\"TextPlaneMaterial\", this._scene);\n teleportationCircleMaterial.diffuseTexture = dynamicTexture;\n this._teleportationTarget.material = teleportationCircleMaterial;\n var torus = BABYLON.Mesh.CreateTorus(\"torusTeleportation\", 0.75, 0.1, 25, this._scene, false);\n torus.isPickable = false;\n torus.parent = this._teleportationTarget;\n var animationInnerCircle = new BABYLON.Animation(\"animationInnerCircle\", \"position.y\", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);\n var keys = [];\n keys.push({\n frame: 0,\n value: 0\n });\n keys.push({\n frame: 30,\n value: 0.4\n });\n keys.push({\n frame: 60,\n value: 0\n });\n animationInnerCircle.setKeys(keys);\n var easingFunction = new BABYLON.SineEase();\n easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);\n animationInnerCircle.setEasingFunction(easingFunction);\n torus.animations = [];\n torus.animations.push(animationInnerCircle);\n this._scene.beginAnimation(torus, 0, 60, true);\n this._hideTeleportationTarget();\n };\n VRExperienceHelper.prototype._displayTeleportationTarget = function () {\n this._teleportActive = true;\n if (this._teleportationInitialized) {\n this._teleportationTarget.isVisible = true;\n if (this._isDefaultTeleportationTarget) {\n this._teleportationTarget.getChildren()[0].isVisible = true;\n }\n }\n };\n VRExperienceHelper.prototype._hideTeleportationTarget = function () {\n this._teleportActive = false;\n if (this._teleportationInitialized) {\n this._teleportationTarget.isVisible = false;\n if (this._isDefaultTeleportationTarget) {\n this._teleportationTarget.getChildren()[0].isVisible = false;\n }\n }\n };\n VRExperienceHelper.prototype._rotateCamera = function (right) {\n var _this = this;\n if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {\n return;\n }\n if (right) {\n this._rotationAngle++;\n }\n else {\n this._rotationAngle--;\n }\n this.currentVRCamera.animations = [];\n var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));\n var animationRotation = new BABYLON.Animation(\"animationRotation\", \"rotationQuaternion\", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n var animationRotationKeys = [];\n animationRotationKeys.push({\n frame: 0,\n value: this.currentVRCamera.rotationQuaternion\n });\n animationRotationKeys.push({\n frame: 6,\n value: target\n });\n animationRotation.setKeys(animationRotationKeys);\n animationRotation.setEasingFunction(this._circleEase);\n this.currentVRCamera.animations.push(animationRotation);\n this._postProcessMove.animations = [];\n var animationPP = new BABYLON.Animation(\"animationPP\", \"vignetteWeight\", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n var vignetteWeightKeys = [];\n vignetteWeightKeys.push({\n frame: 0,\n value: 0\n });\n vignetteWeightKeys.push({\n frame: 3,\n value: 4\n });\n vignetteWeightKeys.push({\n frame: 6,\n value: 0\n });\n animationPP.setKeys(vignetteWeightKeys);\n animationPP.setEasingFunction(this._circleEase);\n this._postProcessMove.animations.push(animationPP);\n var animationPP2 = new BABYLON.Animation(\"animationPP2\", \"vignetteStretch\", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n var vignetteStretchKeys = [];\n vignetteStretchKeys.push({\n frame: 0,\n value: 0\n });\n vignetteStretchKeys.push({\n frame: 3,\n value: 10\n });\n vignetteStretchKeys.push({\n frame: 6,\n value: 0\n });\n animationPP2.setKeys(vignetteStretchKeys);\n animationPP2.setEasingFunction(this._circleEase);\n this._postProcessMove.animations.push(animationPP2);\n this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;\n this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;\n this._postProcessMove.samples = 4;\n this._webVRCamera.attachPostProcess(this._postProcessMove);\n this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {\n _this._webVRCamera.detachPostProcess(_this._postProcessMove);\n });\n this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);\n };\n VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {\n if (hit.pickedPoint) {\n if (gazer._teleportationRequestInitiated) {\n this._displayTeleportationTarget();\n this._haloCenter.copyFrom(hit.pickedPoint);\n this._teleportationTarget.position.copyFrom(hit.pickedPoint);\n }\n var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);\n if (pickNormal) {\n var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);\n var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);\n BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);\n }\n this._teleportationTarget.position.y += 0.1;\n }\n };\n VRExperienceHelper.prototype._teleportCamera = function (location) {\n var _this = this;\n if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {\n return;\n }\n // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the\n // offset of the headset from the anchor.\n if (this.webVRCamera.leftCamera) {\n this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);\n this._workingVector.subtractInPlace(this.webVRCamera.position);\n location.subtractToRef(this._workingVector, this._workingVector);\n }\n else {\n this._workingVector.copyFrom(location);\n }\n // Add height to account for user's height offset\n if (this.isInVRMode) {\n this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;\n }\n else {\n this._workingVector.y += this._defaultHeight;\n }\n this.onBeforeCameraTeleport.notifyObservers(this._workingVector);\n // Create animation from the camera's position to the new location\n this.currentVRCamera.animations = [];\n var animationCameraTeleportation = new BABYLON.Animation(\"animationCameraTeleportation\", \"position\", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n var animationCameraTeleportationKeys = [{\n frame: 0,\n value: this.currentVRCamera.position\n },\n {\n frame: 11,\n value: this._workingVector\n }\n ];\n animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);\n animationCameraTeleportation.setEasingFunction(this._circleEase);\n this.currentVRCamera.animations.push(animationCameraTeleportation);\n this._postProcessMove.animations = [];\n var animationPP = new BABYLON.Animation(\"animationPP\", \"vignetteWeight\", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n var vignetteWeightKeys = [];\n vignetteWeightKeys.push({\n frame: 0,\n value: 0\n });\n vignetteWeightKeys.push({\n frame: 5,\n value: 8\n });\n vignetteWeightKeys.push({\n frame: 11,\n value: 0\n });\n animationPP.setKeys(vignetteWeightKeys);\n this._postProcessMove.animations.push(animationPP);\n var animationPP2 = new BABYLON.Animation(\"animationPP2\", \"vignetteStretch\", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);\n var vignetteStretchKeys = [];\n vignetteStretchKeys.push({\n frame: 0,\n value: 0\n });\n vignetteStretchKeys.push({\n frame: 5,\n value: 10\n });\n vignetteStretchKeys.push({\n frame: 11,\n value: 0\n });\n animationPP2.setKeys(vignetteStretchKeys);\n this._postProcessMove.animations.push(animationPP2);\n this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;\n this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;\n this._webVRCamera.attachPostProcess(this._postProcessMove);\n this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {\n _this._webVRCamera.detachPostProcess(_this._postProcessMove);\n });\n this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {\n _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);\n });\n this._hideTeleportationTarget();\n };\n VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {\n if (normal) {\n var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));\n if (angle < Math.PI / 2) {\n normal.scaleInPlace(-1);\n }\n }\n return normal;\n };\n VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {\n if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {\n return;\n }\n var ray = gazer._getForwardRay(this._rayLength);\n var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);\n if (hit) {\n // Populate the contrllers mesh that can be used for drag/drop\n if (gazer._laserPointer) {\n hit.originMesh = gazer._laserPointer.parent;\n }\n this._scene.simulatePointerMove(hit, { pointerId: gazer._id });\n }\n gazer._currentHit = hit;\n // Moving the gazeTracker on the mesh face targetted\n if (hit && hit.pickedPoint) {\n if (this._displayGaze) {\n var multiplier = 1;\n gazer._gazeTracker.isVisible = true;\n if (gazer._isActionableMesh) {\n multiplier = 3;\n }\n gazer._gazeTracker.scaling.x = hit.distance * multiplier;\n gazer._gazeTracker.scaling.y = hit.distance * multiplier;\n gazer._gazeTracker.scaling.z = hit.distance * multiplier;\n var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);\n // To avoid z-fighting\n var deltaFighting = 0.002;\n if (pickNormal) {\n var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);\n var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);\n BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);\n }\n gazer._gazeTracker.position.copyFrom(hit.pickedPoint);\n if (gazer._gazeTracker.position.x < 0) {\n gazer._gazeTracker.position.x += deltaFighting;\n }\n else {\n gazer._gazeTracker.position.x -= deltaFighting;\n }\n if (gazer._gazeTracker.position.y < 0) {\n gazer._gazeTracker.position.y += deltaFighting;\n }\n else {\n gazer._gazeTracker.position.y -= deltaFighting;\n }\n if (gazer._gazeTracker.position.z < 0) {\n gazer._gazeTracker.position.z += deltaFighting;\n }\n else {\n gazer._gazeTracker.position.z -= deltaFighting;\n }\n }\n // Changing the size of the laser pointer based on the distance from the targetted point\n gazer._updatePointerDistance(hit.distance);\n }\n else {\n gazer._updatePointerDistance();\n gazer._gazeTracker.isVisible = false;\n }\n if (hit && hit.pickedMesh) {\n // The object selected is the floor, we're in a teleportation scenario\n if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {\n // Moving the teleportation area to this targetted point\n //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected\n if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {\n this._notifySelectedMeshUnselected(gazer._currentMeshSelected);\n }\n gazer._currentMeshSelected = null;\n if (gazer._teleportationRequestInitiated) {\n this._moveTeleportationSelectorTo(hit, gazer, ray);\n }\n return;\n }\n // If not, we're in a selection scenario\n //this._teleportationAllowed = false;\n if (hit.pickedMesh !== gazer._currentMeshSelected) {\n if (this.meshSelectionPredicate(hit.pickedMesh)) {\n this.onNewMeshPicked.notifyObservers(hit);\n gazer._currentMeshSelected = hit.pickedMesh;\n if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {\n this.changeGazeColor(new BABYLON.Color3(0, 0, 1));\n this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));\n gazer._isActionableMesh = true;\n }\n else {\n this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));\n this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));\n gazer._isActionableMesh = false;\n }\n try {\n this.onNewMeshSelected.notifyObservers(hit.pickedMesh);\n }\n catch (err) {\n BABYLON.Tools.Warn(\"Error in your custom logic onNewMeshSelected: \" + err);\n }\n }\n else {\n this._notifySelectedMeshUnselected(gazer._currentMeshSelected);\n gazer._currentMeshSelected = null;\n this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));\n this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));\n }\n }\n }\n else {\n this._notifySelectedMeshUnselected(gazer._currentMeshSelected);\n gazer._currentMeshSelected = null;\n //this._teleportationAllowed = false;\n this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));\n this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));\n }\n };\n VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {\n if (mesh) {\n this.onSelectedMeshUnselected.notifyObservers(mesh);\n }\n };\n /**\n * Sets the color of the laser ray from the vr controllers.\n * @param color new color for the ray.\n */\n VRExperienceHelper.prototype.changeLaserColor = function (color) {\n if (this.leftController) {\n this.leftController._setLaserPointerColor(color);\n }\n if (this.rightController) {\n this.rightController._setLaserPointerColor(color);\n }\n };\n /**\n * Sets the color of the ray from the vr headsets gaze.\n * @param color new color for the ray.\n */\n VRExperienceHelper.prototype.changeGazeColor = function (color) {\n if (!this._cameraGazer._gazeTracker.material) {\n return;\n }\n this._cameraGazer._gazeTracker.material.emissiveColor = color;\n if (this.leftController) {\n this.leftController._gazeTracker.material.emissiveColor = color;\n }\n if (this.rightController) {\n this.rightController._gazeTracker.material.emissiveColor = color;\n }\n };\n /**\n * Exits VR and disposes of the vr experience helper\n */\n VRExperienceHelper.prototype.dispose = function () {\n if (this.isInVRMode) {\n this.exitVR();\n }\n if (this._postProcessMove) {\n this._postProcessMove.dispose();\n }\n if (this._webVRCamera) {\n this._webVRCamera.dispose();\n }\n if (this._vrDeviceOrientationCamera) {\n this._vrDeviceOrientationCamera.dispose();\n }\n if (!this._useCustomVRButton && this._btnVR.parentNode) {\n document.body.removeChild(this._btnVR);\n }\n if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {\n this._deviceOrientationCamera.dispose();\n }\n if (this._cameraGazer) {\n this._cameraGazer.dispose();\n }\n if (this.leftController) {\n this.leftController.dispose();\n }\n if (this.rightController) {\n this.rightController.dispose();\n }\n if (this._teleportationTarget) {\n this._teleportationTarget.dispose();\n }\n this._floorMeshesCollection = [];\n document.removeEventListener(\"keydown\", this._onKeyDown);\n window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);\n window.removeEventListener(\"resize\", this._onResize);\n document.removeEventListener(\"fullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"mozfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"webkitfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"msfullscreenchange\", this._onFullscreenChange);\n document.onmsfullscreenchange = null;\n this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);\n this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);\n this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);\n window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);\n this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);\n this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);\n this._scene.unregisterBeforeRender(this.beforeRender);\n };\n /**\n * Gets the name of the VRExperienceHelper class\n * @returns \"VRExperienceHelper\"\n */\n VRExperienceHelper.prototype.getClassName = function () {\n return \"VRExperienceHelper\";\n };\n return VRExperienceHelper;\n }());\n BABYLON.VRExperienceHelper = VRExperienceHelper;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.vrExperienceHelper.js.map\n\n// Mainly based on these 2 articles : \n// Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx\n// & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/ \nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the potential axis of a Joystick\n */\n var JoystickAxis;\n (function (JoystickAxis) {\n /** X axis */\n JoystickAxis[JoystickAxis[\"X\"] = 0] = \"X\";\n /** Y axis */\n JoystickAxis[JoystickAxis[\"Y\"] = 1] = \"Y\";\n /** Z axis */\n JoystickAxis[JoystickAxis[\"Z\"] = 2] = \"Z\";\n })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));\n /**\n * Class used to define virtual joystick (used in touch mode)\n */\n var VirtualJoystick = /** @class */ (function () {\n /**\n * Creates a new virtual joystick\n * @param leftJoystick defines that the joystick is for left hand (false by default)\n */\n function VirtualJoystick(leftJoystick) {\n var _this = this;\n if (leftJoystick) {\n this._leftJoystick = true;\n }\n else {\n this._leftJoystick = false;\n }\n VirtualJoystick._globalJoystickIndex++;\n // By default left & right arrow keys are moving the X\n // and up & down keys are moving the Y\n this._axisTargetedByLeftAndRight = JoystickAxis.X;\n this._axisTargetedByUpAndDown = JoystickAxis.Y;\n this.reverseLeftRight = false;\n this.reverseUpDown = false;\n // collections of pointers\n this._touches = new BABYLON.StringDictionary();\n this.deltaPosition = BABYLON.Vector3.Zero();\n this._joystickSensibility = 25;\n this._inversedSensibility = 1 / (this._joystickSensibility / 1000);\n this._onResize = function (evt) {\n VirtualJoystick.vjCanvasWidth = window.innerWidth;\n VirtualJoystick.vjCanvasHeight = window.innerHeight;\n if (VirtualJoystick.vjCanvas) {\n VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;\n VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;\n }\n VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;\n };\n // injecting a canvas element on top of the canvas 3D game\n if (!VirtualJoystick.vjCanvas) {\n window.addEventListener(\"resize\", this._onResize, false);\n VirtualJoystick.vjCanvas = document.createElement(\"canvas\");\n VirtualJoystick.vjCanvasWidth = window.innerWidth;\n VirtualJoystick.vjCanvasHeight = window.innerHeight;\n VirtualJoystick.vjCanvas.width = window.innerWidth;\n VirtualJoystick.vjCanvas.height = window.innerHeight;\n VirtualJoystick.vjCanvas.style.width = \"100%\";\n VirtualJoystick.vjCanvas.style.height = \"100%\";\n VirtualJoystick.vjCanvas.style.position = \"absolute\";\n VirtualJoystick.vjCanvas.style.backgroundColor = \"transparent\";\n VirtualJoystick.vjCanvas.style.top = \"0px\";\n VirtualJoystick.vjCanvas.style.left = \"0px\";\n VirtualJoystick.vjCanvas.style.zIndex = \"5\";\n VirtualJoystick.vjCanvas.style.msTouchAction = \"none\";\n // Support for jQuery PEP polyfill\n VirtualJoystick.vjCanvas.setAttribute(\"touch-action\", \"none\");\n var context = VirtualJoystick.vjCanvas.getContext('2d');\n if (!context) {\n throw new Error(\"Unable to create canvas for virtual joystick\");\n }\n VirtualJoystick.vjCanvasContext = context;\n VirtualJoystick.vjCanvasContext.strokeStyle = \"#ffffff\";\n VirtualJoystick.vjCanvasContext.lineWidth = 2;\n document.body.appendChild(VirtualJoystick.vjCanvas);\n }\n VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;\n this.pressed = false;\n // default joystick color\n this._joystickColor = \"cyan\";\n this._joystickPointerID = -1;\n // current joystick position\n this._joystickPointerPos = new BABYLON.Vector2(0, 0);\n this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);\n // origin joystick position\n this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);\n this._deltaJoystickVector = new BABYLON.Vector2(0, 0);\n this._onPointerDownHandlerRef = function (evt) {\n _this._onPointerDown(evt);\n };\n this._onPointerMoveHandlerRef = function (evt) {\n _this._onPointerMove(evt);\n };\n this._onPointerUpHandlerRef = function (evt) {\n _this._onPointerUp(evt);\n };\n VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);\n VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);\n VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);\n VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);\n VirtualJoystick.vjCanvas.addEventListener(\"contextmenu\", function (evt) {\n evt.preventDefault(); // Disables system menu\n }, false);\n requestAnimationFrame(function () { _this._drawVirtualJoystick(); });\n }\n /**\n * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)\n * @param newJoystickSensibility defines the new sensibility\n */\n VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {\n this._joystickSensibility = newJoystickSensibility;\n this._inversedSensibility = 1 / (this._joystickSensibility / 1000);\n };\n VirtualJoystick.prototype._onPointerDown = function (e) {\n var positionOnScreenCondition;\n e.preventDefault();\n if (this._leftJoystick === true) {\n positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);\n }\n else {\n positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);\n }\n if (positionOnScreenCondition && this._joystickPointerID < 0) {\n // First contact will be dedicated to the virtual joystick\n this._joystickPointerID = e.pointerId;\n this._joystickPointerStartPos.x = e.clientX;\n this._joystickPointerStartPos.y = e.clientY;\n this._joystickPointerPos = this._joystickPointerStartPos.clone();\n this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();\n this._deltaJoystickVector.x = 0;\n this._deltaJoystickVector.y = 0;\n this.pressed = true;\n this._touches.add(e.pointerId.toString(), e);\n }\n else {\n // You can only trigger the action buttons with a joystick declared\n if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {\n this._action();\n this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });\n }\n }\n };\n VirtualJoystick.prototype._onPointerMove = function (e) {\n // If the current pointer is the one associated to the joystick (first touch contact)\n if (this._joystickPointerID == e.pointerId) {\n this._joystickPointerPos.x = e.clientX;\n this._joystickPointerPos.y = e.clientY;\n this._deltaJoystickVector = this._joystickPointerPos.clone();\n this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);\n var directionLeftRight = this.reverseLeftRight ? -1 : 1;\n var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;\n switch (this._axisTargetedByLeftAndRight) {\n case JoystickAxis.X:\n this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));\n break;\n case JoystickAxis.Y:\n this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));\n break;\n case JoystickAxis.Z:\n this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));\n break;\n }\n var directionUpDown = this.reverseUpDown ? 1 : -1;\n var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;\n switch (this._axisTargetedByUpAndDown) {\n case JoystickAxis.X:\n this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));\n break;\n case JoystickAxis.Y:\n this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));\n break;\n case JoystickAxis.Z:\n this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));\n break;\n }\n }\n else {\n var data = this._touches.get(e.pointerId.toString());\n if (data) {\n data.x = e.clientX;\n data.y = e.clientY;\n }\n }\n };\n VirtualJoystick.prototype._onPointerUp = function (e) {\n if (this._joystickPointerID == e.pointerId) {\n VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);\n VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);\n this._joystickPointerID = -1;\n this.pressed = false;\n }\n else {\n var touch = this._touches.get(e.pointerId.toString());\n if (touch) {\n VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);\n }\n }\n this._deltaJoystickVector.x = 0;\n this._deltaJoystickVector.y = 0;\n this._touches.remove(e.pointerId.toString());\n };\n /**\n * Change the color of the virtual joystick\n * @param newColor a string that must be a CSS color value (like \"red\") or the hexa value (like \"#FF0000\")\n */\n VirtualJoystick.prototype.setJoystickColor = function (newColor) {\n this._joystickColor = newColor;\n };\n /**\n * Defines a callback to call when the joystick is touched\n * @param action defines the callback\n */\n VirtualJoystick.prototype.setActionOnTouch = function (action) {\n this._action = action;\n };\n /**\n * Defines which axis you'd like to control for left & right\n * @param axis defines the axis to use\n */\n VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {\n switch (axis) {\n case JoystickAxis.X:\n case JoystickAxis.Y:\n case JoystickAxis.Z:\n this._axisTargetedByLeftAndRight = axis;\n break;\n default:\n this._axisTargetedByLeftAndRight = JoystickAxis.X;\n break;\n }\n };\n /**\n * Defines which axis you'd like to control for up & down\n * @param axis defines the axis to use\n */\n VirtualJoystick.prototype.setAxisForUpDown = function (axis) {\n switch (axis) {\n case JoystickAxis.X:\n case JoystickAxis.Y:\n case JoystickAxis.Z:\n this._axisTargetedByUpAndDown = axis;\n break;\n default:\n this._axisTargetedByUpAndDown = JoystickAxis.Y;\n break;\n }\n };\n VirtualJoystick.prototype._drawVirtualJoystick = function () {\n var _this = this;\n if (this.pressed) {\n this._touches.forEach(function (key, touch) {\n if (touch.pointerId === _this._joystickPointerID) {\n VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);\n VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);\n VirtualJoystick.vjCanvasContext.beginPath();\n VirtualJoystick.vjCanvasContext.lineWidth = 6;\n VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;\n VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);\n VirtualJoystick.vjCanvasContext.stroke();\n VirtualJoystick.vjCanvasContext.closePath();\n VirtualJoystick.vjCanvasContext.beginPath();\n VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;\n VirtualJoystick.vjCanvasContext.lineWidth = 2;\n VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);\n VirtualJoystick.vjCanvasContext.stroke();\n VirtualJoystick.vjCanvasContext.closePath();\n VirtualJoystick.vjCanvasContext.beginPath();\n VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;\n VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);\n VirtualJoystick.vjCanvasContext.stroke();\n VirtualJoystick.vjCanvasContext.closePath();\n _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();\n }\n else {\n VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);\n VirtualJoystick.vjCanvasContext.beginPath();\n VirtualJoystick.vjCanvasContext.fillStyle = \"white\";\n VirtualJoystick.vjCanvasContext.beginPath();\n VirtualJoystick.vjCanvasContext.strokeStyle = \"red\";\n VirtualJoystick.vjCanvasContext.lineWidth = 6;\n VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);\n VirtualJoystick.vjCanvasContext.stroke();\n VirtualJoystick.vjCanvasContext.closePath();\n touch.prevX = touch.x;\n touch.prevY = touch.y;\n }\n ;\n });\n }\n requestAnimationFrame(function () { _this._drawVirtualJoystick(); });\n };\n /**\n * Release internal HTML canvas\n */\n VirtualJoystick.prototype.releaseCanvas = function () {\n if (VirtualJoystick.vjCanvas) {\n VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);\n VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);\n VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);\n VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);\n window.removeEventListener(\"resize\", this._onResize);\n document.body.removeChild(VirtualJoystick.vjCanvas);\n VirtualJoystick.vjCanvas = null;\n }\n };\n // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas\n VirtualJoystick._globalJoystickIndex = 0;\n return VirtualJoystick;\n }());\n BABYLON.VirtualJoystick = VirtualJoystick;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.virtualJoystick.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Node.AddNodeConstructor(\"VirtualJoysticksCamera\", function (name, scene) {\n return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };\n });\n // We're mainly based on the logic defined into the FreeCamera code\n var VirtualJoysticksCamera = /** @class */ (function (_super) {\n __extends(VirtualJoysticksCamera, _super);\n function VirtualJoysticksCamera(name, position, scene) {\n var _this = _super.call(this, name, position, scene) || this;\n _this.inputs.addVirtualJoystick();\n return _this;\n }\n VirtualJoysticksCamera.prototype.getClassName = function () {\n return \"VirtualJoysticksCamera\";\n };\n return VirtualJoysticksCamera;\n }(BABYLON.FreeCamera));\n BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.virtualJoysticksCamera.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var FreeCameraVirtualJoystickInput = /** @class */ (function () {\n function FreeCameraVirtualJoystickInput() {\n }\n FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {\n return this._leftjoystick;\n };\n FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {\n return this._rightjoystick;\n };\n FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {\n if (this._leftjoystick) {\n var camera = this.camera;\n var speed = camera._computeLocalCameraSpeed() * 50;\n var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);\n var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);\n camera.cameraDirection = camera.cameraDirection.add(deltaTransform);\n camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);\n if (!this._leftjoystick.pressed) {\n this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);\n }\n if (!this._rightjoystick.pressed) {\n this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);\n }\n }\n };\n FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {\n this._leftjoystick = new BABYLON.VirtualJoystick(true);\n this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);\n this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);\n this._leftjoystick.setJoystickSensibility(0.15);\n this._rightjoystick = new BABYLON.VirtualJoystick(false);\n this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);\n this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);\n this._rightjoystick.reverseUpDown = true;\n this._rightjoystick.setJoystickSensibility(0.05);\n this._rightjoystick.setJoystickColor(\"yellow\");\n };\n FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {\n this._leftjoystick.releaseCanvas();\n this._rightjoystick.releaseCanvas();\n };\n FreeCameraVirtualJoystickInput.prototype.getClassName = function () {\n return \"FreeCameraVirtualJoystickInput\";\n };\n FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {\n return \"virtualJoystick\";\n };\n return FreeCameraVirtualJoystickInput;\n }());\n BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;\n BABYLON.CameraInputTypes[\"FreeCameraVirtualJoystickInput\"] = FreeCameraVirtualJoystickInput;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var SimplificationSettings = /** @class */ (function () {\n function SimplificationSettings(quality, distance, optimizeMesh) {\n this.quality = quality;\n this.distance = distance;\n this.optimizeMesh = optimizeMesh;\n }\n return SimplificationSettings;\n }());\n BABYLON.SimplificationSettings = SimplificationSettings;\n var SimplificationQueue = /** @class */ (function () {\n function SimplificationQueue() {\n this.running = false;\n this._simplificationArray = [];\n }\n SimplificationQueue.prototype.addTask = function (task) {\n this._simplificationArray.push(task);\n };\n SimplificationQueue.prototype.executeNext = function () {\n var task = this._simplificationArray.pop();\n if (task) {\n this.running = true;\n this.runSimplification(task);\n }\n else {\n this.running = false;\n }\n };\n SimplificationQueue.prototype.runSimplification = function (task) {\n var _this = this;\n if (task.parallelProcessing) {\n //parallel simplifier\n task.settings.forEach(function (setting) {\n var simplifier = _this.getSimplifier(task);\n simplifier.simplify(setting, function (newMesh) {\n task.mesh.addLODLevel(setting.distance, newMesh);\n newMesh.isVisible = true;\n //check if it is the last\n if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {\n //all done, run the success callback.\n task.successCallback();\n }\n _this.executeNext();\n });\n });\n }\n else {\n //single simplifier.\n var simplifier = this.getSimplifier(task);\n var runDecimation = function (setting, callback) {\n simplifier.simplify(setting, function (newMesh) {\n task.mesh.addLODLevel(setting.distance, newMesh);\n newMesh.isVisible = true;\n //run the next quality level\n callback();\n });\n };\n BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {\n runDecimation(task.settings[loop.index], function () {\n loop.executeNext();\n });\n }, function () {\n //execution ended, run the success callback.\n if (task.successCallback) {\n task.successCallback();\n }\n _this.executeNext();\n });\n }\n };\n SimplificationQueue.prototype.getSimplifier = function (task) {\n switch (task.simplificationType) {\n case SimplificationType.QUADRATIC:\n default:\n return new QuadraticErrorSimplification(task.mesh);\n }\n };\n return SimplificationQueue;\n }());\n BABYLON.SimplificationQueue = SimplificationQueue;\n /**\n * The implemented types of simplification\n * At the moment only Quadratic Error Decimation is implemented\n */\n var SimplificationType;\n (function (SimplificationType) {\n /** Quadratic error decimation */\n SimplificationType[SimplificationType[\"QUADRATIC\"] = 0] = \"QUADRATIC\";\n })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));\n var DecimationTriangle = /** @class */ (function () {\n function DecimationTriangle(vertices) {\n this.vertices = vertices;\n this.error = new Array(4);\n this.deleted = false;\n this.isDirty = false;\n this.deletePending = false;\n this.borderFactor = 0;\n }\n return DecimationTriangle;\n }());\n BABYLON.DecimationTriangle = DecimationTriangle;\n var DecimationVertex = /** @class */ (function () {\n function DecimationVertex(position, id) {\n this.position = position;\n this.id = id;\n this.isBorder = true;\n this.q = new QuadraticMatrix();\n this.triangleCount = 0;\n this.triangleStart = 0;\n this.originalOffsets = [];\n }\n DecimationVertex.prototype.updatePosition = function (newPosition) {\n this.position.copyFrom(newPosition);\n };\n return DecimationVertex;\n }());\n BABYLON.DecimationVertex = DecimationVertex;\n var QuadraticMatrix = /** @class */ (function () {\n function QuadraticMatrix(data) {\n this.data = new Array(10);\n for (var i = 0; i < 10; ++i) {\n if (data && data[i]) {\n this.data[i] = data[i];\n }\n else {\n this.data[i] = 0;\n }\n }\n }\n QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {\n var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +\n this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -\n this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];\n return det;\n };\n QuadraticMatrix.prototype.addInPlace = function (matrix) {\n for (var i = 0; i < 10; ++i) {\n this.data[i] += matrix.data[i];\n }\n };\n QuadraticMatrix.prototype.addArrayInPlace = function (data) {\n for (var i = 0; i < 10; ++i) {\n this.data[i] += data[i];\n }\n };\n QuadraticMatrix.prototype.add = function (matrix) {\n var m = new QuadraticMatrix();\n for (var i = 0; i < 10; ++i) {\n m.data[i] = this.data[i] + matrix.data[i];\n }\n return m;\n };\n QuadraticMatrix.FromData = function (a, b, c, d) {\n return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));\n };\n //returning an array to avoid garbage collection\n QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {\n return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];\n };\n return QuadraticMatrix;\n }());\n BABYLON.QuadraticMatrix = QuadraticMatrix;\n var Reference = /** @class */ (function () {\n function Reference(vertexId, triangleId) {\n this.vertexId = vertexId;\n this.triangleId = triangleId;\n }\n return Reference;\n }());\n BABYLON.Reference = Reference;\n /**\n * An implementation of the Quadratic Error simplification algorithm.\n * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf\n * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS\n * @author RaananW\n */\n var QuadraticErrorSimplification = /** @class */ (function () {\n function QuadraticErrorSimplification(_mesh) {\n this._mesh = _mesh;\n this.syncIterations = 5000;\n this.aggressiveness = 7;\n this.decimationIterations = 100;\n this.boundingBoxEpsilon = BABYLON.Epsilon;\n }\n QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {\n var _this = this;\n this.initDecimatedMesh();\n //iterating through the submeshes array, one after the other.\n BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {\n _this.initWithMesh(loop.index, function () {\n _this.runDecimation(settings, loop.index, function () {\n loop.executeNext();\n });\n }, settings.optimizeMesh);\n }, function () {\n setTimeout(function () {\n successCallback(_this._reconstructedMesh);\n }, 0);\n });\n };\n QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {\n var _this = this;\n var targetCount = ~~(this.triangles.length * settings.quality);\n var deletedTriangles = 0;\n var triangleCount = this.triangles.length;\n var iterationFunction = function (iteration, callback) {\n setTimeout(function () {\n if (iteration % 5 === 0) {\n _this.updateMesh(iteration === 0);\n }\n for (var i = 0; i < _this.triangles.length; ++i) {\n _this.triangles[i].isDirty = false;\n }\n var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);\n var trianglesIterator = function (i) {\n var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);\n var t = _this.triangles[tIdx];\n if (!t)\n return;\n if (t.error[3] > threshold || t.deleted || t.isDirty) {\n return;\n }\n for (var j = 0; j < 3; ++j) {\n if (t.error[j] < threshold) {\n var deleted0 = [];\n var deleted1 = [];\n var v0 = t.vertices[j];\n var v1 = t.vertices[(j + 1) % 3];\n if (v0.isBorder || v1.isBorder)\n continue;\n var p = BABYLON.Vector3.Zero();\n var n = BABYLON.Vector3.Zero();\n var uv = BABYLON.Vector2.Zero();\n var color = new BABYLON.Color4(0, 0, 0, 1);\n _this.calculateError(v0, v1, p, n, uv, color);\n var delTr = new Array();\n if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))\n continue;\n if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))\n continue;\n if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)\n continue;\n var uniqueArray = new Array();\n delTr.forEach(function (deletedT) {\n if (uniqueArray.indexOf(deletedT) === -1) {\n deletedT.deletePending = true;\n uniqueArray.push(deletedT);\n }\n });\n if (uniqueArray.length % 2 !== 0) {\n continue;\n }\n v0.q = v1.q.add(v0.q);\n v0.updatePosition(p);\n var tStart = _this.references.length;\n deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);\n deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);\n var tCount = _this.references.length - tStart;\n if (tCount <= v0.triangleCount) {\n if (tCount) {\n for (var c = 0; c < tCount; c++) {\n _this.references[v0.triangleStart + c] = _this.references[tStart + c];\n }\n }\n }\n else {\n v0.triangleStart = tStart;\n }\n v0.triangleCount = tCount;\n break;\n }\n }\n };\n BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });\n }, 0);\n };\n BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {\n if (triangleCount - deletedTriangles <= targetCount)\n loop.breakLoop();\n else {\n iterationFunction(loop.index, function () {\n loop.executeNext();\n });\n }\n }, function () {\n setTimeout(function () {\n //reconstruct this part of the mesh\n _this.reconstructMesh(submeshIndex);\n successCallback();\n }, 0);\n });\n };\n QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {\n var _this = this;\n this.vertices = [];\n this.triangles = [];\n var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var indices = this._mesh.getIndices();\n var submesh = this._mesh.subMeshes[submeshIndex];\n var findInVertices = function (positionToSearch) {\n if (optimizeMesh) {\n for (var ii = 0; ii < _this.vertices.length; ++ii) {\n if (_this.vertices[ii].position.equals(positionToSearch)) {\n return _this.vertices[ii];\n }\n }\n }\n return null;\n };\n var vertexReferences = [];\n var vertexInit = function (i) {\n if (!positionData) {\n return;\n }\n var offset = i + submesh.verticesStart;\n var position = BABYLON.Vector3.FromArray(positionData, offset * 3);\n var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);\n vertex.originalOffsets.push(offset);\n if (vertex.id === _this.vertices.length) {\n _this.vertices.push(vertex);\n }\n vertexReferences.push(vertex.id);\n };\n //var totalVertices = mesh.getTotalVertices();\n var totalVertices = submesh.verticesCount;\n BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {\n var indicesInit = function (i) {\n if (!indices) {\n return;\n }\n var offset = (submesh.indexStart / 3) + i;\n var pos = (offset * 3);\n var i0 = indices[pos + 0];\n var i1 = indices[pos + 1];\n var i2 = indices[pos + 2];\n var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];\n var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];\n var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];\n var triangle = new DecimationTriangle([v0, v1, v2]);\n triangle.originalOffset = pos;\n _this.triangles.push(triangle);\n };\n BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {\n _this.init(callback);\n });\n });\n };\n QuadraticErrorSimplification.prototype.init = function (callback) {\n var _this = this;\n var triangleInit1 = function (i) {\n var t = _this.triangles[i];\n t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();\n for (var j = 0; j < 3; j++) {\n t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));\n }\n };\n BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {\n var triangleInit2 = function (i) {\n var t = _this.triangles[i];\n for (var j = 0; j < 3; ++j) {\n t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);\n }\n t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);\n };\n BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {\n callback();\n });\n });\n };\n QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {\n var newTriangles = [];\n var i;\n for (i = 0; i < this.vertices.length; ++i) {\n this.vertices[i].triangleCount = 0;\n }\n var t;\n var j;\n for (i = 0; i < this.triangles.length; ++i) {\n if (!this.triangles[i].deleted) {\n t = this.triangles[i];\n for (j = 0; j < 3; ++j) {\n t.vertices[j].triangleCount = 1;\n }\n newTriangles.push(t);\n }\n }\n var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);\n var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);\n var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);\n var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);\n var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);\n var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);\n var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);\n var vertexCount = 0;\n for (i = 0; i < this.vertices.length; ++i) {\n var vertex = this.vertices[i];\n vertex.id = vertexCount;\n if (vertex.triangleCount) {\n vertex.originalOffsets.forEach(function (originalOffset) {\n if (!normalData) {\n return;\n }\n newPositionData.push(vertex.position.x);\n newPositionData.push(vertex.position.y);\n newPositionData.push(vertex.position.z);\n newNormalData.push(normalData[originalOffset * 3]);\n newNormalData.push(normalData[(originalOffset * 3) + 1]);\n newNormalData.push(normalData[(originalOffset * 3) + 2]);\n if (uvs && uvs.length) {\n newUVsData.push(uvs[(originalOffset * 2)]);\n newUVsData.push(uvs[(originalOffset * 2) + 1]);\n }\n else if (colorsData && colorsData.length) {\n newColorsData.push(colorsData[(originalOffset * 4)]);\n newColorsData.push(colorsData[(originalOffset * 4) + 1]);\n newColorsData.push(colorsData[(originalOffset * 4) + 2]);\n newColorsData.push(colorsData[(originalOffset * 4) + 3]);\n }\n ++vertexCount;\n });\n }\n }\n var startingIndex = this._reconstructedMesh.getTotalIndices();\n var startingVertex = this._reconstructedMesh.getTotalVertices();\n var submeshesArray = this._reconstructedMesh.subMeshes;\n this._reconstructedMesh.subMeshes = [];\n var newIndicesArray = this._reconstructedMesh.getIndices(); //[];\n var originalIndices = this._mesh.getIndices();\n for (i = 0; i < newTriangles.length; ++i) {\n t = newTriangles[i]; //now get the new referencing point for each vertex\n [0, 1, 2].forEach(function (idx) {\n var id = originalIndices[t.originalOffset + idx];\n var offset = t.vertices[idx].originalOffsets.indexOf(id);\n if (offset < 0)\n offset = 0;\n newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);\n });\n }\n //overwriting the old vertex buffers and indices.\n this._reconstructedMesh.setIndices(newIndicesArray);\n this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);\n this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);\n if (newUVsData.length > 0)\n this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);\n if (newColorsData.length > 0)\n this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);\n //create submesh\n var originalSubmesh = this._mesh.subMeshes[submeshIndex];\n if (submeshIndex > 0) {\n this._reconstructedMesh.subMeshes = [];\n submeshesArray.forEach(function (submesh) {\n BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());\n });\n BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);\n }\n };\n QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {\n this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + \"Decimated\", this._mesh.getScene());\n this._reconstructedMesh.material = this._mesh.material;\n this._reconstructedMesh.parent = this._mesh.parent;\n this._reconstructedMesh.isVisible = false;\n this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;\n };\n QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {\n for (var i = 0; i < vertex1.triangleCount; ++i) {\n var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];\n if (t.deleted)\n continue;\n var s = this.references[vertex1.triangleStart + i].vertexId;\n var v1 = t.vertices[(s + 1) % 3];\n var v2 = t.vertices[(s + 2) % 3];\n if ((v1 === vertex2 || v2 === vertex2)) {\n deletedArray[i] = true;\n delTr.push(t);\n continue;\n }\n var d1 = v1.position.subtract(point);\n d1 = d1.normalize();\n var d2 = v2.position.subtract(point);\n d2 = d2.normalize();\n if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)\n return true;\n var normal = BABYLON.Vector3.Cross(d1, d2).normalize();\n deletedArray[i] = false;\n if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)\n return true;\n }\n return false;\n };\n QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {\n var newDeleted = deletedTriangles;\n for (var i = 0; i < vertex.triangleCount; ++i) {\n var ref = this.references[vertex.triangleStart + i];\n var t = this.triangles[ref.triangleId];\n if (t.deleted)\n continue;\n if (deletedArray[i] && t.deletePending) {\n t.deleted = true;\n newDeleted++;\n continue;\n }\n t.vertices[ref.vertexId] = origVertex;\n t.isDirty = true;\n t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);\n t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);\n t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);\n t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);\n this.references.push(ref);\n }\n return newDeleted;\n };\n QuadraticErrorSimplification.prototype.identifyBorder = function () {\n for (var i = 0; i < this.vertices.length; ++i) {\n var vCount = [];\n var vId = [];\n var v = this.vertices[i];\n var j;\n for (j = 0; j < v.triangleCount; ++j) {\n var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];\n for (var ii = 0; ii < 3; ii++) {\n var ofs = 0;\n var vv = triangle.vertices[ii];\n while (ofs < vCount.length) {\n if (vId[ofs] === vv.id)\n break;\n ++ofs;\n }\n if (ofs === vCount.length) {\n vCount.push(1);\n vId.push(vv.id);\n }\n else {\n vCount[ofs]++;\n }\n }\n }\n for (j = 0; j < vCount.length; ++j) {\n if (vCount[j] === 1) {\n this.vertices[vId[j]].isBorder = true;\n }\n else {\n this.vertices[vId[j]].isBorder = false;\n }\n }\n }\n };\n QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {\n if (identifyBorders === void 0) { identifyBorders = false; }\n var i;\n if (!identifyBorders) {\n var newTrianglesVector = [];\n for (i = 0; i < this.triangles.length; ++i) {\n if (!this.triangles[i].deleted) {\n newTrianglesVector.push(this.triangles[i]);\n }\n }\n this.triangles = newTrianglesVector;\n }\n for (i = 0; i < this.vertices.length; ++i) {\n this.vertices[i].triangleCount = 0;\n this.vertices[i].triangleStart = 0;\n }\n var t;\n var j;\n var v;\n for (i = 0; i < this.triangles.length; ++i) {\n t = this.triangles[i];\n for (j = 0; j < 3; ++j) {\n v = t.vertices[j];\n v.triangleCount++;\n }\n }\n var tStart = 0;\n for (i = 0; i < this.vertices.length; ++i) {\n this.vertices[i].triangleStart = tStart;\n tStart += this.vertices[i].triangleCount;\n this.vertices[i].triangleCount = 0;\n }\n var newReferences = new Array(this.triangles.length * 3);\n for (i = 0; i < this.triangles.length; ++i) {\n t = this.triangles[i];\n for (j = 0; j < 3; ++j) {\n v = t.vertices[j];\n newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);\n v.triangleCount++;\n }\n }\n this.references = newReferences;\n if (identifyBorders) {\n this.identifyBorder();\n }\n };\n QuadraticErrorSimplification.prototype.vertexError = function (q, point) {\n var x = point.x;\n var y = point.y;\n var z = point.z;\n return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y\n + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];\n };\n QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {\n var q = vertex1.q.add(vertex2.q);\n var border = vertex1.isBorder && vertex2.isBorder;\n var error = 0;\n var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);\n if (qDet !== 0 && !border) {\n if (!pointResult) {\n pointResult = BABYLON.Vector3.Zero();\n }\n pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));\n pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));\n pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));\n error = this.vertexError(q, pointResult);\n }\n else {\n var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));\n //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();\n var error1 = this.vertexError(q, vertex1.position);\n var error2 = this.vertexError(q, vertex2.position);\n var error3 = this.vertexError(q, p3);\n error = Math.min(error1, error2, error3);\n if (error === error1) {\n if (pointResult) {\n pointResult.copyFrom(vertex1.position);\n }\n }\n else if (error === error2) {\n if (pointResult) {\n pointResult.copyFrom(vertex2.position);\n }\n }\n else {\n if (pointResult) {\n pointResult.copyFrom(p3);\n }\n }\n }\n return error;\n };\n return QuadraticErrorSimplification;\n }());\n BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.meshSimplification.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var MeshLODLevel = /** @class */ (function () {\n function MeshLODLevel(distance, mesh) {\n this.distance = distance;\n this.mesh = mesh;\n }\n return MeshLODLevel;\n }());\n BABYLON.MeshLODLevel = MeshLODLevel;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.meshLODLevel.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the root class used to create scene optimization to use with SceneOptimizer\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var SceneOptimization = /** @class */ (function () {\n /**\n * Creates the SceneOptimization object\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @param desc defines the description associated with the optimization\n */\n function SceneOptimization(\n /**\n * Defines the priority of this optimization (0 by default which means first in the list)\n */\n priority) {\n if (priority === void 0) { priority = 0; }\n this.priority = priority;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n SceneOptimization.prototype.getDescription = function () {\n return \"\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n SceneOptimization.prototype.apply = function (scene, optimizer) {\n return true;\n };\n ;\n return SceneOptimization;\n }());\n BABYLON.SceneOptimization = SceneOptimization;\n /**\n * Defines an optimization used to reduce the size of render target textures\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var TextureOptimization = /** @class */ (function (_super) {\n __extends(TextureOptimization, _super);\n /**\n * Creates the TextureOptimization object\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter\n * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.\n */\n function TextureOptimization(\n /**\n * Defines the priority of this optimization (0 by default which means first in the list)\n */\n priority, \n /**\n * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter\n */\n maximumSize, \n /**\n * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.\n */\n step) {\n if (priority === void 0) { priority = 0; }\n if (maximumSize === void 0) { maximumSize = 1024; }\n if (step === void 0) { step = 0.5; }\n var _this = _super.call(this, priority) || this;\n _this.priority = priority;\n _this.maximumSize = maximumSize;\n _this.step = step;\n return _this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n TextureOptimization.prototype.getDescription = function () {\n return \"Reducing render target texture size to \" + this.maximumSize;\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n TextureOptimization.prototype.apply = function (scene, optimizer) {\n var allDone = true;\n for (var index = 0; index < scene.textures.length; index++) {\n var texture = scene.textures[index];\n if (!texture.canRescale || texture.getContext) {\n continue;\n }\n var currentSize = texture.getSize();\n var maxDimension = Math.max(currentSize.width, currentSize.height);\n if (maxDimension > this.maximumSize) {\n texture.scale(this.step);\n allDone = false;\n }\n }\n return allDone;\n };\n return TextureOptimization;\n }(SceneOptimization));\n BABYLON.TextureOptimization = TextureOptimization;\n /**\n * Defines an optimization used to increase or decrease the rendering resolution\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var HardwareScalingOptimization = /** @class */ (function (_super) {\n __extends(HardwareScalingOptimization, _super);\n /**\n * Creates the HardwareScalingOptimization object\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @param maximumScale defines the maximum scale to use (2 by default)\n * @param step defines the step to use between two passes (0.5 by default)\n */\n function HardwareScalingOptimization(\n /**\n * Defines the priority of this optimization (0 by default which means first in the list)\n */\n priority, \n /**\n * Defines the maximum scale to use (2 by default)\n */\n maximumScale, \n /**\n * Defines the step to use between two passes (0.5 by default)\n */\n step) {\n if (priority === void 0) { priority = 0; }\n if (maximumScale === void 0) { maximumScale = 2; }\n if (step === void 0) { step = 0.25; }\n var _this = _super.call(this, priority) || this;\n _this.priority = priority;\n _this.maximumScale = maximumScale;\n _this.step = step;\n _this._currentScale = -1;\n _this._directionOffset = 1;\n return _this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n HardwareScalingOptimization.prototype.getDescription = function () {\n return \"Setting hardware scaling level to \" + this._currentScale;\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {\n if (this._currentScale === -1) {\n this._currentScale = scene.getEngine().getHardwareScalingLevel();\n if (this._currentScale > this.maximumScale) {\n this._directionOffset = -1;\n }\n }\n this._currentScale += this._directionOffset * this.step;\n scene.getEngine().setHardwareScalingLevel(this._currentScale);\n return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;\n };\n ;\n return HardwareScalingOptimization;\n }(SceneOptimization));\n BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;\n /**\n * Defines an optimization used to remove shadows\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var ShadowsOptimization = /** @class */ (function (_super) {\n __extends(ShadowsOptimization, _super);\n function ShadowsOptimization() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n ShadowsOptimization.prototype.getDescription = function () {\n return \"Turning shadows on/off\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n ShadowsOptimization.prototype.apply = function (scene, optimizer) {\n scene.shadowsEnabled = optimizer.isInImprovementMode;\n return true;\n };\n ;\n return ShadowsOptimization;\n }(SceneOptimization));\n BABYLON.ShadowsOptimization = ShadowsOptimization;\n /**\n * Defines an optimization used to turn post-processes off\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var PostProcessesOptimization = /** @class */ (function (_super) {\n __extends(PostProcessesOptimization, _super);\n function PostProcessesOptimization() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n PostProcessesOptimization.prototype.getDescription = function () {\n return \"Turning post-processes on/off\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n PostProcessesOptimization.prototype.apply = function (scene, optimizer) {\n scene.postProcessesEnabled = optimizer.isInImprovementMode;\n return true;\n };\n ;\n return PostProcessesOptimization;\n }(SceneOptimization));\n BABYLON.PostProcessesOptimization = PostProcessesOptimization;\n /**\n * Defines an optimization used to turn lens flares off\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var LensFlaresOptimization = /** @class */ (function (_super) {\n __extends(LensFlaresOptimization, _super);\n function LensFlaresOptimization() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n LensFlaresOptimization.prototype.getDescription = function () {\n return \"Turning lens flares on/off\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n LensFlaresOptimization.prototype.apply = function (scene, optimizer) {\n scene.lensFlaresEnabled = optimizer.isInImprovementMode;\n return true;\n };\n ;\n return LensFlaresOptimization;\n }(SceneOptimization));\n BABYLON.LensFlaresOptimization = LensFlaresOptimization;\n /**\n * Defines an optimization based on user defined callback.\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var CustomOptimization = /** @class */ (function (_super) {\n __extends(CustomOptimization, _super);\n function CustomOptimization() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n CustomOptimization.prototype.getDescription = function () {\n if (this.onGetDescription) {\n return this.onGetDescription();\n }\n return \"Running user defined callback\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n CustomOptimization.prototype.apply = function (scene, optimizer) {\n if (this.onApply) {\n return this.onApply(scene, optimizer);\n }\n return true;\n };\n ;\n return CustomOptimization;\n }(SceneOptimization));\n BABYLON.CustomOptimization = CustomOptimization;\n /**\n * Defines an optimization used to turn particles off\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var ParticlesOptimization = /** @class */ (function (_super) {\n __extends(ParticlesOptimization, _super);\n function ParticlesOptimization() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n ParticlesOptimization.prototype.getDescription = function () {\n return \"Turning particles on/off\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n ParticlesOptimization.prototype.apply = function (scene, optimizer) {\n scene.particlesEnabled = optimizer.isInImprovementMode;\n return true;\n };\n ;\n return ParticlesOptimization;\n }(SceneOptimization));\n BABYLON.ParticlesOptimization = ParticlesOptimization;\n /**\n * Defines an optimization used to turn render targets off\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var RenderTargetsOptimization = /** @class */ (function (_super) {\n __extends(RenderTargetsOptimization, _super);\n function RenderTargetsOptimization() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n RenderTargetsOptimization.prototype.getDescription = function () {\n return \"Turning render targets off\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {\n scene.renderTargetsEnabled = optimizer.isInImprovementMode;\n return true;\n };\n ;\n return RenderTargetsOptimization;\n }(SceneOptimization));\n BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;\n /**\n * Defines an optimization used to merge meshes with compatible materials\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var MergeMeshesOptimization = /** @class */ (function (_super) {\n __extends(MergeMeshesOptimization, _super);\n function MergeMeshesOptimization() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this._canBeMerged = function (abstractMesh) {\n if (!(abstractMesh instanceof BABYLON.Mesh)) {\n return false;\n }\n var mesh = abstractMesh;\n if (mesh.isDisposed()) {\n return false;\n }\n if (!mesh.isVisible || !mesh.isEnabled()) {\n return false;\n }\n if (mesh.instances.length > 0) {\n return false;\n }\n if (mesh.skeleton || mesh.hasLODLevels) {\n return false;\n }\n return true;\n };\n return _this;\n }\n Object.defineProperty(MergeMeshesOptimization, \"UpdateSelectionTree\", {\n /**\n * Gets or sets a boolean which defines if optimization octree has to be updated\n */\n get: function () {\n return MergeMeshesOptimization._UpdateSelectionTree;\n },\n /**\n * Gets or sets a boolean which defines if optimization octree has to be updated\n */\n set: function (value) {\n MergeMeshesOptimization._UpdateSelectionTree = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets a string describing the action executed by the current optimization\n * @return description string\n */\n MergeMeshesOptimization.prototype.getDescription = function () {\n return \"Merging similar meshes together\";\n };\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @param updateSelectionTree defines that the selection octree has to be updated (false by default)\n * @returns true if everything that can be done was applied\n */\n MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {\n var globalPool = scene.meshes.slice(0);\n var globalLength = globalPool.length;\n for (var index = 0; index < globalLength; index++) {\n var currentPool = new Array();\n var current = globalPool[index];\n // Checks\n if (!this._canBeMerged(current)) {\n continue;\n }\n currentPool.push(current);\n // Find compatible meshes\n for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {\n var otherMesh = globalPool[subIndex];\n if (!this._canBeMerged(otherMesh)) {\n continue;\n }\n if (otherMesh.material !== current.material) {\n continue;\n }\n if (otherMesh.checkCollisions !== current.checkCollisions) {\n continue;\n }\n currentPool.push(otherMesh);\n globalLength--;\n globalPool.splice(subIndex, 1);\n subIndex--;\n }\n if (currentPool.length < 2) {\n continue;\n }\n // Merge meshes\n BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);\n }\n if (updateSelectionTree != undefined) {\n if (updateSelectionTree) {\n scene.createOrUpdateSelectionOctree();\n }\n }\n else if (MergeMeshesOptimization.UpdateSelectionTree) {\n scene.createOrUpdateSelectionOctree();\n }\n return true;\n };\n ;\n MergeMeshesOptimization._UpdateSelectionTree = false;\n return MergeMeshesOptimization;\n }(SceneOptimization));\n BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;\n /**\n * Defines a list of options used by SceneOptimizer\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var SceneOptimizerOptions = /** @class */ (function () {\n /**\n * Creates a new list of options used by SceneOptimizer\n * @param targetFrameRate defines the target frame rate to reach (60 by default)\n * @param trackerDuration defines the interval between two checkes (2000ms by default)\n */\n function SceneOptimizerOptions(\n /**\n * Defines the target frame rate to reach (60 by default)\n */\n targetFrameRate, \n /**\n * Defines the interval between two checkes (2000ms by default)\n */\n trackerDuration) {\n if (targetFrameRate === void 0) { targetFrameRate = 60; }\n if (trackerDuration === void 0) { trackerDuration = 2000; }\n this.targetFrameRate = targetFrameRate;\n this.trackerDuration = trackerDuration;\n /**\n * Gets the list of optimizations to apply\n */\n this.optimizations = new Array();\n }\n /**\n * Add a new optimization\n * @param optimization defines the SceneOptimization to add to the list of active optimizations\n * @returns the current SceneOptimizerOptions\n */\n SceneOptimizerOptions.prototype.addOptimization = function (optimization) {\n this.optimizations.push(optimization);\n return this;\n };\n /**\n * Add a new custom optimization\n * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)\n * @param onGetDescription defines the callback called to get the description attached with the optimization.\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @returns the current SceneOptimizerOptions\n */\n SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {\n if (priority === void 0) { priority = 0; }\n var optimization = new CustomOptimization(priority);\n optimization.onApply = onApply;\n optimization.onGetDescription = onGetDescription;\n this.optimizations.push(optimization);\n return this;\n };\n /**\n * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene\n * @param targetFrameRate defines the target frame rate (60 by default)\n * @returns a SceneOptimizerOptions object\n */\n SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {\n var result = new SceneOptimizerOptions(targetFrameRate);\n var priority = 0;\n result.addOptimization(new MergeMeshesOptimization(priority));\n result.addOptimization(new ShadowsOptimization(priority));\n result.addOptimization(new LensFlaresOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new PostProcessesOptimization(priority));\n result.addOptimization(new ParticlesOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new TextureOptimization(priority, 1024));\n return result;\n };\n /**\n * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual\n * @param targetFrameRate defines the target frame rate (60 by default)\n * @returns a SceneOptimizerOptions object\n */\n SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {\n var result = new SceneOptimizerOptions(targetFrameRate);\n var priority = 0;\n result.addOptimization(new MergeMeshesOptimization(priority));\n result.addOptimization(new ShadowsOptimization(priority));\n result.addOptimization(new LensFlaresOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new PostProcessesOptimization(priority));\n result.addOptimization(new ParticlesOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new TextureOptimization(priority, 512));\n // Next priority\n priority++;\n result.addOptimization(new RenderTargetsOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new HardwareScalingOptimization(priority, 2));\n return result;\n };\n /**\n * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual\n * @param targetFrameRate defines the target frame rate (60 by default)\n * @returns a SceneOptimizerOptions object\n */\n SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {\n var result = new SceneOptimizerOptions(targetFrameRate);\n var priority = 0;\n result.addOptimization(new MergeMeshesOptimization(priority));\n result.addOptimization(new ShadowsOptimization(priority));\n result.addOptimization(new LensFlaresOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new PostProcessesOptimization(priority));\n result.addOptimization(new ParticlesOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new TextureOptimization(priority, 256));\n // Next priority\n priority++;\n result.addOptimization(new RenderTargetsOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new HardwareScalingOptimization(priority, 4));\n return result;\n };\n return SceneOptimizerOptions;\n }());\n BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;\n /**\n * Class used to run optimizations in order to reach a target frame rate\n * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer\n */\n var SceneOptimizer = /** @class */ (function () {\n /**\n * Creates a new SceneOptimizer\n * @param scene defines the scene to work on\n * @param options defines the options to use with the SceneOptimizer\n * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)\n * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)\n */\n function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {\n if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }\n if (improvementMode === void 0) { improvementMode = false; }\n var _this = this;\n this._isRunning = false;\n this._currentPriorityLevel = 0;\n this._targetFrameRate = 60;\n this._trackerDuration = 2000;\n this._currentFrameRate = 0;\n this._improvementMode = false;\n /**\n * Defines an observable called when the optimizer reaches the target frame rate\n */\n this.onSuccessObservable = new BABYLON.Observable();\n /**\n * Defines an observable called when the optimizer enables an optimization\n */\n this.onNewOptimizationAppliedObservable = new BABYLON.Observable();\n /**\n * Defines an observable called when the optimizer is not able to reach the target frame rate\n */\n this.onFailureObservable = new BABYLON.Observable();\n if (!options) {\n this._options = new SceneOptimizerOptions();\n }\n else {\n this._options = options;\n }\n if (this._options.targetFrameRate) {\n this._targetFrameRate = this._options.targetFrameRate;\n }\n if (this._options.trackerDuration) {\n this._trackerDuration = this._options.trackerDuration;\n }\n if (autoGeneratePriorities) {\n var priority = 0;\n for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {\n var optim = _a[_i];\n optim.priority = priority++;\n }\n }\n this._improvementMode = improvementMode;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {\n _this._sceneDisposeObserver = null;\n _this.dispose();\n });\n }\n Object.defineProperty(SceneOptimizer.prototype, \"isInImprovementMode\", {\n /**\n * Gets a boolean indicating if the optimizer is in improvement mode\n */\n get: function () {\n return this._improvementMode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneOptimizer.prototype, \"currentPriorityLevel\", {\n /**\n * Gets the current priority level (0 at start)\n */\n get: function () {\n return this._currentPriorityLevel;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneOptimizer.prototype, \"currentFrameRate\", {\n /**\n * Gets the current frame rate checked by the SceneOptimizer\n */\n get: function () {\n return this._currentFrameRate;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneOptimizer.prototype, \"targetFrameRate\", {\n /**\n * Gets or sets the current target frame rate (60 by default)\n */\n get: function () {\n return this._targetFrameRate;\n },\n /**\n * Gets or sets the current target frame rate (60 by default)\n */\n set: function (value) {\n this._targetFrameRate = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneOptimizer.prototype, \"trackerDuration\", {\n /**\n * Gets or sets the current interval between two checks (every 2000ms by default)\n */\n get: function () {\n return this._trackerDuration;\n },\n /**\n * Gets or sets the current interval between two checks (every 2000ms by default)\n */\n set: function (value) {\n this._trackerDuration = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneOptimizer.prototype, \"optimizations\", {\n /**\n * Gets the list of active optimizations\n */\n get: function () {\n return this._options.optimizations;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Stops the current optimizer\n */\n SceneOptimizer.prototype.stop = function () {\n this._isRunning = false;\n };\n /**\n * Reset the optimizer to initial step (current priority level = 0)\n */\n SceneOptimizer.prototype.reset = function () {\n this._currentPriorityLevel = 0;\n };\n /**\n * Start the optimizer. By default it will try to reach a specific framerate\n * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate\n */\n SceneOptimizer.prototype.start = function () {\n var _this = this;\n if (this._isRunning) {\n return;\n }\n this._isRunning = true;\n // Let's wait for the scene to be ready before running our check\n this._scene.executeWhenReady(function () {\n setTimeout(function () {\n _this._checkCurrentState();\n }, _this._trackerDuration);\n });\n };\n SceneOptimizer.prototype._checkCurrentState = function () {\n var _this = this;\n if (!this._isRunning) {\n return;\n }\n var scene = this._scene;\n var options = this._options;\n this._currentFrameRate = Math.round(scene.getEngine().getFps());\n if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||\n !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {\n this._isRunning = false;\n this.onSuccessObservable.notifyObservers(this);\n return;\n }\n // Apply current level of optimizations\n var allDone = true;\n var noOptimizationApplied = true;\n for (var index = 0; index < options.optimizations.length; index++) {\n var optimization = options.optimizations[index];\n if (optimization.priority === this._currentPriorityLevel) {\n noOptimizationApplied = false;\n allDone = allDone && optimization.apply(scene, this);\n this.onNewOptimizationAppliedObservable.notifyObservers(optimization);\n }\n }\n // If no optimization was applied, this is a failure :(\n if (noOptimizationApplied) {\n this._isRunning = false;\n this.onFailureObservable.notifyObservers(this);\n return;\n }\n // If all optimizations were done, move to next level\n if (allDone) {\n this._currentPriorityLevel++;\n }\n // Let's the system running for a specific amount of time before checking FPS\n scene.executeWhenReady(function () {\n setTimeout(function () {\n _this._checkCurrentState();\n }, _this._trackerDuration);\n });\n };\n /**\n * Release all resources\n */\n SceneOptimizer.prototype.dispose = function () {\n this.stop();\n this.onSuccessObservable.clear();\n this.onFailureObservable.clear();\n this.onNewOptimizationAppliedObservable.clear();\n if (this._sceneDisposeObserver) {\n this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);\n }\n };\n /**\n * Helper function to create a SceneOptimizer with one single line of code\n * @param scene defines the scene to work on\n * @param options defines the options to use with the SceneOptimizer\n * @param onSuccess defines a callback to call on success\n * @param onFailure defines a callback to call on failure\n * @returns the new SceneOptimizer object\n */\n SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {\n var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);\n if (onSuccess) {\n optimizer.onSuccessObservable.add(function () {\n onSuccess();\n });\n }\n if (onFailure) {\n optimizer.onFailureObservable.add(function () {\n onFailure();\n });\n }\n optimizer.start();\n return optimizer;\n };\n return SceneOptimizer;\n }());\n BABYLON.SceneOptimizer = SceneOptimizer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sceneOptimizer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var OutlineRenderer = /** @class */ (function () {\n function OutlineRenderer(scene) {\n this.zOffset = 1;\n this._scene = scene;\n }\n OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {\n var _this = this;\n if (useOverlay === void 0) { useOverlay = false; }\n var scene = this._scene;\n var engine = this._scene.getEngine();\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);\n if (!this.isReady(subMesh, hardwareInstancedRendering)) {\n return;\n }\n var mesh = subMesh.getRenderingMesh();\n var material = subMesh.getMaterial();\n if (!material || !scene.activeCamera) {\n return;\n }\n engine.enableEffect(this._effect);\n // Logarithmic depth\n if (material.useLogarithmicDepth) {\n this._effect.setFloat(\"logarithmicDepthConstant\", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));\n }\n this._effect.setFloat(\"offset\", useOverlay ? 0 : mesh.outlineWidth);\n this._effect.setColor4(\"color\", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);\n this._effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n this._effect.setMatrices(\"mBones\", mesh.skeleton.getTransformMatrices(mesh));\n }\n mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n this._effect.setTexture(\"diffuseSampler\", alphaTexture);\n this._effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n engine.setZOffset(-this.zOffset);\n mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix(\"world\", world); });\n engine.setZOffset(0);\n };\n OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {\n var defines = [];\n var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];\n var mesh = subMesh.getMesh();\n var material = subMesh.getMaterial();\n if (material) {\n // Alpha test\n if (material.needAlphaTesting()) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n //Logarithmic depth\n if (material.useLogarithmicDepth) {\n defines.push(\"#define LOGARITHMICDEPTH\");\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n // Get correct effect \n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n this._effect = this._scene.getEngine().createEffect(\"outline\", attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\", \"offset\", \"color\", \"logarithmicDepthConstant\"], [\"diffuseSampler\"], join);\n }\n return this._effect.isReady();\n };\n return OutlineRenderer;\n }());\n BABYLON.OutlineRenderer = OutlineRenderer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.outlineRenderer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var FaceAdjacencies = /** @class */ (function () {\n function FaceAdjacencies() {\n this.edges = new Array();\n this.edgesConnectedCount = 0;\n }\n return FaceAdjacencies;\n }());\n var EdgesRenderer = /** @class */ (function () {\n // Beware when you use this class with complex objects as the adjacencies computation can be really long\n function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {\n if (epsilon === void 0) { epsilon = 0.95; }\n if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }\n this.edgesWidthScalerForOrthographic = 1000.0;\n this.edgesWidthScalerForPerspective = 50.0;\n this._linesPositions = new Array();\n this._linesNormals = new Array();\n this._linesIndices = new Array();\n this._buffers = {};\n this._checkVerticesInsteadOfIndices = false;\n /** Gets or sets a boolean indicating if the edgesRenderer is active */\n this.isEnabled = true;\n this._source = source;\n this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;\n this._epsilon = epsilon;\n this._prepareRessources();\n this._generateEdgesLines();\n }\n EdgesRenderer.prototype._prepareRessources = function () {\n if (this._lineShader) {\n return;\n }\n this._lineShader = new BABYLON.ShaderMaterial(\"lineShader\", this._source.getScene(), \"line\", {\n attributes: [\"position\", \"normal\"],\n uniforms: [\"worldViewProjection\", \"color\", \"width\", \"aspectRatio\"]\n });\n this._lineShader.disableDepthWrite = true;\n this._lineShader.backFaceCulling = false;\n };\n EdgesRenderer.prototype._rebuild = function () {\n var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];\n if (buffer) {\n buffer._rebuild();\n }\n buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];\n if (buffer) {\n buffer._rebuild();\n }\n var scene = this._source.getScene();\n var engine = scene.getEngine();\n this._ib = engine.createIndexBuffer(this._linesIndices);\n };\n EdgesRenderer.prototype.dispose = function () {\n var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];\n if (buffer) {\n buffer.dispose();\n this._buffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];\n if (buffer) {\n buffer.dispose();\n this._buffers[BABYLON.VertexBuffer.NormalKind] = null;\n }\n this._source.getScene().getEngine()._releaseBuffer(this._ib);\n this._lineShader.dispose();\n };\n EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {\n if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {\n return 0;\n }\n if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {\n return 1;\n }\n if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {\n return 2;\n }\n return -1;\n };\n EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {\n if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {\n return 0;\n }\n if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {\n return 1;\n }\n if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {\n return 2;\n }\n return -1;\n };\n EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {\n var needToCreateLine;\n if (edge === undefined) {\n needToCreateLine = true;\n }\n else {\n var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);\n needToCreateLine = dotProduct < this._epsilon;\n }\n if (needToCreateLine) {\n var offset = this._linesPositions.length / 3;\n var normal = p0.subtract(p1);\n normal.normalize();\n // Positions\n this._linesPositions.push(p0.x);\n this._linesPositions.push(p0.y);\n this._linesPositions.push(p0.z);\n this._linesPositions.push(p0.x);\n this._linesPositions.push(p0.y);\n this._linesPositions.push(p0.z);\n this._linesPositions.push(p1.x);\n this._linesPositions.push(p1.y);\n this._linesPositions.push(p1.z);\n this._linesPositions.push(p1.x);\n this._linesPositions.push(p1.y);\n this._linesPositions.push(p1.z);\n // Normals\n this._linesNormals.push(p1.x);\n this._linesNormals.push(p1.y);\n this._linesNormals.push(p1.z);\n this._linesNormals.push(-1);\n this._linesNormals.push(p1.x);\n this._linesNormals.push(p1.y);\n this._linesNormals.push(p1.z);\n this._linesNormals.push(1);\n this._linesNormals.push(p0.x);\n this._linesNormals.push(p0.y);\n this._linesNormals.push(p0.z);\n this._linesNormals.push(-1);\n this._linesNormals.push(p0.x);\n this._linesNormals.push(p0.y);\n this._linesNormals.push(p0.z);\n this._linesNormals.push(1);\n // Indices\n this._linesIndices.push(offset);\n this._linesIndices.push(offset + 1);\n this._linesIndices.push(offset + 2);\n this._linesIndices.push(offset);\n this._linesIndices.push(offset + 2);\n this._linesIndices.push(offset + 3);\n }\n };\n EdgesRenderer.prototype._generateEdgesLines = function () {\n var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);\n var indices = this._source.getIndices();\n if (!indices || !positions) {\n return;\n }\n // First let's find adjacencies\n var adjacencies = new Array();\n var faceNormals = new Array();\n var index;\n var faceAdjacencies;\n // Prepare faces\n for (index = 0; index < indices.length; index += 3) {\n faceAdjacencies = new FaceAdjacencies();\n var p0Index = indices[index];\n var p1Index = indices[index + 1];\n var p2Index = indices[index + 2];\n faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);\n faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);\n faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);\n var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));\n faceNormal.normalize();\n faceNormals.push(faceNormal);\n adjacencies.push(faceAdjacencies);\n }\n // Scan\n for (index = 0; index < adjacencies.length; index++) {\n faceAdjacencies = adjacencies[index];\n for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {\n var otherFaceAdjacencies = adjacencies[otherIndex];\n if (faceAdjacencies.edgesConnectedCount === 3) { // Full\n break;\n }\n if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full\n continue;\n }\n var otherP0 = indices[otherIndex * 3];\n var otherP1 = indices[otherIndex * 3 + 1];\n var otherP2 = indices[otherIndex * 3 + 2];\n for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {\n var otherEdgeIndex = 0;\n if (faceAdjacencies.edges[edgeIndex] !== undefined) {\n continue;\n }\n switch (edgeIndex) {\n case 0:\n if (this._checkVerticesInsteadOfIndices) {\n otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);\n }\n else {\n otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);\n }\n break;\n case 1:\n if (this._checkVerticesInsteadOfIndices) {\n otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);\n }\n else {\n otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);\n }\n break;\n case 2:\n if (this._checkVerticesInsteadOfIndices) {\n otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);\n }\n else {\n otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);\n }\n break;\n }\n if (otherEdgeIndex === -1) {\n continue;\n }\n faceAdjacencies.edges[edgeIndex] = otherIndex;\n otherFaceAdjacencies.edges[otherEdgeIndex] = index;\n faceAdjacencies.edgesConnectedCount++;\n otherFaceAdjacencies.edgesConnectedCount++;\n if (faceAdjacencies.edgesConnectedCount === 3) {\n break;\n }\n }\n }\n }\n // Create lines\n for (index = 0; index < adjacencies.length; index++) {\n // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon\n var current = adjacencies[index];\n this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);\n this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);\n this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);\n }\n // Merge into a single mesh\n var engine = this._source.getScene().getEngine();\n this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);\n this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);\n this._ib = engine.createIndexBuffer(this._linesIndices);\n this._indicesCount = this._linesIndices.length;\n };\n EdgesRenderer.prototype.render = function () {\n var scene = this._source.getScene();\n if (!this._lineShader.isReady() || !scene.activeCamera) {\n return;\n }\n var engine = scene.getEngine();\n this._lineShader._preBind();\n // VBOs\n engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());\n scene.resetCachedMaterial();\n this._lineShader.setColor4(\"color\", this._source.edgesColor);\n if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {\n this._lineShader.setFloat(\"width\", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);\n }\n else {\n this._lineShader.setFloat(\"width\", this._source.edgesWidth / this.edgesWidthScalerForPerspective);\n }\n this._lineShader.setFloat(\"aspectRatio\", engine.getAspectRatio(scene.activeCamera));\n this._lineShader.bind(this._source.getWorldMatrix());\n // Draw order\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);\n this._lineShader.unbind();\n engine.setDepthWrite(true);\n };\n return EdgesRenderer;\n }());\n BABYLON.EdgesRenderer = EdgesRenderer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.edgesRenderer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n // Adds the parser to the scene parsers.\n BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {\n if (parsedData.effectLayers) {\n for (var index = 0; index < parsedData.effectLayers.length; index++) {\n var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);\n container.effectLayers.push(effectLayer);\n }\n }\n });\n BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {\n var index = this.effectLayers.indexOf(toRemove);\n if (index !== -1) {\n this.effectLayers.splice(index, 1);\n }\n return index;\n };\n BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {\n this.effectLayers.push(newEffectLayer);\n };\n /**\n * Defines the layer scene component responsible to manage any effect layers\n * in a given scene.\n */\n var EffectLayerSceneComponent = /** @class */ (function () {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n function EffectLayerSceneComponent(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;\n this._renderEffects = false;\n this._needStencil = false;\n this._previousStencilState = false;\n this.scene = scene;\n this._engine = scene.getEngine();\n scene.effectLayers = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n EffectLayerSceneComponent.prototype.register = function () {\n this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);\n this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);\n this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);\n this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);\n this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);\n this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);\n };\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n EffectLayerSceneComponent.prototype.rebuild = function () {\n var layers = this.scene.effectLayers;\n for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {\n var effectLayer = layers_1[_i];\n effectLayer._rebuild();\n }\n };\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {\n // Effect layers\n serializationObject.effectLayers = [];\n var layers = this.scene.effectLayers;\n for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {\n var effectLayer = layers_2[_i];\n if (effectLayer.serialize) {\n serializationObject.effectLayers.push(effectLayer.serialize());\n }\n }\n };\n /**\n * Adds all the element from the container to the scene\n * @param container the container holding the elements\n */\n EffectLayerSceneComponent.prototype.addFromContainer = function (container) {\n var _this = this;\n if (!container.effectLayers) {\n return;\n }\n container.effectLayers.forEach(function (o) {\n _this.scene.addEffectLayer(o);\n });\n };\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n */\n EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {\n var _this = this;\n if (!container.effectLayers) {\n return;\n }\n container.effectLayers.forEach(function (o) {\n _this.scene.removeEffectLayer(o);\n });\n };\n /**\n * Disposes the component and the associated ressources.\n */\n EffectLayerSceneComponent.prototype.dispose = function () {\n var layers = this.scene.effectLayers;\n while (layers.length) {\n layers[0].dispose();\n }\n };\n EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {\n var layers = this.scene.effectLayers;\n for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {\n var layer = layers_3[_i];\n if (!layer.hasMesh(mesh)) {\n continue;\n }\n for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {\n var subMesh = _b[_a];\n if (!layer.isReady(subMesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n return true;\n };\n EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {\n this._renderEffects = false;\n this._needStencil = false;\n var layers = this.scene.effectLayers;\n if (layers && layers.length > 0) {\n this._previousStencilState = this._engine.getStencilBuffer();\n for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {\n var effectLayer = layers_4[_i];\n if (effectLayer.shouldRender() &&\n (!effectLayer.camera ||\n (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||\n (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {\n this._renderEffects = true;\n this._needStencil = this._needStencil || effectLayer.needStencil();\n var renderTarget = effectLayer._mainTexture;\n if (renderTarget._shouldRender()) {\n this.scene.incrementRenderId();\n renderTarget.render(false, false);\n }\n }\n }\n this.scene.incrementRenderId();\n }\n };\n EffectLayerSceneComponent.prototype._setStencil = function (camera) {\n // Activate effect Layer stencil\n if (this._needStencil) {\n this._engine.setStencilBuffer(true);\n }\n };\n EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {\n // Restore effect Layer stencil\n if (this._needStencil) {\n this._engine.setStencilBuffer(this._previousStencilState);\n }\n };\n EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {\n if (this._renderEffects) {\n this._engine.setDepthBuffer(false);\n var layers = this.scene.effectLayers;\n for (var i = 0; i < layers.length; i++) {\n var effectLayer = layers[i];\n if (effectLayer.renderingGroupId === renderingGroupId) {\n if (effectLayer.shouldRender()) {\n effectLayer.render();\n }\n }\n }\n this._engine.setDepthBuffer(true);\n }\n };\n EffectLayerSceneComponent.prototype._drawCamera = function (camera) {\n if (this._renderEffects) {\n this._draw(-1);\n }\n };\n EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {\n if (!this.scene._isInIntermediateRendering() && this._renderEffects) {\n this._draw(index);\n }\n };\n return EffectLayerSceneComponent;\n }());\n BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.effectLayerSceneComponent.js.map\n\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The effect layer Helps adding post process effect blended with the main pass.\n *\n * This can be for instance use to generate glow or higlight effects on the scene.\n *\n * The effect layer class can not be used directly and is intented to inherited from to be\n * customized per effects.\n */\n var EffectLayer = /** @class */ (function () {\n /**\n * Instantiates a new effect Layer and references it in the scene.\n * @param name The name of the layer\n * @param scene The scene to use the layer in\n */\n function EffectLayer(\n /** The Friendly of the effect in the scene */\n name, scene) {\n this._vertexBuffers = {};\n this._maxSize = 0;\n this._mainTextureDesiredSize = { width: 0, height: 0 };\n this._shouldRender = true;\n this._postProcesses = [];\n this._textures = [];\n this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };\n /**\n * The clear color of the texture used to generate the glow map.\n */\n this.neutralColor = new BABYLON.Color4();\n /**\n * Specifies wether the highlight layer is enabled or not.\n */\n this.isEnabled = true;\n /**\n * An event triggered when the effect layer has been disposed.\n */\n this.onDisposeObservable = new BABYLON.Observable();\n /**\n * An event triggered when the effect layer is about rendering the main texture with the glowy parts.\n */\n this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();\n /**\n * An event triggered when the generated texture is being merged in the scene.\n */\n this.onBeforeComposeObservable = new BABYLON.Observable();\n /**\n * An event triggered when the generated texture has been merged in the scene.\n */\n this.onAfterComposeObservable = new BABYLON.Observable();\n /**\n * An event triggered when the efffect layer changes its size.\n */\n this.onSizeChangedObservable = new BABYLON.Observable();\n this.name = name;\n this._scene = scene || BABYLON.Engine.LastCreatedScene;\n var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);\n if (!component) {\n component = new BABYLON.EffectLayerSceneComponent(this._scene);\n this._scene._addComponent(component);\n }\n this._engine = this._scene.getEngine();\n this._maxSize = this._engine.getCaps().maxTextureSize;\n this._scene.effectLayers.push(this);\n // Generate Buffers\n this._generateIndexBuffer();\n this._genrateVertexBuffer();\n }\n Object.defineProperty(EffectLayer.prototype, \"camera\", {\n /**\n * Gets the camera attached to the layer.\n */\n get: function () {\n return this._effectLayerOptions.camera;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EffectLayer.prototype, \"renderingGroupId\", {\n /**\n * Gets the rendering group id the layer should render in.\n */\n get: function () {\n return this._effectLayerOptions.renderingGroupId;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Initializes the effect layer with the required options.\n * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)\n */\n EffectLayer.prototype._init = function (options) {\n // Adapt options\n this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);\n this._setMainTextureSize();\n this._createMainTexture();\n this._createTextureAndPostProcesses();\n this._mergeEffect = this._createMergeEffect();\n };\n /**\n * Generates the index buffer of the full screen quad blending to the main canvas.\n */\n EffectLayer.prototype._generateIndexBuffer = function () {\n // Indices\n var indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = this._engine.createIndexBuffer(indices);\n };\n /**\n * Generates the vertex buffer of the full screen quad blending to the main canvas.\n */\n EffectLayer.prototype._genrateVertexBuffer = function () {\n // VBO\n var vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;\n };\n /**\n * Sets the main texture desired size which is the closest power of two\n * of the engine canvas size.\n */\n EffectLayer.prototype._setMainTextureSize = function () {\n if (this._effectLayerOptions.mainTextureFixedSize) {\n this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;\n this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;\n }\n else {\n this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;\n this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;\n this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;\n this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;\n }\n this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);\n this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);\n };\n /**\n * Creates the main texture for the effect layer.\n */\n EffectLayer.prototype._createMainTexture = function () {\n var _this = this;\n this._mainTexture = new BABYLON.RenderTargetTexture(\"HighlightLayerMainRTT\", {\n width: this._mainTextureDesiredSize.width,\n height: this._mainTextureDesiredSize.height\n }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n this._mainTexture.activeCamera = this._effectLayerOptions.camera;\n this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._mainTexture.anisotropicFilteringLevel = 1;\n this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n this._mainTexture.renderParticles = false;\n this._mainTexture.renderList = null;\n this._mainTexture.ignoreCameraViewport = true;\n // Custom render function\n this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {\n _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);\n var index;\n var engine = _this._scene.getEngine();\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n _this._renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n _this._renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n _this._renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n for (index = 0; index < transparentSubMeshes.length; index++) {\n _this._renderSubMesh(transparentSubMeshes.data[index]);\n }\n };\n this._mainTexture.onClearObservable.add(function (engine) {\n engine.clear(_this.neutralColor, true, true, true);\n });\n };\n /**\n * Checks for the readiness of the element composing the layer.\n * @param subMesh the mesh to check for\n * @param useInstances specify wether or not to use instances to render the mesh\n * @param emissiveTexture the associated emissive texture used to generate the glow\n * @return true if ready otherwise, false\n */\n EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {\n var material = subMesh.getMaterial();\n if (!material) {\n return false;\n }\n if (!material.isReady(subMesh.getMesh(), useInstances)) {\n return false;\n }\n var defines = [];\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n var mesh = subMesh.getMesh();\n var uv1 = false;\n var uv2 = false;\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&\n alphaTexture.coordinatesIndex === 1) {\n defines.push(\"#define DIFFUSEUV2\");\n uv2 = true;\n }\n else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n defines.push(\"#define DIFFUSEUV1\");\n uv1 = true;\n }\n }\n }\n // Emissive\n if (emissiveTexture) {\n defines.push(\"#define EMISSIVE\");\n if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&\n emissiveTexture.coordinatesIndex === 1) {\n defines.push(\"#define EMISSIVEUV2\");\n uv2 = true;\n }\n else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {\n defines.push(\"#define EMISSIVEUV1\");\n uv1 = true;\n }\n }\n if (uv1) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (uv2) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets \n var manager = mesh.morphTargetManager;\n var morphInfluencers = 0;\n if (manager) {\n if (manager.numInfluencers > 0) {\n defines.push(\"#define MORPHTARGETS\");\n morphInfluencers = manager.numInfluencers;\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + morphInfluencers);\n BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { \"NUM_MORPH_INFLUENCERS\": morphInfluencers });\n }\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n }\n // Get correct effect\n var join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect(\"glowMapGeneration\", attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\", \"color\", \"emissiveMatrix\", \"morphTargetInfluences\"], [\"diffuseSampler\", \"emissiveSampler\"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });\n }\n return this._effectLayerMapGenerationEffect.isReady();\n };\n /**\n * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.\n */\n EffectLayer.prototype.render = function () {\n var currentEffect = this._mergeEffect;\n // Check\n if (!currentEffect.isReady())\n return;\n for (var i = 0; i < this._postProcesses.length; i++) {\n if (!this._postProcesses[i].isReady()) {\n return;\n }\n }\n var engine = this._scene.getEngine();\n this.onBeforeComposeObservable.notifyObservers(this);\n // Render\n engine.enableEffect(currentEffect);\n engine.setState(false);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);\n // Cache\n var previousAlphaMode = engine.getAlphaMode();\n // Go Blend.\n engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);\n // Blends the map on the main canvas.\n this._internalRender(currentEffect);\n // Restore Alpha\n engine.setAlphaMode(previousAlphaMode);\n this.onAfterComposeObservable.notifyObservers(this);\n // Handle size changes.\n var size = this._mainTexture.getSize();\n this._setMainTextureSize();\n if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {\n // Recreate RTT and post processes on size change.\n this.onSizeChangedObservable.notifyObservers(this);\n this._disposeTextureAndPostProcesses();\n this._createMainTexture();\n this._createTextureAndPostProcesses();\n }\n };\n /**\n * Determine if a given mesh will be used in the current effect.\n * @param mesh mesh to test\n * @returns true if the mesh will be used\n */\n EffectLayer.prototype.hasMesh = function (mesh) {\n if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {\n return true;\n }\n return false;\n };\n /**\n * Returns true if the layer contains information to display, otherwise false.\n * @returns true if the glow layer should be rendered\n */\n EffectLayer.prototype.shouldRender = function () {\n return this.isEnabled && this._shouldRender;\n };\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n EffectLayer.prototype._shouldRenderMesh = function (mesh) {\n return true;\n };\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {\n return true;\n };\n /**\n * Renders the submesh passed in parameter to the generation map.\n */\n EffectLayer.prototype._renderSubMesh = function (subMesh) {\n var _this = this;\n if (!this.shouldRender()) {\n return;\n }\n var material = subMesh.getMaterial();\n var mesh = subMesh.getRenderingMesh();\n var scene = this._scene;\n var engine = scene.getEngine();\n if (!material) {\n return;\n }\n // Do not block in blend mode.\n if (material.needAlphaBlendingForMesh(mesh)) {\n return;\n }\n // Culling\n engine.setState(material.backFaceCulling);\n // Managing instances\n var batch = mesh._getInstancesRenderList(subMesh._id);\n if (batch.mustReturn) {\n return;\n }\n // Early Exit per mesh\n if (!this._shouldRenderMesh(mesh)) {\n return;\n }\n var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);\n this._setEmissiveTextureAndColor(mesh, subMesh, material);\n if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {\n engine.enableEffect(this._effectLayerMapGenerationEffect);\n mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);\n this._effectLayerMapGenerationEffect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n this._effectLayerMapGenerationEffect.setFloat4(\"color\", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);\n // Alpha test\n if (material && material.needAlphaTesting()) {\n var alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n this._effectLayerMapGenerationEffect.setTexture(\"diffuseSampler\", alphaTexture);\n var textureMatrix = alphaTexture.getTextureMatrix();\n if (textureMatrix) {\n this._effectLayerMapGenerationEffect.setMatrix(\"diffuseMatrix\", textureMatrix);\n }\n }\n }\n // Glow emissive only\n if (this._emissiveTextureAndColor.texture) {\n this._effectLayerMapGenerationEffect.setTexture(\"emissiveSampler\", this._emissiveTextureAndColor.texture);\n this._effectLayerMapGenerationEffect.setMatrix(\"emissiveMatrix\", this._emissiveTextureAndColor.texture.getTextureMatrix());\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n this._effectLayerMapGenerationEffect.setMatrices(\"mBones\", mesh.skeleton.getTransformMatrices(mesh));\n }\n // Morph targets\n BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);\n // Draw\n mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix(\"world\", world); });\n }\n else {\n // Need to reset refresh rate of the main map\n this._mainTexture.resetRefreshCounter();\n }\n };\n /**\n * Rebuild the required buffers.\n * @hidden Internal use only.\n */\n EffectLayer.prototype._rebuild = function () {\n var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._generateIndexBuffer();\n };\n /**\n * Dispose only the render target textures and post process.\n */\n EffectLayer.prototype._disposeTextureAndPostProcesses = function () {\n this._mainTexture.dispose();\n for (var i = 0; i < this._postProcesses.length; i++) {\n if (this._postProcesses[i]) {\n this._postProcesses[i].dispose();\n }\n }\n this._postProcesses = [];\n for (var i = 0; i < this._textures.length; i++) {\n if (this._textures[i]) {\n this._textures[i].dispose();\n }\n }\n this._textures = [];\n };\n /**\n * Dispose the highlight layer and free resources.\n */\n EffectLayer.prototype.dispose = function () {\n var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n // Clean textures and post processes\n this._disposeTextureAndPostProcesses();\n // Remove from scene\n var index = this._scene.effectLayers.indexOf(this, 0);\n if (index > -1) {\n this._scene.effectLayers.splice(index, 1);\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onBeforeRenderMainTextureObservable.clear();\n this.onBeforeComposeObservable.clear();\n this.onAfterComposeObservable.clear();\n this.onSizeChangedObservable.clear();\n };\n /**\n * Gets the class name of the effect layer\n * @returns the string with the class name of the effect layer\n */\n EffectLayer.prototype.getClassName = function () {\n return \"EffectLayer\";\n };\n /**\n * Creates an effect layer from parsed effect layer data\n * @param parsedEffectLayer defines effect layer data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing the effect layer information\n * @returns a parsed effect Layer\n */\n EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {\n var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);\n return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);\n };\n __decorate([\n BABYLON.serialize()\n ], EffectLayer.prototype, \"name\", void 0);\n __decorate([\n BABYLON.serializeAsColor4()\n ], EffectLayer.prototype, \"neutralColor\", void 0);\n __decorate([\n BABYLON.serialize()\n ], EffectLayer.prototype, \"isEnabled\", void 0);\n __decorate([\n BABYLON.serializeAsCameraReference()\n ], EffectLayer.prototype, \"camera\", null);\n __decorate([\n BABYLON.serialize()\n ], EffectLayer.prototype, \"renderingGroupId\", null);\n return EffectLayer;\n }());\n BABYLON.EffectLayer = EffectLayer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.effectLayer.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {\n for (var index = 0; index < this.effectLayers.length; index++) {\n if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {\n return this.effectLayers[index];\n }\n }\n return null;\n };\n /**\n * Special Glow Blur post process only blurring the alpha channel\n * It enforces keeping the most luminous color in the color channel.\n */\n var GlowBlurPostProcess = /** @class */ (function (_super) {\n __extends(GlowBlurPostProcess, _super);\n function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }\n var _this = _super.call(this, name, \"glowBlurPostProcess\", [\"screenSize\", \"direction\", \"blurWidth\"], null, options, camera, samplingMode, engine, reusable) || this;\n _this.direction = direction;\n _this.kernel = kernel;\n _this.onApplyObservable.add(function (effect) {\n effect.setFloat2(\"screenSize\", _this.width, _this.height);\n effect.setVector2(\"direction\", _this.direction);\n effect.setFloat(\"blurWidth\", _this.kernel);\n });\n return _this;\n }\n return GlowBlurPostProcess;\n }(BABYLON.PostProcess));\n /**\n * The highlight layer Helps adding a glow effect around a mesh.\n *\n * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove\n * glowy meshes to your scene.\n *\n * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!\n */\n var HighlightLayer = /** @class */ (function (_super) {\n __extends(HighlightLayer, _super);\n /**\n * Instantiates a new highlight Layer and references it to the scene..\n * @param name The name of the layer\n * @param scene The scene to use the layer in\n * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)\n */\n function HighlightLayer(name, scene, options) {\n var _this = _super.call(this, name, scene) || this;\n _this.name = name;\n /**\n * Specifies whether or not the inner glow is ACTIVE in the layer.\n */\n _this.innerGlow = true;\n /**\n * Specifies whether or not the outer glow is ACTIVE in the layer.\n */\n _this.outerGlow = true;\n /**\n * An event triggered when the highlight layer is being blurred.\n */\n _this.onBeforeBlurObservable = new BABYLON.Observable();\n /**\n * An event triggered when the highlight layer has been blurred.\n */\n _this.onAfterBlurObservable = new BABYLON.Observable();\n _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;\n _this._meshes = {};\n _this._excludedMeshes = {};\n _this.neutralColor = HighlightLayer.NeutralColor;\n // Warn on stencil\n if (!_this._engine.isStencilEnable) {\n BABYLON.Tools.Warn(\"Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }\");\n }\n // Adapt options\n _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);\n // Initialize the layer\n _this._init({\n alphaBlendingMode: _this._options.alphaBlendingMode,\n camera: _this._options.camera,\n mainTextureFixedSize: _this._options.mainTextureFixedSize,\n mainTextureRatio: _this._options.mainTextureRatio,\n renderingGroupId: _this._options.renderingGroupId\n });\n // Do not render as long as no meshes have been added\n _this._shouldRender = false;\n return _this;\n }\n Object.defineProperty(HighlightLayer.prototype, \"blurHorizontalSize\", {\n /**\n * Gets the horizontal size of the blur.\n */\n get: function () {\n return this._horizontalBlurPostprocess.kernel;\n },\n /**\n * Specifies the horizontal size of the blur.\n */\n set: function (value) {\n this._horizontalBlurPostprocess.kernel = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(HighlightLayer.prototype, \"blurVerticalSize\", {\n /**\n * Gets the vertical size of the blur.\n */\n get: function () {\n return this._verticalBlurPostprocess.kernel;\n },\n /**\n * Specifies the vertical size of the blur.\n */\n set: function (value) {\n this._verticalBlurPostprocess.kernel = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Get the effect name of the layer.\n * @return The effect name\n */\n HighlightLayer.prototype.getEffectName = function () {\n return HighlightLayer.EffectName;\n };\n /**\n * Create the merge effect. This is the shader use to blit the information back\n * to the main canvas at the end of the scene rendering.\n */\n HighlightLayer.prototype._createMergeEffect = function () {\n // Effect\n return this._engine.createEffect(\"glowMapMerge\", [BABYLON.VertexBuffer.PositionKind], [\"offset\"], [\"textureSampler\"], this._options.isStroke ? \"#define STROKE \\n\" : undefined);\n };\n /**\n * Creates the render target textures and post processes used in the highlight layer.\n */\n HighlightLayer.prototype._createTextureAndPostProcesses = function () {\n var _this = this;\n var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;\n var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;\n blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;\n blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;\n var textureType = 0;\n if (this._engine.getCaps().textureHalfFloatRender) {\n textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else {\n textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n this._blurTexture = new BABYLON.RenderTargetTexture(\"HighlightLayerBlurRTT\", {\n width: blurTextureWidth,\n height: blurTextureHeight\n }, this._scene, false, true, textureType);\n this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._blurTexture.anisotropicFilteringLevel = 16;\n this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);\n this._blurTexture.renderParticles = false;\n this._blurTexture.ignoreCameraViewport = true;\n this._textures = [this._blurTexture];\n if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {\n this._downSamplePostprocess = new BABYLON.PassPostProcess(\"HighlightLayerPPP\", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());\n this._downSamplePostprocess.onApplyObservable.add(function (effect) {\n effect.setTexture(\"textureSampler\", _this._mainTexture);\n });\n this._horizontalBlurPostprocess = new GlowBlurPostProcess(\"HighlightLayerHBP\", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());\n this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {\n effect.setFloat2(\"screenSize\", blurTextureWidth, blurTextureHeight);\n });\n this._verticalBlurPostprocess = new GlowBlurPostProcess(\"HighlightLayerVBP\", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());\n this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {\n effect.setFloat2(\"screenSize\", blurTextureWidth, blurTextureHeight);\n });\n this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];\n }\n else {\n this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess(\"HighlightLayerHBP\", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {\n width: blurTextureWidth,\n height: blurTextureHeight\n }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess.width = blurTextureWidth;\n this._horizontalBlurPostprocess.height = blurTextureHeight;\n this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {\n effect.setTexture(\"textureSampler\", _this._mainTexture);\n });\n this._verticalBlurPostprocess = new BABYLON.BlurPostProcess(\"HighlightLayerVBP\", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {\n width: blurTextureWidth,\n height: blurTextureHeight\n }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];\n }\n this._mainTexture.onAfterUnbindObservable.add(function () {\n _this.onBeforeBlurObservable.notifyObservers(_this);\n var internalTexture = _this._blurTexture.getInternalTexture();\n if (internalTexture) {\n _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);\n }\n _this.onAfterBlurObservable.notifyObservers(_this);\n });\n // Prevent autoClear.\n this._postProcesses.map(function (pp) { pp.autoClear = false; });\n };\n /**\n * Returns wether or nood the layer needs stencil enabled during the mesh rendering.\n */\n HighlightLayer.prototype.needStencil = function () {\n return true;\n };\n /**\n * Checks for the readiness of the element composing the layer.\n * @param subMesh the mesh to check for\n * @param useInstances specify wether or not to use instances to render the mesh\n * @param emissiveTexture the associated emissive texture used to generate the glow\n * @return true if ready otherwise, false\n */\n HighlightLayer.prototype.isReady = function (subMesh, useInstances) {\n var material = subMesh.getMaterial();\n var mesh = subMesh.getRenderingMesh();\n if (!material || !mesh || !this._meshes) {\n return false;\n }\n var emissiveTexture = null;\n var highlightLayerMesh = this._meshes[mesh.uniqueId];\n if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {\n emissiveTexture = material.emissiveTexture;\n }\n return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);\n };\n /**\n * Implementation specific of rendering the generating effect on the main canvas.\n * @param effect The effect used to render through\n */\n HighlightLayer.prototype._internalRender = function (effect) {\n // Texture\n effect.setTexture(\"textureSampler\", this._blurTexture);\n // Cache\n var engine = this._engine;\n var previousStencilBuffer = engine.getStencilBuffer();\n var previousStencilFunction = engine.getStencilFunction();\n var previousStencilMask = engine.getStencilMask();\n var previousStencilOperationPass = engine.getStencilOperationPass();\n var previousStencilOperationFail = engine.getStencilOperationFail();\n var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();\n var previousStencilReference = engine.getStencilFunctionReference();\n // Stencil operations\n engine.setStencilOperationPass(BABYLON.Engine.REPLACE);\n engine.setStencilOperationFail(BABYLON.Engine.KEEP);\n engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);\n // Draw order\n engine.setStencilMask(0x00);\n engine.setStencilBuffer(true);\n engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);\n // 2 passes inner outer\n if (this.outerGlow) {\n effect.setFloat(\"offset\", 0);\n engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n }\n if (this.innerGlow) {\n effect.setFloat(\"offset\", 1);\n engine.setStencilFunction(BABYLON.Engine.EQUAL);\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n }\n // Restore Cache\n engine.setStencilFunction(previousStencilFunction);\n engine.setStencilMask(previousStencilMask);\n engine.setStencilBuffer(previousStencilBuffer);\n engine.setStencilOperationPass(previousStencilOperationPass);\n engine.setStencilOperationFail(previousStencilOperationFail);\n engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);\n engine.setStencilFunctionReference(previousStencilReference);\n };\n /**\n * Returns true if the layer contains information to display, otherwise false.\n */\n HighlightLayer.prototype.shouldRender = function () {\n if (_super.prototype.shouldRender.call(this)) {\n return this._meshes ? true : false;\n }\n return false;\n };\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n HighlightLayer.prototype._shouldRenderMesh = function (mesh) {\n // Excluded Mesh\n if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {\n return false;\n }\n ;\n if (!_super.prototype.hasMesh.call(this, mesh)) {\n return false;\n }\n return true;\n };\n /**\n * Sets the required values for both the emissive texture and and the main color.\n */\n HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {\n var highlightLayerMesh = this._meshes[mesh.uniqueId];\n if (highlightLayerMesh) {\n this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);\n }\n else {\n this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);\n }\n if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {\n this._emissiveTextureAndColor.texture = material.emissiveTexture;\n this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);\n }\n else {\n this._emissiveTextureAndColor.texture = null;\n }\n };\n /**\n * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.\n * @param mesh The mesh to exclude from the highlight layer\n */\n HighlightLayer.prototype.addExcludedMesh = function (mesh) {\n if (!this._excludedMeshes) {\n return;\n }\n var meshExcluded = this._excludedMeshes[mesh.uniqueId];\n if (!meshExcluded) {\n this._excludedMeshes[mesh.uniqueId] = {\n mesh: mesh,\n beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {\n mesh.getEngine().setStencilBuffer(false);\n }),\n afterRender: mesh.onAfterRenderObservable.add(function (mesh) {\n mesh.getEngine().setStencilBuffer(true);\n }),\n };\n }\n };\n /**\n * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.\n * @param mesh The mesh to highlight\n */\n HighlightLayer.prototype.removeExcludedMesh = function (mesh) {\n if (!this._excludedMeshes) {\n return;\n }\n var meshExcluded = this._excludedMeshes[mesh.uniqueId];\n if (meshExcluded) {\n if (meshExcluded.beforeRender) {\n mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);\n }\n if (meshExcluded.afterRender) {\n mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);\n }\n }\n this._excludedMeshes[mesh.uniqueId] = null;\n };\n /**\n * Determine if a given mesh will be highlighted by the current HighlightLayer\n * @param mesh mesh to test\n * @returns true if the mesh will be highlighted by the current HighlightLayer\n */\n HighlightLayer.prototype.hasMesh = function (mesh) {\n if (!this._meshes) {\n return false;\n }\n if (!_super.prototype.hasMesh.call(this, mesh)) {\n return false;\n }\n return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;\n };\n /**\n * Add a mesh in the highlight layer in order to make it glow with the chosen color.\n * @param mesh The mesh to highlight\n * @param color The color of the highlight\n * @param glowEmissiveOnly Extract the glow from the emissive texture\n */\n HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {\n var _this = this;\n if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }\n if (!this._meshes) {\n return;\n }\n var meshHighlight = this._meshes[mesh.uniqueId];\n if (meshHighlight) {\n meshHighlight.color = color;\n }\n else {\n this._meshes[mesh.uniqueId] = {\n mesh: mesh,\n color: color,\n // Lambda required for capture due to Observable this context\n observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {\n if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {\n _this._defaultStencilReference(mesh);\n }\n else {\n mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);\n }\n }),\n observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),\n glowEmissiveOnly: glowEmissiveOnly\n };\n mesh.onDisposeObservable.add(function () {\n _this._disposeMesh(mesh);\n });\n }\n this._shouldRender = true;\n };\n /**\n * Remove a mesh from the highlight layer in order to make it stop glowing.\n * @param mesh The mesh to highlight\n */\n HighlightLayer.prototype.removeMesh = function (mesh) {\n if (!this._meshes) {\n return;\n }\n var meshHighlight = this._meshes[mesh.uniqueId];\n if (meshHighlight) {\n if (meshHighlight.observerHighlight) {\n mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);\n }\n if (meshHighlight.observerDefault) {\n mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);\n }\n delete this._meshes[mesh.uniqueId];\n }\n this._shouldRender = false;\n for (var meshHighlightToCheck in this._meshes) {\n if (this._meshes[meshHighlightToCheck]) {\n this._shouldRender = true;\n break;\n }\n }\n };\n /**\n * Force the stencil to the normal expected value for none glowing parts\n */\n HighlightLayer.prototype._defaultStencilReference = function (mesh) {\n mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);\n };\n /**\n * Free any resources and references associated to a mesh.\n * Internal use\n * @param mesh The mesh to free.\n */\n HighlightLayer.prototype._disposeMesh = function (mesh) {\n this.removeMesh(mesh);\n this.removeExcludedMesh(mesh);\n };\n /**\n * Dispose the highlight layer and free resources.\n */\n HighlightLayer.prototype.dispose = function () {\n if (this._meshes) {\n // Clean mesh references \n for (var id in this._meshes) {\n var meshHighlight = this._meshes[id];\n if (meshHighlight && meshHighlight.mesh) {\n if (meshHighlight.observerHighlight) {\n meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);\n }\n if (meshHighlight.observerDefault) {\n meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);\n }\n }\n }\n this._meshes = null;\n }\n if (this._excludedMeshes) {\n for (var id in this._excludedMeshes) {\n var meshHighlight = this._excludedMeshes[id];\n if (meshHighlight) {\n if (meshHighlight.beforeRender) {\n meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);\n }\n if (meshHighlight.afterRender) {\n meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);\n }\n }\n }\n this._excludedMeshes = null;\n }\n _super.prototype.dispose.call(this);\n };\n /**\n * Gets the class name of the effect layer\n * @returns the string with the class name of the effect layer\n */\n HighlightLayer.prototype.getClassName = function () {\n return \"HighlightLayer\";\n };\n /**\n * Serializes this Highlight layer\n * @returns a serialized Highlight layer object\n */\n HighlightLayer.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.HighlightLayer\";\n // Highlighted meshes\n serializationObject.meshes = [];\n if (this._meshes) {\n for (var m in this._meshes) {\n var mesh = this._meshes[m];\n if (mesh) {\n serializationObject.meshes.push({\n glowEmissiveOnly: mesh.glowEmissiveOnly,\n color: mesh.color.asArray(),\n meshId: mesh.mesh.id\n });\n }\n }\n }\n // Excluded meshes\n serializationObject.excludedMeshes = [];\n if (this._excludedMeshes) {\n for (var e in this._excludedMeshes) {\n var excludedMesh = this._excludedMeshes[e];\n if (excludedMesh) {\n serializationObject.excludedMeshes.push(excludedMesh.mesh.id);\n }\n }\n }\n return serializationObject;\n };\n /**\n * Creates a Highlight layer from parsed Highlight layer data\n * @param parsedHightlightLayer defines the Highlight layer data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing the Highlight layer information\n * @returns a parsed Highlight layer\n */\n HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {\n var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);\n var index;\n // Excluded meshes\n for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {\n var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);\n if (mesh) {\n hl.addExcludedMesh(mesh);\n }\n }\n // Included meshes\n for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {\n var highlightedMesh = parsedHightlightLayer.meshes[index];\n var mesh = scene.getMeshByID(highlightedMesh.meshId);\n if (mesh) {\n hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);\n }\n }\n return hl;\n };\n /**\n * Effect Name of the highlight layer.\n */\n HighlightLayer.EffectName = \"HighlightLayer\";\n /**\n * The neutral color used during the preparation of the glow effect.\n * This is black by default as the blend operation is a blend operation.\n */\n HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);\n /**\n * Stencil value used for glowing meshes.\n */\n HighlightLayer.GlowingMeshStencilReference = 0x02;\n /**\n * Stencil value used for the other meshes in the scene.\n */\n HighlightLayer.NormalMeshStencilReference = 0x01;\n __decorate([\n BABYLON.serialize()\n ], HighlightLayer.prototype, \"innerGlow\", void 0);\n __decorate([\n BABYLON.serialize()\n ], HighlightLayer.prototype, \"outerGlow\", void 0);\n __decorate([\n BABYLON.serialize()\n ], HighlightLayer.prototype, \"blurHorizontalSize\", null);\n __decorate([\n BABYLON.serialize()\n ], HighlightLayer.prototype, \"blurVerticalSize\", null);\n __decorate([\n BABYLON.serialize(\"options\")\n ], HighlightLayer.prototype, \"_options\", void 0);\n return HighlightLayer;\n }(BABYLON.EffectLayer));\n BABYLON.HighlightLayer = HighlightLayer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.highlightLayer.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {\n for (var index = 0; index < this.effectLayers.length; index++) {\n if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {\n return this.effectLayers[index];\n }\n }\n return null;\n };\n /**\n * The glow layer Helps adding a glow effect around the emissive parts of a mesh.\n *\n * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove\n * glowy meshes to your scene.\n *\n * Documentation: https://doc.babylonjs.com/how_to/glow_layer\n */\n var GlowLayer = /** @class */ (function (_super) {\n __extends(GlowLayer, _super);\n /**\n * Instantiates a new glow Layer and references it to the scene.\n * @param name The name of the layer\n * @param scene The scene to use the layer in\n * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)\n */\n function GlowLayer(name, scene, options) {\n var _this = _super.call(this, name, scene) || this;\n _this._intensity = 1.0;\n _this._includedOnlyMeshes = [];\n _this._excludedMeshes = [];\n _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);\n // Adapt options\n _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);\n // Initialize the layer\n _this._init({\n alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,\n camera: _this._options.camera,\n mainTextureFixedSize: _this._options.mainTextureFixedSize,\n mainTextureRatio: _this._options.mainTextureRatio,\n renderingGroupId: _this._options.renderingGroupId\n });\n return _this;\n }\n Object.defineProperty(GlowLayer.prototype, \"blurKernelSize\", {\n /**\n * Gets the kernel size of the blur.\n */\n get: function () {\n return this._horizontalBlurPostprocess1.kernel;\n },\n /**\n * Sets the kernel size of the blur.\n */\n set: function (value) {\n this._horizontalBlurPostprocess1.kernel = value;\n this._verticalBlurPostprocess1.kernel = value;\n this._horizontalBlurPostprocess2.kernel = value;\n this._verticalBlurPostprocess2.kernel = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GlowLayer.prototype, \"intensity\", {\n /**\n * Gets the glow intensity.\n */\n get: function () {\n return this._intensity;\n },\n /**\n * Sets the glow intensity.\n */\n set: function (value) {\n this._intensity = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Get the effect name of the layer.\n * @return The effect name\n */\n GlowLayer.prototype.getEffectName = function () {\n return GlowLayer.EffectName;\n };\n /**\n * Create the merge effect. This is the shader use to blit the information back\n * to the main canvas at the end of the scene rendering.\n */\n GlowLayer.prototype._createMergeEffect = function () {\n // Effect\n return this._engine.createEffect(\"glowMapMerge\", [BABYLON.VertexBuffer.PositionKind], [\"offset\"], [\"textureSampler\", \"textureSampler2\"], \"#define EMISSIVE \\n\");\n };\n /**\n * Creates the render target textures and post processes used in the glow layer.\n */\n GlowLayer.prototype._createTextureAndPostProcesses = function () {\n var _this = this;\n var blurTextureWidth = this._mainTextureDesiredSize.width;\n var blurTextureHeight = this._mainTextureDesiredSize.height;\n blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;\n blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;\n var textureType = 0;\n if (this._engine.getCaps().textureHalfFloatRender) {\n textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else {\n textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n this._blurTexture1 = new BABYLON.RenderTargetTexture(\"GlowLayerBlurRTT\", {\n width: blurTextureWidth,\n height: blurTextureHeight\n }, this._scene, false, true, textureType);\n this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n this._blurTexture1.renderParticles = false;\n this._blurTexture1.ignoreCameraViewport = true;\n var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);\n var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);\n this._blurTexture2 = new BABYLON.RenderTargetTexture(\"GlowLayerBlurRTT2\", {\n width: blurTextureWidth2,\n height: blurTextureHeight2\n }, this._scene, false, true, textureType);\n this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n this._blurTexture2.renderParticles = false;\n this._blurTexture2.ignoreCameraViewport = true;\n this._textures = [this._blurTexture1, this._blurTexture2];\n this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess(\"GlowLayerHBP1\", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {\n width: blurTextureWidth,\n height: blurTextureHeight\n }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess1.width = blurTextureWidth;\n this._horizontalBlurPostprocess1.height = blurTextureHeight;\n this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {\n effect.setTexture(\"textureSampler\", _this._mainTexture);\n });\n this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess(\"GlowLayerVBP1\", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {\n width: blurTextureWidth,\n height: blurTextureHeight\n }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess(\"GlowLayerHBP2\", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {\n width: blurTextureWidth2,\n height: blurTextureHeight2\n }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess2.width = blurTextureWidth2;\n this._horizontalBlurPostprocess2.height = blurTextureHeight2;\n this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {\n effect.setTexture(\"textureSampler\", _this._blurTexture1);\n });\n this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess(\"GlowLayerVBP2\", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {\n width: blurTextureWidth2,\n height: blurTextureHeight2\n }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];\n this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];\n this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];\n this._mainTexture.samples = this._options.mainTextureSamples;\n this._mainTexture.onAfterUnbindObservable.add(function () {\n var internalTexture = _this._blurTexture1.getInternalTexture();\n if (internalTexture) {\n _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);\n internalTexture = _this._blurTexture2.getInternalTexture();\n if (internalTexture) {\n _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);\n }\n }\n });\n // Prevent autoClear.\n this._postProcesses.map(function (pp) { pp.autoClear = false; });\n };\n /**\n * Checks for the readiness of the element composing the layer.\n * @param subMesh the mesh to check for\n * @param useInstances specify wether or not to use instances to render the mesh\n * @param emissiveTexture the associated emissive texture used to generate the glow\n * @return true if ready otherwise, false\n */\n GlowLayer.prototype.isReady = function (subMesh, useInstances) {\n var material = subMesh.getMaterial();\n var mesh = subMesh.getRenderingMesh();\n if (!material || !mesh) {\n return false;\n }\n var emissiveTexture = material.emissiveTexture;\n return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);\n };\n /**\n * Returns wether or nood the layer needs stencil enabled during the mesh rendering.\n */\n GlowLayer.prototype.needStencil = function () {\n return false;\n };\n /**\n * Implementation specific of rendering the generating effect on the main canvas.\n * @param effect The effect used to render through\n */\n GlowLayer.prototype._internalRender = function (effect) {\n // Texture\n effect.setTexture(\"textureSampler\", this._blurTexture1);\n effect.setTexture(\"textureSampler2\", this._blurTexture2);\n effect.setFloat(\"offset\", this._intensity);\n // Cache\n var engine = this._engine;\n var previousStencilBuffer = engine.getStencilBuffer();\n // Draw order\n engine.setStencilBuffer(false);\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n // Draw order\n engine.setStencilBuffer(previousStencilBuffer);\n };\n /**\n * Sets the required values for both the emissive texture and and the main color.\n */\n GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {\n var textureLevel = 1.0;\n if (this.customEmissiveTextureSelector) {\n this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);\n }\n else {\n if (material) {\n this._emissiveTextureAndColor.texture = material.emissiveTexture;\n if (this._emissiveTextureAndColor.texture) {\n textureLevel = this._emissiveTextureAndColor.texture.level;\n }\n }\n else {\n this._emissiveTextureAndColor.texture = null;\n }\n }\n if (this.customEmissiveColorSelector) {\n this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);\n }\n else {\n if (material.emissiveColor) {\n this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);\n }\n else {\n this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);\n }\n }\n };\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n GlowLayer.prototype._shouldRenderMesh = function (mesh) {\n return this.hasMesh(mesh);\n };\n /**\n * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.\n * @param mesh The mesh to exclude from the glow layer\n */\n GlowLayer.prototype.addExcludedMesh = function (mesh) {\n if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {\n this._excludedMeshes.push(mesh.uniqueId);\n }\n };\n /**\n * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.\n * @param mesh The mesh to remove\n */\n GlowLayer.prototype.removeExcludedMesh = function (mesh) {\n var index = this._excludedMeshes.indexOf(mesh.uniqueId);\n if (index !== -1) {\n this._excludedMeshes.splice(index, 1);\n }\n };\n /**\n * Add a mesh in the inclusion list to impact or being impacted by the glow layer.\n * @param mesh The mesh to include in the glow layer\n */\n GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {\n if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {\n this._includedOnlyMeshes.push(mesh.uniqueId);\n }\n };\n /**\n * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.\n * @param mesh The mesh to remove\n */\n GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {\n var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);\n if (index !== -1) {\n this._includedOnlyMeshes.splice(index, 1);\n }\n };\n /**\n * Determine if a given mesh will be used in the glow layer\n * @param mesh The mesh to test\n * @returns true if the mesh will be highlighted by the current glow layer\n */\n GlowLayer.prototype.hasMesh = function (mesh) {\n if (!_super.prototype.hasMesh.call(this, mesh)) {\n return false;\n }\n // Included Mesh\n if (this._includedOnlyMeshes.length) {\n return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;\n }\n ;\n // Excluded Mesh\n if (this._excludedMeshes.length) {\n return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;\n }\n ;\n return true;\n };\n /**\n * Free any resources and references associated to a mesh.\n * Internal use\n * @param mesh The mesh to free.\n */\n GlowLayer.prototype._disposeMesh = function (mesh) {\n this.removeIncludedOnlyMesh(mesh);\n this.removeExcludedMesh(mesh);\n };\n /**\n * Gets the class name of the effect layer\n * @returns the string with the class name of the effect layer\n */\n GlowLayer.prototype.getClassName = function () {\n return \"GlowLayer\";\n };\n /**\n * Serializes this glow layer\n * @returns a serialized glow layer object\n */\n GlowLayer.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.GlowLayer\";\n var index;\n // Included meshes\n serializationObject.includedMeshes = [];\n if (this._includedOnlyMeshes.length) {\n for (index = 0; index < this._includedOnlyMeshes.length; index++) {\n var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);\n if (mesh) {\n serializationObject.includedMeshes.push(mesh.id);\n }\n }\n }\n // Excluded meshes\n serializationObject.excludedMeshes = [];\n if (this._excludedMeshes.length) {\n for (index = 0; index < this._excludedMeshes.length; index++) {\n var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);\n if (mesh) {\n serializationObject.excludedMeshes.push(mesh.id);\n }\n }\n }\n return serializationObject;\n };\n /**\n * Creates a Glow Layer from parsed glow layer data\n * @param parsedGlowLayer defines glow layer data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing the glow layer information\n * @returns a parsed Glow Layer\n */\n GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {\n var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);\n var index;\n // Excluded meshes\n for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {\n var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);\n if (mesh) {\n gl.addExcludedMesh(mesh);\n }\n }\n // Included meshes\n for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {\n var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);\n if (mesh) {\n gl.addIncludedOnlyMesh(mesh);\n }\n }\n return gl;\n };\n /**\n * Effect Name of the layer.\n */\n GlowLayer.EffectName = \"GlowLayer\";\n /**\n * The default blur kernel size used for the glow.\n */\n GlowLayer.DefaultBlurKernelSize = 32;\n /**\n * The default texture size ratio used for the glow.\n */\n GlowLayer.DefaultTextureRatio = 0.5;\n __decorate([\n BABYLON.serialize()\n ], GlowLayer.prototype, \"blurKernelSize\", null);\n __decorate([\n BABYLON.serialize()\n ], GlowLayer.prototype, \"intensity\", null);\n __decorate([\n BABYLON.serialize(\"options\")\n ], GlowLayer.prototype, \"_options\", void 0);\n return GlowLayer;\n }(BABYLON.EffectLayer));\n BABYLON.GlowLayer = GlowLayer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glowLayer.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the list of states available for a task inside a {BABYLON.AssetsManager}\n */\n var AssetTaskState;\n (function (AssetTaskState) {\n /**\n * Initialization\n */\n AssetTaskState[AssetTaskState[\"INIT\"] = 0] = \"INIT\";\n /**\n * Running\n */\n AssetTaskState[AssetTaskState[\"RUNNING\"] = 1] = \"RUNNING\";\n /**\n * Done\n */\n AssetTaskState[AssetTaskState[\"DONE\"] = 2] = \"DONE\";\n /**\n * Error\n */\n AssetTaskState[AssetTaskState[\"ERROR\"] = 3] = \"ERROR\";\n })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));\n /**\n * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene\n */\n var AbstractAssetTask = /** @class */ (function () {\n /**\n * Creates a new {BABYLON.AssetsManager}\n * @param name defines the name of the task\n */\n function AbstractAssetTask(\n /**\n * Task name\n */ name) {\n this.name = name;\n this._isCompleted = false;\n this._taskState = AssetTaskState.INIT;\n }\n Object.defineProperty(AbstractAssetTask.prototype, \"isCompleted\", {\n /**\n * Get if the task is completed\n */\n get: function () {\n return this._isCompleted;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractAssetTask.prototype, \"taskState\", {\n /**\n * Gets the current state of the task\n */\n get: function () {\n return this._taskState;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AbstractAssetTask.prototype, \"errorObject\", {\n /**\n * Gets the current error object (if task is in error)\n */\n get: function () {\n return this._errorObject;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Internal only\n * @hidden\n */\n AbstractAssetTask.prototype._setErrorObject = function (message, exception) {\n if (this._errorObject) {\n return;\n }\n this._errorObject = {\n message: message,\n exception: exception\n };\n };\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {\n var _this = this;\n this._taskState = AssetTaskState.RUNNING;\n this.runTask(scene, function () {\n _this.onDoneCallback(onSuccess, onError);\n }, function (msg, exception) {\n _this.onErrorCallback(onError, msg, exception);\n });\n };\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n throw new Error(\"runTask is not implemented\");\n };\n /**\n * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.\n * This can be used with failed tasks that have the reason for failure fixed.\n */\n AbstractAssetTask.prototype.reset = function () {\n this._taskState = AssetTaskState.INIT;\n };\n AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {\n this._taskState = AssetTaskState.ERROR;\n this._errorObject = {\n message: message,\n exception: exception\n };\n if (this.onError) {\n this.onError(this, message, exception);\n }\n onError();\n };\n AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {\n try {\n this._taskState = AssetTaskState.DONE;\n this._isCompleted = true;\n if (this.onSuccess) {\n this.onSuccess(this);\n }\n onSuccess();\n }\n catch (e) {\n this.onErrorCallback(onError, \"Task is done, error executing success callback(s)\", e);\n }\n };\n return AbstractAssetTask;\n }());\n BABYLON.AbstractAssetTask = AbstractAssetTask;\n /**\n * Class used to share progress information about assets loading\n */\n var AssetsProgressEvent = /** @class */ (function () {\n /**\n * Creates a {BABYLON.AssetsProgressEvent}\n * @param remainingCount defines the number of remaining tasks to process\n * @param totalCount defines the total number of tasks\n * @param task defines the task that was just processed\n */\n function AssetsProgressEvent(remainingCount, totalCount, task) {\n this.remainingCount = remainingCount;\n this.totalCount = totalCount;\n this.task = task;\n }\n return AssetsProgressEvent;\n }());\n BABYLON.AssetsProgressEvent = AssetsProgressEvent;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load meshes\n */\n var MeshAssetTask = /** @class */ (function (_super) {\n __extends(MeshAssetTask, _super);\n /**\n * Creates a new {BABYLON.MeshAssetTask}\n * @param name defines the name of the task\n * @param meshesNames defines the list of mesh's names you want to load\n * @param rootUrl defines the root url to use as a base to load your meshes and associated resources\n * @param sceneFilename defines the filename of the scene to load from\n */\n function MeshAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the list of mesh's names you want to load\n */\n meshesNames, \n /**\n * Defines the root url to use as a base to load your meshes and associated resources\n */\n rootUrl, \n /**\n * Defines the filename of the scene to load from\n */\n sceneFilename) {\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.meshesNames = meshesNames;\n _this.rootUrl = rootUrl;\n _this.sceneFilename = sceneFilename;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n var _this = this;\n BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {\n _this.loadedMeshes = meshes;\n _this.loadedParticleSystems = particleSystems;\n _this.loadedSkeletons = skeletons;\n onSuccess();\n }, null, function (scene, message, exception) {\n onError(message, exception);\n });\n };\n return MeshAssetTask;\n }(AbstractAssetTask));\n BABYLON.MeshAssetTask = MeshAssetTask;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load text content\n */\n var TextFileAssetTask = /** @class */ (function (_super) {\n __extends(TextFileAssetTask, _super);\n /**\n * Creates a new TextFileAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n */\n function TextFileAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url) {\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.url = url;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n var _this = this;\n scene._loadFile(this.url, function (data) {\n _this.text = data;\n onSuccess();\n }, undefined, false, false, function (request, exception) {\n if (request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n });\n };\n return TextFileAssetTask;\n }(AbstractAssetTask));\n BABYLON.TextFileAssetTask = TextFileAssetTask;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load binary data\n */\n var BinaryFileAssetTask = /** @class */ (function (_super) {\n __extends(BinaryFileAssetTask, _super);\n /**\n * Creates a new BinaryFileAssetTask object\n * @param name defines the name of the new task\n * @param url defines the location of the file to load\n */\n function BinaryFileAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url) {\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.url = url;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n var _this = this;\n scene._loadFile(this.url, function (data) {\n _this.data = data;\n onSuccess();\n }, undefined, true, true, function (request, exception) {\n if (request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n });\n };\n return BinaryFileAssetTask;\n }(AbstractAssetTask));\n BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load images\n */\n var ImageAssetTask = /** @class */ (function (_super) {\n __extends(ImageAssetTask, _super);\n /**\n * Creates a new ImageAssetTask\n * @param name defines the name of the task\n * @param url defines the location of the image to load\n */\n function ImageAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the image to load\n */\n url) {\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.url = url;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n var _this = this;\n var img = new Image();\n BABYLON.Tools.SetCorsBehavior(this.url, img);\n img.onload = function () {\n _this.image = img;\n onSuccess();\n };\n img.onerror = function (err) {\n onError(\"Error loading image\", err);\n };\n img.src = this.url;\n };\n return ImageAssetTask;\n }(AbstractAssetTask));\n BABYLON.ImageAssetTask = ImageAssetTask;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load 2D textures\n */\n var TextureAssetTask = /** @class */ (function (_super) {\n __extends(TextureAssetTask, _super);\n /**\n * Creates a new TextureAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n * @param noMipmap defines if mipmap should not be generated (default is false)\n * @param invertY defines if texture must be inverted on Y axis (default is false)\n * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)\n */\n function TextureAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url, \n /**\n * Defines if mipmap should not be generated (default is false)\n */\n noMipmap, \n /**\n * Defines if texture must be inverted on Y axis (default is false)\n */\n invertY, \n /**\n * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)\n */\n samplingMode) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.url = url;\n _this.noMipmap = noMipmap;\n _this.invertY = invertY;\n _this.samplingMode = samplingMode;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n var onload = function () {\n onSuccess();\n };\n var onerror = function (message, exception) {\n onError(message, exception);\n };\n this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);\n };\n return TextureAssetTask;\n }(AbstractAssetTask));\n BABYLON.TextureAssetTask = TextureAssetTask;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load cube textures\n */\n var CubeTextureAssetTask = /** @class */ (function (_super) {\n __extends(CubeTextureAssetTask, _super);\n /**\n * Creates a new CubeTextureAssetTask\n * @param name defines the name of the task\n * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)\n * @param extensions defines the extensions to use to load files ([\"_px\", \"_py\", \"_pz\", \"_nx\", \"_ny\", \"_nz\"] by default)\n * @param noMipmap defines if mipmaps should not be generated (default is false)\n * @param files defines the explicit list of files (undefined by default)\n */\n function CubeTextureAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)\n */\n url, \n /**\n * Defines the extensions to use to load files ([\"_px\", \"_py\", \"_pz\", \"_nx\", \"_ny\", \"_nz\"] by default)\n */\n extensions, \n /**\n * Defines if mipmaps should not be generated (default is false)\n */\n noMipmap, \n /**\n * Defines the explicit list of files (undefined by default)\n */\n files) {\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.url = url;\n _this.extensions = extensions;\n _this.noMipmap = noMipmap;\n _this.files = files;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {\n var onload = function () {\n onSuccess();\n };\n var onerror = function (message, exception) {\n onError(message, exception);\n };\n this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);\n };\n return CubeTextureAssetTask;\n }(AbstractAssetTask));\n BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;\n /**\n * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures\n */\n var HDRCubeTextureAssetTask = /** @class */ (function (_super) {\n __extends(HDRCubeTextureAssetTask, _super);\n /**\n * Creates a new HDRCubeTextureAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.\n * @param noMipmap defines if mipmaps should not be generated (default is false)\n * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)\n * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)\n * @param reserved Internal use only\n */\n function HDRCubeTextureAssetTask(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url, \n /**\n * Defines the desired size (the more it increases the longer the generation will be)\n */\n size, \n /**\n * Defines if mipmaps should not be generated (default is false)\n */\n noMipmap, \n /**\n * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)\n */\n generateHarmonics, \n /**\n * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)\n */\n gammaSpace, \n /**\n * Internal Use Only\n */\n reserved) {\n if (noMipmap === void 0) { noMipmap = false; }\n if (generateHarmonics === void 0) { generateHarmonics = true; }\n if (gammaSpace === void 0) { gammaSpace = false; }\n if (reserved === void 0) { reserved = false; }\n var _this = _super.call(this, name) || this;\n _this.name = name;\n _this.url = url;\n _this.size = size;\n _this.noMipmap = noMipmap;\n _this.generateHarmonics = generateHarmonics;\n _this.gammaSpace = gammaSpace;\n _this.reserved = reserved;\n return _this;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {\n var onload = function () {\n onSuccess();\n };\n var onerror = function (message, exception) {\n onError(message, exception);\n };\n this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);\n };\n return HDRCubeTextureAssetTask;\n }(AbstractAssetTask));\n BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;\n /**\n * This class can be used to easily import assets into a scene\n * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager\n */\n var AssetsManager = /** @class */ (function () {\n /**\n * Creates a new AssetsManager\n * @param scene defines the scene to work on\n */\n function AssetsManager(scene) {\n this._isLoading = false;\n this._tasks = new Array();\n this._waitingTasksCount = 0;\n this._totalTasksCount = 0;\n /**\n * Observable called when all tasks are processed\n */\n this.onTaskSuccessObservable = new BABYLON.Observable();\n /**\n * Observable called when a task had an error\n */\n this.onTaskErrorObservable = new BABYLON.Observable();\n /**\n * Observable called when a task is successful\n */\n this.onTasksDoneObservable = new BABYLON.Observable();\n /**\n * Observable called when a task is done (whatever the result is)\n */\n this.onProgressObservable = new BABYLON.Observable();\n /**\n * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen\n * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen\n */\n this.useDefaultLoadingScreen = true;\n this._scene = scene;\n }\n /**\n * Add a {BABYLON.MeshAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param meshesNames defines the name of meshes to load\n * @param rootUrl defines the root url to use to locate files\n * @param sceneFilename defines the filename of the scene file\n * @returns a new {BABYLON.MeshAssetTask} object\n */\n AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {\n var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);\n this._tasks.push(task);\n return task;\n };\n /**\n * Add a {BABYLON.TextFileAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @returns a new {BABYLON.TextFileAssetTask} object\n */\n AssetsManager.prototype.addTextFileTask = function (taskName, url) {\n var task = new TextFileAssetTask(taskName, url);\n this._tasks.push(task);\n return task;\n };\n /**\n * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @returns a new {BABYLON.BinaryFileAssetTask} object\n */\n AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {\n var task = new BinaryFileAssetTask(taskName, url);\n this._tasks.push(task);\n return task;\n };\n /**\n * Add a {BABYLON.ImageAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @returns a new {BABYLON.ImageAssetTask} object\n */\n AssetsManager.prototype.addImageTask = function (taskName, url) {\n var task = new ImageAssetTask(taskName, url);\n this._tasks.push(task);\n return task;\n };\n /**\n * Add a {BABYLON.TextureAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)\n * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)\n * @returns a new {BABYLON.TextureAssetTask} object\n */\n AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);\n this._tasks.push(task);\n return task;\n };\n /**\n * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param extensions defines the extension to use to load the cube map (can be null)\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param files defines the list of files to load (can be null)\n * @returns a new {BABYLON.CubeTextureAssetTask} object\n */\n AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {\n var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);\n this._tasks.push(task);\n return task;\n };\n /**\n *\n * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param size defines the size you want for the cubemap (can be null)\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param generateHarmonics defines if you want to automatically generate (true by default)\n * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)\n * @param reserved Internal use only\n * @returns a new {BABYLON.HDRCubeTextureAssetTask} object\n */\n AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {\n if (noMipmap === void 0) { noMipmap = false; }\n if (generateHarmonics === void 0) { generateHarmonics = true; }\n if (gammaSpace === void 0) { gammaSpace = false; }\n if (reserved === void 0) { reserved = false; }\n var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);\n this._tasks.push(task);\n return task;\n };\n /**\n * Remove a task from the assets manager.\n * @param task the task to remove\n */\n AssetsManager.prototype.removeTask = function (task) {\n var index = this._tasks.indexOf(task);\n if (index > -1) {\n this._tasks.splice(index, 1);\n }\n };\n AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {\n this._waitingTasksCount--;\n try {\n if (this.onProgress) {\n this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);\n }\n this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));\n }\n catch (e) {\n BABYLON.Tools.Error(\"Error running progress callbacks.\");\n console.log(e);\n }\n if (this._waitingTasksCount === 0) {\n try {\n if (this.onFinish) {\n this.onFinish(this._tasks);\n }\n // Let's remove successfull tasks\n var currentTasks = this._tasks.slice();\n for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {\n var task = currentTasks_1[_i];\n if (task.taskState === AssetTaskState.DONE) {\n var index = this._tasks.indexOf(task);\n if (index > -1) {\n this._tasks.splice(index, 1);\n }\n }\n }\n this.onTasksDoneObservable.notifyObservers(this._tasks);\n }\n catch (e) {\n BABYLON.Tools.Error(\"Error running tasks-done callbacks.\");\n console.log(e);\n }\n this._isLoading = false;\n this._scene.getEngine().hideLoadingUI();\n }\n };\n AssetsManager.prototype._runTask = function (task) {\n var _this = this;\n var done = function () {\n try {\n if (_this.onTaskSuccess) {\n _this.onTaskSuccess(task);\n }\n _this.onTaskSuccessObservable.notifyObservers(task);\n _this._decreaseWaitingTasksCount(task);\n }\n catch (e) {\n error(\"Error executing task success callbacks\", e);\n }\n };\n var error = function (message, exception) {\n task._setErrorObject(message, exception);\n if (_this.onTaskError) {\n _this.onTaskError(task);\n }\n _this.onTaskErrorObservable.notifyObservers(task);\n _this._decreaseWaitingTasksCount(task);\n };\n task.run(this._scene, done, error);\n };\n /**\n * Reset the {BABYLON.AssetsManager} and remove all tasks\n * @return the current instance of the {BABYLON.AssetsManager}\n */\n AssetsManager.prototype.reset = function () {\n this._isLoading = false;\n this._tasks = new Array();\n return this;\n };\n /**\n * Start the loading process\n * @return the current instance of the {BABYLON.AssetsManager}\n */\n AssetsManager.prototype.load = function () {\n if (this._isLoading) {\n return this;\n }\n this._isLoading = true;\n this._waitingTasksCount = this._tasks.length;\n this._totalTasksCount = this._tasks.length;\n if (this._waitingTasksCount === 0) {\n this._isLoading = false;\n if (this.onFinish) {\n this.onFinish(this._tasks);\n }\n this.onTasksDoneObservable.notifyObservers(this._tasks);\n return this;\n }\n if (this.useDefaultLoadingScreen) {\n this._scene.getEngine().displayLoadingUI();\n }\n for (var index = 0; index < this._tasks.length; index++) {\n var task = this._tasks[index];\n if (task.taskState === AssetTaskState.INIT) {\n this._runTask(task);\n }\n }\n return this;\n };\n return AssetsManager;\n }());\n BABYLON.AssetsManager = AssetsManager;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.assetsManager.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var serializedGeometries = [];\n var serializeGeometry = function (geometry, serializationGeometries) {\n if (serializedGeometries[geometry.id]) {\n return;\n }\n if (geometry.doNotSerialize) {\n return;\n }\n if (geometry instanceof BABYLON.BoxGeometry) {\n serializationGeometries.boxes.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON.SphereGeometry) {\n serializationGeometries.spheres.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON.CylinderGeometry) {\n serializationGeometries.cylinders.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON.TorusGeometry) {\n serializationGeometries.toruses.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON.GroundGeometry) {\n serializationGeometries.grounds.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON.Plane) {\n serializationGeometries.planes.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON.TorusKnotGeometry) {\n serializationGeometries.torusKnots.push(geometry.serialize());\n }\n else if (geometry instanceof BABYLON._PrimitiveGeometry) {\n throw new Error(\"Unknown primitive type\");\n }\n else {\n serializationGeometries.vertexData.push(geometry.serializeVerticeData());\n }\n serializedGeometries[geometry.id] = true;\n };\n var serializeMesh = function (mesh, serializationScene) {\n var serializationObject = {};\n // Geometry \n var geometry = mesh._geometry;\n if (geometry) {\n if (!mesh.getScene().getGeometryByID(geometry.id)) {\n // Geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry\n serializeGeometry(geometry, serializationScene.geometries);\n }\n }\n // Custom\n if (mesh.serialize) {\n mesh.serialize(serializationObject);\n }\n return serializationObject;\n };\n var finalizeSingleMesh = function (mesh, serializationObject) {\n //only works if the mesh is already loaded\n if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {\n //serialize material\n if (mesh.material) {\n if (mesh.material instanceof BABYLON.MultiMaterial) {\n serializationObject.multiMaterials = serializationObject.multiMaterials || [];\n serializationObject.materials = serializationObject.materials || [];\n if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {\n serializationObject.multiMaterials.push(mesh.material.serialize());\n var _loop_1 = function (submaterial) {\n if (submaterial) {\n if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {\n serializationObject.materials.push(submaterial.serialize());\n }\n }\n };\n for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {\n var submaterial = _a[_i];\n _loop_1(submaterial);\n }\n }\n }\n else {\n serializationObject.materials = serializationObject.materials || [];\n if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {\n serializationObject.materials.push(mesh.material.serialize());\n }\n }\n }\n //serialize geometry\n var geometry = mesh._geometry;\n if (geometry) {\n if (!serializationObject.geometries) {\n serializationObject.geometries = {};\n serializationObject.geometries.boxes = [];\n serializationObject.geometries.spheres = [];\n serializationObject.geometries.cylinders = [];\n serializationObject.geometries.toruses = [];\n serializationObject.geometries.grounds = [];\n serializationObject.geometries.planes = [];\n serializationObject.geometries.torusKnots = [];\n serializationObject.geometries.vertexData = [];\n }\n serializeGeometry(geometry, serializationObject.geometries);\n }\n // Skeletons\n if (mesh.skeleton) {\n serializationObject.skeletons = serializationObject.skeletons || [];\n serializationObject.skeletons.push(mesh.skeleton.serialize());\n }\n //serialize the actual mesh\n serializationObject.meshes = serializationObject.meshes || [];\n serializationObject.meshes.push(serializeMesh(mesh, serializationObject));\n }\n };\n var SceneSerializer = /** @class */ (function () {\n function SceneSerializer() {\n }\n SceneSerializer.ClearCache = function () {\n serializedGeometries = [];\n };\n SceneSerializer.Serialize = function (scene) {\n var serializationObject = {};\n SceneSerializer.ClearCache();\n // Scene\n serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;\n serializationObject.autoClear = scene.autoClear;\n serializationObject.clearColor = scene.clearColor.asArray();\n serializationObject.ambientColor = scene.ambientColor.asArray();\n serializationObject.gravity = scene.gravity.asArray();\n serializationObject.collisionsEnabled = scene.collisionsEnabled;\n serializationObject.workerCollisions = scene.workerCollisions;\n // Fog\n if (scene.fogMode && scene.fogMode !== 0) {\n serializationObject.fogMode = scene.fogMode;\n serializationObject.fogColor = scene.fogColor.asArray();\n serializationObject.fogStart = scene.fogStart;\n serializationObject.fogEnd = scene.fogEnd;\n serializationObject.fogDensity = scene.fogDensity;\n }\n //Physics\n if (scene.isPhysicsEnabled()) {\n var physicEngine = scene.getPhysicsEngine();\n if (physicEngine) {\n serializationObject.physicsEnabled = true;\n serializationObject.physicsGravity = physicEngine.gravity.asArray();\n serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();\n }\n }\n // Metadata\n if (scene.metadata) {\n serializationObject.metadata = scene.metadata;\n }\n // Morph targets\n serializationObject.morphTargetManagers = [];\n for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {\n var abstractMesh = _a[_i];\n var manager = abstractMesh.morphTargetManager;\n if (manager) {\n serializationObject.morphTargetManagers.push(manager.serialize());\n }\n }\n // Lights\n serializationObject.lights = [];\n var index;\n var light;\n for (index = 0; index < scene.lights.length; index++) {\n light = scene.lights[index];\n if (!light.doNotSerialize) {\n serializationObject.lights.push(light.serialize());\n }\n }\n // Cameras\n serializationObject.cameras = [];\n for (index = 0; index < scene.cameras.length; index++) {\n var camera = scene.cameras[index];\n if (!camera.doNotSerialize) {\n serializationObject.cameras.push(camera.serialize());\n }\n }\n if (scene.activeCamera) {\n serializationObject.activeCameraID = scene.activeCamera.id;\n }\n // Animations\n BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);\n // Materials\n serializationObject.materials = [];\n serializationObject.multiMaterials = [];\n var material;\n for (index = 0; index < scene.materials.length; index++) {\n material = scene.materials[index];\n if (!material.doNotSerialize) {\n serializationObject.materials.push(material.serialize());\n }\n }\n // MultiMaterials\n serializationObject.multiMaterials = [];\n for (index = 0; index < scene.multiMaterials.length; index++) {\n var multiMaterial = scene.multiMaterials[index];\n serializationObject.multiMaterials.push(multiMaterial.serialize());\n }\n // Environment texture\n if (scene.environmentTexture) {\n serializationObject.environmentTexture = scene.environmentTexture.name;\n }\n // Skeletons\n serializationObject.skeletons = [];\n for (index = 0; index < scene.skeletons.length; index++) {\n var skeleton = scene.skeletons[index];\n if (!skeleton.doNotSerialize) {\n serializationObject.skeletons.push(skeleton.serialize());\n }\n }\n // Transform nodes\n serializationObject.transformNodes = [];\n for (index = 0; index < scene.transformNodes.length; index++) {\n serializationObject.transformNodes.push(scene.transformNodes[index].serialize());\n }\n // Geometries\n serializationObject.geometries = {};\n serializationObject.geometries.boxes = [];\n serializationObject.geometries.spheres = [];\n serializationObject.geometries.cylinders = [];\n serializationObject.geometries.toruses = [];\n serializationObject.geometries.grounds = [];\n serializationObject.geometries.planes = [];\n serializationObject.geometries.torusKnots = [];\n serializationObject.geometries.vertexData = [];\n serializedGeometries = [];\n var geometries = scene.getGeometries();\n for (index = 0; index < geometries.length; index++) {\n var geometry = geometries[index];\n if (geometry.isReady()) {\n serializeGeometry(geometry, serializationObject.geometries);\n }\n }\n // Meshes\n serializationObject.meshes = [];\n for (index = 0; index < scene.meshes.length; index++) {\n var abstractMesh = scene.meshes[index];\n if (abstractMesh instanceof BABYLON.Mesh) {\n var mesh = abstractMesh;\n if (!mesh.doNotSerialize) {\n if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {\n serializationObject.meshes.push(serializeMesh(mesh, serializationObject));\n }\n }\n }\n }\n // Particles Systems\n serializationObject.particleSystems = [];\n for (index = 0; index < scene.particleSystems.length; index++) {\n serializationObject.particleSystems.push(scene.particleSystems[index].serialize());\n }\n // Shadows\n serializationObject.shadowGenerators = [];\n for (index = 0; index < scene.lights.length; index++) {\n light = scene.lights[index];\n var shadowGenerator = light.getShadowGenerator();\n if (shadowGenerator) {\n serializationObject.shadowGenerators.push(shadowGenerator.serialize());\n }\n }\n // Action Manager\n if (scene.actionManager) {\n serializationObject.actions = scene.actionManager.serialize(\"scene\");\n }\n // Audio\n serializationObject.sounds = [];\n for (index = 0; index < scene.soundTracks.length; index++) {\n var soundtrack = scene.soundTracks[index];\n for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {\n serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());\n }\n }\n // Components\n for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {\n var component = _c[_b];\n component.serialize(serializationObject);\n }\n return serializationObject;\n };\n SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {\n if (withParents === void 0) { withParents = false; }\n if (withChildren === void 0) { withChildren = false; }\n var serializationObject = {};\n SceneSerializer.ClearCache();\n toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];\n if (withParents || withChildren) {\n //deliberate for loop! not for each, appended should be processed as well.\n for (var i = 0; i < toSerialize.length; ++i) {\n if (withChildren) {\n toSerialize[i].getDescendants().forEach(function (node) {\n if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {\n toSerialize.push(node);\n }\n });\n }\n //make sure the array doesn't contain the object already\n if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {\n toSerialize.push(toSerialize[i].parent);\n }\n }\n }\n toSerialize.forEach(function (mesh) {\n finalizeSingleMesh(mesh, serializationObject);\n });\n return serializationObject;\n };\n return SceneSerializer;\n }());\n BABYLON.SceneSerializer = SceneSerializer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sceneSerializer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var ReflectionProbe = /** @class */ (function () {\n function ReflectionProbe(name, size, scene, generateMipMaps) {\n if (generateMipMaps === void 0) { generateMipMaps = true; }\n var _this = this;\n this.name = name;\n this._viewMatrix = BABYLON.Matrix.Identity();\n this._target = BABYLON.Vector3.Zero();\n this._add = BABYLON.Vector3.Zero();\n this._invertYAxis = false;\n this.position = BABYLON.Vector3.Zero();\n this._scene = scene;\n this._scene.reflectionProbes.push(this);\n this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);\n this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {\n switch (faceIndex) {\n case 0:\n _this._add.copyFromFloats(1, 0, 0);\n break;\n case 1:\n _this._add.copyFromFloats(-1, 0, 0);\n break;\n case 2:\n _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);\n break;\n case 3:\n _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);\n break;\n case 4:\n _this._add.copyFromFloats(0, 0, 1);\n break;\n case 5:\n _this._add.copyFromFloats(0, 0, -1);\n break;\n }\n if (_this._attachedMesh) {\n _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());\n }\n _this.position.addToRef(_this._add, _this._target);\n BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);\n scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);\n scene._forcedViewPosition = _this.position;\n });\n this._renderTargetTexture.onAfterUnbindObservable.add(function () {\n scene._forcedViewPosition = null;\n scene.updateTransformMatrix(true);\n });\n if (scene.activeCamera) {\n this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);\n }\n }\n Object.defineProperty(ReflectionProbe.prototype, \"samples\", {\n get: function () {\n return this._renderTargetTexture.samples;\n },\n set: function (value) {\n this._renderTargetTexture.samples = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ReflectionProbe.prototype, \"refreshRate\", {\n get: function () {\n return this._renderTargetTexture.refreshRate;\n },\n set: function (value) {\n this._renderTargetTexture.refreshRate = value;\n },\n enumerable: true,\n configurable: true\n });\n ReflectionProbe.prototype.getScene = function () {\n return this._scene;\n };\n Object.defineProperty(ReflectionProbe.prototype, \"cubeTexture\", {\n get: function () {\n return this._renderTargetTexture;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ReflectionProbe.prototype, \"renderList\", {\n get: function () {\n return this._renderTargetTexture.renderList;\n },\n enumerable: true,\n configurable: true\n });\n ReflectionProbe.prototype.attachToMesh = function (mesh) {\n this._attachedMesh = mesh;\n };\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n */\n ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {\n this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);\n };\n ReflectionProbe.prototype.dispose = function () {\n var index = this._scene.reflectionProbes.indexOf(this);\n if (index !== -1) {\n // Remove from the scene if found \n this._scene.reflectionProbes.splice(index, 1);\n }\n if (this._renderTargetTexture) {\n this._renderTargetTexture.dispose();\n this._renderTargetTexture = null;\n }\n };\n return ReflectionProbe;\n }());\n BABYLON.ReflectionProbe = ReflectionProbe;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.reflectionProbe.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Defines the layer scene component responsible to manage any layers\n * in a given scene.\n */\n var LayerSceneComponent = /** @class */ (function () {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n function LayerSceneComponent(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = BABYLON.SceneComponentConstants.NAME_LAYER;\n this.scene = scene;\n this._engine = scene.getEngine();\n scene.layers = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n LayerSceneComponent.prototype.register = function () {\n this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);\n this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);\n };\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n LayerSceneComponent.prototype.rebuild = function () {\n var layers = this.scene.layers;\n for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {\n var layer = layers_1[_i];\n layer._rebuild();\n }\n };\n /**\n * Disposes the component and the associated ressources.\n */\n LayerSceneComponent.prototype.dispose = function () {\n var layers = this.scene.layers;\n while (layers.length) {\n layers[0].dispose();\n }\n };\n LayerSceneComponent.prototype._draw = function (camera, isBackground) {\n var layers = this.scene.layers;\n if (layers.length) {\n this._engine.setDepthBuffer(false);\n var cameraLayerMask = camera.layerMask;\n for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {\n var layer = layers_2[_i];\n if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {\n layer.render();\n }\n }\n this._engine.setDepthBuffer(true);\n }\n };\n LayerSceneComponent.prototype._drawBackground = function (camera) {\n this._draw(camera, true);\n };\n LayerSceneComponent.prototype._drawForeground = function (camera) {\n this._draw(camera, false);\n };\n return LayerSceneComponent;\n }());\n BABYLON.LayerSceneComponent = LayerSceneComponent;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.layerSceneComponent.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var Layer = /** @class */ (function () {\n function Layer(name, imgUrl, scene, isBackground, color) {\n this.name = name;\n this.scale = new BABYLON.Vector2(1, 1);\n this.offset = new BABYLON.Vector2(0, 0);\n this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;\n this.layerMask = 0x0FFFFFFF;\n this._vertexBuffers = {};\n // Events\n /**\n * An event triggered when the layer is disposed.\n */\n this.onDisposeObservable = new BABYLON.Observable();\n /**\n * An event triggered before rendering the scene\n */\n this.onBeforeRenderObservable = new BABYLON.Observable();\n /**\n * An event triggered after rendering the scene\n */\n this.onAfterRenderObservable = new BABYLON.Observable();\n this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;\n this.isBackground = isBackground === undefined ? true : isBackground;\n this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;\n this._scene = (scene || BABYLON.Engine.LastCreatedScene);\n var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);\n if (!layerComponent) {\n layerComponent = new BABYLON.LayerSceneComponent(this._scene);\n this._scene._addComponent(layerComponent);\n }\n this._scene.layers.push(this);\n var engine = this._scene.getEngine();\n // VBO\n var vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;\n this._createIndexBuffer();\n // Effects\n this._effect = engine.createEffect(\"layer\", [BABYLON.VertexBuffer.PositionKind], [\"textureMatrix\", \"color\", \"scale\", \"offset\"], [\"textureSampler\"], \"\");\n this._alphaTestEffect = engine.createEffect(\"layer\", [BABYLON.VertexBuffer.PositionKind], [\"textureMatrix\", \"color\", \"scale\", \"offset\"], [\"textureSampler\"], \"#define ALPHATEST\");\n }\n Object.defineProperty(Layer.prototype, \"onDispose\", {\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Layer.prototype, \"onBeforeRender\", {\n set: function (callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Layer.prototype, \"onAfterRender\", {\n set: function (callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Layer.prototype._createIndexBuffer = function () {\n var engine = this._scene.getEngine();\n // Indices\n var indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = engine.createIndexBuffer(indices);\n };\n Layer.prototype._rebuild = function () {\n var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._createIndexBuffer();\n };\n Layer.prototype.render = function () {\n var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;\n // Check\n if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())\n return;\n var engine = this._scene.getEngine();\n this.onBeforeRenderObservable.notifyObservers(this);\n // Render\n engine.enableEffect(currentEffect);\n engine.setState(false);\n // Texture\n currentEffect.setTexture(\"textureSampler\", this.texture);\n currentEffect.setMatrix(\"textureMatrix\", this.texture.getTextureMatrix());\n // Color\n currentEffect.setFloat4(\"color\", this.color.r, this.color.g, this.color.b, this.color.a);\n // Scale / offset\n currentEffect.setVector2(\"offset\", this.offset);\n currentEffect.setVector2(\"scale\", this.scale);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);\n // Draw order\n if (!this.alphaTest) {\n engine.setAlphaMode(this.alphaBlendingMode);\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);\n }\n else {\n engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);\n }\n this.onAfterRenderObservable.notifyObservers(this);\n };\n Layer.prototype.dispose = function () {\n var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n if (this.texture) {\n this.texture.dispose();\n this.texture = null;\n }\n // Remove from scene\n var index = this._scene.layers.indexOf(this);\n this._scene.layers.splice(index, 1);\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onAfterRenderObservable.clear();\n this.onBeforeRenderObservable.clear();\n };\n return Layer;\n }());\n BABYLON.Layer = Layer;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.layer.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var TextureTools = /** @class */ (function () {\n function TextureTools() {\n }\n /**\n * Uses the GPU to create a copy texture rescaled at a given size\n * @param texture Texture to copy from\n * @param width Desired width\n * @param height Desired height\n * @return Generated texture\n */\n TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {\n if (useBilinearMode === void 0) { useBilinearMode = true; }\n var scene = texture.getScene();\n var engine = scene.getEngine();\n var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);\n rtt.wrapU = texture.wrapU;\n rtt.wrapV = texture.wrapV;\n rtt.uOffset = texture.uOffset;\n rtt.vOffset = texture.vOffset;\n rtt.uScale = texture.uScale;\n rtt.vScale = texture.vScale;\n rtt.uAng = texture.uAng;\n rtt.vAng = texture.vAng;\n rtt.wAng = texture.wAng;\n rtt.coordinatesIndex = texture.coordinatesIndex;\n rtt.level = texture.level;\n rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;\n rtt._texture.isReady = false;\n texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n var passPostProcess = new BABYLON.PassPostProcess(\"pass\", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);\n passPostProcess.getEffect().executeWhenCompiled(function () {\n passPostProcess.onApply = function (effect) {\n effect.setTexture(\"textureSampler\", texture);\n };\n var internalTexture = rtt.getInternalTexture();\n if (internalTexture) {\n scene.postProcessManager.directRender([passPostProcess], internalTexture);\n engine.unBindFramebuffer(internalTexture);\n rtt.disposeFramebufferObjects();\n passPostProcess.dispose();\n internalTexture.isReady = true;\n }\n });\n return rtt;\n };\n TextureTools.GetEnvironmentBRDFTexture = function (scene) {\n if (!scene._environmentBRDFTexture) {\n var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, \"EnvironmentBRDFTexture\", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);\n texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n scene._environmentBRDFTexture = texture;\n }\n return scene._environmentBRDFTexture;\n };\n TextureTools._environmentBRDFBase64Texture = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=\";\n return TextureTools;\n }());\n BABYLON.TextureTools = TextureTools;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.textureTools.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var FramingBehavior = /** @class */ (function () {\n function FramingBehavior() {\n this._mode = FramingBehavior.FitFrustumSidesMode;\n this._radiusScale = 1.0;\n this._positionScale = 0.5;\n this._defaultElevation = 0.3;\n this._elevationReturnTime = 1500;\n this._elevationReturnWaitTime = 1000;\n this._zoomStopsAnimation = false;\n this._framingTime = 1500;\n this._isPointerDown = false;\n this._lastInteractionTime = -Infinity;\n // Framing control\n this._animatables = new Array();\n this._betaIsAnimating = false;\n }\n Object.defineProperty(FramingBehavior.prototype, \"name\", {\n get: function () {\n return \"Framing\";\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"mode\", {\n /**\n * Gets current mode used by the behavior.\n */\n get: function () {\n return this._mode;\n },\n /**\n * Sets the current mode used by the behavior\n */\n set: function (mode) {\n this._mode = mode;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"radiusScale\", {\n /**\n * Gets the scale applied to the radius\n */\n get: function () {\n return this._radiusScale;\n },\n /**\n * Sets the scale applied to the radius (1 by default)\n */\n set: function (radius) {\n this._radiusScale = radius;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"positionScale\", {\n /**\n * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.\n */\n get: function () {\n return this._positionScale;\n },\n /**\n * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.\n */\n set: function (scale) {\n this._positionScale = scale;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"defaultElevation\", {\n /**\n * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle\n * behaviour is triggered, in radians.\n */\n get: function () {\n return this._defaultElevation;\n },\n /**\n * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle\n * behaviour is triggered, in radians.\n */\n set: function (elevation) {\n this._defaultElevation = elevation;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"elevationReturnTime\", {\n /**\n * Gets the time (in milliseconds) taken to return to the default beta position.\n * Negative value indicates camera should not return to default.\n */\n get: function () {\n return this._elevationReturnTime;\n },\n /**\n * Sets the time (in milliseconds) taken to return to the default beta position.\n * Negative value indicates camera should not return to default.\n */\n set: function (speed) {\n this._elevationReturnTime = speed;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"elevationReturnWaitTime\", {\n /**\n * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.\n */\n get: function () {\n return this._elevationReturnWaitTime;\n },\n /**\n * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.\n */\n set: function (time) {\n this._elevationReturnWaitTime = time;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"zoomStopsAnimation\", {\n /**\n * Gets the flag that indicates if user zooming should stop animation.\n */\n get: function () {\n return this._zoomStopsAnimation;\n },\n /**\n * Sets the flag that indicates if user zooming should stop animation.\n */\n set: function (flag) {\n this._zoomStopsAnimation = flag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FramingBehavior.prototype, \"framingTime\", {\n /**\n * Gets the transition time when framing the mesh, in milliseconds\n */\n get: function () {\n return this._framingTime;\n },\n /**\n * Sets the transition time when framing the mesh, in milliseconds\n */\n set: function (time) {\n this._framingTime = time;\n },\n enumerable: true,\n configurable: true\n });\n FramingBehavior.prototype.init = function () {\n // Do notihng\n };\n FramingBehavior.prototype.attach = function (camera) {\n var _this = this;\n this._attachedCamera = camera;\n var scene = this._attachedCamera.getScene();\n FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);\n this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {\n if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {\n _this._isPointerDown = true;\n return;\n }\n if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {\n _this._isPointerDown = false;\n }\n });\n this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {\n if (mesh) {\n _this.zoomOnMesh(mesh);\n }\n });\n this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {\n // Stop the animation if there is user interaction and the animation should stop for this interaction\n _this._applyUserInteraction();\n // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it\n // back to the default position after a given timeout\n _this._maintainCameraAboveGround();\n });\n };\n FramingBehavior.prototype.detach = function () {\n if (!this._attachedCamera) {\n return;\n }\n var scene = this._attachedCamera.getScene();\n if (this._onPrePointerObservableObserver) {\n scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);\n }\n if (this._onAfterCheckInputsObserver) {\n this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);\n }\n if (this._onMeshTargetChangedObserver) {\n this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);\n }\n this._attachedCamera = null;\n };\n /**\n * Targets the given mesh and updates zoom level accordingly.\n * @param mesh The mesh to target.\n * @param radius Optional. If a cached radius position already exists, overrides default.\n * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {\n if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }\n if (onAnimationEnd === void 0) { onAnimationEnd = null; }\n mesh.computeWorldMatrix(true);\n var boundingBox = mesh.getBoundingInfo().boundingBox;\n this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);\n };\n /**\n * Targets the given mesh with its children and updates zoom level accordingly.\n * @param mesh The mesh to target.\n * @param radius Optional. If a cached radius position already exists, overrides default.\n * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {\n if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }\n if (onAnimationEnd === void 0) { onAnimationEnd = null; }\n mesh.computeWorldMatrix(true);\n var boundingBox = mesh.getHierarchyBoundingVectors(true);\n this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);\n };\n /**\n * Targets the given meshes with their children and updates zoom level accordingly.\n * @param meshes The mesh to target.\n * @param radius Optional. If a cached radius position already exists, overrides default.\n * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {\n if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }\n if (onAnimationEnd === void 0) { onAnimationEnd = null; }\n var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n for (var i = 0; i < meshes.length; i++) {\n var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);\n BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);\n BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);\n }\n this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);\n };\n /**\n * Targets the given mesh and updates zoom level accordingly.\n * @param mesh The mesh to target.\n * @param radius Optional. If a cached radius position already exists, overrides default.\n * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {\n var _this = this;\n if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }\n if (onAnimationEnd === void 0) { onAnimationEnd = null; }\n var zoomTarget;\n if (!this._attachedCamera) {\n return;\n }\n // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY\n var bottom = minimumWorld.y;\n var top = maximumWorld.y;\n var zoomTargetY = bottom + (top - bottom) * this._positionScale;\n var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);\n if (focusOnOriginXZ) {\n zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);\n }\n else {\n var centerWorld = minimumWorld.add(radiusWorld);\n zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);\n }\n if (!this._vectorTransition) {\n this._vectorTransition = BABYLON.Animation.CreateAnimation(\"target\", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);\n }\n this._betaIsAnimating = true;\n var animatable = BABYLON.Animation.TransitionTo(\"target\", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);\n if (animatable) {\n this._animatables.push(animatable);\n }\n // sets the radius and lower radius bounds\n // Small delta ensures camera is not always at lower zoom limit.\n var radius = 0;\n if (this._mode === FramingBehavior.FitFrustumSidesMode) {\n var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);\n this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;\n radius = position;\n }\n else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {\n radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);\n if (this._attachedCamera.lowerRadiusLimit === null) {\n this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;\n }\n }\n // Set sensibilities\n var extend = maximumWorld.subtract(minimumWorld).length();\n this._attachedCamera.panningSensibility = 5000 / extend;\n this._attachedCamera.wheelPrecision = 100 / radius;\n // transition to new radius\n if (!this._radiusTransition) {\n this._radiusTransition = BABYLON.Animation.CreateAnimation(\"radius\", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);\n }\n animatable = BABYLON.Animation.TransitionTo(\"radius\", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {\n _this.stopAllAnimations();\n if (onAnimationEnd) {\n onAnimationEnd();\n }\n if (_this._attachedCamera) {\n _this._attachedCamera.storeState();\n }\n });\n if (animatable) {\n this._animatables.push(animatable);\n }\n };\n /**\n * Calculates the lowest radius for the camera based on the bounding box of the mesh.\n * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary\n *\t\t\t frustum width.\n * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order\n *\t\t to fully enclose the mesh in the viewing frustum.\n */\n FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {\n var size = maximumWorld.subtract(minimumWorld);\n var boxVectorGlobalDiagonal = size.length();\n var frustumSlope = this._getFrustumSlope();\n // Formula for setting distance\n // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)\n var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;\n // Horizon distance\n var radius = radiusWithoutFraming * this._radiusScale;\n var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));\n var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));\n var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);\n var camera = this._attachedCamera;\n if (!camera) {\n return 0;\n }\n if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {\n // Don't exceed the requested limit\n distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;\n }\n // Don't exceed the upper radius limit\n if (camera.upperRadiusLimit) {\n distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;\n }\n return distance;\n };\n /**\n * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera\n * is automatically returned to its default position (expected to be above ground plane).\n */\n FramingBehavior.prototype._maintainCameraAboveGround = function () {\n var _this = this;\n if (this._elevationReturnTime < 0) {\n return;\n }\n var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;\n var defaultBeta = Math.PI * 0.5 - this._defaultElevation;\n var limitBeta = Math.PI * 0.5;\n // Bring the camera back up if below the ground plane\n if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {\n this._betaIsAnimating = true;\n //Transition to new position\n this.stopAllAnimations();\n if (!this._betaTransition) {\n this._betaTransition = BABYLON.Animation.CreateAnimation(\"beta\", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);\n }\n var animatabe = BABYLON.Animation.TransitionTo(\"beta\", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {\n _this._clearAnimationLocks();\n _this.stopAllAnimations();\n });\n if (animatabe) {\n this._animatables.push(animatabe);\n }\n }\n };\n /**\n * Returns the frustum slope based on the canvas ratio and camera FOV\n * @returns The frustum slope represented as a Vector2 with X and Y slopes\n */\n FramingBehavior.prototype._getFrustumSlope = function () {\n // Calculate the viewport ratio\n // Aspect Ratio is Height/Width.\n var camera = this._attachedCamera;\n if (!camera) {\n return BABYLON.Vector2.Zero();\n }\n var engine = camera.getScene().getEngine();\n var aspectRatio = engine.getAspectRatio(camera);\n // Camera FOV is the vertical field of view (top-bottom) in radians.\n // Slope of the frustum top/bottom planes in view space, relative to the forward vector.\n var frustumSlopeY = Math.tan(camera.fov / 2);\n // Slope of the frustum left/right planes in view space, relative to the forward vector.\n // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit\n // along the forward vector.\n var frustumSlopeX = frustumSlopeY * aspectRatio;\n return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);\n };\n /**\n * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.\n */\n FramingBehavior.prototype._clearAnimationLocks = function () {\n this._betaIsAnimating = false;\n };\n /**\n * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.\n */\n FramingBehavior.prototype._applyUserInteraction = function () {\n if (this.isUserIsMoving) {\n this._lastInteractionTime = BABYLON.Tools.Now;\n this.stopAllAnimations();\n this._clearAnimationLocks();\n }\n };\n /**\n * Stops and removes all animations that have been applied to the camera\n */\n FramingBehavior.prototype.stopAllAnimations = function () {\n if (this._attachedCamera) {\n this._attachedCamera.animations = [];\n }\n while (this._animatables.length) {\n if (this._animatables[0]) {\n this._animatables[0].onAnimationEnd = null;\n this._animatables[0].stop();\n }\n this._animatables.shift();\n }\n };\n Object.defineProperty(FramingBehavior.prototype, \"isUserIsMoving\", {\n /**\n * Gets a value indicating if the user is moving the camera\n */\n get: function () {\n if (!this._attachedCamera) {\n return false;\n }\n return this._attachedCamera.inertialAlphaOffset !== 0 ||\n this._attachedCamera.inertialBetaOffset !== 0 ||\n this._attachedCamera.inertialRadiusOffset !== 0 ||\n this._attachedCamera.inertialPanningX !== 0 ||\n this._attachedCamera.inertialPanningY !== 0 ||\n this._isPointerDown;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * The easing function used by animations\n */\n FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();\n /**\n * The easing mode used by animations\n */\n FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;\n // Statics\n /**\n * The camera can move all the way towards the mesh.\n */\n FramingBehavior.IgnoreBoundsSizeMode = 0;\n /**\n * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides\n */\n FramingBehavior.FitFrustumSidesMode = 1;\n return FramingBehavior;\n }());\n BABYLON.FramingBehavior = FramingBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.framingBehavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius\n */\n var BouncingBehavior = /** @class */ (function () {\n function BouncingBehavior() {\n /**\n * The duration of the animation, in milliseconds\n */\n this.transitionDuration = 450;\n /**\n * Length of the distance animated by the transition when lower radius is reached\n */\n this.lowerRadiusTransitionRange = 2;\n /**\n * Length of the distance animated by the transition when upper radius is reached\n */\n this.upperRadiusTransitionRange = -2;\n this._autoTransitionRange = false;\n // Animations\n this._radiusIsAnimating = false;\n this._radiusBounceTransition = null;\n this._animatables = new Array();\n }\n Object.defineProperty(BouncingBehavior.prototype, \"name\", {\n get: function () {\n return \"Bouncing\";\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BouncingBehavior.prototype, \"autoTransitionRange\", {\n /**\n * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically\n */\n get: function () {\n return this._autoTransitionRange;\n },\n /**\n * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically\n * Transition ranges will be set to 5% of the bounding box diagonal in world space\n */\n set: function (value) {\n var _this = this;\n if (this._autoTransitionRange === value) {\n return;\n }\n this._autoTransitionRange = value;\n var camera = this._attachedCamera;\n if (!camera) {\n return;\n }\n if (value) {\n this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {\n if (!mesh) {\n return;\n }\n mesh.computeWorldMatrix(true);\n var diagonal = mesh.getBoundingInfo().diagonalLength;\n _this.lowerRadiusTransitionRange = diagonal * 0.05;\n _this.upperRadiusTransitionRange = diagonal * 0.05;\n });\n }\n else if (this._onMeshTargetChangedObserver) {\n camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);\n }\n },\n enumerable: true,\n configurable: true\n });\n BouncingBehavior.prototype.init = function () {\n // Do notihng\n };\n BouncingBehavior.prototype.attach = function (camera) {\n var _this = this;\n this._attachedCamera = camera;\n this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {\n if (!_this._attachedCamera) {\n return;\n }\n // Add the bounce animation to the lower radius limit\n if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {\n _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);\n }\n // Add the bounce animation to the upper radius limit\n if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {\n _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);\n }\n });\n };\n BouncingBehavior.prototype.detach = function () {\n if (!this._attachedCamera) {\n return;\n }\n if (this._onAfterCheckInputsObserver) {\n this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);\n }\n if (this._onMeshTargetChangedObserver) {\n this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);\n }\n this._attachedCamera = null;\n };\n /**\n * Checks if the camera radius is at the specified limit. Takes into account animation locks.\n * @param radiusLimit The limit to check against.\n * @return Bool to indicate if at limit.\n */\n BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {\n if (!this._attachedCamera) {\n return false;\n }\n if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {\n return true;\n }\n return false;\n };\n /**\n * Applies an animation to the radius of the camera, extending by the radiusDelta.\n * @param radiusDelta The delta by which to animate to. Can be negative.\n */\n BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {\n var _this = this;\n if (!this._attachedCamera) {\n return;\n }\n if (!this._radiusBounceTransition) {\n BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);\n this._radiusBounceTransition = BABYLON.Animation.CreateAnimation(\"radius\", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);\n }\n // Prevent zoom until bounce has completed\n this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;\n this._attachedCamera.wheelPrecision = Infinity;\n this._attachedCamera.inertialRadiusOffset = 0;\n // Animate to the radius limit\n this.stopAllAnimations();\n this._radiusIsAnimating = true;\n var animatable = BABYLON.Animation.TransitionTo(\"radius\", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });\n if (animatable) {\n this._animatables.push(animatable);\n }\n };\n /**\n * Removes all animation locks. Allows new animations to be added to any of the camera properties.\n */\n BouncingBehavior.prototype._clearAnimationLocks = function () {\n this._radiusIsAnimating = false;\n if (this._attachedCamera) {\n this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;\n }\n };\n /**\n * Stops and removes all animations that have been applied to the camera\n */\n BouncingBehavior.prototype.stopAllAnimations = function () {\n if (this._attachedCamera) {\n this._attachedCamera.animations = [];\n }\n while (this._animatables.length) {\n this._animatables[0].onAnimationEnd = null;\n this._animatables[0].stop();\n this._animatables.shift();\n }\n };\n /**\n * The easing function used by animations\n */\n BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);\n /**\n * The easing mode used by animations\n */\n BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;\n return BouncingBehavior;\n }());\n BABYLON.BouncingBehavior = BouncingBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.bouncingBehavior.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n var AutoRotationBehavior = /** @class */ (function () {\n function AutoRotationBehavior() {\n this._zoomStopsAnimation = false;\n this._idleRotationSpeed = 0.05;\n this._idleRotationWaitTime = 2000;\n this._idleRotationSpinupTime = 2000;\n this._isPointerDown = false;\n this._lastFrameTime = null;\n this._lastInteractionTime = -Infinity;\n this._cameraRotationSpeed = 0;\n this._lastFrameRadius = 0;\n }\n Object.defineProperty(AutoRotationBehavior.prototype, \"name\", {\n get: function () {\n return \"AutoRotation\";\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AutoRotationBehavior.prototype, \"zoomStopsAnimation\", {\n /**\n * Gets the flag that indicates if user zooming should stop animation.\n */\n get: function () {\n return this._zoomStopsAnimation;\n },\n /**\n * Sets the flag that indicates if user zooming should stop animation.\n */\n set: function (flag) {\n this._zoomStopsAnimation = flag;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AutoRotationBehavior.prototype, \"idleRotationSpeed\", {\n /**\n * Gets the default speed at which the camera rotates around the model.\n */\n get: function () {\n return this._idleRotationSpeed;\n },\n /**\n * Sets the default speed at which the camera rotates around the model.\n */\n set: function (speed) {\n this._idleRotationSpeed = speed;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AutoRotationBehavior.prototype, \"idleRotationWaitTime\", {\n /**\n * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.\n */\n get: function () {\n return this._idleRotationWaitTime;\n },\n /**\n * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.\n */\n set: function (time) {\n this._idleRotationWaitTime = time;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AutoRotationBehavior.prototype, \"idleRotationSpinupTime\", {\n /**\n * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.\n */\n get: function () {\n return this._idleRotationSpinupTime;\n },\n /**\n * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.\n */\n set: function (time) {\n this._idleRotationSpinupTime = time;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AutoRotationBehavior.prototype, \"rotationInProgress\", {\n /**\n * Gets a value indicating if the camera is currently rotating because of this behavior\n */\n get: function () {\n return Math.abs(this._cameraRotationSpeed) > 0;\n },\n enumerable: true,\n configurable: true\n });\n AutoRotationBehavior.prototype.init = function () {\n // Do notihng\n };\n AutoRotationBehavior.prototype.attach = function (camera) {\n var _this = this;\n this._attachedCamera = camera;\n var scene = this._attachedCamera.getScene();\n this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {\n if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {\n _this._isPointerDown = true;\n return;\n }\n if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {\n _this._isPointerDown = false;\n }\n });\n this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {\n var now = BABYLON.Tools.Now;\n var dt = 0;\n if (_this._lastFrameTime != null) {\n dt = now - _this._lastFrameTime;\n }\n _this._lastFrameTime = now;\n // Stop the animation if there is user interaction and the animation should stop for this interaction\n _this._applyUserInteraction();\n var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;\n var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);\n _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;\n // Step camera rotation by rotation speed\n if (_this._attachedCamera) {\n _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);\n }\n });\n };\n AutoRotationBehavior.prototype.detach = function () {\n if (!this._attachedCamera) {\n return;\n }\n var scene = this._attachedCamera.getScene();\n if (this._onPrePointerObservableObserver) {\n scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);\n }\n this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);\n this._attachedCamera = null;\n };\n /**\n * Returns true if user is scrolling.\n * @return true if user is scrolling.\n */\n AutoRotationBehavior.prototype._userIsZooming = function () {\n if (!this._attachedCamera) {\n return false;\n }\n return this._attachedCamera.inertialRadiusOffset !== 0;\n };\n AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {\n if (!this._attachedCamera) {\n return false;\n }\n var zoomHasHitLimit = false;\n if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {\n zoomHasHitLimit = true;\n }\n // Update the record of previous radius - works as an approx. indicator of hitting radius limits\n this._lastFrameRadius = this._attachedCamera.radius;\n return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();\n };\n /**\n * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.\n */\n AutoRotationBehavior.prototype._applyUserInteraction = function () {\n if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {\n this._lastInteractionTime = BABYLON.Tools.Now;\n }\n };\n // Tools\n AutoRotationBehavior.prototype._userIsMoving = function () {\n if (!this._attachedCamera) {\n return false;\n }\n return this._attachedCamera.inertialAlphaOffset !== 0 ||\n this._attachedCamera.inertialBetaOffset !== 0 ||\n this._attachedCamera.inertialRadiusOffset !== 0 ||\n this._attachedCamera.inertialPanningX !== 0 ||\n this._attachedCamera.inertialPanningY !== 0 ||\n this._isPointerDown;\n };\n return AutoRotationBehavior;\n }());\n BABYLON.AutoRotationBehavior = AutoRotationBehavior;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.autoRotationBehavior.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var NullEngineOptions = /** @class */ (function () {\n function NullEngineOptions() {\n this.renderWidth = 512;\n this.renderHeight = 256;\n this.textureSize = 512;\n this.deterministicLockstep = false;\n this.lockstepMaxSteps = 4;\n }\n return NullEngineOptions;\n }());\n BABYLON.NullEngineOptions = NullEngineOptions;\n /**\n * The null engine class provides support for headless version of babylon.js.\n * This can be used in server side scenario or for testing purposes\n */\n var NullEngine = /** @class */ (function (_super) {\n __extends(NullEngine, _super);\n function NullEngine(options) {\n if (options === void 0) { options = new NullEngineOptions(); }\n var _this = _super.call(this, null) || this;\n if (options.deterministicLockstep === undefined) {\n options.deterministicLockstep = false;\n }\n if (options.lockstepMaxSteps === undefined) {\n options.lockstepMaxSteps = 4;\n }\n _this._options = options;\n // Init caps\n // We consider we are on a webgl1 capable device\n _this._caps = new BABYLON.EngineCapabilities();\n _this._caps.maxTexturesImageUnits = 16;\n _this._caps.maxVertexTextureImageUnits = 16;\n _this._caps.maxTextureSize = 512;\n _this._caps.maxCubemapTextureSize = 512;\n _this._caps.maxRenderTextureSize = 512;\n _this._caps.maxVertexAttribs = 16;\n _this._caps.maxVaryingVectors = 16;\n _this._caps.maxFragmentUniformVectors = 16;\n _this._caps.maxVertexUniformVectors = 16;\n // Extensions\n _this._caps.standardDerivatives = false;\n _this._caps.astc = null;\n _this._caps.s3tc = null;\n _this._caps.pvrtc = null;\n _this._caps.etc1 = null;\n _this._caps.etc2 = null;\n _this._caps.textureAnisotropicFilterExtension = null;\n _this._caps.maxAnisotropy = 0;\n _this._caps.uintIndices = false;\n _this._caps.fragmentDepthSupported = false;\n _this._caps.highPrecisionShaderSupported = true;\n _this._caps.colorBufferFloat = false;\n _this._caps.textureFloat = false;\n _this._caps.textureFloatLinearFiltering = false;\n _this._caps.textureFloatRender = false;\n _this._caps.textureHalfFloat = false;\n _this._caps.textureHalfFloatLinearFiltering = false;\n _this._caps.textureHalfFloatRender = false;\n _this._caps.textureLOD = false;\n _this._caps.drawBuffersExtension = false;\n _this._caps.depthTextureExtension = false;\n _this._caps.vertexArrayObject = false;\n _this._caps.instancedArrays = false;\n BABYLON.Tools.Log(\"Babylon.js null engine (v\" + BABYLON.Engine.Version + \") launched\");\n // Wrappers\n if (typeof URL === \"undefined\") {\n URL = {\n createObjectURL: function () { },\n revokeObjectURL: function () { }\n };\n }\n if (typeof Blob === \"undefined\") {\n Blob = function () { };\n }\n return _this;\n }\n NullEngine.prototype.isDeterministicLockStep = function () {\n return this._options.deterministicLockstep;\n };\n NullEngine.prototype.getLockstepMaxSteps = function () {\n return this._options.lockstepMaxSteps;\n };\n NullEngine.prototype.getHardwareScalingLevel = function () {\n return 1.0;\n };\n NullEngine.prototype.createVertexBuffer = function (vertices) {\n return {\n capacity: 0,\n references: 1,\n is32Bits: false\n };\n };\n NullEngine.prototype.createIndexBuffer = function (indices) {\n return {\n capacity: 0,\n references: 1,\n is32Bits: false\n };\n };\n NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {\n if (stencil === void 0) { stencil = false; }\n };\n NullEngine.prototype.getRenderWidth = function (useScreen) {\n if (useScreen === void 0) { useScreen = false; }\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.width;\n }\n return this._options.renderWidth;\n };\n NullEngine.prototype.getRenderHeight = function (useScreen) {\n if (useScreen === void 0) { useScreen = false; }\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.height;\n }\n return this._options.renderHeight;\n };\n NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {\n this._cachedViewport = viewport;\n };\n NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {\n return {\n transformFeedback: null,\n __SPECTOR_rebuildProgram: null\n };\n };\n NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {\n return [];\n };\n NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {\n return [];\n };\n NullEngine.prototype.bindSamplers = function (effect) {\n this._currentEffect = null;\n };\n NullEngine.prototype.enableEffect = function (effect) {\n this._currentEffect = effect;\n if (effect.onBind) {\n effect.onBind(effect);\n }\n if (effect._onBindObservable) {\n effect._onBindObservable.notifyObservers(effect);\n }\n };\n NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {\n if (zOffset === void 0) { zOffset = 0; }\n if (reverseSide === void 0) { reverseSide = false; }\n };\n NullEngine.prototype.setIntArray = function (uniform, array) {\n };\n NullEngine.prototype.setIntArray2 = function (uniform, array) {\n };\n NullEngine.prototype.setIntArray3 = function (uniform, array) {\n };\n NullEngine.prototype.setIntArray4 = function (uniform, array) {\n };\n NullEngine.prototype.setFloatArray = function (uniform, array) {\n };\n NullEngine.prototype.setFloatArray2 = function (uniform, array) {\n };\n NullEngine.prototype.setFloatArray3 = function (uniform, array) {\n };\n NullEngine.prototype.setFloatArray4 = function (uniform, array) {\n };\n NullEngine.prototype.setArray = function (uniform, array) {\n };\n NullEngine.prototype.setArray2 = function (uniform, array) {\n };\n NullEngine.prototype.setArray3 = function (uniform, array) {\n };\n NullEngine.prototype.setArray4 = function (uniform, array) {\n };\n NullEngine.prototype.setMatrices = function (uniform, matrices) {\n };\n NullEngine.prototype.setMatrix = function (uniform, matrix) {\n };\n NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {\n };\n NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {\n };\n NullEngine.prototype.setFloat = function (uniform, value) {\n };\n NullEngine.prototype.setFloat2 = function (uniform, x, y) {\n };\n NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {\n };\n NullEngine.prototype.setBool = function (uniform, bool) {\n };\n NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {\n };\n NullEngine.prototype.setColor3 = function (uniform, color3) {\n };\n NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {\n };\n NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {\n if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }\n if (this._alphaMode === mode) {\n return;\n }\n this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);\n if (!noDepthWriteChange) {\n this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);\n }\n this._alphaMode = mode;\n };\n NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {\n };\n NullEngine.prototype.wipeCaches = function (bruteForce) {\n if (this.preventCacheWipeBetweenFrames) {\n return;\n }\n this.resetTextureCache();\n this._currentEffect = null;\n if (bruteForce) {\n this._currentProgram = null;\n this._stencilState.reset();\n this._depthCullingState.reset();\n this._alphaState.reset();\n }\n this._cachedVertexBuffers = null;\n this._cachedIndexBuffer = null;\n this._cachedEffectForVertexBuffers = null;\n };\n NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {\n };\n NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {\n };\n NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {\n };\n NullEngine.prototype._createTexture = function () {\n return {};\n };\n NullEngine.prototype._releaseTexture = function (texture) {\n };\n NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (onLoad === void 0) { onLoad = null; }\n if (onError === void 0) { onError = null; }\n if (buffer === void 0) { buffer = null; }\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);\n var url = String(urlArg);\n texture.url = url;\n texture.generateMipMaps = !noMipmap;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture.baseWidth = this._options.textureSize;\n texture.baseHeight = this._options.textureSize;\n texture.width = this._options.textureSize;\n texture.height = this._options.textureSize;\n if (format) {\n texture.format = format;\n }\n texture.isReady = true;\n if (onLoad) {\n onLoad();\n }\n this._internalTexturesCache.push(texture);\n return texture;\n };\n NullEngine.prototype.createRenderTargetTexture = function (size, options) {\n var fullOptions = new BABYLON.RenderTargetCreationOptions();\n if (options !== undefined && typeof options === \"object\") {\n fullOptions.generateMipMaps = options.generateMipMaps;\n fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;\n fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;\n fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;\n }\n else {\n fullOptions.generateMipMaps = options;\n fullOptions.generateDepthBuffer = true;\n fullOptions.generateStencilBuffer = false;\n fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;\n }\n var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);\n var width = size.width || size;\n var height = size.height || size;\n texture._depthStencilBuffer = {};\n texture._framebuffer = {};\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n texture.samples = 1;\n texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n texture._generateDepthBuffer = fullOptions.generateDepthBuffer;\n texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;\n this._internalTexturesCache.push(texture);\n return texture;\n };\n NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {\n texture.samplingMode = samplingMode;\n };\n NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n this._currentRenderTarget = texture;\n this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;\n if (this._cachedViewport && !forceFullscreenViewport) {\n this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);\n }\n };\n NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {\n if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }\n this._currentRenderTarget = null;\n if (onBeforeUnbind) {\n if (texture._MSAAFramebuffer) {\n this._currentFramebuffer = texture._framebuffer;\n }\n onBeforeUnbind();\n }\n this._currentFramebuffer = null;\n };\n NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {\n var vbo = {\n capacity: 1,\n references: 1,\n is32Bits: false\n };\n return vbo;\n };\n NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {\n if (premulAlpha === void 0) { premulAlpha = false; }\n };\n /**\n * Get the current error code of the webGL context\n * @returns the error code\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError\n */\n NullEngine.prototype.getError = function () {\n return 0;\n };\n /** @hidden */\n NullEngine.prototype._getUnpackAlignement = function () {\n return 1;\n };\n /** @hidden */\n NullEngine.prototype._unpackFlipY = function (value) {\n };\n NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {\n if (offset === void 0) { offset = 0; }\n };\n /**\n * Updates a dynamic vertex buffer.\n * @param vertexBuffer the vertex buffer to update\n * @param data the data used to update the vertex buffer\n * @param byteOffset the byte offset of the data (optional)\n * @param byteLength the byte length of the data (optional)\n */\n NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {\n };\n NullEngine.prototype._bindTextureDirectly = function (target, texture) {\n if (this._boundTexturesCache[this._activeChannel] !== texture) {\n this._boundTexturesCache[this._activeChannel] = texture;\n return true;\n }\n return false;\n };\n NullEngine.prototype._bindTexture = function (channel, texture) {\n if (channel < 0) {\n return;\n }\n this._bindTextureDirectly(0, texture);\n };\n NullEngine.prototype._releaseBuffer = function (buffer) {\n buffer.references--;\n if (buffer.references === 0) {\n return true;\n }\n return false;\n };\n NullEngine.prototype.releaseEffects = function () {\n };\n NullEngine.prototype.displayLoadingUI = function () {\n };\n NullEngine.prototype.hideLoadingUI = function () {\n };\n /** @hidden */\n NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n };\n /** @hidden */\n NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n };\n /** @hidden */\n NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n };\n /** @hidden */\n NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {\n if (faceIndex === void 0) { faceIndex = 0; }\n if (lod === void 0) { lod = 0; }\n };\n return NullEngine;\n }(BABYLON.Engine));\n BABYLON.NullEngine = NullEngine;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.nullEngine.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class can be used to get instrumentation data from a Babylon engine\n */\n var EngineInstrumentation = /** @class */ (function () {\n function EngineInstrumentation(engine) {\n this.engine = engine;\n this._captureGPUFrameTime = false;\n this._gpuFrameTime = new BABYLON.PerfCounter();\n this._captureShaderCompilationTime = false;\n this._shaderCompilationTime = new BABYLON.PerfCounter();\n // Observers\n this._onBeginFrameObserver = null;\n this._onEndFrameObserver = null;\n this._onBeforeShaderCompilationObserver = null;\n this._onAfterShaderCompilationObserver = null;\n }\n Object.defineProperty(EngineInstrumentation.prototype, \"gpuFrameTimeCounter\", {\n // Properties\n /**\n * Gets the perf counter used for GPU frame time\n */\n get: function () {\n return this._gpuFrameTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EngineInstrumentation.prototype, \"captureGPUFrameTime\", {\n /**\n * Gets the GPU frame time capture status\n */\n get: function () {\n return this._captureGPUFrameTime;\n },\n /**\n * Enable or disable the GPU frame time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureGPUFrameTime) {\n return;\n }\n this._captureGPUFrameTime = value;\n if (value) {\n this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {\n if (!_this._gpuFrameTimeToken) {\n _this._gpuFrameTimeToken = _this.engine.startTimeQuery();\n }\n });\n this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {\n if (!_this._gpuFrameTimeToken) {\n return;\n }\n var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);\n if (time > -1) {\n _this._gpuFrameTimeToken = null;\n _this._gpuFrameTime.fetchNewFrame();\n _this._gpuFrameTime.addCount(time, true);\n }\n });\n }\n else {\n this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);\n this._onBeginFrameObserver = null;\n this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);\n this._onEndFrameObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EngineInstrumentation.prototype, \"shaderCompilationTimeCounter\", {\n /**\n * Gets the perf counter used for shader compilation time\n */\n get: function () {\n return this._shaderCompilationTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EngineInstrumentation.prototype, \"captureShaderCompilationTime\", {\n /**\n * Gets the shader compilation time capture status\n */\n get: function () {\n return this._captureShaderCompilationTime;\n },\n /**\n * Enable or disable the shader compilation time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureShaderCompilationTime) {\n return;\n }\n this._captureShaderCompilationTime = value;\n if (value) {\n this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {\n _this._shaderCompilationTime.fetchNewFrame();\n _this._shaderCompilationTime.beginMonitoring();\n });\n this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {\n _this._shaderCompilationTime.endMonitoring();\n });\n }\n else {\n this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);\n this._onBeforeShaderCompilationObserver = null;\n this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);\n this._onAfterShaderCompilationObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n EngineInstrumentation.prototype.dispose = function () {\n this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);\n this._onBeginFrameObserver = null;\n this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);\n this._onEndFrameObserver = null;\n this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);\n this._onBeforeShaderCompilationObserver = null;\n this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);\n this._onAfterShaderCompilationObserver = null;\n this.engine = null;\n };\n return EngineInstrumentation;\n }());\n BABYLON.EngineInstrumentation = EngineInstrumentation;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.engineInstrumentation.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class can be used to get instrumentation data from a Babylon engine\n */\n var SceneInstrumentation = /** @class */ (function () {\n function SceneInstrumentation(scene) {\n var _this = this;\n this.scene = scene;\n this._captureActiveMeshesEvaluationTime = false;\n this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();\n this._captureRenderTargetsRenderTime = false;\n this._renderTargetsRenderTime = new BABYLON.PerfCounter();\n this._captureFrameTime = false;\n this._frameTime = new BABYLON.PerfCounter();\n this._captureRenderTime = false;\n this._renderTime = new BABYLON.PerfCounter();\n this._captureInterFrameTime = false;\n this._interFrameTime = new BABYLON.PerfCounter();\n this._captureParticlesRenderTime = false;\n this._particlesRenderTime = new BABYLON.PerfCounter();\n this._captureSpritesRenderTime = false;\n this._spritesRenderTime = new BABYLON.PerfCounter();\n this._capturePhysicsTime = false;\n this._physicsTime = new BABYLON.PerfCounter();\n this._captureAnimationsTime = false;\n this._animationsTime = new BABYLON.PerfCounter();\n this._captureCameraRenderTime = false;\n this._cameraRenderTime = new BABYLON.PerfCounter();\n // Observers\n this._onBeforeActiveMeshesEvaluationObserver = null;\n this._onAfterActiveMeshesEvaluationObserver = null;\n this._onBeforeRenderTargetsRenderObserver = null;\n this._onAfterRenderTargetsRenderObserver = null;\n this._onAfterRenderObserver = null;\n this._onBeforeDrawPhaseObserver = null;\n this._onAfterDrawPhaseObserver = null;\n this._onBeforeAnimationsObserver = null;\n this._onBeforeParticlesRenderingObserver = null;\n this._onAfterParticlesRenderingObserver = null;\n this._onBeforeSpritesRenderingObserver = null;\n this._onAfterSpritesRenderingObserver = null;\n this._onBeforePhysicsObserver = null;\n this._onAfterPhysicsObserver = null;\n this._onAfterAnimationsObserver = null;\n this._onBeforeCameraRenderObserver = null;\n this._onAfterCameraRenderObserver = null;\n // Before render\n this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {\n if (_this._captureActiveMeshesEvaluationTime) {\n _this._activeMeshesEvaluationTime.fetchNewFrame();\n }\n if (_this._captureRenderTargetsRenderTime) {\n _this._renderTargetsRenderTime.fetchNewFrame();\n }\n if (_this._captureFrameTime) {\n BABYLON.Tools.StartPerformanceCounter(\"Scene rendering\");\n _this._frameTime.beginMonitoring();\n }\n if (_this._captureInterFrameTime) {\n _this._interFrameTime.endMonitoring();\n }\n if (_this._captureParticlesRenderTime) {\n _this._particlesRenderTime.fetchNewFrame();\n }\n if (_this._captureSpritesRenderTime) {\n _this._spritesRenderTime.fetchNewFrame();\n }\n if (_this._captureAnimationsTime) {\n _this._animationsTime.beginMonitoring();\n }\n _this.scene.getEngine()._drawCalls.fetchNewFrame();\n _this.scene.getEngine()._textureCollisions.fetchNewFrame();\n });\n // After render\n this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {\n if (_this._captureFrameTime) {\n BABYLON.Tools.EndPerformanceCounter(\"Scene rendering\");\n _this._frameTime.endMonitoring();\n }\n if (_this._captureRenderTime) {\n _this._renderTime.endMonitoring(false);\n }\n if (_this._captureInterFrameTime) {\n _this._interFrameTime.beginMonitoring();\n }\n });\n }\n Object.defineProperty(SceneInstrumentation.prototype, \"activeMeshesEvaluationTimeCounter\", {\n // Properties\n /**\n * Gets the perf counter used for active meshes evaluation time\n */\n get: function () {\n return this._activeMeshesEvaluationTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureActiveMeshesEvaluationTime\", {\n /**\n * Gets the active meshes evaluation time capture status\n */\n get: function () {\n return this._captureActiveMeshesEvaluationTime;\n },\n /**\n * Enable or disable the active meshes evaluation time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureActiveMeshesEvaluationTime) {\n return;\n }\n this._captureActiveMeshesEvaluationTime = value;\n if (value) {\n this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {\n BABYLON.Tools.StartPerformanceCounter(\"Active meshes evaluation\");\n _this._activeMeshesEvaluationTime.beginMonitoring();\n });\n this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {\n BABYLON.Tools.EndPerformanceCounter(\"Active meshes evaluation\");\n _this._activeMeshesEvaluationTime.endMonitoring();\n });\n }\n else {\n this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);\n this._onBeforeActiveMeshesEvaluationObserver = null;\n this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);\n this._onAfterActiveMeshesEvaluationObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"renderTargetsRenderTimeCounter\", {\n /**\n * Gets the perf counter used for render targets render time\n */\n get: function () {\n return this._renderTargetsRenderTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureRenderTargetsRenderTime\", {\n /**\n * Gets the render targets render time capture status\n */\n get: function () {\n return this._captureRenderTargetsRenderTime;\n },\n /**\n * Enable or disable the render targets render time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureRenderTargetsRenderTime) {\n return;\n }\n this._captureRenderTargetsRenderTime = value;\n if (value) {\n this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {\n BABYLON.Tools.StartPerformanceCounter(\"Render targets rendering\");\n _this._renderTargetsRenderTime.beginMonitoring();\n });\n this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {\n BABYLON.Tools.EndPerformanceCounter(\"Render targets rendering\");\n _this._renderTargetsRenderTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);\n this._onBeforeRenderTargetsRenderObserver = null;\n this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);\n this._onAfterRenderTargetsRenderObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"particlesRenderTimeCounter\", {\n /**\n * Gets the perf counter used for particles render time\n */\n get: function () {\n return this._particlesRenderTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureParticlesRenderTime\", {\n /**\n * Gets the particles render time capture status\n */\n get: function () {\n return this._captureParticlesRenderTime;\n },\n /**\n * Enable or disable the particles render time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureParticlesRenderTime) {\n return;\n }\n this._captureParticlesRenderTime = value;\n if (value) {\n this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {\n BABYLON.Tools.StartPerformanceCounter(\"Particles\");\n _this._particlesRenderTime.beginMonitoring();\n });\n this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {\n BABYLON.Tools.EndPerformanceCounter(\"Particles\");\n _this._particlesRenderTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);\n this._onBeforeParticlesRenderingObserver = null;\n this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);\n this._onAfterParticlesRenderingObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"spritesRenderTimeCounter\", {\n /**\n * Gets the perf counter used for sprites render time\n */\n get: function () {\n return this._spritesRenderTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureSpritesRenderTime\", {\n /**\n * Gets the sprites render time capture status\n */\n get: function () {\n return this._captureSpritesRenderTime;\n },\n /**\n * Enable or disable the sprites render time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureSpritesRenderTime) {\n return;\n }\n this._captureSpritesRenderTime = value;\n if (value) {\n this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {\n BABYLON.Tools.StartPerformanceCounter(\"Sprites\");\n _this._spritesRenderTime.beginMonitoring();\n });\n this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {\n BABYLON.Tools.EndPerformanceCounter(\"Sprites\");\n _this._spritesRenderTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);\n this._onBeforeSpritesRenderingObserver = null;\n this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);\n this._onAfterSpritesRenderingObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"physicsTimeCounter\", {\n /**\n * Gets the perf counter used for physics time\n */\n get: function () {\n return this._physicsTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"capturePhysicsTime\", {\n /**\n * Gets the physics time capture status\n */\n get: function () {\n return this._capturePhysicsTime;\n },\n /**\n * Enable or disable the physics time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._capturePhysicsTime) {\n return;\n }\n this._capturePhysicsTime = value;\n if (value) {\n this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {\n BABYLON.Tools.StartPerformanceCounter(\"Physics\");\n _this._physicsTime.beginMonitoring();\n });\n this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {\n BABYLON.Tools.EndPerformanceCounter(\"Physics\");\n _this._physicsTime.endMonitoring();\n });\n }\n else {\n this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);\n this._onBeforePhysicsObserver = null;\n this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);\n this._onAfterPhysicsObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"animationsTimeCounter\", {\n /**\n * Gets the perf counter used for animations time\n */\n get: function () {\n return this._animationsTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureAnimationsTime\", {\n /**\n * Gets the animations time capture status\n */\n get: function () {\n return this._captureAnimationsTime;\n },\n /**\n * Enable or disable the animations time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureAnimationsTime) {\n return;\n }\n this._captureAnimationsTime = value;\n if (value) {\n this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {\n _this._animationsTime.endMonitoring();\n });\n }\n else {\n this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);\n this._onAfterAnimationsObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"frameTimeCounter\", {\n /**\n * Gets the perf counter used for frame time capture\n */\n get: function () {\n return this._frameTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureFrameTime\", {\n /**\n * Gets the frame time capture status\n */\n get: function () {\n return this._captureFrameTime;\n },\n /**\n * Enable or disable the frame time capture\n */\n set: function (value) {\n this._captureFrameTime = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"interFrameTimeCounter\", {\n /**\n * Gets the perf counter used for inter-frames time capture\n */\n get: function () {\n return this._interFrameTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureInterFrameTime\", {\n /**\n * Gets the inter-frames time capture status\n */\n get: function () {\n return this._captureInterFrameTime;\n },\n /**\n * Enable or disable the inter-frames time capture\n */\n set: function (value) {\n this._captureInterFrameTime = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"renderTimeCounter\", {\n /**\n * Gets the perf counter used for render time capture\n */\n get: function () {\n return this._renderTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureRenderTime\", {\n /**\n * Gets the render time capture status\n */\n get: function () {\n return this._captureRenderTime;\n },\n /**\n * Enable or disable the render time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureRenderTime) {\n return;\n }\n this._captureRenderTime = value;\n if (value) {\n this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {\n _this._renderTime.beginMonitoring();\n BABYLON.Tools.StartPerformanceCounter(\"Main render\");\n });\n this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {\n _this._renderTime.endMonitoring(false);\n BABYLON.Tools.EndPerformanceCounter(\"Main render\");\n });\n }\n else {\n this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);\n this._onBeforeDrawPhaseObserver = null;\n this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);\n this._onAfterDrawPhaseObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"cameraRenderTimeCounter\", {\n /**\n * Gets the perf counter used for camera render time capture\n */\n get: function () {\n return this._cameraRenderTime;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"captureCameraRenderTime\", {\n /**\n * Gets the camera render time capture status\n */\n get: function () {\n return this._captureCameraRenderTime;\n },\n /**\n * Enable or disable the camera render time capture\n */\n set: function (value) {\n var _this = this;\n if (value === this._captureCameraRenderTime) {\n return;\n }\n this._captureCameraRenderTime = value;\n if (value) {\n this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {\n _this._cameraRenderTime.beginMonitoring();\n BABYLON.Tools.StartPerformanceCounter(\"Rendering camera \" + camera.name);\n });\n this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {\n _this._cameraRenderTime.endMonitoring(false);\n BABYLON.Tools.EndPerformanceCounter(\"Rendering camera \" + camera.name);\n });\n }\n else {\n this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n this._onBeforeCameraRenderObserver = null;\n this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);\n this._onAfterCameraRenderObserver = null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"drawCallsCounter\", {\n /**\n * Gets the perf counter used for draw calls\n */\n get: function () {\n return this.scene.getEngine()._drawCalls;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SceneInstrumentation.prototype, \"textureCollisionsCounter\", {\n /**\n * Gets the perf counter used for texture collisions\n */\n get: function () {\n return this.scene.getEngine()._textureCollisions;\n },\n enumerable: true,\n configurable: true\n });\n SceneInstrumentation.prototype.dispose = function () {\n this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n this._onAfterRenderObserver = null;\n this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);\n this._onBeforeActiveMeshesEvaluationObserver = null;\n this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);\n this._onAfterActiveMeshesEvaluationObserver = null;\n this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);\n this._onBeforeRenderTargetsRenderObserver = null;\n this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);\n this._onAfterRenderTargetsRenderObserver = null;\n this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);\n this._onBeforeAnimationsObserver = null;\n this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);\n this._onBeforeParticlesRenderingObserver = null;\n this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);\n this._onAfterParticlesRenderingObserver = null;\n this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);\n this._onBeforeSpritesRenderingObserver = null;\n this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);\n this._onAfterSpritesRenderingObserver = null;\n this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);\n this._onBeforeDrawPhaseObserver = null;\n this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);\n this._onAfterDrawPhaseObserver = null;\n this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);\n this._onBeforePhysicsObserver = null;\n this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);\n this._onAfterPhysicsObserver = null;\n this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);\n this._onAfterAnimationsObserver = null;\n this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n this._onBeforeCameraRenderObserver = null;\n this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);\n this._onAfterCameraRenderObserver = null;\n this.scene = null;\n };\n return SceneInstrumentation;\n }());\n BABYLON.SceneInstrumentation = SceneInstrumentation;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.sceneInstrumentation.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * @hidden\n **/\n var _TimeToken = /** @class */ (function () {\n function _TimeToken() {\n this._timeElapsedQueryEnded = false;\n }\n return _TimeToken;\n }());\n BABYLON._TimeToken = _TimeToken;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.timeToken.js.map\n\n\n\n\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Background material defines definition.\n * @hidden Mainly internal Use\n */\n var BackgroundMaterialDefines = /** @class */ (function (_super) {\n __extends(BackgroundMaterialDefines, _super);\n /**\n * Constructor of the defines.\n */\n function BackgroundMaterialDefines() {\n var _this = _super.call(this) || this;\n /**\n * True if the diffuse texture is in use.\n */\n _this.DIFFUSE = false;\n /**\n * The direct UV channel to use.\n */\n _this.DIFFUSEDIRECTUV = 0;\n /**\n * True if the diffuse texture is in gamma space.\n */\n _this.GAMMADIFFUSE = false;\n /**\n * True if the diffuse texture has opacity in the alpha channel.\n */\n _this.DIFFUSEHASALPHA = false;\n /**\n * True if you want the material to fade to transparent at grazing angle.\n */\n _this.OPACITYFRESNEL = false;\n /**\n * True if an extra blur needs to be added in the reflection.\n */\n _this.REFLECTIONBLUR = false;\n /**\n * True if you want the material to fade to reflection at grazing angle.\n */\n _this.REFLECTIONFRESNEL = false;\n /**\n * True if you want the material to falloff as far as you move away from the scene center.\n */\n _this.REFLECTIONFALLOFF = false;\n /**\n * False if the current Webgl implementation does not support the texture lod extension.\n */\n _this.TEXTURELODSUPPORT = false;\n /**\n * True to ensure the data are premultiplied.\n */\n _this.PREMULTIPLYALPHA = false;\n /**\n * True if the texture contains cooked RGB values and not gray scaled multipliers.\n */\n _this.USERGBCOLOR = false;\n /**\n * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color\n * stays aligned with the desired configuration.\n */\n _this.USEHIGHLIGHTANDSHADOWCOLORS = false;\n /**\n * True to add noise in order to reduce the banding effect.\n */\n _this.NOISE = false;\n /**\n * is the reflection texture in BGR color scheme?\n * Mainly used to solve a bug in ios10 video tag\n */\n _this.REFLECTIONBGR = false;\n _this.IMAGEPROCESSING = false;\n _this.VIGNETTE = false;\n _this.VIGNETTEBLENDMODEMULTIPLY = false;\n _this.VIGNETTEBLENDMODEOPAQUE = false;\n _this.TONEMAPPING = false;\n _this.CONTRAST = false;\n _this.COLORCURVES = false;\n _this.COLORGRADING = false;\n _this.COLORGRADING3D = false;\n _this.SAMPLER3DGREENDEPTH = false;\n _this.SAMPLER3DBGRMAP = false;\n _this.IMAGEPROCESSINGPOSTPROCESS = false;\n _this.EXPOSURE = false;\n // Reflection.\n _this.REFLECTION = false;\n _this.REFLECTIONMAP_3D = false;\n _this.REFLECTIONMAP_SPHERICAL = false;\n _this.REFLECTIONMAP_PLANAR = false;\n _this.REFLECTIONMAP_CUBIC = false;\n _this.REFLECTIONMAP_PROJECTION = false;\n _this.REFLECTIONMAP_SKYBOX = false;\n _this.REFLECTIONMAP_EXPLICIT = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n _this.INVERTCUBICMAP = false;\n _this.REFLECTIONMAP_OPPOSITEZ = false;\n _this.LODINREFLECTIONALPHA = false;\n _this.GAMMAREFLECTION = false;\n _this.RGBDREFLECTION = false;\n _this.EQUIRECTANGULAR_RELFECTION_FOV = false;\n // Default BJS.\n _this.MAINUV1 = false;\n _this.MAINUV2 = false;\n _this.UV1 = false;\n _this.UV2 = false;\n _this.CLIPPLANE = false;\n _this.POINTSIZE = false;\n _this.FOG = false;\n _this.NORMAL = false;\n _this.NUM_BONE_INFLUENCERS = 0;\n _this.BonesPerMesh = 0;\n _this.INSTANCES = false;\n _this.SHADOWFLOAT = false;\n _this.rebuild();\n return _this;\n }\n return BackgroundMaterialDefines;\n }(BABYLON.MaterialDefines));\n /**\n * Background material used to create an efficient environement around your scene.\n */\n var BackgroundMaterial = /** @class */ (function (_super) {\n __extends(BackgroundMaterial, _super);\n /**\n * Instantiates a Background Material in the given scene\n * @param name The friendly name of the material\n * @param scene The scene to add the material to\n */\n function BackgroundMaterial(name, scene) {\n var _this = _super.call(this, name, scene) || this;\n /**\n * Key light Color (multiply against the environement texture)\n */\n _this.primaryColor = BABYLON.Color3.White();\n _this._primaryColorShadowLevel = 0;\n _this._primaryColorHighlightLevel = 0;\n /**\n * Reflection Texture used in the material.\n * Should be author in a specific way for the best result (refer to the documentation).\n */\n _this.reflectionTexture = null;\n /**\n * Reflection Texture level of blur.\n *\n * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the\n * texture twice.\n */\n _this.reflectionBlur = 0;\n /**\n * Diffuse Texture used in the material.\n * Should be author in a specific way for the best result (refer to the documentation).\n */\n _this.diffuseTexture = null;\n _this._shadowLights = null;\n /**\n * Specify the list of lights casting shadow on the material.\n * All scene shadow lights will be included if null.\n */\n _this.shadowLights = null;\n /**\n * Helps adjusting the shadow to a softer level if required.\n * 0 means black shadows and 1 means no shadows.\n */\n _this.shadowLevel = 0;\n /**\n * In case of opacity Fresnel or reflection falloff, this is use as a scene center.\n * It is usually zero but might be interesting to modify according to your setup.\n */\n _this.sceneCenter = BABYLON.Vector3.Zero();\n /**\n * This helps specifying that the material is falling off to the sky box at grazing angle.\n * This helps ensuring a nice transition when the camera goes under the ground.\n */\n _this.opacityFresnel = true;\n /**\n * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.\n * This helps adding a mirror texture on the ground.\n */\n _this.reflectionFresnel = false;\n /**\n * This helps specifying the falloff radius off the reflection texture from the sceneCenter.\n * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.\n */\n _this.reflectionFalloffDistance = 0.0;\n /**\n * This specifies the weight of the reflection against the background in case of reflection Fresnel.\n */\n _this.reflectionAmount = 1.0;\n /**\n * This specifies the weight of the reflection at grazing angle.\n */\n _this.reflectionReflectance0 = 0.05;\n /**\n * This specifies the weight of the reflection at a perpendicular point of view.\n */\n _this.reflectionReflectance90 = 0.5;\n /**\n * Helps to directly use the maps channels instead of their level.\n */\n _this.useRGBColor = true;\n /**\n * This helps reducing the banding effect that could occur on the background.\n */\n _this.enableNoise = false;\n _this._fovMultiplier = 1.0;\n /**\n * Enable the FOV adjustment feature controlled by fovMultiplier.\n */\n _this.useEquirectangularFOV = false;\n _this._maxSimultaneousLights = 4;\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n _this.maxSimultaneousLights = 4;\n /**\n * Keep track of the image processing observer to allow dispose and replace.\n */\n _this._imageProcessingObserver = null;\n /**\n * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.\n * Setting this flag to true (not done automatically!) will convert it back to RGB.\n */\n _this.switchToBGR = false;\n // Temp values kept as cache in the material.\n _this._renderTargets = new BABYLON.SmartArray(16);\n _this._reflectionControls = BABYLON.Vector4.Zero();\n _this._white = BABYLON.Color3.White();\n _this._primaryShadowColor = BABYLON.Color3.Black();\n _this._primaryHighlightColor = BABYLON.Color3.Black();\n // Setup the default processing configuration to the scene.\n _this._attachImageProcessingConfiguration(null);\n _this.getRenderTargetTextures = function () {\n _this._renderTargets.reset();\n if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {\n _this._renderTargets.push(_this._diffuseTexture);\n }\n if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {\n _this._renderTargets.push(_this._reflectionTexture);\n }\n return _this._renderTargets;\n };\n return _this;\n }\n Object.defineProperty(BackgroundMaterial.prototype, \"_perceptualColor\", {\n /**\n * Experimental Internal Use Only.\n *\n * Key light Color in \"perceptual value\" meaning the color you would like to see on screen.\n * This acts as a helper to set the primary color to a more \"human friendly\" value.\n * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the\n * output color as close as possible from the chosen value.\n * (This does not account for contrast color grading and color curves as they are considered post effect and not directly\n * part of lighting setup.)\n */\n get: function () {\n return this.__perceptualColor;\n },\n set: function (value) {\n this.__perceptualColor = value;\n this._computePrimaryColorFromPerceptualColor();\n this._markAllSubMeshesAsLightsDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"primaryColorShadowLevel\", {\n /**\n * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.\n * The color opposite to the primary color is used at the level chosen to define what the black area would look.\n */\n get: function () {\n return this._primaryColorShadowLevel;\n },\n set: function (value) {\n this._primaryColorShadowLevel = value;\n this._computePrimaryColors();\n this._markAllSubMeshesAsLightsDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"primaryColorHighlightLevel\", {\n /**\n * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.\n * The primary color is used at the level chosen to define what the white area would look.\n */\n get: function () {\n return this._primaryColorHighlightLevel;\n },\n set: function (value) {\n this._primaryColorHighlightLevel = value;\n this._computePrimaryColors();\n this._markAllSubMeshesAsLightsDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"reflectionStandardFresnelWeight\", {\n /**\n * Sets the reflection reflectance fresnel values according to the default standard\n * empirically know to work well :-)\n */\n set: function (value) {\n var reflectionWeight = value;\n if (reflectionWeight < 0.5) {\n reflectionWeight = reflectionWeight * 2.0;\n this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;\n this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;\n }\n else {\n reflectionWeight = reflectionWeight * 2.0 - 1.0;\n this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;\n this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"fovMultiplier\", {\n /**\n * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values \"zoom in\" and higher values \"zoom out\".\n * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.\n * Recommended to be keep at 1.0 except for special cases.\n */\n get: function () {\n return this._fovMultiplier;\n },\n set: function (value) {\n if (isNaN(value)) {\n value = 1.0;\n }\n this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Attaches a new image processing configuration to the PBR Material.\n * @param configuration (if null the scene configuration will be use)\n */\n BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {\n var _this = this;\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {\n _this._computePrimaryColorFromPerceptualColor();\n _this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n };\n Object.defineProperty(BackgroundMaterial.prototype, \"imageProcessingConfiguration\", {\n /**\n * Gets the image processing configuration used either in this material.\n */\n get: function () {\n return this._imageProcessingConfiguration;\n },\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set: function (value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraColorCurvesEnabled\", {\n /**\n * Gets wether the color curves effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n },\n /**\n * Sets wether the color curves effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraColorGradingEnabled\", {\n /**\n * Gets wether the color grading effect is enabled.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n },\n /**\n * Gets wether the color grading effect is enabled.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraToneMappingEnabled\", {\n /**\n * Gets wether tonemapping is enabled or not.\n */\n get: function () {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n },\n /**\n * Sets wether tonemapping is enabled or not\n */\n set: function (value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraExposure\", {\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n get: function () {\n return this._imageProcessingConfiguration.exposure;\n },\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n set: function (value) {\n this._imageProcessingConfiguration.exposure = value;\n },\n enumerable: true,\n configurable: true\n });\n ;\n ;\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraContrast\", {\n /**\n * Gets The camera contrast used on this material.\n */\n get: function () {\n return this._imageProcessingConfiguration.contrast;\n },\n /**\n * Sets The camera contrast used on this material.\n */\n set: function (value) {\n this._imageProcessingConfiguration.contrast = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraColorGradingTexture\", {\n /**\n * Gets the Color Grading 2D Lookup Texture.\n */\n get: function () {\n return this._imageProcessingConfiguration.colorGradingTexture;\n },\n /**\n * Sets the Color Grading 2D Lookup Texture.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorGradingTexture = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BackgroundMaterial.prototype, \"cameraColorCurves\", {\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n get: function () {\n return this.imageProcessingConfiguration.colorCurves;\n },\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n set: function (value) {\n this.imageProcessingConfiguration.colorCurves = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * The entire material has been created in order to prevent overdraw.\n * @returns false\n */\n BackgroundMaterial.prototype.needAlphaTesting = function () {\n return true;\n };\n /**\n * The entire material has been created in order to prevent overdraw.\n * @returns true if blending is enable\n */\n BackgroundMaterial.prototype.needAlphaBlending = function () {\n return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));\n };\n /**\n * Checks wether the material is ready to be rendered for a given mesh.\n * @param mesh The mesh to render\n * @param subMesh The submesh to check against\n * @param useInstances Specify wether or not the material is used with instances\n * @returns true if all the dependencies are ready (Textures, Effects...)\n */\n BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {\n var _this = this;\n if (useInstances === void 0) { useInstances = false; }\n if (subMesh.effect && this.isFrozen) {\n if (this._wasPreviouslyReady) {\n return true;\n }\n }\n if (!subMesh._materialDefines) {\n subMesh._materialDefines = new BackgroundMaterialDefines();\n }\n var scene = this.getScene();\n var defines = subMesh._materialDefines;\n if (!this.checkReadyOnEveryCall && subMesh.effect) {\n if (defines._renderId === scene.getRenderId()) {\n return true;\n }\n }\n var engine = scene.getEngine();\n // Lights\n BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);\n defines._needNormals = true;\n // Textures\n if (defines._areTexturesDirty) {\n defines._needUVs = false;\n if (scene.texturesEnabled) {\n if (scene.getEngine().getCaps().textureLOD) {\n defines.TEXTURELODSUPPORT = true;\n }\n if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n if (!this._diffuseTexture.isReadyOrNotBlocking()) {\n return false;\n }\n BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, \"DIFFUSE\");\n defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;\n defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;\n defines.OPACITYFRESNEL = this._opacityFresnel;\n }\n else {\n defines.DIFFUSE = false;\n defines.DIFFUSEHASALPHA = false;\n defines.GAMMADIFFUSE = false;\n defines.OPACITYFRESNEL = false;\n }\n var reflectionTexture = this._reflectionTexture;\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n if (!reflectionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n defines.REFLECTION = true;\n defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;\n defines.RGBDREFLECTION = reflectionTexture.isRGBD;\n defines.REFLECTIONBLUR = this._reflectionBlur > 0;\n defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;\n defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;\n defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;\n defines.REFLECTIONBGR = this.switchToBGR;\n if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {\n defines.INVERTCUBICMAP = true;\n }\n defines.REFLECTIONMAP_3D = reflectionTexture.isCube;\n switch (reflectionTexture.coordinatesMode) {\n case BABYLON.Texture.EXPLICIT_MODE:\n defines.REFLECTIONMAP_EXPLICIT = true;\n break;\n case BABYLON.Texture.PLANAR_MODE:\n defines.REFLECTIONMAP_PLANAR = true;\n break;\n case BABYLON.Texture.PROJECTION_MODE:\n defines.REFLECTIONMAP_PROJECTION = true;\n break;\n case BABYLON.Texture.SKYBOX_MODE:\n defines.REFLECTIONMAP_SKYBOX = true;\n break;\n case BABYLON.Texture.SPHERICAL_MODE:\n defines.REFLECTIONMAP_SPHERICAL = true;\n break;\n case BABYLON.Texture.EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR = true;\n break;\n case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;\n break;\n case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;\n break;\n case BABYLON.Texture.CUBIC_MODE:\n case BABYLON.Texture.INVCUBIC_MODE:\n default:\n defines.REFLECTIONMAP_CUBIC = true;\n break;\n }\n if (this.reflectionFresnel) {\n defines.REFLECTIONFRESNEL = true;\n defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;\n this._reflectionControls.x = this.reflectionAmount;\n this._reflectionControls.y = this.reflectionReflectance0;\n this._reflectionControls.z = this.reflectionReflectance90;\n this._reflectionControls.w = 1 / this.reflectionFalloffDistance;\n }\n else {\n defines.REFLECTIONFRESNEL = false;\n defines.REFLECTIONFALLOFF = false;\n }\n }\n else {\n defines.REFLECTION = false;\n defines.REFLECTIONFRESNEL = false;\n defines.REFLECTIONFALLOFF = false;\n defines.REFLECTIONBLUR = false;\n defines.REFLECTIONMAP_3D = false;\n defines.REFLECTIONMAP_SPHERICAL = false;\n defines.REFLECTIONMAP_PLANAR = false;\n defines.REFLECTIONMAP_CUBIC = false;\n defines.REFLECTIONMAP_PROJECTION = false;\n defines.REFLECTIONMAP_SKYBOX = false;\n defines.REFLECTIONMAP_EXPLICIT = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n defines.INVERTCUBICMAP = false;\n defines.REFLECTIONMAP_OPPOSITEZ = false;\n defines.LODINREFLECTIONALPHA = false;\n defines.GAMMAREFLECTION = false;\n defines.RGBDREFLECTION = false;\n }\n }\n defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);\n defines.USERGBCOLOR = this._useRGBColor;\n defines.NOISE = this._enableNoise;\n }\n if (defines._areLightsDirty) {\n defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n if (!this._imageProcessingConfiguration.isReady()) {\n return false;\n }\n this._imageProcessingConfiguration.prepareDefines(defines);\n }\n // Misc.\n BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);\n // Values that need to be evaluated on every frame\n BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);\n // Attribs\n if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {\n if (mesh) {\n if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {\n mesh.createNormals(true);\n BABYLON.Tools.Warn(\"BackgroundMaterial: Normals have been created for the mesh: \" + mesh.name);\n }\n }\n }\n // Get correct effect\n if (defines.isDirty) {\n defines.markAsProcessed();\n scene.resetCachedMaterial();\n // Fallbacks\n var fallbacks = new BABYLON.EffectFallbacks();\n if (defines.FOG) {\n fallbacks.addFallback(0, \"FOG\");\n }\n if (defines.POINTSIZE) {\n fallbacks.addFallback(1, \"POINTSIZE\");\n }\n BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);\n if (defines.NUM_BONE_INFLUENCERS > 0) {\n fallbacks.addCPUSkinningFallback(0, mesh);\n }\n //Attributes\n var attribs = [BABYLON.VertexBuffer.PositionKind];\n if (defines.NORMAL) {\n attribs.push(BABYLON.VertexBuffer.NormalKind);\n }\n if (defines.UV1) {\n attribs.push(BABYLON.VertexBuffer.UVKind);\n }\n if (defines.UV2) {\n attribs.push(BABYLON.VertexBuffer.UV2Kind);\n }\n BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);\n BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);\n var uniforms = [\"world\", \"view\", \"viewProjection\", \"vEyePosition\", \"vLightsType\",\n \"vFogInfos\", \"vFogColor\", \"pointSize\",\n \"vClipPlane\", \"mBones\",\n \"vPrimaryColor\", \"vPrimaryColorShadow\",\n \"vReflectionInfos\", \"reflectionMatrix\", \"vReflectionMicrosurfaceInfos\", \"fFovMultiplier\",\n \"shadowLevel\", \"alpha\",\n \"vBackgroundCenter\", \"vReflectionControl\",\n \"vDiffuseInfos\", \"diffuseMatrix\",\n ];\n var samplers = [\"diffuseSampler\", \"reflectionSampler\", \"reflectionSamplerLow\", \"reflectionSamplerHigh\"];\n var uniformBuffers = [\"Material\", \"Scene\"];\n if (BABYLON.ImageProcessingConfiguration) {\n BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);\n BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);\n }\n BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: defines,\n maxSimultaneousLights: this._maxSimultaneousLights\n });\n var onCompiled = function (effect) {\n if (_this.onCompiled) {\n _this.onCompiled(effect);\n }\n _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());\n };\n var join = defines.toString();\n subMesh.setEffect(scene.getEngine().createEffect(\"background\", {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: onCompiled,\n onError: this.onError,\n indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }\n }, engine), defines);\n this.buildUniformLayout();\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n this._wasPreviouslyReady = true;\n return true;\n };\n /**\n * Compute the primary color according to the chosen perceptual color.\n */\n BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {\n if (!this.__perceptualColor) {\n return;\n }\n this._primaryColor.copyFrom(this.__perceptualColor);\n // Revert gamma space.\n this._primaryColor.toLinearSpaceToRef(this._primaryColor);\n // Revert image processing configuration.\n if (this._imageProcessingConfiguration) {\n // Revert Exposure.\n this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);\n }\n this._computePrimaryColors();\n };\n /**\n * Compute the highlights and shadow colors according to their chosen levels.\n */\n BackgroundMaterial.prototype._computePrimaryColors = function () {\n if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {\n return;\n }\n // Find the highlight color based on the configuration.\n this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);\n this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);\n // Find the shadow color based on the configuration.\n this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);\n this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);\n this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);\n };\n /**\n * Build the uniform buffer used in the material.\n */\n BackgroundMaterial.prototype.buildUniformLayout = function () {\n // Order is important !\n this._uniformBuffer.addUniform(\"vPrimaryColor\", 4);\n this._uniformBuffer.addUniform(\"vPrimaryColorShadow\", 4);\n this._uniformBuffer.addUniform(\"vDiffuseInfos\", 2);\n this._uniformBuffer.addUniform(\"vReflectionInfos\", 2);\n this._uniformBuffer.addUniform(\"diffuseMatrix\", 16);\n this._uniformBuffer.addUniform(\"reflectionMatrix\", 16);\n this._uniformBuffer.addUniform(\"vReflectionMicrosurfaceInfos\", 3);\n this._uniformBuffer.addUniform(\"fFovMultiplier\", 1);\n this._uniformBuffer.addUniform(\"pointSize\", 1);\n this._uniformBuffer.addUniform(\"shadowLevel\", 1);\n this._uniformBuffer.addUniform(\"alpha\", 1);\n this._uniformBuffer.addUniform(\"vBackgroundCenter\", 3);\n this._uniformBuffer.addUniform(\"vReflectionControl\", 4);\n this._uniformBuffer.create();\n };\n /**\n * Unbind the material.\n */\n BackgroundMaterial.prototype.unbind = function () {\n if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {\n this._uniformBuffer.setTexture(\"diffuseSampler\", null);\n }\n if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", null);\n }\n _super.prototype.unbind.call(this);\n };\n /**\n * Bind only the world matrix to the material.\n * @param world The world matrix to bind.\n */\n BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {\n this._activeEffect.setMatrix(\"world\", world);\n };\n /**\n * Bind the material for a dedicated submeh (every used meshes will be considered opaque).\n * @param world The world matrix to bind.\n * @param subMesh The submesh to bind for.\n */\n BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {\n var scene = this.getScene();\n var defines = subMesh._materialDefines;\n if (!defines) {\n return;\n }\n var effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices\n this.bindOnlyWorldMatrix(world);\n // Bones\n BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);\n var mustRebind = this._mustRebind(scene, effect, mesh.visibility);\n if (mustRebind) {\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this.bindViewProjection(effect);\n var reflectionTexture = this._reflectionTexture;\n if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {\n // Texture uniforms\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vDiffuseInfos\", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);\n BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, \"diffuse\");\n }\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n this._uniformBuffer.updateMatrix(\"reflectionMatrix\", reflectionTexture.getReflectionTextureMatrix());\n this._uniformBuffer.updateFloat2(\"vReflectionInfos\", reflectionTexture.level, this._reflectionBlur);\n this._uniformBuffer.updateFloat3(\"vReflectionMicrosurfaceInfos\", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);\n }\n }\n if (this.shadowLevel > 0) {\n this._uniformBuffer.updateFloat(\"shadowLevel\", this.shadowLevel);\n }\n this._uniformBuffer.updateFloat(\"alpha\", this.alpha);\n // Point size\n if (this.pointsCloud) {\n this._uniformBuffer.updateFloat(\"pointSize\", this.pointSize);\n }\n if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {\n this._uniformBuffer.updateColor4(\"vPrimaryColor\", this._primaryHighlightColor, 1.0);\n this._uniformBuffer.updateColor4(\"vPrimaryColorShadow\", this._primaryShadowColor, 1.0);\n }\n else {\n this._uniformBuffer.updateColor4(\"vPrimaryColor\", this._primaryColor, 1.0);\n }\n }\n this._uniformBuffer.updateFloat(\"fFovMultiplier\", this._fovMultiplier);\n // Textures\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {\n this._uniformBuffer.setTexture(\"diffuseSampler\", this._diffuseTexture);\n }\n if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {\n if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture);\n }\n else if (!defines.REFLECTIONBLUR) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture);\n }\n else {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture._lodTextureMid || reflectionTexture);\n this._uniformBuffer.setTexture(\"reflectionSamplerLow\", reflectionTexture._lodTextureLow || reflectionTexture);\n this._uniformBuffer.setTexture(\"reflectionSamplerHigh\", reflectionTexture._lodTextureHigh || reflectionTexture);\n }\n if (defines.REFLECTIONFRESNEL) {\n this._uniformBuffer.updateFloat3(\"vBackgroundCenter\", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);\n this._uniformBuffer.updateFloat4(\"vReflectionControl\", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);\n }\n }\n }\n // Clip plane\n BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);\n BABYLON.MaterialHelper.BindEyePosition(effect, scene);\n }\n if (mustRebind || !this.isFrozen) {\n if (scene.lightsEnabled) {\n BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);\n }\n // View\n this.bindView(effect);\n // Fog\n BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);\n // image processing\n if (this._imageProcessingConfiguration) {\n this._imageProcessingConfiguration.bind(this._activeEffect);\n }\n }\n this._uniformBuffer.update();\n this._afterBind(mesh, this._activeEffect);\n };\n /**\n * Dispose the material.\n * @param forceDisposeEffect Force disposal of the associated effect.\n * @param forceDisposeTextures Force disposal of the associated textures.\n */\n BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {\n if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }\n if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }\n if (forceDisposeTextures) {\n if (this.diffuseTexture) {\n this.diffuseTexture.dispose();\n }\n if (this.reflectionTexture) {\n this.reflectionTexture.dispose();\n }\n }\n this._renderTargets.dispose();\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n _super.prototype.dispose.call(this, forceDisposeEffect);\n };\n /**\n * Clones the material.\n * @param name The cloned name.\n * @returns The cloned material.\n */\n BackgroundMaterial.prototype.clone = function (name) {\n var _this = this;\n return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);\n };\n /**\n * Serializes the current material to its JSON representation.\n * @returns The JSON representation.\n */\n BackgroundMaterial.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.BackgroundMaterial\";\n return serializationObject;\n };\n /**\n * Gets the class name of the material\n * @returns \"BackgroundMaterial\"\n */\n BackgroundMaterial.prototype.getClassName = function () {\n return \"BackgroundMaterial\";\n };\n /**\n * Parse a JSON input to create back a background material.\n * @param source The JSON data to parse\n * @param scene The scene to create the parsed material in\n * @param rootUrl The root url of the assets the material depends upon\n * @returns the instantiated BackgroundMaterial.\n */\n BackgroundMaterial.Parse = function (source, scene, rootUrl) {\n return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);\n };\n /**\n * Standard reflectance value at parallel view angle.\n */\n BackgroundMaterial.StandardReflectance0 = 0.05;\n /**\n * Standard reflectance value at grazing angle.\n */\n BackgroundMaterial.StandardReflectance90 = 0.5;\n __decorate([\n BABYLON.serializeAsColor3()\n ], BackgroundMaterial.prototype, \"_primaryColor\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], BackgroundMaterial.prototype, \"primaryColor\", void 0);\n __decorate([\n BABYLON.serializeAsColor3()\n ], BackgroundMaterial.prototype, \"__perceptualColor\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_primaryColorShadowLevel\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_primaryColorHighlightLevel\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n ], BackgroundMaterial.prototype, \"primaryColorHighlightLevel\", null);\n __decorate([\n BABYLON.serializeAsTexture()\n ], BackgroundMaterial.prototype, \"_reflectionTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionTexture\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_reflectionBlur\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionBlur\", void 0);\n __decorate([\n BABYLON.serializeAsTexture()\n ], BackgroundMaterial.prototype, \"_diffuseTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"diffuseTexture\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"shadowLights\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_shadowLevel\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"shadowLevel\", void 0);\n __decorate([\n BABYLON.serializeAsVector3()\n ], BackgroundMaterial.prototype, \"_sceneCenter\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"sceneCenter\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_opacityFresnel\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"opacityFresnel\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_reflectionFresnel\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionFresnel\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_reflectionFalloffDistance\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionFalloffDistance\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_reflectionAmount\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionAmount\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_reflectionReflectance0\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionReflectance0\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_reflectionReflectance90\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"reflectionReflectance90\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_useRGBColor\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"useRGBColor\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_enableNoise\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"enableNoise\", void 0);\n __decorate([\n BABYLON.serialize()\n ], BackgroundMaterial.prototype, \"_maxSimultaneousLights\", void 0);\n __decorate([\n BABYLON.expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n ], BackgroundMaterial.prototype, \"maxSimultaneousLights\", void 0);\n __decorate([\n BABYLON.serializeAsImageProcessingConfiguration()\n ], BackgroundMaterial.prototype, \"_imageProcessingConfiguration\", void 0);\n return BackgroundMaterial;\n }(BABYLON.PushMaterial));\n BABYLON.BackgroundMaterial = BackgroundMaterial;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.backgroundMaterial.js.map\n\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};\nvar BABYLON;\n(function (BABYLON) {\n /**\n * The Environment helper class can be used to add a fully featuread none expensive background to your scene.\n * It includes by default a skybox and a ground relying on the BackgroundMaterial.\n * It also helps with the default setup of your imageProcessing configuration.\n */\n var EnvironmentHelper = /** @class */ (function () {\n /**\n * constructor\n * @param options\n * @param scene The scene to add the material to\n */\n function EnvironmentHelper(options, scene) {\n var _this = this;\n this._errorHandler = function (message, exception) {\n _this.onErrorObservable.notifyObservers({ message: message, exception: exception });\n };\n this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);\n this._scene = scene;\n this.onErrorObservable = new BABYLON.Observable();\n this._setupBackground();\n this._setupImageProcessing();\n }\n /**\n * Creates the default options for the helper.\n */\n EnvironmentHelper._getDefaultOptions = function () {\n return {\n createGround: true,\n groundSize: 15,\n groundTexture: this._groundTextureCDNUrl,\n groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),\n groundOpacity: 0.9,\n enableGroundShadow: true,\n groundShadowLevel: 0.5,\n enableGroundMirror: false,\n groundMirrorSizeRatio: 0.3,\n groundMirrorBlurKernel: 64,\n groundMirrorAmount: 1,\n groundMirrorFresnelWeight: 1,\n groundMirrorFallOffDistance: 0,\n groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,\n groundYBias: 0.00001,\n createSkybox: true,\n skyboxSize: 20,\n skyboxTexture: this._skyboxTextureCDNUrl,\n skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),\n backgroundYRotation: 0,\n sizeAuto: true,\n rootPosition: BABYLON.Vector3.Zero(),\n setupImageProcessing: true,\n environmentTexture: this._environmentTextureCDNUrl,\n cameraExposure: 0.8,\n cameraContrast: 1.2,\n toneMappingEnabled: true,\n };\n };\n Object.defineProperty(EnvironmentHelper.prototype, \"rootMesh\", {\n /**\n * Gets the root mesh created by the helper.\n */\n get: function () {\n return this._rootMesh;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"skybox\", {\n /**\n * Gets the skybox created by the helper.\n */\n get: function () {\n return this._skybox;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"skyboxTexture\", {\n /**\n * Gets the skybox texture created by the helper.\n */\n get: function () {\n return this._skyboxTexture;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"skyboxMaterial\", {\n /**\n * Gets the skybox material created by the helper.\n */\n get: function () {\n return this._skyboxMaterial;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"ground\", {\n /**\n * Gets the ground mesh created by the helper.\n */\n get: function () {\n return this._ground;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"groundTexture\", {\n /**\n * Gets the ground texture created by the helper.\n */\n get: function () {\n return this._groundTexture;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"groundMirror\", {\n /**\n * Gets the ground mirror created by the helper.\n */\n get: function () {\n return this._groundMirror;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"groundMirrorRenderList\", {\n /**\n * Gets the ground mirror render list to helps pushing the meshes\n * you wish in the ground reflection.\n */\n get: function () {\n if (this._groundMirror) {\n return this._groundMirror.renderList;\n }\n return null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EnvironmentHelper.prototype, \"groundMaterial\", {\n /**\n * Gets the ground material created by the helper.\n */\n get: function () {\n return this._groundMaterial;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Updates the background according to the new options\n * @param options\n */\n EnvironmentHelper.prototype.updateOptions = function (options) {\n var newOptions = __assign({}, this._options, options);\n if (this._ground && !newOptions.createGround) {\n this._ground.dispose();\n this._ground = null;\n }\n if (this._groundMaterial && !newOptions.createGround) {\n this._groundMaterial.dispose();\n this._groundMaterial = null;\n }\n if (this._groundTexture) {\n if (this._options.groundTexture != newOptions.groundTexture) {\n this._groundTexture.dispose();\n this._groundTexture = null;\n }\n }\n if (this._skybox && !newOptions.createSkybox) {\n this._skybox.dispose();\n this._skybox = null;\n }\n if (this._skyboxMaterial && !newOptions.createSkybox) {\n this._skyboxMaterial.dispose();\n this._skyboxMaterial = null;\n }\n if (this._skyboxTexture) {\n if (this._options.skyboxTexture != newOptions.skyboxTexture) {\n this._skyboxTexture.dispose();\n this._skyboxTexture = null;\n }\n }\n if (this._groundMirror && !newOptions.enableGroundMirror) {\n this._groundMirror.dispose();\n this._groundMirror = null;\n }\n if (this._scene.environmentTexture) {\n if (this._options.environmentTexture != newOptions.environmentTexture) {\n this._scene.environmentTexture.dispose();\n }\n }\n this._options = newOptions;\n this._setupBackground();\n this._setupImageProcessing();\n };\n /**\n * Sets the primary color of all the available elements.\n * @param color the main color to affect to the ground and the background\n */\n EnvironmentHelper.prototype.setMainColor = function (color) {\n if (this.groundMaterial) {\n this.groundMaterial.primaryColor = color;\n }\n if (this.skyboxMaterial) {\n this.skyboxMaterial.primaryColor = color;\n }\n if (this.groundMirror) {\n this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);\n }\n };\n /**\n * Setup the image processing according to the specified options.\n */\n EnvironmentHelper.prototype._setupImageProcessing = function () {\n if (this._options.setupImageProcessing) {\n this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;\n this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;\n this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;\n this._setupEnvironmentTexture();\n }\n };\n /**\n * Setup the environment texture according to the specified options.\n */\n EnvironmentHelper.prototype._setupEnvironmentTexture = function () {\n if (this._scene.environmentTexture) {\n return;\n }\n if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {\n this._scene.environmentTexture = this._options.environmentTexture;\n return;\n }\n var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);\n this._scene.environmentTexture = environmentTexture;\n };\n /**\n * Setup the background according to the specified options.\n */\n EnvironmentHelper.prototype._setupBackground = function () {\n if (!this._rootMesh) {\n this._rootMesh = new BABYLON.Mesh(\"BackgroundHelper\", this._scene);\n }\n this._rootMesh.rotation.y = this._options.backgroundYRotation;\n var sceneSize = this._getSceneSize();\n if (this._options.createGround) {\n this._setupGround(sceneSize);\n this._setupGroundMaterial();\n this._setupGroundDiffuseTexture();\n if (this._options.enableGroundMirror) {\n this._setupGroundMirrorTexture(sceneSize);\n }\n this._setupMirrorInGroundMaterial();\n }\n if (this._options.createSkybox) {\n this._setupSkybox(sceneSize);\n this._setupSkyboxMaterial();\n this._setupSkyboxReflectionTexture();\n }\n this._rootMesh.position.x = sceneSize.rootPosition.x;\n this._rootMesh.position.z = sceneSize.rootPosition.z;\n this._rootMesh.position.y = sceneSize.rootPosition.y;\n };\n /**\n * Get the scene sizes according to the setup.\n */\n EnvironmentHelper.prototype._getSceneSize = function () {\n var _this = this;\n var groundSize = this._options.groundSize;\n var skyboxSize = this._options.skyboxSize;\n var rootPosition = this._options.rootPosition;\n if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.\n return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };\n }\n var sceneExtends = this._scene.getWorldExtends(function (mesh) {\n return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);\n });\n var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);\n if (this._options.sizeAuto) {\n if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&\n this._scene.activeCamera.upperRadiusLimit) {\n groundSize = this._scene.activeCamera.upperRadiusLimit * 2;\n skyboxSize = groundSize;\n }\n var sceneDiagonalLenght = sceneDiagonal.length();\n if (sceneDiagonalLenght > groundSize) {\n groundSize = sceneDiagonalLenght * 2;\n skyboxSize = groundSize;\n }\n // 10 % bigger.\n groundSize *= 1.1;\n skyboxSize *= 1.5;\n rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));\n rootPosition.y = sceneExtends.min.y - this._options.groundYBias;\n }\n return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };\n };\n /**\n * Setup the ground according to the specified options.\n */\n EnvironmentHelper.prototype._setupGround = function (sceneSize) {\n var _this = this;\n if (!this._ground || this._ground.isDisposed()) {\n this._ground = BABYLON.Mesh.CreatePlane(\"BackgroundPlane\", sceneSize.groundSize, this._scene);\n this._ground.rotation.x = Math.PI / 2; // Face up by default.\n this._ground.parent = this._rootMesh;\n this._ground.onDisposeObservable.add(function () { _this._ground = null; });\n }\n this._ground.receiveShadows = this._options.enableGroundShadow;\n };\n /**\n * Setup the ground material according to the specified options.\n */\n EnvironmentHelper.prototype._setupGroundMaterial = function () {\n if (!this._groundMaterial) {\n this._groundMaterial = new BABYLON.BackgroundMaterial(\"BackgroundPlaneMaterial\", this._scene);\n }\n this._groundMaterial.alpha = this._options.groundOpacity;\n this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;\n this._groundMaterial.shadowLevel = this._options.groundShadowLevel;\n this._groundMaterial.primaryColor = this._options.groundColor;\n this._groundMaterial.useRGBColor = false;\n this._groundMaterial.enableNoise = true;\n if (this._ground) {\n this._ground.material = this._groundMaterial;\n }\n };\n /**\n * Setup the ground diffuse texture according to the specified options.\n */\n EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {\n if (!this._groundMaterial) {\n return;\n }\n if (this._groundTexture) {\n return;\n }\n if (this._options.groundTexture instanceof BABYLON.BaseTexture) {\n this._groundMaterial.diffuseTexture = this._options.groundTexture;\n return;\n }\n var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);\n diffuseTexture.gammaSpace = false;\n diffuseTexture.hasAlpha = true;\n this._groundMaterial.diffuseTexture = diffuseTexture;\n };\n /**\n * Setup the ground mirror texture according to the specified options.\n */\n EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {\n var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;\n if (!this._groundMirror) {\n this._groundMirror = new BABYLON.MirrorTexture(\"BackgroundPlaneMirrorTexture\", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);\n this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);\n this._groundMirror.anisotropicFilteringLevel = 1;\n this._groundMirror.wrapU = wrapping;\n this._groundMirror.wrapV = wrapping;\n this._groundMirror.gammaSpace = false;\n if (this._groundMirror.renderList) {\n for (var i = 0; i < this._scene.meshes.length; i++) {\n var mesh = this._scene.meshes[i];\n if (mesh !== this._ground &&\n mesh !== this._skybox &&\n mesh !== this._rootMesh) {\n this._groundMirror.renderList.push(mesh);\n }\n }\n }\n }\n this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);\n this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;\n };\n /**\n * Setup the ground to receive the mirror texture.\n */\n EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {\n if (this._groundMaterial) {\n this._groundMaterial.reflectionTexture = this._groundMirror;\n this._groundMaterial.reflectionFresnel = true;\n this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;\n this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;\n this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;\n }\n };\n /**\n * Setup the skybox according to the specified options.\n */\n EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {\n var _this = this;\n if (!this._skybox || this._skybox.isDisposed()) {\n this._skybox = BABYLON.Mesh.CreateBox(\"BackgroundSkybox\", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);\n this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });\n }\n this._skybox.parent = this._rootMesh;\n };\n /**\n * Setup the skybox material according to the specified options.\n */\n EnvironmentHelper.prototype._setupSkyboxMaterial = function () {\n if (!this._skybox) {\n return;\n }\n if (!this._skyboxMaterial) {\n this._skyboxMaterial = new BABYLON.BackgroundMaterial(\"BackgroundSkyboxMaterial\", this._scene);\n }\n this._skyboxMaterial.useRGBColor = false;\n this._skyboxMaterial.primaryColor = this._options.skyboxColor;\n this._skyboxMaterial.enableNoise = true;\n this._skybox.material = this._skyboxMaterial;\n };\n /**\n * Setup the skybox reflection texture according to the specified options.\n */\n EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {\n if (!this._skyboxMaterial) {\n return;\n }\n if (this._skyboxTexture) {\n return;\n }\n if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {\n this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;\n return;\n }\n this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);\n this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;\n this._skyboxTexture.gammaSpace = false;\n this._skyboxMaterial.reflectionTexture = this._skyboxTexture;\n };\n /**\n * Dispose all the elements created by the Helper.\n */\n EnvironmentHelper.prototype.dispose = function () {\n if (this._groundMaterial) {\n this._groundMaterial.dispose(true, true);\n }\n if (this._skyboxMaterial) {\n this._skyboxMaterial.dispose(true, true);\n }\n this._rootMesh.dispose(false);\n };\n /**\n * Default ground texture URL.\n */\n EnvironmentHelper._groundTextureCDNUrl = \"https://assets.babylonjs.com/environments/backgroundGround.png\";\n /**\n * Default skybox texture URL.\n */\n EnvironmentHelper._skyboxTextureCDNUrl = \"https://assets.babylonjs.com/environments/backgroundSkybox.dds\";\n /**\n * Default environment texture URL.\n */\n EnvironmentHelper._environmentTextureCDNUrl = \"https://assets.babylonjs.com/environments/environmentSpecular.env\";\n return EnvironmentHelper;\n }());\n BABYLON.EnvironmentHelper = EnvironmentHelper;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.environmentHelper.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /** Internal class used to store shapes for emitters */\n var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {\n function ParticleSystemSetEmitterCreationOptions() {\n }\n return ParticleSystemSetEmitterCreationOptions;\n }());\n /**\n * Represents a set of particle systems working together to create a specific effect\n */\n var ParticleSystemSet = /** @class */ (function () {\n function ParticleSystemSet() {\n /**\n * Gets the particle system list\n */\n this.systems = new Array();\n }\n Object.defineProperty(ParticleSystemSet.prototype, \"emitterNode\", {\n /**\n * Gets the emitter node used with this set\n */\n get: function () {\n return this._emitterNode;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Creates a new emitter mesh as a sphere\n * @param options defines the options used to create the sphere\n * @param renderingGroupId defines the renderingGroupId to use for the sphere\n * @param scene defines the hosting scene\n */\n ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {\n if (this._emitterNode) {\n this._emitterNode.dispose();\n }\n this._emitterCreationOptions = {\n kind: \"Sphere\",\n options: options,\n renderingGroupId: renderingGroupId\n };\n var emitterMesh = BABYLON.MeshBuilder.CreateSphere(\"emitterSphere\", { diameter: options.diameter, segments: options.segments }, scene);\n emitterMesh.renderingGroupId = renderingGroupId;\n var material = new BABYLON.StandardMaterial(\"emitterSphereMaterial\", scene);\n material.emissiveColor = options.color;\n emitterMesh.material = material;\n for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {\n var system = _a[_i];\n system.emitter = emitterMesh;\n }\n this._emitterNode = emitterMesh;\n };\n /**\n * Starts all particle systems of the set\n * @param emitter defines an optional mesh to use as emitter for the particle systems\n */\n ParticleSystemSet.prototype.start = function (emitter) {\n for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {\n var system = _a[_i];\n if (emitter) {\n system.emitter = emitter;\n }\n system.start();\n }\n };\n /**\n * Release all associated resources\n */\n ParticleSystemSet.prototype.dispose = function () {\n for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {\n var system = _a[_i];\n system.dispose();\n }\n this.systems = [];\n if (this._emitterNode) {\n this._emitterNode.dispose();\n this._emitterNode = null;\n }\n };\n /**\n * Serialize the set into a JSON compatible object\n * @returns a JSON compatible representation of the set\n */\n ParticleSystemSet.prototype.serialize = function () {\n var result = {};\n result.systems = [];\n for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {\n var system = _a[_i];\n result.systems.push(system.serialize());\n }\n if (this._emitterNode) {\n result.emitter = this._emitterCreationOptions;\n }\n return result;\n };\n /**\n * Parse a new ParticleSystemSet from a serialized source\n * @param data defines a JSON compatible representation of the set\n * @param scene defines the hosting scene\n * @param gpu defines if we want GPU particles or CPU particles\n * @returns a new ParticleSystemSet\n */\n ParticleSystemSet.Parse = function (data, scene, gpu) {\n if (gpu === void 0) { gpu = false; }\n var result = new ParticleSystemSet();\n var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + \"/textures/\";\n scene = scene || BABYLON.Engine.LastCreatedScene;\n for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {\n var system = _a[_i];\n result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));\n }\n if (data.emitter) {\n var options = data.emitter.options;\n switch (data.emitter.kind) {\n case \"Sphere\":\n result.setEmitterAsSphere({\n diameter: options.diameter,\n segments: options.segments,\n color: BABYLON.Color3.FromArray(options.color)\n }, data.emitter.renderingGroupId, scene);\n break;\n }\n }\n return result;\n };\n return ParticleSystemSet;\n }());\n BABYLON.ParticleSystemSet = ParticleSystemSet;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.particleSystemSet.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * This class is made for on one-liner static method to help creating particle system set.\n */\n var ParticleHelper = /** @class */ (function () {\n function ParticleHelper() {\n }\n /**\n * Create a default particle system that you can tweak\n * @param emitter defines the emitter to use\n * @param capacity defines the system capacity (default is 500 particles)\n * @param scene defines the hosting scene\n * @returns the new Particle system\n */\n ParticleHelper.CreateDefault = function (emitter, capacity, scene) {\n if (capacity === void 0) { capacity = 500; }\n var system = new BABYLON.ParticleSystem(\"default system\", capacity, scene);\n system.emitter = emitter;\n system.particleTexture = new BABYLON.Texture(\"https://www.babylonjs.com/assets/Flare.png\", system.getScene());\n system.createConeEmitter(0.1, Math.PI / 4);\n // Particle color\n system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);\n system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);\n // Particle Size\n system.minSize = 0.1;\n system.maxSize = 0.1;\n // Emission speed\n system.minEmitPower = 2;\n system.maxEmitPower = 2;\n system.emitRate = 30;\n return system;\n };\n /**\n * This is the main static method (one-liner) of this helper to create different particle systems\n * @param type This string represents the type to the particle system to create\n * @param scene The scene where the particle system should live\n * @param gpu If the system will use gpu\n * @returns the ParticleSystemSet created\n */\n ParticleHelper.CreateAsync = function (type, scene, gpu) {\n if (gpu === void 0) { gpu = false; }\n if (!scene) {\n scene = BABYLON.Engine.LastCreatedScene;\n ;\n }\n var token = {};\n scene._addPendingData(token);\n return new Promise(function (resolve, reject) {\n if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {\n scene._removePendingData(token);\n return reject(\"Particle system with GPU is not supported.\");\n }\n BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + \"/systems/\" + type + \".json\", function (data, response) {\n scene._removePendingData(token);\n var newData = JSON.parse(data.toString());\n return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));\n }, undefined, undefined, undefined, function (req, exception) {\n scene._removePendingData(token);\n return reject(\"An error occured while the creation of your particle system. Check if your type '\" + type + \"' exists.\");\n });\n });\n };\n /**\n * Static function used to export a particle system to a ParticleSystemSet variable.\n * Please note that the emitter shape is not exported\n * @param system defines the particle systems to export\n */\n ParticleHelper.ExportSet = function (systems) {\n var set = new BABYLON.ParticleSystemSet();\n for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {\n var system = systems_1[_i];\n set.systems.push(system);\n }\n return set;\n };\n /**\n * Gets or sets base Assets URL\n */\n ParticleHelper.BaseAssetsUrl = \"https://assets.babylonjs.com/particles\";\n return ParticleHelper;\n }());\n BABYLON.ParticleHelper = ParticleHelper;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.particleHelper.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.\n * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.\n * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.\n * Potential additions to this helper include zoom and and non-infinite distance rendering effects.\n */\n var VideoDome = /** @class */ (function (_super) {\n __extends(VideoDome, _super);\n /**\n * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.\n * @param name Element's name, child elements will append suffixes for their own names.\n * @param urlsOrVideo defines the url(s) or the video element to use\n * @param options An object containing optional or exposed sub element properties\n */\n function VideoDome(name, urlsOrVideo, options, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._useDirectMapping = false;\n // set defaults and manage values\n name = name || \"videoDome\";\n options.resolution = (Math.abs(options.resolution) | 0) || 32;\n options.clickToPlay = Boolean(options.clickToPlay);\n options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);\n options.loop = options.loop === undefined ? true : Boolean(options.loop);\n options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);\n if (options.useDirectMapping === undefined) {\n _this._useDirectMapping = true;\n }\n else {\n _this._useDirectMapping = options.useDirectMapping;\n }\n _this._setReady(false);\n // create\n var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };\n var material = _this._material = new BABYLON.BackgroundMaterial(name + \"_material\", scene);\n var texture = _this._videoTexture = new BABYLON.VideoTexture(name + \"_texture\", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);\n _this._mesh = BABYLON.Mesh.CreateSphere(name + \"_mesh\", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);\n texture.onLoadObservable.addOnce(function () {\n _this._setReady(true);\n });\n // configure material\n material.useEquirectangularFOV = true;\n material.fovMultiplier = 1.0;\n material.opacityFresnel = false;\n if (_this._useDirectMapping) {\n texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n material.diffuseTexture = texture;\n }\n else {\n texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation\n texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n material.reflectionTexture = texture;\n }\n // configure mesh\n _this._mesh.material = material;\n _this._mesh.parent = _this;\n // optional configuration\n if (options.clickToPlay) {\n scene.onPointerUp = function () {\n _this._videoTexture.video.play();\n };\n }\n return _this;\n }\n Object.defineProperty(VideoDome.prototype, \"videoTexture\", {\n /**\n * Gets the video texture being displayed on the sphere\n */\n get: function () {\n return this._videoTexture;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(VideoDome.prototype, \"fovMultiplier\", {\n /**\n * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values \"zoom in\" and higher values \"zoom out\".\n * Also see the options.resolution property.\n */\n get: function () {\n return this._material.fovMultiplier;\n },\n set: function (value) {\n this._material.fovMultiplier = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n this._videoTexture.dispose();\n this._mesh.dispose();\n this._material.dispose();\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n return VideoDome;\n }(BABYLON.Node));\n BABYLON.VideoDome = VideoDome;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.videoDome.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.\n * As a subclass of Node, this allow parenting to the camera with different locations in the scene.\n * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.\n * Potential additions to this helper include zoom and and non-infinite distance rendering effects.\n */\n var PhotoDome = /** @class */ (function (_super) {\n __extends(PhotoDome, _super);\n /**\n * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.\n * @param name Element's name, child elements will append suffixes for their own names.\n * @param urlsOfPhoto define the url of the photo to display\n * @param options An object containing optional or exposed sub element properties\n */\n function PhotoDome(name, urlOfPhoto, options, scene) {\n var _this = _super.call(this, name, scene) || this;\n _this._useDirectMapping = false;\n // set defaults and manage values\n name = name || \"photoDome\";\n options.resolution = (Math.abs(options.resolution) | 0) || 32;\n options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);\n if (options.useDirectMapping === undefined) {\n _this._useDirectMapping = true;\n }\n else {\n _this._useDirectMapping = options.useDirectMapping;\n }\n _this._setReady(false);\n // create\n var material = _this._material = new BABYLON.BackgroundMaterial(name + \"_material\", scene);\n _this._mesh = BABYLON.Mesh.CreateSphere(name + \"_mesh\", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);\n // configure material\n material.opacityFresnel = false;\n material.useEquirectangularFOV = true;\n material.fovMultiplier = 1.0;\n _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);\n _this.photoTexture.onLoadObservable.addOnce(function () {\n _this._setReady(true);\n });\n // configure mesh\n _this._mesh.material = material;\n _this._mesh.parent = _this;\n return _this;\n }\n Object.defineProperty(PhotoDome.prototype, \"photoTexture\", {\n /**\n * Gets or sets the texture being displayed on the sphere\n */\n get: function () {\n return this._photoTexture;\n },\n set: function (value) {\n if (this._photoTexture === value) {\n return;\n }\n this._photoTexture = value;\n if (this._useDirectMapping) {\n this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._material.diffuseTexture = this._photoTexture;\n }\n else {\n this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation\n this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._material.reflectionTexture = this._photoTexture;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PhotoDome.prototype, \"fovMultiplier\", {\n /**\n * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values \"zoom in\" and higher values \"zoom out\".\n * Also see the options.resolution property.\n */\n get: function () {\n return this._material.fovMultiplier;\n },\n set: function (value) {\n this._material.fovMultiplier = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {\n if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }\n this._photoTexture.dispose();\n this._mesh.dispose();\n this._material.dispose();\n _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);\n };\n return PhotoDome;\n }(BABYLON.Node));\n BABYLON.PhotoDome = PhotoDome;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.photoDome.js.map\n\nvar BABYLON;\n(function (BABYLON) {\n BABYLON.Engine.prototype.createQuery = function () {\n return this._gl.createQuery();\n };\n BABYLON.Engine.prototype.deleteQuery = function (query) {\n this._gl.deleteQuery(query);\n return this;\n };\n BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {\n return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);\n };\n BABYLON.Engine.prototype.getQueryResult = function (query) {\n return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);\n };\n BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {\n var glAlgorithm = this._getGlAlgorithmType(algorithmType);\n this._gl.beginQuery(glAlgorithm, query);\n return this;\n };\n BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {\n var glAlgorithm = this._getGlAlgorithmType(algorithmType);\n this._gl.endQuery(glAlgorithm);\n return this;\n };\n BABYLON.Engine.prototype._createTimeQuery = function () {\n var timerQuery = this.getCaps().timerQuery;\n if (timerQuery.createQueryEXT) {\n return timerQuery.createQueryEXT();\n }\n return this.createQuery();\n };\n BABYLON.Engine.prototype._deleteTimeQuery = function (query) {\n var timerQuery = this.getCaps().timerQuery;\n if (timerQuery.deleteQueryEXT) {\n timerQuery.deleteQueryEXT(query);\n return;\n }\n this.deleteQuery(query);\n };\n BABYLON.Engine.prototype._getTimeQueryResult = function (query) {\n var timerQuery = this.getCaps().timerQuery;\n if (timerQuery.getQueryObjectEXT) {\n return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);\n }\n return this.getQueryResult(query);\n };\n BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {\n var timerQuery = this.getCaps().timerQuery;\n if (timerQuery.getQueryObjectEXT) {\n return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);\n }\n return this.isQueryResultAvailable(query);\n };\n BABYLON.Engine.prototype.startTimeQuery = function () {\n var caps = this.getCaps();\n var timerQuery = caps.timerQuery;\n if (!timerQuery) {\n return null;\n }\n var token = new BABYLON._TimeToken();\n this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);\n if (caps.canUseTimestampForTimerQuery) {\n token._startTimeQuery = this._createTimeQuery();\n timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);\n }\n else {\n if (this._currentNonTimestampToken) {\n return this._currentNonTimestampToken;\n }\n token._timeElapsedQuery = this._createTimeQuery();\n if (timerQuery.beginQueryEXT) {\n timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);\n }\n else {\n this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);\n }\n this._currentNonTimestampToken = token;\n }\n return token;\n };\n BABYLON.Engine.prototype.endTimeQuery = function (token) {\n var caps = this.getCaps();\n var timerQuery = caps.timerQuery;\n if (!timerQuery || !token) {\n return -1;\n }\n if (caps.canUseTimestampForTimerQuery) {\n if (!token._startTimeQuery) {\n return -1;\n }\n if (!token._endTimeQuery) {\n token._endTimeQuery = this._createTimeQuery();\n timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);\n }\n }\n else if (!token._timeElapsedQueryEnded) {\n if (!token._timeElapsedQuery) {\n return -1;\n }\n if (timerQuery.endQueryEXT) {\n timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);\n }\n else {\n this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);\n }\n token._timeElapsedQueryEnded = true;\n }\n var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);\n var available = false;\n if (token._endTimeQuery) {\n available = this._getTimeQueryAvailability(token._endTimeQuery);\n }\n else if (token._timeElapsedQuery) {\n available = this._getTimeQueryAvailability(token._timeElapsedQuery);\n }\n if (available && !disjoint) {\n var result = 0;\n if (caps.canUseTimestampForTimerQuery) {\n if (!token._startTimeQuery || !token._endTimeQuery) {\n return -1;\n }\n var timeStart = this._getTimeQueryResult(token._startTimeQuery);\n var timeEnd = this._getTimeQueryResult(token._endTimeQuery);\n result = timeEnd - timeStart;\n this._deleteTimeQuery(token._startTimeQuery);\n this._deleteTimeQuery(token._endTimeQuery);\n token._startTimeQuery = null;\n token._endTimeQuery = null;\n }\n else {\n if (!token._timeElapsedQuery) {\n return -1;\n }\n result = this._getTimeQueryResult(token._timeElapsedQuery);\n this._deleteTimeQuery(token._timeElapsedQuery);\n token._timeElapsedQuery = null;\n token._timeElapsedQueryEnded = false;\n this._currentNonTimestampToken = null;\n }\n return result;\n }\n return -1;\n };\n BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {\n return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;\n };\n // We also need to update AbstractMesh as there is a portion of the code there\n BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {\n var engine = this.getEngine();\n if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced\n this._isOccluded = false;\n return;\n }\n if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {\n this._isOccluded = false;\n return;\n }\n if (this.isOcclusionQueryInProgress && this._occlusionQuery) {\n var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);\n if (isOcclusionQueryAvailable) {\n var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);\n this._isOcclusionQueryInProgress = false;\n this._occlusionInternalRetryCounter = 0;\n this._isOccluded = occlusionQueryResult === 1 ? false : true;\n }\n else {\n this._occlusionInternalRetryCounter++;\n if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {\n this._isOcclusionQueryInProgress = false;\n this._occlusionInternalRetryCounter = 0;\n // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)\n // if strict continue the last state of the object.\n this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;\n }\n else {\n return;\n }\n }\n }\n var scene = this.getScene();\n if (scene.getBoundingBoxRenderer) {\n var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();\n if (!this._occlusionQuery) {\n this._occlusionQuery = engine.createQuery();\n }\n engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);\n occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);\n engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);\n this._isOcclusionQueryInProgress = true;\n }\n };\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.engine.occlusionQuery.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class used to generate noise procedural textures\n */\n var NoiseProceduralTexture = /** @class */ (function (_super) {\n __extends(NoiseProceduralTexture, _super);\n /**\n * Creates a new NoiseProceduralTexture\n * @param name defines the name fo the texture\n * @param size defines the size of the texture (default is 256)\n * @param scene defines the hosting scene\n * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created\n * @param generateMipMaps defines if mipmaps must be generated (true by default)\n */\n function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {\n if (size === void 0) { size = 256; }\n if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }\n var _this = _super.call(this, name, size, \"noise\", scene, fallbackTexture, generateMipMaps) || this;\n _this._time = 0;\n /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */\n _this.brightness = 0.2;\n /** Defines the number of octaves to process */\n _this.octaves = 3;\n /** Defines the level of persistence (0.8 by default) */\n _this.persistence = 0.8;\n /** Gets or sets animation speed factor (default is 1) */\n _this.animationSpeedFactor = 1;\n _this._updateShaderUniforms();\n return _this;\n }\n NoiseProceduralTexture.prototype._updateShaderUniforms = function () {\n var scene = this.getScene();\n if (!scene) {\n return;\n }\n this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;\n this.setFloat(\"brightness\", this.brightness);\n this.setInt(\"octaves\", this.octaves);\n this.setFloat(\"persistence\", this.persistence);\n this.setFloat(\"timeScale\", this._time);\n };\n /** Generate the current state of the procedural texture */\n NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {\n this._updateShaderUniforms();\n _super.prototype.render.call(this, useCameraPostProcess);\n };\n /**\n * Serializes this noise procedural texture\n * @returns a serialized noise procedural texture object\n */\n NoiseProceduralTexture.prototype.serialize = function () {\n var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));\n serializationObject.customType = \"BABYLON.NoiseProceduralTexture\";\n return serializationObject;\n };\n /**\n * Creates a NoiseProceduralTexture from parsed noise procedural texture data\n * @param parsedTexture defines parsed texture data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing noise procedural texture information\n * @returns a parsed NoiseProceduralTexture\n */\n NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {\n var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);\n return texture;\n };\n return NoiseProceduralTexture;\n }(BABYLON.ProceduralTexture));\n BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.noiseProceduralTexture.js.map\n\nBABYLON.Effect.ShadersStore={\"defaultVertexShader\":\"#include<__decl__defaultVertex>\\n\\n#define CUSTOM_VERTEX_BEGIN\\nattribute vec3 position;\\n#ifdef NORMAL\\nattribute vec3 normal;\\n#endif\\n#ifdef TANGENT\\nattribute vec4 tangent;\\n#endif\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#ifdef VERTEXCOLOR\\nattribute vec4 color;\\n#endif\\n#include\\n#include\\n\\n#include\\n#ifdef MAINUV1\\nvarying vec2 vMainUV1;\\n#endif\\n#ifdef MAINUV2\\nvarying vec2 vMainUV2;\\n#endif\\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\\nvarying vec2 vDiffuseUV;\\n#endif\\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\\nvarying vec2 vAmbientUV;\\n#endif\\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\\nvarying vec2 vOpacityUV;\\n#endif\\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\\nvarying vec2 vEmissiveUV;\\n#endif\\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\\nvarying vec2 vLightmapUV;\\n#endif\\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\\nvarying vec2 vSpecularUV;\\n#endif\\n#if defined(BUMP) && BUMPDIRECTUV == 0\\nvarying vec2 vBumpUV;\\n#endif\\n\\nvarying vec3 vPositionW;\\n#ifdef NORMAL\\nvarying vec3 vNormalW;\\n#endif\\n#ifdef VERTEXCOLOR\\nvarying vec4 vColor;\\n#endif\\n#include\\n#include\\n#include\\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\\n#include\\n#include[0..maxSimultaneousMorphTargets]\\n#ifdef REFLECTIONMAP_SKYBOX\\nvarying vec3 vPositionUVW;\\n#endif\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvarying vec3 vDirectionW;\\n#endif\\n#include\\n#define CUSTOM_VERTEX_DEFINITIONS\\nvoid main(void) {\\n#define CUSTOM_VERTEX_MAIN_BEGIN\\nvec3 positionUpdated=position;\\n#ifdef NORMAL \\nvec3 normalUpdated=normal;\\n#endif\\n#ifdef TANGENT\\nvec4 tangentUpdated=tangent;\\n#endif\\n#include[0..maxSimultaneousMorphTargets]\\n#ifdef REFLECTIONMAP_SKYBOX\\nvPositionUVW=positionUpdated;\\n#endif \\n#define CUSTOM_VERTEX_UPDATE_POSITION\\n#define CUSTOM_VERTEX_UPDATE_NORMAL\\n#include\\n#include\\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\\nvPositionW=vec3(worldPos);\\n#ifdef NORMAL\\nmat3 normalWorld=mat3(finalWorld);\\n#ifdef NONUNIFORMSCALING\\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\\n#endif\\nvNormalW=normalize(normalWorld*normalUpdated);\\n#endif\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\\n#endif\\n\\n#ifndef UV1\\nvec2 uv=vec2(0.,0.);\\n#endif\\n#ifndef UV2\\nvec2 uv2=vec2(0.,0.);\\n#endif\\n#ifdef MAINUV1\\nvMainUV1=uv;\\n#endif\\n#ifdef MAINUV2\\nvMainUV2=uv2;\\n#endif\\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\\nif (vDiffuseInfos.x == 0.)\\n{\\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\\nif (vAmbientInfos.x == 0.)\\n{\\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\\nif (vOpacityInfos.x == 0.)\\n{\\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\\nif (vEmissiveInfos.x == 0.)\\n{\\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\\nif (vLightmapInfos.x == 0.)\\n{\\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\\nif (vSpecularInfos.x == 0.)\\n{\\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(BUMP) && BUMPDIRECTUV == 0\\nif (vBumpInfos.x == 0.)\\n{\\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#include\\n#include\\n#include\\n#include[0..maxSimultaneousLights]\\n#ifdef VERTEXCOLOR\\n\\nvColor=color;\\n#endif\\n#include\\n#include\\n#define CUSTOM_VERTEX_MAIN_END\\n}\\n\",\"defaultPixelShader\":\"#include<__decl__defaultFragment>\\n#if defined(BUMP) || !defined(NORMAL)\\n#extension GL_OES_standard_derivatives : enable\\n#endif\\n#define CUSTOM_FRAGMENT_BEGIN\\n#ifdef LOGARITHMICDEPTH\\n#extension GL_EXT_frag_depth : enable\\n#endif\\n\\n#define RECIPROCAL_PI2 0.15915494\\nuniform vec3 vEyePosition;\\nuniform vec3 vAmbientColor;\\n\\nvarying vec3 vPositionW;\\n#ifdef NORMAL\\nvarying vec3 vNormalW;\\n#endif\\n#ifdef VERTEXCOLOR\\nvarying vec4 vColor;\\n#endif\\n#ifdef MAINUV1\\nvarying vec2 vMainUV1;\\n#endif\\n#ifdef MAINUV2\\nvarying vec2 vMainUV2;\\n#endif\\n\\n#include\\n\\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\\n#include\\n#include\\n\\n#ifdef DIFFUSE\\n#if DIFFUSEDIRECTUV == 1\\n#define vDiffuseUV vMainUV1\\n#elif DIFFUSEDIRECTUV == 2\\n#define vDiffuseUV vMainUV2\\n#else\\nvarying vec2 vDiffuseUV;\\n#endif\\nuniform sampler2D diffuseSampler;\\n#endif\\n#ifdef AMBIENT\\n#if AMBIENTDIRECTUV == 1\\n#define vAmbientUV vMainUV1\\n#elif AMBIENTDIRECTUV == 2\\n#define vAmbientUV vMainUV2\\n#else\\nvarying vec2 vAmbientUV;\\n#endif\\nuniform sampler2D ambientSampler;\\n#endif\\n#ifdef OPACITY \\n#if OPACITYDIRECTUV == 1\\n#define vOpacityUV vMainUV1\\n#elif OPACITYDIRECTUV == 2\\n#define vOpacityUV vMainUV2\\n#else\\nvarying vec2 vOpacityUV;\\n#endif\\nuniform sampler2D opacitySampler;\\n#endif\\n#ifdef EMISSIVE\\n#if EMISSIVEDIRECTUV == 1\\n#define vEmissiveUV vMainUV1\\n#elif EMISSIVEDIRECTUV == 2\\n#define vEmissiveUV vMainUV2\\n#else\\nvarying vec2 vEmissiveUV;\\n#endif\\nuniform sampler2D emissiveSampler;\\n#endif\\n#ifdef LIGHTMAP\\n#if LIGHTMAPDIRECTUV == 1\\n#define vLightmapUV vMainUV1\\n#elif LIGHTMAPDIRECTUV == 2\\n#define vLightmapUV vMainUV2\\n#else\\nvarying vec2 vLightmapUV;\\n#endif\\nuniform sampler2D lightmapSampler;\\n#endif\\n#ifdef REFRACTION\\n#ifdef REFRACTIONMAP_3D\\nuniform samplerCube refractionCubeSampler;\\n#else\\nuniform sampler2D refraction2DSampler;\\n#endif\\n#endif\\n#if defined(SPECULAR) && defined(SPECULARTERM)\\n#if SPECULARDIRECTUV == 1\\n#define vSpecularUV vMainUV1\\n#elif SPECULARDIRECTUV == 2\\n#define vSpecularUV vMainUV2\\n#else\\nvarying vec2 vSpecularUV;\\n#endif\\nuniform sampler2D specularSampler;\\n#endif\\n#ifdef ALPHATEST\\nuniform float alphaCutOff;\\n#endif\\n\\n#include\\n\\n#ifdef REFLECTION\\n#ifdef REFLECTIONMAP_3D\\nuniform samplerCube reflectionCubeSampler;\\n#else\\nuniform sampler2D reflection2DSampler;\\n#endif\\n#ifdef REFLECTIONMAP_SKYBOX\\nvarying vec3 vPositionUVW;\\n#else\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvarying vec3 vDirectionW;\\n#endif\\n#endif\\n#include\\n#endif\\n#include\\n#include\\n#include\\n#include\\n#include\\n#include\\n#define CUSTOM_FRAGMENT_DEFINITIONS\\nvoid main(void) {\\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\\n#include\\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\\n\\nvec4 baseColor=vec4(1.,1.,1.,1.);\\nvec3 diffuseColor=vDiffuseColor.rgb;\\n\\nfloat alpha=vDiffuseColor.a;\\n\\n#ifdef NORMAL\\nvec3 normalW=normalize(vNormalW);\\n#else\\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\\n#endif\\n#include\\n#ifdef TWOSIDEDLIGHTING\\nnormalW=gl_FrontFacing ? normalW : -normalW;\\n#endif\\n#ifdef DIFFUSE\\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\\n#ifdef ALPHATEST\\nif (baseColor.a\\n#ifdef VERTEXCOLOR\\nbaseColor.rgb*=vColor.rgb;\\n#endif\\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\\n\\nvec3 baseAmbientColor=vec3(1.,1.,1.);\\n#ifdef AMBIENT\\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\\n#endif\\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\\n\\n#ifdef SPECULARTERM\\nfloat glossiness=vSpecularColor.a;\\nvec3 specularColor=vSpecularColor.rgb;\\n#ifdef SPECULAR\\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\\nspecularColor=specularMapColor.rgb;\\n#ifdef GLOSSINESS\\nglossiness=glossiness*specularMapColor.a;\\n#endif\\n#endif\\n#else\\nfloat glossiness=0.;\\n#endif\\n\\nvec3 diffuseBase=vec3(0.,0.,0.);\\nlightingInfo info;\\n#ifdef SPECULARTERM\\nvec3 specularBase=vec3(0.,0.,0.);\\n#endif\\nfloat shadow=1.;\\n#ifdef LIGHTMAP\\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\\n#endif\\n#include[0..maxSimultaneousLights]\\n\\nvec3 refractionColor=vec3(0.,0.,0.);\\n#ifdef REFRACTION\\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\\n#ifdef REFRACTIONMAP_3D\\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\\nif (dot(refractionVector,viewDirectionW)<1.0) {\\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\\n}\\n#else\\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\\nrefractionCoords.y=1.0-refractionCoords.y;\\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\\n#endif\\n#ifdef IS_REFRACTION_LINEAR\\nrefractionColor=toGammaSpace(refractionColor);\\n#endif\\nrefractionColor*=vRefractionInfos.x;\\n#endif\\n\\nvec3 reflectionColor=vec3(0.,0.,0.);\\n#ifdef REFLECTION\\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\\n#ifdef REFLECTIONMAP_3D\\n#ifdef ROUGHNESS\\nfloat bias=vReflectionInfos.y;\\n#ifdef SPECULARTERM\\n#ifdef SPECULAR\\n#ifdef GLOSSINESS\\nbias*=(1.0-specularMapColor.a);\\n#endif\\n#endif\\n#endif\\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\\n#else\\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\\n#endif\\n#else\\nvec2 coords=vReflectionUVW.xy;\\n#ifdef REFLECTIONMAP_PROJECTION\\ncoords/=vReflectionUVW.z;\\n#endif\\ncoords.y=1.0-coords.y;\\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\\n#endif\\n#ifdef IS_REFLECTION_LINEAR\\nreflectionColor=toGammaSpace(reflectionColor);\\n#endif\\nreflectionColor*=vReflectionInfos.x;\\n#ifdef REFLECTIONFRESNEL\\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\\n#ifdef REFLECTIONFRESNELFROMSPECULAR\\n#ifdef SPECULARTERM\\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\\n#else\\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\\n#endif\\n#else\\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\\n#endif\\n#endif\\n#endif\\n#ifdef REFRACTIONFRESNEL\\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\\n#endif\\n#ifdef OPACITY\\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\\n#ifdef OPACITYRGB\\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\\n#else\\nalpha*=opacityMap.a*vOpacityInfos.y;\\n#endif\\n#endif\\n#ifdef VERTEXALPHA\\nalpha*=vColor.a;\\n#endif\\n#ifdef OPACITYFRESNEL\\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\\n#endif\\n\\nvec3 emissiveColor=vEmissiveColor;\\n#ifdef EMISSIVE\\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\\n#endif\\n#ifdef EMISSIVEFRESNEL\\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\\n#endif\\n\\n#ifdef DIFFUSEFRESNEL\\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\\n#endif\\n\\n#ifdef EMISSIVEASILLUMINATION\\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\\n#else\\n#ifdef LINKEMISSIVEWITHDIFFUSE\\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\\n#else\\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\\n#endif\\n#endif\\n#ifdef SPECULARTERM\\nvec3 finalSpecular=specularBase*specularColor;\\n#ifdef SPECULAROVERALPHA\\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\\n#endif\\n#else\\nvec3 finalSpecular=vec3(0.0);\\n#endif\\n#ifdef REFLECTIONOVERALPHA\\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\\n#endif\\n\\n#ifdef EMISSIVEASILLUMINATION\\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\\n#else\\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\\n#endif\\n\\n#ifdef LIGHTMAP\\n#ifndef LIGHTMAPEXCLUDED\\n#ifdef USELIGHTMAPASSHADOWMAP\\ncolor.rgb*=lightmapColor;\\n#else\\ncolor.rgb+=lightmapColor;\\n#endif\\n#endif\\n#endif\\n#define CUSTOM_FRAGMENT_BEFORE_FOG\\ncolor.rgb=max(color.rgb,0.);\\n#include\\n#include\\n\\n\\n#ifdef IMAGEPROCESSINGPOSTPROCESS\\ncolor.rgb=toLinearSpace(color.rgb);\\n#else\\n#ifdef IMAGEPROCESSING\\ncolor.rgb=toLinearSpace(color.rgb);\\ncolor=applyImageProcessing(color);\\n#endif\\n#endif\\n#ifdef PREMULTIPLYALPHA\\n\\ncolor.rgb*=color.a;\\n#endif\\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\\ngl_FragColor=color;\\n}\\n\",\"pbrVertexShader\":\"precision highp float;\\n#include<__decl__pbrVertex>\\n\\nattribute vec3 position;\\n#ifdef NORMAL\\nattribute vec3 normal;\\n#endif\\n#ifdef TANGENT\\nattribute vec4 tangent;\\n#endif\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#ifdef MAINUV1\\nvarying vec2 vMainUV1;\\n#endif\\n#ifdef MAINUV2\\nvarying vec2 vMainUV2; \\n#endif \\n#ifdef VERTEXCOLOR\\nattribute vec4 color;\\n#endif\\n#include\\n#include\\n\\n#include\\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\\nvarying vec2 vAlbedoUV;\\n#endif\\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\\nvarying vec2 vAmbientUV;\\n#endif\\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\\nvarying vec2 vOpacityUV;\\n#endif\\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\\nvarying vec2 vEmissiveUV;\\n#endif\\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\\nvarying vec2 vLightmapUV;\\n#endif\\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\\nvarying vec2 vReflectivityUV;\\n#endif\\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\\nvarying vec2 vMicroSurfaceSamplerUV;\\n#endif\\n#if defined(BUMP) && BUMPDIRECTUV == 0\\nvarying vec2 vBumpUV;\\n#endif\\n\\nvarying vec3 vPositionW;\\n#ifdef NORMAL\\nvarying vec3 vNormalW;\\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\\nvarying vec3 vEnvironmentIrradiance;\\n#include\\n#endif\\n#endif\\n#ifdef VERTEXCOLOR\\nvarying vec4 vColor;\\n#endif\\n#include\\n#include\\n#include\\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\\n#include\\n#include[0..maxSimultaneousMorphTargets]\\n#ifdef REFLECTIONMAP_SKYBOX\\nvarying vec3 vPositionUVW;\\n#endif\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvarying vec3 vDirectionW;\\n#endif\\n#include\\nvoid main(void) {\\nvec3 positionUpdated=position;\\n#ifdef NORMAL\\nvec3 normalUpdated=normal;\\n#endif\\n#ifdef TANGENT\\nvec4 tangentUpdated=tangent;\\n#endif\\n#include[0..maxSimultaneousMorphTargets]\\n#ifdef REFLECTIONMAP_SKYBOX\\nvPositionUVW=positionUpdated;\\n#endif \\n#include\\n#include\\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\\nvPositionW=vec3(worldPos);\\n#ifdef NORMAL\\nmat3 normalWorld=mat3(finalWorld);\\n#ifdef NONUNIFORMSCALING\\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\\n#endif\\nvNormalW=normalize(normalWorld*normalUpdated);\\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\\n#ifdef REFLECTIONMAP_OPPOSITEZ\\nreflectionVector.z*=-1.0;\\n#endif\\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\\n#endif\\n#endif\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\\n#endif\\n\\n#ifndef UV1\\nvec2 uv=vec2(0.,0.);\\n#endif\\n#ifndef UV2\\nvec2 uv2=vec2(0.,0.);\\n#endif\\n#ifdef MAINUV1\\nvMainUV1=uv;\\n#endif \\n#ifdef MAINUV2\\nvMainUV2=uv2;\\n#endif \\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \\nif (vAlbedoInfos.x == 0.)\\n{\\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \\nif (vAmbientInfos.x == 0.)\\n{\\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \\nif (vOpacityInfos.x == 0.)\\n{\\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \\nif (vEmissiveInfos.x == 0.)\\n{\\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \\nif (vLightmapInfos.x == 0.)\\n{\\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \\nif (vReflectivityInfos.x == 0.)\\n{\\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \\nif (vMicroSurfaceSamplerInfos.x == 0.)\\n{\\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n#if defined(BUMP) && BUMPDIRECTUV == 0 \\nif (vBumpInfos.x == 0.)\\n{\\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n\\n#include\\n\\n#include\\n\\n#include\\n\\n#include[0..maxSimultaneousLights]\\n\\n#ifdef VERTEXCOLOR\\nvColor=color;\\n#endif\\n\\n#ifdef POINTSIZE\\ngl_PointSize=pointSize;\\n#endif\\n\\n#include\\n}\",\"pbrPixelShader\":\"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\\n#extension GL_OES_standard_derivatives : enable\\n#endif\\n#ifdef LODBASEDMICROSFURACE\\n#extension GL_EXT_shader_texture_lod : enable\\n#endif\\n#ifdef LOGARITHMICDEPTH\\n#extension GL_EXT_frag_depth : enable\\n#endif\\nprecision highp float;\\n#include<__decl__pbrFragment>\\nuniform vec4 vEyePosition;\\nuniform vec3 vAmbientColor;\\nuniform vec4 vCameraInfos;\\n\\nvarying vec3 vPositionW;\\n#ifdef MAINUV1\\nvarying vec2 vMainUV1;\\n#endif \\n#ifdef MAINUV2 \\nvarying vec2 vMainUV2;\\n#endif \\n#ifdef NORMAL\\nvarying vec3 vNormalW;\\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\\nvarying vec3 vEnvironmentIrradiance;\\n#endif\\n#endif\\n#ifdef VERTEXCOLOR\\nvarying vec4 vColor;\\n#endif\\n\\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\\n\\n#ifdef ALBEDO\\n#if ALBEDODIRECTUV == 1\\n#define vAlbedoUV vMainUV1\\n#elif ALBEDODIRECTUV == 2\\n#define vAlbedoUV vMainUV2\\n#else\\nvarying vec2 vAlbedoUV;\\n#endif\\nuniform sampler2D albedoSampler;\\n#endif\\n#ifdef AMBIENT\\n#if AMBIENTDIRECTUV == 1\\n#define vAmbientUV vMainUV1\\n#elif AMBIENTDIRECTUV == 2\\n#define vAmbientUV vMainUV2\\n#else\\nvarying vec2 vAmbientUV;\\n#endif\\nuniform sampler2D ambientSampler;\\n#endif\\n#ifdef OPACITY\\n#if OPACITYDIRECTUV == 1\\n#define vOpacityUV vMainUV1\\n#elif OPACITYDIRECTUV == 2\\n#define vOpacityUV vMainUV2\\n#else\\nvarying vec2 vOpacityUV;\\n#endif\\nuniform sampler2D opacitySampler;\\n#endif\\n#ifdef EMISSIVE\\n#if EMISSIVEDIRECTUV == 1\\n#define vEmissiveUV vMainUV1\\n#elif EMISSIVEDIRECTUV == 2\\n#define vEmissiveUV vMainUV2\\n#else\\nvarying vec2 vEmissiveUV;\\n#endif\\nuniform sampler2D emissiveSampler;\\n#endif\\n#ifdef LIGHTMAP\\n#if LIGHTMAPDIRECTUV == 1\\n#define vLightmapUV vMainUV1\\n#elif LIGHTMAPDIRECTUV == 2\\n#define vLightmapUV vMainUV2\\n#else\\nvarying vec2 vLightmapUV;\\n#endif\\nuniform sampler2D lightmapSampler;\\n#endif\\n#ifdef REFLECTIVITY\\n#if REFLECTIVITYDIRECTUV == 1\\n#define vReflectivityUV vMainUV1\\n#elif REFLECTIVITYDIRECTUV == 2\\n#define vReflectivityUV vMainUV2\\n#else\\nvarying vec2 vReflectivityUV;\\n#endif\\nuniform sampler2D reflectivitySampler;\\n#endif\\n#ifdef MICROSURFACEMAP\\n#if MICROSURFACEMAPDIRECTUV == 1\\n#define vMicroSurfaceSamplerUV vMainUV1\\n#elif MICROSURFACEMAPDIRECTUV == 2\\n#define vMicroSurfaceSamplerUV vMainUV2\\n#else\\nvarying vec2 vMicroSurfaceSamplerUV;\\n#endif\\nuniform sampler2D microSurfaceSampler;\\n#endif\\n\\n#ifdef REFRACTION\\n#ifdef REFRACTIONMAP_3D\\n#define sampleRefraction(s,c) textureCube(s,c)\\nuniform samplerCube refractionSampler;\\n#ifdef LODBASEDMICROSFURACE\\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\\n#else\\nuniform samplerCube refractionSamplerLow;\\nuniform samplerCube refractionSamplerHigh;\\n#endif\\n#else\\n#define sampleRefraction(s,c) texture2D(s,c)\\nuniform sampler2D refractionSampler;\\n#ifdef LODBASEDMICROSFURACE\\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\\n#else\\nuniform samplerCube refractionSamplerLow;\\nuniform samplerCube refractionSamplerHigh;\\n#endif\\n#endif\\n#endif\\n\\n#ifdef REFLECTION\\n#ifdef REFLECTIONMAP_3D\\n#define sampleReflection(s,c) textureCube(s,c)\\nuniform samplerCube reflectionSampler;\\n#ifdef LODBASEDMICROSFURACE\\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\\n#else\\nuniform samplerCube reflectionSamplerLow;\\nuniform samplerCube reflectionSamplerHigh;\\n#endif\\n#else\\n#define sampleReflection(s,c) texture2D(s,c)\\nuniform sampler2D reflectionSampler;\\n#ifdef LODBASEDMICROSFURACE\\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\\n#else\\nuniform samplerCube reflectionSamplerLow;\\nuniform samplerCube reflectionSamplerHigh;\\n#endif\\n#endif\\n#ifdef REFLECTIONMAP_SKYBOX\\nvarying vec3 vPositionUVW;\\n#else\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvarying vec3 vDirectionW;\\n#endif\\n#endif\\n#include\\n#endif\\n#ifdef ENVIRONMENTBRDF\\nuniform sampler2D environmentBrdfSampler;\\n#endif\\n\\n#ifndef FROMLINEARSPACE\\n#define FROMLINEARSPACE;\\n#endif\\n#include\\n#include\\n#include\\n\\n#include\\n#include\\n#include\\n#include\\n#include\\n#include\\n#include\\n\\n#include\\nvoid main(void) {\\n#include\\n\\n\\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\\n#ifdef NORMAL\\nvec3 normalW=normalize(vNormalW);\\n#else\\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\\n#endif\\n#include\\n#ifdef SPECULARAA\\nvec3 nDfdx=dFdx(normalW.xyz);\\nvec3 nDfdy=dFdy(normalW.xyz);\\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\\n\\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\\n\\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\\n#else\\nfloat geometricRoughnessFactor=0.;\\n#endif\\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\\n#if defined(TWOSIDEDLIGHTING)\\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\\n#endif\\nnormalW*=sign(dot(normalW,faceNormal));\\n#endif\\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\\nnormalW=gl_FrontFacing ? normalW : -normalW;\\n#endif\\n\\n\\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\\n\\nfloat alpha=vAlbedoColor.a;\\n#ifdef ALBEDO\\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\\nalpha*=albedoTexture.a;\\n#endif\\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\\nsurfaceAlbedo*=vAlbedoInfos.y;\\n#endif\\n\\n#ifdef OPACITY\\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\\n#ifdef OPACITYRGB\\nalpha=getLuminance(opacityMap.rgb);\\n#else\\nalpha*=opacityMap.a;\\n#endif\\nalpha*=vOpacityInfos.y;\\n#endif\\n#ifdef VERTEXALPHA\\nalpha*=vColor.a;\\n#endif\\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\\n#ifdef ALPHATEST\\nif (alpha\\n#ifdef VERTEXCOLOR\\nsurfaceAlbedo*=vColor.rgb;\\n#endif\\n\\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\\n#ifdef AMBIENT\\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\\n#ifdef AMBIENTINGRAYSCALE\\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\\n#endif\\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\\n#endif\\n#ifdef UNLIT\\nvec3 diffuseBase=vec3(1.,1.,1.);\\n#else\\n\\nfloat microSurface=vReflectivityColor.a;\\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\\n#ifdef METALLICWORKFLOW\\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\\n#ifdef REFLECTIVITY\\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\\n#ifdef AOSTOREINMETALMAPRED\\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\\n#endif\\n#ifdef METALLNESSSTOREINMETALMAPBLUE\\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\\n#else\\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\\n#endif\\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\\n#else\\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\\n#endif\\n#endif\\n#endif\\n#ifdef MICROSURFACEMAP\\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\\nmetallicRoughness.g*=microSurfaceTexel.r;\\n#endif\\n\\nmicroSurface=1.0-metallicRoughness.g;\\n\\nvec3 baseColor=surfaceAlbedo;\\n\\n\\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\\n\\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\\n\\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\\n#else\\n#ifdef REFLECTIVITY\\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\\nsurfaceReflectivityColor*=vReflectivityInfos.y;\\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\\nmicroSurface*=surfaceReflectivityColorMap.a;\\nmicroSurface*=vReflectivityInfos.z;\\n#else\\n#ifdef MICROSURFACEAUTOMATIC\\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\\n#endif\\n#ifdef MICROSURFACEMAP\\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\\nmicroSurface*=microSurfaceTexel.r;\\n#endif\\n#endif\\n#endif\\n#endif\\n\\nmicroSurface=clamp(microSurface,0.,1.);\\n\\nfloat roughness=1.-microSurface;\\n\\n#ifdef ALPHAFRESNEL\\n#if defined(ALPHATEST) || defined(ALPHABLEND)\\n\\n\\n\\nfloat opacityPerceptual=alpha;\\n#ifdef LINEARALPHAFRESNEL\\nfloat opacity0=opacityPerceptual;\\n#else\\nfloat opacity0=opacityPerceptual*opacityPerceptual;\\n#endif\\nfloat opacity90=fresnelGrazingReflectance(opacity0);\\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\\n\\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\\n#ifdef ALPHATEST\\nif (alpha[0..maxSimultaneousLights]\\n\\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\\n\\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\\n\\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\\n#ifdef RADIANCEOCCLUSION\\n#ifdef AMBIENTINGRAYSCALE\\nfloat ambientMonochrome=ambientOcclusionColor.r;\\n#else\\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\\n#endif\\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\\nspecularEnvironmentReflectance*=seo;\\n#endif\\n#ifdef HORIZONOCCLUSION\\n#ifdef BUMP\\n#ifdef REFLECTIONMAP_3D\\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\\nspecularEnvironmentReflectance*=eho;\\n#endif\\n#endif\\n#endif\\n#else\\n\\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\\n#endif\\n\\n#ifdef REFRACTION\\nvec3 refractance=vec3(0.0,0.0,0.0);\\nvec3 transmission=vec3(1.0,1.0,1.0);\\n#ifdef LINKREFRACTIONTOTRANSPARENCY\\n\\ntransmission*=(1.0-alpha);\\n\\n\\nvec3 mixedAlbedo=surfaceAlbedo;\\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\\n\\nsurfaceAlbedo*=alpha;\\n\\nenvironmentIrradiance*=alpha;\\n\\nenvironmentRefraction.rgb*=tint;\\n\\nalpha=1.0;\\n#endif\\n\\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\\n\\ntransmission*=1.0-specularEnvironmentReflectance;\\n\\nrefractance=transmission;\\n#endif\\n\\n\\n\\n\\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\\n\\n#ifdef REFLECTION\\nvec3 finalIrradiance=environmentIrradiance;\\nfinalIrradiance*=surfaceAlbedo.rgb;\\n#endif\\n\\n#ifdef SPECULARTERM\\nvec3 finalSpecular=specularBase;\\nfinalSpecular=max(finalSpecular,0.0);\\n\\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\\n#endif\\n\\n#ifdef REFLECTION\\nvec3 finalRadiance=environmentRadiance.rgb;\\nfinalRadiance*=specularEnvironmentReflectance;\\n\\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\\n#endif\\n\\n#ifdef REFRACTION\\nvec3 finalRefraction=environmentRefraction.rgb;\\nfinalRefraction*=refractance;\\n#endif\\n\\n#ifdef ALPHABLEND\\nfloat luminanceOverAlpha=0.0;\\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\\n#endif\\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\\n#endif\\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\\n#endif\\n#endif\\n#endif\\n\\nvec3 finalDiffuse=diffuseBase;\\nfinalDiffuse.rgb+=vAmbientColor;\\nfinalDiffuse*=surfaceAlbedo.rgb;\\nfinalDiffuse=max(finalDiffuse,0.0);\\n\\nvec3 finalEmissive=vEmissiveColor;\\n#ifdef EMISSIVE\\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\\nfinalEmissive*=vEmissiveInfos.y;\\n#endif\\n\\n\\n\\nvec4 finalColor=vec4(\\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\\n#ifndef UNLIT\\n#ifdef REFLECTION\\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\\n#endif\\n#ifdef SPECULARTERM\\n\\n\\nfinalSpecularScaled +\\n#endif\\n#ifdef REFLECTION\\n\\n\\nfinalRadianceScaled +\\n#endif\\n#ifdef REFRACTION\\nfinalRefraction*vLightingIntensity.z +\\n#endif\\n#endif\\nfinalEmissive*vLightingIntensity.y,\\nalpha);\\n\\n#ifdef LIGHTMAP\\n#ifndef LIGHTMAPEXCLUDED\\n#ifdef USELIGHTMAPASSHADOWMAP\\nfinalColor.rgb*=lightmapColor;\\n#else\\nfinalColor.rgb+=lightmapColor;\\n#endif\\n#endif\\n#endif\\n\\nfinalColor=max(finalColor,0.0);\\n#include\\n#include(color,finalColor)\\n#ifdef IMAGEPROCESSINGPOSTPROCESS\\n\\n\\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\\n#else\\n\\nfinalColor=applyImageProcessing(finalColor);\\n#endif\\n#ifdef PREMULTIPLYALPHA\\n\\nfinalColor.rgb*=finalColor.a;\\n#endif\\ngl_FragColor=finalColor;\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n}\",\"rgbdEncodePixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n#include\\nvoid main(void) \\n{\\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\\n}\",\"rgbdDecodePixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n#include\\nvoid main(void) \\n{\\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\\n}\",\"spritesVertexShader\":\"\\nattribute vec4 position;\\nattribute vec4 options;\\nattribute vec4 cellInfo;\\nattribute vec4 color;\\n\\nuniform vec2 textureInfos;\\nuniform mat4 view;\\nuniform mat4 projection;\\n\\nvarying vec2 vUV;\\nvarying vec4 vColor;\\n#include\\nvoid main(void) { \\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \\nvec2 cornerPos;\\nfloat angle=position.w;\\nvec2 size=vec2(options.x,options.y);\\nvec2 offset=options.zw;\\nvec2 uvScale=textureInfos.xy;\\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\\n\\nvec3 rotatedCorner;\\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nrotatedCorner.z=0.;\\n\\nviewPos+=rotatedCorner;\\ngl_Position=projection*vec4(viewPos,1.0); \\n\\nvColor=color;\\n\\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\\nvUV=(uvOffset+cellInfo.zw)*uvScale;\\n\\n#ifdef FOG\\nvFogDistance=viewPos;\\n#endif\\n}\",\"spritesPixelShader\":\"uniform bool alphaTest;\\nvarying vec4 vColor;\\n\\nvarying vec2 vUV;\\nuniform sampler2D diffuseSampler;\\n\\n#include\\nvoid main(void) {\\nvec4 color=texture2D(diffuseSampler,vUV);\\nif (alphaTest) \\n{\\nif (color.a<0.95)\\ndiscard;\\n}\\ncolor*=vColor;\\n#include\\ngl_FragColor=color;\\n}\",\"particlesVertexShader\":\"\\nattribute vec3 position;\\nattribute vec4 color;\\nattribute float angle;\\nattribute vec2 size;\\n#ifdef ANIMATESHEET \\nattribute float cellIndex;\\n#endif\\n#ifndef BILLBOARD \\nattribute vec3 direction;\\n#endif\\nattribute vec2 offset;\\n\\nuniform mat4 view;\\nuniform mat4 projection;\\nuniform vec2 translationPivot;\\n#ifdef ANIMATESHEET \\nuniform vec3 particlesInfos; \\n#endif\\n\\nvarying vec2 vUV;\\nvarying vec4 vColor;\\n#ifdef CLIPPLANE\\nuniform vec4 vClipPlane;\\nuniform mat4 invView;\\nvarying float fClipDistance;\\n#endif\\n#ifdef BILLBOARD\\nuniform vec3 eyePosition; \\n#endif\\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\\nvec3 zaxis=normalize(cross(yaxis,xaxis));\\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\\nmat3 rotMatrix=mat3(row0,row1,row2);\\nvec3 alignedCorner=rotMatrix*rotatedCorner;\\nreturn position+alignedCorner; \\n}\\nvoid main(void) { \\nvec2 cornerPos;\\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\\n#ifdef BILLBOARD \\n\\nvec3 rotatedCorner;\\n#ifdef BILLBOARDY \\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nrotatedCorner.y=0.;\\nvec3 yaxis=position-eyePosition;\\nyaxis.y=0.;\\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \\n#else\\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nrotatedCorner.z=0.;\\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \\n#endif\\n\\ngl_Position=projection*vec4(viewPos,1.0); \\n#else\\n\\nvec3 rotatedCorner;\\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nrotatedCorner.y=0.;\\nvec3 yaxis=normalize(direction);\\nvec3 worldPos=rotate(yaxis,rotatedCorner);\\ngl_Position=projection*view*vec4(worldPos,1.0); \\n#endif \\nvColor=color;\\n#ifdef ANIMATESHEET\\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\\nvec2 uvScale=particlesInfos.xy;\\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\\n#else\\nvUV=offset;\\n#endif\\n\\n#ifdef CLIPPLANE\\nvec4 worldPos=invView*vec4(viewPos,1.0);\\nfClipDistance=dot(worldPos,vClipPlane);\\n#endif\\n}\",\"particlesPixelShader\":\"\\nvarying vec2 vUV;\\nvarying vec4 vColor;\\nuniform vec4 textureMask;\\nuniform sampler2D diffuseSampler;\\n#ifdef CLIPPLANE\\nvarying float fClipDistance;\\n#endif\\nvoid main(void) {\\n#ifdef CLIPPLANE\\nif (fClipDistance>0.0)\\ndiscard;\\n#endif\\nvec4 baseColor=texture2D(diffuseSampler,vUV);\\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\\n}\",\"colorVertexShader\":\"\\nattribute vec3 position;\\n#ifdef VERTEXCOLOR\\nattribute vec4 color;\\n#endif\\n#include\\n\\nuniform mat4 viewProjection;\\nuniform mat4 world;\\n\\n#ifdef VERTEXCOLOR\\nvarying vec4 vColor;\\n#endif\\nvoid main(void) {\\nmat4 finalWorld=world;\\n#include\\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\\n#ifdef VERTEXCOLOR\\n\\nvColor=color;\\n#endif\\n}\",\"colorPixelShader\":\"#ifdef VERTEXCOLOR\\nvarying vec4 vColor;\\n#else\\nuniform vec4 color;\\n#endif\\nvoid main(void) {\\n#ifdef VERTEXCOLOR\\ngl_FragColor=vColor;\\n#else\\ngl_FragColor=color;\\n#endif\\n}\",\"gpuRenderParticlesVertexShader\":\"#version 300 es\\nuniform mat4 view;\\nuniform mat4 projection;\\nuniform vec2 translationPivot;\\n\\nin vec3 position;\\nin float age;\\nin float life;\\nin vec3 size;\\n#ifndef BILLBOARD\\nin vec3 initialDirection;\\n#endif\\nin float angle;\\n#ifdef ANIMATESHEET\\nin float cellIndex;\\n#endif\\nin vec2 offset;\\nin vec2 uv;\\nout vec2 vUV;\\nout vec4 vColor;\\n#ifdef CLIPPLANE\\nuniform vec4 vClipPlane;\\nuniform mat4 invView;\\nout float fClipDistance;\\n#endif\\n#ifdef COLORGRADIENTS\\nuniform sampler2D colorGradientSampler;\\n#else\\nuniform vec4 colorDead;\\nin vec4 color;\\n#endif\\n#ifdef ANIMATESHEET\\nuniform vec3 sheetInfos;\\n#endif\\n#ifdef BILLBOARD\\nuniform vec3 eyePosition; \\n#endif\\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\\nvec3 zaxis=normalize(cross(yaxis,xaxis));\\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\\nmat3 rotMatrix=mat3(row0,row1,row2);\\nvec3 alignedCorner=rotMatrix*rotatedCorner;\\nreturn position+alignedCorner;\\n}\\nvoid main() {\\n#ifdef ANIMATESHEET\\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\\nvec2 uvScale=sheetInfos.xy;\\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\\n#else \\nvUV=uv;\\n#endif\\nfloat ratio=age/life;\\n#ifdef COLORGRADIENTS\\nvColor=texture(colorGradientSampler,vec2(ratio,0));\\n#else\\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\\n#endif\\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\\n#ifdef BILLBOARD\\nvec4 rotatedCorner;\\nrotatedCorner.w=0.;\\n#ifdef BILLBOARDY \\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nrotatedCorner.y=0.;\\nvec3 yaxis=position-eyePosition;\\nyaxis.y=0.;\\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \\n#else\\n\\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nrotatedCorner.z=0.;\\n\\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\\n#endif\\n#else\\n\\nvec3 rotatedCorner;\\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\\nrotatedCorner.y=0.;\\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\\nvec3 yaxis=normalize(initialDirection);\\nvec3 worldPos=rotate(yaxis,rotatedCorner);\\n\\nvec4 viewPosition=view*vec4(worldPos,1.0); \\n#endif\\ngl_Position=projection*viewPosition;\\n\\n#ifdef CLIPPLANE\\nvec4 worldPos=invView*viewPosition;\\nfClipDistance=dot(worldPos,vClipPlane);\\n#endif \\n}\",\"gpuRenderParticlesPixelShader\":\"#version 300 es\\nuniform sampler2D textureSampler;\\nin vec2 vUV;\\nin vec4 vColor;\\nout vec4 outFragColor;\\n#ifdef CLIPPLANE\\nin float fClipDistance;\\n#endif\\nvoid main() {\\n#ifdef CLIPPLANE\\nif (fClipDistance>0.0)\\ndiscard;\\n#endif \\noutFragColor=texture(textureSampler,vUV)*vColor;\\n}\\n\",\"gpuUpdateParticlesVertexShader\":\"#version 300 es\\n#define PI 3.14159\\nuniform float currentCount;\\nuniform float timeDelta;\\nuniform float stopFactor;\\nuniform mat4 emitterWM;\\nuniform vec2 lifeTime;\\nuniform vec2 emitPower;\\nuniform vec2 sizeRange;\\nuniform vec4 scaleRange;\\n#ifndef COLORGRADIENTS\\nuniform vec4 color1;\\nuniform vec4 color2;\\n#endif\\nuniform vec3 gravity;\\nuniform sampler2D randomSampler;\\nuniform sampler2D randomSampler2;\\nuniform vec4 angleRange;\\n#ifdef BOXEMITTER\\nuniform vec3 direction1;\\nuniform vec3 direction2;\\nuniform vec3 minEmitBox;\\nuniform vec3 maxEmitBox;\\n#endif\\n#ifdef POINTEMITTER\\nuniform vec3 direction1;\\nuniform vec3 direction2;\\n#endif\\n#ifdef SPHEREEMITTER\\nuniform float radius;\\nuniform float radiusRange;\\n#ifdef DIRECTEDSPHEREEMITTER\\nuniform vec3 direction1;\\nuniform vec3 direction2;\\n#else\\nuniform float directionRandomizer;\\n#endif\\n#endif\\n#ifdef CONEEMITTER\\nuniform vec2 radius;\\nuniform float coneAngle;\\nuniform vec2 height;\\nuniform float directionRandomizer;\\n#endif\\n\\nin vec3 position;\\nin float age;\\nin float life;\\nin vec4 seed;\\nin vec3 size;\\n#ifndef COLORGRADIENTS\\nin vec4 color;\\n#endif\\nin vec3 direction;\\n#ifndef BILLBOARD\\nin vec3 initialDirection;\\n#endif\\n#ifdef ANGULARSPEEDGRADIENTS\\nin float angle;\\n#else\\nin vec2 angle;\\n#endif\\n#ifdef ANIMATESHEET\\nin float cellIndex;\\n#endif\\n\\nout vec3 outPosition;\\nout float outAge;\\nout float outLife;\\nout vec4 outSeed;\\nout vec3 outSize;\\n#ifndef COLORGRADIENTS\\nout vec4 outColor;\\n#endif\\nout vec3 outDirection;\\n#ifndef BILLBOARD\\nout vec3 outInitialDirection;\\n#endif\\n#ifdef ANGULARSPEEDGRADIENTS\\nout float outAngle;\\n#else\\nout vec2 outAngle;\\n#endif\\n#ifdef ANIMATESHEET\\nout float outCellIndex;\\n#endif\\n#ifdef SIZEGRADIENTS\\nuniform sampler2D sizeGradientSampler;\\n#endif \\n#ifdef ANGULARSPEEDGRADIENTS\\nuniform sampler2D angularSpeedGradientSampler;\\n#endif \\n#ifdef VELOCITYGRADIENTS\\nuniform sampler2D velocityGradientSampler;\\n#endif\\n#ifdef NOISE\\nuniform vec3 noiseStrength;\\nuniform sampler2D noiseSampler;\\n#endif\\n#ifdef ANIMATESHEET\\nuniform vec3 cellInfos;\\n#endif\\nvec3 getRandomVec3(float offset) {\\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\\n}\\nvec4 getRandomVec4(float offset) {\\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\\n}\\nvoid main() {\\nif (age>=life) {\\nif (stopFactor == 0.) {\\noutPosition=position;\\noutAge=life;\\noutLife=life;\\noutSeed=seed;\\n#ifndef COLORGRADIENTS \\noutColor=vec4(0.,0.,0.,0.);\\n#endif\\noutSize=vec3(0.,0.,0.);\\n#ifndef BILLBOARD \\noutInitialDirection=initialDirection;\\n#endif \\noutDirection=direction;\\noutAngle=angle;\\n#ifdef ANIMATESHEET \\noutCellIndex=cellIndex;\\n#endif\\nreturn;\\n}\\nvec3 position;\\nvec3 direction;\\n\\nvec4 randoms=getRandomVec4(seed.x);\\n\\noutAge=0.0;\\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\\n\\noutSeed=seed;\\n\\n#ifdef SIZEGRADIENTS \\noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\\n#else\\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\\n#endif\\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \\n#ifndef COLORGRADIENTS\\n\\noutColor=color1+(color2-color1)*randoms.b;\\n#endif\\n\\n#ifndef ANGULARSPEEDGRADIENTS \\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\\n#else\\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\\n#endif \\n\\n#ifdef POINTEMITTER\\nvec3 randoms2=getRandomVec3(seed.y);\\nvec3 randoms3=getRandomVec3(seed.z);\\nposition=vec3(0,0,0);\\ndirection=direction1+(direction2-direction1)*randoms3;\\n#elif defined(BOXEMITTER)\\nvec3 randoms2=getRandomVec3(seed.y);\\nvec3 randoms3=getRandomVec3(seed.z);\\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\\ndirection=direction1+(direction2-direction1)*randoms3; \\n#elif defined(SPHEREEMITTER)\\nvec3 randoms2=getRandomVec3(seed.y);\\nvec3 randoms3=getRandomVec3(seed.z);\\n\\nfloat phi=2.0*PI*randoms2.x;\\nfloat theta=acos(2.0*randoms2.y-1.0);\\nfloat randX=cos(phi)*sin(theta);\\nfloat randY=cos(theta);\\nfloat randZ=sin(phi)*sin(theta);\\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\\n#ifdef DIRECTEDSPHEREEMITTER\\ndirection=direction1+(direction2-direction1)*randoms3;\\n#else\\n\\ndirection=position+directionRandomizer*randoms3;\\n#endif\\n#elif defined(CONEEMITTER)\\nvec3 randoms2=getRandomVec3(seed.y);\\nfloat s=2.0*PI*randoms2.x;\\n#ifdef CONEEMITTERSPAWNPOINT\\nfloat h=0.00001;\\n#else\\nfloat h=randoms2.y*height.y;\\n\\nh=1.-h*h; \\n#endif\\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\\nlRadius=lRadius*h;\\nfloat randX=lRadius*sin(s);\\nfloat randZ=lRadius*cos(s);\\nfloat randY=h*height.x;\\nposition=vec3(randX,randY,randZ); \\n\\nif (abs(cos(coneAngle)) == 1.0) {\\ndirection=vec3(0.,1.0,0.);\\n} else {\\nvec3 randoms3=getRandomVec3(seed.z);\\ndirection=position+directionRandomizer*randoms3;\\n}\\n#else \\n\\nposition=vec3(0.,0.,0.);\\n\\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\\n#endif\\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\\noutPosition=(emitterWM*vec4(position,1.)).xyz;\\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\\noutDirection=initial*power;\\n#ifndef BILLBOARD \\noutInitialDirection=initial;\\n#endif\\n#ifdef ANIMATESHEET \\noutCellIndex=cellInfos.x;\\n#endif\\n} else { \\nfloat directionScale=timeDelta;\\nfloat ageGradient=age/life;\\n#ifdef VELOCITYGRADIENTS\\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\\n#endif\\noutPosition=position+direction*directionScale;\\noutAge=age+timeDelta;\\noutLife=life;\\noutSeed=seed;\\n#ifndef COLORGRADIENTS \\noutColor=color;\\n#endif\\n#ifdef SIZEGRADIENTS\\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\\noutSize.yz=size.yz;\\n#else\\noutSize=size;\\n#endif \\n#ifndef BILLBOARD \\noutInitialDirection=initialDirection;\\n#endif\\noutDirection=direction+gravity*timeDelta;\\n#ifdef NOISE\\nvec3 localPosition=outPosition-emitterWM[3].xyz;\\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\\noutDirection=outDirection+force*timeDelta;\\n#endif \\n#ifdef ANGULARSPEEDGRADIENTS\\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\\noutAngle=angle+angularSpeed*timeDelta;\\n#else\\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\\n#endif\\n#ifdef ANIMATESHEET \\nfloat dist=cellInfos.y-cellInfos.x;\\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\\noutCellIndex=float(int(cellInfos.x+ratio*dist));\\n#endif\\n}\\n}\",\"gpuUpdateParticlesPixelShader\":\"#version 300 es\\nvoid main() {\\ndiscard;\\n}\\n\",\"postprocessVertexShader\":\"\\nattribute vec2 position;\\nuniform vec2 scale;\\n\\nvarying vec2 vUV;\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) { \\nvUV=(position*madd+madd)*scale;\\ngl_Position=vec4(position,0.0,1.0);\\n}\",\"passPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nvoid main(void) \\n{\\ngl_FragColor=texture2D(textureSampler,vUV);\\n}\",\"shadowMapVertexShader\":\"\\nattribute vec3 position;\\n#ifdef NORMAL\\nattribute vec3 normal;\\nuniform vec3 lightData;\\n#endif\\n#include\\n#include\\n#include[0..maxSimultaneousMorphTargets]\\n\\n#include\\n#include\\nuniform mat4 viewProjection;\\nuniform vec3 biasAndScale;\\nuniform vec2 depthValues;\\nvarying float vDepthMetric;\\n#ifdef ALPHATEST\\nvarying vec2 vUV;\\nuniform mat4 diffuseMatrix;\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#endif\\nvoid main(void)\\n{\\nvec3 positionUpdated=position;\\n#include[0..maxSimultaneousMorphTargets]\\n#include\\n#include\\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\\n\\n#ifdef NORMAL\\nmat3 normalWorld=mat3(finalWorld);\\n#ifdef NONUNIFORMSCALING\\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\\n#endif\\nvec3 worldNor=normalize(normalWorld*normal);\\n#ifdef DIRECTIONINLIGHTDATA\\nvec3 worldLightDir=normalize(-lightData.xyz);\\n#else\\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\\nvec3 worldLightDir=normalize(directionToLight);\\n#endif\\nfloat ndl=dot(worldNor,worldLightDir);\\nfloat sinNL=sqrt(1.0-ndl*ndl);\\nfloat normalBias=biasAndScale.y*sinNL;\\nworldPos.xyz-=worldNor*normalBias;\\n#endif\\n\\ngl_Position=viewProjection*worldPos;\\n#ifdef DEPTHTEXTURE\\n\\ngl_Position.z+=biasAndScale.x*gl_Position.w;\\n#endif\\n\\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\\n#ifdef ALPHATEST\\n#ifdef UV1\\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n#endif\\n#ifdef UV2\\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n#endif\\n#endif\\n}\",\"shadowMapPixelShader\":\"#ifndef FLOAT\\nvec4 pack(float depth)\\n{\\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\\nvec4 res=fract(depth*bit_shift);\\nres-=res.xxyz*bit_mask;\\nreturn res;\\n}\\n#endif\\nvarying float vDepthMetric;\\n#ifdef ALPHATEST\\nvarying vec2 vUV;\\nuniform sampler2D diffuseSampler;\\n#endif\\nuniform vec3 biasAndScale;\\nuniform vec2 depthValues;\\nvoid main(void)\\n{\\n#ifdef ALPHATEST\\nif (texture2D(diffuseSampler,vUV).a<0.4)\\ndiscard;\\n#endif\\nfloat depth=vDepthMetric;\\n#ifdef ESM\\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\\n#endif\\n#ifdef FLOAT\\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\\n#else\\ngl_FragColor=pack(depth);\\n#endif\\n}\",\"depthBoxBlurPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n\\nuniform vec2 screenSize;\\nvoid main(void)\\n{\\nvec4 colorDepth=vec4(0.0);\\nfor (int x=-OFFSET; x<=OFFSET; x++)\\nfor (int y=-OFFSET; y<=OFFSET; y++)\\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\\n}\",\"proceduralVertexShader\":\"\\nattribute vec2 position;\\n\\nvarying vec2 vPosition;\\nvarying vec2 vUV;\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) { \\nvPosition=position;\\nvUV=position*madd+madd;\\ngl_Position=vec4(position,0.0,1.0);\\n}\",\"depthVertexShader\":\"\\nattribute vec3 position;\\n#include\\n\\n#include\\nuniform mat4 viewProjection;\\nuniform vec2 depthValues;\\n#if defined(ALPHATEST) || defined(NEED_UV)\\nvarying vec2 vUV;\\nuniform mat4 diffuseMatrix;\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#endif\\nvarying float vDepthMetric;\\nvoid main(void)\\n{\\n#include\\n#include\\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\\n#ifdef UV1\\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n#endif\\n#ifdef UV2\\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n#endif\\n#endif\\n}\",\"depthPixelShader\":\"#ifdef ALPHATEST\\nvarying vec2 vUV;\\nuniform sampler2D diffuseSampler;\\n#endif\\nvarying float vDepthMetric;\\nvoid main(void)\\n{\\n#ifdef ALPHATEST\\nif (texture2D(diffuseSampler,vUV).a<0.4)\\ndiscard;\\n#endif\\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\\n}\",\"ssaoPixelShader\":\"\\nuniform sampler2D textureSampler;\\nvarying vec2 vUV;\\n#ifdef SSAO\\nuniform sampler2D randomSampler;\\nuniform float randTextureTiles;\\nuniform float samplesFactor;\\nuniform vec3 sampleSphere[SAMPLES];\\nuniform float totalStrength;\\nuniform float radius;\\nuniform float area;\\nuniform float fallOff;\\nuniform float base;\\nvec3 normalFromDepth(float depth,vec2 coords)\\n{\\nvec2 offset1=vec2(0.0,radius);\\nvec2 offset2=vec2(radius,0.0);\\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\\nvec3 p1=vec3(offset1,depth1-depth);\\nvec3 p2=vec3(offset2,depth2-depth);\\nvec3 normal=cross(p1,p2);\\nnormal.z=-normal.z;\\nreturn normalize(normal);\\n}\\nvoid main()\\n{\\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\\nfloat depth=texture2D(textureSampler,vUV).r;\\nvec3 position=vec3(vUV,depth);\\nvec3 normal=normalFromDepth(depth,vUV);\\nfloat radiusDepth=radius/depth;\\nfloat occlusion=0.0;\\nvec3 ray;\\nvec3 hemiRay;\\nfloat occlusionDepth;\\nfloat difference;\\nfor (int i=0; imaxZ) {\\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\\nreturn;\\n}\\nfor (int i=0; i1.0 || offset.y>1.0) {\\ncontinue;\\n}\\n\\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\\n\\nfloat rangeCheck=abs(depth-sampleDepth)=1e-5 ? 1.0 : 0.0)*rangeCheck;\\n}\\n\\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\\nfloat result=clamp(ao+base,0.0,1.0);\\ngl_FragColor=vec4(vec3(result),1.0);\\n}\\n#endif\\n#ifdef BILATERAL_BLUR\\nuniform sampler2D depthSampler;\\nuniform float outSize;\\nuniform float samplerOffsets[SAMPLES];\\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\\nvec4 color=vec4(0.0);\\nvec2 off1=vec2(1.3846153846)*direction;\\nvec2 off2=vec2(3.2307692308)*direction;\\ncolor+=texture2D(image,uv)*0.2270270270;\\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\\nreturn color;\\n}\\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\\nvec4 color=vec4(0.0);\\nvec2 off1=vec2(1.411764705882353)*direction;\\nvec2 off2=vec2(3.2941176470588234)*direction;\\nvec2 off3=vec2(5.176470588235294)*direction;\\ncolor+=texture2D(image,uv)*0.1964825501511404;\\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\\nreturn color;\\n}\\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\\nvec4 color=vec4(0.0);\\nvec2 off1=vec2(1.411764705882353)*direction;\\nvec2 off2=vec2(3.2941176470588234)*direction;\\nvec2 off3=vec2(5.176470588235294)*direction;\\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\\nfloat sampleDepth;\\nfloat weight;\\nfloat weightSum=30.0;\\ncolor+=texture2D(image,uv)*30.0;\\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\\nweightSum+=weight;\\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\\nweightSum+=weight;\\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\\nweightSum+=weight;\\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\\nweightSum+=weight;\\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\\nweightSum+=weight;\\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\\nweightSum+=weight;\\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\\nreturn color/weightSum;\\n}\\nvoid main()\\n{\\n#if EXPENSIVE\\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\\nfloat texelsize=1.0/outSize;\\nfloat result=0.0;\\nfloat weightSum=0.0;\\nfor (int i=0; i1.0) { lum_threshold=0.94+0.01*threshold; }\\nelse { lum_threshold=0.5+0.44*threshold; }\\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\\nhighlight*=luminance*gain;\\nhighlight.a=1.0;\\nreturn highlight;\\n}\\nvoid main(void)\\n{\\nvec4 original=texture2D(textureSampler,vUV);\\n\\nif (gain == -1.0) {\\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\\nreturn;\\n}\\nfloat w=2.0/screen_width;\\nfloat h=2.0/screen_height;\\nfloat weight=1.0;\\n\\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\\n#ifdef PENTAGON\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\\n#else\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\\n#endif\\nblurred/=39.0;\\ngl_FragColor=blurred;\\n\\n}\",\"depthOfFieldPixelShader\":\"\\n\\n\\n\\n\\nuniform sampler2D textureSampler;\\nuniform sampler2D highlightsSampler;\\nuniform sampler2D depthSampler;\\nuniform sampler2D grainSampler;\\n\\nuniform float grain_amount;\\nuniform bool blur_noise;\\nuniform float screen_width;\\nuniform float screen_height;\\nuniform float distortion;\\nuniform bool dof_enabled;\\n\\nuniform float screen_distance; \\nuniform float aperture;\\nuniform float darken;\\nuniform float edge_blur;\\nuniform bool highlights;\\n\\nuniform float near;\\nuniform float far;\\n\\nvarying vec2 vUV;\\n\\n#define PI 3.14159265\\n#define TWOPI 6.28318530\\n#define inverse_focal_length 0.1 \\n\\nvec2 centered_screen_pos;\\nvec2 distorted_coords;\\nfloat radius2;\\nfloat radius;\\n\\nvec2 rand(vec2 co)\\n{\\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\\n}\\n\\nvec2 getDistortedCoords(vec2 coords) {\\nif (distortion == 0.0) { return coords; }\\nvec2 direction=1.0*normalize(centered_screen_pos);\\nvec2 dist_coords=vec2(0.5,0.5);\\ndist_coords.x=0.5+direction.x*radius2*1.0;\\ndist_coords.y=0.5+direction.y*radius2*1.0;\\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\\ndist_coords=mix(coords,dist_coords,dist_amount);\\nreturn dist_coords;\\n}\\n\\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\\n\\nvec2 coords=distorted_coords;\\nfloat angle=rand(coords*100.0).x*TWOPI;\\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\\ncolor+=texture2D(textureSampler,coords)*weight;\\nreturn weight;\\n}\\n\\nfloat getBlurLevel(float size) {\\nreturn min(3.0,ceil(size/1.0));\\n}\\n\\nvec4 getBlurColor(float size) {\\nvec4 col=texture2D(textureSampler,distorted_coords);\\nif (size == 0.0) { return col; }\\n\\n\\nfloat blur_level=getBlurLevel(size);\\nfloat w=(size/screen_width);\\nfloat h=(size/screen_height);\\nfloat total_weight=1.0;\\nvec2 sample_coords;\\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\\nif (blur_level>1.0) {\\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\\n}\\nif (blur_level>2.0) {\\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\\n}\\ncol/=total_weight; \\n\\nif (darken>0.0) {\\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\\n}\\n\\n\\n\\n\\nreturn col;\\n}\\nvoid main(void)\\n{\\n\\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\\nradius=sqrt(radius2);\\ndistorted_coords=getDistortedCoords(vUV); \\nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \\nfloat depth=texture2D(depthSampler,distorted_coords).r; \\nfloat distance=near+(far-near)*depth; \\nvec4 color=texture2D(textureSampler,vUV); \\n\\n\\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\\n\\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\\n\\nfloat edge_blur_amount=0.0;\\nif (edge_blur>0.0) {\\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\\n}\\n\\nfloat blur_amount=max(edge_blur_amount,coc);\\n\\nif (blur_amount == 0.0) {\\ngl_FragColor=texture2D(textureSampler,distorted_coords);\\n}\\nelse {\\n\\ngl_FragColor=getBlurColor(blur_amount*1.7);\\n\\nif (highlights) {\\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\\n}\\nif (blur_noise) {\\n\\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\\n}\\n}\\n\\nif (grain_amount>0.0) {\\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\\n}\\n}\\n\",\"standardPixelShader\":\"uniform sampler2D textureSampler;\\nvarying vec2 vUV;\\n#if defined(PASS_POST_PROCESS)\\nvoid main(void)\\n{\\nvec4 color=texture2D(textureSampler,vUV);\\ngl_FragColor=color;\\n}\\n#endif\\n#if defined(DOWN_SAMPLE_X4)\\nuniform vec2 dsOffsets[16];\\nvoid main(void)\\n{\\nvec4 average=vec4(0.0,0.0,0.0,0.0);\\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\\naverage/=16.0;\\ngl_FragColor=average;\\n}\\n#endif\\n#if defined(BRIGHT_PASS)\\nuniform vec2 dsOffsets[4];\\nuniform float brightThreshold;\\nvoid main(void)\\n{\\nvec4 average=vec4(0.0,0.0,0.0,0.0);\\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\\naverage*=0.25;\\nfloat luminance=length(average.rgb);\\nif (luminanceshadowPixelDepth)\\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\\ncurrentPosition+=stepL;\\n}\\naccumFog/=NB_STEPS;\\nvec3 color=accumFog*scatteringPower;\\ngl_FragColor=vec4(color*exp(color) ,1.0);\\n}\\n#endif\\n#if defined(VLSMERGE)\\nuniform sampler2D originalSampler;\\nvoid main(void)\\n{\\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\\n}\\n#endif\\n#if defined(LUMINANCE)\\nuniform vec2 lumOffsets[4];\\nvoid main()\\n{\\nfloat average=0.0;\\nvec4 color=vec4(0.0);\\nfloat maximum=-1e20;\\nvec3 weight=vec3(0.299,0.587,0.114);\\nfor (int i=0; i<4; i++)\\n{\\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\\n\\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\\n\\n#ifdef WEIGHTED_AVERAGE\\nfloat GreyValue=dot(color.rgb,weight);\\n#endif\\n#ifdef BRIGHTNESS\\nfloat GreyValue=max(color.r,max(color.g,color.b));\\n#endif\\n#ifdef HSL_COMPONENT\\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\\n#endif\\n#ifdef MAGNITUDE\\nfloat GreyValue=length(color.rgb);\\n#endif\\nmaximum=max(maximum,GreyValue);\\naverage+=(0.25*log(1e-5+GreyValue));\\n}\\naverage=exp(average);\\ngl_FragColor=vec4(average,maximum,0.0,1.0);\\n}\\n#endif\\n#if defined(LUMINANCE_DOWN_SAMPLE)\\nuniform vec2 dsOffsets[9];\\nuniform float halfDestPixelSize;\\n#ifdef FINAL_DOWN_SAMPLER\\nvec4 pack(float value) {\\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\\nvec4 res=fract(value*bit_shift);\\nres-=res.xxyz*bit_mask;\\nreturn res;\\n}\\n#endif\\nvoid main()\\n{\\nvec4 color=vec4(0.0);\\nfloat average=0.0;\\nfor (int i=0; i<9; i++)\\n{\\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\\naverage+=color.r;\\n}\\naverage/=9.0;\\n#ifdef FINAL_DOWN_SAMPLER\\ngl_FragColor=pack(average);\\n#else\\ngl_FragColor=vec4(average,average,0.0,1.0);\\n#endif\\n}\\n#endif\\n#if defined(HDR)\\nuniform sampler2D textureAdderSampler;\\nuniform float averageLuminance;\\nvoid main()\\n{\\nvec4 color=texture2D(textureAdderSampler,vUV);\\nvec4 adjustedColor=color/averageLuminance;\\ncolor=adjustedColor;\\ncolor.a=1.0;\\ngl_FragColor=color;\\n}\\n#endif\\n#if defined(LENS_FLARE)\\n#define GHOSTS 3\\nuniform sampler2D lensColorSampler;\\nuniform float strength;\\nuniform float ghostDispersal;\\nuniform float haloWidth;\\nuniform vec2 resolution;\\nuniform float distortionStrength;\\nfloat hash(vec2 p)\\n{\\nfloat h=dot(p,vec2(127.1,311.7));\\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\\n}\\nfloat noise(in vec2 p)\\n{\\nvec2 i=floor(p);\\nvec2 f=fract(p);\\nvec2 u=f*f*(3.0-2.0*f);\\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\\nhash(i+vec2(1.0,0.0)),u.x),\\nmix(hash(i+vec2(0.0,1.0)),\\nhash(i+vec2(1.0,1.0)),u.x),u.y);\\n}\\nfloat fbm(vec2 p)\\n{\\nfloat f=0.0;\\nf+=0.5000*noise(p); p*=2.02;\\nf+=0.2500*noise(p); p*=2.03;\\nf+=0.1250*noise(p); p*=2.01;\\nf+=0.0625*noise(p); p*=2.04;\\nf/=0.9375;\\nreturn f;\\n}\\nvec3 pattern(vec2 uv)\\n{\\nvec2 p=-1.0+2.0*uv;\\nfloat p2=dot(p,p);\\nfloat f=fbm(vec2(15.0*p2))/2.0;\\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\\nreturn (1.0-f)*vec3(r,g,b);\\n}\\nfloat luminance(vec3 color)\\n{\\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\\n}\\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\\n{\\nreturn vec4(\\ntexture2D(tex,texcoord+direction*distortion.r).r,\\ntexture2D(tex,texcoord+direction*distortion.g).g,\\ntexture2D(tex,texcoord+direction*distortion.b).b,\\n1.0\\n);\\n}\\nvoid main(void)\\n{\\nvec2 uv=-vUV+vec2(1.0);\\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\\nvec2 texelSize=1.0/resolution;\\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\\nvec4 result=vec4(0.0);\\nfloat ghostIndice=1.0;\\nfor (int i=0; i=nSamples)\\nbreak;\\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\\nresult+=texture2D(textureSampler,offset1);\\n}\\ngl_FragColor=result/float(nSamples);\\n}\\n#endif\\n\",\"fxaaVertexShader\":\"\\nattribute vec2 position;\\nuniform vec2 texelSize;\\n\\nvarying vec2 vUV;\\nvarying vec2 sampleCoordS;\\nvarying vec2 sampleCoordE;\\nvarying vec2 sampleCoordN;\\nvarying vec2 sampleCoordW;\\nvarying vec2 sampleCoordNW;\\nvarying vec2 sampleCoordSE;\\nvarying vec2 sampleCoordNE;\\nvarying vec2 sampleCoordSW;\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) { \\nvUV=(position*madd+madd);\\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\\ngl_Position=vec4(position,0.0,1.0);\\n}\",\"fxaaPixelShader\":\"uniform sampler2D textureSampler;\\nuniform vec2 texelSize;\\nvarying vec2 vUV;\\nvarying vec2 sampleCoordS;\\nvarying vec2 sampleCoordE;\\nvarying vec2 sampleCoordN;\\nvarying vec2 sampleCoordW;\\nvarying vec2 sampleCoordNW;\\nvarying vec2 sampleCoordSE;\\nvarying vec2 sampleCoordNE;\\nvarying vec2 sampleCoordSW;\\nconst float fxaaQualitySubpix=1.0;\\nconst float fxaaQualityEdgeThreshold=0.166;\\nconst float fxaaQualityEdgeThresholdMin=0.0833;\\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\\nvoid main(){\\nvec2 posM;\\nposM.x=vUV.x;\\nposM.y=vUV.y;\\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\\nfloat lumaM=FxaaLuma(rgbyM);\\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\\nfloat maxSM=max(lumaS,lumaM);\\nfloat minSM=min(lumaS,lumaM);\\nfloat maxESM=max(lumaE,maxSM);\\nfloat minESM=min(lumaE,minSM);\\nfloat maxWN=max(lumaN,lumaW);\\nfloat minWN=min(lumaN,lumaW);\\nfloat rangeMax=max(maxWN,maxESM);\\nfloat rangeMin=min(minWN,minESM);\\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\\nfloat range=rangeMax-rangeMin;\\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\\n#ifndef MALI\\nif(range=edgeVert;\\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\\nif (!horzSpan)\\n{\\nlumaN=lumaW;\\n}\\nif (!horzSpan) \\n{\\nlumaS=lumaE;\\n}\\nif (horzSpan) \\n{\\nlengthSign=texelSize.y;\\n}\\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\\nfloat gradientN=lumaN-lumaM;\\nfloat gradientS=lumaS-lumaM;\\nfloat lumaNN=lumaN+lumaM;\\nfloat lumaSS=lumaS+lumaM;\\nbool pairN=abs(gradientN)>=abs(gradientS);\\nfloat gradient=max(abs(gradientN),abs(gradientS));\\nif (pairN)\\n{\\nlengthSign=-lengthSign;\\n}\\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\\nvec2 posB;\\nposB.x=posM.x;\\nposB.y=posM.y;\\nvec2 offNP;\\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\\nif (!horzSpan) \\n{\\nposB.x+=lengthSign*0.5;\\n}\\nif (horzSpan)\\n{\\nposB.y+=lengthSign*0.5;\\n}\\nvec2 posN;\\nposN.x=posB.x-offNP.x*1.5;\\nposN.y=posB.y-offNP.y*1.5;\\nvec2 posP;\\nposP.x=posB.x+offNP.x*1.5;\\nposP.y=posB.y+offNP.y*1.5;\\nfloat subpixD=((-2.0)*subpixC)+3.0;\\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\\nfloat subpixE=subpixC*subpixC;\\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\\nif (!pairN) \\n{\\nlumaNN=lumaSS;\\n}\\nfloat gradientScaled=gradient*1.0/4.0;\\nfloat lumaMM=lumaM-lumaNN*0.5;\\nfloat subpixF=subpixD*subpixE;\\nbool lumaMLTZero=lumaMM<0.0;\\nlumaEndN-=lumaNN*0.5;\\nlumaEndP-=lumaNN*0.5;\\nbool doneN=abs(lumaEndN)>=gradientScaled;\\nbool doneP=abs(lumaEndP)>=gradientScaled;\\nif (!doneN) \\n{\\nposN.x-=offNP.x*3.0;\\n}\\nif (!doneN) \\n{\\nposN.y-=offNP.y*3.0;\\n}\\nbool doneNP=(!doneN) || (!doneP);\\nif (!doneP) \\n{\\nposP.x+=offNP.x*3.0;\\n}\\nif (!doneP)\\n{\\nposP.y+=offNP.y*3.0;\\n}\\nif (doneNP)\\n{\\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\\ndoneN=abs(lumaEndN)>=gradientScaled;\\ndoneP=abs(lumaEndP)>=gradientScaled;\\nif (!doneN) posN.x-=offNP.x*12.0;\\nif (!doneN) posN.y-=offNP.y*12.0;\\ndoneNP=(!doneN) || (!doneP);\\nif (!doneP) posP.x+=offNP.x*12.0;\\nif (!doneP) posP.y+=offNP.y*12.0;\\n}\\nfloat dstN=posM.x-posN.x;\\nfloat dstP=posP.x-posM.x;\\nif (!horzSpan)\\n{\\ndstN=posM.y-posN.y;\\n}\\nif (!horzSpan) \\n{\\ndstP=posP.y-posM.y;\\n}\\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\\nfloat spanLength=(dstP+dstN);\\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\\nfloat spanLengthRcp=1.0/spanLength;\\nbool directionN=dstN\\n\\nuniform sampler2D textureSampler; \\n\\nuniform float intensity;\\nuniform float animatedSeed;\\n\\nvarying vec2 vUV;\\nvoid main(void)\\n{\\ngl_FragColor=texture2D(textureSampler,vUV);\\nvec2 seed=vUV*(animatedSeed);\\nfloat grain=dither(seed,intensity);\\n\\nfloat lum=getLuminance(gl_FragColor.rgb);\\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\\ngl_FragColor.rgb+=grain*grainAmount;\\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\\n}\",\"sharpenPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform vec2 screenSize;\\nuniform vec2 sharpnessAmounts;\\nvoid main(void)\\n{\\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\\nvec4 color=texture2D(textureSampler,vUV);\\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\\ncolor*4.0;\\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\\n}\",\"kernelBlurVertexShader\":\"\\nattribute vec2 position;\\n\\nuniform vec2 delta;\\n\\nvarying vec2 sampleCenter;\\n#include[0..varyingCount]\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) { \\nsampleCenter=(position*madd+madd);\\n#include[0..varyingCount]\\ngl_Position=vec4(position,0.0,1.0);\\n}\",\"kernelBlurPixelShader\":\"\\nuniform sampler2D textureSampler;\\nuniform vec2 delta;\\n\\nvarying vec2 sampleCenter;\\n#ifdef DOF\\nuniform sampler2D circleOfConfusionSampler;\\nuniform vec2 cameraMinMaxZ;\\nfloat sampleDistance(const in vec2 offset) {\\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \\nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \\n}\\nfloat sampleCoC(const in vec2 offset) {\\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \\nreturn coc; \\n}\\n#endif\\n#include[0..varyingCount]\\n#ifdef PACKEDFLOAT\\nvec4 pack(float depth)\\n{\\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\\nvec4 res=fract(depth*bit_shift);\\nres-=res.xxyz*bit_mask;\\nreturn res;\\n}\\nfloat unpack(vec4 color)\\n{\\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\\nreturn dot(color,bit_shift);\\n}\\n#endif\\nvoid main(void)\\n{\\nfloat computedWeight=0.0;\\n#ifdef PACKEDFLOAT \\nfloat blend=0.;\\n#else\\nvec4 blend=vec4(0.);\\n#endif\\n#ifdef DOF\\nfloat sumOfWeights=CENTER_WEIGHT; \\nfloat factor=0.0;\\n\\n#ifdef PACKEDFLOAT\\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\\n#else\\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\\n#endif\\n#endif\\n#include[0..varyingCount]\\n#include[0..depCount]\\n#ifdef PACKEDFLOAT\\ngl_FragColor=pack(blend);\\n#else\\ngl_FragColor=blend;\\n#endif\\n#ifdef DOF\\ngl_FragColor/=sumOfWeights;\\n#endif\\n}\",\"depthOfFieldMergePixelShader\":\"uniform sampler2D textureSampler;\\nvarying vec2 vUV;\\nuniform sampler2D circleOfConfusionSampler;\\nuniform sampler2D blurStep0;\\n#if BLUR_LEVEL>0\\nuniform sampler2D blurStep1;\\n#endif\\n#if BLUR_LEVEL>1\\nuniform sampler2D blurStep2;\\n#endif\\nvoid main(void)\\n{\\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\\n#if BLUR_LEVEL == 0\\nvec4 original=texture2D(textureSampler,vUV);\\nvec4 blurred0=texture2D(blurStep0,vUV);\\ngl_FragColor=mix(original,blurred0,coc);\\n#endif\\n#if BLUR_LEVEL == 1\\nif(coc<0.5){\\nvec4 original=texture2D(textureSampler,vUV);\\nvec4 blurred1=texture2D(blurStep1,vUV);\\ngl_FragColor=mix(original,blurred1,coc/0.5);\\n}else{\\nvec4 blurred0=texture2D(blurStep0,vUV); \\nvec4 blurred1=texture2D(blurStep1,vUV);\\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\\n}\\n#endif\\n#if BLUR_LEVEL == 2\\nif(coc<0.33){\\nvec4 original=texture2D(textureSampler,vUV);\\nvec4 blurred2=texture2D(blurStep2,vUV);\\ngl_FragColor=mix(original,blurred2,coc/0.33);\\n}else if(coc<0.66){\\nvec4 blurred1=texture2D(blurStep1,vUV);\\nvec4 blurred2=texture2D(blurStep2,vUV);\\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\\n}else{\\nvec4 blurred0=texture2D(blurStep0,vUV);\\nvec4 blurred1=texture2D(blurStep1,vUV);\\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\\n}\\n#endif\\n}\\n\",\"circleOfConfusionPixelShader\":\"\\nuniform sampler2D depthSampler;\\n\\nvarying vec2 vUV;\\n\\nuniform vec2 cameraMinMaxZ;\\n\\nuniform float focusDistance;\\nuniform float cocPrecalculation;\\nvoid main(void)\\n{\\nfloat depth=texture2D(depthSampler,vUV).r;\\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\\ncoc=clamp(coc,0.0,1.0);\\ngl_FragColor=vec4(coc,depth,coc,1.0);\\n}\\n\",\"bloomMergePixelShader\":\"uniform sampler2D textureSampler;\\nuniform sampler2D bloomBlur;\\nvarying vec2 vUV;\\nuniform float bloomWeight;\\nvoid main(void)\\n{\\ngl_FragColor=texture2D(textureSampler,vUV);\\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \\n}\\n\",\"extractHighlightsPixelShader\":\"#include\\n\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform float threshold;\\nuniform float exposure;\\nvoid main(void) \\n{\\ngl_FragColor=texture2D(textureSampler,vUV);\\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\\n}\",\"geometryVertexShader\":\"precision highp float;\\nprecision highp int;\\n#include\\n#include\\nattribute vec3 position;\\nattribute vec3 normal;\\n#if defined(ALPHATEST) || defined(NEED_UV)\\nvarying vec2 vUV;\\nuniform mat4 diffuseMatrix;\\n#ifdef UV1\\nvarying vec2 uv;\\n#endif\\n#ifdef UV2\\nvarying vec2 uv2;\\n#endif\\n#endif\\n\\nuniform mat4 viewProjection;\\nuniform mat4 view;\\nvarying vec3 vNormalV;\\nvarying vec4 vViewPos;\\n#ifdef POSITION\\nvarying vec3 vPosition;\\n#endif\\nvoid main(void)\\n{\\n#include\\n#include\\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\\nvViewPos=view*pos;\\n#ifdef POSITION\\nvPosition=pos.xyz/pos.w;\\n#endif\\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\\n#ifdef UV1\\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n#endif\\n#ifdef UV2\\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n#endif\\n#endif\\n}\",\"geometryPixelShader\":\"#extension GL_EXT_draw_buffers : require\\nprecision highp float;\\nprecision highp int;\\nvarying vec3 vNormalV;\\nvarying vec4 vViewPos;\\n#ifdef POSITION\\nvarying vec3 vPosition;\\n#endif\\n#ifdef ALPHATEST\\nvarying vec2 vUV;\\nuniform sampler2D diffuseSampler;\\n#endif\\n#ifdef POSITION\\n#include[3]\\n#else\\n#include[2]\\n#endif\\nvoid main() {\\n#ifdef ALPHATEST\\nif (texture2D(diffuseSampler,vUV).a<0.4)\\ndiscard;\\n#endif\\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\\n\\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\\n\\n#ifdef POSITION\\ngl_FragData[2]=vec4(vPosition,1.0);\\n#endif\\n}\",\"refractionPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform sampler2D refractionSampler;\\n\\nuniform vec3 baseColor;\\nuniform float depth;\\nuniform float colorLevel;\\nvoid main() {\\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\\nvec2 uv=vUV-vec2(0.5);\\nvec2 offset=uv*depth*ref;\\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\\n}\",\"blackAndWhitePixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform float degree;\\nvoid main(void) \\n{\\nvec3 color=texture2D(textureSampler,vUV).rgb;\\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \\nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\\n}\",\"convolutionPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform vec2 screenSize;\\nuniform float kernel[9];\\nvoid main(void)\\n{\\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\\nvec4 colorSum =\\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\\nfloat kernelWeight =\\nkernel[0] +\\nkernel[1] +\\nkernel[2] +\\nkernel[3] +\\nkernel[4] +\\nkernel[5] +\\nkernel[6] +\\nkernel[7] +\\nkernel[8];\\nif (kernelWeight<=0.0) {\\nkernelWeight=1.0;\\n}\\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\\n}\",\"filterPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform mat4 kernelMatrix;\\nvoid main(void)\\n{\\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\\ngl_FragColor=vec4(updatedColor,1.0);\\n}\",\"volumetricLightScatteringPixelShader\":\"uniform sampler2D textureSampler;\\nuniform sampler2D lightScatteringSampler;\\nuniform float decay;\\nuniform float exposure;\\nuniform float weight;\\nuniform float density;\\nuniform vec2 meshPositionOnScreen;\\nvarying vec2 vUV;\\nvoid main(void) {\\nvec2 tc=vUV;\\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\\nfloat illuminationDecay=1.0;\\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\\nfor(int i=0; i\\n#include\\n#include\\nvoid main(void)\\n{\\nvec4 result=texture2D(textureSampler,vUV);\\n#ifdef IMAGEPROCESSING\\n#ifndef FROMLINEARSPACE\\n\\nresult.rgb=toLinearSpace(result.rgb);\\n#endif\\nresult=applyImageProcessing(result);\\n#else\\n\\n#ifdef FROMLINEARSPACE\\nresult=applyImageProcessing(result);\\n#endif\\n#endif\\ngl_FragColor=result;\\n}\",\"lensFlareVertexShader\":\"\\nattribute vec2 position;\\n\\nuniform mat4 viewportMatrix;\\n\\nvarying vec2 vUV;\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) { \\nvUV=position*madd+madd;\\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\\n}\",\"lensFlarePixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n\\nuniform vec4 color;\\nvoid main(void) {\\nvec4 baseColor=texture2D(textureSampler,vUV);\\ngl_FragColor=baseColor*color;\\n}\",\"anaglyphPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform sampler2D leftSampler;\\nvoid main(void)\\n{\\nvec4 leftFrag=texture2D(leftSampler,vUV);\\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\\nvec4 rightFrag=texture2D(textureSampler,vUV);\\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\\n}\",\"stereoscopicInterlacePixelShader\":\"const vec3 TWO=vec3(2.0,2.0,2.0);\\nvarying vec2 vUV;\\nuniform sampler2D camASampler;\\nuniform sampler2D textureSampler;\\nuniform vec2 stepSize;\\nvoid main(void)\\n{\\nbool useCamB;\\nvec2 texCoord1;\\nvec2 texCoord2;\\nvec3 frag1;\\nvec3 frag2;\\n#ifdef IS_STEREOSCOPIC_HORIZ\\nuseCamB=vUV.x>0.5;\\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\\n#else\\nuseCamB=vUV.y>0.5;\\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\\n#endif\\n\\nif (useCamB){\\nfrag1=texture2D(textureSampler,texCoord1).rgb;\\nfrag2=texture2D(textureSampler,texCoord2).rgb;\\n}else{\\nfrag1=texture2D(camASampler ,texCoord1).rgb;\\nfrag2=texture2D(camASampler ,texCoord2).rgb;\\n}\\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\\n}\",\"vrDistortionCorrectionPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\nuniform vec2 LensCenter;\\nuniform vec2 Scale;\\nuniform vec2 ScaleIn;\\nuniform vec4 HmdWarpParam;\\nvec2 HmdWarp(vec2 in01) {\\nvec2 theta=(in01-LensCenter)*ScaleIn; \\nfloat rSq=theta.x*theta.x+theta.y*theta.y;\\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\\nreturn LensCenter+Scale*rvector;\\n}\\nvoid main(void)\\n{\\nvec2 tc=HmdWarp(vUV);\\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\\nelse{\\ngl_FragColor=texture2D(textureSampler,tc);\\n}\\n}\",\"glowBlurPostProcessPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n\\nuniform vec2 screenSize;\\nuniform vec2 direction;\\nuniform float blurWidth;\\n\\nfloat getLuminance(vec3 color)\\n{\\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\\n}\\nvoid main(void)\\n{\\nfloat weights[7];\\nweights[0]=0.05;\\nweights[1]=0.1;\\nweights[2]=0.2;\\nweights[3]=0.3;\\nweights[4]=0.2;\\nweights[5]=0.1;\\nweights[6]=0.05;\\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\\nvec2 texelStep=texelSize*direction*blurWidth;\\nvec2 start=vUV-3.0*texelStep;\\nvec4 baseColor=vec4(0.,0.,0.,0.);\\nvec2 texelOffset=vec2(0.,0.);\\nfor (int i=0; i<7; i++)\\n{\\n\\nvec4 texel=texture2D(textureSampler,start+texelOffset);\\nbaseColor.a+=texel.a*weights[i];\\n\\nfloat luminance=getLuminance(baseColor.rgb);\\nfloat luminanceTexel=getLuminance(texel.rgb);\\nfloat choice=step(luminanceTexel,luminance);\\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\\ntexelOffset+=texelStep;\\n}\\ngl_FragColor=baseColor;\\n}\",\"glowMapGenerationPixelShader\":\"#ifdef ALPHATEST\\nvarying vec2 vUVDiffuse;\\nuniform sampler2D diffuseSampler;\\n#endif\\n#ifdef EMISSIVE\\nvarying vec2 vUVEmissive;\\nuniform sampler2D emissiveSampler;\\n#endif\\nuniform vec4 color;\\nvoid main(void)\\n{\\n#ifdef ALPHATEST\\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\\ndiscard;\\n#endif\\n#ifdef EMISSIVE\\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\\n#else\\ngl_FragColor=color;\\n#endif\\n}\",\"glowMapGenerationVertexShader\":\"\\nattribute vec3 position;\\n#include\\n#include\\n#include[0..maxSimultaneousMorphTargets]\\n\\n#include\\nuniform mat4 viewProjection;\\nvarying vec4 vPosition;\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#ifdef ALPHATEST\\nvarying vec2 vUVDiffuse;\\nuniform mat4 diffuseMatrix;\\n#endif\\n#ifdef EMISSIVE\\nvarying vec2 vUVEmissive;\\nuniform mat4 emissiveMatrix;\\n#endif\\nvoid main(void)\\n{\\nvec3 positionUpdated=position;\\n#include[0..maxSimultaneousMorphTargets]\\n#include\\n#include\\n#ifdef CUBEMAP\\nvPosition=finalWorld*vec4(positionUpdated,1.0);\\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\\n#else\\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\\ngl_Position=vPosition;\\n#endif\\n#ifdef ALPHATEST\\n#ifdef DIFFUSEUV1\\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n#endif\\n#ifdef DIFFUSEUV2\\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n#endif\\n#endif\\n#ifdef EMISSIVE\\n#ifdef EMISSIVEUV1\\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\\n#endif\\n#ifdef EMISSIVEUV2\\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\\n#endif\\n#endif\\n}\",\"glowMapMergePixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n#ifdef EMISSIVE\\nuniform sampler2D textureSampler2;\\n#endif\\n\\nuniform float offset;\\nvoid main(void) {\\nvec4 baseColor=texture2D(textureSampler,vUV);\\n#ifdef EMISSIVE\\nbaseColor+=texture2D(textureSampler2,vUV);\\nbaseColor*=offset;\\n#else\\nbaseColor.a=abs(offset-baseColor.a);\\n#ifdef STROKE\\nfloat alpha=smoothstep(.0,.1,baseColor.a);\\nbaseColor.a=alpha;\\nbaseColor.rgb=baseColor.rgb*alpha;\\n#endif\\n#endif\\ngl_FragColor=baseColor;\\n}\",\"glowMapMergeVertexShader\":\"\\nattribute vec2 position;\\n\\nvarying vec2 vUV;\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) {\\nvUV=position*madd+madd;\\ngl_Position=vec4(position,0.0,1.0);\\n}\",\"lineVertexShader\":\"\\nattribute vec3 position;\\nattribute vec4 normal;\\n\\nuniform mat4 worldViewProjection;\\nuniform float width;\\nuniform float aspectRatio;\\nvoid main(void) {\\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\\ncurrentScreen.x*=aspectRatio;\\nnextScreen.x*=aspectRatio;\\nvec2 dir=normalize(nextScreen-currentScreen);\\nvec2 normalDir=vec2(-dir.y,dir.x);\\nnormalDir*=width/2.0;\\nnormalDir.x/=aspectRatio;\\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\\ngl_Position=viewPosition+offset;\\n}\",\"linePixelShader\":\"uniform vec4 color;\\nvoid main(void) {\\ngl_FragColor=color;\\n}\",\"outlineVertexShader\":\"\\nattribute vec3 position;\\nattribute vec3 normal;\\n#include\\n\\nuniform float offset;\\n#include\\nuniform mat4 viewProjection;\\n#ifdef ALPHATEST\\nvarying vec2 vUV;\\nuniform mat4 diffuseMatrix;\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#endif\\n#include\\nvoid main(void)\\n{\\nvec3 offsetPosition=position+normal*offset;\\n#include\\n#include\\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\\n#ifdef ALPHATEST\\n#ifdef UV1\\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n#endif\\n#ifdef UV2\\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n#endif\\n#endif\\n#include\\n}\\n\",\"outlinePixelShader\":\"#ifdef LOGARITHMICDEPTH\\n#extension GL_EXT_frag_depth : enable\\n#endif\\nuniform vec4 color;\\n#ifdef ALPHATEST\\nvarying vec2 vUV;\\nuniform sampler2D diffuseSampler;\\n#endif\\n#include\\nvoid main(void) {\\n#ifdef ALPHATEST\\nif (texture2D(diffuseSampler,vUV).a<0.4)\\ndiscard;\\n#endif\\n#include\\ngl_FragColor=color;\\n}\",\"layerVertexShader\":\"\\nattribute vec2 position;\\n\\nuniform vec2 scale;\\nuniform vec2 offset;\\nuniform mat4 textureMatrix;\\n\\nvarying vec2 vUV;\\nconst vec2 madd=vec2(0.5,0.5);\\nvoid main(void) { \\nvec2 shiftedPosition=position*scale+offset;\\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\\ngl_Position=vec4(shiftedPosition,0.0,1.0);\\n}\",\"layerPixelShader\":\"\\nvarying vec2 vUV;\\nuniform sampler2D textureSampler;\\n\\nuniform vec4 color;\\nvoid main(void) {\\nvec4 baseColor=texture2D(textureSampler,vUV);\\n#ifdef ALPHATEST\\nif (baseColor.a<0.4)\\ndiscard;\\n#endif\\ngl_FragColor=baseColor*color;\\n}\",\"backgroundVertexShader\":\"precision highp float;\\n#include<__decl__backgroundVertex>\\n#include\\n\\nattribute vec3 position;\\n#ifdef NORMAL\\nattribute vec3 normal;\\n#endif\\n#include\\n\\n#include\\n#ifdef POINTSIZE\\nuniform float pointSize;\\n#endif\\n\\nvarying vec3 vPositionW;\\n#ifdef NORMAL\\nvarying vec3 vNormalW;\\n#endif\\n#ifdef UV1\\nattribute vec2 uv;\\n#endif\\n#ifdef UV2\\nattribute vec2 uv2;\\n#endif\\n#ifdef MAINUV1\\nvarying vec2 vMainUV1;\\n#endif\\n#ifdef MAINUV2\\nvarying vec2 vMainUV2; \\n#endif\\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\\nvarying vec2 vDiffuseUV;\\n#endif\\n#include\\n#include\\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\\n#ifdef REFLECTIONMAP_SKYBOX\\nvarying vec3 vPositionUVW;\\n#endif\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvarying vec3 vDirectionW;\\n#endif\\nvoid main(void) {\\n#ifdef REFLECTIONMAP_SKYBOX\\nvPositionUVW=position;\\n#endif \\n#include\\n#include\\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\\nvec4 worldPos=finalWorld*vec4(position,1.0);\\nvPositionW=vec3(worldPos);\\n#ifdef NORMAL\\nmat3 normalWorld=mat3(finalWorld);\\n#ifdef NONUNIFORMSCALING\\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\\n#endif\\nvNormalW=normalize(normalWorld*normal);\\n#endif\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\\nif (fFovMultiplier<=1.0) {\\nvDirectionW=normalize(segment);\\n} else {\\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\\n}\\n#endif\\n#endif\\n#ifndef UV1\\nvec2 uv=vec2(0.,0.);\\n#endif\\n#ifndef UV2\\nvec2 uv2=vec2(0.,0.);\\n#endif\\n#ifdef MAINUV1\\nvMainUV1=uv;\\n#endif \\n#ifdef MAINUV2\\nvMainUV2=uv2;\\n#endif\\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \\nif (vDiffuseInfos.x == 0.)\\n{\\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\\n}\\nelse\\n{\\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\\n}\\n#endif\\n\\n#include\\n\\n#include\\n\\n#include[0..maxSimultaneousLights]\\n\\n#ifdef VERTEXCOLOR\\nvColor=color;\\n#endif\\n\\n#ifdef POINTSIZE\\ngl_PointSize=pointSize;\\n#endif\\n}\\n\",\"backgroundPixelShader\":\"#ifdef TEXTURELODSUPPORT\\n#extension GL_EXT_shader_texture_lod : enable\\n#endif\\nprecision highp float;\\n#include<__decl__backgroundFragment>\\n#define RECIPROCAL_PI2 0.15915494\\n\\nuniform vec3 vEyePosition;\\n\\nvarying vec3 vPositionW;\\n#ifdef MAINUV1\\nvarying vec2 vMainUV1;\\n#endif \\n#ifdef MAINUV2 \\nvarying vec2 vMainUV2; \\n#endif \\n#ifdef NORMAL\\nvarying vec3 vNormalW;\\n#endif\\n#ifdef DIFFUSE\\n#if DIFFUSEDIRECTUV == 1\\n#define vDiffuseUV vMainUV1\\n#elif DIFFUSEDIRECTUV == 2\\n#define vDiffuseUV vMainUV2\\n#else\\nvarying vec2 vDiffuseUV;\\n#endif\\nuniform sampler2D diffuseSampler;\\n#endif\\n\\n#ifdef REFLECTION\\n#ifdef REFLECTIONMAP_3D\\n#define sampleReflection(s,c) textureCube(s,c)\\nuniform samplerCube reflectionSampler;\\n#ifdef TEXTURELODSUPPORT\\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\\n#else\\nuniform samplerCube reflectionSamplerLow;\\nuniform samplerCube reflectionSamplerHigh;\\n#endif\\n#else\\n#define sampleReflection(s,c) texture2D(s,c)\\nuniform sampler2D reflectionSampler;\\n#ifdef TEXTURELODSUPPORT\\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\\n#else\\nuniform samplerCube reflectionSamplerLow;\\nuniform samplerCube reflectionSamplerHigh;\\n#endif\\n#endif\\n#ifdef REFLECTIONMAP_SKYBOX\\nvarying vec3 vPositionUVW;\\n#else\\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\\nvarying vec3 vDirectionW;\\n#endif\\n#endif\\n#include\\n#endif\\n\\n#ifndef FROMLINEARSPACE\\n#define FROMLINEARSPACE;\\n#endif\\n\\n#ifndef SHADOWONLY\\n#define SHADOWONLY;\\n#endif\\n#include\\n\\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\\n#include\\n#include\\n#include\\n#include\\n#include\\n\\n#include\\n#ifdef REFLECTIONFRESNEL\\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\\n{\\n\\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\\n}\\n#endif\\nvoid main(void) {\\n#include\\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\\n\\n#ifdef NORMAL\\nvec3 normalW=normalize(vNormalW);\\n#else\\nvec3 normalW=vec3(0.0,1.0,0.0);\\n#endif\\n\\nfloat shadow=1.;\\nfloat globalShadow=0.;\\nfloat shadowLightCount=0.;\\n#include[0..maxSimultaneousLights]\\n#ifdef SHADOWINUSE\\nglobalShadow/=shadowLightCount;\\n#else\\nglobalShadow=1.0;\\n#endif\\n\\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\\n#ifdef REFLECTION\\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\\n#ifdef REFLECTIONMAP_OPPOSITEZ\\nreflectionVector.z*=-1.0;\\n#endif\\n\\n#ifdef REFLECTIONMAP_3D\\nvec3 reflectionCoords=reflectionVector;\\n#else\\nvec2 reflectionCoords=reflectionVector.xy;\\n#ifdef REFLECTIONMAP_PROJECTION\\nreflectionCoords/=reflectionVector.z;\\n#endif\\nreflectionCoords.y=1.0-reflectionCoords.y;\\n#endif\\n#ifdef REFLECTIONBLUR\\nfloat reflectionLOD=vReflectionInfos.y;\\n#ifdef TEXTURELODSUPPORT\\n\\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\\n#else\\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\\nif(lodReflectionNormalizedDoubled<1.0){\\nreflectionColor=mix(\\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\\nreflectionSpecularMid,\\nlodReflectionNormalizedDoubled\\n);\\n} else {\\nreflectionColor=mix(\\nreflectionSpecularMid,\\nsampleReflection(reflectionSamplerLow,reflectionCoords),\\nlodReflectionNormalizedDoubled-1.0\\n);\\n}\\n#endif\\n#else\\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\\nreflectionColor=reflectionSample;\\n#endif\\n#ifdef RGBDREFLECTION\\nreflectionColor.rgb=fromRGBD(reflectionColor);\\n#endif\\n#ifdef GAMMAREFLECTION\\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\\n#endif\\n#ifdef REFLECTIONBGR\\nreflectionColor.rgb=reflectionColor.bgr;\\n#endif\\n\\nreflectionColor.rgb*=vReflectionInfos.x;\\n#endif\\n\\nvec3 diffuseColor=vec3(1.,1.,1.);\\nfloat finalAlpha=alpha;\\n#ifdef DIFFUSE\\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\\n#ifdef GAMMADIFFUSE\\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\\n#endif\\n\\ndiffuseMap.rgb*=vDiffuseInfos.y;\\n#ifdef DIFFUSEHASALPHA\\nfinalAlpha*=diffuseMap.a;\\n#endif\\ndiffuseColor=diffuseMap.rgb;\\n#endif\\n\\n#ifdef REFLECTIONFRESNEL\\nvec3 colorBase=diffuseColor;\\n#else\\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\\n#endif\\ncolorBase=max(colorBase,0.0);\\n\\n#ifdef USERGBCOLOR\\nvec3 finalColor=colorBase;\\n#else\\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\\n#else\\nvec3 mainColor=vPrimaryColor.rgb;\\n#endif\\nvec3 finalColor=colorBase*mainColor;\\n#endif\\n\\n#ifdef REFLECTIONFRESNEL\\nvec3 reflectionAmount=vReflectionControl.xxx;\\nvec3 reflectionReflectance0=vReflectionControl.yyy;\\nvec3 reflectionReflectance90=vReflectionControl.zzz;\\nfloat VdotN=dot(normalize(vEyePosition),normalW);\\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\\nreflectionAmount*=planarReflectionFresnel;\\n#ifdef REFLECTIONFALLOFF\\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\\nreflectionAmount*=reflectionDistanceFalloff;\\n#endif\\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\\n#endif\\n#ifdef OPACITYFRESNEL\\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\\n\\nconst float startAngle=0.1;\\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\\nfinalAlpha*=fadeFactor*fadeFactor;\\n#endif\\n\\n#ifdef SHADOWINUSE\\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\\n#endif\\n\\nvec4 color=vec4(finalColor,finalAlpha);\\n#include\\n#ifdef IMAGEPROCESSINGPOSTPROCESS\\n\\n\\ncolor.rgb=clamp(color.rgb,0.,30.0);\\n#else\\n\\ncolor=applyImageProcessing(color);\\n#endif\\n#ifdef PREMULTIPLYALPHA\\n\\ncolor.rgb*=color.a;\\n#endif\\n#ifdef NOISE\\ncolor.rgb+=dither(vPositionW.xy,0.5);\\ncolor=max(color,0.0);\\n#endif\\ngl_FragColor=color;\\n}\\n\",\"noisePixelShader\":\"\\n\\nuniform float brightness;\\nuniform int octaves;\\nuniform float persistence;\\nuniform float timeScale;\\n\\nvarying vec2 vUV;\\n\\nvec2 hash22(vec2 p)\\n{\\np=p*mat2(127.1,311.7,269.5,183.3);\\np=-1.0+2.0*fract(sin(p)*43758.5453123);\\nreturn sin(p*6.283+timeScale);\\n}\\nfloat interpolationNoise(vec2 p)\\n{\\nvec2 pi=floor(p);\\nvec2 pf=p-pi;\\nvec2 w=pf*pf*(3.-2.*pf);\\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\\nfloat xm1=mix(f00,f10,w.x);\\nfloat xm2=mix(f01,f11,w.x);\\nfloat ym=mix(xm1,xm2,w.y); \\nreturn ym;\\n}\\nfloat perlinNoise2D(float x,float y)\\n{\\nfloat sum=0.0;\\nfloat frequency=0.0;\\nfloat amplitude=0.0;\\nfor(int i=0; i0\\nuniform mat4 mBones[BonesPerMesh];\\nattribute vec4 matricesIndices;\\nattribute vec4 matricesWeights;\\n#if NUM_BONE_INFLUENCERS>4\\nattribute vec4 matricesIndicesExtra;\\nattribute vec4 matricesWeightsExtra;\\n#endif\\n#endif\",\"instancesDeclaration\":\"#ifdef INSTANCES\\nattribute vec4 world0;\\nattribute vec4 world1;\\nattribute vec4 world2;\\nattribute vec4 world3;\\n#else\\nuniform mat4 world;\\n#endif\",\"pointCloudVertexDeclaration\":\"#ifdef POINTSIZE\\nuniform float pointSize;\\n#endif\",\"bumpVertexDeclaration\":\"#if defined(BUMP) || defined(PARALLAX)\\n#if defined(TANGENT) && defined(NORMAL) \\nvarying mat3 vTBN;\\n#endif\\n#endif\\n\",\"clipPlaneVertexDeclaration\":\"#ifdef CLIPPLANE\\nuniform vec4 vClipPlane;\\nvarying float fClipDistance;\\n#endif\",\"fogVertexDeclaration\":\"#ifdef FOG\\nvarying vec3 vFogDistance;\\n#endif\",\"morphTargetsVertexGlobalDeclaration\":\"#ifdef MORPHTARGETS\\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\\n#endif\",\"morphTargetsVertexDeclaration\":\"#ifdef MORPHTARGETS\\nattribute vec3 position{X};\\n#ifdef MORPHTARGETS_NORMAL\\nattribute vec3 normal{X};\\n#endif\\n#ifdef MORPHTARGETS_TANGENT\\nattribute vec3 tangent{X};\\n#endif\\n#endif\",\"logDepthDeclaration\":\"#ifdef LOGARITHMICDEPTH\\nuniform float logarithmicDepthConstant;\\nvarying float vFragmentDepth;\\n#endif\",\"morphTargetsVertex\":\"#ifdef MORPHTARGETS\\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\\n#ifdef MORPHTARGETS_NORMAL\\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\\n#endif\\n#ifdef MORPHTARGETS_TANGENT\\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\\n#endif\\n#endif\",\"instancesVertex\":\"#ifdef INSTANCES\\nmat4 finalWorld=mat4(world0,world1,world2,world3);\\n#else\\nmat4 finalWorld=world;\\n#endif\",\"bonesVertex\":\"#if NUM_BONE_INFLUENCERS>0\\nmat4 influence;\\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\\n#if NUM_BONE_INFLUENCERS>1\\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\\n#endif \\n#if NUM_BONE_INFLUENCERS>2\\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\\n#endif \\n#if NUM_BONE_INFLUENCERS>3\\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\\n#endif \\n#if NUM_BONE_INFLUENCERS>4\\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\\n#endif \\n#if NUM_BONE_INFLUENCERS>5\\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\\n#endif \\n#if NUM_BONE_INFLUENCERS>6\\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\\n#endif \\n#if NUM_BONE_INFLUENCERS>7\\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\\n#endif \\nfinalWorld=finalWorld*influence;\\n#endif\",\"bumpVertex\":\"#if defined(BUMP) || defined(PARALLAX)\\n#if defined(TANGENT) && defined(NORMAL)\\nvec3 tbnNormal=normalize(normalUpdated);\\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\\n#endif\\n#endif\",\"clipPlaneVertex\":\"#ifdef CLIPPLANE\\nfClipDistance=dot(worldPos,vClipPlane);\\n#endif\",\"fogVertex\":\"#ifdef FOG\\nvFogDistance=(view*worldPos).xyz;\\n#endif\",\"shadowsVertex\":\"#ifdef SHADOWS\\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\\n#endif\\n#endif\",\"pointCloudVertex\":\"#ifdef POINTSIZE\\ngl_PointSize=pointSize;\\n#endif\",\"logDepthVertex\":\"#ifdef LOGARITHMICDEPTH\\nvFragmentDepth=1.0+gl_Position.w;\\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\\n#endif\",\"helperFunctions\":\"const float PI=3.1415926535897932384626433832795;\\nconst float LinearEncodePowerApprox=2.2;\\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\\nmat3 transposeMat3(mat3 inMatrix) {\\nvec3 i0=inMatrix[0];\\nvec3 i1=inMatrix[1];\\nvec3 i2=inMatrix[2];\\nmat3 outMatrix=mat3(\\nvec3(i0.x,i1.x,i2.x),\\nvec3(i0.y,i1.y,i2.y),\\nvec3(i0.z,i1.z,i2.z)\\n);\\nreturn outMatrix;\\n}\\n\\nmat3 inverseMat3(mat3 inMatrix) {\\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\\nfloat b01=a22*a11-a12*a21;\\nfloat b11=-a22*a10+a12*a20;\\nfloat b21=a21*a10-a11*a20;\\nfloat det=a00*b01+a01*b11+a02*b21;\\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\\n}\\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\\n{\\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\\nreturn mix(value,1.0,mask);\\n}\\nvec3 applyEaseInOut(vec3 x){\\nreturn x*x*(3.0-2.0*x);\\n}\\nvec3 toLinearSpace(vec3 color)\\n{\\nreturn pow(color,vec3(LinearEncodePowerApprox));\\n}\\nvec3 toGammaSpace(vec3 color)\\n{\\nreturn pow(color,vec3(GammaEncodePowerApprox));\\n}\\nfloat square(float value)\\n{\\nreturn value*value;\\n}\\nfloat getLuminance(vec3 color)\\n{\\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\\n}\\n\\nfloat getRand(vec2 seed) {\\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\\n}\\nfloat dither(vec2 seed,float varianceAmount) {\\nfloat rand=getRand(seed);\\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\\nreturn dither;\\n}\\n\\nconst float rgbdMaxRange=255.0;\\nvec4 toRGBD(vec3 color) {\\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\\nfloat D=max(rgbdMaxRange/maxRGB,1.);\\nD=clamp(floor(D)/255.0,0.,1.);\\n\\nvec3 rgb=color.rgb*D;\\n\\nrgb=toGammaSpace(rgb);\\nreturn vec4(rgb,D); \\n}\\nvec3 fromRGBD(vec4 rgbd) {\\n\\nrgbd.rgb=toLinearSpace(rgbd.rgb);\\n\\nreturn rgbd.rgb/rgbd.a;\\n}\",\"lightFragmentDeclaration\":\"#ifdef LIGHT{X}\\nuniform vec4 vLightData{X};\\nuniform vec4 vLightDiffuse{X};\\n#ifdef SPECULARTERM\\nuniform vec3 vLightSpecular{X};\\n#else\\nvec3 vLightSpecular{X}=vec3(0.);\\n#endif\\n#ifdef SHADOW{X}\\n#if defined(SHADOWCUBE{X})\\nuniform samplerCube shadowSampler{X};\\n#else\\nvarying vec4 vPositionFromLight{X};\\nvarying float vDepthMetric{X};\\n#if defined(SHADOWPCSS{X})\\nuniform highp sampler2DShadow shadowSampler{X};\\nuniform highp sampler2D depthSampler{X};\\n#elif defined(SHADOWPCF{X})\\nuniform highp sampler2DShadow shadowSampler{X};\\n#else\\nuniform sampler2D shadowSampler{X};\\n#endif\\nuniform mat4 lightMatrix{X};\\n#endif\\nuniform vec4 shadowsInfo{X};\\nuniform vec2 depthValues{X};\\n#endif\\n#ifdef SPOTLIGHT{X}\\nuniform vec4 vLightDirection{X};\\n#endif\\n#ifdef HEMILIGHT{X}\\nuniform vec3 vLightGround{X};\\n#endif\\n#ifdef PROJECTEDLIGHTTEXTURE{X}\\nuniform mat4 textureProjectionMatrix{X};\\nuniform sampler2D projectionLightSampler{X};\\n#endif\\n#endif\",\"lightsFragmentFunctions\":\"\\nstruct lightingInfo\\n{\\nvec3 diffuse;\\n#ifdef SPECULARTERM\\nvec3 specular;\\n#endif\\n#ifdef NDOTL\\nfloat ndl;\\n#endif\\n};\\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\\nlightingInfo result;\\nvec3 lightVectorW;\\nfloat attenuation=1.0;\\nif (lightData.w == 0.)\\n{\\nvec3 direction=lightData.xyz-vPositionW;\\nattenuation=max(0.,1.0-length(direction)/range);\\nlightVectorW=normalize(direction);\\n}\\nelse\\n{\\nlightVectorW=normalize(-lightData.xyz);\\n}\\n\\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\\n#ifdef NDOTL\\nresult.ndl=ndl;\\n#endif\\nresult.diffuse=ndl*diffuseColor*attenuation;\\n#ifdef SPECULARTERM\\n\\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\\nfloat specComp=max(0.,dot(vNormal,angleW));\\nspecComp=pow(specComp,max(1.,glossiness));\\nresult.specular=specComp*specularColor*attenuation;\\n#endif\\nreturn result;\\n}\\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\\nlightingInfo result;\\nvec3 direction=lightData.xyz-vPositionW;\\nvec3 lightVectorW=normalize(direction);\\nfloat attenuation=max(0.,1.0-length(direction)/range);\\n\\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\\nif (cosAngle>=lightDirection.w)\\n{\\ncosAngle=max(0.,pow(cosAngle,lightData.w));\\nattenuation*=cosAngle;\\n\\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\\n#ifdef NDOTL\\nresult.ndl=ndl;\\n#endif\\nresult.diffuse=ndl*diffuseColor*attenuation;\\n#ifdef SPECULARTERM\\n\\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\\nfloat specComp=max(0.,dot(vNormal,angleW));\\nspecComp=pow(specComp,max(1.,glossiness));\\nresult.specular=specComp*specularColor*attenuation;\\n#endif\\nreturn result;\\n}\\nresult.diffuse=vec3(0.);\\n#ifdef SPECULARTERM\\nresult.specular=vec3(0.);\\n#endif\\n#ifdef NDOTL\\nresult.ndl=0.;\\n#endif\\nreturn result;\\n}\\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\\nlightingInfo result;\\n\\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\\n#ifdef NDOTL\\nresult.ndl=ndl;\\n#endif\\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\\n#ifdef SPECULARTERM\\n\\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\\nfloat specComp=max(0.,dot(vNormal,angleW));\\nspecComp=pow(specComp,max(1.,glossiness));\\nresult.specular=specComp*specularColor;\\n#endif\\nreturn result;\\n}\\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\\nstrq/=strq.w;\\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\\nreturn textureColor;\\n}\",\"lightUboDeclaration\":\"#ifdef LIGHT{X}\\nuniform Light{X}\\n{\\nvec4 vLightData;\\nvec4 vLightDiffuse;\\nvec3 vLightSpecular;\\n#ifdef SPOTLIGHT{X}\\nvec4 vLightDirection;\\n#endif\\n#ifdef HEMILIGHT{X}\\nvec3 vLightGround;\\n#endif\\nvec4 shadowsInfo;\\nvec2 depthValues;\\n} light{X};\\n#ifdef PROJECTEDLIGHTTEXTURE{X}\\nuniform mat4 textureProjectionMatrix{X};\\nuniform sampler2D projectionLightSampler{X};\\n#endif\\n#ifdef SHADOW{X}\\n#if defined(SHADOWCUBE{X})\\nuniform samplerCube shadowSampler{X}; \\n#else\\nvarying vec4 vPositionFromLight{X};\\nvarying float vDepthMetric{X};\\n#if defined(SHADOWPCSS{X})\\nuniform highp sampler2DShadow shadowSampler{X};\\nuniform highp sampler2D depthSampler{X};\\n#elif defined(SHADOWPCF{X})\\nuniform highp sampler2DShadow shadowSampler{X};\\n#else\\nuniform sampler2D shadowSampler{X};\\n#endif\\nuniform mat4 lightMatrix{X};\\n#endif\\n#endif\\n#endif\",\"defaultVertexDeclaration\":\"\\nuniform mat4 viewProjection;\\nuniform mat4 view;\\n#ifdef DIFFUSE\\nuniform mat4 diffuseMatrix;\\nuniform vec2 vDiffuseInfos;\\n#endif\\n#ifdef AMBIENT\\nuniform mat4 ambientMatrix;\\nuniform vec2 vAmbientInfos;\\n#endif\\n#ifdef OPACITY\\nuniform mat4 opacityMatrix;\\nuniform vec2 vOpacityInfos;\\n#endif\\n#ifdef EMISSIVE\\nuniform vec2 vEmissiveInfos;\\nuniform mat4 emissiveMatrix;\\n#endif\\n#ifdef LIGHTMAP\\nuniform vec2 vLightmapInfos;\\nuniform mat4 lightmapMatrix;\\n#endif\\n#if defined(SPECULAR) && defined(SPECULARTERM)\\nuniform vec2 vSpecularInfos;\\nuniform mat4 specularMatrix;\\n#endif\\n#ifdef BUMP\\nuniform vec3 vBumpInfos;\\nuniform mat4 bumpMatrix;\\n#endif\\n#ifdef POINTSIZE\\nuniform float pointSize;\\n#endif\\n\",\"defaultFragmentDeclaration\":\"uniform vec4 vDiffuseColor;\\n#ifdef SPECULARTERM\\nuniform vec4 vSpecularColor;\\n#endif\\nuniform vec3 vEmissiveColor;\\n\\n#ifdef DIFFUSE\\nuniform vec2 vDiffuseInfos;\\n#endif\\n#ifdef AMBIENT\\nuniform vec2 vAmbientInfos;\\n#endif\\n#ifdef OPACITY \\nuniform vec2 vOpacityInfos;\\n#endif\\n#ifdef EMISSIVE\\nuniform vec2 vEmissiveInfos;\\n#endif\\n#ifdef LIGHTMAP\\nuniform vec2 vLightmapInfos;\\n#endif\\n#ifdef BUMP\\nuniform vec3 vBumpInfos;\\nuniform vec2 vTangentSpaceParams;\\n#endif\\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\\nuniform mat4 view;\\n#endif\\n#ifdef REFRACTION\\nuniform vec4 vRefractionInfos;\\n#ifndef REFRACTIONMAP_3D\\nuniform mat4 refractionMatrix;\\n#endif\\n#ifdef REFRACTIONFRESNEL\\nuniform vec4 refractionLeftColor;\\nuniform vec4 refractionRightColor;\\n#endif\\n#endif\\n#if defined(SPECULAR) && defined(SPECULARTERM)\\nuniform vec2 vSpecularInfos;\\n#endif\\n#ifdef DIFFUSEFRESNEL\\nuniform vec4 diffuseLeftColor;\\nuniform vec4 diffuseRightColor;\\n#endif\\n#ifdef OPACITYFRESNEL\\nuniform vec4 opacityParts;\\n#endif\\n#ifdef EMISSIVEFRESNEL\\nuniform vec4 emissiveLeftColor;\\nuniform vec4 emissiveRightColor;\\n#endif\\n\\n#ifdef REFLECTION\\nuniform vec2 vReflectionInfos;\\n#ifdef REFLECTIONMAP_SKYBOX\\n#else\\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\\nuniform mat4 reflectionMatrix;\\n#endif\\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\\nuniform vec3 vReflectionPosition;\\nuniform vec3 vReflectionSize; \\n#endif\\n#endif\\n#ifdef REFLECTIONFRESNEL\\nuniform vec4 reflectionLeftColor;\\nuniform vec4 reflectionRightColor;\\n#endif\\n#endif\",\"defaultUboDeclaration\":\"layout(std140,column_major) uniform;\\nuniform Material\\n{\\nvec4 diffuseLeftColor;\\nvec4 diffuseRightColor;\\nvec4 opacityParts;\\nvec4 reflectionLeftColor;\\nvec4 reflectionRightColor;\\nvec4 refractionLeftColor;\\nvec4 refractionRightColor;\\nvec4 emissiveLeftColor; \\nvec4 emissiveRightColor;\\nvec2 vDiffuseInfos;\\nvec2 vAmbientInfos;\\nvec2 vOpacityInfos;\\nvec2 vReflectionInfos;\\nvec3 vReflectionPosition;\\nvec3 vReflectionSize;\\nvec2 vEmissiveInfos;\\nvec2 vLightmapInfos;\\nvec2 vSpecularInfos;\\nvec3 vBumpInfos;\\nmat4 diffuseMatrix;\\nmat4 ambientMatrix;\\nmat4 opacityMatrix;\\nmat4 reflectionMatrix;\\nmat4 emissiveMatrix;\\nmat4 lightmapMatrix;\\nmat4 specularMatrix;\\nmat4 bumpMatrix; \\nvec4 vTangentSpaceParams;\\nmat4 refractionMatrix;\\nvec4 vRefractionInfos;\\nvec4 vSpecularColor;\\nvec3 vEmissiveColor;\\nvec4 vDiffuseColor;\\nfloat pointSize; \\n};\\nuniform Scene {\\nmat4 viewProjection;\\nmat4 view;\\n};\",\"shadowsFragmentFunctions\":\"#ifdef SHADOWS\\n#ifndef SHADOWFLOAT\\nfloat unpack(vec4 color)\\n{\\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\\nreturn dot(color,bit_shift);\\n}\\n#endif\\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\\n{\\nvec3 directionToLight=vPositionW-lightPosition;\\nfloat depth=length(directionToLight);\\ndepth=(depth+depthValues.x)/(depthValues.y);\\ndepth=clamp(depth,0.,1.0);\\ndirectionToLight=normalize(directionToLight);\\ndirectionToLight.y=-directionToLight.y;\\n#ifndef SHADOWFLOAT\\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\\n#else\\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\\n#endif\\nif (depth>shadow)\\n{\\nreturn darkness;\\n}\\nreturn 1.0;\\n}\\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\\n{\\nvec3 directionToLight=vPositionW-lightPosition;\\nfloat depth=length(directionToLight);\\ndepth=(depth+depthValues.x)/(depthValues.y);\\ndepth=clamp(depth,0.,1.0);\\ndirectionToLight=normalize(directionToLight);\\ndirectionToLight.y=-directionToLight.y;\\nfloat visibility=1.;\\nvec3 poissonDisk[4];\\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\\n\\n#ifndef SHADOWFLOAT\\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\\n{\\nreturn 1.0;\\n}\\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\\n#ifndef SHADOWFLOAT\\nfloat shadow=unpack(texture2D(shadowSampler,uv));\\n#else\\nfloat shadow=texture2D(shadowSampler,uv).x;\\n#endif\\nif (shadowPixelDepth>shadow)\\n{\\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\\n}\\nreturn 1.;\\n}\\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\\n{\\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\\n{\\nreturn 1.0;\\n}\\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\\nfloat visibility=1.;\\nvec2 poissonDisk[4];\\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\\npoissonDisk[3]=vec2(0.34495938,0.29387760);\\n\\n#ifndef SHADOWFLOAT\\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\\n{\\nreturn 1.0;\\n}\\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\\n#ifndef SHADOWFLOAT\\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\\n#else\\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\\n#endif\\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\\n}\\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\\n{\\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\\n{\\nreturn 1.0;\\n}\\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \\n#ifndef SHADOWFLOAT\\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\\n#else\\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\\n#endif\\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\\n}\\n#ifdef WEBGL2\\n\\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\\n{\\nif (depthMetric>1.0 || depthMetric<0.0) {\\nreturn 1.0;\\n}\\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\\nfloat shadow=texture2D(shadowSampler,uvDepth);\\nshadow=mix(darkness,1.,shadow);\\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\\n}\\n\\n\\n\\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\\n{\\nif (depthMetric>1.0 || depthMetric<0.0) {\\nreturn 1.0;\\n}\\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \\nuv+=0.5; \\nvec2 st=fract(uv); \\nvec2 base_uv=floor(uv)-0.5; \\nbase_uv*=shadowMapSizeAndInverse.y; \\n\\n\\n\\n\\nvec2 uvw0=3.-2.*st;\\nvec2 uvw1=1.+2.*st;\\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\\nfloat shadow=0.;\\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\\nshadow=shadow/16.;\\nshadow=mix(darkness,1.,shadow);\\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\\n}\\n\\n\\n\\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\\n{\\nif (depthMetric>1.0 || depthMetric<0.0) {\\nreturn 1.0;\\n}\\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \\nuv+=0.5; \\nvec2 st=fract(uv); \\nvec2 base_uv=floor(uv)-0.5; \\nbase_uv*=shadowMapSizeAndInverse.y; \\n\\n\\nvec2 uvw0=4.-3.*st;\\nvec2 uvw1=vec2(7.);\\nvec2 uvw2=1.+3.*st;\\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\\nfloat shadow=0.;\\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\\nshadow=shadow/144.;\\nshadow=mix(darkness,1.,shadow);\\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\\n}\\nconst vec3 PoissonSamplers32[64]=vec3[64](\\nvec3(0.06407013,0.05409927,0.),\\nvec3(0.7366577,0.5789394,0.),\\nvec3(-0.6270542,-0.5320278,0.),\\nvec3(-0.4096107,0.8411095,0.),\\nvec3(0.6849564,-0.4990818,0.),\\nvec3(-0.874181,-0.04579735,0.),\\nvec3(0.9989998,0.0009880066,0.),\\nvec3(-0.004920578,-0.9151649,0.),\\nvec3(0.1805763,0.9747483,0.),\\nvec3(-0.2138451,0.2635818,0.),\\nvec3(0.109845,0.3884785,0.),\\nvec3(0.06876755,-0.3581074,0.),\\nvec3(0.374073,-0.7661266,0.),\\nvec3(0.3079132,-0.1216763,0.),\\nvec3(-0.3794335,-0.8271583,0.),\\nvec3(-0.203878,-0.07715034,0.),\\nvec3(0.5912697,0.1469799,0.),\\nvec3(-0.88069,0.3031784,0.),\\nvec3(0.5040108,0.8283722,0.),\\nvec3(-0.5844124,0.5494877,0.),\\nvec3(0.6017799,-0.1726654,0.),\\nvec3(-0.5554981,0.1559997,0.),\\nvec3(-0.3016369,-0.3900928,0.),\\nvec3(-0.5550632,-0.1723762,0.),\\nvec3(0.925029,0.2995041,0.),\\nvec3(-0.2473137,0.5538505,0.),\\nvec3(0.9183037,-0.2862392,0.),\\nvec3(0.2469421,0.6718712,0.),\\nvec3(0.3916397,-0.4328209,0.),\\nvec3(-0.03576927,-0.6220032,0.),\\nvec3(-0.04661255,0.7995201,0.),\\nvec3(0.4402924,0.3640312,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.),\\nvec3(0.,0.,0.)\\n);\\nconst vec3 PoissonSamplers64[64]=vec3[64](\\nvec3(-0.613392,0.617481,0.),\\nvec3(0.170019,-0.040254,0.),\\nvec3(-0.299417,0.791925,0.),\\nvec3(0.645680,0.493210,0.),\\nvec3(-0.651784,0.717887,0.),\\nvec3(0.421003,0.027070,0.),\\nvec3(-0.817194,-0.271096,0.),\\nvec3(-0.705374,-0.668203,0.),\\nvec3(0.977050,-0.108615,0.),\\nvec3(0.063326,0.142369,0.),\\nvec3(0.203528,0.214331,0.),\\nvec3(-0.667531,0.326090,0.),\\nvec3(-0.098422,-0.295755,0.),\\nvec3(-0.885922,0.215369,0.),\\nvec3(0.566637,0.605213,0.),\\nvec3(0.039766,-0.396100,0.),\\nvec3(0.751946,0.453352,0.),\\nvec3(0.078707,-0.715323,0.),\\nvec3(-0.075838,-0.529344,0.),\\nvec3(0.724479,-0.580798,0.),\\nvec3(0.222999,-0.215125,0.),\\nvec3(-0.467574,-0.405438,0.),\\nvec3(-0.248268,-0.814753,0.),\\nvec3(0.354411,-0.887570,0.),\\nvec3(0.175817,0.382366,0.),\\nvec3(0.487472,-0.063082,0.),\\nvec3(-0.084078,0.898312,0.),\\nvec3(0.488876,-0.783441,0.),\\nvec3(0.470016,0.217933,0.),\\nvec3(-0.696890,-0.549791,0.),\\nvec3(-0.149693,0.605762,0.),\\nvec3(0.034211,0.979980,0.),\\nvec3(0.503098,-0.308878,0.),\\nvec3(-0.016205,-0.872921,0.),\\nvec3(0.385784,-0.393902,0.),\\nvec3(-0.146886,-0.859249,0.),\\nvec3(0.643361,0.164098,0.),\\nvec3(0.634388,-0.049471,0.),\\nvec3(-0.688894,0.007843,0.),\\nvec3(0.464034,-0.188818,0.),\\nvec3(-0.440840,0.137486,0.),\\nvec3(0.364483,0.511704,0.),\\nvec3(0.034028,0.325968,0.),\\nvec3(0.099094,-0.308023,0.),\\nvec3(0.693960,-0.366253,0.),\\nvec3(0.678884,-0.204688,0.),\\nvec3(0.001801,0.780328,0.),\\nvec3(0.145177,-0.898984,0.),\\nvec3(0.062655,-0.611866,0.),\\nvec3(0.315226,-0.604297,0.),\\nvec3(-0.780145,0.486251,0.),\\nvec3(-0.371868,0.882138,0.),\\nvec3(0.200476,0.494430,0.),\\nvec3(-0.494552,-0.711051,0.),\\nvec3(0.612476,0.705252,0.),\\nvec3(-0.578845,-0.768792,0.),\\nvec3(-0.772454,-0.090976,0.),\\nvec3(0.504440,0.372295,0.),\\nvec3(0.155736,0.065157,0.),\\nvec3(0.391522,0.849605,0.),\\nvec3(-0.620106,-0.328104,0.),\\nvec3(0.789239,-0.419965,0.),\\nvec3(-0.545396,0.538133,0.),\\nvec3(-0.178564,-0.596057,0.)\\n);\\n\\n\\n\\n\\n\\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\\n{\\nif (depthMetric>1.0 || depthMetric<0.0) {\\nreturn 1.0;\\n}\\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\\nfloat blockerDepth=0.0;\\nfloat sumBlockerDepth=0.0;\\nfloat numBlocker=0.0;\\nfor (int i=0; icurrRayHeight)\\n{\\nfloat delta1=currSampledHeight-currRayHeight;\\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\\nfloat ratio=delta1/(delta1+delta2);\\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\\n\\nbreak;\\n}\\nelse\\n{\\ncurrRayHeight-=stepSize;\\nvLastOffset=vCurrOffset;\\nvCurrOffset+=stepSize*vMaxOffset;\\nlastSampledHeight=currSampledHeight;\\n}\\n}\\nreturn vCurrOffset;\\n}\\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\\n{\\n\\nfloat height=texture2D(bumpSampler,vBumpUV).w;\\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\\nreturn -texCoordOffset;\\n}\\n#endif\\n#endif\",\"clipPlaneFragmentDeclaration\":\"#ifdef CLIPPLANE\\nvarying float fClipDistance;\\n#endif\",\"fogFragmentDeclaration\":\"#ifdef FOG\\n#define FOGMODE_NONE 0.\\n#define FOGMODE_EXP 1.\\n#define FOGMODE_EXP2 2.\\n#define FOGMODE_LINEAR 3.\\n#define E 2.71828\\nuniform vec4 vFogInfos;\\nuniform vec3 vFogColor;\\nvarying vec3 vFogDistance;\\nfloat CalcFogFactor()\\n{\\nfloat fogCoeff=1.0;\\nfloat fogStart=vFogInfos.y;\\nfloat fogEnd=vFogInfos.z;\\nfloat fogDensity=vFogInfos.w;\\nfloat fogDistance=length(vFogDistance);\\nif (FOGMODE_LINEAR == vFogInfos.x)\\n{\\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\\n}\\nelse if (FOGMODE_EXP == vFogInfos.x)\\n{\\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\\n}\\nelse if (FOGMODE_EXP2 == vFogInfos.x)\\n{\\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\\n}\\nreturn clamp(fogCoeff,0.0,1.0);\\n}\\n#endif\",\"clipPlaneFragment\":\"#ifdef CLIPPLANE\\nif (fClipDistance>0.0)\\n{\\ndiscard;\\n}\\n#endif\",\"bumpFragment\":\"vec2 uvOffset=vec2(0.0,0.0);\\n#if defined(BUMP) || defined(PARALLAX)\\n#ifdef NORMALXYSCALE\\nfloat normalScale=1.0;\\n#else \\nfloat normalScale=vBumpInfos.y;\\n#endif\\n#if defined(TANGENT) && defined(NORMAL)\\nmat3 TBN=vTBN;\\n#else\\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\\n#endif\\n#endif\\n#ifdef PARALLAX\\nmat3 invTBN=transposeMat3(TBN);\\n#ifdef PARALLAXOCCLUSION\\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\\n#else\\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\\n#endif\\n#endif\\n#ifdef BUMP\\n#ifdef OBJECTSPACE_NORMALMAP\\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\\nnormalW=normalize(mat3(normalMatrix)*normalW); \\n#else\\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\\n#endif\\n#endif\",\"lightFragment\":\"#ifdef LIGHT{X}\\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\\n\\n#else\\n#ifdef PBR\\n#ifdef SPOTLIGHT{X}\\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\\n#endif\\n#ifdef HEMILIGHT{X}\\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\\n#endif\\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\\n#endif\\n#else\\n#ifdef SPOTLIGHT{X}\\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\\n#endif\\n#ifdef HEMILIGHT{X}\\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\\n#endif\\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\\n#endif\\n#endif\\n#ifdef PROJECTEDLIGHTTEXTURE{X}\\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\\n#endif\\n#endif\\n#ifdef SHADOW{X}\\n#ifdef SHADOWCLOSEESM{X}\\n#if defined(SHADOWCUBE{X})\\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\\n#else\\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\\n#endif\\n#elif defined(SHADOWESM{X})\\n#if defined(SHADOWCUBE{X})\\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\\n#else\\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\\n#endif\\n#elif defined(SHADOWPOISSON{X})\\n#if defined(SHADOWCUBE{X})\\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\\n#else\\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#endif\\n#elif defined(SHADOWPCF{X})\\n#if defined(SHADOWLOWQUALITY{X})\\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#elif defined(SHADOWMEDIUMQUALITY{X})\\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#else\\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#endif\\n#elif defined(SHADOWPCSS{X})\\n#if defined(SHADOWLOWQUALITY{X})\\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#elif defined(SHADOWMEDIUMQUALITY{X})\\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#else\\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#endif\\n#else\\n#if defined(SHADOWCUBE{X})\\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\\n#else\\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\\n#endif\\n#endif\\n#ifdef SHADOWONLY\\n#ifndef SHADOWINUSE\\n#define SHADOWINUSE\\n#endif\\nglobalShadow+=shadow;\\nshadowLightCount+=1.0;\\n#endif\\n#else\\nshadow=1.;\\n#endif\\n#ifndef SHADOWONLY\\n#ifdef CUSTOMUSERLIGHTING\\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\\n#ifdef SPECULARTERM\\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\\n#endif\\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\\ndiffuseBase+=lightmapColor*shadow;\\n#ifdef SPECULARTERM\\n#ifndef LIGHTMAPNOSPECULAR{X}\\nspecularBase+=info.specular*shadow*lightmapColor;\\n#endif\\n#endif\\n#else\\ndiffuseBase+=info.diffuse*shadow;\\n#ifdef SPECULARTERM\\nspecularBase+=info.specular*shadow;\\n#endif\\n#endif\\n#endif\\n#endif\",\"logDepthFragment\":\"#ifdef LOGARITHMICDEPTH\\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\\n#endif\",\"fogFragment\":\"#ifdef FOG\\nfloat fog=CalcFogFactor();\\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\\n#endif\",\"pbrVertexDeclaration\":\"uniform mat4 view;\\nuniform mat4 viewProjection;\\n#ifdef ALBEDO\\nuniform mat4 albedoMatrix;\\nuniform vec2 vAlbedoInfos;\\n#endif\\n#ifdef AMBIENT\\nuniform mat4 ambientMatrix;\\nuniform vec3 vAmbientInfos;\\n#endif\\n#ifdef OPACITY\\nuniform mat4 opacityMatrix;\\nuniform vec2 vOpacityInfos;\\n#endif\\n#ifdef EMISSIVE\\nuniform vec2 vEmissiveInfos;\\nuniform mat4 emissiveMatrix;\\n#endif\\n#ifdef LIGHTMAP\\nuniform vec2 vLightmapInfos;\\nuniform mat4 lightmapMatrix;\\n#endif\\n#ifdef REFLECTIVITY \\nuniform vec3 vReflectivityInfos;\\nuniform mat4 reflectivityMatrix;\\n#endif\\n#ifdef MICROSURFACEMAP\\nuniform vec2 vMicroSurfaceSamplerInfos;\\nuniform mat4 microSurfaceSamplerMatrix;\\n#endif\\n#ifdef BUMP\\nuniform vec3 vBumpInfos;\\nuniform mat4 bumpMatrix;\\n#endif\\n#ifdef POINTSIZE\\nuniform float pointSize;\\n#endif\\n\\n#ifdef REFRACTION\\nuniform vec4 vRefractionInfos;\\nuniform mat4 refractionMatrix;\\nuniform vec3 vRefractionMicrosurfaceInfos;\\n#endif\\n\\n#ifdef REFLECTION\\nuniform vec2 vReflectionInfos;\\nuniform mat4 reflectionMatrix;\\nuniform vec3 vReflectionMicrosurfaceInfos;\\n#endif\\n\",\"pbrFragmentDeclaration\":\"uniform vec3 vReflectionColor;\\nuniform vec4 vAlbedoColor;\\n\\nuniform vec4 vLightingIntensity;\\nuniform vec4 vReflectivityColor;\\nuniform vec3 vEmissiveColor;\\n\\n#ifdef ALBEDO\\nuniform vec2 vAlbedoInfos;\\n#endif\\n#ifdef AMBIENT\\nuniform vec3 vAmbientInfos;\\n#endif\\n#ifdef BUMP\\nuniform vec3 vBumpInfos;\\nuniform vec2 vTangentSpaceParams;\\n#endif\\n#ifdef OPACITY \\nuniform vec2 vOpacityInfos;\\n#endif\\n#ifdef EMISSIVE\\nuniform vec2 vEmissiveInfos;\\n#endif\\n#ifdef LIGHTMAP\\nuniform vec2 vLightmapInfos;\\n#endif\\n#ifdef REFLECTIVITY\\nuniform vec3 vReflectivityInfos;\\n#endif\\n#ifdef MICROSURFACEMAP\\nuniform vec2 vMicroSurfaceSamplerInfos;\\n#endif\\n\\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\\nuniform mat4 view;\\n#endif\\n\\n#ifdef REFRACTION\\nuniform vec4 vRefractionInfos;\\nuniform mat4 refractionMatrix;\\nuniform vec3 vRefractionMicrosurfaceInfos;\\n#endif\\n\\n#ifdef REFLECTION\\nuniform vec2 vReflectionInfos;\\nuniform mat4 reflectionMatrix;\\nuniform vec3 vReflectionMicrosurfaceInfos;\\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\\nuniform vec3 vReflectionPosition;\\nuniform vec3 vReflectionSize; \\n#endif\\n#endif\",\"pbrUboDeclaration\":\"layout(std140,column_major) uniform;\\nuniform Material\\n{\\nuniform vec2 vAlbedoInfos;\\nuniform vec3 vAmbientInfos;\\nuniform vec2 vOpacityInfos;\\nuniform vec2 vEmissiveInfos;\\nuniform vec2 vLightmapInfos;\\nuniform vec3 vReflectivityInfos;\\nuniform vec2 vMicroSurfaceSamplerInfos;\\nuniform vec4 vRefractionInfos;\\nuniform vec2 vReflectionInfos;\\nuniform vec3 vReflectionPosition;\\nuniform vec3 vReflectionSize; \\nuniform vec3 vBumpInfos;\\nuniform mat4 albedoMatrix;\\nuniform mat4 ambientMatrix;\\nuniform mat4 opacityMatrix;\\nuniform mat4 emissiveMatrix;\\nuniform mat4 lightmapMatrix;\\nuniform mat4 reflectivityMatrix;\\nuniform mat4 microSurfaceSamplerMatrix;\\nuniform mat4 bumpMatrix;\\nuniform vec2 vTangentSpaceParams;\\nuniform mat4 refractionMatrix;\\nuniform mat4 reflectionMatrix;\\nuniform vec3 vReflectionColor;\\nuniform vec4 vAlbedoColor;\\nuniform vec4 vLightingIntensity;\\nuniform vec3 vRefractionMicrosurfaceInfos;\\nuniform vec3 vReflectionMicrosurfaceInfos;\\nuniform vec4 vReflectivityColor;\\nuniform vec3 vEmissiveColor;\\nuniform float pointSize;\\n};\\nuniform Scene {\\nmat4 viewProjection;\\nmat4 view;\\n};\",\"pbrFunctions\":\"\\n#define RECIPROCAL_PI2 0.15915494\\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\\n\\nconst float kRougnhessToAlphaScale=0.1;\\nconst float kRougnhessToAlphaOffset=0.29248125;\\nfloat convertRoughnessToAverageSlope(float roughness)\\n{\\n\\nconst float kMinimumVariance=0.0005;\\nfloat alphaG=square(roughness)+kMinimumVariance;\\nreturn alphaG;\\n}\\n\\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\\n{\\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\\n}\\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\\n{\\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\\n}\\n\\n\\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\\n{\\n\\n\\n\\nfloat a2=square(alphaG);\\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\\nreturn a2/(PI*d*d);\\n}\\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\\n{\\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\\n}\\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\\n{\\n\\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\\n}\\n\\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\\n{\\nroughness=max(roughness,geometricRoughnessFactor);\\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\\nvisibility/=(4.0*NdotL*NdotV); \\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\\nreturn fresnel*specTerm;\\n}\\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\\n{\\n\\n\\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\\nfloat fresnel =\\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\\nreturn fresnel*NdotL/PI;\\n}\\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\\n{\\n#ifdef USEPHYSICALLIGHTFALLOFF\\n\\nfloat lightRoughness=lightRadius/lightDistance;\\n\\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\\nreturn totalRoughness;\\n#else\\nreturn roughness;\\n#endif\\n}\\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\\n{\\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\\nreturn microSurface;\\n}\\n\\n\\nfloat fresnelGrazingReflectance(float reflectance0) {\\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\\nreturn reflectance90;\\n}\\n\\n\\n#define UNPACK_LOD(x) (1.0-x)*255.0\\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\\nfloat microsurfaceAverageSlope=alphaG;\\n\\n\\n\\n\\n\\n\\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\\nfloat lod=log2(microsurfaceAverageSlopeTexels);\\nreturn lod;\\n}\\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\\n\\n\\nfloat temp=NdotVUnclamped+ambientOcclusion;\\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\\n}\\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\\n\\nvec3 reflection=reflect(view,normal);\\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\\nreturn square(temp);\\n}\",\"harmonicsFunctions\":\"#ifdef USESPHERICALFROMREFLECTIONMAP\\nuniform vec3 vSphericalX;\\nuniform vec3 vSphericalY;\\nuniform vec3 vSphericalZ;\\nuniform vec3 vSphericalXX_ZZ;\\nuniform vec3 vSphericalYY_ZZ;\\nuniform vec3 vSphericalZZ;\\nuniform vec3 vSphericalXY;\\nuniform vec3 vSphericalYZ;\\nuniform vec3 vSphericalZX;\\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\\nvec3 T=cross(Q.xyz,V);\\nT+=Q.www*V;\\nreturn cross(Q.xyz,T)+V;\\n}\\nvec3 environmentIrradianceJones(vec3 normal)\\n{\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nfloat Nx=normal.x;\\nfloat Ny=normal.y;\\nfloat Nz=normal.z;\\nvec3 C1=vSphericalZZ.rgb;\\nvec3 Cx=vSphericalX.rgb;\\nvec3 Cy=vSphericalY.rgb;\\nvec3 Cz=vSphericalZ.rgb;\\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\\nvec3 Cxy=vSphericalXY.rgb;\\nvec3 Cyz=vSphericalYZ.rgb;\\nvec3 Czx=vSphericalZX.rgb;\\nvec3 a1=Cyy_zz*Ny+Cy;\\nvec3 a2=Cyz*Nz+a1;\\nvec3 b1=Czx*Nz+Cx;\\nvec3 b2=Cxy*Ny+b1;\\nvec3 b3=Cxx_zz*Nx+b2;\\nvec3 t1=Cz*Nz+C1;\\nvec3 t2=a2*Ny+t1;\\nvec3 t3=b3*Nx+t2;\\nreturn t3;\\n}\\n#endif\",\"pbrLightFunctions\":\"\\nstruct lightingInfo\\n{\\nvec3 diffuse;\\n#ifdef SPECULARTERM\\nvec3 specular;\\n#endif\\n};\\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\\n{ \\n#ifdef USEPHYSICALLIGHTFALLOFF\\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\\n#else\\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\\n#endif\\nreturn lightDistanceFalloff;\\n}\\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\\n{\\nfloat falloff=0.0;\\n#ifdef USEPHYSICALLIGHTFALLOFF\\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \\n\\n\\n\\n\\n\\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\\n\\n\\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\\n#else\\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\\nif (cosAngle>=cosHalfAngle)\\n{\\nfalloff=max(0.,pow(cosAngle,exponent));\\n}\\n#endif\\nreturn falloff;\\n}\\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\\nlightingInfo result;\\nvec3 lightDirection;\\nfloat attenuation=1.0;\\nfloat lightDistance;\\n\\nif (lightData.w == 0.)\\n{\\nvec3 lightOffset=lightData.xyz-vPositionW;\\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\\nlightDistance=sqrt(lightDistanceSquared);\\nlightDirection=normalize(lightOffset);\\n}\\n\\nelse\\n{\\nlightDistance=length(-lightData.xyz);\\nlightDirection=normalize(-lightData.xyz);\\n}\\n\\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\\n\\nvec3 H=normalize(viewDirectionW+lightDirection);\\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\\n#ifdef SPECULARTERM\\n\\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\\nresult.specular=specTerm*diffuseColor*attenuation;\\n#endif\\nreturn result;\\n}\\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\\nlightingInfo result;\\nvec3 lightOffset=lightData.xyz-vPositionW;\\nvec3 directionToLightCenterW=normalize(lightOffset);\\n\\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\\n\\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\\nattenuation*=directionalAttenuation;\\n\\nfloat lightDistance=sqrt(lightDistanceSquared);\\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\\n\\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\\n#ifdef SPECULARTERM\\n\\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\\nresult.specular=specTerm*diffuseColor*attenuation;\\n#endif\\nreturn result;\\n}\\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\\nlightingInfo result;\\n\\n\\n\\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\\n#ifdef SPECULARTERM\\n\\nvec3 lightVectorW=normalize(lightData.xyz);\\nvec3 H=normalize(viewDirectionW+lightVectorW);\\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\\nNdotL=clamp(NdotL,0.000000000001,1.0);\\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\\nresult.specular=specTerm*diffuseColor;\\n#endif\\nreturn result;\\n}\\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\\nstrq/=strq.w;\\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\\nreturn toLinearSpace(textureColor);\\n}\",\"kernelBlurFragment\":\"#ifdef DOF\\nfactor=sampleCoC(sampleCoord{X}); \\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\\nsumOfWeights+=computedWeight;\\n#else\\ncomputedWeight=KERNEL_WEIGHT{X};\\n#endif\\n#ifdef PACKEDFLOAT\\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\\n#else\\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\\n#endif\",\"kernelBlurFragment2\":\"#ifdef DOF\\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\\nsumOfWeights+=computedWeight;\\n#else\\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\\n#endif\\n#ifdef PACKEDFLOAT\\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\\n#else\\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\\n#endif\",\"kernelBlurVaryingDeclaration\":\"varying vec2 sampleCoord{X};\",\"kernelBlurVertex\":\"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};\",\"mrtFragmentDeclaration\":\"#if __VERSION__>=200\\nlayout(location=0) out vec4 glFragData[{X}];\\n#endif\\n\",\"bones300Declaration\":\"#if NUM_BONE_INFLUENCERS>0\\nuniform mat4 mBones[BonesPerMesh];\\nin vec4 matricesIndices;\\nin vec4 matricesWeights;\\n#if NUM_BONE_INFLUENCERS>4\\nin vec4 matricesIndicesExtra;\\nin vec4 matricesWeightsExtra;\\n#endif\\n#endif\",\"instances300Declaration\":\"#ifdef INSTANCES\\nin vec4 world0;\\nin vec4 world1;\\nin vec4 world2;\\nin vec4 world3;\\n#else\\nuniform mat4 world;\\n#endif\",\"backgroundVertexDeclaration\":\"uniform mat4 view;\\nuniform mat4 viewProjection;\\nuniform float shadowLevel;\\n#ifdef DIFFUSE\\nuniform mat4 diffuseMatrix;\\nuniform vec2 vDiffuseInfos;\\n#endif\\n#ifdef REFLECTION\\nuniform vec2 vReflectionInfos;\\nuniform mat4 reflectionMatrix;\\nuniform vec3 vReflectionMicrosurfaceInfos;\\nuniform float fFovMultiplier;\\n#endif\\n#ifdef POINTSIZE\\nuniform float pointSize;\\n#endif\",\"backgroundFragmentDeclaration\":\" uniform vec4 vPrimaryColor;\\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\\nuniform vec4 vPrimaryColorShadow;\\n#endif\\nuniform float shadowLevel;\\nuniform float alpha;\\n#ifdef DIFFUSE\\nuniform vec2 vDiffuseInfos;\\n#endif\\n#ifdef REFLECTION\\nuniform vec2 vReflectionInfos;\\nuniform mat4 reflectionMatrix;\\nuniform vec3 vReflectionMicrosurfaceInfos;\\n#endif\\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\\nuniform vec3 vBackgroundCenter;\\n#endif\\n#ifdef REFLECTIONFRESNEL\\nuniform vec4 vReflectionControl;\\n#endif\\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\\nuniform mat4 view;\\n#endif\",\"backgroundUboDeclaration\":\"layout(std140,column_major) uniform;\\nuniform Material\\n{\\nuniform vec4 vPrimaryColor;\\nuniform vec4 vPrimaryColorShadow;\\nuniform vec2 vDiffuseInfos;\\nuniform vec2 vReflectionInfos;\\nuniform mat4 diffuseMatrix;\\nuniform mat4 reflectionMatrix;\\nuniform vec3 vReflectionMicrosurfaceInfos;\\nuniform float fFovMultiplier;\\nuniform float pointSize;\\nuniform float shadowLevel;\\nuniform float alpha;\\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\\nuniform vec3 vBackgroundCenter;\\n#endif\\n#ifdef REFLECTIONFRESNEL\\nuniform vec4 vReflectionControl;\\n#endif\\n};\\nuniform Scene {\\nmat4 viewProjection;\\nmat4 view;\\n};\"};\n \nvar globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);\nglobalObject[\"BABYLON\"] = BABYLON;\n//backwards compatibility\nif(typeof earcut !== 'undefined') {\n globalObject[\"Earcut\"] = {\n earcut: earcut\n };\n}\n\n return BABYLON;\n});\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../Tools/Gulp/node_modules/webpack/buildin/global.js */ \"../Tools/Gulp/node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack://BabylonViewer/../dist/preview_release/babylon.max.js?"); /***/ }), @@ -134,7 +134,7 @@ eval("/* WEBPACK VAR INJECTION */(function(global) {\n\n(function universalModul /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { -eval("\n\n(function universalModuleDefinition(root, factory) {\n var amdDependencies = [];\n var BABYLON = root.BABYLON || this.BABYLON;\n if(true) {\n BABYLON = BABYLON || __webpack_require__(/*! babylonjs */ \"../dist/preview release/babylon.max.js\"); \n\n module.exports = factory(BABYLON);\n } else {}\n})(this, function(BABYLON) {\n BABYLON = BABYLON || this.BABYLON;\n\nvar __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if(\"object\"==typeof Reflect&&\"function\"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};\nvar __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();\n\nvar BABYLON;\n(function (BABYLON) {\n var STLFileLoader = /** @class */ (function () {\n function STLFileLoader() {\n this.solidPattern = /solid (\\S*)([\\S\\s]*)endsolid[ ]*(\\S*)/g;\n this.facetsPattern = /facet([\\s\\S]*?)endfacet/g;\n this.normalPattern = /normal[\\s]+([\\-+]?[0-9]+\\.?[0-9]*([eE][\\-+]?[0-9]+)?)+[\\s]+([\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?)+[\\s]+([\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?)+/g;\n this.vertexPattern = /vertex[\\s]+([\\-+]?[0-9]+\\.?[0-9]*([eE][\\-+]?[0-9]+)?)+[\\s]+([\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?)+[\\s]+([\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?)+/g;\n this.name = \"stl\";\n // force data to come in as an ArrayBuffer\n // we'll convert to string if it looks like it's an ASCII .stl\n this.extensions = {\n \".stl\": { isBinary: true },\n };\n }\n STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {\n var matches;\n if (typeof data !== \"string\") {\n if (this.isBinary(data)) {\n // binary .stl\n var babylonMesh = new BABYLON.Mesh(\"stlmesh\", scene);\n this.parseBinary(babylonMesh, data);\n if (meshes) {\n meshes.push(babylonMesh);\n }\n return true;\n }\n // ASCII .stl\n // convert to string\n var array_buffer = new Uint8Array(data);\n var str = '';\n for (var i = 0; i < data.byteLength; i++) {\n str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian\n }\n data = str;\n }\n //if arrived here, data is a string, containing the STLA data.\n while (matches = this.solidPattern.exec(data)) {\n var meshName = matches[1];\n var meshNameFromEnd = matches[3];\n if (meshName != meshNameFromEnd) {\n BABYLON.Tools.Error(\"Error in STL, solid name != endsolid name\");\n return false;\n }\n // check meshesNames\n if (meshesNames && meshName) {\n if (meshesNames instanceof Array) {\n if (!meshesNames.indexOf(meshName)) {\n continue;\n }\n }\n else {\n if (meshName !== meshesNames) {\n continue;\n }\n }\n }\n // stl mesh name can be empty as well\n meshName = meshName || \"stlmesh\";\n var babylonMesh = new BABYLON.Mesh(meshName, scene);\n this.parseASCII(babylonMesh, matches[2]);\n if (meshes) {\n meshes.push(babylonMesh);\n }\n }\n return true;\n };\n STLFileLoader.prototype.load = function (scene, data, rootUrl) {\n var result = this.importMesh(null, scene, data, rootUrl, null, null, null);\n if (result) {\n scene.createDefaultCameraOrLight();\n }\n return result;\n };\n STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {\n var container = new BABYLON.AssetContainer(scene);\n this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);\n container.removeAllFromScene();\n return container;\n };\n STLFileLoader.prototype.isBinary = function (data) {\n // check if file size is correct for binary stl\n var faceSize, nFaces, reader;\n reader = new DataView(data);\n faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);\n nFaces = reader.getUint32(80, true);\n if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {\n return true;\n }\n // check characters higher than ASCII to confirm binary\n var fileLength = reader.byteLength;\n for (var index = 0; index < fileLength; index++) {\n if (reader.getUint8(index) > 127) {\n return true;\n }\n }\n return false;\n };\n STLFileLoader.prototype.parseBinary = function (mesh, data) {\n var reader = new DataView(data);\n var faces = reader.getUint32(80, true);\n var dataOffset = 84;\n var faceLength = 12 * 4 + 2;\n var offset = 0;\n var positions = new Float32Array(faces * 3 * 3);\n var normals = new Float32Array(faces * 3 * 3);\n var indices = new Uint32Array(faces * 3);\n var indicesCount = 0;\n for (var face = 0; face < faces; face++) {\n var start = dataOffset + face * faceLength;\n var normalX = reader.getFloat32(start, true);\n var normalY = reader.getFloat32(start + 4, true);\n var normalZ = reader.getFloat32(start + 8, true);\n for (var i = 1; i <= 3; i++) {\n var vertexstart = start + i * 12;\n // ordering is intentional to match ascii import\n positions[offset] = reader.getFloat32(vertexstart, true);\n positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);\n positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);\n normals[offset] = normalX;\n normals[offset + 2] = normalY;\n normals[offset + 1] = normalZ;\n offset += 3;\n }\n indices[indicesCount] = indicesCount++;\n indices[indicesCount] = indicesCount++;\n indices[indicesCount] = indicesCount++;\n }\n mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);\n mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);\n mesh.setIndices(indices);\n mesh.computeWorldMatrix(true);\n };\n STLFileLoader.prototype.parseASCII = function (mesh, solidData) {\n var positions = [];\n var normals = [];\n var indices = [];\n var indicesCount = 0;\n //load facets, ignoring loop as the standard doesn't define it can contain more than vertices\n var matches;\n while (matches = this.facetsPattern.exec(solidData)) {\n var facet = matches[1];\n //one normal per face\n var normalMatches = this.normalPattern.exec(facet);\n this.normalPattern.lastIndex = 0;\n if (!normalMatches) {\n continue;\n }\n var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];\n var vertexMatch;\n while (vertexMatch = this.vertexPattern.exec(facet)) {\n positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));\n normals.push(normal[0], normal[1], normal[2]);\n }\n indices.push(indicesCount++, indicesCount++, indicesCount++);\n this.vertexPattern.lastIndex = 0;\n }\n this.facetsPattern.lastIndex = 0;\n mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);\n mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);\n mesh.setIndices(indices);\n mesh.computeWorldMatrix(true);\n };\n return STLFileLoader;\n }());\n BABYLON.STLFileLoader = STLFileLoader;\n if (BABYLON.SceneLoader) {\n BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());\n }\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stlFileLoader.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class reading and parsing the MTL file bundled with the obj file.\n */\n var MTLFileLoader = /** @class */ (function () {\n function MTLFileLoader() {\n // All material loaded from the mtl will be set here\n this.materials = [];\n }\n /**\n * This function will read the mtl file and create each material described inside\n * This function could be improve by adding :\n * -some component missing (Ni, Tf...)\n * -including the specific options available\n *\n * @param scene\n * @param data\n * @param rootUrl\n */\n MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {\n if (data instanceof ArrayBuffer) {\n return;\n }\n //Split the lines from the file\n var lines = data.split('\\n');\n //Space char\n var delimiter_pattern = /\\s+/;\n //Array with RGB colors\n var color;\n //New material\n var material = null;\n //Look at each line\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i].trim();\n // Blank line or comment\n if (line.length === 0 || line.charAt(0) === '#') {\n continue;\n }\n //Get the first parameter (keyword)\n var pos = line.indexOf(' ');\n var key = (pos >= 0) ? line.substring(0, pos) : line;\n key = key.toLowerCase();\n //Get the data following the key\n var value = (pos >= 0) ? line.substring(pos + 1).trim() : \"\";\n //This mtl keyword will create the new material\n if (key === \"newmtl\") {\n //Check if it is the first material.\n // Materials specifications are described after this keyword.\n if (material) {\n //Add the previous material in the material array.\n this.materials.push(material);\n }\n //Create a new material.\n // value is the name of the material read in the mtl file\n material = new BABYLON.StandardMaterial(value, scene);\n }\n else if (key === \"kd\" && material) {\n // Diffuse color (color under white light) using RGB values\n //value = \"r g b\"\n color = value.split(delimiter_pattern, 3).map(parseFloat);\n //color = [r,g,b]\n //Set tghe color into the material\n material.diffuseColor = BABYLON.Color3.FromArray(color);\n }\n else if (key === \"ka\" && material) {\n // Ambient color (color under shadow) using RGB values\n //value = \"r g b\"\n color = value.split(delimiter_pattern, 3).map(parseFloat);\n //color = [r,g,b]\n //Set tghe color into the material\n material.ambientColor = BABYLON.Color3.FromArray(color);\n }\n else if (key === \"ks\" && material) {\n // Specular color (color when light is reflected from shiny surface) using RGB values\n //value = \"r g b\"\n color = value.split(delimiter_pattern, 3).map(parseFloat);\n //color = [r,g,b]\n //Set the color into the material\n material.specularColor = BABYLON.Color3.FromArray(color);\n }\n else if (key === \"ke\" && material) {\n // Emissive color using RGB values\n color = value.split(delimiter_pattern, 3).map(parseFloat);\n material.emissiveColor = BABYLON.Color3.FromArray(color);\n }\n else if (key === \"ns\" && material) {\n //value = \"Integer\"\n material.specularPower = parseFloat(value);\n }\n else if (key === \"d\" && material) {\n //d is dissolve for current material. It mean alpha for BABYLON\n material.alpha = parseFloat(value);\n //Texture\n //This part can be improved by adding the possible options of texture\n }\n else if (key === \"map_ka\" && material) {\n // ambient texture map with a loaded image\n //We must first get the folder of the image\n material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);\n }\n else if (key === \"map_kd\" && material) {\n // Diffuse texture map with a loaded image\n material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);\n }\n else if (key === \"map_ks\" && material) {\n // Specular texture map with a loaded image\n //We must first get the folder of the image\n material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);\n }\n else if (key === \"map_ns\") {\n //Specular\n //Specular highlight component\n //We must first get the folder of the image\n //\n //Not supported by BABYLON\n //\n // continue;\n }\n else if (key === \"map_bump\" && material) {\n //The bump texture\n material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);\n }\n else if (key === \"map_d\" && material) {\n // The dissolve of the material\n material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);\n //Options for illumination\n }\n else if (key === \"illum\") {\n //Illumination\n if (value === \"0\") {\n //That mean Kd == Kd\n }\n else if (value === \"1\") {\n //Color on and Ambient on\n }\n else if (value === \"2\") {\n //Highlight on\n }\n else if (value === \"3\") {\n //Reflection on and Ray trace on\n }\n else if (value === \"4\") {\n //Transparency: Glass on, Reflection: Ray trace on\n }\n else if (value === \"5\") {\n //Reflection: Fresnel on and Ray trace on\n }\n else if (value === \"6\") {\n //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on\n }\n else if (value === \"7\") {\n //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on\n }\n else if (value === \"8\") {\n //Reflection on and Ray trace off\n }\n else if (value === \"9\") {\n //Transparency: Glass on, Reflection: Ray trace off\n }\n else if (value === \"10\") {\n //Casts shadows onto invisible surfaces\n }\n }\n else {\n // console.log(\"Unhandled expression at line : \" + i +'\\n' + \"with value : \" + line);\n }\n }\n //At the end of the file, add the last material\n if (material) {\n this.materials.push(material);\n }\n };\n /**\n * Gets the texture for the material.\n *\n * If the material is imported from input file,\n * We sanitize the url to ensure it takes the textre from aside the material.\n *\n * @param rootUrl The root url to load from\n * @param value The value stored in the mtl\n * @return The Texture\n */\n MTLFileLoader._getTexture = function (rootUrl, value, scene) {\n if (!value) {\n return null;\n }\n var url = rootUrl;\n // Load from input file.\n if (rootUrl === \"file:\") {\n var lastDelimiter = value.lastIndexOf(\"\\\\\");\n if (lastDelimiter === -1) {\n lastDelimiter = value.lastIndexOf(\"/\");\n }\n if (lastDelimiter > -1) {\n url += value.substr(lastDelimiter + 1);\n }\n else {\n url += value;\n }\n }\n // Not from input file.\n else {\n url += value;\n }\n return new BABYLON.Texture(url, scene);\n };\n return MTLFileLoader;\n }());\n BABYLON.MTLFileLoader = MTLFileLoader;\n var OBJFileLoader = /** @class */ (function () {\n function OBJFileLoader() {\n this.name = \"obj\";\n this.extensions = \".obj\";\n this.obj = /^o/;\n this.group = /^g/;\n this.mtllib = /^mtllib /;\n this.usemtl = /^usemtl /;\n this.smooth = /^s /;\n this.vertexPattern = /v( +[\\d|\\.|\\+|\\-|e|E]+)( +[\\d|\\.|\\+|\\-|e|E]+)( +[\\d|\\.|\\+|\\-|e|E]+)/;\n // vn float float float\n this.normalPattern = /vn( +[\\d|\\.|\\+|\\-|e|E]+)( +[\\d|\\.|\\+|\\-|e|E]+)( +[\\d|\\.|\\+|\\-|e|E]+)/;\n // vt float float\n this.uvPattern = /vt( +[\\d|\\.|\\+|\\-|e|E]+)( +[\\d|\\.|\\+|\\-|e|E]+)/;\n // f vertex vertex vertex ...\n this.facePattern1 = /f\\s+(([\\d]{1,}[\\s]?){3,})+/;\n // f vertex/uvs vertex/uvs vertex/uvs ...\n this.facePattern2 = /f\\s+((([\\d]{1,}\\/[\\d]{1,}[\\s]?){3,})+)/;\n // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...\n this.facePattern3 = /f\\s+((([\\d]{1,}\\/[\\d]{1,}\\/[\\d]{1,}[\\s]?){3,})+)/;\n // f vertex//normal vertex//normal vertex//normal ...\n this.facePattern4 = /f\\s+((([\\d]{1,}\\/\\/[\\d]{1,}[\\s]?){3,})+)/;\n // f -vertex/-uvs/-normal -vertex/-uvs/-normal -vertex/-uvs/-normal ...\n this.facePattern5 = /f\\s+(((-[\\d]{1,}\\/-[\\d]{1,}\\/-[\\d]{1,}[\\s]?){3,})+)/;\n }\n /**\n * Calls synchronously the MTL file attached to this obj.\n * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.\n * Without this function materials are not displayed in the first frame (but displayed after).\n * In consequence it is impossible to get material information in your HTML file\n *\n * @param url The URL of the MTL file\n * @param rootUrl\n * @param onSuccess Callback function to be called when the MTL file is loaded\n * @private\n */\n OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {\n //The complete path to the mtl file\n var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;\n // Loads through the babylon tools to allow fileInput search.\n BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn(\"Error - Unable to load \" + pathOfFile); });\n };\n OBJFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {\n //get the meshes from OBJ file\n return this._parseSolid(meshesNames, scene, data, rootUrl).then(function (meshes) {\n return {\n meshes: meshes,\n particleSystems: [],\n skeletons: [],\n animationGroups: []\n };\n });\n };\n OBJFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {\n //Get the 3D model\n return this.importMeshAsync(null, scene, data, rootUrl, onProgress).then(function () {\n // return void\n });\n };\n OBJFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {\n return this.importMeshAsync(null, scene, data, rootUrl).then(function (result) {\n var container = new BABYLON.AssetContainer(scene);\n result.meshes.forEach(function (mesh) { return container.meshes.push(mesh); });\n container.removeAllFromScene();\n return container;\n });\n };\n /**\n * Read the OBJ file and create an Array of meshes.\n * Each mesh contains all information given by the OBJ and the MTL file.\n * i.e. vertices positions and indices, optional normals values, optional UV values, optional material\n *\n * @param meshesNames\n * @param scene BABYLON.Scene The scene where are displayed the data\n * @param data String The content of the obj file\n * @param rootUrl String The path to the folder\n * @returns Array\n * @private\n */\n OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {\n var _this = this;\n var positions = []; //values for the positions of vertices\n var normals = []; //Values for the normals\n var uvs = []; //Values for the textures\n var meshesFromObj = []; //[mesh] Contains all the obj meshes\n var handledMesh; //The current mesh of meshes array\n var indicesForBabylon = []; //The list of indices for VertexData\n var wrappedPositionForBabylon = []; //The list of position in vectors\n var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices\n var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices\n var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]\n var curPositionInIndices = 0;\n var hasMeshes = false; //Meshes are defined in the file\n var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]\n var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]\n var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]\n var triangles = []; //Indices from new triangles coming from polygons\n var materialNameFromObj = \"\"; //The name of the current material\n var fileToLoad = \"\"; //The name of the mtlFile to load\n var materialsFromMTLFile = new MTLFileLoader();\n var objMeshName = \"\"; //The name of the current obj mesh\n var increment = 1; //Id for meshes created by the multimaterial\n var isFirstMaterial = true;\n /**\n * Search for obj in the given array.\n * This function is called to check if a couple of data already exists in an array.\n *\n * If found, returns the index of the founded tuple index. Returns -1 if not found\n * @param arr Array<{ normals: Array, idx: Array }>\n * @param obj Array\n * @returns {boolean}\n */\n var isInArray = function (arr, obj) {\n if (!arr[obj[0]])\n arr[obj[0]] = { normals: [], idx: [] };\n var idx = arr[obj[0]].normals.indexOf(obj[1]);\n return idx === -1 ? -1 : arr[obj[0]].idx[idx];\n };\n var isInArrayUV = function (arr, obj) {\n if (!arr[obj[0]])\n arr[obj[0]] = { normals: [], idx: [], uv: [] };\n var idx = arr[obj[0]].normals.indexOf(obj[1]);\n if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {\n return arr[obj[0]].idx[idx];\n }\n return -1;\n };\n /**\n * This function set the data for each triangle.\n * Data are position, normals and uvs\n * If a tuple of (position, normal) is not set, add the data into the corresponding array\n * If the tuple already exist, add only their indice\n *\n * @param indicePositionFromObj Integer The index in positions array\n * @param indiceUvsFromObj Integer The index in uvs array\n * @param indiceNormalFromObj Integer The index in normals array\n * @param positionVectorFromOBJ Vector3 The value of position at index objIndice\n * @param textureVectorFromOBJ Vector3 The value of uvs\n * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale\n */\n var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {\n //Check if this tuple already exists in the list of tuples\n var _index;\n if (OBJFileLoader.OPTIMIZE_WITH_UV) {\n _index = isInArrayUV(tuplePosNorm, [\n indicePositionFromObj,\n indiceNormalFromObj,\n indiceUvsFromObj\n ]);\n }\n else {\n _index = isInArray(tuplePosNorm, [\n indicePositionFromObj,\n indiceNormalFromObj\n ]);\n }\n //If it not exists\n if (_index == -1) {\n //Add an new indice.\n //The array of indices is only an array with his length equal to the number of triangles - 1.\n //We add vertices data in this order\n indicesForBabylon.push(wrappedPositionForBabylon.length);\n //Push the position of vertice for Babylon\n //Each element is a BABYLON.Vector3(x,y,z)\n wrappedPositionForBabylon.push(positionVectorFromOBJ);\n //Push the uvs for Babylon\n //Each element is a BABYLON.Vector3(u,v)\n wrappedUvsForBabylon.push(textureVectorFromOBJ);\n //Push the normals for Babylon\n //Each element is a BABYLON.Vector3(x,y,z)\n wrappedNormalsForBabylon.push(normalsVectorFromOBJ);\n //Add the tuple in the comparison list\n tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);\n tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);\n if (OBJFileLoader.OPTIMIZE_WITH_UV)\n tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);\n }\n else {\n //The tuple already exists\n //Add the index of the already existing tuple\n //At this index we can get the value of position, normal and uvs of vertex\n indicesForBabylon.push(_index);\n }\n };\n /**\n * Transform BABYLON.Vector() object onto 3 digits in an array\n */\n var unwrapData = function () {\n //Every array has the same length\n for (var l = 0; l < wrappedPositionForBabylon.length; l++) {\n //Push the x, y, z values of each element in the unwrapped array\n unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);\n unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);\n unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON\n }\n // Reset arrays for the next new meshes\n wrappedPositionForBabylon = [];\n wrappedNormalsForBabylon = [];\n wrappedUvsForBabylon = [];\n tuplePosNorm = [];\n curPositionInIndices = 0;\n };\n /**\n * Create triangles from polygons by recursion\n * The best to understand how it works is to draw it in the same time you get the recursion.\n * It is important to notice that a triangle is a polygon\n * We get 5 patterns of face defined in OBJ File :\n * facePattern1 = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"]\n * facePattern2 = [\"1/1\",\"2/2\",\"3/3\",\"4/4\",\"5/5\",\"6/6\"]\n * facePattern3 = [\"1/1/1\",\"2/2/2\",\"3/3/3\",\"4/4/4\",\"5/5/5\",\"6/6/6\"]\n * facePattern4 = [\"1//1\",\"2//2\",\"3//3\",\"4//4\",\"5//5\",\"6//6\"]\n * facePattern5 = [\"-1/-1/-1\",\"-2/-2/-2\",\"-3/-3/-3\",\"-4/-4/-4\",\"-5/-5/-5\",\"-6/-6/-6\"]\n * Each pattern is divided by the same method\n * @param face Array[String] The indices of elements\n * @param v Integer The variable to increment\n */\n var getTriangles = function (face, v) {\n //Work for each element of the array\n if (v + 1 < face.length) {\n //Add on the triangle variable the indexes to obtain triangles\n triangles.push(face[0], face[v], face[v + 1]);\n //Incrementation for recursion\n v += 1;\n //Recursion\n getTriangles(face, v);\n }\n //Result obtained after 2 iterations:\n //Pattern1 => triangle = [\"1\",\"2\",\"3\",\"1\",\"3\",\"4\"];\n //Pattern2 => triangle = [\"1/1\",\"2/2\",\"3/3\",\"1/1\",\"3/3\",\"4/4\"];\n //Pattern3 => triangle = [\"1/1/1\",\"2/2/2\",\"3/3/3\",\"1/1/1\",\"3/3/3\",\"4/4/4\"];\n //Pattern4 => triangle = [\"1//1\",\"2//2\",\"3//3\",\"1//1\",\"3//3\",\"4//4\"];\n //Pattern5 => triangle = [\"-1/-1/-1\",\"-2/-2/-2\",\"-3/-3/-3\",\"-1/-1/-1\",\"-3/-3/-3\",\"-4/-4/-4\"];\n };\n /**\n * Create triangles and push the data for each polygon for the pattern 1\n * In this pattern we get vertice positions\n * @param face\n * @param v\n */\n var setDataForCurrentFaceWithPattern1 = function (face, v) {\n //Get the indices of triangles for each polygon\n getTriangles(face, v);\n //For each element in the triangles array.\n //This var could contains 1 to an infinity of triangles\n for (var k = 0; k < triangles.length; k++) {\n // Set position indice\n var indicePositionFromObj = parseInt(triangles[k]) - 1;\n setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined\n positions[indicePositionFromObj], //Get the vectors data\n BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors\n );\n }\n //Reset variable for the next line\n triangles = [];\n };\n /**\n * Create triangles and push the data for each polygon for the pattern 2\n * In this pattern we get vertice positions and uvsu\n * @param face\n * @param v\n */\n var setDataForCurrentFaceWithPattern2 = function (face, v) {\n //Get the indices of triangles for each polygon\n getTriangles(face, v);\n for (var k = 0; k < triangles.length; k++) {\n //triangle[k] = \"1/1\"\n //Split the data for getting position and uv\n var point = triangles[k].split(\"/\"); // [\"1\", \"1\"]\n //Set position indice\n var indicePositionFromObj = parseInt(point[0]) - 1;\n //Set uv indice\n var indiceUvsFromObj = parseInt(point[1]) - 1;\n setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals\n positions[indicePositionFromObj], //Get the values for each element\n uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals\n );\n }\n //Reset variable for the next line\n triangles = [];\n };\n /**\n * Create triangles and push the data for each polygon for the pattern 3\n * In this pattern we get vertice positions, uvs and normals\n * @param face\n * @param v\n */\n var setDataForCurrentFaceWithPattern3 = function (face, v) {\n //Get the indices of triangles for each polygon\n getTriangles(face, v);\n for (var k = 0; k < triangles.length; k++) {\n //triangle[k] = \"1/1/1\"\n //Split the data for getting position, uv, and normals\n var point = triangles[k].split(\"/\"); // [\"1\", \"1\", \"1\"]\n // Set position indice\n var indicePositionFromObj = parseInt(point[0]) - 1;\n // Set uv indice\n var indiceUvsFromObj = parseInt(point[1]) - 1;\n // Set normal indice\n var indiceNormalFromObj = parseInt(point[2]) - 1;\n setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component\n );\n }\n //Reset variable for the next line\n triangles = [];\n };\n /**\n * Create triangles and push the data for each polygon for the pattern 4\n * In this pattern we get vertice positions and normals\n * @param face\n * @param v\n */\n var setDataForCurrentFaceWithPattern4 = function (face, v) {\n getTriangles(face, v);\n for (var k = 0; k < triangles.length; k++) {\n //triangle[k] = \"1//1\"\n //Split the data for getting position and normals\n var point = triangles[k].split(\"//\"); // [\"1\", \"1\"]\n // We check indices, and normals\n var indicePositionFromObj = parseInt(point[0]) - 1;\n var indiceNormalFromObj = parseInt(point[1]) - 1;\n setData(indicePositionFromObj, 1, //Default value for uv\n indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data\n BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);\n }\n //Reset variable for the next line\n triangles = [];\n };\n /**\n * Create triangles and push the data for each polygon for the pattern 3\n * In this pattern we get vertice positions, uvs and normals\n * @param face\n * @param v\n */\n var setDataForCurrentFaceWithPattern5 = function (face, v) {\n //Get the indices of triangles for each polygon\n getTriangles(face, v);\n for (var k = 0; k < triangles.length; k++) {\n //triangle[k] = \"-1/-1/-1\"\n //Split the data for getting position, uv, and normals\n var point = triangles[k].split(\"/\"); // [\"-1\", \"-1\", \"-1\"]\n // Set position indice\n var indicePositionFromObj = positions.length + parseInt(point[0]);\n // Set uv indice\n var indiceUvsFromObj = uvs.length + parseInt(point[1]);\n // Set normal indice\n var indiceNormalFromObj = normals.length + parseInt(point[2]);\n setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component\n );\n }\n //Reset variable for the next line\n triangles = [];\n };\n var addPreviousObjMesh = function () {\n //Check if it is not the first mesh. Otherwise we don't have data.\n if (meshesFromObj.length > 0) {\n //Get the previous mesh for applying the data about the faces\n //=> in obj file, faces definition append after the name of the mesh\n handledMesh = meshesFromObj[meshesFromObj.length - 1];\n //Set the data into Array for the mesh\n unwrapData();\n // Reverse tab. Otherwise face are displayed in the wrong sens\n indicesForBabylon.reverse();\n //Set the information for the mesh\n //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited\n handledMesh.indices = indicesForBabylon.slice();\n handledMesh.positions = unwrappedPositionsForBabylon.slice();\n handledMesh.normals = unwrappedNormalsForBabylon.slice();\n handledMesh.uvs = unwrappedUVForBabylon.slice();\n //Reset the array for the next mesh\n indicesForBabylon = [];\n unwrappedPositionsForBabylon = [];\n unwrappedNormalsForBabylon = [];\n unwrappedUVForBabylon = [];\n }\n };\n //Main function\n //Split the file into lines\n var lines = data.split('\\n');\n //Look at each line\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i].trim();\n var result;\n //Comment or newLine\n if (line.length === 0 || line.charAt(0) === '#') {\n continue;\n //Get information about one position possible for the vertices\n }\n else if ((result = this.vertexPattern.exec(line)) !== null) {\n //Create a Vector3 with the position x, y, z\n //Value of result:\n // [\"v 1.0 2.0 3.0\", \"1.0\", \"2.0\", \"3.0\"]\n //Add the Vector in the list of positions\n positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));\n }\n else if ((result = this.normalPattern.exec(line)) !== null) {\n //Create a Vector3 with the normals x, y, z\n //Value of result\n // [\"vn 1.0 2.0 3.0\", \"1.0\", \"2.0\", \"3.0\"]\n //Add the Vector in the list of normals\n normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));\n }\n else if ((result = this.uvPattern.exec(line)) !== null) {\n //Create a Vector2 with the normals u, v\n //Value of result\n // [\"vt 0.1 0.2 0.3\", \"0.1\", \"0.2\"]\n //Add the Vector in the list of uvs\n uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));\n //Identify patterns of faces\n //Face could be defined in different type of pattern\n }\n else if ((result = this.facePattern3.exec(line)) !== null) {\n //Value of result:\n //[\"f 1/1/1 2/2/2 3/3/3\", \"1/1/1 2/2/2 3/3/3\"...]\n //Set the data for this face\n setDataForCurrentFaceWithPattern3(result[1].trim().split(\" \"), // [\"1/1/1\", \"2/2/2\", \"3/3/3\"]\n 1);\n }\n else if ((result = this.facePattern4.exec(line)) !== null) {\n //Value of result:\n //[\"f 1//1 2//2 3//3\", \"1//1 2//2 3//3\"...]\n //Set the data for this face\n setDataForCurrentFaceWithPattern4(result[1].trim().split(\" \"), // [\"1//1\", \"2//2\", \"3//3\"]\n 1);\n }\n else if ((result = this.facePattern5.exec(line)) !== null) {\n //Value of result:\n //[\"f -1/-1/-1 -2/-2/-2 -3/-3/-3\", \"-1/-1/-1 -2/-2/-2 -3/-3/-3\"...]\n //Set the data for this face\n setDataForCurrentFaceWithPattern5(result[1].trim().split(\" \"), // [\"-1/-1/-1\", \"-2/-2/-2\", \"-3/-3/-3\"]\n 1);\n }\n else if ((result = this.facePattern2.exec(line)) !== null) {\n //Value of result:\n //[\"f 1/1 2/2 3/3\", \"1/1 2/2 3/3\"...]\n //Set the data for this face\n setDataForCurrentFaceWithPattern2(result[1].trim().split(\" \"), // [\"1/1\", \"2/2\", \"3/3\"]\n 1);\n }\n else if ((result = this.facePattern1.exec(line)) !== null) {\n //Value of result\n //[\"f 1 2 3\", \"1 2 3\"...]\n //Set the data for this face\n setDataForCurrentFaceWithPattern1(result[1].trim().split(\" \"), // [\"1\", \"2\", \"3\"]\n 1);\n //Define a mesh or an object\n //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh\n }\n else if (this.group.test(line) || this.obj.test(line)) {\n //Create a new mesh corresponding to the name of the group.\n //Definition of the mesh\n var objMesh = \n //Set the name of the current obj mesh\n {\n name: line.substring(2).trim(),\n indices: undefined,\n positions: undefined,\n normals: undefined,\n uvs: undefined,\n materialName: \"\"\n };\n addPreviousObjMesh();\n //Push the last mesh created with only the name\n meshesFromObj.push(objMesh);\n //Set this variable to indicate that now meshesFromObj has objects defined inside\n hasMeshes = true;\n isFirstMaterial = true;\n increment = 1;\n //Keyword for applying a material\n }\n else if (this.usemtl.test(line)) {\n //Get the name of the material\n materialNameFromObj = line.substring(7).trim();\n //If this new material is in the same mesh\n if (!isFirstMaterial) {\n //Set the data for the previous mesh\n addPreviousObjMesh();\n //Create a new mesh\n var objMesh = \n //Set the name of the current obj mesh\n {\n name: objMeshName + \"_mm\" + increment.toString(),\n indices: undefined,\n positions: undefined,\n normals: undefined,\n uvs: undefined,\n materialName: materialNameFromObj\n };\n increment++;\n //If meshes are already defined\n meshesFromObj.push(objMesh);\n }\n //Set the material name if the previous line define a mesh\n if (hasMeshes && isFirstMaterial) {\n //Set the material name to the previous mesh (1 material per mesh)\n meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;\n isFirstMaterial = false;\n }\n //Keyword for loading the mtl file\n }\n else if (this.mtllib.test(line)) {\n //Get the name of mtl file\n fileToLoad = line.substring(7).trim();\n //Apply smoothing\n }\n else if (this.smooth.test(line)) {\n // smooth shading => apply smoothing\n //Toda y I don't know it work with babylon and with obj.\n //With the obj file an integer is set\n }\n else {\n //If there is another possibility\n console.log(\"Unhandled expression at line : \" + line);\n }\n }\n //At the end of the file, add the last mesh into the meshesFromObj array\n if (hasMeshes) {\n //Set the data for the last mesh\n handledMesh = meshesFromObj[meshesFromObj.length - 1];\n //Reverse indices for displaying faces in the good sens\n indicesForBabylon.reverse();\n //Get the good array\n unwrapData();\n //Set array\n handledMesh.indices = indicesForBabylon;\n handledMesh.positions = unwrappedPositionsForBabylon;\n handledMesh.normals = unwrappedNormalsForBabylon;\n handledMesh.uvs = unwrappedUVForBabylon;\n }\n //If any o or g keyword found, create a mesj with a random id\n if (!hasMeshes) {\n // reverse tab of indices\n indicesForBabylon.reverse();\n //Get positions normals uvs\n unwrapData();\n //Set data for one mesh\n meshesFromObj.push({\n name: BABYLON.Geometry.RandomId(),\n indices: indicesForBabylon,\n positions: unwrappedPositionsForBabylon,\n normals: unwrappedNormalsForBabylon,\n uvs: unwrappedUVForBabylon,\n materialName: materialNameFromObj\n });\n }\n //Create a BABYLON.Mesh list\n var babylonMeshesArray = []; //The mesh for babylon\n var materialToUse = new Array();\n //Set data for each mesh\n for (var j = 0; j < meshesFromObj.length; j++) {\n //check meshesNames (stlFileLoader)\n if (meshesNames && meshesFromObj[j].name) {\n if (meshesNames instanceof Array) {\n if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {\n continue;\n }\n }\n else {\n if (meshesFromObj[j].name !== meshesNames) {\n continue;\n }\n }\n }\n //Get the current mesh\n //Set the data with VertexBuffer for each mesh\n handledMesh = meshesFromObj[j];\n //Create a BABYLON.Mesh with the name of the obj mesh\n var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);\n //Push the name of the material to an array\n //This is indispensable for the importMesh function\n materialToUse.push(meshesFromObj[j].materialName);\n var vertexData = new BABYLON.VertexData(); //The container for the values\n //Set the data for the babylonMesh\n vertexData.positions = handledMesh.positions;\n vertexData.normals = handledMesh.normals;\n vertexData.uvs = handledMesh.uvs;\n vertexData.indices = handledMesh.indices;\n //Set the data from the VertexBuffer to the current BABYLON.Mesh\n vertexData.applyToMesh(babylonMesh);\n if (OBJFileLoader.INVERT_Y) {\n babylonMesh.scaling.y *= -1;\n }\n //Push the mesh into an array\n babylonMeshesArray.push(babylonMesh);\n }\n var mtlPromises = [];\n //load the materials\n //Check if we have a file to load\n if (fileToLoad !== \"\") {\n //Load the file synchronously\n mtlPromises.push(new Promise(function (resolve, reject) {\n _this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {\n try {\n //Create materials thanks MTLLoader function\n materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);\n //Look at each material loaded in the mtl file\n for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {\n //Three variables to get all meshes with the same material\n var startIndex = 0;\n var _indices = [];\n var _index;\n //The material from MTL file is used in the meshes loaded\n //Push the indice in an array\n //Check if the material is not used for another mesh\n while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {\n _indices.push(_index);\n startIndex = _index + 1;\n }\n //If the material is not used dispose it\n if (_index == -1 && _indices.length == 0) {\n //If the material is not needed, remove it\n materialsFromMTLFile.materials[n].dispose();\n }\n else {\n for (var o = 0; o < _indices.length; o++) {\n //Apply the material to the BABYLON.Mesh for each mesh with the material\n babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];\n }\n }\n }\n resolve();\n }\n catch (e) {\n reject(e);\n }\n });\n }));\n }\n //Return an array with all BABYLON.Mesh\n return Promise.all(mtlPromises).then(function () {\n return babylonMeshesArray;\n });\n };\n OBJFileLoader.OPTIMIZE_WITH_UV = false;\n OBJFileLoader.INVERT_Y = false;\n return OBJFileLoader;\n }());\n BABYLON.OBJFileLoader = OBJFileLoader;\n if (BABYLON.SceneLoader) {\n //Add this loader into the register plugin\n BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());\n }\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.objFileLoader.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Mode that determines the coordinate system to use.\n */\n var GLTFLoaderCoordinateSystemMode;\n (function (GLTFLoaderCoordinateSystemMode) {\n /**\n * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.\n */\n GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode[\"AUTO\"] = 0] = \"AUTO\";\n /**\n * Sets the useRightHandedSystem flag on the scene.\n */\n GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode[\"FORCE_RIGHT_HANDED\"] = 1] = \"FORCE_RIGHT_HANDED\";\n })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));\n /**\n * Mode that determines what animations will start.\n */\n var GLTFLoaderAnimationStartMode;\n (function (GLTFLoaderAnimationStartMode) {\n /**\n * No animation will start.\n */\n GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode[\"NONE\"] = 0] = \"NONE\";\n /**\n * The first animation will start.\n */\n GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode[\"FIRST\"] = 1] = \"FIRST\";\n /**\n * All animations will start.\n */\n GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode[\"ALL\"] = 2] = \"ALL\";\n })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));\n /**\n * Loader state.\n */\n var GLTFLoaderState;\n (function (GLTFLoaderState) {\n /**\n * The asset is loading.\n */\n GLTFLoaderState[GLTFLoaderState[\"LOADING\"] = 0] = \"LOADING\";\n /**\n * The asset is ready for rendering.\n */\n GLTFLoaderState[GLTFLoaderState[\"READY\"] = 1] = \"READY\";\n /**\n * The asset is completely loaded.\n */\n GLTFLoaderState[GLTFLoaderState[\"COMPLETE\"] = 2] = \"COMPLETE\";\n })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));\n /**\n * File loader for loading glTF files into a scene.\n */\n var GLTFFileLoader = /** @class */ (function () {\n function GLTFFileLoader() {\n // #region Common options\n /**\n * Raised when the asset has been parsed\n */\n this.onParsedObservable = new BABYLON.Observable();\n // #endregion\n // #region V2 options\n /**\n * The coordinate system mode. Defaults to AUTO.\n */\n this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;\n /**\n * The animation start mode. Defaults to FIRST.\n */\n this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;\n /**\n * Defines if the loader should compile materials before raising the success callback. Defaults to false.\n */\n this.compileMaterials = false;\n /**\n * Defines if the loader should also compile materials with clip planes. Defaults to false.\n */\n this.useClipPlane = false;\n /**\n * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.\n */\n this.compileShadowGenerators = false;\n /**\n * Defines if the Alpha blended materials are only applied as coverage.\n * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.\n * If true, no extra effects are applied to transparent pixels.\n */\n this.transparencyAsCoverage = false;\n /** @hidden */\n this._normalizeAnimationGroupsToBeginAtZero = true;\n /**\n * Function called before loading a url referenced by the asset.\n */\n this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };\n /**\n * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.\n */\n this.onMeshLoadedObservable = new BABYLON.Observable();\n /**\n * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.\n */\n this.onTextureLoadedObservable = new BABYLON.Observable();\n /**\n * Observable raised when the loader creates a material after parsing the glTF properties of the material.\n */\n this.onMaterialLoadedObservable = new BABYLON.Observable();\n /**\n * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.\n */\n this.onCameraLoadedObservable = new BABYLON.Observable();\n /**\n * Observable raised when the asset is completely loaded, immediately before the loader is disposed.\n * For assets with LODs, raised when all of the LODs are complete.\n * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.\n */\n this.onCompleteObservable = new BABYLON.Observable();\n /**\n * Observable raised after the loader is disposed.\n */\n this.onDisposeObservable = new BABYLON.Observable();\n /**\n * Observable raised after a loader extension is created.\n * Set additional options for a loader extension in this event.\n */\n this.onExtensionLoadedObservable = new BABYLON.Observable();\n // #endregion\n this._loader = null;\n /**\n * Name of the loader (\"gltf\")\n */\n this.name = \"gltf\";\n /**\n * Supported file extensions of the loader (.gltf, .glb)\n */\n this.extensions = {\n \".gltf\": { isBinary: false },\n \".glb\": { isBinary: true }\n };\n this._logIndentLevel = 0;\n this._loggingEnabled = false;\n /** @hidden */\n this._log = this._logDisabled;\n this._capturePerformanceCounters = false;\n /** @hidden */\n this._startPerformanceCounter = this._startPerformanceCounterDisabled;\n /** @hidden */\n this._endPerformanceCounter = this._endPerformanceCounterDisabled;\n }\n Object.defineProperty(GLTFFileLoader.prototype, \"onParsed\", {\n /**\n * Raised when the asset has been parsed\n */\n set: function (callback) {\n if (this._onParsedObserver) {\n this.onParsedObservable.remove(this._onParsedObserver);\n }\n this._onParsedObserver = this.onParsedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onMeshLoaded\", {\n /**\n * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.\n */\n set: function (callback) {\n if (this._onMeshLoadedObserver) {\n this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);\n }\n this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onTextureLoaded\", {\n /**\n * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.\n */\n set: function (callback) {\n if (this._onTextureLoadedObserver) {\n this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);\n }\n this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onMaterialLoaded\", {\n /**\n * Callback raised when the loader creates a material after parsing the glTF properties of the material.\n */\n set: function (callback) {\n if (this._onMaterialLoadedObserver) {\n this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);\n }\n this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onCameraLoaded\", {\n /**\n * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.\n */\n set: function (callback) {\n if (this._onCameraLoadedObserver) {\n this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);\n }\n this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onComplete\", {\n /**\n * Callback raised when the asset is completely loaded, immediately before the loader is disposed.\n */\n set: function (callback) {\n if (this._onCompleteObserver) {\n this.onCompleteObservable.remove(this._onCompleteObserver);\n }\n this._onCompleteObserver = this.onCompleteObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onDispose\", {\n /**\n * Callback raised after the loader is disposed.\n */\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onExtensionLoaded\", {\n /**\n * Callback raised after a loader extension is created.\n */\n set: function (callback) {\n if (this._onExtensionLoadedObserver) {\n this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);\n }\n this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a promise that resolves when the asset is completely loaded.\n * @returns a promise that resolves when the asset is completely loaded.\n */\n GLTFFileLoader.prototype.whenCompleteAsync = function () {\n var _this = this;\n return new Promise(function (resolve) {\n _this.onCompleteObservable.addOnce(function () {\n resolve();\n });\n });\n };\n Object.defineProperty(GLTFFileLoader.prototype, \"loaderState\", {\n /**\n * The loader state or null if the loader is not active.\n */\n get: function () {\n return this._loader ? this._loader.state : null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"loggingEnabled\", {\n /**\n * Defines if the loader logging is enabled.\n */\n get: function () {\n return this._loggingEnabled;\n },\n set: function (value) {\n if (this._loggingEnabled === value) {\n return;\n }\n this._loggingEnabled = value;\n if (this._loggingEnabled) {\n this._log = this._logEnabled;\n }\n else {\n this._log = this._logDisabled;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"capturePerformanceCounters\", {\n /**\n * Defines if the loader should capture performance counters.\n */\n get: function () {\n return this._capturePerformanceCounters;\n },\n set: function (value) {\n if (this._capturePerformanceCounters === value) {\n return;\n }\n this._capturePerformanceCounters = value;\n if (this._capturePerformanceCounters) {\n this._startPerformanceCounter = this._startPerformanceCounterEnabled;\n this._endPerformanceCounter = this._endPerformanceCounterEnabled;\n }\n else {\n this._startPerformanceCounter = this._startPerformanceCounterDisabled;\n this._endPerformanceCounter = this._endPerformanceCounterDisabled;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes the loader, releases resources during load, and cancels any outstanding requests.\n */\n GLTFFileLoader.prototype.dispose = function () {\n if (this._loader) {\n this._loader.dispose();\n this._loader = null;\n }\n this._clear();\n this.onDisposeObservable.notifyObservers(undefined);\n this.onDisposeObservable.clear();\n };\n /** @hidden */\n GLTFFileLoader.prototype._clear = function () {\n this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };\n this.onMeshLoadedObservable.clear();\n this.onTextureLoadedObservable.clear();\n this.onMaterialLoadedObservable.clear();\n this.onCameraLoadedObservable.clear();\n this.onCompleteObservable.clear();\n this.onExtensionLoadedObservable.clear();\n };\n /**\n * Imports one or more meshes from the loaded glTF data and adds them to the scene\n * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file\n * @param scene the scene the meshes should be added to\n * @param data the glTF data to load\n * @param rootUrl root url to load from\n * @param onProgress event that fires when loading progress has occured\n * @returns a promise containg the loaded meshes, particles, skeletons and animations\n */\n GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {\n var _this = this;\n return Promise.resolve().then(function () {\n var loaderData = _this._parse(data);\n _this._loader = _this._getLoader(loaderData);\n return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);\n });\n };\n /**\n * Imports all objects from the loaded glTF data and adds them to the scene\n * @param scene the scene the objects should be added to\n * @param data the glTF data to load\n * @param rootUrl root url to load from\n * @param onProgress event that fires when loading progress has occured\n * @returns a promise which completes when objects have been loaded to the scene\n */\n GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {\n var _this = this;\n return Promise.resolve().then(function () {\n var loaderData = _this._parse(data);\n _this._loader = _this._getLoader(loaderData);\n return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);\n });\n };\n /**\n * Load into an asset container.\n * @param scene The scene to load into\n * @param data The data to import\n * @param rootUrl The root url for scene and resources\n * @param onProgress The callback when the load progresses\n * @returns The loaded asset container\n */\n GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {\n var _this = this;\n return Promise.resolve().then(function () {\n var loaderData = _this._parse(data);\n _this._loader = _this._getLoader(loaderData);\n return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {\n var container = new BABYLON.AssetContainer(scene);\n Array.prototype.push.apply(container.meshes, result.meshes);\n Array.prototype.push.apply(container.particleSystems, result.particleSystems);\n Array.prototype.push.apply(container.skeletons, result.skeletons);\n Array.prototype.push.apply(container.animationGroups, result.animationGroups);\n container.removeAllFromScene();\n return container;\n });\n });\n };\n /**\n * If the data string can be loaded directly.\n * @param data string contianing the file data\n * @returns if the data can be loaded directly\n */\n GLTFFileLoader.prototype.canDirectLoad = function (data) {\n return ((data.indexOf(\"scene\") !== -1) && (data.indexOf(\"node\") !== -1));\n };\n /**\n * Instantiates a glTF file loader plugin.\n * @returns the created plugin\n */\n GLTFFileLoader.prototype.createPlugin = function () {\n return new GLTFFileLoader();\n };\n GLTFFileLoader.prototype._parse = function (data) {\n this._startPerformanceCounter(\"Parse\");\n var parsedData;\n if (data instanceof ArrayBuffer) {\n this._log(\"Parsing binary\");\n parsedData = this._parseBinary(data);\n }\n else {\n this._log(\"Parsing JSON\");\n this._log(\"JSON length: \" + data.length);\n parsedData = {\n json: JSON.parse(data),\n bin: null\n };\n }\n this.onParsedObservable.notifyObservers(parsedData);\n this.onParsedObservable.clear();\n this._endPerformanceCounter(\"Parse\");\n return parsedData;\n };\n GLTFFileLoader.prototype._getLoader = function (loaderData) {\n var asset = loaderData.json.asset || {};\n this._log(\"Asset version: \" + asset.version);\n asset.minVersion && this._log(\"Asset minimum version: \" + asset.minVersion);\n asset.generator && this._log(\"Asset generator: \" + asset.generator);\n var version = GLTFFileLoader._parseVersion(asset.version);\n if (!version) {\n throw new Error(\"Invalid version: \" + asset.version);\n }\n if (asset.minVersion !== undefined) {\n var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);\n if (!minVersion) {\n throw new Error(\"Invalid minimum version: \" + asset.minVersion);\n }\n if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {\n throw new Error(\"Incompatible minimum version: \" + asset.minVersion);\n }\n }\n var createLoaders = {\n 1: GLTFFileLoader._CreateGLTFLoaderV1,\n 2: GLTFFileLoader._CreateGLTFLoaderV2\n };\n var createLoader = createLoaders[version.major];\n if (!createLoader) {\n throw new Error(\"Unsupported version: \" + asset.version);\n }\n return createLoader(this);\n };\n GLTFFileLoader.prototype._parseBinary = function (data) {\n var Binary = {\n Magic: 0x46546C67\n };\n this._log(\"Binary length: \" + data.byteLength);\n var binaryReader = new BinaryReader(data);\n var magic = binaryReader.readUint32();\n if (magic !== Binary.Magic) {\n throw new Error(\"Unexpected magic: \" + magic);\n }\n var version = binaryReader.readUint32();\n if (this.loggingEnabled) {\n this._log(\"Binary version: \" + version);\n }\n switch (version) {\n case 1: return this._parseV1(binaryReader);\n case 2: return this._parseV2(binaryReader);\n }\n throw new Error(\"Unsupported version: \" + version);\n };\n GLTFFileLoader.prototype._parseV1 = function (binaryReader) {\n var ContentFormat = {\n JSON: 0\n };\n var length = binaryReader.readUint32();\n if (length != binaryReader.getLength()) {\n throw new Error(\"Length in header does not match actual data length: \" + length + \" != \" + binaryReader.getLength());\n }\n var contentLength = binaryReader.readUint32();\n var contentFormat = binaryReader.readUint32();\n var content;\n switch (contentFormat) {\n case ContentFormat.JSON: {\n content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));\n break;\n }\n default: {\n throw new Error(\"Unexpected content format: \" + contentFormat);\n }\n }\n var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();\n var body = binaryReader.readUint8Array(bytesRemaining);\n return {\n json: content,\n bin: body\n };\n };\n GLTFFileLoader.prototype._parseV2 = function (binaryReader) {\n var ChunkFormat = {\n JSON: 0x4E4F534A,\n BIN: 0x004E4942\n };\n var length = binaryReader.readUint32();\n if (length !== binaryReader.getLength()) {\n throw new Error(\"Length in header does not match actual data length: \" + length + \" != \" + binaryReader.getLength());\n }\n // JSON chunk\n var chunkLength = binaryReader.readUint32();\n var chunkFormat = binaryReader.readUint32();\n if (chunkFormat !== ChunkFormat.JSON) {\n throw new Error(\"First chunk format is not JSON\");\n }\n var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));\n // Look for BIN chunk\n var bin = null;\n while (binaryReader.getPosition() < binaryReader.getLength()) {\n var chunkLength_1 = binaryReader.readUint32();\n var chunkFormat_1 = binaryReader.readUint32();\n switch (chunkFormat_1) {\n case ChunkFormat.JSON: {\n throw new Error(\"Unexpected JSON chunk\");\n }\n case ChunkFormat.BIN: {\n bin = binaryReader.readUint8Array(chunkLength_1);\n break;\n }\n default: {\n // ignore unrecognized chunkFormat\n binaryReader.skipBytes(chunkLength_1);\n break;\n }\n }\n }\n return {\n json: json,\n bin: bin\n };\n };\n GLTFFileLoader._parseVersion = function (version) {\n if (version === \"1.0\" || version === \"1.0.1\") {\n return {\n major: 1,\n minor: 0\n };\n }\n var match = (version + \"\").match(/^(\\d+)\\.(\\d+)/);\n if (!match) {\n return null;\n }\n return {\n major: parseInt(match[1]),\n minor: parseInt(match[2])\n };\n };\n GLTFFileLoader._compareVersion = function (a, b) {\n if (a.major > b.major)\n return 1;\n if (a.major < b.major)\n return -1;\n if (a.minor > b.minor)\n return 1;\n if (a.minor < b.minor)\n return -1;\n return 0;\n };\n GLTFFileLoader._decodeBufferToText = function (buffer) {\n var result = \"\";\n var length = buffer.byteLength;\n for (var i = 0; i < length; i++) {\n result += String.fromCharCode(buffer[i]);\n }\n return result;\n };\n /** @hidden */\n GLTFFileLoader.prototype._logOpen = function (message) {\n this._log(message);\n this._logIndentLevel++;\n };\n /** @hidden */\n GLTFFileLoader.prototype._logClose = function () {\n --this._logIndentLevel;\n };\n GLTFFileLoader.prototype._logEnabled = function (message) {\n var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);\n BABYLON.Tools.Log(\"\" + spaces + message);\n };\n GLTFFileLoader.prototype._logDisabled = function (message) {\n };\n GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {\n BABYLON.Tools.StartPerformanceCounter(counterName);\n };\n GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {\n };\n GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {\n BABYLON.Tools.EndPerformanceCounter(counterName);\n };\n GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {\n };\n // #endregion\n // #region V1 options\n /**\n * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.\n * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.\n * Defaults to true.\n * @hidden\n */\n GLTFFileLoader.IncrementalLoading = true;\n /**\n * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.\n * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.\n * @hidden\n */\n GLTFFileLoader.HomogeneousCoordinates = false;\n GLTFFileLoader._logSpaces = \" \";\n return GLTFFileLoader;\n }());\n BABYLON.GLTFFileLoader = GLTFFileLoader;\n var BinaryReader = /** @class */ (function () {\n function BinaryReader(arrayBuffer) {\n this._arrayBuffer = arrayBuffer;\n this._dataView = new DataView(arrayBuffer);\n this._byteOffset = 0;\n }\n BinaryReader.prototype.getPosition = function () {\n return this._byteOffset;\n };\n BinaryReader.prototype.getLength = function () {\n return this._arrayBuffer.byteLength;\n };\n BinaryReader.prototype.readUint32 = function () {\n var value = this._dataView.getUint32(this._byteOffset, true);\n this._byteOffset += 4;\n return value;\n };\n BinaryReader.prototype.readUint8Array = function (length) {\n var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);\n this._byteOffset += length;\n return value;\n };\n BinaryReader.prototype.skipBytes = function (length) {\n this._byteOffset += length;\n };\n return BinaryReader;\n }());\n if (BABYLON.SceneLoader) {\n BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());\n }\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFFileLoader.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF1;\n (function (GLTF1) {\n /**\n * Enums\n */\n var EComponentType;\n (function (EComponentType) {\n EComponentType[EComponentType[\"BYTE\"] = 5120] = \"BYTE\";\n EComponentType[EComponentType[\"UNSIGNED_BYTE\"] = 5121] = \"UNSIGNED_BYTE\";\n EComponentType[EComponentType[\"SHORT\"] = 5122] = \"SHORT\";\n EComponentType[EComponentType[\"UNSIGNED_SHORT\"] = 5123] = \"UNSIGNED_SHORT\";\n EComponentType[EComponentType[\"FLOAT\"] = 5126] = \"FLOAT\";\n })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));\n var EShaderType;\n (function (EShaderType) {\n EShaderType[EShaderType[\"FRAGMENT\"] = 35632] = \"FRAGMENT\";\n EShaderType[EShaderType[\"VERTEX\"] = 35633] = \"VERTEX\";\n })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));\n var EParameterType;\n (function (EParameterType) {\n EParameterType[EParameterType[\"BYTE\"] = 5120] = \"BYTE\";\n EParameterType[EParameterType[\"UNSIGNED_BYTE\"] = 5121] = \"UNSIGNED_BYTE\";\n EParameterType[EParameterType[\"SHORT\"] = 5122] = \"SHORT\";\n EParameterType[EParameterType[\"UNSIGNED_SHORT\"] = 5123] = \"UNSIGNED_SHORT\";\n EParameterType[EParameterType[\"INT\"] = 5124] = \"INT\";\n EParameterType[EParameterType[\"UNSIGNED_INT\"] = 5125] = \"UNSIGNED_INT\";\n EParameterType[EParameterType[\"FLOAT\"] = 5126] = \"FLOAT\";\n EParameterType[EParameterType[\"FLOAT_VEC2\"] = 35664] = \"FLOAT_VEC2\";\n EParameterType[EParameterType[\"FLOAT_VEC3\"] = 35665] = \"FLOAT_VEC3\";\n EParameterType[EParameterType[\"FLOAT_VEC4\"] = 35666] = \"FLOAT_VEC4\";\n EParameterType[EParameterType[\"INT_VEC2\"] = 35667] = \"INT_VEC2\";\n EParameterType[EParameterType[\"INT_VEC3\"] = 35668] = \"INT_VEC3\";\n EParameterType[EParameterType[\"INT_VEC4\"] = 35669] = \"INT_VEC4\";\n EParameterType[EParameterType[\"BOOL\"] = 35670] = \"BOOL\";\n EParameterType[EParameterType[\"BOOL_VEC2\"] = 35671] = \"BOOL_VEC2\";\n EParameterType[EParameterType[\"BOOL_VEC3\"] = 35672] = \"BOOL_VEC3\";\n EParameterType[EParameterType[\"BOOL_VEC4\"] = 35673] = \"BOOL_VEC4\";\n EParameterType[EParameterType[\"FLOAT_MAT2\"] = 35674] = \"FLOAT_MAT2\";\n EParameterType[EParameterType[\"FLOAT_MAT3\"] = 35675] = \"FLOAT_MAT3\";\n EParameterType[EParameterType[\"FLOAT_MAT4\"] = 35676] = \"FLOAT_MAT4\";\n EParameterType[EParameterType[\"SAMPLER_2D\"] = 35678] = \"SAMPLER_2D\";\n })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));\n var ETextureWrapMode;\n (function (ETextureWrapMode) {\n ETextureWrapMode[ETextureWrapMode[\"CLAMP_TO_EDGE\"] = 33071] = \"CLAMP_TO_EDGE\";\n ETextureWrapMode[ETextureWrapMode[\"MIRRORED_REPEAT\"] = 33648] = \"MIRRORED_REPEAT\";\n ETextureWrapMode[ETextureWrapMode[\"REPEAT\"] = 10497] = \"REPEAT\";\n })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));\n var ETextureFilterType;\n (function (ETextureFilterType) {\n ETextureFilterType[ETextureFilterType[\"NEAREST\"] = 9728] = \"NEAREST\";\n ETextureFilterType[ETextureFilterType[\"LINEAR\"] = 9728] = \"LINEAR\";\n ETextureFilterType[ETextureFilterType[\"NEAREST_MIPMAP_NEAREST\"] = 9984] = \"NEAREST_MIPMAP_NEAREST\";\n ETextureFilterType[ETextureFilterType[\"LINEAR_MIPMAP_NEAREST\"] = 9985] = \"LINEAR_MIPMAP_NEAREST\";\n ETextureFilterType[ETextureFilterType[\"NEAREST_MIPMAP_LINEAR\"] = 9986] = \"NEAREST_MIPMAP_LINEAR\";\n ETextureFilterType[ETextureFilterType[\"LINEAR_MIPMAP_LINEAR\"] = 9987] = \"LINEAR_MIPMAP_LINEAR\";\n })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));\n var ETextureFormat;\n (function (ETextureFormat) {\n ETextureFormat[ETextureFormat[\"ALPHA\"] = 6406] = \"ALPHA\";\n ETextureFormat[ETextureFormat[\"RGB\"] = 6407] = \"RGB\";\n ETextureFormat[ETextureFormat[\"RGBA\"] = 6408] = \"RGBA\";\n ETextureFormat[ETextureFormat[\"LUMINANCE\"] = 6409] = \"LUMINANCE\";\n ETextureFormat[ETextureFormat[\"LUMINANCE_ALPHA\"] = 6410] = \"LUMINANCE_ALPHA\";\n })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));\n var ECullingType;\n (function (ECullingType) {\n ECullingType[ECullingType[\"FRONT\"] = 1028] = \"FRONT\";\n ECullingType[ECullingType[\"BACK\"] = 1029] = \"BACK\";\n ECullingType[ECullingType[\"FRONT_AND_BACK\"] = 1032] = \"FRONT_AND_BACK\";\n })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));\n var EBlendingFunction;\n (function (EBlendingFunction) {\n EBlendingFunction[EBlendingFunction[\"ZERO\"] = 0] = \"ZERO\";\n EBlendingFunction[EBlendingFunction[\"ONE\"] = 1] = \"ONE\";\n EBlendingFunction[EBlendingFunction[\"SRC_COLOR\"] = 768] = \"SRC_COLOR\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_SRC_COLOR\"] = 769] = \"ONE_MINUS_SRC_COLOR\";\n EBlendingFunction[EBlendingFunction[\"DST_COLOR\"] = 774] = \"DST_COLOR\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_DST_COLOR\"] = 775] = \"ONE_MINUS_DST_COLOR\";\n EBlendingFunction[EBlendingFunction[\"SRC_ALPHA\"] = 770] = \"SRC_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_SRC_ALPHA\"] = 771] = \"ONE_MINUS_SRC_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"DST_ALPHA\"] = 772] = \"DST_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_DST_ALPHA\"] = 773] = \"ONE_MINUS_DST_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"CONSTANT_COLOR\"] = 32769] = \"CONSTANT_COLOR\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_CONSTANT_COLOR\"] = 32770] = \"ONE_MINUS_CONSTANT_COLOR\";\n EBlendingFunction[EBlendingFunction[\"CONSTANT_ALPHA\"] = 32771] = \"CONSTANT_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_CONSTANT_ALPHA\"] = 32772] = \"ONE_MINUS_CONSTANT_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"SRC_ALPHA_SATURATE\"] = 776] = \"SRC_ALPHA_SATURATE\";\n })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));\n })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF1;\n (function (GLTF1) {\n /**\n * Tokenizer. Used for shaders compatibility\n * Automatically map world, view, projection, worldViewProjection, attributes and so on\n */\n var ETokenType;\n (function (ETokenType) {\n ETokenType[ETokenType[\"IDENTIFIER\"] = 1] = \"IDENTIFIER\";\n ETokenType[ETokenType[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\n ETokenType[ETokenType[\"END_OF_INPUT\"] = 3] = \"END_OF_INPUT\";\n })(ETokenType || (ETokenType = {}));\n var Tokenizer = /** @class */ (function () {\n function Tokenizer(toParse) {\n this._pos = 0;\n this.currentToken = ETokenType.UNKNOWN;\n this.currentIdentifier = \"\";\n this.currentString = \"\";\n this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;\n this._toParse = toParse;\n this._maxPos = toParse.length;\n }\n Tokenizer.prototype.getNextToken = function () {\n if (this.isEnd())\n return ETokenType.END_OF_INPUT;\n this.currentString = this.read();\n this.currentToken = ETokenType.UNKNOWN;\n if (this.currentString === \"_\" || this.isLetterOrDigitPattern.test(this.currentString)) {\n this.currentToken = ETokenType.IDENTIFIER;\n this.currentIdentifier = this.currentString;\n while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === \"_\")) {\n this.currentIdentifier += this.currentString;\n this.forward();\n }\n }\n return this.currentToken;\n };\n Tokenizer.prototype.peek = function () {\n return this._toParse[this._pos];\n };\n Tokenizer.prototype.read = function () {\n return this._toParse[this._pos++];\n };\n Tokenizer.prototype.forward = function () {\n this._pos++;\n };\n Tokenizer.prototype.isEnd = function () {\n return this._pos >= this._maxPos;\n };\n return Tokenizer;\n }());\n /**\n * Values\n */\n var glTFTransforms = [\"MODEL\", \"VIEW\", \"PROJECTION\", \"MODELVIEW\", \"MODELVIEWPROJECTION\", \"JOINTMATRIX\"];\n var babylonTransforms = [\"world\", \"view\", \"projection\", \"worldView\", \"worldViewProjection\", \"mBones\"];\n var glTFAnimationPaths = [\"translation\", \"rotation\", \"scale\"];\n var babylonAnimationPaths = [\"position\", \"rotationQuaternion\", \"scaling\"];\n /**\n * Parse\n */\n var parseBuffers = function (parsedBuffers, gltfRuntime) {\n for (var buf in parsedBuffers) {\n var parsedBuffer = parsedBuffers[buf];\n gltfRuntime.buffers[buf] = parsedBuffer;\n gltfRuntime.buffersCount++;\n }\n };\n var parseShaders = function (parsedShaders, gltfRuntime) {\n for (var sha in parsedShaders) {\n var parsedShader = parsedShaders[sha];\n gltfRuntime.shaders[sha] = parsedShader;\n gltfRuntime.shaderscount++;\n }\n };\n var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {\n for (var object in parsedObjects) {\n var parsedObject = parsedObjects[object];\n gltfRuntime[runtimeProperty][object] = parsedObject;\n }\n };\n /**\n * Utils\n */\n var normalizeUVs = function (buffer) {\n if (!buffer) {\n return;\n }\n for (var i = 0; i < buffer.length / 2; i++) {\n buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];\n }\n };\n var getAttribute = function (attributeParameter) {\n if (attributeParameter.semantic === \"NORMAL\") {\n return \"normal\";\n }\n else if (attributeParameter.semantic === \"POSITION\") {\n return \"position\";\n }\n else if (attributeParameter.semantic === \"JOINT\") {\n return \"matricesIndices\";\n }\n else if (attributeParameter.semantic === \"WEIGHT\") {\n return \"matricesWeights\";\n }\n else if (attributeParameter.semantic === \"COLOR\") {\n return \"color\";\n }\n else if (attributeParameter.semantic && attributeParameter.semantic.indexOf(\"TEXCOORD_\") !== -1) {\n var channel = Number(attributeParameter.semantic.split(\"_\")[1]);\n return \"uv\" + (channel === 0 ? \"\" : channel + 1);\n }\n return null;\n };\n /**\n * Loads and creates animations\n */\n var loadAnimations = function (gltfRuntime) {\n for (var anim in gltfRuntime.animations) {\n var animation = gltfRuntime.animations[anim];\n if (!animation.channels || !animation.samplers) {\n continue;\n }\n var lastAnimation = null;\n for (var i = 0; i < animation.channels.length; i++) {\n // Get parameters and load buffers\n var channel = animation.channels[i];\n var sampler = animation.samplers[channel.sampler];\n if (!sampler) {\n continue;\n }\n var inputData = null;\n var outputData = null;\n if (animation.parameters) {\n inputData = animation.parameters[sampler.input];\n outputData = animation.parameters[sampler.output];\n }\n else {\n inputData = sampler.input;\n outputData = sampler.output;\n }\n var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);\n var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);\n var targetID = channel.target.id;\n var targetNode = gltfRuntime.scene.getNodeByID(targetID);\n if (targetNode === null) {\n targetNode = gltfRuntime.scene.getNodeByName(targetID);\n }\n if (targetNode === null) {\n BABYLON.Tools.Warn(\"Creating animation named \" + anim + \". But cannot find node named \" + targetID + \" to attach to\");\n continue;\n }\n var isBone = targetNode instanceof BABYLON.Bone;\n // Get target path (position, rotation or scaling)\n var targetPath = channel.target.path;\n var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);\n if (targetPathIndex !== -1) {\n targetPath = babylonAnimationPaths[targetPathIndex];\n }\n // Determine animation type\n var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;\n if (!isBone) {\n if (targetPath === \"rotationQuaternion\") {\n animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;\n targetNode.rotationQuaternion = new BABYLON.Quaternion();\n }\n else {\n animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;\n }\n }\n // Create animation and key frames\n var babylonAnimation = null;\n var keys = [];\n var arrayOffset = 0;\n var modifyKey = false;\n if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {\n babylonAnimation = lastAnimation;\n modifyKey = true;\n }\n if (!modifyKey) {\n babylonAnimation = new BABYLON.Animation(anim, isBone ? \"_matrix\" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);\n }\n // For each frame\n for (var j = 0; j < bufferInput.length; j++) {\n var value = null;\n if (targetPath === \"rotationQuaternion\") { // VEC4\n value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);\n arrayOffset += 4;\n }\n else { // Position and scaling are VEC3\n value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);\n arrayOffset += 3;\n }\n if (isBone) {\n var bone = targetNode;\n var translation = BABYLON.Vector3.Zero();\n var rotationQuaternion = new BABYLON.Quaternion();\n var scaling = BABYLON.Vector3.Zero();\n // Warning on decompose\n var mat = bone.getBaseMatrix();\n if (modifyKey && lastAnimation) {\n mat = lastAnimation.getKeys()[j].value;\n }\n mat.decompose(scaling, rotationQuaternion, translation);\n if (targetPath === \"position\") {\n translation = value;\n }\n else if (targetPath === \"rotationQuaternion\") {\n rotationQuaternion = value;\n }\n else {\n scaling = value;\n }\n value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);\n }\n if (!modifyKey) {\n keys.push({\n frame: bufferInput[j],\n value: value\n });\n }\n else if (lastAnimation) {\n lastAnimation.getKeys()[j].value = value;\n }\n }\n // Finish\n if (!modifyKey && babylonAnimation) {\n babylonAnimation.setKeys(keys);\n targetNode.animations.push(babylonAnimation);\n }\n lastAnimation = babylonAnimation;\n gltfRuntime.scene.stopAnimation(targetNode);\n gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);\n }\n }\n };\n /**\n * Returns the bones transformation matrix\n */\n var configureBoneTransformation = function (node) {\n var mat = null;\n if (node.translation || node.rotation || node.scale) {\n var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);\n var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);\n var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);\n mat = BABYLON.Matrix.Compose(scale, rotation, position);\n }\n else {\n mat = BABYLON.Matrix.FromArray(node.matrix);\n }\n return mat;\n };\n /**\n * Returns the parent bone\n */\n var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {\n // Try to find\n for (var i = 0; i < newSkeleton.bones.length; i++) {\n if (newSkeleton.bones[i].name === jointName) {\n return newSkeleton.bones[i];\n }\n }\n // Not found, search in gltf nodes\n var nodes = gltfRuntime.nodes;\n for (var nde in nodes) {\n var node = nodes[nde];\n if (!node.jointName) {\n continue;\n }\n var children = node.children;\n for (var i = 0; i < children.length; i++) {\n var child = gltfRuntime.nodes[children[i]];\n if (!child.jointName) {\n continue;\n }\n if (child.jointName === jointName) {\n var mat = configureBoneTransformation(node);\n var bone = new BABYLON.Bone(node.name || \"\", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);\n bone.id = nde;\n return bone;\n }\n }\n }\n return null;\n };\n /**\n * Returns the appropriate root node\n */\n var getNodeToRoot = function (nodesToRoot, id) {\n for (var i = 0; i < nodesToRoot.length; i++) {\n var nodeToRoot = nodesToRoot[i];\n for (var j = 0; j < nodeToRoot.node.children.length; j++) {\n var child = nodeToRoot.node.children[j];\n if (child === id) {\n return nodeToRoot.bone;\n }\n }\n }\n return null;\n };\n /**\n * Returns the node with the joint name\n */\n var getJointNode = function (gltfRuntime, jointName) {\n var nodes = gltfRuntime.nodes;\n var node = nodes[jointName];\n if (node) {\n return {\n node: node,\n id: jointName\n };\n }\n for (var nde in nodes) {\n node = nodes[nde];\n if (node.jointName === jointName) {\n return {\n node: node,\n id: nde\n };\n }\n }\n return null;\n };\n /**\n * Checks if a nodes is in joints\n */\n var nodeIsInJoints = function (skins, id) {\n for (var i = 0; i < skins.jointNames.length; i++) {\n if (skins.jointNames[i] === id) {\n return true;\n }\n }\n return false;\n };\n /**\n * Fills the nodes to root for bones and builds hierarchy\n */\n var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {\n // Creates nodes for root\n for (var nde in gltfRuntime.nodes) {\n var node = gltfRuntime.nodes[nde];\n var id = nde;\n if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {\n continue;\n }\n // Create node to root bone\n var mat = configureBoneTransformation(node);\n var bone = new BABYLON.Bone(node.name || \"\", newSkeleton, null, mat);\n bone.id = id;\n nodesToRoot.push({ bone: bone, node: node, id: id });\n }\n // Parenting\n for (var i = 0; i < nodesToRoot.length; i++) {\n var nodeToRoot = nodesToRoot[i];\n var children = nodeToRoot.node.children;\n for (var j = 0; j < children.length; j++) {\n var child = null;\n for (var k = 0; k < nodesToRoot.length; k++) {\n if (nodesToRoot[k].id === children[j]) {\n child = nodesToRoot[k];\n break;\n }\n }\n if (child) {\n child.bone._parent = nodeToRoot.bone;\n nodeToRoot.bone.children.push(child.bone);\n }\n }\n }\n };\n /**\n * Imports a skeleton\n */\n var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {\n if (!newSkeleton) {\n newSkeleton = new BABYLON.Skeleton(skins.name || \"\", \"\", gltfRuntime.scene);\n }\n if (!skins.babylonSkeleton) {\n return newSkeleton;\n }\n // Find the root bones\n var nodesToRoot = [];\n var nodesToRootToAdd = [];\n getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);\n newSkeleton.bones = [];\n // Joints\n for (var i = 0; i < skins.jointNames.length; i++) {\n var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);\n if (!jointNode) {\n continue;\n }\n var node = jointNode.node;\n if (!node) {\n BABYLON.Tools.Warn(\"Joint named \" + skins.jointNames[i] + \" does not exist\");\n continue;\n }\n var id = jointNode.id;\n // Optimize, if the bone already exists...\n var existingBone = gltfRuntime.scene.getBoneByID(id);\n if (existingBone) {\n newSkeleton.bones.push(existingBone);\n continue;\n }\n // Search for parent bone\n var foundBone = false;\n var parentBone = null;\n for (var j = 0; j < i; j++) {\n var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);\n if (!jointNode_1) {\n continue;\n }\n var joint = jointNode_1.node;\n if (!joint) {\n BABYLON.Tools.Warn(\"Joint named \" + skins.jointNames[j] + \" does not exist when looking for parent\");\n continue;\n }\n var children = joint.children;\n if (!children) {\n continue;\n }\n foundBone = false;\n for (var k = 0; k < children.length; k++) {\n if (children[k] === id) {\n parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);\n foundBone = true;\n break;\n }\n }\n if (foundBone) {\n break;\n }\n }\n // Create bone\n var mat = configureBoneTransformation(node);\n if (!parentBone && nodesToRoot.length > 0) {\n parentBone = getNodeToRoot(nodesToRoot, id);\n if (parentBone) {\n if (nodesToRootToAdd.indexOf(parentBone) === -1) {\n nodesToRootToAdd.push(parentBone);\n }\n }\n }\n var bone = new BABYLON.Bone(node.jointName || \"\", newSkeleton, parentBone, mat);\n bone.id = id;\n }\n // Polish\n var bones = newSkeleton.bones;\n newSkeleton.bones = [];\n for (var i = 0; i < skins.jointNames.length; i++) {\n var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);\n if (!jointNode) {\n continue;\n }\n for (var j = 0; j < bones.length; j++) {\n if (bones[j].id === jointNode.id) {\n newSkeleton.bones.push(bones[j]);\n break;\n }\n }\n }\n newSkeleton.prepare();\n // Finish\n for (var i = 0; i < nodesToRootToAdd.length; i++) {\n newSkeleton.bones.push(nodesToRootToAdd[i]);\n }\n return newSkeleton;\n };\n /**\n * Imports a mesh and its geometries\n */\n var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {\n if (!newMesh) {\n newMesh = new BABYLON.Mesh(node.name || \"\", gltfRuntime.scene);\n newMesh.id = id;\n }\n if (!node.babylonNode) {\n return newMesh;\n }\n var subMaterials = [];\n var vertexData = null;\n var verticesStarts = new Array();\n var verticesCounts = new Array();\n var indexStarts = new Array();\n var indexCounts = new Array();\n for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {\n var meshID = meshes[meshIndex];\n var mesh = gltfRuntime.meshes[meshID];\n if (!mesh) {\n continue;\n }\n // Positions, normals and UVs\n for (var i = 0; i < mesh.primitives.length; i++) {\n // Temporary vertex data\n var tempVertexData = new BABYLON.VertexData();\n var primitive = mesh.primitives[i];\n if (primitive.mode !== 4) {\n // continue;\n }\n var attributes = primitive.attributes;\n var accessor = null;\n var buffer = null;\n // Set positions, normal and uvs\n for (var semantic in attributes) {\n // Link accessor and buffer view\n accessor = gltfRuntime.accessors[attributes[semantic]];\n buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);\n if (semantic === \"NORMAL\") {\n tempVertexData.normals = new Float32Array(buffer.length);\n tempVertexData.normals.set(buffer);\n }\n else if (semantic === \"POSITION\") {\n if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {\n tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);\n for (var j = 0; j < buffer.length; j += 4) {\n tempVertexData.positions[j] = buffer[j];\n tempVertexData.positions[j + 1] = buffer[j + 1];\n tempVertexData.positions[j + 2] = buffer[j + 2];\n }\n }\n else {\n tempVertexData.positions = new Float32Array(buffer.length);\n tempVertexData.positions.set(buffer);\n }\n verticesCounts.push(tempVertexData.positions.length);\n }\n else if (semantic.indexOf(\"TEXCOORD_\") !== -1) {\n var channel = Number(semantic.split(\"_\")[1]);\n var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? \"\" : (channel + 1));\n var uvs = new Float32Array(buffer.length);\n uvs.set(buffer);\n normalizeUVs(uvs);\n tempVertexData.set(uvs, uvKind);\n }\n else if (semantic === \"JOINT\") {\n tempVertexData.matricesIndices = new Float32Array(buffer.length);\n tempVertexData.matricesIndices.set(buffer);\n }\n else if (semantic === \"WEIGHT\") {\n tempVertexData.matricesWeights = new Float32Array(buffer.length);\n tempVertexData.matricesWeights.set(buffer);\n }\n else if (semantic === \"COLOR\") {\n tempVertexData.colors = new Float32Array(buffer.length);\n tempVertexData.colors.set(buffer);\n }\n }\n // Indices\n accessor = gltfRuntime.accessors[primitive.indices];\n if (accessor) {\n buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);\n tempVertexData.indices = new Int32Array(buffer.length);\n tempVertexData.indices.set(buffer);\n indexCounts.push(tempVertexData.indices.length);\n }\n else {\n // Set indices on the fly\n var indices = [];\n for (var j = 0; j < tempVertexData.positions.length / 3; j++) {\n indices.push(j);\n }\n tempVertexData.indices = new Int32Array(indices);\n indexCounts.push(tempVertexData.indices.length);\n }\n if (!vertexData) {\n vertexData = tempVertexData;\n }\n else {\n vertexData.merge(tempVertexData);\n }\n // Sub material\n var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);\n subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);\n // Update vertices start and index start\n verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);\n indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);\n }\n }\n var material;\n if (subMaterials.length > 1) {\n material = new BABYLON.MultiMaterial(\"multimat\" + id, gltfRuntime.scene);\n material.subMaterials = subMaterials;\n }\n else {\n material = new BABYLON.StandardMaterial(\"multimat\" + id, gltfRuntime.scene);\n }\n if (subMaterials.length === 1) {\n material = subMaterials[0];\n }\n if (!newMesh.material) {\n newMesh.material = material;\n }\n // Apply geometry\n new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);\n newMesh.computeWorldMatrix(true);\n // Apply submeshes\n newMesh.subMeshes = [];\n var index = 0;\n for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {\n var meshID = meshes[meshIndex];\n var mesh = gltfRuntime.meshes[meshID];\n if (!mesh) {\n continue;\n }\n for (var i = 0; i < mesh.primitives.length; i++) {\n if (mesh.primitives[i].mode !== 4) {\n //continue;\n }\n BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);\n index++;\n }\n }\n // Finish\n return newMesh;\n };\n /**\n * Configure node transformation from position, rotation and scaling\n */\n var configureNode = function (newNode, position, rotation, scaling) {\n if (newNode.position) {\n newNode.position = position;\n }\n if (newNode.rotationQuaternion || newNode.rotation) {\n newNode.rotationQuaternion = rotation;\n }\n if (newNode.scaling) {\n newNode.scaling = scaling;\n }\n };\n /**\n * Configures node from transformation matrix\n */\n var configureNodeFromMatrix = function (newNode, node, parent) {\n if (node.matrix) {\n var position = new BABYLON.Vector3(0, 0, 0);\n var rotation = new BABYLON.Quaternion();\n var scaling = new BABYLON.Vector3(0, 0, 0);\n var mat = BABYLON.Matrix.FromArray(node.matrix);\n mat.decompose(scaling, rotation, position);\n configureNode(newNode, position, rotation, scaling);\n }\n else if (node.translation && node.rotation && node.scale) {\n configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));\n }\n newNode.computeWorldMatrix(true);\n };\n /**\n * Imports a node\n */\n var importNode = function (gltfRuntime, node, id, parent) {\n var lastNode = null;\n if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {\n if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || \"\") === -1) {\n return null;\n }\n }\n // Meshes\n if (node.skin) {\n if (node.meshes) {\n var skin = gltfRuntime.skins[node.skin];\n var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);\n newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);\n if (newMesh.skeleton === null) {\n newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);\n if (!skin.babylonSkeleton) {\n skin.babylonSkeleton = newMesh.skeleton;\n }\n }\n lastNode = newMesh;\n }\n }\n else if (node.meshes) {\n /**\n * Improve meshes property\n */\n var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);\n lastNode = newMesh;\n }\n // Lights\n else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {\n var light = gltfRuntime.lights[node.light];\n if (light) {\n if (light.type === \"ambient\") {\n var ambienLight = light[light.type];\n var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);\n hemiLight.name = node.name || \"\";\n if (ambienLight.color) {\n hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);\n }\n lastNode = hemiLight;\n }\n else if (light.type === \"directional\") {\n var directionalLight = light[light.type];\n var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);\n dirLight.name = node.name || \"\";\n if (directionalLight.color) {\n dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);\n }\n lastNode = dirLight;\n }\n else if (light.type === \"point\") {\n var pointLight = light[light.type];\n var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);\n ptLight.name = node.name || \"\";\n if (pointLight.color) {\n ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);\n }\n lastNode = ptLight;\n }\n else if (light.type === \"spot\") {\n var spotLight = light[light.type];\n var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);\n spLight.name = node.name || \"\";\n if (spotLight.color) {\n spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);\n }\n if (spotLight.fallOfAngle) {\n spLight.angle = spotLight.fallOfAngle;\n }\n if (spotLight.fallOffExponent) {\n spLight.exponent = spotLight.fallOffExponent;\n }\n lastNode = spLight;\n }\n }\n }\n // Cameras\n else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {\n var camera = gltfRuntime.cameras[node.camera];\n if (camera) {\n if (camera.type === \"orthographic\") {\n var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);\n orthoCamera.name = node.name || \"\";\n orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;\n orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());\n lastNode = orthoCamera;\n }\n else if (camera.type === \"perspective\") {\n var perspectiveCamera = camera[camera.type];\n var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);\n persCamera.name = node.name || \"\";\n persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());\n if (!perspectiveCamera.aspectRatio) {\n perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();\n }\n if (perspectiveCamera.znear && perspectiveCamera.zfar) {\n persCamera.maxZ = perspectiveCamera.zfar;\n persCamera.minZ = perspectiveCamera.znear;\n }\n lastNode = persCamera;\n }\n }\n }\n // Empty node\n if (!node.jointName) {\n if (node.babylonNode) {\n return node.babylonNode;\n }\n else if (lastNode === null) {\n var dummy = new BABYLON.Mesh(node.name || \"\", gltfRuntime.scene);\n node.babylonNode = dummy;\n lastNode = dummy;\n }\n }\n if (lastNode !== null) {\n if (node.matrix && lastNode instanceof BABYLON.Mesh) {\n configureNodeFromMatrix(lastNode, node, parent);\n }\n else {\n var translation = node.translation || [0, 0, 0];\n var rotation = node.rotation || [0, 0, 0, 1];\n var scale = node.scale || [1, 1, 1];\n configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));\n }\n lastNode.updateCache(true);\n node.babylonNode = lastNode;\n }\n return lastNode;\n };\n /**\n * Traverses nodes and creates them\n */\n var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {\n if (meshIncluded === void 0) { meshIncluded = false; }\n var node = gltfRuntime.nodes[id];\n var newNode = null;\n if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {\n if (gltfRuntime.importMeshesNames.indexOf(node.name || \"\") !== -1 || gltfRuntime.importMeshesNames.length === 0) {\n meshIncluded = true;\n }\n else {\n meshIncluded = false;\n }\n }\n else {\n meshIncluded = true;\n }\n if (!node.jointName && meshIncluded) {\n newNode = importNode(gltfRuntime, node, id, parent);\n if (newNode !== null) {\n newNode.id = id;\n newNode.parent = parent;\n }\n }\n if (node.children) {\n for (var i = 0; i < node.children.length; i++) {\n traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);\n }\n }\n };\n /**\n * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)\n */\n var postLoad = function (gltfRuntime) {\n // Nodes\n var currentScene = gltfRuntime.currentScene;\n if (currentScene) {\n for (var i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n else {\n for (var thing in gltfRuntime.scenes) {\n currentScene = gltfRuntime.scenes[thing];\n for (var i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n }\n // Set animations\n loadAnimations(gltfRuntime);\n for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {\n var skeleton = gltfRuntime.scene.skeletons[i];\n gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);\n }\n };\n /**\n * onBind shaderrs callback to set uniforms and matrices\n */\n var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {\n var materialValues = material.values || technique.parameters;\n for (var unif in unTreatedUniforms) {\n var uniform = unTreatedUniforms[unif];\n var type = uniform.type;\n if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {\n if (uniform.semantic && !uniform.source && !uniform.node) {\n GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());\n }\n else if (uniform.semantic && (uniform.source || uniform.node)) {\n var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || \"\");\n if (source === null) {\n source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || \"\");\n }\n if (source === null) {\n continue;\n }\n GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());\n }\n }\n else {\n var value = materialValues[technique.uniforms[unif]];\n if (!value) {\n continue;\n }\n if (type === GLTF1.EParameterType.SAMPLER_2D) {\n var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;\n if (texture === null || texture === undefined) {\n continue;\n }\n shaderMaterial.getEffect().setTexture(unif, texture);\n }\n else {\n GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);\n }\n }\n }\n onSuccess(shaderMaterial);\n };\n /**\n * Prepare uniforms to send the only one time\n * Loads the appropriate textures\n */\n var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {\n var materialValues = material.values || technique.parameters;\n var techniqueUniforms = technique.uniforms;\n /**\n * Prepare values here (not matrices)\n */\n for (var unif in unTreatedUniforms) {\n var uniform = unTreatedUniforms[unif];\n var type = uniform.type;\n var value = materialValues[techniqueUniforms[unif]];\n if (value === undefined) {\n // In case the value is the same for all materials\n value = uniform.value;\n }\n if (!value) {\n continue;\n }\n var onLoadTexture = function (uniformName) {\n return function (texture) {\n if (uniform.value && uniformName) {\n // Static uniform\n shaderMaterial.setTexture(uniformName, texture);\n delete unTreatedUniforms[uniformName];\n }\n };\n };\n // Texture (sampler2D)\n if (type === GLTF1.EParameterType.SAMPLER_2D) {\n GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });\n }\n // Others\n else {\n if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {\n // Static uniform\n delete unTreatedUniforms[unif];\n }\n }\n }\n };\n /**\n * Shader compilation failed\n */\n var onShaderCompileError = function (program, shaderMaterial, onError) {\n return function (effect, error) {\n shaderMaterial.dispose(true);\n onError(\"Cannot compile program named \" + program.name + \". Error: \" + error + \". Default material will be applied\");\n };\n };\n /**\n * Shader compilation success\n */\n var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {\n return function (_) {\n prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);\n shaderMaterial.onBind = function (mesh) {\n onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);\n };\n };\n };\n /**\n * Returns the appropriate uniform if already handled by babylon\n */\n var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {\n for (var unif in technique.uniforms) {\n var uniform = technique.uniforms[unif];\n var uniformParameter = technique.parameters[uniform];\n if (tokenizer.currentIdentifier === unif) {\n if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {\n var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);\n if (transformIndex !== -1) {\n delete unTreatedUniforms[unif];\n return babylonTransforms[transformIndex];\n }\n }\n }\n }\n return tokenizer.currentIdentifier;\n };\n /**\n * All shaders loaded. Create materials one by one\n */\n var importMaterials = function (gltfRuntime) {\n // Create materials\n for (var mat in gltfRuntime.materials) {\n GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });\n }\n };\n /**\n * Implementation of the base glTF spec\n */\n var GLTFLoaderBase = /** @class */ (function () {\n function GLTFLoaderBase() {\n }\n GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {\n var gltfRuntime = {\n extensions: {},\n accessors: {},\n buffers: {},\n bufferViews: {},\n meshes: {},\n lights: {},\n cameras: {},\n nodes: {},\n images: {},\n textures: {},\n shaders: {},\n programs: {},\n samplers: {},\n techniques: {},\n materials: {},\n animations: {},\n skins: {},\n extensionsUsed: [],\n scenes: {},\n buffersCount: 0,\n shaderscount: 0,\n scene: scene,\n rootUrl: rootUrl,\n loadedBufferCount: 0,\n loadedBufferViews: {},\n loadedShaderCount: 0,\n importOnlyMeshes: false,\n dummyNodes: []\n };\n // Parse\n if (parsedData.extensions) {\n parseObject(parsedData.extensions, \"extensions\", gltfRuntime);\n }\n if (parsedData.extensionsUsed) {\n parseObject(parsedData.extensionsUsed, \"extensionsUsed\", gltfRuntime);\n }\n if (parsedData.buffers) {\n parseBuffers(parsedData.buffers, gltfRuntime);\n }\n if (parsedData.bufferViews) {\n parseObject(parsedData.bufferViews, \"bufferViews\", gltfRuntime);\n }\n if (parsedData.accessors) {\n parseObject(parsedData.accessors, \"accessors\", gltfRuntime);\n }\n if (parsedData.meshes) {\n parseObject(parsedData.meshes, \"meshes\", gltfRuntime);\n }\n if (parsedData.lights) {\n parseObject(parsedData.lights, \"lights\", gltfRuntime);\n }\n if (parsedData.cameras) {\n parseObject(parsedData.cameras, \"cameras\", gltfRuntime);\n }\n if (parsedData.nodes) {\n parseObject(parsedData.nodes, \"nodes\", gltfRuntime);\n }\n if (parsedData.images) {\n parseObject(parsedData.images, \"images\", gltfRuntime);\n }\n if (parsedData.textures) {\n parseObject(parsedData.textures, \"textures\", gltfRuntime);\n }\n if (parsedData.shaders) {\n parseShaders(parsedData.shaders, gltfRuntime);\n }\n if (parsedData.programs) {\n parseObject(parsedData.programs, \"programs\", gltfRuntime);\n }\n if (parsedData.samplers) {\n parseObject(parsedData.samplers, \"samplers\", gltfRuntime);\n }\n if (parsedData.techniques) {\n parseObject(parsedData.techniques, \"techniques\", gltfRuntime);\n }\n if (parsedData.materials) {\n parseObject(parsedData.materials, \"materials\", gltfRuntime);\n }\n if (parsedData.animations) {\n parseObject(parsedData.animations, \"animations\", gltfRuntime);\n }\n if (parsedData.skins) {\n parseObject(parsedData.skins, \"skins\", gltfRuntime);\n }\n if (parsedData.scenes) {\n gltfRuntime.scenes = parsedData.scenes;\n }\n if (parsedData.scene && parsedData.scenes) {\n gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];\n }\n return gltfRuntime;\n };\n GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {\n var buffer = gltfRuntime.buffers[id];\n if (BABYLON.Tools.IsBase64(buffer.uri)) {\n setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });\n }\n else {\n BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {\n if (request) {\n onError(request.status + \" \" + request.statusText);\n }\n });\n }\n };\n GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {\n var texture = gltfRuntime.textures[id];\n if (!texture || !texture.source) {\n onError(\"\");\n return;\n }\n if (texture.babylonTexture) {\n onSuccess(null);\n return;\n }\n var source = gltfRuntime.images[texture.source];\n if (BABYLON.Tools.IsBase64(source.uri)) {\n setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });\n }\n else {\n BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {\n if (request) {\n onError(request.status + \" \" + request.statusText);\n }\n });\n }\n };\n GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {\n var texture = gltfRuntime.textures[id];\n if (texture.babylonTexture) {\n onSuccess(texture.babylonTexture);\n return;\n }\n var sampler = gltfRuntime.samplers[texture.sampler];\n var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||\n (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||\n (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||\n (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);\n var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;\n var blob = new Blob([buffer]);\n var blobURL = URL.createObjectURL(blob);\n var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };\n var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);\n if (sampler.wrapS !== undefined) {\n newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);\n }\n if (sampler.wrapT !== undefined) {\n newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);\n }\n newTexture.name = id;\n texture.babylonTexture = newTexture;\n onSuccess(newTexture);\n };\n GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {\n var shader = gltfRuntime.shaders[id];\n if (BABYLON.Tools.IsBase64(shader.uri)) {\n var shaderString = atob(shader.uri.split(\",\")[1]);\n if (onSuccess) {\n onSuccess(shaderString);\n }\n }\n else {\n BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {\n if (request && onError) {\n onError(request.status + \" \" + request.statusText);\n }\n });\n }\n };\n GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {\n var material = gltfRuntime.materials[id];\n if (!material.technique) {\n if (onError) {\n onError(\"No technique found.\");\n }\n return;\n }\n var technique = gltfRuntime.techniques[material.technique];\n if (!technique) {\n var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);\n defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);\n defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;\n onSuccess(defaultMaterial);\n return;\n }\n var program = gltfRuntime.programs[technique.program];\n var states = technique.states;\n var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + \"VertexShader\"];\n var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + \"PixelShader\"];\n var newVertexShader = \"\";\n var newPixelShader = \"\";\n var vertexTokenizer = new Tokenizer(vertexShader);\n var pixelTokenizer = new Tokenizer(pixelShader);\n var unTreatedUniforms = {};\n var uniforms = [];\n var attributes = [];\n var samplers = [];\n // Fill uniform, sampler2D and attributes\n for (var unif in technique.uniforms) {\n var uniform = technique.uniforms[unif];\n var uniformParameter = technique.parameters[uniform];\n unTreatedUniforms[unif] = uniformParameter;\n if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {\n var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);\n if (transformIndex !== -1) {\n uniforms.push(babylonTransforms[transformIndex]);\n delete unTreatedUniforms[unif];\n }\n else {\n uniforms.push(unif);\n }\n }\n else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {\n samplers.push(unif);\n }\n else {\n uniforms.push(unif);\n }\n }\n for (var attr in technique.attributes) {\n var attribute = technique.attributes[attr];\n var attributeParameter = technique.parameters[attribute];\n if (attributeParameter.semantic) {\n attributes.push(getAttribute(attributeParameter));\n }\n }\n // Configure vertex shader\n while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {\n var tokenType = vertexTokenizer.currentToken;\n if (tokenType !== ETokenType.IDENTIFIER) {\n newVertexShader += vertexTokenizer.currentString;\n continue;\n }\n var foundAttribute = false;\n for (var attr in technique.attributes) {\n var attribute = technique.attributes[attr];\n var attributeParameter = technique.parameters[attribute];\n if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {\n newVertexShader += getAttribute(attributeParameter);\n foundAttribute = true;\n break;\n }\n }\n if (foundAttribute) {\n continue;\n }\n newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);\n }\n // Configure pixel shader\n while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {\n var tokenType = pixelTokenizer.currentToken;\n if (tokenType !== ETokenType.IDENTIFIER) {\n newPixelShader += pixelTokenizer.currentString;\n continue;\n }\n newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);\n }\n // Create shader material\n var shaderPath = {\n vertex: program.vertexShader + id,\n fragment: program.fragmentShader + id\n };\n var options = {\n attributes: attributes,\n uniforms: uniforms,\n samplers: samplers,\n needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1\n };\n BABYLON.Effect.ShadersStore[program.vertexShader + id + \"VertexShader\"] = newVertexShader;\n BABYLON.Effect.ShadersStore[program.fragmentShader + id + \"PixelShader\"] = newPixelShader;\n var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);\n shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);\n shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);\n shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;\n if (states && states.functions) {\n var functions = states.functions;\n if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {\n shaderMaterial.backFaceCulling = false;\n }\n var blendFunc = functions.blendFuncSeparate;\n if (blendFunc) {\n if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;\n }\n else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;\n }\n else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;\n }\n else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;\n }\n else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;\n }\n else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;\n }\n }\n }\n };\n return GLTFLoaderBase;\n }());\n GLTF1.GLTFLoaderBase = GLTFLoaderBase;\n /**\n * glTF V1 Loader\n */\n var GLTFLoader = /** @class */ (function () {\n function GLTFLoader() {\n this.state = null;\n }\n GLTFLoader.RegisterExtension = function (extension) {\n if (GLTFLoader.Extensions[extension.name]) {\n BABYLON.Tools.Error(\"Tool with the same name \\\"\" + extension.name + \"\\\" already exists\");\n return;\n }\n GLTFLoader.Extensions[extension.name] = extension;\n };\n GLTFLoader.prototype.dispose = function () {\n // do nothing\n };\n GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {\n var _this = this;\n scene.useRightHandedSystem = true;\n GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {\n gltfRuntime.importOnlyMeshes = true;\n if (meshesNames === \"\") {\n gltfRuntime.importMeshesNames = [];\n }\n else if (typeof meshesNames === \"string\") {\n gltfRuntime.importMeshesNames = [meshesNames];\n }\n else if (meshesNames && !(meshesNames instanceof Array)) {\n gltfRuntime.importMeshesNames = [meshesNames];\n }\n else {\n gltfRuntime.importMeshesNames = [];\n BABYLON.Tools.Warn(\"Argument meshesNames must be of type string or string[]\");\n }\n // Create nodes\n _this._createNodes(gltfRuntime);\n var meshes = new Array();\n var skeletons = new Array();\n // Fill arrays of meshes and skeletons\n for (var nde in gltfRuntime.nodes) {\n var node = gltfRuntime.nodes[nde];\n if (node.babylonNode instanceof BABYLON.AbstractMesh) {\n meshes.push(node.babylonNode);\n }\n }\n for (var skl in gltfRuntime.skins) {\n var skin = gltfRuntime.skins[skl];\n if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {\n skeletons.push(skin.babylonSkeleton);\n }\n }\n // Load buffers, shaders, materials, etc.\n _this._loadBuffersAsync(gltfRuntime, function () {\n _this._loadShadersAsync(gltfRuntime, function () {\n importMaterials(gltfRuntime);\n postLoad(gltfRuntime);\n if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {\n onSuccess(meshes, skeletons);\n }\n });\n }, onProgress);\n if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {\n onSuccess(meshes, skeletons);\n }\n }, onError);\n return true;\n };\n /**\n * Imports one or more meshes from a loaded gltf file and adds them to the scene\n * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file\n * @param scene the scene the meshes should be added to\n * @param data gltf data containing information of the meshes in a loaded file\n * @param rootUrl root url to load from\n * @param onProgress event that fires when loading progress has occured\n * @returns a promise containg the loaded meshes, particles, skeletons and animations\n */\n GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {\n resolve({\n meshes: meshes,\n particleSystems: [],\n skeletons: skeletons,\n animationGroups: []\n });\n }, onProgress, function (message) {\n reject(new Error(message));\n });\n });\n };\n GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {\n var _this = this;\n scene.useRightHandedSystem = true;\n GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {\n // Load runtime extensios\n GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {\n // Create nodes\n _this._createNodes(gltfRuntime);\n // Load buffers, shaders, materials, etc.\n _this._loadBuffersAsync(gltfRuntime, function () {\n _this._loadShadersAsync(gltfRuntime, function () {\n importMaterials(gltfRuntime);\n postLoad(gltfRuntime);\n if (!BABYLON.GLTFFileLoader.IncrementalLoading) {\n onSuccess();\n }\n });\n });\n if (BABYLON.GLTFFileLoader.IncrementalLoading) {\n onSuccess();\n }\n }, onError);\n }, onError);\n };\n /**\n * Imports all objects from a loaded gltf file and adds them to the scene\n * @param scene the scene the objects should be added to\n * @param data gltf data containing information of the meshes in a loaded file\n * @param rootUrl root url to load from\n * @param onProgress event that fires when loading progress has occured\n * @returns a promise which completes when objects have been loaded to the scene\n */\n GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this._loadAsync(scene, data, rootUrl, function () {\n resolve();\n }, onProgress, function (message) {\n reject(new Error(message));\n });\n });\n };\n GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {\n var hasShaders = false;\n var processShader = function (sha, shader) {\n GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {\n if (shaderString instanceof ArrayBuffer) {\n return;\n }\n gltfRuntime.loadedShaderCount++;\n if (shaderString) {\n BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? \"VertexShader\" : \"PixelShader\")] = shaderString;\n }\n if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {\n onload();\n }\n }, function () {\n BABYLON.Tools.Error(\"Error when loading shader program named \" + sha + \" located at \" + shader.uri);\n });\n };\n for (var sha in gltfRuntime.shaders) {\n hasShaders = true;\n var shader = gltfRuntime.shaders[sha];\n if (shader) {\n processShader.bind(this, sha, shader)();\n }\n else {\n BABYLON.Tools.Error(\"No shader named: \" + sha);\n }\n }\n if (!hasShaders) {\n onload();\n }\n };\n ;\n GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {\n var hasBuffers = false;\n var processBuffer = function (buf, buffer) {\n GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {\n gltfRuntime.loadedBufferCount++;\n if (bufferView) {\n if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {\n BABYLON.Tools.Error(\"Buffer named \" + buf + \" is length \" + bufferView.byteLength + \". Expected: \" + buffer.byteLength); // Improve error message\n }\n gltfRuntime.loadedBufferViews[buf] = bufferView;\n }\n if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {\n onLoad();\n }\n }, function () {\n BABYLON.Tools.Error(\"Error when loading buffer named \" + buf + \" located at \" + buffer.uri);\n });\n };\n for (var buf in gltfRuntime.buffers) {\n hasBuffers = true;\n var buffer = gltfRuntime.buffers[buf];\n if (buffer) {\n processBuffer.bind(this, buf, buffer)();\n }\n else {\n BABYLON.Tools.Error(\"No buffer named: \" + buf);\n }\n }\n if (!hasBuffers) {\n onLoad();\n }\n };\n GLTFLoader.prototype._createNodes = function (gltfRuntime) {\n var currentScene = gltfRuntime.currentScene;\n if (currentScene) {\n // Only one scene even if multiple scenes are defined\n for (var i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n else {\n // Load all scenes\n for (var thing in gltfRuntime.scenes) {\n currentScene = gltfRuntime.scenes[thing];\n for (var i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n }\n };\n GLTFLoader.Extensions = {};\n return GLTFLoader;\n }());\n GLTF1.GLTFLoader = GLTFLoader;\n ;\n BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };\n })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFLoader.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF1;\n (function (GLTF1) {\n /**\n * Utils functions for GLTF\n */\n var GLTFUtils = /** @class */ (function () {\n function GLTFUtils() {\n }\n /**\n * Sets the given \"parameter\" matrix\n * @param scene: the {BABYLON.Scene} object\n * @param source: the source node where to pick the matrix\n * @param parameter: the GLTF technique parameter\n * @param uniformName: the name of the shader's uniform\n * @param shaderMaterial: the shader material\n */\n GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {\n var mat = null;\n if (parameter.semantic === \"MODEL\") {\n mat = source.getWorldMatrix();\n }\n else if (parameter.semantic === \"PROJECTION\") {\n mat = scene.getProjectionMatrix();\n }\n else if (parameter.semantic === \"VIEW\") {\n mat = scene.getViewMatrix();\n }\n else if (parameter.semantic === \"MODELVIEWINVERSETRANSPOSE\") {\n mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());\n }\n else if (parameter.semantic === \"MODELVIEW\") {\n mat = source.getWorldMatrix().multiply(scene.getViewMatrix());\n }\n else if (parameter.semantic === \"MODELVIEWPROJECTION\") {\n mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());\n }\n else if (parameter.semantic === \"MODELINVERSE\") {\n mat = source.getWorldMatrix().invert();\n }\n else if (parameter.semantic === \"VIEWINVERSE\") {\n mat = scene.getViewMatrix().invert();\n }\n else if (parameter.semantic === \"PROJECTIONINVERSE\") {\n mat = scene.getProjectionMatrix().invert();\n }\n else if (parameter.semantic === \"MODELVIEWINVERSE\") {\n mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();\n }\n else if (parameter.semantic === \"MODELVIEWPROJECTIONINVERSE\") {\n mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();\n }\n else if (parameter.semantic === \"MODELINVERSETRANSPOSE\") {\n mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());\n }\n else {\n debugger;\n }\n if (mat) {\n switch (parameter.type) {\n case GLTF1.EParameterType.FLOAT_MAT2:\n shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));\n break;\n case GLTF1.EParameterType.FLOAT_MAT3:\n shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));\n break;\n case GLTF1.EParameterType.FLOAT_MAT4:\n shaderMaterial.setMatrix(uniformName, mat);\n break;\n default: break;\n }\n }\n };\n /**\n * Sets the given \"parameter\" matrix\n * @param shaderMaterial: the shader material\n * @param uniform: the name of the shader's uniform\n * @param value: the value of the uniform\n * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)\n */\n GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {\n switch (type) {\n case GLTF1.EParameterType.FLOAT:\n shaderMaterial.setFloat(uniform, value);\n return true;\n case GLTF1.EParameterType.FLOAT_VEC2:\n shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));\n return true;\n case GLTF1.EParameterType.FLOAT_VEC3:\n shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));\n return true;\n case GLTF1.EParameterType.FLOAT_VEC4:\n shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));\n return true;\n default: return false;\n }\n };\n /**\n * Returns the wrap mode of the texture\n * @param mode: the mode value\n */\n GLTFUtils.GetWrapMode = function (mode) {\n switch (mode) {\n case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;\n case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;\n case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;\n default: return BABYLON.Texture.WRAP_ADDRESSMODE;\n }\n };\n /**\n * Returns the byte stride giving an accessor\n * @param accessor: the GLTF accessor objet\n */\n GLTFUtils.GetByteStrideFromType = function (accessor) {\n // Needs this function since \"byteStride\" isn't requiered in glTF format\n var type = accessor.type;\n switch (type) {\n case \"VEC2\": return 2;\n case \"VEC3\": return 3;\n case \"VEC4\": return 4;\n case \"MAT2\": return 4;\n case \"MAT3\": return 9;\n case \"MAT4\": return 16;\n default: return 1;\n }\n };\n /**\n * Returns the texture filter mode giving a mode value\n * @param mode: the filter mode value\n */\n GLTFUtils.GetTextureFilterMode = function (mode) {\n switch (mode) {\n case GLTF1.ETextureFilterType.LINEAR:\n case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:\n case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;\n case GLTF1.ETextureFilterType.NEAREST:\n case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;\n default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;\n }\n };\n GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {\n var byteOffset = bufferView.byteOffset + byteOffset;\n var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];\n if (byteOffset + byteLength > loadedBufferView.byteLength) {\n throw new Error(\"Buffer access is out of range\");\n }\n var buffer = loadedBufferView.buffer;\n byteOffset += loadedBufferView.byteOffset;\n switch (componentType) {\n case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);\n case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);\n case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);\n case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);\n default: return new Float32Array(buffer, byteOffset, byteLength);\n }\n };\n /**\n * Returns a buffer from its accessor\n * @param gltfRuntime: the GLTF runtime\n * @param accessor: the GLTF accessor\n */\n GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {\n var bufferView = gltfRuntime.bufferViews[accessor.bufferView];\n var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);\n return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);\n };\n /**\n * Decodes a buffer view into a string\n * @param view: the buffer view\n */\n GLTFUtils.DecodeBufferToText = function (view) {\n var result = \"\";\n var length = view.byteLength;\n for (var i = 0; i < length; ++i) {\n result += String.fromCharCode(view[i]);\n }\n return result;\n };\n /**\n * Returns the default material of gltf. Related to\n * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material\n * @param scene: the Babylon.js scene\n */\n GLTFUtils.GetDefaultMaterial = function (scene) {\n if (!GLTFUtils._DefaultMaterial) {\n BABYLON.Effect.ShadersStore[\"GLTFDefaultMaterialVertexShader\"] = [\n \"precision highp float;\",\n \"\",\n \"uniform mat4 worldView;\",\n \"uniform mat4 projection;\",\n \"\",\n \"attribute vec3 position;\",\n \"\",\n \"void main(void)\",\n \"{\",\n \" gl_Position = projection * worldView * vec4(position, 1.0);\",\n \"}\"\n ].join(\"\\n\");\n BABYLON.Effect.ShadersStore[\"GLTFDefaultMaterialPixelShader\"] = [\n \"precision highp float;\",\n \"\",\n \"uniform vec4 u_emission;\",\n \"\",\n \"void main(void)\",\n \"{\",\n \" gl_FragColor = u_emission;\",\n \"}\"\n ].join(\"\\n\");\n var shaderPath = {\n vertex: \"GLTFDefaultMaterial\",\n fragment: \"GLTFDefaultMaterial\"\n };\n var options = {\n attributes: [\"position\"],\n uniforms: [\"worldView\", \"projection\", \"u_emission\"],\n samplers: new Array(),\n needAlphaBlending: false\n };\n GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial(\"GLTFDefaultMaterial\", scene, shaderPath, options);\n GLTFUtils._DefaultMaterial.setColor4(\"u_emission\", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));\n }\n return GLTFUtils._DefaultMaterial;\n };\n // The GLTF default material\n GLTFUtils._DefaultMaterial = null;\n return GLTFUtils;\n }());\n GLTF1.GLTFUtils = GLTFUtils;\n })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFLoaderUtils.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF1;\n (function (GLTF1) {\n var GLTFLoaderExtension = /** @class */ (function () {\n function GLTFLoaderExtension(name) {\n this._name = name;\n }\n Object.defineProperty(GLTFLoaderExtension.prototype, \"name\", {\n get: function () {\n return this._name;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Defines an override for loading the runtime\n * Return true to stop further extensions from loading the runtime\n */\n GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {\n return false;\n };\n /**\n * Defines an onverride for creating gltf runtime\n * Return true to stop further extensions from creating the runtime\n */\n GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {\n return false;\n };\n /**\n * Defines an override for loading buffers\n * Return true to stop further extensions from loading this buffer\n */\n GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {\n return false;\n };\n /**\n * Defines an override for loading texture buffers\n * Return true to stop further extensions from loading this texture data\n */\n GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {\n return false;\n };\n /**\n * Defines an override for creating textures\n * Return true to stop further extensions from loading this texture\n */\n GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {\n return false;\n };\n /**\n * Defines an override for loading shader strings\n * Return true to stop further extensions from loading this shader data\n */\n GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {\n return false;\n };\n /**\n * Defines an override for loading materials\n * Return true to stop further extensions from loading this material\n */\n GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {\n return false;\n };\n // ---------\n // Utilities\n // ---------\n GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);\n }, function () {\n setTimeout(function () {\n if (!onSuccess) {\n return;\n }\n onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));\n });\n });\n };\n GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);\n }, function () {\n setTimeout(function () {\n onSuccess();\n });\n });\n };\n GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);\n }, function () {\n GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);\n });\n };\n GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {\n if (buffer) {\n GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);\n }\n }, onError);\n };\n GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);\n }, function () {\n GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);\n });\n };\n GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);\n }, function () {\n GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);\n });\n };\n GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);\n }, function () {\n GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);\n });\n };\n GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);\n }, function () {\n GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);\n });\n };\n GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {\n for (var extensionName in GLTF1.GLTFLoader.Extensions) {\n var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];\n if (func(loaderExtension)) {\n return;\n }\n }\n defaultFunc();\n };\n return GLTFLoaderExtension;\n }());\n GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;\n })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFLoaderExtension.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF1;\n (function (GLTF1) {\n var BinaryExtensionBufferName = \"binary_glTF\";\n ;\n ;\n var GLTFBinaryExtension = /** @class */ (function (_super) {\n __extends(GLTFBinaryExtension, _super);\n function GLTFBinaryExtension() {\n return _super.call(this, \"KHR_binary_glTF\") || this;\n }\n GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {\n var extensionsUsed = data.json.extensionsUsed;\n if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {\n return false;\n }\n this._bin = data.bin;\n onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));\n return true;\n };\n GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {\n if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {\n return false;\n }\n if (id !== BinaryExtensionBufferName) {\n return false;\n }\n onSuccess(this._bin);\n return true;\n };\n GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {\n var texture = gltfRuntime.textures[id];\n var source = gltfRuntime.images[texture.source];\n if (!source.extensions || !(this.name in source.extensions)) {\n return false;\n }\n var sourceExt = source.extensions[this.name];\n var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];\n var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);\n onSuccess(buffer);\n return true;\n };\n GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {\n var shader = gltfRuntime.shaders[id];\n if (!shader.extensions || !(this.name in shader.extensions)) {\n return false;\n }\n var binaryExtensionShader = shader.extensions[this.name];\n var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];\n var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);\n setTimeout(function () {\n var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);\n onSuccess(shaderString);\n });\n return true;\n };\n return GLTFBinaryExtension;\n }(GLTF1.GLTFLoaderExtension));\n GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;\n GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());\n })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFBinaryExtension.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF1;\n (function (GLTF1) {\n ;\n ;\n ;\n var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {\n __extends(GLTFMaterialsCommonExtension, _super);\n function GLTFMaterialsCommonExtension() {\n return _super.call(this, \"KHR_materials_common\") || this;\n }\n GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {\n if (!gltfRuntime.extensions)\n return false;\n var extension = gltfRuntime.extensions[this.name];\n if (!extension)\n return false;\n // Create lights\n var lights = extension.lights;\n if (lights) {\n for (var thing in lights) {\n var light = lights[thing];\n switch (light.type) {\n case \"ambient\":\n var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);\n var ambient = light.ambient;\n if (ambient) {\n ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);\n }\n break;\n case \"point\":\n var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);\n var point = light.point;\n if (point) {\n pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);\n }\n break;\n case \"directional\":\n var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);\n var directional = light.directional;\n if (directional) {\n dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);\n }\n break;\n case \"spot\":\n var spot = light.spot;\n if (spot) {\n var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);\n spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);\n }\n break;\n default:\n BABYLON.Tools.Warn(\"GLTF Material Common extension: light type \\\"\" + light.type + \"\\” not supported\");\n break;\n }\n }\n }\n return false;\n };\n GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {\n var material = gltfRuntime.materials[id];\n if (!material || !material.extensions)\n return false;\n var extension = material.extensions[this.name];\n if (!extension)\n return false;\n var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);\n standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;\n if (extension.technique === \"CONSTANT\") {\n standardMaterial.disableLighting = true;\n }\n standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;\n standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;\n standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;\n // Ambient\n if (typeof extension.values.ambient === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, \"ambientTexture\", onError);\n }\n else {\n standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);\n }\n // Diffuse\n if (typeof extension.values.diffuse === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, \"diffuseTexture\", onError);\n }\n else {\n standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);\n }\n // Emission\n if (typeof extension.values.emission === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, \"emissiveTexture\", onError);\n }\n else {\n standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);\n }\n // Specular\n if (typeof extension.values.specular === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, \"specularTexture\", onError);\n }\n else {\n standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);\n }\n return true;\n };\n GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {\n // Create buffer from texture url\n GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {\n // Create texture from buffer\n GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);\n }, onError);\n };\n return GLTFMaterialsCommonExtension;\n }(GLTF1.GLTFLoaderExtension));\n GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;\n GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());\n })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map\n\n\n\n\n//# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map\n\n\n/**\n * Defines the module used to import/export glTF 2.0 assets\n */\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n /** @hidden */\n var _ArrayItem = /** @class */ (function () {\n function _ArrayItem() {\n }\n _ArrayItem.Assign = function (values) {\n if (values) {\n for (var index = 0; index < values.length; index++) {\n values[index]._index = index;\n }\n }\n };\n return _ArrayItem;\n }());\n GLTF2._ArrayItem = _ArrayItem;\n /** @hidden */\n var GLTFLoader = /** @class */ (function () {\n function GLTFLoader(parent) {\n this._completePromises = new Array();\n this._disposed = false;\n this._state = null;\n this._extensions = {};\n this._defaultSampler = {};\n this._defaultBabylonMaterials = {};\n this._requests = new Array();\n this._parent = parent;\n }\n GLTFLoader._Register = function (name, factory) {\n if (GLTFLoader._ExtensionFactories[name]) {\n BABYLON.Tools.Error(\"Extension with the name '\" + name + \"' already exists\");\n return;\n }\n GLTFLoader._ExtensionFactories[name] = factory;\n // Keep the order of registration so that extensions registered first are called first.\n GLTFLoader._ExtensionNames.push(name);\n };\n Object.defineProperty(GLTFLoader.prototype, \"state\", {\n /**\n * Loader state or null if the loader is not active.\n */\n get: function () {\n return this._state;\n },\n enumerable: true,\n configurable: true\n });\n GLTFLoader.prototype.dispose = function () {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {\n var request = _a[_i];\n request.abort();\n }\n this._requests.length = 0;\n delete this._gltf;\n delete this._babylonScene;\n delete this._readyPromise;\n this._completePromises.length = 0;\n for (var name_1 in this._extensions) {\n this._extensions[name_1].dispose();\n }\n this._extensions = {};\n delete this._rootBabylonMesh;\n delete this._progressCallback;\n this._parent._clear();\n };\n GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {\n var _this = this;\n return Promise.resolve().then(function () {\n _this._babylonScene = scene;\n _this._rootUrl = rootUrl;\n _this._progressCallback = onProgress;\n _this._loadData(data);\n var nodes = null;\n if (meshesNames) {\n var nodeMap_1 = {};\n if (_this._gltf.nodes) {\n for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {\n var node = _a[_i];\n if (node.name) {\n nodeMap_1[node.name] = node._index;\n }\n }\n }\n var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];\n nodes = names.map(function (name) {\n var node = nodeMap_1[name];\n if (node === undefined) {\n throw new Error(\"Failed to find node '\" + name + \"'\");\n }\n return node;\n });\n }\n return _this._loadAsync(nodes).then(function () {\n return {\n meshes: _this._getMeshes(),\n particleSystems: [],\n skeletons: _this._getSkeletons(),\n animationGroups: _this._getAnimationGroups()\n };\n });\n });\n };\n GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {\n var _this = this;\n return Promise.resolve().then(function () {\n _this._babylonScene = scene;\n _this._rootUrl = rootUrl;\n _this._progressCallback = onProgress;\n _this._loadData(data);\n return _this._loadAsync(null);\n });\n };\n GLTFLoader.prototype._loadAsync = function (nodes) {\n var _this = this;\n return Promise.resolve().then(function () {\n _this._parent._startPerformanceCounter(\"Loading => Ready\");\n _this._parent._startPerformanceCounter(\"Loading => Complete\");\n _this._state = BABYLON.GLTFLoaderState.LOADING;\n _this._parent._log(\"Loading\");\n var readyDeferred = new BABYLON.Deferred();\n _this._readyPromise = readyDeferred.promise;\n _this._loadExtensions();\n _this._checkExtensions();\n var promises = new Array();\n if (nodes) {\n promises.push(_this._loadSceneAsync(\"#/nodes\", { nodes: nodes, _index: -1 }));\n }\n else {\n var scene = GLTFLoader._GetProperty(\"#/scene\", _this._gltf.scenes, _this._gltf.scene || 0);\n promises.push(_this._loadSceneAsync(\"#/scenes/\" + scene._index, scene));\n }\n if (_this._parent.compileMaterials) {\n promises.push(_this._compileMaterialsAsync());\n }\n if (_this._parent.compileShadowGenerators) {\n promises.push(_this._compileShadowGeneratorsAsync());\n }\n var resultPromise = Promise.all(promises).then(function () {\n _this._state = BABYLON.GLTFLoaderState.READY;\n _this._parent._log(\"Ready\");\n readyDeferred.resolve();\n _this._startAnimations();\n });\n resultPromise.then(function () {\n _this._parent._endPerformanceCounter(\"Loading => Ready\");\n BABYLON.Tools.SetImmediate(function () {\n if (!_this._disposed) {\n Promise.all(_this._completePromises).then(function () {\n _this._parent._endPerformanceCounter(\"Loading => Complete\");\n _this._state = BABYLON.GLTFLoaderState.COMPLETE;\n _this._parent._log(\"Complete\");\n _this._parent.onCompleteObservable.notifyObservers(undefined);\n _this._parent.onCompleteObservable.clear();\n _this.dispose();\n }).catch(function (error) {\n BABYLON.Tools.Error(\"glTF Loader: \" + error.message);\n _this.dispose();\n });\n }\n });\n });\n return resultPromise;\n }).catch(function (error) {\n if (!_this._disposed) {\n BABYLON.Tools.Error(\"glTF Loader: \" + error.message);\n _this.dispose();\n throw error;\n }\n });\n };\n GLTFLoader.prototype._loadData = function (data) {\n this._gltf = data.json;\n this._setupData();\n if (data.bin) {\n var buffers = this._gltf.buffers;\n if (buffers && buffers[0] && !buffers[0].uri) {\n var binaryBuffer = buffers[0];\n if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {\n BABYLON.Tools.Warn(\"Binary buffer length (\" + binaryBuffer.byteLength + \") from JSON does not match chunk length (\" + data.bin.byteLength + \")\");\n }\n binaryBuffer._data = Promise.resolve(data.bin);\n }\n else {\n BABYLON.Tools.Warn(\"Unexpected BIN chunk\");\n }\n }\n };\n GLTFLoader.prototype._setupData = function () {\n _ArrayItem.Assign(this._gltf.accessors);\n _ArrayItem.Assign(this._gltf.animations);\n _ArrayItem.Assign(this._gltf.buffers);\n _ArrayItem.Assign(this._gltf.bufferViews);\n _ArrayItem.Assign(this._gltf.cameras);\n _ArrayItem.Assign(this._gltf.images);\n _ArrayItem.Assign(this._gltf.materials);\n _ArrayItem.Assign(this._gltf.meshes);\n _ArrayItem.Assign(this._gltf.nodes);\n _ArrayItem.Assign(this._gltf.samplers);\n _ArrayItem.Assign(this._gltf.scenes);\n _ArrayItem.Assign(this._gltf.skins);\n _ArrayItem.Assign(this._gltf.textures);\n if (this._gltf.nodes) {\n var nodeParents = {};\n for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {\n var node = _a[_i];\n if (node.children) {\n for (var _b = 0, _c = node.children; _b < _c.length; _b++) {\n var index = _c[_b];\n nodeParents[index] = node._index;\n }\n }\n }\n var rootNode = this._createRootNode();\n for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {\n var node = _e[_d];\n var parentIndex = nodeParents[node._index];\n node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];\n }\n }\n };\n GLTFLoader.prototype._loadExtensions = function () {\n for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {\n var name_2 = _a[_i];\n var extension = GLTFLoader._ExtensionFactories[name_2](this);\n this._extensions[name_2] = extension;\n this._parent.onExtensionLoadedObservable.notifyObservers(extension);\n }\n this._parent.onExtensionLoadedObservable.clear();\n };\n GLTFLoader.prototype._checkExtensions = function () {\n if (this._gltf.extensionsRequired) {\n for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {\n var name_3 = _a[_i];\n var extension = this._extensions[name_3];\n if (!extension || !extension.enabled) {\n throw new Error(\"Require extension \" + name_3 + \" is not available\");\n }\n }\n }\n };\n GLTFLoader.prototype._createRootNode = function () {\n this._rootBabylonMesh = new BABYLON.Mesh(\"__root__\", this._babylonScene);\n var rootNode = { _babylonMesh: this._rootBabylonMesh };\n switch (this._parent.coordinateSystemMode) {\n case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {\n if (!this._babylonScene.useRightHandedSystem) {\n rootNode.rotation = [0, 1, 0, 0];\n rootNode.scale = [1, 1, -1];\n GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);\n }\n break;\n }\n case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {\n this._babylonScene.useRightHandedSystem = true;\n break;\n }\n default: {\n throw new Error(\"Invalid coordinate system mode (\" + this._parent.coordinateSystemMode + \")\");\n }\n }\n this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);\n return rootNode;\n };\n GLTFLoader.prototype._loadSceneAsync = function (context, scene) {\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);\n if (extensionPromise) {\n return extensionPromise;\n }\n var promises = new Array();\n this._parent._logOpen(context + \" \" + (scene.name || \"\"));\n if (scene.nodes) {\n for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {\n var index = _a[_i];\n var node = GLTFLoader._GetProperty(context + \"/nodes/\" + index, this._gltf.nodes, index);\n promises.push(this._loadNodeAsync(\"#/nodes/\" + node._index, node));\n }\n }\n promises.push(this._loadAnimationsAsync());\n this._parent._logClose();\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._forEachPrimitive = function (node, callback) {\n if (node._primitiveBabylonMeshes) {\n for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {\n var babylonMesh = _a[_i];\n callback(babylonMesh);\n }\n }\n else {\n callback(node._babylonMesh);\n }\n };\n GLTFLoader.prototype._getMeshes = function () {\n var meshes = new Array();\n // Root mesh is always first.\n meshes.push(this._rootBabylonMesh);\n var nodes = this._gltf.nodes;\n if (nodes) {\n for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {\n var node = nodes_1[_i];\n if (node._babylonMesh) {\n meshes.push(node._babylonMesh);\n }\n if (node._primitiveBabylonMeshes) {\n for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {\n var babylonMesh = _b[_a];\n meshes.push(babylonMesh);\n }\n }\n }\n }\n return meshes;\n };\n GLTFLoader.prototype._getSkeletons = function () {\n var skeletons = new Array();\n var skins = this._gltf.skins;\n if (skins) {\n for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {\n var skin = skins_1[_i];\n if (skin._babylonSkeleton) {\n skeletons.push(skin._babylonSkeleton);\n }\n }\n }\n return skeletons;\n };\n GLTFLoader.prototype._getAnimationGroups = function () {\n var animationGroups = new Array();\n var animations = this._gltf.animations;\n if (animations) {\n for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {\n var animation = animations_1[_i];\n if (animation._babylonAnimationGroup) {\n animationGroups.push(animation._babylonAnimationGroup);\n }\n }\n }\n return animationGroups;\n };\n GLTFLoader.prototype._startAnimations = function () {\n switch (this._parent.animationStartMode) {\n case BABYLON.GLTFLoaderAnimationStartMode.NONE: {\n // do nothing\n break;\n }\n case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {\n var babylonAnimationGroups = this._getAnimationGroups();\n if (babylonAnimationGroups.length !== 0) {\n babylonAnimationGroups[0].start(true);\n }\n break;\n }\n case BABYLON.GLTFLoaderAnimationStartMode.ALL: {\n var babylonAnimationGroups = this._getAnimationGroups();\n for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {\n var babylonAnimationGroup = babylonAnimationGroups_1[_i];\n babylonAnimationGroup.start(true);\n }\n break;\n }\n default: {\n BABYLON.Tools.Error(\"Invalid animation start mode (\" + this._parent.animationStartMode + \")\");\n return;\n }\n }\n };\n GLTFLoader.prototype._loadNodeAsync = function (context, node) {\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (node._babylonMesh) {\n throw new Error(context + \": Invalid recursive node hierarchy\");\n }\n var promises = new Array();\n this._parent._logOpen(context + \" \" + (node.name || \"\"));\n var babylonMesh = new BABYLON.Mesh(node.name || \"node\" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);\n node._babylonMesh = babylonMesh;\n babylonMesh.setEnabled(false);\n GLTFLoader._LoadTransform(node, babylonMesh);\n if (node.mesh != undefined) {\n var mesh = GLTFLoader._GetProperty(context + \"/mesh\", this._gltf.meshes, node.mesh);\n promises.push(this._loadMeshAsync(\"#/meshes/\" + mesh._index, node, mesh, babylonMesh));\n }\n if (node.camera != undefined) {\n var camera = GLTFLoader._GetProperty(context + \"/camera\", this._gltf.cameras, node.camera);\n this._loadCamera(\"#/cameras/\" + camera._index, camera, babylonMesh);\n }\n if (node.children) {\n for (var _i = 0, _a = node.children; _i < _a.length; _i++) {\n var index = _a[_i];\n var childNode = GLTFLoader._GetProperty(context + \"/children/\" + index, this._gltf.nodes, index);\n promises.push(this._loadNodeAsync(\"#/nodes/\" + index, childNode));\n }\n }\n this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);\n this._parent._logClose();\n return Promise.all(promises).then(function () {\n babylonMesh.setEnabled(true);\n });\n };\n GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {\n var _this = this;\n var promises = new Array();\n this._parent._logOpen(context + \" \" + (mesh.name || \"\"));\n var primitives = mesh.primitives;\n if (!primitives || primitives.length === 0) {\n throw new Error(context + \": Primitives are missing\");\n }\n _ArrayItem.Assign(primitives);\n if (primitives.length === 1) {\n var primitive = primitives[0];\n promises.push(this._loadPrimitiveAsync(context + \"/primitives/\" + primitive._index, node, mesh, primitive, babylonMesh));\n }\n else {\n node._primitiveBabylonMeshes = [];\n for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {\n var primitive = primitives_1[_i];\n var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + \"_\" + primitive._index, this._babylonScene, babylonMesh);\n node._primitiveBabylonMeshes.push(primitiveBabylonMesh);\n promises.push(this._loadPrimitiveAsync(context + \"/primitives/\" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));\n this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);\n }\n }\n if (node.skin != undefined) {\n var skin = GLTFLoader._GetProperty(context + \"/skin\", this._gltf.skins, node.skin);\n promises.push(this._loadSkinAsync(\"#/skins/\" + skin._index, node, mesh, skin));\n }\n this._parent._logClose();\n return Promise.all(promises).then(function () {\n _this._forEachPrimitive(node, function (babylonMesh) {\n babylonMesh._refreshBoundingInfo(true);\n });\n });\n };\n GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {\n var _this = this;\n var promises = new Array();\n this._parent._logOpen(\"\" + context);\n this._createMorphTargets(context, node, mesh, primitive, babylonMesh);\n promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {\n return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {\n babylonGeometry.applyToMesh(babylonMesh);\n });\n }));\n var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);\n if (primitive.material == undefined) {\n babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);\n }\n else {\n var material = GLTFLoader._GetProperty(context + \"/material}\", this._gltf.materials, primitive.material);\n promises.push(this._loadMaterialAsync(\"#/materials/\" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {\n babylonMesh.material = babylonMaterial;\n }));\n }\n this._parent._logClose();\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {\n var _this = this;\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);\n if (extensionPromise) {\n return extensionPromise;\n }\n var attributes = primitive.attributes;\n if (!attributes) {\n throw new Error(context + \": Attributes are missing\");\n }\n var promises = new Array();\n var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);\n if (primitive.indices == undefined) {\n babylonMesh.isUnIndexed = true;\n }\n else {\n var accessor = GLTFLoader._GetProperty(context + \"/indices\", this._gltf.accessors, primitive.indices);\n promises.push(this._loadIndicesAccessorAsync(\"#/accessors/\" + accessor._index, accessor).then(function (data) {\n babylonGeometry.setIndices(data);\n }));\n }\n var loadAttribute = function (attribute, kind, callback) {\n if (attributes[attribute] == undefined) {\n return;\n }\n babylonMesh._delayInfo = babylonMesh._delayInfo || [];\n if (babylonMesh._delayInfo.indexOf(kind) === -1) {\n babylonMesh._delayInfo.push(kind);\n }\n var accessor = GLTFLoader._GetProperty(context + \"/attributes/\" + attribute, _this._gltf.accessors, attributes[attribute]);\n promises.push(_this._loadVertexAccessorAsync(\"#/accessors/\" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {\n babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);\n }));\n if (callback) {\n callback(accessor);\n }\n };\n loadAttribute(\"POSITION\", BABYLON.VertexBuffer.PositionKind);\n loadAttribute(\"NORMAL\", BABYLON.VertexBuffer.NormalKind);\n loadAttribute(\"TANGENT\", BABYLON.VertexBuffer.TangentKind);\n loadAttribute(\"TEXCOORD_0\", BABYLON.VertexBuffer.UVKind);\n loadAttribute(\"TEXCOORD_1\", BABYLON.VertexBuffer.UV2Kind);\n loadAttribute(\"JOINTS_0\", BABYLON.VertexBuffer.MatricesIndicesKind);\n loadAttribute(\"WEIGHTS_0\", BABYLON.VertexBuffer.MatricesWeightsKind);\n loadAttribute(\"COLOR_0\", BABYLON.VertexBuffer.ColorKind, function (accessor) {\n if (accessor.type === \"VEC4\" /* VEC4 */) {\n babylonMesh.hasVertexAlpha = true;\n }\n });\n return Promise.all(promises).then(function () {\n return babylonGeometry;\n });\n };\n GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {\n if (!primitive.targets) {\n return;\n }\n if (node._numMorphTargets == undefined) {\n node._numMorphTargets = primitive.targets.length;\n }\n else if (primitive.targets.length !== node._numMorphTargets) {\n throw new Error(context + \": Primitives do not have the same number of targets\");\n }\n babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();\n for (var index = 0; index < primitive.targets.length; index++) {\n var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;\n babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget(\"morphTarget\" + index, weight));\n // TODO: tell the target whether it has positions, normals, tangents\n }\n };\n GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {\n if (!primitive.targets) {\n return Promise.resolve();\n }\n var promises = new Array();\n var morphTargetManager = babylonMesh.morphTargetManager;\n for (var index = 0; index < morphTargetManager.numTargets; index++) {\n var babylonMorphTarget = morphTargetManager.getTarget(index);\n promises.push(this._loadMorphTargetVertexDataAsync(context + \"/targets/\" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));\n }\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {\n var _this = this;\n var promises = new Array();\n var loadAttribute = function (attribute, kind, setData) {\n if (attributes[attribute] == undefined) {\n return;\n }\n var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);\n if (!babylonVertexBuffer) {\n return;\n }\n var accessor = GLTFLoader._GetProperty(context + \"/\" + attribute, _this._gltf.accessors, attributes[attribute]);\n promises.push(_this._loadFloatAccessorAsync(\"#/accessors/\" + accessor._index, accessor).then(function (data) {\n setData(babylonVertexBuffer, data);\n }));\n };\n loadAttribute(\"POSITION\", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {\n babylonVertexBuffer.forEach(data.length, function (value, index) {\n data[index] += value;\n });\n babylonMorphTarget.setPositions(data);\n });\n loadAttribute(\"NORMAL\", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {\n babylonVertexBuffer.forEach(data.length, function (value, index) {\n data[index] += value;\n });\n babylonMorphTarget.setNormals(data);\n });\n loadAttribute(\"TANGENT\", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {\n var dataIndex = 0;\n babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {\n // Tangent data for morph targets is stored as xyz delta.\n // The vertexData.tangent is stored as xyzw.\n // So we need to skip every fourth vertexData.tangent.\n if (((index + 1) % 4) !== 0) {\n data[dataIndex++] += value;\n }\n });\n babylonMorphTarget.setTangents(data);\n });\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader._LoadTransform = function (node, babylonNode) {\n var position = BABYLON.Vector3.Zero();\n var rotation = BABYLON.Quaternion.Identity();\n var scaling = BABYLON.Vector3.One();\n if (node.matrix) {\n var matrix = BABYLON.Matrix.FromArray(node.matrix);\n matrix.decompose(scaling, rotation, position);\n }\n else {\n if (node.translation)\n position = BABYLON.Vector3.FromArray(node.translation);\n if (node.rotation)\n rotation = BABYLON.Quaternion.FromArray(node.rotation);\n if (node.scale)\n scaling = BABYLON.Vector3.FromArray(node.scale);\n }\n babylonNode.position = position;\n babylonNode.rotationQuaternion = rotation;\n babylonNode.scaling = scaling;\n };\n GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {\n var _this = this;\n var assignSkeleton = function (skeleton) {\n _this._forEachPrimitive(node, function (babylonMesh) {\n babylonMesh.skeleton = skeleton;\n });\n // Ignore the TRS of skinned nodes.\n // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)\n node._babylonMesh.parent = _this._rootBabylonMesh;\n node._babylonMesh.position = BABYLON.Vector3.Zero();\n node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();\n node._babylonMesh.scaling = BABYLON.Vector3.One();\n };\n if (skin._loaded) {\n return skin._loaded.then(function () {\n assignSkeleton(skin._babylonSkeleton);\n });\n }\n var skeletonId = \"skeleton\" + skin._index;\n var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);\n skin._babylonSkeleton = babylonSkeleton;\n this._loadBones(context, skin);\n assignSkeleton(babylonSkeleton);\n return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {\n _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);\n }));\n };\n GLTFLoader.prototype._loadBones = function (context, skin) {\n var babylonBones = {};\n for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {\n var index = _a[_i];\n var node = GLTFLoader._GetProperty(context + \"/joints/\" + index, this._gltf.nodes, index);\n this._loadBone(node, skin, babylonBones);\n }\n };\n GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {\n var babylonBone = babylonBones[node._index];\n if (babylonBone) {\n return babylonBone;\n }\n var babylonParentBone = null;\n if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {\n babylonParentBone = this._loadBone(node._parent, skin, babylonBones);\n }\n var boneIndex = skin.joints.indexOf(node._index);\n babylonBone = new BABYLON.Bone(node.name || \"joint\" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);\n babylonBones[node._index] = babylonBone;\n node._babylonBones = node._babylonBones || [];\n node._babylonBones.push(babylonBone);\n return babylonBone;\n };\n GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {\n if (skin.inverseBindMatrices == undefined) {\n return Promise.resolve(null);\n }\n var accessor = GLTFLoader._GetProperty(context + \"/inverseBindMatrices\", this._gltf.accessors, skin.inverseBindMatrices);\n return this._loadFloatAccessorAsync(\"#/accessors/\" + accessor._index, accessor);\n };\n GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {\n for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {\n var babylonBone = _a[_i];\n var baseMatrix = BABYLON.Matrix.Identity();\n var boneIndex = babylonBone._index;\n if (inverseBindMatricesData && boneIndex !== -1) {\n BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);\n baseMatrix.invertToRef(baseMatrix);\n }\n var babylonParentBone = babylonBone.getParent();\n if (babylonParentBone) {\n baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);\n }\n babylonBone.updateMatrix(baseMatrix, false, false);\n babylonBone._updateDifferenceMatrix(undefined, false);\n }\n };\n GLTFLoader.prototype._getNodeMatrix = function (node) {\n return node.matrix ?\n BABYLON.Matrix.FromArray(node.matrix) :\n BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());\n };\n GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {\n var babylonCamera = new BABYLON.FreeCamera(camera.name || \"camera\" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);\n babylonCamera.parent = babylonMesh;\n babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);\n switch (camera.type) {\n case \"perspective\" /* PERSPECTIVE */: {\n var perspective = camera.perspective;\n if (!perspective) {\n throw new Error(context + \": Camera perspective properties are missing\");\n }\n babylonCamera.fov = perspective.yfov;\n babylonCamera.minZ = perspective.znear;\n babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;\n break;\n }\n case \"orthographic\" /* ORTHOGRAPHIC */: {\n if (!camera.orthographic) {\n throw new Error(context + \": Camera orthographic properties are missing\");\n }\n babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;\n babylonCamera.orthoLeft = -camera.orthographic.xmag;\n babylonCamera.orthoRight = camera.orthographic.xmag;\n babylonCamera.orthoBottom = -camera.orthographic.ymag;\n babylonCamera.orthoTop = camera.orthographic.ymag;\n babylonCamera.minZ = camera.orthographic.znear;\n babylonCamera.maxZ = camera.orthographic.zfar;\n break;\n }\n default: {\n throw new Error(context + \": Invalid camera type (\" + camera.type + \")\");\n }\n }\n this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);\n };\n GLTFLoader.prototype._loadAnimationsAsync = function () {\n var animations = this._gltf.animations;\n if (!animations) {\n return Promise.resolve();\n }\n var promises = new Array();\n for (var index = 0; index < animations.length; index++) {\n var animation = animations[index];\n promises.push(this._loadAnimationAsync(\"#/animations/\" + index, animation));\n }\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {\n var _this = this;\n var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || \"animation\" + animation._index, this._babylonScene);\n animation._babylonAnimationGroup = babylonAnimationGroup;\n var promises = new Array();\n _ArrayItem.Assign(animation.channels);\n _ArrayItem.Assign(animation.samplers);\n for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {\n var channel = _a[_i];\n promises.push(this._loadAnimationChannelAsync(context + \"/channels/\" + channel._index, context, animation, channel, babylonAnimationGroup));\n }\n return Promise.all(promises).then(function () {\n babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);\n });\n };\n GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {\n var _this = this;\n var targetNode = GLTFLoader._GetProperty(context + \"/target/node\", this._gltf.nodes, channel.target.node);\n // Ignore animations that have no animation targets.\n if ((channel.target.path === \"weights\" /* WEIGHTS */ && !targetNode._numMorphTargets) ||\n (channel.target.path !== \"weights\" /* WEIGHTS */ && !targetNode._babylonMesh)) {\n return Promise.resolve();\n }\n // Ignore animations targeting TRS of skinned nodes.\n // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)\n if (targetNode.skin != undefined && channel.target.path !== \"weights\" /* WEIGHTS */) {\n return Promise.resolve();\n }\n var sampler = GLTFLoader._GetProperty(context + \"/sampler\", animation.samplers, channel.sampler);\n return this._loadAnimationSamplerAsync(animationContext + \"/samplers/\" + channel.sampler, sampler).then(function (data) {\n var targetPath;\n var animationType;\n switch (channel.target.path) {\n case \"translation\" /* TRANSLATION */: {\n targetPath = \"position\";\n animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;\n break;\n }\n case \"rotation\" /* ROTATION */: {\n targetPath = \"rotationQuaternion\";\n animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;\n break;\n }\n case \"scale\" /* SCALE */: {\n targetPath = \"scaling\";\n animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;\n break;\n }\n case \"weights\" /* WEIGHTS */: {\n targetPath = \"influence\";\n animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;\n break;\n }\n default: {\n throw new Error(context + \": Invalid target path (\" + channel.target.path + \")\");\n }\n }\n var outputBufferOffset = 0;\n var getNextOutputValue;\n switch (targetPath) {\n case \"position\": {\n getNextOutputValue = function () {\n var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);\n outputBufferOffset += 3;\n return value;\n };\n break;\n }\n case \"rotationQuaternion\": {\n getNextOutputValue = function () {\n var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);\n outputBufferOffset += 4;\n return value;\n };\n break;\n }\n case \"scaling\": {\n getNextOutputValue = function () {\n var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);\n outputBufferOffset += 3;\n return value;\n };\n break;\n }\n case \"influence\": {\n getNextOutputValue = function () {\n var value = new Array(targetNode._numMorphTargets);\n for (var i = 0; i < targetNode._numMorphTargets; i++) {\n value[i] = data.output[outputBufferOffset++];\n }\n return value;\n };\n break;\n }\n }\n var getNextKey;\n switch (data.interpolation) {\n case \"STEP\" /* STEP */: {\n getNextKey = function (frameIndex) { return ({\n frame: data.input[frameIndex],\n value: getNextOutputValue(),\n interpolation: BABYLON.AnimationKeyInterpolation.STEP\n }); };\n break;\n }\n case \"LINEAR\" /* LINEAR */: {\n getNextKey = function (frameIndex) { return ({\n frame: data.input[frameIndex],\n value: getNextOutputValue()\n }); };\n break;\n }\n case \"CUBICSPLINE\" /* CUBICSPLINE */: {\n getNextKey = function (frameIndex) { return ({\n frame: data.input[frameIndex],\n inTangent: getNextOutputValue(),\n value: getNextOutputValue(),\n outTangent: getNextOutputValue()\n }); };\n break;\n }\n }\n var keys = new Array(data.input.length);\n for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {\n keys[frameIndex] = getNextKey(frameIndex);\n }\n if (targetPath === \"influence\") {\n var _loop_1 = function (targetIndex) {\n var animationName = babylonAnimationGroup.name + \"_channel\" + babylonAnimationGroup.targetedAnimations.length;\n var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);\n babylonAnimation.setKeys(keys.map(function (key) { return ({\n frame: key.frame,\n inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,\n value: key.value[targetIndex],\n outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined\n }); }));\n _this._forEachPrimitive(targetNode, function (babylonMesh) {\n var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);\n var babylonAnimationClone = babylonAnimation.clone();\n morphTarget.animations.push(babylonAnimationClone);\n babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);\n });\n };\n for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {\n _loop_1(targetIndex);\n }\n }\n else {\n var animationName = babylonAnimationGroup.name + \"_channel\" + babylonAnimationGroup.targetedAnimations.length;\n var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);\n babylonAnimation.setKeys(keys);\n if (targetNode._babylonBones) {\n var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);\n for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {\n var babylonAnimationTarget = babylonAnimationTargets_1[_i];\n babylonAnimationTarget.animations.push(babylonAnimation);\n }\n babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);\n }\n else {\n targetNode._babylonMesh.animations.push(babylonAnimation);\n babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);\n }\n }\n });\n };\n GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {\n if (sampler._data) {\n return sampler._data;\n }\n var interpolation = sampler.interpolation || \"LINEAR\" /* LINEAR */;\n switch (interpolation) {\n case \"STEP\" /* STEP */:\n case \"LINEAR\" /* LINEAR */:\n case \"CUBICSPLINE\" /* CUBICSPLINE */: {\n break;\n }\n default: {\n throw new Error(context + \": Invalid interpolation (\" + sampler.interpolation + \")\");\n }\n }\n var inputAccessor = GLTFLoader._GetProperty(context + \"/input\", this._gltf.accessors, sampler.input);\n var outputAccessor = GLTFLoader._GetProperty(context + \"/output\", this._gltf.accessors, sampler.output);\n sampler._data = Promise.all([\n this._loadFloatAccessorAsync(\"#/accessors/\" + inputAccessor._index, inputAccessor),\n this._loadFloatAccessorAsync(\"#/accessors/\" + outputAccessor._index, outputAccessor)\n ]).then(function (_a) {\n var inputData = _a[0], outputData = _a[1];\n return {\n input: inputData,\n interpolation: interpolation,\n output: outputData,\n };\n });\n return sampler._data;\n };\n GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {\n if (buffer._data) {\n return buffer._data;\n }\n if (!buffer.uri) {\n throw new Error(context + \": Uri is missing\");\n }\n buffer._data = this._loadUriAsync(context, buffer.uri);\n return buffer._data;\n };\n GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {\n if (bufferView._data) {\n return bufferView._data;\n }\n var buffer = GLTFLoader._GetProperty(context + \"/buffer\", this._gltf.buffers, bufferView.buffer);\n bufferView._data = this._loadBufferAsync(\"#/buffers/\" + buffer._index, buffer).then(function (data) {\n try {\n return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);\n }\n catch (e) {\n throw new Error(context + \": \" + e.message);\n }\n });\n return bufferView._data;\n };\n GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {\n if (accessor.type !== \"SCALAR\" /* SCALAR */) {\n throw new Error(context + \": Invalid type \" + accessor.type);\n }\n if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&\n accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&\n accessor.componentType !== 5125 /* UNSIGNED_INT */) {\n throw new Error(context + \": Invalid component type \" + accessor.componentType);\n }\n if (accessor._data) {\n return accessor._data;\n }\n var bufferView = GLTFLoader._GetProperty(context + \"/bufferView\", this._gltf.bufferViews, accessor.bufferView);\n accessor._data = this._loadBufferViewAsync(\"#/bufferViews/\" + bufferView._index, bufferView).then(function (data) {\n return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);\n });\n return accessor._data;\n };\n GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {\n // TODO: support normalized and stride\n var _this = this;\n if (accessor.componentType !== 5126 /* FLOAT */) {\n throw new Error(\"Invalid component type \" + accessor.componentType);\n }\n if (accessor._data) {\n return accessor._data;\n }\n var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);\n var length = numComponents * accessor.count;\n if (accessor.bufferView == undefined) {\n accessor._data = Promise.resolve(new Float32Array(length));\n }\n else {\n var bufferView = GLTFLoader._GetProperty(context + \"/bufferView\", this._gltf.bufferViews, accessor.bufferView);\n accessor._data = this._loadBufferViewAsync(\"#/bufferViews/\" + bufferView._index, bufferView).then(function (data) {\n return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);\n });\n }\n if (accessor.sparse) {\n var sparse_1 = accessor.sparse;\n accessor._data = accessor._data.then(function (data) {\n var indicesBufferView = GLTFLoader._GetProperty(context + \"/sparse/indices/bufferView\", _this._gltf.bufferViews, sparse_1.indices.bufferView);\n var valuesBufferView = GLTFLoader._GetProperty(context + \"/sparse/values/bufferView\", _this._gltf.bufferViews, sparse_1.values.bufferView);\n return Promise.all([\n _this._loadBufferViewAsync(\"#/bufferViews/\" + indicesBufferView._index, indicesBufferView),\n _this._loadBufferViewAsync(\"#/bufferViews/\" + valuesBufferView._index, valuesBufferView)\n ]).then(function (_a) {\n var indicesData = _a[0], valuesData = _a[1];\n var indices = GLTFLoader._GetTypedArray(context + \"/sparse/indices\", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);\n var values = GLTFLoader._GetTypedArray(context + \"/sparse/values\", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);\n var valuesIndex = 0;\n for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {\n var dataIndex = indices[indicesIndex] * numComponents;\n for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {\n data[dataIndex++] = values[valuesIndex++];\n }\n }\n return data;\n });\n });\n }\n return accessor._data;\n };\n GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {\n var _this = this;\n if (bufferView._babylonBuffer) {\n return bufferView._babylonBuffer;\n }\n bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {\n return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);\n });\n return bufferView._babylonBuffer;\n };\n GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {\n var _this = this;\n if (accessor._babylonVertexBuffer) {\n return accessor._babylonVertexBuffer;\n }\n if (accessor.sparse) {\n accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {\n return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);\n });\n }\n else {\n var bufferView_1 = GLTFLoader._GetProperty(context + \"/bufferView\", this._gltf.bufferViews, accessor.bufferView);\n accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(\"#/bufferViews/\" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {\n var size = GLTFLoader._GetNumComponents(context, accessor.type);\n return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);\n });\n }\n return accessor._babylonVertexBuffer;\n };\n GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {\n var babylonMaterial = this._defaultBabylonMaterials[drawMode];\n if (!babylonMaterial) {\n babylonMaterial = this._createMaterial(\"__gltf_default\", drawMode);\n babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;\n babylonMaterial.metallic = 1;\n babylonMaterial.roughness = 1;\n this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);\n }\n return babylonMaterial;\n };\n GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {\n var promises = new Array();\n // Ensure metallic workflow\n babylonMaterial.metallic = 1;\n babylonMaterial.roughness = 1;\n var properties = material.pbrMetallicRoughness;\n if (properties) {\n if (properties.baseColorFactor) {\n babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);\n babylonMaterial.alpha = properties.baseColorFactor[3];\n }\n else {\n babylonMaterial.albedoColor = BABYLON.Color3.White();\n }\n babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;\n babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;\n if (properties.baseColorTexture) {\n promises.push(this._loadTextureInfoAsync(context + \"/baseColorTexture\", properties.baseColorTexture, function (texture) {\n babylonMaterial.albedoTexture = texture;\n }));\n }\n if (properties.metallicRoughnessTexture) {\n promises.push(this._loadTextureInfoAsync(context + \"/metallicRoughnessTexture\", properties.metallicRoughnessTexture, function (texture) {\n babylonMaterial.metallicTexture = texture;\n }));\n babylonMaterial.useMetallnessFromMetallicTextureBlue = true;\n babylonMaterial.useRoughnessFromMetallicTextureGreen = true;\n babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;\n }\n }\n this._loadMaterialAlphaProperties(context, material, babylonMaterial);\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n material._babylonData = material._babylonData || {};\n var babylonData = material._babylonData[babylonDrawMode];\n if (!babylonData) {\n this._parent._logOpen(context + \" \" + (material.name || \"\"));\n var name_4 = material.name || \"material\" + material._index;\n var babylonMaterial = this._createMaterial(name_4, babylonDrawMode);\n babylonData = {\n material: babylonMaterial,\n meshes: [],\n loaded: this._loadMaterialPropertiesAsync(context, material, babylonMaterial)\n };\n material._babylonData[babylonDrawMode] = babylonData;\n this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);\n this._parent._logClose();\n }\n babylonData.meshes.push(babylonMesh);\n babylonMesh.onDisposeObservable.addOnce(function () {\n var index = babylonData.meshes.indexOf(babylonMesh);\n if (index !== -1) {\n babylonData.meshes.splice(index, 1);\n }\n });\n assign(babylonData.material);\n return babylonData.loaded;\n };\n GLTFLoader.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadMaterialPropertiesAsync(this, context, material, babylonMaterial);\n if (extensionPromise) {\n return extensionPromise;\n }\n var promises = new Array();\n promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._createMaterial = function (name, drawMode) {\n var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);\n babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;\n babylonMaterial.fillMode = drawMode;\n babylonMaterial.enableSpecularAntiAliasing = true;\n babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;\n babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;\n return babylonMaterial;\n };\n GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {\n var promises = new Array();\n babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);\n if (material.doubleSided) {\n babylonMaterial.backFaceCulling = false;\n babylonMaterial.twoSidedLighting = true;\n }\n if (material.normalTexture) {\n promises.push(this._loadTextureInfoAsync(context + \"/normalTexture\", material.normalTexture, function (texture) {\n babylonMaterial.bumpTexture = texture;\n }));\n babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;\n babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;\n if (material.normalTexture.scale != undefined) {\n babylonMaterial.bumpTexture.level = material.normalTexture.scale;\n }\n }\n if (material.occlusionTexture) {\n promises.push(this._loadTextureInfoAsync(context + \"/occlusionTexture\", material.occlusionTexture, function (texture) {\n babylonMaterial.ambientTexture = texture;\n }));\n babylonMaterial.useAmbientInGrayScale = true;\n if (material.occlusionTexture.strength != undefined) {\n babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;\n }\n }\n if (material.emissiveTexture) {\n promises.push(this._loadTextureInfoAsync(context + \"/emissiveTexture\", material.emissiveTexture, function (texture) {\n babylonMaterial.emissiveTexture = texture;\n }));\n }\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {\n var alphaMode = material.alphaMode || \"OPAQUE\" /* OPAQUE */;\n switch (alphaMode) {\n case \"OPAQUE\" /* OPAQUE */: {\n babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;\n break;\n }\n case \"MASK\" /* MASK */: {\n babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;\n babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);\n if (babylonMaterial.albedoTexture) {\n babylonMaterial.albedoTexture.hasAlpha = true;\n }\n break;\n }\n case \"BLEND\" /* BLEND */: {\n babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;\n if (babylonMaterial.albedoTexture) {\n babylonMaterial.albedoTexture.hasAlpha = true;\n babylonMaterial.useAlphaFromAlbedoTexture = true;\n }\n break;\n }\n default: {\n throw new Error(context + \": Invalid alpha mode (\" + material.alphaMode + \")\");\n }\n }\n };\n GLTFLoader.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) {\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadTextureInfoAsync(this, context, textureInfo, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n this._parent._logOpen(\"\" + context);\n var texture = GLTFLoader._GetProperty(context + \"/index\", this._gltf.textures, textureInfo.index);\n var promise = this._loadTextureAsync(\"#/textures/\" + textureInfo.index, texture, function (babylonTexture) {\n babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;\n assign(babylonTexture);\n });\n this._parent._logClose();\n return promise;\n };\n GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {\n var _this = this;\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, texture, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n var promises = new Array();\n this._parent._logOpen(context + \" \" + (texture.name || \"\"));\n var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + \"/sampler\", this._gltf.samplers, texture.sampler));\n var samplerData = this._loadSampler(\"#/samplers/\" + sampler._index, sampler);\n var deferred = new BABYLON.Deferred();\n var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {\n if (!_this._disposed) {\n deferred.resolve();\n }\n }, function (message, exception) {\n if (!_this._disposed) {\n deferred.reject(new Error(context + \": \" + ((exception && exception.message) ? exception.message : message || \"Failed to load texture\")));\n }\n });\n promises.push(deferred.promise);\n babylonTexture.name = texture.name || \"texture\" + texture._index;\n babylonTexture.wrapU = samplerData.wrapU;\n babylonTexture.wrapV = samplerData.wrapV;\n var image = GLTFLoader._GetProperty(context + \"/source\", this._gltf.images, texture.source);\n promises.push(this._loadImageAsync(\"#/images/\" + image._index, image).then(function (data) {\n var dataUrl = \"data:\" + _this._rootUrl + (image.uri || \"image\" + image._index);\n babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));\n }));\n assign(babylonTexture);\n this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);\n this._parent._logClose();\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._loadSampler = function (context, sampler) {\n if (!sampler._data) {\n sampler._data = {\n noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),\n samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),\n wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),\n wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)\n };\n }\n ;\n return sampler._data;\n };\n GLTFLoader.prototype._loadImageAsync = function (context, image) {\n if (!image._data) {\n this._parent._logOpen(context + \" \" + (image.name || \"\"));\n if (image.uri) {\n image._data = this._loadUriAsync(context, image.uri);\n }\n else {\n var bufferView = GLTFLoader._GetProperty(context + \"/bufferView\", this._gltf.bufferViews, image.bufferView);\n image._data = this._loadBufferViewAsync(\"#/bufferViews/\" + bufferView._index, bufferView);\n }\n this._parent._logClose();\n }\n return image._data;\n };\n GLTFLoader.prototype._loadUriAsync = function (context, uri) {\n var _this = this;\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (!GLTFLoader._ValidateUri(uri)) {\n throw new Error(context + \": Uri '\" + uri + \"' is invalid\");\n }\n if (BABYLON.Tools.IsBase64(uri)) {\n var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));\n this._parent._log(\"Decoded \" + uri.substr(0, 64) + \"... (\" + data.length + \" bytes)\");\n return Promise.resolve(data);\n }\n this._parent._log(\"Loading \" + uri);\n return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {\n return new Promise(function (resolve, reject) {\n if (!_this._disposed) {\n var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {\n if (!_this._disposed) {\n var data = new Uint8Array(fileData);\n _this._parent._log(\"Loaded \" + uri + \" (\" + data.length + \" bytes)\");\n resolve(data);\n }\n }, function (event) {\n if (!_this._disposed) {\n if (request_1) {\n request_1._lengthComputable = event.lengthComputable;\n request_1._loaded = event.loaded;\n request_1._total = event.total;\n }\n if (_this._state === BABYLON.GLTFLoaderState.LOADING) {\n try {\n _this._onProgress();\n }\n catch (e) {\n reject(e);\n }\n }\n }\n }, _this._babylonScene.database, true, function (request, exception) {\n if (!_this._disposed) {\n reject(new BABYLON.LoadFileError(context + \": Failed to load '\" + uri + \"'\" + (request ? \": \" + request.status + \" \" + request.statusText : \"\"), request));\n }\n });\n _this._requests.push(request_1);\n }\n });\n });\n };\n GLTFLoader.prototype._onProgress = function () {\n if (!this._progressCallback) {\n return;\n }\n var lengthComputable = true;\n var loaded = 0;\n var total = 0;\n for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {\n var request = _a[_i];\n if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {\n return;\n }\n lengthComputable = lengthComputable && request._lengthComputable;\n loaded += request._loaded;\n total += request._total;\n }\n this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));\n };\n GLTFLoader._GetProperty = function (context, array, index) {\n if (!array || index == undefined || !array[index]) {\n throw new Error(context + \": Failed to find index (\" + index + \")\");\n }\n return array[index];\n };\n GLTFLoader._GetTextureWrapMode = function (context, mode) {\n // Set defaults if undefined\n mode = mode == undefined ? 10497 /* REPEAT */ : mode;\n switch (mode) {\n case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;\n case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;\n case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;\n default:\n BABYLON.Tools.Warn(context + \": Invalid texture wrap mode (\" + mode + \")\");\n return BABYLON.Texture.WRAP_ADDRESSMODE;\n }\n };\n GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {\n // Set defaults if undefined\n magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;\n minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;\n if (magFilter === 9729 /* LINEAR */) {\n switch (minFilter) {\n case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;\n case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;\n case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;\n case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;\n case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;\n case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;\n default:\n BABYLON.Tools.Warn(context + \": Invalid texture minification filter (\" + minFilter + \")\");\n return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;\n }\n }\n else {\n if (magFilter !== 9728 /* NEAREST */) {\n BABYLON.Tools.Warn(context + \": Invalid texture magnification filter (\" + magFilter + \")\");\n }\n switch (minFilter) {\n case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;\n case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;\n case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;\n case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;\n case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;\n case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;\n default:\n BABYLON.Tools.Warn(context + \": Invalid texture minification filter (\" + minFilter + \")\");\n return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;\n }\n }\n };\n GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {\n var buffer = bufferView.buffer;\n byteOffset = bufferView.byteOffset + (byteOffset || 0);\n try {\n switch (componentType) {\n case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);\n case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);\n case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);\n case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);\n case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);\n case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);\n default: throw new Error(\"Invalid component type \" + componentType);\n }\n }\n catch (e) {\n throw new Error(context + \": \" + e);\n }\n };\n GLTFLoader._GetNumComponents = function (context, type) {\n switch (type) {\n case \"SCALAR\": return 1;\n case \"VEC2\": return 2;\n case \"VEC3\": return 3;\n case \"VEC4\": return 4;\n case \"MAT2\": return 4;\n case \"MAT3\": return 9;\n case \"MAT4\": return 16;\n }\n throw new Error(context + \": Invalid type (\" + type + \")\");\n };\n GLTFLoader._ValidateUri = function (uri) {\n return (BABYLON.Tools.IsBase64(uri) || uri.indexOf(\"..\") === -1);\n };\n GLTFLoader._GetDrawMode = function (context, mode) {\n if (mode == undefined) {\n mode = 4 /* TRIANGLES */;\n }\n switch (mode) {\n case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;\n case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;\n case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;\n case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;\n case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;\n case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;\n case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;\n }\n throw new Error(context + \": Invalid mesh primitive mode (\" + mode + \")\");\n };\n GLTFLoader.prototype._compileMaterialsAsync = function () {\n var _this = this;\n this._parent._startPerformanceCounter(\"Compile materials\");\n var promises = new Array();\n if (this._gltf.materials) {\n for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {\n var material = _a[_i];\n if (material._babylonData) {\n for (var babylonDrawMode in material._babylonData) {\n var babylonData = material._babylonData[babylonDrawMode];\n for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {\n var babylonMesh = _c[_b];\n // Ensure nonUniformScaling is set if necessary.\n babylonMesh.computeWorldMatrix(true);\n var babylonMaterial = babylonData.material;\n promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));\n if (this._parent.useClipPlane) {\n promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));\n }\n }\n }\n }\n }\n }\n return Promise.all(promises).then(function () {\n _this._parent._endPerformanceCounter(\"Compile materials\");\n });\n };\n GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {\n var _this = this;\n this._parent._startPerformanceCounter(\"Compile shadow generators\");\n var promises = new Array();\n var lights = this._babylonScene.lights;\n for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {\n var light = lights_1[_i];\n var generator = light.getShadowGenerator();\n if (generator) {\n promises.push(generator.forceCompilationAsync());\n }\n }\n return Promise.all(promises).then(function () {\n _this._parent._endPerformanceCounter(\"Compile shadow generators\");\n });\n };\n GLTFLoader.prototype._applyExtensions = function (actionAsync) {\n for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {\n var name_5 = _a[_i];\n var extension = this._extensions[name_5];\n if (extension.enabled) {\n var promise = actionAsync(extension);\n if (promise) {\n return promise;\n }\n }\n }\n return null;\n };\n GLTFLoader._ExtensionNames = new Array();\n GLTFLoader._ExtensionFactories = {};\n return GLTFLoader;\n }());\n GLTF2.GLTFLoader = GLTFLoader;\n BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFLoader.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n /**\n * Abstract class that can be implemented to extend existing glTF loader behavior.\n */\n var GLTFLoaderExtension = /** @class */ (function () {\n /**\n * Creates new GLTFLoaderExtension\n * @param loader defines the GLTFLoader to use\n */\n function GLTFLoaderExtension(loader) {\n /**\n * Gets or sets a boolean indicating if the extension is enabled\n */\n this.enabled = true;\n this._loader = loader;\n }\n /**\n * Release all resources\n */\n GLTFLoaderExtension.prototype.dispose = function () {\n delete this._loader;\n };\n // #region Overridable Methods\n /**\n * Override this method to modify the default behavior for loading scenes.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };\n /**\n * Override this method to modify the default behavior for loading nodes.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };\n /**\n * Override this method to modify the default behavior for loading mesh primitive vertex data.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };\n /**\n * Override this method to modify the default behavior for loading materials.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };\n /**\n * Override this method to modify the default behavior for loading material properties.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { return null; };\n /**\n * Override this method to modify the default behavior for loading texture infos.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) { return null; };\n /**\n * Override this method to modify the default behavior for loading textures.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadTextureAsync = function (context, texture, assign) { return null; };\n /**\n * Override this method to modify the default behavior for loading uris.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };\n // #endregion\n /**\n * Helper method called by a loader extension to load an glTF extension.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {\n if (!property.extensions) {\n return null;\n }\n var extensions = property.extensions;\n var extension = extensions[this.name];\n if (!extension) {\n return null;\n }\n // Clear out the extension before executing the action to avoid infinite recursion.\n delete extensions[this.name];\n try {\n return actionAsync(context + \"/extensions/\" + this.name, extension);\n }\n finally {\n // Restore the extension after executing the action.\n extensions[this.name] = extension;\n }\n };\n /**\n * Helper method called by the loader to allow extensions to override loading scenes.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {\n if (!property.extras) {\n return null;\n }\n var extras = property.extras;\n var value = extras[this.name];\n if (value === undefined) {\n return null;\n }\n // Clear out the extras value before executing the action to avoid infinite recursion.\n delete extras[this.name];\n try {\n return actionAsync(context + \"/extras/\" + this.name, value);\n }\n finally {\n // Restore the extras value after executing the action.\n extras[this.name] = value;\n }\n };\n /**\n * Helper method called by the loader to allow extensions to override loading scenes.\n * @hidden\n */\n GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {\n return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading nodes.\n * @hidden\n */\n GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {\n return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.\n * @hidden\n */\n GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {\n return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading materials.\n * @hidden\n */\n GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {\n return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading material properties.\n * @hidden\n */\n GLTFLoaderExtension._LoadMaterialPropertiesAsync = function (loader, context, material, babylonMaterial) {\n return loader._applyExtensions(function (extension) { return extension._loadMaterialPropertiesAsync(context, material, babylonMaterial); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading texture infos.\n * @hidden\n */\n GLTFLoaderExtension._LoadTextureInfoAsync = function (loader, context, textureInfo, assign) {\n return loader._applyExtensions(function (extension) { return extension._loadTextureInfoAsync(context, textureInfo, assign); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading textures.\n * @hidden\n */\n GLTFLoaderExtension._LoadTextureAsync = function (loader, context, texture, assign) {\n return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, texture, assign); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading uris.\n * @hidden\n */\n GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {\n return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });\n };\n return GLTFLoaderExtension;\n }());\n GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFLoaderExtension.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"MSFT_lod\";\n /**\n * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)\n */\n var MSFT_lod = /** @class */ (function (_super) {\n __extends(MSFT_lod, _super);\n function MSFT_lod(loader) {\n var _this = _super.call(this, loader) || this;\n _this.name = NAME;\n /**\n * Maximum number of LODs to load, starting from the lowest LOD.\n */\n _this.maxLODsToLoad = Number.MAX_VALUE;\n /**\n * Observable raised when all node LODs of one level are loaded.\n * The event data is the index of the loaded LOD starting from zero.\n * Dispose the loader to cancel the loading of the next level of LODs.\n */\n _this.onNodeLODsLoadedObservable = new BABYLON.Observable();\n /**\n * Observable raised when all material LODs of one level are loaded.\n * The event data is the index of the loaded LOD starting from zero.\n * Dispose the loader to cancel the loading of the next level of LODs.\n */\n _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();\n _this._nodeIndexLOD = null;\n _this._nodeSignalLODs = new Array();\n _this._nodePromiseLODs = new Array();\n _this._materialIndexLOD = null;\n _this._materialSignalLODs = new Array();\n _this._materialPromiseLODs = new Array();\n _this._loader._readyPromise.then(function () {\n var _loop_1 = function (indexLOD) {\n var promise = Promise.all(_this._nodePromiseLODs[indexLOD]).then(function () {\n if (indexLOD !== 0) {\n _this._loader._parent._endPerformanceCounter(\"Node LOD \" + indexLOD);\n }\n _this._loader._parent._log(\"Loaded node LOD \" + indexLOD);\n _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);\n if (indexLOD !== _this._nodePromiseLODs.length - 1) {\n _this._loader._parent._startPerformanceCounter(\"Node LOD \" + (indexLOD + 1));\n _this._nodeSignalLODs[indexLOD].resolve();\n }\n });\n _this._loader._completePromises.push(promise);\n };\n for (var indexLOD = 0; indexLOD < _this._nodePromiseLODs.length; indexLOD++) {\n _loop_1(indexLOD);\n }\n var _loop_2 = function (indexLOD) {\n var promise = Promise.all(_this._materialPromiseLODs[indexLOD]).then(function () {\n if (indexLOD !== 0) {\n _this._loader._parent._endPerformanceCounter(\"Material LOD \" + indexLOD);\n }\n _this._loader._parent._log(\"Loaded material LOD \" + indexLOD);\n _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);\n if (indexLOD !== _this._materialPromiseLODs.length - 1) {\n _this._loader._parent._startPerformanceCounter(\"Material LOD \" + (indexLOD + 1));\n _this._materialSignalLODs[indexLOD].resolve();\n }\n });\n _this._loader._completePromises.push(promise);\n };\n for (var indexLOD = 0; indexLOD < _this._materialPromiseLODs.length; indexLOD++) {\n _loop_2(indexLOD);\n }\n });\n return _this;\n }\n MSFT_lod.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this._nodeIndexLOD = null;\n this._nodeSignalLODs.length = 0;\n this._nodePromiseLODs.length = 0;\n this._materialIndexLOD = null;\n this._materialSignalLODs.length = 0;\n this._materialPromiseLODs.length = 0;\n this.onMaterialLODsLoadedObservable.clear();\n this.onNodeLODsLoadedObservable.clear();\n };\n MSFT_lod.prototype._loadNodeAsync = function (context, node) {\n var _this = this;\n return this._loadExtensionAsync(context, node, function (extensionContext, extension) {\n var firstPromise;\n var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);\n _this._loader._parent._logOpen(\"\" + extensionContext);\n var _loop_3 = function (indexLOD) {\n var nodeLOD = nodeLODs[indexLOD];\n if (indexLOD !== 0) {\n _this._nodeIndexLOD = indexLOD;\n _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();\n }\n var promise = _this._loader._loadNodeAsync(\"#/nodes/\" + nodeLOD._index, nodeLOD).then(function () {\n if (indexLOD !== 0) {\n var previousNodeLOD = nodeLODs[indexLOD - 1];\n if (previousNodeLOD._babylonMesh) {\n previousNodeLOD._babylonMesh.dispose();\n delete previousNodeLOD._babylonMesh;\n _this._disposeUnusedMaterials();\n }\n }\n });\n if (indexLOD === 0) {\n firstPromise = promise;\n }\n else {\n _this._nodeIndexLOD = null;\n }\n _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];\n _this._nodePromiseLODs[indexLOD].push(promise);\n };\n for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {\n _loop_3(indexLOD);\n }\n _this._loader._parent._logClose();\n return firstPromise;\n });\n };\n MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {\n var _this = this;\n // Don't load material LODs if already loading a node LOD.\n if (this._nodeIndexLOD) {\n return null;\n }\n return this._loadExtensionAsync(context, material, function (extensionContext, extension) {\n var firstPromise;\n var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);\n _this._loader._parent._logOpen(\"\" + extensionContext);\n var _loop_4 = function (indexLOD) {\n var materialLOD = materialLODs[indexLOD];\n if (indexLOD !== 0) {\n _this._materialIndexLOD = indexLOD;\n }\n var promise = _this._loader._loadMaterialAsync(\"#/materials/\" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {\n if (indexLOD !== 0) {\n var babylonDataLOD = materialLOD._babylonData;\n assign(babylonDataLOD[babylonDrawMode].material);\n var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;\n if (previousBabylonDataLOD[babylonDrawMode]) {\n previousBabylonDataLOD[babylonDrawMode].material.dispose();\n delete previousBabylonDataLOD[babylonDrawMode];\n }\n }\n });\n if (indexLOD === 0) {\n firstPromise = promise;\n }\n else {\n _this._materialIndexLOD = null;\n }\n _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];\n _this._materialPromiseLODs[indexLOD].push(promise);\n };\n for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {\n _loop_4(indexLOD);\n }\n _this._loader._parent._logClose();\n return firstPromise;\n });\n };\n MSFT_lod.prototype._loadUriAsync = function (context, uri) {\n var _this = this;\n // Defer the loading of uris if loading a material or node LOD.\n if (this._materialIndexLOD !== null) {\n this._loader._parent._log(\"deferred\");\n var previousIndexLOD = this._materialIndexLOD - 1;\n this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();\n return this._materialSignalLODs[previousIndexLOD].promise.then(function () {\n return _this._loader._loadUriAsync(context, uri);\n });\n }\n else if (this._nodeIndexLOD !== null) {\n this._loader._parent._log(\"deferred\");\n var previousIndexLOD = this._nodeIndexLOD - 1;\n this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();\n return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {\n return _this._loader._loadUriAsync(context, uri);\n });\n }\n return null;\n };\n /**\n * Gets an array of LOD properties from lowest to highest.\n */\n MSFT_lod.prototype._getLODs = function (context, property, array, ids) {\n if (this.maxLODsToLoad <= 0) {\n throw new Error(\"maxLODsToLoad must be greater than zero\");\n }\n var properties = new Array();\n for (var i = ids.length - 1; i >= 0; i--) {\n properties.push(GLTF2.GLTFLoader._GetProperty(context + \"/ids/\" + ids[i], array, ids[i]));\n if (properties.length === this.maxLODsToLoad) {\n return properties;\n }\n }\n properties.push(property);\n return properties;\n };\n MSFT_lod.prototype._disposeUnusedMaterials = function () {\n var materials = this._loader._gltf.materials;\n if (materials) {\n for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {\n var material = materials_1[_i];\n if (material._babylonData) {\n for (var drawMode in material._babylonData) {\n var babylonData = material._babylonData[drawMode];\n if (babylonData.meshes.length === 0) {\n babylonData.material.dispose(false, true);\n delete material._babylonData[drawMode];\n }\n }\n }\n }\n }\n };\n return MSFT_lod;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.MSFT_lod = MSFT_lod;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=MSFT_lod.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"MSFT_minecraftMesh\";\n /** @hidden */\n var MSFT_minecraftMesh = /** @class */ (function (_super) {\n __extends(MSFT_minecraftMesh, _super);\n function MSFT_minecraftMesh() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {\n var _this = this;\n return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {\n if (value) {\n return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {\n if (babylonMaterial.needAlphaBlending()) {\n babylonMaterial.forceDepthWrite = true;\n babylonMaterial.separateCullingPass = true;\n }\n babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;\n babylonMaterial.twoSidedLighting = true;\n assign(babylonMaterial);\n });\n }\n return null;\n });\n };\n return MSFT_minecraftMesh;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=MSFT_minecraftMesh.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"MSFT_sRGBFactors\";\n /** @hidden */\n var MSFT_sRGBFactors = /** @class */ (function (_super) {\n __extends(MSFT_sRGBFactors, _super);\n function MSFT_sRGBFactors() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {\n var _this = this;\n return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {\n if (value) {\n return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {\n if (!babylonMaterial.albedoTexture) {\n babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);\n }\n if (!babylonMaterial.reflectivityTexture) {\n babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);\n }\n assign(babylonMaterial);\n });\n }\n return null;\n });\n };\n return MSFT_sRGBFactors;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=MSFT_sRGBFactors.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"KHR_draco_mesh_compression\";\n /**\n * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)\n */\n var KHR_draco_mesh_compression = /** @class */ (function (_super) {\n __extends(KHR_draco_mesh_compression, _super);\n function KHR_draco_mesh_compression(loader) {\n var _this = _super.call(this, loader) || this;\n _this.name = NAME;\n _this._dracoCompression = null;\n // Disable extension if decoder is not available.\n if (!BABYLON.DracoCompression.DecoderAvailable) {\n _this.enabled = false;\n }\n return _this;\n }\n KHR_draco_mesh_compression.prototype.dispose = function () {\n if (this._dracoCompression) {\n this._dracoCompression.dispose();\n }\n _super.prototype.dispose.call(this);\n };\n KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {\n var _this = this;\n return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {\n if (primitive.mode != undefined) {\n if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&\n primitive.mode !== 4 /* TRIANGLES */) {\n throw new Error(context + \": Unsupported mode \" + primitive.mode);\n }\n // TODO: handle triangle strips\n if (primitive.mode === 5 /* TRIANGLE_STRIP */) {\n throw new Error(context + \": Mode \" + primitive.mode + \" is not currently supported\");\n }\n }\n var attributes = {};\n var loadAttribute = function (name, kind) {\n var uniqueId = extension.attributes[name];\n if (uniqueId == undefined) {\n return;\n }\n babylonMesh._delayInfo = babylonMesh._delayInfo || [];\n if (babylonMesh._delayInfo.indexOf(kind) === -1) {\n babylonMesh._delayInfo.push(kind);\n }\n attributes[kind] = uniqueId;\n };\n loadAttribute(\"POSITION\", BABYLON.VertexBuffer.PositionKind);\n loadAttribute(\"NORMAL\", BABYLON.VertexBuffer.NormalKind);\n loadAttribute(\"TANGENT\", BABYLON.VertexBuffer.TangentKind);\n loadAttribute(\"TEXCOORD_0\", BABYLON.VertexBuffer.UVKind);\n loadAttribute(\"TEXCOORD_1\", BABYLON.VertexBuffer.UV2Kind);\n loadAttribute(\"JOINTS_0\", BABYLON.VertexBuffer.MatricesIndicesKind);\n loadAttribute(\"WEIGHTS_0\", BABYLON.VertexBuffer.MatricesWeightsKind);\n loadAttribute(\"COLOR_0\", BABYLON.VertexBuffer.ColorKind);\n var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);\n if (!bufferView._dracoBabylonGeometry) {\n bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync(\"#/bufferViews/\" + bufferView._index, bufferView).then(function (data) {\n if (!_this._dracoCompression) {\n _this._dracoCompression = new BABYLON.DracoCompression();\n }\n return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {\n var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);\n babylonVertexData.applyToGeometry(babylonGeometry);\n return babylonGeometry;\n }).catch(function (error) {\n throw new Error(context + \": \" + error.message);\n });\n });\n }\n return bufferView._dracoBabylonGeometry;\n });\n };\n return KHR_draco_mesh_compression;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=KHR_draco_mesh_compression.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"KHR_materials_pbrSpecularGlossiness\";\n /**\n * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)\n */\n var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {\n __extends(KHR_materials_pbrSpecularGlossiness, _super);\n function KHR_materials_pbrSpecularGlossiness() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {\n var _this = this;\n return this._loadExtensionAsync(context, material, function (extensionContext, extension) {\n var promises = new Array();\n promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));\n return Promise.all(promises).then(function () { });\n });\n };\n KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {\n var promises = new Array();\n if (properties.diffuseFactor) {\n babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);\n babylonMaterial.alpha = properties.diffuseFactor[3];\n }\n else {\n babylonMaterial.albedoColor = BABYLON.Color3.White();\n }\n babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();\n babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;\n if (properties.diffuseTexture) {\n promises.push(this._loader._loadTextureInfoAsync(context + \"/diffuseTexture\", properties.diffuseTexture, function (texture) {\n babylonMaterial.albedoTexture = texture;\n }));\n }\n if (properties.specularGlossinessTexture) {\n promises.push(this._loader._loadTextureInfoAsync(context + \"/specularGlossinessTexture\", properties.specularGlossinessTexture, function (texture) {\n babylonMaterial.reflectivityTexture = texture;\n }));\n babylonMaterial.reflectivityTexture.hasAlpha = true;\n babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;\n }\n this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);\n return Promise.all(promises).then(function () { });\n };\n return KHR_materials_pbrSpecularGlossiness;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"KHR_materials_unlit\";\n /**\n * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)\n */\n var KHR_materials_unlit = /** @class */ (function (_super) {\n __extends(KHR_materials_unlit, _super);\n function KHR_materials_unlit() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n KHR_materials_unlit.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {\n var _this = this;\n return this._loadExtensionAsync(context, material, function () {\n return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);\n });\n };\n KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {\n var promises = new Array();\n babylonMaterial.unlit = true;\n // Ensure metallic workflow\n babylonMaterial.metallic = 1;\n babylonMaterial.roughness = 1;\n var properties = material.pbrMetallicRoughness;\n if (properties) {\n if (properties.baseColorFactor) {\n babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);\n babylonMaterial.alpha = properties.baseColorFactor[3];\n }\n else {\n babylonMaterial.albedoColor = BABYLON.Color3.White();\n }\n if (properties.baseColorTexture) {\n promises.push(this._loader._loadTextureInfoAsync(context + \"/baseColorTexture\", properties.baseColorTexture, function (texture) {\n babylonMaterial.albedoTexture = texture;\n }));\n }\n }\n if (material.doubleSided) {\n babylonMaterial.backFaceCulling = false;\n babylonMaterial.twoSidedLighting = true;\n }\n this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);\n return Promise.all(promises).then(function () { });\n };\n return KHR_materials_unlit;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.KHR_materials_unlit = KHR_materials_unlit;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=KHR_materials_unlit.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"KHR_lights\";\n var LightType;\n (function (LightType) {\n LightType[\"AMBIENT\"] = \"ambient\";\n LightType[\"DIRECTIONAL\"] = \"directional\";\n LightType[\"POINT\"] = \"point\";\n LightType[\"SPOT\"] = \"spot\";\n })(LightType || (LightType = {}));\n /**\n * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)\n */\n var KHR_lights = /** @class */ (function (_super) {\n __extends(KHR_lights, _super);\n function KHR_lights() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n KHR_lights.prototype._loadSceneAsync = function (context, scene) {\n var _this = this;\n return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {\n var promise = _this._loader._loadSceneAsync(extensionContext, scene);\n var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);\n if (light.type !== LightType.AMBIENT) {\n throw new Error(extensionContext + \": Only ambient lights are allowed on a scene\");\n }\n _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();\n return promise;\n });\n };\n KHR_lights.prototype._loadNodeAsync = function (context, node) {\n var _this = this;\n return this._loadExtensionAsync(context, node, function (extensionContext, extension) {\n var promise = _this._loader._loadNodeAsync(extensionContext, node);\n var babylonLight;\n var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);\n var name = node._babylonMesh.name;\n switch (light.type) {\n case LightType.AMBIENT: {\n throw new Error(extensionContext + \": Ambient lights are not allowed on a node\");\n }\n case LightType.DIRECTIONAL: {\n babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);\n break;\n }\n case LightType.POINT: {\n babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);\n break;\n }\n case LightType.SPOT: {\n // TODO: support inner and outer cone angles\n //const innerConeAngle = spotLight.innerConeAngle || 0;\n var outerConeAngle = light.spot && light.spot.outerConeAngle || Math.PI / 4;\n babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);\n break;\n }\n default: {\n throw new Error(extensionContext + \": Invalid light type (\" + light.type + \")\");\n }\n }\n babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();\n babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;\n babylonLight.parent = node._babylonMesh;\n return promise;\n });\n };\n Object.defineProperty(KHR_lights.prototype, \"_lights\", {\n get: function () {\n var extensions = this._loader._gltf.extensions;\n if (!extensions || !extensions[this.name]) {\n throw new Error(\"#/extensions: '\" + this.name + \"' not found\");\n }\n var extension = extensions[this.name];\n return extension.lights;\n },\n enumerable: true,\n configurable: true\n });\n return KHR_lights;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.KHR_lights = KHR_lights;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"KHR_texture_transform\";\n /**\n * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)\n */\n var KHR_texture_transform = /** @class */ (function (_super) {\n __extends(KHR_texture_transform, _super);\n function KHR_texture_transform() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n KHR_texture_transform.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) {\n var _this = this;\n return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {\n return _this._loader._loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {\n if (extension.offset) {\n babylonTexture.uOffset = extension.offset[0];\n babylonTexture.vOffset = extension.offset[1];\n }\n // Always rotate around the origin.\n babylonTexture.uRotationCenter = 0;\n babylonTexture.vRotationCenter = 0;\n if (extension.rotation) {\n babylonTexture.wAng = -extension.rotation;\n }\n if (extension.scale) {\n babylonTexture.uScale = extension.scale[0];\n babylonTexture.vScale = extension.scale[1];\n }\n if (extension.texCoord != undefined) {\n babylonTexture.coordinatesIndex = extension.texCoord;\n }\n assign(babylonTexture);\n });\n });\n };\n return KHR_texture_transform;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.KHR_texture_transform = KHR_texture_transform;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"EXT_lights_imageBased\";\n /**\n * [Specification](TODO) (Experimental)\n */\n var EXT_lights_imageBased = /** @class */ (function (_super) {\n __extends(EXT_lights_imageBased, _super);\n function EXT_lights_imageBased() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n EXT_lights_imageBased.prototype._loadSceneAsync = function (context, scene) {\n var _this = this;\n return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {\n var promises = new Array();\n promises.push(_this._loader._loadSceneAsync(context, scene));\n _this._loader._parent._logOpen(\"\" + extensionContext);\n var light = GLTF2.GLTFLoader._GetProperty(extensionContext + \"/light\", _this._lights, extension.light);\n promises.push(_this._loadLightAsync(\"#/extensions/\" + _this.name + \"/lights/\" + extension.light, light).then(function (texture) {\n _this._loader._babylonScene.environmentTexture = texture;\n }));\n _this._loader._parent._logClose();\n return Promise.all(promises).then(function () { });\n });\n };\n EXT_lights_imageBased.prototype._loadLightAsync = function (context, light) {\n var _this = this;\n if (!light._loaded) {\n var promises = new Array();\n this._loader._parent._logOpen(\"\" + context);\n var imageData_1 = new Array(light.specularImages.length);\n var _loop_1 = function (mipmap) {\n var faces = light.specularImages[mipmap];\n imageData_1[mipmap] = new Array(faces.length);\n var _loop_2 = function (face) {\n var specularImageContext = context + \"/specularImages/\" + mipmap + \"/\" + face;\n this_1._loader._parent._logOpen(\"\" + specularImageContext);\n var index = faces[face];\n var image = GLTF2.GLTFLoader._GetProperty(specularImageContext, this_1._loader._gltf.images, index);\n promises.push(this_1._loader._loadImageAsync(\"#/images/\" + index, image).then(function (data) {\n imageData_1[mipmap][face] = data;\n }));\n this_1._loader._parent._logClose();\n };\n for (var face = 0; face < faces.length; face++) {\n _loop_2(face);\n }\n };\n var this_1 = this;\n for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {\n _loop_1(mipmap);\n }\n this._loader._parent._logClose();\n light._loaded = Promise.all(promises).then(function () {\n var babylonTexture = new BABYLON.RawCubeTexture(_this._loader._babylonScene, null, light.specularImageSize);\n light._babylonTexture = babylonTexture;\n if (light.intensity != undefined) {\n babylonTexture.level = light.intensity;\n }\n if (light.rotation) {\n var rotation = BABYLON.Quaternion.FromArray(light.rotation);\n // Invert the rotation so that positive rotation is counter-clockwise.\n if (!_this._loader._babylonScene.useRightHandedSystem) {\n rotation = BABYLON.Quaternion.Inverse(rotation);\n }\n BABYLON.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());\n }\n var sphericalHarmonics = BABYLON.SphericalHarmonics.FromArray(light.irradianceCoefficients);\n sphericalHarmonics.scale(light.intensity);\n sphericalHarmonics.convertIrradianceToLambertianRadiance();\n var sphericalPolynomial = BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);\n // Compute the lod generation scale to fit exactly to the number of levels available.\n var lodGenerationScale = (imageData_1.length - 1) / BABYLON.Scalar.Log2(light.specularImageSize);\n return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);\n });\n }\n return light._loaded.then(function () {\n return light._babylonTexture;\n });\n };\n Object.defineProperty(EXT_lights_imageBased.prototype, \"_lights\", {\n get: function () {\n var extensions = this._loader._gltf.extensions;\n if (!extensions || !extensions[this.name]) {\n throw new Error(\"#/extensions: '\" + this.name + \"' not found\");\n }\n var extension = extensions[this.name];\n return extension.lights;\n },\n enumerable: true,\n configurable: true\n });\n return EXT_lights_imageBased;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.EXT_lights_imageBased = EXT_lights_imageBased;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new EXT_lights_imageBased(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n \n\n return BABYLON;\n});\n\n\n//# sourceURL=webpack://BabylonViewer/../dist/preview_release/loaders/babylonjs.loaders.js?"); +eval("\n\n(function universalModuleDefinition(root, factory) {\n var amdDependencies = [];\n var BABYLON = root.BABYLON || this.BABYLON;\n if(true) {\n BABYLON = BABYLON || __webpack_require__(/*! babylonjs */ \"../dist/preview release/babylon.max.js\"); \n\n module.exports = factory(BABYLON);\n } else {}\n})(this, function(BABYLON) {\n BABYLON = BABYLON || this.BABYLON;\n\nvar __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if(\"object\"==typeof Reflect&&\"function\"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};\nvar __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();\n\nvar BABYLON;\n(function (BABYLON) {\n var STLFileLoader = /** @class */ (function () {\n function STLFileLoader() {\n this.solidPattern = /solid (\\S*)([\\S\\s]*)endsolid[ ]*(\\S*)/g;\n this.facetsPattern = /facet([\\s\\S]*?)endfacet/g;\n this.normalPattern = /normal[\\s]+([\\-+]?[0-9]+\\.?[0-9]*([eE][\\-+]?[0-9]+)?)+[\\s]+([\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?)+[\\s]+([\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?)+/g;\n this.vertexPattern = /vertex[\\s]+([\\-+]?[0-9]+\\.?[0-9]*([eE][\\-+]?[0-9]+)?)+[\\s]+([\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?)+[\\s]+([\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?)+/g;\n this.name = \"stl\";\n // force data to come in as an ArrayBuffer\n // we'll convert to string if it looks like it's an ASCII .stl\n this.extensions = {\n \".stl\": { isBinary: true },\n };\n }\n STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {\n var matches;\n if (typeof data !== \"string\") {\n if (this.isBinary(data)) {\n // binary .stl\n var babylonMesh = new BABYLON.Mesh(\"stlmesh\", scene);\n this.parseBinary(babylonMesh, data);\n if (meshes) {\n meshes.push(babylonMesh);\n }\n return true;\n }\n // ASCII .stl\n // convert to string\n var array_buffer = new Uint8Array(data);\n var str = '';\n for (var i = 0; i < data.byteLength; i++) {\n str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian\n }\n data = str;\n }\n //if arrived here, data is a string, containing the STLA data.\n while (matches = this.solidPattern.exec(data)) {\n var meshName = matches[1];\n var meshNameFromEnd = matches[3];\n if (meshName != meshNameFromEnd) {\n BABYLON.Tools.Error(\"Error in STL, solid name != endsolid name\");\n return false;\n }\n // check meshesNames\n if (meshesNames && meshName) {\n if (meshesNames instanceof Array) {\n if (!meshesNames.indexOf(meshName)) {\n continue;\n }\n }\n else {\n if (meshName !== meshesNames) {\n continue;\n }\n }\n }\n // stl mesh name can be empty as well\n meshName = meshName || \"stlmesh\";\n var babylonMesh = new BABYLON.Mesh(meshName, scene);\n this.parseASCII(babylonMesh, matches[2]);\n if (meshes) {\n meshes.push(babylonMesh);\n }\n }\n return true;\n };\n STLFileLoader.prototype.load = function (scene, data, rootUrl) {\n var result = this.importMesh(null, scene, data, rootUrl, null, null, null);\n if (result) {\n scene.createDefaultCameraOrLight();\n }\n return result;\n };\n STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {\n var container = new BABYLON.AssetContainer(scene);\n this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);\n container.removeAllFromScene();\n return container;\n };\n STLFileLoader.prototype.isBinary = function (data) {\n // check if file size is correct for binary stl\n var faceSize, nFaces, reader;\n reader = new DataView(data);\n faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);\n nFaces = reader.getUint32(80, true);\n if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {\n return true;\n }\n // check characters higher than ASCII to confirm binary\n var fileLength = reader.byteLength;\n for (var index = 0; index < fileLength; index++) {\n if (reader.getUint8(index) > 127) {\n return true;\n }\n }\n return false;\n };\n STLFileLoader.prototype.parseBinary = function (mesh, data) {\n var reader = new DataView(data);\n var faces = reader.getUint32(80, true);\n var dataOffset = 84;\n var faceLength = 12 * 4 + 2;\n var offset = 0;\n var positions = new Float32Array(faces * 3 * 3);\n var normals = new Float32Array(faces * 3 * 3);\n var indices = new Uint32Array(faces * 3);\n var indicesCount = 0;\n for (var face = 0; face < faces; face++) {\n var start = dataOffset + face * faceLength;\n var normalX = reader.getFloat32(start, true);\n var normalY = reader.getFloat32(start + 4, true);\n var normalZ = reader.getFloat32(start + 8, true);\n for (var i = 1; i <= 3; i++) {\n var vertexstart = start + i * 12;\n // ordering is intentional to match ascii import\n positions[offset] = reader.getFloat32(vertexstart, true);\n positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);\n positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);\n normals[offset] = normalX;\n normals[offset + 2] = normalY;\n normals[offset + 1] = normalZ;\n offset += 3;\n }\n indices[indicesCount] = indicesCount++;\n indices[indicesCount] = indicesCount++;\n indices[indicesCount] = indicesCount++;\n }\n mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);\n mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);\n mesh.setIndices(indices);\n mesh.computeWorldMatrix(true);\n };\n STLFileLoader.prototype.parseASCII = function (mesh, solidData) {\n var positions = [];\n var normals = [];\n var indices = [];\n var indicesCount = 0;\n //load facets, ignoring loop as the standard doesn't define it can contain more than vertices\n var matches;\n while (matches = this.facetsPattern.exec(solidData)) {\n var facet = matches[1];\n //one normal per face\n var normalMatches = this.normalPattern.exec(facet);\n this.normalPattern.lastIndex = 0;\n if (!normalMatches) {\n continue;\n }\n var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];\n var vertexMatch;\n while (vertexMatch = this.vertexPattern.exec(facet)) {\n positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));\n normals.push(normal[0], normal[1], normal[2]);\n }\n indices.push(indicesCount++, indicesCount++, indicesCount++);\n this.vertexPattern.lastIndex = 0;\n }\n this.facetsPattern.lastIndex = 0;\n mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);\n mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);\n mesh.setIndices(indices);\n mesh.computeWorldMatrix(true);\n };\n return STLFileLoader;\n }());\n BABYLON.STLFileLoader = STLFileLoader;\n if (BABYLON.SceneLoader) {\n BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());\n }\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.stlFileLoader.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Class reading and parsing the MTL file bundled with the obj file.\n */\n var MTLFileLoader = /** @class */ (function () {\n function MTLFileLoader() {\n // All material loaded from the mtl will be set here\n this.materials = [];\n }\n /**\n * This function will read the mtl file and create each material described inside\n * This function could be improve by adding :\n * -some component missing (Ni, Tf...)\n * -including the specific options available\n *\n * @param scene\n * @param data\n * @param rootUrl\n */\n MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {\n if (data instanceof ArrayBuffer) {\n return;\n }\n //Split the lines from the file\n var lines = data.split('\\n');\n //Space char\n var delimiter_pattern = /\\s+/;\n //Array with RGB colors\n var color;\n //New material\n var material = null;\n //Look at each line\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i].trim();\n // Blank line or comment\n if (line.length === 0 || line.charAt(0) === '#') {\n continue;\n }\n //Get the first parameter (keyword)\n var pos = line.indexOf(' ');\n var key = (pos >= 0) ? line.substring(0, pos) : line;\n key = key.toLowerCase();\n //Get the data following the key\n var value = (pos >= 0) ? line.substring(pos + 1).trim() : \"\";\n //This mtl keyword will create the new material\n if (key === \"newmtl\") {\n //Check if it is the first material.\n // Materials specifications are described after this keyword.\n if (material) {\n //Add the previous material in the material array.\n this.materials.push(material);\n }\n //Create a new material.\n // value is the name of the material read in the mtl file\n material = new BABYLON.StandardMaterial(value, scene);\n }\n else if (key === \"kd\" && material) {\n // Diffuse color (color under white light) using RGB values\n //value = \"r g b\"\n color = value.split(delimiter_pattern, 3).map(parseFloat);\n //color = [r,g,b]\n //Set tghe color into the material\n material.diffuseColor = BABYLON.Color3.FromArray(color);\n }\n else if (key === \"ka\" && material) {\n // Ambient color (color under shadow) using RGB values\n //value = \"r g b\"\n color = value.split(delimiter_pattern, 3).map(parseFloat);\n //color = [r,g,b]\n //Set tghe color into the material\n material.ambientColor = BABYLON.Color3.FromArray(color);\n }\n else if (key === \"ks\" && material) {\n // Specular color (color when light is reflected from shiny surface) using RGB values\n //value = \"r g b\"\n color = value.split(delimiter_pattern, 3).map(parseFloat);\n //color = [r,g,b]\n //Set the color into the material\n material.specularColor = BABYLON.Color3.FromArray(color);\n }\n else if (key === \"ke\" && material) {\n // Emissive color using RGB values\n color = value.split(delimiter_pattern, 3).map(parseFloat);\n material.emissiveColor = BABYLON.Color3.FromArray(color);\n }\n else if (key === \"ns\" && material) {\n //value = \"Integer\"\n material.specularPower = parseFloat(value);\n }\n else if (key === \"d\" && material) {\n //d is dissolve for current material. It mean alpha for BABYLON\n material.alpha = parseFloat(value);\n //Texture\n //This part can be improved by adding the possible options of texture\n }\n else if (key === \"map_ka\" && material) {\n // ambient texture map with a loaded image\n //We must first get the folder of the image\n material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);\n }\n else if (key === \"map_kd\" && material) {\n // Diffuse texture map with a loaded image\n material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);\n }\n else if (key === \"map_ks\" && material) {\n // Specular texture map with a loaded image\n //We must first get the folder of the image\n material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);\n }\n else if (key === \"map_ns\") {\n //Specular\n //Specular highlight component\n //We must first get the folder of the image\n //\n //Not supported by BABYLON\n //\n // continue;\n }\n else if (key === \"map_bump\" && material) {\n //The bump texture\n material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);\n }\n else if (key === \"map_d\" && material) {\n // The dissolve of the material\n material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);\n //Options for illumination\n }\n else if (key === \"illum\") {\n //Illumination\n if (value === \"0\") {\n //That mean Kd == Kd\n }\n else if (value === \"1\") {\n //Color on and Ambient on\n }\n else if (value === \"2\") {\n //Highlight on\n }\n else if (value === \"3\") {\n //Reflection on and Ray trace on\n }\n else if (value === \"4\") {\n //Transparency: Glass on, Reflection: Ray trace on\n }\n else if (value === \"5\") {\n //Reflection: Fresnel on and Ray trace on\n }\n else if (value === \"6\") {\n //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on\n }\n else if (value === \"7\") {\n //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on\n }\n else if (value === \"8\") {\n //Reflection on and Ray trace off\n }\n else if (value === \"9\") {\n //Transparency: Glass on, Reflection: Ray trace off\n }\n else if (value === \"10\") {\n //Casts shadows onto invisible surfaces\n }\n }\n else {\n // console.log(\"Unhandled expression at line : \" + i +'\\n' + \"with value : \" + line);\n }\n }\n //At the end of the file, add the last material\n if (material) {\n this.materials.push(material);\n }\n };\n /**\n * Gets the texture for the material.\n *\n * If the material is imported from input file,\n * We sanitize the url to ensure it takes the textre from aside the material.\n *\n * @param rootUrl The root url to load from\n * @param value The value stored in the mtl\n * @return The Texture\n */\n MTLFileLoader._getTexture = function (rootUrl, value, scene) {\n if (!value) {\n return null;\n }\n var url = rootUrl;\n // Load from input file.\n if (rootUrl === \"file:\") {\n var lastDelimiter = value.lastIndexOf(\"\\\\\");\n if (lastDelimiter === -1) {\n lastDelimiter = value.lastIndexOf(\"/\");\n }\n if (lastDelimiter > -1) {\n url += value.substr(lastDelimiter + 1);\n }\n else {\n url += value;\n }\n }\n // Not from input file.\n else {\n url += value;\n }\n return new BABYLON.Texture(url, scene);\n };\n return MTLFileLoader;\n }());\n BABYLON.MTLFileLoader = MTLFileLoader;\n var OBJFileLoader = /** @class */ (function () {\n function OBJFileLoader() {\n this.name = \"obj\";\n this.extensions = \".obj\";\n this.obj = /^o/;\n this.group = /^g/;\n this.mtllib = /^mtllib /;\n this.usemtl = /^usemtl /;\n this.smooth = /^s /;\n this.vertexPattern = /v( +[\\d|\\.|\\+|\\-|e|E]+)( +[\\d|\\.|\\+|\\-|e|E]+)( +[\\d|\\.|\\+|\\-|e|E]+)/;\n // vn float float float\n this.normalPattern = /vn( +[\\d|\\.|\\+|\\-|e|E]+)( +[\\d|\\.|\\+|\\-|e|E]+)( +[\\d|\\.|\\+|\\-|e|E]+)/;\n // vt float float\n this.uvPattern = /vt( +[\\d|\\.|\\+|\\-|e|E]+)( +[\\d|\\.|\\+|\\-|e|E]+)/;\n // f vertex vertex vertex ...\n this.facePattern1 = /f\\s+(([\\d]{1,}[\\s]?){3,})+/;\n // f vertex/uvs vertex/uvs vertex/uvs ...\n this.facePattern2 = /f\\s+((([\\d]{1,}\\/[\\d]{1,}[\\s]?){3,})+)/;\n // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...\n this.facePattern3 = /f\\s+((([\\d]{1,}\\/[\\d]{1,}\\/[\\d]{1,}[\\s]?){3,})+)/;\n // f vertex//normal vertex//normal vertex//normal ...\n this.facePattern4 = /f\\s+((([\\d]{1,}\\/\\/[\\d]{1,}[\\s]?){3,})+)/;\n // f -vertex/-uvs/-normal -vertex/-uvs/-normal -vertex/-uvs/-normal ...\n this.facePattern5 = /f\\s+(((-[\\d]{1,}\\/-[\\d]{1,}\\/-[\\d]{1,}[\\s]?){3,})+)/;\n }\n /**\n * Calls synchronously the MTL file attached to this obj.\n * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.\n * Without this function materials are not displayed in the first frame (but displayed after).\n * In consequence it is impossible to get material information in your HTML file\n *\n * @param url The URL of the MTL file\n * @param rootUrl\n * @param onSuccess Callback function to be called when the MTL file is loaded\n * @private\n */\n OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {\n //The complete path to the mtl file\n var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;\n // Loads through the babylon tools to allow fileInput search.\n BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn(\"Error - Unable to load \" + pathOfFile); });\n };\n OBJFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {\n //get the meshes from OBJ file\n return this._parseSolid(meshesNames, scene, data, rootUrl).then(function (meshes) {\n return {\n meshes: meshes,\n particleSystems: [],\n skeletons: [],\n animationGroups: []\n };\n });\n };\n OBJFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {\n //Get the 3D model\n return this.importMeshAsync(null, scene, data, rootUrl, onProgress).then(function () {\n // return void\n });\n };\n OBJFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {\n return this.importMeshAsync(null, scene, data, rootUrl).then(function (result) {\n var container = new BABYLON.AssetContainer(scene);\n result.meshes.forEach(function (mesh) { return container.meshes.push(mesh); });\n container.removeAllFromScene();\n return container;\n });\n };\n /**\n * Read the OBJ file and create an Array of meshes.\n * Each mesh contains all information given by the OBJ and the MTL file.\n * i.e. vertices positions and indices, optional normals values, optional UV values, optional material\n *\n * @param meshesNames\n * @param scene BABYLON.Scene The scene where are displayed the data\n * @param data String The content of the obj file\n * @param rootUrl String The path to the folder\n * @returns Array\n * @private\n */\n OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {\n var _this = this;\n var positions = []; //values for the positions of vertices\n var normals = []; //Values for the normals\n var uvs = []; //Values for the textures\n var meshesFromObj = []; //[mesh] Contains all the obj meshes\n var handledMesh; //The current mesh of meshes array\n var indicesForBabylon = []; //The list of indices for VertexData\n var wrappedPositionForBabylon = []; //The list of position in vectors\n var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices\n var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices\n var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]\n var curPositionInIndices = 0;\n var hasMeshes = false; //Meshes are defined in the file\n var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]\n var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]\n var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]\n var triangles = []; //Indices from new triangles coming from polygons\n var materialNameFromObj = \"\"; //The name of the current material\n var fileToLoad = \"\"; //The name of the mtlFile to load\n var materialsFromMTLFile = new MTLFileLoader();\n var objMeshName = \"\"; //The name of the current obj mesh\n var increment = 1; //Id for meshes created by the multimaterial\n var isFirstMaterial = true;\n /**\n * Search for obj in the given array.\n * This function is called to check if a couple of data already exists in an array.\n *\n * If found, returns the index of the founded tuple index. Returns -1 if not found\n * @param arr Array<{ normals: Array, idx: Array }>\n * @param obj Array\n * @returns {boolean}\n */\n var isInArray = function (arr, obj) {\n if (!arr[obj[0]])\n arr[obj[0]] = { normals: [], idx: [] };\n var idx = arr[obj[0]].normals.indexOf(obj[1]);\n return idx === -1 ? -1 : arr[obj[0]].idx[idx];\n };\n var isInArrayUV = function (arr, obj) {\n if (!arr[obj[0]])\n arr[obj[0]] = { normals: [], idx: [], uv: [] };\n var idx = arr[obj[0]].normals.indexOf(obj[1]);\n if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {\n return arr[obj[0]].idx[idx];\n }\n return -1;\n };\n /**\n * This function set the data for each triangle.\n * Data are position, normals and uvs\n * If a tuple of (position, normal) is not set, add the data into the corresponding array\n * If the tuple already exist, add only their indice\n *\n * @param indicePositionFromObj Integer The index in positions array\n * @param indiceUvsFromObj Integer The index in uvs array\n * @param indiceNormalFromObj Integer The index in normals array\n * @param positionVectorFromOBJ Vector3 The value of position at index objIndice\n * @param textureVectorFromOBJ Vector3 The value of uvs\n * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale\n */\n var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {\n //Check if this tuple already exists in the list of tuples\n var _index;\n if (OBJFileLoader.OPTIMIZE_WITH_UV) {\n _index = isInArrayUV(tuplePosNorm, [\n indicePositionFromObj,\n indiceNormalFromObj,\n indiceUvsFromObj\n ]);\n }\n else {\n _index = isInArray(tuplePosNorm, [\n indicePositionFromObj,\n indiceNormalFromObj\n ]);\n }\n //If it not exists\n if (_index == -1) {\n //Add an new indice.\n //The array of indices is only an array with his length equal to the number of triangles - 1.\n //We add vertices data in this order\n indicesForBabylon.push(wrappedPositionForBabylon.length);\n //Push the position of vertice for Babylon\n //Each element is a BABYLON.Vector3(x,y,z)\n wrappedPositionForBabylon.push(positionVectorFromOBJ);\n //Push the uvs for Babylon\n //Each element is a BABYLON.Vector3(u,v)\n wrappedUvsForBabylon.push(textureVectorFromOBJ);\n //Push the normals for Babylon\n //Each element is a BABYLON.Vector3(x,y,z)\n wrappedNormalsForBabylon.push(normalsVectorFromOBJ);\n //Add the tuple in the comparison list\n tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);\n tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);\n if (OBJFileLoader.OPTIMIZE_WITH_UV)\n tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);\n }\n else {\n //The tuple already exists\n //Add the index of the already existing tuple\n //At this index we can get the value of position, normal and uvs of vertex\n indicesForBabylon.push(_index);\n }\n };\n /**\n * Transform BABYLON.Vector() object onto 3 digits in an array\n */\n var unwrapData = function () {\n //Every array has the same length\n for (var l = 0; l < wrappedPositionForBabylon.length; l++) {\n //Push the x, y, z values of each element in the unwrapped array\n unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);\n unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);\n unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON\n }\n // Reset arrays for the next new meshes\n wrappedPositionForBabylon = [];\n wrappedNormalsForBabylon = [];\n wrappedUvsForBabylon = [];\n tuplePosNorm = [];\n curPositionInIndices = 0;\n };\n /**\n * Create triangles from polygons by recursion\n * The best to understand how it works is to draw it in the same time you get the recursion.\n * It is important to notice that a triangle is a polygon\n * We get 5 patterns of face defined in OBJ File :\n * facePattern1 = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"]\n * facePattern2 = [\"1/1\",\"2/2\",\"3/3\",\"4/4\",\"5/5\",\"6/6\"]\n * facePattern3 = [\"1/1/1\",\"2/2/2\",\"3/3/3\",\"4/4/4\",\"5/5/5\",\"6/6/6\"]\n * facePattern4 = [\"1//1\",\"2//2\",\"3//3\",\"4//4\",\"5//5\",\"6//6\"]\n * facePattern5 = [\"-1/-1/-1\",\"-2/-2/-2\",\"-3/-3/-3\",\"-4/-4/-4\",\"-5/-5/-5\",\"-6/-6/-6\"]\n * Each pattern is divided by the same method\n * @param face Array[String] The indices of elements\n * @param v Integer The variable to increment\n */\n var getTriangles = function (face, v) {\n //Work for each element of the array\n if (v + 1 < face.length) {\n //Add on the triangle variable the indexes to obtain triangles\n triangles.push(face[0], face[v], face[v + 1]);\n //Incrementation for recursion\n v += 1;\n //Recursion\n getTriangles(face, v);\n }\n //Result obtained after 2 iterations:\n //Pattern1 => triangle = [\"1\",\"2\",\"3\",\"1\",\"3\",\"4\"];\n //Pattern2 => triangle = [\"1/1\",\"2/2\",\"3/3\",\"1/1\",\"3/3\",\"4/4\"];\n //Pattern3 => triangle = [\"1/1/1\",\"2/2/2\",\"3/3/3\",\"1/1/1\",\"3/3/3\",\"4/4/4\"];\n //Pattern4 => triangle = [\"1//1\",\"2//2\",\"3//3\",\"1//1\",\"3//3\",\"4//4\"];\n //Pattern5 => triangle = [\"-1/-1/-1\",\"-2/-2/-2\",\"-3/-3/-3\",\"-1/-1/-1\",\"-3/-3/-3\",\"-4/-4/-4\"];\n };\n /**\n * Create triangles and push the data for each polygon for the pattern 1\n * In this pattern we get vertice positions\n * @param face\n * @param v\n */\n var setDataForCurrentFaceWithPattern1 = function (face, v) {\n //Get the indices of triangles for each polygon\n getTriangles(face, v);\n //For each element in the triangles array.\n //This var could contains 1 to an infinity of triangles\n for (var k = 0; k < triangles.length; k++) {\n // Set position indice\n var indicePositionFromObj = parseInt(triangles[k]) - 1;\n setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined\n positions[indicePositionFromObj], //Get the vectors data\n BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors\n );\n }\n //Reset variable for the next line\n triangles = [];\n };\n /**\n * Create triangles and push the data for each polygon for the pattern 2\n * In this pattern we get vertice positions and uvsu\n * @param face\n * @param v\n */\n var setDataForCurrentFaceWithPattern2 = function (face, v) {\n //Get the indices of triangles for each polygon\n getTriangles(face, v);\n for (var k = 0; k < triangles.length; k++) {\n //triangle[k] = \"1/1\"\n //Split the data for getting position and uv\n var point = triangles[k].split(\"/\"); // [\"1\", \"1\"]\n //Set position indice\n var indicePositionFromObj = parseInt(point[0]) - 1;\n //Set uv indice\n var indiceUvsFromObj = parseInt(point[1]) - 1;\n setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals\n positions[indicePositionFromObj], //Get the values for each element\n uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals\n );\n }\n //Reset variable for the next line\n triangles = [];\n };\n /**\n * Create triangles and push the data for each polygon for the pattern 3\n * In this pattern we get vertice positions, uvs and normals\n * @param face\n * @param v\n */\n var setDataForCurrentFaceWithPattern3 = function (face, v) {\n //Get the indices of triangles for each polygon\n getTriangles(face, v);\n for (var k = 0; k < triangles.length; k++) {\n //triangle[k] = \"1/1/1\"\n //Split the data for getting position, uv, and normals\n var point = triangles[k].split(\"/\"); // [\"1\", \"1\", \"1\"]\n // Set position indice\n var indicePositionFromObj = parseInt(point[0]) - 1;\n // Set uv indice\n var indiceUvsFromObj = parseInt(point[1]) - 1;\n // Set normal indice\n var indiceNormalFromObj = parseInt(point[2]) - 1;\n setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component\n );\n }\n //Reset variable for the next line\n triangles = [];\n };\n /**\n * Create triangles and push the data for each polygon for the pattern 4\n * In this pattern we get vertice positions and normals\n * @param face\n * @param v\n */\n var setDataForCurrentFaceWithPattern4 = function (face, v) {\n getTriangles(face, v);\n for (var k = 0; k < triangles.length; k++) {\n //triangle[k] = \"1//1\"\n //Split the data for getting position and normals\n var point = triangles[k].split(\"//\"); // [\"1\", \"1\"]\n // We check indices, and normals\n var indicePositionFromObj = parseInt(point[0]) - 1;\n var indiceNormalFromObj = parseInt(point[1]) - 1;\n setData(indicePositionFromObj, 1, //Default value for uv\n indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data\n BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);\n }\n //Reset variable for the next line\n triangles = [];\n };\n /**\n * Create triangles and push the data for each polygon for the pattern 3\n * In this pattern we get vertice positions, uvs and normals\n * @param face\n * @param v\n */\n var setDataForCurrentFaceWithPattern5 = function (face, v) {\n //Get the indices of triangles for each polygon\n getTriangles(face, v);\n for (var k = 0; k < triangles.length; k++) {\n //triangle[k] = \"-1/-1/-1\"\n //Split the data for getting position, uv, and normals\n var point = triangles[k].split(\"/\"); // [\"-1\", \"-1\", \"-1\"]\n // Set position indice\n var indicePositionFromObj = positions.length + parseInt(point[0]);\n // Set uv indice\n var indiceUvsFromObj = uvs.length + parseInt(point[1]);\n // Set normal indice\n var indiceNormalFromObj = normals.length + parseInt(point[2]);\n setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component\n );\n }\n //Reset variable for the next line\n triangles = [];\n };\n var addPreviousObjMesh = function () {\n //Check if it is not the first mesh. Otherwise we don't have data.\n if (meshesFromObj.length > 0) {\n //Get the previous mesh for applying the data about the faces\n //=> in obj file, faces definition append after the name of the mesh\n handledMesh = meshesFromObj[meshesFromObj.length - 1];\n //Set the data into Array for the mesh\n unwrapData();\n // Reverse tab. Otherwise face are displayed in the wrong sens\n indicesForBabylon.reverse();\n //Set the information for the mesh\n //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited\n handledMesh.indices = indicesForBabylon.slice();\n handledMesh.positions = unwrappedPositionsForBabylon.slice();\n handledMesh.normals = unwrappedNormalsForBabylon.slice();\n handledMesh.uvs = unwrappedUVForBabylon.slice();\n //Reset the array for the next mesh\n indicesForBabylon = [];\n unwrappedPositionsForBabylon = [];\n unwrappedNormalsForBabylon = [];\n unwrappedUVForBabylon = [];\n }\n };\n //Main function\n //Split the file into lines\n var lines = data.split('\\n');\n //Look at each line\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i].trim();\n var result;\n //Comment or newLine\n if (line.length === 0 || line.charAt(0) === '#') {\n continue;\n //Get information about one position possible for the vertices\n }\n else if ((result = this.vertexPattern.exec(line)) !== null) {\n //Create a Vector3 with the position x, y, z\n //Value of result:\n // [\"v 1.0 2.0 3.0\", \"1.0\", \"2.0\", \"3.0\"]\n //Add the Vector in the list of positions\n positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));\n }\n else if ((result = this.normalPattern.exec(line)) !== null) {\n //Create a Vector3 with the normals x, y, z\n //Value of result\n // [\"vn 1.0 2.0 3.0\", \"1.0\", \"2.0\", \"3.0\"]\n //Add the Vector in the list of normals\n normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));\n }\n else if ((result = this.uvPattern.exec(line)) !== null) {\n //Create a Vector2 with the normals u, v\n //Value of result\n // [\"vt 0.1 0.2 0.3\", \"0.1\", \"0.2\"]\n //Add the Vector in the list of uvs\n uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));\n //Identify patterns of faces\n //Face could be defined in different type of pattern\n }\n else if ((result = this.facePattern3.exec(line)) !== null) {\n //Value of result:\n //[\"f 1/1/1 2/2/2 3/3/3\", \"1/1/1 2/2/2 3/3/3\"...]\n //Set the data for this face\n setDataForCurrentFaceWithPattern3(result[1].trim().split(\" \"), // [\"1/1/1\", \"2/2/2\", \"3/3/3\"]\n 1);\n }\n else if ((result = this.facePattern4.exec(line)) !== null) {\n //Value of result:\n //[\"f 1//1 2//2 3//3\", \"1//1 2//2 3//3\"...]\n //Set the data for this face\n setDataForCurrentFaceWithPattern4(result[1].trim().split(\" \"), // [\"1//1\", \"2//2\", \"3//3\"]\n 1);\n }\n else if ((result = this.facePattern5.exec(line)) !== null) {\n //Value of result:\n //[\"f -1/-1/-1 -2/-2/-2 -3/-3/-3\", \"-1/-1/-1 -2/-2/-2 -3/-3/-3\"...]\n //Set the data for this face\n setDataForCurrentFaceWithPattern5(result[1].trim().split(\" \"), // [\"-1/-1/-1\", \"-2/-2/-2\", \"-3/-3/-3\"]\n 1);\n }\n else if ((result = this.facePattern2.exec(line)) !== null) {\n //Value of result:\n //[\"f 1/1 2/2 3/3\", \"1/1 2/2 3/3\"...]\n //Set the data for this face\n setDataForCurrentFaceWithPattern2(result[1].trim().split(\" \"), // [\"1/1\", \"2/2\", \"3/3\"]\n 1);\n }\n else if ((result = this.facePattern1.exec(line)) !== null) {\n //Value of result\n //[\"f 1 2 3\", \"1 2 3\"...]\n //Set the data for this face\n setDataForCurrentFaceWithPattern1(result[1].trim().split(\" \"), // [\"1\", \"2\", \"3\"]\n 1);\n //Define a mesh or an object\n //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh\n }\n else if (this.group.test(line) || this.obj.test(line)) {\n //Create a new mesh corresponding to the name of the group.\n //Definition of the mesh\n var objMesh = \n //Set the name of the current obj mesh\n {\n name: line.substring(2).trim(),\n indices: undefined,\n positions: undefined,\n normals: undefined,\n uvs: undefined,\n materialName: \"\"\n };\n addPreviousObjMesh();\n //Push the last mesh created with only the name\n meshesFromObj.push(objMesh);\n //Set this variable to indicate that now meshesFromObj has objects defined inside\n hasMeshes = true;\n isFirstMaterial = true;\n increment = 1;\n //Keyword for applying a material\n }\n else if (this.usemtl.test(line)) {\n //Get the name of the material\n materialNameFromObj = line.substring(7).trim();\n //If this new material is in the same mesh\n if (!isFirstMaterial) {\n //Set the data for the previous mesh\n addPreviousObjMesh();\n //Create a new mesh\n var objMesh = \n //Set the name of the current obj mesh\n {\n name: objMeshName + \"_mm\" + increment.toString(),\n indices: undefined,\n positions: undefined,\n normals: undefined,\n uvs: undefined,\n materialName: materialNameFromObj\n };\n increment++;\n //If meshes are already defined\n meshesFromObj.push(objMesh);\n }\n //Set the material name if the previous line define a mesh\n if (hasMeshes && isFirstMaterial) {\n //Set the material name to the previous mesh (1 material per mesh)\n meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;\n isFirstMaterial = false;\n }\n //Keyword for loading the mtl file\n }\n else if (this.mtllib.test(line)) {\n //Get the name of mtl file\n fileToLoad = line.substring(7).trim();\n //Apply smoothing\n }\n else if (this.smooth.test(line)) {\n // smooth shading => apply smoothing\n //Toda y I don't know it work with babylon and with obj.\n //With the obj file an integer is set\n }\n else {\n //If there is another possibility\n console.log(\"Unhandled expression at line : \" + line);\n }\n }\n //At the end of the file, add the last mesh into the meshesFromObj array\n if (hasMeshes) {\n //Set the data for the last mesh\n handledMesh = meshesFromObj[meshesFromObj.length - 1];\n //Reverse indices for displaying faces in the good sens\n indicesForBabylon.reverse();\n //Get the good array\n unwrapData();\n //Set array\n handledMesh.indices = indicesForBabylon;\n handledMesh.positions = unwrappedPositionsForBabylon;\n handledMesh.normals = unwrappedNormalsForBabylon;\n handledMesh.uvs = unwrappedUVForBabylon;\n }\n //If any o or g keyword found, create a mesj with a random id\n if (!hasMeshes) {\n // reverse tab of indices\n indicesForBabylon.reverse();\n //Get positions normals uvs\n unwrapData();\n //Set data for one mesh\n meshesFromObj.push({\n name: BABYLON.Geometry.RandomId(),\n indices: indicesForBabylon,\n positions: unwrappedPositionsForBabylon,\n normals: unwrappedNormalsForBabylon,\n uvs: unwrappedUVForBabylon,\n materialName: materialNameFromObj\n });\n }\n //Create a BABYLON.Mesh list\n var babylonMeshesArray = []; //The mesh for babylon\n var materialToUse = new Array();\n //Set data for each mesh\n for (var j = 0; j < meshesFromObj.length; j++) {\n //check meshesNames (stlFileLoader)\n if (meshesNames && meshesFromObj[j].name) {\n if (meshesNames instanceof Array) {\n if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {\n continue;\n }\n }\n else {\n if (meshesFromObj[j].name !== meshesNames) {\n continue;\n }\n }\n }\n //Get the current mesh\n //Set the data with VertexBuffer for each mesh\n handledMesh = meshesFromObj[j];\n //Create a BABYLON.Mesh with the name of the obj mesh\n var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);\n //Push the name of the material to an array\n //This is indispensable for the importMesh function\n materialToUse.push(meshesFromObj[j].materialName);\n var vertexData = new BABYLON.VertexData(); //The container for the values\n //Set the data for the babylonMesh\n vertexData.positions = handledMesh.positions;\n vertexData.normals = handledMesh.normals;\n vertexData.uvs = handledMesh.uvs;\n vertexData.indices = handledMesh.indices;\n //Set the data from the VertexBuffer to the current BABYLON.Mesh\n vertexData.applyToMesh(babylonMesh);\n if (OBJFileLoader.INVERT_Y) {\n babylonMesh.scaling.y *= -1;\n }\n //Push the mesh into an array\n babylonMeshesArray.push(babylonMesh);\n }\n var mtlPromises = [];\n //load the materials\n //Check if we have a file to load\n if (fileToLoad !== \"\") {\n //Load the file synchronously\n mtlPromises.push(new Promise(function (resolve, reject) {\n _this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {\n try {\n //Create materials thanks MTLLoader function\n materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);\n //Look at each material loaded in the mtl file\n for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {\n //Three variables to get all meshes with the same material\n var startIndex = 0;\n var _indices = [];\n var _index;\n //The material from MTL file is used in the meshes loaded\n //Push the indice in an array\n //Check if the material is not used for another mesh\n while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {\n _indices.push(_index);\n startIndex = _index + 1;\n }\n //If the material is not used dispose it\n if (_index == -1 && _indices.length == 0) {\n //If the material is not needed, remove it\n materialsFromMTLFile.materials[n].dispose();\n }\n else {\n for (var o = 0; o < _indices.length; o++) {\n //Apply the material to the BABYLON.Mesh for each mesh with the material\n babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];\n }\n }\n }\n resolve();\n }\n catch (e) {\n reject(e);\n }\n });\n }));\n }\n //Return an array with all BABYLON.Mesh\n return Promise.all(mtlPromises).then(function () {\n return babylonMeshesArray;\n });\n };\n OBJFileLoader.OPTIMIZE_WITH_UV = false;\n OBJFileLoader.INVERT_Y = false;\n return OBJFileLoader;\n }());\n BABYLON.OBJFileLoader = OBJFileLoader;\n if (BABYLON.SceneLoader) {\n //Add this loader into the register plugin\n BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());\n }\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.objFileLoader.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n /**\n * Mode that determines the coordinate system to use.\n */\n var GLTFLoaderCoordinateSystemMode;\n (function (GLTFLoaderCoordinateSystemMode) {\n /**\n * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.\n */\n GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode[\"AUTO\"] = 0] = \"AUTO\";\n /**\n * Sets the useRightHandedSystem flag on the scene.\n */\n GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode[\"FORCE_RIGHT_HANDED\"] = 1] = \"FORCE_RIGHT_HANDED\";\n })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));\n /**\n * Mode that determines what animations will start.\n */\n var GLTFLoaderAnimationStartMode;\n (function (GLTFLoaderAnimationStartMode) {\n /**\n * No animation will start.\n */\n GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode[\"NONE\"] = 0] = \"NONE\";\n /**\n * The first animation will start.\n */\n GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode[\"FIRST\"] = 1] = \"FIRST\";\n /**\n * All animations will start.\n */\n GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode[\"ALL\"] = 2] = \"ALL\";\n })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));\n /**\n * Loader state.\n */\n var GLTFLoaderState;\n (function (GLTFLoaderState) {\n /**\n * The asset is loading.\n */\n GLTFLoaderState[GLTFLoaderState[\"LOADING\"] = 0] = \"LOADING\";\n /**\n * The asset is ready for rendering.\n */\n GLTFLoaderState[GLTFLoaderState[\"READY\"] = 1] = \"READY\";\n /**\n * The asset is completely loaded.\n */\n GLTFLoaderState[GLTFLoaderState[\"COMPLETE\"] = 2] = \"COMPLETE\";\n })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));\n /**\n * File loader for loading glTF files into a scene.\n */\n var GLTFFileLoader = /** @class */ (function () {\n function GLTFFileLoader() {\n // #region Common options\n /**\n * Raised when the asset has been parsed\n */\n this.onParsedObservable = new BABYLON.Observable();\n // #endregion\n // #region V2 options\n /**\n * The coordinate system mode. Defaults to AUTO.\n */\n this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;\n /**\n * The animation start mode. Defaults to FIRST.\n */\n this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;\n /**\n * Defines if the loader should compile materials before raising the success callback. Defaults to false.\n */\n this.compileMaterials = false;\n /**\n * Defines if the loader should also compile materials with clip planes. Defaults to false.\n */\n this.useClipPlane = false;\n /**\n * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.\n */\n this.compileShadowGenerators = false;\n /**\n * Defines if the Alpha blended materials are only applied as coverage.\n * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.\n * If true, no extra effects are applied to transparent pixels.\n */\n this.transparencyAsCoverage = false;\n /** @hidden */\n this._normalizeAnimationGroupsToBeginAtZero = true;\n /**\n * Function called before loading a url referenced by the asset.\n */\n this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };\n /**\n * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.\n */\n this.onMeshLoadedObservable = new BABYLON.Observable();\n /**\n * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.\n */\n this.onTextureLoadedObservable = new BABYLON.Observable();\n /**\n * Observable raised when the loader creates a material after parsing the glTF properties of the material.\n */\n this.onMaterialLoadedObservable = new BABYLON.Observable();\n /**\n * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.\n */\n this.onCameraLoadedObservable = new BABYLON.Observable();\n /**\n * Observable raised when the asset is completely loaded, immediately before the loader is disposed.\n * For assets with LODs, raised when all of the LODs are complete.\n * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.\n */\n this.onCompleteObservable = new BABYLON.Observable();\n /**\n * Observable raised when an error occurs.\n */\n this.onErrorObservable = new BABYLON.Observable();\n /**\n * Observable raised after the loader is disposed.\n */\n this.onDisposeObservable = new BABYLON.Observable();\n /**\n * Observable raised after a loader extension is created.\n * Set additional options for a loader extension in this event.\n */\n this.onExtensionLoadedObservable = new BABYLON.Observable();\n // #endregion\n this._loader = null;\n /**\n * Name of the loader (\"gltf\")\n */\n this.name = \"gltf\";\n /**\n * Supported file extensions of the loader (.gltf, .glb)\n */\n this.extensions = {\n \".gltf\": { isBinary: false },\n \".glb\": { isBinary: true }\n };\n this._logIndentLevel = 0;\n this._loggingEnabled = false;\n /** @hidden */\n this._log = this._logDisabled;\n this._capturePerformanceCounters = false;\n /** @hidden */\n this._startPerformanceCounter = this._startPerformanceCounterDisabled;\n /** @hidden */\n this._endPerformanceCounter = this._endPerformanceCounterDisabled;\n }\n Object.defineProperty(GLTFFileLoader.prototype, \"onParsed\", {\n /**\n * Raised when the asset has been parsed\n */\n set: function (callback) {\n if (this._onParsedObserver) {\n this.onParsedObservable.remove(this._onParsedObserver);\n }\n this._onParsedObserver = this.onParsedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onMeshLoaded\", {\n /**\n * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.\n */\n set: function (callback) {\n if (this._onMeshLoadedObserver) {\n this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);\n }\n this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onTextureLoaded\", {\n /**\n * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.\n */\n set: function (callback) {\n if (this._onTextureLoadedObserver) {\n this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);\n }\n this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onMaterialLoaded\", {\n /**\n * Callback raised when the loader creates a material after parsing the glTF properties of the material.\n */\n set: function (callback) {\n if (this._onMaterialLoadedObserver) {\n this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);\n }\n this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onCameraLoaded\", {\n /**\n * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.\n */\n set: function (callback) {\n if (this._onCameraLoadedObserver) {\n this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);\n }\n this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onComplete\", {\n /**\n * Callback raised when the asset is completely loaded, immediately before the loader is disposed.\n * For assets with LODs, raised when all of the LODs are complete.\n * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.\n */\n set: function (callback) {\n if (this._onCompleteObserver) {\n this.onCompleteObservable.remove(this._onCompleteObserver);\n }\n this._onCompleteObserver = this.onCompleteObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onError\", {\n /**\n * Callback raised when an error occurs.\n */\n set: function (callback) {\n if (this._onErrorObserver) {\n this.onErrorObservable.remove(this._onErrorObserver);\n }\n this._onErrorObserver = this.onErrorObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onDispose\", {\n /**\n * Callback raised after the loader is disposed.\n */\n set: function (callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"onExtensionLoaded\", {\n /**\n * Callback raised after a loader extension is created.\n */\n set: function (callback) {\n if (this._onExtensionLoadedObserver) {\n this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);\n }\n this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a promise that resolves when the asset is completely loaded.\n * @returns a promise that resolves when the asset is completely loaded.\n */\n GLTFFileLoader.prototype.whenCompleteAsync = function () {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this.onCompleteObservable.addOnce(function () {\n resolve();\n });\n _this.onErrorObservable.addOnce(function (reason) {\n reject(reason);\n });\n });\n };\n Object.defineProperty(GLTFFileLoader.prototype, \"loaderState\", {\n /**\n * The loader state or null if the loader is not active.\n */\n get: function () {\n return this._loader ? this._loader.state : null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"loggingEnabled\", {\n /**\n * Defines if the loader logging is enabled.\n */\n get: function () {\n return this._loggingEnabled;\n },\n set: function (value) {\n if (this._loggingEnabled === value) {\n return;\n }\n this._loggingEnabled = value;\n if (this._loggingEnabled) {\n this._log = this._logEnabled;\n }\n else {\n this._log = this._logDisabled;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GLTFFileLoader.prototype, \"capturePerformanceCounters\", {\n /**\n * Defines if the loader should capture performance counters.\n */\n get: function () {\n return this._capturePerformanceCounters;\n },\n set: function (value) {\n if (this._capturePerformanceCounters === value) {\n return;\n }\n this._capturePerformanceCounters = value;\n if (this._capturePerformanceCounters) {\n this._startPerformanceCounter = this._startPerformanceCounterEnabled;\n this._endPerformanceCounter = this._endPerformanceCounterEnabled;\n }\n else {\n this._startPerformanceCounter = this._startPerformanceCounterDisabled;\n this._endPerformanceCounter = this._endPerformanceCounterDisabled;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Disposes the loader, releases resources during load, and cancels any outstanding requests.\n */\n GLTFFileLoader.prototype.dispose = function () {\n if (this._loader) {\n this._loader.dispose();\n this._loader = null;\n }\n this._clear();\n this.onDisposeObservable.notifyObservers(undefined);\n this.onDisposeObservable.clear();\n };\n /** @hidden */\n GLTFFileLoader.prototype._clear = function () {\n this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };\n this.onMeshLoadedObservable.clear();\n this.onTextureLoadedObservable.clear();\n this.onMaterialLoadedObservable.clear();\n this.onCameraLoadedObservable.clear();\n this.onCompleteObservable.clear();\n this.onExtensionLoadedObservable.clear();\n };\n /**\n * Imports one or more meshes from the loaded glTF data and adds them to the scene\n * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file\n * @param scene the scene the meshes should be added to\n * @param data the glTF data to load\n * @param rootUrl root url to load from\n * @param onProgress event that fires when loading progress has occured\n * @returns a promise containg the loaded meshes, particles, skeletons and animations\n */\n GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {\n var _this = this;\n return Promise.resolve().then(function () {\n var loaderData = _this._parse(data);\n _this._loader = _this._getLoader(loaderData);\n return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);\n });\n };\n /**\n * Imports all objects from the loaded glTF data and adds them to the scene\n * @param scene the scene the objects should be added to\n * @param data the glTF data to load\n * @param rootUrl root url to load from\n * @param onProgress event that fires when loading progress has occured\n * @returns a promise which completes when objects have been loaded to the scene\n */\n GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {\n var _this = this;\n return Promise.resolve().then(function () {\n var loaderData = _this._parse(data);\n _this._loader = _this._getLoader(loaderData);\n return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);\n });\n };\n /**\n * Load into an asset container.\n * @param scene The scene to load into\n * @param data The data to import\n * @param rootUrl The root url for scene and resources\n * @param onProgress The callback when the load progresses\n * @returns The loaded asset container\n */\n GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {\n var _this = this;\n return Promise.resolve().then(function () {\n var loaderData = _this._parse(data);\n _this._loader = _this._getLoader(loaderData);\n return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {\n var container = new BABYLON.AssetContainer(scene);\n Array.prototype.push.apply(container.meshes, result.meshes);\n Array.prototype.push.apply(container.particleSystems, result.particleSystems);\n Array.prototype.push.apply(container.skeletons, result.skeletons);\n Array.prototype.push.apply(container.animationGroups, result.animationGroups);\n container.removeAllFromScene();\n return container;\n });\n });\n };\n /**\n * If the data string can be loaded directly.\n * @param data string contianing the file data\n * @returns if the data can be loaded directly\n */\n GLTFFileLoader.prototype.canDirectLoad = function (data) {\n return ((data.indexOf(\"scene\") !== -1) && (data.indexOf(\"node\") !== -1));\n };\n /**\n * Instantiates a glTF file loader plugin.\n * @returns the created plugin\n */\n GLTFFileLoader.prototype.createPlugin = function () {\n return new GLTFFileLoader();\n };\n GLTFFileLoader.prototype._parse = function (data) {\n this._startPerformanceCounter(\"Parse\");\n var parsedData;\n if (data instanceof ArrayBuffer) {\n this._log(\"Parsing binary\");\n parsedData = this._parseBinary(data);\n }\n else {\n this._log(\"Parsing JSON\");\n this._log(\"JSON length: \" + data.length);\n parsedData = {\n json: JSON.parse(data),\n bin: null\n };\n }\n this.onParsedObservable.notifyObservers(parsedData);\n this.onParsedObservable.clear();\n this._endPerformanceCounter(\"Parse\");\n return parsedData;\n };\n GLTFFileLoader.prototype._getLoader = function (loaderData) {\n var asset = loaderData.json.asset || {};\n this._log(\"Asset version: \" + asset.version);\n asset.minVersion && this._log(\"Asset minimum version: \" + asset.minVersion);\n asset.generator && this._log(\"Asset generator: \" + asset.generator);\n var version = GLTFFileLoader._parseVersion(asset.version);\n if (!version) {\n throw new Error(\"Invalid version: \" + asset.version);\n }\n if (asset.minVersion !== undefined) {\n var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);\n if (!minVersion) {\n throw new Error(\"Invalid minimum version: \" + asset.minVersion);\n }\n if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {\n throw new Error(\"Incompatible minimum version: \" + asset.minVersion);\n }\n }\n var createLoaders = {\n 1: GLTFFileLoader._CreateGLTFLoaderV1,\n 2: GLTFFileLoader._CreateGLTFLoaderV2\n };\n var createLoader = createLoaders[version.major];\n if (!createLoader) {\n throw new Error(\"Unsupported version: \" + asset.version);\n }\n return createLoader(this);\n };\n GLTFFileLoader.prototype._parseBinary = function (data) {\n var Binary = {\n Magic: 0x46546C67\n };\n this._log(\"Binary length: \" + data.byteLength);\n var binaryReader = new BinaryReader(data);\n var magic = binaryReader.readUint32();\n if (magic !== Binary.Magic) {\n throw new Error(\"Unexpected magic: \" + magic);\n }\n var version = binaryReader.readUint32();\n if (this.loggingEnabled) {\n this._log(\"Binary version: \" + version);\n }\n switch (version) {\n case 1: return this._parseV1(binaryReader);\n case 2: return this._parseV2(binaryReader);\n }\n throw new Error(\"Unsupported version: \" + version);\n };\n GLTFFileLoader.prototype._parseV1 = function (binaryReader) {\n var ContentFormat = {\n JSON: 0\n };\n var length = binaryReader.readUint32();\n if (length != binaryReader.getLength()) {\n throw new Error(\"Length in header does not match actual data length: \" + length + \" != \" + binaryReader.getLength());\n }\n var contentLength = binaryReader.readUint32();\n var contentFormat = binaryReader.readUint32();\n var content;\n switch (contentFormat) {\n case ContentFormat.JSON: {\n content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));\n break;\n }\n default: {\n throw new Error(\"Unexpected content format: \" + contentFormat);\n }\n }\n var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();\n var body = binaryReader.readUint8Array(bytesRemaining);\n return {\n json: content,\n bin: body\n };\n };\n GLTFFileLoader.prototype._parseV2 = function (binaryReader) {\n var ChunkFormat = {\n JSON: 0x4E4F534A,\n BIN: 0x004E4942\n };\n var length = binaryReader.readUint32();\n if (length !== binaryReader.getLength()) {\n throw new Error(\"Length in header does not match actual data length: \" + length + \" != \" + binaryReader.getLength());\n }\n // JSON chunk\n var chunkLength = binaryReader.readUint32();\n var chunkFormat = binaryReader.readUint32();\n if (chunkFormat !== ChunkFormat.JSON) {\n throw new Error(\"First chunk format is not JSON\");\n }\n var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));\n // Look for BIN chunk\n var bin = null;\n while (binaryReader.getPosition() < binaryReader.getLength()) {\n var chunkLength_1 = binaryReader.readUint32();\n var chunkFormat_1 = binaryReader.readUint32();\n switch (chunkFormat_1) {\n case ChunkFormat.JSON: {\n throw new Error(\"Unexpected JSON chunk\");\n }\n case ChunkFormat.BIN: {\n bin = binaryReader.readUint8Array(chunkLength_1);\n break;\n }\n default: {\n // ignore unrecognized chunkFormat\n binaryReader.skipBytes(chunkLength_1);\n break;\n }\n }\n }\n return {\n json: json,\n bin: bin\n };\n };\n GLTFFileLoader._parseVersion = function (version) {\n if (version === \"1.0\" || version === \"1.0.1\") {\n return {\n major: 1,\n minor: 0\n };\n }\n var match = (version + \"\").match(/^(\\d+)\\.(\\d+)/);\n if (!match) {\n return null;\n }\n return {\n major: parseInt(match[1]),\n minor: parseInt(match[2])\n };\n };\n GLTFFileLoader._compareVersion = function (a, b) {\n if (a.major > b.major)\n return 1;\n if (a.major < b.major)\n return -1;\n if (a.minor > b.minor)\n return 1;\n if (a.minor < b.minor)\n return -1;\n return 0;\n };\n GLTFFileLoader._decodeBufferToText = function (buffer) {\n var result = \"\";\n var length = buffer.byteLength;\n for (var i = 0; i < length; i++) {\n result += String.fromCharCode(buffer[i]);\n }\n return result;\n };\n /** @hidden */\n GLTFFileLoader.prototype._logOpen = function (message) {\n this._log(message);\n this._logIndentLevel++;\n };\n /** @hidden */\n GLTFFileLoader.prototype._logClose = function () {\n --this._logIndentLevel;\n };\n GLTFFileLoader.prototype._logEnabled = function (message) {\n var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);\n BABYLON.Tools.Log(\"\" + spaces + message);\n };\n GLTFFileLoader.prototype._logDisabled = function (message) {\n };\n GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {\n BABYLON.Tools.StartPerformanceCounter(counterName);\n };\n GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {\n };\n GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {\n BABYLON.Tools.EndPerformanceCounter(counterName);\n };\n GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {\n };\n // #endregion\n // #region V1 options\n /**\n * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.\n * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.\n * Defaults to true.\n * @hidden\n */\n GLTFFileLoader.IncrementalLoading = true;\n /**\n * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.\n * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.\n * @hidden\n */\n GLTFFileLoader.HomogeneousCoordinates = false;\n GLTFFileLoader._logSpaces = \" \";\n return GLTFFileLoader;\n }());\n BABYLON.GLTFFileLoader = GLTFFileLoader;\n var BinaryReader = /** @class */ (function () {\n function BinaryReader(arrayBuffer) {\n this._arrayBuffer = arrayBuffer;\n this._dataView = new DataView(arrayBuffer);\n this._byteOffset = 0;\n }\n BinaryReader.prototype.getPosition = function () {\n return this._byteOffset;\n };\n BinaryReader.prototype.getLength = function () {\n return this._arrayBuffer.byteLength;\n };\n BinaryReader.prototype.readUint32 = function () {\n var value = this._dataView.getUint32(this._byteOffset, true);\n this._byteOffset += 4;\n return value;\n };\n BinaryReader.prototype.readUint8Array = function (length) {\n var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);\n this._byteOffset += length;\n return value;\n };\n BinaryReader.prototype.skipBytes = function (length) {\n this._byteOffset += length;\n };\n return BinaryReader;\n }());\n if (BABYLON.SceneLoader) {\n BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());\n }\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFFileLoader.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF1;\n (function (GLTF1) {\n /**\n * Enums\n */\n var EComponentType;\n (function (EComponentType) {\n EComponentType[EComponentType[\"BYTE\"] = 5120] = \"BYTE\";\n EComponentType[EComponentType[\"UNSIGNED_BYTE\"] = 5121] = \"UNSIGNED_BYTE\";\n EComponentType[EComponentType[\"SHORT\"] = 5122] = \"SHORT\";\n EComponentType[EComponentType[\"UNSIGNED_SHORT\"] = 5123] = \"UNSIGNED_SHORT\";\n EComponentType[EComponentType[\"FLOAT\"] = 5126] = \"FLOAT\";\n })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));\n var EShaderType;\n (function (EShaderType) {\n EShaderType[EShaderType[\"FRAGMENT\"] = 35632] = \"FRAGMENT\";\n EShaderType[EShaderType[\"VERTEX\"] = 35633] = \"VERTEX\";\n })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));\n var EParameterType;\n (function (EParameterType) {\n EParameterType[EParameterType[\"BYTE\"] = 5120] = \"BYTE\";\n EParameterType[EParameterType[\"UNSIGNED_BYTE\"] = 5121] = \"UNSIGNED_BYTE\";\n EParameterType[EParameterType[\"SHORT\"] = 5122] = \"SHORT\";\n EParameterType[EParameterType[\"UNSIGNED_SHORT\"] = 5123] = \"UNSIGNED_SHORT\";\n EParameterType[EParameterType[\"INT\"] = 5124] = \"INT\";\n EParameterType[EParameterType[\"UNSIGNED_INT\"] = 5125] = \"UNSIGNED_INT\";\n EParameterType[EParameterType[\"FLOAT\"] = 5126] = \"FLOAT\";\n EParameterType[EParameterType[\"FLOAT_VEC2\"] = 35664] = \"FLOAT_VEC2\";\n EParameterType[EParameterType[\"FLOAT_VEC3\"] = 35665] = \"FLOAT_VEC3\";\n EParameterType[EParameterType[\"FLOAT_VEC4\"] = 35666] = \"FLOAT_VEC4\";\n EParameterType[EParameterType[\"INT_VEC2\"] = 35667] = \"INT_VEC2\";\n EParameterType[EParameterType[\"INT_VEC3\"] = 35668] = \"INT_VEC3\";\n EParameterType[EParameterType[\"INT_VEC4\"] = 35669] = \"INT_VEC4\";\n EParameterType[EParameterType[\"BOOL\"] = 35670] = \"BOOL\";\n EParameterType[EParameterType[\"BOOL_VEC2\"] = 35671] = \"BOOL_VEC2\";\n EParameterType[EParameterType[\"BOOL_VEC3\"] = 35672] = \"BOOL_VEC3\";\n EParameterType[EParameterType[\"BOOL_VEC4\"] = 35673] = \"BOOL_VEC4\";\n EParameterType[EParameterType[\"FLOAT_MAT2\"] = 35674] = \"FLOAT_MAT2\";\n EParameterType[EParameterType[\"FLOAT_MAT3\"] = 35675] = \"FLOAT_MAT3\";\n EParameterType[EParameterType[\"FLOAT_MAT4\"] = 35676] = \"FLOAT_MAT4\";\n EParameterType[EParameterType[\"SAMPLER_2D\"] = 35678] = \"SAMPLER_2D\";\n })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));\n var ETextureWrapMode;\n (function (ETextureWrapMode) {\n ETextureWrapMode[ETextureWrapMode[\"CLAMP_TO_EDGE\"] = 33071] = \"CLAMP_TO_EDGE\";\n ETextureWrapMode[ETextureWrapMode[\"MIRRORED_REPEAT\"] = 33648] = \"MIRRORED_REPEAT\";\n ETextureWrapMode[ETextureWrapMode[\"REPEAT\"] = 10497] = \"REPEAT\";\n })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));\n var ETextureFilterType;\n (function (ETextureFilterType) {\n ETextureFilterType[ETextureFilterType[\"NEAREST\"] = 9728] = \"NEAREST\";\n ETextureFilterType[ETextureFilterType[\"LINEAR\"] = 9728] = \"LINEAR\";\n ETextureFilterType[ETextureFilterType[\"NEAREST_MIPMAP_NEAREST\"] = 9984] = \"NEAREST_MIPMAP_NEAREST\";\n ETextureFilterType[ETextureFilterType[\"LINEAR_MIPMAP_NEAREST\"] = 9985] = \"LINEAR_MIPMAP_NEAREST\";\n ETextureFilterType[ETextureFilterType[\"NEAREST_MIPMAP_LINEAR\"] = 9986] = \"NEAREST_MIPMAP_LINEAR\";\n ETextureFilterType[ETextureFilterType[\"LINEAR_MIPMAP_LINEAR\"] = 9987] = \"LINEAR_MIPMAP_LINEAR\";\n })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));\n var ETextureFormat;\n (function (ETextureFormat) {\n ETextureFormat[ETextureFormat[\"ALPHA\"] = 6406] = \"ALPHA\";\n ETextureFormat[ETextureFormat[\"RGB\"] = 6407] = \"RGB\";\n ETextureFormat[ETextureFormat[\"RGBA\"] = 6408] = \"RGBA\";\n ETextureFormat[ETextureFormat[\"LUMINANCE\"] = 6409] = \"LUMINANCE\";\n ETextureFormat[ETextureFormat[\"LUMINANCE_ALPHA\"] = 6410] = \"LUMINANCE_ALPHA\";\n })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));\n var ECullingType;\n (function (ECullingType) {\n ECullingType[ECullingType[\"FRONT\"] = 1028] = \"FRONT\";\n ECullingType[ECullingType[\"BACK\"] = 1029] = \"BACK\";\n ECullingType[ECullingType[\"FRONT_AND_BACK\"] = 1032] = \"FRONT_AND_BACK\";\n })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));\n var EBlendingFunction;\n (function (EBlendingFunction) {\n EBlendingFunction[EBlendingFunction[\"ZERO\"] = 0] = \"ZERO\";\n EBlendingFunction[EBlendingFunction[\"ONE\"] = 1] = \"ONE\";\n EBlendingFunction[EBlendingFunction[\"SRC_COLOR\"] = 768] = \"SRC_COLOR\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_SRC_COLOR\"] = 769] = \"ONE_MINUS_SRC_COLOR\";\n EBlendingFunction[EBlendingFunction[\"DST_COLOR\"] = 774] = \"DST_COLOR\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_DST_COLOR\"] = 775] = \"ONE_MINUS_DST_COLOR\";\n EBlendingFunction[EBlendingFunction[\"SRC_ALPHA\"] = 770] = \"SRC_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_SRC_ALPHA\"] = 771] = \"ONE_MINUS_SRC_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"DST_ALPHA\"] = 772] = \"DST_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_DST_ALPHA\"] = 773] = \"ONE_MINUS_DST_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"CONSTANT_COLOR\"] = 32769] = \"CONSTANT_COLOR\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_CONSTANT_COLOR\"] = 32770] = \"ONE_MINUS_CONSTANT_COLOR\";\n EBlendingFunction[EBlendingFunction[\"CONSTANT_ALPHA\"] = 32771] = \"CONSTANT_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_CONSTANT_ALPHA\"] = 32772] = \"ONE_MINUS_CONSTANT_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"SRC_ALPHA_SATURATE\"] = 776] = \"SRC_ALPHA_SATURATE\";\n })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));\n })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF1;\n (function (GLTF1) {\n /**\n * Tokenizer. Used for shaders compatibility\n * Automatically map world, view, projection, worldViewProjection, attributes and so on\n */\n var ETokenType;\n (function (ETokenType) {\n ETokenType[ETokenType[\"IDENTIFIER\"] = 1] = \"IDENTIFIER\";\n ETokenType[ETokenType[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\n ETokenType[ETokenType[\"END_OF_INPUT\"] = 3] = \"END_OF_INPUT\";\n })(ETokenType || (ETokenType = {}));\n var Tokenizer = /** @class */ (function () {\n function Tokenizer(toParse) {\n this._pos = 0;\n this.currentToken = ETokenType.UNKNOWN;\n this.currentIdentifier = \"\";\n this.currentString = \"\";\n this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;\n this._toParse = toParse;\n this._maxPos = toParse.length;\n }\n Tokenizer.prototype.getNextToken = function () {\n if (this.isEnd())\n return ETokenType.END_OF_INPUT;\n this.currentString = this.read();\n this.currentToken = ETokenType.UNKNOWN;\n if (this.currentString === \"_\" || this.isLetterOrDigitPattern.test(this.currentString)) {\n this.currentToken = ETokenType.IDENTIFIER;\n this.currentIdentifier = this.currentString;\n while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === \"_\")) {\n this.currentIdentifier += this.currentString;\n this.forward();\n }\n }\n return this.currentToken;\n };\n Tokenizer.prototype.peek = function () {\n return this._toParse[this._pos];\n };\n Tokenizer.prototype.read = function () {\n return this._toParse[this._pos++];\n };\n Tokenizer.prototype.forward = function () {\n this._pos++;\n };\n Tokenizer.prototype.isEnd = function () {\n return this._pos >= this._maxPos;\n };\n return Tokenizer;\n }());\n /**\n * Values\n */\n var glTFTransforms = [\"MODEL\", \"VIEW\", \"PROJECTION\", \"MODELVIEW\", \"MODELVIEWPROJECTION\", \"JOINTMATRIX\"];\n var babylonTransforms = [\"world\", \"view\", \"projection\", \"worldView\", \"worldViewProjection\", \"mBones\"];\n var glTFAnimationPaths = [\"translation\", \"rotation\", \"scale\"];\n var babylonAnimationPaths = [\"position\", \"rotationQuaternion\", \"scaling\"];\n /**\n * Parse\n */\n var parseBuffers = function (parsedBuffers, gltfRuntime) {\n for (var buf in parsedBuffers) {\n var parsedBuffer = parsedBuffers[buf];\n gltfRuntime.buffers[buf] = parsedBuffer;\n gltfRuntime.buffersCount++;\n }\n };\n var parseShaders = function (parsedShaders, gltfRuntime) {\n for (var sha in parsedShaders) {\n var parsedShader = parsedShaders[sha];\n gltfRuntime.shaders[sha] = parsedShader;\n gltfRuntime.shaderscount++;\n }\n };\n var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {\n for (var object in parsedObjects) {\n var parsedObject = parsedObjects[object];\n gltfRuntime[runtimeProperty][object] = parsedObject;\n }\n };\n /**\n * Utils\n */\n var normalizeUVs = function (buffer) {\n if (!buffer) {\n return;\n }\n for (var i = 0; i < buffer.length / 2; i++) {\n buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];\n }\n };\n var getAttribute = function (attributeParameter) {\n if (attributeParameter.semantic === \"NORMAL\") {\n return \"normal\";\n }\n else if (attributeParameter.semantic === \"POSITION\") {\n return \"position\";\n }\n else if (attributeParameter.semantic === \"JOINT\") {\n return \"matricesIndices\";\n }\n else if (attributeParameter.semantic === \"WEIGHT\") {\n return \"matricesWeights\";\n }\n else if (attributeParameter.semantic === \"COLOR\") {\n return \"color\";\n }\n else if (attributeParameter.semantic && attributeParameter.semantic.indexOf(\"TEXCOORD_\") !== -1) {\n var channel = Number(attributeParameter.semantic.split(\"_\")[1]);\n return \"uv\" + (channel === 0 ? \"\" : channel + 1);\n }\n return null;\n };\n /**\n * Loads and creates animations\n */\n var loadAnimations = function (gltfRuntime) {\n for (var anim in gltfRuntime.animations) {\n var animation = gltfRuntime.animations[anim];\n if (!animation.channels || !animation.samplers) {\n continue;\n }\n var lastAnimation = null;\n for (var i = 0; i < animation.channels.length; i++) {\n // Get parameters and load buffers\n var channel = animation.channels[i];\n var sampler = animation.samplers[channel.sampler];\n if (!sampler) {\n continue;\n }\n var inputData = null;\n var outputData = null;\n if (animation.parameters) {\n inputData = animation.parameters[sampler.input];\n outputData = animation.parameters[sampler.output];\n }\n else {\n inputData = sampler.input;\n outputData = sampler.output;\n }\n var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);\n var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);\n var targetID = channel.target.id;\n var targetNode = gltfRuntime.scene.getNodeByID(targetID);\n if (targetNode === null) {\n targetNode = gltfRuntime.scene.getNodeByName(targetID);\n }\n if (targetNode === null) {\n BABYLON.Tools.Warn(\"Creating animation named \" + anim + \". But cannot find node named \" + targetID + \" to attach to\");\n continue;\n }\n var isBone = targetNode instanceof BABYLON.Bone;\n // Get target path (position, rotation or scaling)\n var targetPath = channel.target.path;\n var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);\n if (targetPathIndex !== -1) {\n targetPath = babylonAnimationPaths[targetPathIndex];\n }\n // Determine animation type\n var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;\n if (!isBone) {\n if (targetPath === \"rotationQuaternion\") {\n animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;\n targetNode.rotationQuaternion = new BABYLON.Quaternion();\n }\n else {\n animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;\n }\n }\n // Create animation and key frames\n var babylonAnimation = null;\n var keys = [];\n var arrayOffset = 0;\n var modifyKey = false;\n if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {\n babylonAnimation = lastAnimation;\n modifyKey = true;\n }\n if (!modifyKey) {\n babylonAnimation = new BABYLON.Animation(anim, isBone ? \"_matrix\" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);\n }\n // For each frame\n for (var j = 0; j < bufferInput.length; j++) {\n var value = null;\n if (targetPath === \"rotationQuaternion\") { // VEC4\n value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);\n arrayOffset += 4;\n }\n else { // Position and scaling are VEC3\n value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);\n arrayOffset += 3;\n }\n if (isBone) {\n var bone = targetNode;\n var translation = BABYLON.Vector3.Zero();\n var rotationQuaternion = new BABYLON.Quaternion();\n var scaling = BABYLON.Vector3.Zero();\n // Warning on decompose\n var mat = bone.getBaseMatrix();\n if (modifyKey && lastAnimation) {\n mat = lastAnimation.getKeys()[j].value;\n }\n mat.decompose(scaling, rotationQuaternion, translation);\n if (targetPath === \"position\") {\n translation = value;\n }\n else if (targetPath === \"rotationQuaternion\") {\n rotationQuaternion = value;\n }\n else {\n scaling = value;\n }\n value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);\n }\n if (!modifyKey) {\n keys.push({\n frame: bufferInput[j],\n value: value\n });\n }\n else if (lastAnimation) {\n lastAnimation.getKeys()[j].value = value;\n }\n }\n // Finish\n if (!modifyKey && babylonAnimation) {\n babylonAnimation.setKeys(keys);\n targetNode.animations.push(babylonAnimation);\n }\n lastAnimation = babylonAnimation;\n gltfRuntime.scene.stopAnimation(targetNode);\n gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);\n }\n }\n };\n /**\n * Returns the bones transformation matrix\n */\n var configureBoneTransformation = function (node) {\n var mat = null;\n if (node.translation || node.rotation || node.scale) {\n var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);\n var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);\n var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);\n mat = BABYLON.Matrix.Compose(scale, rotation, position);\n }\n else {\n mat = BABYLON.Matrix.FromArray(node.matrix);\n }\n return mat;\n };\n /**\n * Returns the parent bone\n */\n var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {\n // Try to find\n for (var i = 0; i < newSkeleton.bones.length; i++) {\n if (newSkeleton.bones[i].name === jointName) {\n return newSkeleton.bones[i];\n }\n }\n // Not found, search in gltf nodes\n var nodes = gltfRuntime.nodes;\n for (var nde in nodes) {\n var node = nodes[nde];\n if (!node.jointName) {\n continue;\n }\n var children = node.children;\n for (var i = 0; i < children.length; i++) {\n var child = gltfRuntime.nodes[children[i]];\n if (!child.jointName) {\n continue;\n }\n if (child.jointName === jointName) {\n var mat = configureBoneTransformation(node);\n var bone = new BABYLON.Bone(node.name || \"\", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);\n bone.id = nde;\n return bone;\n }\n }\n }\n return null;\n };\n /**\n * Returns the appropriate root node\n */\n var getNodeToRoot = function (nodesToRoot, id) {\n for (var i = 0; i < nodesToRoot.length; i++) {\n var nodeToRoot = nodesToRoot[i];\n for (var j = 0; j < nodeToRoot.node.children.length; j++) {\n var child = nodeToRoot.node.children[j];\n if (child === id) {\n return nodeToRoot.bone;\n }\n }\n }\n return null;\n };\n /**\n * Returns the node with the joint name\n */\n var getJointNode = function (gltfRuntime, jointName) {\n var nodes = gltfRuntime.nodes;\n var node = nodes[jointName];\n if (node) {\n return {\n node: node,\n id: jointName\n };\n }\n for (var nde in nodes) {\n node = nodes[nde];\n if (node.jointName === jointName) {\n return {\n node: node,\n id: nde\n };\n }\n }\n return null;\n };\n /**\n * Checks if a nodes is in joints\n */\n var nodeIsInJoints = function (skins, id) {\n for (var i = 0; i < skins.jointNames.length; i++) {\n if (skins.jointNames[i] === id) {\n return true;\n }\n }\n return false;\n };\n /**\n * Fills the nodes to root for bones and builds hierarchy\n */\n var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {\n // Creates nodes for root\n for (var nde in gltfRuntime.nodes) {\n var node = gltfRuntime.nodes[nde];\n var id = nde;\n if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {\n continue;\n }\n // Create node to root bone\n var mat = configureBoneTransformation(node);\n var bone = new BABYLON.Bone(node.name || \"\", newSkeleton, null, mat);\n bone.id = id;\n nodesToRoot.push({ bone: bone, node: node, id: id });\n }\n // Parenting\n for (var i = 0; i < nodesToRoot.length; i++) {\n var nodeToRoot = nodesToRoot[i];\n var children = nodeToRoot.node.children;\n for (var j = 0; j < children.length; j++) {\n var child = null;\n for (var k = 0; k < nodesToRoot.length; k++) {\n if (nodesToRoot[k].id === children[j]) {\n child = nodesToRoot[k];\n break;\n }\n }\n if (child) {\n child.bone._parent = nodeToRoot.bone;\n nodeToRoot.bone.children.push(child.bone);\n }\n }\n }\n };\n /**\n * Imports a skeleton\n */\n var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {\n if (!newSkeleton) {\n newSkeleton = new BABYLON.Skeleton(skins.name || \"\", \"\", gltfRuntime.scene);\n }\n if (!skins.babylonSkeleton) {\n return newSkeleton;\n }\n // Find the root bones\n var nodesToRoot = [];\n var nodesToRootToAdd = [];\n getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);\n newSkeleton.bones = [];\n // Joints\n for (var i = 0; i < skins.jointNames.length; i++) {\n var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);\n if (!jointNode) {\n continue;\n }\n var node = jointNode.node;\n if (!node) {\n BABYLON.Tools.Warn(\"Joint named \" + skins.jointNames[i] + \" does not exist\");\n continue;\n }\n var id = jointNode.id;\n // Optimize, if the bone already exists...\n var existingBone = gltfRuntime.scene.getBoneByID(id);\n if (existingBone) {\n newSkeleton.bones.push(existingBone);\n continue;\n }\n // Search for parent bone\n var foundBone = false;\n var parentBone = null;\n for (var j = 0; j < i; j++) {\n var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);\n if (!jointNode_1) {\n continue;\n }\n var joint = jointNode_1.node;\n if (!joint) {\n BABYLON.Tools.Warn(\"Joint named \" + skins.jointNames[j] + \" does not exist when looking for parent\");\n continue;\n }\n var children = joint.children;\n if (!children) {\n continue;\n }\n foundBone = false;\n for (var k = 0; k < children.length; k++) {\n if (children[k] === id) {\n parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);\n foundBone = true;\n break;\n }\n }\n if (foundBone) {\n break;\n }\n }\n // Create bone\n var mat = configureBoneTransformation(node);\n if (!parentBone && nodesToRoot.length > 0) {\n parentBone = getNodeToRoot(nodesToRoot, id);\n if (parentBone) {\n if (nodesToRootToAdd.indexOf(parentBone) === -1) {\n nodesToRootToAdd.push(parentBone);\n }\n }\n }\n var bone = new BABYLON.Bone(node.jointName || \"\", newSkeleton, parentBone, mat);\n bone.id = id;\n }\n // Polish\n var bones = newSkeleton.bones;\n newSkeleton.bones = [];\n for (var i = 0; i < skins.jointNames.length; i++) {\n var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);\n if (!jointNode) {\n continue;\n }\n for (var j = 0; j < bones.length; j++) {\n if (bones[j].id === jointNode.id) {\n newSkeleton.bones.push(bones[j]);\n break;\n }\n }\n }\n newSkeleton.prepare();\n // Finish\n for (var i = 0; i < nodesToRootToAdd.length; i++) {\n newSkeleton.bones.push(nodesToRootToAdd[i]);\n }\n return newSkeleton;\n };\n /**\n * Imports a mesh and its geometries\n */\n var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {\n if (!newMesh) {\n newMesh = new BABYLON.Mesh(node.name || \"\", gltfRuntime.scene);\n newMesh.id = id;\n }\n if (!node.babylonNode) {\n return newMesh;\n }\n var subMaterials = [];\n var vertexData = null;\n var verticesStarts = new Array();\n var verticesCounts = new Array();\n var indexStarts = new Array();\n var indexCounts = new Array();\n for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {\n var meshID = meshes[meshIndex];\n var mesh = gltfRuntime.meshes[meshID];\n if (!mesh) {\n continue;\n }\n // Positions, normals and UVs\n for (var i = 0; i < mesh.primitives.length; i++) {\n // Temporary vertex data\n var tempVertexData = new BABYLON.VertexData();\n var primitive = mesh.primitives[i];\n if (primitive.mode !== 4) {\n // continue;\n }\n var attributes = primitive.attributes;\n var accessor = null;\n var buffer = null;\n // Set positions, normal and uvs\n for (var semantic in attributes) {\n // Link accessor and buffer view\n accessor = gltfRuntime.accessors[attributes[semantic]];\n buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);\n if (semantic === \"NORMAL\") {\n tempVertexData.normals = new Float32Array(buffer.length);\n tempVertexData.normals.set(buffer);\n }\n else if (semantic === \"POSITION\") {\n if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {\n tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);\n for (var j = 0; j < buffer.length; j += 4) {\n tempVertexData.positions[j] = buffer[j];\n tempVertexData.positions[j + 1] = buffer[j + 1];\n tempVertexData.positions[j + 2] = buffer[j + 2];\n }\n }\n else {\n tempVertexData.positions = new Float32Array(buffer.length);\n tempVertexData.positions.set(buffer);\n }\n verticesCounts.push(tempVertexData.positions.length);\n }\n else if (semantic.indexOf(\"TEXCOORD_\") !== -1) {\n var channel = Number(semantic.split(\"_\")[1]);\n var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? \"\" : (channel + 1));\n var uvs = new Float32Array(buffer.length);\n uvs.set(buffer);\n normalizeUVs(uvs);\n tempVertexData.set(uvs, uvKind);\n }\n else if (semantic === \"JOINT\") {\n tempVertexData.matricesIndices = new Float32Array(buffer.length);\n tempVertexData.matricesIndices.set(buffer);\n }\n else if (semantic === \"WEIGHT\") {\n tempVertexData.matricesWeights = new Float32Array(buffer.length);\n tempVertexData.matricesWeights.set(buffer);\n }\n else if (semantic === \"COLOR\") {\n tempVertexData.colors = new Float32Array(buffer.length);\n tempVertexData.colors.set(buffer);\n }\n }\n // Indices\n accessor = gltfRuntime.accessors[primitive.indices];\n if (accessor) {\n buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);\n tempVertexData.indices = new Int32Array(buffer.length);\n tempVertexData.indices.set(buffer);\n indexCounts.push(tempVertexData.indices.length);\n }\n else {\n // Set indices on the fly\n var indices = [];\n for (var j = 0; j < tempVertexData.positions.length / 3; j++) {\n indices.push(j);\n }\n tempVertexData.indices = new Int32Array(indices);\n indexCounts.push(tempVertexData.indices.length);\n }\n if (!vertexData) {\n vertexData = tempVertexData;\n }\n else {\n vertexData.merge(tempVertexData);\n }\n // Sub material\n var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);\n subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);\n // Update vertices start and index start\n verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);\n indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);\n }\n }\n var material;\n if (subMaterials.length > 1) {\n material = new BABYLON.MultiMaterial(\"multimat\" + id, gltfRuntime.scene);\n material.subMaterials = subMaterials;\n }\n else {\n material = new BABYLON.StandardMaterial(\"multimat\" + id, gltfRuntime.scene);\n }\n if (subMaterials.length === 1) {\n material = subMaterials[0];\n }\n if (!newMesh.material) {\n newMesh.material = material;\n }\n // Apply geometry\n new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);\n newMesh.computeWorldMatrix(true);\n // Apply submeshes\n newMesh.subMeshes = [];\n var index = 0;\n for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {\n var meshID = meshes[meshIndex];\n var mesh = gltfRuntime.meshes[meshID];\n if (!mesh) {\n continue;\n }\n for (var i = 0; i < mesh.primitives.length; i++) {\n if (mesh.primitives[i].mode !== 4) {\n //continue;\n }\n BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);\n index++;\n }\n }\n // Finish\n return newMesh;\n };\n /**\n * Configure node transformation from position, rotation and scaling\n */\n var configureNode = function (newNode, position, rotation, scaling) {\n if (newNode.position) {\n newNode.position = position;\n }\n if (newNode.rotationQuaternion || newNode.rotation) {\n newNode.rotationQuaternion = rotation;\n }\n if (newNode.scaling) {\n newNode.scaling = scaling;\n }\n };\n /**\n * Configures node from transformation matrix\n */\n var configureNodeFromMatrix = function (newNode, node, parent) {\n if (node.matrix) {\n var position = new BABYLON.Vector3(0, 0, 0);\n var rotation = new BABYLON.Quaternion();\n var scaling = new BABYLON.Vector3(0, 0, 0);\n var mat = BABYLON.Matrix.FromArray(node.matrix);\n mat.decompose(scaling, rotation, position);\n configureNode(newNode, position, rotation, scaling);\n }\n else if (node.translation && node.rotation && node.scale) {\n configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));\n }\n newNode.computeWorldMatrix(true);\n };\n /**\n * Imports a node\n */\n var importNode = function (gltfRuntime, node, id, parent) {\n var lastNode = null;\n if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {\n if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || \"\") === -1) {\n return null;\n }\n }\n // Meshes\n if (node.skin) {\n if (node.meshes) {\n var skin = gltfRuntime.skins[node.skin];\n var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);\n newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);\n if (newMesh.skeleton === null) {\n newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);\n if (!skin.babylonSkeleton) {\n skin.babylonSkeleton = newMesh.skeleton;\n }\n }\n lastNode = newMesh;\n }\n }\n else if (node.meshes) {\n /**\n * Improve meshes property\n */\n var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);\n lastNode = newMesh;\n }\n // Lights\n else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {\n var light = gltfRuntime.lights[node.light];\n if (light) {\n if (light.type === \"ambient\") {\n var ambienLight = light[light.type];\n var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);\n hemiLight.name = node.name || \"\";\n if (ambienLight.color) {\n hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);\n }\n lastNode = hemiLight;\n }\n else if (light.type === \"directional\") {\n var directionalLight = light[light.type];\n var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);\n dirLight.name = node.name || \"\";\n if (directionalLight.color) {\n dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);\n }\n lastNode = dirLight;\n }\n else if (light.type === \"point\") {\n var pointLight = light[light.type];\n var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);\n ptLight.name = node.name || \"\";\n if (pointLight.color) {\n ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);\n }\n lastNode = ptLight;\n }\n else if (light.type === \"spot\") {\n var spotLight = light[light.type];\n var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);\n spLight.name = node.name || \"\";\n if (spotLight.color) {\n spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);\n }\n if (spotLight.fallOfAngle) {\n spLight.angle = spotLight.fallOfAngle;\n }\n if (spotLight.fallOffExponent) {\n spLight.exponent = spotLight.fallOffExponent;\n }\n lastNode = spLight;\n }\n }\n }\n // Cameras\n else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {\n var camera = gltfRuntime.cameras[node.camera];\n if (camera) {\n if (camera.type === \"orthographic\") {\n var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);\n orthoCamera.name = node.name || \"\";\n orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;\n orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());\n lastNode = orthoCamera;\n }\n else if (camera.type === \"perspective\") {\n var perspectiveCamera = camera[camera.type];\n var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);\n persCamera.name = node.name || \"\";\n persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());\n if (!perspectiveCamera.aspectRatio) {\n perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();\n }\n if (perspectiveCamera.znear && perspectiveCamera.zfar) {\n persCamera.maxZ = perspectiveCamera.zfar;\n persCamera.minZ = perspectiveCamera.znear;\n }\n lastNode = persCamera;\n }\n }\n }\n // Empty node\n if (!node.jointName) {\n if (node.babylonNode) {\n return node.babylonNode;\n }\n else if (lastNode === null) {\n var dummy = new BABYLON.Mesh(node.name || \"\", gltfRuntime.scene);\n node.babylonNode = dummy;\n lastNode = dummy;\n }\n }\n if (lastNode !== null) {\n if (node.matrix && lastNode instanceof BABYLON.Mesh) {\n configureNodeFromMatrix(lastNode, node, parent);\n }\n else {\n var translation = node.translation || [0, 0, 0];\n var rotation = node.rotation || [0, 0, 0, 1];\n var scale = node.scale || [1, 1, 1];\n configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));\n }\n lastNode.updateCache(true);\n node.babylonNode = lastNode;\n }\n return lastNode;\n };\n /**\n * Traverses nodes and creates them\n */\n var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {\n if (meshIncluded === void 0) { meshIncluded = false; }\n var node = gltfRuntime.nodes[id];\n var newNode = null;\n if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {\n if (gltfRuntime.importMeshesNames.indexOf(node.name || \"\") !== -1 || gltfRuntime.importMeshesNames.length === 0) {\n meshIncluded = true;\n }\n else {\n meshIncluded = false;\n }\n }\n else {\n meshIncluded = true;\n }\n if (!node.jointName && meshIncluded) {\n newNode = importNode(gltfRuntime, node, id, parent);\n if (newNode !== null) {\n newNode.id = id;\n newNode.parent = parent;\n }\n }\n if (node.children) {\n for (var i = 0; i < node.children.length; i++) {\n traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);\n }\n }\n };\n /**\n * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)\n */\n var postLoad = function (gltfRuntime) {\n // Nodes\n var currentScene = gltfRuntime.currentScene;\n if (currentScene) {\n for (var i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n else {\n for (var thing in gltfRuntime.scenes) {\n currentScene = gltfRuntime.scenes[thing];\n for (var i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n }\n // Set animations\n loadAnimations(gltfRuntime);\n for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {\n var skeleton = gltfRuntime.scene.skeletons[i];\n gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);\n }\n };\n /**\n * onBind shaderrs callback to set uniforms and matrices\n */\n var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {\n var materialValues = material.values || technique.parameters;\n for (var unif in unTreatedUniforms) {\n var uniform = unTreatedUniforms[unif];\n var type = uniform.type;\n if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {\n if (uniform.semantic && !uniform.source && !uniform.node) {\n GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());\n }\n else if (uniform.semantic && (uniform.source || uniform.node)) {\n var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || \"\");\n if (source === null) {\n source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || \"\");\n }\n if (source === null) {\n continue;\n }\n GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());\n }\n }\n else {\n var value = materialValues[technique.uniforms[unif]];\n if (!value) {\n continue;\n }\n if (type === GLTF1.EParameterType.SAMPLER_2D) {\n var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;\n if (texture === null || texture === undefined) {\n continue;\n }\n shaderMaterial.getEffect().setTexture(unif, texture);\n }\n else {\n GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);\n }\n }\n }\n onSuccess(shaderMaterial);\n };\n /**\n * Prepare uniforms to send the only one time\n * Loads the appropriate textures\n */\n var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {\n var materialValues = material.values || technique.parameters;\n var techniqueUniforms = technique.uniforms;\n /**\n * Prepare values here (not matrices)\n */\n for (var unif in unTreatedUniforms) {\n var uniform = unTreatedUniforms[unif];\n var type = uniform.type;\n var value = materialValues[techniqueUniforms[unif]];\n if (value === undefined) {\n // In case the value is the same for all materials\n value = uniform.value;\n }\n if (!value) {\n continue;\n }\n var onLoadTexture = function (uniformName) {\n return function (texture) {\n if (uniform.value && uniformName) {\n // Static uniform\n shaderMaterial.setTexture(uniformName, texture);\n delete unTreatedUniforms[uniformName];\n }\n };\n };\n // Texture (sampler2D)\n if (type === GLTF1.EParameterType.SAMPLER_2D) {\n GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });\n }\n // Others\n else {\n if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {\n // Static uniform\n delete unTreatedUniforms[unif];\n }\n }\n }\n };\n /**\n * Shader compilation failed\n */\n var onShaderCompileError = function (program, shaderMaterial, onError) {\n return function (effect, error) {\n shaderMaterial.dispose(true);\n onError(\"Cannot compile program named \" + program.name + \". Error: \" + error + \". Default material will be applied\");\n };\n };\n /**\n * Shader compilation success\n */\n var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {\n return function (_) {\n prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);\n shaderMaterial.onBind = function (mesh) {\n onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);\n };\n };\n };\n /**\n * Returns the appropriate uniform if already handled by babylon\n */\n var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {\n for (var unif in technique.uniforms) {\n var uniform = technique.uniforms[unif];\n var uniformParameter = technique.parameters[uniform];\n if (tokenizer.currentIdentifier === unif) {\n if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {\n var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);\n if (transformIndex !== -1) {\n delete unTreatedUniforms[unif];\n return babylonTransforms[transformIndex];\n }\n }\n }\n }\n return tokenizer.currentIdentifier;\n };\n /**\n * All shaders loaded. Create materials one by one\n */\n var importMaterials = function (gltfRuntime) {\n // Create materials\n for (var mat in gltfRuntime.materials) {\n GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });\n }\n };\n /**\n * Implementation of the base glTF spec\n */\n var GLTFLoaderBase = /** @class */ (function () {\n function GLTFLoaderBase() {\n }\n GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {\n var gltfRuntime = {\n extensions: {},\n accessors: {},\n buffers: {},\n bufferViews: {},\n meshes: {},\n lights: {},\n cameras: {},\n nodes: {},\n images: {},\n textures: {},\n shaders: {},\n programs: {},\n samplers: {},\n techniques: {},\n materials: {},\n animations: {},\n skins: {},\n extensionsUsed: [],\n scenes: {},\n buffersCount: 0,\n shaderscount: 0,\n scene: scene,\n rootUrl: rootUrl,\n loadedBufferCount: 0,\n loadedBufferViews: {},\n loadedShaderCount: 0,\n importOnlyMeshes: false,\n dummyNodes: []\n };\n // Parse\n if (parsedData.extensions) {\n parseObject(parsedData.extensions, \"extensions\", gltfRuntime);\n }\n if (parsedData.extensionsUsed) {\n parseObject(parsedData.extensionsUsed, \"extensionsUsed\", gltfRuntime);\n }\n if (parsedData.buffers) {\n parseBuffers(parsedData.buffers, gltfRuntime);\n }\n if (parsedData.bufferViews) {\n parseObject(parsedData.bufferViews, \"bufferViews\", gltfRuntime);\n }\n if (parsedData.accessors) {\n parseObject(parsedData.accessors, \"accessors\", gltfRuntime);\n }\n if (parsedData.meshes) {\n parseObject(parsedData.meshes, \"meshes\", gltfRuntime);\n }\n if (parsedData.lights) {\n parseObject(parsedData.lights, \"lights\", gltfRuntime);\n }\n if (parsedData.cameras) {\n parseObject(parsedData.cameras, \"cameras\", gltfRuntime);\n }\n if (parsedData.nodes) {\n parseObject(parsedData.nodes, \"nodes\", gltfRuntime);\n }\n if (parsedData.images) {\n parseObject(parsedData.images, \"images\", gltfRuntime);\n }\n if (parsedData.textures) {\n parseObject(parsedData.textures, \"textures\", gltfRuntime);\n }\n if (parsedData.shaders) {\n parseShaders(parsedData.shaders, gltfRuntime);\n }\n if (parsedData.programs) {\n parseObject(parsedData.programs, \"programs\", gltfRuntime);\n }\n if (parsedData.samplers) {\n parseObject(parsedData.samplers, \"samplers\", gltfRuntime);\n }\n if (parsedData.techniques) {\n parseObject(parsedData.techniques, \"techniques\", gltfRuntime);\n }\n if (parsedData.materials) {\n parseObject(parsedData.materials, \"materials\", gltfRuntime);\n }\n if (parsedData.animations) {\n parseObject(parsedData.animations, \"animations\", gltfRuntime);\n }\n if (parsedData.skins) {\n parseObject(parsedData.skins, \"skins\", gltfRuntime);\n }\n if (parsedData.scenes) {\n gltfRuntime.scenes = parsedData.scenes;\n }\n if (parsedData.scene && parsedData.scenes) {\n gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];\n }\n return gltfRuntime;\n };\n GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {\n var buffer = gltfRuntime.buffers[id];\n if (BABYLON.Tools.IsBase64(buffer.uri)) {\n setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });\n }\n else {\n BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {\n if (request) {\n onError(request.status + \" \" + request.statusText);\n }\n });\n }\n };\n GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {\n var texture = gltfRuntime.textures[id];\n if (!texture || !texture.source) {\n onError(\"\");\n return;\n }\n if (texture.babylonTexture) {\n onSuccess(null);\n return;\n }\n var source = gltfRuntime.images[texture.source];\n if (BABYLON.Tools.IsBase64(source.uri)) {\n setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });\n }\n else {\n BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {\n if (request) {\n onError(request.status + \" \" + request.statusText);\n }\n });\n }\n };\n GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {\n var texture = gltfRuntime.textures[id];\n if (texture.babylonTexture) {\n onSuccess(texture.babylonTexture);\n return;\n }\n var sampler = gltfRuntime.samplers[texture.sampler];\n var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||\n (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||\n (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||\n (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);\n var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;\n var blob = new Blob([buffer]);\n var blobURL = URL.createObjectURL(blob);\n var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };\n var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);\n if (sampler.wrapS !== undefined) {\n newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);\n }\n if (sampler.wrapT !== undefined) {\n newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);\n }\n newTexture.name = id;\n texture.babylonTexture = newTexture;\n onSuccess(newTexture);\n };\n GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {\n var shader = gltfRuntime.shaders[id];\n if (BABYLON.Tools.IsBase64(shader.uri)) {\n var shaderString = atob(shader.uri.split(\",\")[1]);\n if (onSuccess) {\n onSuccess(shaderString);\n }\n }\n else {\n BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {\n if (request && onError) {\n onError(request.status + \" \" + request.statusText);\n }\n });\n }\n };\n GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {\n var material = gltfRuntime.materials[id];\n if (!material.technique) {\n if (onError) {\n onError(\"No technique found.\");\n }\n return;\n }\n var technique = gltfRuntime.techniques[material.technique];\n if (!technique) {\n var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);\n defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);\n defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;\n onSuccess(defaultMaterial);\n return;\n }\n var program = gltfRuntime.programs[technique.program];\n var states = technique.states;\n var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + \"VertexShader\"];\n var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + \"PixelShader\"];\n var newVertexShader = \"\";\n var newPixelShader = \"\";\n var vertexTokenizer = new Tokenizer(vertexShader);\n var pixelTokenizer = new Tokenizer(pixelShader);\n var unTreatedUniforms = {};\n var uniforms = [];\n var attributes = [];\n var samplers = [];\n // Fill uniform, sampler2D and attributes\n for (var unif in technique.uniforms) {\n var uniform = technique.uniforms[unif];\n var uniformParameter = technique.parameters[uniform];\n unTreatedUniforms[unif] = uniformParameter;\n if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {\n var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);\n if (transformIndex !== -1) {\n uniforms.push(babylonTransforms[transformIndex]);\n delete unTreatedUniforms[unif];\n }\n else {\n uniforms.push(unif);\n }\n }\n else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {\n samplers.push(unif);\n }\n else {\n uniforms.push(unif);\n }\n }\n for (var attr in technique.attributes) {\n var attribute = technique.attributes[attr];\n var attributeParameter = technique.parameters[attribute];\n if (attributeParameter.semantic) {\n attributes.push(getAttribute(attributeParameter));\n }\n }\n // Configure vertex shader\n while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {\n var tokenType = vertexTokenizer.currentToken;\n if (tokenType !== ETokenType.IDENTIFIER) {\n newVertexShader += vertexTokenizer.currentString;\n continue;\n }\n var foundAttribute = false;\n for (var attr in technique.attributes) {\n var attribute = technique.attributes[attr];\n var attributeParameter = technique.parameters[attribute];\n if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {\n newVertexShader += getAttribute(attributeParameter);\n foundAttribute = true;\n break;\n }\n }\n if (foundAttribute) {\n continue;\n }\n newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);\n }\n // Configure pixel shader\n while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {\n var tokenType = pixelTokenizer.currentToken;\n if (tokenType !== ETokenType.IDENTIFIER) {\n newPixelShader += pixelTokenizer.currentString;\n continue;\n }\n newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);\n }\n // Create shader material\n var shaderPath = {\n vertex: program.vertexShader + id,\n fragment: program.fragmentShader + id\n };\n var options = {\n attributes: attributes,\n uniforms: uniforms,\n samplers: samplers,\n needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1\n };\n BABYLON.Effect.ShadersStore[program.vertexShader + id + \"VertexShader\"] = newVertexShader;\n BABYLON.Effect.ShadersStore[program.fragmentShader + id + \"PixelShader\"] = newPixelShader;\n var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);\n shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);\n shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);\n shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;\n if (states && states.functions) {\n var functions = states.functions;\n if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {\n shaderMaterial.backFaceCulling = false;\n }\n var blendFunc = functions.blendFuncSeparate;\n if (blendFunc) {\n if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;\n }\n else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;\n }\n else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;\n }\n else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;\n }\n else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;\n }\n else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;\n }\n }\n }\n };\n return GLTFLoaderBase;\n }());\n GLTF1.GLTFLoaderBase = GLTFLoaderBase;\n /**\n * glTF V1 Loader\n */\n var GLTFLoader = /** @class */ (function () {\n function GLTFLoader() {\n this.state = null;\n }\n GLTFLoader.RegisterExtension = function (extension) {\n if (GLTFLoader.Extensions[extension.name]) {\n BABYLON.Tools.Error(\"Tool with the same name \\\"\" + extension.name + \"\\\" already exists\");\n return;\n }\n GLTFLoader.Extensions[extension.name] = extension;\n };\n GLTFLoader.prototype.dispose = function () {\n // do nothing\n };\n GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {\n var _this = this;\n scene.useRightHandedSystem = true;\n GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {\n gltfRuntime.importOnlyMeshes = true;\n if (meshesNames === \"\") {\n gltfRuntime.importMeshesNames = [];\n }\n else if (typeof meshesNames === \"string\") {\n gltfRuntime.importMeshesNames = [meshesNames];\n }\n else if (meshesNames && !(meshesNames instanceof Array)) {\n gltfRuntime.importMeshesNames = [meshesNames];\n }\n else {\n gltfRuntime.importMeshesNames = [];\n BABYLON.Tools.Warn(\"Argument meshesNames must be of type string or string[]\");\n }\n // Create nodes\n _this._createNodes(gltfRuntime);\n var meshes = new Array();\n var skeletons = new Array();\n // Fill arrays of meshes and skeletons\n for (var nde in gltfRuntime.nodes) {\n var node = gltfRuntime.nodes[nde];\n if (node.babylonNode instanceof BABYLON.AbstractMesh) {\n meshes.push(node.babylonNode);\n }\n }\n for (var skl in gltfRuntime.skins) {\n var skin = gltfRuntime.skins[skl];\n if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {\n skeletons.push(skin.babylonSkeleton);\n }\n }\n // Load buffers, shaders, materials, etc.\n _this._loadBuffersAsync(gltfRuntime, function () {\n _this._loadShadersAsync(gltfRuntime, function () {\n importMaterials(gltfRuntime);\n postLoad(gltfRuntime);\n if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {\n onSuccess(meshes, skeletons);\n }\n });\n }, onProgress);\n if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {\n onSuccess(meshes, skeletons);\n }\n }, onError);\n return true;\n };\n /**\n * Imports one or more meshes from a loaded gltf file and adds them to the scene\n * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file\n * @param scene the scene the meshes should be added to\n * @param data gltf data containing information of the meshes in a loaded file\n * @param rootUrl root url to load from\n * @param onProgress event that fires when loading progress has occured\n * @returns a promise containg the loaded meshes, particles, skeletons and animations\n */\n GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {\n resolve({\n meshes: meshes,\n particleSystems: [],\n skeletons: skeletons,\n animationGroups: []\n });\n }, onProgress, function (message) {\n reject(new Error(message));\n });\n });\n };\n GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {\n var _this = this;\n scene.useRightHandedSystem = true;\n GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {\n // Load runtime extensios\n GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {\n // Create nodes\n _this._createNodes(gltfRuntime);\n // Load buffers, shaders, materials, etc.\n _this._loadBuffersAsync(gltfRuntime, function () {\n _this._loadShadersAsync(gltfRuntime, function () {\n importMaterials(gltfRuntime);\n postLoad(gltfRuntime);\n if (!BABYLON.GLTFFileLoader.IncrementalLoading) {\n onSuccess();\n }\n });\n });\n if (BABYLON.GLTFFileLoader.IncrementalLoading) {\n onSuccess();\n }\n }, onError);\n }, onError);\n };\n /**\n * Imports all objects from a loaded gltf file and adds them to the scene\n * @param scene the scene the objects should be added to\n * @param data gltf data containing information of the meshes in a loaded file\n * @param rootUrl root url to load from\n * @param onProgress event that fires when loading progress has occured\n * @returns a promise which completes when objects have been loaded to the scene\n */\n GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this._loadAsync(scene, data, rootUrl, function () {\n resolve();\n }, onProgress, function (message) {\n reject(new Error(message));\n });\n });\n };\n GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {\n var hasShaders = false;\n var processShader = function (sha, shader) {\n GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {\n if (shaderString instanceof ArrayBuffer) {\n return;\n }\n gltfRuntime.loadedShaderCount++;\n if (shaderString) {\n BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? \"VertexShader\" : \"PixelShader\")] = shaderString;\n }\n if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {\n onload();\n }\n }, function () {\n BABYLON.Tools.Error(\"Error when loading shader program named \" + sha + \" located at \" + shader.uri);\n });\n };\n for (var sha in gltfRuntime.shaders) {\n hasShaders = true;\n var shader = gltfRuntime.shaders[sha];\n if (shader) {\n processShader.bind(this, sha, shader)();\n }\n else {\n BABYLON.Tools.Error(\"No shader named: \" + sha);\n }\n }\n if (!hasShaders) {\n onload();\n }\n };\n ;\n GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {\n var hasBuffers = false;\n var processBuffer = function (buf, buffer) {\n GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {\n gltfRuntime.loadedBufferCount++;\n if (bufferView) {\n if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {\n BABYLON.Tools.Error(\"Buffer named \" + buf + \" is length \" + bufferView.byteLength + \". Expected: \" + buffer.byteLength); // Improve error message\n }\n gltfRuntime.loadedBufferViews[buf] = bufferView;\n }\n if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {\n onLoad();\n }\n }, function () {\n BABYLON.Tools.Error(\"Error when loading buffer named \" + buf + \" located at \" + buffer.uri);\n });\n };\n for (var buf in gltfRuntime.buffers) {\n hasBuffers = true;\n var buffer = gltfRuntime.buffers[buf];\n if (buffer) {\n processBuffer.bind(this, buf, buffer)();\n }\n else {\n BABYLON.Tools.Error(\"No buffer named: \" + buf);\n }\n }\n if (!hasBuffers) {\n onLoad();\n }\n };\n GLTFLoader.prototype._createNodes = function (gltfRuntime) {\n var currentScene = gltfRuntime.currentScene;\n if (currentScene) {\n // Only one scene even if multiple scenes are defined\n for (var i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n else {\n // Load all scenes\n for (var thing in gltfRuntime.scenes) {\n currentScene = gltfRuntime.scenes[thing];\n for (var i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n }\n };\n GLTFLoader.Extensions = {};\n return GLTFLoader;\n }());\n GLTF1.GLTFLoader = GLTFLoader;\n ;\n BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };\n })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFLoader.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF1;\n (function (GLTF1) {\n /**\n * Utils functions for GLTF\n */\n var GLTFUtils = /** @class */ (function () {\n function GLTFUtils() {\n }\n /**\n * Sets the given \"parameter\" matrix\n * @param scene: the {BABYLON.Scene} object\n * @param source: the source node where to pick the matrix\n * @param parameter: the GLTF technique parameter\n * @param uniformName: the name of the shader's uniform\n * @param shaderMaterial: the shader material\n */\n GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {\n var mat = null;\n if (parameter.semantic === \"MODEL\") {\n mat = source.getWorldMatrix();\n }\n else if (parameter.semantic === \"PROJECTION\") {\n mat = scene.getProjectionMatrix();\n }\n else if (parameter.semantic === \"VIEW\") {\n mat = scene.getViewMatrix();\n }\n else if (parameter.semantic === \"MODELVIEWINVERSETRANSPOSE\") {\n mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());\n }\n else if (parameter.semantic === \"MODELVIEW\") {\n mat = source.getWorldMatrix().multiply(scene.getViewMatrix());\n }\n else if (parameter.semantic === \"MODELVIEWPROJECTION\") {\n mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());\n }\n else if (parameter.semantic === \"MODELINVERSE\") {\n mat = source.getWorldMatrix().invert();\n }\n else if (parameter.semantic === \"VIEWINVERSE\") {\n mat = scene.getViewMatrix().invert();\n }\n else if (parameter.semantic === \"PROJECTIONINVERSE\") {\n mat = scene.getProjectionMatrix().invert();\n }\n else if (parameter.semantic === \"MODELVIEWINVERSE\") {\n mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();\n }\n else if (parameter.semantic === \"MODELVIEWPROJECTIONINVERSE\") {\n mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();\n }\n else if (parameter.semantic === \"MODELINVERSETRANSPOSE\") {\n mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());\n }\n else {\n debugger;\n }\n if (mat) {\n switch (parameter.type) {\n case GLTF1.EParameterType.FLOAT_MAT2:\n shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));\n break;\n case GLTF1.EParameterType.FLOAT_MAT3:\n shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));\n break;\n case GLTF1.EParameterType.FLOAT_MAT4:\n shaderMaterial.setMatrix(uniformName, mat);\n break;\n default: break;\n }\n }\n };\n /**\n * Sets the given \"parameter\" matrix\n * @param shaderMaterial: the shader material\n * @param uniform: the name of the shader's uniform\n * @param value: the value of the uniform\n * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)\n */\n GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {\n switch (type) {\n case GLTF1.EParameterType.FLOAT:\n shaderMaterial.setFloat(uniform, value);\n return true;\n case GLTF1.EParameterType.FLOAT_VEC2:\n shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));\n return true;\n case GLTF1.EParameterType.FLOAT_VEC3:\n shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));\n return true;\n case GLTF1.EParameterType.FLOAT_VEC4:\n shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));\n return true;\n default: return false;\n }\n };\n /**\n * Returns the wrap mode of the texture\n * @param mode: the mode value\n */\n GLTFUtils.GetWrapMode = function (mode) {\n switch (mode) {\n case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;\n case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;\n case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;\n default: return BABYLON.Texture.WRAP_ADDRESSMODE;\n }\n };\n /**\n * Returns the byte stride giving an accessor\n * @param accessor: the GLTF accessor objet\n */\n GLTFUtils.GetByteStrideFromType = function (accessor) {\n // Needs this function since \"byteStride\" isn't requiered in glTF format\n var type = accessor.type;\n switch (type) {\n case \"VEC2\": return 2;\n case \"VEC3\": return 3;\n case \"VEC4\": return 4;\n case \"MAT2\": return 4;\n case \"MAT3\": return 9;\n case \"MAT4\": return 16;\n default: return 1;\n }\n };\n /**\n * Returns the texture filter mode giving a mode value\n * @param mode: the filter mode value\n */\n GLTFUtils.GetTextureFilterMode = function (mode) {\n switch (mode) {\n case GLTF1.ETextureFilterType.LINEAR:\n case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:\n case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;\n case GLTF1.ETextureFilterType.NEAREST:\n case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;\n default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;\n }\n };\n GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {\n var byteOffset = bufferView.byteOffset + byteOffset;\n var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];\n if (byteOffset + byteLength > loadedBufferView.byteLength) {\n throw new Error(\"Buffer access is out of range\");\n }\n var buffer = loadedBufferView.buffer;\n byteOffset += loadedBufferView.byteOffset;\n switch (componentType) {\n case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);\n case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);\n case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);\n case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);\n default: return new Float32Array(buffer, byteOffset, byteLength);\n }\n };\n /**\n * Returns a buffer from its accessor\n * @param gltfRuntime: the GLTF runtime\n * @param accessor: the GLTF accessor\n */\n GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {\n var bufferView = gltfRuntime.bufferViews[accessor.bufferView];\n var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);\n return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);\n };\n /**\n * Decodes a buffer view into a string\n * @param view: the buffer view\n */\n GLTFUtils.DecodeBufferToText = function (view) {\n var result = \"\";\n var length = view.byteLength;\n for (var i = 0; i < length; ++i) {\n result += String.fromCharCode(view[i]);\n }\n return result;\n };\n /**\n * Returns the default material of gltf. Related to\n * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material\n * @param scene: the Babylon.js scene\n */\n GLTFUtils.GetDefaultMaterial = function (scene) {\n if (!GLTFUtils._DefaultMaterial) {\n BABYLON.Effect.ShadersStore[\"GLTFDefaultMaterialVertexShader\"] = [\n \"precision highp float;\",\n \"\",\n \"uniform mat4 worldView;\",\n \"uniform mat4 projection;\",\n \"\",\n \"attribute vec3 position;\",\n \"\",\n \"void main(void)\",\n \"{\",\n \" gl_Position = projection * worldView * vec4(position, 1.0);\",\n \"}\"\n ].join(\"\\n\");\n BABYLON.Effect.ShadersStore[\"GLTFDefaultMaterialPixelShader\"] = [\n \"precision highp float;\",\n \"\",\n \"uniform vec4 u_emission;\",\n \"\",\n \"void main(void)\",\n \"{\",\n \" gl_FragColor = u_emission;\",\n \"}\"\n ].join(\"\\n\");\n var shaderPath = {\n vertex: \"GLTFDefaultMaterial\",\n fragment: \"GLTFDefaultMaterial\"\n };\n var options = {\n attributes: [\"position\"],\n uniforms: [\"worldView\", \"projection\", \"u_emission\"],\n samplers: new Array(),\n needAlphaBlending: false\n };\n GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial(\"GLTFDefaultMaterial\", scene, shaderPath, options);\n GLTFUtils._DefaultMaterial.setColor4(\"u_emission\", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));\n }\n return GLTFUtils._DefaultMaterial;\n };\n // The GLTF default material\n GLTFUtils._DefaultMaterial = null;\n return GLTFUtils;\n }());\n GLTF1.GLTFUtils = GLTFUtils;\n })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFLoaderUtils.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF1;\n (function (GLTF1) {\n var GLTFLoaderExtension = /** @class */ (function () {\n function GLTFLoaderExtension(name) {\n this._name = name;\n }\n Object.defineProperty(GLTFLoaderExtension.prototype, \"name\", {\n get: function () {\n return this._name;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Defines an override for loading the runtime\n * Return true to stop further extensions from loading the runtime\n */\n GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {\n return false;\n };\n /**\n * Defines an onverride for creating gltf runtime\n * Return true to stop further extensions from creating the runtime\n */\n GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {\n return false;\n };\n /**\n * Defines an override for loading buffers\n * Return true to stop further extensions from loading this buffer\n */\n GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {\n return false;\n };\n /**\n * Defines an override for loading texture buffers\n * Return true to stop further extensions from loading this texture data\n */\n GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {\n return false;\n };\n /**\n * Defines an override for creating textures\n * Return true to stop further extensions from loading this texture\n */\n GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {\n return false;\n };\n /**\n * Defines an override for loading shader strings\n * Return true to stop further extensions from loading this shader data\n */\n GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {\n return false;\n };\n /**\n * Defines an override for loading materials\n * Return true to stop further extensions from loading this material\n */\n GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {\n return false;\n };\n // ---------\n // Utilities\n // ---------\n GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);\n }, function () {\n setTimeout(function () {\n if (!onSuccess) {\n return;\n }\n onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));\n });\n });\n };\n GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);\n }, function () {\n setTimeout(function () {\n onSuccess();\n });\n });\n };\n GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);\n }, function () {\n GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);\n });\n };\n GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {\n if (buffer) {\n GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);\n }\n }, onError);\n };\n GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);\n }, function () {\n GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);\n });\n };\n GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);\n }, function () {\n GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);\n });\n };\n GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);\n }, function () {\n GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);\n });\n };\n GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {\n GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {\n return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);\n }, function () {\n GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);\n });\n };\n GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {\n for (var extensionName in GLTF1.GLTFLoader.Extensions) {\n var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];\n if (func(loaderExtension)) {\n return;\n }\n }\n defaultFunc();\n };\n return GLTFLoaderExtension;\n }());\n GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;\n })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFLoaderExtension.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF1;\n (function (GLTF1) {\n var BinaryExtensionBufferName = \"binary_glTF\";\n ;\n ;\n var GLTFBinaryExtension = /** @class */ (function (_super) {\n __extends(GLTFBinaryExtension, _super);\n function GLTFBinaryExtension() {\n return _super.call(this, \"KHR_binary_glTF\") || this;\n }\n GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {\n var extensionsUsed = data.json.extensionsUsed;\n if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {\n return false;\n }\n this._bin = data.bin;\n onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));\n return true;\n };\n GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {\n if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {\n return false;\n }\n if (id !== BinaryExtensionBufferName) {\n return false;\n }\n onSuccess(this._bin);\n return true;\n };\n GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {\n var texture = gltfRuntime.textures[id];\n var source = gltfRuntime.images[texture.source];\n if (!source.extensions || !(this.name in source.extensions)) {\n return false;\n }\n var sourceExt = source.extensions[this.name];\n var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];\n var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);\n onSuccess(buffer);\n return true;\n };\n GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {\n var shader = gltfRuntime.shaders[id];\n if (!shader.extensions || !(this.name in shader.extensions)) {\n return false;\n }\n var binaryExtensionShader = shader.extensions[this.name];\n var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];\n var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);\n setTimeout(function () {\n var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);\n onSuccess(shaderString);\n });\n return true;\n };\n return GLTFBinaryExtension;\n }(GLTF1.GLTFLoaderExtension));\n GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;\n GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());\n })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFBinaryExtension.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF1;\n (function (GLTF1) {\n ;\n ;\n ;\n var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {\n __extends(GLTFMaterialsCommonExtension, _super);\n function GLTFMaterialsCommonExtension() {\n return _super.call(this, \"KHR_materials_common\") || this;\n }\n GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {\n if (!gltfRuntime.extensions)\n return false;\n var extension = gltfRuntime.extensions[this.name];\n if (!extension)\n return false;\n // Create lights\n var lights = extension.lights;\n if (lights) {\n for (var thing in lights) {\n var light = lights[thing];\n switch (light.type) {\n case \"ambient\":\n var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);\n var ambient = light.ambient;\n if (ambient) {\n ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);\n }\n break;\n case \"point\":\n var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);\n var point = light.point;\n if (point) {\n pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);\n }\n break;\n case \"directional\":\n var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);\n var directional = light.directional;\n if (directional) {\n dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);\n }\n break;\n case \"spot\":\n var spot = light.spot;\n if (spot) {\n var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);\n spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);\n }\n break;\n default:\n BABYLON.Tools.Warn(\"GLTF Material Common extension: light type \\\"\" + light.type + \"\\” not supported\");\n break;\n }\n }\n }\n return false;\n };\n GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {\n var material = gltfRuntime.materials[id];\n if (!material || !material.extensions)\n return false;\n var extension = material.extensions[this.name];\n if (!extension)\n return false;\n var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);\n standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;\n if (extension.technique === \"CONSTANT\") {\n standardMaterial.disableLighting = true;\n }\n standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;\n standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;\n standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;\n // Ambient\n if (typeof extension.values.ambient === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, \"ambientTexture\", onError);\n }\n else {\n standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);\n }\n // Diffuse\n if (typeof extension.values.diffuse === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, \"diffuseTexture\", onError);\n }\n else {\n standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);\n }\n // Emission\n if (typeof extension.values.emission === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, \"emissiveTexture\", onError);\n }\n else {\n standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);\n }\n // Specular\n if (typeof extension.values.specular === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, \"specularTexture\", onError);\n }\n else {\n standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);\n }\n return true;\n };\n GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {\n // Create buffer from texture url\n GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {\n // Create texture from buffer\n GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);\n }, onError);\n };\n return GLTFMaterialsCommonExtension;\n }(GLTF1.GLTFLoaderExtension));\n GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;\n GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());\n })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map\n\n\n\n\n//# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map\n\n\n/**\n * Defines the module used to import/export glTF 2.0 assets\n */\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n /** @hidden */\n var _ArrayItem = /** @class */ (function () {\n function _ArrayItem() {\n }\n _ArrayItem.Assign = function (values) {\n if (values) {\n for (var index = 0; index < values.length; index++) {\n values[index]._index = index;\n }\n }\n };\n return _ArrayItem;\n }());\n GLTF2._ArrayItem = _ArrayItem;\n /** @hidden */\n var GLTFLoader = /** @class */ (function () {\n function GLTFLoader(parent) {\n this._completePromises = new Array();\n this._disposed = false;\n this._state = null;\n this._extensions = {};\n this._defaultSampler = {};\n this._defaultBabylonMaterials = {};\n this._requests = new Array();\n this._parent = parent;\n }\n GLTFLoader._Register = function (name, factory) {\n if (GLTFLoader._ExtensionFactories[name]) {\n BABYLON.Tools.Error(\"Extension with the name '\" + name + \"' already exists\");\n return;\n }\n GLTFLoader._ExtensionFactories[name] = factory;\n // Keep the order of registration so that extensions registered first are called first.\n GLTFLoader._ExtensionNames.push(name);\n };\n Object.defineProperty(GLTFLoader.prototype, \"state\", {\n get: function () {\n return this._state;\n },\n enumerable: true,\n configurable: true\n });\n GLTFLoader.prototype.dispose = function () {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {\n var request = _a[_i];\n request.abort();\n }\n this._requests.length = 0;\n delete this._gltf;\n delete this._babylonScene;\n this._completePromises.length = 0;\n for (var name_1 in this._extensions) {\n this._extensions[name_1].dispose();\n }\n this._extensions = {};\n delete this._rootBabylonMesh;\n delete this._progressCallback;\n this._parent._clear();\n };\n GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {\n var _this = this;\n return Promise.resolve().then(function () {\n _this._babylonScene = scene;\n _this._rootUrl = rootUrl;\n _this._progressCallback = onProgress;\n _this._loadData(data);\n var nodes = null;\n if (meshesNames) {\n var nodeMap_1 = {};\n if (_this._gltf.nodes) {\n for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {\n var node = _a[_i];\n if (node.name) {\n nodeMap_1[node.name] = node._index;\n }\n }\n }\n var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];\n nodes = names.map(function (name) {\n var node = nodeMap_1[name];\n if (node === undefined) {\n throw new Error(\"Failed to find node '\" + name + \"'\");\n }\n return node;\n });\n }\n return _this._loadAsync(nodes).then(function () {\n return {\n meshes: _this._getMeshes(),\n particleSystems: [],\n skeletons: _this._getSkeletons(),\n animationGroups: _this._getAnimationGroups()\n };\n });\n });\n };\n GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {\n var _this = this;\n return Promise.resolve().then(function () {\n _this._babylonScene = scene;\n _this._rootUrl = rootUrl;\n _this._progressCallback = onProgress;\n _this._loadData(data);\n return _this._loadAsync(null);\n });\n };\n GLTFLoader.prototype._loadAsync = function (nodes) {\n var _this = this;\n return Promise.resolve().then(function () {\n _this._loadExtensions();\n _this._checkExtensions();\n var loadingToReadyCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + \" => \" + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.READY];\n var loadingToCompleteCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + \" => \" + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.COMPLETE];\n _this._parent._startPerformanceCounter(loadingToReadyCounterName);\n _this._parent._startPerformanceCounter(loadingToCompleteCounterName);\n _this._setState(BABYLON.GLTFLoaderState.LOADING);\n GLTF2.GLTFLoaderExtension._OnLoading(_this);\n var promises = new Array();\n if (nodes) {\n promises.push(_this._loadSceneAsync(\"#/nodes\", { nodes: nodes, _index: -1 }));\n }\n else {\n var scene = GLTFLoader._GetProperty(\"#/scene\", _this._gltf.scenes, _this._gltf.scene || 0);\n promises.push(_this._loadSceneAsync(\"#/scenes/\" + scene._index, scene));\n }\n if (_this._parent.compileMaterials) {\n promises.push(_this._compileMaterialsAsync());\n }\n if (_this._parent.compileShadowGenerators) {\n promises.push(_this._compileShadowGeneratorsAsync());\n }\n var resultPromise = Promise.all(promises).then(function () {\n _this._setState(BABYLON.GLTFLoaderState.READY);\n GLTF2.GLTFLoaderExtension._OnReady(_this);\n _this._startAnimations();\n });\n resultPromise.then(function () {\n _this._parent._endPerformanceCounter(loadingToReadyCounterName);\n BABYLON.Tools.SetImmediate(function () {\n if (!_this._disposed) {\n Promise.all(_this._completePromises).then(function () {\n _this._parent._endPerformanceCounter(loadingToCompleteCounterName);\n _this._setState(BABYLON.GLTFLoaderState.COMPLETE);\n _this._parent.onCompleteObservable.notifyObservers(undefined);\n _this._parent.onCompleteObservable.clear();\n _this.dispose();\n }, function (error) {\n _this._parent.onErrorObservable.notifyObservers(error);\n _this._parent.onErrorObservable.clear();\n _this.dispose();\n });\n }\n });\n });\n return resultPromise;\n }, function (error) {\n if (!_this._disposed) {\n _this._parent.onErrorObservable.notifyObservers(error);\n _this._parent.onErrorObservable.clear();\n _this.dispose();\n throw error;\n }\n });\n };\n GLTFLoader.prototype._loadData = function (data) {\n this._gltf = data.json;\n this._setupData();\n if (data.bin) {\n var buffers = this._gltf.buffers;\n if (buffers && buffers[0] && !buffers[0].uri) {\n var binaryBuffer = buffers[0];\n if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {\n BABYLON.Tools.Warn(\"Binary buffer length (\" + binaryBuffer.byteLength + \") from JSON does not match chunk length (\" + data.bin.byteLength + \")\");\n }\n binaryBuffer._data = Promise.resolve(data.bin);\n }\n else {\n BABYLON.Tools.Warn(\"Unexpected BIN chunk\");\n }\n }\n };\n GLTFLoader.prototype._setupData = function () {\n _ArrayItem.Assign(this._gltf.accessors);\n _ArrayItem.Assign(this._gltf.animations);\n _ArrayItem.Assign(this._gltf.buffers);\n _ArrayItem.Assign(this._gltf.bufferViews);\n _ArrayItem.Assign(this._gltf.cameras);\n _ArrayItem.Assign(this._gltf.images);\n _ArrayItem.Assign(this._gltf.materials);\n _ArrayItem.Assign(this._gltf.meshes);\n _ArrayItem.Assign(this._gltf.nodes);\n _ArrayItem.Assign(this._gltf.samplers);\n _ArrayItem.Assign(this._gltf.scenes);\n _ArrayItem.Assign(this._gltf.skins);\n _ArrayItem.Assign(this._gltf.textures);\n if (this._gltf.nodes) {\n var nodeParents = {};\n for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {\n var node = _a[_i];\n if (node.children) {\n for (var _b = 0, _c = node.children; _b < _c.length; _b++) {\n var index = _c[_b];\n nodeParents[index] = node._index;\n }\n }\n }\n var rootNode = this._createRootNode();\n for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {\n var node = _e[_d];\n var parentIndex = nodeParents[node._index];\n node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];\n }\n }\n };\n GLTFLoader.prototype._loadExtensions = function () {\n for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {\n var name_2 = _a[_i];\n var extension = GLTFLoader._ExtensionFactories[name_2](this);\n this._extensions[name_2] = extension;\n this._parent.onExtensionLoadedObservable.notifyObservers(extension);\n }\n this._parent.onExtensionLoadedObservable.clear();\n };\n GLTFLoader.prototype._checkExtensions = function () {\n if (this._gltf.extensionsRequired) {\n for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {\n var name_3 = _a[_i];\n var extension = this._extensions[name_3];\n if (!extension || !extension.enabled) {\n throw new Error(\"Require extension \" + name_3 + \" is not available\");\n }\n }\n }\n };\n GLTFLoader.prototype._setState = function (state) {\n this._state = state;\n this._parent._log(BABYLON.GLTFLoaderState[this._state]);\n };\n GLTFLoader.prototype._createRootNode = function () {\n this._rootBabylonMesh = new BABYLON.Mesh(\"__root__\", this._babylonScene);\n var rootNode = { _babylonMesh: this._rootBabylonMesh };\n switch (this._parent.coordinateSystemMode) {\n case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {\n if (!this._babylonScene.useRightHandedSystem) {\n rootNode.rotation = [0, 1, 0, 0];\n rootNode.scale = [1, 1, -1];\n GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);\n }\n break;\n }\n case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {\n this._babylonScene.useRightHandedSystem = true;\n break;\n }\n default: {\n throw new Error(\"Invalid coordinate system mode (\" + this._parent.coordinateSystemMode + \")\");\n }\n }\n this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);\n return rootNode;\n };\n GLTFLoader.prototype._loadSceneAsync = function (context, scene) {\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);\n if (extensionPromise) {\n return extensionPromise;\n }\n var promises = new Array();\n this._parent._logOpen(context + \" \" + (scene.name || \"\"));\n if (scene.nodes) {\n for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {\n var index = _a[_i];\n var node = GLTFLoader._GetProperty(context + \"/nodes/\" + index, this._gltf.nodes, index);\n promises.push(this._loadNodeAsync(\"#/nodes/\" + node._index, node));\n }\n }\n promises.push(this._loadAnimationsAsync());\n this._parent._logClose();\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._forEachPrimitive = function (node, callback) {\n if (node._primitiveBabylonMeshes) {\n for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {\n var babylonMesh = _a[_i];\n callback(babylonMesh);\n }\n }\n else {\n callback(node._babylonMesh);\n }\n };\n GLTFLoader.prototype._getMeshes = function () {\n var meshes = new Array();\n // Root mesh is always first.\n meshes.push(this._rootBabylonMesh);\n var nodes = this._gltf.nodes;\n if (nodes) {\n for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {\n var node = nodes_1[_i];\n if (node._babylonMesh) {\n meshes.push(node._babylonMesh);\n }\n if (node._primitiveBabylonMeshes) {\n for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {\n var babylonMesh = _b[_a];\n meshes.push(babylonMesh);\n }\n }\n }\n }\n return meshes;\n };\n GLTFLoader.prototype._getSkeletons = function () {\n var skeletons = new Array();\n var skins = this._gltf.skins;\n if (skins) {\n for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {\n var skin = skins_1[_i];\n if (skin._babylonSkeleton) {\n skeletons.push(skin._babylonSkeleton);\n }\n }\n }\n return skeletons;\n };\n GLTFLoader.prototype._getAnimationGroups = function () {\n var animationGroups = new Array();\n var animations = this._gltf.animations;\n if (animations) {\n for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {\n var animation = animations_1[_i];\n if (animation._babylonAnimationGroup) {\n animationGroups.push(animation._babylonAnimationGroup);\n }\n }\n }\n return animationGroups;\n };\n GLTFLoader.prototype._startAnimations = function () {\n switch (this._parent.animationStartMode) {\n case BABYLON.GLTFLoaderAnimationStartMode.NONE: {\n // do nothing\n break;\n }\n case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {\n var babylonAnimationGroups = this._getAnimationGroups();\n if (babylonAnimationGroups.length !== 0) {\n babylonAnimationGroups[0].start(true);\n }\n break;\n }\n case BABYLON.GLTFLoaderAnimationStartMode.ALL: {\n var babylonAnimationGroups = this._getAnimationGroups();\n for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {\n var babylonAnimationGroup = babylonAnimationGroups_1[_i];\n babylonAnimationGroup.start(true);\n }\n break;\n }\n default: {\n BABYLON.Tools.Error(\"Invalid animation start mode (\" + this._parent.animationStartMode + \")\");\n return;\n }\n }\n };\n GLTFLoader.prototype._loadNodeAsync = function (context, node) {\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (node._babylonMesh) {\n throw new Error(context + \": Invalid recursive node hierarchy\");\n }\n var promises = new Array();\n this._parent._logOpen(context + \" \" + (node.name || \"\"));\n var babylonMesh = new BABYLON.Mesh(node.name || \"node\" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);\n node._babylonMesh = babylonMesh;\n babylonMesh.setEnabled(false);\n GLTFLoader._LoadTransform(node, babylonMesh);\n if (node.mesh != undefined) {\n var mesh = GLTFLoader._GetProperty(context + \"/mesh\", this._gltf.meshes, node.mesh);\n promises.push(this._loadMeshAsync(\"#/meshes/\" + mesh._index, node, mesh, babylonMesh));\n }\n if (node.camera != undefined) {\n var camera = GLTFLoader._GetProperty(context + \"/camera\", this._gltf.cameras, node.camera);\n this._loadCamera(\"#/cameras/\" + camera._index, camera, babylonMesh);\n }\n if (node.children) {\n for (var _i = 0, _a = node.children; _i < _a.length; _i++) {\n var index = _a[_i];\n var childNode = GLTFLoader._GetProperty(context + \"/children/\" + index, this._gltf.nodes, index);\n promises.push(this._loadNodeAsync(\"#/nodes/\" + index, childNode));\n }\n }\n this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);\n this._parent._logClose();\n return Promise.all(promises).then(function () {\n babylonMesh.setEnabled(true);\n });\n };\n GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {\n var _this = this;\n var promises = new Array();\n this._parent._logOpen(context + \" \" + (mesh.name || \"\"));\n var primitives = mesh.primitives;\n if (!primitives || primitives.length === 0) {\n throw new Error(context + \": Primitives are missing\");\n }\n _ArrayItem.Assign(primitives);\n if (primitives.length === 1) {\n var primitive = primitives[0];\n promises.push(this._loadPrimitiveAsync(context + \"/primitives/\" + primitive._index, node, mesh, primitive, babylonMesh));\n }\n else {\n node._primitiveBabylonMeshes = [];\n for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {\n var primitive = primitives_1[_i];\n var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + \"_\" + primitive._index, this._babylonScene, babylonMesh);\n node._primitiveBabylonMeshes.push(primitiveBabylonMesh);\n promises.push(this._loadPrimitiveAsync(context + \"/primitives/\" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));\n this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);\n }\n }\n if (node.skin != undefined) {\n var skin = GLTFLoader._GetProperty(context + \"/skin\", this._gltf.skins, node.skin);\n promises.push(this._loadSkinAsync(\"#/skins/\" + skin._index, node, mesh, skin));\n }\n this._parent._logClose();\n return Promise.all(promises).then(function () {\n _this._forEachPrimitive(node, function (babylonMesh) {\n babylonMesh._refreshBoundingInfo(true);\n });\n });\n };\n GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {\n var _this = this;\n var promises = new Array();\n this._parent._logOpen(\"\" + context);\n this._createMorphTargets(context, node, mesh, primitive, babylonMesh);\n promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {\n return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {\n babylonGeometry.applyToMesh(babylonMesh);\n });\n }));\n var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);\n if (primitive.material == undefined) {\n babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);\n }\n else {\n var material = GLTFLoader._GetProperty(context + \"/material}\", this._gltf.materials, primitive.material);\n promises.push(this._loadMaterialAsync(\"#/materials/\" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {\n babylonMesh.material = babylonMaterial;\n }));\n }\n this._parent._logClose();\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {\n var _this = this;\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);\n if (extensionPromise) {\n return extensionPromise;\n }\n var attributes = primitive.attributes;\n if (!attributes) {\n throw new Error(context + \": Attributes are missing\");\n }\n var promises = new Array();\n var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);\n if (primitive.indices == undefined) {\n babylonMesh.isUnIndexed = true;\n }\n else {\n var accessor = GLTFLoader._GetProperty(context + \"/indices\", this._gltf.accessors, primitive.indices);\n promises.push(this._loadIndicesAccessorAsync(\"#/accessors/\" + accessor._index, accessor).then(function (data) {\n babylonGeometry.setIndices(data);\n }));\n }\n var loadAttribute = function (attribute, kind, callback) {\n if (attributes[attribute] == undefined) {\n return;\n }\n babylonMesh._delayInfo = babylonMesh._delayInfo || [];\n if (babylonMesh._delayInfo.indexOf(kind) === -1) {\n babylonMesh._delayInfo.push(kind);\n }\n var accessor = GLTFLoader._GetProperty(context + \"/attributes/\" + attribute, _this._gltf.accessors, attributes[attribute]);\n promises.push(_this._loadVertexAccessorAsync(\"#/accessors/\" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {\n babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);\n }));\n if (callback) {\n callback(accessor);\n }\n };\n loadAttribute(\"POSITION\", BABYLON.VertexBuffer.PositionKind);\n loadAttribute(\"NORMAL\", BABYLON.VertexBuffer.NormalKind);\n loadAttribute(\"TANGENT\", BABYLON.VertexBuffer.TangentKind);\n loadAttribute(\"TEXCOORD_0\", BABYLON.VertexBuffer.UVKind);\n loadAttribute(\"TEXCOORD_1\", BABYLON.VertexBuffer.UV2Kind);\n loadAttribute(\"JOINTS_0\", BABYLON.VertexBuffer.MatricesIndicesKind);\n loadAttribute(\"WEIGHTS_0\", BABYLON.VertexBuffer.MatricesWeightsKind);\n loadAttribute(\"COLOR_0\", BABYLON.VertexBuffer.ColorKind, function (accessor) {\n if (accessor.type === \"VEC4\" /* VEC4 */) {\n babylonMesh.hasVertexAlpha = true;\n }\n });\n return Promise.all(promises).then(function () {\n return babylonGeometry;\n });\n };\n GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {\n if (!primitive.targets) {\n return;\n }\n if (node._numMorphTargets == undefined) {\n node._numMorphTargets = primitive.targets.length;\n }\n else if (primitive.targets.length !== node._numMorphTargets) {\n throw new Error(context + \": Primitives do not have the same number of targets\");\n }\n babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();\n for (var index = 0; index < primitive.targets.length; index++) {\n var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;\n babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget(\"morphTarget\" + index, weight));\n // TODO: tell the target whether it has positions, normals, tangents\n }\n };\n GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {\n if (!primitive.targets) {\n return Promise.resolve();\n }\n var promises = new Array();\n var morphTargetManager = babylonMesh.morphTargetManager;\n for (var index = 0; index < morphTargetManager.numTargets; index++) {\n var babylonMorphTarget = morphTargetManager.getTarget(index);\n promises.push(this._loadMorphTargetVertexDataAsync(context + \"/targets/\" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));\n }\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {\n var _this = this;\n var promises = new Array();\n var loadAttribute = function (attribute, kind, setData) {\n if (attributes[attribute] == undefined) {\n return;\n }\n var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);\n if (!babylonVertexBuffer) {\n return;\n }\n var accessor = GLTFLoader._GetProperty(context + \"/\" + attribute, _this._gltf.accessors, attributes[attribute]);\n promises.push(_this._loadFloatAccessorAsync(\"#/accessors/\" + accessor._index, accessor).then(function (data) {\n setData(babylonVertexBuffer, data);\n }));\n };\n loadAttribute(\"POSITION\", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {\n babylonVertexBuffer.forEach(data.length, function (value, index) {\n data[index] += value;\n });\n babylonMorphTarget.setPositions(data);\n });\n loadAttribute(\"NORMAL\", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {\n babylonVertexBuffer.forEach(data.length, function (value, index) {\n data[index] += value;\n });\n babylonMorphTarget.setNormals(data);\n });\n loadAttribute(\"TANGENT\", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {\n var dataIndex = 0;\n babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {\n // Tangent data for morph targets is stored as xyz delta.\n // The vertexData.tangent is stored as xyzw.\n // So we need to skip every fourth vertexData.tangent.\n if (((index + 1) % 4) !== 0) {\n data[dataIndex++] += value;\n }\n });\n babylonMorphTarget.setTangents(data);\n });\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader._LoadTransform = function (node, babylonNode) {\n var position = BABYLON.Vector3.Zero();\n var rotation = BABYLON.Quaternion.Identity();\n var scaling = BABYLON.Vector3.One();\n if (node.matrix) {\n var matrix = BABYLON.Matrix.FromArray(node.matrix);\n matrix.decompose(scaling, rotation, position);\n }\n else {\n if (node.translation)\n position = BABYLON.Vector3.FromArray(node.translation);\n if (node.rotation)\n rotation = BABYLON.Quaternion.FromArray(node.rotation);\n if (node.scale)\n scaling = BABYLON.Vector3.FromArray(node.scale);\n }\n babylonNode.position = position;\n babylonNode.rotationQuaternion = rotation;\n babylonNode.scaling = scaling;\n };\n GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {\n var _this = this;\n var assignSkeleton = function (skeleton) {\n _this._forEachPrimitive(node, function (babylonMesh) {\n babylonMesh.skeleton = skeleton;\n });\n // Ignore the TRS of skinned nodes.\n // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)\n node._babylonMesh.parent = _this._rootBabylonMesh;\n node._babylonMesh.position = BABYLON.Vector3.Zero();\n node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();\n node._babylonMesh.scaling = BABYLON.Vector3.One();\n };\n if (skin._loaded) {\n return skin._loaded.then(function () {\n assignSkeleton(skin._babylonSkeleton);\n });\n }\n var skeletonId = \"skeleton\" + skin._index;\n var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);\n skin._babylonSkeleton = babylonSkeleton;\n this._loadBones(context, skin);\n assignSkeleton(babylonSkeleton);\n return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {\n _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);\n }));\n };\n GLTFLoader.prototype._loadBones = function (context, skin) {\n var babylonBones = {};\n for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {\n var index = _a[_i];\n var node = GLTFLoader._GetProperty(context + \"/joints/\" + index, this._gltf.nodes, index);\n this._loadBone(node, skin, babylonBones);\n }\n };\n GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {\n var babylonBone = babylonBones[node._index];\n if (babylonBone) {\n return babylonBone;\n }\n var babylonParentBone = null;\n if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {\n babylonParentBone = this._loadBone(node._parent, skin, babylonBones);\n }\n var boneIndex = skin.joints.indexOf(node._index);\n babylonBone = new BABYLON.Bone(node.name || \"joint\" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);\n babylonBones[node._index] = babylonBone;\n node._babylonBones = node._babylonBones || [];\n node._babylonBones.push(babylonBone);\n return babylonBone;\n };\n GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {\n if (skin.inverseBindMatrices == undefined) {\n return Promise.resolve(null);\n }\n var accessor = GLTFLoader._GetProperty(context + \"/inverseBindMatrices\", this._gltf.accessors, skin.inverseBindMatrices);\n return this._loadFloatAccessorAsync(\"#/accessors/\" + accessor._index, accessor);\n };\n GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {\n for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {\n var babylonBone = _a[_i];\n var baseMatrix = BABYLON.Matrix.Identity();\n var boneIndex = babylonBone._index;\n if (inverseBindMatricesData && boneIndex !== -1) {\n BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);\n baseMatrix.invertToRef(baseMatrix);\n }\n var babylonParentBone = babylonBone.getParent();\n if (babylonParentBone) {\n baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);\n }\n babylonBone.updateMatrix(baseMatrix, false, false);\n babylonBone._updateDifferenceMatrix(undefined, false);\n }\n };\n GLTFLoader.prototype._getNodeMatrix = function (node) {\n return node.matrix ?\n BABYLON.Matrix.FromArray(node.matrix) :\n BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());\n };\n GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {\n var babylonCamera = new BABYLON.FreeCamera(camera.name || \"camera\" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);\n babylonCamera.parent = babylonMesh;\n babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);\n switch (camera.type) {\n case \"perspective\" /* PERSPECTIVE */: {\n var perspective = camera.perspective;\n if (!perspective) {\n throw new Error(context + \": Camera perspective properties are missing\");\n }\n babylonCamera.fov = perspective.yfov;\n babylonCamera.minZ = perspective.znear;\n babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;\n break;\n }\n case \"orthographic\" /* ORTHOGRAPHIC */: {\n if (!camera.orthographic) {\n throw new Error(context + \": Camera orthographic properties are missing\");\n }\n babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;\n babylonCamera.orthoLeft = -camera.orthographic.xmag;\n babylonCamera.orthoRight = camera.orthographic.xmag;\n babylonCamera.orthoBottom = -camera.orthographic.ymag;\n babylonCamera.orthoTop = camera.orthographic.ymag;\n babylonCamera.minZ = camera.orthographic.znear;\n babylonCamera.maxZ = camera.orthographic.zfar;\n break;\n }\n default: {\n throw new Error(context + \": Invalid camera type (\" + camera.type + \")\");\n }\n }\n this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);\n };\n GLTFLoader.prototype._loadAnimationsAsync = function () {\n var animations = this._gltf.animations;\n if (!animations) {\n return Promise.resolve();\n }\n var promises = new Array();\n for (var index = 0; index < animations.length; index++) {\n var animation = animations[index];\n promises.push(this._loadAnimationAsync(\"#/animations/\" + index, animation));\n }\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {\n var _this = this;\n var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || \"animation\" + animation._index, this._babylonScene);\n animation._babylonAnimationGroup = babylonAnimationGroup;\n var promises = new Array();\n _ArrayItem.Assign(animation.channels);\n _ArrayItem.Assign(animation.samplers);\n for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {\n var channel = _a[_i];\n promises.push(this._loadAnimationChannelAsync(context + \"/channels/\" + channel._index, context, animation, channel, babylonAnimationGroup));\n }\n return Promise.all(promises).then(function () {\n babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);\n });\n };\n GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {\n var _this = this;\n var targetNode = GLTFLoader._GetProperty(context + \"/target/node\", this._gltf.nodes, channel.target.node);\n // Ignore animations that have no animation targets.\n if ((channel.target.path === \"weights\" /* WEIGHTS */ && !targetNode._numMorphTargets) ||\n (channel.target.path !== \"weights\" /* WEIGHTS */ && !targetNode._babylonMesh)) {\n return Promise.resolve();\n }\n // Ignore animations targeting TRS of skinned nodes.\n // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)\n if (targetNode.skin != undefined && channel.target.path !== \"weights\" /* WEIGHTS */) {\n return Promise.resolve();\n }\n var sampler = GLTFLoader._GetProperty(context + \"/sampler\", animation.samplers, channel.sampler);\n return this._loadAnimationSamplerAsync(animationContext + \"/samplers/\" + channel.sampler, sampler).then(function (data) {\n var targetPath;\n var animationType;\n switch (channel.target.path) {\n case \"translation\" /* TRANSLATION */: {\n targetPath = \"position\";\n animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;\n break;\n }\n case \"rotation\" /* ROTATION */: {\n targetPath = \"rotationQuaternion\";\n animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;\n break;\n }\n case \"scale\" /* SCALE */: {\n targetPath = \"scaling\";\n animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;\n break;\n }\n case \"weights\" /* WEIGHTS */: {\n targetPath = \"influence\";\n animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;\n break;\n }\n default: {\n throw new Error(context + \": Invalid target path (\" + channel.target.path + \")\");\n }\n }\n var outputBufferOffset = 0;\n var getNextOutputValue;\n switch (targetPath) {\n case \"position\": {\n getNextOutputValue = function () {\n var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);\n outputBufferOffset += 3;\n return value;\n };\n break;\n }\n case \"rotationQuaternion\": {\n getNextOutputValue = function () {\n var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);\n outputBufferOffset += 4;\n return value;\n };\n break;\n }\n case \"scaling\": {\n getNextOutputValue = function () {\n var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);\n outputBufferOffset += 3;\n return value;\n };\n break;\n }\n case \"influence\": {\n getNextOutputValue = function () {\n var value = new Array(targetNode._numMorphTargets);\n for (var i = 0; i < targetNode._numMorphTargets; i++) {\n value[i] = data.output[outputBufferOffset++];\n }\n return value;\n };\n break;\n }\n }\n var getNextKey;\n switch (data.interpolation) {\n case \"STEP\" /* STEP */: {\n getNextKey = function (frameIndex) { return ({\n frame: data.input[frameIndex],\n value: getNextOutputValue(),\n interpolation: BABYLON.AnimationKeyInterpolation.STEP\n }); };\n break;\n }\n case \"LINEAR\" /* LINEAR */: {\n getNextKey = function (frameIndex) { return ({\n frame: data.input[frameIndex],\n value: getNextOutputValue()\n }); };\n break;\n }\n case \"CUBICSPLINE\" /* CUBICSPLINE */: {\n getNextKey = function (frameIndex) { return ({\n frame: data.input[frameIndex],\n inTangent: getNextOutputValue(),\n value: getNextOutputValue(),\n outTangent: getNextOutputValue()\n }); };\n break;\n }\n }\n var keys = new Array(data.input.length);\n for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {\n keys[frameIndex] = getNextKey(frameIndex);\n }\n if (targetPath === \"influence\") {\n var _loop_1 = function (targetIndex) {\n var animationName = babylonAnimationGroup.name + \"_channel\" + babylonAnimationGroup.targetedAnimations.length;\n var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);\n babylonAnimation.setKeys(keys.map(function (key) { return ({\n frame: key.frame,\n inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,\n value: key.value[targetIndex],\n outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined\n }); }));\n _this._forEachPrimitive(targetNode, function (babylonMesh) {\n var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);\n var babylonAnimationClone = babylonAnimation.clone();\n morphTarget.animations.push(babylonAnimationClone);\n babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);\n });\n };\n for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {\n _loop_1(targetIndex);\n }\n }\n else {\n var animationName = babylonAnimationGroup.name + \"_channel\" + babylonAnimationGroup.targetedAnimations.length;\n var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);\n babylonAnimation.setKeys(keys);\n if (targetNode._babylonBones) {\n var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);\n for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {\n var babylonAnimationTarget = babylonAnimationTargets_1[_i];\n babylonAnimationTarget.animations.push(babylonAnimation);\n }\n babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);\n }\n else {\n targetNode._babylonMesh.animations.push(babylonAnimation);\n babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);\n }\n }\n });\n };\n GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {\n if (sampler._data) {\n return sampler._data;\n }\n var interpolation = sampler.interpolation || \"LINEAR\" /* LINEAR */;\n switch (interpolation) {\n case \"STEP\" /* STEP */:\n case \"LINEAR\" /* LINEAR */:\n case \"CUBICSPLINE\" /* CUBICSPLINE */: {\n break;\n }\n default: {\n throw new Error(context + \": Invalid interpolation (\" + sampler.interpolation + \")\");\n }\n }\n var inputAccessor = GLTFLoader._GetProperty(context + \"/input\", this._gltf.accessors, sampler.input);\n var outputAccessor = GLTFLoader._GetProperty(context + \"/output\", this._gltf.accessors, sampler.output);\n sampler._data = Promise.all([\n this._loadFloatAccessorAsync(\"#/accessors/\" + inputAccessor._index, inputAccessor),\n this._loadFloatAccessorAsync(\"#/accessors/\" + outputAccessor._index, outputAccessor)\n ]).then(function (_a) {\n var inputData = _a[0], outputData = _a[1];\n return {\n input: inputData,\n interpolation: interpolation,\n output: outputData,\n };\n });\n return sampler._data;\n };\n GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {\n if (buffer._data) {\n return buffer._data;\n }\n if (!buffer.uri) {\n throw new Error(context + \": Uri is missing\");\n }\n buffer._data = this._loadUriAsync(context, buffer.uri);\n return buffer._data;\n };\n GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {\n if (bufferView._data) {\n return bufferView._data;\n }\n var buffer = GLTFLoader._GetProperty(context + \"/buffer\", this._gltf.buffers, bufferView.buffer);\n bufferView._data = this._loadBufferAsync(\"#/buffers/\" + buffer._index, buffer).then(function (data) {\n try {\n return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);\n }\n catch (e) {\n throw new Error(context + \": \" + e.message);\n }\n });\n return bufferView._data;\n };\n GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {\n if (accessor.type !== \"SCALAR\" /* SCALAR */) {\n throw new Error(context + \": Invalid type \" + accessor.type);\n }\n if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&\n accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&\n accessor.componentType !== 5125 /* UNSIGNED_INT */) {\n throw new Error(context + \": Invalid component type \" + accessor.componentType);\n }\n if (accessor._data) {\n return accessor._data;\n }\n var bufferView = GLTFLoader._GetProperty(context + \"/bufferView\", this._gltf.bufferViews, accessor.bufferView);\n accessor._data = this._loadBufferViewAsync(\"#/bufferViews/\" + bufferView._index, bufferView).then(function (data) {\n return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);\n });\n return accessor._data;\n };\n GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {\n // TODO: support normalized and stride\n var _this = this;\n if (accessor.componentType !== 5126 /* FLOAT */) {\n throw new Error(\"Invalid component type \" + accessor.componentType);\n }\n if (accessor._data) {\n return accessor._data;\n }\n var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);\n var length = numComponents * accessor.count;\n if (accessor.bufferView == undefined) {\n accessor._data = Promise.resolve(new Float32Array(length));\n }\n else {\n var bufferView = GLTFLoader._GetProperty(context + \"/bufferView\", this._gltf.bufferViews, accessor.bufferView);\n accessor._data = this._loadBufferViewAsync(\"#/bufferViews/\" + bufferView._index, bufferView).then(function (data) {\n return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);\n });\n }\n if (accessor.sparse) {\n var sparse_1 = accessor.sparse;\n accessor._data = accessor._data.then(function (data) {\n var indicesBufferView = GLTFLoader._GetProperty(context + \"/sparse/indices/bufferView\", _this._gltf.bufferViews, sparse_1.indices.bufferView);\n var valuesBufferView = GLTFLoader._GetProperty(context + \"/sparse/values/bufferView\", _this._gltf.bufferViews, sparse_1.values.bufferView);\n return Promise.all([\n _this._loadBufferViewAsync(\"#/bufferViews/\" + indicesBufferView._index, indicesBufferView),\n _this._loadBufferViewAsync(\"#/bufferViews/\" + valuesBufferView._index, valuesBufferView)\n ]).then(function (_a) {\n var indicesData = _a[0], valuesData = _a[1];\n var indices = GLTFLoader._GetTypedArray(context + \"/sparse/indices\", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);\n var values = GLTFLoader._GetTypedArray(context + \"/sparse/values\", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);\n var valuesIndex = 0;\n for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {\n var dataIndex = indices[indicesIndex] * numComponents;\n for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {\n data[dataIndex++] = values[valuesIndex++];\n }\n }\n return data;\n });\n });\n }\n return accessor._data;\n };\n GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {\n var _this = this;\n if (bufferView._babylonBuffer) {\n return bufferView._babylonBuffer;\n }\n bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {\n return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);\n });\n return bufferView._babylonBuffer;\n };\n GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {\n var _this = this;\n if (accessor._babylonVertexBuffer) {\n return accessor._babylonVertexBuffer;\n }\n if (accessor.sparse) {\n accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {\n return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);\n });\n }\n else {\n var bufferView_1 = GLTFLoader._GetProperty(context + \"/bufferView\", this._gltf.bufferViews, accessor.bufferView);\n accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(\"#/bufferViews/\" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {\n var size = GLTFLoader._GetNumComponents(context, accessor.type);\n return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);\n });\n }\n return accessor._babylonVertexBuffer;\n };\n GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {\n var babylonMaterial = this._defaultBabylonMaterials[drawMode];\n if (!babylonMaterial) {\n babylonMaterial = this._createMaterial(\"__gltf_default\", drawMode);\n babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;\n babylonMaterial.metallic = 1;\n babylonMaterial.roughness = 1;\n this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);\n }\n return babylonMaterial;\n };\n GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {\n var promises = new Array();\n // Ensure metallic workflow\n babylonMaterial.metallic = 1;\n babylonMaterial.roughness = 1;\n var properties = material.pbrMetallicRoughness;\n if (properties) {\n if (properties.baseColorFactor) {\n babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);\n babylonMaterial.alpha = properties.baseColorFactor[3];\n }\n else {\n babylonMaterial.albedoColor = BABYLON.Color3.White();\n }\n babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;\n babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;\n if (properties.baseColorTexture) {\n promises.push(this._loadTextureInfoAsync(context + \"/baseColorTexture\", properties.baseColorTexture, function (texture) {\n babylonMaterial.albedoTexture = texture;\n }));\n }\n if (properties.metallicRoughnessTexture) {\n promises.push(this._loadTextureInfoAsync(context + \"/metallicRoughnessTexture\", properties.metallicRoughnessTexture, function (texture) {\n babylonMaterial.metallicTexture = texture;\n }));\n babylonMaterial.useMetallnessFromMetallicTextureBlue = true;\n babylonMaterial.useRoughnessFromMetallicTextureGreen = true;\n babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;\n }\n }\n this._loadMaterialAlphaProperties(context, material, babylonMaterial);\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n material._babylonData = material._babylonData || {};\n var babylonData = material._babylonData[babylonDrawMode];\n if (!babylonData) {\n this._parent._logOpen(context + \" \" + (material.name || \"\"));\n var name_4 = material.name || \"material\" + material._index;\n var babylonMaterial = this._createMaterial(name_4, babylonDrawMode);\n babylonData = {\n material: babylonMaterial,\n meshes: [],\n loaded: this._loadMaterialPropertiesAsync(context, material, babylonMaterial)\n };\n material._babylonData[babylonDrawMode] = babylonData;\n this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);\n this._parent._logClose();\n }\n babylonData.meshes.push(babylonMesh);\n babylonMesh.onDisposeObservable.addOnce(function () {\n var index = babylonData.meshes.indexOf(babylonMesh);\n if (index !== -1) {\n babylonData.meshes.splice(index, 1);\n }\n });\n assign(babylonData.material);\n return babylonData.loaded;\n };\n GLTFLoader.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadMaterialPropertiesAsync(this, context, material, babylonMaterial);\n if (extensionPromise) {\n return extensionPromise;\n }\n var promises = new Array();\n promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._createMaterial = function (name, drawMode) {\n var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);\n babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;\n babylonMaterial.fillMode = drawMode;\n babylonMaterial.enableSpecularAntiAliasing = true;\n babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;\n babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;\n return babylonMaterial;\n };\n GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {\n var promises = new Array();\n babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);\n if (material.doubleSided) {\n babylonMaterial.backFaceCulling = false;\n babylonMaterial.twoSidedLighting = true;\n }\n if (material.normalTexture) {\n promises.push(this._loadTextureInfoAsync(context + \"/normalTexture\", material.normalTexture, function (texture) {\n babylonMaterial.bumpTexture = texture;\n }));\n babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;\n babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;\n if (material.normalTexture.scale != undefined) {\n babylonMaterial.bumpTexture.level = material.normalTexture.scale;\n }\n }\n if (material.occlusionTexture) {\n promises.push(this._loadTextureInfoAsync(context + \"/occlusionTexture\", material.occlusionTexture, function (texture) {\n babylonMaterial.ambientTexture = texture;\n }));\n babylonMaterial.useAmbientInGrayScale = true;\n if (material.occlusionTexture.strength != undefined) {\n babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;\n }\n }\n if (material.emissiveTexture) {\n promises.push(this._loadTextureInfoAsync(context + \"/emissiveTexture\", material.emissiveTexture, function (texture) {\n babylonMaterial.emissiveTexture = texture;\n }));\n }\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {\n var alphaMode = material.alphaMode || \"OPAQUE\" /* OPAQUE */;\n switch (alphaMode) {\n case \"OPAQUE\" /* OPAQUE */: {\n babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;\n break;\n }\n case \"MASK\" /* MASK */: {\n babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;\n babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);\n if (babylonMaterial.albedoTexture) {\n babylonMaterial.albedoTexture.hasAlpha = true;\n }\n break;\n }\n case \"BLEND\" /* BLEND */: {\n babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;\n if (babylonMaterial.albedoTexture) {\n babylonMaterial.albedoTexture.hasAlpha = true;\n babylonMaterial.useAlphaFromAlbedoTexture = true;\n }\n break;\n }\n default: {\n throw new Error(context + \": Invalid alpha mode (\" + material.alphaMode + \")\");\n }\n }\n };\n GLTFLoader.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) {\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadTextureInfoAsync(this, context, textureInfo, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n this._parent._logOpen(\"\" + context);\n var texture = GLTFLoader._GetProperty(context + \"/index\", this._gltf.textures, textureInfo.index);\n var promise = this._loadTextureAsync(\"#/textures/\" + textureInfo.index, texture, function (babylonTexture) {\n babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;\n assign(babylonTexture);\n });\n this._parent._logClose();\n return promise;\n };\n GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {\n var _this = this;\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, texture, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n var promises = new Array();\n this._parent._logOpen(context + \" \" + (texture.name || \"\"));\n var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + \"/sampler\", this._gltf.samplers, texture.sampler));\n var samplerData = this._loadSampler(\"#/samplers/\" + sampler._index, sampler);\n var deferred = new BABYLON.Deferred();\n var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {\n if (!_this._disposed) {\n deferred.resolve();\n }\n }, function (message, exception) {\n if (!_this._disposed) {\n deferred.reject(new Error(context + \": \" + ((exception && exception.message) ? exception.message : message || \"Failed to load texture\")));\n }\n });\n promises.push(deferred.promise);\n babylonTexture.name = texture.name || \"texture\" + texture._index;\n babylonTexture.wrapU = samplerData.wrapU;\n babylonTexture.wrapV = samplerData.wrapV;\n var image = GLTFLoader._GetProperty(context + \"/source\", this._gltf.images, texture.source);\n promises.push(this._loadImageAsync(\"#/images/\" + image._index, image).then(function (data) {\n var dataUrl = \"data:\" + _this._rootUrl + (image.uri || \"image\" + image._index);\n babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));\n }));\n assign(babylonTexture);\n this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);\n this._parent._logClose();\n return Promise.all(promises).then(function () { });\n };\n GLTFLoader.prototype._loadSampler = function (context, sampler) {\n if (!sampler._data) {\n sampler._data = {\n noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),\n samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),\n wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),\n wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)\n };\n }\n ;\n return sampler._data;\n };\n GLTFLoader.prototype._loadImageAsync = function (context, image) {\n if (!image._data) {\n this._parent._logOpen(context + \" \" + (image.name || \"\"));\n if (image.uri) {\n image._data = this._loadUriAsync(context, image.uri);\n }\n else {\n var bufferView = GLTFLoader._GetProperty(context + \"/bufferView\", this._gltf.bufferViews, image.bufferView);\n image._data = this._loadBufferViewAsync(\"#/bufferViews/\" + bufferView._index, bufferView);\n }\n this._parent._logClose();\n }\n return image._data;\n };\n GLTFLoader.prototype._loadUriAsync = function (context, uri) {\n var _this = this;\n var extensionPromise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (!GLTFLoader._ValidateUri(uri)) {\n throw new Error(context + \": Uri '\" + uri + \"' is invalid\");\n }\n if (BABYLON.Tools.IsBase64(uri)) {\n var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));\n this._parent._log(\"Decoded \" + uri.substr(0, 64) + \"... (\" + data.length + \" bytes)\");\n return Promise.resolve(data);\n }\n this._parent._log(\"Loading \" + uri);\n return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {\n return new Promise(function (resolve, reject) {\n if (!_this._disposed) {\n var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {\n if (!_this._disposed) {\n var data = new Uint8Array(fileData);\n _this._parent._log(\"Loaded \" + uri + \" (\" + data.length + \" bytes)\");\n resolve(data);\n }\n }, function (event) {\n if (!_this._disposed) {\n if (request_1) {\n request_1._lengthComputable = event.lengthComputable;\n request_1._loaded = event.loaded;\n request_1._total = event.total;\n }\n if (_this._state === BABYLON.GLTFLoaderState.LOADING) {\n try {\n _this._onProgress();\n }\n catch (e) {\n reject(e);\n }\n }\n }\n }, _this._babylonScene.database, true, function (request, exception) {\n if (!_this._disposed) {\n reject(new BABYLON.LoadFileError(context + \": Failed to load '\" + uri + \"'\" + (request ? \": \" + request.status + \" \" + request.statusText : \"\"), request));\n }\n });\n _this._requests.push(request_1);\n }\n });\n });\n };\n GLTFLoader.prototype._onProgress = function () {\n if (!this._progressCallback) {\n return;\n }\n var lengthComputable = true;\n var loaded = 0;\n var total = 0;\n for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {\n var request = _a[_i];\n if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {\n return;\n }\n lengthComputable = lengthComputable && request._lengthComputable;\n loaded += request._loaded;\n total += request._total;\n }\n this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));\n };\n GLTFLoader._GetProperty = function (context, array, index) {\n if (!array || index == undefined || !array[index]) {\n throw new Error(context + \": Failed to find index (\" + index + \")\");\n }\n return array[index];\n };\n GLTFLoader._GetTextureWrapMode = function (context, mode) {\n // Set defaults if undefined\n mode = mode == undefined ? 10497 /* REPEAT */ : mode;\n switch (mode) {\n case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;\n case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;\n case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;\n default:\n BABYLON.Tools.Warn(context + \": Invalid texture wrap mode (\" + mode + \")\");\n return BABYLON.Texture.WRAP_ADDRESSMODE;\n }\n };\n GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {\n // Set defaults if undefined\n magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;\n minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;\n if (magFilter === 9729 /* LINEAR */) {\n switch (minFilter) {\n case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;\n case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;\n case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;\n case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;\n case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;\n case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;\n default:\n BABYLON.Tools.Warn(context + \": Invalid texture minification filter (\" + minFilter + \")\");\n return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;\n }\n }\n else {\n if (magFilter !== 9728 /* NEAREST */) {\n BABYLON.Tools.Warn(context + \": Invalid texture magnification filter (\" + magFilter + \")\");\n }\n switch (minFilter) {\n case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;\n case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;\n case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;\n case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;\n case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;\n case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;\n default:\n BABYLON.Tools.Warn(context + \": Invalid texture minification filter (\" + minFilter + \")\");\n return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;\n }\n }\n };\n GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {\n var buffer = bufferView.buffer;\n byteOffset = bufferView.byteOffset + (byteOffset || 0);\n try {\n switch (componentType) {\n case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);\n case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);\n case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);\n case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);\n case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);\n case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);\n default: throw new Error(\"Invalid component type \" + componentType);\n }\n }\n catch (e) {\n throw new Error(context + \": \" + e);\n }\n };\n GLTFLoader._GetNumComponents = function (context, type) {\n switch (type) {\n case \"SCALAR\": return 1;\n case \"VEC2\": return 2;\n case \"VEC3\": return 3;\n case \"VEC4\": return 4;\n case \"MAT2\": return 4;\n case \"MAT3\": return 9;\n case \"MAT4\": return 16;\n }\n throw new Error(context + \": Invalid type (\" + type + \")\");\n };\n GLTFLoader._ValidateUri = function (uri) {\n return (BABYLON.Tools.IsBase64(uri) || uri.indexOf(\"..\") === -1);\n };\n GLTFLoader._GetDrawMode = function (context, mode) {\n if (mode == undefined) {\n mode = 4 /* TRIANGLES */;\n }\n switch (mode) {\n case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;\n case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;\n case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;\n case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;\n case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;\n case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;\n case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;\n }\n throw new Error(context + \": Invalid mesh primitive mode (\" + mode + \")\");\n };\n GLTFLoader.prototype._compileMaterialsAsync = function () {\n var _this = this;\n this._parent._startPerformanceCounter(\"Compile materials\");\n var promises = new Array();\n if (this._gltf.materials) {\n for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {\n var material = _a[_i];\n if (material._babylonData) {\n for (var babylonDrawMode in material._babylonData) {\n var babylonData = material._babylonData[babylonDrawMode];\n for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {\n var babylonMesh = _c[_b];\n // Ensure nonUniformScaling is set if necessary.\n babylonMesh.computeWorldMatrix(true);\n var babylonMaterial = babylonData.material;\n promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));\n if (this._parent.useClipPlane) {\n promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));\n }\n }\n }\n }\n }\n }\n return Promise.all(promises).then(function () {\n _this._parent._endPerformanceCounter(\"Compile materials\");\n });\n };\n GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {\n var _this = this;\n this._parent._startPerformanceCounter(\"Compile shadow generators\");\n var promises = new Array();\n var lights = this._babylonScene.lights;\n for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {\n var light = lights_1[_i];\n var generator = light.getShadowGenerator();\n if (generator) {\n promises.push(generator.forceCompilationAsync());\n }\n }\n return Promise.all(promises).then(function () {\n _this._parent._endPerformanceCounter(\"Compile shadow generators\");\n });\n };\n GLTFLoader.prototype._applyExtensions = function (actionAsync) {\n for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {\n var name_5 = _a[_i];\n var extension = this._extensions[name_5];\n if (extension.enabled) {\n var promise = actionAsync(extension);\n if (promise) {\n return promise;\n }\n }\n }\n return null;\n };\n GLTFLoader.prototype._forEachExtensions = function (action) {\n for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {\n var name_6 = _a[_i];\n var extension = this._extensions[name_6];\n if (extension.enabled) {\n action(extension);\n }\n }\n };\n GLTFLoader._ExtensionNames = new Array();\n GLTFLoader._ExtensionFactories = {};\n return GLTFLoader;\n }());\n GLTF2.GLTFLoader = GLTFLoader;\n BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFLoader.js.map\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n /**\n * Abstract class that can be implemented to extend existing glTF loader behavior.\n */\n var GLTFLoaderExtension = /** @class */ (function () {\n /**\n * Creates new GLTFLoaderExtension\n * @param loader defines the GLTFLoader to use\n */\n function GLTFLoaderExtension(loader) {\n /**\n * Gets or sets a boolean indicating if the extension is enabled\n */\n this.enabled = true;\n this._loader = loader;\n }\n /**\n * Release all resources\n */\n GLTFLoaderExtension.prototype.dispose = function () {\n delete this._loader;\n };\n // #region Overridable Methods\n /**\n * Override this method to do work after the state changes to LOADING.\n */\n GLTFLoaderExtension.prototype._onLoading = function () { };\n /**\n * Override this method to do work after the state changes to READY.\n */\n GLTFLoaderExtension.prototype._onReady = function () { };\n /**\n * Override this method to modify the default behavior for loading scenes.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };\n /**\n * Override this method to modify the default behavior for loading nodes.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };\n /**\n * Override this method to modify the default behavior for loading mesh primitive vertex data.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };\n /**\n * Override this method to modify the default behavior for loading materials.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };\n /**\n * Override this method to modify the default behavior for loading material properties.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { return null; };\n /**\n * Override this method to modify the default behavior for loading texture infos.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) { return null; };\n /**\n * Override this method to modify the default behavior for loading textures.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadTextureAsync = function (context, texture, assign) { return null; };\n /**\n * Override this method to modify the default behavior for loading uris.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };\n // #endregion\n /**\n * Helper method called by a loader extension to load an glTF extension.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {\n if (!property.extensions) {\n return null;\n }\n var extensions = property.extensions;\n var extension = extensions[this.name];\n if (!extension) {\n return null;\n }\n // Clear out the extension before executing the action to avoid infinite recursion.\n delete extensions[this.name];\n try {\n return actionAsync(context + \"/extensions/\" + this.name, extension);\n }\n finally {\n // Restore the extension after executing the action.\n extensions[this.name] = extension;\n }\n };\n /**\n * Helper method called by the loader to allow extensions to override loading scenes.\n * @hidden\n */\n GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {\n if (!property.extras) {\n return null;\n }\n var extras = property.extras;\n var value = extras[this.name];\n if (value === undefined) {\n return null;\n }\n // Clear out the extras value before executing the action to avoid infinite recursion.\n delete extras[this.name];\n try {\n return actionAsync(context + \"/extras/\" + this.name, value);\n }\n finally {\n // Restore the extras value after executing the action.\n extras[this.name] = value;\n }\n };\n /**\n * Helper method called by the loader after the state changes to LOADING.\n * @hidden\n */\n GLTFLoaderExtension._OnLoading = function (loader) {\n loader._forEachExtensions(function (extension) { return extension._onLoading(); });\n };\n /**\n * Helper method called by the loader after the state changes to READY.\n * @hidden\n */\n GLTFLoaderExtension._OnReady = function (loader) {\n loader._forEachExtensions(function (extension) { return extension._onReady(); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading scenes.\n * @hidden\n */\n GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {\n return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading nodes.\n * @hidden\n */\n GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {\n return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.\n * @hidden\n */\n GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {\n return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading materials.\n * @hidden\n */\n GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {\n return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading material properties.\n * @hidden\n */\n GLTFLoaderExtension._LoadMaterialPropertiesAsync = function (loader, context, material, babylonMaterial) {\n return loader._applyExtensions(function (extension) { return extension._loadMaterialPropertiesAsync(context, material, babylonMaterial); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading texture infos.\n * @hidden\n */\n GLTFLoaderExtension._LoadTextureInfoAsync = function (loader, context, textureInfo, assign) {\n return loader._applyExtensions(function (extension) { return extension._loadTextureInfoAsync(context, textureInfo, assign); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading textures.\n * @hidden\n */\n GLTFLoaderExtension._LoadTextureAsync = function (loader, context, texture, assign) {\n return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, texture, assign); });\n };\n /**\n * Helper method called by the loader to allow extensions to override loading uris.\n * @hidden\n */\n GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {\n return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });\n };\n return GLTFLoaderExtension;\n }());\n GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=babylon.glTFLoaderExtension.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"MSFT_lod\";\n /**\n * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)\n */\n var MSFT_lod = /** @class */ (function (_super) {\n __extends(MSFT_lod, _super);\n function MSFT_lod() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n /**\n * Maximum number of LODs to load, starting from the lowest LOD.\n */\n _this.maxLODsToLoad = Number.MAX_VALUE;\n /**\n * Observable raised when all node LODs of one level are loaded.\n * The event data is the index of the loaded LOD starting from zero.\n * Dispose the loader to cancel the loading of the next level of LODs.\n */\n _this.onNodeLODsLoadedObservable = new BABYLON.Observable();\n /**\n * Observable raised when all material LODs of one level are loaded.\n * The event data is the index of the loaded LOD starting from zero.\n * Dispose the loader to cancel the loading of the next level of LODs.\n */\n _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();\n _this._nodeIndexLOD = null;\n _this._nodeSignalLODs = new Array();\n _this._nodePromiseLODs = new Array();\n _this._materialIndexLOD = null;\n _this._materialSignalLODs = new Array();\n _this._materialPromiseLODs = new Array();\n return _this;\n }\n MSFT_lod.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n this._nodeIndexLOD = null;\n this._nodeSignalLODs.length = 0;\n this._nodePromiseLODs.length = 0;\n this._materialIndexLOD = null;\n this._materialSignalLODs.length = 0;\n this._materialPromiseLODs.length = 0;\n this.onMaterialLODsLoadedObservable.clear();\n this.onNodeLODsLoadedObservable.clear();\n };\n MSFT_lod.prototype._onReady = function () {\n var _this = this;\n var _loop_1 = function (indexLOD) {\n var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () {\n if (indexLOD !== 0) {\n _this._loader._parent._endPerformanceCounter(\"Node LOD \" + indexLOD);\n }\n _this._loader._parent._log(\"Loaded node LOD \" + indexLOD);\n _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);\n if (indexLOD !== _this._nodePromiseLODs.length - 1) {\n _this._loader._parent._startPerformanceCounter(\"Node LOD \" + (indexLOD + 1));\n if (_this._nodeSignalLODs[indexLOD]) {\n _this._nodeSignalLODs[indexLOD].resolve();\n }\n }\n });\n this_1._loader._completePromises.push(promise);\n };\n var this_1 = this;\n for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {\n _loop_1(indexLOD);\n }\n var _loop_2 = function (indexLOD) {\n var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () {\n if (indexLOD !== 0) {\n _this._loader._parent._endPerformanceCounter(\"Material LOD \" + indexLOD);\n }\n _this._loader._parent._log(\"Loaded material LOD \" + indexLOD);\n _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);\n if (indexLOD !== _this._materialPromiseLODs.length - 1) {\n _this._loader._parent._startPerformanceCounter(\"Material LOD \" + (indexLOD + 1));\n if (_this._materialSignalLODs[indexLOD]) {\n _this._materialSignalLODs[indexLOD].resolve();\n }\n }\n });\n this_2._loader._completePromises.push(promise);\n };\n var this_2 = this;\n for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {\n _loop_2(indexLOD);\n }\n };\n MSFT_lod.prototype._loadNodeAsync = function (context, node) {\n var _this = this;\n return this._loadExtensionAsync(context, node, function (extensionContext, extension) {\n var firstPromise;\n var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);\n _this._loader._parent._logOpen(\"\" + extensionContext);\n var _loop_3 = function (indexLOD) {\n var nodeLOD = nodeLODs[indexLOD];\n if (indexLOD !== 0) {\n _this._nodeIndexLOD = indexLOD;\n _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();\n }\n var promise = _this._loader._loadNodeAsync(\"#/nodes/\" + nodeLOD._index, nodeLOD).then(function () {\n if (indexLOD !== 0) {\n var previousNodeLOD = nodeLODs[indexLOD - 1];\n if (previousNodeLOD._babylonMesh) {\n previousNodeLOD._babylonMesh.dispose();\n delete previousNodeLOD._babylonMesh;\n _this._disposeUnusedMaterials();\n }\n }\n });\n if (indexLOD === 0) {\n firstPromise = promise;\n }\n else {\n _this._nodeIndexLOD = null;\n }\n _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];\n _this._nodePromiseLODs[indexLOD].push(promise);\n };\n for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {\n _loop_3(indexLOD);\n }\n _this._loader._parent._logClose();\n return firstPromise;\n });\n };\n MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {\n var _this = this;\n // Don't load material LODs if already loading a node LOD.\n if (this._nodeIndexLOD) {\n return null;\n }\n return this._loadExtensionAsync(context, material, function (extensionContext, extension) {\n var firstPromise;\n var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);\n _this._loader._parent._logOpen(\"\" + extensionContext);\n var _loop_4 = function (indexLOD) {\n var materialLOD = materialLODs[indexLOD];\n if (indexLOD !== 0) {\n _this._materialIndexLOD = indexLOD;\n }\n var promise = _this._loader._loadMaterialAsync(\"#/materials/\" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {\n if (indexLOD !== 0) {\n var babylonDataLOD = materialLOD._babylonData;\n assign(babylonDataLOD[babylonDrawMode].material);\n var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;\n if (previousBabylonDataLOD[babylonDrawMode]) {\n previousBabylonDataLOD[babylonDrawMode].material.dispose();\n delete previousBabylonDataLOD[babylonDrawMode];\n }\n }\n });\n if (indexLOD === 0) {\n firstPromise = promise;\n }\n else {\n _this._materialIndexLOD = null;\n }\n _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];\n _this._materialPromiseLODs[indexLOD].push(promise);\n };\n for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {\n _loop_4(indexLOD);\n }\n _this._loader._parent._logClose();\n return firstPromise;\n });\n };\n MSFT_lod.prototype._loadUriAsync = function (context, uri) {\n var _this = this;\n // Defer the loading of uris if loading a material or node LOD.\n if (this._materialIndexLOD !== null) {\n this._loader._parent._log(\"deferred\");\n var previousIndexLOD = this._materialIndexLOD - 1;\n this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();\n return this._materialSignalLODs[previousIndexLOD].promise.then(function () {\n return _this._loader._loadUriAsync(context, uri);\n });\n }\n else if (this._nodeIndexLOD !== null) {\n this._loader._parent._log(\"deferred\");\n var previousIndexLOD = this._nodeIndexLOD - 1;\n this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();\n return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {\n return _this._loader._loadUriAsync(context, uri);\n });\n }\n return null;\n };\n /**\n * Gets an array of LOD properties from lowest to highest.\n */\n MSFT_lod.prototype._getLODs = function (context, property, array, ids) {\n if (this.maxLODsToLoad <= 0) {\n throw new Error(\"maxLODsToLoad must be greater than zero\");\n }\n var properties = new Array();\n for (var i = ids.length - 1; i >= 0; i--) {\n properties.push(GLTF2.GLTFLoader._GetProperty(context + \"/ids/\" + ids[i], array, ids[i]));\n if (properties.length === this.maxLODsToLoad) {\n return properties;\n }\n }\n properties.push(property);\n return properties;\n };\n MSFT_lod.prototype._disposeUnusedMaterials = function () {\n var materials = this._loader._gltf.materials;\n if (materials) {\n for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {\n var material = materials_1[_i];\n if (material._babylonData) {\n for (var drawMode in material._babylonData) {\n var babylonData = material._babylonData[drawMode];\n if (babylonData.meshes.length === 0) {\n babylonData.material.dispose(false, true);\n delete material._babylonData[drawMode];\n }\n }\n }\n }\n }\n };\n return MSFT_lod;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.MSFT_lod = MSFT_lod;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=MSFT_lod.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"MSFT_minecraftMesh\";\n /** @hidden */\n var MSFT_minecraftMesh = /** @class */ (function (_super) {\n __extends(MSFT_minecraftMesh, _super);\n function MSFT_minecraftMesh() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {\n var _this = this;\n return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {\n if (value) {\n return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {\n if (babylonMaterial.needAlphaBlending()) {\n babylonMaterial.forceDepthWrite = true;\n babylonMaterial.separateCullingPass = true;\n }\n babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;\n babylonMaterial.twoSidedLighting = true;\n assign(babylonMaterial);\n });\n }\n return null;\n });\n };\n return MSFT_minecraftMesh;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=MSFT_minecraftMesh.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"MSFT_sRGBFactors\";\n /** @hidden */\n var MSFT_sRGBFactors = /** @class */ (function (_super) {\n __extends(MSFT_sRGBFactors, _super);\n function MSFT_sRGBFactors() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n MSFT_sRGBFactors.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {\n var _this = this;\n return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {\n if (value) {\n var promise = _this._loader._loadMaterialPropertiesAsync(context, material, babylonMaterial);\n _this._convertColorsToLinear(babylonMaterial);\n return promise;\n }\n return null;\n });\n };\n MSFT_sRGBFactors.prototype._convertColorsToLinear = function (babylonMaterial) {\n if (!babylonMaterial.albedoTexture) {\n babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);\n }\n if (!babylonMaterial.reflectivityTexture) {\n babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);\n }\n };\n return MSFT_sRGBFactors;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=MSFT_sRGBFactors.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"KHR_draco_mesh_compression\";\n /**\n * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)\n */\n var KHR_draco_mesh_compression = /** @class */ (function (_super) {\n __extends(KHR_draco_mesh_compression, _super);\n function KHR_draco_mesh_compression(loader) {\n var _this = _super.call(this, loader) || this;\n _this.name = NAME;\n _this._dracoCompression = null;\n // Disable extension if decoder is not available.\n if (!BABYLON.DracoCompression.DecoderAvailable) {\n _this.enabled = false;\n }\n return _this;\n }\n KHR_draco_mesh_compression.prototype.dispose = function () {\n if (this._dracoCompression) {\n this._dracoCompression.dispose();\n }\n _super.prototype.dispose.call(this);\n };\n KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {\n var _this = this;\n return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {\n if (primitive.mode != undefined) {\n if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&\n primitive.mode !== 4 /* TRIANGLES */) {\n throw new Error(context + \": Unsupported mode \" + primitive.mode);\n }\n // TODO: handle triangle strips\n if (primitive.mode === 5 /* TRIANGLE_STRIP */) {\n throw new Error(context + \": Mode \" + primitive.mode + \" is not currently supported\");\n }\n }\n var attributes = {};\n var loadAttribute = function (name, kind) {\n var uniqueId = extension.attributes[name];\n if (uniqueId == undefined) {\n return;\n }\n babylonMesh._delayInfo = babylonMesh._delayInfo || [];\n if (babylonMesh._delayInfo.indexOf(kind) === -1) {\n babylonMesh._delayInfo.push(kind);\n }\n attributes[kind] = uniqueId;\n };\n loadAttribute(\"POSITION\", BABYLON.VertexBuffer.PositionKind);\n loadAttribute(\"NORMAL\", BABYLON.VertexBuffer.NormalKind);\n loadAttribute(\"TANGENT\", BABYLON.VertexBuffer.TangentKind);\n loadAttribute(\"TEXCOORD_0\", BABYLON.VertexBuffer.UVKind);\n loadAttribute(\"TEXCOORD_1\", BABYLON.VertexBuffer.UV2Kind);\n loadAttribute(\"JOINTS_0\", BABYLON.VertexBuffer.MatricesIndicesKind);\n loadAttribute(\"WEIGHTS_0\", BABYLON.VertexBuffer.MatricesWeightsKind);\n loadAttribute(\"COLOR_0\", BABYLON.VertexBuffer.ColorKind);\n var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);\n if (!bufferView._dracoBabylonGeometry) {\n bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync(\"#/bufferViews/\" + bufferView._index, bufferView).then(function (data) {\n if (!_this._dracoCompression) {\n _this._dracoCompression = new BABYLON.DracoCompression();\n }\n return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {\n var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);\n babylonVertexData.applyToGeometry(babylonGeometry);\n return babylonGeometry;\n }).catch(function (error) {\n throw new Error(context + \": \" + error.message);\n });\n });\n }\n return bufferView._dracoBabylonGeometry;\n });\n };\n return KHR_draco_mesh_compression;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=KHR_draco_mesh_compression.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"KHR_materials_pbrSpecularGlossiness\";\n /**\n * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)\n */\n var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {\n __extends(KHR_materials_pbrSpecularGlossiness, _super);\n function KHR_materials_pbrSpecularGlossiness() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {\n var _this = this;\n return this._loadExtensionAsync(context, material, function (extensionContext, extension) {\n var promises = new Array();\n promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));\n return Promise.all(promises).then(function () { });\n });\n };\n KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {\n var promises = new Array();\n if (properties.diffuseFactor) {\n babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);\n babylonMaterial.alpha = properties.diffuseFactor[3];\n }\n else {\n babylonMaterial.albedoColor = BABYLON.Color3.White();\n }\n babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();\n babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;\n if (properties.diffuseTexture) {\n promises.push(this._loader._loadTextureInfoAsync(context + \"/diffuseTexture\", properties.diffuseTexture, function (texture) {\n babylonMaterial.albedoTexture = texture;\n }));\n }\n if (properties.specularGlossinessTexture) {\n promises.push(this._loader._loadTextureInfoAsync(context + \"/specularGlossinessTexture\", properties.specularGlossinessTexture, function (texture) {\n babylonMaterial.reflectivityTexture = texture;\n }));\n babylonMaterial.reflectivityTexture.hasAlpha = true;\n babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;\n }\n this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);\n return Promise.all(promises).then(function () { });\n };\n return KHR_materials_pbrSpecularGlossiness;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"KHR_materials_unlit\";\n /**\n * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)\n */\n var KHR_materials_unlit = /** @class */ (function (_super) {\n __extends(KHR_materials_unlit, _super);\n function KHR_materials_unlit() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n KHR_materials_unlit.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {\n var _this = this;\n return this._loadExtensionAsync(context, material, function () {\n return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);\n });\n };\n KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {\n var promises = new Array();\n babylonMaterial.unlit = true;\n // Ensure metallic workflow\n babylonMaterial.metallic = 1;\n babylonMaterial.roughness = 1;\n var properties = material.pbrMetallicRoughness;\n if (properties) {\n if (properties.baseColorFactor) {\n babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);\n babylonMaterial.alpha = properties.baseColorFactor[3];\n }\n else {\n babylonMaterial.albedoColor = BABYLON.Color3.White();\n }\n if (properties.baseColorTexture) {\n promises.push(this._loader._loadTextureInfoAsync(context + \"/baseColorTexture\", properties.baseColorTexture, function (texture) {\n babylonMaterial.albedoTexture = texture;\n }));\n }\n }\n if (material.doubleSided) {\n babylonMaterial.backFaceCulling = false;\n babylonMaterial.twoSidedLighting = true;\n }\n this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);\n return Promise.all(promises).then(function () { });\n };\n return KHR_materials_unlit;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.KHR_materials_unlit = KHR_materials_unlit;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n//# sourceMappingURL=KHR_materials_unlit.js.map\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"KHR_lights\";\n var LightType;\n (function (LightType) {\n LightType[\"AMBIENT\"] = \"ambient\";\n LightType[\"DIRECTIONAL\"] = \"directional\";\n LightType[\"POINT\"] = \"point\";\n LightType[\"SPOT\"] = \"spot\";\n })(LightType || (LightType = {}));\n /**\n * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)\n */\n var KHR_lights = /** @class */ (function (_super) {\n __extends(KHR_lights, _super);\n function KHR_lights() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n KHR_lights.prototype._onLoading = function () {\n var extensions = this._loader._gltf.extensions;\n if (extensions && extensions[this.name]) {\n var extension = extensions[this.name];\n this._lights = extension.lights;\n }\n };\n KHR_lights.prototype._loadSceneAsync = function (context, scene) {\n var _this = this;\n return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {\n var promise = _this._loader._loadSceneAsync(extensionContext, scene);\n var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);\n if (light.type !== LightType.AMBIENT) {\n throw new Error(extensionContext + \": Only ambient lights are allowed on a scene\");\n }\n _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();\n return promise;\n });\n };\n KHR_lights.prototype._loadNodeAsync = function (context, node) {\n var _this = this;\n return this._loadExtensionAsync(context, node, function (extensionContext, extension) {\n var promise = _this._loader._loadNodeAsync(extensionContext, node);\n var babylonLight;\n var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);\n var name = node._babylonMesh.name;\n switch (light.type) {\n case LightType.AMBIENT: {\n throw new Error(extensionContext + \": Ambient lights are not allowed on a node\");\n }\n case LightType.DIRECTIONAL: {\n babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);\n break;\n }\n case LightType.POINT: {\n babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);\n break;\n }\n case LightType.SPOT: {\n // TODO: support inner and outer cone angles\n //const innerConeAngle = spotLight.innerConeAngle || 0;\n var outerConeAngle = light.spot && light.spot.outerConeAngle || Math.PI / 4;\n babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);\n break;\n }\n default: {\n throw new Error(extensionContext + \": Invalid light type (\" + light.type + \")\");\n }\n }\n babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();\n babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;\n babylonLight.parent = node._babylonMesh;\n return promise;\n });\n };\n return KHR_lights;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.KHR_lights = KHR_lights;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"KHR_texture_transform\";\n /**\n * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)\n */\n var KHR_texture_transform = /** @class */ (function (_super) {\n __extends(KHR_texture_transform, _super);\n function KHR_texture_transform() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n KHR_texture_transform.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) {\n var _this = this;\n return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {\n return _this._loader._loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {\n if (extension.offset) {\n babylonTexture.uOffset = extension.offset[0];\n babylonTexture.vOffset = extension.offset[1];\n }\n // Always rotate around the origin.\n babylonTexture.uRotationCenter = 0;\n babylonTexture.vRotationCenter = 0;\n if (extension.rotation) {\n babylonTexture.wAng = -extension.rotation;\n }\n if (extension.scale) {\n babylonTexture.uScale = extension.scale[0];\n babylonTexture.vScale = extension.scale[1];\n }\n if (extension.texCoord != undefined) {\n babylonTexture.coordinatesIndex = extension.texCoord;\n }\n assign(babylonTexture);\n });\n });\n };\n return KHR_texture_transform;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.KHR_texture_transform = KHR_texture_transform;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n\n\nvar BABYLON;\n(function (BABYLON) {\n var GLTF2;\n (function (GLTF2) {\n var Extensions;\n (function (Extensions) {\n var NAME = \"EXT_lights_imageBased\";\n /**\n * [Specification](TODO) (Experimental)\n */\n var EXT_lights_imageBased = /** @class */ (function (_super) {\n __extends(EXT_lights_imageBased, _super);\n function EXT_lights_imageBased() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.name = NAME;\n return _this;\n }\n EXT_lights_imageBased.prototype._onLoading = function () {\n var extensions = this._loader._gltf.extensions;\n if (extensions && extensions[this.name]) {\n var extension = extensions[this.name];\n this._lights = extension.lights;\n }\n };\n EXT_lights_imageBased.prototype._loadSceneAsync = function (context, scene) {\n var _this = this;\n return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {\n var promises = new Array();\n promises.push(_this._loader._loadSceneAsync(context, scene));\n _this._loader._parent._logOpen(\"\" + extensionContext);\n var light = GLTF2.GLTFLoader._GetProperty(extensionContext + \"/light\", _this._lights, extension.light);\n promises.push(_this._loadLightAsync(\"#/extensions/\" + _this.name + \"/lights/\" + extension.light, light).then(function (texture) {\n _this._loader._babylonScene.environmentTexture = texture;\n }));\n _this._loader._parent._logClose();\n return Promise.all(promises).then(function () { });\n });\n };\n EXT_lights_imageBased.prototype._loadLightAsync = function (context, light) {\n var _this = this;\n if (!light._loaded) {\n var promises = new Array();\n this._loader._parent._logOpen(\"\" + context);\n var imageData_1 = new Array(light.specularImages.length);\n var _loop_1 = function (mipmap) {\n var faces = light.specularImages[mipmap];\n imageData_1[mipmap] = new Array(faces.length);\n var _loop_2 = function (face) {\n var specularImageContext = context + \"/specularImages/\" + mipmap + \"/\" + face;\n this_1._loader._parent._logOpen(\"\" + specularImageContext);\n var index = faces[face];\n var image = GLTF2.GLTFLoader._GetProperty(specularImageContext, this_1._loader._gltf.images, index);\n promises.push(this_1._loader._loadImageAsync(\"#/images/\" + index, image).then(function (data) {\n imageData_1[mipmap][face] = data;\n }));\n this_1._loader._parent._logClose();\n };\n for (var face = 0; face < faces.length; face++) {\n _loop_2(face);\n }\n };\n var this_1 = this;\n for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {\n _loop_1(mipmap);\n }\n this._loader._parent._logClose();\n light._loaded = Promise.all(promises).then(function () {\n var babylonTexture = new BABYLON.RawCubeTexture(_this._loader._babylonScene, null, light.specularImageSize);\n light._babylonTexture = babylonTexture;\n if (light.intensity != undefined) {\n babylonTexture.level = light.intensity;\n }\n if (light.rotation) {\n var rotation = BABYLON.Quaternion.FromArray(light.rotation);\n // Invert the rotation so that positive rotation is counter-clockwise.\n if (!_this._loader._babylonScene.useRightHandedSystem) {\n rotation = BABYLON.Quaternion.Inverse(rotation);\n }\n BABYLON.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());\n }\n var sphericalHarmonics = BABYLON.SphericalHarmonics.FromArray(light.irradianceCoefficients);\n sphericalHarmonics.scale(light.intensity);\n sphericalHarmonics.convertIrradianceToLambertianRadiance();\n var sphericalPolynomial = BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);\n // Compute the lod generation scale to fit exactly to the number of levels available.\n var lodGenerationScale = (imageData_1.length - 1) / BABYLON.Scalar.Log2(light.specularImageSize);\n return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);\n });\n }\n return light._loaded.then(function () {\n return light._babylonTexture;\n });\n };\n return EXT_lights_imageBased;\n }(GLTF2.GLTFLoaderExtension));\n Extensions.EXT_lights_imageBased = EXT_lights_imageBased;\n GLTF2.GLTFLoader._Register(NAME, function (loader) { return new EXT_lights_imageBased(loader); });\n })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));\n })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));\n})(BABYLON || (BABYLON = {}));\n\n \n\n return BABYLON;\n});\n\n\n//# sourceURL=webpack://BabylonViewer/../dist/preview_release/loaders/babylonjs.loaders.js?"); /***/ }), @@ -145,7 +145,7 @@ eval("\n\n(function universalModuleDefinition(root, factory) {\n var amdDepen /*! no static exports found */ /***/ (function(module, exports) { -eval("module.exports = \"data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABTkAA8AAAAAJEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEgAAABgSlp+MVZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAACIAAAA3oTfhSJjdnQgAAAEMAAAACAAAAAqCdkJr2ZwZ20AAARQAAAA8AAAAVn8nuaOZ2FzcAAABUAAAAAMAAAADAAIABtnbHlmAAAFTAAACPgAAAzOOMLcQmhlYWQAAA5EAAAAMgAAADb+Z7dYaGhlYQAADngAAAAVAAAAJBABCAZobXR4AAAOkAAAACsAAAA2EzQDvGxvY2EAAA68AAAALgAAAC4W1hOObWF4cAAADuwAAAAcAAAAIACPANFuYW1lAAAPCAAABTwAAAvzL/OWdXBvc3QAABREAAAAEwAAACD/UQB3cHJlcAAAFFgAAACJAAAA03i98g542mNgZp/IOIGBlYGDdRarMQMDozSEZr7IkMYkxMHKysXIxAgGDEAgwIAAvsEKCgwODLzf0zjAfAjJAFbHAuEpMDAAAL2BB0542hXJUxQYBgAEwclf2qa2bdu2bdu2bdu2bdu2bTtlur15734WAwz4fwYZPHCIgWGoMHQYJqqD+mHDcGH4MEIYMYwURg6jhFHDaGH0MEYYM4wVxg7jhHHDeGH8MEGYMEwUJg6ThEnDZGHyMEWYMkwVpg7ThGnDdGH6MEOYMcwUZg6zhFnDbGH2MEeYM8wV5g7zhHnDfGH+sEBYMCwUFg6LhEXDYmHxsERYMiwVlg7LhGXDcmH5sEJYMawUVg6rhFXDamH1sEZYM6wV1g7rhHXDemH9sEHYMGwUNg6bhE3DZmHzsEXYMmwVtg7bhG3DdmH7sEPYMewUdg67hF3DbmH3sEfYM+wV9g77hH3DfmH/cEA4MBwUDg6HhEPDYeHwcEQ4MhwVjg7HhGPDceH4cEI4MZwUTg6nhFPDaeH0cEY4M5wVzg7nhHPDeeH8cEG4MFwULg6XhEvDZeHycEW4MlwVrg7XhGvDdeH6cEO4MdwUbg63hFvDbeH2cEe4M9wV7g73hHvDfeH+8EB4MDwUHg6PhEfDY+Hx8ER4MjwVng7PhGfDc+H58EJ4MbwUXg6vhFfDa+H18EZ4M7wV3g7vhHfDe+H98EH4MHwUPg6fhE/DZ+Hz8EX4MnwVvg7fhG/Dd+H78EP4MfwUfg6/hF/Db+H3MDj8Ef4Mf4W/wz/h3zAk/gPilQDpAAAAeNpjYGBgYmBkAAERBmYwy42BjcEISPMCRSAyhAATAwvDDCCtAIQsYJ0Kz/meOzzPfP7lxdOXIm+63/t9lPy27zvvd+Hvaf//Q1XwPrd/noGmggeoIvX///9f/j+S+C5xXGKBhJi4mthP4UaBA3zfOIMYGDhB9uF2FQcUCzEIMogyiAAAKmIy6HjaY9BiCGUoYGhgWMXIwNjA7MB4gMEBiwgQAACqHAeVeNpdj79Ow0AMxnMktIQnQDohnXUqQ5WInemGSyTUJSUM56WA1Eqk74CUhcUDz+JuGfNiCMwR/i62v8/6fL9zp/nJfHacpUcqKVacN+Gg1AsO6u2Z/fkhT+82ZWFM1XlW92XBagmia04X9U2waMjQ9ZZMbR4ftpwtYpfFjvDScNKGTuptAHaov8cd4lU8ksUjhBLfT/F9jEv6tSxWhtOLJqwD916z86gBTMVjE3j0GhB/yKQ/dWcT42w5ZdvATnOCRJ/KAvdEmoT7S49/9aCS/4b7bci/q0H1Tdz0FvSHYcGCsKGXZ9tQCRpg+Q6E/GTGAAEAAgAIAAr//wAPeNptFm1sU9f1nvs+rp0PJ48Xx4mTODw7thO8OJE/gTSOCcWQlH6wdY1mL6HQQWkZm7IBKi1jV6gdWyhiAlRN+wEjUSrKCpPK1DFV2zJtP6qtpasqTeqQxoTUaqtE1WoSI8bvZuc+Oylo03vvvnPvufd8n3MPoeRVQtQXtYNEIYyQpGEZYcuwXlX+XnmTvmmPawfLM2fURwgQEz5mt/R+ohECPjdkgZ0uVsyKWVRO6/0IKbeKlX24T6EKs/WS3OemUTewucpkZbKo2IpNFWW2MlVURIUSQpEj7mQ2cREDaVpGyIAoWGB5LSNpgA8I5dyeLNJZUVJLMG9zTueKCrc5wlNFOkcJp1yU6GwRjxNOOMOHNOJEkqqRsdKM83L1uDYvSsw5Xy45R7V5TijKwhnBk9SRGQwThSZ3CVfOV7arpILIxdt0hs6gzJQD0XChai1IGiHJC+XkiiRSJrrzSe0ISHkIqSdNUjsvPml8DEtDGzNeQUooiSTPF4nOJQ3OVY4IhUv6ODDbRdA6XtKGFKLIiEXdVOplSa7yZ6F55/hcEYZheFHRSJmrJRrmAsmqBMLiOlVm7RKdn8Ud4g8ixF3Evi7CwCkRHMIEZUW7uZAJ6u5G2xnIrd3xRlXSdupAhlwI419FyRZRQhudY3NNGhNX5EwQaSsdXYa6lDl1/jZawCaSG9oEjVHzUYAESYQkSJqsJQ8gt0SAeo0WDw1ZwThNG6kcTVrOqNRYQ6LV26KHgpF0KoNKGywJVtRipCMeamkJxTsW+TIEXI5coCR30ZzlvD8S8eOnFdHiC9M3xVm4mRdnmbOtvEJAcQhQZy71Q03QkwpxzuJn45q4eXNJukWXvnURJwr6yABqMUQ2yGjwhkypSYtH7YJQOpVT06k4DQU91BtCZcLSc068WGmMHCvdR2WIKuj2/Oj+iWRk3ei6CHfGQKrQ21tIBXhi4kDlqPQV8kOdgKOZAeMF8C9DRs0nJ/aPPvC1LUNDG9fk8w4wGpNHJQlJdQGPSfODjCw8hBMpNwaoC6OOJMlTZBplD4DjgBgE4ypKrEpAeiKTzWRzWjIRUH2tLBWNa4jUmY6bA3QIEjlVoiRA01Uf4UHppCT7k79zavbDw9vCI+twHghkUul1I+Fthz+cnery93wpc+LchfOnh9afOX/h3IlMrMfofvHib35xMtq147kfzfzgOxM+Y4xf3LnNjA1m8+Ox2Hg+Oxgzt+34OR+rLEiXcDlo1/2FsFiSNDv7Bvs6nUFyBQgX/D1mW6it2aUormYEzNfazM6+LsOtUNXVaHZYrUa7WNp5kY99cVSyhNiyzx1Py+zAiB0jk2SeXCG/J++htaqhOgDM11qNWzTWMESZXg1gdPYQZONQi2Q5VOOCMp+EQIYEGjApzYYhAolMOhVBy2H5M1pacRkiORhaNqi3hYGkrHsRZ2UzyUQ3SL64MZM2omjuEXAWoUVuc8xvJVqN+2bsPu+4iIyPJeI3T+/+wFwJt9OmX/Dl6PnosXRepgYlvYXJdHqy0Osf2NB7YpfEi5XEaYv3tK6yBiFUdYopTtnXI/5wh+pSO8JVT5lLxPQjL4Rh12XT7zcXTGnfWyYCOLt8dz6CfB28M9b24phfcbWal3zNU7s+uE9GfmpF+kd9T64HJ42lrFLmNQ/nBxtfRjz9iRRVokwr1t6ZCHttJ7NN2Cf5Dmz58pYBOV/wS1kldMmRbVnoT6tCm5focjkRH9eAv30RLXWE1Gq2SaIkhpUhSbJYG0bIRrK1VuVqwSJDxKx5P1SLBtMItVO8sfCe0NKWFxhkNcCC74MwqxZ/UBYm554vFJ6fm1z+yxSXJWD0wEQCi8VRWX6x9mG6l/9aEp8XtUfE5yVoLr8BTSXxmf6rYvW20Mm9ROTfJnh89F5ymrwi+B38BF4mzvVENaRVLIrPStCEJJuRw/T0r+3rNCwvGGwksDxSzJd/4p1nYo2Po9bMAAN1MfBi1VnarbXoDDQTciAzgaUioSAusCxk8DBeGZnV9rNKXslvHLa5/SidptP2STUf6LST4tgUfbdrS++asUw37+v2+OvsrcFj9Jde+n1OD8GGynviIw5b1Sb4mXhS/KUu+K74HVwQb8NaWFvZGR1HElNwiL7T1RlIj63pjrrx/LEgveKVN9MTpJ+9zq4RH/ptA5ki+8kPyTmU3qPSJtoAWoRGc5A1wmYOtDggPIIl04evTpkHmBv1yXqgCRoctBLFIQBySxwGIJJ2pj4kEoBu8LauwmUF1yJRB4VnEYtkWldBFdAZLlcxOVAyPdnqFkAUvohALux1ANbYFvIrq8Rt+9/iP3Ve1/ChYXp1PPVM5cqDxzYe+NfBhonXntBcWmNX4/HKYXFZDXnaPa4G1yqxaN8Wi5ijn+ga0OEXxCeKrsYeX6PRxjbPpmMP1re6c88N17ua3Q+/8u3B7YNUpUbYkz+SH3lhZPPJTQ0+eGzTy4Wh7w6xOpUpyDXzTEZlN6/CvquKplCd0neSu5OKrjz9/h77Su6w7lebEjsviTu/Ndk3/rj7Brx1wwg223tu0UPNHa8knkp2JvxKfMcg1ZXj4tPj8cd77X/ACc2t9U/0s73v70MIel3hr0bGfwxvF2YK2W9lGRL/89NjZx46C9mz6b0Zt+ea2HOt+AYcyXwzQ3Vd+d6dI3Vtrv6v9zd1el8SZZhJ70o1rzYoRQkzz2YafPVAoTlUCAEApVT81NPeiCvr92aPDJSqtb96RzZiNifJZvIVsh1T27DQA7IlQi8YoLOQUS3uuvRMRiZ0DAxNtmeIwTEJ9+S83Ko5lT+TRWdqOahWAJ1x5Wh9o1rxMx7IB+0Luf7hBZmMlIYKlkeWuDz2Hvhiv4Vtzf/P3oFiVGzyd9CH/B0yiXGqY0vWvWG1yu2NZlc9pTZft5lyiawz69SmhmCPU80l1SXs4Zawj67k/6fGYDHo8MNb0eKNaHFAStXhl/0i9hAM2yynF24hFuknxKi1ieD0Eo5lwsbyNef0Po5JZDXDyoKNNbaQUpoFR1nB88uF3c47mjpdnNOOwYIUw5H9iODLNX9pRWzZiP4X0FL98XjaY2BkYGBgujnr9BUxz3h+m68M3BwMILD/78EGEH3d87wDiOZgAItzMjCBKABnJQpuAAB42mNgZGDgYAABOMnIgApYAQLNACAAAAB42mPVYljGAARMhgxgwMHAIMzADIQNTAxMDUCBBoYGBgRoYAgDUQBtJAQEAAAAABQAFAAUABQAKAA9AGQAgQCXAKwAzAEAATYBmgH7Ao8DpgQnBIMFjQYdBmcAAHjaY2BkYGAQY7jAwMUAAoxgEsROAbMYABsCAWF42p1UzYscRRSvTvdmd83uEo0RJUSLIDEJY092JWw+ENkkYKK7CWyWQPBU010zXaanq6mqTtt4Fr14EhG8iaeAB8WDKIgH/Uc8+l/43uvqmd5kDOoMXfWrV+/93mc3Y2zzyD4LGP2CFVxayE7AqcVH2HJwyuOwJ496eImtBWc8PsqeD2KPl9mV4B2PV9jJ4COPj7ELwecerwd/BD95vEHykAVRCH7Xwo8JLwE+Hn5K+CjJvyK8TPJvCa8Q/pHwKjCl4e8eB+xs9IbHR9hGtOdx2JNHPbzEXo4+8PgoOxNZj5eZib70eIVdWFr2+Bg7WNr0eD38bOkTjzdm8ud6uRzDOFfXCa/15BuIV08TPo5xrp4nfALwC6vbhF/s6Z8kntuEX+rJXyHbB4RPkc6E8Omezms9/Drp14QvEG7jf5PwF4hXevGv9Hyt9eRrPpfHfOvi5jbfU4nRVo8dv6FNqY1wShcx38lzvq8mmbN8X1ppHsk0Xr8lR0bW/G4pi4OmlHxXNLpyPNcTlfBEl41BC47MF9/iZ3HbHvB9kZcZvyWKRCcPQfqezgp+q0ot+jnIlOV5n2esDb+uRrlKRM69R9DR4JRbXZlEcgy3Fkbyqkil4S6TfO/2Ad9ViSysvMatlFxORzJNZcrzVspTaROjSkyPfKTSCZXb+LoYNTnI9m7ubvEda6Wz+3JS5cLcl8ai9lZ8+ZLXQqVW556caImBCe6MSOVUmIdcj9tgZjWdGF2VKE70tBSFkjZeWPDMufLqcFjXdTzt7mOwGbqm1BMjyqwZjnXh7HBubquyzBVkiBcxf6ArPhUNryBXh1VFMXeaJ0YKJwc8VbaESg+4KFJeGgW3CahI2IXlpTRT5RzQjRpKoqubgwsov+nAGD0Mnk61NDqtEjfgOC1gO0CbzoEqeJ2pJOtFVoNTVSR5BU2aR6+LvOHn1Pm2fz11YHhWtG27VTHhRlpnVIJVnTtA8xnXNarAOQVenJxiC4wCr6mui1yL9HD1RFsqGDNIR4MrWCtXwrimEtNEnUzm5eGKwgtUNF4dGwKEUJ9MjRTEHLM7TDPDpkywHNCINcE6k+xDVrC/4Jnf3WMO9oKlsBr4UH4d/hD+Gv4Gz8/hL+F37DHjbItdZJtsG9AeUywBPc0sPGOw5ewGsZW0CpAoQAWL4WYH+HPY90E2YRncWTpJ2CVoP4I1Bc3rYAcRUqQFebnJdsErMljSRUu0m7AKtDDS+8RgvTeMMWaX2aUnuDqmPs894tGwcrDGiAQ8jqJPQTol/ocgwwzxJiPdRblP6FxB9p12AvsUzlhTRZnG/6FqWCMH0qtsCP+a/jHwPWkfez9DwA2xTIinBIYGpGNiw2yHC71birmEKinqAZ9ZYN8eUE6cKtHAXlHt2kq0Feu0UaYpawMamIdkAzinpFdSrxqStDPGQWbgrrVNPIv0Z0HcJXUWc3Z0h1YjiqPrRE4ZoVUXV2thqQvmKcl4lsPgX3W1pHMKNgmcB1Svdl5bv4OZnyczUDSLNdUpgXVxzWqfKWonkE1Fc5curD3a5ITOgf552HFCR74ui9jbGP5vbefsKTFNQGZojh11LpnN6qIMOu9Px3WtNwOYSZuLI3/dW4D8ba4pSGrKXNNb+azZE4emSlJftF/brFpc0ZtVkSVG23Wz40HNnN7kf57R9qtW+M7M2bs3RPkq4/xgvCOqdNvb+RdZ0AR35z/h1P9ay0PfZPoqH7oH79Gr0Wb0fvRu9DasVw4xFWB/B/QeUd2KNsrg++CbkFE3d0DTQLyYjfgbYLuFq3jaY2BmAIP/fgzlDFgAACkqAcgAeNrbwKDNsImRk0mbcRMXiNzO1ZobaqvKwKG9nTs12EFPBsTiifCw0JAEsXidzbXlhUEsPh0VGREeEItfTkKYjwPEEuDj4WRnAbEEwQDEEtowoSDAAMhi2M4IN5oJbjQz3GgWuNGscKPZ5CShRrPDjeaAG80JN3qTMCO79gYGBdfaTAkXAMQBKBoAAAA=\"\n\n//# sourceURL=webpack://BabylonViewer/./assets/babylon.woff?"); +eval("module.exports = \"data:font/woff;charset=utf-8;base64,d09GRgABAAAAABTkAA8AAAAAJEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEgAAABgSlp+MVZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAACIAAAA3oTfhSJjdnQgAAAEMAAAACAAAAAqCdkJr2ZwZ20AAARQAAAA8AAAAVn8nuaOZ2FzcAAABUAAAAAMAAAADAAIABtnbHlmAAAFTAAACPgAAAzOOMLcQmhlYWQAAA5EAAAAMgAAADb+Z7dYaGhlYQAADngAAAAVAAAAJBABCAZobXR4AAAOkAAAACsAAAA2EzQDvGxvY2EAAA68AAAALgAAAC4W1hOObWF4cAAADuwAAAAcAAAAIACPANFuYW1lAAAPCAAABTwAAAvzL/OWdXBvc3QAABREAAAAEwAAACD/UQB3cHJlcAAAFFgAAACJAAAA03i98g542mNgZp/IOIGBlYGDdRarMQMDozSEZr7IkMYkxMHKysXIxAgGDEAgwIAAvsEKCgwODLzf0zjAfAjJAFbHAuEpMDAAAL2BB0542hXJUxQYBgAEwclf2qa2bdu2bdu2bdu2bdu2bTtlur15734WAwz4fwYZPHCIgWGoMHQYJqqD+mHDcGH4MEIYMYwURg6jhFHDaGH0MEYYM4wVxg7jhHHDeGH8MEGYMEwUJg6ThEnDZGHyMEWYMkwVpg7ThGnDdGH6MEOYMcwUZg6zhFnDbGH2MEeYM8wV5g7zhHnDfGH+sEBYMCwUFg6LhEXDYmHxsERYMiwVlg7LhGXDcmH5sEJYMawUVg6rhFXDamH1sEZYM6wV1g7rhHXDemH9sEHYMGwUNg6bhE3DZmHzsEXYMmwVtg7bhG3DdmH7sEPYMewUdg67hF3DbmH3sEfYM+wV9g77hH3DfmH/cEA4MBwUDg6HhEPDYeHwcEQ4MhwVjg7HhGPDceH4cEI4MZwUTg6nhFPDaeH0cEY4M5wVzg7nhHPDeeH8cEG4MFwULg6XhEvDZeHycEW4MlwVrg7XhGvDdeH6cEO4MdwUbg63hFvDbeH2cEe4M9wV7g73hHvDfeH+8EB4MDwUHg6PhEfDY+Hx8ER4MjwVng7PhGfDc+H58EJ4MbwUXg6vhFfDa+H18EZ4M7wV3g7vhHfDe+H98EH4MHwUPg6fhE/DZ+Hz8EX4MnwVvg7fhG/Dd+H78EP4MfwUfg6/hF/Db+H3MDj8Ef4Mf4W/wz/h3zAk/gPilQDpAAAAeNpjYGBgYmBkAAERBmYwy42BjcEISPMCRSAyhAATAwvDDCCtAIQsYJ0Kz/meOzzPfP7lxdOXIm+63/t9lPy27zvvd+Hvaf//Q1XwPrd/noGmggeoIvX///9f/j+S+C5xXGKBhJi4mthP4UaBA3zfOIMYGDhB9uF2FQcUCzEIMogyiAAAKmIy6HjaY9BiCGUoYGhgWMXIwNjA7MB4gMEBiwgQAACqHAeVeNpdj79Ow0AMxnMktIQnQDohnXUqQ5WInemGSyTUJSUM56WA1Eqk74CUhcUDz+JuGfNiCMwR/i62v8/6fL9zp/nJfHacpUcqKVacN+Gg1AsO6u2Z/fkhT+82ZWFM1XlW92XBagmia04X9U2waMjQ9ZZMbR4ftpwtYpfFjvDScNKGTuptAHaov8cd4lU8ksUjhBLfT/F9jEv6tSxWhtOLJqwD916z86gBTMVjE3j0GhB/yKQ/dWcT42w5ZdvATnOCRJ/KAvdEmoT7S49/9aCS/4b7bci/q0H1Tdz0FvSHYcGCsKGXZ9tQCRpg+Q6E/GTGAAEAAgAIAAr//wAPeNptFm1sU9f1nvs+rp0PJ48Xx4mTODw7thO8OJE/gTSOCcWQlH6wdY1mL6HQQWkZm7IBKi1jV6gdWyhiAlRN+wEjUSrKCpPK1DFV2zJtP6qtpasqTeqQxoTUaqtE1WoSI8bvZuc+Oylo03vvvnPvufd8n3MPoeRVQtQXtYNEIYyQpGEZYcuwXlX+XnmTvmmPawfLM2fURwgQEz5mt/R+ohECPjdkgZ0uVsyKWVRO6/0IKbeKlX24T6EKs/WS3OemUTewucpkZbKo2IpNFWW2MlVURIUSQpEj7mQ2cREDaVpGyIAoWGB5LSNpgA8I5dyeLNJZUVJLMG9zTueKCrc5wlNFOkcJp1yU6GwRjxNOOMOHNOJEkqqRsdKM83L1uDYvSsw5Xy45R7V5TijKwhnBk9SRGQwThSZ3CVfOV7arpILIxdt0hs6gzJQD0XChai1IGiHJC+XkiiRSJrrzSe0ISHkIqSdNUjsvPml8DEtDGzNeQUooiSTPF4nOJQ3OVY4IhUv6ODDbRdA6XtKGFKLIiEXdVOplSa7yZ6F55/hcEYZheFHRSJmrJRrmAsmqBMLiOlVm7RKdn8Ud4g8ixF3Evi7CwCkRHMIEZUW7uZAJ6u5G2xnIrd3xRlXSdupAhlwI419FyRZRQhudY3NNGhNX5EwQaSsdXYa6lDl1/jZawCaSG9oEjVHzUYAESYQkSJqsJQ8gt0SAeo0WDw1ZwThNG6kcTVrOqNRYQ6LV26KHgpF0KoNKGywJVtRipCMeamkJxTsW+TIEXI5coCR30ZzlvD8S8eOnFdHiC9M3xVm4mRdnmbOtvEJAcQhQZy71Q03QkwpxzuJn45q4eXNJukWXvnURJwr6yABqMUQ2yGjwhkypSYtH7YJQOpVT06k4DQU91BtCZcLSc068WGmMHCvdR2WIKuj2/Oj+iWRk3ei6CHfGQKrQ21tIBXhi4kDlqPQV8kOdgKOZAeMF8C9DRs0nJ/aPPvC1LUNDG9fk8w4wGpNHJQlJdQGPSfODjCw8hBMpNwaoC6OOJMlTZBplD4DjgBgE4ypKrEpAeiKTzWRzWjIRUH2tLBWNa4jUmY6bA3QIEjlVoiRA01Uf4UHppCT7k79zavbDw9vCI+twHghkUul1I+Fthz+cnery93wpc+LchfOnh9afOX/h3IlMrMfofvHib35xMtq147kfzfzgOxM+Y4xf3LnNjA1m8+Ox2Hg+Oxgzt+34OR+rLEiXcDlo1/2FsFiSNDv7Bvs6nUFyBQgX/D1mW6it2aUormYEzNfazM6+LsOtUNXVaHZYrUa7WNp5kY99cVSyhNiyzx1Py+zAiB0jk2SeXCG/J++htaqhOgDM11qNWzTWMESZXg1gdPYQZONQi2Q5VOOCMp+EQIYEGjApzYYhAolMOhVBy2H5M1pacRkiORhaNqi3hYGkrHsRZ2UzyUQ3SL64MZM2omjuEXAWoUVuc8xvJVqN+2bsPu+4iIyPJeI3T+/+wFwJt9OmX/Dl6PnosXRepgYlvYXJdHqy0Osf2NB7YpfEi5XEaYv3tK6yBiFUdYopTtnXI/5wh+pSO8JVT5lLxPQjL4Rh12XT7zcXTGnfWyYCOLt8dz6CfB28M9b24phfcbWal3zNU7s+uE9GfmpF+kd9T64HJ42lrFLmNQ/nBxtfRjz9iRRVokwr1t6ZCHttJ7NN2Cf5Dmz58pYBOV/wS1kldMmRbVnoT6tCm5focjkRH9eAv30RLXWE1Gq2SaIkhpUhSbJYG0bIRrK1VuVqwSJDxKx5P1SLBtMItVO8sfCe0NKWFxhkNcCC74MwqxZ/UBYm554vFJ6fm1z+yxSXJWD0wEQCi8VRWX6x9mG6l/9aEp8XtUfE5yVoLr8BTSXxmf6rYvW20Mm9ROTfJnh89F5ymrwi+B38BF4mzvVENaRVLIrPStCEJJuRw/T0r+3rNCwvGGwksDxSzJd/4p1nYo2Po9bMAAN1MfBi1VnarbXoDDQTciAzgaUioSAusCxk8DBeGZnV9rNKXslvHLa5/SidptP2STUf6LST4tgUfbdrS++asUw37+v2+OvsrcFj9Jde+n1OD8GGynviIw5b1Sb4mXhS/KUu+K74HVwQb8NaWFvZGR1HElNwiL7T1RlIj63pjrrx/LEgveKVN9MTpJ+9zq4RH/ptA5ki+8kPyTmU3qPSJtoAWoRGc5A1wmYOtDggPIIl04evTpkHmBv1yXqgCRoctBLFIQBySxwGIJJ2pj4kEoBu8LauwmUF1yJRB4VnEYtkWldBFdAZLlcxOVAyPdnqFkAUvohALux1ANbYFvIrq8Rt+9/iP3Ve1/ChYXp1PPVM5cqDxzYe+NfBhonXntBcWmNX4/HKYXFZDXnaPa4G1yqxaN8Wi5ijn+ga0OEXxCeKrsYeX6PRxjbPpmMP1re6c88N17ua3Q+/8u3B7YNUpUbYkz+SH3lhZPPJTQ0+eGzTy4Wh7w6xOpUpyDXzTEZlN6/CvquKplCd0neSu5OKrjz9/h77Su6w7lebEjsviTu/Ndk3/rj7Brx1wwg223tu0UPNHa8knkp2JvxKfMcg1ZXj4tPj8cd77X/ACc2t9U/0s73v70MIel3hr0bGfwxvF2YK2W9lGRL/89NjZx46C9mz6b0Zt+ea2HOt+AYcyXwzQ3Vd+d6dI3Vtrv6v9zd1el8SZZhJ70o1rzYoRQkzz2YafPVAoTlUCAEApVT81NPeiCvr92aPDJSqtb96RzZiNifJZvIVsh1T27DQA7IlQi8YoLOQUS3uuvRMRiZ0DAxNtmeIwTEJ9+S83Ko5lT+TRWdqOahWAJ1x5Wh9o1rxMx7IB+0Luf7hBZmMlIYKlkeWuDz2Hvhiv4Vtzf/P3oFiVGzyd9CH/B0yiXGqY0vWvWG1yu2NZlc9pTZft5lyiawz69SmhmCPU80l1SXs4Zawj67k/6fGYDHo8MNb0eKNaHFAStXhl/0i9hAM2yynF24hFuknxKi1ieD0Eo5lwsbyNef0Po5JZDXDyoKNNbaQUpoFR1nB88uF3c47mjpdnNOOwYIUw5H9iODLNX9pRWzZiP4X0FL98XjaY2BkYGBgujnr9BUxz3h+m68M3BwMILD/78EGEH3d87wDiOZgAItzMjCBKABnJQpuAAB42mNgZGDgYAABOMnIgApYAQLNACAAAAB42mPVYljGAARMhgxgwMHAIMzADIQNTAxMDUCBBoYGBgRoYAgDUQBtJAQEAAAAABQAFAAUABQAKAA9AGQAgQCXAKwAzAEAATYBmgH7Ao8DpgQnBIMFjQYdBmcAAHjaY2BkYGAQY7jAwMUAAoxgEsROAbMYABsCAWF42p1UzYscRRSvTvdmd83uEo0RJUSLIDEJY092JWw+ENkkYKK7CWyWQPBU010zXaanq6mqTtt4Fr14EhG8iaeAB8WDKIgH/Uc8+l/43uvqmd5kDOoMXfWrV+/93mc3Y2zzyD4LGP2CFVxayE7AqcVH2HJwyuOwJ496eImtBWc8PsqeD2KPl9mV4B2PV9jJ4COPj7ELwecerwd/BD95vEHykAVRCH7Xwo8JLwE+Hn5K+CjJvyK8TPJvCa8Q/pHwKjCl4e8eB+xs9IbHR9hGtOdx2JNHPbzEXo4+8PgoOxNZj5eZib70eIVdWFr2+Bg7WNr0eD38bOkTjzdm8ud6uRzDOFfXCa/15BuIV08TPo5xrp4nfALwC6vbhF/s6Z8kntuEX+rJXyHbB4RPkc6E8Omezms9/Drp14QvEG7jf5PwF4hXevGv9Hyt9eRrPpfHfOvi5jbfU4nRVo8dv6FNqY1wShcx38lzvq8mmbN8X1ppHsk0Xr8lR0bW/G4pi4OmlHxXNLpyPNcTlfBEl41BC47MF9/iZ3HbHvB9kZcZvyWKRCcPQfqezgp+q0ot+jnIlOV5n2esDb+uRrlKRM69R9DR4JRbXZlEcgy3Fkbyqkil4S6TfO/2Ad9ViSysvMatlFxORzJNZcrzVspTaROjSkyPfKTSCZXb+LoYNTnI9m7ubvEda6Wz+3JS5cLcl8ai9lZ8+ZLXQqVW556caImBCe6MSOVUmIdcj9tgZjWdGF2VKE70tBSFkjZeWPDMufLqcFjXdTzt7mOwGbqm1BMjyqwZjnXh7HBubquyzBVkiBcxf6ArPhUNryBXh1VFMXeaJ0YKJwc8VbaESg+4KFJeGgW3CahI2IXlpTRT5RzQjRpKoqubgwsov+nAGD0Mnk61NDqtEjfgOC1gO0CbzoEqeJ2pJOtFVoNTVSR5BU2aR6+LvOHn1Pm2fz11YHhWtG27VTHhRlpnVIJVnTtA8xnXNarAOQVenJxiC4wCr6mui1yL9HD1RFsqGDNIR4MrWCtXwrimEtNEnUzm5eGKwgtUNF4dGwKEUJ9MjRTEHLM7TDPDpkywHNCINcE6k+xDVrC/4Jnf3WMO9oKlsBr4UH4d/hD+Gv4Gz8/hL+F37DHjbItdZJtsG9AeUywBPc0sPGOw5ewGsZW0CpAoQAWL4WYH+HPY90E2YRncWTpJ2CVoP4I1Bc3rYAcRUqQFebnJdsErMljSRUu0m7AKtDDS+8RgvTeMMWaX2aUnuDqmPs894tGwcrDGiAQ8jqJPQTol/ocgwwzxJiPdRblP6FxB9p12AvsUzlhTRZnG/6FqWCMH0qtsCP+a/jHwPWkfez9DwA2xTIinBIYGpGNiw2yHC71birmEKinqAZ9ZYN8eUE6cKtHAXlHt2kq0Feu0UaYpawMamIdkAzinpFdSrxqStDPGQWbgrrVNPIv0Z0HcJXUWc3Z0h1YjiqPrRE4ZoVUXV2thqQvmKcl4lsPgX3W1pHMKNgmcB1Svdl5bv4OZnyczUDSLNdUpgXVxzWqfKWonkE1Fc5curD3a5ITOgf552HFCR74ui9jbGP5vbefsKTFNQGZojh11LpnN6qIMOu9Px3WtNwOYSZuLI3/dW4D8ba4pSGrKXNNb+azZE4emSlJftF/brFpc0ZtVkSVG23Wz40HNnN7kf57R9qtW+M7M2bs3RPkq4/xgvCOqdNvb+RdZ0AR35z/h1P9ay0PfZPoqH7oH79Gr0Wb0fvRu9DasVw4xFWB/B/QeUd2KNsrg++CbkFE3d0DTQLyYjfgbYLuFq3jaY2BmAIP/fgzlDFgAACkqAcgAeNrbwKDNsImRk0mbcRMXiNzO1ZobaqvKwKG9nTs12EFPBsTiifCw0JAEsXidzbXlhUEsPh0VGREeEItfTkKYjwPEEuDj4WRnAbEEwQDEEtowoSDAAMhi2M4IN5oJbjQz3GgWuNGscKPZ5CShRrPDjeaAG80JN3qTMCO79gYGBdfaTAkXAMQBKBoAAAA=\"\n\n//# sourceURL=webpack://BabylonViewer/./assets/babylon.woff?"); /***/ }), diff --git a/src/Cameras/VR/babylon.vrExperienceHelper.ts b/src/Cameras/VR/babylon.vrExperienceHelper.ts index c6f1bd0c591..2d942ab4c92 100644 --- a/src/Cameras/VR/babylon.vrExperienceHelper.ts +++ b/src/Cameras/VR/babylon.vrExperienceHelper.ts @@ -507,7 +507,9 @@ module BABYLON { * @param scene The scene the VRExperienceHelper belongs to. * @param webVROptions Options to modify the vr experience helper's behavior. */ - constructor(scene: Scene, /** Options to modify the vr experience helper's behavior. */public webVROptions: VRExperienceHelperOptions = {}) { + constructor(scene: Scene, + /** Options to modify the vr experience helper's behavior. */ + public webVROptions: VRExperienceHelperOptions = {}) { this._scene = scene; this._canvas = scene.getEngine().getRenderingCanvas(); diff --git a/src/Engine/babylon.engine.ts b/src/Engine/babylon.engine.ts index 19011bf8eb8..ae23ce06644 100644 --- a/src/Engine/babylon.engine.ts +++ b/src/Engine/babylon.engine.ts @@ -3321,9 +3321,10 @@ * @param effect defines the effect to activate */ public enableEffect(effect: Nullable): void { - if (!effect) { + if (!effect || effect === this._currentEffect) { return; } + // Use program this.bindSamplers(effect); @@ -3332,7 +3333,9 @@ if (effect.onBind) { effect.onBind(effect); } - effect.onBindObservable.notifyObservers(effect); + if (effect._onBindObservable) { + effect._onBindObservable.notifyObservers(effect); + } } /** diff --git a/src/Engine/babylon.nullEngine.ts b/src/Engine/babylon.nullEngine.ts index b5d371a3e24..3b354cd6b0c 100644 --- a/src/Engine/babylon.nullEngine.ts +++ b/src/Engine/babylon.nullEngine.ts @@ -166,7 +166,9 @@ if (effect.onBind) { effect.onBind(effect); } - effect.onBindObservable.notifyObservers(effect); + if (effect._onBindObservable) { + effect._onBindObservable.notifyObservers(effect); + } } public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void { diff --git a/src/Gizmos/babylon.gizmo.ts b/src/Gizmos/babylon.gizmo.ts index d36f6a16b3f..6a6b0bc5b82 100644 --- a/src/Gizmos/babylon.gizmo.ts +++ b/src/Gizmos/babylon.gizmo.ts @@ -64,7 +64,9 @@ module BABYLON { * Creates a gizmo * @param gizmoLayer The utility layer the gizmo will be added to */ - constructor(/** The utility layer the gizmo will be added to */ public gizmoLayer:UtilityLayerRenderer=UtilityLayerRenderer.DefaultUtilityLayer){ + constructor( + /** The utility layer the gizmo will be added to */ + public gizmoLayer: UtilityLayerRenderer = UtilityLayerRenderer.DefaultUtilityLayer){ this._rootMesh = new BABYLON.Mesh("gizmoRootNode",gizmoLayer.utilityLayerScene); this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(()=>{ this._update(); diff --git a/src/Materials/babylon.effect.ts b/src/Materials/babylon.effect.ts index 5ff74326937..de9df4de64d 100644 --- a/src/Materials/babylon.effect.ts +++ b/src/Materials/babylon.effect.ts @@ -202,10 +202,21 @@ * Observable that will be called if an error occurs during shader compilation. */ public onErrorObservable = new Observable(); + + + /** @hidden */ + public _onBindObservable: Nullable>; + /** * Observable that will be called when effect is bound. */ - public onBindObservable = new Observable(); + public get onBindObservable(): Observable { + if (!this._onBindObservable) { + this._onBindObservable = new Observable(); + } + + return this._onBindObservable; + } /** @hidden */ diff --git a/src/Materials/babylon.material.ts b/src/Materials/babylon.material.ts index e4515f30bf1..4573cbb0c71 100644 --- a/src/Materials/babylon.material.ts +++ b/src/Materials/babylon.material.ts @@ -517,6 +517,7 @@ * An observer which watches for dispose events */ private _onDisposeObserver: Nullable>; + private _onUnBindObservable: Nullable>; /** * Called during a dispose event @@ -527,11 +528,19 @@ } this._onDisposeObserver = this.onDisposeObservable.add(callback); } + + private _onBindObservable: Nullable>; /** * An event triggered when the material is bound */ - public onBindObservable = new Observable(); + public get onBindObservable(): Observable { + if (!this._onBindObservable) { + this._onBindObservable = new Observable(); + } + + return this._onBindObservable; + } /** * An observer which watches for bind events @@ -551,7 +560,13 @@ /** * An event triggered when the material is unbound */ - public onUnBindObservable = new Observable(); + public get onUnBindObservable(): Observable { + if (!this._onUnBindObservable) { + this._onUnBindObservable = new Observable(); + } + + return this._onUnBindObservable; + } /** * Stores the value of the alpha mode @@ -1006,8 +1021,8 @@ this._scene._cachedVisibility = 1; } - if (mesh) { - this.onBindObservable.notifyObservers(mesh); + if (this._onBindObservable && mesh) { + this._onBindObservable.notifyObservers(mesh); } if (this.disableDepthWrite) { @@ -1021,8 +1036,9 @@ * Unbinds the material from the mesh */ public unbind(): void { - - this.onUnBindObservable.notifyObservers(this); + if (this._onUnBindObservable) { + this._onUnBindObservable.notifyObservers(this); + } if (this.disableDepthWrite) { var engine = this._scene.getEngine(); @@ -1314,8 +1330,13 @@ this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); - this.onBindObservable.clear(); - this.onUnBindObservable.clear(); + if (this._onBindObservable) { + this._onBindObservable.clear(); + } + + if (this._onUnBindObservable) { + this._onUnBindObservable.clear(); + } } /** diff --git a/src/Materials/babylon.standardMaterial.ts b/src/Materials/babylon.standardMaterial.ts index 6922e8ec975..de0073e2bf8 100644 --- a/src/Materials/babylon.standardMaterial.ts +++ b/src/Materials/babylon.standardMaterial.ts @@ -544,7 +544,7 @@ module BABYLON { */ public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances: boolean = false): boolean { if (subMesh.effect && this.isFrozen) { - if (this._wasPreviouslyReady && subMesh.effect) { + if (this._wasPreviouslyReady) { return true; } } diff --git a/src/Mesh/babylon.mesh.ts b/src/Mesh/babylon.mesh.ts index ed84624f2c2..5b8b6e02347 100644 --- a/src/Mesh/babylon.mesh.ts +++ b/src/Mesh/babylon.mesh.ts @@ -68,21 +68,42 @@ } // Events + private _onBeforeRenderObservable: Nullable>; + private _onAfterRenderObservable: Nullable>; + private _onBeforeDrawObservable: Nullable>; /** * An event triggered before rendering the mesh */ - public onBeforeRenderObservable = new Observable(); + public get onBeforeRenderObservable(): Observable { + if (!this._onBeforeRenderObservable) { + this._onBeforeRenderObservable = new Observable(); + } + + return this._onBeforeRenderObservable; + } /** * An event triggered after rendering the mesh */ - public onAfterRenderObservable = new Observable(); + public get onAfterRenderObservable(): Observable { + if (!this._onAfterRenderObservable) { + this._onAfterRenderObservable = new Observable(); + } + + return this._onAfterRenderObservable; + } /** * An event triggered before drawing the mesh */ - public onBeforeDrawObservable = new Observable(); + public get onBeforeDrawObservable(): Observable { + if (!this._onBeforeDrawObservable) { + this._onBeforeDrawObservable = new Observable(); + } + + return this._onBeforeDrawObservable; + } private _onBeforeDrawObserver: Nullable>; public set onBeforeDraw(callback: () => void) { @@ -184,7 +205,9 @@ // Deep copy Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", - "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], + "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen", + "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw" + ], ["_poseMatrix"]); // Source mesh @@ -1076,7 +1099,9 @@ return this; } - this.onBeforeDrawObservable.notifyObservers(this); + if (this._onBeforeDrawObservable) { + this._onBeforeDrawObservable.notifyObservers(this); + } let scene = this.getScene(); let engine = scene.getEngine(); @@ -1294,10 +1319,10 @@ */ public render(subMesh: SubMesh, enableAlphaMode: boolean): Mesh { - this._checkOcclusionQuery(); - if (this._isOccluded) { - return this; - } + // this._checkOcclusionQuery(); + // if (this._isOccluded) { + // return this; + // } var scene = this.getScene(); // Managing instances @@ -1312,7 +1337,9 @@ return this; } - this.onBeforeRenderObservable.notifyObservers(this); + if (this._onBeforeRenderObservable) { + this._onBeforeRenderObservable.notifyObservers(this); + } var engine = scene.getEngine(); var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined); @@ -1415,7 +1442,9 @@ engine.setAlphaMode(currentMode); } - this.onAfterRenderObservable.notifyObservers(this); + if (this._onAfterRenderObservable) { + this._onAfterRenderObservable.notifyObservers(this); + } return this; } @@ -1748,6 +1777,18 @@ this._geometry.releaseForMesh(this, true); } + if (this._onBeforeDrawObservable) { + this._onBeforeDrawObservable.clear(); + } + + if (this._onBeforeRenderObservable) { + this._onBeforeRenderObservable.clear(); + } + + if (this._onAfterRenderObservable) { + this._onAfterRenderObservable.clear(); + } + // Sources var meshes = this.getScene().meshes; meshes.forEach((abstractMesh: AbstractMesh) => { diff --git a/src/PostProcess/babylon.bloomMergePostProcess.ts b/src/PostProcess/babylon.bloomMergePostProcess.ts index 17e0961c576..f3a957c0072 100644 --- a/src/PostProcess/babylon.bloomMergePostProcess.ts +++ b/src/PostProcess/babylon.bloomMergePostProcess.ts @@ -17,7 +17,11 @@ module BABYLON { * @param textureType Type of textures used when performing the post process. (default: 0) * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ - constructor(name: string, originalFromInput:PostProcess, blurred:PostProcess, /** Weight of the bloom to be added to the original input. */ public weight:number, options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType: number = Engine.TEXTURETYPE_UNSIGNED_INT, blockCompilation = false) { + constructor(name: string, originalFromInput:PostProcess, blurred:PostProcess, + /** Weight of the bloom to be added to the original input. */ + public weight:number, + options: number | PostProcessOptions, + camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType: number = Engine.TEXTURETYPE_UNSIGNED_INT, blockCompilation = false) { super(name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true); this.onApplyObservable.add((effect: Effect) => { effect.setTextureFromPostProcess("textureSampler", originalFromInput); diff --git a/src/PostProcess/babylon.blurPostProcess.ts b/src/PostProcess/babylon.blurPostProcess.ts index d963e54c389..c841fd39912 100644 --- a/src/PostProcess/babylon.blurPostProcess.ts +++ b/src/PostProcess/babylon.blurPostProcess.ts @@ -64,7 +64,10 @@ * @param textureType Type of textures used when performing the post process. (default: 0) * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ - constructor(name: string, /** The direction in which to blur the image. */ public direction: Vector2, kernel: number, options: number | PostProcessOptions, camera: Nullable, samplingMode: number = Texture.BILINEAR_SAMPLINGMODE, engine?: Engine, reusable?: boolean, textureType: number = Engine.TEXTURETYPE_UNSIGNED_INT, defines = "", private blockCompilation = false) { + constructor(name: string, + /** The direction in which to blur the image. */ + public direction: Vector2, + kernel: number, options: number | PostProcessOptions, camera: Nullable, samplingMode: number = Texture.BILINEAR_SAMPLINGMODE, engine?: Engine, reusable?: boolean, textureType: number = Engine.TEXTURETYPE_UNSIGNED_INT, defines = "", private blockCompilation = false) { super(name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", {varyingCount: 0, depCount: 0}, true); this._staticDefines = defines; this.onApplyObservable.add((effect: Effect) => { diff --git a/src/PostProcess/babylon.convolutionPostProcess.ts b/src/PostProcess/babylon.convolutionPostProcess.ts index 93a46a8dc1a..bad53026f64 100644 --- a/src/PostProcess/babylon.convolutionPostProcess.ts +++ b/src/PostProcess/babylon.convolutionPostProcess.ts @@ -16,7 +16,10 @@ * @param reusable If the post process can be reused on the same frame. (default: false) * @param textureType Type of textures used when performing the post process. (default: 0) */ - constructor(name: string, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ public kernel: number[], options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType: number = Engine.TEXTURETYPE_UNSIGNED_INT) { + constructor(name: string, + /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ + public kernel: number[], + options: number | PostProcessOptions, camera: Nullable, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType: number = Engine.TEXTURETYPE_UNSIGNED_INT) { super(name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType); this.onApply = (effect: Effect) => { diff --git a/src/PostProcess/babylon.postProcess.ts b/src/PostProcess/babylon.postProcess.ts index 9380e2a099d..80f669f9958 100644 --- a/src/PostProcess/babylon.postProcess.ts +++ b/src/PostProcess/babylon.postProcess.ts @@ -244,7 +244,10 @@ * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx * @param blockCompilation If the shader should not be compiled imediatly. (default: false) */ - constructor(/** Name of the PostProcess. */public name: string, fragmentUrl: string, parameters: Nullable, samplers: Nullable, options: number | PostProcessOptions, camera: Nullable, + constructor( + /** Name of the PostProcess. */ + public name: string, + fragmentUrl: string, parameters: Nullable, samplers: Nullable, options: number | PostProcessOptions, camera: Nullable, samplingMode: number = Texture.NEAREST_SAMPLINGMODE, engine?: Engine, reusable?: boolean, defines: Nullable = null, textureType: number = Engine.TEXTURETYPE_UNSIGNED_INT, vertexUrl: string = "postprocess", indexParameters?: any, blockCompilation = false) { if (camera != null) { this._camera = camera; diff --git a/src/Rendering/babylon.utilityLayerRenderer.ts b/src/Rendering/babylon.utilityLayerRenderer.ts index 2be5bd9c167..4172da1d743 100644 --- a/src/Rendering/babylon.utilityLayerRenderer.ts +++ b/src/Rendering/babylon.utilityLayerRenderer.ts @@ -67,7 +67,9 @@ module BABYLON { * Instantiates a UtilityLayerRenderer * @param originalScene the original scene that will be rendered on top of */ - constructor(/** the original scene that will be rendered on top of */ public originalScene:Scene){ + constructor( + /** the original scene that will be rendered on top of */ + public originalScene: Scene){ // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine()); this.utilityLayerScene._allowPostProcessClear = false;